proced.el 82 KB

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