org-footnote.el 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. ;;; org-footnote.el --- Footnote support in Org and elsewhere
  2. ;;
  3. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Keywords: outlines, hypermedia, calendar, wp
  7. ;; Homepage: http://orgmode.org
  8. ;; Version: 7.5
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; 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/>.
  22. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  23. ;;
  24. ;;; Commentary:
  25. ;; This file contains the code dealing with footnotes in Org-mode.
  26. ;; The code can also be used in arbitrary text modes to provide
  27. ;; footnotes. Compared to Steven L Baur's footnote.el it provides
  28. ;; better support for resuming editing. It is less configurable than
  29. ;; Steve's code, though.
  30. ;;; Code:
  31. (eval-when-compile
  32. (require 'cl))
  33. (require 'org-macs)
  34. (require 'org-compat)
  35. (declare-function org-in-commented-line "org" ())
  36. (declare-function org-in-regexp "org" (re &optional nlines visually))
  37. (declare-function org-mark-ring-push "org" (&optional pos buffer))
  38. (declare-function outline-next-heading "outline")
  39. (declare-function org-trim "org" (s))
  40. (declare-function org-show-context "org" (&optional key))
  41. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  42. (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
  43. (declare-function org-in-verbatim-emphasis "org" ())
  44. (declare-function org-inside-latex-macro-p "org" ())
  45. (declare-function org-id-uuid "org" ())
  46. (declare-function org-fill-paragraph "org" (justify))
  47. (defvar org-odd-levels-only) ;; defined in org.el
  48. (defvar message-signature-separator) ;; defined in message.el
  49. (defconst org-footnote-re
  50. ;; Only [1]-like footnotes are closed in this regexp, as footnotes
  51. ;; from other types might contain square brackets (i.e. links) in
  52. ;; their definition.
  53. ;;
  54. ;; `org-re' is used for regexp compatibility with XEmacs.
  55. (org-re (concat "\\[\\(?:"
  56. ;; Match inline footnotes.
  57. "fn:\\([-_[:word:]]+\\)?:\\|"
  58. ;; Match other footnotes.
  59. "\\(?:\\([0-9]+\\)\\]\\)\\|"
  60. "\\(fn:[-_[:word:]]+\\)"
  61. "\\)"))
  62. "Regular expression for matching footnotes.")
  63. (defconst org-footnote-definition-re
  64. (org-re "^\\(\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]\\)")
  65. "Regular expression matching the definition of a footnote.")
  66. (defgroup org-footnote nil
  67. "Footnotes in Org-mode."
  68. :tag "Org Footnote"
  69. :group 'org)
  70. (defcustom org-footnote-section "Footnotes"
  71. "Outline heading containing footnote definitions before export.
  72. This can be nil, to place footnotes locally at the end of the current
  73. outline node. If can also be the name of a special outline heading
  74. under which footnotes should be put.
  75. This variable defines the place where Org puts the definition
  76. automatically, i.e. when creating the footnote, and when sorting the notes.
  77. However, by hand you may place definitions *anywhere*.
  78. If this is a string, during export, all subtrees starting with this
  79. heading will be removed after extracting footnote definitions."
  80. :group 'org-footnote
  81. :type '(choice
  82. (string :tag "Collect footnotes under heading")
  83. (const :tag "Define footnotes locally" nil)))
  84. (defcustom org-footnote-tag-for-non-org-mode-files "Footnotes:"
  85. "Tag marking the beginning of footnote section.
  86. The Org-mode footnote engine can be used in arbitrary text files as well
  87. as in Org-mode. Outside Org-mode, new footnotes are always placed at
  88. the end of the file. When you normalize the notes, any line containing
  89. only this tag will be removed, a new one will be inserted at the end
  90. of the file, followed by the collected and normalized footnotes."
  91. :group 'org-footnote
  92. :type 'string)
  93. (defcustom org-footnote-define-inline nil
  94. "Non-nil means define footnotes inline, at reference location.
  95. When nil, footnotes will be defined in a special section near
  96. the end of the document. When t, the [fn:label:definition] notation
  97. will be used to define the footnote at the reference position."
  98. :group 'org-footnote
  99. :type 'boolean)
  100. (defcustom org-footnote-auto-label t
  101. "Non-nil means define automatically new labels for footnotes.
  102. Possible values are:
  103. nil prompt the user for each label
  104. t create unique labels of the form [fn:1], [fn:2], ...
  105. confirm like t, but let the user edit the created value. In particular,
  106. the label can be removed from the minibuffer, to create
  107. an anonymous footnote.
  108. random Automatically generate a unique, random label.
  109. plain Automatically create plain number labels like [1]"
  110. :group 'org-footnote
  111. :type '(choice
  112. (const :tag "Prompt for label" nil)
  113. (const :tag "Create automatic [fn:N]" t)
  114. (const :tag "Offer automatic [fn:N] for editing" confirm)
  115. (const :tag "Create a random label" random)
  116. (const :tag "Create automatic [N]" plain)))
  117. (defcustom org-footnote-auto-adjust nil
  118. "Non-nil means automatically adjust footnotes after insert/delete.
  119. When this is t, after each insertion or deletion of a footnote,
  120. simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
  121. If you want to have just sorting or just renumbering, set this variable
  122. to `sort' or `renumber'.
  123. The main values of this variable can be set with in-buffer options:
  124. #+STARTUP: fnadjust
  125. #+STARTUP: nofnadjust"
  126. :group 'org-footnote
  127. :type '(choice
  128. (const :tag "Renumber" renumber)
  129. (const :tag "Sort" sort)
  130. (const :tag "Renumber and Sort" t)))
  131. (defcustom org-footnote-fill-after-inline-note-extraction nil
  132. "Non-nil means fill paragraphs after extracting footnotes.
  133. When extracting inline footnotes, the lengths of lines can change a lot.
  134. When this option is set, paragraphs from which an inline footnote has been
  135. extracted will be filled again."
  136. :group 'org-footnote
  137. :type 'boolean)
  138. (defun org-footnote-at-reference-p ()
  139. "Is the cursor at a footnote reference?
  140. If so, return an list containing its label, beginning and ending
  141. positions, and the definition, if local."
  142. (when (and (not (or (org-in-commented-line)
  143. (org-in-verbatim-emphasis)))
  144. (or (org-in-regexp org-footnote-re)
  145. (save-excursion (re-search-backward org-footnote-re nil t)))
  146. ;; A footnote reference cannot start at bol.
  147. (/= (match-beginning 0) (point-at-bol)))
  148. (let* ((beg (match-beginning 0))
  149. (label (or (match-string 2) (match-string 3)
  150. ;; Anonymous footnotes don't have labels
  151. (and (match-string 1) (concat "fn:" (match-string 1)))))
  152. ;; Inline footnotes don't end at (match-end 0) as
  153. ;; `org-footnote-re' stops just after the second colon.
  154. ;; Find the real ending with `scan-sexps', so Org doesn't
  155. ;; get fooled by unrelated closing square brackets.
  156. (end (ignore-errors (scan-sexps beg 1))))
  157. ;; Point is really at a reference if it's located before true
  158. ;; ending of the footnote and isn't within a LaTeX macro. About
  159. ;; that case, some special attention should be paid. Indeed,
  160. ;; when two footnotes are side by side, once the first one is
  161. ;; changed into LaTeX, the second one might then be considered
  162. ;; as an optional argument of the command. To prevent that, we
  163. ;; have a look at the `org-protected' property of that LaTeX
  164. ;; command.
  165. (when (and end (< (point) end)
  166. (or (not (org-inside-latex-macro-p))
  167. (and (get-text-property (1- beg) 'org-protected)
  168. (not (get-text-property beg 'org-protected)))))
  169. (list label beg end
  170. ;; Definition: ensure this is an inline footnote first.
  171. (and (or (not label) (match-string 1))
  172. (org-trim (buffer-substring (match-end 0) (1- end)))))))))
  173. (defun org-footnote-at-definition-p ()
  174. "Is the cursor at a footnote definition?
  175. This matches only pure definitions like [1] or [fn:name] at the beginning
  176. of a line. It does not match references like [fn:name:definition], where the
  177. footnote text is included and defined locally.
  178. The return value will be nil if not at a footnote definition, and a list with
  179. label, start, end and definition of the footnote otherwise."
  180. (save-excursion
  181. (end-of-line)
  182. (let ((lim (save-excursion (re-search-backward "^\\*+ \\|^[ \t]*$" nil t))))
  183. (when (re-search-backward org-footnote-definition-re lim t)
  184. (end-of-line)
  185. (list (match-string 2)
  186. (match-beginning 0)
  187. (save-match-data
  188. (or (and (re-search-forward
  189. (org-re "^[ \t]*$\\|^\\*+ \\|^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
  190. nil t)
  191. (progn (skip-chars-forward " \t\n") (point-at-bol)))
  192. (point-max)))
  193. (org-trim (buffer-substring (match-end 0) (point))))))))
  194. (defun org-footnote-get-next-reference (&optional label backward limit)
  195. "Return complete reference of the next footnote.
  196. If LABEL is provided, get the next reference of that footnote. If
  197. BACKWARD is non-nil, find previous reference instead. LIMIT is
  198. the buffer position bounding the search.
  199. Return value is a list like those provided by `org-footnote-at-reference-p'.
  200. If no footnote is found, return nil."
  201. (save-excursion
  202. (let* ((label-fmt (if label (format "\\[%s[]:]" label) org-footnote-re)))
  203. (catch 'exit
  204. (while t
  205. (unless (funcall (if backward #'re-search-backward #'re-search-forward)
  206. label-fmt limit t)
  207. (throw 'exit nil))
  208. (unless backward (backward-char))
  209. (let ((ref (org-footnote-at-reference-p)))
  210. (when ref (throw 'exit ref))))))))
  211. (defun org-footnote-next-reference-or-definition (limit)
  212. "Move point to next footnote reference or definition.
  213. LIMIT is the buffer position bounding the search.
  214. Return value is a list like those provided by
  215. `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
  216. If no footnote is found, return nil."
  217. (let* (ref)
  218. (catch 'exit
  219. (while t
  220. (unless (re-search-forward org-footnote-re limit t)
  221. (throw 'exit nil))
  222. ;; Beware: with [1]-like footnotes point will be just after
  223. ;; the closing square bracket.
  224. (backward-char)
  225. (cond
  226. ((setq ref (org-footnote-at-reference-p))
  227. (throw 'exit ref))
  228. ;; Definition: also grab the last square bracket, only
  229. ;; matched in `org-footnote-re' for [1]-like footnotes.
  230. ((= (point-at-bol) (match-beginning 0))
  231. (let ((end (match-end 0)))
  232. (throw 'exit
  233. (list nil (match-beginning 0)
  234. (if (eq (char-before end) 93) end (1+ end)))))))))))
  235. (defun org-footnote-get-definition (label)
  236. "Return label, boundaries and definition of the footnote LABEL."
  237. (let* ((label (regexp-quote (org-footnote-normalize-label label)))
  238. (re (format "^\\[%s\\]\\|.\\[%s:" label label))
  239. pos)
  240. (save-excursion
  241. (when (or (re-search-forward re nil t)
  242. (and (goto-char (point-min))
  243. (re-search-forward re nil t))
  244. (and (progn (widen) t)
  245. (goto-char (point-min))
  246. (re-search-forward re nil t)))
  247. (let ((refp (org-footnote-at-reference-p)))
  248. (cond
  249. ((and (nth 3 refp) refp))
  250. ((org-footnote-at-definition-p))))))))
  251. (defun org-footnote-goto-definition (label)
  252. "Move point to the definition of the footnote LABEL."
  253. (interactive "sLabel: ")
  254. (org-mark-ring-push)
  255. (let ((def (org-footnote-get-definition label)))
  256. (if (not def)
  257. (error "Cannot find definition of footnote %s" label)
  258. (goto-char (nth 1 def))
  259. (looking-at (format "\\[%s\\]\\|\\[%s:" label label))
  260. (goto-char (match-end 0))
  261. (org-show-context 'link-search)
  262. (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
  263. (defun org-footnote-goto-previous-reference (label)
  264. "Find the first closest (to point) reference of footnote with label LABEL."
  265. (interactive "sLabel: ")
  266. (org-mark-ring-push)
  267. (let* ((label (org-footnote-normalize-label label)) ref)
  268. (save-excursion
  269. (setq ref (or (org-footnote-get-next-reference label t)
  270. (org-footnote-get-next-reference label)
  271. (save-restriction
  272. (widen)
  273. (or
  274. (org-footnote-get-next-reference label t)
  275. (org-footnote-get-next-reference label))))))
  276. (if (not ref)
  277. (error "Cannot find reference of footnote %s" label)
  278. (goto-char (nth 1 ref))
  279. (org-show-context 'link-search))))
  280. (defun org-footnote-normalize-label (label)
  281. "Return LABEL as an appropriate string."
  282. (cond
  283. ((numberp label) (number-to-string label))
  284. ((equal "" label) nil)
  285. ((not (string-match "^[0-9]+$\\|^fn:" label))
  286. (concat "fn:" label))
  287. (t label)))
  288. (defun org-footnote-all-labels (&optional with-defs)
  289. "Return list with all defined foot labels used in the buffer.
  290. If WITH-DEFS is non-nil, also associate the definition to each
  291. label. The function will then return an alist whose key is label
  292. and value definition."
  293. (let (rtn
  294. (push-to-rtn
  295. (function
  296. ;; Depending on WITH-DEFS, store label or (label . def) of
  297. ;; footnote reference/definition given as argument in RTN.
  298. (lambda (el)
  299. (let ((lbl (car el)))
  300. (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
  301. (save-excursion
  302. (save-restriction
  303. (widen)
  304. ;; Find all labels found in definitions.
  305. (goto-char (point-min))
  306. (let (def)
  307. (while (re-search-forward org-footnote-definition-re nil t)
  308. (when (setq def (org-footnote-at-definition-p))
  309. (funcall push-to-rtn def))))
  310. ;; Find all labels found in references.
  311. (goto-char (point-min))
  312. (let (ref)
  313. (while (setq ref (org-footnote-get-next-reference))
  314. (goto-char (nth 2 ref))
  315. (and (car ref) ; ignore anonymous footnotes
  316. (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
  317. (funcall push-to-rtn ref))))))
  318. rtn))
  319. (defun org-footnote-unique-label (&optional current)
  320. "Return a new unique footnote label.
  321. The returns the firsts fn:N labels that is currently not used."
  322. (unless current (setq current (org-footnote-all-labels)))
  323. (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
  324. (cnt 1))
  325. (while (member (format fmt cnt) current)
  326. (incf cnt))
  327. (format fmt cnt)))
  328. (defvar org-footnote-label-history nil
  329. "History of footnote labels entered in current buffer.")
  330. (make-variable-buffer-local 'org-footnote-label-history)
  331. (defun org-footnote-new ()
  332. "Insert a new footnote.
  333. This command prompts for a label. If this is a label referencing an
  334. existing label, only insert the label. If the footnote label is empty
  335. or new, let the user edit the definition of the footnote."
  336. (interactive)
  337. (let* ((labels (and (not (equal org-footnote-auto-label 'random))
  338. (org-footnote-all-labels)))
  339. (propose (org-footnote-unique-label labels))
  340. (label
  341. (org-footnote-normalize-label
  342. (cond
  343. ((member org-footnote-auto-label '(t plain))
  344. propose)
  345. ((equal org-footnote-auto-label 'random)
  346. (require 'org-id)
  347. (substring (org-id-uuid) 0 8))
  348. (t
  349. (completing-read
  350. "Label (leave empty for anonymous): "
  351. (mapcar 'list labels) nil nil
  352. (if (eq org-footnote-auto-label 'confirm) propose nil)
  353. 'org-footnote-label-history))))))
  354. (cond
  355. ((not label)
  356. (insert "[fn:: ]")
  357. (backward-char 1))
  358. ((member label labels)
  359. (insert "[" label "]")
  360. (message "New reference to existing note"))
  361. (org-footnote-define-inline
  362. (insert "[" label ": ]")
  363. (backward-char 1)
  364. (org-footnote-auto-adjust-maybe))
  365. (t
  366. (insert "[" label "]")
  367. (org-footnote-create-definition label)
  368. (org-footnote-auto-adjust-maybe)))))
  369. (defun org-footnote-create-definition (label)
  370. "Start the definition of a footnote with label LABEL."
  371. (interactive "sLabel: ")
  372. (let ((label (org-footnote-normalize-label label)))
  373. (cond
  374. ((org-mode-p)
  375. ;; No section, put footnote into the current outline node Try to
  376. ;; find or make the special node
  377. (when org-footnote-section
  378. (goto-char (point-min))
  379. (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
  380. (unless (or (re-search-forward re nil t)
  381. (and (progn (widen) t)
  382. (re-search-forward re nil t)))
  383. (goto-char (point-max))
  384. (insert "\n\n* " org-footnote-section "\n"))))
  385. ;; Now go to the end of this entry and insert there.
  386. (org-footnote-goto-local-insertion-point)
  387. (org-show-context 'link-search))
  388. (t
  389. (let ((re (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$")))
  390. (unless (re-search-forward re nil t)
  391. (let ((max (if (and (derived-mode-p 'message-mode)
  392. (re-search-forward message-signature-separator nil t))
  393. (progn (beginning-of-line) (point))
  394. (goto-char (point-max)))))
  395. (skip-chars-backward " \t\r\n")
  396. (delete-region (point) max)
  397. (insert "\n\n")
  398. (insert org-footnote-tag-for-non-org-mode-files "\n"))))
  399. ;; Skip existing footnotes
  400. (while (re-search-forward "^[[:space:]]*\\[[^]]+\\] " nil t)
  401. (forward-line))))
  402. (insert "\n[" label "] \n")
  403. (goto-char (1- (point)))
  404. (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
  405. ;;;###autoload
  406. (defun org-footnote-action (&optional special)
  407. "Do the right thing for footnotes.
  408. When at a footnote reference, jump to the definition.
  409. When at a definition, jump to the references if they exist, offer
  410. to create them otherwise.
  411. When neither at definition or reference, create a new footnote,
  412. interactively.
  413. With prefix arg SPECIAL, offer additional commands in a menu."
  414. (interactive "P")
  415. (let (tmp c)
  416. (cond
  417. (special
  418. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
  419. (setq c (read-char-exclusive))
  420. (cond
  421. ((eq c ?s) (org-footnote-normalize 'sort))
  422. ((eq c ?r) (org-footnote-renumber-fn:N))
  423. ((eq c ?S)
  424. (org-footnote-renumber-fn:N)
  425. (org-footnote-normalize 'sort))
  426. ((eq c ?n) (org-footnote-normalize))
  427. ((eq c ?d) (org-footnote-delete))
  428. (t (error "No such footnote command %c" c))))
  429. ((setq tmp (org-footnote-at-reference-p))
  430. (cond
  431. ;; Anonymous footnote: move point at the beginning of its
  432. ;; definition.
  433. ((not (car tmp))
  434. (goto-char (nth 1 tmp))
  435. (forward-char 5))
  436. ;; A definition exists: move to it.
  437. ((ignore-errors (org-footnote-goto-definition (car tmp))))
  438. ;; No definition exists: offer to create it.
  439. ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
  440. (org-footnote-create-definition (car tmp)))))
  441. ((setq tmp (org-footnote-at-definition-p))
  442. (org-footnote-goto-previous-reference (car tmp)))
  443. (t (org-footnote-new)))))
  444. (defvar org-footnote-insert-pos-for-preprocessor 'point-max
  445. "See `org-footnote-normalize'.")
  446. ;;;###autoload
  447. (defun org-footnote-normalize (&optional sort-only pre-process-p)
  448. "Collect the footnotes in various formats and normalize them.
  449. This finds the different sorts of footnotes allowed in Org, and
  450. normalizes them to the usual [N] format that is understood by the
  451. Org-mode exporters.
  452. When SORT-ONLY is set, only sort the footnote definitions into the
  453. referenced sequence.
  454. When PRE-PROCESS-P is non-nil, the default action, is to insert
  455. normalized footnotes towards the end of the pre-processing buffer.
  456. Some exporters like docbook, odt, etc. expect that footnote
  457. definitions be available before any references to them. Such
  458. exporters can let bind `org-footnote-insert-pos-for-preprocessor' to
  459. symbol 'point-min to achieve the desired behaviour.
  460. Additional note on `org-footnote-insert-pos-for-preprocessor':
  461. 1. This variable has not effect when FOR-PREPROCESSOR is nil.
  462. 2. This variable (potentially) obviates the need for extra scan
  463. of pre-processor buffer as witnessed in
  464. `org-export-docbook-get-footnotes'."
  465. ;; This is based on Paul's function, but rewritten.
  466. ;;
  467. ;; Re-create `org-with-limited-levels', but not limited to Org
  468. ;; buffers.
  469. (let* ((limit-level
  470. (and (boundp 'org-inlinetask-min-level)
  471. org-inlinetask-min-level
  472. (1- org-inlinetask-min-level)))
  473. (nstars (and limit-level
  474. (if org-odd-levels-only
  475. (and limit-level (1- (* limit-level 2)))
  476. limit-level)))
  477. (outline-regexp
  478. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
  479. ;; Determine the highest marker used so far.
  480. (ref-table (when pre-process-p org-export-footnotes-seen))
  481. (count (if (and pre-process-p ref-table)
  482. (apply 'max (mapcar (lambda (e) (nth 1 e)) ref-table))
  483. 0))
  484. ins-point ref)
  485. (save-excursion
  486. ;; 1. Find every footnote reference, extract the definition, and
  487. ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
  488. ;; normalize references.
  489. (goto-char (point-min))
  490. (while (setq ref (org-footnote-get-next-reference))
  491. (let* ((lbl (car ref))
  492. ;; When footnote isn't anonymous, check if it's label
  493. ;; (REF) is already stored in REF-TABLE. In that case,
  494. ;; extract number used to identify it (MARKER). If
  495. ;; footnote is unknown, increment the global counter
  496. ;; (COUNT) to create an unused identifier.
  497. (a (and lbl (assoc lbl ref-table)))
  498. (marker (or (nth 1 a) (incf count)))
  499. ;; Is the reference inline or pointing to an inline
  500. ;; footnote?
  501. (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
  502. ;; Replace footnote reference with [MARKER]. Maybe fill
  503. ;; paragraph once done. If SORT-ONLY is non-nil, only move
  504. ;; to the end of reference found to avoid matching it twice.
  505. ;; If PRE-PROCESS-P isn't nil, also add `org-footnote'
  506. ;; property to it, so it can be easily recognized by
  507. ;; exporters.
  508. (if sort-only
  509. (goto-char (nth 2 ref))
  510. (delete-region (nth 1 ref) (nth 2 ref))
  511. (goto-char (nth 1 ref))
  512. (let ((new-ref (format "[%d]" marker)))
  513. (when pre-process-p (org-add-props new-ref '(org-footnote t)))
  514. (insert new-ref))
  515. (and inlinep
  516. org-footnote-fill-after-inline-note-extraction
  517. (org-fill-paragraph)))
  518. ;; Add label (REF), identifier (MARKER) and definition (DEF)
  519. ;; to REF-TABLE if data was unknown.
  520. (unless a
  521. (let ((def (or (nth 3 ref) ; inline
  522. (and pre-process-p
  523. (cdr (assoc lbl org-export-footnotes-data)))
  524. (nth 3 (org-footnote-get-definition lbl)))))
  525. (push (list lbl marker def inlinep) ref-table)))
  526. ;; Remove definition of non-inlined footnotes.
  527. (unless inlinep (org-footnote-delete-definitions lbl))))
  528. ;; 2. Find and remove the footnote section, if any. If we are
  529. ;; exporting, insert it again at end of buffer. In a non
  530. ;; org-mode file, insert instead
  531. ;; `org-footnote-tag-for-non-org-mode-files'.
  532. (goto-char (point-min))
  533. (cond
  534. ((org-mode-p)
  535. (if (and org-footnote-section
  536. (re-search-forward
  537. (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
  538. "[ \t]*$")
  539. nil t))
  540. (if pre-process-p
  541. (replace-match "")
  542. (org-back-to-heading t)
  543. (forward-line 1)
  544. (setq ins-point (point))
  545. (delete-region (point) (org-end-of-subtree t)))
  546. (goto-char (point-max))
  547. (unless pre-process-p
  548. (when org-footnote-section
  549. (or (bolp) (insert "\n"))
  550. (insert "* " org-footnote-section "\n")
  551. (setq ins-point (point))))))
  552. (t
  553. (if (re-search-forward
  554. (concat "^"
  555. (regexp-quote org-footnote-tag-for-non-org-mode-files)
  556. "[ \t]*$")
  557. nil t)
  558. (replace-match ""))
  559. (goto-char (point-max))
  560. (skip-chars-backward " \t\n\r")
  561. (delete-region (point) (point-max))
  562. (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n")
  563. (setq ins-point (point))))
  564. ;; 3. Clean-up REF-TABLE.
  565. (setq ref-table
  566. (delq nil
  567. (mapcar
  568. (lambda (x)
  569. (cond
  570. ;; When only sorting, ignore inline footnotes.
  571. ((and sort-only (nth 3 x)) nil)
  572. ;; No definition available: provide one.
  573. ((not (nth 2 x))
  574. (append (butlast x 2)
  575. (list (format "DEFINITION NOT FOUND: %s" (car x))
  576. (nth 3 x))))
  577. (t x)))
  578. ref-table)))
  579. (setq ref-table (nreverse ref-table))
  580. ;; 4. Insert the footnotes again in the buffer, at the
  581. ;; appropriate spot.
  582. (goto-char (or
  583. (and pre-process-p
  584. (eq org-footnote-insert-pos-for-preprocessor 'point-min)
  585. (point-min))
  586. ins-point
  587. (point-max)))
  588. (cond
  589. ((not ref-table)) ; no footnote: exit
  590. ;; Cases when footnotes should be inserted together in one place.
  591. ((or (not (org-mode-p))
  592. org-footnote-section
  593. (not sort-only))
  594. (insert "\n"
  595. (mapconcat (lambda (x) (format "[%s] %s"
  596. (nth (if sort-only 0 1) x) (nth 2 x)))
  597. ref-table "\n\n")
  598. "\n\n")
  599. ;; When exporting, add newly insert markers along with their
  600. ;; associated definition to `org-export-footnotes-seen'.
  601. (when pre-process-p
  602. (setq org-export-footnotes-seen ref-table)))
  603. ;; Else, insert each definition at the end of the section
  604. ;; containing their first reference. Happens only in Org
  605. ;; files with no special footnote section, and only when
  606. ;; doing sorting.
  607. (t (mapc 'org-insert-footnote-reference-near-definition
  608. ref-table))))))
  609. (defun org-insert-footnote-reference-near-definition (entry)
  610. "Find first reference of footnote ENTRY and insert the definition there.
  611. ENTRY is (fn-label num-mark definition)."
  612. (when (car entry)
  613. (goto-char (point-min))
  614. (let ((ref (org-footnote-get-next-reference (car entry))))
  615. (when ref
  616. (goto-char (nth 2 ref))
  617. (org-footnote-goto-local-insertion-point)
  618. (insert (format "\n[%s] %s\n" (car entry) (nth 2 entry)))))))
  619. (defun org-footnote-goto-local-insertion-point ()
  620. "Find insertion point for footnote, just before next outline heading."
  621. (org-with-limited-levels (outline-next-heading))
  622. (or (bolp) (newline))
  623. (beginning-of-line 0)
  624. (while (and (not (bobp)) (= (char-after) ?#))
  625. (beginning-of-line 0))
  626. (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
  627. (end-of-line 1)
  628. (skip-chars-backward "\n\r\t ")
  629. (forward-line))
  630. (defun org-footnote-delete-references (label)
  631. "Delete every reference to footnote LABEL.
  632. Return the number of footnotes removed."
  633. (save-excursion
  634. (goto-char (point-min))
  635. (let (ref (nref 0))
  636. (while (setq ref (org-footnote-get-next-reference label))
  637. (goto-char (nth 1 ref))
  638. (delete-region (nth 1 ref) (nth 2 ref))
  639. (incf nref))
  640. nref)))
  641. (defun org-footnote-delete-definitions (label)
  642. "Delete every definition of the footnote LABEL.
  643. Return the number of footnotes removed."
  644. (save-excursion
  645. (goto-char (point-min))
  646. (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
  647. (ndef 0))
  648. (while (re-search-forward def-re nil t)
  649. (let ((full-def (org-footnote-at-definition-p)))
  650. (delete-region (nth 1 full-def) (nth 2 full-def)))
  651. (incf ndef))
  652. ndef)))
  653. (defun org-footnote-delete (&optional label)
  654. "Delete the footnote at point.
  655. This will remove the definition (even multiple definitions if they exist)
  656. and all references of a footnote label.
  657. If LABEL is non-nil, delete that footnote instead."
  658. (catch 'done
  659. (let* ((nref 0) (ndef 0) x
  660. ;; 1. Determine LABEL of footnote at point.
  661. (label (cond
  662. ;; LABEL is provided as argument.
  663. (label)
  664. ;; Footnote reference at point. If the footnote is
  665. ;; anonymous, delete it and exit instead.
  666. ((setq x (org-footnote-at-reference-p))
  667. (or (car x)
  668. (progn
  669. (delete-region (nth 1 x) (nth 2 x))
  670. (message "Anonymous footnote removed")
  671. (throw 'done t))))
  672. ;; Footnote definition at point.
  673. ((setq x (org-footnote-at-definition-p))
  674. (car x))
  675. (t (error "Don't know which footnote to remove")))))
  676. ;; 2. Now that LABEL is non-nil, find every reference and every
  677. ;; definition, and delete them.
  678. (setq nref (org-footnote-delete-references label)
  679. ndef (org-footnote-delete-definitions label))
  680. ;; 3. Verify consistency of footnotes and notify user.
  681. (org-footnote-auto-adjust-maybe)
  682. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  683. ndef nref label))))
  684. (defun org-footnote-renumber-fn:N ()
  685. "Renumber the simple footnotes like fn:17 into a sequence in the document."
  686. (interactive)
  687. (let (map i (n 0))
  688. (save-excursion
  689. (save-restriction
  690. (widen)
  691. (goto-char (point-min))
  692. (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
  693. (setq i (string-to-number (match-string 1)))
  694. (when (and (string-match "\\S-" (buffer-substring
  695. (point-at-bol) (match-beginning 0)))
  696. (not (assq i map)))
  697. (push (cons i (number-to-string (incf n))) map)))
  698. (goto-char (point-min))
  699. (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
  700. (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
  701. (defun org-footnote-auto-adjust-maybe ()
  702. "Renumber and/or sort footnotes according to user settings."
  703. (when (memq org-footnote-auto-adjust '(t renumber))
  704. (org-footnote-renumber-fn:N))
  705. (when (memq org-footnote-auto-adjust '(t sort))
  706. (let ((label (car (org-footnote-at-definition-p))))
  707. (org-footnote-normalize 'sort)
  708. (when label
  709. (goto-char (point-min))
  710. (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
  711. nil t)
  712. (progn (insert " ")
  713. (just-one-space)))))))
  714. (provide 'org-footnote)
  715. ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
  716. ;;; org-footnote.el ends here