sponsor Vim development Vim logo Vim Book Ad

vim-xkbswitch : Automatic Keyboard Layout Switcher

 script karma  Rating 393/107, Downloaded by 12797  Comments, bugs, improvements  Vim wiki

created by
Alexey Radkov
 
script type
utility
 
description
About:

Vim plugin XkbSwitch can be used to easily switch current keyboard layout back
and forth when entering and leaving Insert mode. Say you are typing some
document in Russian and have to leave Insert mode: when you press <Esc> your
keyboard layout switches to US/English automatically. When you further enter
Insert mode once again the Russian keyboard layout will be automatically
switched back!

XkbSwitch requires OS dependent keyboard layout switcher. Currently it depends
on xkb-switch (http://github.com/ierton/xkb-switch) for UNIX / X Server and
xkb-switch-win (http://github.com/DeXP/xkb-switch-win) for Windows.

For Mac OS X you can try Input Source Switcher
(http://github.com/vovkasm/input-source-switcher) and set library path as

    let g:XkbSwitchLib = '/usr/local/lib/libInputSourceSwitcher.dylib'

Gnome 3 no longer works correctly with xkb-switch, so consider switching to
g3kb-switch (https://github.com/lyokha/g3kb-switch) if you are using this
environment. The library path should be set as

    let g:XkbSwitchLib = '/usr/local/lib/libg3kbswitch.so'

github: http://github.com/lyokha/vim-xkbswitch


Features:

  - Supported OS: UNIX / X Server, Windows, Mac OS X
  - Switches keyboard layout when entering / leaving Insert and Select modes
  - Keyboard layouts are stored separately for each buffer
  - Keyboard layouts are kept intact while navigating between windows or
    tabs without leaving Insert mode
  - Automatic loading of language-friendly Insert mode mappings. For example
    when Russian mappings have loaded then if there was a mapping

    <C-G>S        <Plug>ISurround

    a new mapping

    <C-G>Ы        <Plug>ISurround

    will be loaded. Insert mode mappings duplicates make it easy to apply
    existing maps in Insert mode without switching current keyboard layout
  - Fast and easy building of custom syntax based keyboard layout switching
    rules in Insert mode


Configuration:

Basic configuration requires only 1 line in your .vimrc:

    let g:XkbSwitchEnabled = 1

Additionally path to the backend switcher library can be defined:

    let g:XkbSwitchLib = '/usr/local/lib/libxkbswitch.so'

However normally it is not necessary as far as the plugin is able to find it
automatically. To enable Insert mode mappings duplicates user may want to add

    let g:XkbSwitchIMappings = ['ru']

Here Insert mappings duplicates for Russian winkeys layout will be generated
whenever Insert mode is started. It is possible to define a list of different
layouts, for example

    let g:XkbSwitchIMappings = ['ru', 'de']

but currently only Russian winkeys layout translation map ('ru') is supported
out of the box. There are 2 ways how a user can provide extra definitions of
keyboard layout translation maps (or replace existing default 'ru' map):

  - Define variable g:XkbSwitchIMappingsTr:

    let g:XkbSwitchIMappingsTr = {
                \ 'ru':
                \ {'<': 'qwertyuiop[]asdfghjkl;''zxcvbnm,.`/'.
                \       'QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?~@#$^&|',
                \  '>': 'йцукенгшщзхъфывапролджэячсмитьбюё.'.
                \       'ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё"№;:?/'},
                \ 'de':
                \ {'<': 'yz-[];''/YZ{}:"<>?~@#^&*_',
                \  '>': 'zyßü+öä-ZYÜ*ÖÄ;:_°"§&/(?#'},
                \ }

  - Create a file with layout translation maps and put its path into variable
    g:XkbSwitchIMappingsTrData, for example:

    let g:XkbSwitchIMappingsTrData = $HOME.'/opt/xkbswitch.tr'

    File with maps must follow this format:

  ru  Russian winkeys layout
  < qwertyuiop[]asdfghjkl;'zxcvbnm,.`/QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?~@#$^&|
  > йцукенгшщзхъфывапролджэячсмитьбюё.ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё"№;:?/

  de
  < yz-[];'/YZ{}:"<>?~@#^&*(_\
  > zyßü+öä-ZYÜ*ÖÄ;:_°"§&/()?#

    Sample file xkbswitch.tr with exactly this content is shipped with this
    plugin distribution. It is encoded in UTF-8 and it is important as far as
    its content is read using readfile()! If your locale is not UTF-8 and
    you want to use this sample file then it seems that you will have to
    re-encode it in your locale standard encoding

Be very careful with mapping duplicates! They won't replace existing Insert
mode mappings but may define extra mappings that will change normal Insert
mode user experience. For example plugin echofunc defines Insert mode mappings
for '(' and ')', therefore assuming that in Deutsch translation map there
could be ')' to '=' translation, we would get '=' unusable in any keyboard
layout (as far as echofunc treats ')' in a very specific way). That is why
this translation is missing in example above and in file xkbswitch.tr content.

There are multiple examples of similar issues. For instance Russian winkeys
translate '.' into 'ю' and when you are editing a C/C++ source file with
enabled omnicompletion plugin character 'ю' (which you can use in comments)
will always be replaced by '.'. To address these issues starting from version
0.10 a new variable g:XkbSwitchSkipIMappings was introduced. It defines which
original Insert mode mappings should not be translated for specific filetypes.
Add into your .vimrc lines

    let g:XkbSwitchSkipIMappings = {'c': ['.', '>', ':', '/*', '/*<CR>'],
            \ 'cpp': ['.', '>', ':', '/*', '/*<CR>']}

and now you will be able to print 'ю' in C and C++ source files. In this
example five Insert mode mappings were prohibited for translation in two
filetypes: C and C++, the first three correspond to omnicompletion plugin
and the last two address plugin c.vim. Why mappings duplicates starting from
'/' were added: Russian winkeys translate '/' into '.' and this makes vim
wait for a next character input after '.' was inserted which makes
omnicompletion plugin almost unusable.

Beware: variable g:XkbSwitchSkipIMappings is not parameterized by keyboard
layouts but only by filetypes.

By default saved Normal mode keyboard layout is restored when leaving Insert
mode, but you can specify to use particular layout for that:

    let g:XkbSwitchNLayout = 'us'

Also you can specify original Insert mode keyboard layout:

    let g:XkbSwitchILayout = 'us'

It makes sense to disable XkbSwitch for buffers with specific filetypes, for
example various file system or tag navigators. For example to disable
XkbSwitch for NerdTree add in your .vimrc line

    let g:XkbSwitchSkipFt = [ 'nerdtree' ]

By default (e.g. when g:XkbSwitchSkipFt is not defined in .vimrc) following
filetypes are skipped: 'tagbar', 'gundo', 'nerdtree' and 'fuf' (FuzzyFinder).

You can enable XkbSwitch in runtime (e.g. when g:XkbSwitchEnabled is not set
in your .vimrc) by issuing command

    :EnableXkbSwitch

This command will respect current settings of g:XkbSwitchIMappings etc. Be
aware that there is no way to disable XkbSwitch after it has been enabled.


Troubleshooting:

  - There is a known issue when vim-latex package is installed. In this case
    entering Russian symbols in Insert mode when editing tex files becomes
    impossible. The issue arises from clashing XkbSwitch Insert mappings
    duplicates with mappings defined in vim-latex. To work this issue around
    you can disable XkbSwitch Insert mode mappings duplicates for filetype
    'tex':

    let g:XkbSwitchIMappingsSkipFt = ['tex']

  - Related to X Server only. When editing files on a remote host via ssh the
    ssh -X option must be supplied:

    ssh -X remote.host

    This option will make ssh forward X Server protocol messages between the
    local host and the remote host thus making it possible to switch the local
    host keyboard layouts.

  - Related to GTK based gvim only. In bare X terminals keycodes for <C-S> and
    <C-Ы> are the same which makes it possible to leave sequences with control
    keys in Insert mode mappings duplicates as they are. But this is not the
    case in GTK based gvim. The issue is still investigated.
 
install details
An external keyboard layout switcher must be installed (see Description). Extract content of the tarball in your home vim directory and run

:helptags ~/.vim/doc/

in vim to create vim help tags.
 

rate this script Life Changing Helpful Unfulfilling 
script versions (upload new version)

Click on the package to download.

package script version date Vim version user release notes
vim-xkbswitch-0.20.tgz 0.20 2023-04-20 7.3 Alexey Radkov - Support for Sway via libswaykbswitch.so (thanks to Andrey Khorokhorin).
- New utility keymap2imaptr.vim to help translate vim's language keymaps to vim-xkbswitch imap translation files.
- Test more paths to detect the location of libg3kbswitch.so
vim-xkbswitch-0.19.tgz 0.19 2023-01-06 7.3 Alexey Radkov It's now possible to run a custom vim function when entering Insert mode. The function is pointed by variable g:XkbSwitchIEnterHook.
vim-xkbswitch-0.18.tgz 0.18 2022-12-21 7.3 Alexey Radkov - Proper support for tracking keyboard layout state upon entering/leaving Select mode using ModeChanged events.
- Setting variables g:XkbSwitchSkipGhKeys and g:XkbSwitchSelectmodeKeys is now deprecated and has no effect when ModeChanged events are supported.
vim-xkbswitch-0.17.2.tgz 0.17.2 2022-12-18 7.3 Alexey Radkov A few improvements and optimizations in the duplicate insert mappings load algorithm.
vim-xkbswitch-0.17.1.tgz 0.17.1 2022-11-15 7.3 Alexey Radkov Bugfix: tracking of the keyboard layout state was getting broken after visiting the command-line window with commands q/ and q?.
vim-xkbswitch-0.17.tgz 0.17 2022-11-13 7.3 Alexey Radkov - Full support for tracking keyboard layout state upon entering/leaving command line when searching patterns with / and ?.
- Setting variables g:XkbSwitchAssistSKeymap and g:XkbSwitchLoadOnBufRead is now deprecated and has no effect.
vim-xkbswitch-0.16.tgz 0.16 2022-04-09 7.3 Alexey Radkov - Improvement: provide ability to toggle iminsert in Normal mode by defining variable g:XkbSwitchIminsertToggleKey.
- Bugfix: added more backslashes to fix translations of insert mappings.
vim-xkbswitch-0.15.2.tgz 0.15.2 2022-03-24 7.3 Alexey Radkov - In default g:XkbSwitchIMappingsTr the Ukrainian ('uk') keyboard layout translation map was added (thanks to kukushkawi).
- Fixed wrong behavior of dynamic keymap assistance in Normal mode.
vim-xkbswitch-0.15.1.tgz 0.15.1 2021-09-06 7.3 Alexey Radkov - Bugfix: insert mappings which contain single quotes must be escaped when building translations.
- Never enable the plugin in nofile buftypes.
vim-xkbswitch-0.15.tgz 0.15 2020-12-02 7.3 Alexey Radkov     - Integration with LeaderF plugin (thanks to Freed-Wu)
    - Fixed interference with neovim's float windows
vim-xkbswitch-0.14.3.tgz 0.14.3 2017-03-16 7.3 Alexey Radkov Bugfix for Mac users after previous version: Re-enable the plugin when vim has() both "macunix" and "unix".
vim-xkbswitch-0.14.2.tgz 0.14.2 2017-02-22 7.3 Alexey Radkov - Do not enable the plugin on Linux/X11 when there is no X server run
- Check validity of imap values when generating imappings, prefer function execute() to redir when reading them
vim-xkbswitch-0.14.1.tgz 0.14.1 2016-01-31 7.3 Alexey Radkov Keymap assistance refactored with more robust behaviour. Added dynamic keymap support. In the docs added an example of how to enable Powerline iminsert indicator.
vim-xkbswitch-0.14.tgz 0.14 2016-01-29 7.3 Alexey Radkov     - Keymap assistance in Normal and Command-line modes provides limited
      support for using the last Insert mode keyboard layout in Normal mode
      commands 'r' and 'f' and search lines (see updated docs)
vim-xkbswitch-0.13.tgz 0.13 2016-01-12 7.3 Alexey Radkov     - Named registers insertion keys translation (e.g <C-R>a to <C-R>ф for
      Russian winkeys layout)
    - Better xkbswitch library search algorithm
    - Option for choosing unconditional keyboard layout when entering Insert
      mode with buffer-variable b:XkbSwitchILayout. This can also be used to
      disable keyboard layout switching when entering Insert mode (see updated
      docs)
vim-xkbswitch-0.12.tgz 0.12 2015-01-06 7.3 Alexey Radkov     - Added support for Mac OS X using external library Input Source Switcher
      (see updated docs)
    - Added new global variable g:XkbSwitchSkipGhKeys which can be used to
      optionally disable gh-mappings required for Select mode support
vim-xkbswitch-0.11.tgz 0.11 2014-08-02 7.3 Alexey Radkov     - Implemented full support for various selection models defined with
      option selectmode
    - Do not duplicate <SNR> mappings
vim-xkbswitch-0.10.1.tgz 0.10.1 2014-03-11 7.0 Alexey Radkov bugfix: bars in Insert mode mappings are now properly escaped
vim-xkbswitch-0.10.tgz 0.10 2013-07-06 7.3 Alexey Radkov - Fixed building Insert mode mappings defined with <expr>
- Added new variable g:XkbSwitchSkipIMappings to disable translation of
  specific Insert mode mappings for specific file types
vim-xkbswitch-0.9.4.tgz 0.9.4 2013-07-05 7.3 Alexey Radkov Switching between Select and Visual modes (with <C-g>) without flickers
vim-xkbswitch-0.9.3.tgz 0.9.3 2013-06-26 7.3 Alexey Radkov Better support and fixes in Select mode
vim-xkbswitch-0.9.2.tgz 0.9.2 2013-05-13 7.3 Alexey Radkov Further fixes related to the custom syntax based switching rules
implementation
vim-xkbswitch-0.9.1.tgz 0.9.1 2013-05-12 7.3 Alexey Radkov fixed broken layout switching
vim-xkbswitch-0.9.tgz 0.9 2013-05-12 7.3 Alexey Radkov Implemented helpers for building custom keyboard layout switching rules
based on syntax inside Insert mode (see updated docs)
vim-xkbswitch-0.8.2.tgz 0.8.2 2013-04-23 7.3 Alexey Radkov - The cause of the issue explained in the 0.8.1 change log discovered. It
  affects gvim in client-server mode (e.g. when files are open from an
  external application using options --remote-tab and similar). Variable
  g:XkbSwitchFixNoBufLeave is not needed any more: the fix is applied
  automatically in gvim with clientserver feature. Also this issue
  investigation revealed that different switcher strategies implemented
  inside backend libraries must be supported. Currently X server switcher
  gets and sets keyboard layout globally whereas Windows switcher does it
  locally in vim window. This difference is reflected in a new field
  'local' in dictionary g:XkbSwitch
vim-xkbswitch-0.8.1.tgz 0.8.1 2013-04-19 7.3 Alexey Radkov - Fixed a bug when original Insert mode layout could be lost when leaving
  a buffer in Insert mode for a new tab in gvim. Thanks to zdm for code
  contribution. The bug was caused by missing BufLeave events in certain
  cases. It seems that it does not affect all vim flavors (both latest
  Mercurial snapshot built on my Fedora 18 desktop and standard vim
  distribution taken from repository seem to be not affected). You can
  disable the code of the fix by adding in your .vimrc line

    let g:XkbSwitchFixNoBufLeave = 0

  if you know that your vim is good and always generates BufLeave events
  when jumping to another tab while being in Insert mode
vim-xkbswitch-0.8.tgz 0.8 2013-04-19 7.3 Alexey Radkov - Added possibility to specify default Normal mode and original Insert
  mode keyboard layouts
- Docs fixed and extended
vim-xkbswitch-0.7.tgz 0.7 2013-04-19 7.3 Alexey Radkov - Keyboard layouts are kept intact while navigating between windows or
  tabs without leaving Insert mode
- A new variable g:XkbSwitchSkipFt was introduced to provide ability of
  disabling XkbSwitch for specific filetypes
vim-xkbswitch-0.6.tgz 0.6 2013-04-15 7.3 Alexey Radkov - Added variable g:XkbSwitchPostIEnterAuto to register InsertEnter
   autocommands that should run after standard XkbSwitch InsertEnter
   autocommand
- Added an example of how custom keyboard layout switching rules inside
   Insert mode can be implemented
- Fixed Select mode switching broken in version 0.5
vim-xkbswitch-0.5.tgz 0.5 2013-04-15 7.3 Alexey Radkov - Cleaner and more generic algorithm for switching layout when leaving
   Insert mode: there is no default keyboard layout in Normal mode any
   more; instead last layout that was actual when entering Insert mode is
   being restored when leaving Insert mode.

- Troubleshooting section in the documentation was extended
vim-xkbswitch-0.4.1.tgz 0.4.1 2013-04-11 7.3 Alexey Radkov Search Windows libraries in $VIMRUNTIME by default
vim-xkbswitch-0.4.tgz 0.4 2013-04-11 7.3 Alexey Radkov - Insert mode mappings duplicates factory algorithm reimplemented
- New global variable g:XkbSwitchIMappingsSkipFt introduced. It is
   supposed to be used to disable Insert mode mappings duplicates creation
- Docs updated
vim-xkbswitch-0.3.tgz 0.3 2013-04-07 7.2 Alexey Radkov - Checking for library presence implemented by filereadable() instead
   executable() - looks like it may have sense for Ubuntu
- Fixed error messages upon start if g:XkbSwitchEnabled were not set
- Added doc about command EnableXkbSwitch
vim-xkbswitch-0.2.tgz 0.2 2013-04-03 7.2 Alexey Radkov Better treatment of Insert mode mapping duplicates. Doc updated.
vim-xkbswitch-0.1.1.tgz 0.1.1 2013-04-01 7.2 Alexey Radkov better check for Windows libs
vim-xkbswitch-0.1.tgz 0.1 2013-04-01 7.2 Alexey Radkov Initial upload
ip used for rating: 18.191.216.163

If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to the maillist. Help Bram help Uganda.
   
Vim at Github