* configure.ac: Fix minimum Jansson version requirement.
[emacs.git] / lisp / proced.el
blobb4bdbb05f0d729fe541a7e7cbb3abd6867023680
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 <https://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 " "
606 'display
607 (list 'space :align-to
608 (line-number-display-width 'columns)))
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))))))
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))))
622 ;; proced mode
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.
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.
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.
644 Type \\[proced-toggle-tree] to toggle whether the listing is
645 displayed as process tree.
647 Type \\[proced-toggle-auto-update] to automatically update the
648 process list. The time interval for updates can be configured
649 via `proced-auto-update-interval'.
651 An existing Proced listing can be refined by typing \\[proced-refine].
652 Refining an existing listing does not update the variable `proced-filter'.
654 The attribute-specific rules for formatting, filtering, sorting, and refining
655 are defined in `proced-grammar-alist'.
657 After displaying or updating a Proced buffer, Proced runs the normal hook
658 `proced-post-display-hook'.
660 \\{proced-mode-map}"
661 (abbrev-mode 0)
662 (auto-fill-mode 0)
663 (setq buffer-read-only t
664 truncate-lines t
665 header-line-format '(:eval (proced-header-line)))
666 (add-hook 'post-command-hook 'force-mode-line-update nil t)
667 (set (make-local-variable 'revert-buffer-function) 'proced-revert)
668 (set (make-local-variable 'font-lock-defaults)
669 '(proced-font-lock-keywords t nil nil beginning-of-line))
670 (if (and (not proced-auto-update-timer) proced-auto-update-interval)
671 (setq proced-auto-update-timer
672 (run-at-time t proced-auto-update-interval
673 'proced-auto-update-timer))))
675 ;;;###autoload
676 (defun proced (&optional arg)
677 "Generate a listing of UNIX system processes.
678 \\<proced-mode-map>
679 If invoked with optional ARG, do not select the window displaying
680 the process information.
682 This function runs the normal hook `proced-post-display-hook'.
684 See `proced-mode' for a description of features available in
685 Proced buffers."
686 (interactive "P")
687 (unless proced-available
688 (error "Proced is not available on this system"))
689 (let ((buffer (get-buffer-create "*Proced*")) new)
690 (set-buffer buffer)
691 (setq new (zerop (buffer-size)))
692 (when new
693 (proced-mode)
694 ;; `proced-update' runs `proced-post-display-hook' only if the
695 ;; Proced buffer has been selected. Yet the following call of
696 ;; `proced-update' is for an empty Proced buffer that has not
697 ;; yet been selected. Therefore we need to call
698 ;; `proced-post-display-hook' below.
699 (proced-update t))
700 (if arg
701 (progn
702 (display-buffer buffer)
703 (with-current-buffer buffer
704 (proced-update t)))
705 (pop-to-buffer buffer)
706 (proced-update t)
707 (message
708 (substitute-command-keys
709 "Type \\<proced-mode-map>\\[quit-window] to quit, \\[proced-help] for help")))))
711 (defun proced-auto-update-timer ()
712 "Auto-update Proced buffers using `run-at-time'."
713 (dolist (buf (buffer-list))
714 (with-current-buffer buf
715 (if (and (eq major-mode 'proced-mode)
716 proced-auto-update-flag)
717 (proced-update t t)))))
719 (defun proced-toggle-auto-update (arg)
720 "Change whether this Proced buffer is updated automatically.
721 With prefix ARG, update this buffer automatically if ARG is positive,
722 otherwise do not update. Sets the variable `proced-auto-update-flag'.
723 The time interval for updates is specified via `proced-auto-update-interval'."
724 (interactive (list (or current-prefix-arg 'toggle)))
725 (setq proced-auto-update-flag
726 (cond ((eq arg 'toggle) (not proced-auto-update-flag))
727 (arg (> (prefix-numeric-value arg) 0))
728 (t (not proced-auto-update-flag))))
729 (message "Proced auto update %s"
730 (if proced-auto-update-flag "enabled" "disabled")))
732 ;;; Mark
734 (defun proced-mark (&optional count)
735 "Mark the current (or next COUNT) processes."
736 (interactive "p")
737 (proced-do-mark t count))
739 (defun proced-unmark (&optional count)
740 "Unmark the current (or next COUNT) processes."
741 (interactive "p")
742 (proced-do-mark nil count))
744 (defun proced-unmark-backward (&optional count)
745 "Unmark the previous (or COUNT previous) processes."
746 ;; Analogous to `dired-unmark-backward',
747 ;; but `ibuffer-unmark-backward' behaves different.
748 (interactive "p")
749 (proced-do-mark nil (- (or count 1))))
751 (defun proced-do-mark (mark &optional count)
752 "Mark the current (or next COUNT) processes using MARK."
753 (or count (setq count 1))
754 (let ((backward (< count 0))
755 buffer-read-only)
756 (setq count (1+ (if (<= 0 count) count
757 (min (1- (line-number-at-pos)) (abs count)))))
758 (beginning-of-line)
759 (while (not (or (zerop (setq count (1- count))) (eobp)))
760 (proced-insert-mark mark backward))
761 (proced-move-to-goal-column)))
763 (defun proced-toggle-marks ()
764 "Toggle marks: marked processes become unmarked, and vice versa."
765 (interactive)
766 (let ((mark-re (proced-marker-regexp))
767 buffer-read-only)
768 (save-excursion
769 (goto-char (point-min))
770 (while (not (eobp))
771 (cond ((looking-at mark-re)
772 (proced-insert-mark nil))
773 ((= (following-char) ?\s)
774 (proced-insert-mark t))
776 (forward-line 1)))))))
778 (defun proced-insert-mark (mark &optional backward)
779 "If MARK is non-nil, insert `proced-marker-char'.
780 If BACKWARD is non-nil, move one line backwards before inserting the mark.
781 Otherwise move one line forward after inserting the mark."
782 (if backward (forward-line -1))
783 (insert (if mark proced-marker-char ?\s))
784 (delete-char 1)
785 (unless backward (forward-line)))
787 (defun proced-mark-all ()
788 "Mark all processes.
789 If `transient-mark-mode' is turned on and the region is active,
790 mark the region."
791 (interactive)
792 (proced-do-mark-all t))
794 (defun proced-unmark-all ()
795 "Unmark all processes.
796 If `transient-mark-mode' is turned on and the region is active,
797 unmark the region."
798 (interactive)
799 (proced-do-mark-all nil))
801 (defun proced-do-mark-all (mark)
802 "Mark all processes using MARK.
803 If `transient-mark-mode' is turned on and the region is active,
804 mark the region."
805 (let* ((count 0)
806 (proced-marker-char (if mark proced-marker-char ?\s))
807 (marker-re (proced-marker-regexp))
808 end buffer-read-only)
809 (save-excursion
810 (if (use-region-p)
811 ;; Operate even on those lines that are only partially a part
812 ;; of region. This appears most consistent with
813 ;; `proced-move-to-goal-column'.
814 (progn (setq end (save-excursion
815 (goto-char (region-end))
816 (unless (looking-at "^") (forward-line))
817 (point)))
818 (goto-char (region-beginning))
819 (unless (looking-at "^") (beginning-of-line)))
820 (goto-char (point-min))
821 (setq end (point-max)))
822 (while (< (point) end)
823 (unless (looking-at marker-re)
824 (setq count (1+ count))
825 (insert proced-marker-char)
826 (delete-char 1))
827 (forward-line))
828 (proced-success-message (if mark "Marked" "Unmarked") count))))
830 (defun proced-mark-children (ppid &optional omit-ppid)
831 "Mark child processes of process PPID.
832 Also mark process PPID unless prefix OMIT-PPID is non-nil."
833 (interactive (list (proced-pid-at-point) current-prefix-arg))
834 (proced-mark-process-alist
835 (proced-filter-children proced-process-alist ppid omit-ppid)))
837 (defun proced-mark-parents (cpid &optional omit-cpid)
838 "Mark parent processes of process CPID.
839 Also mark CPID unless prefix OMIT-CPID is non-nil."
840 (interactive (list (proced-pid-at-point) current-prefix-arg))
841 (proced-mark-process-alist
842 (proced-filter-parents proced-process-alist cpid omit-cpid)))
844 (defun proced-mark-process-alist (process-alist &optional quiet)
845 "Mark processes in PROCESS-ALIST.
846 If QUIET is non-nil suppress status message."
847 (let ((count 0))
848 (if process-alist
849 (let (buffer-read-only)
850 (save-excursion
851 (goto-char (point-min))
852 (while (not (eobp))
853 (when (assq (proced-pid-at-point) process-alist)
854 (insert proced-marker-char)
855 (delete-char 1)
856 (setq count (1+ count)))
857 (forward-line)))))
858 (unless quiet
859 (proced-success-message "Marked" count))))
861 ;; Mostly analog of `dired-do-kill-lines'.
862 ;; However, for negative args the target lines of `dired-do-kill-lines'
863 ;; include the current line, whereas `dired-mark' for negative args operates
864 ;; on the preceding lines. Here we are consistent with `dired-mark'.
865 (defun proced-omit-processes (&optional arg quiet)
866 "Omit marked processes.
867 With prefix ARG, omit that many lines starting with the current line.
868 \(A negative argument omits backward.)
869 If `transient-mark-mode' is turned on and the region is active,
870 omit the processes in region.
871 If QUIET is non-nil suppress status message.
872 Returns count of omitted lines."
873 (interactive "P")
874 (let ((mark-re (proced-marker-regexp))
875 (count 0)
876 buffer-read-only)
877 (cond ((use-region-p) ;; Omit active region
878 (let ((lines (count-lines (region-beginning) (region-end))))
879 (save-excursion
880 (goto-char (region-beginning))
881 (while (< count lines)
882 (proced-omit-process)
883 (setq count (1+ count))))))
884 ((not arg) ;; Omit marked lines
885 (save-excursion
886 (goto-char (point-min))
887 (while (and (not (eobp))
888 (re-search-forward mark-re nil t))
889 (proced-omit-process)
890 (setq count (1+ count)))))
891 ((< 0 arg) ;; Omit forward
892 (while (and (not (eobp)) (< count arg))
893 (proced-omit-process)
894 (setq count (1+ count))))
895 ((< arg 0) ;; Omit backward
896 (while (and (not (bobp)) (< count (- arg)))
897 (forward-line -1)
898 (proced-omit-process)
899 (setq count (1+ count)))))
900 (unless (zerop count) (proced-move-to-goal-column))
901 (unless quiet (proced-success-message "Omitted" count))
902 count))
904 (defun proced-omit-process ()
905 "Omit process from listing point is on.
906 Update `proced-process-alist' accordingly."
907 (setq proced-process-alist
908 (assq-delete-all (proced-pid-at-point) proced-process-alist))
909 (delete-region (line-beginning-position)
910 (save-excursion (forward-line) (point))))
912 ;;; Filtering
914 (defun proced-filter (process-alist filter-list)
915 "Apply FILTER-LIST to PROCESS-ALIST.
916 Return the filtered process list."
917 (if (symbolp filter-list)
918 (setq filter-list (cdr (assq filter-list proced-filter-alist))))
919 (dolist (filter filter-list)
920 (let (new-alist)
921 (cond ( ;; apply function to entire process list
922 (eq (car filter) 'fun-all)
923 (setq new-alist (funcall (cdr filter) process-alist)))
924 ( ;; apply predicate to each list of attributes
925 (eq (car filter) 'function)
926 (dolist (process process-alist)
927 (if (funcall (car filter) (cdr process))
928 (push process new-alist))))
929 (t ;; apply predicate to specified attribute
930 (let ((fun (if (stringp (cdr filter))
931 `(lambda (val)
932 (string-match ,(cdr filter) val))
933 (cdr filter)))
934 value)
935 (dolist (process process-alist)
936 (setq value (cdr (assq (car filter) (cdr process))))
937 (if (and value (funcall fun value))
938 (push process new-alist))))))
939 (setq process-alist new-alist)))
940 process-alist)
942 (defun proced-filter-interactive (scheme)
943 "Filter Proced buffer using SCHEME.
944 When called interactively, an empty string means nil, i.e., no filtering.
945 Set variable `proced-filter' to SCHEME. Revert listing."
946 (interactive
947 (let ((scheme (completing-read "Filter: "
948 proced-filter-alist nil t)))
949 (list (if (string= "" scheme) nil (intern scheme)))))
950 ;; only update if necessary
951 (unless (eq proced-filter scheme)
952 (setq proced-filter scheme)
953 (proced-update t)))
955 (defun proced-filter-parents (process-alist pid &optional omit-pid)
956 "For PROCESS-ALIST return list of parent processes of PID.
957 This list includes PID unless OMIT-PID is non-nil."
958 (let ((parent-list (unless omit-pid (list (assq pid process-alist))))
959 (process (assq pid process-alist))
960 ppid)
961 (while (and (setq ppid (cdr (assq 'ppid (cdr process))))
962 ;; Ignore a PPID that equals PID.
963 (/= ppid pid)
964 ;; Accept only PPIDs that correspond to members in PROCESS-ALIST.
965 (setq process (assq ppid process-alist)))
966 (setq pid ppid)
967 (push process parent-list))
968 parent-list))
970 (defun proced-filter-children (process-alist ppid &optional omit-ppid)
971 "For PROCESS-ALIST return list of child processes of PPID.
972 This list includes PPID unless OMIT-PPID is non-nil."
973 (let ((proced-temp-alist (proced-children-alist process-alist))
974 new-alist)
975 (dolist (pid (proced-children-pids ppid))
976 (push (assq pid process-alist) new-alist))
977 (if omit-ppid
978 (assq-delete-all ppid new-alist)
979 new-alist)))
981 ;;; Process tree
983 (defun proced-children-alist (process-alist)
984 "Return children alist for PROCESS-ALIST.
985 The children alist has elements (PPID PID1 PID2 ...).
986 PPID is a parent PID. PID1, PID2, ... are the child processes of PPID.
987 The children alist inherits the sorting order of PROCESS-ALIST.
988 The list of children does not include grandchildren."
989 ;; The PPIDs inherit the sorting order of PROCESS-ALIST.
990 (let ((process-tree (mapcar (lambda (a) (list (car a))) process-alist))
991 ppid)
992 (dolist (process process-alist)
993 (setq ppid (cdr (assq 'ppid (cdr process))))
994 (if (and ppid
995 ;; Ignore a PPID that equals PID.
996 (/= ppid (car process))
997 ;; Accept only PPIDs that correspond to members in PROCESS-ALIST.
998 (assq ppid process-alist))
999 (let ((temp-alist process-tree) elt)
1000 (while (setq elt (pop temp-alist))
1001 (when (eq ppid (car elt))
1002 (setq temp-alist nil)
1003 (setcdr elt (cons (car process) (cdr elt))))))))
1004 ;; The child processes inherit the sorting order of PROCESS-ALIST.
1005 (setq process-tree
1006 (mapcar (lambda (a) (cons (car a) (nreverse (cdr a))))
1007 process-tree))))
1009 (defun proced-children-pids (ppid)
1010 "Return list of children PIDs of PPID (including PPID)."
1011 (let ((cpids (cdr (assq ppid proced-temp-alist))))
1012 (if cpids
1013 (cons ppid (apply 'append (mapcar 'proced-children-pids cpids)))
1014 (list ppid))))
1016 (defun proced-process-tree (process-alist)
1017 "Return process tree for PROCESS-ALIST.
1018 It is an alist of alists where the car of each alist is a parent process
1019 and the cdr is a list of child processes according to the ppid attribute
1020 of these processes.
1021 The process tree inherits the sorting order of PROCESS-ALIST."
1022 (let ((proced-temp-alist (proced-children-alist process-alist))
1023 pid-alist proced-process-tree)
1024 (while (setq pid-alist (pop proced-temp-alist))
1025 (push (proced-process-tree-internal pid-alist) proced-process-tree))
1026 (nreverse proced-process-tree)))
1028 (defun proced-process-tree-internal (pid-alist)
1029 "Helper function for `proced-process-tree'."
1030 (let ((cpid-list (cdr pid-alist)) cpid-alist cpid)
1031 (while (setq cpid (car cpid-list))
1032 (if (setq cpid-alist (assq cpid proced-temp-alist))
1033 ;; Unprocessed part of process tree that needs to be
1034 ;; analyzed recursively.
1035 (progn
1036 (setq proced-temp-alist
1037 (assq-delete-all cpid proced-temp-alist))
1038 (setcar cpid-list (proced-process-tree-internal cpid-alist)))
1039 ;; We already processed this subtree and take it "as is".
1040 (setcar cpid-list (assq cpid proced-process-tree))
1041 (setq proced-process-tree
1042 (assq-delete-all cpid proced-process-tree)))
1043 (pop cpid-list)))
1044 pid-alist)
1046 (defun proced-toggle-tree (arg)
1047 "Toggle the display of the process listing as process tree.
1048 With prefix ARG, display as process tree if ARG is positive, otherwise
1049 do not display as process tree. Sets the variable `proced-tree-flag'.
1051 The process tree is generated from the selected processes in the
1052 Proced buffer (that is, the processes in `proced-process-alist').
1053 All processes that do not have a parent process in this list
1054 according to their ppid attribute become the root of a process tree.
1055 Each parent process is followed by its child processes.
1056 The process tree inherits the chosen sorting order of the process listing,
1057 that is, child processes of the same parent process are sorted using
1058 the selected sorting order."
1059 (interactive (list (or current-prefix-arg 'toggle)))
1060 (setq proced-tree-flag
1061 (cond ((eq arg 'toggle) (not proced-tree-flag))
1062 (arg (> (prefix-numeric-value arg) 0))
1063 (t (not proced-tree-flag))))
1064 (proced-update)
1065 (message "Proced process tree display %s"
1066 (if proced-tree-flag "enabled" "disabled")))
1068 (defun proced-tree (process-alist)
1069 "Rearrange PROCESS-ALIST as process tree.
1070 If `proced-tree-flag' is non-nil, rearrange PROCESS-ALIST such that
1071 every processes is followed by its child processes. Each process
1072 gets a tree attribute that specifies the depth of the process in the tree.
1073 A root process is a process with no parent within PROCESS-ALIST according
1074 to its value of the ppid attribute. It has depth 0.
1076 If `proced-tree-flag' is nil, remove the tree attribute.
1077 Return the rearranged process list."
1078 (if proced-tree-flag
1079 ;; add tree attribute
1080 (let ((process-tree (proced-process-tree process-alist))
1081 (proced-tree-depth 0)
1082 (proced-temp-alist process-alist)
1083 proced-process-tree pt)
1084 (while (setq pt (pop process-tree))
1085 (proced-tree-insert pt))
1086 (nreverse proced-process-tree))
1087 ;; remove tree attribute
1088 (let ((process-alist process-alist))
1089 (while process-alist
1090 (setcar process-alist
1091 (assq-delete-all 'tree (car process-alist)))
1092 (pop process-alist)))
1093 process-alist))
1095 (defun proced-tree-insert (process-tree)
1096 "Helper function for `proced-tree'."
1097 (let ((pprocess (assq (car process-tree) proced-temp-alist)))
1098 (push (append (list (car pprocess))
1099 (list (cons 'tree proced-tree-depth))
1100 (cdr pprocess))
1101 proced-process-tree)
1102 (if (cdr process-tree)
1103 (let ((proced-tree-depth (1+ proced-tree-depth)))
1104 (mapc 'proced-tree-insert (cdr process-tree))))))
1106 ;; Refining
1108 ;; Filters are used to select the processes in a new listing.
1109 ;; Refiners are used to narrow down further (interactively) the processes
1110 ;; in an existing listing.
1112 (defun proced-refine (&optional event)
1113 "Refine Proced listing by comparing with the attribute value at point.
1114 Optional EVENT is the location of the Proced field.
1116 Refinement is controlled by the REFINER defined for each attribute ATTR
1117 in `proced-grammar-alist'.
1119 If REFINER is a list of flags and point is on a process's value of ATTR,
1120 this command compares the value of ATTR of every process with the value
1121 of ATTR of the process at the position of point.
1123 The predicate for the comparison of two ATTR values is defined
1124 in `proced-grammar-alist'. For each return value of the predicate
1125 a refine flag is defined in `proced-grammar-alist'. One can select
1126 processes for which the value of ATTR is \"less than\", \"equal\",
1127 and / or \"larger\" than ATTR of the process point is on. A process
1128 is included in the new listing if the refine flag for the corresponding
1129 return value of the predicate is non-nil.
1130 The help-echo string for `proced-refine' uses \"+\" or \"-\" to indicate
1131 the current values of these refine flags.
1133 If REFINER is a cons pair (FUNCTION . HELP-ECHO), FUNCTION is called
1134 with one argument, the PID of the process at the position of point.
1135 The function must return a list of PIDs that is used for the refined
1136 listing. HELP-ECHO is a string that is shown when mouse is over this field.
1138 This command refines an already existing process listing generated initially
1139 based on the value of the variable `proced-filter'. It does not change
1140 this variable. It does not revert the listing. If you frequently need
1141 a certain refinement, consider defining a new filter in `proced-filter-alist'."
1142 (interactive (list last-input-event))
1143 (if event (posn-set-point (event-end event)))
1144 (let ((key (get-text-property (point) 'proced-key))
1145 (pid (get-text-property (point) 'proced-pid)))
1146 (if (and key pid)
1147 (let* ((grammar (assq key proced-grammar-alist))
1148 (refiner (nth 7 grammar)))
1149 (when refiner
1150 (cond ((functionp (car refiner))
1151 (setq proced-process-alist (funcall (car refiner) pid)))
1152 ((consp refiner)
1153 (let ((predicate (nth 4 grammar))
1154 (ref (cdr (assq key (cdr (assq pid proced-process-alist)))))
1155 val new-alist)
1156 (dolist (process proced-process-alist)
1157 (setq val (funcall predicate (cdr (assq key (cdr process))) ref))
1158 (if (cond ((not val) (nth 2 refiner))
1159 ((eq val 'equal) (nth 1 refiner))
1160 (val (car refiner)))
1161 (push process new-alist)))
1162 (setq proced-process-alist new-alist))))
1163 ;; Do not revert listing.
1164 (proced-update)))
1165 (message "No refiner defined here."))))
1167 ;; Proced predicates for sorting and filtering are based on a three-valued
1168 ;; logic:
1169 ;; Predicates take two arguments P1 and P2, the corresponding attribute
1170 ;; values of two processes. Predicates should return 'equal if P1 has
1171 ;; same rank like P2. Any other non-nil value says that P1 is "less than" P2,
1172 ;; or nil if not.
1174 (defun proced-< (num1 num2)
1175 "Return t if NUM1 less than NUM2.
1176 Return `equal' if NUM1 equals NUM2. Return nil if NUM1 greater than NUM2."
1177 (if (= num1 num2)
1178 'equal
1179 (< num1 num2)))
1181 (defun proced-string-lessp (s1 s2)
1182 "Return t if string S1 is less than S2 in lexicographic order.
1183 Return `equal' if S1 and S2 have identical contents.
1184 Return nil otherwise."
1185 (if (string= s1 s2)
1186 'equal
1187 (string-lessp s1 s2)))
1189 (defun proced-time-lessp (t1 t2)
1190 "Return t if time value T1 is less than time value T2.
1191 Return `equal' if T1 equals T2. Return nil otherwise."
1192 (or (time-less-p t1 t2)
1193 (if (not (time-less-p t2 t1)) 'equal)))
1195 ;;; Sorting
1197 (defsubst proced-xor (b1 b2)
1198 "Return the logical exclusive or of args B1 and B2."
1199 (and (or b1 b2)
1200 (not (and b1 b2))))
1202 (defun proced-sort-p (p1 p2)
1203 "Predicate for sorting processes P1 and P2."
1204 (if (not (cdr proced-sort-internal))
1205 ;; only one predicate: fast scheme
1206 (let* ((sorter (car proced-sort-internal))
1207 (k1 (cdr (assq (car sorter) (cdr p1))))
1208 (k2 (cdr (assq (car sorter) (cdr p2)))))
1209 ;; if the attributes are undefined, we should really abort sorting
1210 (if (and k1 k2)
1211 (proced-xor (funcall (nth 1 sorter) k1 k2)
1212 (nth 2 sorter))))
1213 (let ((sort-list proced-sort-internal) sorter predicate k1 k2)
1214 (catch 'done
1215 (while (setq sorter (pop sort-list))
1216 (setq k1 (cdr (assq (car sorter) (cdr p1)))
1217 k2 (cdr (assq (car sorter) (cdr p2)))
1218 predicate
1219 (if (and k1 k2)
1220 (funcall (nth 1 sorter) k1 k2)))
1221 (if (not (eq predicate 'equal))
1222 (throw 'done (proced-xor predicate (nth 2 sorter)))))
1223 (eq t predicate)))))
1225 (defun proced-sort (process-alist sorter descend)
1226 "Sort PROCESS-ALIST using scheme SORTER.
1227 SORTER is a scheme like `proced-sort'.
1228 DESCEND is non-nil if the first element of SORTER is sorted
1229 in descending order.
1230 Return the sorted process list."
1231 ;; translate SORTER into a list of lists (KEY PREDICATE REVERSE)
1232 (setq proced-sort-internal
1233 (mapcar (lambda (arg)
1234 (let ((grammar (assq arg proced-grammar-alist)))
1235 (unless (nth 4 grammar)
1236 (error "Attribute %s not sortable" (car grammar)))
1237 (list arg (nth 4 grammar) (nth 5 grammar))))
1238 (cond ((listp sorter) sorter)
1239 ((and (symbolp sorter)
1240 (nth 6 (assq sorter proced-grammar-alist))))
1241 ((symbolp sorter) (list sorter))
1242 (t (error "Sorter undefined %s" sorter)))))
1243 (if proced-sort-internal
1244 (progn
1245 ;; splice DESCEND into the list
1246 (setcar proced-sort-internal
1247 (list (caar proced-sort-internal)
1248 (nth 1 (car proced-sort-internal)) descend))
1249 (sort process-alist 'proced-sort-p))
1250 process-alist))
1252 (defun proced-sort-interactive (scheme &optional arg)
1253 "Sort Proced buffer using SCHEME.
1254 When called interactively, an empty string means nil, i.e., no sorting.
1256 Prefix ARG controls sort order:
1257 - If prefix ARG is positive (negative), sort in ascending (descending) order.
1258 - If ARG is nil or `no-arg' and SCHEME is equal to the previous sorting scheme,
1259 reverse the sorting order.
1260 - If ARG is nil or `no-arg' and SCHEME differs from the previous sorting scheme,
1261 adopt the sorting order defined for SCHEME in `proced-grammar-alist'.
1263 Set variable `proced-sort' to SCHEME. The current sort scheme is displayed
1264 in the mode line, using \"+\" or \"-\" for ascending or descending order."
1265 (interactive
1266 (let* (choices
1267 (scheme (completing-read "Sort attribute: "
1268 (dolist (grammar proced-grammar-alist choices)
1269 (if (nth 4 grammar)
1270 (push (list (car grammar)) choices)))
1271 nil t)))
1272 (list (if (string= "" scheme) nil (intern scheme))
1273 ;; like 'toggle in `define-derived-mode'
1274 (or current-prefix-arg 'no-arg))))
1276 (setq proced-descend
1277 ;; If `proced-sort-interactive' is called repeatedly for the same
1278 ;; sort key, the sort order is reversed.
1279 (cond ((and (eq arg 'no-arg) (equal proced-sort scheme))
1280 (not proced-descend))
1281 ((eq arg 'no-arg)
1282 (nth 5 (assq (if (consp scheme) (car scheme) scheme)
1283 proced-grammar-alist)))
1284 (arg (< (prefix-numeric-value arg) 0))
1285 ((equal proced-sort scheme)
1286 (not proced-descend))
1287 (t (nth 5 (assq (if (consp scheme) (car scheme) scheme)
1288 proced-grammar-alist))))
1289 proced-sort scheme)
1290 (proced-update))
1292 (defun proced-sort-pcpu (&optional arg)
1293 "Sort Proced buffer by percentage CPU time (%CPU).
1294 Prefix ARG controls sort order, see `proced-sort-interactive'."
1295 (interactive (list (or current-prefix-arg 'no-arg)))
1296 (proced-sort-interactive 'pcpu arg))
1298 (defun proced-sort-pmem (&optional arg)
1299 "Sort Proced buffer by percentage memory usage (%MEM).
1300 Prefix ARG controls sort order, see `proced-sort-interactive'."
1301 (interactive (list (or current-prefix-arg 'no-arg)))
1302 (proced-sort-interactive 'pmem arg))
1304 (defun proced-sort-pid (&optional arg)
1305 "Sort Proced buffer by PID.
1306 Prefix ARG controls sort order, see `proced-sort-interactive'."
1307 (interactive (list (or current-prefix-arg 'no-arg)))
1308 (proced-sort-interactive 'pid arg))
1310 (defun proced-sort-start (&optional arg)
1311 "Sort Proced buffer by time the command started (START).
1312 Prefix ARG controls sort order, see `proced-sort-interactive'."
1313 (interactive (list (or current-prefix-arg 'no-arg)))
1314 (proced-sort-interactive 'start arg))
1316 (defun proced-sort-time (&optional arg)
1317 "Sort Proced buffer by CPU time (TIME).
1318 Prefix ARG controls sort order, see `proced-sort-interactive'."
1319 (interactive (list (or current-prefix-arg 'no-arg)))
1320 (proced-sort-interactive 'time arg))
1322 (defun proced-sort-user (&optional arg)
1323 "Sort Proced buffer by USER.
1324 Prefix ARG controls sort order, see `proced-sort-interactive'."
1325 (interactive (list (or current-prefix-arg 'no-arg)))
1326 (proced-sort-interactive 'user arg))
1328 (defun proced-sort-header (event &optional arg)
1329 "Sort Proced listing based on an attribute.
1330 EVENT is a mouse event with starting position in the header line.
1331 It is converted to the corresponding attribute key.
1332 This command updates the variable `proced-sort'.
1333 Prefix ARG controls sort order, see `proced-sort-interactive'."
1334 (interactive (list last-input-event (or last-prefix-arg 'no-arg)))
1335 (let ((start (event-start event))
1336 col key)
1337 (save-selected-window
1338 (select-window (posn-window start))
1339 (setq col (+ (1- (car (posn-actual-col-row start)))
1340 (window-hscroll)))
1341 (when (and (<= 0 col) (< col (length proced-header-line)))
1342 (setq key (get-text-property col 'proced-key proced-header-line))
1343 (if key
1344 (proced-sort-interactive key arg)
1345 (message "No sorter defined here."))))))
1347 ;;; Formatting
1349 (defun proced-format-time (time)
1350 "Format time interval TIME."
1351 (let* ((ftime (float-time time))
1352 (days (truncate ftime 86400))
1353 (ftime (mod ftime 86400))
1354 (hours (truncate ftime 3600))
1355 (ftime (mod ftime 3600))
1356 (minutes (truncate ftime 60))
1357 (seconds (mod ftime 60)))
1358 (cond ((< 0 days)
1359 (format "%d-%02d:%02d:%02d" days hours minutes seconds))
1360 ((< 0 hours)
1361 (format "%02d:%02d:%02d" hours minutes seconds))
1363 (format "%02d:%02d" minutes seconds)))))
1365 (defun proced-format-start (start)
1366 "Format time START.
1367 The return string is always 6 characters wide."
1368 (let ((d-start (decode-time start))
1369 (d-current (decode-time)))
1370 (cond ( ;; process started in previous years
1371 (< (nth 5 d-start) (nth 5 d-current))
1372 (format-time-string " %Y" start))
1373 ;; process started today
1374 ((and (= (nth 3 d-start) (nth 3 d-current))
1375 (= (nth 4 d-start) (nth 4 d-current)))
1376 (format-time-string " %H:%M" start))
1377 (t ;; process started this year
1378 (format-time-string "%b %e" start)))))
1380 (defun proced-format-ttname (ttname)
1381 "Format attribute TTNAME, omitting path \"/dev/\"."
1382 ;; Does this work for all systems?
1383 (substring ttname (if (string-match "\\`/dev/" ttname)
1384 (match-end 0) 0)))
1386 (defun proced-format-tree (tree)
1387 "Format attribute TREE."
1388 (concat (make-string tree ?\s) (number-to-string tree)))
1390 ;; Proced assumes that every process occupies only one line in the listing.
1391 (defun proced-format-args (args)
1392 "Format attribute ARGS.
1393 Replace newline characters by \"^J\" (two characters)."
1394 (replace-regexp-in-string "\n" "^J" args))
1396 (defun proced-format (process-alist format)
1397 "Display PROCESS-ALIST using FORMAT."
1398 (if (symbolp format)
1399 (setq format (cdr (assq format proced-format-alist))))
1401 ;; Not all systems give us all attributes. We take `emacs-pid' as a
1402 ;; representative process PID. If FORMAT contains a list of alternative
1403 ;; attributes, we take the first attribute that is non-nil for `emacs-pid'.
1404 ;; If none of the alternatives is non-nil, the attribute is ignored
1405 ;; in the listing.
1406 (let ((standard-attributes
1407 (car (proced-process-attributes (list (emacs-pid)))))
1408 new-format fmi)
1409 (if (and proced-tree-flag
1410 (assq 'ppid standard-attributes))
1411 (push (cons 'tree 0) standard-attributes))
1412 (dolist (fmt format)
1413 (if (symbolp fmt)
1414 (if (assq fmt standard-attributes)
1415 (push fmt new-format))
1416 (while (setq fmi (pop fmt))
1417 (when (assq fmi standard-attributes)
1418 (push fmi new-format)
1419 (setq fmt nil)))))
1420 (setq format (nreverse new-format)))
1422 (insert (make-string (length process-alist) ?\n))
1423 (let ((whitespace " ") (unknown "?")
1424 (sort-key (if (consp proced-sort) (car proced-sort) proced-sort))
1425 header-list grammar)
1426 ;; Loop over all attributes
1427 (while (setq grammar (assq (pop format) proced-grammar-alist))
1428 (let* ((key (car grammar))
1429 (fun (cond ((stringp (nth 2 grammar))
1430 `(lambda (arg) (format ,(nth 2 grammar) arg)))
1431 ((not (nth 2 grammar)) 'identity)
1432 ( t (nth 2 grammar))))
1433 (whitespace (if format whitespace ""))
1434 ;; Text properties:
1435 ;; We use the text property `proced-key' to store in each
1436 ;; field the corresponding key.
1437 ;; Of course, the sort predicate appearing in help-echo
1438 ;; is only part of the story. But it gives the main idea.
1439 (hprops
1440 (if (nth 4 grammar)
1441 (let ((descend (if (eq key sort-key) proced-descend (nth 5 grammar))))
1442 `(proced-key ,key mouse-face header-line-highlight
1443 help-echo ,(format proced-header-help-echo
1444 (if descend "-" "+")
1445 (nth 1 grammar)
1446 (if descend "descending" "ascending"))))))
1447 (refiner (nth 7 grammar))
1448 (fprops
1449 (cond ((functionp (car refiner))
1450 `(proced-key ,key mouse-face highlight
1451 help-echo ,(format "mouse-2, RET: %s"
1452 (nth 1 refiner))))
1453 ((consp refiner)
1454 `(proced-key ,key mouse-face highlight
1455 help-echo ,(format "mouse-2, RET: refine by attribute %s %s"
1456 (nth 1 grammar)
1457 (mapconcat (lambda (s)
1458 (if s "+" "-"))
1459 refiner ""))))))
1460 value)
1462 ;; highlight the header of the sort column
1463 (if (eq key sort-key)
1464 (setq hprops (append '(face proced-sort-header) hprops)))
1465 (goto-char (point-min))
1466 (cond ( ;; fixed width of output field
1467 (numberp (nth 3 grammar))
1468 (dolist (process process-alist)
1469 (end-of-line)
1470 (setq value (cdr (assq key (cdr process))))
1471 (insert (if value
1472 (apply 'propertize (funcall fun value) fprops)
1473 (format (concat "%" (number-to-string (nth 3 grammar)) "s")
1474 unknown))
1475 whitespace)
1476 (forward-line))
1477 (push (format (concat "%" (number-to-string (nth 3 grammar)) "s")
1478 (apply 'propertize (nth 1 grammar) hprops))
1479 header-list))
1481 ( ;; last field left-justified
1482 (and (not format) (eq 'left (nth 3 grammar)))
1483 (dolist (process process-alist)
1484 (end-of-line)
1485 (setq value (cdr (assq key (cdr process))))
1486 (insert (if value (apply 'propertize (funcall fun value) fprops)
1487 unknown))
1488 (forward-line))
1489 (push (apply 'propertize (nth 1 grammar) hprops) header-list))
1491 (t ;; calculated field width
1492 (let ((width (length (nth 1 grammar)))
1493 field-list value)
1494 (dolist (process process-alist)
1495 (setq value (cdr (assq key (cdr process))))
1496 (if value
1497 (setq value (apply 'propertize (funcall fun value) fprops)
1498 width (max width (length value))
1499 field-list (cons value field-list))
1500 (push unknown field-list)
1501 (setq width (max width (length unknown)))))
1502 (let ((afmt (concat "%" (if (eq 'left (nth 3 grammar)) "-" "")
1503 (number-to-string width) "s")))
1504 (push (format afmt (apply 'propertize (nth 1 grammar) hprops))
1505 header-list)
1506 (dolist (value (nreverse field-list))
1507 (end-of-line)
1508 (insert (format afmt value) whitespace)
1509 (forward-line))))))))
1511 ;; final cleanup
1512 (goto-char (point-min))
1513 (dolist (process process-alist)
1514 ;; We use the text property `proced-pid' to store in each line
1515 ;; the corresponding pid
1516 (put-text-property (point) (line-end-position) 'proced-pid (car process))
1517 (forward-line))
1518 ;; Set header line
1519 (setq proced-header-line
1520 (mapconcat 'identity (nreverse header-list) whitespace))
1521 (if (string-match "[ \t]+$" proced-header-line)
1522 (setq proced-header-line (substring proced-header-line 0
1523 (match-beginning 0))))
1524 ;; (delete-trailing-whitespace)
1525 (goto-char (point-min))
1526 (while (re-search-forward "[ \t\r]+$" nil t)
1527 (delete-region (match-beginning 0) (match-end 0)))))
1529 (defun proced-format-interactive (scheme &optional revert)
1530 "Format Proced buffer using SCHEME.
1531 When called interactively, an empty string means nil, i.e., no formatting.
1532 Set variable `proced-format' to SCHEME.
1533 With prefix REVERT non-nil revert listing."
1534 (interactive
1535 (let ((scheme (completing-read "Format: "
1536 proced-format-alist nil t)))
1537 (list (if (string= "" scheme) nil (intern scheme))
1538 current-prefix-arg)))
1539 ;; only update if necessary
1540 (when (or (not (eq proced-format scheme)) revert)
1541 (setq proced-format scheme)
1542 (proced-update revert)))
1544 ;; generate listing
1546 (defun proced-process-attributes (&optional pid-list)
1547 "Return alist of attributes for each system process.
1548 This alist can be customized via `proced-custom-attributes'.
1549 Optional arg PID-LIST is a list of PIDs of system process that are analyzed.
1550 If no attributes are known for a process (possibly because it already died)
1551 the process is ignored."
1552 ;; Should we make it customizable whether processes with empty attribute
1553 ;; lists are ignored? When would such processes be of interest?
1554 (let (process-alist attributes attr)
1555 (dolist (pid (or pid-list (list-system-processes)) process-alist)
1556 (when (setq attributes (process-attributes pid))
1557 (setq attributes (cons (cons 'pid pid) attributes))
1558 (dolist (fun proced-custom-attributes)
1559 (if (setq attr (funcall fun attributes))
1560 (push attr attributes)))
1561 (push (cons pid attributes) process-alist)))))
1563 (defun proced-update (&optional revert quiet)
1564 "Update the Proced process information. Preserves point and marks.
1565 With prefix REVERT non-nil, revert listing.
1566 Suppress status information if QUIET is nil.
1567 After updating a displayed Proced buffer run the normal hook
1568 `proced-post-display-hook'."
1569 ;; This is the main function that generates and updates the process listing.
1570 (interactive "P")
1571 (setq revert (or revert (not proced-process-alist)))
1572 (or quiet (message (if revert "Updating process information..."
1573 "Updating process display...")))
1574 (if revert ;; evaluate all processes
1575 (setq proced-process-alist (proced-process-attributes)))
1576 ;; filtering and sorting
1577 (setq proced-process-alist
1578 (proced-sort (proced-filter proced-process-alist proced-filter)
1579 proced-sort proced-descend))
1581 ;; display as process tree?
1582 (setq proced-process-alist
1583 (proced-tree proced-process-alist))
1585 ;; It is useless to keep undo information if we revert, filter, or
1586 ;; refine the listing so that `proced-process-alist' has changed.
1587 ;; We could keep the undo information if we only re-sort the buffer.
1588 ;; Would that be useful? Re-re-sorting is easy, too.
1589 (if (consp buffer-undo-list)
1590 (setq buffer-undo-list nil))
1591 (let ((buffer-undo-list t)
1592 ;; If point is on a field, we try to return point to that field.
1593 ;; Otherwise we try to return to the same column
1594 (old-pos (let ((pid (proced-pid-at-point))
1595 (key (get-text-property (point) 'proced-key)))
1596 (list pid key ; can both be nil
1597 (if key
1598 (if (get-text-property (1- (point)) 'proced-key)
1599 (- (point) (previous-single-property-change
1600 (point) 'proced-key))
1602 (current-column)))))
1603 buffer-read-only mp-list)
1604 ;; remember marked processes (whatever the mark was)
1605 (goto-char (point-min))
1606 (while (re-search-forward "^\\(\\S-\\)" nil t)
1607 (push (cons (save-match-data (proced-pid-at-point))
1608 (match-string-no-properties 1)) mp-list))
1610 ;; generate listing
1611 (erase-buffer)
1612 (proced-format proced-process-alist proced-format)
1613 (goto-char (point-min))
1614 (while (not (eobp))
1615 (insert " ")
1616 (forward-line))
1617 (setq proced-header-line (concat " " proced-header-line))
1618 (if revert (set-buffer-modified-p nil))
1620 ;; set `goal-column'
1621 (let ((grammar (assq proced-goal-attribute proced-grammar-alist)))
1622 (setq goal-column ;; set to nil if no match
1623 (if (and grammar
1624 (not (zerop (buffer-size)))
1625 (string-match (regexp-quote (nth 1 grammar))
1626 proced-header-line))
1627 (if (nth 3 grammar)
1628 (match-beginning 0)
1629 (match-end 0)))))
1631 ;; Restore process marks and buffer position (if possible).
1632 ;; Sometimes this puts point in the middle of the proced buffer
1633 ;; where it is not interesting. Is there a better / more flexible solution?
1634 (goto-char (point-min))
1635 (let (pid mark new-pos)
1636 (if (or mp-list (car old-pos))
1637 (while (not (eobp))
1638 (setq pid (proced-pid-at-point))
1639 (when (setq mark (assq pid mp-list))
1640 (insert (cdr mark))
1641 (delete-char 1)
1642 (beginning-of-line))
1643 (when (eq (car old-pos) pid)
1644 (if (nth 1 old-pos)
1645 (let ((limit (line-end-position)) pos)
1646 (while (and (not new-pos)
1647 (setq pos (next-property-change (point) nil limit)))
1648 (goto-char pos)
1649 (when (eq (nth 1 old-pos)
1650 (get-text-property (point) 'proced-key))
1651 (forward-char (min (nth 2 old-pos)
1652 (- (next-property-change (point))
1653 (point))))
1654 (setq new-pos (point))))
1655 (unless new-pos
1656 ;; we found the process, but the field of point
1657 ;; is not listed anymore
1658 (setq new-pos (proced-move-to-goal-column))))
1659 (setq new-pos (min (+ (line-beginning-position) (nth 2 old-pos))
1660 (line-end-position)))))
1661 (forward-line)))
1662 (if new-pos
1663 (goto-char new-pos)
1664 (goto-char (point-min))
1665 (proced-move-to-goal-column)))
1666 ;; update mode line
1667 ;; Does the long `mode-name' clutter the mode line? It would be nice
1668 ;; to have some other location for displaying the values of the various
1669 ;; flags that affect the behavior of proced (flags one might want
1670 ;; to change on the fly). Where??
1671 (setq mode-name
1672 (concat "Proced"
1673 (if proced-filter
1674 (concat ": " (symbol-name proced-filter))
1676 (if proced-sort
1677 (let* ((key (if (consp proced-sort) (car proced-sort)
1678 proced-sort))
1679 (grammar (assq key proced-grammar-alist)))
1680 (concat " by " (if proced-descend "-" "+")
1681 (nth 1 grammar)))
1682 "")))
1683 (force-mode-line-update)
1684 ;; run `proced-post-display-hook' only for a displayed buffer.
1685 (if (get-buffer-window) (run-hooks 'proced-post-display-hook))
1686 ;; done
1687 (or quiet (input-pending-p)
1688 (message (if revert "Updating process information...done."
1689 "Updating process display...done.")))))
1691 (defun proced-revert (&rest _args)
1692 "Reevaluate the process listing based on the currently running processes.
1693 Preserves point and marks."
1694 (proced-update t))
1696 (defun proced-marked-processes ()
1697 "Return marked processes as alist of PIDs.
1698 If no process is marked return alist with the PID of the process point is on.
1699 The cdrs of the alist are the text strings displayed by Proced for these
1700 processes. They are used for error messages."
1701 (let ((regexp (proced-marker-regexp))
1702 process-alist)
1703 ;; collect marked processes
1704 (save-excursion
1705 (goto-char (point-min))
1706 (while (re-search-forward regexp nil t)
1707 (push (cons (proced-pid-at-point)
1708 ;; How much info should we collect here?
1709 (buffer-substring-no-properties
1710 (+ 2 (line-beginning-position))
1711 (line-end-position)))
1712 process-alist)))
1713 (if process-alist
1714 (nreverse process-alist)
1715 ;; take current process
1716 (let ((pid (proced-pid-at-point)))
1717 (if pid
1718 (list (cons pid
1719 (buffer-substring-no-properties
1720 (+ 2 (line-beginning-position))
1721 (line-end-position)))))))))
1723 (defmacro proced-with-processes-buffer (process-alist &rest body)
1724 "Execute the forms in BODY in a temporary buffer displaying PROCESS-ALIST.
1725 PROCESS-ALIST is an alist of process PIDs as in `proced-process-alist'.
1726 The value returned is the value of the last form in BODY."
1727 (declare (indent 1) (debug t))
1728 ;; Use leading space in buffer name to make this buffer ephemeral
1729 `(let ((bufname " *Marked Processes*")
1730 (header-line (substring-no-properties proced-header-line)))
1731 (with-current-buffer (get-buffer-create bufname)
1732 (setq truncate-lines t
1733 proced-header-line header-line ; inherit header line
1734 header-line-format '(:eval (proced-header-line)))
1735 (add-hook 'post-command-hook 'force-mode-line-update nil t)
1736 (let ((inhibit-read-only t))
1737 (erase-buffer)
1738 (buffer-disable-undo)
1739 (setq buffer-read-only t)
1740 (dolist (process ,process-alist)
1741 (insert " " (cdr process) "\n"))
1742 (delete-char -1)
1743 (goto-char (point-min)))
1744 (save-window-excursion
1745 ;; Analogous to `dired-pop-to-buffer'
1746 ;; Don't split window horizontally. (Bug#1806)
1747 (let (split-width-threshold)
1748 (pop-to-buffer (current-buffer)))
1749 (fit-window-to-buffer (get-buffer-window) nil 1)
1750 ,@body))))
1752 (defun proced-send-signal (&optional signal process-alist)
1753 "Send a SIGNAL to processes in PROCESS-ALIST.
1754 PROCESS-ALIST is an alist as returned by `proced-marked-processes'.
1755 Interactively, PROCESS-ALIST contains the marked processes.
1756 If no process is marked, it contains the process point is on,
1757 SIGNAL may be a string (HUP, INT, TERM, etc.) or a number.
1758 After sending SIGNAL to all processes in PROCESS-ALIST, this command
1759 runs the normal hook `proced-after-send-signal-hook'.
1761 For backward compatibility SIGNAL and PROCESS-ALIST may be nil.
1762 Then PROCESS-ALIST contains the marked processes or the process point is on
1763 and SIGNAL is queried interactively. This noninteractive usage is still
1764 supported but discouraged. It will be removed in a future version of Emacs."
1765 (interactive
1766 (let* ((process-alist (proced-marked-processes))
1767 (pnum (if (= 1 (length process-alist))
1768 "1 process"
1769 (format "%d processes" (length process-alist))))
1770 (completion-ignore-case t)
1771 (completion-extra-properties
1772 '(:annotation-function
1773 (lambda (s) (cdr (assoc s proced-signal-list))))))
1774 (proced-with-processes-buffer process-alist
1775 (list (completing-read (concat "Send signal [" pnum
1776 "] (default TERM): ")
1777 proced-signal-list
1778 nil nil nil nil "TERM")
1779 process-alist))))
1781 (unless (and signal process-alist)
1782 ;; Discouraged usage (supported for backward compatibility):
1783 ;; The new calling sequence separates more cleanly between the parts
1784 ;; of the code required for interactive and noninteractive calls so that
1785 ;; the command can be used more flexibly in noninteractive ways, too.
1786 (unless (get 'proced-send-signal 'proced-outdated)
1787 (put 'proced-send-signal 'proced-outdated t)
1788 (message "Outdated usage of `proced-send-signal'")
1789 (sit-for 2))
1790 (setq process-alist (proced-marked-processes))
1791 (unless signal
1792 (let ((pnum (if (= 1 (length process-alist))
1793 "1 process"
1794 (format "%d processes" (length process-alist))))
1795 (completion-ignore-case t)
1796 (completion-extra-properties
1797 '(:annotation-function
1798 (lambda (s) (cdr (assoc s proced-signal-list))))))
1799 (proced-with-processes-buffer process-alist
1800 (setq signal (completing-read (concat "Send signal [" pnum
1801 "] (default TERM): ")
1802 proced-signal-list
1803 nil nil nil nil "TERM"))))))
1805 (let (failures)
1806 ;; Why not always use `signal-process'? See
1807 ;; https://lists.gnu.org/r/emacs-devel/2008-03/msg02955.html
1808 (if (functionp proced-signal-function)
1809 ;; use built-in `signal-process'
1810 (let ((signal (if (stringp signal)
1811 (if (string-match "\\`[0-9]+\\'" signal)
1812 (string-to-number signal)
1813 (make-symbol signal))
1814 signal))) ; number
1815 (dolist (process process-alist)
1816 (condition-case err
1817 (unless (zerop (funcall
1818 proced-signal-function (car process) signal))
1819 (proced-log "%s\n" (cdr process))
1820 (push (cdr process) failures))
1821 (error ; catch errors from failed signals
1822 (proced-log "%s\n" err)
1823 (proced-log "%s\n" (cdr process))
1824 (push (cdr process) failures)))))
1825 ;; use external system call
1826 (let ((signal (format "-%s" signal)))
1827 (dolist (process process-alist)
1828 (with-temp-buffer
1829 (condition-case nil
1830 (unless (zerop (call-process
1831 proced-signal-function nil t nil
1832 signal (number-to-string (car process))))
1833 (proced-log (current-buffer))
1834 (proced-log "%s\n" (cdr process))
1835 (push (cdr process) failures))
1836 (error ; catch errors from failed signals
1837 (proced-log (current-buffer))
1838 (proced-log "%s\n" (cdr process))
1839 (push (cdr process) failures)))))))
1840 (if failures
1841 ;; Proced error message are not always very precise.
1842 ;; Can we issue a useful one-line summary in the
1843 ;; message area (using FAILURES) if only one signal failed?
1844 (proced-log-summary
1845 (format "Signal %s" signal)
1846 (format "%d of %d signal%s failed"
1847 (length failures) (length process-alist)
1848 (if (= 1 (length process-alist)) "" "s")))
1849 (proced-success-message "Sent signal to" (length process-alist))))
1850 ;; final clean-up
1851 (run-hooks 'proced-after-send-signal-hook))
1853 (defun proced-renice (priority process-alist)
1854 "Renice the processes in PROCESS-ALIST to PRIORITY.
1855 PROCESS-ALIST is an alist as returned by `proced-marked-processes'.
1856 Interactively, PROCESS-ALIST contains the marked processes.
1857 If no process is marked, it contains the process point is on,
1858 After renicing all processes in PROCESS-ALIST, this command runs
1859 the normal hook `proced-after-send-signal-hook'."
1860 (interactive
1861 (let ((process-alist (proced-marked-processes)))
1862 (proced-with-processes-buffer process-alist
1863 (list (read-number "New priority: ")
1864 process-alist))))
1865 (if (numberp priority)
1866 (setq priority (number-to-string priority)))
1867 (let (failures)
1868 (dolist (process process-alist)
1869 (with-temp-buffer
1870 (condition-case nil
1871 (unless (zerop (call-process
1872 proced-renice-command nil t nil
1873 priority (number-to-string (car process))))
1874 (proced-log (current-buffer))
1875 (proced-log "%s\n" (cdr process))
1876 (push (cdr process) failures))
1877 (error ; catch errors from failed renice
1878 (proced-log (current-buffer))
1879 (proced-log "%s\n" (cdr process))
1880 (push (cdr process) failures)))))
1881 (if failures
1882 (proced-log-summary
1883 (format "Renice %s" priority)
1884 (format "%d of %d renice%s failed"
1885 (length failures) (length process-alist)
1886 (if (= 1 (length process-alist)) "" "s")))
1887 (proced-success-message "Reniced" (length process-alist))))
1888 ;; final clean-up
1889 (run-hooks 'proced-after-send-signal-hook))
1891 ;; similar to `dired-why'
1892 (defun proced-why ()
1893 "Pop up a buffer with error log output from Proced.
1894 A group of errors from a single command ends with a formfeed.
1895 Thus, use \\[backward-page] to find the beginning of a group of errors."
1896 (interactive)
1897 (if (get-buffer proced-log-buffer)
1898 (save-selected-window
1899 ;; move `proced-log-buffer' to the front of the buffer list
1900 (select-window (display-buffer (get-buffer proced-log-buffer)))
1901 (setq truncate-lines t)
1902 (set-buffer-modified-p nil)
1903 (setq buffer-read-only t)
1904 (goto-char (point-max))
1905 (forward-line -1)
1906 (backward-page 1)
1907 (recenter 0))))
1909 ;; similar to `dired-log'
1910 (defun proced-log (log &rest args)
1911 "Log a message or the contents of a buffer.
1912 If LOG is a string and there are more args, it is formatted with
1913 those ARGS. Usually the LOG string ends with a \\n.
1914 End each bunch of errors with (proced-log t signal):
1915 this inserts the current time, buffer and signal at the start of the page,
1916 and \f (formfeed) at the end."
1917 (let ((obuf (current-buffer)))
1918 (with-current-buffer (get-buffer-create proced-log-buffer)
1919 (goto-char (point-max))
1920 (let (buffer-read-only)
1921 (cond ((stringp log)
1922 (insert (if args
1923 (apply #'format-message log args)
1924 log)))
1925 ((bufferp log)
1926 (insert-buffer-substring log))
1927 ((eq t log)
1928 (backward-page 1)
1929 (unless (bolp)
1930 (insert "\n"))
1931 (insert (current-time-string)
1932 (format-message "\tBuffer `%s', signal `%s'\n"
1933 (buffer-name obuf) (car args)))
1934 (goto-char (point-max))
1935 (insert "\f\n")))))))
1937 ;; similar to `dired-log-summary'
1938 (defun proced-log-summary (signal string)
1939 "State a summary of SIGNAL's failures, in echo area and log buffer.
1940 STRING is an overall summary of the failures."
1941 (message "Signal %s: %s--type ? for details" signal string)
1942 ;; Log a summary describing a bunch of errors.
1943 (proced-log (concat "\n" string "\n"))
1944 (proced-log t signal))
1946 (defun proced-help ()
1947 "Provide help for the Proced user."
1948 (interactive)
1949 (proced-why)
1950 (if (eq last-command 'proced-help)
1951 (describe-mode)
1952 (message proced-help-string)))
1954 (defun proced-undo ()
1955 "Undo in a Proced buffer.
1956 This doesn't recover killed processes, it just undoes changes in the Proced
1957 buffer. You can use it to recover marks."
1958 (interactive)
1959 (let (buffer-read-only)
1960 (undo))
1961 (message "Change in Proced buffer undone.
1962 Killed processes cannot be recovered by Emacs."))
1964 (provide 'proced)
1966 ;;; proced.el ends here