emacsevil-mode

Make gg=G work in Evil-Mode to indent whole buffer?


I'm trying to move from Vim to Emacs using Evil mode, but can't get gg=G to indent the whole buffer working.

However the combination gg=G just doesn't work and I can't work out how to define it myself.

I have the following function defined to indent the whole buffer:

(defun indent-whole-buffer ()
    "indent whole buffer and untabify it"
    (interactive)
    (delete-trailing-whitespace)
    (indent-region (point-min) (point-max) nil)
    (untabify (point-min) (point-max)))

However if I try to bind it to gg=G like this: (define-key evil-normal-state-map "gg=G" 'indent-whole-buffer), then gg no longer works. I'm stuck. Help!


Solution

  • Without rebinding anything, the simplest thing to do is ggVG=, which will 1) take you to the top of the buffer, 2) enter visual line state, 3) take you to the end of the buffer, and 4) indent everything you just highlighted. EDIT: are you sure gg=G doesn't work? It gives the expected behavior for me.

    It'll be best if you forget how Vim does key bindings and look into how Emacs does keymaps (see here, here, and here to get started). In this specific instance, you'll want to remember that you can't have a long sequence of keys (eg, gg=G) as well as a shorter subset (gg) because you're effectively overwriting the shorter subset (ie, you can't get to gg=G without first entering gg).

    So, for example, let's say you wrote a custom function to indent the entire buffer:

    (defun indent-buffer ()
      "Apply indentation rule to the entire buffer."
      (interactive)
      (indent-region (point-min) (point-max)))
    

    You could then bind it to an unbound key such as Q (or a sequence like gQ, or overwrite something else) in the normal state map as:

    (define-key evil-normal-state-map "Q" 'indent-buffer)
    

    (EDIT: d'oh, I'd forgotten that you'd written your function already; sorry for the duplication.)