Coder Social home page Coder Social logo

zsh-autopair's Introduction

Made with Doom Emacs MIT License ZSH 5.0.2+ Build Status

zsh-autopair

A simple plugin that auto-closes, deletes and skips over matching delimiters in zsh intelligently. Hopefully.

NOTE: zsh-autopair is untested for versions of Zsh below 5.0.2. Please report any issues you have in earlier versions!

Specifically, zsh-autopair does 5 things for you:

  1. It inserts matching pairs (by default, that means brackets, quotes and spaces):

    e.g. echo | => " => echo "|"

  2. It skips over matched pairs:

    e.g. cat ./*.{py,rb|} => } => cat ./*.{py,rb}|

  3. It auto-deletes pairs on backspace:

    e.g. git commit -m "|" => backspace => git commit -m |

  4. And does all of the above only when it makes sense to do so. e.g. when the pair is balanced and when the cursor isn't next to a boundary character:

    e.g. echo "|"" => backspace => echo |"" (doesn't aggressively eat up too many quotes)

  5. Spaces between brackets are expanded and contracted.

    e.g. echo [|] => space => echo [ | ] => backspace => echo [|]

Table of Contents

Install

Download and source autopair.zsh

if [[ ! -d ~/.zsh-autopair ]]; then
  git clone https://github.com/hlissner/zsh-autopair ~/.zsh-autopair
fi

source ~/.zsh-autopair/autopair.zsh
autopair-init

Hoembrew

brew install zsh-autopair

# Add to .zshrc
source $HOMEBREW_PREFIX/share/zsh-autopair/autopair.zsh

Antigen

antigen bundle hlissner/zsh-autopair

zgen

if ! zgen saved; then
    echo "Creating a zgen save"

    # ... other plugins
    zgen load hlissner/zsh-autopair

    zgen save
fi

zplug

Load autopair after compinit, otherwise, the plugin won't work.

zplug "hlissner/zsh-autopair", defer:2

Homebrew

For Homebrew users, you can install it through the following command

brew install zsh-autopair

Then source it in your .zshrc

source $(brew --prefix)/share/zsh-autopair/autopair.zsh

Oh My Zsh

  1. Clone this repository into $ZSH_CUSTOM/plugins (by default ~/.oh-my-zsh/custom/plugins)

    git clone https://github.com/hlissner/zsh-autopair ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autopair
  2. Add the plugin to the list of plugins for Oh My Zsh to load (inside ~/.zshrc):

    plugins=(
        # other plugins...
        zsh-autopair
    )
  3. Start a new terminal session.

Configuration

zsh-autopair sets itself up. You can prevent this by setting AUTOPAIR_INHIBIT_INIT.

Options:

  • AUTOPAIR_BETWEEN_WHITESPACE (default: blank): if set, regardless of whether delimiters are unbalanced or do not meet a boundary check, pairs will be auto-closed if surrounded by whitespace, BOL or EOL.

  • AUTOPAIR_INHIBIT_INIT (default: blank): if set, autopair will not automatically set up keybinds. Check out the initialization code if you want to know what it does.

  • AUTOPAIR_PAIRS (default: ('`' '`' "'" "'" '"' '"' '{' '}' '[' ']' '(' ')' ' ' ' ')): An associative array that map pairs. Only one-character pairs are supported. To modify this, see the "Adding/Removing pairs" section.

  • AUTOPAIR_LBOUNDS/AUTOPAIR_RBOUNDS (default: see below): Associative lists of regex character groups dictating the 'boundaries' for autopairing depending on the delimiter. These are their default values:

    AUTOPAIR_LBOUNDS=(all '[.:/\!]')
    AUTOPAIR_LBOUNDS+=(quotes '[]})a-zA-Z0-9]')
    AUTOPAIR_LBOUNDS+=(spaces '[^{([]')
    AUTOPAIR_LBOUNDS+=(braces '')
    AUTOPAIR_LBOUNDS+=('`' '`')
    AUTOPAIR_LBOUNDS+=('"' '"')
    AUTOPAIR_LBOUNDS+=("'" "'")
    
    AUTOPAIR_RBOUNDS=(all '[[{(<,.:?/%$!a-zA-Z0-9]')
    AUTOPAIR_RBOUNDS+=(quotes '[a-zA-Z0-9]')
    AUTOPAIR_RBOUNDS+=(spaces '[^]})]')
    AUTOPAIR_RBOUNDS+=(braces '')

    For example, if $AUTOPAIR_LBOUNDS[braces]="[a-zA-Z]", then braces ({([) won't be autopaired if the cursor follows an alphabetical character.

    Individual delimiters can be used too. Setting $AUTOPAIR_RBOUNDS['{']="[0-9]" will cause { specifically to not be autopaired when the cursor precedes a number.

Adding/Removing pairs

You can change the designated pairs in zsh-autopair by modifying the AUTOPAIR_PAIRS envvar. This can be done before initialization like so:

typeset -gA AUTOPAIR_PAIRS
AUTOPAIR_PAIRS+=("<" ">")

Or after initialization; however, you'll have to bind keys to autopair-insert manually:

AUTOPAIR_PAIRS+=("<" ">")
bindkey "<" autopair-insert
# prevents breakage in isearch
bindkey -M isearch "<" self-insert

To remove pairs, use unset 'AUTOPAIR_PAIRS[<]'. Unbinding is optional.

Troubleshooting & compatibility issues

zgen & prezto compatibility

Prezto's Editor module is known to reset autopair's bindings. A workaround is to defer autopair from initializing (by setting AUTOPAIR_INHIBIT_INIT=1) and initialize it manually (by calling autopair-init):

source "$HOME/.zgen/zgen.zsh"

# Add this
AUTOPAIR_INHIBIT_INIT=1

if ! zgen saved; then
    zgen prezto
    # ...
    zgen load hlissner/zsh-autopair 'autopair.zsh'
    #...
    zgen save
fi

# And this
autopair-init

text on right-side of cursor interfere with completion

Bind Tab to expand-or-complete-prefix and completion will ignore what's to the right of cursor:

bindkey '^I' expand-or-complete-prefix

This has the unfortunate side-effect of overwriting whatever's right of the cursor, however.

zsh-autopair & isearch?

zsh-autopair silently disables itself in isearch, as the two are incompatible.

Midnight Commander

MC hangs when zsh-autopair tries to bind the space key. This also breaks the MC subshell.

Disable space expansion to work around this: unset 'AUTOPAIR_PAIRS[ ]'

Other resources

  • Works wonderfully with [zsh-syntax-highlight] and ZSH_HIGHLIGHT_HIGHLIGHTERS+=brackets, but zsh-syntax-highlight must be loaded after zsh-autopair.
  • Mixes well with these vi-mode zsh modules: surround, select-quoted, and select-bracketed (they're built into zsh as of zsh-5.0.8)
  • Other relevant repositories of mine:

zsh-autopair's People

Contributors

bmedicke avatar disarmer avatar elig0n avatar freed-wu avatar hlissner avatar letientai299 avatar mathisto avatar psprint avatar s4my avatar simono 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

zsh-autopair's Issues

Text following cursor Interferes with autocompletion

Assuming | is the cursor position:

echo $AUTOPAIR_PAIRS[|] => Tab

Expected

  • autocompletes hash table keys.

Hash completion

Actual

Trailing ] interferes with completion and no completion is done.

Workaround

This allows completion to work regardless of what's in front of the cursor:

bindkey '^I' expand-or-complete-prefix

I want a better solution though. Perhaps a combination of setopt COMPLETE_IN_WORD and _prefix completion...?

Improve backwards compatibility

zsh-autopair chokes on zsh 5.0.2 and causes a bad time, something to do with how it reads the array of delimiters during initialization (I wasn't able to note it down at the time). I'll post more about it once I find time to look into it (or fix it).

For now, autopair will disable itself in zsh < 5.0.8 with a message. That message can be disabled for now with: AUTOPAIR_INHIBIT_INIT=1

Feature request: add a function to advance cursor past all end brackets?

In some other autopairs plugins (I use https://github.com/LucHermitte/lh-brackets), there is a shortcut to exit out of all matched scopes.

e.g. if you had this function mapped to Ctrl-L:
cat ./{staging,prod{A,B|}}.{txt,zip} => Ctrl-L => cat ./{staging,prod{A,B}}|.{txt,zip}
but if you used similar to the above (adding quotes for example; now Ctrl-L would move the cursor outside the quotes):
cat "./{staging,prod{A,B|}}.{txt,zip}" => Ctrl-L => cat "./{staging,prod{A,B}}.{txt,zip}"|

So it just places the cursor just to the right of all matching brackets, however deeply nested.

Terminates zsh when typing space

I just updated to a01f074 and now every time I type a space the current shell exits. Both when space is the first character and when it follows after any other.

I update every couple of days so it should be from a recent commit. I have disabled all other zplug plugins but it still occurs. I do have a rather large .zshrc, so let me know if I should try again with a minimal config file.

$ zplug --version
2.4.1
$ zsh --version
zsh 5.4.2 (x86_64-apple-darwin17.0.0)
$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.13
BuildVersion:   17A365

As an aside: zplug's nice has been deprecated, so I'm using
zplug "hlissner/zsh-autopair", defer:2 instead. I can send you a pull request if you'd like to change it.

Edit:

b0a995a is the last commit that's working fine for me, so the bug was introduced in e3f9e30:
"Refactor & more generalized widget fallthrough #14"

For now I have pinned that commit with:
zplug "hlissner/zsh-autopair", defer:2, at:b0a995a

Dashes in _autopair-count cause fgrep to freak out

command -t "|" => Backspace causes:

$ git -t "fgrep: invalid option -- t                                                             ~
usage: fgrep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C[num]]
    [-e pattern] [-f file] [--binary-files=value] [--color=when]
    [--context[=num]] [--directories=action] [--label] [--line-buffered]
    [--null] [pattern] [file ...]

Note to self: escape them!

autopair-close doesn't work

I am running zsh 5.3, and can't seem to get the behavior in the example. When I type a quote, bracket or parenthesis by itself, a matching one appears at the end of the line. However, if I try to encapsulate existing text, nothing happens. I deleted everything from my .zshrc except zsh-autopair, and it still does not work.

Brackets added to pasted input

What would you like to know?

If i were to paste something like

if [[ -z "${DEPLOY_ENV}" ]]; then
  MY_SCRIPT_VARIABLE="Some default value because DEPLOY_ENV is undefined"
else
  MY_SCRIPT_VARIABLE="${DEPLOY_ENV}"
fi

the output ends up as

if [[ -z "${DEPLOY_ENV}" ]]; then ]]
  MY_SCRIPT_VARIABLE="Some default value because DEPLOY_ENV is undefined"
else
  MY_SCRIPT_VARIABLE="${DEPLOY_ENV}"
fi

Autopair seems to add additional brackets to what I'm pasting. Is there away curtail this behavior. I don't generally paste a lot of code snippets like that into my terminal to begin with, so it's not a big deal so I thought I'd ask. I'm not sure how terminal emulators handle pasting, but I've seen the same behavior in kitty and wezterm.

don't collapse ` | ` by itself

[ | ] and then pressing <bs> should result in [] but this is | i a test and then pressing <bs> should not result in this isa test but this is a test instead.

Invalid local array initialization

I am using zsh 5.0.8 (x86_64-apple-darwin15.0) and load zsh-auto-pair with zplug.

The error message is,

/Users/1ambda/.zplug/repos/hlissner/zsh-autopair/autopair.zsh:150: unknown file attribute: )

The code in autopair.zsh line #150 should be

// before
local l=(')', '}', ']', '>')

// should be: http://stackoverflow.com/questions/14917501/local-arrays-in-zsh
local -a l
l=(')', '}', ']', '>')

Also, autopair.zsh line #40 should be modified, otherwise it will throw the ap-next-to-boundary-p:1: number expected error

// before
local groups=(all)

// should be: 
local -a groups
groups=(all)

Thanks for making the great terminal tool :)

Autopairing of `<`

Hi,

I find the autopairing of < an inconvenience. Every time I try to do input redirection, I automatically get <> in my terminal, which is not what I want.

What's the usecase for autopairing < anyway?

Thanks for a great plugin!

autopair doesn't work with prezto

Hi there,

I recently changed from oh-my-zsh to prezto, and noticed that autopair stops working. I use zgen to manage plugins. Below is a copy of my .zshrc

# load zgen
source "${HOME}/.zgen/zgen.zsh"

# check if there's no init script
if ! zgen saved; then
  echo "Creating a zgen save"

  # # theme
  zgen prezto prompt theme 'sorin'

  # # plugins
  zgen prezto
  zgen prezto git
  zgen prezto tmux
  zgen prezto homebrew

  zgen load hlissner/zsh-autopair 'autopair.zsh'
  zgen load zsh-users/zsh-completions
  zgen load felixr/docker-zsh-completion
  zgen load zsh-users/zsh-syntax-highlighting
  zgen load zsh-users/zsh-history-substring-search

  zgen save
fi

it works once after zgen reset and zgen save, but if i reload the shell or start another it stops working.
Seen no problems with oh-my-zsh

Hi! Not about zsh-autopair at all, but about the Equestria maps you made 11 years ago

Do you happen to have any of the older versions (specifically revision 6) on your computer still? I'm looking to archive all the versions of your map (in order to help preserve MLP fandom history) and currently I don't have version 6 (I have two versions of revision 5, as well as revision 7 and of course the public revisions 1, 2, 3, 4, and 8, and so revision 6 is an annoying gap in the timeline.)

Add to Homebrew

would love to be able to install zsh-autopair with Homebrew

autopair don't work with vi-mode open

What did you expect to happen?

I'm using this script as a plugin of oh-my-zsh, but as long as I enable the vi-mode plugin, this plugin just stop working.

What actually happened?

as above

Describe your attempts to resolve the issue

No response

Steps to reproduce

  1. install oh-my-zsh
  2. install this project as plugin
  3. enable oh-my-zsh built-in plugin vi-mode

Package commit

34a90da

System Information

No response

Any way to debug the plugin?

What would you like to know?

Hi,

I've been using the plugin in Linux, and everything was working great. However, I recently switched to a Mac, and the auto-pair feature doesn't seem to be working, so I was wondering if there's a way to debug the behavior and see what's missing for my environment.

Thank you

Keymap conflicts with isearch

Bound keys cause isearch to abort. Applies to any rebound keys.

Steps to reproduce:

  1. Invoke history-*-search-* (e.g. history-incremental-pattern-search-backward)
  2. Press any of the bound keys (e.g. ")

Expected: autopairing in isearch OR stock behavior (self-insert)

Result: isearch aborts prematurely

Delete automatically created closing character on backspace

Great plugin!

Would be nice if the automatically created closing character was deleted if the opening character is removed and they don't contain anything.

Ie, if i press ", immeditaly followed by backspace i would like both " to be removed.

EDIT: I just noticed normal backspace works just fine! but i always use Ctrl + H, which does not work.

Variable localization

Hi!
I found some minor issue with autopair, it's using variable "i" for iterator, but it's not local. So it warns with WARN_CREATE_GLOBAL and may change global variable:

% setopt WARN_CREATE_GLOBAL; . ~/sh/zsh/autopair.zsh
autopair-init:5: scalar parameter i created globally in function autopair-init

If i define "local i" at line 143, it works perfectly

Not compatible with vi-mode

What did you expect to happen?

It should work with the jeffreytse/zsh-vi-mode plugin active

What actually happened?

When jeffreytse/zsh-vi-mode is active, autopairing doesn't work

Describe your attempts to resolve the issue

Removing jeffreytse/zsh-vi-mode makes autopairing work again

Steps to reproduce

I've basically copied this from your dotfiles, only with romkatv/powerlevel10k removed, so I'm not sure why it's not working

if ! zgenom saved; then
  zgenom load lukechilds/zsh-nvm
  zgenom load junegunn/fzf shell
  zgenom load jeffreytse/zsh-vi-mode
  zgenom load zdharma-continuum/fast-syntax-highlighting
  zgenom load zsh-users/zsh-completions src
  zgenom load zsh-users/zsh-autosuggestions
  zgenom load zsh-users/zsh-history-substring-search
  # zgenom load romkatv/powerlevel10k powerlevel10k
  zgenom load hlissner/zsh-autopair autopair.zsh
  zgenom save
fi

Package commit

396c38a

System Information

Arch

Auto delete delimiters with Alt + Backspace

I love this plugin so much. But one thing that sorta bothers me is this:

Typing " once gives me this "|" (where | is the cursor).

Pressing Backspace once removes both quotes.

I feel like Alt + Backspace (for removing whole word) should have the same behviour as just Backspace, which it currently doesn't. Alt + Backspace currently only removes the left ".

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.