cmhughes / latexindent.pl

Perl script to add indentation (leading horizontal space) to LaTeX files. It can modify line breaks before, during and after code blocks; it can perform text wrapping and paragraph line break removal. It can also perform string-based and regex-based substitutions/replacements. The script is customisable through its YAML interface.
GNU General Public License v3.0
867 stars 84 forks source link

BodyStartsOnOwnLine: 2 and optional position arguments adds a second % #464

Closed dpo closed 1 year ago

dpo commented 1 year ago

Please provide the following when posting an issue:

original .tex code

\begin{algorithm}[h]%
        Bla.
\end{algorithm}

yaml settings

modifyLineBreaks:
    environments:
        BodyStartsOnOwnLine: 2  # add % after \begin{env} to preserve page reference

actual/given output

\begin{algorithm}[h]%%
        Bla.
\end{algorithm}

(Note the extra %.)

desired or expected output

\begin{algorithm}[h]%
        Bla.
\end{algorithm}

(NB: only one %.)

anything else

Starting with

\begin{algorithm}%
  Bla.
\end{algorithm}

no second % gets added. There seems to be an interaction with the optional [h] argument.

cmhughes commented 1 year ago

Thanks for this, and apologies for delay (various internet/operating system issues).

solution

You can use the following settings

modifyLineBreaks:
    environments:
        BodyStartsOnOwnLine: 2  # add % after \begin{env} to preserve page reference

replacements:
  -
    when: after
    substitution: |-
      s/%%/%/sg

and call latexindent using the -r switch, such as

latexindent.pl -l -m -r myfile.tex

explanation

Referencing https://latexindentpl.readthedocs.io/en/latest/sec-the-m-switch.html#poly-switches-for-other-code-blocks we see that for environments BodyStartsOnOwnLine refers to the content immediately after the begin statement. During the poly-switch adjustment latexindent

  1. first of all adds the comment and the line break
  2. then checks for arguments, and if it finds any, checks the values of LSqBStartsOnOwnLine (optional arguments) and LCuBStartsOnOwnLine (mandatory arguments) and then makes necessary adjustments; in your example, because you haven't specified that either type of argument should start on their own line, latexindent removes the linebreak added in step 1

At the end of the indentation algorithm, latexindent checks for comments that are not at the end of their line, and then moves them. In your case, this results in two comments.

So, finally in the settings above, we instruct latexindent to replace two comment symbols with a single comment symbol. You might like to use

replacements:
  -
    when: after
    substitution: |-
      s/%{2,}/%/sg

which would replace two or more comment symbols with a single comment symbol.

I hope this helps!

dpo commented 1 year ago

Thank you. Strangely, -r works but -rv does not.