Emacs: Electric undesirables

In my Emacs config I have enabled only electric-pair-mode to speed up some quotes and parens. Either this or something else also enables electric-indent-mode which produces weird cursor behaviour in Org lists, particularly when I disagree that I am in a list, so I have ended up suppressing electric-indent-mode explicitly by setting M-x customize-option RET electric-indent-mode off.

In pure coding situations, however, as opposed to prose writing, indenting is the norm, which is why it is lucky that there is a local version of electric indent:

(add-hook 'prog-mode-hook 'electric-indent-local-mode)

Electric indentation produces indentation for code. Sometimes it is better to unindent some lines, i.e. to make the first non-whitespace character the actual first character of the line. Here is some code for this, which simply triggers fixup-whitespace at the beginning of line:

(defun unindent-this-line (&optional N)
  "Remove whitespace at the beginning of current line. With a
numerical argument, do it on another line as per relative line
  (interactive "P")
    (if (equal N nil)
          (beginning-of-line) (fixup-whitespace))
        (forward-line (prefix-numeric-value N))
        (beginning-of-line) (fixup-whitespace))))

And an unindentation function for the entire buffer:

(defun unindent-buffer ()
  "Remove whitespace at the beginning of all lines."
    (let ((inhibit-message t) (message-log-max nil))
      (replace-regexp "^\\s-+" "" nil (point-min) (point-max)))))

Explanation line by line:

  1. Start of function definition
  2. Documentation
  3. Make it a M-x command
  4. Do not displace the cursor
  5. Suppress messages that the next line’s operations tend to emit
  6. Go through the entire buffer (respecting narrowing) and replace whitespace at the beginning of every line with an empty string. In the first quotes, also "^[[:space:]]*" should do the same job, as the s-unindent function in the s-library suggests.

Leave a Reply

Your email address will not be published. Required fields are marked *