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