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