]> git.donarmstrong.com Git - org-ref.git/blob - org-ref.el
tiny bug: it seems the key is obtained through "=key="
[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-open-notes-function
93   (lambda ()
94     (org-show-entry)
95     (show-branches)
96     (show-children)
97     (org-cycle '(64))
98     ;;(org-tree-to-indirect-buffer)
99     (outline-previous-visible-heading 1)
100     (recenter-top-bottom 0))
101   "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."
102 :type 'function
103 :group 'org-ref)
104
105
106 (defcustom org-ref-open-pdf-function
107    'org-ref-open-pdf-at-point
108 "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'."
109   :type 'function
110   :group 'org-ref)
111
112
113 (defcustom org-ref-insert-cite-function
114   'org-ref-helm-insert-cite-link
115   "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."
116  :type 'function
117  :group 'org-ref)
118
119
120 (defcustom org-ref-cite-onclick-function
121   'org-ref-cite-click-helm
122   "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'."
123  :type 'function
124  :group 'org-ref)
125
126
127 (defcustom org-ref-show-citation-on-enter t
128   "If non-nil add a hook function to show the citation summary in the minibuffer."
129  :group 'org-ref)
130
131 (defcustom org-ref-cite-types
132   '("cite" "nocite" ;; the default latex cite commands
133     ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
134     "citet" "citet*" "citep" "citep*"
135     "citealt" "citealt*" "citealp" "citealp*"
136     "citenum" "citetext"
137     "citeauthor" "citeauthor*"
138     "citeyear" "citeyear*"
139     "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
140     ;; biblatex commands
141     ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
142     "Cite"
143     "parencite" "Parencite"
144     "footcite" "footcitetext"
145     "textcite" "Textcite"
146     "smartcite" "Smartcite"
147     "cite*" "parencite*" "supercite"
148     "autocite" "Autocite" "autocite*" "Autocite*"
149     "Citeauthor*"
150     "citetitle" "citetitle*"
151     "citedate" "citedate*"
152     "citeurl"
153     "fullcite" "footfullcite"
154     ;; "volcite" "Volcite" cannot support the syntax
155     "notecite" "Notecite"
156     "pnotecite" "Pnotecite"
157     "fnotecite"
158     ;; multicites. Very limited support for these.
159     "cites" "Cites" "parencites" "Parencites"
160     "footcites" "footcitetexts"
161     "smartcites" "Smartcites" "textcites" "Textcites"
162     "supercites" "autocites" "Autocites"
163     ;; for the bibentry package
164     "bibentry"
165     )
166   "List of citation types known in `org-ref'."
167   :type '(repeat :tag "List of citation types" string)
168   :group 'org-ref)
169
170 (defcustom org-ref-clean-bibtex-entry-hook nil
171   "Hook that is run in `org-ref-clean-bibtex-entry'.  The functions should take no arguments, and operate on the bibtex entry at point."
172   :group 'org-ref
173   :type 'hook)
174
175 (defvar org-ref-bibliography-files
176   nil
177   "Variable to hold bibliography files to be searched.")
178
179 ;; * org-mode / reftex setup
180 (require 'reftex)
181 (defun org-mode-reftex-setup ()
182   "Setup `org-mode' and reftex for org-ref."
183     (and (buffer-file-name)
184          (file-exists-p (buffer-file-name))
185          (global-auto-revert-mode t))
186     (make-local-variable 'reftex-cite-format)
187     (setq reftex-cite-format 'org))
188
189 ;; define key for inserting citations
190 (define-key org-mode-map
191   (kbd org-ref-insert-cite-key)
192   org-ref-insert-cite-function)
193
194 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
195
196 (eval-after-load 'reftex-vars
197   '(progn
198       (add-to-list 'reftex-cite-format-builtin
199                    '(org "Org-mode citation"
200                          ((?\C-m . "cite:%l")     ; default
201                           (?d . ",%l")            ; for appending
202                           (?a . "autocite:%l")
203                           (?t . "citet:%l")
204                           (?T . "citet*:%l")
205                           (?p . "citep:%l")
206                           (?P . "citep*:%l")
207                           (?h . "citeauthor:%l")
208                           (?H . "citeauthor*:%l")
209                           (?y . "citeyear:%l")
210                           (?x . "citetext:%l")
211                           (?n . "nocite:%l")
212                           )))))
213
214 ;; * Messages for link at cursor
215 (defvar org-ref-message-timer nil
216   "Variable to store the link message timer in.")
217
218
219 (defun org-ref-show-link-messages ()
220   "Turn on link messages.
221 You will see a message in the minibuffer when on a cite, ref or label link."
222   (interactive)
223   (or org-ref-message-timer
224       (setq org-ref-message-timer
225             (run-with-idle-timer 0.5 t 'org-ref-link-message))))
226
227
228 (defun org-ref-cancel-link-messages ()
229   "Stop showing messages in minibuffer when on a link."
230   (interactive)
231   (cancel-timer org-ref-message-timer)
232   (setq org-ref-message-timer nil))
233
234
235 (when org-ref-show-citation-on-enter
236   (org-ref-show-link-messages))
237
238 ;; ** Messages for context under mouse pointer
239
240 (defvar org-ref-last-mouse-pos nil
241  "Stores last mouse position for use in `org-ref-mouse-message'.")
242
243 (defun org-ref-can-move-p ()
244   "See if a character is under the mouse.  If so return the position for `goto-char'."
245   (let* ((line (cddr org-ref-last-mouse-pos))
246          (col  (cadr org-ref-last-mouse-pos)))
247     (save-excursion
248       (goto-char (window-start))
249       (forward-line line)
250       (if
251           (> (- (line-end-position) (line-beginning-position)) col)
252           (progn  (forward-char col) (point))
253         nil))))
254
255
256 (defun org-ref-mouse-message ()
257   "Display message for link under mouse cursor."
258   (interactive)
259   (when (not (equal (mouse-position) org-ref-last-mouse-pos))
260     (setq org-ref-last-mouse-pos (mouse-position))
261     (let ((p (org-ref-can-move-p)))
262       (when p
263           (save-excursion
264             (goto-char p)
265             (org-ref-link-message))))))
266
267
268 (defvar org-ref-message-timer-mouse nil
269   "Store mouse timer.")
270
271
272 (defvar org-ref-mouse-message-interval 0.5
273   "How often to run the mouse message timer in seconds.")
274
275
276 (defun org-ref-mouse-messages-on ()
277   "Turn on mouse messages."
278   (interactive)
279   (or org-ref-message-timer-mouse
280       (setq org-ref-message-timer-mouse
281             (run-at-time "0.5 sec"
282                          org-ref-mouse-message-interval
283                          'org-ref-mouse-message))))
284
285
286 (defun org-ref-mouse-messages-off ()
287   "Turn off mouse messages."
288   (interactive)
289   (cancel-timer org-ref-message-timer-mouse)
290   (setq org-ref-message-timer-mouse nil)
291   (message "Mouse messages are off"))
292
293 ;; Colorizing org-ref links
294 (defcustom org-ref-colorize-links
295   t
296   "When non-nil, change colors of links."
297   :group 'org-ref)
298
299
300 (defcustom org-ref-cite-color
301   "forest green"
302   "Color of cite like links."
303   :group 'org-ref)
304
305
306 (defcustom org-ref-ref-color
307   "dark red"
308   "Color of ref like links."
309   :group 'org-ref)
310
311
312 (defcustom org-ref-label-color
313   "dark magenta"
314   "Color of label links."
315   :group 'org-ref)
316
317
318 (defvar org-ref-cite-re nil
319  "Regexp for cite links.")
320
321
322 (setq org-ref-cite-re
323       (concat "\\(" (mapconcat
324                      (lambda (x)
325                        (replace-regexp-in-string "\*" "\\\\*" x)
326                        )
327                      org-ref-cite-types "\\|") "\\)"
328   ":\\([a-zA-Z0-9-_:\\./]*,?\\)*"))
329
330
331 (defvar org-ref-label-re
332   "label:\\([a-zA-Z0-9-_:]*,?\\)*")
333
334
335 (defvar org-ref-ref-re
336   "\\(eq\\)?ref:\\([a-zA-Z0-9-_:]*,?\\)*")
337
338
339 (defface org-ref-cite-face
340   `((t (:inherit org-link :foreground ,org-ref-cite-color)))
341   "Color for cite-like links in org-ref.")
342
343
344 (defface org-ref-label-face
345   `((t (:inherit org-link :foreground ,org-ref-label-color)))
346   "Color for ref links in org-ref.")
347
348
349 (defface org-ref-ref-face
350   `((t (:inherit org-link :foreground ,org-ref-ref-color)))
351   "Face for ref links in org-ref.")
352
353
354 (defun org-ref-colorize-links ()
355   "Colorize org-ref links."
356   (hi-lock-mode 1)
357   (highlight-regexp org-ref-cite-re 'org-ref-cite-face)
358   (highlight-regexp org-ref-label-re 'org-ref-label-face)
359   (highlight-regexp org-ref-ref-re 'org-ref-ref-face))
360
361
362 (when org-ref-colorize-links
363   (add-hook 'org-mode-hook 'org-ref-colorize-links))
364
365 ;; * General org-ref utilities
366 (defun org-ref-strip-string (string)
367   "Strip leading and trailing whitespace from the STRING."
368   (replace-regexp-in-string
369    (concat search-whitespace-regexp "$" ) ""
370    (replace-regexp-in-string
371     (concat "^" search-whitespace-regexp ) "" string)))
372
373 (defun org-ref-split-and-strip-string (string)
374   "Split key-string and strip keys in STRING.
375 Assumes the key-string is comma delimited."
376   (mapcar 'org-ref-strip-string (split-string string ",")))
377
378 (defun org-ref-reftex-get-bib-field (field entry &optional format)
379   "Similar to reftex-get-bib-field, but removes enclosing braces and quotes in FIELD in the bibtex ENTRY.
380 Optional argument FORMAT bibtex format."
381   (let ((result))
382     (setq result (reftex-get-bib-field field entry format))
383     (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
384       (setq result (substring result 1 -1)))
385     (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
386       (setq result (substring result 1 -1)))
387       result))
388
389 (defun org-ref-reftex-format-citation (entry format)
390   "Return a formatted string for the bibtex ENTRY (from bibtex-parse-entry) according to the FORMAT argument.
391 The format is a string with these percent escapes.
392
393 In the format, the following percent escapes will be expanded.
394
395 %l   The BibTeX label of the citation.
396 %a   List of author names, see also `reftex-cite-punctuation'.
397 %2a  Like %a, but abbreviate more than 2 authors like Jones et al.
398 %A   First author name only.
399 %e   Works like %a, but on list of editor names. (%2e and %E work a well)
400
401 It is also possible to access all other BibTeX database fields:
402 %b booktitle     %c chapter        %d edition    %h howpublished
403 %i institution   %j journal        %k key        %m month
404 %n number        %o organization   %p pages      %P first page
405 %r address       %s school         %u publisher  %t title
406 %v volume        %y year
407 %B booktitle, abbreviated          %T title, abbreviated
408 %U url
409 %D doi
410 %S series
411
412 Usually, only %l is needed.  The other stuff is mainly for the echo area
413 display, and for (setq reftex-comment-citations t).
414
415 %< as a special operator kills punctuation and space around it after the
416 string has been formatted.
417
418 A pair of square brackets indicates an optional argument, and RefTeX
419 will prompt for the values of these arguments.
420
421 Beware that all this only works with BibTeX database files.  When
422 citations are made from the \bibitems in an explicit thebibliography
423 environment, only %l is available."
424   ;; Format a citation from the info in the BibTeX ENTRY
425   (unless (stringp format) (setq format "\\cite{%l}"))
426
427   (if (and reftex-comment-citations
428            (string-match "%l" reftex-cite-comment-format))
429       (error "Reftex-cite-comment-format contains invalid %%l"))
430
431   (while (string-match
432           "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
433           format)
434     (let ((n (string-to-number (match-string 4 format)))
435           (l (string-to-char (match-string 5 format)))
436           rpl b e)
437       (save-match-data
438         (setq rpl
439               (cond
440                ((= l ?l) (concat
441                           (org-ref-reftex-get-bib-field "&key" entry)
442                           (if reftex-comment-citations
443                               reftex-cite-comment-format
444                             "")))
445                ((= l ?a) (reftex-format-names
446                           (reftex-get-bib-names "author" entry)
447                           (or n 2)))
448                ((= l ?A) (car (reftex-get-bib-names "author" entry)))
449                ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
450                ((= l ?B) (reftex-abbreviate-title
451                           (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
452                ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
453                ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
454                ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
455                ((= l ?e) (reftex-format-names
456                           (reftex-get-bib-names "editor" entry)
457                           (or n 2)))
458                ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
459                ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
460                ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
461                ((= l ?j) (let ((jt (reftex-get-bib-field "journal" entry)))
462                            (if (string= "" jt)
463                                (reftex-get-bib-field "journaltitle" entry)
464                              jt)))
465                ((= l ?k) (org-ref-reftex-get-bib-field "=key=" entry))
466                ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
467                ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
468                ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
469                ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
470                ((= l ?P) (car (split-string
471                                (org-ref-reftex-get-bib-field "pages" entry)
472                                "[- .]+")))
473                ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
474                ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
475                ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
476                ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
477                ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
478                ;; strip enclosing brackets from title if they are there
479                ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
480                ((= l ?T) (reftex-abbreviate-title
481                           (org-ref-reftex-get-bib-field "title" entry)))
482                ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
483                ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
484
485       (if (string= rpl "")
486           (setq b (match-beginning 2) e (match-end 2))
487         (setq b (match-beginning 3) e (match-end 3)))
488       (setq format (concat (substring format 0 b) rpl (substring format e)))))
489   (while (string-match "%%" format)
490     (setq format (replace-match "%" t t format)))
491   (while (string-match "[ ,.;:]*%<" format)
492     (setq format (replace-match "" t t format)))
493   ;; also replace carriage returns, tabs, and multiple whitespaces
494   (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
495   format)
496
497 (defun org-ref-get-bibtex-entry-citation (key)
498   "Return a string for the bibliography entry corresponding to KEY.
499 Format according to the type in `org-ref-bibliography-entry-format'."
500
501   (let ((org-ref-bibliography-files (org-ref-find-bibliography))
502         (file) (entry) (bibtex-entry) (entry-type) (format))
503
504     (setq file (catch 'result
505                  (cl-loop for file in org-ref-bibliography-files do
506                           (if (org-ref-key-in-file-p key (file-truename file))
507                               (throw 'result file)
508                             (message "%s not found in %s"
509                                      key (file-truename file))))))
510
511     (with-temp-buffer
512       (insert-file-contents file)
513       (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
514       (bibtex-search-entry key nil 0)
515       (setq bibtex-entry (bibtex-parse-entry))
516       ;; downcase field names so they work in the format-citation code
517       (dolist (cons-cell bibtex-entry)
518         (setf (car cons-cell) (downcase (car cons-cell))))
519       (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
520       (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
521       (if format
522           (setq entry  (org-ref-reftex-format-citation bibtex-entry format))
523         ;; if no format, we use the bibtex entry itself as a fallback
524         (save-restriction
525           (bibtex-narrow-to-entry)
526           (setq entry (buffer-string)))))
527     entry))
528
529 (defun org-ref-get-bibtex-keys ()
530   "Return a list of unique keys in the buffer."
531   (let ((keys '()))
532     (org-element-map (org-element-parse-buffer) 'link
533       (lambda (link)
534         (let ((plist (nth 1 link)))
535           (when (-contains? org-ref-cite-types (plist-get plist ':type))
536             (dolist
537                 (key
538                  (org-ref-split-and-strip-string (plist-get plist ':path)))
539               (when (not (-contains? keys key))
540                 (setq keys (append keys (list key))))))))
541       ;; set with-affiliated to get keys in captions
542       nil nil nil t)
543     ;; Sort keys alphabetically
544     (setq keys (cl-sort keys 'string-lessp :key 'downcase))
545     keys))
546
547 (defun org-ref-get-bibtex-entry-html (key)
548   "Return an html string for the bibliography entry corresponding to KEY."
549   (let ((output))
550     (setq output (org-ref-get-bibtex-entry-citation key))
551     ;; unescape the &
552     (setq output (replace-regexp-in-string "\\\\&" "&" output))
553     ;; hack to replace {} around text
554     (setq output (replace-regexp-in-string "{" "" output))
555     (setq output (replace-regexp-in-string "}" "" output))
556     ;; get rid of empty parens
557     (setq output (replace-regexp-in-string "()" "" output))
558     ;; get rid of empty link and doi
559     (setq output (replace-regexp-in-string " <a href=\"\">link</a>\\." "" output))
560     ;; change double dash to single dash
561     (setq output (replace-regexp-in-string "--" "-" output))
562     (setq output (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" output))
563     (format "<li><a id=\"%s\">[%s] %s</a></li>"
564             key key output)))
565
566 (defun org-ref-get-html-bibliography ()
567   "Create an html bibliography when there are keys."
568   (let ((keys (org-ref-get-bibtex-keys)))
569     (when keys
570       (concat "<h1>Bibliography</h1>
571 <ul>"
572               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
573               "\n</ul>"))))
574
575 (defun org-ref-get-bibtex-entry-org (key)
576   "Return an org string for the bibliography entry corresponding to KEY."
577   (let ((org-ref-bibliography-files (org-ref-find-bibliography))
578         (file) (entry) (bibtex-entry) (entry-type) (format))
579
580     (setq file (catch 'result
581                  (cl-loop for file in org-ref-bibliography-files do
582                        (if (org-ref-key-in-file-p key (file-truename file))
583                            (throw 'result file)
584                          (message "%s not found in %s" key (file-truename file))))))
585
586     (with-temp-buffer
587       (insert-file-contents file)
588       (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
589       (bibtex-search-entry key nil 0)
590       (setq entry (bibtex-parse-entry))
591       (format "** %s - %s
592   :PROPERTIES:
593   %s
594   :END:
595 " (org-ref-reftex-get-bib-field "author" entry)
596 (org-ref-reftex-get-bib-field "title" entry)
597 (concat "   :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
598         (mapconcat (lambda (element) (format "   :%s: %s"
599                                              (upcase (car element))
600                                              (cdr element)))
601                    entry
602                    "\n"))))))
603
604 (defun org-ref-get-org-bibliography ()
605   "Create an org bibliography when there are keys."
606   (let ((keys (org-ref-get-bibtex-keys)))
607     (when keys
608       (concat "* Bibliography
609 "
610               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
611               "\n"))))
612
613 (defun org-ref-get-bibtex-entry-ascii (key)
614   "Return an ascii string for the bibliography entry corresponding to KEY."
615
616   (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
617
618 (defun org-ref-get-ascii-bibliography ()
619   "Create an html bibliography when there are keys."
620   (let ((keys (org-ref-get-bibtex-keys)))
621     (when keys
622       (concat
623 "Bibliography
624 =============
625 "
626               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
627               "\n"))))
628
629 ;; * Links
630 ;; ** bibliography and bibliographystyle
631 (org-add-link-type "bibliography"
632                    ;; this code is run on clicking. The bibliography
633                    ;; may contain multiple files. this code finds the
634                    ;; one you clicked on and opens it.
635                    (lambda (link-string)
636                        ;; get link-string boundaries we have to go to the
637                        ;; beginning of the line, and then search forward
638                      (let* ((bibfile)
639                             ;; object is the link you clicked on
640                             (object (org-element-context))
641                             (link-string-beginning)
642                             (link-string-end)
643                             (cp (point)))
644                      (save-excursion
645                        (goto-char (org-element-property :begin object))
646                        (search-forward link-string nil nil 1)
647                        (setq link-string-beginning (match-beginning 0))
648                        (setq link-string-end (match-end 0)))
649
650                      ;; Make sure point is in the link-path.
651                      (if (< cp link-string-beginning)
652                          (goto-char link-string-beginning))
653                      ;; We set the reftex-default-bibliography
654                      ;; here. it should be a local variable only in
655                      ;; the current buffer. We need this for using
656                      ;; reftex to do citations.
657                      (set (make-local-variable 'reftex-default-bibliography)
658                           (split-string
659                            (org-element-property :path object) ","))
660
661                      (let (key-beginning key-end)
662                        ;; now if we have comma separated bibliographies
663                        ;; we find the one clicked on. we want to
664                        ;; search forward to next comma from point
665                        (save-excursion
666                          (if (search-forward "," link-string-end 1 1)
667                              ;; we found a match
668                              (setq key-end (- (match-end 0) 1))
669                            ;; no comma found so take the point
670                            (setq key-end (point))))
671                        ;; and backward to previous comma from point
672                        (save-excursion
673                          (if (search-backward "," link-string-beginning 1 1)
674                              ;; we found a match
675                              (setq key-beginning (+ (match-beginning 0) 1))
676                            (setq key-beginning (point)))) ; no match found
677                        ;; save the key we clicked on.
678                        (setq bibfile (org-ref-strip-string
679                                       (buffer-substring key-beginning key-end)))
680                        ;; open file on click
681                        (find-file bibfile))))
682
683                    ;; formatting code
684                    (lambda (keyword desc format)
685                      (cond
686                       ((eq format 'org) (org-ref-get-org-bibliography))
687                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
688                       ((eq format 'html) (org-ref-get-html-bibliography))
689                       ((eq format 'latex)
690                        ;; write out the latex bibliography command
691                        (format "\\bibliography{%s}"
692                                (replace-regexp-in-string
693                                 "\\.bib" ""
694                                 (mapconcat
695                                  'identity
696                                  (mapcar 'expand-file-name
697                                          (split-string keyword ","))
698                                  ",")))))))
699
700 (org-add-link-type "nobibliography"
701                    ;; this code is run on clicking. The bibliography
702                    ;; may contain multiple files. this code finds the
703                    ;; one you clicked on and opens it.
704                    (lambda (link-string)
705                        ;; get link-string boundaries
706                        ;; we have to go to the beginning of the line, and then search forward
707
708                      (let* ((bibfile)
709                             ;; object is the link you clicked on
710                             (object (org-element-context))
711
712                             (link-string-beginning)
713                             (link-string-end))
714
715                      (save-excursion
716                        (goto-char (org-element-property :begin object))
717                        (search-forward link-string nil nil 1)
718                        (setq link-string-beginning (match-beginning 0))
719                        (setq link-string-end (match-end 0)))
720
721                        ;; We set the reftex-default-bibliography
722                        ;; here. it should be a local variable only in
723                        ;; the current buffer. We need this for using
724                        ;; reftex to do citations.
725                        (set (make-local-variable 'reftex-default-bibliography)
726                             (split-string (org-element-property :path object) ","))
727
728                        (let (key-beginning key-end)
729                          ;; now if we have comma separated bibliographies
730                          ;; we find the one clicked on. we want to
731                          ;; search forward to next comma from point
732                          (save-excursion
733                            (if (search-forward "," link-string-end 1 1)
734                                (setq key-end (- (match-end 0) 1)) ; we found a match
735                              (setq key-end (point)))) ; no comma found so take the point
736                          ;; and backward to previous comma from point
737                          (save-excursion
738                            (if (search-backward "," link-string-beginning 1 1)
739                                (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
740                              (setq key-beginning (point)))) ; no match found
741                          ;; save the key we clicked on.
742                          (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
743                          (find-file bibfile)))) ; open file on click
744
745                      ;; formatting code
746                    (lambda (keyword desc format)
747                      (cond
748                       ((eq format 'org) (org-ref-get-org-bibliography))
749                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
750                       ((eq format 'html) (org-ref-get-html-bibliography))
751                       ((eq format 'latex)
752                        ;; write out the latex bibliography command
753                        (format "\\nobibliography{%s}"
754                                (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
755                                                                                  (mapcar 'expand-file-name
756                                                                                          (split-string keyword ","))
757                                                                                  ",")))))))
758
759 (org-add-link-type "printbibliography"
760                    (lambda (arg) (message "Nothing implemented for clicking here."))
761                    (lambda (keyword desc format)
762                      (cond
763                       ((eq format 'org) (org-ref-get-org-bibliography))
764                       ((eq format 'html) (org-ref-get-html-bibliography))
765                       ((eq format 'latex)
766                        ;; write out the biblatex bibliography command
767                        "\\printbibliography"))))
768
769 (org-add-link-type "bibliographystyle"
770                    (lambda (arg) (message "Nothing implemented for clicking here."))
771                    (lambda (keyword desc format)
772                      (cond
773                       ((eq format 'latex)
774                        ;; write out the latex bibliography command
775                        (format "\\bibliographystyle{%s}" keyword))
776                       ;; Other styles should not have an output for this
777                       (t
778                        ""))))
779
780
781 (defun org-bibliographystyle-complete-link (&optional arg)
782   "Completion function for bibliographystyle link.
783 ARG does nothing."
784   (format "bibliographystyle:%s" (ido-completing-read
785                                   "style: "
786                                   '("unsrt" "plain" "alpha"
787                                     ;; natbib
788                                     ;; https://www.sharelatex.com/learn/Natbib_bibliography_styles
789                                     "dinat" "humannat" "plainnat"
790                                     "abbrnat" "unsrtnat" "rusnat"
791                                     "ksfhnat"))))
792
793
794 (defun org-bibliography-complete-link (&optional arg)
795   "Completion function for bibliography link.
796 ARG does nothing."
797   (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
798
799
800 (defun org-ref-insert-bibliography-link ()
801   "Insert a bibliography with completion."
802   (interactive)
803   (insert (org-bibliography-complete-link)))
804
805 ;; ** addbibresource
806
807 (org-add-link-type "addbibresource"
808                    ;; this code is run on clicking. The addbibresource
809                    ;; may contain multiple files. this code finds the
810                    ;; one you clicked on and opens it.
811                    (lambda (link-string)
812                        ;; get link-string boundaries
813                        ;; we have to go to the beginning of the line, and then search forward
814
815                      (let* ((bibfile)
816                             ;; object is the link you clicked on
817                             (object (org-element-context))
818
819                             (link-string-beginning)
820                             (link-string-end))
821
822                      (save-excursion
823                        (goto-char (org-element-property :begin object))
824                        (search-forward link-string nil nil 1)
825                        (setq link-string-beginning (match-beginning 0))
826                        (setq link-string-end (match-end 0)))
827
828                        ;; We set the reftex-default-addbibresource
829                        ;; here. it should be a local variable only in
830                        ;; the current buffer. We need this for using
831                        ;; reftex to do citations.
832                        (set (make-local-variable 'reftex-default-addbibresource)
833                             (split-string (org-element-property :path object) ","))
834
835                        (let (key-beginning key-end)
836                          ;; now if we have comma separated bibliographies
837                          ;; we find the one clicked on. we want to
838                          ;; search forward to next comma from point
839                          (save-excursion
840                            (if (search-forward "," link-string-end 1 1)
841                                (setq key-end (- (match-end 0) 1)) ; we found a match
842                              (setq key-end (point)))) ; no comma found so take the point
843                          ;; and backward to previous comma from point
844                          (save-excursion
845                            (if (search-backward "," link-string-beginning 1 1)
846                                (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
847                              (setq key-beginning (point)))) ; no match found
848                          ;; save the key we clicked on.
849                          (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
850                          (find-file bibfile)))) ; open file on click
851
852                      ;; formatting code
853                    (lambda (keyword desc format)
854                      (cond
855                       ((eq format 'html) (format "")); no output for html
856                       ((eq format 'latex)
857                          ;; write out the latex addbibresource command
858                        (format "\\addbibresource{%s}" keyword)))))
859
860 ;; ** List of figures
861 (defun org-ref-list-of-figures (&optional arg)
862   "Generate buffer with list of figures in them.
863 ARG does nothing."
864   (interactive)
865   (save-excursion (widen)
866   (let* ((c-b (buffer-name))
867          (counter 0)
868          (list-of-figures
869           (org-element-map (org-element-parse-buffer) 'link
870             (lambda (link)
871               "create a link for to the figure"
872               (when
873                   (and (string= (org-element-property :type link) "file")
874                        (string-match-p
875                         "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
876                         (org-element-property :path link)))
877                 (cl-incf counter)
878
879                 (let* ((start (org-element-property :begin link))
880                        (parent (car (cdr (org-element-property :parent link))))
881                        (caption (cl-caaar (plist-get parent :caption)))
882                        (name (plist-get parent :name)))
883                   (if caption
884                       (format
885                        "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
886                        c-b start counter (or name "") caption)
887                     (format
888                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
889                      c-b start counter (or name "")))))))))
890     (switch-to-buffer "*List of Figures*")
891     (setq buffer-read-only nil)
892     (org-mode)
893     (erase-buffer)
894     (insert (mapconcat 'identity list-of-figures ""))
895     (setq buffer-read-only t)
896     (use-local-map (copy-keymap org-mode-map))
897     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
898
899 (org-add-link-type
900  "list-of-figures"
901  'org-ref-list-of-figures ; on click
902  (lambda (keyword desc format)
903    (cond
904     ((eq format 'latex)
905      (format "\\listoffigures")))))
906
907 ;; ** List of tables
908 (defun org-ref-list-of-tables (&optional arg)
909   "Generate a buffer with a list of tables.
910 ARG does nothing."
911   (interactive)
912   (save-excursion
913   (widen)
914   (let* ((c-b (buffer-name))
915          (counter 0)
916          (list-of-tables
917           (org-element-map (org-element-parse-buffer 'element) 'table
918             (lambda (table)
919               "create a link for to the table"
920               (cl-incf counter)
921               (let ((start (org-element-property :begin table))
922                     (name  (org-element-property :name table))
923                     (caption (cl-caaar (org-element-property :caption table))))
924                 (if caption
925                     (format
926                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
927                      c-b start counter (or name "") caption)
928                   (format
929                    "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
930                    c-b start counter (or name ""))))))))
931     (switch-to-buffer "*List of Tables*")
932     (setq buffer-read-only nil)
933     (org-mode)
934     (erase-buffer)
935     (insert (mapconcat 'identity list-of-tables ""))
936     (setq buffer-read-only t)
937     (use-local-map (copy-keymap org-mode-map))
938     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
939
940 (org-add-link-type
941  "list-of-tables"
942  'org-ref-list-of-tables
943  (lambda (keyword desc format)
944    (cond
945     ((eq format 'latex)
946      (format "\\listoftables")))))
947
948
949 ;; ** label link
950 (defun org-ref-count-labels (label)
951   "Counts number of matches for LABEL in the document."
952   (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
953      ;; for tblname, it is not enough to get word boundary
954      ;; tab-little and tab-little-2 match then.
955      (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
956      (count-matches (format "\\label{%s}" label) (point-min) (point-max))
957      ;; this is the org-format #+label:
958      (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
959      (let ((custom-id-count 0))
960        (org-map-entries
961         (lambda ()
962           (when (string= label (org-entry-get (point) "CUSTOM_ID"))
963             (setq custom-id-count (+ 1 custom-id-count)))))
964        custom-id-count)))
965
966 (org-add-link-type
967  "label"
968  (lambda (label)
969    "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
970    (let ((count (org-ref-count-labels label)))
971    (message (format "%s occurence%s"
972                     count
973                     (if (or (= count 0)
974                               (> count 1))
975                         "s"
976                       ""))
977                     (org-ref-count-labels label))))
978  (lambda (keyword desc format)
979    (cond
980     ((eq format 'html) (format "<div id=\"%s\">" keyword))
981     ((eq format 'latex)
982      (format "\\label{%s}" keyword)))))
983
984 (defun org-label-store-link ()
985   "Store a link to a label.  The output will be a ref to that label."
986   ;; First we have to make sure we are on a label link.
987   (let* ((object (org-element-context)))
988     (when (and (equal (org-element-type object) 'link)
989                (equal (org-element-property :type object) "label"))
990       (org-store-link-props
991        :type "ref"
992        :link (concat "ref:" (org-element-property :path object))))
993
994     ;; Store link on table
995     (when (equal (org-element-type object) 'table)
996       (org-store-link-props
997        :type "ref"
998        :link (concat "ref:" (org-element-property :name object))))
999
1000     ;; store link on heading with custom_id
1001     ;; this is not a ref link, but it is still what you want
1002     (when (and (equal (org-element-type object) 'headline)
1003                (org-entry-get (point) "CUSTOM_ID"))
1004       (org-store-link-props
1005        :type "custom_id"
1006        :link (format "[[#%s]]" (org-entry-get (point) "CUSTOM_ID"))))
1007
1008     ;; and to #+label: lines
1009
1010     (when (and (equal (org-element-type object) 'paragraph)
1011                (org-element-property :name object))
1012       (org-store-link-props
1013        :type "ref"
1014        :link (concat "ref:" (org-element-property :name object))))))
1015
1016 (add-hook 'org-store-link-functions 'org-label-store-link)
1017
1018 ;; ** ref link
1019 (org-add-link-type
1020  "ref"
1021  (lambda (label)
1022    "on clicking goto the label. Navigate back with C-c &"
1023    (org-mark-ring-push)
1024    ;; next search from beginning of the buffer
1025    ;; it is possible you would not find the label if narrowing is in effect
1026    (widen)
1027    (unless
1028        (or
1029         ;; our label links
1030         (progn
1031           (goto-char (point-min))
1032           (re-search-forward (format "label:%s\\b" label) nil t))
1033
1034         ;; a latex label
1035         (progn
1036           (goto-char (point-min))
1037           (re-search-forward (format "\\label{%s}" label) nil t))
1038
1039         ;; #+label: name  org-definition
1040         (progn
1041           (goto-char (point-min))
1042           (re-search-forward
1043            (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1044
1045         ;; org tblname
1046         (progn
1047           (goto-char (point-min))
1048           (re-search-forward
1049            (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1050
1051      ;; we did not find anything, so go back to where we came
1052      (org-mark-ring-goto)
1053      (error "%s not found" label))
1054    (org-show-entry)
1055    (message "go back with (org-mark-ring-goto) `C-c &`"))
1056  ;formatting
1057  (lambda (keyword desc format)
1058    (cond
1059     ((eq format 'html) (format "<a href=\"#%s\">%s</a>" keyword keyword))
1060     ((eq format 'latex)
1061      (format "\\ref{%s}" keyword)))))
1062
1063
1064 (defun org-ref-get-org-labels ()
1065  "Return a list of #+LABEL: labels."
1066   (save-excursion
1067     (goto-char (point-min))
1068     (let ((matches '()))
1069       (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1070         ;; do not do this for tables. We get those in `org-ref-get-tblnames'.
1071         ;; who would have thought you have save match data here? Trust me. When
1072         ;; I wrote this, you did.
1073         (unless (save-match-data  (equal (car (org-element-at-point)) 'table))
1074           (add-to-list 'matches (match-string-no-properties 1) t)))
1075       matches)))
1076
1077
1078 (defun org-ref-get-custom-ids ()
1079  "Return a list of custom_id properties in the buffer."
1080  (let ((results '()) custom_id)
1081    (org-map-entries
1082     (lambda ()
1083       (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1084         (when (not (null custom_id))
1085           (setq results (append results (list custom_id)))))))
1086    results))
1087
1088
1089 (defun org-ref-get-latex-labels ()
1090   "Return list of matchin LaTeX defined labels in buffer."
1091   (save-excursion
1092     (goto-char (point-min))
1093     (let ((matches '()))
1094       (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1095         (add-to-list 'matches (match-string-no-properties 1) t))
1096       matches)))
1097
1098
1099 (defun org-ref-get-tblnames ()
1100   "Return list of table names in the buffer."
1101   (org-element-map (org-element-parse-buffer 'element) 'table
1102     (lambda (table)
1103       (org-element-property :name table))))
1104
1105
1106 (defun org-ref-get-labels ()
1107   "Return a list of labels in the buffer that you can make a ref link to.
1108 This is used to complete ref links and in helm menus."
1109   (save-excursion
1110     (save-restriction
1111       (widen)
1112       (goto-char (point-min))
1113       (let ((matches '()))
1114         ;; these are the org-ref label:stuff  kinds
1115         (while (re-search-forward
1116                 "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1117           (add-to-list 'matches (match-string-no-properties 1) t))
1118         ;; now add all the other kinds of labels.
1119         (append matches
1120                 ;; #+label:
1121                 (org-ref-get-org-labels)
1122                 ;; \label{}
1123                 (org-ref-get-latex-labels)
1124                 ;; #+tblname: and actually #+label
1125                 (org-ref-get-tblnames)
1126                 ;; CUSTOM_IDs
1127                 (org-ref-get-custom-ids))))))
1128
1129
1130 (defun org-ref-helm-insert-label-link ()
1131   "Insert a label link. helm just shows you what labels already exist.
1132 If you are on a label link, replace it."
1133   (interactive)
1134   (let* ((labels (org-ref-get-labels))
1135          (cb (current-buffer)))
1136     (helm :sources `(((name . "Existing labels")
1137                       (candidates . ,labels)
1138                       ;; default action is to open to the label
1139                       (action . (lambda (label)
1140                                   ;; unfortunately I do not have markers here
1141                                   (org-open-link-from-string
1142                                    (format "ref:%s" label))))
1143                       ;; if you select a label, replace current one
1144                       (action . (lambda (label)
1145                                   (switch-to-buffer ,cb)
1146                                   (cond
1147                                    ;;  no prefix or on a link
1148                                    ((equal helm-current-prefix-arg nil)
1149                                     (let* ((object (org-element-context))
1150                                            (last-char (save-excursion
1151                                                         (goto-char (org-element-property :end object))
1152                                                         (backward-char)
1153                                                         (if (looking-at " ")
1154                                                             " "
1155                                                           ""))))
1156                                       (when (-contains? '("label")
1157                                                         (org-element-property :type object))
1158                                           ;; we are on a link, so replace it.
1159                                         (setf
1160                                            (buffer-substring
1161                                             (org-element-property :begin object)
1162                                             (org-element-property :end object))
1163                                            (concat
1164                                             (replace-regexp-in-string
1165                                              (org-element-property :path object)
1166                                              label
1167                                              (org-element-property :raw-link object))
1168                                             last-char)))))
1169                                    ;; no prefix options defined
1170                                    ))))
1171                      ;; no matching selection creates a new label
1172                      ((name . "Create new label")
1173                       (dummy)
1174                       ;; default action creates a new label, or replaces old one
1175                       (action .  (lambda (label)
1176                                    (switch-to-buffer ,cb)
1177                                    (let* ((object (org-element-context))
1178                                           (last-char (save-excursion
1179                                                        (goto-char (org-element-property :end object))
1180                                                        (backward-char)
1181                                                        (if (looking-at " ")
1182                                                            " "
1183                                                          ""))))
1184                                      (if (-contains? '("label")
1185                                                      (org-element-property :type object))
1186                                          ;; we are on a link, so replace it.
1187                                          (setf
1188                                           (buffer-substring
1189                                            (org-element-property :begin object)
1190                                            (org-element-property :end object))
1191                                           (concat
1192                                            (replace-regexp-in-string
1193                                             (org-element-property :path object)
1194                                             helm-pattern
1195                                             (org-element-property :raw-link object))
1196                                            last-char))
1197                                        ;; new link
1198                                        (insert
1199                                         (concat
1200                                          "label:"
1201                                          (or label
1202                                              helm-pattern))))))))))))
1203
1204
1205 (defun org-ref-complete-link (&optional arg)
1206   "Completion function for ref links.
1207 Optional argument ARG Does nothing."
1208   (let ((label))
1209     (setq label (completing-read "label: " (org-ref-get-labels)))
1210     (format "ref:%s" label)))
1211
1212
1213 (defun org-ref-insert-ref-link ()
1214   "Completion function for a ref link."
1215  (interactive)
1216  (insert (org-ref-complete-link)))
1217
1218
1219 (defun org-ref-helm-insert-ref-link ()
1220   "Helm menu to insert ref links to labels in the document.
1221 If you are on link, replace with newly selected label.
1222 Use C-u to insert a different kind of ref link.
1223 Use C-u C-u to insert a [[#custom-id]] link"
1224   (interactive)
1225   (let* ((labels (org-ref-get-labels))
1226          (bs (buffer-string))
1227          (contexts (with-temp-buffer
1228                      (insert bs)
1229                      (mapcar 'org-ref-get-label-context labels)))
1230          (cb (current-buffer)))
1231
1232     (helm :input (thing-at-point 'word)
1233           :sources `(((name . "Available labels to ref")
1234                       (candidates . ,(cl-loop for label in labels
1235                                               for context in contexts
1236                                               ;; we do some kludgy adding spaces
1237                                               ;; and bars to make it "easier" to
1238                                               ;; see in helm.
1239                                               collect (cons (concat
1240                                                              label "\n"
1241                                                              (mapconcat
1242                                                               (lambda (x)
1243                                                                 (concat "   |" x))
1244                                                               (split-string context "\n")
1245                                                               "\n"
1246                                                               ) "\n\n") label)))
1247                       ;; default action to replace or insert ref link.
1248                       (action . (lambda (label)
1249                                   (switch-to-buffer ,cb)
1250
1251                                   (cond
1252                                    ;;  no prefix or on a link
1253                                    ((equal helm-current-prefix-arg nil)
1254                                     (let* ((object (org-element-context))
1255                                            (last-char (save-excursion
1256                                                         (goto-char (org-element-property :end object))
1257                                                         (backward-char)
1258                                                         (if (looking-at " ")
1259                                                             " "
1260                                                           ""))))
1261                                       (if (-contains? '("ref" "eqref" "pageref" "nameref")
1262                                                       (org-element-property :type object))
1263                                           ;; we are on a link, so replace it.
1264                                           (setf
1265                                            (buffer-substring
1266                                             (org-element-property :begin object)
1267                                             (org-element-property :end object))
1268                                            (concat
1269                                             (replace-regexp-in-string
1270                                              (org-element-property :path object)
1271                                              label
1272                                              (org-element-property :raw-link object))
1273                                             last-char))
1274                                         ;; insert a new link
1275                                         (insert
1276                                          (concat
1277                                           "ref:" label))
1278                                         )))
1279                                    ;; one prefix, alternate ref link
1280                                    ((equal helm-current-prefix-arg '(4))
1281                                     (insert
1282                                      (concat
1283                                       (helm :sources '((name . "Ref link types")
1284                                                        (candidates . ("ref" "eqref" "pageref" "nameref"))
1285                                                        (action . (lambda (x) x))))
1286                                       ":" label)))
1287                                    ;; two prefixes, insert section custom-id link
1288                                    ((equal helm-current-prefix-arg '(16))
1289                                     (insert
1290                                      (format "[[#%s]]" label)))
1291                                    ))
1292                               ))))))
1293
1294 ;; *** pageref link
1295 (org-add-link-type
1296  "pageref"
1297  (lambda (label)
1298    "on clicking goto the label. Navigate back with C-c &"
1299    (org-mark-ring-push)
1300    ;; next search from beginning of the buffer
1301    (widen)
1302    (unless
1303        (or
1304         ;; our label links
1305         (progn
1306           (goto-char (point-min))
1307           (re-search-forward (format "label:%s\\b" label) nil t))
1308
1309         ;; a latex label
1310         (progn
1311           (goto-char (point-min))
1312           (re-search-forward (format "\\label{%s}" label) nil t))
1313
1314         ;; #+label: name  org-definition
1315         (progn
1316           (goto-char (point-min))
1317           (re-search-forward
1318            (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1319
1320         ;; org tblname
1321         (progn
1322           (goto-char (point-min))
1323           (re-search-forward
1324            (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1325      ;; we did not find anything, so go back to where we came
1326      (org-mark-ring-goto)
1327      (error "%s not found" label))
1328    (message "go back with (org-mark-ring-goto) `C-c &`"))
1329  ;formatting
1330  (lambda (keyword desc format)
1331    (cond
1332     ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1333     ((eq format 'latex)
1334      (format "\\pageref{%s}" keyword)))))
1335
1336
1337 (defun org-pageref-complete-link (&optional arg)
1338   "Completion function for ref links.
1339 Optional argument ARG Does nothing."
1340   (let ((label))
1341     (setq label (completing-read "label: " (org-ref-get-labels)))
1342     (format "ref:%s" label)))
1343
1344
1345 (defun org-pageref-insert-ref-link ()
1346   "Insert a pageref link with completion."
1347  (interactive)
1348  (insert (org-pageref-complete-link)))
1349
1350
1351 ;; *** nameref link
1352 (org-add-link-type
1353  "nameref"
1354  (lambda (label)
1355    "on clicking goto the label. Navigate back with C-c &"
1356    (org-mark-ring-push)
1357    ;; next search from beginning of the buffer
1358    (widen)
1359    (unless
1360        (or
1361         ;; a latex label
1362         (progn
1363           (goto-char (point-min))
1364           (re-search-forward (format "\\label{%s}" label) nil t))
1365         )
1366      ;; we did not find anything, so go back to where we came
1367      (org-mark-ring-goto)
1368      (error "%s not found" label))
1369    (message "go back with (org-mark-ring-goto) `C-c &`"))
1370  ;formatting
1371  (lambda (keyword desc format)
1372    (cond
1373     ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1374     ((eq format 'latex)
1375      (format "\\nameref{%s}" keyword)))))
1376
1377 ;; *** eqref link
1378
1379 (org-add-link-type
1380  "eqref"
1381  (lambda (label)
1382    "on clicking goto the label. Navigate back with C-c &"
1383    (org-mark-ring-push)
1384    ;; next search from beginning of the buffer
1385    (widen)
1386    (goto-char (point-min))
1387    (unless
1388        (or
1389         ;; search forward for the first match
1390         ;; our label links
1391         (re-search-forward (format "label:%s" label) nil t)
1392         ;; a latex label
1393         (re-search-forward (format "\\label{%s}" label) nil t)
1394         ;; #+label: name  org-definition
1395         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1396      (org-mark-ring-goto)
1397      (error "%s not found" label))
1398    (message "go back with (org-mark-ring-goto) `C-c &`"))
1399  ;formatting
1400  (lambda (keyword desc format)
1401    (cond
1402     ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1403     ((eq format 'latex)
1404      (format "\\eqref{%s}" keyword)))))
1405
1406 ;; ** cite link
1407
1408 (defun org-ref-get-bibtex-key-under-cursor ()
1409   "Return key under the bibtex cursor.
1410 We search forward from
1411 point to get a comma, or the end of the link, and then backwards
1412 to get a comma, or the beginning of the link.  that delimits the
1413 keyword we clicked on.  We also strip the text properties."
1414   (let* ((object (org-element-context))
1415          (link-string (org-element-property :path object)))
1416     ;; you may click on the part before the citations. here we make
1417     ;; sure to move to the beginning so you get the first citation.
1418     (let ((cp (point)))
1419       (goto-char (org-element-property :begin object))
1420       (search-forward link-string (org-element-property :end object))
1421       (goto-char (match-beginning 0))
1422       ;; check if we clicked before the path and move as needed.
1423       (unless (< cp (point))
1424         (goto-char cp)))
1425
1426     (if (not (org-element-property :contents-begin object))
1427         ;; this means no description in the link
1428         (progn
1429           ;; we need the link path start and end
1430           (let (link-string-beginning link-string-end)
1431             (save-excursion
1432               (goto-char (org-element-property :begin object))
1433               (search-forward link-string nil nil 1)
1434               (setq link-string-beginning (match-beginning 0))
1435               (setq link-string-end (match-end 0)))
1436
1437             (let (key-beginning key-end)
1438               ;; The key is the text between commas, or the link boundaries
1439               (save-excursion
1440                 (if (search-forward "," link-string-end t 1)
1441                     (setq key-end (- (match-end 0) 1)) ; we found a match
1442                   (setq key-end link-string-end))) ; no comma found so take the end
1443               ;; and backward to previous comma from point which defines the start character
1444               (save-excursion
1445                 (if (search-backward "," link-string-beginning 1 1)
1446                     (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1447                   (setq key-beginning link-string-beginning))) ; no match found
1448               ;; save the key we clicked on.
1449               (let ((bibtex-key
1450                      (org-ref-strip-string
1451                       (buffer-substring key-beginning key-end))))
1452                 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1453                 bibtex-key))))
1454       ;; link with description. assume only one key
1455       link-string)))
1456
1457 (defun org-ref-find-bibliography ()
1458   "Find the bibliography in the buffer.
1459 This function sets and returns cite-bibliography-files, which is a list of files
1460 either from bibliography:f1.bib,f2.bib
1461 \bibliography{f1,f2}
1462 internal bibliographies
1463
1464 falling back to what the user has set in `org-ref-default-bibliography'"
1465   (catch 'result
1466     (save-excursion
1467       (goto-char (point-min))
1468       ;;  look for a bibliography link
1469       (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1470         (setq org-ref-bibliography-files
1471               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1472         (throw 'result org-ref-bibliography-files))
1473
1474
1475       ;; we did not find a bibliography link. now look for \bibliography
1476       (goto-char (point-min))
1477       (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1478         ;; split, and add .bib to each file
1479         (setq org-ref-bibliography-files
1480               (mapcar (lambda (x) (concat x ".bib"))
1481                       (mapcar 'org-ref-strip-string
1482                               (split-string (match-string 1) ","))))
1483         (throw 'result org-ref-bibliography-files))
1484
1485       ;; no bibliography found. maybe we need a biblatex addbibresource
1486       (goto-char (point-min))
1487       ;;  look for a bibliography link
1488       (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1489         (setq org-ref-bibliography-files
1490               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1491         (throw 'result org-ref-bibliography-files))
1492
1493       ;; we did not find anything. use defaults
1494       (setq org-ref-bibliography-files org-ref-default-bibliography)))
1495
1496     ;; set reftex-default-bibliography so we can search
1497     (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1498     org-ref-bibliography-files)
1499
1500 (defun org-ref-key-in-file-p (key filename)
1501   "Determine if the KEY is in the FILENAME."
1502   (save-current-buffer
1503     (let ((bibtex-files (list filename)))
1504       ;; This is something I am trying because when the bibtex file is open, and
1505       ;; you have added to it, the only way I find to get the update to update
1506       ;; is to close it and reopen it. or to save it and revert it.
1507       (when (get-file-buffer filename)
1508         (set-buffer (get-file-buffer filename))
1509         (save-buffer)
1510         (revert-buffer t t))
1511       (bibtex-search-entry key t))))
1512
1513 (defun org-ref-get-bibtex-key-and-file (&optional key)
1514   "Return the bibtex KEY and file that it is in.  If no key is provided, get one under point."
1515  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1516        (file))
1517    (unless key
1518      (setq key (org-ref-get-bibtex-key-under-cursor)))
1519    (setq file     (catch 'result
1520                     (cl-loop for file in org-ref-bibliography-files do
1521                              (if (org-ref-key-in-file-p key (file-truename file))
1522                                  (throw 'result file)))))
1523    (cons key file)))
1524
1525 ;; *** key at point functions
1526
1527 (defun org-ref-open-pdf-at-point ()
1528   "Open the pdf for bibtex key under point if it exists."
1529   (interactive)
1530   (let* ((results (org-ref-get-bibtex-key-and-file))
1531          (key (car results))
1532          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1533     (if (file-exists-p pdf-file)
1534         (org-open-file pdf-file)
1535 (message "no pdf found for %s" key))))
1536
1537
1538 (defun org-ref-open-url-at-point ()
1539   "Open the url for bibtex key under point."
1540   (interactive)
1541   (let* ((results (org-ref-get-bibtex-key-and-file))
1542          (key (car results))
1543          (bibfile (cdr results)))
1544     (save-excursion
1545       (with-temp-buffer
1546         (insert-file-contents bibfile)
1547         (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1548         (bibtex-search-entry key)
1549         ;; I like this better than bibtex-url which does not always find
1550         ;; the urls
1551         (catch 'done
1552           (let ((url (bibtex-autokey-get-field "url")))
1553             (when  url
1554               (browse-url (s-trim url))
1555               (throw 'done nil)))
1556
1557           (let ((doi (bibtex-autokey-get-field "doi")))
1558             (when doi
1559               (if (string-match "^http" doi)
1560                   (browse-url doi)
1561                 (browse-url (format "http://dx.doi.org/%s" (s-trim doi))))
1562               (throw 'done nil))))))))
1563
1564
1565 (defun org-ref-open-notes-at-point ()
1566   "Open the notes for bibtex key under point."
1567   (interactive)
1568   (let* ((results (org-ref-get-bibtex-key-and-file))
1569          (key (car results))
1570          (bibfile (cdr results)))
1571     (save-excursion
1572       (with-temp-buffer
1573         (insert-file-contents bibfile)
1574         (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1575         (bibtex-search-entry key)
1576         (org-ref-open-bibtex-notes)))))
1577
1578
1579 (defun org-ref-citation-at-point ()
1580   "Give message of current citation at point."
1581   (interactive)
1582   (let* ((cb (current-buffer))
1583         (results (org-ref-get-bibtex-key-and-file))
1584         (key (car results))
1585         (bibfile (cdr results)))
1586     (message "%s" (progn
1587                     (with-temp-buffer
1588                       (insert-file-contents bibfile)
1589                       (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1590                       (bibtex-search-entry key)
1591                       (org-ref-bib-citation))))))
1592
1593
1594 (defun org-ref-open-citation-at-point ()
1595   "Open bibtex file to key at point."
1596   (interactive)
1597   (let* ((cb (current-buffer))
1598         (results (org-ref-get-bibtex-key-and-file))
1599         (key (car results))
1600         (bibfile (cdr results)))
1601     (find-file bibfile)
1602     (bibtex-search-entry key)))
1603
1604 ;; *** cite menu
1605
1606 (defvar org-ref-cite-menu-funcs '()
1607  "Functions to run on cite click menu.
1608 Each entry is a list of (key menu-name function).
1609 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.")
1610
1611
1612 (defvar org-ref-user-cite-menu-funcs
1613   '(("C" "rossref" org-ref-crossref-at-point)
1614     ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1615     ("s" "Copy summary" org-ref-copy-entry-as-summary))
1616   "User-defined functions to run on bibtex key at point.")
1617
1618
1619 (defun org-ref-copy-entry-as-summary ()
1620   "Copy the bibtex entry for the citation at point as a summary."
1621   (interactive)
1622     (save-window-excursion
1623       (org-ref-open-citation-at-point)
1624       (kill-new (org-ref-bib-citation))))
1625
1626
1627 (defun org-ref-copy-entry-at-point-to-file ()
1628   "Copy the bibtex entry for the citation at point to NEW-FILE.
1629 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."
1630   (interactive)
1631   (let ((new-file (ido-completing-read
1632                    "Copy to bibfile: "
1633                    (append org-ref-default-bibliography
1634                            (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1635         (key (org-ref-get-bibtex-key-under-cursor)))
1636     (save-window-excursion
1637       (org-ref-open-citation-at-point)
1638       (bibtex-copy-entry-as-kill))
1639
1640     (let ((bibtex-files (list (file-truename new-file))))
1641       (if (assoc key (bibtex-global-key-alist))
1642           (message "That key already exists in %s" new-file)
1643         ;; add to file
1644         (save-window-excursion
1645           (find-file new-file)
1646           (goto-char (point-max))
1647           ;; make sure we are at the beginning of a line.
1648           (unless (looking-at "^") (insert "\n\n"))
1649           (bibtex-yank)
1650           (save-buffer))))))
1651
1652
1653 (defun org-ref-get-doi-at-point ()
1654   "Get doi for key at point."
1655   (let* ((results (org-ref-get-bibtex-key-and-file))
1656          (key (car results))
1657          (bibfile (cdr results))
1658          doi)
1659     (save-excursion
1660       (with-temp-buffer
1661         (insert-file-contents bibfile)
1662         (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1663         (bibtex-search-entry key)
1664         (setq doi (bibtex-autokey-get-field "doi"))
1665         ;; in case doi is a url, remove the url part.
1666         (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1667
1668
1669 ;; **** functions that operate on key at point for click menu
1670 (defun org-ref-wos-at-point ()
1671   "Open the doi in wos for bibtex key under point."
1672   (interactive)
1673   (doi-utils-wos (org-ref-get-doi-at-point)))
1674
1675
1676 (defun org-ref-wos-citing-at-point ()
1677   "Open the doi in wos citing articles for bibtex key under point."
1678   (interactive)
1679   (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1680
1681
1682 (defun org-ref-wos-related-at-point ()
1683   "Open the doi in wos related articles for bibtex key under point."
1684   (interactive)
1685   (doi-utils-wos-related (org-ref-get-doi-at-point)))
1686
1687
1688 (defun org-ref-google-scholar-at-point ()
1689   "Open the doi in google scholar for bibtex key under point."
1690   (interactive)
1691   (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1692
1693
1694 (defun org-ref-pubmed-at-point ()
1695   "Open the doi in pubmed for bibtex key under point."
1696   (interactive)
1697   (doi-utils-pubmed (org-ref-get-doi-at-point)))
1698
1699
1700 (defun org-ref-crossref-at-point ()
1701   "Open the doi in crossref for bibtex key under point."
1702   (interactive)
1703   (doi-utils-crossref (org-ref-get-doi-at-point)))
1704
1705 ;; *** Minibuffer menu
1706
1707 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1708   "Action when a cite link is clicked on.
1709 Provides a menu of context sensitive actions.  If the bibtex entry
1710 has a pdf, you get an option to open it.  If there is a doi, you
1711 get a lot of options.  LINK-STRING is used by the link function."
1712   (interactive)
1713   (let* ((results (org-ref-get-bibtex-key-and-file))
1714          (key (car results))
1715          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1716          (bibfile (cdr results))
1717          (url (save-excursion
1718                 (with-temp-buffer
1719                   (insert-file-contents bibfile)
1720                   (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1721                   (bibtex-search-entry key)
1722                   (bibtex-autokey-get-field "url"))))
1723          (doi (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                   ;; I like this better than bibtex-url which does not always find
1729                   ;; the urls
1730                   (bibtex-autokey-get-field "doi")))))
1731
1732     (when (string= "" doi) (setq doi nil))
1733     (when (string= "" url) (setq url nil))
1734     (setq org-ref-cite-menu-funcs '())
1735
1736     ;; open action
1737     (when
1738         bibfile
1739       (add-to-list
1740        'org-ref-cite-menu-funcs
1741        '("o" "pen" org-ref-open-citation-at-point)))
1742
1743     ;; pdf
1744     (when (file-exists-p pdf-file)
1745       (add-to-list
1746        'org-ref-cite-menu-funcs
1747        `("p" "df" ,org-ref-open-pdf-function) t))
1748
1749     ;; notes
1750     (add-to-list
1751      'org-ref-cite-menu-funcs
1752      '("n" "otes" org-ref-open-notes-at-point) t)
1753
1754     ;; url
1755     (when (or url doi)
1756       (add-to-list
1757        'org-ref-cite-menu-funcs
1758        '("u" "rl" org-ref-open-url-at-point) t))
1759
1760     ;; doi funcs
1761     (when doi
1762       (add-to-list
1763        'org-ref-cite-menu-funcs
1764        '("w" "os" org-ref-wos-at-point) t)
1765
1766       (add-to-list
1767        'org-ref-cite-menu-funcs
1768        '("c" "iting" org-ref-wos-citing-at-point) t)
1769
1770       (add-to-list
1771        'org-ref-cite-menu-funcs
1772        '("r" "elated" org-ref-wos-related-at-point) t)
1773
1774       (add-to-list
1775        'org-ref-cite-menu-funcs
1776        '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1777
1778       (add-to-list
1779        'org-ref-cite-menu-funcs
1780        '("P" "ubmed" org-ref-pubmed-at-point) t))
1781
1782     ;; add user functions
1783     (dolist (tup org-ref-user-cite-menu-funcs)
1784       (add-to-list
1785        'org-ref-cite-menu-funcs
1786        tup t))
1787
1788     ;; finally quit
1789     (add-to-list
1790      'org-ref-cite-menu-funcs
1791      '("q" "uit" (lambda ())) t)
1792
1793     ;; now we make a menu
1794     ;; construct menu string as a message
1795     (message
1796      (concat
1797       (let* ((results (org-ref-get-bibtex-key-and-file))
1798              (key (car results))
1799              (bibfile (cdr results)))
1800         (save-excursion
1801           (with-temp-buffer
1802             (insert-file-contents bibfile)
1803             (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1804             (bibtex-search-entry key)
1805             (org-ref-bib-citation))))
1806       "\n"
1807       (mapconcat
1808        (lambda (tup)
1809          (concat "[" (elt tup 0) "]"
1810                  (elt tup 1) " "))
1811        org-ref-cite-menu-funcs "")))
1812     ;; get the input
1813     (let* ((input (read-char-exclusive))
1814            (choice (assoc
1815                     (char-to-string input) org-ref-cite-menu-funcs)))
1816       ;; now run the function (2nd element in choice)
1817       (when choice
1818         (funcall
1819          (elt
1820           choice
1821           2))))))
1822
1823 ;; *** Generation of the cite links
1824 (defmacro org-ref-make-completion-function (type)
1825   "Macro to make a link completion function for a link of TYPE."
1826   `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1827      (interactive)
1828      (format "%s:%s"
1829              ,type
1830              (completing-read
1831               "bibtex key: "
1832               (let ((bibtex-files (org-ref-find-bibliography)))
1833                 (bibtex-global-key-alist))))))
1834
1835 (defmacro org-ref-make-format-function (type)
1836   "Macro to make a format function for a link of TYPE."
1837   `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1838      (cond
1839       ((eq format 'org)
1840        (mapconcat
1841         (lambda (key)
1842           (format "[[#%s][%s]]" key key))
1843         (org-ref-split-and-strip-string keyword) ","))
1844
1845       ((eq format 'ascii)
1846        (concat "["
1847                (mapconcat
1848                 (lambda (key)
1849                   (format "%s" key))
1850                 (org-ref-split-and-strip-string keyword) ",") "]"))
1851
1852       ((eq format 'html)
1853        (mapconcat
1854         (lambda (key)
1855           (format "<a href=\"#%s\">%s</a>" key key))
1856         (org-ref-split-and-strip-string keyword) ","))
1857
1858       ((eq format 'latex)
1859        (if (string= (substring type -1) "s")
1860            ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1861            (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}"  key))
1862                                          (org-ref-split-and-strip-string keyword) ""))
1863          ;; bibtex format
1864        (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1865                (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1866                "}")))
1867       ;; for markdown we generate pandoc citations
1868       ((eq format 'md)
1869        (cond
1870         (desc  ;; pre and or post text
1871          (let* ((text (split-string desc "::"))
1872                 (pre (car text))
1873                 (post (cadr text)))
1874            (concat
1875             (format "[@%s," keyword)
1876             (when pre (format " %s" pre))
1877             (when post (format ", %s" post))
1878             "]")))
1879         (t
1880          (format "[%s]"
1881                  (mapconcat
1882                   (lambda (key) (concat "@" key))
1883                   (org-ref-split-and-strip-string keyword)
1884                   "; "))))))))
1885
1886 (defun org-ref-format-citation-description (desc)
1887   "Return formatted citation description.
1888 If the cite link has a DESC (description), it is optional text
1889 for the citation command.  You can specify pre and post text by
1890 separating these with ::, for example [[cite:key][pre text::post
1891 text]]."
1892   (cond
1893    ((string-match "::" desc)
1894     (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1895    (t (format "[%s]" desc))))
1896
1897 (defun org-ref-define-citation-link (type &optional key)
1898   "Add a citation link of TYPE for org-ref.
1899 With optional KEY, set the reftex binding. For example:
1900 \(org-ref-define-citation-link \"citez\" ?z) will create a new
1901 citez link, with reftex key of z, and the completion function."
1902   (interactive "sCitation Type: \ncKey: ")
1903
1904   ;; create the formatting function
1905   (eval `(org-ref-make-format-function ,type))
1906
1907   (eval-expression
1908    `(org-add-link-type
1909      ,type
1910      org-ref-cite-onclick-function
1911      (quote ,(intern (format "org-ref-format-%s" type)))))
1912
1913   ;; create the completion function
1914   (eval `(org-ref-make-completion-function ,type))
1915
1916   ;; store new type so it works with adding citations, which checks
1917   ;; for existence in this list
1918   (add-to-list 'org-ref-cite-types type)
1919
1920   ;; and finally if a key is specified, we modify the reftex menu
1921   (when key
1922     (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1923           (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1924                   `((,key  . ,(concat type ":%l")))))))
1925
1926 ;; create all the link types and their completion functions
1927 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1928
1929 (defun org-ref-insert-cite-link (alternative-cite)
1930   "Insert a default citation link using reftex.
1931 If you are on a link, it appends to the end of the link,
1932 otherwise, a new link is inserted.  Use a prefix
1933 arg (ALTERNATIVE-CITE) to get a menu of citation types."
1934   (interactive "P")
1935   (org-ref-find-bibliography)
1936   (let* ((object (org-element-context))
1937          (link-string-beginning (org-element-property :begin object))
1938          (link-string-end (org-element-property :end object))
1939          (path (org-element-property :path object)))
1940
1941     (if (not alternative-cite)
1942
1943         (cond
1944          ;; case where we are in a link
1945          ((and (equal (org-element-type object) 'link)
1946                (-contains? org-ref-cite-types (org-element-property :type object)))
1947           (goto-char link-string-end)
1948           ;; sometimes there are spaces at the end of the link
1949           ;; this code moves point pack until no spaces are there
1950           (while (looking-back " ") (backward-char))
1951           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1952
1953          ;; We are next to a link, and we want to append
1954          ((save-excursion
1955             (backward-char)
1956             (and (equal (org-element-type (org-element-context)) 'link)
1957                  (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1958           (while (looking-back " ") (backward-char))
1959           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1960
1961          ;; insert fresh link
1962          (t
1963           (insert
1964            (concat org-ref-default-citation-link
1965                    ":"
1966                    (mapconcat 'identity (reftex-citation t) ",")))))
1967
1968       ;; you pressed a C-u so we run this code
1969       (reftex-citation))))
1970
1971 (defun org-ref-insert-cite-with-completion (type)
1972   "Insert a cite link of TYPE with completion."
1973   (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1974   (insert (funcall (intern (format "org-%s-complete-link" type)))))
1975
1976 (defun org-ref-store-bibtex-entry-link ()
1977   "Save a citation link to the current bibtex entry.  Save in the default link type."
1978   (interactive)
1979   (let ((link (concat org-ref-default-citation-link
1980                  ":"
1981                  (save-excursion
1982                    (bibtex-beginning-of-entry)
1983                    (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1984     (message "saved %s" link)
1985     (push (list link) org-stored-links)
1986     (car org-stored-links)))
1987
1988 ;; ** Index link
1989 (org-add-link-type
1990  "index"
1991  (lambda (path)
1992    (occur path))
1993
1994  (lambda (path desc format)
1995    (cond
1996     ((eq format 'latex)
1997       (format "\\index{%s}" path)))))
1998
1999 ;; this will generate a temporary index of entries in the file.
2000 (org-add-link-type
2001  "printindex"
2002  (lambda (path)
2003    (let ((*index-links* '())
2004          (*initial-letters* '()))
2005
2006      ;; get links
2007      (org-element-map (org-element-parse-buffer) 'link
2008        (lambda (link)
2009          (let ((type (nth 0 link))
2010                (plist (nth 1 link)))
2011
2012            (when (equal (plist-get plist ':type) "index")
2013              (add-to-list
2014               '*index-links*
2015               (cons (plist-get plist :path)
2016                     (format
2017                      "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2018 (current-buffer)
2019                      (plist-get plist :begin)  ;; position of link
2020                      ;; grab a description
2021                      (save-excursion
2022                        (goto-char (plist-get plist :begin))
2023                        (if (thing-at-point 'sentence)
2024                            ;; get a sentence
2025                            (replace-regexp-in-string
2026                             "\n" "" (thing-at-point 'sentence))
2027                          ;; or call it a link
2028                          "link")))))))))
2029
2030      ;; sort the links
2031      (setq *index-links*  (cl-sort *index-links* 'string-lessp :key 'car))
2032
2033      ;; now first letters
2034      (dolist (link *index-links*)
2035        (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2036
2037      ;; now create the index
2038      (switch-to-buffer (get-buffer-create "*index*"))
2039      (org-mode)
2040      (erase-buffer)
2041      (insert "#+TITLE: Index\n\n")
2042      (dolist (letter *initial-letters*)
2043        (insert (format "* %s\n" (upcase letter)))
2044        ;; now process the links
2045        (while (and
2046                *index-links*
2047                (string= letter (substring (car (car *index-links*)) 0 1)))
2048          (let ((link (pop *index-links*)))
2049            (insert (format "%s %s\n\n" (car link) (cdr link))))))
2050      (switch-to-buffer "*index*")))
2051  ;; formatting
2052  (lambda (path desc format)
2053    (cond
2054     ((eq format 'latex)
2055       (format "\\printindex")))))
2056
2057 ;; ** Glossary link
2058 (org-add-link-type
2059  "newglossaryentry"
2060  nil ;; no follow action
2061  (lambda (path desc format)
2062    (cond
2063     ((eq format 'latex)
2064      (format "\\newglossaryentry{%s}{%s}" path desc)))))
2065
2066
2067 ;; link to entry
2068 (org-add-link-type
2069  "gls"
2070   nil ;; no follow action
2071  (lambda (path desc format)
2072    (cond
2073     ((eq format 'latex)
2074      (format "\\gls{%s}" path)))))
2075
2076 ;; plural
2077 (org-add-link-type
2078  "glspl"
2079   nil ;; no follow action
2080  (lambda (path desc format)
2081    (cond
2082     ((eq format 'latex)
2083      (format "\\glspl{%s}" path)))))
2084
2085 ;; capitalized link
2086 (org-add-link-type
2087  "Gls"
2088   nil ;; no follow action
2089  (lambda (path desc format)
2090    (cond
2091     ((eq format 'latex)
2092      (format "\\Gls{%s}" path)))))
2093
2094 ;; capitalized link
2095 (org-add-link-type
2096  "Glspl"
2097   nil ;; no follow action
2098  (lambda (path desc format)
2099    (cond
2100     ((eq format 'latex)
2101      (format "\\Glspl{%s}" path)))))
2102
2103 ;; * Utilities
2104 ;; ** create text citations from a bibtex entry
2105 (defun org-ref-bib-citation ()
2106   "From a bibtex entry, create and return a simple citation string.
2107 This assumes you are in an article."
2108   (bibtex-set-dialect nil t)
2109   (bibtex-beginning-of-entry)
2110   (let* ((cb (current-buffer))
2111          (bibtex-expand-strings t)
2112          (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2113                          collect (cons (downcase key) value)))
2114          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2115          (year  (reftex-get-bib-field "year" entry))
2116          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2117          (key (reftex-get-bib-field "=key=" entry))
2118          (journal (let ((jt (reftex-get-bib-field "journal" entry)))
2119                     (if (string= "" jt)
2120                         (reftex-get-bib-field "journaltitle" entry)
2121                       jt)))
2122          (volume (reftex-get-bib-field "volume" entry))
2123          (pages (reftex-get-bib-field "pages" entry))
2124          (doi (reftex-get-bib-field "doi" entry))
2125          (url (reftex-get-bib-field "url" entry))
2126          )
2127     ;;authors, "title", Journal, vol(iss):pages (year).
2128     (format "%s, \"%s\", %s, %s:%s (%s)"
2129             author title journal  volume pages year)))
2130
2131 (defun org-ref-bib-html-citation ()
2132   "From a bibtex entry, create and return a simple citation with html links."
2133   (bibtex-beginning-of-entry)
2134   (let* ((cb (current-buffer))
2135          (bibtex-expand-strings t)
2136          (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2137                          collect (cons (downcase key) value)))
2138          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2139          (year  (reftex-get-bib-field "year" entry))
2140          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2141          (key (reftex-get-bib-field "=key=" entry))
2142          (journal (reftex-get-bib-field "journal" entry))
2143          (volume (reftex-get-bib-field "volume" entry))
2144          (pages (reftex-get-bib-field "pages" entry))
2145          (doi (reftex-get-bib-field "doi" entry))
2146          (url (reftex-get-bib-field "url" entry)))
2147     ;;authors, "title", Journal, vol(iss):pages (year).
2148     (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2149                     author title journal  volume pages year)
2150             (when url (format " <a href=\"%s\">link</a>" url))
2151             (when doi
2152               (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))))
2153
2154 ;; ** Open pdf in bibtex entry
2155 (defun org-ref-open-bibtex-pdf ()
2156   "Open pdf for a bibtex entry, if it exists.
2157 assumes point is in
2158 the entry of interest in the bibfile.  but does not check that."
2159   (interactive)
2160   (save-excursion
2161     (bibtex-beginning-of-entry)
2162     (let* ((bibtex-expand-strings t)
2163            (entry (bibtex-parse-entry t))
2164            (key (reftex-get-bib-field "=key=" entry))
2165            (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2166       (message "%s" pdf)
2167       (if (file-exists-p pdf)
2168           (org-open-link-from-string (format "[[file:%s]]" pdf))
2169         (ding)))))
2170
2171 ;; ** Open notes from bibtex entry
2172
2173 (defun org-ref-open-bibtex-notes ()
2174   "From a bibtex entry, open the notes if they exist, and create a heading if they do not.
2175
2176 I never did figure out how to use reftex to make this happen
2177 non-interactively. the reftex-format-citation function did not
2178 work perfectly; there were carriage returns in the strings, and
2179 it did not put the key where it needed to be. so, below I replace
2180 the carriage returns and extra spaces with a single space and
2181 construct the heading by hand."
2182   (interactive)
2183
2184   (bibtex-beginning-of-entry)
2185   (let* ((cb (current-buffer))
2186          (bibtex-expand-strings t)
2187          (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2188                          collect (cons (downcase key) value)))
2189          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2190          (year  (reftex-get-bib-field "year" entry))
2191          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2192          (key (reftex-get-bib-field "=key=" entry))
2193          (journal (reftex-get-bib-field "journal" entry))
2194          (volume (reftex-get-bib-field "volume" entry))
2195          (pages (reftex-get-bib-field "pages" entry))
2196          (doi (reftex-get-bib-field "doi" entry))
2197          (url (reftex-get-bib-field "url" entry))
2198          )
2199
2200     ;; save key to clipboard to make saving pdf later easier by pasting.
2201     (with-temp-buffer
2202       (insert key)
2203       (kill-ring-save (point-min) (point-max)))
2204
2205     ;; now look for entry in the notes file
2206     (if  org-ref-bibliography-notes
2207         (find-file-other-window org-ref-bibliography-notes)
2208       (error "Org-ref-bib-bibliography-notes is not set to anything"))
2209
2210     (goto-char (point-min))
2211     ;; put new entry in notes if we don't find it.
2212     (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2213         (funcall org-ref-open-notes-function)
2214       ;; no entry found, so add one
2215       (insert (format "\n** TODO %s - %s" year title))
2216       (insert (format"
2217  :PROPERTIES:
2218   :Custom_ID: %s
2219   :AUTHOR: %s
2220   :JOURNAL: %s
2221   :YEAR: %s
2222   :VOLUME: %s
2223   :PAGES: %s
2224   :DOI: %s
2225   :URL: %s
2226  :END:
2227 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2228 key author journal year volume pages doi url 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