# Automatically change l to \ell in a math mode

I want to find a way how to automatically change "l" into "\ell" in a math mode.

I tried to do it using \catcode, but it's quite difficult for me.

I want it to change "l" only when it appears alone.

(e.g., do not change "l" in \log or if I define a variable lb as follows:

$\log l = lb + l^2$


I want to change the second and the fourth "l" only)

It would be even better if I can typeset the original "l" by using "\ell" instead (i.e., change the role of them)

• The problem is that, in math mode, lb represents the multiplication of l and b, not the variable lb. For multi-letter mathematical symbols, one might use, for example, \mathrm{lb}. In this sense, your question might be considered ambiguous. Dec 2 '21 at 19:35
• I think this question has already been answered by Lev Bishop in Substituting character $l$ with $\ell$ throughout math mode Dec 3 '21 at 9:36
• 1/ Thanks a lot for pointing out why this is hard. 2/ Thanks! Dec 4 '21 at 23:06

A proof of concept. You need to mark up the multiletter variables anyway, because you don't want that your reader mistake them for products.

\documentclass{article}

\mathchardef\standardl=\mathcodel
\mathcodel=\ell
\newcommand{\deactivatel}{\mathcodel=\standardl}
\makeatletter
\edef\operator@font{\operator@font\noexpand\deactivatel}
\makeatother

\newcommand{\mlvar}[1]{\mathit{\deactivatel #1}}

\begin{document}

$\log l+\mlvar{lb}+l^2$

\end{document}


The letter l is assigned as mathcode the one of \ell. But in some places (operators and multiletter variables) it is set back to the original.

However, you should use \ell when you want it (and in my opinion one never needs it).

• Thanks a lot! This seems the best I can do with pdf latex. Dec 4 '21 at 23:08

Here's a LuaLaTeX-based solution. The solution provides a Lua function called l2ell that does most of the actual work, along with two utility LaTeX macros, \lellOff and \lellOn, which deactivate and reactivate the l2ell function.

This approach will admittedly go astray on $\l$. However, as \l is a text-mode command (for the Polish "soft ell", to be specific), it shouldn't occur in math-y circumstances, right?

\documentclass{article}
\usepackage{luacode}
\begin{luacode}
function l2ell ( s )
s = s:gsub ( "^l(%A)" , "\\ell %1" )
\end{document}
`
• Really awesome! (except for the fact that I have to figure out how to compile my tex file with LuaLaTeX). Thanks a lot! Dec 4 '21 at 23:07
• @user182849 - Which front-end editor do you use? If it has a drop-down menu to select which program to run, chances are that "lualatex" will be one of the options.
– Mico
Dec 5 '21 at 0:52
• Thanks for the follow up. I am using texmaker, and now I have figured out how to compile it with lualatex! Your solution works well. I should read some articles like tex.stackexchange.com/questions/28642/… before moving to LuaLaTeX, though:) Dec 5 '21 at 1:41