proced.el 79 KB

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