65 lines
2.5 KiB
EmacsLisp
65 lines
2.5 KiB
EmacsLisp
;;; c-comments.el --- Functions for working with C-style comments.-*- lexical-binding: t -*-
|
|
;;; Commentary:
|
|
;;; Code:
|
|
|
|
(defun c-comments-bounds-at-point ()
|
|
"Return the bounds of the multi-line comment around point."
|
|
(let* ((syntax-info (syntax-ppss))
|
|
(in-comment (nth 4 syntax-info))
|
|
(is-multiline (and in-comment
|
|
(not (nth 7 syntax-info)))))
|
|
(cond
|
|
(is-multiline
|
|
(let ((start (save-excursion
|
|
(end-of-line)
|
|
(search-backward "/*" nil t)))
|
|
(end (save-excursion
|
|
(beginning-of-line)
|
|
(search-forward "*/" nil t))))
|
|
(when (and start
|
|
(>= (point) start)
|
|
(or (not end)
|
|
(<= (point) (- end 2))))
|
|
(cons start end))))
|
|
(in-comment
|
|
(let ((start (save-excursion
|
|
(beginning-of-line)
|
|
(search-forward "//" (pos-eol) t))))
|
|
(and (>= (point) start)
|
|
(cons start (pos-eol))))))))
|
|
(defun c-comments--need-comment-terminator (bounds)
|
|
"Return non-nil if a comment terminator needs to be inserted given BOUNDS."
|
|
(and (or (not (cdr bounds))
|
|
(save-excursion
|
|
(search-forward "/*" (cdr bounds) t)))))
|
|
(defun c-comments-newline (&optional arg always-continue)
|
|
"Insert ARG newlines and indent, automatically closing multi-line comments.
|
|
Also, insert \"* \" at the beginning of every line when executed from inside a
|
|
multi-line comment. If ALWAYS-CONTINUE is true, also insert \"//\" if called
|
|
from inside a C++-style single-line comment."
|
|
(interactive "*Pi")
|
|
(when (and arg (< (prefix-numeric-value arg) 0))
|
|
(user-error "Count cannot be negative"))
|
|
(if-let ((bounds (c-comments-bounds-at-point))
|
|
((or always-continue (not (nth 7 (syntax-ppss))))))
|
|
(progn
|
|
(when (c-comments--need-comment-terminator bounds)
|
|
(save-excursion
|
|
(insert "\n*/")
|
|
(indent-region (pos-bol) (pos-eol))))
|
|
(dotimes (_ (prefix-numeric-value arg))
|
|
(default-indent-new-line))
|
|
(when (save-excursion
|
|
(forward-char -1)
|
|
(looking-at-p (regexp-opt '("*" "/"))))
|
|
(insert " ")))
|
|
(newline arg t)))
|
|
(defun c-comments-newline-always-continue (&optional arg)
|
|
"Like calling `c-comments-newline', but always continue comments.
|
|
That is, this is equivalent to (c-comments-newline ARG t)."
|
|
(interactive "*P")
|
|
(c-comments-newline arg t))
|
|
|
|
(provide 'c-comments)
|
|
;;; c-comments.el ends here
|