a76233e278482a8297a628e7add8e3f120c1dbfb
[gnus] / lisp / gnus-kill.el
1 ;;; gnus-kill --- kill commands for Gnus
2 ;; Copyright (C) 1995 Free Software Foundation, Inc.
3
4 ;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
5 ;;      Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to
22 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (require 'gnus)
29
30 (defvar gnus-kill-file-mode-hook nil
31   "A hook for Gnus kill file mode.")
32
33 (defvar gnus-winconf-kill-file nil)
34
35 \f
36
37 (defmacro gnus-raise (field expression level)
38   (` (gnus-kill (, field) (, expression)
39                 (function (gnus-summary-raise-score (, level))) t)))
40
41 (defmacro gnus-lower (field expression level)
42   (` (gnus-kill (, field) (, expression)
43                 (function (gnus-summary-raise-score (- (, level)))) t)))
44
45 ;;;
46 ;;; Gnus Kill File Mode
47 ;;;
48
49 (defvar gnus-kill-file-mode-map nil)
50
51 (if gnus-kill-file-mode-map
52     nil
53   (setq gnus-kill-file-mode-map (copy-keymap emacs-lisp-mode-map))
54   (define-key gnus-kill-file-mode-map 
55     "\C-c\C-k\C-s" 'gnus-kill-file-kill-by-subject)
56   (define-key gnus-kill-file-mode-map
57     "\C-c\C-k\C-a" 'gnus-kill-file-kill-by-author)
58   (define-key gnus-kill-file-mode-map
59     "\C-c\C-k\C-a" 'gnus-kill-file-kill-by-thread)
60   (define-key gnus-kill-file-mode-map 
61     "\C-c\C-k\C-a" 'gnus-kill-file-kill-by-xref)
62   (define-key gnus-kill-file-mode-map
63     "\C-c\C-a" 'gnus-kill-file-apply-buffer)
64   (define-key gnus-kill-file-mode-map
65     "\C-c\C-e" 'gnus-kill-file-apply-last-sexp)
66   (define-key gnus-kill-file-mode-map 
67     "\C-c\C-c" 'gnus-kill-file-exit))
68
69 (defun gnus-kill-file-mode ()
70   "Major mode for editing kill files.
71
72 If you are using this mode - you probably shouldn't.  Kill files
73 perform badly and paint with a pretty broad brush.  Score files, on
74 the other hand, are vastly faster (40x speedup) and give you more
75 control over what to do.
76
77 In addition to Emacs-Lisp Mode, the following commands are available:
78
79 \\{gnus-kill-file-mode-map}
80
81   A kill file contains Lisp expressions to be applied to a selected
82 newsgroup.  The purpose is to mark articles as read on the basis of
83 some set of regexps.  A global kill file is applied to every newsgroup,
84 and a local kill file is applied to a specified newsgroup.  Since a
85 global kill file is applied to every newsgroup, for better performance
86 use a local one.
87
88   A kill file can contain any kind of Emacs Lisp expressions expected
89 to be evaluated in the Summary buffer.  Writing Lisp programs for this
90 purpose is not so easy because the internal working of Gnus must be
91 well-known.  For this reason, Gnus provides a general function which
92 does this easily for non-Lisp programmers.
93
94   The `gnus-kill' function executes commands available in Summary Mode
95 by their key sequences. `gnus-kill' should be called with FIELD,
96 REGEXP and optional COMMAND and ALL.  FIELD is a string representing
97 the header field or an empty string.  If FIELD is an empty string, the
98 entire article body is searched for.  REGEXP is a string which is
99 compared with FIELD value. COMMAND is a string representing a valid
100 key sequence in Summary mode or Lisp expression. COMMAND defaults to
101 '(gnus-summary-mark-as-read nil \"X\").  Make sure that COMMAND is
102 executed in the Summary buffer.  If the second optional argument ALL
103 is non-nil, the COMMAND is applied to articles which are already
104 marked as read or unread.  Articles which are marked are skipped over
105 by default.
106
107   For example, if you want to mark articles of which subjects contain
108 the string `AI' as read, a possible kill file may look like:
109
110         (gnus-kill \"Subject\" \"AI\")
111
112   If you want to mark articles with `D' instead of `X', you can use
113 the following expression:
114
115         (gnus-kill \"Subject\" \"AI\" \"d\")
116
117 In this example it is assumed that the command
118 `gnus-summary-mark-as-read-forward' is assigned to `d' in Summary Mode.
119
120   It is possible to delete unnecessary headers which are marked with
121 `X' in a kill file as follows:
122
123         (gnus-expunge \"X\")
124
125   If the Summary buffer is empty after applying kill files, Gnus will
126 exit the selected newsgroup normally.  If headers which are marked
127 with `D' are deleted in a kill file, it is impossible to read articles
128 which are marked as read in the previous Gnus sessions.  Marks other
129 than `D' should be used for articles which should really be deleted.
130
131 Entry to this mode calls emacs-lisp-mode-hook and
132 gnus-kill-file-mode-hook with no arguments, if that value is non-nil."
133   (interactive)
134   (kill-all-local-variables)
135   (use-local-map gnus-kill-file-mode-map)
136   (set-syntax-table emacs-lisp-mode-syntax-table)
137   (setq major-mode 'gnus-kill-file-mode)
138   (setq mode-name "Kill")
139   (lisp-mode-variables nil)
140   (run-hooks 'emacs-lisp-mode-hook 'gnus-kill-file-mode-hook))
141
142 (defun gnus-kill-file-edit-file (newsgroup)
143   "Begin editing a kill file for NEWSGROUP.
144 If NEWSGROUP is nil, the global kill file is selected."
145   (interactive "sNewsgroup: ")
146   (let ((file (gnus-newsgroup-kill-file newsgroup)))
147     (gnus-make-directory (file-name-directory file))
148     ;; Save current window configuration if this is first invocation.
149     (or (and (get-file-buffer file)
150              (get-buffer-window (get-file-buffer file)))
151         (setq gnus-winconf-kill-file (current-window-configuration)))
152     ;; Hack windows.
153     (let ((buffer (find-file-noselect file)))
154       (cond ((get-buffer-window buffer)
155              (pop-to-buffer buffer))
156             ((eq major-mode 'gnus-group-mode)
157              (gnus-configure-windows '(1 0 0)) ;Take all windows.
158              (pop-to-buffer gnus-group-buffer)
159              ;; Fix by sachs@SLINKY.CS.NYU.EDU (Jay Sachs).
160              (let ((gnus-summary-buffer buffer))
161                (gnus-configure-windows '(1 1 0))) ;Split into two.
162              (pop-to-buffer buffer))
163             ((eq major-mode 'gnus-summary-mode)
164              (gnus-configure-windows 'article)
165              (pop-to-buffer gnus-article-buffer)
166              (bury-buffer gnus-article-buffer)
167              (switch-to-buffer buffer))
168             (t                          ;No good rules.
169              (find-file-other-window file))))
170     (gnus-kill-file-mode)))
171
172 ;; Fix by Sudish Joseph <joseph@cis.ohio-state.edu>.
173 (defun gnus-kill-set-kill-buffer ()
174   (let* ((file (gnus-newsgroup-kill-file gnus-newsgroup-name))
175          (buffer (find-file-noselect file)))
176     (set-buffer buffer)
177     (gnus-kill-file-mode)
178     (bury-buffer buffer)))
179
180 (defun gnus-kill-file-enter-kill (field regexp)
181   ;; Enter kill file entry.
182   ;; FIELD: String containing the name of the header field to kill.
183   ;; REGEXP: The string to kill.
184   (save-excursion
185     (let (string)
186       (gnus-kill-set-kill-buffer)
187       (goto-char (point-max))
188       (insert (setq string (format "(gnus-kill %S %S)\n" field regexp)))
189       (gnus-kill-file-apply-string string))))
190     
191 (defun gnus-kill-file-kill-by-subject ()
192   "Kill by subject."
193   (interactive)
194   (gnus-kill-file-enter-kill
195    "Subject" 
196    (regexp-quote 
197     (gnus-simplify-subject (header-subject gnus-current-headers)))))
198   
199 (defun gnus-kill-file-kill-by-author ()
200   "Kill by author."
201   (interactive)
202   (gnus-kill-file-enter-kill
203    "From" (regexp-quote (header-from gnus-current-headers))))
204  
205 (defun gnus-kill-file-kill-by-thread ()
206   "Kill by author."
207   (interactive "p")
208   (gnus-kill-file-enter-kill
209    "References" (regexp-quote (header-id gnus-current-headers))))
210  
211 (defun gnus-kill-file-kill-by-xref ()
212   "Kill by Xref."
213   (interactive)
214   (let ((xref (header-xref gnus-current-headers))
215         (start 0)
216         group)
217     (if xref
218         (while (string-match " \\([^ \t]+\\):" xref start)
219           (setq start (match-end 0))
220           (if (not (string= 
221                     (setq group 
222                           (substring xref (match-beginning 1) (match-end 1)))
223                     gnus-newsgroup-name))
224               (gnus-kill-file-enter-kill 
225                "Xref" (concat " " (regexp-quote group) ":"))))
226       (gnus-kill-file-enter-kill "Xref" ""))))
227
228 (defun gnus-kill-file-raise-followups-to-author (level)
229   "Raise score for all followups to the current author."
230   (interactive "p")
231   (let ((name (header-from gnus-current-headers))
232         string)
233     (save-excursion
234       (gnus-kill-set-kill-buffer)
235       (goto-char (point-min))
236       (setq name (read-string (concat "Add " level
237                                       " to followup articles to: ")
238                               (regexp-quote name)))
239       (setq 
240        string
241        (format
242         "(gnus-kill %S %S '(gnus-summary-temporarily-raise-by-thread %S))\n"
243         "From" name level))
244       (insert string)
245       (gnus-kill-file-apply-string string))
246     (message "Added temporary score file entry for followups to %s." name)))
247
248 (defun gnus-kill-file-apply-buffer ()
249   "Apply current buffer to current newsgroup."
250   (interactive)
251   (if (and gnus-current-kill-article
252            (get-buffer gnus-summary-buffer))
253       ;; Assume newsgroup is selected.
254       (gnus-kill-file-apply-string (buffer-string))
255     (ding) (message "No newsgroup is selected.")))
256
257 (defun gnus-kill-file-apply-string (string)
258   "Apply STRING to current newsgroup."
259   (interactive)
260   (let ((string (concat "(progn \n" string "\n)")))
261     (save-excursion
262       (save-window-excursion
263         (pop-to-buffer gnus-summary-buffer)
264         (eval (car (read-from-string string)))))))
265
266 (defun gnus-kill-file-apply-last-sexp ()
267   "Apply sexp before point in current buffer to current newsgroup."
268   (interactive)
269   (if (and gnus-current-kill-article
270            (get-buffer gnus-summary-buffer))
271       ;; Assume newsgroup is selected.
272       (let ((string
273              (buffer-substring
274               (save-excursion (forward-sexp -1) (point)) (point))))
275         (save-excursion
276           (save-window-excursion
277             (pop-to-buffer gnus-summary-buffer)
278             (eval (car (read-from-string string))))))
279     (ding) (message "No newsgroup is selected.")))
280
281 (defun gnus-kill-file-exit ()
282   "Save a kill file, then return to the previous buffer."
283   (interactive)
284   (save-buffer)
285   (let ((killbuf (current-buffer)))
286     ;; We don't want to return to article buffer.
287     (and (get-buffer gnus-article-buffer)
288          (bury-buffer gnus-article-buffer))
289     ;; Delete the KILL file windows.
290     (delete-windows-on killbuf)
291     ;; Restore last window configuration if available.
292     (and gnus-winconf-kill-file
293          (set-window-configuration gnus-winconf-kill-file))
294     (setq gnus-winconf-kill-file nil)
295     ;; Kill the KILL file buffer.  Suggested by tale@pawl.rpi.edu.
296     (kill-buffer killbuf)))
297
298 ;; For kill files
299
300 (defun gnus-Newsgroup-kill-file (newsgroup)
301   "Return the name of a kill file for NEWSGROUP.
302 If NEWSGROUP is nil, return the global kill file instead."
303   (cond ((or (null newsgroup)
304              (string-equal newsgroup ""))
305          ;; The global kill file is placed at top of the directory.
306          (expand-file-name gnus-kill-file-name
307                            (or gnus-kill-files-directory "~/News")))
308         (gnus-use-long-file-name
309          ;; Append ".KILL" to capitalized newsgroup name.
310          (expand-file-name (concat (gnus-capitalize-newsgroup newsgroup)
311                                    "." gnus-kill-file-name)
312                            (or gnus-kill-files-directory "~/News")))
313         (t
314          ;; Place "KILL" under the hierarchical directory.
315          (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
316                                    "/" gnus-kill-file-name)
317                            (or gnus-kill-files-directory "~/News")))))
318
319 (defalias 'gnus-expunge 'gnus-summary-remove-lines-marked-with)
320
321 (defun gnus-apply-kill-file-internal ()
322   "Apply a kill file to the current newsgroup.
323 Returns the number of articles marked as read."
324   (let* ((kill-files (list (gnus-newsgroup-kill-file nil)
325                            (gnus-newsgroup-kill-file gnus-newsgroup-name)))
326          (unreads (length gnus-newsgroup-unreads))
327          (gnus-summary-inhibit-highlight t)
328          (mark-below (or gnus-summary-mark-below gnus-summary-default-score 0))
329          (expunge-below gnus-summary-expunge-below)
330          form beg)
331     (setq gnus-newsgroup-kill-headers nil)
332     (or gnus-newsgroup-headers-hashtb-by-number
333         (gnus-make-headers-hashtable-by-number))
334     ;; If there are any previously scored articles, we remove these
335     ;; from the `gnus-newsgroup-headers' list that the score functions
336     ;; will see. This is probably pretty wasteful when it comes to
337     ;; conses, but is, I think, faster than having to assq in every
338     ;; single score funtion.
339     (let ((files kill-files))
340       (while files
341         (if (file-exists-p (car files))
342             (let ((headers gnus-newsgroup-headers))
343               (if gnus-kill-killed
344                   (setq gnus-newsgroup-kill-headers
345                         (mapcar (lambda (header) (header-number header))
346                                 headers))
347                 (while headers
348                   (or (gnus-member-of-range 
349                        (header-number (car headers)) 
350                        gnus-newsgroup-killed)
351                       (setq gnus-newsgroup-kill-headers 
352                             (cons (header-number (car headers))
353                                   gnus-newsgroup-kill-headers)))
354                   (setq headers (cdr headers))))
355               (setq files nil))
356           (setq files (cdr files)))))
357     (if gnus-newsgroup-kill-headers
358         (save-excursion
359           (while kill-files
360             (if (file-exists-p (car kill-files))
361                 (progn
362                   (message "Processing kill file %s..." (car kill-files))
363                   (find-file (car kill-files))
364                   (gnus-kill-file-mode)
365                   (gnus-add-current-to-buffer-list)
366                   (goto-char (point-min))
367                   (while (progn
368                            (setq beg (point))
369                            (setq form (condition-case nil 
370                                           (read (current-buffer)) 
371                                         (error nil))))
372                     (if (or (eq (car form) 'gnus-kill)
373                             (eq (car form) 'gnus-raise)
374                             (eq (car form) 'gnus-lower))
375                         (progn
376                           (delete-region beg (point))
377                           (insert (or (eval form) "")))
378                       (condition-case ()
379                           (eval form)
380                         (error nil))))
381                   (and (buffer-modified-p) (save-buffer))
382                   (message "Processing kill file %s...done" (car kill-files))))
383             (setq kill-files (cdr kill-files)))))
384     (if beg
385         (let ((nunreads (- unreads (length gnus-newsgroup-unreads))))
386           (or (eq nunreads 0)
387               (message "Marked %d articles as read" nunreads))
388           nunreads)
389       0)))
390
391 ;; Kill changes and new format by suggested by JWZ and Sudish Joseph
392 ;; <joseph@cis.ohio-state.edu>.  
393 (defun gnus-kill (field regexp &optional exe-command all)
394   "If FIELD of an article matches REGEXP, execute COMMAND.
395 Optional 1st argument COMMAND is default to
396         (gnus-summary-mark-as-read nil \"X\").
397 If optional 2nd argument ALL is non-nil, articles marked are also applied to.
398 If FIELD is an empty string (or nil), entire article body is searched for.
399 COMMAND must be a lisp expression or a string representing a key sequence."
400   ;; We don't want to change current point nor window configuration.
401   (save-excursion
402     (save-window-excursion
403       ;; Selected window must be summary buffer to execute keyboard
404       ;; macros correctly. See command_loop_1.
405       (switch-to-buffer gnus-summary-buffer 'norecord)
406       (goto-char (point-min))           ;From the beginning.
407       (let ((kill-list regexp)
408             (date (current-time-string))
409             (command (or exe-command '(gnus-summary-mark-as-read 
410                                        nil gnus-kill-file-mark)))
411             kill kdate prev)
412         (if (listp kill-list)
413             ;; It is a list.
414             (if (not (consp (cdr kill-list)))
415                 ;; It's on the form (regexp . date).
416                 (if (zerop (gnus-execute field (car kill-list) 
417                                          command nil (not all)))
418                     (if (> (gnus-days-between date (cdr kill-list))
419                            gnus-score-expiry-days)
420                         (setq regexp nil))
421                   (setcdr kill-list date))
422               (while (setq kill (car kill-list))
423                 (if (consp kill)
424                     ;; It's a temporary kill.
425                     (progn
426                       (setq kdate (cdr kill))
427                       (if (zerop (gnus-execute 
428                                   field (car kill) command nil (not all)))
429                           (if (> (gnus-days-between date kdate)
430                                  gnus-score-expiry-days)
431                               ;; Time limit has been exceeded, so we
432                               ;; remove the match.
433                               (if prev
434                                   (setcdr prev (cdr kill-list))
435                                 (setq regexp (cdr regexp))))
436                         ;; Successful kill. Set the date to today.
437                         (setcdr kill date)))
438                   ;; It's a permanent kill.
439                   (gnus-execute field kill command nil (not all)))
440                 (setq prev kill-list)
441                 (setq kill-list (cdr kill-list))))
442           (gnus-execute field kill-list command nil (not all))))))
443   (if (and (eq major-mode 'gnus-kill-file-mode) regexp)
444       (gnus-pp-gnus-kill
445        (nconc (list 'gnus-kill field 
446                     (if (consp regexp) (list 'quote regexp) regexp))
447               (if (or exe-command all) (list (list 'quote exe-command)))
448               (if all (list t) nil)))))
449
450 (defun gnus-pp-gnus-kill (object)
451   (if (or (not (consp (nth 2 object)))
452           (not (consp (cdr (nth 2 object))))
453           (and (eq 'quote (car (nth 2 object)))
454                (not (consp (cdr (car (cdr (nth 2 object))))))))
455       (concat "\n" (prin1-to-string object))
456     (save-excursion
457       (set-buffer (get-buffer-create "*Gnus PP*"))
458       (buffer-disable-undo (current-buffer))
459       (erase-buffer)
460       (insert (format "\n(%S %S\n  '(" (nth 0 object) (nth 1 object)))
461       (let ((klist (car (cdr (nth 2 object))))
462             (first t))
463         (while klist
464           (insert (if first (progn (setq first nil) "")  "\n    ")
465                   (prin1-to-string (car klist)))
466           (setq klist (cdr klist))))
467       (insert ")")
468       (and (nth 3 object)
469            (insert "\n  " 
470                    (if (and (consp (nth 3 object))
471                             (not (eq 'quote (car (nth 3 object))))) 
472                        "'" "")
473                    (prin1-to-string (nth 3 object))))
474       (and (nth 4 object)
475            (insert "\n  t"))
476       (insert ")")
477       (prog1
478           (buffer-substring (point-min) (point-max))
479         (kill-buffer (current-buffer))))))
480
481 (defun gnus-execute-1 (function regexp form header)
482   (save-excursion
483     (let (did-kill)
484       (if (null header)
485           nil                           ;Nothing to do.
486         (if function
487             ;; Compare with header field.
488             (let (value)
489               (and header
490                    (progn
491                      (setq value (funcall function header))
492                      ;; Number (Lines:) or symbol must be converted to string.
493                      (or (stringp value)
494                          (setq value (prin1-to-string value)))
495                      (setq did-kill (string-match regexp value)))
496                    (if (stringp form)   ;Keyboard macro.
497                        (execute-kbd-macro form)
498                      (funcall form))))
499           ;; Search article body.
500           (let ((gnus-current-article nil) ;Save article pointer.
501                 (gnus-last-article nil)
502                 (gnus-break-pages nil)  ;No need to break pages.
503                 (gnus-mark-article-hook nil)) ;Inhibit marking as read.
504             (message "Searching for article: %d..." (header-number header))
505             (gnus-article-setup-buffer)
506             (gnus-article-prepare (header-number header) t)
507             (if (save-excursion
508                   (set-buffer gnus-article-buffer)
509                   (goto-char (point-min))
510                   (setq did-kill (re-search-forward regexp nil t)))
511                 (if (stringp form)      ;Keyboard macro.
512                     (execute-kbd-macro form)
513                   (eval form))))))
514       did-kill)))
515
516 (defun gnus-execute (field regexp form &optional backward ignore-marked)
517   "If FIELD of article header matches REGEXP, execute lisp FORM (or a string).
518 If FIELD is an empty string (or nil), entire article body is searched for.
519 If optional 1st argument BACKWARD is non-nil, do backward instead.
520 If optional 2nd argument IGNORE-MARKED is non-nil, articles which are
521 marked as read or ticked are ignored."
522   (save-excursion
523     (let ((killed-no 0)
524           function header article)
525       (if (or (null field) (string-equal field ""))
526           (setq function nil)
527         ;; Get access function of header filed.
528         (setq function (intern-soft (concat "gnus-header-" (downcase field))))
529         (if (and function (fboundp function))
530             (setq function (symbol-function function))
531           (error "Unknown header field: \"%s\"" field))
532         ;; Make FORM funcallable.
533         (if (and (listp form) (not (eq (car form) 'lambda)))
534             (setq form (list 'lambda nil form))))
535       ;; Starting from the current article.
536       (while (or (and (not article)
537                       (setq article (gnus-summary-article-number))
538                       t)
539                  (setq article 
540                        (gnus-summary-search-subject 
541                         backward (not ignore-marked))))
542         (and (or (null gnus-newsgroup-kill-headers)
543                  (memq article gnus-newsgroup-kill-headers))
544              (gnus-execute-1 function regexp form 
545                              (gnus-get-header-by-number article))
546              (setq killed-no (1+ killed-no))))
547       killed-no)))
548