ox-html: Fix stack overflow in regexp matching
[org-mode.git] / lisp / ox-publish.el
blob2a89167622ad9cef196daaa28b467da6e0bf7564
1 ;;; ox-publish.el --- Publish Related Org Mode Files as a Website
2 ;; Copyright (C) 2006-2013 Free Software Foundation, Inc.
4 ;; Author: David O'Toole <dto@gnu.org>
5 ;; Maintainer: Carsten Dominik <carsten DOT dominik AT gmail DOT com>
6 ;; Keywords: hypermedia, outlines, wp
8 ;; This file is part of GNU Emacs.
9 ;;
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This program allow configurable publishing of related sets of
26 ;; Org mode files as a complete website.
28 ;; ox-publish.el can do the following:
30 ;; + Publish all one's Org files to a given export back-end
31 ;; + Upload HTML, images, attachments and other files to a web server
32 ;; + Exclude selected private pages from publishing
33 ;; + Publish a clickable sitemap of pages
34 ;; + Manage local timestamps for publishing only changed files
35 ;; + Accept plugin functions to extend range of publishable content
37 ;; Documentation for publishing is in the manual.
39 ;;; Code:
41 (eval-when-compile (require 'cl))
42 (require 'format-spec)
43 (require 'ox)
47 ;;; Variables
49 (defvar org-publish-temp-files nil
50 "Temporary list of files to be published.")
52 ;; Here, so you find the variable right before it's used the first time:
53 (defvar org-publish-cache nil
54 "This will cache timestamps and titles for files in publishing projects.
55 Blocks could hash sha1 values here.")
57 (defgroup org-publish nil
58 "Options for publishing a set of Org-mode and related files."
59 :tag "Org Publishing"
60 :group 'org)
62 (defcustom org-publish-project-alist nil
63 "Association list to control publishing behavior.
64 Each element of the alist is a publishing 'project.' The CAR of
65 each element is a string, uniquely identifying the project. The
66 CDR of each element is in one of the following forms:
68 1. A well-formed property list with an even number of elements,
69 alternating keys and values, specifying parameters for the
70 publishing process.
72 \(:property value :property value ... )
74 2. A meta-project definition, specifying of a list of
75 sub-projects:
77 \(:components (\"project-1\" \"project-2\" ...))
79 When the CDR of an element of org-publish-project-alist is in
80 this second form, the elements of the list after `:components'
81 are taken to be components of the project, which group together
82 files requiring different publishing options. When you publish
83 such a project with \\[org-publish], the components all publish.
85 When a property is given a value in `org-publish-project-alist',
86 its setting overrides the value of the corresponding user
87 variable (if any) during publishing. However, options set within
88 a file override everything.
90 Most properties are optional, but some should always be set:
92 `:base-directory'
94 Directory containing publishing source files.
96 `:base-extension'
98 Extension (without the dot!) of source files. This can be
99 a regular expression. If not given, \"org\" will be used as
100 default extension.
102 `:publishing-directory'
104 Directory (possibly remote) where output files will be
105 published.
107 The `:exclude' property may be used to prevent certain files from
108 being published. Its value may be a string or regexp matching
109 file names you don't want to be published.
111 The `:include' property may be used to include extra files. Its
112 value may be a list of filenames to include. The filenames are
113 considered relative to the base directory.
115 When both `:include' and `:exclude' properties are given values,
116 the exclusion step happens first.
118 One special property controls which back-end function to use for
119 publishing files in the project. This can be used to extend the
120 set of file types publishable by `org-publish', as well as the
121 set of output formats.
123 `:publishing-function'
125 Function to publish file. Each back-end may define its
126 own (i.e. `org-latex-publish-to-pdf',
127 `org-html-publish-to-html'). May be a list of functions, in
128 which case each function in the list is invoked in turn.
130 Another property allows you to insert code that prepares
131 a project for publishing. For example, you could call GNU Make
132 on a certain makefile, to ensure published files are built up to
133 date.
135 `:preparation-function'
137 Function to be called before publishing this project. This
138 may also be a list of functions.
140 `:completion-function'
142 Function to be called after publishing this project. This
143 may also be a list of functions.
145 Some properties control details of the Org publishing process,
146 and are equivalent to the corresponding user variables listed in
147 the right column. Back-end specific properties may also be
148 included. See the back-end documentation for more information.
150 :author `user-full-name'
151 :creator `org-export-creator-string'
152 :email `user-mail-address'
153 :exclude-tags `org-export-exclude-tags'
154 :headline-levels `org-export-headline-levels'
155 :language `org-export-default-language'
156 :preserve-breaks `org-export-preserve-breaks'
157 :section-numbers `org-export-with-section-numbers'
158 :select-tags `org-export-select-tags'
159 :time-stamp-file `org-export-time-stamp-file'
160 :with-archived-trees `org-export-with-archived-trees'
161 :with-author `org-export-with-author'
162 :with-creator `org-export-with-creator'
163 :with-date `org-export-with-date'
164 :with-drawers `org-export-with-drawers'
165 :with-email `org-export-with-email'
166 :with-emphasize `org-export-with-emphasize'
167 :with-entities `org-export-with-entities'
168 :with-fixed-width `org-export-with-fixed-width'
169 :with-footnotes `org-export-with-footnotes'
170 :with-inlinetasks `org-export-with-inlinetasks'
171 :with-latex `org-export-with-latex'
172 :with-priority `org-export-with-priority'
173 :with-smart-quotes `org-export-with-smart-quotes'
174 :with-special-strings `org-export-with-special-strings'
175 :with-statistics-cookies' `org-export-with-statistics-cookies'
176 :with-sub-superscript `org-export-with-sub-superscripts'
177 :with-toc `org-export-with-toc'
178 :with-tables `org-export-with-tables'
179 :with-tags `org-export-with-tags'
180 :with-tasks `org-export-with-tasks'
181 :with-timestamps `org-export-with-timestamps'
182 :with-todo-keywords `org-export-with-todo-keywords'
184 The following properties may be used to control publishing of
185 a site-map of files or summary page for a given project.
187 `:auto-sitemap'
189 Whether to publish a site-map during
190 `org-publish-current-project' or `org-publish-all'.
192 `:sitemap-filename'
194 Filename for output of sitemap. Defaults to \"sitemap.org\".
196 `:sitemap-title'
198 Title of site-map page. Defaults to name of file.
200 `:sitemap-function'
202 Plugin function to use for generation of site-map. Defaults
203 to `org-publish-org-sitemap', which generates a plain list of
204 links to all files in the project.
206 `:sitemap-style'
208 Can be `list' (site-map is just an itemized list of the
209 titles of the files involved) or `tree' (the directory
210 structure of the source files is reflected in the site-map).
211 Defaults to `tree'.
213 `:sitemap-sans-extension'
215 Remove extension from site-map's file-names. Useful to have
216 cool URIs (see http://www.w3.org/Provider/Style/URI).
217 Defaults to nil.
219 If you create a site-map file, adjust the sorting like this:
221 `:sitemap-sort-folders'
223 Where folders should appear in the site-map. Set this to
224 `first' (default) or `last' to display folders first or last,
225 respectively. Any other value will mix files and folders.
227 `:sitemap-sort-files'
229 The site map is normally sorted alphabetically. You can
230 change this behaviour setting this to `anti-chronologically',
231 `chronologically', or nil.
233 `:sitemap-ignore-case'
235 Should sorting be case-sensitive? Default nil.
237 The following property control the creation of a concept index.
239 `:makeindex'
241 Create a concept index. The file containing the index has to
242 be called \"theindex.org\". If it doesn't exist in the
243 project, it will be generated. Contents of the index are
244 stored in the file \"theindex.inc\", which can be included in
245 \"theindex.org\".
247 Other properties affecting publication.
249 `:body-only'
251 Set this to t to publish only the body of the documents."
252 :group 'org-export-publish
253 :type 'alist)
255 (defcustom org-publish-use-timestamps-flag t
256 "Non-nil means use timestamp checking to publish only changed files.
257 When nil, do no timestamp checking and always publish all files."
258 :group 'org-export-publish
259 :type 'boolean)
261 (defcustom org-publish-timestamp-directory
262 (convert-standard-filename "~/.org-timestamps/")
263 "Name of directory in which to store publishing timestamps."
264 :group 'org-export-publish
265 :type 'directory)
267 (defcustom org-publish-list-skipped-files t
268 "Non-nil means show message about files *not* published."
269 :group 'org-export-publish
270 :type 'boolean)
272 (defcustom org-publish-sitemap-sort-files 'alphabetically
273 "Method to sort files in site-maps.
274 Possible values are `alphabetically', `chronologically',
275 `anti-chronologically' and nil.
277 If `alphabetically', files will be sorted alphabetically. If
278 `chronologically', files will be sorted with older modification
279 time first. If `anti-chronologically', files will be sorted with
280 newer modification time first. nil won't sort files.
282 You can overwrite this default per project in your
283 `org-publish-project-alist', using `:sitemap-sort-files'."
284 :group 'org-export-publish
285 :type 'symbol)
287 (defcustom org-publish-sitemap-sort-folders 'first
288 "A symbol, denoting if folders are sorted first in sitemaps.
289 Possible values are `first', `last', and nil.
290 If `first', folders will be sorted before files.
291 If `last', folders are sorted to the end after the files.
292 Any other value will not mix files and folders.
294 You can overwrite this default per project in your
295 `org-publish-project-alist', using `:sitemap-sort-folders'."
296 :group 'org-export-publish
297 :type 'symbol)
299 (defcustom org-publish-sitemap-sort-ignore-case nil
300 "Non-nil when site-map sorting should ignore case.
302 You can overwrite this default per project in your
303 `org-publish-project-alist', using `:sitemap-ignore-case'."
304 :group 'org-export-publish
305 :type 'boolean)
307 (defcustom org-publish-sitemap-date-format "%Y-%m-%d"
308 "Format for printing a date in the sitemap.
309 See `format-time-string' for allowed formatters."
310 :group 'org-export-publish
311 :type 'string)
313 (defcustom org-publish-sitemap-file-entry-format "%t"
314 "Format string for site-map file entry.
315 You could use brackets to delimit on what part the link will be.
317 %t is the title.
318 %a is the author.
319 %d is the date formatted using `org-publish-sitemap-date-format'."
320 :group 'org-export-publish
321 :type 'string)
325 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
326 ;;; Timestamp-related functions
328 (defun org-publish-timestamp-filename (filename &optional pub-dir pub-func)
329 "Return path to timestamp file for filename FILENAME."
330 (setq filename (concat filename "::" (or pub-dir "") "::"
331 (format "%s" (or pub-func ""))))
332 (concat "X" (if (fboundp 'sha1) (sha1 filename) (md5 filename))))
334 (defun org-publish-needed-p
335 (filename &optional pub-dir pub-func true-pub-dir base-dir)
336 "Non-nil if FILENAME should be published in PUB-DIR using PUB-FUNC.
337 TRUE-PUB-DIR is where the file will truly end up. Currently we
338 are not using this - maybe it can eventually be used to check if
339 the file is present at the target location, and how old it is.
340 Right now we cannot do this, because we do not know under what
341 file name the file will be stored - the publishing function can
342 still decide about that independently."
343 (let ((rtn (if (not org-publish-use-timestamps-flag) t
344 (org-publish-cache-file-needs-publishing
345 filename pub-dir pub-func base-dir))))
346 (if rtn (message "Publishing file %s using `%s'" filename pub-func)
347 (when org-publish-list-skipped-files
348 (message "Skipping unmodified file %s" filename)))
349 rtn))
351 (defun org-publish-update-timestamp
352 (filename &optional pub-dir pub-func base-dir)
353 "Update publishing timestamp for file FILENAME.
354 If there is no timestamp, create one."
355 (let ((key (org-publish-timestamp-filename filename pub-dir pub-func))
356 (stamp (org-publish-cache-ctime-of-src filename)))
357 (org-publish-cache-set key stamp)))
359 (defun org-publish-remove-all-timestamps ()
360 "Remove all files in the timestamp directory."
361 (let ((dir org-publish-timestamp-directory)
362 files)
363 (when (and (file-exists-p dir) (file-directory-p dir))
364 (mapc 'delete-file (directory-files dir 'full "[^.]\\'"))
365 (org-publish-reset-cache))))
369 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
370 ;;; Getting project information out of `org-publish-project-alist'
372 (defun org-publish-expand-projects (projects-alist)
373 "Expand projects in PROJECTS-ALIST.
374 This splices all the components into the list."
375 (let ((rest projects-alist) rtn p components)
376 (while (setq p (pop rest))
377 (if (setq components (plist-get (cdr p) :components))
378 (setq rest (append
379 (mapcar (lambda (x) (assoc x org-publish-project-alist))
380 components)
381 rest))
382 (push p rtn)))
383 (nreverse (delete-dups (delq nil rtn)))))
385 (defvar org-sitemap-sort-files)
386 (defvar org-sitemap-sort-folders)
387 (defvar org-sitemap-ignore-case)
388 (defvar org-sitemap-requested)
389 (defvar org-sitemap-date-format)
390 (defvar org-sitemap-file-entry-format)
391 (defun org-publish-compare-directory-files (a b)
392 "Predicate for `sort', that sorts folders and files for sitemap."
393 (let ((retval t))
394 (when (or org-sitemap-sort-files org-sitemap-sort-folders)
395 ;; First we sort files:
396 (when org-sitemap-sort-files
397 (case org-sitemap-sort-files
398 (alphabetically
399 (let* ((adir (file-directory-p a))
400 (aorg (and (string-match "\\.org$" a) (not adir)))
401 (bdir (file-directory-p b))
402 (borg (and (string-match "\\.org$" b) (not bdir)))
403 (A (if aorg (concat (file-name-directory a)
404 (org-publish-find-title a)) a))
405 (B (if borg (concat (file-name-directory b)
406 (org-publish-find-title b)) b)))
407 (setq retval (if org-sitemap-ignore-case
408 (not (string-lessp (upcase B) (upcase A)))
409 (not (string-lessp B A))))))
410 ((anti-chronologically chronologically)
411 (let* ((adate (org-publish-find-date a))
412 (bdate (org-publish-find-date b))
413 (A (+ (lsh (car adate) 16) (cadr adate)))
414 (B (+ (lsh (car bdate) 16) (cadr bdate))))
415 (setq retval
416 (if (eq org-sitemap-sort-files 'chronologically) (<= A B)
417 (>= A B)))))))
418 ;; Directory-wise wins:
419 (when org-sitemap-sort-folders
420 ;; a is directory, b not:
421 (cond
422 ((and (file-directory-p a) (not (file-directory-p b)))
423 (setq retval (equal org-sitemap-sort-folders 'first)))
424 ;; a is not a directory, but b is:
425 ((and (not (file-directory-p a)) (file-directory-p b))
426 (setq retval (equal org-sitemap-sort-folders 'last))))))
427 retval))
429 (defun org-publish-get-base-files-1
430 (base-dir &optional recurse match skip-file skip-dir)
431 "Set `org-publish-temp-files' with files from BASE-DIR directory.
432 If RECURSE is non-nil, check BASE-DIR recursively. If MATCH is
433 non-nil, restrict this list to the files matching the regexp
434 MATCH. If SKIP-FILE is non-nil, skip file matching the regexp
435 SKIP-FILE. If SKIP-DIR is non-nil, don't check directories
436 matching the regexp SKIP-DIR when recursing through BASE-DIR."
437 (mapc (lambda (f)
438 (let ((fd-p (file-directory-p f))
439 (fnd (file-name-nondirectory f)))
440 (if (and fd-p recurse
441 (not (string-match "^\\.+$" fnd))
442 (if skip-dir (not (string-match skip-dir fnd)) t))
443 (org-publish-get-base-files-1
444 f recurse match skip-file skip-dir)
445 (unless (or fd-p ;; this is a directory
446 (and skip-file (string-match skip-file fnd))
447 (not (file-exists-p (file-truename f)))
448 (not (string-match match fnd)))
450 (pushnew f org-publish-temp-files)))))
451 (if org-sitemap-requested
452 (sort (directory-files base-dir t (unless recurse match))
453 'org-publish-compare-directory-files)
454 (directory-files base-dir t (unless recurse match)))))
456 (defun org-publish-get-base-files (project &optional exclude-regexp)
457 "Return a list of all files in PROJECT.
458 If EXCLUDE-REGEXP is set, this will be used to filter out
459 matching filenames."
460 (let* ((project-plist (cdr project))
461 (base-dir (file-name-as-directory
462 (plist-get project-plist :base-directory)))
463 (include-list (plist-get project-plist :include))
464 (recurse (plist-get project-plist :recursive))
465 (extension (or (plist-get project-plist :base-extension) "org"))
466 ;; sitemap-... variables are dynamically scoped for
467 ;; org-publish-compare-directory-files:
468 (org-sitemap-requested
469 (plist-get project-plist :auto-sitemap))
470 (sitemap-filename
471 (or (plist-get project-plist :sitemap-filename) "sitemap.org"))
472 (org-sitemap-sort-folders
473 (if (plist-member project-plist :sitemap-sort-folders)
474 (plist-get project-plist :sitemap-sort-folders)
475 org-publish-sitemap-sort-folders))
476 (org-sitemap-sort-files
477 (cond ((plist-member project-plist :sitemap-sort-files)
478 (plist-get project-plist :sitemap-sort-files))
479 ;; For backward compatibility:
480 ((plist-member project-plist :sitemap-alphabetically)
481 (if (plist-get project-plist :sitemap-alphabetically)
482 'alphabetically nil))
483 (t org-publish-sitemap-sort-files)))
484 (org-sitemap-ignore-case
485 (if (plist-member project-plist :sitemap-ignore-case)
486 (plist-get project-plist :sitemap-ignore-case)
487 org-publish-sitemap-sort-ignore-case))
488 (match (if (eq extension 'any) "^[^\\.]"
489 (concat "^[^\\.].*\\.\\(" extension "\\)$"))))
490 ;; Make sure `org-sitemap-sort-folders' has an accepted value
491 (unless (memq org-sitemap-sort-folders '(first last))
492 (setq org-sitemap-sort-folders nil))
494 (setq org-publish-temp-files nil)
495 (if org-sitemap-requested
496 (pushnew (expand-file-name (concat base-dir sitemap-filename))
497 org-publish-temp-files))
498 (org-publish-get-base-files-1 base-dir recurse match
499 ;; FIXME distinguish exclude regexp
500 ;; for skip-file and skip-dir?
501 exclude-regexp exclude-regexp)
502 (mapc (lambda (f)
503 (pushnew
504 (expand-file-name (concat base-dir f))
505 org-publish-temp-files))
506 include-list)
507 org-publish-temp-files))
509 (defun org-publish-get-project-from-filename (filename &optional up)
510 "Return the project that FILENAME belongs to."
511 (let* ((filename (expand-file-name filename))
512 project-name)
514 (catch 'p-found
515 (dolist (prj org-publish-project-alist)
516 (unless (plist-get (cdr prj) :components)
517 ;; [[info:org:Selecting%20files]] shows how this is supposed to work:
518 (let* ((r (plist-get (cdr prj) :recursive))
519 (b (expand-file-name (file-name-as-directory
520 (plist-get (cdr prj) :base-directory))))
521 (x (or (plist-get (cdr prj) :base-extension) "org"))
522 (e (plist-get (cdr prj) :exclude))
523 (i (plist-get (cdr prj) :include))
524 (xm (concat "^" b (if r ".+" "[^/]+") "\\.\\(" x "\\)$")))
525 (when
526 (or (and i
527 (member filename
528 (mapcar (lambda (file)
529 (expand-file-name file b))
530 i)))
531 (and (not (and e (string-match e filename)))
532 (string-match xm filename)))
533 (setq project-name (car prj))
534 (throw 'p-found project-name))))))
535 (when up
536 (dolist (prj org-publish-project-alist)
537 (if (member project-name (plist-get (cdr prj) :components))
538 (setq project-name (car prj)))))
539 (assoc project-name org-publish-project-alist)))
543 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
544 ;;; Tools for publishing functions in back-ends
546 (defun org-publish-org-to (backend filename extension plist &optional pub-dir)
547 "Publish an Org file to a specified back-end.
549 BACKEND is a symbol representing the back-end used for
550 transcoding. FILENAME is the filename of the Org file to be
551 published. EXTENSION is the extension used for the output
552 string, with the leading dot. PLIST is the property list for the
553 given project.
555 Optional argument PUB-DIR, when non-nil is the publishing
556 directory.
558 Return output file name."
559 (unless (or (not pub-dir) (file-exists-p pub-dir)) (make-directory pub-dir t))
560 ;; Check if a buffer visiting FILENAME is already open.
561 (let* ((visitingp (find-buffer-visiting filename))
562 (work-buffer (or visitingp (find-file-noselect filename))))
563 (prog1 (with-current-buffer work-buffer
564 (let ((output-file
565 (org-export-output-file-name extension nil pub-dir))
566 (body-p (plist-get plist :body-only)))
567 (org-export-to-file
568 backend output-file nil nil body-p
569 ;; Add `org-publish-collect-numbering' and
570 ;; `org-publish-collect-index' to final output
571 ;; filters. The latter isn't dependent on
572 ;; `:makeindex', since we want to keep it up-to-date
573 ;; in cache anyway.
574 (org-combine-plists
575 plist
576 `(:filter-final-output
577 ,(cons 'org-publish-collect-numbering
578 (cons 'org-publish-collect-index
579 (plist-get plist :filter-final-output))))))))
580 ;; Remove opened buffer in the process.
581 (unless visitingp (kill-buffer work-buffer)))))
583 (defvar project-plist)
585 (defun org-publish-attachment (plist filename pub-dir)
586 "Publish a file with no transformation of any kind.
588 FILENAME is the filename of the Org file to be published. PLIST
589 is the property list for the given project. PUB-DIR is the
590 publishing directory.
592 Return output file name."
593 (unless (file-directory-p pub-dir)
594 (make-directory pub-dir t))
595 (or (equal (expand-file-name (file-name-directory filename))
596 (file-name-as-directory (expand-file-name pub-dir)))
597 (copy-file filename
598 (expand-file-name (file-name-nondirectory filename) pub-dir)
599 t)))
603 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
604 ;;; Publishing files, sets of files, and indices
606 (defun org-publish-file (filename &optional project no-cache)
607 "Publish file FILENAME from PROJECT.
608 If NO-CACHE is not nil, do not initialize org-publish-cache and
609 write it to disk. This is needed, since this function is used to
610 publish single files, when entire projects are published.
611 See `org-publish-projects'."
612 (let* ((project
613 (or project
614 (or (org-publish-get-project-from-filename filename)
615 (error "File %s not part of any known project"
616 (abbreviate-file-name filename)))))
617 (project-plist (cdr project))
618 (ftname (expand-file-name filename))
619 (publishing-function
620 (or (plist-get project-plist :publishing-function)
621 (error "No publishing function chosen")))
622 (base-dir
623 (file-name-as-directory
624 (expand-file-name
625 (or (plist-get project-plist :base-directory)
626 (error "Project %s does not have :base-directory defined"
627 (car project))))))
628 (pub-dir
629 (file-name-as-directory
630 (file-truename
631 (or (eval (plist-get project-plist :publishing-directory))
632 (error "Project %s does not have :publishing-directory defined"
633 (car project))))))
634 tmp-pub-dir)
636 (unless no-cache (org-publish-initialize-cache (car project)))
638 (setq tmp-pub-dir
639 (file-name-directory
640 (concat pub-dir
641 (and (string-match (regexp-quote base-dir) ftname)
642 (substring ftname (match-end 0))))))
643 (if (listp publishing-function)
644 ;; allow chain of publishing functions
645 (mapc (lambda (f)
646 (when (org-publish-needed-p
647 filename pub-dir f tmp-pub-dir base-dir)
648 (funcall f project-plist filename tmp-pub-dir)
649 (org-publish-update-timestamp filename pub-dir f base-dir)))
650 publishing-function)
651 (when (org-publish-needed-p
652 filename pub-dir publishing-function tmp-pub-dir base-dir)
653 (funcall publishing-function project-plist filename tmp-pub-dir)
654 (org-publish-update-timestamp
655 filename pub-dir publishing-function base-dir)))
656 (unless no-cache (org-publish-write-cache-file))))
658 (defun org-publish-projects (projects)
659 "Publish all files belonging to the PROJECTS alist.
660 If `:auto-sitemap' is set, publish the sitemap too. If
661 `:makeindex' is set, also produce a file theindex.org."
662 (mapc
663 (lambda (project)
664 ;; Each project uses its own cache file:
665 (org-publish-initialize-cache (car project))
666 (let* ((project-plist (cdr project))
667 (exclude-regexp (plist-get project-plist :exclude))
668 (sitemap-p (plist-get project-plist :auto-sitemap))
669 (sitemap-filename (or (plist-get project-plist :sitemap-filename)
670 "sitemap.org"))
671 (sitemap-function (or (plist-get project-plist :sitemap-function)
672 'org-publish-org-sitemap))
673 (org-sitemap-date-format
674 (or (plist-get project-plist :sitemap-date-format)
675 org-publish-sitemap-date-format))
676 (org-sitemap-file-entry-format
677 (or (plist-get project-plist :sitemap-file-entry-format)
678 org-publish-sitemap-file-entry-format))
679 (preparation-function
680 (plist-get project-plist :preparation-function))
681 (completion-function (plist-get project-plist :completion-function))
682 (files (org-publish-get-base-files project exclude-regexp))
683 (theindex
684 (expand-file-name "theindex.org"
685 (plist-get project-plist :base-directory))))
686 (when preparation-function (run-hooks 'preparation-function))
687 (if sitemap-p (funcall sitemap-function project sitemap-filename))
688 ;; Publish all files from PROJECT excepted "theindex.org". Its
689 ;; publishing will be deferred until "theindex.inc" is
690 ;; populated.
691 (dolist (file files)
692 (unless (equal file theindex)
693 (org-publish-file file project t)))
694 ;; Populate "theindex.inc", if needed, and publish
695 ;; "theindex.org".
696 (when (plist-get project-plist :makeindex)
697 (org-publish-index-generate-theindex
698 project (plist-get project-plist :base-directory))
699 (org-publish-file theindex project t))
700 (when completion-function (run-hooks 'completion-function))
701 (org-publish-write-cache-file)))
702 (org-publish-expand-projects projects)))
704 (defun org-publish-org-sitemap (project &optional sitemap-filename)
705 "Create a sitemap of pages in set defined by PROJECT.
706 Optionally set the filename of the sitemap with SITEMAP-FILENAME.
707 Default for SITEMAP-FILENAME is 'sitemap.org'."
708 (let* ((project-plist (cdr project))
709 (dir (file-name-as-directory
710 (plist-get project-plist :base-directory)))
711 (localdir (file-name-directory dir))
712 (indent-str (make-string 2 ?\ ))
713 (exclude-regexp (plist-get project-plist :exclude))
714 (files (nreverse
715 (org-publish-get-base-files project exclude-regexp)))
716 (sitemap-filename (concat dir (or sitemap-filename "sitemap.org")))
717 (sitemap-title (or (plist-get project-plist :sitemap-title)
718 (concat "Sitemap for project " (car project))))
719 (sitemap-style (or (plist-get project-plist :sitemap-style)
720 'tree))
721 (sitemap-sans-extension
722 (plist-get project-plist :sitemap-sans-extension))
723 (visiting (find-buffer-visiting sitemap-filename))
724 (ifn (file-name-nondirectory sitemap-filename))
725 file sitemap-buffer)
726 (with-current-buffer (setq sitemap-buffer
727 (or visiting (find-file sitemap-filename)))
728 (erase-buffer)
729 (insert (concat "#+TITLE: " sitemap-title "\n\n"))
730 (while (setq file (pop files))
731 (let ((fn (file-name-nondirectory file))
732 (link (file-relative-name file dir))
733 (oldlocal localdir))
734 (when sitemap-sans-extension
735 (setq link (file-name-sans-extension link)))
736 ;; sitemap shouldn't list itself
737 (unless (equal (file-truename sitemap-filename)
738 (file-truename file))
739 (if (eq sitemap-style 'list)
740 (message "Generating list-style sitemap for %s" sitemap-title)
741 (message "Generating tree-style sitemap for %s" sitemap-title)
742 (setq localdir (concat (file-name-as-directory dir)
743 (file-name-directory link)))
744 (unless (string= localdir oldlocal)
745 (if (string= localdir dir)
746 (setq indent-str (make-string 2 ?\ ))
747 (let ((subdirs
748 (split-string
749 (directory-file-name
750 (file-name-directory
751 (file-relative-name localdir dir))) "/"))
752 (subdir "")
753 (old-subdirs (split-string
754 (file-relative-name oldlocal dir) "/")))
755 (setq indent-str (make-string 2 ?\ ))
756 (while (string= (car old-subdirs) (car subdirs))
757 (setq indent-str (concat indent-str (make-string 2 ?\ )))
758 (pop old-subdirs)
759 (pop subdirs))
760 (dolist (d subdirs)
761 (setq subdir (concat subdir d "/"))
762 (insert (concat indent-str " + " d "\n"))
763 (setq indent-str (make-string
764 (+ (length indent-str) 2) ?\ )))))))
765 ;; This is common to 'flat and 'tree
766 (let ((entry
767 (org-publish-format-file-entry
768 org-sitemap-file-entry-format file project-plist))
769 (regexp "\\(.*\\)\\[\\([^][]+\\)\\]\\(.*\\)"))
770 (cond ((string-match-p regexp entry)
771 (string-match regexp entry)
772 (insert (concat indent-str " + " (match-string 1 entry)
773 "[[file:" link "]["
774 (match-string 2 entry)
775 "]]" (match-string 3 entry) "\n")))
777 (insert (concat indent-str " + [[file:" link "]["
778 entry
779 "]]\n"))))))))
780 (save-buffer))
781 (or visiting (kill-buffer sitemap-buffer))))
783 (defun org-publish-format-file-entry (fmt file project-plist)
784 (format-spec fmt
785 `((?t . ,(org-publish-find-title file t))
786 (?d . ,(format-time-string org-sitemap-date-format
787 (org-publish-find-date file)))
788 (?a . ,(or (plist-get project-plist :author) user-full-name)))))
790 (defun org-publish-find-title (file &optional reset)
791 "Find the title of FILE in project."
793 (and (not reset) (org-publish-cache-get-file-property file :title nil t))
794 (let* ((visiting (find-buffer-visiting file))
795 (buffer (or visiting (find-file-noselect file)))
796 title)
797 (with-current-buffer buffer
798 (org-mode)
799 (setq title
800 (or (org-element-interpret-data
801 (plist-get (org-export-get-environment) :title))
802 (file-name-nondirectory (file-name-sans-extension file)))))
803 (unless visiting (kill-buffer buffer))
804 (org-publish-cache-set-file-property file :title title)
805 title)))
807 (defun org-publish-find-date (file)
808 "Find the date of FILE in project.
809 If FILE provides a #+date keyword use it else use the file
810 system's modification time.
812 It returns time in `current-time' format."
813 (let* ((visiting (find-buffer-visiting file))
814 (file-buf (or visiting (find-file-noselect file nil)))
815 (date (plist-get
816 (with-current-buffer file-buf
817 (org-mode)
818 (org-export--get-inbuffer-options))
819 :date)))
820 (unless visiting (kill-buffer file-buf))
821 (if date (org-time-string-to-time date)
822 (when (file-exists-p file)
823 (nth 5 (file-attributes file))))))
827 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
828 ;;; Interactive publishing functions
830 ;;;###autoload
831 (defalias 'org-publish-project 'org-publish)
833 ;;;###autoload
834 (defun org-publish (project &optional force async)
835 "Publish PROJECT.
837 PROJECT is either a project name, as a string, or a project
838 alist (see `org-publish-project-alist' variable).
840 When optional argument FORCE is non-nil, force publishing all
841 files in PROJECT. With a non-nil optional argument ASYNC,
842 publishing will be done asynchronously, in another process."
843 (interactive
844 (list
845 (assoc (org-icompleting-read
846 "Publish project: "
847 org-publish-project-alist nil t)
848 org-publish-project-alist)
849 current-prefix-arg))
850 (let ((project-alist (if (not (stringp project)) (list project)
851 ;; If this function is called in batch mode,
852 ;; project is still a string here.
853 (list (assoc project org-publish-project-alist)))))
854 (if async
855 (org-export-async-start 'ignore
856 `(let ((org-publish-use-timestamps-flag
857 (if ',force nil ,org-publish-use-timestamps-flag)))
858 (org-publish-projects ',project-alist)))
859 (save-window-excursion
860 (let* ((org-publish-use-timestamps-flag
861 (if force nil org-publish-use-timestamps-flag)))
862 (org-publish-projects project-alist))))))
864 ;;;###autoload
865 (defun org-publish-all (&optional force async)
866 "Publish all projects.
867 With prefix argument FORCE, remove all files in the timestamp
868 directory and force publishing all projects. With a non-nil
869 optional argument ASYNC, publishing will be done asynchronously,
870 in another process."
871 (interactive "P")
872 (if async
873 (org-export-async-start 'ignore
874 `(when ',force (org-publish-remove-all-timestamps))
875 `(let ((org-publish-use-timestamps-flag
876 (if ',force nil ,org-publish-use-timestamps-flag)))
877 (org-publish-projects ',org-publish-project-alist)))
878 (when force (org-publish-remove-all-timestamps))
879 (save-window-excursion
880 (let ((org-publish-use-timestamps-flag
881 (if force nil org-publish-use-timestamps-flag)))
882 (org-publish-projects org-publish-project-alist)))))
885 ;;;###autoload
886 (defun org-publish-current-file (&optional force async)
887 "Publish the current file.
888 With prefix argument FORCE, force publish the file. When
889 optional argument ASYNC is non-nil, publishing will be done
890 asynchronously, in another process."
891 (interactive "P")
892 (let ((file (buffer-file-name (buffer-base-buffer))))
893 (if async
894 (org-export-async-start 'ignore
895 `(let ((org-publish-use-timestamps-flag
896 (if ',force nil ,org-publish-use-timestamps-flag)))
897 (org-publish-file ,file)))
898 (save-window-excursion
899 (let ((org-publish-use-timestamps-flag
900 (if force nil org-publish-use-timestamps-flag)))
901 (org-publish-file file))))))
903 ;;;###autoload
904 (defun org-publish-current-project (&optional force async)
905 "Publish the project associated with the current file.
906 With a prefix argument, force publishing of all files in
907 the project."
908 (interactive "P")
909 (save-window-excursion
910 (let ((project (org-publish-get-project-from-filename
911 (buffer-file-name (buffer-base-buffer)) 'up)))
912 (if project (org-publish project force async)
913 (error "File %s is not part of any known project"
914 (buffer-file-name (buffer-base-buffer)))))))
918 ;;; Index generation
920 (defun org-publish-collect-index (output backend info)
921 "Update index for a file in cache.
923 OUTPUT is the output from transcoding current file. BACKEND is
924 the back-end that was used for transcoding. INFO is a plist
925 containing publishing and export options.
927 The index relative to current file is stored as an alist. An
928 association has the following shape: (TERM FILE-NAME PARENT),
929 where TERM is the indexed term, as a string, FILE-NAME is the
930 original full path of the file where the term in encountered, and
931 PARENT is a reference to the headline, if any, containing the
932 original index keyword. When non-nil, this reference is a cons
933 cell. Its CAR is a symbol among `id', `custom-id' and `name' and
934 its CDR is a string."
935 (let ((file (plist-get info :input-file)))
936 (org-publish-cache-set-file-property
937 file :index
938 (delete-dups
939 (org-element-map (plist-get info :parse-tree) 'keyword
940 (lambda (k)
941 (when (equal (org-element-property :key k) "INDEX")
942 (let ((parent (org-export-get-parent-headline k)))
943 (list (org-element-property :value k)
944 file
945 (cond
946 ((not parent) nil)
947 ((let ((id (org-element-property :ID parent)))
948 (and id (cons 'id id))))
949 ((let ((id (org-element-property :CUSTOM_ID parent)))
950 (and id (cons 'custom-id id))))
951 (t (cons 'name
952 ;; Remove statistics cookie.
953 (replace-regexp-in-string
954 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
955 (org-element-property :raw-value parent)))))))))
956 info))))
957 ;; Return output unchanged.
958 output)
960 (defun org-publish-index-generate-theindex (project directory)
961 "Retrieve full index from cache and build \"theindex.org\".
962 PROJECT is the project the index relates to. DIRECTORY is the
963 publishing directory."
964 (let ((all-files (org-publish-get-base-files
965 project (plist-get (cdr project) :exclude)))
966 full-index)
967 ;; Compile full index and sort it alphabetically.
968 (dolist (file all-files
969 (setq full-index
970 (sort (nreverse full-index)
971 (lambda (a b) (string< (downcase (car a))
972 (downcase (car b)))))))
973 (let ((index (org-publish-cache-get-file-property file :index)))
974 (dolist (term index)
975 (unless (member term full-index) (push term full-index)))))
976 ;; Write "theindex.inc" in DIRECTORY.
977 (with-temp-file (expand-file-name "theindex.inc" directory)
978 (let ((current-letter nil) (last-entry nil))
979 (dolist (idx full-index)
980 (let* ((entry (org-split-string (car idx) "!"))
981 (letter (upcase (substring (car entry) 0 1)))
982 ;; Transform file into a path relative to publishing
983 ;; directory.
984 (file (file-relative-name
985 (nth 1 idx)
986 (plist-get (cdr project) :base-directory))))
987 ;; Check if another letter has to be inserted.
988 (unless (string= letter current-letter)
989 (insert (format "* %s\n" letter)))
990 ;; Compute the first difference between last entry and
991 ;; current one: it tells the level at which new items
992 ;; should be added.
993 (let* ((rank (if (equal entry last-entry) (1- (length entry))
994 (loop for n from 0 to (length entry)
995 unless (equal (nth n entry) (nth n last-entry))
996 return n)))
997 (len (length (nthcdr rank entry))))
998 ;; For each term after the first difference, create
999 ;; a new sub-list with the term as body. Moreover,
1000 ;; linkify the last term.
1001 (dotimes (n len)
1002 (insert
1003 (concat
1004 (make-string (* (+ rank n) 2) ? ) " - "
1005 (if (not (= (1- len) n)) (nth (+ rank n) entry)
1006 ;; Last term: Link it to TARGET, if possible.
1007 (let ((target (nth 2 idx)))
1008 (format
1009 "[[%s][%s]]"
1010 ;; Destination.
1011 (case (car target)
1012 ('nil (format "file:%s" file))
1013 (id (format "id:%s" (cdr target)))
1014 (custom-id (format "file:%s::#%s" file (cdr target)))
1015 (otherwise (format "file:%s::*%s" file (cdr target))))
1016 ;; Description.
1017 (car (last entry)))))
1018 "\n"))))
1019 (setq current-letter letter last-entry entry))))
1020 ;; Create "theindex.org", if it doesn't exist yet, and provide
1021 ;; a default index file.
1022 (let ((index.org (expand-file-name "theindex.org" directory)))
1023 (unless (file-exists-p index.org)
1024 (with-temp-file index.org
1025 (insert "#+TITLE: Index\n\n#+INCLUDE: \"theindex.inc\"\n\n")))))))
1029 ;;; External Fuzzy Links Resolution
1031 ;; This part implements tools to resolve [[file.org::*Some headline]]
1032 ;; links, where "file.org" belongs to the current project.
1034 (defun org-publish-collect-numbering (output backend info)
1035 (org-publish-cache-set-file-property
1036 (plist-get info :input-file) :numbering
1037 (mapcar (lambda (entry)
1038 (cons (org-split-string
1039 (replace-regexp-in-string
1040 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
1041 (org-element-property :raw-value (car entry))))
1042 (cdr entry)))
1043 (plist-get info :headline-numbering)))
1044 ;; Return output unchanged.
1045 output)
1047 (defun org-publish-resolve-external-fuzzy-link (file fuzzy)
1048 "Return numbering for headline matching FUZZY search in FILE.
1050 Return value is a list of numbers, or nil. This function allows
1051 to resolve external fuzzy links like:
1053 [[file.org::*fuzzy][description]"
1054 (when org-publish-cache
1055 (cdr (assoc (org-split-string
1056 (if (eq (aref fuzzy 0) ?*) (substring fuzzy 1) fuzzy))
1057 (org-publish-cache-get-file-property
1058 (expand-file-name file) :numbering nil t)))))
1062 ;;; Caching functions
1064 (defun org-publish-write-cache-file (&optional free-cache)
1065 "Write `org-publish-cache' to file.
1066 If FREE-CACHE, empty the cache."
1067 (unless org-publish-cache
1068 (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 (make-hash-table :test 'equal :weakness nil :size 100))\n")
1076 (maphash (lambda (k v)
1077 (insert
1078 (format (concat "(puthash %S "
1079 (if (or (listp v) (symbolp v))
1080 "'" "")
1081 "%S org-publish-cache)\n") k v)))
1082 org-publish-cache)))
1083 (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."
1088 (unless project-name
1089 (error "Cannot initialize `org-publish-cache' without projects name in `org-publish-initialize-cache'"))
1091 (unless (file-exists-p org-publish-timestamp-directory)
1092 (make-directory org-publish-timestamp-directory t))
1093 (unless (file-directory-p org-publish-timestamp-directory)
1094 (error "Org publish timestamp: %s is not a directory"
1095 org-publish-timestamp-directory))
1097 (unless (and org-publish-cache
1098 (string= (org-publish-cache-get ":project:") project-name))
1099 (let* ((cache-file
1100 (concat
1101 (expand-file-name org-publish-timestamp-directory)
1102 project-name ".cache"))
1103 (cexists (file-exists-p cache-file)))
1105 (when org-publish-cache (org-publish-reset-cache))
1107 (if cexists (load-file cache-file)
1108 (setq org-publish-cache
1109 (make-hash-table :test 'equal :weakness nil :size 100))
1110 (org-publish-cache-set ":project:" project-name)
1111 (org-publish-cache-set ":cache-file:" cache-file))
1112 (unless cexists (org-publish-write-cache-file nil))))
1113 org-publish-cache)
1115 (defun org-publish-reset-cache ()
1116 "Empty org-publish-cache and reset it nil."
1117 (message "%s" "Resetting org-publish-cache")
1118 (when (hash-table-p org-publish-cache)
1119 (clrhash org-publish-cache))
1120 (setq org-publish-cache nil))
1122 (defun org-publish-cache-file-needs-publishing
1123 (filename &optional pub-dir pub-func base-dir)
1124 "Check the timestamp of the last publishing of FILENAME.
1125 Non-nil if the file needs publishing. The function also checks
1126 if any included files have been more recently published, so that
1127 the file including them will be republished as well."
1128 (unless org-publish-cache
1129 (error
1130 "`org-publish-cache-file-needs-publishing' called, but no cache present"))
1131 (let* ((case-fold-search t)
1132 (key (org-publish-timestamp-filename filename pub-dir pub-func))
1133 (pstamp (org-publish-cache-get key))
1134 (visiting (find-buffer-visiting filename))
1135 included-files-ctime buf)
1137 (when (equal (file-name-extension filename) "org")
1138 (setq buf (find-file (expand-file-name filename)))
1139 (with-current-buffer buf
1140 (goto-char (point-min))
1141 (while (re-search-forward
1142 "^#\\+INCLUDE:[ \t]+\"\\([^\t\n\r\"]*\\)\"[ \t]*.*$" nil t)
1143 (let* ((included-file (expand-file-name (match-string 1))))
1144 (add-to-list 'included-files-ctime
1145 (org-publish-cache-ctime-of-src included-file) t))))
1146 (unless visiting (kill-buffer buf)))
1147 (if (null pstamp) t
1148 (let ((ctime (org-publish-cache-ctime-of-src filename)))
1149 (or (< pstamp ctime)
1150 (when included-files-ctime
1151 (not (null (delq nil (mapcar (lambda(ct) (< ctime ct))
1152 included-files-ctime))))))))))
1154 (defun org-publish-cache-set-file-property
1155 (filename property value &optional project-name)
1156 "Set the VALUE for a PROPERTY of file FILENAME in publishing cache to VALUE.
1157 Use cache file of PROJECT-NAME. If the entry does not exist, it
1158 will be created. Return VALUE."
1159 ;; Evtl. load the requested cache file:
1160 (if project-name (org-publish-initialize-cache project-name))
1161 (let ((pl (org-publish-cache-get filename)))
1162 (if pl (progn (plist-put pl property value) value)
1163 (org-publish-cache-get-file-property
1164 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. If the entry will
1171 be created, unless NO-CREATE is not nil."
1172 ;; Evtl. load the requested cache file:
1173 (if project-name (org-publish-initialize-cache project-name))
1174 (let ((pl (org-publish-cache-get filename)) retval)
1175 (if pl
1176 (if (plist-member pl property)
1177 (setq retval (plist-get pl property))
1178 (setq retval default))
1179 ;; no pl yet:
1180 (unless no-create
1181 (org-publish-cache-set filename (list property default)))
1182 (setq retval default))
1183 retval))
1185 (defun org-publish-cache-get (key)
1186 "Return the value stored in `org-publish-cache' for key KEY.
1187 Returns nil, if no value or nil is found, or the cache does not
1188 exist."
1189 (unless org-publish-cache
1190 (error "`org-publish-cache-get' called, but no cache present"))
1191 (gethash key org-publish-cache))
1193 (defun org-publish-cache-set (key value)
1194 "Store KEY VALUE pair in `org-publish-cache'.
1195 Returns value on success, else nil."
1196 (unless org-publish-cache
1197 (error "`org-publish-cache-set' called, but no cache present"))
1198 (puthash key value org-publish-cache))
1200 (defun org-publish-cache-ctime-of-src (file)
1201 "Get the ctime of FILE as an integer."
1202 (let ((attr (file-attributes
1203 (expand-file-name (or (file-symlink-p file) file)
1204 (file-name-directory file)))))
1205 (+ (lsh (car (nth 5 attr)) 16)
1206 (cadr (nth 5 attr)))))
1209 (provide 'ox-publish)
1211 ;; Local variables:
1212 ;; generated-autoload-file: "org-loaddefs.el"
1213 ;; End:
1215 ;;; ox-publish.el ends here