mirror of https://github.com/Chizi123/.emacs.d.git

Chizi123
2018-11-18 76bbd07de7add0f9d13c6914f158d19630fe2f62
commit | author | age
76bbd0 1 ;;; ox-texinfo.el --- Texinfo Back-End for Org Export Engine -*- lexical-binding: t; -*-
C 2
3 ;; Copyright (C) 2012-2018 Free Software Foundation, Inc.
4 ;; Author: Jonathan Leech-Pepin <jonathan.leechpepin at gmail dot com>
5 ;; Keywords: outlines, hypermedia, calendar, wp
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23 ;;
24 ;; See Org manual for details.
25
26 ;;; Code:
27
28 (require 'cl-lib)
29 (require 'ox)
30
31 (defvar orgtbl-exp-regexp)
32
33
34
35 ;;; Define Back-End
36
37 (org-export-define-backend 'texinfo
38   '((bold . org-texinfo-bold)
39     (center-block . org-texinfo-center-block)
40     (clock . org-texinfo-clock)
41     (code . org-texinfo-code)
42     (drawer . org-texinfo-drawer)
43     (dynamic-block . org-texinfo-dynamic-block)
44     (entity . org-texinfo-entity)
45     (example-block . org-texinfo-example-block)
46     (export-block . org-texinfo-export-block)
47     (export-snippet . org-texinfo-export-snippet)
48     (fixed-width . org-texinfo-fixed-width)
49     (footnote-definition . org-texinfo-footnote-definition)
50     (footnote-reference . org-texinfo-footnote-reference)
51     (headline . org-texinfo-headline)
52     (inline-src-block . org-texinfo-inline-src-block)
53     (inlinetask . org-texinfo-inlinetask)
54     (italic . org-texinfo-italic)
55     (item . org-texinfo-item)
56     (keyword . org-texinfo-keyword)
57     (line-break . org-texinfo-line-break)
58     (link . org-texinfo-link)
59     (node-property . org-texinfo-node-property)
60     (paragraph . org-texinfo-paragraph)
61     (plain-list . org-texinfo-plain-list)
62     (plain-text . org-texinfo-plain-text)
63     (planning . org-texinfo-planning)
64     (property-drawer . org-texinfo-property-drawer)
65     (quote-block . org-texinfo-quote-block)
66     (radio-target . org-texinfo-radio-target)
67     (section . org-texinfo-section)
68     (special-block . org-texinfo-special-block)
69     (src-block . org-texinfo-src-block)
70     (statistics-cookie . org-texinfo-statistics-cookie)
71     (strike-through . org-texinfo-strike-through)
72     (subscript . org-texinfo-subscript)
73     (superscript . org-texinfo-superscript)
74     (table . org-texinfo-table)
75     (table-cell . org-texinfo-table-cell)
76     (table-row . org-texinfo-table-row)
77     (target . org-texinfo-target)
78     (template . org-texinfo-template)
79     (timestamp . org-texinfo-timestamp)
80     (underline . org-texinfo-underline)
81     (verbatim . org-texinfo-verbatim)
82     (verse-block . org-texinfo-verse-block))
83   :filters-alist
84   '((:filter-headline . org-texinfo--filter-section-blank-lines)
85     (:filter-parse-tree . org-texinfo--normalize-headlines)
86     (:filter-section . org-texinfo--filter-section-blank-lines)
87     (:filter-final-output . org-texinfo--untabify))
88   :menu-entry
89   '(?i "Export to Texinfo"
90        ((?t "As TEXI file" org-texinfo-export-to-texinfo)
91     (?i "As INFO file" org-texinfo-export-to-info)
92     (?o "As INFO file and open"
93         (lambda (a s v b)
94           (if a (org-texinfo-export-to-info t s v b)
95         (org-open-file (org-texinfo-export-to-info nil s v b)))))))
96   :options-alist
97   '((:texinfo-filename "TEXINFO_FILENAME" nil nil t)
98     (:texinfo-class "TEXINFO_CLASS" nil org-texinfo-default-class t)
99     (:texinfo-header "TEXINFO_HEADER" nil nil newline)
100     (:texinfo-post-header "TEXINFO_POST_HEADER" nil nil newline)
101     (:subtitle "SUBTITLE" nil nil parse)
102     (:subauthor "SUBAUTHOR" nil nil newline)
103     (:texinfo-dircat "TEXINFO_DIR_CATEGORY" nil nil t)
104     (:texinfo-dirtitle "TEXINFO_DIR_TITLE" nil nil t)
105     (:texinfo-dirdesc "TEXINFO_DIR_DESC" nil nil t)
106     (:texinfo-printed-title "TEXINFO_PRINTED_TITLE" nil nil t)
107     ;; Other variables.
108     (:texinfo-classes nil nil org-texinfo-classes)
109     (:texinfo-format-headline-function nil nil org-texinfo-format-headline-function)
110     (:texinfo-node-description-column nil nil org-texinfo-node-description-column)
111     (:texinfo-active-timestamp-format nil nil org-texinfo-active-timestamp-format)
112     (:texinfo-inactive-timestamp-format nil nil org-texinfo-inactive-timestamp-format)
113     (:texinfo-diary-timestamp-format nil nil org-texinfo-diary-timestamp-format)
114     (:texinfo-link-with-unknown-path-format nil nil org-texinfo-link-with-unknown-path-format)
115     (:texinfo-tables-verbatim nil nil org-texinfo-tables-verbatim)
116     (:texinfo-table-scientific-notation nil nil org-texinfo-table-scientific-notation)
117     (:texinfo-table-default-markup nil nil org-texinfo-table-default-markup)
118     (:texinfo-text-markup-alist nil nil org-texinfo-text-markup-alist)
119     (:texinfo-format-drawer-function nil nil org-texinfo-format-drawer-function)
120     (:texinfo-format-inlinetask-function nil nil org-texinfo-format-inlinetask-function)))
121
122
123
124 ;;; User Configurable Variables
125
126 (defgroup org-export-texinfo nil
127   "Options for exporting Org mode files to Texinfo."
128   :tag "Org Export Texinfo"
129   :version "24.4"
130   :package-version '(Org . "8.0")
131   :group 'org-export)
132
133 ;;;; Preamble
134
135 (defcustom org-texinfo-coding-system nil
136   "Default document encoding for Texinfo output.
137
138 If nil it will default to `buffer-file-coding-system'."
139   :group 'org-export-texinfo
140   :type 'coding-system)
141
142 (defcustom org-texinfo-default-class "info"
143   "The default Texinfo class."
144   :group 'org-export-texinfo
145   :type '(string :tag "Texinfo class"))
146
147 (defcustom org-texinfo-classes
148   '(("info"
149      "@documentencoding AUTO\n@documentlanguage AUTO"
150      ("@chapter %s" "@unnumbered %s" "@appendix %s")
151      ("@section %s" "@unnumberedsec %s" "@appendixsec %s")
152      ("@subsection %s" "@unnumberedsubsec %s" "@appendixsubsec %s")
153      ("@subsubsection %s" "@unnumberedsubsubsec %s" "@appendixsubsubsec %s")))
154   "Alist of Texinfo classes and associated header and structure.
155 If #+TEXINFO_CLASS is set in the buffer, use its value and the
156 associated information.  Here is the structure of a class
157 definition:
158
159   (class-name
160     header-string
161     (numbered-1 unnumbered-1 appendix-1)
162     (numbered-2 unnumbered-2 appendix-2)
163     ...)
164
165
166 The header string
167 -----------------
168
169 The header string is inserted in the header of the generated
170 document, right after \"@setfilename\" and \"@settitle\"
171 commands.
172
173 If it contains the special string
174
175   \"@documentencoding AUTO\"
176
177 \"AUTO\" will be replaced with an appropriate coding system.  See
178 `org-texinfo-coding-system' for more information.  Likewise, if
179 the string contains the special string
180
181   \"@documentlanguage AUTO\"
182
183 \"AUTO\" will be replaced with the language defined in the
184 buffer, through #+LANGUAGE keyword, or globally, with
185 `org-export-default-language', which see.
186
187
188 The sectioning structure
189 ------------------------
190
191 The sectioning structure of the class is given by the elements
192 following the header string.  For each sectioning level, a number
193 of strings is specified.  A %s formatter is mandatory in each
194 section string and will be replaced by the title of the section."
195   :group 'org-export-texinfo
196   :version "26.1"
197   :package-version '(Org . "9.1")
198   :type '(repeat
199       (list (string :tag "Texinfo class")
200         (string :tag "Texinfo header")
201         (repeat :tag "Levels" :inline t
202             (choice
203              (list :tag "Heading"
204                    (string :tag "  numbered")
205                    (string :tag "unnumbered")
206                    (string :tag "  appendix")))))))
207
208 ;;;; Headline
209
210 (defcustom org-texinfo-format-headline-function
211   'org-texinfo-format-headline-default-function
212   "Function to format headline text.
213
214 This function will be called with 5 arguments:
215 TODO      the todo keyword (string or nil).
216 TODO-TYPE the type of todo (symbol: `todo', `done', nil)
217 PRIORITY  the priority of the headline (integer or nil)
218 TEXT      the main headline text (string).
219 TAGS      the tags as a list of strings (list of strings or nil).
220
221 The function result will be used in the section format string."
222   :group 'org-export-texinfo
223   :type 'function
224   :version "26.1"
225   :package-version '(Org . "8.3"))
226
227 ;;;; Node listing (menu)
228
229 (defcustom org-texinfo-node-description-column 32
230   "Column at which to start the description in the node listings.
231 If a node title is greater than this length, the description will
232 be placed after the end of the title."
233   :group 'org-export-texinfo
234   :type 'integer)
235
236 ;;;; Timestamps
237
238 (defcustom org-texinfo-active-timestamp-format "@emph{%s}"
239   "A printf format string to be applied to active timestamps."
240   :group 'org-export-texinfo
241   :type 'string)
242
243 (defcustom org-texinfo-inactive-timestamp-format "@emph{%s}"
244   "A printf format string to be applied to inactive timestamps."
245   :group 'org-export-texinfo
246   :type 'string)
247
248 (defcustom org-texinfo-diary-timestamp-format "@emph{%s}"
249   "A printf format string to be applied to diary timestamps."
250   :group 'org-export-texinfo
251   :type 'string)
252
253 ;;;; Links
254
255 (defcustom org-texinfo-link-with-unknown-path-format "@indicateurl{%s}"
256   "Format string for links with unknown path type."
257   :group 'org-export-texinfo
258   :type 'string)
259
260 ;;;; Tables
261
262 (defcustom org-texinfo-tables-verbatim nil
263   "When non-nil, tables are exported verbatim."
264   :group 'org-export-texinfo
265   :type 'boolean)
266
267 (defcustom org-texinfo-table-scientific-notation "%s\\,(%s)"
268   "Format string to display numbers in scientific notation.
269
270 The format should have \"%s\" twice, for mantissa and exponent
271 \(i.e. \"%s\\\\times10^{%s}\").
272
273 When nil, no transformation is made."
274   :group 'org-export-texinfo
275   :type '(choice
276       (string :tag "Format string")
277       (const :tag "No formatting" nil)))
278
279 (defcustom org-texinfo-table-default-markup "@asis"
280   "Default markup for first column in two-column tables.
281
282 This should an indicating command, e.g., \"@code\", \"@kbd\" or
283 \"@samp\".
284
285 It can be overridden locally using the \":indic\" attribute."
286   :group 'org-export-texinfo
287   :type 'string
288   :version "26.1"
289   :package-version '(Org . "9.1")
290   :safe #'stringp)
291
292 ;;;; Text markup
293
294 (defcustom org-texinfo-text-markup-alist '((bold . "@strong{%s}")
295                        (code . code)
296                        (italic . "@emph{%s}")
297                        (verbatim . samp))
298   "Alist of Texinfo expressions to convert text markup.
299
300 The key must be a symbol among `bold', `code', `italic',
301 `strike-through', `underscore' and `verbatim'.  The value is
302 a formatting string to wrap fontified text with.
303
304 Value can also be set to the following symbols: `verb', `samp'
305 and `code'.  With the first one, Org uses \"@verb\" to create
306 a format string and selects a delimiter character that isn't in
307 the string.  For the other two, Org uses \"@samp\" or \"@code\"
308 to typeset and protects special characters.
309
310 When no association is found for a given markup, text is returned
311 as-is."
312   :group 'org-export-texinfo
313   :version "26.1"
314   :package-version '(Org . "9.1")
315   :type 'alist
316   :options '(bold code italic strike-through underscore verbatim))
317
318 ;;;; Drawers
319
320 (defcustom org-texinfo-format-drawer-function (lambda (_name contents) contents)
321   "Function called to format a drawer in Texinfo code.
322
323 The function must accept two parameters:
324   NAME      the drawer name, like \"LOGBOOK\"
325   CONTENTS  the contents of the drawer.
326
327 The function should return the string to be exported.
328
329 The default function simply returns the value of CONTENTS."
330   :group 'org-export-texinfo
331   :version "24.4"
332   :package-version '(Org . "8.2")
333   :type 'function)
334
335 ;;;; Inlinetasks
336
337 (defcustom org-texinfo-format-inlinetask-function
338   'org-texinfo-format-inlinetask-default-function
339   "Function called to format an inlinetask in Texinfo code.
340
341 The function must accept six parameters:
342   TODO      the todo keyword, as a string
343   TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
344   PRIORITY  the inlinetask priority, as a string
345   NAME      the inlinetask name, as a string.
346   TAGS      the inlinetask tags, as a list of strings.
347   CONTENTS  the contents of the inlinetask, as a string.
348
349 The function should return the string to be exported."
350   :group 'org-export-texinfo
351   :type 'function)
352
353 ;;;; Compilation
354
355 (defcustom org-texinfo-info-process '("makeinfo --no-split %f")
356   "Commands to process a Texinfo file to an INFO file.
357
358 This is a list of strings, each of them will be given to the
359 shell as a command.  %f in the command will be replaced by the
360 relative file name, %F by the absolute file name, %b by the file
361 base name (i.e. without directory and extension parts), %o by the
362 base directory of the file and %O by the absolute file name of
363 the output file."
364   :group 'org-export-texinfo
365   :version "26.1"
366   :package-version '(Org . "9.1")
367   :type '(repeat :tag "Shell command sequence"
368          (string :tag "Shell command")))
369
370 (defcustom org-texinfo-logfiles-extensions
371   '("aux" "toc" "cp" "fn" "ky" "pg" "tp" "vr")
372   "The list of file extensions to consider as Texinfo logfiles.
373 The logfiles will be remove if `org-texinfo-remove-logfiles' is
374 non-nil."
375   :group 'org-export-texinfo
376   :type '(repeat (string :tag "Extension")))
377
378 (defcustom org-texinfo-remove-logfiles t
379   "Non-nil means remove the logfiles produced by compiling a Texinfo file.
380 By default, logfiles are files with these extensions: .aux, .toc,
381 .cp, .fn, .ky, .pg and .tp.  To define the set of logfiles to remove,
382 set `org-texinfo-logfiles-extensions'."
383   :group 'org-export-latex
384   :type 'boolean)
385
386 ;;; Constants
387
388 (defconst org-texinfo-max-toc-depth 4
389   "Maximum depth for creation of detailed menu listings.
390 Beyond this depth, Texinfo will not recognize the nodes and will
391 cause errors.  Left as a constant in case this value ever
392 changes.")
393
394 (defconst org-texinfo-supported-coding-systems
395   '("US-ASCII" "UTF-8" "ISO-8859-15" "ISO-8859-1" "ISO-8859-2" "koi8-r" "koi8-u")
396   "List of coding systems supported by Texinfo, as strings.
397 Specified coding system will be matched against these strings.
398 If two strings share the same prefix (e.g. \"ISO-8859-1\" and
399 \"ISO-8859-15\"), the most specific one has to be listed first.")
400
401 (defconst org-texinfo-inline-image-rules
402   (list (cons "file"
403           (regexp-opt '("eps" "pdf" "png" "jpg" "jpeg" "gif" "svg"))))
404   "Rules characterizing image files that can be inlined.")
405
406
407 ;;; Internal Functions
408
409 (defun org-texinfo--untabify (s _backend _info)
410   "Remove TAB characters in string S."
411   (replace-regexp-in-string "\t" (make-string tab-width ?\s) s))
412
413 (defun org-texinfo--filter-section-blank-lines (headline _backend _info)
414   "Filter controlling number of blank lines after a section."
415   (replace-regexp-in-string "\n\\(?:\n[ \t]*\\)*\\'" "\n\n" headline))
416
417 (defun org-texinfo--normalize-headlines (tree _backend info)
418   "Normalize headlines in TREE.
419
420 BACK-END is the symbol specifying back-end used for export. INFO
421 is a plist used as a communication channel.
422
423 Make sure every headline in TREE contains a section, since those
424 are required to install a menu.  Also put exactly one blank line
425 at the end of each section.
426
427 Return new tree."
428   (org-element-map tree 'headline
429     (lambda (hl)
430       (org-element-put-property hl :post-blank 1)
431       (let ((contents (org-element-contents hl)))
432     (when contents
433       (let ((first (org-element-map contents '(headline section)
434              #'identity info t)))
435         (unless (eq (org-element-type first) 'section)
436           (apply #'org-element-set-contents
437              hl
438              (cons `(section (:parent ,hl)) contents)))))))
439     info)
440   tree)
441
442 (defun org-texinfo--find-verb-separator (s)
443   "Return a character not used in string S.
444 This is used to choose a separator for constructs like \\verb."
445   (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
446     (cl-loop for c across ll
447          when (not (string-match (regexp-quote (char-to-string c)) s))
448          return (char-to-string c))))
449
450 (defun org-texinfo--text-markup (text markup _info)
451   "Format TEXT depending on MARKUP text markup.
452 INFO is a plist used as a communication channel.  See
453 `org-texinfo-text-markup-alist' for details."
454   (pcase (cdr (assq markup org-texinfo-text-markup-alist))
455     (`nil text)                ;no markup: return raw text
456     (`code (format "@code{%s}" (org-texinfo--sanitize-content text)))
457     (`samp (format "@samp{%s}" (org-texinfo--sanitize-content text)))
458     (`verb
459      (let ((separator (org-texinfo--find-verb-separator text)))
460        (format "@verb{%s%s%s}" separator text separator)))
461     ;; Else use format string.
462     (fmt (format fmt text))))
463
464 (defun org-texinfo--get-node (datum info)
465   "Return node or anchor associated to DATUM.
466 DATUM is an element or object.  INFO is a plist used as
467 a communication channel.  The function guarantees the node or
468 anchor name is unique."
469   (let ((cache (plist-get info :texinfo-node-cache)))
470     (or (cdr (assq datum cache))
471     (let* ((salt 0)
472            (basename
473         (org-texinfo--sanitize-node
474          (if (eq (org-element-type datum) 'headline)
475              (org-texinfo--sanitize-title
476               (org-export-get-alt-title datum info) info)
477            (org-export-get-reference datum info))))
478            (name basename))
479       ;; Ensure NAME is unique and not reserved node name "Top".
480       (while (or (equal name "Top") (rassoc name cache))
481         (setq name (concat basename (format " %d" (cl-incf salt)))))
482       (plist-put info :texinfo-node-cache (cons (cons datum name) cache))
483       name))))
484
485 (defun org-texinfo--sanitize-node (title)
486   "Bend string TITLE to node line requirements.
487 Trim string and collapse multiple whitespace characters as they
488 are not significant.  Replace leading left parenthesis, when
489 followed by a right parenthesis, with a square bracket.  Remove
490 periods, commas and colons."
491   (org-trim
492    (replace-regexp-in-string
493     "[ \t]+" " "
494     (replace-regexp-in-string
495      "[:,.]" ""
496      (replace-regexp-in-string "\\`(\\(.*?)\\)" "[\\1" title)))))
497
498 (defun org-texinfo--sanitize-title (title info)
499   "Make TITLE suitable as a section name.
500 TITLE is a string or a secondary string.  INFO is the current
501 export state, as a plist."
502   (org-export-data-with-backend
503    title
504    (org-export-create-backend
505     :parent 'texinfo
506     :transcoders '((footnote-reference . ignore)
507            (link . (lambda (l c i)
508                  (or c
509                  (org-export-data
510                   (org-element-property :raw-link l)
511                   i))))
512            (radio-target . (lambda (_r c _i) c))
513            (target . ignore)))
514    info))
515
516 (defun org-texinfo--sanitize-content (text)
517   "Escape special characters in string TEXT.
518 Special characters are: @ { }"
519   (replace-regexp-in-string "[@{}]" "@\\&" text))
520
521 (defun org-texinfo--wrap-float (value info &optional type label caption short)
522   "Wrap string VALUE within a @float command.
523 INFO is the current export state, as a plist.  TYPE is float
524 type, as a string.  LABEL is the cross reference label for the
525 float, as a string.  CAPTION and SHORT are, respectively, the
526 caption and shortcaption used for the float, as secondary
527 strings (e.g., returned by `org-export-get-caption')."
528   (let* ((backend
529       (org-export-create-backend
530        :parent 'texinfo
531        :transcoders '((link . (lambda (l c i)
532                     (or c
533                     (org-export-data
534                      (org-element-property :raw-link l)
535                      i))))
536               (radio-target . (lambda (_r c _i) c))
537               (target . ignore))))
538      (short-backend
539       (org-export-create-backend
540        :parent 'texinfo
541        :transcoders
542        '((footnote-reference . ignore)
543          (inline-src-block . ignore)
544          (link . (lambda (l c i)
545                (or c
546                (org-export-data
547                 (org-element-property :raw-link l)
548                 i))))
549          (radio-target . (lambda (_r c _i) c))
550          (target . ignore)
551          (verbatim . ignore))))
552      (short-str
553       (if (and short caption)
554           (format "@shortcaption{%s}\n"
555               (org-export-data-with-backend short short-backend info))
556         ""))
557      (caption-str
558       (if (or short caption)
559           (format "@caption{%s}\n"
560               (org-export-data-with-backend
561                (or caption short)
562                (if (equal short-str "") short-backend backend)
563                info))
564         "")))
565     (format "@float %s%s\n%s\n%s%s@end float"
566         type (if label (concat "," label) "") value caption-str short-str)))
567
568 ;;; Template
569
570 (defun org-texinfo-template (contents info)
571   "Return complete document string after Texinfo conversion.
572 CONTENTS is the transcoded contents string.  INFO is a plist
573 holding export options."
574   (let ((title (org-export-data (plist-get info :title) info))
575     ;; Copying data is the contents of the first headline in
576     ;; parse tree with a non-nil copying property.
577     (copying (org-element-map (plist-get info :parse-tree) 'headline
578            (lambda (hl)
579              (and (org-not-nil (org-element-property :COPYING hl))
580               (org-element-contents hl)))
581            info t)))
582     (concat
583      "\\input texinfo    @c -*- texinfo -*-\n"
584      "@c %**start of header\n"
585      (let ((file (or (plist-get info :texinfo-filename)
586              (let ((f (plist-get info :output-file)))
587                (and f (concat (file-name-sans-extension f) ".info"))))))
588        (and file (format "@setfilename %s\n" file)))
589      (format "@settitle %s\n" title)
590      ;; Insert class-defined header.
591      (org-element-normalize-string
592       (let ((header (nth 1 (assoc (plist-get info :texinfo-class)
593                   org-texinfo-classes)))
594         (coding
595          (catch 'coding-system
596            (let ((case-fold-search t)
597              (name (symbol-name (or org-texinfo-coding-system
598                         buffer-file-coding-system))))
599          (dolist (system org-texinfo-supported-coding-systems "UTF-8")
600            (when (string-match-p (regexp-quote system) name)
601              (throw 'coding-system system))))))
602         (language (plist-get info :language))
603         (case-fold-search nil))
604     ;; Auto coding system.
605     (replace-regexp-in-string
606      "^@documentencoding \\(AUTO\\)$"
607      coding
608      (replace-regexp-in-string
609       "^@documentlanguage \\(AUTO\\)$" language header t nil 1) t nil 1)))
610      ;; Additional header options set by #+TEXINFO_HEADER.
611      (let ((texinfo-header (plist-get info :texinfo-header)))
612        (and texinfo-header (org-element-normalize-string texinfo-header)))
613      "@c %**end of header\n\n"
614      ;; Additional options set by #+TEXINFO_POST_HEADER.
615      (let ((texinfo-post-header (plist-get info :texinfo-post-header)))
616        (and texinfo-post-header
617         (org-element-normalize-string texinfo-post-header)))
618      ;; Copying.
619      (and copying
620       (format "@copying\n%s@end copying\n\n"
621           (org-element-normalize-string
622            (org-export-data copying info))))
623      ;; Info directory information.  Only supply if both title and
624      ;; category are provided.
625      (let ((dircat (plist-get info :texinfo-dircat))
626        (dirtitle
627         (let ((title (plist-get info :texinfo-dirtitle)))
628           (and title
629            (string-match "^\\(?:\\* \\)?\\(.*?\\)\\(\\.\\)?$" title)
630            (format "* %s." (match-string 1 title))))))
631        (when (and dircat dirtitle)
632      (concat "@dircategory " dircat "\n"
633          "@direntry\n"
634          (let ((dirdesc
635             (let ((desc (plist-get info :texinfo-dirdesc)))
636               (cond ((not desc) nil)
637                 ((string-suffix-p "." desc) desc)
638                 (t (concat desc "."))))))
639            (if dirdesc (format "%-23s %s" dirtitle dirdesc) dirtitle))
640          "\n"
641          "@end direntry\n\n")))
642      ;; Title
643      "@finalout\n"
644      "@titlepage\n"
645      (when (plist-get info :with-title)
646        (concat
647     (format "@title %s\n"
648         (or (plist-get info :texinfo-printed-title) title ""))
649     (let ((subtitle (plist-get info :subtitle)))
650       (when subtitle
651         (format "@subtitle %s\n"
652             (org-export-data subtitle info))))))
653      (when (plist-get info :with-author)
654        (concat
655     ;; Primary author.
656     (let ((author (org-string-nw-p
657                (org-export-data (plist-get info :author) info)))
658           (email (and (plist-get info :with-email)
659               (org-string-nw-p
660                (org-export-data (plist-get info :email) info)))))
661       (cond ((and author email)
662          (format "@author %s (@email{%s})\n" author email))
663         (author (format "@author %s\n" author))
664         (email (format "@author @email{%s}\n" email))))
665     ;; Other authors.
666     (let ((subauthor (plist-get info :subauthor)))
667       (and subauthor
668            (org-element-normalize-string
669         (replace-regexp-in-string "^" "@author " subauthor))))))
670      (and copying "@page\n@vskip 0pt plus 1filll\n@insertcopying\n")
671      "@end titlepage\n\n"
672      ;; Table of contents.
673      (and (plist-get info :with-toc) "@contents\n\n")
674      ;; Configure Top Node when not for TeX.  Also include contents
675      ;; from the first section of the document.
676      "@ifnottex\n"
677      "@node Top\n"
678      (format "@top %s\n" title)
679      (let* ((first-section
680          (org-element-map (plist-get info :parse-tree) 'section
681            #'identity info t '(headline)))
682         (top-contents
683          (org-export-data (org-element-contents first-section) info)))
684        (and (org-string-nw-p top-contents) (concat "\n" top-contents)))
685      "@end ifnottex\n\n"
686      ;; Menu.
687      (org-texinfo-make-menu (plist-get info :parse-tree) info 'master)
688      "\n"
689      ;; Document's body.
690      contents "\n"
691      ;; Creator.
692      (and (plist-get info :with-creator)
693       (concat (plist-get info :creator) "\n"))
694      ;; Document end.
695      "@bye")))
696
697
698
699 ;;; Transcode Functions
700
701 ;;;; Bold
702
703 (defun org-texinfo-bold (_bold contents info)
704   "Transcode BOLD from Org to Texinfo.
705 CONTENTS is the text with bold markup.  INFO is a plist holding
706 contextual information."
707   (org-texinfo--text-markup contents 'bold info))
708
709 ;;;; Center Block
710
711 (defun org-texinfo-center-block (_center-block contents _info)
712   "Transcode a CENTER-BLOCK element from Org to Texinfo.
713 CONTENTS holds the contents of the block.  INFO is a plist used
714 as a communication channel."
715   contents)
716
717 ;;;; Clock
718
719 (defun org-texinfo-clock (clock _contents info)
720   "Transcode a CLOCK element from Org to Texinfo.
721 CONTENTS is nil.  INFO is a plist holding contextual
722 information."
723   (concat
724    "@noindent"
725    (format "@strong{%s} " org-clock-string)
726    (format (plist-get info :texinfo-inactive-timestamp-format)
727        (concat (org-timestamp-translate (org-element-property :value clock))
728            (let ((time (org-element-property :duration clock)))
729              (and time (format " (%s)" time)))))
730    "@*"))
731
732 ;;;; Code
733
734 (defun org-texinfo-code (code _contents info)
735   "Transcode a CODE object from Org to Texinfo.
736 CONTENTS is nil.  INFO is a plist used as a communication
737 channel."
738   (org-texinfo--text-markup (org-element-property :value code) 'code info))
739
740 ;;;; Drawer
741
742 (defun org-texinfo-drawer (drawer contents info)
743   "Transcode a DRAWER element from Org to Texinfo.
744 CONTENTS holds the contents of the block.  INFO is a plist
745 holding contextual information."
746   (let* ((name (org-element-property :drawer-name drawer))
747      (output (funcall (plist-get info :texinfo-format-drawer-function)
748               name contents)))
749     output))
750
751 ;;;; Dynamic Block
752
753 (defun org-texinfo-dynamic-block (_dynamic-block contents _info)
754   "Transcode a DYNAMIC-BLOCK element from Org to Texinfo.
755 CONTENTS holds the contents of the block.  INFO is a plist
756 holding contextual information."
757   contents)
758
759 ;;;; Entity
760
761 (defun org-texinfo-entity (entity _contents _info)
762   "Transcode an ENTITY object from Org to Texinfo."
763   ;; Since there is not specific Texinfo entry in entities, use
764   ;; Texinfo-specific commands whenever possible, and fallback to
765   ;; UTF-8 otherwise.
766   (pcase (org-element-property :name entity)
767     ("AElig"                       "@AE{}")
768     ("aelig"                       "@ae{}")
769     ((or "bull" "bullet")          "@bullet{}")
770     ("copy"                        "@copyright{}")
771     ("deg"                         "@textdegree{}")
772     ((or "dots" "hellip")          "@dots{}")
773     ("equiv"                       "@equiv{}")
774     ((or "euro" "EUR")             "@euro{}")
775     ((or "ge" "geq")               "@geq{}")
776     ("laquo"                       "@guillemetleft{}")
777     ("iexcl"                       "@exclamdown{}")
778     ("imath"                       "@dotless{i}")
779     ("iquest"                      "@questiondown{}")
780     ("jmath"                       "@dotless{j}")
781     ((or "le" "leq")               "@leq{}")
782     ("lsaquo"                      "@guilsinglleft{}")
783     ("mdash"                       "---")
784     ("minus"                       "@minus{}")
785     ("nbsp"                        "@tie{}")
786     ("ndash"                       "--")
787     ("OElig"                       "@OE{}")
788     ("oelig"                       "@oe{}")
789     ("ordf"                        "@ordf{}")
790     ("ordm"                        "@ordm{}")
791     ("pound"                       "@pound{}")
792     ("raquo"                       "@guillemetright{}")
793     ((or "rArr" "Rightarrow")      "@result{}")
794     ("reg"                         "@registeredsymbol{}")
795     ((or "rightarrow" "to" "rarr") "@arrow{}")
796     ("rsaquo"                      "@guilsinglright{}")
797     ("thorn"                       "@th{}")
798     ("THORN"                       "@TH{}")
799     ((and (pred (string-prefix-p "_")) name) ;spacing entities
800      (format "@w{%s}" (substring name 1)))
801     (_ (org-element-property :utf-8 entity))))
802
803 ;;;; Example Block
804
805 (defun org-texinfo-example-block (example-block _contents info)
806   "Transcode an EXAMPLE-BLOCK element from Org to Texinfo.
807 CONTENTS is nil.  INFO is a plist holding contextual
808 information."
809   (format "@example\n%s@end example"
810       (org-texinfo--sanitize-content
811        (org-export-format-code-default example-block info))))
812
813 ;;; Export Block
814
815 (defun org-texinfo-export-block (export-block _contents _info)
816   "Transcode a EXPORT-BLOCK element from Org to Texinfo.
817 CONTENTS is nil.  INFO is a plist holding contextual information."
818   (when (string= (org-element-property :type export-block) "TEXINFO")
819     (org-remove-indentation (org-element-property :value export-block))))
820
821 ;;; Export Snippet
822
823 (defun org-texinfo-export-snippet (export-snippet _contents _info)
824   "Transcode a EXPORT-SNIPPET object from Org to Texinfo.
825 CONTENTS is nil.  INFO is a plist holding contextual information."
826   (when (eq (org-export-snippet-backend export-snippet) 'texinfo)
827     (org-element-property :value export-snippet)))
828
829 ;;;; Fixed Width
830
831 (defun org-texinfo-fixed-width (fixed-width _contents _info)
832   "Transcode a FIXED-WIDTH element from Org to Texinfo.
833 CONTENTS is nil.  INFO is a plist holding contextual information."
834   (format "@example\n%s@end example"
835       (org-remove-indentation
836        (org-texinfo--sanitize-content
837         (org-element-property :value fixed-width)))))
838
839 ;;;; Footnote Reference
840
841 (defun org-texinfo-footnote-reference (footnote _contents info)
842   "Create a footnote reference for FOOTNOTE.
843
844 FOOTNOTE is the footnote to define.  CONTENTS is nil.  INFO is a
845 plist holding contextual information."
846   (let ((def (org-export-get-footnote-definition footnote info)))
847     (format "@footnote{%s}"
848         (org-trim (org-export-data def info)))))
849
850 ;;;; Headline
851
852 (defun org-texinfo--structuring-command (headline info)
853   "Return Texinfo structuring command string for HEADLINE element.
854 Return nil if HEADLINE is to be ignored, `plain-list' if it
855 should be exported as a plain-list item.  INFO is a plist holding
856 contextual information."
857   (cond
858    ((org-element-property :footnote-section-p headline) nil)
859    ((org-not-nil (org-export-get-node-property :COPYING headline t)) nil)
860    ((org-export-low-level-p headline info) 'plain-list)
861    (t
862     (let ((class (plist-get info :texinfo-class)))
863       (pcase (assoc class (plist-get info :texinfo-classes))
864     (`(,_ ,_ . ,sections)
865      (pcase (nth (1- (org-export-get-relative-level headline info))
866              sections)
867        (`(,numbered ,unnumbered ,appendix)
868         (cond
869          ((org-not-nil (org-export-get-node-property :APPENDIX headline t))
870           appendix)
871          ((org-not-nil (org-export-get-node-property :INDEX headline t))
872           unnumbered)
873          ((org-export-numbered-headline-p headline info) numbered)
874          (t unnumbered)))
875        (`nil 'plain-list)
876        (_ (user-error "Invalid Texinfo class specification: %S" class))))
877     (_ (user-error "Invalid Texinfo class specification: %S" class)))))))
878
879 (defun org-texinfo-headline (headline contents info)
880   "Transcode a HEADLINE element from Org to Texinfo.
881 CONTENTS holds the contents of the headline.  INFO is a plist
882 holding contextual information."
883   (let ((section-fmt (org-texinfo--structuring-command headline info)))
884     (when section-fmt
885       (let* ((todo
886           (and (plist-get info :with-todo-keywords)
887            (let ((todo (org-element-property :todo-keyword headline)))
888              (and todo (org-export-data todo info)))))
889          (todo-type (and todo (org-element-property :todo-type headline)))
890          (tags (and (plist-get info :with-tags)
891             (org-export-get-tags headline info)))
892          (priority (and (plist-get info :with-priority)
893                 (org-element-property :priority headline)))
894          (text (org-texinfo--sanitize-title
895             (org-element-property :title headline) info))
896          (full-text
897           (funcall (plist-get info :texinfo-format-headline-function)
898                todo todo-type priority text tags))
899          (contents
900           (concat "\n"
901               (if (org-string-nw-p contents)
902               (concat "\n" contents)
903             "")
904               (let ((index (org-element-property :INDEX headline)))
905             (and (member index '("cp" "fn" "ky" "pg" "tp" "vr"))
906                  (format "\n@printindex %s\n" index))))))
907     (cond
908      ((eq section-fmt 'plain-list)
909       (let ((numbered? (org-export-numbered-headline-p headline info)))
910         (concat (and (org-export-first-sibling-p headline info)
911              (format "@%s\n" (if numbered? 'enumerate 'itemize)))
912             "@item\n" full-text "\n"
913             contents
914             (if (org-export-last-sibling-p headline info)
915             (format "@end %s" (if numbered? 'enumerate 'itemize))
916               "\n"))))
917      (t
918       (concat (format "@node %s\n" (org-texinfo--get-node headline info))
919           (format section-fmt full-text)
920           contents)))))))
921
922 (defun org-texinfo-format-headline-default-function
923   (todo _todo-type priority text tags)
924   "Default format function for a headline.
925 See `org-texinfo-format-headline-function' for details."
926   (concat (when todo (format "@strong{%s} " todo))
927       (when priority (format "@emph{#%s} " priority))
928       text
929       (when tags (format " :%s:" (mapconcat 'identity tags ":")))))
930
931 ;;;; Inline Src Block
932
933 (defun org-texinfo-inline-src-block (inline-src-block _contents _info)
934   "Transcode an INLINE-SRC-BLOCK element from Org to Texinfo.
935 CONTENTS holds the contents of the item.  INFO is a plist holding
936 contextual information."
937   (format "@code{%s}"
938       (org-texinfo--sanitize-content
939        (org-element-property :value inline-src-block))))
940
941 ;;;; Inlinetask
942
943 (defun org-texinfo-inlinetask (inlinetask contents info)
944   "Transcode an INLINETASK element from Org to Texinfo.
945 CONTENTS holds the contents of the block.  INFO is a plist
946 holding contextual information."
947   (let ((title (org-export-data (org-element-property :title inlinetask) info))
948     (todo (and (plist-get info :with-todo-keywords)
949            (let ((todo (org-element-property :todo-keyword inlinetask)))
950              (and todo (org-export-data todo info)))))
951     (todo-type (org-element-property :todo-type inlinetask))
952     (tags (and (plist-get info :with-tags)
953            (org-export-get-tags inlinetask info)))
954     (priority (and (plist-get info :with-priority)
955                (org-element-property :priority inlinetask))))
956     (funcall (plist-get info :texinfo-format-inlinetask-function)
957          todo todo-type priority title tags contents)))
958
959 (defun org-texinfo-format-inlinetask-default-function
960   (todo _todo-type priority title tags contents)
961   "Default format function for inlinetasks.
962 See `org-texinfo-format-inlinetask-function' for details."
963   (let ((full-title
964      (concat (when todo (format "@strong{%s} " todo))
965          (when priority (format "#%c " priority))
966          title
967          (when tags (format ":%s:" (mapconcat #'identity tags ":"))))))
968     (format "@center %s\n\n%s\n" full-title contents)))
969
970 ;;;; Italic
971
972 (defun org-texinfo-italic (_italic contents info)
973   "Transcode ITALIC from Org to Texinfo.
974 CONTENTS is the text with italic markup.  INFO is a plist holding
975 contextual information."
976   (org-texinfo--text-markup contents 'italic info))
977
978 ;;;; Item
979
980 (defun org-texinfo-item (item contents info)
981   "Transcode an ITEM element from Org to Texinfo.
982 CONTENTS holds the contents of the item.  INFO is a plist holding
983 contextual information."
984   (let* ((tag (org-element-property :tag item))
985      (split (org-string-nw-p
986          (org-export-read-attribute :attr_texinfo
987                         (org-element-property :parent item)
988                         :sep)))
989      (items (and tag
990              (let ((tag (org-export-data tag info)))
991                (if split
992                (split-string tag (regexp-quote split) t "[ \t\n]+")
993              (list tag))))))
994     (format "%s\n%s"
995         (pcase items
996           (`nil "@item")
997           (`(,item) (concat "@item " item))
998           (`(,item . ,items)
999            (concat "@item " item "\n"
1000                (mapconcat (lambda (i) (concat "@itemx " i))
1001                   items
1002                   "\n"))))
1003         (or contents ""))))
1004
1005 ;;;; Keyword
1006
1007 (defun org-texinfo-keyword (keyword _contents info)
1008   "Transcode a KEYWORD element from Org to Texinfo.
1009 CONTENTS is nil.  INFO is a plist holding contextual information."
1010   (let ((value (org-element-property :value keyword)))
1011     (pcase (org-element-property :key keyword)
1012       ("TEXINFO" value)
1013       ("CINDEX" (format "@cindex %s" value))
1014       ("FINDEX" (format "@findex %s" value))
1015       ("KINDEX" (format "@kindex %s" value))
1016       ("PINDEX" (format "@pindex %s" value))
1017       ("TINDEX" (format "@tindex %s" value))
1018       ("VINDEX" (format "@vindex %s" value))
1019       ("TOC"
1020        (cond ((string-match-p "\\<tables\\>" value)
1021           (concat "@listoffloats "
1022               (org-export-translate "Table" :utf-8 info)))
1023          ((string-match-p "\\<listings\\>" value)
1024           (concat "@listoffloats "
1025               (org-export-translate "Listing" :utf-8 info))))))))
1026
1027 ;;;; Line Break
1028
1029 (defun org-texinfo-line-break (_line-break _contents _info)
1030   "Transcode a LINE-BREAK object from Org to Texinfo.
1031 CONTENTS is nil.  INFO is a plist holding contextual information."
1032   "@*\n")
1033
1034 ;;;; Link
1035
1036 (defun org-texinfo--@ref (datum description info)
1037   "Return @ref command for element or object DATUM.
1038 DESCRIPTION is the printed name of the section, as a string, or
1039 nil."
1040   (let ((node-name (org-texinfo--get-node datum info))
1041     ;; Sanitize DESCRIPTION for cross-reference use.  In
1042     ;; particular, remove colons as they seem to cause pain (even
1043     ;; within @asis{...}) to the Texinfo reader.
1044     (title (and description
1045             (replace-regexp-in-string
1046              "[ \t]*:+" ""
1047              (replace-regexp-in-string "," "@comma{}" description)))))
1048     (if (or (not title) (equal title node-name))
1049     (format "@ref{%s}" node-name)
1050       (format "@ref{%s, , %s}" node-name title))))
1051
1052 (defun org-texinfo-link (link desc info)
1053   "Transcode a LINK object from Org to Texinfo.
1054 DESC is the description part of the link, or the empty string.
1055 INFO is a plist holding contextual information.  See
1056 `org-export-data'."
1057   (let* ((type (org-element-property :type link))
1058      (raw-path (org-element-property :path link))
1059      ;; Ensure DESC really exists, or set it to nil.
1060      (desc (and (not (string= desc "")) desc))
1061      (path (cond
1062         ((member type '("http" "https" "ftp"))
1063          (concat type ":" raw-path))
1064         ((string= type "file") (org-export-file-uri raw-path))
1065         (t raw-path))))
1066     (cond
1067      ((org-export-custom-protocol-maybe link desc 'texinfo))
1068      ((org-export-inline-image-p link org-texinfo-inline-image-rules)
1069       (org-texinfo--inline-image link info))
1070      ((equal type "radio")
1071       (let ((destination (org-export-resolve-radio-link link info)))
1072     (if (not destination) desc
1073       (org-texinfo--@ref destination desc info))))
1074      ((member type '("custom-id" "id" "fuzzy"))
1075       (let ((destination
1076          (if (equal type "fuzzy")
1077          (org-export-resolve-fuzzy-link link info)
1078            (org-export-resolve-id-link link info))))
1079     (pcase (org-element-type destination)
1080       (`nil
1081        (format org-texinfo-link-with-unknown-path-format
1082            (org-texinfo--sanitize-content path)))
1083       ;; Id link points to an external file.
1084       (`plain-text
1085        (if desc (format "@uref{file://%s,%s}" destination desc)
1086          (format "@uref{file://%s}" destination)))
1087       ((or `headline
1088            ;; Targets within headlines cannot be turned into
1089            ;; @anchor{}, so we refer to the headline parent
1090            ;; directly.
1091            (and `target
1092             (guard (eq 'headline
1093                    (org-element-type
1094                 (org-element-property :parent destination))))))
1095        (let ((headline (org-element-lineage destination '(headline) t)))
1096          (org-texinfo--@ref headline desc info)))
1097       (_ (org-texinfo--@ref destination desc info)))))
1098      ((string= type "mailto")
1099       (format "@email{%s}"
1100           (concat (org-texinfo--sanitize-content path)
1101               (and desc (concat ", " desc)))))
1102      ;; External link with a description part.
1103      ((and path desc) (format "@uref{%s, %s}" path desc))
1104      ;; External link without a description part.
1105      (path (format "@uref{%s}" path))
1106      ;; No path, only description.  Try to do something useful.
1107      (t
1108       (format (plist-get info :texinfo-link-with-unknown-path-format) desc)))))
1109
1110 (defun org-texinfo--inline-image (link info)
1111   "Return Texinfo code for an inline image.
1112 LINK is the link pointing to the inline image.  INFO is the
1113 current state of the export, as a plist."
1114   (let* ((parent (org-export-get-parent-element link))
1115      (label (and (org-element-property :name parent)
1116              (org-texinfo--get-node parent info)))
1117      (caption (org-export-get-caption parent))
1118      (shortcaption (org-export-get-caption parent t))
1119      (path  (org-element-property :path link))
1120      (filename
1121       (file-name-sans-extension
1122        (if (file-name-absolute-p path) (expand-file-name path) path)))
1123      (extension (file-name-extension path))
1124      (attributes (org-export-read-attribute :attr_texinfo parent))
1125      (height (or (plist-get attributes :height) ""))
1126      (width (or (plist-get attributes :width) ""))
1127      (alt (or (plist-get attributes :alt) ""))
1128      (image (format "@image{%s,%s,%s,%s,%s}"
1129             filename width height alt extension)))
1130     (cond ((or caption shortcaption)
1131        (org-texinfo--wrap-float image
1132                     info
1133                     (org-export-translate "Figure" :utf-8 info)
1134                     label
1135                     caption
1136                     shortcaption))
1137       (label (concat "@anchor{" label "}\n" image))
1138       (t image))))
1139
1140
1141 ;;;; Menu
1142
1143 (defun org-texinfo-make-menu (scope info &optional master)
1144   "Create the menu for inclusion in the Texinfo document.
1145
1146 SCOPE is a headline or a full parse tree.  INFO is the
1147 communication channel, as a plist.
1148
1149 When optional argument MASTER is non-nil, generate a master menu,
1150 including detailed node listing."
1151   (let ((menu (org-texinfo--build-menu scope info)))
1152     (when (org-string-nw-p menu)
1153       (org-element-normalize-string
1154        (format
1155     "@menu\n%s@end menu"
1156     (concat menu
1157         (when master
1158           (let ((detailmenu
1159              (org-texinfo--build-menu
1160               scope info
1161               (let ((toc-depth (plist-get info :with-toc)))
1162                 (if (wholenump toc-depth) toc-depth
1163                   org-texinfo-max-toc-depth)))))
1164             (when (org-string-nw-p detailmenu)
1165               (concat "\n@detailmenu\n"
1166                   "--- The Detailed Node Listing ---\n\n"
1167                   detailmenu
1168                   "@end detailmenu\n"))))))))))
1169
1170 (defun org-texinfo--build-menu (scope info &optional level)
1171   "Build menu for entries within SCOPE.
1172 SCOPE is a headline or a full parse tree.  INFO is a plist
1173 containing contextual information.  When optional argument LEVEL
1174 is an integer, build the menu recursively, down to this depth."
1175   (cond
1176    ((not level)
1177     (org-texinfo--format-entries (org-texinfo--menu-entries scope info) info))
1178    ((zerop level) "\n")
1179    (t
1180     (mapconcat
1181      (lambda (h)
1182        (let ((entries (org-texinfo--menu-entries h info)))
1183      (when entries
1184        (concat
1185         (format "%s\n\n%s\n"
1186             (org-export-data (org-export-get-alt-title h info) info)
1187             (org-texinfo--format-entries entries info))
1188         (org-texinfo--build-menu h info (1- level))))))
1189      (org-texinfo--menu-entries scope info)
1190      ""))))
1191
1192 (defun org-texinfo--format-entries (entries info)
1193   "Format all direct menu entries in SCOPE, as a string.
1194 SCOPE is either a headline or a full Org document.  INFO is
1195 a plist containing contextual information."
1196   (org-element-normalize-string
1197    (mapconcat
1198     (lambda (h)
1199       (let* ((title
1200           ;; Colons are used as a separator between title and node
1201           ;; name.  Remove them.
1202           (replace-regexp-in-string
1203            "[ \t]+:+" ""
1204            (org-texinfo--sanitize-title
1205         (org-export-get-alt-title h info) info)))
1206          (node (org-texinfo--get-node h info))
1207          (entry (concat "* " title ":"
1208                 (if (string= title node) ":"
1209                   (concat " " node ". "))))
1210          (desc (org-element-property :DESCRIPTION h)))
1211     (if (not desc) entry
1212       (format (format "%%-%ds %%s" org-texinfo-node-description-column)
1213           entry desc))))
1214     entries "\n")))
1215
1216 (defun org-texinfo--menu-entries (scope info)
1217   "List direct children in SCOPE needing a menu entry.
1218 SCOPE is a headline or a full parse tree.  INFO is a plist
1219 holding contextual information."
1220   (let* ((cache (or (plist-get info :texinfo-entries-cache)
1221             (plist-get (plist-put info :texinfo-entries-cache
1222                       (make-hash-table :test #'eq))
1223                    :texinfo-entries-cache)))
1224      (cached-entries (gethash scope cache 'no-cache)))
1225     (if (not (eq cached-entries 'no-cache)) cached-entries
1226       (puthash scope
1227            (cl-remove-if
1228         (lambda (h)
1229           (org-not-nil (org-export-get-node-property :COPYING h t)))
1230         (org-export-collect-headlines info 1 scope))
1231            cache))))
1232
1233 ;;;; Node Property
1234
1235 (defun org-texinfo-node-property (node-property _contents _info)
1236   "Transcode a NODE-PROPERTY element from Org to Texinfo.
1237 CONTENTS is nil.  INFO is a plist holding contextual
1238 information."
1239   (format "%s:%s"
1240           (org-element-property :key node-property)
1241           (let ((value (org-element-property :value node-property)))
1242             (if value (concat " " value) ""))))
1243
1244 ;;;; Paragraph
1245
1246 (defun org-texinfo-paragraph (_paragraph contents _info)
1247   "Transcode a PARAGRAPH element from Org to Texinfo.
1248 CONTENTS is the contents of the paragraph, as a string.  INFO is
1249 the plist used as a communication channel."
1250   contents)
1251
1252 ;;;; Plain List
1253
1254 (defun org-texinfo-plain-list (plain-list contents info)
1255   "Transcode a PLAIN-LIST element from Org to Texinfo.
1256 CONTENTS is the contents of the list.  INFO is a plist holding
1257 contextual information."
1258   (let* ((attr (org-export-read-attribute :attr_texinfo plain-list))
1259      (indic (let ((i (or (plist-get attr :indic)
1260                  (plist-get info :texinfo-table-default-markup))))
1261           ;; Allow indicating commands with missing @ sign.
1262           (if (string-prefix-p "@" i) i (concat "@" i))))
1263      (table-type (plist-get attr :table-type))
1264      (type (org-element-property :type plain-list))
1265      (list-type (cond
1266              ((eq type 'ordered) "enumerate")
1267              ((eq type 'unordered) "itemize")
1268              ((member table-type '("ftable" "vtable")) table-type)
1269              (t "table"))))
1270     (format "@%s\n%s@end %s"
1271         (if (eq type 'descriptive) (concat list-type " " indic) list-type)
1272         contents
1273         list-type)))
1274
1275 ;;;; Plain Text
1276
1277 (defun org-texinfo-plain-text (text info)
1278   "Transcode a TEXT string from Org to Texinfo.
1279 TEXT is the string to transcode.  INFO is a plist holding
1280 contextual information."
1281   ;; First protect @, { and }.
1282   (let ((output (org-texinfo--sanitize-content text)))
1283     ;; Activate smart quotes.  Be sure to provide original TEXT string
1284     ;; since OUTPUT may have been modified.
1285     (when (plist-get info :with-smart-quotes)
1286       (setq output
1287         (org-export-activate-smart-quotes output :texinfo info text)))
1288     ;; LaTeX into @LaTeX{} and TeX into @TeX{}
1289     (let ((case-fold-search nil))
1290       (setq output (replace-regexp-in-string "\\(?:La\\)?TeX" "@\\&{}" output)))
1291     ;; Convert special strings.
1292     (when (plist-get info :with-special-strings)
1293       (setq output
1294         (replace-regexp-in-string
1295          "\\.\\.\\." "@dots{}"
1296          (replace-regexp-in-string "\\\\-" "@-" output))))
1297     ;; Handle break preservation if required.
1298     (when (plist-get info :preserve-breaks)
1299       (setq output (replace-regexp-in-string
1300             "\\(\\\\\\\\\\)?[ \t]*\n" " @*\n" output)))
1301     ;; Return value.
1302     output))
1303
1304 ;;;; Planning
1305
1306 (defun org-texinfo-planning (planning _contents info)
1307   "Transcode a PLANNING element from Org to Texinfo.
1308 CONTENTS is nil.  INFO is a plist holding contextual
1309 information."
1310   (concat
1311    "@noindent"
1312    (mapconcat
1313     'identity
1314     (delq nil
1315       (list
1316        (let ((closed (org-element-property :closed planning)))
1317          (when closed
1318            (concat
1319         (format "@strong{%s} " org-closed-string)
1320         (format (plist-get info :texinfo-inactive-timestamp-format)
1321             (org-timestamp-translate closed)))))
1322        (let ((deadline (org-element-property :deadline planning)))
1323          (when deadline
1324            (concat
1325         (format "@strong{%s} " org-deadline-string)
1326         (format (plist-get info :texinfo-active-timestamp-format)
1327             (org-timestamp-translate deadline)))))
1328        (let ((scheduled (org-element-property :scheduled planning)))
1329          (when scheduled
1330            (concat
1331         (format "@strong{%s} " org-scheduled-string)
1332         (format (plist-get info :texinfo-active-timestamp-format)
1333             (org-timestamp-translate scheduled)))))))
1334     " ")
1335    "@*"))
1336
1337 ;;;; Property Drawer
1338
1339 (defun org-texinfo-property-drawer (_property-drawer contents _info)
1340   "Transcode a PROPERTY-DRAWER element from Org to Texinfo.
1341 CONTENTS holds the contents of the drawer.  INFO is a plist
1342 holding contextual information."
1343   (and (org-string-nw-p contents)
1344        (format "@verbatim\n%s@end verbatim" contents)))
1345
1346 ;;;; Quote Block
1347
1348 (defun org-texinfo-quote-block (quote-block contents _info)
1349   "Transcode a QUOTE-BLOCK element from Org to Texinfo.
1350 CONTENTS holds the contents of the block.  INFO is a plist
1351 holding contextual information."
1352   (let* ((title (org-element-property :name quote-block))
1353      (start-quote (concat "@quotation"
1354                   (if title
1355                   (format " %s" title)))))
1356     (format "%s\n%s@end quotation" start-quote contents)))
1357
1358 ;;;; Radio Target
1359
1360 (defun org-texinfo-radio-target (radio-target text info)
1361   "Transcode a RADIO-TARGET object from Org to Texinfo.
1362 TEXT is the text of the target.  INFO is a plist holding
1363 contextual information."
1364   (format "@anchor{%s}%s"
1365       (org-texinfo--get-node radio-target info)
1366       text))
1367
1368 ;;;; Section
1369
1370 (defun org-texinfo-section (section contents info)
1371   "Transcode a SECTION element from Org to Texinfo.
1372 CONTENTS holds the contents of the section.  INFO is a plist
1373 holding contextual information."
1374   (let ((parent (org-export-get-parent-headline section)))
1375     (when parent            ;ignore very first section
1376       (org-trim
1377        (concat contents "\n" (org-texinfo-make-menu parent info))))))
1378
1379 ;;;; Special Block
1380
1381 (defun org-texinfo-special-block (special-block contents _info)
1382   "Transcode a SPECIAL-BLOCK element from Org to Texinfo.
1383 CONTENTS holds the contents of the block.  INFO is a plist used
1384 as a communication channel."
1385   (let ((opt (org-export-read-attribute :attr_texinfo special-block :options))
1386     (type (org-element-property :type special-block)))
1387     (format "@%s%s\n%s@end %s"
1388         type
1389         (if opt (concat " " opt) "")
1390         (or contents "")
1391         type)))
1392
1393 ;;;; Src Block
1394
1395 (defun org-texinfo-src-block (src-block _contents info)
1396   "Transcode a SRC-BLOCK element from Org to Texinfo.
1397 CONTENTS holds the contents of the item.  INFO is a plist holding
1398 contextual information."
1399   (let* ((lisp (string-match-p "lisp"
1400                    (org-element-property :language src-block)))
1401      (code (org-texinfo--sanitize-content
1402         (org-export-format-code-default src-block info)))
1403      (value (format
1404          (if lisp "@lisp\n%s@end lisp" "@example\n%s@end example")
1405          code))
1406      (caption (org-export-get-caption src-block))
1407      (shortcaption (org-export-get-caption src-block t)))
1408     (if (not (or caption shortcaption)) value
1409       (org-texinfo--wrap-float value
1410                    info
1411                    (org-export-translate "Listing" :utf-8 info)
1412                    (org-texinfo--get-node src-block info)
1413                    caption
1414                    shortcaption))))
1415
1416 ;;;; Statistics Cookie
1417
1418 (defun org-texinfo-statistics-cookie (statistics-cookie _contents _info)
1419   "Transcode a STATISTICS-COOKIE object from Org to Texinfo.
1420 CONTENTS is nil.  INFO is a plist holding contextual information."
1421   (org-element-property :value statistics-cookie))
1422
1423
1424 ;;;; Strike-through
1425
1426 (defun org-texinfo-strike-through (_strike-through contents info)
1427   "Transcode STRIKE-THROUGH from Org to Texinfo.
1428 CONTENTS is the text with strike-through markup.  INFO is a plist
1429 holding contextual information."
1430   (org-texinfo--text-markup contents 'strike-through info))
1431
1432 ;;;; Subscript
1433
1434 (defun org-texinfo-subscript (_subscript contents _info)
1435   "Transcode a SUBSCRIPT object from Org to Texinfo.
1436 CONTENTS is the contents of the object.  INFO is a plist holding
1437 contextual information."
1438   (format "@math{_%s}" contents))
1439
1440 ;;;; Superscript
1441
1442 (defun org-texinfo-superscript (_superscript contents _info)
1443   "Transcode a SUPERSCRIPT object from Org to Texinfo.
1444 CONTENTS is the contents of the object.  INFO is a plist holding
1445 contextual information."
1446   (format "@math{^%s}" contents))
1447
1448 ;;;; Table
1449
1450 (defun org-texinfo-table (table contents info)
1451   "Transcode a TABLE element from Org to Texinfo.
1452 CONTENTS is the contents of the table.  INFO is a plist holding
1453 contextual information."
1454   (if (eq (org-element-property :type table) 'table.el)
1455       (format "@verbatim\n%s@end verbatim"
1456           (org-element-normalize-string
1457            (org-element-property :value table)))
1458     (let* ((col-width (org-export-read-attribute :attr_texinfo table :columns))
1459        (columns
1460         (if col-width (format "@columnfractions %s" col-width)
1461           (org-texinfo-table-column-widths table info)))
1462        (caption (org-export-get-caption table))
1463        (shortcaption (org-export-get-caption table t))
1464        (table-str (format "@multitable %s\n%s@end multitable"
1465                   columns
1466                   contents)))
1467       (if (not (or caption shortcaption)) table-str
1468     (org-texinfo--wrap-float table-str
1469                  info
1470                  (org-export-translate "Table" :utf-8 info)
1471                  (org-texinfo--get-node table info)
1472                  caption
1473                  shortcaption)))))
1474
1475 (defun org-texinfo-table-column-widths (table info)
1476   "Determine the largest table cell in each column to process alignment.
1477 TABLE is the table element to transcode.  INFO is a plist used as
1478 a communication channel."
1479   (let ((widths (make-vector (cdr (org-export-table-dimensions table info)) 0)))
1480     (org-element-map table 'table-row
1481       (lambda (row)
1482     (let ((idx 0))
1483       (org-element-map row 'table-cell
1484         (lambda (cell)
1485           ;; Length of the cell in the original buffer is only an
1486           ;; approximation of the length of the cell in the
1487           ;; output.  It can sometimes fail (e.g. it considers
1488           ;; "/a/" being larger than "ab").
1489           (let ((w (- (org-element-property :contents-end cell)
1490               (org-element-property :contents-begin cell))))
1491         (aset widths idx (max w (aref widths idx))))
1492           (cl-incf idx))
1493         info)))
1494       info)
1495     (format "{%s}" (mapconcat (lambda (w) (make-string w ?a)) widths "} {"))))
1496
1497 ;;;; Table Cell
1498
1499 (defun org-texinfo-table-cell (table-cell contents info)
1500   "Transcode a TABLE-CELL element from Org to Texinfo.
1501 CONTENTS is the cell contents.  INFO is a plist used as
1502 a communication channel."
1503   (concat
1504    (let ((scientific-notation
1505       (plist-get info :texinfo-table-scientific-notation)))
1506      (if (and contents
1507           scientific-notation
1508           (string-match orgtbl-exp-regexp contents))
1509      ;; Use appropriate format string for scientific notation.
1510      (format scientific-notation
1511          (match-string 1 contents)
1512          (match-string 2 contents))
1513        contents))
1514    (when (org-export-get-next-element table-cell info) "\n@tab ")))
1515
1516 ;;;; Table Row
1517
1518 (defun org-texinfo-table-row (table-row contents info)
1519   "Transcode a TABLE-ROW element from Org to Texinfo.
1520 CONTENTS is the contents of the row.  INFO is a plist used as
1521 a communication channel."
1522   ;; Rules are ignored since table separators are deduced from
1523   ;; borders of the current row.
1524   (when (eq (org-element-property :type table-row) 'standard)
1525     (let ((rowgroup-tag
1526        (if (and (= 1 (org-export-table-row-group table-row info))
1527             (org-export-table-has-header-p
1528              (org-export-get-parent-table table-row) info))
1529            "@headitem "
1530          "@item ")))
1531       (concat rowgroup-tag contents "\n"))))
1532
1533 ;;;; Target
1534
1535 (defun org-texinfo-target (target _contents info)
1536   "Transcode a TARGET object from Org to Texinfo.
1537 CONTENTS is nil.  INFO is a plist holding contextual
1538 information."
1539   (format "@anchor{%s}" (org-texinfo--get-node target info)))
1540
1541 ;;;; Timestamp
1542
1543 (defun org-texinfo-timestamp (timestamp _contents info)
1544   "Transcode a TIMESTAMP object from Org to Texinfo.
1545 CONTENTS is nil.  INFO is a plist holding contextual
1546 information."
1547   (let ((value (org-texinfo-plain-text
1548         (org-timestamp-translate timestamp) info)))
1549     (pcase (org-element-property :type timestamp)
1550       ((or `active `active-range)
1551        (format (plist-get info :texinfo-active-timestamp-format) value))
1552       ((or `inactive `inactive-range)
1553        (format (plist-get info :texinfo-inactive-timestamp-format) value))
1554       (_ (format (plist-get info :texinfo-diary-timestamp-format) value)))))
1555
1556 ;;;; Underline
1557
1558 (defun org-texinfo-underline (_underline contents info)
1559   "Transcode UNDERLINE from Org to Texinfo.
1560 CONTENTS is the text with underline markup.  INFO is a plist
1561 holding contextual information."
1562   (org-texinfo--text-markup contents 'underline info))
1563
1564 ;;;; Verbatim
1565
1566 (defun org-texinfo-verbatim (verbatim _contents info)
1567   "Transcode a VERBATIM object from Org to Texinfo.
1568 CONTENTS is nil.  INFO is a plist used as a communication
1569 channel."
1570   (org-texinfo--text-markup
1571    (org-element-property :value verbatim) 'verbatim info))
1572
1573 ;;;; Verse Block
1574
1575 (defun org-texinfo-verse-block (_verse-block contents _info)
1576   "Transcode a VERSE-BLOCK element from Org to Texinfo.
1577 CONTENTS is verse block contents. INFO is a plist holding
1578 contextual information."
1579   (format "@display\n%s@end display" contents))
1580
1581
1582 ;;; Interactive functions
1583
1584 ;;;###autoload
1585 (defun org-texinfo-export-to-texinfo
1586   (&optional async subtreep visible-only body-only ext-plist)
1587   "Export current buffer to a Texinfo file.
1588
1589 If narrowing is active in the current buffer, only export its
1590 narrowed part.
1591
1592 If a region is active, export that region.
1593
1594 A non-nil optional argument ASYNC means the process should happen
1595 asynchronously.  The resulting file should be accessible through
1596 the `org-export-stack' interface.
1597
1598 When optional argument SUBTREEP is non-nil, export the sub-tree
1599 at point, extracting information from the headline properties
1600 first.
1601
1602 When optional argument VISIBLE-ONLY is non-nil, don't export
1603 contents of hidden elements.
1604
1605 When optional argument BODY-ONLY is non-nil, only write code
1606 between \"\\begin{document}\" and \"\\end{document}\".
1607
1608 EXT-PLIST, when provided, is a property list with external
1609 parameters overriding Org default settings, but still inferior to
1610 file-local settings.
1611
1612 Return output file's name."
1613   (interactive)
1614   (let ((outfile (org-export-output-file-name ".texi" subtreep))
1615     (org-export-coding-system org-texinfo-coding-system))
1616     (org-export-to-file 'texinfo outfile
1617       async subtreep visible-only body-only ext-plist)))
1618
1619 ;;;###autoload
1620 (defun org-texinfo-export-to-info
1621   (&optional async subtreep visible-only body-only ext-plist)
1622   "Export current buffer to Texinfo then process through to INFO.
1623
1624 If narrowing is active in the current buffer, only export its
1625 narrowed part.
1626
1627 If a region is active, export that region.
1628
1629 A non-nil optional argument ASYNC means the process should happen
1630 asynchronously.  The resulting file should be accessible through
1631 the `org-export-stack' interface.
1632
1633 When optional argument SUBTREEP is non-nil, export the sub-tree
1634 at point, extracting information from the headline properties
1635 first.
1636
1637 When optional argument VISIBLE-ONLY is non-nil, don't export
1638 contents of hidden elements.
1639
1640 When optional argument BODY-ONLY is non-nil, only write code
1641 between \"\\begin{document}\" and \"\\end{document}\".
1642
1643 EXT-PLIST, when provided, is a property list with external
1644 parameters overriding Org default settings, but still inferior to
1645 file-local settings.
1646
1647 When optional argument PUB-DIR is set, use it as the publishing
1648 directory.
1649
1650 Return INFO file's name."
1651   (interactive)
1652   (let ((outfile (org-export-output-file-name ".texi" subtreep))
1653     (org-export-coding-system org-texinfo-coding-system))
1654     (org-export-to-file 'texinfo outfile
1655       async subtreep visible-only body-only ext-plist
1656       (lambda (file) (org-texinfo-compile file)))))
1657
1658 ;;;###autoload
1659 (defun org-texinfo-publish-to-texinfo (plist filename pub-dir)
1660   "Publish an org file to Texinfo.
1661
1662 FILENAME is the filename of the Org file to be published.  PLIST
1663 is the property list for the given project.  PUB-DIR is the
1664 publishing directory.
1665
1666 Return output file name."
1667   (org-publish-org-to 'texinfo filename ".texi" plist pub-dir))
1668
1669 ;;;###autoload
1670 (defun org-texinfo-convert-region-to-texinfo ()
1671   "Assume the current region has Org syntax, and convert it to Texinfo.
1672 This can be used in any buffer.  For example, you can write an
1673 itemized list in Org syntax in an Texinfo buffer and use this
1674 command to convert it."
1675   (interactive)
1676   (org-export-replace-region-by 'texinfo))
1677
1678 (defun org-texinfo-compile (file)
1679   "Compile a texinfo file.
1680
1681 FILE is the name of the file being compiled.  Processing is done
1682 through the command specified in `org-texinfo-info-process',
1683 which see.  Output is redirected to \"*Org INFO Texinfo Output*\"
1684 buffer.
1685
1686 Return INFO file name or an error if it couldn't be produced."
1687   (message "Processing Texinfo file %s..." file)
1688   (let* ((log-name "*Org INFO Texinfo Output*")
1689      (log (get-buffer-create log-name))
1690      (output
1691       (org-compile-file file org-texinfo-info-process "info"
1692                 (format "See %S for details" log-name)
1693                 log)))
1694     (when org-texinfo-remove-logfiles
1695       (let ((base (file-name-sans-extension output)))
1696     (dolist (ext org-texinfo-logfiles-extensions)
1697       (let ((file (concat base "." ext)))
1698         (when (file-exists-p file) (delete-file file))))))
1699     (message "Process completed.")
1700     output))
1701
1702
1703 (provide 'ox-texinfo)
1704
1705 ;; Local variables:
1706 ;; generated-autoload-file: "org-loaddefs.el"
1707 ;; End:
1708
1709 ;;; ox-texinfo.el ends here