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