(flyspell-post-command-hook): Do nothing unless flyspell-mode is enabled.
[bpt/emacs.git] / lisp / proced.el
1 ;;; proced.el --- operate on system processes like dired
2
3 ;; Copyright (C) 2008, 2009 Free Software Foundation, Inc.
4
5 ;; Author: Roland Winkler <Roland.Winkler@physik.uni-erlangen.de>
6 ;; Keywords: Processes, Unix
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 3 of the License, or
13 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; Proced makes an Emacs buffer containing a listing of the current
26 ;; system processes. You can use the normal Emacs commands to move around
27 ;; in this buffer, and special Proced commands to operate on the processes
28 ;; listed. See `proced-mode' for getting started.
29 ;;
30 ;; To do:
31 ;; - interactive temporary customizability of flags in `proced-grammar-alist'
32 ;; - allow "sudo kill PID", "renice PID"
33 ;;
34 ;; Thoughts and Ideas
35 ;; - Currently, `system-process-attributes' returns the list of
36 ;; command-line arguments of a process as one concatenated string.
37 ;; This format is compatible with `shell-command'. Also, under
38 ;; MS-Windows, the command-line arguments are actually stored as a
39 ;; single string, so that it is impossible to reverse-engineer it back
40 ;; into separate arguments. Alternatively, `system-process-attributes'
41 ;; could (try to) return a list of strings that correspond to individual
42 ;; command-line arguments. Then one could feed such a list of
43 ;; command-line arguments into `call-process' or `start-process'.
44 ;; Are there real-world applications when such a feature would be useful?
45 ;; What about something like `proced-restart-pid'?
46
47 ;;; Code:
48
49 (require 'time-date) ; for `with-decoded-time-value'
50
51 (defgroup proced nil
52 "Proced mode."
53 :group 'processes
54 :group 'unix
55 :prefix "proced-")
56
57 (defcustom proced-signal-function 'signal-process
58 "Name of signal function.
59 It can be an elisp function (usually `signal-process') or a string specifying
60 the external command (usually \"kill\")."
61 :group 'proced
62 :type '(choice (function :tag "function")
63 (string :tag "command")))
64
65 (defcustom proced-signal-list
66 '( ;; signals supported on all POSIX compliant systems
67 ("HUP (1. Hangup)")
68 ("INT (2. Terminal interrupt)")
69 ("QUIT (3. Terminal quit)")
70 ("ABRT (6. Process abort)")
71 ("KILL (9. Kill - cannot be caught or ignored)")
72 ("ALRM (14. Alarm Clock)")
73 ("TERM (15. Termination)")
74 ;; POSIX 1003.1-2001
75 ;; Which systems do not support these signals so that we can
76 ;; exclude them from `proced-signal-list'?
77 ("CONT (Continue executing)")
78 ("STOP (Stop executing / pause - cannot be caught or ignored)")
79 ("TSTP (Terminal stop / pause)"))
80 "List of signals, used for minibuffer completion."
81 :group 'proced
82 :type '(repeat (string :tag "signal")))
83
84 ;; For which attributes can we use a fixed width of the output field?
85 ;; A fixed width speeds up formatting, yet it can make
86 ;; `proced-grammar-alist' system-dependent.
87 ;; (If proced runs like top(1) we want it to be fast.)
88 ;;
89 ;; If it is impossible / unlikely that an attribute has the same value
90 ;; for two processes, then sorting can be based on one ordinary (fast)
91 ;; predicate like `<'. Otherwise, a list of proced predicates can be used
92 ;; to refine the sort.
93 ;;
94 ;; It would be neat if one could temporarily override the following
95 ;; predefined rules.
96 (defcustom proced-grammar-alist
97 '( ;; attributes defined in `system-process-attributes'
98 (euid "EUID" "%d" right proced-< nil (euid pid) (nil t nil))
99 (user "USER" nil left proced-string-lessp nil (user pid) (nil t nil))
100 (egid "EGID" "%d" right proced-< nil (egid euid pid) (nil t nil))
101 (group "GROUP" nil left proced-string-lessp nil (group user pid) (nil t nil))
102 (comm "COMMAND" nil left proced-string-lessp nil (comm pid) (nil t nil))
103 (state "STAT" nil left proced-string-lessp nil (state pid) (nil t nil))
104 (ppid "PPID" "%d" right proced-< nil (ppid pid)
105 ((lambda (ppid) (proced-filter-parents proced-process-alist ppid))
106 "refine to process parents"))
107 (pgrp "PGRP" "%d" right proced-< nil (pgrp euid pid) (nil t nil))
108 (sess "SESS" "%d" right proced-< nil (sess pid) (nil t nil))
109 (ttname "TTY" proced-format-ttname left proced-string-lessp nil (ttname pid) (nil t nil))
110 (tpgid "TPGID" "%d" right proced-< nil (tpgid pid) (nil t nil))
111 (minflt "MINFLT" "%d" right proced-< nil (minflt pid) (nil t t))
112 (majflt "MAJFLT" "%d" right proced-< nil (majflt pid) (nil t t))
113 (cminflt "CMINFLT" "%d" right proced-< nil (cminflt pid) (nil t t))
114 (cmajflt "CMAJFLT" "%d" right proced-< nil (cmajflt pid) (nil t t))
115 (utime "UTIME" proced-format-time right proced-time-lessp t (utime pid) (nil t t))
116 (stime "STIME" proced-format-time right proced-time-lessp t (stime pid) (nil t t))
117 (time "TIME" proced-format-time right proced-time-lessp t (time pid) (nil t t))
118 (cutime "CUTIME" proced-format-time right proced-time-lessp t (cutime pid) (nil t t))
119 (cstime "CSTIME" proced-format-time right proced-time-lessp t (cstime pid) (nil t t))
120 (ctime "CTIME" proced-format-time right proced-time-lessp t (ctime pid) (nil t t))
121 (pri "PR" "%d" right proced-< t (pri pid) (nil t t))
122 (nice "NI" "%3d" 3 proced-< t (nice pid) (t t nil))
123 (thcount "THCOUNT" "%d" right proced-< t (thcount pid) (nil t t))
124 (start "START" proced-format-start 6 proced-time-lessp nil (start pid) (t t nil))
125 (vsize "VSIZE" "%d" right proced-< t (vsize pid) (nil t t))
126 (rss "RSS" "%d" right proced-< t (rss pid) (nil t t))
127 (etime "ETIME" proced-format-time right proced-time-lessp t (etime pid) (nil t t))
128 (pcpu "%CPU" "%.1f" right proced-< t (pcpu pid) (nil t t))
129 (pmem "%MEM" "%.1f" right proced-< t (pmem pid) (nil t t))
130 (args "ARGS" proced-format-args left proced-string-lessp nil (args pid) (nil t nil))
131 ;;
132 ;; attributes defined by proced (see `proced-process-attributes')
133 (pid "PID" "%d" right proced-< nil (pid)
134 ((lambda (ppid) (proced-filter-children proced-process-alist ppid))
135 "refine to process children"))
136 ;; process tree
137 (tree "TREE" proced-format-tree left nil nil nil nil))
138 "Alist of rules for handling Proced attributes.
139
140 Each element has the form
141
142 (KEY NAME FORMAT JUSTIFY PREDICATE REVERSE SORT-SCHEME REFINER).
143
144 Symbol KEY is the car of a process attribute.
145
146 String NAME appears in the header line.
147
148 FORMAT specifies the format for displaying the attribute values. It can
149 be a string passed to `format'. It can be a function called with one
150 argument, the value of the attribute. The value nil means take as is.
151
152 If JUSTIFY is an integer, its modulus gives the width of the attribute
153 values formatted with FORMAT. If JUSTIFY is positive, NAME appears
154 right-justified, otherwise it appears left-justified. If JUSTIFY is 'left
155 or 'right, the field width is calculated from all field values in the listing.
156 If JUSTIFY is 'left, the field values are formatted left-justified and
157 right-justified otherwise.
158
159 PREDICATE is the predicate for sorting and filtering the process listing
160 based on attribute KEY. PREDICATE takes two arguments P1 and P2,
161 the corresponding attribute values of two processes. PREDICATE should
162 return 'equal if P1 has same rank like P2. Any other non-nil value says
163 that P1 is \"less than\" P2, or nil if not.
164 If PREDICATE is nil the attribute cannot be sorted.
165
166 PREDICATE defines an ascending sort order. REVERSE is non-nil if the sort
167 order is descending.
168
169 SORT-SCHEME is a list (KEY1 KEY2 ...) defining a hierarchy of rules
170 for sorting the process listing. KEY1, KEY2, ... are KEYs appearing as cars
171 of `proced-grammar-alist'. First the PREDICATE of KEY1 is evaluated.
172 If it yields non-equal, it defines the sort order for the corresponding
173 processes. If it evaluates to 'equal the PREDICATE of KEY2 is evaluated, etc.
174
175 REFINER can be a list of flags (LESS-B EQUAL-B LARGER-B) used by the command
176 `proced-refine' (see there) to refine the listing based on attribute KEY.
177 This command compares the value of attribute KEY of every process with
178 the value of attribute KEY of the process at the position of point
179 using PREDICATE.
180 If PREDICATE yields non-nil, the process is accepted if LESS-B is non-nil.
181 If PREDICATE yields 'equal, the process is accepted if EQUAL-B is non-nil.
182 If PREDICATE yields nil, the process is accepted if LARGER-B is non-nil.
183
184 REFINER can also be a list (FUNCTION HELP-ECHO).
185 FUNCTION is called with one argument, the PID of the process at the position
186 of point. The function must return a list of PIDs that is used for the refined
187 listing. HELP-ECHO is a string that is shown when mouse is over this field.
188
189 If REFINER is nil no refinement is done."
190 :group 'proced
191 :type '(repeat (list :tag "Attribute"
192 (symbol :tag "Key")
193 (string :tag "Header")
194 (choice :tag "Format"
195 (const :tag "None" nil)
196 (string :tag "Format String")
197 (function :tag "Formatting Function"))
198 (choice :tag "Justification"
199 (const :tag "left" left)
200 (const :tag "right" right)
201 (integer :tag "width"))
202 (choice :tag "Predicate"
203 (const :tag "None" nil)
204 (function :tag "Function"))
205 (boolean :tag "Descending Sort Order")
206 (repeat :tag "Sort Scheme" (symbol :tag "Key"))
207 (choice :tag "Refiner"
208 (const :tag "None" nil)
209 (list (function :tag "Refinement Function")
210 (string :tag "Help echo"))
211 (list :tag "Refine Flags"
212 (boolean :tag "Less")
213 (boolean :tag "Equal")
214 (boolean :tag "Larger"))))))
215
216 (defcustom proced-custom-attributes nil
217 "List of functions defining custom attributes.
218 This variable extends the functionality of `proced-process-attributes'.
219 Each function is called with one argument, the list of attributes
220 of a system process. It returns a cons cell of the form (KEY . VALUE)
221 like `system-process-attributes'. This cons cell is appended to the list
222 returned by `proced-process-attributes'.
223 If the function returns nil, the value is ignored."
224 :group 'proced
225 :type '(repeat (function :tag "Attribute")))
226
227 ;; Formatting and sorting rules are defined "per attribute". If formatting
228 ;; and / or sorting should use more than one attribute, it appears more
229 ;; transparent to define a new derived attribute, so that formatting and
230 ;; sorting can use them consistently. (Are there exceptions to this rule?
231 ;; Would it be advantageous to have yet more general methods available?)
232 ;; Sorting can also be based on attributes that are invisible in the listing.
233
234 (defcustom proced-format-alist
235 '((short user pid tree pcpu pmem start time (args comm))
236 (medium user pid tree pcpu pmem vsize rss ttname state start time (args comm))
237 (long user euid group pid tree pri nice pcpu pmem vsize rss ttname state
238 start time (args comm))
239 (verbose user euid group egid pid ppid tree pgrp sess pri nice pcpu pmem
240 state thcount vsize rss ttname tpgid minflt majflt cminflt cmajflt
241 start time utime stime ctime cutime cstime etime (args comm)))
242 "Alist of formats of listing.
243 The car of each element is a symbol, the name of the format.
244 The cdr is a list of attribute keys appearing in `proced-grammar-alist'.
245 An element of this list may also be a list of attribute keys that specifies
246 alternatives. If the first attribute is absent for a process, use the second
247 one, etc."
248 :group 'proced
249 :type '(alist :key-type (symbol :tag "Format Name")
250 :value-type (repeat :tag "Keys"
251 (choice (symbol :tag "")
252 (repeat :tag "Alternative Keys"
253 (symbol :tag ""))))))
254
255 (defcustom proced-format 'short
256 "Current format of Proced listing.
257 It can be the car of an element of `proced-format-alist'.
258 It can also be a list of keys appearing in `proced-grammar-alist'."
259 :group 'proced
260 :type '(choice (symbol :tag "Format Name")
261 (repeat :tag "Keys" (symbol :tag ""))))
262 (make-variable-buffer-local 'proced-format)
263
264 ;; FIXME: is there a better name for filter `user' that does not coincide
265 ;; with an attribute key?
266 (defcustom proced-filter-alist
267 `((user (user . ,(concat "\\`" (user-real-login-name) "\\'")))
268 (user-running (user . ,(concat "\\`" (user-real-login-name) "\\'"))
269 (state . "\\`[Rr]\\'"))
270 (all)
271 (all-running (state . "\\`[Rr]\\'"))
272 (emacs (fun-all . (lambda (list)
273 (proced-filter-children list ,(emacs-pid))))))
274 "Alist of process filters.
275 The car of each element is a symbol, the name of the filter.
276 The cdr is a list of elementary filters that are applied to every process.
277 A process is displayed if it passes all elementary filters of a selected
278 filter.
279
280 An elementary filter can be one of the following:
281 \(KEY . REGEXP) If value of attribute KEY matches REGEXP,
282 accept this process.
283 \(KEY . FUN) Apply function FUN to attribute KEY. Accept this process,
284 if FUN returns non-nil.
285 \(function . FUN) For each process, apply function FUN to list of attributes
286 of each. Accept the process if FUN returns non-nil.
287 \(fun-all . FUN) Apply function FUN to entire process list.
288 FUN must return the filtered list."
289 :group 'proced
290 :type '(repeat (cons :tag "Filter"
291 (symbol :tag "Filter Name")
292 (repeat :tag "Filters"
293 (choice (cons :tag "Key . Regexp" (symbol :tag "Key") regexp)
294 (cons :tag "Key . Function" (symbol :tag "Key") function)
295 (cons :tag "Function" (const :tag "Key: function" function) function)
296 (cons :tag "Fun-all" (const :tag "Key: fun-all" fun-all) function))))))
297
298 (defcustom proced-filter 'user
299 "Current filter of proced listing.
300 It can be the car of an element of `proced-filter-alist'.
301 It can also be a list of elementary filters as in the cdrs of the elements
302 of `proced-filter-alist'."
303 :group 'proced
304 :type '(choice (symbol :tag "Filter Name")
305 (repeat :tag "Filters"
306 (choice (cons :tag "Key . Regexp" (symbol :tag "Key") regexp)
307 (cons :tag "Key . Function" (symbol :tag "Key") function)
308 (cons :tag "Function" (const :tag "Key: function" function) function)
309 (cons :tag "Fun-all" (const :tag "Key: fun-all" fun-all) function)))))
310 (make-variable-buffer-local 'proced-filter)
311
312 (defcustom proced-sort 'pcpu
313 "Current sort scheme for proced listing.
314 It must be the KEY of an element of `proced-grammar-alist'.
315 It can also be a list of KEYs as in the SORT-SCHEMEs of the elements
316 of `proced-grammar-alist'."
317 :group 'proced
318 :type '(choice (symbol :tag "Sort Scheme")
319 (repeat :tag "Key List" (symbol :tag "Key"))))
320 (make-variable-buffer-local 'proced-format)
321
322 (defcustom proced-descend t
323 "Non-nil if proced listing is sorted in descending order."
324 :group 'proced
325 :type '(boolean :tag "Descending Sort Order"))
326 (make-variable-buffer-local 'proced-descend)
327
328 (defcustom proced-goal-attribute 'args
329 "If non-nil, key of the attribute that defines the `goal-column'."
330 :group 'proced
331 :type '(choice (const :tag "none" nil)
332 (symbol :tag "key")))
333
334 (defcustom proced-auto-update-interval 5
335 "Time interval in seconds for auto updating Proced buffers."
336 :group 'proced
337 :type 'integer)
338
339 (defcustom proced-auto-update-flag nil
340 "Non-nil for auto update of a Proced buffer.
341 Can be changed interactively via `proced-toggle-auto-update'."
342 :group 'proced
343 :type 'boolean)
344 (make-variable-buffer-local 'proced-auto-update-flag)
345
346 (defcustom proced-tree-flag nil
347 "Non-nil for display of Proced buffer as process tree."
348 :group 'proced
349 :type 'boolean)
350 (make-variable-buffer-local 'proced-tree-flag)
351
352 (defcustom proced-post-display-hook nil
353 "Normal hook run after displaying or updating a Proced buffer.
354 May be used to adapt the window size via `fit-window-to-buffer'."
355 :type 'hook
356 :options '(fit-window-to-buffer)
357 :group 'proced)
358
359 ;; Internal variables
360
361 (defvar proced-available (not (null (list-system-processes)))
362 "Non-nil means Proced is known to work on this system.")
363
364 (defvar proced-process-alist nil
365 "Alist of processes displayed by Proced.
366 The car of each element is the PID, and the cdr is a list of
367 cons pairs, see `proced-process-attributes'.")
368 (make-variable-buffer-local 'proced-process-alist)
369
370 (defvar proced-sort-internal nil
371 "Sort scheme for listing (internal format).
372 It is a list of lists (KEY PREDICATE REVERSE).")
373
374 (defvar proced-marker-char ?* ; the answer is 42
375 "In Proced, the current mark character.")
376
377 ;; Faces and font-lock code taken from dired,
378 ;; but face variables are deprecated for new code.
379 (defgroup proced-faces nil
380 "Faces used by Proced."
381 :group 'proced
382 :group 'faces)
383
384 (defface proced-mark
385 '((t (:inherit font-lock-constant-face)))
386 "Face used for Proced marks."
387 :group 'proced-faces)
388
389 (defface proced-marked
390 '((t (:inherit font-lock-warning-face)))
391 "Face used for marked processes."
392 :group 'proced-faces)
393
394 (defface proced-sort-header
395 '((t (:inherit font-lock-keyword-face)))
396 "Face used for header of attribute used for sorting."
397 :group 'proced-faces)
398
399 (defvar proced-re-mark "^[^ \n]"
400 "Regexp matching a marked line.
401 Important: the match ends just after the marker.")
402
403 (defvar proced-header-line nil
404 "Headers in Proced buffer as a string.")
405 (make-variable-buffer-local 'proced-header-line)
406
407 (defvar proced-temp-alist nil
408 "Temporary alist (internal variable).")
409
410 (defvar proced-process-tree nil
411 "Proced process tree (internal variable).")
412
413 (defvar proced-tree-depth nil
414 "Internal variable for depth of Proced process tree.")
415
416 (defvar proced-auto-update-timer nil
417 "Stores if Proced auto update timer is already installed.")
418
419 (defvar proced-log-buffer "*Proced log*"
420 "Name of Proced Log buffer.")
421
422 (defconst proced-help-string
423 "(n)ext, (p)revious, (m)ark, (u)nmark, (k)ill, (q)uit (type ? for more help)"
424 "Help string for Proced.")
425
426 (defconst proced-header-help-echo
427 "mouse-1, mouse-2: sort by attribute %s%s (%s)"
428 "Help string shown when mouse is over a sortable header.")
429
430 (defconst proced-field-help-echo
431 "mouse-2, RET: refine by attribute %s %s"
432 "Help string shown when mouse is over a refinable field.")
433
434 (defvar proced-font-lock-keywords
435 `(;; (Any) proced marks.
436 (,proced-re-mark . 'proced-mark)
437 ;; Processes marked with `proced-marker-char'
438 ;; Should we make sure that only certain attributes are font-locked?
439 (,(concat "^[" (char-to-string proced-marker-char) "]")
440 ".+" (proced-move-to-goal-column) nil (0 'proced-marked))))
441
442 (defvar proced-mode-map
443 (let ((km (make-sparse-keymap)))
444 ;; moving
445 (define-key km " " 'next-line)
446 (define-key km "n" 'next-line)
447 (define-key km "p" 'previous-line)
448 (define-key km "\C-n" 'next-line)
449 (define-key km "\C-p" 'previous-line)
450 (define-key km "\C-?" 'previous-line)
451 (define-key km [down] 'next-line)
452 (define-key km [up] 'previous-line)
453 ;; marking
454 (define-key km "d" 'proced-mark) ; Dired compatibility ("delete")
455 (define-key km "m" 'proced-mark)
456 (define-key km "u" 'proced-unmark)
457 (define-key km "\177" 'proced-unmark-backward)
458 (define-key km "M" 'proced-mark-all)
459 (define-key km "U" 'proced-unmark-all)
460 (define-key km "t" 'proced-toggle-marks)
461 (define-key km "C" 'proced-mark-children)
462 (define-key km "P" 'proced-mark-parents)
463 ;; filtering
464 (define-key km "f" 'proced-filter-interactive)
465 (define-key km [mouse-2] 'proced-refine)
466 (define-key km "\C-m" 'proced-refine)
467 ;; sorting
468 (define-key km "sc" 'proced-sort-pcpu)
469 (define-key km "sm" 'proced-sort-pmem)
470 (define-key km "sp" 'proced-sort-pid)
471 (define-key km "ss" 'proced-sort-start)
472 (define-key km "sS" 'proced-sort-interactive)
473 (define-key km "st" 'proced-sort-time)
474 (define-key km "su" 'proced-sort-user)
475 ;; similar to `Buffer-menu-sort-by-column'
476 (define-key km [header-line mouse-1] 'proced-sort-header)
477 (define-key km [header-line mouse-2] 'proced-sort-header)
478 (define-key km "T" 'proced-toggle-tree)
479 ;; formatting
480 (define-key km "F" 'proced-format-interactive)
481 ;; operate
482 (define-key km "o" 'proced-omit-processes)
483 (define-key km "x" 'proced-send-signal) ; Dired compatibility
484 (define-key km "k" 'proced-send-signal) ; kill processes
485 ;; misc
486 (define-key km "h" 'describe-mode)
487 (define-key km "?" 'proced-help)
488 (define-key km [remap undo] 'proced-undo)
489 (define-key km [remap advertised-undo] 'proced-undo)
490 ;; Additional keybindings are inherited from `special-mode-map'
491 km)
492 "Keymap for Proced commands.")
493
494 (easy-menu-define
495 proced-menu proced-mode-map "Proced Menu"
496 `("Proced"
497 ["Mark" proced-mark
498 :help "Mark Current Process"]
499 ["Unmark" proced-unmark
500 :help "Unmark Current Process"]
501 ["Mark All" proced-mark-all
502 :help "Mark All Processes"]
503 ["Unmark All" proced-unmark-all
504 :help "Unmark All Process"]
505 ["Toggle Marks" proced-toggle-marks
506 :help "Marked Processes Become Unmarked, and Vice Versa"]
507 ["Mark Children" proced-mark-children
508 :help "Mark Current Process and its Children"]
509 ["Mark Parents" proced-mark-parents
510 :help "Mark Current Process and its Parents"]
511 "--"
512 ("Filters"
513 :help "Select Filter for Process Listing"
514 ,@(mapcar (lambda (el)
515 (let ((filter (car el)))
516 `[,(symbol-name filter)
517 (proced-filter-interactive ',filter)
518 :style radio
519 :selected (eq proced-filter ',filter)]))
520 proced-filter-alist))
521 ("Sorting"
522 :help "Select Sort Scheme"
523 ["Sort..." proced-sort-interactive
524 :help "Sort Process List"]
525 "--"
526 ["Sort by %CPU" proced-sort-pcpu]
527 ["Sort by %MEM" proced-sort-pmem]
528 ["Sort by PID" proced-sort-pid]
529 ["Sort by START" proced-sort-start]
530 ["Sort by TIME" proced-sort-time]
531 ["Sort by USER" proced-sort-user])
532 ("Formats"
533 :help "Select Format for Process Listing"
534 ,@(mapcar (lambda (el)
535 (let ((format (car el)))
536 `[,(symbol-name format)
537 (proced-format-interactive ',format)
538 :style radio
539 :selected (eq proced-format ',format)]))
540 proced-format-alist))
541 ["Tree Display" proced-toggle-tree
542 :style toggle
543 :selected (eval proced-tree-flag)
544 :help "Display Proced Buffer as Process Tree"]
545 "--"
546 ["Omit Marked Processes" proced-omit-processes
547 :help "Omit Marked Processes in Process Listing."]
548 "--"
549 ["Revert" revert-buffer
550 :help "Revert Process Listing"]
551 ["Auto Update" proced-toggle-auto-update
552 :style toggle
553 :selected (eval proced-auto-update-flag)
554 :help "Auto Update of Proced Buffer"]
555 ["Send signal" proced-send-signal
556 :help "Send Signal to Marked Processes"]))
557
558 ;; helper functions
559 (defun proced-marker-regexp ()
560 "Return regexp matching `proced-marker-char'."
561 ;; `proced-marker-char' must appear in column zero
562 (concat "^" (regexp-quote (char-to-string proced-marker-char))))
563
564 (defun proced-success-message (action count)
565 "Display success message for ACTION performed for COUNT processes."
566 (message "%s %s process%s" action count (if (= 1 count) "" "es")))
567
568 ;; Unlike dired, we do not define our own commands for vertical motion.
569 ;; If `goal-column' is set, `next-line' and `previous-line' are fancy
570 ;; commands to satisfy our modest needs. If `proced-goal-attribute'
571 ;; and/or `goal-column' are not set, `next-line' and `previous-line'
572 ;; are really what we need to preserve the column of point.
573 ;; We use `proced-move-to-goal-column' for "non-interactive" cases only
574 ;; to get a well-defined position of point.
575
576 (defun proced-move-to-goal-column ()
577 "Move to `goal-column' if non-nil. Return position of point."
578 (beginning-of-line)
579 (unless (eobp)
580 (if goal-column
581 (forward-char goal-column)
582 (forward-char 2)))
583 (point))
584
585 (defun proced-header-line ()
586 "Return header line for Proced buffer."
587 (list (propertize " " 'display '(space :align-to 0))
588 (replace-regexp-in-string ;; preserve text properties
589 "\\(%\\)" "\\1\\1" (substring proced-header-line (window-hscroll)))))
590
591 (defun proced-pid-at-point ()
592 "Return pid of system process at point.
593 Return nil if point is not on a process line."
594 (save-excursion
595 (beginning-of-line)
596 (if (looking-at "^. .")
597 (get-text-property (match-end 0) 'proced-pid))))
598
599 ;; proced mode
600
601 (define-derived-mode proced-mode special-mode "Proced"
602 "Mode for displaying UNIX system processes and sending signals to them.
603 Type \\[proced] to start a Proced session. In a Proced buffer
604 type \\<proced-mode-map>\\[proced-mark] to mark a process for later commands.
605 Type \\[proced-send-signal] to send signals to marked processes.
606
607 The initial content of a listing is defined by the variable `proced-filter'
608 and the variable `proced-format'.
609 The variable `proced-filter' specifies which system processes are displayed.
610 The variable `proced-format' specifies which attributes are displayed for
611 each process. Type \\[proced-filter-interactive] and \\[proced-format-interactive]
612 to change the values of `proced-filter' and `proced-format'.
613 The current value of the variable `proced-filter' is indicated in the
614 mode line.
615
616 The sort order of Proced listings is defined by the variable `proced-sort'.
617 Type \\[proced-sort-interactive] or click on a header in the header line
618 to change the sort scheme. The current sort scheme is indicated in the
619 mode line, using \"+\" or \"-\" for ascending or descending sort order.
620
621 Type \\[proced-toggle-tree] to toggle whether the listing is
622 displayed as process tree.
623
624 An existing Proced listing can be refined by typing \\[proced-refine].
625 Refining an existing listing does not update the variable `proced-filter'.
626
627 The attribute-specific rules for formatting, filtering, sorting, and refining
628 are defined in `proced-grammar-alist'.
629
630 After displaying or updating a Proced buffer, Proced runs the normal hook
631 `proced-post-display-hook'.
632
633 \\{proced-mode-map}"
634 (abbrev-mode 0)
635 (auto-fill-mode 0)
636 (setq buffer-read-only t
637 truncate-lines t
638 header-line-format '(:eval (proced-header-line)))
639 (add-hook 'post-command-hook 'force-mode-line-update nil t)
640 (set (make-local-variable 'revert-buffer-function) 'proced-revert)
641 (set (make-local-variable 'font-lock-defaults)
642 '(proced-font-lock-keywords t nil nil beginning-of-line))
643 (if (and (not proced-auto-update-timer) proced-auto-update-interval)
644 (setq proced-auto-update-timer
645 (run-at-time t proced-auto-update-interval
646 'proced-auto-update-timer))))
647
648 ;;;###autoload
649 (defun proced (&optional arg)
650 "Generate a listing of UNIX system processes.
651 If invoked with optional ARG the window displaying the process
652 information will be displayed but not selected.
653 Runs the normal hook `proced-post-display-hook'.
654
655 See `proced-mode' for a description of features available in Proced buffers."
656 (interactive "P")
657 (unless proced-available
658 (error "Proced is not available on this system"))
659 (let ((buffer (get-buffer-create "*Proced*")) new)
660 (set-buffer buffer)
661 (setq new (zerop (buffer-size)))
662 (when new
663 (proced-mode)
664 ;; `proced-update' runs `proced-post-display-hook' only if the
665 ;; Proced buffer has been selected. Yet the following call of
666 ;; `proced-update' is for an empty Proced buffer that has not
667 ;; yet been selected. Therefore we need to call
668 ;; `proced-post-display-hook' below.
669 (proced-update t))
670 (if arg
671 (progn
672 (display-buffer buffer)
673 (with-current-buffer buffer
674 (run-hooks 'proced-post-display-hook)))
675 (pop-to-buffer buffer)
676 (run-hooks 'proced-post-display-hook)
677 (message
678 (substitute-command-keys
679 "Type \\<proced-mode-map>\\[quit-window] to quit, \\[proced-help] for help")))))
680
681 (defun proced-auto-update-timer ()
682 "Auto-update Proced buffers using `run-at-time'."
683 (dolist (buf (buffer-list))
684 (with-current-buffer buf
685 (if (and (eq major-mode 'proced-mode)
686 proced-auto-update-flag)
687 (proced-update t t)))))
688
689 (defun proced-toggle-auto-update (arg)
690 "Change whether this Proced buffer is updated automatically.
691 With prefix ARG, update this buffer automatically if ARG is positive,
692 otherwise do not update. Sets the variable `proced-auto-update-flag'.
693 The time interval for updates is specified via `proced-auto-update-interval'."
694 (interactive (list (or current-prefix-arg 'toggle)))
695 (setq proced-auto-update-flag
696 (cond ((eq arg 'toggle) (not proced-auto-update-flag))
697 (arg (> (prefix-numeric-value arg) 0))
698 (t (not proced-auto-update-flag))))
699 (message "Proced auto update %s"
700 (if proced-auto-update-flag "enabled" "disabled")))
701
702 ;;; Mark
703
704 (defun proced-mark (&optional count)
705 "Mark the current (or next COUNT) processes."
706 (interactive "p")
707 (proced-do-mark t count))
708
709 (defun proced-unmark (&optional count)
710 "Unmark the current (or next COUNT) processes."
711 (interactive "p")
712 (proced-do-mark nil count))
713
714 (defun proced-unmark-backward (&optional count)
715 "Unmark the previous (or COUNT previous) processes."
716 ;; Analogous to `dired-unmark-backward',
717 ;; but `ibuffer-unmark-backward' behaves different.
718 (interactive "p")
719 (proced-do-mark nil (- (or count 1))))
720
721 (defun proced-do-mark (mark &optional count)
722 "Mark the current (or next COUNT) processes using MARK."
723 (or count (setq count 1))
724 (let ((backward (< count 0))
725 buffer-read-only)
726 (setq count (1+ (if (<= 0 count) count
727 (min (1- (line-number-at-pos)) (abs count)))))
728 (beginning-of-line)
729 (while (not (or (zerop (setq count (1- count))) (eobp)))
730 (proced-insert-mark mark backward))
731 (proced-move-to-goal-column)))
732
733 (defun proced-toggle-marks ()
734 "Toggle marks: marked processes become unmarked, and vice versa."
735 (interactive)
736 (let ((mark-re (proced-marker-regexp))
737 buffer-read-only)
738 (save-excursion
739 (goto-char (point-min))
740 (while (not (eobp))
741 (cond ((looking-at mark-re)
742 (proced-insert-mark nil))
743 ((looking-at " ")
744 (proced-insert-mark t))
745 (t
746 (forward-line 1)))))))
747
748 (defun proced-insert-mark (mark &optional backward)
749 "If MARK is non-nil, insert `proced-marker-char'.
750 If BACKWARD is non-nil, move one line backwards before inserting the mark.
751 Otherwise move one line forward after inserting the mark."
752 (if backward (forward-line -1))
753 (insert (if mark proced-marker-char ?\s))
754 (delete-char 1)
755 (unless backward (forward-line)))
756
757 (defun proced-mark-all ()
758 "Mark all processes.
759 If `transient-mark-mode' is turned on and the region is active,
760 mark the region."
761 (interactive)
762 (proced-do-mark-all t))
763
764 (defun proced-unmark-all ()
765 "Unmark all processes.
766 If `transient-mark-mode' is turned on and the region is active,
767 unmark the region."
768 (interactive)
769 (proced-do-mark-all nil))
770
771 (defun proced-do-mark-all (mark)
772 "Mark all processes using MARK.
773 If `transient-mark-mode' is turned on and the region is active,
774 mark the region."
775 (let* ((count 0)
776 (proced-marker-char (if mark proced-marker-char ?\s))
777 (marker-re (proced-marker-regexp))
778 end buffer-read-only)
779 (save-excursion
780 (if (use-region-p)
781 ;; Operate even on those lines that are only partially a part
782 ;; of region. This appears most consistent with
783 ;; `proced-move-to-goal-column'.
784 (progn (setq end (save-excursion
785 (goto-char (region-end))
786 (unless (looking-at "^") (forward-line))
787 (point)))
788 (goto-char (region-beginning))
789 (unless (looking-at "^") (beginning-of-line)))
790 (goto-char (point-min))
791 (setq end (point-max)))
792 (while (< (point) end)
793 (unless (looking-at marker-re)
794 (setq count (1+ count))
795 (insert proced-marker-char)
796 (delete-char 1))
797 (forward-line))
798 (proced-success-message (if mark "Marked" "Unmarked") count))))
799
800 (defun proced-mark-children (ppid &optional omit-ppid)
801 "Mark child processes of process PPID.
802 Also mark process PPID unless prefix OMIT-PPID is non-nil."
803 (interactive (list (proced-pid-at-point) current-prefix-arg))
804 (proced-mark-process-alist
805 (proced-filter-children proced-process-alist ppid omit-ppid)))
806
807 (defun proced-mark-parents (cpid &optional omit-cpid)
808 "Mark parent processes of process CPID.
809 Also mark CPID unless prefix OMIT-CPID is non-nil."
810 (interactive (list (proced-pid-at-point) current-prefix-arg))
811 (proced-mark-process-alist
812 (proced-filter-parents proced-process-alist cpid omit-cpid)))
813
814 (defun proced-mark-process-alist (process-alist &optional quiet)
815 "Mark processes in PROCESS-ALIST.
816 If QUIET is non-nil suppress status message."
817 (let ((count 0))
818 (if process-alist
819 (let (buffer-read-only)
820 (save-excursion
821 (goto-char (point-min))
822 (while (not (eobp))
823 (when (assq (proced-pid-at-point) process-alist)
824 (insert proced-marker-char)
825 (delete-char 1)
826 (setq count (1+ count)))
827 (forward-line)))))
828 (unless quiet
829 (proced-success-message "Marked" count))))
830
831 ;; Mostly analog of `dired-do-kill-lines'.
832 ;; However, for negative args the target lines of `dired-do-kill-lines'
833 ;; include the current line, whereas `dired-mark' for negative args operates
834 ;; on the preceding lines. Here we are consistent with `dired-mark'.
835 (defun proced-omit-processes (&optional arg quiet)
836 "Omit marked processes.
837 With prefix ARG, omit that many lines starting with the current line.
838 \(A negative argument omits backward.)
839 If `transient-mark-mode' is turned on and the region is active,
840 omit the processes in region.
841 If QUIET is non-nil suppress status message.
842 Returns count of omitted lines."
843 (interactive "P")
844 (let ((mark-re (proced-marker-regexp))
845 (count 0)
846 buffer-read-only)
847 (cond ((use-region-p) ;; Omit active region
848 (let ((lines (count-lines (region-beginning) (region-end))))
849 (save-excursion
850 (goto-char (region-beginning))
851 (while (< count lines)
852 (proced-omit-process)
853 (setq count (1+ count))))))
854 ((not arg) ;; Omit marked lines
855 (save-excursion
856 (goto-char (point-min))
857 (while (and (not (eobp))
858 (re-search-forward mark-re nil t))
859 (proced-omit-process)
860 (setq count (1+ count)))))
861 ((< 0 arg) ;; Omit forward
862 (while (and (not (eobp)) (< count arg))
863 (proced-omit-process)
864 (setq count (1+ count))))
865 ((< arg 0) ;; Omit backward
866 (while (and (not (bobp)) (< count (- arg)))
867 (forward-line -1)
868 (proced-omit-process)
869 (setq count (1+ count)))))
870 (unless (zerop count) (proced-move-to-goal-column))
871 (unless quiet (proced-success-message "Omitted" count))
872 count))
873
874 (defun proced-omit-process ()
875 "Omit process from listing point is on.
876 Update `proced-process-alist' accordingly."
877 (setq proced-process-alist
878 (assq-delete-all (proced-pid-at-point) proced-process-alist))
879 (delete-region (line-beginning-position)
880 (save-excursion (forward-line) (point))))
881
882 ;;; Filtering
883
884 (defun proced-filter (process-alist filter-list)
885 "Apply FILTER-LIST to PROCESS-ALIST.
886 Return the filtered process list."
887 (if (symbolp filter-list)
888 (setq filter-list (cdr (assq filter-list proced-filter-alist))))
889 (dolist (filter filter-list)
890 (let (new-alist)
891 (cond ( ;; apply function to entire process list
892 (eq (car filter) 'fun-all)
893 (setq new-alist (funcall (cdr filter) process-alist)))
894 ( ;; apply predicate to each list of attributes
895 (eq (car filter) 'function)
896 (dolist (process process-alist)
897 (if (funcall (car filter) (cdr process))
898 (push process new-alist))))
899 (t ;; apply predicate to specified attribute
900 (let ((fun (if (stringp (cdr filter))
901 `(lambda (val)
902 (string-match ,(cdr filter) val))
903 (cdr filter)))
904 value)
905 (dolist (process process-alist)
906 (setq value (cdr (assq (car filter) (cdr process))))
907 (if (and value (funcall fun value))
908 (push process new-alist))))))
909 (setq process-alist new-alist)))
910 process-alist)
911
912 (defun proced-filter-interactive (scheme)
913 "Filter Proced buffer using SCHEME.
914 When called interactively, an empty string means nil, i.e., no filtering.
915 Set variable `proced-filter' to SCHEME. Revert listing."
916 (interactive
917 (let ((scheme (completing-read "Filter: "
918 proced-filter-alist nil t)))
919 (list (if (string= "" scheme) nil (intern scheme)))))
920 ;; only update if necessary
921 (unless (eq proced-filter scheme)
922 (setq proced-filter scheme)
923 (proced-update t)))
924
925 (defun proced-filter-parents (process-alist pid &optional omit-pid)
926 "For PROCESS-ALIST return list of parent processes of PID.
927 This list includes PID unless OMIT-PID is non-nil."
928 (let ((parent-list (unless omit-pid (list (assq pid process-alist))))
929 (process (assq pid process-alist))
930 ppid)
931 (while (and (setq ppid (cdr (assq 'ppid (cdr process))))
932 ;; Ignore a PPID that equals PID.
933 (/= ppid pid)
934 ;; Accept only PPIDs that correspond to members in PROCESS-ALIST.
935 (setq process (assq ppid process-alist)))
936 (setq pid ppid)
937 (push process parent-list))
938 parent-list))
939
940 (defun proced-filter-children (process-alist ppid &optional omit-ppid)
941 "For PROCESS-ALIST return list of child processes of PPID.
942 This list includes PPID unless OMIT-PPID is non-nil."
943 (let ((proced-temp-alist (proced-children-alist process-alist))
944 new-alist)
945 (dolist (pid (proced-children-pids ppid))
946 (push (assq pid process-alist) new-alist))
947 (if omit-ppid
948 (assq-delete-all ppid new-alist)
949 new-alist)))
950
951 ;;; Process tree
952
953 (defun proced-children-alist (process-alist)
954 "Return children alist for PROCESS-ALIST.
955 The children alist has elements (PPID PID1 PID2 ...).
956 PPID is a parent PID. PID1, PID2, ... are the child processes of PPID.
957 The children alist inherits the sorting order of PROCESS-ALIST.
958 The list of children does not include grandchildren."
959 ;; The PPIDs inherit the sorting order of PROCESS-ALIST.
960 (let ((process-tree (mapcar (lambda (a) (list (car a))) process-alist))
961 ppid)
962 (dolist (process process-alist)
963 (setq ppid (cdr (assq 'ppid (cdr process))))
964 (if (and ppid
965 ;; Ignore a PPID that equals PID.
966 (/= ppid (car process))
967 ;; Accept only PPIDs that correspond to members in PROCESS-ALIST.
968 (assq ppid process-alist))
969 (let ((temp-alist process-tree) elt)
970 (while (setq elt (pop temp-alist))
971 (when (eq ppid (car elt))
972 (setq temp-alist nil)
973 (setcdr elt (cons (car process) (cdr elt))))))))
974 ;; The child processes inherit the sorting order of PROCESS-ALIST.
975 (setq process-tree
976 (mapcar (lambda (a) (cons (car a) (nreverse (cdr a))))
977 process-tree))))
978
979 (defun proced-children-pids (ppid)
980 "Return list of children PIDs of PPID (including PPID)."
981 (let ((cpids (cdr (assq ppid proced-temp-alist))))
982 (if cpids
983 (cons ppid (apply 'append (mapcar 'proced-children-pids cpids)))
984 (list ppid))))
985
986 (defun proced-process-tree (process-alist)
987 "Return process tree for PROCESS-ALIST.
988 It is an alist of alists where the car of each alist is a parent process
989 and the cdr is a list of child processes according to the ppid attribute
990 of these processes.
991 The process tree inherits the sorting order of PROCESS-ALIST."
992 (let ((proced-temp-alist (proced-children-alist process-alist))
993 pid-alist proced-process-tree)
994 (while (setq pid-alist (pop proced-temp-alist))
995 (push (proced-process-tree-internal pid-alist) proced-process-tree))
996 (nreverse proced-process-tree)))
997
998 (defun proced-process-tree-internal (pid-alist)
999 "Helper function for `proced-process-tree'."
1000 (let ((cpid-list (cdr pid-alist)) cpid-alist cpid)
1001 (while (setq cpid (car cpid-list))
1002 (if (setq cpid-alist (assq cpid proced-temp-alist))
1003 ;; Unprocessed part of process tree that needs to be
1004 ;; analyzed recursively.
1005 (progn
1006 (setq proced-temp-alist
1007 (assq-delete-all cpid proced-temp-alist))
1008 (setcar cpid-list (proced-process-tree-internal cpid-alist)))
1009 ;; We already processed this subtree and take it "as is".
1010 (setcar cpid-list (assq cpid proced-process-tree))
1011 (setq proced-process-tree
1012 (assq-delete-all cpid proced-process-tree)))
1013 (pop cpid-list)))
1014 pid-alist)
1015
1016 (defun proced-toggle-tree (arg)
1017 "Toggle the display of the process listing as process tree.
1018 With prefix ARG, display as process tree if ARG is positive, otherwise
1019 do not display as process tree. Sets the variable `proced-tree-flag'.
1020
1021 The process tree is generated from the selected processes in the
1022 Proced buffer (that is, the processes in `proced-process-alist').
1023 All processes that do not have a parent process in this list
1024 according to their ppid attribute become the root of a process tree.
1025 Each parent process is followed by its child processes.
1026 The process tree inherits the chosen sorting order of the process listing,
1027 that is, child processes of the same parent process are sorted using
1028 the selected sorting order."
1029 (interactive (list (or current-prefix-arg 'toggle)))
1030 (setq proced-tree-flag
1031 (cond ((eq arg 'toggle) (not proced-tree-flag))
1032 (arg (> (prefix-numeric-value arg) 0))
1033 (t (not proced-tree-flag))))
1034 (proced-update)
1035 (message "Proced process tree display %s"
1036 (if proced-tree-flag "enabled" "disabled")))
1037
1038 (defun proced-tree (process-alist)
1039 "Rearrange PROCESS-ALIST as process tree.
1040 If `proced-tree-flag' is non-nil, rearrange PROCESS-ALIST such that
1041 every processes is followed by its child processes. Each process
1042 gets a tree attribute that specifies the depth of the process in the tree.
1043 A root process is a process with no parent within PROCESS-ALIST according
1044 to its value of the ppid attribute. It has depth 0.
1045
1046 If `proced-tree-flag' is nil, remove the tree attribute.
1047 Return the rearranged process list."
1048 (if proced-tree-flag
1049 ;; add tree attribute
1050 (let ((process-tree (proced-process-tree process-alist))
1051 (proced-tree-depth 0)
1052 (proced-temp-alist process-alist)
1053 proced-process-tree pt)
1054 (while (setq pt (pop process-tree))
1055 (proced-tree-insert pt))
1056 (nreverse proced-process-tree))
1057 ;; remove tree attribute
1058 (let ((process-alist process-alist))
1059 (while process-alist
1060 (setcar process-alist
1061 (assq-delete-all 'tree (car process-alist)))
1062 (pop process-alist)))
1063 process-alist))
1064
1065 (defun proced-tree-insert (process-tree)
1066 "Helper function for `proced-tree'."
1067 (let ((pprocess (assq (car process-tree) proced-temp-alist)))
1068 (push (append (list (car pprocess))
1069 (list (cons 'tree proced-tree-depth))
1070 (cdr pprocess))
1071 proced-process-tree)
1072 (if (cdr process-tree)
1073 (let ((proced-tree-depth (1+ proced-tree-depth)))
1074 (mapc 'proced-tree-insert (cdr process-tree))))))
1075
1076 ;; Refining
1077
1078 ;; Filters are used to select the processes in a new listing.
1079 ;; Refiners are used to narrow down further (interactively) the processes
1080 ;; in an existing listing.
1081
1082 (defun proced-refine (&optional event)
1083 "Refine Proced listing by comparing with the attribute value at point.
1084 Optional EVENT is the location of the Proced field.
1085
1086 Refinement is controlled by the REFINER defined for each attribute ATTR
1087 in `proced-grammar-alist'.
1088
1089 If REFINER is a list of flags and point is on a process's value of ATTR,
1090 this command compares the value of ATTR of every process with the value
1091 of ATTR of the process at the position of point.
1092
1093 The predicate for the comparison of two ATTR values is defined
1094 in `proced-grammar-alist'. For each return value of the predicate
1095 a refine flag is defined in `proced-grammar-alist'. One can select
1096 processes for which the value of ATTR is \"less than\", \"equal\",
1097 and / or \"larger\" than ATTR of the process point is on. A process
1098 is included in the new listing if the refine flag for the corresponding
1099 return value of the predicate is non-nil.
1100 The help-echo string for `proced-refine' uses \"+\" or \"-\" to indicate
1101 the current values of these refine flags.
1102
1103 If REFINER is a cons pair (FUNCTION . HELP-ECHO), FUNCTION is called
1104 with one argument, the PID of the process at the position of point.
1105 The function must return a list of PIDs that is used for the refined
1106 listing. HELP-ECHO is a string that is shown when mouse is over this field.
1107
1108 This command refines an already existing process listing generated initially
1109 based on the value of the variable `proced-filter'. It does not change
1110 this variable. It does not revert the listing. If you frequently need
1111 a certain refinement, consider defining a new filter in `proced-filter-alist'."
1112 (interactive (list last-input-event))
1113 (if event (posn-set-point (event-end event)))
1114 (let ((key (get-text-property (point) 'proced-key))
1115 (pid (get-text-property (point) 'proced-pid)))
1116 (if (and key pid)
1117 (let* ((grammar (assq key proced-grammar-alist))
1118 (refiner (nth 7 grammar)))
1119 (when refiner
1120 (cond ((functionp (car refiner))
1121 (setq proced-process-alist (funcall (car refiner) pid)))
1122 ((consp refiner)
1123 (let ((predicate (nth 4 grammar))
1124 (ref (cdr (assq key (cdr (assq pid proced-process-alist)))))
1125 val new-alist)
1126 (dolist (process proced-process-alist)
1127 (setq val (funcall predicate (cdr (assq key (cdr process))) ref))
1128 (if (cond ((not val) (nth 2 refiner))
1129 ((eq val 'equal) (nth 1 refiner))
1130 (val (car refiner)))
1131 (push process new-alist)))
1132 (setq proced-process-alist new-alist))))
1133 ;; Do not revert listing.
1134 (proced-update)))
1135 (message "No refiner defined here."))))
1136
1137 ;; Proced predicates for sorting and filtering are based on a three-valued
1138 ;; logic:
1139 ;; Predicates take two arguments P1 and P2, the corresponding attribute
1140 ;; values of two processes. Predicates should return 'equal if P1 has
1141 ;; same rank like P2. Any other non-nil value says that P1 is "less than" P2,
1142 ;; or nil if not.
1143
1144 (defun proced-< (num1 num2)
1145 "Return t if NUM1 less than NUM2.
1146 Return `equal' if NUM1 equals NUM2. Return nil if NUM1 greater than NUM2."
1147 (if (= num1 num2)
1148 'equal
1149 (< num1 num2)))
1150
1151 (defun proced-string-lessp (s1 s2)
1152 "Return t if string S1 is less than S2 in lexicographic order.
1153 Return `equal' if S1 and S2 have identical contents.
1154 Return nil otherwise."
1155 (if (string= s1 s2)
1156 'equal
1157 (string-lessp s1 s2)))
1158
1159 (defun proced-time-lessp (t1 t2)
1160 "Return t if time value T1 is less than time value T2.
1161 Return `equal' if T1 equals T2. Return nil otherwise."
1162 (with-decoded-time-value ((high1 low1 micro1 t1)
1163 (high2 low2 micro2 t2))
1164 (cond ((< high1 high2))
1165 ((< high2 high1) nil)
1166 ((< low1 low2))
1167 ((< low2 low1) nil)
1168 ((< micro1 micro2))
1169 ((< micro2 micro1) nil)
1170 (t 'equal))))
1171
1172 ;;; Sorting
1173
1174 (defsubst proced-xor (b1 b2)
1175 "Return the logical exclusive or of args B1 and B2."
1176 (and (or b1 b2)
1177 (not (and b1 b2))))
1178
1179 (defun proced-sort-p (p1 p2)
1180 "Predicate for sorting processes P1 and P2."
1181 (if (not (cdr proced-sort-internal))
1182 ;; only one predicate: fast scheme
1183 (let* ((sorter (car proced-sort-internal))
1184 (k1 (cdr (assq (car sorter) (cdr p1))))
1185 (k2 (cdr (assq (car sorter) (cdr p2)))))
1186 ;; if the attributes are undefined, we should really abort sorting
1187 (if (and k1 k2)
1188 (proced-xor (funcall (nth 1 sorter) k1 k2)
1189 (nth 2 sorter))))
1190 (let ((sort-list proced-sort-internal) sorter predicate k1 k2)
1191 (catch 'done
1192 (while (setq sorter (pop sort-list))
1193 (setq k1 (cdr (assq (car sorter) (cdr p1)))
1194 k2 (cdr (assq (car sorter) (cdr p2)))
1195 predicate
1196 (if (and k1 k2)
1197 (funcall (nth 1 sorter) k1 k2)))
1198 (if (not (eq predicate 'equal))
1199 (throw 'done (proced-xor predicate (nth 2 sorter)))))
1200 (eq t predicate)))))
1201
1202 (defun proced-sort (process-alist sorter descend)
1203 "Sort PROCESS-ALIST using scheme SORTER.
1204 SORTER is a scheme like `proced-sort'.
1205 DESCEND is non-nil if the first element of SORTER is sorted
1206 in descending order.
1207 Return the sorted process list."
1208 ;; translate SORTER into a list of lists (KEY PREDICATE REVERSE)
1209 (setq proced-sort-internal
1210 (mapcar (lambda (arg)
1211 (let ((grammar (assq arg proced-grammar-alist)))
1212 (unless (nth 4 grammar)
1213 (error "Attribute %s not sortable" (car grammar)))
1214 (list arg (nth 4 grammar) (nth 5 grammar))))
1215 (cond ((listp sorter) sorter)
1216 ((and (symbolp sorter)
1217 (nth 6 (assq sorter proced-grammar-alist))))
1218 ((symbolp sorter) (list sorter))
1219 (t (error "Sorter undefined %s" sorter)))))
1220 (if proced-sort-internal
1221 (progn
1222 ;; splice DESCEND into the list
1223 (setcar proced-sort-internal
1224 (list (caar proced-sort-internal)
1225 (nth 1 (car proced-sort-internal)) descend))
1226 (sort process-alist 'proced-sort-p))
1227 process-alist))
1228
1229 (defun proced-sort-interactive (scheme &optional arg)
1230 "Sort Proced buffer using SCHEME.
1231 When called interactively, an empty string means nil, i.e., no sorting.
1232
1233 Prefix ARG controls sort order:
1234 - If prefix ARG is positive (negative), sort in ascending (descending) order.
1235 - If ARG is nil or 'no-arg and SCHEME is equal to the previous sorting scheme,
1236 reverse the sorting order.
1237 - If ARG is nil or 'no-arg and SCHEME differs from the previous sorting scheme,
1238 adopt the sorting order defined for SCHEME in `proced-grammar-alist'.
1239
1240 Set variable `proced-sort' to SCHEME. The current sort scheme is displayed
1241 in the mode line, using \"+\" or \"-\" for ascending or descending order."
1242 (interactive
1243 (let* (choices
1244 (scheme (completing-read "Sort attribute: "
1245 (dolist (grammar proced-grammar-alist choices)
1246 (if (nth 4 grammar)
1247 (push (list (car grammar)) choices)))
1248 nil t)))
1249 (list (if (string= "" scheme) nil (intern scheme))
1250 ;; like 'toggle in `define-derived-mode'
1251 (or current-prefix-arg 'no-arg))))
1252
1253 (setq proced-descend
1254 ;; If `proced-sort-interactive' is called repeatedly for the same
1255 ;; sort key, the sort order is reversed.
1256 (cond ((and (eq arg 'no-arg) (equal proced-sort scheme))
1257 (not proced-descend))
1258 ((eq arg 'no-arg)
1259 (nth 5 (assq (if (consp scheme) (car scheme) scheme)
1260 proced-grammar-alist)))
1261 (arg (< (prefix-numeric-value arg) 0))
1262 ((equal proced-sort scheme)
1263 (not proced-descend))
1264 (t (nth 5 (assq (if (consp scheme) (car scheme) scheme)
1265 proced-grammar-alist))))
1266 proced-sort scheme)
1267 (proced-update))
1268
1269 (defun proced-sort-pcpu (&optional arg)
1270 "Sort Proced buffer by percentage CPU time (%CPU).
1271 Prefix ARG controls sort order, see `proced-sort-interactive'."
1272 (interactive (list (or current-prefix-arg 'no-arg)))
1273 (proced-sort-interactive 'pcpu arg))
1274
1275 (defun proced-sort-pmem (&optional arg)
1276 "Sort Proced buffer by percentage memory usage (%MEM).
1277 Prefix ARG controls sort order, see `proced-sort-interactive'."
1278 (interactive (list (or current-prefix-arg 'no-arg)))
1279 (proced-sort-interactive 'pmem arg))
1280
1281 (defun proced-sort-pid (&optional arg)
1282 "Sort Proced buffer by PID.
1283 Prefix ARG controls sort order, see `proced-sort-interactive'."
1284 (interactive (list (or current-prefix-arg 'no-arg)))
1285 (proced-sort-interactive 'pid arg))
1286
1287 (defun proced-sort-start (&optional arg)
1288 "Sort Proced buffer by time the command started (START).
1289 Prefix ARG controls sort order, see `proced-sort-interactive'."
1290 (interactive (list (or current-prefix-arg 'no-arg)))
1291 (proced-sort-interactive 'start arg))
1292
1293 (defun proced-sort-time (&optional arg)
1294 "Sort Proced buffer by CPU time (TIME).
1295 Prefix ARG controls sort order, see `proced-sort-interactive'."
1296 (interactive (list (or current-prefix-arg 'no-arg)))
1297 (proced-sort-interactive 'time arg))
1298
1299 (defun proced-sort-user (&optional arg)
1300 "Sort Proced buffer by USER.
1301 Prefix ARG controls sort order, see `proced-sort-interactive'."
1302 (interactive (list (or current-prefix-arg 'no-arg)))
1303 (proced-sort-interactive 'user arg))
1304
1305 (defun proced-sort-header (event &optional arg)
1306 "Sort Proced listing based on an attribute.
1307 EVENT is a mouse event with starting position in the header line.
1308 It is converted to the corresponding attribute key.
1309 This command updates the variable `proced-sort'.
1310 Prefix ARG controls sort order, see `proced-sort-interactive'."
1311 (interactive (list last-input-event (or last-prefix-arg 'no-arg)))
1312 (let ((start (event-start event))
1313 col key)
1314 (save-selected-window
1315 (select-window (posn-window start))
1316 (setq col (+ (1- (car (posn-actual-col-row start)))
1317 (window-hscroll)))
1318 (when (and (<= 0 col) (< col (length proced-header-line)))
1319 (setq key (get-text-property col 'proced-key proced-header-line))
1320 (if key
1321 (proced-sort-interactive key arg)
1322 (message "No sorter defined here."))))))
1323
1324 ;;; Formating
1325
1326 (defun proced-format-time (time)
1327 "Format time interval TIME."
1328 (let* ((ftime (float-time time))
1329 (days (truncate ftime 86400))
1330 (ftime (mod ftime 86400))
1331 (hours (truncate ftime 3600))
1332 (ftime (mod ftime 3600))
1333 (minutes (truncate ftime 60))
1334 (seconds (mod ftime 60)))
1335 (cond ((< 0 days)
1336 (format "%d-%02d:%02d:%02d" days hours minutes seconds))
1337 ((< 0 hours)
1338 (format "%02d:%02d:%02d" hours minutes seconds))
1339 (t
1340 (format "%02d:%02d" minutes seconds)))))
1341
1342 (defun proced-format-start (start)
1343 "Format time START.
1344 The return string is always 6 characters wide."
1345 (let ((d-start (decode-time start))
1346 (d-current (decode-time)))
1347 (cond ( ;; process started in previous years
1348 (< (nth 5 d-start) (nth 5 d-current))
1349 (format-time-string " %Y" start))
1350 ;; process started today
1351 ((and (= (nth 3 d-start) (nth 3 d-current))
1352 (= (nth 4 d-start) (nth 4 d-current)))
1353 (format-time-string " %H:%M" start))
1354 (t ;; process started this year
1355 (format-time-string "%b %e" start)))))
1356
1357 (defun proced-format-ttname (ttname)
1358 "Format attribute TTNAME, omitting path \"/dev/\"."
1359 ;; Does this work for all systems?
1360 (substring ttname (if (string-match "\\`/dev/" ttname)
1361 (match-end 0) 0)))
1362
1363 (defun proced-format-tree (tree)
1364 "Format attribute TREE."
1365 (concat (make-string tree ?\s) (number-to-string tree)))
1366
1367 ;; Proced assumes that every process occupies only one line in the listing.
1368 (defun proced-format-args (args)
1369 "Format attribute ARGS.
1370 Replace newline characters by \"^J\" (two characters)."
1371 (replace-regexp-in-string "\n" "^J" args))
1372
1373 (defun proced-format (process-alist format)
1374 "Display PROCESS-ALIST using FORMAT."
1375 (if (symbolp format)
1376 (setq format (cdr (assq format proced-format-alist))))
1377
1378 ;; Not all systems give us all attributes. We take `emacs-pid' as a
1379 ;; representative process PID. If FORMAT contains a list of alternative
1380 ;; attributes, we take the first attribute that is non-nil for `emacs-pid'.
1381 ;; If none of the alternatives is non-nil, the attribute is ignored
1382 ;; in the listing.
1383 (let ((standard-attributes
1384 (car (proced-process-attributes (list (emacs-pid)))))
1385 new-format fmi)
1386 (if (and proced-tree-flag
1387 (assq 'ppid standard-attributes))
1388 (push (cons 'tree 0) standard-attributes))
1389 (dolist (fmt format)
1390 (if (symbolp fmt)
1391 (if (assq fmt standard-attributes)
1392 (push fmt new-format))
1393 (while (setq fmi (pop fmt))
1394 (when (assq fmi standard-attributes)
1395 (push fmi new-format)
1396 (setq fmt nil)))))
1397 (setq format (nreverse new-format)))
1398
1399 (insert (make-string (length process-alist) ?\n))
1400 (let ((whitespace " ") (unknown "?")
1401 (sort-key (if (consp proced-sort) (car proced-sort) proced-sort))
1402 header-list grammar)
1403 ;; Loop over all attributes
1404 (while (setq grammar (assq (pop format) proced-grammar-alist))
1405 (let* ((key (car grammar))
1406 (fun (cond ((stringp (nth 2 grammar))
1407 `(lambda (arg) (format ,(nth 2 grammar) arg)))
1408 ((not (nth 2 grammar)) 'identity)
1409 ( t (nth 2 grammar))))
1410 (whitespace (if format whitespace ""))
1411 ;; Text properties:
1412 ;; We use the text property `proced-key' to store in each
1413 ;; field the corresponding key.
1414 ;; Of course, the sort predicate appearing in help-echo
1415 ;; is only part of the story. But it gives the main idea.
1416 (hprops
1417 (if (nth 4 grammar)
1418 (let ((descend (if (eq key sort-key) proced-descend (nth 5 grammar))))
1419 `(proced-key ,key mouse-face highlight
1420 help-echo ,(format proced-header-help-echo
1421 (if descend "-" "+")
1422 (nth 1 grammar)
1423 (if descend "descending" "ascending"))))))
1424 (refiner (nth 7 grammar))
1425 (fprops
1426 (cond ((functionp (car refiner))
1427 `(proced-key ,key mouse-face highlight
1428 help-echo ,(format "mouse-2, RET: %s"
1429 (nth 1 refiner))))
1430 ((consp refiner)
1431 `(proced-key ,key mouse-face highlight
1432 help-echo ,(format "mouse-2, RET: refine by attribute %s %s"
1433 (nth 1 grammar)
1434 (mapconcat (lambda (s)
1435 (if s "+" "-"))
1436 refiner ""))))))
1437 value)
1438
1439 ;; highlight the header of the sort column
1440 (if (eq key sort-key)
1441 (setq hprops (append '(face proced-sort-header) hprops)))
1442 (goto-char (point-min))
1443 (cond ( ;; fixed width of output field
1444 (numberp (nth 3 grammar))
1445 (dolist (process process-alist)
1446 (end-of-line)
1447 (setq value (cdr (assq key (cdr process))))
1448 (insert (if value
1449 (apply 'propertize (funcall fun value) fprops)
1450 (format (concat "%" (number-to-string (nth 3 grammar)) "s")
1451 unknown))
1452 whitespace)
1453 (forward-line))
1454 (push (format (concat "%" (number-to-string (nth 3 grammar)) "s")
1455 (apply 'propertize (nth 1 grammar) hprops))
1456 header-list))
1457
1458 ( ;; last field left-justified
1459 (and (not format) (eq 'left (nth 3 grammar)))
1460 (dolist (process process-alist)
1461 (end-of-line)
1462 (setq value (cdr (assq key (cdr process))))
1463 (insert (if value (apply 'propertize (funcall fun value) fprops)
1464 unknown))
1465 (forward-line))
1466 (push (apply 'propertize (nth 1 grammar) hprops) header-list))
1467
1468 (t ;; calculated field width
1469 (let ((width (length (nth 1 grammar)))
1470 field-list value)
1471 (dolist (process process-alist)
1472 (setq value (cdr (assq key (cdr process))))
1473 (if value
1474 (setq value (apply 'propertize (funcall fun value) fprops)
1475 width (max width (length value))
1476 field-list (cons value field-list))
1477 (push unknown field-list)
1478 (setq width (max width (length unknown)))))
1479 (let ((afmt (concat "%" (if (eq 'left (nth 3 grammar)) "-" "")
1480 (number-to-string width) "s")))
1481 (push (format afmt (apply 'propertize (nth 1 grammar) hprops))
1482 header-list)
1483 (dolist (value (nreverse field-list))
1484 (end-of-line)
1485 (insert (format afmt value) whitespace)
1486 (forward-line))))))))
1487
1488 ;; final cleanup
1489 (goto-char (point-min))
1490 (dolist (process process-alist)
1491 ;; We use the text property `proced-pid' to store in each line
1492 ;; the corresponding pid
1493 (put-text-property (point) (line-end-position) 'proced-pid (car process))
1494 (forward-line))
1495 ;; Set header line
1496 (setq proced-header-line
1497 (mapconcat 'identity (nreverse header-list) whitespace))
1498 (if (string-match "[ \t]+$" proced-header-line)
1499 (setq proced-header-line (substring proced-header-line 0
1500 (match-beginning 0))))
1501 ;; (delete-trailing-whitespace)
1502 (goto-char (point-min))
1503 (while (re-search-forward "[ \t\r]+$" nil t)
1504 (delete-region (match-beginning 0) (match-end 0)))))
1505
1506 (defun proced-format-interactive (scheme &optional revert)
1507 "Format Proced buffer using SCHEME.
1508 When called interactively, an empty string means nil, i.e., no formatting.
1509 Set variable `proced-format' to SCHEME.
1510 With prefix REVERT non-nil revert listing."
1511 (interactive
1512 (let ((scheme (completing-read "Format: "
1513 proced-format-alist nil t)))
1514 (list (if (string= "" scheme) nil (intern scheme))
1515 current-prefix-arg)))
1516 ;; only update if necessary
1517 (when (or (not (eq proced-format scheme)) revert)
1518 (setq proced-format scheme)
1519 (proced-update revert)))
1520
1521 ;; generate listing
1522
1523 (defun proced-process-attributes (&optional pid-list)
1524 "Return alist of attributes for each system process.
1525 This alist can be customized via `proced-custom-attributes'.
1526 Optional arg PID-LIST is a list of PIDs of system process that are analyzed.
1527 If no attributes are known for a process (possibly because it already died)
1528 the process is ignored."
1529 ;; Should we make it customizable whether processes with empty attribute
1530 ;; lists are ignored? When would such processes be of interest?
1531 (let (process-alist attributes attr)
1532 (dolist (pid (or pid-list (list-system-processes)) process-alist)
1533 (when (setq attributes (system-process-attributes pid))
1534 (setq attributes (cons (cons 'pid pid) attributes))
1535 (dolist (fun proced-custom-attributes)
1536 (if (setq attr (funcall fun attributes))
1537 (push attr attributes)))
1538 (push (cons pid attributes) process-alist)))))
1539
1540 (defun proced-update (&optional revert quiet)
1541 "Update the Proced process information. Preserves point and marks.
1542 With prefix REVERT non-nil, revert listing.
1543 Suppress status information if QUIET is nil.
1544 After updating a displayed Proced buffer run the normal hook
1545 `proced-post-display-hook'."
1546 ;; This is the main function that generates and updates the process listing.
1547 (interactive "P")
1548 (setq revert (or revert (not proced-process-alist)))
1549 (or quiet (message (if revert "Updating process information..."
1550 "Updating process display...")))
1551 (if revert ;; evaluate all processes
1552 (setq proced-process-alist (proced-process-attributes)))
1553 ;; filtering and sorting
1554 (setq proced-process-alist
1555 (proced-sort (proced-filter proced-process-alist proced-filter)
1556 proced-sort proced-descend))
1557
1558 ;; display as process tree?
1559 (setq proced-process-alist
1560 (proced-tree proced-process-alist))
1561
1562 ;; It is useless to keep undo information if we revert, filter, or
1563 ;; refine the listing so that `proced-process-alist' has changed.
1564 ;; We could keep the undo information if we only re-sort the buffer.
1565 ;; Would that be useful? Re-re-sorting is easy, too.
1566 (if (consp buffer-undo-list)
1567 (setq buffer-undo-list nil))
1568 (let ((buffer-undo-list t)
1569 ;; If point is on a field, we try to return point to that field.
1570 ;; Otherwise we try to return to the same column
1571 (old-pos (let ((pid (proced-pid-at-point))
1572 (key (get-text-property (point) 'proced-key)))
1573 (list pid key ; can both be nil
1574 (if key
1575 (if (get-text-property (1- (point)) 'proced-key)
1576 (- (point) (previous-single-property-change
1577 (point) 'proced-key))
1578 0)
1579 (current-column)))))
1580 buffer-read-only mp-list)
1581 ;; remember marked processes (whatever the mark was)
1582 (goto-char (point-min))
1583 (while (re-search-forward "^\\(\\S-\\)" nil t)
1584 (push (cons (save-match-data (proced-pid-at-point))
1585 (match-string-no-properties 1)) mp-list))
1586
1587 ;; generate listing
1588 (erase-buffer)
1589 (proced-format proced-process-alist proced-format)
1590 (goto-char (point-min))
1591 (while (not (eobp))
1592 (insert " ")
1593 (forward-line))
1594 (setq proced-header-line (concat " " proced-header-line))
1595 (if revert (set-buffer-modified-p nil))
1596
1597 ;; set `goal-column'
1598 (let ((grammar (assq proced-goal-attribute proced-grammar-alist)))
1599 (setq goal-column ;; set to nil if no match
1600 (if (and grammar
1601 (not (zerop (buffer-size)))
1602 (string-match (regexp-quote (nth 1 grammar))
1603 proced-header-line))
1604 (if (nth 3 grammar)
1605 (match-beginning 0)
1606 (match-end 0)))))
1607
1608 ;; Restore process marks and buffer position (if possible).
1609 ;; Sometimes this puts point in the middle of the proced buffer
1610 ;; where it is not interesting. Is there a better / more flexible solution?
1611 (goto-char (point-min))
1612 (let (pid mark new-pos)
1613 (if (or mp-list (car old-pos))
1614 (while (not (eobp))
1615 (setq pid (proced-pid-at-point))
1616 (when (setq mark (assq pid mp-list))
1617 (insert (cdr mark))
1618 (delete-char 1)
1619 (beginning-of-line))
1620 (when (eq (car old-pos) pid)
1621 (if (nth 1 old-pos)
1622 (let ((limit (line-end-position)) pos)
1623 (while (and (not new-pos)
1624 (setq pos (next-property-change (point) nil limit)))
1625 (goto-char pos)
1626 (when (eq (nth 1 old-pos)
1627 (get-text-property (point) 'proced-key))
1628 (forward-char (min (nth 2 old-pos)
1629 (- (next-property-change (point))
1630 (point))))
1631 (setq new-pos (point))))
1632 (unless new-pos
1633 ;; we found the process, but the field of point
1634 ;; is not listed anymore
1635 (setq new-pos (proced-move-to-goal-column))))
1636 (setq new-pos (min (+ (line-beginning-position) (nth 2 old-pos))
1637 (line-end-position)))))
1638 (forward-line)))
1639 (if new-pos
1640 (goto-char new-pos)
1641 (goto-char (point-min))
1642 (proced-move-to-goal-column)))
1643 ;; update modeline
1644 ;; Does the long `mode-name' clutter the modeline? It would be nice
1645 ;; to have some other location for displaying the values of the various
1646 ;; flags that affect the behavior of proced (flags one might want
1647 ;; to change on the fly). Where??
1648 (setq mode-name
1649 (concat "Proced"
1650 (if proced-filter
1651 (concat ": " (symbol-name proced-filter))
1652 "")
1653 (if proced-sort
1654 (let* ((key (if (consp proced-sort) (car proced-sort)
1655 proced-sort))
1656 (grammar (assq key proced-grammar-alist)))
1657 (concat " by " (if proced-descend "-" "+")
1658 (nth 1 grammar)))
1659 "")))
1660 (force-mode-line-update)
1661 ;; run `proced-post-display-hook' only for a displayed buffer.
1662 (if (get-buffer-window) (run-hooks 'proced-post-display-hook))
1663 ;; done
1664 (or quiet (input-pending-p)
1665 (message (if revert "Updating process information...done."
1666 "Updating process display...done.")))))
1667
1668 (defun proced-revert (&rest args)
1669 "Reevaluate the process listing based on the currently running processes.
1670 Preserves point and marks."
1671 (proced-update t))
1672
1673 (defun proced-send-signal (&optional signal)
1674 "Send a SIGNAL to the marked processes.
1675 If no process is marked, operate on current process.
1676 SIGNAL may be a string (HUP, INT, TERM, etc.) or a number.
1677 If SIGNAL is nil display marked processes and query interactively for SIGNAL.
1678 After sending the signal, this command runs the normal hook
1679 `proced-after-send-signal-hook'."
1680 (interactive)
1681 (let ((regexp (proced-marker-regexp))
1682 process-alist)
1683 ;; collect marked processes
1684 (save-excursion
1685 (goto-char (point-min))
1686 (while (re-search-forward regexp nil t)
1687 (push (cons (proced-pid-at-point)
1688 ;; How much info should we collect here?
1689 (buffer-substring-no-properties
1690 (+ 2 (line-beginning-position))
1691 (line-end-position)))
1692 process-alist)))
1693 (setq process-alist
1694 (if process-alist
1695 (nreverse process-alist)
1696 ;; take current process
1697 (list (cons (proced-pid-at-point)
1698 (buffer-substring-no-properties
1699 (+ 2 (line-beginning-position))
1700 (line-end-position))))))
1701 (unless signal
1702 ;; Display marked processes (code taken from `dired-mark-pop-up').
1703 (let ((bufname " *Marked Processes*")
1704 (header-line (substring-no-properties proced-header-line)))
1705 (with-current-buffer (get-buffer-create bufname)
1706 (setq truncate-lines t
1707 proced-header-line header-line ; inherit header line
1708 header-line-format '(:eval (proced-header-line)))
1709 (add-hook 'post-command-hook 'force-mode-line-update nil t)
1710 (erase-buffer)
1711 (dolist (process process-alist)
1712 (insert " " (cdr process) "\n"))
1713 (save-window-excursion
1714 (pop-to-buffer (current-buffer))
1715 (fit-window-to-buffer (get-buffer-window) nil 1)
1716 (let* ((completion-ignore-case t)
1717 (pnum (if (= 1 (length process-alist))
1718 "1 process"
1719 (format "%d processes" (length process-alist))))
1720 ;; The following is an ugly hack. Is there a better way
1721 ;; to help people like me to remember the signals and
1722 ;; their meanings?
1723 (tmp (completing-read (concat "Send signal [" pnum
1724 "] (default TERM): ")
1725 proced-signal-list
1726 nil nil nil nil "TERM")))
1727 (setq signal (if (string-match "^\\(\\S-+\\)\\s-" tmp)
1728 (match-string 1 tmp) tmp))))))
1729 ;; send signal
1730 (let ((count 0)
1731 failures)
1732 ;; Why not always use `signal-process'? See
1733 ;; http://lists.gnu.org/archive/html/emacs-devel/2008-03/msg02955.html
1734 (if (functionp proced-signal-function)
1735 ;; use built-in `signal-process'
1736 (let ((signal (if (stringp signal)
1737 (if (string-match "\\`[0-9]+\\'" signal)
1738 (string-to-number signal)
1739 (make-symbol signal))
1740 signal))) ; number
1741 (dolist (process process-alist)
1742 (condition-case err
1743 (if (zerop (funcall
1744 proced-signal-function (car process) signal))
1745 (setq count (1+ count))
1746 (proced-log "%s\n" (cdr process))
1747 (push (cdr process) failures))
1748 (error ; catch errors from failed signals
1749 (proced-log "%s\n" err)
1750 (proced-log "%s\n" (cdr process))
1751 (push (cdr process) failures)))))
1752 ;; use external system call
1753 (let ((signal (concat "-" (if (numberp signal)
1754 (number-to-string signal) signal))))
1755 (dolist (process process-alist)
1756 (with-temp-buffer
1757 (condition-case err
1758 (if (zerop (call-process
1759 proced-signal-function nil t nil
1760 signal (number-to-string (car process))))
1761 (setq count (1+ count))
1762 (proced-log (current-buffer))
1763 (proced-log "%s\n" (cdr process))
1764 (push (cdr process) failures))
1765 (error ; catch errors from failed signals
1766 (proced-log (current-buffer))
1767 (proced-log "%s\n" (cdr process))
1768 (push (cdr process) failures)))))))
1769 (if failures
1770 ;; Proced error message are not always very precise.
1771 ;; Can we issue a useful one-line summary in the
1772 ;; message area (using FAILURES) if only one signal failed?
1773 (proced-log-summary
1774 signal
1775 (format "%d of %d signal%s failed"
1776 (length failures) (length process-alist)
1777 (if (= 1 (length process-alist)) "" "s")))
1778 (proced-success-message "Sent signal to" count)))
1779 ;; final clean-up
1780 (run-hooks 'proced-after-send-signal-hook))))
1781
1782 ;; similar to `dired-why'
1783 (defun proced-why ()
1784 "Pop up a buffer with error log output from Proced.
1785 A group of errors from a single command ends with a formfeed.
1786 Thus, use \\[backward-page] to find the beginning of a group of errors."
1787 (interactive)
1788 (if (get-buffer proced-log-buffer)
1789 (save-selected-window
1790 ;; move `proced-log-buffer' to the front of the buffer list
1791 (select-window (display-buffer (get-buffer proced-log-buffer)))
1792 (setq truncate-lines t)
1793 (set-buffer-modified-p nil)
1794 (setq buffer-read-only t)
1795 (goto-char (point-max))
1796 (forward-line -1)
1797 (backward-page 1)
1798 (recenter 0))))
1799
1800 ;; similar to `dired-log'
1801 (defun proced-log (log &rest args)
1802 "Log a message or the contents of a buffer.
1803 If LOG is a string and there are more args, it is formatted with
1804 those ARGS. Usually the LOG string ends with a \\n.
1805 End each bunch of errors with (proced-log t signal):
1806 this inserts the current time, buffer and signal at the start of the page,
1807 and \f (formfeed) at the end."
1808 (let ((obuf (current-buffer)))
1809 (with-current-buffer (get-buffer-create proced-log-buffer)
1810 (goto-char (point-max))
1811 (let (buffer-read-only)
1812 (cond ((stringp log)
1813 (insert (if args
1814 (apply 'format log args)
1815 log)))
1816 ((bufferp log)
1817 (insert-buffer-substring log))
1818 ((eq t log)
1819 (backward-page 1)
1820 (unless (bolp)
1821 (insert "\n"))
1822 (insert (current-time-string)
1823 "\tBuffer `" (buffer-name obuf) "', "
1824 (format "signal `%s'\n" (car args)))
1825 (goto-char (point-max))
1826 (insert "\f\n")))))))
1827
1828 ;; similar to `dired-log-summary'
1829 (defun proced-log-summary (signal string)
1830 "State a summary of SIGNAL's failures, in echo area and log buffer.
1831 STRING is an overall summary of the failures."
1832 (message "Signal %s: %s--type ? for details" signal string)
1833 ;; Log a summary describing a bunch of errors.
1834 (proced-log (concat "\n" string "\n"))
1835 (proced-log t signal))
1836
1837 (defun proced-help ()
1838 "Provide help for the Proced user."
1839 (interactive)
1840 (proced-why)
1841 (if (eq last-command 'proced-help)
1842 (describe-mode)
1843 (message proced-help-string)))
1844
1845 (defun proced-undo ()
1846 "Undo in a Proced buffer.
1847 This doesn't recover killed processes, it just undoes changes in the Proced
1848 buffer. You can use it to recover marks."
1849 (interactive)
1850 (let (buffer-read-only)
1851 (undo))
1852 (message "Change in Proced buffer undone.
1853 Killed processes cannot be recovered by Emacs."))
1854
1855 (provide 'proced)
1856
1857 ;; arch-tag: a6e312ad-9032-45aa-972d-31a8cfc545af
1858 ;;; proced.el ends here