5

Lets say I have two group of settings one for writing and one for programming. How do I modify my .vimrc so that the first set load while working on files with the .md extension and the latter with html/js/css ones?

2 Answers 2

8

Though :autocmds based on FileType are a quick and easy way for your ~/.vimrc (as suggested by @andrewdotn), Vim has a proper abstraction for that: filetype plugins.

Put settings and buffer-local mappings into ~/.vim/after/ftplugin/{filetype}.vim. (This requires that you have :filetype plugin on; use of the after directory allows you to override any default filetype settings done by $VIMRUNTIME/ftplugin/{filetype}.vim.)

Sign up to request clarification or add additional context in comments.

Comments

5

Use autocommands. For example, here are the settings from my ~/.vimrc:

autocmd BufRead,BufNewFile *.js,*.html
      \ setlocal indentkeys=!^F,o
autocmd BufRead,BufNewFile *.md
      \ setlocal filetype=markdown | syntax clear

setlocal is used instead of set so that only the buffer matching the filename pattern is affected. Otherwise, the change to an option like shiftwidth will affect all buffers every time you load a *.foo file.

The \ is the line-continuation character, which lets you split a single command over multiple lines to increase readability.

The | character is the bar which is used to chain together multiple commands in one line.

See autocmd.txt in the vim documentation for more.

6 Comments

@andewdotn Thanks a lot! One question: do the settings need to be set as setlocal? can they just be set as set? Sorry I'm not very familiar with vimscript. Is it necessary to wrap those settings inside conditional blocks or something?
I usually see settings as this: set expandtab with set.
If you don’t use setlocal then the setting will apply to all buffers which will be really annoying if you have multiple files open. See :he :setlocal. You don’t need to wrap that in a block or anything; the corresponding settings will be applied only if the filename matches the pattern.
Thanks. What I mean right now in your example I don't see how the setlocal is "connected" with autocmd BufRead,BufNewFile. It seems like the setlocals are "nested" inside? Could you expand the example to include one ore more settings?
Oh, I see—the \ at the beginning of the line is a line-continuation character. Technically that’s the same as writing autocmd BufRead,BufNewFile *.js,*.html setlocal indentkeys=!^F,o all on one line, it’s just more readable and more customary to do it with the \ at the start of the next line. Note that vimscript syntax is actually defined in eval.html.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.