2

Ask people to help me write a script that replaces all the math formulas $$ ... $$ into \ [... ] in texstudio. Thank you!

5
  • 3
    Latexindent can help with this, see latexindentpl.readthedocs.io/en/latest/… – cmhughes Apr 15 '20 at 6:33
  • You can use function replace (Ctrl + R) in TeXstudio or TeXmaker. – minhthien_2016 Apr 15 '20 at 10:12
  • I want to replace large numbers of files so manually Ctrl + R is not suitable – Anh Tuấn Trần Apr 15 '20 at 11:30
  • That seems difficult – Someone Apr 15 '20 at 14:40
  • You could use Geany, ctrl + H finds all occurrences. – c.p. Apr 18 '20 at 18:18
1

Here are a few ways that might help to get you started.

We'll start with the following file, say myfile.tex:

myfile.tex

before text $$a^2+b^2=4$$ and $$c^2$$

$$
d^2+e^2 = f^2
$$
and also $$ g^2
$$ and some inline math: $h^2$

in each of the following, the output is:

output.tex

before text \[a^2+b^2=4\] and \[c^2\]

\[
d^2+e^2 = f^2
\]
and also \[ g^2
\] and some inline math: $h^2$

option 1: a perl one liner

perl -p0 -e 's/\$\$(.*?)\$\$/\\\[$1\\\]/sg' myfile.tex > output.tex

See https://perldoc.perl.org/perlrun.html, for example, for details of perl switches.

option 2: using a perl script

Using the following script, and the command

perl replace.pl myfile.tex > output.tex

replace.pl

#!/usr/bin/env perl

use strict;
use warnings;

# read the file into the Document body
my @lines;
my $fileName = $ARGV[0];

# if the file exists, read it into an array
if(-e $fileName){
    open(MAINFILE, $fileName) or die "Could not open input file, $fileName";
    push(@lines,$_) while(<MAINFILE>);
    close(MAINFILE);
} 

# join the lines up
my $body = join("",@lines);

# make the substitution
$body =~ s/\$\$
           (.*?)
           \$\$/\\\[$1\\\]/sgx;

# output the body
print $body;

exit(0);

option 3: using latexindent

Using latexindent which should be available as part of your LaTeX distribution, you can use the following YAML settings file:

Anh.yaml

replacements:
  -
    substitution: |-
     s/\$\$
       (.*?)
       \$\$/\\\[$1\\\]/sgx

and then call it with

latexindent.pl -rr -l=Anh.yaml myfile.tex -o=output.tex
3
  • Not so simple. You have to handle cases like For $x$$=$$y$, we have no displays. – Donald Arseneau Apr 18 '20 at 18:28
  • @DonaldArseneau an interesting test case... I wonder: is it realistic...? Also, you'll note that my post said help get you started... – cmhughes Apr 18 '20 at 18:37
  • to whoever gave -1: thanks! – cmhughes Apr 18 '20 at 18:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.