8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vimで拡張子のないファイルにファイルタイプ設定を反映する

Last updated at Posted at 2015-01-17
  • 環境はMac。

動機

  • Vimで拡張子なしのシェルスクリプトファイル(要はシェルコマンド)を編集することがよくある。
  • 毎回setf=shするのめどい。

コード

  • ~/.vim/ftdetect/sh.vim に書き込む。
    • ~/.vim/ftdetect に (filetype).vim を作ることで、そのfiletypeの定義パターンを拡張できる。
~/.vim/ftdetect/sh.vim
" Vim起動時に、「バッファ名が空」かつ「の場合はfiletype=sh
autocmd VimEnter * nested if @% == '' && s:GetBufByte() == 0 | set filetype=sh | endif
function! s:GetBufByte()
    let byte = line2byte(line('$') + 1)
    if byte == -1
        return 0
    else
        return byte - 1
    endif
endfunction

" バッファを開いたとき、「バッファ名にドットを含まない」かつ「Shebangがない」場合はfiletype=sh
autocmd BufRead,BufNewFile * nested if @% !~ '\.' && getline(1) !~ '^#!.*' | set filetype=sh | endif
  • **「拡張子を持たず」「ドットファイルでない」**ファイルは、「バッファ名にドットを含まない 」=@% !~ '\.'として簡潔に記述できる。
  • シェルコマンドを他言語でも書けるように、Shebangがある場合に対応
  • これで、ファイルタイプに応じた機能(例えばシンタックスハイライトやneosnippet.vim)を利用できる。

参考

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?