30

In my daily life I'm always typing <kbd>Keyboard Character</kbd> and I'd like to set up a macro in Ubuntu to automatically enter <kbd> </kbd>.

I'd like to assign it to say Shift+Control+K or whatever keyboard control character combination isn't assigned and already used by Ubuntu.

Back in the day of TSR (Terminate and Stay Resident) MS-DOS programs this was possible. Certainly it must be in Ubuntu too?

Do I have to write a daemon to accomplish this?


I found other questions with no answers: How can I assign macros to my keyboard keys on Ubuntu, similar to Razer Keyboard Macros in Windows?, what is a good mouse/keyboard macro recorder?

I found a similar question with an answer: Can I use Keyboard Shortcuts to implement text macros?. However that question stipulated the answer could not be AutoKey.

wjandrea
  • 14,236
  • 4
  • 48
  • 98

5 Answers5

24

I did some googling and found a program called AutoKey (Autokey - Linux utility for text substitution hotkeys) near the top of the list.

Rather than a hotkey using Ctrl+Shift+K I chose to assign the abbreviation kz which is automatically expanded into <kbd></kbd>+.

It is simply installed using:

sudo apt install autokey-gtk

It installs in Launcher and the screen is pretty simple to use:

Autokey

wjandrea
  • 14,236
  • 4
  • 48
  • 98
20

What also can be done is to use xdotool withtype flag, like so:

bash -c ' sleep 0.5; xdotool getactivewindow  type "<kbd></kbd>"'

Go to System Settings-> Keyboard-> Shortcuts -> Custom and bind that command to whatever keyboard shortcut you want. I chose CtrlSuperK. What happens here is that we give user delay of 0.5 seconds to release keyboard shortcut, and then xdotool will type out the key markup tags just as if you were doing it yourself on keyboard. Very easy and simple approach. In fact I am used it just now to put in those 3 keys above.

Note that xdotool doesn't come with Ubuntu by default, so you will have to install it via sudo apt-get install xdotool

Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497
  • Can you also make the insertion pointer go back so that it will be between <kbd> and </kbd>? – DK Bose Jan 01 '17 at 15:55
  • 6
    I'm using bash -c 'sleep 0.5; xdotool getactivewindow type "[CODE][/CODE]" && sleep 0.5 && xdotool key Left Left Left Left Left Left Left' to get the text cursor between the code tags. – DK Bose Jan 01 '17 at 16:29
1

If you have a compose file you can use it as a poor-man’s text insertion utility.

You can use a few of the modifiers in X. Apparently you can use Shift as a modifier:

! Ctrl Shift <k> : "<kbd></kbd>"

But this does not work, at least on my machine.

Nor does this work (omitted Shift, capitalized K):

! Ctrl <K> : "<kbd></kbd>"

However, you can use Ctrl and Ctrl+Alt:

! Ctrl Alt <k> : "<kbd></kbd>"
! Ctrl <k> : "<kbd></kbd>"

Placing the cursor correctly

The above mappings will place the cursor after the string (| indicates the cursor):

<kbd></kbd>|

I reckon there can be no general-purpose solution for putting the cursor inside of the tag; for that you would need to use a fit-for-purpose tool. But you can the cursor go inside the tag in certain applications.

I use gnome-terminal with Bash which uses readline keybindings (Emacs-like). Ctrl-b is the keybinding for going backwards one character. In my terminal I can type Ctrl+v b and get the control character ^B (U+0002 (Start of Text)). So type six of these characters at the end of the string:

! Ctrl Alt <k> : "<kbd></kbd>^B^B^B^B^B^B"

The cursor will be placed inside the tag if you are inside an application that interprets ^B correctly (e.g. terminals and Emacs):

<kbd>|</kbd>

Using the compose key

You can of course use the compose key (<Multi_key>) to achieve the same thing. For example, use t (“tag”) and k (“keyboard”):

<Multi_key> <t> <k> : "<kbd></kbd>^B^B^B^B^B^B"
1

An update for 2023 and Wayland

ydotool is a command line keyboard automation that works both on Xorg and on Wayland. As opposed to a full-fledged keyboard macro program such as Autokey, there is graphical user interface to create and manage keyboard macros, nor is there a facility to record keystrokes (neither Autokey has that). Moreover, currently, the syntax to program key presses is rather awkward, where codes need to be supplied instead of easily recognizable key names.

For example, to implement autotyping <kbd></kbd> and place the cursor in between the codes, following command can be bound to a shortcut key:

sh -c 'sleep 0.4 && ydotool type "<kbd></kbd>" && ydotool key 105:1 105:0 105:1 105:0  105:1 105:0  105:1 105:0  105:1 105:0  105:1 105:0'

Hitting the shortcut key will type <kbd></kbd> then arrow-left 6 times to place the cursor in between the codes.

ydotool can be installed through the Ubuntu software center. On Ubuntu 23.10, install it with sudo apt install ydotool. Ubuntu 22.04 ships a not working, outdated version of ydotool. Fortunatelly, it is rather easy to compile and configure ydotool yourself.

Explanation

  • sh -c calls a shell to execute the command. Shortcut daemons may support only a single command. This construct allows to chain multiple commands. Another possibility involves calling a script that contains the commands.

  • sleep 0.4 delays the typing: this allows you to release the keyboard before simulated typing starts. Otherwise, you still holding e.g. a modifier key would interfere with the simulated typing.

  • Two ydotool commands follow. The following command types the string, whereas a second ydotool command is needed to simulate hitting the Left key six times.

  • Commands are separated using && rather than ;, meaning that the next command will be executed only if the previous one was successful.

  • The easiest way to see the keyboard codes you must use is to load sudo showkey. 105 is the code for Right, :1 means pressing, :0 means releasing the key.

vanadium
  • 88,010
1

Solution 1: input-remapper-gtk

Here is a modern graphical busy-wait-free solution that works on both X11 and Wayland:

  1. sudo apt install input-remapper
  2. Open input-remapper-gtk
  3. Enter your password
  4. Select your keyboard

input-remapper-gtk devices

  1. Click "new preset"

input-remapper-gtk presets

  1. Click "+ Add"

input-remapper-gtk editor add

  1. Click " Record"

input-remapper-gtk editor record

  1. Press Ctrl+Shift+k or what you would like to bind

input-remapper-gtk editor recording

  1. Select "Key or Macro"

input-remapper-gtk editor output

  1. Enter modify(Shift_L,key(comma)).key(k).key(b).key(d).modify(Shift_L,key(period)).modify(Shift_L,key(comma)).key(slash).key(k).key(b).key(d).modify(Shift_L,key(period)).modify(Control_L,key(KEY_LEFT)).repeat(2,key(KEY_LEFT)) . See more examples

  2. Click "▶️ Apply"

input-remapper-gtk editor done

Solution 2: Userscript

If you're only using this for websites like AskUbuntu, it's better to use a userscript so that the rest of your system is not affected.

  1. Install the Greasemonkey/Tampermonkey/Violentmonkey extension

  2. Create a new userscript with the following contents:

    // ==UserScript==
    // @name         AskUbuntu <kbd>
    // @namespace    http://tampermonkey.net/
    // @version      2024-02-18
    // @description  try to take over the world!
    // @author       You
    // @match        https://askubuntu.com/*
    // @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
    // @grant        none
    // ==/UserScript==
    

    (function() { 'use strict'; document.addEventListener('keydown', (e) => { const { activeElement } = document; if (!(activeElement instanceof HTMLTextAreaElement) || !e.altKey || e.key !== "k") return; e.preventDefault(); document.execCommand("insertText", false, "<kbd></kbd>"); activeElement.selectionEnd = activeElement.selectionStart -= 6; }) })();

  3. Save

  4. Refresh all AskUbuntu tabs

Daniel T
  • 4,594