Vim не работает backspace

Почему клавиша возврата не работает в режиме вставки?

Попытка удалить символы в режиме вставки с помощью backspace клавиши иногда не работает. backspace Иногда я могу , но иногда ничего не происходит; курсор не идет влево, и кажется, что ничего не происходит.

Я заметил это с помощью gVim в Windows. Тем не backspace менее, кажется, что работает как ожидалось при использовании Vim из терминала в большинстве систем Linux.

  1. Почему это происходит?
  2. Как заставить backspace ключ удалять символы как обычно?
  3. Это поведение задумано как функция? Другими словами: есть ли лучшие альтернативы backspace для удаления символов в режиме вставки?

tl; dr: Добавьте это в ваш vimrc, чтобы заставить backspace работать, как в большинстве других программ:

Более длинный ответ

Хотя поведение по умолчанию может быть удивительным, возврат на «не работающий» может рассматриваться как функция ; это может предотвратить случайное удаление отступа и слишком большого объема текста, ограничивая его текущей строкой и / или началом вставки.

Итак, что именно означают эти значения?

indent
Vim добавляет автоматический отступ для многих типов файлов; по умолчанию вы не можете вернуться на это; правила того, что считается «автоиндентированием», несколько неуловимы, например, если бы мы напечатали это (где █ — курсор):

Читайте также:  Обновил драйвера не работает микрофон

Backspace не будет работать.

Но если бы мы затем добавить команды и fi , и вернуться, мы которые позволили удалить отступ:

Это потому, что в первом примере Vim определил, что он должен добавить 1 уровень отступа, когда вы нажимаете Enter; но во втором примере Vim ничего не делал автоматически, это просто символы табуляции или несколько пробелов.

eol
Это должно быть наиболее очевидным, нажатие Backspace также удаляет маркеры EOL ( \n или \r\n ); если отключено, Backspace ничего не сделает, если вы попытаетесь удалить маркер EOL.

start
Это означает, что вы можете удалить только тот текст, который вы вставили с момента запуска режима вставки, и вы не можете удалить текст, который был вставлен ранее.

Итак, каковы настройки по умолчанию?

Я заметил это, используя GVIM в Windows. Backspace, кажется, работает как ожидалось при использовании VIM из терминала в большинстве систем Linux.

Причина этого в том, что многие дистрибутивы Linux поставляются с готовыми файлами vimrc, которые устанавливают некоторые общие параметры. Например, в моей системе Arch Linux у меня есть /usr/share/vim/vimfiles/archlinux.vim :

Если вы устанавливаете Vim в Windows, по умолчанию используется vimrc и gvimrc, которые поставляются с Vim по умолчанию.

По умолчанию Vim является пустым значением для backspace . Arch Linux, Debian, CentOS или $other_distro default могут отличаться.

Нормальный режим

Этот вопрос касается Backspace в режиме вставки, но позвольте мне также добавить несколько кратких замечаний о Backspace в обычном режиме.

В обычном режиме Backspace действует как h , он просто идет влево.

По умолчанию backspace будет переходить к предыдущей строке, если она находится в начале строки (как если бы она eol была внутри backspace ); Вы можете контролировать это поведение с помощью ‘whichwrap’ опции через b флаг (по умолчанию включено).

Вы также можете сделать символы возврата на обратную позицию, сопоставив их с X командой:

Источник

Клавиша Backspace не работает в Vim/vi

Я только что внесли некоторые изменения в файл .vimrc и .bash_aliases , и с этого времени я не могу удалить слова с помощью клавиши backspace.

В моем файле .vimrc есть:

И мой файл .bash_aliases имеет две строки для Vim:

В моем каталоге

/.vim нет единого плагина или script, поэтому нет никакого шанса, что этот плагин вызовет это.

/.vim/.vimrc является символической ссылкой. Фактический .vimrc файл находится в директории

/vimrc/ , которая представляет собой репозиторий git.

ОТВЕТЫ

Ответ 1

Чтобы разрешить обратное перемещение по всему в режиме вставки (включая автоматически вставленные отступы, разрывы строк и начало вставки), установите следующую опцию:

По умолчанию этот параметр пуст, не позволяя вам отступать над вышеупомянутыми вещами. Это стандартное поведение Vi.

Ответ 2

Для меня (сервер Debian, связанный с «Konsole» из другого Linux), проблемы с ключом backspace и клавишами со стрелками были решены после удаления пакета vim-small и установки пакета vim.

Ответ 3

У меня была та же проблема на Debian 7.8 над SSH в urxvt + tmux. У меня был vim и vim-tiny.

Удаление vim-tiny устраняет проблему.

Ответ 4

Много раз это также функция выбранного типа getty, если вы используете SSH-клиент, такой как Putty или некоторые из них. Наиболее предпочтительным было бы использовать vt100 +, поскольку это самая стандартная эмуляция.

У меня уже был :fixdel , который не работал. Я должен был удалить его и заменить его первым предложением, чтобы заставить его работать.

Ответ 5

Для меня у меня была настройка ниже, однако backspace все еще не работает.

Наконец, я нашел, что следующая строка привела к этой проблеме.

Когда этот параметр удаляется, клавиша backspace работает хорошо в режиме вставки.

Reason : Это потому, что Vim видит CTRL-H в качестве backspace, и эта строка делает переопределенную функцию neocomplete # smart_close_popup() в режиме вставки.

Источник

Backspace and delete problems

On some systems, you may experience problems using the backspace or delete keys. This tip discusses the causes and solutions. Generally, these problems arise on Unix-based systems because of the wide variety of hardware and software involved.

  • Following is a rough merge from some mysterious tips.
  • Need to reword and clarify what each is talking about.

Contents

Backspace key won’t move from current line [ ]

Backspace works in Insert mode (e.g. not inserting a ^?), but won’t delete over line breaks, or automatically-inserted indentation, or the place where insert mode started:

Alternately, add this to your .vimrc:

Strange characters are inserted [ ]

Backspace just puts weird characters in my file.

There’s also a bug in xterm (at least v224) that may bring other users into the same backspace problem. Here’s the link: http://bugs.gentoo.org/show_bug.cgi?id=154090.

If backspace doesn’t work properly in insert mode, e.g. inserting ‘^?’, try putting this your .bashrc:

Delete key problems [ ]

From :help :fixdel (please read all):

If your delete key terminal code is wrong, but the code for backspace is alright, you can put this in your vimrc: This works no matter what the actual code for backspace is. This is, at best, horrifically misleading. In particular, this will break things for Linux users, and for any other Unix system that has «seen the light». For most modern terminal emulators, sends ^? and sends ^[[3

— and putting :fixdel into your .vimrc will change t_kD from the correct ^[[3

to the incorrect ^H.

For many terminal emulators, Backspace will send either or , and Ctrl-Backspace will emit the other. So, if you don’t want to spend the time to fix your settings, you might be able to work around your problems using ctrl+backspace instead of backspace.

Checking for bad mappings [ ]

Your backspace key may be broken due to a bad mapping which has been loaded into Vim. This may be unintentional; Vim sees CTRL-H as a backspace (because CTRL-H is the ASCII code for a backspace), so you also cannot map anything to that. You can check if there are any mappings set, and where they came from, like this:

If you find a mapping you can try clearing it with:

If you want to create your own emergency mapping, you could try:

If you want an even more authentic mapping for a malfunctioning Backspace key, try this function:

And add put this mapping into your .vimrc:

See also [ ]

Comments [ ]

Might want to add following info somewhere in tip:

On many Linux systems, running in an xterm window:

  • Backspace key emits (8 or ^H)
  • Ctrl-Backspace key combination emits (127 or ^?)

I got it to work on my system by creating a .vimrc file in the home directory with the line: set t_kb=^? where for ^? I pressed backspace. Don’t forget to open a new terminal window after your changes in .vimrc

On some Linux systems, pressing backspace in xterm or uxterm will move the cursor left (without deleting the character). To fix, add:

To your .Xresources file and run:

Alternatively, in .vimrc, type this: «imap ^? ^H»

My terminal sends ^? for backspace and ^[[3

for delete. To get these keys working in vim like they work in other programs, I put

into my .vimrc. (Of course, using ^V and ^V to insert the characters.)

Источник

Backspace key not working in Vim/vi

I just did some changes to the .vimrc file and .bash_aliases file and from that time I can’t delete words with backspace key.

My .vimrc file has:

And my .bash_aliases file has two line for Vim:

/.vim directory doesn’t have a single plugin or script, so there’s isn’t any chance that plugin will cause this.

/.vim/.vimrc is a symlink. The actual .vimrc file is in

/vimrc/ directory which is a git repository.

9 Answers 9

To allow backspacing over everything in insert mode (including automatically inserted indentation, line breaks and start of insert) you can set the backspace option:

By default this option is empty, not allowing you to backspace over the above-mentioned things. This is the standard Vi behavior.

You can put this line to your vimrc file to have it set automatically when Vim starts:

Also, starting from Vim 8.0 if no user vimrc file is found, Vim will set backspace to this value by loading the defaults.vim script.

Like a linux-newb, I was on a fresh Ubuntu 18.04 install and my vim editor behaved differently than I was used to on the other machines I use (to include the backspace behavior you’re describing). I didn’t realize that I was actually using vi and not vim (both of which are executed with vi ).

Installing vim and then editing a file brought back the behavior I was used to, including the backspacing working like I was expecting.

Источник

Why doesn’t the backspace key work in insert mode?

Trying to delete characters in insert mode with the backspace key sometimes doesn’t seem to work. I can backspace sometimes, but at other times it does nothing; the cursor doesn’t go to the left, and absolutely nothing seems to happen.

I noticed this using gVim in Windows. The backspace seems to work as expected while using Vim from the terminal in most Linux systems however.

  1. Why does this happen?
  2. How can I make the backspace key delete characters as usual?
  3. Is this behaviour intended as a feature? In other words: are there better alternatives to the backspace to delete characters in insert mode?

5 Answers 5

tl;dr: Add this to your vimrc to make the backspace work like in most other programs:

Longer answer

Though the default behaviour may be surprising, the backspace «not working» can be considered a feature; it can prevent you from accidentally removing indentation, and from removing too much text by restricting it to the current line and/or the start of the insert.

So what do these values mean exactly?

indent
Vim adds automatic indentation for many filetypes; by default, you’re not allowed to backspace over this; the rules of what is considered to be ‘autoindentation’ are somewhat subtle, for example, if we would type this (where █ is the cursor):

Backspacing won’t work.

But if we would then add a command and the > , and go back up, we are allowed to remove the indentation:

This is because in the first example, Vim determined it should add 1 level of indentation when you pressed Enter; but in the second example, Vim didn’t autoindent anything, it’s just Tab characters or a few spaces.

eol
This should be the most obvious, pressing Backspace also removes EOL markers ( \n or \r\n ); if disabled, Backspace will do nothing if you try to delete a EOL marker.

start
This means you can only delete text that you’ve inserted since insert mode started, and you can’t delete any text that was previously inserted.

So what’s the default setting?

I noticed this using GVIM in windows. The backspace seems to work as expected while using VIM from the terminal in most Linux systems however.

The reason for this is because many Linux distro’s ship with pre-made vimrc files which set some common options. For example on my Arch Linux system I have /usr/share/vim/vimfiles/archlinux.vim with:

If you install Vim on Windows, the default is to use the default vimrc and gvimrc that Vim ships with.

The Vim default is an empty value for backspace . The Arch Linux, Debian, CentOS, or $other_distro default may be different.

Normal mode

This question is about Backspace in insert mode, but let me also add some brief remarks about Backspace in normal mode.

In normal mode, the Backspace acts as h , it just goes to the left.

By default, the backspace will go to the previous line if at the start of a line (as if eol was in backspace ); you can control this behaviour with the ‘whichwrap’ option through the b flag (enabled by default).

You can also make backspace delete characters by mapping it to the X command:

Источник

Оцените статью