Coder Social home page Coder Social logo

autoclose.nvim's Introduction

autoclose.nvim

Stargazers Issues Contributors

📃 Introduction

A minimalist Neovim plugin that auto pairs & closes brackets written in 100% Lua.

⚙️ Functions

Most functions work in both insert and command-line mode.

Auto-close

Auto-delete

(works in <BS> and <C-W>)

Auto-escape

Auto-indent

(works in <CR> and <S-CR>, only in insert mode)

⚡ Requirements

📦 Installation

  1. Install via your favorite package manager.
Plug 'm4xshen/autoclose.nvim'
use 'm4xshen/autoclose.nvim'
  1. Setup the plugin in your init.lua.
require("autoclose").setup()

🔧 Configuration

You can pass your config table into the setup() function.

Keys

The available options in keys:

  • close: If set to true, pressing the character will insert both the opening and closing characters, and place the cursor in between them.
  • escape: If set to true, pressing the character again will escape it instead of inserting a closing character.
  • pair: The string that represents the pair of opening and closing characters. This should be a two-character string, with the opening character first and the closing character second.
  • disabled_filetypes: Table of filetypes where the specific key should not be autoclosed.
  • enabled_filetypes: Only autoclose the key under these filetypes. This option takes precedence over disabled_filetypes.
  • disable_command_mode: If set to true, the character will be disabled in command-line mode.

Example: Add a $$ pair.

require("autoclose").setup({
   keys = {
      ["$"] = { escape = true, close = true, pair = "$$", disabled_filetypes = {} },
   },
})

You can also overwrite the default config.

Example: Remove the escape function of >.

require("autoclose").setup({
   keys = {
      [">"] = { escape = false, close = false, pair = "<>", disabled_filetypes = {} },
   },
})

Options

The available options in options:

  • disabled_filetypes: The plugin will be disabled under the filetypes in this table.
    • type of the value: table of strings
    • default value: { "text" }

Example: Disable the plugin in text and markdown file.

require("autoclose").setup({
   options = {
      disabled_filetypes = { "text", "markdown" },
   },
})
  • disable_when_touch: Set this to true will disable the auto-close function when the cursor touches character that matches touch_regex.

    • type of the value: boolean
    • default value: false
  • touch_regex

    • type of the value: string
    • default value: "[%w(%[{]" (alphanumeric characters or ( or [ or {)

Example:

Your current file: ( ^ points to your cursor position)

word
^

You press ( and the file will become

(word
^

It doesn't autoclose for you because your cursor touches w.

  • pair_spaces: Pair the spaces when cursor is inside a pair of keys.
    • type of the value: boolean
    • default value: false

Example:

The | is your cursor in insert mode.

import {|}

after inserting a space:

import { | }
  • auto_indent: Enable auto-indent feature

    • type of the value: boolean
    • default value: true
  • disable_command_mode: Disable autoclose for command mode globally

    • type of the value: boolean
    • default value: false

Default config

local config = {
   keys = {
      ["("] = { escape = false, close = true, pair = "()" },
      ["["] = { escape = false, close = true, pair = "[]" },
      ["{"] = { escape = false, close = true, pair = "{}" },

      [">"] = { escape = true, close = false, pair = "<>" },
      [")"] = { escape = true, close = false, pair = "()" },
      ["]"] = { escape = true, close = false, pair = "[]" },
      ["}"] = { escape = true, close = false, pair = "{}" },

      ['"'] = { escape = true, close = true, pair = '""' },
      ["'"] = { escape = true, close = true, pair = "''" },
      ["`"] = { escape = true, close = true, pair = "``" },
   },
   options = {
      disabled_filetypes = { "text" },
      disable_when_touch = false,
      touch_regex = "[%w(%[{]",
      pair_spaces = false,
      auto_indent = true,
      disable_command_mode = false,
   },
}

autoclose.nvim vs other plugins

Some plugins such as nvim-autopairs and ultimate-autopair.nvim provide a wider range of features such as fast wrap, treesitter pair checking, etc., but some users may not need all of them. If you just want the basic functionality of editing with pairs, you can use autoclose.nvim to achieve the same thing in a simpler and faster way.

autoclose.nvim's People

Contributors

andygeorge avatar driesceuppens avatar github-actions[bot] avatar hachy avatar itzaeon avatar j-ace-svg avatar m4xshen avatar telemachus avatar xxiaoa avatar zwodahs 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

autoclose.nvim's Issues

Ignore specific keys for filetype

This plugin works great and I have been using it for some time. However even with the disable_filetypes option I notice it is only certain keys I want to disable. For instance in markdown files I want to disable ' because it's part of normal grammer but () and [] are part of markdown and I want them to autoclose. Is there any current way to do this?

Add an option to not add closing half of the pair when it's next to a none whitespace character

Autoclose.nvim is convinient when I freshly type things like below.

   cursor
     |
     V 
(word|)

However I actually edit more than write I often find myself doing very inefficient editing like following.

; move the cursor to a existing word
|word

; type (
(|)word

; delete ) - this is a multiple key strokes
(|word

; put ) at the end
(word)|

I came up with a simple idea. Perhaps not adding a closing half of the pair when the cursor is "touching" the word.
So it would be nice if this plugin can offer an option like that.

Add a vim help file

All the documentation is in the readme which is not easily accessible from within nvim. If you would put the documentation in a help file you could still link to it from the readme and it could be read from within nvim after installation. This would help if I want to edit my config later on and need to look up some detail of the documentation.

Changes that use autoclose break single-repeat (dot repeat)

When a text is inserted or changed and a autocloase pair is inserted during that operation, the operation can no longer be dot repeated with . (:help single-repeat).

For example if I would like to replace the word abc with (xyz) I could move the cursor over the word, then type ciw(xyz)<ESC> and could then repeat this operation on any other abc by pressing ..

With autoclose.vim enabled I get xyzabc when repeating.

Pairing characters and strings

This is the only extension I know which pairs $ correctly in LaTeX.
However, in LaTeX we pair \[ with \] and \left( with \right), etc. How can this be accomplished here, and without interfering with the pairs ( and )?

Consider documenting a short comparison to nvim-autopairs

I was setting up nvim and looking for a lua version for closing brackets.
I found your project and nvim-autopairs (which seems more popular due to star count).

It seems like you saw a need in writing a new plugin. You could consider adding some infos to the Rradme comparing the two plugins as well as the advantages of autoclose.nvim. This would have helped me to decide which one to use.

Thank you for your work.

<CR> in insert mode does nothing

Hi, not sure what context should i provide but for some reason after installing this plugin in insert mode does nothing. I disabled all of my plugins to test if something clashes but still the same. Any ideas?

NVIM v0.8.1
Build type: Release
LuaJIT 2.1.0-beta3
Compiled by [email protected]

Features: +acl +iconv +tui
See ":help feature-compile"

   system vimrc file: "$VIM/sysinit.vim"
  fall-back for $VIM: "/opt/homebrew/Cellar/neovim/0.8.1/share/nvim"

Run :checkhealth for more info

`touch_regex` should scan the previous character as well

An example, in this situation pressing " will create a pair "":

options = {
            disable_when_touch = true*, -- * indicates a cursor
          }

However, in this one disable_when_touch will work as expected and only one " will be inserted:

options = {
            disable_when_touch = *true, -- * indicates a cursor
          }

Ignore filetypes option.

Very useful plugin!

The only issue i have is that it makes switching between markdown/plaintext files and code a bit of a pain. would love the option to ignore specific filetypes.

Add an ability to jump "outside" on hotkey

Picture this:

foo = bar(baz['blah'](b*leh{'one'{'two', 'three'}}))
                       ^
                     cursor

Now imagine you can move cursor to each closing character via, for example, Shift+Enter. Sounds cool?

Adding support for html/xml tags.

Currently when writing html, '<' autocompletes with '>'.

I was thinking of extending the plugin to autocomplete the end tag when completing the initial tag.
Eg. when typing <body>, the plugin automatically adds </body> in a new line.

Option to double space

For the sake of demonstration, I will use | to represent the cursor
Currently, when I press { it will result in this: {|}, which is expected.
However, I like to add a space before and after the content within the brackets, like this:

use { 'm4xshen/autoclose.nvim' }

Currently, If I start with {|} and press space, it results in { |}, which is not ideal, if im inside two braces and there is no content, and I press space, I'd like it to result in { | }, which I feel flows best.
Thank you for your time.

`<CR>` keybind is enabled in command mode by default

From this line https://github.com/m4xshen/autoclose.nvim/blob/main/lua/autoclose.lua#L23, I infer that the autoclose.nvim functionality should not be enabled for <CR> in command mode by default. However, it is, which messes with my config.

I am not an expert in lua, but I guess the error may be in this line https://github.com/m4xshen/autoclose.nvim/blob/main/lua/autoclose.lua#L150. Should it not read if not info.disable_command_mode then, because the disable option is set per key and not in the keys table?

Code formatter

Just a question.
Are you using a code formatter? Or are you planning to use one?

Does not work with (multibyte) UTF8 characters

Thanks again for autoclose, which is terrific and very straightforward code to read!

I tried adding a pair for curly quotes (“”), and I ran into a problem. autoclose can insert the pair okay, but escape does not work. I think that's because you use Lua's string.sub to check for the last part of the pair, and Lua's string capabilities operate on bytes rather than UTF8 characters. (I also think that my problem is somewhat related to issues #39 and #23.)

This may be a reasonable limitation to keep for this plugin, but one approach occurs to me. If the pairs were entered as (for example) "(,)", then you could potentially pick out the closing part of the pair by splitting the pair on the comma. That might be a way forward, but it may complicate the code and people would have to adjust their configurations for the breaking change. In any case, I'm happy to work on this or submit a PR if you are interested.

<BS> in signs that `[ [ ] " " " ' ' ' (() { { }` already have matched will delete both

I find something weird,
in the cases that has been already matched like [ [ ] " " " ' ' ' (() { { }, we dont want autoclose.nvim to delete both signs for us
for example:

|  <------- Cursor
#include "stdio.h"|"

as we can see, "stdio.h"|" have a pair that already matched ( "stdio.h"|), if we press <BS> at |, it will delete the both sign for us.
In this cases, we might not wish to delete both sign :D

CoC Support

I'm not sure if this is really an issue but when using this with CoC and doing a '{' and pressing enter, it does not do an indent

Backspace?

I'm trying to find a neovim autoclose plugin where I can enter a new line:

something({
...
})

and when I backspace, it goes to ({}) and once more ()

Is this possible and i'm not seeing it?

It's just thank you

I just wanted to thank you for writing such a wonderful plugin that really works, in fact this is so cool that it doesn't interfere with autocomplete and needless to say this was one of the reasons I ditched nvim-autopairs. Thanks a lot.

completely disable specific keys: `'` and `"`

Great plugin, but I don't want it to work for ' and " (actually, for any duplication of an identical key).

I tried the following:

  require("autoclose").setup({
    ["'"] = { escape = false, close = false, pair = "''"},
    ['"'] = { escape = false, close = false, pair = '""'},
  }) 

-- but they automated closing still happens.

How to completely disable specific keys?

Thanks!

ADD new move

For example:

#include "stdio.h|"               press  "                    #include "stdio.h"|
#include <stdio.h|>             press  >                   #include <stdio.h>|
etc...

Support deleting with `<C-h>`

The plugin works as expected with <BS> and <C-w>, but it doesn't acknowledge for <C-h>, which has the same functionality as <BS>.

Need ability to assign a single keybinding to all escape situations

First of all, thanks for this plugin. It works very smoothly.

I use autoclose plugins because fumble when typing ( or ) and { or }. I usually mistype them and use backspace to fix them.

I like the escape feature of the plugin but because I have to again use ) or } to escape from inside the parenthesis or curly braces it becomes a bit tedious for me.

Also I have to move my fingers to a lot to escape out of a sequence like {("|")} I have to type " ) and } to escape all the closed characters.

I would like the ability to attach the escape functionality to a keybinding which I can mindlessly press to escape out of the current closed parenthesis or quote or other supported elements.

This way it can much quicker and less tedious because I have to remember only they keybinding and I wouldn't have to move my fingers a lot.

Add versioning

Hi,

is this plugin right now in a stable phase?
If yes, would it possible to add versioning, to be sure to always have the same version installed?

Doesn't respect language layout

Intro

Hello, I love the simplicity of your plugin, thanks man

Module(s)

m4xshen/autoclose.nvim, lyokha/vim-xkbswitch

Description

  • When the Russian layout is active, it is impossible to use letters that are on the same key together with '[', ']', '{', '}', `'`, `"`, '`', '~'
    image

Error that I get:

E15: Invalid expression: <Lua 174: path/to/file.lua:157>
  • I had set up vim.opt.langmap but it didn't help
local langmap_keys = {
  'ёЁ;`~', '№;#',
  'йЙ;qQ', 'цЦ;wW', 'уУ;eE', 'кК;rR', 'еЕ;tT', 'нН;yY', 'гГ;uU', 'шШ;iI', 'щЩ;oO', 'зЗ;pP', 'хХ;[{', 'ъЪ;]}',
  'фФ;aA', 'ыЫ;sS', 'вВ;dD', 'аА;fF', 'пП;gG', 'рР;hH', 'оО;jJ', 'лЛ;kK', 'дД;lL', [[жЖ;\;:]], [[эЭ;'\"]],
  'яЯ;zZ', 'чЧ;xX', 'сС;cC', 'мМ;vV', 'иИ;bB', 'тТ;nN', 'ьЬ;mM', [[бБ;\,<]], 'юЮ;.>',
}
vim.opt.langmap = table.concat(langmap_keys, ',')

Neovim version

0.9.4

Steps to reproduce

minimal reproducing config

Using folke/lazy.nvim to manage plugins.

  • autoclose
return {
      {
        "m4xshen/autoclose.nvim", enabled = true,
        config = function()
            require("autoclose").setup({
                keys = {
                    ["$"] = { escape = true, close = true, pair = "$$", disabled_filetypes = {} },
                    ["<"] = { escape = true, close = true, pair = "<>" },
                },
                options = {
                    disabled_filetypes = { "text", "markdown" },
                    disable_command_mode = true,
                }
            })
        end
    },
  }
  • xkb-switch
return {
    "lyokha/vim-xkbswitch",
}
  • opts.lua
-- ...
vim.g.XkbSwitchEnabled = 1
vim.g.XkbSwitchIMappings = { "ru" }
-- ...
  • tmux-3.3_a-7

  • setxkbmap -print -verbose 10

Setting verbose level to 10
locale is C
Trying to load rules file ./rules/evdev...
Trying to load rules file /usr/share/X11/xkb/rules/evdev...
Success.
Applied rules from evdev:
rules:      evdev
model:      pc104
layout:     us,ru
options:    ctrl:nocaps,grp:win_space_toggle
Trying to build keymap using the following components:
keycodes:   evdev+aliases(qwerty)
types:      complete
compat:     complete
symbols:    pc+us+ru:2+inet(evdev)+ctrl(nocaps)+group(win_space_toggle):1+group(win_space_toggle):2
geometry:   pc(pc104)
xkb_keymap {
	xkb_keycodes  { include "evdev+aliases(qwerty)"	};
	xkb_types     { include "complete"	};
	xkb_compat    { include "complete"	};
	xkb_symbols   { include "pc+us+ru:2+inet(evdev)+ctrl(nocaps)+group(win_space_toggle):1+group(win_space_toggle):2"	};
	xkb_geometry  { include "pc(pc104)"	};
};

Expected behavior

file.* and active Russian keyboard layout:

Before        Input         After
------------------------------------
Лорем |         х          Лорем х
Лорем |         э          Лорем э
------------------------------------

Actual behavior

file.* and active Russian keyboard layout:

Before        Input         After
------------------------------------
Лорем |         х          Лорем *ERROR*
Лорем |         э          Лорем *ERROR*
------------------------------------

disable ` in verilog files

            require("autoclose"):setup({
                keys = {
                    ["`"] = { escape = false, close = false, pair = "``", disabled_filetypes = { "verilog" } },
                },
            })

The configuration does not take effect.

Make disable_command_mode also a global option

I'd prefer not to have autoclose enabled at all in command mode. So I now have to copy all the default keys just to disable it everywhere.

Could we get a options.disable_command_mode? It could behave like a fallback. E.g. if also set for a key it overrides whatever is set under options.

Allow Shift-Enter to trigger auto-indent

I run alacritty as my terminal, and that lets me properly map <S-CR> in the terminal by sending vim the keystrokes it expects. This causes problems with auto-indent though, as sometimes if I type quickly I'll press Shift+{, then press enter while Shift is still pressed, and then the indentation won't trigger. I tried doing inoremap <S-CR> <CR> but that didn't seem to work. Any ideas on how to solve this minor annoyance?

Interference with autocomplete/popup menus

I've just tried using this plugin and it works well for the autoclose part of it.

The downside is that it's interfering with popup menus. When selecting something from a menu, <CR> now inserts a literal newline instead of accepting the selection (both inside and outside things this plugin considers pairs). I can reliably reproduce it by adding and removing this plugin and I wondered if there was a known issue and/or a workaround before I started trying to debug what's going on?

Is there an order that plugins need to be loaded so they don't overwrite each others configs? I'm using nvim-cmp if that helps.

Add an option to only trigger auto-close when Enter is pressed.

I mainly use vim-closer, which only closes pairs when enter is pressed, which I find more useful as sometimes if I'm typing inline, I don't want the pair inserted - whereas having it inserted when enter is pressed (and then triggering auto-indent) is pretty much always useful.

This could be a global option, or maybe even enabled per-pair, depending on your preferences. I'd be simply ok with a global option, as then I could mirror my current workflow with vim-closer and move on.

Make it possible to correct close the double string like /*

I'd like to use you awesome plugin to autoclose the inline block comments in typescript/js. eg

/* this is the comment */

But when I added the config

          ["/*"] = {
            escape = true,
            close = true,
            pair = "/**/",
            enabled_filetypes = { "typescript", "typescriptreact", "javascript", "javascriptreact" }
          },

Auto pair works incorrectly because when it adds a pair cursor is moved to the last character /**{here}/ instead of /*{here}*/

Screen.Recording.2023-08-28.at.13.02.39.mov

Escape does not work after auto-indent / multiline was triggered

When auto-indent is activated it seems escaping the current section does no longer work

  • nvim test.md
  • Go to insert mode
  • Press ": you see "|" (| indicates cursor position)
  • Press <CR>: you see
    "
    |
    "
    
  • Press abc followed by ": you see
    "
    abc"|"
    "
    

I would have expected that the second " character triggers escape and I see this instead:

"
abc
"|

Or is there another way to escape the current section if you're editing a multiline text?

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.