How to encircle a character inside a Latex formula?

Slight improvement of ThV's answer, in order to preserve the proper math style.

\documentclass{article}

\usepackage{tikz}

\makeatletter
\newcommand*{\encircled}[1]{\relax\ifmmode\mathpalette\@encircled@math{#1}\else\@encircled{#1}\fi}
\newcommand*{\@encircled@math}[2]{\@encircled{$\m@th#1#2$}}
\newcommand*{\@encircled}[1]{%
  \tikz[baseline,anchor=base]{\node[draw,circle,outer sep=0pt,inner sep=.2ex] {#1};}}
\makeatother

\begin{document}

\encircled{Text} outside math. $\encircled{n=1}$ formula.
\[
f_{\encircled{n}} = \encircled{f_n}
\]

\end{document}

enter image description here


I would use TikZ to achieve this. Here's some rough sample code that is similar to what is used in the answers to question 1 and question 2 that you mentioned:

\documentclass{article}
\usepackage{tikz}

\newif\ifstartedinmathmode
\newcommand\encircled[1]{%
  \relax\ifmmode\startedinmathmodetrue\else\startedinmathmodefalse\fi%
  \tikz[baseline,anchor=base]{%
  \node[draw,circle,outer sep=0pt,inner sep=.2ex]
    {\ifstartedinmathmode$#1$\else#1\fi};}%
}

\begin{document}

\encircled{Text} outside math. \encircled{$n=1$} formula.
Or $\encircled{n}$ like this.
\[ f_{\encircled{n}} = \encircled{f_n} \]

\end{document}

For convenience, I've added code to automatically switch to math mode if needed. This is based on question 3.

enter image description here