The simplest clipboard integration I can think of

Based on a tip given by @Screwtapello , I’ve been using this minimal clipboard integration for more than a year now:

hook global RegisterModified '"' %{
    nop %sh{
        printf "%s" "$kak_main_reg_dquote" | (eval wl-copy --foreground) > /dev/null 2>&1 &
    }
}

define-command read-clipboard %{
    set-register dquote %sh{
        wl-paste --no-newline
    }
}

# Brazilian keyboards have an extra `ç` key.
map global normal ç '\: read-clipboard<ret>'

That’s it! Setting clipboard contents once the " register changes is done automatically using the RegisterModified hook. On the other hand, whenver I want to read the contents of the clipboard on Kakoune, I just press the ç key on my keyboard.

Preserving an eventual newline at the end

For some reason I don’t really understand, the %sh{} expansion trims newlines at the end. I found that a bit annoying, so I defined read-clipboard using lua:

define-command read-clipboard %{
    lua %{
        local content = io.popen("wl-paste --no-newline"):read("a")
        kak.set_register("dquote", content)
    }
}

Integrating different clipboard managers

I don’t really use wl-clipboard, and perhaps neither you. So, for convenience, I’m showing here how to integrate other clipboard tools.

Klipper

If you, like me, use the Plasma Desktop, you can rely on Klipper for clipboard management (no need to install an extra tool like wl-clipboard or xsel):

hook global RegisterModified '"' %{
    nop %sh{
        # Be aware that on some systems, like Opensuse, `qdbus` is called `qdbus-qt5`.
        qdbus org.kde.klipper /klipper org.kde.klipper.klipper.setClipboardContents "$kak_main_reg_dquote"
    }
}

define-command read-clipboard %{
    set-register dquote %sh{
        qdbus org.kde.klipper /klipper org.kde.klipper.klipper.getClipboardContents
    }
}

Or, using lua to preserve the last newline:

define-command read-clipboard %{
    lua %{
        local clipboard = io.popen("qdbus org.kde.klipper /klipper org.kde.klipper.klipper.getClipboardContents"):read("a")
        -- The dbus interface of Klipper adds an extra newline at the end we are removing here.
        kak.set_register("dquote", clipboard:sub(1, -2))
    }
}

Since I prefer using Klipper, the above code is the one I’m really using.

xsel

hook global RegisterModified '"' %{
    nop %sh{
        printf "%s" "$kak_main_reg_dquote" | xsel --input --clipboard
    }
}

define-command read-clipboard %{
    set-register dquote %sh{
        xsel --output --clipboard
    }
}

Copyq

hook global RegisterModified '"' %{
    nop %sh{
        printf "%s" "$kak_main_reg_dquote" | copyq copy -
    }
}

define-command read-clipboard %{
    set-register dquote %sh{
        copyq clipboard
    }
}
3 Likes