org-footnote.el 28 KB

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