Skip to content

Allow linebreaks in latex(pdf) codeblocks - #2343

Merged
jfbu merged 2 commits into
sphinx-doc:stablefrom
jfbu:codeautolinebreakV3
Apr 25, 2016
Merged

jfbu merged 2 commits into
sphinx-doc:stablefrom
jfbu:codeautolinebreakV3

Conversation

@jfbu

@jfbu jfbu commented Feb 19, 2016

Copy link
Copy Markdown
Contributor

This addresses the issue raised in #1534 and #2304: currently long lines do not wrap in code blocks for LaTeX output, they cross the frame, go to the page margin and possibly beyond.

Currently, Sphinx uses LaTeX package fancyvrb for its Verbatim environment. This environment scans each input line and puts it in an unbreakable horizontal box (actually multiple nested ones). It does not do any syntax highlighting, the latter has been incorporated by Sphinx LaTeX writer directly via macros \PYG... in the produced latex file.

More recent packages exist, among them minted which however needs -shell-escape for its latex runs as it appeals to pygmentize. Switching to minted would mean presumably a complete revision of how the Sphinx LaTeX builder operates. There is a sub-part of minted which modifies fancyvrb's Verbatim to allow line-breaks, and this does not require -shell-escape but only "draft" option, but this is not available separately so far and consists of at least 300 hundred lines of code possibly using more stuff from other LaTeX packages (for key-value handling for example).

I propose this patch which is a minimal modification of fancyvrb's Verbatim: the macro \FancyVerbFormatLine is modified to wrap its arguments first in a paragraph building box. Then, linebreaks can occur at spaces (the \FV@Space is modified to allow such a line break.)

But having break-points only at spaces is not enough (in my testing of minted it did not do more than that in its modification of fancyvrb's Verbatim) Thus it is proposed to exploit the already existing Pygmentization and modify (only in the Verbatim naturally) the PYGZus, etc... macros, which end up in the document LaTeX preamble; this modification is done to insert potential break points. For some characters like the ? or the / which do not seem to be treated by pygmentization another approach is used which consists of making them "catcode active" (only in the Verbatim naturally).

This depends on new macros \Sphinxbreaksatspecials and \Sphinxbreaksatpunct which can be redefined to do nothing if the behaviour is not desired. Either from the user via something in the 'preamble' key in conf.py, or possibly via a dedicated new option.

When a line-break occurs, a continuation symbol will be displayed at start of second line. This symbol and the amount of indentation from the left margin are set in macros the user can redefine in the 'preamble'. For the space character a red visible space is printed at end of broken line. This can also be customized via certain \Sphinx... macros.

Some characters where breaks are allowed will stay on first line, others go to continuation line. See code comments.

The new Verbatim makes option obeytabs a no-op but I don't think this option was available via Sphinx (it specified to use tabs from the input as tabulation stops in the latex (pdf) output, like for example in an Emacs buffer; from looking the Sphinx docs, I got the impression no option was provided to handle tab-formatted source code, perhaps I am wrong).

The extra lines do not modify the numbering: the first of the lines is still the numbered one.

It may happen that at bottom of page, the extra lines spill over the verbatim frame (by the way, although fancyvrb has the ability to draw frames, for some reason sphinx.sty uses framed environment for that; this is not impacted). It is impossible to allow page breaks at these locations if not rewriting core parts of fancyvrb latex code. At least the material is now visible by the reader it does not disappear to the right of the printed page. Notice that the exact same issue arises when using minted with "draft" option and \fvset{breaklines=true}

The core changes in this patch are only about ten lines in sphinx.sty to allow breaks at spaces. Further changes handle the breaks at characters. Note that digits or letters will not allow linebreaks, but this could be added.

As an after effect the spacing with the top rule and bottom rule of the surrounding frame are improved.

@jfbu jfbu changed the title Codeautolinebreak v3 Allow linebreaks in latex(pdf) codeblocks Feb 19, 2016
@jnaulty

jnaulty commented Feb 26, 2016

Copy link
Copy Markdown

@jfbu
are there any special changes I have to make to test your PR? (add config to the preamble, update minted.sty, etc.)

@jnaulty

jnaulty commented Feb 26, 2016

Copy link
Copy Markdown

When I use your implementation I get a problem in domains/cpp.py

 cat /tmp/sphinx-err-wdibWx.log
 # Sphinx version: 1.4a1+
 # Python version: 2.7.6 (CPython)
 # Docutils version: 0.12 release
 # Jinja2 version: 2.8 
 # Last messages:
 #   Running Sphinx v1.4a1+
 #   loading pickled environment...
 #   done
 #   building [mo]: targets for 0 po files that are out of date
 #   building [html]: targets for 13 source files that are out of date
 #   updating environment:
 #   [config changed] 13 added, 0 changed, 0 removed
 #   reading sources... [  7%] 7850-VSG-VSA-IG-00-LOT-LOF
 # Loaded extensions:
 #   alabaster (0.7.7) from /home/smeiers/playground/venv/local/lib/python2.7/site-packages/alabaster/__init__.pyc
 #   sphinx.ext.intersphinx (1.4a1+) from /home/smeiers/playground/venv/local/lib/python2.7/site-packages/sphinx/ext/intersphinx.pyc
Traceback (most recent call last):
File "/home/smeiers/playground/venv/local/lib/python2.7/site-packages/sphinx/cmdline.py", line 244, in main
app.build(opts.force_all, filenames)
File "/home/smeiers/playground/venv/local/lib/python2.7/site-packages/sphinx/application.py", line 286, in build
self.builder.build_update()
File "/home/smeiers/playground/venv/local/lib/python2.7/site-packages/sphinx/builders/__init__.py", line 251, in build_update
'out of date' % len(to_build))
File "/home/smeiers/playground/venv/local/lib/python2.7/site-packages/sphinx/builders/__init__.py", line 265, in build
self.doctreedir, self.app))
File "/home/smeiers/playground/venv/local/lib/python2.7/site-packages/sphinx/environment.py", line 548, in update
self._read_serial(docnames, app)
File "/home/smeiers/playground/venv/local/lib/python2.7/site-packages/sphinx/environment.py", line 567, in _read_serial
self.clear_doc(docname)
File "/home/smeiers/playground/venv/local/lib/python2.7/site-packages/sphinx/environment.py", line 291, in clear_doc
domain.clear_doc(docname)
File "/home/smeiers/playground/venv/local/lib/python2.7/site-packages/sphinx/domains/cpp.py", line 3990, in clear_doc
rootSymbol = self.data['rootSymbol']
KeyError: 'rootSymbol'

@jfbu

jfbu commented Feb 26, 2016

Copy link
Copy Markdown
Contributor Author

@jnaulty no special changes. The PR does not use minted.sty at all: it patches the Verbatim environment provided by package fancyvrb, which is loaded by sphinx.sty. If you want to test it quickly and don't have a local clone of sphinx repo to which you could apply just grab the sphinx/texinputs/sphinx.sty at https://github.com/jfbu/sphinx/tree/codeautolinebreakV3 and put it in the build/latex/ repertory of a random Sphinx project, overwriting the sphinx.sty which was created by make latex. Then run pdflatex on the .tex file of the project.

@jnaulty

jnaulty commented Feb 26, 2016

Copy link
Copy Markdown

I setup a virtualenv with your repo.

@jfbu

jfbu commented Feb 26, 2016

Copy link
Copy Markdown
Contributor Author

@jnaulty I have had random errors of that type in unrelated topic branches, I did make latexpdf again and the error went away ...

@jnaulty

jnaulty commented Feb 26, 2016

Copy link
Copy Markdown

hmm, it has this error on each new build. Rerunning it solves the problem, but I don't know why. Any ideas?

@jfbu

jfbu commented Feb 26, 2016

Copy link
Copy Markdown
Contributor Author

Strange, I have not encountered persistent errors of that type. I don't see how it could be related to my patch which only modifies sphinx.sty. Can you try the patch on stable branch ?

@jnaulty

jnaulty commented Feb 26, 2016

Copy link
Copy Markdown

how do I patch stable with your changes?

@jfbu

jfbu commented Feb 26, 2016

Copy link
Copy Markdown
Contributor Author

If you have cloned my repo, git diff 1.3.5..codeautolinebreakV3 > mypatch.txt, then git checkout master (if you are not already there), git apply mypatch.txt. Make sure the Makefile in the project has
SPHINXBUILD = /path/to/cloneof/jfbu/sphinx/sphinx-build.py

@jfbu

jfbu commented Feb 26, 2016

Copy link
Copy Markdown
Contributor Author

Sorry I meant git checkout stable in previous comment.

@jnaulty

jnaulty commented Feb 26, 2016

Copy link
Copy Markdown

😄 👍
Also, I'm using a virtualenv, so I don't think I have to change the SPHINXBUILD variable in the makefile.
It seemed to work! Thanks for the assistance. I hope this get's merged into the main repo soon. It'd make my CD much easier.

@jfbu
jfbu force-pushed the codeautolinebreakV3 branch from 1ce04d0 to 8473ae9 Compare March 6, 2016 08:28
@jfbu

jfbu commented Mar 6, 2016

Copy link
Copy Markdown
Contributor Author

I have replaced the series of commits in this PR by a unique final one. This new presentation is more compact for easier reading of LaTeX code for review, and revised macro names. I try for consistency to always use \Sphinx... prefix. As LaTeX has no domain protection of macro names, this is needed to avoid potential conflicts with loaded packages.

The commit is still based on top of 1.3.5. release.

@xuhdev

xuhdev commented Mar 6, 2016

Copy link
Copy Markdown
Contributor

I found an issue, with the default settings, the following rst file fails to find the correct spot to break line:

::

   xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x 


- Good morning
  ::
     xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x 

@jfbu

jfbu commented Mar 6, 2016

Copy link
Copy Markdown
Contributor Author

good find thanks

::

   xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x 


- Good morning

  * Hello
    ::
       xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x xx x x x 

shows that clearly the problem is with informing the code about the left indent. Ok I have a fix which I am pushing now, but it is night here, I will investigate better tomorrow.

@jfbu
jfbu force-pushed the codeautolinebreakV3 branch from 35463c1 to 9124f69 Compare April 16, 2016 20:38
@jfbu

jfbu commented Apr 16, 2016

Copy link
Copy Markdown
Contributor Author

I have rebased on current stable, fixing conflicts in passing, and squashed into a single commit.

Comment thread sphinx/texinputs/sphinx.sty Outdated
% These are user customizable e.g. from latex_elements's preamble key.
% Use of \textvisiblespace for compatibility with XeTeX/LuaTeX/fontspec.
\newcommand*\Sphinxvisiblespace
{\textcolor{red}{\textvisiblespace}}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why \textcolor{red}?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, sorry. I understand what Sphinxvisiblespace means. It's OK to use \textcolor{red}.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we make this color customizable ? it is possible already for the user to use 'preamble' key to do own definition to overwrite the one from sphinx.sty.

@tk0miya

tk0miya commented Apr 25, 2016

Copy link
Copy Markdown
Member

It works fine for me.
I don't know whether this is stable code or not.
But, anyway, it is already broken with longer lines. So I think this is ready to merge :-)

@tk0miya tk0miya added this to the 1.4.2 milestone Apr 25, 2016
Also related to sphinx-doc#1534. Convert code lines into flushleft paragraphs,
thus allowing linebreaks at spaces, and use pre-existing Pygments
mark-up to also allow line breaks at (type 1) characters {, <, #, %, $,
' and " and (type 2) _, }, ^, &, >, -, ~, ., ;, :, ?, !, / and the
comma. Characters of type 1 go to next line in case of break, those of
type 2 stay on same line.

 - no new LaTeX package is used, but current use of fancyverb modified.

 - code line numbering is not affected (extra lines are not numbered.

 - spacing of top line and last line with respect of frame is improved.

 - near bottom of page the wrapping of lines longer than text width,
   which formerly continued into right margin, can produce one or more
   extra lines at bottom of page. It looks impossible without extensive
   rewrite of fancyvrb.sty or the switch to an altogether different
   LaTeX package doing source code formatting to allow page breaks
   there.
@jfbu
jfbu force-pushed the codeautolinebreakV3 branch from 9124f69 to ac7d7b5 Compare April 25, 2016 15:31
@jfbu

jfbu commented Apr 25, 2016

Copy link
Copy Markdown
Contributor Author

@tk0miya on existing Sphinx projects not having literal blocks with lines longer than text width, the impact will be that top frame is a bit higher compared to first baseline and bottom frame a bit lower compared to last baseline, because now a \strut is added to each. This will modify existing documents making them a bit longer. But we have had a number of commits to stable recently with slight such impact on vertical layout ;-).

I have rebased on current tip of stable branch and will update CHANGES.

@jfbu

jfbu commented Apr 25, 2016

Copy link
Copy Markdown
Contributor Author

I am not sure if my additions to Features added in CHANGES are of the correct type.

@jfbu
jfbu merged commit 8419147 into sphinx-doc:stable Apr 25, 2016
@jfbu
jfbu deleted the codeautolinebreakV3 branch April 25, 2016 16:14
jfbu added a commit to jfbu/sphinx that referenced this pull request Oct 28, 2016
Indeed, LaTeX's handling of package options is not robust when options
contain LaTeX macros; thus we pass all the user customization to
``\sphinxsetup``, not as package options to "sphinx.sty".

Also, make parameters for long code line breaking (ref sphinx-doc#2343, 1.4.2)
accessible as sub-keys of 'sphinxpackageoptions'. The space reserved for
the continuation character has been modified for coherence and
compatibility with use in footnotes. In fact it did not use the correct
font for the dimension computation. The documentation explains how to
recover former value.
@ghost

ghost commented Jan 6, 2017

Copy link
Copy Markdown

What would be involved in getting a similar feature enabled for the parsed-literal directive? I don't know that much about the inner workings of Sphinx, but I'm using parsed-literal in order to use substitutions (eg |apiurl|) inside my code blocks.

@tk0miya

tk0miya commented Jan 6, 2017

Copy link
Copy Markdown
Member

@spencer-rig We should investigate inside of the directive to do that or not to do.
Could you file a new issue?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants