- (format "[%s] %s" (nth (if sort-only 0 1) x)
- (org-trim (nth 2 x))))
- ref-table "\n\n"))
- (if ref-table (insert "\n" def "\n\n")))
- ;; Insert each footnote near the first reference
- ;; Happens only in Org files with no special footnote section,
- ;; and only when doing sorting
- (mapc 'org-insert-footnote-reference-near-definition
- ref-table)))))
-
-(defun org-insert-footnote-reference-near-definition (entry)
- "Find first reference of footnote ENTRY and insert the definition there.
-ENTRY is (fn-label num-mark definition)."
- (when (car entry)
- (goto-char (point-min))
- (when (re-search-forward (format ".\\[%s[]:]" (regexp-quote (car entry)))
- nil t)
- (org-footnote-goto-local-insertion-point)
- (insert (format "\n\n[%s] %s" (car entry) (nth 2 entry))))))
+ (cond
+ ;; When only sorting, ignore inline footnotes.
+ ;; Also clear position marker.
+ ((and sort-only (nth 3 x))
+ (set-marker (nth 4 x) nil) nil)
+ ;; No definition available: provide one.
+ ((not (nth 2 x))
+ (append
+ (list (car x) (nth 1 x)
+ (format "DEFINITION NOT FOUND: %s" (car x)))
+ (nthcdr 3 x)))
+ (t x)))
+ ref-table)))
+ (setq ref-table (nreverse ref-table))
+ ;; 4. Remove left-over definitions in the buffer.
+ (mapc (lambda (x)
+ (unless (nth 3 x) (org-footnote-delete-definitions (car x))))
+ ref-table)
+ ;; 5. Insert the footnotes again in the buffer, at the
+ ;; appropriate spot.
+ (goto-char ins-point)
+ (cond
+ ;; No footnote: exit.
+ ((not ref-table))
+ ;; Cases when footnotes should be inserted in one place.
+ ((or (not (derived-mode-p 'org-mode)) org-footnote-section)
+ ;; Insert again the section title, if any. Ensure that title,
+ ;; or the subsequent footnotes, will be separated by a blank
+ ;; lines from the rest of the document. In an Org buffer,
+ ;; separate section with a blank line, unless explicitly
+ ;; stated in `org-blank-before-new-entry'.
+ (if (not (derived-mode-p 'org-mode))
+ (progn (skip-chars-backward " \t\n\r")
+ (delete-region (point) ins-point)
+ (unless (bolp) (newline))
+ (when org-footnote-tag-for-non-org-mode-files
+ (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
+ (when (and (cdr (assq 'heading org-blank-before-new-entry))
+ (zerop (save-excursion (org-back-over-empty-lines))))
+ (insert "\n"))
+ (insert "* " org-footnote-section "\n"))
+ (set-marker ins-point nil)
+ ;; Insert the footnotes, separated by a blank line.
+ (insert
+ (mapconcat
+ (lambda (x)
+ ;; Clean markers.
+ (set-marker (nth 4 x) nil)
+ (format "\n[%s] %s" (nth (if sort-only 0 1) x) (nth 2 x)))
+ ref-table "\n"))
+ (unless (eobp) (insert "\n\n")))
+ ;; Each footnote definition has to be inserted at the end of
+ ;; the section where its first reference belongs.
+ (t
+ (mapc
+ (lambda (x)
+ (let ((pos (nth 4 x)))
+ (goto-char pos)
+ ;; Clean marker.
+ (set-marker pos nil))
+ (org-footnote-goto-local-insertion-point)
+ (insert (format "\n[%s] %s\n"
+ (if sort-only (car x) (nth 1 x))
+ (nth 2 x))))
+ ref-table))))))