Here's something simpler without Yassnippet:
(defun sprintf-to-ofstream (file) (interactive "sFile to print to: ") (back-to-indentation) (let* ((start (point)) arglist sprintf-args ofstream-args (end (save-excursion (move-end-of-line 1) (point))) (line (buffer-substring-no-properties start end))) (unless (string= (substring line 0 7) "sprintf") (error "No `sprintf' at this line")) (setq arglist (split-string (substring line (1+ (position ?\( line)) (position ?\) line :from-end t)) "\\s-*,\\s-*") sprintf-args (split-string (substring (cadr arglist) 1 -1) "%[^[:alpha:]%#]*[[:alpha:]%#]") ofstream-args (with-output-to-string (princ (concat "\"" (car sprintf-args) "\"")) (setq sprintf-args (cdr sprintf-args)) (dotimes (i (length sprintf-args)) (princ " + ") (when (< (+ i 2) (length arglist)) (princ (nth (+ i 2) arglist)) (princ " + ")) (princ (concat "\"" (nth i sprintf-args) "\""))))) (kill-region start end) (insert (concat "ofstream " file "((" ofstream-args ").c_str());" ))))
You can bind it to any key you use and use it like this:
- Move the point to the line containing
sprintf that you want to replace, for example, by running M-% sprintf , then call this function. He will ask you to specify the name of the file in which you want to print the message (maybe I could make it more complex and look up for the place where the stream was declared, but if you say that it may have been declared in an arbitrary place, which sounds like a wasted effort). - Press RET , after which the function will change the line to look:
ofstream foo(("" + a.c_str() + "/soln" + b + ".dat").c_str());
considering your original example. Obviously, if you think adding the to_string() arguments around is more likely, then this is easy to do, but with some extra effort it is also easy to avoid joining blank lines, but sometimes this can change the effect / interpretation of the + operator, so I decided to keep it in this way. I will try to do this in the yassnippet script a little later today, so that it would be possible to interactively go to undefined places in the replaced line and have some predefined replacements.
user797257
source share