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