proced.el 83 KB

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