TransWikia.com

Automatic LaTeX code formatting (similar to clang-format)

TeX - LaTeX Asked by MakisH on January 21, 2021

There are tools such as clang-format that take e.g. an "ugly" (unformatted) C++ source code file and apply specific indentation and other rules to make the code more readable.

Is there such a tool that can automatically format LaTeX source code? I want to somehow keep my LaTeX files clean and consistent among contributors.

2 Answers

The tool latexindent that was suggested by @muzimuzhi-Z in a commect worked for me. This Perl script seems to be very powerful, but starting is easy:

Installation

I already had an older version (probably through texlive-full), but since this project is quite actively developed, I decided to get the latest version:

  1. I got the source from its official repository GitHub
  2. I installed any missing dependencies with sudo ./helper-scripts/latexindent-module-installer.pl
  3. I added it to my path in my ~/.bashrc: export PATH="/path/to/latexindent.pl:$PATH"

Usage

Default options, overwriting the file (-w), without writing a copy to the terminal (-s):

latexindent.pl -w -s myfile.tex

This will keep a backup of the original file .bak0 (or .bak1 etc). If you have this in a repository, you may want to add *.bak? in your .gitignore.

You can also specify your own formatting style in a yml file, like this: latexindent.pl -l mysettings.yml myfile.tex.

Correct answer by MakisH on January 21, 2021

emacs (surpise!) comes with LaTeX support out-of-the-box, much, much fancier support gives AUC-TeX (and RefTeX for cross-references and citing bibliographies). All standard packages, check the package index.

In any case, I format my LaTeX source files to contain a phrase each line, end with punctuation, ... That way (suggested a long while back when writing troff (!) for my thesis, using vi...) changes often mean delete/insert or move a line/lines around, checking for boo-boos like "an thesis" or "a elephant" or "the the case" can be done with line-oriented tools (fix even automated with a simple regex replace). Today I stash it in git, the format has the added benefit that adding/deleting e.g. a word doesn't reflow the paragraph, so version differences do highlight real changes.

Yes, reformatting that way is a chore that has to be done by hand... but it is needed once (and keep it up later).

Answered by vonbrand on January 21, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP