6

Say you would for instance define 5 variables with multiple cursors and you wanted to name them x_i where i ∈ {1,2,3,4,5}. Instead of writing 5 rows with x_ and then filling the rest manually, is there any way this could be done with multiple cursors?

I.e. like https://github.com/duydao/Text-Pastry for sublime.

2 Answers 2

14

Yes, it's possible with multiple-cursors.

enter image description here

  • Let's say you have atleast 5 consecutive empty lines.
  • With the cursor at the topmost empty line, create 5 multiple cursors by keeping on hitting C-> (default binding for mc/mark-next-like-this).
  • Type the common variable prefix: x_ as per your example.
  • Insert numbers starting with the prefix you specify (default starting number is 0) to mc/insert-numbers. For your example, you would do C-u 1 M-x mc/insert-numbers.
  • Hit C-g or RET to exit multiple cursors mode.

Alternative way using the tiny package

Type m1\n5|x_%d and M-x tiny-expand.

The best part is that you can undo and get back to that expression, tweak it, M-x tiny-expand, repeat, ..


tiny syntax cheat-sheet

mBSEO|F ││││-- │││││└──> (optional) Format - %x | 0x%x | %c | %s | %(+ x x) | %014.2f | %03d ││││└───> (optional) Pipe character used if Format specified for reading clarity │││└────> (optional) Lisp Operation - *xx | (* x x) | (+ x ?A) | *2+3x | (* 2 (+ 3 x)) ││└─────> End value │└──────> (optional) Separator - Space | , | \n (default=Space) └───────> (optional) Begin value (default=0) - No space allowed between 'm' and 'B' - No space allowed between 'E' and 'O' 
5

This can also easily be done with built-in features of Emacs, namely keyboard macros. Let's say, as in kashualmodi's answer, that you want to write this:

x_1 x_2 x_3 x_4 x_5 

You can type: C-1 <f3> x_ <f3> RET C-5 <f4>. Step by step:

  • C-1 <f3>: the <f3> starts recording a keyboard macro, each keyboard macro gets its own counter which starts at 0 by default; the C-1 makes the counter start at 1 for this macro.

  • x_: x_ obviously just inserts that text into the buffer.

  • <f3>: during a macro recording <f3> inserts the current value of the counter and increments it by one.

  • RET: add a newline.

  • C-5 <f4>: <f4> stops recording if you are recording and runs the most recent keyboard macro if you are not recording. Here we combine these functions: the C-5 means "do 5 <f4>s", so it will stop the recording and then execute the macro 4 more times ---I think of it as "5 executions, counting the one I just recorded".

1
  • What about a,b,c? or FE FF 100? Is there a counter for abc too? Commented Mar 14, 2023 at 21:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.