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