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