How to run hook depending on file location

你。 提交于 2019-12-04 09:16:37

A very easy solution is to just add a configuration variable that can be used to disable the hooks. For example:

(defvar tweak-tabs t)
(add-hook 'find-file-hook
          (lambda () (when tweak-tabs (untabify (point-min) (point-max)))))
(add-hook 'before-save-hook
          (lambda () (when tweak-tabs (tabify (point-min) (point-max)))))

Now you can add a .dir-locals.el file in the relevant directories, setting tweak-tabs to nil, disabling this feature there.

(But another problem is that this is a pretty bad way to deal with tabs. For example, after you save a file you do see the tabs in it.)

Just for the record, to answer the literal question in the title (as I reached this question via a web search): one way to add a hook that depends on file location is to make it a function that checks for buffer-file-name. (Idea from this answer.)

For example, for the exact same problem (turn on tabs only in a particular directory, and leave tabs turned off elsewhere), I'm currently doing something like (after having installed the package smart-tabs-mode with M-x package-install):

(smart-tabs-insinuate 'python) ; This screws up all Python files (inserts tabs)
(add-hook 'python-mode-hook    ; So we need to un-screw most of them
          (lambda ()
            (unless (and (stringp buffer-file-name)
                         (string-match "specialproject" buffer-file-name))
              (setq smart-tabs-mode nil)))
          t)                   ; Add this hook to end of the list

(This is a bit inverted, as smart-tabs-insinuate itself modifies python-mode-hook and then we're modifying it back, but it should do as an example.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!