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