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