(proced-grammar-alist): Allow refiner elements that
[emacs.git] / lisp / proced.el
blob2988925c1d09d6f912a0661f08f204b9eee6b888
1 ;;; proced.el --- operate on system processes like dired
3 ;; Copyright (C) 2008 Free Software Foundation, Inc.
5 ;; Author: Roland Winkler <Roland.Winkler@physik.uni-erlangen.de>
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", "renice PID"
34 ;; Wishlist
35 ;; - tree view like pstree(1)
37 ;; Thoughts and Ideas
38 ;; - Currently, `system-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, `system-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 (require 'time-date) ; for `with-decoded-time-value'
54 (defgroup proced nil
55 "Proced mode."
56 :group 'processes
57 :group 'unix
58 :prefix "proced-")
60 (defcustom proced-signal-function 'signal-process
61 "Name of signal function.
62 It can be an elisp function (usually `signal-process') or a string specifying
63 the external command (usually \"kill\")."
64 :group 'proced
65 :type '(choice (function :tag "function")
66 (string :tag "command")))
68 (defcustom proced-signal-list
69 '( ;; signals supported on all POSIX compliant systems
70 ("HUP (1. Hangup)")
71 ("INT (2. Terminal interrupt)")
72 ("QUIT (3. Terminal quit)")
73 ("ABRT (6. Process abort)")
74 ("KILL (9. Kill - cannot be caught or ignored)")
75 ("ALRM (14. Alarm Clock)")
76 ("TERM (15. Termination)")
77 ;; POSIX 1003.1-2001
78 ;; Which systems do not support these signals so that we can
79 ;; exclude them from `proced-signal-list'?
80 ("CONT (Continue executing)")
81 ("STOP (Stop executing / pause - cannot be caught or ignored)")
82 ("TSTP (Terminal stop / pause)"))
83 "List of signals, used for minibuffer completion."
84 :group 'proced
85 :type '(repeat (string :tag "signal")))
87 ;; For which attributes can we use a fixed width of the output field?
88 ;; A fixed width speeds up formatting, yet it can make
89 ;; `proced-grammar-alist' system-dependent.
90 ;; (If proced runs like top(1) we want it to be fast.)
92 ;; If it is impossible / unlikely that an attribute has the same value
93 ;; for two processes, then sorting can be based on one ordinary (fast)
94 ;; predicate like `<'. Otherwise, a list of proced predicates can be used
95 ;; to refine the sort.
97 ;; It would be neat if one could temporarily override the following
98 ;; predefined rules.
99 (defcustom proced-grammar-alist
100 '( ;; attributes defined in `system-process-attributes'
101 (euid "EUID" "%d" right proced-< nil (euid pid) (nil t nil))
102 (user "USER" nil left proced-string-lessp nil (user pid) (nil t nil))
103 (egid "EGID" "%d" right proced-< nil (egid euid pid) (nil t nil))
104 (group "GROUP" nil left proced-string-lessp nil (group user pid) (nil t nil))
105 (comm "COMMAND" nil left proced-string-lessp nil (comm pid) (nil t nil))
106 (state "STAT" nil left proced-string-lessp nil (state pid) (nil t nil))
107 (ppid "PPID" "%d" right proced-< nil (ppid pid)
108 ((lambda (ppid) (proced-filter-parents proced-process-alist ppid)) .
109 "refine to process parents"))
110 (pgrp "PGRP" "%d" right proced-< nil (pgrp euid pid) (nil t nil))
111 (sess "SESS" "%d" right proced-< nil (sess pid) (nil t nil))
112 (ttname "TTY" proced-format-ttname left proced-string-lessp nil (ttname pid) (nil t nil))
113 (tpgid "TPGID" "%d" right proced-< nil (tpgid pid) (nil t nil))
114 (minflt "MINFLT" "%d" right proced-< nil (minflt pid) (nil t t))
115 (majflt "MAJFLT" "%d" right proced-< nil (majflt pid) (nil t t))
116 (cminflt "CMINFLT" "%d" right proced-< nil (cminflt pid) (nil t t))
117 (cmajflt "CMAJFLT" "%d" right proced-< nil (cmajflt pid) (nil t t))
118 (utime "UTIME" proced-format-time right proced-time-lessp t (utime pid) (nil t t))
119 (stime "STIME" proced-format-time right proced-time-lessp t (stime pid) (nil t t))
120 (cutime "CUTIME" proced-format-time right proced-time-lessp t (cutime pid) (nil t t))
121 (cstime "CSTIME" proced-format-time right proced-time-lessp t (cstime pid) (nil t t))
122 (pri "PR" "%d" right proced-< t (pri pid) (nil t t))
123 (nice "NI" "%3d" 3 proced-< t (nice pid) (t t nil))
124 (thcount "THCOUNT" "%d" right proced-< t (thcount pid) (nil t t))
125 (start "START" proced-format-start 6 proced-time-lessp nil (start pid) (t t nil))
126 (vsize "VSIZE" "%d" right proced-< t (vsize pid) (nil t t))
127 (rss "RSS" "%d" right proced-< t (rss pid) (nil t t))
128 (etime "ETIME" proced-format-time right proced-time-lessp t (etime pid) (nil t t))
129 (pcpu "%CPU" "%.1f" right proced-< t (pcpu pid) (nil t t))
130 (pmem "%MEM" "%.1f" right proced-< t (pmem pid) (nil t t))
131 (args "ARGS" proced-format-args left proced-string-lessp nil (args pid) (nil t nil))
133 ;; attributes defined by proced (see `proced-process-attributes')
134 (pid "PID" "%d" right proced-< nil (pid)
135 ((lambda (ppid) (proced-filter-children proced-process-alist ppid)) .
136 "refine to process children"))
137 ;; time: sum of utime and stime
138 (time "TIME" proced-format-time right proced-time-lessp t (time pid) (nil t t))
139 ;; ctime: sum of cutime and cstime
140 (ctime "CTIME" proced-format-time right proced-time-lessp t (ctime pid) (nil t t)))
141 "Alist of rules for handling Proced attributes.
143 Each element has the form
145 (KEY NAME FORMAT JUSTIFY PREDICATE REVERSE SORT-SCHEME REFINER).
147 Symbol KEY is the car of a process attribute.
149 String NAME appears in the header line.
151 FORMAT specifies the format for displaying the attribute values.
152 It can be a string passed to `format'. It can be a function called
153 with one argument, the value of the attribute. Nil means take as is.
155 If JUSTIFY is an integer, its modulus gives the width of the attribute
156 values formatted with FORMAT. If JUSTIFY is positive, NAME appears
157 right-justified, otherwise it appears left-justified. If JUSTIFY is 'left
158 or 'right, the field width is calculated from all field values in the listing.
159 If JUSTIFY is 'left, the field values are formatted left-justified and
160 right-justified otherwise.
162 PREDICATE is the predicate for sorting and filtering the process listing
163 based on attribute KEY. PREDICATE takes two arguments P1 and P2,
164 the corresponding attribute values of two processes. PREDICATE should
165 return 'equal if P1 has same rank like P2. Any other non-nil value says
166 that P1 is \"less than\" P2, or nil if not.
168 PREDICATE defines an ascending sort order. REVERSE is non-nil if the sort
169 order is descending.
171 SORT-SCHEME is a list (KEY1 KEY2 ...) defining a hierarchy of rules
172 for sorting the process listing. KEY1, KEY2, ... are KEYs appearing as cars
173 of `proced-grammar-alist'. First the PREDICATE of KEY1 is evaluated.
174 If it yields non-equal, it defines the sort order for the corresponding
175 processes. If it evaluates to 'equal the PREDICATE of KEY2 is evaluated, etc.
177 REFINER can be a list of flags (LESS-B EQUAL-B LARGER-B) used by the command
178 `proced-refine' (see there) to refine the listing based on attribute KEY.
179 This command compares the value of attribute KEY of every process with
180 the value of attribute KEY of the process at the position of point
181 using PREDICATE.
182 If PREDICATE yields non-nil, the process is accepted if LESS-B is non-nil.
183 If PREDICATE yields 'equal, the process is accepted if EQUAL-B is non-nil.
184 If PREDICATE yields nil, the process is accepted if LARGER-B is non-nil.
186 REFINER can also be a cons pair (FUNCTION . HELP-ECHO).
187 FUNCTION is called with one argument, the PID of the process at the position
188 of point. The function must return a list of PIDs that is used for the refined
189 listing. HELP-ECHO is a string that is shown when mouse is over this field.
191 If REFINER is nil no refinement is done."
192 :group 'proced
193 :type '(repeat (list :tag "Attribute"
194 (symbol :tag "Key")
195 (string :tag "Header")
196 (choice :tag "Format"
197 (const :tag "None" nil)
198 (string :tag "Format String")
199 (function :tag "Formatting Function"))
200 (choice :tag "Justification"
201 (const :tag "left" left)
202 (const :tag "right" right)
203 (integer :tag "width"))
204 (function :tag "Predicate")
205 (boolean :tag "Descending Sort Order")
206 (repeat :tag "Sort Scheme" (symbol :tag "Key"))
207 (choice :tag "Refiner"
208 (list :tag "Refine Flags"
209 (boolean :tag "Less")
210 (boolean :tag "Equal")
211 (boolean :tag "Larger"))
212 (cons (function :tag "Refinement Function")
213 (string :tag "Help echo"))
214 (const :tag "None" nil)))))
216 (defcustom proced-custom-attributes nil
217 "List of functions defining custom attributes.
218 This variable extends the functionality of `proced-process-attributes'.
219 Each function is called with one argument, the list of attributes
220 of a system process. It returns a cons cell of the form (KEY . VALUE)
221 like `system-process-attributes'. This cons cell is appended to the list
222 returned by `proced-process-attributes'.
223 If the function returns nil, the value is ignored."
224 :group 'proced
225 :type '(repeat (function :tag "Attribute")))
227 ;; Formatting and sorting rules are defined "per attribute". If formatting
228 ;; and / or sorting should use more than one attribute, it appears more
229 ;; transparent to define a new derived attribute, so that formatting and
230 ;; sorting can use them consistently. (Are there exceptions to this rule?
231 ;; Would it be advantageous to have yet more general methods available?)
232 ;; Sorting can also be based on attributes that are invisible in the listing.
234 (defcustom proced-format-alist
235 '((short user pid pcpu pmem start time (args comm))
236 (medium user pid pcpu pmem vsize rss ttname state start time (args comm))
237 (long user euid group pid pri nice pcpu pmem vsize rss ttname state
238 start time (args comm))
239 (verbose user euid group egid pid ppid pgrp sess pri nice pcpu pmem
240 state thcount vsize rss ttname tpgid minflt majflt cminflt cmajflt
241 start time utime stime ctime cutime cstime etime (args comm)))
242 "Alist of formats of listing.
243 The car of each element is a symbol, the name of the format.
244 The cdr is a list of attribute keys appearing in `proced-grammar-alist'.
245 An element of this list may also be a list of attribute keys that specifies
246 alternatives. If the first attribute is absent for a process, use the second
247 one, etc."
248 :group 'proced
249 :type '(alist :key-type (symbol :tag "Format Name")
250 :value-type (repeat :tag "Keys"
251 (choice (symbol :tag "")
252 (repeat :tag "Alternative Keys"
253 (symbol :tag ""))))))
255 (defcustom proced-format 'short
256 "Current format of Proced listing.
257 It can be the car of an element of `proced-format-alist'.
258 It can also be a list of keys appearing in `proced-grammar-alist'."
259 :group 'proced
260 :type '(choice (symbol :tag "Format Name")
261 (repeat :tag "Keys" (symbol :tag ""))))
262 (make-variable-buffer-local 'proced-format)
264 ;; FIXME: is there a better name for filter `user' that does not coincide
265 ;; with an attribute key?
266 (defcustom proced-filter-alist
267 `((user (user . ,(concat "\\`" (user-real-login-name) "\\'")))
268 (user-running (user . ,(concat "\\`" (user-real-login-name) "\\'"))
269 (state . "\\`[Rr]\\'"))
270 (all)
271 (all-running (state . "\\`[Rr]\\'"))
272 (emacs (fun-all . (lambda (list)
273 (proced-filter-children list ,(emacs-pid))))))
274 "Alist of process filters.
275 The car of each element is a symbol, the name of the filter.
276 The cdr is a list of elementary filters that are applied to every process.
277 A process is displayed if it passes all elementary filters of a selected
278 filter.
280 An elementary filter can be one of the following:
281 \(KEY . REGEXP) If value of attribute KEY matches REGEXP,
282 accept this process.
283 \(KEY . FUN) Apply function FUN to attribute KEY. Accept this process,
284 if FUN returns non-nil.
285 \(function . FUN) For each process, apply function FUN to list of attributes
286 of each. Accept the process if FUN returns non-nil.
287 \(fun-all . FUN) Apply function FUN to entire process list.
288 FUN must return the filtered list."
289 :group 'proced
290 :type '(repeat (cons :tag "Filter"
291 (symbol :tag "Filter Name")
292 (repeat :tag "Filters"
293 (choice (cons :tag "Key . Regexp" (symbol :tag "Key") regexp)
294 (cons :tag "Key . Function" (symbol :tag "Key") function)
295 (cons :tag "Function" (const :tag "Key: function" function) function)
296 (cons :tag "Fun-all" (const :tag "Key: fun-all" fun-all) function))))))
298 (defcustom proced-filter 'user
299 "Current filter of proced listing.
300 It can be the car of an element of `proced-filter-alist'.
301 It can also be a list of elementary filters as in the cdrs of the elements
302 of `proced-filter-alist'."
303 :group 'proced
304 :type '(choice (symbol :tag "Filter Name")
305 (repeat :tag "Filters"
306 (choice (cons :tag "Key . Regexp" (symbol :tag "Key") regexp)
307 (cons :tag "Key . Function" (symbol :tag "Key") function)
308 (cons :tag "Function" (const :tag "Key: function" function) function)
309 (cons :tag "Fun-all" (const :tag "Key: fun-all" fun-all) function)))))
310 (make-variable-buffer-local 'proced-filter)
312 (defcustom proced-sort 'pcpu
313 "Current sort scheme for proced listing.
314 It must be the KEY of an element of `proced-grammar-alist'.
315 It can also be a list of KEYs as in the SORT-SCHEMEs of the elements
316 of `proced-grammar-alist'."
317 :group 'proced
318 :type '(choice (symbol :tag "Sort Scheme")
319 (repeat :tag "Key List" (symbol :tag "Key"))))
320 (make-variable-buffer-local 'proced-format)
322 (defcustom proced-descend t
323 "Non-nil if proced listing is sorted in descending order."
324 :group 'proced
325 :type '(boolean :tag "Descending Sort Order"))
326 (make-variable-buffer-local 'proced-descend)
328 (defcustom proced-goal-attribute 'args
329 "If non-nil, key of the attribute that defines the `goal-column'."
330 :group 'proced
331 :type '(choice (const :tag "none" nil)
332 (symbol :tag "key")))
334 (defcustom proced-auto-update-interval 5
335 "Time interval in seconds for auto updating Proced buffers."
336 :group 'proced
337 :type 'integer)
339 (defcustom proced-auto-update-flag nil
340 "Non-nil for auto update of a Proced buffer.
341 Can be changed interactively via `proced-toggle-auto-update'."
342 :group 'proced
343 :type 'boolean)
344 (make-variable-buffer-local 'proced-auto-update-flag)
346 ;; Internal variables
348 (defvar proced-process-alist nil
349 "Alist of processes displayed by Proced.
350 The car of each element is the PID, and the cdr is a list of
351 cons pairs, see `proced-process-attributes'.")
352 (make-variable-buffer-local 'proced-process-alist)
354 (defvar proced-sort-internal nil
355 "Sort scheme for listing (internal format).
356 It is a list of lists (KEY PREDICATE REVERSE).")
358 (defvar proced-marker-char ?* ; the answer is 42
359 "In proced, the current mark character.")
361 ;; Faces and font-lock code taken from dired,
362 ;; but face variables are deprecated for new code.
363 (defgroup proced-faces nil
364 "Faces used by Proced."
365 :group 'proced
366 :group 'faces)
368 (defface proced-mark
369 '((t (:inherit font-lock-constant-face)))
370 "Face used for proced marks."
371 :group 'proced-faces)
373 (defface proced-marked
374 '((t (:inherit font-lock-warning-face)))
375 "Face used for marked processes."
376 :group 'proced-faces)
378 (defface proced-sort-header
379 '((t (:inherit font-lock-keyword-face)))
380 "Face used for header of attribute used for sorting."
381 :group 'proced-faces)
383 (defvar proced-re-mark "^[^ \n]"
384 "Regexp matching a marked line.
385 Important: the match ends just after the marker.")
387 (defvar proced-header-line nil
388 "Headers in Proced buffer as a string.")
389 (make-variable-buffer-local 'proced-header-line)
391 (defvar proced-process-tree nil
392 "Process tree of listing (internal variable).")
394 (defvar proced-auto-update-timer nil
395 "Stores if Proced auto update timer is already installed.")
397 (defvar proced-log-buffer "*Proced log*"
398 "Name of Proced Log buffer.")
400 (defconst proced-help-string
401 "(n)ext, (p)revious, (m)ark, (u)nmark, (k)ill, (q)uit (type ? for more help)"
402 "Help string for proced.")
404 (defconst proced-header-help-echo
405 "mouse-1, mouse-2: sort by attribute %s%s (%s)"
406 "Help string shown when mouse is over a sortable header.")
408 (defconst proced-field-help-echo
409 "mouse-2, RET: refine by attribute %s %s"
410 "Help string shown when mouse is over a refinable field.")
412 (defvar proced-font-lock-keywords
413 `(;; (Any) proced marks.
414 (,proced-re-mark . 'proced-mark)
415 ;; Processes marked with `proced-marker-char'
416 ;; Should we make sure that only certain attributes are font-locked?
417 (,(concat "^[" (char-to-string proced-marker-char) "]")
418 ".+" (proced-move-to-goal-column) nil (0 'proced-marked))))
420 (defvar proced-mode-map
421 (let ((km (make-sparse-keymap)))
422 ;; moving
423 (define-key km " " 'proced-next-line)
424 (define-key km "n" 'next-line)
425 (define-key km "p" 'previous-line)
426 (define-key km "\C-n" 'next-line)
427 (define-key km "\C-p" 'previous-line)
428 (define-key km "\C-?" 'previous-line)
429 (define-key km [down] 'next-line)
430 (define-key km [up] 'previous-line)
431 ;; marking
432 (define-key km "d" 'proced-mark) ; Dired compatibility ("delete")
433 (define-key km "m" 'proced-mark)
434 (define-key km "u" 'proced-unmark)
435 (define-key km "\177" 'proced-unmark-backward)
436 (define-key km "M" 'proced-mark-all)
437 (define-key km "U" 'proced-unmark-all)
438 (define-key km "t" 'proced-toggle-marks)
439 (define-key km "C" 'proced-mark-children)
440 (define-key km "P" 'proced-mark-parents)
441 ;; filtering
442 (define-key km "f" 'proced-filter-interactive)
443 (define-key km [mouse-2] 'proced-refine)
444 (define-key km "\C-m" 'proced-refine)
445 ;; sorting
446 (define-key km "sc" 'proced-sort-pcpu)
447 (define-key km "sm" 'proced-sort-pmem)
448 (define-key km "sp" 'proced-sort-pid)
449 (define-key km "ss" 'proced-sort-start)
450 (define-key km "sS" 'proced-sort-interactive)
451 (define-key km "st" 'proced-sort-time)
452 (define-key km "su" 'proced-sort-user)
453 ;; similar to `Buffer-menu-sort-by-column'
454 (define-key km [header-line mouse-1] 'proced-sort-header)
455 (define-key km [header-line mouse-2] 'proced-sort-header)
456 ;; formatting
457 (define-key km "F" 'proced-format-interactive)
458 ;; operate
459 (define-key km "o" 'proced-omit-processes)
460 (define-key km "x" 'proced-send-signal) ; Dired compatibility
461 (define-key km "k" 'proced-send-signal) ; kill processes
462 ;; misc
463 (define-key km "g" 'revert-buffer) ; Dired compatibility
464 (define-key km "h" 'describe-mode)
465 (define-key km "?" 'proced-help)
466 (define-key km "q" 'quit-window)
467 (define-key km [remap undo] 'proced-undo)
468 (define-key km [remap advertised-undo] 'proced-undo)
470 "Keymap for proced commands.")
472 (easy-menu-define
473 proced-menu proced-mode-map "Proced Menu"
474 `("Proced"
475 ["Mark" proced-mark
476 :help "Mark Current Process"]
477 ["Unmark" proced-unmark
478 :help "Unmark Current Process"]
479 ["Mark All" proced-mark-all
480 :help "Mark All Processes"]
481 ["Unmark All" proced-unmark-all
482 :help "Unmark All Process"]
483 ["Toggle Marks" proced-toggle-marks
484 :help "Marked Processes Become Unmarked, and Vice Versa"]
485 ["Mark Children" proced-mark-children
486 :help "Mark Current Process and its Children"]
487 ["Mark Parents" proced-mark-parents
488 :help "Mark Current Process and its Parents"]
489 "--"
490 ("Filters"
491 :help "Select Filter for Process Listing"
492 ,@(mapcar (lambda (el)
493 (let ((filter (car el)))
494 `[,(symbol-name filter)
495 (proced-filter-interactive ',filter)
496 :style radio
497 :selected (eq proced-filter ',filter)]))
498 proced-filter-alist))
499 ("Sorting"
500 :help "Select Sort Scheme"
501 ["Sort..." proced-sort-interactive
502 :help "Sort Process List"]
503 "--"
504 ["Sort by %CPU" proced-sort-pcpu]
505 ["Sort by %MEM" proced-sort-pmem]
506 ["Sort by PID" proced-sort-pid]
507 ["Sort by START" proced-sort-start]
508 ["Sort by TIME" proced-sort-time]
509 ["Sort by USER" proced-sort-user])
510 ("Formats"
511 :help "Select Format for Process Listing"
512 ,@(mapcar (lambda (el)
513 (let ((format (car el)))
514 `[,(symbol-name format)
515 (proced-format-interactive ',format)
516 :style radio
517 :selected (eq proced-format ',format)]))
518 proced-format-alist))
519 "--"
520 ["Omit Marked Processes" proced-omit-processes
521 :help "Omit Marked Processes in Process Listing."]
522 "--"
523 ["Revert" revert-buffer
524 :help "Revert Process Listing"]
525 ["Auto Update" proced-toggle-auto-update
526 :style toggle
527 :selected (eval proced-auto-update-flag)
528 :help "Auto Update of Proced Buffer"]
529 ["Send signal" proced-send-signal
530 :help "Send Signal to Marked Processes"]))
532 ;; helper functions
533 (defun proced-marker-regexp ()
534 "Return regexp matching `proced-marker-char'."
535 ;; `proced-marker-char' must appear in column zero
536 (concat "^" (regexp-quote (char-to-string proced-marker-char))))
538 (defun proced-success-message (action count)
539 "Display success message for ACTION performed for COUNT processes."
540 (message "%s %s process%s" action count (if (= 1 count) "" "es")))
542 ;; Unlike dired, we do not define our own commands for vertical motion.
543 ;; If `goal-column' is set, `next-line' and `previous-line' are fancy
544 ;; commands to satisfy our modest needs. If `proced-goal-attribute'
545 ;; and/or `goal-column' are not set, `next-line' and `previous-line'
546 ;; are really what we need to preserve the column of point.
547 ;; We use `proced-move-to-goal-column' for "non-interactive" cases only
548 ;; to get a well-defined position of point.
550 (defun proced-move-to-goal-column ()
551 "Move to `goal-column' if non-nil. Return position of point."
552 (beginning-of-line)
553 (unless (eobp)
554 (if goal-column
555 (forward-char goal-column)
556 (forward-char 2)))
557 (point))
559 (defun proced-header-line ()
560 "Return header line for Proced buffer."
561 (list (propertize " " 'display '(space :align-to 0))
562 (replace-regexp-in-string ;; preserve text properties
563 "\\(%\\)" "\\1\\1" (substring proced-header-line (window-hscroll)))))
565 (defun proced-pid-at-point ()
566 "Return pid of system process at point.
567 Return nil if point is not on a process line."
568 (save-excursion
569 (beginning-of-line)
570 (if (looking-at "^. .")
571 (get-text-property (match-end 0) 'proced-pid))))
573 ;; proced mode
575 (define-derived-mode proced-mode nil "Proced"
576 "Mode for displaying UNIX system processes and sending signals to them.
577 Type \\[proced] to start a Proced session. In a Proced buffer
578 type \\<proced-mode-map>\\[proced-mark] to mark a process for later commands.
579 Type \\[proced-send-signal] to send signals to marked processes.
581 The initial content of a listing is defined by the variable `proced-filter'
582 and the variable `proced-format'.
583 The variable `proced-filter' specifies which system processes are displayed.
584 The variable `proced-format' specifies which attributes are displayed for
585 each process. Type \\[proced-filter-interactive] and \\[proced-format-interactive]
586 to change the values of `proced-filter' and `proced-format'.
587 The current value of the variable `proced-filter' is indicated in the
588 mode line.
590 The sort order of Proced listings is defined by the variable `proced-sort'.
591 Type \\[proced-sort-interactive] or click on a header in the header line
592 to change the sort scheme. The current sort scheme is indicated in the
593 mode line, using \"+\" or \"-\" for ascending or descending sort order.
595 An existing Proced listing can be refined by typing \\[proced-refine]
596 with point on the attribute of a process. If point is on the attribute ATTR,
597 this compares the value of ATTR of every process with the value of ATTR
598 of the process at the position of point. See `proced-refine' for details.
599 Refining an existing listing does not update the variable `proced-filter'.
601 The attribute-specific rules for formatting, filtering, sorting, and refining
602 are defined in `proced-grammar-alist'.
604 \\{proced-mode-map}"
605 (abbrev-mode 0)
606 (auto-fill-mode 0)
607 (setq buffer-read-only t
608 truncate-lines t
609 header-line-format '(:eval (proced-header-line)))
610 (add-hook 'post-command-hook 'force-mode-line-update nil t)
611 (set (make-local-variable 'revert-buffer-function) 'proced-revert)
612 (set (make-local-variable 'font-lock-defaults)
613 '(proced-font-lock-keywords t nil nil beginning-of-line))
614 (if (and (not proced-auto-update-timer) proced-auto-update-interval)
615 (setq proced-auto-update-timer
616 (run-at-time t proced-auto-update-interval
617 'proced-auto-update-timer))))
619 ;; Proced mode is suitable only for specially formatted data.
620 (put 'proced-mode 'mode-class 'special)
622 (defvar proced-available (not (null (list-system-processes)))
623 "Non-nil means Proced is known to work on this system.")
625 ;;;###autoload
626 (defun proced (&optional arg)
627 "Generate a listing of UNIX system processes.
628 If invoked with optional ARG the window displaying the process
629 information will be displayed but not selected.
631 See `proced-mode' for a description of features available in Proced buffers."
632 (interactive "P")
633 (unless proced-available
634 (error "Proced is not available on this system"))
635 (let ((buffer (get-buffer-create "*Proced*")) new)
636 (set-buffer buffer)
637 (setq new (zerop (buffer-size)))
638 (if new (proced-mode))
639 (if (or new arg)
640 (proced-update t))
641 (if arg
642 (display-buffer buffer)
643 (pop-to-buffer buffer)
644 (message
645 (substitute-command-keys
646 "Type \\<proced-mode-map>\\[quit-window] to quit, \\[proced-help] for help")))))
648 (defun proced-auto-update-timer ()
649 "Auto-update Proced buffers using `run-at-time'."
650 (dolist (buf (buffer-list))
651 (with-current-buffer buf
652 (if (and (eq major-mode 'proced-mode)
653 proced-auto-update-flag)
654 (proced-update t t)))))
656 (defun proced-toggle-auto-update (arg)
657 "Change whether this Proced buffer is updated automatically.
658 With prefix ARG, update this buffer automatically if ARG is positive,
659 otherwise do not update. Sets the variable `proced-auto-update-flag'.
660 The time interval for updates is specified via `proced-auto-update-interval'."
661 (interactive (list (or current-prefix-arg 'toggle)))
662 (setq proced-auto-update-flag
663 (cond ((eq arg 'toggle) (not proced-auto-update-flag))
664 (arg (> (prefix-numeric-value arg) 0))
665 (t (not proced-auto-update-flag))))
666 (message "Proced auto update %s"
667 (if proced-auto-update-flag "enabled" "disabled")))
669 (defun proced-mark (&optional count)
670 "Mark the current (or next COUNT) processes."
671 (interactive "p")
672 (proced-do-mark t count))
674 (defun proced-unmark (&optional count)
675 "Unmark the current (or next COUNT) processes."
676 (interactive "p")
677 (proced-do-mark nil count))
679 (defun proced-unmark-backward (&optional count)
680 "Unmark the previous (or COUNT previous) processes."
681 ;; Analogous to `dired-unmark-backward',
682 ;; but `ibuffer-unmark-backward' behaves different.
683 (interactive "p")
684 (proced-do-mark nil (- (or count 1))))
686 (defun proced-do-mark (mark &optional count)
687 "Mark the current (or next COUNT) processes using MARK."
688 (or count (setq count 1))
689 (let ((backward (< count 0))
690 buffer-read-only)
691 (setq count (1+ (if (<= 0 count) count
692 (min (1- (line-number-at-pos)) (abs count)))))
693 (beginning-of-line)
694 (while (not (or (zerop (setq count (1- count))) (eobp)))
695 (proced-insert-mark mark backward))
696 (proced-move-to-goal-column)))
698 (defun proced-mark-all ()
699 "Mark all processes.
700 If `transient-mark-mode' is turned on and the region is active,
701 mark the region."
702 (interactive)
703 (proced-do-mark-all t))
705 (defun proced-unmark-all ()
706 "Unmark all processes.
707 If `transient-mark-mode' is turned on and the region is active,
708 unmark the region."
709 (interactive)
710 (proced-do-mark-all nil))
712 (defun proced-do-mark-all (mark)
713 "Mark all processes using MARK.
714 If `transient-mark-mode' is turned on and the region is active,
715 mark the region."
716 (let ((count 0) end buffer-read-only)
717 (save-excursion
718 (if (use-region-p)
719 ;; Operate even on those lines that are only partially a part
720 ;; of region. This appears most consistent with
721 ;; `proced-move-to-goal-column'.
722 (progn (setq end (save-excursion
723 (goto-char (region-end))
724 (unless (looking-at "^") (forward-line))
725 (point)))
726 (goto-char (region-beginning))
727 (unless (looking-at "^") (beginning-of-line)))
728 (goto-char (point-min))
729 (setq end (point-max)))
730 (while (< (point) end)
731 (setq count (1+ count))
732 (proced-insert-mark mark))
733 (proced-success-message "Marked" count))))
735 (defun proced-toggle-marks ()
736 "Toggle marks: marked processes become unmarked, and vice versa."
737 (interactive)
738 (let ((mark-re (proced-marker-regexp))
739 buffer-read-only)
740 (save-excursion
741 (goto-char (point-min))
742 (while (not (eobp))
743 (cond ((looking-at mark-re)
744 (proced-insert-mark nil))
745 ((looking-at " ")
746 (proced-insert-mark t))
748 (forward-line 1)))))))
750 (defun proced-insert-mark (mark &optional backward)
751 "If MARK is non-nil, insert `proced-marker-char'.
752 If BACKWARD is non-nil, move one line backwards before inserting the mark.
753 Otherwise move one line forward after inserting the mark."
754 (if backward (forward-line -1))
755 (insert (if mark proced-marker-char ?\s))
756 (delete-char 1)
757 (unless backward (forward-line)))
759 (defun proced-mark-children (ppid &optional omit-ppid)
760 "Mark child processes of process PPID.
761 Also mark process PPID unless prefix OMIT-PPID is non-nil."
762 (interactive (list (proced-pid-at-point) current-prefix-arg))
763 (proced-mark-process-alist
764 (proced-filter-children proced-process-alist ppid omit-ppid)))
766 (defun proced-mark-parents (cpid &optional omit-cpid)
767 "Mark parent processes of process CPID.
768 Also mark CPID unless prefix OMIT-CPID is non-nil."
769 (interactive (list (proced-pid-at-point) current-prefix-arg))
770 (proced-mark-process-alist
771 (proced-filter-parents proced-process-alist cpid omit-cpid)))
773 (defun proced-mark-process-alist (process-alist &optional quiet)
774 (let ((count 0))
775 (if process-alist
776 (let (buffer-read-only)
777 (save-excursion
778 (goto-char (point-min))
779 (while (not (eobp))
780 (when (assq (proced-pid-at-point) process-alist)
781 (insert proced-marker-char)
782 (delete-char 1)
783 (setq count (1+ count)))
784 (forward-line)))))
785 (unless quiet
786 (proced-success-message "Marked" count))))
788 ;; Mostly analog of `dired-do-kill-lines'.
789 ;; However, for negative args the target lines of `dired-do-kill-lines'
790 ;; include the current line, whereas `dired-mark' for negative args operates
791 ;; on the preceding lines. Here we are consistent with `dired-mark'.
792 (defun proced-omit-processes (&optional arg quiet)
793 "Omit marked processes.
794 With prefix ARG, omit that many lines starting with the current line.
795 \(A negative argument omits backward.)
796 If `transient-mark-mode' is turned on and the region is active,
797 omit the processes in region.
798 If QUIET is non-nil suppress status message.
799 Returns count of omitted lines."
800 (interactive "P")
801 (let ((mark-re (proced-marker-regexp))
802 (count 0)
803 buffer-read-only)
804 (cond ((use-region-p) ;; Omit active region
805 (let ((lines (count-lines (region-beginning) (region-end))))
806 (save-excursion
807 (goto-char (region-beginning))
808 (while (< count lines)
809 (proced-omit-process)
810 (setq count (1+ count))))))
811 ((not arg) ;; Omit marked lines
812 (save-excursion
813 (goto-char (point-min))
814 (while (and (not (eobp))
815 (re-search-forward mark-re nil t))
816 (proced-omit-process)
817 (setq count (1+ count)))))
818 ((< 0 arg) ;; Omit forward
819 (while (and (not (eobp)) (< count arg))
820 (proced-omit-process)
821 (setq count (1+ count))))
822 ((< arg 0) ;; Omit backward
823 (while (and (not (bobp)) (< count (- arg)))
824 (forward-line -1)
825 (proced-omit-process)
826 (setq count (1+ count)))))
827 (unless (zerop count) (proced-move-to-goal-column))
828 (unless quiet (proced-success-message "Omitted" count))
829 count))
831 (defun proced-omit-process ()
832 "Omit process from listing point is on.
833 Update `proced-process-alist' accordingly."
834 (setq proced-process-alist
835 (assq-delete-all (proced-pid-at-point) proced-process-alist))
836 (delete-region (line-beginning-position)
837 (save-excursion (forward-line) (point))))
839 ;;; Filtering
841 (defun proced-filter (process-alist filter-list)
842 "Apply FILTER-LIST to PROCESS-ALIST.
843 Return the filtered process list."
844 (if (symbolp filter-list)
845 (setq filter-list (cdr (assq filter-list proced-filter-alist))))
846 (dolist (filter filter-list)
847 (let (new-alist)
848 (cond ( ;; apply function to entire process list
849 (eq (car filter) 'fun-all)
850 (setq new-alist (funcall (cdr filter) process-alist)))
851 ( ;; apply predicate to each list of attributes
852 (eq (car filter) 'function)
853 (dolist (process process-alist)
854 (if (funcall (car filter) (cdr process))
855 (push process new-alist))))
856 (t ;; apply predicate to specified attribute
857 (let ((fun (if (stringp (cdr filter))
858 `(lambda (val)
859 (string-match ,(cdr filter) val))
860 (cdr filter)))
861 value)
862 (dolist (process process-alist)
863 (setq value (cdr (assq (car filter) (cdr process))))
864 (if (and value (funcall fun value))
865 (push process new-alist))))))
866 (setq process-alist new-alist)))
867 process-alist)
869 (defun proced-filter-interactive (scheme)
870 "Filter Proced buffer using SCHEME.
871 When called interactively, an empty string means nil, i.e., no filtering.
872 Set variable `proced-filter' to SCHEME. Revert listing."
873 (interactive
874 (let ((scheme (completing-read "Filter: "
875 proced-filter-alist nil t)))
876 (list (if (string= "" scheme) nil (intern scheme)))))
877 ;; only update if necessary
878 (unless (eq proced-filter scheme)
879 (setq proced-filter scheme)
880 (proced-update t)))
882 (defun proced-process-tree (process-alist)
883 "Return process tree for PROCESS-ALIST.
884 The process tree is an alist with elements (PPID PID1 PID2 ...).
885 PPID is a parent PID. PID1, PID2, ... are the child processes of PPID.
886 The list of children does not include grandchildren."
887 (let (children-list ppid cpids)
888 (dolist (process process-alist children-list)
889 (setq ppid (cdr (assq 'ppid (cdr process))))
890 (if ppid
891 (setq children-list
892 (if (setq cpids (assq ppid children-list))
893 (cons (cons ppid (cons (car process) (cdr cpids)))
894 (assq-delete-all ppid children-list))
895 (cons (list ppid (car process))
896 children-list)))))))
898 (defun proced-filter-children (process-alist ppid &optional omit-ppid)
899 "For PROCESS-ALIST return list of child processes of PPID.
900 This list includes PPID unless OMIT-PPID is non-nil."
901 (let ((proced-process-tree (proced-process-tree process-alist))
902 new-alist)
903 (dolist (pid (proced-children-pids ppid))
904 (push (assq pid process-alist) new-alist))
905 (if omit-ppid
906 (assq-delete-all ppid new-alist)
907 new-alist)))
909 ;; helper function
910 (defun proced-children-pids (ppid)
911 "Return list of children PIDs of PPID (including PPID)."
912 (let ((cpids (cdr (assq ppid proced-process-tree))))
913 (if cpids
914 (cons ppid (apply 'append (mapcar 'proced-children-pids cpids)))
915 (list ppid))))
917 (defun proced-filter-parents (process-alist pid &optional omit-pid)
918 "For PROCESS-ALIST return list of parent processes of PID.
919 This list includes CPID unless OMIT-CPID is non-nil."
920 (let ((parent-list (unless omit-pid (list (assq pid process-alist)))))
921 (while (setq pid (cdr (assq 'ppid (cdr (assq pid process-alist)))))
922 (push (assq pid process-alist) parent-list))
923 parent-list))
925 ;; Refining
927 ;; Filters are used to select the processes in a new listing.
928 ;; Refiners are used to narrow down further (interactively) the processes
929 ;; in an existing listing.
931 (defun proced-refine (&optional event)
932 "Refine Proced listing by comparing with the attribute value at point.
933 Optional EVENT is the location of the Proced field.
935 Refinement is controlled by the REFINER defined for each attribute ATTR
936 in `proced-grammar-alist'.
938 If REFINER is a list of flags and point is on the attribute ATTR, this command
939 compares the value of ATTR of every process with the value of ATTR
940 of the process at the position of point.
942 The predicate for the comparison of two ATTR values is defined
943 in `proced-grammar-alist'. For each return value of the predicate
944 a refine flag is defined in `proced-grammar-alist'. One can select
945 processes for which the value of ATTR is \"less than\", \"equal\",
946 and / or \"larger\" than ATTR of the process point is on. A process
947 is included in the new listing if the refine flag for the corresponding
948 return value of the predicate is non-nil.
949 The help-echo string for `proced-refine' uses \"+\" or \"-\" to indicate
950 the current values of these refine flags.
952 If REFINER is a cons pair (FUNCTION . HELP-ECHO), FUNCTION is called
953 with one argument, the PID of the process at the position of point.
954 The function must return a list of PIDs that is used for the refined
955 listing. HELP-ECHO is a string that is shown when mouse is over this field.
957 This command refines an already existing process listing generated initially
958 based on the value of the variable `proced-filter'. It does not change
959 this variable. It does not revert the listing. If you frequently need
960 a certain refinement, consider defining a new filter in `proced-filter-alist'."
961 (interactive (list last-input-event))
962 (if event (posn-set-point (event-end event)))
963 (let ((key (get-text-property (point) 'proced-key))
964 (pid (get-text-property (point) 'proced-pid)))
965 (if (and key pid)
966 (let* ((grammar (assq key proced-grammar-alist))
967 (refiner (nth 7 grammar)))
968 (when refiner
969 (cond ((functionp (car refiner))
970 (setq proced-process-alist (funcall (car refiner) pid)))
971 ((consp refiner)
972 (let ((predicate (nth 4 grammar))
973 (ref (cdr (assq key (cdr (assq pid proced-process-alist)))))
974 val new-alist)
975 (dolist (process proced-process-alist)
976 (setq val (funcall predicate (cdr (assq key (cdr process))) ref))
977 (if (cond ((not val) (nth 2 refiner))
978 ((eq val 'equal) (nth 1 refiner))
979 (val (car refiner)))
980 (push process new-alist)))
981 (setq proced-process-alist new-alist))))
982 ;; Do not revert listing.
983 (proced-update)))
984 (message "No refiner defined here."))))
986 ;; Proced predicates for sorting and filtering are based on a three-valued
987 ;; logic:
988 ;; Predicates take two arguments P1 and P2, the corresponding attribute
989 ;; values of two processes. Predicates should return 'equal if P1 has
990 ;; same rank like P2. Any other non-nil value says that P1 is "less than" P2,
991 ;; or nil if not.
993 (defun proced-< (num1 num2)
994 "Return t if NUM1 less than NUM2.
995 Return `equal' if NUM1 equals NUM2. Return nil if NUM1 greater than NUM2."
996 (if (= num1 num2)
997 'equal
998 (< num1 num2)))
1000 (defun proced-string-lessp (s1 s2)
1001 "Return t if string S1 is less than S2 in lexicographic order.
1002 Return `equal' if S1 and S2 have identical contents.
1003 Return nil otherwise."
1004 (if (string= s1 s2)
1005 'equal
1006 (string-lessp s1 s2)))
1008 (defun proced-time-lessp (t1 t2)
1009 "Return t if time value T1 is less than time value T2.
1010 Return `equal' if T1 equals T2. Return nil otherwise."
1011 (with-decoded-time-value ((high1 low1 micro1 t1)
1012 (high2 low2 micro2 t2))
1013 (cond ((< high1 high2))
1014 ((< high2 high1) nil)
1015 ((< low1 low2))
1016 ((< low2 low1) nil)
1017 ((< micro1 micro2))
1018 ((< micro2 micro1) nil)
1019 (t 'equal))))
1021 ;;; Sorting
1023 (defsubst proced-xor (b1 b2)
1024 "Return the logical exclusive or of args B1 and B2."
1025 (and (or b1 b2)
1026 (not (and b1 b2))))
1028 (defun proced-sort-p (p1 p2)
1029 "Predicate for sorting processes P1 and P2."
1030 (if (not (cdr proced-sort-internal))
1031 ;; only one predicate: fast scheme
1032 (let* ((sorter (car proced-sort-internal))
1033 (k1 (cdr (assq (car sorter) (cdr p1))))
1034 (k2 (cdr (assq (car sorter) (cdr p2)))))
1035 ;; if the attributes are undefined, we should really abort sorting
1036 (if (and k1 k2)
1037 (proced-xor (funcall (nth 1 sorter) k1 k2)
1038 (nth 2 sorter))))
1039 (let ((sort-list proced-sort-internal) sorter predicate k1 k2)
1040 (catch 'done
1041 (while (setq sorter (pop sort-list))
1042 (setq k1 (cdr (assq (car sorter) (cdr p1)))
1043 k2 (cdr (assq (car sorter) (cdr p2)))
1044 predicate
1045 (if (and k1 k2)
1046 (funcall (nth 1 sorter) k1 k2)))
1047 (if (not (eq predicate 'equal))
1048 (throw 'done (proced-xor predicate (nth 2 sorter)))))
1049 (eq t predicate)))))
1051 (defun proced-sort (process-alist sorter descend)
1052 "Sort PROCESS-ALIST using scheme SORTER.
1053 SORTER is a scheme like `proced-sort'.
1054 DESCEND is non-nil if the first element of SORTER is sorted
1055 in descending order.
1056 Return the sorted process list."
1057 ;; translate SORTER into a list of lists (KEY PREDICATE REVERSE)
1058 (setq proced-sort-internal
1059 (mapcar (lambda (arg)
1060 (let ((grammar (assq arg proced-grammar-alist)))
1061 (list arg (nth 4 grammar) (nth 5 grammar))))
1062 (cond ((listp sorter) sorter)
1063 ((and (symbolp sorter)
1064 (nth 6 (assq sorter proced-grammar-alist))))
1065 ((symbolp sorter) (list sorter))
1066 (t (error "Sorter undefined %s" sorter)))))
1067 (if proced-sort-internal
1068 (progn
1069 ;; splice DESCEND into the list
1070 (setcar proced-sort-internal
1071 (list (caar proced-sort-internal)
1072 (nth 1 (car proced-sort-internal)) descend))
1073 (sort process-alist 'proced-sort-p))
1074 process-alist))
1076 (defun proced-sort-interactive (scheme &optional revert)
1077 "Sort Proced buffer using SCHEME.
1078 When called interactively, an empty string means nil, i.e., no sorting.
1079 With prefix REVERT non-nil revert listing.
1081 Repeated calls using the same value of SCHEME toggle the sort order.
1083 Set variable `proced-sort' to SCHEME. The current sort scheme is displayed
1084 in the mode line, using \"+\" or \"-\" for ascending or descending order."
1085 (interactive
1086 (let ((scheme (completing-read "Sort attribute: "
1087 proced-grammar-alist nil t)))
1088 (list (if (string= "" scheme) nil (intern scheme))
1089 current-prefix-arg)))
1090 (setq proced-descend
1091 ;; If `proced-sort-interactive' is called repeatedly for the same sort key,
1092 ;; the sort order is reversed.
1093 (if (equal proced-sort scheme)
1094 (not proced-descend)
1095 (nth 5 (assq (if (consp scheme) (car scheme) scheme)
1096 proced-grammar-alist)))
1097 proced-sort scheme)
1098 (proced-update revert))
1100 (defun proced-sort-pcpu (&optional revert)
1101 "Sort Proced buffer by percentage CPU time (%CPU).
1102 Repeated calls toggle the sort order."
1103 (interactive "P")
1104 (proced-sort-interactive 'pcpu revert))
1106 (defun proced-sort-pmem (&optional revert)
1107 "Sort Proced buffer by percentage memory usage (%MEM).
1108 Repeated calls toggle the sort order."
1109 (interactive "P")
1110 (proced-sort-interactive 'pmem revert))
1112 (defun proced-sort-pid (&optional revert)
1113 "Sort Proced buffer by PID.
1114 Repeated calls toggle the sort order."
1115 (interactive "P")
1116 (proced-sort-interactive 'pid revert))
1118 (defun proced-sort-start (&optional revert)
1119 "Sort Proced buffer by time the command started (START).
1120 Repeated calls toggle the sort order."
1121 (interactive "P")
1122 (proced-sort-interactive 'start revert))
1124 (defun proced-sort-time (&optional revert)
1125 "Sort Proced buffer by CPU time (TIME).
1126 Repeated calls toggle the sort order."
1127 (interactive "P")
1128 (proced-sort-interactive 'time revert))
1130 (defun proced-sort-user (&optional revert)
1131 "Sort Proced buffer by USER.
1132 Repeated calls toggle the sort order."
1133 (interactive "P")
1134 (proced-sort-interactive 'user revert))
1136 (defun proced-sort-header (event &optional revert)
1137 "Sort Proced listing based on an attribute.
1138 EVENT is a mouse event with starting position in the header line.
1139 It is converted in the corresponding attribute key.
1140 This command updates the variable `proced-sort'.
1141 Repeated calls for the same header toggle the sort order."
1142 (interactive "e\nP")
1143 (let ((start (event-start event))
1144 col key)
1145 (save-selected-window
1146 (select-window (posn-window start))
1147 (setq col (+ (1- (car (posn-actual-col-row start)))
1148 (window-hscroll)))
1149 (when (and (<= 0 col) (< col (length proced-header-line)))
1150 (setq key (get-text-property col 'proced-key proced-header-line))
1151 (if key
1152 (proced-sort-interactive key revert)
1153 (message "No sorter defined here."))))))
1155 ;;; Formating
1157 (defun proced-format-time (time)
1158 "Format time interval TIME."
1159 (let* ((ftime (float-time time))
1160 (days (truncate ftime 86400))
1161 (ftime (mod ftime 86400))
1162 (hours (truncate ftime 3600))
1163 (ftime (mod ftime 3600))
1164 (minutes (truncate ftime 60))
1165 (seconds (mod ftime 60)))
1166 (cond ((< 0 days)
1167 (format "%d-%02d:%02d:%02d" days hours minutes seconds))
1168 ((< 0 hours)
1169 (format "%02d:%02d:%02d" hours minutes seconds))
1171 (format "%02d:%02d" minutes seconds)))))
1173 (defun proced-format-start (start)
1174 "Format time START.
1175 The return string is always 6 characters wide."
1176 (let ((d-start (decode-time start))
1177 (d-current (decode-time)))
1178 (cond ( ;; process started in previous years
1179 (< (nth 5 d-start) (nth 5 d-current))
1180 (format-time-string " %Y" start))
1181 ;; process started today
1182 ((and (= (nth 3 d-start) (nth 3 d-current))
1183 (= (nth 4 d-start) (nth 4 d-current)))
1184 (format-time-string " %H:%M" start))
1185 (t ;; process started this year
1186 (format-time-string "%b %e" start)))))
1188 (defun proced-format-ttname (ttname)
1189 "Format attribute TTNAME, omitting path \"/dev/\"."
1190 ;; Does this work for all systems?
1191 (substring ttname (if (string-match "\\`/dev/" ttname)
1192 (match-end 0) 0)))
1194 ;; Proced assumes that every process occupies only one line in the listing.
1195 (defun proced-format-args (args)
1196 "Format attribute ARGS.
1197 Replace newline characters by \"^J\" (two characters)."
1198 (replace-regexp-in-string "\n" "^J" args))
1200 (defun proced-format (process-alist format)
1201 "Display PROCESS-ALIST using FORMAT."
1202 (if (symbolp format)
1203 (setq format (cdr (assq format proced-format-alist))))
1205 ;; Not all systems give us all attributes. We take `emacs-pid' as a
1206 ;; representative process PID. If FORMAT contains a list of alternative
1207 ;; attributes, we take the first attribute that is non-nil for `emacs-pid'.
1208 ;; If none of the alternatives is non-nil, the attribute is ignored
1209 ;; in the listing.
1210 (let ((standard-attributes
1211 (car (proced-process-attributes (list (emacs-pid)))))
1212 new-format fmi)
1213 (dolist (fmt format)
1214 (if (symbolp fmt)
1215 (if (assq fmt standard-attributes)
1216 (push fmt new-format))
1217 (while (setq fmi (pop fmt))
1218 (when (assq fmi standard-attributes)
1219 (push fmi new-format)
1220 (setq fmt nil)))))
1221 (setq format (nreverse new-format)))
1223 (insert (make-string (length process-alist) ?\n))
1224 (let ((whitespace " ") (unknown "?")
1225 (sort-key (if (consp proced-sort) (car proced-sort) proced-sort))
1226 header-list grammar)
1227 ;; Loop over all attributes
1228 (while (setq grammar (assq (pop format) proced-grammar-alist))
1229 (let* ((key (car grammar))
1230 (fun (cond ((stringp (nth 2 grammar))
1231 `(lambda (arg) (format ,(nth 2 grammar) arg)))
1232 ((not (nth 2 grammar)) 'identity)
1233 ( t (nth 2 grammar))))
1234 (whitespace (if format whitespace ""))
1235 ;; Text properties:
1236 ;; We use the text property `proced-key' to store in each
1237 ;; field the corresponding key.
1238 ;; Of course, the sort predicate appearing in help-echo
1239 ;; is only part of the story. But it gives the main idea.
1240 (hprops (let ((descend (if (eq key sort-key) proced-descend (nth 5 grammar))))
1241 `(proced-key ,key mouse-face highlight
1242 help-echo ,(format proced-header-help-echo
1243 (if descend "-" "+")
1244 (nth 1 grammar)
1245 (if descend "descending" "ascending")))))
1246 (refiner (nth 7 grammar))
1247 (fprops
1248 (cond ((functionp (car refiner))
1249 `(proced-key ,key mouse-face highlight
1250 help-echo ,(format "mouse-2, RET: %s"
1251 (cdr refiner))))
1252 ((consp refiner)
1253 `(proced-key ,key mouse-face highlight
1254 help-echo ,(format "mouse-2, RET: refine by attribute %s %s"
1255 (nth 1 grammar)
1256 (mapconcat (lambda (s)
1257 (if s "+" "-"))
1258 refiner ""))))))
1259 value)
1261 ;; highlight the header of the sort column
1262 (if (eq key sort-key)
1263 (setq hprops (append '(face proced-sort-header) hprops)))
1264 (goto-char (point-min))
1265 (cond ( ;; fixed width of output field
1266 (numberp (nth 3 grammar))
1267 (dolist (process process-alist)
1268 (end-of-line)
1269 (setq value (cdr (assq key (cdr process))))
1270 (insert (if value
1271 (apply 'propertize (funcall fun value) fprops)
1272 (format (concat "%" (number-to-string (nth 3 grammar)) "s")
1273 unknown))
1274 whitespace)
1275 (forward-line))
1276 (push (format (concat "%" (number-to-string (nth 3 grammar)) "s")
1277 (apply 'propertize (nth 1 grammar) hprops))
1278 header-list))
1280 ( ;; last field left-justified
1281 (and (not format) (eq 'left (nth 3 grammar)))
1282 (dolist (process process-alist)
1283 (end-of-line)
1284 (setq value (cdr (assq key (cdr process))))
1285 (insert (if value (apply 'propertize (funcall fun value) fprops)
1286 unknown))
1287 (forward-line))
1288 (push (apply 'propertize (nth 1 grammar) hprops) header-list))
1290 (t ;; calculated field width
1291 (let ((width (length (nth 1 grammar)))
1292 field-list value)
1293 (dolist (process process-alist)
1294 (setq value (cdr (assq key (cdr process))))
1295 (if value
1296 (setq value (apply 'propertize (funcall fun value) fprops)
1297 width (max width (length value))
1298 field-list (cons value field-list))
1299 (push unknown field-list)
1300 (setq width (max width (length unknown)))))
1301 (let ((afmt (concat "%" (if (eq 'left (nth 3 grammar)) "-" "")
1302 (number-to-string width) "s")))
1303 (push (format afmt (apply 'propertize (nth 1 grammar) hprops))
1304 header-list)
1305 (dolist (value (nreverse field-list))
1306 (end-of-line)
1307 (insert (format afmt value) whitespace)
1308 (forward-line))))))))
1310 ;; final cleanup
1311 (goto-char (point-min))
1312 (dolist (process process-alist)
1313 ;; We use the text property `proced-pid' to store in each line
1314 ;; the corresponding pid
1315 (put-text-property (point) (line-end-position) 'proced-pid (car process))
1316 (forward-line))
1317 ;; Set header line
1318 (setq proced-header-line
1319 (mapconcat 'identity (nreverse header-list) whitespace))
1320 (if (string-match "[ \t]+$" proced-header-line)
1321 (setq proced-header-line (substring proced-header-line 0
1322 (match-beginning 0))))
1323 ;; (delete-trailing-whitespace)
1324 (goto-char (point-min))
1325 (while (re-search-forward "[ \t\r]+$" nil t)
1326 (delete-region (match-beginning 0) (match-end 0)))))
1328 (defun proced-format-interactive (scheme &optional revert)
1329 "Format Proced buffer using SCHEME.
1330 When called interactively, an empty string means nil, i.e., no formatting.
1331 Set variable `proced-format' to SCHEME.
1332 With prefix REVERT non-nil revert listing."
1333 (interactive
1334 (let ((scheme (completing-read "Format: "
1335 proced-format-alist nil t)))
1336 (list (if (string= "" scheme) nil (intern scheme))
1337 current-prefix-arg)))
1338 ;; only update if necessary
1339 (when (or (not (eq proced-format scheme)) revert)
1340 (setq proced-format scheme)
1341 (proced-update revert)))
1343 ;; generate listing
1345 (defun proced-process-attributes (&optional pid-list)
1346 "Return alist of attributes for each system process.
1347 This alist can be customized via `proced-custom-attributes'.
1348 Optional arg PID-LIST is a list of PIDs of system process that are analyzed.
1349 If no attributes are known for a process (possibly because it already died)
1350 the process is ignored."
1351 ;; Should we make it customizable whether processes with empty attribute
1352 ;; lists are ignored? When would such processes be of interest?
1353 (let (process-alist attributes)
1354 (dolist (pid (or pid-list (list-system-processes)) process-alist)
1355 (when (setq attributes (system-process-attributes pid))
1356 (let ((utime (cdr (assq 'utime attributes)))
1357 (stime (cdr (assq 'stime attributes)))
1358 (cutime (cdr (assq 'cutime attributes)))
1359 (cstime (cdr (assq 'cstime attributes)))
1360 attr)
1361 (setq attributes
1362 (append (list (cons 'pid pid))
1363 (if (and utime stime)
1364 (list (cons 'time (time-add utime stime))))
1365 (if (and cutime cstime)
1366 (list (cons 'ctime (time-add cutime cstime))))
1367 attributes))
1368 (dolist (fun proced-custom-attributes)
1369 (if (setq attr (funcall fun attributes))
1370 (push attr attributes)))
1371 (push (cons pid attributes) process-alist))))))
1373 (defun proced-update (&optional revert quiet)
1374 "Update the `proced' process information. Preserves point and marks.
1375 With prefix REVERT non-nil, revert listing.
1376 Suppress status information if QUIET is nil."
1377 ;; This is the main function that generates and updates the process listing.
1378 (interactive "P")
1379 (setq revert (or revert (not proced-process-alist)))
1380 (or quiet (message (if revert "Updating process information..."
1381 "Updating process display...")))
1382 (if revert ;; evaluate all processes
1383 (setq proced-process-alist (proced-process-attributes)))
1384 ;; filtering and sorting
1385 (setq proced-process-alist
1386 (proced-sort (proced-filter proced-process-alist proced-filter)
1387 proced-sort proced-descend))
1389 ;; It is useless to keep undo information if we revert, filter, or
1390 ;; refine the listing so that `proced-process-alist' has changed.
1391 ;; We could keep the undo information if we only re-sort the buffer.
1392 ;; Would that be useful? Re-re-sorting is easy, too.
1393 (if (consp buffer-undo-list)
1394 (setq buffer-undo-list nil))
1395 (let ((buffer-undo-list t)
1396 ;; If point is on a field, we try to return point to that field.
1397 ;; Otherwise we try to return to the same column
1398 (old-pos (let ((pid (proced-pid-at-point))
1399 (key (get-text-property (point) 'proced-key)))
1400 (list pid key ; can both be nil
1401 (if key
1402 (if (get-text-property (1- (point)) 'proced-key)
1403 (- (point) (previous-single-property-change
1404 (point) 'proced-key))
1406 (current-column)))))
1407 buffer-read-only mp-list)
1408 ;; remember marked processes (whatever the mark was)
1409 (goto-char (point-min))
1410 (while (re-search-forward "^\\(\\S-\\)" nil t)
1411 (push (cons (save-match-data (proced-pid-at-point))
1412 (match-string-no-properties 1)) mp-list))
1414 ;; generate listing
1415 (erase-buffer)
1416 (proced-format proced-process-alist proced-format)
1417 (goto-char (point-min))
1418 (while (not (eobp))
1419 (insert " ")
1420 (forward-line))
1421 (setq proced-header-line (concat " " proced-header-line))
1422 (if revert (set-buffer-modified-p nil))
1424 ;; set `goal-column'
1425 (let ((grammar (assq proced-goal-attribute proced-grammar-alist)))
1426 (setq goal-column ;; set to nil if no match
1427 (if (and grammar
1428 (not (zerop (buffer-size)))
1429 (string-match (regexp-quote (nth 1 grammar))
1430 proced-header-line))
1431 (if (nth 3 grammar)
1432 (match-beginning 0)
1433 (match-end 0)))))
1435 ;; Restore process marks and buffer position (if possible).
1436 ;; Sometimes this puts point in the middle of the proced buffer
1437 ;; where it is not interesting. Is there a better / more flexible solution?
1438 (goto-char (point-min))
1439 (let (pid mark new-pos)
1440 (if (or mp-list (car old-pos))
1441 (while (not (eobp))
1442 (setq pid (proced-pid-at-point))
1443 (when (setq mark (assq pid mp-list))
1444 (insert (cdr mark))
1445 (delete-char 1)
1446 (beginning-of-line))
1447 (when (eq (car old-pos) pid)
1448 (if (nth 1 old-pos)
1449 (let ((limit (line-end-position)) pos)
1450 (while (and (not new-pos)
1451 (setq pos (next-property-change (point) nil limit)))
1452 (goto-char pos)
1453 (when (eq (nth 1 old-pos)
1454 (get-text-property (point) 'proced-key))
1455 (forward-char (min (nth 2 old-pos)
1456 (- (next-property-change (point))
1457 (point))))
1458 (setq new-pos (point))))
1459 (unless new-pos
1460 ;; we found the process, but the field of point
1461 ;; is not listed anymore
1462 (setq new-pos (proced-move-to-goal-column))))
1463 (setq new-pos (min (+ (line-beginning-position) (nth 2 old-pos))
1464 (line-end-position)))))
1465 (forward-line)))
1466 (if new-pos
1467 (goto-char new-pos)
1468 (goto-char (point-min))
1469 (proced-move-to-goal-column)))
1470 ;; update modeline
1471 ;; Does the long `mode-name' clutter the modeline? It would be nice
1472 ;; to have some other location for displaying the values of the various
1473 ;; flags that affect the behavior of proced (flags one might want
1474 ;; to change on the fly). Where??
1475 (setq mode-name
1476 (concat "Proced"
1477 (if proced-filter
1478 (concat ": " (symbol-name proced-filter))
1480 (if proced-sort
1481 (let* ((key (if (consp proced-sort) (car proced-sort)
1482 proced-sort))
1483 (grammar (assq key proced-grammar-alist)))
1484 (concat " by " (if proced-descend "-" "+")
1485 (nth 1 grammar)))
1486 "")))
1487 (force-mode-line-update)
1488 ;; done
1489 (or quiet (input-pending-p)
1490 (message (if revert "Updating process information...done."
1491 "Updating process display...done.")))))
1493 (defun proced-revert (&rest args)
1494 "Analog of `revert-buffer'."
1495 (proced-update t))
1497 ;; I do not want to reinvent the wheel. Should we rename `dired-pop-to-buffer'
1498 ;; and move it to window.el so that proced and ibuffer can easily use it, too?
1499 ;; What about functions like `appt-disp-window' that use
1500 ;; `shrink-window-if-larger-than-buffer'?
1501 (autoload 'dired-pop-to-buffer "dired")
1503 (defun proced-send-signal (&optional signal)
1504 "Send a SIGNAL to the marked processes.
1505 If no process is marked, operate on current process.
1506 SIGNAL may be a string (HUP, INT, TERM, etc.) or a number.
1507 If SIGNAL is nil display marked processes and query interactively for SIGNAL."
1508 (interactive)
1509 (let ((regexp (proced-marker-regexp))
1510 process-alist)
1511 ;; collect marked processes
1512 (save-excursion
1513 (goto-char (point-min))
1514 (while (re-search-forward regexp nil t)
1515 (push (cons (proced-pid-at-point)
1516 ;; How much info should we collect here?
1517 (substring (match-string-no-properties 0) 2))
1518 process-alist)))
1519 (setq process-alist
1520 (if process-alist
1521 (nreverse process-alist)
1522 ;; take current process
1523 (list (cons (proced-pid-at-point)
1524 (buffer-substring-no-properties
1525 (+ 2 (line-beginning-position))
1526 (line-end-position))))))
1527 (unless signal
1528 ;; Display marked processes (code taken from `dired-mark-pop-up').
1529 (let ((bufname " *Marked Processes*")
1530 (header-line (substring-no-properties proced-header-line)))
1531 (with-current-buffer (get-buffer-create bufname)
1532 (setq truncate-lines t
1533 proced-header-line header-line ; inherit header line
1534 header-line-format '(:eval (proced-header-line)))
1535 (add-hook 'post-command-hook 'force-mode-line-update nil t)
1536 (erase-buffer)
1537 (dolist (process process-alist)
1538 (insert " " (cdr process) "\n"))
1539 (save-window-excursion
1540 (dired-pop-to-buffer bufname) ; all we need
1541 (let* ((completion-ignore-case t)
1542 (pnum (if (= 1 (length process-alist))
1543 "1 process"
1544 (format "%d processes" (length process-alist))))
1545 ;; The following is an ugly hack. Is there a better way
1546 ;; to help people like me to remember the signals and
1547 ;; their meanings?
1548 (tmp (completing-read (concat "Send signal [" pnum
1549 "] (default TERM): ")
1550 proced-signal-list
1551 nil nil nil nil "TERM")))
1552 (setq signal (if (string-match "^\\(\\S-+\\)\\s-" tmp)
1553 (match-string 1 tmp) tmp))))))
1554 ;; send signal
1555 (let ((count 0)
1556 failures)
1557 ;; Why not always use `signal-process'? See
1558 ;; http://lists.gnu.org/archive/html/emacs-devel/2008-03/msg02955.html
1559 (if (functionp proced-signal-function)
1560 ;; use built-in `signal-process'
1561 (let ((signal (if (stringp signal)
1562 (if (string-match "\\`[0-9]+\\'" signal)
1563 (string-to-number signal)
1564 (make-symbol signal))
1565 signal))) ; number
1566 (dolist (process process-alist)
1567 (condition-case err
1568 (if (zerop (funcall
1569 proced-signal-function (car process) signal))
1570 (setq count (1+ count))
1571 (proced-log "%s\n" (cdr process))
1572 (push (cdr process) failures))
1573 (error ;; catch errors from failed signals
1574 (proced-log "%s\n" err)
1575 (proced-log "%s\n" (cdr process))
1576 (push (cdr process) failures)))))
1577 ;; use external system call
1578 (let ((signal (concat "-" (if (numberp signal)
1579 (number-to-string signal) signal))))
1580 (dolist (process process-alist)
1581 (with-temp-buffer
1582 (condition-case err
1583 (if (zerop (call-process
1584 proced-signal-function nil t nil
1585 signal (number-to-string (car process))))
1586 (setq count (1+ count))
1587 (proced-log (current-buffer))
1588 (proced-log "%s\n" (cdr process))
1589 (push (cdr process) failures))
1590 (error ;; catch errors from failed signals
1591 (proced-log (current-buffer))
1592 (proced-log "%s\n" (cdr process))
1593 (push (cdr process) failures)))))))
1594 (if failures
1595 ;; Proced error message are not always very precise.
1596 ;; Can we issue a useful one-line summary in the
1597 ;; message area (using FAILURES) if only one signal failed?
1598 (proced-log-summary
1599 signal
1600 (format "%d of %d signal%s failed"
1601 (length failures) (length process-alist)
1602 (if (= 1 (length process-alist)) "" "s")))
1603 (proced-success-message "Sent signal to" count)))
1604 ;; final clean-up
1605 (run-hooks 'proced-after-send-signal-hook))))
1607 ;; similar to `dired-why'
1608 (defun proced-why ()
1609 "Pop up a buffer with error log output from Proced.
1610 A group of errors from a single command ends with a formfeed.
1611 Thus, use \\[backward-page] to find the beginning of a group of errors."
1612 (interactive)
1613 (if (get-buffer proced-log-buffer)
1614 (save-selected-window
1615 ;; move `proced-log-buffer' to the front of the buffer list
1616 (select-window (display-buffer (get-buffer proced-log-buffer)))
1617 (setq truncate-lines t)
1618 (set-buffer-modified-p nil)
1619 (setq buffer-read-only t)
1620 (goto-char (point-max))
1621 (forward-line -1)
1622 (backward-page 1)
1623 (recenter 0))))
1625 ;; similar to `dired-log'
1626 (defun proced-log (log &rest args)
1627 "Log a message or the contents of a buffer.
1628 If LOG is a string and there are more args, it is formatted with
1629 those ARGS. Usually the LOG string ends with a \\n.
1630 End each bunch of errors with (proced-log t signal):
1631 this inserts the current time, buffer and signal at the start of the page,
1632 and \f (formfeed) at the end."
1633 (let ((obuf (current-buffer)))
1634 (with-current-buffer (get-buffer-create proced-log-buffer)
1635 (goto-char (point-max))
1636 (let (buffer-read-only)
1637 (cond ((stringp log)
1638 (insert (if args
1639 (apply 'format log args)
1640 log)))
1641 ((bufferp log)
1642 (insert-buffer-substring log))
1643 ((eq t log)
1644 (backward-page 1)
1645 (unless (bolp)
1646 (insert "\n"))
1647 (insert (current-time-string)
1648 "\tBuffer `" (buffer-name obuf) "', "
1649 (format "signal `%s'\n" (car args)))
1650 (goto-char (point-max))
1651 (insert "\f\n")))))))
1653 ;; similar to `dired-log-summary'
1654 (defun proced-log-summary (signal string)
1655 "State a summary of SIGNAL's failures, in echo area and log buffer.
1656 STRING is an overall summary of the failures."
1657 (message "Signal %s: %s--type ? for details" signal string)
1658 ;; Log a summary describing a bunch of errors.
1659 (proced-log (concat "\n" string "\n"))
1660 (proced-log t signal))
1662 (defun proced-help ()
1663 "Provide help for the `proced' user."
1664 (interactive)
1665 (proced-why)
1666 (if (eq last-command 'proced-help)
1667 (describe-mode)
1668 (message proced-help-string)))
1670 (defun proced-undo ()
1671 "Undo in a proced buffer.
1672 This doesn't recover killed processes, it just undoes changes in the proced
1673 buffer. You can use it to recover marks."
1674 (interactive)
1675 (let (buffer-read-only)
1676 (undo))
1677 (message "Change in Proced buffer undone.
1678 Killed processes cannot be recovered by Emacs."))
1680 (provide 'proced)
1682 ;; arch-tag: a6e312ad-9032-45aa-972d-31a8cfc545af
1683 ;;; proced.el ends here