Create a TeXstudio macro to remove extra brackets

findtexstudio

I have a software to write mathematical expressions that let me quite faster type while teaching. This software have a LaTeX translation tool that works fine, but it adds as many brackets as it wants.

I have been using the replace tool of TeXstudio with regular expressions (regexp) for a while in order to correct some issues and recently I found how to remove extra brackets in expressions. So I can transform {{any}} into {any}.

I would like to have a TeXstudio macro to perform all replacements, but I got some difficult
writing the correct code for the macro version of the find and replace syntax.

The following links helped me to create the macro as far as I could.

  1. How to insert submatches from regular expression in TexStudio
  2. Broken regexp replace in TeXstudio macros
  3. TexStudio, How to search regexp to the next }-bracket
  4. https://www.w3schools.com/jsref/jsref_obj_regexp.asp

The following figure shows the Find/Replace syntax that works and the macro version I tried without success.

enter image description here

The Find syntax {{([^\{\}]+)}} also works with {{([^\{\}]*)}}.

I don't know what I should do with the "\1" part I used in the Replace when it goes into the macro.

The operation performed by Find and Replace works as expected.

enter image description here

But when applying the macro I get null as result. I clearly don't know the correct syntax to do the substitutions properly.

enter image description here

A MWE follows, this MWE don't need to be executed.

\begin{equation}
  {{1}} \frac{{a}}{{b}} \dfrac{{num}}{{den}}
  {{a + b}}^{{c + d}}
  {{m + n}
  }
\end{equation}

The SCRIPT I'm trying to create is:

%SCRIPT
options = "g"
scope = editor.document().cursor(0, 0, -1)
editor.replace(/\{\{[^\{\}]*\}\}/g,
    options,scope,
    /\{\\1\}/)

I also tried

editor.replace(/\{\{[^\{\}]*\}\}/g,
    options,scope,
    "{\\1}")

and also some variations like /\{$1\}/ without success.


Edit

The regexp in Find syntax /\{\{[^\{\}]+\}\}/ (or * instead of +) seems to work properly, it finds every double brackets. Using a replace syntax with a fixed string such as "{A}" does the correct replacement as presented at the following figure.

enter image description here

Best Answer

I asked the same question at the TeXstudio GitHub's forum: https://github.com/texstudio-org/texstudio/discussions/1884.

I reproduce the solution and present the result below.

Basically there must be parenthesis in the search syntax (I misssed them), and there should not be the scope optional argument. The replace argument must be a string with double backslashes before the number of replacemente, that is, "{\\1}". Therefore the macro to remove extra brackets is:

%SCRIPT
editor.replace(/{{([^\{\}]*)}}/, "g", "{\\1}")

The following gif shows the result.

enter image description here

Related Question