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