Reputation: 5917
I recently switched from vi to emacs, and now I'm porting my most important macros to emacs. What I need most is the ability to prefix a marked region of text with a string, including header and footer:
Original:
line 1
line 2
line 3
line 4
After marking the 2nd and 3rd line, I want emacs to ask me for a number, say 002, and do the following, ideally remembering my choice:
line 1
*#002# Start:
*$line 2
*$line 3
*#002# End.
line 4
So far, I have managed to insert start and end tags with the following code:
(defun comment-region (start end)
"Insert COBOL comments."
(interactive "r")
(save-excursion
(goto-char end) (insert "*#xxx# End.\n")
(goto-char start) (insert "*#xxx# Start:\n")
))
However, I can't seem to find out how to prefix all lines in the region with *$
and how to make emacs ask me for a string.
Any ideas?
Upvotes: 2
Views: 620
Reputation: 826
This is a better approach, but its a little awkward at the end...
(defun comment-region (start end prefix)
"Insert COBOL comments."
(interactive "r\nsPrefix: ")
(save-excursion
(narrow-to-region start end)
(goto-char (point-min))
(insert "*#" prefix " #Start.\n")
(while (not (eobp))
(insert "*$")
(forward-line))
(insert "*#" prefix " #End.\n")
(widen)))
Upvotes: 1
Reputation: 60014
Your best bet is to use cobol-mode instead of writing ad hoc functions yourself.
The file header contains detailed instructions on how to use it.
Then just use C-x C which runs the command comment-region
, which comments the region according to the major mode (in your case, cobol).
Upvotes: 1
Reputation: 17707
I've taken to solving this type of problems by dynamically generating a snippet with yasnippet lately.
Here is the code:
(require 'yasnippet)
(defun cobol-comment-region (beg end)
"comment a region as cobol (lines 2,3 commented)
line 1
*#002# Start:
*$line 2
*$line 3
*#002# End.
line 4
"
(interactive "*r")
(setq beg (progn
(goto-char beg)
(point-at-bol 1))
end (progn
(goto-char end)
(if (bolp)
(point)
(forward-line 1)
(if (bolp)
(point)
(insert "\n")
(point)))))
(let* ((str (replace-regexp-in-string
"^" "*$" (buffer-substring-no-properties beg (1- end))))
(template (concat "*#${1:002}# Start:\n"
str
"\n*#$1# End.\n"))
(yas-indent-line 'fixed))
(delete-region beg end)
(yas-expand-snippet template)))
Here is a video of it in action:
Upvotes: 3