Emacs: Set tab indent for just one file on the fly

前端 未结 6 1609
无人及你
无人及你 2021-02-01 17:02

I work on an open source project where the creator sets his tab-indents to 2 spaces.

I\'d like to just enable it on the fly for the one file I work on and not other fil

6条回答
  •  青春惊慌失措
    2021-02-01 18:03

    As indicated by others, one issue with the File Local Variables approach is that you need to modify the file, and that's not ideal if you need to keep those declarations out of version control.

    If you want the variables to apply to all files under a given directory, then Directory Local Variables is obviously the way to go, and you can implement that with either a .dir-locals.el file, or by calling (dir-locals-set-directory-class):

    • http://www.emacswiki.org/emacs/DirectoryVariables
    • http://www.gnu.org/software/emacs/manual/html_node/emacs/Directory-Variables.html

    I prefer the directory class approach myself, and I was thinking that it's a shame that there isn't an analogous approach for file local variables, but I found that the directory class code actually works perfectly with files, and the only issue is that dir-locals-set-directory-class calls file-name-as-directory on its argument, which prevents it from being matched, due to the trailing slash.

    The following therefore is a way to configure directory local variables for a single file, without modifying the file itself, or affecting other files under the same parent directory.

    (defun my-file-locals-set-directory-class (file class &optional mtime)
      "Enable 'directory local' classes for individual files,
    by allowing non-directories in `dir-locals-directory-cache'.
    Adapted from `dir-locals-set-directory-class'."
      (setq file (expand-file-name file))
      (unless (assq class dir-locals-class-alist)
        (error "No such class `%s'" (symbol-name class)))
      (push (list file class mtime) dir-locals-directory-cache))
    
    (dir-locals-set-class-variables
     'my-javascript-class
     '((nil . ((js-indent-level . 2)
               (indent-tabs-mode . nil)))))
    
    (my-file-locals-set-directory-class
     "path/to/the/file.js" 'my-javascript-class)
    

提交回复
热议问题