newcomment.el 56 KB

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