David Wilson over at the System Crafters Youtube channel has a useful video that discusses file and directory local variables. File local variables are Emacs variables that are specific to a particular file. A common use is to set the major mode of a file. You can do the same thing on a directory-wide basis with directory local variables.
Local variables are very useful but I’ve always had a hard time remembering the exact syntax. I almost always use the property line at the head of the file for file local variables and Wilson shows how to edit those by hand but the nice thing is that you don’t have to remember the syntax. You can use the command add-file-local-variable-prop-line
to add a local variable to the property line and it will even add the property line itself if it doesn’t already exist. If you use the alternate syntax that puts the variables at the end of file, you can use the Emacs command add-file-local-variable
to add a variable. There are also commands to delete variables although you can, of course, simply edit them out by hand. Local variables do not take effect immediately after being set. You have to reload the file or run the command normal-mode
. I didn’t know about normal-mode
so that alone made the video worthwhile for me.
Wilson shows a very nice example of using local variables to arrange for a file’s Org-mode Babel source blocks to be evaluated each time the file is saved. This applies to the single file only so it’s very convenient.
If you’d like to apply a set of variables to a group of files—a project, say—you can use directory local variables that will take effect for each file in the directory. The syntax for directory local variables is even more complex so you will almost certainly want to use add-dir-local-variable
to add them and delete-dir-local-variable
to remove them.
Wilson’s video also covers some of the finer details of using local variables and is definitely worth watching. The video is 37 and a half minutes long so plan accordingly.