Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete the current line using AutoHotkey?

Tags:

autohotkey

Using an AutoHotkey script I'd like to set the keyboard command Ctrl+D to delete the current line in any active Windows app.

How?

like image 774
GollyJer Avatar asked Oct 19 '25 14:10

GollyJer


2 Answers

^d::Send {Home}{ShiftDown}{End}{Right}{ShiftUp}{Del}

Might not work in all edge cases, but passes some very basic testing in Notepad. =~)

like image 165
HaveSpacesuit Avatar answered Oct 22 '25 05:10

HaveSpacesuit


HaveSpacesuit's answer works but after using it for a while I realized it deletes the active line and sometimes re-positions the spacing of the line below.

This led me to rethink his solution. Instead of going from the front of the line to the back, I tried going from back to front. This solved the re-positioning issue.

SendInput {End}
SendInput +{Home}
SendInput ^+{Left}
SendInput {Delete}

There is still a small problem though. If the cursor is on an empty line, with more empty lines above, then all empty lines get deleted.

I don't know a key combo to replace ^+{Left} that doesn't have this behavior so I had to write a more comprehensive solution.

^d:: DeleteCurrentLine()

DeleteCurrentLine() {
   SendInput {End}
   SendInput +{Home}
   If get_SelectedText() = "" {
      ; On an empty line.
      SendInput {Delete}
   } Else {
      SendInput ^+{Left}
      SendInput {Delete}
   }
}

get_SelectedText() {

    ; See if selection can be captured without using the clipboard.
    WinActive("A")
    ControlGetFocus ctrl
    ControlGet selectedText, Selected,, %ctrl%

    ;If not, use the clipboard as a fallback.
    If (selectedText = "") {
        originalClipboard := ClipboardAll ; Store current clipboard.
        Clipboard := ""
        SendInput ^c
        ClipWait .2
        selectedText := ClipBoard
        ClipBoard := originalClipboard
    }

    Return selectedText
}

As far as I can tell this produces no unexpected behaviour.

However, be careful if you're using a clipboard manager as this script uses the clipboard, if necessary, as an intermediary to get the selected text. This will impact clipboard manager history.

like image 38
GollyJer Avatar answered Oct 22 '25 05:10

GollyJer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!