问题
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