ox-publish.el 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. ;;; ox-publish.el --- Publish Related Org Mode Files as a Website -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2006-2022 Free Software Foundation, Inc.
  3. ;; Author: David O'Toole <dto@gnu.org>
  4. ;; Maintainer: Nicolas Goaziou <mail@nicolasgoaziou.fr>
  5. ;; Keywords: hypermedia, outlines, wp
  6. ;; This file is part of GNU Emacs.
  7. ;;
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; This program allow configurable publishing of related sets of
  20. ;; Org mode files as a complete website.
  21. ;;
  22. ;; ox-publish.el can do the following:
  23. ;;
  24. ;; + Publish all one's Org files to a given export back-end
  25. ;; + Upload HTML, images, attachments and other files to a web server
  26. ;; + Exclude selected private pages from publishing
  27. ;; + Publish a clickable sitemap of pages
  28. ;; + Manage local timestamps for publishing only changed files
  29. ;; + Accept plugin functions to extend range of publishable content
  30. ;;
  31. ;; Documentation for publishing is in the manual.
  32. ;;; Code:
  33. (require 'org-macs)
  34. (org-assert-version)
  35. (require 'cl-lib)
  36. (require 'format-spec)
  37. (require 'ox)
  38. (declare-function org-at-heading-p "org" (&optional _))
  39. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  40. (declare-function org-next-visible-heading "org" (arg))
  41. ;;; Variables
  42. ;; Here, so you find the variable right before it's used the first time:
  43. (defvar org-publish-cache nil
  44. "This will cache timestamps and titles for files in publishing projects.
  45. Blocks could hash sha1 values here.")
  46. (defvar org-publish-after-publishing-hook nil
  47. "Hook run each time a file is published.
  48. Every function in this hook will be called with two arguments:
  49. the name of the original file and the name of the file
  50. produced.")
  51. (defgroup org-export-publish nil
  52. "Options for publishing a set of files."
  53. :tag "Org Publishing"
  54. :group 'org-export)
  55. (defcustom org-publish-project-alist nil
  56. "Association list to control publishing behavior.
  57. \\<org-mode-map>
  58. Each element of the alist is a publishing project. The car of
  59. each element is a string, uniquely identifying the project. The
  60. cdr of each element is in one of the following forms:
  61. 1. A well-formed property list with an even number of elements,
  62. alternating keys and values, specifying parameters for the
  63. publishing process.
  64. (:property value :property value ... )
  65. 2. A meta-project definition, specifying of a list of
  66. sub-projects:
  67. (:components (\"project-1\" \"project-2\" ...))
  68. When the CDR of an element of org-publish-project-alist is in
  69. this second form, the elements of the list after `:components'
  70. are taken to be components of the project, which group together
  71. files requiring different publishing options. When you publish
  72. such a project with `\\[org-publish]', the components all publish.
  73. When a property is given a value in `org-publish-project-alist',
  74. its setting overrides the value of the corresponding user
  75. variable (if any) during publishing. However, options set within
  76. a file override everything.
  77. Most properties are optional, but some should always be set:
  78. `:base-directory'
  79. Directory containing publishing source files.
  80. `:base-extension'
  81. Extension (without the dot!) of source files. This can be
  82. a regular expression. If not given, \"org\" will be used as
  83. default extension. If it is `any', include all the files,
  84. even without extension.
  85. `:publishing-directory'
  86. Directory (possibly remote) where output files will be
  87. published.
  88. If `:recursive' is non-nil files in sub-directories of
  89. `:base-directory' are considered.
  90. The `:exclude' property may be used to prevent certain files from
  91. being published. Its value may be a string or regexp matching
  92. file names you don't want to be published.
  93. The `:include' property may be used to include extra files. Its
  94. value may be a list of filenames to include. The filenames are
  95. considered relative to the base directory.
  96. When both `:include' and `:exclude' properties are given values,
  97. the exclusion step happens first.
  98. One special property controls which back-end function to use for
  99. publishing files in the project. This can be used to extend the
  100. set of file types publishable by `org-publish', as well as the
  101. set of output formats.
  102. `:publishing-function'
  103. Function to publish file. Each back-end may define its
  104. own (i.e. `org-latex-publish-to-pdf',
  105. `org-html-publish-to-html'). May be a list of functions, in
  106. which case each function in the list is invoked in turn.
  107. Another property allows you to insert code that prepares
  108. a project for publishing. For example, you could call GNU Make
  109. on a certain makefile, to ensure published files are built up to
  110. date.
  111. `:preparation-function'
  112. Function to be called before publishing this project. This
  113. may also be a list of functions. Preparation functions are
  114. called with the project properties list as their sole
  115. argument.
  116. `:completion-function'
  117. Function to be called after publishing this project. This
  118. may also be a list of functions. Completion functions are
  119. called with the project properties list as their sole
  120. argument.
  121. Some properties control details of the Org publishing process,
  122. and are equivalent to the corresponding user variables listed in
  123. the right column. Back-end specific properties may also be
  124. included. See the back-end documentation for more information.
  125. :author `user-full-name'
  126. :creator `org-export-creator-string'
  127. :email `user-mail-address'
  128. :exclude-tags `org-export-exclude-tags'
  129. :headline-levels `org-export-headline-levels'
  130. :language `org-export-default-language'
  131. :preserve-breaks `org-export-preserve-breaks'
  132. :section-numbers `org-export-with-section-numbers'
  133. :select-tags `org-export-select-tags'
  134. :time-stamp-file `org-export-time-stamp-file'
  135. :with-archived-trees `org-export-with-archived-trees'
  136. :with-author `org-export-with-author'
  137. :with-creator `org-export-with-creator'
  138. :with-date `org-export-with-date'
  139. :with-drawers `org-export-with-drawers'
  140. :with-email `org-export-with-email'
  141. :with-emphasize `org-export-with-emphasize'
  142. :with-entities `org-export-with-entities'
  143. :with-fixed-width `org-export-with-fixed-width'
  144. :with-footnotes `org-export-with-footnotes'
  145. :with-inlinetasks `org-export-with-inlinetasks'
  146. :with-latex `org-export-with-latex'
  147. :with-planning `org-export-with-planning'
  148. :with-priority `org-export-with-priority'
  149. :with-properties `org-export-with-properties'
  150. :with-smart-quotes `org-export-with-smart-quotes'
  151. :with-special-strings `org-export-with-special-strings'
  152. :with-statistics-cookies' `org-export-with-statistics-cookies'
  153. :with-sub-superscript `org-export-with-sub-superscripts'
  154. :with-toc `org-export-with-toc'
  155. :with-tables `org-export-with-tables'
  156. :with-tags `org-export-with-tags'
  157. :with-tasks `org-export-with-tasks'
  158. :with-timestamps `org-export-with-timestamps'
  159. :with-title `org-export-with-title'
  160. :with-todo-keywords `org-export-with-todo-keywords'
  161. The following properties may be used to control publishing of
  162. a site-map of files or summary page for a given project.
  163. `:auto-sitemap'
  164. Whether to publish a site-map during
  165. `org-publish-current-project' or `org-publish-all'.
  166. `:sitemap-filename'
  167. Filename for output of site-map. Defaults to \"sitemap.org\".
  168. `:sitemap-title'
  169. Title of site-map page. Defaults to name of file.
  170. `:sitemap-style'
  171. Can be `list' (site-map is just an itemized list of the
  172. titles of the files involved) or `tree' (the directory
  173. structure of the source files is reflected in the site-map).
  174. Defaults to `tree'.
  175. `:sitemap-format-entry'
  176. Plugin function used to format entries in the site-map. It
  177. is called with three arguments: the file or directory name
  178. relative to base directory, the site map style and the
  179. current project. It has to return a string.
  180. Defaults to `org-publish-sitemap-default-entry', which turns
  181. file names into links and use document titles as
  182. descriptions. For specific formatting needs, one can use
  183. `org-publish-find-date', `org-publish-find-title' and
  184. `org-publish-find-property', to retrieve additional
  185. information about published documents.
  186. `:sitemap-function'
  187. Plugin function to use for generation of site-map. It is
  188. called with two arguments: the title of the site-map, as
  189. a string, and a representation of the files involved in the
  190. project, as returned by `org-list-to-lisp'. The latter can
  191. further be transformed using `org-list-to-generic',
  192. `org-list-to-subtree' and alike. It has to return a string.
  193. Defaults to `org-publish-sitemap-default', which generates
  194. a plain list of links to all files in the project.
  195. If you create a site-map file, adjust the sorting like this:
  196. `:sitemap-sort-folders'
  197. Where folders should appear in the site-map. Set this to
  198. `first' or `last' to display folders first or last,
  199. respectively. When set to `ignore' (default), folders are
  200. ignored altogether. Any other value will mix files and
  201. folders. This variable has no effect when site-map style is
  202. `tree'.
  203. `:sitemap-sort-files'
  204. The site map is normally sorted alphabetically. You can
  205. change this behavior setting this to `anti-chronologically',
  206. `chronologically', or nil.
  207. `:sitemap-ignore-case'
  208. Should sorting be case-sensitive? Default nil.
  209. The following property control the creation of a concept index.
  210. `:makeindex'
  211. Create a concept index. The file containing the index has to
  212. be called \"theindex.org\". If it doesn't exist in the
  213. project, it will be generated. Contents of the index are
  214. stored in the file \"theindex.inc\", which can be included in
  215. \"theindex.org\".
  216. Other properties affecting publication.
  217. `:body-only'
  218. Set this to t to publish only the body of the documents."
  219. :group 'org-export-publish
  220. :type 'alist)
  221. (defcustom org-publish-use-timestamps-flag t
  222. "Non-nil means use timestamp checking to publish only changed files.
  223. When nil, do no timestamp checking and always publish all files."
  224. :group 'org-export-publish
  225. :type 'boolean)
  226. (defcustom org-publish-timestamp-directory
  227. (convert-standard-filename "~/.org-timestamps/")
  228. "Name of directory in which to store publishing timestamps."
  229. :group 'org-export-publish
  230. :type 'directory)
  231. (defcustom org-publish-list-skipped-files t
  232. "Non-nil means show message about files *not* published."
  233. :group 'org-export-publish
  234. :type 'boolean)
  235. (defcustom org-publish-sitemap-sort-files 'alphabetically
  236. "Method to sort files in site-maps.
  237. Possible values are `alphabetically', `chronologically',
  238. `anti-chronologically' and nil.
  239. If `alphabetically', files will be sorted alphabetically. If
  240. `chronologically', files will be sorted with older modification
  241. time first. If `anti-chronologically', files will be sorted with
  242. newer modification time first. nil won't sort files.
  243. You can overwrite this default per project in your
  244. `org-publish-project-alist', using `:sitemap-sort-files'."
  245. :group 'org-export-publish
  246. :type 'symbol)
  247. (defcustom org-publish-sitemap-sort-folders 'ignore
  248. "A symbol, denoting if folders are sorted first in site-maps.
  249. Possible values are `first', `last', `ignore' and nil.
  250. If `first', folders will be sorted before files.
  251. If `last', folders are sorted to the end after the files.
  252. If `ignore', folders do not appear in the site-map.
  253. Any other value will mix files and folders.
  254. You can overwrite this default per project in your
  255. `org-publish-project-alist', using `:sitemap-sort-folders'.
  256. This variable is ignored when site-map style is `tree'."
  257. :group 'org-export-publish
  258. :type '(choice
  259. (const :tag "Folders before files" first)
  260. (const :tag "Folders after files" last)
  261. (const :tag "No folder in site-map" ignore)
  262. (const :tag "Mix folders and files" nil))
  263. :version "26.1"
  264. :package-version '(Org . "9.1")
  265. :safe #'symbolp)
  266. (defcustom org-publish-sitemap-sort-ignore-case nil
  267. "Non-nil when site-map sorting should ignore case.
  268. You can overwrite this default per project in your
  269. `org-publish-project-alist', using `:sitemap-ignore-case'."
  270. :group 'org-export-publish
  271. :type 'boolean)
  272. ;;; Timestamp-related functions
  273. (defun org-publish-timestamp-filename (filename &optional pub-dir pub-func)
  274. "Return path to timestamp file for filename FILENAME."
  275. (setq filename (concat filename "::" (or pub-dir "") "::"
  276. (format "%s" (or pub-func ""))))
  277. (concat "X" (if (fboundp 'sha1) (sha1 filename) (md5 filename))))
  278. (defun org-publish-needed-p
  279. (filename &optional pub-dir pub-func _true-pub-dir base-dir)
  280. "Non-nil if FILENAME should be published in PUB-DIR using PUB-FUNC.
  281. TRUE-PUB-DIR is where the file will truly end up. Currently we
  282. are not using this - maybe it can eventually be used to check if
  283. the file is present at the target location, and how old it is.
  284. Right now we cannot do this, because we do not know under what
  285. file name the file will be stored - the publishing function can
  286. still decide about that independently."
  287. (let ((rtn (if (not org-publish-use-timestamps-flag) t
  288. (org-publish-cache-file-needs-publishing
  289. filename pub-dir pub-func base-dir))))
  290. (if rtn (message "Publishing file %s using `%s'" filename pub-func)
  291. (when org-publish-list-skipped-files
  292. (message "Skipping unmodified file %s" filename)))
  293. rtn))
  294. (defun org-publish-update-timestamp
  295. (filename &optional pub-dir pub-func _base-dir)
  296. "Update publishing timestamp for file FILENAME.
  297. If there is no timestamp, create one."
  298. (let ((key (org-publish-timestamp-filename filename pub-dir pub-func))
  299. (stamp (org-publish-cache-mtime-of-src filename)))
  300. (org-publish-cache-set key stamp)))
  301. (defun org-publish-remove-all-timestamps ()
  302. "Remove all files in the timestamp directory."
  303. (let ((dir org-publish-timestamp-directory))
  304. (when (and (file-exists-p dir) (file-directory-p dir))
  305. (mapc #'delete-file (directory-files dir 'full "[^.]\\'"))
  306. (org-publish-reset-cache))))
  307. ;;; Getting project information out of `org-publish-project-alist'
  308. (defun org-publish-property (property project &optional default)
  309. "Return value PROPERTY, as a symbol, in PROJECT.
  310. DEFAULT is returned when PROPERTY is not actually set in PROJECT
  311. definition."
  312. (let ((properties (cdr project)))
  313. (if (plist-member properties property)
  314. (plist-get properties property)
  315. default)))
  316. (defun org-publish--expand-file-name (file project)
  317. "Return full file name for FILE in PROJECT.
  318. When FILE is a relative file name, it is expanded according to
  319. project base directory."
  320. (if (file-name-absolute-p file) file
  321. (expand-file-name file (org-publish-property :base-directory project))))
  322. (defun org-publish-expand-projects (projects-alist)
  323. "Expand projects in PROJECTS-ALIST.
  324. This splices all the components into the list."
  325. (let ((rest projects-alist) rtn p components)
  326. (while (setq p (pop rest))
  327. (if (setq components (plist-get (cdr p) :components))
  328. (setq rest (append
  329. (mapcar
  330. (lambda (x)
  331. (or (assoc x org-publish-project-alist)
  332. (user-error "Unknown component %S in project %S"
  333. x (car p))))
  334. components)
  335. rest))
  336. (push p rtn)))
  337. (nreverse (delete-dups (delq nil rtn)))))
  338. (defun org-publish-get-base-files (project)
  339. "Return a list of all files in PROJECT."
  340. (let* ((base-dir (file-name-as-directory
  341. (org-publish-property :base-directory project)))
  342. (extension (or (org-publish-property :base-extension project) "org"))
  343. (match (if (eq extension 'any) ""
  344. (format "^[^\\.].*\\.\\(%s\\)$" extension)))
  345. (base-files
  346. (cond ((not (file-exists-p base-dir)) nil)
  347. ((not (org-publish-property :recursive project))
  348. (cl-remove-if #'file-directory-p
  349. (directory-files base-dir t match t)))
  350. (t
  351. ;; Find all files recursively. Unlike to
  352. ;; `directory-files-recursively', we follow symlinks
  353. ;; to other directories.
  354. (letrec ((files nil)
  355. (walk-tree
  356. (lambda (dir depth)
  357. (when (> depth 100)
  358. (error "Apparent cycle of symbolic links for %S"
  359. base-dir))
  360. (dolist (f (file-name-all-completions "" dir))
  361. (pcase f
  362. ((or "./" "../") nil)
  363. ((pred directory-name-p)
  364. (funcall walk-tree
  365. (expand-file-name f dir)
  366. (1+ depth)))
  367. ((pred (string-match match))
  368. (push (expand-file-name f dir) files))
  369. (_ nil)))
  370. files)))
  371. (funcall walk-tree base-dir 0))))))
  372. (org-uniquify
  373. (append
  374. ;; Files from BASE-DIR. Apply exclusion filter before adding
  375. ;; included files.
  376. (let ((exclude-regexp (org-publish-property :exclude project)))
  377. (if exclude-regexp
  378. (cl-remove-if
  379. (lambda (f)
  380. ;; Match against relative names, yet BASE-DIR file
  381. ;; names are absolute.
  382. (string-match exclude-regexp
  383. (file-relative-name f base-dir)))
  384. base-files)
  385. base-files))
  386. ;; Sitemap file.
  387. (and (org-publish-property :auto-sitemap project)
  388. (list (expand-file-name
  389. (or (org-publish-property :sitemap-filename project)
  390. "sitemap.org")
  391. base-dir)))
  392. ;; Included files.
  393. (mapcar (lambda (f) (expand-file-name f base-dir))
  394. (org-publish-property :include project))))))
  395. (defun org-publish-get-project-from-filename (filename &optional up)
  396. "Return a project that FILENAME belongs to.
  397. When UP is non-nil, return a meta-project (i.e., with a :components part)
  398. publishing FILENAME."
  399. (let* ((filename (expand-file-name filename))
  400. (project
  401. (cl-some
  402. (lambda (p)
  403. ;; Ignore meta-projects.
  404. (unless (org-publish-property :components p)
  405. (let ((base (expand-file-name
  406. (org-publish-property :base-directory p))))
  407. (cond
  408. ;; Check if FILENAME is explicitly included in one
  409. ;; project.
  410. ((cl-some (lambda (f) (file-equal-p f filename))
  411. (mapcar (lambda (f) (expand-file-name f base))
  412. (org-publish-property :include p)))
  413. p)
  414. ;; Exclude file names matching :exclude property.
  415. ((let ((exclude-re (org-publish-property :exclude p)))
  416. (and exclude-re
  417. (string-match-p exclude-re
  418. (file-relative-name filename base))))
  419. nil)
  420. ;; Check :extension. Handle special `any'
  421. ;; extension.
  422. ((let ((extension (org-publish-property :base-extension p)))
  423. (not (or (eq extension 'any)
  424. (string= (or extension "org")
  425. (file-name-extension filename)))))
  426. nil)
  427. ;; Check if FILENAME belong to project's base
  428. ;; directory, or some of its sub-directories
  429. ;; if :recursive in non-nil.
  430. ((member filename (org-publish-get-base-files p)) p)
  431. (t nil)))))
  432. org-publish-project-alist)))
  433. (cond
  434. ((not project) nil)
  435. ((not up) project)
  436. ;; When optional argument UP is non-nil, return the top-most
  437. ;; meta-project effectively publishing FILENAME.
  438. (t
  439. (letrec ((find-parent-project
  440. (lambda (project)
  441. (or (cl-some
  442. (lambda (p)
  443. (and (member (car project)
  444. (org-publish-property :components p))
  445. (funcall find-parent-project p)))
  446. org-publish-project-alist)
  447. project))))
  448. (funcall find-parent-project project))))))
  449. ;;; Tools for publishing functions in back-ends
  450. (defun org-publish-org-to (backend filename extension plist &optional pub-dir)
  451. "Publish an Org file to a specified back-end.
  452. BACKEND is a symbol representing the back-end used for
  453. transcoding. FILENAME is the filename of the Org file to be
  454. published. EXTENSION is the extension used for the output
  455. string, with the leading dot. PLIST is the property list for the
  456. given project.
  457. Optional argument PUB-DIR, when non-nil is the publishing
  458. directory.
  459. Return output file name."
  460. (unless (or (not pub-dir) (file-exists-p pub-dir)) (make-directory pub-dir t))
  461. ;; Check if a buffer visiting FILENAME is already open.
  462. (let* ((org-inhibit-startup t)
  463. (visiting (find-buffer-visiting filename))
  464. (work-buffer (or visiting (find-file-noselect filename))))
  465. (unwind-protect
  466. (with-current-buffer work-buffer
  467. (let ((output (org-export-output-file-name extension nil pub-dir)))
  468. (org-export-to-file backend output
  469. nil nil nil (plist-get plist :body-only)
  470. ;; Add `org-publish--store-crossrefs' and
  471. ;; `org-publish-collect-index' to final output filters.
  472. ;; The latter isn't dependent on `:makeindex', since we
  473. ;; want to keep it up-to-date in cache anyway.
  474. (org-combine-plists
  475. plist
  476. `(:crossrefs
  477. ,(org-publish-cache-get-file-property
  478. ;; Normalize file names in cache.
  479. (file-truename filename) :crossrefs nil t)
  480. :filter-final-output
  481. (org-publish--store-crossrefs
  482. org-publish-collect-index
  483. ,@(plist-get plist :filter-final-output)))))))
  484. ;; Remove opened buffer in the process.
  485. (unless visiting (kill-buffer work-buffer)))))
  486. (defun org-publish-attachment (_plist filename pub-dir)
  487. "Publish a file with no transformation of any kind.
  488. FILENAME is the filename of the Org file to be published. PLIST
  489. is the property list for the given project. PUB-DIR is the
  490. publishing directory.
  491. Return output file name."
  492. (unless (file-directory-p pub-dir)
  493. (make-directory pub-dir t))
  494. (let ((output (expand-file-name (file-name-nondirectory filename) pub-dir)))
  495. (unless (file-equal-p (expand-file-name (file-name-directory filename))
  496. (file-name-as-directory (expand-file-name pub-dir)))
  497. (copy-file filename output t))
  498. ;; Return file name.
  499. output))
  500. ;;; Publishing files, sets of files
  501. (defun org-publish-file (filename &optional project no-cache)
  502. "Publish file FILENAME from PROJECT.
  503. If NO-CACHE is not nil, do not initialize `org-publish-cache'.
  504. This is needed, since this function is used to publish single
  505. files, when entire projects are published (see
  506. `org-publish-projects')."
  507. (let* ((project
  508. (or project
  509. (org-publish-get-project-from-filename filename)
  510. (user-error "File %S is not part of any known project"
  511. (abbreviate-file-name filename))))
  512. (project-plist (cdr project))
  513. (publishing-function
  514. (pcase (org-publish-property :publishing-function project
  515. 'org-html-publish-to-html)
  516. (`nil (user-error "No publishing function chosen"))
  517. ((and f (pred listp)) f)
  518. (f (list f))))
  519. (base-dir
  520. (file-name-as-directory
  521. (or (org-publish-property :base-directory project)
  522. (user-error "Project %S does not have :base-directory defined"
  523. (car project)))))
  524. (pub-base-dir
  525. (file-name-as-directory
  526. (or (org-publish-property :publishing-directory project)
  527. (user-error
  528. "Project %S does not have :publishing-directory defined"
  529. (car project)))))
  530. (pub-dir
  531. (file-name-directory
  532. (expand-file-name (file-relative-name filename base-dir)
  533. pub-base-dir))))
  534. (unless no-cache (org-publish-initialize-cache (car project)))
  535. ;; Allow chain of publishing functions.
  536. (dolist (f publishing-function)
  537. (when (org-publish-needed-p filename pub-base-dir f pub-dir base-dir)
  538. (let ((output (funcall f project-plist filename pub-dir)))
  539. (org-publish-update-timestamp filename pub-base-dir f base-dir)
  540. (run-hook-with-args 'org-publish-after-publishing-hook
  541. filename
  542. output))))
  543. ;; Make sure to write cache to file after successfully publishing
  544. ;; a file, so as to minimize impact of a publishing failure.
  545. (org-publish-write-cache-file)))
  546. (defun org-publish-projects (projects)
  547. "Publish all files belonging to the PROJECTS alist.
  548. If `:auto-sitemap' is set, publish the sitemap too. If
  549. `:makeindex' is set, also produce a file \"theindex.org\"."
  550. (dolist (project (org-publish-expand-projects projects))
  551. (let ((plist (cdr project)))
  552. (let ((fun (org-publish-property :preparation-function project)))
  553. (cond
  554. ((functionp fun) (funcall fun plist))
  555. ((consp fun) (dolist (f fun) (funcall f plist)))))
  556. ;; Each project uses its own cache file.
  557. (org-publish-initialize-cache (car project))
  558. (when (org-publish-property :auto-sitemap project)
  559. (let ((sitemap-filename
  560. (or (org-publish-property :sitemap-filename project)
  561. "sitemap.org")))
  562. (org-publish-sitemap project sitemap-filename)))
  563. ;; Publish all files from PROJECT except "theindex.org". Its
  564. ;; publishing will be deferred until "theindex.inc" is
  565. ;; populated.
  566. (let ((theindex
  567. (expand-file-name "theindex.org"
  568. (org-publish-property :base-directory project))))
  569. (dolist (file (org-publish-get-base-files project))
  570. (unless (file-equal-p file theindex)
  571. (org-publish-file file project t)))
  572. ;; Populate "theindex.inc", if needed, and publish
  573. ;; "theindex.org".
  574. (when (org-publish-property :makeindex project)
  575. (org-publish-index-generate-theindex
  576. project (org-publish-property :base-directory project))
  577. (org-publish-file theindex project t)))
  578. (let ((fun (org-publish-property :completion-function project)))
  579. (cond
  580. ((functionp fun) (funcall fun plist))
  581. ((consp fun) (dolist (f fun) (funcall f plist))))))
  582. (org-publish-write-cache-file)))
  583. ;;; Site map generation
  584. (defun org-publish--sitemap-files-to-lisp (files project style format-entry)
  585. "Represent FILES as a parsed plain list.
  586. FILES is the list of files in the site map. PROJECT is the
  587. current project. STYLE determines is either `list' or `tree'.
  588. FORMAT-ENTRY is a function called on each file which should
  589. return a string. Return value is a list as returned by
  590. `org-list-to-lisp'."
  591. (let ((root (expand-file-name
  592. (file-name-as-directory
  593. (org-publish-property :base-directory project)))))
  594. (pcase style
  595. (`list
  596. (cons 'unordered
  597. (mapcar
  598. (lambda (f)
  599. (list (funcall format-entry
  600. (file-relative-name f root)
  601. style
  602. project)))
  603. files)))
  604. (`tree
  605. (letrec ((files-only (cl-remove-if #'directory-name-p files))
  606. (directories (cl-remove-if-not #'directory-name-p files))
  607. (subtree-to-list
  608. (lambda (dir)
  609. (cons 'unordered
  610. (nconc
  611. ;; Files in DIR.
  612. (mapcar
  613. (lambda (f)
  614. (list (funcall format-entry
  615. (file-relative-name f root)
  616. style
  617. project)))
  618. (cl-remove-if-not
  619. (lambda (f) (string= dir (file-name-directory f)))
  620. files-only))
  621. ;; Direct sub-directories.
  622. (mapcar
  623. (lambda (sub)
  624. (list (funcall format-entry
  625. (file-relative-name sub root)
  626. style
  627. project)
  628. (funcall subtree-to-list sub)))
  629. (cl-remove-if-not
  630. (lambda (f)
  631. (string=
  632. dir
  633. ;; Parent directory.
  634. (file-name-directory (directory-file-name f))))
  635. directories)))))))
  636. (funcall subtree-to-list root)))
  637. (_ (user-error "Unknown site-map style: `%s'" style)))))
  638. (defun org-publish-sitemap (project &optional sitemap-filename)
  639. "Create a sitemap of pages in set defined by PROJECT.
  640. Optionally set the filename of the sitemap with SITEMAP-FILENAME.
  641. Default for SITEMAP-FILENAME is `sitemap.org'."
  642. (let* ((root (expand-file-name
  643. (file-name-as-directory
  644. (org-publish-property :base-directory project))))
  645. (sitemap-filename (expand-file-name (or sitemap-filename "sitemap.org")
  646. root))
  647. (title (or (org-publish-property :sitemap-title project)
  648. (concat "Sitemap for project " (car project))))
  649. (style (or (org-publish-property :sitemap-style project)
  650. 'tree))
  651. (sitemap-builder (or (org-publish-property :sitemap-function project)
  652. #'org-publish-sitemap-default))
  653. (format-entry (or (org-publish-property :sitemap-format-entry project)
  654. #'org-publish-sitemap-default-entry))
  655. (sort-folders
  656. (org-publish-property :sitemap-sort-folders project
  657. org-publish-sitemap-sort-folders))
  658. (sort-files
  659. (org-publish-property :sitemap-sort-files project
  660. org-publish-sitemap-sort-files))
  661. (ignore-case
  662. (org-publish-property :sitemap-ignore-case project
  663. org-publish-sitemap-sort-ignore-case))
  664. (org-file-p (lambda (f) (equal "org" (file-name-extension f))))
  665. (sort-predicate
  666. (lambda (a b)
  667. (let ((retval t))
  668. ;; First we sort files:
  669. (pcase sort-files
  670. (`alphabetically
  671. (let ((A (if (funcall org-file-p a)
  672. (concat (file-name-directory a)
  673. (org-publish-find-title a project))
  674. a))
  675. (B (if (funcall org-file-p b)
  676. (concat (file-name-directory b)
  677. (org-publish-find-title b project))
  678. b)))
  679. (setq retval
  680. (if ignore-case
  681. (not (string-lessp (upcase B) (upcase A)))
  682. (not (string-lessp B A))))))
  683. ((or `anti-chronologically `chronologically)
  684. (let* ((adate (org-publish-find-date a project))
  685. (bdate (org-publish-find-date b project)))
  686. (setq retval
  687. (not (if (eq sort-files 'chronologically)
  688. (time-less-p bdate adate)
  689. (time-less-p adate bdate))))))
  690. (`nil nil)
  691. (_ (user-error "Invalid sort value %s" sort-files)))
  692. ;; Directory-wise wins:
  693. (when (memq sort-folders '(first last))
  694. ;; a is directory, b not:
  695. (cond
  696. ((and (file-directory-p a) (not (file-directory-p b)))
  697. (setq retval (eq sort-folders 'first)))
  698. ;; a is not a directory, but b is:
  699. ((and (not (file-directory-p a)) (file-directory-p b))
  700. (setq retval (eq sort-folders 'last)))))
  701. retval))))
  702. (message "Generating sitemap for %s" title)
  703. (with-temp-file sitemap-filename
  704. (insert
  705. (let ((files (remove sitemap-filename
  706. (org-publish-get-base-files project))))
  707. ;; Add directories, if applicable.
  708. (unless (and (eq style 'list) (eq sort-folders 'ignore))
  709. (setq files
  710. (nconc (remove root (org-uniquify
  711. (mapcar #'file-name-directory files)))
  712. files)))
  713. ;; Eventually sort all entries.
  714. (when (or sort-files (not (memq sort-folders 'ignore)))
  715. (setq files (sort files sort-predicate)))
  716. (funcall sitemap-builder
  717. title
  718. (org-publish--sitemap-files-to-lisp
  719. files project style format-entry)))))))
  720. (defun org-publish-find-property (file property project &optional backend)
  721. "Find the PROPERTY of FILE in project.
  722. PROPERTY is a keyword referring to an export option, as defined
  723. in `org-export-options-alist' or in export back-ends. In the
  724. latter case, optional argument BACKEND has to be set to the
  725. back-end where the option is defined, e.g.,
  726. (org-publish-find-property file :subtitle \\='latex)
  727. Return value may be a string or a list, depending on the type of
  728. PROPERTY, i.e. \"behavior\" parameter from `org-export-options-alist'."
  729. (let ((file (org-publish--expand-file-name file project)))
  730. (when (and (file-readable-p file) (not (directory-name-p file)))
  731. (let* ((org-inhibit-startup t)
  732. (visiting (find-buffer-visiting file))
  733. (buffer (or visiting (find-file-noselect file))))
  734. (unwind-protect
  735. (plist-get (with-current-buffer buffer
  736. (if (not visiting) (org-export-get-environment backend)
  737. ;; Protect local variables in open buffers.
  738. (org-export-with-buffer-copy
  739. (org-export-get-environment backend))))
  740. property)
  741. (unless visiting (kill-buffer buffer)))))))
  742. (defun org-publish-find-title (file project)
  743. "Find the title of FILE in PROJECT."
  744. (let ((file (org-publish--expand-file-name file project)))
  745. (or (org-publish-cache-get-file-property file :title nil t)
  746. (let* ((parsed-title (org-publish-find-property file :title project))
  747. (title
  748. (if parsed-title
  749. ;; Remove property so that the return value is
  750. ;; cache-able (i.e., it can be `read' back).
  751. (org-no-properties
  752. (org-element-interpret-data parsed-title))
  753. (file-name-nondirectory (file-name-sans-extension file)))))
  754. (org-publish-cache-set-file-property file :title title)))))
  755. (defun org-publish-find-date (file project)
  756. "Find the date of FILE in PROJECT.
  757. This function assumes FILE is either a directory or an Org file.
  758. If FILE is an Org file and provides a DATE keyword use it. In
  759. any other case use the file system's modification time. Return
  760. time in `current-time' format."
  761. (let ((file (org-publish--expand-file-name file project)))
  762. (or (org-publish-cache-get-file-property file :date nil t)
  763. (org-publish-cache-set-file-property
  764. file :date
  765. (if (file-directory-p file)
  766. (file-attribute-modification-time (file-attributes file))
  767. (let ((date (org-publish-find-property file :date project)))
  768. ;; DATE is a secondary string. If it contains
  769. ;; a time-stamp, convert it to internal format.
  770. ;; Otherwise, use FILE modification time.
  771. (cond ((let ((ts (and (consp date) (assq 'timestamp date))))
  772. (and ts
  773. (let ((value (org-element-interpret-data ts)))
  774. (and (org-string-nw-p value)
  775. (org-time-string-to-time value))))))
  776. ((file-exists-p file)
  777. (file-attribute-modification-time (file-attributes file)))
  778. (t (error "No such file: \"%s\"" file)))))))))
  779. (defun org-publish-sitemap-default-entry (entry style project)
  780. "Default format for site map ENTRY, as a string.
  781. ENTRY is a file name. STYLE is the style of the sitemap.
  782. PROJECT is the current project."
  783. (cond ((not (directory-name-p entry))
  784. (format "[[file:%s][%s]]"
  785. entry
  786. (org-publish-find-title entry project)))
  787. ((eq style 'tree)
  788. ;; Return only last subdir.
  789. (file-name-nondirectory (directory-file-name entry)))
  790. (t entry)))
  791. (defun org-publish-sitemap-default (title list)
  792. "Default site map, as a string.
  793. TITLE is the title of the site map. LIST is an internal
  794. representation for the files to include, as returned by
  795. `org-list-to-lisp'. PROJECT is the current project."
  796. (concat "#+TITLE: " title "\n\n"
  797. (org-list-to-org list)))
  798. ;;; Interactive publishing functions
  799. ;;;###autoload
  800. (defalias 'org-publish-project 'org-publish)
  801. ;;;###autoload
  802. (defun org-publish (project &optional force async)
  803. "Publish PROJECT.
  804. PROJECT is either a project name, as a string, or a project
  805. alist (see `org-publish-project-alist' variable).
  806. When optional argument FORCE is non-nil, force publishing all
  807. files in PROJECT. With a non-nil optional argument ASYNC,
  808. publishing will be done asynchronously, in another process."
  809. (interactive
  810. (list (assoc (completing-read "Publish project: "
  811. org-publish-project-alist nil t)
  812. org-publish-project-alist)
  813. current-prefix-arg))
  814. (let ((project (if (not (stringp project)) project
  815. ;; If this function is called in batch mode,
  816. ;; PROJECT is still a string here.
  817. (assoc project org-publish-project-alist))))
  818. (cond
  819. ((not project))
  820. (async
  821. (org-export-async-start (lambda (_) nil)
  822. `(let ((org-publish-use-timestamps-flag
  823. ,(and (not force) org-publish-use-timestamps-flag)))
  824. ;; Expand components right now as external process may not
  825. ;; be aware of complete `org-publish-project-alist'.
  826. (org-publish-projects
  827. ',(org-publish-expand-projects (list project))))))
  828. (t (save-window-excursion
  829. (let ((org-publish-use-timestamps-flag
  830. (and (not force) org-publish-use-timestamps-flag)))
  831. (org-publish-projects (list project))))))))
  832. ;;;###autoload
  833. (defun org-publish-all (&optional force async)
  834. "Publish all projects.
  835. With prefix argument FORCE, remove all files in the timestamp
  836. directory and force publishing all projects. With a non-nil
  837. optional argument ASYNC, publishing will be done asynchronously,
  838. in another process."
  839. (interactive "P")
  840. (if async
  841. (org-export-async-start (lambda (_) nil)
  842. `(progn
  843. (when ',force (org-publish-remove-all-timestamps))
  844. (let ((org-publish-use-timestamps-flag
  845. (if ',force nil ,org-publish-use-timestamps-flag)))
  846. (org-publish-projects ',org-publish-project-alist))))
  847. (when force (org-publish-remove-all-timestamps))
  848. (save-window-excursion
  849. (let ((org-publish-use-timestamps-flag
  850. (if force nil org-publish-use-timestamps-flag)))
  851. (org-publish-projects org-publish-project-alist)))))
  852. ;;;###autoload
  853. (defun org-publish-current-file (&optional force async)
  854. "Publish the current file.
  855. With prefix argument FORCE, force publish the file. When
  856. optional argument ASYNC is non-nil, publishing will be done
  857. asynchronously, in another process."
  858. (interactive "P")
  859. (let ((file (buffer-file-name (buffer-base-buffer))))
  860. (if async
  861. (org-export-async-start (lambda (_) nil)
  862. `(let ((org-publish-use-timestamps-flag
  863. (if ',force nil ,org-publish-use-timestamps-flag)))
  864. (org-publish-file ,file)))
  865. (save-window-excursion
  866. (let ((org-publish-use-timestamps-flag
  867. (if force nil org-publish-use-timestamps-flag)))
  868. (org-publish-file file))))))
  869. ;;;###autoload
  870. (defun org-publish-current-project (&optional force async)
  871. "Publish the project associated with the current file.
  872. With a prefix argument, force publishing of all files in
  873. the project."
  874. (interactive "P")
  875. (save-window-excursion
  876. (let ((project (org-publish-get-project-from-filename
  877. (buffer-file-name (buffer-base-buffer)) 'up)))
  878. (if project (org-publish project force async)
  879. (error "File %s is not part of any known project"
  880. (buffer-file-name (buffer-base-buffer)))))))
  881. ;;; Index generation
  882. (defun org-publish-collect-index (output _backend info)
  883. "Update index for a file in cache.
  884. OUTPUT is the output from transcoding current file. BACKEND is
  885. the back-end that was used for transcoding. INFO is a plist
  886. containing publishing and export options.
  887. The index relative to current file is stored as an alist. An
  888. association has the following shape: (TERM FILE-NAME PARENT),
  889. where TERM is the indexed term, as a string, FILE-NAME is the
  890. original full path of the file where the term in encountered, and
  891. PARENT is a reference to the headline, if any, containing the
  892. original index keyword. When non-nil, this reference is a cons
  893. cell. Its CAR is a symbol among `id', `custom-id' and `name' and
  894. its CDR is a string."
  895. (let ((file (file-truename (plist-get info :input-file))))
  896. (org-publish-cache-set-file-property
  897. file :index
  898. (delete-dups
  899. (org-element-map (plist-get info :parse-tree) 'keyword
  900. (lambda (k)
  901. (when (equal (org-element-property :key k) "INDEX")
  902. (let ((parent (org-export-get-parent-headline k)))
  903. (list (org-element-property :value k)
  904. file
  905. (cond
  906. ((not parent) nil)
  907. ((let ((id (org-element-property :ID parent)))
  908. (and id (cons 'id id))))
  909. ((let ((id (org-element-property :CUSTOM_ID parent)))
  910. (and id (cons 'custom-id id))))
  911. (t (cons 'name
  912. ;; Remove statistics cookie.
  913. (replace-regexp-in-string
  914. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  915. (org-element-property :raw-value parent)))))))))
  916. info))))
  917. ;; Return output unchanged.
  918. output)
  919. (defun org-publish-index-generate-theindex (project directory)
  920. "Retrieve full index from cache and build \"theindex.org\".
  921. PROJECT is the project the index relates to. DIRECTORY is the
  922. publishing directory."
  923. (let ((all-files (org-publish-get-base-files project))
  924. full-index)
  925. ;; Compile full index and sort it alphabetically.
  926. (dolist (file all-files
  927. (setq full-index
  928. (sort (nreverse full-index)
  929. (lambda (a b) (string< (downcase (car a))
  930. (downcase (car b)))))))
  931. (let ((index (org-publish-cache-get-file-property file :index)))
  932. (dolist (term index)
  933. (unless (member term full-index) (push term full-index)))))
  934. ;; Write "theindex.inc" in DIRECTORY.
  935. (with-temp-file (expand-file-name "theindex.inc" directory)
  936. (let ((current-letter nil) (last-entry nil))
  937. (dolist (idx full-index)
  938. (let* ((entry (org-split-string (car idx) "!"))
  939. (letter (upcase (substring (car entry) 0 1)))
  940. ;; Transform file into a path relative to publishing
  941. ;; directory.
  942. (file (file-relative-name
  943. (nth 1 idx)
  944. (plist-get (cdr project) :base-directory))))
  945. ;; Check if another letter has to be inserted.
  946. (unless (string= letter current-letter)
  947. (insert (format "* %s\n" letter)))
  948. ;; Compute the first difference between last entry and
  949. ;; current one: it tells the level at which new items
  950. ;; should be added.
  951. (let* ((rank
  952. (if (equal entry last-entry) (1- (length entry))
  953. (cl-loop for n from 0 to (length entry)
  954. unless (equal (nth n entry) (nth n last-entry))
  955. return n)))
  956. (len (length (nthcdr rank entry))))
  957. ;; For each term after the first difference, create
  958. ;; a new sub-list with the term as body. Moreover,
  959. ;; linkify the last term.
  960. (dotimes (n len)
  961. (insert
  962. (concat
  963. (make-string (* (+ rank n) 2) ?\s) " - "
  964. (if (not (= (1- len) n)) (nth (+ rank n) entry)
  965. ;; Last term: Link it to TARGET, if possible.
  966. (let ((target (nth 2 idx)))
  967. (format
  968. "[[%s][%s]]"
  969. ;; Destination.
  970. (pcase (car target)
  971. (`nil (format "file:%s" file))
  972. (`id (format "id:%s" (cdr target)))
  973. (`custom-id (format "file:%s::#%s" file (cdr target)))
  974. (_ (format "file:%s::*%s" file (cdr target))))
  975. ;; Description.
  976. (car (last entry)))))
  977. "\n"))))
  978. (setq current-letter letter last-entry entry))))
  979. ;; Create "theindex.org", if it doesn't exist yet, and provide
  980. ;; a default index file.
  981. (let ((index.org (expand-file-name "theindex.org" directory)))
  982. (unless (file-exists-p index.org)
  983. (with-temp-file index.org
  984. (insert "#+TITLE: Index\n\n#+INCLUDE: \"theindex.inc\"\n\n")))))))
  985. ;;; External Fuzzy Links Resolution
  986. ;;
  987. ;; This part implements tools to resolve [[file.org::*Some headline]]
  988. ;; links, where "file.org" belongs to the current project.
  989. (defun org-publish--store-crossrefs (output _backend info)
  990. "Store cross-references for current published file.
  991. OUTPUT is the produced output, as a string. BACKEND is the export
  992. back-end used, as a symbol. INFO is the final export state, as
  993. a plist.
  994. This function is meant to be used as a final output filter. See
  995. `org-publish-org-to'."
  996. (org-publish-cache-set-file-property
  997. (file-truename (plist-get info :input-file))
  998. :crossrefs
  999. ;; Update `:crossrefs' so as to remove unused references and search
  1000. ;; cells. Actually used references are extracted from
  1001. ;; `:internal-references', with references as strings removed. See
  1002. ;; `org-export-get-reference' for details.
  1003. (cl-remove-if (lambda (pair) (stringp (car pair)))
  1004. (plist-get info :internal-references)))
  1005. ;; Return output unchanged.
  1006. output)
  1007. (defun org-publish-resolve-external-link (search file &optional prefer-custom)
  1008. "Return reference for element matching string SEARCH in FILE.
  1009. Return value is an internal reference, as a string.
  1010. This function allows resolving external links with a search
  1011. option, e.g.,
  1012. [[file:file.org::*heading][description]]
  1013. [[file:file.org::#custom-id][description]]
  1014. [[file:file.org::fuzzy][description]]
  1015. When PREFER-CUSTOM is non-nil, and SEARCH targets a headline in
  1016. FILE, return its custom ID, if any.
  1017. It only makes sense to use this if export back-end builds
  1018. references with `org-export-get-reference'."
  1019. (cond
  1020. ((and prefer-custom
  1021. (if (string-prefix-p "#" search)
  1022. (substring search 1)
  1023. (with-current-buffer (find-file-noselect file)
  1024. (org-with-point-at 1
  1025. (let ((org-link-search-must-match-exact-headline t))
  1026. (condition-case err
  1027. (org-link-search search nil t)
  1028. (error
  1029. (signal 'org-link-broken (cdr err)))))
  1030. (and (org-at-heading-p)
  1031. (org-string-nw-p (org-entry-get (point) "CUSTOM_ID"))))))))
  1032. ((not org-publish-cache)
  1033. (progn
  1034. (message "Reference %S in file %S cannot be resolved without publishing"
  1035. search
  1036. file)
  1037. "MissingReference"))
  1038. (t
  1039. (let* ((filename (file-truename file))
  1040. (crossrefs
  1041. (org-publish-cache-get-file-property filename :crossrefs nil t))
  1042. (cells (org-export-string-to-search-cell search)))
  1043. (or
  1044. ;; Look for reference associated to search cells triggered by
  1045. ;; LINK. It can match when targeted file has been published
  1046. ;; already.
  1047. (let ((known (cdr (cl-some (lambda (c) (assoc c crossrefs)) cells))))
  1048. (and known (org-export-format-reference known)))
  1049. ;; Search cell is unknown so far. Generate a new internal
  1050. ;; reference that will be used when the targeted file will be
  1051. ;; published.
  1052. (let ((new (org-export-new-reference crossrefs)))
  1053. (dolist (cell cells) (push (cons cell new) crossrefs))
  1054. (org-publish-cache-set-file-property filename :crossrefs crossrefs)
  1055. (org-export-format-reference new)))))))
  1056. (defun org-publish-file-relative-name (filename info)
  1057. "Convert FILENAME to be relative to current project's base directory.
  1058. INFO is the plist containing the current export state. The
  1059. function does not change relative file names."
  1060. (let ((base (plist-get info :base-directory)))
  1061. (if (and base
  1062. (file-name-absolute-p filename)
  1063. (file-in-directory-p filename base))
  1064. (file-relative-name filename base)
  1065. filename)))
  1066. ;;; Caching functions
  1067. (defun org-publish-write-cache-file (&optional free-cache)
  1068. "Write `org-publish-cache' to file.
  1069. If FREE-CACHE, empty the cache."
  1070. (unless org-publish-cache
  1071. (error "`org-publish-write-cache-file' called, but no cache present"))
  1072. (let ((cache-file (org-publish-cache-get ":cache-file:")))
  1073. (unless cache-file
  1074. (error "Cannot find cache-file name in `org-publish-write-cache-file'"))
  1075. (with-temp-file cache-file
  1076. (let (print-level print-length)
  1077. (insert "(setq org-publish-cache \
  1078. \(make-hash-table :test 'equal :weakness nil :size 100))\n")
  1079. (maphash (lambda (k v)
  1080. (insert
  1081. (format "(puthash %S %s%S org-publish-cache)\n"
  1082. k (if (or (listp v) (symbolp v)) "'" "") v)))
  1083. org-publish-cache)))
  1084. (when free-cache (org-publish-reset-cache))))
  1085. (defun org-publish-initialize-cache (project-name)
  1086. "Initialize the projects cache if not initialized yet and return it."
  1087. (unless project-name
  1088. (error "Cannot initialize `org-publish-cache' without projects name in \
  1089. `org-publish-initialize-cache'"))
  1090. (unless (file-exists-p org-publish-timestamp-directory)
  1091. (make-directory org-publish-timestamp-directory t))
  1092. (unless (file-directory-p org-publish-timestamp-directory)
  1093. (error "Org publish timestamp: %s is not a directory"
  1094. org-publish-timestamp-directory))
  1095. (unless (and org-publish-cache
  1096. (string= (org-publish-cache-get ":project:") project-name))
  1097. (let* ((cache-file
  1098. (concat
  1099. (expand-file-name org-publish-timestamp-directory)
  1100. project-name ".cache"))
  1101. (cexists (file-exists-p cache-file)))
  1102. (when org-publish-cache (org-publish-reset-cache))
  1103. (if cexists (load-file cache-file)
  1104. (setq org-publish-cache
  1105. (make-hash-table :test 'equal :weakness nil :size 100))
  1106. (org-publish-cache-set ":project:" project-name)
  1107. (org-publish-cache-set ":cache-file:" cache-file))
  1108. (unless cexists (org-publish-write-cache-file nil))))
  1109. org-publish-cache)
  1110. (defun org-publish-reset-cache ()
  1111. "Empty `org-publish-cache' and reset it nil."
  1112. (message "%s" "Resetting org-publish-cache")
  1113. (when (hash-table-p org-publish-cache)
  1114. (clrhash org-publish-cache))
  1115. (setq org-publish-cache nil))
  1116. (defun org-publish-cache-file-needs-publishing
  1117. (filename &optional pub-dir pub-func _base-dir)
  1118. "Check the timestamp of the last publishing of FILENAME.
  1119. Return non-nil if the file needs publishing. Also check if
  1120. any included files have been more recently published, so that
  1121. the file including them will be republished as well."
  1122. (unless org-publish-cache
  1123. (error
  1124. "`org-publish-cache-file-needs-publishing' called, but no cache present"))
  1125. (let* ((key (org-publish-timestamp-filename filename pub-dir pub-func))
  1126. (pstamp (org-publish-cache-get key))
  1127. (org-inhibit-startup t)
  1128. included-files-mtime)
  1129. (when (equal (file-name-extension filename) "org")
  1130. (let ((case-fold-search t))
  1131. (with-temp-buffer
  1132. (delay-mode-hooks
  1133. (org-mode)
  1134. (insert-file-contents filename)
  1135. (goto-char (point-min))
  1136. (while (re-search-forward "^[ \t]*#\\+INCLUDE:" nil t)
  1137. (let ((element (org-element-at-point)))
  1138. (when (eq 'keyword (org-element-type element))
  1139. (let* ((value (org-element-property :value element))
  1140. (include-filename
  1141. (and (string-match "\\`\\(\".+?\"\\|\\S-+\\)" value)
  1142. (let ((m (org-strip-quotes
  1143. (match-string 1 value))))
  1144. ;; Ignore search suffix.
  1145. (if (string-match "::.*?\\'" m)
  1146. (substring m 0 (match-beginning 0))
  1147. m)))))
  1148. (when include-filename
  1149. (push (org-publish-cache-mtime-of-src
  1150. (expand-file-name include-filename (file-name-directory filename)))
  1151. included-files-mtime))))))))))
  1152. (or (null pstamp)
  1153. (let ((mtime (org-publish-cache-mtime-of-src filename)))
  1154. (or (time-less-p pstamp mtime)
  1155. (cl-some (lambda (ct) (time-less-p mtime ct))
  1156. included-files-mtime))))))
  1157. (defun org-publish-cache-set-file-property
  1158. (filename property value &optional project-name)
  1159. "Set the VALUE for a PROPERTY of file FILENAME in publishing cache to VALUE.
  1160. Use cache file of PROJECT-NAME. If the entry does not exist, it
  1161. will be created. Return VALUE."
  1162. ;; Evtl. load the requested cache file:
  1163. (when project-name (org-publish-initialize-cache project-name))
  1164. (let ((pl (org-publish-cache-get filename)))
  1165. (if pl (progn (plist-put pl property value) value)
  1166. (org-publish-cache-get-file-property
  1167. filename property value nil project-name))))
  1168. (defun org-publish-cache-get-file-property
  1169. (filename property &optional default no-create project-name)
  1170. "Return the value for a PROPERTY of file FILENAME in publishing cache.
  1171. Use cache file of PROJECT-NAME. Return the value of that PROPERTY,
  1172. or DEFAULT, if the value does not yet exist. Create the entry,
  1173. if necessary, unless NO-CREATE is non-nil."
  1174. (when project-name (org-publish-initialize-cache project-name))
  1175. (let ((properties (org-publish-cache-get filename)))
  1176. (cond ((null properties)
  1177. (unless no-create
  1178. (org-publish-cache-set filename (list property default)))
  1179. default)
  1180. ((plist-member properties property) (plist-get properties property))
  1181. (t default))))
  1182. (defun org-publish-cache-get (key)
  1183. "Return the value stored in `org-publish-cache' for key KEY.
  1184. Return nil, if no value or nil is found. Raise an error if the
  1185. cache does not exist."
  1186. (unless org-publish-cache
  1187. (error "`org-publish-cache-get' called, but no cache present"))
  1188. (gethash key org-publish-cache))
  1189. (defun org-publish-cache-set (key value)
  1190. "Store KEY VALUE pair in `org-publish-cache'.
  1191. Returns value on success, else nil. Raise an error if the cache
  1192. does not exist."
  1193. (unless org-publish-cache
  1194. (error "`org-publish-cache-set' called, but no cache present"))
  1195. (puthash key value org-publish-cache))
  1196. (defun org-publish-cache-mtime-of-src (file)
  1197. "Get the mtime of FILE as an integer."
  1198. (let ((attr (file-attributes
  1199. (expand-file-name (or (file-symlink-p file) file)
  1200. (file-name-directory file)))))
  1201. (if attr (file-attribute-modification-time attr)
  1202. (error "No such file: %S" file))))
  1203. (provide 'ox-publish)
  1204. ;; Local variables:
  1205. ;; generated-autoload-file: "org-loaddefs.el"
  1206. ;; End:
  1207. ;;; ox-publish.el ends here