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
115 function must get the key at point, and derive a path to the pdf
116 file, then open it. The default function is
117 `org-ref-open-pdf-at-point'."
122 (defcustom org-ref-get-pdf-filename-function
123 'org-ref-get-pdf-filename
124 "User-defined function to get a filename from a bibtex key.
125 The function must take a key as an argument, and return the path
126 to the corresponding filename. The default is
127 `org-ref-get-pdf-filename'.")
130 (defcustom org-ref-insert-cite-function
131 'org-ref-helm-insert-cite-link
132 "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."
137 (defcustom org-ref-cite-onclick-function
138 'org-ref-cite-click-helm
139 "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'."
144 (defcustom org-ref-show-citation-on-enter t
145 "If non-nil add a hook function to show the citation summary in the minibuffer."
148 (defcustom org-ref-cite-types
149 '("cite" "nocite" ;; the default latex cite commands
150 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
151 "citet" "citet*" "citep" "citep*"
152 "citealt" "citealt*" "citealp" "citealp*"
154 "citeauthor" "citeauthor*"
155 "citeyear" "citeyear*"
156 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
158 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
160 "parencite" "Parencite"
161 "footcite" "footcitetext"
162 "textcite" "Textcite"
163 "smartcite" "Smartcite"
164 "cite*" "parencite*" "supercite"
165 "autocite" "Autocite" "autocite*" "Autocite*"
167 "citetitle" "citetitle*"
168 "citedate" "citedate*"
170 "fullcite" "footfullcite"
171 ;; "volcite" "Volcite" cannot support the syntax
172 "notecite" "Notecite"
173 "pnotecite" "Pnotecite"
175 ;; multicites. Very limited support for these.
176 "cites" "Cites" "parencites" "Parencites"
177 "footcites" "footcitetexts"
178 "smartcites" "Smartcites" "textcites" "Textcites"
179 "supercites" "autocites" "Autocites"
180 ;; for the bibentry package
183 "List of citation types known in `org-ref'."
184 :type '(repeat :tag "List of citation types" string)
187 (defcustom org-ref-clean-bibtex-entry-hook nil
188 "Hook that is run in `org-ref-clean-bibtex-entry'. The functions should take no arguments, and operate on the bibtex entry at point."
192 (defvar org-ref-bibliography-files
194 "Variable to hold bibliography files to be searched.")
196 ;; * org-mode / reftex setup
198 (defun org-mode-reftex-setup ()
199 "Setup `org-mode' and reftex for org-ref."
200 (and (buffer-file-name)
201 (file-exists-p (buffer-file-name))
202 (global-auto-revert-mode t))
203 (make-local-variable 'reftex-cite-format)
204 (setq reftex-cite-format 'org))
206 ;; define key for inserting citations
207 (define-key org-mode-map
208 (kbd org-ref-insert-cite-key)
209 org-ref-insert-cite-function)
211 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
213 (eval-after-load 'reftex-vars
215 (add-to-list 'reftex-cite-format-builtin
216 '(org "Org-mode citation"
217 ((?\C-m . "cite:%l") ; default
218 (?d . ",%l") ; for appending
224 (?h . "citeauthor:%l")
225 (?H . "citeauthor*:%l")
231 ;; * Messages for link at cursor
232 (defvar org-ref-message-timer nil
233 "Variable to store the link message timer in.")
236 (defun org-ref-show-link-messages ()
237 "Turn on link messages.
238 You will see a message in the minibuffer when on a cite, ref or label link."
240 (or org-ref-message-timer
241 (setq org-ref-message-timer
242 (run-with-idle-timer 0.5 t 'org-ref-link-message))))
245 (defun org-ref-cancel-link-messages ()
246 "Stop showing messages in minibuffer when on a link."
248 (cancel-timer org-ref-message-timer)
249 (setq org-ref-message-timer nil))
252 (when org-ref-show-citation-on-enter
253 (org-ref-show-link-messages))
255 ;; ** Messages for context under mouse pointer
257 (defvar org-ref-last-mouse-pos nil
258 "Stores last mouse position for use in `org-ref-mouse-message'.")
260 (defun org-ref-can-move-p ()
261 "See if a character is under the mouse. If so return the position for `goto-char'."
262 (let* ((line (cddr org-ref-last-mouse-pos))
263 (col (cadr org-ref-last-mouse-pos)))
265 (goto-char (window-start))
268 (> (- (line-end-position) (line-beginning-position)) col)
269 (progn (forward-char col) (point))
273 (defun org-ref-mouse-message ()
274 "Display message for link under mouse cursor."
276 (when (not (equal (mouse-position) org-ref-last-mouse-pos))
277 (setq org-ref-last-mouse-pos (mouse-position))
278 (let ((p (org-ref-can-move-p)))
282 (org-ref-link-message))))))
285 (defvar org-ref-message-timer-mouse nil
286 "Store mouse timer.")
289 (defvar org-ref-mouse-message-interval 0.5
290 "How often to run the mouse message timer in seconds.")
293 (defun org-ref-mouse-messages-on ()
294 "Turn on mouse messages."
296 (or org-ref-message-timer-mouse
297 (setq org-ref-message-timer-mouse
298 (run-at-time "0.5 sec"
299 org-ref-mouse-message-interval
300 'org-ref-mouse-message))))
303 (defun org-ref-mouse-messages-off ()
304 "Turn off mouse messages."
306 (cancel-timer org-ref-message-timer-mouse)
307 (setq org-ref-message-timer-mouse nil)
308 (message "Mouse messages are off"))
310 ;; Colorizing org-ref links
311 (defcustom org-ref-colorize-links
313 "When non-nil, change colors of links."
317 (defcustom org-ref-cite-color
319 "Color of cite like links."
323 (defcustom org-ref-ref-color
325 "Color of ref like links."
329 (defcustom org-ref-label-color
331 "Color of label links."
335 (defvar org-ref-cite-re nil
336 "Regexp for cite links.")
339 (setq org-ref-cite-re
340 (concat "\\(" (mapconcat
342 (replace-regexp-in-string "\*" "\\\\*" x)
344 org-ref-cite-types "\\|") "\\)"
345 ":\\([a-zA-Z0-9-_:\\./]*,?\\)*"))
348 (defvar org-ref-label-re
349 "label:\\([a-zA-Z0-9-_:]*,?\\)*")
352 (defvar org-ref-ref-re
353 "\\(eq\\)?ref:\\([a-zA-Z0-9-_:]*,?\\)*")
356 (defface org-ref-cite-face
357 `((t (:inherit org-link :foreground ,org-ref-cite-color)))
358 "Color for cite-like links in org-ref.")
361 (defface org-ref-label-face
362 `((t (:inherit org-link :foreground ,org-ref-label-color)))
363 "Color for ref links in org-ref.")
366 (defface org-ref-ref-face
367 `((t (:inherit org-link :foreground ,org-ref-ref-color)))
368 "Face for ref links in org-ref.")
371 (defun org-ref-colorize-links ()
372 "Colorize org-ref links."
374 (highlight-regexp org-ref-cite-re 'org-ref-cite-face)
375 (highlight-regexp org-ref-label-re 'org-ref-label-face)
376 (highlight-regexp org-ref-ref-re 'org-ref-ref-face))
379 (when org-ref-colorize-links
380 (add-hook 'org-mode-hook 'org-ref-colorize-links))
382 ;; * General org-ref utilities
383 (defun org-ref-strip-string (string)
384 "Strip leading and trailing whitespace from the STRING."
385 (replace-regexp-in-string
386 (concat search-whitespace-regexp "$" ) ""
387 (replace-regexp-in-string
388 (concat "^" search-whitespace-regexp ) "" string)))
390 (defun org-ref-split-and-strip-string (string)
391 "Split key-string and strip keys in STRING.
392 Assumes the key-string is comma delimited."
393 (mapcar 'org-ref-strip-string (split-string string ",")))
395 (defun org-ref-reftex-get-bib-field (field entry &optional format)
396 "Similar to reftex-get-bib-field, but removes enclosing braces and quotes in FIELD in the bibtex ENTRY.
397 Optional argument FORMAT bibtex format."
399 (setq result (reftex-get-bib-field field entry format))
400 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
401 (setq result (substring result 1 -1)))
402 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
403 (setq result (substring result 1 -1)))
406 (defun org-ref-reftex-format-citation (entry format)
407 "Return a formatted string for the bibtex ENTRY (from bibtex-parse-entry) according to the FORMAT argument.
408 The format is a string with these percent escapes.
410 In the format, the following percent escapes will be expanded.
412 %l The BibTeX label of the citation.
413 %a List of author names, see also `reftex-cite-punctuation'.
414 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
415 %A First author name only.
416 %e Works like %a, but on list of editor names. (%2e and %E work a well)
418 It is also possible to access all other BibTeX database fields:
419 %b booktitle %c chapter %d edition %h howpublished
420 %i institution %j journal %k key %m month
421 %n number %o organization %p pages %P first page
422 %r address %s school %u publisher %t title
424 %B booktitle, abbreviated %T title, abbreviated
429 Usually, only %l is needed. The other stuff is mainly for the echo area
430 display, and for (setq reftex-comment-citations t).
432 %< as a special operator kills punctuation and space around it after the
433 string has been formatted.
435 A pair of square brackets indicates an optional argument, and RefTeX
436 will prompt for the values of these arguments.
438 Beware that all this only works with BibTeX database files. When
439 citations are made from the \bibitems in an explicit thebibliography
440 environment, only %l is available."
441 ;; Format a citation from the info in the BibTeX ENTRY
442 (unless (stringp format) (setq format "\\cite{%l}"))
444 (if (and reftex-comment-citations
445 (string-match "%l" reftex-cite-comment-format))
446 (error "Reftex-cite-comment-format contains invalid %%l"))
449 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
451 (let ((n (string-to-number (match-string 4 format)))
452 (l (string-to-char (match-string 5 format)))
458 (org-ref-reftex-get-bib-field "&key" entry)
459 (if reftex-comment-citations
460 reftex-cite-comment-format
462 ((= l ?a) (replace-regexp-in-string
465 (reftex-get-bib-names "author" entry)
467 ((= l ?A) (replace-regexp-in-string
469 (car (reftex-get-bib-names "author" entry))))
470 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
471 ((= l ?B) (reftex-abbreviate-title
472 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
473 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
474 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
475 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
476 ((= l ?e) (reftex-format-names
477 (reftex-get-bib-names "editor" entry)
479 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
480 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
481 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
482 ((= l ?j) (let ((jt (reftex-get-bib-field "journal" entry)))
484 (reftex-get-bib-field "journaltitle" entry)
486 ((= l ?k) (org-ref-reftex-get-bib-field "=key=" entry))
487 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
488 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
489 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
490 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
491 ((= l ?P) (car (split-string
492 (org-ref-reftex-get-bib-field "pages" entry)
494 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
495 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
496 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
497 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
498 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
499 ;; strip enclosing brackets from title if they are there
500 ((= l ?t) (replace-regexp-in-string
502 (org-ref-reftex-get-bib-field "title" entry)))
503 ((= l ?T) (reftex-abbreviate-title
504 ((replace-regexp-in-string
506 (org-ref-reftex-get-bib-field "title" entry)))))
507 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
508 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
511 (setq b (match-beginning 2) e (match-end 2))
512 (setq b (match-beginning 3) e (match-end 3)))
513 (setq format (concat (substring format 0 b) rpl (substring format e)))))
514 (while (string-match "%%" format)
515 (setq format (replace-match "%" t t format)))
516 (while (string-match "[ ,.;:]*%<" format)
517 (setq format (replace-match "" t t format)))
520 (defun org-ref-get-bibtex-entry-citation (key)
521 "Return a string for the bibliography entry corresponding to KEY.
522 Format according to the type in `org-ref-bibliography-entry-format'."
524 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
525 (file) (entry) (bibtex-entry) (entry-type) (format))
527 (setq file (catch 'result
528 (cl-loop for file in org-ref-bibliography-files do
529 (if (org-ref-key-in-file-p key (file-truename file))
531 (message "%s not found in %s"
532 key (file-truename file))))))
535 (insert-file-contents file)
536 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
537 (bibtex-search-entry key nil 0)
538 (setq bibtex-entry (bibtex-parse-entry))
539 ;; downcase field names so they work in the format-citation code
540 (dolist (cons-cell bibtex-entry)
541 (setf (car cons-cell) (downcase (car cons-cell))))
542 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
543 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
545 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
546 ;; if no format, we use the bibtex entry itself as a fallback
548 (bibtex-narrow-to-entry)
549 (setq entry (buffer-string)))))
552 (defun org-ref-get-bibtex-keys ()
553 "Return a list of unique keys in the buffer."
555 (org-element-map (org-element-parse-buffer) 'link
557 (let ((plist (nth 1 link)))
558 (when (-contains? org-ref-cite-types (plist-get plist ':type))
561 (org-ref-split-and-strip-string (plist-get plist ':path)))
562 (when (not (-contains? keys key))
563 (setq keys (append keys (list key))))))))
564 ;; set with-affiliated to get keys in captions
566 ;; Sort keys alphabetically
567 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
570 (defun org-ref-get-bibtex-entry-html (key)
571 "Return an html string for the bibliography entry corresponding to KEY."
573 (setq output (org-ref-get-bibtex-entry-citation key))
575 (setq output (replace-regexp-in-string "\\\\&" "&" output))
576 ;; hack to replace {} around text
577 (setq output (replace-regexp-in-string "{" "" output))
578 (setq output (replace-regexp-in-string "}" "" output))
579 ;; get rid of empty parens
580 (setq output (replace-regexp-in-string "()" "" output))
581 ;; get rid of empty link and doi
582 (setq output (replace-regexp-in-string " <a href=\"\">link</a>\\." "" output))
583 ;; change double dash to single dash
584 (setq output (replace-regexp-in-string "--" "-" output))
585 (setq output (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" output))
586 (format "<li><a id=\"%s\">[%s] %s</a></li>"
589 (defun org-ref-get-html-bibliography ()
590 "Create an html bibliography when there are keys."
591 (let ((keys (org-ref-get-bibtex-keys)))
593 (concat "<h1>Bibliography</h1>
595 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
598 (defun org-ref-get-bibtex-entry-org (key)
599 "Return an org string for the bibliography entry corresponding to KEY."
600 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
601 (file) (entry) (bibtex-entry) (entry-type) (format))
603 (setq file (catch 'result
604 (cl-loop for file in org-ref-bibliography-files do
605 (if (org-ref-key-in-file-p key (file-truename file))
607 (message "%s not found in %s" key (file-truename file))))))
610 (insert-file-contents file)
611 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
612 (bibtex-search-entry key nil 0)
613 (setq entry (bibtex-parse-entry))
618 " (org-ref-reftex-get-bib-field "author" entry)
619 (org-ref-reftex-get-bib-field "title" entry)
620 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
621 (mapconcat (lambda (element) (format " :%s: %s"
622 (upcase (car element))
627 (defun org-ref-get-org-bibliography ()
628 "Create an org bibliography when there are keys."
629 (let ((keys (org-ref-get-bibtex-keys)))
631 (concat "* Bibliography
633 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
636 (defun org-ref-get-bibtex-entry-ascii (key)
637 "Return an ascii string for the bibliography entry corresponding to KEY."
639 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
641 (defun org-ref-get-ascii-bibliography ()
642 "Create an html bibliography when there are keys."
643 (let ((keys (org-ref-get-bibtex-keys)))
649 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
653 ;; ** bibliography and bibliographystyle
654 (org-add-link-type "bibliography"
655 ;; this code is run on clicking. The bibliography
656 ;; may contain multiple files. this code finds the
657 ;; one you clicked on and opens it.
658 (lambda (link-string)
659 ;; get link-string boundaries we have to go to the
660 ;; beginning of the line, and then search forward
662 ;; object is the link you clicked on
663 (object (org-element-context))
664 (link-string-beginning)
668 (goto-char (org-element-property :begin object))
669 (search-forward link-string nil nil 1)
670 (setq link-string-beginning (match-beginning 0))
671 (setq link-string-end (match-end 0)))
673 ;; Make sure point is in the link-path.
674 (if (< cp link-string-beginning)
675 (goto-char link-string-beginning))
676 ;; We set the reftex-default-bibliography
677 ;; here. it should be a local variable only in
678 ;; the current buffer. We need this for using
679 ;; reftex to do citations.
680 (set (make-local-variable 'reftex-default-bibliography)
682 (org-element-property :path object) ","))
684 (let (key-beginning key-end)
685 ;; now if we have comma separated bibliographies
686 ;; we find the one clicked on. we want to
687 ;; search forward to next comma from point
689 (if (search-forward "," link-string-end 1 1)
691 (setq key-end (- (match-end 0) 1))
692 ;; no comma found so take the point
693 (setq key-end (point))))
694 ;; and backward to previous comma from point
696 (if (search-backward "," link-string-beginning 1 1)
698 (setq key-beginning (+ (match-beginning 0) 1))
699 (setq key-beginning (point)))) ; no match found
700 ;; save the key we clicked on.
701 (setq bibfile (org-ref-strip-string
702 (buffer-substring key-beginning key-end)))
703 ;; open file on click
704 (find-file bibfile))))
707 (lambda (keyword desc format)
709 ((eq format 'org) (org-ref-get-org-bibliography))
710 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
711 ((eq format 'html) (org-ref-get-html-bibliography))
713 ;; write out the latex bibliography command
714 (format "\\bibliography{%s}"
715 (replace-regexp-in-string
719 (mapcar 'expand-file-name
720 (split-string keyword ","))
723 (org-add-link-type "nobibliography"
724 ;; this code is run on clicking. The bibliography
725 ;; may contain multiple files. this code finds the
726 ;; one you clicked on and opens it.
727 (lambda (link-string)
728 ;; get link-string boundaries
729 ;; we have to go to the beginning of the line, and then search forward
732 ;; object is the link you clicked on
733 (object (org-element-context))
735 (link-string-beginning)
739 (goto-char (org-element-property :begin object))
740 (search-forward link-string nil nil 1)
741 (setq link-string-beginning (match-beginning 0))
742 (setq link-string-end (match-end 0)))
744 ;; We set the reftex-default-bibliography
745 ;; here. it should be a local variable only in
746 ;; the current buffer. We need this for using
747 ;; reftex to do citations.
748 (set (make-local-variable 'reftex-default-bibliography)
749 (split-string (org-element-property :path object) ","))
751 (let (key-beginning key-end)
752 ;; now if we have comma separated bibliographies
753 ;; we find the one clicked on. we want to
754 ;; search forward to next comma from point
756 (if (search-forward "," link-string-end 1 1)
757 (setq key-end (- (match-end 0) 1)) ; we found a match
758 (setq key-end (point)))) ; no comma found so take the point
759 ;; and backward to previous comma from point
761 (if (search-backward "," link-string-beginning 1 1)
762 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
763 (setq key-beginning (point)))) ; no match found
764 ;; save the key we clicked on.
765 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
766 (find-file bibfile)))) ; open file on click
769 (lambda (keyword desc format)
771 ((eq format 'org) (org-ref-get-org-bibliography))
772 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
773 ((eq format 'html) (org-ref-get-html-bibliography))
775 ;; write out the latex bibliography command
776 (format "\\nobibliography{%s}"
777 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
778 (mapcar 'expand-file-name
779 (split-string keyword ","))
782 (org-add-link-type "printbibliography"
783 (lambda (arg) (message "Nothing implemented for clicking here."))
784 (lambda (keyword desc format)
786 ((eq format 'org) (org-ref-get-org-bibliography))
787 ((eq format 'html) (org-ref-get-html-bibliography))
789 ;; write out the biblatex bibliography command
790 "\\printbibliography"))))
792 (org-add-link-type "bibliographystyle"
793 (lambda (arg) (message "Nothing implemented for clicking here."))
794 (lambda (keyword desc format)
797 ;; write out the latex bibliography command
798 (format "\\bibliographystyle{%s}" keyword))
799 ;; Other styles should not have an output for this
804 (defun org-bibliographystyle-complete-link (&optional arg)
805 "Completion function for bibliographystyle link.
807 (format "bibliographystyle:%s" (ido-completing-read
809 '("unsrt" "plain" "alpha"
811 ;; https://www.sharelatex.com/learn/Natbib_bibliography_styles
812 "dinat" "humannat" "plainnat"
813 "abbrnat" "unsrtnat" "rusnat"
817 (defun org-bibliography-complete-link (&optional arg)
818 "Completion function for bibliography link.
820 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
823 (defun org-ref-insert-bibliography-link ()
824 "Insert a bibliography with completion."
826 (insert (org-bibliography-complete-link)))
830 (org-add-link-type "addbibresource"
831 ;; this code is run on clicking. The addbibresource
832 ;; may contain multiple files. this code finds the
833 ;; one you clicked on and opens it.
834 (lambda (link-string)
835 ;; get link-string boundaries
836 ;; we have to go to the beginning of the line, and then search forward
839 ;; object is the link you clicked on
840 (object (org-element-context))
842 (link-string-beginning)
846 (goto-char (org-element-property :begin object))
847 (search-forward link-string nil nil 1)
848 (setq link-string-beginning (match-beginning 0))
849 (setq link-string-end (match-end 0)))
851 ;; We set the reftex-default-addbibresource
852 ;; here. it should be a local variable only in
853 ;; the current buffer. We need this for using
854 ;; reftex to do citations.
855 (set (make-local-variable 'reftex-default-addbibresource)
856 (split-string (org-element-property :path object) ","))
858 (let (key-beginning key-end)
859 ;; now if we have comma separated bibliographies
860 ;; we find the one clicked on. we want to
861 ;; search forward to next comma from point
863 (if (search-forward "," link-string-end 1 1)
864 (setq key-end (- (match-end 0) 1)) ; we found a match
865 (setq key-end (point)))) ; no comma found so take the point
866 ;; and backward to previous comma from point
868 (if (search-backward "," link-string-beginning 1 1)
869 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
870 (setq key-beginning (point)))) ; no match found
871 ;; save the key we clicked on.
872 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
873 (find-file bibfile)))) ; open file on click
876 (lambda (keyword desc format)
878 ((eq format 'html) (format "")); no output for html
880 ;; write out the latex addbibresource command
881 (format "\\addbibresource{%s}" keyword)))))
883 ;; ** List of figures
884 (defun org-ref-list-of-figures (&optional arg)
885 "Generate buffer with list of figures in them.
888 (save-excursion (widen)
889 (let* ((c-b (buffer-name))
892 (org-element-map (org-element-parse-buffer) 'link
894 "create a link for to the figure"
896 (and (string= (org-element-property :type link) "file")
898 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
899 (org-element-property :path link)))
902 (let* ((start (org-element-property :begin link))
903 (parent (car (cdr (org-element-property :parent link))))
904 (caption (cl-caaar (plist-get parent :caption)))
905 (name (plist-get parent :name)))
908 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
909 c-b start counter (or name "") caption)
911 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
912 c-b start counter (or name "")))))))))
913 (switch-to-buffer "*List of Figures*")
914 (setq buffer-read-only nil)
917 (insert (mapconcat 'identity list-of-figures ""))
918 (setq buffer-read-only t)
919 (use-local-map (copy-keymap org-mode-map))
920 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
924 'org-ref-list-of-figures ; on click
925 (lambda (keyword desc format)
928 (format "\\listoffigures")))))
931 (defun org-ref-list-of-tables (&optional arg)
932 "Generate a buffer with a list of tables.
937 (let* ((c-b (buffer-name))
940 (org-element-map (org-element-parse-buffer 'element) 'table
942 "create a link for to the table"
944 (let ((start (org-element-property :begin table))
945 (name (org-element-property :name table))
946 (caption (cl-caaar (org-element-property :caption table))))
949 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
950 c-b start counter (or name "") caption)
952 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
953 c-b start counter (or name ""))))))))
954 (switch-to-buffer "*List of Tables*")
955 (setq buffer-read-only nil)
958 (insert (mapconcat 'identity list-of-tables ""))
959 (setq buffer-read-only t)
960 (use-local-map (copy-keymap org-mode-map))
961 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
965 'org-ref-list-of-tables
966 (lambda (keyword desc format)
969 (format "\\listoftables")))))
973 (defun org-ref-count-labels (label)
974 "Counts number of matches for LABEL in the document."
975 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
976 ;; for tblname, it is not enough to get word boundary
977 ;; tab-little and tab-little-2 match then.
978 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
979 (count-matches (format "\\label{%s}" label) (point-min) (point-max))
980 ;; this is the org-format #+label:
981 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
982 (let ((custom-id-count 0))
985 (when (string= label (org-entry-get (point) "CUSTOM_ID"))
986 (setq custom-id-count (+ 1 custom-id-count)))))
992 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
993 (let ((count (org-ref-count-labels label)))
994 (message (format "%s occurence%s"
1000 (org-ref-count-labels label))))
1001 (lambda (keyword desc format)
1003 ((eq format 'html) (format "<div id=\"%s\">" keyword))
1005 (format "\\label{%s}" keyword)))))
1007 (defun org-label-store-link ()
1008 "Store a link to a label. The output will be a ref to that label."
1009 ;; First we have to make sure we are on a label link.
1010 (let* ((object (org-element-context)))
1011 (when (and (equal (org-element-type object) 'link)
1012 (equal (org-element-property :type object) "label"))
1013 (org-store-link-props
1015 :link (concat "ref:" (org-element-property :path object))))
1017 ;; Store link on table
1018 (when (equal (org-element-type object) 'table)
1019 (org-store-link-props
1021 :link (concat "ref:" (org-element-property :name object))))
1023 ;; store link on heading with custom_id
1024 ;; this is not a ref link, but it is still what you want
1025 (when (and (equal (org-element-type object) 'headline)
1026 (org-entry-get (point) "CUSTOM_ID"))
1027 (org-store-link-props
1029 :link (format "[[#%s]]" (org-entry-get (point) "CUSTOM_ID"))))
1031 ;; and to #+label: lines
1033 (when (and (equal (org-element-type object) 'paragraph)
1034 (org-element-property :name object))
1035 (org-store-link-props
1037 :link (concat "ref:" (org-element-property :name object))))))
1039 (add-hook 'org-store-link-functions 'org-label-store-link)
1045 "on clicking goto the label. Navigate back with C-c &"
1046 (org-mark-ring-push)
1047 ;; next search from beginning of the buffer
1048 ;; it is possible you would not find the label if narrowing is in effect
1054 (goto-char (point-min))
1055 (re-search-forward (format "label:%s\\b" label) nil t))
1059 (goto-char (point-min))
1060 (re-search-forward (format "\\label{%s}" label) nil t))
1062 ;; #+label: name org-definition
1064 (goto-char (point-min))
1066 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1070 (goto-char (point-min))
1072 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1074 ;; we did not find anything, so go back to where we came
1075 (org-mark-ring-goto)
1076 (error "%s not found" label))
1078 (message "go back with (org-mark-ring-goto) `C-c &`"))
1080 (lambda (keyword desc format)
1082 ((eq format 'html) (format "<a href=\"#%s\">%s</a>" keyword keyword))
1084 (format "\\ref{%s}" keyword)))))
1087 (defun org-ref-get-org-labels ()
1088 "Return a list of #+LABEL: labels."
1090 (goto-char (point-min))
1091 (let ((matches '()))
1092 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1093 ;; do not do this for tables. We get those in `org-ref-get-tblnames'.
1094 ;; who would have thought you have save match data here? Trust me. When
1095 ;; I wrote this, you did.
1096 (unless (save-match-data (equal (car (org-element-at-point)) 'table))
1097 (add-to-list 'matches (match-string-no-properties 1) t)))
1101 (defun org-ref-get-custom-ids ()
1102 "Return a list of custom_id properties in the buffer."
1103 (let ((results '()) custom_id)
1106 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1107 (when (not (null custom_id))
1108 (setq results (append results (list custom_id)))))))
1112 (defun org-ref-get-latex-labels ()
1113 "Return list of matchin LaTeX defined labels in buffer."
1115 (goto-char (point-min))
1116 (let ((matches '()))
1117 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1118 (add-to-list 'matches (match-string-no-properties 1) t))
1122 (defun org-ref-get-tblnames ()
1123 "Return list of table names in the buffer."
1124 (org-element-map (org-element-parse-buffer 'element) 'table
1126 (org-element-property :name table))))
1129 (defun org-ref-get-labels ()
1130 "Return a list of labels in the buffer that you can make a ref link to.
1131 This is used to complete ref links and in helm menus."
1135 (goto-char (point-min))
1136 (let ((matches '()))
1137 ;; these are the org-ref label:stuff kinds
1138 (while (re-search-forward
1139 "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1140 (add-to-list 'matches (match-string-no-properties 1) t))
1141 ;; now add all the other kinds of labels.
1144 (org-ref-get-org-labels)
1146 (org-ref-get-latex-labels)
1147 ;; #+tblname: and actually #+label
1148 (org-ref-get-tblnames)
1150 (org-ref-get-custom-ids))))))
1153 (defun org-ref-helm-insert-label-link ()
1154 "Insert a label link. helm just shows you what labels already exist.
1155 If you are on a label link, replace it."
1157 (let* ((labels (org-ref-get-labels))
1158 (cb (current-buffer)))
1159 (helm :sources `(((name . "Existing labels")
1160 (candidates . ,labels)
1161 ;; default action is to open to the label
1162 (action . (lambda (label)
1163 ;; unfortunately I do not have markers here
1164 (org-open-link-from-string
1165 (format "ref:%s" label))))
1166 ;; if you select a label, replace current one
1167 (action . (lambda (label)
1168 (switch-to-buffer ,cb)
1170 ;; no prefix or on a link
1171 ((equal helm-current-prefix-arg nil)
1172 (let* ((object (org-element-context))
1173 (last-char (save-excursion
1174 (goto-char (org-element-property :end object))
1176 (if (looking-at " ")
1179 (when (-contains? '("label")
1180 (org-element-property :type object))
1181 ;; we are on a link, so replace it.
1184 (org-element-property :begin object)
1185 (org-element-property :end object))
1187 (replace-regexp-in-string
1188 (org-element-property :path object)
1190 (org-element-property :raw-link object))
1192 ;; no prefix options defined
1194 ;; no matching selection creates a new label
1195 ((name . "Create new label")
1197 ;; default action creates a new label, or replaces old one
1198 (action . (lambda (label)
1199 (switch-to-buffer ,cb)
1200 (let* ((object (org-element-context))
1201 (last-char (save-excursion
1202 (goto-char (org-element-property :end object))
1204 (if (looking-at " ")
1207 (if (-contains? '("label")
1208 (org-element-property :type object))
1209 ;; we are on a link, so replace it.
1212 (org-element-property :begin object)
1213 (org-element-property :end object))
1215 (replace-regexp-in-string
1216 (org-element-property :path object)
1218 (org-element-property :raw-link object))
1225 helm-pattern))))))))))))
1228 (defun org-ref-complete-link (&optional arg)
1229 "Completion function for ref links.
1230 Optional argument ARG Does nothing."
1232 (setq label (completing-read "label: " (org-ref-get-labels)))
1233 (format "ref:%s" label)))
1236 (defun org-ref-insert-ref-link ()
1237 "Completion function for a ref link."
1239 (insert (org-ref-complete-link)))
1242 (defun org-ref-helm-insert-ref-link ()
1243 "Helm menu to insert ref links to labels in the document.
1244 If you are on link, replace with newly selected label.
1245 Use C-u to insert a different kind of ref link.
1246 Use C-u C-u to insert a [[#custom-id]] link"
1248 (let* ((labels (org-ref-get-labels))
1249 (bs (buffer-string))
1250 (contexts (with-temp-buffer
1252 (mapcar 'org-ref-get-label-context labels)))
1253 (cb (current-buffer)))
1255 (helm :input (thing-at-point 'word)
1256 :sources `(((name . "Available labels to ref")
1257 (candidates . ,(cl-loop for label in labels
1258 for context in contexts
1259 ;; we do some kludgy adding spaces
1260 ;; and bars to make it "easier" to
1262 collect (cons (concat
1267 (split-string context "\n")
1270 ;; default action to replace or insert ref link.
1271 (action . (lambda (label)
1272 (switch-to-buffer ,cb)
1275 ;; no prefix or on a link
1276 ((equal helm-current-prefix-arg nil)
1277 (let* ((object (org-element-context))
1278 (last-char (save-excursion
1279 (goto-char (org-element-property :end object))
1281 (if (looking-at " ")
1284 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1285 (org-element-property :type object))
1286 ;; we are on a link, so replace it.
1289 (org-element-property :begin object)
1290 (org-element-property :end object))
1292 (replace-regexp-in-string
1293 (org-element-property :path object)
1295 (org-element-property :raw-link object))
1297 ;; insert a new link
1302 ;; one prefix, alternate ref link
1303 ((equal helm-current-prefix-arg '(4))
1306 (helm :sources '((name . "Ref link types")
1307 (candidates . ("ref" "eqref" "pageref" "nameref"))
1308 (action . (lambda (x) x))))
1310 ;; two prefixes, insert section custom-id link
1311 ((equal helm-current-prefix-arg '(16))
1313 (format "[[#%s]]" label)))
1321 "on clicking goto the label. Navigate back with C-c &"
1322 (org-mark-ring-push)
1323 ;; next search from beginning of the buffer
1329 (goto-char (point-min))
1330 (re-search-forward (format "label:%s\\b" label) nil t))
1334 (goto-char (point-min))
1335 (re-search-forward (format "\\label{%s}" label) nil t))
1337 ;; #+label: name org-definition
1339 (goto-char (point-min))
1341 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1345 (goto-char (point-min))
1347 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1348 ;; we did not find anything, so go back to where we came
1349 (org-mark-ring-goto)
1350 (error "%s not found" label))
1351 (message "go back with (org-mark-ring-goto) `C-c &`"))
1353 (lambda (keyword desc format)
1355 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1357 (format "\\pageref{%s}" keyword)))))
1360 (defun org-pageref-complete-link (&optional arg)
1361 "Completion function for ref links.
1362 Optional argument ARG Does nothing."
1364 (setq label (completing-read "label: " (org-ref-get-labels)))
1365 (format "ref:%s" label)))
1368 (defun org-pageref-insert-ref-link ()
1369 "Insert a pageref link with completion."
1371 (insert (org-pageref-complete-link)))
1378 "on clicking goto the label. Navigate back with C-c &"
1379 (org-mark-ring-push)
1380 ;; next search from beginning of the buffer
1386 (goto-char (point-min))
1387 (re-search-forward (format "\\label{%s}" label) nil t))
1389 ;; we did not find anything, so go back to where we came
1390 (org-mark-ring-goto)
1391 (error "%s not found" label))
1392 (message "go back with (org-mark-ring-goto) `C-c &`"))
1394 (lambda (keyword desc format)
1396 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1398 (format "\\nameref{%s}" keyword)))))
1405 "on clicking goto the label. Navigate back with C-c &"
1406 (org-mark-ring-push)
1407 ;; next search from beginning of the buffer
1409 (goto-char (point-min))
1412 ;; search forward for the first match
1414 (re-search-forward (format "label:%s" label) nil t)
1416 (re-search-forward (format "\\label{%s}" label) nil t)
1417 ;; #+label: name org-definition
1418 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1419 (org-mark-ring-goto)
1420 (error "%s not found" label))
1421 (message "go back with (org-mark-ring-goto) `C-c &`"))
1423 (lambda (keyword desc format)
1425 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1427 (format "\\eqref{%s}" keyword)))))
1431 (defun org-ref-get-bibtex-key-under-cursor ()
1432 "Return key under the bibtex cursor.
1433 We search forward from
1434 point to get a comma, or the end of the link, and then backwards
1435 to get a comma, or the beginning of the link. that delimits the
1436 keyword we clicked on. We also strip the text properties."
1437 (let* ((object (org-element-context))
1438 (link-string (org-element-property :path object)))
1439 ;; you may click on the part before the citations. here we make
1440 ;; sure to move to the beginning so you get the first citation.
1442 (goto-char (org-element-property :begin object))
1443 (search-forward link-string (org-element-property :end object))
1444 (goto-char (match-beginning 0))
1445 ;; check if we clicked before the path and move as needed.
1446 (unless (< cp (point))
1449 (if (not (org-element-property :contents-begin object))
1450 ;; this means no description in the link
1452 ;; we need the link path start and end
1453 (let (link-string-beginning link-string-end)
1455 (goto-char (org-element-property :begin object))
1456 (search-forward link-string nil nil 1)
1457 (setq link-string-beginning (match-beginning 0))
1458 (setq link-string-end (match-end 0)))
1460 (let (key-beginning key-end)
1461 ;; The key is the text between commas, or the link boundaries
1463 (if (search-forward "," link-string-end t 1)
1464 (setq key-end (- (match-end 0) 1)) ; we found a match
1465 (setq key-end link-string-end))) ; no comma found so take the end
1466 ;; and backward to previous comma from point which defines the start character
1468 (if (search-backward "," link-string-beginning 1 1)
1469 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1470 (setq key-beginning link-string-beginning))) ; no match found
1471 ;; save the key we clicked on.
1473 (org-ref-strip-string
1474 (buffer-substring key-beginning key-end))))
1475 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1477 ;; link with description. assume only one key
1480 (defun org-ref-find-bibliography ()
1481 "Find the bibliography in the buffer.
1482 This function sets and returns cite-bibliography-files, which is a list of files
1483 either from bibliography:f1.bib,f2.bib
1484 \bibliography{f1,f2}
1485 internal bibliographies
1487 falling back to what the user has set in `org-ref-default-bibliography'"
1490 (goto-char (point-min))
1491 ;; look for a bibliography link
1492 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1493 (setq org-ref-bibliography-files
1494 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1495 (throw 'result org-ref-bibliography-files))
1498 ;; we did not find a bibliography link. now look for \bibliography
1499 (goto-char (point-min))
1500 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1501 ;; split, and add .bib to each file
1502 (setq org-ref-bibliography-files
1503 (mapcar (lambda (x) (concat x ".bib"))
1504 (mapcar 'org-ref-strip-string
1505 (split-string (match-string 1) ","))))
1506 (throw 'result org-ref-bibliography-files))
1508 ;; no bibliography found. maybe we need a biblatex addbibresource
1509 (goto-char (point-min))
1510 ;; look for a bibliography link
1511 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1512 (setq org-ref-bibliography-files
1513 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1514 (throw 'result org-ref-bibliography-files))
1516 ;; we did not find anything. use defaults
1517 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1519 ;; set reftex-default-bibliography so we can search
1520 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1521 org-ref-bibliography-files)
1523 (defun org-ref-key-in-file-p (key filename)
1524 "Determine if the KEY is in the FILENAME."
1525 (save-current-buffer
1526 (let ((bibtex-files (list filename)))
1527 ;; This is something I am trying because when the bibtex file is open, and
1528 ;; you have added to it, the only way I find to get the update to update
1529 ;; is to close it and reopen it. or to save it and revert it.
1530 (when (get-file-buffer filename)
1531 (set-buffer (get-file-buffer filename))
1533 (revert-buffer t t))
1534 (bibtex-search-entry key t))))
1536 (defun org-ref-get-bibtex-key-and-file (&optional key)
1537 "Return the bibtex KEY and file that it is in. If no key is provided, get one under point."
1538 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1541 (setq key (org-ref-get-bibtex-key-under-cursor)))
1542 (setq file (catch 'result
1543 (cl-loop for file in org-ref-bibliography-files do
1544 (if (org-ref-key-in-file-p key (file-truename file))
1545 (throw 'result file)))))
1548 ;; *** key at point functions
1550 (defun org-ref-get-pdf-filename (key)
1551 "Return the pdf filename associated with a bibtex KEY."
1552 (format (concat org-ref-pdf-directory "%s.pdf") key))
1554 (defun org-ref-open-pdf-at-point ()
1555 "Open the pdf for bibtex key under point if it exists."
1557 (let* ((results (org-ref-get-bibtex-key-and-file))
1559 (pdf-file (funcall org-ref-get-pdf-filename-function key)))
1560 (if (file-exists-p pdf-file)
1561 (org-open-file pdf-file)
1562 (message "no pdf found for %s" key))))
1565 (defun org-ref-open-url-at-point ()
1566 "Open the url for bibtex key under point."
1568 (let* ((results (org-ref-get-bibtex-key-and-file))
1570 (bibfile (cdr results)))
1573 (insert-file-contents bibfile)
1574 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1575 (bibtex-search-entry key)
1576 ;; I like this better than bibtex-url which does not always find
1579 (let ((url (bibtex-autokey-get-field "url")))
1581 (browse-url (s-trim url))
1584 (let ((doi (bibtex-autokey-get-field "doi")))
1586 (if (string-match "^http" doi)
1588 (browse-url (format "http://dx.doi.org/%s" (s-trim doi))))
1589 (throw 'done nil))))))))
1592 (defun org-ref-open-notes-at-point ()
1593 "Open the notes for bibtex key under point."
1595 (let* ((results (org-ref-get-bibtex-key-and-file))
1597 (bibfile (cdr results)))
1600 (insert-file-contents bibfile)
1601 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1602 (bibtex-search-entry key)
1603 (org-ref-open-bibtex-notes)))))
1606 (defun org-ref-citation-at-point ()
1607 "Give message of current citation at point."
1609 (let* ((cb (current-buffer))
1610 (results (org-ref-get-bibtex-key-and-file))
1612 (bibfile (cdr results)))
1613 (message "%s" (progn
1615 (insert-file-contents bibfile)
1616 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1617 (bibtex-search-entry key)
1618 (org-ref-bib-citation))))))
1621 (defun org-ref-open-citation-at-point ()
1622 "Open bibtex file to key at point."
1624 (let* ((cb (current-buffer))
1625 (results (org-ref-get-bibtex-key-and-file))
1627 (bibfile (cdr results)))
1629 (bibtex-search-entry key)))
1633 (defvar org-ref-cite-menu-funcs '()
1634 "Functions to run on cite click menu.
1635 Each entry is a list of (key menu-name function).
1636 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.")
1639 (defvar org-ref-user-cite-menu-funcs
1640 '(("C" "rossref" org-ref-crossref-at-point)
1641 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1642 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1643 "User-defined functions to run on bibtex key at point.")
1646 (defun org-ref-copy-entry-as-summary ()
1647 "Copy the bibtex entry for the citation at point as a summary."
1649 (save-window-excursion
1650 (org-ref-open-citation-at-point)
1651 (kill-new (org-ref-bib-citation))))
1654 (defun org-ref-copy-entry-at-point-to-file ()
1655 "Copy the bibtex entry for the citation at point to NEW-FILE.
1656 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."
1658 (let ((new-file (ido-completing-read
1660 (append org-ref-default-bibliography
1661 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1662 (key (org-ref-get-bibtex-key-under-cursor)))
1663 (save-window-excursion
1664 (org-ref-open-citation-at-point)
1665 (bibtex-copy-entry-as-kill))
1667 (let ((bibtex-files (list (file-truename new-file))))
1668 (if (assoc key (bibtex-global-key-alist))
1669 (message "That key already exists in %s" new-file)
1671 (save-window-excursion
1672 (find-file new-file)
1673 (goto-char (point-max))
1674 ;; make sure we are at the beginning of a line.
1675 (unless (looking-at "^") (insert "\n\n"))
1680 (defun org-ref-get-doi-at-point ()
1681 "Get doi for key at point."
1682 (let* ((results (org-ref-get-bibtex-key-and-file))
1684 (bibfile (cdr results))
1688 (insert-file-contents bibfile)
1689 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1690 (bibtex-search-entry key)
1691 (setq doi (bibtex-autokey-get-field "doi"))
1692 ;; in case doi is a url, remove the url part.
1693 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1696 ;; **** functions that operate on key at point for click menu
1697 (defun org-ref-wos-at-point ()
1698 "Open the doi in wos for bibtex key under point."
1700 (doi-utils-wos (org-ref-get-doi-at-point)))
1703 (defun org-ref-wos-citing-at-point ()
1704 "Open the doi in wos citing articles for bibtex key under point."
1706 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1709 (defun org-ref-wos-related-at-point ()
1710 "Open the doi in wos related articles for bibtex key under point."
1712 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1715 (defun org-ref-google-scholar-at-point ()
1716 "Open the doi in google scholar for bibtex key under point."
1718 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1721 (defun org-ref-pubmed-at-point ()
1722 "Open the doi in pubmed for bibtex key under point."
1724 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1727 (defun org-ref-crossref-at-point ()
1728 "Open the doi in crossref for bibtex key under point."
1730 (doi-utils-crossref (org-ref-get-doi-at-point)))
1732 ;; *** Minibuffer menu
1734 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1735 "Action when a cite link is clicked on.
1736 Provides a menu of context sensitive actions. If the bibtex entry
1737 has a pdf, you get an option to open it. If there is a doi, you
1738 get a lot of options. LINK-STRING is used by the link function."
1740 (let* ((results (org-ref-get-bibtex-key-and-file))
1742 (pdf-file (funcall org-ref-get-pdf-filename-function key))
1743 (bibfile (cdr results))
1744 (url (save-excursion
1746 (insert-file-contents bibfile)
1747 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1748 (bibtex-search-entry key)
1749 (bibtex-autokey-get-field "url"))))
1750 (doi (save-excursion
1752 (insert-file-contents bibfile)
1753 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1754 (bibtex-search-entry key)
1755 ;; I like this better than bibtex-url which does not always find
1757 (bibtex-autokey-get-field "doi")))))
1759 (when (string= "" doi) (setq doi nil))
1760 (when (string= "" url) (setq url nil))
1761 (setq org-ref-cite-menu-funcs '())
1767 'org-ref-cite-menu-funcs
1768 '("o" "pen" org-ref-open-citation-at-point)))
1771 (when (file-exists-p pdf-file)
1773 'org-ref-cite-menu-funcs
1774 `("p" "df" ,org-ref-open-pdf-function) t))
1778 'org-ref-cite-menu-funcs
1779 '("n" "otes" org-ref-open-notes-at-point) t)
1784 'org-ref-cite-menu-funcs
1785 '("u" "rl" org-ref-open-url-at-point) t))
1790 'org-ref-cite-menu-funcs
1791 '("w" "os" org-ref-wos-at-point) t)
1794 'org-ref-cite-menu-funcs
1795 '("c" "iting" org-ref-wos-citing-at-point) t)
1798 'org-ref-cite-menu-funcs
1799 '("r" "elated" org-ref-wos-related-at-point) t)
1802 'org-ref-cite-menu-funcs
1803 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1806 'org-ref-cite-menu-funcs
1807 '("P" "ubmed" org-ref-pubmed-at-point) t))
1809 ;; add user functions
1810 (dolist (tup org-ref-user-cite-menu-funcs)
1812 'org-ref-cite-menu-funcs
1817 'org-ref-cite-menu-funcs
1818 '("q" "uit" (lambda ())) t)
1820 ;; now we make a menu
1821 ;; construct menu string as a message
1824 (let* ((results (org-ref-get-bibtex-key-and-file))
1826 (bibfile (cdr results)))
1829 (insert-file-contents bibfile)
1830 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1831 (bibtex-search-entry key)
1832 (org-ref-bib-citation))))
1836 (concat "[" (elt tup 0) "]"
1838 org-ref-cite-menu-funcs "")))
1840 (let* ((input (read-char-exclusive))
1842 (char-to-string input) org-ref-cite-menu-funcs)))
1843 ;; now run the function (2nd element in choice)
1850 ;; *** Generation of the cite links
1851 (defmacro org-ref-make-completion-function (type)
1852 "Macro to make a link completion function for a link of TYPE."
1853 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1859 (let ((bibtex-files (org-ref-find-bibliography)))
1860 (bibtex-global-key-alist))))))
1862 (defmacro org-ref-make-format-function (type)
1863 "Macro to make a format function for a link of TYPE."
1864 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1869 (format "[[#%s][%s]]" key key))
1870 (org-ref-split-and-strip-string keyword) ","))
1877 (org-ref-split-and-strip-string keyword) ",") "]"))
1882 (format "<a href=\"#%s\">%s</a>" key key))
1883 (org-ref-split-and-strip-string keyword) ","))
1886 (if (string= (substring type -1) "s")
1887 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1888 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1889 (org-ref-split-and-strip-string keyword) ""))
1891 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1892 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1894 ;; for markdown we generate pandoc citations
1897 (desc ;; pre and or post text
1898 (let* ((text (split-string desc "::"))
1902 (format "[@%s," keyword)
1903 (when pre (format " %s" pre))
1904 (when post (format ", %s" post))
1909 (lambda (key) (concat "@" key))
1910 (org-ref-split-and-strip-string keyword)
1913 (defun org-ref-format-citation-description (desc)
1914 "Return formatted citation description.
1915 If the cite link has a DESC (description), it is optional text
1916 for the citation command. You can specify pre and post text by
1917 separating these with ::, for example [[cite:key][pre text::post
1920 ((string-match "::" desc)
1921 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1922 (t (format "[%s]" desc))))
1924 (defun org-ref-define-citation-link (type &optional key)
1925 "Add a citation link of TYPE for org-ref.
1926 With optional KEY, set the reftex binding. For example:
1927 \(org-ref-define-citation-link \"citez\" ?z) will create a new
1928 citez link, with reftex key of z, and the completion function."
1929 (interactive "sCitation Type: \ncKey: ")
1931 ;; create the formatting function
1932 (eval `(org-ref-make-format-function ,type))
1937 org-ref-cite-onclick-function
1938 (quote ,(intern (format "org-ref-format-%s" type)))))
1940 ;; create the completion function
1941 (eval `(org-ref-make-completion-function ,type))
1943 ;; store new type so it works with adding citations, which checks
1944 ;; for existence in this list
1945 (add-to-list 'org-ref-cite-types type)
1947 ;; and finally if a key is specified, we modify the reftex menu
1949 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1950 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1951 `((,key . ,(concat type ":%l")))))))
1953 ;; create all the link types and their completion functions
1954 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1956 (defun org-ref-insert-cite-link (alternative-cite)
1957 "Insert a default citation link using reftex.
1958 If you are on a link, it appends to the end of the link,
1959 otherwise, a new link is inserted. Use a prefix
1960 arg (ALTERNATIVE-CITE) to get a menu of citation types."
1962 (org-ref-find-bibliography)
1963 (let* ((object (org-element-context))
1964 (link-string-beginning (org-element-property :begin object))
1965 (link-string-end (org-element-property :end object))
1966 (path (org-element-property :path object)))
1968 (if (not alternative-cite)
1971 ;; case where we are in a link
1972 ((and (equal (org-element-type object) 'link)
1973 (-contains? org-ref-cite-types (org-element-property :type object)))
1974 (goto-char link-string-end)
1975 ;; sometimes there are spaces at the end of the link
1976 ;; this code moves point pack until no spaces are there
1977 (while (looking-back " ") (backward-char))
1978 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1980 ;; We are next to a link, and we want to append
1983 (and (equal (org-element-type (org-element-context)) 'link)
1984 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1985 (while (looking-back " ") (backward-char))
1986 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1988 ;; insert fresh link
1991 (concat org-ref-default-citation-link
1993 (mapconcat 'identity (reftex-citation t) ",")))))
1995 ;; you pressed a C-u so we run this code
1996 (reftex-citation))))
1998 (defun org-ref-insert-cite-with-completion (type)
1999 "Insert a cite link of TYPE with completion."
2000 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
2001 (insert (funcall (intern (format "org-%s-complete-link" type)))))
2003 (defun org-ref-store-bibtex-entry-link ()
2004 "Save a citation link to the current bibtex entry. Save in the default link type."
2006 (let ((link (concat org-ref-default-citation-link
2009 (bibtex-beginning-of-entry)
2010 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
2011 (message "saved %s" link)
2012 (push (list link) org-stored-links)
2013 (car org-stored-links)))
2021 (lambda (path desc format)
2024 (format "\\index{%s}" path)))))
2026 ;; this will generate a temporary index of entries in the file.
2030 (let ((*index-links* '())
2031 (*initial-letters* '()))
2034 (org-element-map (org-element-parse-buffer) 'link
2036 (let ((type (nth 0 link))
2037 (plist (nth 1 link)))
2039 (when (equal (plist-get plist ':type) "index")
2042 (cons (plist-get plist :path)
2044 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2046 (plist-get plist :begin) ;; position of link
2047 ;; grab a description
2049 (goto-char (plist-get plist :begin))
2050 (if (thing-at-point 'sentence)
2052 (replace-regexp-in-string
2053 "\n" "" (thing-at-point 'sentence))
2054 ;; or call it a link
2058 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
2060 ;; now first letters
2061 (dolist (link *index-links*)
2062 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2064 ;; now create the index
2065 (switch-to-buffer (get-buffer-create "*index*"))
2068 (insert "#+TITLE: Index\n\n")
2069 (dolist (letter *initial-letters*)
2070 (insert (format "* %s\n" (upcase letter)))
2071 ;; now process the links
2074 (string= letter (substring (car (car *index-links*)) 0 1)))
2075 (let ((link (pop *index-links*)))
2076 (insert (format "%s %s\n\n" (car link) (cdr link))))))
2077 (switch-to-buffer "*index*")))
2079 (lambda (path desc format)
2082 (format "\\printindex")))))
2087 nil ;; no follow action
2088 (lambda (path desc format)
2091 (format "\\newglossaryentry{%s}{%s}" path desc)))))
2097 nil ;; no follow action
2098 (lambda (path desc format)
2101 (format "\\gls{%s}" path)))))
2106 nil ;; no follow action
2107 (lambda (path desc format)
2110 (format "\\glspl{%s}" path)))))
2115 nil ;; no follow action
2116 (lambda (path desc format)
2119 (format "\\Gls{%s}" path)))))
2124 nil ;; no follow action
2125 (lambda (path desc format)
2128 (format "\\Glspl{%s}" path)))))
2131 ;; ** create text citations from a bibtex entry
2132 (defun org-ref-bib-citation ()
2133 "From a bibtex entry, create and return a simple citation string.
2134 This assumes you are in an article."
2135 (bibtex-set-dialect nil t)
2136 (bibtex-beginning-of-entry)
2137 (let* ((cb (current-buffer))
2138 (bibtex-expand-strings t)
2139 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2140 collect (cons (downcase key) value)))
2141 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2142 (year (reftex-get-bib-field "year" entry))
2143 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2144 (key (reftex-get-bib-field "=key=" entry))
2145 (journal (let ((jt (reftex-get-bib-field "journal" entry)))
2147 (reftex-get-bib-field "journaltitle" entry)
2149 (volume (reftex-get-bib-field "volume" entry))
2150 (pages (reftex-get-bib-field "pages" entry))
2151 (doi (reftex-get-bib-field "doi" entry))
2152 (url (reftex-get-bib-field "url" entry))
2154 ;;authors, "title", Journal, vol(iss):pages (year).
2155 (format "%s, \"%s\", %s, %s:%s (%s)"
2156 author title journal volume pages year)))
2158 (defun org-ref-bib-html-citation ()
2159 "From a bibtex entry, create and return a simple citation with html links."
2160 (bibtex-beginning-of-entry)
2161 (let* ((cb (current-buffer))
2162 (bibtex-expand-strings t)
2163 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2164 collect (cons (downcase key) value)))
2165 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2166 (year (reftex-get-bib-field "year" entry))
2167 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2168 (key (reftex-get-bib-field "=key=" entry))
2169 (journal (reftex-get-bib-field "journal" entry))
2170 (volume (reftex-get-bib-field "volume" entry))
2171 (pages (reftex-get-bib-field "pages" entry))
2172 (doi (reftex-get-bib-field "doi" entry))
2173 (url (reftex-get-bib-field "url" entry)))
2174 ;;authors, "title", Journal, vol(iss):pages (year).
2175 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2176 author title journal volume pages year)
2177 (when url (format " <a href=\"%s\">link</a>" url))
2179 (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))))
2181 ;; ** Open pdf in bibtex entry
2182 (defun org-ref-open-bibtex-pdf ()
2183 "Open pdf for a bibtex entry, if it exists.
2185 the entry of interest in the bibfile. but does not check that."
2188 (bibtex-beginning-of-entry)
2189 (let* ((bibtex-expand-strings t)
2190 (entry (bibtex-parse-entry t))
2191 (key (reftex-get-bib-field "=key=" entry))
2192 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2194 (if (file-exists-p pdf)
2195 (org-open-link-from-string (format "[[file:%s]]" pdf))
2198 ;; ** Open notes from bibtex entry
2200 (defun org-ref-open-bibtex-notes ()
2201 "From a bibtex entry, open the notes if they exist, and create a heading if they do not.
2203 I never did figure out how to use reftex to make this happen
2204 non-interactively. the reftex-format-citation function did not
2205 work perfectly; there were carriage returns in the strings, and
2206 it did not put the key where it needed to be. so, below I replace
2207 the carriage returns and extra spaces with a single space and
2208 construct the heading by hand."
2211 (bibtex-beginning-of-entry)
2212 (let* ((cb (current-buffer))
2213 (bibtex-expand-strings t)
2214 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2215 collect (cons (downcase key) value)))
2216 (key (reftex-get-bib-field "=key=" entry)))
2218 ;; save key to clipboard to make saving pdf later easier by pasting.
2221 (kill-ring-save (point-min) (point-max)))
2223 ;; now look for entry in the notes file
2224 (if org-ref-bibliography-notes
2225 (find-file-other-window org-ref-bibliography-notes)
2226 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2228 (goto-char (point-min))
2229 ;; put new entry in notes if we don't find it.
2230 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2231 (funcall org-ref-open-notes-function)
2232 ;; no entry found, so add one
2233 (insert (org-ref-reftex-format-citation entry (concat "\n" org-ref-note-title-format)))
2234 (insert (org-ref-reftex-format-citation
2248 (format "[[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2249 key org-ref-pdf-directory key))))
2252 (defun org-ref-open-notes-from-reftex ()
2253 "Call reftex, and open notes for selected entry."
2255 (let ((bibtex-key )))
2257 ;; now look for entry in the notes file
2258 (if org-ref-bibliography-notes
2259 (find-file-other-window org-ref-bibliography-notes)
2260 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2262 (goto-char (point-min))
2264 (re-search-forward (format
2266 (cl-first (reftex-citation t)) nil 'end))
2267 (funcall org-ref-open-notes-function))
2269 ;; ** Open bibtex entry in browser
2270 (defun org-ref-open-in-browser ()
2271 "Open the bibtex entry at point in a browser using the url field or doi field."
2274 (bibtex-beginning-of-entry)
2276 (let ((url (bibtex-autokey-get-field "url")))
2281 (let ((doi (bibtex-autokey-get-field "doi")))
2283 (if (string-match "^http" doi)
2285 (browse-url (format "http://dx.doi.org/%s" doi)))
2287 (message "No url or doi found"))))
2289 ;; ** upload entry to citeulike
2291 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2292 "With point in a bibtex entry get bibtex string and submit to citeulike.
2294 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2296 (message "uploading to citeulike")
2298 (bibtex-narrow-to-entry)
2299 (let ((startpos (point-min))
2300 (endpos (point-max))
2301 (bibtex-string (buffer-string))
2302 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2303 (with-temp-buffer (insert bibtex-string)
2304 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2306 ;; ** Build a pdf of the bibtex file
2307 (defun org-ref-build-full-bibliography ()
2308 "Build pdf of all bibtex entries, and open it."
2310 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2311 (bib-base (file-name-sans-extension bibfile))
2312 (texfile (concat bib-base ".tex"))
2313 (pdffile (concat bib-base ".pdf")))
2316 (insert (format "\\documentclass[12pt]{article}
2317 \\usepackage[version=3]{mhchem}
2319 \\usepackage[numbers]{natbib}
2320 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2324 \\bibliographystyle{unsrtnat}
2326 \\end{document}" bib-base))
2328 (shell-command (concat "pdflatex " bib-base))
2329 (shell-command (concat "bibtex " bib-base))
2330 (shell-command (concat "pdflatex " bib-base))
2331 (shell-command (concat "pdflatex " bib-base))
2332 (kill-buffer texfile)
2333 (org-open-file pdffile)
2336 ;; ** Extract bibtex entries in org-file
2338 (defun org-ref-extract-bibtex-entries ()
2339 "Extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2341 If no bibliography is in the buffer the variable
2342 `reftex-default-bibliography' is used."
2344 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2345 (tempname (make-temp-file "extract-bib"))
2346 (contents (buffer-string))
2347 (cb (current-buffer))
2348 basename texfile bibfile results)
2350 ;; open tempfile and insert org-buffer contents
2351 (find-file tempname)
2353 (setq basename (file-name-sans-extension
2354 (file-name-nondirectory buffer-file-name))
2355 texfile (concat tempname ".tex")
2356 bibfile (concat tempname ".bib"))
2358 ;; see if we have a bibliography, and insert the default one if not.
2360 (goto-char (point-min))
2361 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2362 (insert (format "\nbibliography:%s"
2363 (mapconcat 'identity reftex-default-bibliography ",")))))
2366 ;; get a latex file and extract the references
2367 (org-latex-export-to-latex)
2370 (reftex-create-bibtex-file bibfile)
2372 ;; save results of the references
2373 (setq results (buffer-string))
2375 ;; kill buffers. these are named by basename, not full path
2376 (kill-buffer (concat basename ".bib"))
2377 (kill-buffer (concat basename ".tex"))
2378 (kill-buffer basename)
2380 (delete-file bibfile)
2381 (delete-file texfile)
2382 (delete-file tempname)
2384 ;; Now back to the original org buffer and insert the results
2385 (switch-to-buffer cb)
2386 (when (not (string= "" results))
2388 (goto-char (point-max))
2390 (org-insert-heading)
2391 (insert (format " Bibtex entries
2393 #+BEGIN_SRC text :tangle %s
2395 #+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2397 ;; ** Find bad citations
2400 (defun index (substring list)
2401 "Return the index of SUBSTRING in a LIST of strings."
2404 (dolist (arg list i)
2405 (if (string-match (concat "^" substring "$") arg)
2410 ;; return counter if found, otherwise return nil
2414 (defun org-ref-find-bad-citations ()
2415 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2417 Makes a new buffer with clickable links."
2419 ;; generate the list of bibtex-keys and cited keys
2420 (let* ((bibtex-files (org-ref-find-bibliography))
2421 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2422 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2423 (bad-citations '()))
2425 (org-element-map (org-element-parse-buffer) 'link
2427 (let ((plist (nth 1 link)))
2428 (when (-contains? org-ref-cite-types (plist-get plist :type))
2429 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)))
2430 (when (not (index key bibtex-keys))
2435 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2438 (plist-get plist :begin)))))
2440 ;; set with-affilates to t to get citations in a caption
2445 (switch-to-buffer-other-window "*Missing citations*")
2448 (insert "* List of bad cite links\n")
2449 (insert (mapconcat 'identity bad-citations ""))
2450 ;(setq buffer-read-only t)
2451 (use-local-map (copy-keymap org-mode-map))
2452 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2454 (when (get-buffer "*Missing citations*")
2455 (kill-buffer "*Missing citations*"))
2456 (message "No bad cite links found"))))
2458 ;; ** helm interface to bad citations, labels, refs and files in orgfile
2459 (defun org-ref-bad-cite-candidates ()
2460 "Return a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2461 (let* ((cp (point)) ; save to return to later
2462 (bibtex-files (org-ref-find-bibliography))
2463 (bibtex-file-path (mapconcat
2465 (file-name-directory (file-truename x)))
2467 (bibtex-keys (mapcar (lambda (x) (car x))
2468 (bibtex-global-key-alist)))
2469 (bad-citations '()))
2471 (org-element-map (org-element-parse-buffer) 'link
2473 (let ((plist (nth 1 link)))
2474 (when (-contains? org-ref-cite-types (plist-get plist :type))
2475 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)) )
2476 (when (not (index key bibtex-keys))
2477 (goto-char (plist-get plist :begin))
2478 (re-search-forward key)
2479 (push (cons key (point-marker)) bad-citations)))
2481 ;; add with-affiliates to get cites in caption
2487 (defun org-ref-bad-ref-candidates ()
2488 "Return a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2489 ;; first get a list of legitimate labels
2491 (labels (org-ref-get-labels))
2493 ;; now loop over ref links
2494 (goto-char (point-min))
2495 (org-element-map (org-element-parse-buffer) 'link
2497 (let ((plist (nth 1 link)))
2498 (when (or (equal (plist-get plist ':type) "ref")
2499 (equal (plist-get plist ':type) "eqref")
2500 (equal (plist-get plist ':type) "pageref")
2501 (equal (plist-get plist ':type) "nameref"))
2502 (unless (-contains? labels (plist-get plist :path))
2503 (goto-char (plist-get plist :begin))
2506 (cons (plist-get plist :path)
2507 (point-marker))))))))
2512 (defun org-ref-bad-label-candidates ()
2513 "Return a list of labels where label is multiply defined."
2514 (let ((labels (org-ref-get-labels))
2515 (multiple-labels '()))
2516 (when (not (= (length labels)
2517 (length (-uniq labels))))
2518 (dolist (label labels)
2519 (when (> (-count (lambda (a)
2522 ;; this is a multiply defined label.
2524 (goto-char (point-min))
2525 (while (re-search-forward
2526 (format "[^#+]label:%s\\s-" label) nil t)
2527 (push (cons label (point-marker)) multiple-labels))
2528 (goto-char (point-min))
2529 (while (re-search-forward
2530 (format "\\label{%s}\\s-?" label) nil t)
2531 (push (cons label (point-marker)) multiple-labels))
2533 (goto-char (point-min))
2534 (while (re-search-forward
2535 (format "^#\\+label:\\s-*%s" label) nil t)
2536 (push (cons label (point-marker)) multiple-labels))
2538 (goto-char (point-min))
2539 (while (re-search-forward
2540 (format "^#\\+tblname:\\s-*%s" label) nil t)
2541 (push (cons label (point-marker)) multiple-labels))
2545 (defun org-ref-bad-file-link-candidates ()
2546 "Return list of conses (link . marker) wehre the file in the link does not exist."
2547 (let* ((bad-files '()))
2548 (org-element-map (org-element-parse-buffer) 'link
2550 (let ((type (org-element-property :type link)))
2551 (when (or (string= "file" type)
2552 (string= "attachfile" type))
2553 (unless (file-exists-p (org-element-property :path link))
2554 (add-to-list 'bad-files
2555 (cons (org-element-property :path link)
2558 (org-element-property :begin link))
2559 (point-marker)))))))))
2560 ;; Let us also check \attachfile{fname}
2562 (goto-char (point-min))
2563 (while (re-search-forward "\\attachfile{\\(.*\\)}" nil t)
2564 (unless (file-exists-p (match-string 1))
2565 (add-to-list 'bad-files (cons (match-string 1) (point-marker))))))
2570 "Opens a helm interface to actions for org-ref.
2571 Shows bad citations, ref links and labels"
2573 (let ((cb (current-buffer))
2574 (bad-citations (org-ref-bad-cite-candidates))
2575 (bad-refs (org-ref-bad-ref-candidates))
2576 (bad-labels (org-ref-bad-label-candidates))
2577 (bad-files (org-ref-bad-file-link-candidates)))
2579 (helm :sources `(((name . "Bad citations")
2580 (candidates . ,bad-citations)
2581 (action . (lambda (marker)
2582 (switch-to-buffer (marker-buffer marker))
2583 (goto-char marker))))
2585 ((name . "Bad Labels")
2586 (candidates . ,bad-labels)
2587 (action . (lambda (marker)
2588 (switch-to-buffer (marker-buffer marker))
2589 (goto-char marker))))
2591 ((name . "Bad ref links")
2592 (candidates . ,bad-refs)
2593 (action . (lambda (marker)
2594 (switch-to-buffer (marker-buffer marker))
2595 (goto-char marker))))
2597 ((name . "Bad file links")
2598 (candidates . ,bad-files)
2600 (switch-to-buffer (marker-buffer marker))
2601 (goto-char marker)))
2603 ((name . "Utilities")
2604 (candidates . (("Check buffer again" . org-ref)
2605 ("Insert citation" . helm-bibtex)
2606 ("Insert label link" . org-ref-helm-insert-label-link)
2607 ("Insert ref link" . org-ref-helm-insert-ref-link)
2608 ("List of figures" . org-ref-list-of-figures)
2609 ("List of tables" . org-ref-list-of-tables)
2610 ("Table of contents" . nil)
2612 (action . (lambda (x)
2613 (switch-to-buffer ,cb)
2616 ((name . "Export functions")
2617 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2618 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2619 ("Export to pdf and open" . (lambda ()
2620 (org-open-file (org-latex-export-to-pdf))))
2621 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2622 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2625 (action . (lambda (x)
2626 (switch-to-buffer ,cb)
2629 ;; ** Find non-ascii charaters
2630 (defun org-ref-find-non-ascii-characters ()
2631 "Find non-ascii characters in the buffer. Useful for cleaning up bibtex files."
2633 (occur "[^[:ascii:]]"))
2635 ;; ** Sort fields in a bibtex entry
2637 (defun org-ref-sort-bibtex-entry ()
2638 "Sort fields of entry in standard order and downcase them."
2640 (bibtex-beginning-of-entry)
2641 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2642 (entry (bibtex-parse-entry))
2645 (type (cdr (assoc "=type=" entry)))
2646 (key (cdr (assoc "=key=" entry))))
2648 ;; these are the fields we want to order that are in this entry
2649 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2650 ;; we do not want to reenter these fields
2651 (setq entry-fields (remove "=key=" entry-fields))
2652 (setq entry-fields (remove "=type=" entry-fields))
2654 ;;these are the other fields in the entry
2655 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2658 ;; right now we only resort articles
2659 ((string= (downcase type) "article")
2662 (concat "@article{" key ",\n"
2665 (when (member field entry-fields)
2666 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2669 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2671 (bibtex-find-entry key)
2673 (bibtex-clean-entry)
2676 ;; ** Clean a bibtex entry
2677 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2678 "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"
2680 (bibtex-beginning-of-entry)
2682 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2683 (unless (string-match ",$" (thing-at-point 'line))
2687 ;; check for empty pages, and put eid or article id in its place
2688 (let ((entry (bibtex-parse-entry))
2689 (pages (bibtex-autokey-get-field "pages"))
2690 (year (bibtex-autokey-get-field "year"))
2691 (doi (bibtex-autokey-get-field "doi"))
2692 ;; The Journal of Chemical Physics uses eid
2693 (eid (bibtex-autokey-get-field "eid")))
2695 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2696 ;; but we only want the doi.
2697 (when (string-match "^http://dx.doi.org/" doi)
2698 (bibtex-beginning-of-entry)
2699 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2701 (bibtex-make-field "doi")
2703 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2705 ;; asap articles often set year to 0, which messes up key
2706 ;; generation. fix that.
2707 (when (string= "0" year)
2708 (bibtex-beginning-of-entry)
2709 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2711 (bibtex-make-field "year")
2713 (insert (read-string "Enter year: ")))
2715 ;; fix pages if they are empty if there is an eid to put there.
2716 (when (string= "-" pages)
2718 (bibtex-beginning-of-entry)
2719 ;; this seems like a clunky way to set the pages field.But I
2720 ;; cannot find a better way.
2721 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2723 (bibtex-make-field "pages")
2727 ;; replace naked & with \&
2729 (bibtex-narrow-to-entry)
2730 (bibtex-beginning-of-entry)
2731 (message "checking &")
2732 (replace-regexp " & " " \\\\& ")
2735 ;; generate a key, and if it duplicates an existing key, edit it.
2737 (let ((key (bibtex-generate-autokey)))
2739 ;; first we delete the existing key
2740 (bibtex-beginning-of-entry)
2741 (re-search-forward bibtex-entry-maybe-empty-head)
2742 (if (match-beginning bibtex-key-in-head)
2743 (delete-region (match-beginning bibtex-key-in-head)
2744 (match-end bibtex-key-in-head)))
2745 ;; check if the key is in the buffer
2746 (when (save-excursion
2747 (bibtex-search-entry key))
2749 (bibtex-search-entry key)
2750 (bibtex-copy-entry-as-kill)
2751 (switch-to-buffer-other-window "*duplicate entry*")
2753 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2756 (kill-new key))) ;; save key for pasting
2758 ;; run hooks. each of these operates on the entry with no arguments.
2759 ;; this did not work like i thought, it gives a symbolp error.
2760 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2765 org-ref-clean-bibtex-entry-hook)
2767 ;; sort fields within entry
2768 (org-ref-sort-bibtex-entry)
2769 ;; check for non-ascii characters
2770 (occur "[^[:ascii:]]")
2773 (defun org-ref-get-citation-year (key)
2774 "Get the year of an entry with KEY. Return year as a string."
2775 (let* ((results (org-ref-get-bibtex-key-and-file key))
2776 (bibfile (cdr results)))
2778 (insert-file-contents bibfile)
2779 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
2780 (bibtex-search-entry key nil 0)
2781 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2784 ;; ** Sort cite in cite link
2785 (defun org-ref-sort-citation-link ()
2786 "Replace link at point with sorted link by year."
2788 (let* ((object (org-element-context))
2789 (type (org-element-property :type object))
2790 (begin (org-element-property :begin object))
2791 (end (org-element-property :end object))
2792 (link-string (org-element-property :path object))
2794 (setq keys (org-ref-split-and-strip-string link-string))
2795 (setq years (mapcar 'org-ref-get-citation-year keys))
2796 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2797 (setq data (cl-sort data (lambda (x y) (< (string-to-number (car x)) (string-to-number (car y))))))
2798 ;; now get the keys separated by commas
2799 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2800 ;; and replace the link with the sorted keys
2801 (cl--set-buffer-substring begin end (concat type ":" keys))))
2803 ;; ** Shift-arrow sorting of keys in a cite link
2805 (defun org-ref-swap-keys (i j keys)
2806 "Swap the KEYS in a list with index I and J."
2807 (let ((tempi (nth i keys)))
2808 (setf (nth i keys) (nth j keys))
2809 (setf (nth j keys) tempi))
2813 (defun org-ref-swap-citation-link (direction)
2814 "Move citation at point in DIRECTION +1 is to the right, -1 to the left."
2816 (let* ((object (org-element-context))
2817 (type (org-element-property :type object))
2818 (begin (org-element-property :begin object))
2819 (end (org-element-property :end object))
2820 (link-string (org-element-property :path object))
2822 ;; We only want this to work on citation links
2823 (when (-contains? org-ref-cite-types type)
2824 (setq key (org-ref-get-bibtex-key-under-cursor))
2825 (setq keys (org-ref-split-and-strip-string link-string))
2826 (setq i (index key keys)) ;; defined in org-ref
2827 (if (> direction 0) ;; shift right
2828 (org-ref-swap-keys i (+ i 1) keys)
2829 (org-ref-swap-keys i (- i 1) keys))
2830 (setq keys (mapconcat 'identity keys ","))
2831 ;; and replace the link with the sorted keys
2832 (cl--set-buffer-substring
2836 ;; It seems the space at the end can get consumed, so we see if there
2837 ;; is a space, and add it if so. Sometimes there is a comma or period,
2838 ;; then we do not want a space.
2842 (looking-back " ")) " ")))
2843 ;; now go forward to key so we can move with the key
2844 (re-search-forward key)
2845 (goto-char (match-beginning 0)))))
2847 ;; add hooks to make it work
2848 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2849 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2851 ;; ** context around org-ref links
2852 (defun org-ref-get-label-context (label)
2853 "Return a string of context around a LABEL."
2856 (goto-char (point-min))
2857 (when (re-search-forward
2858 (format "label:%s\\b" label) nil t)
2859 (throw 'result (buffer-substring
2868 (goto-char (point-min))
2869 (when (re-search-forward
2870 (format "\\label{%s}" label) nil t)
2871 (throw 'result (buffer-substring
2880 (goto-char (point-min))
2881 (when (re-search-forward
2882 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2883 (throw 'result (buffer-substring
2892 (goto-char (point-min))
2893 (when (re-search-forward
2894 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2895 (throw 'result (buffer-substring
2903 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
2906 (defun org-ref-link-message ()
2907 "Print a minibuffer message about the link that point is on."
2911 (when (eq major-mode 'org-mode)
2912 (let* ((object (org-element-context))
2913 (type (org-element-property :type object)))
2917 ((-contains? org-ref-cite-types type)
2918 (message (org-ref-get-citation-string-at-point)))
2920 ;; message some context about the label we are referring to
2921 ((string= type "ref")
2922 (message "%scount: %s"
2923 (org-ref-get-label-context
2924 (org-element-property :path object))
2925 (org-ref-count-labels
2926 (org-element-property :path object))))
2928 ((string= type "eqref")
2929 (message "%scount: %s"
2930 (org-ref-get-label-context
2931 (org-element-property :path object))
2932 (org-ref-count-labels
2933 (org-element-property :path object))))
2935 ;; message the count
2936 ((string= type "label")
2937 (let ((count (org-ref-count-labels
2938 (org-element-property :path object))))
2939 ;; get plurality on occurrence correct
2941 (number-to-string count)
2943 (when (or (= count 0)
2947 ((string= type "custom-id")
2949 (org-open-link-from-string
2950 (format "[[#%s]]" (org-element-property :path object)))
2951 (message "%s" (org-get-heading))))
2953 ;; check if the bibliography files exist.
2954 ((string= type "bibliography")
2956 ;; object is the link you clicked on
2957 (object (org-element-context))
2958 (link-string (org-element-property :path object))
2959 (link-string-beginning)
2962 (goto-char (org-element-property :begin object))
2963 (search-forward link-string nil nil 1)
2964 (setq link-string-beginning (match-beginning 0))
2965 (setq link-string-end (match-end 0)))
2967 ;; make sure we are in link and not before the :
2968 (when (> link-string-beginning (point))
2969 (goto-char link-string-beginning))
2971 (let (key-beginning key-end)
2972 ;; now if we have comma separated bibliographies
2973 ;; we find the one clicked on. we want to
2974 ;; search forward to next comma from point
2976 (if (search-forward "," link-string-end 1 1)
2977 (setq key-end (- (match-end 0) 1)) ; we found a match
2978 (setq key-end (point)))) ; no comma found so take the point
2980 ;; and backward to previous comma from point
2982 (if (search-backward "," link-string-beginning 1 1)
2983 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
2984 (setq key-beginning (point)))) ; no match found
2985 ;; save the key we clicked on.
2987 (org-ref-strip-string
2988 (buffer-substring key-beginning key-end)))
2989 (if (file-exists-p bibfile)
2990 (message "%s exists." bibfile)
2991 (message "!!! %s NOT FOUND !!!" bibfile)))))))))))
2994 (defalias 'oro 'org-ref-open-citation-at-point)
2995 (defalias 'orc 'org-ref-citation-at-point)
2996 (defalias 'orp 'org-ref-open-pdf-at-point)
2997 (defalias 'oru 'org-ref-open-url-at-point)
2998 (defalias 'orn 'org-ref-open-notes-at-point)
2999 (defalias 'ornr 'org-ref-open-notes-from-reftex)
3001 (defalias 'orib 'org-ref-insert-bibliography-link)
3002 (defalias 'oric 'org-ref-insert-cite-link)
3003 (defalias 'orir 'org-ref-insert-ref-link)
3004 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
3006 (defalias 'orcb 'org-ref-clean-bibtex-entry)
3008 ;; * Helm bibtex setup
3010 (setq helm-bibtex-additional-search-fields '(keywords))
3012 (defun helm-bibtex-candidates-formatter (candidates source)
3013 "Formats BibTeX entries for display in results list.
3014 Argument CANDIDATES helm candidates.
3015 Argument SOURCE the helm source."
3017 with width = (with-helm-window (helm-bibtex-window-width))
3018 for entry in candidates
3019 for entry = (cdr entry)
3020 for entry-key = (helm-bibtex-get-value "=key=" entry)
3021 if (assoc-string "author" entry 'case-fold)
3022 for fields = '("author" "title" "year" "=has-pdf=" "=has-note=" "=type=")
3024 for fields = '("editor" "title" "year" "=has-pdf=" "=has-note=" "=type=")
3025 for fields = (--map (helm-bibtex-clean-string
3026 (helm-bibtex-get-value it entry " "))
3028 for fields = (-update-at 0 'helm-bibtex-shorten-authors fields)
3029 for fields = (append fields
3030 (list (or (helm-bibtex-get-value "keywords" entry)
3033 (cons (s-format "$0 $1 $2 $3 $4$5 $6" 'elt
3034 (-zip-with (lambda (f w) (truncate-string-to-width f w 0 ?\s))
3035 fields (list 36 (- width 85) 4 1 1 7 7)))
3038 ;; * org-ref bibtex keywords
3039 ;; adapted from bibtex-utils.el
3040 ;; these are candidates for selecting keywords/tags
3041 (defun org-ref-bibtex-keywords ()
3042 "Get keywords defined in current bibtex file.
3043 These are in the keywords field, and are comma or semicolon separated."
3045 (goto-char (point-min))
3046 (let (keywords kstring)
3047 (while (re-search-forward "^\\s-*keywords.*{\\([^}]+\\)}" nil t)
3048 ;; TWS - remove newlines/multiple spaces:
3049 (setq kstring (replace-regexp-in-string "[ \t\n]+" " " (match-string 1)))
3052 (add-to-list 'keywords v t))
3053 (split-string kstring "\\(,\\|;\\)[ \n]*\\|{\\|}" t)))
3057 (defun org-ref-set-bibtex-keywords (keywords &optional arg)
3058 "Add KEYWORDS to a bibtex entry.
3059 If KEYWORDS is a list, it is converted to a comma-separated
3060 string. The KEYWORDS are added to the beginning of the
3061 field. Otherwise KEYWORDS should be a string of comma-separate
3062 keywords. Optional argument ARG prefix arg to replace keywords."
3063 (interactive "sKeywords: \nP")
3068 (if (listp keywords)
3069 (mapconcat 'identity keywords ", ")
3071 ;; else concatentate
3073 (if (listp keywords)
3074 (mapconcat 'identity keywords ", ")
3076 (when (not (string= "" (bibtex-autokey-get-field "keywords")))
3077 (concat ", " (bibtex-autokey-get-field "keywords"))))))
3081 (defun helm-tag-bibtex-entry ()
3082 "Helm interface to add keywords to a bibtex entry.
3083 Run this with the point in a bibtex entry."
3085 (let ((keyword-source `((name . "Existing keywords")
3086 (candidates . ,(org-ref-bibtex-keywords))
3087 (action . (lambda (candidate)
3088 (org-ref-set-bibtex-keywords
3091 (helm-marked-candidates)
3093 (fallback-source `((name . "Add new keywords")
3095 (action . (lambda (candidate)
3096 (org-ref-set-bibtex-keywords helm-pattern)
3098 (helm :sources '(keyword-source fallback-source))))
3100 (defun helm-bibtex-show-entry (key)
3101 "Show the entry for KEY in the BibTeX file.
3102 The original function in `helm-bibtex' has a bug where it finds the
3103 first key that partially matches. This version avoids that."
3105 (dolist (bibtex-file (if (listp helm-bibtex-bibliography)
3106 helm-bibtex-bibliography
3107 (list helm-bibtex-bibliography)))
3108 (let ((buf (helm-bibtex-buffer-visiting bibtex-file))
3110 (find-file bibtex-file)
3112 (lambda (key start end)
3113 (add-to-list 'entries (cons key start))))
3114 (if (assoc key entries)
3116 (goto-char (cdr (assoc key entries)))
3121 (defun org-ref-helm-tag-entries (candidates)
3122 "Set tags on selected bibtex entries from `helm-bibtex'.
3123 User is prompted for tags. This function is called from `helm-bibtex'.
3124 Argument CANDIDATES helm candidates."
3126 (let ((keywords (read-string "Keywords (comma separated): ")))
3127 (cl-loop for key in (helm-marked-candidates)
3129 (save-window-excursion
3130 (helm-bibtex-show-entry key)
3135 ", " (bibtex-autokey-get-field "keywords")))
3138 (setq helm-source-bibtex
3139 '((name . "BibTeX entries")
3140 (init . helm-bibtex-init)
3141 (candidates . helm-bibtex-candidates)
3142 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3143 (action . (("Insert citation" . helm-bibtex-insert-citation)
3144 ("Show entry" . helm-bibtex-show-entry)
3145 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3146 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3147 ("Insert formatted reference" . helm-bibtex-insert-reference)
3148 ("Insert BibTeX key" . helm-bibtex-insert-key)
3149 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3150 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3151 ("Edit notes" . helm-bibtex-edit-notes)
3152 ("Add keywords to entries" . org-ref-helm-tag-entries)
3155 (defun helm-bibtex-format-org-ref (keys)
3156 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3157 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.
3159 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3161 C-u C-u will change the key at point to the selected keys."
3162 (let* ((object (org-element-context))
3163 (last-char (save-excursion
3164 (when (org-element-property :end object)
3165 (goto-char (org-element-property :end object))
3168 (if (looking-at " ")
3172 ;; case where we are in a link
3173 ((and (equal (org-element-type object) 'link)
3176 (org-element-property :type object)))
3178 ;; no prefix. append keys
3179 ((equal helm-current-prefix-arg nil)
3180 (goto-char (org-element-property :end object))
3181 (while (looking-back " ") (backward-char))
3182 (insert (concat "," (mapconcat 'identity keys ","))))
3183 ;; double prefix, replace key at point
3184 ((equal helm-current-prefix-arg '(16))
3185 (setf (buffer-substring
3186 (org-element-property :begin object)
3187 (org-element-property :end object))
3189 (replace-regexp-in-string
3190 (car (org-ref-get-bibtex-key-and-file)) ; key
3191 (mapconcat 'identity keys ",") ; new keys
3192 (org-element-property :raw-link object))
3193 ;; replace space at end to avoid collapsing into next word.
3195 ;; and we want to go to the end of the new link
3197 (org-element-property :end (org-element-context))))
3199 (message "Not found"))))
3201 ;; We are next to a link, and we want to append
3202 ;; next to a link means one character back is on a link.
3204 (unless (bobp) (backward-char))
3205 (and (equal (org-element-type (org-element-context)) 'link)
3208 (org-element-property :type (org-element-context)))))
3209 (while (looking-back " ") (backward-char))
3210 (insert (concat "," (mapconcat 'identity keys ","))))
3212 ;; insert fresh link
3214 ;;(message-box "fresh link")
3216 (concat (if (equal helm-current-prefix-arg '(4))
3217 (helm :sources `((name . "link types")
3218 (candidates . ,org-ref-cite-types)
3219 (action . (lambda (x) x))))
3220 org-ref-default-citation-link)
3222 (s-join "," keys))))))
3223 ;; return empty string for helm
3226 (setq helm-bibtex-format-citation-functions
3227 '((org-mode . helm-bibtex-format-org-ref)))
3230 (defun org-ref-helm-insert-cite-link (arg)
3231 "org-ref function to use helm-bibtex to insert a citation link.
3232 With one prefix arg, insert a ref link.
3233 With two prefix args, insert a label link."
3237 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3240 (org-ref-helm-insert-ref-link))
3242 (org-ref-helm-insert-label-link))))
3245 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3246 (setq helm-bibtex-fallback-options
3247 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3249 (setq helm-bibtex-fallback-options
3252 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3253 helm-bibtex-fallback-options))
3255 (setq helm-bibtex-fallback-options
3256 (-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))
3258 (defun org-ref-get-citation-string-at-point ()
3259 "Get a string of a formatted citation."
3260 (let* ((results (org-ref-get-bibtex-key-and-file))
3262 (bibfile (cdr results)))
3266 (insert-file-contents bibfile)
3267 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3268 (bibtex-search-entry key)
3269 (org-ref-bib-citation)))
3270 "!!! No entry found !!!" )))
3273 (defun org-ref-cite-candidates ()
3274 "Generate the list of possible candidates for click actions on a cite link.
3275 Checks for pdf and doi, and add appropriate functions."
3276 (let* ((results (org-ref-get-bibtex-key-and-file))
3278 (pdf-file (funcall org-ref-get-pdf-filename-function key))
3279 (bibfile (cdr results))
3280 (url (save-excursion
3282 (insert-file-contents bibfile)
3283 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3284 (bibtex-search-entry key)
3285 (bibtex-autokey-get-field "url"))))
3286 (doi (save-excursion
3288 (insert-file-contents bibfile)
3289 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3290 (bibtex-search-entry key)
3291 ;; I like this better than bibtex-url which does not always find
3293 (bibtex-autokey-get-field "doi"))))
3294 (candidates `(("Quit" . org-ref-citation-at-point)
3295 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3296 ;; for some reason, when there is no doi or url, they are returned as "". I
3297 ;; prefer nil so we correct this here.
3298 (when (string= doi "") (setq doi nil))
3299 (when (string= url "") (setq url nil))
3301 ;; Conditional pdf functions
3302 (if (file-exists-p pdf-file)
3305 '("Open pdf" . org-ref-open-pdf-at-point)
3309 '("Try to get pdf" . (lambda ()
3310 (save-window-excursion
3311 (org-ref-open-citation-at-point)
3312 (bibtex-beginning-of-entry)
3313 (doi-utils-get-bibtex-entry-pdf))))
3319 '("Open notes" . org-ref-open-notes-at-point)
3322 ;; conditional url and doi functions
3326 '("Open in browser" . org-ref-open-url-at-point)
3331 (add-to-list 'candidates x t))
3332 `(("WOS" . org-ref-wos-at-point)
3333 ("Related articles in WOS" . org-ref-wos-related-at-point)
3334 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3335 ("Google Scholar" . org-ref-google-scholar-at-point)
3336 ("Pubmed" . org-ref-pubmed-at-point)
3337 ("Crossref" . org-ref-crossref-at-point)
3342 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3347 '("Copy key to clipboard" . (lambda ()
3349 (car (org-ref-get-bibtex-key-and-file)))))
3354 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3359 '("Email bibtex entry and pdf" . (lambda ()
3361 (org-ref-open-citation-at-point)
3362 (email-bibtex-entry))))
3364 ;; finally return a numbered list of the candidates
3365 (cl-loop for i from 0
3366 for cell in candidates
3367 collect (cons (format "%2s. %s" i (car cell))
3371 (defvar org-ref-helm-user-candidates '()
3372 "List of user-defined candidates to act when clicking on a cite link.
3373 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.")
3375 ;; example of adding your own function
3377 'org-ref-helm-user-candidates
3378 '("Example" . (lambda () (message-box "You did it!")))
3382 (defun org-ref-cite-click-helm (key)
3383 "Open helm for actions on a cite link.
3386 1. get name and candidates before entering helm because we need
3389 2. switch back to the org buffer before evaluating the
3390 action. most of them need the point and buffer.
3392 KEY is returned for the selected item(s) in helm."
3394 (let ((name (org-ref-get-citation-string-at-point))
3395 (candidates (org-ref-cite-candidates))
3396 (cb (current-buffer)))
3398 (helm :sources `(((name . ,name)
3399 (candidates . ,candidates)
3400 (action . (lambda (f)
3401 (switch-to-buffer cb)
3403 ((name . "User functions")
3404 (candidates . ,org-ref-helm-user-candidates)
3405 (action . (lambda (f)
3406 (switch-to-buffer cb)
3410 ;; * Hydra menus in org-ref
3412 (when (featurep 'hydra)
3414 (setq hydra-is-helpful t)
3416 (defhydra org-ref-cite-hydra (:color blue)
3418 _p_: Open pdf _w_: WOS _g_: Google Scholar _K_: Copy citation to clipboard
3419 _u_: Open url _r_: WOS related _P_: Pubmed _k_: Copy key to clipboard
3420 _n_: Open notes _c_: WOS citing _C_: Crossref _f_: Copy bibtex entry to file
3421 _o_: Open entry _e_: Email entry and pdf
3423 ("o" org-ref-open-citation-at-point nil)
3424 ("p" org-ref-open-pdf-at-point nil)
3425 ("n" org-ref-open-notes-at-point nil)
3426 ("u" org-ref-open-url-at-point nil)
3427 ("w" org-ref-wos-at-point nil)
3428 ("r" org-ref-wos-related-at-point nil)
3429 ("c" org-ref-wos-citing-at-point nil)
3430 ("g" org-ref-google-scholar-at-point nil)
3431 ("P" org-ref-pubmed-at-point nil)
3432 ("C" org-ref-crossref-at-point nil)
3433 ("K" org-ref-copy-entry-as-summary nil)
3436 (car (org-ref-get-bibtex-key-and-file)))) nil)
3437 ("f" org-ref-copy-entry-at-point-to-file nil)
3439 ("e" (save-excursion
3440 (org-ref-open-citation-at-point)
3441 (email-bibtex-entry)) nil)))
3444 (defun org-ref-help ()
3445 "Open the org-ref manual."
3447 (find-file (expand-file-name
3449 (file-name-directory
3450 (find-library-name "org-ref")))))
3453 (defun org-ref-org-menu ()
3454 "Add org-ref menu to the Org menu."
3458 '( ["Insert citation" org-ref-helm-insert-cite-link]
3459 ["Insert ref" org-ref-helm-insert-ref-link]
3460 ["Insert label" org-ref-helm-insert-label-link]
3462 ["List of figures" org-ref-list-of-figures]
3463 ["List of tables" org-ref-list-of-tables]
3464 ["Extract bibtex entries" org-ref-extract-bibtex-entries]
3465 ["Check org-file" org-ref]
3467 ["Help" org-ref-help]
3468 ["Customize org-ref" (customize-group 'org-ref)])
3471 (easy-menu-change '("Org") "--" nil "Show/Hide"))
3473 (add-hook 'org-mode-hook 'org-ref-org-menu)
3478 ;;; org-ref.el ends here