, , , Posted on 4 February 2025 by

Weekly Emacs tip #9: Removing superfluous spaces

Today’s tip is about managing superfluous spaces (in the sense of whitespace). For that, I use the following two functions:

  • The function delete-horizontal-space (bound to M-\) removes all whitespace (spaces and tabs) around the point (Emacs-speak for “the cursor”).
  • The function cycle-spacing (bound to M-SPC) is a “smarter” version of the above. It manipulates whitespace around the point by cycling the following actions as you repeatedly call the function:
    • “just one space”, delete all but one space
    • “delete all space”, delete all spaces (like delete-horizontal-space above)
    • “restore”, go back to the original spacing.

I typically use the second function when reformatting text, e.g. code or regular text with indentation. In such cases, it often happens that you remove some text on a given line and, as a result, text from the next line moves up, but with many spaces in between (because of the indentation). In cases like this hitting M-SPC collapses all indentation spaces into a single one (cliffhanger: there will be a future tip about fill-paragraph, which is also handy in this case :-)).

Before I got to know about M-SPC, I often used M-\. Nowadays, I don’t use it that much any more.

One note about the keyboard shortcut M-SPC: in most desktop environment using Alt-SPC opens the window menu for the given application, so you’ll have to use the alternative to Alt, which is the Esc key. Note that in that case, you press and release Esc and then hit the space bar, so you don’t keep Esc pressed like you do with Alt. Alternatively, you can tell the desktop not to catch Alt-SPC. In the Gnome desktop you do this via Settings → Keyboard → Keyboard Shortcuts → select “Windows” → disable the “Activate the window menu” option by clicking on it and hitting backspace.

No Comments

Let us keep you updated!

Once a month we’ll send you an overview of our newest articles. No spam, we promise.

Thank you for signing up! We've send you an confirmation mail.