I have written the following code
(defun krmet-replace()
(interactive)
(save-excursion
(save-restriction
;; Narrow to the region
(narrow-to-region
(progn (search-forward "C %% MODULE %%")
(line-beginning-position))
(progn (search-forward "C %% END MODULE %%")
(line-end-position)))
;; Find Replace
(goto-char (point-min))
(while (search-forward "KRMET" nil t)
(replace-match "KR23" nil t)) ;; remove the hard coded replacement, use user input
(goto-char (point-min))
(while (search-forward "KR-MET" nil t)
(replace-match "KR-23" nil t))))) ;;;; remove the hard coded replacement, use user input
(global-set-key (kbd "C-c #") 'krmet-replace)
There are two things that I don not know how to do:
- How to interactively pass a number, in this case it is "23". I want to replace
KRMET
withKR23
. I modified the code like shown below
(defun krmet-replace (r)
(interactive "nRx # : ")
and used the r
in replace match line like so
(replace-match (concat "KR" string(r)) nil t))
I get this error: replace-match: Symbol’s value as variable is void: string
Answer Edit:
I fixed the first problem like so using number-to-string
function
(goto-char (point-min))
(while (search-forward "KRMET" nil t)
(replace-match (concat "KR" (number-to-string r)) nil t))
(goto-char (point-min))
(while (search-forward "KR-MET" nil t)
(replace-match (concat "KR-" (number-to-string r)) nil t)))))
- How to replace string using regex? Like KRMET or KR-MET with KR
nn
or KR-nn
wherenn
is the user provided number when running the function
(format "KR-%d" r)
to convert your number into a string? Use%02d
if single digit numbers should have a zero prefixed.string(r)
isn't passingr
to a functionstring
; it's two separate expressions:string
-- evaluating the variablestring
, and(r)
-- calling the functionr
. Hence the error "Symbol’s value as variable is void: string" because it turned out thatstring
wasn't a variable. As you established yourself,(number-to-string r)
was how that should have looked. I would still suggest usingformat
, but either approach is fine.