8

Rumor has reached me that it is possible to place vim commands in the first five, or in the last five lines of a a file. But, I could not find this in Google. Any leads would be appreciated.

I wonder if it would be possible to employ this feature to define file specific additions to the word list.

Edit Thanks! The modeline it is! Can it be used for spell checking in the manner suggested?

8
+50

Modelines may seem like a way to do this, but unfortunately they won't work. Modelines only support setting options (shiftwidth, colorcolumn, that sort of thing). You can use a modeline like vim: spell to enable spellchecking for a document. However, spellgood! is an Ex command, not an option. Further, you specifically can't set some options (including spellfile, see :help spellfile) from modelines for security reasons.

You could craft a bunch of file-specific autocommands in your vimrc, but that would become really hard to maintain over time, tedious if you ever happen to have two files with the same name in different locations, and wouldn't travel "with the file."

Instead, the best solution is probably to build your own modeline-like feature for adding words by parsing some defined block of text in the document. For example, you can look for lines starting with "spellgood:" and automatically add the space-delimited set of words after to the internal word list:

function! AddLocalSpelling ()
  " Save the cursor position.
  let cursor_position = getcurpos()

  let location = searchpos("\"spellgood:", "c")
  while location != [0, 0]
    let words = split(getline(location[0]))
    " The first 'word' will be the sentinel token itself (unless)
    " we found the token in an embedded string or comment...
    if words[0] == "\"spellgood:"
      call remove(words, 0)
      for word in words
        execute "silent spellgood! " . word
      endfor
    endif
    let location = searchpos("\"spellgood:", "W")
  endwhile

  " Restore cursor position.
  call setpos(".", cursor_position)
endfunction

Then you can set up an autocommand for, say BufReadPost * call AddLocalSpelling() in your .vimrc. In practice you'd probably want to make the above function more robust in the face of errors, and possibly use comments to see what a valid comment token is (I picked " because I tested this in a VimL buffer). This SuperUser answer linked by JJoao in the comments provides a similar-but-alternative implementation that lets you use blocks of words instead of just a single line at a time.

This method will require others use the same function or at least agree on the same parse rules, so it's not perfect. But you could take it and promote the functionality to a plugin if you so desired, enabling easier access for other users.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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