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