how to auto-indent latex in sublime text 4?

142 views Asked by At

The sublime text auto-indent (ctrl+shift+p "indentation: Reindent Lines") doesn't work for latex files. I suspect sublime-text doesn't recognize/associate a particular set of indentation rules for .tex files (works fine for python).

I also haven't been able to find anything which auto-indents in the LatexTools plugin. This old-ish (2014) question doesn't seem to work for me as well.

(running sublime text 4 on ubuntu 22.04 if relevant)

1

There are 1 answers

3
eretmochelys On

Per @samcarter's answer above, installing the perl script ctan.org/pkg/latexindent indents as needed.

I wanted to integrate a bit with sublime-text so I wrote a little plugin (largely stolen from here). To install yourself, just make a new plugin (Tools > Developer > New Plugin ...) and past the code below as latexindent.py (sublime should default to the proper location for this file if you created it via the tools menu as described).

import sublime
import sublime_plugin
import os
import subprocess

class LatexIndentOnSave(sublime_plugin.EventListener):
    def on_post_save_async(self, view):
        filename = view.file_name()    
        if filename.endswith('.tex'):
            subprocess.run(['latexindent', filename, '-o', filename], cwd=os.path.dirname(filename))

Note that this plugin will run latexindent on all files ending in .tex after saving them, replacing the original contents (which can be very troublesome if latexindent isn't working as you'd like!). If you'd like to have a backup made with every save, consider swapping the -o for the -w switch as @cmhughes suggests below.