3

I'd like to prevent Vim from saving a file if it contains the following text

:style=>

This could potentially be in multiple places in the file.

As a bonus if it could come up with an error message like "stop putting styles inline!" that would be great too ;)

Thanks!

PS : I would like this prevent action to be triggered upon attempting to write the file :w

robzolkos
  • 2,196
  • 3
  • 30
  • 47

2 Answers2

7

One way

to do this is to "bind" the save (:w) command to a function that checks for your pattern:

autocmd BufWriteCmd * call CheckWrite()

where your Check() function could look like this:

function! CheckWrite()
  let contents=getline(1,"$")
  if match(contents,":style=>") >= 0
    echohl WarningMsg | echo "stop putting styles inline!" | echohl None
  else
    call writefile(contents, bufname("%"))
    set nomodified
  endif
endfunction

Note that in this case you have to provide a "save-file" mechanism yourself (probably a not so good idea, but works well).


A safer way

would be to set readonly when your pattern appears:

autocmd InsertLeave * call CheckRO()

and issue the warning when you try to save:

autocmd BufWritePre * call Warnme()

where CheckRO() and Warnme() would be something like:

function! CheckRO()
  if match(getline(1,"$"),":style=>") >= 0
    set ro
  else
    set noro
  endif
endfunction
function! Warnme()
  if match(getline(1,"$"),":style=>") >= 0
    echohl WarningMsg | echo "stop putting styles inline!" | echohl None
  endif
endfunction

Highlight

It is also probably a good idea to highlight your pattern with a hi+syntax match command:

syntax match STOPPER /:style=>/
hi STOPPER ctermbg=red

Finally, have a look at this script.

Community
  • 1
  • 1
Eelvex
  • 8,975
  • 26
  • 42
0

It might be more typical to enforce restrictions like this through your VCS's commit hook. See, for example, http://git-scm.com/docs/githooks.

This would leave the capabilities of your editor intact while forbidding committing offending code.

Ryan
  • 116
  • 2
  • true. Thats one way of tackling it. I just wanted something a little more immediate. Thought there may be something simple I can setup within VIM to help. – robzolkos Feb 26 '11 at 14:38