Emacs insert centered comment block - emacs

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?

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)))

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.

The question was whether it is possible in emacs-lisp. Yes it is. There are several ways to do it.
I will show one way where you can also comment several lines of text.
Maybe, in the first line there is the title of the part of text and in the second one there is the author of this part.
A better way would be to advice LaTeX-indent-line function. This way you could edit the comment text and re-indent. When I find time I will show you also this variant.
Usage: Write your comment as clear text. Mark text as region with the mouse and then run the following command.
(defun LaTeX-centered-comment (b e)
"Convert region into centered comment."
(interactive "r")
(let* ((n (count-lines b e)))
(goto-char b)
(beginning-of-line)
(insert-char ?% fill-column)
(insert ?\n)
(setq b (point))
(center-line n)
(goto-char b)
(loop for i from 1 upto n do
(replace-region (point) (+ (point) 3) "%%%")
(end-of-line)
(insert-char ?\ (max 0 (- fill-column (- (point) (line-beginning-position)) 3)))
(insert "%%%")
(forward-line))
(insert-char ?% fill-column)
(insert ?\n)
))

Related

Split lines of current paragraph in Emacs

I want to add a function (para2lines) to Emacs by which I can split the current paragraph into its sentences and print them line by line in a separate buffer. Following is code in Racket/Scheme:
(define (p2l paraString)
(define lst (string-split paraString ". "))
(for ((i lst))
(displayln i)))
Testing:
(p2l "This is a test. For checking only. Only three lines.")
Output:
This is a test.
For checking only.
Only three lines.
In Emacs Lisp, I could manage following code:
(defun pl (ss)
(interactive)
(let ((lst (split-string (ss))))
(while lst
(print (pop lst)))))
But I do not know how to get the text from the paragraph with current position. How can I correct this function?
Edit: basically, I want to read it as separate lines but want to save it as paragraph.
Here's an example that might help you on your way. It will do your conversion to the current paragraph (i.e. where the cursor is positioned), rather than to a new buffer. You could modify this to pass a string to your function if that's what you require.
(defun p2l ()
"Format current paragraph into single lines."
(interactive "*")
(save-excursion
(forward-paragraph)
(let ((foo (point)))
(backward-paragraph)
(replace-regexp "\n" " " nil (1+ (point)) foo)
(backward-paragraph)
(replace-regexp "\\. ?" ".\n" nil (point) foo))))
I would just run Emacs commands or write a macro to convert a paragraph to single-sentence lines, but maybe you are really just wanting to read wrapped paragraphs as lines, thus the need to have an Emacs command.
Here's something that will grab the current paragraph, insert a new buffer *Lines*, and then convert sentences to lines.
(defun para-lines ()
"Split sentences of paragraph to lines in new buffer."
(interactive)
;; Move the paragraph to a new buffer.
(let ((b (generate-new-buffer "*Lines*")))
(with-output-to-temp-buffer b
(let ((beg (save-excursion (forward-paragraph -1) (point)))
(end (save-excursion (forward-paragraph +1) (point))))
(princ (buffer-substring-no-properties beg end))))
;; Switch to new buffer
(with-current-buffer b
;; Since the name starts with "*", shut off Help Mode
(fundamental-mode)
;; Make sure buffer is writable
(setq buffer-read-only nil)
;; From the start of the buffer
(goto-char (point-min))
;; While not at the end of the buffer
(while (< (point) (point-max))
(forward-sentence 1)
;; Delete spaces between sentences before making new new line
(delete-horizontal-space)
;; Don't add a new line, if already at the end of the line
(unless (= (line-end-position) (point))
(newline))))))
To avoid using forward-sentence, and just use a regular expression, use re-search-forward. For instance, to match semi-colons as well as periods.
(defun para-lines ()
"Split sentences of paragraph to lines in new buffer."
(interactive)
;; Move the paragraph to a new buffer.
(let ((b (generate-new-buffer "*Lines*")))
(with-output-to-temp-buffer b
(let ((beg (save-excursion (forward-paragraph -1) (point)))
(end (save-excursion (forward-paragraph +1) (point))))
(princ (buffer-substring-no-properties beg end))))
;; Switch to new buffer
(with-current-buffer b
;; Since the name starts with "*", shut off Help Mode
(fundamental-mode)
;; Make sure buffer is writable
(setq buffer-read-only nil)
;; From the start of the buffer
(goto-char (point-min))
;; While not at the end of the buffer
(while (< (point) (point-max))
(re-search-forward "[.;]\\s-+" nil t)
;; Delete spaces between sentences before making new new line
(delete-horizontal-space)
;; Don't add a new line, if already at the end of the line
(unless (= (line-end-position) (point))
(newline))))))

Emacs24 and python-mode: indention in docstrings

I have the following code/text:
def f():
"""
Return nothing.
.. NOTE::
First note line
second note line
In Emacs23 (23.4.1) I was able to press TAB in the last line ("second note line"; nomatter how this line was indented) and it was aligned correctly like this:
def f():
"""
Return nothing.
.. NOTE::
First note line
second note line
I.e., it uses the previous line and indents the following line in the same way.
Now in Emacs24 (24.3.1) this does not work anymore and it is aligned like this:
def f():
"""
Return nothing.
.. NOTE::
First note line
second note line
I.e. it aligns the multi-line string block, but does not depend on the previous line.
It affects only docstrings; code is indented as I want. I am using python-mode. How can I change this, so that pressing TAB aligns the block correctly?
Python mode has changed quite a bit between Emacs 23 and 24. There is no configuration that would allow you to do what you want.
But, Emacs is quite flexible and you can advise the (python-indent-context) function to make it return a different result that will lead to the behavior you want. The function (python-indent-context) returns a character at which the indentation is measured and used for indenting the current line. By default, when inside a string, it returns the point where the beginning of the string resides. Thus, your line will be indented to the indentation of the start of the string. We can easily modify it to return a point in the previous non-empty line instead, for instance like this:
(defun python-fake-indent-context (orig-fun &rest args)
(let ((res (apply orig-fun args))) ; Get the original result
(pcase res
(`(:inside-string . ,start) ; When inside a string
`(:inside-string . ,(save-excursion ; Find a point in previous non-empty line
(beginning-of-line)
(backward-sexp)
(point))))
(_ res)))) ; Otherwise, return the result as is
;; Add the advice
(advice-add 'python-indent-context :around #'python-fake-indent-context)
The same effect can be achieved using the old defadvice for older Emacs:
(defadvice python-indent-context (after python-fake-indent-context)
(pcase ad-return-value
(`(:inside-string . ,start) ; When inside a string
(setq ad-return-value ; Set return value
`(:inside-string . ,(save-excursion ; Find a point in previous non-empty line
(beginning-of-line)
(backward-sexp)
(point)))))))
(ad-activate 'python-indent-context)
What about editing the section de-stringified in a separate buffer? That would allow python-mode with all its facilities.
Here a first draft - original string will be stored in kill-ring:
(defun temp-edit-docstring ()
"Edit docstring in python-mode. "
(interactive "*")
(let ((orig (point))
(pps (parse-partial-sexp (point-min) (point))))
(when (nth 3 pps)
(let* (;; relative position in string
(relpos (- orig (+ 2 (nth 8 pps))))
(beg (progn (goto-char (nth 8 pps))
(skip-chars-forward (char-to-string (char-after)))(push-mark)(point)))
(end (progn (goto-char (nth 8 pps))
(forward-sexp)
(skip-chars-backward (char-to-string (char-before)))
(point)))
(docstring (buffer-substring beg end)))
(kill-region beg end)
(set-buffer (get-buffer-create "Edit docstring"))
(erase-buffer)
(switch-to-buffer (current-buffer))
(insert docstring)
(python-mode)
(goto-char relpos)))))
When ready, copy the contents back into original buffer.
Which remains to be implemented still.

Creating emacs mode: defining indentation

I'm writing a simple mode for a Lisp-like language, and am having trouble setting up indentation. I've been following the emacswiki mode tutorial.
However, I can't figure out how to adapt their example indentation to my needs because they don't do any form of counting.
Basically, I just need to add 2 spaces to my indentation count every time I see a { or (, even if there are multiple on the same line, and subtract 2 spaces when I see closures of the above. I'm new to elisp; how can I adapt their example to count braces and brackets?
For convenience, here is the code they are using (for a non-bracket language):
(defun wpdl-indent-line ()
"Indent current line as WPDL code"
(interactive)
(beginning-of-line)
(if (bobp) ; Check for rule 1
(indent-line-to 0)
(let ((not-indented t) cur-indent)
(if (looking-at "^[ \t]*END_") ; Check for rule 2
(progn
(save-excursion
(forward-line -1)
(setq cur-indent (- (current-indentation) default-tab-width)))
(if (< cur-indent 0)
(setq cur-indent 0)))
(save-excursion
(while not-indented
(forward-line -1)
(if (looking-at "^[ \t]*END_") ; Check for rule 3
(progn
(setq cur-indent (current-indentation))
(setq not-indented nil))
; Check for rule 4
(if (looking-at "^[ \t]*\\(PARTICIPANT\\|MODEL\\|APPLICATION\\|WORKFLOW\\|ACTIVITY\\|DATA\\|TOOL_LIST\\|TRANSITION\\)")
(progn
(setq cur-indent (+ (current-indentation) default-tab-width))
(setq not-indented nil))
(if (bobp) ; Check for rule 5
(setq not-indented nil)))))))
(if cur-indent
(indent-line-to cur-indent)
(indent-line-to 0))))) ; If we didn't see an indentation hint, then allow no indentation
How can I just implement lisp-like indentation (but also with curly braces)?
If you want something simple for a Lisp-style language, I suggest you start with (syntax-ppss) which returns the "parsing state" at point. The first element of that state is the current paren-nesting depth. While I used the word "paren", this doesn't really count parens but counts those chars which the syntax-table defines as paren-like, so if you set your syntax-table such that { and } are declared as paren-like, then those will also be counted.
So you could start with something like
(defun foo-indent-function ()
(save-excursion
(beginning-of-line)
(indent-line-to (* 2 (car (syntax-ppss))))))
Do not define this as interactive, since the way to use it is by adding
(set (make-local-variable 'indent-line-function) #'foo-indent-function)
in your major-mode function.
But maybe a better option is to simply do:
(require 'smie)
...
(define-derived-mode foo-mode "Foo"
...
(smie-setup nil #'ignore)
...)
This will use an indentation step of 4 (configured in smie-indent-basic).

a custom comment box on emacs

What would an Emacs macro look like which turns the following line:
# abc def
into:
# +-------------+
# | abc def |
# +-------------+
? The macro need not be general at all: It can hard code the box specs (i.e. 3 spaces before and after the comment, the frame characters (|, +, - ), and assume that the comment is a one-liner. It should, however, use whatever comment character is set for the current mode, and get the box length correct.
I'd also appreciate if you knew of an existing package which does this.
Thanks!
This does what I think you want:
(defun box-comment-region (beg end)
"do some fancy commenting"
(interactive "r")
(save-restriction
(narrow-to-region beg end)
(comment-region beg end -1) ; first, uncomment
(string-rectangle (point-min)
(progn (goto-char (point-max)) (line-beginning-position))
" | ")
(goto-char (point-min))
(let ((max-len 0))
(while (< (point) (point-max))
(end-of-line)
(setq max-len (max max-len (current-column)))
(forward-line 1))
(previous-line)
(end-of-line)
(insert (make-string (- max-len (current-column)) ?\ ))
(goto-char (point-min))
(end-of-line)
(insert (make-string (- max-len (current-column)) ?\ ))
(end-of-line)
(let ((top (point)))
(goto-char (point-max))
(previous-line)
(end-of-line)
(string-rectangle top (point) " | "))
(let ((line-seg (concat " +" (make-string (- max-len 2) ?-) "+ \n")))
(goto-char (point-max))
(insert line-seg)
(goto-char (point-min))
(insert line-seg)))
(comment-region (point-min) (point-max))))
newcomment has a function called comment-box, which produces a box comment consisting of the comment characters, i.e.:
###########
# abc def #
###########
or
/***********/
/* abc def */
/***********/
depending on the mode. The only configurability it has is the number of characters to use for the box; for example in Lisp modes you end up with:
;;;;;;;;;;;;;
;; abc def ;;
;;;;;;;;;;;;;
The comment-region-default function should give you some idea of how to do comments. newcomment's comment styles aren't sufficiently flexible to implement what you want, so I think it'd be easiest to simply draw the box then add a regular (single or multiline, in languages where there is difference) comment to the region using the existing newcomment machinery.
There is a feature called picture-mode, which might do something like that.
M-x picture-mode
rebox2 is the most comprehensive emacs box drawing extension.
The function
M-x comment-box
available as of Emacs 24.4 does this using point and mark as one would expect.

Wrap selection in Open/Close Tag like TextMate?

In TextMate, one can use ctrl-shift-w to wrap text in an Open/Close tag and ctrl-shift-cmd-w to wrap each line in a region in Open/Close tags. How can I implement this same functionality in Emacs using emacs lisp?
emacs
becomes
<p>emacs</p>
And ...
emacs
textmate
vi
becomes
<li>emacs</li>
<li>textmate</li>
<li>vi</li>
This answer gives you a solution for wrapping the region (once you modify it to use angle brackets).
This routine will prompt you for the tag to use, and should tag every line in the region with an open/close tag of that type:
(defun my-tag-lines (b e tag)
"'tag' every line in the region with a tag"
(interactive "r\nMTag for line: ")
(save-restriction
(narrow-to-region b e)
(save-excursion
(goto-char (point-min))
(while (< (point) (point-max))
(beginning-of-line)
(insert (format "<%s>" tag))
(end-of-line)
(insert (format "</%s>" tag))
(forward-line 1)))))
*Note: *If you wanted the tag to always be li, then remove the tag argument, remove the text \nMTag for line: from the call to interactive, and update the insert calls to just insert the "<li\>" as you would expect.
For sgml-mode deratives, mark region to tagify, type M-x sgml-tag, and type the tag name you like to use (press TAB to get list of available HTML elements). Altough, this method does not allow you to tagify each line in a region, you can work around this by recording a keyboard macro.
yasnippet is a particularly good implementation of Textmate's snippet syntax for Emacs. With that you can import all of Textmate's snippets. If you install it then, this snippet that I wrote should do what you want:
(defun wrap-region-or-point-with-html-tag (start end)
"Wraps the selected text or the point with a tag"
(interactive "r")
(let (string)
(if mark-active
(list (setq string (buffer-substring start end))
(delete-region start end)))
(yas/expand-snippet (point)
(point)
(concat "<${1:p}>" string "$0</${1:$(replace-regexp-in-string \" .*\" \"\" text)}>"))))
(global-set-key (kbd "C-W") 'wrap-region-or-point-with-html-tag)
EDIT: (Okay this is my last attempt at fixing this. It is exactly like Textmate's version. It even ignores characters after a space in the end tag)
Sorry I misread your question. This function should edit each line in the region.
(defun wrap-lines-in-region-with-html-tag (start end)
"Wraps the selected text or the point with a tag"
(interactive "r")
(let (string)
(if mark-active
(list (setq string (buffer-substring start end))
(delete-region start end)))
(yas/expand-snippet
(replace-regexp-in-string "\\(<$1>\\).*\\'" "<${1:p}>"
(mapconcat
(lambda (line) (format "%s" line))
(mapcar
(lambda (match) (concat "<$1>" match "</${1:$(replace-regexp-in-string \" .*\" \"\" text)}>"))
(split-string string "[\r\n]")) "\n") t nil 1) (point) (point))))
This variant on Trey's answer will also indent the html correctly.
(defun wrap-lines-region-html (b e tag)
"'tag' every line in the region with a tag"
(interactive "r\nMTag for line: ")
(setq p (point-marker))
(save-excursion
(goto-char b)
(while (< (point) p)
(beginning-of-line)
(indent-according-to-mode)
(insert (format "<%s>" tag))
(end-of-line)
(insert (format "</%s>" tag))
(forward-line 1))))