如何从终端设置自定义键盘快捷键?


56

如何从终端为不同的Linux版本设置自定义键盘快捷键?

基本上,我想知道Linux在哪里存储键盘快捷方式文件以及如何对其进行编辑。

在我的研究中,我找到了一个文件,~/.config/compiz-1/compizconfig但是当我尝试使用打开文件时,该文件或多或少被加密了nano


注意,XFCE / Xubuntu系统已经在这里
Ulad Kasach '16

Answers:


62

从命令行分两步添加快捷键绑定(14.04+)

可以从命令行添加自定义快捷方式,但是有点复杂。每个键绑定需要完成几个步骤。在另一方面,它非常简单,可以很好地照本宣科,如果你以某种方式要在命令行(这是这个问题,对不对?)做到这一点。

就像您的界面(“系统设置”>“键盘”>“快捷方式”>“自定义快捷方式”)一样,自定义键盘快捷方式是从命令行中分两个步骤进行的:

  1. 通过编辑(添加到)命令返回的列表来创建键绑定:

    gsettings get org.gnome.settings-daemon.plugins.media-keys custom-keybindings
    

    返回的列表看起来像(如果当前只是一个快捷方式):

    ['/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/']
    

    通过以下命令应用编辑后的列表:

    gsettings set org.gnome.settings-daemon.plugins.media-keys custom-keybindings "[<altered_list>]"
    

    (注意双引号)

    NB无需说,在列表中提及(例如custom1custom2)应该是唯一的一个。如果编写脚本,脚本应防止重复。在这种情况下,编辑后的列表应如下所示:

    ['/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom1/']
    

    添加一个键绑定: custom1

  2. 设置其属性:

    • 名称:

      gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom1/ name '<newname>'
      
    • 命令:

      gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom1/ command '<newcommand>'
      
    • 组合键(例如<Primary><Alt>g):

      gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom1/ binding '<key_combination>'
      

有用的信息可以在这里找到

设置新的自定义快捷方式的示例脚本

下面的脚本可用于从命令行设置新的快捷键组合。可以与命令一起使用(假设组合键可用):

python3 /path/to/script.py '<name>' '<command>' '<key_combination>'

一个例子:

要将快捷键组合设置为使用组合geditAlt+ 打开7

python3 /path/to/script.py 'open gedit' 'gedit' '<Alt>7'

剧本:

#!/usr/bin/env python3
import subprocess
import sys

# defining keys & strings to be used
key = "org.gnome.settings-daemon.plugins.media-keys custom-keybindings"
subkey1 = key.replace(" ", ".")[:-1]+":"
item_s = "/"+key.replace(" ", "/").replace(".", "/")+"/"
firstname = "custom"
# get the current list of custom shortcuts
get = lambda cmd: subprocess.check_output(["/bin/bash", "-c", cmd]).decode("utf-8")
array_str = get("gsettings get "+key)
# in case the array was empty, remove the annotation hints
command_result = array_str.lstrip("@as")
current = eval(command_result)
# make sure the additional keybinding mention is no duplicate
n = 1
while True:
    new = item_s+firstname+str(n)+"/"
    if new in current:
        n = n+1
    else:
        break
# add the new keybinding to the list
current.append(new)
# create the shortcut, set the name, command and shortcut key
cmd0 = 'gsettings set '+key+' "'+str(current)+'"'
cmd1 = 'gsettings set '+subkey1+new+" name '"+sys.argv[1]+"'"
cmd2 = 'gsettings set '+subkey1+new+" command '"+sys.argv[2]+"'"
cmd3 = 'gsettings set '+subkey1+new+" binding '"+sys.argv[3]+"'"

for cmd in [cmd0, cmd1, cmd2, cmd3]:
    subprocess.call(["/bin/bash", "-c", cmd])

如何使用:

将脚本粘贴到一个空文件中,另存为set_customshortcut.py,然后按照上述说明运行。

一些最常用的关键提示(通过实验发现,调查GUI方式对绑定值所做的更改):

Super key:                 <Super>
Control key:               <Primary> or <Control>
Alt key:                   <Alt>
Shift key:                 <Shift>
numbers:                   1 (just the number)
Spacebar:                  space
Slash key:                 slash
Asterisk key:              asterisk (so it would need `<Shift>` as well)
Ampersand key:             ampersand (so it would need <Shift> as well)

a few numpad keys:
Numpad divide key (`/`):   KP_Divide
Numpad multiply (Asterisk):KP_Multiply
Numpad number key(s):      KP_1
Numpad `-`:                KP_Subtract

等等


5
极好的答案。我需要100个按钮来对该脚本进行投票。;)
Anandu M Das 2015年

@JacobVlijm您能否在组合键部分进行一些解释?该<primary>标记表示什么?我可以代替我想代替的任何字母g,ryt吗?
匿名鸭嘴兽2015年

1
@VladK ai,xubuntu,可能是xubuntu的快捷方式(仍然)设置在xml文件中。我将不得不看。如果是这样,我们需要重新打开您的问题,标记为特定于xubuntu。
Jacob Vlijm '16

1
谢谢@JacobVlijm,我已经尝试了。而且我发现我的修复是一个错误。这里确实有些棘手。 custom-keybinding在架构中时,结尾不应包含“ s”。但是,当用作键或在路径中时,它应包含“ s”。否则,“ set”命令将引发异常。因此,请删除custom-keybinding架构中的“ s” 。此外,您的python脚本也应该更新。
e-cloud

2
仅供参考,您的Python脚本中包含错误。如果没有安装键盘快捷键,则gsettings返回的结果@as []将不生效。
Seanny123 '18

11

有一个简单的使用方法dconf

dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/command "'move-window.sh'"
dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/binding "'<Primary><Alt>Page_Down'"
dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/name "'move-window'"

使用gsettings

gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/ name "'move-window'"
gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/ binding "'<Primary><Alt>Page_Down'"
gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/ command "'/usr/local/bin/move-window.sh'"

您需要增加custom0零件数量以添加更多的绑定,即。custom1custom2等等。

要使其永久存在,只需将其添加到.bash_profile或由登录Shell运行的类似脚本即可。只是不要对非登录shell去做.bashrc,因为从我的经验,这些dconfgsettings显著慢下来。更改/添加30个绑定需要一秒钟!您不希望在非登录shell(.bashrc)中使用它!


1
两者都在Ubuntu 18.04中失败。遵循@Jacob Vlijm的回答和此社区Wiki之后,您需要添加custom0到自定义快捷方式列表,例如,使用gsettings set org.gnome.settings-daemon.plugins.media-keys custom-keybindings "['.../custom1/']"。我不知道dconf
miguelmorin

dconf dump DIR可以将整个子路径转储到stdout。输出为类似密钥文件的格式,其值采用GVariant语法。
Pablo A

10

所有自定义键盘快捷键设置都存储在dconf数据库中。

您可以使用以下命令轻松访问它们dconf-editor

sudo apt-get install dconf-editor

然后在编辑器中转到以下dconf路径:

/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/

在此处输入图片说明


所有版本的Linux的位置都相同吗?还是至少有所有版本的Ubuntu?
匿名鸭嘴兽

1
@AnonymousPlatypus:这是自14.04起设置的位置(我无法告诉其他发行版)
Sylvain Pineau

2
这是图形方法,而不是终端程序
Anandu M Das

1
如果我的媒体键键没有自定义键绑定子键,该怎么办?
布兰登·库曾斯基

问题是关于终端,而不是GUI,因此答案无关紧要
Alexei Martianov

6

在12.04中从命令行添加快捷键绑定

为避免接受的答案过于广泛,请发布适用于12.04的单独解决方案。

在(包括12.04)之前,自定义键绑定未存储在dconf数据库中,而是存储在~/.gconf/desktop/gnome/keybindings(在xml文件中,在类似的子文件夹中custom0)。

下面的脚本创建xml文件及其包含文件夹,并自动正确命名。

如何使用

  1. 将该脚本粘贴到一个空文件中,另存为 set_customshortcuts_12.py
  2. 使用以下命令运行它:

    python /path/to/set_customshortcuts_12.py <name> <command> <key1> <key2> <key3>
    

    key3 是可选的,命令可以是例如:

    python /path/to/set_customshortcuts_12.py run_browser firefox Primary 7 
    

    要么

    python /path/to/set_customshortcuts_12.py run_texteditor gedit Primary Alt 3 
    

笔记

  • 请注意,键的命名与编辑gsettings不同。据我所知,这些键的名称就像在“系统设置”>“键盘”>“快捷方式”>“自定义快捷方式”中显示的一样。
  • 我在VirtualBox的12.04上测试了脚本;它需要注销/登录才能进行更改。
#!/usr/bin/env python
import os
import sys

home = os.environ["HOME"]
name = sys.argv[1]
command = sys.argv[2]
keys = sys.argv[3:]

keyfile = [
    '<?xml version="1.0"?>',
    '<gconf>',
    '\t<entry name="action" mtime="1427791732" type="string">',
    '\t\t<stringvalue>'+command+'</stringvalue>',
    '\t</entry>',
    '\t<entry name="name" mtime="1427791732" type="string">',
    '\t\t<stringvalue>'+name+'</stringvalue>',
    '\t</entry>',
    '\t<entry name="binding" mtime="1427791736" type="string">',
    '\t</entry>',
    '</gconf>',
    ]

if len(keys) == 2:
    keyfile.insert(9, '\t\t<stringvalue>&lt;'+keys[0]+'&gt;'+keys[1]+'</stringvalue>')
else:
    keyfile.insert(9, '\t\t<stringvalue>&lt;'+keys[0]+'&gt;&lt;'+keys[1]+'&gt;'+keys[2]+'</stringvalue>')

n = 0
while True:
    check = home+"/"+".gconf/desktop/gnome/keybindings/custom"+str(n)
    if os.path.exists(check):
        n = n+1
    else:
        newdir = check
        newfile = check+"/"+"%gconf.xml"
        break

os.makedirs(newdir)
with open(newfile, "wt") as shortcut:
    for l in keyfile:
        shortcut.write(l+"\n")

1

您可以使用sed来设置新的自定义快捷方式,而无需使用python脚本。您只需在以下脚本中将namebindingaction设置为您的选择:

name="myaction"
binding="<CTRL><ALT>v"
action="/usr/local/bin/myaction"

media_keys=org.gnome.settings-daemon.plugins.media-keys
custom_kbd=org.gnome.settings-daemon.plugins.media-keys.custom-keybinding
kbd_path=/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/$name/
new_bindings=`gsettings get $media_keys custom-keybindings | sed -e"s>'\]>','$kbd_path']>"| sed -e"s>@as \[\]>['$kbd_path']>"`
gsettings set $media_keys custom-keybindings "$new_bindings"
gsettings set $custom_kbd:$kbd_path name $name
gsettings set $custom_kbd:$kbd_path binding $binding
gsettings set $custom_kbd:$kbd_path command $action

1

为此编写了一个脚本。见下文。

请参阅creatShortcut调用中的用法。

export nextShortcutId=0
function creatShortcut() {
    name="$1"
    commandToRun="$2"
    binding="$3"
    path="/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom${nextShortcutId}"
    nextShortcutId=$nextShortcutId+1
    dconf write "$path/name" "'""$name""'"
    dconf write "$path/command" "'""$commandToRun""'"
    dconf write "$path/binding" "'""$binding""'"
}

# dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/binding '"<Primary><Shift>exclam"'
creatShortcut 'copyq show' 'copyq show' '<Primary><Shift>exclam'
creatShortcut 'System Monitor' 'gnome-system-monitor' '<Primary><Alt>m'
creatShortcut 'Suspend' 'systemctl suspend -i' '<Super>d'
creatShortcut 'Volume Up' 'amixer -D pulse sset Master 5%+' '<Super>Page_Up'
creatShortcut 'Volume Down' 'amixer -D pulse sset Master 5%-' '<Super>Page_Down'

overallbindings=""
for ((i = 0 ; i < $nextShortcutId ; i++ ));
do
    overallbindings="$overallbindings, '$customindingPathPrefix$i/'"
done
overallbindings="[${overallbindings:2}]" # Delete the first 2 chars: " ," - space and comma
# echo $overallbindings

# Update the list of bindings for the shortcuts to work
dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings "$overallbindings"
# dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings "['/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom1/', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom2/', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom3/', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom4/', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom5/']"

如果nextShortcutId可以自动检测旧密钥是否已经存在(已经由其他程序创建),以确保没有冲突,那将是完美的。另外,请检查是否有其他内容绑定到输入的密钥。
杰克·吉芬

0

我发现@JacobVlijm发布的答案非常有用,尤其是脚本。我将代码移植到bash。我不是这个功能是完美的,它可能包含一些错误,但是,它对我有用。

function set_shortcuts(){
    # Usage: set_shortcuts [name] [command] [shortcut]
    unset num i name command shortcut value test value_new
    local name="$1"
    local command="$2"
    local shortcut="$3"
    local value=$(gsettings get org.gnome.settings-daemon.plugins.media-keys custom-keybindings)
    local test=$(echo $value | sed "s/\['//;s/', '/,/g;s/'\]//" - | tr ',' '\n' | grep -oP ".*/custom\K[0-9]*(?=/$)")

    if [ "$(echo "$value" | grep -o "@as")" = "@as" ]; then
        local num=0
        local value_new="['/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom${num}/']"
    else
        local i=1
        until [ "$num" != "" ]; do
            if [ "$(echo $test | grep -o $i)" != "$i" ]; then
                local num=$i
            fi
            i=$(echo 1+$i | bc);
        done
        local value_new=$(gsettings get org.gnome.settings-daemon.plugins.media-keys custom-keybindings | sed "s#']\$#', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom${num}/']#" -)
    fi

    gsettings set org.gnome.settings-daemon.plugins.media-keys custom-keybindings "$value_new"
    gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom${num}/ name "$name"
    gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom${num}/ command "$command"
    gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom${num}/ binding "$shortcut"
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.