1

Say that I have rect1 one and I'll multiply it 3 times by yanking.

let rect1 = Rectangle {
    width: 10,
    height: 40,
    }
    
    let rect1 = Rectangle {
    width: 10,
    height: 40,
    }
    
    let rect1 = Rectangle {
    width: 10,
    height: 40,

How can I obtain rect1, rect2, rect3 etc. instead of just repeating rect1?

3
  • In this particular situation, nothing will beat moving your cursor to the appropriate place, deleting the 1 and typing the appropriate replacement. But if you have ten or a hundred or a thousand copies of that (which you should not have: that's what arrays are for), it's a different story. – NickD Feb 8 at 14:30
  • I'm new to programming, and I ran into this issue many times. I understand your point, but I switched from vim to emacs basically because of such problems :D Maybe I've reached to the point write my own elisp script? o.O – zoldseges Feb 8 at 14:44
  • 2
    Writing a keyboard macro would be the next step up from just editing them all by hand. But as NickD said, there are ways to write your programs that don't require so much repetition. For example, you could have one variable that holds an array of Rectangles, rather than having three variables each holding one Rectangle. If you haven't learned about arrays yet, then just keep going until you do. – db48x Feb 8 at 15:57
3

query-replace-regexp can do the trick. Select the region you want for replacing and :

 C-M %  \brect1\b RET rect\,(1+ \#) RET !

for more information

(info "(emacs)Regexp Replacement")

;;;;;;;;;;;;;;;;;;;;;;;;; A function for more comfort;;;;;;;;;;;;;;;;;;;;;;;;;

(defun multiple-paste-renum(n renum paste )
  "Paste N copy of PASTE and renumber the string RENUM followed by digits
 from 1 to until the last"
  (interactive "nNumber repeats: \nsWord to be renumerate: \nsText or RET for the current kill-ring: ")
  (let ((text (if (string= "" paste) (substring-no-properties (current-kill 0))paste)))
  (insert (with-temp-buffer
            (dotimes (p n) (insert "\n" text "\n"))
            (goto-char (point-min))
            (let ((p 0))
            (while (search-forward-regexp (format "\\b%s[0-9]+\\b" renum) nil t)
              (replace-match (format "%s%d" renum (setq p (1+ p))))))
            (buffer-string)))))
1
  • I have composed a function which I hope corresponds to your desire. Just evaluate it (or in your init file if you want to keep it). You can activate it with M-x multiple-paste-renum or you can assign a key of your choice. Type the number of copies you want, the word you want to index, and the text. If the latter is in the kill-ting, just hit Enter. – gigiair Feb 15 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.