Removed ebib-entry-types-hash.
[ebib.git] / src / ebib.el
blob137a09c9b1fe7a8fc7ef41e988ae10337264387c
1 ;; Ebib v==VERSION==
2 ;;
3 ;; Copyright (c) 2003-2008 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-strings '((0 . "%s")
76 (1 . "\\cite{%s}"))
77 "*The string to insert when calling EBIB-INSERT-BIBTEX-KEY.
78 The directive \"%s\" is replaced with the entry key."
79 :group 'ebib
80 :type '(repeat (cons :tag "Insertion string" (integer :tag "Number") (string))))
82 (defcustom ebib-sort-order nil
83 "*The fields on which the BibTeX entries are to be sorted in the .bib file.
84 Sorting is done on different sort levels, and each sort level contains one
85 or more sort keys."
86 :group 'ebib
87 :type '(repeat (repeat :tag "Sort level" (symbol :tag "Sort field"))))
89 (defcustom ebib-save-xrefs-first nil
90 "*If true, entries with a crossref field will be saved first in the .bib-file.
91 Setting this option has unpredictable results for the sort order
92 of entries, so it is not compatible with setting the Sort Order option."
93 :group 'ebib
94 :type 'boolean)
96 (defface ebib-crossref-face '((t (:foreground "red")))
97 "*Face used to indicate values inherited from crossreferenced entries."
98 :group 'ebib)
100 (defface ebib-marked-face (if (featurep 'xemacs)
101 '((t (:foreground "white" :background "red")))
102 '((t (:inverse-video t))))
103 "*Face to indicate marked entries."
104 :group 'ebib)
106 (defcustom ebib-use-timestamp nil
107 "*If true, new entries will get a time stamp.
108 The time stamp will be stored in a field \"timestamp\" that can
109 be made visible with the `H' command in the index buffer."
110 :group 'ebib
111 :type 'boolean)
113 (defcustom ebib-timestamp-format "%a %b %e %T %Y"
114 "*Format of the time string used in the timestamp.
115 The format is passed unmodified to FORMAT-TIME-STRING, see the
116 documentation of that function for details."
117 :group 'ebib
118 :type 'string)
120 (defcustom ebib-standard-url-field 'url
121 "*Standard field to store urls in.
122 In the index buffer, the command ebib-browse-url can be used to
123 send a url to a browser. This option sets the field from which
124 this command extracts the url."
125 :group 'ebib
126 :type 'symbol)
128 (defcustom ebib-url-regexp "\\\\url{\\(.*\\)}\\|https?://[^ '<>\"\n\t\f]+"
129 "*Regular expression to extract urls."
130 :group 'ebib
131 :type 'string)
133 (defcustom ebib-browser-command ""
134 "*Command to call the browser with.
135 GNU/Emacs has a function call-browser, which is used if this
136 option is unset."
137 :group 'ebib
138 :type '(string :tag "Browser command"))
140 (defcustom ebib-standard-file-field 'file
141 "*Standard field to store filenames in.
142 In the index buffer, the command ebib-view-file can be used to
143 view a file externally. This option sets the field from which
144 this command extracts the filename."
145 :group 'ebib
146 :type 'symbol)
148 (defcustom ebib-file-associations '(("pdf" . "xpdf")
149 ("ps" . "gv"))
150 "*List of file associations.
151 Lists file extensions together with external programs to handle
152 files with those extensions. If the external program is left
153 blank, Ebib tries to handle the file internally in
154 Emacs (e.g. with doc-view-mode)."
155 :group 'ebib
156 :type '(repeat (cons :tag "File association"
157 (string :tag "Extension") (string :tag "Command"))))
159 (defcustom ebib-file-regexp "[^?|\\:*<>\" \n\t\f]+"
160 "*Regular expression to match filenames."
161 :group 'ebib
162 :type 'string)
164 (defcustom ebib-file-search-dirs '("~")
165 "*List of directories to search for files."
166 :group 'ebib
167 :type '(repeat :tag "Search directories" (string :tag "Directory")))
169 (defcustom ebib-print-preamble nil
170 "*Preamble used for the LaTeX file for printing the database.
171 Each string is added to the preamble on a separate line."
172 :group 'ebib
173 :type '(repeat (string :tag "Add to preamble")))
175 (defcustom ebib-print-multiline nil
176 "*If set, multiline fields are included when printing the database."
177 :group 'ebib
178 :type 'boolean)
180 (defcustom ebib-latex-preamble '("\\bibliographystyle{plain}")
181 "*Preamble used for the LaTeX file for BibTeXing the database.
182 Each string is added to the preamble on a separate line."
183 :group 'ebib
184 :type '(repeat (string :tag "Add to preamble")))
186 (defcustom ebib-print-tempfile ""
187 "*Temporary file for use with EBIB-PRINT-DATABASE and EBIB-LATEX-DATABASE."
188 :group 'ebib
189 :type '(file))
191 (defcustom ebib-allow-identical-fields nil
192 "*If set, Ebib handles multiple occurrences of a field gracefully."
193 :group 'ebib
194 :type 'boolean)
196 (defvar ebib-unique-field-list nil
197 "Holds a list of all field names.")
199 (defmacro add-to-listq (listvar element &optional append fn)
200 (if (or (featurep 'xemacs)
201 (string< emacs-version "22"))
202 `(add-to-list (quote ,listvar) ,element ,append)
203 `(add-to-list (quote ,listvar) ,element ,append ,fn)))
205 (defun ebib-set-unique-field-list (var value)
206 "Sets EBIB-UNIQUE-FIELD-LIST on the basis of EBIB-ENTRY-TYPES"
207 (set-default var value)
208 (setq ebib-unique-field-list nil)
209 (mapc #'(lambda (entry)
210 (mapc #'(lambda (field)
211 (add-to-listq ebib-unique-field-list field t 'eq))
212 (cadr entry))
213 (mapc #'(lambda (field)
214 (add-to-listq ebib-unique-field-list field t 'eq))
215 (caddr entry)))
216 value))
218 (defcustom ebib-entry-types
219 '((article ;; name of entry type
220 (author title journal year) ;; obligatory fields
221 (volume number pages month note)) ;; optional fields
223 (book
224 (author title publisher year)
225 (editor volume number series address edition month note))
227 (booklet
228 (title)
229 (author howpublished address month year note))
231 (inbook
232 (author title chapter pages publisher year)
233 (editor volume series address edition month note))
235 (incollection
236 (author title booktitle publisher year)
237 (editor volume number series type chapter pages address edition month note))
239 (inproceedings
240 (author title booktitle year)
241 (editor pages organization publisher address month note))
243 (manual
244 (title)
245 (author organization address edition month year note))
247 (misc
249 (title author howpublished month year note))
251 (mastersthesis
252 (author title school year)
253 (address month note))
255 (phdthesis
256 (author title school year)
257 (address month note))
259 (proceedings
260 (title year)
261 (editor publisher organization address month note))
263 (techreport
264 (author title institution year)
265 (type number address month note))
267 (unpublished
268 (author title note)
269 (month year)))
271 "List of entry type definitions for Ebib"
272 :group 'ebib
273 :type '(repeat (list :tag "Entry type" (symbol :tag "Name")
274 (repeat :tag "Obligatory fields" (symbol :tag "Field"))
275 (repeat :tag "Optional fields" (symbol :tag "Field"))))
276 :set 'ebib-set-unique-field-list)
278 ;; generic for all databases
280 ;; constants and variables that are set only once
281 (defconst ebib-bibtex-identifier "[^\"#%'(),={} \t\n\f]*" "Regexp describing a licit BibTeX identifier.")
282 (defconst ebib-version "==VERSION==")
283 (defvar ebib-initialized nil "T if Ebib has been initialized.")
285 ;; buffers and highlights
286 (defvar ebib-index-buffer nil "The index buffer.")
287 (defvar ebib-entry-buffer nil "The entry buffer.")
288 (defvar ebib-strings-buffer nil "The strings buffer.")
289 (defvar ebib-multiline-buffer nil "Buffer for editing multiline strings.")
290 (defvar ebib-log-buffer nil "Buffer showing warnings and errors during loading of .bib files")
291 (defvar ebib-index-highlight nil "Highlight to mark the current entry.")
292 (defvar ebib-fields-highlight nil "Highlight to mark the current field.")
293 (defvar ebib-strings-highlight nil "Highlight to mark the current string.")
295 ;; general bookkeeping
296 (defvar ebib-minibuf-hist nil "Holds the minibuffer history for Ebib")
297 (defvar ebib-saved-window-config nil "Stores the window configuration when Ebib is called.")
298 (defvar ebib-pre-ebib-window nil "The window that was active when Ebib was called.")
299 (defvar ebib-pre-multiline-buffer nil "The buffer in the window before switching to the multiline edit buffer.")
300 (defvar ebib-export-filename nil "Filename to export entries to.")
301 (defvar ebib-push-buffer nil "Buffer to push entries to.")
302 (defvar ebib-search-string nil "Stores the last search string.")
303 (defvar ebib-editing nil "Indicates what the user is editing.
304 Its value can be 'strings, 'fields, or 'preamble.")
305 (defvar ebib-multiline-raw nil "Indicates whether the multiline text being edited is raw.")
306 (defvar ebib-log-error nil "Indicates whether an error was logged.")
307 (defvar ebib-local-bibtex-filenames nil
308 "A buffer-local variable holding a list of the name(s) of that buffer's .bib file(s)")
309 (make-variable-buffer-local 'ebib-local-bibtex-filenames)
310 (defvar ebib-syntax-table (make-syntax-table) "Syntax table used for reading .bib files.")
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 ?\) "." ebib-syntax-table)
315 (modify-syntax-entry ?\" "w" ebib-syntax-table)
317 ;; the databases
319 ;; each database is represented by a struct
320 (defstruct edb
321 (database (make-hash-table :test 'equal)) ; hashtable containing the database itself
322 (keys-list nil) ; sorted list of the keys in the database
323 (cur-entry nil) ; sublist of KEYS-LIST that starts with the current entry
324 (marked-entries nil) ; list of marked entries
325 (n-entries 0) ; number of entries stored in this database
326 (strings (make-hash-table :test 'equal)) ; hashtable with the @STRING definitions
327 (strings-list nil) ; sorted list of the @STRING abbreviations
328 (preamble nil) ; string with the @PREAMBLE definition
329 (filename nil) ; name of the BibTeX file that holds this database
330 (name nil) ; name of the database
331 (modified nil) ; has this database been modified?
332 (make-backup nil) ; do we need to make a backup of the .bib file?
333 (virtual nil)) ; is this a virtual database?
335 ;; the master list and the current database
336 (defvar ebib-databases nil "List of structs containing the databases.")
337 (defvar ebib-cur-db nil "The database that is currently active.")
339 ;;;;;; bookkeeping required when editing field values or @STRING definitions
341 (defvar ebib-hide-hidden-fields t "If set to T, hidden fields are not shown.")
343 ;; these two variables are set when the user enters the entry buffer
344 (defvar ebib-cur-entry-hash nil "The hash table containing the data of the current entry.")
345 (defvar ebib-cur-entry-fields nil "The fields of the type of the current entry.")
347 ;; and these two are set by EBIB-FILL-ENTRY-BUFFER and EBIB-FILL-STRINGS-BUFFER, respectively
348 (defvar ebib-current-field nil "The current field.")
349 (defvar ebib-current-string nil "The current @STRING definition.")
351 ;; the prefix key is stored in a variable so that the user can customise it.
352 (defvar ebib-prefix-key ?\;)
354 ;; this is an AucTeX variable, but we want to check its value, so let's
355 ;; keep the compiler from complaining.
356 (eval-when-compile
357 (defvar TeX-master))
359 ;; this is to keep XEmacs from complaining.
360 (eval-when-compile
361 (if (featurep 'xemacs)
362 (defvar mark-active)))
364 ;; XEmacs has line-number, not line-number-at-pos.
365 (eval-and-compile
366 (if (featurep 'xemacs)
367 (defalias 'line-number-at-pos 'line-number)))
369 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
370 ;; useful macros and functions ;;
371 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
373 (defmacro nor (&rest args)
374 "Returns T if none of its arguments are true."
375 `(not (or ,@args)))
377 ;; we sometimes (often, in fact ;-) need to do something with a string, but
378 ;; take special action (or do nothing) if that string is empty. IF-STR
379 ;; makes that easier:
381 (defmacro if-str (bindvar then &rest else)
382 "Execute THEN only if STRING is nonempty.
383 Format: (if-str (var value) then-form [else-forms]) VAR is bound
384 to VALUE, which is evaluated. If VAR is a nonempty string,
385 THEN-FORM is executed. If VAR is either \"\" or nil, ELSE-FORM is
386 executed. Returns the value of THEN or of ELSE."
387 (declare (indent 2))
388 `(let ,(list bindvar)
389 (if (nor (null ,(car bindvar))
390 (equal ,(car bindvar) ""))
391 ,then
392 ,@else)))
394 (defmacro last1 (lst &optional n)
395 "Returns the last (or Nth last) element of LST."
396 `(car (last ,lst ,n)))
398 ;; we sometimes need to walk through lists. these functions yield the
399 ;; element directly preceding or following ELEM in LIST. in order to work
400 ;; properly, ELEM must be unique in LIST, obviously. if ELEM is the
401 ;; first/last element of LIST, or if it is not contained in LIST at all,
402 ;; the result is nil.
403 (defun next-elem (elem list)
404 (cadr (member elem list)))
406 (defun prev-elem (elem list)
407 (if (or (equal elem (car list))
408 (not (member elem list)))
410 (last1 list (1+ (length (member elem list))))))
412 (defun read-string-at-point (chars)
413 "Reads a string at POINT delimited by CHARS and returns it.
414 CHARS is a string of characters that should not occur in the string."
415 (save-excursion
416 (skip-chars-backward (concat "^" chars))
417 (let ((beg (point)))
418 (looking-at-goto-end (concat "[^" chars "]*"))
419 (buffer-substring-no-properties beg (point)))))
421 (defun remove-from-string (string remove)
422 "Returns a copy of STRING with all the occurrences of REMOVE taken out.
423 REMOVE can be a regex."
424 (apply 'concat (split-string string remove)))
426 (defun in-string (char string)
427 "Returns T if CHAR is in STRING, otherwise NIL."
428 (catch 'found
429 (do ((len (length string))
430 (i 0 (1+ i)))
431 ((= i len) nil)
432 (if (eq char (aref string i))
433 (throw 'found t)))))
435 (defun ensure-extension (string ext)
436 "Makes sure STRING has the extension EXT, by appending it if necessary.
437 EXT should be an extension without the dot."
438 (if (string-match (concat "\\." ext "$") string)
439 string
440 (concat string "." ext)))
442 (defmacro with-buffer-writable (&rest body)
443 "Makes the current buffer writable and executes the commands in BODY.
444 After BODY is executed, the buffer modified flag is unset."
445 (declare (indent defun))
446 `(unwind-protect
447 (let ((buffer-read-only nil))
448 ,@body)
449 (set-buffer-modified-p nil)))
451 (defmacro safe-write-region (start end filename &optional append visit lockname mustbenew)
452 "XEmacs does not have the MUSTBENEW argument, so this is a way to implement it."
453 (if (featurep 'xemacs)
454 `(if (and (file-exists-p ,filename)
455 (not (y-or-n-p (format "File %s already exists; overwrite anyway? " ,filename))))
456 (error "File %s exist" ,filename)
457 (write-region ,start ,end ,filename ,append ,visit ,lockname))
458 `(write-region ,start ,end ,filename ,append ,visit ,lockname ,mustbenew)))
460 (defun symbol-or-string (x)
461 "Returns the symbol-name of X if X is a symbol, otherwise return X.
462 Much like SYMBOL-NAME, except it does not throw an error if X is
463 not a symbol."
464 (if (symbolp x)
465 (symbol-name x)
468 ;; XEmacs doesn't know about propertize...
469 (if (not (fboundp 'propertize))
470 (defun propertize (string &rest properties)
471 "Return a copy of STRING with text properties added.
472 First argument is the string to copy. Remaining arguments form a
473 sequence of PROPERTY VALUE pairs for text properties to add to
474 the result."
475 (let ((new-string (copy-sequence string)))
476 (add-text-properties 0 (length new-string) properties new-string)
477 new-string)))
479 (defun region-active ()
480 (if (featurep 'xemacs)
481 (region-active-p)
482 mark-active))
484 ;; RAW-P determines if STRING is raw. note that we cannot do this by
485 ;; simply checking whether STRING begins with { and ends with } (or
486 ;; begins and ends with "), because something like "{abc} # D # {efg}"
487 ;; would then be incorrectly recognised as non-raw. so we need to do
488 ;; the following: take out everything that is between braces or
489 ;; quotes, and see if anything is left. if there is, the original
490 ;; string was raw, otherwise it was not.
492 ;; so i first check whether the string begins with { or ". if not, we
493 ;; certainly have a raw string. (RAW-P recognises this through the default
494 ;; clause of the COND.) if the first character is { or ", we first take out
495 ;; every occurrence of backslash-escaped { and } or ", so that the rest of
496 ;; the function does not get confused over them.
498 ;; then, if the first character is {, i use REMOVE-FROM-STRING to take out
499 ;; every occurrence of the regex "{[^{]*?}", which translates to "the
500 ;; smallest string that starts with { and ends with }, and does not contain
501 ;; another {. IOW, it takes out the innermost braces and their
502 ;; contents. because braces may be embedded, we have to repeat this step
503 ;; until no more balanced braces are found in the string. (note that it
504 ;; would be unwise to check for just the occurrence of { or }, because that
505 ;; would throw RAW-P in an infinite loop if a string contains an unbalanced
506 ;; brace.)
508 ;; for strings beginning with " i do the same, except that it is not
509 ;; necessary to repeat this in a WHILE loop, for the simple reason that
510 ;; strings surrounded with double quotes cannot be embedded; i.e.,
511 ;; "ab"cd"ef" is not a valid (BibTeX) string, while {ab{cd}ef} is.
513 ;; note: because these strings are to be fed to BibTeX and ultimately
514 ;; (La)TeX, it might seem that we don't need to worry about strings
515 ;; containing unbalanced braces, because (La)TeX would choke on them. but
516 ;; the user may inadvertently enter such a string, and we therefore need to
517 ;; be able to handle it. (alternatively, we could perform a check on
518 ;; strings and warn the user.)
520 (defun raw-p (string)
521 "Non-nil if STRING is raw."
522 (when (stringp string)
523 (cond
524 ((eq (string-to-char string) ?\{)
525 ;; we remove all occurrences of `\{' and of `\}' from the string:
526 (let ((clear-str (remove-from-string (remove-from-string string "[\\][{]")
527 "[\\][}]")))
528 (while (and (in-string ?\{ clear-str) (in-string ?\} clear-str))
529 (setq clear-str (remove-from-string clear-str "{[^{]*?}")))
530 (> (length clear-str) 0)))
531 ((eq (string-to-char string) ?\")
532 (let ((clear-str (remove-from-string string "[\\][\"]"))) ; remove occurrences of `\"'
533 (setq clear-str (remove-from-string clear-str "\"[^\"]*?\""))
534 (> (length clear-str) 0)))
535 (t t))))
537 (defun to-raw (string)
538 "Converts a string to its raw counterpart."
539 (if (and (stringp string)
540 (not (raw-p string)))
541 (substring string 1 -1)
542 string))
544 (defun from-raw (string)
545 "Converts a raw string to a non-raw one."
546 (if (raw-p string)
547 (concat "{" string "}")
548 string))
550 (defun multiline-p (string)
551 "True if STRING is multiline."
552 (if (stringp string)
553 (string-match "\n" string)))
555 (defun first-line (string)
556 "Returns the first line of a multi-line string."
557 (string-match "\n" string)
558 (substring string 0 (match-beginning 0)))
560 (defun sort-in-buffer (limit str)
561 "Moves POINT to the right position to insert STR in a buffer with lines sorted A-Z."
562 (let ((upper limit)
563 middle)
564 (when (> limit 0)
565 (let ((lower 0))
566 (goto-char (point-min))
567 (while (progn
568 (setq middle (/ (+ lower upper 1) 2))
569 (goto-line middle) ; if this turns out to be where we need to be,
570 (beginning-of-line) ; this puts POINT at the right spot.
571 (> (- upper lower) 1)) ; if upper and lower differ by only 1, we have found the
572 ; position to insert the entry in.
573 (save-excursion
574 (let ((beg (point)))
575 (end-of-line)
576 (if (string< (buffer-substring-no-properties beg (point)) str)
577 (setq lower middle)
578 (setq upper middle)))))))))
580 (defun match-all (match-str string)
581 "Highlights all the matches of MATCH-STR in STRING.
582 The return value is a list of two elements: the first is the
583 modified string, the second either t or nil, indicating whether a
584 match was found at all."
585 (do ((counter 0 (match-end 0)))
586 ((not (string-match match-str string counter)) (values string (not (= counter 0))))
587 (add-text-properties (match-beginning 0) (match-end 0) '(face highlight) string)))
589 (defun looking-at-goto-end (str &optional match)
590 "Like LOOKING-AT but moves point to the end of the matching string.
591 MATCH acts just like the argument to MATCH-END, and defaults to 0."
592 (or match (setq match 0))
593 (let ((case-fold-search t))
594 (if (looking-at str)
595 (goto-char (match-end match)))))
597 ;; this needs to be wrapped in an eval-and-compile, to keep Emacs from
598 ;; complaining that ebib-execute-helper isn't defined when it compiles
599 ;; ebib-execute-when.
600 (eval-and-compile
601 (defun ebib-execute-helper (env)
602 "Helper function for EBIB-EXECUTE-WHEN."
603 (cond
604 ((eq env 'entries)
605 '(and ebib-cur-db
606 (edb-cur-entry ebib-cur-db)))
607 ((eq env 'marked-entries)
608 '(and ebib-cur-db
609 (edb-marked-entries ebib-cur-db)))
610 ((eq env 'database)
611 'ebib-cur-db)
612 ((eq env 'real-db)
613 '(and ebib-cur-db
614 (not (edb-virtual ebib-cur-db))))
615 ((eq env 'virtual-db)
616 '(and ebib-cur-db
617 (edb-virtual ebib-cur-db)))
618 ((eq env 'no-database)
619 '(not ebib-cur-db))
620 (t t))))
622 (defmacro ebib-execute-when (&rest forms)
623 "Macro to facilitate writing Ebib functions.
624 This functions essentially like a COND clause: the basic format
625 is (ebib-execute-when FORMS ...), where each FORM is built up
626 as (ENVIRONMENTS BODY). ENVIRONMENTS is a list of symbols (not
627 quoted) that specify under which conditions BODY is to be
628 executed. Valid symbols are:
630 entries: execute when there are entries in the database,
631 marked-entries: execute when there are marked entries in the database,
632 database: execute if there is a database,
633 no-database: execute if there is no database,
634 real-db: execute when there is a database and it is real,
635 virtual-db: execute when there is a database and it is virtual,
636 default: execute if all else fails.
638 Just like with COND, only one form is actually executed, the
639 first one that matches. If ENVIRONMENT contains more than one
640 condition, BODY is executed if they all match (i.e., the
641 conditions are AND'ed.)"
642 (declare (indent defun))
643 `(cond
644 ,@(mapcar #'(lambda (form)
645 (cons (if (= 1 (length (car form)))
646 (ebib-execute-helper (caar form))
647 `(and ,@(mapcar #'(lambda (env)
648 (ebib-execute-helper env))
649 (car form))))
650 (cdr form)))
651 forms)))
653 ;; the numeric prefix argument is 1 if the user gave no prefix argument at
654 ;; all. the raw prefix argument is not always a number. so we need to do
655 ;; our own conversion.
656 (defun ebib-prefix (num)
657 (when (numberp num)
658 num))
660 (defun ebib-called-with-prefix ()
661 "Returns T if the command was called with a prefix key."
662 (if (featurep 'xemacs)
663 (member (character-to-event ebib-prefix-key) (append (this-command-keys) nil))
664 (member (event-convert-list (list ebib-prefix-key))
665 (append (this-command-keys-vector) nil))))
667 (defmacro ebib-export-to-db (num message copy-fn)
668 "Exports data to another database.
669 NUM is the number of the database to which the data is to be copied.
671 MESSAGE is a string displayed in the echo area if the export was
672 succesful. It must contain a %d directive, which is used to
673 display the database number to which the entry was exported.
675 COPY-FN is the function that actually copies the relevant
676 data. It must take as argument the database to which the data is
677 to be copied. COPY-FN must return T if the copying was
678 successful, and NIL otherwise."
679 (let ((goal-db (gensym)))
680 `(let ((,goal-db (nth (1- ,num) ebib-databases)))
681 (cond
682 ((not ,goal-db)
683 (error "Database %d does not exist" ,num))
684 ((edb-virtual ,goal-db)
685 (error "Database %d is virtual" ,num))
686 (t (when (funcall ,copy-fn ,goal-db)
687 (ebib-set-modified t ,goal-db)
688 (message ,message ,num)))))))
690 (defmacro ebib-export-to-file (prompt-string message insert-fn)
691 "Exports data to a file.
692 PROMPT-STRING is the string that is used to ask for the filename
693 to export to. INSERT-FN must insert the data to be exported into
694 the current buffer: it is called within a WITH-TEMP-BUFFER, whose
695 contents is appended to the file the user enters.
697 MESSAGE is shown in the echo area when the export was
698 successful. It must contain a %s directive, which is used to
699 display the actual filename."
700 (let ((filename (gensym)))
701 `(let ((insert-default-directory (not ebib-export-filename)))
702 (if-str (,filename (read-file-name
703 ,prompt-string "~/" nil nil ebib-export-filename))
704 (with-temp-buffer
705 (funcall ,insert-fn)
706 (append-to-file (point-min) (point-max) ,filename)
707 (setq ebib-export-filename ,filename))))))
709 (defun ebib-temp-window ()
710 "Returns a window to be used for temporary use."
711 (if (eq ebib-layout 'full)
712 (get-buffer-window ebib-entry-buffer)
713 ebib-pre-ebib-window))
715 (defun ebib-get-obl-fields (entry-type)
716 "Returns the obligatory fields of ENTRY-TYPE."
717 (nth 1 (assoc entry-type ebib-entry-types)))
719 (defun ebib-get-opt-fields (entry-type)
720 "Returns the optional fields of ENTRY-TYPE."
721 (nth 2 (assoc entry-type ebib-entry-types)))
723 (defun ebib-get-all-fields (entry-type)
724 "Returns all the fields of ENTRY-TYPE."
725 (cons 'type* (append (ebib-get-obl-fields entry-type)
726 (ebib-get-opt-fields entry-type)
727 ebib-additional-fields)))
729 (defmacro ebib-retrieve-entry (entry-key db)
730 "Returns the hash table of the fields stored in DB under ENTRY-KEY."
731 `(gethash ,entry-key (edb-database ,db)))
733 (defun ebib-erase-buffer (buffer)
734 (set-buffer buffer)
735 (with-buffer-writable
736 (erase-buffer)))
738 (defun ebib-make-highlight (begin end buffer)
739 (let (highlight)
740 (if (featurep 'xemacs)
741 (progn
742 (setq highlight (make-extent begin end buffer))
743 (set-extent-face highlight 'highlight))
744 (progn
745 (setq highlight (make-overlay begin end buffer))
746 (overlay-put highlight 'face 'highlight)))
747 highlight))
749 (defun ebib-move-highlight (highlight begin end buffer)
750 (if (featurep 'xemacs)
751 (set-extent-endpoints highlight begin end buffer)
752 (move-overlay highlight begin end buffer)))
754 (defun ebib-highlight-start (highlight)
755 (if (featurep 'xemacs)
756 (extent-start-position highlight)
757 (overlay-start highlight)))
759 (defun ebib-highlight-end (highlight)
760 (if (featurep 'xemacs)
761 (extent-end-position highlight)
762 (overlay-end highlight)))
764 (defun ebib-delete-highlight (highlight)
765 (if (featurep 'xemacs)
766 (detach-extent highlight)
767 (delete-overlay highlight)))
769 (defun ebib-set-index-highlight ()
770 (set-buffer ebib-index-buffer)
771 (beginning-of-line)
772 (let ((beg (point)))
773 (if ebib-index-display-fields
774 (end-of-line)
775 (skip-chars-forward "^ "))
776 (ebib-move-highlight ebib-index-highlight beg (point) ebib-index-buffer)
777 (beginning-of-line)))
779 (defun ebib-set-fields-highlight ()
780 (set-buffer ebib-entry-buffer)
781 (beginning-of-line)
782 (let ((beg (point)))
783 (looking-at-goto-end "[^ \t\n\f]*")
784 (ebib-move-highlight ebib-fields-highlight beg (point) ebib-entry-buffer)
785 (beginning-of-line)))
787 (defun ebib-set-strings-highlight ()
788 (set-buffer ebib-strings-buffer)
789 (beginning-of-line)
790 (let ((beg (point)))
791 (looking-at-goto-end "[^ \t\n\f]*")
792 (ebib-move-highlight ebib-strings-highlight beg (point) ebib-strings-buffer)
793 (beginning-of-line)))
795 (defun ebib-display-entry (entry-key)
796 "Displays ENTRY-KEY in the index buffer at POINT."
797 (set-buffer ebib-index-buffer)
798 (insert (format "%-30s %s\n"
799 entry-key
800 (if ebib-index-display-fields
801 (let ((cur-entry-hash (ebib-retrieve-entry entry-key ebib-cur-db)))
802 (mapconcat #'(lambda (field)
804 (to-raw (gethash field cur-entry-hash))
805 ""))
806 ebib-index-display-fields
807 "; "))
808 ""))))
810 (defun ebib-redisplay-current-field ()
811 "Redisplays the contents of the current field in the entry buffer."
812 (set-buffer ebib-entry-buffer)
813 (if (eq ebib-current-field 'crossref)
814 (progn
815 (ebib-fill-entry-buffer)
816 (setq ebib-current-field 'crossref)
817 (re-search-forward "^crossref")
818 (ebib-set-fields-highlight))
819 (with-buffer-writable
820 (goto-char (ebib-highlight-start ebib-fields-highlight))
821 (let ((beg (point)))
822 (end-of-line)
823 (delete-region beg (point)))
824 (insert (format "%-17s " (symbol-name ebib-current-field))
825 (ebib-get-field-highlighted ebib-current-field ebib-cur-entry-hash))
826 (ebib-set-fields-highlight))))
828 (defun ebib-redisplay-current-string ()
829 "Redisplays the current string definition in the strings buffer."
830 (set-buffer ebib-strings-buffer)
831 (with-buffer-writable
832 (let ((str (to-raw (gethash ebib-current-string (edb-strings ebib-cur-db)))))
833 (goto-char (ebib-highlight-start ebib-strings-highlight))
834 (let ((beg (point)))
835 (end-of-line)
836 (delete-region beg (point)))
837 (insert (format "%-18s %s" ebib-current-string
838 (if (multiline-p str)
839 (concat "+" (first-line str))
840 (concat " " str))))
841 (ebib-set-strings-highlight))))
843 (defun ebib-move-to-field (field direction)
844 "Moves the fields overlay to the line containing FIELD.
845 If DIRECTION is positive, searches forward, if DIRECTION is
846 negative, searches backward. If DIRECTION is 1 or -1, searches
847 from POINT, if DIRECTION is 2 or -2, searches from beginning or
848 end of buffer. If FIELD is not found in the entry buffer, the
849 overlay is not moved. FIELD must be a symbol."
851 ;;Note: this function does NOT change the value of EBIB-CURRENT-FIELD!
853 (set-buffer ebib-entry-buffer)
854 (if (eq field 'type*)
855 (goto-char (point-min))
856 (multiple-value-bind (fn start limit) (if (>= direction 0)
857 (values 're-search-forward (point-min) (point-max))
858 (values 're-search-backward (point-max) (point-min)))
859 ;; make sure we can get back to our original position, if the field
860 ;; cannot be found in the buffer:
861 (let ((current-pos (point)))
862 (when (evenp direction)
863 (goto-char start))
864 (unless (funcall fn (concat "^" (symbol-name field)) limit t)
865 (goto-char current-pos)))))
866 (ebib-set-fields-highlight))
868 (defun ebib-create-collection (hashtable)
869 "Creates a list from the keys in HASHTABLE that can be used as COLLECTION in COMPLETING-READ.
870 The keys of HASHTABLE must be either symbols or strings."
871 (let ((result nil))
872 (maphash #'(lambda (x y)
873 (setq result (cons (cons (symbol-or-string x)
875 result)))
876 hashtable)
877 result))
879 (defun ebib-get-field-highlighted (field current-entry &optional match-str)
880 ;; note: we need to work on a copy of the string, otherwise the highlights
881 ;; are made to the string as stored in the database. hence copy-sequence.
882 (let ((case-fold-search t)
883 (string (copy-sequence (gethash field current-entry)))
884 (raw " ")
885 (multiline " ")
886 (matched nil))
887 ;; we have to do a couple of things now:
888 ;; - remove {} or "" around the string, if they're there
889 ;; - search for match-str
890 ;; - properly adjust the string if it's multiline
891 ;; but all this is not necessary if there was no string
892 (if (null string)
893 (let* ((xref (to-raw (gethash 'crossref current-entry)))
894 (xref-entry (ebib-retrieve-entry xref ebib-cur-db)))
895 (when xref-entry
896 (setq string (gethash field xref-entry))
897 (if string
898 (setq string (propertize (to-raw string) 'face 'ebib-crossref-face 'fontified t))
899 (setq string ""))))
900 (if (raw-p string)
901 (setq raw "*")
902 (setq string (to-raw string))) ; we have to make the string look nice
903 (when match-str
904 (multiple-value-setq (string matched) (match-all match-str string)))
905 (when (multiline-p string)
906 ;; IIUC PROPERTIZE shouldn't be necessary here, as the variable
907 ;; multiline is local and therefore the object it refers to should
908 ;; be GC'ed when the function returns. but for some reason, the
909 ;; plus sign is persistent, and if it's been highlighted as the
910 ;; result of a search, it stays that way.
911 (setq multiline (propertize "+" 'face nil))
912 (setq string (first-line string))))
913 (when (and matched
914 (string= multiline "+"))
915 (add-text-properties 0 1 '(face highlight) multiline))
916 (concat raw multiline string)))
918 (defun ebib-format-fields (entry fn &optional match-str)
919 (let* ((entry-type (gethash 'type* entry))
920 (obl-fields (ebib-get-obl-fields entry-type))
921 (opt-fields (ebib-get-opt-fields entry-type)))
922 (funcall fn (format "%-19s %s\n" "type" entry-type))
923 (mapc #'(lambda (fields)
924 (funcall fn "\n")
925 (mapcar #'(lambda (field)
926 (unless (and (get field 'ebib-hidden)
927 ebib-hide-hidden-fields)
928 (funcall fn (format "%-17s " field))
929 (funcall fn (or
930 (ebib-get-field-highlighted field entry match-str)
931 ""))
932 (funcall fn "\n")))
933 fields))
934 (list obl-fields opt-fields ebib-additional-fields))))
936 (defun ebib-fill-entry-buffer (&optional match-str)
937 "Fills the entry buffer with the fields of the current entry.
938 MATCH-STRING is a regexp that will be highlighted when it occurs in the
939 field contents."
940 (set-buffer ebib-entry-buffer)
941 (with-buffer-writable
942 (erase-buffer)
943 (when (and ebib-cur-db ; do we have a database?
944 (edb-keys-list ebib-cur-db) ; does it contain entries?
945 (gethash (car (edb-cur-entry ebib-cur-db))
946 (edb-database ebib-cur-db))) ; does the current entry exist?
947 (ebib-format-fields (gethash (car (edb-cur-entry ebib-cur-db))
948 (edb-database ebib-cur-db)) 'insert match-str)
949 (setq ebib-current-field 'type*)
950 (goto-char (point-min))
951 (ebib-set-fields-highlight))))
952 ;; (skip-chars-forward "^ "))))
954 (defun ebib-set-modified (mod &optional db)
955 "Sets the modified flag of the database DB to MOD.
956 If DB is nil, it defaults to the current database, and the
957 modified flag of the index buffer is also (re)set. MOD must be
958 either T or NIL."
959 (unless db
960 (setq db ebib-cur-db))
961 (setf (edb-modified db) mod)
962 (when (eq db ebib-cur-db)
963 (save-excursion
964 (set-buffer ebib-index-buffer)
965 (set-buffer-modified-p mod))))
967 (defun ebib-modified-p ()
968 "Checks if any of the databases in Ebib were modified.
969 Returns the first modified database, or NIL if none was modified."
970 (let ((db (car ebib-databases)))
971 (while (and db
972 (not (edb-modified db)))
973 (setq db (next-elem db ebib-databases)))
974 db))
976 (defun ebib-create-new-database (&optional db)
977 "Creates a new database instance and returns it.
978 If DB is set to a database, the new database is a copy of DB."
979 (let ((new-db
980 (if (edb-p db)
981 (copy-edb db)
982 (make-edb))))
983 (setq ebib-databases (append ebib-databases (list new-db)))
984 new-db))
986 (defun ebib-match-paren-forward (limit)
987 "Moves forward to the closing parenthesis matching the opening parenthesis at POINT.
988 This function handles parentheses () and braces {}. Does not
989 search/move beyond LIMIT. Returns T if a matching parenthesis was
990 found, NIL otherwise. If point was not at an opening parenthesis
991 at all, NIL is returned and point is not moved. If point was at
992 an opening parenthesis but no matching closing parenthesis was
993 found, an error is logged and point is moved one character
994 forward to allow parsing to continue."
995 (cond
996 ((eq (char-after) ?\{)
997 (ebib-match-brace-forward limit))
998 ((eq (char-after) ?\()
999 ;; we wrap this in a condition-case because we need to log the error
1000 ;; message outside of the save-restriction, otherwise we get the wrong
1001 ;; line number.
1002 (condition-case nil
1003 (save-restriction
1004 (narrow-to-region (point) limit)
1005 ;; this is really a hack. we want to allow unbalanced parentheses in
1006 ;; field values (bibtex does), so we cannot use forward-list
1007 ;; here. for the same reason, looking for the matching paren by hand
1008 ;; is pretty complicated. however, balanced parentheses can only be
1009 ;; used to enclose entire entries (or @STRINGs or @PREAMBLEs) so we
1010 ;; can be pretty sure we'll find it right before the next @ at the
1011 ;; start of a line, or right before the end of the file.
1012 (re-search-forward "^@" nil 0)
1013 (skip-chars-backward "@ \n\t\f")
1014 (forward-char -1)
1015 (if (eq (char-after) ?\))
1017 (goto-char (1+ (point-min)))
1018 (error "")))
1019 (error (ebib-log 'error "Error in line %d: Matching closing parenthesis not found!" (line-number-at-pos))
1020 nil)))
1021 (t nil)))
1023 (defun ebib-match-delim-forward (limit)
1024 "Moves forward to the closing delimiter matching the opening delimiter at POINT.
1025 This function handles braces {} and double quotes \"\". Does not
1026 search/move beyond LIMIT. Returns T if a matching delimiter was
1027 found, NIL otherwise. If point was not at an opening delimiter at
1028 all, NIL is returned and point is not moved. If point was at an
1029 opening delimiter but no matching closing delimiter was found, an
1030 error is logged and point is moved one character forward to allow
1031 parsing to continue."
1032 (cond
1033 ((eq (char-after) ?\")
1034 (ebib-match-quote-forward limit))
1035 ((eq (char-after) ?\{)
1036 (ebib-match-brace-forward limit))
1037 (t nil)))
1039 (defun ebib-match-brace-forward (limit)
1040 "Moves forward to the closing brace matching the opening brace at POINT.
1041 Does not search/move beyond LIMIT. Returns T if a matching brace
1042 was found, NIL otherwise. If point was not at an opening brace at
1043 all, NIL is returned and point is not moved. If point was at an
1044 opening brace but no matching closing brace was found, an error
1045 is logged and point is moved one character forward to allow
1046 parsing to continue."
1047 (when (eq (char-after) ?\{) ; make sure we're really on a brace, otherwise return nil
1048 (condition-case nil
1049 (save-restriction
1050 (narrow-to-region (point) limit)
1051 (progn
1052 (forward-list)
1053 ;; all of ebib expects that point moves to the closing
1054 ;; parenthesis, not right after it, so we adjust.
1055 (forward-char -1)
1056 t)) ; return t because a matching brace was found
1057 (error (progn
1058 (ebib-log 'error "Error in line %d: Matching closing brace not found!" (line-number-at-pos))
1059 (forward-char 1)
1060 nil)))))
1062 (defun ebib-match-quote-forward (limit)
1063 "Moves to the closing double quote matching the quote at POINT.
1064 Does not search/move beyond LIMIT. Returns T if a matching quote
1065 was found, NIL otherwise. If point was not at a double quote at
1066 all, NIL is returned and point is not moved. If point was at a
1067 quote but no matching closing quote was found, an error is logged
1068 and point is moved one character forward to allow parsing to
1069 continue."
1070 (when (eq (char-after (point)) ?\") ; make sure we're on a double quote.
1071 (condition-case nil
1072 (save-restriction
1073 (narrow-to-region (point) limit)
1074 (while (progn
1075 (forward-char) ; move forward because we're on a double quote
1076 (skip-chars-forward "^\"") ; search the next double quote
1077 (eq (char-before) ?\\))) ; if it's preceded by a backslash, keep on searching
1078 (or (eq (char-after) ?\")
1079 (progn
1080 (goto-char (1+ (point-min)))
1081 (error ""))))
1082 (error (ebib-log 'error "Error in line %d: Matching closing quote not found!" (line-number-at-pos))
1083 nil))))
1085 (defun ebib-insert-entry (entry-key fields db &optional sort timestamp)
1086 "Stores the entry defined by ENTRY-KEY and FIELDS into DB.
1087 Optional argument SORT indicates whether the KEYS-LIST must be
1088 sorted after insertion. Default is NIL. Optional argument
1089 TIMESTAMP indicates whether a timestamp is to be added to the
1090 entry. Note that for a timestamp to be added, EBIB-USE-TIMESTAMP
1091 must also be set to T."
1092 (when (and timestamp ebib-use-timestamp)
1093 (puthash 'timestamp (from-raw (format-time-string ebib-timestamp-format)) fields))
1094 (puthash entry-key fields (edb-database db))
1095 (ebib-set-modified t db)
1096 (setf (edb-n-entries db) (1+ (edb-n-entries db)))
1097 (setf (edb-keys-list db)
1098 (if sort
1099 (sort (cons entry-key (edb-keys-list db)) 'string<)
1100 (cons entry-key (edb-keys-list db)))))
1102 (defun ebib-insert-string (abbr string db &optional sort)
1103 "Stores the @STRING definition defined by ABBR and STRING into DB.
1104 Optional argument SORT indicates whether the STRINGS-LIST must be sorted
1105 after insertion. When loading or merging a file, for example, it is more
1106 economic to sort KEYS-LIST manually after all entries in the file have been
1107 added."
1108 (puthash abbr (from-raw string) (edb-strings db))
1109 (ebib-set-modified t db)
1110 (setf (edb-strings-list db)
1111 (if sort
1112 (sort (cons abbr (edb-strings-list db)) 'string<)
1113 (cons abbr (edb-strings-list db)))))
1115 (defmacro ebib-cur-entry-key ()
1116 "Returns the key of the current entry in EBIB-CUR-DB."
1117 `(car (edb-cur-entry ebib-cur-db)))
1119 (defun ebib-search-key-in-buffer (entry-key)
1120 "Searches ENTRY-KEY in the index buffer.
1122 Moves point to the first character of the key and returns point."
1123 (goto-char (point-min))
1124 (search-forward entry-key)
1125 (beginning-of-line)
1126 (point))
1128 ;; when we sort entries, we either use string< on the entry keys, or
1129 ;; ebib-entry<, if the user has defined a sort order.
1131 (defun ebib-entry< (x y)
1132 "Returns T if entry X is smaller than entry Y.
1133 The entries are compared based on the fields listed in EBIB-SORT-ORDER. X
1134 and Y should be keys of entries in the current database."
1135 (let* ((sort-list ebib-sort-order)
1136 (sortstring-x (to-raw (ebib-get-sortstring x (car sort-list))))
1137 (sortstring-y (to-raw (ebib-get-sortstring y (car sort-list)))))
1138 (while (and sort-list
1139 (string= sortstring-x sortstring-y))
1140 (setq sort-list (cdr sort-list))
1141 (setq sortstring-x (to-raw (ebib-get-sortstring x (car sort-list))))
1142 (setq sortstring-y (to-raw (ebib-get-sortstring y (car sort-list)))))
1143 (if (and sortstring-x sortstring-y)
1144 (string< sortstring-x sortstring-y)
1145 (string< x y))))
1147 (defun ebib-get-sortstring (entry-key sortkey-list)
1148 "Returns the field value on which the entry ENTRY-KEY is to be sorted.
1149 ENTRY-KEY must be the key of an entry in the current database. SORTKEY-LIST
1150 is a list of fields that are considered in order for the sort value."
1151 (let ((sort-string nil))
1152 (while (and sortkey-list
1153 (null (setq sort-string (gethash (car sortkey-list)
1154 (ebib-retrieve-entry entry-key ebib-cur-db)))))
1155 (setq sortkey-list (cdr sortkey-list)))
1156 sort-string))
1158 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1159 ;; main program execution ;;
1160 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1162 ;;;###autoload
1163 (defun ebib ()
1164 "Ebib, a BibTeX database manager."
1165 (interactive)
1166 (if (or (equal (window-buffer) ebib-index-buffer)
1167 (equal (window-buffer) ebib-entry-buffer))
1168 (error "Ebib already active")
1169 ;; we save the buffer from which ebib is called
1170 (setq ebib-push-buffer (current-buffer))
1171 ;; initialize ebib if required
1172 (unless ebib-initialized
1173 (ebib-init)
1174 (if ebib-preload-bib-files
1175 (mapc #'(lambda (file)
1176 (ebib-load-bibtex-file file))
1177 ebib-preload-bib-files)))
1178 ;; if ebib is visible, we just switch to the index buffer
1179 (let ((index-window (get-buffer-window ebib-index-buffer)))
1180 (if index-window
1181 (select-window index-window nil)
1182 (ebib-setup-windows)))))
1184 (defun ebib-setup-windows ()
1185 "Creates the window configuration we want for Ebib in the
1186 current window."
1187 ;; we save the current window configuration.
1188 (setq ebib-saved-window-config (current-window-configuration))
1189 (if (eq ebib-layout 'full)
1190 (delete-other-windows)
1191 (setq ebib-pre-ebib-window (selected-window))
1192 (let ((ebib-window (split-window (selected-window) (- (window-width) ebib-layout) t)))
1193 (select-window ebib-window nil)))
1194 (let* ((index-window (selected-window))
1195 (entry-window (split-window index-window ebib-index-window-size)))
1196 (switch-to-buffer ebib-index-buffer)
1197 (set-window-buffer entry-window ebib-entry-buffer)
1198 (unless (eq ebib-layout 'full)
1199 (set-window-dedicated-p index-window t)
1200 (set-window-dedicated-p entry-window t))))
1202 (defun ebib-init ()
1203 "Initialises Ebib.
1204 This function sets all variables to their initial values, creates the
1205 buffers and reads the rc file."
1206 (setq ebib-cur-entry-hash nil
1207 ebib-current-field nil
1208 ebib-minibuf-hist nil
1209 ebib-saved-window-config nil)
1210 (put 'timestamp 'ebib-hidden t)
1211 (load "~/.ebibrc" t)
1212 (ebib-create-buffers)
1213 (setq ebib-index-highlight (ebib-make-highlight 1 1 ebib-index-buffer))
1214 (setq ebib-fields-highlight (ebib-make-highlight 1 1 ebib-entry-buffer))
1215 (setq ebib-strings-highlight (ebib-make-highlight 1 1 ebib-strings-buffer))
1216 (setq ebib-initialized t))
1218 (defun ebib-create-buffers ()
1219 "Creates the buffers for Ebib."
1220 ;; first we create a buffer for multiline editing. this one does *not*
1221 ;; have a name beginning with a space, because undo-info is normally
1222 ;; present in an edit buffer.
1223 (setq ebib-multiline-buffer (get-buffer-create "*Ebib-edit*"))
1224 (set-buffer ebib-multiline-buffer)
1225 (ebib-multiline-edit-mode)
1226 ;; then we create a buffer to hold the fields of the current entry.
1227 (setq ebib-entry-buffer (get-buffer-create " *Ebib-entry*"))
1228 (set-buffer ebib-entry-buffer)
1229 (ebib-entry-mode)
1230 ;; then we create a buffer to hold the @STRING definitions
1231 (setq ebib-strings-buffer (get-buffer-create " *Ebib-strings*"))
1232 (set-buffer ebib-strings-buffer)
1233 (ebib-strings-mode)
1234 ;; the log buffer
1235 (setq ebib-log-buffer (get-buffer-create " *Ebib-log*"))
1236 (set-buffer ebib-log-buffer)
1237 (erase-buffer)
1238 (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")
1239 (ebib-log-mode)
1240 ;; and lastly we create a buffer for the entry keys.
1241 (setq ebib-index-buffer (get-buffer-create " none"))
1242 (set-buffer ebib-index-buffer)
1243 (ebib-index-mode))
1245 (defun ebib-quit ()
1246 "Quits Ebib.
1247 The Ebib buffers are killed, all variables except the keymaps are set to nil."
1248 (interactive)
1249 (when (if (ebib-modified-p)
1250 (yes-or-no-p "There are modified databases. Quit anyway? ")
1251 (y-or-n-p "Quit Ebib? "))
1252 (mapc #'(lambda (buffer)
1253 (kill-buffer buffer))
1254 (list ebib-entry-buffer
1255 ebib-index-buffer
1256 ebib-strings-buffer
1257 ebib-multiline-buffer
1258 ebib-log-buffer))
1259 (setq ebib-databases nil
1260 ebib-index-buffer nil
1261 ebib-entry-buffer nil
1262 ebib-initialized nil
1263 ebib-index-highlight nil
1264 ebib-fields-highlight nil
1265 ebib-strings-highlight nil
1266 ebib-export-filename nil
1267 ebib-pre-ebib-window nil)
1268 (set-window-configuration ebib-saved-window-config)
1269 (message "")))
1271 (defun ebib-kill-emacs-query-function ()
1272 "Ask if the user wants to save the database loaded in Ebib when Emacs is
1273 killed and the database has been modified."
1274 (if (not (ebib-modified-p))
1276 (if (y-or-n-p "Save all unsaved Ebib databases? ")
1277 (progn
1278 (ebib-save-all-databases)
1280 (yes-or-no-p "Ebib database was modified. Kill anyway? "))))
1282 (add-hook 'kill-emacs-query-functions 'ebib-kill-emacs-query-function)
1284 ;;;;;;;;;;;;;;;;
1285 ;; index-mode ;;
1286 ;;;;;;;;;;;;;;;;
1288 (eval-and-compile
1289 (define-prefix-command 'ebib-prefix-map)
1290 (suppress-keymap ebib-prefix-map)
1291 (defvar ebib-prefixed-functions '(ebib-delete-entry
1292 ebib-latex-entries
1293 ebib-mark-entry
1294 ebib-print-entries
1295 ebib-export-entry
1296 ebib-push-entry-key)))
1298 ;; macro to redefine key bindings.
1300 (defmacro ebib-key (buffer key &optional command)
1301 (cond
1302 ((eq buffer 'index)
1303 (let ((one `(define-key ebib-index-mode-map ,key (quote ,command)))
1304 (two (when (or (null command)
1305 (member command ebib-prefixed-functions))
1306 `(define-key ebib-prefix-map ,key (quote ,command)))))
1307 (if two
1308 `(progn ,one ,two)
1309 one)))
1310 ((eq buffer 'entry)
1311 `(define-key ebib-entry-mode-map ,key (quote ,command)))
1312 ((eq buffer 'strings)
1313 `(define-key ebib-strings-mode-map ,key (quote ,command)))
1314 ((eq buffer 'mark-prefix)
1315 `(progn
1316 (define-key ebib-index-mode-map (format "%c" ebib-prefix-key) nil)
1317 (define-key ebib-index-mode-map ,key 'ebib-prefix-map)
1318 (setq ebib-prefix-key (string-to-char ,key))))))
1320 (defvar ebib-index-mode-map
1321 (let ((map (make-keymap)))
1322 (suppress-keymap map)
1323 map)
1324 "Keymap for the ebib index buffer.")
1326 ;; we define the keys with ebib-key rather than with define-key, because
1327 ;; that automatically sets up ebib-prefix-map as well.
1328 (ebib-key index [up] ebib-prev-entry)
1329 (ebib-key index [down] ebib-next-entry)
1330 (ebib-key index [right] ebib-next-database)
1331 (ebib-key index [left] ebib-prev-database)
1332 (ebib-key index [prior] ebib-index-scroll-down)
1333 (ebib-key index [next] ebib-index-scroll-up)
1334 (ebib-key index [home] ebib-goto-first-entry)
1335 (ebib-key index [end] ebib-goto-last-entry)
1336 (ebib-key index [return] ebib-select-entry)
1337 (ebib-key index " " ebib-index-scroll-up)
1338 (ebib-key index "/" ebib-search)
1339 (ebib-key index "&" ebib-virtual-db-and)
1340 (ebib-key index "|" ebib-virtual-db-or)
1341 (ebib-key index "~" ebib-virtual-db-not)
1342 (ebib-key index ";" ebib-prefix-map)
1343 (ebib-key index "a" ebib-add-entry)
1344 (ebib-key index "b" ebib-index-scroll-down)
1345 (ebib-key index "c" ebib-close-database)
1346 (ebib-key index "C" ebib-customize)
1347 (ebib-key index "d" ebib-delete-entry)
1348 (ebib-key index "e" ebib-edit-entry)
1349 (ebib-key index "E" ebib-edit-keyname)
1350 (ebib-key index "f" ebib-view-file)
1351 (ebib-key index "F" ebib-follow-crossref)
1352 (ebib-key index "g" ebib-goto-first-entry)
1353 (ebib-key index "G" ebib-goto-last-entry)
1354 (ebib-key index "H" ebib-toggle-hidden)
1355 (ebib-key index "j" ebib-next-entry)
1356 (ebib-key index "J" ebib-switch-to-database)
1357 (ebib-key index "k" ebib-prev-entry)
1358 (ebib-key index "l" ebib-show-log)
1359 (ebib-key index "L" ebib-latex-entries)
1360 (ebib-key index "m" ebib-mark-entry)
1361 (ebib-key index "M" ebib-merge-bibtex-file)
1362 (ebib-key index "n" ebib-search-next)
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-entry-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-edit-strings ()
2289 "Edits the @STRING definitions in the database."
2290 (interactive)
2291 (ebib-execute-when
2292 ((real-db)
2293 (ebib-fill-strings-buffer)
2294 (select-window (get-buffer-window ebib-entry-buffer) nil)
2295 (set-window-dedicated-p (selected-window) nil)
2296 (switch-to-buffer ebib-strings-buffer)
2297 (unless (eq ebib-layout 'full)
2298 (set-window-dedicated-p (selected-window) t))
2299 (goto-char (point-min)))
2300 ((default)
2301 (beep))))
2303 (defun ebib-edit-preamble ()
2304 "Edits the @PREAMBLE definition in the database."
2305 (interactive)
2306 (ebib-execute-when
2307 ((real-db)
2308 (select-window (ebib-temp-window) nil)
2309 (ebib-multiline-edit 'preamble (edb-preamble ebib-cur-db)))
2310 ((default)
2311 (beep))))
2313 (defun ebib-export-preamble (prefix)
2314 "Exports the @PREAMBLE definition.
2315 If a prefix argument is given, it is taken as the database to
2316 export the preamble to. If the goal database already has a
2317 preamble, the new preamble will be appended to it. If no prefix
2318 argument is given, the user is asked to enter a filename to which
2319 the preamble is appended."
2320 (interactive "P")
2321 (ebib-execute-when
2322 ((real-db)
2323 (if (null (edb-preamble ebib-cur-db))
2324 (error "No @PREAMBLE defined")
2325 (let ((num (ebib-prefix prefix)))
2326 (if num
2327 (ebib-export-to-db num "@PREAMBLE copied to database %d"
2328 #'(lambda (db)
2329 (let ((text (edb-preamble ebib-cur-db)))
2330 (if (edb-preamble db)
2331 (setf (edb-preamble db) (concat (edb-preamble db) "\n# " text))
2332 (setf (edb-preamble db) text)))))
2333 (ebib-export-to-file "Export @PREAMBLE to file: "
2334 "@PREAMBLE exported to %s"
2335 #'(lambda ()
2336 (insert (format "\n@preamble{%s}\n\n" (edb-preamble ebib-cur-db)))))))))
2337 ((default)
2338 (beep))))
2340 (defun ebib-print-entries ()
2341 "Creates a LaTeX file listing the entries.
2342 Either prints the entire database, or the marked entries."
2343 (interactive)
2344 (ebib-execute-when
2345 ((entries)
2346 (let ((entries (if (ebib-called-with-prefix)
2347 (edb-marked-entries ebib-cur-db)
2348 (edb-keys-list ebib-cur-db))))
2349 (if-str (tempfile (if (not (string= "" ebib-print-tempfile))
2350 ebib-print-tempfile
2351 (read-file-name "Use temp file: " "~/" nil nil)))
2352 (progn
2353 (with-temp-buffer
2354 (insert "\\documentclass{article}\n\n")
2355 (when ebib-print-preamble
2356 (mapc #'(lambda (string)
2357 (insert (format "%s\n" string)))
2358 ebib-print-preamble))
2359 (insert "\n\\begin{document}\n\n")
2360 (mapc #'(lambda (entry-key)
2361 (insert "\\begin{tabular}{p{0.2\\textwidth}p{0.8\\textwidth}}\n")
2362 (let ((entry (ebib-retrieve-entry entry-key ebib-cur-db)))
2363 (insert (format "\\multicolumn{2}{l}{\\texttt{%s (%s)}}\\\\\n"
2364 entry-key (symbol-name (gethash 'type* entry))))
2365 (insert "\\hline\n")
2366 (mapc #'(lambda (field)
2367 (if-str (value (gethash field entry))
2368 (when (or (not (multiline-p value))
2369 ebib-print-multiline)
2370 (insert (format "%s: & %s\\\\\n"
2371 field (to-raw value))))))
2372 (cdr (ebib-get-all-fields (gethash 'type* entry)))))
2373 (insert "\\end{tabular}\n\n")
2374 (insert "\\bigskip\n\n"))
2375 entries)
2376 (insert "\\end{document}\n")
2377 (write-region (point-min) (point-max) tempfile))
2378 (ebib-lower)
2379 (find-file tempfile)))))
2380 ((default)
2381 (beep))))
2383 (defun ebib-latex-entries ()
2384 "Creates a LaTeX file that \\nocites entries from the database.
2385 Operates either on all entries or on the marked entries."
2386 (interactive)
2387 (ebib-execute-when
2388 ((real-db entries)
2389 (if-str (tempfile (if (not (string= "" ebib-print-tempfile))
2390 ebib-print-tempfile
2391 (read-file-name "Use temp file: " "~/" nil nil)))
2392 (progn
2393 (with-temp-buffer
2394 (insert "\\documentclass{article}\n\n")
2395 (when ebib-print-preamble
2396 (mapc #'(lambda (string)
2397 (insert (format "%s\n" string)))
2398 ebib-latex-preamble))
2399 (insert "\n\\begin{document}\n\n")
2400 (if (ebib-called-with-prefix)
2401 (mapc #'(lambda (entry)
2402 (insert (format "\\nocite{%s}\n" entry)))
2403 (edb-marked-entries ebib-cur-db))
2404 (insert "\\nocite{*}\n"))
2405 (insert (format "\n\\bibliography{%s}\n\n" (expand-file-name (edb-filename ebib-cur-db))))
2406 (insert "\\end{document}\n")
2407 (write-region (point-min) (point-max) tempfile))
2408 (ebib-lower)
2409 (find-file tempfile))))
2410 ((default)
2411 (beep))))
2413 (defun ebib-switch-to-database (num)
2414 (interactive "NSwitch to database number: ")
2415 (let ((new-db (nth (1- num) ebib-databases)))
2416 (if new-db
2417 (progn
2418 (setq ebib-cur-db new-db)
2419 (ebib-fill-entry-buffer)
2420 (ebib-fill-index-buffer))
2421 (error "Database %d does not exist" num))))
2423 (defun ebib-next-database ()
2424 (interactive)
2425 (ebib-execute-when
2426 ((database)
2427 (let ((new-db (next-elem ebib-cur-db ebib-databases)))
2428 (unless new-db
2429 (setq new-db (car ebib-databases)))
2430 (setq ebib-cur-db new-db)
2431 (ebib-fill-entry-buffer)
2432 (ebib-fill-index-buffer)))))
2434 (defun ebib-prev-database ()
2435 (interactive)
2436 (ebib-execute-when
2437 ((database)
2438 (let ((new-db (prev-elem ebib-cur-db ebib-databases)))
2439 (unless new-db
2440 (setq new-db (last1 ebib-databases)))
2441 (setq ebib-cur-db new-db)
2442 (ebib-fill-entry-buffer)
2443 (ebib-fill-index-buffer)))))
2445 (defun ebib-browse-url (num)
2446 "Asks a browser to load the URL in the standard URL field.
2447 The standard URL field may contain more than one URL, if they're
2448 whitespace-separated. In that case, a numeric prefix argument
2449 specifies which URL to choose.
2451 By \"standard URL field\" is meant the field defined in the
2452 customisation variable EBIB-STANDARD-URL-FIELD. Its default value
2453 is `url'."
2454 (interactive "p")
2455 (ebib-execute-when
2456 ((entries)
2457 (let ((url (to-raw (gethash ebib-standard-url-field
2458 (ebib-retrieve-entry (ebib-cur-entry-key) ebib-cur-db)))))
2459 (when (not (and url
2460 (ebib-call-browser url num)))
2461 (error "No url found in field `%s'" ebib-standard-url-field))))
2462 ((default)
2463 (beep))))
2465 (defun ebib-call-browser (urls n)
2466 "Passes the Nth url in URLS to a browser.
2467 URLs must be a string of whitespace-separated urls."
2468 (let ((url (nth (1- n)
2469 (let ((start 0)
2470 (result nil))
2471 (while (string-match ebib-url-regexp urls start)
2472 (add-to-list 'result (match-string 0 urls) t)
2473 (setq start (match-end 0)))
2474 result))))
2475 (cond
2476 ((string-match "\\\\url{\\(.*?\\)}" url)
2477 (setq url (match-string 1 url)))
2478 ((string-match ebib-url-regexp url)
2479 (setq url (match-string 0 url)))
2480 (t (setq url nil)))
2481 (when url
2482 (if (not (string= ebib-browser-command ""))
2483 (start-process "Ebib-browser" nil ebib-browser-command url)
2484 (browse-url url)))))
2486 (defun ebib-view-file (num)
2487 "Views a file in the standard file field.
2488 The standard file field may contain more than one filename, if
2489 they're whitespace-separated. In that case, a numeric prefix
2490 argument specifies which file to choose.
2492 By \"standard file field\" is meant the field defined in the
2493 customisation variable EBIB-STANDARD-FILE-FIELD. Its default
2494 value is `file'."
2495 (interactive "p")
2496 (ebib-execute-when
2497 ((entries)
2498 (let ((filename (to-raw (gethash ebib-standard-file-field
2499 (ebib-retrieve-entry (ebib-cur-entry-key) ebib-cur-db)))))
2500 (when (not (and filename
2501 (ebib-call-file-viewer filename num)))
2502 (error "No valid filename found in field `%s'" ebib-standard-file-field))))
2503 ((default)
2504 (beep))))
2506 (defun ebib-call-file-viewer (files n)
2507 "Passes the Nth file in FILES to an external viewer.
2508 FILES must be a string of whitespace-separated filenames."
2509 (let* ((file (nth (1- n)
2510 (let ((start 0)
2511 (result nil))
2512 (while (string-match ebib-file-regexp files start)
2513 (add-to-list 'result (match-string 0 files) t)
2514 (setq start (match-end 0)))
2515 result)))
2516 (ext (file-name-extension file)))
2517 (let ((file-full-path (locate-file file ebib-file-search-dirs)))
2518 (when file-full-path
2519 (if-str (viewer (cdr (assoc ext ebib-file-associations)))
2520 (start-process (concat "ebib " ext " viewer process") nil viewer file-full-path)
2521 (ebib-lower)
2522 (find-file file-full-path))))))
2524 (defun ebib-virtual-db-and (not)
2525 "Filters entries into a virtual database.
2526 If the current database is a virtual database already, perform a
2527 logical AND on the entries."
2528 (interactive "p")
2529 (ebib-execute-when
2530 ((entries)
2531 (ebib-filter-to-virtual-db 'and not))
2532 ((default)
2533 (beep))))
2535 (defun ebib-virtual-db-or (not)
2536 "Filters entries into a virtual database.
2537 If the current database is a virtual database already, perform a
2538 logical OR with the entries in the original database."
2539 (interactive "p")
2540 (ebib-execute-when
2541 ((entries)
2542 (ebib-filter-to-virtual-db 'or not))
2543 ((default)
2544 (beep))))
2546 (defun ebib-virtual-db-not ()
2547 "Negates the current virtual database."
2548 (interactive)
2549 (ebib-execute-when
2550 ((virtual-db)
2551 (setf (edb-virtual ebib-cur-db)
2552 (if (eq (car (edb-virtual ebib-cur-db)) 'not)
2553 (cadr (edb-virtual ebib-cur-db))
2554 `(not ,(edb-virtual ebib-cur-db))))
2555 (ebib-run-filter (edb-virtual ebib-cur-db) ebib-cur-db)
2556 (ebib-fill-entry-buffer)
2557 (ebib-fill-index-buffer))
2558 ((default)
2559 (beep))))
2561 (defun ebib-filter-to-virtual-db (bool not)
2562 "Filters the current database to a virtual database.
2563 BOOL is the operator to be used, either `and' or `or'. If NOT<0,
2564 a logical `not' is applied to the selection."
2565 (let ((field (completing-read (format "Filter: %s(contains <field> <regexp>)%s. Enter field: "
2566 (if (< not 0) "(not " "")
2567 (if (< not 0) ")" ""))
2568 (cons '("any" 0)
2569 (mapcar #'(lambda (x)
2570 (cons (symbol-name x) 0))
2571 (append ebib-unique-field-list ebib-additional-fields)))
2572 nil t)))
2573 (setq field (intern-soft field))
2574 (let ((regexp (read-string (format "Filter: %s(contains %s <regexp>)%s. Enter regexp: "
2575 (if (< not 0) "(not " "")
2576 field
2577 (if (< not 0) ")" "")))))
2578 (ebib-execute-when
2579 ((virtual-db)
2580 (setf (edb-virtual ebib-cur-db) `(,bool ,(edb-virtual ebib-cur-db)
2581 ,(if (>= not 0)
2582 `(contains ,field ,regexp)
2583 `(not (contains ,field ,regexp))))))
2584 ((real-db)
2585 (setq ebib-cur-db (ebib-create-virtual-db field regexp not))))
2586 (ebib-run-filter (edb-virtual ebib-cur-db) ebib-cur-db)
2587 (ebib-fill-entry-buffer)
2588 (ebib-fill-index-buffer))))
2590 (defun ebib-create-virtual-db (field regexp not)
2591 "Creates a virtual database based on EBIB-CUR-DB."
2592 ;; a virtual database is a database whose edb-virtual field contains an
2593 ;; expression that selects entries. this function only sets that
2594 ;; expression, it does not actually filter the entries.
2595 (let ((new-db (ebib-create-new-database ebib-cur-db)))
2596 (setf (edb-virtual new-db) (if (>= not 0)
2597 `(contains ,field ,regexp)
2598 `(not (contains ,field ,regexp))))
2599 (setf (edb-filename new-db) nil)
2600 (setf (edb-name new-db) (concat "V:" (edb-name new-db)))
2601 (setf (edb-modified new-db) nil)
2602 (setf (edb-make-backup new-db) nil)
2603 new-db))
2605 (defmacro contains (field regexp)
2606 ;; Note: the variable ENTRY is *not* bound in this macro! The function
2607 ;; calling CONTAINS *must* set ENTRY to an actual Ebib entry. The point
2608 ;; of this macro is to facilitate defining filters for virtual databases.
2609 ;; It enables us to define filters of the form:
2611 ;; (and (not (contains author "Chomsky")) (contains year "1995"))
2613 `(ebib-search-in-entry ,regexp entry ,(unless (eq field 'any) `(quote ,field))))
2615 (defun ebib-run-filter (filter db)
2616 "Runs FILTER on DB"
2617 (setf (edb-keys-list db)
2618 (sort (let ((result nil))
2619 (maphash #'(lambda (key value)
2620 (let ((entry value)) ; this is necessary for actually running the filter
2621 (when (eval filter)
2622 (setq result (cons key result)))))
2623 (edb-database db))
2624 result)
2625 'string<))
2626 (setf (edb-n-entries db) (length (edb-keys-list db)))
2627 (setf (edb-cur-entry db) (edb-keys-list db)))
2629 (defun ebib-print-filter (num)
2630 "Displays the filter of the current virtual database.
2631 With any prefix argument, reapplies the filter to the
2632 database. This can be useful when the source database was
2633 modified."
2634 (interactive "P")
2635 (ebib-execute-when
2636 ((virtual-db)
2637 (when num
2638 (ebib-run-filter (edb-virtual ebib-cur-db) ebib-cur-db)
2639 (ebib-fill-entry-buffer)
2640 (ebib-fill-index-buffer))
2641 (message "%S" (edb-virtual ebib-cur-db)))
2642 ((default)
2643 (beep))))
2645 (defun ebib-show-log ()
2646 "Displays the contents of the log buffer."
2647 (interactive)
2648 (select-window (get-buffer-window ebib-entry-buffer) nil)
2649 (set-window-dedicated-p (selected-window) nil)
2650 (switch-to-buffer ebib-log-buffer)
2651 (unless (eq ebib-layout 'full)
2652 (set-window-dedicated-p (selected-window) t)))
2654 (defun ebib-push-entry-key (prefix)
2655 "Pushes the current entry to a LaTeX buffer.
2656 The user is prompted for the buffer to push the entry into."
2657 (interactive "p")
2658 (let ((called-with-prefix (ebib-called-with-prefix)))
2659 (ebib-execute-when
2660 ((entries)
2661 (let ((buffer (read-buffer "Push entry(ies) to buffer: " ebib-push-buffer t)))
2662 (when buffer
2663 (setq ebib-push-buffer buffer)
2664 (let ((latex-cmd (or (cdr (assoc prefix ebib-insertion-strings))
2665 "{%s}"))
2666 (latex-arg (if called-with-prefix
2667 (when (edb-marked-entries ebib-cur-db)
2668 (mapconcat #'(lambda (x) x)
2669 (edb-marked-entries ebib-cur-db)
2670 ","))
2671 (car (edb-cur-entry ebib-cur-db)))))
2672 (save-excursion
2673 (set-buffer buffer)
2674 (insert (format latex-cmd latex-arg)))
2675 (message "Pushed entries to buffer %s" buffer)))))
2676 ((default)
2677 (beep)))))
2679 ;;;;;;;;;;;;;;;;
2680 ;; entry-mode ;;
2681 ;;;;;;;;;;;;;;;;
2683 (defvar ebib-entry-mode-map
2684 (let ((map (make-keymap)))
2685 (suppress-keymap map)
2686 (define-key map [up] 'ebib-prev-field)
2687 (define-key map [down] 'ebib-next-field)
2688 (define-key map [prior] 'ebib-goto-prev-set)
2689 (define-key map [next] 'ebib-goto-next-set)
2690 (define-key map [home] 'ebib-goto-first-field)
2691 (define-key map [end] 'ebib-goto-last-field)
2692 (define-key map " " 'ebib-goto-next-set)
2693 (define-key map "b" 'ebib-goto-prev-set)
2694 (define-key map "c" 'ebib-copy-field-contents)
2695 (define-key map "d" 'ebib-delete-field-contents)
2696 (define-key map "e" 'ebib-edit-field)
2697 (define-key map "f" 'ebib-view-file-in-field)
2698 (define-key map "g" 'ebib-goto-first-field)
2699 (define-key map "G" 'ebib-goto-last-field)
2700 (define-key map "j" 'ebib-next-field)
2701 (define-key map "k" 'ebib-prev-field)
2702 (define-key map "l" 'ebib-edit-multiline-field)
2703 (define-key map [(control n)] 'ebib-next-field)
2704 (define-key map [(meta n)] 'ebib-goto-prev-set)
2705 (define-key map [(control p)] 'ebib-prev-field)
2706 (define-key map [(meta p)] 'ebib-goto-next-set)
2707 (define-key map "q" 'ebib-quit-entry-buffer)
2708 (define-key map "r" 'ebib-toggle-raw)
2709 (define-key map "s" 'ebib-insert-abbreviation)
2710 (define-key map "u" 'ebib-browse-url-in-field)
2711 (define-key map "x" 'ebib-cut-field-contents)
2712 (define-key map "\C-xb" 'undefined)
2713 (define-key map "\C-xk" 'undefined)
2714 (define-key map "y" 'ebib-yank-field-contents)
2715 map)
2716 "Keymap for the Ebib entry buffer.")
2718 (define-derived-mode ebib-entry-mode
2719 fundamental-mode "Ebib-entry"
2720 "Major mode for the Ebib entry buffer."
2721 (setq buffer-read-only t)
2722 (setq truncate-lines t))
2724 (defun ebib-quit-entry-buffer ()
2725 "Quits editing the entry."
2726 (interactive)
2727 (select-window (get-buffer-window ebib-index-buffer) nil))
2729 (defun ebib-find-visible-field (field direction)
2730 "Finds the first visible field before or after FIELD.
2731 If DIRECTION is negative, search the preceding fields, otherwise
2732 search the succeeding fields. If FIELD is visible itself, return
2733 that. If there is no preceding/following visible field, return
2734 NIL. If EBIB-HIDE-HIDDEN-FIELDS is NIL, return FIELD."
2735 (when ebib-hide-hidden-fields
2736 (let ((fn (if (>= direction 0)
2737 'next-elem
2738 'prev-elem)))
2739 (while (and field
2740 (get field 'ebib-hidden))
2741 (setq field (funcall fn field ebib-cur-entry-fields)))))
2742 field)
2744 (defun ebib-prev-field ()
2745 "Moves to the previous field."
2746 (interactive)
2747 (let ((new-field (ebib-find-visible-field (prev-elem ebib-current-field ebib-cur-entry-fields) -1)))
2748 (if (null new-field)
2749 (beep)
2750 (setq ebib-current-field new-field)
2751 (ebib-move-to-field ebib-current-field -1))))
2753 (defun ebib-next-field ()
2754 "Moves to the next field."
2755 (interactive)
2756 (let ((new-field (ebib-find-visible-field (next-elem ebib-current-field ebib-cur-entry-fields) 1)))
2757 (if (null new-field)
2758 (when (interactive-p) ; i call this function after editing a field,
2759 ; and we don't want a beep then
2760 (beep))
2761 (setq ebib-current-field new-field)
2762 (ebib-move-to-field ebib-current-field 1))))
2764 (defun ebib-goto-first-field ()
2765 "Moves to the first field."
2766 (interactive)
2767 (let ((new-field (ebib-find-visible-field (car ebib-cur-entry-fields) 1)))
2768 (if (null new-field)
2769 (beep)
2770 (setq ebib-current-field new-field)
2771 (ebib-move-to-field ebib-current-field -1))))
2773 (defun ebib-goto-last-field ()
2774 "Moves to the last field."
2775 (interactive)
2776 (let ((new-field (ebib-find-visible-field (last1 ebib-cur-entry-fields) -1)))
2777 (if (null new-field)
2778 (beep)
2779 (setq ebib-current-field new-field)
2780 (ebib-move-to-field ebib-current-field 1))))
2782 (defun ebib-goto-next-set ()
2783 "Moves to the next set of fields."
2784 (interactive)
2785 (cond
2786 ((eq ebib-current-field 'type*) (ebib-next-field))
2787 ((member ebib-current-field ebib-additional-fields) (ebib-goto-last-field))
2788 (t (let* ((entry-type (gethash 'type* ebib-cur-entry-hash))
2789 (obl-fields (ebib-get-obl-fields entry-type))
2790 (opt-fields (ebib-get-opt-fields entry-type))
2791 (new-field nil))
2792 (when (member ebib-current-field obl-fields)
2793 (setq new-field (ebib-find-visible-field (car opt-fields) 1)))
2794 ;; new-field is nil if there are no opt-fields
2795 (when (or (member ebib-current-field opt-fields)
2796 (null new-field))
2797 (setq new-field (ebib-find-visible-field (car ebib-additional-fields) 1)))
2798 (if (null new-field)
2799 (ebib-goto-last-field) ; if there was no further set to go to,
2800 ; go to the last field of the current set
2801 (setq ebib-current-field new-field)
2802 (ebib-move-to-field ebib-current-field 1))))))
2804 (defun ebib-goto-prev-set ()
2805 "Moves to the previous set of fields."
2806 (interactive)
2807 (unless (eq ebib-current-field 'type*)
2808 (let* ((entry-type (gethash 'type* ebib-cur-entry-hash))
2809 (obl-fields (ebib-get-obl-fields entry-type))
2810 (opt-fields (ebib-get-opt-fields entry-type))
2811 (new-field nil))
2812 (if (member ebib-current-field obl-fields)
2813 (ebib-goto-first-field)
2814 (when (member ebib-current-field ebib-additional-fields)
2815 (setq new-field (ebib-find-visible-field (last1 opt-fields) -1)))
2816 (when (or (member ebib-current-field opt-fields)
2817 (null new-field))
2818 (setq new-field (ebib-find-visible-field (last1 obl-fields) -1)))
2819 (if (null new-field)
2820 (ebib-goto-first-field)
2821 (setq ebib-current-field new-field)
2822 (ebib-move-to-field ebib-current-field -1))))))
2824 (defun ebib-edit-entry-type ()
2825 "Edits the entry type."
2826 ;; we don't want the completion buffer to be shown in the index window,
2827 ;; so we need to switch to an appropriate window first. we do this in an
2828 ;; unwind-protect to make sure we always get back to the entry buffer.
2829 (unwind-protect
2830 (progn
2831 (if (eq ebib-layout 'full)
2832 (other-window 1)
2833 (select-window ebib-pre-ebib-window) nil)
2834 (if-str (new-type (completing-read "type: " ebib-entry-types nil t))
2835 (progn
2836 (puthash 'type* (intern-soft new-type) ebib-cur-entry-hash)
2837 (ebib-fill-entry-buffer)
2838 (setq ebib-cur-entry-fields (ebib-get-all-fields (gethash 'type* ebib-cur-entry-hash)))
2839 (ebib-set-modified t))))
2840 (select-window (get-buffer-window ebib-entry-buffer) nil)))
2842 (defun ebib-edit-crossref ()
2843 "Edits the crossref field."
2844 ;; we don't want the completion buffer to be shown in the index window,
2845 ;; so we need to switch to an appropriate window first. we do this in an
2846 ;; unwind-protect to make sure we always get back to the entry buffer.
2847 (unwind-protect
2848 (progn
2849 (if (eq ebib-layout 'full)
2850 (other-window 1)
2851 (select-window ebib-pre-ebib-window) nil)
2852 (let ((collection (ebib-create-collection (edb-database ebib-cur-db))))
2853 (if-str (key (completing-read "Key to insert in `crossref': " collection nil t))
2854 (progn
2855 (puthash 'crossref (from-raw key) ebib-cur-entry-hash)
2856 (ebib-set-modified t)))))
2857 (select-window (get-buffer-window ebib-entry-buffer) nil)
2858 ;; we now redisplay the entire entry buffer, so that the crossref'ed
2859 ;; fields show up. this also puts the cursor back on the type field.
2860 (ebib-fill-entry-buffer)
2861 (setq ebib-current-field 'crossref)
2862 (re-search-forward "^crossref")
2863 (ebib-set-fields-highlight)))
2865 ;; we should modify ebib-edit-field, so that it calls the appropriate
2866 ;; helper function, which asks the user for the new value and just returns
2867 ;; that. storing it should then be done by ebib-edit-field, no matter what
2868 ;; sort of field the user edits.
2870 (defun ebib-edit-field ()
2871 "Edits a field of a BibTeX entry."
2872 (interactive)
2873 (cond
2874 ((eq ebib-current-field 'type*) (ebib-edit-entry-type))
2875 ((eq ebib-current-field 'crossref) (ebib-edit-crossref))
2876 ((eq ebib-current-field 'annote) (ebib-edit-multiline-field))
2878 (let ((init-contents (gethash ebib-current-field ebib-cur-entry-hash))
2879 (raw nil))
2880 (if (multiline-p init-contents)
2881 (ebib-edit-multiline-field)
2882 (when init-contents
2883 (if (raw-p init-contents)
2884 (setq raw t)
2885 (setq init-contents (to-raw init-contents))))
2886 (if-str (new-contents (read-string (format "%s: " (symbol-name ebib-current-field))
2887 (if init-contents
2888 (cons init-contents 0)
2889 nil)
2890 ebib-minibuf-hist))
2891 (puthash ebib-current-field (if raw
2892 new-contents
2893 (concat "{" new-contents "}"))
2894 ebib-cur-entry-hash)
2895 (remhash ebib-current-field ebib-cur-entry-hash))
2896 (ebib-redisplay-current-field)
2897 ;; we move to the next field, but only if ebib-edit-field was
2898 ;; called interactively, otherwise we get a strange bug in
2899 ;; ebib-toggle-raw...
2900 (if (interactive-p) (ebib-next-field))
2901 (ebib-set-modified t))))))
2903 (defun ebib-browse-url-in-field (num)
2904 "Browses a URL in the current field.
2905 The field may contain a whitespace-separated set of URLs. The
2906 prefix argument indicates which URL is to be sent to the
2907 browser."
2908 (interactive "p")
2909 (let ((urls (to-raw (gethash ebib-current-field ebib-cur-entry-hash))))
2910 (if (not (and urls
2911 (ebib-call-browser urls num)))
2912 (error "No url found in field `%s'" ebib-current-field))))
2914 (defun ebib-view-file-in-field (num)
2915 "Views a file in the current field.
2916 The field may contain a whitespace-separated set of
2917 filenames. The prefix argument indicates which file is to be
2918 viewed."
2919 (interactive "p")
2920 (let ((files (to-raw (gethash ebib-current-field ebib-cur-entry-hash))))
2921 (if (not (and files
2922 (ebib-call-file-viewer files num)))
2923 (error "No valid filename found in field `%s'" ebib-current-field))))
2925 (defun ebib-copy-field-contents ()
2926 "Copies the contents of the current field to the kill ring."
2927 (interactive)
2928 (unless (eq ebib-current-field 'type*)
2929 (let ((contents (gethash ebib-current-field ebib-cur-entry-hash)))
2930 (when (stringp contents)
2931 (kill-new contents)
2932 (message "Field contents copied.")))))
2934 (defun ebib-cut-field-contents ()
2935 "Kills the contents of the current field. The killed text is put in the kill ring."
2936 (interactive)
2937 (unless (eq ebib-current-field 'type*)
2938 (let ((contents (gethash ebib-current-field ebib-cur-entry-hash)))
2939 (when (stringp contents)
2940 (remhash ebib-current-field ebib-cur-entry-hash)
2941 (kill-new contents)
2942 (ebib-redisplay-current-field)
2943 (ebib-set-modified t)
2944 (message "Field contents killed.")))))
2946 (defun ebib-yank-field-contents (arg)
2947 "Inserts the last killed text into the current field.
2948 If the current field already has a contents, nothing is inserted,
2949 unless the previous command was also ebib-yank-field-contents,
2950 then the field contents is replaced with the previous yank. That
2951 is, multiple uses of this command function like the combination
2952 of C-y/M-y. Prefix arguments also work the same as with C-y/M-y."
2953 (interactive "P")
2954 (if (or (eq ebib-current-field 'type*) ; we cannot yank into the type* or crossref fields
2955 (eq ebib-current-field 'crossref)
2956 (unless (eq last-command 'ebib-yank-field-contents)
2957 (gethash ebib-current-field ebib-cur-entry-hash))) ; nor into a field already filled
2958 (progn
2959 (setq this-command t)
2960 (beep))
2961 (let ((new-contents (current-kill (cond
2962 ((listp arg) (if (eq last-command 'ebib-yank-field-contents)
2965 ((eq arg '-) -2)
2966 (t (1- arg))))))
2967 (when new-contents
2968 (puthash ebib-current-field new-contents ebib-cur-entry-hash)
2969 (ebib-redisplay-current-field)
2970 (ebib-set-modified t)))))
2972 (defun ebib-delete-field-contents ()
2973 "Deletes the contents of the current field.
2974 The deleted text is not put in the kill ring."
2975 (interactive)
2976 (if (eq ebib-current-field 'type*)
2977 (beep)
2978 (remhash ebib-current-field ebib-cur-entry-hash)
2979 (ebib-redisplay-current-field)
2980 (ebib-set-modified t)
2981 (message "Field contents deleted.")))
2983 (defun ebib-toggle-raw ()
2984 "Toggles the raw status of the current field contents."
2985 (interactive)
2986 (unless (or (eq ebib-current-field 'type*)
2987 (eq ebib-current-field 'crossref))
2988 (let ((contents (gethash ebib-current-field ebib-cur-entry-hash)))
2989 (if (not contents) ; if there is no value,
2990 (progn
2991 (ebib-edit-field) ; the user can enter one, which we must then make raw
2992 (let ((new-contents (gethash ebib-current-field ebib-cur-entry-hash)))
2993 (when new-contents
2994 ;; note: we don't have to check for empty string, since that is
2995 ;; already done in ebib-edit-field
2996 (puthash ebib-current-field (to-raw new-contents) ebib-cur-entry-hash))))
2997 (if (raw-p contents)
2998 (puthash ebib-current-field (from-raw contents) ebib-cur-entry-hash)
2999 (puthash ebib-current-field (to-raw contents) ebib-cur-entry-hash)))
3000 (ebib-redisplay-current-field)
3001 (ebib-set-modified t))))
3003 (defun ebib-edit-multiline-field ()
3004 "Edits the current field in multiline-mode."
3005 (interactive)
3006 (unless (or (eq ebib-current-field 'type*)
3007 (eq ebib-current-field 'crossref))
3008 (let ((text (gethash ebib-current-field ebib-cur-entry-hash)))
3009 (if (raw-p text)
3010 (setq ebib-multiline-raw t)
3011 (setq text (to-raw text))
3012 (setq ebib-multiline-raw nil))
3013 (select-window (ebib-temp-window) nil)
3014 (ebib-multiline-edit 'fields text))))
3016 (defun ebib-insert-abbreviation ()
3017 "Inserts an abbreviation from the ones defined in the database."
3018 (interactive)
3019 (if (gethash ebib-current-field ebib-cur-entry-hash)
3020 (beep)
3021 (when (edb-strings-list ebib-cur-db)
3022 (unwind-protect
3023 (progn
3024 (other-window 1)
3025 (let* ((collection (ebib-create-collection (edb-strings ebib-cur-db)))
3026 (string (completing-read "Abbreviation to insert: " collection nil t)))
3027 (when string
3028 (puthash ebib-current-field string ebib-cur-entry-hash)
3029 (ebib-set-modified t))))
3030 (other-window 1)
3031 ;; we can't do this earlier, because we would be writing to the index buffer...
3032 (ebib-redisplay-current-field)
3033 (ebib-next-field)))))
3035 ;;;;;;;;;;;;;;;;;;
3036 ;; strings-mode ;;
3037 ;;;;;;;;;;;;;;;;;;
3039 (defvar ebib-strings-mode-map
3040 (let ((map (make-keymap)))
3041 (suppress-keymap map)
3042 (define-key map [up] 'ebib-prev-string)
3043 (define-key map [down] 'ebib-next-string)
3044 (define-key map [prior] 'ebib-strings-page-up)
3045 (define-key map [next] 'ebib-strings-page-down)
3046 (define-key map [home] 'ebib-goto-first-string)
3047 (define-key map [end] 'ebib-goto-last-string)
3048 (define-key map " " 'ebib-strings-page-down)
3049 (define-key map "a" 'ebib-add-string)
3050 (define-key map "b" 'ebib-strings-page-up)
3051 (define-key map "c" 'ebib-copy-string-contents)
3052 (define-key map "d" 'ebib-delete-string)
3053 (define-key map "e" 'ebib-edit-string)
3054 (define-key map "g" 'ebib-goto-first-string)
3055 (define-key map "G" 'ebib-goto-last-string)
3056 (define-key map "j" 'ebib-next-string)
3057 (define-key map "k" 'ebib-prev-string)
3058 (define-key map "l" 'ebib-edit-multiline-string)
3059 (define-key map [(control n)] 'ebib-next-string)
3060 (define-key map [(meta n)] 'ebib-strings-page-down)
3061 (define-key map [(control p)] 'ebib-prev-string)
3062 (define-key map [(meta p)] 'ebib-strings-page-up)
3063 (define-key map "q" 'ebib-quit-strings-buffer)
3064 (define-key map "x" 'ebib-export-string)
3065 (define-key map "X" 'ebib-export-all-strings)
3066 (define-key map "\C-xb" 'disabled)
3067 (define-key map "\C-xk" 'disabled)
3068 map)
3069 "Keymap for the ebib strings buffer.")
3071 (define-derived-mode ebib-strings-mode
3072 fundamental-mode "Ebib-strings"
3073 "Major mode for the Ebib strings buffer."
3074 (setq buffer-read-only t)
3075 (setq truncate-lines t))
3077 (defun ebib-quit-strings-buffer ()
3078 "Quits editing the @STRING definitions."
3079 (interactive)
3080 (set-window-dedicated-p (selected-window) nil)
3081 (switch-to-buffer ebib-entry-buffer)
3082 (unless (eq ebib-layout 'full)
3083 (set-window-dedicated-p (selected-window) t))
3084 (select-window (get-buffer-window ebib-index-buffer) nil))
3086 (defun ebib-prev-string ()
3087 "Moves to the previous string."
3088 (interactive)
3089 (if (equal ebib-current-string (car (edb-strings-list ebib-cur-db))) ; if we're on the first string
3090 (beep)
3091 ;; go to the beginnig of the highlight and move upward one line.
3092 (goto-char (ebib-highlight-start ebib-strings-highlight))
3093 (forward-line -1)
3094 (setq ebib-current-string (prev-elem ebib-current-string (edb-strings-list ebib-cur-db)))
3095 (ebib-set-strings-highlight)))
3097 (defun ebib-next-string ()
3098 "Moves to the next string."
3099 (interactive)
3100 (if (equal ebib-current-string (last1 (edb-strings-list ebib-cur-db)))
3101 (when (interactive-p) (beep))
3102 (goto-char (ebib-highlight-start ebib-strings-highlight))
3103 (forward-line 1)
3104 (setq ebib-current-string (next-elem ebib-current-string (edb-strings-list ebib-cur-db)))
3105 (ebib-set-strings-highlight)))
3107 (defun ebib-goto-first-string ()
3108 "Moves to the first string."
3109 (interactive)
3110 (setq ebib-current-string (car (edb-strings-list ebib-cur-db)))
3111 (goto-char (point-min))
3112 (ebib-set-strings-highlight))
3114 (defun ebib-goto-last-string ()
3115 "Moves to the last string."
3116 (interactive)
3117 (setq ebib-current-string (last1 (edb-strings-list ebib-cur-db)))
3118 (goto-char (point-max))
3119 (forward-line -1)
3120 (ebib-set-strings-highlight))
3122 (defun ebib-strings-page-up ()
3123 "Moves 10 entries up in the database."
3124 (interactive)
3125 (let ((number-of-strings (length (edb-strings-list ebib-cur-db)))
3126 (remaining-number-of-strings (length (member ebib-current-string (edb-strings-list ebib-cur-db)))))
3127 (if (<= (- number-of-strings remaining-number-of-strings) 10)
3128 (ebib-goto-first-string)
3129 (setq ebib-current-string (nth
3130 (- number-of-strings remaining-number-of-strings 10)
3131 (edb-strings-list ebib-cur-db)))
3132 (goto-char (ebib-highlight-start ebib-strings-highlight))
3133 (forward-line -10)
3134 (ebib-set-strings-highlight)))
3135 (message ebib-current-string))
3137 (defun ebib-strings-page-down ()
3138 "Moves 10 entries down in the database."
3139 (interactive)
3140 (let ((number-of-strings (length (edb-strings-list ebib-cur-db)))
3141 (remaining-number-of-strings (length (member ebib-current-string (edb-strings-list ebib-cur-db)))))
3142 (if (<= remaining-number-of-strings 10)
3143 (ebib-goto-last-string)
3144 (setq ebib-current-string (nth
3145 (- number-of-strings remaining-number-of-strings -10)
3146 (edb-strings-list ebib-cur-db)))
3147 (goto-char (ebib-highlight-start ebib-strings-highlight))
3148 (forward-line 10)
3149 (ebib-set-strings-highlight)))
3150 (message ebib-current-string))
3152 (defun ebib-fill-strings-buffer ()
3153 "Fills the strings buffer with the @STRING definitions."
3154 (set-buffer ebib-strings-buffer)
3155 (with-buffer-writable
3156 (erase-buffer)
3157 (dolist (elem (edb-strings-list ebib-cur-db))
3158 (let ((str (to-raw (gethash elem (edb-strings ebib-cur-db)))))
3159 (insert (format "%-18s %s\n" elem
3160 (if (multiline-p str)
3161 (concat "+" (first-line str))
3162 (concat " " str)))))))
3163 (goto-char (point-min))
3164 (setq ebib-current-string (car (edb-strings-list ebib-cur-db)))
3165 (ebib-set-strings-highlight)
3166 (set-buffer-modified-p nil))
3168 (defun ebib-edit-string ()
3169 "Edits the value of an @STRING definition
3170 When the user enters an empty string, the value is not changed."
3171 (interactive)
3172 (let ((init-contents (to-raw (gethash ebib-current-string (edb-strings ebib-cur-db)))))
3173 (if (multiline-p init-contents)
3174 (ebib-edit-multiline-string)
3175 (if-str (new-contents (read-string (format "%s: " ebib-current-string)
3176 (if init-contents
3177 (cons init-contents 0)
3178 nil)
3179 ebib-minibuf-hist))
3180 (progn
3181 (puthash ebib-current-string (from-raw new-contents) (edb-strings ebib-cur-db))
3182 (ebib-redisplay-current-string)
3183 (ebib-next-string)
3184 (ebib-set-modified t))
3185 (error "@STRING definition cannot be empty")))))
3187 (defun ebib-copy-string-contents ()
3188 "Copies the contents of the current string to the kill ring."
3189 (interactive)
3190 (let ((contents (gethash ebib-current-string (edb-strings ebib-cur-db))))
3191 (kill-new contents)
3192 (message "String value copied.")))
3194 (defun ebib-delete-string ()
3195 "Deletes the current @STRING definition from the database."
3196 (interactive)
3197 (when (y-or-n-p (format "Delete @STRING definition %s? " ebib-current-string))
3198 (remhash ebib-current-string (edb-strings ebib-cur-db))
3199 (with-buffer-writable
3200 (let ((beg (progn
3201 (goto-char (ebib-highlight-start ebib-strings-highlight))
3202 (point))))
3203 (forward-line 1)
3204 (delete-region beg (point))))
3205 (let ((new-cur-string (next-elem ebib-current-string (edb-strings-list ebib-cur-db))))
3206 (setf (edb-strings-list ebib-cur-db) (delete ebib-current-string (edb-strings-list ebib-cur-db)))
3207 (when (null new-cur-string) ; deleted the last string
3208 (setq new-cur-string (last1 (edb-strings-list ebib-cur-db)))
3209 (forward-line -1))
3210 (setq ebib-current-string new-cur-string))
3211 (ebib-set-strings-highlight)
3212 (ebib-set-modified t)
3213 (message "@STRING definition deleted.")))
3215 (defun ebib-add-string ()
3216 "Creates a new @STRING definition."
3217 (interactive)
3218 (if-str (new-abbr (read-string "New @STRING abbreviation: "))
3219 (progn
3220 (if (member new-abbr (edb-strings-list ebib-cur-db))
3221 (error (format "%s already exists" new-abbr)))
3222 (if-str (new-string (read-string (format "Value for %s: " new-abbr)))
3223 (progn
3224 (ebib-insert-string new-abbr new-string ebib-cur-db t)
3225 (sort-in-buffer (length (edb-strings-list ebib-cur-db)) new-abbr)
3226 (with-buffer-writable
3227 (insert (format "%-19s %s\n" new-abbr new-string)))
3228 (forward-line -1)
3229 (ebib-set-strings-highlight)
3230 (setq ebib-current-string new-abbr)
3231 (ebib-set-modified t))))))
3233 (defun ebib-export-string (prefix)
3234 "Exports the current @STRING.
3235 The prefix argument indicates which database to copy the string
3236 to. If no prefix argument is present, a filename is asked to
3237 which the string is appended."
3238 (interactive "P")
3239 (let ((num (ebib-prefix prefix)))
3240 (if num
3241 (ebib-export-to-db num (format "@STRING definition `%s' copied to database %%d" ebib-current-string)
3242 #'(lambda (db)
3243 (let ((abbr ebib-current-string)
3244 (string (gethash ebib-current-string (edb-strings ebib-cur-db))))
3245 (if (member abbr (edb-strings-list db))
3246 (error "@STRING definition already exists in database %d" num)
3247 (ebib-insert-string abbr string db t)))))
3248 (ebib-export-to-file (format "Export @STRING definition `%s' to file: " ebib-current-string)
3249 (format "@STRING definition `%s' exported to %%s" ebib-current-string)
3250 #'(lambda ()
3251 (insert (format "\n@string{%s = %s}\n"
3252 ebib-current-string
3253 (gethash ebib-current-string (edb-strings ebib-cur-db)))))))))
3255 (defun ebib-export-all-strings (prefix)
3256 "Exports all @STRING definitions.
3257 If a prefix argument is given, it is taken as the database to
3258 copy the definitions to. Without prefix argument, asks for a file
3259 to append them to."
3260 (interactive "P")
3261 (when ebib-current-string ; there is always a current string, unless there are no strings
3262 (let ((num (ebib-prefix prefix)))
3263 (if num
3264 (ebib-export-to-db
3265 num "All @STRING definitions copied to database %d"
3266 #'(lambda (db)
3267 (mapc #'(lambda (abbr)
3268 (if (member abbr (edb-strings-list db))
3269 (message "@STRING definition `%s' already exists in database %d" abbr num)
3270 (ebib-insert-string abbr (gethash abbr (edb-strings ebib-cur-db)) db t)))
3271 (edb-strings-list ebib-cur-db))))
3272 (ebib-export-to-file "Export all @STRING definitions to file: "
3273 "All @STRING definitions exported to %s"
3274 #'(lambda ()
3275 (insert (format "\n")) ; to keep things tidy.
3276 (ebib-format-strings ebib-cur-db)))))))
3278 (defun ebib-edit-multiline-string ()
3279 "Edits the current string in multiline-mode."
3280 (interactive)
3281 (select-window (ebib-temp-window) nil)
3282 (ebib-multiline-edit 'string (to-raw (gethash ebib-current-string (edb-strings ebib-cur-db)))))
3284 ;;;;;;;;;;;;;;;;;;;;;;;;;
3285 ;; multiline edit mode ;;
3286 ;;;;;;;;;;;;;;;;;;;;;;;;;
3288 (define-derived-mode ebib-multiline-edit-mode
3289 text-mode "Ebib-edit"
3290 "Major mode for editing multiline values in Ebib."
3291 ;; we redefine some basic keys because we need them to leave this buffer.
3292 (local-set-key "\C-xb" 'ebib-quit-multiline-edit)
3293 (local-set-key "\C-x\C-s" 'ebib-save-from-multiline-edit)
3294 (local-set-key "\C-xk" 'ebib-cancel-multiline-edit))
3296 (defun ebib-multiline-edit (type &optional starttext)
3297 "Switches to Ebib's multiline edit buffer.
3298 STARTTEXT is a string that contains the initial text of the buffer."
3299 ;; note: the buffer is put in the currently active window!
3300 (setq ebib-pre-multiline-buffer (current-buffer))
3301 (switch-to-buffer ebib-multiline-buffer)
3302 (set-buffer-modified-p nil)
3303 (erase-buffer)
3304 (setq ebib-editing type)
3305 (when starttext
3306 (insert starttext)
3307 (goto-char (point-min))
3308 (set-buffer-modified-p nil)))
3310 (defun ebib-quit-multiline-edit ()
3311 "Quits the multiline edit buffer, saving the text."
3312 (interactive)
3313 (ebib-store-multiline-text)
3314 (ebib-leave-multiline-edit-buffer)
3315 (cond
3316 ((eq ebib-editing 'fields)
3317 (ebib-next-field))
3318 ((eq ebib-editing 'strings)
3319 (ebib-next-string)))
3320 (message "Text stored."))
3322 (defun ebib-cancel-multiline-edit ()
3323 "Quits the multiline edit buffer and discards the changes."
3324 (interactive)
3325 (catch 'no-cancel
3326 (when (buffer-modified-p)
3327 (unless (y-or-n-p "Text has been modified. Abandon changes? ")
3328 (throw 'no-cancel nil)))
3329 (ebib-leave-multiline-edit-buffer)))
3331 (defun ebib-leave-multiline-edit-buffer ()
3332 "Leaves the multiline edit buffer.
3333 Restores the previous buffer in the window that the multiline
3334 edit buffer was shown in."
3335 (switch-to-buffer ebib-pre-multiline-buffer)
3336 (cond
3337 ((eq ebib-editing 'preamble)
3338 (select-window (get-buffer-window ebib-index-buffer) nil))
3339 ((eq ebib-editing 'fields)
3340 ;; in full-frame layout, select-window isn't necessary, but it doesn't hurt either.
3341 (select-window (get-buffer-window ebib-entry-buffer) nil)
3342 (ebib-redisplay-current-field))
3343 ((eq ebib-editing 'strings)
3344 ;; in full-frame layout, select-window isn't necessary, but it doesn't hurt either.
3345 (select-window (get-buffer-window ebib-strings-buffer) nil)
3346 (ebib-redisplay-current-string))))
3348 (defun ebib-save-from-multiline-edit ()
3349 "Saves the database from within the multiline edit buffer.
3350 The text being edited is stored before saving the database."
3351 (interactive)
3352 (ebib-store-multiline-text)
3353 (ebib-save-database ebib-cur-db)
3354 (set-buffer-modified-p nil))
3356 (defun ebib-store-multiline-text ()
3357 "Stores the text being edited in the multiline edit buffer."
3358 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
3359 (cond
3360 ((eq ebib-editing 'preamble)
3361 (if (equal text "")
3362 (setf (edb-preamble ebib-cur-db) nil)
3363 (setf (edb-preamble ebib-cur-db) text)))
3364 ((eq ebib-editing 'fields)
3365 (if (equal text "")
3366 (remhash ebib-current-field ebib-cur-entry-hash)
3367 (when (not ebib-multiline-raw)
3368 (setq text (from-raw text)))
3369 (puthash ebib-current-field text ebib-cur-entry-hash)))
3370 ((eq ebib-editing 'strings)
3371 (if (equal text "")
3372 ;; with ERROR, we avoid execution of EBIB-SET-MODIFIED and
3373 ;; MESSAGE, but we also do not switch back to the strings
3374 ;; buffer. this may not be so bad, actually, because the user
3375 ;; may want to change his edit.
3376 (error "@STRING definition cannot be empty ")
3377 (setq text (from-raw text)) ; strings cannot be raw
3378 (puthash ebib-current-string text (edb-strings ebib-cur-db))))))
3379 (ebib-set-modified t))
3381 ;;;;;;;;;;;;;;;;;;;
3382 ;; ebib-log-mode ;;
3383 ;;;;;;;;;;;;;;;;;;;
3385 (defvar ebib-log-mode-map
3386 (let ((map (make-keymap)))
3387 (suppress-keymap map)
3388 (define-key map " " 'scroll-up)
3389 (define-key map "b" 'scroll-down)
3390 (define-key map "q" 'ebib-quit-log-buffer)
3391 map)
3392 "Keymap for the ebib log buffer.")
3394 (define-derived-mode ebib-log-mode
3395 fundamental-mode "Ebib-log"
3396 "Major mode for the Ebib log buffer."
3397 (local-set-key "\C-xb" 'ebib-quit-log-buffer)
3398 (local-set-key "\C-xk" 'ebib-quit-log-buffer))
3400 (defun ebib-quit-log-buffer ()
3401 "Exits the log buffer."
3402 (interactive)
3403 (set-window-dedicated-p (selected-window) nil)
3404 (switch-to-buffer ebib-entry-buffer)
3405 (unless (eq ebib-layout 'full)
3406 (set-window-dedicated-p (selected-window) t))
3407 (select-window (get-buffer-window ebib-index-buffer) nil))
3409 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3410 ;; functions for non-Ebib buffers ;;
3411 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3413 (defun ebib-import ()
3414 "Searches for BibTeX entries in the current buffer.
3415 The entries are added to the current database (i.e. the database
3416 that was active when Ebib was lowered. Works on the whole buffer,
3417 or on the region if it is active."
3418 (interactive)
3419 (if (not ebib-cur-db)
3420 (error "No database loaded. Use `o' to open a database")
3421 (if (edb-virtual ebib-cur-db)
3422 (error "Cannot import to a virtual database")
3423 (with-syntax-table ebib-syntax-table
3424 (save-excursion
3425 (save-restriction
3426 (if (region-active)
3427 (narrow-to-region (region-beginning)
3428 (region-end)))
3429 (let ((buffer (current-buffer)))
3430 (with-temp-buffer
3431 (insert-buffer-substring buffer)
3432 (let ((n (ebib-find-bibtex-entries t)))
3433 (setf (edb-keys-list ebib-cur-db) (sort (edb-keys-list ebib-cur-db) 'string<))
3434 (setf (edb-n-entries ebib-cur-db) (length (edb-keys-list ebib-cur-db)))
3435 (when (edb-strings-list ebib-cur-db)
3436 (setf (edb-strings-list ebib-cur-db) (sort (edb-strings-list ebib-cur-db) 'string<)))
3437 (setf (edb-cur-entry ebib-cur-db) (edb-keys-list ebib-cur-db))
3438 (ebib-fill-entry-buffer)
3439 (ebib-fill-index-buffer)
3440 (ebib-set-modified t)
3441 (message (format "%d entries, %d @STRINGs and %s @PREAMBLE found in buffer."
3442 (car n)
3443 (cadr n)
3444 (if (caddr n)
3446 "no"))))))))))))
3448 (defun ebib-get-db-from-filename (filename)
3449 "Returns the database struct associated with FILENAME."
3450 (catch 'found
3451 (mapc #'(lambda (db)
3452 (if (string= (file-name-nondirectory (edb-filename db)) filename)
3453 (throw 'found db)))
3454 ebib-databases)
3455 nil))
3457 (defun ebib-get-local-databases ()
3458 "Returns a list of .bib files associated with the file in the current LaTeX buffer.
3459 Each element in the list is a string holding the name of the .bib
3460 file. This function simply searches the current LaTeX file or its
3461 master file for a \\bibliography command and returns the file(s)
3462 given in its argument. If no \\bibliography command is found,
3463 returns the symbol NONE."
3464 (let ((texfile-buffer (current-buffer))
3465 texfile)
3466 ;; if AucTeX's TeX-master is used and set to a string, we must
3467 ;; search that file for a \bibliography command, as it's more
3468 ;; likely to be in there than in the file we're in.
3469 (and (boundp 'TeX-master)
3470 (stringp TeX-master)
3471 (setq texfile (ensure-extension TeX-master "tex")))
3472 (with-temp-buffer
3473 (if (and texfile (file-readable-p texfile))
3474 (insert-file-contents texfile)
3475 (insert-buffer-substring texfile-buffer))
3476 (save-excursion
3477 (goto-char (point-min))
3478 (if (re-search-forward "\\\\bibliography{\\(.*?\\)}" nil t)
3479 (mapcar #'(lambda (file)
3480 (ensure-extension file "bib"))
3481 (split-string (buffer-substring-no-properties (match-beginning 1) (match-end 1)) ",[ ]*"))
3482 'none)))))
3484 (defun ebib-insert-bibtex-key (prefix)
3485 "Inserts a BibTeX key at POINT.
3486 The user is prompted for a BibTeX key and has to choose one from
3487 the database(s) associated with the current LaTeX file, or from
3488 the current database if there is no \\bibliography command. Tab
3489 completion works."
3490 (interactive "p")
3491 (ebib-execute-when
3492 ((database)
3493 (or ebib-local-bibtex-filenames
3494 (setq ebib-local-bibtex-filenames (ebib-get-local-databases)))
3495 (let (collection)
3496 (if (eq ebib-local-bibtex-filenames 'none)
3497 (if (null (edb-cur-entry ebib-cur-db))
3498 (error "No entries found in current database")
3499 (setq collection (ebib-create-collection (edb-database ebib-cur-db))))
3500 (mapc #'(lambda (file)
3501 (let ((db (ebib-get-db-from-filename file)))
3502 (cond
3503 ((null db)
3504 (message "Database %s not loaded" file))
3505 ((null (edb-cur-entry db))
3506 (message "No entries in database %s" file))
3507 (t (setq collection (append (ebib-create-collection (edb-database db))
3508 collection))))))
3509 ebib-local-bibtex-filenames))
3510 (if collection
3511 (let* ((latex-cmd (or (cdr (assoc prefix ebib-insertion-strings))
3512 "{%s}"))
3513 (key (completing-read (format "Insert \"%s\" with key: " latex-cmd)
3514 collection nil t nil ebib-minibuf-hist)))
3515 (when key
3516 (insert (format (or (cdr (assoc prefix ebib-insertion-strings))
3517 "{%s}") key)))))))
3518 ((default)
3519 (error "No database loaded"))))
3521 (defun ebib-entry-summary ()
3522 "Shows the fields of the key at POINT.
3523 The key is searched in the database associated with the LaTeX
3524 file, or in the current database if no \\bibliography command can
3525 be found."
3526 (interactive)
3527 (ebib-execute-when
3528 ((database)
3529 (or ebib-local-bibtex-filenames
3530 (setq ebib-local-bibtex-filenames (ebib-get-local-databases)))
3531 (let ((key (read-string-at-point "\"#%'(),={} \n\t\f"))
3532 entry
3533 database)
3534 (if (eq ebib-local-bibtex-filenames 'none)
3535 (if (not (member key (edb-keys-list ebib-cur-db)))
3536 (error "Entry `%s' is not in the current database" key)
3537 (setq entry (gethash key (edb-database ebib-cur-db)))
3538 (setq database ebib-cur-db))
3539 (multiple-value-setq (entry database)
3540 (catch 'found
3541 (mapc #'(lambda (file)
3542 (let ((db (ebib-get-db-from-filename file)))
3543 (if (null db)
3544 (message "Database %s not loaded" file)
3545 (if (member key (edb-keys-list db))
3546 (throw 'found (values (gethash key (edb-database db)) db))))))
3547 ebib-local-bibtex-filenames)
3548 (list nil nil))))
3549 (if (null entry)
3550 (error "Entry `%s' not found" key)
3551 (let ((index-window (get-buffer-window ebib-index-buffer)))
3552 (if (not index-window)
3553 (with-output-to-temp-buffer "*Help*"
3554 (ebib-format-fields entry 'princ))
3555 (with-selected-window index-window
3556 (setq ebib-cur-db database)
3557 (ebib-fill-index-buffer)
3558 (setf (edb-cur-entry ebib-cur-db) (member key (edb-keys-list ebib-cur-db)))
3559 (goto-char (point-min))
3560 (re-search-forward (format "^%s " key))
3561 (beginning-of-line)
3562 (ebib-set-index-highlight))
3563 (ebib-fill-entry-buffer))))))
3564 ((default)
3565 (error "No database(s) loaded"))))
3567 (provide 'ebib)
3569 ;;; ebib ends here