M-g vs. goto-line

Just as many of you, I always missed the goto-line command in Emacs having no key assigned by default despite its usefulness, and one day (when I moved from XEmacs) I bound it to M-g. However, starting with Emacs 22, they decided to have it bound to M-g M-g, along with previous-error which was bound to M-g M-p and next-error to M-g M-n. The last part looked nice especially when I wasn’t happy with C-x ` at all, but it was just far from acceptable to me that I had to type M-g twice for jumping to a specific line number, so I insisted on my binding of M-g.

Time has passed, and now I have a bit of skills in elisp, and here it goes:

(defun goto-line-number ()
  (goto-line (string-to-number
               "Goto line: "
               (char-to-string last-command-event)))))
(loop for n from 1 to 9 do
      (global-set-key (format "\M-g%d" n) 'goto-line-number))
(global-set-key "\M-g?" 'describe-prefix-bindings)

This snippet makes it as if M-g were a key for goto-line by tweaking the key bindings of M-g 1..9. For example, typing M-g 2 lets you enter the minibuffer with the first figure (2) input, and you are ready to type the rest of the figures of a line number, just as below:

-UUU:@----F13  init.el        Top (1,0)     [1]  (Emacs-Lisp FlyC:1/5 hs AC yas)
Goto line: 2 

This means you can just say M-g 2 0 0 RET to get to the line 200 while you can say M-g M-n to jump to the next error line. Cool.

For those who may wonder, the last line of the snippet helps you remember other key combinations of the M-g family by typing ? after M-g. Happy hacking!

Leave a Reply

Your email address will not be published.