Hot answers tagged

36

As far as I know there is no setting or some such to do this. But not all is lost, we can of course use the BufWritePre autocommand. This is executed before the buffer is written to the disk. So we can create the directory there if it doesn't exist yet. For example: augroup Mkdir autocmd! autocmd BufWritePre * \ if !isdirectory(expand("<afile>...


27

The main reason to use augroups is to allow greater control over ranges of autocommands, e.g. to delete a bunch of autocommands in one go. A common pattern is to use the au! as the first part of a group. This removes all existing autocommands in the group, and allows one to start afresh. If you did not use a group, then au! would remove all/many autocommands ...


20

Silent should go before !./make.sh, not before au. Putting silent before au just means it will register the autocommand silently. It should look like this instead: au BufWritePost * silent! !./make.sh One issue with running an external command like this with the :silent command is that the screen does not redraw, leaving you with a blank screen. However,...


18

Autocommand groups give you the opportunity to organize your autocommands, which is a quite useful feature in and of itself. Say you are writing a plugin. Grouping your plugin's autocommands under your own namespace makes sense, if only because it lets you enable/disable your autocommands at will. Your vimrc is not fundamentally different from a plugin/foo....


15

Building on your answer: you don't need a variable to keep state of the augroup, you can use exists() for that, provided that you know at least one of the autocmds that are part of the group: function! ToggleTestAutoGroup() if !exists('#TestAutoGroup#BufEnter') augroup TestAutoGroup autocmd! autocmd BufEnter * echom "...


14

An autocommand command is executed when one event occurs. You want a command to be executed after a sequence of events has occurred. One way to do that is like this: autocmd FileType c,cpp,python \ autocmd BufWritePre <buffer> call StripTrailingWhiteSpaces() The <buffer> pattern causes the autocommand to be be triggered when the current ...


14

The best way to set an option for a particular filetype is to use autocommands. Here you could add something like that in your .vimrc: autocmd FileType markdown setlocal spell This line will trigger the command setlocal spell when the filetype of a buffer is set as markdown. you can also use the autocommand based on the extension of the file you edit with ...


14

You can use the following mapping: cnoremap <expr> <CR> getcmdtype() == '/' ? '<CR>zz' : '<CR>' Which can be explained like this: cnoremap Create a mapping in the command line mode <expr> The mapping will evaluate an expression (allowing to use conditions) <CR> The key to remap (Enter) ...


13

You should be able to add something like this to your vimrc: autocmd BufReadPost *.odt :%!odt2txt % That will send the entire buffer through the odt2txt program after it's read in by vim, but only if the file name ends with .odt. There's also the textutil.vim plugin that says it can do what you're talking about for a few of those file types (but I haven't ...


13

Aside from the other answers, I find that the most immediate practical benefit is that it makes it easy to reload vimscript files. For example stick this in your vimrc: autocmd BufCreate * echom "New buffer!" Quit, restart, make a new buffer. you see New buffer!, which you can verify with :messages. Now reload your vimrc: :source $MYVIMRC, and again make ...


12

You need to add this to your vimrc: autocmd BufNewFile * startinsert The autocommand creates a command which is executed on a specific event. Here the event is BufNewFile the doc descibes it has: When starting to edit a file that doesn't exist. Can be used to read in a skeleton file. The * is here to execute the ...


11

To complete the @sundar answer : You can log the order of the events simply with a logging function : augroup EventLoggin autocmd! autocmd BufNewFile * call s:Log('BufNewFile') autocmd BufReadPre * call s:Log('BufReadPre') ... autocmd User * call s:Log('User') augroup END function! s:Log(eventName) abort silent execute '!echo '.a:eventName.' &...


11

Is this usage of <buffer> correct? I think it is correct, but you just need to wrap it inside an augroup, and clear the latter, to make sure that the autocmd won't be duplicated every time you execute a command which reloads the same buffer. As you explained, the special pattern <buffer> allows you to rely on the built-in filetype detection ...


10

You can use autocommands to run things automatically when certain events occur. In your case, you could do this: autocmd BufWritePost *.less !less <afile> This autocommand runs every time a buffer with a name that ends in .less is written. The command that is being run is a bash command, and <afile> is the name of the file that is being ...


10

This comment by derobert led me to the solution: autocmd Filetype xml if getfsize(@%) > 1000000 | setlocal syntax=OFF | endif This seems to reliably disable syntax highlighting in one buffer only. The autocmd BufReadPre was a bit of a red herring. syntax off works in the BufReadPre context but not in the Filetype context (and of course disables syntax ...


10

I tried googling for this with different sets of keywords, and struck gold on one such attempt with this result: http://www.ibm.com/developerworks/library/l-vim-script-5/ Specifically, this part is relevant to the current question: For example, if you start Vim, edit a file named demo.txt, swap into Insert mode, type in some text, save the file, and ...


10

When you execute an external command with :!, Vim doesn't know what the external command might have written to the terminal, so it waits for you to confirm that you are ready to continue. To avoid that, you can use the system() function like this: autocmd BufWritePost *.cpp call system("ctags -R") autocmd BufWritePost *.h call system("ctags -R") You ...


9

Instead of using the BufWritePre autocmd, you can use the BufWriteCmd autocmd, from :help BufWriteCmd: Should do the writing of the file and reset 'modified' if successful, unless '+' is in 'cpo' and writing to another file cpo-+. We can just call :write from the autocmd. This will take care of setting modified. So the logic would then be modified to ...


9

This works for all 3 of your cases for me: function InsertIfEmpty() if @% == "" " No filename for current buffer startinsert elseif filereadable(@%) == 0 " File doesn't exist yet startinsert elseif line('$') == 1 && col('$') == 1 " File is empty startinsert endif endfunction au ...


8

This is rather simple: :autocmd CursorHold * \ let save_modified = &modified | \ silent! execute 'write' fnameescape(tempname()) | \ let &modified = save_modified However, this has the side effect of naming a :new buffer on the first triggering. (It doesn't affect existing files; this is the difference between :write and :saveas.) You can ...


8

(I actually figured it out by myself but as I didn't find an answer on this site I thought that could be usefull to create a self-answered question) To do so it is possible to create the following function and put it in the .vimrc: function! ToggleTestAutoGroup() if !exists('g:TestAutoGroupMarker') let g:TestAutoGroupMarker = 1 endif " ...


8

<amatch> is exactly what is matched against the autocmd pattern. For autocmds that match filenames, symlinks are resolved, the result is canonicalized, and the full path is returned. <afile> is the canonical full path as above, but the result is also shortened, which is essentially the same as fnamemodify(file, ':.') (the exact details are more ...


7

Asked: Setting the filetype The autocommands in the question are a good start, and with 2 extra pieces of knowledge we can finish it: You can define autocommands everywhere. autocmd and augroup are "just" regular Vim commands, not special syntax or keywords. So defining an autocmd from within an autocmd is perfectly fine. You can define autocommands to be ...


7

The answer to your direct question is just as @EvergreenTree posted. However I feel like you are missing some of Vim builtin tool for building/compiling/linting projects. Most notably :make and the quickfix list. What does using :make get us? Using :make allows for you to collect your errors up into a list known as the quickfix list. Using the quickfix you ...


7

I find the easy way is to use a global variable. Example: augroup TestAutoGroup autocmd! autocmd BufEnter * | \ if get(g:, 'toggle_autocmd', 1) | \ echom "BufEnter " . bufnr("%") | \ endif augroup END nnoremap <f4> :<c-u>let g:toggle_autocmd = !get(g:, 'toggle_autocmd', 1)<cr> For more help see: :h g: :h ...


7

What I was doing wrong is adding <cr> at the end of the line. That's work pretty well: autocmd VimLeave * :!touch /home/odiszapc/vimleave


7

I looked into the source and I think I found the problem. If you look in the help (:h :au) you will see this: :au[tocmd] [group] {event} {pat} [nested] {cmd} Add {cmd} to the list of commands that Vim will execute automatically on {event} for a file matching {pat} autocmd-patterns. Vim always adds the {cmd} after existing ...


7

I think the problem comes from the second bang in your command which has a special meaning for vim. It is automatically replaced with the previous external command. Any '!' in {cmd} is replaced with the previous external command (see also 'cpoptions'). But not when there is a backslash before the '!', then that ...


7

Since this should only work for existing files, you'll want to use BufRead instead of BufWinEnter. vim-template won't trigger BufRead. If you really need BufWinEnter to be used to process modelines before calling your function, you can use BufRead to set a buffer variable: autocmd BufRead * let b:not_new = 1 And check if the variable exists before moving ...


Only top voted, non community-wiki answers of a minimum length are eligible