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