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