ox-publish.el 51 KB

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