How to start a hook based on file location

I participate in a python project where tabs are used, however I do not use them in every other code that I write, it is vital to use them in this particular project. Projects are located in one directory in certain directories. I.e:

\main_folder \project1 \project2 \project3 ...etc 

I have a couple of functions / hooks on opening a file and keep that untabify and tabify are the whole buffer I'm working on.

  ;; My Functions (defun untabify-buffer () "Untabify current buffer" (interactive) (untabify (point-min) (point-max))) (defun tabify-buffer () "Tabify current buffer" (interactive) (tabify (point-min) (point-max))) ;; HOOKS ; untabify buffer on open (add-hook 'find-file-hook 'untabify-buffer) ; tabify on save (add-hook 'before-save-hook 'tabify-buffer) 

If I put it in a .emacs file, it runs on every .py file that I open, which is not what I want. I would like these hooks to be used only in one specific folder with the corresponding subfolders. Tried .dir_locals, but it only works for properties that don't intercept. I cannot use hooks in certain modes (e.g. python-mode), since almost all projects are written in python. Honestly, I tried writing esisp conditional save, but failed.

+5
source share
2 answers

A very simple solution is to simply add a configuration variable that can be used to disable hooks. For instance:

 (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 the .dir-locals.el to the appropriate directories by setting tweak-tabs to nil , disabling this function there.

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

+2
source

Just for the record, to answer a personal question in the header (since I reached this question through a web search): one way to add a hook that depends on the location of the file is to make it a function that checks for the presence of buffer-file-name . (The idea is from this answer .)

For example, for the same problem (enable tabs only in a specific directory and leave tabs disabled elsewhere), I'm doing something now (after installing the smart-tabs-mode Mx package-install with Mx 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 little inverted since smart-tabs-insinuate modifies python-mode-hook , and then we modify it, but this should be an example.)

0
source

Source: https://habr.com/ru/post/891160/


All Articles