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