]> git.donarmstrong.com Git - org-ref.git/blob - org-ref.el
rm {} individually and add techreport.
[org-ref.git] / org-ref.el
1 ;;; org-ref.el --- cite and cross-reference in org-mode
2
3 ;; Copyright(C) 2014 John Kitchin
4
5 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
6 ;; URL: https://github.com/jkitchin/org-ref
7 ;; Version: 0.2
8 ;; Keywords: org-mode, cite, ref, label
9 ;; Package-Requires: ((org) (dash) (helm) (helm-bibtex) (hydra))
10
11 ;; This file is not currently part of GNU Emacs.
12
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.
17
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.
22
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.
27
28 ;;; Commentary:
29 ;;
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.
34 ;;
35
36 ;;; Code:
37
38 (require 'reftex-cite)
39 (require 'dash)
40 (require 'helm)
41 (require 'helm-config)
42 (require 'helm-bibtex)
43 (require 'org)
44
45 ;; * Custom variables
46 (defgroup org-ref nil
47   "Customization group for org-ref.")
48
49 (defcustom org-ref-bibliography-notes
50   nil
51   "Filename where you will put all your notes about an entry in the default bibliography."
52   :type 'file
53   :group 'org-ref)
54
55 (defcustom org-ref-default-bibliography
56   nil
57   "List of bibtex files to search for.
58 You should use full-paths for each file."
59   :type '(repeat :tag "List of bibtex files" file)
60   :group 'org-ref)
61
62 (defcustom org-ref-pdf-directory
63   nil
64   "Directory where pdfs are stored by key.  put a trailing / in."
65   :type 'directory
66   :group 'org-ref)
67
68 (defcustom org-ref-default-citation-link
69   "cite"
70   "The default type of citation link to use."
71   :type 'string
72   :group 'org-ref)
73
74 (defcustom org-ref-insert-cite-key
75   "C-c ]"
76   "Keyboard shortcut to insert a citation."
77   :type 'string
78   :group 'org-ref)
79
80 (defcustom org-ref-bibliography-entry-format
81   '(("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>.")
82
83     ("book" . "%a, %t, %u (%y).")
84     ("techreport" . "%a, %t, %u (%y).")
85     ("proceedings" . "%e, %t in %S, %u (%y).")
86     ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
87   "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."
88   :type 'string
89   :group 'org-ref)
90
91 (defcustom org-ref-open-notes-function
92   (lambda ()
93     (org-show-entry)
94     (show-branches)
95     (show-children)
96     (org-cycle '(64))
97     ;;(org-tree-to-indirect-buffer)
98     (outline-previous-visible-heading 1)
99     (recenter-top-bottom 0))
100   "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."
101 :type 'function
102 :group 'org-ref)
103
104
105 (defcustom org-ref-open-pdf-function
106    'org-ref-open-pdf-at-point
107 "User-defined function to open a pdf from a link.  The function must get the key at point, and derive a path to the pdf file, then open it.  The default function is `org-ref-open-pdf-at-point'."
108   :type 'function
109   :group 'org-ref)
110
111
112 (defcustom org-ref-insert-cite-function
113   'org-ref-helm-insert-cite-link
114   "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."
115  :type 'function
116  :group 'org-ref)
117
118
119 (defcustom org-ref-cite-onclick-function
120   'org-ref-cite-click-helm
121   "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'."
122  :type 'function
123  :group 'org-ref)
124
125
126 (defcustom org-ref-show-citation-on-enter t
127   "If non-nil add a hook function to show the citation summary in the minibuffer."
128  :group 'org-ref)
129
130 (defcustom org-ref-cite-types
131   '("cite" "nocite" ;; the default latex cite commands
132     ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
133     "citet" "citet*" "citep" "citep*"
134     "citealt" "citealt*" "citealp" "citealp*"
135     "citenum" "citetext"
136     "citeauthor" "citeauthor*"
137     "citeyear" "citeyear*"
138     "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
139     ;; biblatex commands
140     ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
141     "Cite"
142     "parencite" "Parencite"
143     "footcite" "footcitetext"
144     "textcite" "Textcite"
145     "smartcite" "Smartcite"
146     "cite*" "parencite*" "supercite"
147     "autocite" "Autocite" "autocite*" "Autocite*"
148     "Citeauthor*"
149     "citetitle" "citetitle*"
150     "citedate" "citedate*"
151     "citeurl"
152     "fullcite" "footfullcite"
153     ;; "volcite" "Volcite" cannot support the syntax
154     "notecite" "Notecite"
155     "pnotecite" "Pnotecite"
156     "fnotecite"
157     ;; multicites. Very limited support for these.
158     "cites" "Cites" "parencites" "Parencites"
159     "footcites" "footcitetexts"
160     "smartcites" "Smartcites" "textcites" "Textcites"
161     "supercites" "autocites" "Autocites"
162     ;; for the bibentry package
163     "bibentry"
164     )
165   "List of citation types known in `org-ref'."
166   :type '(repeat :tag "List of citation types" string)
167   :group 'org-ref)
168
169 (defcustom org-ref-clean-bibtex-entry-hook nil
170   "Hook that is run in `org-ref-clean-bibtex-entry'.  The functions should take no arguments, and operate on the bibtex entry at point."
171   :group 'org-ref
172   :type 'hook)
173
174 (defvar org-ref-bibliography-files
175   nil
176   "Variable to hold bibliography files to be searched.")
177
178 ;; * org-mode / reftex setup
179 (require 'reftex)
180 (defun org-mode-reftex-setup ()
181   "Setup `org-mode' and reftex for org-ref."
182     (and (buffer-file-name)
183          (file-exists-p (buffer-file-name))
184          (global-auto-revert-mode t))
185     (make-local-variable 'reftex-cite-format)
186     (setq reftex-cite-format 'org))
187
188 ;; define key for inserting citations
189 (define-key org-mode-map
190   (kbd org-ref-insert-cite-key)
191   org-ref-insert-cite-function)
192
193 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
194
195 (eval-after-load 'reftex-vars
196   '(progn
197       (add-to-list 'reftex-cite-format-builtin
198                    '(org "Org-mode citation"
199                          ((?\C-m . "cite:%l")     ; default
200                           (?d . ",%l")            ; for appending
201                           (?a . "autocite:%l")
202                           (?t . "citet:%l")
203                           (?T . "citet*:%l")
204                           (?p . "citep:%l")
205                           (?P . "citep*:%l")
206                           (?h . "citeauthor:%l")
207                           (?H . "citeauthor*:%l")
208                           (?y . "citeyear:%l")
209                           (?x . "citetext:%l")
210                           (?n . "nocite:%l")
211                           )))))
212
213 ;; * Messages for link at cursor
214 (defvar org-ref-message-timer nil
215   "Variable to store the link message timer in.")
216
217
218 (defun org-ref-show-link-messages ()
219   "Turn on link messages.
220 You will see a message in the minibuffer when on a cite, ref or label link."
221   (interactive)
222   (or org-ref-message-timer
223       (setq org-ref-message-timer
224             (run-with-idle-timer 0.5 t 'org-ref-link-message))))
225
226
227 (defun org-ref-cancel-link-messages ()
228   "Stop showing messages in minibuffer when on a link."
229   (interactive)
230   (cancel-timer org-ref-message-timer)
231   (setq org-ref-message-timer nil))
232
233
234 (when org-ref-show-citation-on-enter
235   (org-ref-show-link-messages))
236
237 ;; ** Messages for context under mouse pointer
238
239 (defvar org-ref-last-mouse-pos nil
240  "Stores last mouse position for use in `org-ref-mouse-message'.")
241
242 (defun org-ref-can-move-p ()
243   "See if a character is under the mouse.  If so return the position for `goto-char'."
244   (let* ((line (cddr org-ref-last-mouse-pos))
245          (col  (cadr org-ref-last-mouse-pos)))
246     (save-excursion
247       (goto-char (window-start))
248       (forward-line line)
249       (if
250           (> (- (line-end-position) (line-beginning-position)) col)
251           (progn  (forward-char col) (point))
252         nil))))
253
254
255 (defun org-ref-mouse-message ()
256   "Display message for link under mouse cursor."
257   (interactive)
258   (when (not (equal (mouse-position) org-ref-last-mouse-pos))
259     (setq org-ref-last-mouse-pos (mouse-position))
260     (let ((p (org-ref-can-move-p)))
261       (when p
262           (save-excursion
263             (goto-char p)
264             (org-ref-link-message))))))
265
266
267 (defvar org-ref-message-timer-mouse nil
268   "Store mouse timer.")
269
270
271 (defvar org-ref-mouse-message-interval 0.5
272   "How often to run the mouse message timer in seconds.")
273
274
275 (defun org-ref-mouse-messages-on ()
276   "Turn on mouse messages."
277   (interactive)
278   (or org-ref-message-timer-mouse
279       (setq org-ref-message-timer-mouse
280             (run-at-time "0.5 sec"
281                          org-ref-mouse-message-interval
282                          'org-ref-mouse-message))))
283
284
285 (defun org-ref-mouse-messages-off ()
286   "Turn off mouse messages."
287   (interactive)
288   (cancel-timer org-ref-message-timer-mouse)
289   (setq org-ref-message-timer-mouse nil)
290   (message "Mouse messages are off"))
291
292 ;; Colorizing org-ref links
293 (defcustom org-ref-colorize-links
294   t
295   "When non-nil, change colors of links."
296   :group 'org-ref)
297
298
299 (defcustom org-ref-cite-color
300   "forest green"
301   "Color of cite like links."
302   :group 'org-ref)
303
304
305 (defcustom org-ref-ref-color
306   "dark red"
307   "Color of ref like links."
308   :group 'org-ref)
309
310
311 (defcustom org-ref-label-color
312   "dark magenta"
313   "Color of label links."
314   :group 'org-ref)
315
316
317 (defvar org-ref-cite-re nil
318  "Regexp for cite links.")
319
320
321 (setq org-ref-cite-re
322       (concat "\\(" (mapconcat
323                      (lambda (x)
324                        (replace-regexp-in-string "\*" "\\\\*" x)
325                        )
326                      org-ref-cite-types "\\|") "\\)"
327   ":\\([a-zA-Z0-9-_:\\./]*,?\\)*"))
328
329
330 (setq org-ref-label-re
331       "label:\\([a-zA-Z0-9-_:]*,?\\)*")
332
333
334 (setq org-ref-ref-re
335       "\\(eq\\)?ref:\\([a-zA-Z0-9-_:]*,?\\)*")
336
337
338 (defface org-ref-cite-face
339   `((t (:inherit org-link :foreground ,org-ref-cite-color)))
340   "Color for cite-like links in org-ref.")
341
342
343 (defface org-ref-label-face
344   `((t (:inherit org-link :foreground ,org-ref-label-color)))
345   "Color for ref links in org-ref.")
346
347
348 (defface org-ref-ref-face
349   `((t (:inherit org-link :foreground ,org-ref-ref-color)))
350   "Face for ref links in org-ref.")
351
352
353 (defun org-ref-colorize-links ()
354   "Colorize org-ref links."
355   (hi-lock-mode 1)
356   (highlight-regexp org-ref-cite-re 'org-ref-cite-face)
357   (highlight-regexp org-ref-label-re 'org-ref-label-face)
358   (highlight-regexp org-ref-ref-re 'org-ref-ref-face))
359
360
361 (when org-ref-colorize-links
362   (add-hook 'org-mode-hook 'org-ref-colorize-links))
363
364 ;; * General org-ref utilities
365 (defun org-ref-strip-string (string)
366   "Strip leading and trailing whitespace from the STRING."
367   (replace-regexp-in-string
368    (concat search-whitespace-regexp "$" ) ""
369    (replace-regexp-in-string
370     (concat "^" search-whitespace-regexp ) "" string)))
371
372 (defun org-ref-split-and-strip-string (string)
373   "Split key-string and strip keys in STRING.
374 Assumes the key-string is comma delimited."
375   (mapcar 'org-ref-strip-string (split-string string ",")))
376
377 (defun org-ref-reftex-get-bib-field (field entry &optional format)
378   "Similar to reftex-get-bib-field, but removes enclosing braces and quotes in FIELD in the bibtex ENTRY.
379 Optional argument FORMAT bibtex format."
380   (let ((result))
381     (setq result (reftex-get-bib-field field entry format))
382     (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
383       (setq result (substring result 1 -1)))
384     (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
385       (setq result (substring result 1 -1)))
386       result))
387
388 (defun org-ref-reftex-format-citation (entry format)
389   "Return a formatted string for the bibtex ENTRY (from bibtex-parse-entry) according to the FORMAT argument.
390 The format is a string with these percent escapes.
391
392 In the format, the following percent escapes will be expanded.
393
394 %l   The BibTeX label of the citation.
395 %a   List of author names, see also `reftex-cite-punctuation'.
396 %2a  Like %a, but abbreviate more than 2 authors like Jones et al.
397 %A   First author name only.
398 %e   Works like %a, but on list of editor names. (%2e and %E work a well)
399
400 It is also possible to access all other BibTeX database fields:
401 %b booktitle     %c chapter        %d edition    %h howpublished
402 %i institution   %j journal        %k key        %m month
403 %n number        %o organization   %p pages      %P first page
404 %r address       %s school         %u publisher  %t title
405 %v volume        %y year
406 %B booktitle, abbreviated          %T title, abbreviated
407 %U url
408 %D doi
409 %S series
410
411 Usually, only %l is needed.  The other stuff is mainly for the echo area
412 display, and for (setq reftex-comment-citations t).
413
414 %< as a special operator kills punctuation and space around it after the
415 string has been formatted.
416
417 A pair of square brackets indicates an optional argument, and RefTeX
418 will prompt for the values of these arguments.
419
420 Beware that all this only works with BibTeX database files.  When
421 citations are made from the \bibitems in an explicit thebibliography
422 environment, only %l is available."
423   ;; Format a citation from the info in the BibTeX ENTRY
424   (unless (stringp format) (setq format "\\cite{%l}"))
425
426   (if (and reftex-comment-citations
427            (string-match "%l" reftex-cite-comment-format))
428       (error "Reftex-cite-comment-format contains invalid %%l"))
429
430   (while (string-match
431           "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
432           format)
433     (let ((n (string-to-number (match-string 4 format)))
434           (l (string-to-char (match-string 5 format)))
435           rpl b e)
436       (save-match-data
437         (setq rpl
438               (cond
439                ((= l ?l) (concat
440                           (org-ref-reftex-get-bib-field "&key" entry)
441                           (if reftex-comment-citations
442                               reftex-cite-comment-format
443                             "")))
444                ((= l ?a) (reftex-format-names
445                           (reftex-get-bib-names "author" entry)
446                           (or n 2)))
447                ((= l ?A) (car (reftex-get-bib-names "author" entry)))
448                ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
449                ((= l ?B) (reftex-abbreviate-title
450                           (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
451                ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
452                ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
453                ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
454                ((= l ?e) (reftex-format-names
455                           (reftex-get-bib-names "editor" entry)
456                           (or n 2)))
457                ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
458                ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
459                ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
460                ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
461                ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
462                ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
463                ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
464                ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
465                ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
466                ((= l ?P) (car (split-string
467                                (org-ref-reftex-get-bib-field "pages" entry)
468                                "[- .]+")))
469                ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
470                ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
471                ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
472                ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
473                ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
474                ;; strip enclosing brackets from title if they are there
475                ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
476                ((= l ?T) (reftex-abbreviate-title
477                           (org-ref-reftex-get-bib-field "title" entry)))
478                ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
479                ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
480
481       (if (string= rpl "")
482           (setq b (match-beginning 2) e (match-end 2))
483         (setq b (match-beginning 3) e (match-end 3)))
484       (setq format (concat (substring format 0 b) rpl (substring format e)))))
485   (while (string-match "%%" format)
486     (setq format (replace-match "%" t t format)))
487   (while (string-match "[ ,.;:]*%<" format)
488     (setq format (replace-match "" t t format)))
489   ;; also replace carriage returns, tabs, and multiple whitespaces
490   (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
491   format)
492
493 (defun org-ref-get-bibtex-entry-citation (key)
494   "Return a string for the bibliography entry corresponding to KEY.
495 Format according to the type in `org-ref-bibliography-entry-format'."
496
497   (let ((org-ref-bibliography-files (org-ref-find-bibliography))
498         (file) (entry) (bibtex-entry) (entry-type) (format))
499
500     (setq file (catch 'result
501                  (loop for file in org-ref-bibliography-files do
502                        (if (org-ref-key-in-file-p key (file-truename file))
503                            (throw 'result file)
504                          (message "%s not found in %s"
505                                   key (file-truename file))))))
506
507     (with-temp-buffer
508       (insert-file-contents file)
509       (bibtex-search-entry key nil 0)
510       (setq bibtex-entry (bibtex-parse-entry))
511       ;; downcase field names so they work in the format-citation code
512       (dolist (cons-cell bibtex-entry)
513         (setf (car cons-cell) (downcase (car cons-cell))))
514       (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
515       (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
516       (if format
517           (setq entry  (org-ref-reftex-format-citation bibtex-entry format))
518         ;; if no format, we use the bibtex entry itself as a fallback
519         (save-restriction
520           (bibtex-narrow-to-entry)
521           (setq entry (buffer-string)))))
522     entry))
523
524 (defun org-ref-get-bibtex-keys ()
525   "Return a list of unique keys in the buffer."
526   (let ((keys '()))
527     (org-element-map (org-element-parse-buffer) 'link
528       (lambda (link)
529         (let ((plist (nth 1 link)))
530           (when (-contains? org-ref-cite-types (plist-get plist ':type))
531             (dolist
532                 (key
533                  (org-ref-split-and-strip-string (plist-get plist ':path)))
534               (when (not (-contains? keys key))
535                 (setq keys (append keys (list key))))))))
536       ;; set with-affiliated to get keys in captions
537       nil nil nil t)
538     ;; Sort keys alphabetically
539     (setq keys (cl-sort keys 'string-lessp :key 'downcase))
540     keys))
541
542 (defun org-ref-get-bibtex-entry-html (key)
543   "Return an html string for the bibliography entry corresponding to KEY."
544   (let ((output))
545     (setq output (org-ref-get-bibtex-entry-citation key))
546     ;; unescape the &
547     (setq output (replace-regexp-in-string "\\\\&" "&" output))
548     ;; hack to replace {} around text
549     (setq output (replace-regexp-in-string "{" "" output))
550     (setq output (replace-regexp-in-string "}" "" output))
551     ;; get rid of empty parens
552     (setq output (replace-regexp-in-string "()" "" output))
553     ;; get rid of empty link and doi
554     (setq output (replace-regexp-in-string " <a href=\"\">link</a>\\." "" output))
555     (setq output (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" output))
556     (format "<li><a id=\"%s\">[%s] %s</a></li>"
557             key key output)))
558
559 (defun org-ref-get-html-bibliography ()
560   "Create an html bibliography when there are keys."
561   (let ((keys (org-ref-get-bibtex-keys)))
562     (when keys
563       (concat "<h1>Bibliography</h1>
564 <ul>"
565               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
566               "\n</ul>"))))
567
568 (defun org-ref-get-bibtex-entry-org (key)
569   "Return an org string for the bibliography entry corresponding to KEY."
570   (let ((org-ref-bibliography-files (org-ref-find-bibliography))
571         (file) (entry) (bibtex-entry) (entry-type) (format))
572
573     (setq file (catch 'result
574                  (loop for file in org-ref-bibliography-files do
575                        (if (org-ref-key-in-file-p key (file-truename file))
576                            (throw 'result file)
577                          (message "%s not found in %s" key (file-truename file))))))
578
579     (with-temp-buffer
580       (insert-file-contents file)
581       (bibtex-search-entry key nil 0)
582       (setq entry (bibtex-parse-entry))
583       (format "** %s - %s
584   :PROPERTIES:
585   %s
586   :END:
587 " (org-ref-reftex-get-bib-field "author" entry)
588 (org-ref-reftex-get-bib-field "title" entry)
589 (concat "   :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
590         (mapconcat (lambda (element) (format "   :%s: %s"
591                                              (upcase (car element))
592                                              (cdr element)))
593                    entry
594                    "\n"))))))
595
596 (defun org-ref-get-org-bibliography ()
597   "Create an org bibliography when there are keys."
598   (let ((keys (org-ref-get-bibtex-keys)))
599     (when keys
600       (concat "* Bibliography
601 "
602               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
603               "\n"))))
604
605 (defun org-ref-get-bibtex-entry-ascii (key)
606   "Return an ascii string for the bibliography entry corresponding to KEY."
607
608   (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
609
610 (defun org-ref-get-ascii-bibliography ()
611   "Create an html bibliography when there are keys."
612   (let ((keys (org-ref-get-bibtex-keys)))
613     (when keys
614       (concat
615 "Bibliography
616 =============
617 "
618               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
619               "\n"))))
620
621 ;; * Links
622 ;; ** bibliography and bibliographystyle
623 (org-add-link-type "bibliography"
624                    ;; this code is run on clicking. The bibliography
625                    ;; may contain multiple files. this code finds the
626                    ;; one you clicked on and opens it.
627                    (lambda (link-string)
628                        ;; get link-string boundaries we have to go to the
629                        ;; beginning of the line, and then search forward
630                      (let* ((bibfile)
631                             ;; object is the link you clicked on
632                             (object (org-element-context))
633                             (link-string-beginning)
634                             (link-string-end)
635                             (cp (point)))
636                      (save-excursion
637                        (goto-char (org-element-property :begin object))
638                        (search-forward link-string nil nil 1)
639                        (setq link-string-beginning (match-beginning 0))
640                        (setq link-string-end (match-end 0)))
641
642                      ;; Make sure point is in the link-path.
643                      (if (< cp link-string-beginning)
644                          (goto-char link-string-beginning))
645                      ;; We set the reftex-default-bibliography
646                      ;; here. it should be a local variable only in
647                      ;; the current buffer. We need this for using
648                      ;; reftex to do citations.
649                      (set (make-local-variable 'reftex-default-bibliography)
650                           (split-string
651                            (org-element-property :path object) ","))
652
653                      ;; now if we have comma separated bibliographies
654                      ;; we find the one clicked on. we want to
655                      ;; search forward to next comma from point
656                      (save-excursion
657                        (if (search-forward "," link-string-end 1 1)
658                            ;; we found a match
659                            (setq key-end (- (match-end 0) 1))
660                          ;; no comma found so take the point
661                          (setq key-end (point))))
662                      ;; and backward to previous comma from point
663                      (save-excursion
664                        (if (search-backward "," link-string-beginning 1 1)
665                            ;; we found a match
666                            (setq key-beginning (+ (match-beginning 0) 1))
667                          (setq key-beginning (point)))) ; no match found
668                        ;; save the key we clicked on.
669                      (setq bibfile (org-ref-strip-string
670                                     (buffer-substring key-beginning key-end)))
671                      ;; open file on click
672                      (find-file bibfile)))
673
674                    ;; formatting code
675                    (lambda (keyword desc format)
676                      (cond
677                       ((eq format 'org) (org-ref-get-org-bibliography))
678                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
679                       ((eq format 'html) (org-ref-get-html-bibliography))
680                       ((eq format 'latex)
681                        ;; write out the latex bibliography command
682                        (format "\\bibliography{%s}"
683                                (replace-regexp-in-string
684                                 "\\.bib" ""
685                                 (mapconcat
686                                  'identity
687                                  (mapcar 'expand-file-name
688                                          (split-string keyword ","))
689                                  ",")))))))
690
691 (org-add-link-type "nobibliography"
692                    ;; this code is run on clicking. The bibliography
693                    ;; may contain multiple files. this code finds the
694                    ;; one you clicked on and opens it.
695                    (lambda (link-string)
696                        ;; get link-string boundaries
697                        ;; we have to go to the beginning of the line, and then search forward
698
699                      (let* ((bibfile)
700                             ;; object is the link you clicked on
701                             (object (org-element-context))
702
703                             (link-string-beginning)
704                             (link-string-end))
705
706                      (save-excursion
707                        (goto-char (org-element-property :begin object))
708                        (search-forward link-string nil nil 1)
709                        (setq link-string-beginning (match-beginning 0))
710                        (setq link-string-end (match-end 0)))
711
712                        ;; We set the reftex-default-bibliography
713                        ;; here. it should be a local variable only in
714                        ;; the current buffer. We need this for using
715                        ;; reftex to do citations.
716                        (set (make-local-variable 'reftex-default-bibliography)
717                             (split-string (org-element-property :path object) ","))
718
719                        ;; now if we have comma separated bibliographies
720                        ;; we find the one clicked on. we want to
721                        ;; search forward to next comma from point
722                        (save-excursion
723                          (if (search-forward "," link-string-end 1 1)
724                              (setq key-end (- (match-end 0) 1)) ; we found a match
725                            (setq key-end (point)))) ; no comma found so take the point
726                        ;; and backward to previous comma from point
727                        (save-excursion
728                          (if (search-backward "," link-string-beginning 1 1)
729                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
730                            (setq key-beginning (point)))) ; no match found
731                        ;; save the key we clicked on.
732                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
733                        (find-file bibfile))) ; open file on click
734
735                      ;; formatting code
736                    (lambda (keyword desc format)
737                      (cond
738                       ((eq format 'org) (org-ref-get-org-bibliography))
739                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
740                       ((eq format 'html) (org-ref-get-html-bibliography))
741                       ((eq format 'latex)
742                        ;; write out the latex bibliography command
743                        (format "\\nobibliography{%s}"
744                                (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
745                                                                                  (mapcar 'expand-file-name
746                                                                                          (split-string keyword ","))
747                                                                                  ",")))))))
748
749 (org-add-link-type "printbibliography"
750                    (lambda (arg) (message "Nothing implemented for clicking here."))
751                    (lambda (keyword desc format)
752                      (cond
753                       ((eq format 'org) (org-ref-get-org-bibliography))
754                       ((eq format 'html) (org-ref-get-html-bibliography))
755                       ((eq format 'latex)
756                        ;; write out the biblatex bibliography command
757                        "\\printbibliography"))))
758
759 (org-add-link-type "bibliographystyle"
760                    (lambda (arg) (message "Nothing implemented for clicking here."))
761                    (lambda (keyword desc format)
762                      (cond
763                       ((eq format 'latex)
764                        ;; write out the latex bibliography command
765                        (format "\\bibliographystyle{%s}" keyword))
766                       ;; Other styles should not have an output for this
767                       (t
768                        ""))))
769
770
771 (defun org-bibliographystyle-complete-link (&optional arg)
772   "Completion function for bibliographystyle link.
773 ARG does nothing."
774   (format "bibliographystyle:%s" (ido-completing-read
775                                   "style: "
776                                   '("unsrt" "plain" "alpha"
777                                     ;; natbib
778                                     ;; https://www.sharelatex.com/learn/Natbib_bibliography_styles
779                                     "dinat" "humannat" "plainnat"
780                                     "abbrnat" "unsrtnat" "rusnat"
781                                     "ksfhnat"))))
782
783
784 (defun org-bibliography-complete-link (&optional arg)
785   "Completion function for bibliography link.
786 ARG does nothing."
787   (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
788
789
790 (defun org-ref-insert-bibliography-link ()
791   "Insert a bibliography with completion."
792   (interactive)
793   (insert (org-bibliography-complete-link)))
794
795 ;; ** addbibresource
796
797 (org-add-link-type "addbibresource"
798                    ;; this code is run on clicking. The addbibresource
799                    ;; may contain multiple files. this code finds the
800                    ;; one you clicked on and opens it.
801                    (lambda (link-string)
802                        ;; get link-string boundaries
803                        ;; we have to go to the beginning of the line, and then search forward
804
805                      (let* ((bibfile)
806                             ;; object is the link you clicked on
807                             (object (org-element-context))
808
809                             (link-string-beginning)
810                             (link-string-end))
811
812                      (save-excursion
813                        (goto-char (org-element-property :begin object))
814                        (search-forward link-string nil nil 1)
815                        (setq link-string-beginning (match-beginning 0))
816                        (setq link-string-end (match-end 0)))
817
818                        ;; We set the reftex-default-addbibresource
819                        ;; here. it should be a local variable only in
820                        ;; the current buffer. We need this for using
821                        ;; reftex to do citations.
822                        (set (make-local-variable 'reftex-default-addbibresource)
823                             (split-string (org-element-property :path object) ","))
824
825                        ;; now if we have comma separated bibliographies
826                        ;; we find the one clicked on. we want to
827                        ;; search forward to next comma from point
828                        (save-excursion
829                          (if (search-forward "," link-string-end 1 1)
830                              (setq key-end (- (match-end 0) 1)) ; we found a match
831                            (setq key-end (point)))) ; no comma found so take the point
832                        ;; and backward to previous comma from point
833                        (save-excursion
834                          (if (search-backward "," link-string-beginning 1 1)
835                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
836                            (setq key-beginning (point)))) ; no match found
837                        ;; save the key we clicked on.
838                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
839                        (find-file bibfile))) ; open file on click
840
841                      ;; formatting code
842                    (lambda (keyword desc format)
843                      (cond
844                       ((eq format 'html) (format "")); no output for html
845                       ((eq format 'latex)
846                          ;; write out the latex addbibresource command
847                        (format "\\addbibresource{%s}" keyword)))))
848
849 ;; ** List of figures
850 (defun org-ref-list-of-figures (&optional arg)
851   "Generate buffer with list of figures in them.
852 ARG does nothing."
853   (interactive)
854   (save-excursion (widen)
855   (let* ((c-b (buffer-name))
856          (counter 0)
857          (list-of-figures
858           (org-element-map (org-element-parse-buffer) 'link
859             (lambda (link)
860               "create a link for to the figure"
861               (when
862                   (and (string= (org-element-property :type link) "file")
863                        (string-match-p
864                         "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
865                         (org-element-property :path link)))
866                 (incf counter)
867
868                 (let* ((start (org-element-property :begin link))
869                        (parent (car (cdr (org-element-property :parent link))))
870                        (caption (caaar (plist-get parent :caption)))
871                        (name (plist-get parent :name)))
872                   (if caption
873                       (format
874                        "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
875                        c-b start counter (or name "") caption)
876                     (format
877                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
878                      c-b start counter (or name "")))))))))
879     (switch-to-buffer "*List of Figures*")
880     (setq buffer-read-only nil)
881     (org-mode)
882     (erase-buffer)
883     (insert (mapconcat 'identity list-of-figures ""))
884     (setq buffer-read-only t)
885     (use-local-map (copy-keymap org-mode-map))
886     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
887
888 (org-add-link-type
889  "list-of-figures"
890  'org-ref-list-of-figures ; on click
891  (lambda (keyword desc format)
892    (cond
893     ((eq format 'latex)
894      (format "\\listoffigures")))))
895
896 ;; ** List of tables
897 (defun org-ref-list-of-tables (&optional arg)
898   "Generate a buffer with a list of tables.
899 ARG does nothing."
900   (interactive)
901   (save-excursion
902   (widen)
903   (let* ((c-b (buffer-name))
904          (counter 0)
905          (list-of-tables
906           (org-element-map (org-element-parse-buffer 'element) 'table
907             (lambda (table)
908               "create a link for to the table"
909               (incf counter)
910               (let ((start (org-element-property :begin table))
911                     (name  (org-element-property :name table))
912                     (caption (caaar (org-element-property :caption table))))
913                 (if caption
914                     (format
915                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
916                      c-b start counter (or name "") caption)
917                   (format
918                    "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
919                    c-b start counter (or name ""))))))))
920     (switch-to-buffer "*List of Tables*")
921     (setq buffer-read-only nil)
922     (org-mode)
923     (erase-buffer)
924     (insert (mapconcat 'identity list-of-tables ""))
925     (setq buffer-read-only t)
926     (use-local-map (copy-keymap org-mode-map))
927     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
928
929 (org-add-link-type
930  "list-of-tables"
931  'org-ref-list-of-tables
932  (lambda (keyword desc format)
933    (cond
934     ((eq format 'latex)
935      (format "\\listoftables")))))
936
937
938 ;; ** label link
939 (defun org-ref-count-labels (label)
940   "Counts number of matches for LABEL in the document."
941   (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
942      ;; for tblname, it is not enough to get word boundary
943      ;; tab-little and tab-little-2 match then.
944      (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
945      (count-matches (format "\\label{%s}" label) (point-min) (point-max))
946      ;; this is the org-format #+label:
947      (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
948      (let ((custom-id-count 0))
949        (org-map-entries
950         (lambda ()
951           (when (string= label (org-entry-get (point) "CUSTOM_ID"))
952             (setq custom-id-count (+ 1 custom-id-count)))))
953        custom-id-count)))
954
955 (org-add-link-type
956  "label"
957  (lambda (label)
958    "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
959    (let ((count (org-ref-count-labels label)))
960    (message (format "%s occurence%s"
961                     count
962                     (if (or (= count 0)
963                               (> count 1))
964                         "s"
965                       ""))
966                     (org-ref-count-labels label))))
967  (lambda (keyword desc format)
968    (cond
969     ((eq format 'html) (format "(<label>%s</label>)" path))
970     ((eq format 'latex)
971      (format "\\label{%s}" keyword)))))
972
973 (defun org-label-store-link ()
974   "Store a link to a label.  The output will be a ref to that label."
975   ;; First we have to make sure we are on a label link.
976   (let* ((object (org-element-context)))
977     (when (and (equal (org-element-type object) 'link)
978                (equal (org-element-property :type object) "label"))
979       (org-store-link-props
980        :type "ref"
981        :link (concat "ref:" (org-element-property :path object))))
982
983     ;; Store link on table
984     (when (equal (org-element-type object) 'table)
985       (org-store-link-props
986        :type "ref"
987        :link (concat "ref:" (org-element-property :name object))))
988
989     ;; store link on heading with custom_id
990     ;; this is not a ref link, but it is still what you want
991     (when (and (equal (org-element-type object) 'headline)
992                (org-entry-get (point) "CUSTOM_ID"))
993       (org-store-link-props
994        :type "custom_id"
995        :link (format "[[#%s]]" (org-entry-get (point) "CUSTOM_ID"))))
996
997     ;; and to #+label: lines
998
999     (when (and (equal (org-element-type object) 'paragraph)
1000                (org-element-property :name object))
1001       (org-store-link-props
1002        :type "ref"
1003        :link (concat "ref:" (org-element-property :name object))))))
1004
1005 (add-hook 'org-store-link-functions 'org-label-store-link)
1006
1007 ;; ** ref link
1008 (org-add-link-type
1009  "ref"
1010  (lambda (label)
1011    "on clicking goto the label. Navigate back with C-c &"
1012    (org-mark-ring-push)
1013    ;; next search from beginning of the buffer
1014    ;; it is possible you would not find the label if narrowing is in effect
1015    (widen)
1016    (unless
1017        (or
1018         ;; our label links
1019         (progn
1020           (goto-char (point-min))
1021           (re-search-forward (format "label:%s\\b" label) nil t))
1022
1023         ;; a latex label
1024         (progn
1025           (goto-char (point-min))
1026           (re-search-forward (format "\\label{%s}" label) nil t))
1027
1028         ;; #+label: name  org-definition
1029         (progn
1030           (goto-char (point-min))
1031           (re-search-forward
1032            (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1033
1034         ;; org tblname
1035         (progn
1036           (goto-char (point-min))
1037           (re-search-forward
1038            (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1039
1040      ;; we did not find anything, so go back to where we came
1041      (org-mark-ring-goto)
1042      (error "%s not found" label))
1043    (org-show-entry)
1044    (message "go back with (org-mark-ring-goto) `C-c &`"))
1045  ;formatting
1046  (lambda (keyword desc format)
1047    (cond
1048     ((eq format 'html) (format "(<ref>%s</ref>)" path))
1049     ((eq format 'latex)
1050      (format "\\ref{%s}" keyword)))))
1051
1052
1053 (defun org-ref-get-org-labels ()
1054  "Return a list of #+LABEL: labels."
1055   (save-excursion
1056     (goto-char (point-min))
1057     (let ((matches '()))
1058       (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1059         ;; do not do this for tables. We get those in `org-ref-get-tblnames'.
1060         ;; who would have thought you have save match data here? Trust me. When
1061         ;; I wrote this, you did.
1062         (unless (save-match-data  (equal (car (org-element-at-point)) 'table))
1063           (add-to-list 'matches (match-string-no-properties 1) t)))
1064       matches)))
1065
1066
1067 (defun org-ref-get-custom-ids ()
1068  "Return a list of custom_id properties in the buffer."
1069  (let ((results '()) custom_id)
1070    (org-map-entries
1071     (lambda ()
1072       (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1073         (when (not (null custom_id))
1074           (setq results (append results (list custom_id)))))))
1075    results))
1076
1077
1078 (defun org-ref-get-latex-labels ()
1079   "Return list of matchin LaTeX defined labels in buffer."
1080   (save-excursion
1081     (goto-char (point-min))
1082     (let ((matches '()))
1083       (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1084         (add-to-list 'matches (match-string-no-properties 1) t))
1085       matches)))
1086
1087
1088 (defun org-ref-get-tblnames ()
1089   "Return list of table names in the buffer."
1090   (org-element-map (org-element-parse-buffer 'element) 'table
1091     (lambda (table)
1092       (org-element-property :name table))))
1093
1094
1095 (defun org-ref-get-labels ()
1096   "Return a list of labels in the buffer that you can make a ref link to.
1097 This is used to complete ref links and in helm menus."
1098   (save-excursion
1099     (save-restriction
1100       (widen)
1101       (goto-char (point-min))
1102       (let ((matches '()))
1103         ;; these are the org-ref label:stuff  kinds
1104         (while (re-search-forward
1105                 "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1106           (add-to-list 'matches (match-string-no-properties 1) t))
1107         ;; now add all the other kinds of labels.
1108         (append matches
1109                 ;; #+label:
1110                 (org-ref-get-org-labels)
1111                 ;; \label{}
1112                 (org-ref-get-latex-labels)
1113                 ;; #+tblname: and actually #+label
1114                 (org-ref-get-tblnames)
1115                 ;; CUSTOM_IDs
1116                 (org-ref-get-custom-ids))))))
1117
1118
1119 (defun org-ref-helm-insert-label-link ()
1120   "Insert a label link. helm just shows you what labels already exist.
1121 If you are on a label link, replace it."
1122   (interactive)
1123   (let* ((labels (org-ref-get-labels))
1124          (cb (current-buffer)))
1125     (helm :sources `(((name . "Existing labels")
1126                       (candidates . ,labels)
1127                       ;; default action is to open to the label
1128                       (action . (lambda (label)
1129                                   ;; unfortunately I do not have markers here
1130                                   (org-open-link-from-string
1131                                    (format "ref:%s" label))))
1132                       ;; if you select a label, replace current one
1133                       (action . (lambda (label)
1134                                   (switch-to-buffer ,cb)
1135                                   (cond
1136                                    ;;  no prefix or on a link
1137                                    ((equal helm-current-prefix-arg nil)
1138                                     (let* ((object (org-element-context))
1139                                            (last-char (save-excursion
1140                                                         (goto-char (org-element-property :end object))
1141                                                         (backward-char)
1142                                                         (if (looking-at " ")
1143                                                             " "
1144                                                           ""))))
1145                                       (when (-contains? '("label")
1146                                                         (org-element-property :type object))
1147                                           ;; we are on a link, so replace it.
1148                                         (setf
1149                                            (buffer-substring
1150                                             (org-element-property :begin object)
1151                                             (org-element-property :end object))
1152                                            (concat
1153                                             (replace-regexp-in-string
1154                                              (org-element-property :path object)
1155                                              label
1156                                              (org-element-property :raw-link object))
1157                                             last-char)))))
1158                                    ;; no prefix options defined
1159                                    ))))
1160                      ;; no matching selection creates a new label
1161                      ((name . "Create new label")
1162                       (dummy)
1163                       ;; default action creates a new label, or replaces old one
1164                       (action .  (lambda (label)
1165                                    (switch-to-buffer ,cb)
1166                                    (let* ((object (org-element-context))
1167                                           (last-char (save-excursion
1168                                                        (goto-char (org-element-property :end object))
1169                                                        (backward-char)
1170                                                        (if (looking-at " ")
1171                                                            " "
1172                                                          ""))))
1173                                      (if (-contains? '("label")
1174                                                      (org-element-property :type object))
1175                                          ;; we are on a link, so replace it.
1176                                          (setf
1177                                           (buffer-substring
1178                                            (org-element-property :begin object)
1179                                            (org-element-property :end object))
1180                                           (concat
1181                                            (replace-regexp-in-string
1182                                             (org-element-property :path object)
1183                                             helm-pattern
1184                                             (org-element-property :raw-link object))
1185                                            last-char))
1186                                        ;; new link
1187                                        (insert
1188                                         (concat
1189                                          "label:"
1190                                          (or label
1191                                              helm-pattern))))))))))))
1192
1193
1194 (defun org-ref-complete-link (&optional arg)
1195   "Completion function for ref links.
1196 Optional argument ARG Does nothing."
1197   (let ((label))
1198     (setq label (completing-read "label: " (org-ref-get-labels)))
1199     (format "ref:%s" label)))
1200
1201
1202 (defun org-ref-insert-ref-link ()
1203   "Completion function for a ref link."
1204  (interactive)
1205  (insert (org-ref-complete-link)))
1206
1207
1208 (defun org-ref-helm-insert-ref-link ()
1209   "Helm menu to insert ref links to labels in the document.
1210 If you are on link, replace with newly selected label.
1211 Use C-u to insert a different kind of ref link.
1212 Use C-u C-u to insert a [[#custom-id]] link"
1213   (interactive)
1214   (let* ((labels (org-ref-get-labels))
1215          (bs (buffer-string))
1216          (contexts (with-temp-buffer
1217                      (insert bs)
1218                      (mapcar 'org-ref-get-label-context labels)))
1219          (cb (current-buffer)))
1220
1221     (helm :input (thing-at-point 'word)
1222           :sources `(((name . "Available labels to ref")
1223                       (candidates . ,(loop for label in labels
1224                                            for context in contexts
1225                                            ;; we do some kludgy adding spaces
1226                                            ;; and bars to make it "easier" to
1227                                            ;; see in helm.
1228                                            collect (cons (concat
1229                                                           label "\n"
1230                                                           (mapconcat
1231                                                            (lambda (x)
1232                                                              (concat "   |" x))
1233                                                            (split-string context "\n")
1234                                                            "\n"
1235                                                            ) "\n\n") label)))
1236                       ;; default action to replace or insert ref link.
1237                       (action . (lambda (label)
1238                                   (switch-to-buffer ,cb)
1239
1240                                   (cond
1241                                    ;;  no prefix or on a link
1242                                    ((equal helm-current-prefix-arg nil)
1243                                     (let* ((object (org-element-context))
1244                                            (last-char (save-excursion
1245                                                         (goto-char (org-element-property :end object))
1246                                                         (backward-char)
1247                                                         (if (looking-at " ")
1248                                                             " "
1249                                                           ""))))
1250                                       (if (-contains? '("ref" "eqref" "pageref" "nameref")
1251                                                       (org-element-property :type object))
1252                                           ;; we are on a link, so replace it.
1253                                           (setf
1254                                            (buffer-substring
1255                                             (org-element-property :begin object)
1256                                             (org-element-property :end object))
1257                                            (concat
1258                                             (replace-regexp-in-string
1259                                              (org-element-property :path object)
1260                                              label
1261                                              (org-element-property :raw-link object))
1262                                             last-char))
1263                                         ;; insert a new link
1264                                         (insert
1265                                          (concat
1266                                           "ref:" label))
1267                                         )))
1268                                    ;; one prefix, alternate ref link
1269                                    ((equal helm-current-prefix-arg '(4))
1270                                     (insert
1271                                      (concat
1272                                       (helm :sources '((name . "Ref link types")
1273                                                        (candidates . ("ref" "eqref" "pageref" "nameref"))
1274                                                        (action . (lambda (x) x))))
1275                                       ":" label)))
1276                                    ;; two prefixes, insert section custom-id link
1277                                    ((equal helm-current-prefix-arg '(16))
1278                                     (insert
1279                                      (format "[[#%s]]" label)))
1280                                    ))
1281                               ))))))
1282
1283 ;; *** pageref link
1284 (org-add-link-type
1285  "pageref"
1286  (lambda (label)
1287    "on clicking goto the label. Navigate back with C-c &"
1288    (org-mark-ring-push)
1289    ;; next search from beginning of the buffer
1290    (widen)
1291    (unless
1292        (or
1293         ;; our label links
1294         (progn
1295           (goto-char (point-min))
1296           (re-search-forward (format "label:%s\\b" label) nil t))
1297
1298         ;; a latex label
1299         (progn
1300           (goto-char (point-min))
1301           (re-search-forward (format "\\label{%s}" label) nil t))
1302
1303         ;; #+label: name  org-definition
1304         (progn
1305           (goto-char (point-min))
1306           (re-search-forward
1307            (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1308
1309         ;; org tblname
1310         (progn
1311           (goto-char (point-min))
1312           (re-search-forward
1313            (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1314      ;; we did not find anything, so go back to where we came
1315      (org-mark-ring-goto)
1316      (error "%s not found" label))
1317    (message "go back with (org-mark-ring-goto) `C-c &`"))
1318  ;formatting
1319  (lambda (keyword desc format)
1320    (cond
1321     ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1322     ((eq format 'latex)
1323      (format "\\pageref{%s}" keyword)))))
1324
1325
1326 (defun org-pageref-complete-link (&optional arg)
1327   "Completion function for ref links.
1328 Optional argument ARG Does nothing."
1329   (let ((label))
1330     (setq label (completing-read "label: " (org-ref-get-labels)))
1331     (format "ref:%s" label)))
1332
1333
1334 (defun org-pageref-insert-ref-link ()
1335   "Insert a pageref link with completion."
1336  (interactive)
1337  (insert (org-pageref-complete-link)))
1338
1339
1340 ;; *** nameref link
1341 (org-add-link-type
1342  "nameref"
1343  (lambda (label)
1344    "on clicking goto the label. Navigate back with C-c &"
1345    (org-mark-ring-push)
1346    ;; next search from beginning of the buffer
1347    (widen)
1348    (unless
1349        (or
1350         ;; a latex label
1351         (progn
1352           (goto-char (point-min))
1353           (re-search-forward (format "\\label{%s}" label) nil t))
1354         )
1355      ;; we did not find anything, so go back to where we came
1356      (org-mark-ring-goto)
1357      (error "%s not found" label))
1358    (message "go back with (org-mark-ring-goto) `C-c &`"))
1359  ;formatting
1360  (lambda (keyword desc format)
1361    (cond
1362     ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1363     ((eq format 'latex)
1364      (format "\\nameref{%s}" keyword)))))
1365
1366 ;; *** eqref link
1367
1368 (org-add-link-type
1369  "eqref"
1370  (lambda (label)
1371    "on clicking goto the label. Navigate back with C-c &"
1372    (org-mark-ring-push)
1373    ;; next search from beginning of the buffer
1374    (widen)
1375    (goto-char (point-min))
1376    (unless
1377        (or
1378         ;; search forward for the first match
1379         ;; our label links
1380         (re-search-forward (format "label:%s" label) nil t)
1381         ;; a latex label
1382         (re-search-forward (format "\\label{%s}" label) nil t)
1383         ;; #+label: name  org-definition
1384         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1385      (org-mark-ring-goto)
1386      (error "%s not found" label))
1387    (message "go back with (org-mark-ring-goto) `C-c &`"))
1388  ;formatting
1389  (lambda (keyword desc format)
1390    (cond
1391     ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1392     ((eq format 'latex)
1393      (format "\\eqref{%s}" keyword)))))
1394
1395 ;; ** cite link
1396
1397 (defun org-ref-get-bibtex-key-under-cursor ()
1398   "Return key under the bibtex cursor.
1399 We search forward from
1400 point to get a comma, or the end of the link, and then backwards
1401 to get a comma, or the beginning of the link.  that delimits the
1402 keyword we clicked on.  We also strip the text properties."
1403   (let* ((object (org-element-context))
1404          (link-string (org-element-property :path object)))
1405     ;; you may click on the part before the citations. here we make
1406     ;; sure to move to the beginning so you get the first citation.
1407     (let ((cp (point)))
1408       (goto-char (org-element-property :begin object))
1409       (search-forward link-string (org-element-property :end object))
1410       (goto-char (match-beginning 0))
1411       ;; check if we clicked before the path and move as needed.
1412       (unless (< cp (point))
1413         (goto-char cp)))
1414
1415     (if (not (org-element-property :contents-begin object))
1416         ;; this means no description in the link
1417         (progn
1418           ;; we need the link path start and end
1419           (save-excursion
1420             (goto-char (org-element-property :begin object))
1421             (search-forward link-string nil nil 1)
1422             (setq link-string-beginning (match-beginning 0))
1423             (setq link-string-end (match-end 0)))
1424
1425           ;; The key is the text between commas, or the link boundaries
1426           (save-excursion
1427             (if (search-forward "," link-string-end t 1)
1428                 (setq key-end (- (match-end 0) 1)) ; we found a match
1429               (setq key-end link-string-end))) ; no comma found so take the end
1430           ;; and backward to previous comma from point which defines the start character
1431           (save-excursion
1432             (if (search-backward "," link-string-beginning 1 1)
1433                 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1434               (setq key-beginning link-string-beginning))) ; no match found
1435           ;; save the key we clicked on.
1436           (setq bibtex-key
1437                 (org-ref-strip-string
1438                  (buffer-substring key-beginning key-end)))
1439           (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1440           bibtex-key)
1441       ;; link with description. assume only one key
1442       link-string)))
1443
1444 (defun org-ref-find-bibliography ()
1445   "Find the bibliography in the buffer.
1446 This function sets and returns cite-bibliography-files, which is a list of files
1447 either from bibliography:f1.bib,f2.bib
1448 \bibliography{f1,f2}
1449 internal bibliographies
1450
1451 falling back to what the user has set in `org-ref-default-bibliography'"
1452   (catch 'result
1453     (save-excursion
1454       (goto-char (point-min))
1455       ;;  look for a bibliography link
1456       (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1457         (setq org-ref-bibliography-files
1458               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1459         (throw 'result org-ref-bibliography-files))
1460
1461
1462       ;; we did not find a bibliography link. now look for \bibliography
1463       (goto-char (point-min))
1464       (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1465         ;; split, and add .bib to each file
1466         (setq org-ref-bibliography-files
1467               (mapcar (lambda (x) (concat x ".bib"))
1468                       (mapcar 'org-ref-strip-string
1469                               (split-string (match-string 1) ","))))
1470         (throw 'result org-ref-bibliography-files))
1471
1472       ;; no bibliography found. maybe we need a biblatex addbibresource
1473       (goto-char (point-min))
1474       ;;  look for a bibliography link
1475       (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1476         (setq org-ref-bibliography-files
1477               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1478         (throw 'result org-ref-bibliography-files))
1479
1480       ;; we did not find anything. use defaults
1481       (setq org-ref-bibliography-files org-ref-default-bibliography)))
1482
1483     ;; set reftex-default-bibliography so we can search
1484     (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1485     org-ref-bibliography-files)
1486
1487 (defun org-ref-key-in-file-p (key filename)
1488   "Determine if the KEY is in the FILENAME."
1489   (save-current-buffer
1490     (let ((bibtex-files (list filename)))
1491       ;; This is something I am trying because when the bibtex file is open, and
1492       ;; you have added to it, the only way I find to get the update to update
1493       ;; is to close it and reopen it. or to save it and revert it.
1494       (when (get-file-buffer filename)
1495         (set-buffer (get-file-buffer filename))
1496         (save-buffer)
1497         (revert-buffer t t))
1498       (bibtex-search-entry key t))))
1499
1500 (defun org-ref-get-bibtex-key-and-file (&optional key)
1501   "Return the bibtex KEY and file that it is in.  If no key is provided, get one under point."
1502  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1503        (file))
1504    (unless key
1505      (setq key (org-ref-get-bibtex-key-under-cursor)))
1506    (setq file     (catch 'result
1507                     (loop for file in org-ref-bibliography-files do
1508                           (if (org-ref-key-in-file-p key (file-truename file))
1509                               (throw 'result file)))))
1510    (cons key file)))
1511
1512 ;; *** key at point functions
1513
1514 (defun org-ref-open-pdf-at-point ()
1515   "Open the pdf for bibtex key under point if it exists."
1516   (interactive)
1517   (let* ((results (org-ref-get-bibtex-key-and-file))
1518          (key (car results))
1519          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1520     (if (file-exists-p pdf-file)
1521         (org-open-file pdf-file)
1522 (message "no pdf found for %s" key))))
1523
1524
1525 (defun org-ref-open-url-at-point ()
1526   "Open the url for bibtex key under point."
1527   (interactive)
1528   (let* ((results (org-ref-get-bibtex-key-and-file))
1529          (key (car results))
1530          (bibfile (cdr results)))
1531     (save-excursion
1532       (with-temp-buffer
1533         (insert-file-contents bibfile)
1534         (bibtex-search-entry key)
1535         ;; I like this better than bibtex-url which does not always find
1536         ;; the urls
1537         (catch 'done
1538           (let ((url (bibtex-autokey-get-field "url")))
1539             (when  url
1540               (browse-url (s-trim url))
1541               (throw 'done nil)))
1542
1543           (let ((doi (bibtex-autokey-get-field "doi")))
1544             (when doi
1545               (if (string-match "^http" doi)
1546                   (browse-url doi)
1547                 (browse-url (format "http://dx.doi.org/%s" (s-trim doi))))
1548               (throw 'done nil))))))))
1549
1550
1551 (defun org-ref-open-notes-at-point ()
1552   "Open the notes for bibtex key under point."
1553   (interactive)
1554   (let* ((results (org-ref-get-bibtex-key-and-file))
1555          (key (car results))
1556          (bibfile (cdr results)))
1557     (save-excursion
1558       (with-temp-buffer
1559         (insert-file-contents bibfile)
1560         (bibtex-search-entry key)
1561         (org-ref-open-bibtex-notes)))))
1562
1563
1564 (defun org-ref-citation-at-point ()
1565   "Give message of current citation at point."
1566   (interactive)
1567   (let* ((cb (current-buffer))
1568         (results (org-ref-get-bibtex-key-and-file))
1569         (key (car results))
1570         (bibfile (cdr results)))
1571     (message "%s" (progn
1572                     (with-temp-buffer
1573                       (insert-file-contents bibfile)
1574                       (bibtex-search-entry key)
1575                       (org-ref-bib-citation))))))
1576
1577
1578 (defun org-ref-open-citation-at-point ()
1579   "Open bibtex file to key at point."
1580   (interactive)
1581   (let* ((cb (current-buffer))
1582         (results (org-ref-get-bibtex-key-and-file))
1583         (key (car results))
1584         (bibfile (cdr results)))
1585     (find-file bibfile)
1586     (bibtex-search-entry key)))
1587
1588 ;; *** cite menu
1589
1590 (defvar org-ref-cite-menu-funcs '()
1591  "Functions to run on cite click menu.
1592 Each entry is a list of (key menu-name function).
1593 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.")
1594
1595
1596 (defvar org-ref-user-cite-menu-funcs
1597   '(("C" "rossref" org-ref-crossref-at-point)
1598     ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1599     ("s" "Copy summary" org-ref-copy-entry-as-summary))
1600   "User-defined functions to run on bibtex key at point.")
1601
1602
1603 (defun org-ref-copy-entry-as-summary ()
1604   "Copy the bibtex entry for the citation at point as a summary."
1605   (interactive)
1606     (save-window-excursion
1607       (org-ref-open-citation-at-point)
1608       (kill-new (org-ref-bib-citation))))
1609
1610
1611 (defun org-ref-copy-entry-at-point-to-file ()
1612   "Copy the bibtex entry for the citation at point to NEW-FILE.
1613 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."
1614   (interactive)
1615   (let ((new-file (ido-completing-read
1616                    "Copy to bibfile: "
1617                    (append org-ref-default-bibliography
1618                            (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1619         (key (org-ref-get-bibtex-key-under-cursor)))
1620     (save-window-excursion
1621       (org-ref-open-citation-at-point)
1622       (bibtex-copy-entry-as-kill))
1623
1624     (let ((bibtex-files (list (file-truename new-file))))
1625       (if (assoc key (bibtex-global-key-alist))
1626           (message "That key already exists in %s" new-file)
1627         ;; add to file
1628         (save-window-excursion
1629           (find-file new-file)
1630           (goto-char (point-max))
1631           ;; make sure we are at the beginning of a line.
1632           (unless (looking-at "^") (insert "\n\n"))
1633           (bibtex-yank)
1634           (save-buffer))))))
1635
1636
1637 (defun org-ref-get-doi-at-point ()
1638   "Get doi for key at point."
1639   (let* ((results (org-ref-get-bibtex-key-and-file))
1640          (key (car results))
1641          (bibfile (cdr results))
1642          doi)
1643     (save-excursion
1644       (with-temp-buffer
1645         (insert-file-contents bibfile)
1646         (bibtex-search-entry key)
1647         (setq doi (bibtex-autokey-get-field "doi"))
1648         ;; in case doi is a url, remove the url part.
1649         (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1650
1651
1652 ;; **** functions that operate on key at point for click menu
1653 (defun org-ref-wos-at-point ()
1654   "Open the doi in wos for bibtex key under point."
1655   (interactive)
1656   (doi-utils-wos (org-ref-get-doi-at-point)))
1657
1658
1659 (defun org-ref-wos-citing-at-point ()
1660   "Open the doi in wos citing articles for bibtex key under point."
1661   (interactive)
1662   (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1663
1664
1665 (defun org-ref-wos-related-at-point ()
1666   "Open the doi in wos related articles for bibtex key under point."
1667   (interactive)
1668   (doi-utils-wos-related (org-ref-get-doi-at-point)))
1669
1670
1671 (defun org-ref-google-scholar-at-point ()
1672   "Open the doi in google scholar for bibtex key under point."
1673   (interactive)
1674   (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1675
1676
1677 (defun org-ref-pubmed-at-point ()
1678   "Open the doi in pubmed for bibtex key under point."
1679   (interactive)
1680   (doi-utils-pubmed (org-ref-get-doi-at-point)))
1681
1682
1683 (defun org-ref-crossref-at-point ()
1684   "Open the doi in crossref for bibtex key under point."
1685   (interactive)
1686   (doi-utils-crossref (org-ref-get-doi-at-point)))
1687
1688 ;; *** Minibuffer menu
1689
1690 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1691   "Action when a cite link is clicked on.
1692 Provides a menu of context sensitive actions.  If the bibtex entry
1693 has a pdf, you get an option to open it.  If there is a doi, you
1694 get a lot of options.  LINK-STRING is used by the link function."
1695   (interactive)
1696   (let* ((results (org-ref-get-bibtex-key-and-file))
1697          (key (car results))
1698          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1699          (bibfile (cdr results))
1700          (url (save-excursion
1701                 (with-temp-buffer
1702                   (insert-file-contents bibfile)
1703                   (bibtex-search-entry key)
1704                   (bibtex-autokey-get-field "url"))))
1705          (doi (save-excursion
1706                 (with-temp-buffer
1707                   (insert-file-contents bibfile)
1708                   (bibtex-search-entry key)
1709                   ;; I like this better than bibtex-url which does not always find
1710                   ;; the urls
1711                   (bibtex-autokey-get-field "doi")))))
1712
1713     (when (string= "" doi) (setq doi nil))
1714     (when (string= "" url) (setq url nil))
1715     (setq org-ref-cite-menu-funcs '())
1716
1717     ;; open action
1718     (when
1719         bibfile
1720       (add-to-list
1721        'org-ref-cite-menu-funcs
1722        '("o" "pen" org-ref-open-citation-at-point)))
1723
1724     ;; pdf
1725     (when (file-exists-p pdf-file)
1726       (add-to-list
1727        'org-ref-cite-menu-funcs
1728        `("p" "df" ,org-ref-open-pdf-function) t))
1729
1730     ;; notes
1731     (add-to-list
1732      'org-ref-cite-menu-funcs
1733      '("n" "otes" org-ref-open-notes-at-point) t)
1734
1735     ;; url
1736     (when (or url doi)
1737       (add-to-list
1738        'org-ref-cite-menu-funcs
1739        '("u" "rl" org-ref-open-url-at-point) t))
1740
1741     ;; doi funcs
1742     (when doi
1743       (add-to-list
1744        'org-ref-cite-menu-funcs
1745        '("w" "os" org-ref-wos-at-point) t)
1746
1747       (add-to-list
1748        'org-ref-cite-menu-funcs
1749        '("c" "iting" org-ref-wos-citing-at-point) t)
1750
1751       (add-to-list
1752        'org-ref-cite-menu-funcs
1753        '("r" "elated" org-ref-wos-related-at-point) t)
1754
1755       (add-to-list
1756        'org-ref-cite-menu-funcs
1757        '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1758
1759       (add-to-list
1760        'org-ref-cite-menu-funcs
1761        '("P" "ubmed" org-ref-pubmed-at-point) t))
1762
1763     ;; add user functions
1764     (dolist (tup org-ref-user-cite-menu-funcs)
1765       (add-to-list
1766        'org-ref-cite-menu-funcs
1767        tup t))
1768
1769     ;; finally quit
1770     (add-to-list
1771      'org-ref-cite-menu-funcs
1772      '("q" "uit" (lambda ())) t)
1773
1774     ;; now we make a menu
1775     ;; construct menu string as a message
1776     (message
1777      (concat
1778       (let* ((results (org-ref-get-bibtex-key-and-file))
1779              (key (car results))
1780              (bibfile (cdr results)))
1781         (save-excursion
1782           (with-temp-buffer
1783             (insert-file-contents bibfile)
1784             (bibtex-search-entry key)
1785             (org-ref-bib-citation))))
1786       "\n"
1787       (mapconcat
1788        (lambda (tup)
1789          (concat "[" (elt tup 0) "]"
1790                  (elt tup 1) " "))
1791        org-ref-cite-menu-funcs "")))
1792     ;; get the input
1793     (let* ((input (read-char-exclusive))
1794            (choice (assoc
1795                     (char-to-string input) org-ref-cite-menu-funcs)))
1796       ;; now run the function (2nd element in choice)
1797       (when choice
1798         (funcall
1799          (elt
1800           choice
1801           2))))))
1802
1803 ;; *** Generation of the cite links
1804 (defmacro org-ref-make-completion-function (type)
1805   "Macro to make a link completion function for a link of TYPE."
1806   `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1807      (interactive)
1808      (format "%s:%s"
1809              ,type
1810              (completing-read
1811               "bibtex key: "
1812               (let ((bibtex-files (org-ref-find-bibliography)))
1813                 (bibtex-global-key-alist))))))
1814
1815 (defmacro org-ref-make-format-function (type)
1816   "Macro to make a format function for a link of TYPE."
1817   `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1818      (cond
1819       ((eq format 'org)
1820        (mapconcat
1821         (lambda (key)
1822           (format "[[#%s][%s]]" key key))
1823         (org-ref-split-and-strip-string keyword) ","))
1824
1825       ((eq format 'ascii)
1826        (concat "["
1827                (mapconcat
1828                 (lambda (key)
1829                   (format "%s" key))
1830                 (org-ref-split-and-strip-string keyword) ",") "]"))
1831
1832       ((eq format 'html)
1833        (mapconcat
1834         (lambda (key)
1835           (format "<a href=\"#%s\">%s</a>" key key))
1836         (org-ref-split-and-strip-string keyword) ","))
1837
1838       ((eq format 'latex)
1839        (if (string= (substring type -1) "s")
1840            ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1841            (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}"  key))
1842                                          (org-ref-split-and-strip-string keyword) ""))
1843          ;; bibtex format
1844        (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1845                (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1846                "}")))
1847       ;; for markdown we generate pandoc citations
1848       ((eq format 'md)
1849        (cond
1850         (desc  ;; pre and or post text
1851          (let* ((text (split-string desc "::"))
1852                 (pre (car text))
1853                 (post (cadr text)))
1854            (concat
1855             (format "[@%s," keyword)
1856             (when pre (format " %s" pre))
1857             (when post (format ", %s" post))
1858             "]")))
1859         (t
1860          (format "[%s]"
1861                  (mapconcat
1862                   (lambda (key) (concat "@" key))
1863                   (org-ref-split-and-strip-string keyword)
1864                   "; "))))))))
1865
1866 (defun org-ref-format-citation-description (desc)
1867   "Return formatted citation description.
1868 If the cite link has a DESC (description), it is optional text
1869 for the citation command.  You can specify pre and post text by
1870 separating these with ::, for example [[cite:key][pre text::post
1871 text]]."
1872   (cond
1873    ((string-match "::" desc)
1874     (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1875    (t (format "[%s]" desc))))
1876
1877 (defun org-ref-define-citation-link (type &optional key)
1878   "Add a citation link of TYPE for org-ref.
1879 With optional KEY, set the reftex binding. For example:
1880 \(org-ref-define-citation-link \"citez\" ?z) will create a new
1881 citez link, with reftex key of z, and the completion function."
1882   (interactive "sCitation Type: \ncKey: ")
1883
1884   ;; create the formatting function
1885   (eval `(org-ref-make-format-function ,type))
1886
1887   (eval-expression
1888    `(org-add-link-type
1889      ,type
1890      org-ref-cite-onclick-function
1891      (quote ,(intern (format "org-ref-format-%s" type)))))
1892
1893   ;; create the completion function
1894   (eval `(org-ref-make-completion-function ,type))
1895
1896   ;; store new type so it works with adding citations, which checks
1897   ;; for existence in this list
1898   (add-to-list 'org-ref-cite-types type)
1899
1900   ;; and finally if a key is specified, we modify the reftex menu
1901   (when key
1902     (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1903           (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1904                   `((,key  . ,(concat type ":%l")))))))
1905
1906 ;; create all the link types and their completion functions
1907 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1908
1909 (defun org-ref-insert-cite-link (alternative-cite)
1910   "Insert a default citation link using reftex.
1911 If you are on a link, it appends to the end of the link,
1912 otherwise, a new link is inserted.  Use a prefix
1913 arg (ALTERNATIVE-CITE) to get a menu of citation types."
1914   (interactive "P")
1915   (org-ref-find-bibliography)
1916   (let* ((object (org-element-context))
1917          (link-string-beginning (org-element-property :begin object))
1918          (link-string-end (org-element-property :end object))
1919          (path (org-element-property :path object)))
1920
1921     (if (not alternative-cite)
1922
1923         (cond
1924          ;; case where we are in a link
1925          ((and (equal (org-element-type object) 'link)
1926                (-contains? org-ref-cite-types (org-element-property :type object)))
1927           (goto-char link-string-end)
1928           ;; sometimes there are spaces at the end of the link
1929           ;; this code moves point pack until no spaces are there
1930           (while (looking-back " ") (backward-char))
1931           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1932
1933          ;; We are next to a link, and we want to append
1934          ((save-excursion
1935             (backward-char)
1936             (and (equal (org-element-type (org-element-context)) 'link)
1937                  (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1938           (while (looking-back " ") (backward-char))
1939           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1940
1941          ;; insert fresh link
1942          (t
1943           (insert
1944            (concat org-ref-default-citation-link
1945                    ":"
1946                    (mapconcat 'identity (reftex-citation t) ",")))))
1947
1948       ;; you pressed a C-u so we run this code
1949       (reftex-citation))))
1950
1951 (defun org-ref-insert-cite-with-completion (type)
1952   "Insert a cite link of TYPE with completion."
1953   (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1954   (insert (funcall (intern (format "org-%s-complete-link" type)))))
1955
1956 (defun org-ref-store-bibtex-entry-link ()
1957   "Save a citation link to the current bibtex entry.  Save in the default link type."
1958   (interactive)
1959   (let ((link (concat org-ref-default-citation-link
1960                  ":"
1961                  (save-excursion
1962                    (bibtex-beginning-of-entry)
1963                    (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1964     (message "saved %s" link)
1965     (push (list link) org-stored-links)
1966     (car org-stored-links)))
1967
1968 ;; ** Index link
1969 (org-add-link-type
1970  "index"
1971  (lambda (path)
1972    (occur path))
1973
1974  (lambda (path desc format)
1975    (cond
1976     ((eq format 'latex)
1977       (format "\\index{%s}" path)))))
1978
1979 ;; this will generate a temporary index of entries in the file.
1980 (org-add-link-type
1981  "printindex"
1982  (lambda (path)
1983    (let ((*index-links* '())
1984          (*initial-letters* '()))
1985
1986      ;; get links
1987      (org-element-map (org-element-parse-buffer) 'link
1988        (lambda (link)
1989          (let ((type (nth 0 link))
1990                (plist (nth 1 link)))
1991
1992            (when (equal (plist-get plist ':type) "index")
1993              (add-to-list
1994               '*index-links*
1995               (cons (plist-get plist :path)
1996                     (format
1997                      "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
1998 (current-buffer)
1999                      (plist-get plist :begin)  ;; position of link
2000                      ;; grab a description
2001                      (save-excursion
2002                        (goto-char (plist-get plist :begin))
2003                        (if (thing-at-point 'sentence)
2004                            ;; get a sentence
2005                            (replace-regexp-in-string
2006                             "\n" "" (thing-at-point 'sentence))
2007                          ;; or call it a link
2008                          "link")))))))))
2009
2010      ;; sort the links
2011      (setq *index-links*  (cl-sort *index-links* 'string-lessp :key 'car))
2012
2013      ;; now first letters
2014      (dolist (link *index-links*)
2015        (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2016
2017      ;; now create the index
2018      (switch-to-buffer (get-buffer-create "*index*"))
2019      (org-mode)
2020      (erase-buffer)
2021      (insert "#+TITLE: Index\n\n")
2022      (dolist (letter *initial-letters*)
2023        (insert (format "* %s\n" (upcase letter)))
2024        ;; now process the links
2025        (while (and
2026                *index-links*
2027                (string= letter (substring (car (car *index-links*)) 0 1)))
2028          (let ((link (pop *index-links*)))
2029            (insert (format "%s %s\n\n" (car link) (cdr link))))))
2030      (switch-to-buffer "*index*")))
2031  ;; formatting
2032  (lambda (path desc format)
2033    (cond
2034     ((eq format 'latex)
2035       (format "\\printindex")))))
2036
2037 ;; ** Glossary link
2038 (org-add-link-type
2039  "newglossaryentry"
2040  nil ;; no follow action
2041  (lambda (path desc format)
2042    (cond
2043     ((eq format 'latex)
2044      (format "\\newglossaryentry{%s}{%s}" path desc)))))
2045
2046
2047 ;; link to entry
2048 (org-add-link-type
2049  "gls"
2050   nil ;; no follow action
2051  (lambda (path desc format)
2052    (cond
2053     ((eq format 'latex)
2054      (format "\\gls{%s}" path)))))
2055
2056 ;; plural
2057 (org-add-link-type
2058  "glspl"
2059   nil ;; no follow action
2060  (lambda (path desc format)
2061    (cond
2062     ((eq format 'latex)
2063      (format "\\glspl{%s}" path)))))
2064
2065 ;; capitalized link
2066 (org-add-link-type
2067  "Gls"
2068   nil ;; no follow action
2069  (lambda (path desc format)
2070    (cond
2071     ((eq format 'latex)
2072      (format "\\Gls{%s}" path)))))
2073
2074 ;; capitalized link
2075 (org-add-link-type
2076  "Glspl"
2077   nil ;; no follow action
2078  (lambda (path desc format)
2079    (cond
2080     ((eq format 'latex)
2081      (format "\\Glspl{%s}" path)))))
2082
2083 ;; * Utilities
2084 ;; ** create text citations from a bibtex entry
2085 (defun org-ref-bib-citation ()
2086   "From a bibtex entry, create and return a simple citation string.
2087 This assumes you are in an article."
2088
2089   (bibtex-beginning-of-entry)
2090   (let* ((cb (current-buffer))
2091          (bibtex-expand-strings t)
2092          (entry (loop for (key . value) in (bibtex-parse-entry t)
2093                       collect (cons (downcase key) value)))
2094          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2095          (year  (reftex-get-bib-field "year" entry))
2096          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2097          (key (reftex-get-bib-field "=key=" entry))
2098          (journal (reftex-get-bib-field "journal" entry))
2099          (volume (reftex-get-bib-field "volume" entry))
2100          (pages (reftex-get-bib-field "pages" entry))
2101          (doi (reftex-get-bib-field "doi" entry))
2102          (url (reftex-get-bib-field "url" entry))
2103          )
2104     ;;authors, "title", Journal, vol(iss):pages (year).
2105     (format "%s, \"%s\", %s, %s:%s (%s)"
2106             author title journal  volume pages year)))
2107
2108 (defun org-ref-bib-html-citation ()
2109   "From a bibtex entry, create and return a simple citation with html links."
2110   (bibtex-beginning-of-entry)
2111   (let* ((cb (current-buffer))
2112          (bibtex-expand-strings t)
2113          (entry (loop for (key . value) in (bibtex-parse-entry t)
2114                       collect (cons (downcase key) value)))
2115          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2116          (year  (reftex-get-bib-field "year" entry))
2117          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2118          (key (reftex-get-bib-field "=key=" entry))
2119          (journal (reftex-get-bib-field "journal" entry))
2120          (volume (reftex-get-bib-field "volume" entry))
2121          (pages (reftex-get-bib-field "pages" entry))
2122          (doi (reftex-get-bib-field "doi" entry))
2123          (url (reftex-get-bib-field "url" entry)))
2124     ;;authors, "title", Journal, vol(iss):pages (year).
2125     (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2126                     author title journal  volume pages year)
2127             (when url (format " <a href=\"%s\">link</a>" url))
2128             (when doi
2129               (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))))
2130
2131 ;; ** Open pdf in bibtex entry
2132 (defun org-ref-open-bibtex-pdf ()
2133   "Open pdf for a bibtex entry, if it exists.
2134 assumes point is in
2135 the entry of interest in the bibfile.  but does not check that."
2136   (interactive)
2137   (save-excursion
2138     (bibtex-beginning-of-entry)
2139     (let* ((bibtex-expand-strings t)
2140            (entry (bibtex-parse-entry t))
2141            (key (reftex-get-bib-field "=key=" entry))
2142            (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2143       (message "%s" pdf)
2144       (if (file-exists-p pdf)
2145           (org-open-link-from-string (format "[[file:%s]]" pdf))
2146         (ding)))))
2147
2148 ;; ** Open notes from bibtex entry
2149
2150 (defun org-ref-open-bibtex-notes ()
2151   "From a bibtex entry, open the notes if they exist, and create a heading if they do not.
2152
2153 I never did figure out how to use reftex to make this happen
2154 non-interactively. the reftex-format-citation function did not
2155 work perfectly; there were carriage returns in the strings, and
2156 it did not put the key where it needed to be. so, below I replace
2157 the carriage returns and extra spaces with a single space and
2158 construct the heading by hand."
2159   (interactive)
2160
2161   (bibtex-beginning-of-entry)
2162   (let* ((cb (current-buffer))
2163          (bibtex-expand-strings t)
2164          (entry (loop for (key . value) in (bibtex-parse-entry t)
2165                       collect (cons (downcase key) value)))
2166          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2167          (year  (reftex-get-bib-field "year" entry))
2168          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2169          (key (reftex-get-bib-field "=key=" entry))
2170          (journal (reftex-get-bib-field "journal" entry))
2171          (volume (reftex-get-bib-field "volume" entry))
2172          (pages (reftex-get-bib-field "pages" entry))
2173          (doi (reftex-get-bib-field "doi" entry))
2174          (url (reftex-get-bib-field "url" entry))
2175          )
2176
2177     ;; save key to clipboard to make saving pdf later easier by pasting.
2178     (with-temp-buffer
2179       (insert key)
2180       (kill-ring-save (point-min) (point-max)))
2181
2182     ;; now look for entry in the notes file
2183     (if  org-ref-bibliography-notes
2184         (find-file-other-window org-ref-bibliography-notes)
2185       (error "Org-ref-bib-bibliography-notes is not set to anything"))
2186
2187     (goto-char (point-min))
2188     ;; put new entry in notes if we don't find it.
2189     (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2190         (funcall org-ref-open-notes-function)
2191       ;; no entry found, so add one
2192       (insert (format "\n** TODO %s - %s" year title))
2193       (insert (format"
2194  :PROPERTIES:
2195   :Custom_ID: %s
2196   :AUTHOR: %s
2197   :JOURNAL: %s
2198   :YEAR: %s
2199   :VOLUME: %s
2200   :PAGES: %s
2201   :DOI: %s
2202   :URL: %s
2203  :END:
2204 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2205 key author journal year volume pages doi url key org-ref-pdf-directory key))
2206 (save-buffer))))
2207
2208 (defun org-ref-open-notes-from-reftex ()
2209   "Call reftex, and open notes for selected entry."
2210   (interactive)
2211   (let ((bibtex-key )))
2212
2213     ;; now look for entry in the notes file
2214     (if  org-ref-bibliography-notes
2215         (find-file-other-window org-ref-bibliography-notes)
2216       (error "Org-ref-bib-bibliography-notes is not set to anything"))
2217
2218     (goto-char (point-min))
2219
2220     (re-search-forward (format
2221                         ":Custom_ID: %s$"
2222                         (first (reftex-citation t)) nil 'end))
2223     (funcall org-ref-open-notes-function))
2224
2225 ;; ** Open bibtex entry in browser
2226 (defun org-ref-open-in-browser ()
2227   "Open the bibtex entry at point in a browser using the url field or doi field."
2228 (interactive)
2229 (save-excursion
2230   (bibtex-beginning-of-entry)
2231   (catch 'done
2232     (let ((url (bibtex-autokey-get-field "url")))
2233       (when  url
2234         (browse-url url)
2235         (throw 'done nil)))
2236
2237     (let ((doi (bibtex-autokey-get-field "doi")))
2238       (when doi
2239         (if (string-match "^http" doi)
2240             (browse-url doi)
2241           (browse-url (format "http://dx.doi.org/%s" doi)))
2242         (throw 'done nil)))
2243     (message "No url or doi found"))))
2244
2245 ;; ** upload entry to citeulike
2246
2247 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2248   "With point in  a bibtex entry get bibtex string and submit to citeulike.
2249
2250 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2251   (interactive)
2252   (message "uploading to citeulike")
2253   (save-restriction
2254     (bibtex-narrow-to-entry)
2255     (let ((startpos (point-min))
2256           (endpos (point-max))
2257           (bibtex-string (buffer-string))
2258           (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2259       (with-temp-buffer (insert bibtex-string)
2260                         (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2261
2262 ;; ** Build a pdf of the bibtex file
2263 (defun org-ref-build-full-bibliography ()
2264   "Build pdf of all bibtex entries, and open it."
2265   (interactive)
2266   (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2267         (bib-base (file-name-sans-extension bibfile))
2268         (texfile (concat bib-base ".tex"))
2269         (pdffile (concat bib-base ".pdf")))
2270     (find-file texfile)
2271     (erase-buffer)
2272     (insert (format "\\documentclass[12pt]{article}
2273 \\usepackage[version=3]{mhchem}
2274 \\usepackage{url}
2275 \\usepackage[numbers]{natbib}
2276 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2277 \\usepackage{doi}
2278 \\begin{document}
2279 \\nocite{*}
2280 \\bibliographystyle{unsrtnat}
2281 \\bibliography{%s}
2282 \\end{document}" bib-base))
2283     (save-buffer)
2284     (shell-command (concat "pdflatex " bib-base))
2285     (shell-command (concat "bibtex " bib-base))
2286     (shell-command (concat "pdflatex " bib-base))
2287     (shell-command (concat "pdflatex " bib-base))
2288     (kill-buffer texfile)
2289     (org-open-file pdffile)
2290     ))
2291
2292 ;; ** Extract bibtex entries in org-file
2293
2294 (defun org-ref-extract-bibtex-entries ()
2295   "Extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2296
2297 If no bibliography is in the buffer the variable
2298 `reftex-default-bibliography' is used."
2299   (interactive)
2300   (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2301          (tempname (make-temp-file "extract-bib"))
2302          (contents (buffer-string))
2303          (cb (current-buffer))
2304          basename texfile bibfile results)
2305
2306     ;; open tempfile and insert org-buffer contents
2307     (find-file tempname)
2308     (insert contents)
2309     (setq basename (file-name-sans-extension
2310                     (file-name-nondirectory buffer-file-name))
2311           texfile (concat tempname ".tex")
2312           bibfile (concat tempname ".bib"))
2313
2314     ;; see if we have a bibliography, and insert the default one if not.
2315     (save-excursion
2316       (goto-char (point-min))
2317       (unless (re-search-forward "^bibliography:" (point-max) 'end)
2318         (insert (format "\nbibliography:%s"
2319                         (mapconcat 'identity reftex-default-bibliography ",")))))
2320     (save-buffer)
2321
2322     ;; get a latex file and extract the references
2323     (org-latex-export-to-latex)
2324     (find-file texfile)
2325     (reftex-parse-all)
2326     (reftex-create-bibtex-file bibfile)
2327     (save-buffer)
2328     ;; save results of the references
2329     (setq results (buffer-string))
2330
2331     ;; kill buffers. these are named by basename, not full path
2332     (kill-buffer (concat basename ".bib"))
2333     (kill-buffer (concat basename ".tex"))
2334     (kill-buffer basename)
2335
2336     (delete-file bibfile)
2337     (delete-file texfile)
2338     (delete-file tempname)
2339
2340     ;; Now back to the original org buffer and insert the results
2341     (switch-to-buffer cb)
2342     (when (not (string= "" results))
2343       (save-excursion
2344         (goto-char (point-max))
2345         (insert "\n\n")
2346         (org-insert-heading)
2347         (insert (format " Bibtex entries
2348
2349 #+BEGIN_SRC text :tangle %s
2350 %s
2351 #+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2352
2353 ;; ** Find bad citations
2354 (require 'cl)
2355
2356 (defun index (substring list)
2357   "Return the index of SUBSTRING in a LIST of strings."
2358   (let ((i 0)
2359         (found nil))
2360     (dolist (arg list i)
2361       (if (string-match (concat "^" substring "$") arg)
2362           (progn
2363             (setq found t)
2364             (return i)))
2365       (setq i (+ i 1)))
2366     ;; return counter if found, otherwise return nil
2367     (if found i nil)))
2368
2369
2370 (defun org-ref-find-bad-citations ()
2371   "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2372
2373 Makes a new buffer with clickable links."
2374   (interactive)
2375   ;; generate the list of bibtex-keys and cited keys
2376   (let* ((bibtex-files (org-ref-find-bibliography))
2377          (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2378          (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2379          (bad-citations '()))
2380
2381     (org-element-map (org-element-parse-buffer) 'link
2382       (lambda (link)
2383         (let ((plist (nth 1 link)))
2384           (when (-contains? org-ref-cite-types (plist-get plist :type))
2385             (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)))
2386               (when (not (index key bibtex-keys))
2387                 (setq
2388                  bad-citations
2389                  (append
2390                   bad-citations
2391                   `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2392                              key
2393                              (buffer-name)
2394                              (plist-get plist :begin)))))
2395                 )))))
2396       ;; set with-affilates to t to get citations in a caption
2397       nil nil nil t)
2398
2399     (if bad-citations
2400       (progn
2401         (switch-to-buffer-other-window "*Missing citations*")
2402         (org-mode)
2403         (erase-buffer)
2404         (insert "* List of bad cite links\n")
2405         (insert (mapconcat 'identity bad-citations ""))
2406                                         ;(setq buffer-read-only t)
2407         (use-local-map (copy-keymap org-mode-map))
2408         (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2409
2410       (when (get-buffer "*Missing citations*")
2411           (kill-buffer "*Missing citations*"))
2412       (message "No bad cite links found"))))
2413
2414 ;; ** helm interface to bad citations, labels, refs and files in orgfile
2415 (defun org-ref-bad-cite-candidates ()
2416   "Return a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2417   (let* ((cp (point))                   ; save to return to later
2418          (bibtex-files (org-ref-find-bibliography))
2419          (bibtex-file-path (mapconcat
2420                             (lambda (x)
2421                               (file-name-directory (file-truename x)))
2422                             bibtex-files ":"))
2423          (bibtex-keys (mapcar (lambda (x) (car x))
2424                               (bibtex-global-key-alist)))
2425          (bad-citations '()))
2426
2427     (org-element-map (org-element-parse-buffer) 'link
2428       (lambda (link)
2429         (let ((plist (nth 1 link)))
2430           (when (-contains? org-ref-cite-types (plist-get plist :type))
2431             (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)) )
2432               (when (not (index key bibtex-keys))
2433                 (goto-char (plist-get plist :begin))
2434                 (re-search-forward key)
2435                 (push (cons key (point-marker)) bad-citations)))
2436             )))
2437       ;; add with-affiliates to get cites in caption
2438       nil nil nil t)
2439     (goto-char cp)
2440     bad-citations))
2441
2442
2443 (defun org-ref-bad-ref-candidates ()
2444   "Return a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2445   ;; first get a list of legitimate labels
2446   (let ((cp (point))
2447         (labels (org-ref-get-labels))
2448         (bad-refs '()))
2449     ;; now loop over ref links
2450     (goto-char (point-min))
2451     (org-element-map (org-element-parse-buffer) 'link
2452       (lambda (link)
2453         (let ((plist (nth 1 link)))
2454           (when (or  (equal (plist-get plist ':type) "ref")
2455                      (equal (plist-get plist ':type) "eqref")
2456                      (equal (plist-get plist ':type) "pageref")
2457                      (equal (plist-get plist ':type) "nameref"))
2458             (unless (-contains? labels (plist-get plist :path))
2459               (goto-char (plist-get plist :begin))
2460               (add-to-list
2461                'bad-refs
2462                (cons (plist-get plist :path)
2463                      (point-marker))))))))
2464     (goto-char cp)
2465     bad-refs))
2466
2467
2468 (defun org-ref-bad-label-candidates ()
2469   "Return a list of labels where label is multiply defined."
2470   (let ((labels (org-ref-get-labels))
2471         (multiple-labels '()))
2472     (when (not (= (length labels)
2473                   (length (-uniq labels))))
2474       (dolist (label labels)
2475         (when (> (-count (lambda (a)
2476                            (equal a label))
2477                          labels) 1)
2478           ;; this is a multiply defined label.
2479           (let ((cp (point)))
2480             (goto-char (point-min))
2481             (while (re-search-forward
2482                     (format  "[^#+]label:%s\\s-" label) nil t)
2483               (push (cons label (point-marker)) multiple-labels))
2484             (goto-char (point-min))
2485             (while (re-search-forward
2486                     (format  "\\label{%s}\\s-?" label) nil t)
2487               (push (cons label (point-marker)) multiple-labels))
2488
2489             (goto-char (point-min))
2490             (while (re-search-forward
2491                     (format  "^#\\+label:\\s-*%s" label) nil t)
2492               (push (cons label (point-marker)) multiple-labels))
2493
2494             (goto-char (point-min))
2495             (while (re-search-forward
2496                     (format   "^#\\+tblname:\\s-*%s" label) nil t)
2497               (push (cons label (point-marker)) multiple-labels))
2498             (goto-char cp)))))
2499       multiple-labels))
2500
2501 (defun org-ref-bad-file-link-candidates ()
2502   "Return list of conses (link . marker) wehre the file in the link does not exist."
2503   (let* ((bad-files '()))
2504     (org-element-map (org-element-parse-buffer) 'link
2505       (lambda (link)
2506         (let ((type (org-element-property :type link)))
2507           (when (or  (string= "file" type)
2508                      (string= "attachfile" type))
2509             (unless (file-exists-p (org-element-property :path link))
2510               (add-to-list 'bad-files
2511                            (cons (org-element-property :path link)
2512                                  (save-excursion
2513                                    (goto-char
2514                                     (org-element-property :begin link))
2515                                    (point-marker)))))))))
2516     ;; Let us also check \attachfile{fname}
2517     (save-excursion
2518       (goto-char (point-min))
2519       (while (re-search-forward "\\attachfile{\\(.*\\)}" nil t)
2520         (unless (file-exists-p (match-string 1))
2521           (add-to-list 'bad-files (cons (match-string 1) (point-marker))))))
2522     bad-files))
2523
2524 ;;;###autoload
2525 (defun org-ref ()
2526   "Opens a helm interface to actions for org-ref.
2527 Shows bad citations, ref links and labels"
2528   (interactive)
2529   (let ((cb (current-buffer))
2530         (bad-citations (org-ref-bad-cite-candidates))
2531         (bad-refs (org-ref-bad-ref-candidates))
2532         (bad-labels (org-ref-bad-label-candidates))
2533         (bad-files (org-ref-bad-file-link-candidates)))
2534
2535     (helm :sources `(((name . "Bad citations")
2536                        (candidates . ,bad-citations)
2537                        (action . (lambda (marker)
2538                                    (switch-to-buffer (marker-buffer marker))
2539                                    (goto-char marker))))
2540                      ;;
2541                      ((name . "Bad Labels")
2542                       (candidates . ,bad-labels)
2543                       (action . (lambda (marker)
2544                                    (switch-to-buffer (marker-buffer marker))
2545                                    (goto-char marker))))
2546                      ;;
2547                      ((name . "Bad ref links")
2548                       (candidates . ,bad-refs)
2549                       (action . (lambda (marker)
2550                                           (switch-to-buffer (marker-buffer marker))
2551                                           (goto-char marker))))
2552                      ;;
2553                      ((name . "Bad file links")
2554                       (candidates . ,bad-files)
2555                       (lambda (marker)
2556                                    (switch-to-buffer (marker-buffer marker))
2557                                    (goto-char marker)))
2558                      ;;
2559                      ((name . "Utilities")
2560                       (candidates . (("Check buffer again" . org-ref)
2561                                      ("Insert citation" . helm-bibtex)
2562                                      ("Insert label link" . org-ref-helm-insert-label-link)
2563                                      ("Insert ref link" . org-ref-helm-insert-ref-link)
2564                                      ("List of figures" . org-ref-list-of-figures)
2565                                      ("List of tables" . org-ref-list-of-tables)
2566                                      ("Table of contents" . nil)
2567                                      ))
2568                       (action . (lambda (x)
2569                                   (switch-to-buffer ,cb)
2570                                   (funcall x))))
2571                      ;;
2572                      ((name . "Export functions")
2573                       (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2574                                      ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2575                                      ("Export to pdf and open" . (lambda ()
2576                                                                    (org-open-file (org-latex-export-to-pdf))))
2577                                      ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2578                                      ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2579
2580                                      ))
2581                       (action . (lambda (x)
2582                                   (switch-to-buffer ,cb)
2583                                   (funcall x))))))))
2584
2585 ;; ** Find non-ascii charaters
2586 (defun org-ref-find-non-ascii-characters ()
2587   "Find non-ascii characters in the buffer.  Useful for cleaning up bibtex files."
2588   (interactive)
2589   (occur "[^[:ascii:]]"))
2590
2591 ;; ** Sort fields in a bibtex entry
2592
2593 (defun org-ref-sort-bibtex-entry ()
2594   "Sort fields of entry in standard order and downcase them."
2595   (interactive)
2596   (bibtex-beginning-of-entry)
2597   (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2598          (entry (bibtex-parse-entry))
2599          (entry-fields)
2600          (other-fields)
2601          (type (cdr (assoc "=type=" entry)))
2602          (key (cdr (assoc "=key=" entry))))
2603
2604     ;; these are the fields we want to order that are in this entry
2605     (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2606     ;; we do not want to reenter these fields
2607     (setq entry-fields (remove "=key=" entry-fields))
2608     (setq entry-fields (remove "=type=" entry-fields))
2609
2610     ;;these are the other fields in the entry
2611     (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2612
2613     (cond
2614      ;; right now we only resort articles
2615      ((string= (downcase type) "article")
2616       (bibtex-kill-entry)
2617       (insert
2618        (concat "@article{" key ",\n"
2619                (mapconcat
2620                 (lambda (field)
2621                   (when (member field entry-fields)
2622                     (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2623                (mapconcat
2624                 (lambda (field)
2625                   (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2626                "\n}\n\n"))
2627       (bibtex-find-entry key)
2628       (bibtex-fill-entry)
2629       (bibtex-clean-entry)
2630        ))))
2631
2632 ;; ** Clean a bibtex entry
2633 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2634   "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"
2635   (interactive "P")
2636   (bibtex-beginning-of-entry)
2637 (end-of-line)
2638   ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2639   (unless (string-match ",$" (thing-at-point 'line))
2640     (end-of-line)
2641     (insert ","))
2642
2643   ;; check for empty pages, and put eid or article id in its place
2644   (let ((entry (bibtex-parse-entry))
2645         (pages (bibtex-autokey-get-field "pages"))
2646         (year (bibtex-autokey-get-field "year"))
2647         (doi  (bibtex-autokey-get-field "doi"))
2648         ;; The Journal of Chemical Physics uses eid
2649         (eid (bibtex-autokey-get-field "eid")))
2650
2651     ;; replace http://dx.doi.org/ in doi. some journals put that in,
2652     ;; but we only want the doi.
2653     (when (string-match "^http://dx.doi.org/" doi)
2654       (bibtex-beginning-of-entry)
2655       (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2656       (bibtex-kill-field)
2657       (bibtex-make-field "doi")
2658       (backward-char)
2659       (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2660
2661     ;; asap articles often set year to 0, which messes up key
2662     ;; generation. fix that.
2663     (when (string= "0" year)
2664       (bibtex-beginning-of-entry)
2665       (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2666       (bibtex-kill-field)
2667       (bibtex-make-field "year")
2668       (backward-char)
2669       (insert (read-string "Enter year: ")))
2670
2671     ;; fix pages if they are empty if there is an eid to put there.
2672     (when (string= "-" pages)
2673       (when eid
2674         (bibtex-beginning-of-entry)
2675         ;; this seems like a clunky way to set the pages field.But I
2676         ;; cannot find a better way.
2677         (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2678         (bibtex-kill-field)
2679         (bibtex-make-field "pages")
2680         (backward-char)
2681         (insert eid)))
2682
2683     ;; replace naked & with \&
2684     (save-restriction
2685       (bibtex-narrow-to-entry)
2686       (bibtex-beginning-of-entry)
2687       (message "checking &")
2688       (replace-regexp " & " " \\\\& ")
2689       (widen))
2690
2691     ;; generate a key, and if it duplicates an existing key, edit it.
2692     (unless keep-key
2693       (let ((key (bibtex-generate-autokey)))
2694
2695         ;; first we delete the existing key
2696         (bibtex-beginning-of-entry)
2697         (re-search-forward bibtex-entry-maybe-empty-head)
2698         (if (match-beginning bibtex-key-in-head)
2699             (delete-region (match-beginning bibtex-key-in-head)
2700                            (match-end bibtex-key-in-head)))
2701         ;; check if the key is in the buffer
2702         (when (save-excursion
2703                 (bibtex-search-entry key))
2704           (save-excursion
2705             (bibtex-search-entry key)
2706             (bibtex-copy-entry-as-kill)
2707             (switch-to-buffer-other-window "*duplicate entry*")
2708             (bibtex-yank))
2709           (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2710
2711         (insert key)
2712         (kill-new key))) ;; save key for pasting
2713
2714     ;; run hooks. each of these operates on the entry with no arguments.
2715     ;; this did not work like  i thought, it gives a symbolp error.
2716     ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2717     (mapcar (lambda (x)
2718               (save-restriction
2719                 (save-excursion
2720                   (funcall x))))
2721             org-ref-clean-bibtex-entry-hook)
2722
2723     ;; sort fields within entry
2724     (org-ref-sort-bibtex-entry)
2725     ;; check for non-ascii characters
2726     (occur "[^[:ascii:]]")
2727     ))
2728
2729 (defun org-ref-get-citation-year (key)
2730   "Get the year of an entry with KEY.  Return year as a string."
2731   (let* ((results (org-ref-get-bibtex-key-and-file key))
2732          (bibfile (cdr results)))
2733     (with-temp-buffer
2734       (insert-file-contents bibfile)
2735       (bibtex-search-entry key nil 0)
2736       (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2737         ))))
2738
2739 ;; ** Sort cite in cite link
2740 (defun org-ref-sort-citation-link ()
2741  "Replace link at point with sorted link by year."
2742  (interactive)
2743  (let* ((object (org-element-context))
2744         (type (org-element-property :type object))
2745         (begin (org-element-property :begin object))
2746         (end (org-element-property :end object))
2747         (link-string (org-element-property :path object))
2748         keys years data)
2749   (setq keys (org-ref-split-and-strip-string link-string))
2750   (setq years (mapcar 'org-ref-get-citation-year keys))
2751   (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2752   (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2753   ;; now get the keys separated by commas
2754   (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2755   ;; and replace the link with the sorted keys
2756   (cl--set-buffer-substring begin end (concat type ":" keys))))
2757
2758 ;; ** Shift-arrow sorting of keys in a cite link
2759
2760 (defun org-ref-swap-keys (i j keys)
2761  "Swap the KEYS in a list with index I and J."
2762  (let ((tempi (nth i keys)))
2763    (setf (nth i keys) (nth j keys))
2764    (setf (nth j keys) tempi))
2765   keys)
2766
2767
2768 (defun org-ref-swap-citation-link (direction)
2769  "Move citation at point in DIRECTION +1 is to the right, -1 to the left."
2770  (interactive)
2771  (let* ((object (org-element-context))
2772         (type (org-element-property :type object))
2773         (begin (org-element-property :begin object))
2774         (end (org-element-property :end object))
2775         (link-string (org-element-property :path object))
2776         key keys i)
2777    ;;   We only want this to work on citation links
2778    (when (-contains? org-ref-cite-types type)
2779         (setq key (org-ref-get-bibtex-key-under-cursor))
2780         (setq keys (org-ref-split-and-strip-string link-string))
2781         (setq i (index key keys))  ;; defined in org-ref
2782         (if (> direction 0) ;; shift right
2783             (org-ref-swap-keys i (+ i 1) keys)
2784           (org-ref-swap-keys i (- i 1) keys))
2785         (setq keys (mapconcat 'identity keys ","))
2786         ;; and replace the link with the sorted keys
2787         (cl--set-buffer-substring
2788          begin end
2789          (concat
2790           type ":" keys
2791           ;; It seems the space at the end can get consumed, so we see if there
2792           ;; is a space, and add it if so. Sometimes there is a comma or period,
2793           ;; then we do not want a space.
2794           (when
2795               (save-excursion
2796                 (goto-char end)
2797                 (looking-back " ")) " ")))
2798         ;; now go forward to key so we can move with the key
2799         (re-search-forward key)
2800         (goto-char (match-beginning 0)))))
2801
2802 ;; add hooks to make it work
2803 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2804 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2805
2806 ;; ** context around org-ref links
2807 (defun org-ref-get-label-context (label)
2808   "Return a string of context around a LABEL."
2809   (save-excursion
2810     (catch 'result
2811       (goto-char (point-min))
2812       (when (re-search-forward
2813              (format "label:%s\\b" label) nil t)
2814         (throw 'result (buffer-substring
2815                         (progn
2816                           (previous-line)
2817                           (beginning-of-line)
2818                           (point))
2819                         (progn
2820                           (forward-line 4)
2821                           (point)))))
2822
2823       (goto-char (point-min))
2824       (when (re-search-forward
2825              (format "\\label{%s}" label) nil t)
2826         (throw 'result (buffer-substring
2827                         (progn
2828                           (previous-line)
2829                           (beginning-of-line)
2830                           (point))
2831                         (progn
2832                           (forward-line 4)
2833                           (point)))))
2834
2835       (goto-char (point-min))
2836       (when (re-search-forward
2837              (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2838         (throw 'result (buffer-substring
2839                         (progn
2840                           (previous-line)
2841                           (beginning-of-line)
2842                           (point))
2843                         (progn
2844                           (forward-line 4)
2845                           (point)))))
2846
2847       (goto-char (point-min))
2848       (when (re-search-forward
2849              (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2850         (throw 'result (buffer-substring
2851                         (progn
2852                           (previous-line)
2853                           (beginning-of-line)
2854                           (point))
2855                         (progn
2856                           (forward-line 4)
2857                           (point)))))
2858       (throw 'result "!!! NO CONTEXT FOUND !!!"))))
2859
2860
2861 (defun org-ref-link-message ()
2862   "Print a minibuffer message about the link that point is on."
2863   (interactive)
2864   (save-restriction
2865     (widen)
2866     (when (eq major-mode 'org-mode)
2867       (let* ((object (org-element-context))
2868              (type (org-element-property :type object)))
2869         (save-excursion
2870           (cond
2871            ;; cite links
2872            ((-contains? org-ref-cite-types type)
2873             (message (org-ref-get-citation-string-at-point)))
2874
2875            ;; message some context about the label we are referring to
2876            ((string= type "ref")
2877             (message "%scount: %s"
2878                      (org-ref-get-label-context
2879                       (org-element-property :path object))
2880                      (org-ref-count-labels
2881                       (org-element-property :path object))))
2882
2883            ((string= type "eqref")
2884             (message "%scount: %s"
2885                      (org-ref-get-label-context
2886                       (org-element-property :path object))
2887                      (org-ref-count-labels
2888                       (org-element-property :path object))))
2889
2890            ;; message the count
2891            ((string= type "label")
2892             (let ((count (org-ref-count-labels
2893                           (org-element-property :path object))))
2894               ;; get plurality on occurrence correct
2895               (message (concat
2896                         (number-to-string count)
2897                         " occurence"
2898                         (when (or (= count 0)
2899                                   (> count 1))
2900                           "s")))))
2901
2902            ((string= type "custom-id")
2903             (save-excursion
2904               (org-open-link-from-string
2905                (format "[[#%s]]" (org-element-property :path object)))
2906               (message "%s" (org-get-heading))))
2907
2908            ;; check if the bibliography files exist.
2909            ((string= type "bibliography")
2910             (let* ((bibfile)
2911                    ;; object is the link you clicked on
2912                    (object (org-element-context))
2913                    (link-string (org-element-property :path object))
2914                    (link-string-beginning)
2915                    (link-string-end))
2916               (save-excursion
2917                 (goto-char (org-element-property :begin object))
2918                 (search-forward link-string nil nil 1)
2919                 (setq link-string-beginning (match-beginning 0))
2920                 (setq link-string-end (match-end 0)))
2921
2922               ;; make sure we are in link and not before the :
2923               (when (> link-string-beginning (point))
2924                 (goto-char link-string-beginning))
2925
2926               ;; now if we have comma separated bibliographies
2927               ;; we find the one clicked on. we want to
2928               ;; search forward to next comma from point
2929               (save-excursion
2930                 (if (search-forward "," link-string-end 1 1)
2931                     (setq key-end (- (match-end 0) 1)) ; we found a match
2932                   (setq key-end (point)))) ; no comma found so take the point
2933
2934               ;; and backward to previous comma from point
2935               (save-excursion
2936                 (if (search-backward "," link-string-beginning 1 1)
2937                     (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
2938                   (setq key-beginning (point)))) ; no match found
2939               ;; save the key we clicked on.
2940               (setq bibfile
2941                     (org-ref-strip-string
2942                      (buffer-substring key-beginning key-end)))
2943               (if (file-exists-p bibfile)
2944                   (message "%s exists." bibfile)
2945                 (message "!!! %s NOT FOUND !!!" bibfile))))))))))
2946
2947 ;; ** aliases
2948 (defalias 'oro 'org-ref-open-citation-at-point)
2949 (defalias 'orc 'org-ref-citation-at-point)
2950 (defalias 'orp 'org-ref-open-pdf-at-point)
2951 (defalias 'oru 'org-ref-open-url-at-point)
2952 (defalias 'orn 'org-ref-open-notes-at-point)
2953 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2954
2955 (defalias 'orib 'org-ref-insert-bibliography-link)
2956 (defalias 'oric 'org-ref-insert-cite-link)
2957 (defalias 'orir 'org-ref-insert-ref-link)
2958 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2959
2960 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2961
2962 ;; * Helm bibtex setup
2963
2964 (setq helm-bibtex-additional-search-fields '(keywords))
2965
2966 (defun helm-bibtex-candidates-formatter (candidates source)
2967   "Formats BibTeX entries for display in results list.
2968 Argument CANDIDATES helm candidates.
2969 Argument SOURCE the helm source."
2970   (cl-loop
2971    with width = (with-helm-window (helm-bibtex-window-width))
2972    for entry in candidates
2973    for entry = (cdr entry)
2974    for entry-key = (helm-bibtex-get-value "=key=" entry)
2975    if (assoc-string "author" entry 'case-fold)
2976      for fields = '("author" "title" "year" "=has-pdf=" "=has-note=" "=type=")
2977    else
2978      for fields = '("editor" "title" "year" "=has-pdf=" "=has-note=" "=type=")
2979    for fields = (--map (helm-bibtex-clean-string
2980                         (helm-bibtex-get-value it entry " "))
2981                        fields)
2982    for fields = (-update-at 0 'helm-bibtex-shorten-authors fields)
2983    for fields = (append fields
2984                          (list  (or (helm-bibtex-get-value "keywords" entry)
2985                                     "" )))
2986    collect
2987    (cons (s-format "$0 $1 $2 $3 $4$5 $6" 'elt
2988                    (-zip-with (lambda (f w) (truncate-string-to-width f w 0 ?\s))
2989                               fields (list 36 (- width 85) 4 1 1 7 7)))
2990          entry-key)))
2991
2992 ;; * org-ref bibtex keywords
2993 ;; adapted from bibtex-utils.el
2994 ;; these are candidates for selecting keywords/tags
2995 (defun org-ref-bibtex-keywords ()
2996   "Get keywords defined in current bibtex file.
2997 These are in the keywords field, and are comma or semicolon separated."
2998   (save-excursion
2999     (goto-char (point-min))
3000     (let (keywords kstring)
3001       (while (re-search-forward "^\\s-*keywords.*{\\([^}]+\\)}" nil t)
3002         ;; TWS - remove newlines/multiple spaces:
3003         (setq kstring (replace-regexp-in-string "[ \t\n]+" " " (match-string 1)))
3004         (mapc
3005          (lambda (v)
3006            (add-to-list 'keywords v t))
3007          (split-string kstring "\\(,\\|;\\)[ \n]*\\|{\\|}" t)))
3008       keywords)))
3009
3010
3011 (defun org-ref-set-bibtex-keywords (keywords &optional arg)
3012   "Add KEYWORDS to a bibtex entry.
3013 If KEYWORDS is a list, it is converted to a comma-separated
3014 string.  The KEYWORDS are added to the beginning of the
3015 field.  Otherwise KEYWORDS should be a string of comma-separate
3016 keywords.  Optional argument ARG prefix arg to replace keywords."
3017   (interactive "sKeywords: \nP")
3018   (bibtex-set-field
3019    "keywords"
3020    (if arg
3021        ;; replace with arg
3022        (if (listp keywords)
3023            (mapconcat 'identity keywords ", ")
3024          keywords)
3025      ;; else concatentate
3026      (concat
3027       (if (listp keywords)
3028           (mapconcat 'identity keywords ", ")
3029         keywords)
3030       (when (not (string= "" (bibtex-autokey-get-field "keywords")))
3031         (concat ", "  (bibtex-autokey-get-field "keywords"))))))
3032   (save-buffer))
3033
3034
3035 (defun helm-tag-bibtex-entry ()
3036   "Helm interface to add keywords to a bibtex entry.
3037 Run this with the point in a bibtex entry."
3038   (interactive)
3039   (let ((keyword-source `((name . "Existing keywords")
3040                           (candidates . ,(org-ref-bibtex-keywords))
3041                           (action . (lambda (candidate)
3042                                       (org-ref-set-bibtex-keywords
3043                                        (mapconcat
3044                                         'identity
3045                                         (helm-marked-candidates)
3046                                         ", "))))))
3047         (fallback-source `((name . "Add new keywords")
3048                            (dummy)
3049                            (action . (lambda (candidate)
3050                                        (org-ref-set-bibtex-keywords helm-pattern)
3051                                        )))))
3052     (helm :sources '(keyword-source fallback-source))))
3053
3054 (defun helm-bibtex-show-entry (key)
3055   "Show the entry for KEY in the BibTeX file.
3056 The original function in `helm-bibtex' has a bug where it finds the
3057 first key that partially matches.  This version avoids that."
3058   (catch 'break
3059     (dolist (bibtex-file (if (listp helm-bibtex-bibliography)
3060                              helm-bibtex-bibliography
3061                            (list helm-bibtex-bibliography)))
3062       (let ((buf (helm-bibtex-buffer-visiting bibtex-file))
3063             (entries '()))
3064         (find-file bibtex-file)
3065         (bibtex-map-entries
3066          (lambda (key start end)
3067            (add-to-list 'entries (cons key start))))
3068         (if (assoc key entries)
3069             (progn
3070               (goto-char (cdr (assoc key entries)))
3071               (throw 'break t))
3072           (unless buf
3073             (kill-buffer)))))))
3074
3075 (defun org-ref-helm-tag-entries (candidates)
3076   "Set tags on selected bibtex entries from `helm-bibtex'.
3077 User is prompted for tags.  This function is called from `helm-bibtex'.
3078 Argument CANDIDATES helm candidates."
3079   (message "")
3080   (let ((keywords (read-string "Keywords (comma separated): ")))
3081     (loop for key in (helm-marked-candidates)
3082           do
3083           (save-window-excursion
3084             (helm-bibtex-show-entry key)
3085             (bibtex-set-field
3086              "keywords"
3087              (concat
3088               keywords
3089               ", " (bibtex-autokey-get-field "keywords")))
3090             (save-buffer)))))
3091
3092 (setq helm-source-bibtex
3093       '((name                                      . "BibTeX entries")
3094         (init                                      . helm-bibtex-init)
3095         (candidates                                . helm-bibtex-candidates)
3096         (filtered-candidate-transformer            . helm-bibtex-candidates-formatter)
3097         (action . (("Insert citation"              . helm-bibtex-insert-citation)
3098                    ("Show entry"                   . helm-bibtex-show-entry)
3099                    ("Open PDF file (if present)"   . helm-bibtex-open-pdf)
3100                    ("Open URL or DOI in browser"   . helm-bibtex-open-url-or-doi)
3101                    ("Insert formatted reference"   . helm-bibtex-insert-reference)
3102                    ("Insert BibTeX key"            . helm-bibtex-insert-key)
3103                    ("Insert BibTeX entry"          . helm-bibtex-insert-bibtex)
3104                    ("Attach PDF to email"          . helm-bibtex-add-PDF-attachment)
3105                    ("Edit notes"                   . helm-bibtex-edit-notes)
3106                    ("Add keywords to entries"      . org-ref-helm-tag-entries)
3107                    ))))
3108
3109 (defun helm-bibtex-format-org-ref (keys)
3110   "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3111 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.
3112
3113 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3114
3115 C-u C-u will change the key at point to the selected keys."
3116   (let* ((object (org-element-context))
3117          (last-char (save-excursion
3118                       (when (org-element-property :end object)
3119                         (goto-char (org-element-property :end object))
3120                         (unless (bobp)
3121                           (backward-char))
3122                         (if (looking-at " ")
3123                             " "
3124                           "")))))
3125     (cond
3126      ;; case where we are in a link
3127      ((and (equal (org-element-type object) 'link)
3128            (-contains?
3129             org-ref-cite-types
3130             (org-element-property :type object)))
3131       (cond
3132        ;; no prefix. append keys
3133        ((equal helm-current-prefix-arg nil)
3134         (goto-char (org-element-property :end object))
3135         (while (looking-back " ") (backward-char))
3136         (insert (concat "," (mapconcat 'identity keys ","))))
3137        ;; double prefix, replace key at point
3138        ((equal helm-current-prefix-arg '(16))
3139         (setf (buffer-substring
3140                (org-element-property :begin object)
3141                (org-element-property :end object))
3142               (concat
3143                (replace-regexp-in-string
3144                 (car (org-ref-get-bibtex-key-and-file)) ; key
3145                 (mapconcat 'identity keys ",")          ; new keys
3146                 (org-element-property :raw-link object))
3147                ;; replace space at end to avoid collapsing into next word.
3148                last-char))
3149         ;; and we want to go to the end of the new link
3150         (goto-char
3151          (org-element-property :end (org-element-context))))
3152        (t
3153         (message "Not found"))))
3154
3155      ;; We are next to a link, and we want to append
3156      ;; next to a link means one character back is on a link.
3157      ((save-excursion
3158         (unless (bobp) (backward-char))
3159         (and (equal (org-element-type (org-element-context)) 'link)
3160              (-contains?
3161               org-ref-cite-types
3162               (org-element-property :type (org-element-context)))))
3163       (while (looking-back " ") (backward-char))
3164       (insert (concat "," (mapconcat 'identity keys ","))))
3165
3166      ;; insert fresh link
3167      (t
3168       ;;(message-box "fresh link")
3169       (insert
3170        (concat (if (equal helm-current-prefix-arg '(4))
3171                    (helm :sources `((name . "link types")
3172                                     (candidates . ,org-ref-cite-types)
3173                                     (action . (lambda (x) x))))
3174                org-ref-default-citation-link)
3175                ":"
3176                (s-join "," keys))))))
3177   ;; return empty string for helm
3178   "")
3179
3180 (setq helm-bibtex-format-citation-functions
3181       '((org-mode . helm-bibtex-format-org-ref)))
3182
3183 ;;;###autoload
3184 (defun org-ref-helm-insert-cite-link (arg)
3185   "org-ref function to use helm-bibtex to insert a citation link.
3186 With one prefix arg, insert a ref link.
3187 With two prefix args, insert a label link."
3188   (interactive "P")
3189   (cond
3190    ((equal arg nil)
3191      (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3192        (helm-bibtex)))
3193    ((equal arg '(4))
3194     (org-ref-helm-insert-ref-link))
3195    ((equal arg '(16))
3196     (org-ref-helm-insert-label-link))))
3197
3198
3199 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3200 (setq helm-bibtex-fallback-options
3201       (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3202
3203 (setq helm-bibtex-fallback-options
3204       (-insert-at
3205        1
3206        '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3207        helm-bibtex-fallback-options))
3208
3209 (setq helm-bibtex-fallback-options
3210       (-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))
3211
3212 (defun org-ref-get-citation-string-at-point ()
3213   "Get a string of a formatted citation."
3214   (let* ((results (org-ref-get-bibtex-key-and-file))
3215          (key (car results))
3216          (bibfile (cdr results)))
3217     (if bibfile
3218         (save-excursion
3219           (with-temp-buffer
3220             (insert-file-contents bibfile)
3221             (bibtex-search-entry key)
3222             (org-ref-bib-citation)))
3223       "!!! No entry found !!!" )))
3224
3225
3226 (defun org-ref-cite-candidates ()
3227   "Generate the list of possible candidates for click actions on a cite link.
3228 Checks for pdf and doi, and add appropriate functions."
3229   (let* ((results (org-ref-get-bibtex-key-and-file))
3230          (key (car results))
3231          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3232          (bibfile (cdr results))
3233          (url (save-excursion
3234                 (with-temp-buffer
3235                   (insert-file-contents bibfile)
3236                   (bibtex-search-entry key)
3237                   (bibtex-autokey-get-field "url"))))
3238          (doi (save-excursion
3239                 (with-temp-buffer
3240                   (insert-file-contents bibfile)
3241                   (bibtex-search-entry key)
3242                   ;; I like this better than bibtex-url which does not always find
3243                   ;; the urls
3244                   (bibtex-autokey-get-field "doi"))))
3245          (candidates `(("Quit" . org-ref-citation-at-point)
3246                        ("Open bibtex entry" . org-ref-open-citation-at-point))))
3247     ;; for some reason, when there is no doi or url, they are returned as "". I
3248     ;; prefer nil so we correct this here.
3249     (when (string= doi "") (setq doi nil))
3250     (when (string= url "") (setq url nil))
3251
3252     ;; Conditional pdf functions
3253     (if (file-exists-p pdf-file)
3254         (add-to-list
3255          'candidates
3256          '("Open pdf" . org-ref-open-pdf-at-point)
3257          t)
3258       (add-to-list
3259        'candidates
3260        '("Try to get pdf" . (lambda ()
3261                               (save-window-excursion
3262                                 (org-ref-open-citation-at-point)
3263                                 (bibtex-beginning-of-entry)
3264                                 (doi-utils-get-bibtex-entry-pdf))))
3265        t))
3266
3267
3268     (add-to-list
3269      'candidates
3270      '("Open notes" . org-ref-open-notes-at-point)
3271      t)
3272
3273     ;; conditional url and doi functions
3274     (when (or url doi)
3275       (add-to-list
3276        'candidates
3277        '("Open in browser" . org-ref-open-url-at-point)
3278        t))
3279
3280     (when doi
3281       (mapc (lambda (x)
3282               (add-to-list 'candidates x t))
3283             `(("WOS" . org-ref-wos-at-point)
3284               ("Related articles in WOS" . org-ref-wos-related-at-point)
3285               ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3286               ("Google Scholar" . org-ref-google-scholar-at-point)
3287               ("Pubmed" . org-ref-pubmed-at-point)
3288               ("Crossref" . org-ref-crossref-at-point)
3289               )))
3290
3291     (add-to-list
3292      'candidates
3293      '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3294      t)
3295
3296     (add-to-list
3297      'candidates
3298      '("Copy key to clipboard" . (lambda ()
3299                                   (kill-new
3300                                    (car (org-ref-get-bibtex-key-and-file)))))
3301      t)
3302
3303     (add-to-list
3304      'candidates
3305      '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3306      t)
3307
3308     (add-to-list
3309      'candidates
3310      '("Email bibtex entry and pdf" . (lambda ()
3311                   (save-excursion
3312                     (org-ref-open-citation-at-point)
3313                     (email-bibtex-entry))))
3314      t)
3315   ;; finally return a numbered list of the candidates
3316   (loop for i from 0
3317         for cell in candidates
3318         collect (cons (format "%2s. %s" i (car cell))
3319                       (cdr cell)))))
3320
3321
3322 (defvar org-ref-helm-user-candidates '()
3323   "List of user-defined candidates to act when clicking on a cite link.
3324 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.")
3325
3326 ;; example of adding your own function
3327 (add-to-list
3328  'org-ref-helm-user-candidates
3329  '("Example" . (lambda () (message-box "You did it!")))
3330  t)
3331
3332 ;;;###autoload
3333 (defun org-ref-cite-click-helm (key)
3334   "Open helm for actions on a cite link.
3335 subtle points.
3336
3337 1. get name and candidates before entering helm because we need
3338 the org-buffer.
3339
3340 2. switch back to the org buffer before evaluating the
3341 action.  most of them need the point and buffer.
3342
3343 KEY is returned for the selected item(s) in helm."
3344   (interactive)
3345   (let ((name (org-ref-get-citation-string-at-point))
3346         (candidates (org-ref-cite-candidates))
3347         (cb (current-buffer)))
3348
3349     (helm :sources `(((name . ,name)
3350                       (candidates . ,candidates)
3351                       (action . (lambda (f)
3352                                   (switch-to-buffer cb)
3353                                   (funcall f))))
3354                      ((name . "User functions")
3355                       (candidates . ,org-ref-helm-user-candidates)
3356                       (action . (lambda (f)
3357                                   (switch-to-buffer cb)
3358                                   (funcall f))))
3359                      ))))
3360
3361 ;; * Hydra menus in org-ref
3362
3363 (when (featurep 'hydra)
3364   (require 'hydra)
3365   (setq hydra-is-helpful t)
3366
3367   (defhydra org-ref-cite-hydra (:color blue)
3368     "
3369 _p_: Open pdf     _w_: WOS          _g_: Google Scholar _K_: Copy citation to clipboard
3370 _u_: Open url     _r_: WOS related  _P_: Pubmed         _k_: Copy key to clipboard
3371 _n_: Open notes   _c_: WOS citing   _C_: Crossref       _f_: Copy bibtex entry to file
3372 _o_: Open entry   _e_: Email entry and pdf
3373 "
3374     ("o" org-ref-open-citation-at-point nil)
3375     ("p" org-ref-open-pdf-at-point nil)
3376     ("n" org-ref-open-notes-at-point nil)
3377     ("u" org-ref-open-url-at-point nil)
3378     ("w" org-ref-wos-at-point nil)
3379     ("r" org-ref-wos-related-at-point nil)
3380     ("c" org-ref-wos-citing-at-point nil)
3381     ("g" org-ref-google-scholar-at-point nil)
3382     ("P" org-ref-pubmed-at-point nil)
3383     ("C" org-ref-crossref-at-point nil)
3384     ("K" org-ref-copy-entry-as-summary nil)
3385     ("k" (progn
3386            (kill-new
3387             (car (org-ref-get-bibtex-key-and-file)))) nil)
3388     ("f" org-ref-copy-entry-at-point-to-file nil)
3389
3390     ("e" (save-excursion
3391            (org-ref-open-citation-at-point)
3392            (email-bibtex-entry)) nil)))
3393
3394 ;; * org-ref-help
3395 (defun org-ref-help ()
3396   "Open the org-ref manual."
3397   (interactive)
3398   (find-file (expand-file-name
3399               "org-ref.org"
3400               (file-name-directory
3401                (find-library-name "org-ref")))))
3402
3403 ;; * org-ref menu
3404 (defun org-ref-org-menu ()
3405   "Add org-ref menu to the Org menu."
3406
3407   (easy-menu-change
3408    '("Org") "org-ref"
3409    '( ["Insert citation" org-ref-helm-insert-cite-link]
3410       ["Insert ref" org-ref-helm-insert-ref-link]
3411       ["Insert label" org-ref-helm-insert-label-link]
3412       "--"
3413       ["List of figures" org-ref-list-of-figures]
3414       ["List of tables" org-ref-list-of-tables]
3415       ["Extract bibtex entries" org-ref-extract-bibtex-entries]
3416       ["Check org-file" org-ref]
3417       "--"
3418       ["Help" org-ref-help]
3419       ["Customize org-ref" (customize-group 'org-ref)])
3420    "Show/Hide")
3421
3422   (easy-menu-change '("Org") "--" nil "Show/Hide"))
3423
3424 (add-hook 'org-mode-hook 'org-ref-org-menu)
3425
3426 ;; * The end
3427 (provide 'org-ref)
3428
3429 ;;; org-ref.el ends here