# Multiple Find & Replace in TexStudio using Script Macros

I am using TexStudio with MikTex. I am using at least two packages regularly to create certain lists. Let us say, in one package I have to use \begin{exam} and \end{exam} to start and end list and \item to create list items. In another package, \begin{test} and \end{test} along with \choice to do the same. There are some other similar commands which are different. The subject matter (contents of items) in both is exactly the same. I am using Find and Replace to convert one to another. It takes time to do it carefully, some replacements need to be done whole word some case sensitive and so on.

Question: Is there a way to use Macros with Script in TexStudio to create a Macro which can work for the whole document and do all replacements in one go?

Attempts: In TexStudio user manual at TexStudio Manual it mentions

I have tried using editor.replace("\item","\choice") but didn't work. I don't know if I am following syntax correctly or not, and what to put in Abbreviation and Trigger.

Any help would be gratefully appreciated.

Paste this under "LaTeX content":

%SCRIPT
options = "g"
scope = editor.document().cursor(0, 0, -1);
editor.replace("\\item",options,scope,"\\choice")


Note that the backslash \ needs to be escaped (i.e., typed twice), if not, the script searches for the word item instead, and not \item. This then has the undesired effect of changing items in your normal paragraphs to \choices, and also, \begin{itemize} to \begin{choiceize}, for example.

The g stands for global, omit it if you want the macro to only search and replace one \item at every call of the macro.

I should note that this is a very crude way of searching and replacing (are you sure you want to change all \items to \choice?) More sophisticated replacements are possible (e.g. by limiting the scope with the scope variable: currently it searches the entire document), but then you would have to describe your use case more precisely (and provide an example for me to test with).

Abbreviations and Trigger can be left empty in your case.

• Thank you very much. This is exactly what I was looking for. I have added more lines and it is working perfectly fine. For example editor.replace("\\begin{exam}",options,scope,"\\begin{test}") and also had to delete some code which was occupying whole line so initially I replaced it with blank but that started giving error as it was inside list environment. Now I have replaced them like this editor.replace("\\stlist",options,scope,"\%\\stlist"). The good thing is, now I can go back to original document using a reversal of this script and it is working. – MathNovice Mar 13 '18 at 5:46