Vim 启动时未设置 `tex` 文件类型

Vim not setting `tex` filetype on startup

我注意到如果我用 Vim 打开一个不存在的 HTML 文件,文件类型会自动设置为 html:

$ vim foobar.html
:set filetype # --> filetype=html

另一方面,TeX 不会发生同样的情况。如果我创建一个不存在的文件,文件类型是 plaintext,我必须保存文件并重新打开它以正确设置它:

$ vim blabla.tex
:set filetype # --> filetype=plaintext

我也试过 Python、C、VimL、Javascript 文件,文件类型总是立即设置。我不知道为什么这不会发生在 TeX 文件上。

我认为唯一可能干扰的是 vim-latex。那可能吗?如果是这样,我该如何解决这个问题?

如果可能有帮助,here 是我不长的 .vimrc 文件。

有一种方法可以使您手动执行的过程自动化。

autocmd BufRead,BufNewFile *.tex set filetype=tex 添加到您的 .vimrc 文件将为每个 tex 文件设置 tex 文件类型,一旦您在 vim.

中打开它们

Vim 使用巨大的启发式来确定 plaintex 与 tex 的其他变体。

如果你查看 $VIMRUNTIME/filetype.vim,你会发现以下函数

" Choose context, plaintex, or tex (LaTeX) based on these rules:
" 1. Check the first line of the file for "%&<format>".
" 2. Check the first 1000 non-comment lines for LaTeX or ConTeXt keywords.
" 3. Default to "latex" or to g:tex_flavor, can be set in user's vimrc.
func! s:FTtex()
  let firstline = getline(1)
  if firstline =~ '^%&\s*\a\+'
    let format = tolower(matchstr(firstline, '\a\+'))
    let format = substitute(format, 'pdf', '', '')
    if format == 'tex'
      let format = 'plain'
    endif
  else
    " Default value, may be changed later:
    let format = exists("g:tex_flavor") ? g:tex_flavor : 'plain'
    " Save position, go to the top of the file, find first non-comment line.
    let save_cursor = getpos('.')
    call cursor(1,1)
    let firstNC = search('^\s*[^[:space:]%]', 'c', 1000)
    if firstNC " Check the next thousand lines for a LaTeX or ConTeXt keyword.
      let lpat = 'documentclass\>\|usepackage\>\|begin{\|newcommand\>\|renewcommand\>'
      let cpat = 'start\a\+\|setup\a\+\|usemodule\|enablemode\|enableregime\|setvariables\|useencoding\|usesymbols\|stelle\a\+\|verwende\a\+\|stel\a\+\|gebruik\a\+\|usa\a\+\|imposta\a\+\|regle\a\+\|utilisemodule\>'
      let kwline = search('^\s*\\%(' . lpat . '\)\|^\s*\\(' . cpat . '\)',
                              \ 'cnp', firstNC + 1000)
      if kwline == 1    " lpat matched
        let format = 'latex'
      elseif kwline == 2    " cpat matched
        let format = 'context'
      endif     " If neither matched, keep default set above.
      " let lline = search('^\s*\\%(' . lpat . '\)', 'cn', firstNC + 1000)
      " let cline = search('^\s*\\%(' . cpat . '\)', 'cn', firstNC + 1000)
      " if cline > 0
      "   let format = 'context'
      " endif
      " if lline > 0 && (cline == 0 || cline > lline)
      "   let format = 'tex'
      " endif
    endif " firstNC
    call setpos('.', save_cursor)
  endif " firstline =~ '^%&\s*\a\+'

  " Translation from formats to file types.  TODO:  add AMSTeX, RevTex, others?
  if format == 'plain'
    setf plaintex
  elseif format == 'context'
    setf context
  else " probably LaTeX
    setf tex
  endif
  return
endfunc

此函数确定使用哪种风格的 tex。如果您查看它,您会发现默认值取自 g:tex_flavor(如果存在,则默认为普通值)。如果将此变量设置为 tex(在 vimrc 中),vim 将默认为 tex 文件类型。

let g:tex_flavor = 'tex'