0

I have these long lines, using Vim built in function to auto-indent programming files on saving file.

How can I make this more compact ?

Actually, I just want to exclude .txt files, because I don't want autoformat them.

autocmd BufRead,BufWritePre *.py normal mzgg=G`z
autocmd BufRead,BufWritePre *.java normal mzgg=G`z
autocmd BufRead,BufWritePre *.c normal mzgg=G`z
autocmd BufRead,BufWritePre *.cpp normal mzgg=G`z
autocmd BufRead,BufWritePre *.cs normal mzgg=G`z
autocmd BufRead,BufWritePre *.php normal mzgg=G`z
autocmd BufRead,BufWritePre *.rb normal mzgg=G`z
autocmd BufRead,BufWritePre *.go normal mzgg=G`z
autocmd BufRead,BufWritePre *.swift normal mzgg=G`z
autocmd BufRead,BufWritePre *.m normal mzgg=G`z
autocmd BufRead,BufWritePre *.html normal mzgg=G`z
autocmd BufRead,BufWritePre *.css normal mzgg=G`z
autocmd BufRead,BufWritePre *.sql normal mzgg=G`z
autocmd BufRead,BufWritePre *.js normal mzgg=G`z
autocmd BufRead,BufWritePre *.cc normal mzgg=G`z
autocmd BufRead,BufWritePre *.htm normal mzgg=G`z
autocmd BufRead,BufWritePre *.h normal mzgg=G`z
autocmd BufRead,BufWritePre *.scss normal mzgg=G`z
autocmd BufRead,BufWritePre *.json normal mzgg=G`z
autocmd BufRead,BufWritePre *.xml normal mzgg=G`z
autocmd BufRead,BufWritePre *.yaml normal mzgg=G`z
autocmd BufRead,BufWritePre *.yml normal mzgg=G`z
autocmd BufRead,BufWritePre *.sh normal mzgg=G`z
autocmd BufRead,BufWritePre *.md normal mzgg=G`z
autocmd BufRead,BufWritePre *.tex normal mzgg=G`z
autocmd BufRead,BufWritePre *.csv normal mzgg=G`z

This doesn't work:

autocmd BufRead,BufWritePre *.py,*.java,*.c,*.cpp,*.cs,*.php,*.rb,*.go,*.swift,*.m,*.html,*.css,*.sql,*.js normal mzgg=G`z
1
  • It's odd that the comma-separated version didn't work for you. :help autocmd-patterns suggests a comma-separated list of patterns should work just fine. Also, consider using :normal! to prevent any mappings on m or g or = etc. from affecting the way your command runs.
    – filbranden
    Feb 28, 2023 at 21:03

1 Answer 1

1

You could do with a loop:

let s:extensions = ['py', 'java', 'c']
for ext in s:extensions
  execute 'autocmd BufRead,BufWritePre *.' .. ext .. ' normal mzgg=G`z'
endfor
2
  • yea, that seems to work. does this execute only once if file is appropriate type. like, if it's java, then it will run only one line (for java autoindent) and not try to run others ? Feb 26, 2023 at 18:14
  • Thanks for the feedback :-) It is completely equivalent to your previous code. It simply setup all the call backs. As before the specific call back is called only once per event (e.g. Read Buffer of Java type) Feb 26, 2023 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.