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