DEV Community

The Struggling Dev
The Struggling Dev

Posted on

Major Mode Comfort Functions, Because I'm Lazy

Introduction

After creating a bare bones major mode for Emacs, there are some minor things to do to improve the overall usability. For one, I currently have to build the .el file every time I want to use the mode. And for another I have to manually choose the mode for a given buffer. Let's fix these two annoyances.

Registering the Major Mode when Emacs Starts

We could just always load the file on startup. A better way though is to autoload the major mode. This way the actual function is only evaluated if and when the mode is used. Kinda like a method definition in a header file. The time tracking mode is not really complex, but why load it every time we start Emacs when we can do it only when it's actually being used. To achieve this we add the following line to init.el.

(autoload 'time-tracking-mode "/path/to/major/mode/directory/time-tracking-mode.el" "Major mode for time tracking." t)
Enter fullscreen mode Exit fullscreen mode
  • the first parameter is the name of the function that defines the major mode
  • the second one is the path to the file containing the function
  • the third one is the doc string of the function
  • and the fourth one says that function can be called interactively
  • Autoload (GNU)

If we now restart Emacs the major mode should be available without us first needing to open and evaluate the file manually.

We can test whether it's really only loading the major mode when needed. If we change the file name to something that doesn't exist, we get an error when we activate the major mode for a buffer, saying that the file couldn't be found.

Great, let's move on to the next quality of life feature.

Activating the Major Mode When We Open a File with a Certain Extension

We can tell Emacs to switch to a major mode whenever a file with a certain extension is opened. The only thing we need to do is to add the corresponding mapping to the auto-mode-alist.

(add-to-list 'auto-mode-alist '("\\.ttr" . time-tracking-mode))
Enter fullscreen mode Exit fullscreen mode
  • "\\.ttr" is the file extension
  • time-tracking-mode is our major mode

If we restart Emacs and open a file with the extension ttr the time tracking mode gets activated automatically.

The Struggles

Still struggling a bit with the Emacs documentation, but it's getting better. I'm taking more time to really read the articles - I'm still quite impatient though - small changes and have to read 2 pages of text ;). What I'm not really getting the hang of is where to put the functions. add-to-list for example didn't work in init.el, only in config.el. Need to read up on that.

Thanks for reading and keep on struggling.

Top comments (0)