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