5

Assume that I have the following code:

int x;
string s = "some very long "
           " string";

I would like to have one command that swaps the order of these without ending up with something like:

string s = "some very long"
int x;
           "string";

Is there an easy way to do it?

  • Does C-M-t (transpose-sexps) help? It's supposed to, but maybe it doesn't in C. – Drew Feb 27 '16 at 20:55
  • Nope, it does something very different. – eof Feb 28 '16 at 0:14
  • 1
    It might depend on where you put the cursor. Dunno what Emacs considers a sexp in C. Perhaps it is not very sophisticated. You might see whether any of the other transpose-* commands (transpose-paragraph?) help at all here. Anyway, probably there are 3rd-party libraries that offer what you request, and hopefully someone will let you know here. – Drew Feb 28 '16 at 2:08
  • I would suggest: 1) highlite one of the statements 2) 'yank' the statement 3) 'put' the statement in its' new location. When you have developed a macro that will yank from start of statement (??beginning of line??) to first semicolon, then add feature to search for next semicolon then step forward past newline, then paste. Then you can use that macro for what you want to perform. (probably a LOT faster to just perform the steps via keyboard and mouse actions) Be sure to save that macro into the emacs startup file – user3629249 Feb 29 '16 at 0:42
  • Maybe sp-transpose-hybrid-sexp docs from smartparens will do it, at least it you put parenthesis around the pair of strings. – Omar Feb 29 '16 at 17:31
1

I recommend using smartparens. For non-lisp languages it has the useful notion of "hybrid s-expression". Its command sp-transpose-hybrid-sexp doesn't quite work directly on your example, but if you are willing to wrap those two string in parenthesis it does work (also, Emacs seems to indent much better with the added parenthesis). If you run it on the following text with the point any where in string s = it will correctly swap the two declarations:

int x;
string s = ("some very long "
            " string");
0

anchored-transpose may be another option.

Bind anchored-transpose to C-x t, then you can mark the first statement, press C-x t, mark the second statement, press C-x t, and these two statements are swapped. It seems NOT very convenient at the first sight, so it's better if you use it with other packages which can quickly mark the statements.

EDIT: I've just realized that anchored-transpose may not be a good solution to this special case. If you quickly mark the region, you can just do a C-w to kill the region then paste it. anchored-transpose should fit some more general cases where there are no something like sexp or statement, just random texts.

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.