CLOVER🍀

That was when it all began.

Emacsで、特定のディレクトリの配下だけ設定を変更する

Emacsを使っていて、特定のディレクトリの配下だけ設定を変えられないかな、と思う時がありまして。

たとえば、ふだんはインデントにスペースを使っているけれども、特定のディレクトリ内はインデントにタブを使いたい、
といった時ですね。

調べてみると、こちらの仕組みを使えば実現できそうです。

Per-Directory Local Variables

これは、.dir-locals.elというファイルを作成して設定をすることで、ディレクトリのローカルな値で全体の設定を上書きできる
ものになります。

Sometimes, you may wish to define the same set of local variables to all the files in a certain directory and its subdirectories, such as the directory tree of a large software project. This can be accomplished with directory-local variables. File local variables override directory local variables, so if some of the files in a directory need specialized settings, you can specify the settings for the majority of the directory’s files in directory variables, and then define file local variables in a few files which need the general settings overridden.

配置したディレクトリだけでなく、サブディレクトリに対しても有効になります(該当のディレクトリのみにすることも
できるようです)。

たとえば、自分はインデントをスペースに設定してJavaScript用のモードではインデント幅を2にしていますが

.emacs.d/init.el

;; TABの表示幅設定(初期値8から4に変更)
(setq default-tab-width 4)
(setq tab-stop-list '(4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72
                        76 80 84 88 92 96 100 104 108 112 116 120 124 128
                        132 136 140 144
                        148 152 156 160 164 168 172 176 180 184 188 192
                        196 200 204 208 212 216))

;; TABでなくスペースを使う
(setq-default indent-tabs-mode nil)

;; javascript                                                                                                                                                                
(add-hook 'js-mode-hook '(lambda () (setq js-indent-level 2)))                                                                                                               
(use-package lsp-mode                                                                                                                                                        
  :ensure t                                                                                                                                                                  
  :commands (lsp lsp-deferred)                                                                                                                                               
  :hook (js-mode . lsp-deferred))

以下のように.dir-locals.elファイルを作成して配置することで、このファイルがあるディレクトリ以下はJavaScript用のモードで
インデントにタブを使うようにしています。

.dir-locals.el

((js-mode . ((indent-tabs-mode . t)
             (js-indent-level . 8))))

便利なので、覚えておきましょう。