As of Version 3.7, latexindent.pl can help with this.
As a warning: do take care when using regular expressions such as those below, always check that they are behaving as you would like, and test them before using them on anything important.
Starting with the following sample code
\begin{env}
$f_i^k+10=x$
\end{env}
$g_ij^12-3=x$
and the YAML file, say puk1.yaml
replacements:
-
substitution: |-
s/\$(.*?)\$/%%
%% Insert comment describing function here
%%
\$$1\$/sxg
and running the command
latexindent.pl -r myfile.tex -l=puk1.yaml
gives the output:
\begin{env}
%%
%% Insert comment describing function here
%%
$f_i^k+10=x$
\end{env}
%%
%% Insert comment describing function here
%%
$g_ij^12-3=x$
This doesn't have everything you requested. We can incorporate some more replacements in the following file, say puk2.yaml
replacements:
-
substitution: |-
s/\$\h*(.*?)\h*\$/#
my $comment = "%%\n%% Insert comment describing function here\n%%\n";
my $body = $1;
# add braces to superscripts and subscripts
$body =~ s@(\^|\_)([a-zA-Z0-9]+)@$1\{$2\}@sg;
# add a single space around + - =
$body =~ s@\h*([+\-=])\h*@ $1 @sg;
# put it all together
$comment."\$ ".$body." \$";/sxge
and running
latexindent.pl -r myfile.tex -l=puk2.yaml
gives
\begin{env}
%%
%% Insert comment describing function here
%%
$ f_{i}^{k} + 10 = x $
\end{env}
%%
%% Insert comment describing function here
%%
$ g_{ij}^{12} - 3 = x $
.texfile) so that super-/subscripts are actually put in braces{ }, thereby possibly avoiding formatting problems? – Werner Oct 05 '11 at 19:17sedmight be able to do some of the grouping based on certain assumptions. But such rules would be source-specific; again, not very general. – Werner Feb 02 '12 at 06:33