emacs make square block comments with right aligned border

ascii-art, code-formatting, emacs

Solution

The venerable and versatile library "rebox2" can do this.

To install, download https://raw.github.com/lewang/rebox2/master/rebox2.el into your site-lisp dir, and add the following to your `.emacs` file:

(require 'rebox2)

; The following template defines the specific style required here,
; which does not correspond to any built-in rebox2 style.
;
; "75" means that the style is registered as x75, where "x" depends
; on the current langauge mode. The "?" char is switched for the language
; specific comment char
;
; "999" is the weighting used for recognising this comment style.
; This value works for me.
(rebox-register-template
 75
 999
 '("?*************?"
   "?* box123456 *?"
   "?*************?"))

(add-hook 'perl-mode-hook (lambda ()
; The "style loop" specifies a list of box styles which rebox will cycle
; through if you refill (M-q) a box repeatedly. Having "11" in this loop
; will allow you to easily "unbox" a comment block, e.g. for "uncomment-region"
                (set (make-local-variable 'rebox-style-loop) '(75 11))
; The "min-fill-column" setting ensures that the box is not made narrower
; when the text is short
                (set (make-local-variable 'rebox-min-fill-column) 79)
                (rebox-mode 1)))

Now:

- To convert some text into a block comment in this format, you just select the text and do `M-q`

- To edit the text in a block comment, you can just edit the text directly, and emacs will reflow the box automatically. (You may need to do `M-q` to request a reflow if emacs doesn't automatically do it.)

Problem

I need to write code comments with aligned borders on all four sides due to an externally enforced coding standard. What's the easiest way, in Emacs, to: - Convert some text into a block comment in this format - Edit the text in a block comment and have Emacs reflow it correctly Comment format examples: ``` #*****************************************************************************# #* This is a block comment. It has right-aligned borders. *# #* *# #* It can have separate paragraphs. Text in a long paragraph flows from one *# #* line to the next with one space of internal padding. *# #* *# #* The right hand border is at char 78 *# #*****************************************************************************# sub MySub { #***************************************************************************# #* The left hand edge of the comment is aligned with the current code *# #* block, but the right hand border is still at char 78 *# #***************************************************************************# my $var = 3; } ``` `auto-fill-mode` by itself doesn't preserve the right hand border.

Original source