Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs insert centered comment block

I would like to create a macro for emacs that will insert a latex comment block with some centerd text like:

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%                Comment 1                    %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%           Comment 2 Commenttext 3           %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Is this possible in emacs-lisp?

like image 328
user3181422 Avatar asked Feb 14 '23 03:02

user3181422


2 Answers

Emacs comes with the command comment-box for this purpose. It produces centered comment boxes, although the width of the box varies depending on the content. E.g., with the region set around the following line:

This is a comment

when you call M-x comment-box the text is transformed to:

;;;;;;;;;;;;;;;;;;;;;;;
;; This is a comment ;;
;;;;;;;;;;;;;;;;;;;;;;;

I use a modifed version that places the comment box around the current line if the region isn't active, and then steps out of the comment afterwards. It also temporarily reduces the fill-column, so the comment box is not wider than your longest line:

(defun ty-box-comment (beg end &optional arg) 
  (interactive "*r\np")
  (when (not (region-active-p))
    (setq beg (point-at-bol))
    (setq end (point-at-eol)))
  (let ((fill-column (- fill-column 6)))
    (fill-region beg end))
  (comment-box beg end arg)
  (ty-move-point-forward-out-of-comment))

(defun ty-point-is-in-comment-p ()
  "t if point is in comment or at the beginning of a commented line, otherwise nil"
  (or (nth 4 (syntax-ppss))
      (looking-at "^\\s *\\s<")))

(defun ty-move-point-forward-out-of-comment ()
  "Move point forward until it's no longer in a comment"
  (while (ty-point-is-in-comment-p)
    (forward-char)))
like image 121
Tyler Avatar answered Feb 16 '23 17:02

Tyler


Here's a yasnippet that you can use:

# -*- mode: snippet -*-
# name: huge_comment
# key: hc
# --
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%${1:$(repeat-char (- 33 (/ (length yas-text) 2)) " ")}$1${1:$(repeat-char (- 74 (length yas-text) (- 33 (/ (length yas-text) 2))) " ")}%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
$0

How to use it: type hc, call yas-expand and start typing the text. It will re-center itself automatically.

This snippet will work from latex-mode or text-mode. I've noticed however a bug that messes up the cursor position if you're using AUCTeX. In that case, you can momentarily switch to text-mode.

like image 40
abo-abo Avatar answered Feb 16 '23 18:02

abo-abo