开发者

Vim - prevent saving/writing a file if it contains certain string

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 w开发者_Go百科ith 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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜