Prevent comments from breaking paragraphs in org-mode latex export

In an org-mode document, comments like this:

Some text forming a paragraph
# with some lines
# commented out
but I still want this to be a single paragraph.

are exported in latex like this:

Some text forming a paragraph

but I still want this to be a single paragraph.

which leads to a paragraph break between the two lines. This is the intended behaviour of the exporter, but I want it to export like this:

Some text forming a paragraph
but I still want this to be a single paragraph.

This was raised on stackexchange, and the mighty John Kitchin provided a quick solution with the following simple function to strip comments from the org file, which we then add to the org export hook:

;; remove comments from org document for use with export hook
;; https://emacs.stackexchange.com/questions/22574/orgmode-export-how-to-prevent-a-new-line-for-comment-lines
(defun delete-org-comments (backend)
  (loop for comment in (reverse (org-element-map (org-element-parse-buffer)
                    'comment 'identity))
    do
    (setf (buffer-substring (org-element-property :begin comment)
                (org-element-property :end comment))
          "")))

;; add to export hook
(add-hook 'org-export-before-processing-hook 'delete-org-comments)

and then when we export an org-mode file, the comments are stripped out on-the-fly giving the desired result. The original org-mode file is not modified – the comments stay in place.

Advertisement

One comment

  1. John’s code is probably faster for large documents, but for the sake of exploring the org-element API, here’s an alternative function:

    https://emacs.stackexchange.com/a/35389/3871

    (defun delete-org-comments (backend)
    (let ((tree (org-element-parse-buffer)))
    (org-element-map tree ‘comment #’org-element-extract-element)
    (erase-buffer)
    (insert (org-element-interpret-data tree))))

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s