]> git.donarmstrong.com Git - org-ref.git/blobdiff - org-ref.el
make the example user function more functional.
[org-ref.git] / org-ref.el
index 939b8ee7102ee218574b0fac89f6616c3ec2177f..72b4b528d9741b8722b4377d751474e5f0b60542 100644 (file)
@@ -41,6 +41,7 @@
 (require 'helm-config)
 (require 'helm-bibtex)
 (require 'org)
+(require 'org-element)
 
 ;; * Custom variables
 (defgroup org-ref nil
@@ -81,15 +82,19 @@ You should use full-paths for each file."
   '(("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>.")
 
     ("book" . "%a, %t, %u (%y).")
-
+    ("techreport" . "%a, %t, %i, %u (%y).")
     ("proceedings" . "%e, %t in %S, %u (%y).")
-
     ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
-
   "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."
   :type 'string
   :group 'org-ref)
 
+(defcustom org-ref-note-title-format
+  "** TODO %y - %t"
+  "String to format the title of a note. See the `org-ref-reftex-format-citation' docstring for the escape codes."
+  :type 'string
+  :group 'org-ref)
+
 (defcustom org-ref-open-notes-function
   (lambda ()
     (org-show-entry)
@@ -106,11 +111,23 @@ You should use full-paths for each file."
 
 (defcustom org-ref-open-pdf-function
    'org-ref-open-pdf-at-point
-"User-defined function to open a pdf from a link.  The function must get the key at point, and derive a path to the pdf file, then open it.  The default function is `org-ref-open-pdf-at-point'."
+   "User-defined function to open a pdf from a link.  The
+function must get the key at point, and derive a path to the pdf
+file, then open it.  The default function is
+`org-ref-open-pdf-at-point'."
   :type 'function
   :group 'org-ref)
 
 
+(defcustom org-ref-get-pdf-filename-function
+  'org-ref-get-pdf-filename
+  "User-defined function to get a filename from a bibtex key.
+The function must take a key as an argument, and return the path
+to the corresponding filename. The default is
+`org-ref-get-pdf-filename'. An alternative value is
+`org-ref-get-mendeley-filename'.")
+
+
 (defcustom org-ref-insert-cite-function
   'org-ref-helm-insert-cite-link
   "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."
@@ -326,15 +343,15 @@ You will see a message in the minibuffer when on a cite, ref or label link."
                       (replace-regexp-in-string "\*" "\\\\*" x)
                       )
                     org-ref-cite-types "\\|") "\\)"
-  ":\\([a-zA-Z0-9-_:]*,?\\)*"))
+  ":\\([a-zA-Z0-9-_:\\./]*,?\\)*"))
 
 
-(setq org-ref-label-re
-      "label:\\([a-zA-Z0-9-_:]*,?\\)*")
+(defvar org-ref-label-re
+  "label:\\([a-zA-Z0-9-_:]*,?\\)*")
 
 
-(setq org-ref-ref-re
-      "\\(eq\\)?ref:\\([a-zA-Z0-9-_:]*,?\\)*")
+(defvar org-ref-ref-re
+  "\\(eq\\)?ref:\\([a-zA-Z0-9-_:]*,?\\)*")
 
 
 (defface org-ref-cite-face
@@ -423,7 +440,6 @@ Beware that all this only works with BibTeX database files.  When
 citations are made from the \bibitems in an explicit thebibliography
 environment, only %l is available."
   ;; Format a citation from the info in the BibTeX ENTRY
-
   (unless (stringp format) (setq format "\\cite{%l}"))
 
   (if (and reftex-comment-citations
@@ -444,10 +460,14 @@ environment, only %l is available."
                           (if reftex-comment-citations
                               reftex-cite-comment-format
                             "")))
-               ((= l ?a) (reftex-format-names
-                          (reftex-get-bib-names "author" entry)
-                          (or n 2)))
-               ((= l ?A) (car (reftex-get-bib-names "author" entry)))
+               ((= l ?a) (replace-regexp-in-string
+                          "\n\\|\t\\|\s+" " "
+                          (reftex-format-names
+                           (reftex-get-bib-names "author" entry)
+                           (or n 2))))
+               ((= l ?A) (replace-regexp-in-string
+                          "\n\\|\t\\|\s+" " "
+                          (car (reftex-get-bib-names "author" entry))))
                ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
                ((= l ?B) (reftex-abbreviate-title
                           (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
@@ -460,8 +480,11 @@ environment, only %l is available."
                ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
                ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
                ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
-               ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
-               ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
+               ((= l ?j) (let ((jt (reftex-get-bib-field "journal" entry)))
+                           (if (string= "" jt)
+                               (reftex-get-bib-field "journaltitle" entry)
+                             jt)))
+               ((= l ?k) (org-ref-reftex-get-bib-field "=key=" entry))
                ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
                ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
                ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
@@ -475,9 +498,13 @@ environment, only %l is available."
                ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
                ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
               ;; strip enclosing brackets from title if they are there
-               ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
-               ((= l ?T) (reftex-abbreviate-title
+               ((= l ?t) (replace-regexp-in-string
+                          "\n\\|\t\\|\s+" " "
                           (org-ref-reftex-get-bib-field "title" entry)))
+               ((= l ?T) (reftex-abbreviate-title
+                          ((replace-regexp-in-string
+                            "\n\\|\t\\|\s+" " "
+                            (org-ref-reftex-get-bib-field "title" entry)))))
                ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
                ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
 
@@ -489,8 +516,6 @@ environment, only %l is available."
     (setq format (replace-match "%" t t format)))
   (while (string-match "[ ,.;:]*%<" format)
     (setq format (replace-match "" t t format)))
-  ;; also replace carriage returns, tabs, and multiple whitespaces
-  (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
   format)
 
 (defun org-ref-get-bibtex-entry-citation (key)
@@ -501,19 +526,25 @@ Format according to the type in `org-ref-bibliography-entry-format'."
        (file) (entry) (bibtex-entry) (entry-type) (format))
 
     (setq file (catch 'result
-                (loop for file in org-ref-bibliography-files do
-                      (if (org-ref-key-in-file-p key (file-truename file))
-                          (throw 'result file)
-                        (message "%s not found in %s" key (file-truename file))))))
+                (cl-loop for file in org-ref-bibliography-files do
+                         (if (org-ref-key-in-file-p key (file-truename file))
+                             (throw 'result file)
+                           (message "%s not found in %s"
+                                    key (file-truename file))))))
 
     (with-temp-buffer
       (insert-file-contents file)
+      (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
       (bibtex-search-entry key nil 0)
       (setq bibtex-entry (bibtex-parse-entry))
+      ;; downcase field names so they work in the format-citation code
+      (dolist (cons-cell bibtex-entry)
+       (setf (car cons-cell) (downcase (car cons-cell))))
       (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
       (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
       (if format
          (setq entry  (org-ref-reftex-format-citation bibtex-entry format))
+       ;; if no format, we use the bibtex entry itself as a fallback
        (save-restriction
          (bibtex-narrow-to-entry)
          (setq entry (buffer-string)))))
@@ -539,8 +570,22 @@ Format according to the type in `org-ref-bibliography-entry-format'."
 
 (defun org-ref-get-bibtex-entry-html (key)
   "Return an html string for the bibliography entry corresponding to KEY."
-
-  (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
+  (let ((output))
+    (setq output (org-ref-get-bibtex-entry-citation key))
+    ;; unescape the &
+    (setq output (replace-regexp-in-string "\\\\&" "&" output))
+    ;; hack to replace {} around text
+    (setq output (replace-regexp-in-string "{" "" output))
+    (setq output (replace-regexp-in-string "}" "" output))
+    ;; get rid of empty parens
+    (setq output (replace-regexp-in-string "()" "" output))
+    ;; get rid of empty link and doi
+    (setq output (replace-regexp-in-string " <a href=\"\">link</a>\\." "" output))
+    ;; change double dash to single dash
+    (setq output (replace-regexp-in-string "--" "-" output))
+    (setq output (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" output))
+    (format "<li><a id=\"%s\">[%s] %s</a></li>"
+           key key output)))
 
 (defun org-ref-get-html-bibliography ()
   "Create an html bibliography when there are keys."
@@ -557,13 +602,14 @@ Format according to the type in `org-ref-bibliography-entry-format'."
        (file) (entry) (bibtex-entry) (entry-type) (format))
 
     (setq file (catch 'result
-                (loop for file in org-ref-bibliography-files do
+                (cl-loop for file in org-ref-bibliography-files do
                       (if (org-ref-key-in-file-p key (file-truename file))
                           (throw 'result file)
                         (message "%s not found in %s" key (file-truename file))))))
 
     (with-temp-buffer
       (insert-file-contents file)
+      (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
       (bibtex-search-entry key nil 0)
       (setq entry (bibtex-parse-entry))
       (format "** %s - %s
@@ -611,45 +657,54 @@ Format according to the type in `org-ref-bibliography-entry-format'."
                   ;; may contain multiple files. this code finds the
                   ;; one you clicked on and opens it.
                   (lambda (link-string)
-                      ;; get link-string boundaries
-                      ;; we have to go to the beginning of the line, and then search forward
-
+                      ;; get link-string boundaries we have to go to the
+                      ;; beginning of the line, and then search forward
                     (let* ((bibfile)
                            ;; object is the link you clicked on
                            (object (org-element-context))
                            (link-string-beginning)
-                           (link-string-end))
-
+                           (link-string-end)
+                           (cp (point)))
                     (save-excursion
                       (goto-char (org-element-property :begin object))
                       (search-forward link-string nil nil 1)
                       (setq link-string-beginning (match-beginning 0))
                       (setq link-string-end (match-end 0)))
 
-                      ;; We set the reftex-default-bibliography
-                      ;; here. it should be a local variable only in
-                      ;; the current buffer. We need this for using
-                      ;; reftex to do citations.
-                      (set (make-local-variable 'reftex-default-bibliography)
-                           (split-string (org-element-property :path object) ","))
-
+                    ;; Make sure point is in the link-path.
+                    (if (< cp link-string-beginning)
+                        (goto-char link-string-beginning))
+                    ;; We set the reftex-default-bibliography
+                    ;; here. it should be a local variable only in
+                    ;; the current buffer. We need this for using
+                    ;; reftex to do citations.
+                    (set (make-local-variable 'reftex-default-bibliography)
+                         (split-string
+                          (org-element-property :path object) ","))
+
+                    (let (key-beginning key-end)
                       ;; now if we have comma separated bibliographies
                       ;; we find the one clicked on. we want to
                       ;; search forward to next comma from point
                       (save-excursion
                         (if (search-forward "," link-string-end 1 1)
-                            (setq key-end (- (match-end 0) 1)) ; we found a match
-                          (setq key-end (point)))) ; no comma found so take the point
+                            ;; we found a match
+                            (setq key-end (- (match-end 0) 1))
+                          ;; no comma found so take the point
+                          (setq key-end (point))))
                       ;; and backward to previous comma from point
                       (save-excursion
                         (if (search-backward "," link-string-beginning 1 1)
-                            (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
+                            ;; we found a match
+                            (setq key-beginning (+ (match-beginning 0) 1))
                           (setq key-beginning (point)))) ; no match found
                       ;; save the key we clicked on.
-                      (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
-                      (find-file bibfile))) ; open file on click
+                      (setq bibfile (org-ref-strip-string
+                                     (buffer-substring key-beginning key-end)))
+                      ;; open file on click
+                      (find-file bibfile))))
 
-                    ;; formatting code
+                  ;; formatting code
                   (lambda (keyword desc format)
                     (cond
                      ((eq format 'org) (org-ref-get-org-bibliography))
@@ -657,10 +712,14 @@ Format according to the type in `org-ref-bibliography-entry-format'."
                      ((eq format 'html) (org-ref-get-html-bibliography))
                      ((eq format 'latex)
                       ;; write out the latex bibliography command
-                      (format "\\bibliography{%s}" (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
-                                                                                                     (mapcar 'expand-file-name
-                                                                                                             (split-string keyword ","))
-                                                                                                     ",")))))))
+                      (format "\\bibliography{%s}"
+                              (replace-regexp-in-string
+                               "\\.bib" ""
+                               (mapconcat
+                                'identity
+                                (mapcar 'expand-file-name
+                                        (split-string keyword ","))
+                                ",")))))))
 
 (org-add-link-type "nobibliography"
                   ;; this code is run on clicking. The bibliography
@@ -690,21 +749,22 @@ Format according to the type in `org-ref-bibliography-entry-format'."
                       (set (make-local-variable 'reftex-default-bibliography)
                            (split-string (org-element-property :path object) ","))
 
-                      ;; now if we have comma separated bibliographies
-                      ;; we find the one clicked on. we want to
-                      ;; search forward to next comma from point
-                      (save-excursion
-                        (if (search-forward "," link-string-end 1 1)
-                            (setq key-end (- (match-end 0) 1)) ; we found a match
-                          (setq key-end (point)))) ; no comma found so take the point
-                      ;; and backward to previous comma from point
-                      (save-excursion
-                        (if (search-backward "," link-string-beginning 1 1)
-                            (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
-                          (setq key-beginning (point)))) ; no match found
-                      ;; save the key we clicked on.
-                      (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
-                      (find-file bibfile))) ; open file on click
+                      (let (key-beginning key-end)
+                        ;; now if we have comma separated bibliographies
+                        ;; we find the one clicked on. we want to
+                        ;; search forward to next comma from point
+                        (save-excursion
+                          (if (search-forward "," link-string-end 1 1)
+                              (setq key-end (- (match-end 0) 1)) ; we found a match
+                            (setq key-end (point)))) ; no comma found so take the point
+                        ;; and backward to previous comma from point
+                        (save-excursion
+                          (if (search-backward "," link-string-beginning 1 1)
+                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
+                            (setq key-beginning (point)))) ; no match found
+                        ;; save the key we clicked on.
+                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
+                        (find-file bibfile)))) ; open file on click
 
                     ;; formatting code
                   (lambda (keyword desc format)
@@ -714,20 +774,11 @@ Format according to the type in `org-ref-bibliography-entry-format'."
                      ((eq format 'html) (org-ref-get-html-bibliography))
                      ((eq format 'latex)
                       ;; write out the latex bibliography command
-
-;                     (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
-;                             (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
-;                                                                               (mapcar 'expand-file-name
-;                                                                                       (split-string keyword ","))
-;                                                                               ",")))
-
                       (format "\\nobibliography{%s}"
                               (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
                                                                                 (mapcar 'expand-file-name
                                                                                         (split-string keyword ","))
-                                                                                ",")))
-
-                      ))))
+                                                                                ",")))))))
 
 (org-add-link-type "printbibliography"
                   (lambda (arg) (message "Nothing implemented for clicking here."))
@@ -737,8 +788,7 @@ Format according to the type in `org-ref-bibliography-entry-format'."
                       ((eq format 'html) (org-ref-get-html-bibliography))
                      ((eq format 'latex)
                       ;; write out the biblatex bibliography command
-                      "\\printbibliography"))
-))
+                      "\\printbibliography"))))
 
 (org-add-link-type "bibliographystyle"
                   (lambda (arg) (message "Nothing implemented for clicking here."))
@@ -746,13 +796,31 @@ Format according to the type in `org-ref-bibliography-entry-format'."
                     (cond
                      ((eq format 'latex)
                       ;; write out the latex bibliography command
-                      (format "\\bibliographystyle{%s}" keyword)))))
+                      (format "\\bibliographystyle{%s}" keyword))
+                     ;; Other styles should not have an output for this
+                     (t
+                      ""))))
+
+
+(defun org-bibliographystyle-complete-link (&optional arg)
+  "Completion function for bibliographystyle link.
+ARG does nothing."
+  (format "bibliographystyle:%s" (ido-completing-read
+                                 "style: "
+                                 '("unsrt" "plain" "alpha"
+                                   ;; natbib
+                                   ;; https://www.sharelatex.com/learn/Natbib_bibliography_styles
+                                   "dinat" "humannat" "plainnat"
+                                   "abbrnat" "unsrtnat" "rusnat"
+                                   "ksfhnat"))))
+
 
 (defun org-bibliography-complete-link (&optional arg)
   "Completion function for bibliography link.
 ARG does nothing."
   (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
 
+
 (defun org-ref-insert-bibliography-link ()
   "Insert a bibliography with completion."
   (interactive)
@@ -788,21 +856,22 @@ ARG does nothing."
                       (set (make-local-variable 'reftex-default-addbibresource)
                            (split-string (org-element-property :path object) ","))
 
-                      ;; now if we have comma separated bibliographies
-                      ;; we find the one clicked on. we want to
-                      ;; search forward to next comma from point
-                      (save-excursion
-                        (if (search-forward "," link-string-end 1 1)
-                            (setq key-end (- (match-end 0) 1)) ; we found a match
-                          (setq key-end (point)))) ; no comma found so take the point
-                      ;; and backward to previous comma from point
-                      (save-excursion
-                        (if (search-backward "," link-string-beginning 1 1)
-                            (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
-                          (setq key-beginning (point)))) ; no match found
-                      ;; save the key we clicked on.
-                      (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
-                      (find-file bibfile))) ; open file on click
+                      (let (key-beginning key-end)
+                        ;; now if we have comma separated bibliographies
+                        ;; we find the one clicked on. we want to
+                        ;; search forward to next comma from point
+                        (save-excursion
+                          (if (search-forward "," link-string-end 1 1)
+                              (setq key-end (- (match-end 0) 1)) ; we found a match
+                            (setq key-end (point)))) ; no comma found so take the point
+                        ;; and backward to previous comma from point
+                        (save-excursion
+                          (if (search-backward "," link-string-beginning 1 1)
+                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
+                            (setq key-beginning (point)))) ; no match found
+                        ;; save the key we clicked on.
+                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
+                        (find-file bibfile)))) ; open file on click
 
                     ;; formatting code
                   (lambda (keyword desc format)
@@ -829,11 +898,11 @@ ARG does nothing."
                       (string-match-p
                        "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
                        (org-element-property :path link)))
-               (incf counter)
+               (cl-incf counter)
 
                (let* ((start (org-element-property :begin link))
                       (parent (car (cdr (org-element-property :parent link))))
-                      (caption (caaar (plist-get parent :caption)))
+                      (caption (cl-caaar (plist-get parent :caption)))
                       (name (plist-get parent :name)))
                  (if caption
                      (format
@@ -872,10 +941,10 @@ ARG does nothing."
          (org-element-map (org-element-parse-buffer 'element) 'table
            (lambda (table)
              "create a link for to the table"
-             (incf counter)
+             (cl-incf counter)
              (let ((start (org-element-property :begin table))
                    (name  (org-element-property :name table))
-                   (caption (caaar (org-element-property :caption table))))
+                   (caption (cl-caaar (org-element-property :caption table))))
                (if caption
                    (format
                     "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
@@ -900,6 +969,8 @@ ARG does nothing."
     ((eq format 'latex)
      (format "\\listoftables")))))
 
+
+;; ** label link
 (defun org-ref-count-labels (label)
   "Counts number of matches for LABEL in the document."
   (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
@@ -916,7 +987,6 @@ ARG does nothing."
            (setq custom-id-count (+ 1 custom-id-count)))))
        custom-id-count)))
 
-;; ** label link
 (org-add-link-type
  "label"
  (lambda (label)
@@ -931,7 +1001,7 @@ ARG does nothing."
                    (org-ref-count-labels label))))
  (lambda (keyword desc format)
    (cond
-    ((eq format 'html) (format "(<label>%s</label>)" path))
+    ((eq format 'html) (format "<div id=\"%s\">" keyword))
     ((eq format 'latex)
      (format "\\label{%s}" keyword)))))
 
@@ -951,21 +1021,21 @@ ARG does nothing."
        :type "ref"
        :link (concat "ref:" (org-element-property :name object))))
 
-;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
     ;; store link on heading with custom_id
-;    (when (and (equal (org-element-type object) 'headline)
-;             (org-entry-get (point) "CUSTOM_ID"))
-;      (org-store-link-props
-;       :type "ref"
-;       :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
+    ;; this is not a ref link, but it is still what you want
+    (when (and (equal (org-element-type object) 'headline)
+              (org-entry-get (point) "CUSTOM_ID"))
+      (org-store-link-props
+       :type "custom_id"
+       :link (format "[[#%s]]" (org-entry-get (point) "CUSTOM_ID"))))
 
     ;; and to #+label: lines
+
     (when (and (equal (org-element-type object) 'paragraph)
               (org-element-property :name object))
       (org-store-link-props
        :type "ref"
-       :link (concat "ref:" (org-element-property :name object))))
-))
+       :link (concat "ref:" (org-element-property :name object))))))
 
 (add-hook 'org-store-link-functions 'org-label-store-link)
 
@@ -976,10 +1046,8 @@ ARG does nothing."
    "on clicking goto the label. Navigate back with C-c &"
    (org-mark-ring-push)
    ;; next search from beginning of the buffer
-
    ;; it is possible you would not find the label if narrowing is in effect
    (widen)
-
    (unless
        (or
        ;; our label links
@@ -995,20 +1063,15 @@ ARG does nothing."
        ;; #+label: name  org-definition
        (progn
          (goto-char (point-min))
-         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
+         (re-search-forward
+          (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
 
        ;; org tblname
        (progn
          (goto-char (point-min))
-         (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
-
-;; Commented out because these ref links do not actually translate correctly in LaTeX.
-;; you need [[#label]] links.
-       ;; CUSTOM_ID
-;      (progn
-;        (goto-char (point-min))
-;        (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
-       )
+         (re-search-forward
+          (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
+
      ;; we did not find anything, so go back to where we came
      (org-mark-ring-goto)
      (error "%s not found" label))
@@ -1017,18 +1080,24 @@ ARG does nothing."
  ;formatting
  (lambda (keyword desc format)
    (cond
-    ((eq format 'html) (format "(<ref>%s</ref>)" path))
+    ((eq format 'html) (format "<a href=\"#%s\">%s</a>" keyword keyword))
     ((eq format 'latex)
      (format "\\ref{%s}" keyword)))))
 
+
 (defun org-ref-get-org-labels ()
  "Return a list of #+LABEL: labels."
   (save-excursion
     (goto-char (point-min))
     (let ((matches '()))
       (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
-       (add-to-list 'matches (match-string-no-properties 1) t))
-matches)))
+       ;; do not do this for tables. We get those in `org-ref-get-tblnames'.
+       ;; who would have thought you have save match data here? Trust me. When
+       ;; I wrote this, you did.
+       (unless (save-match-data  (equal (car (org-element-at-point)) 'table))
+         (add-to-list 'matches (match-string-no-properties 1) t)))
+      matches)))
+
 
 (defun org-ref-get-custom-ids ()
  "Return a list of custom_id properties in the buffer."
@@ -1038,7 +1107,8 @@ matches)))
       (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
        (when (not (null custom_id))
          (setq results (append results (list custom_id)))))))
-results))
+   results))
+
 
 (defun org-ref-get-latex-labels ()
   "Return list of matchin LaTeX defined labels in buffer."
@@ -1047,7 +1117,8 @@ results))
     (let ((matches '()))
       (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
        (add-to-list 'matches (match-string-no-properties 1) t))
-matches)))
+      matches)))
+
 
 (defun org-ref-get-tblnames ()
   "Return list of table names in the buffer."
@@ -1055,6 +1126,7 @@ matches)))
     (lambda (table)
       (org-element-property :name table))))
 
+
 (defun org-ref-get-labels ()
   "Return a list of labels in the buffer that you can make a ref link to.
 This is used to complete ref links and in helm menus."
@@ -1063,15 +1135,22 @@ This is used to complete ref links and in helm menus."
       (widen)
       (goto-char (point-min))
       (let ((matches '()))
-        ;; these are the label:stuff  kinds
-       (while (re-search-forward "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
+        ;; these are the org-ref label:stuff  kinds
+       (while (re-search-forward
+               "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
          (add-to-list 'matches (match-string-no-properties 1) t))
+       ;; now add all the other kinds of labels.
        (append matches
+               ;; #+label:
                (org-ref-get-org-labels)
+               ;; \label{}
                (org-ref-get-latex-labels)
+               ;; #+tblname: and actually #+label
                (org-ref-get-tblnames)
+               ;; CUSTOM_IDs
                (org-ref-get-custom-ids))))))
 
+
 (defun org-ref-helm-insert-label-link ()
   "Insert a label link. helm just shows you what labels already exist.
 If you are on a label link, replace it."
@@ -1083,7 +1162,8 @@ If you are on a label link, replace it."
                      ;; default action is to open to the label
                      (action . (lambda (label)
                                  ;; unfortunately I do not have markers here
-                                 (org-open-link-from-string (format "ref:%s" label))))
+                                 (org-open-link-from-string
+                                  (format "ref:%s" label))))
                      ;; if you select a label, replace current one
                      (action . (lambda (label)
                                  (switch-to-buffer ,cb)
@@ -1145,6 +1225,7 @@ If you are on a label link, replace it."
                                         (or label
                                             helm-pattern))))))))))))
 
+
 (defun org-ref-complete-link (&optional arg)
   "Completion function for ref links.
 Optional argument ARG Does nothing."
@@ -1152,11 +1233,13 @@ Optional argument ARG Does nothing."
     (setq label (completing-read "label: " (org-ref-get-labels)))
     (format "ref:%s" label)))
 
+
 (defun org-ref-insert-ref-link ()
   "Completion function for a ref link."
  (interactive)
  (insert (org-ref-complete-link)))
 
+
 (defun org-ref-helm-insert-ref-link ()
   "Helm menu to insert ref links to labels in the document.
 If you are on link, replace with newly selected label.
@@ -1172,19 +1255,19 @@ Use C-u C-u to insert a [[#custom-id]] link"
 
     (helm :input (thing-at-point 'word)
          :sources `(((name . "Available labels to ref")
-                     (candidates . ,(loop for label in labels
-                                          for context in contexts
-                                          ;; we do some kludgy adding spaces
-                                          ;; and bars to make it "easier" to
-                                          ;; see in helm.
-                                          collect (cons (concat
-                                                         label "\n"
-                                                         (mapconcat
-                                                          (lambda (x)
-                                                            (concat "   |" x))
-                                                          (split-string context "\n")
-                                                          "\n"
-                                                          ) "\n\n") label)))
+                     (candidates . ,(cl-loop for label in labels
+                                             for context in contexts
+                                             ;; we do some kludgy adding spaces
+                                             ;; and bars to make it "easier" to
+                                             ;; see in helm.
+                                             collect (cons (concat
+                                                            label "\n"
+                                                            (mapconcat
+                                                             (lambda (x)
+                                                               (concat "   |" x))
+                                                             (split-string context "\n")
+                                                             "\n"
+                                                             ) "\n\n") label)))
                      ;; default action to replace or insert ref link.
                      (action . (lambda (label)
                                  (switch-to-buffer ,cb)
@@ -1255,20 +1338,14 @@ Use C-u C-u to insert a [[#custom-id]] link"
        ;; #+label: name  org-definition
        (progn
          (goto-char (point-min))
-         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
+         (re-search-forward
+          (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
 
        ;; org tblname
        (progn
          (goto-char (point-min))
-         (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
-
-;; Commented out because these ref links do not actually translate correctly in LaTeX.
-;; you need [[#label]] links.
-       ;; CUSTOM_ID
-;      (progn
-;        (goto-char (point-min))
-;        (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
-       )
+         (re-search-forward
+          (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
      ;; we did not find anything, so go back to where we came
      (org-mark-ring-goto)
      (error "%s not found" label))
@@ -1280,6 +1357,7 @@ Use C-u C-u to insert a [[#custom-id]] link"
     ((eq format 'latex)
      (format "\\pageref{%s}" keyword)))))
 
+
 (defun org-pageref-complete-link (&optional arg)
   "Completion function for ref links.
 Optional argument ARG Does nothing."
@@ -1287,11 +1365,13 @@ Optional argument ARG Does nothing."
     (setq label (completing-read "label: " (org-ref-get-labels)))
     (format "ref:%s" label)))
 
+
 (defun org-pageref-insert-ref-link ()
   "Insert a pageref link with completion."
  (interactive)
  (insert (org-pageref-complete-link)))
 
+
 ;; *** nameref link
 (org-add-link-type
  "nameref"
@@ -1343,9 +1423,10 @@ Optional argument ARG Does nothing."
  ;formatting
  (lambda (keyword desc format)
    (cond
-    ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
-    ((eq format 'latex)
-     (format "\\eqref{%s}" keyword)))))
+    ((eq format 'latex) (format "\\eqref{%s}" keyword))
+    ;;considering the fact that latex's the standard of math formulas, just use mathjax to render the html
+    ;;customize the variable 'org-html-mathjax-template' and 'org-html-mathjax-options' refering to  'autonumber'
+    ((eq format 'html) (format "\\eqref{%s}" keyword)))))
 
 ;; ** cite link
 
@@ -1371,26 +1452,30 @@ keyword we clicked on.  We also strip the text properties."
        ;; this means no description in the link
        (progn
          ;; we need the link path start and end
-         (save-excursion
-           (goto-char (org-element-property :begin object))
-           (search-forward link-string nil nil 1)
-           (setq link-string-beginning (match-beginning 0))
-           (setq link-string-end (match-end 0)))
+         (let (link-string-beginning link-string-end)
+           (save-excursion
+             (goto-char (org-element-property :begin object))
+             (search-forward link-string nil nil 1)
+             (setq link-string-beginning (match-beginning 0))
+             (setq link-string-end (match-end 0)))
 
-         ;; The key is the text between commas, or the link boundaries
-         (save-excursion
-           (if (search-forward "," link-string-end t 1)
-               (setq key-end (- (match-end 0) 1)) ; we found a match
-             (setq key-end link-string-end))) ; no comma found so take the end
-         ;; and backward to previous comma from point which defines the start character
-         (save-excursion
-           (if (search-backward "," link-string-beginning 1 1)
-               (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
-             (setq key-beginning link-string-beginning))) ; no match found
-         ;; save the key we clicked on.
-         (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
-         (set-text-properties 0 (length bibtex-key) nil bibtex-key)
-         bibtex-key)
+           (let (key-beginning key-end)
+             ;; The key is the text between commas, or the link boundaries
+             (save-excursion
+               (if (search-forward "," link-string-end t 1)
+                   (setq key-end (- (match-end 0) 1)) ; we found a match
+                 (setq key-end link-string-end))) ; no comma found so take the end
+             ;; and backward to previous comma from point which defines the start character
+             (save-excursion
+               (if (search-backward "," link-string-beginning 1 1)
+                   (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
+                 (setq key-beginning link-string-beginning))) ; no match found
+             ;; save the key we clicked on.
+             (let ((bibtex-key
+                    (org-ref-strip-string
+                     (buffer-substring key-beginning key-end))))
+               (set-text-properties 0 (length bibtex-key) nil bibtex-key)
+               bibtex-key))))
       ;; link with description. assume only one key
       link-string)))
 
@@ -1457,19 +1542,44 @@ falling back to what the user has set in `org-ref-default-bibliography'"
    (unless key
      (setq key (org-ref-get-bibtex-key-under-cursor)))
    (setq file     (catch 'result
-                   (loop for file in org-ref-bibliography-files do
-                         (if (org-ref-key-in-file-p key (file-truename file))
-                             (throw 'result file)))))
+                   (cl-loop for file in org-ref-bibliography-files do
+                            (if (org-ref-key-in-file-p key (file-truename file))
+                                (throw 'result file)))))
    (cons key file)))
 
 ;; *** key at point functions
 
+(defun org-ref-get-pdf-filename (key)
+  "Return the pdf filename associated with a bibtex KEY."
+  (format (concat org-ref-pdf-directory "%s.pdf") key))
+
+
+(defun org-ref-get-mendeley-filename (key)
+  "Return the pdf filename indicated by mendeley file field.
+Falls back to org-ref-get-pdf-filename if file filed does not exist.
+Contributed by https://github.com/autosquid."
+  (let* ((results (org-ref-get-bibtex-key-and-file key))
+        (bibfile (cdr results)))
+    (with-temp-buffer
+      (insert-file-contents bibfile)
+      (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
+      (bibtex-search-entry key nil 0)
+      (setq entry (bibtex-parse-entry))
+      (let ((e (org-ref-reftex-get-bib-field "file" entry)))
+       (if (> (length e) 4)
+           (remove-if
+            (lambda (ch)
+              (find ch "{}\\"))
+            (format "/%s" (subseq e 1 (- (length e) 4))))
+         (format (concat org-ref-pdf-directory "%s.pdf") key))))))
+
+
 (defun org-ref-open-pdf-at-point ()
   "Open the pdf for bibtex key under point if it exists."
   (interactive)
   (let* ((results (org-ref-get-bibtex-key-and-file))
         (key (car results))
-         (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
+         (pdf-file (funcall org-ref-get-pdf-filename-function key)))
     (if (file-exists-p pdf-file)
        (org-open-file pdf-file)
 (message "no pdf found for %s" key))))
@@ -1484,6 +1594,7 @@ falling back to what the user has set in `org-ref-default-bibliography'"
     (save-excursion
       (with-temp-buffer
         (insert-file-contents bibfile)
+        (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
         (bibtex-search-entry key)
         ;; I like this better than bibtex-url which does not always find
         ;; the urls
@@ -1510,6 +1621,7 @@ falling back to what the user has set in `org-ref-default-bibliography'"
     (save-excursion
       (with-temp-buffer
         (insert-file-contents bibfile)
+        (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
         (bibtex-search-entry key)
         (org-ref-open-bibtex-notes)))))
 
@@ -1524,6 +1636,7 @@ falling back to what the user has set in `org-ref-default-bibliography'"
     (message "%s" (progn
                    (with-temp-buffer
                       (insert-file-contents bibfile)
+                      (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
                       (bibtex-search-entry key)
                       (org-ref-bib-citation))))))
 
@@ -1596,6 +1709,7 @@ Prompt for NEW-FILE includes bib files in `org-ref-default-bibliography', and bi
     (save-excursion
       (with-temp-buffer
         (insert-file-contents bibfile)
+        (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
         (bibtex-search-entry key)
        (setq doi (bibtex-autokey-get-field "doi"))
        ;; in case doi is a url, remove the url part.
@@ -1648,16 +1762,18 @@ get a lot of options.  LINK-STRING is used by the link function."
   (interactive)
   (let* ((results (org-ref-get-bibtex-key-and-file))
         (key (car results))
-         (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
+         (pdf-file (funcall org-ref-get-pdf-filename-function key))
          (bibfile (cdr results))
         (url (save-excursion
                (with-temp-buffer
                  (insert-file-contents bibfile)
+                  (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
                  (bibtex-search-entry key)
                  (bibtex-autokey-get-field "url"))))
         (doi (save-excursion
                (with-temp-buffer
                  (insert-file-contents bibfile)
+                  (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
                  (bibtex-search-entry key)
                  ;; I like this better than bibtex-url which does not always find
                  ;; the urls
@@ -1734,6 +1850,7 @@ get a lot of options.  LINK-STRING is used by the link function."
        (save-excursion
          (with-temp-buffer
            (insert-file-contents bibfile)
+            (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
            (bibtex-search-entry key)
            (org-ref-bib-citation))))
       "\n"
@@ -2038,17 +2155,20 @@ arg (ALTERNATIVE-CITE) to get a menu of citation types."
 (defun org-ref-bib-citation ()
   "From a bibtex entry, create and return a simple citation string.
 This assumes you are in an article."
-
+  (bibtex-set-dialect nil t)
   (bibtex-beginning-of-entry)
   (let* ((cb (current-buffer))
         (bibtex-expand-strings t)
-        (entry (loop for (key . value) in (bibtex-parse-entry t)
-                     collect (cons (downcase key) value)))
+        (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
+                        collect (cons (downcase key) value)))
         (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
         (year  (reftex-get-bib-field "year" entry))
         (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
         (key (reftex-get-bib-field "=key=" entry))
-        (journal (reftex-get-bib-field "journal" entry))
+        (journal (let ((jt (reftex-get-bib-field "journal" entry)))
+                    (if (string= "" jt)
+                        (reftex-get-bib-field "journaltitle" entry)
+                      jt)))
         (volume (reftex-get-bib-field "volume" entry))
         (pages (reftex-get-bib-field "pages" entry))
         (doi (reftex-get-bib-field "doi" entry))
@@ -2060,12 +2180,11 @@ This assumes you are in an article."
 
 (defun org-ref-bib-html-citation ()
   "From a bibtex entry, create and return a simple citation with html links."
-
   (bibtex-beginning-of-entry)
   (let* ((cb (current-buffer))
         (bibtex-expand-strings t)
-        (entry (loop for (key . value) in (bibtex-parse-entry t)
-                     collect (cons (downcase key) value)))
+        (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
+                        collect (cons (downcase key) value)))
         (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
         (year  (reftex-get-bib-field "year" entry))
         (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
@@ -2074,14 +2193,13 @@ This assumes you are in an article."
         (volume (reftex-get-bib-field "volume" entry))
         (pages (reftex-get-bib-field "pages" entry))
         (doi (reftex-get-bib-field "doi" entry))
-        (url (reftex-get-bib-field "url" entry))
-        )
+        (url (reftex-get-bib-field "url" entry)))
     ;;authors, "title", Journal, vol(iss):pages (year).
     (concat (format "%s, \"%s\", %s, %s:%s (%s)."
                    author title journal  volume pages year)
            (when url (format " <a href=\"%s\">link</a>" url))
-           (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
-    ))
+           (when doi
+             (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))))
 
 ;; ** Open pdf in bibtex entry
 (defun org-ref-open-bibtex-pdf ()
@@ -2116,18 +2234,9 @@ construct the heading by hand."
   (bibtex-beginning-of-entry)
   (let* ((cb (current-buffer))
         (bibtex-expand-strings t)
-        (entry (loop for (key . value) in (bibtex-parse-entry t)
-                     collect (cons (downcase key) value)))
-        (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
-        (year  (reftex-get-bib-field "year" entry))
-        (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
-        (key (reftex-get-bib-field "=key=" entry))
-        (journal (reftex-get-bib-field "journal" entry))
-        (volume (reftex-get-bib-field "volume" entry))
-        (pages (reftex-get-bib-field "pages" entry))
-        (doi (reftex-get-bib-field "doi" entry))
-        (url (reftex-get-bib-field "url" entry))
-        )
+        (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
+                        collect (cons (downcase key) value)))
+        (key (reftex-get-bib-field "=key=" entry)))
 
     ;; save key to clipboard to make saving pdf later easier by pasting.
     (with-temp-buffer
@@ -2144,38 +2253,41 @@ construct the heading by hand."
     (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
        (funcall org-ref-open-notes-function)
       ;; no entry found, so add one
-      (insert (format "\n** TODO %s - %s" year title))
-      (insert (format"
+      (insert (org-ref-reftex-format-citation entry (concat "\n" org-ref-note-title-format)))
+      (insert (org-ref-reftex-format-citation
+               entry
+               (concat "
  :PROPERTIES:
-  :Custom_ID: %s
-  :AUTHOR: %s
-  :JOURNAL: %s
-  :YEAR: %s
-  :VOLUME: %s
-  :PAGES: %s
-  :DOI: %s
-  :URL: %s
+  :Custom_ID: %k
+  :AUTHOR: %9a
+  :JOURNAL: %j
+  :YEAR: %y
+  :VOLUME: %v
+  :PAGES: %p
+  :DOI: %D
+  :URL: %U
  :END:
-[[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
-key author journal year volume pages doi url key org-ref-pdf-directory key))
-(save-buffer))))
+"
+                       (format "[[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
+                               key org-ref-pdf-directory key))))
+      (save-buffer))))
 
 (defun org-ref-open-notes-from-reftex ()
   "Call reftex, and open notes for selected entry."
   (interactive)
   (let ((bibtex-key )))
 
-    ;; now look for entry in the notes file
-    (if  org-ref-bibliography-notes
-       (find-file-other-window org-ref-bibliography-notes)
-      (error "Org-ref-bib-bibliography-notes is not set to anything"))
+  ;; now look for entry in the notes file
+  (if  org-ref-bibliography-notes
+      (find-file-other-window org-ref-bibliography-notes)
+    (error "Org-ref-bib-bibliography-notes is not set to anything"))
 
-    (goto-char (point-min))
+  (goto-char (point-min))
 
-    (re-search-forward (format
-                       ":Custom_ID: %s$"
-                       (first (reftex-citation t)) nil 'end))
-    (funcall org-ref-open-notes-function))
+  (re-search-forward (format
+                      ":Custom_ID: %s$"
+                      (cl-first (reftex-citation t)) nil 'end))
+  (funcall org-ref-open-notes-function))
 
 ;; ** Open bibtex entry in browser
 (defun org-ref-open-in-browser ()
@@ -2366,7 +2478,7 @@ Makes a new buffer with clickable links."
           (kill-buffer "*Missing citations*"))
       (message "No bad cite links found"))))
 
-;; ** helm interface to bad citations, labels, refs in orgfile
+;; ** helm interface to bad citations, labels, refs and files in orgfile
 (defun org-ref-bad-cite-candidates ()
   "Return a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
   (let* ((cp (point))                  ; save to return to later
@@ -2436,7 +2548,6 @@ Makes a new buffer with clickable links."
            (while (re-search-forward
                    (format  "[^#+]label:%s\\s-" label) nil t)
              (push (cons label (point-marker)) multiple-labels))
-
            (goto-char (point-min))
            (while (re-search-forward
                    (format  "\\label{%s}\\s-?" label) nil t)
@@ -2454,6 +2565,29 @@ Makes a new buffer with clickable links."
            (goto-char cp)))))
       multiple-labels))
 
+(defun org-ref-bad-file-link-candidates ()
+  "Return list of conses (link . marker) wehre the file in the link does not exist."
+  (let* ((bad-files '()))
+    (org-element-map (org-element-parse-buffer) 'link
+      (lambda (link)
+       (let ((type (org-element-property :type link)))
+         (when (or  (string= "file" type)
+                    (string= "attachfile" type))
+           (unless (file-exists-p (org-element-property :path link))
+             (add-to-list 'bad-files
+                          (cons (org-element-property :path link)
+                                (save-excursion
+                                  (goto-char
+                                   (org-element-property :begin link))
+                                  (point-marker)))))))))
+    ;; Let us also check \attachfile{fname}
+    (save-excursion
+      (goto-char (point-min))
+      (while (re-search-forward "\\attachfile{\\(.*\\)}" nil t)
+       (unless (file-exists-p (match-string 1))
+         (add-to-list 'bad-files (cons (match-string 1) (point-marker))))))
+    bad-files))
+
 ;;;###autoload
 (defun org-ref ()
   "Opens a helm interface to actions for org-ref.
@@ -2462,7 +2596,8 @@ Shows bad citations, ref links and labels"
   (let ((cb (current-buffer))
        (bad-citations (org-ref-bad-cite-candidates))
        (bad-refs (org-ref-bad-ref-candidates))
-       (bad-labels (org-ref-bad-label-candidates)))
+       (bad-labels (org-ref-bad-label-candidates))
+       (bad-files (org-ref-bad-file-link-candidates)))
 
     (helm :sources `(((name . "Bad citations")
                       (candidates . ,bad-citations)
@@ -2482,6 +2617,12 @@ Shows bad citations, ref links and labels"
                                          (switch-to-buffer (marker-buffer marker))
                                          (goto-char marker))))
                     ;;
+                    ((name . "Bad file links")
+                     (candidates . ,bad-files)
+                     (lambda (marker)
+                                  (switch-to-buffer (marker-buffer marker))
+                                  (goto-char marker)))
+                    ;;
                     ((name . "Utilities")
                      (candidates . (("Check buffer again" . org-ref)
                                     ("Insert citation" . helm-bibtex)
@@ -2506,8 +2647,7 @@ Shows bad citations, ref links and labels"
                                     ))
                      (action . (lambda (x)
                                  (switch-to-buffer ,cb)
-                                 (funcall x))))
-                     ))))
+                                 (funcall x))))))))
 
 ;; ** Find non-ascii charaters
 (defun org-ref-find-non-ascii-characters ()
@@ -2659,6 +2799,7 @@ Shows bad citations, ref links and labels"
         (bibfile (cdr results)))
     (with-temp-buffer
       (insert-file-contents bibfile)
+      (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
       (bibtex-search-entry key nil 0)
       (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
         ))))
@@ -2676,7 +2817,7 @@ Shows bad citations, ref links and labels"
   (setq keys (org-ref-split-and-strip-string link-string))
   (setq years (mapcar 'org-ref-get-citation-year keys))
   (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
-  (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
+  (setq data (cl-sort data (lambda (x y) (< (string-to-number (car x)) (string-to-number (car y))))))
   ;; now get the keys separated by commas
   (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
   ;; and replace the link with the sorted keys
@@ -2788,87 +2929,89 @@ Shows bad citations, ref links and labels"
 (defun org-ref-link-message ()
   "Print a minibuffer message about the link that point is on."
   (interactive)
-  (when (eq major-mode 'org-mode)
-    (let* ((object (org-element-context))
-          (type (org-element-property :type object)))
-      (save-excursion
-       (cond
-        ;; cite links
-        ((-contains? org-ref-cite-types type)
-         (message (org-ref-get-citation-string-at-point)))
-
-        ;; message some context about the label we are referring to
-        ((string= type "ref")
-         (message "%scount: %s"
-                  (org-ref-get-label-context
-                   (org-element-property :path object))
-                  (org-ref-count-labels
-                       (org-element-property :path object))))
-
-        ((string= type "eqref")
-         (message "%scount: %s"
-                  (org-ref-get-label-context
-                   (org-element-property :path object))
-                  (org-ref-count-labels
-                       (org-element-property :path object))))
-
-        ;; message the count
-        ((string= type "label")
-         (let ((count (org-ref-count-labels
-                       (org-element-property :path object))))
-           ;; get plurality on occurrence correct
-           (message (concat
-                     (number-to-string count)
-                     " occurence"
-                     (when (or (= count 0)
-                               (> count 1))
-                       "s")))))
-
-        ((string= type "custom-id")
-         (save-excursion
-           (org-open-link-from-string
-            (format "[[#%s]]" (org-element-property :path object)))
-           (message "%s" (org-get-heading))))
-
-         ;; check if the bibliography files exist.
-        ((string= type "bibliography")
-         (let* ((bibfile)
-                ;; object is the link you clicked on
-                (object (org-element-context))
-                (link-string (org-element-property :path object))
-                (link-string-beginning)
-                (link-string-end))
-           (save-excursion
-             (goto-char (org-element-property :begin object))
-             (search-forward link-string nil nil 1)
-             (setq link-string-beginning (match-beginning 0))
-             (setq link-string-end (match-end 0)))
-
-            ;; make sure we are in link and not before the :
-           (when (> link-string-beginning (point))
-             (goto-char link-string-beginning))
-
-           ;; now if we have comma separated bibliographies
-           ;; we find the one clicked on. we want to
-           ;; search forward to next comma from point
+  (save-restriction
+    (widen)
+    (when (eq major-mode 'org-mode)
+      (let* ((object (org-element-context))
+            (type (org-element-property :type object)))
+       (save-excursion
+         (cond
+          ;; cite links
+          ((-contains? org-ref-cite-types type)
+           (message (org-ref-get-citation-string-at-point)))
+
+          ;; message some context about the label we are referring to
+          ((string= type "ref")
+           (message "%scount: %s"
+                    (org-ref-get-label-context
+                     (org-element-property :path object))
+                    (org-ref-count-labels
+                     (org-element-property :path object))))
+
+          ((string= type "eqref")
+           (message "%scount: %s"
+                    (org-ref-get-label-context
+                     (org-element-property :path object))
+                    (org-ref-count-labels
+                     (org-element-property :path object))))
+
+          ;; message the count
+          ((string= type "label")
+           (let ((count (org-ref-count-labels
+                         (org-element-property :path object))))
+             ;; get plurality on occurrence correct
+             (message (concat
+                       (number-to-string count)
+                       " occurence"
+                       (when (or (= count 0)
+                                 (> count 1))
+                         "s")))))
+
+          ((string= type "custom-id")
            (save-excursion
-             (if (search-forward "," link-string-end 1 1)
-                 (setq key-end (- (match-end 0) 1)) ; we found a match
-               (setq key-end (point)))) ; no comma found so take the point
+             (org-open-link-from-string
+              (format "[[#%s]]" (org-element-property :path object)))
+             (message "%s" (org-get-heading))))
+
+          ;; check if the bibliography files exist.
+          ((string= type "bibliography")
+           (let* ((bibfile)
+                  ;; object is the link you clicked on
+                  (object (org-element-context))
+                  (link-string (org-element-property :path object))
+                  (link-string-beginning)
+                  (link-string-end))
+             (save-excursion
+               (goto-char (org-element-property :begin object))
+               (search-forward link-string nil nil 1)
+               (setq link-string-beginning (match-beginning 0))
+               (setq link-string-end (match-end 0)))
+
+             ;; make sure we are in link and not before the :
+             (when (> link-string-beginning (point))
+               (goto-char link-string-beginning))
+
+             (let (key-beginning key-end)
+               ;; now if we have comma separated bibliographies
+               ;; we find the one clicked on. we want to
+               ;; search forward to next comma from point
+               (save-excursion
+                 (if (search-forward "," link-string-end 1 1)
+                     (setq key-end (- (match-end 0) 1)) ; we found a match
+                   (setq key-end (point)))) ; no comma found so take the point
 
-           ;; and backward to previous comma from point
-           (save-excursion
-             (if (search-backward "," link-string-beginning 1 1)
-                 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
-               (setq key-beginning (point)))) ; no match found
-           ;; save the key we clicked on.
-           (setq bibfile
-                 (org-ref-strip-string
-                  (buffer-substring key-beginning key-end)))
-           (if (file-exists-p bibfile)
-               (message "%s exists." bibfile)
-             (message "!!! %s NOT FOUND !!!" bibfile))))
-        )))))
+               ;; and backward to previous comma from point
+               (save-excursion
+                 (if (search-backward "," link-string-beginning 1 1)
+                     (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
+                   (setq key-beginning (point)))) ; no match found
+               ;; save the key we clicked on.
+               (setq bibfile
+                     (org-ref-strip-string
+                      (buffer-substring key-beginning key-end)))
+               (if (file-exists-p bibfile)
+                   (message "%s exists." bibfile)
+                 (message "!!! %s NOT FOUND !!!" bibfile)))))))))))
 
 ;; ** aliases
 (defalias 'oro 'org-ref-open-citation-at-point)
@@ -3003,17 +3146,17 @@ first key that partially matches.  This version avoids that."
 User is prompted for tags.  This function is called from `helm-bibtex'.
 Argument CANDIDATES helm candidates."
   (message "")
-  (let ((keywords (read-input "Keywords (comma separated): ")))
-    (loop for key in (helm-marked-candidates)
-         do
-         (save-window-excursion
-           (helm-bibtex-show-entry key)
-           (bibtex-set-field
-            "keywords"
-            (concat
-             keywords
-             ", " (bibtex-autokey-get-field "keywords")))
-           (save-buffer)))))
+  (let ((keywords (read-string "Keywords (comma separated): ")))
+    (cl-loop for key in (helm-marked-candidates)
+            do
+            (save-window-excursion
+              (helm-bibtex-show-entry key)
+              (bibtex-set-field
+               "keywords"
+               (concat
+                keywords
+                ", " (bibtex-autokey-get-field "keywords")))
+              (save-buffer)))))
 
 (setq helm-source-bibtex
       '((name                                      . "BibTeX entries")
@@ -3041,11 +3184,13 @@ In the helm-bibtex buffer, C-u will give you a helm menu to select a new link ty
 C-u C-u will change the key at point to the selected keys."
   (let* ((object (org-element-context))
         (last-char (save-excursion
-                     (goto-char (org-element-property :end object))
-                     (backward-char)
-                     (if (looking-at " ")
-                         " "
-                       ""))))
+                     (when (org-element-property :end object)
+                       (goto-char (org-element-property :end object))
+                       (unless (bobp)
+                         (backward-char))
+                       (if (looking-at " ")
+                           " "
+                         "")))))
     (cond
      ;; case where we are in a link
      ((and (equal (org-element-type object) 'link)
@@ -3079,7 +3224,7 @@ C-u C-u will change the key at point to the selected keys."
      ;; We are next to a link, and we want to append
      ;; next to a link means one character back is on a link.
      ((save-excursion
-       (backward-char)
+       (unless (bobp) (backward-char))
        (and (equal (org-element-type (org-element-context)) 'link)
             (-contains?
              org-ref-cite-types
@@ -3142,6 +3287,7 @@ With two prefix args, insert a label link."
        (save-excursion
          (with-temp-buffer
            (insert-file-contents bibfile)
+            (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
            (bibtex-search-entry key)
            (org-ref-bib-citation)))
       "!!! No entry found !!!" )))
@@ -3152,16 +3298,18 @@ With two prefix args, insert a label link."
 Checks for pdf and doi, and add appropriate functions."
   (let* ((results (org-ref-get-bibtex-key-and-file))
         (key (car results))
-         (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
+         (pdf-file (funcall org-ref-get-pdf-filename-function key))
          (bibfile (cdr results))
         (url (save-excursion
                (with-temp-buffer
                  (insert-file-contents bibfile)
+                  (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
                  (bibtex-search-entry key)
                  (bibtex-autokey-get-field "url"))))
         (doi (save-excursion
                (with-temp-buffer
                  (insert-file-contents bibfile)
+                  (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
                  (bibtex-search-entry key)
                  ;; I like this better than bibtex-url which does not always find
                  ;; the urls
@@ -3237,10 +3385,10 @@ Checks for pdf and doi, and add appropriate functions."
                    (email-bibtex-entry))))
      t)
   ;; finally return a numbered list of the candidates
-  (loop for i from 0
-       for cell in candidates
-       collect (cons (format "%2s. %s" i (car cell))
-                     (cdr cell)))))
+  (cl-loop for i from 0
+          for cell in candidates
+          collect (cons (format "%2s. %s" i (car cell))
+                        (cdr cell)))))
 
 
 (defvar org-ref-helm-user-candidates '()
@@ -3250,7 +3398,13 @@ This is a list of cons cells '((\"description\" . action)). The action function
 ;; example of adding your own function
 (add-to-list
  'org-ref-helm-user-candidates
- '("Example" . (lambda () (message-box "You did it!")))
+ '("Open pdf in emacs" . (lambda ()
+
+                          (find-file
+                           (concat
+                            org-ref-pdf-directory
+                            (car (org-ref-get-bibtex-key-and-file))
+                            ".pdf"))))
  t)
 
 ;;;###autoload