Vim檔案型別判斷

叕叒双又發表於2024-03-21

  vim中判斷檔案的型別也是非常重要的,開啟vim後,使用命令::e $VIMRUNTIME/filetype.vim

例如如下片段:

1047 " Markdown
1048 au BufNewFile,BufRead *.markdown,*.mdown,*.mkd,*.mkdn,*.mdwn,*.md  setf markdown
1049 
1050 " Mason
1051 au BufNewFile,BufRead *.mason,*.mhtml,*.comp    setf mason
1052 
1053 " Mathematica, Matlab, Murphi, Objective C or Octave
1054 au BufNewFile,BufRead *.m           call dist#ft#FTm()                                                                                            
1055 

以1053行為例,其中有多種檔案的字尾名都是一樣的,就無法直接透過字尾名直接判斷檔案型別;

vim會繼續執行程式碼,呼叫 ft.vim中的檔案,使用命令 :e $VIMRUNTIME/autoload/dist/ft.vim 具體在:/usr/share/vim/vim82/autoload/dist/ft.vim裡,下面是判斷m字尾名的的具體屬性函式

283 func dist#ft#FTm()                                                                                                                                                                                                                                                                                         
284   if exists("g:filetype_m")
285     exe "setf " . g:filetype_m
286     return
287   endif
288 
289   " excluding end(for|function|if|switch|while) common to Murphi
290   let octave_block_terminators = '\<end\%(_try_catch\|classdef\|enumeration\|events\|methods\|parfor\|properties\)\>'
291 
292   let objc_preprocessor = '^\s*#\s*\%(import\|include\|define\|if\|ifn\=def\|undef\|line\|error\|pragma\)\>'
293 
294   let n = 1
295   let saw_comment = 0 " Whether we've seen a multiline comment leader.
296   while n < 100
297     let line = getline(n)
298     if line =~ '^\s*/\*'
299       " /* ... */ is a comment in Objective C and Murphi, so we can't conclude
300       " it's either of them yet, but track this as a hint in case we don't see
301       " anything more definitive.
302       let saw_comment = 1
303     endif
304     if line =~ '^\s*//' || line =~ '^\s*@import\>' || line =~ objc_preprocessor
305       setf objc
306       return
307     endif
308     if line =~ '^\s*\%(#\|%!\)' || line =~ '^\s*unwind_protect\>' ||
309       \ line =~ '\%(^\|;\)\s*' .. octave_block_terminators
310       setf octave
311       return
312     endif
313     " TODO: could be Matlab or Octave
314     if line =~ '^\s*%'
315       setf matlab
316       return
317     endif
318     if line =~ '^\s*(\*'
319       setf mma
320       return
321     endif
322     if line =~ '^\c\s*\(\(type\|var\)\>\|--\)'
323       setf murphi
324       return
325     endif
326     let n = n + 1
327   endwhile
328 
329   if saw_comment
330     " We didn't see anything definitive, but this looks like either Objective C
331     " or Murphi based on the comment leader. Assume the former as it is more
332     " common.
333     setf objc
334   else
335     " Default is Matlab
336     setf matlab
337   endif
338 endfunc

直至確認成功,還是不錯的。

相關文章