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