How can I delete the current line in Emacs? - emacs

What is the emacs equivalent of vi's dd? I want to delete the current line. Tried CTRL + k but it only deletes from current position.

C-a # Go to beginning of line
C-k # Kill line from current point
There is also
C-S-backspace # Ctrl-Shift-Backspace
which invokes M-x kill-whole-line.
If you'd like to set a different global key binding, you'd put this in ~/.emacs:
(global-set-key "\C-cd" 'kill-whole-line) # Sets `C-c d` to `M-x kill-whole-line`
If you want to delete a number of whole lines, you can prefix the command with a number:
C-u 5 C-S-backspace # deletes 5 whole lines
M-5 C-S-backspace # deletes 5 whole lines
C-u C-S-backspace # delete 4 whole lines. C-u without a number defaults to 4
C-u -5 C-S-backspace # deletes previous 5 whole lines
M--5 C-S-backspace # deletes previous 5 whole lines
Sometimes I also find C-x z helpful:
C-S-backspace # delete 1 whole line
C-x z # repeat last command
z # repeat last command again.
# Press z as many times as you wish.
# Any other key acts normally, and ends the repeat command.

In case you don't want to kill the line (which would put it into the OS clipboard and kill ring) but simply delete it:
(defun delete-current-line ()
"Delete (not kill) the current line."
(interactive)
(save-excursion
(delete-region
(progn (forward-visible-line 0) (point))
(progn (forward-visible-line 1) (point)))))

Another method to delete the line without placing it into the kill ring:
(defun delete-current-line ()
"Deletes the current line"
(interactive)
(delete-region
(line-beginning-position)
(line-end-position)))
This will leave the point at the beginning of a blank line. To get rid of this also, you may wish to add something like (delete-blank-lines) to the end of the function, as in this example, which is perhaps a little less intuitive:
(defun delete-current-line ()
"Deletes the current line"
(interactive)
(forward-line 0)
(delete-char (- (line-end-position) (point)))
(delete-blank-lines))

Rather than having separate key to delete line, or having to invoke
prefix-argument. You can use crux-smart-kill-line
which will "kill to the end of the line and kill whole line on the next
call". But if you prefer delete instead of kill, you can use the
code below.
For point-to-string operation (kill/delete) I recommend to use zop-to-char
(defun aza-delete-line ()
"Delete from current position to end of line without pushing to `kill-ring'."
(interactive)
(delete-region (point) (line-end-position)))
(defun aza-delete-whole-line ()
"Delete whole line without pushing to kill-ring."
(interactive)
(delete-region (line-beginning-position) (line-end-position)))
(defun crux-smart-delete-line ()
"Kill to the end of the line and kill whole line on the next call."
(interactive)
(let ((orig-point (point)))
(move-end-of-line 1)
(if (= orig-point (point))
(aza-delete-whole-line)
(goto-char orig-point)
(aza-delete-line))))
source

The fastest/simplest way to delete (kill) a full line, from any point
on the line, without selecting anything, is:
C-w ; kill-region
It is versatile in deleting whatever is selected, or a line by default
if nothing is selected.
Given the question, you're probably also interested in replicating
Vim's "yank", yy (though in Emacs parlance a "yank" is confusingly
Vim's "put", p). This is:
M-w ; kill-ring-save
Nice and congruent, and pretty easy to remember. Even slightly
similar to Vim's i_CTRL-W.
Once you've put something in the kill ring with either of the above,
you'll likely want to "yank" (paste) it:
M-y ; yank-pop
(Note that C-S-backspace may not work in terminal Emacs.)

Install package whole-line-or-region and then run (whole-line-or-region-global-mode). This will make C-w kill the whole line if no region (selection) is active.
See the Package's GitHub page https://github.com/purcell/whole-line-or-region

Related

Is there an apply-command-to-each-line-in-region in emacs?

I have a bunch of links saved in an orgmode file, say...
http://www.stackoverflow.com
http://www.google.com
http://www.github.com
I can open each one by having the cursor on the link and doing C-c C-o, and it conveniently pops up my default browser and opens that link in a tab.
Now suppose I have like 20 of these links. Is there a convenient way to apply a function like this to each line within a selected region, without recording an explicit macro?
I'd imagine it looking something like...
Select region
M-x foreach-in-region
Keystrokes to apply to each line: C-c C-o
And this is just for functions already defined. I imagine the way without would be something like...
with cursor on first line of link
F3 # to start record macro
C-c C-o
down arrow
F4
Select region (omitting the first line, since that's now already opened in my browser)
C-x C-k r
Does this exist? If not, how would I lisp this?
You should record the macro for one line, then use apply-macro-to-region-lines to execute it for all lines in region. C-x C-k r
Alternatively, you can use multiple-cursors to create a cursor on each line and C-c C-o to open all. multiple-cursors will transform your usage patterns over time for the better if you give it a chance.
(defun do-lines (fun &optional start end)
"Invoke function FUN on the text of each line from START to END."
(interactive
(let ((fn (intern (completing-read "Function: " obarray 'functionp t))))
(if (use-region-p)
(list fn (region-beginning) (region-end))
(list fn (point-min) (point-max)))))
(save-excursion
(goto-char start)
(while (< (point) end)
(funcall fun (buffer-substring (line-beginning-position) (line-end-position)))
(forward-line 1))))
Update after your comment --
Now it sounds like you want to not enter a function name but hit a key, and have the command bound to that key be applied to each line in the region (or buffer).
Something like the following will do that. However, be aware that command often have particular behavior wrt lines. For example, if you were to hit key C-k (kill-lines) then it already moves forward after each line it kills. Because do-lines does not know what kind of function (command) you will invoke, it advances to the next line after each invocation. For a command such as kill-lines this will thus do the wrong thing: it will end up advancing two lines, not one, thus skipping lines. IOW, be aware that the code for do-lines cannot compensate for what a particular function it invokes might do that might not correspond to what you expect. Instead, it does what it says it does.
(defun do-lines (command &optional start end)
"Invoke COMMAND on the text of each line from START to END."
(interactive
(let* ((key (read-key-sequence-vector "Hit key sequence: "))
(cmd (lookup-key global-map key t)))
(when (numberp cmd) (error "Not a valid key sequence"))
(unless (commandp cmd) (error "Key `%s' is not defined" (key-description key)))
(if (use-region-p)
(list cmd (region-beginning) (region-end))
(list cmd (point-min) (point-max)))))
(setq start (copy-marker start)
end (copy-marker end))
(save-excursion
(goto-char start)
(while (< (point) end)
(funcall command (buffer-substring (line-beginning-position) (line-end-position)))
(forward-line 1))))
In some situations, you can use Emacs Repeating using C-x z following by more `z'. I was trying to comment all the lines in region and it worked nicely for my use case.
The command C-x z (repeat) provides another way to repeat an Emacs
command many times
To repeat the command more than once, type additional z’s: each z repeats the command one more time
In the spirit of TIMTOWTDI[1], I'll point out a technique that works well for some situations, including the one in the OP.
If you're looking to run an external command on a line of space-separated strings (like URLs):
Select the region
Invoke M-| (Alt+Shift+\, shell-command-on-region)
Use xargs as a prefix command to the desired command (e.g., xdg-open, or x-www-browser)
For example, the full command entered for step 3 might be:
xargs -n1 xdg-open
The -n1 switch causes xargs to open invoke the given program with one argument at a time; it will run the program once for each input. If the command can handle multiple arguments at once, you can omit -n1. For example, I have a web command that can open multiple URLs as arguments, so just xargs web works.
The major benefit of this approach is, it works on anything POSIX-compliant without doing anything in advance. Disadvantages include, it only works on external commands, and it requires xargs (not included with every OS by default).
[1] There's More Than One Way To Do It, originally from Perl, but useful elsewhere.

Delete from current position to the beginning of line in emacs?

Ctrlk would delete everything from the current position of the cursor to the end of line. Is there some equivalence to delete everything from the current position to the beginning of line?
For me Ctrl-0Ctrl-k does what you want. I think this is the default configuration, it's certainly not something I've modified.
If this doesn't work try Ctrl-u0Ctrl-k. Again, that seems to be Emacs' default behaviour on my installation (Emacs 24.x, Mac OS X).
If you prefer to have lesser keybinding (rather than having separate key to delete line, or having to invoke prefix-argument). You can use crux-smart-kill-line
which will "kill to the end of the line and kill whole line on the next
call". But if you prefer delete instead of kill, you can use the
code below.
For point-to-string operation (kill/delete) I recommend to use zop-to-char
(defun aza-delete-line ()
"Delete from current position to end of line without pushing to `kill-ring'."
(interactive)
(delete-region (point) (line-end-position)))
(defun aza-delete-whole-line ()
"Delete whole line without pushing to kill-ring."
(interactive)
(delete-region (line-beginning-position) (line-end-position)))
(defun crux-smart-delete-line ()
"Kill to the end of the line and kill whole line on the next call."
(interactive)
(let ((orig-point (point)))
(move-end-of-line 1)
(if (= orig-point (point))
(aza-delete-whole-line)
(goto-char orig-point)
(aza-delete-line))))
source
Emacs has steep learning curve. When a new user encounters this problem, she should record a macro of 2 keystrokes: Shift+Ctrl+a and Ctrl-w (cut), name it, save it, and set up a key binding so that the macro is available in the subsequent Emacs sessions.

Emacs indent/unindent current line

I've been using Emacs for a while, and I really miss a good old Geany shortcut - "C-i" and "C-u".
"C-i" indents the whole current line (keeping the mouse cursor where it is), and "C-u" unindents the whole current line.
I found many indenting commands for Emacs, some to indent a region. Basically, what I need is Vim's ">>" and "<<", but keeping the mouse cursor where it is.
My main doubt is, however, how I can indent only the current line.
Any ideas? Thank you in advance!
EDIT
Tab adds two spaces, I want to be on any position on the line and add two spaces on the beginning of the line, or remove two spaces from the beginning of the line.
That is the default behavior I have for my TAB key in emacs, which runs the command indent-for-tab-command. From one of the documentation pages:
In programming modes, adds or removes some combination of space and tab characters at the start of the line, in a way that makes sense given the text in the preceding lines. If the region is active and spans multiple lines, all those lines are indented this way. If point was initially within the current line's indentation, it is positioned after that indentation; otherwise, it remains at same point in the newly-indented text. See Program Indent.
Also worth noting is the tab-always-indent variable:
The variable tab-always-indent tweaks the behavior of the (indent-for-tab-command) command. The default value, t, gives the behavior described above. If you change the value to the symbol complete, then first tries to indent the current line, and if the line was already indented, it tries to complete the text at point (see Symbol Completion). If the value is nil, then indents the current line only if point is at the left margin or in the line's indentation; otherwise, it inserts a real tab character.
I have this in my init.el:
(defun rofrol/indent-region(numSpaces)
(progn
; default to start and end of current line
(setq regionStart (line-beginning-position))
(setq regionEnd (line-end-position))
; if there's a selection, use that instead of the current line
(when (use-region-p)
(setq regionStart (region-beginning))
(setq regionEnd (region-end))
)
(save-excursion ; restore the position afterwards
(goto-char regionStart) ; go to the start of region
(setq start (line-beginning-position)) ; save the start of the line
(goto-char regionEnd) ; go to the end of region
(setq end (line-end-position)) ; save the end of the line
(indent-rigidly start end numSpaces) ; indent between start and end
(setq deactivate-mark nil) ; restore the selected region
)
)
)
(defun rofrol/indent-lines(&optional N)
(interactive "p")
(indent-rigidly (line-beginning-position)
(line-end-position)
(* (or N 1) tab-width)))
(defun rofrol/untab-region (&optional N)
(interactive "p")
(rofrol/indent-region (* (* (or N 1) tab-width)-1)))
(defun rofrol/tab-region (N)
(interactive "p")
(if (use-region-p)
(rofrol/indent-region (* (or N 1) tab-width)) ; region was selected, call indent-region
(rofrol/indent-lines N); else insert spaces as expected
))
(global-set-key (kbd "C->") 'rofrol/tab-region)
(global-set-key (kbd "C-<") 'rofrol/untab-region)
Emacs Shift-Tab to left shift the block
How to bind keys to indent/unindent region in emacs?

Get Emacs to join lines when killing lines

When I hit C-k, Emacs kills to end-of-line. When I hit C-k again, it "kills the newline" and brings the next line up. However, the next line's indentation remains intact, and you can end up with a line that has lots of spaces in the middle.
So, from this:
previous line material
next line material
to this:
previous line material next line material
I understand I can use M-^ to join lines properly, but that requires the cursor to be on the next line. How do I modify C-k so that when it kills the newline, also kills the next line's indentation?
For C-k I don't know, but you could use the just-one-space function to transform any number of space into juste one space (it's bound on M-space)
If you give M-^ an argument (for example C-u M-^), it will join the next line to the current line.
Here's a way to plug in the behavior (I think) you want into kill-line: when killing a newline, also kill the indentation that follows. Note that this may result in no space being present after the cursor, which is why I think I'd go with M-1 M-^ or C-k M-SPC instead.
(defadvice kill-line (around kill-indentation
activate compile)
"When killing a line break, also kill any subsequent indentation."
(let ((f-v-l (symbol-function 'forward-visible-line)))
(flet ((forward-visible-line (arg)
(funcall f-v-l arg)
(skip-chars-forward " \t")))
ad-do-it)))
I have this in my .emacs:
(defun pull-line ()
"Pull the next line that contains anything up to the end of this one"
(interactive)
(save-excursion
(end-of-line)
(while (looking-at "[ \n\r\t]")
(delete-char 1))
(if (looking-back "^[[:blank:]]*[[:punct:][:alnum:]].*")
(fixup-whitespace)
(indent-according-to-mode))))
(global-set-key "\C-cp" 'pull-line)
It pulls the next non-blank line up to the this one, and if there is anything on this line it makes calls (fixup-whitespace) which does the right thing about 95% of the time, otherwise it indents it to what emacs thinks is the right level. I think I copied the concept from vim?
I use it all the time, anyway.
I just realized I also have this in my .emacs, it is more exactly what you want, although I forget that I have it since I use pull-line much more often. I think I stole this from emacswiki:
(defun kill-and-join-forward (&optional arg)
"If at end of line, join with following; otherwise kill line.
Deletes whitespace at join."
(interactive "P")
(if (and (eolp) (not (bolp)))
(progn
(delete-indentation t)
(if (looking-at " $")
(delete-char 1)))
(kill-line arg)))
(global-set-key "\C-k" 'kill-and-join-forward)
This will do it:
(defun my-kill-line (&optional arg)
(interactive "P")
(if arg
(kill-line arg)
(when (prog1 (eolp) (kill-line))
(just-one-space 1))))

Emacs Command to Delete Up to Non-Whitespace Character

I often want to make a multiline function call and reduce it down to one line. For example, convert...
function_call(
'first_arg',
'second')
to
function_call('first_arg', 'second')
Does emacs have some commands to help with this. Specifically, is there a command that will delete all whitespace from the point to the first non-whitespace character?
You might try delete-indentation, my favorite command for joining multiple lines into one line. In your example, put the cursor on the line with "second" and hit M-^ twice. Here are the docs:
M-^ runs the command delete-indentation, which is an interactive compiled Lisp function in simple.el.
It is bound to M-^.
(delete-indentation &optional arg)
Join this line to previous and fix up whitespace at join. If there is a fill prefix, delete it from the beginning of this line. With argument, join this line to following line.
Take a look at the fixup-whitespace function. It comes with Emacs, in simple.el. Its docs are:
Fixup white space between objects around point.
Leave one space or none, according to the context.
A similar function, just-one-space, that
Deletes all spaces and tabs around point, leaving one space
is typically bound to M-SPC.
Specifically, is there a command that will delete all whitespace from the point to the first non-whitespace character?
There's a command that does almost that:
M-\ runs the command delete-horizontal-space
which is an interactive compiled Lisp function in `simple.el'.
It is bound to M-\.
(delete-horizontal-space &optional backward-only)
Delete all spaces and tabs around point.
If backward-only is non-nil, only delete them before point.
You can always use M-z to delete upto a character.
For eg in your case:
M-z ' to delete upto the single quote (unfortunately this will delete the single quote as well, but that is a minor inconvenience).
I use the following macro to "pull" the next line onto the end of the current line, compressing whitespace.
(defun pull-next-line()
(interactive)
(move-end-of-line 1)
(kill-line)
(just-one-space))
This is exactly the opposite of #jrockway's move-line-up and of delete-indentation, which I find more natural. The just-one-space command in the macro is exactly #Mike's M-SPACE.
I bind pull-next-line to M-J (in analogy with Vim's J, for "join", command) using the following in my .emacs.
(global-set-key (kbd "M-J") 'pull-next-line)
Example. Calling pull-next-line on the first line of
function_call(
'first_arg',
'second')
yields
function_call( 'first_arg',
'second')
Calling it a second time yields
function_call( 'first_arg', 'second')
Alt-space will reduce a string of whitespace to a single space character, but it won't delete the newline. Still, that should help a little.
To delete everything from point to the first non-whitespace (or newline), type a non-whitespace char, Alt-space, backspace (to remove final whitespace char), then backspace (to delete the char you added.
To turn the multi-line function declaration into a single-line declaration, use a combination of Alt-space, backspace, and Alt-E (goto-endofline) commands.
A rather drastic way of doing this is Hungry-Delete mode:
Hungry-Delete is a minor-mode that causes deletion to delete all whitespace in the direction you are deleting.
A slightly different approach would be creating a keyboard macro to do the job for you.
so, for creating the macro stage a general scenario like so:
foo
bar
[a line with "foo" then a couple of lines later and with some white spaces, write "bar"]
then standing anywhere between foo and bar, do the following:
C-x ( ; start recording macro
M-b ; move backwards to the beginning of foo
END ; move to the end of foo
C-space ; place mark
C-M-f ; move to the end of bar
HOME ; move to the beginning of the line
C-w ; yank out all the white space
M-SPACE ; leave only one space
C-x ) ; end recording the macro
M-x name-last-kbd-macro ; name it, call it jline or something
Now you can always remove all whitespace between two words with M-x one-line
Make sure you remember to save your keyboard macro by issuing M-x insert-kbd-macro somewhere in your .emacs file - this is how it looks:
(fset 'jline
[?\M-b end ?\C- ?\C-\M-f home ?\C-w escape ? ])
I do this:
(defun move-line-up ()
"Removes leading spaces from the current line, and then moves
the current line to the end of the previous line."
(interactive)
(let (start end)
(save-excursion
(beginning-of-line)
; get first non-space character, only look on this line
(let ((search-end (save-excursion (end-of-line) (point))))
(re-search-forward "[^[:space:]]" search-end))
(setq end (1- (point)))
(previous-line)
(end-of-line)
(setq start (point))
(delete-region start end))
(goto-char start)))
(defun move-next-line-up ()
"Moves the next line to the end of the current line"
(interactive)
(next-line)
(move-line-up))
And bind these as:
(global-set-key (kbd "C-x ,") 'move-line-up)
(global-set-key (kbd "C-x .") 'move-next-line-up)
So to solve your problem, on the line that says "second)", just run C-x , C-x ,
If you want all of your deletes to act that way, you might check out greedy-delete.