Skip to content

Instantly share code, notes, and snippets.

@riccardomurri
Created August 19, 2011 18:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riccardomurri/1157664 to your computer and use it in GitHub Desktop.
Save riccardomurri/1157664 to your computer and use it in GitHub Desktop.
Emacs commands to wrap a block of text into start/end tags, or insert them. Similar to what AUC-TeX' font commands do, but generic.
(defun wrap-region-in (start-text end-text)
"Insert START-TEXT at the beginning of the currently active
region, and END-TEXT at the end of it."
(let ((start (min (point) (mark)))
(end (max (point) (mark))))
(save-excursion
(goto-char end)
(insert end-text)
(goto-char start)
(insert start-text))))
(defun insert-or-wrap (start-text end-text)
"If mark is set, wrap region by inserting START-TEXT and
END-TEXT at the beginning and end of the region
respectively. Otherwise, insert START-TEXT followed by END-TEXT
at point and move point in between the two."
(if (mark t)
(wrap-region-in start-text end-text)
(insert start-text)
(insert end-text)
(backward-char (length end-text))))
(defun define-html-insert-or-wrap-command (key tag &optional keymap)
"Bind KEY in KEYMAP to a command that inserts a
pair of opening and closing tags, or wraps the currently active
region in them. Second argument TAG should be a string with the
HTML tag name, i.e., not comprising the any `<' or `>'
characters."
(define-key (or keymap html-mode-map) key
`(lambda ()
(interactive)
(insert-or-wrap
(concat "<" ,tag ">")
(concat "</" ,tag ">")))))
;; example -- bind font keys in HTML mode
(add-hook 'html-mode-hook
(lambda ()
(define-html-insert-or-wrap-command (kbd "C-c C-f C-b") "b")
(define-html-insert-or-wrap-command (kbd "C-c C-f C-e") "e")
(define-html-insert-or-wrap-command (kbd "C-c C-f C-i") "i")
(define-html-insert-or-wrap-command (kbd "C-c C-f C-s") "strong")
(define-html-insert-or-wrap-command (kbd "C-c C-f C-t") "tt")
(define-html-insert-or-wrap-command (kbd "C-c C-f C-u") "u")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment