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 (org-ref-reftex-get-bib-field "title" entry)))
488 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
489 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
492 (setq b (match-beginning 2) e (match-end 2))
493 (setq b (match-beginning 3) e (match-end 3)))
494 (setq format (concat (substring format 0 b) rpl (substring format e)))))
495 (while (string-match "%%" format)
496 (setq format (replace-match "%" t t format)))
497 (while (string-match "[ ,.;:]*%<" format)
498 (setq format (replace-match "" t t format)))
499 ;; also replace carriage returns, tabs, and multiple whitespaces
502 (defun org-ref-get-bibtex-entry-citation (key)
503 "Return a string for the bibliography entry corresponding to KEY.
504 Format according to the type in `org-ref-bibliography-entry-format'."
506 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
507 (file) (entry) (bibtex-entry) (entry-type) (format))
509 (setq file (catch 'result
510 (cl-loop for file in org-ref-bibliography-files do
511 (if (org-ref-key-in-file-p key (file-truename file))
513 (message "%s not found in %s"
514 key (file-truename file))))))
517 (insert-file-contents file)
518 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
519 (bibtex-search-entry key nil 0)
520 (setq bibtex-entry (bibtex-parse-entry))
521 ;; downcase field names so they work in the format-citation code
522 (dolist (cons-cell bibtex-entry)
523 (setf (car cons-cell) (downcase (car cons-cell))))
524 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
525 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
527 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
528 ;; if no format, we use the bibtex entry itself as a fallback
530 (bibtex-narrow-to-entry)
531 (setq entry (buffer-string)))))
534 (defun org-ref-get-bibtex-keys ()
535 "Return a list of unique keys in the buffer."
537 (org-element-map (org-element-parse-buffer) 'link
539 (let ((plist (nth 1 link)))
540 (when (-contains? org-ref-cite-types (plist-get plist ':type))
543 (org-ref-split-and-strip-string (plist-get plist ':path)))
544 (when (not (-contains? keys key))
545 (setq keys (append keys (list key))))))))
546 ;; set with-affiliated to get keys in captions
548 ;; Sort keys alphabetically
549 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
552 (defun org-ref-get-bibtex-entry-html (key)
553 "Return an html string for the bibliography entry corresponding to KEY."
555 (setq output (org-ref-get-bibtex-entry-citation key))
557 (setq output (replace-regexp-in-string "\\\\&" "&" output))
558 ;; hack to replace {} around text
559 (setq output (replace-regexp-in-string "{" "" output))
560 (setq output (replace-regexp-in-string "}" "" output))
561 ;; get rid of empty parens
562 (setq output (replace-regexp-in-string "()" "" output))
563 ;; get rid of empty link and doi
564 (setq output (replace-regexp-in-string " <a href=\"\">link</a>\\." "" output))
565 ;; change double dash to single dash
566 (setq output (replace-regexp-in-string "--" "-" output))
567 (setq output (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" output))
568 (format "<li><a id=\"%s\">[%s] %s</a></li>"
571 (defun org-ref-get-html-bibliography ()
572 "Create an html bibliography when there are keys."
573 (let ((keys (org-ref-get-bibtex-keys)))
575 (concat "<h1>Bibliography</h1>
577 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
580 (defun org-ref-get-bibtex-entry-org (key)
581 "Return an org string for the bibliography entry corresponding to KEY."
582 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
583 (file) (entry) (bibtex-entry) (entry-type) (format))
585 (setq file (catch 'result
586 (cl-loop for file in org-ref-bibliography-files do
587 (if (org-ref-key-in-file-p key (file-truename file))
589 (message "%s not found in %s" key (file-truename file))))))
592 (insert-file-contents file)
593 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
594 (bibtex-search-entry key nil 0)
595 (setq entry (bibtex-parse-entry))
600 " (org-ref-reftex-get-bib-field "author" entry)
601 (org-ref-reftex-get-bib-field "title" entry)
602 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
603 (mapconcat (lambda (element) (format " :%s: %s"
604 (upcase (car element))
609 (defun org-ref-get-org-bibliography ()
610 "Create an org bibliography when there are keys."
611 (let ((keys (org-ref-get-bibtex-keys)))
613 (concat "* Bibliography
615 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
618 (defun org-ref-get-bibtex-entry-ascii (key)
619 "Return an ascii string for the bibliography entry corresponding to KEY."
621 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
623 (defun org-ref-get-ascii-bibliography ()
624 "Create an html bibliography when there are keys."
625 (let ((keys (org-ref-get-bibtex-keys)))
631 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
635 ;; ** bibliography and bibliographystyle
636 (org-add-link-type "bibliography"
637 ;; this code is run on clicking. The bibliography
638 ;; may contain multiple files. this code finds the
639 ;; one you clicked on and opens it.
640 (lambda (link-string)
641 ;; get link-string boundaries we have to go to the
642 ;; beginning of the line, and then search forward
644 ;; object is the link you clicked on
645 (object (org-element-context))
646 (link-string-beginning)
650 (goto-char (org-element-property :begin object))
651 (search-forward link-string nil nil 1)
652 (setq link-string-beginning (match-beginning 0))
653 (setq link-string-end (match-end 0)))
655 ;; Make sure point is in the link-path.
656 (if (< cp link-string-beginning)
657 (goto-char link-string-beginning))
658 ;; We set the reftex-default-bibliography
659 ;; here. it should be a local variable only in
660 ;; the current buffer. We need this for using
661 ;; reftex to do citations.
662 (set (make-local-variable 'reftex-default-bibliography)
664 (org-element-property :path object) ","))
666 (let (key-beginning key-end)
667 ;; now if we have comma separated bibliographies
668 ;; we find the one clicked on. we want to
669 ;; search forward to next comma from point
671 (if (search-forward "," link-string-end 1 1)
673 (setq key-end (- (match-end 0) 1))
674 ;; no comma found so take the point
675 (setq key-end (point))))
676 ;; and backward to previous comma from point
678 (if (search-backward "," link-string-beginning 1 1)
680 (setq key-beginning (+ (match-beginning 0) 1))
681 (setq key-beginning (point)))) ; no match found
682 ;; save the key we clicked on.
683 (setq bibfile (org-ref-strip-string
684 (buffer-substring key-beginning key-end)))
685 ;; open file on click
686 (find-file bibfile))))
689 (lambda (keyword desc format)
691 ((eq format 'org) (org-ref-get-org-bibliography))
692 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
693 ((eq format 'html) (org-ref-get-html-bibliography))
695 ;; write out the latex bibliography command
696 (format "\\bibliography{%s}"
697 (replace-regexp-in-string
701 (mapcar 'expand-file-name
702 (split-string keyword ","))
705 (org-add-link-type "nobibliography"
706 ;; this code is run on clicking. The bibliography
707 ;; may contain multiple files. this code finds the
708 ;; one you clicked on and opens it.
709 (lambda (link-string)
710 ;; get link-string boundaries
711 ;; we have to go to the beginning of the line, and then search forward
714 ;; object is the link you clicked on
715 (object (org-element-context))
717 (link-string-beginning)
721 (goto-char (org-element-property :begin object))
722 (search-forward link-string nil nil 1)
723 (setq link-string-beginning (match-beginning 0))
724 (setq link-string-end (match-end 0)))
726 ;; We set the reftex-default-bibliography
727 ;; here. it should be a local variable only in
728 ;; the current buffer. We need this for using
729 ;; reftex to do citations.
730 (set (make-local-variable 'reftex-default-bibliography)
731 (split-string (org-element-property :path object) ","))
733 (let (key-beginning key-end)
734 ;; now if we have comma separated bibliographies
735 ;; we find the one clicked on. we want to
736 ;; search forward to next comma from point
738 (if (search-forward "," link-string-end 1 1)
739 (setq key-end (- (match-end 0) 1)) ; we found a match
740 (setq key-end (point)))) ; no comma found so take the point
741 ;; and backward to previous comma from point
743 (if (search-backward "," link-string-beginning 1 1)
744 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
745 (setq key-beginning (point)))) ; no match found
746 ;; save the key we clicked on.
747 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
748 (find-file bibfile)))) ; open file on click
751 (lambda (keyword desc format)
753 ((eq format 'org) (org-ref-get-org-bibliography))
754 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
755 ((eq format 'html) (org-ref-get-html-bibliography))
757 ;; write out the latex bibliography command
758 (format "\\nobibliography{%s}"
759 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
760 (mapcar 'expand-file-name
761 (split-string keyword ","))
764 (org-add-link-type "printbibliography"
765 (lambda (arg) (message "Nothing implemented for clicking here."))
766 (lambda (keyword desc format)
768 ((eq format 'org) (org-ref-get-org-bibliography))
769 ((eq format 'html) (org-ref-get-html-bibliography))
771 ;; write out the biblatex bibliography command
772 "\\printbibliography"))))
774 (org-add-link-type "bibliographystyle"
775 (lambda (arg) (message "Nothing implemented for clicking here."))
776 (lambda (keyword desc format)
779 ;; write out the latex bibliography command
780 (format "\\bibliographystyle{%s}" keyword))
781 ;; Other styles should not have an output for this
786 (defun org-bibliographystyle-complete-link (&optional arg)
787 "Completion function for bibliographystyle link.
789 (format "bibliographystyle:%s" (ido-completing-read
791 '("unsrt" "plain" "alpha"
793 ;; https://www.sharelatex.com/learn/Natbib_bibliography_styles
794 "dinat" "humannat" "plainnat"
795 "abbrnat" "unsrtnat" "rusnat"
799 (defun org-bibliography-complete-link (&optional arg)
800 "Completion function for bibliography link.
802 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
805 (defun org-ref-insert-bibliography-link ()
806 "Insert a bibliography with completion."
808 (insert (org-bibliography-complete-link)))
812 (org-add-link-type "addbibresource"
813 ;; this code is run on clicking. The addbibresource
814 ;; may contain multiple files. this code finds the
815 ;; one you clicked on and opens it.
816 (lambda (link-string)
817 ;; get link-string boundaries
818 ;; we have to go to the beginning of the line, and then search forward
821 ;; object is the link you clicked on
822 (object (org-element-context))
824 (link-string-beginning)
828 (goto-char (org-element-property :begin object))
829 (search-forward link-string nil nil 1)
830 (setq link-string-beginning (match-beginning 0))
831 (setq link-string-end (match-end 0)))
833 ;; We set the reftex-default-addbibresource
834 ;; here. it should be a local variable only in
835 ;; the current buffer. We need this for using
836 ;; reftex to do citations.
837 (set (make-local-variable 'reftex-default-addbibresource)
838 (split-string (org-element-property :path object) ","))
840 (let (key-beginning key-end)
841 ;; now if we have comma separated bibliographies
842 ;; we find the one clicked on. we want to
843 ;; search forward to next comma from point
845 (if (search-forward "," link-string-end 1 1)
846 (setq key-end (- (match-end 0) 1)) ; we found a match
847 (setq key-end (point)))) ; no comma found so take the point
848 ;; and backward to previous comma from point
850 (if (search-backward "," link-string-beginning 1 1)
851 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
852 (setq key-beginning (point)))) ; no match found
853 ;; save the key we clicked on.
854 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
855 (find-file bibfile)))) ; open file on click
858 (lambda (keyword desc format)
860 ((eq format 'html) (format "")); no output for html
862 ;; write out the latex addbibresource command
863 (format "\\addbibresource{%s}" keyword)))))
865 ;; ** List of figures
866 (defun org-ref-list-of-figures (&optional arg)
867 "Generate buffer with list of figures in them.
870 (save-excursion (widen)
871 (let* ((c-b (buffer-name))
874 (org-element-map (org-element-parse-buffer) 'link
876 "create a link for to the figure"
878 (and (string= (org-element-property :type link) "file")
880 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
881 (org-element-property :path link)))
884 (let* ((start (org-element-property :begin link))
885 (parent (car (cdr (org-element-property :parent link))))
886 (caption (cl-caaar (plist-get parent :caption)))
887 (name (plist-get parent :name)))
890 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
891 c-b start counter (or name "") caption)
893 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
894 c-b start counter (or name "")))))))))
895 (switch-to-buffer "*List of Figures*")
896 (setq buffer-read-only nil)
899 (insert (mapconcat 'identity list-of-figures ""))
900 (setq buffer-read-only t)
901 (use-local-map (copy-keymap org-mode-map))
902 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
906 'org-ref-list-of-figures ; on click
907 (lambda (keyword desc format)
910 (format "\\listoffigures")))))
913 (defun org-ref-list-of-tables (&optional arg)
914 "Generate a buffer with a list of tables.
919 (let* ((c-b (buffer-name))
922 (org-element-map (org-element-parse-buffer 'element) 'table
924 "create a link for to the table"
926 (let ((start (org-element-property :begin table))
927 (name (org-element-property :name table))
928 (caption (cl-caaar (org-element-property :caption table))))
931 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
932 c-b start counter (or name "") caption)
934 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
935 c-b start counter (or name ""))))))))
936 (switch-to-buffer "*List of Tables*")
937 (setq buffer-read-only nil)
940 (insert (mapconcat 'identity list-of-tables ""))
941 (setq buffer-read-only t)
942 (use-local-map (copy-keymap org-mode-map))
943 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
947 'org-ref-list-of-tables
948 (lambda (keyword desc format)
951 (format "\\listoftables")))))
955 (defun org-ref-count-labels (label)
956 "Counts number of matches for LABEL in the document."
957 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
958 ;; for tblname, it is not enough to get word boundary
959 ;; tab-little and tab-little-2 match then.
960 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
961 (count-matches (format "\\label{%s}" label) (point-min) (point-max))
962 ;; this is the org-format #+label:
963 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
964 (let ((custom-id-count 0))
967 (when (string= label (org-entry-get (point) "CUSTOM_ID"))
968 (setq custom-id-count (+ 1 custom-id-count)))))
974 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
975 (let ((count (org-ref-count-labels label)))
976 (message (format "%s occurence%s"
982 (org-ref-count-labels label))))
983 (lambda (keyword desc format)
985 ((eq format 'html) (format "<div id=\"%s\">" keyword))
987 (format "\\label{%s}" keyword)))))
989 (defun org-label-store-link ()
990 "Store a link to a label. The output will be a ref to that label."
991 ;; First we have to make sure we are on a label link.
992 (let* ((object (org-element-context)))
993 (when (and (equal (org-element-type object) 'link)
994 (equal (org-element-property :type object) "label"))
995 (org-store-link-props
997 :link (concat "ref:" (org-element-property :path object))))
999 ;; Store link on table
1000 (when (equal (org-element-type object) 'table)
1001 (org-store-link-props
1003 :link (concat "ref:" (org-element-property :name object))))
1005 ;; store link on heading with custom_id
1006 ;; this is not a ref link, but it is still what you want
1007 (when (and (equal (org-element-type object) 'headline)
1008 (org-entry-get (point) "CUSTOM_ID"))
1009 (org-store-link-props
1011 :link (format "[[#%s]]" (org-entry-get (point) "CUSTOM_ID"))))
1013 ;; and to #+label: lines
1015 (when (and (equal (org-element-type object) 'paragraph)
1016 (org-element-property :name object))
1017 (org-store-link-props
1019 :link (concat "ref:" (org-element-property :name object))))))
1021 (add-hook 'org-store-link-functions 'org-label-store-link)
1027 "on clicking goto the label. Navigate back with C-c &"
1028 (org-mark-ring-push)
1029 ;; next search from beginning of the buffer
1030 ;; it is possible you would not find the label if narrowing is in effect
1036 (goto-char (point-min))
1037 (re-search-forward (format "label:%s\\b" label) nil t))
1041 (goto-char (point-min))
1042 (re-search-forward (format "\\label{%s}" label) nil t))
1044 ;; #+label: name org-definition
1046 (goto-char (point-min))
1048 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1052 (goto-char (point-min))
1054 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1056 ;; we did not find anything, so go back to where we came
1057 (org-mark-ring-goto)
1058 (error "%s not found" label))
1060 (message "go back with (org-mark-ring-goto) `C-c &`"))
1062 (lambda (keyword desc format)
1064 ((eq format 'html) (format "<a href=\"#%s\">%s</a>" keyword keyword))
1066 (format "\\ref{%s}" keyword)))))
1069 (defun org-ref-get-org-labels ()
1070 "Return a list of #+LABEL: labels."
1072 (goto-char (point-min))
1073 (let ((matches '()))
1074 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1075 ;; do not do this for tables. We get those in `org-ref-get-tblnames'.
1076 ;; who would have thought you have save match data here? Trust me. When
1077 ;; I wrote this, you did.
1078 (unless (save-match-data (equal (car (org-element-at-point)) 'table))
1079 (add-to-list 'matches (match-string-no-properties 1) t)))
1083 (defun org-ref-get-custom-ids ()
1084 "Return a list of custom_id properties in the buffer."
1085 (let ((results '()) custom_id)
1088 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1089 (when (not (null custom_id))
1090 (setq results (append results (list custom_id)))))))
1094 (defun org-ref-get-latex-labels ()
1095 "Return list of matchin LaTeX defined labels in buffer."
1097 (goto-char (point-min))
1098 (let ((matches '()))
1099 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1100 (add-to-list 'matches (match-string-no-properties 1) t))
1104 (defun org-ref-get-tblnames ()
1105 "Return list of table names in the buffer."
1106 (org-element-map (org-element-parse-buffer 'element) 'table
1108 (org-element-property :name table))))
1111 (defun org-ref-get-labels ()
1112 "Return a list of labels in the buffer that you can make a ref link to.
1113 This is used to complete ref links and in helm menus."
1117 (goto-char (point-min))
1118 (let ((matches '()))
1119 ;; these are the org-ref label:stuff kinds
1120 (while (re-search-forward
1121 "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1122 (add-to-list 'matches (match-string-no-properties 1) t))
1123 ;; now add all the other kinds of labels.
1126 (org-ref-get-org-labels)
1128 (org-ref-get-latex-labels)
1129 ;; #+tblname: and actually #+label
1130 (org-ref-get-tblnames)
1132 (org-ref-get-custom-ids))))))
1135 (defun org-ref-helm-insert-label-link ()
1136 "Insert a label link. helm just shows you what labels already exist.
1137 If you are on a label link, replace it."
1139 (let* ((labels (org-ref-get-labels))
1140 (cb (current-buffer)))
1141 (helm :sources `(((name . "Existing labels")
1142 (candidates . ,labels)
1143 ;; default action is to open to the label
1144 (action . (lambda (label)
1145 ;; unfortunately I do not have markers here
1146 (org-open-link-from-string
1147 (format "ref:%s" label))))
1148 ;; if you select a label, replace current one
1149 (action . (lambda (label)
1150 (switch-to-buffer ,cb)
1152 ;; no prefix or on a link
1153 ((equal helm-current-prefix-arg nil)
1154 (let* ((object (org-element-context))
1155 (last-char (save-excursion
1156 (goto-char (org-element-property :end object))
1158 (if (looking-at " ")
1161 (when (-contains? '("label")
1162 (org-element-property :type object))
1163 ;; we are on a link, so replace it.
1166 (org-element-property :begin object)
1167 (org-element-property :end object))
1169 (replace-regexp-in-string
1170 (org-element-property :path object)
1172 (org-element-property :raw-link object))
1174 ;; no prefix options defined
1176 ;; no matching selection creates a new label
1177 ((name . "Create new label")
1179 ;; default action creates a new label, or replaces old one
1180 (action . (lambda (label)
1181 (switch-to-buffer ,cb)
1182 (let* ((object (org-element-context))
1183 (last-char (save-excursion
1184 (goto-char (org-element-property :end object))
1186 (if (looking-at " ")
1189 (if (-contains? '("label")
1190 (org-element-property :type object))
1191 ;; we are on a link, so replace it.
1194 (org-element-property :begin object)
1195 (org-element-property :end object))
1197 (replace-regexp-in-string
1198 (org-element-property :path object)
1200 (org-element-property :raw-link object))
1207 helm-pattern))))))))))))
1210 (defun org-ref-complete-link (&optional arg)
1211 "Completion function for ref links.
1212 Optional argument ARG Does nothing."
1214 (setq label (completing-read "label: " (org-ref-get-labels)))
1215 (format "ref:%s" label)))
1218 (defun org-ref-insert-ref-link ()
1219 "Completion function for a ref link."
1221 (insert (org-ref-complete-link)))
1224 (defun org-ref-helm-insert-ref-link ()
1225 "Helm menu to insert ref links to labels in the document.
1226 If you are on link, replace with newly selected label.
1227 Use C-u to insert a different kind of ref link.
1228 Use C-u C-u to insert a [[#custom-id]] link"
1230 (let* ((labels (org-ref-get-labels))
1231 (bs (buffer-string))
1232 (contexts (with-temp-buffer
1234 (mapcar 'org-ref-get-label-context labels)))
1235 (cb (current-buffer)))
1237 (helm :input (thing-at-point 'word)
1238 :sources `(((name . "Available labels to ref")
1239 (candidates . ,(cl-loop for label in labels
1240 for context in contexts
1241 ;; we do some kludgy adding spaces
1242 ;; and bars to make it "easier" to
1244 collect (cons (concat
1249 (split-string context "\n")
1252 ;; default action to replace or insert ref link.
1253 (action . (lambda (label)
1254 (switch-to-buffer ,cb)
1257 ;; no prefix or on a link
1258 ((equal helm-current-prefix-arg nil)
1259 (let* ((object (org-element-context))
1260 (last-char (save-excursion
1261 (goto-char (org-element-property :end object))
1263 (if (looking-at " ")
1266 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1267 (org-element-property :type object))
1268 ;; we are on a link, so replace it.
1271 (org-element-property :begin object)
1272 (org-element-property :end object))
1274 (replace-regexp-in-string
1275 (org-element-property :path object)
1277 (org-element-property :raw-link object))
1279 ;; insert a new link
1284 ;; one prefix, alternate ref link
1285 ((equal helm-current-prefix-arg '(4))
1288 (helm :sources '((name . "Ref link types")
1289 (candidates . ("ref" "eqref" "pageref" "nameref"))
1290 (action . (lambda (x) x))))
1292 ;; two prefixes, insert section custom-id link
1293 ((equal helm-current-prefix-arg '(16))
1295 (format "[[#%s]]" label)))
1303 "on clicking goto the label. Navigate back with C-c &"
1304 (org-mark-ring-push)
1305 ;; next search from beginning of the buffer
1311 (goto-char (point-min))
1312 (re-search-forward (format "label:%s\\b" label) nil t))
1316 (goto-char (point-min))
1317 (re-search-forward (format "\\label{%s}" label) nil t))
1319 ;; #+label: name org-definition
1321 (goto-char (point-min))
1323 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1327 (goto-char (point-min))
1329 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1330 ;; we did not find anything, so go back to where we came
1331 (org-mark-ring-goto)
1332 (error "%s not found" label))
1333 (message "go back with (org-mark-ring-goto) `C-c &`"))
1335 (lambda (keyword desc format)
1337 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1339 (format "\\pageref{%s}" keyword)))))
1342 (defun org-pageref-complete-link (&optional arg)
1343 "Completion function for ref links.
1344 Optional argument ARG Does nothing."
1346 (setq label (completing-read "label: " (org-ref-get-labels)))
1347 (format "ref:%s" label)))
1350 (defun org-pageref-insert-ref-link ()
1351 "Insert a pageref link with completion."
1353 (insert (org-pageref-complete-link)))
1360 "on clicking goto the label. Navigate back with C-c &"
1361 (org-mark-ring-push)
1362 ;; next search from beginning of the buffer
1368 (goto-char (point-min))
1369 (re-search-forward (format "\\label{%s}" label) nil t))
1371 ;; we did not find anything, so go back to where we came
1372 (org-mark-ring-goto)
1373 (error "%s not found" label))
1374 (message "go back with (org-mark-ring-goto) `C-c &`"))
1376 (lambda (keyword desc format)
1378 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1380 (format "\\nameref{%s}" keyword)))))
1387 "on clicking goto the label. Navigate back with C-c &"
1388 (org-mark-ring-push)
1389 ;; next search from beginning of the buffer
1391 (goto-char (point-min))
1394 ;; search forward for the first match
1396 (re-search-forward (format "label:%s" label) nil t)
1398 (re-search-forward (format "\\label{%s}" label) nil t)
1399 ;; #+label: name org-definition
1400 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1401 (org-mark-ring-goto)
1402 (error "%s not found" label))
1403 (message "go back with (org-mark-ring-goto) `C-c &`"))
1405 (lambda (keyword desc format)
1407 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1409 (format "\\eqref{%s}" keyword)))))
1413 (defun org-ref-get-bibtex-key-under-cursor ()
1414 "Return key under the bibtex cursor.
1415 We search forward from
1416 point to get a comma, or the end of the link, and then backwards
1417 to get a comma, or the beginning of the link. that delimits the
1418 keyword we clicked on. We also strip the text properties."
1419 (let* ((object (org-element-context))
1420 (link-string (org-element-property :path object)))
1421 ;; you may click on the part before the citations. here we make
1422 ;; sure to move to the beginning so you get the first citation.
1424 (goto-char (org-element-property :begin object))
1425 (search-forward link-string (org-element-property :end object))
1426 (goto-char (match-beginning 0))
1427 ;; check if we clicked before the path and move as needed.
1428 (unless (< cp (point))
1431 (if (not (org-element-property :contents-begin object))
1432 ;; this means no description in the link
1434 ;; we need the link path start and end
1435 (let (link-string-beginning link-string-end)
1437 (goto-char (org-element-property :begin object))
1438 (search-forward link-string nil nil 1)
1439 (setq link-string-beginning (match-beginning 0))
1440 (setq link-string-end (match-end 0)))
1442 (let (key-beginning key-end)
1443 ;; The key is the text between commas, or the link boundaries
1445 (if (search-forward "," link-string-end t 1)
1446 (setq key-end (- (match-end 0) 1)) ; we found a match
1447 (setq key-end link-string-end))) ; no comma found so take the end
1448 ;; and backward to previous comma from point which defines the start character
1450 (if (search-backward "," link-string-beginning 1 1)
1451 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1452 (setq key-beginning link-string-beginning))) ; no match found
1453 ;; save the key we clicked on.
1455 (org-ref-strip-string
1456 (buffer-substring key-beginning key-end))))
1457 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1459 ;; link with description. assume only one key
1462 (defun org-ref-find-bibliography ()
1463 "Find the bibliography in the buffer.
1464 This function sets and returns cite-bibliography-files, which is a list of files
1465 either from bibliography:f1.bib,f2.bib
1466 \bibliography{f1,f2}
1467 internal bibliographies
1469 falling back to what the user has set in `org-ref-default-bibliography'"
1472 (goto-char (point-min))
1473 ;; look for a bibliography link
1474 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1475 (setq org-ref-bibliography-files
1476 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1477 (throw 'result org-ref-bibliography-files))
1480 ;; we did not find a bibliography link. now look for \bibliography
1481 (goto-char (point-min))
1482 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1483 ;; split, and add .bib to each file
1484 (setq org-ref-bibliography-files
1485 (mapcar (lambda (x) (concat x ".bib"))
1486 (mapcar 'org-ref-strip-string
1487 (split-string (match-string 1) ","))))
1488 (throw 'result org-ref-bibliography-files))
1490 ;; no bibliography found. maybe we need a biblatex addbibresource
1491 (goto-char (point-min))
1492 ;; look for a bibliography link
1493 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1494 (setq org-ref-bibliography-files
1495 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1496 (throw 'result org-ref-bibliography-files))
1498 ;; we did not find anything. use defaults
1499 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1501 ;; set reftex-default-bibliography so we can search
1502 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1503 org-ref-bibliography-files)
1505 (defun org-ref-key-in-file-p (key filename)
1506 "Determine if the KEY is in the FILENAME."
1507 (save-current-buffer
1508 (let ((bibtex-files (list filename)))
1509 ;; This is something I am trying because when the bibtex file is open, and
1510 ;; you have added to it, the only way I find to get the update to update
1511 ;; is to close it and reopen it. or to save it and revert it.
1512 (when (get-file-buffer filename)
1513 (set-buffer (get-file-buffer filename))
1515 (revert-buffer t t))
1516 (bibtex-search-entry key t))))
1518 (defun org-ref-get-bibtex-key-and-file (&optional key)
1519 "Return the bibtex KEY and file that it is in. If no key is provided, get one under point."
1520 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1523 (setq key (org-ref-get-bibtex-key-under-cursor)))
1524 (setq file (catch 'result
1525 (cl-loop for file in org-ref-bibliography-files do
1526 (if (org-ref-key-in-file-p key (file-truename file))
1527 (throw 'result file)))))
1530 ;; *** key at point functions
1532 (defun org-ref-open-pdf-at-point ()
1533 "Open the pdf for bibtex key under point if it exists."
1535 (let* ((results (org-ref-get-bibtex-key-and-file))
1537 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1538 (if (file-exists-p pdf-file)
1539 (org-open-file pdf-file)
1540 (message "no pdf found for %s" key))))
1543 (defun org-ref-open-url-at-point ()
1544 "Open the url for bibtex key under point."
1546 (let* ((results (org-ref-get-bibtex-key-and-file))
1548 (bibfile (cdr results)))
1551 (insert-file-contents bibfile)
1552 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1553 (bibtex-search-entry key)
1554 ;; I like this better than bibtex-url which does not always find
1557 (let ((url (bibtex-autokey-get-field "url")))
1559 (browse-url (s-trim url))
1562 (let ((doi (bibtex-autokey-get-field "doi")))
1564 (if (string-match "^http" doi)
1566 (browse-url (format "http://dx.doi.org/%s" (s-trim doi))))
1567 (throw 'done nil))))))))
1570 (defun org-ref-open-notes-at-point ()
1571 "Open the notes for bibtex key under point."
1573 (let* ((results (org-ref-get-bibtex-key-and-file))
1575 (bibfile (cdr results)))
1578 (insert-file-contents bibfile)
1579 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1580 (bibtex-search-entry key)
1581 (org-ref-open-bibtex-notes)))))
1584 (defun org-ref-citation-at-point ()
1585 "Give message of current citation at point."
1587 (let* ((cb (current-buffer))
1588 (results (org-ref-get-bibtex-key-and-file))
1590 (bibfile (cdr results)))
1591 (message "%s" (progn
1593 (insert-file-contents bibfile)
1594 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1595 (bibtex-search-entry key)
1596 (org-ref-bib-citation))))))
1599 (defun org-ref-open-citation-at-point ()
1600 "Open bibtex file to key at point."
1602 (let* ((cb (current-buffer))
1603 (results (org-ref-get-bibtex-key-and-file))
1605 (bibfile (cdr results)))
1607 (bibtex-search-entry key)))
1611 (defvar org-ref-cite-menu-funcs '()
1612 "Functions to run on cite click menu.
1613 Each entry is a list of (key menu-name function).
1614 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.")
1617 (defvar org-ref-user-cite-menu-funcs
1618 '(("C" "rossref" org-ref-crossref-at-point)
1619 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1620 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1621 "User-defined functions to run on bibtex key at point.")
1624 (defun org-ref-copy-entry-as-summary ()
1625 "Copy the bibtex entry for the citation at point as a summary."
1627 (save-window-excursion
1628 (org-ref-open-citation-at-point)
1629 (kill-new (org-ref-bib-citation))))
1632 (defun org-ref-copy-entry-at-point-to-file ()
1633 "Copy the bibtex entry for the citation at point to NEW-FILE.
1634 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."
1636 (let ((new-file (ido-completing-read
1638 (append org-ref-default-bibliography
1639 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1640 (key (org-ref-get-bibtex-key-under-cursor)))
1641 (save-window-excursion
1642 (org-ref-open-citation-at-point)
1643 (bibtex-copy-entry-as-kill))
1645 (let ((bibtex-files (list (file-truename new-file))))
1646 (if (assoc key (bibtex-global-key-alist))
1647 (message "That key already exists in %s" new-file)
1649 (save-window-excursion
1650 (find-file new-file)
1651 (goto-char (point-max))
1652 ;; make sure we are at the beginning of a line.
1653 (unless (looking-at "^") (insert "\n\n"))
1658 (defun org-ref-get-doi-at-point ()
1659 "Get doi for key at point."
1660 (let* ((results (org-ref-get-bibtex-key-and-file))
1662 (bibfile (cdr results))
1666 (insert-file-contents bibfile)
1667 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1668 (bibtex-search-entry key)
1669 (setq doi (bibtex-autokey-get-field "doi"))
1670 ;; in case doi is a url, remove the url part.
1671 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1674 ;; **** functions that operate on key at point for click menu
1675 (defun org-ref-wos-at-point ()
1676 "Open the doi in wos for bibtex key under point."
1678 (doi-utils-wos (org-ref-get-doi-at-point)))
1681 (defun org-ref-wos-citing-at-point ()
1682 "Open the doi in wos citing articles for bibtex key under point."
1684 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1687 (defun org-ref-wos-related-at-point ()
1688 "Open the doi in wos related articles for bibtex key under point."
1690 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1693 (defun org-ref-google-scholar-at-point ()
1694 "Open the doi in google scholar for bibtex key under point."
1696 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1699 (defun org-ref-pubmed-at-point ()
1700 "Open the doi in pubmed for bibtex key under point."
1702 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1705 (defun org-ref-crossref-at-point ()
1706 "Open the doi in crossref for bibtex key under point."
1708 (doi-utils-crossref (org-ref-get-doi-at-point)))
1710 ;; *** Minibuffer menu
1712 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1713 "Action when a cite link is clicked on.
1714 Provides a menu of context sensitive actions. If the bibtex entry
1715 has a pdf, you get an option to open it. If there is a doi, you
1716 get a lot of options. LINK-STRING is used by the link function."
1718 (let* ((results (org-ref-get-bibtex-key-and-file))
1720 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1721 (bibfile (cdr results))
1722 (url (save-excursion
1724 (insert-file-contents bibfile)
1725 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1726 (bibtex-search-entry key)
1727 (bibtex-autokey-get-field "url"))))
1728 (doi (save-excursion
1730 (insert-file-contents bibfile)
1731 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1732 (bibtex-search-entry key)
1733 ;; I like this better than bibtex-url which does not always find
1735 (bibtex-autokey-get-field "doi")))))
1737 (when (string= "" doi) (setq doi nil))
1738 (when (string= "" url) (setq url nil))
1739 (setq org-ref-cite-menu-funcs '())
1745 'org-ref-cite-menu-funcs
1746 '("o" "pen" org-ref-open-citation-at-point)))
1749 (when (file-exists-p pdf-file)
1751 'org-ref-cite-menu-funcs
1752 `("p" "df" ,org-ref-open-pdf-function) t))
1756 'org-ref-cite-menu-funcs
1757 '("n" "otes" org-ref-open-notes-at-point) t)
1762 'org-ref-cite-menu-funcs
1763 '("u" "rl" org-ref-open-url-at-point) t))
1768 'org-ref-cite-menu-funcs
1769 '("w" "os" org-ref-wos-at-point) t)
1772 'org-ref-cite-menu-funcs
1773 '("c" "iting" org-ref-wos-citing-at-point) t)
1776 'org-ref-cite-menu-funcs
1777 '("r" "elated" org-ref-wos-related-at-point) t)
1780 'org-ref-cite-menu-funcs
1781 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1784 'org-ref-cite-menu-funcs
1785 '("P" "ubmed" org-ref-pubmed-at-point) t))
1787 ;; add user functions
1788 (dolist (tup org-ref-user-cite-menu-funcs)
1790 'org-ref-cite-menu-funcs
1795 'org-ref-cite-menu-funcs
1796 '("q" "uit" (lambda ())) t)
1798 ;; now we make a menu
1799 ;; construct menu string as a message
1802 (let* ((results (org-ref-get-bibtex-key-and-file))
1804 (bibfile (cdr results)))
1807 (insert-file-contents bibfile)
1808 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1809 (bibtex-search-entry key)
1810 (org-ref-bib-citation))))
1814 (concat "[" (elt tup 0) "]"
1816 org-ref-cite-menu-funcs "")))
1818 (let* ((input (read-char-exclusive))
1820 (char-to-string input) org-ref-cite-menu-funcs)))
1821 ;; now run the function (2nd element in choice)
1828 ;; *** Generation of the cite links
1829 (defmacro org-ref-make-completion-function (type)
1830 "Macro to make a link completion function for a link of TYPE."
1831 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1837 (let ((bibtex-files (org-ref-find-bibliography)))
1838 (bibtex-global-key-alist))))))
1840 (defmacro org-ref-make-format-function (type)
1841 "Macro to make a format function for a link of TYPE."
1842 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1847 (format "[[#%s][%s]]" key key))
1848 (org-ref-split-and-strip-string keyword) ","))
1855 (org-ref-split-and-strip-string keyword) ",") "]"))
1860 (format "<a href=\"#%s\">%s</a>" key key))
1861 (org-ref-split-and-strip-string keyword) ","))
1864 (if (string= (substring type -1) "s")
1865 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1866 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1867 (org-ref-split-and-strip-string keyword) ""))
1869 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1870 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1872 ;; for markdown we generate pandoc citations
1875 (desc ;; pre and or post text
1876 (let* ((text (split-string desc "::"))
1880 (format "[@%s," keyword)
1881 (when pre (format " %s" pre))
1882 (when post (format ", %s" post))
1887 (lambda (key) (concat "@" key))
1888 (org-ref-split-and-strip-string keyword)
1891 (defun org-ref-format-citation-description (desc)
1892 "Return formatted citation description.
1893 If the cite link has a DESC (description), it is optional text
1894 for the citation command. You can specify pre and post text by
1895 separating these with ::, for example [[cite:key][pre text::post
1898 ((string-match "::" desc)
1899 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1900 (t (format "[%s]" desc))))
1902 (defun org-ref-define-citation-link (type &optional key)
1903 "Add a citation link of TYPE for org-ref.
1904 With optional KEY, set the reftex binding. For example:
1905 \(org-ref-define-citation-link \"citez\" ?z) will create a new
1906 citez link, with reftex key of z, and the completion function."
1907 (interactive "sCitation Type: \ncKey: ")
1909 ;; create the formatting function
1910 (eval `(org-ref-make-format-function ,type))
1915 org-ref-cite-onclick-function
1916 (quote ,(intern (format "org-ref-format-%s" type)))))
1918 ;; create the completion function
1919 (eval `(org-ref-make-completion-function ,type))
1921 ;; store new type so it works with adding citations, which checks
1922 ;; for existence in this list
1923 (add-to-list 'org-ref-cite-types type)
1925 ;; and finally if a key is specified, we modify the reftex menu
1927 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1928 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1929 `((,key . ,(concat type ":%l")))))))
1931 ;; create all the link types and their completion functions
1932 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1934 (defun org-ref-insert-cite-link (alternative-cite)
1935 "Insert a default citation link using reftex.
1936 If you are on a link, it appends to the end of the link,
1937 otherwise, a new link is inserted. Use a prefix
1938 arg (ALTERNATIVE-CITE) to get a menu of citation types."
1940 (org-ref-find-bibliography)
1941 (let* ((object (org-element-context))
1942 (link-string-beginning (org-element-property :begin object))
1943 (link-string-end (org-element-property :end object))
1944 (path (org-element-property :path object)))
1946 (if (not alternative-cite)
1949 ;; case where we are in a link
1950 ((and (equal (org-element-type object) 'link)
1951 (-contains? org-ref-cite-types (org-element-property :type object)))
1952 (goto-char link-string-end)
1953 ;; sometimes there are spaces at the end of the link
1954 ;; this code moves point pack until no spaces are there
1955 (while (looking-back " ") (backward-char))
1956 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1958 ;; We are next to a link, and we want to append
1961 (and (equal (org-element-type (org-element-context)) 'link)
1962 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1963 (while (looking-back " ") (backward-char))
1964 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1966 ;; insert fresh link
1969 (concat org-ref-default-citation-link
1971 (mapconcat 'identity (reftex-citation t) ",")))))
1973 ;; you pressed a C-u so we run this code
1974 (reftex-citation))))
1976 (defun org-ref-insert-cite-with-completion (type)
1977 "Insert a cite link of TYPE with completion."
1978 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1979 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1981 (defun org-ref-store-bibtex-entry-link ()
1982 "Save a citation link to the current bibtex entry. Save in the default link type."
1984 (let ((link (concat org-ref-default-citation-link
1987 (bibtex-beginning-of-entry)
1988 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1989 (message "saved %s" link)
1990 (push (list link) org-stored-links)
1991 (car org-stored-links)))
1999 (lambda (path desc format)
2002 (format "\\index{%s}" path)))))
2004 ;; this will generate a temporary index of entries in the file.
2008 (let ((*index-links* '())
2009 (*initial-letters* '()))
2012 (org-element-map (org-element-parse-buffer) 'link
2014 (let ((type (nth 0 link))
2015 (plist (nth 1 link)))
2017 (when (equal (plist-get plist ':type) "index")
2020 (cons (plist-get plist :path)
2022 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2024 (plist-get plist :begin) ;; position of link
2025 ;; grab a description
2027 (goto-char (plist-get plist :begin))
2028 (if (thing-at-point 'sentence)
2030 (replace-regexp-in-string
2031 "\n" "" (thing-at-point 'sentence))
2032 ;; or call it a link
2036 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
2038 ;; now first letters
2039 (dolist (link *index-links*)
2040 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2042 ;; now create the index
2043 (switch-to-buffer (get-buffer-create "*index*"))
2046 (insert "#+TITLE: Index\n\n")
2047 (dolist (letter *initial-letters*)
2048 (insert (format "* %s\n" (upcase letter)))
2049 ;; now process the links
2052 (string= letter (substring (car (car *index-links*)) 0 1)))
2053 (let ((link (pop *index-links*)))
2054 (insert (format "%s %s\n\n" (car link) (cdr link))))))
2055 (switch-to-buffer "*index*")))
2057 (lambda (path desc format)
2060 (format "\\printindex")))))
2065 nil ;; no follow action
2066 (lambda (path desc format)
2069 (format "\\newglossaryentry{%s}{%s}" path desc)))))
2075 nil ;; no follow action
2076 (lambda (path desc format)
2079 (format "\\gls{%s}" path)))))
2084 nil ;; no follow action
2085 (lambda (path desc format)
2088 (format "\\glspl{%s}" path)))))
2093 nil ;; no follow action
2094 (lambda (path desc format)
2097 (format "\\Gls{%s}" path)))))
2102 nil ;; no follow action
2103 (lambda (path desc format)
2106 (format "\\Glspl{%s}" path)))))
2109 ;; ** create text citations from a bibtex entry
2110 (defun org-ref-bib-citation ()
2111 "From a bibtex entry, create and return a simple citation string.
2112 This assumes you are in an article."
2113 (bibtex-set-dialect nil t)
2114 (bibtex-beginning-of-entry)
2115 (let* ((cb (current-buffer))
2116 (bibtex-expand-strings t)
2117 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2118 collect (cons (downcase key) value)))
2119 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2120 (year (reftex-get-bib-field "year" entry))
2121 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2122 (key (reftex-get-bib-field "=key=" entry))
2123 (journal (let ((jt (reftex-get-bib-field "journal" entry)))
2125 (reftex-get-bib-field "journaltitle" entry)
2127 (volume (reftex-get-bib-field "volume" entry))
2128 (pages (reftex-get-bib-field "pages" entry))
2129 (doi (reftex-get-bib-field "doi" entry))
2130 (url (reftex-get-bib-field "url" entry))
2132 ;;authors, "title", Journal, vol(iss):pages (year).
2133 (format "%s, \"%s\", %s, %s:%s (%s)"
2134 author title journal volume pages year)))
2136 (defun org-ref-bib-html-citation ()
2137 "From a bibtex entry, create and return a simple citation with html links."
2138 (bibtex-beginning-of-entry)
2139 (let* ((cb (current-buffer))
2140 (bibtex-expand-strings t)
2141 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2142 collect (cons (downcase key) value)))
2143 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2144 (year (reftex-get-bib-field "year" entry))
2145 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2146 (key (reftex-get-bib-field "=key=" entry))
2147 (journal (reftex-get-bib-field "journal" entry))
2148 (volume (reftex-get-bib-field "volume" entry))
2149 (pages (reftex-get-bib-field "pages" entry))
2150 (doi (reftex-get-bib-field "doi" entry))
2151 (url (reftex-get-bib-field "url" entry)))
2152 ;;authors, "title", Journal, vol(iss):pages (year).
2153 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2154 author title journal volume pages year)
2155 (when url (format " <a href=\"%s\">link</a>" url))
2157 (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))))
2159 ;; ** Open pdf in bibtex entry
2160 (defun org-ref-open-bibtex-pdf ()
2161 "Open pdf for a bibtex entry, if it exists.
2163 the entry of interest in the bibfile. but does not check that."
2166 (bibtex-beginning-of-entry)
2167 (let* ((bibtex-expand-strings t)
2168 (entry (bibtex-parse-entry t))
2169 (key (reftex-get-bib-field "=key=" entry))
2170 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2172 (if (file-exists-p pdf)
2173 (org-open-link-from-string (format "[[file:%s]]" pdf))
2176 ;; ** Open notes from bibtex entry
2178 (defun org-ref-open-bibtex-notes ()
2179 "From a bibtex entry, open the notes if they exist, and create a heading if they do not.
2181 I never did figure out how to use reftex to make this happen
2182 non-interactively. the reftex-format-citation function did not
2183 work perfectly; there were carriage returns in the strings, and
2184 it did not put the key where it needed to be. so, below I replace
2185 the carriage returns and extra spaces with a single space and
2186 construct the heading by hand."
2189 (bibtex-beginning-of-entry)
2190 (let* ((cb (current-buffer))
2191 (bibtex-expand-strings t)
2192 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2193 collect (cons (downcase key) value)))
2194 (key (reftex-get-bib-field "=key=" entry)))
2196 ;; save key to clipboard to make saving pdf later easier by pasting.
2199 (kill-ring-save (point-min) (point-max)))
2201 ;; now look for entry in the notes file
2202 (if org-ref-bibliography-notes
2203 (find-file-other-window org-ref-bibliography-notes)
2204 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2206 (goto-char (point-min))
2207 ;; put new entry in notes if we don't find it.
2208 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2209 (funcall org-ref-open-notes-function)
2210 ;; no entry found, so add one
2211 (insert (org-ref-reftex-format-citation entry (concat "\n" org-ref-note-title-format)))
2212 (insert (org-ref-reftex-format-citation
2226 (format "[[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2227 key org-ref-pdf-directory key))))
2230 (defun org-ref-open-notes-from-reftex ()
2231 "Call reftex, and open notes for selected entry."
2233 (let ((bibtex-key )))
2235 ;; now look for entry in the notes file
2236 (if org-ref-bibliography-notes
2237 (find-file-other-window org-ref-bibliography-notes)
2238 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2240 (goto-char (point-min))
2242 (re-search-forward (format
2244 (cl-first (reftex-citation t)) nil 'end))
2245 (funcall org-ref-open-notes-function))
2247 ;; ** Open bibtex entry in browser
2248 (defun org-ref-open-in-browser ()
2249 "Open the bibtex entry at point in a browser using the url field or doi field."
2252 (bibtex-beginning-of-entry)
2254 (let ((url (bibtex-autokey-get-field "url")))
2259 (let ((doi (bibtex-autokey-get-field "doi")))
2261 (if (string-match "^http" doi)
2263 (browse-url (format "http://dx.doi.org/%s" doi)))
2265 (message "No url or doi found"))))
2267 ;; ** upload entry to citeulike
2269 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2270 "With point in a bibtex entry get bibtex string and submit to citeulike.
2272 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2274 (message "uploading to citeulike")
2276 (bibtex-narrow-to-entry)
2277 (let ((startpos (point-min))
2278 (endpos (point-max))
2279 (bibtex-string (buffer-string))
2280 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2281 (with-temp-buffer (insert bibtex-string)
2282 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2284 ;; ** Build a pdf of the bibtex file
2285 (defun org-ref-build-full-bibliography ()
2286 "Build pdf of all bibtex entries, and open it."
2288 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2289 (bib-base (file-name-sans-extension bibfile))
2290 (texfile (concat bib-base ".tex"))
2291 (pdffile (concat bib-base ".pdf")))
2294 (insert (format "\\documentclass[12pt]{article}
2295 \\usepackage[version=3]{mhchem}
2297 \\usepackage[numbers]{natbib}
2298 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2302 \\bibliographystyle{unsrtnat}
2304 \\end{document}" bib-base))
2306 (shell-command (concat "pdflatex " bib-base))
2307 (shell-command (concat "bibtex " bib-base))
2308 (shell-command (concat "pdflatex " bib-base))
2309 (shell-command (concat "pdflatex " bib-base))
2310 (kill-buffer texfile)
2311 (org-open-file pdffile)
2314 ;; ** Extract bibtex entries in org-file
2316 (defun org-ref-extract-bibtex-entries ()
2317 "Extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2319 If no bibliography is in the buffer the variable
2320 `reftex-default-bibliography' is used."
2322 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2323 (tempname (make-temp-file "extract-bib"))
2324 (contents (buffer-string))
2325 (cb (current-buffer))
2326 basename texfile bibfile results)
2328 ;; open tempfile and insert org-buffer contents
2329 (find-file tempname)
2331 (setq basename (file-name-sans-extension
2332 (file-name-nondirectory buffer-file-name))
2333 texfile (concat tempname ".tex")
2334 bibfile (concat tempname ".bib"))
2336 ;; see if we have a bibliography, and insert the default one if not.
2338 (goto-char (point-min))
2339 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2340 (insert (format "\nbibliography:%s"
2341 (mapconcat 'identity reftex-default-bibliography ",")))))
2344 ;; get a latex file and extract the references
2345 (org-latex-export-to-latex)
2348 (reftex-create-bibtex-file bibfile)
2350 ;; save results of the references
2351 (setq results (buffer-string))
2353 ;; kill buffers. these are named by basename, not full path
2354 (kill-buffer (concat basename ".bib"))
2355 (kill-buffer (concat basename ".tex"))
2356 (kill-buffer basename)
2358 (delete-file bibfile)
2359 (delete-file texfile)
2360 (delete-file tempname)
2362 ;; Now back to the original org buffer and insert the results
2363 (switch-to-buffer cb)
2364 (when (not (string= "" results))
2366 (goto-char (point-max))
2368 (org-insert-heading)
2369 (insert (format " Bibtex entries
2371 #+BEGIN_SRC text :tangle %s
2373 #+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2375 ;; ** Find bad citations
2378 (defun index (substring list)
2379 "Return the index of SUBSTRING in a LIST of strings."
2382 (dolist (arg list i)
2383 (if (string-match (concat "^" substring "$") arg)
2388 ;; return counter if found, otherwise return nil
2392 (defun org-ref-find-bad-citations ()
2393 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2395 Makes a new buffer with clickable links."
2397 ;; generate the list of bibtex-keys and cited keys
2398 (let* ((bibtex-files (org-ref-find-bibliography))
2399 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2400 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2401 (bad-citations '()))
2403 (org-element-map (org-element-parse-buffer) 'link
2405 (let ((plist (nth 1 link)))
2406 (when (-contains? org-ref-cite-types (plist-get plist :type))
2407 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)))
2408 (when (not (index key bibtex-keys))
2413 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2416 (plist-get plist :begin)))))
2418 ;; set with-affilates to t to get citations in a caption
2423 (switch-to-buffer-other-window "*Missing citations*")
2426 (insert "* List of bad cite links\n")
2427 (insert (mapconcat 'identity bad-citations ""))
2428 ;(setq buffer-read-only t)
2429 (use-local-map (copy-keymap org-mode-map))
2430 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2432 (when (get-buffer "*Missing citations*")
2433 (kill-buffer "*Missing citations*"))
2434 (message "No bad cite links found"))))
2436 ;; ** helm interface to bad citations, labels, refs and files in orgfile
2437 (defun org-ref-bad-cite-candidates ()
2438 "Return a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2439 (let* ((cp (point)) ; save to return to later
2440 (bibtex-files (org-ref-find-bibliography))
2441 (bibtex-file-path (mapconcat
2443 (file-name-directory (file-truename x)))
2445 (bibtex-keys (mapcar (lambda (x) (car x))
2446 (bibtex-global-key-alist)))
2447 (bad-citations '()))
2449 (org-element-map (org-element-parse-buffer) 'link
2451 (let ((plist (nth 1 link)))
2452 (when (-contains? org-ref-cite-types (plist-get plist :type))
2453 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)) )
2454 (when (not (index key bibtex-keys))
2455 (goto-char (plist-get plist :begin))
2456 (re-search-forward key)
2457 (push (cons key (point-marker)) bad-citations)))
2459 ;; add with-affiliates to get cites in caption
2465 (defun org-ref-bad-ref-candidates ()
2466 "Return a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2467 ;; first get a list of legitimate labels
2469 (labels (org-ref-get-labels))
2471 ;; now loop over ref links
2472 (goto-char (point-min))
2473 (org-element-map (org-element-parse-buffer) 'link
2475 (let ((plist (nth 1 link)))
2476 (when (or (equal (plist-get plist ':type) "ref")
2477 (equal (plist-get plist ':type) "eqref")
2478 (equal (plist-get plist ':type) "pageref")
2479 (equal (plist-get plist ':type) "nameref"))
2480 (unless (-contains? labels (plist-get plist :path))
2481 (goto-char (plist-get plist :begin))
2484 (cons (plist-get plist :path)
2485 (point-marker))))))))
2490 (defun org-ref-bad-label-candidates ()
2491 "Return a list of labels where label is multiply defined."
2492 (let ((labels (org-ref-get-labels))
2493 (multiple-labels '()))
2494 (when (not (= (length labels)
2495 (length (-uniq labels))))
2496 (dolist (label labels)
2497 (when (> (-count (lambda (a)
2500 ;; this is a multiply defined label.
2502 (goto-char (point-min))
2503 (while (re-search-forward
2504 (format "[^#+]label:%s\\s-" label) nil t)
2505 (push (cons label (point-marker)) multiple-labels))
2506 (goto-char (point-min))
2507 (while (re-search-forward
2508 (format "\\label{%s}\\s-?" label) nil t)
2509 (push (cons label (point-marker)) multiple-labels))
2511 (goto-char (point-min))
2512 (while (re-search-forward
2513 (format "^#\\+label:\\s-*%s" label) nil t)
2514 (push (cons label (point-marker)) multiple-labels))
2516 (goto-char (point-min))
2517 (while (re-search-forward
2518 (format "^#\\+tblname:\\s-*%s" label) nil t)
2519 (push (cons label (point-marker)) multiple-labels))
2523 (defun org-ref-bad-file-link-candidates ()
2524 "Return list of conses (link . marker) wehre the file in the link does not exist."
2525 (let* ((bad-files '()))
2526 (org-element-map (org-element-parse-buffer) 'link
2528 (let ((type (org-element-property :type link)))
2529 (when (or (string= "file" type)
2530 (string= "attachfile" type))
2531 (unless (file-exists-p (org-element-property :path link))
2532 (add-to-list 'bad-files
2533 (cons (org-element-property :path link)
2536 (org-element-property :begin link))
2537 (point-marker)))))))))
2538 ;; Let us also check \attachfile{fname}
2540 (goto-char (point-min))
2541 (while (re-search-forward "\\attachfile{\\(.*\\)}" nil t)
2542 (unless (file-exists-p (match-string 1))
2543 (add-to-list 'bad-files (cons (match-string 1) (point-marker))))))
2548 "Opens a helm interface to actions for org-ref.
2549 Shows bad citations, ref links and labels"
2551 (let ((cb (current-buffer))
2552 (bad-citations (org-ref-bad-cite-candidates))
2553 (bad-refs (org-ref-bad-ref-candidates))
2554 (bad-labels (org-ref-bad-label-candidates))
2555 (bad-files (org-ref-bad-file-link-candidates)))
2557 (helm :sources `(((name . "Bad citations")
2558 (candidates . ,bad-citations)
2559 (action . (lambda (marker)
2560 (switch-to-buffer (marker-buffer marker))
2561 (goto-char marker))))
2563 ((name . "Bad Labels")
2564 (candidates . ,bad-labels)
2565 (action . (lambda (marker)
2566 (switch-to-buffer (marker-buffer marker))
2567 (goto-char marker))))
2569 ((name . "Bad ref links")
2570 (candidates . ,bad-refs)
2571 (action . (lambda (marker)
2572 (switch-to-buffer (marker-buffer marker))
2573 (goto-char marker))))
2575 ((name . "Bad file links")
2576 (candidates . ,bad-files)
2578 (switch-to-buffer (marker-buffer marker))
2579 (goto-char marker)))
2581 ((name . "Utilities")
2582 (candidates . (("Check buffer again" . org-ref)
2583 ("Insert citation" . helm-bibtex)
2584 ("Insert label link" . org-ref-helm-insert-label-link)
2585 ("Insert ref link" . org-ref-helm-insert-ref-link)
2586 ("List of figures" . org-ref-list-of-figures)
2587 ("List of tables" . org-ref-list-of-tables)
2588 ("Table of contents" . nil)
2590 (action . (lambda (x)
2591 (switch-to-buffer ,cb)
2594 ((name . "Export functions")
2595 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2596 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2597 ("Export to pdf and open" . (lambda ()
2598 (org-open-file (org-latex-export-to-pdf))))
2599 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2600 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2603 (action . (lambda (x)
2604 (switch-to-buffer ,cb)
2607 ;; ** Find non-ascii charaters
2608 (defun org-ref-find-non-ascii-characters ()
2609 "Find non-ascii characters in the buffer. Useful for cleaning up bibtex files."
2611 (occur "[^[:ascii:]]"))
2613 ;; ** Sort fields in a bibtex entry
2615 (defun org-ref-sort-bibtex-entry ()
2616 "Sort fields of entry in standard order and downcase them."
2618 (bibtex-beginning-of-entry)
2619 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2620 (entry (bibtex-parse-entry))
2623 (type (cdr (assoc "=type=" entry)))
2624 (key (cdr (assoc "=key=" entry))))
2626 ;; these are the fields we want to order that are in this entry
2627 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2628 ;; we do not want to reenter these fields
2629 (setq entry-fields (remove "=key=" entry-fields))
2630 (setq entry-fields (remove "=type=" entry-fields))
2632 ;;these are the other fields in the entry
2633 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2636 ;; right now we only resort articles
2637 ((string= (downcase type) "article")
2640 (concat "@article{" key ",\n"
2643 (when (member field entry-fields)
2644 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2647 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2649 (bibtex-find-entry key)
2651 (bibtex-clean-entry)
2654 ;; ** Clean a bibtex entry
2655 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2656 "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"
2658 (bibtex-beginning-of-entry)
2660 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2661 (unless (string-match ",$" (thing-at-point 'line))
2665 ;; check for empty pages, and put eid or article id in its place
2666 (let ((entry (bibtex-parse-entry))
2667 (pages (bibtex-autokey-get-field "pages"))
2668 (year (bibtex-autokey-get-field "year"))
2669 (doi (bibtex-autokey-get-field "doi"))
2670 ;; The Journal of Chemical Physics uses eid
2671 (eid (bibtex-autokey-get-field "eid")))
2673 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2674 ;; but we only want the doi.
2675 (when (string-match "^http://dx.doi.org/" doi)
2676 (bibtex-beginning-of-entry)
2677 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2679 (bibtex-make-field "doi")
2681 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2683 ;; asap articles often set year to 0, which messes up key
2684 ;; generation. fix that.
2685 (when (string= "0" year)
2686 (bibtex-beginning-of-entry)
2687 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2689 (bibtex-make-field "year")
2691 (insert (read-string "Enter year: ")))
2693 ;; fix pages if they are empty if there is an eid to put there.
2694 (when (string= "-" pages)
2696 (bibtex-beginning-of-entry)
2697 ;; this seems like a clunky way to set the pages field.But I
2698 ;; cannot find a better way.
2699 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2701 (bibtex-make-field "pages")
2705 ;; replace naked & with \&
2707 (bibtex-narrow-to-entry)
2708 (bibtex-beginning-of-entry)
2709 (message "checking &")
2710 (replace-regexp " & " " \\\\& ")
2713 ;; generate a key, and if it duplicates an existing key, edit it.
2715 (let ((key (bibtex-generate-autokey)))
2717 ;; first we delete the existing key
2718 (bibtex-beginning-of-entry)
2719 (re-search-forward bibtex-entry-maybe-empty-head)
2720 (if (match-beginning bibtex-key-in-head)
2721 (delete-region (match-beginning bibtex-key-in-head)
2722 (match-end bibtex-key-in-head)))
2723 ;; check if the key is in the buffer
2724 (when (save-excursion
2725 (bibtex-search-entry key))
2727 (bibtex-search-entry key)
2728 (bibtex-copy-entry-as-kill)
2729 (switch-to-buffer-other-window "*duplicate entry*")
2731 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2734 (kill-new key))) ;; save key for pasting
2736 ;; run hooks. each of these operates on the entry with no arguments.
2737 ;; this did not work like i thought, it gives a symbolp error.
2738 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2743 org-ref-clean-bibtex-entry-hook)
2745 ;; sort fields within entry
2746 (org-ref-sort-bibtex-entry)
2747 ;; check for non-ascii characters
2748 (occur "[^[:ascii:]]")
2751 (defun org-ref-get-citation-year (key)
2752 "Get the year of an entry with KEY. Return year as a string."
2753 (let* ((results (org-ref-get-bibtex-key-and-file key))
2754 (bibfile (cdr results)))
2756 (insert-file-contents bibfile)
2757 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
2758 (bibtex-search-entry key nil 0)
2759 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2762 ;; ** Sort cite in cite link
2763 (defun org-ref-sort-citation-link ()
2764 "Replace link at point with sorted link by year."
2766 (let* ((object (org-element-context))
2767 (type (org-element-property :type object))
2768 (begin (org-element-property :begin object))
2769 (end (org-element-property :end object))
2770 (link-string (org-element-property :path object))
2772 (setq keys (org-ref-split-and-strip-string link-string))
2773 (setq years (mapcar 'org-ref-get-citation-year keys))
2774 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2775 (setq data (cl-sort data (lambda (x y) (< (string-to-number (car x)) (string-to-number (car y))))))
2776 ;; now get the keys separated by commas
2777 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2778 ;; and replace the link with the sorted keys
2779 (cl--set-buffer-substring begin end (concat type ":" keys))))
2781 ;; ** Shift-arrow sorting of keys in a cite link
2783 (defun org-ref-swap-keys (i j keys)
2784 "Swap the KEYS in a list with index I and J."
2785 (let ((tempi (nth i keys)))
2786 (setf (nth i keys) (nth j keys))
2787 (setf (nth j keys) tempi))
2791 (defun org-ref-swap-citation-link (direction)
2792 "Move citation at point in DIRECTION +1 is to the right, -1 to the left."
2794 (let* ((object (org-element-context))
2795 (type (org-element-property :type object))
2796 (begin (org-element-property :begin object))
2797 (end (org-element-property :end object))
2798 (link-string (org-element-property :path object))
2800 ;; We only want this to work on citation links
2801 (when (-contains? org-ref-cite-types type)
2802 (setq key (org-ref-get-bibtex-key-under-cursor))
2803 (setq keys (org-ref-split-and-strip-string link-string))
2804 (setq i (index key keys)) ;; defined in org-ref
2805 (if (> direction 0) ;; shift right
2806 (org-ref-swap-keys i (+ i 1) keys)
2807 (org-ref-swap-keys i (- i 1) keys))
2808 (setq keys (mapconcat 'identity keys ","))
2809 ;; and replace the link with the sorted keys
2810 (cl--set-buffer-substring
2814 ;; It seems the space at the end can get consumed, so we see if there
2815 ;; is a space, and add it if so. Sometimes there is a comma or period,
2816 ;; then we do not want a space.
2820 (looking-back " ")) " ")))
2821 ;; now go forward to key so we can move with the key
2822 (re-search-forward key)
2823 (goto-char (match-beginning 0)))))
2825 ;; add hooks to make it work
2826 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2827 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2829 ;; ** context around org-ref links
2830 (defun org-ref-get-label-context (label)
2831 "Return a string of context around a LABEL."
2834 (goto-char (point-min))
2835 (when (re-search-forward
2836 (format "label:%s\\b" label) nil t)
2837 (throw 'result (buffer-substring
2846 (goto-char (point-min))
2847 (when (re-search-forward
2848 (format "\\label{%s}" label) nil t)
2849 (throw 'result (buffer-substring
2858 (goto-char (point-min))
2859 (when (re-search-forward
2860 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2861 (throw 'result (buffer-substring
2870 (goto-char (point-min))
2871 (when (re-search-forward
2872 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2873 (throw 'result (buffer-substring
2881 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
2884 (defun org-ref-link-message ()
2885 "Print a minibuffer message about the link that point is on."
2889 (when (eq major-mode 'org-mode)
2890 (let* ((object (org-element-context))
2891 (type (org-element-property :type object)))
2895 ((-contains? org-ref-cite-types type)
2896 (message (org-ref-get-citation-string-at-point)))
2898 ;; message some context about the label we are referring to
2899 ((string= type "ref")
2900 (message "%scount: %s"
2901 (org-ref-get-label-context
2902 (org-element-property :path object))
2903 (org-ref-count-labels
2904 (org-element-property :path object))))
2906 ((string= type "eqref")
2907 (message "%scount: %s"
2908 (org-ref-get-label-context
2909 (org-element-property :path object))
2910 (org-ref-count-labels
2911 (org-element-property :path object))))
2913 ;; message the count
2914 ((string= type "label")
2915 (let ((count (org-ref-count-labels
2916 (org-element-property :path object))))
2917 ;; get plurality on occurrence correct
2919 (number-to-string count)
2921 (when (or (= count 0)
2925 ((string= type "custom-id")
2927 (org-open-link-from-string
2928 (format "[[#%s]]" (org-element-property :path object)))
2929 (message "%s" (org-get-heading))))
2931 ;; check if the bibliography files exist.
2932 ((string= type "bibliography")
2934 ;; object is the link you clicked on
2935 (object (org-element-context))
2936 (link-string (org-element-property :path object))
2937 (link-string-beginning)
2940 (goto-char (org-element-property :begin object))
2941 (search-forward link-string nil nil 1)
2942 (setq link-string-beginning (match-beginning 0))
2943 (setq link-string-end (match-end 0)))
2945 ;; make sure we are in link and not before the :
2946 (when (> link-string-beginning (point))
2947 (goto-char link-string-beginning))
2949 (let (key-beginning key-end)
2950 ;; now if we have comma separated bibliographies
2951 ;; we find the one clicked on. we want to
2952 ;; search forward to next comma from point
2954 (if (search-forward "," link-string-end 1 1)
2955 (setq key-end (- (match-end 0) 1)) ; we found a match
2956 (setq key-end (point)))) ; no comma found so take the point
2958 ;; and backward to previous comma from point
2960 (if (search-backward "," link-string-beginning 1 1)
2961 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
2962 (setq key-beginning (point)))) ; no match found
2963 ;; save the key we clicked on.
2965 (org-ref-strip-string
2966 (buffer-substring key-beginning key-end)))
2967 (if (file-exists-p bibfile)
2968 (message "%s exists." bibfile)
2969 (message "!!! %s NOT FOUND !!!" bibfile)))))))))))
2972 (defalias 'oro 'org-ref-open-citation-at-point)
2973 (defalias 'orc 'org-ref-citation-at-point)
2974 (defalias 'orp 'org-ref-open-pdf-at-point)
2975 (defalias 'oru 'org-ref-open-url-at-point)
2976 (defalias 'orn 'org-ref-open-notes-at-point)
2977 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2979 (defalias 'orib 'org-ref-insert-bibliography-link)
2980 (defalias 'oric 'org-ref-insert-cite-link)
2981 (defalias 'orir 'org-ref-insert-ref-link)
2982 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2984 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2986 ;; * Helm bibtex setup
2988 (setq helm-bibtex-additional-search-fields '(keywords))
2990 (defun helm-bibtex-candidates-formatter (candidates source)
2991 "Formats BibTeX entries for display in results list.
2992 Argument CANDIDATES helm candidates.
2993 Argument SOURCE the helm source."
2995 with width = (with-helm-window (helm-bibtex-window-width))
2996 for entry in candidates
2997 for entry = (cdr entry)
2998 for entry-key = (helm-bibtex-get-value "=key=" entry)
2999 if (assoc-string "author" entry 'case-fold)
3000 for fields = '("author" "title" "year" "=has-pdf=" "=has-note=" "=type=")
3002 for fields = '("editor" "title" "year" "=has-pdf=" "=has-note=" "=type=")
3003 for fields = (--map (helm-bibtex-clean-string
3004 (helm-bibtex-get-value it entry " "))
3006 for fields = (-update-at 0 'helm-bibtex-shorten-authors fields)
3007 for fields = (append fields
3008 (list (or (helm-bibtex-get-value "keywords" entry)
3011 (cons (s-format "$0 $1 $2 $3 $4$5 $6" 'elt
3012 (-zip-with (lambda (f w) (truncate-string-to-width f w 0 ?\s))
3013 fields (list 36 (- width 85) 4 1 1 7 7)))
3016 ;; * org-ref bibtex keywords
3017 ;; adapted from bibtex-utils.el
3018 ;; these are candidates for selecting keywords/tags
3019 (defun org-ref-bibtex-keywords ()
3020 "Get keywords defined in current bibtex file.
3021 These are in the keywords field, and are comma or semicolon separated."
3023 (goto-char (point-min))
3024 (let (keywords kstring)
3025 (while (re-search-forward "^\\s-*keywords.*{\\([^}]+\\)}" nil t)
3026 ;; TWS - remove newlines/multiple spaces:
3027 (setq kstring (replace-regexp-in-string "[ \t\n]+" " " (match-string 1)))
3030 (add-to-list 'keywords v t))
3031 (split-string kstring "\\(,\\|;\\)[ \n]*\\|{\\|}" t)))
3035 (defun org-ref-set-bibtex-keywords (keywords &optional arg)
3036 "Add KEYWORDS to a bibtex entry.
3037 If KEYWORDS is a list, it is converted to a comma-separated
3038 string. The KEYWORDS are added to the beginning of the
3039 field. Otherwise KEYWORDS should be a string of comma-separate
3040 keywords. Optional argument ARG prefix arg to replace keywords."
3041 (interactive "sKeywords: \nP")
3046 (if (listp keywords)
3047 (mapconcat 'identity keywords ", ")
3049 ;; else concatentate
3051 (if (listp keywords)
3052 (mapconcat 'identity keywords ", ")
3054 (when (not (string= "" (bibtex-autokey-get-field "keywords")))
3055 (concat ", " (bibtex-autokey-get-field "keywords"))))))
3059 (defun helm-tag-bibtex-entry ()
3060 "Helm interface to add keywords to a bibtex entry.
3061 Run this with the point in a bibtex entry."
3063 (let ((keyword-source `((name . "Existing keywords")
3064 (candidates . ,(org-ref-bibtex-keywords))
3065 (action . (lambda (candidate)
3066 (org-ref-set-bibtex-keywords
3069 (helm-marked-candidates)
3071 (fallback-source `((name . "Add new keywords")
3073 (action . (lambda (candidate)
3074 (org-ref-set-bibtex-keywords helm-pattern)
3076 (helm :sources '(keyword-source fallback-source))))
3078 (defun helm-bibtex-show-entry (key)
3079 "Show the entry for KEY in the BibTeX file.
3080 The original function in `helm-bibtex' has a bug where it finds the
3081 first key that partially matches. This version avoids that."
3083 (dolist (bibtex-file (if (listp helm-bibtex-bibliography)
3084 helm-bibtex-bibliography
3085 (list helm-bibtex-bibliography)))
3086 (let ((buf (helm-bibtex-buffer-visiting bibtex-file))
3088 (find-file bibtex-file)
3090 (lambda (key start end)
3091 (add-to-list 'entries (cons key start))))
3092 (if (assoc key entries)
3094 (goto-char (cdr (assoc key entries)))
3099 (defun org-ref-helm-tag-entries (candidates)
3100 "Set tags on selected bibtex entries from `helm-bibtex'.
3101 User is prompted for tags. This function is called from `helm-bibtex'.
3102 Argument CANDIDATES helm candidates."
3104 (let ((keywords (read-string "Keywords (comma separated): ")))
3105 (cl-loop for key in (helm-marked-candidates)
3107 (save-window-excursion
3108 (helm-bibtex-show-entry key)
3113 ", " (bibtex-autokey-get-field "keywords")))
3116 (setq helm-source-bibtex
3117 '((name . "BibTeX entries")
3118 (init . helm-bibtex-init)
3119 (candidates . helm-bibtex-candidates)
3120 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3121 (action . (("Insert citation" . helm-bibtex-insert-citation)
3122 ("Show entry" . helm-bibtex-show-entry)
3123 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3124 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3125 ("Insert formatted reference" . helm-bibtex-insert-reference)
3126 ("Insert BibTeX key" . helm-bibtex-insert-key)
3127 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3128 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3129 ("Edit notes" . helm-bibtex-edit-notes)
3130 ("Add keywords to entries" . org-ref-helm-tag-entries)
3133 (defun helm-bibtex-format-org-ref (keys)
3134 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3135 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.
3137 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3139 C-u C-u will change the key at point to the selected keys."
3140 (let* ((object (org-element-context))
3141 (last-char (save-excursion
3142 (when (org-element-property :end object)
3143 (goto-char (org-element-property :end object))
3146 (if (looking-at " ")
3150 ;; case where we are in a link
3151 ((and (equal (org-element-type object) 'link)
3154 (org-element-property :type object)))
3156 ;; no prefix. append keys
3157 ((equal helm-current-prefix-arg nil)
3158 (goto-char (org-element-property :end object))
3159 (while (looking-back " ") (backward-char))
3160 (insert (concat "," (mapconcat 'identity keys ","))))
3161 ;; double prefix, replace key at point
3162 ((equal helm-current-prefix-arg '(16))
3163 (setf (buffer-substring
3164 (org-element-property :begin object)
3165 (org-element-property :end object))
3167 (replace-regexp-in-string
3168 (car (org-ref-get-bibtex-key-and-file)) ; key
3169 (mapconcat 'identity keys ",") ; new keys
3170 (org-element-property :raw-link object))
3171 ;; replace space at end to avoid collapsing into next word.
3173 ;; and we want to go to the end of the new link
3175 (org-element-property :end (org-element-context))))
3177 (message "Not found"))))
3179 ;; We are next to a link, and we want to append
3180 ;; next to a link means one character back is on a link.
3182 (unless (bobp) (backward-char))
3183 (and (equal (org-element-type (org-element-context)) 'link)
3186 (org-element-property :type (org-element-context)))))
3187 (while (looking-back " ") (backward-char))
3188 (insert (concat "," (mapconcat 'identity keys ","))))
3190 ;; insert fresh link
3192 ;;(message-box "fresh link")
3194 (concat (if (equal helm-current-prefix-arg '(4))
3195 (helm :sources `((name . "link types")
3196 (candidates . ,org-ref-cite-types)
3197 (action . (lambda (x) x))))
3198 org-ref-default-citation-link)
3200 (s-join "," keys))))))
3201 ;; return empty string for helm
3204 (setq helm-bibtex-format-citation-functions
3205 '((org-mode . helm-bibtex-format-org-ref)))
3208 (defun org-ref-helm-insert-cite-link (arg)
3209 "org-ref function to use helm-bibtex to insert a citation link.
3210 With one prefix arg, insert a ref link.
3211 With two prefix args, insert a label link."
3215 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3218 (org-ref-helm-insert-ref-link))
3220 (org-ref-helm-insert-label-link))))
3223 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3224 (setq helm-bibtex-fallback-options
3225 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3227 (setq helm-bibtex-fallback-options
3230 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3231 helm-bibtex-fallback-options))
3233 (setq helm-bibtex-fallback-options
3234 (-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))
3236 (defun org-ref-get-citation-string-at-point ()
3237 "Get a string of a formatted citation."
3238 (let* ((results (org-ref-get-bibtex-key-and-file))
3240 (bibfile (cdr results)))
3244 (insert-file-contents bibfile)
3245 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3246 (bibtex-search-entry key)
3247 (org-ref-bib-citation)))
3248 "!!! No entry found !!!" )))
3251 (defun org-ref-cite-candidates ()
3252 "Generate the list of possible candidates for click actions on a cite link.
3253 Checks for pdf and doi, and add appropriate functions."
3254 (let* ((results (org-ref-get-bibtex-key-and-file))
3256 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3257 (bibfile (cdr results))
3258 (url (save-excursion
3260 (insert-file-contents bibfile)
3261 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3262 (bibtex-search-entry key)
3263 (bibtex-autokey-get-field "url"))))
3264 (doi (save-excursion
3266 (insert-file-contents bibfile)
3267 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3268 (bibtex-search-entry key)
3269 ;; I like this better than bibtex-url which does not always find
3271 (bibtex-autokey-get-field "doi"))))
3272 (candidates `(("Quit" . org-ref-citation-at-point)
3273 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3274 ;; for some reason, when there is no doi or url, they are returned as "". I
3275 ;; prefer nil so we correct this here.
3276 (when (string= doi "") (setq doi nil))
3277 (when (string= url "") (setq url nil))
3279 ;; Conditional pdf functions
3280 (if (file-exists-p pdf-file)
3283 '("Open pdf" . org-ref-open-pdf-at-point)
3287 '("Try to get pdf" . (lambda ()
3288 (save-window-excursion
3289 (org-ref-open-citation-at-point)
3290 (bibtex-beginning-of-entry)
3291 (doi-utils-get-bibtex-entry-pdf))))
3297 '("Open notes" . org-ref-open-notes-at-point)
3300 ;; conditional url and doi functions
3304 '("Open in browser" . org-ref-open-url-at-point)
3309 (add-to-list 'candidates x t))
3310 `(("WOS" . org-ref-wos-at-point)
3311 ("Related articles in WOS" . org-ref-wos-related-at-point)
3312 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3313 ("Google Scholar" . org-ref-google-scholar-at-point)
3314 ("Pubmed" . org-ref-pubmed-at-point)
3315 ("Crossref" . org-ref-crossref-at-point)
3320 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3325 '("Copy key to clipboard" . (lambda ()
3327 (car (org-ref-get-bibtex-key-and-file)))))
3332 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3337 '("Email bibtex entry and pdf" . (lambda ()
3339 (org-ref-open-citation-at-point)
3340 (email-bibtex-entry))))
3342 ;; finally return a numbered list of the candidates
3343 (cl-loop for i from 0
3344 for cell in candidates
3345 collect (cons (format "%2s. %s" i (car cell))
3349 (defvar org-ref-helm-user-candidates '()
3350 "List of user-defined candidates to act when clicking on a cite link.
3351 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.")
3353 ;; example of adding your own function
3355 'org-ref-helm-user-candidates
3356 '("Example" . (lambda () (message-box "You did it!")))
3360 (defun org-ref-cite-click-helm (key)
3361 "Open helm for actions on a cite link.
3364 1. get name and candidates before entering helm because we need
3367 2. switch back to the org buffer before evaluating the
3368 action. most of them need the point and buffer.
3370 KEY is returned for the selected item(s) in helm."
3372 (let ((name (org-ref-get-citation-string-at-point))
3373 (candidates (org-ref-cite-candidates))
3374 (cb (current-buffer)))
3376 (helm :sources `(((name . ,name)
3377 (candidates . ,candidates)
3378 (action . (lambda (f)
3379 (switch-to-buffer cb)
3381 ((name . "User functions")
3382 (candidates . ,org-ref-helm-user-candidates)
3383 (action . (lambda (f)
3384 (switch-to-buffer cb)
3388 ;; * Hydra menus in org-ref
3390 (when (featurep 'hydra)
3392 (setq hydra-is-helpful t)
3394 (defhydra org-ref-cite-hydra (:color blue)
3396 _p_: Open pdf _w_: WOS _g_: Google Scholar _K_: Copy citation to clipboard
3397 _u_: Open url _r_: WOS related _P_: Pubmed _k_: Copy key to clipboard
3398 _n_: Open notes _c_: WOS citing _C_: Crossref _f_: Copy bibtex entry to file
3399 _o_: Open entry _e_: Email entry and pdf
3401 ("o" org-ref-open-citation-at-point nil)
3402 ("p" org-ref-open-pdf-at-point nil)
3403 ("n" org-ref-open-notes-at-point nil)
3404 ("u" org-ref-open-url-at-point nil)
3405 ("w" org-ref-wos-at-point nil)
3406 ("r" org-ref-wos-related-at-point nil)
3407 ("c" org-ref-wos-citing-at-point nil)
3408 ("g" org-ref-google-scholar-at-point nil)
3409 ("P" org-ref-pubmed-at-point nil)
3410 ("C" org-ref-crossref-at-point nil)
3411 ("K" org-ref-copy-entry-as-summary nil)
3414 (car (org-ref-get-bibtex-key-and-file)))) nil)
3415 ("f" org-ref-copy-entry-at-point-to-file nil)
3417 ("e" (save-excursion
3418 (org-ref-open-citation-at-point)
3419 (email-bibtex-entry)) nil)))
3422 (defun org-ref-help ()
3423 "Open the org-ref manual."
3425 (find-file (expand-file-name
3427 (file-name-directory
3428 (find-library-name "org-ref")))))
3431 (defun org-ref-org-menu ()
3432 "Add org-ref menu to the Org menu."
3436 '( ["Insert citation" org-ref-helm-insert-cite-link]
3437 ["Insert ref" org-ref-helm-insert-ref-link]
3438 ["Insert label" org-ref-helm-insert-label-link]
3440 ["List of figures" org-ref-list-of-figures]
3441 ["List of tables" org-ref-list-of-tables]
3442 ["Extract bibtex entries" org-ref-extract-bibtex-entries]
3443 ["Check org-file" org-ref]
3445 ["Help" org-ref-help]
3446 ["Customize org-ref" (customize-group 'org-ref)])
3449 (easy-menu-change '("Org") "--" nil "Show/Hide"))
3451 (add-hook 'org-mode-hook 'org-ref-org-menu)
3456 ;;; org-ref.el ends here