In evil-mode how to just press J to move the cursor down 3 lines - emacs

When in evil-mode, I can make the cursor go down 3 lines by command 'C-u 3 M-x evil-next-line' , but how can I make the cursor go down 3 lines by just pressing J?

1. Short answer
Add this to your .emacs file:
(evil-define-motion evil-next-line-3 (count)
"Move the cursor 3 * COUNT lines down."
:type line
(let (line-move-visual)
(evil-line-move (* 3 (or count 1)))))
Note that J is currently bound to evil-join.
If you are ok to rebind it, just add:
(define-key evil-normal-state-map "J" 'evil-next-line-3)
Now, to join lines, you may either type M-x evil-join RET or bind something else to evil-join (see below).
Note that, if you type 2J, you'll move twice 3 lines down, which is more or less 6 lines down... and C-u J will move 4*3 = 12 lines down.
2. Not so short answer (what I actually did)
I never used evil-mode... so I tried to add this package and enabled the evil-mode (which is ok for me since I know the main vi commands and I know how to disable it with C-- M-x evil-mode RET).
When evil-mode is enabled and I type C-h k J, the Help buffer says:
J runs the command evil-join (found in evil-normal-state-map),
which is an interactive compiled Lisp function in ‘evil-commands.el’.
It is bound to J.
(evil-join BEG END)
Join the selected lines.
Then I typed C-h k j, clicked the evil-commands.el link from the Help buffer and copied and adapted the definition of the evil-next-line function to the evil-next-line-3 function and bound it to J.
In case you want to go back to the previous binding of J (or want to bind it to something else), you can evaluate something like:
(define-key evil-normal-state-map "J" 'evil-join)

Related

Defining step size of Emacs Macro Counter

I love the Emacs keyboard-macro functionality and I am using it a lot.
Sometimes, I don't want to just statically enter certain keyboard macros, but there should be a value there that will get changed in between. There is the feature of Emacs Macro counters (Macro counters in Emacs Manual).
The problem is that this counter always just counts up by one. Is there a way to specify the stepping size (i.e. move forward by 4 in each step)?
Thanks in advance for your help!
You can use kmacro-add-counter, bound to C-x C-k C-a.
For example to add 3 to the counter, use M-3 C-x C-k C-a.
Small full example: <f3> <f3> RET M-3 C-x C-k C-a <f4> <f4> <f4> <f4> will produce:
0
4
8
12
Alternative to kmacro
Sometimes, you can use tiny to do
what kmacro does in fewer keystrokes and with better undo context.
The above example can generated by entering:
m\n3*x4
and pressing the shortcut for tiny-expand. I bind it like this:
(global-set-key (kbd "C-;") 'tiny-expand)
Here, m\n3 basically means 4 repetitions (index starts from 0) joined by the newline character (\n). And *x4 is a shorthand for Elisp (* x 4).

emacs multi-keystroke binding [duplicate]

This question already has answers here:
How to write a key bindings in emacs for easy repeat?
(5 answers)
Closed 8 years ago.
I'm still very new to EMACS, but are getting familiar when i'm going through the emacs and elisp manual. But right now i'm stuck on this:
Is there a simple way to bind input sequences in regexp style?
eg: the default binding for function enlarge-window-horizontally is "C-x {", is it possible to rebind it to something like "C-x ({)+" so that enlarge-window-horizontally can be called repeatedly by repeating "{" character, instead of release Ctrl key multiple times?
There is another way to archive what you desire:
The first time you want to repeat the last command, press C-x z, afterwards you may repeat your command as often as desired by just pressing z.
The advantage of this approach is that it works with every command you use and not just for a specific one.
For additional reference here is the output of C-h f
8.11 Repeating a Command
Many simple commands, such as those invoked with a single key or with
M-x COMMAND-NAME , can be repeated by invoking them with a
numeric argument that serves as a repeat count (*note Arguments::).
However, if the command you want to repeat prompts for input, or uses
a numeric argument in another way, that method won't work.
The command C-x z (`repeat') provides another way to repeat an
Emacs command many times. This command repeats the previous Emacs
command, whatever that was. Repeating a command uses the same
arguments that were used before; it does not read new arguments each
time.
To repeat the command more than once, type additional z's: each
z repeats the command one more time. Repetition ends when you type
a character other than z, or press a mouse button.
For example, suppose you type C-u 2 0 C-d to delete 20
characters. You can repeat that command (including its argument) three
additional times, to delete a total of 80 characters, by typing C-x z
z z. The first C-x z repeats the command once, and each subsequent
z repeats it once again.
The "Emacs way" is to use C-u as a prefix key. E.g. C-u20C-x{.
Having said that, it's possible to do what you ask for. However, it would require you to bind C-x { and { separately. The former would be defined like it is today, but the latter would have to look something like:
(defun my-open-brace ()
(interactive)
(if (eq last-command 'shrink-window-horizontally)
(progn
(setq this-command 'shrink-window-horizontally)
(call-interactively 'shrink-window-horizontally))
(call-interactively 'self-insert-command)))
Unfortunately, if you have many sequences ending in {, you would have to write one function to handle them all.
You can also define your own repeatable command and bind it to C-x {. You can then use it exactly as you requested: C-x { { { {..., instead of having to use C-x { C-x z z z z...
Here is what you do:
(defun your-repeat-command (command)
"Repeat COMMAND."
(let ((repeat-message-function 'ignore))
(setq last-repeatable-command command)
(repeat nil)))
(defun your-shrink-window-horizontally ()
"Shrink window horizontally.
You can repeat this by hitting the last key again..."
(interactive)
(require 'repeat nil t)
(my-repeat-command 'shrink-window-horizontally))
(define-key ctl-x-map "{" 'your-shrink-window-horizontally)
You can do this with any command you like --- use my-repeat-command to make a repeatable version of it. I do this all the time, in several of my libraries.
Write a multi repeat command for emacs by using minor mode. I name it smart-repeat-mode
https://github.com/zhsfei/emacs-ext

How to attach character to the next N lines using Emacs?

Using emacs24 I'd like to attach for example # at the beginning of the next five lines.
So having this:
Line1
line2
line3
get this:
#Line1
#line2
#line3
for the number of lines that I specify. How can I do that? Thanks!
While there may be something built in to Emacs that does this, and you can certainly write a little Lisp to get it done, I would usually use "rectangular editing" features to get this done. Imagine that the buffer contains the following, with . representing the point (where your cursor is)
.Line1
line2
line3
Set the mark
Press C-n twice. This is the state of the buffer now:
Line1
line2
.line3
Press C-x r t.
Type #.
Press enter.
I would find this much more natural than entering a value for the number of times to repeat a command, because you can visually select the lines you want to edit. YMMV
Edit
Here's how to do this using a bit of Emacs Lisp. Note that although I've been using Emacs for a few years now, I only recently began learning how to actually use Emacs Lisp, so this code might not be that great! It does get the job done.
(defun insert-n-times (s n)
(interactive "Mstring:\nNtimes:")
(while (> n 0)
(insert s)
(goto-char (- (point) 1))
(next-line)
(setq n (- n 1))))
Use it by doing the following: M-x insert-n-times RET <type a string> RET <type a number>
Another method is using macro to get such repetitive work done. Here is a page that describes how to use macros in Emacs. You can have a look at it if you are not familiar with it.
In your case, the following keys would work:
Move the cursor to the beginning of Line1
C-x (
Type a '#'
C-n, then C-a
C-x )
Move the cursor to the line to the beginning of which you want to add '#'
C-u 10 C-x e
Basically, step 2-5 will record a macro which will add a # at the beginning, and then move to the beginning of the next line. Step 6-7 will execute the macro 10 times (of course, you can change it to arbitrary number). I guess this will be quite a lot of keystrokes and newbies may not like it. Maybe others have better solutions.
Line1
line2
line3
I wrote the following code:
You first give a digit argument (the amount of times you want to do this), e.g. M-3 (hold alt, hit 3), to do the following 3 times
Either use a key for it, like a suggestion below (f8), or use M-x prompt-for-insert
It will ask you for a string to enter. e.g. "foo" and hit return button.
It will then do as you ask.
(defun prompt-for-insert (val)
(interactive "P")
(let ((astring (read-string "What do you want to insert?"))
(value val))
(while (> value 0)
(insert astring)
(move-beginning-of-line 2)
(decf value)))
)
(global-set-key [f8] 'prompt-for-insert)
The whole sequence will then be:
M-3 [f8] foo RET
Resulting in:
fooLine1
fooline2
fooline3
Why not just query-replace-regexp or replace-regexp? E.g. select the region and do C-M-%^RET#RET!
Try M-x string-insert-rectangle. This command inserts a string on every line of the rectangle.
While comment-region is good in this specific example, check out the multiple-cursors package for a very powerful way to do this kind of thing in general.
You can just hit C-> repeatedly until you have a cursor at the beginning of each line, then hit # and you're done (C-g to get rid of the extra cursors.)
It's a much more interactive form of C-x r t and works with non-rectangular regions too (after a C-s for example.)

Changing window faster in Emacs (or repeating last shortcut with a single strike)

if I want to change windows in emacs I do C-x o and that's fine with me...but when I want to change window lots of times in a row C-x o is not so convenient...is there a way to change window with just one strike after first C-x o ?
and in general...is there a (single) strike that would repeat my last shortcut?
I use C-tab to switch windows:
(global-set-key [C-tab] 'other-window)
Holding down the Control key, you can jump windows repeatedly just by hitting the tab key.
EDIT: my original answer contained the following
I don't think there's a built-in way to repeat last command for basic commands like this ...
This is no longer true. Emacs now contains repeat.el, which allows for exactly the behaviour rabidmachine9 asked for.
The following code will create a repeating other-window, such that after pressing C-x o the first time, pressing o afterwards will continue moving to the next window.
(require 'repeat)
(defun make-repeatable-command (cmd)
"Returns a new command that is a repeatable version of CMD.
The new command is named CMD-repeat. CMD should be a quoted
command.
This allows you to bind the command to a compound keystroke and
repeat it with just the final key. For example:
(global-set-key (kbd \"C-c a\") (make-repeatable-command 'foo))
will create a new command called foo-repeat. Typing C-c a will
just invoke foo. Typing C-c a a a will invoke foo three times,
and so on.
See related discussion here:
http://batsov.com/articles/2012/03/08/emacs-tip-number-4-repeat-last-command/#comment-459843643
https://groups.google.com/forum/?hl=en&fromgroups=#!topic/gnu.emacs.help/RHKP2gjx7I8"
(fset (intern (concat (symbol-name cmd) "-repeat"))
`(lambda ,(help-function-arglist cmd) ;; arg list
,(format "A repeatable version of `%s'." (symbol-name cmd)) ;; doc string
,(interactive-form cmd) ;; interactive form
;; see also repeat-message-function
(setq last-repeatable-command ',cmd)
(repeat nil)))
(intern (concat (symbol-name cmd) "-repeat")))
(global-set-key (kbd "C-x o") (make-repeatable-command 'other-window))
The function make-repeatable-command than then be used to create other repeating commands, using the same template.
Check out windmove; it lets you just hold down a modifier key and press an arrow key to move to the window in that direction. I've been using it for years with the default modifier (shift) and strangely enough it doesn't interfere with my impulses to use shift-arrow text selection in other applications.
There's also an equivalent for frames, which I should really try...
You have, say, 10 windows in the frame, and you are doing M-x other-window a lots of times in a row, I take it you mean to jump from, say window #2 to window #8 and then on to window #1 and so on. By doing lots of other-window in a row, I would imagine you do nothing of importance until you reach the desired window.
See if universal-argument bound to C-u helps. In the 10 window frame, if you are in window #3 and want to go to window #9, you are hopping to the 6th next window. So you would do C-u 6 C-x o. Or, you could as well do C-u -4 C-x o and reach window #9 from window #3.
Bit late to the party, but there is also window-numbering (known as 'window-number' in MELPA).
This includes a window number in the modeline -1-, -2- etc, and provides M-1, M-2 etc key bindings to directly select them. Very quick.

How do I bind a key to "the function represented by the following key sequence"?

I'm just starting to learn emacs (woohoo!) and I've been mucking around in my .emacs quite happily. Unfortunately, I don't know Lisp yet, so I'm having issues with the basics.
I've already remapped a few keys until I fix my muscle memory:
(global-set-key (kbd "<f9>") 'recompile)
That's fine. But how can I tell a key to 'simulate pressing several keys'? For instance, I don't know, make <f1> do the same as C-u 2 C-x } (widen buffer by two chars).
One way is to look up that C-x } calls shrink-window-horizontally, and do some sort of lambda thing. This is of course the neat and elegant way (how do you do this?). But surely there's a way to define <f1> to send the keystrokes C-u 2 C-x }?
Sure there is, and it's the obvious way:
(global-set-key (kbd "<f1>") (kbd "C-u 2 C-x }"))
For anything long-term, I would recommend the approach shown by seh, as that will naturally be more robust in most situations. It requires a little more work and know-how, of course, but it's all worthwhile :)
angus' approach is like a cut-down version of the keyboard macros feature that gives Emacs its name (and slightly simpler to use than macros for the example in question). You should definitely be aware of macros, however -- they can be exceedingly useful, and for anything more complicated it quickly becomes far easier to record one dynamically than to write out all the individual keys manually.
Here's the summary I wrote myself of the most important bits:
;;;; * Keyboard macros
;; C-x ( or F3 Begin recording.
;; F3 Insert counter (if recording has already commenced).
;; C-u <n> C-x ( or F3 Begin recording with an initial counter value <n>.
;; C-x ) or F4 End recording.
;; C-u <n> C-x ) or F4 End recording, then execute the macro <n>-1 times.
;; C-x e or F4 Execute the last recorded keyboard macro.
;; e or F4 Additional e or F4 presses repeat the macro.
;; C-u <n> C-x e or F4 Execute the last recorded keyboard macro <n> times.
;; C-x C-k r Apply the last macro to each line of the region.
;; C-x C-k e Edit a keyboard macro (RET for most recent).
;; C-x C-k b Set a key-binding.
;;
;; If you find yourself using lots of macros, you can even name them
;; for later use, and save them to your init file.
;; M-x name-last-kbd-macro RET (name) RET
;; M-x insert-kbd-macro RET (name) RET
;;
;; For more documentation:
;; C-h k C-x (
;; M-: (info "(emacs) Keyboard Macros") RET
If we play with the example from the question, you'll see how some of these things tie together...
To begin with, you can define the macro with F3C-u2C-x}F4
You could then bind it temporarily to F1 with C-xC-kbF1 (actually that's not true if F1 is currently a prefix key for an existing keymap, as typing it interactively will simply prompt for the remainder. You can circumvent this in code with (global-set-key (kbd "<f1>") ...), but I would suggest sticking to the reserved bindings).
If you then use describe-key (C-hk) to examine what is bound to that key, Emacs will show you a (lambda) expression which you could copy to your init file if you so wished.
Alternatively, you could name the macro and ask Emacs to insert the code into the current buffer:
M-x name-last-kbd-macro RET (name) RET
M-x insert-kbd-macro RETRET
This code will look different to the lambda expression shown by describe-key, but if you evaluate the inserted macro, you'll see the equivalence. You can likewise show that the (kbd "...") expression also evaluates to the same value, and therefore these are all just alternative ways of doing the same thing.
(You can use the *scratch* buffer to evaluate the code by moving point after the end of the expression, and either typing C-xC-e to show the value in the minibuffer, or C-j to insert the value into the buffer).
Note that the 'inserted' code uses fset to assign the macro to a symbol. You could bind the macro to a key either by executing the (fset) and then assigning that symbol to a key with (global-set-key), or you could ignore the (fset) and simply assign the macro value directly. This, of course, is directly equivalent to angus' answer.
Edit: I've just noticed that there's a kmacro-name-last-macro function bound to C-xC-kn which is nearly identical in form to name-last-kbd-macro, but which generates the lambda expression form seen when using kmacro-bind-to-key (C-xC-kb) and describe-key.
I'll use shrink-window-horizontally as the example function, but you can generalize the idea to any bindings you'd like to define.
If you want to use two as the default amount to shrink the window, rather than one, try the following:
(global-set-key [f9]
(lambda (&optional n)
(interactive "P")
(shrink-window-horizontally (or n 2))))
That binds the F9 key to an interactive function accepting a prefix argument. If you just press F9, you'll pass no argument, which summons the default value of 2, as the parameter n will receive nil as an argument. However, if you press, say, C-u 10 F9, you'll pass ten as the argument for n. This allows you to use your binding more flexibly.
general-simulate-key from general.el works better (in my case a sequence with popups and changing keymaps that I couldn't get to work with macros): https://github.com/noctuid/general.el#simulating-keypresses