proced.el 82 KB

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