1 ;;; org-ref.el --- cite and cross-reference in org-mode
3 ;; Copyright(C) 2014 John Kitchin
5 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
6 ;; URL: https://github.com/jkitchin/org-ref
8 ;; Keywords: org-mode, cite, ref, label
9 ;; Package-Requires: ((org) (dash) (helm) (helm-bibtex) (hydra))
11 ;; This file is not currently part of GNU Emacs.
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License as
15 ;; published by the Free Software Foundation; either version 2, or (at
16 ;; your option) any later version.
18 ;; This program is distributed in the hope that it will be useful, but
19 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 ;; General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program ; see the file COPYING. If not, write to
25 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
30 ;; Lisp code to setup bibliography cite, ref and label org-mode links.
31 ;; also sets up reftex and helm for org-mode citations. The links are
32 ;; clickable and do things that are useful. You should really read
33 ;; org-ref.org for details.
38 (require 'reftex-cite)
41 (require 'helm-config)
42 (require 'helm-bibtex)
44 (require 'org-element)
48 "Customization group for org-ref.")
50 (defcustom org-ref-bibliography-notes
52 "Filename where you will put all your notes about an entry in the default bibliography."
56 (defcustom org-ref-default-bibliography
58 "List of bibtex files to search for.
59 You should use full-paths for each file."
60 :type '(repeat :tag "List of bibtex files" file)
63 (defcustom org-ref-pdf-directory
65 "Directory where pdfs are stored by key. put a trailing / in."
69 (defcustom org-ref-default-citation-link
71 "The default type of citation link to use."
75 (defcustom org-ref-insert-cite-key
77 "Keyboard shortcut to insert a citation."
81 (defcustom org-ref-bibliography-entry-format
82 '(("article" . "%a, %t, <i>%j</i>, <b>%v(%n)</b>, %p (%y). <a href=\"%U\">link</a>. <a href=\"http://dx.doi.org/%D\">doi</a>.")
84 ("book" . "%a, %t, %u (%y).")
85 ("techreport" . "%a, %t, %i, %u (%y).")
86 ("proceedings" . "%e, %t in %S, %u (%y).")
87 ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
88 "String to format an entry. Just the reference, no numbering at the beginning, etc... see the `org-ref-reftex-format-citation' docstring for the escape codes."
92 (defcustom org-ref-note-title-format
94 "String to format the title of a note. See the `org-ref-reftex-format-citation' docstring for the escape codes."
98 (defcustom org-ref-open-notes-function
104 ;;(org-tree-to-indirect-buffer)
105 (outline-previous-visible-heading 1)
106 (recenter-top-bottom 0))
107 "User-defined way to open a notes entry. This is excecuted after the entry is found, with the cursor at the beginning of the headline. The default setting fully expands the notes, and moves the headline to the top of the buffer."
112 (defcustom org-ref-open-pdf-function
113 'org-ref-open-pdf-at-point
114 "User-defined function to open a pdf from a link. The function must get the key at point, and derive a path to the pdf file, then open it. The default function is `org-ref-open-pdf-at-point'."
119 (defcustom org-ref-insert-cite-function
120 'org-ref-helm-insert-cite-link
121 "Function to call to insert citation links. The default is `org-ref-helm-insert-cite-link' which uses `helm-bibtex'. `org-ref' modifies `helm-bibtex' a little bit to give `org-mode' citations, and to reorder default actions. You may use `org-ref-insert-cite-link' if you like the reftex interface."
126 (defcustom org-ref-cite-onclick-function
127 'org-ref-cite-click-helm
128 "Function that runs when you click on a cite link. The function must take no arguments. You may also use `org-ref-cite-onclick-minibuffer-menu' if you do not like helm. If you like `hydra', consider using `org-ref-cite-hydra'."
133 (defcustom org-ref-show-citation-on-enter t
134 "If non-nil add a hook function to show the citation summary in the minibuffer."
137 (defcustom org-ref-cite-types
138 '("cite" "nocite" ;; the default latex cite commands
139 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
140 "citet" "citet*" "citep" "citep*"
141 "citealt" "citealt*" "citealp" "citealp*"
143 "citeauthor" "citeauthor*"
144 "citeyear" "citeyear*"
145 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
147 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
149 "parencite" "Parencite"
150 "footcite" "footcitetext"
151 "textcite" "Textcite"
152 "smartcite" "Smartcite"
153 "cite*" "parencite*" "supercite"
154 "autocite" "Autocite" "autocite*" "Autocite*"
156 "citetitle" "citetitle*"
157 "citedate" "citedate*"
159 "fullcite" "footfullcite"
160 ;; "volcite" "Volcite" cannot support the syntax
161 "notecite" "Notecite"
162 "pnotecite" "Pnotecite"
164 ;; multicites. Very limited support for these.
165 "cites" "Cites" "parencites" "Parencites"
166 "footcites" "footcitetexts"
167 "smartcites" "Smartcites" "textcites" "Textcites"
168 "supercites" "autocites" "Autocites"
169 ;; for the bibentry package
172 "List of citation types known in `org-ref'."
173 :type '(repeat :tag "List of citation types" string)
176 (defcustom org-ref-clean-bibtex-entry-hook nil
177 "Hook that is run in `org-ref-clean-bibtex-entry'. The functions should take no arguments, and operate on the bibtex entry at point."
181 (defvar org-ref-bibliography-files
183 "Variable to hold bibliography files to be searched.")
185 ;; * org-mode / reftex setup
187 (defun org-mode-reftex-setup ()
188 "Setup `org-mode' and reftex for org-ref."
189 (and (buffer-file-name)
190 (file-exists-p (buffer-file-name))
191 (global-auto-revert-mode t))
192 (make-local-variable 'reftex-cite-format)
193 (setq reftex-cite-format 'org))
195 ;; define key for inserting citations
196 (define-key org-mode-map
197 (kbd org-ref-insert-cite-key)
198 org-ref-insert-cite-function)
200 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
202 (eval-after-load 'reftex-vars
204 (add-to-list 'reftex-cite-format-builtin
205 '(org "Org-mode citation"
206 ((?\C-m . "cite:%l") ; default
207 (?d . ",%l") ; for appending
213 (?h . "citeauthor:%l")
214 (?H . "citeauthor*:%l")
220 ;; * Messages for link at cursor
221 (defvar org-ref-message-timer nil
222 "Variable to store the link message timer in.")
225 (defun org-ref-show-link-messages ()
226 "Turn on link messages.
227 You will see a message in the minibuffer when on a cite, ref or label link."
229 (or org-ref-message-timer
230 (setq org-ref-message-timer
231 (run-with-idle-timer 0.5 t 'org-ref-link-message))))
234 (defun org-ref-cancel-link-messages ()
235 "Stop showing messages in minibuffer when on a link."
237 (cancel-timer org-ref-message-timer)
238 (setq org-ref-message-timer nil))
241 (when org-ref-show-citation-on-enter
242 (org-ref-show-link-messages))
244 ;; ** Messages for context under mouse pointer
246 (defvar org-ref-last-mouse-pos nil
247 "Stores last mouse position for use in `org-ref-mouse-message'.")
249 (defun org-ref-can-move-p ()
250 "See if a character is under the mouse. If so return the position for `goto-char'."
251 (let* ((line (cddr org-ref-last-mouse-pos))
252 (col (cadr org-ref-last-mouse-pos)))
254 (goto-char (window-start))
257 (> (- (line-end-position) (line-beginning-position)) col)
258 (progn (forward-char col) (point))
262 (defun org-ref-mouse-message ()
263 "Display message for link under mouse cursor."
265 (when (not (equal (mouse-position) org-ref-last-mouse-pos))
266 (setq org-ref-last-mouse-pos (mouse-position))
267 (let ((p (org-ref-can-move-p)))
271 (org-ref-link-message))))))
274 (defvar org-ref-message-timer-mouse nil
275 "Store mouse timer.")
278 (defvar org-ref-mouse-message-interval 0.5
279 "How often to run the mouse message timer in seconds.")
282 (defun org-ref-mouse-messages-on ()
283 "Turn on mouse messages."
285 (or org-ref-message-timer-mouse
286 (setq org-ref-message-timer-mouse
287 (run-at-time "0.5 sec"
288 org-ref-mouse-message-interval
289 'org-ref-mouse-message))))
292 (defun org-ref-mouse-messages-off ()
293 "Turn off mouse messages."
295 (cancel-timer org-ref-message-timer-mouse)
296 (setq org-ref-message-timer-mouse nil)
297 (message "Mouse messages are off"))
299 ;; Colorizing org-ref links
300 (defcustom org-ref-colorize-links
302 "When non-nil, change colors of links."
306 (defcustom org-ref-cite-color
308 "Color of cite like links."
312 (defcustom org-ref-ref-color
314 "Color of ref like links."
318 (defcustom org-ref-label-color
320 "Color of label links."
324 (defvar org-ref-cite-re nil
325 "Regexp for cite links.")
328 (setq org-ref-cite-re
329 (concat "\\(" (mapconcat
331 (replace-regexp-in-string "\*" "\\\\*" x)
333 org-ref-cite-types "\\|") "\\)"
334 ":\\([a-zA-Z0-9-_:\\./]*,?\\)*"))
337 (defvar org-ref-label-re
338 "label:\\([a-zA-Z0-9-_:]*,?\\)*")
341 (defvar org-ref-ref-re
342 "\\(eq\\)?ref:\\([a-zA-Z0-9-_:]*,?\\)*")
345 (defface org-ref-cite-face
346 `((t (:inherit org-link :foreground ,org-ref-cite-color)))
347 "Color for cite-like links in org-ref.")
350 (defface org-ref-label-face
351 `((t (:inherit org-link :foreground ,org-ref-label-color)))
352 "Color for ref links in org-ref.")
355 (defface org-ref-ref-face
356 `((t (:inherit org-link :foreground ,org-ref-ref-color)))
357 "Face for ref links in org-ref.")
360 (defun org-ref-colorize-links ()
361 "Colorize org-ref links."
363 (highlight-regexp org-ref-cite-re 'org-ref-cite-face)
364 (highlight-regexp org-ref-label-re 'org-ref-label-face)
365 (highlight-regexp org-ref-ref-re 'org-ref-ref-face))
368 (when org-ref-colorize-links
369 (add-hook 'org-mode-hook 'org-ref-colorize-links))
371 ;; * General org-ref utilities
372 (defun org-ref-strip-string (string)
373 "Strip leading and trailing whitespace from the STRING."
374 (replace-regexp-in-string
375 (concat search-whitespace-regexp "$" ) ""
376 (replace-regexp-in-string
377 (concat "^" search-whitespace-regexp ) "" string)))
379 (defun org-ref-split-and-strip-string (string)
380 "Split key-string and strip keys in STRING.
381 Assumes the key-string is comma delimited."
382 (mapcar 'org-ref-strip-string (split-string string ",")))
384 (defun org-ref-reftex-get-bib-field (field entry &optional format)
385 "Similar to reftex-get-bib-field, but removes enclosing braces and quotes in FIELD in the bibtex ENTRY.
386 Optional argument FORMAT bibtex format."
388 (setq result (reftex-get-bib-field field entry format))
389 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
390 (setq result (substring result 1 -1)))
391 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
392 (setq result (substring result 1 -1)))
395 (defun org-ref-reftex-format-citation (entry format)
396 "Return a formatted string for the bibtex ENTRY (from bibtex-parse-entry) according to the FORMAT argument.
397 The format is a string with these percent escapes.
399 In the format, the following percent escapes will be expanded.
401 %l The BibTeX label of the citation.
402 %a List of author names, see also `reftex-cite-punctuation'.
403 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
404 %A First author name only.
405 %e Works like %a, but on list of editor names. (%2e and %E work a well)
407 It is also possible to access all other BibTeX database fields:
408 %b booktitle %c chapter %d edition %h howpublished
409 %i institution %j journal %k key %m month
410 %n number %o organization %p pages %P first page
411 %r address %s school %u publisher %t title
413 %B booktitle, abbreviated %T title, abbreviated
418 Usually, only %l is needed. The other stuff is mainly for the echo area
419 display, and for (setq reftex-comment-citations t).
421 %< as a special operator kills punctuation and space around it after the
422 string has been formatted.
424 A pair of square brackets indicates an optional argument, and RefTeX
425 will prompt for the values of these arguments.
427 Beware that all this only works with BibTeX database files. When
428 citations are made from the \bibitems in an explicit thebibliography
429 environment, only %l is available."
430 ;; Format a citation from the info in the BibTeX ENTRY
431 (unless (stringp format) (setq format "\\cite{%l}"))
433 (if (and reftex-comment-citations
434 (string-match "%l" reftex-cite-comment-format))
435 (error "Reftex-cite-comment-format contains invalid %%l"))
438 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
440 (let ((n (string-to-number (match-string 4 format)))
441 (l (string-to-char (match-string 5 format)))
447 (org-ref-reftex-get-bib-field "&key" entry)
448 (if reftex-comment-citations
449 reftex-cite-comment-format
451 ((= l ?a) (reftex-format-names
452 (reftex-get-bib-names "author" entry)
454 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
455 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
456 ((= l ?B) (reftex-abbreviate-title
457 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
458 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
459 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
460 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
461 ((= l ?e) (reftex-format-names
462 (reftex-get-bib-names "editor" entry)
464 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
465 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
466 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
467 ((= l ?j) (let ((jt (reftex-get-bib-field "journal" entry)))
469 (reftex-get-bib-field "journaltitle" entry)
471 ((= l ?k) (org-ref-reftex-get-bib-field "=key=" entry))
472 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
473 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
474 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
475 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
476 ((= l ?P) (car (split-string
477 (org-ref-reftex-get-bib-field "pages" entry)
479 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
480 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
481 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
482 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
483 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
484 ;; strip enclosing brackets from title if they are there
485 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
486 ((= l ?T) (reftex-abbreviate-title
487 ((replace-regexp-in-string
489 (org-ref-reftex-get-bib-field "title" entry)))))
490 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
491 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
494 (setq b (match-beginning 2) e (match-end 2))
495 (setq b (match-beginning 3) e (match-end 3)))
496 (setq format (concat (substring format 0 b) rpl (substring format e)))))
497 (while (string-match "%%" format)
498 (setq format (replace-match "%" t t format)))
499 (while (string-match "[ ,.;:]*%<" format)
500 (setq format (replace-match "" t t format)))
503 (defun org-ref-get-bibtex-entry-citation (key)
504 "Return a string for the bibliography entry corresponding to KEY.
505 Format according to the type in `org-ref-bibliography-entry-format'."
507 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
508 (file) (entry) (bibtex-entry) (entry-type) (format))
510 (setq file (catch 'result
511 (cl-loop for file in org-ref-bibliography-files do
512 (if (org-ref-key-in-file-p key (file-truename file))
514 (message "%s not found in %s"
515 key (file-truename file))))))
518 (insert-file-contents file)
519 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
520 (bibtex-search-entry key nil 0)
521 (setq bibtex-entry (bibtex-parse-entry))
522 ;; downcase field names so they work in the format-citation code
523 (dolist (cons-cell bibtex-entry)
524 (setf (car cons-cell) (downcase (car cons-cell))))
525 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
526 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
528 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
529 ;; if no format, we use the bibtex entry itself as a fallback
531 (bibtex-narrow-to-entry)
532 (setq entry (buffer-string)))))
535 (defun org-ref-get-bibtex-keys ()
536 "Return a list of unique keys in the buffer."
538 (org-element-map (org-element-parse-buffer) 'link
540 (let ((plist (nth 1 link)))
541 (when (-contains? org-ref-cite-types (plist-get plist ':type))
544 (org-ref-split-and-strip-string (plist-get plist ':path)))
545 (when (not (-contains? keys key))
546 (setq keys (append keys (list key))))))))
547 ;; set with-affiliated to get keys in captions
549 ;; Sort keys alphabetically
550 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
553 (defun org-ref-get-bibtex-entry-html (key)
554 "Return an html string for the bibliography entry corresponding to KEY."
556 (setq output (org-ref-get-bibtex-entry-citation key))
558 (setq output (replace-regexp-in-string "\\\\&" "&" output))
559 ;; hack to replace {} around text
560 (setq output (replace-regexp-in-string "{" "" output))
561 (setq output (replace-regexp-in-string "}" "" output))
562 ;; get rid of empty parens
563 (setq output (replace-regexp-in-string "()" "" output))
564 ;; get rid of empty link and doi
565 (setq output (replace-regexp-in-string " <a href=\"\">link</a>\\." "" output))
566 ;; change double dash to single dash
567 (setq output (replace-regexp-in-string "--" "-" output))
568 (setq output (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" output))
569 (format "<li><a id=\"%s\">[%s] %s</a></li>"
572 (defun org-ref-get-html-bibliography ()
573 "Create an html bibliography when there are keys."
574 (let ((keys (org-ref-get-bibtex-keys)))
576 (concat "<h1>Bibliography</h1>
578 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
581 (defun org-ref-get-bibtex-entry-org (key)
582 "Return an org string for the bibliography entry corresponding to KEY."
583 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
584 (file) (entry) (bibtex-entry) (entry-type) (format))
586 (setq file (catch 'result
587 (cl-loop for file in org-ref-bibliography-files do
588 (if (org-ref-key-in-file-p key (file-truename file))
590 (message "%s not found in %s" key (file-truename file))))))
593 (insert-file-contents file)
594 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
595 (bibtex-search-entry key nil 0)
596 (setq entry (bibtex-parse-entry))
601 " (org-ref-reftex-get-bib-field "author" entry)
602 (org-ref-reftex-get-bib-field "title" entry)
603 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
604 (mapconcat (lambda (element) (format " :%s: %s"
605 (upcase (car element))
610 (defun org-ref-get-org-bibliography ()
611 "Create an org bibliography when there are keys."
612 (let ((keys (org-ref-get-bibtex-keys)))
614 (concat "* Bibliography
616 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
619 (defun org-ref-get-bibtex-entry-ascii (key)
620 "Return an ascii string for the bibliography entry corresponding to KEY."
622 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
624 (defun org-ref-get-ascii-bibliography ()
625 "Create an html bibliography when there are keys."
626 (let ((keys (org-ref-get-bibtex-keys)))
632 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
636 ;; ** bibliography and bibliographystyle
637 (org-add-link-type "bibliography"
638 ;; this code is run on clicking. The bibliography
639 ;; may contain multiple files. this code finds the
640 ;; one you clicked on and opens it.
641 (lambda (link-string)
642 ;; get link-string boundaries we have to go to the
643 ;; beginning of the line, and then search forward
645 ;; object is the link you clicked on
646 (object (org-element-context))
647 (link-string-beginning)
651 (goto-char (org-element-property :begin object))
652 (search-forward link-string nil nil 1)
653 (setq link-string-beginning (match-beginning 0))
654 (setq link-string-end (match-end 0)))
656 ;; Make sure point is in the link-path.
657 (if (< cp link-string-beginning)
658 (goto-char link-string-beginning))
659 ;; We set the reftex-default-bibliography
660 ;; here. it should be a local variable only in
661 ;; the current buffer. We need this for using
662 ;; reftex to do citations.
663 (set (make-local-variable 'reftex-default-bibliography)
665 (org-element-property :path object) ","))
667 (let (key-beginning key-end)
668 ;; now if we have comma separated bibliographies
669 ;; we find the one clicked on. we want to
670 ;; search forward to next comma from point
672 (if (search-forward "," link-string-end 1 1)
674 (setq key-end (- (match-end 0) 1))
675 ;; no comma found so take the point
676 (setq key-end (point))))
677 ;; and backward to previous comma from point
679 (if (search-backward "," link-string-beginning 1 1)
681 (setq key-beginning (+ (match-beginning 0) 1))
682 (setq key-beginning (point)))) ; no match found
683 ;; save the key we clicked on.
684 (setq bibfile (org-ref-strip-string
685 (buffer-substring key-beginning key-end)))
686 ;; open file on click
687 (find-file bibfile))))
690 (lambda (keyword desc format)
692 ((eq format 'org) (org-ref-get-org-bibliography))
693 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
694 ((eq format 'html) (org-ref-get-html-bibliography))
696 ;; write out the latex bibliography command
697 (format "\\bibliography{%s}"
698 (replace-regexp-in-string
702 (mapcar 'expand-file-name
703 (split-string keyword ","))
706 (org-add-link-type "nobibliography"
707 ;; this code is run on clicking. The bibliography
708 ;; may contain multiple files. this code finds the
709 ;; one you clicked on and opens it.
710 (lambda (link-string)
711 ;; get link-string boundaries
712 ;; we have to go to the beginning of the line, and then search forward
715 ;; object is the link you clicked on
716 (object (org-element-context))
718 (link-string-beginning)
722 (goto-char (org-element-property :begin object))
723 (search-forward link-string nil nil 1)
724 (setq link-string-beginning (match-beginning 0))
725 (setq link-string-end (match-end 0)))
727 ;; We set the reftex-default-bibliography
728 ;; here. it should be a local variable only in
729 ;; the current buffer. We need this for using
730 ;; reftex to do citations.
731 (set (make-local-variable 'reftex-default-bibliography)
732 (split-string (org-element-property :path object) ","))
734 (let (key-beginning key-end)
735 ;; now if we have comma separated bibliographies
736 ;; we find the one clicked on. we want to
737 ;; search forward to next comma from point
739 (if (search-forward "," link-string-end 1 1)
740 (setq key-end (- (match-end 0) 1)) ; we found a match
741 (setq key-end (point)))) ; no comma found so take the point
742 ;; and backward to previous comma from point
744 (if (search-backward "," link-string-beginning 1 1)
745 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
746 (setq key-beginning (point)))) ; no match found
747 ;; save the key we clicked on.
748 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
749 (find-file bibfile)))) ; open file on click
752 (lambda (keyword desc format)
754 ((eq format 'org) (org-ref-get-org-bibliography))
755 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
756 ((eq format 'html) (org-ref-get-html-bibliography))
758 ;; write out the latex bibliography command
759 (format "\\nobibliography{%s}"
760 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
761 (mapcar 'expand-file-name
762 (split-string keyword ","))
765 (org-add-link-type "printbibliography"
766 (lambda (arg) (message "Nothing implemented for clicking here."))
767 (lambda (keyword desc format)
769 ((eq format 'org) (org-ref-get-org-bibliography))
770 ((eq format 'html) (org-ref-get-html-bibliography))
772 ;; write out the biblatex bibliography command
773 "\\printbibliography"))))
775 (org-add-link-type "bibliographystyle"
776 (lambda (arg) (message "Nothing implemented for clicking here."))
777 (lambda (keyword desc format)
780 ;; write out the latex bibliography command
781 (format "\\bibliographystyle{%s}" keyword))
782 ;; Other styles should not have an output for this
787 (defun org-bibliographystyle-complete-link (&optional arg)
788 "Completion function for bibliographystyle link.
790 (format "bibliographystyle:%s" (ido-completing-read
792 '("unsrt" "plain" "alpha"
794 ;; https://www.sharelatex.com/learn/Natbib_bibliography_styles
795 "dinat" "humannat" "plainnat"
796 "abbrnat" "unsrtnat" "rusnat"
800 (defun org-bibliography-complete-link (&optional arg)
801 "Completion function for bibliography link.
803 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
806 (defun org-ref-insert-bibliography-link ()
807 "Insert a bibliography with completion."
809 (insert (org-bibliography-complete-link)))
813 (org-add-link-type "addbibresource"
814 ;; this code is run on clicking. The addbibresource
815 ;; may contain multiple files. this code finds the
816 ;; one you clicked on and opens it.
817 (lambda (link-string)
818 ;; get link-string boundaries
819 ;; we have to go to the beginning of the line, and then search forward
822 ;; object is the link you clicked on
823 (object (org-element-context))
825 (link-string-beginning)
829 (goto-char (org-element-property :begin object))
830 (search-forward link-string nil nil 1)
831 (setq link-string-beginning (match-beginning 0))
832 (setq link-string-end (match-end 0)))
834 ;; We set the reftex-default-addbibresource
835 ;; here. it should be a local variable only in
836 ;; the current buffer. We need this for using
837 ;; reftex to do citations.
838 (set (make-local-variable 'reftex-default-addbibresource)
839 (split-string (org-element-property :path object) ","))
841 (let (key-beginning key-end)
842 ;; now if we have comma separated bibliographies
843 ;; we find the one clicked on. we want to
844 ;; search forward to next comma from point
846 (if (search-forward "," link-string-end 1 1)
847 (setq key-end (- (match-end 0) 1)) ; we found a match
848 (setq key-end (point)))) ; no comma found so take the point
849 ;; and backward to previous comma from point
851 (if (search-backward "," link-string-beginning 1 1)
852 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
853 (setq key-beginning (point)))) ; no match found
854 ;; save the key we clicked on.
855 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
856 (find-file bibfile)))) ; open file on click
859 (lambda (keyword desc format)
861 ((eq format 'html) (format "")); no output for html
863 ;; write out the latex addbibresource command
864 (format "\\addbibresource{%s}" keyword)))))
866 ;; ** List of figures
867 (defun org-ref-list-of-figures (&optional arg)
868 "Generate buffer with list of figures in them.
871 (save-excursion (widen)
872 (let* ((c-b (buffer-name))
875 (org-element-map (org-element-parse-buffer) 'link
877 "create a link for to the figure"
879 (and (string= (org-element-property :type link) "file")
881 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
882 (org-element-property :path link)))
885 (let* ((start (org-element-property :begin link))
886 (parent (car (cdr (org-element-property :parent link))))
887 (caption (cl-caaar (plist-get parent :caption)))
888 (name (plist-get parent :name)))
891 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
892 c-b start counter (or name "") caption)
894 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
895 c-b start counter (or name "")))))))))
896 (switch-to-buffer "*List of Figures*")
897 (setq buffer-read-only nil)
900 (insert (mapconcat 'identity list-of-figures ""))
901 (setq buffer-read-only t)
902 (use-local-map (copy-keymap org-mode-map))
903 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
907 'org-ref-list-of-figures ; on click
908 (lambda (keyword desc format)
911 (format "\\listoffigures")))))
914 (defun org-ref-list-of-tables (&optional arg)
915 "Generate a buffer with a list of tables.
920 (let* ((c-b (buffer-name))
923 (org-element-map (org-element-parse-buffer 'element) 'table
925 "create a link for to the table"
927 (let ((start (org-element-property :begin table))
928 (name (org-element-property :name table))
929 (caption (cl-caaar (org-element-property :caption table))))
932 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
933 c-b start counter (or name "") caption)
935 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
936 c-b start counter (or name ""))))))))
937 (switch-to-buffer "*List of Tables*")
938 (setq buffer-read-only nil)
941 (insert (mapconcat 'identity list-of-tables ""))
942 (setq buffer-read-only t)
943 (use-local-map (copy-keymap org-mode-map))
944 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
948 'org-ref-list-of-tables
949 (lambda (keyword desc format)
952 (format "\\listoftables")))))
956 (defun org-ref-count-labels (label)
957 "Counts number of matches for LABEL in the document."
958 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
959 ;; for tblname, it is not enough to get word boundary
960 ;; tab-little and tab-little-2 match then.
961 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
962 (count-matches (format "\\label{%s}" label) (point-min) (point-max))
963 ;; this is the org-format #+label:
964 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
965 (let ((custom-id-count 0))
968 (when (string= label (org-entry-get (point) "CUSTOM_ID"))
969 (setq custom-id-count (+ 1 custom-id-count)))))
975 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
976 (let ((count (org-ref-count-labels label)))
977 (message (format "%s occurence%s"
983 (org-ref-count-labels label))))
984 (lambda (keyword desc format)
986 ((eq format 'html) (format "<div id=\"%s\">" keyword))
988 (format "\\label{%s}" keyword)))))
990 (defun org-label-store-link ()
991 "Store a link to a label. The output will be a ref to that label."
992 ;; First we have to make sure we are on a label link.
993 (let* ((object (org-element-context)))
994 (when (and (equal (org-element-type object) 'link)
995 (equal (org-element-property :type object) "label"))
996 (org-store-link-props
998 :link (concat "ref:" (org-element-property :path object))))
1000 ;; Store link on table
1001 (when (equal (org-element-type object) 'table)
1002 (org-store-link-props
1004 :link (concat "ref:" (org-element-property :name object))))
1006 ;; store link on heading with custom_id
1007 ;; this is not a ref link, but it is still what you want
1008 (when (and (equal (org-element-type object) 'headline)
1009 (org-entry-get (point) "CUSTOM_ID"))
1010 (org-store-link-props
1012 :link (format "[[#%s]]" (org-entry-get (point) "CUSTOM_ID"))))
1014 ;; and to #+label: lines
1016 (when (and (equal (org-element-type object) 'paragraph)
1017 (org-element-property :name object))
1018 (org-store-link-props
1020 :link (concat "ref:" (org-element-property :name object))))))
1022 (add-hook 'org-store-link-functions 'org-label-store-link)
1028 "on clicking goto the label. Navigate back with C-c &"
1029 (org-mark-ring-push)
1030 ;; next search from beginning of the buffer
1031 ;; it is possible you would not find the label if narrowing is in effect
1037 (goto-char (point-min))
1038 (re-search-forward (format "label:%s\\b" label) nil t))
1042 (goto-char (point-min))
1043 (re-search-forward (format "\\label{%s}" label) nil t))
1045 ;; #+label: name org-definition
1047 (goto-char (point-min))
1049 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1053 (goto-char (point-min))
1055 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1057 ;; we did not find anything, so go back to where we came
1058 (org-mark-ring-goto)
1059 (error "%s not found" label))
1061 (message "go back with (org-mark-ring-goto) `C-c &`"))
1063 (lambda (keyword desc format)
1065 ((eq format 'html) (format "<a href=\"#%s\">%s</a>" keyword keyword))
1067 (format "\\ref{%s}" keyword)))))
1070 (defun org-ref-get-org-labels ()
1071 "Return a list of #+LABEL: labels."
1073 (goto-char (point-min))
1074 (let ((matches '()))
1075 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1076 ;; do not do this for tables. We get those in `org-ref-get-tblnames'.
1077 ;; who would have thought you have save match data here? Trust me. When
1078 ;; I wrote this, you did.
1079 (unless (save-match-data (equal (car (org-element-at-point)) 'table))
1080 (add-to-list 'matches (match-string-no-properties 1) t)))
1084 (defun org-ref-get-custom-ids ()
1085 "Return a list of custom_id properties in the buffer."
1086 (let ((results '()) custom_id)
1089 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1090 (when (not (null custom_id))
1091 (setq results (append results (list custom_id)))))))
1095 (defun org-ref-get-latex-labels ()
1096 "Return list of matchin LaTeX defined labels in buffer."
1098 (goto-char (point-min))
1099 (let ((matches '()))
1100 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1101 (add-to-list 'matches (match-string-no-properties 1) t))
1105 (defun org-ref-get-tblnames ()
1106 "Return list of table names in the buffer."
1107 (org-element-map (org-element-parse-buffer 'element) 'table
1109 (org-element-property :name table))))
1112 (defun org-ref-get-labels ()
1113 "Return a list of labels in the buffer that you can make a ref link to.
1114 This is used to complete ref links and in helm menus."
1118 (goto-char (point-min))
1119 (let ((matches '()))
1120 ;; these are the org-ref label:stuff kinds
1121 (while (re-search-forward
1122 "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1123 (add-to-list 'matches (match-string-no-properties 1) t))
1124 ;; now add all the other kinds of labels.
1127 (org-ref-get-org-labels)
1129 (org-ref-get-latex-labels)
1130 ;; #+tblname: and actually #+label
1131 (org-ref-get-tblnames)
1133 (org-ref-get-custom-ids))))))
1136 (defun org-ref-helm-insert-label-link ()
1137 "Insert a label link. helm just shows you what labels already exist.
1138 If you are on a label link, replace it."
1140 (let* ((labels (org-ref-get-labels))
1141 (cb (current-buffer)))
1142 (helm :sources `(((name . "Existing labels")
1143 (candidates . ,labels)
1144 ;; default action is to open to the label
1145 (action . (lambda (label)
1146 ;; unfortunately I do not have markers here
1147 (org-open-link-from-string
1148 (format "ref:%s" label))))
1149 ;; if you select a label, replace current one
1150 (action . (lambda (label)
1151 (switch-to-buffer ,cb)
1153 ;; no prefix or on a link
1154 ((equal helm-current-prefix-arg nil)
1155 (let* ((object (org-element-context))
1156 (last-char (save-excursion
1157 (goto-char (org-element-property :end object))
1159 (if (looking-at " ")
1162 (when (-contains? '("label")
1163 (org-element-property :type object))
1164 ;; we are on a link, so replace it.
1167 (org-element-property :begin object)
1168 (org-element-property :end object))
1170 (replace-regexp-in-string
1171 (org-element-property :path object)
1173 (org-element-property :raw-link object))
1175 ;; no prefix options defined
1177 ;; no matching selection creates a new label
1178 ((name . "Create new label")
1180 ;; default action creates a new label, or replaces old one
1181 (action . (lambda (label)
1182 (switch-to-buffer ,cb)
1183 (let* ((object (org-element-context))
1184 (last-char (save-excursion
1185 (goto-char (org-element-property :end object))
1187 (if (looking-at " ")
1190 (if (-contains? '("label")
1191 (org-element-property :type object))
1192 ;; we are on a link, so replace it.
1195 (org-element-property :begin object)
1196 (org-element-property :end object))
1198 (replace-regexp-in-string
1199 (org-element-property :path object)
1201 (org-element-property :raw-link object))
1208 helm-pattern))))))))))))
1211 (defun org-ref-complete-link (&optional arg)
1212 "Completion function for ref links.
1213 Optional argument ARG Does nothing."
1215 (setq label (completing-read "label: " (org-ref-get-labels)))
1216 (format "ref:%s" label)))
1219 (defun org-ref-insert-ref-link ()
1220 "Completion function for a ref link."
1222 (insert (org-ref-complete-link)))
1225 (defun org-ref-helm-insert-ref-link ()
1226 "Helm menu to insert ref links to labels in the document.
1227 If you are on link, replace with newly selected label.
1228 Use C-u to insert a different kind of ref link.
1229 Use C-u C-u to insert a [[#custom-id]] link"
1231 (let* ((labels (org-ref-get-labels))
1232 (bs (buffer-string))
1233 (contexts (with-temp-buffer
1235 (mapcar 'org-ref-get-label-context labels)))
1236 (cb (current-buffer)))
1238 (helm :input (thing-at-point 'word)
1239 :sources `(((name . "Available labels to ref")
1240 (candidates . ,(cl-loop for label in labels
1241 for context in contexts
1242 ;; we do some kludgy adding spaces
1243 ;; and bars to make it "easier" to
1245 collect (cons (concat
1250 (split-string context "\n")
1253 ;; default action to replace or insert ref link.
1254 (action . (lambda (label)
1255 (switch-to-buffer ,cb)
1258 ;; no prefix or on a link
1259 ((equal helm-current-prefix-arg nil)
1260 (let* ((object (org-element-context))
1261 (last-char (save-excursion
1262 (goto-char (org-element-property :end object))
1264 (if (looking-at " ")
1267 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1268 (org-element-property :type object))
1269 ;; we are on a link, so replace it.
1272 (org-element-property :begin object)
1273 (org-element-property :end object))
1275 (replace-regexp-in-string
1276 (org-element-property :path object)
1278 (org-element-property :raw-link object))
1280 ;; insert a new link
1285 ;; one prefix, alternate ref link
1286 ((equal helm-current-prefix-arg '(4))
1289 (helm :sources '((name . "Ref link types")
1290 (candidates . ("ref" "eqref" "pageref" "nameref"))
1291 (action . (lambda (x) x))))
1293 ;; two prefixes, insert section custom-id link
1294 ((equal helm-current-prefix-arg '(16))
1296 (format "[[#%s]]" label)))
1304 "on clicking goto the label. Navigate back with C-c &"
1305 (org-mark-ring-push)
1306 ;; next search from beginning of the buffer
1312 (goto-char (point-min))
1313 (re-search-forward (format "label:%s\\b" label) nil t))
1317 (goto-char (point-min))
1318 (re-search-forward (format "\\label{%s}" label) nil t))
1320 ;; #+label: name org-definition
1322 (goto-char (point-min))
1324 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1328 (goto-char (point-min))
1330 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1331 ;; we did not find anything, so go back to where we came
1332 (org-mark-ring-goto)
1333 (error "%s not found" label))
1334 (message "go back with (org-mark-ring-goto) `C-c &`"))
1336 (lambda (keyword desc format)
1338 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1340 (format "\\pageref{%s}" keyword)))))
1343 (defun org-pageref-complete-link (&optional arg)
1344 "Completion function for ref links.
1345 Optional argument ARG Does nothing."
1347 (setq label (completing-read "label: " (org-ref-get-labels)))
1348 (format "ref:%s" label)))
1351 (defun org-pageref-insert-ref-link ()
1352 "Insert a pageref link with completion."
1354 (insert (org-pageref-complete-link)))
1361 "on clicking goto the label. Navigate back with C-c &"
1362 (org-mark-ring-push)
1363 ;; next search from beginning of the buffer
1369 (goto-char (point-min))
1370 (re-search-forward (format "\\label{%s}" label) nil t))
1372 ;; we did not find anything, so go back to where we came
1373 (org-mark-ring-goto)
1374 (error "%s not found" label))
1375 (message "go back with (org-mark-ring-goto) `C-c &`"))
1377 (lambda (keyword desc format)
1379 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1381 (format "\\nameref{%s}" keyword)))))
1388 "on clicking goto the label. Navigate back with C-c &"
1389 (org-mark-ring-push)
1390 ;; next search from beginning of the buffer
1392 (goto-char (point-min))
1395 ;; search forward for the first match
1397 (re-search-forward (format "label:%s" label) nil t)
1399 (re-search-forward (format "\\label{%s}" label) nil t)
1400 ;; #+label: name org-definition
1401 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1402 (org-mark-ring-goto)
1403 (error "%s not found" label))
1404 (message "go back with (org-mark-ring-goto) `C-c &`"))
1406 (lambda (keyword desc format)
1408 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1410 (format "\\eqref{%s}" keyword)))))
1414 (defun org-ref-get-bibtex-key-under-cursor ()
1415 "Return key under the bibtex cursor.
1416 We search forward from
1417 point to get a comma, or the end of the link, and then backwards
1418 to get a comma, or the beginning of the link. that delimits the
1419 keyword we clicked on. We also strip the text properties."
1420 (let* ((object (org-element-context))
1421 (link-string (org-element-property :path object)))
1422 ;; you may click on the part before the citations. here we make
1423 ;; sure to move to the beginning so you get the first citation.
1425 (goto-char (org-element-property :begin object))
1426 (search-forward link-string (org-element-property :end object))
1427 (goto-char (match-beginning 0))
1428 ;; check if we clicked before the path and move as needed.
1429 (unless (< cp (point))
1432 (if (not (org-element-property :contents-begin object))
1433 ;; this means no description in the link
1435 ;; we need the link path start and end
1436 (let (link-string-beginning link-string-end)
1438 (goto-char (org-element-property :begin object))
1439 (search-forward link-string nil nil 1)
1440 (setq link-string-beginning (match-beginning 0))
1441 (setq link-string-end (match-end 0)))
1443 (let (key-beginning key-end)
1444 ;; The key is the text between commas, or the link boundaries
1446 (if (search-forward "," link-string-end t 1)
1447 (setq key-end (- (match-end 0) 1)) ; we found a match
1448 (setq key-end link-string-end))) ; no comma found so take the end
1449 ;; and backward to previous comma from point which defines the start character
1451 (if (search-backward "," link-string-beginning 1 1)
1452 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1453 (setq key-beginning link-string-beginning))) ; no match found
1454 ;; save the key we clicked on.
1456 (org-ref-strip-string
1457 (buffer-substring key-beginning key-end))))
1458 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1460 ;; link with description. assume only one key
1463 (defun org-ref-find-bibliography ()
1464 "Find the bibliography in the buffer.
1465 This function sets and returns cite-bibliography-files, which is a list of files
1466 either from bibliography:f1.bib,f2.bib
1467 \bibliography{f1,f2}
1468 internal bibliographies
1470 falling back to what the user has set in `org-ref-default-bibliography'"
1473 (goto-char (point-min))
1474 ;; look for a bibliography link
1475 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1476 (setq org-ref-bibliography-files
1477 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1478 (throw 'result org-ref-bibliography-files))
1481 ;; we did not find a bibliography link. now look for \bibliography
1482 (goto-char (point-min))
1483 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1484 ;; split, and add .bib to each file
1485 (setq org-ref-bibliography-files
1486 (mapcar (lambda (x) (concat x ".bib"))
1487 (mapcar 'org-ref-strip-string
1488 (split-string (match-string 1) ","))))
1489 (throw 'result org-ref-bibliography-files))
1491 ;; no bibliography found. maybe we need a biblatex addbibresource
1492 (goto-char (point-min))
1493 ;; look for a bibliography link
1494 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1495 (setq org-ref-bibliography-files
1496 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1497 (throw 'result org-ref-bibliography-files))
1499 ;; we did not find anything. use defaults
1500 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1502 ;; set reftex-default-bibliography so we can search
1503 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1504 org-ref-bibliography-files)
1506 (defun org-ref-key-in-file-p (key filename)
1507 "Determine if the KEY is in the FILENAME."
1508 (save-current-buffer
1509 (let ((bibtex-files (list filename)))
1510 ;; This is something I am trying because when the bibtex file is open, and
1511 ;; you have added to it, the only way I find to get the update to update
1512 ;; is to close it and reopen it. or to save it and revert it.
1513 (when (get-file-buffer filename)
1514 (set-buffer (get-file-buffer filename))
1516 (revert-buffer t t))
1517 (bibtex-search-entry key t))))
1519 (defun org-ref-get-bibtex-key-and-file (&optional key)
1520 "Return the bibtex KEY and file that it is in. If no key is provided, get one under point."
1521 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1524 (setq key (org-ref-get-bibtex-key-under-cursor)))
1525 (setq file (catch 'result
1526 (cl-loop for file in org-ref-bibliography-files do
1527 (if (org-ref-key-in-file-p key (file-truename file))
1528 (throw 'result file)))))
1531 ;; *** key at point functions
1533 (defun org-ref-open-pdf-at-point ()
1534 "Open the pdf for bibtex key under point if it exists."
1536 (let* ((results (org-ref-get-bibtex-key-and-file))
1538 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1539 (if (file-exists-p pdf-file)
1540 (org-open-file pdf-file)
1541 (message "no pdf found for %s" key))))
1544 (defun org-ref-open-url-at-point ()
1545 "Open the url for bibtex key under point."
1547 (let* ((results (org-ref-get-bibtex-key-and-file))
1549 (bibfile (cdr results)))
1552 (insert-file-contents bibfile)
1553 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1554 (bibtex-search-entry key)
1555 ;; I like this better than bibtex-url which does not always find
1558 (let ((url (bibtex-autokey-get-field "url")))
1560 (browse-url (s-trim url))
1563 (let ((doi (bibtex-autokey-get-field "doi")))
1565 (if (string-match "^http" doi)
1567 (browse-url (format "http://dx.doi.org/%s" (s-trim doi))))
1568 (throw 'done nil))))))))
1571 (defun org-ref-open-notes-at-point ()
1572 "Open the notes for bibtex key under point."
1574 (let* ((results (org-ref-get-bibtex-key-and-file))
1576 (bibfile (cdr results)))
1579 (insert-file-contents bibfile)
1580 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1581 (bibtex-search-entry key)
1582 (org-ref-open-bibtex-notes)))))
1585 (defun org-ref-citation-at-point ()
1586 "Give message of current citation at point."
1588 (let* ((cb (current-buffer))
1589 (results (org-ref-get-bibtex-key-and-file))
1591 (bibfile (cdr results)))
1592 (message "%s" (progn
1594 (insert-file-contents bibfile)
1595 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1596 (bibtex-search-entry key)
1597 (org-ref-bib-citation))))))
1600 (defun org-ref-open-citation-at-point ()
1601 "Open bibtex file to key at point."
1603 (let* ((cb (current-buffer))
1604 (results (org-ref-get-bibtex-key-and-file))
1606 (bibfile (cdr results)))
1608 (bibtex-search-entry key)))
1612 (defvar org-ref-cite-menu-funcs '()
1613 "Functions to run on cite click menu.
1614 Each entry is a list of (key menu-name function).
1615 The function must take no arguments and work on the key at point. Do not modify this variable, it is set to empty in the menu click function, and functions are conditionally added to it.")
1618 (defvar org-ref-user-cite-menu-funcs
1619 '(("C" "rossref" org-ref-crossref-at-point)
1620 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1621 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1622 "User-defined functions to run on bibtex key at point.")
1625 (defun org-ref-copy-entry-as-summary ()
1626 "Copy the bibtex entry for the citation at point as a summary."
1628 (save-window-excursion
1629 (org-ref-open-citation-at-point)
1630 (kill-new (org-ref-bib-citation))))
1633 (defun org-ref-copy-entry-at-point-to-file ()
1634 "Copy the bibtex entry for the citation at point to NEW-FILE.
1635 Prompt for NEW-FILE includes bib files in `org-ref-default-bibliography', and bib files in current working directory. You can also specify a new file."
1637 (let ((new-file (ido-completing-read
1639 (append org-ref-default-bibliography
1640 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1641 (key (org-ref-get-bibtex-key-under-cursor)))
1642 (save-window-excursion
1643 (org-ref-open-citation-at-point)
1644 (bibtex-copy-entry-as-kill))
1646 (let ((bibtex-files (list (file-truename new-file))))
1647 (if (assoc key (bibtex-global-key-alist))
1648 (message "That key already exists in %s" new-file)
1650 (save-window-excursion
1651 (find-file new-file)
1652 (goto-char (point-max))
1653 ;; make sure we are at the beginning of a line.
1654 (unless (looking-at "^") (insert "\n\n"))
1659 (defun org-ref-get-doi-at-point ()
1660 "Get doi for key at point."
1661 (let* ((results (org-ref-get-bibtex-key-and-file))
1663 (bibfile (cdr results))
1667 (insert-file-contents bibfile)
1668 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1669 (bibtex-search-entry key)
1670 (setq doi (bibtex-autokey-get-field "doi"))
1671 ;; in case doi is a url, remove the url part.
1672 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1675 ;; **** functions that operate on key at point for click menu
1676 (defun org-ref-wos-at-point ()
1677 "Open the doi in wos for bibtex key under point."
1679 (doi-utils-wos (org-ref-get-doi-at-point)))
1682 (defun org-ref-wos-citing-at-point ()
1683 "Open the doi in wos citing articles for bibtex key under point."
1685 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1688 (defun org-ref-wos-related-at-point ()
1689 "Open the doi in wos related articles for bibtex key under point."
1691 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1694 (defun org-ref-google-scholar-at-point ()
1695 "Open the doi in google scholar for bibtex key under point."
1697 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1700 (defun org-ref-pubmed-at-point ()
1701 "Open the doi in pubmed for bibtex key under point."
1703 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1706 (defun org-ref-crossref-at-point ()
1707 "Open the doi in crossref for bibtex key under point."
1709 (doi-utils-crossref (org-ref-get-doi-at-point)))
1711 ;; *** Minibuffer menu
1713 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1714 "Action when a cite link is clicked on.
1715 Provides a menu of context sensitive actions. If the bibtex entry
1716 has a pdf, you get an option to open it. If there is a doi, you
1717 get a lot of options. LINK-STRING is used by the link function."
1719 (let* ((results (org-ref-get-bibtex-key-and-file))
1721 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1722 (bibfile (cdr results))
1723 (url (save-excursion
1725 (insert-file-contents bibfile)
1726 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1727 (bibtex-search-entry key)
1728 (bibtex-autokey-get-field "url"))))
1729 (doi (save-excursion
1731 (insert-file-contents bibfile)
1732 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1733 (bibtex-search-entry key)
1734 ;; I like this better than bibtex-url which does not always find
1736 (bibtex-autokey-get-field "doi")))))
1738 (when (string= "" doi) (setq doi nil))
1739 (when (string= "" url) (setq url nil))
1740 (setq org-ref-cite-menu-funcs '())
1746 'org-ref-cite-menu-funcs
1747 '("o" "pen" org-ref-open-citation-at-point)))
1750 (when (file-exists-p pdf-file)
1752 'org-ref-cite-menu-funcs
1753 `("p" "df" ,org-ref-open-pdf-function) t))
1757 'org-ref-cite-menu-funcs
1758 '("n" "otes" org-ref-open-notes-at-point) t)
1763 'org-ref-cite-menu-funcs
1764 '("u" "rl" org-ref-open-url-at-point) t))
1769 'org-ref-cite-menu-funcs
1770 '("w" "os" org-ref-wos-at-point) t)
1773 'org-ref-cite-menu-funcs
1774 '("c" "iting" org-ref-wos-citing-at-point) t)
1777 'org-ref-cite-menu-funcs
1778 '("r" "elated" org-ref-wos-related-at-point) t)
1781 'org-ref-cite-menu-funcs
1782 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1785 'org-ref-cite-menu-funcs
1786 '("P" "ubmed" org-ref-pubmed-at-point) t))
1788 ;; add user functions
1789 (dolist (tup org-ref-user-cite-menu-funcs)
1791 'org-ref-cite-menu-funcs
1796 'org-ref-cite-menu-funcs
1797 '("q" "uit" (lambda ())) t)
1799 ;; now we make a menu
1800 ;; construct menu string as a message
1803 (let* ((results (org-ref-get-bibtex-key-and-file))
1805 (bibfile (cdr results)))
1808 (insert-file-contents bibfile)
1809 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1810 (bibtex-search-entry key)
1811 (org-ref-bib-citation))))
1815 (concat "[" (elt tup 0) "]"
1817 org-ref-cite-menu-funcs "")))
1819 (let* ((input (read-char-exclusive))
1821 (char-to-string input) org-ref-cite-menu-funcs)))
1822 ;; now run the function (2nd element in choice)
1829 ;; *** Generation of the cite links
1830 (defmacro org-ref-make-completion-function (type)
1831 "Macro to make a link completion function for a link of TYPE."
1832 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1838 (let ((bibtex-files (org-ref-find-bibliography)))
1839 (bibtex-global-key-alist))))))
1841 (defmacro org-ref-make-format-function (type)
1842 "Macro to make a format function for a link of TYPE."
1843 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1848 (format "[[#%s][%s]]" key key))
1849 (org-ref-split-and-strip-string keyword) ","))
1856 (org-ref-split-and-strip-string keyword) ",") "]"))
1861 (format "<a href=\"#%s\">%s</a>" key key))
1862 (org-ref-split-and-strip-string keyword) ","))
1865 (if (string= (substring type -1) "s")
1866 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1867 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1868 (org-ref-split-and-strip-string keyword) ""))
1870 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1871 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1873 ;; for markdown we generate pandoc citations
1876 (desc ;; pre and or post text
1877 (let* ((text (split-string desc "::"))
1881 (format "[@%s," keyword)
1882 (when pre (format " %s" pre))
1883 (when post (format ", %s" post))
1888 (lambda (key) (concat "@" key))
1889 (org-ref-split-and-strip-string keyword)
1892 (defun org-ref-format-citation-description (desc)
1893 "Return formatted citation description.
1894 If the cite link has a DESC (description), it is optional text
1895 for the citation command. You can specify pre and post text by
1896 separating these with ::, for example [[cite:key][pre text::post
1899 ((string-match "::" desc)
1900 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1901 (t (format "[%s]" desc))))
1903 (defun org-ref-define-citation-link (type &optional key)
1904 "Add a citation link of TYPE for org-ref.
1905 With optional KEY, set the reftex binding. For example:
1906 \(org-ref-define-citation-link \"citez\" ?z) will create a new
1907 citez link, with reftex key of z, and the completion function."
1908 (interactive "sCitation Type: \ncKey: ")
1910 ;; create the formatting function
1911 (eval `(org-ref-make-format-function ,type))
1916 org-ref-cite-onclick-function
1917 (quote ,(intern (format "org-ref-format-%s" type)))))
1919 ;; create the completion function
1920 (eval `(org-ref-make-completion-function ,type))
1922 ;; store new type so it works with adding citations, which checks
1923 ;; for existence in this list
1924 (add-to-list 'org-ref-cite-types type)
1926 ;; and finally if a key is specified, we modify the reftex menu
1928 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1929 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1930 `((,key . ,(concat type ":%l")))))))
1932 ;; create all the link types and their completion functions
1933 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1935 (defun org-ref-insert-cite-link (alternative-cite)
1936 "Insert a default citation link using reftex.
1937 If you are on a link, it appends to the end of the link,
1938 otherwise, a new link is inserted. Use a prefix
1939 arg (ALTERNATIVE-CITE) to get a menu of citation types."
1941 (org-ref-find-bibliography)
1942 (let* ((object (org-element-context))
1943 (link-string-beginning (org-element-property :begin object))
1944 (link-string-end (org-element-property :end object))
1945 (path (org-element-property :path object)))
1947 (if (not alternative-cite)
1950 ;; case where we are in a link
1951 ((and (equal (org-element-type object) 'link)
1952 (-contains? org-ref-cite-types (org-element-property :type object)))
1953 (goto-char link-string-end)
1954 ;; sometimes there are spaces at the end of the link
1955 ;; this code moves point pack until no spaces are there
1956 (while (looking-back " ") (backward-char))
1957 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1959 ;; We are next to a link, and we want to append
1962 (and (equal (org-element-type (org-element-context)) 'link)
1963 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1964 (while (looking-back " ") (backward-char))
1965 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1967 ;; insert fresh link
1970 (concat org-ref-default-citation-link
1972 (mapconcat 'identity (reftex-citation t) ",")))))
1974 ;; you pressed a C-u so we run this code
1975 (reftex-citation))))
1977 (defun org-ref-insert-cite-with-completion (type)
1978 "Insert a cite link of TYPE with completion."
1979 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1980 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1982 (defun org-ref-store-bibtex-entry-link ()
1983 "Save a citation link to the current bibtex entry. Save in the default link type."
1985 (let ((link (concat org-ref-default-citation-link
1988 (bibtex-beginning-of-entry)
1989 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1990 (message "saved %s" link)
1991 (push (list link) org-stored-links)
1992 (car org-stored-links)))
2000 (lambda (path desc format)
2003 (format "\\index{%s}" path)))))
2005 ;; this will generate a temporary index of entries in the file.
2009 (let ((*index-links* '())
2010 (*initial-letters* '()))
2013 (org-element-map (org-element-parse-buffer) 'link
2015 (let ((type (nth 0 link))
2016 (plist (nth 1 link)))
2018 (when (equal (plist-get plist ':type) "index")
2021 (cons (plist-get plist :path)
2023 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2025 (plist-get plist :begin) ;; position of link
2026 ;; grab a description
2028 (goto-char (plist-get plist :begin))
2029 (if (thing-at-point 'sentence)
2031 (replace-regexp-in-string
2032 "\n" "" (thing-at-point 'sentence))
2033 ;; or call it a link
2037 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
2039 ;; now first letters
2040 (dolist (link *index-links*)
2041 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2043 ;; now create the index
2044 (switch-to-buffer (get-buffer-create "*index*"))
2047 (insert "#+TITLE: Index\n\n")
2048 (dolist (letter *initial-letters*)
2049 (insert (format "* %s\n" (upcase letter)))
2050 ;; now process the links
2053 (string= letter (substring (car (car *index-links*)) 0 1)))
2054 (let ((link (pop *index-links*)))
2055 (insert (format "%s %s\n\n" (car link) (cdr link))))))
2056 (switch-to-buffer "*index*")))
2058 (lambda (path desc format)
2061 (format "\\printindex")))))
2066 nil ;; no follow action
2067 (lambda (path desc format)
2070 (format "\\newglossaryentry{%s}{%s}" path desc)))))
2076 nil ;; no follow action
2077 (lambda (path desc format)
2080 (format "\\gls{%s}" path)))))
2085 nil ;; no follow action
2086 (lambda (path desc format)
2089 (format "\\glspl{%s}" path)))))
2094 nil ;; no follow action
2095 (lambda (path desc format)
2098 (format "\\Gls{%s}" path)))))
2103 nil ;; no follow action
2104 (lambda (path desc format)
2107 (format "\\Glspl{%s}" path)))))
2110 ;; ** create text citations from a bibtex entry
2111 (defun org-ref-bib-citation ()
2112 "From a bibtex entry, create and return a simple citation string.
2113 This assumes you are in an article."
2114 (bibtex-set-dialect nil t)
2115 (bibtex-beginning-of-entry)
2116 (let* ((cb (current-buffer))
2117 (bibtex-expand-strings t)
2118 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2119 collect (cons (downcase key) value)))
2120 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2121 (year (reftex-get-bib-field "year" entry))
2122 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2123 (key (reftex-get-bib-field "=key=" entry))
2124 (journal (let ((jt (reftex-get-bib-field "journal" entry)))
2126 (reftex-get-bib-field "journaltitle" entry)
2128 (volume (reftex-get-bib-field "volume" entry))
2129 (pages (reftex-get-bib-field "pages" entry))
2130 (doi (reftex-get-bib-field "doi" entry))
2131 (url (reftex-get-bib-field "url" entry))
2133 ;;authors, "title", Journal, vol(iss):pages (year).
2134 (format "%s, \"%s\", %s, %s:%s (%s)"
2135 author title journal volume pages year)))
2137 (defun org-ref-bib-html-citation ()
2138 "From a bibtex entry, create and return a simple citation with html links."
2139 (bibtex-beginning-of-entry)
2140 (let* ((cb (current-buffer))
2141 (bibtex-expand-strings t)
2142 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2143 collect (cons (downcase key) value)))
2144 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2145 (year (reftex-get-bib-field "year" entry))
2146 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2147 (key (reftex-get-bib-field "=key=" entry))
2148 (journal (reftex-get-bib-field "journal" entry))
2149 (volume (reftex-get-bib-field "volume" entry))
2150 (pages (reftex-get-bib-field "pages" entry))
2151 (doi (reftex-get-bib-field "doi" entry))
2152 (url (reftex-get-bib-field "url" entry)))
2153 ;;authors, "title", Journal, vol(iss):pages (year).
2154 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2155 author title journal volume pages year)
2156 (when url (format " <a href=\"%s\">link</a>" url))
2158 (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))))
2160 ;; ** Open pdf in bibtex entry
2161 (defun org-ref-open-bibtex-pdf ()
2162 "Open pdf for a bibtex entry, if it exists.
2164 the entry of interest in the bibfile. but does not check that."
2167 (bibtex-beginning-of-entry)
2168 (let* ((bibtex-expand-strings t)
2169 (entry (bibtex-parse-entry t))
2170 (key (reftex-get-bib-field "=key=" entry))
2171 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2173 (if (file-exists-p pdf)
2174 (org-open-link-from-string (format "[[file:%s]]" pdf))
2177 ;; ** Open notes from bibtex entry
2179 (defun org-ref-open-bibtex-notes ()
2180 "From a bibtex entry, open the notes if they exist, and create a heading if they do not.
2182 I never did figure out how to use reftex to make this happen
2183 non-interactively. the reftex-format-citation function did not
2184 work perfectly; there were carriage returns in the strings, and
2185 it did not put the key where it needed to be. so, below I replace
2186 the carriage returns and extra spaces with a single space and
2187 construct the heading by hand."
2190 (bibtex-beginning-of-entry)
2191 (let* ((cb (current-buffer))
2192 (bibtex-expand-strings t)
2193 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2194 collect (cons (downcase key) value)))
2195 (key (reftex-get-bib-field "=key=" entry)))
2197 ;; save key to clipboard to make saving pdf later easier by pasting.
2200 (kill-ring-save (point-min) (point-max)))
2202 ;; now look for entry in the notes file
2203 (if org-ref-bibliography-notes
2204 (find-file-other-window org-ref-bibliography-notes)
2205 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2207 (goto-char (point-min))
2208 ;; put new entry in notes if we don't find it.
2209 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2210 (funcall org-ref-open-notes-function)
2211 ;; no entry found, so add one
2212 (insert (org-ref-reftex-format-citation entry (concat "\n" org-ref-note-title-format)))
2213 (insert (org-ref-reftex-format-citation
2227 (format "[[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2228 key org-ref-pdf-directory key))))
2231 (defun org-ref-open-notes-from-reftex ()
2232 "Call reftex, and open notes for selected entry."
2234 (let ((bibtex-key )))
2236 ;; now look for entry in the notes file
2237 (if org-ref-bibliography-notes
2238 (find-file-other-window org-ref-bibliography-notes)
2239 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2241 (goto-char (point-min))
2243 (re-search-forward (format
2245 (cl-first (reftex-citation t)) nil 'end))
2246 (funcall org-ref-open-notes-function))
2248 ;; ** Open bibtex entry in browser
2249 (defun org-ref-open-in-browser ()
2250 "Open the bibtex entry at point in a browser using the url field or doi field."
2253 (bibtex-beginning-of-entry)
2255 (let ((url (bibtex-autokey-get-field "url")))
2260 (let ((doi (bibtex-autokey-get-field "doi")))
2262 (if (string-match "^http" doi)
2264 (browse-url (format "http://dx.doi.org/%s" doi)))
2266 (message "No url or doi found"))))
2268 ;; ** upload entry to citeulike
2270 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2271 "With point in a bibtex entry get bibtex string and submit to citeulike.
2273 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2275 (message "uploading to citeulike")
2277 (bibtex-narrow-to-entry)
2278 (let ((startpos (point-min))
2279 (endpos (point-max))
2280 (bibtex-string (buffer-string))
2281 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2282 (with-temp-buffer (insert bibtex-string)
2283 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2285 ;; ** Build a pdf of the bibtex file
2286 (defun org-ref-build-full-bibliography ()
2287 "Build pdf of all bibtex entries, and open it."
2289 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2290 (bib-base (file-name-sans-extension bibfile))
2291 (texfile (concat bib-base ".tex"))
2292 (pdffile (concat bib-base ".pdf")))
2295 (insert (format "\\documentclass[12pt]{article}
2296 \\usepackage[version=3]{mhchem}
2298 \\usepackage[numbers]{natbib}
2299 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2303 \\bibliographystyle{unsrtnat}
2305 \\end{document}" bib-base))
2307 (shell-command (concat "pdflatex " bib-base))
2308 (shell-command (concat "bibtex " bib-base))
2309 (shell-command (concat "pdflatex " bib-base))
2310 (shell-command (concat "pdflatex " bib-base))
2311 (kill-buffer texfile)
2312 (org-open-file pdffile)
2315 ;; ** Extract bibtex entries in org-file
2317 (defun org-ref-extract-bibtex-entries ()
2318 "Extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2320 If no bibliography is in the buffer the variable
2321 `reftex-default-bibliography' is used."
2323 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2324 (tempname (make-temp-file "extract-bib"))
2325 (contents (buffer-string))
2326 (cb (current-buffer))
2327 basename texfile bibfile results)
2329 ;; open tempfile and insert org-buffer contents
2330 (find-file tempname)
2332 (setq basename (file-name-sans-extension
2333 (file-name-nondirectory buffer-file-name))
2334 texfile (concat tempname ".tex")
2335 bibfile (concat tempname ".bib"))
2337 ;; see if we have a bibliography, and insert the default one if not.
2339 (goto-char (point-min))
2340 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2341 (insert (format "\nbibliography:%s"
2342 (mapconcat 'identity reftex-default-bibliography ",")))))
2345 ;; get a latex file and extract the references
2346 (org-latex-export-to-latex)
2349 (reftex-create-bibtex-file bibfile)
2351 ;; save results of the references
2352 (setq results (buffer-string))
2354 ;; kill buffers. these are named by basename, not full path
2355 (kill-buffer (concat basename ".bib"))
2356 (kill-buffer (concat basename ".tex"))
2357 (kill-buffer basename)
2359 (delete-file bibfile)
2360 (delete-file texfile)
2361 (delete-file tempname)
2363 ;; Now back to the original org buffer and insert the results
2364 (switch-to-buffer cb)
2365 (when (not (string= "" results))
2367 (goto-char (point-max))
2369 (org-insert-heading)
2370 (insert (format " Bibtex entries
2372 #+BEGIN_SRC text :tangle %s
2374 #+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2376 ;; ** Find bad citations
2379 (defun index (substring list)
2380 "Return the index of SUBSTRING in a LIST of strings."
2383 (dolist (arg list i)
2384 (if (string-match (concat "^" substring "$") arg)
2389 ;; return counter if found, otherwise return nil
2393 (defun org-ref-find-bad-citations ()
2394 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2396 Makes a new buffer with clickable links."
2398 ;; generate the list of bibtex-keys and cited keys
2399 (let* ((bibtex-files (org-ref-find-bibliography))
2400 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2401 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2402 (bad-citations '()))
2404 (org-element-map (org-element-parse-buffer) 'link
2406 (let ((plist (nth 1 link)))
2407 (when (-contains? org-ref-cite-types (plist-get plist :type))
2408 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)))
2409 (when (not (index key bibtex-keys))
2414 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2417 (plist-get plist :begin)))))
2419 ;; set with-affilates to t to get citations in a caption
2424 (switch-to-buffer-other-window "*Missing citations*")
2427 (insert "* List of bad cite links\n")
2428 (insert (mapconcat 'identity bad-citations ""))
2429 ;(setq buffer-read-only t)
2430 (use-local-map (copy-keymap org-mode-map))
2431 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2433 (when (get-buffer "*Missing citations*")
2434 (kill-buffer "*Missing citations*"))
2435 (message "No bad cite links found"))))
2437 ;; ** helm interface to bad citations, labels, refs and files in orgfile
2438 (defun org-ref-bad-cite-candidates ()
2439 "Return a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2440 (let* ((cp (point)) ; save to return to later
2441 (bibtex-files (org-ref-find-bibliography))
2442 (bibtex-file-path (mapconcat
2444 (file-name-directory (file-truename x)))
2446 (bibtex-keys (mapcar (lambda (x) (car x))
2447 (bibtex-global-key-alist)))
2448 (bad-citations '()))
2450 (org-element-map (org-element-parse-buffer) 'link
2452 (let ((plist (nth 1 link)))
2453 (when (-contains? org-ref-cite-types (plist-get plist :type))
2454 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)) )
2455 (when (not (index key bibtex-keys))
2456 (goto-char (plist-get plist :begin))
2457 (re-search-forward key)
2458 (push (cons key (point-marker)) bad-citations)))
2460 ;; add with-affiliates to get cites in caption
2466 (defun org-ref-bad-ref-candidates ()
2467 "Return a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2468 ;; first get a list of legitimate labels
2470 (labels (org-ref-get-labels))
2472 ;; now loop over ref links
2473 (goto-char (point-min))
2474 (org-element-map (org-element-parse-buffer) 'link
2476 (let ((plist (nth 1 link)))
2477 (when (or (equal (plist-get plist ':type) "ref")
2478 (equal (plist-get plist ':type) "eqref")
2479 (equal (plist-get plist ':type) "pageref")
2480 (equal (plist-get plist ':type) "nameref"))
2481 (unless (-contains? labels (plist-get plist :path))
2482 (goto-char (plist-get plist :begin))
2485 (cons (plist-get plist :path)
2486 (point-marker))))))))
2491 (defun org-ref-bad-label-candidates ()
2492 "Return a list of labels where label is multiply defined."
2493 (let ((labels (org-ref-get-labels))
2494 (multiple-labels '()))
2495 (when (not (= (length labels)
2496 (length (-uniq labels))))
2497 (dolist (label labels)
2498 (when (> (-count (lambda (a)
2501 ;; this is a multiply defined label.
2503 (goto-char (point-min))
2504 (while (re-search-forward
2505 (format "[^#+]label:%s\\s-" label) nil t)
2506 (push (cons label (point-marker)) multiple-labels))
2507 (goto-char (point-min))
2508 (while (re-search-forward
2509 (format "\\label{%s}\\s-?" label) nil t)
2510 (push (cons label (point-marker)) multiple-labels))
2512 (goto-char (point-min))
2513 (while (re-search-forward
2514 (format "^#\\+label:\\s-*%s" label) nil t)
2515 (push (cons label (point-marker)) multiple-labels))
2517 (goto-char (point-min))
2518 (while (re-search-forward
2519 (format "^#\\+tblname:\\s-*%s" label) nil t)
2520 (push (cons label (point-marker)) multiple-labels))
2524 (defun org-ref-bad-file-link-candidates ()
2525 "Return list of conses (link . marker) wehre the file in the link does not exist."
2526 (let* ((bad-files '()))
2527 (org-element-map (org-element-parse-buffer) 'link
2529 (let ((type (org-element-property :type link)))
2530 (when (or (string= "file" type)
2531 (string= "attachfile" type))
2532 (unless (file-exists-p (org-element-property :path link))
2533 (add-to-list 'bad-files
2534 (cons (org-element-property :path link)
2537 (org-element-property :begin link))
2538 (point-marker)))))))))
2539 ;; Let us also check \attachfile{fname}
2541 (goto-char (point-min))
2542 (while (re-search-forward "\\attachfile{\\(.*\\)}" nil t)
2543 (unless (file-exists-p (match-string 1))
2544 (add-to-list 'bad-files (cons (match-string 1) (point-marker))))))
2549 "Opens a helm interface to actions for org-ref.
2550 Shows bad citations, ref links and labels"
2552 (let ((cb (current-buffer))
2553 (bad-citations (org-ref-bad-cite-candidates))
2554 (bad-refs (org-ref-bad-ref-candidates))
2555 (bad-labels (org-ref-bad-label-candidates))
2556 (bad-files (org-ref-bad-file-link-candidates)))
2558 (helm :sources `(((name . "Bad citations")
2559 (candidates . ,bad-citations)
2560 (action . (lambda (marker)
2561 (switch-to-buffer (marker-buffer marker))
2562 (goto-char marker))))
2564 ((name . "Bad Labels")
2565 (candidates . ,bad-labels)
2566 (action . (lambda (marker)
2567 (switch-to-buffer (marker-buffer marker))
2568 (goto-char marker))))
2570 ((name . "Bad ref links")
2571 (candidates . ,bad-refs)
2572 (action . (lambda (marker)
2573 (switch-to-buffer (marker-buffer marker))
2574 (goto-char marker))))
2576 ((name . "Bad file links")
2577 (candidates . ,bad-files)
2579 (switch-to-buffer (marker-buffer marker))
2580 (goto-char marker)))
2582 ((name . "Utilities")
2583 (candidates . (("Check buffer again" . org-ref)
2584 ("Insert citation" . helm-bibtex)
2585 ("Insert label link" . org-ref-helm-insert-label-link)
2586 ("Insert ref link" . org-ref-helm-insert-ref-link)
2587 ("List of figures" . org-ref-list-of-figures)
2588 ("List of tables" . org-ref-list-of-tables)
2589 ("Table of contents" . nil)
2591 (action . (lambda (x)
2592 (switch-to-buffer ,cb)
2595 ((name . "Export functions")
2596 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2597 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2598 ("Export to pdf and open" . (lambda ()
2599 (org-open-file (org-latex-export-to-pdf))))
2600 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2601 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2604 (action . (lambda (x)
2605 (switch-to-buffer ,cb)
2608 ;; ** Find non-ascii charaters
2609 (defun org-ref-find-non-ascii-characters ()
2610 "Find non-ascii characters in the buffer. Useful for cleaning up bibtex files."
2612 (occur "[^[:ascii:]]"))
2614 ;; ** Sort fields in a bibtex entry
2616 (defun org-ref-sort-bibtex-entry ()
2617 "Sort fields of entry in standard order and downcase them."
2619 (bibtex-beginning-of-entry)
2620 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2621 (entry (bibtex-parse-entry))
2624 (type (cdr (assoc "=type=" entry)))
2625 (key (cdr (assoc "=key=" entry))))
2627 ;; these are the fields we want to order that are in this entry
2628 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2629 ;; we do not want to reenter these fields
2630 (setq entry-fields (remove "=key=" entry-fields))
2631 (setq entry-fields (remove "=type=" entry-fields))
2633 ;;these are the other fields in the entry
2634 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2637 ;; right now we only resort articles
2638 ((string= (downcase type) "article")
2641 (concat "@article{" key ",\n"
2644 (when (member field entry-fields)
2645 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2648 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2650 (bibtex-find-entry key)
2652 (bibtex-clean-entry)
2655 ;; ** Clean a bibtex entry
2656 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2657 "clean and replace the key in a bibtex function. When keep-key is t, do not replace it. You can use a prefix to specify the key should be kept"
2659 (bibtex-beginning-of-entry)
2661 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2662 (unless (string-match ",$" (thing-at-point 'line))
2666 ;; check for empty pages, and put eid or article id in its place
2667 (let ((entry (bibtex-parse-entry))
2668 (pages (bibtex-autokey-get-field "pages"))
2669 (year (bibtex-autokey-get-field "year"))
2670 (doi (bibtex-autokey-get-field "doi"))
2671 ;; The Journal of Chemical Physics uses eid
2672 (eid (bibtex-autokey-get-field "eid")))
2674 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2675 ;; but we only want the doi.
2676 (when (string-match "^http://dx.doi.org/" doi)
2677 (bibtex-beginning-of-entry)
2678 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2680 (bibtex-make-field "doi")
2682 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2684 ;; asap articles often set year to 0, which messes up key
2685 ;; generation. fix that.
2686 (when (string= "0" year)
2687 (bibtex-beginning-of-entry)
2688 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2690 (bibtex-make-field "year")
2692 (insert (read-string "Enter year: ")))
2694 ;; fix pages if they are empty if there is an eid to put there.
2695 (when (string= "-" pages)
2697 (bibtex-beginning-of-entry)
2698 ;; this seems like a clunky way to set the pages field.But I
2699 ;; cannot find a better way.
2700 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2702 (bibtex-make-field "pages")
2706 ;; replace naked & with \&
2708 (bibtex-narrow-to-entry)
2709 (bibtex-beginning-of-entry)
2710 (message "checking &")
2711 (replace-regexp " & " " \\\\& ")
2714 ;; generate a key, and if it duplicates an existing key, edit it.
2716 (let ((key (bibtex-generate-autokey)))
2718 ;; first we delete the existing key
2719 (bibtex-beginning-of-entry)
2720 (re-search-forward bibtex-entry-maybe-empty-head)
2721 (if (match-beginning bibtex-key-in-head)
2722 (delete-region (match-beginning bibtex-key-in-head)
2723 (match-end bibtex-key-in-head)))
2724 ;; check if the key is in the buffer
2725 (when (save-excursion
2726 (bibtex-search-entry key))
2728 (bibtex-search-entry key)
2729 (bibtex-copy-entry-as-kill)
2730 (switch-to-buffer-other-window "*duplicate entry*")
2732 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2735 (kill-new key))) ;; save key for pasting
2737 ;; run hooks. each of these operates on the entry with no arguments.
2738 ;; this did not work like i thought, it gives a symbolp error.
2739 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2744 org-ref-clean-bibtex-entry-hook)
2746 ;; sort fields within entry
2747 (org-ref-sort-bibtex-entry)
2748 ;; check for non-ascii characters
2749 (occur "[^[:ascii:]]")
2752 (defun org-ref-get-citation-year (key)
2753 "Get the year of an entry with KEY. Return year as a string."
2754 (let* ((results (org-ref-get-bibtex-key-and-file key))
2755 (bibfile (cdr results)))
2757 (insert-file-contents bibfile)
2758 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
2759 (bibtex-search-entry key nil 0)
2760 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2763 ;; ** Sort cite in cite link
2764 (defun org-ref-sort-citation-link ()
2765 "Replace link at point with sorted link by year."
2767 (let* ((object (org-element-context))
2768 (type (org-element-property :type object))
2769 (begin (org-element-property :begin object))
2770 (end (org-element-property :end object))
2771 (link-string (org-element-property :path object))
2773 (setq keys (org-ref-split-and-strip-string link-string))
2774 (setq years (mapcar 'org-ref-get-citation-year keys))
2775 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2776 (setq data (cl-sort data (lambda (x y) (< (string-to-number (car x)) (string-to-number (car y))))))
2777 ;; now get the keys separated by commas
2778 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2779 ;; and replace the link with the sorted keys
2780 (cl--set-buffer-substring begin end (concat type ":" keys))))
2782 ;; ** Shift-arrow sorting of keys in a cite link
2784 (defun org-ref-swap-keys (i j keys)
2785 "Swap the KEYS in a list with index I and J."
2786 (let ((tempi (nth i keys)))
2787 (setf (nth i keys) (nth j keys))
2788 (setf (nth j keys) tempi))
2792 (defun org-ref-swap-citation-link (direction)
2793 "Move citation at point in DIRECTION +1 is to the right, -1 to the left."
2795 (let* ((object (org-element-context))
2796 (type (org-element-property :type object))
2797 (begin (org-element-property :begin object))
2798 (end (org-element-property :end object))
2799 (link-string (org-element-property :path object))
2801 ;; We only want this to work on citation links
2802 (when (-contains? org-ref-cite-types type)
2803 (setq key (org-ref-get-bibtex-key-under-cursor))
2804 (setq keys (org-ref-split-and-strip-string link-string))
2805 (setq i (index key keys)) ;; defined in org-ref
2806 (if (> direction 0) ;; shift right
2807 (org-ref-swap-keys i (+ i 1) keys)
2808 (org-ref-swap-keys i (- i 1) keys))
2809 (setq keys (mapconcat 'identity keys ","))
2810 ;; and replace the link with the sorted keys
2811 (cl--set-buffer-substring
2815 ;; It seems the space at the end can get consumed, so we see if there
2816 ;; is a space, and add it if so. Sometimes there is a comma or period,
2817 ;; then we do not want a space.
2821 (looking-back " ")) " ")))
2822 ;; now go forward to key so we can move with the key
2823 (re-search-forward key)
2824 (goto-char (match-beginning 0)))))
2826 ;; add hooks to make it work
2827 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2828 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2830 ;; ** context around org-ref links
2831 (defun org-ref-get-label-context (label)
2832 "Return a string of context around a LABEL."
2835 (goto-char (point-min))
2836 (when (re-search-forward
2837 (format "label:%s\\b" label) nil t)
2838 (throw 'result (buffer-substring
2847 (goto-char (point-min))
2848 (when (re-search-forward
2849 (format "\\label{%s}" label) nil t)
2850 (throw 'result (buffer-substring
2859 (goto-char (point-min))
2860 (when (re-search-forward
2861 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2862 (throw 'result (buffer-substring
2871 (goto-char (point-min))
2872 (when (re-search-forward
2873 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2874 (throw 'result (buffer-substring
2882 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
2885 (defun org-ref-link-message ()
2886 "Print a minibuffer message about the link that point is on."
2890 (when (eq major-mode 'org-mode)
2891 (let* ((object (org-element-context))
2892 (type (org-element-property :type object)))
2896 ((-contains? org-ref-cite-types type)
2897 (message (org-ref-get-citation-string-at-point)))
2899 ;; message some context about the label we are referring to
2900 ((string= type "ref")
2901 (message "%scount: %s"
2902 (org-ref-get-label-context
2903 (org-element-property :path object))
2904 (org-ref-count-labels
2905 (org-element-property :path object))))
2907 ((string= type "eqref")
2908 (message "%scount: %s"
2909 (org-ref-get-label-context
2910 (org-element-property :path object))
2911 (org-ref-count-labels
2912 (org-element-property :path object))))
2914 ;; message the count
2915 ((string= type "label")
2916 (let ((count (org-ref-count-labels
2917 (org-element-property :path object))))
2918 ;; get plurality on occurrence correct
2920 (number-to-string count)
2922 (when (or (= count 0)
2926 ((string= type "custom-id")
2928 (org-open-link-from-string
2929 (format "[[#%s]]" (org-element-property :path object)))
2930 (message "%s" (org-get-heading))))
2932 ;; check if the bibliography files exist.
2933 ((string= type "bibliography")
2935 ;; object is the link you clicked on
2936 (object (org-element-context))
2937 (link-string (org-element-property :path object))
2938 (link-string-beginning)
2941 (goto-char (org-element-property :begin object))
2942 (search-forward link-string nil nil 1)
2943 (setq link-string-beginning (match-beginning 0))
2944 (setq link-string-end (match-end 0)))
2946 ;; make sure we are in link and not before the :
2947 (when (> link-string-beginning (point))
2948 (goto-char link-string-beginning))
2950 (let (key-beginning key-end)
2951 ;; now if we have comma separated bibliographies
2952 ;; we find the one clicked on. we want to
2953 ;; search forward to next comma from point
2955 (if (search-forward "," link-string-end 1 1)
2956 (setq key-end (- (match-end 0) 1)) ; we found a match
2957 (setq key-end (point)))) ; no comma found so take the point
2959 ;; and backward to previous comma from point
2961 (if (search-backward "," link-string-beginning 1 1)
2962 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
2963 (setq key-beginning (point)))) ; no match found
2964 ;; save the key we clicked on.
2966 (org-ref-strip-string
2967 (buffer-substring key-beginning key-end)))
2968 (if (file-exists-p bibfile)
2969 (message "%s exists." bibfile)
2970 (message "!!! %s NOT FOUND !!!" bibfile)))))))))))
2973 (defalias 'oro 'org-ref-open-citation-at-point)
2974 (defalias 'orc 'org-ref-citation-at-point)
2975 (defalias 'orp 'org-ref-open-pdf-at-point)
2976 (defalias 'oru 'org-ref-open-url-at-point)
2977 (defalias 'orn 'org-ref-open-notes-at-point)
2978 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2980 (defalias 'orib 'org-ref-insert-bibliography-link)
2981 (defalias 'oric 'org-ref-insert-cite-link)
2982 (defalias 'orir 'org-ref-insert-ref-link)
2983 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2985 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2987 ;; * Helm bibtex setup
2989 (setq helm-bibtex-additional-search-fields '(keywords))
2991 (defun helm-bibtex-candidates-formatter (candidates source)
2992 "Formats BibTeX entries for display in results list.
2993 Argument CANDIDATES helm candidates.
2994 Argument SOURCE the helm source."
2996 with width = (with-helm-window (helm-bibtex-window-width))
2997 for entry in candidates
2998 for entry = (cdr entry)
2999 for entry-key = (helm-bibtex-get-value "=key=" entry)
3000 if (assoc-string "author" entry 'case-fold)
3001 for fields = '("author" "title" "year" "=has-pdf=" "=has-note=" "=type=")
3003 for fields = '("editor" "title" "year" "=has-pdf=" "=has-note=" "=type=")
3004 for fields = (--map (helm-bibtex-clean-string
3005 (helm-bibtex-get-value it entry " "))
3007 for fields = (-update-at 0 'helm-bibtex-shorten-authors fields)
3008 for fields = (append fields
3009 (list (or (helm-bibtex-get-value "keywords" entry)
3012 (cons (s-format "$0 $1 $2 $3 $4$5 $6" 'elt
3013 (-zip-with (lambda (f w) (truncate-string-to-width f w 0 ?\s))
3014 fields (list 36 (- width 85) 4 1 1 7 7)))
3017 ;; * org-ref bibtex keywords
3018 ;; adapted from bibtex-utils.el
3019 ;; these are candidates for selecting keywords/tags
3020 (defun org-ref-bibtex-keywords ()
3021 "Get keywords defined in current bibtex file.
3022 These are in the keywords field, and are comma or semicolon separated."
3024 (goto-char (point-min))
3025 (let (keywords kstring)
3026 (while (re-search-forward "^\\s-*keywords.*{\\([^}]+\\)}" nil t)
3027 ;; TWS - remove newlines/multiple spaces:
3028 (setq kstring (replace-regexp-in-string "[ \t\n]+" " " (match-string 1)))
3031 (add-to-list 'keywords v t))
3032 (split-string kstring "\\(,\\|;\\)[ \n]*\\|{\\|}" t)))
3036 (defun org-ref-set-bibtex-keywords (keywords &optional arg)
3037 "Add KEYWORDS to a bibtex entry.
3038 If KEYWORDS is a list, it is converted to a comma-separated
3039 string. The KEYWORDS are added to the beginning of the
3040 field. Otherwise KEYWORDS should be a string of comma-separate
3041 keywords. Optional argument ARG prefix arg to replace keywords."
3042 (interactive "sKeywords: \nP")
3047 (if (listp keywords)
3048 (mapconcat 'identity keywords ", ")
3050 ;; else concatentate
3052 (if (listp keywords)
3053 (mapconcat 'identity keywords ", ")
3055 (when (not (string= "" (bibtex-autokey-get-field "keywords")))
3056 (concat ", " (bibtex-autokey-get-field "keywords"))))))
3060 (defun helm-tag-bibtex-entry ()
3061 "Helm interface to add keywords to a bibtex entry.
3062 Run this with the point in a bibtex entry."
3064 (let ((keyword-source `((name . "Existing keywords")
3065 (candidates . ,(org-ref-bibtex-keywords))
3066 (action . (lambda (candidate)
3067 (org-ref-set-bibtex-keywords
3070 (helm-marked-candidates)
3072 (fallback-source `((name . "Add new keywords")
3074 (action . (lambda (candidate)
3075 (org-ref-set-bibtex-keywords helm-pattern)
3077 (helm :sources '(keyword-source fallback-source))))
3079 (defun helm-bibtex-show-entry (key)
3080 "Show the entry for KEY in the BibTeX file.
3081 The original function in `helm-bibtex' has a bug where it finds the
3082 first key that partially matches. This version avoids that."
3084 (dolist (bibtex-file (if (listp helm-bibtex-bibliography)
3085 helm-bibtex-bibliography
3086 (list helm-bibtex-bibliography)))
3087 (let ((buf (helm-bibtex-buffer-visiting bibtex-file))
3089 (find-file bibtex-file)
3091 (lambda (key start end)
3092 (add-to-list 'entries (cons key start))))
3093 (if (assoc key entries)
3095 (goto-char (cdr (assoc key entries)))
3100 (defun org-ref-helm-tag-entries (candidates)
3101 "Set tags on selected bibtex entries from `helm-bibtex'.
3102 User is prompted for tags. This function is called from `helm-bibtex'.
3103 Argument CANDIDATES helm candidates."
3105 (let ((keywords (read-string "Keywords (comma separated): ")))
3106 (cl-loop for key in (helm-marked-candidates)
3108 (save-window-excursion
3109 (helm-bibtex-show-entry key)
3114 ", " (bibtex-autokey-get-field "keywords")))
3117 (setq helm-source-bibtex
3118 '((name . "BibTeX entries")
3119 (init . helm-bibtex-init)
3120 (candidates . helm-bibtex-candidates)
3121 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3122 (action . (("Insert citation" . helm-bibtex-insert-citation)
3123 ("Show entry" . helm-bibtex-show-entry)
3124 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3125 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3126 ("Insert formatted reference" . helm-bibtex-insert-reference)
3127 ("Insert BibTeX key" . helm-bibtex-insert-key)
3128 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3129 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3130 ("Edit notes" . helm-bibtex-edit-notes)
3131 ("Add keywords to entries" . org-ref-helm-tag-entries)
3134 (defun helm-bibtex-format-org-ref (keys)
3135 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3136 Technically, this function should return a string that is inserted by helm. This function does the insertion and gives helm an empty string to insert. This lets us handle appending to a link properly.
3138 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3140 C-u C-u will change the key at point to the selected keys."
3141 (let* ((object (org-element-context))
3142 (last-char (save-excursion
3143 (when (org-element-property :end object)
3144 (goto-char (org-element-property :end object))
3147 (if (looking-at " ")
3151 ;; case where we are in a link
3152 ((and (equal (org-element-type object) 'link)
3155 (org-element-property :type object)))
3157 ;; no prefix. append keys
3158 ((equal helm-current-prefix-arg nil)
3159 (goto-char (org-element-property :end object))
3160 (while (looking-back " ") (backward-char))
3161 (insert (concat "," (mapconcat 'identity keys ","))))
3162 ;; double prefix, replace key at point
3163 ((equal helm-current-prefix-arg '(16))
3164 (setf (buffer-substring
3165 (org-element-property :begin object)
3166 (org-element-property :end object))
3168 (replace-regexp-in-string
3169 (car (org-ref-get-bibtex-key-and-file)) ; key
3170 (mapconcat 'identity keys ",") ; new keys
3171 (org-element-property :raw-link object))
3172 ;; replace space at end to avoid collapsing into next word.
3174 ;; and we want to go to the end of the new link
3176 (org-element-property :end (org-element-context))))
3178 (message "Not found"))))
3180 ;; We are next to a link, and we want to append
3181 ;; next to a link means one character back is on a link.
3183 (unless (bobp) (backward-char))
3184 (and (equal (org-element-type (org-element-context)) 'link)
3187 (org-element-property :type (org-element-context)))))
3188 (while (looking-back " ") (backward-char))
3189 (insert (concat "," (mapconcat 'identity keys ","))))
3191 ;; insert fresh link
3193 ;;(message-box "fresh link")
3195 (concat (if (equal helm-current-prefix-arg '(4))
3196 (helm :sources `((name . "link types")
3197 (candidates . ,org-ref-cite-types)
3198 (action . (lambda (x) x))))
3199 org-ref-default-citation-link)
3201 (s-join "," keys))))))
3202 ;; return empty string for helm
3205 (setq helm-bibtex-format-citation-functions
3206 '((org-mode . helm-bibtex-format-org-ref)))
3209 (defun org-ref-helm-insert-cite-link (arg)
3210 "org-ref function to use helm-bibtex to insert a citation link.
3211 With one prefix arg, insert a ref link.
3212 With two prefix args, insert a label link."
3216 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3219 (org-ref-helm-insert-ref-link))
3221 (org-ref-helm-insert-label-link))))
3224 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3225 (setq helm-bibtex-fallback-options
3226 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3228 (setq helm-bibtex-fallback-options
3231 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3232 helm-bibtex-fallback-options))
3234 (setq helm-bibtex-fallback-options
3235 (-insert-at 1 '("WOS" . "http://gateway.webofknowledge.com/gateway/Gateway.cgi?topic=%s&GWVersion=2&SrcApp=WEB&SrcAuth=HSB&DestApp=UA&DestLinkType=GeneralSearchSummary") helm-bibtex-fallback-options))
3237 (defun org-ref-get-citation-string-at-point ()
3238 "Get a string of a formatted citation."
3239 (let* ((results (org-ref-get-bibtex-key-and-file))
3241 (bibfile (cdr results)))
3245 (insert-file-contents bibfile)
3246 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3247 (bibtex-search-entry key)
3248 (org-ref-bib-citation)))
3249 "!!! No entry found !!!" )))
3252 (defun org-ref-cite-candidates ()
3253 "Generate the list of possible candidates for click actions on a cite link.
3254 Checks for pdf and doi, and add appropriate functions."
3255 (let* ((results (org-ref-get-bibtex-key-and-file))
3257 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3258 (bibfile (cdr results))
3259 (url (save-excursion
3261 (insert-file-contents bibfile)
3262 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3263 (bibtex-search-entry key)
3264 (bibtex-autokey-get-field "url"))))
3265 (doi (save-excursion
3267 (insert-file-contents bibfile)
3268 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3269 (bibtex-search-entry key)
3270 ;; I like this better than bibtex-url which does not always find
3272 (bibtex-autokey-get-field "doi"))))
3273 (candidates `(("Quit" . org-ref-citation-at-point)
3274 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3275 ;; for some reason, when there is no doi or url, they are returned as "". I
3276 ;; prefer nil so we correct this here.
3277 (when (string= doi "") (setq doi nil))
3278 (when (string= url "") (setq url nil))
3280 ;; Conditional pdf functions
3281 (if (file-exists-p pdf-file)
3284 '("Open pdf" . org-ref-open-pdf-at-point)
3288 '("Try to get pdf" . (lambda ()
3289 (save-window-excursion
3290 (org-ref-open-citation-at-point)
3291 (bibtex-beginning-of-entry)
3292 (doi-utils-get-bibtex-entry-pdf))))
3298 '("Open notes" . org-ref-open-notes-at-point)
3301 ;; conditional url and doi functions
3305 '("Open in browser" . org-ref-open-url-at-point)
3310 (add-to-list 'candidates x t))
3311 `(("WOS" . org-ref-wos-at-point)
3312 ("Related articles in WOS" . org-ref-wos-related-at-point)
3313 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3314 ("Google Scholar" . org-ref-google-scholar-at-point)
3315 ("Pubmed" . org-ref-pubmed-at-point)
3316 ("Crossref" . org-ref-crossref-at-point)
3321 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3326 '("Copy key to clipboard" . (lambda ()
3328 (car (org-ref-get-bibtex-key-and-file)))))
3333 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3338 '("Email bibtex entry and pdf" . (lambda ()
3340 (org-ref-open-citation-at-point)
3341 (email-bibtex-entry))))
3343 ;; finally return a numbered list of the candidates
3344 (cl-loop for i from 0
3345 for cell in candidates
3346 collect (cons (format "%2s. %s" i (car cell))
3350 (defvar org-ref-helm-user-candidates '()
3351 "List of user-defined candidates to act when clicking on a cite link.
3352 This is a list of cons cells '((\"description\" . action)). The action function should not take an argument, and should assume point is on the cite key of interest.")
3354 ;; example of adding your own function
3356 'org-ref-helm-user-candidates
3357 '("Example" . (lambda () (message-box "You did it!")))
3361 (defun org-ref-cite-click-helm (key)
3362 "Open helm for actions on a cite link.
3365 1. get name and candidates before entering helm because we need
3368 2. switch back to the org buffer before evaluating the
3369 action. most of them need the point and buffer.
3371 KEY is returned for the selected item(s) in helm."
3373 (let ((name (org-ref-get-citation-string-at-point))
3374 (candidates (org-ref-cite-candidates))
3375 (cb (current-buffer)))
3377 (helm :sources `(((name . ,name)
3378 (candidates . ,candidates)
3379 (action . (lambda (f)
3380 (switch-to-buffer cb)
3382 ((name . "User functions")
3383 (candidates . ,org-ref-helm-user-candidates)
3384 (action . (lambda (f)
3385 (switch-to-buffer cb)
3389 ;; * Hydra menus in org-ref
3391 (when (featurep 'hydra)
3393 (setq hydra-is-helpful t)
3395 (defhydra org-ref-cite-hydra (:color blue)
3397 _p_: Open pdf _w_: WOS _g_: Google Scholar _K_: Copy citation to clipboard
3398 _u_: Open url _r_: WOS related _P_: Pubmed _k_: Copy key to clipboard
3399 _n_: Open notes _c_: WOS citing _C_: Crossref _f_: Copy bibtex entry to file
3400 _o_: Open entry _e_: Email entry and pdf
3402 ("o" org-ref-open-citation-at-point nil)
3403 ("p" org-ref-open-pdf-at-point nil)
3404 ("n" org-ref-open-notes-at-point nil)
3405 ("u" org-ref-open-url-at-point nil)
3406 ("w" org-ref-wos-at-point nil)
3407 ("r" org-ref-wos-related-at-point nil)
3408 ("c" org-ref-wos-citing-at-point nil)
3409 ("g" org-ref-google-scholar-at-point nil)
3410 ("P" org-ref-pubmed-at-point nil)
3411 ("C" org-ref-crossref-at-point nil)
3412 ("K" org-ref-copy-entry-as-summary nil)
3415 (car (org-ref-get-bibtex-key-and-file)))) nil)
3416 ("f" org-ref-copy-entry-at-point-to-file nil)
3418 ("e" (save-excursion
3419 (org-ref-open-citation-at-point)
3420 (email-bibtex-entry)) nil)))
3423 (defun org-ref-help ()
3424 "Open the org-ref manual."
3426 (find-file (expand-file-name
3428 (file-name-directory
3429 (find-library-name "org-ref")))))
3432 (defun org-ref-org-menu ()
3433 "Add org-ref menu to the Org menu."
3437 '( ["Insert citation" org-ref-helm-insert-cite-link]
3438 ["Insert ref" org-ref-helm-insert-ref-link]
3439 ["Insert label" org-ref-helm-insert-label-link]
3441 ["List of figures" org-ref-list-of-figures]
3442 ["List of tables" org-ref-list-of-tables]
3443 ["Extract bibtex entries" org-ref-extract-bibtex-entries]
3444 ["Check org-file" org-ref]
3446 ["Help" org-ref-help]
3447 ["Customize org-ref" (customize-group 'org-ref)])
3450 (easy-menu-change '("Org") "--" nil "Show/Hide"))
3452 (add-hook 'org-mode-hook 'org-ref-org-menu)
3457 ;;; org-ref.el ends here