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