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