emacs-orgmode@gnu.org archives
 help / color / mirror / code / Atom feed
blob 38c0957dba31b98e332246ecd4be9ad1a84c1bed 16665 bytes (raw)
name: contrib/lisp/ox-bibtex.el 	 # note: path name is non-authoritative(*)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
 
;;; ox-bibtex.el --- Export bibtex fragments

;; Copyright (C) 2009-2014 Taru Karttunen

;; Author: Taru Karttunen <taruti@taruti.net>
;;      Nicolas Goaziou <n dot goaziou at gmail dot com>
;; This file is not currently part of GNU Emacs.

;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation; either version 2, or (at
;; your option) any later version.

;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program ; see the file COPYING.  If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:
;;
;; This is an utility to handle BibTeX export to LaTeX, html and ascii
;; exports.  For HTML and ascii it uses the bibtex2html software from:
;;
;;   http://www.lri.fr/~filliatr/bibtex2html/
;;
;; For ascii it uses the pandoc software from:
;;
;;   http://johnmacfarlane.net/pandoc/
;;
;; It also introduces "cite" syntax for Org links.
;;
;; The usage is as follows:
;;
;;   #+BIBLIOGRAPHY: bibfilename stylename optional-options
;;
;; e.g. given foo.bib and using style plain:
;;
;;   #+BIBLIOGRAPHY: foo plain option:-d
;;
;; "stylename" can also be "nil", in which case no style will be used.
;;
;; Full filepaths are also possible:
;;
;;   #+BIBLIOGRAPHY: /home/user/Literature/foo.bib plain option:-d
;;
;; Optional options are of the form:
;;
;;   option:-foobar pass '-foobar' to bibtex2html
;;
;; e.g.,
;;
;;   option:-d    sort by date
;;   option:-a    sort as BibTeX (usually by author) *default*
;;   option:-u    unsorted i.e. same order as in .bib file
;;   option:-r    reverse the sort
;;
;; See the bibtex2html man page for more.  Multiple options can be
;; combined like:
;;
;;   option:-d option:-r
;;
;; Limiting to only the entries cited in the document:
;;
;;   limit:t
;;
;; For LaTeX export this simply inserts the lines
;;
;;   \bibliographystyle{plain}
;;   \bibliography{foo}
;;
;; into the TeX file when exporting.
;;
;; For HTML export it:
;; 1) converts all \cite{foo} and [[cite:foo]] to links to the
;;    bibliography,
;; 2) creates a foo.html and foo_bib.html,
;; 3) includes the contents of foo.html in the exported HTML file.
;;
;; For ascii export it:
;; 1) converts all \cite{foo} and [[cite:foo]] to links to the
;;    bibliography,
;; 2) creates a foo.txt and foo_bib.html,
;; 3) includes the contents of foo.txt in the exported ascii file.
;;
;; For LaTeX export it:
;; 1) converts all [[cite:foo]] to \cite{foo}.

;; Initialization

(require 'cl-lib)

;;; Internal Functions

(defun org-bibtex-get-file (keyword)
  "Return bibliography file as a string.
KEYWORD is a \"BIBLIOGRAPHY\" keyword. If no file is found,
return nil instead."
  (let ((value (org-element-property :value keyword)))
    (and value
         (string-match "\\(\\S-+\\)[ \t]+\\(\\S-+\\)\\(.*\\)" value)
         (match-string 1 value))))

(defun org-bibtex-get-style (keyword)
  "Return bibliography style as a string.
KEYWORD is a \"BIBLIOGRAPHY\" keyword. If no style is found,
return nil instead."
  (let ((value (org-element-property :value keyword)))
    (and value
         (string-match "\\(\\S-+\\)[ \t]+\\(\\S-+\\)\\(.*\\)" value)
         (match-string 2 value))))

(defun org-bibtex-get-arguments (keyword)
  "Return \"bibtex2html\" arguments specified by the user.
KEYWORD is a \"BIBLIOGRAPHY\" keyword. Return value is a plist
containing `:options' and `:limit' properties.  The former
contains a list of strings to be passed as options to
\"bibtex2html\" process.  The latter contains a boolean."
  (let ((value (org-element-property :value keyword)))
    (and value
         (string-match "\\(\\S-+\\)[ \t]+\\(\\S-+\\)\\(.*\\)" value)
         (let (options limit)
           (dolist (arg (org-split-string (match-string 3 value))
                        ;; Return value.
                        (list :options (nreverse options) :limit limit))
             (let* ((s (split-string arg ":"))
                    (key (car s))
                    (value (nth 1 s)))
               (cond ((equal "limit" key)
                      (setq limit (not (equal "nil" value))))
                     ((equal "option" key) (push value options)))))))))

(defun org-bibtex-citation-p (object)
  "Non-nil when OBJECT is a citation."
  (cl-case (org-element-type object)
    (link (equal (org-element-property :type object) "cite"))
    (latex-fragment
     (string-match "\\`\\\\cite{" (org-element-property :value object)))))

(defun org-bibtex-get-citation-key (citation)
  "Return key for a given citation, as a string.
CITATION is a `latex-fragment' or `link' type object satisfying
to `org-bibtex-citation-p' predicate."
  (if (eq (org-element-type citation) 'link)
      (org-element-property :path citation)
    (let ((value (org-element-property :value citation)))
      (and (string-match "\\`\\\\cite{" value)
	   (substring value (match-end 0) -1)))))

\f
;;; Follow cite: links

(defun org-bibtex-file nil "Org-mode file of bibtex entries.")

(defun org-bibtex-goto-citation (&optional citation)
  "Visit a citation given its ID."
  (interactive)
  (let ((citation (or citation (completing-read "Citation: " (obe-citations)))))
    (find-file (or org-bibtex-file
		   (error "`org-bibtex-file' has not been configured")))
    (goto-char (point-min))
    (when (re-search-forward (format "  :CUSTOM_ID: %s" citation) nil t)
      (outline-previous-visible-heading 1)
      t)))

(let ((jump-fn (car (cl-remove-if-not #'fboundp '(ebib org-bibtex-goto-citation)))))
  (org-add-link-type "cite" jump-fn))


\f
;;; Filters

(defun org-bibtex-process-bib-files (tree backend info)
  "Send each bibliography in parse tree to \"bibtex2html\" process.
Return new parse tree."
  (when (org-export-derived-backend-p backend 'ascii 'html)
    ;; Initialize dynamically scoped variables.  The first one
    ;; contain an alist between keyword objects and their HTML
    ;; translation.  The second one will contain an alist between
    ;; citation keys and names in the output (according to style).
    (setq org-bibtex-html-entries-alist nil
	  org-bibtex-html-keywords-alist nil)
    (org-element-map tree 'keyword
      (lambda (keyword)
	(when (equal (org-element-property :key keyword) "BIBLIOGRAPHY")
	  (let* ((arguments (org-bibtex-get-arguments keyword))
		 (file (org-bibtex-get-file keyword))
		 temp-file
		 out-file
		 (multiple-bib-files (split-string file ","))
		 (multiple-bib-p (< 1 (length multiple-bib-files)))
		 multiple-bib-file)
	    (when multiple-bib-p
	      (setq multiple-bib-file
		    (concat
		     (file-name-sans-extension
		      (file-name-nondirectory
		       (buffer-file-name))) "-combined.bib"))
	      (setq file multiple-bib-file))
	    ;; Test if filename is given with .bib-extension and strip
    	    ;; it off. Filenames with another extensions will be
	    ;; untouched and will finally rise an error in bibtex2html.
	    (setq file (if (equal (file-name-extension file) "bib")
			   (file-name-sans-extension file) file))
	    ;; Output files of bibtex2html will be put into current
	    ;; working directory so define a variable for this.
	    (setq out-file (file-name-sans-extension
			    (file-name-nondirectory file)))
	    ;; limit is set: collect citations throughout the document
	    ;; in TEMP-FILE and pass it to "bibtex2html" as "-citefile"
	    ;; argument.
	    (when (plist-get arguments :limit)
	      (let ((citations
		     (org-element-map tree '(latex-fragment link)
		       (lambda (object)
			 (and (org-bibtex-citation-p object)
			      (org-bibtex-get-citation-key object))))))
		(with-temp-file (setq temp-file (make-temp-file "ox-bibtex"))
		  (insert (mapconcat 'identity citations "\n")))
		(setq arguments
		      (plist-put arguments
				 :options
				 (append (plist-get arguments :options)
					 (list "-citefile" temp-file))))))
	    ;; Call "bibtex2html" on specified file.
	    (let* ((bibtex2html-cmd '("bibtex2html" nil nil nil))
		   (bibtex2html-args-default '("-a" "-nodoc" "-noheader"
					       "-nofooter"))
		   (bibtex2html-style
		    (let ((style
			   (org-not-nil
			    (org-bibtex-get-style keyword))))
		      (and style (list "--style" style))))
		   (bibtex2html-opts (plist-get arguments :options)))
	      (message "mf=%s file=%s" multiple-bib-file multiple-bib-files)
	      (if multiple-bib-p
		  (with-temp-buffer
		    multiple-bib-file
		    (dolist (bib multiple-bib-files)
		      (insert-file-contents
		       (if (equal (file-name-extension bib) "bib")
			   bib
			 (concat bib ".bib"))))
		    (unless
			(eq 0
			    (apply
			     'call-process-region
			     (append `(,(point-min) ,(point-max))
				     bibtex2html-cmd
				     bibtex2html-args-default
				     bibtex2html-style
				     bibtex2html-opts
				     `("-o" ,file)))))
		      (error "Executing bibtex2html failed"))
		(unless
		    (eq 0
			(apply
			 'call-process
			 (append bibtex2html-cmd
				 bibtex2html-args-default
				 bibtex2html-style
				 bibtex2html-opts
				 (list (concat file ".bib")))))
		  (error "Executing bibtex2html failed"))))
	    (and temp-file (delete-file temp-file))
	    ;; Open produced HTML file, and collect Bibtex key names
	    (with-temp-buffer
	      (insert-file-contents (concat out-file ".html"))
	      ;; Update `org-bibtex-html-entries-alist'.
	      (goto-char (point-min))
	      (while (re-search-forward
		      "a name=\"\\([-_a-zA-Z0-9:]+\\)\">\\(\\w+\\)" nil t)
		(push (cons (match-string 1) (match-string 2))
		      org-bibtex-html-entries-alist)))
	    ;; Open produced HTML file, wrap references within a block and
	    ;; return it.
	    (with-temp-buffer
	      (cond
	       ((org-export-derived-backend-p backend 'html)
		(insert (format "<div id=\"bibliography\">\n<h2>%s</h2>\n"
				(org-export-translate "References" :html info)))
		(insert-file-contents (concat out-file ".html"))
		(goto-char (point-max))
		(insert "\n</div>"))
	       ((org-export-derived-backend-p backend 'ascii)
		;; convert HTML references to text w/pandoc
		(unless (eq 0 (call-process "pandoc" nil nil nil
					    (concat out-file ".html")
					    "-o"
					    (concat out-file ".txt")))
		  (error "Executing pandoc failed"))
		(insert
		 (format
		  "%s\n==========\n\n"
		  (org-export-translate
		   "References"
		   (intern (format ":%s" (plist-get info :ascii-charset)))
		   info)))
		(insert-file-contents (concat out-file ".txt"))
		(goto-char (point-min))
		(while (re-search-forward
			"\\\\[bib\\][^ ]+ \\(\\]\\||[\n\r]\\)" nil t)
		  (replace-match ""))
		(goto-char (point-min))
		(while (re-search-forward "\\\\]\\\\]\\| |\\)" nil t)
		  (replace-match ""))
		(goto-char (point-min))
		(while (re-search-forward "[\n\r]\\([\n\r][\n\r]\\)" nil t)
		  (replace-match "\\1"))))
	      ;; Update `org-bibtex-html-keywords-alist'.
	      (push (cons keyword (buffer-string))
		    org-bibtex-html-keywords-alist)))))))
  ;; Return parse tree unchanged.
  tree)

(defun org-bibtex-merge-contiguous-citations (tree backend info)
  "Merge all contiguous citation in parse tree.
As a side effect, this filter will also turn all \"cite\" links
into \"\\cite{...}\" LaTeX fragments and will extract options.
Cite options are placed into square brackets at the beginning of
the \"\\cite\" command for the LaTeX backend, and are removed for
the HTML and ASCII backends."
  (when (org-export-derived-backend-p backend 'html 'latex 'ascii)
    (org-element-map tree '(link latex-fragment)
      (lambda (object)
	(when (org-bibtex-citation-p object)
	  (let ((new-citation (list 'latex-fragment
				    (list :value ""
					  :post-blank (org-element-property
						       :post-blank object))))
		option)
	    ;; Insert NEW-CITATION right before OBJECT.
	    (org-element-insert-before new-citation object)
	    ;; Remove all subsequent contiguous citations from parse
	    ;; tree, keeping only their citation key.
	    (let ((keys (list (org-bibtex-get-citation-key object)))
		  next)
	      (while (and (setq next (org-export-get-next-element object info))
			  (or (and (stringp next)
				   (not (string-match-p "\\S-" next)))
			      (org-bibtex-citation-p next)))
		(unless (stringp next)
		  (push (org-bibtex-get-citation-key next) keys))
		(org-element-extract-element object)
		(setq object next))
	      ;; Find any options in keys, e.g., "(Chapter 2)key" has
	      ;; the option "Chapter 2".
	      (setq keys
		    (mapcar
		     (lambda (k)
		       (if (string-match "^(\\([^)]\+\\))\\(.*\\)" k)
			   (progn
			     (when (org-export-derived-backend-p backend 'latex)
			       (setq option (format "[%s]" (match-string 1 k))))
			     (match-string 2 k))
			 k))
		     keys))
	      (org-element-extract-element object)
	      ;; Eventually merge all keys within NEW-CITATION.  Also
	      ;; ensure NEW-CITATION has the same :post-blank property
	      ;; as the last citation removed.
	      (org-element-put-property
	       new-citation
	       :post-blank (org-element-property :post-blank object))
	      (org-element-put-property
	       new-citation
	       :value (format "\\cite%s{%s}"
			      (or option "")
			      (mapconcat 'identity (nreverse keys) ",")))))))))
  tree)

(eval-after-load 'ox
  '(progn (add-to-list 'org-export-filter-parse-tree-functions
		       'org-bibtex-process-bib-files)
	  (add-to-list 'org-export-filter-parse-tree-functions
		       'org-bibtex-merge-contiguous-citations)))


\f
;;; LaTeX Part

(defadvice org-latex-keyword (around bibtex-keyword)
  "Translate \"BIBLIOGRAPHY\" keywords into LaTeX syntax.
Fallback to `latex' back-end for other keywords."
  (let ((keyword (ad-get-arg 0)))
    (if (not (equal (org-element-property :key keyword) "BIBLIOGRAPHY"))
        ad-do-it
      (let ((file (org-bibtex-get-file keyword))
            (style (org-not-nil (org-bibtex-get-style keyword))))
        (setq ad-return-value
              (when file
                (concat (and style (format "\\bibliographystyle{%s}\n" style))
                        (format "\\bibliography{%s}" file))))))))

(ad-activate 'org-latex-keyword)


\f
;;; HTML Part

(defvar org-bibtex-html-entries-alist nil)  ; Dynamically scoped.
(defvar org-bibtex-html-keywords-alist nil) ; Dynamically scoped.


;;;; Advices

(defadvice org-html-keyword (around bibtex-keyword)
  "Translate \"BIBLIOGRAPHY\" keywords into HTML syntax.
Fallback to `html' back-end for other keywords."
  (let ((keyword (ad-get-arg 0)))
    (if (not (equal (org-element-property :key keyword) "BIBLIOGRAPHY"))
        ad-do-it
      (setq ad-return-value
            (cdr (assq keyword org-bibtex-html-keywords-alist))))))

(defadvice org-html-latex-fragment (around bibtex-citation)
  "Translate \"\\cite\" LaTeX fragments into HTML syntax.
Fallback to `html' back-end for other keywords."
  (let ((fragment (ad-get-arg 0)))
    (if (not (org-bibtex-citation-p fragment)) ad-do-it
      (setq ad-return-value
            (format "[%s]"
		    (mapconcat
		     (lambda (key)
		       (format "<a href=\"#%s\">%s</a>"
			       key
			       (or (cdr (assoc key org-bibtex-html-entries-alist))
				   key)))
		     (org-split-string
		      (org-bibtex-get-citation-key fragment) ",") ","))))))

(ad-activate 'org-html-keyword)
(ad-activate 'org-html-latex-fragment)

\f
;;; Ascii Part
(defadvice org-ascii-keyword (around bibtex-keyword)
  "Translate \"BIBLIOGRAPHY\" keywords into ascii syntax.
Fallback to `ascii' back-end for other keywords."
  (let ((keyword (ad-get-arg 0)))
    (if (not (equal (org-element-property :key keyword) "BIBLIOGRAPHY"))
        ad-do-it
      (setq ad-return-value
            (cdr (assq keyword org-bibtex-html-keywords-alist))))))

(defadvice org-ascii-latex-fragment (around bibtex-citation)
  "Translate \"\\cite\" LaTeX fragments into ascii syntax.
Fallback to `ascii' back-end for other keywords."
  (let ((fragment (ad-get-arg 0)))
    (if (not (org-bibtex-citation-p fragment)) ad-do-it
      (setq ad-return-value
            (format "[%s]"
		    (mapconcat
		     (lambda (key)
		       (or (cdr (assoc key org-bibtex-html-entries-alist))
			   key))
		     (org-split-string
		      (org-bibtex-get-citation-key fragment) ",") ","))))))

(ad-activate 'org-ascii-keyword)
(ad-activate 'org-ascii-latex-fragment)

(provide 'ox-bibtex)

;;; ox-bibtex.el ends here

debug log:

solving 38c0957 ...
found 38c0957 in https://yhetil.org/orgmode/87wpilbucl.fsf@dell-desktop.WORKGROUP/
found b46cb76 in https://yhetil.org/orgmode/871t0wl6by.fsf@dell-desktop.WORKGROUP/ ||
	https://yhetil.org/orgmode/87h978j8i2.fsf@dell-desktop.WORKGROUP/
found 56dec38 in https://git.savannah.gnu.org/cgit/emacs/org-mode.git
preparing index
index prepared:
100644 56dec38375809896bbd8eb056b2dea8c1c3fca42	contrib/lisp/ox-bibtex.el

applying [1/2] https://yhetil.org/orgmode/871t0wl6by.fsf@dell-desktop.WORKGROUP/
diff --git a/contrib/lisp/ox-bibtex.el b/contrib/lisp/ox-bibtex.el
index 56dec38..b46cb76 100644

Checking patch contrib/lisp/ox-bibtex.el...
Applied patch contrib/lisp/ox-bibtex.el cleanly.

skipping https://yhetil.org/orgmode/87h978j8i2.fsf@dell-desktop.WORKGROUP/ for b46cb76
index at:
100644 b46cb76625c036396143be2ddce474231daa13c7	contrib/lisp/ox-bibtex.el

applying [2/2] https://yhetil.org/orgmode/87wpilbucl.fsf@dell-desktop.WORKGROUP/
diff --git a/contrib/lisp/ox-bibtex.el b/contrib/lisp/ox-bibtex.el
index b46cb76..38c0957 100644

Checking patch contrib/lisp/ox-bibtex.el...
Applied patch contrib/lisp/ox-bibtex.el cleanly.

index at:
100644 38c0957dba31b98e332246ecd4be9ad1a84c1bed	contrib/lisp/ox-bibtex.el

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs/org-mode.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).