newcomment.el 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. ;;; newcomment.el --- (un)comment regions of buffers -*- lexical-binding: t -*-
  2. ;; Copyright (C) 1999-2017 Free Software Foundation, Inc.
  3. ;; Author: code extracted from Emacs-20's simple.el
  4. ;; Maintainer: Stefan Monnier <monnier@iro.umontreal.ca>
  5. ;; Keywords: comment uncomment
  6. ;; Package: emacs
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; This library contains functions and variables for commenting and
  20. ;; uncommenting source code.
  21. ;; Prior to calling any `comment-*' function, you should ensure that
  22. ;; `comment-normalize-vars' is first called to set up the appropriate
  23. ;; variables; except for the `comment-*' commands, which call
  24. ;; `comment-normalize-vars' automatically as a subroutine.
  25. ;;; Bugs:
  26. ;; - boxed comments in Perl are not properly uncommented because they are
  27. ;; uncommented one-line at a time.
  28. ;; - nested comments in sgml-mode are not properly quoted.
  29. ;; - single-char nestable comment-start can only do the "\\s<+" stuff
  30. ;; if the corresponding closing marker happens to be right.
  31. ;; - uncomment-region with a numeric argument can render multichar
  32. ;; comment markers invalid.
  33. ;; - comment-indent or comment-region when called inside a comment
  34. ;; will happily break the surrounding comment.
  35. ;; - comment-quote-nested will not (un)quote properly all nested comment
  36. ;; markers if there are more than just comment-start and comment-end.
  37. ;; For example, in Pascal where {...*) and (*...} are possible.
  38. ;;; Todo:
  39. ;; - rebox.el-style refill.
  40. ;; - quantized steps in comment-alignment.
  41. ;; - try to align tail comments.
  42. ;; - check what c-comment-line-break-function has to say.
  43. ;; - spill auto-fill of comments onto the end of the next line.
  44. ;; - uncomment-region with a consp (for blocks) or somehow make the
  45. ;; deletion of continuation markers less dangerous.
  46. ;; - drop block-comment-<foo> unless it's really used.
  47. ;; - uncomment-region on a subpart of a comment.
  48. ;; - support gnu-style "multi-line with space in continue".
  49. ;; - somehow allow comment-dwim to use the region even if transient-mark-mode
  50. ;; is not turned on.
  51. ;; - when auto-filling a comment, try to move the comment to the left
  52. ;; rather than break it (if possible).
  53. ;; - sometimes default the comment-column to the same
  54. ;; one used on the preceding line(s).
  55. ;;; Code:
  56. ;;;###autoload
  57. (defalias 'indent-for-comment 'comment-indent)
  58. ;;;###autoload
  59. (defalias 'set-comment-column 'comment-set-column)
  60. ;;;###autoload
  61. (defalias 'kill-comment 'comment-kill)
  62. ;;;###autoload
  63. (defalias 'indent-new-comment-line 'comment-indent-new-line)
  64. (defgroup comment nil
  65. "Indenting and filling of comments."
  66. :prefix "comment-"
  67. :version "21.1"
  68. :group 'fill)
  69. ;; Autoload this to avoid warnings, since some major modes define it.
  70. ;;;###autoload
  71. (defvar comment-use-syntax 'undecided
  72. "Non-nil if syntax-tables can be used instead of regexps.
  73. Can also be `undecided' which means that a somewhat expensive test will
  74. be used to try to determine whether syntax-tables should be trusted
  75. to understand comments or not in the given buffer.
  76. Major modes should set this variable.")
  77. (defcustom comment-fill-column nil
  78. "Column to use for `comment-indent'. If nil, use `fill-column' instead."
  79. :type '(choice (const nil) integer)
  80. :group 'comment)
  81. ;;;###autoload
  82. (defcustom comment-column 32
  83. "Column to indent right-margin comments to.
  84. Each mode may establish a different default value for this variable; you
  85. can set the value for a particular mode using that mode's hook.
  86. Comments might be indented to a different value in order not to go beyond
  87. `comment-fill-column' or in order to align them with surrounding comments."
  88. :type 'integer
  89. :group 'comment)
  90. (make-variable-buffer-local 'comment-column)
  91. ;;;###autoload
  92. (put 'comment-column 'safe-local-variable 'integerp)
  93. ;;;###autoload
  94. (defvar comment-start nil
  95. "String to insert to start a new comment, or nil if no comment syntax.")
  96. ;;;###autoload
  97. (put 'comment-start 'safe-local-variable 'string-or-null-p)
  98. ;;;###autoload
  99. (defvar comment-start-skip nil
  100. "Regexp to match the start of a comment plus everything up to its body.
  101. If there are any \\(...\\) pairs and `comment-use-syntax' is nil,
  102. the comment delimiter text is held to begin at the place matched
  103. by the close of the first pair.")
  104. ;;;###autoload
  105. (put 'comment-start-skip 'safe-local-variable 'stringp)
  106. ;;;###autoload
  107. (defvar comment-end-skip nil
  108. "Regexp to match the end of a comment plus everything back to its body.")
  109. ;;;###autoload
  110. (put 'comment-end-skip 'safe-local-variable 'stringp)
  111. ;;;###autoload
  112. (defvar comment-end (purecopy "")
  113. "String to insert to end a new comment.
  114. Should be an empty string if comments are terminated by end-of-line.")
  115. ;;;###autoload
  116. (put 'comment-end 'safe-local-variable 'stringp)
  117. ;;;###autoload
  118. (defvar comment-indent-function 'comment-indent-default
  119. "Function to compute desired indentation for a comment.
  120. This function is called with no args with point at the beginning
  121. of the comment's starting delimiter and should return either the
  122. desired column indentation, a range of acceptable
  123. indentation (MIN . MAX), or nil.
  124. If nil is returned, indentation is delegated to `indent-according-to-mode'.")
  125. ;;;###autoload
  126. (defvar comment-insert-comment-function nil
  127. "Function to insert a comment when a line doesn't contain one.
  128. The function has no args.
  129. Applicable at least in modes for languages like fixed-format Fortran where
  130. comments always start in column zero.")
  131. (defvar comment-region-function 'comment-region-default
  132. "Function to comment a region.
  133. Its args are the same as those of `comment-region', but BEG and END are
  134. guaranteed to be correctly ordered. It is called within `save-excursion'.
  135. Applicable at least in modes for languages like fixed-format Fortran where
  136. comments always start in column zero.")
  137. (defvar uncomment-region-function 'uncomment-region-default
  138. "Function to uncomment a region.
  139. Its args are the same as those of `uncomment-region', but BEG and END are
  140. guaranteed to be correctly ordered. It is called within `save-excursion'.
  141. Applicable at least in modes for languages like fixed-format Fortran where
  142. comments always start in column zero.")
  143. ;; ?? never set
  144. (defvar block-comment-start nil)
  145. (defvar block-comment-end nil)
  146. (defvar comment-quote-nested t
  147. "Non-nil if nested comments should be quoted.
  148. This should be locally set by each major mode if needed.")
  149. (defvar comment-quote-nested-function #'comment-quote-nested-default
  150. "Function to quote nested comments in a region.
  151. It takes the same arguments as `comment-quote-nested-default',
  152. and is called with the buffer narrowed to a single comment.")
  153. (defvar comment-continue nil
  154. "Continuation string to insert for multiline comments.
  155. This string will be added at the beginning of each line except the very
  156. first one when commenting a region with a commenting style that allows
  157. comments to span several lines.
  158. It should generally have the same length as `comment-start' in order to
  159. preserve indentation.
  160. If it is nil a value will be automatically derived from `comment-start'
  161. by replacing its first character with a space.")
  162. (defvar comment-add 0
  163. "How many more comment chars should be inserted by `comment-region'.
  164. This determines the default value of the numeric argument of `comment-region'.
  165. The `plain' comment style doubles this value.
  166. This should generally stay 0, except for a few modes like Lisp where
  167. it is 1 so that regions are commented with two or three semi-colons.")
  168. ;;;###autoload
  169. (defconst comment-styles
  170. '((plain nil nil nil nil
  171. "Start in column 0 (do not indent), as in Emacs-20")
  172. (indent-or-triple nil nil nil multi-char
  173. "Start in column 0, but only for single-char starters")
  174. (indent nil nil nil t
  175. "Full comment per line, ends not aligned")
  176. (aligned nil t nil t
  177. "Full comment per line, ends aligned")
  178. (box nil t t t
  179. "Full comment per line, ends aligned, + top and bottom")
  180. (extra-line t nil t t
  181. "One comment for all lines, end on a line by itself")
  182. (multi-line t nil nil t
  183. "One comment for all lines, end on last commented line")
  184. (box-multi t t t t
  185. "One comment for all lines, + top and bottom"))
  186. "Comment region style definitions.
  187. Each style is defined with a form (STYLE . (MULTI ALIGN EXTRA INDENT DOC)).
  188. DOC should succinctly describe the style.
  189. STYLE should be a mnemonic symbol.
  190. MULTI specifies that comments are allowed to span multiple lines.
  191. e.g. in C it comments regions as
  192. /* blabla
  193. * bli */
  194. rather than
  195. /* blabla */
  196. /* bli */
  197. if `comment-end' is empty, this has no effect.
  198. ALIGN specifies that the `comment-end' markers should be aligned.
  199. e.g. in C it comments regions as
  200. /* blabla */
  201. /* bli */
  202. rather than
  203. /* blabla */
  204. /* bli */
  205. if `comment-end' is empty, this has no effect, unless EXTRA is also set,
  206. in which case the comment gets wrapped in a box.
  207. EXTRA specifies that an extra line should be used before and after the
  208. region to comment (to put the `comment-end' and `comment-start').
  209. e.g. in C it comments regions as
  210. /*
  211. * blabla
  212. * bli
  213. */
  214. rather than
  215. /* blabla
  216. * bli */
  217. if the comment style is not multi line, this has no effect, unless ALIGN
  218. is also set, in which case the comment gets wrapped in a box.
  219. INDENT specifies that the `comment-start' markers should not be put at the
  220. left margin but at the current indentation of the region to comment.
  221. If INDENT is `multi-char', that means indent multi-character
  222. comment starters, but not one-character comment starters.")
  223. ;;;###autoload
  224. (defcustom comment-style 'indent
  225. "Style to be used for `comment-region'.
  226. See `comment-styles' for a list of available styles."
  227. :type (if (boundp 'comment-styles)
  228. `(choice
  229. ,@(mapcar (lambda (s)
  230. `(const :tag ,(format "%s: %s" (car s) (nth 5 s))
  231. ,(car s)))
  232. comment-styles))
  233. 'symbol)
  234. :version "23.1"
  235. :group 'comment)
  236. ;;;###autoload
  237. (defcustom comment-padding (purecopy " ")
  238. "Padding string that `comment-region' puts between comment chars and text.
  239. Can also be an integer which will be automatically turned into a string
  240. of the corresponding number of spaces.
  241. Extra spacing between the comment characters and the comment text
  242. makes the comment easier to read. Default is 1. nil means 0."
  243. :type '(choice string integer (const nil))
  244. :group 'comment)
  245. (defcustom comment-inline-offset 1
  246. "Inline comments have to be preceded by at least this many spaces.
  247. This is useful when style-conventions require a certain minimal offset.
  248. Python's PEP8 for example recommends two spaces, so you could do:
  249. \(add-hook \\='python-mode-hook
  250. (lambda () (set (make-local-variable \\='comment-inline-offset) 2)))
  251. See `comment-padding' for whole-line comments."
  252. :version "24.3"
  253. :type 'integer
  254. :group 'comment)
  255. ;;;###autoload
  256. (defcustom comment-multi-line nil
  257. "Non-nil means `comment-indent-new-line' continues comments.
  258. That is, it inserts no new terminator or starter.
  259. This affects `auto-fill-mode', which is the main reason to
  260. customize this variable.
  261. It also affects \\[indent-new-comment-line]. However, if you want this
  262. behavior for explicit filling, you might as well use \\[newline-and-indent]."
  263. :type 'boolean
  264. :safe #'booleanp
  265. :group 'comment)
  266. (defcustom comment-empty-lines nil
  267. "If nil, `comment-region' does not comment out empty lines.
  268. If t, it always comments out empty lines.
  269. If `eol' it only comments out empty lines if comments are
  270. terminated by the end of line (i.e. `comment-end' is empty)."
  271. :type '(choice (const :tag "Never" nil)
  272. (const :tag "Always" t)
  273. (const :tag "EOl-terminated" eol))
  274. :group 'comment)
  275. ;;;;
  276. ;;;; Helpers
  277. ;;;;
  278. (defun comment-string-strip (str beforep afterp)
  279. "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
  280. (string-match (concat "\\`" (if beforep "\\s-*")
  281. "\\(.*?\\)" (if afterp "\\s-*\n?")
  282. "\\'") str)
  283. (match-string 1 str))
  284. (defun comment-string-reverse (s)
  285. "Return the mirror image of string S, without any trailing space."
  286. (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
  287. ;;;###autoload
  288. (defun comment-normalize-vars (&optional noerror)
  289. "Check and set up variables needed by other commenting functions.
  290. All the `comment-*' commands call this function to set up various
  291. variables, like `comment-start', to ensure that the commenting
  292. functions work correctly. Lisp callers of any other `comment-*'
  293. function should first call this function explicitly."
  294. (unless (and (not comment-start) noerror)
  295. (unless comment-start
  296. (let ((cs (read-string "No comment syntax is defined. Use: ")))
  297. (if (zerop (length cs))
  298. (error "No comment syntax defined")
  299. (set (make-local-variable 'comment-start) cs)
  300. (set (make-local-variable 'comment-start-skip) cs))))
  301. ;; comment-use-syntax
  302. (when (eq comment-use-syntax 'undecided)
  303. (set (make-local-variable 'comment-use-syntax)
  304. (let ((st (syntax-table))
  305. (cs comment-start)
  306. (ce (if (string= "" comment-end) "\n" comment-end)))
  307. ;; Try to skip over a comment using forward-comment
  308. ;; to see if the syntax tables properly recognize it.
  309. (with-temp-buffer
  310. (set-syntax-table st)
  311. (insert cs " hello " ce)
  312. (goto-char (point-min))
  313. (and (forward-comment 1) (eobp))))))
  314. ;; comment-padding
  315. (unless comment-padding (setq comment-padding 0))
  316. (when (integerp comment-padding)
  317. (setq comment-padding (make-string comment-padding ? )))
  318. ;; comment markers
  319. ;;(setq comment-start (comment-string-strip comment-start t nil))
  320. ;;(setq comment-end (comment-string-strip comment-end nil t))
  321. ;; comment-continue
  322. (unless (or comment-continue (string= comment-end ""))
  323. (set (make-local-variable 'comment-continue)
  324. (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
  325. (substring comment-start 1)))
  326. ;; Hasn't been necessary yet.
  327. ;; (unless (string-match comment-start-skip comment-continue)
  328. ;; (kill-local-variable 'comment-continue))
  329. )
  330. ;; comment-skip regexps
  331. (unless (and comment-start-skip
  332. ;; In case comment-start has changed since last time.
  333. (string-match comment-start-skip comment-start))
  334. (set (make-local-variable 'comment-start-skip)
  335. (concat (unless (eq comment-use-syntax t)
  336. ;; `syntax-ppss' will detect escaping.
  337. "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)")
  338. "\\(?:\\s<+\\|"
  339. (regexp-quote (comment-string-strip comment-start t t))
  340. ;; Let's not allow any \s- but only [ \t] since \n
  341. ;; might be both a comment-end marker and \s-.
  342. "+\\)[ \t]*")))
  343. (unless (and comment-end-skip
  344. ;; In case comment-end has changed since last time.
  345. (string-match comment-end-skip
  346. (if (string= "" comment-end) "\n" comment-end)))
  347. (let ((ce (if (string= "" comment-end) "\n"
  348. (comment-string-strip comment-end t t))))
  349. (set (make-local-variable 'comment-end-skip)
  350. ;; We use [ \t] rather than \s- because we don't want to
  351. ;; remove ^L in C mode when uncommenting.
  352. (concat "[ \t]*\\(\\s>" (if comment-quote-nested "" "+")
  353. "\\|" (regexp-quote (substring ce 0 1))
  354. (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
  355. (regexp-quote (substring ce 1))
  356. "\\)"))))))
  357. (defun comment-quote-re (str unp)
  358. (concat (regexp-quote (substring str 0 1))
  359. "\\\\" (if unp "+" "*")
  360. (regexp-quote (substring str 1))))
  361. (defun comment-quote-nested (cs ce unp)
  362. "Quote or unquote nested comments.
  363. If UNP is non-nil, unquote nested comment markers."
  364. (setq cs (comment-string-strip cs t t))
  365. (setq ce (comment-string-strip ce t t))
  366. (when (and comment-quote-nested
  367. (> (length ce) 0))
  368. (funcall comment-quote-nested-function cs ce unp)))
  369. (defun comment-quote-nested-default (cs ce unp)
  370. "Quote comment delimiters in the buffer.
  371. It expects to be called with the buffer narrowed to a single comment.
  372. It is used as a default for `comment-quote-nested-function'.
  373. The arguments CS and CE are strings matching comment starting and
  374. ending delimiters respectively.
  375. If UNP is non-nil, comments are unquoted instead.
  376. To quote the delimiters, a \\ is inserted after the first
  377. character of CS or CE. If CE is a single character it will
  378. change CE into !CS."
  379. (let ((re (concat (comment-quote-re ce unp)
  380. "\\|" (comment-quote-re cs unp))))
  381. (goto-char (point-min))
  382. (while (re-search-forward re nil t)
  383. (goto-char (match-beginning 0))
  384. (forward-char 1)
  385. (if unp (delete-char 1) (insert "\\"))
  386. (when (= (length ce) 1)
  387. ;; If the comment-end is a single char, adding a \ after that
  388. ;; "first" char won't deactivate it, so we turn such a CE
  389. ;; into !CS. I.e. for pascal, we turn } into !{
  390. (if (not unp)
  391. (when (string= (match-string 0) ce)
  392. (replace-match (concat "!" cs) t t))
  393. (when (and (< (point-min) (match-beginning 0))
  394. (string= (buffer-substring (1- (match-beginning 0))
  395. (1- (match-end 0)))
  396. (concat "!" cs)))
  397. (backward-char 2)
  398. (delete-char (- (match-end 0) (match-beginning 0)))
  399. (insert ce)))))))
  400. ;;;;
  401. ;;;; Navigation
  402. ;;;;
  403. (defvar comment-use-global-state t
  404. "Non-nil means that the global syntactic context is used.
  405. More specifically, it means that `syntax-ppss' is used to find out whether
  406. point is within a string or not. Major modes whose syntax is not faithfully
  407. described by the syntax-tables (or where `font-lock-syntax-table' is radically
  408. different from the main syntax table) can set this to nil,
  409. then `syntax-ppss' cache won't be used in comment-related routines.")
  410. (make-obsolete-variable 'comment-use-global-state 'comment-use-syntax "24.4")
  411. (defun comment-search-forward (limit &optional noerror)
  412. "Find a comment start between point and LIMIT.
  413. Moves point to inside the comment and returns the position of the
  414. comment-starter. If no comment is found, moves point to LIMIT
  415. and raises an error or returns nil if NOERROR is non-nil.
  416. Ensure that `comment-normalize-vars' has been called before you use this."
  417. (if (not comment-use-syntax)
  418. (if (re-search-forward comment-start-skip limit noerror)
  419. (or (match-end 1) (match-beginning 0))
  420. (goto-char limit)
  421. (unless noerror (error "No comment")))
  422. (let* ((pt (point))
  423. ;; Assume (at first) that pt is outside of any string.
  424. (s (parse-partial-sexp pt (or limit (point-max)) nil nil
  425. (if comment-use-global-state (syntax-ppss pt))
  426. t)))
  427. (when (and (nth 8 s) (nth 3 s) (not comment-use-global-state))
  428. ;; The search ended at eol inside a string. Try to see if it
  429. ;; works better when we assume that pt is inside a string.
  430. (setq s (parse-partial-sexp
  431. pt (or limit (point-max)) nil nil
  432. (list nil nil nil (nth 3 s) nil nil nil nil)
  433. t)))
  434. (if (or (not (and (nth 8 s) (not (nth 3 s))))
  435. ;; Make sure the comment starts after PT.
  436. (< (nth 8 s) pt))
  437. (unless noerror (error "No comment"))
  438. ;; We found the comment.
  439. (let ((pos (point))
  440. (start (nth 8 s))
  441. (bol (line-beginning-position))
  442. (end nil))
  443. (while (and (null end) (>= (point) bol))
  444. (if (looking-at comment-start-skip)
  445. (setq end (min (or limit (point-max)) (match-end 0)))
  446. (backward-char)))
  447. (goto-char (or end pos))
  448. start)))))
  449. (defun comment-search-backward (&optional limit noerror)
  450. "Find a comment start between LIMIT and point.
  451. Moves point to inside the comment and returns the position of the
  452. comment-starter. If no comment is found, moves point to LIMIT
  453. and raises an error or returns nil if NOERROR is non-nil.
  454. Ensure that `comment-normalize-vars' has been called before you use this."
  455. ;; FIXME: If a comment-start appears inside a comment, we may erroneously
  456. ;; stop there. This can be rather bad in general, but since
  457. ;; comment-search-backward is only used to find the comment-column (in
  458. ;; comment-set-column) and to find the comment-start string (via
  459. ;; comment-beginning) in indent-new-comment-line, it should be harmless.
  460. (if (not (re-search-backward comment-start-skip limit t))
  461. (unless noerror (error "No comment"))
  462. (beginning-of-line)
  463. (let* ((end (match-end 0))
  464. (cs (comment-search-forward end t))
  465. (pt (point)))
  466. (if (not cs)
  467. (progn (beginning-of-line)
  468. (comment-search-backward limit noerror))
  469. (while (progn (goto-char cs)
  470. (comment-forward)
  471. (and (< (point) end)
  472. (setq cs (comment-search-forward end t))))
  473. (setq pt (point)))
  474. (goto-char pt)
  475. cs))))
  476. (defun comment-beginning ()
  477. "Find the beginning of the enclosing comment.
  478. Returns nil if not inside a comment, else moves point and returns
  479. the same as `comment-search-backward'."
  480. (if (and comment-use-syntax comment-use-global-state)
  481. (let ((state (syntax-ppss)))
  482. (when (nth 4 state)
  483. (goto-char (nth 8 state))
  484. (prog1 (point)
  485. (when (save-restriction
  486. ;; `comment-start-skip' sometimes checks that the
  487. ;; comment char is not escaped. (Bug#16971)
  488. (narrow-to-region (point) (point-max))
  489. (looking-at comment-start-skip))
  490. (goto-char (match-end 0))))))
  491. ;; Can't rely on the syntax table, let's guess based on font-lock.
  492. (unless (eq (get-text-property (point) 'face) 'font-lock-string-face)
  493. (let ((pt (point))
  494. (cs (comment-search-backward nil t)))
  495. (when cs
  496. (if (save-excursion
  497. (goto-char cs)
  498. (and
  499. ;; For modes where comment-start and comment-end are the same,
  500. ;; the search above may have found a `ce' rather than a `cs'.
  501. (or (if comment-end-skip (not (looking-at comment-end-skip)))
  502. ;; Maybe font-lock knows that it's a `cs'?
  503. (eq (get-text-property (match-end 0) 'face)
  504. 'font-lock-comment-face)
  505. (unless (eq (get-text-property (point) 'face)
  506. 'font-lock-comment-face)
  507. ;; Let's assume it's a `cs' if we're on the same line.
  508. (>= (line-end-position) pt)))
  509. ;; Make sure that PT is not past the end of the comment.
  510. (if (comment-forward 1) (> (point) pt) (eobp))))
  511. cs
  512. (goto-char pt)
  513. nil))))))
  514. (defun comment-forward (&optional n)
  515. "Skip forward over N comments.
  516. Just like `forward-comment' but only for positive N
  517. and can use regexps instead of syntax."
  518. (setq n (or n 1))
  519. (if (< n 0) (error "No comment-backward")
  520. (if comment-use-syntax (forward-comment n)
  521. (while (> n 0)
  522. (setq n
  523. (if (or (forward-comment 1)
  524. (and (looking-at comment-start-skip)
  525. (goto-char (match-end 0))
  526. (re-search-forward comment-end-skip nil 'move)))
  527. (1- n) -1)))
  528. (= n 0))))
  529. (defun comment-enter-backward ()
  530. "Move from the end of a comment to the end of its content.
  531. Point is assumed to be just at the end of a comment."
  532. (if (bolp)
  533. ;; comment-end = ""
  534. (progn (backward-char) (skip-syntax-backward " "))
  535. (cond
  536. ((save-excursion
  537. (save-restriction
  538. (narrow-to-region (line-beginning-position) (point))
  539. (goto-char (point-min))
  540. (re-search-forward (concat comment-end-skip "\\'") nil t)))
  541. (goto-char (match-beginning 0)))
  542. ;; comment-end-skip not found probably because it was not set
  543. ;; right. Since \\s> should catch the single-char case, let's
  544. ;; check that we're looking at a two-char comment ender.
  545. ((not (or (<= (- (point-max) (line-beginning-position)) 1)
  546. (zerop (logand (car (syntax-after (- (point) 1)))
  547. ;; Here we take advantage of the fact that
  548. ;; the syntax class " " is encoded to 0,
  549. ;; so " 4" gives us just the 4 bit.
  550. (car (string-to-syntax " 4"))))
  551. (zerop (logand (car (syntax-after (- (point) 2)))
  552. (car (string-to-syntax " 3"))))))
  553. (backward-char 2)
  554. (skip-chars-backward (string (char-after)))
  555. (skip-syntax-backward " "))
  556. ;; No clue what's going on: maybe we're really not right after the
  557. ;; end of a comment. Maybe we're at the "end" because of EOB rather
  558. ;; than because of a marker.
  559. (t (skip-syntax-backward " ")))))
  560. ;;;;
  561. ;;;; Commands
  562. ;;;;
  563. ;;;###autoload
  564. (defun comment-indent-default ()
  565. "Default for `comment-indent-function'."
  566. (if (and (looking-at "\\s<\\s<\\(\\s<\\)?")
  567. (or (match-end 1) (/= (current-column) (current-indentation))))
  568. 0
  569. (when (or (/= (current-column) (current-indentation))
  570. (and (> comment-add 0) (looking-at "\\s<\\(\\S<\\|\\'\\)")))
  571. comment-column)))
  572. (defun comment-choose-indent (&optional indent)
  573. "Choose the indentation to use for a right-hand-side comment.
  574. The criteria are (in this order):
  575. - try to keep the comment's text within `comment-fill-column'.
  576. - try to align with surrounding comments.
  577. - prefer INDENT (or `comment-column' if nil).
  578. Point is expected to be at the start of the comment."
  579. (unless indent (setq indent comment-column))
  580. (let ((other nil)
  581. min max)
  582. (pcase indent
  583. (`(,lo . ,hi) (setq min lo) (setq max hi)
  584. (setq indent comment-column))
  585. (_ ;; Avoid moving comments past the fill-column.
  586. (setq max (+ (current-column)
  587. (- (or comment-fill-column fill-column)
  588. (save-excursion (end-of-line) (current-column)))))
  589. (setq min (save-excursion
  590. (skip-chars-backward " \t")
  591. ;; Leave at least `comment-inline-offset' space after
  592. ;; other nonwhite text on the line.
  593. (if (bolp) 0 (+ comment-inline-offset (current-column)))))))
  594. ;; Fix up the range.
  595. (if (< max min) (setq max min))
  596. ;; Don't move past the fill column.
  597. (if (<= max indent) (setq indent max))
  598. ;; We can choose anywhere between min..max.
  599. ;; Let's try to align to a comment on the previous line.
  600. (save-excursion
  601. (when (and (zerop (forward-line -1))
  602. (setq other (comment-search-forward
  603. (line-end-position) t)))
  604. (goto-char other) (setq other (current-column))))
  605. (if (and other (<= other max) (>= other min))
  606. ;; There is a comment and it's in the range: bingo!
  607. other
  608. ;; Can't align to a previous comment: let's try to align to comments
  609. ;; on the following lines, then. These have not been re-indented yet,
  610. ;; so we can't directly align ourselves with them. All we do is to try
  611. ;; and choose an indentation point with which they will be able to
  612. ;; align themselves.
  613. (save-excursion
  614. (while (and (zerop (forward-line 1))
  615. (setq other (comment-search-forward
  616. (line-end-position) t)))
  617. (goto-char other)
  618. (let ((omax (+ (current-column)
  619. (- (or comment-fill-column fill-column)
  620. (save-excursion (end-of-line) (current-column)))))
  621. (omin (save-excursion (skip-chars-backward " \t")
  622. (1+ (current-column)))))
  623. (if (and (>= omax min) (<= omin max))
  624. (progn (setq min (max omin min))
  625. (setq max (min omax max)))
  626. ;; Can't align with this anyway, so exit the loop.
  627. (goto-char (point-max))))))
  628. ;; Return the closest point to indent within min..max.
  629. (max min (min max indent)))))
  630. ;;;###autoload
  631. (defun comment-indent (&optional continue)
  632. "Indent this line's comment to `comment-column', or insert an empty comment.
  633. If CONTINUE is non-nil, use the `comment-continue' markers if any."
  634. (interactive "*")
  635. (comment-normalize-vars)
  636. (let* ((empty (save-excursion (beginning-of-line)
  637. (looking-at "[ \t]*$")))
  638. (starter (or (and continue comment-continue)
  639. (and empty block-comment-start) comment-start))
  640. (ender (or (and continue comment-continue "")
  641. (and empty block-comment-end) comment-end)))
  642. (unless starter (error "No comment syntax defined"))
  643. (beginning-of-line)
  644. (let* ((eolpos (line-end-position))
  645. (begpos (comment-search-forward eolpos t))
  646. cpos indent)
  647. (if (and comment-insert-comment-function (not begpos))
  648. ;; If no comment and c-i-c-f is set, let it do everything.
  649. (funcall comment-insert-comment-function)
  650. ;; An existing comment?
  651. (if begpos
  652. (progn
  653. (if (and (not (looking-at "[\t\n ]"))
  654. (looking-at comment-end-skip))
  655. ;; The comment is empty and we have skipped all its space
  656. ;; and landed right before the comment-ender:
  657. ;; Go back to the middle of the space.
  658. (forward-char (/ (skip-chars-backward " \t") -2)))
  659. (setq cpos (point-marker)))
  660. ;; If none, insert one.
  661. (save-excursion
  662. ;; Some `comment-indent-function's insist on not moving
  663. ;; comments that are in column 0, so we first go to the
  664. ;; likely target column.
  665. (indent-to comment-column)
  666. ;; Ensure there's a space before the comment for things
  667. ;; like sh where it matters (as well as being neater).
  668. (unless (memq (char-before) '(nil ?\n ?\t ?\s))
  669. (insert ?\s))
  670. (setq begpos (point))
  671. (insert starter)
  672. (setq cpos (point-marker))
  673. (insert ender)))
  674. (goto-char begpos)
  675. ;; Compute desired indent.
  676. (setq indent (save-excursion (funcall comment-indent-function)))
  677. ;; If `indent' is nil and there's code before the comment, we can't
  678. ;; use `indent-according-to-mode', so we default to comment-column.
  679. (unless (or indent (save-excursion (skip-chars-backward " \t") (bolp)))
  680. (setq indent comment-column))
  681. (if (not indent)
  682. ;; comment-indent-function refuses: delegate to line-indent.
  683. (indent-according-to-mode)
  684. ;; If the comment is at the right of code, adjust the indentation.
  685. (unless (save-excursion (skip-chars-backward " \t") (bolp))
  686. (setq indent (comment-choose-indent indent)))
  687. ;; If that's different from comment's current position, change it.
  688. (unless (= (current-column) indent)
  689. (delete-region (point) (progn (skip-chars-backward " \t") (point)))
  690. (indent-to indent)))
  691. (goto-char cpos)
  692. (set-marker cpos nil)))))
  693. ;;;###autoload
  694. (defun comment-set-column (arg)
  695. "Set the comment column based on point.
  696. With no ARG, set the comment column to the current column.
  697. With just minus as arg, kill any comment on this line.
  698. With any other arg, set comment column to indentation of the previous comment
  699. and then align or create a comment on this line at that column."
  700. (interactive "P")
  701. (cond
  702. ((eq arg '-) (comment-kill nil))
  703. (arg
  704. (comment-normalize-vars)
  705. (save-excursion
  706. (beginning-of-line)
  707. (comment-search-backward)
  708. (beginning-of-line)
  709. (goto-char (comment-search-forward (line-end-position)))
  710. (setq comment-column (current-column))
  711. (message "Comment column set to %d" comment-column))
  712. (comment-indent))
  713. (t (setq comment-column (current-column))
  714. (message "Comment column set to %d" comment-column))))
  715. ;;;###autoload
  716. (defun comment-kill (arg)
  717. "Kill the first comment on this line, if any.
  718. With prefix ARG, kill comments on that many lines starting with this one."
  719. (interactive "P")
  720. (comment-normalize-vars)
  721. (dotimes (_i (prefix-numeric-value arg))
  722. (save-excursion
  723. (beginning-of-line)
  724. (let ((cs (comment-search-forward (line-end-position) t)))
  725. (when cs
  726. (goto-char cs)
  727. (skip-syntax-backward " ")
  728. (setq cs (point))
  729. (comment-forward)
  730. (kill-region cs (if (bolp) (1- (point)) (point)))
  731. (indent-according-to-mode))))
  732. (if arg (forward-line 1))))
  733. (defun comment-padright (str &optional n)
  734. "Construct a string composed of STR plus `comment-padding'.
  735. It also adds N copies of the last non-whitespace chars of STR.
  736. If STR already contains padding, the corresponding amount is
  737. ignored from `comment-padding'.
  738. N defaults to 0.
  739. If N is `re', a regexp is returned instead, that would match
  740. the string for any N."
  741. (setq n (or n 0))
  742. (when (and (stringp str) (string-match "\\S-" str))
  743. ;; Separate the actual string from any leading/trailing padding
  744. (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
  745. (let ((s (match-string 1 str)) ;actual string
  746. (lpad (substring str 0 (match-beginning 1))) ;left padding
  747. (rpad (concat (substring str (match-end 1)) ;original right padding
  748. (substring comment-padding ;additional right padding
  749. (min (- (match-end 0) (match-end 1))
  750. (length comment-padding)))))
  751. ;; We can only duplicate C if the comment-end has multiple chars
  752. ;; or if comments can be nested, else the comment-end `}' would
  753. ;; be turned into `}}}' where only the first ends the comment
  754. ;; and the rest becomes bogus junk.
  755. (multi (not (and comment-quote-nested
  756. ;; comment-end is a single char
  757. (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
  758. (if (not (symbolp n))
  759. (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
  760. ;; construct a regexp that would match anything from just S
  761. ;; to any possible output of this function for any N.
  762. (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
  763. lpad "") ;padding is not required
  764. (regexp-quote s)
  765. (when multi "+") ;the last char of S might be repeated
  766. (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
  767. rpad "")))))) ;padding is not required
  768. (defun comment-padleft (str &optional n)
  769. "Construct a string composed of `comment-padding' plus STR.
  770. It also adds N copies of the first non-whitespace chars of STR.
  771. If STR already contains padding, the corresponding amount is
  772. ignored from `comment-padding'.
  773. N defaults to 0.
  774. If N is `re', a regexp is returned instead, that would match
  775. the string for any N."
  776. (setq n (or n 0))
  777. (when (and (stringp str) (not (string= "" str)))
  778. ;; Only separate the left pad because we assume there is no right pad.
  779. (string-match "\\`\\s-*" str)
  780. (let ((s (substring str (match-end 0)))
  781. (pad (concat (substring comment-padding
  782. (min (- (match-end 0) (match-beginning 0))
  783. (length comment-padding)))
  784. (match-string 0 str)))
  785. (c (aref str (match-end 0))) ;the first non-space char of STR
  786. ;; We can only duplicate C if the comment-end has multiple chars
  787. ;; or if comments can be nested, else the comment-end `}' would
  788. ;; be turned into `}}}' where only the first ends the comment
  789. ;; and the rest becomes bogus junk.
  790. (multi (not (and comment-quote-nested
  791. ;; comment-end is a single char
  792. (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
  793. (if (not (symbolp n))
  794. (concat pad (when multi (make-string n c)) s)
  795. ;; Construct a regexp that would match anything from just S
  796. ;; to any possible output of this function for any N.
  797. ;; We match any number of leading spaces because this regexp will
  798. ;; be used for uncommenting where we might want to remove
  799. ;; uncomment markers with arbitrary leading space (because
  800. ;; they were aligned).
  801. (concat "\\s-*"
  802. (if multi (concat (regexp-quote (string c)) "*"))
  803. (regexp-quote s))))))
  804. ;;;###autoload
  805. (defun uncomment-region (beg end &optional arg)
  806. "Uncomment each line in the BEG .. END region.
  807. The numeric prefix ARG can specify a number of chars to remove from the
  808. comment markers."
  809. (interactive "*r\nP")
  810. (comment-normalize-vars)
  811. (when (> beg end) (setq beg (prog1 end (setq end beg))))
  812. ;; Bind `comment-use-global-state' to nil. While uncommenting a region
  813. ;; (which works a line at a time), a comment can appear to be
  814. ;; included in a mult-line string, but it is actually not.
  815. (let ((comment-use-global-state nil))
  816. (save-excursion
  817. (funcall uncomment-region-function beg end arg))))
  818. (defun uncomment-region-default (beg end &optional arg)
  819. "Uncomment each line in the BEG .. END region.
  820. The numeric prefix ARG can specify a number of chars to remove from the
  821. comment markers."
  822. (goto-char beg)
  823. (setq end (copy-marker end))
  824. (let* ((numarg (prefix-numeric-value arg))
  825. (ccs comment-continue)
  826. (srei (comment-padright ccs 're))
  827. (csre (comment-padright comment-start 're))
  828. (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
  829. spt)
  830. (while (and (< (point) end)
  831. (setq spt (comment-search-forward end t)))
  832. (let ((ipt (point))
  833. ;; Find the end of the comment.
  834. (ept (progn
  835. (goto-char spt)
  836. (unless (or (comment-forward)
  837. ;; Allow non-terminated comments.
  838. (eobp))
  839. (error "Can't find the comment end"))
  840. (point)))
  841. (box nil)
  842. (box-equal nil)) ;Whether we might be using `=' for boxes.
  843. (save-restriction
  844. (narrow-to-region spt ept)
  845. ;; Remove the comment-start.
  846. (goto-char ipt)
  847. (skip-syntax-backward " ")
  848. ;; A box-comment starts with a looong comment-start marker.
  849. (when (and (or (and (= (- (point) (point-min)) 1)
  850. (setq box-equal t)
  851. (looking-at "=\\{7\\}")
  852. (not (eq (char-before (point-max)) ?\n))
  853. (skip-chars-forward "="))
  854. (> (- (point) (point-min) (length comment-start)) 7))
  855. (> (count-lines (point-min) (point-max)) 2))
  856. (setq box t))
  857. ;; Skip the padding. Padding can come from comment-padding and/or
  858. ;; from comment-start, so we first check comment-start.
  859. (if (or (save-excursion (goto-char (point-min)) (looking-at csre))
  860. (looking-at (regexp-quote comment-padding)))
  861. (goto-char (match-end 0)))
  862. (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
  863. (goto-char (match-end 0)))
  864. (if (null arg) (delete-region (point-min) (point))
  865. (let ((opoint (point-marker)))
  866. (skip-syntax-backward " ")
  867. (delete-char (- numarg))
  868. (unless (and (not (bobp))
  869. (save-excursion (goto-char (point-min))
  870. (looking-at comment-start-skip)))
  871. ;; If there's something left but it doesn't look like
  872. ;; a comment-start any more, just remove it.
  873. (delete-region (point-min) opoint))))
  874. ;; Remove the end-comment (and leading padding and such).
  875. (goto-char (point-max)) (comment-enter-backward)
  876. ;; Check for special `=' used sometimes in comment-box.
  877. (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
  878. (let ((pos (point)))
  879. ;; skip `=' but only if there are at least 7.
  880. (when (> (skip-chars-backward "=") -7) (goto-char pos))))
  881. (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
  882. (when (and (bolp) (not (bobp))) (backward-char))
  883. (if (null arg) (delete-region (point) (point-max))
  884. (skip-syntax-forward " ")
  885. (delete-char numarg)
  886. (unless (or (eobp) (looking-at comment-end-skip))
  887. ;; If there's something left but it doesn't look like
  888. ;; a comment-end any more, just remove it.
  889. (delete-region (point) (point-max)))))
  890. ;; Unquote any nested end-comment.
  891. (comment-quote-nested comment-start comment-end t)
  892. ;; Eliminate continuation markers as well.
  893. (when sre
  894. (let* ((cce (comment-string-reverse (or comment-continue
  895. comment-start)))
  896. (erei (and box (comment-padleft cce 're)))
  897. (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
  898. (goto-char (point-min))
  899. (while (progn
  900. (if (and ere (re-search-forward
  901. ere (line-end-position) t))
  902. (replace-match "" t t nil (if (match-end 2) 2 1))
  903. (setq ere nil))
  904. (forward-line 1)
  905. (re-search-forward sre (line-end-position) t))
  906. (replace-match "" t t nil (if (match-end 2) 2 1)))))
  907. ;; Go to the end for the next comment.
  908. (goto-char (point-max))))))
  909. (set-marker end nil))
  910. (defun comment-make-bol-ws (len)
  911. "Make a white-space string of width LEN for use at BOL.
  912. When `indent-tabs-mode' is non-nil, tab characters will be used."
  913. (if (and indent-tabs-mode (> tab-width 0))
  914. (concat (make-string (/ len tab-width) ?\t)
  915. (make-string (% len tab-width) ? ))
  916. (make-string len ? )))
  917. (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
  918. "Make the leading and trailing extra lines.
  919. This is used for `extra-line' style (or `box' style if BLOCK is specified)."
  920. (let ((eindent 0))
  921. (if (not block)
  922. ;; Try to match CS and CE's content so they align aesthetically.
  923. (progn
  924. (setq ce (comment-string-strip ce t t))
  925. (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
  926. (setq eindent
  927. (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
  928. 0))))
  929. ;; box comment
  930. (let* ((width (- max-indent min-indent))
  931. (s (concat cs "a=m" cce))
  932. (e (concat ccs "a=m" ce))
  933. (c (if (string-match ".*\\S-\\S-" cs)
  934. (aref cs (1- (match-end 0)))
  935. (if (and (equal comment-end "") (string-match ".*\\S-" cs))
  936. (aref cs (1- (match-end 0))) ?=)))
  937. (re "\\s-*a=m\\s-*")
  938. (_ (string-match re s))
  939. (lcs (length cs))
  940. (fill
  941. (make-string (+ width (- (match-end 0)
  942. (match-beginning 0) lcs 3)) c)))
  943. (setq cs (replace-match fill t t s))
  944. (when (and (not (string-match comment-start-skip cs))
  945. (string-match "a=m" s))
  946. ;; The whitespace around CS cannot be ignored: put it back.
  947. (setq re "a=m")
  948. (setq fill (make-string (- width lcs) c))
  949. (setq cs (replace-match fill t t s)))
  950. (string-match re e)
  951. (setq ce (replace-match fill t t e))))
  952. (cons (concat cs "\n" (comment-make-bol-ws min-indent) ccs)
  953. (concat cce "\n" (comment-make-bol-ws (+ min-indent eindent)) ce))))
  954. (defmacro comment-with-narrowing (beg end &rest body)
  955. "Execute BODY with BEG..END narrowing.
  956. Space is added (and then removed) at the beginning for the text's
  957. indentation to be kept as it was before narrowing."
  958. (declare (debug t) (indent 2))
  959. (let ((bindent (make-symbol "bindent")))
  960. `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
  961. (save-restriction
  962. (narrow-to-region ,beg ,end)
  963. (goto-char (point-min))
  964. (insert (make-string ,bindent ? ))
  965. (prog1
  966. (progn ,@body)
  967. ;; remove the bindent
  968. (save-excursion
  969. (goto-char (point-min))
  970. (when (looking-at " *")
  971. (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
  972. (delete-char n)
  973. (setq ,bindent (- ,bindent n))))
  974. (end-of-line)
  975. (let ((e (point)))
  976. (beginning-of-line)
  977. (while (and (> ,bindent 0) (re-search-forward " *" e t))
  978. (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
  979. (goto-char (match-beginning 0))
  980. (delete-char n)
  981. (setq ,bindent (- ,bindent n)))))))))))
  982. (defun comment-add (arg)
  983. "Compute the number of extra comment starter characters.
  984. \(Extra semicolons in Lisp mode, extra stars in C mode, etc.)
  985. If ARG is non-nil, just follow ARG.
  986. If the comment starter is multi-char, just follow ARG.
  987. Otherwise obey `comment-add'."
  988. (if (and (null arg) (= (string-match "[ \t]*\\'" comment-start) 1))
  989. (* comment-add 1)
  990. (1- (prefix-numeric-value arg))))
  991. (defun comment-region-internal (beg end cs ce
  992. &optional ccs cce block lines indent)
  993. "Comment region BEG .. END.
  994. CS and CE are the comment start string and comment end string,
  995. respectively. CCS and CCE are the comment continuation strings
  996. for the start and end of lines, respectively (default to CS and CE).
  997. BLOCK indicates that end of lines should be marked with either CCE,
  998. CE or CS \(if CE is empty) and that those markers should be aligned.
  999. LINES indicates that an extra lines will be used at the beginning
  1000. and end of the region for CE and CS.
  1001. INDENT indicates to put CS and CCS at the current indentation of
  1002. the region rather than at left margin."
  1003. ;;(assert (< beg end))
  1004. (let ((no-empty (not (or (eq comment-empty-lines t)
  1005. (and comment-empty-lines (zerop (length ce))))))
  1006. ce-sanitized)
  1007. ;; Sanitize CE and CCE.
  1008. (if (and (stringp ce) (string= "" ce)) (setq ce nil))
  1009. (setq ce-sanitized ce)
  1010. (if (and (stringp cce) (string= "" cce)) (setq cce nil))
  1011. ;; If CE is empty, multiline cannot be used.
  1012. (unless ce (setq ccs nil cce nil))
  1013. ;; Should we mark empty lines as well ?
  1014. (if (or ccs block lines) (setq no-empty nil))
  1015. ;; Make sure we have end-markers for BLOCK mode.
  1016. (when block (unless ce (setq ce (comment-string-reverse cs))))
  1017. ;; If BLOCK is not requested, we don't need CCE.
  1018. (unless block (setq cce nil))
  1019. ;; Continuation defaults to the same as CS and CE.
  1020. (unless ccs (setq ccs cs cce ce))
  1021. (save-excursion
  1022. (goto-char end)
  1023. ;; If the end is not at the end of a line and the comment-end
  1024. ;; is implicit (i.e. a newline), explicitly insert a newline.
  1025. (unless (or ce-sanitized (eolp)) (insert "\n") (indent-according-to-mode))
  1026. (comment-with-narrowing beg end
  1027. (let ((min-indent (point-max))
  1028. (max-indent 0))
  1029. (goto-char (point-min))
  1030. ;; Quote any nested comment marker
  1031. (comment-quote-nested comment-start comment-end nil)
  1032. ;; Loop over all lines to find the needed indentations.
  1033. (goto-char (point-min))
  1034. (while
  1035. (progn
  1036. (unless (looking-at "[ \t]*$")
  1037. (setq min-indent (min min-indent (current-indentation))))
  1038. (end-of-line)
  1039. (setq max-indent (max max-indent (current-column)))
  1040. (not (or (eobp) (progn (forward-line) nil)))))
  1041. (setq max-indent
  1042. (+ max-indent (max (length cs) (length ccs))
  1043. ;; Inserting ccs can change max-indent by (1- tab-width)
  1044. ;; but only if there are TABs in the boxed text, of course.
  1045. (if (save-excursion (goto-char beg)
  1046. (search-forward "\t" end t))
  1047. (1- tab-width) 0)))
  1048. (unless indent (setq min-indent 0))
  1049. ;; make the leading and trailing lines if requested
  1050. (when lines
  1051. (let ((csce
  1052. (comment-make-extra-lines
  1053. cs ce ccs cce min-indent max-indent block)))
  1054. (setq cs (car csce))
  1055. (setq ce (cdr csce))))
  1056. (goto-char (point-min))
  1057. ;; Loop over all lines from BEG to END.
  1058. (while
  1059. (progn
  1060. (unless (and no-empty (looking-at "[ \t]*$"))
  1061. (move-to-column min-indent t)
  1062. (insert cs) (setq cs ccs) ;switch to CCS after the first line
  1063. (end-of-line)
  1064. (if (eobp) (setq cce ce))
  1065. (when cce
  1066. (when block (move-to-column max-indent t))
  1067. (insert cce)))
  1068. (end-of-line)
  1069. (not (or (eobp) (progn (forward-line) nil))))))))))
  1070. ;;;###autoload
  1071. (defun comment-region (beg end &optional arg)
  1072. "Comment or uncomment each line in the region.
  1073. With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
  1074. Numeric prefix ARG means use ARG comment characters.
  1075. If ARG is negative, delete that many comment characters instead.
  1076. The strings used as comment starts are built from `comment-start'
  1077. and `comment-padding'; the strings used as comment ends are built
  1078. from `comment-end' and `comment-padding'.
  1079. By default, the `comment-start' markers are inserted at the
  1080. current indentation of the region, and comments are terminated on
  1081. each line (even for syntaxes in which newline does not end the
  1082. comment and blank lines do not get comments). This can be
  1083. changed with `comment-style'."
  1084. (interactive "*r\nP")
  1085. (comment-normalize-vars)
  1086. (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
  1087. (save-excursion
  1088. ;; FIXME: maybe we should call uncomment depending on ARG.
  1089. (funcall comment-region-function beg end arg)))
  1090. (defun comment-region-default (beg end &optional arg)
  1091. (let* ((numarg (prefix-numeric-value arg))
  1092. (style (cdr (assoc comment-style comment-styles)))
  1093. (lines (nth 2 style))
  1094. (block (nth 1 style))
  1095. (multi (nth 0 style)))
  1096. ;; We use `chars' instead of `syntax' because `\n' might be
  1097. ;; of end-comment syntax rather than of whitespace syntax.
  1098. ;; sanitize BEG and END
  1099. (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
  1100. (setq beg (max beg (point)))
  1101. (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
  1102. (setq end (min end (point)))
  1103. (if (>= beg end) (error "Nothing to comment"))
  1104. ;; sanitize LINES
  1105. (setq lines
  1106. (and
  1107. lines ;; multi
  1108. (progn (goto-char beg) (beginning-of-line)
  1109. (skip-syntax-forward " ")
  1110. (>= (point) beg))
  1111. (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
  1112. (<= (point) end))
  1113. (or block (not (string= "" comment-end)))
  1114. (or block (progn (goto-char beg) (search-forward "\n" end t)))))
  1115. ;; don't add end-markers just because the user asked for `block'
  1116. (unless (or lines (string= "" comment-end)) (setq block nil))
  1117. (cond
  1118. ((consp arg) (uncomment-region beg end))
  1119. ((< numarg 0) (uncomment-region beg end (- numarg)))
  1120. (t
  1121. (let ((multi-char (/= (string-match "[ \t]*\\'" comment-start) 1))
  1122. indent triple)
  1123. (if (eq (nth 3 style) 'multi-char)
  1124. (save-excursion
  1125. (goto-char beg)
  1126. (setq indent multi-char
  1127. ;; Triple if we will put the comment starter at the margin
  1128. ;; and the first line of the region isn't indented
  1129. ;; at least two spaces.
  1130. triple (and (not multi-char) (looking-at "\t\\| "))))
  1131. (setq indent (nth 3 style)))
  1132. ;; In Lisp and similar modes with one-character comment starters,
  1133. ;; double it by default if `comment-add' says so.
  1134. ;; If it isn't indented, triple it.
  1135. (if (and (null arg) (not multi-char))
  1136. (setq numarg (* comment-add (if triple 2 1)))
  1137. (setq numarg (1- (prefix-numeric-value arg))))
  1138. (comment-region-internal
  1139. beg end
  1140. (let ((s (comment-padright comment-start numarg)))
  1141. (if (string-match comment-start-skip s) s
  1142. (comment-padright comment-start)))
  1143. (let ((s (comment-padleft comment-end numarg)))
  1144. (and s (if (string-match comment-end-skip s) s
  1145. (comment-padright comment-end))))
  1146. (if multi (comment-padright comment-continue numarg))
  1147. (if multi
  1148. (comment-padleft (comment-string-reverse comment-continue) numarg))
  1149. block
  1150. lines
  1151. indent))))))
  1152. ;;;###autoload
  1153. (defun comment-box (beg end &optional arg)
  1154. "Comment out the BEG .. END region, putting it inside a box.
  1155. The numeric prefix ARG specifies how many characters to add to begin- and
  1156. end- comment markers additionally to what variable `comment-add' already
  1157. specifies."
  1158. (interactive "*r\np")
  1159. (comment-normalize-vars)
  1160. (let ((comment-style (if (cadr (assoc comment-style comment-styles))
  1161. 'box-multi 'box)))
  1162. (comment-region beg end (+ comment-add arg))))
  1163. (defun comment-only-p (beg end)
  1164. "Return non-nil if the text between BEG and END is all comments."
  1165. (save-excursion
  1166. (goto-char beg)
  1167. (comment-forward (point-max))
  1168. (<= end (point))))
  1169. ;;;###autoload
  1170. (defun comment-or-uncomment-region (beg end &optional arg)
  1171. "Call `comment-region', unless the region only consists of comments,
  1172. in which case call `uncomment-region'. If a prefix arg is given, it
  1173. is passed on to the respective function."
  1174. (interactive "*r\nP")
  1175. (comment-normalize-vars)
  1176. (funcall (if (comment-only-p beg end)
  1177. 'uncomment-region 'comment-region)
  1178. beg end arg))
  1179. ;;;###autoload
  1180. (defun comment-dwim (arg)
  1181. "Call the comment command you want (Do What I Mean).
  1182. If the region is active and `transient-mark-mode' is on, call
  1183. `comment-region' (unless it only consists of comments, in which
  1184. case it calls `uncomment-region').
  1185. Else, if the current line is empty, call `comment-insert-comment-function'
  1186. if it is defined, otherwise insert a comment and indent it.
  1187. Else if a prefix ARG is specified, call `comment-kill'.
  1188. Else, call `comment-indent'.
  1189. You can configure `comment-style' to change the way regions are commented."
  1190. (interactive "*P")
  1191. (comment-normalize-vars)
  1192. (if (use-region-p)
  1193. (comment-or-uncomment-region (region-beginning) (region-end) arg)
  1194. (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
  1195. ;; FIXME: If there's no comment to kill on this line and ARG is
  1196. ;; specified, calling comment-kill is not very clever.
  1197. (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
  1198. ;; Inserting a comment on a blank line. comment-indent calls
  1199. ;; c-i-c-f if needed in the non-blank case.
  1200. (if comment-insert-comment-function
  1201. (funcall comment-insert-comment-function)
  1202. (let ((add (comment-add arg)))
  1203. ;; Some modes insist on keeping column 0 comment in column 0
  1204. ;; so we need to move away from it before inserting the comment.
  1205. (indent-according-to-mode)
  1206. (insert (comment-padright comment-start add))
  1207. (save-excursion
  1208. (unless (string= "" comment-end)
  1209. (insert (comment-padleft comment-end add)))
  1210. (indent-according-to-mode)))))))
  1211. ;;;###autoload
  1212. (defcustom comment-auto-fill-only-comments nil
  1213. "Non-nil means to only auto-fill inside comments.
  1214. This has no effect in modes that do not define a comment syntax."
  1215. :type 'boolean
  1216. :group 'comment)
  1217. (defun comment-valid-prefix-p (prefix compos)
  1218. "Check that the adaptive fill prefix is consistent with the context.
  1219. PREFIX is the prefix (presumably guessed by `adaptive-fill-mode').
  1220. COMPOS is the position of the beginning of the comment we're in, or nil
  1221. if we're not inside a comment."
  1222. ;; This consistency checking is mostly needed to workaround the limitation
  1223. ;; of auto-fill-mode whose paragraph-determination doesn't pay attention
  1224. ;; to comment boundaries.
  1225. (if (null compos)
  1226. ;; We're not inside a comment: the prefix shouldn't match
  1227. ;; a comment-starter.
  1228. (not (and comment-start comment-start-skip
  1229. (string-match comment-start-skip prefix)))
  1230. (or
  1231. ;; Accept any prefix if the current comment is not EOL-terminated.
  1232. (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
  1233. ;; Accept any prefix that starts with the same comment-start marker
  1234. ;; as the current one.
  1235. (when (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
  1236. prefix)
  1237. (let ((prefix-com (comment-string-strip (match-string 0 prefix) nil t)))
  1238. (string-match "\\`[ \t]*" prefix-com)
  1239. (let* ((prefix-space (match-string 0 prefix-com))
  1240. (prefix-indent (string-width prefix-space))
  1241. (prefix-comstart (substring prefix-com (match-end 0))))
  1242. (save-excursion
  1243. (goto-char compos)
  1244. ;; The comstart marker is the same.
  1245. (and (looking-at (regexp-quote prefix-comstart))
  1246. ;; The indentation as well.
  1247. (or (= prefix-indent
  1248. (- (current-column) (current-left-margin)))
  1249. ;; Check the indentation in two different ways, just
  1250. ;; to try and avoid most of the potential funny cases.
  1251. (equal prefix-space
  1252. (buffer-substring (point)
  1253. (progn (move-to-left-margin)
  1254. (point)))))))))))))
  1255. ;;;###autoload
  1256. (defun comment-indent-new-line (&optional soft)
  1257. "Break line at point and indent, continuing comment if within one.
  1258. This indents the body of the continued comment
  1259. under the previous comment line.
  1260. This command is intended for styles where you write a comment per line,
  1261. starting a new comment (and terminating it if necessary) on each line.
  1262. If you want to continue one comment across several lines, use \\[newline-and-indent].
  1263. If a fill column is specified, it overrides the use of the comment column
  1264. or comment indentation.
  1265. The inserted newline is marked hard if variable `use-hard-newlines' is true,
  1266. unless optional argument SOFT is non-nil."
  1267. (interactive)
  1268. (comment-normalize-vars t)
  1269. (let (compos comin)
  1270. ;; If we are not inside a comment and we only auto-fill comments,
  1271. ;; don't do anything (unless no comment syntax is defined).
  1272. (unless (and comment-start
  1273. comment-auto-fill-only-comments
  1274. (not (called-interactively-p 'interactive))
  1275. (not (save-excursion
  1276. (prog1 (setq compos (comment-beginning))
  1277. (setq comin (point))))))
  1278. ;; Now we know we should auto-fill.
  1279. ;; Insert the newline before removing empty space so that markers
  1280. ;; get preserved better.
  1281. (if soft (insert-and-inherit ?\n) (newline 1))
  1282. (save-excursion (forward-char -1) (delete-horizontal-space))
  1283. (delete-horizontal-space)
  1284. (if (and fill-prefix (not adaptive-fill-mode))
  1285. ;; Blindly trust a non-adaptive fill-prefix.
  1286. (progn
  1287. (indent-to-left-margin)
  1288. (insert-before-markers-and-inherit fill-prefix))
  1289. ;; If necessary check whether we're inside a comment.
  1290. (unless (or compos (null comment-start))
  1291. (save-excursion
  1292. (backward-char)
  1293. (setq compos (comment-beginning))
  1294. (setq comin (point))))
  1295. (cond
  1296. ;; If there's an adaptive prefix, use it unless we're inside
  1297. ;; a comment and the prefix is not a comment starter.
  1298. ((and fill-prefix
  1299. (comment-valid-prefix-p fill-prefix compos))
  1300. (indent-to-left-margin)
  1301. (insert-and-inherit fill-prefix))
  1302. ;; If we're not inside a comment, just try to indent.
  1303. ((not compos) (indent-according-to-mode))
  1304. (t
  1305. (let* ((comstart (buffer-substring compos comin))
  1306. (normalp
  1307. (string-match (regexp-quote (comment-string-strip
  1308. comment-start t t))
  1309. comstart))
  1310. (comend
  1311. (if normalp comment-end
  1312. ;; The comment starter is not the normal comment-start
  1313. ;; so we can't just use comment-end.
  1314. (save-excursion
  1315. (goto-char compos)
  1316. (if (not (comment-forward)) comment-end
  1317. (comment-string-strip
  1318. (buffer-substring
  1319. (save-excursion (comment-enter-backward) (point))
  1320. (point))
  1321. nil t))))))
  1322. (if (and comment-multi-line (> (length comend) 0))
  1323. (indent-according-to-mode)
  1324. (insert-and-inherit ?\n)
  1325. (forward-char -1)
  1326. (let* ((comment-column
  1327. ;; The continuation indentation should be somewhere
  1328. ;; between the current line's indentation (plus 2 for
  1329. ;; good measure) and the current comment's indentation,
  1330. ;; with a preference for comment-column.
  1331. (save-excursion
  1332. ;; FIXME: use prev line's info rather than first
  1333. ;; line's.
  1334. (goto-char compos)
  1335. (min (current-column)
  1336. (max comment-column
  1337. (+ 2 (current-indentation))))))
  1338. (comment-indent-function
  1339. ;; If the previous comment is on its own line, then
  1340. ;; reuse its indentation unconditionally.
  1341. ;; Important for modes like Python/Haskell where
  1342. ;; auto-indentation is unreliable.
  1343. (if (save-excursion (goto-char compos)
  1344. (skip-chars-backward " \t")
  1345. (bolp))
  1346. (lambda () comment-column) comment-indent-function))
  1347. (comment-start comstart)
  1348. (comment-end comend)
  1349. (continuep (or comment-multi-line
  1350. (cadr (assoc comment-style
  1351. comment-styles))))
  1352. ;; Recreate comment-continue from comment-start.
  1353. ;; FIXME: wrong if comment-continue was set explicitly!
  1354. ;; FIXME: use prev line's continuation if available.
  1355. (comment-continue nil))
  1356. (comment-indent continuep))
  1357. (save-excursion
  1358. (let ((pt (point)))
  1359. (end-of-line)
  1360. (let ((comend (buffer-substring pt (point))))
  1361. ;; The 1+ is to make sure we delete the \n inserted above.
  1362. (delete-region pt (1+ (point)))
  1363. (end-of-line 0)
  1364. (insert comend))))))))))))
  1365. ;;;###autoload
  1366. (defun comment-line (n)
  1367. "Comment or uncomment current line and leave point after it.
  1368. With positive prefix, apply to N lines including current one.
  1369. With negative prefix, apply to -N lines above. Also, further
  1370. consecutive invocations of this command will inherit the negative
  1371. argument.
  1372. If region is active, comment lines in active region instead.
  1373. Unlike `comment-dwim', this always comments whole lines."
  1374. (interactive "p")
  1375. (if (use-region-p)
  1376. (comment-or-uncomment-region
  1377. (save-excursion
  1378. (goto-char (region-beginning))
  1379. (line-beginning-position))
  1380. (save-excursion
  1381. (goto-char (region-end))
  1382. (line-end-position)))
  1383. (when (and (eq last-command 'comment-line-backward)
  1384. (natnump n))
  1385. (setq n (- n)))
  1386. (let ((range
  1387. (list (line-beginning-position)
  1388. (goto-char (line-end-position n)))))
  1389. (comment-or-uncomment-region
  1390. (apply #'min range)
  1391. (apply #'max range)))
  1392. (forward-line 1)
  1393. (back-to-indentation)
  1394. (unless (natnump n) (setq this-command 'comment-line-backward))))
  1395. (provide 'newcomment)
  1396. ;;; newcomment.el ends here