I want to write a function that copies the current line from a buffer, but transforms it before in certain way. Specifically, I need to generate file names depending from lines of code. For example, having this line of C code:
__asm__ volatile (".rept 200\n\t"
"sub r5, r4, #255\n\t"| // <---- point is the bar
".endr\n\t"
I want to have in my kill-ring/clipboard the string
sub_r5_r4_255.csv
I came up with this very ugly solution:
(defun my--get-instruction-csv-id ()
"Generate a file .csv id from current line."
(interactive)
(save-excursion
(move-beginning-of-line nil)
(set-mark-command nil)
(move-end-of-line nil)
(kill-ring-save nil nil t))
(let ((old-buffer (current-buffer)))
(with-temp-buffer
(yank)
(replace-regexp " " "_" nil (point-min) (point-max))
(replace-regexp "," "" nil (point-min) (point-max))
(replace-regexp "#" "" nil (point-min) (point-max))
(replace-regexp "\\\\t" "" nil (point-min) (point-max))
(replace-regexp "\\\\n" "" nil (point-min) (point-max))
(replace-regexp "\"" "" nil (point-min) (point-max))
(move-end-of-line nil)
(insert ".csv")
(print (buffer-string)) ;(kill-new
)))
(where in the last line kill-new
has been substituded by print
for debug purposes).
However, I recognize this is inefficient and non idiomatic. How can I improve it?
For example, Emacs tells me I should replace replace-regexp
with re-search-forward
and replace-match
: should I do that with a while
loop? Is there an equivalent non regexp function that I can use? Can I avoid killing + yanking from the C buffer?
(buffer-substring (line-beginning-position) (point))
would get you the current line (up to wherepoint
is - if you want the whole line, replace the(point)
call with(line-end-position)
) as a string that you caninsert
into your temp buffer instead ofyank
ing. I'm sure you'll get more suggestions for the rest as well.line-beginning-position
andline-end-position
but I couldn't find them