The Computer Oracle

How can I write a emacs command that inserts a text with a variable string at the current cursor position?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle

--

Chapters
00:00 How Can I Write A Emacs Command That Inserts A Text With A Variable String At The Current Cursor Pos
00:24 Accepted Answer Score 13
01:18 Thank you

--

Full question
https://superuser.com/questions/389303/h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#emacs #elisp

#avk47



ACCEPTED ANSWER

Score 13


Elisp

Here is a simple elisp function for it:

(defun labelnameref (string)
  "Insert \label{ARG} \index{\nameref{ARG}} at point"
  (interactive "sString for \\label and \\nameref: ")
  (insert "\\label{" string "} \\index{\\nameref{" string "}}"))

This function queries in the minibuffer for the string and then inserts it all at point. To use it you can put it in your .emacs and then invoke it via M-x labelnameref or bind it to a key.

YASnippet

If you want to use lots of similar constructs it might be easier to write them as yasnippets. With YASnippet you can easily create a snippet with similar behavior as above. For example you can use the following (you have replace "keybinding" with a proper keybinding if you want a keybinding for it):

# -*- mode: snippet -*-
# name: foo
# key: foo
# binding: "keybinding"
# --
\label{$1} \index{\nameref{$1}}

With this you write foo and press Tab directly afterwards to expand it to \label{$1} \index{\nameref{$1}} and query for $1.