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