I would like to do the following: activate some mode so that whenener I type the $ character in my buffer, it immediately gets replaced by <m>.

Even better: when I type $ it puts <m></m> and places the cursor between the matching tag pair.

I have no problem with the solution being quick and dirty, but I would need to be able to turn it on and off.

Context: I've started using PreTeXt, which is basically "laTeX meets xml", to write a math text. It works very well, but having to type <m> all the time is damaging my productivity (I'm already enjoying c-C ] to close the tags.)

  • 1
    You can use abbrev for this emacswiki.org/emacs/AbbrevMode there is a hook you can run after abbrev which might be able to move the cursor. To check surrounding context or move the cursor you might need to use a post-command-hook. You could also look into yasnippets which is a template system which can position the cursor. – ideasman42 Aug 19 '20 at 22:29
  • @ideasman42: Please consider posting your comment, or similar, as an answer. – Drew Aug 20 '20 at 0:08
  • @ideasman thanks for the reply. I've been using emacs for 15 years, so all the terms and words you wrote look familiar to me (e.g. hooks) but I don't know what they mean. EDIT: okay maybe I should carefully read the link youto abbrevmode you provided :-) – NWMT Aug 20 '20 at 0:14

This can be done using abbrev mode:

;; Hook to go back N chars after completion.
(defun my-abbrev-back-4-no-self-insert ()
    (forward-char -4)
(put 'my-abbrev-back-4-no-self-insert 'no-self-insert t)

    (list "$" "<m></m>" 'my-abbrev-back-4-no-self-insert 0)
    ;; More typical examples of abbrev mode usage.
    (list "btw" "by the way" nil 3)
    (list "pov" "point of view" nil 1)))

;; Enable abbrev mode.
(add-hook 'after-change-major-mode-hook
  (lambda ()
    (when (or (derived-mode-p 'prog-mode)
              (derived-mode-p 'text-mode))
      (abbrev-mode 1))))

The above code block can be copy-pasted into your emacs init file.

For more advanced templating you may want to look into: yasnippets.

  • 1
    @ideasman2 WHOA SO AWESOME!!!!!!! Thank you! – NWMT Aug 20 '20 at 15:23
  • I omitted the enable abbrev mode part at the bottom as I don't want my text editor to do this all thie time. I'm fine with invoking M-x abbrev-mode as I need it. I'm guessing there's a way to make this work automatically when working on certain types of flles. – NWMT Aug 20 '20 at 15:26
  • 1
    You can adjust (or (derived-mode-p 'prog-mode) (derived-mode-p 'text-mode)) to check for a more spesific mode. – ideasman42 Aug 21 '20 at 1:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.