Initial Commit
[packages] / xemacs-packages / edit-utils / bookmark.el
1 ;;; bookmark.el --- set bookmarks, maybe annotate them, jump to them later.
2
3 ;; Copyright (C) 1993, 1994, 1995, 1996 Free Software Foundation
4
5 ;; Author: Karl Fogel <kfogel@red-bean.com>
6 ;; Maintainer: Karl Fogel <kfogel@red-bean.com>
7 ;; Created: July, 1993
8 ;; Author's Update Number: see variable `bookmark-version'.
9 ;; Keywords: bookmarks, placeholders, annotations
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Commentary:
29
30 ;; This package is for setting "bookmarks" in files.  A bookmark
31 ;; associates a string with a location in a certain file.  Thus, you
32 ;; can navigate your way to that location by providing the string.
33 ;; See the "User Variables" section for customizations.
34
35 ;; Thanks to David Bremner <bremner@cs.sfu.ca> for thinking of and
36 ;; then implementing the bookmark-current-bookmark idea.  He even
37 ;; sent *patches*, bless his soul...
38
39 ;; Thanks to Gregory M. Saunders <saunders@cis.ohio-state.edu> for
40 ;; fixing and improving bookmark-time-to-save-p.
41
42 ;; Thanks go to Andrew V. Klein <avk@cig.mot.com> for the code that
43 ;; sorts the alist before presenting it to the user (in bookmark-bmenu-list
44 ;; and the menu-bar).
45
46 ;; And much thanks to David Hughes <djh@harston.cv.com> for many small
47 ;; suggestions and the code to implement them (like
48 ;; bookmark-bmenu-check-position, and some of the Lucid compatibility
49 ;; stuff).
50
51 ;; Kudos (whatever they are) go to Jim Blandy <jimb@red-bean.com>
52 ;; for his eminently sensible suggestion to separate bookmark-jump
53 ;; into bookmark-jump and bookmark-jump-noselect, which made many
54 ;; other things cleaner as well.
55
56 ;; Thanks to Roland McGrath for encouragement and help with defining
57 ;; autoloads on the menu-bar.
58
59 ;; Jonathan Stigelman <stig@hackvan.com> gave patches for default
60 ;; values in bookmark-jump and bookmark-set.  Everybody please keep
61 ;; all the keystrokes they save thereby and send them to him at the
62 ;; end of each year :-)  (No, seriously, thanks Jonathan!)
63
64 ;; Buckets of gratitude to John Grabowski <johng@media.mit.edu> for
65 ;; thinking up the annotations feature and implementing it so well.
66
67 ;; Based on info-bookmark.el, by Karl Fogel and Ken Olstad
68 ;; <olstad@msc.edu>.
69
70 ;; Thanks to Mikio Nakajima <PBC01764@niftyserve.or.jp> for many bugs
71 ;; reported and fixed.
72
73 ;; Thank you, Michael Kifer, for contributing the XEmacs support.
74
75 ;; Enough with the credits already, get on to the good stuff:
76
77 ;; FAVORITE CHINESE RESTAURANT: 
78 ;; Boy, that's a tough one.  Probably Hong Min, or maybe Emperor's
79 ;; Choice (both in Chicago's Chinatown).  Well, both.  How about you?
80 \f
81 ;;;; Code:
82
83 (require 'pp)
84
85 (defconst bookmark-version "2.6.4"
86   "Version number of bookmark.el.  This is not related to the version
87 of Emacs bookmark comes with; it is used solely by bookmark's
88 maintainers to avoid version confusion.")
89
90 ;;; Misc comments:
91 ;;
92 ;; If variable bookmark-use-annotations is non-nil, an annotation is
93 ;; queried for when setting a bookmark.  
94 ;;
95 ;; The bookmark list is sorted lexically by default, but you can turn
96 ;; this off by setting bookmark-sort-flag to nil.  If it is nil, then
97 ;; the list will be presented in the order it is recorded
98 ;; (chronologically), which is actually fairly useful as well.
99
100 ;;; User Variables
101
102 (defgroup bookmarks nil
103   "Set bookmarks, maybe annotate them, jump to them later."
104   :prefix "bookmark-"
105   :group 'editing)
106
107
108 (defcustom bookmark-use-annotations nil
109   "*If non-nil, saving a bookmark will query for an annotation in a
110 buffer."
111   :type 'boolean
112   :group 'bookmarks)
113
114
115 (defcustom bookmark-save-flag t
116   "*Controls when Emacs saves bookmarks to a file.
117 --> Nil means never save bookmarks, except when `bookmark-save' is
118     explicitly called \(\\[bookmark-save]\).
119 --> t means save bookmarks when Emacs is killed.
120 --> Otherwise, it should be a number that is the frequency with which
121     the bookmark list is saved \(i.e.: the number of times which
122     Emacs' bookmark list may be modified before it is automatically
123     saved.\).  If it is a number, Emacs will also automatically save
124     bookmarks when it is killed.
125
126 Therefore, the way to get it to save every time you make or delete a
127 bookmark is to set this variable to 1 \(or 0, which produces the same
128 behavior.\)
129
130 To specify the file in which to save them, modify the variable
131 bookmark-default-file, which is `~/.emacs.bmk' by default."
132   :type '(choice (const :tag "Never" nil)
133                  (const :tag "On Exit" t)
134                  (number :tag "Frequency" 1))
135   :group 'bookmarks)
136
137
138 (defconst bookmark-old-default-file "~/.emacs-bkmrks"
139   "*The .emacs.bmk file used to be called this.")
140
141
142 ;; defvarred to avoid a compilation warning:
143 (defvar bookmark-file nil
144   "Old name for `bookmark-default-file'.")
145
146 (defvar bookmark-default-file
147   (if bookmark-file
148       ;; In case user set `bookmark-file' in her .emacs:
149       bookmark-file
150     (convert-standard-filename "~/.emacs.bmk"))
151   "*File in which to save bookmarks by default.")
152
153
154 (defcustom bookmark-version-control 'nospecial
155   "*Whether or not to make numbered backups of the bookmark file.
156 It can have four values: t, nil, `never', and `nospecial'.
157 The first three have the same meaning that they do for the
158 variable `version-control', and the final value `nospecial' means just
159 use the value of `version-control'."
160   :type '(choice (const t) (const nil) (const never) (const nospecial))
161   :group 'bookmarks)
162
163
164 (defcustom bookmark-completion-ignore-case t
165   "*Non-nil means bookmark functions ignore case in completion."
166   :type 'boolean
167   :group 'bookmarks)
168
169
170 (defcustom bookmark-sort-flag t
171   "*Non-nil means that bookmarks will be displayed sorted by bookmark
172 name.  Otherwise they will be displayed in LIFO order (that is, most
173 recently set ones come first, oldest ones come last)."
174   :type 'boolean
175   :group 'bookmarks)
176
177
178 (defcustom bookmark-automatically-show-annotations t
179   "*Nil means don't show annotations when jumping to a bookmark."
180   :type 'boolean
181   :group 'bookmarks)
182
183
184 (defcustom bookmark-bmenu-file-column 30
185   "*Column at which to display filenames in a buffer listing bookmarks.
186 You can toggle whether files are shown with \\<bookmark-bmenu-mode-map>\\[bookmark-bmenu-toggle-filenames]."
187   :type 'integer
188   :group 'bookmarks)
189
190
191 (defcustom bookmark-bmenu-toggle-filenames t
192   "*Non-nil means show filenames when listing bookmarks.
193 This may result in truncated bookmark names.  To disable this, put the
194 following in your .emacs:
195
196 \(setq bookmark-bmenu-toggle-filenames nil\)"
197   :type 'boolean
198   :group 'bookmarks)
199
200
201 (defcustom bookmark-menu-length 70
202   "*Maximum length of a bookmark name displayed on a popup menu."
203   :type 'integer
204   :group 'bookmarks)
205
206
207 ;;; No user-serviceable parts beyond this point.
208
209 ;; Is it XEmacs?
210 (defconst bookmark-xemacsp
211   (string-match "\\(Lucid\\|XEmacs\\)" emacs-version))
212
213
214 ;; Added  for lucid emacs  compatibility, db
215 (or (fboundp 'defalias)  (fset 'defalias 'fset))
216
217 ;; suggested for lucid compatibility by david hughes:
218 (or (fboundp 'frame-height)  (defalias 'frame-height 'screen-height))
219
220 ;; This variable is probably obsolete now...
221 ;; It is. -sb
222 ;(or (boundp 'baud-rate)
223 ;    ;; some random value higher than 9600    
224 ;    (setq baud-rate 19200))
225
226 ;; XEmacs apparently call this `buffer-substring-without-properties',
227 ;; sigh.
228 (or (fboundp 'buffer-substring-no-properties)
229     (if (fboundp 'buffer-substring-without-properties)
230         (fset 'buffer-substring-no-properties
231               'buffer-substring-without-properties)
232       (fset 'buffer-substring-no-properties 'buffer-substring)))
233
234 \f
235 ;;; Keymap stuff:
236 ;; some people have C-x r set to rmail or whatever.  We don't want to
237 ;; assume that C-x r is a prefix map just because it's distributed
238 ;; that way...
239 ;; These are the distribution keybindings suggested by RMS, everything
240 ;; else will be done with M-x or the menubar:
241 ;;;###autoload
242 (if (symbolp (key-binding "\C-xr"))
243     nil
244   (progn (define-key ctl-x-map "rb" 'bookmark-jump)
245          (define-key ctl-x-map "rm" 'bookmark-set)
246          (define-key ctl-x-map "rl" 'bookmark-bmenu-list)))
247
248 ;; define the map, so it can be bound by those who desire to do so:
249
250 ;;;###autoload
251 (defvar bookmark-map nil
252   "Keymap containing bindings to bookmark functions.
253 It is not bound to any key by default: to bind it
254 so that you have a bookmark prefix, just use `global-set-key' and bind a
255 key of your choice to `bookmark-map'.  All interactive bookmark
256 functions have a binding in this keymap.")
257
258 ;;;###autoload
259 (define-prefix-command 'bookmark-map)
260
261 ;; Read the help on all of these functions for details...
262 ;;;###autoload
263 (define-key bookmark-map "x" 'bookmark-set)
264 ;;;###autoload
265 (define-key bookmark-map "m" 'bookmark-set) ; "m" for "mark"
266 ;;;###autoload
267 (define-key bookmark-map "j" 'bookmark-jump)
268 ;;;###autoload
269 (define-key bookmark-map "g" 'bookmark-jump) ; "g" for "go"
270 ;;;###autoload
271 (define-key bookmark-map "i" 'bookmark-insert)
272 ;;;###autoload
273 (define-key bookmark-map "e" 'edit-bookmarks)
274 ;;;###autoload
275 (define-key bookmark-map "f" 'bookmark-insert-location) ; "f" for "find"
276 ;;;###autoload
277 (define-key bookmark-map "r" 'bookmark-rename)
278 ;;;###autoload
279 (define-key bookmark-map "d" 'bookmark-delete)
280 ;;;###autoload
281 (define-key bookmark-map "l" 'bookmark-load)
282 ;;;###autoload
283 (define-key bookmark-map "w" 'bookmark-write)
284 ;;;###autoload
285 (define-key bookmark-map "s" 'bookmark-save)
286
287
288 ;;; The annotation maps.
289 (defvar bookmark-read-annotation-mode-map (copy-keymap text-mode-map)
290   "Keymap for composing an annotation for a bookmark.")
291
292 (define-key bookmark-read-annotation-mode-map "\C-c\C-c"
293   'bookmark-send-annotation)
294
295
296 \f
297 ;;; Core variables and data structures:
298 (defvar bookmark-alist ()
299   "Association list of bookmarks and their records.
300 You probably don't want to change the value of this alist yourself;
301 instead, let the various bookmark functions do it for you.
302
303 The format of the alist is
304
305        \(BOOKMARK1 BOOKMARK2 ...\)
306
307 where each BOOKMARK is of the form
308
309 \(NAME
310   \(filename . FILE\)
311   \(front-context-string . FRONT-STR\)
312   \(rear-context-string  . REAR-STR\)
313   \(position . POS\)
314   \(info-node . POS\)
315   \(annotation . ANNOTATION\)\)
316
317 So the cdr of each bookmark is an alist too.
318 `info-node' is optional, by the way.")
319
320
321 (defvar bookmarks-already-loaded nil)
322
323
324 ;; just add the hook to make sure that people don't lose bookmarks
325 ;; when they kill Emacs, unless they don't want to save them.
326 ;;;###autoload
327 (add-hook 'kill-emacs-hook
328           (function
329            (lambda () (and (featurep 'bookmark)
330                            bookmark-alist
331                            (bookmark-time-to-save-p t)
332                            (bookmark-save)))))
333
334 ;; more stuff added by db.
335
336 (defvar bookmark-current-bookmark nil 
337   "Name of bookmark most recently used in the current file.
338 It is buffer local, used to make moving a bookmark forward
339 through a file easier.")
340
341 (make-variable-buffer-local 'bookmark-current-bookmark)
342
343
344 (defvar bookmark-alist-modification-count 0
345   "Number of modifications to bookmark list since it was last saved.")
346
347
348 (defvar bookmark-search-size 16
349   "Length of the context strings recorded on either side of a bookmark.")
350
351
352 (defvar bookmark-current-point 0)
353 (defvar bookmark-yank-point 0)
354 (defvar bookmark-current-buffer nil)
355
356
357 \f
358 ;; Helper functions.
359
360 ;; Only functions on this page and the next one (file formats) need to
361 ;; know anything about the format of bookmark-alist entries.
362 ;; Everyone else should go through them.
363
364 (defun bookmark-name-from-full-record (full-record)
365   "Return name of FULL-RECORD \(an alist element instead of a string\)."
366   (car full-record))
367
368 ;;;###autoload
369 (defun bookmark-all-names ()
370   "Return a list of all current bookmark names."
371   (bookmark-maybe-load-default-file)
372   (mapcar
373    (lambda (full-record)
374      (bookmark-name-from-full-record full-record))
375    bookmark-alist))
376
377
378 (defun bookmark-get-bookmark (bookmark)
379   "Return the full entry for BOOKMARK in bookmark-alist."
380   (assoc bookmark bookmark-alist))
381
382
383 (defun bookmark-get-bookmark-record (bookmark)
384   "Return the guts of the entry for BOOKMARK in bookmark-alist.
385 That is, all information but the name."
386   (car (cdr (bookmark-get-bookmark bookmark))))
387
388
389 (defun bookmark-set-name (bookmark newname)
390   "Set BOOKMARK's name to NEWNAME."
391   (setcar (bookmark-get-bookmark bookmark) newname))
392
393
394 (defun bookmark-get-annotation (bookmark)
395   "Return the annotation of BOOKMARK, or nil if none."
396   (cdr (assq 'annotation (bookmark-get-bookmark-record bookmark))))
397
398
399 (defun bookmark-set-annotation (bookmark ann)
400   "Set the annotation of BOOKMARK to ANN."
401   (let ((cell (assq 'annotation (bookmark-get-bookmark-record bookmark))))
402     (if cell
403         (setcdr cell ann)
404       (nconc (bookmark-get-bookmark-record bookmark)
405              (list (cons 'annotation ann))))))
406
407
408 (defun bookmark-get-filename (bookmark)
409   "Return the full filename of BOOKMARK."
410   (cdr (assq 'filename (bookmark-get-bookmark-record bookmark))))
411
412
413 (defun bookmark-set-filename (bookmark filename)
414   "Set the full filename of BOOKMARK to FILENAME."
415   (let ((cell (assq 'filename (bookmark-get-bookmark-record bookmark))))
416     (if cell
417         (setcdr cell filename)
418       (nconc (bookmark-get-bookmark-record bookmark)
419              (list (cons 'filename filename))))))
420
421
422 (defun bookmark-get-position (bookmark)
423   "Return the position \(i.e.: point\) of BOOKMARK."
424   (cdr (assq 'position (bookmark-get-bookmark-record bookmark))))
425
426
427 (defun bookmark-set-position (bookmark position)
428   "Set the position \(i.e.: point\) of BOOKMARK to POSITION."
429   (let ((cell (assq 'position (bookmark-get-bookmark-record bookmark))))
430     (if cell
431         (setcdr cell position)
432       (nconc (bookmark-get-bookmark-record bookmark)
433              (list (cons 'position position))))))
434
435
436 (defun bookmark-get-front-context-string (bookmark)
437   "Return the front-context-string of BOOKMARK."
438   (cdr (assq 'front-context-string (bookmark-get-bookmark-record bookmark))))
439
440
441 (defun bookmark-set-front-context-string (bookmark string)
442   "Set the front-context-string of BOOKMARK to STRING."
443   (let ((cell (assq 'front-context-string
444                     (bookmark-get-bookmark-record bookmark))))
445     (if cell
446         (setcdr cell string)
447       (nconc (bookmark-get-bookmark-record bookmark)
448              (list (cons 'front-context-string string))))))
449
450
451 (defun bookmark-get-rear-context-string (bookmark)
452   "Return the rear-context-string of BOOKMARK."
453   (cdr (assq 'rear-context-string (bookmark-get-bookmark-record bookmark))))
454
455
456 (defun bookmark-set-rear-context-string (bookmark string)
457   "Set the rear-context-string of BOOKMARK to STRING."
458   (let ((cell (assq 'rear-context-string
459                     (bookmark-get-bookmark-record bookmark))))
460     (if cell
461         (setcdr cell string)
462       (nconc (bookmark-get-bookmark-record bookmark)
463              (list (cons 'rear-context-string string))))))
464
465
466 (defun bookmark-get-info-node (bookmark)
467   "Get the info node associated with BOOKMARK."
468   (cdr (assq 'info-node (bookmark-get-bookmark-record bookmark))))
469   
470
471 (defun bookmark-set-info-node (bookmark node)
472   "Set the Info node of BOOKMARK to NODE."
473   (let ((cell (assq 'info-node
474                     (bookmark-get-bookmark-record bookmark))))
475     (if cell
476         (setcdr cell node)
477       (nconc (bookmark-get-bookmark-record bookmark)
478              (list (cons 'info-node node)))))
479
480   (message "%S" (assq 'info-node (bookmark-get-bookmark-record bookmark)))
481   (sit-for 4)
482   )
483   
484
485 (defvar bookmark-history nil
486   "The history list for bookmark functions.")
487
488
489 (defun bookmark-completing-read (prompt &optional default)
490   "Prompting with PROMPT, read a bookmark name in completion.
491 PROMPT will get a \": \" stuck on the end no matter what, so you
492 probably don't want to include one yourself.
493 Optional second arg DEFAULT is a string to return if the user enters
494 the empty string."
495   (bookmark-maybe-load-default-file) ; paranoia
496   (let* ((completion-ignore-case bookmark-completion-ignore-case)
497          (default default)
498          (prompt (if default
499                      (concat prompt (format " (%s): " default))
500                    (concat prompt ": ")))
501          (str
502           (condition-case nil
503               ;; XEmacs 21.2 adds the default argument.
504               (completing-read prompt
505                                bookmark-alist
506                                nil
507                                0
508                                nil
509                                'bookmark-history
510                                default)
511             (wrong-number-of-arguments
512              (completing-read prompt
513                               bookmark-alist
514                               nil
515                               0
516                               nil
517                               'bookmark-history)))))
518     ;; Take care of the lack of the default argument in XEmacs 21.1.
519     (if (string-equal "" str)
520         (list default)
521       (list str))))
522
523
524 (defmacro bookmark-maybe-historicize-string (string)
525   "Put STRING into the bookmark prompt history, if caller non-interactive.
526 We need this because sometimes bookmark functions are invoked from
527 menus, so `completing-read' never gets a chance to set `bookmark-history'."
528   (` (or
529       (interactive-p)
530       (setq bookmark-history (cons (, string) bookmark-history)))))
531
532
533 (defun bookmark-make (name &optional annotation overwrite info-node)
534   "Make a bookmark named NAME.
535 Optional second arg ANNOTATION gives it an annotation.
536 Optional third arg OVERWRITE means replace any existing bookmarks with
537 this name.
538 Optional fourth arg INFO-NODE means this bookmark is at info node
539 INFO-NODE, so record this fact in the bookmark's entry."
540   (bookmark-maybe-load-default-file)
541   (let ((stripped-name (copy-sequence name)))
542     (or bookmark-xemacsp
543         ;; XEmacs's `set-text-properties' doesn't work on
544         ;; free-standing strings, apparently.
545         (set-text-properties 0 (length stripped-name) nil stripped-name))
546     (if (and (bookmark-get-bookmark stripped-name) (not overwrite))
547         ;; already existing bookmark under that name and
548         ;; no prefix arg means just overwrite old bookmark
549         (setcdr (bookmark-get-bookmark stripped-name)
550                 (list (bookmark-make-cell annotation info-node)))
551       
552       ;; otherwise just cons it onto the front (either the bookmark
553       ;; doesn't exist already, or there is no prefix arg.  In either
554       ;; case, we want the new bookmark consed onto the alist...)
555       
556       (setq bookmark-alist
557             (cons
558              (list stripped-name 
559                    (bookmark-make-cell annotation info-node))
560              bookmark-alist)))
561     
562     ;; Added by db
563     (setq bookmark-current-bookmark stripped-name)
564     (setq bookmark-alist-modification-count
565           (1+ bookmark-alist-modification-count))
566     (if (bookmark-time-to-save-p)
567         (bookmark-save))))
568
569
570 (defun bookmark-make-cell (annotation &optional info-node)
571   "Return the record part of a new bookmark, given ANNOTATION.
572 Must be at the correct position in the buffer in which the bookmark is
573 being set.  This might change someday.
574 Optional second arg INFO-NODE means this bookmark is at info node
575 INFO-NODE, so record this fact in the bookmark's entry."
576   (let ((the-record
577          (` ((filename . (, (bookmark-buffer-file-name)))
578              (front-context-string
579               . (, (if (>= (- (point-max) (point)) bookmark-search-size)
580                        (buffer-substring-no-properties
581                         (point)
582                         (+ (point) bookmark-search-size))
583                      nil)))
584              (rear-context-string
585               . (, (if (>= (- (point) (point-min)) bookmark-search-size)
586                        (buffer-substring-no-properties
587                         (point)
588                         (- (point) bookmark-search-size))
589                      nil)))
590              (position . (, (point)))
591              ))))
592
593     ;; Now fill in the optional parts:
594     (if annotation
595         (nconc the-record (list (cons 'annotation annotation))))
596     (if info-node
597         (nconc the-record (list (cons 'info-node info-node))))
598
599     ;; Finally, return the completed record.
600     the-record))
601     
602   
603 \f
604 ;;; File format stuff
605
606 ;; The OLD format of the bookmark-alist was:
607 ;;
608 ;;       ((bookmark-name (filename
609 ;;                        string-in-front
610 ;;                        string-behind
611 ;;                        point))
612 ;;        ...)
613 ;;
614 ;; The NEW format of the bookmark-alist is:
615 ;;
616 ;;       ((bookmark-name ((filename . FILENAME)
617 ;;                        (front-context-string . string-in-front)
618 ;;                        (rear-context-string  . string-behind)
619 ;;                        (position . POINT)
620 ;;                        (annotation . annotation)
621 ;;                        (whatever   . VALUE)
622 ;;                        ...
623 ;;                        ))
624 ;;        ...)
625 ;;
626 ;;
627 ;; I switched to using an internal as well as external alist because I
628 ;; felt that would be a more flexible framework in which to add
629 ;; features.  It means that the order in which values appear doesn't
630 ;; matter, and it means that arbitrary values can be added without
631 ;; risk of interfering with existing ones.
632 ;;
633 ;; BOOKMARK-NAME is the string the user gives the bookmark and
634 ;; accesses it by from then on.  
635 ;;
636 ;; FILENAME is the location of the file in which the bookmark is set.
637 ;;
638 ;; STRING-IN-FRONT is a string of `bookmark-search-size' chars of
639 ;; context in front of the point at which the bookmark is set.
640 ;;
641 ;; STRING-BEHIND is the same thing, but after the point.  
642 ;;
643 ;; The context strings exist so that modifications to a file don't
644 ;; necessarily cause a bookmark's position to be invalidated. 
645 ;; bookmark-jump will search for STRING-BEHIND and STRING-IN-FRONT in
646 ;; case the file has changed since the bookmark was set.  It will
647 ;; attempt to place the user before the changes, if there were any.
648 ;; ANNOTATION is the annotation for the bookmark; it may not exist
649 ;; (for backward compatibility), be nil (no annotation), or be a
650 ;; string.
651
652
653 (defconst bookmark-file-format-version 1
654   "The current version of the format used by bookmark files.
655 You should never need to change this.")
656
657
658 (defconst bookmark-end-of-version-stamp-marker
659   "-*- End Of Bookmark File Format Version Stamp -*-\n"
660   "This string marks the end of the version stamp in a bookmark file.")
661
662
663 (defun bookmark-alist-from-buffer ()
664   "Return a bookmark-alist (in any format) from the current buffer.
665 The buffer must of course contain bookmark format information.
666 Does not care from where in the buffer it is called, and does not
667 affect point."
668   (save-excursion
669     (goto-char (point-min))
670     (if (search-forward bookmark-end-of-version-stamp-marker nil t)
671         (read (current-buffer))
672       ;; Else we're dealing with format version 0
673       (if (search-forward "(" nil t)
674           (progn
675             (forward-char -1)
676             (read (current-buffer)))
677         ;; Else no hope of getting information here.
678         (error "Not bookmark format")))))
679
680
681 (defun bookmark-upgrade-version-0-alist (old-list)
682   "Upgrade a version 0 alist OLD-LIST to the current version."
683   (mapcar
684    (lambda (bookmark)
685      (let* ((name      (car bookmark))
686             (record    (car (cdr bookmark)))
687             (filename  (nth 0 record))
688             (front-str (nth 1 record))
689             (rear-str  (nth 2 record))
690             (position  (nth 3 record))
691             (ann       (nth 4 record)))
692        (list
693         name
694         (` ((filename             .    (, filename))
695             (front-context-string .    (, (or front-str "")))
696             (rear-context-string  .    (, (or rear-str  "")))
697             (position             .    (, position))
698             (annotation           .    (, ann)))))))
699    old-list))
700
701
702 (defun bookmark-upgrade-file-format-from-0 ()
703   "Upgrade a bookmark file of format 0 (the original format) to format 1.
704 This expects to be called from point-min in a bookmark file."
705   (message "Upgrading bookmark format from 0 to %d..."
706            bookmark-file-format-version)
707   (let* ((old-list (bookmark-alist-from-buffer))
708          (new-list (bookmark-upgrade-version-0-alist old-list)))
709     (delete-region (point-min) (point-max))
710     (bookmark-insert-file-format-version-stamp)
711     (pp new-list (current-buffer))
712     (save-buffer))
713   (goto-char (point-min))
714   (message "Upgrading bookmark format from 0 to %d...done"
715            bookmark-file-format-version)
716   )
717
718
719 (defun bookmark-grok-file-format-version ()
720   "Return an integer which is the file-format version of this bookmark file.
721 This expects to be called from point-min in a bookmark file."
722   (if (looking-at "^;;;;")
723       (save-excursion
724         (save-match-data
725           (re-search-forward "[0-9]")
726           (forward-char -1)
727           (read (current-buffer))))
728     ;; Else this is format version 0, the original one, which didn't
729     ;; even have version stamps.
730     0))
731
732
733 (defun bookmark-maybe-upgrade-file-format ()
734   "Check the file-format version of this bookmark file.
735 If the version is not up-to-date, upgrade it automatically.
736 This expects to be called from point-min in a bookmark file."
737   (let ((version (bookmark-grok-file-format-version)))
738     (cond
739      ((= version bookmark-file-format-version)
740       ) ; home free -- version is current
741      ((= version 0)
742       (bookmark-upgrade-file-format-from-0))
743      (t
744       (error "Bookmark file format version strangeness")))))
745
746
747 (defun bookmark-insert-file-format-version-stamp ()
748   "Insert text indicating current version of bookmark file format."
749   (insert
750    (format ";;;; Emacs Bookmark Format Version %d ;;;;\n"
751            bookmark-file-format-version))
752   (insert ";;; This format is meant to be slightly human-readable;\n"
753           ";;; nevertheless, you probably don't want to edit it.\n"
754           ";;; "
755           bookmark-end-of-version-stamp-marker))
756
757
758 ;;; end file-format stuff
759
760 \f
761 ;;; Core code:
762
763 ;;;###autoload
764 (defun bookmark-set (&optional name parg)
765   "Set a bookmark named NAME inside a file.
766 If name is nil, then the user will be prompted.
767 With prefix arg, will not overwrite a bookmark that has the same name
768 as NAME if such a bookmark already exists, but instead will \"push\"
769 the new bookmark onto the bookmark alist.  Thus the most recently set
770 bookmark with name NAME would be the one in effect at any given time,
771 but the others are still there, should you decide to delete the most
772 recent one.
773
774 To yank words from the text of the buffer and use them as part of the
775 bookmark name, type C-w while setting a bookmark.  Successive C-w's
776 yank successive words.
777
778 Typing C-u inserts the name of the last bookmark used in the buffer
779 \(as an aid in using a single bookmark name to track your progress
780 through a large file\).  If no bookmark was used, then C-u inserts the
781 name of the file being visited.
782
783 Use \\[bookmark-delete] to remove bookmarks \(you give it a name,
784 and it removes only the first instance of a bookmark with that name from
785 the list of bookmarks.\)"
786   (interactive (list nil current-prefix-arg))
787   (or
788    (bookmark-buffer-file-name)
789    (error "Buffer not visiting a file or directory"))
790
791   (bookmark-maybe-load-default-file)
792
793   (setq bookmark-current-point (point))
794   (setq bookmark-yank-point (point))
795   (setq bookmark-current-buffer (current-buffer))
796
797   (let* ((default (or bookmark-current-bookmark
798                       (bookmark-buffer-name)))
799          (str
800           (or name
801               (read-from-minibuffer
802                (format "Set bookmark (%s): " default)
803                nil
804                (let ((now-map (copy-keymap minibuffer-local-map)))
805                  (progn (define-key now-map  "\C-w" 
806                           'bookmark-yank-word)
807                         (define-key now-map  "\C-u" 
808                           'bookmark-insert-current-bookmark))
809                  now-map))))
810          (annotation nil))
811     (and (string-equal str "") (setq str default))
812     ;; Ask for an annotation buffer for this bookmark 
813     (if bookmark-use-annotations
814         (bookmark-read-annotation parg str)
815       (progn
816         (bookmark-make str annotation parg (bookmark-info-current-node))
817         (setq bookmark-current-bookmark str)
818         (bookmark-bmenu-surreptitiously-rebuild-list)
819         (goto-char bookmark-current-point)))))
820
821
822 (defun bookmark-info-current-node ()
823   "If in Info-mode, return current node name (a string), else nil."
824   (if (eq major-mode 'Info-mode)
825       Info-current-node))
826
827
828 (defun bookmark-kill-line (&optional newline-too)
829   "Kill from point to end of line.
830 If optional arg NEWLINE-TOO is non-nil, delete the newline too.
831 Does not affect the kill-ring."
832   (let ((eol (save-excursion (end-of-line) (point))))
833     (delete-region (point) eol)
834     (if (and newline-too (looking-at "\n"))
835         (delete-char 1))))
836
837
838 ;; Defvars to avoid compilation warnings:
839 (defvar bookmark-annotation-paragraph nil)
840 (defvar bookmark-annotation-name nil)
841 (defvar bookmark-annotation-buffer nil)
842 (defvar bookmark-annotation-file nil)
843 (defvar bookmark-annotation-point nil)
844
845
846 (defun bookmark-send-annotation ()
847   "Use buffer contents as the annotation for a bookmark.
848 Exclude lines that begin with `#'.
849 Store the annotation text in the bookmark list with
850 the bookmark (and file, and point) specified in buffer local variables."
851   (interactive)
852   (if (not (eq major-mode 'bookmark-read-annotation-mode))
853       (error "Not in bookmark-read-annotation-mode"))
854   (goto-char (point-min))
855   (while (< (point) (point-max))
856     (if (looking-at "^#")
857         (bookmark-kill-line t)
858       (forward-line 1)))
859   (let ((annotation (buffer-substring (point-min) (point-max)))
860         (parg bookmark-annotation-paragraph)
861         (bookmark bookmark-annotation-name)
862         (pt bookmark-annotation-point)
863         (buf bookmark-annotation-buffer))
864     ;; for bookmark-make-cell to work, we need to be
865     ;; in the relevant buffer, at the relevant point.
866     ;; Actually, bookmark-make-cell should probably be re-written,
867     ;; to avoid this need.  Should I handle the error if a buffer is
868     ;; killed between "C-x r m" and a "C-c C-c" in the annotation buffer?
869     (save-excursion 
870       (pop-to-buffer buf)
871       (goto-char pt)
872       (bookmark-make bookmark annotation parg (bookmark-info-current-node))
873       (setq bookmark-current-bookmark bookmark))
874     (bookmark-bmenu-surreptitiously-rebuild-list)
875     (goto-char bookmark-current-point))
876   (kill-buffer (current-buffer)))
877
878
879 (defun bookmark-default-annotation-text (bookmark)
880   (concat "#  Type the annotation for bookmark '" bookmark "' here.\n"
881           "#  All lines which start with a '#' will be deleted.\n"
882           "#  Type C-c C-c when done.\n#\n"
883           "#  Author: " (user-full-name) " <" (user-login-name) "@"
884           (system-name) ">\n"
885           "#  Date:    " (current-time-string) "\n"))
886
887
888 (defvar bookmark-read-annotation-text-func 'bookmark-default-annotation-text
889   "Function to return default text to use for a bookmark annotation.
890 It takes the name of the bookmark, as a string, as an arg.")
891
892 (defun bookmark-read-annotation-mode (buf point parg bookmark)
893   "Mode for composing annotations for a bookmark.
894 Wants BUF POINT PARG and BOOKMARK.
895 When you have finished composing, type \\[bookmark-send-annotation] to send
896 the annotation.
897
898 \\{bookmark-read-annotation-mode-map}
899 "
900   (interactive)
901   (kill-all-local-variables)
902   (make-local-variable 'bookmark-annotation-paragraph)
903   (make-local-variable 'bookmark-annotation-name)
904   (make-local-variable 'bookmark-annotation-buffer)
905   (make-local-variable 'bookmark-annotation-file)
906   (make-local-variable 'bookmark-annotation-point)
907   (setq bookmark-annotation-paragraph parg)
908   (setq bookmark-annotation-name bookmark)
909   (setq bookmark-annotation-buffer buf)
910   (setq bookmark-annotation-file (buffer-file-name buf))
911   (setq bookmark-annotation-point point)
912   (use-local-map bookmark-read-annotation-mode-map)
913   (setq major-mode 'bookmark-read-annotation-mode)
914   (insert (funcall bookmark-read-annotation-text-func bookmark))
915   (run-hooks 'text-mode-hook))
916
917
918 (defun bookmark-read-annotation (parg bookmark)
919   "Pop up a buffer for entering a bookmark annotation.
920 Text surrounding the bookmark is PARG; the bookmark name is BOOKMARK."
921   (let ((buf (current-buffer))
922         (point (point)))
923     (pop-to-buffer (generate-new-buffer-name "*Bookmark Annotation Compose*"))
924     (bookmark-read-annotation-mode buf point parg bookmark)))
925
926
927 (defvar bookmark-edit-annotation-mode-map (copy-keymap text-mode-map)
928   "Keymap for editing an annotation of a bookmark.")
929
930
931 (define-key bookmark-edit-annotation-mode-map "\C-c\C-c"
932   'bookmark-send-edited-annotation)
933
934
935 (defun bookmark-edit-annotation-mode (bookmark)
936   "Mode for editing the annotation of bookmark BOOKMARK.
937 When you have finished composing, type \\[bookmark-send-annotation].
938
939 \\{bookmark-edit-annotation-mode-map}
940 "
941   (interactive)
942   (kill-all-local-variables)
943   (make-local-variable 'bookmark-annotation-name)
944   (setq bookmark-annotation-name bookmark)
945   (use-local-map bookmark-edit-annotation-mode-map)
946   (setq major-mode 'bookmark-edit-annotation-mode)
947   (insert (funcall bookmark-read-annotation-text-func bookmark))
948   (let ((annotation (bookmark-get-annotation bookmark)))
949     (if (and (not (eq annotation nil))
950              (not (string-equal annotation "")))
951         (insert annotation)))
952   (run-hooks 'text-mode-hook))
953
954
955 (defun bookmark-send-edited-annotation ()
956   "Use buffer contents (minus beginning with `#' as annotation for a bookmark."
957   (interactive)
958   (if (not (eq major-mode 'bookmark-edit-annotation-mode))
959       (error "Not in bookmark-edit-annotation-mode"))
960   (goto-char (point-min))
961   (while (< (point) (point-max))
962     (if (looking-at "^#")
963         (bookmark-kill-line t)
964       (forward-line 1)))
965   (let ((annotation (buffer-substring (point-min) (point-max)))
966         (bookmark bookmark-annotation-name))
967     (bookmark-set-annotation bookmark annotation)
968     (bookmark-bmenu-surreptitiously-rebuild-list)
969     (goto-char bookmark-current-point))
970   (kill-buffer (current-buffer)))
971
972
973 (defun bookmark-edit-annotation (bookmark)
974   "Pop up a buffer for editing bookmark BOOKMARK's annotation."
975   (let ((buf (current-buffer))
976         (point (point)))
977     (pop-to-buffer (generate-new-buffer-name "*Bookmark Annotation Compose*"))
978     (bookmark-edit-annotation-mode bookmark)))
979
980
981 (defun bookmark-insert-current-bookmark ()
982   "Insert this buffer's value of bookmark-current-bookmark.
983 Default to file name if it's nil."
984   (interactive)
985   (let ((str
986          (save-excursion
987            (set-buffer bookmark-current-buffer)
988            bookmark-current-bookmark)))
989     (if str (insert str) (bookmark-insert-buffer-name))))
990
991
992 (defun bookmark-insert-buffer-name ()
993   "Insert the current file name into the bookmark name being set.
994 The directory part of the file name is not used."
995   (interactive)
996   (let ((str
997          (save-excursion
998            (set-buffer bookmark-current-buffer)
999            (bookmark-buffer-name))))
1000     (insert str)))
1001
1002
1003 (defun bookmark-buffer-name ()
1004   "Return the name of the current buffer's file, non-directory.
1005 In Info, return the current node."
1006   (cond
1007    ;; Are we in Info?
1008    ((string-equal mode-name "Info") Info-current-node)
1009    ;; Or are we a file?
1010    (buffer-file-name (file-name-nondirectory buffer-file-name))
1011    ;; Or are we a directory?
1012    ((and (boundp 'dired-directory) dired-directory)
1013     (let* ((dirname (if (stringp dired-directory)
1014                         dired-directory
1015                       (car dired-directory)))
1016            (idx (1- (length dirname))))
1017       ;; Strip the trailing slash.
1018       (if (= ?/ (aref dirname idx))
1019           (file-name-nondirectory (substring dirname 0 idx))
1020         ;; Else return the current-buffer
1021         (buffer-name (current-buffer)))))
1022    ;; If all else fails, use the buffer's name.
1023    (t
1024     (buffer-name (current-buffer)))))
1025
1026
1027 (defun bookmark-yank-word ()
1028   (interactive)
1029   ;; get the next word from the buffer and append it to the name of
1030   ;; the bookmark currently being set.
1031   (let ((string (save-excursion
1032                     (set-buffer bookmark-current-buffer)
1033                     (goto-char bookmark-yank-point)
1034                     (buffer-substring-no-properties
1035                      (point)
1036                      (save-excursion
1037                        (forward-word 1)
1038                        (setq bookmark-yank-point (point)))))))
1039     (insert string)))
1040
1041
1042 (defun bookmark-buffer-file-name ()
1043   "Return the current buffer's file in a way useful for bookmarks.
1044 For example, if this is a Info buffer, return the Info file's name."
1045   (if (eq major-mode 'Info-mode)
1046         Info-current-file
1047     (or
1048      buffer-file-name
1049      (if (and (boundp 'dired-directory) dired-directory)
1050          (if (stringp dired-directory)
1051              dired-directory
1052            (car dired-directory))))))
1053
1054
1055 (defun bookmark-maybe-load-default-file ()
1056   (and (not bookmarks-already-loaded)
1057        (null bookmark-alist)
1058        (prog2
1059            (and
1060             ;; Possibly the old bookmark file, "~/.emacs-bkmrks", needs
1061             ;; to be renamed.
1062             (file-exists-p (expand-file-name bookmark-old-default-file))
1063             (not (file-exists-p (expand-file-name bookmark-default-file)))
1064             (rename-file (expand-file-name bookmark-old-default-file)
1065                          (expand-file-name bookmark-default-file)))
1066            ;; return t so the `and' will continue...
1067            t)
1068        
1069        (file-readable-p (expand-file-name bookmark-default-file))
1070        (progn
1071          (bookmark-load bookmark-default-file t t)
1072          (setq bookmarks-already-loaded t))))
1073
1074
1075 (defun bookmark-maybe-sort-alist ()
1076   ;;Return the bookmark-alist for display.  If the bookmark-sort-flag
1077   ;;is non-nil, then return a sorted copy of the alist.
1078   (if bookmark-sort-flag
1079       (setq bookmark-alist
1080             (sort (copy-alist bookmark-alist)
1081                   (function
1082                    (lambda (x y) (string-lessp (car x) (car y))))))))
1083
1084
1085 ;;;###autoload
1086 (defun bookmark-jump (bookmark)
1087   "Jump to bookmark BOOKMARK (a point in some file).  
1088 You may have a problem using this function if the value of variable
1089 `bookmark-alist' is nil.  If that happens, you need to load in some
1090 bookmarks.  See help on function `bookmark-load' for more about
1091 this.
1092
1093 If the file pointed to by BOOKMARK no longer exists, you will be asked
1094 if you wish to give the bookmark a new location, and bookmark-jump
1095 will then jump to the new location, as well as recording it in place
1096 of the old one in the permanent bookmark record."
1097   (interactive
1098    (bookmark-completing-read "Jump to bookmark" bookmark-current-bookmark))
1099   (bookmark-maybe-historicize-string bookmark)
1100   (let ((cell (bookmark-jump-noselect bookmark)))
1101     (and cell
1102          (switch-to-buffer (car cell))
1103          (goto-char (cdr cell))
1104          (if bookmark-automatically-show-annotations
1105              ;; if there is an annotation for this bookmark,
1106              ;; show it in a buffer.
1107              (bookmark-show-annotation bookmark)))))
1108
1109
1110 (defun bookmark-jump-noselect (str)
1111   ;; a leetle helper for bookmark-jump :-)
1112   ;; returns (BUFFER . POINT)
1113   (bookmark-maybe-load-default-file)
1114   (let* ((file (expand-file-name (bookmark-get-filename str)))
1115          (forward-str            (bookmark-get-front-context-string str))
1116          (behind-str             (bookmark-get-rear-context-string str))
1117          (place                  (bookmark-get-position str))
1118          (info-node              (bookmark-get-info-node str))
1119          (orig-file              file)
1120          )
1121     (if (or
1122          (file-exists-p file)
1123          ;; else try some common compression extensions
1124          ;; and Emacs better handle it right!
1125          ;; Sigh: I think it may *not* be handled at the moment.  What
1126          ;; to do about this?
1127          (setq file
1128                (or
1129                 (let ((altname (concat file ".Z")))
1130                   (and (file-exists-p altname)
1131                        altname))
1132                 (let ((altname (concat file ".gz")))
1133                   (and (file-exists-p altname)
1134                        altname))
1135                 (let ((altname (concat file ".z")))
1136                   (and (file-exists-p altname)
1137                        altname)))))
1138         (save-excursion
1139           (if info-node
1140               ;; Info nodes must be visited with care.
1141               (progn
1142                 (require 'info)
1143                 (Info-find-node file info-node))
1144             ;; Else no Info.  Can do an ordinary find-file:
1145             (set-buffer (find-file-noselect file))
1146             (goto-char place))
1147
1148           ;; Go searching forward first.  Then, if forward-str exists and
1149           ;; was found in the file, we can search backward for behind-str.
1150           ;; Rationale is that if text was inserted between the two in the
1151           ;; file, it's better to be put before it so you can read it,
1152           ;; rather than after and remain perhaps unaware of the changes.
1153           (if forward-str
1154               (if (search-forward forward-str (point-max) t)
1155                   (goto-char (match-beginning 0))))
1156           (if behind-str
1157               (if (search-backward behind-str (point-min) t)
1158                   (goto-char (match-end 0))))
1159           ;; added by db
1160           (setq bookmark-current-bookmark str)
1161           (cons (current-buffer) (point)))
1162       (progn
1163         (ding)
1164         (if (y-or-n-p (concat (file-name-nondirectory orig-file)
1165                               " nonexistent.  Relocate \""
1166                               str
1167                               "\"? "))
1168             (progn
1169               (bookmark-relocate str)
1170               ;; gasp!  It's a recursive function call in Emacs Lisp!
1171               (bookmark-jump-noselect str))
1172           (message 
1173            "Bookmark not relocated; consider removing it \(%s\)." str)
1174           nil)))))
1175
1176
1177 ;;;###autoload
1178 (defun bookmark-relocate (bookmark)
1179   "Relocate BOOKMARK to another file (reading file name with minibuffer).
1180 This makes an already existing bookmark point to that file, instead of
1181 the one it used to point at.  Useful when a file has been renamed
1182 after a bookmark was set in it."
1183   (interactive (bookmark-completing-read "Bookmark to relocate"))
1184   (bookmark-maybe-historicize-string bookmark)
1185   (bookmark-maybe-load-default-file)
1186   (let* ((bmrk-filename (bookmark-get-filename bookmark))
1187          (newloc (expand-file-name
1188                   (read-file-name
1189                    (format "Relocate %s to: " bookmark)
1190                    (file-name-directory bmrk-filename)))))
1191     (bookmark-set-filename bookmark newloc)))
1192
1193
1194 ;;;###autoload
1195 (defun bookmark-insert-location (bookmark &optional no-history)
1196   "Insert the name of the file associated with BOOKMARK.
1197 Optional second arg NO-HISTORY means don't record this in the
1198 minibuffer history list `bookmark-history'."
1199   (interactive (bookmark-completing-read "Insert bookmark location"))
1200   (or no-history (bookmark-maybe-historicize-string bookmark))
1201   (let ((start (point)))
1202     (prog1
1203         (insert (bookmark-location bookmark)) ; *Return this line*
1204       (if window-system
1205           (put-text-property start 
1206                              (save-excursion (re-search-backward
1207                                               "[^ \t]")
1208                                              (1+ (point)))
1209                              'mouse-face 'highlight)))))
1210
1211 ;;;###autoload
1212 (defalias 'bookmark-locate 'bookmark-insert-location)
1213
1214 (defun bookmark-location (bookmark)
1215   "Return the name of the file associated with BOOKMARK."
1216   (bookmark-maybe-load-default-file)
1217   (bookmark-get-filename bookmark))
1218
1219
1220 ;;;###autoload
1221 (defun bookmark-rename (old &optional new)
1222   "Change the name of OLD bookmark to NEW name.
1223 If called from keyboard, prompt for OLD and NEW.  If called from
1224 menubar, select OLD from a menu and prompt for NEW.
1225
1226 If called from Lisp, prompt for NEW if only OLD was passed as an
1227 argument.  If called with two strings, then no prompting is done.  You
1228 must pass at least OLD when calling from Lisp.
1229
1230 While you are entering the new name, consecutive C-w's insert
1231 consecutive words from the text of the buffer into the new bookmark
1232 name."
1233   (interactive (bookmark-completing-read "Old bookmark name"))
1234   (bookmark-maybe-historicize-string old)
1235   (bookmark-maybe-load-default-file)
1236   (progn
1237     (setq bookmark-current-point (point))
1238     (setq bookmark-yank-point (point))
1239     (setq bookmark-current-buffer (current-buffer))
1240     (let ((newname
1241            (or new   ; use second arg, if non-nil
1242                (read-from-minibuffer
1243                 "New name: "
1244                 nil
1245                 (let ((now-map (copy-keymap minibuffer-local-map)))
1246                   (define-key now-map  "\C-w" 'bookmark-yank-word)
1247                   now-map)
1248                 nil
1249                 'bookmark-history))))
1250       (progn
1251         (bookmark-set-name old newname)
1252         (setq bookmark-current-bookmark newname)
1253         (bookmark-bmenu-surreptitiously-rebuild-list)
1254         (setq bookmark-alist-modification-count
1255               (1+ bookmark-alist-modification-count))
1256         (if (bookmark-time-to-save-p)
1257             (bookmark-save))))))
1258
1259
1260 ;;;###autoload
1261 (defun bookmark-insert (bookmark)
1262   "Insert the text of the file pointed to by bookmark BOOKMARK.  
1263 You may have a problem using this function if the value of variable
1264 `bookmark-alist' is nil.  If that happens, you need to load in some
1265 bookmarks.  See help on function `bookmark-load' for more about
1266 this."
1267   (interactive (bookmark-completing-read "Insert bookmark contents"))
1268   (bookmark-maybe-historicize-string bookmark)
1269   (bookmark-maybe-load-default-file)
1270   (let ((orig-point (point))
1271         (str-to-insert
1272          (save-excursion
1273            (set-buffer (car (bookmark-jump-noselect bookmark)))
1274            (buffer-substring (point-min) (point-max)))))
1275     (insert str-to-insert)
1276     (push-mark)
1277     (goto-char orig-point)))
1278
1279
1280 ;;;###autoload
1281 (defun bookmark-delete (bookmark &optional batch)
1282   "Delete BOOKMARK from the bookmark list.  
1283 Removes only the first instance of a bookmark with that name.  If
1284 there are one or more other bookmarks with the same name, they will
1285 not be deleted.  Defaults to the \"current\" bookmark \(that is, the
1286 one most recently used in this file, if any\).
1287 Optional second arg BATCH means don't update the bookmark list buffer,
1288 probably because we were called from there."
1289   (interactive
1290    (bookmark-completing-read "Delete bookmark" bookmark-current-bookmark))
1291   (bookmark-maybe-historicize-string bookmark)
1292   (bookmark-maybe-load-default-file)
1293   (let ((will-go (bookmark-get-bookmark bookmark)))
1294     (setq bookmark-alist (delq will-go bookmark-alist))
1295     ;; Added by db, nil bookmark-current-bookmark if the last
1296     ;; occurrence has been deleted
1297     (or (bookmark-get-bookmark bookmark-current-bookmark)
1298         (setq bookmark-current-bookmark nil)))
1299   ;; Don't rebuild the list
1300   (if batch
1301       nil
1302     (bookmark-bmenu-surreptitiously-rebuild-list)
1303     (setq bookmark-alist-modification-count
1304           (1+ bookmark-alist-modification-count))
1305     (if (bookmark-time-to-save-p)
1306         (bookmark-save))))
1307
1308
1309 (defun bookmark-time-to-save-p (&optional last-time)
1310   ;; By Gregory M. Saunders <saunders@cis.ohio-state.edu>
1311   ;; finds out whether it's time to save bookmarks to a file, by
1312   ;; examining the value of variable bookmark-save-flag, and maybe
1313   ;; bookmark-alist-modification-count.  Returns t if they should be
1314   ;; saved, nil otherwise.  if last-time is non-nil, then this is
1315   ;; being called when emacs is killed.
1316   (cond (last-time 
1317          (and (> bookmark-alist-modification-count 0)
1318               bookmark-save-flag))
1319         ((numberp bookmark-save-flag)
1320          (>= bookmark-alist-modification-count bookmark-save-flag))
1321         (t
1322          nil)))
1323
1324
1325 ;;;###autoload
1326 (defun bookmark-write ()
1327   "Write bookmarks to a file (reading the file name with the minibuffer).
1328 Don't use this in Lisp programs; use `bookmark-save' instead."
1329   (interactive)
1330   (bookmark-maybe-load-default-file)
1331   (bookmark-save t))
1332
1333
1334 ;;;###autoload
1335 (defun bookmark-save (&optional parg file) 
1336   "Save currently defined bookmarks.
1337 Saves by default in the file defined by the variable
1338 `bookmark-default-file'.  With a prefix arg, save it in file FILE
1339 \(second argument\).
1340
1341 If you are calling this from Lisp, the two arguments are PREFIX-ARG
1342 and FILE, and if you just want it to write to the default file, then
1343 pass no arguments.  Or pass in nil and FILE, and it will save in FILE
1344 instead.  If you pass in one argument, and it is non-nil, then the
1345 user will be interactively queried for a file to save in.
1346
1347 When you want to load in the bookmarks from a file, use
1348 \`bookmark-load\', \\[bookmark-load].  That function will prompt you
1349 for a file, defaulting to the file defined by variable
1350 `bookmark-default-file'."
1351   (interactive "P")
1352   (bookmark-maybe-load-default-file)
1353   (cond
1354    ((and (null parg) (null file))
1355     ;;whether interactive or not, write to default file
1356     (bookmark-write-file bookmark-default-file))
1357    ((and (null parg) file)
1358     ;;whether interactive or not, write to given file
1359     (bookmark-write-file file))
1360    ((and parg (not file))
1361     ;;have been called interactively w/ prefix arg
1362     (let ((file (read-file-name "File to save bookmarks in: ")))
1363       (bookmark-write-file file)))
1364    (t ; someone called us with prefix-arg *and* a file, so just write to file
1365     (bookmark-write-file file)))
1366   ;; signal that we have synced the bookmark file by setting this to
1367   ;; 0.  If there was an error at any point before, it will not get
1368   ;; set, which is what we want.
1369   (setq bookmark-alist-modification-count 0))
1370
1371
1372 \f
1373 (defun bookmark-write-file (file)
1374   (save-excursion
1375     (save-window-excursion
1376       (message "Saving bookmarks to file %s..." file)
1377       (set-buffer (let ((enable-local-variables nil))
1378                     (find-file-noselect file)))
1379       (goto-char (point-min))
1380       (delete-region (point-min) (point-max))
1381       (bookmark-insert-file-format-version-stamp)
1382       (pp bookmark-alist (current-buffer))
1383       (let ((version-control
1384              (cond
1385               ((null bookmark-version-control) nil)
1386               ((eq 'never bookmark-version-control) 'never)
1387               ((eq 'nospecial bookmark-version-control) version-control)
1388               (t
1389                t))))
1390         (write-file file)
1391         (kill-buffer (current-buffer))
1392         (message "Saving bookmarks to file %s...done" file)
1393         ))))
1394
1395
1396 ;;;###autoload
1397 (defun bookmark-load (file &optional revert no-msg)
1398   "Load bookmarks from FILE (which must be in bookmark format).
1399 Appends loaded bookmarks to the front of the list of bookmarks.  If
1400 optional second argument REVERT is non-nil, existing bookmarks are
1401 destroyed.  Optional third arg NO-MSG means don't display any messages
1402 while loading.
1403
1404 If you load a file that doesn't contain a proper bookmark alist, you
1405 will corrupt Emacs's bookmark list.  Generally, you should only load
1406 in files that were created with the bookmark functions in the first
1407 place.  Your own personal bookmark file, `~/.emacs.bmk', is
1408 maintained automatically by Emacs; you shouldn't need to load it
1409 explicitly."
1410   (interactive
1411    (list (read-file-name
1412           (format "Load bookmarks from: (%s) "
1413                   bookmark-default-file)        
1414           ;;Default might not be used often,
1415           ;;but there's no better default, and
1416           ;;I guess it's better than none at all.
1417           "~/" bookmark-default-file 'confirm)))
1418   (setq file (expand-file-name file))
1419   (if (file-readable-p file)
1420       (save-excursion
1421         (save-window-excursion
1422           (if (null no-msg)
1423               (message "Loading bookmarks from %s..." file))
1424           (set-buffer (let ((enable-local-variables nil))
1425                         (find-file-noselect file)))
1426           (goto-char (point-min))
1427           (bookmark-maybe-upgrade-file-format)
1428           (let ((blist (bookmark-alist-from-buffer)))
1429             (if (listp blist)
1430                 (progn
1431                   (if (not revert)
1432                       (setq bookmark-alist-modification-count
1433                             (1+ bookmark-alist-modification-count))
1434                     (setq bookmark-alist-modification-count 0))
1435                   (setq bookmark-alist
1436                         (append blist (if (not revert) bookmark-alist)))
1437                   (bookmark-bmenu-surreptitiously-rebuild-list)) 
1438               (error "Invalid bookmark list in %s" file)))
1439           (kill-buffer (current-buffer)))
1440         (if (null no-msg)
1441             (message "Loading bookmarks from %s...done" file)))
1442     (error "Cannot read bookmark file %s" file)))
1443
1444
1445 \f
1446 ;;; Code supporting the dired-like bookmark menu.  Prefix is
1447 ;;; "bookmark-bmenu" for "buffer-menu":
1448
1449
1450 (defvar bookmark-bmenu-bookmark-column nil)
1451
1452
1453 (defvar bookmark-bmenu-hidden-bookmarks ())
1454
1455
1456 (defvar bookmark-bmenu-mode-map nil)
1457
1458
1459 (if bookmark-bmenu-mode-map
1460     nil
1461   (setq bookmark-bmenu-mode-map (make-keymap))
1462   (suppress-keymap bookmark-bmenu-mode-map t)
1463   (define-key bookmark-bmenu-mode-map "q" 'bookmark-bmenu-quit)
1464   (define-key bookmark-bmenu-mode-map "v" 'bookmark-bmenu-select)
1465   (define-key bookmark-bmenu-mode-map "w" 'bookmark-bmenu-locate)
1466   (define-key bookmark-bmenu-mode-map "2" 'bookmark-bmenu-2-window)
1467   (define-key bookmark-bmenu-mode-map "1" 'bookmark-bmenu-1-window)
1468   (define-key bookmark-bmenu-mode-map "j" 'bookmark-bmenu-this-window)
1469   (define-key bookmark-bmenu-mode-map "\C-c\C-c" 'bookmark-bmenu-this-window)
1470   (define-key bookmark-bmenu-mode-map "f" 'bookmark-bmenu-this-window)
1471   (define-key bookmark-bmenu-mode-map "o" 'bookmark-bmenu-other-window)
1472   (define-key bookmark-bmenu-mode-map "\C-o"
1473     'bookmark-bmenu-switch-other-window)
1474   (define-key bookmark-bmenu-mode-map "s" 'bookmark-bmenu-save)
1475   (define-key bookmark-bmenu-mode-map "k" 'bookmark-bmenu-delete)
1476   (define-key bookmark-bmenu-mode-map "\C-d" 'bookmark-bmenu-delete-backwards)
1477   (define-key bookmark-bmenu-mode-map "x" 'bookmark-bmenu-execute-deletions)
1478   (define-key bookmark-bmenu-mode-map "d" 'bookmark-bmenu-delete)
1479   (define-key bookmark-bmenu-mode-map " " 'next-line)
1480   (define-key bookmark-bmenu-mode-map "n" 'next-line)
1481   (define-key bookmark-bmenu-mode-map "p" 'previous-line)
1482   (define-key bookmark-bmenu-mode-map 'backspace 'bookmark-bmenu-backup-unmark)
1483   (define-key bookmark-bmenu-mode-map 'delete 'bookmark-bmenu-backup-unmark)
1484   (define-key bookmark-bmenu-mode-map "?" 'describe-mode)
1485   (define-key bookmark-bmenu-mode-map "u" 'bookmark-bmenu-unmark)
1486   (define-key bookmark-bmenu-mode-map "m" 'bookmark-bmenu-mark)
1487   (define-key bookmark-bmenu-mode-map "l" 'bookmark-bmenu-load) 
1488   (define-key bookmark-bmenu-mode-map "r" 'bookmark-bmenu-rename)
1489   (define-key bookmark-bmenu-mode-map "t" 'bookmark-bmenu-toggle-filenames)
1490   (define-key bookmark-bmenu-mode-map "a" 'bookmark-bmenu-show-annotation)
1491   (define-key bookmark-bmenu-mode-map "A" 'bookmark-bmenu-show-all-annotations)
1492   (define-key bookmark-bmenu-mode-map "e" 'bookmark-bmenu-edit-annotation)
1493   (define-key bookmark-bmenu-mode-map [mouse-2]
1494     'bookmark-bmenu-other-window-with-mouse))
1495
1496   
1497
1498 ;; Bookmark Buffer Menu mode is suitable only for specially formatted
1499 ;; data.
1500 (put 'bookmark-bmenu-mode 'mode-class 'special)
1501
1502
1503 ;; todo: need to display whether or not bookmark exists as a buffer in
1504 ;; flag column. 
1505
1506 ;; Format:
1507 ;; FLAGS  BOOKMARK [ LOCATION ]
1508
1509
1510 (defun bookmark-bmenu-surreptitiously-rebuild-list ()
1511   "Rebuild the Bookmark List if it exists.
1512 Don't affect the buffer ring order."
1513   (if (get-buffer "*Bookmark List*")
1514       (save-excursion
1515         (save-window-excursion 
1516           (bookmark-bmenu-list)))))
1517
1518
1519 ;;;###autoload
1520 (defun bookmark-bmenu-list ()
1521   "Display a list of existing bookmarks.
1522 The list is displayed in a buffer named `*Bookmark List*'.
1523 The leftmost column displays a D if the bookmark is flagged for
1524 deletion, or > if it is flagged for displaying."
1525   (interactive)
1526   (bookmark-maybe-load-default-file)
1527   (if (interactive-p)
1528       (switch-to-buffer (get-buffer-create "*Bookmark List*"))
1529     (set-buffer (get-buffer-create "*Bookmark List*")))
1530   (let ((buffer-read-only nil))
1531     (delete-region (point-max) (point-min))
1532     (goto-char (point-min)) ;sure are playing it safe...
1533     (insert "% Bookmark\n- --------\n")
1534     (bookmark-maybe-sort-alist)
1535     (mapcar
1536      (lambda (full-record)
1537        ;; if a bookmark has an annotation, prepend a "*"
1538        ;; in the list of bookmarks.
1539        (let ((annotation (bookmark-get-annotation
1540                           (bookmark-name-from-full-record full-record))))
1541          (if (and (not (eq annotation nil))
1542                   (not (string-equal annotation "")))
1543              (insert " *")
1544            (insert "  "))
1545          (let ((start (point)))
1546            (insert (bookmark-name-from-full-record full-record))
1547            (if window-system
1548                (put-text-property start 
1549                                   (save-excursion (re-search-backward
1550                                                    "[^ \t]")
1551                                                   (1+ (point)))
1552                                   'mouse-face 'highlight))
1553            (insert "\n")
1554            )))
1555      bookmark-alist))
1556   (goto-char (point-min))
1557   (forward-line 2)
1558   (bookmark-bmenu-mode)
1559   (if bookmark-bmenu-toggle-filenames
1560       (bookmark-bmenu-toggle-filenames t)))
1561
1562 ;;;###autoload
1563 (defalias 'list-bookmarks 'bookmark-bmenu-list)
1564 ;;;###autoload
1565 (defalias 'edit-bookmarks 'bookmark-bmenu-list)
1566
1567
1568
1569 (defun bookmark-bmenu-mode ()
1570   "Major mode for editing a list of bookmarks.
1571 Each line describes one of the bookmarks in Emacs.
1572 Letters do not insert themselves; instead, they are commands.
1573 Bookmark names preceded by a \"*\" have annotations.
1574 \\<bookmark-bmenu-mode-map>
1575 \\[bookmark-bmenu-mark] -- mark bookmark to be displayed.
1576 \\[bookmark-bmenu-select] -- select bookmark of line point is on.
1577   Also show bookmarks marked using m in other windows.
1578 \\[bookmark-bmenu-toggle-filenames] -- toggle displaying of filenames (they may obscure long bookmark names).
1579 \\[bookmark-bmenu-locate] -- display (in minibuffer) location of this bookmark.
1580 \\[bookmark-bmenu-1-window] -- select this bookmark in full-frame window.
1581 \\[bookmark-bmenu-2-window] -- select this bookmark in one window,
1582   together with bookmark selected before this one in another window.
1583 \\[bookmark-bmenu-this-window] -- select this bookmark in place of the bookmark menu buffer.
1584 \\[bookmark-bmenu-other-window] -- select this bookmark in another window,
1585   so the bookmark menu bookmark remains visible in its window.
1586 \\[bookmark-bmenu-switch-other-window] -- switch the other window to this bookmark.
1587 \\[bookmark-bmenu-rename] -- rename this bookmark \(prompts for new name\).   
1588 \\[bookmark-bmenu-delete] -- mark this bookmark to be deleted, and move down.
1589 \\[bookmark-bmenu-delete-backwards] -- mark this bookmark to be deleted, and move up. 
1590 \\[bookmark-bmenu-execute-deletions] -- delete bookmarks marked with `\\[bookmark-bmenu-delete]'.
1591 \\[bookmark-bmenu-save] -- save the current bookmark list in the default file.
1592   With a prefix arg, prompts for a file to save in.
1593 \\[bookmark-bmenu-load] -- load in a file of bookmarks (prompts for file.)
1594 \\[bookmark-bmenu-unmark] -- remove all kinds of marks from current line.
1595   With prefix argument, also move up one line.
1596 \\[bookmark-bmenu-backup-unmark] -- back up a line and remove marks.
1597 \\[bookmark-bmenu-show-annotation] -- show the annotation, if it exists, for the current bookmark
1598   in another buffer.
1599 \\[bookmark-bmenu-show-all-annotations] -- show the annotations of all bookmarks in another buffer.
1600 \\[bookmark-bmenu-edit-annotation] -- edit the annotation for the current bookmark."
1601   (kill-all-local-variables)
1602   (use-local-map bookmark-bmenu-mode-map)
1603   (setq truncate-lines t)
1604   (setq buffer-read-only t)
1605   (setq major-mode 'bookmark-bmenu-mode)
1606   (setq mode-name "Bookmark Menu")
1607   (run-hooks 'bookmark-bmenu-mode-hook))
1608
1609
1610 (defun bookmark-bmenu-toggle-filenames (&optional show)
1611   "Toggle whether filenames are shown in the bookmark list.
1612 Optional argument SHOW means show them unconditionally."
1613   (interactive)
1614   (cond
1615    (show
1616     (setq bookmark-bmenu-toggle-filenames nil)
1617     (bookmark-bmenu-show-filenames)
1618     (setq bookmark-bmenu-toggle-filenames t))
1619    (bookmark-bmenu-toggle-filenames
1620     (bookmark-bmenu-hide-filenames)
1621     (setq bookmark-bmenu-toggle-filenames nil))
1622    (t
1623     (bookmark-bmenu-show-filenames)
1624     (setq bookmark-bmenu-toggle-filenames t))))
1625
1626
1627 (defun bookmark-bmenu-show-filenames (&optional force)
1628   (if (and (not force) bookmark-bmenu-toggle-filenames)
1629       nil ;already shown, so do nothing
1630     (save-excursion
1631       (save-window-excursion
1632         (goto-char (point-min))
1633         (forward-line 2)
1634         (setq bookmark-bmenu-hidden-bookmarks ())
1635         (let ((buffer-read-only nil))
1636           (while (< (point) (point-max))
1637             (let ((bmrk (bookmark-bmenu-bookmark)))
1638               (setq bookmark-bmenu-hidden-bookmarks
1639                     (cons bmrk bookmark-bmenu-hidden-bookmarks))
1640               (let ((start (save-excursion (end-of-line) (point))))
1641                 (move-to-column bookmark-bmenu-file-column t)
1642                 ;; Strip off `mouse-face' from the white spaces region.
1643                 (if window-system
1644                     (remove-text-properties start (point)
1645                                             '(mouse-face))))
1646               (delete-region (point) (progn (end-of-line) (point)))
1647               (insert "  ")
1648               ;; Pass the NO-HISTORY arg:
1649               (bookmark-insert-location bmrk t)
1650               (forward-line 1))))))))
1651
1652
1653 (defun bookmark-bmenu-hide-filenames (&optional force)
1654   (if (and (not force) bookmark-bmenu-toggle-filenames)
1655       ;; nothing to hide if above is nil
1656       (save-excursion
1657         (save-window-excursion
1658           (goto-char (point-min))
1659           (forward-line 2)
1660           (setq bookmark-bmenu-hidden-bookmarks
1661                 (nreverse bookmark-bmenu-hidden-bookmarks))
1662           (save-excursion
1663             (goto-char (point-min))
1664             (search-forward "Bookmark")
1665             (backward-word 1)
1666             (setq bookmark-bmenu-bookmark-column (current-column)))
1667           (save-excursion
1668             (let ((buffer-read-only nil))
1669               (while bookmark-bmenu-hidden-bookmarks
1670                 (move-to-column bookmark-bmenu-bookmark-column t)
1671                 (bookmark-kill-line)
1672                 (let ((start (point)))
1673                   (insert (car bookmark-bmenu-hidden-bookmarks))
1674                   (if window-system
1675                       (put-text-property start 
1676                                          (save-excursion (re-search-backward
1677                                                           "[^ \t]")
1678                                                          (1+ (point)))
1679                                          'mouse-face 'highlight)))
1680                 (setq bookmark-bmenu-hidden-bookmarks
1681                       (cdr bookmark-bmenu-hidden-bookmarks))
1682                 (forward-line 1))))))))
1683
1684
1685 ;; if you look at this next function from far away, it resembles a
1686 ;; gun.  But only with this comment above... 
1687 (defun bookmark-bmenu-check-position ()
1688   ;; Returns t if on a line with a bookmark.
1689   ;; Otherwise, repositions and returns t.
1690   ;; written by David Hughes <djh@harston.cv.com>
1691   ;; Mucho thanks, David!  -karl
1692   (cond ((< (count-lines (point-min) (point)) 2)
1693          (goto-char (point-min))
1694          (forward-line 2)
1695          t)
1696         ((and (bolp) (eobp))
1697          (beginning-of-line 0)
1698          t)
1699         (t
1700          t)))
1701
1702
1703 (defun bookmark-bmenu-bookmark ()
1704   ;; return a string which is bookmark of this line.
1705   (if (bookmark-bmenu-check-position)
1706       (save-excursion
1707         (save-window-excursion
1708           (goto-char (point-min))
1709           (search-forward "Bookmark")
1710           (backward-word 1)
1711           (setq bookmark-bmenu-bookmark-column (current-column)))))
1712   (if bookmark-bmenu-toggle-filenames
1713       (bookmark-bmenu-hide-filenames))
1714   (save-excursion
1715     (save-window-excursion
1716       (beginning-of-line)
1717       (forward-char bookmark-bmenu-bookmark-column)
1718       (prog1
1719           (buffer-substring-no-properties (point) 
1720                             (progn 
1721                               (end-of-line)
1722                               (point)))
1723         ;; well, this is certainly crystal-clear:
1724         (if bookmark-bmenu-toggle-filenames
1725             (bookmark-bmenu-toggle-filenames t))))))
1726
1727
1728 (defun bookmark-show-annotation (bookmark)
1729   "Display the annotation for bookmark named BOOKMARK in a buffer,
1730 if an annotation exists."
1731   (let ((annotation (bookmark-get-annotation bookmark)))
1732     (if (and (not (eq annotation nil))
1733              (not (string-equal annotation "")))
1734         (progn
1735           (save-excursion
1736             (let ((old-buf (current-buffer)))
1737               (pop-to-buffer (get-buffer-create "*Bookmark Annotation*") t)
1738               (delete-region (point-min) (point-max))
1739               ; (insert (concat "Annotation for bookmark '" bookmark "':\n\n"))
1740               (insert annotation)
1741               (goto-char (point-min))
1742               (pop-to-buffer old-buf)))))))
1743
1744
1745 (defun bookmark-show-all-annotations ()
1746   "Display the annotations for all bookmarks in a buffer."
1747   (let ((old-buf (current-buffer)))
1748     (pop-to-buffer (get-buffer-create "*Bookmark Annotation*") t)
1749     (delete-region (point-min) (point-max))
1750     (mapcar
1751      (lambda (full-record)
1752        (let* ((name (bookmark-name-from-full-record full-record))
1753               (ann  (bookmark-get-annotation name)))
1754          (insert (concat name ":\n"))
1755          (if (and (not (eq ann nil)) (not (string-equal ann "")))
1756              ;; insert the annotation, indented by 4 spaces.
1757              (progn
1758                (save-excursion (insert ann))
1759                (while (< (point) (point-max))
1760                  (beginning-of-line) ; paranoia
1761                  (insert "    ")
1762                  (forward-line)
1763                  (end-of-line))))))
1764      bookmark-alist)
1765     (goto-char (point-min))
1766     (pop-to-buffer old-buf)))
1767
1768
1769 (defun bookmark-bmenu-mark ()
1770   "Mark bookmark on this line to be displayed by \\<bookmark-bmenu-mode-map>\\[bookmark-bmenu-select]."
1771   (interactive)
1772   (beginning-of-line)
1773   (if (bookmark-bmenu-check-position)
1774       (let ((buffer-read-only nil))
1775         (delete-char 1)
1776         (insert ?>)
1777         (forward-line 1))))
1778
1779
1780 (defun bookmark-bmenu-select ()
1781   "Select this line's bookmark; also display bookmarks marked with `>'.
1782 You can mark bookmarks with the \\<bookmark-bmenu-mode-map>\\[bookmark-bmenu-mark] command."
1783   (interactive)
1784   (if (bookmark-bmenu-check-position)
1785       (let ((bmrk (bookmark-bmenu-bookmark))
1786             (menu (current-buffer))           
1787             (others ())
1788             tem)
1789         (goto-char (point-min))
1790         (while (re-search-forward "^>" nil t)
1791           (setq tem (bookmark-bmenu-bookmark))
1792           (let ((buffer-read-only nil))
1793             (delete-char -1)
1794             (insert ?\ ))
1795           (or (string-equal tem bmrk) 
1796               (member tem others) 
1797               (setq others (cons tem others))))
1798         (setq others (nreverse others)
1799               tem (/ (1- (frame-height)) (1+ (length others))))
1800         (delete-other-windows)
1801         (bookmark-jump bmrk)
1802         (bury-buffer menu)
1803         (if others
1804             (while others
1805               (split-window nil tem)
1806               (other-window 1)
1807               (bookmark-jump (car others))
1808               (setq others (cdr others)))
1809           (other-window 1)))))
1810
1811
1812 (defun bookmark-bmenu-save (parg)
1813   "Save the current list into a bookmark file.
1814 With a prefix arg, prompts for a file to save them in."
1815   (interactive "P")
1816   (save-excursion
1817     (save-window-excursion
1818       (bookmark-save parg))))
1819
1820
1821 (defun bookmark-bmenu-load ()
1822   "Load the bookmark file and rebuild the bookmark menu-buffer."
1823   (interactive)
1824   (if (bookmark-bmenu-check-position)
1825       (save-excursion
1826         (save-window-excursion
1827           ;; This will call `bookmark-bmenu-list'
1828           (call-interactively 'bookmark-load)))))
1829
1830
1831 (defun bookmark-bmenu-1-window ()
1832   "Select this line's bookmark, alone, in full frame."
1833   (interactive)
1834   (if (bookmark-bmenu-check-position)
1835       (progn
1836         (bookmark-jump (bookmark-bmenu-bookmark))
1837         (bury-buffer (other-buffer))
1838         (delete-other-windows))))
1839
1840
1841 (defun bookmark-bmenu-2-window ()
1842   "Select this line's bookmark, with previous buffer in second window."
1843   (interactive)
1844   (if (bookmark-bmenu-check-position)
1845       (let ((bmrk (bookmark-bmenu-bookmark))
1846             (menu (current-buffer))
1847             (pop-up-windows t))
1848         (delete-other-windows)
1849         (switch-to-buffer (other-buffer))
1850         (let* ((pair (bookmark-jump-noselect bmrk))
1851                (buff (car pair))
1852                (pos  (cdr pair)))
1853           (pop-to-buffer buff)
1854           (goto-char pos))
1855         (bury-buffer menu))))
1856
1857
1858 (defun bookmark-bmenu-this-window ()
1859   "Select this line's bookmark in this window."
1860   (interactive)
1861   (if (bookmark-bmenu-check-position)
1862       (bookmark-jump (bookmark-bmenu-bookmark))))
1863
1864
1865 (defun bookmark-bmenu-other-window ()
1866   "Select this line's bookmark in other window, leaving bookmark menu visible."
1867   (interactive)
1868   (let ((bookmark (bookmark-bmenu-bookmark)))
1869     (if (bookmark-bmenu-check-position)
1870         (let* ((pair (bookmark-jump-noselect bookmark))
1871                (buff (car pair))
1872                (pos  (cdr pair)))
1873           (switch-to-buffer-other-window buff)
1874           (goto-char pos)
1875           (set-window-point (get-buffer-window buff) pos)
1876           (bookmark-show-annotation bookmark)))))
1877
1878
1879 (defun bookmark-bmenu-switch-other-window ()
1880   "Make the other window select this line's bookmark.
1881 The current window remains selected."
1882   (interactive)
1883   (let ((bookmark (bookmark-bmenu-bookmark)))
1884     (if (bookmark-bmenu-check-position)
1885         (let* ((pair (bookmark-jump-noselect bookmark))
1886                (buff (car pair))
1887                (pos  (cdr pair)))
1888           (display-buffer buff)
1889           (let ((o-buffer (current-buffer)))
1890             ;; save-excursion won't do
1891             (set-buffer buff)
1892             (goto-char pos)
1893             (set-window-point (get-buffer-window buff) pos)
1894             (set-buffer o-buffer))
1895           (bookmark-show-annotation bookmark)))))
1896
1897 (defun bookmark-bmenu-other-window-with-mouse (event)
1898   "Select bookmark at the mouse pointer in other window, leaving bookmark menu visible."
1899   (interactive "e")
1900   (save-excursion
1901     (set-buffer (if (fboundp 'event-buffer) ; XEmacs
1902                     (event-buffer event)
1903                   (window-buffer (posn-window (event-end event)))))
1904     (save-excursion
1905       (goto-char (if (fboundp 'event-closest-point)
1906                      (event-closest-point event)
1907                    (posn-point (event-end event))))
1908       (bookmark-bmenu-other-window))))
1909
1910
1911 (defun bookmark-bmenu-show-annotation ()
1912   "Show the annotation for the current bookmark in another window."
1913   (interactive)
1914   (let ((bookmark (bookmark-bmenu-bookmark)))
1915     (if (bookmark-bmenu-check-position)
1916         (bookmark-show-annotation bookmark))))
1917
1918
1919 (defun bookmark-bmenu-show-all-annotations ()
1920   "Show the annotation for all bookmarks in another window."
1921   (interactive)
1922   (bookmark-show-all-annotations))
1923
1924
1925 (defun bookmark-bmenu-edit-annotation ()
1926   "Edit the annotation for the current bookmark in another window."
1927   (interactive)
1928   (let ((bookmark (bookmark-bmenu-bookmark)))
1929     (if (bookmark-bmenu-check-position)
1930         (bookmark-edit-annotation bookmark))))
1931
1932
1933 (defun bookmark-bmenu-quit ()
1934   "Quit the bookmark menu."
1935   (interactive)
1936   (let ((buffer (current-buffer)))
1937     (switch-to-buffer (other-buffer))
1938     (bury-buffer buffer)))
1939
1940
1941 (defun bookmark-bmenu-unmark (&optional backup)
1942   "Cancel all requested operations on bookmark on this line and move down.
1943 Optional BACKUP means move up."
1944   (interactive "P")
1945   (beginning-of-line)
1946   (if (bookmark-bmenu-check-position)
1947       (progn
1948         (let ((buffer-read-only nil))
1949           (delete-char 1)
1950           ;; any flags to reset according to circumstances?  How about a
1951           ;; flag indicating whether this bookmark is being visited?
1952           ;; well, we don't have this now, so maybe later.
1953           (insert " "))
1954         (forward-line (if backup -1 1)))))
1955
1956
1957 (defun bookmark-bmenu-backup-unmark ()
1958   "Move up and cancel all requested operations on bookmark on line above."
1959   (interactive)
1960   (forward-line -1)
1961   (if (bookmark-bmenu-check-position)
1962       (progn
1963         (bookmark-bmenu-unmark)
1964         (forward-line -1))))
1965
1966
1967 (defun bookmark-bmenu-delete ()
1968   "Mark bookmark on this line to be deleted.
1969 To carry out the deletions that you've marked, use \\<bookmark-bmenu-mode-map>\\[bookmark-bmenu-execute-deletions]."
1970   (interactive)
1971   (beginning-of-line)
1972   (if (bookmark-bmenu-check-position)
1973       (let ((buffer-read-only nil))
1974         (delete-char 1)
1975         (insert ?D)
1976         (forward-line 1))))
1977
1978
1979 (defun bookmark-bmenu-delete-backwards ()
1980   "Mark bookmark on this line to be deleted, then move up one line.
1981 To carry out the deletions that you've marked, use \\<bookmark-bmenu-mode-map>\\[bookmark-bmenu-execute-deletions]."
1982   (interactive)
1983   (bookmark-bmenu-delete)
1984   (forward-line -2)
1985   (if (bookmark-bmenu-check-position)
1986       (forward-line 1)))
1987
1988
1989 (defun bookmark-bmenu-execute-deletions ()
1990   "Delete bookmarks marked with \\<Buffer-menu-mode-map>\\[Buffer-menu-delete] commands."
1991   (interactive)
1992   (message "Deleting bookmarks...")
1993   (let ((hide-em bookmark-bmenu-toggle-filenames)
1994         (o-point  (point))
1995         (o-str    (save-excursion
1996                     (beginning-of-line)
1997                     (if (looking-at "^D")
1998                         nil
1999                       (buffer-substring
2000                        (point)
2001                        (progn (end-of-line) (point))))))
2002         (o-col     (current-column)))
2003     (if hide-em (bookmark-bmenu-hide-filenames))
2004     (setq bookmark-bmenu-toggle-filenames nil)
2005     (goto-char (point-min))
2006     (forward-line 1)
2007     (while (re-search-forward "^D" (point-max) t)
2008       (bookmark-delete (bookmark-bmenu-bookmark) t)) ; pass BATCH arg
2009     (bookmark-bmenu-list)
2010     (setq bookmark-bmenu-toggle-filenames hide-em)
2011     (if bookmark-bmenu-toggle-filenames
2012         (bookmark-bmenu-toggle-filenames t))
2013     (if o-str
2014         (progn
2015           (goto-char (point-min))
2016           (search-forward o-str)
2017           (beginning-of-line)
2018           (forward-char o-col))
2019       (goto-char o-point))
2020     (beginning-of-line)
2021     (setq bookmark-alist-modification-count
2022           (1+ bookmark-alist-modification-count))
2023     (if (bookmark-time-to-save-p)
2024         (bookmark-save))
2025     (message "Deleting bookmarks...done")
2026     ))
2027
2028
2029 (defun bookmark-bmenu-rename ()
2030   "Rename bookmark on current line.  Prompts for a new name."
2031   (interactive)
2032   (if (bookmark-bmenu-check-position)
2033       (let ((bmrk (bookmark-bmenu-bookmark))
2034             (thispoint (point)))
2035         (bookmark-rename bmrk)
2036         (bookmark-bmenu-list)
2037         (goto-char thispoint))))
2038
2039
2040 (defun bookmark-bmenu-locate ()
2041   "Display location of this bookmark.  Displays in the minibuffer."
2042   (interactive)
2043   (if (bookmark-bmenu-check-position)
2044       (let ((bmrk (bookmark-bmenu-bookmark)))
2045         (message (bookmark-location bmrk)))))
2046
2047
2048 \f
2049 ;;; Menu bar stuff.  Prefix is "bookmark-menu".
2050
2051 (defun bookmark-menu-build-paned-menu (name entries)
2052   "Build a multi-paned menu named NAME from the strings in ENTRIES.
2053 That is, ENTRIES is a list of strings which appear as the choices
2054 in the menu.  The number of panes depends on the number of entries.
2055 The visible entries are truncated to `bookmark-menu-length', but the
2056 strings returned are not."
2057   (let* ((f-height (/ (frame-height) 2))
2058          (pane-list
2059           (let (temp-pane-list
2060                 (iter 0))
2061             (while entries
2062               (let (lst
2063                     (count 0))
2064                 (while (and (< count f-height) entries)
2065                   (let ((str (car entries)))
2066                     (setq lst (cons
2067                                (cons
2068                                 (if (> (length str) bookmark-menu-length)
2069                                     (substring str 0 bookmark-menu-length)
2070                                   str)
2071                                 str)
2072                                lst))
2073                     (setq entries (cdr entries))
2074                     (setq count (1+ count))))
2075                 (setq iter (1+ iter))
2076                 (setq
2077                  temp-pane-list
2078                  (cons
2079                   (cons
2080                    (format "-*- %s (%d) -*-" name iter)
2081                    (nreverse lst))
2082                   temp-pane-list))))
2083             (nreverse temp-pane-list))))
2084
2085     ;; Return the menu:
2086     (cons (concat "-*- " name " -*-") pane-list)))
2087
2088
2089 (defun bookmark-build-xemacs-menu (name entries function)
2090   "Build a menu named NAME from the strings in ENTRIES.
2091 That is, ENTRIES is a list of strings that appear as the choices
2092 in the menu.
2093 The visible entries are truncated to `bookmark-menu-length', but the
2094 strings returned are not."
2095   (let* (lst 
2096          (pane-list
2097           (progn
2098             (while entries
2099               (let ((str (car entries)))
2100                 (setq lst (cons
2101                            (vector
2102                             (if (> (length str) bookmark-menu-length)
2103                                 (substring str 0 bookmark-menu-length)
2104                               str)
2105                             (list function str)
2106                             t)
2107                            lst))
2108                 (setq entries (cdr entries))))
2109             (nreverse lst))))
2110
2111     ;; Return the menu:
2112     (append (if popup-menu-titles (list (concat "-*- " name " -*-")))
2113             pane-list)))
2114
2115
2116 (defun bookmark-menu-popup-paned-menu (event name entries)
2117   "Pop up multi-paned menu at EVENT, return string chosen from ENTRIES.
2118 That is, ENTRIES is a list of strings which appear as the choices
2119 in the menu.
2120 The number of panes depends on the number of entries."
2121   (interactive "e")
2122   (if (not (featurep 'xemacs))
2123       (x-popup-menu event (bookmark-menu-build-paned-menu name entries))
2124     ;; Kludge.  Emulate x-popup-menu
2125     (eval 
2126      (event-object
2127       (get-popup-menu-response
2128        (cons name
2129              (mapcar
2130               (lambda (x)
2131                 (vector x (list 'identity x)))
2132               entries)))))))
2133
2134
2135 (defun bookmark-menu-popup-paned-bookmark-menu (event name)
2136   "Pop up menu of bookmarks, return chosen bookmark.
2137 Pop up at EVENT, menu's name is NAME.
2138 The number of panes depends on the number of bookmarks."
2139   (bookmark-menu-popup-paned-menu event name (bookmark-all-names)))
2140
2141
2142 (defun bookmark-popup-menu-and-apply-function (func-sym menu-label event)
2143   ;; help function for making menus that need to apply a bookmark
2144   ;; function to a string.
2145   (let* ((choice (bookmark-menu-popup-paned-bookmark-menu
2146                   event menu-label)))
2147     (if choice (apply func-sym (list choice)))))
2148
2149
2150 ;;;###autoload
2151 (defun bookmark-menu-insert (event)
2152   "Insert the text of the file pointed to by bookmark BOOKMARK.  
2153 You may have a problem using this function if the value of variable
2154 `bookmark-alist' is nil.  If that happens, you need to load in some
2155 bookmarks.  See help on function `bookmark-load' for more about
2156 this.
2157
2158 Warning: this function only takes an EVENT as argument.  Use the
2159 corresponding bookmark function from Lisp \(the one without the
2160 \"-menu-\" in its name\)."
2161   (interactive "e")
2162   (bookmark-popup-menu-and-apply-function
2163    'bookmark-insert "Insert Bookmark Contents" event))
2164
2165
2166 ;;;###autoload
2167 (defun bookmark-menu-jump (event)
2168   "Jump to bookmark BOOKMARK (a point in some file).  
2169 You may have a problem using this function if the value of variable
2170 `bookmark-alist' is nil.  If that happens, you need to load in some
2171 bookmarks.  See help on function `bookmark-load' for more about
2172 this.
2173
2174 Warning: this function only takes an EVENT as argument.  Use the
2175 corresponding bookmark function from Lisp \(the one without the
2176 \"-menu-\" in its name\)."
2177   (interactive "e")
2178   (bookmark-popup-menu-and-apply-function
2179    'bookmark-jump "Jump to Bookmark" event))
2180
2181
2182 ;;;###autoload
2183 (defun bookmark-menu-locate (event)
2184   "Insert the name of the file associated with BOOKMARK. 
2185 \(This is not the same as the contents of that file\).
2186
2187 Warning: this function only takes an EVENT as argument.  Use the
2188 corresponding bookmark function from Lisp \(the one without the
2189 \"-menu-\" in its name\)."
2190   (interactive "e")
2191   (bookmark-popup-menu-and-apply-function
2192    'bookmark-insert-location "Insert Bookmark Location" event))
2193
2194
2195 ;;;###autoload
2196 (defun bookmark-menu-rename (event)
2197   "Change the name of OLD-BOOKMARK to NEWNAME.  
2198 If called from keyboard, prompts for OLD-BOOKMARK and NEWNAME.
2199 If called from menubar, OLD-BOOKMARK is selected from a menu, and
2200 prompts for NEWNAME. 
2201 If called from Lisp, prompts for NEWNAME if only OLD-BOOKMARK was
2202 passed as an argument.  If called with two strings, then no prompting
2203 is done.  You must pass at least OLD-BOOKMARK when calling from Lisp.
2204
2205 While you are entering the new name, consecutive C-w's insert
2206 consecutive words from the text of the buffer into the new bookmark
2207 name.
2208
2209 Warning: this function only takes an EVENT as argument.  Use the
2210 corresponding bookmark function from Lisp \(the one without the
2211 \"-menu-\" in its name\)."
2212   (interactive "e")
2213   (bookmark-popup-menu-and-apply-function
2214    'bookmark-rename "Rename Bookmark" event))
2215
2216
2217 ;;;###autoload
2218 (defun bookmark-menu-delete (event)
2219   "Delete the bookmark named NAME from the bookmark list.  
2220 Removes only the first instance of a bookmark with that name.  If
2221 there are one or more other bookmarks with the same name, they will
2222 not be deleted.  Defaults to the \"current\" bookmark \(that is, the
2223 one most recently used in this file, if any\).
2224
2225 Warning: this function only takes an EVENT as argument.  Use the
2226 corresponding bookmark function from Lisp \(the one without the
2227 \"-menu-\" in its name\)."
2228   (interactive "e")
2229   (bookmark-popup-menu-and-apply-function
2230    'bookmark-delete "Delete Bookmark" event))
2231
2232
2233 ;; Thanks to Roland McGrath for fixing menubar.el so that the
2234 ;; following works, and for explaining what to do to make it work.
2235
2236 ;; We MUST autoload EACH form used to set up this variable's value, so
2237 ;; that the whole job is done in loaddefs.el.
2238
2239 ;; Emacs menubar stuff.
2240
2241 ;;;###autoload
2242 (defvar menu-bar-bookmark-map (make-sparse-keymap "Bookmark functions"))
2243
2244 ;;;###autoload
2245 (defalias 'menu-bar-bookmark-map (symbol-value 'menu-bar-bookmark-map))
2246
2247 ;; make bookmarks appear toward the right side of the menu.
2248 (if (boundp 'menu-bar-final-items)
2249     (if menu-bar-final-items 
2250         (setq menu-bar-final-items
2251               (cons 'bookmark menu-bar-final-items)))
2252   (setq menu-bar-final-items '(bookmark)))
2253
2254 ;;;###autoload
2255 (define-key menu-bar-bookmark-map [load]
2256   '("Load a Bookmark File..." . bookmark-load))
2257
2258 ;;;###autoload
2259 (define-key menu-bar-bookmark-map [write]
2260   '("Save Bookmarks As..." . bookmark-write))
2261
2262 ;;;###autoload
2263 (define-key menu-bar-bookmark-map [save]
2264   '("Save Bookmarks" . bookmark-save))
2265
2266 ;;;###autoload
2267 (define-key menu-bar-bookmark-map [edit]
2268   '("Edit Bookmark List" . bookmark-bmenu-list))
2269
2270 ;;;###autoload
2271 (define-key menu-bar-bookmark-map [delete]
2272   '("Delete Bookmark" . bookmark-menu-delete))
2273
2274 ;;;###autoload
2275 (define-key menu-bar-bookmark-map [rename]
2276   '("Rename Bookmark" . bookmark-menu-rename))
2277
2278 ;;;###autoload
2279 (define-key menu-bar-bookmark-map [locate]
2280   '("Insert Location" . bookmark-menu-locate))
2281
2282 ;;;###autoload
2283 (define-key menu-bar-bookmark-map [insert]
2284   '("Insert Contents" . bookmark-menu-insert))
2285
2286 ;;;###autoload
2287 (define-key menu-bar-bookmark-map [set]
2288   '("Set Bookmark" . bookmark-set))
2289
2290 ;;;###autoload
2291 (define-key menu-bar-bookmark-map [jump] 
2292   '("Jump to Bookmark" . bookmark-menu-jump))
2293
2294 ;;;; end bookmark menu stuff ;;;;
2295
2296 \f
2297 ;;; Load Hook
2298 (defvar bookmark-load-hook nil
2299   "Hook to run at the end of loading bookmark.")
2300
2301 (run-hooks 'bookmark-load-hook)
2302
2303 (provide 'bookmark)
2304       
2305 ;;; bookmark.el ends here