How to add space between parenthesis and quotes on save

纵饮孤独 提交于 2020-01-06 03:07:30

问题


I would like to add have VIM automatically add space between parenthesis and "/' to match jquery style guidelines: http://contribute.jquery.org/style-guide/js/. This could be on save or by triggering a custom command.

Ideally it would also add spaces before variable names but not functions or objects literal.

What would be the best way to go about this?


回答1:


To insert spaces on saves, use an autocommand:

au BufWrite *.js silent! %s/\m(\@<=["']/ \0/g | silent! %s/\m["'])\@=/\0 /g

au BufWrite *.js will trigger whenever a file with a js extension (eg jquery.js) is saved, while the remainder of the command will insert spaces between all occurrences of a single/double quote preceded/followed by a space (inside comments and strings, for instance, too). To perform the insertion only in front of variable names, you'd need to parse the javascript file and identify its variables, only after which you'd know the places you want to modify (otherwise, to Vim, all of your code is just text).

Alternatively, you can bind everything to a command:

com InsertSpaces silent! %s/\m(\@<=["']/ \0/g | silent! %s/\m["'])\@=/\0 /g

at which point :InsertSpace will perform the substitution.

The best solution, though, is what @romainl suggested: train yourself to passively follow the style guide. Automating space insertion is an ugly hack.



来源:https://stackoverflow.com/questions/24737490/how-to-add-space-between-parenthesis-and-quotes-on-save

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!