Synch with Gnus.
[elisp/gnus.git-] / lisp / gnus-topic.el
1 ;;; gnus-topic.el --- a folding minor mode for Gnus group buffers
2 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Ilja Weis <kult@uni-paderborn.de>
6 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; Keywords: news
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;;; Code:
29
30 (eval-when-compile (require 'cl))
31 (eval-when-compile (require 'gnus-clfns))
32
33 (require 'gnus)
34 (require 'gnus-group)
35 (require 'gnus-start)
36 (require 'gnus-util)
37
38 (defgroup gnus-topic nil
39   "Group topics."
40   :group 'gnus-group)
41
42 (defvar gnus-topic-mode nil
43   "Minor mode for Gnus group buffers.")
44
45 (defcustom gnus-topic-mode-hook nil
46   "Hook run in topic mode buffers."
47   :type 'hook
48   :group 'gnus-topic)
49
50 (defcustom gnus-topic-line-format "%i[ %(%{%n%}%) -- %A ]%v\n"
51   "Format of topic lines.
52 It works along the same lines as a normal formatting string,
53 with some simple extensions.
54
55 %i  Indentation based on topic level.
56 %n  Topic name.
57 %v  Nothing if the topic is visible, \"...\" otherwise.
58 %g  Number of groups in the topic.
59 %a  Number of unread articles in the groups in the topic.
60 %A  Number of unread articles in the groups in the topic and its subtopics.
61 "
62   :type 'string
63   :group 'gnus-topic)
64
65 (defcustom gnus-topic-indent-level 2
66   "*How much each subtopic should be indented."
67   :type 'integer
68   :group 'gnus-topic)
69
70 (defcustom gnus-topic-display-empty-topics t
71   "*If non-nil, display the topic lines even of topics that have no unread articles."
72   :type 'boolean
73   :group 'gnus-topic)
74
75 ;; Internal variables.
76
77 (defvar gnus-topic-active-topology nil)
78 (defvar gnus-topic-active-alist nil)
79 (defvar gnus-topic-unreads nil)
80
81 (defvar gnus-topology-checked-p nil
82   "Whether the topology has been checked in this session.")
83
84 (defvar gnus-topic-killed-topics nil)
85 (defvar gnus-topic-inhibit-change-level nil)
86
87 (defconst gnus-topic-line-format-alist
88   `((?n name ?s)
89     (?v visible ?s)
90     (?i indentation ?s)
91     (?g number-of-groups ?d)
92     (?a (gnus-topic-articles-in-topic entries) ?d)
93     (?A total-number-of-articles ?d)
94     (?l level ?d)))
95
96 (defvar gnus-topic-line-format-spec nil)
97
98 ;;; Utility functions
99
100 (defun gnus-group-topic-name ()
101   "The name of the topic on the current line."
102   (let ((topic (get-text-property (gnus-point-at-bol) 'gnus-topic)))
103     (and topic (symbol-name topic))))
104
105 (defun gnus-group-topic-level ()
106   "The level of the topic on the current line."
107   (get-text-property (gnus-point-at-bol) 'gnus-topic-level))
108
109 (defun gnus-group-topic-unread ()
110   "The number of unread articles in topic on the current line."
111   (get-text-property (gnus-point-at-bol) 'gnus-topic-unread))
112
113 (defun gnus-topic-unread (topic)
114   "Return the number of unread articles in TOPIC."
115   (or (cdr (assoc topic gnus-topic-unreads))
116       0))
117
118 (defun gnus-group-topic-p ()
119   "Return non-nil if the current line is a topic."
120   (gnus-group-topic-name))
121
122 (defun gnus-topic-visible-p ()
123   "Return non-nil if the current topic is visible."
124   (get-text-property (gnus-point-at-bol) 'gnus-topic-visible))
125
126 (defun gnus-topic-articles-in-topic (entries)
127   (let ((total 0)
128         number)
129     (while entries
130       (when (numberp (setq number (car (pop entries))))
131         (incf total number)))
132     total))
133
134 (defun gnus-group-topic (group)
135   "Return the topic GROUP is a member of."
136   (let ((alist gnus-topic-alist)
137         out)
138     (while alist
139       (when (member group (cdar alist))
140         (setq out (caar alist)
141               alist nil))
142       (setq alist (cdr alist)))
143     out))
144
145 (defun gnus-group-parent-topic (group)
146   "Return the topic GROUP is member of by looking at the group buffer."
147   (save-excursion
148     (set-buffer gnus-group-buffer)
149     (if (gnus-group-goto-group group)
150         (gnus-current-topic)
151       (gnus-group-topic group))))
152
153 (defun gnus-topic-goto-topic (topic)
154   (when topic
155     (gnus-goto-char (text-property-any (point-min) (point-max)
156                                        'gnus-topic (intern topic)))))
157
158 (defun gnus-topic-jump-to-topic (topic)
159   "Go to TOPIC."
160   (interactive
161    (list (completing-read "Go to topic: "
162                           (mapcar 'list (gnus-topic-list))
163                           nil t)))
164   (dolist (topic (gnus-current-topics topic))
165     (gnus-topic-fold t))
166   (gnus-topic-goto-topic topic))
167   
168 (defun gnus-current-topic ()
169   "Return the name of the current topic."
170   (let ((result
171          (or (get-text-property (point) 'gnus-topic)
172              (save-excursion
173                (and (gnus-goto-char (previous-single-property-change
174                                      (point) 'gnus-topic))
175                     (get-text-property (max (1- (point)) (point-min))
176                                        'gnus-topic))))))
177     (when result
178       (symbol-name result))))
179
180 (defun gnus-current-topics (&optional topic)
181   "Return a list of all current topics, lowest in hierarchy first.
182 If TOPIC, start with that topic."
183   (let ((topic (or topic (gnus-current-topic)))
184         topics)
185     (while topic
186       (push topic topics)
187       (setq topic (gnus-topic-parent-topic topic)))
188     (nreverse topics)))
189
190 (defun gnus-group-active-topic-p ()
191   "Say whether the current topic comes from the active topics."
192   (save-excursion
193     (beginning-of-line)
194     (get-text-property (point) 'gnus-active)))
195
196 (defun gnus-topic-find-groups (topic &optional level all lowest)
197   "Return entries for all visible groups in TOPIC."
198   (let ((groups (cdr (assoc topic gnus-topic-alist)))
199         info clevel unread group params visible-groups entry active)
200     (setq lowest (or lowest 1))
201     (setq level (or level gnus-level-unsubscribed))
202     ;; We go through the newsrc to look for matches.
203     (while groups
204       (when (setq group (pop groups))
205         (setq entry (gnus-gethash group gnus-newsrc-hashtb)
206               info (nth 2 entry)
207               params (gnus-info-params info)
208               active (gnus-active group)
209               unread (or (car entry)
210                          (and (not (equal group "dummy.group"))
211                               active
212                               (- (1+ (cdr active)) (car active))))
213               clevel (or (gnus-info-level info)
214                          (if (member group gnus-zombie-list)
215                              gnus-level-zombie gnus-level-killed))))
216       (and
217        info                             ; nil means that the group is dead.
218        (<= clevel level)
219        (>= clevel lowest)               ; Is inside the level we want.
220        (or all
221            (if (or (eq unread t)
222                    (eq unread nil))
223                gnus-group-list-inactive-groups
224              (> unread 0))
225            (and gnus-list-groups-with-ticked-articles
226                 (cdr (assq 'tick (gnus-info-marks info))))
227            ;; Has right readedness.
228            ;; Check for permanent visibility.
229            (and gnus-permanently-visible-groups
230                 (string-match gnus-permanently-visible-groups group))
231            (memq 'visible params)
232            (cdr (assq 'visible params)))
233        ;; Add this group to the list of visible groups.
234        (push (or entry group) visible-groups)))
235     (nreverse visible-groups)))
236
237 (defun gnus-topic-previous-topic (topic)
238   "Return the previous topic on the same level as TOPIC."
239   (let ((top (cddr (gnus-topic-find-topology
240                     (gnus-topic-parent-topic topic)))))
241     (unless (equal topic (caaar top))
242       (while (and top (not (equal (caaadr top) topic)))
243         (setq top (cdr top)))
244       (caaar top))))
245
246 (defun gnus-topic-parent-topic (topic &optional topology)
247   "Return the parent of TOPIC."
248   (unless topology
249     (setq topology gnus-topic-topology))
250   (let ((parent (car (pop topology)))
251         result found)
252     (while (and topology
253                 (not (setq found (equal (caaar topology) topic)))
254                 (not (setq result (gnus-topic-parent-topic
255                                    topic (car topology)))))
256       (setq topology (cdr topology)))
257     (or result (and found parent))))
258
259 (defun gnus-topic-next-topic (topic &optional previous)
260   "Return the next sibling of TOPIC."
261   (let ((parentt (cddr (gnus-topic-find-topology
262                         (gnus-topic-parent-topic topic))))
263         prev)
264     (while (and parentt
265                 (not (equal (caaar parentt) topic)))
266       (setq prev (caaar parentt)
267             parentt (cdr parentt)))
268     (if previous
269         prev
270       (caaadr parentt))))
271
272 (defun gnus-topic-forward-topic (num)
273   "Go to the next topic on the same level as the current one."
274   (let* ((topic (gnus-current-topic))
275          (way (if (< num 0) 'gnus-topic-previous-topic
276                 'gnus-topic-next-topic))
277          (num (abs num)))
278     (while (and (not (zerop num))
279                 (setq topic (funcall way topic)))
280       (when (gnus-topic-goto-topic topic)
281         (decf num)))
282     (unless (zerop num)
283       (goto-char (point-max)))
284     num))
285
286 (defun gnus-topic-find-topology (topic &optional topology level remove)
287   "Return the topology of TOPIC."
288   (unless topology
289     (setq topology gnus-topic-topology)
290     (setq level 0))
291   (let ((top topology)
292         result)
293     (if (equal (caar topology) topic)
294         (progn
295           (when remove
296             (delq topology remove))
297           (cons level topology))
298       (setq topology (cdr topology))
299       (while (and topology
300                   (not (setq result (gnus-topic-find-topology
301                                      topic (car topology) (1+ level)
302                                      (and remove top)))))
303         (setq topology (cdr topology)))
304       result)))
305
306 (defvar gnus-tmp-topics nil)
307 (defun gnus-topic-list (&optional topology)
308   "Return a list of all topics in the topology."
309   (unless topology
310     (setq topology gnus-topic-topology
311           gnus-tmp-topics nil))
312   (push (caar topology) gnus-tmp-topics)
313   (mapcar 'gnus-topic-list (cdr topology))
314   gnus-tmp-topics)
315
316 ;;; Topic parameter jazz
317
318 (defun gnus-topic-parameters (topic)
319   "Return the parameters for TOPIC."
320   (let ((top (gnus-topic-find-topology topic)))
321     (when top
322       (nth 3 (cadr top)))))
323
324 (defun gnus-topic-set-parameters (topic parameters)
325   "Set the topic parameters of TOPIC to PARAMETERS."
326   (let ((top (gnus-topic-find-topology topic)))
327     (unless top
328       (error "No such topic: %s" topic))
329     ;; We may have to extend if there is no parameters here
330     ;; to begin with.
331     (unless (nthcdr 2 (cadr top))
332       (nconc (cadr top) (list nil)))
333     (unless (nthcdr 3 (cadr top))
334       (nconc (cadr top) (list nil)))
335     (setcar (nthcdr 3 (cadr top)) parameters)
336     (gnus-dribble-enter
337      (format "(gnus-topic-set-parameters %S '%S)" topic parameters))))
338
339 (defun gnus-group-topic-parameters (group)
340   "Compute the group parameters for GROUP taking into account inheritance from topics."
341   (let ((params-list (copy-sequence (gnus-group-get-parameter group))))
342     (save-excursion
343       (gnus-group-goto-group group)
344       (nconc params-list
345              (gnus-topic-hierarchical-parameters (gnus-current-topic))))))
346
347 (defun gnus-topic-hierarchical-parameters (topic)
348   "Return a topic list computed for TOPIC."
349   (let ((topics (gnus-current-topics topic))
350         params-list param out params)
351     (while topics
352       (push (gnus-topic-parameters (pop topics)) params-list))
353     ;; We probably have lots of nil elements here, so
354     ;; we remove them.  Probably faster than doing this "properly".
355     (setq params-list (delq nil params-list))
356     ;; Now we have all the parameters, so we go through them
357     ;; and do inheritance in the obvious way.
358     (while (setq params (pop params-list))
359       (while (setq param (pop params))
360         (when (atom param)
361           (setq param (cons param t)))
362         ;; Override any old versions of this param.
363         (gnus-pull (car param) out)
364         (push param out)))
365     ;; Return the resulting parameter list.
366     out))
367
368 ;;; General utility functions
369
370 (defun gnus-topic-enter-dribble ()
371   (gnus-dribble-enter
372    (format "(setq gnus-topic-topology '%S)" gnus-topic-topology)))
373
374 ;;; Generating group buffers
375
376 (defun gnus-group-prepare-topics (level &optional all lowest
377                                         regexp list-topic topic-level)
378   "List all newsgroups with unread articles of level LEVEL or lower.
379 Use the `gnus-group-topics' to sort the groups.
380 If ALL is non-nil, list groups that have no unread articles.
381 If LOWEST is non-nil, list all newsgroups of level LOWEST or higher."
382   (set-buffer gnus-group-buffer)
383   (let ((buffer-read-only nil)
384         (lowest (or lowest 1)))
385
386     (when (or (not gnus-topic-alist)
387               (not gnus-topology-checked-p))
388       (gnus-topic-check-topology))
389
390     (unless list-topic
391       (erase-buffer))
392
393     ;; List dead groups?
394     (when (and (>= level gnus-level-zombie)
395                (<= lowest gnus-level-zombie))
396       (gnus-group-prepare-flat-list-dead
397        (setq gnus-zombie-list (sort gnus-zombie-list 'string<))
398        gnus-level-zombie ?Z
399        regexp))
400
401     (when (and (>= level gnus-level-killed) (<= lowest gnus-level-killed))
402       (gnus-group-prepare-flat-list-dead
403        (setq gnus-killed-list (sort gnus-killed-list 'string<))
404        gnus-level-killed ?K
405        regexp))
406
407     ;; Use topics.
408     (prog1
409         (when (< lowest gnus-level-zombie)
410           (if list-topic
411               (let ((top (gnus-topic-find-topology list-topic)))
412                 (gnus-topic-prepare-topic (cdr top) (car top)
413                                           (or topic-level level) all
414                                           nil lowest))
415             (gnus-topic-prepare-topic gnus-topic-topology 0
416                                       (or topic-level level) all
417                                       nil lowest)))
418
419       (gnus-group-set-mode-line)
420       (setq gnus-group-list-mode (cons level all))
421       (gnus-run-hooks 'gnus-group-prepare-hook))))
422
423 (defun gnus-topic-prepare-topic (topicl level &optional list-level all silent
424                                         lowest)
425   "Insert TOPIC into the group buffer.
426 If SILENT, don't insert anything.  Return the number of unread
427 articles in the topic and its subtopics."
428   (let* ((type (pop topicl))
429          (entries (gnus-topic-find-groups
430                    (car type) list-level
431                    (or all
432                        (cdr (assq 'visible
433                                   (gnus-topic-hierarchical-parameters
434                                    (car type)))))
435                    lowest))
436          (visiblep (and (eq (nth 1 type) 'visible) (not silent)))
437          (gnus-group-indentation
438           (make-string (* gnus-topic-indent-level level) ? ))
439          (beg (progn (beginning-of-line) (point)))
440          (topicl (reverse topicl))
441          (all-entries entries)
442          (point-max (point-max))
443          (unread 0)
444          (topic (car type))
445          info entry end active tick)
446     ;; Insert any sub-topics.
447     (while topicl
448       (incf unread
449             (gnus-topic-prepare-topic
450              (pop topicl) (1+ level) list-level all
451              (not visiblep) lowest)))
452     (setq end (point))
453     (goto-char beg)
454     ;; Insert all the groups that belong in this topic.
455     (while (setq entry (pop entries))
456       (when visiblep
457         (if (stringp entry)
458             ;; Dead groups.
459             (gnus-group-insert-group-line
460              entry (if (member entry gnus-zombie-list)
461                        gnus-level-zombie gnus-level-killed)
462              nil (- (1+ (cdr (setq active (gnus-active entry))))
463                     (car active))
464              nil)
465           ;; Living groups.
466           (when (setq info (nth 2 entry))
467             (gnus-group-insert-group-line
468              (gnus-info-group info)
469              (gnus-info-level info) (gnus-info-marks info)
470              (car entry) (gnus-info-method info)))))
471       (when (and (listp entry)
472                  (numberp (car entry)))
473         (incf unread (car entry)))
474       (when (listp entry)
475         (setq tick t)))
476     (goto-char beg)
477     ;; Insert the topic line.
478     (when (and (not silent)
479                (or gnus-topic-display-empty-topics ;We want empty topics
480                    (not (zerop unread)) ;Non-empty
481                    tick                 ;Ticked articles
482                    (/= point-max (point-max)))) ;Unactivated groups
483       (gnus-extent-start-open (point))
484       (gnus-topic-insert-topic-line
485        (car type) visiblep
486        (not (eq (nth 2 type) 'hidden))
487        level all-entries unread))
488     (gnus-topic-update-unreads (car type) unread)
489     (goto-char end)
490     unread))
491
492 (defun gnus-topic-remove-topic (&optional insert total-remove hide in-level)
493   "Remove the current topic."
494   (let ((topic (gnus-group-topic-name))
495         (level (gnus-group-topic-level))
496         (beg (progn (beginning-of-line) (point)))
497         buffer-read-only)
498     (when topic
499       (while (and (zerop (forward-line 1))
500                   (> (or (gnus-group-topic-level) (1+ level)) level)))
501       (delete-region beg (point))
502       ;; Do the change in this rather odd manner because it has been
503       ;; reported that some topics share parts of some lists, for some
504       ;; reason.  I have been unable to determine why this is the
505       ;; case, but this hack seems to take care of things.
506       (let ((data (cadr (gnus-topic-find-topology topic))))
507         (setcdr data
508                 (list (if insert 'visible 'invisible)
509                       hide
510                       (cadddr data))))
511       (if total-remove
512           (setq gnus-topic-alist
513                 (delq (assoc topic gnus-topic-alist) gnus-topic-alist))
514         (gnus-topic-insert-topic topic in-level)))))
515
516 (defun gnus-topic-insert-topic (topic &optional level)
517   "Insert TOPIC."
518   (gnus-group-prepare-topics
519    (car gnus-group-list-mode) (cdr gnus-group-list-mode)
520    nil nil topic level))
521
522 (defun gnus-topic-fold (&optional insert topic)
523   "Remove/insert the current topic."
524   (let ((topic (or topic (gnus-group-topic-name))))
525     (when topic
526       (save-excursion
527         (if (not (gnus-group-active-topic-p))
528             (gnus-topic-remove-topic
529              (or insert (not (gnus-topic-visible-p))))
530           (let ((gnus-topic-topology gnus-topic-active-topology)
531                 (gnus-topic-alist gnus-topic-active-alist)
532                 (gnus-group-list-mode (cons 5 t)))
533             (gnus-topic-remove-topic
534              (or insert (not (gnus-topic-visible-p))) nil nil 9)
535             (gnus-topic-enter-dribble)))))))
536
537 (defun gnus-topic-insert-topic-line (name visiblep shownp level entries
538                                           &optional unread)
539   (let* ((visible (if visiblep "" "..."))
540          (indentation (make-string (* gnus-topic-indent-level level) ? ))
541          (total-number-of-articles unread)
542          (number-of-groups (length entries))
543          (active-topic (eq gnus-topic-alist gnus-topic-active-alist))
544          gnus-tmp-header)
545     (gnus-topic-update-unreads name unread)
546     (beginning-of-line)
547     ;; Insert the text.
548     (if shownp
549         (gnus-add-text-properties
550          (point)
551          (prog1 (1+ (point))
552            (eval gnus-topic-line-format-spec))
553          (list 'gnus-topic (intern name)
554                'gnus-topic-level level
555                'gnus-topic-unread unread
556                'gnus-active active-topic
557                'gnus-topic-visible visiblep)))))
558
559 (defun gnus-topic-update-unreads (topic unreads)
560   (setq gnus-topic-unreads (delq (assoc topic gnus-topic-unreads)
561                                  gnus-topic-unreads))
562   (push (cons topic unreads) gnus-topic-unreads))
563
564 (defun gnus-topic-update-topics-containing-group (group)
565   "Update all topics that have GROUP as a member."
566   (when (and (eq major-mode 'gnus-group-mode)
567              gnus-topic-mode)
568     (save-excursion
569       (let ((alist gnus-topic-alist))
570         ;; This is probably not entirely correct.  If a topic
571         ;; isn't shown, then it's not updated.  But the updating
572         ;; should be performed in any case, since the topic's
573         ;; parent should be updated.  Pfft.
574         (while alist
575           (when (and (member group (cdar alist))
576                      (gnus-topic-goto-topic (caar alist)))
577             (gnus-topic-update-topic-line (caar alist)))
578           (pop alist))))))
579
580 (defun gnus-topic-update-topic ()
581   "Update all parent topics to the current group."
582   (when (and (eq major-mode 'gnus-group-mode)
583              gnus-topic-mode)
584     (let ((group (gnus-group-group-name))
585           (m (point-marker))
586           (buffer-read-only nil))
587       (when (and group
588                  (gnus-get-info group)
589                  (gnus-topic-goto-topic (gnus-current-topic)))
590         (gnus-topic-update-topic-line (gnus-group-topic-name))
591         (goto-char m)
592         (set-marker m nil)
593         (gnus-group-position-point)))))
594
595 (defun gnus-topic-goto-missing-group (group)
596   "Place point where GROUP is supposed to be inserted."
597   (let* ((topic (gnus-group-topic group))
598          (groups (cdr (assoc topic gnus-topic-alist)))
599          (g (cdr (member group groups)))
600          (unfound t)
601          entry)
602     ;; Try to jump to a visible group.
603     (while (and g (not (gnus-group-goto-group (car g) t)))
604       (pop g))
605     ;; It wasn't visible, so we try to see where to insert it.
606     (when (not g)
607       (setq g (cdr (member group (reverse groups))))
608       (while (and g unfound)
609         (when (gnus-group-goto-group (pop g) t)
610           (forward-line 1)
611           (setq unfound nil)))
612       (when (and unfound
613                  topic
614                  (not (gnus-topic-goto-missing-topic topic)))
615         (let* ((top (gnus-topic-find-topology topic))
616                (children (cddr top))
617                (type (cadr top))
618                (unread 0)
619                (entries (gnus-topic-find-groups
620                          (car type) (car gnus-group-list-mode)
621                          (cdr gnus-group-list-mode))))
622           (while children
623             (incf unread (gnus-topic-unread (caar (pop children)))))
624           (while (setq entry (pop entries))
625             (when (numberp (car entry))
626               (incf unread (car entry))))
627           (gnus-topic-insert-topic-line
628            topic t t (car (gnus-topic-find-topology topic)) nil unread))))))
629
630 (defun gnus-topic-goto-missing-topic (topic)
631   (if (gnus-topic-goto-topic topic)
632       (forward-line 1)
633     ;; Topic not displayed.
634     (let* ((top (gnus-topic-find-topology
635                  (gnus-topic-parent-topic topic)))
636            (tp (reverse (cddr top))))
637       (if (not top)
638           (gnus-topic-insert-topic-line
639            topic t t (car (gnus-topic-find-topology topic)) nil 0)
640         (while (not (equal (caaar tp) topic))
641           (setq tp (cdr tp)))
642         (pop tp)
643         (while (and tp
644                     (not (gnus-topic-goto-topic (caaar tp))))
645           (pop tp))
646         (if tp
647             (gnus-topic-forward-topic 1)
648           (gnus-topic-goto-missing-topic (caadr top)))))
649     nil))
650
651 (defun gnus-topic-update-topic-line (topic-name &optional reads)
652   (let* ((top (gnus-topic-find-topology topic-name))
653          (type (cadr top))
654          (children (cddr top))
655          (entries (gnus-topic-find-groups
656                    (car type) (car gnus-group-list-mode)
657                    (cdr gnus-group-list-mode)))
658          (parent (gnus-topic-parent-topic topic-name))
659          (all-entries entries)
660          (unread 0)
661          old-unread entry new-unread)
662     (when (gnus-topic-goto-topic (car type))
663       ;; Tally all the groups that belong in this topic.
664       (if reads
665           (setq unread (- (gnus-group-topic-unread) reads))
666         (while children
667           (incf unread (gnus-topic-unread (caar (pop children)))))
668         (while (setq entry (pop entries))
669           (when (numberp (car entry))
670             (incf unread (car entry)))))
671       (setq old-unread (gnus-group-topic-unread))
672       ;; Insert the topic line.
673       (gnus-topic-insert-topic-line
674        (car type) (gnus-topic-visible-p)
675        (not (eq (nth 2 type) 'hidden))
676        (gnus-group-topic-level) all-entries unread)
677       (gnus-delete-line)
678       (forward-line -1)
679       (setq new-unread (gnus-group-topic-unread)))
680     (when parent
681       (forward-line -1)
682       (gnus-topic-update-topic-line
683        parent
684        (- (or old-unread 0) (or new-unread 0))))
685     unread))
686
687 (defun gnus-topic-group-indentation ()
688   (make-string
689    (* gnus-topic-indent-level
690       (or (save-excursion
691             (forward-line -1)
692             (gnus-topic-goto-topic (gnus-current-topic))
693             (gnus-group-topic-level))
694           0))
695    ? ))
696
697 ;;; Initialization
698
699 (gnus-add-shutdown 'gnus-topic-close 'gnus)
700
701 (defun gnus-topic-close ()
702   (setq gnus-topic-active-topology nil
703         gnus-topic-active-alist nil
704         gnus-topic-killed-topics nil
705         gnus-topology-checked-p nil))
706
707 (defun gnus-topic-check-topology ()
708   ;; The first time we set the topology to whatever we have
709   ;; gotten here, which can be rather random.
710   (unless gnus-topic-alist
711     (gnus-topic-init-alist))
712
713   (setq gnus-topology-checked-p t)
714   ;; Go through the topic alist and make sure that all topics
715   ;; are in the topic topology.
716   (let ((topics (gnus-topic-list))
717         (alist gnus-topic-alist)
718         changed)
719     (while alist
720       (unless (member (caar alist) topics)
721         (nconc gnus-topic-topology
722                (list (list (list (caar alist) 'visible))))
723         (setq changed t))
724       (setq alist (cdr alist)))
725     (when changed
726       (gnus-topic-enter-dribble))
727     ;; Conversely, go through the topology and make sure that all
728     ;; topologies have alists.
729     (while topics
730       (unless (assoc (car topics) gnus-topic-alist)
731         (push (list (car topics)) gnus-topic-alist))
732       (pop topics)))
733   ;; Go through all living groups and make sure that
734   ;; they belong to some topic.
735   (let* ((tgroups (apply 'append (mapcar (lambda (entry) (cdr entry))
736                                          gnus-topic-alist)))
737          (entry (last (assoc (caar gnus-topic-topology) gnus-topic-alist)))
738          (newsrc (cdr gnus-newsrc-alist))
739          group)
740     (while newsrc
741       (unless (member (setq group (gnus-info-group (pop newsrc))) tgroups)
742         (setcdr entry (list group))
743         (setq entry (cdr entry)))))
744   ;; Go through all topics and make sure they contain only living groups.
745   (let ((alist gnus-topic-alist)
746         topic)
747     (while (setq topic (pop alist))
748       (while (cdr topic)
749         (if (and (cadr topic)
750                  (gnus-gethash (cadr topic) gnus-newsrc-hashtb))
751             (setq topic (cdr topic))
752           (setcdr topic (cddr topic)))))))
753
754 (defun gnus-topic-init-alist ()
755   "Initialize the topic structures."
756   (setq gnus-topic-topology
757         (cons (list "Gnus" 'visible)
758               (mapcar (lambda (topic)
759                         (list (list (car topic) 'visible)))
760                       '(("misc")))))
761   (setq gnus-topic-alist
762         (list (cons "misc"
763                     (mapcar (lambda (info) (gnus-info-group info))
764                             (cdr gnus-newsrc-alist)))
765               (list "Gnus")))
766   (gnus-topic-enter-dribble))
767
768 ;;; Maintenance
769
770 (defun gnus-topic-clean-alist ()
771   "Remove bogus groups from the topic alist."
772   (let ((topic-alist gnus-topic-alist)
773         result topic)
774     (unless gnus-killed-hashtb
775       (gnus-make-hashtable-from-killed))
776     (while (setq topic (pop topic-alist))
777       (let ((topic-name (pop topic))
778             group filtered-topic)
779         (while (setq group (pop topic))
780           (when (and (or (gnus-gethash group gnus-active-hashtb)
781                          (gnus-info-method (gnus-get-info group)))
782                      (not (gnus-gethash group gnus-killed-hashtb)))
783             (push group filtered-topic)))
784         (push (cons topic-name (nreverse filtered-topic)) result)))
785     (setq gnus-topic-alist (nreverse result))))
786
787 (defun gnus-topic-change-level (group level oldlevel &optional previous)
788   "Run when changing levels to enter/remove groups from topics."
789   (save-excursion
790     (set-buffer gnus-group-buffer)
791     (let ((buffer-read-only nil))
792       (unless gnus-topic-inhibit-change-level
793         (gnus-group-goto-group (or (car (nth 2 previous)) group))
794         (when (and gnus-topic-mode
795                    gnus-topic-alist
796                    (not gnus-topic-inhibit-change-level))
797           ;; Remove the group from the topics.
798           (if (and (< oldlevel gnus-level-zombie)
799                    (>= level gnus-level-zombie))
800               (let ((alist gnus-topic-alist))
801                 (while (gnus-group-goto-group group)
802                   (gnus-delete-line))
803                 (while alist
804                   (when (member group (car alist))
805                     (setcdr (car alist) (delete group (cdar alist))))
806                   (pop alist)))
807             ;; If the group is subscribed we enter it into the topics.
808             (when (and (< level gnus-level-zombie)
809                        (>= oldlevel gnus-level-zombie))
810               (let* ((prev (gnus-group-group-name))
811                      (gnus-topic-inhibit-change-level t)
812                      (gnus-group-indentation
813                       (make-string
814                        (* gnus-topic-indent-level
815                           (or (save-excursion
816                                 (gnus-topic-goto-topic (gnus-current-topic))
817                                 (gnus-group-topic-level))
818                               0))
819                        ? ))
820                      (yanked (list group))
821                      alist talist end)
822                 ;; Then we enter the yanked groups into the topics they belong
823                 ;; to.
824                 (when (setq alist (assoc (save-excursion
825                                            (forward-line -1)
826                                            (or
827                                             (gnus-current-topic)
828                                             (caar gnus-topic-topology)))
829                                          gnus-topic-alist))
830                   (setq talist alist)
831                   (when (stringp yanked)
832                     (setq yanked (list yanked)))
833                   (if (not prev)
834                       (nconc alist yanked)
835                     (if (not (cdr alist))
836                         (setcdr alist (nconc yanked (cdr alist)))
837                       (while (and (not end) (cdr alist))
838                         (when (equal (cadr alist) prev)
839                           (setcdr alist (nconc yanked (cdr alist)))
840                           (setq end t))
841                         (setq alist (cdr alist)))
842                       (unless end
843                         (nconc talist yanked))))))
844               (gnus-topic-update-topic))))))))
845
846 (defun gnus-topic-goto-next-group (group props)
847   "Go to group or the next group after group."
848   (if (not group)
849       (if (not (memq 'gnus-topic props))
850           (goto-char (point-max))
851         (gnus-topic-goto-topic (symbol-name (cadr (memq 'gnus-topic props)))))
852     (if (gnus-group-goto-group group)
853         t
854       ;; The group is no longer visible.
855       (let* ((list (assoc (gnus-group-topic group) gnus-topic-alist))
856              (after (cdr (member group (cdr list)))))
857         ;; First try to put point on a group after the current one.
858         (while (and after
859                     (not (gnus-group-goto-group (car after))))
860           (setq after (cdr after)))
861         ;; Then try to put point on a group before point.
862         (unless after
863           (setq after (cdr (member group (reverse (cdr list)))))
864           (while (and after
865                       (not (gnus-group-goto-group (car after))))
866             (setq after (cdr after))))
867         ;; Finally, just put point on the topic.
868         (if (not (car list))
869             (goto-char (point-min))
870           (unless after
871             (gnus-topic-goto-topic (car list))
872             (setq after nil)))
873         t))))
874
875 ;;; Topic-active functions
876
877 (defun gnus-topic-grok-active (&optional force)
878   "Parse all active groups and create topic structures for them."
879   ;; First we make sure that we have really read the active file.
880   (when (or force
881             (not gnus-topic-active-alist))
882     (let (groups)
883       ;; Get a list of all groups available.
884       (mapatoms (lambda (g) (when (symbol-value g)
885                               (push (symbol-name g) groups)))
886                 gnus-active-hashtb)
887       (setq groups (sort groups 'string<))
888       ;; Init the variables.
889       (setq gnus-topic-active-topology (list (list "" 'visible)))
890       (setq gnus-topic-active-alist nil)
891       ;; Descend the top-level hierarchy.
892       (gnus-topic-grok-active-1 gnus-topic-active-topology groups)
893       ;; Set the top-level topic names to something nice.
894       (setcar (car gnus-topic-active-topology) "Gnus active")
895       (setcar (car gnus-topic-active-alist) "Gnus active"))))
896
897 (defun gnus-topic-grok-active-1 (topology groups)
898   (let* ((name (caar topology))
899          (prefix (concat "^" (regexp-quote name)))
900          tgroups ntopology group)
901     (while (and groups
902                 (string-match prefix (setq group (car groups))))
903       (if (not (string-match "\\." group (match-end 0)))
904           ;; There are no further hierarchies here, so we just
905           ;; enter this group into the list belonging to this
906           ;; topic.
907           (push (pop groups) tgroups)
908         ;; New sub-hierarchy, so we add it to the topology.
909         (nconc topology (list (setq ntopology
910                                     (list (list (substring
911                                                  group 0 (match-end 0))
912                                                 'invisible)))))
913         ;; Descend the hierarchy.
914         (setq groups (gnus-topic-grok-active-1 ntopology groups))))
915     ;; We remove the trailing "." from the topic name.
916     (setq name
917           (if (string-match "\\.$" name)
918               (substring name 0 (match-beginning 0))
919             name))
920     ;; Add this topic and its groups to the topic alist.
921     (push (cons name (nreverse tgroups)) gnus-topic-active-alist)
922     (setcar (car topology) name)
923     ;; We return the rest of the groups that didn't belong
924     ;; to this topic.
925     groups))
926
927 ;;; Topic mode, commands and keymap.
928
929 (defvar gnus-topic-mode-map nil)
930 (defvar gnus-group-topic-map nil)
931
932 (unless gnus-topic-mode-map
933   (setq gnus-topic-mode-map (make-sparse-keymap))
934
935   ;; Override certain group mode keys.
936   (gnus-define-keys gnus-topic-mode-map
937     "=" gnus-topic-select-group
938     "\r" gnus-topic-select-group
939     " " gnus-topic-read-group
940     "\C-c\C-x" gnus-topic-expire-articles
941     "\C-k" gnus-topic-kill-group
942     "\C-y" gnus-topic-yank-group
943     "\M-g" gnus-topic-get-new-news-this-topic
944     "AT" gnus-topic-list-active
945     "Gp" gnus-topic-edit-parameters
946     "#" gnus-topic-mark-topic
947     "\M-#" gnus-topic-unmark-topic
948     [tab] gnus-topic-indent
949     [(meta tab)] gnus-topic-unindent
950     "\C-i" gnus-topic-indent
951     "\M-\C-i" gnus-topic-unindent
952     gnus-mouse-2 gnus-mouse-pick-topic)
953
954   ;; Define a new submap.
955   (gnus-define-keys (gnus-group-topic-map "T" gnus-group-mode-map)
956     "#" gnus-topic-mark-topic
957     "\M-#" gnus-topic-unmark-topic
958     "n" gnus-topic-create-topic
959     "m" gnus-topic-move-group
960     "D" gnus-topic-remove-group
961     "c" gnus-topic-copy-group
962     "h" gnus-topic-hide-topic
963     "s" gnus-topic-show-topic
964     "j" gnus-topic-jump-to-topic
965     "M" gnus-topic-move-matching
966     "C" gnus-topic-copy-matching
967     "\C-i" gnus-topic-indent
968     [tab] gnus-topic-indent
969     "r" gnus-topic-rename
970     "\177" gnus-topic-delete
971     [delete] gnus-topic-delete
972     "H" gnus-topic-toggle-display-empty-topics)
973
974   (gnus-define-keys (gnus-topic-sort-map "S" gnus-group-topic-map)
975     "s" gnus-topic-sort-groups
976     "a" gnus-topic-sort-groups-by-alphabet
977     "u" gnus-topic-sort-groups-by-unread
978     "l" gnus-topic-sort-groups-by-level
979     "v" gnus-topic-sort-groups-by-score
980     "r" gnus-topic-sort-groups-by-rank
981     "m" gnus-topic-sort-groups-by-method))
982
983 (defun gnus-topic-make-menu-bar ()
984   (unless (boundp 'gnus-topic-menu)
985     (easy-menu-define
986      gnus-topic-menu gnus-topic-mode-map ""
987      '("Topics"
988        ["Toggle topics" gnus-topic-mode t]
989        ("Groups"
990         ["Copy" gnus-topic-copy-group t]
991         ["Move" gnus-topic-move-group t]
992         ["Remove" gnus-topic-remove-group t]
993         ["Copy matching" gnus-topic-copy-matching t]
994         ["Move matching" gnus-topic-move-matching t])
995        ("Topics"
996         ["Goto" gnus-topic-jump-to-topic t]
997         ["Show" gnus-topic-show-topic t]
998         ["Hide" gnus-topic-hide-topic t]
999         ["Delete" gnus-topic-delete t]
1000         ["Rename" gnus-topic-rename t]
1001         ["Create" gnus-topic-create-topic t]
1002         ["Mark" gnus-topic-mark-topic t]
1003         ["Indent" gnus-topic-indent t]
1004         ["Sort" gnus-topic-sort-topics t]
1005         ["Toggle hide empty" gnus-topic-toggle-display-empty-topics t]
1006         ["Edit parameters" gnus-topic-edit-parameters t])
1007        ["List active" gnus-topic-list-active t]))))
1008
1009 (defun gnus-topic-mode (&optional arg redisplay)
1010   "Minor mode for topicsifying Gnus group buffers."
1011   (interactive (list current-prefix-arg t))
1012   (when (eq major-mode 'gnus-group-mode)
1013     (make-local-variable 'gnus-topic-mode)
1014     (setq gnus-topic-mode
1015           (if (null arg) (not gnus-topic-mode)
1016             (> (prefix-numeric-value arg) 0)))
1017     ;; Infest Gnus with topics.
1018     (if (not gnus-topic-mode)
1019         (setq gnus-goto-missing-group-function nil)
1020       (when (gnus-visual-p 'topic-menu 'menu)
1021         (gnus-topic-make-menu-bar))
1022       (gnus-set-format 'topic t)
1023       (gnus-add-minor-mode 'gnus-topic-mode " Topic" gnus-topic-mode-map)
1024       (add-hook 'gnus-group-catchup-group-hook 'gnus-topic-update-topic)
1025       (set (make-local-variable 'gnus-group-prepare-function)
1026            'gnus-group-prepare-topics)
1027       (set (make-local-variable 'gnus-group-get-parameter-function)
1028            'gnus-group-topic-parameters)
1029       (set (make-local-variable 'gnus-group-goto-next-group-function)
1030            'gnus-topic-goto-next-group)
1031       (set (make-local-variable 'gnus-group-indentation-function)
1032            'gnus-topic-group-indentation)
1033       (set (make-local-variable 'gnus-group-update-group-function)
1034            'gnus-topic-update-topics-containing-group)
1035       (set (make-local-variable 'gnus-group-sort-alist-function)
1036            'gnus-group-sort-topic)
1037       (setq gnus-group-change-level-function 'gnus-topic-change-level)
1038       (setq gnus-goto-missing-group-function 'gnus-topic-goto-missing-group)
1039       (make-local-hook 'gnus-check-bogus-groups-hook)
1040       (add-hook 'gnus-check-bogus-groups-hook 'gnus-topic-clean-alist)
1041       (setq gnus-topology-checked-p nil)
1042       ;; We check the topology.
1043       (when gnus-newsrc-alist
1044         (gnus-topic-check-topology))
1045       (gnus-run-hooks 'gnus-topic-mode-hook))
1046     ;; Remove topic infestation.
1047     (unless gnus-topic-mode
1048       (remove-hook 'gnus-summary-exit-hook 'gnus-topic-update-topic)
1049       (remove-hook 'gnus-group-change-level-function
1050                    'gnus-topic-change-level)
1051       (remove-hook 'gnus-check-bogus-groups-hook 'gnus-topic-clean-alist)
1052       (setq gnus-group-prepare-function 'gnus-group-prepare-flat)
1053       (setq gnus-group-sort-alist-function 'gnus-group-sort-flat))
1054     (when redisplay
1055       (gnus-group-list-groups))))
1056
1057 (defun gnus-topic-select-group (&optional all)
1058   "Select this newsgroup.
1059 No article is selected automatically.
1060 If ALL is non-nil, already read articles become readable.
1061 If ALL is a number, fetch this number of articles.
1062
1063 If performed over a topic line, toggle folding the topic."
1064   (interactive "P")
1065   (if (gnus-group-topic-p)
1066       (let ((gnus-group-list-mode
1067              (if all (cons (if (numberp all) all 7) t) gnus-group-list-mode)))
1068         (gnus-topic-fold all)
1069         (gnus-dribble-touch))
1070     (gnus-group-select-group all)))
1071
1072 (defun gnus-mouse-pick-topic (e)
1073   "Select the group or topic under the mouse pointer."
1074   (interactive "e")
1075   (mouse-set-point e)
1076   (gnus-topic-read-group nil))
1077
1078 (defun gnus-topic-expire-articles (topic)
1079   "Expire articles in this topic or group."
1080   (interactive (list (gnus-group-topic-name)))
1081   (if (not topic)
1082       (call-interactively 'gnus-group-expire-articles)
1083     (save-excursion
1084       (gnus-message 5 "Expiring groups in %s..." topic)
1085       (let ((gnus-group-marked
1086              (mapcar (lambda (entry) (car (nth 2 entry)))
1087                      (gnus-topic-find-groups topic gnus-level-killed t))))
1088         (gnus-group-expire-articles nil))
1089       (gnus-message 5 "Expiring groups in %s...done" topic))))
1090
1091 (defun gnus-topic-read-group (&optional all no-article group)
1092   "Read news in this newsgroup.
1093 If the prefix argument ALL is non-nil, already read articles become
1094 readable.  IF ALL is a number, fetch this number of articles.  If the
1095 optional argument NO-ARTICLE is non-nil, no article will be
1096 auto-selected upon group entry.  If GROUP is non-nil, fetch that
1097 group.
1098
1099 If performed over a topic line, toggle folding the topic."
1100   (interactive "P")
1101   (if (gnus-group-topic-p)
1102       (let ((gnus-group-list-mode
1103              (if all (cons (if (numberp all) all 7) t) gnus-group-list-mode)))
1104         (gnus-topic-fold all))
1105     (gnus-group-read-group all no-article group)))
1106
1107 (defun gnus-topic-create-topic (topic parent &optional previous full-topic)
1108   "Create a new TOPIC under PARENT.
1109 When used interactively, PARENT will be the topic under point."
1110   (interactive
1111    (list
1112     (read-string "New topic: ")
1113     (gnus-current-topic)))
1114   ;; Check whether this topic already exists.
1115   (when (gnus-topic-find-topology topic)
1116     (error "Topic already exists"))
1117   (unless parent
1118     (setq parent (caar gnus-topic-topology)))
1119   (let ((top (cdr (gnus-topic-find-topology parent)))
1120         (full-topic (or full-topic `((,topic visible)))))
1121     (unless top
1122       (error "No such parent topic: %s" parent))
1123     (if previous
1124         (progn
1125           (while (and (cdr top)
1126                       (not (equal (caaadr top) previous)))
1127             (setq top (cdr top)))
1128           (setcdr top (cons full-topic (cdr top))))
1129       (nconc top (list full-topic)))
1130     (unless (assoc topic gnus-topic-alist)
1131       (push (list topic) gnus-topic-alist)))
1132   (gnus-topic-enter-dribble)
1133   (gnus-group-list-groups)
1134   (gnus-topic-goto-topic topic))
1135
1136 ;; FIXME: 
1137 ;;  1. When the marked groups are overlapped with the process 
1138 ;;     region, the behavior of move or remove is not right.
1139 ;;  2. Can't process on several marked groups with a same name, 
1140 ;;     because gnus-group-marked only keeps one copy.
1141
1142 (defun gnus-topic-move-group (n topic &optional copyp)
1143   "Move the next N groups to TOPIC.
1144 If COPYP, copy the groups instead."
1145   (interactive
1146    (list current-prefix-arg
1147          (completing-read "Move to topic: " gnus-topic-alist nil t)))
1148   (let ((use-marked (and (not n) (not (gnus-region-active-p)) 
1149                          gnus-group-marked t))
1150         (groups (gnus-group-process-prefix n))
1151         (topicl (assoc topic gnus-topic-alist))
1152         (start-topic (gnus-group-topic-name))
1153         (start-group (progn (forward-line 1) (gnus-group-group-name)))
1154         entry)
1155     (if (and (not groups) (not copyp) start-topic)
1156         (gnus-topic-move start-topic topic)
1157       (mapcar
1158        (lambda (g)
1159          (gnus-group-remove-mark g use-marked)
1160          (when (and
1161                 (setq entry (assoc (gnus-current-topic) gnus-topic-alist))
1162                 (not copyp))
1163            (setcdr entry (gnus-delete-first g (cdr entry))))
1164          (nconc topicl (list g)))
1165        groups)
1166       (gnus-topic-enter-dribble)
1167       (if start-group
1168           (gnus-group-goto-group start-group)
1169         (gnus-topic-goto-topic start-topic))
1170       (gnus-group-list-groups))))
1171
1172 (defun gnus-topic-remove-group (&optional n)
1173   "Remove the current group from the topic."
1174   (interactive "P")
1175   (let ((use-marked (and (not n) (not (gnus-region-active-p)) 
1176                          gnus-group-marked t))
1177         (groups (gnus-group-process-prefix n)))
1178     (mapcar
1179      (lambda (group)
1180        (gnus-group-remove-mark group use-marked)
1181        (let ((topicl (assoc (gnus-current-topic) gnus-topic-alist))
1182              (buffer-read-only nil))
1183          (when (and topicl group)
1184            (gnus-delete-line)
1185            (gnus-delete-first group topicl))
1186          (gnus-topic-update-topic)))
1187      groups)
1188     (gnus-topic-enter-dribble)
1189     (gnus-group-position-point)))
1190
1191 (defun gnus-topic-copy-group (n topic)
1192   "Copy the current group to a topic."
1193   (interactive
1194    (list current-prefix-arg
1195          (completing-read "Copy to topic: " gnus-topic-alist nil t)))
1196   (gnus-topic-move-group n topic t))
1197
1198 (defun gnus-topic-kill-group (&optional n discard)
1199   "Kill the next N groups."
1200   (interactive "P")
1201   (if (gnus-group-topic-p)
1202       (let ((topic (gnus-group-topic-name)))
1203         (push (cons
1204                (gnus-topic-find-topology topic)
1205                (assoc topic gnus-topic-alist))
1206               gnus-topic-killed-topics)
1207         (gnus-topic-remove-topic nil t)
1208         (gnus-topic-find-topology topic nil nil gnus-topic-topology)
1209         (gnus-topic-enter-dribble))
1210     (gnus-group-kill-group n discard)
1211     (if (not (gnus-group-topic-p))
1212         (gnus-topic-update-topic)
1213       ;; Move up one line so that we update the right topic.
1214       (forward-line -1)
1215       (gnus-topic-update-topic)
1216       (forward-line 1))))
1217
1218 (defun gnus-topic-yank-group (&optional arg)
1219   "Yank the last topic."
1220   (interactive "p")
1221   (if gnus-topic-killed-topics
1222       (let* ((previous
1223               (or (gnus-group-topic-name)
1224                   (gnus-topic-next-topic (gnus-current-topic))))
1225              (data (pop gnus-topic-killed-topics))
1226              (alist (cdr data))
1227              (item (cdar data)))
1228         (push alist gnus-topic-alist)
1229         (gnus-topic-create-topic
1230          (caar item) (gnus-topic-parent-topic previous) previous
1231          item)
1232         (gnus-topic-enter-dribble)
1233         (gnus-topic-goto-topic (caar item)))
1234     (let* ((prev (gnus-group-group-name))
1235            (gnus-topic-inhibit-change-level t)
1236            (gnus-group-indentation
1237             (make-string
1238              (* gnus-topic-indent-level
1239                 (or (save-excursion
1240                       (gnus-topic-goto-topic (gnus-current-topic))
1241                       (gnus-group-topic-level))
1242                     0))
1243              ? ))
1244            yanked alist)
1245       ;; We first yank the groups the normal way...
1246       (setq yanked (gnus-group-yank-group arg))
1247       ;; Then we enter the yanked groups into the topics they belong
1248       ;; to.
1249       (setq alist (assoc (save-excursion
1250                            (forward-line -1)
1251                            (gnus-current-topic))
1252                          gnus-topic-alist))
1253       (when (stringp yanked)
1254         (setq yanked (list yanked)))
1255       (if (not prev)
1256           (nconc alist yanked)
1257         (if (not (cdr alist))
1258             (setcdr alist (nconc yanked (cdr alist)))
1259           (while (cdr alist)
1260             (when (equal (cadr alist) prev)
1261               (setcdr alist (nconc yanked (cdr alist)))
1262               (setq alist nil))
1263             (setq alist (cdr alist))))))
1264     (gnus-topic-update-topic)))
1265
1266 (defun gnus-topic-hide-topic (&optional permanent)
1267   "Hide the current topic.
1268 If PERMANENT, make it stay hidden in subsequent sessions as well."
1269   (interactive "P")
1270   (when (gnus-current-topic)
1271     (gnus-topic-goto-topic (gnus-current-topic))
1272     (setcar (cddr (assoc (gnus-current-topic) gnus-topic-topology)) 'hidden)
1273     (gnus-topic-remove-topic nil nil)))
1274
1275 (defun gnus-topic-show-topic (&optional permanent)
1276   "Show the hidden topic.
1277 If PERMANENT, make it stay shown in subsequent sessions as well."
1278   (interactive "P")
1279   (when (gnus-group-topic-p)
1280     (setcar (cddr (assoc (gnus-current-topic) gnus-topic-topology)) nil)
1281     (gnus-topic-remove-topic t nil)))
1282
1283 (defun gnus-topic-mark-topic (topic &optional unmark)
1284   "Mark all groups in the topic with the process mark."
1285   (interactive (list (gnus-group-topic-name)))
1286   (if (not topic)
1287       (call-interactively 'gnus-group-mark-group)
1288     (save-excursion
1289       (let ((groups (gnus-topic-find-groups topic gnus-level-killed t)))
1290         (while groups
1291           (funcall (if unmark 'gnus-group-remove-mark 'gnus-group-set-mark)
1292                    (gnus-info-group (nth 2 (pop groups)))))))))
1293
1294 (defun gnus-topic-unmark-topic (topic &optional unmark)
1295   "Remove the process mark from all groups in the topic."
1296   (interactive (list (gnus-group-topic-name)))
1297   (if (not topic)
1298       (call-interactively 'gnus-group-unmark-group)
1299     (gnus-topic-mark-topic topic t)))
1300
1301 (defun gnus-topic-get-new-news-this-topic (&optional n)
1302   "Check for new news in the current topic."
1303   (interactive "P")
1304   (if (not (gnus-group-topic-p))
1305       (gnus-group-get-new-news-this-group n)
1306     (gnus-topic-mark-topic (gnus-group-topic-name))
1307     (gnus-group-get-new-news-this-group)))
1308
1309 (defun gnus-topic-move-matching (regexp topic &optional copyp)
1310   "Move all groups that match REGEXP to some topic."
1311   (interactive
1312    (let (topic)
1313      (nreverse
1314       (list
1315        (setq topic (completing-read "Move to topic: " gnus-topic-alist nil t))
1316        (read-string (format "Move to %s (regexp): " topic))))))
1317   (gnus-group-mark-regexp regexp)
1318   (gnus-topic-move-group nil topic copyp))
1319
1320 (defun gnus-topic-copy-matching (regexp topic &optional copyp)
1321   "Copy all groups that match REGEXP to some topic."
1322   (interactive
1323    (let (topic)
1324      (nreverse
1325       (list
1326        (setq topic (completing-read "Copy to topic: " gnus-topic-alist nil t))
1327        (read-string (format "Copy to %s (regexp): " topic))))))
1328   (gnus-topic-move-matching regexp topic t))
1329
1330 (defun gnus-topic-delete (topic)
1331   "Delete a topic."
1332   (interactive (list (gnus-group-topic-name)))
1333   (unless topic
1334     (error "No topic to be deleted"))
1335   (let ((entry (assoc topic gnus-topic-alist))
1336         (buffer-read-only nil))
1337     (when (cdr entry)
1338       (error "Topic not empty"))
1339     ;; Delete if visible.
1340     (when (gnus-topic-goto-topic topic)
1341       (gnus-delete-line))
1342     ;; Remove from alist.
1343     (setq gnus-topic-alist (delq entry gnus-topic-alist))
1344     ;; Remove from topology.
1345     (gnus-topic-find-topology topic nil nil 'delete)
1346     (gnus-dribble-touch)))
1347
1348 (defun gnus-topic-rename (old-name new-name)
1349   "Rename a topic."
1350   (interactive
1351    (let ((topic (gnus-current-topic)))
1352      (list topic
1353            (read-string (format "Rename %s to: " topic)))))
1354   ;; Check whether the new name exists.
1355   (when (gnus-topic-find-topology new-name)
1356     (error "Topic '%s' already exists" new-name))
1357   ;; "nil" is an invalid name, for reasons I'd rather not go
1358   ;; into here.  Trust me.
1359   (when (equal new-name "nil")
1360     (error "Invalid name: %s" nil))
1361   ;; Do the renaming.
1362   (let ((top (gnus-topic-find-topology old-name))
1363         (entry (assoc old-name gnus-topic-alist)))
1364     (when top
1365       (setcar (cadr top) new-name))
1366     (when entry
1367       (setcar entry new-name))
1368     (forward-line -1)
1369     (gnus-dribble-touch)
1370     (gnus-group-list-groups)
1371     (forward-line 1)))
1372
1373 (defun gnus-topic-indent (&optional unindent)
1374   "Indent a topic -- make it a sub-topic of the previous topic.
1375 If UNINDENT, remove an indentation."
1376   (interactive "P")
1377   (if unindent
1378       (gnus-topic-unindent)
1379     (let* ((topic (gnus-current-topic))
1380            (parent (gnus-topic-previous-topic topic))
1381            (buffer-read-only nil))
1382       (unless parent
1383         (error "Nothing to indent %s into" topic))
1384       (when topic
1385         (gnus-topic-goto-topic topic)
1386         (gnus-topic-kill-group)
1387         (push (cdar gnus-topic-killed-topics) gnus-topic-alist)
1388         (gnus-topic-create-topic
1389          topic parent nil (cdaar gnus-topic-killed-topics))
1390         (pop gnus-topic-killed-topics)
1391         (or (gnus-topic-goto-topic topic)
1392             (gnus-topic-goto-topic parent))))))
1393
1394 (defun gnus-topic-unindent ()
1395   "Unindent a topic."
1396   (interactive)
1397   (let* ((topic (gnus-current-topic))
1398          (parent (gnus-topic-parent-topic topic))
1399          (grandparent (gnus-topic-parent-topic parent)))
1400     (unless grandparent
1401       (error "Nothing to indent %s into" topic))
1402     (when topic
1403       (gnus-topic-goto-topic topic)
1404       (gnus-topic-kill-group)
1405       (push (cdar gnus-topic-killed-topics) gnus-topic-alist)
1406       (gnus-topic-create-topic
1407        topic grandparent (gnus-topic-next-topic parent)
1408        (cdaar gnus-topic-killed-topics))
1409       (pop gnus-topic-killed-topics)
1410       (gnus-topic-goto-topic topic))))
1411
1412 (defun gnus-topic-list-active (&optional force)
1413   "List all groups that Gnus knows about in a topicsified fashion.
1414 If FORCE, always re-read the active file."
1415   (interactive "P")
1416   (when force
1417     (gnus-get-killed-groups))
1418   (gnus-topic-grok-active force)
1419   (let ((gnus-topic-topology gnus-topic-active-topology)
1420         (gnus-topic-alist gnus-topic-active-alist)
1421         gnus-killed-list gnus-zombie-list)
1422     (gnus-group-list-groups gnus-level-killed nil 1)))
1423
1424 (defun gnus-topic-toggle-display-empty-topics ()
1425   "Show/hide topics that have no unread articles."
1426   (interactive)
1427   (setq gnus-topic-display-empty-topics
1428         (not gnus-topic-display-empty-topics))
1429   (gnus-group-list-groups)
1430   (message "%s empty topics"
1431            (if gnus-topic-display-empty-topics
1432                "Showing" "Hiding")))
1433
1434 ;;; Topic sorting functions
1435
1436 (defun gnus-topic-edit-parameters (group)
1437   "Edit the group parameters of GROUP.
1438 If performed on a topic, edit the topic parameters instead."
1439   (interactive (list (gnus-group-group-name)))
1440   (if group
1441       (gnus-group-edit-group-parameters group)
1442     (if (not (gnus-group-topic-p))
1443         (error "Nothing to edit on the current line")
1444       (let ((topic (gnus-group-topic-name)))
1445         (gnus-edit-form
1446          (gnus-topic-parameters topic)
1447          (format "Editing the topic parameters for `%s'."
1448                  (or group topic))
1449          `(lambda (form)
1450             (gnus-topic-set-parameters ,topic form)))))))
1451
1452 (defun gnus-group-sort-topic (func reverse)
1453   "Sort groups in the topics according to FUNC and REVERSE."
1454   (let ((alist gnus-topic-alist))
1455     (while alist
1456       ;; !!!Sometimes nil elements sneak into the alist,
1457       ;; for some reason or other.
1458       (setcar alist (delq nil (car alist)))
1459       (setcar alist (delete "dummy.group" (car alist)))
1460       (gnus-topic-sort-topic (pop alist) func reverse))))
1461
1462 (defun gnus-topic-sort-topic (topic func reverse)
1463   ;; Each topic only lists the name of the group, while
1464   ;; the sort predicates expect group infos as inputs.
1465   ;; So we first transform the group names into infos,
1466   ;; then sort, and then transform back into group names.
1467   (setcdr
1468    topic
1469    (mapcar
1470     (lambda (info) (gnus-info-group info))
1471     (sort
1472      (mapcar
1473       (lambda (group) (gnus-get-info group))
1474       (cdr topic))
1475      func)))
1476   ;; Do the reversal, if necessary.
1477   (when reverse
1478     (setcdr topic (nreverse (cdr topic)))))
1479
1480 (defun gnus-topic-sort-groups (func &optional reverse)
1481   "Sort the current topic according to FUNC.
1482 If REVERSE, reverse the sorting order."
1483   (interactive (list gnus-group-sort-function current-prefix-arg))
1484   (let ((topic (assoc (gnus-current-topic) gnus-topic-alist)))
1485     (gnus-topic-sort-topic
1486      topic (gnus-make-sort-function func) reverse)
1487     (gnus-group-list-groups)))
1488
1489 (defun gnus-topic-sort-groups-by-alphabet (&optional reverse)
1490   "Sort the current topic alphabetically by group name.
1491 If REVERSE, sort in reverse order."
1492   (interactive "P")
1493   (gnus-topic-sort-groups 'gnus-group-sort-by-alphabet reverse))
1494
1495 (defun gnus-topic-sort-groups-by-unread (&optional reverse)
1496   "Sort the current topic by number of unread articles.
1497 If REVERSE, sort in reverse order."
1498   (interactive "P")
1499   (gnus-topic-sort-groups 'gnus-group-sort-by-unread reverse))
1500
1501 (defun gnus-topic-sort-groups-by-level (&optional reverse)
1502   "Sort the current topic by group level.
1503 If REVERSE, sort in reverse order."
1504   (interactive "P")
1505   (gnus-topic-sort-groups 'gnus-group-sort-by-level reverse))
1506
1507 (defun gnus-topic-sort-groups-by-score (&optional reverse)
1508   "Sort the current topic by group score.
1509 If REVERSE, sort in reverse order."
1510   (interactive "P")
1511   (gnus-topic-sort-groups 'gnus-group-sort-by-score reverse))
1512
1513 (defun gnus-topic-sort-groups-by-rank (&optional reverse)
1514   "Sort the current topic by group rank.
1515 If REVERSE, sort in reverse order."
1516   (interactive "P")
1517   (gnus-topic-sort-groups 'gnus-group-sort-by-rank reverse))
1518
1519 (defun gnus-topic-sort-groups-by-method (&optional reverse)
1520   "Sort the current topic alphabetically by backend name.
1521 If REVERSE, sort in reverse order."
1522   (interactive "P")
1523   (gnus-topic-sort-groups 'gnus-group-sort-by-method reverse))
1524
1525 (defun gnus-topic-sort-topics-1 (top reverse)
1526   (if (cdr top)
1527       (let ((subtop
1528              (mapcar `(lambda (top)
1529                         (gnus-topic-sort-topics-1 top ,reverse))
1530                      (sort (cdr top)
1531                            '(lambda (t1 t2) 
1532                               (string-lessp (caar t1) (caar t2)))))))
1533         (setcdr top (if reverse (reverse subtop) subtop))))
1534   top)
1535
1536 (defun gnus-topic-sort-topics (&optional topic reverse)
1537   "Sort topics in TOPIC alphabeticaly by topic name.
1538 If REVERSE, reverse the sorting order."
1539   (interactive 
1540    (list (completing-read "Sort topics in : " gnus-topic-alist nil t 
1541                           (gnus-current-topic))
1542          current-prefix-arg))
1543   (let ((topic-topology (or (and topic (cdr (gnus-topic-find-topology topic)))
1544                             gnus-topic-topology)))
1545     (gnus-topic-sort-topics-1 topic-topology reverse)
1546     (gnus-topic-enter-dribble)
1547     (gnus-group-list-groups)
1548     (gnus-topic-goto-topic topic)))
1549
1550 (defun gnus-topic-move (current to)
1551   "Move the CURRENT topic to TO."
1552   (interactive 
1553    (list 
1554     (gnus-group-topic-name)
1555     (completing-read "Move to topic: " gnus-topic-alist nil t)))
1556   (unless (and current to)
1557     (error "Can't find topic"))
1558   (let ((current-top (cdr (gnus-topic-find-topology current)))
1559         (to-top (cdr (gnus-topic-find-topology to))))
1560     (unless current-top
1561       (error "Can't find topic `%s'" current))
1562     (unless to-top
1563       (error "Can't find topic `%s'" to))
1564     (if (gnus-topic-find-topology to current-top 0);; Don't care the level
1565         (error "Can't move `%s' to its sub-level" current))
1566     (gnus-topic-find-topology current nil nil 'delete)
1567     (while (cdr to-top)
1568       (setq to-top (cdr to-top)))
1569     (setcdr to-top (list current-top))
1570     (gnus-topic-enter-dribble)
1571     (gnus-group-list-groups)
1572     (gnus-topic-goto-topic current)))
1573
1574 (defun gnus-subscribe-topics (newsgroup)
1575   (catch 'end
1576     (let (match gnus-group-change-level-function)
1577       (dolist (topic (gnus-topic-list))
1578         (when (and (setq match (cdr (assq 'subscribe
1579                                           (gnus-topic-parameters topic))))
1580                    (string-match match newsgroup))
1581           ;; Just subscribe the group.
1582           (gnus-subscribe-alphabetically newsgroup)
1583           ;; Add the group to the topic.
1584           (nconc (assoc topic gnus-topic-alist) (list newsgroup))
1585           (throw 'end t))))))
1586           
1587 (provide 'gnus-topic)
1588
1589 ;;; gnus-topic.el ends here