# Shortcut to wrap text with latex macro (macOS, systemwide)

I'm looking for a way to create systemwide shortcuts on macOS to wrap selected text with some LaTeX macro (like {}, or \emph{}, but especially I'm interested in some creating some custom ones).

I know editors such as TeXShop do this, but I'd like to create a service, that I can then assign a shortcut to in the System Preferences, which wraps text in any application (at least the ones that use standard Mac text processing). Can anyone point me in the right direction?

• As that's basically a MacOS Services question not specific to TeX, this might get closed as off-topic. But How To Create Your Own Services Menu Options on Mac at MakeUseOf looks like the way to go. – Mike Renfro Mar 30 '18 at 1:18
• Hmm, Automator is of course a possibility, but I was hoping maybe someone already has a solution to this? – jan Mar 30 '18 at 1:46
• See this question, for a simple version of what you want: How to create a service that puts selected text into quotation marks? – Alan Munn Mar 30 '18 at 2:29
• @HaraldHanche-Olsen -- why don't you post an answer citing your inspiration as the question/answer on the apple site. – barbara beeton Mar 30 '18 at 20:24
• @barbarabeeton I'll give it some thought. I admit I had not read the question carefully enough; clearly, using sed is not appropriate for the present usage. For adding emphasis, something like echo -n '\emph{'; cat; echo -n '}' comes closer. However, Automator's “Run shell script” action adds a newline to the end of the text, and that seems tricky to remove with standard unix utilities. If I can think of a good way, I'll post an answer. – Harald Hanche-Olsen Mar 31 '18 at 6:09

Instead of the sed script posted there, you can use the following to wrap \emph{…} around the text:
IFS='' echo -n '\emph{'"cat"'}'

Note the careful use of quotes: The single quotes in '\emph{' and '}' ensure that all characters within are taken literally, while the double quotes around the backquoted cat in the middle allow the backquotes to do their work. The initial IFS='' serves to tell bash not to split the text on spaces, tabs, and newlines.
If you need single quotes in the inserted text, a tricky construct is needed: Something like 'fo'\''c'\''sle' will expand into fo'c'sle.
• For some reason I don't quite understand, the simpler script echo -n '\emph{'; cat; echo -n '}' introduces an extra space before the final brace. – Harald Hanche-Olsen Mar 31 '18 at 6:59