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