]> code.delx.au - gnu-emacs/blob - lisp/proced.el
5bd53e47db5980049e23c07efe292ddebb9e4506
[gnu-emacs] / lisp / proced.el
1 ;;; proced.el --- operate on system processes like dired
2
3 ;; Copyright (C) 2008-2015 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 (defgroup proced nil
53 "Proced mode."
54 :group 'processes
55 :group 'unix
56 :prefix "proced-")
57
58 (defcustom proced-signal-function 'signal-process
59 "Name of signal function.
60 It can be an elisp function (usually `signal-process') or a string specifying
61 the external command (usually \"kill\")."
62 :group 'proced
63 :type '(choice (function :tag "function")
64 (string :tag "command")))
65
66 (defcustom proced-renice-command "renice"
67 "Name of renice command."
68 :group 'proced
69 :version "24.3"
70 :type '(string :tag "command"))
71
72 (defcustom proced-signal-list
73 '( ;; signals supported on all POSIX compliant systems
74 ("HUP" . " (1. Hangup)")
75 ("INT" . " (2. Terminal interrupt)")
76 ("QUIT" . " (3. Terminal quit)")
77 ("ABRT" . " (6. Process abort)")
78 ("KILL" . " (9. Kill - cannot be caught or ignored)")
79 ("ALRM" . " (14. Alarm Clock)")
80 ("TERM" . " (15. Termination)")
81 ;; POSIX 1003.1-2001
82 ;; Which systems do not support these signals so that we can
83 ;; exclude them from `proced-signal-list'?
84 ("CONT" . " (Continue executing)")
85 ("STOP" . " (Stop executing / pause - cannot be caught or ignored)")
86 ("TSTP" . " (Terminal stop / pause)"))
87 "List of signals, used for minibuffer completion."
88 :group 'proced
89 :type '(repeat (cons (string :tag "signal name")
90 (string :tag "description"))))
91
92 ;; For which attributes can we use a fixed width of the output field?
93 ;; A fixed width speeds up formatting, yet it can make
94 ;; `proced-grammar-alist' system-dependent.
95 ;; (If proced runs like top(1) we want it to be fast.)
96 ;;
97 ;; If it is impossible / unlikely that an attribute has the same value
98 ;; for two processes, then sorting can be based on one ordinary (fast)
99 ;; predicate like `<'. Otherwise, a list of proced predicates can be used
100 ;; to refine the sort.
101 ;;
102 ;; It would be neat if one could temporarily override the following
103 ;; predefined rules.
104 (defcustom proced-grammar-alist
105 '( ;; attributes defined in `process-attributes'
106 (euid "EUID" "%d" right proced-< nil (euid pid) (nil t nil))
107 (user "User" nil left proced-string-lessp nil (user pid) (nil t nil))
108 (egid "EGID" "%d" right proced-< nil (egid euid pid) (nil t nil))
109 (group "Group" nil left proced-string-lessp nil (group user pid) (nil t nil))
110 (comm "Command" nil left proced-string-lessp nil (comm pid) (nil t nil))
111 (state "Stat" nil left proced-string-lessp nil (state pid) (nil t nil))
112 (ppid "PPID" "%d" right proced-< nil (ppid pid)
113 ((lambda (ppid) (proced-filter-parents proced-process-alist ppid))
114 "refine to process parents"))
115 (pgrp "PGrp" "%d" right proced-< nil (pgrp euid pid) (nil t nil))
116 (sess "Sess" "%d" right proced-< nil (sess pid) (nil t nil))
117 (ttname "TTY" proced-format-ttname left proced-string-lessp nil (ttname pid) (nil t nil))
118 (tpgid "TPGID" "%d" right proced-< nil (tpgid pid) (nil t nil))
119 (minflt "MinFlt" "%d" right proced-< nil (minflt pid) (nil t t))
120 (majflt "MajFlt" "%d" right proced-< nil (majflt pid) (nil t t))
121 (cminflt "CMinFlt" "%d" right proced-< nil (cminflt pid) (nil t t))
122 (cmajflt "CMajFlt" "%d" right proced-< nil (cmajflt pid) (nil t t))
123 (utime "UTime" proced-format-time right proced-time-lessp t (utime pid) (nil t t))
124 (stime "STime" proced-format-time right proced-time-lessp t (stime pid) (nil t t))
125 (time "Time" proced-format-time right proced-time-lessp t (time pid) (nil t t))
126 (cutime "CUTime" proced-format-time right proced-time-lessp t (cutime pid) (nil t t))
127 (cstime "CSTime" proced-format-time right proced-time-lessp t (cstime pid) (nil t t))
128 (ctime "CTime" proced-format-time right proced-time-lessp t (ctime pid) (nil t t))
129 (pri "Pr" "%d" right proced-< t (pri pid) (nil t t))
130 (nice "Ni" "%3d" 3 proced-< t (nice pid) (t t nil))
131 (thcount "THCount" "%d" right proced-< t (thcount pid) (nil t t))
132 (start "Start" proced-format-start 6 proced-time-lessp nil (start pid) (t t nil))
133 (vsize "VSize" "%d" right proced-< t (vsize pid) (nil t t))
134 (rss "RSS" "%d" right proced-< t (rss pid) (nil t t))
135 (etime "ETime" proced-format-time right proced-time-lessp t (etime pid) (nil t t))
136 (pcpu "%CPU" "%.1f" right proced-< t (pcpu pid) (nil t t))
137 (pmem "%Mem" "%.1f" right proced-< t (pmem pid) (nil t t))
138 (args "Args" proced-format-args left proced-string-lessp nil (args pid) (nil t nil))
139 ;;
140 ;; attributes defined by proced (see `proced-process-attributes')
141 (pid "PID" "%d" right proced-< nil (pid)
142 ((lambda (ppid) (proced-filter-children proced-process-alist ppid))
143 "refine to process children"))
144 ;; process tree
145 (tree "Tree" proced-format-tree left nil nil nil nil))
146 "Alist of rules for handling Proced attributes.
147
148 Each element has the form
149
150 (KEY NAME FORMAT JUSTIFY PREDICATE REVERSE SORT-SCHEME REFINER).
151
152 Symbol KEY is the car of a process attribute.
153
154 String NAME appears in the header line.
155
156 FORMAT specifies the format for displaying the attribute values. It can
157 be a string passed to `format'. It can be a function called with one
158 argument, the value of the attribute. The value nil means take as is.
159
160 If JUSTIFY is an integer, its modulus gives the width of the attribute
161 values formatted with FORMAT. If JUSTIFY is positive, NAME appears
162 right-justified, otherwise it appears left-justified. If JUSTIFY is `left'
163 or `right', the field width is calculated from all field values in the listing.
164 If JUSTIFY is `left', the field values are formatted left-justified and
165 right-justified otherwise.
166
167 PREDICATE is the predicate for sorting and filtering the process listing
168 based on attribute KEY. PREDICATE takes two arguments P1 and P2,
169 the corresponding attribute values of two processes. PREDICATE should
170 return `equal' if P1 has same rank like P2. Any other non-nil value says
171 that P1 is \"less than\" P2, or nil if not.
172 If PREDICATE is nil the attribute cannot be sorted.
173
174 PREDICATE defines an ascending sort order. REVERSE is non-nil if the sort
175 order is descending.
176
177 SORT-SCHEME is a list (KEY1 KEY2 ...) defining a hierarchy of rules
178 for sorting the process listing. KEY1, KEY2, ... are KEYs appearing as cars
179 of `proced-grammar-alist'. First the PREDICATE of KEY1 is evaluated.
180 If it yields non-equal, it defines the sort order for the corresponding
181 processes. If it evaluates to `equal' the PREDICATE of KEY2 is evaluated, etc.
182
183 REFINER can be a list of flags (LESS-B EQUAL-B LARGER-B) used by the command
184 `proced-refine' (see there) to refine the listing based on attribute KEY.
185 This command compares the value of attribute KEY of every process with
186 the value of attribute KEY of the process at the position of point
187 using PREDICATE.
188 If PREDICATE yields non-nil, the process is accepted if LESS-B is non-nil.
189 If PREDICATE yields `equal', the process is accepted if EQUAL-B is non-nil.
190 If PREDICATE yields nil, the process is accepted if LARGER-B is non-nil.
191
192 REFINER can also be a list (FUNCTION HELP-ECHO).
193 FUNCTION is called with one argument, the PID of the process at the position
194 of point. The function must return a list of PIDs that is used for the refined
195 listing. HELP-ECHO is a string that is shown when mouse is over this field.
196
197 If REFINER is nil no refinement is done."
198 :group 'proced
199 :type '(repeat (list :tag "Attribute"
200 (symbol :tag "Key")
201 (string :tag "Header")
202 (choice :tag "Format"
203 (const :tag "None" nil)
204 (string :tag "Format String")
205 (function :tag "Formatting Function"))
206 (choice :tag "Justification"
207 (const :tag "left" left)
208 (const :tag "right" right)
209 (integer :tag "width"))
210 (choice :tag "Predicate"
211 (const :tag "None" nil)
212 (function :tag "Function"))
213 (boolean :tag "Descending Sort Order")
214 (repeat :tag "Sort Scheme" (symbol :tag "Key"))
215 (choice :tag "Refiner"
216 (const :tag "None" nil)
217 (list (function :tag "Refinement Function")
218 (string :tag "Help echo"))
219 (list :tag "Refine Flags"
220 (boolean :tag "Less")
221 (boolean :tag "Equal")
222 (boolean :tag "Larger"))))))
223
224 (defcustom proced-custom-attributes nil
225 "List of functions defining custom attributes.
226 This variable extends the functionality of `proced-process-attributes'.
227 Each function is called with one argument, the list of attributes
228 of a system process. It returns a cons cell of the form (KEY . VALUE)
229 like `process-attributes'. This cons cell is appended to the list
230 returned by `proced-process-attributes'.
231 If the function returns nil, the value is ignored."
232 :group 'proced
233 :type '(repeat (function :tag "Attribute")))
234
235 ;; Formatting and sorting rules are defined "per attribute". If formatting
236 ;; and / or sorting should use more than one attribute, it appears more
237 ;; transparent to define a new derived attribute, so that formatting and
238 ;; sorting can use them consistently. (Are there exceptions to this rule?
239 ;; Would it be advantageous to have yet more general methods available?)
240 ;; Sorting can also be based on attributes that are invisible in the listing.
241
242 (defcustom proced-format-alist
243 '((short user pid tree pcpu pmem start time (args comm))
244 (medium user pid tree pcpu pmem vsize rss ttname state start time (args comm))
245 (long user euid group pid tree pri nice pcpu pmem vsize rss ttname state
246 start time (args comm))
247 (verbose user euid group egid pid ppid tree pgrp sess pri nice pcpu pmem
248 state thcount vsize rss ttname tpgid minflt majflt cminflt cmajflt
249 start time utime stime ctime cutime cstime etime (args comm)))
250 "Alist of formats of listing.
251 The car of each element is a symbol, the name of the format.
252 The cdr is a list of attribute keys appearing in `proced-grammar-alist'.
253 An element of this list may also be a list of attribute keys that specifies
254 alternatives. If the first attribute is absent for a process, use the second
255 one, etc."
256 :group 'proced
257 :type '(alist :key-type (symbol :tag "Format Name")
258 :value-type (repeat :tag "Keys"
259 (choice (symbol :tag "")
260 (repeat :tag "Alternative Keys"
261 (symbol :tag ""))))))
262
263 (defcustom proced-format 'short
264 "Current format of Proced listing.
265 It can be the car of an element of `proced-format-alist'.
266 It can also be a list of keys appearing in `proced-grammar-alist'."
267 :group 'proced
268 :type '(choice (symbol :tag "Format Name")
269 (repeat :tag "Keys" (symbol :tag ""))))
270 (make-variable-buffer-local 'proced-format)
271
272 ;; FIXME: is there a better name for filter `user' that does not coincide
273 ;; with an attribute key?
274 (defcustom proced-filter-alist
275 `((user (user . ,(concat "\\`" (regexp-quote (user-real-login-name)) "\\'")))
276 (user-running (user . ,(concat "\\`" (regexp-quote (user-real-login-name)) "\\'"))
277 (state . "\\`[Rr]\\'"))
278 (all)
279 (all-running (state . "\\`[Rr]\\'"))
280 (emacs (fun-all . (lambda (list)
281 (proced-filter-children list ,(emacs-pid))))))
282 "Alist of process filters.
283 The car of each element is a symbol, the name of the filter.
284 The cdr is a list of elementary filters that are applied to every process.
285 A process is displayed if it passes all elementary filters of a selected
286 filter.
287
288 An elementary filter can be one of the following:
289 \(KEY . REGEXP) If value of attribute KEY matches REGEXP,
290 accept this process.
291 \(KEY . FUN) Apply function FUN to attribute KEY. Accept this process,
292 if FUN returns non-nil.
293 \(function . FUN) For each process, apply function FUN to list of attributes
294 of each. Accept the process if FUN returns non-nil.
295 \(fun-all . FUN) Apply function FUN to entire process list.
296 FUN must return the filtered list."
297 :group 'proced
298 :type '(repeat (cons :tag "Filter"
299 (symbol :tag "Filter Name")
300 (repeat :tag "Filters"
301 (choice (cons :tag "Key . Regexp" (symbol :tag "Key") regexp)
302 (cons :tag "Key . Function" (symbol :tag "Key") function)
303 (cons :tag "Function" (const :tag "Key: function" function) function)
304 (cons :tag "Fun-all" (const :tag "Key: fun-all" fun-all) function))))))
305
306 (defcustom proced-filter 'user
307 "Current filter of proced listing.
308 It can be the car of an element of `proced-filter-alist'.
309 It can also be a list of elementary filters as in the cdrs of the elements
310 of `proced-filter-alist'."
311 :group 'proced
312 :type '(choice (symbol :tag "Filter Name")
313 (repeat :tag "Filters"
314 (choice (cons :tag "Key . Regexp" (symbol :tag "Key") regexp)
315 (cons :tag "Key . Function" (symbol :tag "Key") function)
316 (cons :tag "Function" (const :tag "Key: function" function) function)
317 (cons :tag "Fun-all" (const :tag "Key: fun-all" fun-all) function)))))
318 (make-variable-buffer-local 'proced-filter)
319
320 (defcustom proced-sort 'pcpu
321 "Current sort scheme for proced listing.
322 It must be the KEY of an element of `proced-grammar-alist'.
323 It can also be a list of KEYs as in the SORT-SCHEMEs of the elements
324 of `proced-grammar-alist'."
325 :group 'proced
326 :type '(choice (symbol :tag "Sort Scheme")
327 (repeat :tag "Key List" (symbol :tag "Key"))))
328 (make-variable-buffer-local 'proced-sort)
329
330 (defcustom proced-descend t
331 "Non-nil if proced listing is sorted in descending order."
332 :group 'proced
333 :type '(boolean :tag "Descending Sort Order"))
334 (make-variable-buffer-local 'proced-descend)
335
336 (defcustom proced-goal-attribute 'args
337 "If non-nil, key of the attribute that defines the `goal-column'."
338 :group 'proced
339 :type '(choice (const :tag "none" nil)
340 (symbol :tag "key")))
341
342 (defcustom proced-auto-update-interval 5
343 "Time interval in seconds for auto updating Proced buffers."
344 :group 'proced
345 :type 'integer)
346
347 (defcustom proced-auto-update-flag nil
348 "Non-nil for auto update of a Proced buffer.
349 Can be changed interactively via `proced-toggle-auto-update'."
350 :group 'proced
351 :type 'boolean)
352 (make-variable-buffer-local 'proced-auto-update-flag)
353
354 (defcustom proced-tree-flag nil
355 "Non-nil for display of Proced buffer as process tree."
356 :group 'proced
357 :type 'boolean)
358 (make-variable-buffer-local 'proced-tree-flag)
359
360 (defcustom proced-post-display-hook nil
361 "Normal hook run after displaying or updating a Proced buffer.
362 May be used to adapt the window size via `fit-window-to-buffer'."
363 :type 'hook
364 :options '(fit-window-to-buffer)
365 :group 'proced)
366
367 (defcustom proced-after-send-signal-hook nil
368 "Normal hook run after sending a signal to processes by `proced-send-signal'.
369 May be used to revert the process listing."
370 :type 'hook
371 :options '(proced-revert)
372 :group 'proced)
373
374 ;; Internal variables
375
376 (defvar proced-available (not (null (list-system-processes)))
377 "Non-nil means Proced is known to work on this system.")
378
379 (defvar proced-process-alist nil
380 "Alist of processes displayed by Proced.
381 The car of each element is the PID, and the cdr is a list of
382 cons pairs, see `proced-process-attributes'.")
383 (make-variable-buffer-local 'proced-process-alist)
384
385 (defvar proced-sort-internal nil
386 "Sort scheme for listing (internal format).
387 It is a list of lists (KEY PREDICATE REVERSE).")
388
389 (defvar proced-marker-char ?* ; the answer is 42
390 "In Proced, the current mark character.")
391
392 ;; Faces and font-lock code taken from dired,
393 ;; but face variables are deprecated for new code.
394 (defgroup proced-faces nil
395 "Faces used by Proced."
396 :group 'proced
397 :group 'faces)
398
399 (defface proced-mark
400 '((t (:inherit font-lock-constant-face)))
401 "Face used for Proced marks."
402 :group 'proced-faces)
403
404 (defface proced-marked
405 '((t (:inherit error)))
406 "Face used for marked processes."
407 :group 'proced-faces)
408
409 (defface proced-sort-header
410 '((t (:inherit font-lock-keyword-face)))
411 "Face used for header of attribute used for sorting."
412 :group 'proced-faces)
413
414 (defvar proced-re-mark "^[^ \n]"
415 "Regexp matching a marked line.
416 Important: the match ends just after the marker.")
417
418 (defvar proced-header-line nil
419 "Headers in Proced buffer as a string.")
420 (make-variable-buffer-local 'proced-header-line)
421
422 (defvar proced-temp-alist nil
423 "Temporary alist (internal variable).")
424
425 (defvar proced-process-tree nil
426 "Proced process tree (internal variable).")
427
428 (defvar proced-tree-depth nil
429 "Internal variable for depth of Proced process tree.")
430
431 (defvar proced-auto-update-timer nil
432 "Stores if Proced auto update timer is already installed.")
433
434 (defvar proced-log-buffer "*Proced log*"
435 "Name of Proced Log buffer.")
436
437 (defconst proced-help-string
438 "(n)ext, (p)revious, (m)ark, (u)nmark, (k)ill, (q)uit (type ? for more help)"
439 "Help string for Proced.")
440
441 (defconst proced-header-help-echo
442 "mouse-1, mouse-2: sort by attribute %s%s (%s)"
443 "Help string shown when mouse is over a sortable header.")
444
445 (defconst proced-field-help-echo
446 "mouse-2, RET: refine by attribute %s %s"
447 "Help string shown when mouse is over a refinable field.")
448
449 (defvar proced-font-lock-keywords
450 `(;; (Any) proced marks.
451 (,proced-re-mark . 'proced-mark)
452 ;; Processes marked with `proced-marker-char'
453 ;; Should we make sure that only certain attributes are font-locked?
454 (,(concat "^[" (char-to-string proced-marker-char) "]")
455 ".+" (proced-move-to-goal-column) nil (0 'proced-marked))))
456
457 (defvar proced-mode-map
458 (let ((km (make-sparse-keymap)))
459 ;; moving
460 (define-key km " " 'next-line)
461 (define-key km "n" 'next-line)
462 (define-key km "p" 'previous-line)
463 (define-key km "\C-n" 'next-line)
464 (define-key km "\C-p" 'previous-line)
465 (define-key km "\C-?" 'previous-line)
466 (define-key km [?\S-\ ] '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 (or (time-less-p t1 t2)
1189 (if (not (time-less-p t2 t1)) 'equal)))
1190
1191 ;;; Sorting
1192
1193 (defsubst proced-xor (b1 b2)
1194 "Return the logical exclusive or of args B1 and B2."
1195 (and (or b1 b2)
1196 (not (and b1 b2))))
1197
1198 (defun proced-sort-p (p1 p2)
1199 "Predicate for sorting processes P1 and P2."
1200 (if (not (cdr proced-sort-internal))
1201 ;; only one predicate: fast scheme
1202 (let* ((sorter (car proced-sort-internal))
1203 (k1 (cdr (assq (car sorter) (cdr p1))))
1204 (k2 (cdr (assq (car sorter) (cdr p2)))))
1205 ;; if the attributes are undefined, we should really abort sorting
1206 (if (and k1 k2)
1207 (proced-xor (funcall (nth 1 sorter) k1 k2)
1208 (nth 2 sorter))))
1209 (let ((sort-list proced-sort-internal) sorter predicate k1 k2)
1210 (catch 'done
1211 (while (setq sorter (pop sort-list))
1212 (setq k1 (cdr (assq (car sorter) (cdr p1)))
1213 k2 (cdr (assq (car sorter) (cdr p2)))
1214 predicate
1215 (if (and k1 k2)
1216 (funcall (nth 1 sorter) k1 k2)))
1217 (if (not (eq predicate 'equal))
1218 (throw 'done (proced-xor predicate (nth 2 sorter)))))
1219 (eq t predicate)))))
1220
1221 (defun proced-sort (process-alist sorter descend)
1222 "Sort PROCESS-ALIST using scheme SORTER.
1223 SORTER is a scheme like `proced-sort'.
1224 DESCEND is non-nil if the first element of SORTER is sorted
1225 in descending order.
1226 Return the sorted process list."
1227 ;; translate SORTER into a list of lists (KEY PREDICATE REVERSE)
1228 (setq proced-sort-internal
1229 (mapcar (lambda (arg)
1230 (let ((grammar (assq arg proced-grammar-alist)))
1231 (unless (nth 4 grammar)
1232 (error "Attribute %s not sortable" (car grammar)))
1233 (list arg (nth 4 grammar) (nth 5 grammar))))
1234 (cond ((listp sorter) sorter)
1235 ((and (symbolp sorter)
1236 (nth 6 (assq sorter proced-grammar-alist))))
1237 ((symbolp sorter) (list sorter))
1238 (t (error "Sorter undefined %s" sorter)))))
1239 (if proced-sort-internal
1240 (progn
1241 ;; splice DESCEND into the list
1242 (setcar proced-sort-internal
1243 (list (caar proced-sort-internal)
1244 (nth 1 (car proced-sort-internal)) descend))
1245 (sort process-alist 'proced-sort-p))
1246 process-alist))
1247
1248 (defun proced-sort-interactive (scheme &optional arg)
1249 "Sort Proced buffer using SCHEME.
1250 When called interactively, an empty string means nil, i.e., no sorting.
1251
1252 Prefix ARG controls sort order:
1253 - If prefix ARG is positive (negative), sort in ascending (descending) order.
1254 - If ARG is nil or `no-arg' and SCHEME is equal to the previous sorting scheme,
1255 reverse the sorting order.
1256 - If ARG is nil or `no-arg' and SCHEME differs from the previous sorting scheme,
1257 adopt the sorting order defined for SCHEME in `proced-grammar-alist'.
1258
1259 Set variable `proced-sort' to SCHEME. The current sort scheme is displayed
1260 in the mode line, using \"+\" or \"-\" for ascending or descending order."
1261 (interactive
1262 (let* (choices
1263 (scheme (completing-read "Sort attribute: "
1264 (dolist (grammar proced-grammar-alist choices)
1265 (if (nth 4 grammar)
1266 (push (list (car grammar)) choices)))
1267 nil t)))
1268 (list (if (string= "" scheme) nil (intern scheme))
1269 ;; like 'toggle in `define-derived-mode'
1270 (or current-prefix-arg 'no-arg))))
1271
1272 (setq proced-descend
1273 ;; If `proced-sort-interactive' is called repeatedly for the same
1274 ;; sort key, the sort order is reversed.
1275 (cond ((and (eq arg 'no-arg) (equal proced-sort scheme))
1276 (not proced-descend))
1277 ((eq arg 'no-arg)
1278 (nth 5 (assq (if (consp scheme) (car scheme) scheme)
1279 proced-grammar-alist)))
1280 (arg (< (prefix-numeric-value arg) 0))
1281 ((equal proced-sort scheme)
1282 (not proced-descend))
1283 (t (nth 5 (assq (if (consp scheme) (car scheme) scheme)
1284 proced-grammar-alist))))
1285 proced-sort scheme)
1286 (proced-update))
1287
1288 (defun proced-sort-pcpu (&optional arg)
1289 "Sort Proced buffer by percentage CPU time (%CPU).
1290 Prefix ARG controls sort order, see `proced-sort-interactive'."
1291 (interactive (list (or current-prefix-arg 'no-arg)))
1292 (proced-sort-interactive 'pcpu arg))
1293
1294 (defun proced-sort-pmem (&optional arg)
1295 "Sort Proced buffer by percentage memory usage (%MEM).
1296 Prefix ARG controls sort order, see `proced-sort-interactive'."
1297 (interactive (list (or current-prefix-arg 'no-arg)))
1298 (proced-sort-interactive 'pmem arg))
1299
1300 (defun proced-sort-pid (&optional arg)
1301 "Sort Proced buffer by PID.
1302 Prefix ARG controls sort order, see `proced-sort-interactive'."
1303 (interactive (list (or current-prefix-arg 'no-arg)))
1304 (proced-sort-interactive 'pid arg))
1305
1306 (defun proced-sort-start (&optional arg)
1307 "Sort Proced buffer by time the command started (START).
1308 Prefix ARG controls sort order, see `proced-sort-interactive'."
1309 (interactive (list (or current-prefix-arg 'no-arg)))
1310 (proced-sort-interactive 'start arg))
1311
1312 (defun proced-sort-time (&optional arg)
1313 "Sort Proced buffer by CPU time (TIME).
1314 Prefix ARG controls sort order, see `proced-sort-interactive'."
1315 (interactive (list (or current-prefix-arg 'no-arg)))
1316 (proced-sort-interactive 'time arg))
1317
1318 (defun proced-sort-user (&optional arg)
1319 "Sort Proced buffer by USER.
1320 Prefix ARG controls sort order, see `proced-sort-interactive'."
1321 (interactive (list (or current-prefix-arg 'no-arg)))
1322 (proced-sort-interactive 'user arg))
1323
1324 (defun proced-sort-header (event &optional arg)
1325 "Sort Proced listing based on an attribute.
1326 EVENT is a mouse event with starting position in the header line.
1327 It is converted to the corresponding attribute key.
1328 This command updates the variable `proced-sort'.
1329 Prefix ARG controls sort order, see `proced-sort-interactive'."
1330 (interactive (list last-input-event (or last-prefix-arg 'no-arg)))
1331 (let ((start (event-start event))
1332 col key)
1333 (save-selected-window
1334 (select-window (posn-window start))
1335 (setq col (+ (1- (car (posn-actual-col-row start)))
1336 (window-hscroll)))
1337 (when (and (<= 0 col) (< col (length proced-header-line)))
1338 (setq key (get-text-property col 'proced-key proced-header-line))
1339 (if key
1340 (proced-sort-interactive key arg)
1341 (message "No sorter defined here."))))))
1342
1343 ;;; Formatting
1344
1345 (defun proced-format-time (time)
1346 "Format time interval TIME."
1347 (let* ((ftime (float-time time))
1348 (days (truncate ftime 86400))
1349 (ftime (mod ftime 86400))
1350 (hours (truncate ftime 3600))
1351 (ftime (mod ftime 3600))
1352 (minutes (truncate ftime 60))
1353 (seconds (mod ftime 60)))
1354 (cond ((< 0 days)
1355 (format "%d-%02d:%02d:%02d" days hours minutes seconds))
1356 ((< 0 hours)
1357 (format "%02d:%02d:%02d" hours minutes seconds))
1358 (t
1359 (format "%02d:%02d" minutes seconds)))))
1360
1361 (defun proced-format-start (start)
1362 "Format time START.
1363 The return string is always 6 characters wide."
1364 (let ((d-start (decode-time start))
1365 (d-current (decode-time)))
1366 (cond ( ;; process started in previous years
1367 (< (nth 5 d-start) (nth 5 d-current))
1368 (format-time-string " %Y" start))
1369 ;; process started today
1370 ((and (= (nth 3 d-start) (nth 3 d-current))
1371 (= (nth 4 d-start) (nth 4 d-current)))
1372 (format-time-string " %H:%M" start))
1373 (t ;; process started this year
1374 (format-time-string "%b %e" start)))))
1375
1376 (defun proced-format-ttname (ttname)
1377 "Format attribute TTNAME, omitting path \"/dev/\"."
1378 ;; Does this work for all systems?
1379 (substring ttname (if (string-match "\\`/dev/" ttname)
1380 (match-end 0) 0)))
1381
1382 (defun proced-format-tree (tree)
1383 "Format attribute TREE."
1384 (concat (make-string tree ?\s) (number-to-string tree)))
1385
1386 ;; Proced assumes that every process occupies only one line in the listing.
1387 (defun proced-format-args (args)
1388 "Format attribute ARGS.
1389 Replace newline characters by \"^J\" (two characters)."
1390 (replace-regexp-in-string "\n" "^J" args))
1391
1392 (defun proced-format (process-alist format)
1393 "Display PROCESS-ALIST using FORMAT."
1394 (if (symbolp format)
1395 (setq format (cdr (assq format proced-format-alist))))
1396
1397 ;; Not all systems give us all attributes. We take `emacs-pid' as a
1398 ;; representative process PID. If FORMAT contains a list of alternative
1399 ;; attributes, we take the first attribute that is non-nil for `emacs-pid'.
1400 ;; If none of the alternatives is non-nil, the attribute is ignored
1401 ;; in the listing.
1402 (let ((standard-attributes
1403 (car (proced-process-attributes (list (emacs-pid)))))
1404 new-format fmi)
1405 (if (and proced-tree-flag
1406 (assq 'ppid standard-attributes))
1407 (push (cons 'tree 0) standard-attributes))
1408 (dolist (fmt format)
1409 (if (symbolp fmt)
1410 (if (assq fmt standard-attributes)
1411 (push fmt new-format))
1412 (while (setq fmi (pop fmt))
1413 (when (assq fmi standard-attributes)
1414 (push fmi new-format)
1415 (setq fmt nil)))))
1416 (setq format (nreverse new-format)))
1417
1418 (insert (make-string (length process-alist) ?\n))
1419 (let ((whitespace " ") (unknown "?")
1420 (sort-key (if (consp proced-sort) (car proced-sort) proced-sort))
1421 header-list grammar)
1422 ;; Loop over all attributes
1423 (while (setq grammar (assq (pop format) proced-grammar-alist))
1424 (let* ((key (car grammar))
1425 (fun (cond ((stringp (nth 2 grammar))
1426 `(lambda (arg) (format ,(nth 2 grammar) arg)))
1427 ((not (nth 2 grammar)) 'identity)
1428 ( t (nth 2 grammar))))
1429 (whitespace (if format whitespace ""))
1430 ;; Text properties:
1431 ;; We use the text property `proced-key' to store in each
1432 ;; field the corresponding key.
1433 ;; Of course, the sort predicate appearing in help-echo
1434 ;; is only part of the story. But it gives the main idea.
1435 (hprops
1436 (if (nth 4 grammar)
1437 (let ((descend (if (eq key sort-key) proced-descend (nth 5 grammar))))
1438 `(proced-key ,key mouse-face highlight
1439 help-echo ,(format proced-header-help-echo
1440 (if descend "-" "+")
1441 (nth 1 grammar)
1442 (if descend "descending" "ascending"))))))
1443 (refiner (nth 7 grammar))
1444 (fprops
1445 (cond ((functionp (car refiner))
1446 `(proced-key ,key mouse-face highlight
1447 help-echo ,(format "mouse-2, RET: %s"
1448 (nth 1 refiner))))
1449 ((consp refiner)
1450 `(proced-key ,key mouse-face highlight
1451 help-echo ,(format "mouse-2, RET: refine by attribute %s %s"
1452 (nth 1 grammar)
1453 (mapconcat (lambda (s)
1454 (if s "+" "-"))
1455 refiner ""))))))
1456 value)
1457
1458 ;; highlight the header of the sort column
1459 (if (eq key sort-key)
1460 (setq hprops (append '(face proced-sort-header) hprops)))
1461 (goto-char (point-min))
1462 (cond ( ;; fixed width of output field
1463 (numberp (nth 3 grammar))
1464 (dolist (process process-alist)
1465 (end-of-line)
1466 (setq value (cdr (assq key (cdr process))))
1467 (insert (if value
1468 (apply 'propertize (funcall fun value) fprops)
1469 (format (concat "%" (number-to-string (nth 3 grammar)) "s")
1470 unknown))
1471 whitespace)
1472 (forward-line))
1473 (push (format (concat "%" (number-to-string (nth 3 grammar)) "s")
1474 (apply 'propertize (nth 1 grammar) hprops))
1475 header-list))
1476
1477 ( ;; last field left-justified
1478 (and (not format) (eq 'left (nth 3 grammar)))
1479 (dolist (process process-alist)
1480 (end-of-line)
1481 (setq value (cdr (assq key (cdr process))))
1482 (insert (if value (apply 'propertize (funcall fun value) fprops)
1483 unknown))
1484 (forward-line))
1485 (push (apply 'propertize (nth 1 grammar) hprops) header-list))
1486
1487 (t ;; calculated field width
1488 (let ((width (length (nth 1 grammar)))
1489 field-list value)
1490 (dolist (process process-alist)
1491 (setq value (cdr (assq key (cdr process))))
1492 (if value
1493 (setq value (apply 'propertize (funcall fun value) fprops)
1494 width (max width (length value))
1495 field-list (cons value field-list))
1496 (push unknown field-list)
1497 (setq width (max width (length unknown)))))
1498 (let ((afmt (concat "%" (if (eq 'left (nth 3 grammar)) "-" "")
1499 (number-to-string width) "s")))
1500 (push (format afmt (apply 'propertize (nth 1 grammar) hprops))
1501 header-list)
1502 (dolist (value (nreverse field-list))
1503 (end-of-line)
1504 (insert (format afmt value) whitespace)
1505 (forward-line))))))))
1506
1507 ;; final cleanup
1508 (goto-char (point-min))
1509 (dolist (process process-alist)
1510 ;; We use the text property `proced-pid' to store in each line
1511 ;; the corresponding pid
1512 (put-text-property (point) (line-end-position) 'proced-pid (car process))
1513 (forward-line))
1514 ;; Set header line
1515 (setq proced-header-line
1516 (mapconcat 'identity (nreverse header-list) whitespace))
1517 (if (string-match "[ \t]+$" proced-header-line)
1518 (setq proced-header-line (substring proced-header-line 0
1519 (match-beginning 0))))
1520 ;; (delete-trailing-whitespace)
1521 (goto-char (point-min))
1522 (while (re-search-forward "[ \t\r]+$" nil t)
1523 (delete-region (match-beginning 0) (match-end 0)))))
1524
1525 (defun proced-format-interactive (scheme &optional revert)
1526 "Format Proced buffer using SCHEME.
1527 When called interactively, an empty string means nil, i.e., no formatting.
1528 Set variable `proced-format' to SCHEME.
1529 With prefix REVERT non-nil revert listing."
1530 (interactive
1531 (let ((scheme (completing-read "Format: "
1532 proced-format-alist nil t)))
1533 (list (if (string= "" scheme) nil (intern scheme))
1534 current-prefix-arg)))
1535 ;; only update if necessary
1536 (when (or (not (eq proced-format scheme)) revert)
1537 (setq proced-format scheme)
1538 (proced-update revert)))
1539
1540 ;; generate listing
1541
1542 (defun proced-process-attributes (&optional pid-list)
1543 "Return alist of attributes for each system process.
1544 This alist can be customized via `proced-custom-attributes'.
1545 Optional arg PID-LIST is a list of PIDs of system process that are analyzed.
1546 If no attributes are known for a process (possibly because it already died)
1547 the process is ignored."
1548 ;; Should we make it customizable whether processes with empty attribute
1549 ;; lists are ignored? When would such processes be of interest?
1550 (let (process-alist attributes attr)
1551 (dolist (pid (or pid-list (list-system-processes)) process-alist)
1552 (when (setq attributes (process-attributes pid))
1553 (setq attributes (cons (cons 'pid pid) attributes))
1554 (dolist (fun proced-custom-attributes)
1555 (if (setq attr (funcall fun attributes))
1556 (push attr attributes)))
1557 (push (cons pid attributes) process-alist)))))
1558
1559 (defun proced-update (&optional revert quiet)
1560 "Update the Proced process information. Preserves point and marks.
1561 With prefix REVERT non-nil, revert listing.
1562 Suppress status information if QUIET is nil.
1563 After updating a displayed Proced buffer run the normal hook
1564 `proced-post-display-hook'."
1565 ;; This is the main function that generates and updates the process listing.
1566 (interactive "P")
1567 (setq revert (or revert (not proced-process-alist)))
1568 (or quiet (message (if revert "Updating process information..."
1569 "Updating process display...")))
1570 (if revert ;; evaluate all processes
1571 (setq proced-process-alist (proced-process-attributes)))
1572 ;; filtering and sorting
1573 (setq proced-process-alist
1574 (proced-sort (proced-filter proced-process-alist proced-filter)
1575 proced-sort proced-descend))
1576
1577 ;; display as process tree?
1578 (setq proced-process-alist
1579 (proced-tree proced-process-alist))
1580
1581 ;; It is useless to keep undo information if we revert, filter, or
1582 ;; refine the listing so that `proced-process-alist' has changed.
1583 ;; We could keep the undo information if we only re-sort the buffer.
1584 ;; Would that be useful? Re-re-sorting is easy, too.
1585 (if (consp buffer-undo-list)
1586 (setq buffer-undo-list nil))
1587 (let ((buffer-undo-list t)
1588 ;; If point is on a field, we try to return point to that field.
1589 ;; Otherwise we try to return to the same column
1590 (old-pos (let ((pid (proced-pid-at-point))
1591 (key (get-text-property (point) 'proced-key)))
1592 (list pid key ; can both be nil
1593 (if key
1594 (if (get-text-property (1- (point)) 'proced-key)
1595 (- (point) (previous-single-property-change
1596 (point) 'proced-key))
1597 0)
1598 (current-column)))))
1599 buffer-read-only mp-list)
1600 ;; remember marked processes (whatever the mark was)
1601 (goto-char (point-min))
1602 (while (re-search-forward "^\\(\\S-\\)" nil t)
1603 (push (cons (save-match-data (proced-pid-at-point))
1604 (match-string-no-properties 1)) mp-list))
1605
1606 ;; generate listing
1607 (erase-buffer)
1608 (proced-format proced-process-alist proced-format)
1609 (goto-char (point-min))
1610 (while (not (eobp))
1611 (insert " ")
1612 (forward-line))
1613 (setq proced-header-line (concat " " proced-header-line))
1614 (if revert (set-buffer-modified-p nil))
1615
1616 ;; set `goal-column'
1617 (let ((grammar (assq proced-goal-attribute proced-grammar-alist)))
1618 (setq goal-column ;; set to nil if no match
1619 (if (and grammar
1620 (not (zerop (buffer-size)))
1621 (string-match (regexp-quote (nth 1 grammar))
1622 proced-header-line))
1623 (if (nth 3 grammar)
1624 (match-beginning 0)
1625 (match-end 0)))))
1626
1627 ;; Restore process marks and buffer position (if possible).
1628 ;; Sometimes this puts point in the middle of the proced buffer
1629 ;; where it is not interesting. Is there a better / more flexible solution?
1630 (goto-char (point-min))
1631 (let (pid mark new-pos)
1632 (if (or mp-list (car old-pos))
1633 (while (not (eobp))
1634 (setq pid (proced-pid-at-point))
1635 (when (setq mark (assq pid mp-list))
1636 (insert (cdr mark))
1637 (delete-char 1)
1638 (beginning-of-line))
1639 (when (eq (car old-pos) pid)
1640 (if (nth 1 old-pos)
1641 (let ((limit (line-end-position)) pos)
1642 (while (and (not new-pos)
1643 (setq pos (next-property-change (point) nil limit)))
1644 (goto-char pos)
1645 (when (eq (nth 1 old-pos)
1646 (get-text-property (point) 'proced-key))
1647 (forward-char (min (nth 2 old-pos)
1648 (- (next-property-change (point))
1649 (point))))
1650 (setq new-pos (point))))
1651 (unless new-pos
1652 ;; we found the process, but the field of point
1653 ;; is not listed anymore
1654 (setq new-pos (proced-move-to-goal-column))))
1655 (setq new-pos (min (+ (line-beginning-position) (nth 2 old-pos))
1656 (line-end-position)))))
1657 (forward-line)))
1658 (if new-pos
1659 (goto-char new-pos)
1660 (goto-char (point-min))
1661 (proced-move-to-goal-column)))
1662 ;; update mode line
1663 ;; Does the long `mode-name' clutter the mode line? It would be nice
1664 ;; to have some other location for displaying the values of the various
1665 ;; flags that affect the behavior of proced (flags one might want
1666 ;; to change on the fly). Where??
1667 (setq mode-name
1668 (concat "Proced"
1669 (if proced-filter
1670 (concat ": " (symbol-name proced-filter))
1671 "")
1672 (if proced-sort
1673 (let* ((key (if (consp proced-sort) (car proced-sort)
1674 proced-sort))
1675 (grammar (assq key proced-grammar-alist)))
1676 (concat " by " (if proced-descend "-" "+")
1677 (nth 1 grammar)))
1678 "")))
1679 (force-mode-line-update)
1680 ;; run `proced-post-display-hook' only for a displayed buffer.
1681 (if (get-buffer-window) (run-hooks 'proced-post-display-hook))
1682 ;; done
1683 (or quiet (input-pending-p)
1684 (message (if revert "Updating process information...done."
1685 "Updating process display...done.")))))
1686
1687 (defun proced-revert (&rest _args)
1688 "Reevaluate the process listing based on the currently running processes.
1689 Preserves point and marks."
1690 (proced-update t))
1691
1692 (defun proced-marked-processes ()
1693 "Return marked processes as alist of PIDs.
1694 If no process is marked return alist with the PID of the process point is on.
1695 The cdrs of the alist are the text strings displayed by Proced for these
1696 processes. They are used for error messages."
1697 (let ((regexp (proced-marker-regexp))
1698 process-alist)
1699 ;; collect marked processes
1700 (save-excursion
1701 (goto-char (point-min))
1702 (while (re-search-forward regexp nil t)
1703 (push (cons (proced-pid-at-point)
1704 ;; How much info should we collect here?
1705 (buffer-substring-no-properties
1706 (+ 2 (line-beginning-position))
1707 (line-end-position)))
1708 process-alist)))
1709 (if process-alist
1710 (nreverse process-alist)
1711 ;; take current process
1712 (let ((pid (proced-pid-at-point)))
1713 (if pid
1714 (list (cons pid
1715 (buffer-substring-no-properties
1716 (+ 2 (line-beginning-position))
1717 (line-end-position)))))))))
1718
1719 (defmacro proced-with-processes-buffer (process-alist &rest body)
1720 "Execute the forms in BODY in a temporary buffer displaying PROCESS-ALIST.
1721 PROCESS-ALIST is an alist of process PIDs as in `proced-process-alist'.
1722 The value returned is the value of the last form in BODY."
1723 (declare (indent 1) (debug t))
1724 ;; Use leading space in buffer name to make this buffer ephemeral
1725 `(let ((bufname " *Marked Processes*")
1726 (header-line (substring-no-properties proced-header-line)))
1727 (with-current-buffer (get-buffer-create bufname)
1728 (setq truncate-lines t
1729 proced-header-line header-line ; inherit header line
1730 header-line-format '(:eval (proced-header-line)))
1731 (add-hook 'post-command-hook 'force-mode-line-update nil t)
1732 (let ((inhibit-read-only t))
1733 (erase-buffer)
1734 (buffer-disable-undo)
1735 (setq buffer-read-only t)
1736 (dolist (process ,process-alist)
1737 (insert " " (cdr process) "\n"))
1738 (delete-char -1)
1739 (goto-char (point-min)))
1740 (save-window-excursion
1741 ;; Analogous to `dired-pop-to-buffer'
1742 ;; Don't split window horizontally. (Bug#1806)
1743 (let (split-width-threshold)
1744 (pop-to-buffer (current-buffer)))
1745 (fit-window-to-buffer (get-buffer-window) nil 1)
1746 ,@body))))
1747
1748 (defun proced-send-signal (&optional signal process-alist)
1749 "Send a SIGNAL to processes in PROCESS-ALIST.
1750 PROCESS-ALIST is an alist as returned by `proced-marked-processes'.
1751 Interactively, PROCESS-ALIST contains the marked processes.
1752 If no process is marked, it contains the process point is on,
1753 SIGNAL may be a string (HUP, INT, TERM, etc.) or a number.
1754 After sending SIGNAL to all processes in PROCESS-ALIST, this command
1755 runs the normal hook `proced-after-send-signal-hook'.
1756
1757 For backward compatibility SIGNAL and PROCESS-ALIST may be nil.
1758 Then PROCESS-ALIST contains the marked processes or the process point is on
1759 and SIGNAL is queried interactively. This noninteractive usage is still
1760 supported but discouraged. It will be removed in a future version of Emacs."
1761 (interactive
1762 (let* ((process-alist (proced-marked-processes))
1763 (pnum (if (= 1 (length process-alist))
1764 "1 process"
1765 (format "%d processes" (length process-alist))))
1766 (completion-ignore-case t)
1767 (completion-extra-properties
1768 '(:annotation-function
1769 (lambda (s) (cdr (assoc s proced-signal-list))))))
1770 (proced-with-processes-buffer process-alist
1771 (list (completing-read (concat "Send signal [" pnum
1772 "] (default TERM): ")
1773 proced-signal-list
1774 nil nil nil nil "TERM")
1775 process-alist))))
1776
1777 (unless (and signal process-alist)
1778 ;; Discouraged usage (supported for backward compatibility):
1779 ;; The new calling sequence separates more cleanly between the parts
1780 ;; of the code required for interactive and noninteractive calls so that
1781 ;; the command can be used more flexibly in noninteractive ways, too.
1782 (unless (get 'proced-send-signal 'proced-outdated)
1783 (put 'proced-send-signal 'proced-outdated t)
1784 (message "Outdated usage of `proced-send-signal'")
1785 (sit-for 2))
1786 (setq process-alist (proced-marked-processes))
1787 (unless signal
1788 (let ((pnum (if (= 1 (length process-alist))
1789 "1 process"
1790 (format "%d processes" (length process-alist))))
1791 (completion-ignore-case t)
1792 (completion-extra-properties
1793 '(:annotation-function
1794 (lambda (s) (cdr (assoc s proced-signal-list))))))
1795 (proced-with-processes-buffer process-alist
1796 (setq signal (completing-read (concat "Send signal [" pnum
1797 "] (default TERM): ")
1798 proced-signal-list
1799 nil nil nil nil "TERM"))))))
1800
1801 (let (failures)
1802 ;; Why not always use `signal-process'? See
1803 ;; http://lists.gnu.org/archive/html/emacs-devel/2008-03/msg02955.html
1804 (if (functionp proced-signal-function)
1805 ;; use built-in `signal-process'
1806 (let ((signal (if (stringp signal)
1807 (if (string-match "\\`[0-9]+\\'" signal)
1808 (string-to-number signal)
1809 (make-symbol signal))
1810 signal))) ; number
1811 (dolist (process process-alist)
1812 (condition-case err
1813 (unless (zerop (funcall
1814 proced-signal-function (car process) signal))
1815 (proced-log "%s\n" (cdr process))
1816 (push (cdr process) failures))
1817 (error ; catch errors from failed signals
1818 (proced-log "%s\n" err)
1819 (proced-log "%s\n" (cdr process))
1820 (push (cdr process) failures)))))
1821 ;; use external system call
1822 (let ((signal (format "-%s" signal)))
1823 (dolist (process process-alist)
1824 (with-temp-buffer
1825 (condition-case nil
1826 (unless (zerop (call-process
1827 proced-signal-function nil t nil
1828 signal (number-to-string (car process))))
1829 (proced-log (current-buffer))
1830 (proced-log "%s\n" (cdr process))
1831 (push (cdr process) failures))
1832 (error ; catch errors from failed signals
1833 (proced-log (current-buffer))
1834 (proced-log "%s\n" (cdr process))
1835 (push (cdr process) failures)))))))
1836 (if failures
1837 ;; Proced error message are not always very precise.
1838 ;; Can we issue a useful one-line summary in the
1839 ;; message area (using FAILURES) if only one signal failed?
1840 (proced-log-summary
1841 (format "Signal %s" signal)
1842 (format "%d of %d signal%s failed"
1843 (length failures) (length process-alist)
1844 (if (= 1 (length process-alist)) "" "s")))
1845 (proced-success-message "Sent signal to" (length process-alist))))
1846 ;; final clean-up
1847 (run-hooks 'proced-after-send-signal-hook))
1848
1849 (defun proced-renice (priority process-alist)
1850 "Renice the processes in PROCESS-ALIST to PRIORITY.
1851 PROCESS-ALIST is an alist as returned by `proced-marked-processes'.
1852 Interactively, PROCESS-ALIST contains the marked processes.
1853 If no process is marked, it contains the process point is on,
1854 After renicing all processes in PROCESS-ALIST, this command runs
1855 the normal hook `proced-after-send-signal-hook'."
1856 (interactive
1857 (let ((process-alist (proced-marked-processes)))
1858 (proced-with-processes-buffer process-alist
1859 (list (read-number "New priority: ")
1860 process-alist))))
1861 (if (numberp priority)
1862 (setq priority (number-to-string priority)))
1863 (let (failures)
1864 (dolist (process process-alist)
1865 (with-temp-buffer
1866 (condition-case nil
1867 (unless (zerop (call-process
1868 proced-renice-command nil t nil
1869 priority (number-to-string (car process))))
1870 (proced-log (current-buffer))
1871 (proced-log "%s\n" (cdr process))
1872 (push (cdr process) failures))
1873 (error ; catch errors from failed renice
1874 (proced-log (current-buffer))
1875 (proced-log "%s\n" (cdr process))
1876 (push (cdr process) failures)))))
1877 (if failures
1878 (proced-log-summary
1879 (format "Renice %s" priority)
1880 (format "%d of %d renice%s failed"
1881 (length failures) (length process-alist)
1882 (if (= 1 (length process-alist)) "" "s")))
1883 (proced-success-message "Reniced" (length process-alist))))
1884 ;; final clean-up
1885 (run-hooks 'proced-after-send-signal-hook))
1886
1887 ;; similar to `dired-why'
1888 (defun proced-why ()
1889 "Pop up a buffer with error log output from Proced.
1890 A group of errors from a single command ends with a formfeed.
1891 Thus, use \\[backward-page] to find the beginning of a group of errors."
1892 (interactive)
1893 (if (get-buffer proced-log-buffer)
1894 (save-selected-window
1895 ;; move `proced-log-buffer' to the front of the buffer list
1896 (select-window (display-buffer (get-buffer proced-log-buffer)))
1897 (setq truncate-lines t)
1898 (set-buffer-modified-p nil)
1899 (setq buffer-read-only t)
1900 (goto-char (point-max))
1901 (forward-line -1)
1902 (backward-page 1)
1903 (recenter 0))))
1904
1905 ;; similar to `dired-log'
1906 (defun proced-log (log &rest args)
1907 "Log a message or the contents of a buffer.
1908 If LOG is a string and there are more args, it is formatted with
1909 those ARGS. Usually the LOG string ends with a \\n.
1910 End each bunch of errors with (proced-log t signal):
1911 this inserts the current time, buffer and signal at the start of the page,
1912 and \f (formfeed) at the end."
1913 (let ((obuf (current-buffer)))
1914 (with-current-buffer (get-buffer-create proced-log-buffer)
1915 (goto-char (point-max))
1916 (let (buffer-read-only)
1917 (cond ((stringp log)
1918 (insert (if args
1919 (apply #'format-message log args)
1920 log)))
1921 ((bufferp log)
1922 (insert-buffer-substring log))
1923 ((eq t log)
1924 (backward-page 1)
1925 (unless (bolp)
1926 (insert "\n"))
1927 (insert (current-time-string)
1928 (format-message "\tBuffer `%s', signal `%s'\n"
1929 (buffer-name obuf) (car args)))
1930 (goto-char (point-max))
1931 (insert "\f\n")))))))
1932
1933 ;; similar to `dired-log-summary'
1934 (defun proced-log-summary (signal string)
1935 "State a summary of SIGNAL's failures, in echo area and log buffer.
1936 STRING is an overall summary of the failures."
1937 (message "Signal %s: %s--type ? for details" signal string)
1938 ;; Log a summary describing a bunch of errors.
1939 (proced-log (concat "\n" string "\n"))
1940 (proced-log t signal))
1941
1942 (defun proced-help ()
1943 "Provide help for the Proced user."
1944 (interactive)
1945 (proced-why)
1946 (if (eq last-command 'proced-help)
1947 (describe-mode)
1948 (message proced-help-string)))
1949
1950 (defun proced-undo ()
1951 "Undo in a Proced buffer.
1952 This doesn't recover killed processes, it just undoes changes in the Proced
1953 buffer. You can use it to recover marks."
1954 (interactive)
1955 (let (buffer-read-only)
1956 (undo))
1957 (message "Change in Proced buffer undone.
1958 Killed processes cannot be recovered by Emacs."))
1959
1960 (provide 'proced)
1961
1962 ;;; proced.el ends here