Initial Commit
[packages] / xemacs-packages / speedbar / speedbar.el
1 ;;; speedbar --- quick access to files and tags in a frame
2
3 ;;; Copyright (C) 1996, 97, 98, 99, 00, 01, 02, 03, 04, 05, 06, 07 Free Software Foundation
4
5 ;; Author: Eric M. Ludlam <zappo@gnu.org>
6 ;; Keywords: file, tags, tools
7 ;; X-RCS: $Id: speedbar.el,v 1.253 2007/02/07 18:05:48 zappo Exp $
8
9 (defvar speedbar-version "1.0.1"
10   "The current version of speedbar.")
11 (defvar speedbar-incompatible-version "0.14beta4"
12   "This version of speedbar is incompatible with this version.
13 Due to massive API changes (removing the use of the word PATH) 
14 this version is not backward compatible to 0.14 or earlier.")
15
16 ;; This file is part of GNU Emacs.
17
18 ;; GNU Emacs is free software; you can redistribute it and/or modify
19 ;; it under the terms of the GNU General Public License as published by
20 ;; the Free Software Foundation; either version 2, or (at your option)
21 ;; any later version.
22
23 ;; GNU Emacs is distributed in the hope that it will be useful,
24 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
25 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26 ;; GNU General Public License for more details.
27
28 ;; You should have received a copy of the GNU General Public License
29 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
30 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
31 ;; Boston, MA 02110-1301, USA.
32
33 ;;; Commentary:
34 ;;
35 ;;   The speedbar provides a frame in which files, and locations in
36 ;; files are displayed.  These items can be clicked on with mouse-2 in
37 ;; to display that file location.
38 ;;
39 ;;; Customizing and Developing for speedbar
40 ;;
41 ;; Please see the speedbar manual for informaion.
42 ;;
43 ;;; Notes:
44 ;;
45 ;;    Users of really old emacsen without the need timer functions
46 ;; will not have speedbar updating automatically.  Use "g" to refresh
47 ;; the display after changing directories.  Remember, do not interrupt
48 ;; the stealthy updates or your display may not be completely
49 ;; refreshed.
50 ;;
51 ;;    AUC-TEX users: The imenu tags for AUC-TEX mode don't work very
52 ;; well.  Use the imenu keywords from tex-mode.el for better results.
53 ;;
54 ;; This file requires the library package assoc (association lists)
55 ;;     assoc should be available in all modern versions of Emacs.
56 ;; The custom package is optional (for easy configuration of speedbar)
57 ;;     http://www.dina.kvl.dk/~abraham/custom/
58 ;;     custom is available in all versions of Emacs version 20 or better.
59 ;;
60
61 ;;; TODO:
62 ;; - Timeout directories we haven't visited in a while.
63
64 (require 'assoc)
65 (require 'easymenu)
66 (require 'dframe)
67 (require 'sb-image)
68
69 ;; customization stuff
70 (defgroup speedbar nil
71   "File and tag browser frame."
72   :group 'etags
73   :group 'tools
74   :group 'convenience
75 ;  :version "20.3"
76   )
77
78 (defgroup speedbar-faces nil
79   "Faces used in speedbar."
80   :prefix "speedbar-"
81   :group 'speedbar
82   :group 'faces)
83
84 (defgroup speedbar-vc nil
85   "Version control display in speedbar."
86   :prefix "speedbar-"
87   :group 'speedbar)
88
89 ;;; Code:
90 (defun speedbar-require-version (major minor &optional beta)
91   "Non-nil if this version of SPEEDBAR does not satisfy a specific version.
92 Arguments can be:
93
94   (MAJOR MINOR &optional BETA)
95
96   Values MAJOR and MINOR must be integers.  BETA can be an integer, or
97 excluded if a released version is required.
98
99 It is assumed that if the current version is newer than that specified,
100 everything passes.  Exceptions occur when known incompatibilities are
101 introduced."
102   (inversion-test 'speedbar
103                   (concat major "." minor
104                           (when beta (concat "beta" beta)))))
105
106 (defvar speedbar-initial-expansion-mode-alist
107   '(("buffers" speedbar-buffer-easymenu-definition speedbar-buffers-key-map
108      speedbar-buffer-buttons)
109     ("quick buffers" speedbar-buffer-easymenu-definition speedbar-buffers-key-map
110      speedbar-buffer-buttons-temp)
111     ;; Files last, means first in the Displays menu
112     ("files" speedbar-easymenu-definition-special speedbar-file-key-map
113      speedbar-directory-buttons speedbar-default-directory-list)
114     )
115   "List of named expansion elements for filling the speedbar frame.
116 These expansion lists are only valid for regular files.  Special modes
117 still get to override this list on a mode-by-mode basis.  This list of
118 lists is of the form (NAME MENU KEYMAP FN1 FN2 ...).  NAME is a string
119 representing the types of things to be displayed.  MENU is an easymenu
120 structure used when in this mode.  KEYMAP is a local keymap to install
121 over the regular speedbar keymap.  FN1 ...  are functions that will be
122 called in order.  These functions will always get the default
123 directory to use passed in as the first parameter, and a 0 as the
124 second parameter.  The 0 indicates the uppermost indentation level.
125 They must assume that the cursor is at the position where they start
126 inserting buttons.")
127
128 (defvar speedbar-initial-expansion-list-name "files"
129   "A symbol name representing the expansion list to use.
130 The expansion list `speedbar-initial-expansion-mode-alist' contains
131 the names and associated functions to use for buttons in speedbar.")
132
133 (defvar speedbar-previously-used-expansion-list-name "files"
134   "Save the last expansion list method.
135 This is used for returning to a previous expansion list method when
136 the user is done with the current expansion list.")
137
138 (defvar speedbar-stealthy-function-list
139   '(("files"
140      speedbar-update-current-file
141      speedbar-check-read-only
142      speedbar-check-vc
143      speedbar-check-objects)
144     )
145   "List of functions to periodically call stealthily.
146 This list is of the form:
147  '( (\"NAME\" FUNCTION ...)
148     ...)
149 where NAME is the name of the major display mode these functions are
150 for, and the remaining elements FUNCTION are functions to call in order.
151 Each function must return nil if interrupted, or t if completed.
152 Stealthy functions which have a single operation should always return
153 t.  Functions which take a long time should maintain a state (where
154 they are in their speedbar related calculations) and permit
155 interruption.  See `speedbar-check-vc' as a good example.")
156
157 (defvar speedbar-mode-functions-list
158   '(("files" (speedbar-item-info . speedbar-files-item-info)
159      (speedbar-line-directory . speedbar-files-line-directory))
160     ("buffers" (speedbar-item-info . speedbar-buffers-item-info)
161      (speedbar-line-directory . speedbar-buffers-line-directory))
162     ("quick buffers" (speedbar-item-info . speedbar-buffers-item-info)
163      (speedbar-line-directory . speedbar-buffers-line-directory))
164     )
165   "List of function tables to use for different major display modes.
166 It is not necessary to define any functions for a specialized mode.
167 This just provides a simple way of adding lots of customizations.
168 Each sublist is of the form:
169   (\"NAME\" (FUNCTIONSYMBOL . REPLACEMENTFUNCTION) ...)
170 Where NAME is the name of the specialized mode.  The rest of the list
171 is a set of dotted pairs of the form FUNCTIONSYMBOL, which is the name
172 of a function you would like to replace, and REPLACEMENTFUNCTION,
173 which is a function you can call instead.  Not all functions can be
174 replaced this way.  Replaceable functions must provide that
175 functionality individually.")
176
177 (defcustom speedbar-mode-specific-contents-flag t
178   "*Non-nil means speedbar will show special mode contents.
179 This permits some modes to create customized contents for the speedbar
180 frame."
181   :group 'speedbar
182   :type 'boolean)
183
184 (defcustom speedbar-query-confirmation-method 'all
185   "*Query control for file operations.
186 The 'always flag means to always query before file operations.
187 The 'none-but-delete flag means to not query before any file
188 operations, except before a file deletion."
189   :group 'speedbar
190   :type '(radio (const :tag "Always Query before some file operations."
191                        all)
192                 (const :tag "Never Query before file operations, except for deletions."
193                        none-but-delete)
194 ;;;;            (const :tag "Never Every Query."
195 ;;;;                   none)
196                 ))
197
198 (defvar speedbar-special-mode-expansion-list nil
199   "Default function list for creating specialized button lists.
200 This list is set by modes that wish to have special speedbar displays.
201 The list is of function names.  Each function is called with one
202 parameter BUFFER, the originating buffer.  The current buffer is the
203 speedbar buffer.")
204
205 (defvar speedbar-special-mode-key-map nil
206   "Default keymap used when identifying a specialized display mode.
207 This keymap is local to each buffer that wants to define special keybindings
208 effective when its display is shown.")
209
210 (defcustom speedbar-before-visiting-file-hook '(push-mark)
211   "*Hooks run before speedbar visits a file in the selected frame.
212 The default buffer is the buffer in the selected window in the attached frame."
213   :group 'speedbar
214   :type 'hook)
215
216 (defcustom speedbar-visiting-file-hook nil
217   "*Hooks run when speedbar visits a file in the selected frame."
218   :group 'speedbar
219   :type 'hook)
220
221 (defcustom speedbar-before-visiting-tag-hook '(push-mark)
222   "*Hooks run before speedbar visits a tag in the selected frame.
223 The default buffer is the buffer in the selected window in the attached frame."
224   :group 'speedbar
225   :type 'hook)
226
227 (defcustom speedbar-visiting-tag-hook '(speedbar-highlight-one-tag-line)
228   "*Hooks run when speedbar visits a tag in the selected frame."
229   :group 'speedbar
230   :type 'hook
231   :options '(speedbar-highlight-one-tag-line
232              speedbar-recenter-to-top
233              speedbar-recenter
234              ))
235
236 (defcustom speedbar-load-hook nil
237   "*Hooks run when speedbar is loaded."
238   :group 'speedbar
239   :type 'hook)
240
241 (defcustom speedbar-reconfigure-keymaps-hook nil
242   "*Hooks run when the keymaps are regenerated."
243   :group 'speedbar
244   :type 'hook)
245
246 (defcustom speedbar-show-unknown-files nil
247   "*Non-nil show files we can't expand with a ? in the expand button.
248 nil means don't show the file in the list."
249   :group 'speedbar
250   :type 'boolean)
251
252 ;;; EVENTUALLY REMOVE THESE
253
254 ;; When I moved to a repeating timer, I had the horrible missfortune
255 ;; of loosing the ability for adaptive speed choice.  This update
256 ;; speed currently causes long delays when it should have been turned off.
257 (defvar speedbar-update-speed dframe-update-speed
258   "*Obsoleted variable.  Use `dframe-update-speed'.")
259
260 (defvar speedbar-navigating-speed dframe-update-speed
261   "*Obsoleted variable.  Use `dframe-update-speed'.")
262 ;;; END REMOVE THESE
263
264 (defcustom speedbar-frame-parameters '((minibuffer . nil)
265                                        (width . 20)
266                                        (border-width . 0)
267                                        (menu-bar-lines . 0)
268                                        (tool-bar-lines . 0)
269                                        (unsplittable . t)
270                                        (left-fringe . 0)
271                                        )
272   "*Parameters to use when creating the speedbar frame in Emacs.
273 Any parameter supported by a frame may be added.  The parameter `height'
274 will be initialized to the height of the frame speedbar is
275 attached to and added to this list before the new frame is initialized."
276   :group 'speedbar
277   :type '(repeat (sexp :tag "Parameter:")))
278
279 ;; These values by Hrvoje Niksic <hniksic@srce.hr>
280 (defcustom speedbar-frame-plist
281   '(minibuffer nil width 20 border-width 0
282                internal-border-width 0 unsplittable t
283                default-toolbar-visible-p nil has-modeline-p nil
284                menubar-visible-p nil
285                default-gutter-visible-p nil
286                )
287   "*Parameters to use when creating the speedbar frame in XEmacs.
288 Parameters not listed here which will be added automatically are
289 `height' which will be initialized to the height of the frame speedbar
290 is attached to."
291   :group 'speedbar
292   :type '(repeat (group :inline t
293                         (symbol :tag "Property")
294                         (sexp :tag "Value"))))
295
296 (defcustom speedbar-use-imenu-flag (stringp (locate-library "imenu"))
297   "*Non-nil means use imenu for file parsing.  nil to use etags.
298 XEmacs prior to 20.4 doesn't support imenu, therefore the default is to
299 use etags instead.  Etags support is not as robust as imenu support."
300   :tag "Use Imenu for tags"
301   :group 'speedbar
302   :type 'boolean)
303
304 (defvar speedbar-dynamic-tags-function-list
305   '((speedbar-fetch-dynamic-imenu . speedbar-insert-imenu-list)
306     (speedbar-fetch-dynamic-etags . speedbar-insert-etags-list))
307   "A list of functions which will return and insert a list of tags.
308 Each element is of the form ( FETCH .  INSERT ) where FETCH
309 is a function which takes one parameter (the file to tag) and returns a
310 list of tags.  The tag list can be of any form as long as the
311 corresponding insert method can handle it.  If it returns t, then an
312 error occurred, and the next fetch routine is tried.
313 INSERT is a function which takes an INDENTation level, and a LIST of
314 tags to insert.  It will then create the speedbar buttons.")
315
316 (defcustom speedbar-use-tool-tips-flag (and (not (featurep 'xemacs))
317                                        (>= emacs-major-version 21))
318   "*Non-nil means to use tool tips if they are avaialble.
319 When tooltips are not available, mouse-tracking and minibuffer
320 display is used instead."
321   :group 'speedbar
322   :type 'boolean)
323
324 (defcustom speedbar-track-mouse-flag (not speedbar-use-tool-tips-flag)
325   "*Non-nil means to display info about the line under the mouse."
326   :group 'speedbar
327   :type 'boolean)
328
329 (defcustom speedbar-default-position 'left-right
330   "*Default position of the speedbar frame.
331 Possible values are 'left, 'right or 'left-right.
332 If value is 'left-right, the most suitable location is
333 determined automatically."
334   :group 'speedbar
335   :type '(radio (const :tag "Automatic" left-right)
336                 (const :tag "Left" left)
337                 (const :tag "Right" right)))
338
339 (defcustom speedbar-sort-tags nil
340   "*If non-nil, sort tags in the speedbar display.  *Obsolete*.
341 Use `semantic-tag-hierarchy-method' instead."
342   :group 'speedbar
343   :type 'boolean)
344
345 (defcustom speedbar-tag-hierarchy-method
346   '(speedbar-prefix-group-tag-hierarchy
347     speedbar-trim-words-tag-hierarchy)
348   "*List of hooks which speedbar will use to organize tags into groups.
349 Groups are defined as expandable meta-tags.  Imenu supports
350 such things in some languages, such as separating variables from
351 functions.  Each hook takes one argument LST, and may destructively
352 create a new list of the same form.  LST is a list of elements of the
353 form:
354   (ELT1 ELT2 ... ELTn)
355 where each ELT is of the form
356   (TAG-NAME-STRING . NUMBER-OR-MARKER)
357 or
358   (GROUP-NAME-STRING ELT1 ELT2... ELTn)"
359   :group 'speedbar
360   :type 'hook
361   :options '(speedbar-prefix-group-tag-hierarchy
362              speedbar-trim-words-tag-hierarchy
363              speedbar-simple-group-tag-hierarchy
364              speedbar-sort-tag-hierarchy)
365   )
366
367 (defcustom speedbar-tag-group-name-minimum-length 4
368   "*The minimum length of a prefix group name before expanding.
369 Thus, if the `speedbar-tag-hierarchy-method' includes `prefix-group'
370 and one such groups common characters is less than this number of
371 characters, then the group name will be changed to the form of:
372   worda to wordb
373 instead of just
374   word
375 This way we won't get silly looking listings."
376   :group 'speedbar
377   :type 'integer)
378
379 (defcustom speedbar-tag-split-minimum-length 20
380   "*Minimum length before we stop trying to create sub-lists in tags.
381 This is used by all tag-hierarchy methods that break large lists into
382 sub-lists."
383   :group 'speedbar
384   :type 'integer)
385
386 (defcustom speedbar-tag-regroup-maximum-length 10
387   "*Maximum length of submenus that are regrouped.
388 If the regrouping option is used, then if two or more short subgroups
389 are next to each other, then they are combined until this number of
390 items is reached."
391   :group 'speedbar
392   :type 'integer)
393
394 (defcustom speedbar-directory-button-trim-method 'span
395   "*Indicates how the directory button will be displayed.
396 Possible values are:
397  'span - span large directories over multiple lines.
398  'trim - trim large directories to only show the last few.
399  nil   - no trimming."
400   :group 'speedbar
401   :type '(radio (const :tag "Span large directories over mutiple lines."
402                        span)
403                 (const :tag "Trim large directories to only show the last few."
404                        trim)
405                 (const :tag "No trimming." nil)))
406
407 (defcustom speedbar-smart-directory-expand-flag t
408   "*Non-nil means speedbar should use smart expansion.
409 Smart expansion only affects when speedbar wants to display a
410 directory for a file in the attached frame.  When smart expansion is
411 enabled, new directories which are children of a displayed directory
412 are expanded in the current framework.  If nil, then the current
413 hierarchy would be replaced with the new directory."
414   :group 'speedbar
415   :type 'boolean)
416
417 (defcustom speedbar-indentation-width 1
418   "*When sub-nodes are expanded, the number of spaces used for indentation."
419   :group 'speedbar
420   :type 'integer)
421
422 (defcustom speedbar-hide-button-brackets-flag nil
423   "*Non-nil means speedbar will hide the brackets around the + or -."
424   :group 'speedbar
425   :type 'boolean)
426
427 (defcustom speedbar-before-popup-hook nil
428   "*Hooks called before popping up the speedbar frame."
429   :group 'speedbar
430   :type 'hook)
431
432 (defcustom speedbar-after-create-hook '(speedbar-frame-reposition-smartly)
433   "*Hooks called before popping up the speedbar frame."
434   :group 'speedbar
435   :type 'hook)
436
437 (defcustom speedbar-before-delete-hook nil
438   "*Hooks called before deleting the speedbar frame."
439   :group 'speedbar
440   :type 'hook)
441
442 (defcustom speedbar-mode-hook nil
443   "*Hooks called after creating a speedbar buffer."
444   :group 'speedbar
445   :type 'hook)
446
447 (defcustom speedbar-timer-hook nil
448   "*Hooks called after running the speedbar timer function."
449   :group 'speedbar
450   :type 'hook)
451
452 (defcustom speedbar-verbosity-level 1
453   "*Verbosity level of the speedbar.  0 means say nothing.
454 1 means medium level verbosity.  2 and higher are higher levels of
455 verbosity."
456   :group 'speedbar
457   :type 'integer)
458
459 (defvar speedbar-indicator-separator " "
460   "String separating file text from indicator characters.")
461
462 (defcustom speedbar-vc-do-check t
463   "*Non-nil check all files in speedbar to see if they have been checked out.
464 Any file checked out is marked with `speedbar-vc-indicator'."
465   :group 'speedbar-vc
466   :type 'boolean)
467
468 (defvar speedbar-vc-indicator "*"
469   "Text used to mark files which are currently checked out.
470 Other version control systems can be added by examining the function
471 `speedbar-vc-directory-enable-hook' and `speedbar-vc-in-control-hook'.")
472
473 (defcustom speedbar-vc-directory-enable-hook nil
474   "*Return non-nil if the current directory should be checked for Version Control.
475 Functions in this hook must accept one parameter which is the directory
476 being checked."
477   :group 'speedbar-vc
478   :type 'hook)
479
480 (defcustom speedbar-vc-in-control-hook nil
481   "*Return non-nil if the specified file is under Version Control.
482 Functions in this hook must accept two parameters.  The DIRECTORY of the
483 current file, and the FILENAME of the file being checked."
484   :group 'speedbar-vc
485   :type 'hook)
486
487 (defvar speedbar-vc-to-do-point nil
488   "Local variable maintaining the current version control check position.")
489
490 (defcustom speedbar-obj-do-check t
491   "*Non-nil check all files in speedbar to see if they have an object file.
492 Any file checked out is marked with `speedbar-obj-indicator', and the
493 marking is based on `speedbar-obj-alist'"
494   :group 'speedbar-vc
495   :type 'boolean)
496
497 (defvar speedbar-obj-to-do-point nil
498   "Local variable maintaining the current version control check position.")
499
500 (defvar speedbar-obj-indicator '("#" . "!")
501   "Text used to mark files that have a corresponding hidden object file.
502 The car is for an up-to-date object.  The cdr is for an out of date object.
503 The expression `speedbar-obj-alist' defines who gets tagged.")
504
505 (defvar speedbar-obj-alist
506   '(("\\.\\([cpC]\\|cpp\\|cc\\|cxx\\)$" . ".o")
507     ("\\.el$" . ".elc")
508     ("\\.java$" . ".class")
509     ("\\.f\\(or\\|90\\|77\\)?$" . ".o")
510     ("\\.tex$" . ".dvi")
511     ("\\.texi$" . ".info"))
512   "Alist of file extensions, and their corresponding object file type.")
513
514 (defvar speedbar-ro-to-do-point nil
515   "Local variable maintaining the current read only check position.")
516
517 (defvar speedbar-object-read-only-indicator "%"
518   "Indicator to append onto a line if that item is Read Only.")
519
520 ;; Note: Look for addition place to add indicator lists that
521 ;; use skip-chars instead of a regular expression.
522 (defvar speedbar-indicator-regex
523   (concat (regexp-quote speedbar-indicator-separator)
524           "\\("
525           (regexp-quote speedbar-vc-indicator)
526           "\\|"
527           (regexp-quote (car speedbar-obj-indicator))
528           "\\|"
529           (regexp-quote (cdr speedbar-obj-indicator))
530           "\\|"
531           (regexp-quote speedbar-object-read-only-indicator)
532           "\\)*")
533   "Regular expression used when identifying files.
534 Permits stripping of indicator characters from a line.")
535
536 (defcustom speedbar-scanner-reset-hook nil
537   "*Hook called whenever generic scanners are reset.
538 Set this to implement your own scanning / rescan safe functions with
539 state data."
540   :group 'speedbar
541   :type 'hook)
542
543 (defvar speedbar-ignored-modes '(fundamental-mode)
544   "*List of major modes which speedbar will not switch directories for.")
545
546 (defun speedbar-extension-list-to-regex (extlist)
547   "Takes EXTLIST, a list of extensions and transforms it into regexp.
548 All the preceding `.' are stripped for an optimized expression starting
549 with `.' followed by extensions, followed by full-filenames."
550   (let ((regex1 nil) (regex2 nil))
551     (while extlist
552       (if (= (string-to-char (car extlist)) ?.)
553           (setq regex1 (concat regex1 (if regex1 "\\|" "")
554                                (substring (car extlist) 1)))
555         (setq regex2 (concat regex2 (if regex2 "\\|" "") (car extlist))))
556       (setq extlist (cdr extlist)))
557     ;; concat all the sub-exressions together, making sure all types
558     ;; of parts exist during concatination.
559     (concat "\\("
560             (if regex1 (concat "\\(\\.\\(" regex1 "\\)\\)") "")
561             (if (and regex1 regex2) "\\|" "")
562             (if regex2 (concat "\\(" regex2 "\\)") "")
563             "\\)$")))
564
565 (defvar speedbar-ignored-directory-regexp nil
566   "Regular expression matching directorys speedbar will not switch to.
567 Created from `speedbar-ignored-directory-expressions' with the function
568 `speedbar-extension-list-to-regex' (A misnamed function in this case.)
569 Use the function `speedbar-add-ignored-directory-regexp', or customize the
570 variable `speedbar-ignored-directory-expressions' to modify this variable.")
571
572 (defcustom speedbar-ignored-directory-expressions
573   '("[/\\]logs?[/\\]\\'")
574   "*List of regular expressions matching directories speedbar will ignore.
575 They should included directorys to directories which are notoriously very
576 large and take a long time to load in.  Use the function
577 `speedbar-add-ignored-directory-regexp' to add new items to this list after
578 speedbar is loaded.  You may place anything you like in this list
579 before speedbar has been loaded."
580   :group 'speedbar
581   :type '(repeat (regexp :tag "Directory Regexp"))
582   :set (lambda (sym val)
583          (setq speedbar-ignored-directory-expressions val
584                speedbar-ignored-directory-regexp
585                (speedbar-extension-list-to-regex val))))
586
587 (defcustom speedbar-directory-unshown-regexp "^\\(CVS\\|RCS\\|SCCS\\|\\..*\\)\\'"
588   "*Regular expression matching directories not to show in speedbar.
589 They should include commonly existing directories which are not
590 useful, such as version control."
591   :group 'speedbar
592   :type 'string)
593
594 (defvar speedbar-file-unshown-regexp
595   (let ((nstr "") (noext completion-ignored-extensions))
596     (while noext
597       (setq nstr (concat nstr (regexp-quote (car noext)) "\\'"
598                          (if (cdr noext) "\\|" ""))
599             noext (cdr noext)))
600     ;;               backup      refdir      lockfile
601     (concat nstr "\\|#[^#]+#$\\|\\.\\.?\\'\\|\\.#"))
602   "*Regexp matching files we don't want displayed in a speedbar buffer.
603 It is generated from the variable `completion-ignored-extensions'")
604
605 ;; this is dangerous to customize, because the defaults will probably
606 ;; change in the future.
607 (defcustom speedbar-supported-extension-expressions
608   (append '(".[ch]\\(\\+\\+\\|pp\\|c\\|h\\|xx\\)?" ".tex\\(i\\(nfo\\)?\\)?"
609             ".el" ".emacs" ".l" ".lsp" ".p" ".java" ".f\\(90\\|77\\|or\\)?")
610           (if speedbar-use-imenu-flag
611               '(".ada" ".p[lm]" ".tcl" ".m" ".scm" ".pm" ".py" ".g"
612                 ;; html is not supported by default, but an imenu tags package
613                 ;; is available.  Also, html files are nice to be able to see.
614                 ".s?html"
615                 ".ma?k" "[Mm]akefile\\(\\.in\\)?")))
616   "*List of regular expressions which will match files supported by tagging.
617 Do not prefix the `.' char with a double \\ to quote it, as the period
618 will be stripped by a simplified optimizer when compiled into a
619 singular expression.  This variable will be turned into
620 `speedbar-file-regexp' for use with speedbar.  You should use the
621 function `speedbar-add-supported-extension' to add a new extension at
622 runtime, or use the configuration dialog to set it in your .emacs
623 file.
624 If you add an extension to this list, and it does not appear, you may
625 need to also modify `completion-ignored-extension' which will also help
626 file completion."
627   :group 'speedbar
628   :type '(repeat (regexp :tag "Extension Regexp"))
629   :set (lambda (sym val)
630          (setq speedbar-supported-extension-expressions val
631                speedbar-file-regexp (speedbar-extension-list-to-regex val)))
632   )
633
634 (defvar speedbar-file-regexp
635   (speedbar-extension-list-to-regex speedbar-supported-extension-expressions)
636   "Regular expression matching files we know how to expand.
637 Created from `speedbar-supported-extension-expressions' with the
638 function `speedbar-extension-list-to-regex'")
639
640 (defun speedbar-add-supported-extension (extension)
641   "Add EXTENSION as a new supported extension for speedbar tagging.
642 This should start with a `.' if it is not a complete file name, and
643 the dot should NOT be quoted in with \\.  Other regular expression
644 matchers are allowed however.  EXTENSION may be a single string or a
645 list of strings."
646   (interactive "sExtension: ")
647   (if (not (listp extension)) (setq extension (list extension)))
648   (while extension
649     (if (member (car extension) speedbar-supported-extension-expressions)
650         nil
651       (setq speedbar-supported-extension-expressions
652             (cons (car extension) speedbar-supported-extension-expressions)))
653     (setq extension (cdr extension)))
654   (setq speedbar-file-regexp (speedbar-extension-list-to-regex
655                               speedbar-supported-extension-expressions)))
656
657 (defun speedbar-add-ignored-directory-regexp (directory-expression)
658   "Add DIRECTORY-EXPRESSION as a new ignored directory for speedbar tracking.
659 This function will modify `speedbar-ignored-directory-regexp' and add
660 DIRECTORY-EXPRESSION to `speedbar-ignored-directory-expressions'."
661   (interactive "sDirectory regex: ")
662   (if (not (listp directory-expression))
663       (setq directory-expression (list directory-expression)))
664   (while directory-expression
665     (if (member (car directory-expression) speedbar-ignored-directory-expressions)
666         nil
667       (setq speedbar-ignored-directory-expressions
668             (cons (car directory-expression) speedbar-ignored-directory-expressions)))
669     (setq directory-expression (cdr directory-expression)))
670   (setq speedbar-ignored-directory-regexp (speedbar-extension-list-to-regex
671                                       speedbar-ignored-directory-expressions)))
672
673 ;; If we don't have custom, then we set it here by hand.
674 (if (not (fboundp 'custom-declare-variable))
675     (setq speedbar-file-regexp (speedbar-extension-list-to-regex
676                                 speedbar-supported-extension-expressions)
677           speedbar-ignored-directory-regexp (speedbar-extension-list-to-regex
678                                         speedbar-ignored-directory-expressions)))
679
680 (defvar speedbar-update-flag dframe-have-timer-flag
681   "*Non-nil means to automatically update the display.
682 When this is nil then speedbar will not follow the attached frame's directory.
683 When speedbar is active, use:
684
685 \\<speedbar-key-map> `\\[speedbar-toggle-updates]'
686
687 to toggle this value.")
688
689 (defvar speedbar-update-flag-disable nil
690   "Permanently disable changing of the update flag.")
691
692 (defvar speedbar-syntax-table nil
693   "Syntax-table used on the speedbar.")
694
695 (if speedbar-syntax-table
696     nil
697   (setq speedbar-syntax-table (make-syntax-table))
698   ;; turn off paren matching around here.
699   (modify-syntax-entry ?\' " " speedbar-syntax-table)
700   (modify-syntax-entry ?\" " " speedbar-syntax-table)
701   (modify-syntax-entry ?( " " speedbar-syntax-table)
702   (modify-syntax-entry ?) " " speedbar-syntax-table)
703   (modify-syntax-entry ?{ " " speedbar-syntax-table)
704   (modify-syntax-entry ?} " " speedbar-syntax-table)
705   (modify-syntax-entry ?[ " " speedbar-syntax-table)
706   (modify-syntax-entry ?] " " speedbar-syntax-table))
707
708 (defvar speedbar-key-map nil
709   "Keymap used in speedbar buffer.")
710
711 (if speedbar-key-map
712     nil
713   (setq speedbar-key-map (make-keymap))
714   (suppress-keymap speedbar-key-map t)
715
716   ;; control
717   (define-key speedbar-key-map "t" 'speedbar-toggle-updates)
718   (define-key speedbar-key-map "g" 'speedbar-refresh)
719
720   ;; navigation
721   (define-key speedbar-key-map "n" 'speedbar-next)
722   (define-key speedbar-key-map "p" 'speedbar-prev)
723   (define-key speedbar-key-map "\M-n" 'speedbar-restricted-next)
724   (define-key speedbar-key-map "\M-p" 'speedbar-restricted-prev)
725   (define-key speedbar-key-map "\C-\M-n" 'speedbar-forward-list)
726   (define-key speedbar-key-map "\C-\M-p" 'speedbar-backward-list)
727 ;; These commands never seemed useful.
728 ;;  (define-key speedbar-key-map " " 'speedbar-scroll-up)
729 ;;  (define-key speedbar-key-map [delete] 'speedbar-scroll-down)
730
731   ;; Short cuts I happen to find useful
732   (define-key speedbar-key-map "r"
733     (lambda () (interactive)
734       (speedbar-change-initial-expansion-list
735        speedbar-previously-used-expansion-list-name)))
736   (define-key speedbar-key-map "b"
737     (lambda () (interactive)
738       (speedbar-change-initial-expansion-list "quick buffers")))
739   (define-key speedbar-key-map "f"
740     (lambda () (interactive)
741       (speedbar-change-initial-expansion-list "files")))
742
743   (dframe-update-keymap speedbar-key-map)
744 )
745
746 (defun speedbar-make-specialized-keymap ()
747   "Create a keymap for use with a speedbar major or minor display mode.
748 This basically creates a sparse keymap, and makes it's parent be
749 `speedbar-key-map'."
750   (let ((k (make-sparse-keymap)))
751     (set-keymap-parent k speedbar-key-map)
752     k))
753
754 (defvar speedbar-file-key-map nil
755   "Keymap used in speedbar buffer while files are displayed.")
756
757 (if speedbar-file-key-map
758     nil
759   (setq speedbar-file-key-map (speedbar-make-specialized-keymap))
760
761   ;; Basic tree features
762   (define-key speedbar-file-key-map "e" 'speedbar-edit-line)
763   (define-key speedbar-file-key-map "\C-m" 'speedbar-edit-line)
764   (define-key speedbar-file-key-map "+" 'speedbar-expand-line)
765   (define-key speedbar-file-key-map "=" 'speedbar-expand-line)
766   (define-key speedbar-file-key-map "-" 'speedbar-contract-line)
767
768   (define-key speedbar-file-key-map "[" 'speedbar-expand-line-descendants)
769   (define-key speedbar-file-key-map "]" 'speedbar-close-line-descendants)
770
771   (define-key speedbar-file-key-map " " 'speedbar-toggle-line-expansion)
772
773   ;; file based commands
774   (define-key speedbar-file-key-map "U" 'speedbar-up-directory)
775   (define-key speedbar-file-key-map "I" 'speedbar-item-info)
776   (define-key speedbar-file-key-map "B" 'speedbar-item-byte-compile)
777   (define-key speedbar-file-key-map "L" 'speedbar-item-load)
778   (define-key speedbar-file-key-map "C" 'speedbar-item-copy)
779   (define-key speedbar-file-key-map "D" 'speedbar-item-delete)
780   (define-key speedbar-file-key-map "O" 'speedbar-item-object-delete)
781   (define-key speedbar-file-key-map "R" 'speedbar-item-rename)
782   (define-key speedbar-file-key-map "M" 'speedbar-create-directory)
783   )
784
785 (defvar speedbar-easymenu-definition-base
786   (append
787    '("Speedbar"
788      ["Update" speedbar-refresh t]
789      ["Auto Update" speedbar-toggle-updates
790       :active (not speedbar-update-flag-disable)
791       :style toggle :selected speedbar-update-flag])
792    (if (and (or (fboundp 'defimage)
793                 (fboundp 'make-image-specifier))
794             (if (fboundp 'display-graphic-p)
795                 (display-graphic-p)
796               window-system))
797        (list
798         ["Use Images" speedbar-toggle-images
799          :style toggle :selected speedbar-use-images]))
800    )
801   "Base part of the speedbar menu.")
802
803 (defvar speedbar-easymenu-definition-special
804   '(["Edit Item On Line" speedbar-edit-line t]
805     ["Show All Files" speedbar-toggle-show-all-files
806      :style toggle :selected speedbar-show-unknown-files]
807     ["Expand File Tags" speedbar-expand-line
808      (save-excursion (beginning-of-line)
809                      (looking-at "[0-9]+: *.\\+. "))]
810     ["Flush Cache & Expand" speedbar-flush-expand-line
811      (save-excursion (beginning-of-line)
812                      (looking-at "[0-9]+: *.\\+. "))]
813     ["Expand All Descendants" speedbar-expand-line-descendants
814      (save-excursion (beginning-of-line)
815                      (looking-at "[0-9]+: *.\\+. ")) ]
816     ["Contract File Tags" speedbar-contract-line
817      (save-excursion (beginning-of-line)
818                      (looking-at "[0-9]+: *.-. "))]
819 ;    ["Sort Tags" speedbar-toggle-sorting
820 ;     :style toggle :selected speedbar-sort-tags]
821     "----"
822     ["File/Tag Information" speedbar-item-info t]
823     ["Load Lisp File" speedbar-item-load
824      (save-excursion
825        (beginning-of-line)
826        (looking-at "[0-9]+: *\\[[+-]\\] .+\\(\\.el\\)\\( \\|$\\)"))]
827     ["Byte Compile File" speedbar-item-byte-compile
828      (save-excursion
829        (beginning-of-line)
830        (looking-at "[0-9]+: *\\[[+-]\\] .+\\(\\.el\\)\\( \\|$\\)"))]
831     ["Copy File" speedbar-item-copy
832      (save-excursion (beginning-of-line) (looking-at "[0-9]+: *\\["))]
833     ["Rename File" speedbar-item-rename
834      (save-excursion (beginning-of-line) (looking-at "[0-9]+: *[[<]"))]
835     ["Create Directory" speedbar-create-directory
836      (save-excursion (beginning-of-line) (looking-at "[0-9]+: *[[<]"))]
837     ["Delete File" speedbar-item-delete
838      (save-excursion (beginning-of-line) (looking-at "[0-9]+: *[[<]"))]
839     ["Delete Object" speedbar-item-object-delete
840      (save-excursion (beginning-of-line)
841                      (looking-at "[0-9]+: *\\[[+-]\\] [^ \n]+ \\*?[!#]$"))]
842     )
843   "Additional menu items while in file-mode.")
844  
845 (defvar speedbar-easymenu-definition-trailer
846   (append
847    (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
848        (list ["Customize..." speedbar-customize t]))
849    (list
850     ["Detach" speedbar-detach (and speedbar-frame
851                                     (eq (selected-frame) speedbar-frame)) ]
852     ["Close" dframe-close-frame t]
853     ["Quit" delete-frame t] ))
854   "Menu items appearing at the end of the speedbar menu.")
855
856 (defvar speedbar-desired-buffer nil
857   "Non-nil when speedbar is showing buttons specific to a special mode.
858 In this case it is the originating buffer.")
859 (defvar speedbar-buffer nil
860   "The buffer displaying the speedbar.")
861 (defvar speedbar-frame nil
862   "The frame displaying speedbar.")
863 (defvar speedbar-cached-frame nil
864   "The frame that was last created, then removed from the display.")
865 (defvar speedbar-full-text-cache nil
866   "The last open directory is saved in its entirety for ultra-fast switching.")
867
868 (defvar speedbar-last-selected-file nil
869   "The last file which was selected in speedbar buffer.")
870
871 (defvar speedbar-shown-directories nil
872   "Maintain list of directories simultaneously open in the current speedbar.")
873
874 (defvar speedbar-directory-contents-alist nil
875   "An association list of directories and their contents.
876 Each sublist was returned by `speedbar-file-lists'.  This list is
877 maintained to speed up the refresh rate when switching between
878 directories.")
879
880 (defvar speedbar-power-click nil
881   "Never set this by hand.  Value is t when S-mouse activity occurs.")
882
883 \f
884 ;;; Compatibility
885 ;;
886 (if (featurep 'xemacs)
887     (progn
888       (defalias 'speedbar-make-overlay 'make-extent)
889       (defalias 'speedbar-overlay-put 'set-extent-property)
890       (defalias 'speedbar-delete-overlay 'delete-extent)
891       (defalias 'speedbar-mode-line-update 'redraw-modeline))
892   (defalias 'speedbar-make-overlay 'make-overlay)
893   (defalias 'speedbar-overlay-put 'overlay-put)
894   (defalias 'speedbar-delete-overlay 'delete-overlay)
895   (defalias 'speedbar-mode-line-update 'force-mode-line-update))
896 \f
897 ;;; Mode definitions/ user commands
898 ;;
899
900 ;;;###autoload
901 (defalias 'speedbar 'speedbar-frame-mode)
902 ;;;###autoload
903 (defun speedbar-frame-mode (&optional arg)
904   "Enable or disable speedbar.  Positive ARG means turn on, negative turn off.
905 nil means toggle.  Once the speedbar frame is activated, a buffer in
906 `speedbar-mode' will be displayed.  Currently, only one speedbar is
907 supported at a time.
908 `speedbar-before-popup-hook' is called before popping up the speedbar frame.
909 `speedbar-before-delete-hook' is called before the frame is deleted."
910   (interactive "P")
911   ;; Get the buffer to play with
912   (if (not (buffer-live-p speedbar-buffer))
913       (save-excursion
914         (setq speedbar-buffer (get-buffer-create " SPEEDBAR"))
915         (set-buffer speedbar-buffer)
916         (speedbar-mode)))
917   ;; Do the frame thing
918   (dframe-frame-mode arg
919                      'speedbar-frame
920                      'speedbar-cached-frame
921                      'speedbar-buffer
922                      "Speedbar"
923                      #'speedbar-frame-mode
924                      (if dframe-xemacsp
925                          (append speedbar-frame-plist
926                                  ;; This is a hack to get speedbar to iconfiy
927                                  ;; with the selected frame.
928                                  (list 'parent (selected-frame)))
929                        speedbar-frame-parameters)
930                      speedbar-before-delete-hook
931                      speedbar-before-popup-hook
932                      speedbar-after-create-hook)
933   ;; Start up the timer
934   (if (not speedbar-frame)
935       (speedbar-set-timer nil)
936     (speedbar-reconfigure-keymaps)
937     (speedbar-update-contents)
938     (speedbar-set-timer dframe-update-speed)
939     )
940   ;; Frame modifications
941   (set (make-local-variable 'dframe-delete-frame-function)
942        'speedbar-handle-delete-frame)
943   ;; hscroll
944   (set (make-local-variable 'automatic-hscrolling) nil) ; Emacs 21
945   ;; reset the selection variable
946   (setq speedbar-last-selected-file nil))
947
948 (defun speedbar-frame-reposition-smartly ()
949   "Reposition the speedbar frame to be next to the attached frame."
950   (cond ((and dframe-xemacsp
951               (or (member 'left speedbar-frame-plist)
952                   (member 'top speedbar-frame-plist)))
953          (dframe-reposition-frame
954           speedbar-frame
955           (dframe-attached-frame speedbar-frame)
956           (cons (car (cdr (member 'left speedbar-frame-plist)))
957                 (car (cdr (member 'top speedbar-frame-plist)))))
958          )
959         ((and (not dframe-xemacsp)
960               (or (assoc 'left speedbar-frame-parameters)
961                   (assoc 'top speedbar-frame-parameters)))
962          ;; if left/top were specified in the parameters, pass them
963          ;; down to the reposition function
964          (dframe-reposition-frame
965           speedbar-frame
966           (dframe-attached-frame speedbar-frame)
967           (cons (cdr (assoc 'left speedbar-frame-parameters))
968                 (cdr (assoc 'top  speedbar-frame-parameters))))
969          )
970         (t
971          (dframe-reposition-frame speedbar-frame
972                                   (dframe-attached-frame speedbar-frame)
973                                   speedbar-default-position))))
974
975 (defun speedbar-detach ()
976   "Detach the current Speedbar from auto-updating.
977 Doing this allows the creation of a second speedbar."
978   (interactive)
979   (let ((buffer speedbar-buffer))
980     (dframe-detach 'speedbar-frame 'speedbar-cached-frame 'speedbar-buffer)
981     (save-excursion
982       (set-buffer buffer)
983       ;; Permanently disable auto-updating in this speedbar buffer.
984       (set (make-local-variable 'speedbar-update-flag) nil)
985       (set (make-local-variable 'speedbar-update-flag-disable) t)
986       ;; Make local copies of all the different variables to prevent
987       ;; funny stuff later...
988       )))
989
990 (defsubst speedbar-current-frame ()
991   "Return the frame to use for speedbar based on current context."
992   (dframe-current-frame 'speedbar-frame 'speedbar-mode))
993
994 (defun speedbar-handle-delete-frame (e)
995   "Handle a delete frame event E.
996 If the deleted frame is the frame SPEEDBAR is attached to,
997 we need to delete speedbar also."
998   (let ((frame-to-be-deleted (car (car (cdr e)))))
999     (if (eq frame-to-be-deleted dframe-attached-frame)
1000         (delete-frame speedbar-frame)))
1001   )
1002
1003 ;;;###autoload
1004 (defun speedbar-get-focus ()
1005   "Change frame focus to or from the speedbar frame.
1006 If the selected frame is not speedbar, then speedbar frame is
1007 selected.  If the speedbar frame is active, then select the attached frame."
1008   (interactive)
1009   (speedbar-reset-scanners)
1010   (dframe-get-focus 'speedbar-frame 'speedbar-frame-mode
1011                     (lambda () (let ((speedbar-update-flag t))
1012                                  (speedbar-timer-fn)))))
1013
1014 (defmacro speedbar-frame-width ()
1015   "Return the width of the speedbar frame in characters.
1016 nil if it doesn't exist."
1017   '(window-width (get-buffer-window speedbar-buffer)))
1018
1019 (defun speedbar-mode ()
1020   "Major mode for managing a display of directories and tags.
1021 \\<speedbar-key-map>
1022 The first line represents the default directory of the speedbar frame.
1023 Each directory segment is a button which jumps speedbar's default
1024 directory to that directory.  Buttons are activated by clicking `\\[speedbar-click]'.
1025 In some situations using `\\[dframe-power-click]' is a `power click' which will
1026 rescan cached items, or pop up new frames.
1027
1028 Each line starting with <+> represents a directory.  Click on the <+>
1029 to insert the directory listing into the current tree.  Click on the
1030 <-> to retract that list.  Click on the directory name to go to that
1031 directory as the default.
1032
1033 Each line starting with [+] is a file.  If the variable
1034 `speedbar-show-unknown-files' is t, the lines starting with [?] are
1035 files which don't have imenu support, but are not expressly ignored.
1036 Files are completely ignored if they match `speedbar-file-unshown-regexp'
1037 which is generated from `completion-ignored-extensions'.
1038
1039 Files with a `*' character after their name are files checked out of a
1040 version control system.  (Currently only RCS is supported.)  New
1041 version control systems can be added by examining the documentation
1042 for `speedbar-this-file-in-vc' and `speedbar-vc-check-dir-p'.
1043
1044 Files with a `#' or `!' character after them are source files that
1045 have an object file associated with them.  The `!' indicates that the
1046 files is out of date.  You can control what source/object associations
1047 exist through the variable `speedbar-obj-alist'.
1048
1049 Click on the [+] to display a list of tags from that file.  Click on
1050 the [-] to retract the list.  Click on the file name to edit the file
1051 in the attached frame.
1052
1053 If you open tags, you might find a node starting with {+}, which is a
1054 category of tags.  Click the {+} to expand the category.  Jump-able
1055 tags start with >.  Click the name of the tag to go to that position
1056 in the selected file.
1057
1058 \\{speedbar-key-map}"
1059   ;; NOT interactive
1060   (save-excursion
1061     (kill-all-local-variables)
1062     (setq major-mode 'speedbar-mode)
1063     (setq mode-name "Speedbar")
1064     (set-syntax-table speedbar-syntax-table)
1065     (setq font-lock-keywords nil) ;; no font-locking please
1066     (setq truncate-lines t)
1067     (make-local-variable 'frame-title-format)
1068     (setq frame-title-format (concat "Speedbar " speedbar-version))
1069     (setq case-fold-search nil)
1070     (toggle-read-only 1)
1071     (speedbar-set-mode-line-format)
1072     ;; Add in our dframe hooks.
1073     (if speedbar-track-mouse-flag
1074         (setq dframe-track-mouse-function #'speedbar-track-mouse))
1075     (setq dframe-help-echo-function #'speedbar-item-info
1076           dframe-mouse-click-function #'speedbar-click
1077           dframe-mouse-position-function #'speedbar-position-cursor-on-line)
1078     (run-hooks 'speedbar-mode-hook))
1079   speedbar-buffer)
1080
1081 (defmacro speedbar-message (fmt &rest args)
1082   "Like message, but for use in the speedbar frame.
1083 Argument FMT is the format string, and ARGS are the arguments for message."
1084   `(dframe-message ,fmt ,@args))
1085
1086 (defsubst speedbar-y-or-n-p (prompt &optional deleting)
1087   "Like `y-or-n-p', but for use in the speedbar frame.
1088 Argument PROMPT is the prompt to use.
1089 Optional argument DELETING means this is a query that will delete something.
1090 The variable `speedbar-query-confirmation-method' can cause this to
1091 return true without a query."
1092   (or (and (not deleting)
1093            (eq speedbar-query-confirmation-method 'none-but-delete))
1094       (dframe-y-or-n-p prompt)))
1095
1096 (defsubst speedbar-select-attached-frame ()
1097   "Select the frame attached to this speedbar."
1098   (dframe-select-attached-frame (speedbar-current-frame)))
1099
1100 ;; Backwards compatibility
1101 (defalias 'speedbar-with-attached-buffer 'dframe-with-attached-buffer)
1102 (defalias 'speedbar-maybee-jump-to-attached-frame 'dframe-maybee-jump-to-attached-frame)
1103  
1104 (defun speedbar-set-mode-line-format ()
1105   "Set the format of the mode line based on the current speedbar environment.
1106 This gives visual indications of what is up.  It EXPECTS the speedbar
1107 frame and window to be the currently active frame and window."
1108   (if (and (frame-live-p (speedbar-current-frame))
1109            (or (not dframe-xemacsp)
1110                (specifier-instance has-modeline-p))
1111            speedbar-buffer)      (save-excursion
1112         (set-buffer speedbar-buffer)
1113         (let* ((w (or (speedbar-frame-width) 20))
1114                (p1 "<<")
1115                (p5 ">>")
1116                (p3 (if speedbar-update-flag "#" "!"))
1117                (p35 (capitalize speedbar-initial-expansion-list-name))
1118                (blank (- w (length p1) (length p3) (length p5) (length p35)
1119                          (if line-number-mode 5 1)))
1120                (p2 (if (> blank 0)
1121                        (make-string (/ blank 2) ? )
1122                      ""))
1123                (p4 (if (> blank 0)
1124                        (make-string (+ (/ blank 2) (% blank 2)) ? )
1125                      ""))
1126                (tf
1127                 (if line-number-mode
1128                     (list (concat p1 p2 p3 " " p35) '(line-number-mode " %3l")
1129                           (concat p4 p5))
1130                   (list (concat p1 p2 p3 p4 p5)))))
1131           (if (not (equal mode-line-format tf))
1132               (progn
1133                 (setq mode-line-format tf)
1134                 (speedbar-mode-line-update)))))))
1135
1136 (defvar speedbar-previous-menu nil
1137   "The menu before the last `speedbar-reconfigure-keymaps' was called.")
1138
1139 (defun speedbar-reconfigure-keymaps ()
1140   "Reconfigure the menu-bar in a speedbar frame.
1141 Different menu items are displayed depending on the current display mode
1142 and the existence of packages."
1143   (let ((md (append
1144              speedbar-easymenu-definition-base
1145              (if speedbar-shown-directories
1146                  ;; file display mode version
1147                  (speedbar-initial-menu)
1148                (save-excursion
1149                  (dframe-select-attached-frame speedbar-frame)
1150                  (if (local-variable-p
1151                       'speedbar-easymenu-definition-special
1152                       (current-buffer))
1153                      ;; If bound locally, we can use it
1154                      speedbar-easymenu-definition-special)))
1155              ;; Dynamic menu stuff
1156              '("-")
1157             (list (cons "Displays"
1158                         (let ((displays nil)
1159                               (alist speedbar-initial-expansion-mode-alist))
1160                           (while alist
1161                             (setq displays
1162                                   (cons
1163                                    (vector
1164                                     (capitalize (car (car alist)))
1165                                     (list
1166                                      'speedbar-change-initial-expansion-list
1167                                      (car (car alist)))
1168                                     :style 'radio
1169                                     :selected
1170                                     `(string= ,(car (car alist))
1171                                          speedbar-initial-expansion-list-name)
1172                                     )
1173                                    displays))
1174                             (setq alist (cdr alist)))
1175                           displays)))
1176             ;; The trailer
1177             speedbar-easymenu-definition-trailer))
1178         (localmap (save-excursion
1179                     (let ((cf (selected-frame)))
1180                       (prog2
1181                           (dframe-select-attached-frame speedbar-frame)
1182                           (if (local-variable-p
1183                                'speedbar-special-mode-key-map
1184                                (current-buffer))
1185                               speedbar-special-mode-key-map)
1186                         (select-frame cf))))))
1187     (save-excursion
1188       (set-buffer speedbar-buffer)
1189       (use-local-map (or localmap
1190                          (speedbar-initial-keymap)
1191                          ;; This creates a small keymap we can glom the
1192                          ;; menu adjustments into.
1193                          (speedbar-make-specialized-keymap)))
1194       ;; Delete the old menu if applicable.
1195       (if speedbar-previous-menu (easy-menu-remove speedbar-previous-menu))
1196       (setq speedbar-previous-menu md)
1197       ;; Now add the new menu
1198       (if (not dframe-xemacsp)
1199           (easy-menu-define speedbar-menu-map (current-local-map)
1200                             "Speedbar menu" md)
1201         (easy-menu-add md (current-local-map))
1202         (if (featurep 'menubars) (set-buffer-menubar (list md)))))
1203     (run-hooks 'speedbar-reconfigure-keymaps-hook)))
1204
1205 \f
1206 ;;; User Input stuff
1207 ;;
1208 (defun speedbar-customize ()
1209   "Customize speedbar using the Custom package."
1210   (interactive)
1211   (let ((sf (selected-frame)))
1212     (dframe-select-attached-frame speedbar-frame)
1213     (customize-group 'speedbar)
1214     (select-frame sf))
1215   (dframe-maybee-jump-to-attached-frame))
1216
1217 (defun speedbar-track-mouse (event)
1218   "For motion EVENT, display info about the current line."
1219   (if (not speedbar-track-mouse-flag)
1220       nil
1221     (save-excursion
1222       (save-window-excursion
1223         (condition-case nil
1224             (progn
1225               (mouse-set-point event)
1226               (if (eq major-mode 'speedbar-mode)
1227                   ;; XEmacs may let us get in here in other mode buffers.
1228                   (speedbar-item-info)))
1229           (t (speedbar-message nil)))))))
1230
1231 (defun speedbar-show-info-under-mouse ()
1232   "Call the info function for the line under the mouse.
1233 Optional EVENT is currently not used."
1234   (let ((pos (mouse-position))) ; we ignore event until I use it later.
1235     (if (equal (car pos) speedbar-frame)
1236         (save-excursion
1237           (save-window-excursion
1238             (apply 'set-mouse-position pos)
1239             (speedbar-item-info))))))
1240
1241 (defun speedbar-next (arg)
1242   "Move to the next ARGth line in a speedbar buffer."
1243   (interactive "p")
1244   (forward-line (or arg 1))
1245   (speedbar-item-info)
1246   (speedbar-position-cursor-on-line))
1247
1248 (defun speedbar-prev (arg)
1249   "Move to the previous ARGth line in a speedbar buffer."
1250   (interactive "p")
1251   (speedbar-next (if arg (- arg) -1)))
1252
1253 (defun speedbar-restricted-move (arg)
1254   "Move to the next ARGth line in a speedbar buffer at the same depth.
1255 This means that movement is restricted to a subnode, and that siblings
1256 of intermediate nodes are skipped."
1257   (if (not (numberp arg)) (signal 'wrong-type-argument (list arg 'numberp)))
1258   ;; First find the extent for which we are allowed to move.
1259   (let ((depth (save-excursion (beginning-of-line)
1260                                (if (looking-at "[0-9]+:")
1261                                    (string-to-int (match-string 0))
1262                                  0)))
1263         (crement (if (< arg 0) 1 -1))   ; decrement or increment
1264         (lastmatch (point)))
1265     (while (/= arg 0)
1266       (forward-line (- crement))
1267       (let ((subdepth (save-excursion (beginning-of-line)
1268                                       (if (looking-at "[0-9]+:")
1269                                           (string-to-int (match-string 0))
1270                                         0))))
1271         (cond ((or (< subdepth depth)
1272                    (progn (end-of-line) (eobp))
1273                    (progn (beginning-of-line) (bobp)))
1274                ;; We have reached the end of this block.
1275                (goto-char lastmatch)
1276                (setq arg 0)
1277                (error "End of sub-list"))
1278               ((= subdepth depth)
1279                (setq lastmatch (point)
1280                      arg (+ arg crement))))))
1281     (speedbar-position-cursor-on-line)))
1282
1283 (defun speedbar-restricted-next (arg)
1284   "Move to the next ARGth line in a speedbar buffer at the same depth.
1285 This means that movement is restricted to a subnode, and that siblings
1286 of intermediate nodes are skipped."
1287   (interactive "p")
1288   (speedbar-restricted-move (or arg 1))
1289   (speedbar-item-info))
1290
1291 (defun speedbar-restricted-prev (arg)
1292   "Move to the previous ARGth line in a speedbar buffer at the same depth.
1293 This means that movement is restricted to a subnode, and that siblings
1294 of intermediate nodes are skipped."
1295   (interactive "p")
1296   (speedbar-restricted-move (if arg (- arg) -1))
1297   (speedbar-item-info))
1298
1299 (defun speedbar-navigate-list (arg)
1300   "Move across ARG groups of similarly typed items in speedbar.
1301 Stop on the first line of the next type of item, or on the last or first item
1302 if we reach a buffer boundary."
1303   (interactive "p")
1304   (beginning-of-line)
1305   (if (looking-at "[0-9]+: *[[<{][-+?][]>}] ")
1306       (let ((str (regexp-quote (match-string 0))))
1307         (while (looking-at str)
1308           (speedbar-restricted-move arg)
1309           (beginning-of-line))))
1310   (speedbar-position-cursor-on-line))
1311
1312 (defun speedbar-forward-list ()
1313   "Move forward over the current list.
1314 A LIST in speedbar is a group of similarly typed items, such as directories,
1315 files, or the directory button."
1316   (interactive)
1317   (speedbar-navigate-list 1)
1318   (speedbar-item-info))
1319
1320 (defun speedbar-backward-list ()
1321   "Move backward over the current list.
1322 A LIST in speedbar is a group of similarly typed items, such as directories,
1323 files, or the directory button."
1324   (interactive)
1325   (speedbar-navigate-list -1)
1326   (speedbar-item-info))
1327
1328 (defun speedbar-scroll-up (&optional arg)
1329   "Page down one screen-full of the speedbar, or ARG lines."
1330   (interactive "P")
1331   (scroll-up arg)
1332   (speedbar-position-cursor-on-line))
1333
1334 (defun speedbar-scroll-down (&optional arg)
1335   "Page up one screen-full of the speedbar, or ARG lines."
1336   (interactive "P")
1337   (scroll-down arg)
1338   (speedbar-position-cursor-on-line))
1339
1340 (defun speedbar-up-directory ()
1341   "Keyboard accelerator for moving the default directory up one.
1342 Assumes that the current buffer is the speedbar buffer."
1343   (interactive)
1344   (setq default-directory (expand-file-name (concat default-directory "../")))
1345   (speedbar-update-contents))
1346 \f
1347 ;;; Speedbar file activity (aka creeping featurism)
1348 ;;
1349 (defun speedbar-refresh (&optional arg)
1350   "Refresh the current speedbar display, disposing of any cached data.
1351 Argument ARG represents to force a refresh past any caches that may exist."
1352   (interactive "P")
1353   (let ((dl speedbar-shown-directories)
1354         (dframe-power-click arg)
1355         deactivate-mark)
1356     ;; We need to hack something so this works in detached frames.
1357     (while dl
1358       (adelete 'speedbar-directory-contents-alist (car dl))
1359       (setq dl (cdr dl)))
1360     (if (<= 1 speedbar-verbosity-level)
1361         (speedbar-message "Refreshing speedbar..."))
1362     (speedbar-update-contents)
1363     (speedbar-stealthy-updates)
1364     ;; Reset the timer in case it got really hosed for some reason...
1365     (speedbar-set-timer dframe-update-speed)
1366     (if (<= 1 speedbar-verbosity-level)
1367         (speedbar-message "Refreshing speedbar...done"))))
1368
1369 (defun speedbar-item-load ()
1370   "Load the item under the cursor or mouse if it is a Lisp file."
1371   (interactive)
1372   (let ((f (speedbar-line-file)))
1373     (if (and (file-exists-p f) (string-match "\\.el\\'" f))
1374         (if (and (file-exists-p (concat f "c"))
1375                  (speedbar-y-or-n-p (format "Load %sc? " f)))
1376             ;; If the compiled version exists, load that instead...
1377             (load-file (concat f "c"))
1378           (load-file f))
1379       (error "Not a loadable file"))))
1380
1381 (defun speedbar-item-byte-compile ()
1382   "Byte compile the item under the cursor or mouse if it is a Lisp file."
1383   (interactive)
1384   (let ((f (speedbar-line-file))
1385         (sf (selected-frame)))
1386     (if (and (file-exists-p f) (string-match "\\.el\\'" f))
1387         (progn
1388           (dframe-select-attached-frame speedbar-frame)
1389           (byte-compile-file f nil)
1390           (select-frame sf)
1391           (speedbar-reset-scanners)))
1392     ))
1393
1394 (defun speedbar-mouse-item-info (event)
1395   "Provide information about what the user clicked on.
1396 This should be bound to a mouse EVENT."
1397   (interactive "e")
1398   (mouse-set-point event)
1399   (speedbar-item-info))
1400
1401 (defun speedbar-generic-item-info ()
1402   "Attempt to derive, and then display information about this line item.
1403 File style information is displayed with `speedbar-item-info'."
1404   (save-excursion
1405     (beginning-of-line)
1406     ;; Skip invisible number info.
1407     (if (looking-at "\\([0-9]+\\):") (goto-char (match-end 0)))
1408     ;; Skip items in "folder" type text characters.
1409     (if (looking-at "\\s-*[[<({].[]>)}] ") (goto-char (match-end 0)))
1410     ;; Get the text
1411     (speedbar-message "Text: %s" (buffer-substring-no-properties
1412                                   (point) (progn (end-of-line) (point))))))
1413
1414 (defun speedbar-item-info ()
1415   "Display info in the mini-buffer about the button the mouse is over.
1416 This function can be replaced in `speedbar-mode-functions-list' as
1417 `speedbar-item-info'."
1418   (interactive)
1419   (let (message-log-max)
1420     (funcall (or (speedbar-fetch-replacement-function 'speedbar-item-info)
1421                  'speedbar-generic-item-info))))
1422
1423 (defun speedbar-item-info-file-helper (&optional filename)
1424   "Display info about a file that is on the current line.
1425 nil if not applicable.  If FILENAME, then use that instead of reading
1426 it from the speedbar buffer."
1427   (let* ((item (or filename (speedbar-line-file)))
1428          (attr (if item (file-attributes item) nil)))
1429     (if (and item attr) (speedbar-message "%s %-6d %s" (nth 8 attr)
1430                                           (nth 7 attr) item)
1431       nil)))
1432
1433 (defun speedbar-item-info-tag-helper ()
1434   "Display info about a tag that is on the current line.
1435 nil if not applicable."
1436   (save-excursion
1437     (beginning-of-line)
1438     (if (re-search-forward " [-+=]?> \\([^\n]+\\)"
1439                            (save-excursion(end-of-line)(point)) t)
1440         (let ((tag (match-string 1))
1441               (attr (speedbar-line-token))
1442               (item nil))
1443           (if (and (featurep 'semantic) (semantic-tag-p attr))
1444               (save-excursion
1445                 (when (and (semantic-tag-overlay attr)
1446                            (semantic-tag-buffer attr))
1447                   (set-buffer (semantic-tag-buffer attr)))
1448                 (speedbar-message
1449                  (funcall semantic-sb-info-format-tag-function attr)
1450                  ))
1451             (looking-at "\\([0-9]+\\):")
1452             (setq item (file-name-nondirectory (speedbar-line-directory)))
1453             (speedbar-message "Tag: %s  in %s" tag item)))
1454       (if (re-search-forward "{[+-]} \\([^\n]+\\)$"
1455                              (save-excursion(end-of-line)(point)) t)
1456           (speedbar-message "Group of tags \"%s\"" (match-string 1))
1457         (if (re-search-forward " [+-]?[()|@] \\([^\n]+\\)$" nil t)
1458             (let* ((detailtext (match-string 1))
1459                    (detail (or (speedbar-line-token) detailtext))
1460                    (parent (save-excursion
1461                              (beginning-of-line)
1462                              (let ((dep (if (looking-at "[0-9]+:")
1463                                             (1- (string-to-int (match-string 0)))
1464                                           0)))
1465                                (re-search-backward (concat "^"
1466                                (int-to-string dep)
1467                                ":")
1468                                                    nil t))
1469                              (if (looking-at "[0-9]+: +[-+=>]> \\([^\n]+\\)$")
1470                                  (speedbar-line-token)
1471                                nil))))
1472               (if (and (featurep 'semantic) (semantic-tag-p detail))
1473                   (speedbar-message
1474                    (funcall semantic-sb-info-format-tag-function detail parent))
1475                 (if parent
1476                     (speedbar-message "Detail: %s of tag %s" detail
1477                                       (if (and (featurep 'semantic)
1478                                                (semantic-tag-p parent))
1479                                           (semantic-format-tag-name parent nil t)
1480                                         parent))
1481                   (speedbar-message "Detail: %s" detail))))
1482           nil)))))
1483
1484 (defun speedbar-files-item-info ()
1485   "Display info in the mini-buffer about the button the mouse is over."
1486   (if (not speedbar-shown-directories)
1487       (speedbar-generic-item-info)
1488     (or (speedbar-item-info-file-helper)
1489         (speedbar-item-info-tag-helper)
1490         (speedbar-generic-item-info))))
1491
1492 (defun speedbar-item-copy ()
1493   "Copy the item under the cursor.
1494 Files can be copied to new names or places."
1495   (interactive)
1496   (let ((f (speedbar-line-file)))
1497     (if (not f) (error "Not a file"))
1498     (if (file-directory-p f)
1499         (error "Cannot copy directory")
1500       (let* ((rt (read-file-name (format "Copy %s to: "
1501                                          (file-name-nondirectory f))
1502                                  (file-name-directory f)))
1503              (refresh (member (expand-file-name (file-name-directory rt))
1504                               speedbar-shown-directories)))
1505         ;; Create the right file name part
1506         (if (file-directory-p rt)
1507             (setq rt
1508                   (concat (expand-file-name rt)
1509                           (if (string-match "[/\\]$" rt) "" "/")
1510                           (file-name-nondirectory f))))
1511         (if (or (not (file-exists-p rt))
1512                 (speedbar-y-or-n-p (format "Overwrite %s with %s? " rt f)
1513                                    t))
1514             (progn
1515               (copy-file f rt t t)
1516               ;; refresh display if the new place is currently displayed.
1517               (if refresh
1518                   (progn
1519                     (speedbar-refresh)
1520                     (if (not (speedbar-goto-this-file rt))
1521                         (speedbar-goto-this-file f))))
1522               ))))))
1523
1524 (defun speedbar-item-rename ()
1525   "Rename the item under the cursor or mouse.
1526 Files can be renamed to new names or moved to new directories."
1527   (interactive)
1528   (let ((f (speedbar-line-file)))
1529     (if f
1530         (let* ((rt (read-file-name (format "Rename %s to: "
1531                                            (file-name-nondirectory f))
1532                                    (file-name-directory f)))
1533                (refresh (member (expand-file-name (file-name-directory rt))
1534                                 speedbar-shown-directories)))
1535           ;; Create the right file name part
1536           (if (file-directory-p rt)
1537               (setq rt
1538                     (concat (expand-file-name rt)
1539                             (if (string-match "[/\\]\\'" rt) "" "/")
1540                             (file-name-nondirectory f))))
1541           (if (or (not (file-exists-p rt))
1542                   (speedbar-y-or-n-p (format "Overwrite %s with %s? " rt f)
1543                                      t))
1544               (progn
1545                 (rename-file f rt t)
1546                 ;; refresh display if the new place is currently displayed.
1547                 (if refresh
1548                     (progn
1549                       (speedbar-refresh)
1550                       (speedbar-goto-this-file rt)
1551                       )))))
1552       (error "Not a file"))))
1553
1554 (defun speedbar-create-directory ()
1555   "Create a directory in speedbar."
1556   (interactive)
1557   (let ((f (speedbar-line-file)))
1558     (if f
1559         (let* ((basedir (file-name-directory f))
1560                (nd (read-file-name "Create directory: "
1561                                    basedir)))
1562           ;; Make the directory
1563           (make-directory nd t)
1564           (speedbar-refresh)
1565           (speedbar-goto-this-file nd)
1566           )
1567       (error "Not a file"))))
1568
1569 (defun speedbar-item-delete ()
1570   "Delete the item under the cursor.  Files are removed from disk."
1571   (interactive)
1572   (let ((f (speedbar-line-file)))
1573     (if (not f) (error "Not a file"))
1574     (if (speedbar-y-or-n-p (format "Delete %s? " f) t)
1575         (progn
1576           (if (file-directory-p f)
1577               (delete-directory f)
1578             (delete-file f))
1579           (speedbar-message "Okie dokie..")
1580           (let ((p (point)))
1581             (speedbar-refresh)
1582             (goto-char p))
1583           ))
1584     ))
1585
1586 (defun speedbar-item-object-delete ()
1587   "Delete the object associated from the item under the cursor.
1588 The file is removed from disk.  The object is determined from the
1589 variable `speedbar-obj-alist'."
1590   (interactive)
1591   (let* ((f (speedbar-line-file))
1592          (obj nil)
1593          (oa speedbar-obj-alist))
1594     (if (not f) (error "Not a file"))
1595     (while (and oa (not (string-match (car (car oa)) f)))
1596       (setq oa (cdr oa)))
1597     (setq obj (concat (file-name-sans-extension f) (cdr (car oa))))
1598     (if (and oa (file-exists-p obj)
1599              (speedbar-y-or-n-p (format "Delete %s? " obj) t))
1600         (progn
1601           (delete-file obj)
1602           (speedbar-reset-scanners)))))
1603
1604 (defun speedbar-enable-update ()
1605   "Enable automatic updating in speedbar via timers."
1606   (interactive)
1607   (setq speedbar-update-flag t)
1608   (speedbar-set-mode-line-format)
1609   (speedbar-set-timer dframe-update-speed))
1610
1611 (defun speedbar-disable-update ()
1612   "Disable automatic updating and stop consuming resources."
1613   (interactive)
1614   (setq speedbar-update-flag nil)
1615   (speedbar-set-mode-line-format)
1616   (speedbar-set-timer nil))
1617
1618 (defun speedbar-toggle-updates ()
1619   "Toggle automatic update for the speedbar frame."
1620   (interactive)
1621   (if speedbar-update-flag
1622       (speedbar-disable-update)
1623     (speedbar-enable-update)))
1624
1625 (defun speedbar-toggle-images ()
1626   "Toggle use of images in the speedbar frame.
1627 Images are not available in Emacs 20 or earlier."
1628   (interactive)
1629   (setq speedbar-use-images (not speedbar-use-images))
1630   (speedbar-refresh))
1631
1632 (defun speedbar-toggle-sorting ()
1633   "Toggle tag sorting."
1634   (interactive)
1635   (setq speedbar-sort-tags (not speedbar-sort-tags)))
1636
1637 (defun speedbar-toggle-show-all-files ()
1638   "Toggle display of files speedbar can not tag."
1639   (interactive)
1640   (setq speedbar-show-unknown-files (not speedbar-show-unknown-files))
1641   (speedbar-refresh))
1642
1643 (defmacro speedbar-with-writable (&rest forms)
1644   "Allow the buffer to be writable and evaluate FORMS."
1645   (list 'let '((inhibit-read-only t))
1646         (cons 'progn forms)))
1647 (put 'speedbar-with-writable 'lisp-indent-function 0)
1648
1649 (defun speedbar-insert-button (text face mouse function
1650                                     &optional token prevline)
1651   "Insert TEXT as the next logical speedbar button.
1652 FACE is the face to put on the button, MOUSE is the highlight face to use.
1653 When the user clicks on TEXT, FUNCTION is called with the TOKEN parameter.
1654 This function assumes that the current buffer is the speedbar buffer.
1655 If PREVLINE, then put this button on the previous line.
1656
1657 This is a convenience function for special modes that create their own
1658 specialized speedbar displays."
1659   (goto-char (point-max))
1660   (let ((start (point)))
1661     (if (/= (current-column) 0) (insert "\n"))
1662     (put-text-property start (point) 'invisible nil))
1663   (if prevline (progn (delete-char -1)
1664                       (insert " ") ;back up if desired...
1665                       (put-text-property (1- (point)) (point) 'invisible nil)))
1666   (let ((start (point)))
1667     (insert text)
1668     (speedbar-make-button start (point) face mouse function token))
1669   (let ((start (point)))
1670     (insert "\n")
1671     (put-text-property start (point) 'face nil)
1672     (put-text-property start (point) 'invisible nil)
1673     (put-text-property start (point) 'mouse-face nil)))
1674
1675 (defun speedbar-insert-separator (text)
1676   "Insert a separation label of TEXT.
1677 Separators are not active, have no labels, depth, or actions."
1678   (if speedbar-use-images
1679       (let ((start (point)))
1680         (insert "//")
1681         (speedbar-insert-image-button-maybe start 2)))
1682   (let ((start (point)))
1683     (insert text "\n")
1684     (speedbar-make-button start (point)
1685                           'speedbar-separator-face
1686                           nil nil nil)))
1687
1688 (defun speedbar-make-button (start end face mouse function &optional token)
1689   "Create a button from START to END, with FACE as the display face.
1690 MOUSE is the mouse face.  When this button is clicked on FUNCTION
1691 will be run with the TOKEN parameter (any Lisp object)"
1692   (put-text-property start end 'face face)
1693   (put-text-property start end 'mouse-face mouse)
1694   (if speedbar-use-tool-tips-flag
1695       (put-text-property start end 'help-echo #'dframe-help-echo))
1696   (put-text-property start end 'invisible nil)
1697   (put-text-property start end 'speedbar-text
1698                      (buffer-substring-no-properties start end))
1699   (if function (put-text-property start end 'speedbar-function function))
1700   (if token (put-text-property start end 'speedbar-token token))
1701   ;; So far the only text we have is less that 3 chars.
1702   (if (<= (- end start) 3)
1703       (speedbar-insert-image-button-maybe start (- end start)))
1704   )
1705 \f
1706 ;;; Initial Expansion list management
1707 ;;
1708 (defun speedbar-initial-expansion-list ()
1709   "Return the current default expansion list.
1710 This is based on `speedbar-initial-expansion-list-name' referencing
1711 `speedbar-initial-expansion-mode-alist'."
1712   ;; cdr1 - name, cdr2 - menu
1713   (cdr (cdr (cdr (assoc speedbar-initial-expansion-list-name
1714                         speedbar-initial-expansion-mode-alist)))))
1715
1716 (defun speedbar-initial-menu ()
1717   "Return the current default menu data.
1718 This is based on `speedbar-initial-expansion-list-name' referencing
1719 `speedbar-initial-expansion-mode-alist'."
1720   (symbol-value
1721    (car (cdr (assoc speedbar-initial-expansion-list-name
1722                     speedbar-initial-expansion-mode-alist)))))
1723
1724 (defun speedbar-initial-keymap ()
1725   "Return the current default menu data.
1726 This is based on `speedbar-initial-expansion-list-name' referencing
1727 `speedbar-initial-expansion-mode-alist'."
1728   (symbol-value
1729    (car (cdr (cdr (assoc speedbar-initial-expansion-list-name
1730                          speedbar-initial-expansion-mode-alist))))))
1731
1732 (defun speedbar-initial-stealthy-functions ()
1733   "Return a list of functions to call stealthily.
1734 This is based on `speedbar-initial-expansion-list-name' referencing
1735 `speedbar-stealthy-function-list'."
1736   (cdr (assoc speedbar-initial-expansion-list-name
1737               speedbar-stealthy-function-list)))
1738
1739 (defun speedbar-add-expansion-list (new-list)
1740   "Add NEW-LIST to the list of expansion lists."
1741   (add-to-list 'speedbar-initial-expansion-mode-alist new-list))
1742
1743 (defun speedbar-change-initial-expansion-list (new-default)
1744   "Change speedbar's default expansion list to NEW-DEFAULT."
1745   (interactive
1746    (list
1747     (completing-read (format "Speedbar Mode (default %s): "
1748                              speedbar-previously-used-expansion-list-name)
1749                      speedbar-initial-expansion-mode-alist
1750                      nil t "" nil
1751                      speedbar-previously-used-expansion-list-name)))
1752   (setq speedbar-previously-used-expansion-list-name
1753         speedbar-initial-expansion-list-name
1754         speedbar-initial-expansion-list-name new-default)
1755   (if (and (speedbar-current-frame) (frame-live-p (speedbar-current-frame)))
1756       (progn
1757         (speedbar-refresh)
1758         (speedbar-reconfigure-keymaps))))
1759
1760 (defun speedbar-fetch-replacement-function (function)
1761   "Return a current mode specific replacement for function, or nil.
1762 Scans `speedbar-mode-functions-list' first for the current mode, then
1763 for FUNCTION."
1764   (cdr (assoc function
1765               (cdr (assoc speedbar-initial-expansion-list-name
1766                           speedbar-mode-functions-list)))))
1767
1768 (defun speedbar-add-mode-functions-list (new-list)
1769   "Add NEW-LIST to the list of mode functions.
1770 See `speedbar-mode-functions-list' for details."
1771   (add-to-list 'speedbar-mode-functions-list new-list))
1772
1773 \f
1774 ;;; Special speedbar display management
1775 ;;
1776 (defun speedbar-maybe-add-localized-support (buffer)
1777   "Quick check function called on BUFFERs by the speedbar timer function.
1778 Maintains the value of local variables which control speedbars use
1779 of the special mode functions."
1780   (or speedbar-special-mode-expansion-list
1781       (speedbar-add-localized-speedbar-support buffer)))
1782
1783 (defun speedbar-add-localized-speedbar-support (buffer)
1784   "Add localized speedbar support to BUFFER's mode if it is available."
1785   (interactive "bBuffer: ")
1786   (if (stringp buffer) (setq buffer (get-buffer buffer)))
1787   (if (not (buffer-live-p buffer))
1788       nil
1789     (save-excursion
1790       (set-buffer buffer)
1791       (save-match-data
1792         (let ((ms (symbol-name major-mode)) v)
1793           (if (not (string-match "-mode$" ms))
1794               nil ;; do nothing to broken mode
1795             (setq ms (substring ms 0 (match-beginning 0)))
1796             (setq v (intern-soft (concat ms "-speedbar-buttons")))
1797             (make-local-variable 'speedbar-special-mode-expansion-list)
1798             (if (not v)
1799                 (setq speedbar-special-mode-expansion-list t)
1800               ;; If it is autoloaded, we need to load it now so that
1801               ;; we have access to the varialbe -speedbar-menu-items.
1802               ;; Is this XEmacs safe?
1803               (let ((sf (symbol-function v)))
1804                 (if (and (listp sf) (eq (car sf) 'autoload))
1805                     (load-library (car (cdr sf)))))
1806               (setq speedbar-special-mode-expansion-list (list v))
1807               (setq v (intern-soft (concat ms "-speedbar-key-map")))
1808               (if (not v)
1809                   nil ;; don't add special keymap
1810                 (make-local-variable 'speedbar-special-mode-key-map)
1811                 (setq speedbar-special-mode-key-map
1812                       (symbol-value v)))
1813               (setq v (intern-soft (concat ms "-speedbar-menu-items")))
1814               (if (not v)
1815                   nil ;; don't add special menus
1816                 (make-local-variable 'speedbar-easymenu-definition-special)
1817                 (setq speedbar-easymenu-definition-special
1818                       (symbol-value v)))
1819               )))))))
1820
1821 (defun speedbar-remove-localized-speedbar-support (buffer)
1822   "Remove any traces that BUFFER supports speedbar in a specialized way."
1823   (save-excursion
1824     (set-buffer buffer)
1825     (kill-local-variable 'speedbar-special-mode-expansion-list)
1826     (kill-local-variable 'speedbar-special-mode-key-map)
1827     (kill-local-variable 'speedbar-easymenu-definition-special)))
1828 \f
1829 ;;; File button management
1830 ;;
1831 (defun speedbar-file-lists (directory)
1832   "Create file lists for DIRECTORY.
1833 The car is the list of directories, the cdr is list of files not
1834 matching ignored headers.  Cache any directory files found in
1835 `speedbar-directory-contents-alist' and use that cache before scanning
1836 the file-system."
1837   (setq directory (expand-file-name directory))
1838   ;; If in powerclick mode, then the directory we are getting
1839   ;; should be rescanned.
1840   (if dframe-power-click
1841       (adelete 'speedbar-directory-contents-alist directory))
1842   ;; find the directory, either in the cache, or build it.
1843   (or (cdr-safe (assoc directory speedbar-directory-contents-alist))
1844       (let ((default-directory directory)
1845             (dir (directory-files directory nil))
1846             (dirs nil)
1847             (files nil))
1848         (while dir
1849           (if (not
1850                (or (string-match speedbar-file-unshown-regexp (car dir))
1851                    (string-match speedbar-directory-unshown-regexp (car dir))))
1852               (if (file-directory-p (car dir))
1853                   (setq dirs (cons (car dir) dirs))
1854                 (setq files (cons (car dir) files))))
1855           (setq dir (cdr dir)))
1856         (let ((nl (cons (nreverse dirs) (list (nreverse files)))))
1857           (aput 'speedbar-directory-contents-alist directory nl)
1858           nl))
1859       ))
1860
1861 (defun speedbar-directory-buttons (directory index)
1862   "Insert a single button group at point for DIRECTORY.
1863 Each directory directory part is a different button.  If part of the directory
1864 matches the user directory ~, then it is replaced with a ~.
1865 INDEX is not used, but is required by the caller."
1866   (let* ((tilde (expand-file-name "~/"))
1867          (dd (expand-file-name directory))
1868          (junk (string-match (regexp-quote tilde) dd))
1869          (displayme (if junk
1870                         (concat "~/" (substring dd (match-end 0)))
1871                       dd))
1872          (p (point)))
1873     (if (string-match "^~[/\\]?\\'" displayme) (setq displayme tilde))
1874     (insert displayme)
1875     (save-excursion
1876       (goto-char p)
1877       (while (re-search-forward "\\([^/\\]+\\)[/\\]" nil t)
1878         (speedbar-make-button (match-beginning 1) (match-end 1)
1879                               'speedbar-directory-face
1880                               'speedbar-highlight-face
1881                               'speedbar-directory-buttons-follow
1882                               (if (and (= (match-beginning 1) p)
1883                                        (not (char-equal (char-after (+ p 1)) ?:)))
1884                                   (expand-file-name "~/")  ;the tilde
1885                                 (buffer-substring-no-properties
1886                                  p (match-end 0)))))
1887       ;; Nuke the beginning of the directory if it's too long...
1888       (cond ((eq speedbar-directory-button-trim-method 'span)
1889              (beginning-of-line)
1890              (let ((ww (or (speedbar-frame-width) 20)))
1891                (move-to-column ww nil)
1892                (while (>= (current-column) ww)
1893                  (re-search-backward "[/\\]" nil t)
1894                  (if (<= (current-column) 2)
1895                      (progn
1896                        (re-search-forward "[/\\]" nil t)
1897                        (if (< (current-column) 4)
1898                            (re-search-forward "[/\\]" nil t))
1899                        (forward-char -1)))
1900                  (if (looking-at "[/\\]?$")
1901                      (beginning-of-line)
1902                    (insert "/...\n ")
1903                    (move-to-column ww nil)))))
1904             ((eq speedbar-directory-button-trim-method 'trim)
1905              (end-of-line)
1906              (let ((ww (or (speedbar-frame-width) 20))
1907                    (tl (current-column)))
1908                (if (< ww tl)
1909                    (progn
1910                      (move-to-column (- tl ww))
1911                      (if (re-search-backward "[/\\]" nil t)
1912                          (progn
1913                            (delete-region (point-min) (point))
1914                            (insert "$")
1915                            )))))))
1916       )
1917     (if (string-match "\\`[/\\][^/\\]+[/\\]\\'" displayme)
1918         (progn
1919           (insert "  ")
1920           (let ((p (point)))
1921             (insert "<root>")
1922             (speedbar-make-button p (point)
1923                                   'speedbar-directory-face
1924                                   'speedbar-highlight-face
1925                                   'speedbar-directory-buttons-follow
1926                                   "/"))))
1927     (end-of-line)
1928     (insert-char ?\n 1 nil)))
1929
1930 (defun speedbar-make-tag-line (exp-button-type
1931                                exp-button-char exp-button-function
1932                                exp-button-data
1933                                tag-button tag-button-function tag-button-data
1934                                tag-button-face depth)
1935   "Create a tag line with EXP-BUTTON-TYPE for the small expansion button.
1936 This is the button that expands or contracts a node (if applicable),
1937 and EXP-BUTTON-CHAR the character in it (+, -, ?, etc).  EXP-BUTTON-FUNCTION
1938 is the function to call if it's clicked on.  Button types are
1939 'bracket, 'angle, 'curly, 'expandtag, 'statictag, t, or nil.
1940 EXP-BUTTON-DATA is extra data attached to the text forming the expansion
1941 button.
1942
1943 Next, TAG-BUTTON is the text of the tag.  TAG-BUTTON-FUNCTION is the
1944 function to call if clicked on, and TAG-BUTTON-DATA is the data to
1945 attach to the text field (such a tag positioning, etc).
1946 TAG-BUTTON-FACE is a face used for this type of tag.
1947
1948 Lastly, DEPTH shows the depth of expansion.
1949
1950 This function assumes that the cursor is in the speedbar window at the
1951 position to insert a new item, and that the new item will end with a CR."
1952   (let ((start (point))
1953         (end (progn
1954                (insert (int-to-string depth) ":")
1955                (point)))
1956         (depthspacesize (* depth speedbar-indentation-width)))
1957     (put-text-property start end 'invisible t)
1958     (insert-char ?  depthspacesize nil)
1959     (put-text-property (- (point) depthspacesize) (point) 'invisible nil)
1960     (let* ((exp-button (cond ((eq exp-button-type 'bracket) "[%c]")
1961                              ((eq exp-button-type 'angle) "<%c>")
1962                              ((eq exp-button-type 'curly) "{%c}")
1963                              ((eq exp-button-type 'expandtag) " %c>")
1964                              ((eq exp-button-type 'statictag) " =>")
1965                              (t ">")))
1966            (buttxt (format exp-button exp-button-char))
1967            (start (point))
1968            (end (progn (insert buttxt) (point)))
1969            (bf (if (and exp-button-type (not (eq exp-button-type 'statictag)))
1970                    'speedbar-button-face nil))
1971            (mf (if exp-button-function 'speedbar-highlight-face nil))
1972            )
1973       (speedbar-make-button start end bf mf exp-button-function exp-button-data)
1974       (if speedbar-hide-button-brackets-flag
1975           (progn
1976             (put-text-property start (1+ start) 'invisible t)
1977             (put-text-property end (1- end) 'invisible t)))
1978       )
1979     (insert-char ?  1 nil)
1980     (put-text-property (1- (point)) (point) 'invisible nil)
1981     (let ((start (point))
1982           (end (progn (insert tag-button) (point))))
1983       (insert-char ?\n 1 nil)
1984       (put-text-property (1- (point)) (point) 'invisible nil)
1985       (speedbar-make-button start end tag-button-face
1986                             (if tag-button-function 'speedbar-highlight-face nil)
1987                             tag-button-function tag-button-data))
1988     ))
1989   
1990 (defun speedbar-change-expand-button-char (char)
1991   "Change the expansion button character to CHAR for the current line."
1992   (save-excursion
1993     (beginning-of-line)
1994     (if (re-search-forward ":\\s-*.\\([-+?]\\)" (save-excursion (end-of-line)
1995                                                                 (point)) t)
1996         (speedbar-with-writable
1997           (goto-char (match-end 1))
1998           (insert-char char 1 t)
1999           (forward-char -1)
2000           (delete-char -1)
2001           ;;(put-text-property (point) (1- (point)) 'invisible nil)
2002           ;; make sure we fix the image on the text here.
2003           (speedbar-insert-image-button-maybe (- (point) 1) 3)))))
2004
2005 \f
2006 ;;; Build button lists
2007 ;;
2008 (defun speedbar-insert-files-at-point (files level)
2009   "Insert list of FILES starting at point, and indenting all files to LEVEL.
2010 Tag expandable items with a +, otherwise a ?.  Don't highlight ? as we
2011 don't know how to manage them.  The input parameter FILES is a cons
2012 cell of the form ( 'DIRLIST .  'FILELIST )."
2013   ;; Start inserting all the directories
2014   (let ((dirs (car files)))
2015     (while dirs
2016       (speedbar-make-tag-line 'angle ?+ 'speedbar-dired (car dirs)
2017                               (car dirs) 'speedbar-dir-follow nil
2018                               'speedbar-directory-face level)
2019       (setq dirs (cdr dirs))))
2020   (let ((lst (car (cdr files)))
2021         (case-fold-search t))
2022     (while lst
2023       (let* ((known (string-match speedbar-file-regexp (car lst)))
2024              (expchar (if known ?+ ??))
2025              (fn (if known 'speedbar-tag-file nil)))
2026         (if (or speedbar-show-unknown-files (/= expchar ??))
2027             (speedbar-make-tag-line 'bracket expchar fn (car lst)
2028                                     (car lst) 'speedbar-find-file nil
2029                                     'speedbar-file-face level)))
2030       (setq lst (cdr lst)))))
2031
2032 (defun speedbar-default-directory-list (directory index)
2033   "Insert files for DIRECTORY with level INDEX at point."
2034   (speedbar-insert-files-at-point 
2035    (speedbar-file-lists directory) index)
2036   (speedbar-reset-scanners)
2037   (if (= index 0)
2038       ;; If the shown files variable has extra directories, then
2039       ;; it is our responsibility to redraw them all
2040       ;; Luckilly, the nature of inserting items into this list means
2041       ;; that by reversing it, we can easilly go in the right order
2042       (let ((sf (cdr (reverse speedbar-shown-directories))))
2043         (setq speedbar-shown-directories
2044               (list (expand-file-name default-directory)))
2045         ;; exand them all as we find them
2046         (while sf
2047           (if (speedbar-goto-this-file (car sf))
2048               (progn
2049                 (beginning-of-line)
2050                 (if (looking-at "[0-9]+:[ ]*<")
2051                     (progn
2052                       (goto-char (match-end 0))
2053                       (speedbar-do-function-pointer)))))
2054           (setq sf (cdr sf)))
2055         )))
2056 ;;; Generic List support
2057 ;;
2058 ;;  Generic lists are hierarchies of tags which we may need to permute
2059 ;;  in order to make it look nice.
2060 ;;
2061 ;;  A generic list is of the form:
2062 ;;  ( ("name" . marker-or-number)              <-- one tag at this level
2063 ;;    ("name" ("name" . mon) ("name" . mon) )  <-- one group of tags
2064 ;;    ("name" mon ("name" . mon) )             <-- group w/ a position and tags
2065 (defun speedbar-generic-list-group-p (sublst)
2066   "Non-nil if SUBLST is a group.
2067 Groups may optionally contain a position."
2068   (and (stringp (car-safe sublst))
2069        (or (and (listp (cdr-safe sublst))
2070                 (or (speedbar-generic-list-tag-p (car-safe (cdr-safe sublst)))
2071                     (speedbar-generic-list-group-p (car-safe (cdr-safe sublst))
2072                                                    )))
2073            (and (number-or-marker-p (car-safe (cdr-safe sublst)))
2074                 (listp (cdr-safe (cdr-safe sublst)))
2075                 (speedbar-generic-list-tag-p
2076                  (car-safe (cdr-safe (cdr-safe sublst)))))
2077            )))
2078
2079 (defun speedbar-generic-list-positioned-group-p (sublst)
2080   "Non-nil of SUBLST is a group with a position."
2081   (and (stringp (car-safe sublst))
2082        (number-or-marker-p (car-safe (cdr-safe sublst)))
2083        (listp (cdr-safe (cdr-safe sublst)))
2084        (let ((rest (car-safe (cdr-safe (cdr-safe sublst)))))
2085          (or (speedbar-generic-list-tag-p rest)
2086              (speedbar-generic-list-group-p rest)
2087              (speedbar-generic-list-positioned-group-p rest)
2088              ))))
2089
2090 (defun speedbar-generic-list-tag-p (sublst)
2091   "Non nil if SUBLST is a tag."
2092   (and (stringp (car-safe sublst))
2093        (or (and (number-or-marker-p (cdr-safe sublst))
2094                 (not (cdr-safe (cdr-safe sublst))))
2095            ;; For semantic/bovine items, this is needed
2096            (symbolp (car-safe (cdr-safe sublst))))
2097        ))
2098
2099 (defun speedbar-sort-tag-hierarchy (lst)
2100   "Sort all elements of tag hierarchy LST."
2101   (sort (copy-alist lst)
2102         (lambda (a b) (string< (car a) (car b)))))
2103
2104 (defun speedbar-try-completion (string alist)
2105   "A wrapper for `try-completion'.
2106 Passes STRING and ALIST to `try-completion' if ALIST
2107 passes some tests."
2108   (if (and (listp alist) (not (null alist))
2109            (listp (car alist)) (stringp (car (car alist))))
2110       (try-completion string alist)
2111     nil))
2112
2113 (defun speedbar-prefix-group-tag-hierarchy (lst)
2114   "Prefix group names for tag hierarchy LST."
2115   (let ((newlst nil)
2116         (sublst nil)
2117         (work-list nil)
2118         (junk-list nil)
2119         (short-group-list nil)
2120         (short-start-name nil)
2121         (short-end-name nil)
2122         (num-shorts-grouped 0)
2123         (bins (make-vector 256 nil))
2124         (diff-idx 0))
2125     (if (<= (length lst) speedbar-tag-regroup-maximum-length)
2126         ;; Do nothing.  Too short to bother with.
2127         lst
2128       ;; Break out sub-lists
2129       (while lst
2130         (if (speedbar-generic-list-group-p (car-safe lst))
2131             (setq newlst (cons (car lst) newlst))
2132           (setq sublst (cons (car lst) sublst)))
2133         (setq lst (cdr lst)))
2134       ;; Reverse newlst because it was made backwards.
2135       ;; Sublist doesn't need reversing because the act
2136       ;; of binning things will reverse it for us.
2137       (setq newlst (nreverse newlst)
2138             sublst sublst)
2139       ;; Now, first find out how long our list is.  Never let a
2140       ;; list get-shorter than our minimum.
2141       (if (<= (length sublst) speedbar-tag-split-minimum-length)
2142           (setq work-list sublst)
2143         (setq diff-idx (length (speedbar-try-completion "" sublst)))
2144         ;; Sort the whole list into bins.
2145         (while sublst
2146           (let ((e (car sublst))
2147                 (s (car (car sublst))))
2148             (cond ((<= (length s) diff-idx)
2149                    ;; 0 storage bin for shorty.
2150                    (aset bins 0 (cons e (aref bins 0))))
2151                   (t
2152                    ;; stuff into a bin based on ascii value at diff
2153                    (aset bins (aref s diff-idx)
2154                          (cons e (aref bins (aref s diff-idx)))))))
2155           (setq sublst (cdr sublst)))
2156         ;; Go through all our bins  Stick singles into our
2157         ;; junk-list, everything else as sublsts in work-list.
2158         ;; If two neighboring lists are both small, make a grouped
2159         ;; group combinding those two sub-lists.
2160         (setq diff-idx 0)
2161         (while (> 256 diff-idx)
2162           ;; The bins contents are currently in forward order.
2163           (let ((l (aref bins diff-idx)))
2164             (if l
2165                 (let ((tmp (cons (speedbar-try-completion "" l) l)))
2166                   (if (or (> (length l) speedbar-tag-regroup-maximum-length)
2167                           (> (+ (length l) (length short-group-list))
2168                              speedbar-tag-split-minimum-length))
2169                       (progn
2170                         ;; We have reached a longer list, so we
2171                         ;; must finish off a grouped group.
2172                         (cond
2173                          ((and short-group-list
2174                                (= (length short-group-list)
2175                                   num-shorts-grouped))
2176                           ;; All singles?  Junk list
2177                           (setq junk-list (append (nreverse short-group-list)
2178                                                   junk-list)))
2179                          ((= num-shorts-grouped 1)
2180                           ;; Only one short group?  Just stick it in
2181                           ;; there by itself.  Make a group, and find
2182                           ;; a subexpression
2183                           (let ((subexpression (speedbar-try-completion
2184                                                 "" short-group-list)))
2185                             (if (< (length subexpression)
2186                                    speedbar-tag-group-name-minimum-length)
2187                                 (setq subexpression
2188                                       (concat short-start-name
2189                                               " ("
2190                                               (substring
2191                                                (car (car short-group-list))
2192                                                (length short-start-name))
2193                                               ")")))
2194                             (setq work-list
2195                                   (cons (cons subexpression
2196                                               short-group-list)
2197                                         work-list ))))
2198                          (short-group-list
2199                           ;; Multiple groups to be named in a special
2200                           ;; way by displaying the range over which we
2201                           ;; have grouped them.
2202                           (setq work-list
2203                                 (cons (cons (concat short-start-name
2204                                                     " to "
2205                                                     short-end-name)
2206                                             short-group-list)
2207                                       work-list))))
2208                      ;; Reset short group list information every time.
2209                         (setq short-group-list nil
2210                               short-start-name nil
2211                               short-end-name nil
2212                               num-shorts-grouped 0)))
2213                   ;; Ok, now that we cleaned up the short-group-list,
2214                   ;; we can deal with this new list, to decide if it
2215                   ;; should go on one of these sub-lists or not.
2216                   (if (< (length l) speedbar-tag-regroup-maximum-length)
2217                       (setq short-group-list (append l short-group-list)
2218                             num-shorts-grouped (1+ num-shorts-grouped)
2219                             short-end-name (car tmp)
2220                             short-start-name (if short-start-name
2221                                                  short-start-name
2222                                                (car tmp)))
2223                     (setq work-list (cons tmp work-list))))))
2224           (setq diff-idx (1+ diff-idx))))
2225       ;; Did we run out of things?  Drop our new list onto the end.
2226       (cond
2227        ((and short-group-list (= (length short-group-list) num-shorts-grouped))
2228         ;; All singles?  Junk list
2229         (setq junk-list (append short-group-list junk-list)))
2230        ((= num-shorts-grouped 1)
2231         ;; Only one short group?  Just stick it in
2232         ;; there by itself.
2233         (setq work-list
2234               (cons (cons (speedbar-try-completion "" short-group-list)
2235                           short-group-list)
2236                     work-list)))
2237        (short-group-list
2238         ;; Multiple groups to be named in a special
2239         ;; way by displaying the range over which we
2240         ;; have grouped them.
2241         (setq work-list
2242               (cons (cons (concat short-start-name " to " short-end-name)
2243                           short-group-list)
2244                     work-list))))
2245       ;; Reverse the work list nreversed when consing.
2246       (setq work-list (nreverse work-list))
2247       ;; Now, stick our new list onto the end of
2248       (if work-list
2249           (if junk-list
2250               (append newlst work-list junk-list)
2251             (append newlst work-list))
2252         (append  newlst junk-list)))))
2253
2254 (defun speedbar-trim-words-tag-hierarchy (lst)
2255   "Trim all words in a tag hierarchy.
2256 Base trimming information on word separators, and group names.
2257 Argument LST is the list of tags to trim."
2258   (let ((newlst nil)
2259         (sublst nil)
2260         (trim-prefix nil)
2261         (trim-chars 0)
2262         (trimlst nil))
2263     (while lst
2264       (if (speedbar-generic-list-group-p (car-safe lst))
2265           (setq newlst (cons (car lst) newlst))
2266         (setq sublst (cons (car lst) sublst)))
2267       (setq lst (cdr lst)))
2268     ;; Get the prefix to trim by.  Make sure that we don't trim
2269     ;; off silly pieces, only complete understandable words.
2270     (setq trim-prefix (speedbar-try-completion "" sublst)
2271           newlst (nreverse newlst))
2272     (if (or (= (length sublst) 1)
2273             (not trim-prefix)
2274             (not (string-match "\\(\\w+\\W+\\)+" trim-prefix)))
2275         (append newlst (nreverse sublst))
2276       (setq trim-prefix (substring trim-prefix (match-beginning 0)
2277                                    (match-end 0)))
2278       (setq trim-chars (length trim-prefix))
2279       (while sublst
2280         (setq trimlst (cons
2281                        (cons (substring (car (car sublst)) trim-chars)
2282                              (cdr (car sublst)))
2283                        trimlst)
2284               sublst (cdr sublst)))
2285       ;; Put the lists together
2286       (append newlst trimlst))))
2287
2288 (defun speedbar-simple-group-tag-hierarchy (lst)
2289   "Create a simple 'Tags' group with orphaned tags.
2290 Argument LST is the list of tags to sort into groups."
2291   (let ((newlst nil)
2292         (sublst nil))
2293     (while lst
2294       (if (speedbar-generic-list-group-p (car-safe lst))
2295           (setq newlst (cons (car lst) newlst))
2296         (setq sublst (cons (car lst) sublst)))
2297       (setq lst (cdr lst)))
2298     (if (not newlst)
2299         (nreverse sublst)
2300       (setq newlst (cons (cons "Tags" (nreverse sublst)) newlst))
2301       (nreverse newlst))))
2302
2303 (defun speedbar-create-tag-hierarchy (lst)
2304   "Adjust the tag hierarchy in LST, and return it.
2305 This uses `speedbar-tag-hierarchy-method' to determine how to adjust
2306 the list."
2307   (let* ((f (save-excursion
2308               (forward-line -1)
2309               (or (speedbar-line-file)
2310                   (speedbar-line-directory))))
2311          (methods (if (get-file-buffer f)
2312                       (save-excursion (set-buffer (get-file-buffer f))
2313                                       speedbar-tag-hierarchy-method)
2314                     speedbar-tag-hierarchy-method))
2315          (lst (if (fboundp 'copy-tree)
2316                   (copy-tree lst)
2317                 lst)))
2318     (while methods
2319       (setq lst (funcall (car methods) lst)
2320             methods (cdr methods)))
2321     lst))
2322
2323 (defvar speedbar-generic-list-group-expand-button-type 'curly
2324   "The type of button created for groups of tags.
2325 Good values for this are `curly' and `expandtag'.
2326 Make buffer local for your mode.")
2327
2328 (defvar speedbar-generic-list-tag-button-type nil
2329   "The type of button created for tags in generic lists.
2330 Good values for this are nil and `statictag'.
2331 Make buffer local for your mode.")
2332
2333 (defun speedbar-insert-generic-list (level lst expand-fun find-fun)
2334   "At LEVEL, insert a generic multi-level alist LST.
2335 Associations with lists get {+} tags (to expand into more nodes) and
2336 those with positions just get a > as the indicator.  {+} buttons will
2337 have the function EXPAND-FUN and the token is the CDR list.  The token
2338 name will have the function FIND-FUN and not token."
2339   ;; Remove imenu rescan button
2340   (if (string= (car (car lst)) "*Rescan*")
2341       (setq lst (cdr lst)))
2342   ;; Get, and set up variables that define how we treat these tags.
2343    (let ((f (save-excursion (forward-line -1)
2344                             (or (speedbar-line-file)
2345                                 (speedbar-line-directory))))
2346          expand-button tag-button)
2347      (save-excursion
2348        (if (get-file-buffer f)
2349            (set-buffer (get-file-buffer f)))
2350        (setq expand-button speedbar-generic-list-group-expand-button-type
2351              tag-button speedbar-generic-list-tag-button-type))
2352      ;; Adjust the list.
2353      (setq lst (speedbar-create-tag-hierarchy lst))
2354      ;; insert the parts
2355      (while lst
2356        (cond ((null (car-safe lst)) nil)        ;this would be a separator
2357             ((speedbar-generic-list-tag-p (car lst))
2358              (speedbar-make-tag-line tag-button
2359                                      nil nil nil ;no expand button data
2360                                      (car (car lst)) ;button name
2361                                      find-fun ;function
2362                                      (cdr (car lst)) ;token is position
2363                                      'speedbar-tag-face
2364                                      (1+ level)))
2365             ((speedbar-generic-list-positioned-group-p (car lst))
2366              (speedbar-make-tag-line expand-button
2367                                      ?+ expand-fun (cdr (cdr (car lst)))
2368                                      (car (car lst)) ;button name
2369                                      find-fun ;function
2370                                      (car (cdr (car lst))) ;token is posn
2371                                      'speedbar-tag-face
2372                                      (1+ level)))
2373             ((speedbar-generic-list-group-p (car lst))
2374              (speedbar-make-tag-line expand-button
2375                                      ?+ expand-fun (cdr (car lst))
2376                                      (car (car lst)) ;button name
2377                                      nil nil 'speedbar-tag-face
2378                                      (1+ level)))
2379             (t (speedbar-message "speedbar-insert-generic-list: malformed list!")
2380                ))
2381       (setq lst (cdr lst)))))
2382
2383 (defun speedbar-insert-imenu-list (indent lst)
2384   "At level INDENT, insert the imenu generated LST."
2385   (speedbar-insert-generic-list indent lst
2386                                 'speedbar-tag-expand
2387                                 'speedbar-tag-find))
2388                                 
2389 (defun speedbar-insert-etags-list (indent lst)
2390   "At level INDENT, insert the etags generated LST."
2391   (speedbar-insert-generic-list indent lst
2392                                 'speedbar-tag-expand
2393                                 'speedbar-tag-find))
2394 \f
2395 ;;; Timed functions
2396 ;;
2397 (defun speedbar-update-contents ()
2398   "Generically update the contents of the speedbar buffer."
2399   (interactive)
2400   ;; Set the current special buffer
2401   (setq speedbar-desired-buffer nil)
2402
2403   ;; Check for special modes
2404   (speedbar-maybe-add-localized-support (current-buffer))
2405
2406   ;; Choose the correct method of doodling.
2407   (if (and speedbar-mode-specific-contents-flag
2408            (listp speedbar-special-mode-expansion-list)
2409            speedbar-special-mode-expansion-list
2410            (local-variable-p
2411             'speedbar-special-mode-expansion-list
2412             (current-buffer)))
2413       ;;(eq (get major-mode 'mode-class 'special)))
2414       (speedbar-update-special-contents)
2415     (speedbar-update-directory-contents)))
2416
2417 (defun speedbar-update-localized-contents ()
2418   "Update the contents of the speedbar buffer for the current situation."
2419   ;; Due to the historical growth of speedbar, we need to do something
2420   ;; special for "files" mode.  Too bad.
2421   (let ((name speedbar-initial-expansion-list-name)
2422         (funclst (speedbar-initial-expansion-list))
2423         )
2424     (if (string= name "files")
2425         ;; Do all the files type work.  It still goes through the
2426         ;; expansion list stuff. :(
2427         (if (or (member (expand-file-name default-directory)
2428                         speedbar-shown-directories)
2429                 (and speedbar-ignored-directory-regexp
2430                      (string-match
2431                       speedbar-ignored-directory-regexp
2432                       (expand-file-name default-directory))))
2433             nil
2434           (if (<= 1 speedbar-verbosity-level)
2435               (speedbar-message "Updating speedbar to: %s..."
2436                                 default-directory))
2437           (speedbar-update-directory-contents)
2438           (if (<= 1 speedbar-verbosity-level)
2439               (progn
2440                 (speedbar-message "Updating speedbar to: %s...done"
2441                                   default-directory)
2442                 (speedbar-message nil))))
2443       ;; Else, we can do a short cut.  No text cache.
2444       (let ((cbd (expand-file-name default-directory))
2445             )
2446         (set-buffer speedbar-buffer)
2447         (speedbar-with-writable
2448           (erase-buffer)
2449           (while funclst
2450             (setq default-directory cbd)
2451             (funcall (car funclst) cbd 0)
2452             (setq funclst (cdr funclst)))
2453         (speedbar-reconfigure-keymaps)
2454         (goto-char (point-min)))
2455         ))))
2456
2457 (defun speedbar-update-directory-contents ()
2458   "Update the contents of the speedbar buffer based on the current directory."
2459
2460   (save-excursion
2461
2462     (let ((cbd (expand-file-name default-directory))
2463           cbd-parent
2464           (funclst (speedbar-initial-expansion-list))
2465           (cache speedbar-full-text-cache)
2466           ;; disable stealth during update
2467           (speedbar-stealthy-function-list nil)
2468           (use-cache nil)
2469           (expand-local nil)
2470           ;; Because there is a bug I can't find just yet
2471           (inhibit-quit nil))
2472       (set-buffer speedbar-buffer)
2473       ;; If we are updating contents to where we are, then this is
2474       ;; really a request to update existing contents, so we must be
2475       ;; careful with our text cache!
2476       (if (member cbd speedbar-shown-directories)
2477           (progn
2478             (setq cache nil)
2479             ;; If the current directory is not the last element in the dir
2480             ;; list, then we ALSO need to zap the list of expanded directories
2481             (if (/= (length (member cbd speedbar-shown-directories)) 1)
2482                 (setq speedbar-shown-directories (list cbd))))
2483
2484         ;; Build cbd-parent, and see if THAT is in the current shown
2485         ;; directories.  First, go through pains to get the parent directory
2486         (if (and speedbar-smart-directory-expand-flag
2487                  (save-match-data
2488                    (setq cbd-parent cbd)
2489                    (if (string-match "[/\\]$" cbd-parent)
2490                        (setq cbd-parent (substring cbd-parent 0
2491                                                    (match-beginning 0))))
2492                    (setq cbd-parent (file-name-directory cbd-parent)))
2493                  (member cbd-parent speedbar-shown-directories))
2494             (setq expand-local t)
2495
2496           ;; If this directory is NOT in the current list of available
2497           ;; directorys, then use the cache, and set the cache to our new
2498           ;; value.  Make sure to unhighlight the current file, or if we
2499           ;; come back to this directory, it might be a different file
2500           ;; and then we get a mess!
2501           (if (> (point-max) 1)
2502               (progn
2503                 (speedbar-clear-current-file)
2504                 (setq speedbar-full-text-cache
2505                       (cons speedbar-shown-directories (buffer-string)))))
2506
2507           ;; Check if our new directory is in the list of directories
2508           ;; shown in the text-cache
2509           (if (member cbd (car cache))
2510               (setq speedbar-shown-directories (car cache)
2511                     use-cache t)
2512             ;; default the shown directories to this list...
2513             (setq speedbar-shown-directories (list cbd)))
2514           ))
2515       (if (not expand-local) (setq speedbar-last-selected-file nil))
2516       (speedbar-with-writable
2517         (if (and expand-local
2518                  ;; Find this directory as a speedbar node.
2519                  (speedbar-directory-line cbd))
2520             ;; Open it.
2521             (speedbar-expand-line)
2522           (erase-buffer)
2523           (cond (use-cache
2524                  (setq default-directory
2525                        (nth (1- (length speedbar-shown-directories))
2526                             speedbar-shown-directories))
2527                  (insert (cdr cache)))
2528                 (t
2529                  (while funclst
2530                    (setq default-directory cbd)
2531                    (funcall (car funclst) cbd 0)
2532                    (setq funclst (cdr funclst))))))
2533         (goto-char (point-min)))))
2534   (speedbar-reconfigure-keymaps))
2535
2536 (defun speedbar-update-special-contents ()
2537   "Use the mode-specific variable to fill in the speedbar buffer.
2538 This should only be used by modes classified as special."
2539   (let ((funclst speedbar-special-mode-expansion-list)
2540         (specialbuff (current-buffer)))
2541     (save-excursion
2542       (setq speedbar-desired-buffer specialbuff)
2543       (set-buffer speedbar-buffer)
2544       ;; If we are leaving a directory, cache it.
2545       (if (not speedbar-shown-directories)
2546           ;; Do nothing
2547           nil
2548         ;; Clean up directory maintenance stuff
2549         (speedbar-clear-current-file)
2550         (setq speedbar-full-text-cache
2551               (cons speedbar-shown-directories (buffer-string))
2552               speedbar-shown-directories nil))
2553       ;; Now fill in the buffer with our newly found specialized list.
2554       (speedbar-with-writable
2555         (while funclst
2556           ;; We do not erase the buffer because these functions may
2557           ;; decide NOT to update themselves.
2558           (funcall (car funclst) specialbuff)
2559           (setq funclst (cdr funclst))))
2560
2561       (goto-char (point-min))))
2562   (speedbar-reconfigure-keymaps))
2563
2564 (defun speedbar-set-timer (timeout)
2565   "Set up the speedbar timer with TIMEOUT.
2566 Uses `dframe-set-timer'.
2567 Also resets scanner functions."
2568   (dframe-set-timer timeout 'speedbar-timer-fn 'speedbar-update-flag)
2569   ;; Apply a revert hook that will reset the scanners.  We attach to revert
2570   ;; because most reverts occur during VC state change, and this lets our
2571   ;; VC scanner fix itself.
2572   (if timeout
2573       (add-hook 'after-revert-hook 'speedbar-reset-scanners)
2574     (remove-hook 'after-revert-hook 'speedbar-reset-scanners))
2575   ;; change this if it changed for some reason
2576   (speedbar-set-mode-line-format))
2577
2578 (defun speedbar-timer-fn ()
2579   "Run whenever Emacs is idle to update the speedbar item."
2580   (if (or (not (speedbar-current-frame))
2581           (not (frame-live-p (speedbar-current-frame))))
2582       (speedbar-set-timer nil)
2583     ;; Save all the match data so that we don't mess up executing fns
2584     (save-match-data
2585       ;; Only do stuff if the frame is visible, not an icon, and if
2586       ;; it is currently flagged to do something.
2587       (if (and speedbar-update-flag
2588                (speedbar-current-frame)
2589                (frame-visible-p (speedbar-current-frame))
2590                (not (eq (frame-visible-p (speedbar-current-frame)) 'icon)))
2591           (let ((af (selected-frame)))
2592             (save-window-excursion
2593               (dframe-select-attached-frame speedbar-frame)
2594               ;; make sure we at least choose a window to
2595               ;; get a good directory from
2596               (if (window-minibuffer-p (selected-window))
2597                   nil
2598                 ;; Check for special modes
2599                 (speedbar-maybe-add-localized-support (current-buffer))
2600                 ;; Update for special mode all the time!
2601                 (if (and speedbar-mode-specific-contents-flag
2602                          (listp speedbar-special-mode-expansion-list)
2603                          speedbar-special-mode-expansion-list
2604                          (local-variable-p
2605                           'speedbar-special-mode-expansion-list
2606                           (current-buffer)))
2607                     ;;(eq (get major-mode 'mode-class 'special)))
2608                     (progn
2609                       (if (<= 2 speedbar-verbosity-level)
2610                           (speedbar-message
2611                            "Updating speedbar to special mode: %s..."
2612                            major-mode))
2613                       (speedbar-update-special-contents)
2614                       (if (<= 2 speedbar-verbosity-level)
2615                           (progn
2616                             (speedbar-message
2617                              "Updating speedbar to special mode: %s...done"
2618                              major-mode)
2619                             (speedbar-message nil))))
2620                   ;; Update all the contents if directories change!
2621                   (if (or (member major-mode speedbar-ignored-modes)
2622                           (eq af (speedbar-current-frame))
2623                           (not (buffer-file-name)))
2624                       nil
2625                     (speedbar-update-localized-contents)
2626                     ))
2627                 (select-frame af)))
2628             ;; Now run stealthy updates of time-consuming items
2629             (speedbar-stealthy-updates)))))
2630   (run-hooks 'speedbar-timer-hook))
2631
2632 \f
2633 ;;; Stealthy activities
2634 ;;
2635 (defvar speedbar-stealthy-update-recurse nil
2636   "Recursion avoidance variable for stealthy update.")
2637
2638 (defun speedbar-stealthy-updates ()
2639   "For a given speedbar, run all items in the stealthy function list.
2640 Each item returns t if it completes successfully, or nil if
2641 interrupted by the user."
2642   (if (not speedbar-stealthy-update-recurse)
2643       (let ((l (speedbar-initial-stealthy-functions))
2644             (speedbar-stealthy-update-recurse t))
2645         (unwind-protect
2646             (speedbar-with-writable
2647               (while (and l (funcall (car l)))
2648                 ;;(sit-for 0)
2649                 (setq l (cdr l))))
2650           ;;(speedbar-message "Exit with %S" (car l))
2651           ))))
2652
2653 (defun speedbar-reset-scanners ()
2654   "Reset any variables used by functions in the stealthy list as state.
2655 If new functions are added, their state needs to be updated here."
2656   (setq speedbar-vc-to-do-point t
2657         speedbar-obj-to-do-point t
2658         speedbar-ro-to-do-point t)
2659   (run-hooks 'speedbar-scanner-reset-hook)
2660   )
2661
2662 (defun speedbar-find-selected-file (file)
2663   "Go to the line where FILE is."
2664
2665   (set-buffer speedbar-buffer)
2666   
2667   (goto-char (point-min))
2668   (let ((m nil))
2669     (while (and (setq m (re-search-forward
2670                          (concat " \\(" (regexp-quote (file-name-nondirectory file))
2671                                  "\\)\\(" speedbar-indicator-regex "\\)?\n")
2672                          nil t))
2673                 (not (string= file
2674                               (concat
2675                                (speedbar-line-directory
2676                                 (save-excursion
2677                                   (goto-char (match-beginning 0))
2678                                   (beginning-of-line)
2679                                   (save-match-data
2680                                     (looking-at "[0-9]+:")
2681                                     (string-to-number (match-string 0)))))
2682                                (match-string 1))))))
2683     (if m
2684         (progn
2685           (goto-char (match-beginning 1))
2686           (match-string 1)))))
2687
2688 (defun speedbar-clear-current-file ()
2689   "Locate the file thought to be current, and remove its highlighting."
2690   (save-excursion
2691     ;;(set-buffer speedbar-buffer)
2692     (if speedbar-last-selected-file
2693         (speedbar-with-writable
2694           (if (speedbar-find-selected-file speedbar-last-selected-file)
2695               (put-text-property (match-beginning 1)
2696                                  (match-end 1)
2697                                  'face
2698                                  'speedbar-file-face))))))
2699
2700 (defun speedbar-update-current-file ()
2701   "Find the current file, and update our visuals to indicate its name.
2702 This is specific to file names.  If the file name doesn't show up, but
2703 it should be in the list, then the directory cache needs to be
2704 updated."
2705   (let* ((lastf (selected-frame))
2706          (newcfd (save-excursion
2707                    (dframe-select-attached-frame speedbar-frame)
2708                    (let ((rf (if (buffer-file-name)
2709                                  (buffer-file-name)
2710                                nil)))
2711                      (select-frame lastf)
2712                      rf)))
2713          (newcf (if newcfd newcfd))
2714          (lastb (current-buffer))
2715          (sucf-recursive (boundp 'sucf-recursive))
2716          (case-fold-search t))
2717     (if (and newcf
2718              ;; check here, that way we won't refresh to newcf until
2719              ;; its been written, thus saving ourselves some time
2720              (file-exists-p newcf)
2721              (not (string= newcf speedbar-last-selected-file)))
2722         (progn
2723           ;; It is important to select the frame, otherwise the window
2724           ;; we want the cursor to move in will not be updated by the
2725           ;; search-forward command.
2726           (select-frame (speedbar-current-frame))
2727           ;; Remove the old file...
2728           (speedbar-clear-current-file)
2729           ;; now highlight the new one.
2730           ;; (set-buffer speedbar-buffer)
2731           (speedbar-with-writable
2732             (if (speedbar-find-selected-file newcf)
2733                 ;; put the property on it
2734                 (put-text-property (match-beginning 1)
2735                                    (match-end 1)
2736                                    'face
2737                                    'speedbar-selected-face)
2738               ;; Oops, it's not in the list.  Should it be?
2739               (if (and (string-match speedbar-file-regexp newcf)
2740                        (string= (file-name-directory newcfd)
2741                                 (expand-file-name default-directory)))
2742                   ;; yes, it is (we will ignore unknowns for now...)
2743                   (progn
2744                     (speedbar-refresh)
2745                     (if (speedbar-find-selected-file newcf)
2746                         ;; put the property on it
2747                         (put-text-property (match-beginning 1)
2748                                            (match-end 1)
2749                                            'face
2750                                            'speedbar-selected-face)))
2751                 ;; if it's not in there now, whatever...
2752                 ))
2753             (setq speedbar-last-selected-file newcf))
2754           (if (not sucf-recursive)
2755               (progn
2756
2757                 ;;Sat Dec 15 2001 12:40 AM (burton@openprivacy.org): this
2758                 ;;doesn't need to be in.  We don't want to recenter when we are
2759                 ;;updating files.
2760
2761                 ;;(speedbar-center-buffer-smartly)
2762
2763                 (speedbar-position-cursor-on-line)
2764                 ))
2765           (set-buffer lastb)
2766           (select-frame lastf)
2767           )))
2768   ;; return that we are done with this activity.
2769   t)
2770
2771 (defun speedbar-add-indicator (indicator-string &optional replace-this)
2772   "Add INDICATOR-STRING to the end of this speedbar line.
2773 If INDICATOR-STRING is space, and REPLACE-THIS is a character, then
2774 the existing indicator is removed.  If there is already an
2775 indicator, then do not add a space."
2776   (beginning-of-line)
2777   ;; The nature of the beast: Assume we are in "the right place"
2778   (end-of-line)
2779   (skip-chars-backward (concat " " speedbar-vc-indicator
2780                                speedbar-object-read-only-indicator
2781                                (car speedbar-obj-indicator)
2782                                (cdr speedbar-obj-indicator)))
2783   (if (and (not (looking-at speedbar-indicator-regex))
2784            (not (string= indicator-string " ")))
2785       (insert speedbar-indicator-separator))
2786   (speedbar-with-writable
2787     (save-excursion
2788       (if (and replace-this
2789                (re-search-forward replace-this (save-excursion (end-of-line)
2790                                                                (point))
2791                                   t))
2792           (delete-region (match-beginning 0) (match-end 0))))
2793     (end-of-line)
2794     (if (not (string= " " indicator-string))
2795         (let ((start (point)))
2796           (insert indicator-string)
2797           (speedbar-insert-image-button-maybe start (length indicator-string))
2798           ))))
2799
2800 (defun speedbar-check-read-only ()
2801   "Scan all the files in a directory, and for each see if it is read only."
2802   ;; Check for to-do to be reset.  If reset but no RCS is available
2803   ;; then set to nil (do nothing) otherwise, start at the beginning
2804   (save-excursion
2805     (if speedbar-buffer (set-buffer speedbar-buffer))
2806     (if (eq speedbar-ro-to-do-point t)
2807         (setq speedbar-ro-to-do-point 0))
2808     (if (numberp speedbar-ro-to-do-point)
2809         (progn
2810           (goto-char speedbar-ro-to-do-point)
2811           (while (and (not (input-pending-p))
2812                       (re-search-forward "^\\([0-9]+\\):\\s-*[[<][+-\?][]>] "
2813                                          nil t))
2814             (setq speedbar-ro-to-do-point (point))
2815             (if (not (file-writable-p (speedbar-line-file)))
2816                 (speedbar-add-indicator
2817                  speedbar-object-read-only-indicator
2818                  (regexp-quote speedbar-object-read-only-indicator))
2819               (speedbar-add-indicator
2820                " " (regexp-quote speedbar-object-read-only-indicator))))
2821           (if (input-pending-p)
2822               ;; return that we are incomplete
2823               nil
2824             ;; we are done, set to-do to nil
2825             (setq speedbar-ro-to-do-point nil)
2826             ;; and return t
2827             t))
2828       t)))
2829
2830 ;; Load efs/ange-ftp only if compiling to remove byte-compiler warnings.
2831 ;; Steven L Baur <steve@xemacs.org> said this was important:
2832 (eval-when-compile (or (featurep 'xemacs)
2833                        (condition-case () (require 'efs)
2834                          (error (require 'ange-ftp)))))
2835
2836 (defun speedbar-check-vc ()
2837   "Scan all files in a directory, and for each see if it's checked out.
2838 See `speedbar-this-file-in-vc' and `speedbar-vc-check-dir-p' for how
2839 to add more types of version control systems."
2840   ;; Check for to-do to be reset.  If reset but no RCS is available
2841   ;; then set to nil (do nothing) otherwise, start at the beginning
2842   (save-excursion
2843     (if speedbar-buffer (set-buffer speedbar-buffer))
2844     (if (and speedbar-vc-do-check (eq speedbar-vc-to-do-point t)
2845              (speedbar-vc-check-dir-p default-directory)
2846              (not (or (and (featurep 'ange-ftp)
2847                            (string-match
2848                             (car (if dframe-xemacsp
2849                                      ange-ftp-directory-format
2850                                    ange-ftp-name-format))
2851                             (expand-file-name default-directory)))
2852                       ;; efs support: Bob Weiner
2853                       (and (featurep 'efs)
2854                            (string-match
2855                             (if (stringp efs-directory-regexp)
2856                                 efs-directory-regexp
2857                               (car efs-directory-regexp))
2858                             (expand-file-name default-directory))))))
2859         (setq speedbar-vc-to-do-point 0))
2860     (if (numberp speedbar-vc-to-do-point)
2861         (progn
2862           (goto-char speedbar-vc-to-do-point)
2863           (while (and (not (input-pending-p))
2864                       (re-search-forward "^\\([0-9]+\\):\\s-*\\[[+-?]\\] "
2865                                          nil t))
2866             (setq speedbar-vc-to-do-point (point))
2867             (if (speedbar-check-vc-this-line (match-string 1))
2868                 (speedbar-add-indicator speedbar-vc-indicator
2869                                         (regexp-quote speedbar-vc-indicator))
2870               (speedbar-add-indicator " "
2871                                       (regexp-quote speedbar-vc-indicator))))
2872           (if (input-pending-p)
2873               ;; return that we are incomplete
2874               nil
2875             ;; we are done, set to-do to nil
2876             (setq speedbar-vc-to-do-point nil)
2877             ;; and return t
2878             t))
2879       t)))
2880
2881 (defun speedbar-check-vc-this-line (depth)
2882   "Return t if the file on this line is check of of a version control system.
2883 Parameter DEPTH is a string with the current depth of indentation of
2884 the file being checked."
2885   (let* ((d (string-to-int depth))
2886          (f (speedbar-line-directory d))
2887          (fn (buffer-substring-no-properties
2888               ;; Skip-chars: thanks ptype@dra.hmg.gb
2889               (point) (progn
2890                         (skip-chars-forward "^ "
2891                                             (save-excursion (end-of-line)
2892                                                             (point)))
2893                         (point))))
2894          (fulln (concat f fn)))
2895     (if (<= 2 speedbar-verbosity-level)
2896         (speedbar-message "Speedbar vc check...%s" fulln))
2897     (and (file-writable-p fulln)
2898          (speedbar-this-file-in-vc f fn))))
2899
2900 (defun speedbar-vc-check-dir-p (directory)
2901   "Return t if we should bother checking DIRECTORY for version control files.
2902 This can be overloaded to add new types of version control systems."
2903   (or
2904    ;; Local CVS available in Emacs 21
2905    (and (fboundp 'vc-state)
2906         (file-exists-p (concat directory "CVS/")))
2907    ;; Local RCS
2908    (file-exists-p (concat directory "RCS/"))
2909    ;; Local SCCS
2910    (file-exists-p (concat directory "SCCS/"))
2911    ;; Remote SCCS project
2912    (let ((proj-dir (getenv "PROJECTDIR")))
2913      (if proj-dir
2914          (file-exists-p (concat proj-dir "/SCCS"))
2915        nil))
2916    ;; User extension
2917    (run-hook-with-args-until-success 'speedbar-vc-directory-enable-hook
2918                                      directory)
2919    ))
2920
2921 (defun speedbar-this-file-in-vc (directory name)
2922   "Check to see if the file in DIRECTORY with NAME is in a version control system.
2923 You can add new VC systems by overriding this function.  You can
2924 optimize this function by overriding it and only doing those checks
2925 that will occur on your system."
2926   (or
2927    (if (fboundp 'vc-state)
2928        ;; Emacs 21 handles VC state in a nice way.
2929        (condition-case nil
2930            (let ((state  (vc-state (concat directory name))))
2931              (not (or (eq 'up-to-date state)
2932                       (null state))))
2933          ;; An error means not in a VC system
2934          (error nil))
2935      (or
2936       ;; RCS file name
2937       (file-exists-p (concat directory "RCS/" name ",v"))
2938       (file-exists-p (concat directory "RCS/" name))
2939       ;; Local SCCS file name
2940       (file-exists-p (concat directory "SCCS/s." name))
2941       ;; Remote SCCS file name
2942       (let ((proj-dir (getenv "PROJECTDIR")))
2943         (if proj-dir
2944             (file-exists-p (concat proj-dir "/SCCS/s." name))
2945           nil))))
2946    ;; User extension
2947    (run-hook-with-args 'speedbar-vc-in-control-hook directory name)
2948    ))
2949
2950 ;; Objet File scanning
2951 (defun speedbar-check-objects ()
2952   "Scan all files in a directory, and for each see if there is an object.
2953 See `speedbar-check-obj-this-line' and `speedbar-obj-alist' for how
2954 to add more object types."
2955   ;; Check for to-do to be reset.  If reset but no RCS is available
2956   ;; then set to nil (do nothing) otherwise, start at the beginning
2957   (save-excursion
2958     (if speedbar-buffer (set-buffer speedbar-buffer))
2959     (if (and speedbar-obj-do-check (eq speedbar-obj-to-do-point t))
2960         (setq speedbar-obj-to-do-point 0))
2961     (if (numberp speedbar-obj-to-do-point)
2962         (progn
2963           (goto-char speedbar-obj-to-do-point)
2964           (while (and (not (input-pending-p))
2965                       (re-search-forward "^\\([0-9]+\\):\\s-*\\[[+-]\\] "
2966                                          nil t))
2967             (setq speedbar-obj-to-do-point (point))
2968             (let ((ind (speedbar-check-obj-this-line (match-string 1))))
2969               (if (not ind) (setq ind " "))
2970               (speedbar-add-indicator ind (concat
2971                                            (car speedbar-obj-indicator)
2972                                            "\\|"
2973                                            (cdr speedbar-obj-indicator)))))
2974           (if (input-pending-p)
2975               ;; return that we are incomplete
2976               nil
2977             ;; we are done, set to-do to nil
2978             (setq speedbar-obj-to-do-point nil)
2979             ;; and return t
2980             t))
2981       t)))
2982
2983 (defun speedbar-check-obj-this-line (depth)
2984   "Return t if the file on this line has an associated object.
2985 Parameter DEPTH is a string with the current depth of indentation of
2986 the file being checked."
2987   (let* ((d (string-to-int depth))
2988          (f (speedbar-line-directory d))
2989          (fn (buffer-substring-no-properties
2990               ;; Skip-chars: thanks ptype@dra.hmg.gb
2991               (point) (progn
2992                         (skip-chars-forward "^ "
2993                                             (save-excursion (end-of-line)
2994                                                             (point)))
2995                         (point))))
2996          (fulln (concat f fn)))
2997     (if (<= 2 speedbar-verbosity-level)
2998         (speedbar-message "Speedbar obj check...%s" fulln))
2999     (let ((oa speedbar-obj-alist))
3000       (while (and oa (not (string-match (car (car oa)) fulln)))
3001         (setq oa (cdr oa)))
3002       (if (not (and oa (file-exists-p (concat (file-name-sans-extension fulln)
3003                                               (cdr (car oa))))))
3004           nil
3005         ;; Find out if the object is out of date or not.
3006         (let ((date1 (nth 5 (file-attributes fulln)))
3007               (date2 (nth 5 (file-attributes (concat
3008                                               (file-name-sans-extension fulln)
3009                                               (cdr (car oa)))))))
3010           (if (or (< (car date1) (car date2))
3011                   (and (= (car date1) (car date2))
3012                        (< (nth 1 date1) (nth 1 date2))))
3013               (car speedbar-obj-indicator)
3014             (cdr speedbar-obj-indicator)))))))
3015 \f
3016 ;;; Clicking Activity
3017 ;;
3018 (defun speedbar-position-cursor-on-line ()
3019   "Position the cursor on a line."
3020   (let ((oldpos (point)))
3021     (beginning-of-line)
3022     (if (looking-at "[0-9]+:\\s-*..?.? ")
3023         (goto-char (1- (match-end 0)))
3024       (goto-char oldpos))))
3025
3026 (defun speedbar-click (e)
3027   "Activate any speedbar buttons where the mouse is clicked.
3028 This must be bound to a mouse event.  A button is any location of text
3029 with a mouse face that has a text property called `speedbar-function'.
3030 Argument E is the click event."
3031   ;; Backward compatibility let statement.
3032   (let ((speedbar-power-click dframe-power-click))
3033     (speedbar-do-function-pointer))
3034   (dframe-quick-mouse e))
3035
3036 (defun speedbar-do-function-pointer ()
3037   "Look under the cursor and examine the text properties.
3038 From this extract the file/tag name, token, indentation level and call
3039 a function if appropriate."
3040   (let* ((speedbar-frame (speedbar-current-frame))
3041          (fn (get-text-property (point) 'speedbar-function))
3042          (tok (get-text-property (point) 'speedbar-token))
3043          ;; The 1-,+ is safe because scaning starts AFTER the point
3044          ;; specified.  This lets the search include the character the
3045          ;; cursor is on.
3046          (tp (previous-single-property-change
3047               (1+ (point)) 'speedbar-function))
3048          (np (next-single-property-change
3049               (point) 'speedbar-function))
3050          (txt (buffer-substring-no-properties (or tp (point-min))
3051                                               (or np (point-max))))
3052          (dent (save-excursion (beginning-of-line)
3053                                (string-to-number
3054                                 (if (looking-at "[0-9]+")
3055                                     (buffer-substring-no-properties
3056                                     (match-beginning 0) (match-end 0))
3057                                   "0")))))
3058     ;;(speedbar-message "%S:%S:%S:%s" fn tok txt dent)
3059     (and fn (funcall fn txt tok dent)))
3060   (speedbar-position-cursor-on-line))
3061 \f
3062 ;;; Reading info from the speedbar buffer
3063 ;;
3064 (defun speedbar-line-text (&optional p)
3065   "Retrieve the text after prefix junk for the current line.
3066 Optional argument P is where to start the search from."
3067   (save-excursion
3068     (if p (goto-char p))
3069     (beginning-of-line)
3070     (if (looking-at (concat
3071                      "\\([0-9]+\\): *[[<{]?[-+?= ][]>}@()|] \\([^ \n]+\\)"))
3072         (get-text-property (match-beginning 2) 'speedbar-text)
3073       nil)))
3074
3075 (defun speedbar-line-token (&optional p)
3076   "Retrieve the token information after the prefix junk for the current line.
3077 Optional argument P is where to start the search from."
3078   (save-excursion
3079     (if p (goto-char p))
3080     (beginning-of-line)
3081     (if (looking-at (concat
3082                      "\\([0-9]+\\): *[[<{]?[-+?= ][]>}@()|] \\([^ \n]+\\)\\("
3083                      speedbar-indicator-regex "\\)?"))
3084         (progn
3085           (goto-char (match-beginning 2))
3086           (get-text-property (point) 'speedbar-token))
3087       nil)))
3088
3089 (defun speedbar-line-file (&optional p)
3090   "Retrieve the file or whatever from the line at point P.
3091 The return value is a string representing the file.  If it is a
3092 directory, then it is the directory name."
3093   (save-match-data
3094     (save-restriction
3095       (widen)
3096       (let ((f (speedbar-line-text p)))
3097         (if f
3098             (let* ((depth (string-to-int (match-string 1)))
3099                    (directory (speedbar-line-directory depth)))
3100               (cond ((and (file-directory-p directory)
3101                           (file-exists-p (concat directory f)))
3102                      ;; if directory is a directory, and adding
3103                      ;; f to it makes it a file.
3104                      (concat directory f))
3105                     ((and (not (file-directory-p directory))
3106                           (file-exists-p directory))
3107                      ;; if directory isn't a directory, but it
3108                      ;; does exist, then it is our file.
3109                      directory)
3110                     (t nil)))
3111           nil)))))
3112
3113 (defun speedbar-goto-this-file (file)
3114   "If FILE is displayed, go to this line and return t.
3115 Otherwise do not move and return nil."
3116   (let ((directory (substring (file-name-directory (expand-file-name file))
3117                          (length (expand-file-name default-directory))))
3118         (dest (point)))
3119     (save-match-data
3120       (goto-char (point-min))
3121       ;; scan all the directories
3122       (while (and directory (not (eq directory t)))
3123         (if (string-match "^[/\\]?\\([^/\\]+\\)" directory)
3124             (let ((pp (match-string 1 directory)))
3125               (if (save-match-data
3126                     (re-search-forward (concat "> " (regexp-quote pp) "$")
3127                                        nil t))
3128                   (setq directory (substring directory (match-end 1)))
3129                 (setq directory nil)))
3130           (setq directory t)))
3131       ;; find the file part
3132       (if (or (not directory) (string= (file-name-nondirectory file) ""))
3133           ;; only had a dir part
3134           (if directory
3135               (progn
3136                 (speedbar-position-cursor-on-line)
3137                 t)
3138             (goto-char dest) nil)
3139         ;; find the file part
3140         (let ((nd (file-name-nondirectory file)))
3141           (if (re-search-forward
3142                (concat "] \\(" (regexp-quote nd)
3143                        "\\)\\(" speedbar-indicator-regex "\\)$")
3144                nil t)
3145               (progn
3146                 (speedbar-position-cursor-on-line)
3147                 t)
3148             (goto-char dest)
3149             nil))))))
3150
3151 (defun speedbar-line-directory (&optional depth)
3152   "Retrieve the directoryname associated with the current line.
3153 This may require traversing backwards from DEPTH and combining the default
3154 directory with these items.  This function is replaceable in
3155 `speedbar-mode-functions-list' as `speedbar-line-directory'."
3156   (save-restriction
3157     (widen)
3158     (let ((rf (speedbar-fetch-replacement-function 'speedbar-line-directory)))
3159       (if rf (funcall rf depth) default-directory))))
3160       
3161 (defun speedbar-files-line-directory (&optional depth)
3162   "Retrieve the directoryname associated with the current line.
3163 This may require traversing backwards from DEPTH and combining the default
3164 directory with these items."
3165   (save-excursion
3166     (save-match-data
3167       (if (not depth)
3168           (progn
3169             (beginning-of-line)
3170             (looking-at "^\\([0-9]+\\):")
3171             (setq depth (string-to-int (match-string 1)))))
3172       (let ((directory nil))
3173         (setq depth (1- depth))
3174         (while (/= depth -1)
3175           (if (not (re-search-backward (format "^%d:" depth) nil t))
3176               (error "Error building filename of tag")
3177             (cond ((looking-at "[0-9]+:\\s-*<->\\s-+\\([^\n]+\\)")
3178                    (setq directory (concat (speedbar-line-text)
3179                                       "/"
3180                                       directory)))
3181                   ((looking-at "[0-9]+:\\s-*[-]\\s-+\\([^\n]+\\)")
3182                    ;; This is the start of our directory.
3183                    (setq directory (speedbar-line-text)))))
3184           (setq depth (1- depth)))
3185         (if (and directory
3186                  (string-match (concat speedbar-indicator-regex "$")
3187                                directory))
3188             (setq directory (substring directory 0 (match-beginning 0))))
3189         (concat default-directory directory)))))
3190
3191 (defun speedbar-directory-line (directory)
3192   "Position the cursor on the line specified by DIRECTORY."
3193   (save-match-data
3194     (if (string-match "[/\\]$" directory)
3195         (setq directory (substring directory 0 (match-beginning 0))))
3196     (let ((nomatch t) (depth 0)
3197           (fname (file-name-nondirectory directory))
3198           (pname (file-name-directory directory)))
3199       (if (not (member pname speedbar-shown-directories))
3200           (error "Internal Error: File %s not shown in speedbar" directory))
3201       (goto-char (point-min))
3202       (while (and nomatch
3203                   (re-search-forward
3204                    (concat "[]>] \\(" (regexp-quote fname)
3205                            "\\)\\(" speedbar-indicator-regex "\\)?$")
3206                    nil t))
3207         (beginning-of-line)
3208         (looking-at "\\([0-9]+\\):")
3209         (setq depth (string-to-int (match-string 0))
3210               nomatch (not (string= pname (speedbar-line-directory depth))))
3211         (end-of-line))
3212       (beginning-of-line)
3213       (not nomatch))))
3214
3215 (defun speedbar-edit-line ()
3216   "Edit whatever tag or file is on the current speedbar line."
3217   (interactive)
3218   (or (save-excursion
3219         (beginning-of-line)
3220         ;; If this fails, then it is a non-standard click, and as such,
3221         ;; perfectly allowed.
3222         (if (re-search-forward "[]>?}] [^ ]"
3223                                (save-excursion (end-of-line) (point))
3224                                t)
3225             (progn
3226               (forward-char -1)
3227               (speedbar-do-function-pointer))
3228           nil))
3229       (speedbar-do-function-pointer)))
3230
3231 (defun speedbar-expand-line (&optional arg)
3232   "Expand the line under the cursor.
3233 With universal argument ARG, flush cached data."
3234   (interactive "P")
3235   (beginning-of-line)
3236   (let* ((dframe-power-click arg)
3237          (speedbar-power-click arg))
3238     (condition-case nil
3239         (progn
3240           (re-search-forward ":\\s-*.\\+. "
3241                              (save-excursion (end-of-line) (point)))
3242           (forward-char -2)
3243           (speedbar-do-function-pointer))
3244       (error (speedbar-position-cursor-on-line)))))
3245   
3246 (defun speedbar-flush-expand-line ()
3247   "Expand the line under the cursor and flush any cached information."
3248   (interactive)
3249   (speedbar-expand-line 1))
3250   
3251 (defun speedbar-contract-line ()
3252   "Contract the line under the cursor."
3253   (interactive)
3254   (beginning-of-line)
3255   (condition-case nil
3256       (progn
3257         (re-search-forward ":\\s-*.-. "
3258                            (save-excursion (end-of-line) (point)))
3259         (forward-char -2)
3260         (speedbar-do-function-pointer))
3261     (error (speedbar-position-cursor-on-line))))
3262
3263 (defun speedbar-toggle-line-expansion ()
3264   "Contract or expand the line under the cursor."
3265   (interactive)
3266   (beginning-of-line)
3267   (condition-case nil
3268       (progn
3269         (re-search-forward ":\\s-*.[-+]. "
3270                            (save-excursion (end-of-line) (point)))
3271         (forward-char -2)
3272         (speedbar-do-function-pointer))
3273     (error (speedbar-position-cursor-on-line))))
3274
3275 (defun speedbar-expand-line-descendants (&optional arg)
3276   "Expand the line under the cursor and all descendants.
3277 Optional argument ARG indicates that any cache should be flushed."
3278   (interactive "P")
3279   (speedbar-expand-line arg)
3280   ;; Now, inside the area expaded here, expand all subnodes of
3281   ;; the same descendant type.
3282   (save-excursion
3283     (speedbar-next 1) ;; Move into the list.
3284     (let ((err nil))
3285       (while (not err)
3286         (condition-case nil
3287             (progn
3288               (speedbar-expand-line-descendants arg)
3289               (speedbar-restricted-next 1))
3290           (error (setq err t))))))
3291   )
3292
3293 (defun speedbar-contract-line-descendants ()
3294   "Expand the line under the cursor and all descendants."
3295   (interactive)
3296   (speedbar-contract-line)
3297   ;; Don't need to do anything else since all descendants are
3298   ;; hidden by default anyway.  Yay!  It's easy.
3299   )
3300
3301 (defun speedbar-find-file (text token indent)
3302   "Speedbar click handler for filenames.
3303 TEXT, the file will be displayed in the attached frame.
3304 TOKEN is unused, but required by the click handler.  INDENT is the
3305 current indentation level."
3306   (let ((cdd (speedbar-line-directory indent)))
3307     ;; Run before visiting file hook here.
3308     (let ((f (selected-frame)))
3309       (dframe-select-attached-frame speedbar-frame)
3310       (run-hooks 'speedbar-before-visiting-file-hook)
3311       (select-frame f))
3312     (speedbar-find-file-in-frame (concat cdd text))
3313     (speedbar-stealthy-updates)
3314     (run-hooks 'speedbar-visiting-file-hook)
3315     ;; Reset the timer with a new timeout when cliking a file
3316     ;; in case the user was navigating directories, we can cancel
3317     ;; that other timer.
3318     (speedbar-set-timer dframe-update-speed))
3319   (dframe-maybee-jump-to-attached-frame))
3320
3321 (defun speedbar-dir-follow (text token indent)
3322   "Speedbar click handler for directory names.
3323 Clicking a directory will cause the speedbar to list files in
3324 the subdirectory TEXT.  TOKEN is an unused requirement.  The
3325 subdirectory chosen will be at INDENT level."
3326   (setq default-directory
3327         (concat (expand-file-name (concat (speedbar-line-directory indent) text))
3328                 "/"))
3329   ;; Because we leave speedbar as the current buffer,
3330   ;; update contents will change directory without
3331   ;; having to touch the attached frame.  Turn off smart expand just
3332   ;; in case.
3333   (let ((speedbar-smart-directory-expand-flag nil))
3334     (speedbar-update-contents))
3335   (speedbar-set-timer speedbar-navigating-speed)
3336   (setq speedbar-last-selected-file nil)
3337   (speedbar-stealthy-updates))
3338
3339 (defun speedbar-delete-subblock (indent)
3340   "Delete text from point to indentation level INDENT or greater.
3341 Handles end-of-sublist smartly."
3342   (speedbar-with-writable
3343     (save-excursion
3344       (end-of-line) (forward-char 1)
3345       (let ((start (point)))
3346         (while (and (looking-at "^\\([0-9]+\\):")
3347                     (> (string-to-int (match-string 1)) indent)
3348                     (not (eobp)))
3349           (forward-line 1)
3350           (beginning-of-line))
3351         (delete-region start (point))))))
3352
3353 (defun speedbar-dired (text token indent)
3354   "Speedbar click handler for directory expand button.
3355 Clicking this button expands or contracts a directory.  TEXT is the
3356 button clicked which has either a + or -.  TOKEN is the directory to be
3357 expanded.  INDENT is the current indentation level."
3358   (cond ((string-match "+" text)        ;we have to expand this dir
3359          (setq speedbar-shown-directories
3360                (cons (expand-file-name
3361                       (concat (speedbar-line-directory indent) token "/"))
3362                      speedbar-shown-directories))
3363          (speedbar-change-expand-button-char ?-)
3364          (speedbar-reset-scanners)
3365          (save-excursion
3366            (end-of-line) (forward-char 1)
3367            (speedbar-with-writable
3368              (speedbar-default-directory-list
3369               (concat (speedbar-line-directory indent) token "/")
3370               (1+ indent)))))
3371         ((string-match "-" text)        ;we have to contract this node
3372          (speedbar-reset-scanners)
3373          (let ((oldl speedbar-shown-directories)
3374                (newl nil)
3375                (td (expand-file-name
3376                     (concat (speedbar-line-directory indent) token))))
3377            (while oldl
3378              (if (not (string-match (concat "^" (regexp-quote td)) (car oldl)))
3379                  (setq newl (cons (car oldl) newl)))
3380              (setq oldl (cdr oldl)))
3381            (setq speedbar-shown-directories (nreverse newl)))
3382          (speedbar-change-expand-button-char ?+)
3383          (speedbar-delete-subblock indent)
3384          )
3385         (t (error "Ooops...  not sure what to do")))
3386   (speedbar-center-buffer-smartly)
3387   (save-excursion (speedbar-stealthy-updates)))
3388
3389 (defun speedbar-directory-buttons-follow (text token indent)
3390   "Speedbar click handler for default directory buttons.
3391 TEXT is the button clicked on.  TOKEN is the directory to follow.
3392 INDENT is the current indentation level and is unused."
3393   (if (string-match "^[A-z]:$" token)
3394       (setq default-directory (concat token "/"))
3395     (setq default-directory token))
3396   ;; Because we leave speedbar as the current buffer,
3397   ;; update contents will change directory without
3398   ;; having to touch the attached frame.
3399   (speedbar-update-contents)
3400   (speedbar-set-timer speedbar-navigating-speed))
3401
3402 (defun speedbar-tag-file (text token indent)
3403   "The cursor is on a selected line.  Expand the tags in the specified file.
3404 The parameter TEXT and TOKEN are required, where TEXT is the button
3405 clicked, and TOKEN is the file to expand.  INDENT is the current
3406 indentation level."
3407   (cond ((string-match "+" text)        ;we have to expand this file
3408          (let* ((fn (expand-file-name (concat (speedbar-line-directory indent)
3409                                               token)))
3410                 (mode nil)
3411                 (lst (speedbar-fetch-dynamic-tags fn)))
3412            ;; if no list, then remove expando button
3413            (if (not lst)
3414                (speedbar-change-expand-button-char ??)
3415              (speedbar-change-expand-button-char ?-)
3416              (speedbar-with-writable
3417                (save-excursion
3418                  (end-of-line) (forward-char 1)
3419                  (funcall (car lst) indent (cdr lst)))))))
3420         ((string-match "-" text)        ;we have to contract this node
3421          (speedbar-change-expand-button-char ?+)
3422          (speedbar-delete-subblock indent))
3423         (t (error "Ooops...  not sure what to do")))
3424   (speedbar-center-buffer-smartly))
3425
3426 (defun speedbar-tag-find (text token indent)
3427   "For the tag TEXT in a file TOKEN, go to that position.
3428 INDENT is the current indentation level."
3429   (let ((file (speedbar-line-directory indent)))
3430     (let ((f (selected-frame)))
3431       (dframe-select-attached-frame speedbar-frame)
3432       (run-hooks 'speedbar-before-visiting-tag-hook)
3433       (select-frame f))
3434     (speedbar-find-file-in-frame file)
3435     (save-excursion (speedbar-stealthy-updates))
3436     ;; Reset the timer with a new timeout when cliking a file
3437     ;; in case the user was navigating directories, we can cancel
3438     ;; that other timer.
3439     (speedbar-set-timer dframe-update-speed)
3440     (goto-char token)
3441     (run-hooks 'speedbar-visiting-tag-hook)
3442     (dframe-maybee-jump-to-attached-frame)
3443     ))
3444
3445 (defun speedbar-tag-expand (text token indent)
3446   "Expand a tag sublist.  Imenu will return sub-lists of specialized tag types.
3447 Etags does not support this feature.  TEXT will be the button
3448 string.  TOKEN will be the list, and INDENT is the current indentation
3449 level."
3450   (cond ((string-match "+" text)        ;we have to expand this file
3451          (speedbar-change-expand-button-char ?-)
3452          (speedbar-with-writable
3453            (save-excursion
3454              (end-of-line) (forward-char 1)
3455              (speedbar-insert-generic-list indent token 'speedbar-tag-expand
3456                                            'speedbar-tag-find))))
3457         ((string-match "-" text)        ;we have to contract this node
3458          (speedbar-change-expand-button-char ?+)
3459          (speedbar-delete-subblock indent))
3460         (t (error "Ooops...  not sure what to do")))
3461   (speedbar-center-buffer-smartly))
3462 \f
3463 ;;; Loading files into the attached frame.
3464 ;;
3465 (defcustom speedbar-select-frame-method 'attached
3466   "*Specify how to select a frame for displaying a file.
3467 A value of 'attached means to use the attached frame (the frame
3468 that speedbar was started from.)  A number such as 1 or -1 means to
3469 pass that number to `other-frame' while selecting a frame from speedbar."
3470   :group 'speedbar
3471   :type 'sexp)
3472
3473 (defun speedbar-find-file-in-frame (file)
3474   "This will load FILE into the speedbar attached frame.
3475 If the file is being displayed in a different frame already, then raise that
3476 frame instead."
3477   (let* ((buff (find-file-noselect file))
3478          (bwin (get-buffer-window buff 0)))
3479     (if bwin
3480         (progn
3481           (select-window bwin)
3482           (raise-frame (window-frame bwin)))
3483       (if dframe-power-click
3484           (let ((pop-up-frames t)) (select-window (display-buffer buff)))
3485         (if (numberp speedbar-select-frame-method)
3486             (other-frame speedbar-select-frame-method)
3487           (dframe-select-attached-frame speedbar-frame))
3488         (switch-to-buffer buff))))
3489  )
3490
3491 ;;; Centering Utility
3492 ;;
3493 (defun speedbar-center-buffer-smartly ()
3494   "Recenter a speedbar buffer so the current indentation level is all visible.
3495 This assumes that the cursor is on a file, or tag of a file which the user is
3496 interested in."
3497
3498   (save-selected-window
3499   
3500     (select-window (get-buffer-window speedbar-buffer t))
3501     
3502     (set-buffer speedbar-buffer)
3503     
3504     (if (<= (count-lines (point-min) (point-max))
3505             (1- (window-height (selected-window))))
3506         ;; whole buffer fits
3507         (let ((cp (point)))
3508
3509           (goto-char (point-min))
3510           (recenter 0)
3511           (goto-char cp))
3512       ;; too big
3513       (let (depth start end exp p)
3514         (save-excursion
3515           (beginning-of-line)
3516           (setq depth (if (looking-at "[0-9]+")
3517                           (string-to-int (buffer-substring-no-properties
3518                                           (match-beginning 0) (match-end 0)))
3519                         0))
3520           (setq exp (format "^%d:" depth)))
3521         (save-excursion
3522           (end-of-line)
3523           (if (re-search-backward exp nil t)
3524               (setq start (point))
3525             (setq start (point-min)))
3526           (save-excursion               ;Not sure about this part.
3527             (end-of-line)
3528             (setq p (point))
3529             (while (and (not (re-search-forward exp nil t))
3530                         (>= depth 0))
3531               (setq depth (1- depth))
3532               (setq exp (format "^%d:" depth)))
3533             (if (/= (point) p)
3534                 (setq end (point))
3535               (setq end (point-max)))))
3536         ;; Now work out the details of centering
3537         (let ((nl (count-lines start end))
3538               (wl (1- (window-height (selected-window))))
3539               (cp (point)))
3540           (if (> nl wl)
3541               ;; We can't fit it all, so just center on cursor
3542               (progn (goto-char start)
3543                      (recenter 1))
3544             ;; we can fit everything on the screen, but...
3545             (if (and (pos-visible-in-window-p start (selected-window))
3546                      (pos-visible-in-window-p end (selected-window)))
3547                 ;; we are all set!
3548                 nil
3549               ;; we need to do something...
3550               (goto-char start)
3551               (let ((newcent (/ (- (window-height (selected-window)) nl) 2))
3552                     (lte (count-lines start (point-max))))
3553                 (if (and (< (+ newcent lte) (window-height (selected-window)))
3554                          (> (- (window-height (selected-window)) lte 1)
3555                             newcent))
3556                     (setq newcent (- (window-height (selected-window))
3557                                      lte 1)))
3558                 (recenter newcent))))
3559           (goto-char cp))))))
3560 \f
3561 ;;; Tag Management -- List of expanders:
3562 ;;
3563 (defun speedbar-fetch-dynamic-tags (file)
3564   "Return a list of tags generated dynamically from FILE.
3565 This uses the entries in `speedbar-dynamic-tags-function-list'
3566 to find the proper tags.  It is up to each of those individual
3567 functions to do caching and flushing if appropriate."
3568   (save-excursion
3569     ;; If a file is in memory, switch to that buffer.  This allows
3570     ;; us to use the local variable.  If the file is on disk, we
3571     ;; can try a few of the defaults that can get tags without
3572     ;; opening the file.
3573     (if (get-file-buffer file)
3574         (set-buffer (get-file-buffer file)))
3575     ;; If there is a buffer-local value of
3576     ;; speedbar-dynamic-tags-function-list, it will now be available.
3577     (let ((dtf speedbar-dynamic-tags-function-list)
3578           (ret t))
3579       (while (and (eq ret t) dtf)
3580         (setq ret
3581               (if (fboundp (car (car dtf)))
3582                   (funcall (car (car dtf)) file)
3583                 t))
3584         (if (eq ret t)
3585             (setq dtf (cdr dtf))))
3586       (if (eq ret t)
3587           ;; No valid tag list, return nil
3588           nil
3589         ;; We have some tags.  Return the list with the insert fn
3590         ;; prepended
3591         (cons (cdr (car dtf)) ret)))))
3592
3593 ;;; Tag Management -- Imenu
3594 ;;
3595 (if (not speedbar-use-imenu-flag)
3596
3597     nil
3598
3599 (eval-when-compile (if (locate-library "imenu") (require 'imenu)))
3600
3601 (defun speedbar-fetch-dynamic-imenu (file)
3602   "Load FILE into a buffer, and generate tags using Imenu.
3603 Returns the tag list, or t for an error."
3604   ;; Load this AND compile it in
3605   (require 'imenu)
3606   (set-buffer (find-file-noselect file))
3607   (if dframe-power-click (setq imenu--index-alist nil))
3608   (condition-case nil
3609       (let ((index-alist (imenu--make-index-alist t)))
3610         (if speedbar-sort-tags
3611             (sort (copy-alist index-alist)
3612                   (lambda (a b) (string< (car a) (car b))))
3613           index-alist))
3614     (error t)))
3615 )
3616 \f
3617 ;;; Tag Management -- etags  (old XEmacs compatibility part)
3618 ;;
3619 (defvar speedbar-fetch-etags-parse-list
3620   '(;; Note that java has the same parse-group as c
3621     ("\\.\\([cChH]\\|c\\+\\+\\|cpp\\|cc\\|hh\\|java\\|cxx\\|hxx\\)\\'" .
3622      speedbar-parse-c-or-c++tag)
3623     ("^\\.emacs$\\|.\\(el\\|l\\|lsp\\)\\'" .
3624      "def[^i]+\\s-+\\(\\(\\w\\|[-_]\\)+\\)\\s-*\C-?")
3625 ;    ("\\.\\([fF]\\|for\\|FOR\\|77\\|90\\)\\'" .
3626 ;      speedbar-parse-fortran77-tag)
3627     ("\\.tex\\'" . speedbar-parse-tex-string)
3628     ("\\.p\\'" .
3629      "\\(\\(FUNCTION\\|function\\|PROCEDURE\\|procedure\\)\\s-+\\([a-zA-Z0-9_.:]+\\)\\)\\s-*(?^?")
3630     )
3631   "Associations of file extensions and expressions for extracting tags.
3632 To add a new file type, you would want to add a new association to the
3633 list, where the car is the file match, and the cdr is the way to
3634 extract an element from the tags output.  If the output is complex,
3635 use a function symbol instead of regexp.  The function should expect
3636 to be at the beginning of a line in the etags buffer.
3637
3638 This variable is ignored if `speedbar-use-imenu-flag' is non-nil.")
3639
3640 (defvar speedbar-fetch-etags-command "etags"
3641   "*Command used to create an etags file.
3642
3643 This variable is ignored if `speedbar-use-imenu-flag' is t.")
3644
3645 (defvar speedbar-fetch-etags-arguments '("-D" "-I" "-o" "-")
3646   "*List of arguments to use with `speedbar-fetch-etags-command'.
3647 This creates an etags output buffer.  Use `speedbar-toggle-etags' to
3648 modify this list conveniently.
3649
3650 This variable is ignored if `speedbar-use-imenu-flag' is t.")
3651
3652 (defun speedbar-toggle-etags (flag)
3653   "Toggle FLAG in `speedbar-fetch-etags-arguments'.
3654 FLAG then becomes a member of etags command line arguments.  If flag
3655 is \"sort\", then toggle the value of `speedbar-sort-tags'.  If its
3656 value is \"show\" then toggle the value of
3657 `speedbar-show-unknown-files'.
3658
3659   This function is a convenience function for XEmacs menu created by
3660 Farzin Guilak <farzin@protocol.com>."
3661   (interactive)
3662   (cond
3663    ((equal flag "sort")
3664     (setq speedbar-sort-tags (not speedbar-sort-tags)))
3665    ((equal flag "show")
3666     (setq speedbar-show-unknown-files (not speedbar-show-unknown-files)))
3667    ((or (equal flag "-C")
3668         (equal flag "-S")
3669         (equal flag "-D"))
3670     (if (member flag speedbar-fetch-etags-arguments)
3671         (setq speedbar-fetch-etags-arguments
3672               (delete flag speedbar-fetch-etags-arguments))
3673       (add-to-list 'speedbar-fetch-etags-arguments flag)))
3674    (t nil)))
3675
3676 (defun speedbar-fetch-dynamic-etags (file)
3677   "For FILE, run etags and create a list of symbols extracted.
3678 Each symbol will be associated with its line position in FILE."
3679   (let ((newlist nil))
3680     (unwind-protect
3681         (save-excursion
3682           (if (get-buffer "*etags tmp*")
3683               (kill-buffer "*etags tmp*"))      ;kill to clean it up
3684           (if (<= 1 speedbar-verbosity-level)
3685               (speedbar-message "Fetching etags..."))
3686           (set-buffer (get-buffer-create "*etags tmp*"))
3687           (apply 'call-process speedbar-fetch-etags-command nil
3688                  (current-buffer) nil
3689                  (append speedbar-fetch-etags-arguments (list file)))
3690           (goto-char (point-min))
3691           (if (<= 1 speedbar-verbosity-level)
3692               (speedbar-message "Fetching etags..."))
3693           (let ((expr
3694                  (let ((exprlst speedbar-fetch-etags-parse-list)
3695                        (ans nil))
3696                    (while (and (not ans) exprlst)
3697                      (if (string-match (car (car exprlst)) file)
3698                          (setq ans (car exprlst)))
3699                      (setq exprlst (cdr exprlst)))
3700                    (cdr ans))))
3701             (if expr
3702                 (let (tnl)
3703                   (set-buffer (get-buffer-create "*etags tmp*"))
3704                   (while (not (save-excursion (end-of-line) (eobp)))
3705                     (save-excursion
3706                       (setq tnl (speedbar-extract-one-symbol expr)))
3707                     (if tnl (setq newlist (cons tnl newlist)))
3708                     (forward-line 1)))
3709               (speedbar-message
3710                "Sorry, no support for a file of that extension"))))
3711       )
3712     (if speedbar-sort-tags
3713         (sort newlist (lambda (a b) (string< (car a) (car b))))
3714       (reverse newlist))))
3715
3716 ;; This bit donated by Farzin Guilak <farzin@protocol.com> but I'm not
3717 ;; sure it's needed with the different sorting method.
3718 ;;
3719 ;(defun speedbar-clean-etags()
3720 ;  "Removes spaces before the ^? character, and removes `#define',
3721 ;return types, etc. preceding tags.  This ensures that the sort operation
3722 ;works on the tags, not the return types."
3723 ;  (save-excursion
3724 ;    (goto-char (point-min))
3725 ;    (while
3726 ;       (re-search-forward "(?[ \t](?\C-?" nil t)
3727 ;      (replace-match "\C-?" nil nil))
3728 ;    (goto-char (point-min))
3729 ;    (while
3730 ;       (re-search-forward "\\(.*[ \t]+\\)\\([^ \t\n]+.*\C-?\\)" nil t)
3731 ;      (delete-region (match-beginning 1) (match-end 1)))))
3732
3733 (defun speedbar-extract-one-symbol (expr)
3734   "At point, return nil, or one alist in the form: (SYMBOL .  POSITION)
3735 The line should contain output from etags.  Parse the output using the
3736 regular expression EXPR."
3737   (let* ((sym (if (stringp expr)
3738                   (if (save-excursion
3739                         (re-search-forward expr (save-excursion
3740                                                   (end-of-line)
3741                                                   (point)) t))
3742                       (buffer-substring-no-properties (match-beginning 1)
3743                                                       (match-end 1)))
3744                 (funcall expr)))
3745          (pos (let ((j (re-search-forward "[\C-?\C-a]\\([0-9]+\\),\\([0-9]+\\)"
3746                                           (save-excursion
3747                                             (end-of-line)
3748                                             (point))
3749                                           t)))
3750                 (if (and j sym)
3751                     (1+ (string-to-int (buffer-substring-no-properties
3752                                         (match-beginning 2)
3753                                         (match-end 2))))
3754                   0))))
3755     (if (/= pos 0)
3756         (cons sym pos)
3757       nil)))
3758
3759 (defun speedbar-parse-c-or-c++tag ()
3760   "Parse a C or C++ tag, which tends to be a little complex."
3761   (save-excursion
3762     (let ((bound (save-excursion (end-of-line) (point))))
3763       (cond ((re-search-forward "\C-?\\([^\C-a]+\\)\C-a" bound t)
3764              (buffer-substring-no-properties (match-beginning 1)
3765                                              (match-end 1)))
3766             ((re-search-forward "\\<\\([^ \t]+\\)\\s-+new(" bound t)
3767              (buffer-substring-no-properties (match-beginning 1)
3768                                              (match-end 1)))
3769             ((re-search-forward "\\<\\([^ \t(]+\\)\\s-*(\C-?" bound t)
3770              (buffer-substring-no-properties (match-beginning 1)
3771                                              (match-end 1)))
3772             (t nil))
3773       )))
3774
3775 (defun speedbar-parse-tex-string ()
3776   "Parse a Tex string.  Only find data which is relevant."
3777   (save-excursion
3778     (let ((bound (save-excursion (end-of-line) (point))))
3779       (cond ((re-search-forward "\\(\\(sub\\)*section\\|chapter\\|cite\\)\\s-*{[^\C-?}]*}?" bound t)
3780              (buffer-substring-no-properties (match-beginning 0)
3781                                              (match-end 0)))
3782             (t nil)))))
3783
3784 \f
3785 ;;; BUFFER DISPLAY mode.
3786 ;;
3787 (defvar speedbar-buffers-key-map nil
3788   "Keymap used when in the buffers display mode.")
3789
3790 (if speedbar-buffers-key-map
3791     nil
3792   (setq speedbar-buffers-key-map (speedbar-make-specialized-keymap))
3793
3794   ;; Basic tree features
3795   (define-key speedbar-buffers-key-map "e" 'speedbar-edit-line)
3796   (define-key speedbar-buffers-key-map "\C-m" 'speedbar-edit-line)
3797   (define-key speedbar-buffers-key-map "+" 'speedbar-expand-line)
3798   (define-key speedbar-buffers-key-map "=" 'speedbar-expand-line)
3799   (define-key speedbar-buffers-key-map "-" 'speedbar-contract-line)
3800   (define-key speedbar-buffers-key-map " " 'speedbar-toggle-line-expansion)
3801
3802   ;; Buffer specific keybindings
3803   (define-key speedbar-buffers-key-map "k" 'speedbar-buffer-kill-buffer)
3804   (define-key speedbar-buffers-key-map "r" 'speedbar-buffer-revert-buffer)
3805
3806   )
3807
3808 (defvar speedbar-buffer-easymenu-definition
3809   '(["Jump to buffer" speedbar-edit-line t]
3810     ["Expand File Tags" speedbar-expand-line
3811      (save-excursion (beginning-of-line)
3812                      (looking-at "[0-9]+: *.\\+. "))]
3813     ["Flush Cache & Expand" speedbar-flush-expand-line
3814      (save-excursion (beginning-of-line)
3815                      (looking-at "[0-9]+: *.\\+. "))]
3816     ["Contract File Tags" speedbar-contract-line
3817      (save-excursion (beginning-of-line)
3818                      (looking-at "[0-9]+: *.-. "))]
3819     ["Kill Buffer" speedbar-buffer-kill-buffer
3820      (save-excursion (beginning-of-line)
3821                      (looking-at "[0-9]+: *.[-+?]. "))]
3822     ["Revert Buffer" speedbar-buffer-revert-buffer
3823      (save-excursion (beginning-of-line)
3824                      (looking-at "[0-9]+: *.[-+?]. "))]
3825     )
3826   "Menu item elements shown when displaying a buffer list.")
3827
3828 (defun speedbar-buffer-buttons (directory zero)
3829   "Create speedbar buttons based on the buffers currently loaded.
3830 DIRECTORY is the directory to the currently active buffer, and ZERO is 0."
3831   (speedbar-buffer-buttons-engine nil))
3832
3833 (defun speedbar-buffer-buttons-temp (directory zero)
3834   "Create speedbar buttons based on the buffers currently loaded.
3835 DIRECTORY is the directory to the currently active buffer, and ZERO is 0."
3836   (speedbar-buffer-buttons-engine t))
3837
3838 (defun speedbar-buffer-buttons-engine (temp)
3839   "Create speedbar buffer buttons.
3840 If TEMP is non-nil, then clicking on a buffer restores the previous display."
3841   (speedbar-insert-separator "Active Buffers:")
3842   (let ((bl (buffer-list))
3843         (case-fold-search t))
3844     (while bl
3845       (if (string-match "^[ *]" (buffer-name (car bl)))
3846           nil
3847         (let* ((known (string-match speedbar-file-regexp
3848                                     (buffer-name (car bl))))
3849                (expchar (if known ?+ ??))
3850                (fn (if known 'speedbar-tag-file nil))
3851                (fname (save-excursion (set-buffer (car bl))
3852                                       (buffer-file-name))))
3853           (speedbar-make-tag-line 'bracket expchar fn
3854                                   (if fname (file-name-nondirectory fname))
3855                                   (buffer-name (car bl))
3856                                   'speedbar-buffer-click temp
3857                                   'speedbar-file-face 0)
3858           (speedbar-buffers-tail-notes (car bl))))
3859       (setq bl (cdr bl)))
3860     (setq bl (buffer-list))
3861     (speedbar-insert-separator "Scratch Buffers:")
3862     (while bl
3863       (if (not (string-match "^\\*" (buffer-name (car bl))))
3864           nil
3865         (if (eq (car bl) speedbar-buffer)
3866             nil
3867           (speedbar-make-tag-line 'bracket ?? nil nil
3868                                   (buffer-name (car bl))
3869                                   'speedbar-buffer-click temp
3870                                   'speedbar-file-face 0)
3871           (speedbar-buffers-tail-notes (car bl))))
3872       (setq bl (cdr bl)))
3873     (setq bl (buffer-list))
3874     ;;(speedbar-insert-separator "Hidden Buffers:")
3875     ;;(while bl
3876     ;;  (if (not (string-match "^ " (buffer-name (car bl))))
3877     ;;    nil
3878     ;;  (if (eq (car bl) speedbar-buffer)
3879     ;;      nil
3880     ;;    (speedbar-make-tag-line 'bracket ?? nil nil
3881     ;;                            (buffer-name (car bl))
3882     ;;                            'speedbar-buffer-click temp
3883     ;;                            'speedbar-file-face 0)
3884     ;;    (speedbar-buffers-tail-notes (car bl))))
3885     ;;  (setq bl (cdr bl)))
3886     ))
3887
3888 (defun speedbar-buffers-tail-notes (buffer)
3889   "Add a note to the end of the last tag line.
3890 Argument BUFFER is the buffer being tested."
3891   (let (mod ro)
3892     (save-excursion
3893       (set-buffer buffer)
3894       (setq mod (buffer-modified-p)
3895             ro buffer-read-only))
3896     (if ro (speedbar-insert-button "%" nil nil nil nil t))))
3897
3898 (defun speedbar-buffers-item-info ()
3899   "Display information about the current buffer on the current line."
3900   (or (speedbar-item-info-tag-helper)
3901       (let* ((item (speedbar-line-text))
3902              (buffer (if item (get-buffer item) nil)))
3903         (and buffer
3904              (speedbar-message "%s%s %S %d %s"
3905                                (if (buffer-modified-p buffer) "* " "")
3906                                item
3907                                (save-excursion (set-buffer buffer) major-mode)
3908                                (save-excursion (set-buffer buffer)
3909                                                (buffer-size))
3910                                (or (buffer-file-name buffer) "<No file>"))))))
3911
3912 (defun speedbar-buffers-line-directory (&optional depth)
3913   "Fetch the full directory to the file (buffer) specified on the current line.
3914 Optional argument DEPTH specifies the current depth of the back search."
3915   (save-excursion
3916     (end-of-line)
3917     (let ((start (point)))
3918       ;; Buffers are always at level 0
3919       (if (not (re-search-backward "^0:" nil t))
3920           nil
3921         (let* ((bn (speedbar-line-text))
3922                (buffer (if bn (get-buffer bn))))
3923           (if buffer
3924               (if (save-excursion
3925                     (end-of-line)
3926                     (eq start (point)))
3927                   (or (save-excursion (set-buffer buffer)
3928                                       default-directory)
3929                       "")
3930                 (buffer-file-name buffer))))))))
3931
3932 (defun speedbar-buffer-click (text token indent)
3933   "When the users clicks on a buffer-button in speedbar.
3934 TEXT is the buffer's name, TOKEN and INDENT are unused."
3935   (if dframe-power-click
3936       (let ((pop-up-frames t)) (select-window (display-buffer text)))
3937     (dframe-select-attached-frame speedbar-frame)
3938     (switch-to-buffer text)
3939     (if token (speedbar-change-initial-expansion-list
3940                speedbar-previously-used-expansion-list-name))))
3941
3942 (defun speedbar-buffer-kill-buffer ()
3943   "Kill the buffer the cursor is on in the speedbar buffer."
3944   (interactive)
3945   (or (save-excursion
3946         (let ((text (speedbar-line-text)))
3947           (if (and (get-buffer text)
3948                    (speedbar-y-or-n-p (format "Kill buffer %s? " text)))
3949               (kill-buffer text))
3950           (speedbar-refresh)))))
3951
3952 (defun speedbar-buffer-revert-buffer ()
3953   "Revert the buffer the cursor is on in the speedbar buffer."
3954   (interactive)
3955   (save-excursion
3956     (beginning-of-line)
3957     ;; If this fails, then it is a non-standard click, and as such,
3958     ;; perfectly allowed
3959     (if (re-search-forward "[]>?}] [^ ]"
3960                            (save-excursion (end-of-line) (point))
3961                            t)
3962         (let ((text (progn
3963                       (forward-char -1)
3964                       (buffer-substring (point) (save-excursion
3965                                                   (end-of-line)
3966                                                   (point))))))
3967           (if (get-buffer text)
3968               (progn
3969                 (set-buffer text)
3970                 (revert-buffer t)))))))
3971
3972 \f
3973 ;;; Useful hook values and such.
3974 ;;
3975 (defvar speedbar-highlight-one-tag-line nil
3976   "Overlay used for highlighting the most recently jumped to tag line.")
3977
3978 (defun speedbar-highlight-one-tag-line ()
3979   "Highlight the current line, unhighlighting a previously jumped to line."
3980   (speedbar-unhighlight-one-tag-line)
3981   (setq speedbar-highlight-one-tag-line
3982         (speedbar-make-overlay (save-excursion (beginning-of-line) (point))
3983                                (save-excursion (end-of-line)
3984                                                (forward-char 1)
3985                                                (point))))
3986   (speedbar-overlay-put speedbar-highlight-one-tag-line 'face
3987                         'speedbar-highlight-face)
3988   (add-hook 'pre-command-hook 'speedbar-unhighlight-one-tag-line)
3989   )
3990
3991 (defun speedbar-unhighlight-one-tag-line ()
3992   "Unhighlight the currently highlighted line."
3993   (if speedbar-highlight-one-tag-line
3994       (progn
3995         (speedbar-delete-overlay speedbar-highlight-one-tag-line)
3996         (setq speedbar-highlight-one-tag-line nil)))
3997   (remove-hook 'pre-command-hook 'speedbar-unhighlight-one-tag-line))
3998
3999 (defun speedbar-recenter-to-top ()
4000   "Recenter the current buffer so POINT is on the top of the window."
4001   (recenter 1))
4002
4003 (defun speedbar-recenter ()
4004   "Recenter the current buffer so POINT is in the center of the window."
4005   (recenter (/ (window-height (selected-window)) 2)))
4006
4007 \f
4008 ;;; Color loading section.
4009 ;;
4010 (defface speedbar-button-face '((((class color) (background light))
4011                                  (:foreground "green4"))
4012                                 (((class color) (background dark))
4013                                  (:foreground "green3")))
4014   "Face used for +/- buttons."
4015   :group 'speedbar-faces)
4016
4017 (defface speedbar-file-face '((((class color) (background light))
4018                                (:foreground "cyan4"))
4019                               (((class color) (background dark))
4020                                (:foreground "cyan"))
4021                               (t (:bold t)))
4022   "Face used for file names."
4023   :group 'speedbar-faces)
4024
4025 (defface speedbar-directory-face '((((class color) (background light))
4026                                     (:foreground "blue4"))
4027                                    (((class color) (background dark))
4028                                     (:foreground "light blue")))
4029   "Face used for directory names."
4030   :group 'speedbar-faces)
4031 (defface speedbar-tag-face '((((class color) (background light))
4032                               (:foreground "brown"))
4033                              (((class color) (background dark))
4034                               (:foreground "yellow")))
4035   "Face used for displaying tags."
4036   :group 'speedbar-faces)
4037
4038 (defface speedbar-selected-face '((((class color) (background light))
4039                                     (:foreground "red" :underline t))
4040                                   (((class color) (background dark))
4041                                    (:foreground "red" :underline t))
4042                                   (t (:underline t)))
4043   "Face used to underline the file in the active window."
4044   :group 'speedbar-faces)
4045
4046 (defface speedbar-highlight-face '((((class color) (background light))
4047                                     (:background "green"))
4048                                    (((class color) (background dark))
4049                                     (:background "sea green"))
4050                                    (((class grayscale monochrome)
4051                                      (background light))
4052                                     (:background "black"))
4053                                    (((class grayscale monochrome)
4054                                      (background dark))
4055                                     (:background "white")))
4056   "Face used for highlighting buttons with the mouse."
4057   :group 'speedbar-faces)
4058
4059 (defface speedbar-separator-face '((((class color) (background light))
4060                                     (:background "blue"
4061                                      :foreground "white"
4062                                      :overline "gray"))
4063                                    (((class color) (background dark))
4064                                     (:background "blue"
4065                                      :foreground "white"
4066                                      :overline "gray"))
4067                                    (((class grayscale monochrome)
4068                                      (background light))
4069                                     (:background "black"
4070                                      :foreground "white"
4071                                      :overline "white"))
4072                                    (((class grayscale monochrome)
4073                                      (background dark))
4074                                     (:background "white"
4075                                      :foreground "black"
4076                                      :overline "black")))
4077   "Face used for separator labes in a display."
4078   :group 'speedbar-faces)
4079
4080 ;; some edebug hooks
4081 (add-hook 'edebug-setup-hook
4082           (lambda ()
4083             (def-edebug-spec speedbar-with-writable def-body)))
4084
4085 ;; Fix a font lock problem for some versions of Emacs
4086 (if (boundp 'font-lock-global-modes)
4087     (if (listp font-lock-global-modes)
4088         (add-to-list 'font-lock-global-modes '(not speedbar-mode))
4089       )
4090   )
4091
4092 (provide 'speedbar)
4093 ;;; speedbar ends here
4094
4095 ;; run load-time hooks
4096 (run-hooks 'speedbar-load-hook)