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