18
16

More than 3 years have passed since last update.

Vim: 拡張子ごとにインデントを変更する方法 ~ 初心者 ~

Last updated at Posted at 2020-03-26

Vim: 拡張子ごとにインデントを変更する方法

だいぶvimも使い慣れてきたのですが,
インデントが全て同じになってしまっていて
不便だったので拡張子ごとに設定してみたというお話です。

ファイルタイプの確認

今回は拡張子 .jsを対象に紹介します。
1. hoge.jsというファイルをvimで開きます。
2. exモード(:wq の時に使う ':' で入るモード)で以下を入力

:echo &filetype

1__Thanks_for_flying_Vim__tmux_.png

echoで出力されるのが, filetypeになります。
hoge.png

今回はこのファイルタイプを使っていきます。

導入

それぞれの設定は以下のようになります。
if has('autocmd') を使っているのは,
古いバージョンでautocmdが存在しなかった時のために入れてあります。

.vimrc

"""""""""""""""""""""""""
"      インデント
""""""""""""""""""""""""
set autoindent          "改行時に前の行のインデントを計測
set smartindent         "改行時に入力された行の末尾に合わせて次の行のインデントを増減する 
set cindent             "Cプログラムファイルの自動インデントを始める
set smarttab            "新しい行を作った時に高度な自動インデントを行う
set expandtab           "タブ入力を複数の空白に置き換える 

set tabstop=2           "タブを含むファイルを開いた際, タブを何文字の空白に変換するか
set shiftwidth=2        "自動インデントで入る空白数
set softtabstop=0       "キーボードから入るタブの数

if has("autocmd")
  "ファイルタイプの検索を有効にする
  filetype plugin on
  "ファイルタイプに合わせたインデントを利用
  filetype indent on
  "sw=shiftwidth, sts=softtabstop, ts=tabstop, et=expandtabの略
  autocmd FileType c           setlocal sw=4 sts=4 ts=4 et
  autocmd FileType html        setlocal sw=4 sts=4 ts=4 et
  autocmd FileType ruby        setlocal sw=2 sts=2 ts=2 et
  autocmd FileType js          setlocal sw=4 sts=4 ts=4 et
  autocmd FileType zsh         setlocal sw=4 sts=4 ts=4 et
  autocmd FileType python      setlocal sw=4 sts=4 ts=4 et
  autocmd FileType scala       setlocal sw=4 sts=4 ts=4 et
  autocmd FileType json        setlocal sw=4 sts=4 ts=4 et
  autocmd FileType html        setlocal sw=4 sts=4 ts=4 et
  autocmd FileType css         setlocal sw=4 sts=4 ts=4 et
  autocmd FileType scss        setlocal sw=4 sts=4 ts=4 et
  autocmd FileType sass        setlocal sw=4 sts=4 ts=4 et
  autocmd FileType javascript  setlocal sw=4 sts=4 ts=4 et
endif

上記に載せてる拡張子以外にもファイルタイプさえわかれば,
設定できますので他にも設定していこうと思います。

参考サイト

18
16
1

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
18
16