Replace text with latex

I wondered if it is possible to make emacs replace occurences of a/b with ${a \over b}$ , where a and b are integers or letters in the text.

• Note that {a \over b} is TeX but depreciated in LaTeX. You should use \frac{a}{b} in LaTeX. – Tobias Jul 19 at 11:00
• M-x replace-regexp should do the trick, if you are familiar with regex. – whatacold Jul 19 at 11:13
• Ok, thanks, I will look into regex – Olav Jul 19 at 11:15
• You can use calc-embedded to replace any formula in algebric syntax to latex syntax. The built-in command is C-x * E. It can be smart to bind a F key since you have to strike it twice to return to latex-mode – gigiair Jul 19 at 18:59

Go to the beginning of your text and press C-M-%. That key sequence is bound to the command query-replace-regexp.

Give $$[+-]?[0-9]+\|\_<[[:alpha:]]$$/$$[+-]?[0-9]+\|[[:alpha:]]\_>$$ as search string and {\1 \\over \2} as replacement and press RET.

Note that this searches for integers maybe composed of several digits and with optional sign + or -. Variables must consist of exactly one letter. Variables composed of several letters are ignored because of the symbol delimiters \_< and \_>.

No space is permitted between the variables/numbers and the slash.

Some comments on the used constructs in the regular expression:

• $$...$$ delimit groups which you can refere to in the replacement string with \1, ..., \9
• \\ in the replacement text is a literal backslash. (backslash alone is used for referencing groups in the search string)
• [0-9] is the character class consisteing of the characters from 0 to 9
• \| is the or-operator. Match either the left-hand side or the right-hand side. Left-hand and right-hand side can be delimited by a group.
• [[:alpha:]] is the character class that matches one character within A-Z and a-z, they match actually more: characters with word-syntax.
• \_< and \_> are symbol boundaries at the beginning and the end, respectively.

Reason for this answer: The tag search for [replace] does not give a simple answer for that question. Most questions address more complicated cases.

• Using [[:alnum:]]+ should simply that expression. – Andreas Röhler Jul 19 at 12:15
• @AndreasRöhler No it doesn't. The OP says there may be letters or integers. Letters consist only of a single character while integers are composed of the optional sign and a sequence of digits. Thus those cases must be separated anyway. – Tobias Jul 19 at 12:23
• Thanks, that worked – Olav Jul 19 at 15:58