man.el 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. ;;; man.el --- browse UNIX manual pages -*- lexical-binding: t -*-
  2. ;; Copyright (C) 1993-1994, 1996-1997, 2001-2017 Free Software
  3. ;; Foundation, Inc.
  4. ;; Author: Barry A. Warsaw <bwarsaw@cen.com>
  5. ;; Maintainer: emacs-devel@gnu.org
  6. ;; Keywords: help
  7. ;; Adapted-By: ESR, pot
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;; This code provides a function, `man', with which you can browse
  21. ;; UNIX manual pages. Formatting is done in background so that you
  22. ;; can continue to use your Emacs while processing is going on.
  23. ;;
  24. ;; The mode also supports hypertext-like following of manual page SEE
  25. ;; ALSO references, and other features. See below or do `?' in a
  26. ;; manual page buffer for details.
  27. ;; ========== Credits and History ==========
  28. ;; In mid 1991, several people posted some interesting improvements to
  29. ;; man.el from the standard Emacs 18.57 distribution. I liked many of
  30. ;; these, but wanted everything in one single package, so I decided
  31. ;; to incorporate them into a single manual browsing mode. While
  32. ;; much of the code here has been rewritten, and some features added,
  33. ;; these folks deserve lots of credit for providing the initial
  34. ;; excellent packages on which this one is based.
  35. ;; Nick Duffek <duffek@chaos.cs.brandeis.edu>, posted a very nice
  36. ;; improvement which retrieved and cleaned the manpages in a
  37. ;; background process, and which correctly deciphered such options as
  38. ;; man -k.
  39. ;; Eric Rose <erose@jessica.stanford.edu>, submitted manual.el which
  40. ;; provided a very nice manual browsing mode.
  41. ;; This package was available as `superman.el' from the LCD package
  42. ;; for some time before it was accepted into Emacs 19. The entry
  43. ;; point and some other names have been changed to make it a drop-in
  44. ;; replacement for the old man.el package.
  45. ;; Francesco Potortì <pot@cnuce.cnr.it> cleaned it up thoroughly,
  46. ;; making it faster, more robust and more tolerant of different
  47. ;; systems' man idiosyncrasies.
  48. ;; ========== Features ==========
  49. ;; + Runs "man" in the background and pipes the results through a
  50. ;; series of sed and awk scripts so that all retrieving and cleaning
  51. ;; is done in the background. The cleaning commands are configurable.
  52. ;; + Syntax is the same as Un*x man
  53. ;; + Functionality is the same as Un*x man, including "man -k" and
  54. ;; "man <section>", etc.
  55. ;; + Provides a manual browsing mode with keybindings for traversing
  56. ;; the sections of a manpage, following references in the SEE ALSO
  57. ;; section, and more.
  58. ;; + Multiple manpages created with the same man command are put into
  59. ;; a narrowed buffer circular list.
  60. ;; ============= TODO ===========
  61. ;; - Add a command for printing.
  62. ;; - The awk script deletes multiple blank lines. This behavior does
  63. ;; not allow one to understand if there was indeed a blank line at the
  64. ;; end or beginning of a page (after the header, or before the
  65. ;; footer). A different algorithm should be used. It is easy to
  66. ;; compute how many blank lines there are before and after the page
  67. ;; headers, and after the page footer. But it is possible to compute
  68. ;; the number of blank lines before the page footer by heuristics
  69. ;; only. Is it worth doing?
  70. ;; - Allow a user option to mean that all the manpages should go in
  71. ;; the same buffer, where they can be browsed with M-n and M-p.
  72. ;;; Code:
  73. (require 'ansi-color)
  74. (require 'cl-lib)
  75. (require 'button)
  76. (defgroup man nil
  77. "Browse UNIX manual pages."
  78. :prefix "Man-"
  79. :group 'external
  80. :group 'help)
  81. (defvar Man-notify)
  82. (defcustom Man-filter-list nil
  83. "Manpage cleaning filter command phrases.
  84. This variable contains a list of the following form:
  85. ((command-string phrase-string*)*)
  86. Each phrase-string is concatenated onto the command-string to form a
  87. command filter. The (standard) output (and standard error) of the Un*x
  88. man command is piped through each command filter in the order the
  89. commands appear in the association list. The final output is placed in
  90. the manpage buffer."
  91. :type '(repeat (list (string :tag "Command String")
  92. (repeat :inline t
  93. (string :tag "Phrase String"))))
  94. :group 'man)
  95. (defvar Man-uses-untabify-flag t
  96. "Non-nil means use `untabify' instead of `Man-untabify-command'.")
  97. (defvar Man-sed-script nil
  98. "Script for sed to nuke backspaces and ANSI codes from manpages.")
  99. (defcustom Man-fontify-manpage-flag t
  100. "Non-nil means make up the manpage with fonts."
  101. :type 'boolean
  102. :group 'man)
  103. (defface Man-overstrike
  104. '((t (:inherit bold)))
  105. "Face to use when fontifying overstrike."
  106. :group 'man
  107. :version "24.3")
  108. (defface Man-underline
  109. '((t (:inherit underline)))
  110. "Face to use when fontifying underlining."
  111. :group 'man
  112. :version "24.3")
  113. (defface Man-reverse
  114. '((t (:inherit highlight)))
  115. "Face to use when fontifying reverse video."
  116. :group 'man
  117. :version "24.3")
  118. (defvar Man-ansi-color-map (let ((ansi-color-faces-vector
  119. [ default Man-overstrike default Man-underline
  120. Man-underline default default Man-reverse ]))
  121. (ansi-color-make-color-map))
  122. "The value used here for `ansi-color-map'.")
  123. ;; Use the value of the obsolete user option Man-notify, if set.
  124. (defcustom Man-notify-method (if (boundp 'Man-notify) Man-notify 'friendly)
  125. "Selects the behavior when manpage is ready.
  126. This variable may have one of the following values, where (sf) means
  127. that the frames are switched, so the manpage is displayed in the frame
  128. where the man command was called from:
  129. newframe -- put the manpage in its own frame (see `Man-frame-parameters')
  130. pushy -- make the manpage the current buffer in the current window
  131. bully -- make the manpage the current buffer and only window (sf)
  132. aggressive -- make the manpage the current buffer in the other window (sf)
  133. friendly -- display manpage in the other window but don't make current (sf)
  134. polite -- don't display manpage, but prints message and beep when ready
  135. quiet -- like `polite', but don't beep
  136. meek -- make no indication that the manpage is ready
  137. Any other value of `Man-notify-method' is equivalent to `meek'."
  138. :type '(radio (const newframe) (const pushy) (const bully)
  139. (const aggressive) (const friendly)
  140. (const polite) (const quiet) (const meek))
  141. :group 'man)
  142. (defcustom Man-width nil
  143. "Number of columns for which manual pages should be formatted.
  144. If nil, use the width of the window where the manpage is displayed.
  145. If non-nil, use the width of the frame where the manpage is displayed.
  146. The value also can be a positive integer for a fixed width."
  147. :type '(choice (const :tag "Window width" nil)
  148. (const :tag "Frame width" t)
  149. (integer :tag "Fixed width" :value 65))
  150. :group 'man)
  151. (defcustom Man-frame-parameters nil
  152. "Frame parameter list for creating a new frame for a manual page."
  153. :type '(repeat (cons :format "%v"
  154. (symbol :tag "Parameter")
  155. (sexp :tag "Value")))
  156. :group 'man)
  157. (defcustom Man-downcase-section-letters-flag t
  158. "Non-nil means letters in sections are converted to lower case.
  159. Some Un*x man commands can't handle uppercase letters in sections, for
  160. example \"man 2V chmod\", but they are often displayed in the manpage
  161. with the upper case letter. When this variable is t, the section
  162. letter (e.g., \"2V\") is converted to lowercase (e.g., \"2v\") before
  163. being sent to the man background process."
  164. :type 'boolean
  165. :group 'man)
  166. (defcustom Man-circular-pages-flag t
  167. "Non-nil means the manpage list is treated as circular for traversal."
  168. :type 'boolean
  169. :group 'man)
  170. (defcustom Man-section-translations-alist
  171. (list
  172. '("3C++" . "3")
  173. ;; Some systems have a real 3x man section, so let's comment this.
  174. ;; '("3X" . "3") ; Xlib man pages
  175. '("3X11" . "3")
  176. '("1-UCB" . ""))
  177. "Association list of bogus sections to real section numbers.
  178. Some manpages (e.g. the Sun C++ 2.1 manpages) have section numbers in
  179. their references which Un*x `man' does not recognize. This
  180. association list is used to translate those sections, when found, to
  181. the associated section number."
  182. :type '(repeat (cons (string :tag "Bogus Section")
  183. (string :tag "Real Section")))
  184. :group 'man)
  185. ;; FIXME see comments at ffap-c-path.
  186. (defcustom Man-header-file-path
  187. (let ((arch (with-temp-buffer
  188. (when (eq 0 (ignore-errors
  189. (call-process "gcc" nil '(t nil) nil
  190. "-print-multiarch")))
  191. (goto-char (point-min))
  192. (buffer-substring (point) (line-end-position)))))
  193. (base '("/usr/include" "/usr/local/include")))
  194. (if (zerop (length arch))
  195. base
  196. (append base (list (expand-file-name arch "/usr/include")))))
  197. "C Header file search path used in Man."
  198. :version "24.1" ; add multiarch
  199. :type '(repeat string)
  200. :group 'man)
  201. (defcustom Man-name-local-regexp (concat "^" (regexp-opt '("NOM" "NAME")) "$")
  202. "Regexp that matches the text that precedes the command's name.
  203. Used in `bookmark-set' to get the default bookmark name."
  204. :version "24.1"
  205. :type 'string :group 'bookmark)
  206. (defcustom manual-program "man"
  207. "Program used by `man' to produce man pages."
  208. :type 'string
  209. :group 'man)
  210. (defcustom Man-untabify-command "pr"
  211. "Program used by `man' for untabifying."
  212. :type 'string
  213. :group 'man)
  214. (defcustom Man-untabify-command-args (list "-t" "-e")
  215. "List of arguments to be passed to `Man-untabify-command' (which see)."
  216. :type '(repeat string)
  217. :group 'man)
  218. (defcustom Man-sed-command "sed"
  219. "Program used by `man' to process sed scripts."
  220. :type 'string
  221. :group 'man)
  222. (defcustom Man-awk-command "awk"
  223. "Program used by `man' to process awk scripts."
  224. :type 'string
  225. :group 'man)
  226. (defcustom Man-mode-hook nil
  227. "Hook run when Man mode is enabled."
  228. :type 'hook
  229. :group 'man)
  230. (defcustom Man-cooked-hook nil
  231. "Hook run after removing backspaces but before `Man-mode' processing."
  232. :type 'hook
  233. :group 'man)
  234. (defvar Man-name-regexp "[-[:alnum:]_­+][-[:alnum:]_.:­+]*"
  235. "Regular expression describing the name of a manpage (without section).")
  236. (defvar Man-section-regexp "[0-9][a-zA-Z0-9+]*\\|[LNln]"
  237. "Regular expression describing a manpage section within parentheses.")
  238. (defvar Man-page-header-regexp
  239. (if (string-match "-solaris2\\." system-configuration)
  240. (concat "^[-[:alnum:]_].*[ \t]\\(" Man-name-regexp
  241. "(\\(" Man-section-regexp "\\))\\)$")
  242. (concat "^[ \t]*\\(" Man-name-regexp
  243. "(\\(" Man-section-regexp "\\))\\).*\\1"))
  244. "Regular expression describing the heading of a page.")
  245. (defvar Man-heading-regexp "^\\([[:upper:]][[:upper:]0-9 /-]+\\)$"
  246. "Regular expression describing a manpage heading entry.")
  247. (defvar Man-see-also-regexp "\\(SEE ALSO\\|VOIR AUSSI\\|SIEHE AUCH\\|VÉASE TAMBIÉN\\|VEJA TAMBÉM\\|VEDERE ANCHE\\|ZOBACZ TAKŻE\\|İLGİLİ BELGELER\\|参照\\|参见 SEE ALSO\\|參見 SEE ALSO\\)"
  248. "Regular expression for SEE ALSO heading (or your equivalent).
  249. This regexp should not start with a `^' character.")
  250. ;; This used to have leading space [ \t]*, but was removed because it
  251. ;; causes false page splits on an occasional NAME with leading space
  252. ;; inside a manpage. And `Man-heading-regexp' doesn't have [ \t]* anyway.
  253. (defvar Man-first-heading-regexp "^NAME$\\|^[ \t]*No manual entry fo.*$"
  254. "Regular expression describing first heading on a manpage.
  255. This regular expression should start with a `^' character.")
  256. (defvar Man-reference-regexp
  257. (concat "\\(" Man-name-regexp
  258. "\\(‐?\n[ \t]+" Man-name-regexp "\\)*\\)[ \t]*(\\("
  259. Man-section-regexp "\\))")
  260. "Regular expression describing a reference to another manpage.")
  261. (defvar Man-apropos-regexp
  262. (concat "\\[\\(" Man-name-regexp "\\)\\][ \t]*(\\(" Man-section-regexp "\\))")
  263. "Regular expression describing a reference to manpages in \"man -k output\".")
  264. (defvar Man-synopsis-regexp "SYNOPSIS"
  265. "Regular expression for SYNOPSIS heading (or your equivalent).
  266. This regexp should not start with a `^' character.")
  267. (defvar Man-files-regexp "FILES\\>"
  268. ;; Add \> so as not to match mount(8)'s FILESYSTEM INDEPENDENT MOUNT OPTIONS.
  269. "Regular expression for FILES heading (or your equivalent).
  270. This regexp should not start with a `^' character.")
  271. (defvar Man-include-regexp "#[ \t]*include[ \t]*"
  272. "Regular expression describing the #include (directive of cpp).")
  273. (defvar Man-file-name-regexp "[^<>\", \t\n]+"
  274. "Regular expression describing <> in #include line (directive of cpp).")
  275. (defvar Man-normal-file-prefix-regexp "[/~$]"
  276. "Regular expression describing a file path appeared in FILES section.")
  277. (defvar Man-header-regexp
  278. (concat "\\(" Man-include-regexp "\\)"
  279. "[<\"]"
  280. "\\(" Man-file-name-regexp "\\)"
  281. "[>\"]")
  282. "Regular expression describing references to header files.")
  283. (defvar Man-normal-file-regexp
  284. (concat Man-normal-file-prefix-regexp Man-file-name-regexp)
  285. "Regular expression describing references to normal files.")
  286. ;; This includes the section as an optional part to catch hyphenated
  287. ;; references to manpages.
  288. (defvar Man-hyphenated-reference-regexp
  289. (concat "\\(" Man-name-regexp "\\)\\((\\(" Man-section-regexp "\\))\\)?")
  290. "Regular expression describing a reference in the SEE ALSO section.")
  291. (defcustom Man-switches ""
  292. "Switches passed to the man command, as a single string.
  293. For example, the -a switch lets you see all the manpages for a
  294. specified subject, if your `man' program supports it."
  295. :type 'string
  296. :group 'man)
  297. (defvar Man-specified-section-option
  298. (if (string-match "-solaris[0-9.]*$" system-configuration)
  299. "-s"
  300. "")
  301. "Option that indicates a specified a manual section name.")
  302. (defvar Man-support-local-filenames 'auto-detect
  303. "Internal cache for the value of the function `Man-support-local-filenames'.
  304. `auto-detect' means the value is not yet determined.
  305. Otherwise, the value is whatever the function
  306. `Man-support-local-filenames' should return.")
  307. (defcustom man-imenu-title "Contents"
  308. "The title to use if man adds a Contents menu to the menubar."
  309. :version "24.4"
  310. :type 'string
  311. :group 'man)
  312. ;; other variables and keymap initializations
  313. (defvar Man-original-frame)
  314. (make-variable-buffer-local 'Man-original-frame)
  315. (defvar Man-arguments)
  316. (make-variable-buffer-local 'Man-arguments)
  317. (put 'Man-arguments 'permanent-local t)
  318. (defvar Man--sections nil)
  319. (make-variable-buffer-local 'Man--sections)
  320. (defvar Man--refpages nil)
  321. (make-variable-buffer-local 'Man--refpages)
  322. (defvar Man-page-list nil)
  323. (make-variable-buffer-local 'Man-page-list)
  324. (defvar Man-current-page 0)
  325. (make-variable-buffer-local 'Man-current-page)
  326. (defvar Man-page-mode-string "1 of 1")
  327. (make-variable-buffer-local 'Man-page-mode-string)
  328. (defconst Man-sysv-sed-script "\
  329. /\b/ { s/_\b//g
  330. s/\b_//g
  331. s/o\b+/o/g
  332. s/+\bo/o/g
  333. :ovstrk
  334. s/\\(.\\)\b\\1/\\1/g
  335. t ovstrk
  336. }
  337. /\e\\[[0-9][0-9]*m/ s///g"
  338. "Script for sysV-like sed to nuke backspaces and ANSI codes from manpages.")
  339. (defconst Man-berkeley-sed-script "\
  340. /\b/ { s/_\b//g\\
  341. s/\b_//g\\
  342. s/o\b+/o/g\\
  343. s/+\bo/o/g\\
  344. :ovstrk\\
  345. s/\\(.\\)\b\\1/\\1/g\\
  346. t ovstrk\\
  347. }\\
  348. /\e\\[[0-9][0-9]*m/ s///g"
  349. "Script for berkeley-like sed to nuke backspaces and ANSI codes from manpages.")
  350. (defvar Man-topic-history nil "Topic read history.")
  351. (defvar Man-mode-syntax-table
  352. (let ((table (copy-syntax-table (standard-syntax-table))))
  353. (modify-syntax-entry ?. "w" table)
  354. (modify-syntax-entry ?_ "w" table)
  355. (modify-syntax-entry ?: "w" table) ; for PDL::Primitive in Perl man pages
  356. table)
  357. "Syntax table used in Man mode buffers.")
  358. (defvar Man-mode-map
  359. (let ((map (make-sparse-keymap)))
  360. (suppress-keymap map)
  361. (set-keymap-parent map
  362. (make-composed-keymap button-buffer-map special-mode-map))
  363. (define-key map "n" 'Man-next-section)
  364. (define-key map "p" 'Man-previous-section)
  365. (define-key map "\en" 'Man-next-manpage)
  366. (define-key map "\ep" 'Man-previous-manpage)
  367. (define-key map "." 'beginning-of-buffer)
  368. (define-key map "r" 'Man-follow-manual-reference)
  369. (define-key map "g" 'Man-goto-section)
  370. (define-key map "s" 'Man-goto-see-also-section)
  371. (define-key map "k" 'Man-kill)
  372. (define-key map "u" 'Man-update-manpage)
  373. (define-key map "m" 'man)
  374. ;; Not all the man references get buttons currently. The text in the
  375. ;; manual page can contain references to other man pages
  376. (define-key map "\r" 'man-follow)
  377. (easy-menu-define nil map
  378. "`Man-mode' menu."
  379. '("Man"
  380. ["Next Section" Man-next-section t]
  381. ["Previous Section" Man-previous-section t]
  382. ["Go To Section..." Man-goto-section t]
  383. ["Go To \"SEE ALSO\" Section" Man-goto-see-also-section
  384. :active (cl-member Man-see-also-regexp Man--sections
  385. :test #'string-match-p)]
  386. ["Follow Reference..." Man-follow-manual-reference
  387. :active Man--refpages
  388. :help "Go to a manpage referred to in the \"SEE ALSO\" section"]
  389. "--"
  390. ["Next Manpage" Man-next-manpage
  391. :active (> (length Man-page-list) 1)]
  392. ["Previous Manpage" Man-previous-manpage
  393. :active (> (length Man-page-list) 1)]
  394. "--"
  395. ["Man..." man t]
  396. ["Kill Buffer" Man-kill t]
  397. ["Quit" quit-window t]))
  398. map)
  399. "Keymap for Man mode.")
  400. ;; buttons
  401. (define-button-type 'Man-abstract-xref-man-page
  402. 'follow-link t
  403. 'help-echo "mouse-2, RET: display this man page"
  404. 'func nil
  405. 'action #'Man-xref-button-action)
  406. (defun Man-xref-button-action (button)
  407. (let ((target (button-get button 'Man-target-string)))
  408. (funcall
  409. (button-get button 'func)
  410. (cond ((null target)
  411. (button-label button))
  412. ((functionp target)
  413. (funcall target (button-start button)))
  414. (t target)))))
  415. (define-button-type 'Man-xref-man-page
  416. :supertype 'Man-abstract-xref-man-page
  417. 'func 'man-follow)
  418. (define-button-type 'Man-xref-header-file
  419. 'action (lambda (button)
  420. (let ((w (button-get button 'Man-target-string)))
  421. (unless (Man-view-header-file w)
  422. (error "Cannot find header file: %s" w))))
  423. 'follow-link t
  424. 'help-echo "mouse-2: display this header file")
  425. (define-button-type 'Man-xref-normal-file
  426. 'action (lambda (button)
  427. (let ((f (substitute-in-file-name
  428. (button-get button 'Man-target-string))))
  429. (if (file-exists-p f)
  430. (if (file-readable-p f)
  431. (view-file f)
  432. (error "Cannot read a file: %s" f))
  433. (error "Cannot find a file: %s" f))))
  434. 'follow-link t
  435. 'help-echo "mouse-2: display this file")
  436. ;; ======================================================================
  437. ;; utilities
  438. (defun Man-init-defvars ()
  439. "Used for initializing variables based on display's color support.
  440. This is necessary if one wants to dump man.el with Emacs."
  441. ;; Avoid possible error in call-process by using a directory that must exist.
  442. (let ((default-directory "/"))
  443. (setq Man-sed-script
  444. (cond
  445. (Man-fontify-manpage-flag
  446. nil)
  447. ((eq 0 (call-process Man-sed-command nil nil nil Man-sysv-sed-script))
  448. Man-sysv-sed-script)
  449. ((eq 0 (call-process Man-sed-command nil nil nil Man-berkeley-sed-script))
  450. Man-berkeley-sed-script)
  451. (t
  452. nil))))
  453. (setq Man-filter-list
  454. ;; Avoid trailing nil which confuses customize.
  455. (apply 'list
  456. (cons
  457. Man-sed-command
  458. (if (eq system-type 'windows-nt)
  459. ;; Windows needs ".." quoting, not '..'.
  460. (list
  461. "-e \"/Reformatting page. Wait/d\""
  462. "-e \"/Reformatting entry. Wait/d\""
  463. "-e \"/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d\""
  464. "-e \"/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d\""
  465. "-e \"/^Printed[ \t][0-9].*[0-9]$/d\""
  466. "-e \"/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d\""
  467. "-e \"/^[A-Za-z].*Last[ \t]change:/d\""
  468. "-e \"/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d\""
  469. "-e \"/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d\"")
  470. (list
  471. (if Man-sed-script
  472. (concat "-e '" Man-sed-script "'")
  473. "")
  474. "-e '/^[\001-\032][\001-\032]*$/d'"
  475. "-e '/\e[789]/s///g'"
  476. "-e '/Reformatting page. Wait/d'"
  477. "-e '/Reformatting entry. Wait/d'"
  478. "-e '/^[ \t]*Hewlett-Packard[ \t]Company[ \t]*-[ \t][0-9]*[ \t]-/d'"
  479. "-e '/^[ \t]*Hewlett-Packard[ \t]*-[ \t][0-9]*[ \t]-.*$/d'"
  480. "-e '/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d'"
  481. "-e '/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d'"
  482. "-e '/^Printed[ \t][0-9].*[0-9]$/d'"
  483. "-e '/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d'"
  484. "-e '/^[A-Za-z].*Last[ \t]change:/d'"
  485. "-e '/^Sun[ \t]Release[ \t][0-9].*[0-9]$/d'"
  486. "-e '/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d'"
  487. "-e '/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d'"
  488. )))
  489. ;; Windows doesn't support multi-line commands, so don't
  490. ;; invoke Awk there.
  491. (unless (eq system-type 'windows-nt)
  492. (cons
  493. Man-awk-command
  494. (list
  495. "'\n"
  496. "BEGIN { blankline=0; anonblank=0; }\n"
  497. "/^$/ { if (anonblank==0) next; }\n"
  498. "{ anonblank=1; }\n"
  499. "/^$/ { blankline++; next; }\n"
  500. "{ if (blankline>0) { print \"\"; blankline=0; } print $0; }\n"
  501. "'"
  502. )))
  503. (if (not Man-uses-untabify-flag)
  504. ;; The outer list will be stripped off by apply.
  505. (list (cons
  506. Man-untabify-command
  507. Man-untabify-command-args))
  508. )))
  509. )
  510. (defsubst Man-make-page-mode-string ()
  511. "Formats part of the mode line for Man mode."
  512. (format "%s page %d of %d"
  513. (or (nth 2 (nth (1- Man-current-page) Man-page-list))
  514. "")
  515. Man-current-page
  516. (length Man-page-list)))
  517. (defsubst Man-build-man-command ()
  518. "Builds the entire background manpage and cleaning command."
  519. (let ((command (concat manual-program " " Man-switches
  520. (cond
  521. ;; Already has %s
  522. ((string-match "%s" manual-program) "")
  523. ;; Stock MS-DOS shells cannot redirect stderr;
  524. ;; `call-process' below sends it to /dev/null,
  525. ;; so we don't need `2>' even with DOS shells
  526. ;; which do support stderr redirection.
  527. ((not (fboundp 'make-process)) " %s")
  528. ((concat " %s 2>" null-device)))))
  529. (flist Man-filter-list))
  530. (while (and flist (car flist))
  531. (let ((pcom (car (car flist)))
  532. (pargs (cdr (car flist))))
  533. (setq command
  534. (concat command " | " pcom " "
  535. (mapconcat (lambda (phrase)
  536. (if (not (stringp phrase))
  537. (error "Malformed Man-filter-list"))
  538. phrase)
  539. pargs " ")))
  540. (setq flist (cdr flist))))
  541. command))
  542. (defun Man-translate-cleanup (string)
  543. "Strip leading, trailing and middle spaces."
  544. (when (stringp string)
  545. ;; Strip leading and trailing
  546. (if (string-match "^[ \t\f\r\n]*\\(.+[^ \t\f\r\n]\\)" string)
  547. (setq string (match-string 1 string)))
  548. ;; middle spaces
  549. (setq string (replace-regexp-in-string "[\t\r\n]" " " string))
  550. (setq string (replace-regexp-in-string " +" " " string))
  551. string))
  552. (defun Man-translate-references (ref)
  553. "Translates REF from \"chmod(2V)\" to \"2v chmod\" style.
  554. Leave it as is if already in that style. Possibly downcase and
  555. translate the section (see the `Man-downcase-section-letters-flag'
  556. and the `Man-section-translations-alist' variables)."
  557. (let ((name "")
  558. (section "")
  559. (slist Man-section-translations-alist))
  560. (setq ref (Man-translate-cleanup ref))
  561. (cond
  562. ;; "chmod(2V)" case ?
  563. ((string-match (concat "^" Man-reference-regexp "$") ref)
  564. (setq name (replace-regexp-in-string "[\n\t ]" "" (match-string 1 ref))
  565. section (match-string 3 ref)))
  566. ;; "2v chmod" case ?
  567. ((string-match (concat "^\\(" Man-section-regexp
  568. "\\) +\\(" Man-name-regexp "\\)$") ref)
  569. (setq name (match-string 2 ref)
  570. section (match-string 1 ref))))
  571. (if (string= name "")
  572. ref ; Return the reference as is
  573. (if Man-downcase-section-letters-flag
  574. (setq section (downcase section)))
  575. (while slist
  576. (let ((s1 (car (car slist)))
  577. (s2 (cdr (car slist))))
  578. (setq slist (cdr slist))
  579. (if Man-downcase-section-letters-flag
  580. (setq s1 (downcase s1)))
  581. (if (not (string= s1 section)) nil
  582. (setq section (if Man-downcase-section-letters-flag
  583. (downcase s2)
  584. s2)
  585. slist nil))))
  586. (concat Man-specified-section-option section " " name))))
  587. (defun Man-support-local-filenames ()
  588. "Return non-nil if the man command supports local filenames.
  589. Different man programs support this feature in different ways.
  590. The default Debian man program (\"man-db\") has a `--local-file'
  591. \(or `-l') option for this purpose. The default Red Hat man
  592. program has no such option, but interprets any name containing
  593. a \"/\" as a local filename. The function returns either `man-db'
  594. `man', or nil."
  595. (if (eq Man-support-local-filenames 'auto-detect)
  596. (setq Man-support-local-filenames
  597. (with-temp-buffer
  598. (let ((default-directory
  599. ;; Ensure that `default-directory' exists and is readable.
  600. (if (file-accessible-directory-p default-directory)
  601. default-directory
  602. (expand-file-name "~/"))))
  603. (ignore-errors
  604. (call-process manual-program nil t nil "--help")))
  605. (cond ((search-backward "--local-file" nil 'move)
  606. 'man-db)
  607. ;; This feature seems to be present in at least ver 1.4f,
  608. ;; which is about 20 years old.
  609. ;; I don't know if this version has an official name?
  610. ((looking-at "^man, versione? [1-9]")
  611. 'man))))
  612. Man-support-local-filenames))
  613. ;; ======================================================================
  614. ;; default man entry: get word near point
  615. (defun Man-default-man-entry (&optional pos)
  616. "Guess default manual entry based on the text near position POS.
  617. POS defaults to `point'."
  618. (let (word start column distance)
  619. (save-excursion
  620. (when pos (goto-char pos))
  621. (setq pos (point))
  622. ;; The default title is the nearest entry-like object before or
  623. ;; after POS.
  624. (if (and (skip-chars-backward " \ta-zA-Z0-9+")
  625. (not (zerop (skip-chars-backward "(")))
  626. ;; Try to handle the special case where POS is on a
  627. ;; section number.
  628. (looking-at
  629. (concat "([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
  630. ;; We skipped a valid section number backwards, look at
  631. ;; preceding text.
  632. (or (and (skip-chars-backward ",; \t")
  633. (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:"))))
  634. ;; Not a valid entry, move POS after closing paren.
  635. (not (setq pos (match-end 0)))))
  636. ;; We have a candidate, make `start' record its starting
  637. ;; position.
  638. (setq start (point))
  639. ;; Otherwise look at char before POS.
  640. (goto-char pos)
  641. (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
  642. ;; Our candidate is just before or around POS.
  643. (setq start (point))
  644. ;; Otherwise record the current column and look backwards.
  645. (setq column (current-column))
  646. (skip-chars-backward ",; \t")
  647. ;; Record the distance traveled.
  648. (setq distance (- column (current-column)))
  649. (when (looking-back
  650. (concat "([ \t]*\\(?:" Man-section-regexp "\\)[ \t]*)")
  651. (line-beginning-position))
  652. ;; Skip section number backwards.
  653. (goto-char (match-beginning 0))
  654. (skip-chars-backward " \t"))
  655. (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
  656. (progn
  657. ;; We have a candidate before POS ...
  658. (setq start (point))
  659. (goto-char pos)
  660. (if (and (skip-chars-forward ",; \t")
  661. (< (- (current-column) column) distance)
  662. (looking-at "[-a-zA-Z0-9._+:]"))
  663. ;; ... but the one after POS is better.
  664. (setq start (point))
  665. ;; ... and anything after POS is worse.
  666. (goto-char start)))
  667. ;; No candidate before POS.
  668. (goto-char pos)
  669. (skip-chars-forward ",; \t")
  670. (setq start (point)))))
  671. ;; We have found a suitable starting point, try to skip at least
  672. ;; one character.
  673. (skip-chars-forward "-a-zA-Z0-9._+:")
  674. (setq word (buffer-substring-no-properties start (point)))
  675. ;; If there is a continuation at the end of line, check the
  676. ;; following line too, eg:
  677. ;; see this-
  678. ;; command-here(1)
  679. ;; Note: This code gets executed iff our entry is after POS.
  680. (when (looking-at "‐?[ \t\r\n]+\\([-a-zA-Z0-9._+:]+\\)([0-9])")
  681. (setq word (concat word (match-string-no-properties 1)))
  682. ;; Make sure the section number gets included by the code below.
  683. (goto-char (match-end 1)))
  684. (when (string-match "[-._]+$" word)
  685. (setq word (substring word 0 (match-beginning 0))))
  686. ;; The following was commented out since the preceding code
  687. ;; should not produce a leading "*" in the first place.
  688. ;;; ;; If looking at something like *strcat(... , remove the '*'
  689. ;;; (when (string-match "^*" word)
  690. ;;; (setq word (substring word 1)))
  691. (concat
  692. word
  693. (and (not (string-equal word ""))
  694. ;; If looking at something like ioctl(2) or brc(1M),
  695. ;; include the section number in the returned value.
  696. (looking-at
  697. (concat "[ \t]*([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
  698. (format "(%s)" (match-string-no-properties 1)))))))
  699. ;; ======================================================================
  700. ;; Top level command and background process sentinel
  701. ;; For compatibility with older versions.
  702. ;;;###autoload
  703. (defalias 'manual-entry 'man)
  704. (defvar Man-completion-cache nil
  705. ;; On my machine, "man -k" is so fast that a cache makes no sense,
  706. ;; but apparently that's not the case in all cases, so let's add a cache.
  707. "Cache of completion table of the form (PREFIX . TABLE).")
  708. (defvar Man-man-k-use-anchor
  709. ;; man-db or man-1.*
  710. (memq system-type '(gnu gnu/linux gnu/kfreebsd))
  711. "If non-nil prepend ^ to the prefix passed to \"man -k\" for completion.
  712. The value should be nil if \"man -k ^PREFIX\" may omit some man
  713. pages whose names start with PREFIX.
  714. Currently, the default value depends on `system-type' and is
  715. non-nil where the standard man programs are known to behave
  716. properly. Setting the value to nil always gives correct results
  717. but computing the list of completions may take a bit longer.")
  718. (defun Man-parse-man-k ()
  719. "Parse \"man -k\" output and return the list of page names.
  720. The current buffer should contain the output of a command of the
  721. form \"man -k keyword\", which is traditionally also available with
  722. apropos(1).
  723. While POSIX man(1p) is a bit vague about what to expect here,
  724. this function tries to parse some commonly used formats, which
  725. can be described in the following informal way, with square brackets
  726. indicating optional parts and whitespace being interpreted
  727. somewhat loosely.
  728. foo[, bar [, ...]] [other stuff] (sec) - description
  729. foo(sec)[, bar(sec) [, ...]] [other stuff] - description"
  730. (goto-char (point-min))
  731. ;; See man-tests for data about which systems use which format (hopefully we
  732. ;; will be able to simplify the code if/when some of those formats aren't
  733. ;; used any more).
  734. (let (table)
  735. (while (search-forward-regexp "^\\([^ \t,\n]+\\)\\(.*?\\)\
  736. \\(?:[ \t]\\(([^ \t,\n]+?)\\)\\)?\\(?:[ \t]+- ?\\(.*\\)\\)?$" nil t)
  737. (let ((section (match-string 3))
  738. (description (match-string 4))
  739. (bound (match-end 2)))
  740. (goto-char (match-end 1))
  741. (while
  742. (progn
  743. ;; The first regexp grouping may already match the section
  744. ;; tacked on to the name, which is ok since for the formats we
  745. ;; claim to support the third (non-shy) grouping does not
  746. ;; match in this case, i.e., section is nil.
  747. (push (propertize (concat (match-string 1) section)
  748. 'help-echo description)
  749. table)
  750. (search-forward-regexp "\\=, *\\([^ \t,]+\\)" bound t)))))
  751. (nreverse table)))
  752. (defun Man-completion-table (string pred action)
  753. (cond
  754. ;; This ends up returning t for pretty much any string, and hence leads to
  755. ;; spurious "complete but not unique" messages. And since `man' doesn't
  756. ;; require-match anyway, there's not point being clever.
  757. ;;((eq action 'lambda) (not (string-match "([^)]*\\'" string)))
  758. ((equal string "-k")
  759. ;; Let SPC (minibuffer-complete-word) insert the space.
  760. (complete-with-action action '("-k ") string pred))
  761. (t
  762. (let ((table (cdr Man-completion-cache))
  763. (section nil)
  764. (prefix string))
  765. (when (string-match "\\`\\([[:digit:]].*?\\) " string)
  766. (setq section (match-string 1 string))
  767. (setq prefix (substring string (match-end 0))))
  768. (unless (and Man-completion-cache
  769. (string-prefix-p (car Man-completion-cache) prefix))
  770. (with-temp-buffer
  771. (setq default-directory "/") ;; in case inherited doesn't exist
  772. ;; Actually for my `man' the arg is a regexp.
  773. ;; POSIX says it must be ERE and "man-db" seems to agree,
  774. ;; whereas under macOS it seems to be BRE-style and doesn't
  775. ;; accept backslashes at all. Let's not bother to
  776. ;; quote anything.
  777. (let ((process-environment (copy-sequence process-environment)))
  778. (setenv "COLUMNS" "999") ;; don't truncate long names
  779. ;; manual-program might not even exist. And since it's
  780. ;; run differently in Man-getpage-in-background, an error
  781. ;; here may not necessarily mean that we'll also get an
  782. ;; error later.
  783. (ignore-errors
  784. (call-process manual-program nil '(t nil) nil
  785. "-k" (concat (when (or Man-man-k-use-anchor
  786. (string-equal prefix ""))
  787. "^")
  788. prefix))))
  789. (setq table (Man-parse-man-k)))
  790. ;; Cache the table for later reuse.
  791. (setq Man-completion-cache (cons prefix table)))
  792. ;; The table may contain false positives since the match is made
  793. ;; by "man -k" not just on the manpage's name.
  794. (if section
  795. (let ((re (concat "(" (regexp-quote section) ")\\'")))
  796. (dolist (comp (prog1 table (setq table nil)))
  797. (if (string-match re comp)
  798. (push (substring comp 0 (match-beginning 0)) table)))
  799. (completion-table-with-context (concat section " ") table
  800. prefix pred action))
  801. ;; If the current text looks like a possible section name,
  802. ;; then add a completion entry that just adds a space so SPC
  803. ;; can be used to insert a space.
  804. (if (string-match "\\`[[:digit:]]" string)
  805. (push (concat string " ") table))
  806. (let ((res (complete-with-action action table string pred)))
  807. ;; In case we're completing to a single name that exists in
  808. ;; several sections, the longest prefix will look like "foo(".
  809. (if (and (stringp res)
  810. (string-match "([^(]*\\'" res)
  811. ;; In case the paren was already in `prefix', don't
  812. ;; remove it.
  813. (> (match-beginning 0) (length prefix)))
  814. (substring res 0 (match-beginning 0))
  815. res)))))))
  816. ;;;###autoload
  817. (defun man (man-args)
  818. "Get a Un*x manual page and put it in a buffer.
  819. This command is the top-level command in the man package.
  820. It runs a Un*x command to retrieve and clean a manpage in the
  821. background and places the results in a `Man-mode' browsing
  822. buffer. The variable `Man-width' defines the number of columns in
  823. formatted manual pages. The buffer is displayed immediately.
  824. The variable `Man-notify-method' defines how the buffer is displayed.
  825. If a buffer already exists for this man page, it will be displayed
  826. without running the man command.
  827. For a manpage from a particular section, use either of the
  828. following. \"cat(1)\" is how cross-references appear and is
  829. passed to man as \"1 cat\".
  830. cat(1)
  831. 1 cat
  832. To see manpages from all sections related to a subject, use an
  833. \"all pages\" option (which might be \"-a\" if it's not the
  834. default), then step through with `Man-next-manpage' (\\<Man-mode-map>\\[Man-next-manpage]) etc.
  835. Add to `Man-switches' to make this option permanent.
  836. -a chmod
  837. An explicit filename can be given too. Use -l if it might
  838. otherwise look like a page name.
  839. /my/file/name.1.gz
  840. -l somefile.1
  841. An \"apropos\" query with -k gives a buffer of matching page
  842. names or descriptions. The pattern argument is usually an
  843. \"grep -E\" style regexp.
  844. -k pattern"
  845. (interactive
  846. (list (let* ((default-entry (Man-default-man-entry))
  847. ;; ignore case because that's friendly for bizarre
  848. ;; caps things like the X11 function names and because
  849. ;; "man" itself is case-insensitive on the command line
  850. ;; so you're accustomed not to bother about the case
  851. ;; ("man -k" is case-insensitive similarly, so the
  852. ;; table has everything available to complete)
  853. (completion-ignore-case t)
  854. Man-completion-cache ;Don't cache across calls.
  855. (input (completing-read
  856. (format "Manual entry%s"
  857. (if (string= default-entry "")
  858. ": "
  859. (format " (default %s): " default-entry)))
  860. 'Man-completion-table
  861. nil nil nil 'Man-topic-history default-entry)))
  862. (if (string= input "")
  863. (error "No man args given")
  864. input))))
  865. ;; Possibly translate the "subject(section)" syntax into the
  866. ;; "section subject" syntax and possibly downcase the section.
  867. (setq man-args (Man-translate-references man-args))
  868. (Man-getpage-in-background man-args))
  869. ;;;###autoload
  870. (defun man-follow (man-args)
  871. "Get a Un*x manual page of the item under point and put it in a buffer."
  872. (interactive (list (Man-default-man-entry)))
  873. (if (or (not man-args)
  874. (string= man-args ""))
  875. (error "No item under point")
  876. (man man-args)))
  877. (defmacro Man-start-calling (&rest body)
  878. "Start the man command in `body' after setting up the environment"
  879. `(let ((process-environment (copy-sequence process-environment))
  880. ;; The following is so Awk script gets \n intact
  881. ;; But don't prevent decoding of the outside.
  882. (coding-system-for-write 'raw-text-unix)
  883. ;; We must decode the output by a coding system that the
  884. ;; system's locale suggests in multibyte mode.
  885. (coding-system-for-read locale-coding-system)
  886. ;; Avoid possible error by using a directory that always exists.
  887. (default-directory
  888. (if (and (file-directory-p default-directory)
  889. (not (find-file-name-handler default-directory
  890. 'file-directory-p)))
  891. default-directory
  892. "/")))
  893. ;; Prevent any attempt to use display terminal fanciness.
  894. (setenv "TERM" "dumb")
  895. ;; In Debian Woody, at least, we get overlong lines under X
  896. ;; unless COLUMNS or MANWIDTH is set. This isn't a problem on
  897. ;; a tty. man(1) says:
  898. ;; MANWIDTH
  899. ;; If $MANWIDTH is set, its value is used as the line
  900. ;; length for which manual pages should be formatted.
  901. ;; If it is not set, manual pages will be formatted
  902. ;; with a line length appropriate to the current ter-
  903. ;; minal (using an ioctl(2) if available, the value of
  904. ;; $COLUMNS, or falling back to 80 characters if nei-
  905. ;; ther is available).
  906. (when (or window-system
  907. (not (or (getenv "MANWIDTH") (getenv "COLUMNS"))))
  908. ;; Since the page buffer is displayed beforehand,
  909. ;; we can select its window and get the window/frame width.
  910. (setenv "COLUMNS" (number-to-string
  911. (cond
  912. ((and (integerp Man-width) (> Man-width 0))
  913. Man-width)
  914. (Man-width
  915. (if (window-live-p (get-buffer-window (current-buffer) t))
  916. (with-selected-window (get-buffer-window (current-buffer) t)
  917. (frame-width))
  918. (frame-width)))
  919. (t
  920. (if (window-live-p (get-buffer-window (current-buffer) t))
  921. (with-selected-window (get-buffer-window (current-buffer) t)
  922. (window-width))
  923. (window-width)))))))
  924. ;; Since man-db 2.4.3-1, man writes plain text with no escape
  925. ;; sequences when stdout is not a tty. In 2.5.0, the following
  926. ;; env-var was added to allow control of this (see Debian Bug#340673).
  927. (setenv "MAN_KEEP_FORMATTING" "1")
  928. ,@body))
  929. (defun Man-getpage-in-background (topic)
  930. "Use TOPIC to build and fire off the manpage and cleaning command.
  931. Return the buffer in which the manpage will appear."
  932. (let* ((man-args topic)
  933. (bufname (concat "*Man " man-args "*"))
  934. (buffer (get-buffer bufname)))
  935. (if buffer
  936. (Man-notify-when-ready buffer)
  937. (require 'env)
  938. (message "Invoking %s %s in the background" manual-program man-args)
  939. (setq buffer (generate-new-buffer bufname))
  940. (with-current-buffer buffer
  941. (Man-notify-when-ready buffer)
  942. (setq buffer-undo-list t)
  943. (setq Man-original-frame (selected-frame))
  944. (setq Man-arguments man-args)
  945. (Man-mode)
  946. (setq mode-line-process
  947. (concat " " (propertize (if Man-fontify-manpage-flag
  948. "[formatting...]"
  949. "[cleaning...]")
  950. 'face 'mode-line-emphasis)))
  951. (Man-start-calling
  952. (if (fboundp 'make-process)
  953. (let ((proc (start-process
  954. manual-program buffer
  955. (if (memq system-type '(cygwin windows-nt))
  956. shell-file-name
  957. "sh")
  958. shell-command-switch
  959. (format (Man-build-man-command) man-args))))
  960. (set-process-sentinel proc 'Man-bgproc-sentinel)
  961. (set-process-filter proc 'Man-bgproc-filter))
  962. (let* ((inhibit-read-only t)
  963. (exit-status
  964. (call-process shell-file-name nil (list buffer nil) nil
  965. shell-command-switch
  966. (format (Man-build-man-command) man-args)))
  967. (msg ""))
  968. (or (and (numberp exit-status)
  969. (= exit-status 0))
  970. (and (numberp exit-status)
  971. (setq msg
  972. (format "exited abnormally with code %d"
  973. exit-status)))
  974. (setq msg exit-status))
  975. (if Man-fontify-manpage-flag
  976. (Man-fontify-manpage)
  977. (Man-cleanup-manpage))
  978. (Man-bgproc-sentinel bufname msg))))))
  979. buffer))
  980. (defun Man-update-manpage ()
  981. "Reformat current manpage by calling the man command again synchronously."
  982. (interactive)
  983. (when (eq Man-arguments nil)
  984. ;;this shouldn't happen unless it is not in a Man buffer."
  985. (error "Man-arguments not initialized"))
  986. (let ((old-pos (point))
  987. (text (current-word))
  988. (old-size (buffer-size))
  989. (inhibit-read-only t)
  990. (buffer-read-only nil))
  991. (erase-buffer)
  992. (Man-start-calling
  993. (call-process shell-file-name nil (list (current-buffer) nil) nil
  994. shell-command-switch
  995. (format (Man-build-man-command) Man-arguments)))
  996. (if Man-fontify-manpage-flag
  997. (Man-fontify-manpage)
  998. (Man-cleanup-manpage))
  999. (goto-char old-pos)
  1000. ;;restore the point, not strictly right.
  1001. (unless (or (eq text nil) (= old-size (buffer-size)))
  1002. (let ((case-fold-search nil))
  1003. (if (> old-size (buffer-size))
  1004. (search-backward text nil t))
  1005. (search-forward text nil t)))))
  1006. (defun Man-notify-when-ready (man-buffer)
  1007. "Notify the user when MAN-BUFFER is ready.
  1008. See the variable `Man-notify-method' for the different notification behaviors."
  1009. (let ((saved-frame (with-current-buffer man-buffer
  1010. Man-original-frame)))
  1011. (pcase Man-notify-method
  1012. (`newframe
  1013. ;; Since we run asynchronously, perhaps while Emacs is waiting
  1014. ;; for input, we must not leave a different buffer current. We
  1015. ;; can't rely on the editor command loop to reselect the
  1016. ;; selected window's buffer.
  1017. (save-excursion
  1018. (let ((frame (make-frame Man-frame-parameters)))
  1019. (set-window-buffer (frame-selected-window frame) man-buffer)
  1020. (set-window-dedicated-p (frame-selected-window frame) t)
  1021. (or (display-multi-frame-p frame)
  1022. (select-frame frame)))))
  1023. (`pushy
  1024. (switch-to-buffer man-buffer))
  1025. (`bully
  1026. (and (frame-live-p saved-frame)
  1027. (select-frame saved-frame))
  1028. (pop-to-buffer man-buffer)
  1029. (delete-other-windows))
  1030. (`aggressive
  1031. (and (frame-live-p saved-frame)
  1032. (select-frame saved-frame))
  1033. (pop-to-buffer man-buffer))
  1034. (`friendly
  1035. (and (frame-live-p saved-frame)
  1036. (select-frame saved-frame))
  1037. (display-buffer man-buffer 'not-this-window))
  1038. (`polite
  1039. (beep)
  1040. (message "Manual buffer %s is ready" (buffer-name man-buffer)))
  1041. (`quiet
  1042. (message "Manual buffer %s is ready" (buffer-name man-buffer)))
  1043. (_ ;; meek
  1044. (message ""))
  1045. )))
  1046. (defun Man-softhyphen-to-minus ()
  1047. ;; \255 is SOFT HYPHEN in Latin-N. Versions of Debian man, at
  1048. ;; least, emit it even when not in a Latin-N locale.
  1049. (unless (eq t (compare-strings "latin-" 0 nil
  1050. current-language-environment 0 6 t))
  1051. (goto-char (point-min))
  1052. (let ((str "\255"))
  1053. (if enable-multibyte-characters
  1054. (setq str (string-as-multibyte str)))
  1055. (while (search-forward str nil t) (replace-match "-")))))
  1056. (defun Man-fontify-manpage ()
  1057. "Convert overstriking and underlining to the correct fonts.
  1058. Same for the ANSI bold and normal escape sequences."
  1059. (interactive)
  1060. (goto-char (point-min))
  1061. ;; Fontify ANSI escapes.
  1062. (let ((ansi-color-apply-face-function
  1063. (lambda (beg end face)
  1064. (when face
  1065. (put-text-property beg end 'face face))))
  1066. (ansi-color-map Man-ansi-color-map))
  1067. (ansi-color-apply-on-region (point-min) (point-max)))
  1068. ;; Other highlighting.
  1069. (let ((buffer-undo-list t))
  1070. (if (< (buffer-size) (position-bytes (point-max)))
  1071. ;; Multibyte characters exist.
  1072. (progn
  1073. (goto-char (point-min))
  1074. (while (and (search-forward "__\b\b" nil t) (not (eobp)))
  1075. (backward-delete-char 4)
  1076. (put-text-property (point) (1+ (point)) 'face 'Man-underline))
  1077. (goto-char (point-min))
  1078. (while (search-forward "\b\b__" nil t)
  1079. (backward-delete-char 4)
  1080. (put-text-property (1- (point)) (point) 'face 'Man-underline))))
  1081. (goto-char (point-min))
  1082. (while (and (search-forward "_\b" nil t) (not (eobp)))
  1083. (backward-delete-char 2)
  1084. (put-text-property (point) (1+ (point)) 'face 'Man-underline))
  1085. (goto-char (point-min))
  1086. (while (search-forward "\b_" nil t)
  1087. (backward-delete-char 2)
  1088. (put-text-property (1- (point)) (point) 'face 'Man-underline))
  1089. (goto-char (point-min))
  1090. (while (re-search-forward "\\(.\\)\\(\b+\\1\\)+" nil t)
  1091. (replace-match "\\1")
  1092. (put-text-property (1- (point)) (point) 'face 'Man-overstrike))
  1093. (goto-char (point-min))
  1094. (while (re-search-forward "o\b\\+\\|\\+\bo" nil t)
  1095. (replace-match "o")
  1096. (put-text-property (1- (point)) (point) 'face 'bold))
  1097. (goto-char (point-min))
  1098. (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t)
  1099. (replace-match "+")
  1100. (put-text-property (1- (point)) (point) 'face 'bold))
  1101. ;; When the header is longer than the manpage name, groff tries to
  1102. ;; condense it to a shorter line interspersed with ^H. Remove ^H with
  1103. ;; their preceding chars (but don't put Man-overstrike). (Bug#5566)
  1104. (goto-char (point-min))
  1105. (while (re-search-forward ".\b" nil t) (backward-delete-char 2))
  1106. (goto-char (point-min))
  1107. ;; Try to recognize common forms of cross references.
  1108. (Man-highlight-references)
  1109. (Man-softhyphen-to-minus)
  1110. (goto-char (point-min))
  1111. (while (re-search-forward Man-heading-regexp nil t)
  1112. (put-text-property (match-beginning 0)
  1113. (match-end 0)
  1114. 'face 'Man-overstrike))))
  1115. (defun Man-highlight-references (&optional xref-man-type)
  1116. "Highlight the references on mouse-over.
  1117. References include items in the SEE ALSO section,
  1118. header file (#include <foo.h>), and files in FILES.
  1119. If optional argument XREF-MAN-TYPE is non-nil, it used as the
  1120. button type for items in SEE ALSO section. If it is nil, the
  1121. default type, `Man-xref-man-page' is used for the buttons."
  1122. ;; `Man-highlight-references' is used from woman.el, too.
  1123. ;; woman.el doesn't set `Man-arguments'.
  1124. (unless Man-arguments
  1125. (setq Man-arguments ""))
  1126. (if (string-match "-k " Man-arguments)
  1127. (progn
  1128. (Man-highlight-references0 nil Man-reference-regexp 1
  1129. 'Man-default-man-entry
  1130. (or xref-man-type 'Man-xref-man-page))
  1131. (Man-highlight-references0 nil Man-apropos-regexp 1
  1132. 'Man-default-man-entry
  1133. (or xref-man-type 'Man-xref-man-page)))
  1134. (Man-highlight-references0 Man-see-also-regexp Man-reference-regexp 1
  1135. 'Man-default-man-entry
  1136. (or xref-man-type 'Man-xref-man-page))
  1137. (Man-highlight-references0 Man-synopsis-regexp Man-header-regexp 0 2
  1138. 'Man-xref-header-file)
  1139. (Man-highlight-references0 Man-files-regexp Man-normal-file-regexp 0 0
  1140. 'Man-xref-normal-file)))
  1141. (defun Man-highlight-references0 (start-section regexp button-pos target type)
  1142. ;; Based on `Man-build-references-alist'
  1143. (when (or (null start-section)
  1144. (Man-find-section start-section))
  1145. (let ((end (if start-section
  1146. (progn
  1147. (forward-line 1)
  1148. (back-to-indentation)
  1149. (save-excursion
  1150. (Man-next-section 1)
  1151. (point)))
  1152. (goto-char (point-min))
  1153. nil)))
  1154. (while (re-search-forward regexp end t)
  1155. ;; An overlay button is preferable because the underlying text
  1156. ;; may have text property highlights (Bug#7881).
  1157. (make-button
  1158. (match-beginning button-pos)
  1159. (match-end button-pos)
  1160. 'type type
  1161. 'Man-target-string (cond
  1162. ((numberp target)
  1163. (match-string target))
  1164. ((functionp target)
  1165. target)
  1166. (t nil)))))))
  1167. (defun Man-cleanup-manpage (&optional interactive)
  1168. "Remove overstriking and underlining from the current buffer.
  1169. Normally skip any jobs that should have been done by the sed script,
  1170. but when called interactively, do those jobs even if the sed
  1171. script would have done them."
  1172. (interactive "p")
  1173. (if (or interactive (not Man-sed-script))
  1174. (progn
  1175. (goto-char (point-min))
  1176. (while (search-forward "_\b" nil t) (backward-delete-char 2))
  1177. (goto-char (point-min))
  1178. (while (search-forward "\b_" nil t) (backward-delete-char 2))
  1179. (goto-char (point-min))
  1180. (while (re-search-forward "\\(.\\)\\(\b\\1\\)+" nil t)
  1181. (replace-match "\\1"))
  1182. (goto-char (point-min))
  1183. (while (re-search-forward "\e\\[[0-9]+m" nil t) (replace-match ""))
  1184. (goto-char (point-min))
  1185. (while (re-search-forward "o\b\\+\\|\\+\bo" nil t) (replace-match "o"))
  1186. ))
  1187. (goto-char (point-min))
  1188. (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t) (replace-match "+"))
  1189. ;; When the header is longer than the manpage name, groff tries to
  1190. ;; condense it to a shorter line interspersed with ^H. Remove ^H with
  1191. ;; their preceding chars (but don't put Man-overstrike). (Bug#5566)
  1192. (goto-char (point-min))
  1193. (while (re-search-forward ".\b" nil t) (backward-delete-char 2))
  1194. (Man-softhyphen-to-minus))
  1195. (defun Man-bgproc-filter (process string)
  1196. "Manpage background process filter.
  1197. When manpage command is run asynchronously, PROCESS is the process
  1198. object for the manpage command; when manpage command is run
  1199. synchronously, PROCESS is the name of the buffer where the manpage
  1200. command is run. Second argument STRING is the entire string of output."
  1201. (save-excursion
  1202. (let ((Man-buffer (process-buffer process)))
  1203. (if (null (buffer-name Man-buffer)) ;; deleted buffer
  1204. (set-process-buffer process nil)
  1205. (with-current-buffer Man-buffer
  1206. (let ((inhibit-read-only t)
  1207. (beg (marker-position (process-mark process))))
  1208. (save-excursion
  1209. (goto-char beg)
  1210. (insert string)
  1211. (save-restriction
  1212. (narrow-to-region
  1213. (save-excursion
  1214. (goto-char beg)
  1215. (line-beginning-position))
  1216. (point))
  1217. (if Man-fontify-manpage-flag
  1218. (Man-fontify-manpage)
  1219. (Man-cleanup-manpage)))
  1220. (set-marker (process-mark process) (point-max)))))))))
  1221. (defun Man-bgproc-sentinel (process msg)
  1222. "Manpage background process sentinel.
  1223. When manpage command is run asynchronously, PROCESS is the process
  1224. object for the manpage command; when manpage command is run
  1225. synchronously, PROCESS is the name of the buffer where the manpage
  1226. command is run. Second argument MSG is the exit message of the
  1227. manpage command."
  1228. (let ((Man-buffer (if (stringp process) (get-buffer process)
  1229. (process-buffer process)))
  1230. (delete-buff nil)
  1231. (err-mess nil))
  1232. (if (null (buffer-name Man-buffer)) ;; deleted buffer
  1233. (or (stringp process)
  1234. (set-process-buffer process nil))
  1235. (with-current-buffer Man-buffer
  1236. (save-excursion
  1237. (let ((case-fold-search nil))
  1238. (goto-char (point-min))
  1239. (cond ((or (looking-at "No \\(manual \\)*entry for")
  1240. (looking-at "[^\n]*: nothing appropriate$"))
  1241. (setq err-mess (buffer-substring (point)
  1242. (progn
  1243. (end-of-line) (point)))
  1244. delete-buff t))
  1245. ;; "-k foo", successful exit, but no output (from man-db)
  1246. ;; ENHANCE-ME: share the check for -k with
  1247. ;; `Man-highlight-references'. The \\s- bits here are
  1248. ;; meant to allow for multiple options with -k among them.
  1249. ((and (string-match "\\(\\`\\|\\s-\\)-k\\s-" Man-arguments)
  1250. (eq (process-status process) 'exit)
  1251. (= (process-exit-status process) 0)
  1252. (= (point-min) (point-max)))
  1253. (setq err-mess (format "%s: no matches" Man-arguments)
  1254. delete-buff t))
  1255. ((or (stringp process)
  1256. (not (and (eq (process-status process) 'exit)
  1257. (= (process-exit-status process) 0))))
  1258. (or (zerop (length msg))
  1259. (progn
  1260. (setq err-mess
  1261. (concat (buffer-name Man-buffer)
  1262. ": process "
  1263. (let ((eos (1- (length msg))))
  1264. (if (= (aref msg eos) ?\n)
  1265. (substring msg 0 eos) msg))))
  1266. (goto-char (point-max))
  1267. (insert (format "\nprocess %s" msg))))
  1268. ))
  1269. (if delete-buff
  1270. (if (window-live-p (get-buffer-window Man-buffer t))
  1271. (quit-restore-window
  1272. (get-buffer-window Man-buffer t) 'kill)
  1273. (kill-buffer Man-buffer))
  1274. (run-hooks 'Man-cooked-hook)
  1275. (Man-build-page-list)
  1276. (Man-strip-page-headers)
  1277. (Man-unindent)
  1278. (Man-goto-page 1 t)
  1279. (if (not Man-page-list)
  1280. (let ((args Man-arguments))
  1281. (if (window-live-p (get-buffer-window (current-buffer) t))
  1282. (quit-restore-window
  1283. (get-buffer-window (current-buffer) t) 'kill)
  1284. (kill-buffer (current-buffer)))
  1285. ;; Entries hyphenated due to the window's width
  1286. ;; won't be found in the man database, so remove
  1287. ;; the hyphenation -- assuming Groff hyphenates
  1288. ;; either with hyphen-minus (ASCII 45, #x2d),
  1289. ;; hyphen (#x2010) or soft hyphen (#xad) -- and
  1290. ;; look again.
  1291. (if (string-match "[-‐­]" args)
  1292. (let ((str (replace-match "" nil nil args)))
  1293. (Man-getpage-in-background str))
  1294. (message "Can't find the %s manpage"
  1295. (Man-page-from-arguments args))))
  1296. (if Man-fontify-manpage-flag
  1297. (message "%s man page formatted"
  1298. (Man-page-from-arguments Man-arguments))
  1299. (message "%s man page cleaned up"
  1300. (Man-page-from-arguments Man-arguments)))
  1301. (unless (and (processp process)
  1302. (not (eq (process-status process) 'exit)))
  1303. (setq mode-line-process nil))
  1304. (set-buffer-modified-p nil)))))
  1305. (if err-mess
  1306. (message "%s" err-mess))
  1307. ))))
  1308. (defun Man-page-from-arguments (args)
  1309. ;; Skip arguments and only print the page name.
  1310. (mapconcat
  1311. 'identity
  1312. (delete nil
  1313. (mapcar
  1314. (lambda (elem)
  1315. (and (not (string-match "^-" elem))
  1316. elem))
  1317. (split-string args " ")))
  1318. " "))
  1319. ;; ======================================================================
  1320. ;; set up manual mode in buffer and build alists
  1321. (defvar bookmark-make-record-function)
  1322. (define-derived-mode Man-mode special-mode "Man"
  1323. "A mode for browsing Un*x manual pages.
  1324. The following man commands are available in the buffer. Try
  1325. \"\\[describe-key] <key> RET\" for more information:
  1326. \\[man] Prompt to retrieve a new manpage.
  1327. \\[Man-follow-manual-reference] Retrieve reference in SEE ALSO section.
  1328. \\[Man-next-manpage] Jump to next manpage in circular list.
  1329. \\[Man-previous-manpage] Jump to previous manpage in circular list.
  1330. \\[Man-next-section] Jump to next manpage section.
  1331. \\[Man-previous-section] Jump to previous manpage section.
  1332. \\[Man-goto-section] Go to a manpage section.
  1333. \\[Man-goto-see-also-section] Jumps to the SEE ALSO manpage section.
  1334. \\[quit-window] Deletes the manpage window, bury its buffer.
  1335. \\[Man-kill] Deletes the manpage window, kill its buffer.
  1336. \\[describe-mode] Prints this help text.
  1337. The following variables may be of some use. Try
  1338. \"\\[describe-variable] <variable-name> RET\" for more information:
  1339. `Man-notify-method' What happens when manpage is ready to display.
  1340. `Man-downcase-section-letters-flag' Force section letters to lower case.
  1341. `Man-circular-pages-flag' Treat multiple manpage list as circular.
  1342. `Man-section-translations-alist' List of section numbers and their Un*x equiv.
  1343. `Man-filter-list' Background manpage filter command.
  1344. `Man-mode-map' Keymap bindings for Man mode buffers.
  1345. `Man-mode-hook' Normal hook run on entry to Man mode.
  1346. `Man-section-regexp' Regexp describing manpage section letters.
  1347. `Man-heading-regexp' Regexp describing section headers.
  1348. `Man-see-also-regexp' Regexp for SEE ALSO section (or your equiv).
  1349. `Man-first-heading-regexp' Regexp for first heading on a manpage.
  1350. `Man-reference-regexp' Regexp matching a references in SEE ALSO.
  1351. `Man-switches' Background `man' command switches.
  1352. The following key bindings are currently in effect in the buffer:
  1353. \\{Man-mode-map}"
  1354. (setq buffer-auto-save-file-name nil
  1355. mode-line-buffer-identification
  1356. (list (default-value 'mode-line-buffer-identification)
  1357. " {" 'Man-page-mode-string "}")
  1358. truncate-lines t)
  1359. (buffer-disable-undo)
  1360. (auto-fill-mode -1)
  1361. (setq imenu-generic-expression (list (list nil Man-heading-regexp 0)))
  1362. (imenu-add-to-menubar man-imenu-title)
  1363. (set (make-local-variable 'outline-regexp) Man-heading-regexp)
  1364. (set (make-local-variable 'outline-level) (lambda () 1))
  1365. (set (make-local-variable 'bookmark-make-record-function)
  1366. 'Man-bookmark-make-record))
  1367. (defsubst Man-build-section-alist ()
  1368. "Build the list of manpage sections."
  1369. (setq Man--sections nil)
  1370. (goto-char (point-min))
  1371. (let ((case-fold-search nil))
  1372. (while (re-search-forward Man-heading-regexp (point-max) t)
  1373. (let ((section (match-string 1)))
  1374. (unless (member section Man--sections)
  1375. (push section Man--sections)))
  1376. (forward-line 1))))
  1377. (defsubst Man-build-references-alist ()
  1378. "Build the list of references (in the SEE ALSO section)."
  1379. (setq Man--refpages nil)
  1380. (save-excursion
  1381. (if (Man-find-section Man-see-also-regexp)
  1382. (let ((start (progn (forward-line 1) (point)))
  1383. (end (progn
  1384. (Man-next-section 1)
  1385. (point)))
  1386. hyphenated
  1387. (runningpoint -1))
  1388. (save-restriction
  1389. (narrow-to-region start end)
  1390. (goto-char (point-min))
  1391. (back-to-indentation)
  1392. (while (and (not (eobp)) (/= (point) runningpoint))
  1393. (setq runningpoint (point))
  1394. (if (re-search-forward Man-hyphenated-reference-regexp end t)
  1395. (let* ((word (match-string 0))
  1396. (len (1- (length word))))
  1397. (if hyphenated
  1398. (setq word (concat hyphenated word)
  1399. hyphenated nil
  1400. ;; Update len, in case a reference spans
  1401. ;; more than two lines (paranoia).
  1402. len (1- (length word))))
  1403. (if (memq (aref word len) '(?- ?­))
  1404. (setq hyphenated (substring word 0 len)))
  1405. (and (string-match Man-reference-regexp word)
  1406. (not (member word Man--refpages))
  1407. (push word Man--refpages))))
  1408. (skip-chars-forward " \t\n,"))))))
  1409. (setq Man--refpages (nreverse Man--refpages)))
  1410. (defun Man-build-page-list ()
  1411. "Build the list of separate manpages in the buffer."
  1412. (setq Man-page-list nil)
  1413. (let ((page-start (point-min))
  1414. (page-end (point-max))
  1415. (header ""))
  1416. (goto-char page-start)
  1417. (while (not (eobp))
  1418. (setq header
  1419. (if (looking-at Man-page-header-regexp)
  1420. (match-string 1)
  1421. nil))
  1422. ;; Go past both the current and the next Man-first-heading-regexp
  1423. (if (re-search-forward Man-first-heading-regexp nil 'move 2)
  1424. (let ((p (progn (beginning-of-line) (point))))
  1425. ;; We assume that the page header is delimited by blank
  1426. ;; lines and that it contains at most one blank line. So
  1427. ;; if we back by three blank lines we will be sure to be
  1428. ;; before the page header but not before the possible
  1429. ;; previous page header.
  1430. (search-backward "\n\n" nil t 3)
  1431. (if (re-search-forward Man-page-header-regexp p 'move)
  1432. (beginning-of-line))))
  1433. (setq page-end (point))
  1434. (setq Man-page-list (append Man-page-list
  1435. (list (list (copy-marker page-start)
  1436. (copy-marker page-end)
  1437. header))))
  1438. (setq page-start page-end)
  1439. )))
  1440. (defun Man-strip-page-headers ()
  1441. "Strip all the page headers but the first from the manpage."
  1442. (let ((inhibit-read-only t)
  1443. (case-fold-search nil)
  1444. (header ""))
  1445. (dolist (page Man-page-list)
  1446. (and (nth 2 page)
  1447. (goto-char (car page))
  1448. (re-search-forward Man-first-heading-regexp nil t)
  1449. (setq header (buffer-substring (car page) (match-beginning 0)))
  1450. ;; Since the awk script collapses all successive blank
  1451. ;; lines into one, and since we don't want to get rid of
  1452. ;; the fast awk script, one must choose between adding
  1453. ;; spare blank lines between pages when there were none and
  1454. ;; deleting blank lines at page boundaries when there were
  1455. ;; some. We choose the first, so we comment the following
  1456. ;; line.
  1457. ;; (setq header (concat "\n" header)))
  1458. (while (search-forward header (nth 1 page) t)
  1459. (replace-match ""))))))
  1460. (defun Man-unindent ()
  1461. "Delete the leading spaces that indent the manpage."
  1462. (let ((inhibit-read-only t)
  1463. (case-fold-search nil))
  1464. (dolist (page Man-page-list)
  1465. (let ((indent "")
  1466. (nindent 0))
  1467. (narrow-to-region (car page) (car (cdr page)))
  1468. (if Man-uses-untabify-flag
  1469. ;; The space characters inserted by `untabify' inherit
  1470. ;; sticky text properties, which is unnecessary and looks
  1471. ;; ugly with underlining (Bug#11408).
  1472. (let ((text-property-default-nonsticky
  1473. (cons '(face . t) text-property-default-nonsticky)))
  1474. (untabify (point-min) (point-max))))
  1475. (if (catch 'unindent
  1476. (goto-char (point-min))
  1477. (if (not (re-search-forward Man-first-heading-regexp nil t))
  1478. (throw 'unindent nil))
  1479. (beginning-of-line)
  1480. (setq indent (buffer-substring (point)
  1481. (progn
  1482. (skip-chars-forward " ")
  1483. (point))))
  1484. (setq nindent (length indent))
  1485. (if (zerop nindent)
  1486. (throw 'unindent nil))
  1487. (setq indent (concat indent "\\|$"))
  1488. (goto-char (point-min))
  1489. (while (not (eobp))
  1490. (if (looking-at indent)
  1491. (forward-line 1)
  1492. (throw 'unindent nil)))
  1493. (goto-char (point-min)))
  1494. (while (not (eobp))
  1495. (or (eolp)
  1496. (delete-char nindent))
  1497. (forward-line 1)))
  1498. ))))
  1499. ;; ======================================================================
  1500. ;; Man mode commands
  1501. (defun Man-next-section (n)
  1502. "Move point to Nth next section (default 1)."
  1503. (interactive "p")
  1504. (let ((case-fold-search nil)
  1505. (start (point)))
  1506. (if (looking-at Man-heading-regexp)
  1507. (forward-line 1))
  1508. (if (re-search-forward Man-heading-regexp (point-max) t n)
  1509. (beginning-of-line)
  1510. (goto-char (point-max))
  1511. ;; The last line doesn't belong to any section.
  1512. (forward-line -1))
  1513. ;; But don't move back from the starting point (can happen if `start'
  1514. ;; is somewhere on the last line).
  1515. (if (< (point) start) (goto-char start))))
  1516. (defun Man-previous-section (n)
  1517. "Move point to Nth previous section (default 1)."
  1518. (interactive "p")
  1519. (let ((case-fold-search nil))
  1520. (if (looking-at Man-heading-regexp)
  1521. (forward-line -1))
  1522. (if (re-search-backward Man-heading-regexp (point-min) t n)
  1523. (beginning-of-line)
  1524. (goto-char (point-min)))))
  1525. (defun Man-find-section (section)
  1526. "Move point to SECTION if it exists, otherwise don't move point.
  1527. Returns t if section is found, nil otherwise."
  1528. (let ((curpos (point))
  1529. (case-fold-search nil))
  1530. (goto-char (point-min))
  1531. (if (re-search-forward (concat "^" section) (point-max) t)
  1532. (progn (beginning-of-line) t)
  1533. (goto-char curpos)
  1534. nil)
  1535. ))
  1536. (defvar Man--last-section nil)
  1537. (defun Man-goto-section (section)
  1538. "Move point to SECTION."
  1539. (interactive
  1540. (let* ((default (if (member Man--last-section Man--sections)
  1541. Man--last-section
  1542. (car Man--sections)))
  1543. (completion-ignore-case t)
  1544. (prompt (concat "Go to section (default " default "): "))
  1545. (chosen (completing-read prompt Man--sections
  1546. nil nil nil nil default)))
  1547. (list chosen)))
  1548. (setq Man--last-section section)
  1549. (unless (Man-find-section section)
  1550. (error "Section %s not found" section)))
  1551. (defun Man-goto-see-also-section ()
  1552. "Move point to the \"SEE ALSO\" section.
  1553. Actually the section moved to is described by `Man-see-also-regexp'."
  1554. (interactive)
  1555. (if (not (Man-find-section Man-see-also-regexp))
  1556. (error "%s" (concat "No " Man-see-also-regexp
  1557. " section found in the current manpage"))))
  1558. (defun Man-possibly-hyphenated-word ()
  1559. "Return a possibly hyphenated word at point.
  1560. If the word starts at the first non-whitespace column, and the
  1561. previous line ends with a hyphen, return the last word on the previous
  1562. line instead. Thus, if a reference to \"tcgetpgrp(3V)\" is hyphenated
  1563. as \"tcgetp-grp(3V)\", and point is at \"grp(3V)\", we return
  1564. \"tcgetp-\" instead of \"grp\"."
  1565. (save-excursion
  1566. (skip-syntax-backward "w()")
  1567. (skip-chars-forward " \t")
  1568. (let ((beg (point))
  1569. (word (current-word)))
  1570. (when (eq beg (save-excursion
  1571. (back-to-indentation)
  1572. (point)))
  1573. (end-of-line 0)
  1574. (if (eq (char-before) ?-)
  1575. (setq word (current-word))))
  1576. word)))
  1577. (defvar Man--last-refpage nil)
  1578. (defun Man-follow-manual-reference (reference)
  1579. "Get one of the manpages referred to in the \"SEE ALSO\" section.
  1580. Specify which REFERENCE to use; default is based on word at point."
  1581. (interactive
  1582. (if (not Man--refpages)
  1583. (error "There are no references in the current man page")
  1584. (list
  1585. (let* ((default (or
  1586. (car (all-completions
  1587. (let ((word
  1588. (or (Man-possibly-hyphenated-word)
  1589. "")))
  1590. ;; strip a trailing '-':
  1591. (if (string-match "-$" word)
  1592. (substring word 0
  1593. (match-beginning 0))
  1594. word))
  1595. Man--refpages))
  1596. (if (member Man--last-refpage Man--refpages)
  1597. Man--last-refpage
  1598. (car Man--refpages))))
  1599. (defaults
  1600. (mapcar 'substring-no-properties
  1601. (cons default Man--refpages)))
  1602. (prompt (concat "Refer to (default " default "): "))
  1603. (chosen (completing-read prompt Man--refpages
  1604. nil nil nil nil defaults)))
  1605. chosen))))
  1606. (if (not Man--refpages)
  1607. (error "Can't find any references in the current manpage")
  1608. (setq Man--last-refpage reference)
  1609. (Man-getpage-in-background
  1610. (Man-translate-references reference))))
  1611. (defun Man-kill ()
  1612. "Kill the buffer containing the manpage."
  1613. (interactive)
  1614. (quit-window t))
  1615. (defun Man-goto-page (page &optional noerror)
  1616. "Go to the manual page on page PAGE."
  1617. (interactive
  1618. (if (not Man-page-list)
  1619. (error "Not a man page buffer")
  1620. (if (= (length Man-page-list) 1)
  1621. (error "You're looking at the only manpage in the buffer")
  1622. (list (read-minibuffer (format "Go to manpage [1-%d]: "
  1623. (length Man-page-list)))))))
  1624. (if (and (not Man-page-list) (not noerror))
  1625. (error "Not a man page buffer"))
  1626. (when Man-page-list
  1627. (if (or (< page 1)
  1628. (> page (length Man-page-list)))
  1629. (user-error "No manpage %d found" page))
  1630. (let* ((page-range (nth (1- page) Man-page-list))
  1631. (page-start (car page-range))
  1632. (page-end (car (cdr page-range))))
  1633. (setq Man-current-page page
  1634. Man-page-mode-string (Man-make-page-mode-string))
  1635. (widen)
  1636. (goto-char page-start)
  1637. (narrow-to-region page-start page-end)
  1638. (Man-build-section-alist)
  1639. (Man-build-references-alist)
  1640. (goto-char (point-min)))))
  1641. (defun Man-next-manpage ()
  1642. "Find the next manpage entry in the buffer."
  1643. (interactive)
  1644. (if (= (length Man-page-list) 1)
  1645. (error "This is the only manpage in the buffer"))
  1646. (if (< Man-current-page (length Man-page-list))
  1647. (Man-goto-page (1+ Man-current-page))
  1648. (if Man-circular-pages-flag
  1649. (Man-goto-page 1)
  1650. (error "You're looking at the last manpage in the buffer"))))
  1651. (defun Man-previous-manpage ()
  1652. "Find the previous manpage entry in the buffer."
  1653. (interactive)
  1654. (if (= (length Man-page-list) 1)
  1655. (error "This is the only manpage in the buffer"))
  1656. (if (> Man-current-page 1)
  1657. (Man-goto-page (1- Man-current-page))
  1658. (if Man-circular-pages-flag
  1659. (Man-goto-page (length Man-page-list))
  1660. (error "You're looking at the first manpage in the buffer"))))
  1661. ;; Header file support
  1662. (defun Man-view-header-file (file)
  1663. "View a header file specified by FILE from `Man-header-file-path'."
  1664. (let ((path Man-header-file-path)
  1665. complete-path)
  1666. (while path
  1667. (setq complete-path (expand-file-name file (car path))
  1668. path (cdr path))
  1669. (if (file-readable-p complete-path)
  1670. (progn (view-file complete-path)
  1671. (setq path nil))
  1672. (setq complete-path nil)))
  1673. complete-path))
  1674. ;;; Bookmark Man Support
  1675. (declare-function bookmark-make-record-default
  1676. "bookmark" (&optional no-file no-context posn))
  1677. (declare-function bookmark-prop-get "bookmark" (bookmark prop))
  1678. (declare-function bookmark-default-handler "bookmark" (bmk))
  1679. (declare-function bookmark-get-bookmark-record "bookmark" (bmk))
  1680. (defun Man-default-bookmark-title ()
  1681. "Default bookmark name for Man or WoMan pages.
  1682. Uses `Man-name-local-regexp'."
  1683. (save-excursion
  1684. (goto-char (point-min))
  1685. (when (re-search-forward Man-name-local-regexp nil t)
  1686. (skip-chars-forward "\n\t ")
  1687. (buffer-substring-no-properties (point) (line-end-position)))))
  1688. (defun Man-bookmark-make-record ()
  1689. "Make a bookmark entry for a Man buffer."
  1690. `(,(Man-default-bookmark-title)
  1691. ,@(bookmark-make-record-default 'no-file)
  1692. (location . ,(concat "man " Man-arguments))
  1693. (man-args . ,Man-arguments)
  1694. (handler . Man-bookmark-jump)))
  1695. ;;;###autoload
  1696. (defun Man-bookmark-jump (bookmark)
  1697. "Default bookmark handler for Man buffers."
  1698. (let* ((man-args (bookmark-prop-get bookmark 'man-args))
  1699. ;; Let bookmark.el do the window handling.
  1700. ;; This let-binding needs to be active during the call to both
  1701. ;; Man-getpage-in-background and accept-process-output.
  1702. (Man-notify-method 'meek)
  1703. (buf (Man-getpage-in-background man-args))
  1704. (proc (get-buffer-process buf)))
  1705. (while (and proc (eq (process-status proc) 'run))
  1706. (accept-process-output proc))
  1707. (bookmark-default-handler
  1708. `("" (buffer . ,buf) . ,(bookmark-get-bookmark-record bookmark)))))
  1709. ;; Init the man package variables, if not already done.
  1710. (Man-init-defvars)
  1711. (provide 'man)
  1712. ;;; man.el ends here