Giter Site home page Giter Site logo

vim-xkbswitch's Introduction

Vim-xkbswitch

by Alexey Radkov and Dmitry Hrabrov a.k.a. DeXPeriX

Table of contents

About

If you speak and write in two or more languages, you may know how it's frustrating to constantly switch keyboard layouts manually, because vim in command mode can understand only English letters. So you need constantly change keyboard layout into English if you need perform some command and if you are writing texts, for example, in Russian, German or Chinese at the same time.

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 an OS dependent keyboard layout switcher. Below is the list of compatible switchers.

Features

  • Supported OS: UNIX (X Server / Sway), Windows, Mac OS X.

  • Switches keyboard layout when entering / leaving Insert and Select modes as well as the command line when searching patterns.

  • Dynamic keymap assistance in commands like r and f in Normal mode.

  • 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 duplicates. 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.

Setup

Before installation of the plugin the OS dependent keyboard layout switcher must be installed (see About). The plugin itself is installed by extracting of the distribution in your vim runtime directory.

Configuration

Basic 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 ('ru') and Ukrainian ('uk') layout translation maps are supported out of the box. There are 2 ways how a user can provide extra definitions of keyboard layout translation maps (or alter/remove existing default 'ru' and 'uk' maps):

  • 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. Files with translation maps can be easily created from vim keymap definitions: see details here.

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>', '/*', '/*<CR>'],
        \  'cpp' : ['.', '>', ':', '{<CR>', '/*', '/*<CR>']}

and now you will be able to print 'ю' in C and C++ source files. In this example six Insert mode mappings were prohibited for translation in two filetypes: C and C++. The first three correspond to omnicompletion plugin and the last three address plugin c.vim. Why mappings duplicates starting from '/' were added: Russian winkeys translate '/' into '.' and this makes vim wait for a while until the next character after '.' has been inserted which makes omnicompletion plugin almost unusable. If you want to skip specific Insert mode mappings for all filetypes then you can use '*' as the filetype key in g:XkbSwitchSkipIMappings.

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

Besides natural Insert mode mappings, register insertion translations are also supported. For example, being in Insert mode and having Russian winkeys layout on, you can insert content of register 'a' just printing <C-R>ф without switching current keyboard layout. To disable translation of register names in Insert mode put line

let g:XkbSwitchLoadRIMappings = 0

into your .vimrc.

Keymap assistance in Normal mode

XkbSwitch is unable to guess keyboard layout when using Normal mode commands r and f and, in the past, searching patterns with / and ?. Fortunately, it can assist keymap in this by setting

let g:XkbSwitchAssistNKeymap = 1        " for commands r and f
if !exists('##CmdlineEnter')
    let g:XkbSwitchAssistSKeymap = 1    " for search lines
endif

given that keymap is set to some value, for example

set keymap=russian-jcukenwin
set iminsert=0
set imsearch=0

(Note that setting of g:XkbSwitchAssistSKeymap is deprecated because tracking of entering / leaving command line for searching patterns is fully supported after CmdlineEnter and CmdlineLeave events have been introduced in vim.)

Now when you leave Insert mode, the keyboard layout is switched back to the usual Normal mode value, but values of iminsert and imsearch are set depending on the last Insert mode keyboard layout: if it was equal to the value of b:keymap_name that is normally defined in keymap files then they are set to 1, otherwise to 0. If keymap names do not match system keyboard layout names then you can remap them using variable g:XkbSwitchKeymapNames.

let g:XkbSwitchKeymapNames = {'ru' : 'ru_keymap', 'uk' : 'uk_keymap'}

Here ru and uk are system keyboard layout names whereas ru_keymap and uk_keymap are values of b:keymap_name.

When more than two keyboard layouts are used it probably makes sense to set keymaps dynamically in runtime. XkbSwitch can do it for you! You only need to define a new variable

let g:XkbSwitchDynamicKeymap = 1

and map g:XkbSwitchKeymapNames to keymap names instead of values of b:keymap_name. For example

let g:XkbSwitchKeymapNames =
            \ {'ru' : 'russian-jcukenwin', 'uk' : 'ukrainian-jcuken'}

Now keymap will automatically switch to the last keyboard layout when you leave Insert mode.

To toggle keymap layout in Normal mode for using in commands r and f, you may need to set a dedicated key:

let g:XkbSwitchIminsertToggleKey = '<C-^>'

By default pressing the key will be echoed in the command-line which is sometimes superfluous: modern status-line plugins such as airline normally provide support for showing iminsert indicators.

To disable echo messages when toggling keymap layout add line

let g:XkbSwitchIminsertToggleEcho = 0

into your .vimrc.

To enable the iminsert indicator in airline add line

let g:airline_detect_iminsert = 1

Notice that toggling keymap layout when typing a pattern for a search command can be done with the builtin key Ctrl-^.

Default layouts

By default last 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'

Or unconditional Insert mode keyboard layout using buffer variable with the same name:

let b:XkbSwitchILayout = 'us'

If b:XkbSwitchILayout is set to the empty value then the keyboard layout is not changed when entering Insert mode. Be aware that momental switching from-and-to Insert mode (e.g. with Insert mode command <C-O> and all types of selections) will turn current keyboard layout to the value of b:XkbSwitchILayout. If you want to use unconditional Insert mode keyboard layout by default then put line

autocmd BufEnter * let b:XkbSwitchILayout = 'us'

into your .vimrc (change us to desired value if needed).

Disable for specific filetypes

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).

Enable in runtime

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.

Insert enter hook

You may want to run a custom vim function when entering Insert mode. For example, let's flash the cursor for a moment if the keyboard layout effectively switches. Plugin Beacon fits very well this purpose. Just put lines

let g:XkbSwitchIEnterHook = 'XkbSwitchIEnterHook'

highlight link BeaconIEnter Cursor

fun! XkbSwitchRevertBeaconHighlight(id)
    highlight! link Beacon BeaconDefault
endfun

fun! XkbSwitchIEnterHook(old, new)
    if a:new != a:old
        let save_beacon_size = g:beacon_size
        let g:beacon_size = 20
        highlight! link Beacon BeaconIEnter
        Beacon
        let g:beacon_size = save_beacon_size
        call timer_start(500, 'XkbSwitchRevertBeaconHighlight')
    endif
endfun

into .vimrc file. Arguments old and new are keyboard layouts being switched from and to while transitioning from Normal to Insert mode.

Custom keyboard layout switching rules

Imagine that you are editing a simple dictionary with 2 columns delimited by vertical bars. In the first column you are writing down a German word and in the second column - its Russian translation. For example:

| Wort         | Übersetzung |
|--------------|-------------|
| der Mond     | луна        |
| humpeln      | хромать     |
| stark        | сильный     |

You want the keyboard layout to be automatically switched to the corresponding language when you are moving between the columns in Insert mode. It is feasible! When you start editing switch layouts in the both columns manually just once: after that XkbSwitch will learn how to switch them further. It will restore layouts after leaving Insert mode and entering it once again.

In this section it will be shown how to achieve this. First of all there should exist criteria upon which XkbSwitch will decide when it must switch layouts. The simplest criteria are syntactic rules. So the content of the columns must be syntactically distinguishable. It means that we need a file with syntax rules and some new filetype defined, say mdict. For the sake of simplicity let it be not an absolutely new filetype but rather a subclass of an existing one, for example vimwiki. Then we should create a new file after/syntax/vimwiki.vim:

if match(bufname('%'), '\.mdict$') == -1
    finish
endif

let s:colors = {'original':   [189, '#d7d7ff'],
              \ 'translated': [194, '#d7ffd7'],
              \ 'extra':      [191, '#d7ff5f']}

function! s:set_colors()
    let colors = deepcopy(s:colors)
    if exists('g:colors_name') && g:colors_name == 'lucius' &&
                \ g:lucius_style == 'light'
        let colors['original']   = [26,  '#005fd7']
        let colors['translated'] = [22,  '#005f00']
        let colors['extra']      = [167, '#d75f5f']
    endif
    exe 'hi mdictOriginalHl term=standout ctermfg='.colors['original'][0].
                \ ' guifg='.colors['original'][1]
    exe 'hi mdictTranslatedHl term=standout ctermfg='.colors['translated'][0].
                \ ' guifg='.colors['translated'][1]
    exe 'hi mdictExtraHl term=standout ctermfg='.colors['extra'][0].
                \ ' guifg='.colors['extra'][1]
endfunction

syntax match mdictCell '|[^|]*\ze|' containedin=VimwikiTableRow contained
            \ contains=VimwikiCellSeparator,mdictOriginal,mdictTranslated
syntax match mdictOriginal '[^|]\+\ze|\s*\S*.*$' contained contains=mdictExtra
syntax match mdictTranslated '[^|]\+\ze|\s*$' contained contains=mdictExtra
syntax match mdictExtra '([^()]*)' contained

call s:set_colors()
autocmd ColorScheme * call s:set_colors()

hi link mdictOriginal   mdictOriginalHl
hi link mdictTranslated mdictTranslatedHl
hi link mdictExtra      mdictExtraHl

Here the syntactic criteria have been defined: content of the first column will have syntax id mdictOriginal and content of the second column - mdictTranslated.

In .vimrc following lines must be added:

let g:mdict_synroles = ['mdictOriginal', 'mdictTranslated']

fun! MdictCheckLang(force)
    if !filereadable(g:XkbSwitchLib)
        return
    endif

    let cur_synid  = synIDattr(synID(line("."), col("."), 1), "name")

    if !exists('b:saved_cur_synid')
        let b:saved_cur_synid = cur_synid
    endif
    if !exists('b:saved_cur_layout')
        let b:saved_cur_layout = {}
    endif

    if cur_synid != b:saved_cur_synid || a:force
        let cur_layout = ''
        for role in g:mdict_synroles
            if b:saved_cur_synid == role
                let cur_layout =
                    \ libcall(g:XkbSwitchLib, 'Xkb_Switch_getXkbLayout', '')
                let b:saved_cur_layout[role] = cur_layout
                break
            endif
        endfor
        for role in g:mdict_synroles
            if cur_synid == role
                if exists('b:saved_cur_layout[role]')
                    call libcall(g:XkbSwitchLib, 'Xkb_Switch_setXkbLayout',
                                \ b:saved_cur_layout[role])
                else
                    let b:saved_cur_layout[role] = empty(cur_layout) ?
                                \ libcall(g:XkbSwitchLib,
                                \ 'Xkb_Switch_getXkbLayout', '') : cur_layout
                endif
                break
            endif
        endfor
        let b:saved_cur_synid = cur_synid
    endif
endfun

autocmd BufNewFile,BufRead *.mdict setlocal filetype=vimwiki |
           \ EnableXkbSwitch
autocmd BufNewFile         *.mdict VimwikiTable 2 2
autocmd BufNewFile         *.mdict exe "normal dd" | startinsert
autocmd CursorMovedI       *.mdict call MdictCheckLang(0)

let g:XkbSwitchPostIEnterAuto = [
            \ [{'pat': '*.mdict', 'cmd': 'call MdictCheckLang(1)'}, 0] ]

Function MdictCheckLang() does all the custom layout switching and can be regarded as a plugin to the XkbSwitch. The first autocommand states that if file has extension .mdict then its filetype must be vimwiki and turns on XkbSwitch. The next two autocommands are optional and only make editing mdict files more comfortable. The last autocommand (for CursorMovedI events) calls MdictCheckLang() when cursor moves into different columns in Insert mode. The next definition

let g:XkbSwitchPostIEnterAuto = [
            \ [{'pat': '*.mdict', 'cmd': 'call MdictCheckLang(1)'}, 0] ]

registers an InsertEnter autocommand in augroup XkbSwitch. If we had instead defined an InsertEnter autocommand here then the command would have been put before the standard InsertEnter autocommand in augroup XkbSwitch. Using variable g:XkbSwitchPostIEnterAuto ensures that the new command will run after the standard InsertEnter autocommand. The second element in an item inside g:XkbSwitchPostIEnterAuto can be 0 or 1. If it is 1 then XkbSwitch won't switch layout itself when entering Insert mode. In our case it should be 0 because MdictCheckLang() requires preliminary switching keyboard layout from XkbSwitch when entering Insert mode.

Starting from version 0.9 a generic helper for building custom syntax based keyboard layout switching rules was implemented inside the plugin code. Now building syntax rules is as simple as defining variable g:XkbSwitchSyntaxRules in .vimrc. For example

let g:XkbSwitchSyntaxRules = [
            \ {'pat': '*.mdict', 'in': ['mdictOriginal', 'mdictTranslated']},
            \ {'ft': 'c,cpp', 'inout': ['cComment', 'cCommentL']} ]

registers syntax rules for files with extension .mdict (the first element in g:XkbSwitchSyntaxRules: it replaces our old definitions of g:mdict_synroles, MdictCheckLang(), autocmd CursorMovedI and g:XkbSwitchPostIEnterAuto) and comments rules for C and C++ files (the second element in g:XkbSwitchSyntaxRules). The comments rules define that comments areas may have their own keyboard layouts in Insert mode and when cursor enters or leaves them the corresponding layouts must be restored. It may be useful if a user wants to make comments in a language that uses not standard keyboard layout without switching layouts back and forth. Notice that the second rule lists syntax groups in element inout whereas the first rule uses element in. The difference is that in the case of the comments rule we want to restore basic keyboard layout (i.e. layout for code areas) when leaving comments areas, but in the mdict rule we do not care about leaving areas mdictOriginal and mdictTranslated and only care about entering them.

Troubleshooting

  • To test if the switcher library is well configured, run commands

    :echo libcall(g:XkbSwitchLib, 'Xkb_Switch_getXkbLayout', '')

    and

    :call libcall(g:XkbSwitchLib, 'Xkb_Switch_setXkbLayout', 'ru')

    which get and set the keyboard layout.

  • Some characters from alternative keyboard layouts may fail to enter or behave in strange ways for certain filetypes. For example in Russian winkeys layout characters 'б', 'ю', 'ж' and 'э' may fail to enter in C++ source files. The reason of that is layout translation maps specified in variable g:XkbSwitchIMappings. You may work this around by simply not setting this variable, or better by specifying characters from the main keyboard layout whose translation should be skipped using variable g:XkbSwitchSkipIMappings. See details in section Basic configuration.

  • 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']
  • When leaving Insert mode after using an alternative keyboard layout (say Russian), there could be a time lag (of length 1 sec if the value of timeoutlen was not altered) before typing commands in Normal mode gets back to produce any effect. To cope with this issue, the value of ttimeoutlen (notice the double-t in the beginning of its name!) must be set to some small value, say

    set ttimeoutlen=50
  • 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.

vim-xkbswitch's People

Contributors

freed-wu avatar khaser avatar kukushkawi avatar l29ah avatar lyokha avatar mtex01 avatar myshov avatar shatur avatar solopasha avatar vbauerster avatar vovkasm avatar zenbro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vim-xkbswitch's Issues

Не работает (не получилось настроить?) на Ubuntu 16.04

Пишу в инсерт моде текст на русском, выхожу в нормал мод - расскладка остаётся русской.
Настройки:
let g:XkbSwitchEnabled = 1
let g:XkbSwitchLib = '/usr/lib/libxkbswitch.so'
let g:XkbSwitchILayout = 'ru'
let g:XkbSwitchNLayout = 'us'

libxkbswitch.so с правами chmod +x

g:XkbSwitchIMappingsTr not overriding existing default 'ru' map

Пользуюсь раскладкой Programmer Dvorak, и в следующей конфигурации попытался перезаписать маппинг по умолчанию для qwerty:

let g:XkbSwitchIMappingsTr = {
            \ 'ru':
            \ {'<': ';,.pyfgcrl`/@aoeuidhtns-''qjkxbmwvz'.
            \       ':<>PYFGCRL?^AOEUIDHTNS_"QJKXBMWVZ~75390|',
            \  '>': 'йцукенгшщзхъфывапролджэячсмитьбюё.'.
            \       'ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё"№;:?/'},
            \ }
let g:XkbSwitchIMappings = ['ru']

При входе в режим вставки переключаюсь с дворака на русскую раскладку, затем нажимаю ^R (^O на qwerty) и любой регистр вставки, ничего не происходит. Однако если я тоже самое делаю как если бы у меня была qwerty, т.е. комбинация ^P на двораке (^R на qwerty соотвественно) то текст вставляется из регистров.

Что делаю не так?

Не удается заставить работать на ubuntu 18.04

Добрый день!
Успешно использую ваш замечательный плагин под виндами, сейчас перехожу на ubuntu, но пока не удалось заставить его работать.

Сначала попытался собрать xkb-switch отсюда
https://github.com/ierton/xkb-switch/releases/tag/1.6.0 по инструкции
https://github.com/ierton/xkb-switch#installing
Но не удачно, на шаге
cmake ..
получаю ошибку
CMake Error at /usr/share/cmake-3.10/Modules/FindX11.cmake:429 (message): Could not find X11
Побороть эту ошибку не удалось.

Нашел этот пакет в PPA и установил

  sudo add-apt-repository ppa:atareao/atareao
  sudo apt update
  sudo apt install xkb-switch

правда версия 1.4.0
xkb-switch -l
выдает

us
ru
us

После этого попробовал - плагин не работает.
.vimrc:

let g:XkbSwitchEnabled = 1 
let g:XkbSwitchIMappings = ['ru']
"плагин ставится с помощью Vandle
Plugin 'lyokha/vim-xkbswitch'

Прочитал в документации про
let g:XkbSwitchLib = '/usr/local/lib/libxkbswitch.so'
но у меня по этому пути такого файла нет.

Типографская раскладка Бирмана

Системные раскладки заменены на http://ilyabirman.ru/projects/typography-layout/, установлены https://github.com/myshov/xkbswitch-macosx и https://github.com/myshov/libxkbswitch-macosx.
При english-раскладке команда
:echo libcall('/usr/local/lib/libxkbswitch.dylib', 'Xkb_Switch_getXkbLayout', '')
возвращает 2, при русской, соответсвенно — 1. Корректно работают

:echo libcall('/usr/local/lib/libxkbswitch.dylib', 'Xkb_Switch_setXkbLayout', '1')
:echo libcall('/usr/local/lib/libxkbswitch.dylib', 'Xkb_Switch_setXkbLayout', '2')

устанавливая русскую и английскую раскладки.
В .vimrc (vim-xkbswitch установлен через Vundle):

let g:XkbSwitchEnabled = 1
let g:XkbSwitchLib = '/usr/local/lib/libxkbswitch.dylib'
let g:XkbSwitchIMappings = ['ru']
let g:XkbSwitchDynamicKeymap = 1
let g:XkbSwitchKeymapNames = {'1' : 'russian-jcukenwin'}

set keymap=russian-jcukenwin
set iminsert=0
set imsearch=0

Что ещё я упускаю? Не работает ни автомаппинг, ни возврат к предыдущей раскладке при выходе из Insert-mode.

Появление ошибок во время открытия файла

Здраствуйте. Очень благодарен вам за плагин. Довольно долгое время он работал бесперебойно, но некоторое время назад я столкнулся с багом (?). Случилось это когда я переписывал конфиг для nvim (версия 0.6.0). Некоторое время он отказывался работать вовсе, но я всё же как-то его настроил и он работает. Сейчас при открытии любых файлов выбивает ошибки. Пробовал создать отдельный конфиг с только вашим плагином и результат не очень изменился, точнее совсем не изменился. Приложил скриншот ошибок (не всех, но они там почти не отличаются, буквально несколько чуть-чуть других ошибок если понадобится и их приложу).
pic-full-211227-2142-57
Содержание конфигурации плагина:
Plug 'lyokha/vim-xkbswitch' let g:XkbSwitchEnabled = 1 let g:XkbSwitchLib = "/usr/lib/libxkbswitch.so" let g:XkbSwitchNLayout = 'us' let g:XkbSwitchIMappings = ['ru, uk, us']
Пробовал наверное все возможные конфигурации плагина, но только с этими он работал (могу для точности проверить не ошибся ли я если нужно).
Постарался дать столько информации сколько могу, надеюсь она будет полезна

При работе через ssh vim падает с SIGSERV

Шаги для повторения:

  • включить плагин;
  • зайти под ssh на машину;
  • включить vim;
  • перейти в режим вставки;

Первопричина, видимо, в либе xkb-switch.so, но всё же неприятно.

Очевидно, что через xkb-switch по ssh никак работать не будет, но хотя бы падать оно не должно.

Switch layout when in normal mode

First, thank you for the great plugin! It is the real life-changer when you need to edit multilingual text.

I wonder, is there a way to switch layout when in normal mode? Occasionally, I realize that I need to switch all key maps to another language when in normal mode. Now I enter insert mode, switch the layout and then switch back to the normal mode. That sequence is time-consuming. Is it possible to replace that sequence above by a key combination somehow?

Discussion: Why do I need this plugin if I have `&keymap`?

Hello @lyokha,

I encountered your plugin while I saw it's extension on airline and I'm very impressed by it's features and documentation but I'm not sure I totally understand why would I need it.

Up until now, I used the vanilla &keymap setting of Vim and it was always enough for me. It even provides assistance in Normal mode as your plugin suggests to provide it as well (haven't succeeded yet in configuring it on my machine and with il keyboard layout).

One feature though which seems to be very promising is Custom keyboard layout switching rules. Vanilla Vim doesn't provides it I'm sure.

What am I missing?

не получается заставить работать на Mac OS 10.10.2

установил Input Source Switcher - проверил, работает - issw в терминале переключает язык.
прописал в .vimrc
let g:XkbSwitchEnabled = 1
let g:XkbSwitchLib = '/usr/local/lib/libInputSourceSwitcher.dylib'

запустил vim - не работает авто переключение на US раскладку.
Из всех протестированных вариантов сработало только
let g:XkbSwitchILayout = 'ru'
При входе в vim в инсерт режим - включался русский, при выходе по Esc включался английский, при входе обратно в инсерт - опять русский.
Убираю эту строчку, и ничего не работает - автопереключение не срабатывает.

если оставляю вышесказанную строчку и добавляю
let g:XkbSwitchNLayout = 'us'
то при переключении в инсерт - русский переключается, и при выходе остается. Если включить принудительно английский, то при следующем заходе в инсерт на русский уже не переключается.

Хотелось бы, чтобы заработало так - при нормал режиме всегда был английский, при инсерт режиме, тот язык, который был включен последним в этом режиме.

Спасибо.

Only switching when going back to normal

Really cool idea! Is there a way to not switch back to last active layout when going back to insert/select modes? I want to only switch back to us automatically when going to normal. Ideally I would like to set this on a per-buffer basis with aucmd Filetype or custom mappings. Is this possible?

Локализованные хоткеи в Gvim в Ubuntu

По хоткею "< C-N >v" у меня стоит NerdTree. Плагин создаёт локализованный хоткей "< C-N >м". Однако моя убунта посылает "< C-рус.Т >м" и NerdTree не запускается

$ uname -a
Linux dxp-7750G 3.2.0-40-generic #64-Ubuntu SMP Mon Mar 25 21:22:10 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

Смена расскладки при r{char}

Иногда возникает необходимость исправить одну букву в строке и я использую для этого комманду r{char}. При этом смена раскладки не происходит. Хотелось бы иметь такую фичу.

Time lag when switching to normal mode with russian layout

When i switch to normal mode (by pressing esc) from insert mode with russian layout not switched to english there is a short but unpleasant time lag (about one second) before i can use normal mode command (not switching to english manually).

I use Ubuntu 18.04 LTS with i3-wm, PC: thinkpad yoga s1

[question] how to change input method in insert mode?

sorry for my disturbance!

in insert mode, i press
<c-o>:call system('g3kb-switch -s libpinyin')<CR>
(libpinyin is an input method)

the input method don't change. but when i quit the insert mode, it change to libpinyin in normal mode...

i know SuperSpace can switch input method. but i want a method to change it in vim.
image

thanks!

Не работает в ArchLinux

ArchLinux, VIM.

Выставил:

let g:XkbSwitchEnabled = 1 
let g:XkbSwitchLib = '/usr/lib/libxkbswitch.so' 
let g:XkbSwitchIMappings = ['ru']

$ xkb-switch -l 
us
ru

Перезапускаю VIM.

  1. Вхожу в режим редактирования,
  2. Включаю русский
  3. Выхожу из режима редактирования не переключая языка

Пытаюсь сделать хоть что-то dd не пашет, двоеточие не пашет. Но при этом в режиме вставки работают горячие клавиши. Например, ctrl+t, что в русской, что в английской раскладке сдвигает текст.

vim --version: https://gist.github.com/petRUShka/8fc456fedcd2d4ac3aa2
Версия xkb-switch -- последняя из git: 20130407

g:XkbSwitchILayout and g:XkbSwitchNLayout

При установке этих переменных одновременно работает, только первая из установленных.
let g:XkbSwitchILayout = 'us(dvp)'
let g:XkbSwitchNLayout = 'us(dvp)'

How to use vim-xkbswitch with i3wm?

Began using i3wm, configured switching keyboard layout with this i3 config:

exec --no-startup-id setxkbmap -layout us,ru
exec --no-startup-id setxkbmap -option 'grp:shifts_toggle'

If I get this correctly, each time i3 starts those two setxkbmap commands are executed. Except now vim-xkbswitch does not switch keyboard layout while changing modes. I understand everything that contains xkb in it very poorly. Where can I look for help? Maybe there are solutions for aligning i3wm and xkbswitch?

Keymap assistance in Normal mode not working

r and f commands not working with configuration from readme:

let g:XkbSwitchAssistNKeymap = 1    " for commands r and f
let g:XkbSwitchAssistSKeymap = 1    " for search lines

XkbSwitchAssistNKeymap -> not working
XkbSwitchAssistSKeymap -> working, but have deprecation messages when vim started

tried with:

set keymap=russian-jcukenwin
set iminsert=0
set imsearch=0

and

let g:XkbSwitchDynamicKeymap = 1

Cannot switch layout while searching + cannot use shortcuts with modifier keys in insert mode

Поставил вчера Ваш плагин в Ubuntu 19.10 на X11. Все отлично, пока не могу разобраться с двумя вещами. То ли я чего-то не пойму, то ли этого функционала нет.

  1. Чтобы при поиске (/) автоматом переключалась раскладка, настроил Keymap Assitance по документации. Работает, но одна проблема: когда нахожусь уже в строке поиска, не могу переключить раскладку. Например, если в инсерт-моде печатал на русском, то когда выхожу в нормал-мод и жму поиск (/), то я опять печатаю на русском. Отлично. Но тут понимаю, что мне нужно искать по-английски (в тексте имеются слова на обоих языках). Жму переключалку (в моем случае - win+space), продолжает печатать в строке поиска по-русски. Но зато после нажатия escape в нормал-моде раскладка оказывается русской. Это баг? Или я чего-то недонастроил?

  2. В инсерт-моде с русской раскладкой не работают шорткаты с control-клавишей. Скажем, всплывает менюшка автодополнения, но я не могу ничего в ней выбрать с помощью и .

Не работает на Ubuntu 16.04

Здравствуйте! На свежеустановленную Ubuntu 16.04 только поставил vim. Никаких плагинов для vim-а нет. Сделал все по инструкции, собрал xkb-switch, скопировал плагин в (~/.vim/plugin, ~/.vim/doc, ~/.vim/xkbswitch.tr). Прописал в ~/.vimrc следующее:

let g:XkbSwitchEnabled = 1 
let g:XkbSwitchLib = '/usr/lib/libxkbswitch.so' 
let g:XkbSwitchIMappings = ['ru']

И не работает.
Попробовал:

$ xkb-switch -l 
us
ru

В vim-е переключается с русской на английскую:

:call libcall('/usr/lib/libxkbswitch.so', 'Xkb_Switch_setXkbLayout', 'us')

также:

:echo g:XkbSwitchEnabled
> 1

:echo g:XkbSwitchLib
> /usr/local/lib/libxkbswitch.so

:echo g:XkbSwitchIMappings
> ['ru']

:echo libcall('/usr/local/lib/libxkbswitch.so', 'Xkb_Switch_getXkbLayout', '')
> ru

Подскажите пожалуйста, что можно сделать?

Can't restore Normal mode keyboard layout when leaving search '/' mode

Добрый день!
Не получается настроить чтобы в нормальном режиме после выхода из поиска восстанавливалась английская раскладка, то есть сценарий такой:
в нормальном режиме, раскладка 'us'
нажимаю '/' для поиска
переключаю раскладку на 'ru' и ввожу русские символы,
затем нажимаю 'enter' vim находит текст и возвращается в нормальный режим
далее в нормальном режиме раскладка остается 'ru', а хотелось бы чтобы она автоматом возвращалась на 'us', как это происходит при выходе из insert mode.

ubuntu 22.04.01
gvim 8.2.4919

gdbus call --session --dest org.gnome.Shell --object-path /org/g3kbswitch/G3kbSwitch --method org.g3kbswitch.G3kbSwitch.List
(true, '[{"key":"0","value":"us"},{"key":"1","value":"ru"}]')

.vimrc:

let g:XkbSwitchEnabled = 1 
let g:XkbSwitchIMappings = ['ru']
let g:XkbSwitchNLayout = 'us'
let g:XkbSwitchAssistSKeymap = 1
let g:XkbSwitchLib = '/usr/local/lib/libg3kbswitch.so'

Возможна ли автоматическая смена раскладки в зависимости от языка текста вокруг курсора?

Узнал из документации, что имеется возможность настройки автоматического переключения раскладки на основе указания синтаксических правил в переменной g:XkbSwitchSyntaxRules.

Но возник вопрос.
Возможно ли автоматическое переключение языка раскладки, при входе в режим вставки, в зависимости от языка самого текста, который окружает текущее положение курсора?

Было бы удобно иметь уже включенной ту раскладку, которая соответствует текущему языку окружающего текста. Чтобы не затрачивать время на ручное переключение.

mapping duplicate for script local mapping

If the original mapping uses, say, a script local function nnoremap ; :<c-u>call <sid>function()<cr>, then the duplicate mapping, say ö, does not work because the script local SID is no longer correct that where the duplicate mapping is defined.
Could patch 8.2.4861 resolve this?

Disable dot (repeat last command) in non-english layouts in normal mode

In other-than english layout (for example in Russian) dot may be on unusual place. For example for Russian layout / key (which in English layout start search) is .. So when you want to make search and have by accident Russian layout instead of English you face dot command instead of search. Last can be pretty destructible: delete couple of lines or insert some non sense and etc.

Idea is to have an option to disable or remap . in non-english layout to avoid such unexpected and annoying behavior.

XkbSwitchIMappings does not work with Meta-mappings

The XkbSwitchIMappings appears to ignore existing insert-mode mappings with Meta (Alt). I'm not sure there's a way to fix this though: I have not been able to get cyrillic meta mappings to work at all, neither in normal nor in insert.

Oh this of course only applies to console vim with terminal configured to send for alt-combos as per ECMA-35, which is needed if you want to use Unicode. I have no idea how the plugin works with regular, 8th-bit meta (do you want me to test?)

Cause lagging in vim

I used this plugin for a long time, but after I updated some other plugins, vim starts to lagging very hard(scrolling, moving cursor, etc). To research this problem, I turn off plugins one by one and it looks like xkbwitch cause of the problem. Don't know how updating of other plugins could break xkbswitch.

"No mappings found" error

Hi.

I am using vim 8 under windows 10.

Here is my config:

let g:XkbSwitchEnabled = 1
let g:XkbSwitchIMappings = ['ru']
let g:XkbSwitchIMappingsSkipFt = ['tex']
let g:XkbSwitchNLayout = 'US'
let g:XkbSwitchILayout = 'US'

When I am starting vim I constantly see this error message, duplicated many times.

...
No mappings found
No mappings found
No mappings found
No mappings found
...

Could you, pls, tell me how to avoid this?

Bspwm Support

I'm currently using the plugin on elementary OS 6.1 (based on Ubuntu focal) stripped of DE, with bspwm in place. I can't however get the plugin to work. presumably it has to do with the GUI, given that you've referenced linux and the i3 variant too.

Current configuration

let g:XkbSwitchEnabled = 1
let g:XkbSwitchLib = '/usr/local/lib/libxkbswitch.so'
let g:XkbSwitchIMappings = ['ru']

restore keyboard layout on vim exit

I just installed the plugin and it works really nicely. Just one thing, I haven't figured out how to do, is: How can I restore my original key map as opposed to the normal mode one, when exiting vim.

I use swiss layout for typing text and us for vim normal mode. So I'd like vim to go back swiss layout, once I exit vim, as opposed to staying us. Is there any way to do that?

Не находит бинарник xkb-switch

        use {↲                                                                                                                           
           'lyokha/vim-xkbswitch',↲                                                                                                     
           config = function()↲                                                                                                         
             vim.g.XkbSwitchEnabled = 1vim.g.XkbSwitchIMappings = { 'ru' }↲                                                                                       
             vim.g.XkbSwitchLib = '/run/current-system/sw/bin/' --или
             vim.g.XkbSwitchLib = '/run/current-system/sw/bin/xkb-switch' end,↲                                                                                                                        
        }
    λ which xkb-switch
    /run/current-system/sw/bin/xkb-switch

Libcalls to `libxkbswitch` don't work properly

Disclaimer

The issue is very weird and I completely understand and acknowledge its weirdness, I also assume there could be something terribly wrong with my setup, however despite my thorough trials I couldn't figure out the root cause, so decided to ask for an advice here.

Issue

vim-xkbswitch plugin doesn't switch the layout when exiting to normal mode (from insert). For instance: I start Vim, go into insert mode, switch layout to Russian and type some text, press Esc to return to normal: layout doesn't change. What's weird: if I manually switch back to English and repeat the procedure: go to insert, type something, exit to normal again --- then the layout gets switched (but back to Russian, since I already was in English after manual switch, so it just inverts the layout).

Sounds crazy, but basically layout switch works only on the second call.

Troubleshooting

I have tried to remove all plugins and configurations from my .vimrc, only leave the minimal few lines to enable vim-xkbswitch, removed xxkb, changed Xkb settings to simplest possible setup setxkbmap -layout 'us,ru' even though I usually have more complicated configuration and 3 layouts.

But the issue persisted: libcall to libxkbswitch switched the layout only on the second call, so the plugin messes up and gets completely confused. At the same time console utility (xkb-switch) works as expected and successfully switches layouts with just one call. That's the reason why I decided to open issue here instead of xkb-switch repo, as the issue actually happens only when I use it through Vim.

I went down to just manually perform the libcall from Vim console like so:

:call libcall(g:XkbSwitchLib, Xkb_Switch_setXkbLayout, 'ru')

And again nothing happens on the first call, only when I repeat this command for the second time, the layout actually changes (same when I use this command to switch back to English).

I even tried to remove the plugin and Vundle completely, and just paste the code from your article straight into .vimrc, but the behavior is the same.

For now I could only workaround the issue by literally duplicating all set calls to Xkb in the plugin --- then it works.

Debug info

OS: Arch Linux (of course everything is updated to latest versions).

$ pacman -Qi xkb-switch-git
Name            : xkb-switch-git
Version         : 20150826-4
...
$ pacman -Qi libxkbcommon-x11 
Name            : libxkbcommon-x11
Version         : 0.6.1-1
...
$ vim --version
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Aug  2 2016 05:21:06)
Included patches: 1-2143
Compiled by Arch Linux
Huge version with GTK2 GUI.
...

Please let me know if there's any other useful debug info I can provide. If only I could debug the libcall to Xkb in detail to see what's actually going on, but I don't know how, and strace on xkb-switch itself wouldn't help, as the command line utility works fine: it's only libcall from Vim that misbehaves.

Thank you!

SELECT -> INSERT modes layout improvement

Is it possible to implement following:

  1. INSERT mode layout - 'EN';
  2. Switch to SELECT mode. SELECT mode layout is 'EN';
  3. Select some text in select mode;
  4. Switch layout to 'RU'';
  5. Type some text, selected text begin replaced with typed;
  6. When I start typing - vim switch to INSERT mode and layout automatically switched to 'EN'. This is very inconvenient, natively I think, that layout is 'RU';

So, is it possible to combine SELECT and INSERT mode layouts, and do not switch layout, when switching between this modes?

vim-xkbswitch does not remember the layout

When exit and return to Insert, layout is not remembered. If I write in Russian in Insert, then press Esc and exit to Normal, the layout changes to English, as it should. But when I go back to Insert, the layout does not change back to Russian and stays English.

xkb-switch triggered by neoclide Coc documentation float window

Hello,

thank you for your amazing plugin. It has solved elegantly a problem that I had since I have started to learn to use Vim with qwerty keyboard, but typing with french bépo layout.

I have one question : in insert mode, layout switches from my locale (fr(bepo) in my case) to us layout, when a documentation float window is triggered by Neoclide Coc Intellisense-like plugin.

cfv https://github.com/neoclide/coc.nvim, and screen captures on https://www.reddit.com/r/neovim/comments/b1pctc/float_window_support_with_cocnvim/ to see how it looks like.

It sticks to us layout after the float window disappear, so I end up typing in qwerty instead of bépo whenever I hit some autocompletion trigger.

Is there a known workaround ?

this is an excerpt of a vim log, but feel free to close issue if appropriate as is really a borderline case.

chdir(/home/evoludigit/code/project)
Executing InsertEnter Autocommands for "*"
autocommand let s:XkbSwitchLastIEnterBufnr = bufnr('%') | call <SID>xkb_switch(1)

Executing InsertEnter Autocommands for "*"
autocommand call s:Autocmd('InsertEnter', +expand('<abuf>'))

Executing InsertEnter Autocommands for "*"
autocommand match ExtraWhitespace /\s\+\%#\@<!$/    
-- INSERT --
Executing CursorMovedI Autocommands for "*"
autocommand call s:Autocmd('CursorMovedI', +expand('<abuf>'), [line('.'), col('.')])

Executing CursorMovedI Autocommands for "*"
autocommand call s:Highlight_Matching_Pair()

Executing CursorMovedI Autocommands for "<buffer=1>"
autocommand call SemshiCursorMoved(line('w0'), line('w$'))

Executing User Autocommands for "AirlineModeChanged"
autocommand call airline#mode_changed()

chdir(/home/evoludigit/code/project)
chdir(tests/entrypoints)
chdir(/home/evoludigit/code/project)
chdir(/home/evoludigit/code/project)
chdir(tests/entrypoints)
chdir(/home/evoludigit/code/project)
chdir(/home/evoludigit/code/project)
chdir(tests/entrypoints)
chdir(/home/evoludigit/code/project)
chdir(/home/evoludigit/code/project)
Executing CursorHoldI Autocommands for "*"
autocommand call s:Autocmd('CursorHoldI', +expand('<abuf>'))

chdir(/home/evoludigit/code/project)
chdir(tests/entrypoints)
chdir(/home/evoludigit/code/project)
chdir(/home/evoludigit/code/project)
chdir(tests/entrypoints)
chdir(/home/evoludigit/code/project)
Executing InsertCharPre Autocommands for "*"
autocommand call s:Autocmd('InsertCharPre', v:char)

airline: group: airline_error already done, skipping
airline: group: airline_error_bold already done, skipping
airline: group: airline_error_red already done, skipping
airline: group: airline_warning already done, skipping
airline: group: airline_warning_bold already done, skipping
airline: group: airline_warning_red already done, skipping
airline: group: airline_c already done, skipping
airline: group: airline_c_bold already done, skipping
airline: group: airline_c_red already done, skipping
airline: group: airline_term already done, skipping
airline: group: airline_term_bold already done, skipping
airline: group: airline_term_red already done, skipping
Executing User Autocommands for "AirlineModeChanged"
autocommand call airline#mode_changed()

chdir(/home/evoludigit/code/project)
chdir(tests/entrypoints)
chdir(/home/evoludigit/code/project)
chdir(/home/evoludigit/code/project)
chdir(tests/entrypoints)
chdir(/home/evoludigit/code/project)-- INSERT --
Executing CursorMovedI Autocommands for "*"
autocommand call s:Autocmd('CursorMovedI', +expand('<abuf>'), [line('.'), col('.')])

Executing CursorMovedI Autocommands for "*"
autocommand call s:Highlight_Matching_Pair()

Executing CursorMovedI Autocommands for "<buffer=1>"
autocommand call SemshiCursorMoved(line('w0'), line('w$'))

Executing TextChangedI Autocommands for "*"
autocommand call s:Autocmd('TextChangedI', +expand('<abuf>'), {'lnum': line('.'), 'col': col('.'), 'pre': strpart(getline('.'), 0, col('.') - 1), 'changedtick': b:changedtick})

Executing TextChangedI Autocommands for "*"
autocommand call s:Highlight_Matching_Pair()

Executing TextChangedI Autocommands for "<buffer=1>"
autocommand call SemshiTextChanged()

Executing FuncUndefined Autocommands for "SemshiTextChanged"
autocommand call remote#define#FunctionBootstrap("python3", "/home/evoludigit/.config/nvim/plugged/semshi/rplugin/python3/semshi:function:SemshiTextChanged", v:false, "SemshiTextChanged", {}, "RPC_DEFINE_AUTOCMD_GROUP_6")

Off Topic Feature Request: pentadactyl port?

First of all I'd like to say how useful your plugin is, very interesting
indeed! I also find it would be very useful in Pentadactyl since the mode
changing workflow is much like vim's. Is there such possibility?

Unexpected output to textarea

Доброго времени суток. Терминале xfce4 при открытии vim выводиться(в место где мы привыкли видеть файл) следующая строка: /khaser/build/xkb-switch/src/XKeyboard.cpp:110: raw layout string "us,ru". Причём сам файл не меняется и, если развернуть терминал на всё окно, то надпись пропадёт. В tty проблема пропадает. Пробовал просто скомпилировать xkb-switch без этого вывода в cerr, но тогда вообще всё ломается.

В некоторых типах файлов слетают русские буквы Ж,Б,Ю

Проблема выявлена на типах файлов .md и .txt.

Сценарии: 1 Создал новый файл -- буквы на месте. Сохранил как a.txt -- буквы на месте. Выхожу из vim, снова захожу в vim, открываю a.txt -- теперь нельзя вводить буквы "ж", "б" и "ю" на любых регистрах, вместо них символы из английской раскладки.
2. Создал новый файл, Сохранил как a.cpp. Вышел-зашёл в vim, открыл этот файл -- все буквы вводятся нормально.

Если удалить данный плагин, или dll которую он использует, то описанного не наблюдается.

Vim-xkbswitch conflicts with delimitMate

DelimitMate - this is a very popular plugin for automatically closing pairs of chars (', ", [, () and it does other realted stuff.

I was trying to install it and find out that delimitMate cause insertion chars ', [ and ]instead of э, х and ъ resprectively. When I troubleshooted that problem I found out that without vim-xkbswitch being loaded this plugin works without errors.

Is it problem of vim-xkbswitch or delimitMate itself?

By the way here is realated issue from delimitMate's repository, hope it helps maybe Raimondi/delimitMate#13

Sway support

@grwlf is it really complicated issue to add Wayland switching? E.g for sway.
The interface is similar to xkb and could be invoke with sway-msg from vim.

Ошибка, если не выставлена g:XkbSwitchEnabled

Если до загрузки плагина не выставлена переменная g:XkbSwitchEnabled, vim выдаёт ошибку:

Обнаружена ошибка при обработке /home/petrushka/Dropbox/dotfiles/yadr/.yadr/vim/bundle/vim-xkbswitch/plugin/xkbswitch.vim:
строка  241:
E121: Неопределенная переменная: g:XkbSwitchEnabled
E15: Недопустимое выражение: g:XkbSwitchEnabled

Видимо, нужен какой-то обработчик на случай, если плагин установлен, но не используется.

Кроме того, если g:XkbSwitchEnabled будет установлен слишком поздно (например, после инициалзиации плагина), то плагин не "подсосёт" его значение. Видимо, об этом тоже стоит предупредить.

Question. How can I get current layout?

Recently I switched from airline to lualine and I miss ability to see my layout right next to my current mode.
I thought I can add it by myself, but I cannot find how can I get current layout from this plugin

[feature] Extract keybindings

How about extracting ability to setup some keybindings like

    for hcmd in ['gh', 'gH', 'g<C-h>']
        exe "nnoremap <buffer> <silent> ".hcmd.
                    \ " :call <SID>xkb_switch(1, 1)<CR>".hcmd
    endfor

out of this plugin? As it was done in vim-surround or in other way:

if !exists("g:surround_no_mappings") || ! g:surround_no_mappings
  nmap ds  <Plug>Dsurround
  nmap cs  <Plug>Csurround
  nmap ys  <Plug>Ysurround
  nmap yS  <Plug>YSurround

So user could replace them or disable. Cause I use all those mappings like gh, gH, g for my own purposes. They are too consistent with hjkl navigation))

Mapping for Alt-o?

I realized that this commands doesn't work in russian layout.

When I press Alt-o or Alt-O in english it gives me new line and stay in insert mode, but in russian layout this doesn't happen.

Shouldn't it be mapped automatically?

Windows 10, gvim/nvim-qt, stopped working - how to debug/diagnose?

Hi.

It stopped working few days ago and I don't know why. En/Ru layouts, Alt-Shift to switch between them. Steps to reproduce:

  • go to insert mode
  • switch to Russian
  • type
  • ESC
  • Russian layout is still active

I did plugins update around that time, so I rolled back to 0.15, but it didn't help.

I have Bitdefender Security Endpoint Antivirus software and it caused issues for me in the past with other software, like blocking silver searcher. I can imagine that it somehow prevents DLL to do layout switch.

Could you tell if there is a way to debug/diagnose what happens?

Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.