2011-05-06

Emacs: Defining Keys to Navigate Brackets

Perm url with updates: http://xahlee.org/emacs/emacs_navigating_keys_for_brackets.html

Emacs: Defining Keys to Navigate Brackets

Xah Lee, 2011-05-06

Here are some convenient keys to move cursor by brackets. Very useful in coding C, Java, Python, HTML, or any other languages.

Commands to Navigate Brackets

(defun forward-open-bracket ()
  "Move cursor to the next occurrence of one of ( { [ <."
  (interactive)
  (forward-char 1)
  (search-forward-regexp "(\\|{\\|\\[\\|<")
  (backward-char 1)
  )

(defun backward-open-bracket ()
  "Move cursor to the previous occurrence of one of ( { [ <."
  (interactive)
  (search-backward-regexp "(\\|{\\|\\[\\|<")
  )

(defun forward-close-bracket ()
  "Move cursor to the next occurrence of one of ) } ] >."
  (interactive)
  (search-forward-regexp ")\\|\\]\\|}\\|>")
  )

(defun backward-close-bracket ()
  "Move cursor to the next occurrence of one of ) } ] >."
  (interactive)
  (backward-char 1)
  (search-backward-regexp ")\\|\\]\\|}\\|>")
  (forward-char 1)
  )

These commands lets you move cursor around any brackets, (){}[] but also <>. You can assign them keys. See: Emacs: How to Define Keyboard Shortcuts.

What Keys to Use?

Good keys are the arrow keys, with a combination of Alt, Shift, or Win and Menu keys by mapping emacs's Hyper and Super to them. For me, i use the Win key with Super. (See: Emacs: How to define Hyper & Super Keys.) Here's my code:

(global-set-key (kbd "<s-left>") 'backward-open-bracket)
(global-set-key (kbd "<s-right>") 'forward-open-bracket)
(global-set-key (kbd "<s-up>") 'backward-close-bracket)
(global-set-key (kbd "<s-down>") 'forward-close-bracket)

Emacs's Keys To Navigate Nested Code

The above commands is a very good complement to emacs built-in keys to navigate matching brackets in lisp code and matching tags in html code.

Built-in Keys to Navigate Lisp Code

The keys to navigate lisp code are:

  • Ctrl+Alt+
  • Ctrl+Alt+
  • Ctrl+Alt+
  • Ctrl+Alt+

Highlighting Matching Brackets

Emacs will also highlight matching brackets. When your cursor is on a matching pair char, emacs will highlight the matching pair or the code between them. For detail about these, see: How to Edit Lisp Code with Emacs.

Select Code Between Matching Brackets

Also, you can define a command so that when cursor is on a opening bracket, you can press a key to have the whole code enclosed by the matching pair highlighted. See the command “extend-selection” at Suggestions on Emacs's mark-word Command.

Built-in Keys for Navigating Matching HTML Tags

For html, when in “html-mode”, it has “sgml-skip-tag-backward” 【Ctrl+c Ctrl+b】 and “sgml-skip-tag-forward” 【Ctrl+c Ctrl+f】.

For more productivity tips with html, see: Emacs and HTML Tips.