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