Search code examples
latexvimsageautocmd

Vim autocmd based on file contents


I'm trying to set up Vim to detect when a .tex file contains the command '\usepackage{sagemath}', and run a command accordingly. I've gotten to

:au BufReadPost,BufWritePost *.tex TTarget sagepdf

but that will fire for all .tex files, which isn't what I want.


Solution

  • Theres an example in my filetype.vim on how to destinguish html types. You can easily modify to suit your logic. Note the getline(n) =~ lines

    " HTML (.shtml and .stm for server side)
    au BufNewFile,BufRead *.html,*.htm,*.shtml,*.stm  call s:FThtml()
    
    " Distinguish between HTML, XHTML and Django
    fun! s:FThtml()
      let n = 1
      while n < 10 && n < line("$")
        if getline(n) =~ '\<DTD\s\+XHTML\s'
          setf xhtml
          return
        endif
        if getline(n) =~ '{%\s*\(extends\|block\)\>'
          setf html.django_template
    "      setf htmldjango
          return
        endif
        let n = n + 1
      endwhile
      setf html
    endfun