[Tex/LaTex] How to use latexindent in TeXStudio on Windows

latexindentmiktextexstudio

I am using TeXStudio with MiKTeX on my Windows 10 computer. I would like TeXStudio to automatically handle the code's indentation in my tex-files, so I enabled Indentation mode under the Editor settings. However, that is not sufficient, since the indentation is not always correct. After some research on the internet, I discovered that there is a useful script latexindent which ships with MiKTeX.

How am I supposed to use latexindent? Is it 'activated' automatically while TeXing or is there some key combination to run the script? I am a bit confused for the moment and also surprised that I cannot find any documentation about this topic.

Best Answer

The following works for me without any other necessities, such as arara.

  1. Install latexindent via MiKTeX Console > Packages.
  2. Download latexindent on CTAN (zip-file).
  3. Navigate to C:\Program Files\MiKTeX 2.9\scripts\latexindent and replace the files in there with the files from the downloaded zip-file in step 2.
  4. Create a new User Command in TeXStudio > Options > Build: "C:/Programs Files/MiKTeX 2.9/scripts/latexindent/latexindent.exe" -w -s %.tex

User Command

Calling this new command via Tools > User, should run latexindent and indent your file! You can even assign a shortcut to the User Command at TeXStudio > Options > Shortcuts to make things quicker.

Note: As Johannes_B pointed out in the comments above (thanks!) and as mentioned in TeXStudio's manual, the % just refers to the basename, i.e. the file name without the file extension. But the extension is needed for the script. If you also want to use latexindent for other extensions, you can replace %.tex by ?c:me", which is equivalent to the current document's filename with the extension attached. To conclude, if the backup files generated by -w annoy you, you can use -s -o ?c:me" ?c:me" instead; this will directly override your tex-file without backups.

Related Question