Vim Tips Wiki
Advertisement
Tip 331 Printable Monobook Previous Next

created September 22, 2002 · complexity basic · version 6.0


Options set in your vimrc will apply to all files that you edit. You can also set:

  • Different options for all files of a certain type (for example, all *.py files). See filetypes and an example.
  • Different options for a particular file using modelines (this tip).

Examples

For example, in a particular file you may want each tab character that you type to be expanded to spaces. To achieve this, put the following modeline near the top or the bottom of that file:

# vim: set expandtab:

In a Python file, the '#' starts a comment so the modeline is not interpreted by Python.

The following examples show some alternatives that could be in a C file:

// vim: noai:ts=4:sw=4
   -or-
/* vim: noai:ts=4:sw=4
*/
   -or-
/* vim: set noai ts=4 sw=4: */

With "set", the modeline ends at the first colon. Without "set", no text can follow the options, so for example, the following is invalid:

Error E518: Unknown option: */
/* vim: noai:ts=4:sw=4 */

Adding a modeline

With the following in your vimrc and the default leader key, you could type \ml to add a modeline based on your current settings:

" Append modeline after last line in buffer.
function! AppendModeline()
  let save_cursor = getpos('.')
  let append = ' vim: set ts='.&tabstop.' sw='.&shiftwidth.' tw='.&textwidth.': '
  $put =substitute(&commentstring,\"%s\",append,\"\")
  call setpos('.', save_cursor)
endfunction
nnoremap <silent> <Leader>ml :call AppendModeline()<CR>

In a C file, you would get a modeline like this:

/* vim: set ts=8 sw=4 tw=0: */

Alternatively, you could use a simple menu entry like this:

amenu Edit.Insert\ &modeline <C-\><C-N>ggOvim:ff=unix ts=4 ss=4<CR>vim60:fdm=marker<Esc>

Choosing the menu item would insert two modelines like this:

vim:ff=unix ts=4 ss=4
vim60:fdm=marker

Security

 TO DO 

  • Need note on security implications of modelines and reference to alternatives.
  • Text other than "vim:" can be recognised as a modeline.
  • Google "vim modeline vulnerability" (without quotes) for information.

References

Comments

This mechanism can be extended to 'let' – see script#83.


see script#1876


in "set:" modelines, colons can be used if they are escaped. Example (untested)

vim: set fdm=expr fde=getline('.')=~'{'?'>1'\:'1' :
Advertisement