org-footnote.el 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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. (if (numberp label) (setq label (number-to-string label)))
  272. (if (not (string-match "^[0-9]+$\\|^$\\|^fn:" label))
  273. (setq label (concat "fn:" label)))
  274. label)
  275. (defun org-footnote-all-labels ()
  276. "Return list with all defined foot labels used in the buffer."
  277. (let (rtn l ref)
  278. (save-excursion
  279. (save-restriction
  280. (widen)
  281. ;; Find all labels found in definitions.
  282. (goto-char (point-min))
  283. (while (re-search-forward org-footnote-definition-re nil t)
  284. (setq l (org-match-string-no-properties 2))
  285. (and l (add-to-list 'rtn l)))
  286. ;; Find all labels found in references.
  287. (goto-char (point-min))
  288. (while (and (setq ref (org-footnote-get-next-reference))
  289. (goto-char (nth 2 ref)))
  290. (and (car ref) (add-to-list 'rtn (car ref))))))
  291. rtn))
  292. (defun org-footnote-unique-label (&optional current)
  293. "Return a new unique footnote label.
  294. The returns the firsts fn:N labels that is currently not used."
  295. (unless current (setq current (org-footnote-all-labels)))
  296. (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
  297. (cnt 1))
  298. (while (member (format fmt cnt) current)
  299. (incf cnt))
  300. (format fmt cnt)))
  301. (defvar org-footnote-label-history nil
  302. "History of footnote labels entered in current buffer.")
  303. (make-variable-buffer-local 'org-footnote-label-history)
  304. (defun org-footnote-new ()
  305. "Insert a new footnote.
  306. This command prompts for a label. If this is a label referencing an
  307. existing label, only insert the label. If the footnote label is empty
  308. or new, let the user edit the definition of the footnote."
  309. (interactive)
  310. (let* ((labels (and (not (equal org-footnote-auto-label 'random))
  311. (org-footnote-all-labels)))
  312. (propose (org-footnote-unique-label labels))
  313. (label
  314. (cond
  315. ((member org-footnote-auto-label '(t plain))
  316. propose)
  317. ((equal org-footnote-auto-label 'random)
  318. (require 'org-id)
  319. (substring (org-id-uuid) 0 8))
  320. (t
  321. (completing-read
  322. "Label (leave empty for anonymous): "
  323. (mapcar 'list labels) nil nil
  324. (if (eq org-footnote-auto-label 'confirm) propose nil)
  325. 'org-footnote-label-history)))))
  326. (setq label (org-footnote-normalize-label label))
  327. (cond
  328. ((equal label "")
  329. (insert "[fn:: ]")
  330. (backward-char 1))
  331. ((member label labels)
  332. (insert "[" label "]")
  333. (message "New reference to existing note"))
  334. (org-footnote-define-inline
  335. (insert "[" label ": ]")
  336. (backward-char 1)
  337. (org-footnote-auto-adjust-maybe))
  338. (t
  339. (insert "[" label "]")
  340. (org-footnote-create-definition label)
  341. (org-footnote-auto-adjust-maybe)))))
  342. (defun org-footnote-create-definition (label)
  343. "Start the definition of a footnote with label LABEL."
  344. (interactive "sLabel: ")
  345. (setq label (org-footnote-normalize-label label))
  346. (let (re)
  347. (cond
  348. ((org-mode-p)
  349. (if (not org-footnote-section)
  350. ;; No section, put footnote into the current outline node
  351. nil
  352. ;; Try to find or make the special node
  353. (goto-char (point-min))
  354. (setq re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$"))
  355. (unless (or (re-search-forward re nil t)
  356. (and (progn (widen) t)
  357. (re-search-forward re nil t)))
  358. (goto-char (point-max))
  359. (insert "\n\n* " org-footnote-section "\n")))
  360. ;; Now go to the end of this entry and insert there.
  361. (org-footnote-goto-local-insertion-point)
  362. (org-show-context 'link-search))
  363. (t
  364. (setq re (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$"))
  365. (unless (re-search-forward re nil t)
  366. (let ((max (if (and (derived-mode-p 'message-mode)
  367. (re-search-forward message-signature-separator nil t))
  368. (progn (beginning-of-line) (point))
  369. (goto-char (point-max)))))
  370. (skip-chars-backward " \t\r\n")
  371. (delete-region (point) max)
  372. (insert "\n\n")
  373. (insert org-footnote-tag-for-non-org-mode-files "\n")))
  374. ;; Skip existing footnotes
  375. (while (re-search-forward "^[[:space:]]*\\[[^]]+\\] " nil t)
  376. (forward-line))))
  377. (insert "\n[" label "] \n")
  378. (goto-char (1- (point)))
  379. (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
  380. ;;;###autoload
  381. (defun org-footnote-action (&optional special)
  382. "Do the right thing for footnotes.
  383. When at a footnote reference, jump to the definition. When at a definition,
  384. jump to the references. When neither at definition or reference,
  385. create a new footnote, interactively.
  386. With prefix arg SPECIAL, offer additional commands in a menu."
  387. (interactive "P")
  388. (let (tmp c)
  389. (cond
  390. (special
  391. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
  392. (setq c (read-char-exclusive))
  393. (cond
  394. ((equal c ?s)
  395. (org-footnote-normalize 'sort))
  396. ((equal c ?r)
  397. (org-footnote-renumber-fn:N))
  398. ((equal c ?S)
  399. (org-footnote-renumber-fn:N)
  400. (org-footnote-normalize 'sort))
  401. ((equal c ?n)
  402. (org-footnote-normalize))
  403. ((equal c ?d)
  404. (org-footnote-delete))
  405. (t (error "No such footnote command %c" c))))
  406. ((setq tmp (org-footnote-at-reference-p))
  407. (if (car tmp)
  408. (org-footnote-goto-definition (car tmp))
  409. (goto-char (nth 1 tmp))
  410. (forward-char 5)))
  411. ((setq tmp (org-footnote-at-definition-p))
  412. (org-footnote-goto-previous-reference (car tmp)))
  413. (t (org-footnote-new)))))
  414. (defvar org-footnote-insert-pos-for-preprocessor 'point-max
  415. "See `org-footnote-normalize'.")
  416. ;;;###autoload
  417. (defun org-footnote-normalize (&optional sort-only pre-process-p)
  418. "Collect the footnotes in various formats and normalize them.
  419. This finds the different sorts of footnotes allowed in Org, and
  420. normalizes them to the usual [N] format that is understood by the
  421. Org-mode exporters.
  422. When SORT-ONLY is set, only sort the footnote definitions into the
  423. referenced sequence.
  424. When PRE-PROCESS-P is non-nil, the default action, is to insert
  425. normalized footnotes towards the end of the pre-processing
  426. buffer. Some exporters like docbook, odt etc expect that footnote
  427. definitions be available before any references to them. Such
  428. exporters can let bind `org-footnote-insert-pos-for-preprocessor'
  429. to symbol 'point-min to achieve the desired behaviour.
  430. Additional note on `org-footnote-insert-pos-for-preprocessor':
  431. 1. This variable has not effect when FOR-PREPROCESSOR is nil.
  432. 2. This variable (potentially) obviates the need for extra scan
  433. of pre-processor buffer as witnessed in
  434. `org-export-docbook-get-footnotes'."
  435. ;; This is based on Paul's function, but rewritten.
  436. ;;
  437. ;; Re-create `org-with-limited-levels', but not limited to Org
  438. ;; buffers.
  439. (let* ((limit-level
  440. (and (boundp 'org-inlinetask-min-level)
  441. org-inlinetask-min-level
  442. (1- org-inlinetask-min-level)))
  443. (nstars (and limit-level
  444. (if org-odd-levels-only
  445. (and limit-level (1- (* limit-level 2)))
  446. limit-level)))
  447. (outline-regexp
  448. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
  449. ;; Determine the highest marker used so far.
  450. (count (if (and pre-process-p org-export-footnotes-markers)
  451. (apply 'max (mapcar 'car org-export-footnotes-markers))
  452. 0))
  453. ref-table ins-point ref)
  454. (save-excursion
  455. ;; 1. Find every footnote reference, extract the definition, and
  456. ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
  457. ;; normalize references.
  458. (goto-char (point-min))
  459. (while (setq ref (org-footnote-get-next-reference))
  460. (let* ((lbl (car ref))
  461. ;; When footnote isn't anonymous, check if it's label
  462. ;; (REF) is already stored in REF-TABLE. In that case,
  463. ;; extract number used to identify it (MARKER). If
  464. ;; footnote is unknown, increment the global counter
  465. ;; (COUNT) to create an unused identifier.
  466. (a (and lbl (assoc lbl ref-table)))
  467. (marker (or (nth 1 a) (incf count)))
  468. ;; Is the reference inline or pointing to an inline
  469. ;; footnote?
  470. (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
  471. ;; Replace footnote reference with [MARKER]. Maybe fill
  472. ;; paragraph once done. If SORT-ONLY is non-nil, only move
  473. ;; to the end of reference found to avoid matching it twice.
  474. (if sort-only
  475. (goto-char (nth 2 ref))
  476. (delete-region (nth 1 ref) (nth 2 ref))
  477. (goto-char (nth 1 ref))
  478. (insert (format "[%d]" marker))
  479. (and inlinep
  480. org-footnote-fill-after-inline-note-extraction
  481. (org-fill-paragraph)))
  482. ;; Add label (REF), identifier (MARKER) and definition (DEF)
  483. ;; to REF-TABLE if data was unknown.
  484. (unless a
  485. (let ((def (or (nth 3 ref) ; inline
  486. (and pre-process-p
  487. (cdr (assoc lbl org-export-footnotes-data)))
  488. (nth 3 (org-footnote-get-definition lbl)))))
  489. (push (list lbl marker def inlinep) ref-table)))
  490. ;; Remove definition of non-inlined footnotes.
  491. (unless inlinep (org-footnote-delete-definitions lbl))))
  492. ;; 2. Find and remove the footnote section, if any. If we are
  493. ;; exporting, insert it again at end of buffer. In a non
  494. ;; org-mode file, insert instead
  495. ;; `org-footnote-tag-for-non-org-mode-files'.
  496. (goto-char (point-min))
  497. (cond
  498. ((org-mode-p)
  499. (if (and org-footnote-section
  500. (re-search-forward
  501. (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
  502. "[ \t]*$")
  503. nil t))
  504. (if pre-process-p
  505. (replace-match "")
  506. (org-back-to-heading t)
  507. (forward-line 1)
  508. (setq ins-point (point))
  509. (delete-region (point) (org-end-of-subtree t)))
  510. (goto-char (point-max))
  511. (unless pre-process-p
  512. (when org-footnote-section
  513. (or (bolp) (insert "\n"))
  514. (insert "* " org-footnote-section "\n")
  515. (setq ins-point (point))))))
  516. (t
  517. (if (re-search-forward
  518. (concat "^"
  519. (regexp-quote org-footnote-tag-for-non-org-mode-files)
  520. "[ \t]*$")
  521. nil t)
  522. (replace-match ""))
  523. (goto-char (point-max))
  524. (skip-chars-backward " \t\n\r")
  525. (delete-region (point) (point-max))
  526. (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n")
  527. (setq ins-point (point))))
  528. ;; 3. Clean-up REF-TABLE.
  529. (setq ref-table
  530. (delq nil
  531. (mapcar
  532. (lambda (x)
  533. (cond
  534. ;; When only sorting, ignore inline footnotes.
  535. ((and sort-only (nth 3 x)) nil)
  536. ;; No definition available: provide one.
  537. ((not (nth 2 x))
  538. (append (butlast x 2)
  539. (list (format "DEFINITION NOT FOUND: %s" (car x))
  540. (nth 3 x))))
  541. (t x)))
  542. ref-table)))
  543. (setq ref-table (nreverse ref-table))
  544. ;; 4. Insert the footnotes again in the buffer, at INS-POINT.
  545. (goto-char (or ins-point (point-max)))
  546. (cond
  547. ((not ref-table)) ; no footnote: exit
  548. ;; Cases when footnotes should be inserted together in one place.
  549. ((or (not (org-mode-p))
  550. org-footnote-section
  551. (not sort-only))
  552. (insert "\n"
  553. (mapconcat (lambda (x) (format "[%s] %s"
  554. (nth (if sort-only 0 1) x) (nth 2 x)))
  555. ref-table "\n\n")
  556. "\n\n")
  557. ;; When exporting, add newly insert markers along with their
  558. ;; associated definition to `org-export-footnotes-markers'.
  559. (when pre-process-p
  560. (setq org-export-footnotes-markers
  561. (append (mapcar (lambda (ref) (cons (nth 1 ref) (nth 2 ref)))
  562. ref-table)
  563. org-export-footnotes-markers))))
  564. ;; Else, insert each definition at the end of the section
  565. ;; containing their first reference. Happens only in Org
  566. ;; files with no special footnote section, and only when
  567. ;; doing sorting.
  568. (t (mapc 'org-insert-footnote-reference-near-definition
  569. ref-table))))))
  570. (defun org-insert-footnote-reference-near-definition (entry)
  571. "Find first reference of footnote ENTRY and insert the definition there.
  572. ENTRY is (fn-label num-mark definition)."
  573. (when (car entry)
  574. (goto-char (point-min))
  575. (let ((ref (org-footnote-get-next-reference (car entry))))
  576. (when ref
  577. (goto-char (nth 2 ref))
  578. (org-footnote-goto-local-insertion-point)
  579. (insert (format "\n[%s] %s\n" (car entry) (nth 2 entry)))))))
  580. (defun org-footnote-goto-local-insertion-point ()
  581. "Find insertion point for footnote, just before next outline heading."
  582. (org-with-limited-levels (outline-next-heading))
  583. (or (bolp) (newline))
  584. (beginning-of-line 0)
  585. (while (and (not (bobp)) (= (char-after) ?#))
  586. (beginning-of-line 0))
  587. (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
  588. (end-of-line 1)
  589. (skip-chars-backward "\n\r\t ")
  590. (forward-line))
  591. (defun org-footnote-delete-references (label)
  592. "Delete every reference to footnote LABEL.
  593. Return the number of footnotes removed."
  594. (save-excursion
  595. (goto-char (point-min))
  596. (let (ref (nref 0))
  597. (while (setq ref (org-footnote-get-next-reference label))
  598. (goto-char (nth 1 ref))
  599. (delete-region (nth 1 ref) (nth 2 ref))
  600. (incf nref))
  601. nref)))
  602. (defun org-footnote-delete-definitions (label)
  603. "Delete every definition of the footnote LABEL.
  604. Return the number of footnotes removed."
  605. (save-excursion
  606. (goto-char (point-min))
  607. (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
  608. (ndef 0))
  609. (while (re-search-forward def-re nil t)
  610. (let ((full-def (org-footnote-at-definition-p)))
  611. (delete-region (nth 1 full-def) (nth 2 full-def)))
  612. (incf ndef))
  613. ndef)))
  614. (defun org-footnote-delete (&optional label)
  615. "Delete the footnote at point.
  616. This will remove the definition (even multiple definitions if they exist)
  617. and all references of a footnote label.
  618. If LABEL is non-nil, delete that footnote instead."
  619. (catch 'done
  620. (let* ((nref 0) (ndef 0) x
  621. ;; 1. Determine LABEL of footnote at point.
  622. (label (cond
  623. ;; LABEL is provided as argument.
  624. (label)
  625. ;; Footnote reference at point. If the footnote is
  626. ;; anonymous, delete it and exit instead.
  627. ((setq x (org-footnote-at-reference-p))
  628. (or (car x)
  629. (progn
  630. (delete-region (nth 1 x) (nth 2 x))
  631. (message "Anonymous footnote removed")
  632. (throw 'done t))))
  633. ;; Footnote definition at point.
  634. ((setq x (org-footnote-at-definition-p))
  635. (car x))
  636. (t (error "Don't know which footnote to remove")))))
  637. ;; 2. Now that LABEL is non-nil, find every reference and every
  638. ;; definition, and delete them.
  639. (setq nref (org-footnote-delete-references label)
  640. ndef (org-footnote-delete-definitions label))
  641. ;; 3. Verify consistency of footnotes and notify user.
  642. (org-footnote-auto-adjust-maybe)
  643. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  644. ndef nref label))))
  645. (defun org-footnote-renumber-fn:N ()
  646. "Renumber the simple footnotes like fn:17 into a sequence in the document."
  647. (interactive)
  648. (let (map i (n 0))
  649. (save-excursion
  650. (save-restriction
  651. (widen)
  652. (goto-char (point-min))
  653. (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
  654. (setq i (string-to-number (match-string 1)))
  655. (when (and (string-match "\\S-" (buffer-substring
  656. (point-at-bol) (match-beginning 0)))
  657. (not (assq i map)))
  658. (push (cons i (number-to-string (incf n))) map)))
  659. (goto-char (point-min))
  660. (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
  661. (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
  662. (defun org-footnote-auto-adjust-maybe ()
  663. "Renumber and/or sort footnotes according to user settings."
  664. (when (memq org-footnote-auto-adjust '(t renumber))
  665. (org-footnote-renumber-fn:N))
  666. (when (memq org-footnote-auto-adjust '(t sort))
  667. (let ((label (car (org-footnote-at-definition-p))))
  668. (org-footnote-normalize 'sort)
  669. (when label
  670. (goto-char (point-min))
  671. (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
  672. nil t)
  673. (progn (insert " ")
  674. (just-one-space)))))))
  675. (provide 'org-footnote)
  676. ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
  677. ;;; org-footnote.el ends here