newcomment.el 55 KB

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