Q:

How to encircle a character inside a Latex formula?

I would like to encircle one character inside a LaTeX formula. An example is

$f_1 = ...$ or $f_k = ...$,

where I want to encircle the characters 1 and k. I've found some questions (question 1, question 2) about how to encircle one character or an entire (small) formula. But how should I encircle only one character of a LaTeX formula? Is there an easy solution such as

$f_\encircled{1} = ...$

(my preference), should I use symbols such as from the \ding library, or use TikZ?

A:

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}

A:

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.

