]> git.eshelyaron.com Git - emacs.git/commitdiff
New minor mode: `electric-block-comment-mode'
authorElías Gabriel Pérez <eg642616@gmail.com>
Mon, 17 Mar 2025 18:56:52 +0000 (12:56 -0600)
committerEshel Yaron <me@eshelyaron.com>
Mon, 31 Mar 2025 08:33:25 +0000 (10:33 +0200)
This minor lets you automatically closing block comments after
typing `block-comment-start'.  Thus, typing "/*" in c-mode and
its derivatives automatically inserts "*/".  (Bug#77081)

* etc/NEWS: Add minor-mode item.
* lisp/electric.el
(electric-block-comment-post-self-insert-function): New function.
(electric-block-comment-mode): New minor mode definition.

(cherry picked from commit 989f9f01f731c0dd0382bad50f1c45894d69c3ea)

lisp/electric.el

index 7aacb3af39f514f97d6d52d23b0d91caa55ffacc..8c8824a63279dbe999f6d66fc5d1bf5e2717ff79 100644 (file)
@@ -398,6 +398,36 @@ use `electric-quote-local-mode'."
     (setq-default electric-quote-mode nil) ; But keep it globally disabled.
     )))
 
+;;; Electric comment block
+
+(defun electric-block-comment-post-self-insert-function ()
+  "Function that `electric-block-comment' adds to `post-self-insert-hook'.
+This closes block comment with `block-comment-end' when `block-comment-start'
+is typed."
+  (when (and block-comment-start block-comment-end
+             ;; Check if we are exactly behind a `block-comment-start'
+             (save-excursion
+               (save-match-data
+                 (re-search-backward (regexp-quote block-comment-start)
+                                     (- (point) (length block-comment-start))
+                                     t)))
+             ;; And if there is not anything front us
+             (looking-at-p (concat "[^[:space:]]")))
+    (insert " ")
+    (save-excursion
+      (insert (concat " " block-comment-end)))))
+
+(define-minor-mode electric-block-comment-mode
+  "Toggle automatic closing of block comments (Electric Block Comment mode).
+
+When enabled, typing `block-comment-start' closes it inserting their
+corresponding `block-comment-end'."
+  :group 'electricity
+  :version "31.1"
+  (if electric-block-comment-mode
+      (add-hook 'post-self-insert-hook #'electric-block-comment-post-self-insert-function 10 t)
+    (remove-hook 'post-self-insert-hook #'electric-block-comment-post-self-insert-function t)))
+
 (provide 'electric)
 
 ;;; electric.el ends here