Add ebib-get-field-value
[ebib.git] / src / ebib.el
blobedc5fb0e1f20a780874e6bc048f9ba514236a5c9
1 ;; Ebib v==VERSION==
2 ;;
3 ;; Copyright (c) 2003-2010 Joost Kremers
4 ;; All rights reserved.
5 ;;
6 ;; Redistribution and use in source and binary forms, with or without
7 ;; modification, are permitted provided that the following conditions
8 ;; are met:
9 ;;
10 ;; 1. Redistributions of source code must retain the above copyright
11 ;; notice, this list of conditions and the following disclaimer.
12 ;; 2. Redistributions in binary form must reproduce the above copyright
13 ;; notice, this list of conditions and the following disclaimer in the
14 ;; documentation and/or other materials provided with the distribution.
15 ;; 3. The name of the author may not be used to endorse or promote products
16 ;; derived from this software without specific prior written permission.
18 ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE,
24 ;; DATA, OR PROFITS ; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 (eval-when-compile
30 (require 'cl))
31 (require 'easymenu)
33 ;;;;;;;;;;;;;;;;;;;;;;
34 ;; global variables ;;
35 ;;;;;;;;;;;;;;;;;;;;;;
37 ;; user customisation
39 (defgroup ebib nil "Ebib: a BibTeX database manager" :group 'Tex)
41 (defcustom ebib-default-type 'article
42 "*The default type for a newly created BibTeX entry."
43 :group 'ebib
44 :type 'symbol)
46 (defcustom ebib-preload-bib-files nil
47 "*List of .bib files to load automatically when Ebib starts."
48 :group 'ebib
49 :type '(repeat (file :must-match t)))
51 (defcustom ebib-additional-fields '(crossref url annote abstract
52 keywords file timestamp)
53 "*List of the additional fields."
54 :group 'ebib
55 :type '(repeat (symbol :tag "Field")))
57 (defcustom ebib-layout 'full
58 "*Ebib window layout.
59 Full width: Ebib occupies the entire Emacs frame.
60 Custom width: Ebib occupies the right side of the Emacs frame,
61 with the left side free for another window."
62 :group 'ebib
63 :type '(choice (const :tag "Full width" full)
64 (const :tag "Custom width" custom)))
66 (defcustom ebib-width 80
67 "*Width of the Ebib windows.
68 Only takes effect if EBIB-LAYOUT is set to CUSTOM."
69 :group 'ebib
70 :type 'integer)
72 (defcustom ebib-index-window-size 10
73 "*The number of lines used for the index buffer window."
74 :group 'ebib
75 :type 'integer)
77 (defcustom ebib-index-display-fields nil
78 "*List of the fields to display in the index buffer."
79 :group 'ebib
80 :type '(repeat (symbol :tag "Index Field")))
82 (defcustom ebib-insertion-commands '(("cite" 1 nil))
83 "*A list of commands that can be used to insert an entry into a (La)TeX buffer.
84 For use with EBIB-INSERT-BIBTEX-KEY and EBIB-PUSH-BIBTEX-KEY."
85 :group 'ebib
86 :type '(repeat (list :tag "Citation command" (string :tag "Command")
87 (integer :tag "Optional arguments")
88 (choice (const :tag "Standard command" nil)
89 (const :tag "Multicite command" t)))))
91 (defcustom ebib-multiline-major-mode 'text-mode
92 "*The major mode of the multiline edit buffer."
93 :group 'ebib
94 :type '(function :tag "Mode function"))
96 (defcustom ebib-sort-order nil
97 "*The fields on which the BibTeX entries are to be sorted in the .bib file.
98 Sorting is done on different sort levels, and each sort level contains one
99 or more sort keys."
100 :group 'ebib
101 :type '(repeat (repeat :tag "Sort level" (symbol :tag "Sort field"))))
103 (defcustom ebib-save-xrefs-first nil
104 "*If true, entries with a crossref field will be saved first in the .bib-file.
105 Setting this option has unpredictable results for the sort order
106 of entries, so it is not compatible with setting the Sort Order option."
107 :group 'ebib
108 :type 'boolean)
110 (defface ebib-crossref-face '((t (:foreground "red")))
111 "*Face used to indicate values inherited from crossreferenced entries."
112 :group 'ebib)
114 (defface ebib-marked-face (if (featurep 'xemacs)
115 '((t (:foreground "white" :background "red")))
116 '((t (:inverse-video t))))
117 "*Face to indicate marked entries."
118 :group 'ebib)
120 (defcustom ebib-use-timestamp nil
121 "*If true, new entries will get a time stamp.
122 The time stamp will be stored in a field \"timestamp\" that can
123 be made visible with the `H' command in the index buffer."
124 :group 'ebib
125 :type 'boolean)
127 (defcustom ebib-timestamp-format "%a %b %e %T %Y"
128 "*Format of the time string used in the timestamp.
129 The format is passed unmodified to FORMAT-TIME-STRING, see the
130 documentation of that function for details."
131 :group 'ebib
132 :type 'string)
134 (defcustom ebib-standard-url-field 'url
135 "*Standard field to store urls in.
136 In the index buffer, the command ebib-browse-url can be used to
137 send a url to a browser. This option sets the field from which
138 this command extracts the url."
139 :group 'ebib
140 :type 'symbol)
142 (defcustom ebib-url-regexp "\\\\url{\\(.*\\)}\\|https?://[^ '<>\"\n\t\f]+"
143 "*Regular expression to extract urls."
144 :group 'ebib
145 :type 'string)
147 (defcustom ebib-browser-command ""
148 "*Command to call the browser with.
149 GNU/Emacs has a function call-browser, which is used if this
150 option is unset."
151 :group 'ebib
152 :type '(string :tag "Browser command"))
154 (defcustom ebib-standard-file-field 'file
155 "*Standard field to store filenames in.
156 In the index buffer, the command ebib-view-file can be used to
157 view a file externally. This option sets the field from which
158 this command extracts the filename."
159 :group 'ebib
160 :type 'symbol)
162 (defcustom ebib-file-associations '(("pdf" . "xpdf")
163 ("ps" . "gv"))
164 "*List of file associations.
165 Lists file extensions together with external programs to handle
166 files with those extensions. If the external program is left
167 blank, Ebib tries to handle the file internally in
168 Emacs (e.g. with doc-view-mode)."
169 :group 'ebib
170 :type '(repeat (cons :tag "File association"
171 (string :tag "Extension") (string :tag "Command"))))
173 (defcustom ebib-file-regexp "[^?|\\:*<>\" \n\t\f]+"
174 "*Regular expression to match filenames."
175 :group 'ebib
176 :type 'string)
178 (defcustom ebib-file-search-dirs '("~")
179 "*List of directories to search for files."
180 :group 'ebib
181 :type '(repeat :tag "Search directories" (string :tag "Directory")))
183 (defcustom ebib-print-preamble nil
184 "*Preamble used for the LaTeX file for printing the database.
185 Each string is added to the preamble on a separate line."
186 :group 'ebib
187 :type '(repeat (string :tag "Add to preamble")))
189 (defcustom ebib-print-newpage nil
190 "*If set, each entry is printed on a separate page."
191 :group 'ebib
192 :type 'boolean)
194 (defcustom ebib-print-multiline nil
195 "*If set, multiline fields are included when printing the database."
196 :group 'ebib
197 :type 'boolean)
199 (defcustom ebib-latex-preamble '("\\bibliographystyle{plain}")
200 "*Preamble used for the LaTeX file for BibTeXing the database.
201 Each string is added to the preamble on a separate line."
202 :group 'ebib
203 :type '(repeat (string :tag "Add to preamble")))
205 (defcustom ebib-print-tempfile ""
206 "*Temporary file for use with EBIB-PRINT-DATABASE and EBIB-LATEX-DATABASE."
207 :group 'ebib
208 :type '(file))
210 (defcustom ebib-allow-identical-fields nil
211 "*If set, Ebib handles multiple occurrences of a field gracefully."
212 :group 'ebib
213 :type 'boolean)
215 (defvar ebib-unique-field-list nil
216 "Holds a list of all field names.")
218 (defmacro add-to-listq (listvar element &optional append fn)
219 (if (or (featurep 'xemacs)
220 (string< emacs-version "22"))
221 `(add-to-list (quote ,listvar) ,element ,append)
222 `(add-to-list (quote ,listvar) ,element ,append ,fn)))
224 (defun ebib-set-unique-field-list (var value)
225 "Sets EBIB-UNIQUE-FIELD-LIST on the basis of EBIB-ENTRY-TYPES"
226 (set-default var value)
227 (setq ebib-unique-field-list nil)
228 (mapc #'(lambda (entry)
229 (mapc #'(lambda (field)
230 (add-to-listq ebib-unique-field-list field t 'eq))
231 (cadr entry))
232 (mapc #'(lambda (field)
233 (add-to-listq ebib-unique-field-list field t 'eq))
234 (caddr entry)))
235 value))
237 (defcustom ebib-entry-types
238 '((article ;; name of entry type
239 (author title journal year) ;; obligatory fields
240 (volume number pages month note)) ;; optional fields
242 (book
243 (author title publisher year)
244 (editor volume number series address edition month note))
246 (booklet
247 (title)
248 (author howpublished address month year note))
250 (inbook
251 (author title chapter pages publisher year)
252 (editor volume series address edition month note))
254 (incollection
255 (author title booktitle publisher year)
256 (editor volume number series type chapter pages address edition month note))
258 (inproceedings
259 (author title booktitle year)
260 (editor pages organization publisher address month note))
262 (manual
263 (title)
264 (author organization address edition month year note))
266 (misc
268 (title author howpublished month year note))
270 (mastersthesis
271 (author title school year)
272 (address month note))
274 (phdthesis
275 (author title school year)
276 (address month note))
278 (proceedings
279 (title year)
280 (editor publisher organization address month note))
282 (techreport
283 (author title institution year)
284 (type number address month note))
286 (unpublished
287 (author title note)
288 (month year)))
290 "List of entry type definitions for Ebib"
291 :group 'ebib
292 :type '(repeat (list :tag "Entry type" (symbol :tag "Name")
293 (repeat :tag "Obligatory fields" (symbol :tag "Field"))
294 (repeat :tag "Optional fields" (symbol :tag "Field"))))
295 :set 'ebib-set-unique-field-list)
297 ;; generic for all databases
299 ;; constants and variables that are set only once
300 (defconst ebib-bibtex-identifier "[^\"#%'(),={} \t\n\f]*" "Regexp describing a licit BibTeX identifier.")
301 (defconst ebib-version "==VERSION==")
302 (defvar ebib-initialized nil "T if Ebib has been initialized.")
304 ;; buffers and highlights
305 (defvar ebib-index-buffer nil "The index buffer.")
306 (defvar ebib-entry-buffer nil "The entry buffer.")
307 (defvar ebib-strings-buffer nil "The strings buffer.")
308 (defvar ebib-multiline-buffer nil "Buffer for editing multiline strings.")
309 (defvar ebib-log-buffer nil "Buffer showing warnings and errors during loading of .bib files")
310 (defvar ebib-index-highlight nil "Highlight to mark the current entry.")
311 (defvar ebib-fields-highlight nil "Highlight to mark the current field.")
312 (defvar ebib-strings-highlight nil "Highlight to mark the current string.")
314 ;; general bookkeeping
315 (defvar ebib-minibuf-hist nil "Holds the minibuffer history for Ebib")
316 (defvar ebib-saved-window-config nil "Stores the window configuration when Ebib is called.")
317 (defvar ebib-pre-ebib-window nil "The window that was active when Ebib was called.")
318 (defvar ebib-pre-multiline-buffer nil "The buffer in the window before switching to the multiline edit buffer.")
319 (defvar ebib-export-filename nil "Filename to export entries to.")
320 (defvar ebib-push-buffer nil "Buffer to push entries to.")
321 (defvar ebib-search-string nil "Stores the last search string.")
322 (defvar ebib-editing nil "Indicates what the user is editing.
323 Its value can be 'strings, 'fields, or 'preamble.")
324 (defvar ebib-multiline-raw nil "Indicates whether the multiline text being edited is raw.")
325 (defvar ebib-log-error nil "Indicates whether an error was logged.")
326 (defvar ebib-local-bibtex-filenames nil
327 "A buffer-local variable holding a list of the name(s) of that buffer's .bib file(s)")
328 (make-variable-buffer-local 'ebib-local-bibtex-filenames)
329 (defvar ebib-syntax-table (make-syntax-table) "Syntax table used for reading .bib files.")
330 (modify-syntax-entry ?\[ "." ebib-syntax-table)
331 (modify-syntax-entry ?\] "." ebib-syntax-table)
332 (modify-syntax-entry ?\( "." ebib-syntax-table)
333 (modify-syntax-entry ?\) "." ebib-syntax-table)
334 (modify-syntax-entry ?\" "w" ebib-syntax-table)
336 ;; the databases
338 ;; each database is represented by a struct
339 (defstruct edb
340 (database (make-hash-table :test 'equal)) ; hashtable containing the database itself
341 (keys-list nil) ; sorted list of the keys in the database
342 (cur-entry nil) ; sublist of KEYS-LIST that starts with the current entry
343 (marked-entries nil) ; list of marked entries
344 (n-entries 0) ; number of entries stored in this database
345 (strings (make-hash-table :test 'equal)) ; hashtable with the @STRING definitions
346 (strings-list nil) ; sorted list of the @STRING abbreviations
347 (preamble nil) ; string with the @PREAMBLE definition
348 (filename nil) ; name of the BibTeX file that holds this database
349 (name nil) ; name of the database
350 (modified nil) ; has this database been modified?
351 (make-backup nil) ; do we need to make a backup of the .bib file?
352 (virtual nil)) ; is this a virtual database?
354 ;; the master list and the current database
355 (defvar ebib-databases nil "List of structs containing the databases.")
356 (defvar ebib-cur-db nil "The database that is currently active.")
358 ;;;;;; bookkeeping required when editing field values or @STRING definitions
360 (defvar ebib-hide-hidden-fields t "If set to T, hidden fields are not shown.")
362 ;; this variable is set when the user enters the entry buffer
363 (defvar ebib-cur-entry-fields nil "The fields of the type of the current entry.")
365 ;; these two are set by EBIB-FILL-ENTRY-BUFFER
366 (defvar ebib-cur-entry-hash nil "The hash table containing the data of the current entry.")
367 (defvar ebib-current-field nil "The current field.")
369 ;; and this one by EBIB-FILL-STRINGS-BUFFER
370 (defvar ebib-current-string nil "The current @STRING definition.")
372 ;; the prefix key and the multiline key are stored in a variable so that the
373 ;; user can customise them.
374 (defvar ebib-prefix-key ?\;)
375 (defvar ebib-multiline-key ?\|)
377 ;; this is an AucTeX variable, but we want to check its value, so let's
378 ;; keep the compiler from complaining.
379 (eval-when-compile
380 (defvar TeX-master))
382 ;; this is to keep XEmacs from complaining.
383 (eval-when-compile
384 (if (featurep 'xemacs)
385 (defvar mark-active)))
387 ;; XEmacs has line-number, not line-number-at-pos.
388 (eval-and-compile
389 (if (featurep 'xemacs)
390 (defalias 'line-number-at-pos 'line-number)))
392 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
393 ;; useful macros and functions ;;
394 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
396 (defmacro nor (&rest args)
397 "Returns T if none of its arguments are true."
398 `(not (or ,@args)))
400 ;; we sometimes (often, in fact ;-) need to do something with a string, but
401 ;; take special action (or do nothing) if that string is empty. IF-STR
402 ;; makes that easier:
404 (defmacro if-str (bindvar then &rest else)
405 "Execute THEN only if STRING is nonempty.
406 Format: (if-str (var value) then-form [else-forms]) VAR is bound
407 to VALUE, which is evaluated. If VAR is a nonempty string,
408 THEN-FORM is executed. If VAR is either \"\" or nil, ELSE-FORM is
409 executed. Returns the value of THEN or of ELSE."
410 (declare (indent 2))
411 `(let ,(list bindvar)
412 (if (nor (null ,(car bindvar))
413 (equal ,(car bindvar) ""))
414 ,then
415 ,@else)))
417 (defmacro last1 (lst &optional n)
418 "Returns the last (or Nth last) element of LST."
419 `(car (last ,lst ,n)))
421 ;; we sometimes need to walk through lists. these functions yield the
422 ;; element directly preceding or following ELEM in LIST. in order to work
423 ;; properly, ELEM must be unique in LIST, obviously. if ELEM is the
424 ;; first/last element of LIST, or if it is not contained in LIST at all,
425 ;; the result is nil.
426 (defun next-elem (elem list)
427 (cadr (member elem list)))
429 (defun prev-elem (elem list)
430 (if (or (equal elem (car list))
431 (not (member elem list)))
433 (last1 list (1+ (length (member elem list))))))
435 (defun read-string-at-point (chars)
436 "Reads a string at POINT delimited by CHARS and returns it.
437 CHARS is a string of characters that should not occur in the string."
438 (save-excursion
439 (skip-chars-backward (concat "^" chars))
440 (let ((beg (point)))
441 (looking-at-goto-end (concat "[^" chars "]*"))
442 (buffer-substring-no-properties beg (point)))))
444 (defun remove-from-string (string remove)
445 "Returns a copy of STRING with all the occurrences of REMOVE taken out.
446 REMOVE can be a regex."
447 (apply 'concat (split-string string remove)))
449 (defun in-string (char string)
450 "Returns T if CHAR is in STRING, otherwise NIL."
451 (catch 'found
452 (do ((len (length string))
453 (i 0 (1+ i)))
454 ((= i len) nil)
455 (if (eq char (aref string i))
456 (throw 'found t)))))
458 (defun ensure-extension (string ext)
459 "Makes sure STRING has the extension EXT, by appending it if necessary.
460 EXT should be an extension without the dot."
461 (if (string-match (concat "\\." ext "$") string)
462 string
463 (concat string "." ext)))
465 (defmacro with-buffer-writable (&rest body)
466 "Makes the current buffer writable and executes the commands in BODY.
467 After BODY is executed, the buffer modified flag is unset."
468 (declare (indent defun))
469 `(unwind-protect
470 (let ((buffer-read-only nil))
471 ,@body)
472 (set-buffer-modified-p nil)))
474 (defmacro safe-write-region (start end filename &optional append visit lockname mustbenew)
475 "XEmacs does not have the MUSTBENEW argument, so this is a way to implement it."
476 (if (featurep 'xemacs)
477 `(if (and (file-exists-p ,filename)
478 (not (y-or-n-p (format "File %s already exists; overwrite anyway? " ,filename))))
479 (error "File %s exist" ,filename)
480 (write-region ,start ,end ,filename ,append ,visit ,lockname))
481 `(write-region ,start ,end ,filename ,append ,visit ,lockname ,mustbenew)))
483 (defun symbol-or-string (x)
484 "Returns the symbol-name of X if X is a symbol, otherwise return X.
485 Much like SYMBOL-NAME, except it does not throw an error if X is
486 not a symbol."
487 (if (symbolp x)
488 (symbol-name x)
491 ;; XEmacs doesn't know about propertize...
492 (if (not (fboundp 'propertize))
493 (defun propertize (string &rest properties)
494 "Return a copy of STRING with text properties added.
495 First argument is the string to copy. Remaining arguments form a
496 sequence of PROPERTY VALUE pairs for text properties to add to
497 the result."
498 (let ((new-string (copy-sequence string)))
499 (add-text-properties 0 (length new-string) properties new-string)
500 new-string)))
502 (defun region-active ()
503 (if (featurep 'xemacs)
504 (region-active-p)
505 mark-active))
507 ;; RAW-P determines if STRING is raw. note that we cannot do this by
508 ;; simply checking whether STRING begins with { and ends with } (or
509 ;; begins and ends with "), because something like "{abc} # D # {efg}"
510 ;; would then be incorrectly recognised as non-raw. so we need to do
511 ;; the following: take out everything that is between braces or
512 ;; quotes, and see if anything is left. if there is, the original
513 ;; string was raw, otherwise it was not.
515 ;; so i first check whether the string begins with { or ". if not, we
516 ;; certainly have a raw string. (RAW-P recognises this through the default
517 ;; clause of the COND.) if the first character is { or ", we first take out
518 ;; every occurrence of backslash-escaped { and } or ", so that the rest of
519 ;; the function does not get confused over them.
521 ;; then, if the first character is {, i use REMOVE-FROM-STRING to take out
522 ;; every occurrence of the regex "{[^{]*?}", which translates to "the
523 ;; smallest string that starts with { and ends with }, and does not contain
524 ;; another {. IOW, it takes out the innermost braces and their
525 ;; contents. because braces may be embedded, we have to repeat this step
526 ;; until no more balanced braces are found in the string. (note that it
527 ;; would be unwise to check for just the occurrence of { or }, because that
528 ;; would throw RAW-P in an infinite loop if a string contains an unbalanced
529 ;; brace.)
531 ;; for strings beginning with " i do the same, except that it is not
532 ;; necessary to repeat this in a WHILE loop, for the simple reason that
533 ;; strings surrounded with double quotes cannot be embedded; i.e.,
534 ;; "ab"cd"ef" is not a valid (BibTeX) string, while {ab{cd}ef} is.
536 ;; note: because these strings are to be fed to BibTeX and ultimately
537 ;; (La)TeX, it might seem that we don't need to worry about strings
538 ;; containing unbalanced braces, because (La)TeX would choke on them. but
539 ;; the user may inadvertently enter such a string, and we therefore need to
540 ;; be able to handle it. (alternatively, we could perform a check on
541 ;; strings and warn the user.)
543 (defun raw-p (string)
544 "Non-nil if STRING is raw."
545 (when (stringp string)
546 (cond
547 ((eq (string-to-char string) ?\{)
548 ;; we remove all occurrences of `\{' and of `\}' from the string:
549 (let ((clear-str (remove-from-string (remove-from-string string "[\\][{]")
550 "[\\][}]")))
551 (while (and (in-string ?\{ clear-str) (in-string ?\} clear-str))
552 (setq clear-str (remove-from-string clear-str "{[^{]*?}")))
553 (> (length clear-str) 0)))
554 ((eq (string-to-char string) ?\")
555 (let ((clear-str (remove-from-string string "[\\][\"]"))) ; remove occurrences of `\"'
556 (setq clear-str (remove-from-string clear-str "\"[^\"]*?\""))
557 (> (length clear-str) 0)))
558 (t t))))
560 (defun to-raw (string)
561 "Converts a string to its raw counterpart."
562 (if (and (stringp string)
563 (not (raw-p string)))
564 (substring string 1 -1)
565 string))
567 (defun from-raw (string)
568 "Converts a raw string to a non-raw one."
569 (if (raw-p string)
570 (concat "{" string "}")
571 string))
573 (defun multiline-p (string)
574 "True if STRING is multiline."
575 (if (stringp string)
576 (string-match "\n" string)))
578 (defun first-line (string)
579 "Returns the first line of a multi-line string."
580 (string-match "\n" string)
581 (substring string 0 (match-beginning 0)))
583 (defun sort-in-buffer (limit str)
584 "Moves POINT to the right position to insert STR in a buffer with lines sorted A-Z."
585 (let ((upper limit)
586 middle)
587 (when (> limit 0)
588 (let ((lower 0))
589 (goto-char (point-min))
590 (while (progn
591 (setq middle (/ (+ lower upper 1) 2))
592 (goto-char (point-min))
593 (forward-line (1- middle)) ; if this turns out to be where we need to be,
594 (beginning-of-line) ; this puts POINT at the right spot.
595 (> (- upper lower) 1)) ; if upper and lower differ by only 1, we have found the
596 ; position to insert the entry in.
597 (save-excursion
598 (let ((beg (point)))
599 (end-of-line)
600 (if (string< (buffer-substring-no-properties beg (point)) str)
601 (setq lower middle)
602 (setq upper middle)))))))))
604 (defun match-all (match-str string)
605 "Highlights all the matches of MATCH-STR in STRING.
606 The return value is a list of two elements: the first is the
607 modified string, the second either t or nil, indicating whether a
608 match was found at all."
609 (do ((counter 0 (match-end 0)))
610 ((not (string-match match-str string counter)) (values string (not (= counter 0))))
611 (add-text-properties (match-beginning 0) (match-end 0) '(face highlight) string)))
613 (defun looking-at-goto-end (str &optional match)
614 "Like LOOKING-AT but moves point to the end of the matching string.
615 MATCH acts just like the argument to MATCH-END, and defaults to 0."
616 (or match (setq match 0))
617 (let ((case-fold-search t))
618 (if (looking-at str)
619 (goto-char (match-end match)))))
621 ;; this needs to be wrapped in an eval-and-compile, to keep Emacs from
622 ;; complaining that ebib-execute-helper isn't defined when it compiles
623 ;; ebib-execute-when.
624 (eval-and-compile
625 (defun ebib-execute-helper (env)
626 "Helper function for EBIB-EXECUTE-WHEN."
627 (cond
628 ((eq env 'entries)
629 '(and ebib-cur-db
630 (edb-cur-entry ebib-cur-db)))
631 ((eq env 'marked-entries)
632 '(and ebib-cur-db
633 (edb-marked-entries ebib-cur-db)))
634 ((eq env 'database)
635 'ebib-cur-db)
636 ((eq env 'real-db)
637 '(and ebib-cur-db
638 (not (edb-virtual ebib-cur-db))))
639 ((eq env 'virtual-db)
640 '(and ebib-cur-db
641 (edb-virtual ebib-cur-db)))
642 ((eq env 'no-database)
643 '(not ebib-cur-db))
644 (t t))))
646 (defmacro ebib-execute-when (&rest forms)
647 "Macro to facilitate writing Ebib functions.
648 This functions essentially like a COND clause: the basic format
649 is (ebib-execute-when FORMS ...), where each FORM is built up
650 as (ENVIRONMENTS BODY). ENVIRONMENTS is a list of symbols (not
651 quoted) that specify under which conditions BODY is to be
652 executed. Valid symbols are:
654 entries: execute when there are entries in the database,
655 marked-entries: execute when there are marked entries in the database,
656 database: execute if there is a database,
657 no-database: execute if there is no database,
658 real-db: execute when there is a database and it is real,
659 virtual-db: execute when there is a database and it is virtual,
660 default: execute if all else fails.
662 Just like with COND, only one form is actually executed, the
663 first one that matches. If ENVIRONMENT contains more than one
664 condition, BODY is executed if they all match (i.e., the
665 conditions are AND'ed.)"
666 (declare (indent defun))
667 `(cond
668 ,@(mapcar #'(lambda (form)
669 (cons (if (= 1 (length (car form)))
670 (ebib-execute-helper (caar form))
671 `(and ,@(mapcar #'(lambda (env)
672 (ebib-execute-helper env))
673 (car form))))
674 (cdr form)))
675 forms)))
677 ;; the numeric prefix argument is 1 if the user gave no prefix argument at
678 ;; all. the raw prefix argument is not always a number. so we need to do
679 ;; our own conversion.
680 (defun ebib-prefix (num)
681 (when (numberp num)
682 num))
684 (defun ebib-called-with-prefix ()
685 "Returns T if the command was called with a prefix key."
686 (if (featurep 'xemacs)
687 (member (character-to-event ebib-prefix-key) (append (this-command-keys) nil))
688 (member (event-convert-list (list ebib-prefix-key))
689 (append (this-command-keys-vector) nil))))
691 (defmacro ebib-export-to-db (num message copy-fn)
692 "Exports data to another database.
693 NUM is the number of the database to which the data is to be copied.
695 MESSAGE is a string displayed in the echo area if the export was
696 succesful. It must contain a %d directive, which is used to
697 display the database number to which the entry was exported.
699 COPY-FN is the function that actually copies the relevant
700 data. It must take as argument the database to which the data is
701 to be copied. COPY-FN must return T if the copying was
702 successful, and NIL otherwise."
703 (let ((goal-db (make-symbol "goal-db")))
704 `(let ((,goal-db (nth (1- ,num) ebib-databases)))
705 (cond
706 ((not ,goal-db)
707 (error "Database %d does not exist" ,num))
708 ((edb-virtual ,goal-db)
709 (error "Database %d is virtual" ,num))
710 (t (when (funcall ,copy-fn ,goal-db)
711 (ebib-set-modified t ,goal-db)
712 (message ,message ,num)))))))
714 (defmacro ebib-cur-entry-key ()
715 "Returns the key of the current entry in EBIB-CUR-DB."
716 `(car (edb-cur-entry ebib-cur-db)))
718 (defmacro ebib-export-to-file (prompt-string message insert-fn)
719 "Exports data to a file.
720 PROMPT-STRING is the string that is used to ask for the filename
721 to export to. INSERT-FN must insert the data to be exported into
722 the current buffer: it is called within a WITH-TEMP-BUFFER, whose
723 contents is appended to the file the user enters.
725 MESSAGE is shown in the echo area when the export was
726 successful. It must contain a %s directive, which is used to
727 display the actual filename."
728 (let ((filename (make-symbol "filename")))
729 `(let ((insert-default-directory (not ebib-export-filename)))
730 (if-str (,filename (read-file-name
731 ,prompt-string "~/" nil nil ebib-export-filename))
732 (with-temp-buffer
733 (funcall ,insert-fn)
734 (append-to-file (point-min) (point-max) ,filename)
735 (setq ebib-export-filename ,filename))))))
737 (defun ebib-temp-window ()
738 "Returns a window to be used for temporary use."
739 (if (eq ebib-layout 'full)
740 (get-buffer-window ebib-entry-buffer)
741 ebib-pre-ebib-window))
743 (defun ebib-get-obl-fields (entry-type)
744 "Returns the obligatory fields of ENTRY-TYPE."
745 (nth 1 (assoc entry-type ebib-entry-types)))
747 (defun ebib-get-opt-fields (entry-type)
748 "Returns the optional fields of ENTRY-TYPE."
749 (nth 2 (assoc entry-type ebib-entry-types)))
751 (defun ebib-get-all-fields (entry-type)
752 "Returns all the fields of ENTRY-TYPE."
753 (cons 'type* (append (ebib-get-obl-fields entry-type)
754 (ebib-get-opt-fields entry-type)
755 ebib-additional-fields)))
757 (defmacro ebib-retrieve-entry (entry-key db)
758 "Returns the hash table of the fields stored in DB under ENTRY-KEY."
759 `(gethash ,entry-key (edb-database ,db)))
761 (defun ebib-erase-buffer (buffer)
762 (set-buffer buffer)
763 (with-buffer-writable
764 (erase-buffer)))
766 (defun ebib-make-highlight (begin end buffer)
767 (let (highlight)
768 (if (featurep 'xemacs)
769 (progn
770 (setq highlight (make-extent begin end buffer))
771 (set-extent-face highlight 'highlight))
772 (progn
773 (setq highlight (make-overlay begin end buffer))
774 (overlay-put highlight 'face 'highlight)))
775 highlight))
777 (defun ebib-move-highlight (highlight begin end buffer)
778 (if (featurep 'xemacs)
779 (set-extent-endpoints highlight begin end buffer)
780 (move-overlay highlight begin end buffer)))
782 (defun ebib-highlight-start (highlight)
783 (if (featurep 'xemacs)
784 (extent-start-position highlight)
785 (overlay-start highlight)))
787 (defun ebib-highlight-end (highlight)
788 (if (featurep 'xemacs)
789 (extent-end-position highlight)
790 (overlay-end highlight)))
792 (defun ebib-delete-highlight (highlight)
793 (if (featurep 'xemacs)
794 (detach-extent highlight)
795 (delete-overlay highlight)))
797 (defun ebib-set-index-highlight ()
798 (set-buffer ebib-index-buffer)
799 (beginning-of-line)
800 (let ((beg (point)))
801 (if ebib-index-display-fields
802 (end-of-line)
803 (skip-chars-forward "^ "))
804 (ebib-move-highlight ebib-index-highlight beg (point) ebib-index-buffer)
805 (beginning-of-line)))
807 (defun ebib-set-fields-highlight ()
808 (set-buffer ebib-entry-buffer)
809 (beginning-of-line)
810 (let ((beg (point)))
811 (looking-at-goto-end "[^ \t\n\f]*")
812 (ebib-move-highlight ebib-fields-highlight beg (point) ebib-entry-buffer)
813 (beginning-of-line)))
815 (defun ebib-set-strings-highlight ()
816 (set-buffer ebib-strings-buffer)
817 (beginning-of-line)
818 (let ((beg (point)))
819 (looking-at-goto-end "[^ \t\n\f]*")
820 (ebib-move-highlight ebib-strings-highlight beg (point) ebib-strings-buffer)
821 (beginning-of-line)))
823 (defun ebib-display-entry (entry-key)
824 "Displays ENTRY-KEY in the index buffer at POINT."
825 (set-buffer ebib-index-buffer)
826 (insert (format "%-30s %s\n"
827 entry-key
828 (if ebib-index-display-fields
829 (let ((cur-entry-hash (ebib-retrieve-entry entry-key ebib-cur-db)))
830 (mapconcat #'(lambda (field)
832 (to-raw (gethash field cur-entry-hash))
833 ""))
834 ebib-index-display-fields
835 "; "))
836 ""))))
838 (defun ebib-redisplay-current-field ()
839 "Redisplays the contents of the current field in the entry buffer."
840 (set-buffer ebib-entry-buffer)
841 (if (eq ebib-current-field 'crossref)
842 (progn
843 (ebib-fill-entry-buffer)
844 (setq ebib-current-field 'crossref)
845 (re-search-forward "^crossref")
846 (ebib-set-fields-highlight))
847 (with-buffer-writable
848 (goto-char (ebib-highlight-start ebib-fields-highlight))
849 (let ((beg (point)))
850 (end-of-line)
851 (delete-region beg (point)))
852 (insert (format "%-17s " (symbol-name ebib-current-field))
853 (ebib-get-field-highlighted ebib-current-field ebib-cur-entry-hash))
854 (ebib-set-fields-highlight))))
856 (defun ebib-redisplay-current-string ()
857 "Redisplays the current string definition in the strings buffer."
858 (set-buffer ebib-strings-buffer)
859 (with-buffer-writable
860 (let ((str (to-raw (gethash ebib-current-string (edb-strings ebib-cur-db)))))
861 (goto-char (ebib-highlight-start ebib-strings-highlight))
862 (let ((beg (point)))
863 (end-of-line)
864 (delete-region beg (point)))
865 (insert (format "%-18s %s" ebib-current-string
866 (if (multiline-p str)
867 (concat "+" (first-line str))
868 (concat " " str))))
869 (ebib-set-strings-highlight))))
871 (defun ebib-move-to-field (field direction)
872 "Moves the fields overlay to the line containing FIELD.
873 If DIRECTION is positive, searches forward, if DIRECTION is
874 negative, searches backward. If DIRECTION is 1 or -1, searches
875 from POINT, if DIRECTION is 2 or -2, searches from beginning or
876 end of buffer. If FIELD is not found in the entry buffer, the
877 overlay is not moved. FIELD must be a symbol."
879 ;;Note: this function does NOT change the value of EBIB-CURRENT-FIELD!
881 (set-buffer ebib-entry-buffer)
882 (if (eq field 'type*)
883 (goto-char (point-min))
884 (multiple-value-bind (fn start limit) (if (>= direction 0)
885 (values 're-search-forward (point-min) (point-max))
886 (values 're-search-backward (point-max) (point-min)))
887 ;; make sure we can get back to our original position, if the field
888 ;; cannot be found in the buffer:
889 (let ((current-pos (point)))
890 (when (eq (logand direction 1) 0) ; if direction is even
891 (goto-char start))
892 (unless (funcall fn (concat "^" (symbol-name field)) limit t)
893 (goto-char current-pos)))))
894 (ebib-set-fields-highlight))
896 (defun ebib-create-collection (hashtable)
897 "Creates a list from the keys in HASHTABLE that can be used as COLLECTION in COMPLETING-READ.
898 The keys of HASHTABLE must be either symbols or strings."
899 (let ((result nil))
900 (maphash #'(lambda (x y)
901 (setq result (cons (cons (symbol-or-string x)
903 result)))
904 hashtable)
905 result))
907 (defun ebib-get-field-value (field entry-key &optional db)
908 "Returns the value of FIELD in the entry ENTRY-KEY in DB.
909 Actually returns a list with the value of FIELD as the first
910 element. The second element is T if the value was obtained from a
911 cross-referenced entry.
913 If DB is nil, it defaults to the current database."
914 (unless db
915 (setq db ebib-cur-db))
916 (let ((entry (ebib-retrieve-entry entry-key db)))
917 (if entry
919 (let ((val (copy-sequence (gethash field entry))))
920 (if val
921 (values val nil)))
922 (let ((xref (ebib-retrieve-entry (to-raw (gethash 'crossref entry)) db)))
923 (if xref
924 (values (gethash field xref) t))))
925 (values nil nil))))
927 (defun ebib-get-field-highlighted (field current-entry &optional match-str)
928 ;; note: we need to work on a copy of the string, otherwise the highlights
929 ;; are made to the string as stored in the database. hence copy-sequence.
930 (let ((case-fold-search t)
931 (string (copy-sequence (gethash field current-entry)))
932 (raw " ")
933 (multiline " ")
934 (matched nil))
935 ;; we have to do a couple of things now:
936 ;; - remove {} or "" around the string, if they're there
937 ;; - search for match-str
938 ;; - properly adjust the string if it's multiline
939 ;; but all this is not necessary if there was no string
940 (if (null string)
941 (let* ((xref (to-raw (gethash 'crossref current-entry)))
942 (xref-entry (ebib-retrieve-entry xref ebib-cur-db)))
943 (when xref-entry
944 (setq string (copy-sequence (gethash field xref-entry)))
945 (if string
946 (setq string (propertize (to-raw string) 'face 'ebib-crossref-face 'fontified t))
947 (setq string ""))))
948 (if (raw-p string)
949 (setq raw "*")
950 (setq string (to-raw string))) ; we have to make the string look nice
951 (when match-str
952 (multiple-value-setq (string matched) (match-all match-str string))))
953 (when (multiline-p string)
954 ;; IIUC PROPERTIZE shouldn't be necessary here, as the variable
955 ;; multiline is local and therefore the object it refers to should
956 ;; be GC'ed when the function returns. but for some reason, the
957 ;; plus sign is persistent, and if it's been highlighted as the
958 ;; result of a search, it stays that way.
959 (setq multiline (propertize "+" 'face nil))
960 (setq string (first-line string)))
961 (when (and matched
962 (string= multiline "+"))
963 (add-text-properties 0 1 '(face highlight) multiline))
964 (concat raw multiline string)))
966 (defun ebib-format-fields (entry fn &optional match-str)
967 (let* ((entry-type (gethash 'type* entry))
968 (obl-fields (ebib-get-obl-fields entry-type))
969 (opt-fields (ebib-get-opt-fields entry-type)))
970 (funcall fn (format "%-19s %s\n" "type" entry-type))
971 (mapc #'(lambda (fields)
972 (funcall fn "\n")
973 (mapcar #'(lambda (field)
974 (unless (and (get field 'ebib-hidden)
975 ebib-hide-hidden-fields)
976 (funcall fn (format "%-17s " field))
977 (funcall fn (or
978 (ebib-get-field-highlighted field entry match-str)
979 ""))
980 (funcall fn "\n")))
981 fields))
982 (list obl-fields opt-fields ebib-additional-fields))))
984 (defun ebib-fill-entry-buffer (&optional match-str)
985 "Fills the entry buffer with the fields of the current entry.
986 MATCH-STRING is a regexp that will be highlighted when it occurs in the
987 field contents."
988 (set-buffer ebib-entry-buffer)
989 (with-buffer-writable
990 (erase-buffer)
991 (when (and ebib-cur-db ; do we have a database?
992 (edb-keys-list ebib-cur-db) ; does it contain entries?
993 (gethash (car (edb-cur-entry ebib-cur-db))
994 (edb-database ebib-cur-db))) ; does the current entry exist?
995 (ebib-format-fields (gethash (car (edb-cur-entry ebib-cur-db))
996 (edb-database ebib-cur-db)) 'insert match-str)
997 (setq ebib-current-field 'type*)
998 (setq ebib-cur-entry-hash (ebib-retrieve-entry (ebib-cur-entry-key) ebib-cur-db))
999 (goto-char (point-min))
1000 (ebib-set-fields-highlight))))
1001 ;; (skip-chars-forward "^ "))))
1003 (defun ebib-set-modified (mod &optional db)
1004 "Sets the modified flag of the database DB to MOD.
1005 If DB is nil, it defaults to the current database, and the
1006 modified flag of the index buffer is also (re)set. MOD must be
1007 either T or NIL."
1008 (unless db
1009 (setq db ebib-cur-db))
1010 (setf (edb-modified db) mod)
1011 (when (eq db ebib-cur-db)
1012 (with-current-buffer ebib-index-buffer
1013 (set-buffer-modified-p mod))))
1015 (defun ebib-modified-p ()
1016 "Checks if any of the databases in Ebib were modified.
1017 Returns the first modified database, or NIL if none was modified."
1018 (let ((db (car ebib-databases)))
1019 (while (and db
1020 (not (edb-modified db)))
1021 (setq db (next-elem db ebib-databases)))
1022 db))
1024 (defun ebib-create-new-database (&optional db)
1025 "Creates a new database instance and returns it.
1026 If DB is set to a database, the new database is a copy of DB."
1027 (let ((new-db
1028 (if (edb-p db)
1029 (copy-edb db)
1030 (make-edb))))
1031 (setq ebib-databases (append ebib-databases (list new-db)))
1032 new-db))
1034 (defun ebib-match-paren-forward (limit)
1035 "Moves forward to the closing parenthesis matching the opening parenthesis at POINT.
1036 This function handles parentheses () and braces {}. Does not
1037 search/move beyond LIMIT. Returns T if a matching parenthesis was
1038 found, NIL otherwise. If point was not at an opening parenthesis
1039 at all, NIL is returned and point is not moved. If point was at
1040 an opening parenthesis but no matching closing parenthesis was
1041 found, an error is logged and point is moved one character
1042 forward to allow parsing to continue."
1043 (cond
1044 ((eq (char-after) ?\{)
1045 (ebib-match-brace-forward limit))
1046 ((eq (char-after) ?\()
1047 ;; we wrap this in a condition-case because we need to log the error
1048 ;; message outside of the save-restriction, otherwise we get the wrong
1049 ;; line number.
1050 (condition-case nil
1051 (save-restriction
1052 (narrow-to-region (point) limit)
1053 ;; this is really a hack. we want to allow unbalanced parentheses in
1054 ;; field values (bibtex does), so we cannot use forward-list
1055 ;; here. for the same reason, looking for the matching paren by hand
1056 ;; is pretty complicated. however, balanced parentheses can only be
1057 ;; used to enclose entire entries (or @STRINGs or @PREAMBLEs) so we
1058 ;; can be pretty sure we'll find it right before the next @ at the
1059 ;; start of a line, or right before the end of the file.
1060 (re-search-forward "^@" nil 0)
1061 (skip-chars-backward "@ \n\t\f")
1062 (forward-char -1)
1063 (if (eq (char-after) ?\))
1065 (goto-char (1+ (point-min)))
1066 (error "")))
1067 (error (ebib-log 'error "Error in line %d: Matching closing parenthesis not found!" (line-number-at-pos))
1068 nil)))
1069 (t nil)))
1071 (defun ebib-match-delim-forward (limit)
1072 "Moves forward to the closing delimiter matching the opening delimiter at POINT.
1073 This function handles braces {} and double quotes \"\". Does not
1074 search/move beyond LIMIT. Returns T if a matching delimiter was
1075 found, NIL otherwise. If point was not at an opening delimiter at
1076 all, NIL is returned and point is not moved. If point was at an
1077 opening delimiter but no matching closing delimiter was found, an
1078 error is logged and point is moved one character forward to allow
1079 parsing to continue."
1080 (cond
1081 ((eq (char-after) ?\")
1082 (ebib-match-quote-forward limit))
1083 ((eq (char-after) ?\{)
1084 (ebib-match-brace-forward limit))
1085 (t nil)))
1087 (defun ebib-match-brace-forward (limit)
1088 "Moves forward to the closing brace matching the opening brace at POINT.
1089 Does not search/move beyond LIMIT. Returns T if a matching brace
1090 was found, NIL otherwise. If point was not at an opening brace at
1091 all, NIL is returned and point is not moved. If point was at an
1092 opening brace but no matching closing brace was found, an error
1093 is logged and point is moved one character forward to allow
1094 parsing to continue."
1095 (when (eq (char-after) ?\{) ; make sure we're really on a brace, otherwise return nil
1096 (condition-case nil
1097 (save-restriction
1098 (narrow-to-region (point) limit)
1099 (progn
1100 (forward-list)
1101 ;; all of ebib expects that point moves to the closing
1102 ;; parenthesis, not right after it, so we adjust.
1103 (forward-char -1)
1104 t)) ; return t because a matching brace was found
1105 (error (progn
1106 (ebib-log 'error "Error in line %d: Matching closing brace not found!" (line-number-at-pos))
1107 (forward-char 1)
1108 nil)))))
1110 (defun ebib-match-quote-forward (limit)
1111 "Moves to the closing double quote matching the quote at POINT.
1112 Does not search/move beyond LIMIT. Returns T if a matching quote
1113 was found, NIL otherwise. If point was not at a double quote at
1114 all, NIL is returned and point is not moved. If point was at a
1115 quote but no matching closing quote was found, an error is logged
1116 and point is moved one character forward to allow parsing to
1117 continue."
1118 (when (eq (char-after (point)) ?\") ; make sure we're on a double quote.
1119 (condition-case nil
1120 (save-restriction
1121 (narrow-to-region (point) limit)
1122 (while (progn
1123 (forward-char) ; move forward because we're on a double quote
1124 (skip-chars-forward "^\"") ; search the next double quote
1125 (eq (char-before) ?\\))) ; if it's preceded by a backslash, keep on searching
1126 (or (eq (char-after) ?\")
1127 (progn
1128 (goto-char (1+ (point-min)))
1129 (error ""))))
1130 (error (ebib-log 'error "Error in line %d: Matching closing quote not found!" (line-number-at-pos))
1131 nil))))
1133 (defun ebib-insert-entry (entry-key fields db &optional sort timestamp)
1134 "Stores the entry defined by ENTRY-KEY and FIELDS into DB.
1135 Optional argument SORT indicates whether the KEYS-LIST must be
1136 sorted after insertion. Default is NIL. Optional argument
1137 TIMESTAMP indicates whether a timestamp is to be added to the
1138 entry. Note that for a timestamp to be added, EBIB-USE-TIMESTAMP
1139 must also be set to T."
1140 (when (and timestamp ebib-use-timestamp)
1141 (puthash 'timestamp (from-raw (format-time-string ebib-timestamp-format)) fields))
1142 (puthash entry-key fields (edb-database db))
1143 (ebib-set-modified t db)
1144 (setf (edb-n-entries db) (1+ (edb-n-entries db)))
1145 (setf (edb-keys-list db)
1146 (if sort
1147 (sort (cons entry-key (edb-keys-list db)) 'string<)
1148 (cons entry-key (edb-keys-list db)))))
1150 (defun ebib-insert-string (abbr string db &optional sort)
1151 "Stores the @STRING definition defined by ABBR and STRING into DB.
1152 Optional argument SORT indicates whether the STRINGS-LIST must be sorted
1153 after insertion. When loading or merging a file, for example, it is more
1154 economic to sort KEYS-LIST manually after all entries in the file have been
1155 added."
1156 (puthash abbr (from-raw string) (edb-strings db))
1157 (ebib-set-modified t db)
1158 (setf (edb-strings-list db)
1159 (if sort
1160 (sort (cons abbr (edb-strings-list db)) 'string<)
1161 (cons abbr (edb-strings-list db)))))
1163 (defun ebib-search-key-in-buffer (entry-key)
1164 "Searches ENTRY-KEY in the index buffer.
1165 Moves point to the first character of the key and returns point."
1166 (goto-char (point-min))
1167 (re-search-forward (concat "^" entry-key))
1168 (beginning-of-line)
1169 (point))
1171 ;; when we sort entries, we either use string< on the entry keys, or
1172 ;; ebib-entry<, if the user has defined a sort order.
1174 (defun ebib-entry< (x y)
1175 "Returns T if entry X is smaller than entry Y.
1176 The entries are compared based on the fields listed in EBIB-SORT-ORDER. X
1177 and Y should be keys of entries in the current database."
1178 (let* ((sort-list ebib-sort-order)
1179 (sortstring-x (to-raw (ebib-get-sortstring x (car sort-list))))
1180 (sortstring-y (to-raw (ebib-get-sortstring y (car sort-list)))))
1181 (while (and sort-list
1182 (string= sortstring-x sortstring-y))
1183 (setq sort-list (cdr sort-list))
1184 (setq sortstring-x (to-raw (ebib-get-sortstring x (car sort-list))))
1185 (setq sortstring-y (to-raw (ebib-get-sortstring y (car sort-list)))))
1186 (if (and sortstring-x sortstring-y)
1187 (string< sortstring-x sortstring-y)
1188 (string< x y))))
1190 (defun ebib-get-sortstring (entry-key sortkey-list)
1191 "Returns the field value on which the entry ENTRY-KEY is to be sorted.
1192 ENTRY-KEY must be the key of an entry in the current database. SORTKEY-LIST
1193 is a list of fields that are considered in order for the sort value."
1194 (let ((sort-string nil))
1195 (while (and sortkey-list
1196 (null (setq sort-string (gethash (car sortkey-list)
1197 (ebib-retrieve-entry entry-key ebib-cur-db)))))
1198 (setq sortkey-list (cdr sortkey-list)))
1199 sort-string))
1201 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1202 ;; main program execution ;;
1203 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1205 ;;;###autoload
1206 (defun ebib (&optional key)
1207 "Ebib, a BibTeX database manager.
1208 Optional argument key specifies the entry of the current database
1209 that is to be displayed."
1210 (interactive)
1211 (if (or (equal (window-buffer) ebib-index-buffer)
1212 (equal (window-buffer) ebib-entry-buffer))
1213 (error "Ebib already active")
1214 ;; we save the buffer from which ebib is called
1215 (setq ebib-push-buffer (current-buffer))
1216 ;; initialize ebib if required
1217 (unless ebib-initialized
1218 (ebib-init)
1219 (if ebib-preload-bib-files
1220 (mapc #'(lambda (file)
1221 (ebib-load-bibtex-file file))
1222 ebib-preload-bib-files)))
1223 ;; if ebib is visible, we just switch to the index buffer
1224 (let ((index-window (get-buffer-window ebib-index-buffer)))
1225 (if index-window
1226 (select-window index-window nil)
1227 (ebib-setup-windows)))
1228 ;; if ebib is called with an argument, we look for it
1229 (when key
1230 (let ((exists? (member key (edb-keys-list ebib-cur-db))))
1231 (if exists?
1232 (progn
1233 (setf (edb-cur-entry ebib-cur-db) exists?)
1234 (set-buffer ebib-index-buffer)
1235 (goto-char (point-min))
1236 (re-search-forward (format "^%s " (ebib-cur-entry-key)))
1237 (ebib-select-entry))
1238 (message "No entry `%s' in current database " key))))))
1240 (defun ebib-setup-windows ()
1241 "Creates the window configuration we want for Ebib in the
1242 current window."
1243 ;; we save the current window configuration.
1244 (setq ebib-saved-window-config (current-window-configuration))
1245 (if (eq ebib-layout 'full)
1246 (delete-other-windows)
1247 (setq ebib-pre-ebib-window (selected-window))
1248 (let ((ebib-window (split-window (selected-window) (- (window-width) ebib-width) t)))
1249 (select-window ebib-window nil)))
1250 (let* ((index-window (selected-window))
1251 (entry-window (split-window index-window ebib-index-window-size)))
1252 (switch-to-buffer ebib-index-buffer)
1253 (set-window-buffer entry-window ebib-entry-buffer)
1254 (unless (eq ebib-layout 'full)
1255 (set-window-dedicated-p index-window t)
1256 (set-window-dedicated-p entry-window t))))
1258 (defun ebib-init ()
1259 "Initialises Ebib.
1260 This function sets all variables to their initial values, creates the
1261 buffers and reads the rc file."
1262 (setq ebib-cur-entry-hash nil
1263 ebib-current-field nil
1264 ebib-minibuf-hist nil
1265 ebib-saved-window-config nil)
1266 (put 'timestamp 'ebib-hidden t)
1267 (load "~/.ebibrc" t)
1268 (ebib-create-buffers)
1269 (setq ebib-index-highlight (ebib-make-highlight 1 1 ebib-index-buffer))
1270 (setq ebib-fields-highlight (ebib-make-highlight 1 1 ebib-entry-buffer))
1271 (setq ebib-strings-highlight (ebib-make-highlight 1 1 ebib-strings-buffer))
1272 (setq ebib-initialized t))
1274 (defun ebib-create-buffers ()
1275 "Creates the buffers for Ebib."
1276 ;; first we create a buffer for multiline editing. this one does *not*
1277 ;; have a name beginning with a space, because undo-info is normally
1278 ;; present in an edit buffer.
1279 (setq ebib-multiline-buffer (get-buffer-create "*Ebib-edit*"))
1280 (set-buffer ebib-multiline-buffer)
1281 (funcall ebib-multiline-major-mode)
1282 (ebib-multiline-mode t)
1283 ;; then we create a buffer to hold the fields of the current entry.
1284 (setq ebib-entry-buffer (get-buffer-create " *Ebib-entry*"))
1285 (set-buffer ebib-entry-buffer)
1286 (ebib-entry-mode)
1287 ;; then we create a buffer to hold the @STRING definitions
1288 (setq ebib-strings-buffer (get-buffer-create " *Ebib-strings*"))
1289 (set-buffer ebib-strings-buffer)
1290 (ebib-strings-mode)
1291 ;; the log buffer
1292 (setq ebib-log-buffer (get-buffer-create " *Ebib-log*"))
1293 (set-buffer ebib-log-buffer)
1294 (erase-buffer)
1295 (insert "Ebib log messages\n\n(Press C-v or SPACE to scroll down, M-v or `b' to scroll up, `q' to quit.)\n\n\n")
1296 (ebib-log-mode)
1297 ;; and lastly we create a buffer for the entry keys.
1298 (setq ebib-index-buffer (get-buffer-create " none"))
1299 (set-buffer ebib-index-buffer)
1300 (ebib-index-mode))
1302 (defun ebib-quit ()
1303 "Quits Ebib.
1304 The Ebib buffers are killed, all variables except the keymaps are set to nil."
1305 (interactive)
1306 (when (if (ebib-modified-p)
1307 (yes-or-no-p "There are modified databases. Quit anyway? ")
1308 (y-or-n-p "Quit Ebib? "))
1309 (mapc #'(lambda (buffer)
1310 (kill-buffer buffer))
1311 (list ebib-entry-buffer
1312 ebib-index-buffer
1313 ebib-strings-buffer
1314 ebib-multiline-buffer
1315 ebib-log-buffer))
1316 (setq ebib-databases nil
1317 ebib-index-buffer nil
1318 ebib-entry-buffer nil
1319 ebib-initialized nil
1320 ebib-index-highlight nil
1321 ebib-fields-highlight nil
1322 ebib-strings-highlight nil
1323 ebib-export-filename nil
1324 ebib-pre-ebib-window nil)
1325 (set-window-configuration ebib-saved-window-config)
1326 (message "")))
1328 (defun ebib-kill-emacs-query-function ()
1329 "Ask if the user wants to save the database loaded in Ebib when Emacs is
1330 killed and the database has been modified."
1331 (if (not (ebib-modified-p))
1333 (if (y-or-n-p "Save all unsaved Ebib databases? ")
1334 (progn
1335 (ebib-save-all-databases)
1337 (yes-or-no-p "Ebib database was modified. Kill anyway? "))))
1339 (add-hook 'kill-emacs-query-functions 'ebib-kill-emacs-query-function)
1341 ;;;;;;;;;;;;;;;;
1342 ;; index-mode ;;
1343 ;;;;;;;;;;;;;;;;
1345 (eval-and-compile
1346 (define-prefix-command 'ebib-prefix-map)
1347 (suppress-keymap ebib-prefix-map)
1348 (defvar ebib-prefixed-functions '(ebib-delete-entry
1349 ebib-latex-entries
1350 ebib-mark-entry
1351 ebib-print-entries
1352 ebib-push-bibtex-key
1353 ebib-export-entry)))
1355 ;; macro to redefine key bindings.
1357 (defmacro ebib-key (buffer key &optional command)
1358 (cond
1359 ((eq buffer 'index)
1360 (let ((one `(define-key ebib-index-mode-map ,key (quote ,command)))
1361 (two (when (or (null command)
1362 (member command ebib-prefixed-functions))
1363 `(define-key ebib-prefix-map ,key (quote ,command)))))
1364 (if two
1365 `(progn ,one ,two)
1366 one)))
1367 ((eq buffer 'entry)
1368 `(define-key ebib-entry-mode-map ,key (quote ,command)))
1369 ((eq buffer 'strings)
1370 `(define-key ebib-strings-mode-map ,key (quote ,command)))
1371 ((eq buffer 'mark-prefix)
1372 `(progn
1373 (define-key ebib-index-mode-map (format "%c" ebib-prefix-key) nil)
1374 (define-key ebib-index-mode-map ,key 'ebib-prefix-map)
1375 (setq ebib-prefix-key (string-to-char ,key))))
1376 ((eq buffer 'multiline)
1377 `(progn
1378 (define-key ebib-multiline-mode-map "\C-c" nil)
1379 (mapc #'(lambda (command)
1380 (define-key ebib-multiline-mode-map (format "\C-c%s%c" ,key (car command)) (cdr command)))
1381 '((?q . ebib-quit-multiline-edit)
1382 (?c . ebib-cancel-multiline-edit)
1383 (?s . ebib-save-from-multiline-edit)))
1384 (setq ebib-multiline-key (string-to-char ,key))))))
1386 (defvar ebib-index-mode-map
1387 (let ((map (make-keymap)))
1388 (suppress-keymap map)
1389 map)
1390 "Keymap for the ebib index buffer.")
1392 ;; we define the keys with ebib-key rather than with define-key, because
1393 ;; that automatically sets up ebib-prefix-map as well.
1394 (ebib-key index [up] ebib-prev-entry)
1395 (ebib-key index [down] ebib-next-entry)
1396 (ebib-key index [right] ebib-next-database)
1397 (ebib-key index [left] ebib-prev-database)
1398 (ebib-key index [prior] ebib-index-scroll-down)
1399 (ebib-key index [next] ebib-index-scroll-up)
1400 (ebib-key index [home] ebib-goto-first-entry)
1401 (ebib-key index [end] ebib-goto-last-entry)
1402 (ebib-key index [return] ebib-select-entry)
1403 (ebib-key index " " ebib-index-scroll-up)
1404 (ebib-key index "/" ebib-search)
1405 (ebib-key index "&" ebib-virtual-db-and)
1406 (ebib-key index "|" ebib-virtual-db-or)
1407 (ebib-key index "~" ebib-virtual-db-not)
1408 (ebib-key index ";" ebib-prefix-map)
1409 (ebib-key index "a" ebib-add-entry)
1410 (ebib-key index "b" ebib-index-scroll-down)
1411 (ebib-key index "c" ebib-close-database)
1412 (ebib-key index "d" ebib-delete-entry)
1413 (ebib-key index "e" ebib-edit-entry)
1414 (ebib-key index "E" ebib-edit-keyname)
1415 (ebib-key index "f" ebib-view-file)
1416 (ebib-key index "F" ebib-follow-crossref)
1417 (ebib-key index "g" ebib-goto-first-entry)
1418 (ebib-key index "G" ebib-goto-last-entry)
1419 (ebib-key index "h" ebib-index-help)
1420 (ebib-key index "j" ebib-next-entry)
1421 (ebib-key index "J" ebib-switch-to-database)
1422 (ebib-key index "k" ebib-prev-entry)
1423 (ebib-key index "l" ebib-show-log)
1424 (ebib-key index "m" ebib-mark-entry)
1425 (ebib-key index "n" ebib-search-next)
1426 (ebib-key index "N" ebib-search-crossref)
1427 (ebib-key index [(control n)] ebib-next-entry)
1428 (ebib-key index [(meta n)] ebib-index-scroll-up)
1429 (ebib-key index "o" ebib-load-bibtex-file)
1430 (ebib-key index "p" ebib-push-bibtex-key)
1431 (ebib-key index [(control p)] ebib-prev-entry)
1432 (ebib-key index [(meta p)] ebib-index-scroll-down)
1433 (ebib-key index "P" ebib-edit-preamble)
1434 (ebib-key index "q" ebib-quit)
1435 (ebib-key index "s" ebib-save-current-database)
1436 (ebib-key index "S" ebib-edit-strings)
1437 (ebib-key index "u" ebib-browse-url)
1438 (ebib-key index "V" ebib-print-filter)
1439 (ebib-key index "x" ebib-export-entry)
1440 (ebib-key index "\C-xb" ebib-leave-ebib-windows)
1441 (ebib-key index "\C-xk" ebib-quit)
1442 (ebib-key index "X" ebib-export-preamble)
1443 (ebib-key index "z" ebib-leave-ebib-windows)
1444 (ebib-key index "Z" ebib-lower)
1446 (defun ebib-switch-to-database-nth (key)
1447 (interactive (list (if (featurep 'xemacs)
1448 (event-key last-command-event)
1449 last-command-event)))
1450 (ebib-switch-to-database (- (if (featurep 'xemacs)
1451 (char-to-int key)
1452 key) 48)))
1454 (mapc #'(lambda (key)
1455 (define-key ebib-index-mode-map (format "%d" key)
1456 'ebib-switch-to-database-nth))
1457 '(1 2 3 4 5 6 7 8 9))
1459 (define-derived-mode ebib-index-mode
1460 fundamental-mode "Ebib-index"
1461 "Major mode for the Ebib index buffer."
1462 (setq buffer-read-only t)
1463 (setq truncate-lines t))
1465 (easy-menu-define ebib-index-menu ebib-index-mode-map "Ebib index menu"
1466 '("Ebib"
1467 ["Open Database..." ebib-load-bibtex-file t]
1468 ["Merge Database..." ebib-merge-bibtex-file (and ebib-cur-db (not (edb-virtual ebib-cur-db)))]
1469 ["Save Database" ebib-save-current-database (and ebib-cur-db
1470 (edb-modified ebib-cur-db))]
1471 ["Save All Databases" ebib-save-all-databases (ebib-modified-p)]
1472 ["Save Database As..." ebib-write-database ebib-cur-db]
1473 ["Close Database" ebib-close-database ebib-cur-db]
1474 "--"
1475 ("Entry"
1476 ["Add" ebib-add-entry (and ebib-cur-db (not (edb-virtual ebib-cur-db)))]
1477 ["Edit" ebib-edit-entry (and ebib-cur-db
1478 (edb-cur-entry ebib-cur-db)
1479 (not (edb-virtual ebib-cur-db)))]
1480 ["Delete" ebib-delete-entry (and ebib-cur-db
1481 (edb-cur-entry ebib-cur-db)
1482 (not (edb-virtual ebib-cur-db)))])
1483 ["Edit Strings" ebib-edit-strings (and ebib-cur-db (not (edb-virtual ebib-cur-db)))]
1484 ["Edit Preamble" ebib-edit-preamble (and ebib-cur-db (not (edb-virtual ebib-cur-db)))]
1485 "--"
1486 ["Open URL" ebib-browse-url (gethash ebib-standard-url-field ebib-cur-entry-hash)]
1487 ["View File" ebib-view-file (gethash ebib-standard-file-field ebib-cur-entry-hash)]
1488 ("Print Entries"
1489 ["As Bibliography" ebib-latex-entries (and ebib-cur-db (not (edb-virtual ebib-cur-db)))]
1490 ["As Index Cards" ebib-print-entries ebib-cur-db]
1491 ["Print Multiline Fields" ebib-toggle-print-multiline :enable t
1492 :style toggle :selected ebib-print-multiline]
1493 ["Print Cards on Separate Pages" ebib-toggle-print-newpage :enable t
1494 :style toggle :selected ebib-print-newpage])
1495 "--"
1496 ("Options"
1497 ["Show Hidden Fields" ebib-toggle-hidden :enable t
1498 :style toggle :selected (not ebib-hide-hidden-fields)]
1499 ["Use Timestamp" ebib-toggle-timestamp :enable t
1500 :style toggle :selected ebib-use-timestamp]
1501 ["Save Cross-Referenced Entries First" ebib-toggle-xrefs-first :enable t
1502 :style toggle :selected ebib-save-xrefs-first]
1503 ["Allow Identical Fields" ebib-toggle-identical-fields :enable t
1504 :style toggle :selected ebib-allow-identical-fields]
1505 ["Full Layout" ebib-toggle-layout :enable t
1506 :style toggle :selected (eq ebib-layout 'full)]
1507 ["Modify Entry Types" ebib-customize-entry-types t]
1508 ["Customize Ebib" ebib-customize t])
1509 ["View Log Buffer" ebib-show-log t]
1510 ["Lower Ebib" ebib-lower t]
1511 ["Quit" ebib-quit t]
1512 ["Help on Ebib" ebib-info t]))
1514 (easy-menu-add ebib-index-menu ebib-index-mode-map)
1516 (defun ebib-fill-index-buffer ()
1517 "Fills the index buffer with the list of keys in EBIB-CUR-DB.
1518 If EBIB-CUR-DB is nil, the buffer is just erased and its name set
1519 to \"none\"."
1520 (set-buffer ebib-index-buffer)
1521 (let ((buffer-read-only nil))
1522 (erase-buffer)
1523 (if ebib-cur-db
1524 (progn
1525 ;; we may call this function when there are no entries in the
1526 ;; database. if so, we don't need to do this:
1527 (when (edb-cur-entry ebib-cur-db)
1528 (mapc #'(lambda (entry)
1529 (ebib-display-entry entry)
1530 (when (member entry (edb-marked-entries ebib-cur-db))
1531 (save-excursion
1532 (let ((beg (progn
1533 (beginning-of-line)
1534 (point))))
1535 (skip-chars-forward "^ ")
1536 (add-text-properties beg (point) '(face ebib-marked-face))))))
1537 (edb-keys-list ebib-cur-db))
1538 (goto-char (point-min))
1539 (re-search-forward (format "^%s " (ebib-cur-entry-key)))
1540 (beginning-of-line)
1541 (ebib-set-index-highlight))
1542 (set-buffer-modified-p (edb-modified ebib-cur-db))
1543 (rename-buffer (concat (format " %d:" (1+ (- (length ebib-databases)
1544 (length (member ebib-cur-db ebib-databases)))))
1545 (edb-name ebib-cur-db))))
1546 (rename-buffer " none"))))
1548 (defun ebib-customize ()
1549 "Switches to Ebib's customisation group."
1550 (interactive)
1551 (ebib-lower)
1552 (customize-group 'ebib))
1554 (defun ebib-customize-entry-types ()
1555 "Customizes EBIB-ENTRY-TYPES."
1556 (interactive)
1557 (ebib-lower)
1558 (customize-variable 'ebib-entry-types))
1560 (defun ebib-log (type format-string &rest args)
1561 "Writes a message to Ebib's log buffer.
1562 TYPE (a symbol) is the type of message. It can be LOG, which
1563 writes the message to the log buffer only; MESSAGE, which writes
1564 the message to the log buffer and outputs it with the function
1565 MESSAGE; WARNING, which logs the message and sets the variable
1566 EBIB-LOG-ERROR to 0; or ERROR, which logs the message and sets
1567 the variable EBIB-LOG-ERROR to 1. The latter two can be used to
1568 signal the user to check the log for warnings or errors."
1569 (with-current-buffer ebib-log-buffer
1570 (cond
1571 ((eq type 'warning)
1572 (or ebib-log-error ; if ebib-error-log is already set to 1, we don't want to overwrite it!
1573 (setq ebib-log-error 0)))
1574 ((eq type 'error)
1575 (setq ebib-log-error 1))
1576 ((eq type 'message)
1577 (apply 'message format-string args)))
1578 (insert (apply 'format (concat format-string "\n") args))))
1580 (defun ebib-load-bibtex-file (&optional file)
1581 "Loads a BibTeX file into Ebib."
1582 (interactive)
1583 (unless file
1584 (setq file (ensure-extension (read-file-name "File to open: " "~/") "bib")))
1585 (setq ebib-cur-db (ebib-create-new-database))
1586 (setf (edb-filename ebib-cur-db) (expand-file-name file))
1587 (setf (edb-name ebib-cur-db) (file-name-nondirectory (edb-filename ebib-cur-db)))
1588 (setq ebib-log-error nil) ; we haven't found any errors
1589 (ebib-log 'log "%s: Opening file %s" (format-time-string "%d %b %Y, %H:%M:%S") (edb-filename ebib-cur-db))
1590 ;; first, we empty the buffers
1591 (ebib-erase-buffer ebib-index-buffer)
1592 (ebib-erase-buffer ebib-entry-buffer)
1593 (if (file-readable-p file)
1594 ;; if the user entered the name of an existing file, we load it
1595 ;; by putting it in a buffer and then parsing it.
1596 (with-temp-buffer
1597 (with-syntax-table ebib-syntax-table
1598 (insert-file-contents file)
1599 ;; if the user makes any changes, we'll want to create a back-up.
1600 (setf (edb-make-backup ebib-cur-db) t)
1601 (let ((result (ebib-find-bibtex-entries nil)))
1602 (setf (edb-n-entries ebib-cur-db) (car result))
1603 (when (edb-keys-list ebib-cur-db)
1604 (setf (edb-keys-list ebib-cur-db) (sort (edb-keys-list ebib-cur-db) 'string<)))
1605 (when (edb-strings-list ebib-cur-db)
1606 (setf (edb-strings-list ebib-cur-db) (sort (edb-strings-list ebib-cur-db) 'string<)))
1607 (setf (edb-cur-entry ebib-cur-db) (edb-keys-list ebib-cur-db))
1608 ;; and fill the buffers. note that filling a buffer also makes
1609 ;; that buffer active. therefore we do EBIB-FILL-INDEX-BUFFER
1610 ;; later.
1611 (ebib-set-modified nil)
1612 (ebib-fill-entry-buffer)
1613 ;; and now we tell the user the result
1614 (ebib-log 'message "%d entries, %d @STRINGs and %s @PREAMBLE found in file."
1615 (car result)
1616 (cadr result)
1617 (if (caddr result)
1619 "no")))))
1620 ;; if the file does not exist, we need to issue a message.
1621 (ebib-log 'message "(New file)"))
1622 ;; what we have to do in *any* case, is fill the index buffer. (this
1623 ;; even works if there are no keys in the database, e.g. when the
1624 ;; user opened a new file or if no BibTeX entries were found.
1625 (ebib-fill-index-buffer)
1626 (when ebib-log-error
1627 (message "%s found! Press `l' to check Ebib log buffer." (nth ebib-log-error '("Warnings" "Errors"))))
1628 (ebib-log 'log "\n\f\n"))
1630 (defun ebib-merge-bibtex-file ()
1631 "Merges a BibTeX file into the database."
1632 (interactive)
1633 (unless (edb-virtual ebib-cur-db)
1634 (if (not ebib-cur-db)
1635 (error "No database loaded. Use `o' to open a database")
1636 (let ((file (read-file-name "File to merge: ")))
1637 (setq ebib-log-error nil) ; we haven't found any errors
1638 (ebib-log 'log "%s: Merging file %s" (format-time-string "%d-%b-%Y: %H:%M:%S") (edb-filename ebib-cur-db))
1639 (with-temp-buffer
1640 (with-syntax-table ebib-syntax-table
1641 (insert-file-contents file)
1642 (let ((n (ebib-find-bibtex-entries t)))
1643 (setf (edb-keys-list ebib-cur-db) (sort (edb-keys-list ebib-cur-db) 'string<))
1644 (setf (edb-n-entries ebib-cur-db) (length (edb-keys-list ebib-cur-db)))
1645 (when (edb-strings-list ebib-cur-db)
1646 (setf (edb-strings-list ebib-cur-db) (sort (edb-strings-list ebib-cur-db) 'string<)))
1647 (setf (edb-cur-entry ebib-cur-db) (edb-keys-list ebib-cur-db))
1648 (ebib-fill-entry-buffer)
1649 (ebib-fill-index-buffer)
1650 (ebib-set-modified t)
1651 (ebib-log 'message "%d entries, %d @STRINGs and %s @PREAMBLE found in file."
1652 (car n)
1653 (cadr n)
1654 (if (caddr n)
1656 "no"))
1657 (when ebib-log-error
1658 (message "%s found! Press `l' to check Ebib log buffer." (nth ebib-log-error '("Warnings" "Errors"))))
1659 (ebib-log 'log "\n\f\n"))))))))
1661 (defun ebib-find-bibtex-entries (timestamp)
1662 "Finds the BibTeX entries in the current buffer.
1663 The search is started at the beginnig of the buffer. All entries
1664 found are stored in the hash table DATABASE of
1665 EBIB-CUR-DB. Returns a three-element list: the first element is
1666 the number of entries found, the second the number of @STRING
1667 definitions, and the third is T or NIL, indicating whether a
1668 @PREAMBLE was found.
1670 TIMESTAMP indicates whether a timestamp is to be added to each
1671 entry. Note that a timestamp is only added if EBIB-USE-TIMESTAMP
1672 is set to T."
1673 (let ((n-entries 0)
1674 (n-strings 0)
1675 (preamble nil))
1676 (goto-char (point-min))
1677 (while (re-search-forward "^@" nil t) ; find the next entry
1678 (let ((beg (point)))
1679 (when (looking-at-goto-end (concat "\\(" ebib-bibtex-identifier "\\)[[:space:]]*[\(\{]") 1)
1680 (let ((entry-type (downcase (buffer-substring-no-properties beg (point)))))
1681 (looking-at-goto-end "[[:space:]]*[\(\{]")
1682 (cond
1683 ((equal entry-type "string") ; string and preamble must be treated differently
1684 (if (ebib-read-string)
1685 (setq n-strings (1+ n-strings))))
1686 ((equal entry-type "preamble")
1687 (when (ebib-read-preamble)
1688 (setq preamble t)))
1689 ((equal entry-type "comment") ; ignore comments
1690 (ebib-log 'log "Comment at line %d ignored" (line-number-at-pos))
1691 (ebib-match-paren-forward (point-max)))
1692 ((assoc (intern-soft entry-type) ebib-entry-types) ; if the entry type has been defined
1693 (if (ebib-read-entry entry-type timestamp)
1694 (setq n-entries (1+ n-entries))))
1695 ;; anything else we report as an unknown entry type.
1696 (t (ebib-log 'warning "Line %d: Unknown entry type `%s'. Skipping." (line-number-at-pos) entry-type)
1697 (ebib-match-paren-forward (point-max))))))))
1698 (list n-entries n-strings preamble)))
1700 (defun ebib-read-string ()
1701 "Reads the @STRING definition beginning at the line POINT is on.
1702 If a proper abbreviation and string are found, they are stored in the
1703 database. Returns the string if one was read, nil otherwise."
1704 (let ((limit (save-excursion ; we find the matching end parenthesis
1705 (backward-char)
1706 (ebib-match-paren-forward (point-max))
1707 (point))))
1708 (skip-chars-forward "\"#%'(),={} \n\t\f" limit)
1709 (let ((beg (point)))
1710 (when (looking-at-goto-end (concat "\\(" ebib-bibtex-identifier "\\)[ \t\n\f]*=") 1)
1711 (if-str (abbr (buffer-substring-no-properties beg (point)))
1712 (progn
1713 (skip-chars-forward "^\"{" limit)
1714 (let ((beg (point)))
1715 (if-str (string (if (ebib-match-delim-forward limit)
1716 (buffer-substring-no-properties beg (1+ (point)))
1717 nil))
1718 (if (member abbr (edb-strings-list ebib-cur-db))
1719 (ebib-log 'warning (format "Line %d: @STRING definition `%s' duplicated. Skipping."
1720 (line-number-at-pos) abbr))
1721 (ebib-insert-string abbr string ebib-cur-db))))))))))
1723 (defun ebib-read-preamble ()
1724 "Reads the @PREAMBLE definition and stores it in EBIB-PREAMBLE.
1725 If there was already another @PREAMBLE definition, the new one is
1726 added to the existing one with a hash sign `#' between them."
1727 (let ((beg (point)))
1728 (forward-char -1)
1729 (when (ebib-match-paren-forward (point-max))
1730 (let ((text (buffer-substring-no-properties beg (point))))
1731 (if (edb-preamble ebib-cur-db)
1732 (setf (edb-preamble ebib-cur-db) (concat (edb-preamble ebib-cur-db) "\n# " text))
1733 (setf (edb-preamble ebib-cur-db) text))))))
1735 (defun ebib-read-entry (entry-type &optional timestamp)
1736 "Reads a BibTeX entry and stores it in DATABASE of EBIB-CUR-DB.
1737 Returns the new EBIB-KEYS-LIST if an entry was found, nil
1738 otherwise. Optional argument TIMESTAMP indicates whether a
1739 timestamp is to be added. (Whether a timestamp is actually added,
1740 also depends on EBIB-USE-TIMESTAMP.)"
1741 (let ((entry-limit (save-excursion
1742 (backward-char)
1743 (ebib-match-paren-forward (point-max))
1744 (point)))
1745 (beg (progn
1746 (skip-chars-forward " \n\t\f") ; note the space!
1747 (point))))
1748 (when (looking-at-goto-end (concat "\\("
1749 ebib-bibtex-identifier
1750 "\\)[ \t\n\f]*,")
1751 1) ; this delimits the entry key
1752 (let ((entry-key (buffer-substring-no-properties beg (point))))
1753 (if (member entry-key (edb-keys-list ebib-cur-db))
1754 (ebib-log 'warning "Line %d: Entry `%s' duplicated. Skipping." (line-number-at-pos) entry-key)
1755 (let ((fields (ebib-find-bibtex-fields (intern-soft entry-type) entry-limit)))
1756 (when fields ; if fields were found, we store them, and return T.
1757 (ebib-insert-entry entry-key fields ebib-cur-db nil timestamp)
1758 t)))))))
1760 (defun ebib-find-bibtex-fields (entry-type limit)
1761 "Finds the fields of the BibTeX entry that starts on the line POINT is on.
1762 Returns a hash table containing all the fields and values, or NIL
1763 if none were found. ENTRY-TYPE is the type of the entry, which
1764 will be recorded in the hash table. Before the search starts,
1765 POINT is moved back to the beginning of the line."
1766 (beginning-of-line)
1767 ;; we assign a function to fn in order to avoid putting the test on
1768 ;; ebib-allow-identical-fields in the while loop, where it would get
1769 ;; tested with every field being read.
1770 (let ((fn (if (not ebib-allow-identical-fields)
1771 (symbol-function 'puthash)
1772 #'(lambda (field-type field-contents fields)
1773 (let ((existing-contents (gethash field-type fields)))
1774 (puthash field-type (if existing-contents
1775 (from-raw (concat (to-raw existing-contents)
1776 "; "
1777 (to-raw field-contents)))
1778 field-contents)
1779 fields))))))
1780 (let ((fields (make-hash-table :size 15)))
1781 (while (progn
1782 (skip-chars-forward "^," limit) ; we must move to the next comma,
1783 (eq (char-after) ?,)) ; and make sure we are really on a comma.
1784 (skip-chars-forward "\"#%'(),={} \n\t\f" limit)
1785 (let ((beg (point)))
1786 (when (looking-at-goto-end (concat "\\(" ebib-bibtex-identifier "\\)[ \t\n\f]*=") 1)
1787 (let ((field-type (intern (downcase (buffer-substring-no-properties beg (point))))))
1788 (unless (eq field-type 'type*) ; the 'type*' key holds the entry type, so we can't use it
1789 (let ((field-contents (ebib-read-field-contents limit)))
1790 (when field-contents
1791 (funcall fn field-type field-contents fields))))))))
1792 (when (> (hash-table-count fields) 0)
1793 (puthash 'type* entry-type fields)
1794 fields))))
1796 (defun ebib-read-field-contents (limit)
1797 "Reads the contents of a BibTeX field from a .bib file.
1798 LIMIT indicates the end of the entry, beyond which the function will not
1799 search."
1800 (skip-chars-forward "#%'(),=} \n\t\f" limit)
1801 (let ((beg (point)))
1802 (buffer-substring-no-properties beg (ebib-find-end-of-field limit))))
1804 (defun ebib-find-end-of-field (limit)
1805 "Moves POINT to the end of a field's contents and returns POINT.
1806 The contents of a field is delimited by a comma or by the closing brace of
1807 the entry. The latter is at position LIMIT."
1808 (while (and (not (eq (char-after) ?\,))
1809 (< (point) limit))
1810 (ebib-match-delim-forward limit) ; check if we're on a delimiter and if so, jump to the matching closing delimiter
1811 (forward-char 1))
1812 (if (= (point) limit)
1813 (skip-chars-backward " \n\t\f"))
1814 (point))
1816 (defun ebib-leave-ebib-windows ()
1817 "Leaves the Ebib windows, lowering them if necessary."
1818 (interactive)
1819 (ebib-lower t))
1821 (defun ebib-lower (&optional soft)
1822 "Hides the Ebib windows.
1823 If optional argument SOFT is non-nil, just switch to a non-Ebib
1824 buffer if Ebib is not occupying the entire frame."
1825 (interactive)
1826 (unless (member (window-buffer) (list ebib-index-buffer
1827 ebib-entry-buffer
1828 ebib-strings-buffer
1829 ebib-multiline-buffer
1830 ebib-log-buffer))
1831 (error "Ebib is not active "))
1832 (if (and soft
1833 (not (eq ebib-layout 'full)))
1834 (select-window ebib-pre-ebib-window nil)
1835 (set-window-configuration ebib-saved-window-config))
1836 (mapc #'(lambda (buffer)
1837 (bury-buffer buffer))
1838 (list ebib-index-buffer
1839 ebib-entry-buffer
1840 ebib-strings-buffer
1841 ebib-multiline-buffer
1842 ebib-log-buffer)))
1844 (defun ebib-prev-entry ()
1845 "Moves to the previous BibTeX entry."
1846 (interactive)
1847 (ebib-execute-when
1848 ((entries)
1849 ;; if the current entry is the first entry,
1850 (if (eq (edb-cur-entry ebib-cur-db) (edb-keys-list ebib-cur-db))
1851 (beep) ; just beep.
1852 (setf (edb-cur-entry ebib-cur-db) (last (edb-keys-list ebib-cur-db)
1853 (1+ (length (edb-cur-entry ebib-cur-db)))))
1854 (goto-char (ebib-highlight-start ebib-index-highlight))
1855 (forward-line -1)
1856 (ebib-set-index-highlight)
1857 (ebib-fill-entry-buffer)))
1858 ((default)
1859 (beep))))
1861 (defun ebib-next-entry ()
1862 "Moves to the next BibTeX entry."
1863 (interactive)
1864 (ebib-execute-when
1865 ((entries)
1866 (if (= (length (edb-cur-entry ebib-cur-db)) 1) ; if we're on the last entry,
1867 (beep) ; just beep.
1868 (setf (edb-cur-entry ebib-cur-db)
1869 (last (edb-keys-list ebib-cur-db) (1- (length (edb-cur-entry ebib-cur-db)))))
1870 (goto-char (ebib-highlight-start ebib-index-highlight))
1871 (forward-line 1)
1872 (ebib-set-index-highlight)
1873 (ebib-fill-entry-buffer)))
1874 ((default)
1875 (beep))))
1877 (defun ebib-add-entry ()
1878 "Adds a new entry to the database."
1879 (interactive)
1880 (ebib-execute-when
1881 ((real-db)
1882 (if-str (entry-key (read-string "New entry key: "))
1883 (progn
1884 (if (member entry-key (edb-keys-list ebib-cur-db))
1885 (error "Key already exists")
1886 (set-buffer ebib-index-buffer)
1887 (sort-in-buffer (1+ (edb-n-entries ebib-cur-db)) entry-key)
1888 ;; we create the hash table *before* the call to
1889 ;; ebib-display-entry, because that function refers to the
1890 ;; hash table if ebib-index-display-fields is set.
1891 (let ((fields (make-hash-table)))
1892 (puthash 'type* ebib-default-type fields)
1893 (ebib-insert-entry entry-key fields ebib-cur-db t t))
1894 (with-buffer-writable
1895 (ebib-display-entry entry-key))
1896 (forward-line -1) ; move one line up to position the cursor on the new entry.
1897 (ebib-set-index-highlight)
1898 (setf (edb-cur-entry ebib-cur-db) (member entry-key (edb-keys-list ebib-cur-db)))
1899 (ebib-fill-entry-buffer)
1900 (ebib-edit-entry)
1901 (ebib-set-modified t)))))
1902 ((no-database)
1903 (error "No database open. Use `o' to open a database first"))
1904 ((default)
1905 (beep))))
1907 (defun ebib-close-database ()
1908 "Closes the current BibTeX database."
1909 (interactive)
1910 (ebib-execute-when
1911 ((database)
1912 (when (if (edb-modified ebib-cur-db)
1913 (yes-or-no-p "Database modified. Close it anyway? ")
1914 (y-or-n-p "Close database? "))
1915 (let ((to-be-deleted ebib-cur-db)
1916 (new-db (next-elem ebib-cur-db ebib-databases)))
1917 (setq ebib-databases (delete to-be-deleted ebib-databases))
1918 (if ebib-databases ; do we still have another database loaded?
1919 (progn
1920 (setq ebib-cur-db (or new-db
1921 (last1 ebib-databases)))
1922 (unless (edb-cur-entry ebib-cur-db)
1923 (setf (edb-cur-entry ebib-cur-db) (edb-keys-list ebib-cur-db)))
1924 (ebib-fill-entry-buffer)
1925 (ebib-fill-index-buffer))
1926 ;; otherwise, we have to clean up a little and empty all the buffers.
1927 (setq ebib-cur-db nil)
1928 (mapc #'(lambda (buf) ; this is just to avoid typing almost the same thing three times...
1929 (set-buffer (car buf))
1930 (with-buffer-writable
1931 (erase-buffer))
1932 (ebib-delete-highlight (cadr buf)))
1933 (list (list ebib-entry-buffer ebib-fields-highlight)
1934 (list ebib-index-buffer ebib-index-highlight)
1935 (list ebib-strings-buffer ebib-strings-highlight)))
1936 ;; multiline edit buffer
1937 (set-buffer ebib-multiline-buffer)
1938 (with-buffer-writable
1939 (erase-buffer))
1940 (set-buffer ebib-index-buffer)
1941 (rename-buffer " none"))
1942 (message "Database closed."))))))
1944 (defun ebib-goto-first-entry ()
1945 "Moves to the first BibTeX entry in the database."
1946 (interactive)
1947 (ebib-execute-when
1948 ((entries)
1949 (setf (edb-cur-entry ebib-cur-db) (edb-keys-list ebib-cur-db))
1950 (set-buffer ebib-index-buffer)
1951 (goto-char (point-min))
1952 (ebib-set-index-highlight)
1953 (ebib-fill-entry-buffer))
1954 ((default)
1955 (beep))))
1957 (defun ebib-goto-last-entry ()
1958 "Moves to the last entry in the BibTeX database."
1959 (interactive)
1960 (ebib-execute-when
1961 ((entries)
1962 (setf (edb-cur-entry ebib-cur-db) (last (edb-keys-list ebib-cur-db)))
1963 (set-buffer ebib-index-buffer)
1964 (goto-char (point-min))
1965 (forward-line (1- (edb-n-entries ebib-cur-db)))
1966 (ebib-set-index-highlight)
1967 (ebib-fill-entry-buffer))
1968 ((default)
1969 (beep))))
1971 (defun ebib-edit-entry ()
1972 "Edits the current BibTeX entry."
1973 (interactive)
1974 (ebib-execute-when
1975 ((real-db entries)
1976 (setq ebib-cur-entry-fields (ebib-get-all-fields (gethash 'type* ebib-cur-entry-hash)))
1977 (select-window (get-buffer-window ebib-entry-buffer) nil))
1978 ((default)
1979 (beep))))
1981 (defun ebib-edit-keyname ()
1982 "Changes the key of a BibTeX entry."
1983 (interactive)
1984 (ebib-execute-when
1985 ((real-db entries)
1986 (let ((cur-keyname (ebib-cur-entry-key)))
1987 (if-str (new-keyname (read-string (format "Change `%s' to: " cur-keyname)
1988 cur-keyname))
1989 (if (member new-keyname (edb-keys-list ebib-cur-db))
1990 (error (format "Key `%s' already exists" new-keyname))
1991 (unless (string= cur-keyname new-keyname)
1992 (let ((fields (ebib-retrieve-entry cur-keyname ebib-cur-db))
1993 (marked (member cur-keyname (edb-marked-entries ebib-cur-db))))
1994 (ebib-remove-entry-from-db cur-keyname ebib-cur-db)
1995 (ebib-remove-key-from-buffer cur-keyname)
1996 (ebib-insert-entry new-keyname fields ebib-cur-db t nil)
1997 (setf (edb-cur-entry ebib-cur-db) (member new-keyname (edb-keys-list ebib-cur-db)))
1998 (sort-in-buffer (edb-n-entries ebib-cur-db) new-keyname)
1999 (with-buffer-writable
2000 (ebib-display-entry new-keyname))
2001 (forward-line -1) ; move one line up to position the cursor on the new entry.
2002 (ebib-set-index-highlight)
2003 (ebib-set-modified t)
2004 (when marked (ebib-mark-entry))))))))
2005 ((default)
2006 (beep))))
2008 (defun ebib-mark-entry ()
2009 "Marks or unmarks the current entry."
2010 (interactive)
2011 (if (ebib-called-with-prefix)
2012 (ebib-execute-when
2013 ((marked-entries)
2014 (setf (edb-marked-entries ebib-cur-db) nil)
2015 (ebib-fill-index-buffer))
2016 ((entries)
2017 (setf (edb-marked-entries ebib-cur-db) (copy-sequence (edb-keys-list ebib-cur-db)))
2018 (ebib-fill-index-buffer))
2019 ((default)
2020 (beep)))
2021 (ebib-execute-when
2022 ((entries)
2023 (set-buffer ebib-index-buffer)
2024 (with-buffer-writable
2025 (if (member (ebib-cur-entry-key) (edb-marked-entries ebib-cur-db))
2026 (progn
2027 (setf (edb-marked-entries ebib-cur-db)
2028 (delete (ebib-cur-entry-key) (edb-marked-entries ebib-cur-db)))
2029 (remove-text-properties (ebib-highlight-start ebib-index-highlight)
2030 (ebib-highlight-end ebib-index-highlight)
2031 '(face ebib-marked-face)))
2032 (setf (edb-marked-entries ebib-cur-db) (sort (cons (ebib-cur-entry-key)
2033 (edb-marked-entries ebib-cur-db))
2034 'string<))
2035 (add-text-properties (ebib-highlight-start ebib-index-highlight)
2036 (ebib-highlight-end ebib-index-highlight)
2037 '(face ebib-marked-face)))))
2038 ((default)
2039 (beep)))))
2041 (defun ebib-index-scroll-down ()
2042 "Moves one page up in the database."
2043 (interactive)
2044 (ebib-execute-when
2045 ((entries)
2046 (scroll-down)
2047 (ebib-select-entry))
2048 ((default)
2049 (beep))))
2051 (defun ebib-index-scroll-up ()
2052 "Moves one page down in the database."
2053 (interactive)
2054 (ebib-execute-when
2055 ((entries)
2056 (scroll-up)
2057 (ebib-select-entry))
2058 ((default)
2059 (beep))))
2061 (defun ebib-format-entry (key db timestamp)
2062 "Formats entry KEY from database DB into the current buffer in BibTeX format.
2063 If TIMESTAMP is T, a timestamp is added to the entry if
2064 EBIB-USE-TIMESTAMP is T."
2065 (let ((entry (ebib-retrieve-entry key db)))
2066 (when entry
2067 (insert (format "@%s{%s,\n" (gethash 'type* entry) key))
2068 (maphash #'(lambda (key value)
2069 (unless (or (eq key 'type*)
2070 (and (eq key 'timestamp) timestamp ebib-use-timestamp))
2071 (insert (format "\t%s = %s,\n" key value))))
2072 entry)
2073 (if (and timestamp ebib-use-timestamp)
2074 (insert (format "\ttimestamp = {%s}" (format-time-string ebib-timestamp-format)))
2075 (delete-char -2)) ; the final ",\n" must be deleted
2076 (insert "\n}\n\n"))))
2078 (defun ebib-format-strings (db)
2079 "Formats the @STRING commands in database DB."
2080 (maphash #'(lambda (key value)
2081 (insert (format "@STRING{%s = %s}\n" key value)))
2082 (edb-strings db))
2083 (insert "\n"))
2085 (defun ebib-compare-xrefs (x y)
2086 (gethash 'crossref (ebib-retrieve-entry x ebib-cur-db)))
2088 (defun ebib-format-database (db)
2089 "Writes database DB into the current buffer in BibTeX format."
2090 (when (edb-preamble db)
2091 (insert (format "@PREAMBLE{%s}\n\n" (edb-preamble db))))
2092 (ebib-format-strings db)
2093 (let ((sorted-list (copy-tree (edb-keys-list db))))
2094 (cond
2095 (ebib-save-xrefs-first
2096 (setq sorted-list (sort sorted-list 'ebib-compare-xrefs)))
2097 (ebib-sort-order
2098 (setq sorted-list (sort sorted-list 'ebib-entry<))))
2099 (mapc #'(lambda (key) (ebib-format-entry key db nil)) sorted-list)))
2101 (defun ebib-save-database (db)
2102 "Saves the database DB."
2103 (ebib-execute-when
2104 ((real-db)
2105 (when (and (edb-make-backup db)
2106 (file-exists-p (edb-filename db)))
2107 (rename-file (edb-filename db) (concat (edb-filename db) "~") t)
2108 (setf (edb-make-backup db) nil))
2109 (with-temp-buffer
2110 (ebib-format-database db)
2111 (write-region (point-min) (point-max) (edb-filename db)))
2112 (ebib-set-modified nil db))))
2114 (defun ebib-write-database ()
2115 "Writes the current database to a different file.
2116 Can also be used to change a virtual database into a real one."
2117 (interactive)
2118 (ebib-execute-when
2119 ((database)
2120 (if-str (new-filename (read-file-name "Save to file: " "~/"))
2121 (progn
2122 (with-temp-buffer
2123 (ebib-format-database ebib-cur-db)
2124 (safe-write-region (point-min) (point-max) new-filename nil nil nil t))
2125 ;; if SAFE-WRITE-REGION was cancelled by the user because he
2126 ;; didn't want to overwrite an already existing file with his
2127 ;; new database, it throws an error, so the next lines will not
2128 ;; be executed. hence we can safely set (EDB-FILENAME DB) and
2129 ;; (EDB-NAME DB).
2130 (setf (edb-filename ebib-cur-db) new-filename)
2131 (setf (edb-name ebib-cur-db) (file-name-nondirectory new-filename))
2132 (rename-buffer (concat (format " %d:" (1+ (- (length ebib-databases)
2133 (length (member ebib-cur-db ebib-databases)))))
2134 (edb-name ebib-cur-db)))
2135 (ebib-execute-when
2136 ((virtual-db)
2137 (setf (edb-virtual ebib-cur-db) nil)
2138 (setf (edb-database ebib-cur-db)
2139 (let ((new-db (make-hash-table :test 'equal)))
2140 (mapc #'(lambda (key)
2141 (let ((entry (gethash key (edb-database ebib-cur-db))))
2142 (when entry
2143 (puthash key (copy-hash-table entry) new-db))))
2144 (edb-keys-list ebib-cur-db))
2145 new-db))))
2146 (ebib-set-modified nil))))
2147 ((default)
2148 (beep))))
2150 (defun ebib-save-current-database ()
2151 "Saves the current database."
2152 (interactive)
2153 (ebib-execute-when
2154 ((real-db)
2155 (if (not (edb-modified ebib-cur-db))
2156 (message "No changes need to be saved.")
2157 (ebib-save-database ebib-cur-db)))
2158 ((virtual-db)
2159 (error "Cannot save a virtual database. Use `w' to write to a file."))))
2161 (defun ebib-save-all-databases ()
2162 "Saves all currently open databases if they were modified."
2163 (interactive)
2164 (ebib-execute-when
2165 ((database)
2166 (mapc #'(lambda (db)
2167 (when (edb-modified db)
2168 (ebib-save-database db)))
2169 ebib-databases)
2170 (message "All databases saved."))))
2172 (defun ebib-print-filename ()
2173 "Displays the filename of the current database in the minibuffer."
2174 (interactive)
2175 (message (edb-filename ebib-cur-db)))
2177 (defun ebib-follow-crossref ()
2178 "Goes to the entry mentioned in the crossref field of the current entry."
2179 (interactive)
2180 (let ((new-cur-entry (to-raw (gethash 'crossref
2181 (ebib-retrieve-entry (ebib-cur-entry-key) ebib-cur-db)))))
2182 (setf (edb-cur-entry ebib-cur-db)
2183 (or (member new-cur-entry (edb-keys-list ebib-cur-db))
2184 (edb-cur-entry ebib-cur-db))))
2185 (ebib-fill-entry-buffer)
2186 (ebib-fill-index-buffer))
2188 (defun ebib-toggle-hidden ()
2189 "Toggle viewing hidden fields."
2190 (interactive)
2191 (setq ebib-hide-hidden-fields (not ebib-hide-hidden-fields))
2192 (ebib-fill-entry-buffer))
2194 (defun ebib-toggle-timestamp ()
2195 "Toggle using timestamp for new entries."
2196 (interactive)
2197 (setq ebib-use-timestamp (not ebib-use-timestamp)))
2199 (defun ebib-toggle-xrefs-first ()
2200 "Toggle saving of crossreferenced entries first."
2201 (interactive)
2202 (setq ebib-save-xrefs-first (not ebib-save-xrefs-first)))
2204 (defun ebib-toggle-identical-fields ()
2205 "Toggle whether Ebib allows identical fields when opening a .bib file."
2206 (interactive)
2207 (setq ebib-allow-identical-fields (not ebib-allow-identical-fields)))
2209 (defun ebib-toggle-layout ()
2210 "Toggles the Ebib layout."
2211 (interactive)
2212 (if (eq ebib-layout 'full)
2213 (setq ebib-layout 'custom)
2214 (setq ebib-layout 'full))
2215 (ebib-lower)
2216 (ebib))
2218 (defun ebib-toggle-print-newpage ()
2219 "Toggle whether index cards are printed with a newpage after each card."
2220 (interactive)
2221 (setq ebib-print-newpage (not ebib-print-newpage)))
2223 (defun ebib-toggle-print-multiline ()
2224 "Toggle whether multiline fields are printed."
2225 (interactive)
2226 (setq ebib-print-multiline (not ebib-print-multiline)))
2228 (defun ebib-delete-entry ()
2229 "Deletes the current entry from the database."
2230 (interactive)
2231 (if (ebib-called-with-prefix)
2232 (ebib-execute-when
2233 ((real-db marked-entries)
2234 (when (y-or-n-p "Delete all marked entries? ")
2235 (mapc #'(lambda (entry)
2236 (ebib-remove-entry-from-db entry ebib-cur-db (not (string= entry (ebib-cur-entry-key)))))
2237 (edb-marked-entries ebib-cur-db))
2238 (message "Marked entries deleted.")
2239 (ebib-set-modified t)
2240 (ebib-fill-entry-buffer)
2241 (ebib-fill-index-buffer)))
2242 ((default)
2243 (beep)))
2244 (ebib-execute-when
2245 ((real-db entries)
2246 (let ((cur-entry (ebib-cur-entry-key)))
2247 (when (y-or-n-p (format "Delete %s? " cur-entry))
2248 (ebib-remove-entry-from-db cur-entry ebib-cur-db)
2249 (ebib-remove-key-from-buffer cur-entry)
2250 (ebib-fill-entry-buffer)
2251 (ebib-set-modified t)
2252 (message (format "Entry `%s' deleted." cur-entry)))))
2253 ((default)
2254 (beep)))))
2256 (defun ebib-remove-entry-from-db (entry-key db &optional new-cur-entry)
2257 "Removes ENTRY-KEY from DB.
2258 Optional argument NEW-CUR-ENTRY is the key of the entry that is
2259 to become the new current entry. It it is NIL, the entry after
2260 the deleted one becomes the new current entry. If it is T, the
2261 current entry is not changed."
2262 (remhash entry-key (edb-database db))
2263 (setf (edb-n-entries db) (1- (edb-n-entries db)))
2264 (cond
2265 ((null new-cur-entry) (setq new-cur-entry (cadr (edb-cur-entry db))))
2266 ((stringp new-cur-entry) t)
2267 (t (setq new-cur-entry (ebib-cur-entry-key))))
2268 (setf (edb-keys-list db) (delete entry-key (edb-keys-list db)))
2269 (setf (edb-marked-entries db) (delete entry-key (edb-marked-entries db)))
2270 (setf (edb-cur-entry db) (member new-cur-entry (edb-keys-list db)))
2271 (unless (edb-cur-entry db) ; if (edb-cur-entry db) is nil, we deleted the last entry.
2272 (setf (edb-cur-entry db) (last (edb-keys-list db)))))
2274 (defun ebib-remove-key-from-buffer (entry-key)
2275 "Removes ENTRY-KEY from the index buffer and highlights the current entry."
2276 (with-buffer-writable
2277 (let ((beg (ebib-search-key-in-buffer entry-key)))
2278 (forward-line 1)
2279 (delete-region beg (point))))
2280 (ebib-execute-when
2281 ((entries)
2282 (ebib-search-key-in-buffer (ebib-cur-entry-key))
2283 (ebib-set-index-highlight))))
2285 (defun ebib-select-entry ()
2286 "Makes the entry at POINT the current entry."
2287 (interactive)
2288 (ebib-execute-when
2289 ((entries)
2290 (beginning-of-line)
2291 (let ((beg (point)))
2292 (let* ((key (save-excursion
2293 (skip-chars-forward "^ ")
2294 (buffer-substring-no-properties beg (point))))
2295 (new-cur-entry (member key (edb-keys-list ebib-cur-db))))
2296 (when new-cur-entry
2297 (setf (edb-cur-entry ebib-cur-db) new-cur-entry)
2298 (ebib-set-index-highlight)
2299 (ebib-fill-entry-buffer)))))
2300 ((default)
2301 (beep))))
2303 (defun ebib-export-entry (prefix)
2304 "Copies entries to another database.
2305 The prefix argument indicates which database to copy the entry
2306 to. If no prefix argument is present, a filename is asked to
2307 which the entry is appended."
2308 (interactive "P")
2309 (let ((num (ebib-prefix prefix)))
2310 (if (ebib-called-with-prefix)
2311 (ebib-export-marked-entries num)
2312 (ebib-export-single-entry num))))
2314 (defun ebib-export-single-entry (num)
2315 "Copies the current entry to another database.
2316 NUM indicates which database to copy the entry to. If it is NIL,
2317 a filename is asked to which the entry is appended."
2318 (ebib-execute-when
2319 ((real-db entries)
2320 (if num
2321 (ebib-export-to-db num (format "Entry `%s' copied to database %%d." (ebib-cur-entry-key))
2322 #'(lambda (db)
2323 (let ((entry-key (ebib-cur-entry-key)))
2324 (if (member entry-key (edb-keys-list db))
2325 (error "Entry key `%s' already exists in database %d" entry-key num)
2326 (ebib-insert-entry entry-key
2327 (copy-hash-table (ebib-retrieve-entry entry-key
2328 ebib-cur-db))
2329 db t t)
2330 ;; if this is the first entry in the target DB,
2331 ;; its CUR-ENTRY must be set!
2332 (when (null (edb-cur-entry db))
2333 (setf (edb-cur-entry db) (edb-keys-list db)))
2334 t)))) ; we must return T, WHEN does not always do this.
2335 (ebib-export-to-file (format "Export `%s' to file: " (ebib-cur-entry-key))
2336 (format "Entry `%s' exported to %%s." (ebib-cur-entry-key))
2337 #'(lambda ()
2338 (insert "\n")
2339 (ebib-format-entry (ebib-cur-entry-key) ebib-cur-db t)))))
2340 ((default)
2341 (beep))))
2343 (defun ebib-export-marked-entries (num)
2344 "Copies the marked entries to another database.
2345 NUM indicates which database to copy the entry to. If it is NIL,
2346 a filename is asked to which the entry is appended."
2347 (ebib-execute-when
2348 ((real-db marked-entries)
2349 (if num
2350 (ebib-export-to-db
2351 num "Entries copied to database %d."
2352 #'(lambda (db)
2353 (mapc #'(lambda (entry-key)
2354 (if (member entry-key (edb-keys-list db))
2355 (error "Entry key `%s' already exists in database %d" entry-key num)
2356 (ebib-insert-entry entry-key
2357 (copy-hash-table (ebib-retrieve-entry entry-key
2358 ebib-cur-db))
2359 db t t)))
2360 (edb-marked-entries ebib-cur-db))
2361 ;; if the target DB was empty before, its CUR-ENTRY must be set!
2362 (when (null (edb-cur-entry db))
2363 (setf (edb-cur-entry db) (edb-keys-list db)))
2364 t)) ; we must return T, WHEN does not always do this.
2365 (ebib-export-to-file "Export to file: " "Entries exported to %s."
2366 #'(lambda ()
2367 (mapc #'(lambda (entry-key)
2368 (insert "\n")
2369 (ebib-format-entry entry-key ebib-cur-db t))
2370 (edb-marked-entries ebib-cur-db))))))
2371 ((default)
2372 (beep))))
2374 (defun ebib-search ()
2375 "Search the current Ebib database.
2376 The search is conducted with STRING-MATCH and can therefore be a
2377 regexp. Searching starts with the current entry."
2378 (interactive)
2379 (ebib-execute-when
2380 ((entries)
2381 (if-str (search-str (read-string "Search database for: "))
2382 (progn
2383 (setq ebib-search-string search-str)
2384 ;; first we search the current entry
2385 (if (ebib-search-in-entry ebib-search-string
2386 (ebib-retrieve-entry (ebib-cur-entry-key) ebib-cur-db))
2387 (ebib-fill-entry-buffer ebib-search-string)
2388 ;; if the search string wasn't found in the current entry, we continue searching.
2389 (ebib-search-next)))))
2390 ((default)
2391 (beep))))
2393 (defun ebib-search-next ()
2394 "Searches the next occurrence of EBIB-SEARCH-STRING.
2395 Searching starts at the entry following the current entry. If a
2396 match is found, the matching entry is shown and becomes the new
2397 current entry."
2398 (interactive)
2399 (ebib-execute-when
2400 ((entries)
2401 (if (null ebib-search-string)
2402 (message "No search string")
2403 (let ((cur-search-entry (cdr (edb-cur-entry ebib-cur-db))))
2404 (while (and cur-search-entry
2405 (null (ebib-search-in-entry ebib-search-string
2406 (gethash (car cur-search-entry)
2407 (edb-database ebib-cur-db)))))
2408 (setq cur-search-entry (cdr cur-search-entry)))
2409 (if (null cur-search-entry)
2410 (message (format "`%s' not found" ebib-search-string))
2411 (setf (edb-cur-entry ebib-cur-db) cur-search-entry)
2412 (set-buffer ebib-index-buffer)
2413 (goto-char (point-min))
2414 (re-search-forward (format "^%s " (ebib-cur-entry-key)))
2415 (beginning-of-line)
2416 (ebib-set-index-highlight)
2417 (ebib-fill-entry-buffer ebib-search-string)))))
2418 ((default)
2419 (beep))))
2421 (defun ebib-search-in-entry (search-str entry &optional field)
2422 "Searches one entry of the ebib database.
2423 Returns a list of fields in ENTRY that match the regexp
2424 SEARCH-STR, or NIL if no matches were found. If FIELD is given,
2425 only that field is searched."
2426 (let ((case-fold-search t) ; we want to ensure a case-insensitive search
2427 (result nil))
2428 (if field
2429 (let ((value (gethash field entry)))
2430 (when (and (stringp value) ; the type* field has a symbol as value
2431 (string-match search-str value))
2432 (setq result (list field))))
2433 (maphash #'(lambda (field value)
2434 (when (and (stringp value) ; the type* field has a symbol as value
2435 (string-match search-str value))
2436 (setq result (cons field result))))
2437 entry))
2438 result))
2440 (defun ebib-search-crossref ()
2441 "Searches the database for the key of the current entry.
2442 This is useful in searching the entries that cross-reference the
2443 current entry."
2444 (interactive)
2445 (setq ebib-search-string (car (edb-cur-entry ebib-cur-db)))
2446 (ebib-search-next))
2448 (defun ebib-edit-strings ()
2449 "Edits the @STRING definitions in the database."
2450 (interactive)
2451 (ebib-execute-when
2452 ((real-db)
2453 (ebib-fill-strings-buffer)
2454 (select-window (get-buffer-window ebib-entry-buffer) nil)
2455 (set-window-dedicated-p (selected-window) nil)
2456 (switch-to-buffer ebib-strings-buffer)
2457 (unless (eq ebib-layout 'full)
2458 (set-window-dedicated-p (selected-window) t))
2459 (goto-char (point-min)))
2460 ((default)
2461 (beep))))
2463 (defun ebib-edit-preamble ()
2464 "Edits the @PREAMBLE definition in the database."
2465 (interactive)
2466 (ebib-execute-when
2467 ((real-db)
2468 (select-window (ebib-temp-window) nil)
2469 (ebib-multiline-edit 'preamble (edb-preamble ebib-cur-db)))
2470 ((default)
2471 (beep))))
2473 (defun ebib-export-preamble (prefix)
2474 "Exports the @PREAMBLE definition.
2475 If a prefix argument is given, it is taken as the database to
2476 export the preamble to. If the goal database already has a
2477 preamble, the new preamble will be appended to it. If no prefix
2478 argument is given, the user is asked to enter a filename to which
2479 the preamble is appended."
2480 (interactive "P")
2481 (ebib-execute-when
2482 ((real-db)
2483 (if (null (edb-preamble ebib-cur-db))
2484 (error "No @PREAMBLE defined")
2485 (let ((num (ebib-prefix prefix)))
2486 (if num
2487 (ebib-export-to-db num "@PREAMBLE copied to database %d"
2488 #'(lambda (db)
2489 (let ((text (edb-preamble ebib-cur-db)))
2490 (if (edb-preamble db)
2491 (setf (edb-preamble db) (concat (edb-preamble db) "\n# " text))
2492 (setf (edb-preamble db) text)))))
2493 (ebib-export-to-file "Export @PREAMBLE to file: "
2494 "@PREAMBLE exported to %s"
2495 #'(lambda ()
2496 (insert (format "\n@preamble{%s}\n\n" (edb-preamble ebib-cur-db)))))))))
2497 ((default)
2498 (beep))))
2500 (defun ebib-print-entries ()
2501 "Creates a LaTeX file listing the entries.
2502 Either prints the entire database, or the marked entries."
2503 (interactive)
2504 (ebib-execute-when
2505 ((entries)
2506 (let ((entries (or (when (or (ebib-called-with-prefix)
2507 (equal '(menu-bar) (elt (this-command-keys-vector) 0)))
2508 (edb-marked-entries ebib-cur-db))
2509 (edb-keys-list ebib-cur-db))))
2510 (if-str (tempfile (if (not (string= "" ebib-print-tempfile))
2511 ebib-print-tempfile
2512 (read-file-name "Use temp file: " "~/" nil nil)))
2513 (progn
2514 (with-temp-buffer
2515 (insert "\\documentclass{article}\n\n")
2516 (when ebib-print-preamble
2517 (mapc #'(lambda (string)
2518 (insert (format "%s\n" string)))
2519 ebib-print-preamble))
2520 (insert "\n\\begin{document}\n\n")
2521 (mapc #'(lambda (entry-key)
2522 (insert "\\begin{tabular}{p{0.2\\textwidth}p{0.8\\textwidth}}\n")
2523 (let ((entry (ebib-retrieve-entry entry-key ebib-cur-db)))
2524 (insert (format "\\multicolumn{2}{l}{\\texttt{%s (%s)}}\\\\\n"
2525 entry-key (symbol-name (gethash 'type* entry))))
2526 (insert "\\hline\n")
2527 (mapc #'(lambda (field)
2528 (if-str (value (gethash field entry))
2529 (when (or (not (multiline-p value))
2530 ebib-print-multiline)
2531 (insert (format "%s: & %s\\\\\n"
2532 field (to-raw value))))))
2533 (cdr (ebib-get-all-fields (gethash 'type* entry)))))
2534 (insert "\\end{tabular}\n\n")
2535 (insert (if ebib-print-newpage
2536 "\\newpage\n\n"
2537 "\\bigskip\n\n")))
2538 entries)
2539 (insert "\\end{document}\n")
2540 (write-region (point-min) (point-max) tempfile))
2541 (ebib-lower)
2542 (find-file tempfile)))))
2543 ((default)
2544 (beep))))
2546 (defun ebib-latex-entries ()
2547 "Creates a LaTeX file that \\nocites entries from the database.
2548 Operates either on all entries or on the marked entries."
2549 (interactive)
2550 (ebib-execute-when
2551 ((real-db entries)
2552 (if-str (tempfile (if (not (string= "" ebib-print-tempfile))
2553 ebib-print-tempfile
2554 (read-file-name "Use temp file: " "~/" nil nil)))
2555 (progn
2556 (with-temp-buffer
2557 (insert "\\documentclass{article}\n\n")
2558 (when ebib-print-preamble
2559 (mapc #'(lambda (string)
2560 (insert (format "%s\n" string)))
2561 ebib-latex-preamble))
2562 (insert "\n\\begin{document}\n\n")
2563 (if (and (or (ebib-called-with-prefix)
2564 (equal '(menu-bar) (elt (this-command-keys-vector) 0)))
2565 (edb-marked-entries ebib-cur-db))
2566 (mapc #'(lambda (entry)
2567 (insert (format "\\nocite{%s}\n" entry)))
2568 (edb-marked-entries ebib-cur-db))
2569 (insert "\\nocite{*}\n"))
2570 (insert (format "\n\\bibliography{%s}\n\n" (expand-file-name (edb-filename ebib-cur-db))))
2571 (insert "\\end{document}\n")
2572 (write-region (point-min) (point-max) tempfile))
2573 (ebib-lower)
2574 (find-file tempfile))))
2575 ((default)
2576 (beep))))
2578 (defun ebib-switch-to-database (num)
2579 (interactive "NSwitch to database number: ")
2580 (let ((new-db (nth (1- num) ebib-databases)))
2581 (if new-db
2582 (progn
2583 (setq ebib-cur-db new-db)
2584 (ebib-fill-entry-buffer)
2585 (ebib-fill-index-buffer))
2586 (error "Database %d does not exist" num))))
2588 (defun ebib-next-database ()
2589 (interactive)
2590 (ebib-execute-when
2591 ((database)
2592 (let ((new-db (next-elem ebib-cur-db ebib-databases)))
2593 (unless new-db
2594 (setq new-db (car ebib-databases)))
2595 (setq ebib-cur-db new-db)
2596 (ebib-fill-entry-buffer)
2597 (ebib-fill-index-buffer)))))
2599 (defun ebib-prev-database ()
2600 (interactive)
2601 (ebib-execute-when
2602 ((database)
2603 (let ((new-db (prev-elem ebib-cur-db ebib-databases)))
2604 (unless new-db
2605 (setq new-db (last1 ebib-databases)))
2606 (setq ebib-cur-db new-db)
2607 (ebib-fill-entry-buffer)
2608 (ebib-fill-index-buffer)))))
2610 (defun ebib-browse-url (num)
2611 "Asks a browser to load the URL in the standard URL field.
2612 The standard URL field may contain more than one URL, if they're
2613 whitespace-separated. In that case, a numeric prefix argument
2614 specifies which URL to choose.
2616 By \"standard URL field\" is meant the field defined in the
2617 customisation variable EBIB-STANDARD-URL-FIELD. Its default value
2618 is `url'."
2619 (interactive "p")
2620 (ebib-execute-when
2621 ((entries)
2622 (let ((url (to-raw (gethash ebib-standard-url-field
2623 (ebib-retrieve-entry (ebib-cur-entry-key) ebib-cur-db)))))
2624 (when (not (and url
2625 (ebib-call-browser url num)))
2626 (error "No url found in field `%s'" ebib-standard-url-field))))
2627 ((default)
2628 (beep))))
2630 (defun ebib-call-browser (urls n)
2631 "Passes the Nth url in URLS to a browser.
2632 URLs must be a string of whitespace-separated urls."
2633 (let ((url (nth (1- n)
2634 (let ((start 0)
2635 (result nil))
2636 (while (string-match ebib-url-regexp urls start)
2637 (add-to-list 'result (match-string 0 urls) t)
2638 (setq start (match-end 0)))
2639 result))))
2640 (cond
2641 ((string-match "\\\\url{\\(.*?\\)}" url)
2642 (setq url (match-string 1 url)))
2643 ((string-match ebib-url-regexp url)
2644 (setq url (match-string 0 url)))
2645 (t (setq url nil)))
2646 (when url
2647 (if (not (string= ebib-browser-command ""))
2648 (start-process "Ebib-browser" nil ebib-browser-command url)
2649 (browse-url url)))))
2651 (defun ebib-view-file (num)
2652 "Views a file in the standard file field.
2653 The standard file field may contain more than one filename, if
2654 they're whitespace-separated. In that case, a numeric prefix
2655 argument specifies which file to choose.
2657 By \"standard file field\" is meant the field defined in the
2658 customisation variable EBIB-STANDARD-FILE-FIELD. Its default
2659 value is `file'."
2660 (interactive "p")
2661 (ebib-execute-when
2662 ((entries)
2663 (let ((filename (to-raw (gethash ebib-standard-file-field
2664 (ebib-retrieve-entry (ebib-cur-entry-key) ebib-cur-db)))))
2665 (when (not (and filename
2666 (ebib-call-file-viewer filename num)))
2667 (error "No valid filename found in field `%s'" ebib-standard-file-field))))
2668 ((default)
2669 (beep))))
2671 (defun ebib-call-file-viewer (files n)
2672 "Passes the Nth file in FILES to an external viewer.
2673 FILES must be a string of whitespace-separated filenames."
2674 (let* ((file (nth (1- n)
2675 (let ((start 0)
2676 (result nil))
2677 (while (string-match ebib-file-regexp files start)
2678 (add-to-list 'result (match-string 0 files) t)
2679 (setq start (match-end 0)))
2680 result)))
2681 (ext (file-name-extension file)))
2682 (let ((file-full-path (locate-file file ebib-file-search-dirs)))
2683 (when file-full-path
2684 (if-str (viewer (cdr (assoc ext ebib-file-associations)))
2685 (start-process (concat "ebib " ext " viewer process") nil viewer file-full-path)
2686 (ebib-lower)
2687 (find-file file-full-path))))))
2689 (defun ebib-virtual-db-and (not)
2690 "Filters entries into a virtual database.
2691 If the current database is a virtual database already, perform a
2692 logical AND on the entries."
2693 (interactive "p")
2694 (ebib-execute-when
2695 ((entries)
2696 (ebib-filter-to-virtual-db 'and not))
2697 ((default)
2698 (beep))))
2700 (defun ebib-virtual-db-or (not)
2701 "Filters entries into a virtual database.
2702 If the current database is a virtual database already, perform a
2703 logical OR with the entries in the original database."
2704 (interactive "p")
2705 (ebib-execute-when
2706 ((entries)
2707 (ebib-filter-to-virtual-db 'or not))
2708 ((default)
2709 (beep))))
2711 (defun ebib-virtual-db-not ()
2712 "Negates the current virtual database."
2713 (interactive)
2714 (ebib-execute-when
2715 ((virtual-db)
2716 (setf (edb-virtual ebib-cur-db)
2717 (if (eq (car (edb-virtual ebib-cur-db)) 'not)
2718 (cadr (edb-virtual ebib-cur-db))
2719 `(not ,(edb-virtual ebib-cur-db))))
2720 (ebib-run-filter (edb-virtual ebib-cur-db) ebib-cur-db)
2721 (ebib-fill-entry-buffer)
2722 (ebib-fill-index-buffer))
2723 ((default)
2724 (beep))))
2726 (defun ebib-filter-to-virtual-db (bool not)
2727 "Filters the current database to a virtual database.
2728 BOOL is the operator to be used, either `and' or `or'. If NOT<0,
2729 a logical `not' is applied to the selection."
2730 (let ((field (completing-read (format "Filter: %s(contains <field> <regexp>)%s. Enter field: "
2731 (if (< not 0) "(not " "")
2732 (if (< not 0) ")" ""))
2733 (cons '("any" 0)
2734 (mapcar #'(lambda (x)
2735 (cons (symbol-name x) 0))
2736 (append ebib-unique-field-list ebib-additional-fields)))
2737 nil t)))
2738 (setq field (intern-soft field))
2739 (let ((regexp (read-string (format "Filter: %s(contains %s <regexp>)%s. Enter regexp: "
2740 (if (< not 0) "(not " "")
2741 field
2742 (if (< not 0) ")" "")))))
2743 (ebib-execute-when
2744 ((virtual-db)
2745 (setf (edb-virtual ebib-cur-db) `(,bool ,(edb-virtual ebib-cur-db)
2746 ,(if (>= not 0)
2747 `(contains ,field ,regexp)
2748 `(not (contains ,field ,regexp))))))
2749 ((real-db)
2750 (setq ebib-cur-db (ebib-create-virtual-db field regexp not))))
2751 (ebib-run-filter (edb-virtual ebib-cur-db) ebib-cur-db)
2752 (ebib-fill-entry-buffer)
2753 (ebib-fill-index-buffer))))
2755 (defun ebib-create-virtual-db (field regexp not)
2756 "Creates a virtual database based on EBIB-CUR-DB."
2757 ;; a virtual database is a database whose edb-virtual field contains an
2758 ;; expression that selects entries. this function only sets that
2759 ;; expression, it does not actually filter the entries.
2760 (let ((new-db (ebib-create-new-database ebib-cur-db)))
2761 (setf (edb-virtual new-db) (if (>= not 0)
2762 `(contains ,field ,regexp)
2763 `(not (contains ,field ,regexp))))
2764 (setf (edb-filename new-db) nil)
2765 (setf (edb-name new-db) (concat "V:" (edb-name new-db)))
2766 (setf (edb-modified new-db) nil)
2767 (setf (edb-make-backup new-db) nil)
2768 new-db))
2770 (defmacro contains (field regexp)
2771 ;; Note: the variable ENTRY is *not* bound in this macro! The function
2772 ;; calling CONTAINS *must* set ENTRY to an actual Ebib entry. The point
2773 ;; of this macro is to facilitate defining filters for virtual databases.
2774 ;; It enables us to define filters of the form:
2776 ;; (and (not (contains author "Chomsky")) (contains year "1995"))
2778 `(ebib-search-in-entry ,regexp entry ,(unless (eq field 'any) `(quote ,field))))
2780 (defun ebib-run-filter (filter db)
2781 "Runs FILTER on DB"
2782 (setf (edb-keys-list db)
2783 (sort (let ((result nil))
2784 (maphash #'(lambda (key value)
2785 (let ((entry value)) ; this is necessary for actually running the filter
2786 (when (eval filter)
2787 (setq result (cons key result)))))
2788 (edb-database db))
2789 result)
2790 'string<))
2791 (setf (edb-n-entries db) (length (edb-keys-list db)))
2792 (setf (edb-cur-entry db) (edb-keys-list db)))
2794 (defun ebib-print-filter (num)
2795 "Displays the filter of the current virtual database.
2796 With any prefix argument, reapplies the filter to the
2797 database. This can be useful when the source database was
2798 modified."
2799 (interactive "P")
2800 (ebib-execute-when
2801 ((virtual-db)
2802 (when num
2803 (ebib-run-filter (edb-virtual ebib-cur-db) ebib-cur-db)
2804 (ebib-fill-entry-buffer)
2805 (ebib-fill-index-buffer))
2806 (message "%S" (edb-virtual ebib-cur-db)))
2807 ((default)
2808 (beep))))
2810 (defun ebib-show-log ()
2811 "Displays the contents of the log buffer."
2812 (interactive)
2813 (select-window (get-buffer-window ebib-entry-buffer) nil)
2814 (set-window-dedicated-p (selected-window) nil)
2815 (switch-to-buffer ebib-log-buffer)
2816 (unless (eq ebib-layout 'full)
2817 (set-window-dedicated-p (selected-window) t)))
2819 (defun ebib-create-citation-command (command n-opt-args key)
2820 "Create a LaTeX citation command with COMMAND and KEY.
2821 N-OPT-ARGS is the number of optional arguments COMMAND takes. A
2822 backslash is prefixed to COMMAND if none is present (and COMMAND
2823 is non-empty)."
2824 (let ((opt-args (loop for i from 1 to n-opt-args
2825 collect (read-from-minibuffer (format "Cite %s with optional argument %d: " key i)))))
2826 (while (equal (car opt-args) "") ; empty args at the beginning of the list don't need
2827 (setq opt-args (cdr opt-args))) ; to be included.
2828 (format "%s%s%s{%s}"
2829 (if (or (string= command "")
2830 (= (aref command 0) 92))
2831 "" "\\") ; add a backslash if the user didn't type one.
2832 command
2833 (mapconcat #'(lambda (str)
2834 (format "[%s]" str))
2835 opt-args "")
2836 key)))
2838 (defun ebib-push-bibtex-key ()
2839 "Pushes the current entry to a LaTeX buffer.
2840 The user is prompted for the buffer to push the entry into."
2841 (interactive)
2842 (let ((called-with-prefix (ebib-called-with-prefix)))
2843 (ebib-execute-when
2844 ((entries)
2845 (let ((buffer (read-buffer (if called-with-prefix
2846 "Push marked entries to buffer: "
2847 "Push entry to buffer: ")
2848 ebib-push-buffer t)))
2849 (when buffer
2850 (setq ebib-push-buffer buffer)
2851 (let (insert-string)
2852 (if-str (command (completing-read "Command to use: " ebib-insertion-commands
2853 nil nil nil ebib-minibuf-hist))
2854 (let* ((n-opt-args (or (cadr (assoc command ebib-insertion-commands))
2856 (allow-mult-args (caddr (assoc command ebib-insertion-commands)))
2857 (key (if (and called-with-prefix ; if there are marked entries...
2858 (edb-marked-entries ebib-cur-db))
2859 (if allow-mult-args ; and the command allows multiple separate args
2860 (car (edb-marked-entries ebib-cur-db)) ; just take the first one here
2861 (mapconcat #'(lambda (x) x) ; otherwise take all the marked entries
2862 (edb-marked-entries ebib-cur-db)
2863 ","))
2864 (car (edb-cur-entry ebib-cur-db)))) ; if there are no marked entries, take the current entry
2865 (first (ebib-create-citation-command command n-opt-args key))
2866 (rest (when (and called-with-prefix ; if we have marked entries...
2867 (edb-marked-entries ebib-cur-db)
2868 allow-mult-args) ; and a command that allows multiple separate arguments
2869 (mapcar #'(lambda (key) ; we need to process the rest of the entries
2870 (ebib-create-citation-command "" n-opt-args key))
2871 (cdr (edb-marked-entries ebib-cur-db))))))
2872 (setq insert-string (apply #'concat first rest)))
2873 ;; if the user did not provide a comand, we just insert the
2874 ;; current entry, or the marked entries, separated by commas:
2875 (setq insert-string
2876 (if (and called-with-prefix
2877 (edb-marked-entries ebib-cur-db))
2878 (mapconcat #'(lambda (x) x) ; otherwise take all the marked entries
2879 (edb-marked-entries ebib-cur-db)
2880 ",")
2881 (car (edb-cur-entry ebib-cur-db)))))
2882 (when insert-string
2883 (with-current-buffer buffer
2884 (insert insert-string))
2885 (message "Pushed entries to buffer %s" buffer))))))
2886 ((default)
2887 (beep)))))
2889 (defun ebib-index-help ()
2890 "Shows the info node of Ebib's index buffer."
2891 (interactive)
2892 (ebib-lower)
2893 (info "(ebib) The Index Buffer"))
2895 (defun ebib-info ()
2896 "Shows Ebib's info node."
2897 (interactive)
2898 (ebib-lower)
2899 (info "(ebib)"))
2901 ;;;;;;;;;;;;;;;;
2902 ;; entry-mode ;;
2903 ;;;;;;;;;;;;;;;;
2905 (defvar ebib-entry-mode-map
2906 (let ((map (make-keymap)))
2907 (suppress-keymap map)
2908 (define-key map [up] 'ebib-prev-field)
2909 (define-key map [down] 'ebib-next-field)
2910 (define-key map [prior] 'ebib-goto-prev-set)
2911 (define-key map [next] 'ebib-goto-next-set)
2912 (define-key map [home] 'ebib-goto-first-field)
2913 (define-key map [end] 'ebib-goto-last-field)
2914 (define-key map [return] 'ebib-edit-field)
2915 (define-key map " " 'ebib-goto-next-set)
2916 (define-key map "b" 'ebib-goto-prev-set)
2917 (define-key map "c" 'ebib-copy-field-contents)
2918 (define-key map "d" 'ebib-delete-field-contents)
2919 (define-key map "e" 'ebib-edit-field)
2920 (define-key map "f" 'ebib-view-file-in-field)
2921 (define-key map "g" 'ebib-goto-first-field)
2922 (define-key map "G" 'ebib-goto-last-field)
2923 (define-key map "h" 'ebib-entry-help)
2924 (define-key map "j" 'ebib-next-field)
2925 (define-key map "k" 'ebib-prev-field)
2926 (define-key map "l" 'ebib-edit-multiline-field)
2927 (define-key map [(control n)] 'ebib-next-field)
2928 (define-key map [(meta n)] 'ebib-goto-prev-set)
2929 (define-key map [(control p)] 'ebib-prev-field)
2930 (define-key map [(meta p)] 'ebib-goto-next-set)
2931 (define-key map "q" 'ebib-quit-entry-buffer)
2932 (define-key map "r" 'ebib-toggle-raw)
2933 (define-key map "s" 'ebib-insert-abbreviation)
2934 (define-key map "u" 'ebib-browse-url-in-field)
2935 (define-key map "x" 'ebib-cut-field-contents)
2936 (define-key map "\C-xb" 'undefined)
2937 (define-key map "\C-xk" 'undefined)
2938 (define-key map "y" 'ebib-yank-field-contents)
2939 map)
2940 "Keymap for the Ebib entry buffer.")
2942 (define-derived-mode ebib-entry-mode
2943 fundamental-mode "Ebib-entry"
2944 "Major mode for the Ebib entry buffer."
2945 (setq buffer-read-only t)
2946 (setq truncate-lines t))
2948 (defun ebib-quit-entry-buffer ()
2949 "Quits editing the entry."
2950 (interactive)
2951 (select-window (get-buffer-window ebib-index-buffer) nil))
2953 (defun ebib-find-visible-field (field direction)
2954 "Finds the first visible field before or after FIELD.
2955 If DIRECTION is negative, search the preceding fields, otherwise
2956 search the succeeding fields. If FIELD is visible itself, return
2957 that. If there is no preceding/following visible field, return
2958 NIL. If EBIB-HIDE-HIDDEN-FIELDS is NIL, return FIELD."
2959 (when ebib-hide-hidden-fields
2960 (let ((fn (if (>= direction 0)
2961 'next-elem
2962 'prev-elem)))
2963 (while (and field
2964 (get field 'ebib-hidden))
2965 (setq field (funcall fn field ebib-cur-entry-fields)))))
2966 field)
2968 (defun ebib-prev-field ()
2969 "Moves to the previous field."
2970 (interactive)
2971 (let ((new-field (ebib-find-visible-field (prev-elem ebib-current-field ebib-cur-entry-fields) -1)))
2972 (if (null new-field)
2973 (beep)
2974 (setq ebib-current-field new-field)
2975 (ebib-move-to-field ebib-current-field -1))))
2977 (defun ebib-next-field ()
2978 "Moves to the next field."
2979 (interactive)
2980 (let ((new-field (ebib-find-visible-field (next-elem ebib-current-field ebib-cur-entry-fields) 1)))
2981 (if (null new-field)
2982 (when (interactive-p) ; i call this function after editing a field,
2983 ; and we don't want a beep then
2984 (beep))
2985 (setq ebib-current-field new-field)
2986 (ebib-move-to-field ebib-current-field 1))))
2988 (defun ebib-goto-first-field ()
2989 "Moves to the first field."
2990 (interactive)
2991 (let ((new-field (ebib-find-visible-field (car ebib-cur-entry-fields) 1)))
2992 (if (null new-field)
2993 (beep)
2994 (setq ebib-current-field new-field)
2995 (ebib-move-to-field ebib-current-field -1))))
2997 (defun ebib-goto-last-field ()
2998 "Moves to the last field."
2999 (interactive)
3000 (let ((new-field (ebib-find-visible-field (last1 ebib-cur-entry-fields) -1)))
3001 (if (null new-field)
3002 (beep)
3003 (setq ebib-current-field new-field)
3004 (ebib-move-to-field ebib-current-field 1))))
3006 (defun ebib-goto-next-set ()
3007 "Moves to the next set of fields."
3008 (interactive)
3009 (cond
3010 ((eq ebib-current-field 'type*) (ebib-next-field))
3011 ((member ebib-current-field ebib-additional-fields) (ebib-goto-last-field))
3012 (t (let* ((entry-type (gethash 'type* ebib-cur-entry-hash))
3013 (obl-fields (ebib-get-obl-fields entry-type))
3014 (opt-fields (ebib-get-opt-fields entry-type))
3015 (new-field nil))
3016 (when (member ebib-current-field obl-fields)
3017 (setq new-field (ebib-find-visible-field (car opt-fields) 1)))
3018 ;; new-field is nil if there are no opt-fields
3019 (when (or (member ebib-current-field opt-fields)
3020 (null new-field))
3021 (setq new-field (ebib-find-visible-field (car ebib-additional-fields) 1)))
3022 (if (null new-field)
3023 (ebib-goto-last-field) ; if there was no further set to go to,
3024 ; go to the last field of the current set
3025 (setq ebib-current-field new-field)
3026 (ebib-move-to-field ebib-current-field 1))))))
3028 (defun ebib-goto-prev-set ()
3029 "Moves to the previous set of fields."
3030 (interactive)
3031 (unless (eq ebib-current-field 'type*)
3032 (let* ((entry-type (gethash 'type* ebib-cur-entry-hash))
3033 (obl-fields (ebib-get-obl-fields entry-type))
3034 (opt-fields (ebib-get-opt-fields entry-type))
3035 (new-field nil))
3036 (if (member ebib-current-field obl-fields)
3037 (ebib-goto-first-field)
3038 (when (member ebib-current-field ebib-additional-fields)
3039 (setq new-field (ebib-find-visible-field (last1 opt-fields) -1)))
3040 (when (or (member ebib-current-field opt-fields)
3041 (null new-field))
3042 (setq new-field (ebib-find-visible-field (last1 obl-fields) -1)))
3043 (if (null new-field)
3044 (ebib-goto-first-field)
3045 (setq ebib-current-field new-field)
3046 (ebib-move-to-field ebib-current-field -1))))))
3048 (defun ebib-edit-entry-type ()
3049 "Edits the entry type."
3050 ;; we don't want the completion buffer to be shown in the index window,
3051 ;; so we need to switch to an appropriate window first. we do this in an
3052 ;; unwind-protect to make sure we always get back to the entry buffer.
3053 (unwind-protect
3054 (progn
3055 (if (eq ebib-layout 'full)
3056 (other-window 1)
3057 (select-window ebib-pre-ebib-window) nil)
3058 (if-str (new-type (completing-read "type: " ebib-entry-types nil t))
3059 (progn
3060 (puthash 'type* (intern-soft new-type) ebib-cur-entry-hash)
3061 (ebib-fill-entry-buffer)
3062 (setq ebib-cur-entry-fields (ebib-get-all-fields (gethash 'type* ebib-cur-entry-hash)))
3063 (ebib-set-modified t))))
3064 (select-window (get-buffer-window ebib-entry-buffer) nil)))
3066 (defun ebib-edit-crossref ()
3067 "Edits the crossref field."
3068 ;; we don't want the completion buffer to be shown in the index window,
3069 ;; so we need to switch to an appropriate window first. we do this in an
3070 ;; unwind-protect to make sure we always get back to the entry buffer.
3071 (unwind-protect
3072 (progn
3073 (if (eq ebib-layout 'full)
3074 (other-window 1)
3075 (select-window ebib-pre-ebib-window) nil)
3076 (let ((collection (ebib-create-collection (edb-database ebib-cur-db))))
3077 (if-str (key (completing-read "Key to insert in `crossref': " collection nil t))
3078 (progn
3079 (puthash 'crossref (from-raw key) ebib-cur-entry-hash)
3080 (ebib-set-modified t)))))
3081 (select-window (get-buffer-window ebib-entry-buffer) nil)
3082 ;; we now redisplay the entire entry buffer, so that the crossref'ed
3083 ;; fields show up. this also puts the cursor back on the type field.
3084 (ebib-fill-entry-buffer)
3085 (setq ebib-current-field 'crossref)
3086 (re-search-forward "^crossref")
3087 (ebib-set-fields-highlight)))
3089 ;; we should modify ebib-edit-field, so that it calls the appropriate
3090 ;; helper function, which asks the user for the new value and just returns
3091 ;; that. storing it should then be done by ebib-edit-field, no matter what
3092 ;; sort of field the user edits.
3094 (defun ebib-edit-field ()
3095 "Edits a field of a BibTeX entry."
3096 (interactive)
3097 (cond
3098 ((eq ebib-current-field 'type*) (ebib-edit-entry-type))
3099 ((eq ebib-current-field 'crossref) (ebib-edit-crossref))
3100 ((eq ebib-current-field 'annote) (ebib-edit-multiline-field))
3102 (let ((init-contents (gethash ebib-current-field ebib-cur-entry-hash))
3103 (raw nil))
3104 (if (multiline-p init-contents)
3105 (ebib-edit-multiline-field)
3106 (when init-contents
3107 (if (raw-p init-contents)
3108 (setq raw t)
3109 (setq init-contents (to-raw init-contents))))
3110 (if-str (new-contents (read-string (format "%s: " (symbol-name ebib-current-field))
3111 (if init-contents
3112 (cons init-contents 0)
3113 nil)
3114 ebib-minibuf-hist))
3115 (puthash ebib-current-field (if raw
3116 new-contents
3117 (concat "{" new-contents "}"))
3118 ebib-cur-entry-hash)
3119 (remhash ebib-current-field ebib-cur-entry-hash))
3120 (ebib-redisplay-current-field)
3121 ;; we move to the next field, but only if ebib-edit-field was
3122 ;; called interactively, otherwise we get a strange bug in
3123 ;; ebib-toggle-raw...
3124 (if (interactive-p) (ebib-next-field))
3125 (ebib-set-modified t))))))
3127 (defun ebib-browse-url-in-field (num)
3128 "Browses a URL in the current field.
3129 The field may contain a whitespace-separated set of URLs. The
3130 prefix argument indicates which URL is to be sent to the
3131 browser."
3132 (interactive "p")
3133 (let ((urls (to-raw (gethash ebib-current-field ebib-cur-entry-hash))))
3134 (if (not (and urls
3135 (ebib-call-browser urls num)))
3136 (error "No url found in field `%s'" ebib-current-field))))
3138 (defun ebib-view-file-in-field (num)
3139 "Views a file in the current field.
3140 The field may contain a whitespace-separated set of
3141 filenames. The prefix argument indicates which file is to be
3142 viewed."
3143 (interactive "p")
3144 (let ((files (to-raw (gethash ebib-current-field ebib-cur-entry-hash))))
3145 (if (not (and files
3146 (ebib-call-file-viewer files num)))
3147 (error "No valid filename found in field `%s'" ebib-current-field))))
3149 (defun ebib-copy-field-contents ()
3150 "Copies the contents of the current field to the kill ring."
3151 (interactive)
3152 (unless (eq ebib-current-field 'type*)
3153 (let ((contents (gethash ebib-current-field ebib-cur-entry-hash)))
3154 (when (stringp contents)
3155 (kill-new contents)
3156 (message "Field contents copied.")))))
3158 (defun ebib-cut-field-contents ()
3159 "Kills the contents of the current field. The killed text is put in the kill ring."
3160 (interactive)
3161 (unless (eq ebib-current-field 'type*)
3162 (let ((contents (gethash ebib-current-field ebib-cur-entry-hash)))
3163 (when (stringp contents)
3164 (remhash ebib-current-field ebib-cur-entry-hash)
3165 (kill-new contents)
3166 (ebib-redisplay-current-field)
3167 (ebib-set-modified t)
3168 (message "Field contents killed.")))))
3170 (defun ebib-yank-field-contents (arg)
3171 "Inserts the last killed text into the current field.
3172 If the current field already has a contents, nothing is inserted,
3173 unless the previous command was also ebib-yank-field-contents,
3174 then the field contents is replaced with the previous yank. That
3175 is, multiple uses of this command function like the combination
3176 of C-y/M-y. Prefix arguments also work the same as with C-y/M-y."
3177 (interactive "P")
3178 (if (or (eq ebib-current-field 'type*) ; we cannot yank into the type* or crossref fields
3179 (eq ebib-current-field 'crossref)
3180 (unless (eq last-command 'ebib-yank-field-contents)
3181 (gethash ebib-current-field ebib-cur-entry-hash))) ; nor into a field already filled
3182 (progn
3183 (setq this-command t)
3184 (beep))
3185 (let ((new-contents (current-kill (cond
3186 ((listp arg) (if (eq last-command 'ebib-yank-field-contents)
3189 ((eq arg '-) -2)
3190 (t (1- arg))))))
3191 (when new-contents
3192 (puthash ebib-current-field new-contents ebib-cur-entry-hash)
3193 (ebib-redisplay-current-field)
3194 (ebib-set-modified t)))))
3196 (defun ebib-delete-field-contents ()
3197 "Deletes the contents of the current field.
3198 The deleted text is not put in the kill ring."
3199 (interactive)
3200 (if (eq ebib-current-field 'type*)
3201 (beep)
3202 (when (y-or-n-p "Delete field contents? ")
3203 (remhash ebib-current-field ebib-cur-entry-hash)
3204 (ebib-redisplay-current-field)
3205 (ebib-set-modified t)
3206 (message "Field contents deleted."))))
3208 (defun ebib-toggle-raw ()
3209 "Toggles the raw status of the current field contents."
3210 (interactive)
3211 (unless (or (eq ebib-current-field 'type*)
3212 (eq ebib-current-field 'crossref))
3213 (let ((contents (gethash ebib-current-field ebib-cur-entry-hash)))
3214 (if (not contents) ; if there is no value,
3215 (progn
3216 (ebib-edit-field) ; the user can enter one, which we must then make raw
3217 (let ((new-contents (gethash ebib-current-field ebib-cur-entry-hash)))
3218 (when new-contents
3219 ;; note: we don't have to check for empty string, since that is
3220 ;; already done in ebib-edit-field
3221 (puthash ebib-current-field (to-raw new-contents) ebib-cur-entry-hash))))
3222 (if (raw-p contents)
3223 (puthash ebib-current-field (from-raw contents) ebib-cur-entry-hash)
3224 (puthash ebib-current-field (to-raw contents) ebib-cur-entry-hash)))
3225 (ebib-redisplay-current-field)
3226 (ebib-set-modified t))))
3228 (defun ebib-edit-multiline-field ()
3229 "Edits the current field in multiline-mode."
3230 (interactive)
3231 (unless (or (eq ebib-current-field 'type*)
3232 (eq ebib-current-field 'crossref))
3233 (let ((text (gethash ebib-current-field ebib-cur-entry-hash)))
3234 (if (raw-p text)
3235 (setq ebib-multiline-raw t)
3236 (setq text (to-raw text))
3237 (setq ebib-multiline-raw nil))
3238 (select-window (ebib-temp-window) nil)
3239 (ebib-multiline-edit 'fields text))))
3241 (defun ebib-insert-abbreviation ()
3242 "Inserts an abbreviation from the ones defined in the database."
3243 (interactive)
3244 (if (gethash ebib-current-field ebib-cur-entry-hash)
3245 (beep)
3246 (when (edb-strings-list ebib-cur-db)
3247 (unwind-protect
3248 (progn
3249 (other-window 1)
3250 (let* ((collection (ebib-create-collection (edb-strings ebib-cur-db)))
3251 (string (completing-read "Abbreviation to insert: " collection nil t)))
3252 (when string
3253 (puthash ebib-current-field string ebib-cur-entry-hash)
3254 (ebib-set-modified t))))
3255 (other-window 1)
3256 ;; we can't do this earlier, because we would be writing to the index buffer...
3257 (ebib-redisplay-current-field)
3258 (ebib-next-field)))))
3260 (defun ebib-entry-help ()
3261 "Shows the info node for Ebib's entry buffer."
3262 (interactive)
3263 (ebib-lower)
3264 (info "(ebib) The Entry Buffer"))
3266 ;;;;;;;;;;;;;;;;;;
3267 ;; strings-mode ;;
3268 ;;;;;;;;;;;;;;;;;;
3270 (defvar ebib-strings-mode-map
3271 (let ((map (make-keymap)))
3272 (suppress-keymap map)
3273 (define-key map [up] 'ebib-prev-string)
3274 (define-key map [down] 'ebib-next-string)
3275 (define-key map [prior] 'ebib-strings-page-up)
3276 (define-key map [next] 'ebib-strings-page-down)
3277 (define-key map [home] 'ebib-goto-first-string)
3278 (define-key map [end] 'ebib-goto-last-string)
3279 (define-key map " " 'ebib-strings-page-down)
3280 (define-key map "a" 'ebib-add-string)
3281 (define-key map "b" 'ebib-strings-page-up)
3282 (define-key map "c" 'ebib-copy-string-contents)
3283 (define-key map "d" 'ebib-delete-string)
3284 (define-key map "e" 'ebib-edit-string)
3285 (define-key map "g" 'ebib-goto-first-string)
3286 (define-key map "G" 'ebib-goto-last-string)
3287 (define-key map "h" 'ebib-strings-help)
3288 (define-key map "j" 'ebib-next-string)
3289 (define-key map "k" 'ebib-prev-string)
3290 (define-key map "l" 'ebib-edit-multiline-string)
3291 (define-key map [(control n)] 'ebib-next-string)
3292 (define-key map [(meta n)] 'ebib-strings-page-down)
3293 (define-key map [(control p)] 'ebib-prev-string)
3294 (define-key map [(meta p)] 'ebib-strings-page-up)
3295 (define-key map "q" 'ebib-quit-strings-buffer)
3296 (define-key map "x" 'ebib-export-string)
3297 (define-key map "X" 'ebib-export-all-strings)
3298 (define-key map "\C-xb" 'disabled)
3299 (define-key map "\C-xk" 'disabled)
3300 map)
3301 "Keymap for the ebib strings buffer.")
3303 (define-derived-mode ebib-strings-mode
3304 fundamental-mode "Ebib-strings"
3305 "Major mode for the Ebib strings buffer."
3306 (setq buffer-read-only t)
3307 (setq truncate-lines t))
3309 (defun ebib-quit-strings-buffer ()
3310 "Quits editing the @STRING definitions."
3311 (interactive)
3312 (set-window-dedicated-p (selected-window) nil)
3313 (switch-to-buffer ebib-entry-buffer)
3314 (unless (eq ebib-layout 'full)
3315 (set-window-dedicated-p (selected-window) t))
3316 (select-window (get-buffer-window ebib-index-buffer) nil))
3318 (defun ebib-prev-string ()
3319 "Moves to the previous string."
3320 (interactive)
3321 (if (equal ebib-current-string (car (edb-strings-list ebib-cur-db))) ; if we're on the first string
3322 (beep)
3323 ;; go to the beginnig of the highlight and move upward one line.
3324 (goto-char (ebib-highlight-start ebib-strings-highlight))
3325 (forward-line -1)
3326 (setq ebib-current-string (prev-elem ebib-current-string (edb-strings-list ebib-cur-db)))
3327 (ebib-set-strings-highlight)))
3329 (defun ebib-next-string ()
3330 "Moves to the next string."
3331 (interactive)
3332 (if (equal ebib-current-string (last1 (edb-strings-list ebib-cur-db)))
3333 (when (interactive-p) (beep))
3334 (goto-char (ebib-highlight-start ebib-strings-highlight))
3335 (forward-line 1)
3336 (setq ebib-current-string (next-elem ebib-current-string (edb-strings-list ebib-cur-db)))
3337 (ebib-set-strings-highlight)))
3339 (defun ebib-goto-first-string ()
3340 "Moves to the first string."
3341 (interactive)
3342 (setq ebib-current-string (car (edb-strings-list ebib-cur-db)))
3343 (goto-char (point-min))
3344 (ebib-set-strings-highlight))
3346 (defun ebib-goto-last-string ()
3347 "Moves to the last string."
3348 (interactive)
3349 (setq ebib-current-string (last1 (edb-strings-list ebib-cur-db)))
3350 (goto-char (point-max))
3351 (forward-line -1)
3352 (ebib-set-strings-highlight))
3354 (defun ebib-strings-page-up ()
3355 "Moves 10 entries up in the database."
3356 (interactive)
3357 (let ((number-of-strings (length (edb-strings-list ebib-cur-db)))
3358 (remaining-number-of-strings (length (member ebib-current-string (edb-strings-list ebib-cur-db)))))
3359 (if (<= (- number-of-strings remaining-number-of-strings) 10)
3360 (ebib-goto-first-string)
3361 (setq ebib-current-string (nth
3362 (- number-of-strings remaining-number-of-strings 10)
3363 (edb-strings-list ebib-cur-db)))
3364 (goto-char (ebib-highlight-start ebib-strings-highlight))
3365 (forward-line -10)
3366 (ebib-set-strings-highlight)))
3367 (message ebib-current-string))
3369 (defun ebib-strings-page-down ()
3370 "Moves 10 entries down in the database."
3371 (interactive)
3372 (let ((number-of-strings (length (edb-strings-list ebib-cur-db)))
3373 (remaining-number-of-strings (length (member ebib-current-string (edb-strings-list ebib-cur-db)))))
3374 (if (<= remaining-number-of-strings 10)
3375 (ebib-goto-last-string)
3376 (setq ebib-current-string (nth
3377 (- number-of-strings remaining-number-of-strings -10)
3378 (edb-strings-list ebib-cur-db)))
3379 (goto-char (ebib-highlight-start ebib-strings-highlight))
3380 (forward-line 10)
3381 (ebib-set-strings-highlight)))
3382 (message ebib-current-string))
3384 (defun ebib-fill-strings-buffer ()
3385 "Fills the strings buffer with the @STRING definitions."
3386 (set-buffer ebib-strings-buffer)
3387 (with-buffer-writable
3388 (erase-buffer)
3389 (dolist (elem (edb-strings-list ebib-cur-db))
3390 (let ((str (to-raw (gethash elem (edb-strings ebib-cur-db)))))
3391 (insert (format "%-18s %s\n" elem
3392 (if (multiline-p str)
3393 (concat "+" (first-line str))
3394 (concat " " str)))))))
3395 (goto-char (point-min))
3396 (setq ebib-current-string (car (edb-strings-list ebib-cur-db)))
3397 (ebib-set-strings-highlight)
3398 (set-buffer-modified-p nil))
3400 (defun ebib-edit-string ()
3401 "Edits the value of an @STRING definition
3402 When the user enters an empty string, the value is not changed."
3403 (interactive)
3404 (let ((init-contents (to-raw (gethash ebib-current-string (edb-strings ebib-cur-db)))))
3405 (if (multiline-p init-contents)
3406 (ebib-edit-multiline-string)
3407 (if-str (new-contents (read-string (format "%s: " ebib-current-string)
3408 (if init-contents
3409 (cons init-contents 0)
3410 nil)
3411 ebib-minibuf-hist))
3412 (progn
3413 (puthash ebib-current-string (from-raw new-contents) (edb-strings ebib-cur-db))
3414 (ebib-redisplay-current-string)
3415 (ebib-next-string)
3416 (ebib-set-modified t))
3417 (error "@STRING definition cannot be empty")))))
3419 (defun ebib-copy-string-contents ()
3420 "Copies the contents of the current string to the kill ring."
3421 (interactive)
3422 (let ((contents (gethash ebib-current-string (edb-strings ebib-cur-db))))
3423 (kill-new contents)
3424 (message "String value copied.")))
3426 (defun ebib-delete-string ()
3427 "Deletes the current @STRING definition from the database."
3428 (interactive)
3429 (when (y-or-n-p (format "Delete @STRING definition %s? " ebib-current-string))
3430 (remhash ebib-current-string (edb-strings ebib-cur-db))
3431 (with-buffer-writable
3432 (let ((beg (progn
3433 (goto-char (ebib-highlight-start ebib-strings-highlight))
3434 (point))))
3435 (forward-line 1)
3436 (delete-region beg (point))))
3437 (let ((new-cur-string (next-elem ebib-current-string (edb-strings-list ebib-cur-db))))
3438 (setf (edb-strings-list ebib-cur-db) (delete ebib-current-string (edb-strings-list ebib-cur-db)))
3439 (when (null new-cur-string) ; deleted the last string
3440 (setq new-cur-string (last1 (edb-strings-list ebib-cur-db)))
3441 (forward-line -1))
3442 (setq ebib-current-string new-cur-string))
3443 (ebib-set-strings-highlight)
3444 (ebib-set-modified t)
3445 (message "@STRING definition deleted.")))
3447 (defun ebib-add-string ()
3448 "Creates a new @STRING definition."
3449 (interactive)
3450 (if-str (new-abbr (read-string "New @STRING abbreviation: "))
3451 (progn
3452 (if (member new-abbr (edb-strings-list ebib-cur-db))
3453 (error (format "%s already exists" new-abbr)))
3454 (if-str (new-string (read-string (format "Value for %s: " new-abbr)))
3455 (progn
3456 (ebib-insert-string new-abbr new-string ebib-cur-db t)
3457 (sort-in-buffer (length (edb-strings-list ebib-cur-db)) new-abbr)
3458 (with-buffer-writable
3459 (insert (format "%-19s %s\n" new-abbr new-string)))
3460 (forward-line -1)
3461 (ebib-set-strings-highlight)
3462 (setq ebib-current-string new-abbr)
3463 (ebib-set-modified t))))))
3465 (defun ebib-export-string (prefix)
3466 "Exports the current @STRING.
3467 The prefix argument indicates which database to copy the string
3468 to. If no prefix argument is present, a filename is asked to
3469 which the string is appended."
3470 (interactive "P")
3471 (let ((num (ebib-prefix prefix)))
3472 (if num
3473 (ebib-export-to-db num (format "@STRING definition `%s' copied to database %%d" ebib-current-string)
3474 #'(lambda (db)
3475 (let ((abbr ebib-current-string)
3476 (string (gethash ebib-current-string (edb-strings ebib-cur-db))))
3477 (if (member abbr (edb-strings-list db))
3478 (error "@STRING definition already exists in database %d" num)
3479 (ebib-insert-string abbr string db t)))))
3480 (ebib-export-to-file (format "Export @STRING definition `%s' to file: " ebib-current-string)
3481 (format "@STRING definition `%s' exported to %%s" ebib-current-string)
3482 #'(lambda ()
3483 (insert (format "\n@string{%s = %s}\n"
3484 ebib-current-string
3485 (gethash ebib-current-string (edb-strings ebib-cur-db)))))))))
3487 (defun ebib-export-all-strings (prefix)
3488 "Exports all @STRING definitions.
3489 If a prefix argument is given, it is taken as the database to
3490 copy the definitions to. Without prefix argument, asks for a file
3491 to append them to."
3492 (interactive "P")
3493 (when ebib-current-string ; there is always a current string, unless there are no strings
3494 (let ((num (ebib-prefix prefix)))
3495 (if num
3496 (ebib-export-to-db
3497 num "All @STRING definitions copied to database %d"
3498 #'(lambda (db)
3499 (mapc #'(lambda (abbr)
3500 (if (member abbr (edb-strings-list db))
3501 (message "@STRING definition `%s' already exists in database %d" abbr num)
3502 (ebib-insert-string abbr (gethash abbr (edb-strings ebib-cur-db)) db t)))
3503 (edb-strings-list ebib-cur-db))))
3504 (ebib-export-to-file "Export all @STRING definitions to file: "
3505 "All @STRING definitions exported to %s"
3506 #'(lambda ()
3507 (insert (format "\n")) ; to keep things tidy.
3508 (ebib-format-strings ebib-cur-db)))))))
3510 (defun ebib-edit-multiline-string ()
3511 "Edits the current string in multiline-mode."
3512 (interactive)
3513 (select-window (ebib-temp-window) nil)
3514 (ebib-multiline-edit 'string (to-raw (gethash ebib-current-string (edb-strings ebib-cur-db)))))
3516 (defun ebib-strings-help ()
3517 "Shows the info node on Ebib's strings buffer."
3518 (interactive)
3519 (ebib-lower)
3520 (info "(ebib) The Strings Buffer"))
3522 ;;;;;;;;;;;;;;;;;;;;
3523 ;; multiline edit ;;
3524 ;;;;;;;;;;;;;;;;;;;;
3526 (define-minor-mode ebib-multiline-mode
3527 "Minor mode for Ebib's multiline edit buffer."
3528 :init-value nil :lighter nil :global nil
3529 :keymap '(("\C-c|q" . ebib-quit-multiline-edit)
3530 ("\C-c|c" . ebib-cancel-multiline-edit)
3531 ("\C-c|s" . ebib-save-from-multiline-edit)
3532 ("\C-c|h" . ebib-multiline-help)))
3534 (easy-menu-define ebib-multiline-menu ebib-multiline-mode-map "Ebib multiline menu"
3535 '("Ebib"
3536 ["Store Text and Exit" ebib-quit-multiline-edit t]
3537 ["Cancel Edit" ebib-cancel-multiline-edit t]
3538 ["Save Text" ebib-save-from-multiline-edit t]
3539 ["Help" ebib-multiline-help t]))
3541 (easy-menu-add ebib-multiline-menu ebib-multiline-mode-map)
3543 (defun ebib-multiline-edit (type &optional starttext)
3544 "Switches to Ebib's multiline edit buffer.
3545 STARTTEXT is a string that contains the initial text of the buffer."
3546 ;; note: the buffer is put in the currently active window!
3547 (setq ebib-pre-multiline-buffer (current-buffer))
3548 (switch-to-buffer ebib-multiline-buffer)
3549 (set-buffer-modified-p nil)
3550 (erase-buffer)
3551 (setq ebib-editing type)
3552 (when starttext
3553 (insert starttext)
3554 (goto-char (point-min))
3555 (set-buffer-modified-p nil)))
3557 (defun ebib-quit-multiline-edit ()
3558 "Quits the multiline edit buffer, saving the text."
3559 (interactive)
3560 (ebib-store-multiline-text)
3561 (ebib-leave-multiline-edit-buffer)
3562 (cond
3563 ((eq ebib-editing 'fields)
3564 (ebib-next-field))
3565 ((eq ebib-editing 'strings)
3566 (ebib-next-string)))
3567 (message "Text stored."))
3569 (defun ebib-cancel-multiline-edit ()
3570 "Quits the multiline edit buffer and discards the changes."
3571 (interactive)
3572 (catch 'no-cancel
3573 (when (buffer-modified-p)
3574 (unless (y-or-n-p "Text has been modified. Abandon changes? ")
3575 (throw 'no-cancel nil)))
3576 (ebib-leave-multiline-edit-buffer)))
3578 (defun ebib-leave-multiline-edit-buffer ()
3579 "Leaves the multiline edit buffer.
3580 Restores the previous buffer in the window that the multiline
3581 edit buffer was shown in."
3582 (switch-to-buffer ebib-pre-multiline-buffer)
3583 (cond
3584 ((eq ebib-editing 'preamble)
3585 (select-window (get-buffer-window ebib-index-buffer) nil))
3586 ((eq ebib-editing 'fields)
3587 ;; in full-frame layout, select-window isn't necessary, but it doesn't hurt either.
3588 (select-window (get-buffer-window ebib-entry-buffer) nil)
3589 (ebib-redisplay-current-field))
3590 ((eq ebib-editing 'strings)
3591 ;; in full-frame layout, select-window isn't necessary, but it doesn't hurt either.
3592 (select-window (get-buffer-window ebib-strings-buffer) nil)
3593 (ebib-redisplay-current-string))))
3595 (defun ebib-save-from-multiline-edit ()
3596 "Saves the database from within the multiline edit buffer.
3597 The text being edited is stored before saving the database."
3598 (interactive)
3599 (ebib-store-multiline-text)
3600 (ebib-save-database ebib-cur-db)
3601 (set-buffer-modified-p nil))
3603 (defun ebib-store-multiline-text ()
3604 "Stores the text being edited in the multiline edit buffer."
3605 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
3606 (cond
3607 ((eq ebib-editing 'preamble)
3608 (if (equal text "")
3609 (setf (edb-preamble ebib-cur-db) nil)
3610 (setf (edb-preamble ebib-cur-db) text)))
3611 ((eq ebib-editing 'fields)
3612 (if (equal text "")
3613 (remhash ebib-current-field ebib-cur-entry-hash)
3614 (when (not ebib-multiline-raw)
3615 (setq text (from-raw text)))
3616 (puthash ebib-current-field text ebib-cur-entry-hash)))
3617 ((eq ebib-editing 'strings)
3618 (if (equal text "")
3619 ;; with ERROR, we avoid execution of EBIB-SET-MODIFIED and
3620 ;; MESSAGE, but we also do not switch back to the strings
3621 ;; buffer. this may not be so bad, actually, because the user
3622 ;; may want to change his edit.
3623 (error "@STRING definition cannot be empty ")
3624 (setq text (from-raw text)) ; strings cannot be raw
3625 (puthash ebib-current-string text (edb-strings ebib-cur-db))))))
3626 (ebib-set-modified t))
3628 (defun ebib-multiline-help ()
3629 "Show the info node on Ebib's multiline edit buffer."
3630 (interactive)
3631 (ebib-lower)
3632 (info "(ebib) The Multiline Edit Buffer"))
3634 ;;;;;;;;;;;;;;;;;;;
3635 ;; ebib-log-mode ;;
3636 ;;;;;;;;;;;;;;;;;;;
3638 (defvar ebib-log-mode-map
3639 (let ((map (make-keymap)))
3640 (suppress-keymap map)
3641 (define-key map " " 'scroll-up)
3642 (define-key map "b" 'scroll-down)
3643 (define-key map "q" 'ebib-quit-log-buffer)
3644 map)
3645 "Keymap for the ebib log buffer.")
3647 (define-derived-mode ebib-log-mode
3648 fundamental-mode "Ebib-log"
3649 "Major mode for the Ebib log buffer."
3650 (local-set-key "\C-xb" 'ebib-quit-log-buffer)
3651 (local-set-key "\C-xk" 'ebib-quit-log-buffer))
3653 (defun ebib-quit-log-buffer ()
3654 "Exits the log buffer."
3655 (interactive)
3656 (set-window-dedicated-p (selected-window) nil)
3657 (switch-to-buffer ebib-entry-buffer)
3658 (unless (eq ebib-layout 'full)
3659 (set-window-dedicated-p (selected-window) t))
3660 (select-window (get-buffer-window ebib-index-buffer) nil))
3662 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3663 ;; functions for non-Ebib buffers ;;
3664 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3666 (defun ebib-import ()
3667 "Searches for BibTeX entries in the current buffer.
3668 The entries are added to the current database (i.e. the database
3669 that was active when Ebib was lowered. Works on the whole buffer,
3670 or on the region if it is active."
3671 (interactive)
3672 (if (not ebib-cur-db)
3673 (error "No database loaded. Use `o' to open a database")
3674 (if (edb-virtual ebib-cur-db)
3675 (error "Cannot import to a virtual database")
3676 (with-syntax-table ebib-syntax-table
3677 (save-excursion
3678 (save-restriction
3679 (if (region-active)
3680 (narrow-to-region (region-beginning)
3681 (region-end)))
3682 (let ((buffer (current-buffer)))
3683 (with-temp-buffer
3684 (insert-buffer-substring buffer)
3685 (let ((n (ebib-find-bibtex-entries t)))
3686 (setf (edb-keys-list ebib-cur-db) (sort (edb-keys-list ebib-cur-db) 'string<))
3687 (setf (edb-n-entries ebib-cur-db) (length (edb-keys-list ebib-cur-db)))
3688 (when (edb-strings-list ebib-cur-db)
3689 (setf (edb-strings-list ebib-cur-db) (sort (edb-strings-list ebib-cur-db) 'string<)))
3690 (setf (edb-cur-entry ebib-cur-db) (edb-keys-list ebib-cur-db))
3691 (ebib-fill-entry-buffer)
3692 (ebib-fill-index-buffer)
3693 (ebib-set-modified t)
3694 (message (format "%d entries, %d @STRINGs and %s @PREAMBLE found in buffer."
3695 (car n)
3696 (cadr n)
3697 (if (caddr n)
3699 "no"))))))))))))
3701 (defun ebib-get-db-from-filename (filename)
3702 "Returns the database struct associated with FILENAME."
3703 (when (file-name-absolute-p filename)
3704 (setq filename (expand-file-name filename))) ; expand ~, . and ..
3705 (catch 'found
3706 (mapc #'(lambda (db)
3707 (if (string= filename
3708 ; if filename is absolute, we want to compare to the
3709 ; absolute filename of the database, otherwise we
3710 ; should use only the non-directory component.
3711 (if (file-name-absolute-p filename)
3712 (edb-filename db)
3713 (file-name-nondirectory (edb-filename db))))
3714 (throw 'found db)))
3715 ebib-databases)
3716 nil))
3718 (defun ebib-get-local-databases ()
3719 "Returns a list of .bib files associated with the file in the current LaTeX buffer.
3720 Each element in the list is a string holding the name of the .bib
3721 file. This function simply searches the current LaTeX file or its
3722 master file for a \\bibliography command and returns the file(s)
3723 given in its argument. If no \\bibliography command is found,
3724 returns the symbol NONE."
3725 (let ((texfile-buffer (current-buffer))
3726 texfile)
3727 ;; if AucTeX's TeX-master is used and set to a string, we must
3728 ;; search that file for a \bibliography command, as it's more
3729 ;; likely to be in there than in the file we're in.
3730 (and (boundp 'TeX-master)
3731 (stringp TeX-master)
3732 (setq texfile (ensure-extension TeX-master "tex")))
3733 (with-temp-buffer
3734 (if (and texfile (file-readable-p texfile))
3735 (insert-file-contents texfile)
3736 (insert-buffer-substring texfile-buffer))
3737 (save-excursion
3738 (goto-char (point-min))
3739 (if (re-search-forward "\\\\bibliography{\\(.*?\\)}" nil t)
3740 (mapcar #'(lambda (file)
3741 (ensure-extension file "bib"))
3742 (split-string (buffer-substring-no-properties (match-beginning 1) (match-end 1)) ",[ ]*"))
3743 'none)))))
3745 (defun ebib-insert-bibtex-key ()
3746 "Inserts a BibTeX key at POINT.
3747 The user is prompted for a BibTeX key and has to choose one from
3748 the database(s) associated with the current LaTeX file, or from
3749 the current database if there is no \\bibliography command. Tab
3750 completion works."
3751 (interactive)
3752 (ebib-execute-when
3753 ((database)
3754 (or ebib-local-bibtex-filenames
3755 (setq ebib-local-bibtex-filenames (ebib-get-local-databases)))
3756 (let (collection)
3757 (if (eq ebib-local-bibtex-filenames 'none)
3758 (if (null (edb-cur-entry ebib-cur-db))
3759 (error "No entries found in current database")
3760 (setq collection (ebib-create-collection (edb-database ebib-cur-db))))
3761 (mapc #'(lambda (file)
3762 (let ((db (ebib-get-db-from-filename file)))
3763 (cond
3764 ((null db)
3765 (message "Database %s not loaded" file))
3766 ((null (edb-cur-entry db))
3767 (message "No entries in database %s" file))
3768 (t (setq collection (append (ebib-create-collection (edb-database db))
3769 collection))))))
3770 ebib-local-bibtex-filenames))
3771 (when collection
3772 (let* ((key (completing-read "Key to insert: " collection nil t nil ebib-minibuf-hist))
3773 (insert-string (if-str (command (completing-read "Command to use: " ebib-insertion-commands
3774 nil nil nil ebib-minibuf-hist))
3775 (ebib-create-citation-command command
3777 (cadr (assoc command ebib-insertion-commands))
3779 key)
3780 key)))
3781 (when insert-string
3782 (insert insert-string))))))
3783 ((default)
3784 (error "No database loaded"))))
3786 (defun ebib-entry-summary ()
3787 "Shows the fields of the key at POINT.
3788 The key is searched in the database associated with the LaTeX
3789 file, or in the current database if no \\bibliography command can
3790 be found."
3791 (interactive)
3792 (ebib-execute-when
3793 ((database)
3794 (or ebib-local-bibtex-filenames
3795 (setq ebib-local-bibtex-filenames (ebib-get-local-databases)))
3796 (let ((key (read-string-at-point "\"#%'(),={} \n\t\f"))
3797 entry
3798 database)
3799 (if (eq ebib-local-bibtex-filenames 'none)
3800 (if (not (member key (edb-keys-list ebib-cur-db)))
3801 (error "Entry `%s' is not in the current database" key)
3802 (setq entry (gethash key (edb-database ebib-cur-db)))
3803 (setq database ebib-cur-db))
3804 (multiple-value-setq (entry database)
3805 (catch 'found
3806 (mapc #'(lambda (file)
3807 (let ((db (ebib-get-db-from-filename file)))
3808 (if (null db)
3809 (message "Database %s not loaded" file)
3810 (if (member key (edb-keys-list db))
3811 (throw 'found (values (gethash key (edb-database db)) db))))))
3812 ebib-local-bibtex-filenames)
3813 (list nil nil))))
3814 (if (null entry)
3815 (error "Entry `%s' not found" key)
3816 (let ((index-window (get-buffer-window ebib-index-buffer)))
3817 (if (not index-window)
3818 (with-help-window "*Help*"
3819 (ebib-format-fields entry 'princ))
3820 (with-selected-window index-window
3821 (setq ebib-cur-db database)
3822 (ebib-fill-index-buffer)
3823 (setf (edb-cur-entry ebib-cur-db) (member key (edb-keys-list ebib-cur-db)))
3824 (goto-char (point-min))
3825 (re-search-forward (format "^%s " key))
3826 (beginning-of-line)
3827 (ebib-set-index-highlight))
3828 (ebib-fill-entry-buffer))))))
3829 ((default)
3830 (error "No database(s) loaded"))))
3832 (provide 'ebib)
3834 ;;; ebib ends here