Toggle Org Emphasis with the Marker Itself
I recently read an Irreal post about org-emphasize. It reminded me
of a small command I have used for a long time: when a region is active, the
* key toggles bold emphasis instead of merely inserting a character.
The interaction is simple:
|text| + * → *text* |*text*| + * → text *|text|* + * → text
Without an active region, * behaves normally.
(defun my/org-toggle-emphasis (char)
"Toggle emphasis CHAR around the region, or insert CHAR normally."
(if (not (use-region-p))
(let ((last-command-event char))
(org-self-insert-command 1))
(let ((beg (region-beginning))
(end (region-end)))
(cond
((and (>= (- end beg) 2)
(eq (char-after beg) char)
(eq (char-before end) char))
(save-excursion
(goto-char end)
(delete-char -1)
(goto-char beg)
(delete-char 1)))
((and (> beg (point-min))
(< end (point-max))
(eq (char-before beg) char)
(eq (char-after end) char))
(save-excursion
(goto-char end)
(delete-char 1)
(goto-char beg)
(delete-char -1)))
(t
(org-emphasize char))))))
(defun my/org-make-toggle (char)
"Return an interactive Org emphasis toggle for CHAR."
(lambda ()
(interactive)
(my/org-toggle-emphasis char)))
(define-key org-mode-map (kbd "*") (my/org-make-toggle ?*))
This resembles how electric pairs can surround a selected region, but
electric-pair-mode does not provide the removal part of the
toggle. Using org-emphasize directly keeps the implementation
self-contained and leaves the rest of Org’s pairing behavior
unchanged.
The same helper can also be bound to /, _, +, =, or ~.