Emacs: Commands and Keys to Navigate Brackets

Advertise Here

, , …,

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

Commands to Navigate Brackets

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

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

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

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

These commands lets you move cursor around all the most used brackets. (➲ Matching Brackets in Unicode)

Setup Alt and Arrow Keys

You can assign them keys with Alt and arrow, like this:

(global-set-key (kbd "<M-left>") 'backward-open-bracket) ; Alt+←
(global-set-key (kbd "<M-right>") 'forward-open-bracket) ; Alt+→

(global-set-key (kbd "<M-up>") 'backward-close-bracket)  ; Alt+↑
(global-set-key (kbd "<M-down>") 'forward-close-bracket) ; Alt+↓

If you want to use {PageUp, PageDown} or other special keys, see: Emacs: How to Define Keyboard Shortcuts.

If you want {Super, Hyper}, see: Emacs: How to define Super & Hyper Keys.

Emacs's Keys to Navigate Nested Brackets as Tree

The above commands move cursor to any of the brackets. If you want to navigate brackets as trees (e.g. jump to parent, skip siblings), you can use the following built-in commands:

Built-in Keys to Navigate Lisp Code

The keys to navigate lisp code are:

Highlighting Matching Brackets

Emacs will also highlight matching brackets. When your cursor is on a matching pair, emacs will highlight the matching brackets, or, the text between them, depending on your settings. For how to turn it on or set your preferences, 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 bracket selected. 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-backwardCtrl+c Ctrl+b】 and sgml-skip-tag-forwardCtrl+c Ctrl+f】.

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

Insert Brackets by Pair

Emacs: Insert Brackets by Pair

blog comments powered by Disqus