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