emacs-orgmode@gnu.org archives
 help / color / mirror / code / Atom feed
* Export to Texinfo
@ 2012-07-20  0:29 Jonathan Leech-Pepin
  2012-07-20  9:32 ` Nicolas Goaziou
  0 siblings, 1 reply; 13+ messages in thread
From: Jonathan Leech-Pepin @ 2012-07-20  0:29 UTC (permalink / raw)
  To: Org Mode Mailing List

[-- Attachment #1: Type: text/plain, Size: 3558 bytes --]

Hello all,

Over the last few days I've been working on implementing an Org ->
Texinfo exporter based on the new e-latex exporter.

It is not yet able to generate all the expected contents for export
towards an Info file, however it does create enough to successfully
export and read through Info.

Current it can do the following:
- Create the initial preamble.
- Create the menu and detailed menus in the =@top= node.
- Create the menus within each node for child menus.
- Descriptions for menus are pulled from the :DESCRIPTION: property of
  the headline.
- Convert *bold*, /italic/, ~verbatim~ and =code= markup to @strong{},
  @emph{}, @verb{} and @code{} respectively.
- Convert lisp code blocks to @lisp and other code blocks to @example.
- Create ordered and unordered lists.
- Turn descriptive lists into @table.
- Export verbatim tables to @verbatim blocks.
- Export standard tables as @multitable, using the largest cell in
  each column to define the output (outputs a string of a's equal to
  the lengths).
- Exports comments and comment blocks
- Exports Quote and example blocks, including labels for quotes.
- Footnotes are generated inline using @footnote{}.
- The copyright (@copying) section can be created by generating a
  headline with the property :copying: set to t (or any non-nil
  value).  It will be exported at the correct place in the .texi file
  and will not be duplicated in the tree.  Children of this headline
  will export within the block, so I would recommend not including any
  (it will likely result in a very odd section and errors in
  makeinfo).
- Export to .texi (org-e-texinfo-export-to-texinfo) and compile to
  info (org-e-texinfo-export-to-info).  It will not however provide an
  error buffer if it fails. That is also on the list of additions.


It will not do the following:
- Export table.el tables, they are currently being exported using the
  e-latex code, so they will cause issues with makeinfo.  I do plan to
  look at that in the future
- There is no provision for indices, limiting usefulness in
  cross-referencing.
- Additionally descriptive lists cannot be exported to @ftable or
  @vtable
- Sub and super-scripts are still being exported via latex processing.
  This likely will also fail in makeinfo.
- There is no #+attr_texinfo or #+TEXINFO: for arbitrary snippets or
  for passing features to tables/blocks.  I'm not sure exactly how to
  hook these in and would need a pointer in the right direction to do
  so.
- While looking over the reference document for the new exporter I
  realized I could likely use pre- and post- processing hooks to
  simplify some of the export process.  I have to look into this as
  well.
- The largest issue perhaps: There is no method to create @kbd{} and
  @key{} commands on export.  If anyone has any suggestions how these
  might be achieved (perhaps looking for a prefix in =code=?) I would
  greatly appreciate it.

There are a few limitations to what will successfully be exported:
- Headlines cannot contain any of the following symbols: periods,
  commas, colons or parentheses.  This is a limitation of texinfo and
  will result in errors when running makeinfo.  Semi-colons will
  export however.
- Headlines cannot contain markup or links.  Once again these are
  forbidden in texinfo and will cause failures.
- I've currently only been looking at creating valid info output,
  output to PDF or HTML via makeinfo may fail.

It can also be found at
https://github.com/jleechpe/org-mode/blob/texinfo/contrib/lisp/org-e-texinfo.el

Regards,

Jon

[-- Attachment #2: org-e-texinfo.el --]
[-- Type: application/octet-stream, Size: 61103 bytes --]

;;; org-e-texinfo.el --- Texinfo Back-End For Org Export Engine

;; Author: Jonathan Leech-Pepin <jonathan.leechpepin at gmail dot com
;; Keywords: outlines, hypermedia, calendar, wp

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:
;;
;; This library implements a Texinfo back-end for Org generic exporter.
;;
;; To test it, run
;;
;;   M-: (org-export-to-buffer 'e-texinfo "*Test e-texinfo*") RET
;;
;; in an org-mode buffer then switch to the buffer to see the Texinfo
;; export.  See contrib/lisp/org-export.el for more details on how
;; this exporter works.
;;
;; It introduces five new buffer keywords: "TEXINFO_CLASS",
;; "TEXINFO_FILENAME", "TEXINFO_HEADER", "SUBTITLE" and "SUBAUTHOR".

;;; Code:

(eval-when-compile (require 'cl))
(require 'org-export)

(defvar orgtbl-exp-regexp)

\f
;;; Define Back-End

(defvar org-e-texinfo-translate-alist
  '((babel-call . org-e-texinfo-babel-call)
    (bold . org-e-texinfo-bold)
    (center-block . org-e-texinfo-center-block)
    (clock . org-e-texinfo-clock)
    (code . org-e-texinfo-code)
    (comment . org-e-texinfo-comment)
    (comment-block . org-e-texinfo-comment-block)
    (drawer . org-e-texinfo-drawer)
    (dynamic-block . org-e-texinfo-dynamic-block)
    (entity . org-e-texinfo-entity)
    (example-block . org-e-texinfo-example-block)
    (export-block . org-e-texinfo-export-block)
    (export-snippet . org-e-texinfo-export-snippet)
    (fixed-width . org-e-texinfo-fixed-width)
    (footnote-definition . org-e-texinfo-footnote-definition)
    (footnote-reference . org-e-texinfo-footnote-reference)
    (headline . org-e-texinfo-headline)
    (horizontal-rule . org-e-texinfo-horizontal-rule)
    (inline-babel-call . org-e-texinfo-inline-babel-call)
    (inline-src-block . org-e-texinfo-inline-src-block)
    (inlinetask . org-e-texinfo-inlinetask)
    (italic . org-e-texinfo-italic)
    (item . org-e-texinfo-item)
    (keyword . org-e-texinfo-keyword)
    (latex-environment . org-e-texinfo-latex-environment)
    (latex-fragment . org-e-texinfo-latex-fragment)
    (line-break . org-e-texinfo-line-break)
    (link . org-e-texinfo-link)
    (macro . org-e-texinfo-macro)
    (paragraph . org-e-texinfo-paragraph)
    (plain-list . org-e-texinfo-plain-list)
    (plain-text . org-e-texinfo-plain-text)
    (planning . org-e-texinfo-planning)
    (property-drawer . org-e-texinfo-property-drawer)
    (quote-block . org-e-texinfo-quote-block)
    (quote-section . org-e-texinfo-quote-section)
    (radio-target . org-e-texinfo-radio-target)
    (section . org-e-texinfo-section)
    (special-block . org-e-texinfo-special-block)
    (src-block . org-e-texinfo-src-block)
    (statistics-cookie . org-e-texinfo-statistics-cookie)
    (strike-through . org-e-texinfo-strike-through)
    (subscript . org-e-texinfo-subscript)
    (superscript . org-e-texinfo-superscript)
    (table . org-e-texinfo-table)
    (table-cell . org-e-texinfo-table-cell)
    (table-row . org-e-texinfo-table-row)
    (target . org-e-texinfo-target)
    (template . org-e-texinfo-template)
    (timestamp . org-e-texinfo-timestamp)
    (underline . org-e-texinfo-underline)
    (verbatim . org-e-texinfo-verbatim)
    (verse-block . org-e-texinfo-verse-block))
  "Alist between element or object types and translators.")

(defconst org-e-texinfo-options-alist
  '((:texinfo-filename "TEXINFO_FILENAME" nil org-e-texinfo-filename t)
    (:texinfo-class "TEXINFO_CLASS" nil org-e-texinfo-default-class t)
    (:texinfo-header "TEXINFO_HEADER" nil nil newline)
    (:subtitle "SUBTITLE" nil nil newline)
    (:subauthor "SUBAUTHOR" nil nil newline))
  "Alist between Texinfo export properties and ways to set them.
See `org-export-options-alist' for more information on the
structure of the values.

SUBAUTHOR and SUBTITLE are for the inclusion of additional author
and title information beyond the initial variable.")


\f
;;; Internal Variables

\f
;;; User Configurable Variables

(defgroup org-export-e-texinfo nil
  "Options for exporting Org mode files to Texinfo."
  :tag "Org Export Texinfo"
  :group 'org-export)


;;;; Preamble

(defcustom org-e-texinfo-filename nil
  "Default filename for texinfo output."
  :group 'org-export-e-texinfo
  :type '(string :tag "Export Filename"))

(defcustom org-e-texinfo-default-class "info"
  "The default Texinfo class."
  :group 'org-export-e-texinfo
  :type '(string :tag "Texinfo class"))

(defcustom org-e-texinfo-classes
  '(("info"
     "\\input texinfo    @c -*- texinfo -*-"
     ("@chapter %s" . "@unnumbered %s")
     ("@section %s" . "@unnumberedsec %s")
     ("@subsection %s" . "@unnumberedsubsec %s")
     ("@subsubsection %s" . "@unnumberedsubsubsec %s")))
  "Alist of Texinfo classes and associated header and structure.
If #+Texinfo_CLASS is set in the buffer, use its value and the
associated information.  Here is the structure of each cell:

  \(class-name
    header-string
    \(numbered-section . unnumbered-section\)
    ...\)

The sectioning structure
------------------------

The sectioning structure of the class is given by the elements
following the header string.  For each sectioning level, a number
of strings is specified.  A %s formatter is mandatory in each
section string and will be replaced by the title of the section.

Instead of a cons cell \(numbered . unnumbered\), you can also
provide a list of 2 or 4 elements,

  \(numbered-open numbered-close\)

or

  \(numbered-open numbered-close unnumbered-open unnumbered-close\)

providing opening and closing strings for a Texinfo environment
that should represent the document section.  The opening clause
should have a %s to represent the section title.

Instead of a list of sectioning commands, you can also specify
a function name.  That function will be called with two
parameters, the \(reduced) level of the headline, and a predicate
non-nil when the headline should be numbered.  It must return
a format string in which the section title will be added."
  :group 'org-export-e-texinfo
  :type '(repeat
	  (list (string :tag "Texinfo class")
		(string :tag "Texinfo header")
		(repeat :tag "Levels" :inline t
			(choice
			 (cons :tag "Heading"
			       (string :tag "  numbered")
			       (string :tag "unnumbered"))
			 (list :tag "Environment"
			       (string :tag "Opening   (numbered)")
			       (string :tag "Closing   (numbered)")
			       (string :tag "Opening (unnumbered)")
			       (string :tag "Closing (unnumbered)"))
			 (function :tag "Hook computing sectioning"))))))


;;;; Headline

(defcustom org-e-texinfo-format-headline-function nil
  "Function to format headline text.

This function will be called with 5 arguments:
TODO      the todo keyword (string or nil).
TODO-TYPE the type of todo (symbol: `todo', `done', nil)
PRIORITY  the priority of the headline (integer or nil)
TEXT      the main headline text (string).
TAGS      the tags as a list of strings (list of strings or nil).

The function result will be used in the section format string.

As an example, one could set the variable to the following, in
order to reproduce the default set-up:

\(defun org-e-texinfo-format-headline (todo todo-type priority text tags)
  \"Default format function for an headline.\"
  \(concat (when todo
            \(format \"\\\\textbf{\\\\textsc{\\\\textsf{%s}}} \" todo))
	  \(when priority
            \(format \"\\\\framebox{\\\\#%c} \" priority))
	  text
	  \(when tags
            \(format \"\\\\hfill{}\\\\textsc{%s}\"
              \(mapconcat 'identity tags \":\"))))"
  :group 'org-export-e-texinfo
  :type 'function)


;;;; Footnotes
;;
;; Footnotes are inserted directly

;;;; Timestamps

(defcustom org-e-texinfo-active-timestamp-format "@emph{%s}"
  "A printf format string to be applied to active timestamps."
  :group 'org-export-e-texinfo
  :type 'string)

(defcustom org-e-texinfo-inactive-timestamp-format "@emph{%s}"
  "A printf format string to be applied to inactive timestamps."
  :group 'org-export-e-texinfo
  :type 'string)

(defcustom org-e-texinfo-diary-timestamp-format "@emph{%s}"
  "A printf format string to be applied to diary timestamps."
  :group 'org-export-e-texinfo
  :type 'string)

;;;; Links

(defcustom org-e-texinfo-link-with-unknown-path-format "@indicateurl{%s}"
  "Format string for links with unknown path type."
  :group 'org-export-e-texinfo
  :type 'string)


;;;; Tables

(defcustom org-e-texinfo-tables-verbatim nil
  "When non-nil, tables are exported verbatim."
  :group 'org-export-e-texinfo
  :type 'boolean)

(defcustom org-e-texinfo-table-scientific-notation "%s\\,(%s)"
  "Format string to display numbers in scientific notation.
The format should have \"%s\" twice, for mantissa and exponent
\(i.e. \"%s\\\\times10^{%s}\").

When nil, no transformation is made."
  :group 'org-export-e-texinfo
  :type '(choice
	  (string :tag "Format string")
	  (const :tag "No formatting")))

(defcustom org-e-texinfo-def-table-markup "@samp"
  "Default setting for @table environments.")

;;;; Text markup

(defcustom org-e-texinfo-text-markup-alist '((bold . "@strong{%s}")
					   (code . code)
					   (italic . "@emph{%s}")
					   (verbatim . verb)
					   (comment . "@c %s"))
  "Alist of Texinfo expressions to convert text markup.

The key must be a symbol among `bold', `code', `italic',
`strike-through', `underline' and `verbatim'.  The value is
a formatting string to wrap fontified text with.

Value can also be set to the following symbols: `verb' and
`protectedtexttt'.  For the former, Org will use \"\\verb\" to
create a format string and select a delimiter character that
isn't in the string.  For the latter, Org will use \"\\texttt\"
to typeset and try to protect special characters.

If no association can be found for a given markup, text will be
returned as-is."
  :group 'org-export-e-texinfo
  :type 'alist
  :options '(bold code italic verbatim comment))


;;;; Drawers

(defcustom org-e-texinfo-format-drawer-function nil
  "Function called to format a drawer in Texinfo code.

The function must accept two parameters:
  NAME      the drawer name, like \"LOGBOOK\"
  CONTENTS  the contents of the drawer.

The function should return the string to be exported.

For example, the variable could be set to the following function
in order to mimic default behaviour:

\(defun org-e-texinfo-format-drawer-default \(name contents\)
  \"Format a drawer element for Texinfo export.\"
  contents\)"
  :group 'org-export-e-texinfo
  :type 'function)


;;;; Inlinetasks

(defcustom org-e-texinfo-format-inlinetask-function nil
  "Function called to format an inlinetask in Texinfo code.

The function must accept six parameters:
  TODO      the todo keyword, as a string
  TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
  PRIORITY  the inlinetask priority, as a string
  NAME      the inlinetask name, as a string.
  TAGS      the inlinetask tags, as a list of strings.
  CONTENTS  the contents of the inlinetask, as a string.

The function should return the string to be exported.

For example, the variable could be set to the following function
in order to mimic default behaviour:

\(defun org-e-texinfo-format-inlinetask \(todo type priority name tags contents\)
\"Format an inline task element for Texinfo export.\"
  \(let ((full-title
	 \(concat
	  \(when todo
            \(format \"\\\\textbf{\\\\textsf{\\\\textsc{%s}}} \" todo))
	  \(when priority (format \"\\\\framebox{\\\\#%c} \" priority))
	  title
	  \(when tags
            \(format \"\\\\hfill{}\\\\textsc{:%s:}\"
                    \(mapconcat 'identity tags \":\")))))
    \(format (concat \"\\\\begin{center}\\n\"
		    \"\\\\fbox{\\n\"
		    \"\\\\begin{minipage}[c]{.6\\\\textwidth}\\n\"
		    \"%s\\n\\n\"
		    \"\\\\rule[.8em]{\\\\textwidth}{2pt}\\n\\n\"
		    \"%s\"
		    \"\\\\end{minipage}}\"
		    \"\\\\end{center}\")
	    full-title contents))"
  :group 'org-export-e-texinfo
  :type 'function)


;;;; Src blocks
;;
;; Src Blocks are example blocks, except for LISP

;;;; Plain text

(defcustom org-e-texinfo-quotes
  '(("quotes"
     ("\\(\\s-\\|[[(]\\|^\\)\"" . "``")
     ("\\(\\S-\\)\"" . "''")
     ("\\(\\s-\\|(\\|^\\)'" . "`")))
  "Alist for quotes to use when converting english double-quotes.

The CAR of each item in this alist is the language code.
The CDR of each item in this alist is a list of three CONS:
- the first CONS defines the opening quote;
- the second CONS defines the closing quote;
- the last CONS defines single quotes.

For each item in a CONS, the first string is a regexp
for allowed characters before/after the quote, the second
string defines the replacement string for this quote."
  :group 'org-export-e-texinfo
  :type '(list
	  (cons :tag "Opening quote"
		(string :tag "Regexp for char before")
		(string :tag "Replacement quote     "))
	  (cons :tag "Closing quote"
		(string :tag "Regexp for char after ")
		(string :tag "Replacement quote     "))
	  (cons :tag "Single quote"
		(string :tag "Regexp for char before")
		(string :tag "Replacement quote     "))))


;;;; Compilation

(defcustom org-e-texinfo-info-process
  '("makeinfo %f")
  "Commands to process a texinfo file to an INFO file.
This is list of strings, each of them will be given to the shell
as a command.  %f in the command will be replaced by the full
file name, %b by the file base name \(i.e without extension) and
%o by the base directory of the file."
  :group 'org-export-texinfo
  :type '(repeat :tag "Shell command sequence"
		 (string :tag "Shell command")))

\f
;;; Internal Functions

(defun org-e-texinfo--find-copying (info)
  ""
  (let (copying)
    (org-element-map (plist-get info :parse-tree) 'headline
		     (lambda (ref)
		       (when (org-element-property :copying ref)
			 (push ref copying))) info 't)
    ;; Retrieve the single entry
    (car copying)))

(defun org-e-texinfo--find-verb-separator (s)
  "Return a character not used in string S.
This is used to choose a separator for constructs like \\verb."
  (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
    (loop for c across ll
	  when (not (string-match (regexp-quote (char-to-string c)) s))
	  return (char-to-string c))))

(defun org-e-texinfo--make-option-string (options)
  "Return a comma separated string of keywords and values.
OPTIONS is an alist where the key is the options keyword as
a string, and the value a list containing the keyword value, or
nil."
  (mapconcat (lambda (pair)
	       (concat (first pair)
		       (when (> (length (second pair)) 0)
			 (concat "=" (second pair)))))
	     options
	     ","))

(defun org-e-texinfo--quotation-marks (text info)
  "Export quotation marks using ` and ' as the markers.
TEXT is a string containing quotation marks to be replaced.  INFO
is a plist used as a communication channel."
  (mapc (lambda(l)
	  (let ((start 0))
	    (while (setq start (string-match (car l) text start))
	      (let ((new-quote (concat (match-string 1 text) (cdr l))))
		(setq text (replace-match new-quote  t t text))))))
	(cdr org-e-texinfo-quotes))
  text)

(defun org-e-texinfo--text-markup (text markup)
  "Format TEXT depending on MARKUP text markup.
See `org-e-texinfo-text-markup-alist' for details."
  (let ((fmt (cdr (assq markup org-e-texinfo-text-markup-alist))))
    (cond
     ;; No format string: Return raw text.
     ((not fmt) text)
     ((eq 'verb fmt)
      (let ((separator (org-e-texinfo--find-verb-separator text)))
	(concat "@verb{" separator text separator "}")))
     ((eq 'code fmt)
      (let ((start 0)
	    (rtn "")
	    char)
	(while (string-match "[@{}]" text)
	  (setq char (match-string 0 text))
	  (if (> (match-beginning 0) 0)
	      (setq rtn (concat rtn (substring text 0 (match-beginning 0)))))
	  (setq text (substring text (1+ (match-beginning 0))))
	  (setq char (concat "@" char)
		rtn (concat rtn char)))
	(setq text (concat rtn text)
	      fmt "@code{%s}")
	(format fmt text)))
     ;; Else use format string.
     (t (format fmt text)))))

;;;; Menu creation

(defun org-e-texinfo--build-menu (tree level info &optional detailed)
  ""
  (let ((menu (org-e-texinfo--generate-menu-list tree level info)))
    (cond
     (detailed
      ;; Looping is done separately
      (setq text-menu (org-e-texinfo--generate-detailed menu level info)))
     (t
      (setq text-menu (org-e-texinfo--generate-menu-items menu info))))
    (when text-menu
      (setq output (org-e-texinfo--format-menu text-menu))
      (mapconcat 'identity output "\n"))))

(defun org-e-texinfo--generate-detailed (menu level info)
  ""
  ;; Export class definition has 2 descriptive lines, this omits them
  ;; then calculates how many levels of headlines are used for TOC/Menu.
  (setq max-depth (plist-get info :headline-levels))
  (when (> max-depth level)
    (loop for headline in menu append
	  (let* ((title (org-e-texinfo--menu-headlines headline info))
		 (sublist (org-e-texinfo--generate-menu-list
			   headline (1+ level) info))
		 (submenu (if (org-e-texinfo--generate-menu-items sublist info)
			      (append (list title)
				      (org-e-texinfo--generate-menu-items sublist info))
			    'nil))
		 ;; Recursion
		 (recursion (org-e-texinfo--generate-detailed sublist (1+ level) info))
		 )
	    (setq recursion (append submenu recursion))
	    recursion))))

(defun org-e-texinfo--generate-menu-list (tree level info)
  "Generate the list of headlines that are within a given level
of the tree for further formatting.

TREE is the parse-tree containing the headlines.  LEVEL is the
headline level to generate a list of.  INFO is a plist holding
contextual information."
  (let (seq)
    (org-element-map
     tree 'headline
     (lambda (ref)
       (when (org-element-property :level ref)
	 (if (and (eq level (org-element-property :level ref))
		  ;; Do not take note of footnotes or copying headlines
		  (not (org-element-property :copying ref))
		  (not (org-element-property :footnote-section-p ref)))
	     (push ref seq)))))
    ;; Return the list of headlines (reverse to have in actual order)
    (reverse seq)))

(defun org-e-texinfo--generate-menu-items (menu info)
  ""
  
  (loop for headline in menu collect
	(let* ((title (org-export-data
		       (org-element-property :title headline) info))
	       (descr (org-export-data
		       (org-element-property :description headline) info))
	       (len (length title))
	       (output (list len title descr)))
	  output)))

(defun org-e-texinfo--menu-headlines (menu info)
  ""
  (setq title (org-export-data
               (org-element-property :title headline) info))
  (list 0 title 'nil))

(defun org-e-texinfo--format-menu (text-menu)
  ""
  ;; Format should be a list of menu entries
  ;; (length title description).  For headlines they should be
  ;; (nil title nil).  This permits proper spacing settings
  (let* ((lengths (mapcar 'car text-menu))
         (max-length (apply 'max lengths)))
    (setq output
          (mapcar (lambda (name)
                    (let* ((title (nth 1 name))
                           (desc (nth 2 name))
                           (length (nth 0 name)))
                      (if (> length 0)
                          (concat "* " title ":: "
                                  (make-string (- (+ 3 max-length) length)
                                               ?\s)
                                  (if desc
                                      (concat desc)))
                        (concat "\n" title "\n"))))
		  text-menu))
    output))



;;; Template

(defun org-e-texinfo-template (contents info)
  "Return complete document string after Texinfo conversion.
CONTENTS is the transcoded contents string.  INFO is a plist
holding export options."
  (let* ((title (org-export-data (plist-get info :title) info))
	 (info-filename (or (plist-get info :texinfo-filename)
			    (file-name-nondirectory
			     (org-export-output-file-name ".info"))))
	 (author (org-export-data (plist-get info :author) info))
	 (texinfo-header (plist-get info :texinfo-header))
	 (subtitle (plist-get info :subtitle))
	 (subauthor (plist-get info :subauthor))
	 (class (plist-get info :texinfo-class))
	 (header (nth 1 (assoc class org-e-texinfo-classes)))
	 (copying (org-e-texinfo--find-copying info)))
    (concat
     ;; Header
     header "\n"
     "@c %**start of header\n"
     ;; Filename and Title
     "@setfilename " info-filename "\n"
     "@settitle " title "\n"
     "\n\n"
     "@c Version and Contact Info\n"
     "@set AUTHOR " author "\n"

     ;; Additional Header Options set by `#+TEXINFO_HEADER
     (if texinfo-header
	 (concat "\n"
		 texinfo-header
		 "\n"))
     
     "@c %**end of header\n"
     "@finalout\n"
     "\n\n"

     ;; Copying
     "@copying\n"
     ;; Only export the content of the headline, do not need the
     ;; initial headline.
     (org-export-data (nth 2 copying) info)
     "@end copying\n"
     "\n\n"

     ;; Title
     "@titlepage\n"
     "@title " title "\n\n"
     (if subtitle
	 (concat "@subtitle " subtitle "\n"))
     "@author " author "\n"
     (if subauthor
	 (concat subauthor "\n"))
     "\n"
     "@c The following two commands start the copyright page.\n"
     "@page\n"
     "@vskip 0pt plus 1filll\n"
     "@insertcopying\n"
     "@end titlepage\n\n"
     "@c Output the table of contents at the beginning.\n"
     "@contents\n\n"

     ;; Configure Top Node when not for Tex
     "@ifnottex\n"
     "@node Top\n"
     "@top " title " Manual\n"
     "@insertcopying\n"
     "@end ifnottex\n\n"
     
     ;; Menu
     "@menu\n"
     (org-e-texinfo-make-menu info 'main)
     "\n\n"
     ;; Detailed Menu
     "@detailmenu\n"
     " --- The Detailed Node Listing ---\n"
     (org-e-texinfo-make-menu info 'detailed)
     "\n\n"
     "@end detailmenu\n"
     "@end menu\n"
     "\n\n"
     
     ;; Document's body.
     contents
     "\n"
     ;; Creator.
     (let ((creator-info (plist-get info :with-creator)))
       (cond
	((not creator-info) "")
	((eq creator-info 'comment)
	 (format "@c %s\n" (plist-get info :creator)))
	(t (concat (plist-get info :creator) "\n"))))
     ;; Document end.
     "\n@bye")))


\f
;;; Transcode Functions

;;;; Babel Call
;;
;; Babel Calls are ignored.


;;;; Bold

(defun org-e-texinfo-bold (bold contents info)
  "Transcode BOLD from Org to Texinfo.
CONTENTS is the text with bold markup.  INFO is a plist holding
contextual information."
  (org-e-texinfo--text-markup contents 'bold))


;;;; Center Block
;;
;; Center blocks are ignored


;;;; Clock

(defun org-e-texinfo-clock (clock contents info)
  "Transcode a CLOCK element from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual
information."
  (concat
   "@noindent"
   (format "@strong{%s} " org-clock-string)
   (format org-e-texinfo-inactive-timestamp-format
	   (concat (org-translate-time (org-element-property :value clock))
		   (let ((time (org-element-property :time clock)))
		     (and time (format " (%s)" time)))))
   "@*"))


;;;; Code

(defun org-e-texinfo-code (code contents info)
  "Transcode a CODE object from Org to Texinfo.
CONTENTS is nil.  INFO is a plist used as a communication
channel."
  (org-e-texinfo--text-markup (org-element-property :value code) 'code))

;;;; Comment

(defun org-e-texinfo-comment (comment contents info)
  "Transcode a COMMENT object from Org to Texinfo.
CONTENTS is the text in the comment.  INFO is a plist holding
contextual information."
  (org-e-texinfo--text-markup (org-element-property :value comment) 'comment))

;;;; Comment Block

(defun org-e-texinfo-comment-block (comment-block contents info)
  "Transcode a COMMENT-BLOCK object from Org to Texinfo.
CONTENTS is the text within the block.  INFO is a plist holding
contextual information."
  (format "@ignore\n%s@end ignore" (org-element-property :value comment-block)))

;;;; Drawer

(defun org-e-texinfo-drawer (drawer contents info)
  "Transcode a DRAWER element from Org to Texinfo.
CONTENTS holds the contents of the block.  INFO is a plist
holding contextual information."
  (let* ((name (org-element-property :drawer-name drawer))
	 (output (if (functionp org-e-texinfo-format-drawer-function)
		     (funcall org-e-texinfo-format-drawer-function
			      name contents)
		   ;; If there's no user defined function: simply
		   ;; display contents of the drawer.
		   contents)))
    output))


;;;; Dynamic Block

(defun org-e-texinfo-dynamic-block (dynamic-block contents info)
  "Transcode a DYNAMIC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block.  INFO is a plist
holding contextual information.  See `org-export-data'."
  contents)


;;;; Entity

(defun org-e-texinfo-entity (entity contents info)
  "Transcode an ENTITY object from Org to Texinfo.
CONTENTS are the definition itself.  INFO is a plist holding
contextual information."
  (let ((ent (org-element-property :latex entity)))
    (if (org-element-property :latex-math-p entity) (format "@math{%s}" ent) ent)))


;;;; Example Block

(defun org-e-texinfo-example-block (example-block contents info)
  "Transcode an EXAMPLE-BLOCK element from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual
information."
  (format "@verbatim\n%s@end verbatim"
	  (org-export-format-code-default example-block info)))


;;;; Export Block

(defun org-e-texinfo-export-block (export-block contents info)
  "Transcode a EXPORT-BLOCK element from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual information."
  (when (string= (org-element-property :type export-block) "LATEX")
    (org-remove-indentation (org-element-property :value export-block))))


;;;; Export Snippet

(defun org-e-texinfo-export-snippet (export-snippet contents info)
  "Transcode a EXPORT-SNIPPET object from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual information."
  (when (eq (org-export-snippet-backend export-snippet) 'e-texinfo)
    (org-element-property :value export-snippet)))


;;;; Fixed Width

(defun org-e-texinfo-fixed-width (fixed-width contents info)
  "Transcode a FIXED-WIDTH element from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual information."
  (format "@example\n%s\n@end example"
	  (org-remove-indentation
	   (org-element-property :value fixed-width))))


;;;; Footnote Definition
;;
;; Footnote Definitions are ignored.


;;;; Footnote Reference
;;

(defun org-e-texinfo-footnote-reference (footnote contents info)
  ""
  (let ((def (org-export-get-footnote-definition footnote info)))
    (format "@footnote{%s}"
	    (org-trim (org-export-data def info)))))

;;;; Headline

(defun org-e-texinfo-headline (headline contents info)
  "Transcode an HEADLINE element from Org to Texinfo.
CONTENTS holds the contents of the headline.  INFO is a plist
holding contextual information."
  (let* ((class (plist-get info :texinfo-class))
	 (level (org-export-get-relative-level headline info))
	 (numberedp (org-export-numbered-headline-p headline info))
	 (class-sectionning (assoc class org-e-texinfo-classes))
	 ;; Create node info, to insert it before section formatting.
	 (node (format "@node %s\n"
		       (org-export-data (org-element-property :title headline) info)))
	 ;; Menus must be generated with first child, otherwise they
	 ;; will not nest properly
	 (menu (let* ((first (org-export-first-sibling-p headline))
		      (parent (org-export-get-parent-headline headline))
		      (title (org-export-data (org-element-property :title parent) info))
		      heading
		      (tree (plist-get info :parse-tree)))
		 (if first
		     (org-element-map
		      (plist-get info :parse-tree) 'headline
		      (lambda (ref)
			(if (member title (org-element-property :title ref))
			    (push ref heading)))
		      info 't))
		 (setq listing (org-e-texinfo--build-menu (car heading) level info))
	 	 (if listing
	 	     (setq listing (format "\n@menu\n%s\n@end menu\n\n" listing))
	 	   'nil)
		 ))
	 ;; Section formatting will set two placeholders: one for the
	 ;; title and the other for the contents.
	 (section-fmt
	  (let ((sec (if (and (symbolp (nth 2 class-sectionning))
			      (fboundp (nth 2 class-sectionning)))
			 (funcall (nth 2 class-sectionning) level numberedp)
		       (nth (1+ level) class-sectionning))))
	    (cond
	     ;; No section available for that LEVEL.
	     ((not sec) nil)
	     ;; Section format directly returned by a function.
	     ((stringp sec) sec)
	     ;; (numbered-section . unnumbered-section)
	     ((not (consp (cdr sec)))
	      (concat menu node (funcall (if numberedp #'car #'cdr) sec) "\n%s"))
	     ;; (numbered-open numbered-close)
	     ((= (length sec) 2)
	      (when numberedp (concat menu node (car sec) "\n%s" (nth 1 sec))))
	     ;; (num-in num-out no-num-in no-num-out)
	     ((= (length sec) 4)
	      (if numberedp (concat (car sec) "\n%s" (nth 1 sec))
		(concat menu node (nth 2 sec) "\n%s" (nth 3 sec)))))))
	 (text (org-export-data (org-element-property :title headline) info))
	 (todo
	  (and (plist-get info :with-todo-keywords)
	       (let ((todo (org-element-property :todo-keyword headline)))
		 (and todo (org-export-data todo info)))))
	 (todo-type (and todo (org-element-property :todo-type headline)))
	 (tags (and (plist-get info :with-tags)
		    (org-export-get-tags headline info)))
	 (priority (and (plist-get info :with-priority)
			(org-element-property :priority headline)))
	 ;; Create the headline text along with a no-tag version.  The
	 ;; latter is required to remove tags from table of contents.
	 (full-text (if (functionp org-e-texinfo-format-headline-function)
			;; User-defined formatting function.
			(funcall org-e-texinfo-format-headline-function
				 todo todo-type priority text tags)
		      ;; Default formatting.
		      (concat
		       (when todo
			 (format "@strong{%s} " todo))
		       (when priority (format "@emph{#%s} " priority))
		       text
		       (when tags
			 (format ":%s:"
				 (mapconcat 'identity tags ":"))))))
	 (full-text-no-tag
	  (if (functionp org-e-texinfo-format-headline-function)
	      ;; User-defined formatting function.
	      (funcall org-e-texinfo-format-headline-function
		       todo todo-type priority text nil)
	    ;; Default formatting.
	    (concat
	     (when todo (format "@strong{%s} " todo))
	     (when priority (format "@emph{#%c} " priority))
	     text)))
	 (pre-blanks
	  (make-string (org-element-property :pre-blank headline) 10))
	 )
    (cond
     ;; Case 1: This is a footnote section: ignore it.
     ((org-element-property :footnote-section-p headline) nil)
     ;; Case 2: This is the `copying' section: ignore it
     ;;         This is used elsewhere.
     ((org-element-property :copying headline) nil)
     ;; Case 3: This is a deep sub-tree: export it as a list item.
     ;;         Also export as items headlines for which no section
     ;;         format has been found.
     ((or (not section-fmt) (org-export-low-level-p headline info))
      ;; Build the real contents of the sub-tree.
      (let ((low-level-body
	     (concat
	      ;; If the headline is the first sibling, start a list.
	      (when (org-export-first-sibling-p headline)
		(format "@%s\n" (if numberedp 'enumerate 'itemize)))
	      ;; Itemize headline
	      "@item\n" full-text "\n" pre-blanks contents)))
	;; If headline is not the last sibling simply return
	;; LOW-LEVEL-BODY.  Otherwise, also close the list, before any
	;; blank line.
	(if (not (org-export-last-sibling-p headline)) low-level-body
	  (replace-regexp-in-string
	   "[ \t\n]*\\'"
	   (format "\n@end %s" (if numberedp 'enumerate 'itemize))
	   low-level-body))))
     ;; Case 4: Standard headline.  Export it as a section.
     (t
      (cond
       ((not (and tags (eq (plist-get info :with-tags) 'not-in-toc)))
	;; Regular section.  Use specified format string.
	(format (replace-regexp-in-string "%]" "%%]" section-fmt) full-text
		(concat pre-blanks contents "\n")))
       ((string-match "\\`@\\(.*?\\){" section-fmt)
	;; If tags should be removed from table of contents, insert
	;; title without tags as an alternative heading in sectioning
	;; command.
	(format (replace-match (concat (match-string 1 section-fmt) "[%s]")
			       nil nil section-fmt 1)
		;; Replace square brackets with parenthesis since
		;; square brackets are not supported in optional
		;; arguments.
		(replace-regexp-in-string
		 "\\[" "("
		 (replace-regexp-in-string
		  "\\]" ")"
		  full-text-no-tag))
		full-text
		(concat pre-blanks contents "\n")))
       (t
	;; Impossible to add an alternative heading.  Fallback to
	;; regular sectioning format string.
	(format (replace-regexp-in-string "%]" "%%]" section-fmt) full-text
		(concat pre-blanks contents "\n"))))))))


;;;; Horizontal Rule
;;
;; Horizontal rules are ignored

;;;; Inline Babel Call
;;
;; Inline Babel Calls are ignored.


;;;; Inline Src Block

(defun org-e-texinfo-inline-src-block (inline-src-block contents info)
  "Transcode an INLINE-SRC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the item.  INFO is a plist holding
contextual information."
  (let* ((code (org-element-property :value inline-src-block))
	 (separator (org-e-texinfo--find-verb-separator code)))
    (cond
     ;; Do not use a special package: transcode it verbatim.
     ((not org-e-texinfo-listings)
      (concat "\\verb" separator code separator))
     ;; Use minted package.
     ((eq org-e-texinfo-listings 'minted)
      (let* ((org-lang (org-element-property :language inline-src-block))
	     (mint-lang (or (cadr (assq (intern org-lang)
					org-e-texinfo-minted-langs))
			    org-lang))
	     (options (org-e-texinfo--make-option-string
		       org-e-texinfo-minted-options)))
	(concat (format "\\mint%s{%s}"
			(if (string= options "") "" (format "[%s]" options))
			mint-lang)
		separator code separator)))
     ;; Use listings package.
     (t
      ;; Maybe translate language's name.
      (let* ((org-lang (org-element-property :language inline-src-block))
	     (lst-lang (or (cadr (assq (intern org-lang)
				       org-e-texinfo-listings-langs))
			   org-lang))
	     (options (org-e-texinfo--make-option-string
		       (append org-e-texinfo-listings-options
			       `(("language" ,lst-lang))))))
	(concat (format "\\lstinline[%s]" options)
		separator code separator))))))


;;;; Inlinetask

(defun org-e-texinfo-inlinetask (inlinetask contents info)
  "Transcode an INLINETASK element from Org to Texinfo.
CONTENTS holds the contents of the block.  INFO is a plist
holding contextual information."
  (let ((title (org-export-data (org-element-property :title inlinetask) info))
	(todo (and (plist-get info :with-todo-keywords)
		   (let ((todo (org-element-property :todo-keyword inlinetask)))
		     (and todo (org-export-data todo info)))))
	(todo-type (org-element-property :todo-type inlinetask))
	(tags (and (plist-get info :with-tags)
		   (org-export-get-tags inlinetask info)))
	(priority (and (plist-get info :with-priority)
		       (org-element-property :priority inlinetask))))
    ;; If `org-e-texinfo-format-inlinetask-function' is provided, call it
    ;; with appropriate arguments.
    (if (functionp org-e-texinfo-format-inlinetask-function)
	(funcall org-e-texinfo-format-inlinetask-function
		 todo todo-type priority title tags contents)
      ;; Otherwise, use a default template.
      (let ((full-title
	     (concat
	      (when todo (format "@strong{%s} " todo))
	      (when priority (format "%c " priority))
	      title
	      (when tags (format ":%s:"
				 (mapconcat 'identity tags ":"))))))
	(format (concat "@center %s\n\n"
			"%s"
			"\n")
		full-title contents)))))


;;;; Italic

(defun org-e-texinfo-italic (italic contents info)
  "Transcode ITALIC from Org to Texinfo.
CONTENTS is the text with italic markup.  INFO is a plist holding
contextual information."
  (org-e-texinfo--text-markup contents 'italic))

;;;; Item

(defun org-e-texinfo-item (item contents info)
  "Transcode an ITEM element from Org to Texinfo.
CONTENTS holds the contents of the item.  INFO is a plist holding
contextual information."
  (concat "\n@item\n"
	    (org-trim contents) "\n"))


;;;; Keyword

(defun org-e-texinfo-keyword (keyword contents info)
  "Transcode a KEYWORD element from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual information."
  (let ((key (org-element-property :key keyword))
	(value (org-element-property :value keyword)))
    (cond
     ((string= key "LATEX") value)
     ((string= key "INDEX") (format "\\index{%s}" value))
     ;; Invisible targets.
     ((string= key "TARGET") nil)
     ((string= key "TOC")
      (let ((value (downcase value)))
	(cond
	 ((string-match "\\<headlines\\>" value)
	  (let ((depth (or (and (string-match "[0-9]+" value)
				(string-to-number (match-string 0 value)))
			   (plist-get info :with-toc))))
	    (concat
	     (when (wholenump depth)
	       (format "\\setcounter{tocdepth}{%s}\n" depth))
	     "\\tableofcontents")))
	 ((string= "tables" value) "\\listoftables")
	 ((string= "figures" value) "\\listoffigures")
	 ((string= "listings" value)
	  (cond
	   ((eq org-e-texinfo-listings 'minted) "\\listoflistings")
	   (org-e-texinfo-listings "\\lstlistoflistings")
	   ;; At the moment, src blocks with a caption are wrapped
	   ;; into a figure environment.
	   (t "\\listoffigures")))))))))


;;;; Latex Environment

(defun org-e-texinfo-latex-environment (latex-environment contents info)
  "Transcode a LATEX-ENVIRONMENT element from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual information."
  (let ((label (org-element-property :name latex-environment))
	(value (org-remove-indentation
		(org-element-property :value latex-environment))))
    (if (not (org-string-nw-p label)) value
      ;; Environment is labelled: label must be within the environment
      ;; (otherwise, a reference pointing to that element will count
      ;; the section instead).
      (with-temp-buffer
	(insert value)
	(goto-char (point-min))
	(forward-line)
	(insert (format "\\label{%s}\n" label))
	(buffer-string)))))


;;;; Latex Fragment

(defun org-e-texinfo-latex-fragment (latex-fragment contents info)
  "Transcode a LATEX-FRAGMENT object from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual information."
  (org-element-property :value latex-fragment))


;;;; Line Break

(defun org-e-texinfo-line-break (line-break contents info)
  "Transcode a LINE-BREAK object from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual information."
  "@*")


;;;; Link

(defun org-e-texinfo-link (link desc info)
  "Transcode a LINK object from Org to Texinfo.

DESC is the description part of the link, or the empty string.
INFO is a plist holding contextual information.  See
`org-export-data'."
  (let* ((type (org-element-property :type link))
	 (raw-path (org-element-property :path link))
	 ;; Ensure DESC really exists, or set it to nil.
	 (desc (and (not (string= desc "")) desc))
	 (path (cond
		((member type '("http" "https" "ftp"))
		 (concat type ":" raw-path))
		((string= type "file")
		 (when (string-match "\\(.+\\)::.+" raw-path)
		   (setq raw-path (match-string 1 raw-path)))
		 (if (file-name-absolute-p raw-path)
		     (concat "file://" (expand-file-name raw-path))
		   (concat "file://" raw-path)))
		(t raw-path)))
	 (email (if (string= type "mailto")
		    (let ((text (replace-regexp-in-string
				 "@" "@@" raw-path)))
		     (concat text (if desc (concat "," desc))))))
	 protocol)
    (cond
     ;; Links pointing to an headline: Find destination and build
     ;; appropriate referencing command.
     ((member type '("custom-id" "fuzzy" "id"))
      (let ((destination (org-export-resolve-id-link link info)))
	(case (org-element-type destination)
	  ;; Id link points to an external file.
	  (plain-text
	   (if desc (format "@uref{file://%s,%s}" destination desc)
	     (format "@uref{file://%s}" destination)))
	  ;; LINK points to an headline.  Use the headline as the NODE target
	  (headline
	   (format "@ref{%s}"
		   (org-export-data
		    (org-element-property :title destination) info)))
	  (t))))
     ;; Special case for email addresses
     (email
      (format "@email{%s}" email))
     ;; External link with a description part.
     ((and path desc) (format "@uref{%s,%s}" path desc))
     ;; External link without a description part.
     (path (format "@uref{%s}" path))
     ;; No path, only description.  Try to do something useful.
     (t (format org-e-texinfo-link-with-unknown-path-format desc)))))


;;;; Macro

(defun org-e-texinfo-macro (macro contents info)
  "Transcode a MACRO element from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual information."
  ;; Use available tools.
  (org-export-expand-macro macro info))


;;;; Menu

(defun org-e-texinfo-make-menu (tree level &optional info)
  "Create the menu for inclusion in the texifo document.
INFO is the parsed buffer that contains the headlines.  LEVEL
determines whether to make the main menu, or the detailed menu."
  (let* ((info (if info
		   info
		 tree))
	 (parse (plist-get tree :parse-tree))
	 ;; Top determines level to build menu from, it finds the
	 ;; level of the first headline in the export.
	 (top (org-element-map
	       parse 'headline
	       (lambda (headline)
		 (org-element-property :level headline)) info 't))
	 menu menu-title)
    (cond
     ;; Generate the main menu
     ((eq level 'main)
      (org-e-texinfo--build-menu parse top info))
     ;; Generate the detailed (recursive) menu
     ((eq level 'detailed)
      ;; Requires recursion
      ;;(org-e-texinfo--build-detailed-menu parse top info)
      (or (org-e-texinfo--build-menu parse top info 'detailed)
	  "detailed")
      )
     ;; If an integer, create specific menu for that level
     ((integerp level)
      (org-e-texinfo--build-menu parse level info))
     ;; Otherwise do nothing
     (t
      ))))


;;;; Paragraph

(defun org-e-texinfo-paragraph (paragraph contents info)
  "Transcode a PARAGRAPH element from Org to Texinfo.
CONTENTS is the contents of the paragraph, as a string.  INFO is
the plist used as a communication channel."
  contents)


;;;; Plain List

(defun org-e-texinfo-plain-list (plain-list contents info)
  "Transcode a PLAIN-LIST element from Org to Texinfo.
CONTENTS is the contents of the list.  INFO is a plist holding
contextual information."
  (let* ((type (org-element-property :type plain-list))
	 (list-type (cond
		     ((eq type 'ordered) "enumerate")
		     ((eq type 'unordered) "itemize")
		     ((eq type 'descriptive) "table"))))
    (format "@%s%s\n@end %s"
	    (if (eq type 'descriptive)
		(concat list-type " " org-e-texinfo-def-table-markup)
	     list-type)
	    contents
	    list-type)))


;;;; Plain Text

(defun org-e-texinfo-plain-text (text info)
  "Transcode a TEXT string from Org to Texinfo.
TEXT is the string to transcode.  INFO is a plist holding
contextual information."
  ;; Protect @ { and }.
  (while (string-match "\\([^\\]\\|^\\)\\([@{}]\\)" text)
    (setq text
	  (replace-match (format "\\%s" (match-string 2 text)) nil t text 2)))
  ;; Handle quotation marks
  (setq text (org-e-texinfo--quotation-marks text info))
  ;; Convert special strings.
  (when (plist-get info :with-special-strings)
    (while (string-match (regexp-quote "...") text)
      (setq text (replace-match "@dots{}" nil t text))))
  ;; Handle break preservation if required.
  (when (plist-get info :preserve-breaks)
    (setq text (replace-regexp-in-string "\\(\\\\\\\\\\)?[ \t]*\n" " @*\n"
					 text)))
  ;; Return value.
  text)


;;;; Planning

(defun org-e-texinfo-planning (planning contents info)
  "Transcode a PLANNING element from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual
information."
  (concat
   "@noindent"
   (mapconcat
    'identity
    (delq nil
	  (list
	   (let ((closed (org-element-property :closed planning)))
	     (when closed
	       (concat
		(format "@strong%s} " org-closed-string)
		(format org-e-texinfo-inactive-timestamp-format
			(org-translate-time closed)))))
	   (let ((deadline (org-element-property :deadline planning)))
	     (when deadline
	       (concat
		(format "@strong{%s} " org-deadline-string)
		(format org-e-texinfo-active-timestamp-format
			(org-translate-time deadline)))))
	   (let ((scheduled (org-element-property :scheduled planning)))
	     (when scheduled
	       (concat
		(format "@strong{%s} " org-scheduled-string)
		(format org-e-texinfo-active-timestamp-format
			(org-translate-time scheduled)))))))
    " ")
   "@*"))


;;;; Property Drawer

(defun org-e-texinfo-property-drawer (property-drawer contents info)
  "Transcode a PROPERTY-DRAWER element from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual
information."
  ;; The property drawer isn't exported but we want separating blank
  ;; lines nonetheless.
  "")


;;;; Quote Block



(defun org-e-texinfo-quote-block (quote-block contents info)
  "Transcode a QUOTE-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block.  INFO is a plist
holding contextual information."
  
  (let* ((title (org-element-property :name quote-block))
	 (start-quote (concat "@quotation"

			      (if title
				 (format " %s" title)))))
    
    (format "%s\n%s@end quotation" start-quote contents)))



;;;; Quote Section

(defun org-e-texinfo-quote-section (quote-section contents info)
  "Transcode a QUOTE-SECTION element from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual information."
  (let ((value (org-remove-indentation
		(org-element-property :value quote-section))))
    (when value (format "@verbatim\n%s@end verbatim" value))))


;;;; Radio Target
;;
;; Radio targets are not exported at the moment


;;;; Section

(defun org-e-texinfo-section (section contents info)
  "Transcode a SECTION element from Org to Texinfo.
CONTENTS holds the contents of the section.  INFO is a plist
holding contextual information."
  contents)


;;;; Special Block
;;
;; Are ignored at the moment

;;;; Src Block

(defun org-e-texinfo-src-block (src-block contents info)
  "Transcode a SRC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the item.  INFO is a plist holding
contextual information."
  (let* ((lang (org-element-property :language src-block))
	 (lisp-p (string-match-p "lisp" lang)))
    (cond
     ;; Case 1.  Lisp Block
     (lisp-p
      (format "@lisp\n%s\n@end lisp" contents))
     ;; Case 2.  Other blocks
     (t
      (format "@example\n%s\n@end example" contents)))))


;;;; Statistics Cookie

(defun org-e-texinfo-statistics-cookie (statistics-cookie contents info)
  "Transcode a STATISTICS-COOKIE object from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual information."
  (org-element-property :value statistics-cookie))


;;;; Strike-Through
;;
;; Strikethrough is ignored


;;;; Subscript

(defun org-e-texinfo-subscript (subscript contents info)
  "Transcode a SUBSCRIPT object from Org to Texinfo.
CONTENTS is the contents of the object.  INFO is a plist holding
contextual information."
  (format (if (= (length contents) 1) "$_%s$" "$_{\\mathrm{%s}}$") contents))


;;;; Superscript

(defun org-e-texinfo-superscript (superscript contents info)
  "Transcode a SUPERSCRIPT object from Org to Texinfo.
CONTENTS is the contents of the object.  INFO is a plist holding
contextual information."
  (format (if (= (length contents) 1) "$^%s$" "$^{\\mathrm{%s}}$") contents))


;;;; Table
;;
;; `org-e-texinfo-table' is the entry point for table transcoding.  It
;; takes care of tables with a "verbatim" attribute.  Otherwise, it
;; delegates the job to either `org-e-texinfo-table--table.el-table' or
;; `org-e-texinfo-table--org-table' functions, depending of the type of
;; the table.
;;
;; `org-e-texinfo-table--align-string' is a subroutine used to build
;; alignment string for Org tables.

(defun org-e-texinfo-table (table contents info)
  "Transcode a TABLE element from Org to Texinfo.
CONTENTS is the contents of the table.  INFO is a plist holding
contextual information."
  (cond
   ;; Case 1: verbatim table.
   ((or org-e-texinfo-tables-verbatim
	(let ((attr (mapconcat 'identity
			       (org-element-property :attr_latex table)
			       " ")))
	  (and attr (string-match "\\<verbatim\\>" attr))))
    (format "@verbatim \n%s\n@end verbatim"
	    ;; Re-create table, without affiliated keywords.
	    (org-trim
	     (org-element-interpret-data
	      `(table nil ,@(org-element-contents table))))))
   ;; Case 2: table.el table.  Convert it using appropriate tools.
   ((eq (org-element-property :type table) 'table.el)
    (org-e-texinfo-table--table.el-table table contents info))
   ;; Case 3: Standard table.
   (t (org-e-texinfo-table--org-table table contents info))))

(defun org-e-texinfo-table-column-widths (table info)
  "Determine the largest table cell in each column to process alignment.

TABLE is the table element to transcode.  INFO is a plist used as
a communication channel."
  (let* ((rows (org-element-map table 'table-row 'identity info))
	 (collected (loop for row in rows collect
			  (org-element-map
			   row 'table-cell 'identity info)))
	 (number-cells (length (car collected)))
	 cells counts)
    (loop for row in collected do
	  (push (mapcar (lambda (ref)
		     (let* ((start (org-element-property :contents-begin ref))
			    (end (org-element-property :contents-end ref))
			    (length (- end start)))
		       length)) row) cells))
    (setq cells (remove-if #'null cells))
    (push (loop for count from 0 to (- number-cells 1) collect
		   (loop for item in cells collect
			 (nth count item))) counts)
    (mapconcat '(lambda (size)
		  (make-string size ?a)) (mapcar (lambda (ref)
				   (apply 'max `,@ref)) (car counts))
	       "} {")
  ))

(defun org-e-texinfo-table--org-table (table contents info)
  "Return appropriate Texinfo code for an Org table.

TABLE is the table type element to transcode.  CONTENTS is its
contents, as a string.  INFO is a plist used as a communication
channel.

This function assumes TABLE has `org' as its `:type' attribute."
  (let* (
	 (columns (org-e-texinfo-table-column-widths table info))
	 )
    ;; Prepare the final format string for the table.
    (cond
     ;; Longtable.
     ;; Others.
     (t (concat
	 (format "@multitable {%s}\n%s@end multitable"
		 columns
		 contents))))))

(defun org-e-texinfo-table--table.el-table (table contents info)
  "Return appropriate Texinfo code for a table.el table.

TABLE is the table type element to transcode.  CONTENTS is its
contents, as a string.  INFO is a plist used as a communication
channel.

This function assumes TABLE has `table.el' as its `:type'
attribute."
  (require 'table)
  ;; Ensure "*org-export-table*" buffer is empty.
  (with-current-buffer (get-buffer-create "*org-export-table*")
    (erase-buffer))
  (let ((output (with-temp-buffer
		  (insert (org-element-property :value table))
		  (goto-char 1)
		  (re-search-forward "^[ \t]*|[^|]" nil t)
		  (table-generate-source 'latex "*org-export-table*")
		  (with-current-buffer "*org-export-table*"
		    (org-trim (buffer-string))))))
    (kill-buffer (get-buffer "*org-export-table*"))
    ;; Remove left out comments.
    (while (string-match "^%.*\n" output)
      (setq output (replace-match "" t t output)))
    ;; When the "rmlines" attribute is provided, remove all hlines but
    ;; the the one separating heading from the table body.
    (let ((attr (mapconcat 'identity
			   (org-element-property :attr_latex table)
			   " ")))
      (when (and attr (string-match "\\<rmlines\\>" attr))
	(let ((n 0) (pos 0))
	  (while (and (< (length output) pos)
		      (setq pos (string-match "^\\\\hline\n?" output pos)))
	    (incf n)
	    (unless (= n 2)
	      (setq output (replace-match "" nil nil output)))))))
    (if (not org-e-texinfo-tables-centered) output
      (format "\\begin{center}\n%s\n\\end{center}" output))))


;;;; Table Cell

(defun org-e-texinfo-table-cell (table-cell contents info)
  "Transcode a TABLE-CELL element from Org to Texinfo.
CONTENTS is the cell contents.  INFO is a plist used as
a communication channel."
  (concat (if (and contents
		   org-e-texinfo-table-scientific-notation
		   (string-match orgtbl-exp-regexp contents))
	      ;; Use appropriate format string for scientific
	      ;; notation.
	      (format org-e-texinfo-table-scientific-notation
		      (match-string 1 contents)
		      (match-string 2 contents))
	    contents)
	  (when (org-export-get-next-element table-cell) "\n@tab ")))


;;;; Table Row

(defun org-e-texinfo-table-row (table-row contents info)
  "Transcode a TABLE-ROW element from Org to Texinfo.
CONTENTS is the contents of the row.  INFO is a plist used as
a communication channel."
  ;; Rules are ignored since table separators are deduced from
  ;; borders of the current row.
  (when (eq (org-element-property :type table-row) 'standard) 
    (concat "@item " contents "\n")))


;;;; Target

(defun org-e-texinfo-target (target contents info)
  "Transcode a TARGET object from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual
information."
  (format "\\label{%s}"
	  (org-export-solidify-link-text (org-element-property :value target))))


;;;; Timestamp

(defun org-e-texinfo-timestamp (timestamp contents info)
  "Transcode a TIMESTAMP object from Org to Texinfo.
CONTENTS is nil.  INFO is a plist holding contextual
information."
  (let ((value (org-translate-time (org-element-property :value timestamp)))
	(type (org-element-property :type timestamp)))
    (cond ((memq type '(active active-range))
	   (format org-e-texinfo-active-timestamp-format value))
	  ((memq type '(inactive inactive-range))
	   (format org-e-texinfo-inactive-timestamp-format value))
	  (t (format org-e-texinfo-diary-timestamp-format value)))))


;;;; Underline
;;
;; Underline is ignored


;;;; Verbatim

(defun org-e-texinfo-verbatim (verbatim contents info)
  "Transcode a VERBATIM object from Org to Texinfo.
CONTENTS is nil.  INFO is a plist used as a communication
channel."
  (org-e-texinfo--text-markup (org-element-property :value verbatim) 'verbatim))


;;;; Verse Block

(defun org-e-texinfo-verse-block (verse-block contents info)
  "Transcode a VERSE-BLOCK element from Org to Texinfo.
CONTENTS is verse block contents. INFO is a plist holding
contextual information."
  ;; In a verse environment, add a line break to each newline
  ;; character and change each white space at beginning of a line
  ;; into a space of 1 em.  Also change each blank line with
  ;; a vertical space of 1 em.
  (progn
    (setq contents (replace-regexp-in-string
		    "^ *\\\\\\\\$" "\\\\vspace*{1em}"
		    (replace-regexp-in-string
		     "\\(\\\\\\\\\\)?[ \t]*\n" " \\\\\\\\\n" contents)))
    (while (string-match "^[ \t]+" contents)
      (let ((new-str (format "\\hspace*{%dem}"
			     (length (match-string 0 contents)))))
	(setq contents (replace-match new-str nil t contents))))
    (format "\\begin{verse}\n%s\\end{verse}" contents)))


\f
;;; Interactive functions

(defun org-e-texinfo-export-to-texinfo
  (&optional subtreep visible-only body-only ext-plist pub-dir)
  "Export current buffer to a Texinfo file.

If narrowing is active in the current buffer, only export its
narrowed part.

If a region is active, export that region.

When optional argument SUBTREEP is non-nil, export the sub-tree
at point, extracting information from the headline properties
first.

When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.

When optional argument BODY-ONLY is non-nil, only write code
between \"\\begin{document}\" and \"\\end{document}\".

EXT-PLIST, when provided, is a property list with external
parameters overriding Org default settings, but still inferior to
file-local settings.

When optional argument PUB-DIR is set, use it as the publishing
directory.

Return output file's name."
  (interactive)
  (let ((outfile (org-export-output-file-name ".texi" subtreep pub-dir)))
    (org-export-to-file
     'e-texinfo outfile subtreep visible-only body-only ext-plist)))

(defun org-e-texinfo-export-to-info
  (&optional subtreep visible-only body-only ext-plist pub-dir)
  "Export current buffer to Texinfo then process through to INFO.

If narrowing is active in the current buffer, only export its
narrowed part.

If a region is active, export that region.

When optional argument SUBTREEP is non-nil, export the sub-tree
at point, extracting information from the headline properties
first.

When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.

When optional argument BODY-ONLY is non-nil, only write code
between \"\\begin{document}\" and \"\\end{document}\".

EXT-PLIST, when provided, is a property list with external
parameters overriding Org default settings, but still inferior to
file-local settings.

When optional argument PUB-DIR is set, use it as the publishing
directory.

Return INFO file's name."
  (interactive)
  (org-e-texinfo-compile
   (org-e-texinfo-export-to-texinfo
    subtreep visible-only body-only ext-plist pub-dir)))

(defun org-e-texinfo-compile (texifile)
  "Compile a texinfo file.

TEXIFILE is the name of the file being compiled.  Processing is
done through the command specified in `org-e-texinfo-info-process'.

Return INFO file name or an error if it couldn't be produced."
  (let* ((wconfig (current-window-configuration))
	 (texifile (file-truename texifile))
	 (base (file-name-sans-extension texifile))
	 errors)
    (message (format "Processing Texinfo file %s ..." texifile))
    (unwind-protect
	(progn
	  (cond
	   ;; A function is provided: Apply it.
	   ((functionp org-e-texinfo-info-process)
	    (funcall org-e-texinfo-info-process (shell-quote-argument texifile)))
	   ;; A list is provided: Replace %b, %f and %o with appropriate
	   ;; values in each command before applying it.  Output is
	   ;; redirected to "*Org INFO Texinfo Output*" buffer.
	   ((consp org-e-texinfo-info-process)
	    (let* ((out-dir (or (file-name-directory texifile) "./"))
		   (outbuf (get-buffer-create "*Org Info Texinfo Output*")))
	      (mapc
	       (lambda (command)
		 (shell-command
		  (replace-regexp-in-string
		   "%b" (shell-quote-argument base)
		   (replace-regexp-in-string
		    "%f" (shell-quote-argument texifile)
		    (replace-regexp-in-string
		     "%o" (shell-quote-argument out-dir) command t t) t t) t t)
		  outbuf))
	       org-e-texinfo-info-process)
	      ;; Collect standard errors from output buffer.
	      (setq errors (org-e-texinfo-collect-errors outbuf))))
	   (t (error "No valid command to process to Info")))
	  (let ((infofile (concat base ".info")))
	    ;; Check for process failure.  Provide collected errors if
	    ;; possible.
	    (if (not (file-exists-p infofile))
		(error (concat (format "INFO file %s wasn't produced" infofile)
			       (when errors (concat ": " errors))))
	      ;; Else remove log files, when specified, and signal end of
	      ;; process to user, along with any error encountered.
	      (message (concat "Process completed"
			       (if (not errors) "."
				 (concat " with errors: " errors)))))
	    ;; Return output file name.
	    infofile))
      (set-window-configuration wconfig))))

(defun org-e-texinfo-collect-errors (buffer)
  "Collect some kind of errors from \"pdflatex\" command output.

BUFFER is the buffer containing output.

Return collected error types as a string, or nil if there was
none."
  (with-current-buffer buffer
    (save-excursion
      (goto-char (point-max))
      ;; Find final "makeinfo" run.
      (when (re-search-backward "^[ \t]*This is pdf.*?TeX.*?Version" nil t)
	(let ((case-fold-search t)
	      (errors ""))
	  (when (save-excursion
		  (re-search-forward "Reference.*?undefined" nil t))
	    (setq errors (concat errors " [undefined reference]")))
	  (when (save-excursion
		  (re-search-forward "Citation.*?undefined" nil t))
	    (setq errors (concat errors " [undefined citation]")))
	  (when (save-excursion
		  (re-search-forward "Undefined control sequence" nil t))
	    (setq errors (concat errors " [undefined control sequence]")))
	  (when (save-excursion
		  (re-search-forward "^! LaTeX.*?Error" nil t))
	    (setq errors (concat errors " [LaTeX error]")))
	  (when (save-excursion
		  (re-search-forward "^! Package.*?Error" nil t))
	    (setq errors (concat errors " [package error]")))
	  (and (org-string-nw-p errors) (org-trim errors)))))))


(provide 'org-e-texinfo)
;;; org-e-texinfo.el ends here

^ permalink raw reply	[flat|nested] 13+ messages in thread

end of thread, other threads:[~2012-08-03 13:30 UTC | newest]

Thread overview: 13+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2012-07-20  0:29 Export to Texinfo Jonathan Leech-Pepin
2012-07-20  9:32 ` Nicolas Goaziou
2012-07-20 13:34   ` Jonathan Leech-Pepin
2012-07-20 13:42     ` Nicolas Goaziou
2012-07-31 21:03       ` Jonathan Leech-Pepin
2012-07-31 21:18         ` Nicolas Goaziou
2012-07-31 22:35           ` Jonathan Leech-Pepin
2012-07-31 23:45             ` Jonathan Leech-Pepin
2012-08-02 15:34         ` Bastien
     [not found]           ` <CAHRqSkQTzE-OYmTFs+BRjrER=jgS3=2BE5Yi4A6v8ipaZ1kWQA@mail.gmail.com>
2012-08-02 22:24             ` Fwd: " Jonathan Leech-Pepin
2012-08-03  7:29               ` Bastien
2012-08-03  8:41               ` Nicolas Goaziou
2012-08-03 13:30                 ` Jonathan Leech-Pepin

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs/org-mode.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).