Most programming modes in Emacs support two commands,
beginning-of-defun and end-of-defun. These move you to the beginning
and end of the nearest function, and by default are bound to C-M-a and
C-M-e, respectively.
However, sql-mode does not have anything similar. I have the above
two commands bound to C-up and C-down for quickly moving around
functions, but I find myself often hitting them when viewing an SQL
file to move through tables—which doesn’t work. Fortunately that
functionality is pretty easy to add.
For my fellow Emacs users, here is some code I whipped up that you can
use to easily move between tables and views.
(defconst sql-beginning-of-table-or-view-regexp
“^\\s-*create\\s-+\\(?:table\\|view\\)”
“Regular expression for matching the start of an SQL table or
view definition.”)
(defun sql-prev-table-or-view ()
“Move backwards to the beginning of the nearest table or view
from point.”
(interactive)
(re-search-backward sql-beginning-of-table-or-view-regexp
nil ‘noerror))
(defun sql-next-table-or-view ()
“Move forwards to the beginning of the nearest table or view
from point.”
(interactive)
(re-search-forward sql-beginning-of-table-or-view-regexp
nil ‘noerror))
Then you can add a hook for sql-mode to bind those commands to keys
whenever sql-mode is first loaded. I know you guys already know about
using global-set-key, but you can also create key bindings specific
for modes. Each mode in Emacs has an associated “mode map”, for
example, sql-mode has the sql-mode-map, php-mode has the php-mode-map,
et cetera. You can use the function define-key to create a binding
for a specific mode map. Like I said, I have C-up and C-down globally
bound to move functions, but I use define-key like this to make the
keys move by tables/views is sql-mode:
(global-set-key (kbd “<C-up>”) ‘beginning-of-defun)
(global-set-key (kbd “<C-down>”) ‘end-of-defun)
(add-hook ’sql-mode-hook
(lambda ()
(define-key sql-mode-map (kbd “<C-up>”)
’sql-prev-table-or-view)
(define-key sql-mode-map (kbd “<C-down>”)
’sql-next-table-or-view)))
I put my global key settings in there just for comparison. The call
to define-key is almost identical, except the first argument is the
mode map.
While I’m on the subject, there are two similar commands for text-mode
that have no default binding, which I find come in handy:
(add-hook ‘text-mode-hook
(lambda ()
(define-key text-mode-map (kbd “<C-down>”)
‘forward-paragraph)
(define-key text-mode-map (kbd “<C-up>”)
‘backward-paragraph)))
So there’s some hopefully useful commands for SQL work, and for
configuring key bindings in general.
Related posts: