diff --git a/vim-config/plugins/coc.nvim/.eslintignore b/vim-config/plugins/coc.nvim/.eslintignore deleted file mode 100644 index f38d5306..00000000 --- a/vim-config/plugins/coc.nvim/.eslintignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules -coverage -build -lib -typings diff --git a/vim-config/plugins/coc.nvim/.eslintrc.js b/vim-config/plugins/coc.nvim/.eslintrc.js deleted file mode 100644 index f2faedbb..00000000 --- a/vim-config/plugins/coc.nvim/.eslintrc.js +++ /dev/null @@ -1,338 +0,0 @@ -module.exports = { - "root": true, - "env": { - "es6": true, - "node": true, - "jest/globals": true - }, - "extends": [ - "plugin:@typescript-eslint/recommended", - "plugin:@typescript-eslint/recommended-requiring-type-checking" - ], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "project": "./tsconfig.json", - "sourceType": "module" - }, - "plugins": [ - "jsdoc", - "jest", - "@typescript-eslint" - ], - "rules": { - "comma-dangle": [ - 0 - ], - "guard-for-in": [ - 0 - ], - "no-dupe-class-members": [ - 0 - ], - "prefer-spread": [ - 0 - ], - "prefer-rest-params": [ - 0 - ], - "func-names": [ - 0 - ], - "require-atomic-updates": [ - 0 - ], - "no-empty": "off", - "no-console": "off", - "linebreak-style": [ - 1, - "unix" - ], - "no-prototype-builtins": [ - 0 - ], - "no-unused-vars": [ - 0 - ], - "no-async-promise-executor": [ - 0 - ], - "constructor-super": "error", - "for-direction": [ - "error" - ], - "getter-return": [ - "error" - ], - "no-case-declarations": [ - "error" - ], - "no-class-assign": [ - "error" - ], - "no-compare-neg-zero": [ - "error" - ], - "no-cond-assign": "error", - "no-const-assign": [ - "error" - ], - "no-constant-condition": [ - "error" - ], - "no-control-regex": [ - "error" - ], - "no-debugger": "error", - "no-delete-var": [ - "error" - ], - "no-dupe-args": [ - "error" - ], - "no-dupe-keys": [ - "error" - ], - "no-duplicate-case": [ - "error" - ], - "no-empty-character-class": [ - "error" - ], - "no-empty-pattern": [ - "error" - ], - "no-ex-assign": [ - "error" - ], - "no-extra-boolean-cast": [ - "error" - ], - "no-extra-semi": [ - "error" - ], - "no-fallthrough": "off", - "no-func-assign": [ - "error" - ], - "no-global-assign": [ - "error" - ], - "no-inner-declarations": [ - "error" - ], - "no-invalid-regexp": [ - "error" - ], - "no-irregular-whitespace": "error", - "no-misleading-character-class": [ - "error" - ], - "no-mixed-spaces-and-tabs": [ - "error" - ], - "no-new-symbol": [ - "error" - ], - "no-obj-calls": [ - "error" - ], - "no-octal": [ - "error" - ], - "no-redeclare": "error", - "no-regex-spaces": [ - "error" - ], - "no-self-assign": [ - "error" - ], - "no-shadow-restricted-names": [ - "error" - ], - "no-sparse-arrays": "error", - "no-this-before-super": [ - "error" - ], - "no-undef": [ - "off" - ], - "no-unexpected-multiline": [ - "error" - ], - "no-unreachable": [ - "warn" - ], - "no-unsafe-finally": "error", - "no-unsafe-negation": [ - "error" - ], - "no-unused-labels": "error", - "no-useless-catch": [ - "error" - ], - "no-useless-escape": [ - "error" - ], - "no-with": [ - "error" - ], - "require-yield": [ - "error" - ], - "use-isnan": "error", - "valid-typeof": "off", - "@typescript-eslint/no-unnecessary-boolean-literal-compare": "off", - "@typescript-eslint/no-unnecessary-type-assertion": "off", - "@typescript-eslint/prefer-string-starts-ends-with": "off", - "@typescript-eslint/prefer-regexp-exec": "off", - "@typescript-eslint/adjacent-overload-signatures": "error", - "@typescript-eslint/array-type": "off", - "@typescript-eslint/require-await": "off", - "@typescript-eslint/await-thenable": "error", - "@typescript-eslint/ban-types": "off", - "@typescript-eslint/no-unsafe-assignment": "off", - "@typescript-eslint/no-unsafe-member-access": "off", - "@typescript-eslint/no-unsafe-call": "off", - "@typescript-eslint/explicit-module-boundary-types": "off", - "@typescript-eslint/no-unsafe-return": "off", - "@typescript-eslint/no-non-null-assertion": "off", - "@typescript-eslint/restrict-plus-operands": "off", - "@typescript-eslint/restrict-template-expressions": "off", - "@typescript-eslint/consistent-type-assertions": "error", - "@typescript-eslint/consistent-type-definitions": "error", - "@typescript-eslint/explicit-member-accessibility": [ - "error", - { - "accessibility": "explicit", - "overrides": { - "accessors": "explicit", - "constructors": "off" - } - } - ], - "@typescript-eslint/interface-name-prefix": "off", - "@typescript-eslint/member-delimiter-style": "off", - "@typescript-eslint/camelcase": "off", - "@typescript-eslint/member-ordering": "off", - "@typescript-eslint/no-empty-function": "off", - "@typescript-eslint/no-empty-interface": "off", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-floating-promises": "error", - "@typescript-eslint/no-misused-promises": "off", - "@typescript-eslint/no-for-in-array": "error", - "@typescript-eslint/no-inferrable-types": "error", - "@typescript-eslint/no-misused-new": "error", - "@typescript-eslint/no-namespace": "off", - "@typescript-eslint/no-parameter-properties": "off", - "@typescript-eslint/no-unused-vars": "off", - "@typescript-eslint/no-unnecessary-qualifier": "error", - "@typescript-eslint/no-use-before-define": "off", - "@typescript-eslint/explicit-function-return-type": "off", - "@typescript-eslint/no-var-requires": "off", - "@typescript-eslint/prefer-for-of": "off", - "@typescript-eslint/prefer-function-type": "off", - "@typescript-eslint/prefer-namespace-keyword": "error", - "@typescript-eslint/quotes": "off", - "@typescript-eslint/semi": [ - "error", - "never" - ], - "@typescript-eslint/triple-slash-reference": [ - "error", - { - "path": "always", - "types": "prefer-import", - "lib": "always" - } - ], - "@typescript-eslint/unbound-method": "off", - "@typescript-eslint/unified-signatures": "error", - "arrow-body-style": "off", - "arrow-parens": [ - "error", - "as-needed" - ], - "camelcase": "off", - "complexity": "off", - "curly": "off", - "dot-notation": "off", - "eol-last": "off", - "eqeqeq": [ - "off", - "always" - ], - "id-blacklist": [ - "error", - "any", - "Number", - "number", - "String", - "string", - "Boolean", - "boolean", - "Undefined" - ], - "id-match": "error", - "jsdoc/check-alignment": "error", - "jsdoc/check-indentation": "error", - "jsdoc/newline-after-description": "error", - "max-classes-per-file": "off", - "new-parens": "error", - "no-bitwise": "off", - "no-caller": "error", - "no-eval": "error", - "no-invalid-this": "off", - "no-magic-numbers": "off", - "no-multiple-empty-lines": [ - "error", - { - "max": 1 - } - ], - "no-new-wrappers": "error", - "no-shadow": [ - "off", - { - "hoist": "all" - } - ], - "no-template-curly-in-string": "off", - "no-throw-literal": "error", - "no-trailing-spaces": "error", - "no-undef-init": "error", - "no-underscore-dangle": "off", - "no-unused-expressions": "off", - "no-var": "error", - "no-void": "off", - "object-shorthand": "error", - "one-var": [ - "error", - "never" - ], - "prefer-const": "off", - "prefer-template": "off", - "quote-props": [ - "error", - "as-needed" - ], - "radix": "error", - "space-before-function-paren": [ - "error", - { - "anonymous": "never", - "asyncArrow": "always", - "named": "never" - } - ], - "spaced-comment": [ - "error", - "always", - { - "markers": [ - "/" - ] - } - ] - }, - "settings": {} -} diff --git a/vim-config/plugins/coc.nvim/.github/.codecov.yml b/vim-config/plugins/coc.nvim/.github/.codecov.yml deleted file mode 100644 index fa348a8f..00000000 --- a/vim-config/plugins/coc.nvim/.github/.codecov.yml +++ /dev/null @@ -1,3 +0,0 @@ -coverage: - status: - patch: off diff --git a/vim-config/plugins/coc.nvim/.github/FUNDING.yml b/vim-config/plugins/coc.nvim/.github/FUNDING.yml deleted file mode 100644 index bc74b9db..00000000 --- a/vim-config/plugins/coc.nvim/.github/FUNDING.yml +++ /dev/null @@ -1,4 +0,0 @@ -# These are supported funding model platforms - -open_collective: cocnvim -patreon: chemzqm diff --git a/vim-config/plugins/coc.nvim/.github/ISSUE_TEMPLATE/bug_report.md b/vim-config/plugins/coc.nvim/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 3b0eaebb..00000000 --- a/vim-config/plugins/coc.nvim/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve ---- - - - -## Result from CocInfo - - - -## Describe the bug - -A clear and concise description of what the bug is. - -## Reproduce the bug - -**We will close your issue when you don't provide minimal vimrc and we can't -reproduce it** - -- Create file `mini.vim` with๏ผš - - ```vim - set nocompatible - set runtimepath^=/path/to/coc.nvim - filetype plugin indent on - syntax on - set hidden - ``` - -- Start (neo)vim with command: `vim -u mini.vim` - -- Operate vim. - -## Screenshots (optional) - -If applicable, add screenshots to help explain your problem. diff --git a/vim-config/plugins/coc.nvim/.github/ISSUE_TEMPLATE/feature_request.md b/vim-config/plugins/coc.nvim/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 066b2d92..00000000 --- a/vim-config/plugins/coc.nvim/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. diff --git a/vim-config/plugins/coc.nvim/.github/workflows/ci.yml b/vim-config/plugins/coc.nvim/.github/workflows/ci.yml deleted file mode 100644 index 9e8bd99c..00000000 --- a/vim-config/plugins/coc.nvim/.github/workflows/ci.yml +++ /dev/null @@ -1,74 +0,0 @@ -name: Dev - -on: - push: - branches: - - master - pull_request: - branches: - - master - -jobs: - test: - timeout-minutes: 60 - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - matrix: - os: - - "ubuntu-latest" - node: - - "16" - - "14" - - "12" - include: - # only enable coverage on the fastest job - - os: "ubuntu-latest" - node: "16" - ENABLE_CODE_COVERAGE: true - - env: - NODE_ENV: test - - steps: - - name: Checkout - uses: actions/checkout@v2.3.4 - with: - fetch-depth: 2 - - - name: Setup Node.js ${{ matrix.node }} - uses: actions/setup-node@v2.4.0 - with: - node-version: ${{ matrix.node }} - cache: "yarn" - - - name: Install Dependencies - run: | - yarn global add typescript - yarn install --frozen-lockfile - - - if: matrix.os == 'macos-latest' - name: yarn test on macOS - run: | - curl -LO https://github.com/neovim/neovim/releases/download/v0.5.0/nvim-macos.tar.gz - tar xzf nvim-macos.tar.gz - export PATH="${PATH}:node_modules/.bin:$(pwd)/nvim-osx64/bin" - nvim --version - yarn test-build --maxWorkers=4 - - if: matrix.os == 'ubuntu-latest' - name: yarn test on Ubuntu - run: | - sudo apt-get install ripgrep -y - rg --version - curl -LO https://github.com/neovim/neovim/releases/download/v0.5.0/nvim-linux64.tar.gz - tar xzf nvim-linux64.tar.gz - export PATH="${PATH}:node_modules/.bin:$(pwd)/nvim-linux64/bin" - nvim --version - yarn test-build --maxWorkers=2 - - - name: Codecov - uses: codecov/codecov-action@v2.0.2 - if: ${{ matrix.ENABLE_CODE_COVERAGE }} - with: - fail_ci_if_error: true diff --git a/vim-config/plugins/coc.nvim/.github/workflows/lint.yml b/vim-config/plugins/coc.nvim/.github/workflows/lint.yml deleted file mode 100644 index 7fcf066e..00000000 --- a/vim-config/plugins/coc.nvim/.github/workflows/lint.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Lint - -on: - push: - branches: - - master - pull_request: - branches: - - master - -jobs: - lint: - name: Lint - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v2.3.4 - - - name: Setup Node.js - uses: actions/setup-node@v2.4.0 - with: - cache: "yarn" - - - name: Install Dependencies - run: yarn install --frozen-lockfile - - - name: Check Types by TSC - run: yarn lint:typecheck - - - name: Lint ESLint - run: yarn lint - - - name: Check Lock File Changes - run: yarn && echo "Listing changed files:" && git diff --name-only --exit-code && echo "No files changed during lint." diff --git a/vim-config/plugins/coc.nvim/.gitignore b/vim-config/plugins/coc.nvim/.gitignore index 266844b7..f9ec5e3d 100644 --- a/vim-config/plugins/coc.nvim/.gitignore +++ b/vim-config/plugins/coc.nvim/.gitignore @@ -1,16 +1,13 @@ lib -.cache *.map coverage __pycache__ .pyc .log -build +src +publish.sh doc/tags -typings/package.json +doc/tags-cn node_modules -publish.sh -release.sh -!src/__tests__/tags -src/__tests__/extensions/db.json -package-lock.json +src/__tests__/tags +typings diff --git a/vim-config/plugins/coc.nvim/.ignore b/vim-config/plugins/coc.nvim/.ignore deleted file mode 100644 index a65b4177..00000000 --- a/vim-config/plugins/coc.nvim/.ignore +++ /dev/null @@ -1 +0,0 @@ -lib diff --git a/vim-config/plugins/coc.nvim/.npmignore b/vim-config/plugins/coc.nvim/.npmignore deleted file mode 100644 index 0193cd28..00000000 --- a/vim-config/plugins/coc.nvim/.npmignore +++ /dev/null @@ -1,16 +0,0 @@ -*.map -.cache -lib/extensions -lib/__tests__ -plugin -autoload -rplugin -src -.github -build -coverage -data -tslint.json -tsconfig.json -.zip -.DS_Store diff --git a/vim-config/plugins/coc.nvim/.vim/coc-settings.json b/vim-config/plugins/coc.nvim/.vim/coc-settings.json deleted file mode 100644 index 7746fb78..00000000 --- a/vim-config/plugins/coc.nvim/.vim/coc-settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "eslint.validate": ["typescript"], - "eslint.lintTask.options": [".", "--ext", ".ts"], - "typescript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": false, - "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": true, - "typescript.suggestionActions.enabled": false -} diff --git a/vim-config/plugins/coc.nvim/Backers.md b/vim-config/plugins/coc.nvim/Backers.md deleted file mode 100644 index b3cdb0b2..00000000 --- a/vim-config/plugins/coc.nvim/Backers.md +++ /dev/null @@ -1,207 +0,0 @@ -# Backers - -โค๏ธ coc.nvim? Help us keep it alive by [donating funds](https://www.bountysource.com/teams/coc-nvim)๐Ÿ˜˜! - - - oblitum - - - free-easy - - - ruanyl - - - robjuffermans - - - iamcco - - - phcerdan - - - sarene - - - robtrac - - - raidou - - - tomspeak - - - taigacute - - - weirongxu - - - tbo - - - darthShadow - - - yatli - - - Matt Greer - - - malob - - - Emigre - - - OkanEsen - - - Lennaert Meijvogel - - - Nils Landt - - - dlants - - - RCVU - - - yatli - - - mikker - - - Velovix - - - stCarolas - - - Robbie Clarken - - - hallettj - - - appelgriebsch - - - cosminadrianpopescu - - - partizan - - - ksaldana1 - - - jesperryom - - - JackCA - - - peymanmortazavi - - - jonaustin - - - Yuriy Ivanyuk - - - abenz1267 - - - Sh3Rm4n - - - mwcz - - - Philipp-M - - - gvelchuru - - - JSamir - - - toby de havilland - - - viniciusarcanjo - - - Mike Hearn - - - darsto - - - pyrho - - - Frydac - - - gsa9 - - - _andys8 - - - iago-lito - - - ddaletski - - - jonatan-branting - - - yutakatay - - - kevinrambaud - - - tomaskallup - - - LewisSteele - - -## ๅพฎไฟกๆ‰ซ็ ่ตžๅŠฉ่€… - -- free-easy -- sarene -- tomspeak -- robtrac -- ่‘ซ่Šฆๅฐ้‡‘ๅˆš -- leo ้™ถ -- ้ฃž็ฟ”็š„็™ฝๆ–ฉ้ธก -- mark_ll -- ็ซๅ†ท -- Solomon -- ๆŽๅฎ‡ๆ˜Ÿ -- Yus -- IndexXuan -- Sniper -- ้™ˆ่พพ้‡Ž -- ่ƒ–ๅฌ -- Jimmy -- lightxue -- ๅฐไบฆไฟŠ -- ๅ‘จๆ…Žๆ• -- ๅ‡ค้ธฃ -- Wilson -- Abel diff --git a/vim-config/plugins/coc.nvim/CONTRIBUTING.md b/vim-config/plugins/coc.nvim/CONTRIBUTING.md deleted file mode 100644 index a3cac5f5..00000000 --- a/vim-config/plugins/coc.nvim/CONTRIBUTING.md +++ /dev/null @@ -1,142 +0,0 @@ -# Contributing - -## How do I... - -- [Use This Guide](#introduction)? -- Make Something? ๐Ÿค“๐Ÿ‘ฉ๐Ÿฝโ€๐Ÿ’ป๐Ÿ“œ๐Ÿณ - - [Project Setup](#project-setup) - - [Contribute Documentation](#contribute-documentation) - - [Contribute Code](#contribute-code) -- Manage Something โœ…๐Ÿ™†๐Ÿผ๐Ÿ’ƒ๐Ÿ‘” - - [Provide Support on Issues](#provide-support-on-issues) - - [Review Pull Requests](#review-pull-requests) - - [Join the Project Team](#join-the-project-team) - -## Introduction - -Thank you so much for your interest in contributing!. All types of contributions are encouraged and valued. See the [table of contents](#toc) for different ways to help and details about how this project handles them!๐Ÿ“ - -The [Project Team](#join-the-project-team) looks forward to your contributions. ๐Ÿ™Œ๐Ÿพโœจ - -## Project Setup - -So you wanna contribute some code! That's great! This project uses GitHub Pull Requests to manage contributions, so [read up on how to fork a GitHub project and file a PR](https://guides.github.com/activities/forking) if you've never done it before. - -If this seems like a lot or you aren't able to do all this setup, you might also be able to [edit the files directly](https://help.github.com/articles/editing-files-in-another-user-s-repository/) without having to do any of this setup. Yes, [even code](#contribute-code). - -If you want to go the usual route and run the project locally, though: - -- [Install Node.js](https://nodejs.org/en/download/) -- [Install Yarn](https://yarnpkg.com) -- [Fork the project](https://guides.github.com/activities/forking/#fork) - -Then in your terminal: - -- Add coc.nvim to your vim's rtp by `set runtimepath^=/path/to/coc.nvim` -- `cd path/to/your/coc.nvim` -- `yarn install` -- Install [coc-tsserver](https://github.com/neoclide/coc-tsserver) by - `:CocInstall coc-tsserver` in your vim -- Install [coc-tslint-plugin](https://github.com/neoclide/coc-tslint-plugin) by - `:CocInstall coc-tslint-plugin` in your vim. - -And you should be ready to go! - -## Contribute Documentation - -Documentation is a super important, critical part of this project. Docs are how we keep track of what we're doing, how, and why. It's how we stay on the same page about our policies. And it's how we tell others everything they need in order to be able to use this project -- or contribute to it. So thank you in advance. - -Documentation contributions of any size are welcome! Feel free to file a PR even if you're just rewording a sentence to be more clear, or fixing a spelling mistake! - -To contribute documentation: - -- [Set up the project](#project-setup). -- Edit or add any relevant documentation. -- Make sure your changes are formatted correctly and consistently with the rest of the documentation. -- Re-read what you wrote, and run a spellchecker on it to make sure you didn't miss anything. -- In your commit message(s), begin the first line with `docs:`. For example: `docs: Adding a doc contrib section to CONTRIBUTING.md`. -- Write clear, concise commit message(s) using [conventional-changelog format](https://github.com/conventional-changelog/conventional-changelog-angular/blob/master/convention.md). Documentation commits should use `docs(): `. -- Go to https://github.com/neoclide/coc.nvim/pulls and open a new pull request with your changes. -- If your PR is connected to an open issue, add a line in your PR's description that says `Fixes: #123`, where `#123` is the number of the issue you're fixing. - -## Contribute Code - -We like code commits a lot! They're super handy, and they keep the project going and doing the work it needs to do to be useful to others. - -Code contributions of just about any size are acceptable! - -The main difference between code contributions and documentation contributions is that contributing code requires inclusion of relevant tests for the code being added or changed. Contributions without accompanying tests will be held off until a test is added, unless the maintainers consider the specific tests to be either impossible, or way too much of a burden for such a contribution. - -To contribute code: - -- [Set up the project](#project-setup). -- Make any necessary changes to the source code. -- Include any [additional documentation](#contribute-documentation) the changes might need. -- Make sure the code doesn't have lint issue by command `yarn lint` in your - terminal. -- Write tests that verify that your contribution works as expected when necessary. -- Make sure all tests passed by command `yarn jest` in your terminal. -- Write clear, concise commit message(s) using [conventional-changelog format](https://github.com/conventional-changelog/conventional-changelog-angular/blob/master/convention.md). -- Dependency updates, additions, or removals must be in individual commits, and the message must use the format: `(deps): PKG@VERSION`, where `` is any of the usual `conventional-changelog` prefixes, at your discretion. -- Go to https://github.com/neoclide/coc.nvim/pulls and open a new pull request with your changes. -- If your PR is connected to an open issue, add a line in your PR's description that says `Fixes: #123`, where `#123` is the number of the issue you're fixing. - -Once you've filed the PR: - -- Barring special circumstances, maintainers will not review PRs until all checks pass (Travis, AppVeyor, etc). -- One or more maintainers will use GitHub's review feature to review your PR. -- If the maintainer asks for any changes, edit your changes, push, and ask for another review. Additional tags (such as `needs-tests`) will be added depending on the review. -- If the maintainer decides to pass on your PR, they will thank you for the contribution and explain why they won't be accepting the changes. That's ok! We still really appreciate you taking the time to do it, and we don't take that lightly. ๐Ÿ’š -- If your PR gets accepted, it will be marked as such, and merged into the `latest` branch soon after. Your contribution will be distributed to the masses next time the maintainers [tag a release](#tag-a-release) - -## Provide Support on Issues - -[Needs Collaborator](#join-the-project-team): none - -Helping out other users with their questions is a really awesome way of contributing to any community. It's not uncommon for most of the issues on an open source projects being support-related questions by users trying to understand something they ran into, or find their way around a known bug. - -Sometimes, the `support` label will be added to things that turn out to actually be other things, like bugs or feature requests. In that case, suss out the details with the person who filed the original issue, add a comment explaining what the bug is, and change the label from `support` to `bug` or `feature`. If you can't do this yourself, @mention a maintainer so they can do it. - -In order to help other folks out with their questions: - -- Go to the issue tracker and [filter open issues by the `support` label](https://github.com/neoclide/coc.nvim/issues?q=is%3Aopen+is%3Aissue+label%3Asupport). -- Read through the list until you find something that you're familiar enough with to give an answer to. -- Respond to the issue with whatever details are needed to clarify the question, or get more details about what's going on. -- Once the discussion wraps up and things are clarified, either close the issue, or ask the original issue filer (or a maintainer) to close it for you. - -Some notes on picking up support issues: - -- Avoid responding to issues you don't know you can answer accurately. -- As much as possible, try to refer to past issues with accepted answers. Link to them from your replies with the `#123` format. -- Be kind and patient with users -- often, folks who have run into confusing things might be upset or impatient. This is ok. Try to understand where they're coming from, and if you're too uncomfortable with the tone, feel free to stay away or withdraw from the issue. (note: if the user is outright hostile or is violating the CoC, [refer to the Code of Conduct](CODE_OF_CONDUCT.md) to resolve the conflict). - -## Review Pull Requests - -[Needs Collaborator](#join-the-project-team): Issue Tracker - -While anyone can comment on a PR, add feedback, etc, PRs are only _approved_ by team members with Issue Tracker or higher permissions. - -PR reviews use [GitHub's own review feature](https://help.github.com/articles/about-pull-request-reviews/), which manages comments, approval, and review iteration. - -Some notes: - -- You may ask for minor changes ("nitpicks"), but consider whether they are really blockers to merging: try to err on the side of "approve, with comments". -- _ALL PULL REQUESTS_ should be covered by a test: either by a previously-failing test, an existing test that covers the entire functionality of the submitted code, or new tests to verify any new/changed behavior. All tests must also pass and follow established conventions. Test coverage should not drop, unless the specific case is considered reasonable by maintainers. -- Please make sure you're familiar with the code or documentation being updated, unless it's a minor change (spellchecking, minor formatting, etc). You may @mention another project member who you think is better suited for the review, but still provide a non-approving review of your own. -- Be extra kind: people who submit code/doc contributions are putting themselves in a pretty vulnerable position, and have put time and care into what they've done (even if that's not obvious to you!) -- always respond with respect, be understanding, but don't feel like you need to sacrifice your standards for their sake, either. Just don't be a jerk about it? - -## Join the Project Team - -### Ways to Join - -There are many ways to contribute! Most of them don't require any official status unless otherwise noted. That said, there's a couple of positions that grant special repository abilities, and this section describes how they're granted and what they do. - -All of the below positions are granted based on the project team's needs, as well as their consensus opinion about whether they would like to work with the person and think that they would fit well into that position. The process is relatively informal, and it's likely that people who express interest in participating can just be granted the permissions they'd like. - -You can spot a collaborator on the repo by looking for the `[Collaborator]` or `[Owner]` tags next to their names. - -| Permission | Description | -| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Issue Tracker | Granted to contributors who express a strong interest in spending time on the project's issue tracker. These tasks are mainly [labeling issues](#label-issues), [cleaning up old ones](#clean-up-issues-and-prs), and [reviewing pull requests](#review-pull-requests), as well as all the usual things non-team-member contributors can do. Issue handlers should not merge pull requests, tag releases, or directly commit code themselves: that should still be done through the usual pull request process. Becoming an Issue Handler means the project team trusts you to understand enough of the team's process and context to implement it on the issue tracker. | -| Committer | Granted to contributors who want to handle the actual pull request merges, tagging new versions, etc. Committers should have a good level of familiarity with the codebase, and enough context to understand the implications of various changes, as well as a good sense of the will and expectations of the project team. | -| Admin/Owner | Granted to people ultimately responsible for the project, its community, etc. | diff --git a/vim-config/plugins/coc.nvim/LICENSE.md b/vim-config/plugins/coc.nvim/LICENSE.md index 2a5396de..bee2bf1d 100644 --- a/vim-config/plugins/coc.nvim/LICENSE.md +++ b/vim-config/plugins/coc.nvim/LICENSE.md @@ -1,4 +1,4 @@ -Copyright 2018-2018 by Qiming Zhao +Copyright 2018-2018 by Qiming Zhao aaa Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: diff --git a/vim-config/plugins/coc.nvim/README.md b/vim-config/plugins/coc.nvim/README.md deleted file mode 100644 index cc215f87..00000000 --- a/vim-config/plugins/coc.nvim/README.md +++ /dev/null @@ -1,334 +0,0 @@ -

- - Coc Logo - -

Make your Vim/Neovim as smart as VSCode.

-

- Software License - Actions - Codecov Coverage Status - Doc - Gitter -

-

- ---- - -Gif - -_True snippet and additional text editing support_ - -## Why? - -- ๐Ÿš€ **Fast**: [instant increment completion](https://github.com/neoclide/coc.nvim/wiki/Completion-with-sources), increment buffer sync using buffer update events. -- ๐Ÿ’Ž **Reliable**: typed language, tested with CI. -- ๐ŸŒŸ **Featured**: [full LSP support](https://github.com/neoclide/coc.nvim/wiki/Language-servers#supported-features) -- โค๏ธ **Flexible**: [configured like VSCode](https://github.com/neoclide/coc.nvim/wiki/Using-the-configuration-file), [extensions work like in VSCode](https://github.com/neoclide/coc.nvim/wiki/Using-coc-extensions) - -## Quick Start - -Install [nodejs](https://nodejs.org/en/download/) >= 12.12: - -```bash -curl -sL install-node.vercel.app/lts | bash -``` - -For [vim-plug](https://github.com/junegunn/vim-plug) users: - -```vim -" Use release branch (recommend) -Plug 'neoclide/coc.nvim', {'branch': 'release'} - -" Or build from source code by using yarn: https://yarnpkg.com -Plug 'neoclide/coc.nvim', {'branch': 'master', 'do': 'yarn install --frozen-lockfile'} -``` - -in your `.vimrc` or `init.vim`, then restart Vim and run `:PlugInstall`. - -Checkout [Install -coc.nvim](https://github.com/neoclide/coc.nvim/wiki/Install-coc.nvim) for -more info. - -You **have to** install coc extension or configure language servers for -LSP support. - -Install extensions like: - - :CocInstall coc-json coc-tsserver - -Or configure language server in `coc-settings.json` opened by -`:CocConfig`, like: - -```json -{ - "languageserver": { - "go": { - "command": "gopls", - "rootPatterns": ["go.mod"], - "trace.server": "verbose", - "filetypes": ["go"] - } - } -} -``` - -Checkout wiki for more details: - -- [Completion with sources](https://github.com/neoclide/coc.nvim/wiki/Completion-with-sources) -- [Using the configuration file](https://github.com/neoclide/coc.nvim/wiki/Using-the-configuration-file) -- [Using coc extensions](https://github.com/neoclide/coc.nvim/wiki/Using-coc-extensions) -- [Configure language servers](https://github.com/neoclide/coc.nvim/wiki/Language-servers) -- [F.A.Q](https://github.com/neoclide/coc.nvim/wiki/F.A.Q) - -Checkout `:h coc-nvim` for vim interface. - -## Example vim configuration - -Configuration is required to make coc.nvim easier to work with, since it -doesn't change your key-mappings or Vim options. This is done as much as -possible to avoid conflict with your other plugins. - -**โ—๏ธImportant**: Some Vim plugins could change key mappings. Please use -command like`:verbose imap ` to make sure that your keymap has taken effect. - -```vim -" Set internal encoding of vim, not needed on neovim, since coc.nvim using some -" unicode characters in the file autoload/float.vim -set encoding=utf-8 - -" TextEdit might fail if hidden is not set. -set hidden - -" Some servers have issues with backup files, see #649. -set nobackup -set nowritebackup - -" Give more space for displaying messages. -set cmdheight=2 - -" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable -" delays and poor user experience. -set updatetime=300 - -" Don't pass messages to |ins-completion-menu|. -set shortmess+=c - -" Always show the signcolumn, otherwise it would shift the text each time -" diagnostics appear/become resolved. -if has("nvim-0.5.0") || has("patch-8.1.1564") - " Recently vim can merge signcolumn and number column into one - set signcolumn=number -else - set signcolumn=yes -endif - -" Use tab for trigger completion with characters ahead and navigate. -" NOTE: Use command ':verbose imap ' to make sure tab is not mapped by -" other plugin before putting this into your config. -inoremap - \ pumvisible() ? "\" : - \ check_back_space() ? "\" : - \ coc#refresh() -inoremap pumvisible() ? "\" : "\" - -function! s:check_back_space() abort - let col = col('.') - 1 - return !col || getline('.')[col - 1] =~# '\s' -endfunction - -" Use to trigger completion. -if has('nvim') - inoremap coc#refresh() -else - inoremap coc#refresh() -endif - -" Make auto-select the first completion item and notify coc.nvim to -" format on enter, could be remapped by other vim plugin -inoremap pumvisible() ? coc#_select_confirm() - \: "\u\\=coc#on_enter()\" - -" Use `[g` and `]g` to navigate diagnostics -" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list. -nmap [g (coc-diagnostic-prev) -nmap ]g (coc-diagnostic-next) - -" GoTo code navigation. -nmap gd (coc-definition) -nmap gy (coc-type-definition) -nmap gi (coc-implementation) -nmap gr (coc-references) - -" Use K to show documentation in preview window. -nnoremap K :call show_documentation() - -function! s:show_documentation() - if (index(['vim','help'], &filetype) >= 0) - execute 'h '.expand('') - elseif (coc#rpc#ready()) - call CocActionAsync('doHover') - else - execute '!' . &keywordprg . " " . expand('') - endif -endfunction - -" Highlight the symbol and its references when holding the cursor. -autocmd CursorHold * silent call CocActionAsync('highlight') - -" Symbol renaming. -nmap rn (coc-rename) - -" Formatting selected code. -xmap f (coc-format-selected) -nmap f (coc-format-selected) - -augroup mygroup - autocmd! - " Setup formatexpr specified filetype(s). - autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected') - " Update signature help on jump placeholder. - autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp') -augroup end - -" Applying codeAction to the selected region. -" Example: `aap` for current paragraph -xmap a (coc-codeaction-selected) -nmap a (coc-codeaction-selected) - -" Remap keys for applying codeAction to the current buffer. -nmap ac (coc-codeaction) -" Apply AutoFix to problem on the current line. -nmap qf (coc-fix-current) - -" Map function and class text objects -" NOTE: Requires 'textDocument.documentSymbol' support from the language server. -xmap if (coc-funcobj-i) -omap if (coc-funcobj-i) -xmap af (coc-funcobj-a) -omap af (coc-funcobj-a) -xmap ic (coc-classobj-i) -omap ic (coc-classobj-i) -xmap ac (coc-classobj-a) -omap ac (coc-classobj-a) - -" Remap and for scroll float windows/popups. -if has('nvim-0.4.0') || has('patch-8.2.0750') - nnoremap coc#float#has_scroll() ? coc#float#scroll(1) : "\" - nnoremap coc#float#has_scroll() ? coc#float#scroll(0) : "\" - inoremap coc#float#has_scroll() ? "\=coc#float#scroll(1)\" : "\" - inoremap coc#float#has_scroll() ? "\=coc#float#scroll(0)\" : "\" - vnoremap coc#float#has_scroll() ? coc#float#scroll(1) : "\" - vnoremap coc#float#has_scroll() ? coc#float#scroll(0) : "\" -endif - -" Use CTRL-S for selections ranges. -" Requires 'textDocument/selectionRange' support of language server. -nmap (coc-range-select) -xmap (coc-range-select) - -" Add `:Format` command to format current buffer. -command! -nargs=0 Format :call CocAction('format') - -" Add `:Fold` command to fold current buffer. -command! -nargs=? Fold :call CocAction('fold', ) - -" Add `:OR` command for organize imports of the current buffer. -command! -nargs=0 OR :call CocActionAsync('runCommand', 'editor.action.organizeImport') - -" Add (Neo)Vim's native statusline support. -" NOTE: Please see `:h coc-status` for integrations with external plugins that -" provide custom statusline: lightline.vim, vim-airline. -set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')} - -" Mappings for CoCList -" Show all diagnostics. -nnoremap a :CocList diagnostics -" Manage extensions. -nnoremap e :CocList extensions -" Show commands. -nnoremap c :CocList commands -" Find symbol of current document. -nnoremap o :CocList outline -" Search workspace symbols. -nnoremap s :CocList -I symbols -" Do default action for next item. -nnoremap j :CocNext -" Do default action for previous item. -nnoremap k :CocPrev -" Resume latest coc list. -nnoremap p :CocListResume -``` - -## Articles - -- [coc.nvim ๆ’ไปถไฝ“็ณปไป‹็ป](https://zhuanlan.zhihu.com/p/65524706) -- [CocList ๅ…ฅๅ‘ๆŒ‡ๅ—](https://zhuanlan.zhihu.com/p/71846145) -- [Create coc.nvim extension to improve Vim experience](https://medium.com/@chemzqm/create-coc-nvim-extension-to-improve-vim-experience-4461df269173) -- [How to write a coc.nvim extension (and why)](https://samroeca.com/coc-plugin.html) - -## Trouble shooting - -Try these steps when you have problem with coc.nvim. - -- Make sure your Vim version >= 8.0 by command `:version`. -- If service failed to start, use command `:CocInfo` or `:checkhealth` on Neovim. -- Checkout the log of coc.nvim by command `:CocOpenLog`. -- When you have issues with the language server, it's recommended to [checkout - the output](https://github.com/neoclide/coc.nvim/wiki/Debug-language-server#using-output-channel). - -## Feedback - -- If you think Coc is useful, consider giving it a star. -- If you have a question, [ask on gitter](https://gitter.im/neoclide/coc.nvim) -- ไธญๆ–‡็”จๆˆท่ฏทๅˆฐ [ไธญๆ–‡ gitter](https://gitter.im/neoclide/coc-cn) ่ฎจ่ฎบ -- If something is not working, [create an - issue](https://github.com/neoclide/coc.nvim/issues/new). - -## Backers - -[Become a backer](https://opencollective.com/cocnvim#backer) and get your image on our README on Github with a link to your site. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Support the project - -Buy cloud service from [www.vultr.com](https://www.vultr.com/?ref=8890170-6G) - -## License - -MIT diff --git a/vim-config/plugins/coc.nvim/Readme.md b/vim-config/plugins/coc.nvim/Readme.md new file mode 100644 index 00000000..c7d1224b --- /dev/null +++ b/vim-config/plugins/coc.nvim/Readme.md @@ -0,0 +1,845 @@ +

+ + Logo + +

Make your Vim/Neovim as smart as VSCode

+

+ Software License + Actions + Codecov Coverage Status + Doc + Gitter +

+

+ +--- + +Gif + +_Custom popup menu with snippet support_ + +## Why? + +- ๐Ÿš€ **Fast**: separated NodeJS process that does not slow down Vim most of the time. +- ๐Ÿ’Ž **Reliable**: typed language, tested with CI. +- ๐ŸŒŸ **Featured**: all LSP 3.16 features are supported, see `:h coc-lsp`. +- โค๏ธ **Flexible**: [configured like VS Code](https://github.com/neoclide/coc.nvim/wiki/Using-the-configuration-file), [Coc extensions function similarly to VS Code extensions](https://github.com/neoclide/coc.nvim/wiki/Using-coc-extensions) + +## Quick Start + +Make sure use Vim >= 8.1.1719 or Neovim >= 0.4.0. + +Install [nodejs](https://nodejs.org/en/download/) >= 14.14: + +```bash +curl -sL install-node.vercel.app/lts | bash +``` + +For [vim-plug](https://github.com/junegunn/vim-plug) users: + +```vim +" Use release branch (recommend) +Plug 'neoclide/coc.nvim', {'branch': 'release'} + +" Or build from source code by using yarn: https://yarnpkg.com +Plug 'neoclide/coc.nvim', {'branch': 'master', 'do': 'yarn install --frozen-lockfile'} +``` + +in your `.vimrc` or `init.vim`, then restart Vim and run `:PlugInstall`. + +Checkout [Install +coc.nvim](https://github.com/neoclide/coc.nvim/wiki/Install-coc.nvim) for +more info. + +You **have to** install coc extension or configure language servers for +LSP support. + +Install extensions like: + + :CocInstall coc-json coc-tsserver + +Or configure language server in `coc-settings.json` opened by +`:CocConfig`, like: + +```json +{ + "languageserver": { + "go": { + "command": "gopls", + "rootPatterns": ["go.mod"], + "trace.server": "verbose", + "filetypes": ["go"] + } + } +} +``` + +Checkout the wiki for more details: + +- [Completion with sources](https://github.com/neoclide/coc.nvim/wiki/Completion-with-sources) +- [Using the configuration file](https://github.com/neoclide/coc.nvim/wiki/Using-the-configuration-file) +- [Using coc extensions](https://github.com/neoclide/coc.nvim/wiki/Using-coc-extensions) +- [Configure language servers](https://github.com/neoclide/coc.nvim/wiki/Language-servers) +- [F.A.Q](https://github.com/neoclide/coc.nvim/wiki/F.A.Q) + +Checkout `:h coc-nvim` for Vim interface. + +## Example Vim configuration + +Configuration is required to make coc.nvim easier to work with, since it +doesn't change your key-mappings or Vim options. This is done as much as +possible to avoid conflict with your other plugins. + +**โ—๏ธImportant**: Some Vim plugins could change key mappings. Please use +command like`:verbose imap ` to make sure that your keymap has taken effect. + +```vim + +" May need for Vim (not Neovim) since coc.nvim calculates byte offset by count +" utf-8 byte sequence +set encoding=utf-8 +" Some servers have issues with backup files, see #649 +set nobackup +set nowritebackup + +" Having longer updatetime (default is 4000 ms = 4s) leads to noticeable +" delays and poor user experience +set updatetime=300 + +" Always show the signcolumn, otherwise it would shift the text each time +" diagnostics appear/become resolved +set signcolumn=yes + +" Use tab for trigger completion with characters ahead and navigate +" NOTE: There's always complete item selected by default, you may want to enable +" no select by `"suggest.noselect": true` in your configuration file +" NOTE: Use command ':verbose imap ' to make sure tab is not mapped by +" other plugin before putting this into your config +inoremap + \ coc#pum#visible() ? coc#pum#next(1) : + \ CheckBackspace() ? "\" : + \ coc#refresh() +inoremap coc#pum#visible() ? coc#pum#prev(1) : "\" + +" Make to accept selected completion item or notify coc.nvim to format +" u breaks current undo, please make your own choice +inoremap coc#pum#visible() ? coc#pum#confirm() + \: "\u\\=coc#on_enter()\" + +function! CheckBackspace() abort + let col = col('.') - 1 + return !col || getline('.')[col - 1] =~# '\s' +endfunction + +" Use to trigger completion +if has('nvim') + inoremap coc#refresh() +else + inoremap coc#refresh() +endif + +" Use `[g` and `]g` to navigate diagnostics +" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list +nmap [g (coc-diagnostic-prev) +nmap ]g (coc-diagnostic-next) + +" GoTo code navigation +nmap gd (coc-definition) +nmap gy (coc-type-definition) +nmap gi (coc-implementation) +nmap gr (coc-references) + +" Use K to show documentation in preview window +nnoremap K :call ShowDocumentation() + +function! ShowDocumentation() + if CocAction('hasProvider', 'hover') + call CocActionAsync('doHover') + else + call feedkeys('K', 'in') + endif +endfunction + +" Highlight the symbol and its references when holding the cursor +autocmd CursorHold * silent call CocActionAsync('highlight') + +" Symbol renaming +nmap rn (coc-rename) + +" Formatting selected code +xmap f (coc-format-selected) +nmap f (coc-format-selected) + +augroup mygroup + autocmd! + " Setup formatexpr specified filetype(s) + autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected') + " Update signature help on jump placeholder + autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp') +augroup end + +" Applying code actions to the selected code block +" Example: `aap` for current paragraph +xmap a (coc-codeaction-selected) +nmap a (coc-codeaction-selected) + +" Remap keys for applying code actions at the cursor position +nmap ac (coc-codeaction-cursor) +" Remap keys for apply code actions affect whole buffer +nmap as (coc-codeaction-source) +" Apply the most preferred quickfix action to fix diagnostic on the current line +nmap qf (coc-fix-current) + +" Remap keys for applying refactor code actions +nmap re (coc-codeaction-refactor) +xmap r (coc-codeaction-refactor-selected) +nmap r (coc-codeaction-refactor-selected) + +" Run the Code Lens action on the current line +nmap cl (coc-codelens-action) + +" Map function and class text objects +" NOTE: Requires 'textDocument.documentSymbol' support from the language server +xmap if (coc-funcobj-i) +omap if (coc-funcobj-i) +xmap af (coc-funcobj-a) +omap af (coc-funcobj-a) +xmap ic (coc-classobj-i) +omap ic (coc-classobj-i) +xmap ac (coc-classobj-a) +omap ac (coc-classobj-a) + +" Remap and to scroll float windows/popups +if has('nvim-0.4.0') || has('patch-8.2.0750') + nnoremap coc#float#has_scroll() ? coc#float#scroll(1) : "\" + nnoremap coc#float#has_scroll() ? coc#float#scroll(0) : "\" + inoremap coc#float#has_scroll() ? "\=coc#float#scroll(1)\" : "\" + inoremap coc#float#has_scroll() ? "\=coc#float#scroll(0)\" : "\" + vnoremap coc#float#has_scroll() ? coc#float#scroll(1) : "\" + vnoremap coc#float#has_scroll() ? coc#float#scroll(0) : "\" +endif + +" Use CTRL-S for selections ranges +" Requires 'textDocument/selectionRange' support of language server +nmap (coc-range-select) +xmap (coc-range-select) + +" Add `:Format` command to format current buffer +command! -nargs=0 Format :call CocActionAsync('format') + +" Add `:Fold` command to fold current buffer +command! -nargs=? Fold :call CocAction('fold', ) + +" Add `:OR` command for organize imports of the current buffer +command! -nargs=0 OR :call CocActionAsync('runCommand', 'editor.action.organizeImport') + +" Add (Neo)Vim's native statusline support +" NOTE: Please see `:h coc-status` for integrations with external plugins that +" provide custom statusline: lightline.vim, vim-airline +set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')} + +" Mappings for CoCList +" Show all diagnostics +nnoremap a :CocList diagnostics +" Manage extensions +nnoremap e :CocList extensions +" Show commands +nnoremap c :CocList commands +" Find symbol of current document +nnoremap o :CocList outline +" Search workspace symbols +nnoremap s :CocList -I symbols +" Do default action for next item +nnoremap j :CocNext +" Do default action for previous item +nnoremap k :CocPrev +" Resume latest coc list +nnoremap p :CocListResume +``` + +## Example Lua configuration + +NOTE: This only works in Neovim 0.7.0dev+. + +```lua +-- Some servers have issues with backup files, see #649 +vim.opt.backup = false +vim.opt.writebackup = false + +-- Having longer updatetime (default is 4000 ms = 4s) leads to noticeable +-- delays and poor user experience +vim.opt.updatetime = 300 + +-- Always show the signcolumn, otherwise it would shift the text each time +-- diagnostics appeared/became resolved +vim.opt.signcolumn = "yes" + +local keyset = vim.keymap.set +-- Autocomplete +function _G.check_back_space() + local col = vim.fn.col('.') - 1 + return col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') ~= nil +end + +-- Use Tab for trigger completion with characters ahead and navigate +-- NOTE: There's always a completion item selected by default, you may want to enable +-- no select by setting `"suggest.noselect": true` in your configuration file +-- NOTE: Use command ':verbose imap ' to make sure Tab is not mapped by +-- other plugins before putting this into your config +local opts = {silent = true, noremap = true, expr = true, replace_keycodes = false} +keyset("i", "", 'coc#pum#visible() ? coc#pum#next(1) : v:lua.check_back_space() ? "" : coc#refresh()', opts) +keyset("i", "", [[coc#pum#visible() ? coc#pum#prev(1) : "\"]], opts) + +-- Make to accept selected completion item or notify coc.nvim to format +-- u breaks current undo, please make your own choice +keyset("i", "", [[coc#pum#visible() ? coc#pum#confirm() : "\u\\=coc#on_enter()\"]], opts) + +-- Use to trigger snippets +keyset("i", "", "(coc-snippets-expand-jump)") +-- Use to trigger completion +keyset("i", "", "coc#refresh()", {silent = true, expr = true}) + +-- Use `[g` and `]g` to navigate diagnostics +-- Use `:CocDiagnostics` to get all diagnostics of current buffer in location list +keyset("n", "[g", "(coc-diagnostic-prev)", {silent = true}) +keyset("n", "]g", "(coc-diagnostic-next)", {silent = true}) + +-- GoTo code navigation +keyset("n", "gd", "(coc-definition)", {silent = true}) +keyset("n", "gy", "(coc-type-definition)", {silent = true}) +keyset("n", "gi", "(coc-implementation)", {silent = true}) +keyset("n", "gr", "(coc-references)", {silent = true}) + + +-- Use K to show documentation in preview window +function _G.show_docs() + local cw = vim.fn.expand('') + if vim.fn.index({'vim', 'help'}, vim.bo.filetype) >= 0 then + vim.api.nvim_command('h ' .. cw) + elseif vim.api.nvim_eval('coc#rpc#ready()') then + vim.fn.CocActionAsync('doHover') + else + vim.api.nvim_command('!' .. vim.o.keywordprg .. ' ' .. cw) + end +end +keyset("n", "K", 'lua _G.show_docs()', {silent = true}) + + +-- Highlight the symbol and its references on a CursorHold event(cursor is idle) +vim.api.nvim_create_augroup("CocGroup", {}) +vim.api.nvim_create_autocmd("CursorHold", { + group = "CocGroup", + command = "silent call CocActionAsync('highlight')", + desc = "Highlight symbol under cursor on CursorHold" +}) + + +-- Symbol renaming +keyset("n", "rn", "(coc-rename)", {silent = true}) + + +-- Formatting selected code +keyset("x", "f", "(coc-format-selected)", {silent = true}) +keyset("n", "f", "(coc-format-selected)", {silent = true}) + + +-- Setup formatexpr specified filetype(s) +vim.api.nvim_create_autocmd("FileType", { + group = "CocGroup", + pattern = "typescript,json", + command = "setl formatexpr=CocAction('formatSelected')", + desc = "Setup formatexpr specified filetype(s)." +}) + +-- Update signature help on jump placeholder +vim.api.nvim_create_autocmd("User", { + group = "CocGroup", + pattern = "CocJumpPlaceholder", + command = "call CocActionAsync('showSignatureHelp')", + desc = "Update signature help on jump placeholder" +}) + +-- Apply codeAction to the selected region +-- Example: `aap` for current paragraph +local opts = {silent = true, nowait = true} +keyset("x", "a", "(coc-codeaction-selected)", opts) +keyset("n", "a", "(coc-codeaction-selected)", opts) + +-- Remap keys for apply code actions at the cursor position. +keyset("n", "ac", "(coc-codeaction-cursor)", opts) +-- Remap keys for apply code actions affect whole buffer. +keyset("n", "as", "(coc-codeaction-source)", opts) +-- Remap keys for applying codeActions to the current buffer +keyset("n", "ac", "(coc-codeaction)", opts) +-- Apply the most preferred quickfix action on the current line. +keyset("n", "qf", "(coc-fix-current)", opts) + +-- Remap keys for apply refactor code actions. +keyset("n", "re", "(coc-codeaction-refactor)", { silent = true }) +keyset("x", "r", "(coc-codeaction-refactor-selected)", { silent = true }) +keyset("n", "r", "(coc-codeaction-refactor-selected)", { silent = true }) + +-- Run the Code Lens actions on the current line +keyset("n", "cl", "(coc-codelens-action)", opts) + + +-- Map function and class text objects +-- NOTE: Requires 'textDocument.documentSymbol' support from the language server +keyset("x", "if", "(coc-funcobj-i)", opts) +keyset("o", "if", "(coc-funcobj-i)", opts) +keyset("x", "af", "(coc-funcobj-a)", opts) +keyset("o", "af", "(coc-funcobj-a)", opts) +keyset("x", "ic", "(coc-classobj-i)", opts) +keyset("o", "ic", "(coc-classobj-i)", opts) +keyset("x", "ac", "(coc-classobj-a)", opts) +keyset("o", "ac", "(coc-classobj-a)", opts) + + +-- Remap and to scroll float windows/popups +---@diagnostic disable-next-line: redefined-local +local opts = {silent = true, nowait = true, expr = true} +keyset("n", "", 'coc#float#has_scroll() ? coc#float#scroll(1) : ""', opts) +keyset("n", "", 'coc#float#has_scroll() ? coc#float#scroll(0) : ""', opts) +keyset("i", "", + 'coc#float#has_scroll() ? "=coc#float#scroll(1)" : ""', opts) +keyset("i", "", + 'coc#float#has_scroll() ? "=coc#float#scroll(0)" : ""', opts) +keyset("v", "", 'coc#float#has_scroll() ? coc#float#scroll(1) : ""', opts) +keyset("v", "", 'coc#float#has_scroll() ? coc#float#scroll(0) : ""', opts) + + +-- Use CTRL-S for selections ranges +-- Requires 'textDocument/selectionRange' support of language server +keyset("n", "", "(coc-range-select)", {silent = true}) +keyset("x", "", "(coc-range-select)", {silent = true}) + + +-- Add `:Format` command to format current buffer +vim.api.nvim_create_user_command("Format", "call CocAction('format')", {}) + +-- " Add `:Fold` command to fold current buffer +vim.api.nvim_create_user_command("Fold", "call CocAction('fold', )", {nargs = '?'}) + +-- Add `:OR` command for organize imports of the current buffer +vim.api.nvim_create_user_command("OR", "call CocActionAsync('runCommand', 'editor.action.organizeImport')", {}) + +-- Add (Neo)Vim's native statusline support +-- NOTE: Please see `:h coc-status` for integrations with external plugins that +-- provide custom statusline: lightline.vim, vim-airline +vim.opt.statusline:prepend("%{coc#status()}%{get(b:,'coc_current_function','')}") + +-- Mappings for CoCList +-- code actions and coc stuff +---@diagnostic disable-next-line: redefined-local +local opts = {silent = true, nowait = true} +-- Show all diagnostics +keyset("n", "a", ":CocList diagnostics", opts) +-- Manage extensions +keyset("n", "e", ":CocList extensions", opts) +-- Show commands +keyset("n", "c", ":CocList commands", opts) +-- Find symbol of current document +keyset("n", "o", ":CocList outline", opts) +-- Search workspace symbols +keyset("n", "s", ":CocList -I symbols", opts) +-- Do default action for next item +keyset("n", "j", ":CocNext", opts) +-- Do default action for previous item +keyset("n", "k", ":CocPrev", opts) +-- Resume latest coc list +keyset("n", "p", ":CocListResume", opts) +``` + +## Articles + +- [coc.nvim ๆ’ไปถไฝ“็ณปไป‹็ป](https://zhuanlan.zhihu.com/p/65524706) +- [CocList ๅ…ฅๅ‘ๆŒ‡ๅ—](https://zhuanlan.zhihu.com/p/71846145) +- [Create coc.nvim extension to improve Vim experience](https://medium.com/@chemzqm/create-coc-nvim-extension-to-improve-vim-experience-4461df269173) +- [How to write a coc.nvim extension (and why)](https://samroeca.com/coc-plugin.html) + +## Troubleshooting + +Try these steps if you experience problems with coc.nvim: + +- Ensure your Vim version >= 8.0 using `:version` +- If a service failed to start, use `:CocInfo` or `:checkhealth` if you use Neovim +- Checkout the log of coc.nvim with `:CocOpenLog` +- If you have issues with the language server, it's recommended to [checkout + the language server output](https://github.com/neoclide/coc.nvim/wiki/Debug-language-server#using-output-channel) + +## Feedback + +- If you think Coc is useful, consider giving it a star +- If you have a question, [ask on gitter](https://gitter.im/neoclide/coc.nvim) +- ไธญๆ–‡็”จๆˆท่ฏทๅˆฐ [ไธญๆ–‡ gitter](https://gitter.im/neoclide/coc-cn) ่ฎจ่ฎบ +- If something is not working, [create an + issue](https://github.com/neoclide/coc.nvim/issues/new) + +## Backers + +[Become a backer](https://opencollective.com/cocnvim#backer) and get your image on our README on GitHub with a link to your site. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Contributors + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Qiming zhao
Qiming zhao

๐Ÿ’ป
Heyward Fann
Heyward Fann

๐Ÿ’ป
Raidou
Raidou

๐Ÿ’ป
kevinhwang91
kevinhwang91

๐Ÿ’ป
ๅนด็ณ•ๅฐ่ฑ†ๆฑค
ๅนด็ณ•ๅฐ่ฑ†ๆฑค

๐Ÿ’ป
Avi Dessauer
Avi Dessauer

๐Ÿ’ป
ๆœ€ไธŠๅท
ๆœ€ไธŠๅท

๐Ÿ’ป
Yatao Li
Yatao Li

๐Ÿ’ป
wongxy
wongxy

๐Ÿ’ป
Sam McCall
Sam McCall

๐Ÿ’ป
Samuel Roeca
Samuel Roeca

๐Ÿ’ป
Amirali Esmaeili
Amirali Esmaeili

๐Ÿ’ป
Jack Rowlingson
Jack Rowlingson

๐Ÿ’ป
Jaehwang Jung
Jaehwang Jung

๐Ÿ’ป
Antoine
Antoine

๐Ÿ’ป
Cosmin Popescu
Cosmin Popescu

๐Ÿ’ป
Duc Nghiem Xuan
Duc Nghiem Xuan

๐Ÿ’ป
Francisco Lopes
Francisco Lopes

๐Ÿ’ป
daquexian
daquexian

๐Ÿ’ป
dependabot[bot]
dependabot[bot]

๐Ÿ’ป
greenkeeper[bot]
greenkeeper[bot]

๐Ÿ’ป
Chris Kipp
Chris Kipp

๐Ÿ’ป
Dmytro Meleshko
Dmytro Meleshko

๐Ÿ’ป
Kirill Bobyrev
Kirill Bobyrev

๐Ÿ’ป
Gontran Baerts
Gontran Baerts

๐Ÿ’ป
Andy
Andy

๐Ÿ’ป
Cheng JIANG
Cheng JIANG

๐Ÿ’ป
Corin
Corin

๐Ÿ’ป
Daniel Zhang
Daniel Zhang

๐Ÿ’ป
Ferdinand Bachmann
Ferdinand Bachmann

๐Ÿ’ป
Guangqing Chen
Guangqing Chen

๐Ÿ’ป
Jade Meskill
Jade Meskill

๐Ÿ’ป
Jasper Poppe
Jasper Poppe

๐Ÿ’ป
Jean Jordaan
Jean Jordaan

๐Ÿ’ป
Kid
Kid

๐Ÿ’ป
Pieter van Loon
Pieter van Loon

๐Ÿ’ป
Robert Liebowitz
Robert Liebowitz

๐Ÿ’ป
Seth Messer
Seth Messer

๐Ÿ’ป
UncleBill
UncleBill

๐Ÿ’ป
ZERO
ZERO

๐Ÿ’ป
fsouza
fsouza

๐Ÿ’ป
XiaoZhang
XiaoZhang

๐Ÿ’ป
whyreal
whyreal

๐Ÿ’ป
yehuohan
yehuohan

๐Ÿ’ป
ใƒใ‚ฏใƒ€ใƒณใใ‚“
ใƒใ‚ฏใƒ€ใƒณใใ‚“

๐Ÿ’ป
Raphael
Raphael

๐Ÿ’ป
tbodt
tbodt

๐Ÿ’ป
Aaron McDaid
Aaron McDaid

๐Ÿ’ป
Aasif Versi
Aasif Versi

๐Ÿ’ป
Abner Silva
Abner Silva

๐Ÿ’ป
Adam Stankiewicz
Adam Stankiewicz

๐Ÿ’ป
Adamansky Anton
Adamansky Anton

๐Ÿ’ป
Ahmed El Gabri
Ahmed El Gabri

๐Ÿ’ป
Alexandr Kondratev
Alexandr Kondratev

๐Ÿ’ป
Andrew Shim
Andrew Shim

๐Ÿ’ป
Andy Lindeman
Andy Lindeman

๐Ÿ’ป
Augustin
Augustin

๐Ÿ’ป
Bastien Orivel
Bastien Orivel

๐Ÿ’ป
Ben Lu
Ben Lu

๐Ÿ’ป
Ben
Ben

๐Ÿ’ป
Brendan Roy
Brendan Roy

๐Ÿ’ป
brianembry
brianembry

๐Ÿ’ป
br
br

๐Ÿ’ป
Cason Adams
Cason Adams

๐Ÿ’ป
Chang Y
Chang Y

๐Ÿ’ป
Chayoung You
Chayoung You

๐Ÿ’ป
Chen Lijun
Chen Lijun

๐Ÿ’ป
Chen Mulong
Chen Mulong

๐Ÿ’ป
Chris Weyl
Chris Weyl

๐Ÿ’ป
dezza
dezza

๐Ÿ’ป
Cody Allen
Cody Allen

๐Ÿ’ป
Damien Rajon
Damien Rajon

๐Ÿ’ป
Daniel Eriksson
Daniel Eriksson

๐Ÿ’ป
Daniel Jenson
Daniel Jenson

๐Ÿ’ป
David Mejorado
David Mejorado

๐Ÿ’ป
Deric Pang
Deric Pang

๐Ÿ’ป
Ding Tao
Ding Tao

๐Ÿ’ป
Doron Behar
Doron Behar

๐Ÿ’ป
Egor Kovetskiy
Egor Kovetskiy

๐Ÿ’ป
ElKowar
ElKowar

๐Ÿ’ป
Emeliov Dmitrii
Emeliov Dmitrii

๐Ÿ’ป
Fabian Becker
Fabian Becker

๐Ÿ’ป
FallenWarrior2k
FallenWarrior2k

๐Ÿ’ป
Fausto Nรบรฑez Alberro
Fausto Nรบรฑez Alberro

๐Ÿ’ป
Felipe Ramos
Felipe Ramos

๐Ÿ’ป
Fredrik Borg
Fredrik Borg

๐Ÿ’ป
Gavin Sim
Gavin Sim

๐Ÿ’ป
Gibson Fahnestock
Gibson Fahnestock

๐Ÿ’ป
Giovanni Giordano
Giovanni Giordano

๐Ÿ’ป
Gopal Adhikari
Gopal Adhikari

๐Ÿ’ป
Hanh Le
Hanh Le

๐Ÿ’ป
hedy
hedy

๐Ÿ’ป
Hendrik Lammers
Hendrik Lammers

๐Ÿ’ป
Henry Barreto
Henry Barreto

๐Ÿ’ป
Hugo
Hugo

๐Ÿ’ป
Jackie Li
Jackie Li

๐Ÿ’ป
Jakub Nowak
Jakub Nowak

๐Ÿ’ป
James Pickard
James Pickard

๐Ÿ’ป
Jia Sui
Jia Sui

๐Ÿ’ป
Ellie Hermaszewska
Ellie Hermaszewska

๐Ÿ’ป
Joel Bradshaw
Joel Bradshaw

๐Ÿ’ป
John Carlo Roberto
John Carlo Roberto

๐Ÿ’ป
Jonas Holst Damtoft
Jonas Holst Damtoft

๐Ÿ’ป
Jonathan Lehman
Jonathan Lehman

๐Ÿ’ป
Joosep Alviste
Joosep Alviste

๐Ÿ’ป
Josa Gesell
Josa Gesell

๐Ÿ’ป
Joshua Rubin
Joshua Rubin

๐Ÿ’ป
Julian Grinblat
Julian Grinblat

๐Ÿ’ป
Julian Valentin
Julian Valentin

๐Ÿ’ป
KabbAmine
KabbAmine

๐Ÿ’ป
Kay Gosho
Kay Gosho

๐Ÿ’ป
Kenny Huynh
Kenny Huynh

๐Ÿ’ป
Kevin Rambaud
Kevin Rambaud

๐Ÿ’ป
Kian Cross
Kian Cross

๐Ÿ’ป
Kristijan Husak
Kristijan Husak

๐Ÿ’ป
NullVoxPopuli
NullVoxPopuli

๐Ÿ’ป
Lasse Peters
Lasse Peters

๐Ÿ’ป
Noel Errenil
Noel Errenil

๐Ÿ’ป
LinArcX
LinArcX

๐Ÿ’ป
Liu-Cheng Xu
Liu-Cheng Xu

๐Ÿ’ป
Marc
Marc

๐Ÿ’ป
Marius Gawrisch
Marius Gawrisch

๐Ÿ’ป
Mark Hintz
Mark Hintz

๐Ÿ’ป
Mathieu Le Tiec
Mathieu Le Tiec

๐Ÿ’ป
Matt White
Matt White

๐Ÿ’ป
Matthew Evans
Matthew Evans

๐Ÿ’ป
Me1onRind
Me1onRind

๐Ÿ’ป
Qyriad
Qyriad

๐Ÿ’ป
Narcis B.
Narcis B.

๐Ÿ’ป
Neur1n
Neur1n

๐Ÿ’ป
Nicolas Dermine
Nicolas Dermine

๐Ÿ’ป
Noah
Noah

๐Ÿ’ป
PENG Rui
PENG Rui

๐Ÿ’ป
Paco
Paco

๐Ÿ’ป
Peng Guanwen
Peng Guanwen

๐Ÿ’ป
Petter Wahlman
Petter Wahlman

๐Ÿ’ป
Pooya Moradi
Pooya Moradi

๐Ÿ’ป
Quade Morrison
Quade Morrison

๐Ÿ’ป
Ralf Vogler
Ralf Vogler

๐Ÿ’ป
Ran Chen
Ran Chen

๐Ÿ’ป
Ricardo Garcรญa Vega
Ricardo Garcรญa Vega

๐Ÿ’ป
Rick Jones
Rick Jones

๐Ÿ’ป
Ryan Christian
Ryan Christian

๐Ÿ’ป
Salo
Salo

๐Ÿ’ป
Sam Nolan
Sam Nolan

๐Ÿ’ป
Saurav
Saurav

๐Ÿ’ป
Sean Mackesey
Sean Mackesey

๐Ÿ’ป
Sheel Patel
Sheel Patel

๐Ÿ’ป
Solomon Ng
Solomon Ng

๐Ÿ’ป
Sri Kadimisetty
Sri Kadimisetty

๐Ÿ’ป
Stephen Prater
Stephen Prater

๐Ÿ’ป
Sune Kibsgaard
Sune Kibsgaard

๐Ÿ’ป
Aquaakuma
Aquaakuma

๐Ÿ’ป
Takumi Kawase
Takumi Kawase

๐Ÿ’ป
The Blob SCP
The Blob SCP

๐Ÿ’ป
Tomasz N
Tomasz N

๐Ÿ’ป
Tomoyuki Harada
Tomoyuki Harada

๐Ÿ’ป
Tony Fettes
Tony Fettes

๐Ÿ’ป
Tony Narlock
Tony Narlock

๐Ÿ’ป
Tony Wang
Tony Wang

๐Ÿ’ป
Victor Quach
Victor Quach

๐Ÿ’ป
Whisperity
Whisperity

๐Ÿ’ป
William Turner
William Turner

๐Ÿ’ป
Xiaochao Dong
Xiaochao Dong

๐Ÿ’ป
Hugh Hou
Hugh Hou

๐Ÿ’ป
Jackie Li
Jackie Li

๐Ÿ’ป
Zachary Freed
Zachary Freed

๐Ÿ’ป
akiyosi
akiyosi

๐Ÿ’ป
alexjg
alexjg

๐Ÿ’ป
aste4
aste4

๐Ÿ’ป
clyfish
clyfish

๐Ÿ’ป
dev7ba
dev7ba

๐Ÿ’ป
diartyz
diartyz

๐Ÿ’ป
doza-daniel
doza-daniel

๐Ÿ’ป
equal-l2
equal-l2

๐Ÿ’ป
fong
fong

๐Ÿ’ป
hexh
hexh

๐Ÿ’ป
hhiraba
hhiraba

๐Ÿ’ป
ic-768
ic-768

๐Ÿ’ป
javiertury
javiertury

๐Ÿ’ป
karasu
karasu

๐Ÿ’ป
kevineato
kevineato

๐Ÿ’ป
Eduardo Costa
Eduardo Costa

๐Ÿ’ป
micchy326
micchy326

๐Ÿ’ป
midchildan
midchildan

๐Ÿ’ป
minefuto
minefuto

๐Ÿ’ป
miyanokomiya
miyanokomiya

๐Ÿ’ป
miyaviee
miyaviee

๐Ÿ’ป
monkoose
monkoose

๐Ÿ’ป ๐Ÿ›
mujx
mujx

๐Ÿ’ป
mvilim
mvilim

๐Ÿ’ป
naruaway
naruaway

๐Ÿ’ป
piersy
piersy

๐Ÿ’ป
ryantig
ryantig

๐Ÿ’ป
rydesun
rydesun

๐Ÿ’ป
sc00ter
sc00ter

๐Ÿ’ป
smhc
smhc

๐Ÿ’ป
Sam Kaplan
Sam Kaplan

๐Ÿ’ป
tasuten
tasuten

๐Ÿ’ป
todesking
todesking

๐Ÿ’ป
typicode
typicode

๐Ÿ’ป
ๆŽ้ธฃ้ฃž
ๆŽ้ธฃ้ฃž

๐Ÿ’ป
Ikko Ashimine
Ikko Ashimine

๐Ÿ“–
Rammiah
Rammiah

๐Ÿ›
Alisue
Alisue

๐Ÿ›
bigshans
bigshans

๐Ÿ“–
Robert Boyd III
Robert Boyd III

๐Ÿ›
Yuki Iwanaga
Yuki Iwanaga

๐Ÿ’ป
SpringHack
SpringHack

๐Ÿ›
Lucas Burns
Lucas Burns

๐Ÿ“–
qiqiboy
qiqiboy

๐Ÿ’ป
timsu92
timsu92

๐Ÿ“–
Shawn M Moore
Shawn M Moore

๐Ÿ’ป
Aaron U'Ren
Aaron U'Ren

๐Ÿ›
SeniorMars
SeniorMars

๐Ÿ“–
็‰ง็พŠ็Šฌ็œŸQ
็‰ง็พŠ็Šฌ็œŸQ

๐Ÿ“–
geraldspreer
geraldspreer

๐Ÿ“–
Fabio
Fabio

๐Ÿ“–
Li Yunting
Li Yunting

๐Ÿ›
Jeff L.
Jeff L.

๐Ÿ’ป
+ + + + + + + + + + + + +This project follows the [all-contributors](https://allcontributors.org) specification. +Contributions of any kind are welcome! + +## License + +[Anti 996](./LICENSE.md) diff --git a/vim-config/plugins/coc.nvim/autoload/coc.vim b/vim-config/plugins/coc.nvim/autoload/coc.vim index e7bf2dfc..732bfc0a 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc.vim @@ -6,10 +6,12 @@ let g:coc_selected_text = '' let g:coc_vim_commands = [] let s:watched_keys = [] let s:is_vim = !has('nvim') -let s:error_sign = get(g:, 'coc_status_error_sign', has('mac') ? 'โŒ ' : 'E') -let s:warning_sign = get(g:, 'coc_status_warning_sign', has('mac') ? 'โš ๏ธ ' : 'W') +let s:utf = has('nvim') || &encoding =~# '^utf' +let s:error_sign = get(g:, 'coc_status_error_sign', has('mac') && s:utf ? "\u274c " : 'E ') +let s:warning_sign = get(g:, 'coc_status_warning_sign', has('mac') && s:utf ? "\u26a0\ufe0f " : 'W ') let s:select_api = exists('*nvim_select_popupmenu_item') let s:callbacks = {} +let s:hide_pum = has('nvim-0.6.1') || has('patch-8.2.3389') function! coc#expandable() abort return coc#rpc#request('snippetCheck', [1, 0]) @@ -31,89 +33,21 @@ function! coc#add_command(id, cmd, ...) call coc#rpc#notify('addCommand', [config]) endfunction -function! coc#refresh() abort - return "\=coc#start()\" -endfunction - function! coc#on_enter() call coc#rpc#notify('CocAutocmd', ['Enter', bufnr('%')]) return '' endfunction function! coc#_insert_key(method, key, ...) abort + let prefix = '' if get(a:, 1, 1) - call coc#_cancel() - endif - return "\=coc#rpc#".a:method."('doKeymap', ['".a:key."'])\" -endfunction - -function! coc#_complete() abort - let items = get(g:coc#_context, 'candidates', []) - let preselect = get(g:coc#_context, 'preselect', -1) - let startcol = g:coc#_context.start + 1 - if s:select_api && len(items) && preselect != -1 - noa call complete(startcol, items) - call nvim_select_popupmenu_item(preselect, v:false, v:false, {}) - " use specific key to preselect item at once - call feedkeys("\\" , 'i') - else - call complete(startcol, items) - endif - return '' -endfunction - -function! coc#_do_complete(start, items, preselect) - let g:coc#_context = { - \ 'start': a:start, - \ 'candidates': a:items, - \ 'preselect': a:preselect - \} - if mode() =~# 'i' && &paste != 1 - call feedkeys("\CocRefresh", 'i') - endif -endfunction - -function! coc#_select_confirm() abort - if !exists('*complete_info') - throw 'coc#_select_confirm requires complete_info function to work' - endif - let selected = complete_info()['selected'] - if selected != -1 - return "\" - elseif pumvisible() - return "\\" + if coc#pum#visible() + let prefix = "\=coc#pum#close()\" + elseif pumvisible() && s:hide_pum + let prefix = "\\" + endif endif - return '' -endfunction - -function! coc#_selected() - if !pumvisible() | return 0 | endif - return coc#rpc#request('hasSelected', []) -endfunction - -function! coc#_hide() abort - if !pumvisible() | return | endif - call feedkeys("\", 'in') -endfunction - -function! coc#_cancel() - " hack for close pum - if pumvisible() - let g:coc#_context = {'start': 0, 'preselect': -1,'candidates': []} - call feedkeys("\CocRefresh", 'i') - call coc#rpc#notify('stopCompletion', []) - endif -endfunction - -function! coc#_select() abort - if !pumvisible() | return | endif - call feedkeys("\", 'in') -endfunction - -function! coc#start(...) - let opt = coc#util#get_complete_option() - call CocActionAsync('startCompletion', extend(opt, get(a:, 1, {}))) - return '' + return prefix."\=coc#rpc#".a:method."('doKeymap', ['".a:key."'])\" endfunction " used for statusline @@ -126,14 +60,7 @@ function! coc#status() if !empty(info) && get(info, 'warning', 0) call add(msgs, s:warning_sign . info['warning']) endif - return s:trim(join(msgs, ' ') . ' ' . get(g:, 'coc_status', '')) -endfunction - -function! s:trim(str) - if exists('*trim') - return trim(a:str) - endif - return substitute(a:str, '\s\+$', '', '') + return coc#compat#trim(join(msgs, ' ') . ' ' . get(g:, 'coc_status', '')) endfunction function! coc#config(section, value) @@ -167,24 +94,10 @@ function! s:GlobalChange(dict, key, val) call coc#rpc#notify('GlobalChange', [a:key, get(a:val, 'old', v:null), get(a:val, 'new', v:null)]) endfunction -function! coc#_map() - if !s:select_api | return | endif - for i in range(1, 9) - exe 'inoremap '.i.' call nvim_select_popupmenu_item('.(i - 1).', v:true, v:true, {})' - endfor -endfunction - -function! coc#_unmap() - if !s:select_api | return | endif - for i in range(1, 9) - exe 'silent! iunmap '.i - endfor -endfunction - function! coc#on_notify(id, method, Cb) let key = a:id. '-'.a:method let s:callbacks[key] = a:Cb - call coc#rpc#notify('registNotification', [a:id, a:method]) + call coc#rpc#notify('registerNotification', [a:id, a:method]) endfunction function! coc#do_notify(id, method, result) @@ -194,3 +107,40 @@ function! coc#do_notify(id, method, result) call Fn(a:result) endif endfunction + +" Deprecated, not used any more +function! coc#_complete() abort + let items = get(g:coc#_context, 'candidates', []) + let preselect = get(g:coc#_context, 'preselect', -1) + let startcol = g:coc#_context.start + 1 + if s:select_api && len(items) && preselect != -1 + noa call complete(startcol, items) + call nvim_select_popupmenu_item(preselect, v:false, v:false, {}) + " use specific key to preselect item at once + call feedkeys("\\" , 'i') + else + if pumvisible() + let g:coc_disable_complete_done = 1 + endif + call complete(startcol, items) + endif + return '' +endfunction + +function! coc#start(...) + call CocActionAsync('startCompletion', get(a:, 1, {})) + return '' +endfunction + +" Could be used by coc extensions +function! coc#_cancel(...) + call coc#pum#close() +endfunction + +function! coc#refresh() abort + return "\=coc#start()\" +endfunction + +function! coc#_select_confirm() abort + return "\=coc#pum#select_confirm()\" +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/api.vim b/vim-config/plugins/coc.nvim/autoload/coc/api.vim index 3dc4ae31..429e0db9 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/api.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/api.vim @@ -1,17 +1,124 @@ " ============================================================================ " Description: Client api used by vim8 " Author: Qiming Zhao -" Licence: MIT licence -" Last Modified: Aug 10, 2021 +" Licence: Anti 996 licence +" Last Modified: 2022-12-20 " ============================================================================ -if has('nvim') | finish | endif +if has('nvim') + finish +endif + scriptencoding utf-8 let s:funcs = {} let s:prop_offset = get(g:, 'coc_text_prop_offset', 1000) let s:namespace_id = 1 let s:namespace_cache = {} +let s:max_src_id = 1000 +" bufnr => max textprop id +let s:buffer_id = {} +" srcId => list of types +let s:id_types = {} +let s:tab_id = 1 +let s:keymap_arguments = ['nowait', 'silent', 'script', 'expr', 'unique'] " helper {{ +" Create a window with bufnr for execute win_execute +function! s:create_popup(bufnr) abort + noa let id = popup_create(1, { + \ 'line': 1, + \ 'col': &columns, + \ 'maxwidth': 1, + \ 'maxheight': 1, + \ }) + call popup_hide(id) + return id +endfunction + +function! s:check_bufnr(bufnr) abort + if !bufloaded(a:bufnr) + throw 'Invalid buffer id: '.a:bufnr + endif +endfunction + +" TextChanged not fired when using channel on vim. +function! s:on_textchange(bufnr) abort + let event = mode() ==# 'i' ? 'TextChangedI' : 'TextChanged' + exe 'doautocmd '.event.' '.bufname(a:bufnr) +endfunction + +" execute command for bufnr +function! s:buf_execute(bufnr, cmds) abort + call s:check_bufnr(a:bufnr) + let winid = get(win_findbuf(a:bufnr), 0, -1) + let close = 0 + if winid == -1 + let winid = s:create_popup(a:bufnr) + let close = 1 + endif + for cmd in a:cmds + call win_execute(winid, cmd, 'silent') + endfor + if close + noa call popup_close(winid) + endif +endfunction + +function! s:check_winid(winid) abort + if empty(getwininfo(a:winid)) && empty(popup_getpos(a:winid)) + throw 'Invalid window id: '.a:winid + endif +endfunction + +function! s:is_popup(winid) abort + try + return !empty(popup_getpos(a:winid)) + catch /^Vim\%((\a\+)\)\=:E993/ + return 0 + endtry +endfunction + +function! s:tabid_nr(tid) abort + for nr in range(1, tabpagenr('$')) + if gettabvar(nr, '__tid', v:null) is a:tid + return nr + endif + endfor + throw 'Invalid tabpage id: '.a:tid +endfunction + +function! s:tabnr_id(nr) abort + let tid = gettabvar(a:nr, '__tid', -1) + if tid == -1 + let tid = s:tab_id + call settabvar(a:nr, '__tid', tid) + let s:tab_id = s:tab_id + 1 + endif + return tid +endfunction + +function! s:generate_id(bufnr) abort + let max = get(s:buffer_id, a:bufnr, s:prop_offset) + let id = max + 1 + let s:buffer_id[a:bufnr] = id + return id +endfunction + +function! s:win_execute(winid, cmd, ...) abort + let ref = get(a:000, 0, v:null) + let cmd = ref is v:null ? a:cmd : 'let ref["out"] = ' . a:cmd + call win_execute(a:winid, cmd) +endfunction + +function! s:win_tabnr(winid) abort + let ref = {} + call win_execute(a:winid, 'let ref["out"] = tabpagenr()') + let tabnr = get(ref, 'out', -1) + if tabnr == -1 + throw 'Invalid window id: '.a:winid + endif + return tabnr +endfunction + function! s:buf_line_count(bufnr) abort if bufnr('%') == a:bufnr return line('$') @@ -21,17 +128,12 @@ function! s:buf_line_count(bufnr) abort if empty(info) return 0 endif - return info[0]['linecount'] - endif - if exists('*getbufline') - let lines = getbufline(a:bufnr, 1, '$') - return len(lines) + " vim 8.1 has getbufinfo but no linecount + if has_key(info[0], 'linecount') + return info[0]['linecount'] + endif endif - let curr = bufnr('%') - execute 'buffer '.a:bufnr - let n = line('$') - execute 'buffer '.curr - return n + return len(getbufline(a:bufnr, 1, '$')) endfunction function! s:execute(cmd) @@ -41,71 +143,111 @@ function! s:execute(cmd) silent! execute a:cmd endif endfunction + +function s:inspect_type(v) abort + let types = ['Number', 'String', 'Funcref', 'List', 'Dictionary', 'Float', 'Boolean', 'Null'] + return get(types, type(a:v), 'Unknown') +endfunction + +function! s:escape_space(text) abort + return substitute(a:text, ' ', '', 'g') +endfunction + +function! s:create_mode_prefix(mode, opts) abort + if a:mode ==# '!' + return 'map!' + endif + return get(a:opts, 'noremap', 0) ? a:mode . 'noremap' : a:mode . 'map' +endfunction + +function! s:create_arguments(opts) abort + let arguments = '' + for key in keys(a:opts) + if a:opts[key] && index(s:keymap_arguments, key) != -1 + let arguments .= '<'.key.'>' + endif + endfor + return arguments +endfunction " }}" " nvim client methods {{ function! s:funcs.set_current_dir(dir) abort - execute 'cd '.a:dir + execute 'cd '.fnameescape(a:dir) + return v:null endfunction function! s:funcs.set_var(name, value) abort execute 'let g:'.a:name.'= a:value' + return v:null endfunction function! s:funcs.del_var(name) abort + if !has_key(g:, a:name) + throw 'Key not found: '.a:name + endif execute 'unlet g:'.a:name + return v:null endfunction function! s:funcs.set_option(name, value) abort execute 'let &'.a:name.' = a:value' + return v:null +endfunction + +function! s:funcs.get_option(name) + return eval('&'.a:name) endfunction function! s:funcs.set_current_buf(bufnr) abort - if !bufexists(a:bufnr) | return | endif + call s:check_bufnr(a:bufnr) execute 'buffer '.a:bufnr + return v:null endfunction -function! s:funcs.set_current_win(win_id) abort - let [tabnr, winnr] = win_id2tabwin(a:win_id) - if tabnr == 0 | return | endif - execute 'normal! '.tabnr.'gt' - execute winnr.' wincmd w' +function! s:funcs.set_current_win(winid) abort + call s:win_tabnr(a:winid) + call win_gotoid(a:winid) + return v:null endfunction -function! s:funcs.set_current_tabpage(tabnr) abort - execute 'normal! '.a:tabnr.'gt' +function! s:funcs.set_current_tabpage(tid) abort + let nr = s:tabid_nr(a:tid) + execute 'normal! '.nr.'gt' + return v:null endfunction function! s:funcs.list_wins() abort return map(getwininfo(), 'v:val["winid"]') endfunction -function s:inspect_type(v) abort - let types = ['Number', 'String', 'Funcref', 'List', 'Dictionary', 'Float', 'Boolean', 'Null'] - return get(types, type(a:v), 'Unknown') -endfunction - function! s:funcs.call_atomic(calls) - let res = [] + let results = [] for i in range(len(a:calls)) let [key, arglist] = a:calls[i] let name = key[5:] try - call add(res, call(s:funcs[name], arglist)) + call add(results, call(s:funcs[name], arglist)) catch /.*/ - return [res, [i, "VimException(".s:inspect_type(v:exception).")", v:exception]] + return [results, [i, "VimException(".s:inspect_type(v:exception).")", v:exception . ' on function "'.name.'"']] endtry endfor - return [res, v:null] + return [results, v:null] endfunction function! s:funcs.set_client_info(...) abort + " not supported + return v:null endfunction function! s:funcs.subscribe(...) abort + " not supported + return v:null endfunction function! s:funcs.unsubscribe(...) abort + " not supported + return v:null endfunction function! s:funcs.call_function(method, args) abort @@ -113,6 +255,9 @@ function! s:funcs.call_function(method, args) abort endfunction function! s:funcs.call_dict_function(dict, method, args) abort + if type(a:dict) == v:t_string + return call(a:method, a:args, eval(a:dict)) + endif return call(a:method, a:args, a:dict) endfunction @@ -137,35 +282,72 @@ endfunction function! s:funcs.get_api_info() let names = coc#api#func_names() - return [1, {'functions': map(names, '{"name": "nvim_".v:val}')}] + let channel = coc#rpc#get_channel() + if empty(channel) + throw 'Unable to get channel' + endif + return [ch_info(channel)['id'], {'functions': map(names, '{"name": "nvim_".v:val}')}] endfunction function! s:funcs.list_bufs() - return map(getbufinfo({'bufloaded': 1}), 'v:val["bufnr"]') + return map(getbufinfo(), 'v:val["bufnr"]') endfunction function! s:funcs.feedkeys(keys, mode, escape_csi) call feedkeys(a:keys, a:mode) + return v:null endfunction function! s:funcs.list_runtime_paths() - return split(&runtimepath, ',') + return globpath(&runtimepath, '', 0, 1) endfunction function! s:funcs.command_output(cmd) return execute(a:cmd) endfunction +function! s:funcs.exec(code, output) abort + let cmds = split(a:code, '\n') + if a:output + return substitute(execute(cmds, 'silent!'), '^\n', '', '') + endif + call execute(cmds) + return v:null +endfunction + +" Queues raw user-input, <" is special. To input a literal "<", send . +function! s:funcs.input(keys) abort + let escaped = substitute(a:keys, '<', '\\<', 'g') + call feedkeys(eval('"'.escaped.'"'), 't') + return v:null +endfunction + +function! s:funcs.create_buf(listed, scratch) abort + let bufnr = bufadd('') + call setbufvar(bufnr, '&buflisted', a:listed ? 1 : 0) + if a:scratch + call setbufvar(bufnr, '&modeline', 0) + call setbufvar(bufnr, '&buftype', 'nofile') + call setbufvar(bufnr, '&swapfile', 0) + endif + call bufload(bufnr) + return bufnr +endfunction + function! s:funcs.get_current_line() return getline('.') endfunction function! s:funcs.set_current_line(line) call setline('.', a:line) + call s:on_textchange(bufnr('%')) + return v:null endfunction -function! s:funcs.del_current_line(line) - execute 'normal! dd' +function! s:funcs.del_current_line() + call deletebufline('%', line('.')) + call s:on_textchange(bufnr('%')) + return v:null endfunction function! s:funcs.get_var(var) @@ -176,10 +358,6 @@ function! s:funcs.get_vvar(var) return get(v:, a:var, v:null) endfunction -function! s:funcs.get_option(name) - return eval('&'.a:name) -endfunction - function! s:funcs.get_current_buf() return bufnr('%') endfunction @@ -189,15 +367,20 @@ function! s:funcs.get_current_win() endfunction function! s:funcs.get_current_tabpage() - return tabpagenr() + return s:tabnr_id(tabpagenr()) endfunction function! s:funcs.list_tabpages() - return range(1, tabpagenr('$')) + let ids = [] + for nr in range(1, tabpagenr('$')) + call add(ids, s:tabnr_id(nr)) + endfor + return ids endfunction function! s:funcs.get_mode() - return {'blocking': v:false, 'mode': mode()} + let m = mode() + return {'blocking': m ==# 'r' ? v:true : v:false, 'mode': m} endfunction function! s:funcs.strwidth(str) @@ -234,6 +417,22 @@ function! s:funcs.create_namespace(name) abort endif return id endfunction + +function! s:funcs.set_keymap(mode, lhs, rhs, opts) abort + let modekey = s:create_mode_prefix(a:mode, a:opts) + let arguments = s:create_arguments(a:opts) + let lhs = s:escape_space(a:lhs) + let rhs = empty(a:rhs) ? '' : s:escape_space(a:rhs) + let cmd = modekey . ' ' . arguments .' '.lhs. ' '.rhs + execute cmd + return v:null +endfunction + +function! s:funcs.del_keymap(mode, lhs) abort + let lhs = substitute(a:lhs, ' ', '', 'g') + execute 'silent '.a:mode.'unmap '.lhs + return v:null +endfunction " }} " buffer methods {{ @@ -244,7 +443,13 @@ function! s:funcs.buf_set_option(bufnr, name, val) elseif val is v:false let val = 0 endif - return setbufvar(a:bufnr, '&'.a:name, val) + call setbufvar(a:bufnr, '&'.a:name, val) + return v:null +endfunction + +function! s:funcs.buf_get_option(bufnr, name) + call s:check_bufnr(a:bufnr) + return getbufvar(a:bufnr, '&'.a:name) endfunction function! s:funcs.buf_get_changedtick(bufnr) @@ -252,49 +457,44 @@ function! s:funcs.buf_get_changedtick(bufnr) endfunction function! s:funcs.buf_is_valid(bufnr) + return bufexists(a:bufnr) ? v:true : v:false +endfunction + +function! s:funcs.buf_is_loaded(bufnr) return bufloaded(a:bufnr) ? v:true : v:false endfunction function! s:funcs.buf_get_mark(bufnr, name) - let nr = bufnr('%') - if a:bufnr != 0 || a:bufnr != nr + if a:bufnr != 0 && a:bufnr != bufnr('%') throw 'buf_get_mark support current buffer only' endif - return [line("'" . a:name), col("'" . a:name)] + return [line("'" . a:name), col("'" . a:name) - 1] endfunction -function! s:funcs.buf_add_highlight(bufnr, srcId, hlGroup, line, colStart, colEnd) abort - if !has('textprop') || !has('patch-8.1.1719') - return +function! s:funcs.buf_add_highlight(bufnr, srcId, hlGroup, line, colStart, colEnd, ...) abort + if a:srcId == 0 + let srcId = s:max_src_id + 1 + let s:max_src_id = srcId + else + let srcId = a:srcId endif let bufnr = a:bufnr == 0 ? bufnr('%') : a:bufnr - let type = 'CocHighlight'.a:hlGroup - if empty(prop_type_get(type)) - call prop_type_add(type, {'highlight': a:hlGroup, 'combine': 1}) - endif - let total = strlen(getbufline(bufnr, a:line + 1)[0]) - let end = a:colEnd - if end == -1 - let end = total - else - let end = min([end, total]) + let type = srcId == -1 ? a:hlGroup : a:hlGroup.'_'.srcId + let types = get(s:id_types, srcId, []) + if index(types, type) == -1 + call add(types, type) + let s:id_types[srcId] = types + if empty(prop_type_get(type)) + call prop_type_add(type, extend({'highlight': a:hlGroup}, get(a:, 1, {}))) + endif endif - if end <= a:colStart + let end = a:colEnd == -1 ? strlen(get(getbufline(bufnr, a:line + 1), 0, '')) + 1 : a:colEnd + 1 + if end < a:colStart + 1 return endif - let srcId = a:srcId - if srcId == 0 - while v:true - let srcId = srcId + 1 - if empty(prop_find({'id': s:prop_offset + srcId, 'lnum' : 1})) - break - endif - endwhile - " generate srcId - endif - let id = srcId == -1 ? 0 : s:prop_offset + srcId + let id = s:generate_id(a:bufnr) try - call prop_add(a:line + 1, a:colStart + 1, {'length': end - a:colStart, 'bufnr': bufnr, 'type': type, 'id': id}) + call prop_add(a:line + 1, a:colStart + 1, {'bufnr': bufnr, 'type': type, 'id': id, 'end_col': end}) catch /^Vim\%((\a\+)\)\=:E967/ " ignore 967 endtry @@ -302,27 +502,32 @@ function! s:funcs.buf_add_highlight(bufnr, srcId, hlGroup, line, colStart, colEn " return generated srcId return srcId endif + return v:null endfunction function! s:funcs.buf_clear_namespace(bufnr, srcId, startLine, endLine) abort - if !has('textprop') || !has('patch-8.1.1719') - return - endif let bufnr = a:bufnr == 0 ? bufnr('%') : a:bufnr let start = a:startLine + 1 - let end = a:endLine == -1 ? len(getbufline(bufnr, 1, '$')) : a:endLine + 1 + let end = a:endLine == -1 ? len(getbufline(bufnr, 1, '$')) : a:endLine if a:srcId == -1 + if has_key(s:buffer_id, a:bufnr) + unlet s:buffer_id[a:bufnr] + endif call prop_clear(start, end, {'bufnr' : bufnr}) else - try - call prop_remove({'bufnr': bufnr, 'all': 1, 'id': s:prop_offset + a:srcId}, start, end) - catch /^Vim\%((\a\+)\)\=:E968/ - " ignore 968 - endtry + for type in get(s:id_types, a:srcId, []) + try + call prop_remove({'bufnr': bufnr, 'all': 1, 'type': type}, start, end) + catch /^Vim\%((\a\+)\)\=:E968/ + " ignore 968 + endtry + endfor endif + return v:null endfunction function! s:funcs.buf_line_count(bufnr) abort + call s:check_bufnr(a:bufnr) return s:buf_line_count(a:bufnr) endfunction @@ -337,282 +542,319 @@ function! s:funcs.buf_detach() endfunction function! s:funcs.buf_get_lines(bufnr, start, end, strict) abort - let lines = getbufline(a:bufnr, 1, '$') - let start = a:start < 0 ? a:start + 1 : a:start - let end = a:end < 0 ? a:end + 1 : a:end - if a:strict && end > len(lines) - throw 'line number out of range: '. end + call s:check_bufnr(a:bufnr) + let len = s:buf_line_count(a:bufnr) + let start = a:start < 0 ? len + a:start + 2 : a:start + 1 + let end = a:end < 0 ? len + a:end + 1 : a:end + if a:strict && end > len + throw 'Index out of bounds '. end endif - return lines[start : end - 1] + return getbufline(a:bufnr, start, end) endfunction function! s:funcs.buf_set_lines(bufnr, start, end, strict, ...) abort - if !bufloaded(a:bufnr) - return - endif - let replacement = get(a:, 1, []) - let lineCount = s:buf_line_count(a:bufnr) - let startLnum = a:start >= 0 ? a:start + 1 : lineCount + a:start + 1 - let end = a:end >= 0 ? a:end : lineCount + a:end + 1 - if end == lineCount + 1 - let end = lineCount - endif - let delCount = end - (startLnum - 1) - let changeBuffer = 0 - let curr = bufnr('%') - if a:bufnr != curr && !exists('*setbufline') - let changeBuffer = 1 - exe 'buffer '.a:bufnr - endif - if a:bufnr == curr || changeBuffer - " replace - let storeView = winsaveview() - if delCount == len(replacement) - call setline(startLnum, replacement) + call s:check_bufnr(a:bufnr) + let bufnr = a:bufnr == 0 ? bufnr('%') : a:bufnr + let len = s:buf_line_count(bufnr) + let startLnum = a:start < 0 ? len + a:start + 2 : a:start + 1 + let endLnum = a:end < 0 ? len + a:end + 1 : a:end + if endLnum > len + if a:strict + throw 'Index out of bounds '. end else - if len(replacement) - call append(startLnum - 1, replacement) - endif - if delCount - let start = startLnum + len(replacement) - let saved_reg = @" - silent execute start . ','.(start + delCount - 1).'d' - let @" = saved_reg - endif + let endLnum = len endif - call winrestview(storeView) - if changeBuffer - exe 'buffer '.curr + endif + let delCount = endLnum - (startLnum - 1) + let view = bufnr == bufnr('%') ? winsaveview() : v:null + let replacement = get(a:, 1, []) + if delCount == len(replacement) + call setbufline(bufnr, startLnum, replacement) + else + if len(replacement) + call appendbufline(bufnr, startLnum - 1, replacement) endif - elseif exists('*setbufline') - " replace - if delCount == len(replacement) - " 8.0.1039 - call setbufline(a:bufnr, startLnum, replacement) - else - if len(replacement) - " 8.10037 - call appendbufline(a:bufnr, startLnum - 1, replacement) - endif - if delCount - let start = startLnum + len(replacement) - "8.1.0039 - silent call deletebufline(a:bufnr, start, start + delCount - 1) - endif + if delCount + let start = startLnum + len(replacement) + silent call deletebufline(bufnr, start, start + delCount - 1) endif endif + if view isnot v:null + call winrestview(view) + endif + call s:on_textchange(a:bufnr) + return v:null endfunction function! s:funcs.buf_set_name(bufnr, name) abort - let nr = bufnr('%') - if a:bufnr != nr - throw 'buf_set_name support current buffer only' - else - execute '0f' - execute 'file '.fnameescape(a:name) - endif + call s:check_bufnr(a:bufnr) + call s:buf_execute(a:bufnr, [ + \ 'noa 0f', + \ 'file '.fnameescape(a:name) + \ ]) + return v:null +endfunction + +function! s:funcs.buf_get_name(bufnr) + call s:check_bufnr(a:bufnr) + return bufname(a:bufnr) endfunction function! s:funcs.buf_get_var(bufnr, name) + call s:check_bufnr(a:bufnr) + if !has_key(b:, a:name) + throw 'Key not found: '.a:name + endif return getbufvar(a:bufnr, a:name) endfunction function! s:funcs.buf_set_var(bufnr, name, val) - if !bufloaded(a:bufnr) | return | endif + call s:check_bufnr(a:bufnr) call setbufvar(a:bufnr, a:name, a:val) + return v:null endfunction function! s:funcs.buf_del_var(bufnr, name) - call coc#compat#buf_del_var(a:bufnr, a:name) + call s:check_bufnr(a:bufnr) + if a:bufnr == bufnr('%') + execute 'unlet! b:'.a:name + else + call s:buf_execute(a:bufnr, ['unlet! b:'.a:name]) + endif + return v:null endfunction -function! s:funcs.buf_get_option(bufnr, name) - return getbufvar(a:bufnr, '&'.a:name) +function! s:funcs.buf_set_keymap(bufnr, mode, lhs, rhs, opts) abort + let modekey = s:create_mode_prefix(a:mode, a:opts) + let arguments = s:create_arguments(a:opts) + let lhs = s:escape_space(a:lhs) + let rhs = empty(a:rhs) ? '' : s:escape_space(a:rhs) + let cmd = modekey . ' ' . arguments .' '.lhs. ' '.rhs + if bufnr('%') == a:bufnr || a:bufnr == 0 + execute cmd + else + call s:buf_execute(a:bufnr, [cmd]) + endif + return v:null endfunction -function! s:funcs.buf_get_name(bufnr) - return bufname(a:bufnr) +function! s:funcs.buf_del_keymap(bufnr, mode, lhs) abort + let lhs = substitute(a:lhs, ' ', '', 'g') + let cmd = 'silent '.a:mode.'unmap '.lhs + if bufnr('%') == a:bufnr || a:bufnr == 0 + execute cmd + else + call s:buf_execute(a:bufnr, [cmd]) + endif + return v:null endfunction " }} " window methods {{ function! s:funcs.win_get_buf(winid) + call s:check_winid(a:winid) return winbufnr(a:winid) endfunction -function! s:funcs.win_get_position(win_id) abort - let [row, col] = win_screenpos(a:win_id) +function! s:funcs.win_set_buf(winid, bufnr) abort + call s:check_winid(a:winid) + call s:check_bufnr(a:bufnr) + call s:win_execute(a:winid, 'buffer '.a:bufnr) + return v:null +endfunction + +function! s:funcs.win_get_position(winid) abort + let [row, col] = win_screenpos(a:winid) if row == 0 && col == 0 - throw 'Invalid window '.a:win_id + throw 'Invalid window '.a:winid endif return [row - 1, col - 1] endfunction -function! s:funcs.win_get_height(win_id) abort - return winheight(a:win_id) -endfunction - -function! s:funcs.win_get_width(win_id) abort - return winwidth(a:win_id) -endfunction - -if exists('*win_execute') - function! s:win_execute(win_id, cmd, ...) abort - let ref = get(a:000, 0, v:null) - let cmd = ref is v:null ? a:cmd : 'let ref["out"] = ' . a:cmd - call win_execute(a:win_id, cmd) - endfunction -else - function! s:win_execute(win_id, cmd, ...) abort - let ref = get(a:000, 0, v:null) - let cmd = ref is v:null ? a:cmd : 'let ref["out"] = ' . a:cmd - let winid = win_getid() - if winid == a:win_id - execute cmd - else - let goto_status = win_gotoid(a:win_id) - if !goto_status - return - endif - execute cmd - call win_gotoid(winid) - endif - endfunction -endif - -function! s:get_tabnr(winid) abort - let ref = {} - call s:win_execute(a:winid, 'tabpagenr()', ref) - return get(ref, 'out', 0) -endfunction - -function! s:funcs.win_get_cursor(win_id) abort - let ref = {} - call s:win_execute(a:win_id, "[line('.'), col('.')-1]", ref) - return get(ref, 'out', 0) +function! s:funcs.win_set_height(winid, height) abort + call s:check_winid(a:winid) + if s:is_popup(a:winid) + call popup_move(a:winid, {'maxheight': a:height, 'minheight': a:height}) + else + call s:win_execute(a:winid, 'resize '.a:height) + endif + return v:null endfunction -function! s:funcs.win_get_var(win_id, name) abort - let tabnr = s:get_tabnr(a:win_id) - if tabnr - return gettabwinvar(tabnr, a:win_id, a:name) +function! s:funcs.win_get_height(winid) abort + call s:check_winid(a:winid) + if s:is_popup(a:winid) + return popup_getpos(a:winid)['height'] endif - throw 'window '.a:win_id. ' not a valid window' + return winheight(a:winid) endfunction -function! s:funcs.win_set_width(win_id, width) abort - call s:win_execute(a:win_id, 'vertical resize '.a:width) +function! s:funcs.win_set_width(winid, width) abort + call s:check_winid(a:winid) + if s:is_popup(a:winid) + call popup_move(a:winid, {'maxwidth': a:width, 'minwidth': a:width}) + else + call s:win_execute(a:winid, 'vertical resize '.a:width) + endif + return v:null endfunction -function! s:funcs.win_set_buf(win_id, buf_id) abort - call s:win_execute(a:win_id, 'buffer '.a:buf_id) +function! s:funcs.win_get_width(winid) abort + call s:check_winid(a:winid) + if s:is_popup(a:winid) + return popup_getpos(a:winid)['width'] + endif + return winwidth(a:winid) endfunction -function! s:funcs.win_get_option(win_id, name) abort - let tabnr = s:get_tabnr(a:win_id) - if tabnr - return gettabwinvar(tabnr, a:win_id, '&'.a:name) - endif - throw 'window '.a:win_id. ' not a valid window' +function! s:funcs.win_set_cursor(winid, pos) abort + call s:check_winid(a:winid) + let [line, col] = a:pos + call s:win_execute(a:winid, 'call cursor('.line.','.(col + 1).')') + return v:null endfunction -function! s:funcs.win_set_height(win_id, height) abort - return s:win_execute(a:win_id, 'resize '.a:height) +function! s:funcs.win_get_cursor(winid) abort + call s:check_winid(a:winid) + let ref = {} + call s:win_execute(a:winid, "[line('.'), col('.')-1]", ref) + return get(ref, 'out', [1, 0]) endfunction -function! s:funcs.win_set_option(win_id, name, value) abort +function! s:funcs.win_set_option(winid, name, value) abort + let tabnr = s:win_tabnr(a:winid) let val = a:value if val is v:true let val = 1 elseif val is v:false let val = 0 endif - let tabnr = s:get_tabnr(a:win_id) - if tabnr - call settabwinvar(tabnr, a:win_id, '&'.a:name, val) - else - throw 'window '.a:win_id. ' not a valid window' - endif + call settabwinvar(tabnr, a:winid, '&'.a:name, val) + return v:null endfunction -function! s:funcs.win_set_var(win_id, name, value) abort - let tabnr = s:get_tabnr(a:win_id) - if tabnr - call settabwinvar(tabnr, a:win_id, a:name, a:value) - else - throw 'window '.a:win_id. ' not a valid window' +function! s:funcs.win_get_option(winid, name, ...) abort + let tabnr = s:win_tabnr(a:winid) + let result = gettabwinvar(tabnr, a:winid, '&'.a:name, get(a:, 1, v:null)) + if result is v:null + throw "Invalid option name: '".a:name."'" endif + return result +endfunction + +function! s:funcs.win_get_var(winid, name, ...) abort + let tabnr = s:win_tabnr(a:winid) + return gettabwinvar(tabnr, a:winid, a:name, get(a:, 1, v:null)) endfunction -function! s:funcs.win_del_var(win_id, name) abort - call s:win_execute(a:win_id, 'unlet! w:'.a:name) +function! s:funcs.win_set_var(winid, name, value) abort + let tabnr = s:win_tabnr(a:winid) + call settabwinvar(tabnr, a:winid, a:name, a:value) + return v:null endfunction -function! s:funcs.win_is_valid(win_id) abort - let info = getwininfo(a:win_id) - return empty(info) ? v:false : v:true +function! s:funcs.win_del_var(winid, name) abort + call s:check_winid(a:winid) + call win_execute(a:winid, 'unlet! w:'.a:name) + return v:null endfunction -function! s:funcs.win_get_number(win_id) abort - let info = getwininfo(a:win_id) +function! s:funcs.win_is_valid(winid) abort + let invalid = empty(getwininfo(a:winid)) && empty(popup_getpos(a:winid)) + return invalid ? v:false : v:true +endfunction + +" Not work for popup +function! s:funcs.win_get_number(winid) abort + if s:is_popup(a:winid) + return 0 + endif + let info = getwininfo(a:winid) if empty(info) - throw 'Invalid window id '.a:win_id + throw 'Invalid window id '.a:winid endif return info[0]['winnr'] endfunction -function! s:funcs.win_set_cursor(win_id, pos) abort - let [line, col] = a:pos - call s:win_execute(a:win_id, 'call cursor('.line.','.(col + 1).')') +function! s:funcs.win_get_tabpage(winid) abort + let nr = s:win_tabnr(a:winid) + return s:tabnr_id(nr) endfunction -function! s:funcs.win_close(win_id, ...) abort +function! s:funcs.win_close(winid, ...) abort + call s:check_winid(a:winid) let force = get(a:, 1, 0) - call s:win_execute(a:win_id, 'close'.(force ? '!' : '')) -endfunction - -function! s:funcs.win_get_tabpage(win_id) abort - let tabnr = s:get_tabnr(a:win_id) - if !tabnr - throw 'Invalid window id '.a:win_id + if s:is_popup(a:winid) + call popup_close(a:winid) + else + call s:win_execute(a:winid, 'close'.(force ? '!' : '')) endif - return tabnr + return v:null endfunction " }} " tabpage methods {{ -function! s:funcs.tabpage_get_number(id) - return a:id +function! s:funcs.tabpage_get_number(tid) + return s:tabid_nr(a:tid) endfunction -function! s:funcs.tabpage_list_wins(tabnr) - let info = getwininfo() - return map(filter(info, 'v:val["tabnr"] == a:tabnr'), 'v:val["winid"]') +function! s:funcs.tabpage_list_wins(tid) + let nr = s:tabid_nr(a:tid) + return gettabinfo(nr)[0]['windows'] endfunction -function! s:funcs.tabpage_get_var(tabnr, name) - return gettabvar(a:tabnr, a:name, v:null) +function! s:funcs.tabpage_get_var(tid, name) + let nr = s:tabid_nr(a:tid) + return gettabvar(nr, a:name, v:null) endfunction -function! s:funcs.tabpage_set_var(tabnr, name, value) - call settabvar(a:tabnr, a:name, a:value) +function! s:funcs.tabpage_set_var(tid, name, value) + let nr = s:tabid_nr(a:tid) + call settabvar(nr, a:name, a:value) + return v:null endfunction -function! s:funcs.tabpage_del_var(tabnr, name) - call settabvar(a:tabnr, a:name, v:null) +function! s:funcs.tabpage_del_var(tid, name) + let nr = s:tabid_nr(a:tid) + call settabvar(nr, a:name, v:null) + return v:null endfunction -function! s:funcs.tabpage_is_valid(tabnr) - let max = tabpagenr('$') - return a:tabnr <= max +function! s:funcs.tabpage_is_valid(tid) + for nr in range(1, tabpagenr('$')) + if gettabvar(nr, '__tid', -1) == a:tid + return v:true + endif + endfor + return v:false endfunction -function! s:funcs.tabpage_get_win(tabnr) - let wnr = tabpagewinnr(a:tabnr) - return win_getid(wnr, a:tabnr) +function! s:funcs.tabpage_get_win(tid) + let nr = s:tabid_nr(a:tid) + return win_getid(tabpagewinnr(nr), nr) endfunction " }} +function! coc#api#get_types(srcId) abort + return get(s:id_types, a:srcId, []) +endfunction + +function! coc#api#get_id_types() abort + return s:id_types +endfunction + +function! coc#api#create_type(srcId, hlGroup, opts) abort + let type = a:hlGroup.'_'.a:srcId + let types = get(s:id_types, a:srcId, []) + if index(types, type) == -1 + call add(types, type) + let s:id_types[a:srcId] = types + let combine = get(a:opts, 'hl_mode', 'combine') ==# 'combine' + call prop_type_add(type, {'highlight': a:hlGroup, 'combine': combine}) + endif + return type +endfunction + function! coc#api#func_names() abort return keys(s:funcs) endfunction @@ -623,12 +865,34 @@ function! coc#api#call(method, args) abort try let res = call(s:funcs[a:method], a:args) catch /.*/ - let err = v:exception + let err = v:exception .' on api "'.a:method.'" '.json_encode(a:args) endtry return [err, res] endfunction +function! coc#api#exec(method, args) abort + return call(s:funcs[a:method], a:args) +endfunction + function! coc#api#notify(method, args) abort - call call(s:funcs[a:method], a:args) + try + call call(s:funcs[a:method], a:args) + catch /.*/ + call coc#rpc#notify('nvim_error_event', [0, v:exception.' on api "'.a:method.'" '.json_encode(a:args)]) + endtry +endfunction + +" create id for all tabpages +function! coc#api#tabpage_ids() abort + for nr in range(1, tabpagenr('$')) + if gettabvar(nr, '__tid', -1) == -1 + call settabvar(nr, '__tid', s:tab_id) + let s:tab_id = s:tab_id + 1 + endif + endfor +endfunction + +function! coc#api#get_tabid(nr) abort + return s:tabnr_id(a:nr) endfunction " vim: set sw=2 ts=2 sts=2 et tw=78 foldmarker={{,}} foldmethod=marker foldlevel=0: diff --git a/vim-config/plugins/coc.nvim/autoload/coc/client.vim b/vim-config/plugins/coc.nvim/autoload/coc/client.vim index 6987ebbf..0a8023c1 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/client.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/client.vim @@ -5,6 +5,7 @@ let s:is_win = has("win32") || has("win64") let s:clients = {} if get(g:, 'node_client_debug', 0) + echohl WarningMsg | echo '[coc.nvim] Enable g:node_client_debug could impact your vim experience' | echohl None let $NODE_CLIENT_LOG_LEVEL = 'debug' if exists('$NODE_CLIENT_LOG_FILE') let s:logfile = resolve($NODE_CLIENT_LOG_FILE) @@ -38,13 +39,16 @@ endfunction function! s:start() dict if self.running | return | endif if !isdirectory(getcwd()) - echohl Error | echon '[coc.nvim] Current cwd is not a valid directory.' | echohl None + echoerr '[coc.nvim] Current cwd is not a valid directory.' return endif - let timeout = string(get(g:, 'coc_channel_timeout', 30)) - let disable_warning = string(get(g:, 'coc_disable_startup_warning', 0)) let tmpdir = fnamemodify(tempname(), ':p:h') if s:is_vim + if get(g:, 'node_client_debug', 0) + let file = tmpdir . '/coc.log' + call ch_logfile(file, 'w') + echohl MoreMsg | echo '[coc.nvim] channel log to '.file | echohl None + endif let options = { \ 'in_mode': 'json', \ 'out_mode': 'json', @@ -54,8 +58,6 @@ function! s:start() dict \ 'env': { \ 'NODE_NO_WARNINGS': '1', \ 'VIM_NODE_RPC': '1', - \ 'COC_NVIM': '1', - \ 'COC_CHANNEL_TIMEOUT': timeout, \ 'TMPDIR': tmpdir, \ } \} @@ -82,7 +84,6 @@ function! s:start() dict " could use env option let opts['env'] = { \ 'NODE_NO_WARNINGS': '1', - \ 'COC_CHANNEL_TIMEOUT': timeout, \ 'TMPDIR': tmpdir \ } else @@ -90,24 +91,14 @@ function! s:start() dict \ 'NODE_NO_WARNINGS': getenv('NODE_NO_WARNINGS'), \ 'TMPDIR': getenv('TMPDIR'), \ } - if exists('*setenv') - call setenv('NODE_NO_WARNINGS', '1') - call setenv('COC_CHANNEL_TIMEOUT', timeout) - call setenv('TMPDIR', tmpdir) - else - let $NODE_NO_WARNINGS = 1 - let $TMPDIR = tmpdir - endif + call setenv('NODE_NO_WARNINGS', '1') + call setenv('TMPDIR', tmpdir) endif let chan_id = jobstart(self.command, opts) if !empty(original) - if exists('*setenv') - for key in keys(original) - call setenv(key, original[key]) - endfor - else - let $TMPDIR = original['TMPDIR'] - endif + for key in keys(original) + call setenv(key, original[key]) + endfor endif if chan_id <= 0 echohl Error | echom 'Failed to start '.self.name.' service' | echohl None @@ -120,12 +111,40 @@ endfunction function! s:on_stderr(name, msgs) if get(g:, 'coc_vim_leaving', 0) | return | endif - if get(g:, 'coc_disable_uncaught_error', 0) | return | endif let data = filter(copy(a:msgs), '!empty(v:val)') if empty(data) | return | endif let client = a:name ==# 'coc' ? '[coc.nvim]' : '['.a:name.']' let data[0] = client.': '.data[0] - call coc#util#echo_messages('Error', data) + if a:name ==# 'coc' && len(filter(copy(data), 'v:val =~# "SyntaxError: "')) + call coc#client#check_version() + return + endif + if get(g:, 'coc_disable_uncaught_error', 0) | return | endif + call s:on_error(a:name, data) +endfunction + +function! coc#client#check_version() abort + if (has_key(g:, 'coc_node_path')) + let node = expand(g:coc_node_path) + else + let node = $COC_NODE_PATH == '' ? 'node' : $COC_NODE_PATH + endif + let cmd = node . ' --version' + let output = system(cmd) + let msgs = [] + if v:shell_error + let msgs = ['Unexpected result from "'.cmd.'"'] + split(output, '\n') + else + let ms = matchlist(output, 'v\(\d\+\).\(\d\+\).\(\d\+\)') + if empty(ms) + let msgs = ['Unable to get node version by "'.cmd.'" please install NodeJS from https://nodejs.org/en/download/'] + elseif str2nr(ms[1]) < 14 || (str2nr(ms[1]) == 14 && str2nr(ms[2]) < 14) + let msgs = ['Current Node.js version '.trim(output).' < 14.14.0 ', 'Please upgrade your .js'] + endif + endif + if !empty(msgs) + call s:on_error('coc', msgs) + endif endfunction function! s:on_exit(name, code) abort @@ -164,7 +183,7 @@ function! s:request(method, args) dict endif let [l:errmsg, res] = res if !empty(l:errmsg) - throw l:errmsg + throw 'Error on "'.a:method.'" request: '.l:errmsg else return res endif @@ -181,7 +200,11 @@ function! s:request(method, args) dict elseif v:exception =~# 'E12' " neovim's bug, ignore it else - echohl Error | echo 'Error on request ('.a:method.'): '.v:exception | echohl None + if s:is_vim + throw v:exception + else + throw 'Error on request: '.v:exception + endif endif endtry endfunction @@ -246,14 +269,18 @@ function! coc#client#is_running(name) abort let client = get(s:clients, a:name, v:null) if empty(client) | return 0 | endif if !client['running'] | return 0 | endif - if s:is_vim - let status = job_status(ch_getjob(client['channel'])) - return status ==# 'run' - else - let chan_id = client['chan_id'] - let [code] = jobwait([chan_id], 10) - return code == -1 - endif + try + if s:is_vim + let status = job_status(ch_getjob(client['channel'])) + return status ==# 'run' + else + let chan_id = client['chan_id'] + let [code] = jobwait([chan_id], 10) + return code == -1 + endif + catch /.*/ + return 0 + endtry endfunction function! coc#client#stop(name) abort @@ -279,6 +306,22 @@ function! coc#client#stop(name) abort return 1 endfunction +function! coc#client#kill(name) abort + let client = get(s:clients, a:name, v:null) + if empty(client) | return 1 | endif + let running = coc#client#is_running(a:name) + if empty(client) || exists('$COC_NVIM_REMOTE_ADDRESS') + return 1 + endif + if running + if s:is_vim + call job_stop(ch_getjob(client['channel']), 'kill') + else + call jobstop(client['chan_id']) + endif + endif +endfunction + function! coc#client#request(name, method, args) let client = get(s:clients, a:name, v:null) if !empty(client) @@ -324,8 +367,20 @@ endfunction function! coc#client#open_log() if !get(g:, 'node_client_debug', 0) - echohl Error | echon '[coc.nvim] use let g:node_client_debug = 1 in your vimrc to enabled debug mode.' | echohl None + echohl Error | echon '[coc.nvim] use let g:node_client_debug = 1 in your vimrc to enable debug mode.' | echohl None return endif execute 'vs '.s:logfile endfunction + +function! s:on_error(name, msgs) abort + echohl ErrorMsg + echo join(a:msgs, "\n") + echohl None + let client = get(s:clients, a:name, v:null) + if !empty(client) + let errors = get(client, 'stderr', []) + call extend(errors, a:msgs) + let client['stderr'] = errors + endif +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/color.vim b/vim-config/plugins/coc.nvim/autoload/coc/color.vim index 3ef527e8..e0d92fc7 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/color.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/color.vim @@ -1,4 +1,250 @@ scriptencoding utf-8 + +let s:activate = "" +let s:quit = "" +if has("gui_macvim") && has('gui_running') + let s:app = "MacVim" +elseif $TERM_PROGRAM ==# "Apple_Terminal" + let s:app = "Terminal" +elseif $TERM_PROGRAM ==# "iTerm.app" + let s:app = "iTerm2" +elseif has('mac') + let s:app = "System Events" + let s:quit = "quit" + let s:activate = 'activate' +endif + +let s:patterns = {} +let s:patterns['hex'] = '\v#?(\x{2})(\x{2})(\x{2})' +let s:patterns['shortHex'] = '\v#(\x{1})(\x{1})(\x{1})' + +let s:xterm_colors = { + \ '0': '#000000', '1': '#800000', '2': '#008000', '3': '#808000', '4': '#000080', + \ '5': '#800080', '6': '#008080', '7': '#c0c0c0', '8': '#808080', '9': '#ff0000', + \ '10': '#00ff00', '11': '#ffff00', '12': '#0000ff', '13': '#ff00ff', '14': '#00ffff', + \ '15': '#ffffff', '16': '#000000', '17': '#00005f', '18': '#000087', '19': '#0000af', + \ '20': '#0000df', '21': '#0000ff', '22': '#005f00', '23': '#005f5f', '24': '#005f87', + \ '25': '#005faf', '26': '#005fdf', '27': '#005fff', '28': '#008700', '29': '#00875f', + \ '30': '#008787', '31': '#0087af', '32': '#0087df', '33': '#0087ff', '34': '#00af00', + \ '35': '#00af5f', '36': '#00af87', '37': '#00afaf', '38': '#00afdf', '39': '#00afff', + \ '40': '#00df00', '41': '#00df5f', '42': '#00df87', '43': '#00dfaf', '44': '#00dfdf', + \ '45': '#00dfff', '46': '#00ff00', '47': '#00ff5f', '48': '#00ff87', '49': '#00ffaf', + \ '50': '#00ffdf', '51': '#00ffff', '52': '#5f0000', '53': '#5f005f', '54': '#5f0087', + \ '55': '#5f00af', '56': '#5f00df', '57': '#5f00ff', '58': '#5f5f00', '59': '#5f5f5f', + \ '60': '#5f5f87', '61': '#5f5faf', '62': '#5f5fdf', '63': '#5f5fff', '64': '#5f8700', + \ '65': '#5f875f', '66': '#5f8787', '67': '#5f87af', '68': '#5f87df', '69': '#5f87ff', + \ '70': '#5faf00', '71': '#5faf5f', '72': '#5faf87', '73': '#5fafaf', '74': '#5fafdf', + \ '75': '#5fafff', '76': '#5fdf00', '77': '#5fdf5f', '78': '#5fdf87', '79': '#5fdfaf', + \ '80': '#5fdfdf', '81': '#5fdfff', '82': '#5fff00', '83': '#5fff5f', '84': '#5fff87', + \ '85': '#5fffaf', '86': '#5fffdf', '87': '#5fffff', '88': '#870000', '89': '#87005f', + \ '90': '#870087', '91': '#8700af', '92': '#8700df', '93': '#8700ff', '94': '#875f00', + \ '95': '#875f5f', '96': '#875f87', '97': '#875faf', '98': '#875fdf', '99': '#875fff', + \ '100': '#878700', '101': '#87875f', '102': '#878787', '103': '#8787af', '104': '#8787df', + \ '105': '#8787ff', '106': '#87af00', '107': '#87af5f', '108': '#87af87', '109': '#87afaf', + \ '110': '#87afdf', '111': '#87afff', '112': '#87df00', '113': '#87df5f', '114': '#87df87', + \ '115': '#87dfaf', '116': '#87dfdf', '117': '#87dfff', '118': '#87ff00', '119': '#87ff5f', + \ '120': '#87ff87', '121': '#87ffaf', '122': '#87ffdf', '123': '#87ffff', '124': '#af0000', + \ '125': '#af005f', '126': '#af0087', '127': '#af00af', '128': '#af00df', '129': '#af00ff', + \ '130': '#af5f00', '131': '#af5f5f', '132': '#af5f87', '133': '#af5faf', '134': '#af5fdf', + \ '135': '#af5fff', '136': '#af8700', '137': '#af875f', '138': '#af8787', '139': '#af87af', + \ '140': '#af87df', '141': '#af87ff', '142': '#afaf00', '143': '#afaf5f', '144': '#afaf87', + \ '145': '#afafaf', '146': '#afafdf', '147': '#afafff', '148': '#afdf00', '149': '#afdf5f', + \ '150': '#afdf87', '151': '#afdfaf', '152': '#afdfdf', '153': '#afdfff', '154': '#afff00', + \ '155': '#afff5f', '156': '#afff87', '157': '#afffaf', '158': '#afffdf', '159': '#afffff', + \ '160': '#df0000', '161': '#df005f', '162': '#df0087', '163': '#df00af', '164': '#df00df', + \ '165': '#df00ff', '166': '#df5f00', '167': '#df5f5f', '168': '#df5f87', '169': '#df5faf', + \ '170': '#df5fdf', '171': '#df5fff', '172': '#df8700', '173': '#df875f', '174': '#df8787', + \ '175': '#df87af', '176': '#df87df', '177': '#df87ff', '178': '#dfaf00', '179': '#dfaf5f', + \ '180': '#dfaf87', '181': '#dfafaf', '182': '#dfafdf', '183': '#dfafff', '184': '#dfdf00', + \ '185': '#dfdf5f', '186': '#dfdf87', '187': '#dfdfaf', '188': '#dfdfdf', '189': '#dfdfff', + \ '190': '#dfff00', '191': '#dfff5f', '192': '#dfff87', '193': '#dfffaf', '194': '#dfffdf', + \ '195': '#dfffff', '196': '#ff0000', '197': '#ff005f', '198': '#ff0087', '199': '#ff00af', + \ '200': '#ff00df', '201': '#ff00ff', '202': '#ff5f00', '203': '#ff5f5f', '204': '#ff5f87', + \ '205': '#ff5faf', '206': '#ff5fdf', '207': '#ff5fff', '208': '#ff8700', '209': '#ff875f', + \ '210': '#ff8787', '211': '#ff87af', '212': '#ff87df', '213': '#ff87ff', '214': '#ffaf00', + \ '215': '#ffaf5f', '216': '#ffaf87', '217': '#ffafaf', '218': '#ffafdf', '219': '#ffafff', + \ '220': '#ffdf00', '221': '#ffdf5f', '222': '#ffdf87', '223': '#ffdfaf', '224': '#ffdfdf', + \ '225': '#ffdfff', '226': '#ffff00', '227': '#ffff5f', '228': '#ffff87', '229': '#ffffaf', + \ '230': '#ffffdf', '231': '#ffffff', '232': '#080808', '233': '#121212', '234': '#1c1c1c', + \ '235': '#262626', '236': '#303030', '237': '#3a3a3a', '238': '#444444', '239': '#4e4e4e', + \ '240': '#585858', '241': '#606060', '242': '#666666', '243': '#767676', '244': '#808080', + \ '245': '#8a8a8a', '246': '#949494', '247': '#9e9e9e', '248': '#a8a8a8', '249': '#b2b2b2', + \ '250': '#bcbcbc', '251': '#c6c6c6', '252': '#d0d0d0', '253': '#dadada', '254': '#e4e4e4', + \ '255': '#eeeeee'} + +let s:xterm_16colors = { +\ 'black': '#000000', +\ 'darkblue': '#00008B', +\ 'darkgreen': '#00CD00', +\ 'darkcyan': '#00CDCD', +\ 'darkred': '#CD0000', +\ 'darkmagenta': '#8B008B', +\ 'brown': '#CDCD00', +\ 'darkyellow': '#CDCD00', +\ 'lightgrey': '#E5E5E5', +\ 'lightgray': '#E5E5E5', +\ 'gray': '#E5E5E5', +\ 'grey': '#E5E5E5', +\ 'darkgrey': '#7F7F7F', +\ 'darkgray': '#7F7F7F', +\ 'blue': '#5C5CFF', +\ 'lightblue': '#5C5CFF', +\ 'green': '#00FF00', +\ 'lightgreen': '#00FF00', +\ 'cyan': '#00FFFF', +\ 'lightcyan': '#00FFFF', +\ 'red': '#FF0000', +\ 'lightred': '#FF0000', +\ 'magenta': '#FF00FF', +\ 'lightmagenta': '#FF00FF', +\ 'yellow': '#FFFF00', +\ 'lightyellow': '#FFFF00', +\ 'white': '#FFFFFF', +\ } + +let s:w3c_color_names = { +\ 'aliceblue': '#F0F8FF', +\ 'antiquewhite': '#FAEBD7', +\ 'aqua': '#00FFFF', +\ 'aquamarine': '#7FFFD4', +\ 'azure': '#F0FFFF', +\ 'beige': '#F5F5DC', +\ 'bisque': '#FFE4C4', +\ 'black': '#000000', +\ 'blanchedalmond': '#FFEBCD', +\ 'blue': '#0000FF', +\ 'blueviolet': '#8A2BE2', +\ 'brown': '#A52A2A', +\ 'burlywood': '#DEB887', +\ 'cadetblue': '#5F9EA0', +\ 'chartreuse': '#7FFF00', +\ 'chocolate': '#D2691E', +\ 'coral': '#FF7F50', +\ 'cornflowerblue': '#6495ED', +\ 'cornsilk': '#FFF8DC', +\ 'crimson': '#DC143C', +\ 'cyan': '#00FFFF', +\ 'darkblue': '#00008B', +\ 'darkcyan': '#008B8B', +\ 'darkgoldenrod': '#B8860B', +\ 'darkgray': '#A9A9A9', +\ 'darkgreen': '#006400', +\ 'darkkhaki': '#BDB76B', +\ 'darkmagenta': '#8B008B', +\ 'darkolivegreen': '#556B2F', +\ 'darkorange': '#FF8C00', +\ 'darkorchid': '#9932CC', +\ 'darkred': '#8B0000', +\ 'darksalmon': '#E9967A', +\ 'darkseagreen': '#8FBC8F', +\ 'darkslateblue': '#483D8B', +\ 'darkslategray': '#2F4F4F', +\ 'darkturquoise': '#00CED1', +\ 'darkviolet': '#9400D3', +\ 'deeppink': '#FF1493', +\ 'deepskyblue': '#00BFFF', +\ 'dimgray': '#696969', +\ 'dodgerblue': '#1E90FF', +\ 'firebrick': '#B22222', +\ 'floralwhite': '#FFFAF0', +\ 'forestgreen': '#228B22', +\ 'fuchsia': '#FF00FF', +\ 'gainsboro': '#DCDCDC', +\ 'ghostwhite': '#F8F8FF', +\ 'gold': '#FFD700', +\ 'goldenrod': '#DAA520', +\ 'gray': '#808080', +\ 'green': '#008000', +\ 'greenyellow': '#ADFF2F', +\ 'honeydew': '#F0FFF0', +\ 'hotpink': '#FF69B4', +\ 'indianred': '#CD5C5C', +\ 'indigo': '#4B0082', +\ 'ivory': '#FFFFF0', +\ 'khaki': '#F0E68C', +\ 'lavender': '#E6E6FA', +\ 'lavenderblush': '#FFF0F5', +\ 'lawngreen': '#7CFC00', +\ 'lemonchiffon': '#FFFACD', +\ 'lightblue': '#ADD8E6', +\ 'lightcoral': '#F08080', +\ 'lightcyan': '#E0FFFF', +\ 'lightgoldenrodyellow': '#FAFAD2', +\ 'lightgray': '#D3D3D3', +\ 'lightgreen': '#90EE90', +\ 'lightpink': '#FFB6C1', +\ 'lightsalmon': '#FFA07A', +\ 'lightseagreen': '#20B2AA', +\ 'lightskyblue': '#87CEFA', +\ 'lightslategray': '#778899', +\ 'lightsteelblue': '#B0C4DE', +\ 'lightyellow': '#FFFFE0', +\ 'lime': '#00FF00', +\ 'limegreen': '#32CD32', +\ 'linen': '#FAF0E6', +\ 'magenta': '#FF00FF', +\ 'maroon': '#800000', +\ 'mediumaquamarine': '#66CDAA', +\ 'mediumblue': '#0000CD', +\ 'mediumorchid': '#BA55D3', +\ 'mediumpurple': '#9370D8', +\ 'mediumseagreen': '#3CB371', +\ 'mediumslateblue': '#7B68EE', +\ 'mediumspringgreen': '#00FA9A', +\ 'mediumturquoise': '#48D1CC', +\ 'mediumvioletred': '#C71585', +\ 'midnightblue': '#191970', +\ 'mintcream': '#F5FFFA', +\ 'mistyrose': '#FFE4E1', +\ 'moccasin': '#FFE4B5', +\ 'navajowhite': '#FFDEAD', +\ 'navy': '#000080', +\ 'oldlace': '#FDF5E6', +\ 'olive': '#808000', +\ 'olivedrab': '#6B8E23', +\ 'orange': '#FFA500', +\ 'orangered': '#FF4500', +\ 'orchid': '#DA70D6', +\ 'palegoldenrod': '#EEE8AA', +\ 'palegreen': '#98FB98', +\ 'paleturquoise': '#AFEEEE', +\ 'palevioletred': '#D87093', +\ 'papayawhip': '#FFEFD5', +\ 'peachpuff': '#FFDAB9', +\ 'peru': '#CD853F', +\ 'pink': '#FFC0CB', +\ 'plum': '#DDA0DD', +\ 'powderblue': '#B0E0E6', +\ 'purple': '#800080', +\ 'red': '#FF0000', +\ 'rosybrown': '#BC8F8F', +\ 'royalblue': '#4169E1', +\ 'saddlebrown': '#8B4513', +\ 'salmon': '#FA8072', +\ 'sandybrown': '#F4A460', +\ 'seagreen': '#2E8B57', +\ 'seashell': '#FFF5EE', +\ 'sienna': '#A0522D', +\ 'silver': '#C0C0C0', +\ 'skyblue': '#87CEEB', +\ 'slateblue': '#6A5ACD', +\ 'slategray': '#708090', +\ 'snow': '#FFFAFA', +\ 'springgreen': '#00FF7F', +\ 'steelblue': '#4682B4', +\ 'tan': '#D2B48C', +\ 'teal': '#008080', +\ 'thistle': '#D8BFD8', +\ 'tomato': '#FF6347', +\ 'turquoise': '#40E0D0', +\ 'violet': '#EE82EE', +\ 'wheat': '#F5DEB3', +\ 'white': '#FFFFFF', +\ 'whitesmoke': '#F5F5F5', +\ 'yellow': '#FFFF00', +\ 'yellowgreen': '#9ACD32' +\ } + " Returns an approximate grey index for the given grey level fun! s:grey_number(x) if &t_Co == 88 @@ -184,9 +430,181 @@ fun! s:colour(r, g, b) endif endfun +function! coc#color#term2rgb(term) abort + if a:term < 0 || a:term > 255 + return '#000000' + endif + return s:xterm_colors[a:term] +endfunction + function! coc#color#rgb2term(rgb) let l:r = ("0x" . strpart(a:rgb, 0, 2)) + 0 let l:g = ("0x" . strpart(a:rgb, 2, 2)) + 0 let l:b = ("0x" . strpart(a:rgb, 4, 2)) + 0 return s:colour(l:r, l:g, l:b) -endfun +endfunction + +function! coc#color#rgbToHex(...) + let [r, g, b] = ( a:0==1 ? a:1 : a:000 ) + let num = printf('%02x', float2nr(r)) . '' + \ . printf('%02x', float2nr(g)) . '' + \ . printf('%02x', float2nr(b)) . '' + return '#' . num +endfunction + +function! coc#color#hexToRgb(color) + if type(a:color) == 2 + let color = printf('%x', a:color) + else + let color = a:color + end + let matches = matchlist(color, s:patterns['hex']) + let factor = 0x1 + if empty(matches) + let matches = matchlist(color, s:patterns['shortHex']) + let factor = 0x10 + end + if len(matches) < 4 + echohl Error + echom 'Couldnt parse ' . string(color) . ' ' . string(matches) + echohl None + return + end + let r = str2nr(matches[1], 16) * factor + let g = str2nr(matches[2], 16) * factor + let b = str2nr(matches[3], 16) * factor + return [r, g, b] +endfunction + +function! coc#color#lighten(color, ...) + let amount = a:0 ? + \(type(a:1) < 2 ? + \str2float(a:1) : a:1 ) + \: 5 + let rgb = coc#color#hexToRgb(a:color) + let rgb = map(rgb, 'v:val + amount*(255 - v:val)/255') + let rgb = map(rgb, 'v:val > 255.0 ? 255.0 : v:val') + let rgb = map(rgb, 'float2nr(v:val)') + let hex = coc#color#rgbToHex(rgb) + return hex +endfunction + +function! coc#color#darken(color, ...) + let amount = a:0 ? + \(type(a:1) < 2 ? + \str2float(a:1) : a:1 ) + \: 5.0 + let rgb = coc#color#hexToRgb(a:color) + let rgb = map(rgb, 'v:val - amount*v:val/255') + let rgb = map(rgb, 'v:val < 0.0 ? 0.0 : v:val') + let rgb = map(rgb, 'float2nr(v:val)') + let hex = coc#color#rgbToHex(rgb) + return hex +endfu + +function! coc#color#luminance(rgb) abort + let vals = [] + for val in a:rgb + let val = (val + 0.0)/255 + if val <= 0.03928 + call add(vals, val/12.92) + else + call add(vals, pow((val + 0.055)/1.055, 2.4)) + endif + endfor + return vals[0] * 0.2126 + vals[1] * 0.7152 + vals[2] * 0.0722 +endfunction + +function! coc#color#contrast(rgb1, rgb2) abort + let lnum1 = coc#color#luminance(a:rgb1) + let lnum2 = coc#color#luminance(a:rgb2) + let brightest = lnum1 > lnum2 ? lnum1 : lnum2 + let darkest = lnum1 < lnum2 ? lnum1 : lnum2 + return (brightest + 0.05) / (darkest + 0.05) +endfunction + +function! coc#color#hex_contrast(hex1, hex2) abort + return coc#color#contrast(coc#color#hexToRgb(a:hex1), coc#color#hexToRgb(a:hex2)) +endfunction + +function! coc#color#nameToHex(name, term) abort + if a:term + return has_key(s:xterm_16colors, a:name) ? s:xterm_16colors[a:name] : v:null + endif + return has_key(s:w3c_color_names, a:name) ? s:w3c_color_names[a:name] : v:null +endfunction + +" [r, g, b] ['255', '255', '255'] +" return ['65535', '65535', '65535'] or return v:false to cancel +function! coc#color#pick_color(default_color) + if has('mac') + let default_color = map(a:default_color, {idx, val -> str2nr(val) * 65535 / 255 }) + " This is the AppleScript magic: + let ascrpt = ['-e "tell application \"' . s:app . '\""', + \ '-e "' . s:activate . '"', + \ "-e \"set AppleScript's text item delimiters to {\\\",\\\"}\"", + \ '-e "set theColor to (choose color default color {' . default_color[0] . ", " . default_color[1] . ", " . default_color[2] . '}) as text"', + \ '-e "' . s:quit . '"', + \ '-e "end tell"', + \ '-e "return theColor"'] + let res = trim(system("osascript " . join(ascrpt, ' ') . " 2>/dev/null")) + if empty(res) + return v:false + else + return split(trim(res), ',') + endif + endif + + let hex_color = printf('#%02x%02x%02x', a:default_color[0], a:default_color[1], a:default_color[2]) + + if has('unix') + if executable('zenity') + let res = trim(system('zenity --title="Select a color" --color-selection --color="' . hex_color . '" 2> /dev/null')) + if empty(res) + return v:false + else + " res format is rgb(255,255,255) + return map(split(res[4:-2], ','), {idx, val -> string(str2nr(trim(val)) * 65535 / 255)}) + endif + endif + endif + + let rgb = v:false + if !has('python') + echohl Error | echom 'python support required, checkout :echo has(''python'')' | echohl None + return + endif + try + execute 'py import gtk' + catch /.*/ + echohl Error | echom 'python gtk module not found' | echohl None + return + endtry +python << endpython + +import vim +import gtk, sys + +# message strings +wnd_title_insert = "Insert a color" + +csd = gtk.ColorSelectionDialog(wnd_title_insert) +cs = csd.colorsel + +cs.set_current_color(gtk.gdk.color_parse(vim.eval("hex_color"))) + +cs.set_current_alpha(65535) +cs.set_has_opacity_control(False) +# cs.set_has_palette(int(vim.eval("s:display_palette"))) + +if csd.run()==gtk.RESPONSE_OK: + c = cs.get_current_color() + s = [str(int(c.red)),',',str(int(c.green)),',',str(int(c.blue))] + thecolor = ''.join(s) + vim.command(":let rgb = split('%s',',')" % thecolor) + +csd.destroy() + +endpython + return rgb +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/compat.vim b/vim-config/plugins/coc.nvim/autoload/coc/compat.vim index d53c1098..21bab01c 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/compat.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/compat.vim @@ -13,12 +13,50 @@ endfunction function! coc#compat#buf_set_lines(bufnr, start, end, replacement) abort if s:is_vim - call coc#api#notify('buf_set_lines', [a:bufnr, a:start, a:end, 0, a:replacement]) + call coc#api#exec('buf_set_lines', [a:bufnr, a:start, a:end, 0, a:replacement]) else call nvim_buf_set_lines(a:bufnr, a:start, a:end, 0, a:replacement) endif endfunction +function! coc#compat#buf_line_count(bufnr) abort + if exists('*nvim_buf_line_count') + return nvim_buf_line_count(a:bufnr) + endif + if bufnr('%') == a:bufnr + return line('$') + endif + if exists('*getbufinfo') + let info = getbufinfo(a:bufnr) + if empty(info) + return 0 + endif + " vim 8.1 has getbufinfo but no linecount + if has_key(info[0], 'linecount') + return info[0]['linecount'] + endif + endif + if exists('*getbufline') + let lines = getbufline(a:bufnr, 1, '$') + return len(lines) + endif + let curr = bufnr('%') + execute 'noa buffer '.a:bufnr + let n = line('$') + execute 'noa buffer '.curr + return n +endfunction + +function! coc#compat#prepend_lines(bufnr, replacement) abort + if exists('*appendbufline') + call appendbufline(a:bufnr, 0, a:replacement) + elseif !s:is_vim + call nvim_buf_set_lines(a:bufnr, 0, 0, 0, a:replacement) + else + throw 'appendbufline() required for prepend lines.' + endif +endfunction + function! coc#compat#win_is_valid(winid) abort if exists('*nvim_win_is_valid') return nvim_win_is_valid(a:winid) @@ -60,13 +98,7 @@ function! coc#compat#matchaddpos(group, pos, priority, winid) abort call matchaddpos(a:group, a:pos, a:priority, -1, {'window': a:winid}) endif else - if has('nvim-0.4.0') - call matchaddpos(a:group, a:pos, a:priority, -1, {'window': a:winid}) - elseif exists('*nvim_set_current_win') - noa call nvim_set_current_win(a:winid) - call matchaddpos(a:group, a:pos, a:priority, -1) - noa call nvim_set_current_win(curr) - endif + call matchaddpos(a:group, a:pos, a:priority, -1, {'window': a:winid}) endif endif endfunction @@ -78,7 +110,7 @@ function! coc#compat#buf_del_var(bufnr, name) abort if exists('*nvim_buf_del_var') silent! call nvim_buf_del_var(a:bufnr, a:name) else - if bufnr == bufnr('%') + if a:bufnr == bufnr('%') execute 'unlet! b:'.a:name elseif exists('*win_execute') let winid = coc#compat#buf_win_id(a:bufnr) @@ -91,24 +123,16 @@ endfunction " hlGroup, pos, priority function! coc#compat#matchaddgroups(winid, groups) abort - " add by winid - if has('patch-8.1.0218') || has('nvim-0.4.0') - for group in a:groups - call matchaddpos(group['hlGroup'], [group['pos']], group['priority'], -1, {'window': a:winid}) - endfor - return - endif - let curr = win_getid() - if curr == a:winid - for group in a:groups - call matchaddpos(group['hlGroup'], [group['pos']], group['priority'], -1) - endfor - elseif exists('*nvim_set_current_win') - noa call nvim_set_current_win(a:winid) - for group in a:groups - call matchaddpos(group['hlGroup'], [group['pos']], group['priority'], -1) - endfor - noa call nvim_set_current_win(curr) + for group in a:groups + call matchaddpos(group['hlGroup'], [group['pos']], group['priority'], -1, {'window': a:winid}) + endfor +endfunction + +function! coc#compat#del_var(name) abort + if exists('*nvim_del_var') + silent! call nvim_del_var(a:name) + else + execute 'unlet! '.a:name endif endfunction @@ -121,20 +145,15 @@ function! coc#compat#buf_del_keymap(bufnr, mode, lhs) abort try call nvim_buf_del_keymap(a:bufnr, a:mode, a:lhs) catch /^Vim\%((\a\+)\)\=:E5555/ - " ignore keymap not exists. + " ignore keymap doesn't exist endtry return endif - if bufnr == a:bufnr - execute 'silent! '.a:mode.'unmap '.a:lhs - return - endif - if exists('*win_execute') - let winid = coc#compat#buf_win_id(a:bufnr) - if winid != -1 - call win_execute(winid, 'silent! '.a:mode.'unmap '.a:lhs) - endif - endif + try + call coc#api#exec('buf_del_keymap', [a:bufnr, a:mode, a:lhs]) + catch /E31/ + " ignore keymap doesn't exist + endtry endfunction function! coc#compat#buf_add_keymap(bufnr, mode, lhs, rhs, opts) abort @@ -144,21 +163,7 @@ function! coc#compat#buf_add_keymap(bufnr, mode, lhs, rhs, opts) abort if exists('*nvim_buf_set_keymap') call nvim_buf_set_keymap(a:bufnr, a:mode, a:lhs, a:rhs, a:opts) else - let cmd = a:mode . 'noremap ' - for key in keys(a:opts) - if get(a:opts, key, 0) - let cmd .= '<'.key.'>' - endif - endfor - let cmd .= ' '.a:lhs.' '.a:rhs - if bufnr('%') == a:bufnr - execute cmd - elseif exists('*win_execute') - let winid = coc#compat#buf_win_id(a:bufnr) - if winid != -1 - call win_execute(winid, cmd) - endif - endif + call coc#api#exec('buf_set_keymap', [a:bufnr, a:mode, a:lhs, a:rhs, a:opts]) endif endfunction @@ -185,6 +190,14 @@ function! coc#compat#execute(winid, command, ...) abort endif noa keepalt call nvim_set_current_win(curr) else - throw 'win_execute not exists, please upgrade vim.' + throw 'win_execute does not exist, please upgrade vim.' endif endfunc + +function! coc#compat#trim(str) + if exists('*trim') + return trim(a:str) + endif + " TODO trim from beginning + return substitute(a:str, '\s\+$', '', '') +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/cursor.vim b/vim-config/plugins/coc.nvim/autoload/coc/cursor.vim index f5ba66ad..74c81d95 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/cursor.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/cursor.vim @@ -14,15 +14,14 @@ endfunction " Get cursor position. function! coc#cursor#position() - return [line('.') - 1, strchars(strpart(getline('.'), 0, col('.') - 1))] + let line = getline('.') + return [line('.') - 1, coc#string#character_index(line, col('.') - 1)] endfunction " Move cursor to position. function! coc#cursor#move_to(line, character) abort let content = getline(a:line + 1) - let pre = strcharpart(content, 0, a:character) - let col = strlen(pre) + 1 - call cursor(a:line + 1, col) + call cursor(a:line + 1, coc#string#byte_index(content, a:character) + 1) endfunction " Character offset of current cursor, vim provide bytes offset only. @@ -39,3 +38,22 @@ function! coc#cursor#char_offset() abort return offset endfunction +" Returns latest selection range +function! coc#cursor#get_selection(char) abort + let m = a:char ? 'char' : visualmode() + if empty(m) + return v:null + endif + let [_, sl, sc, soff] = getpos(m ==# 'char' ? "'[" : "'<") + let [_, el, ec, eoff] = getpos(m ==# 'char' ? "']" : "'>") + let start_idx = coc#string#character_index(getline(sl), sc - 1) + if m ==# 'V' + return [sl - 1, start_idx, el, 0] + endif + let line = getline(el) + let end_idx = coc#string#character_index(line, ec - 1) + if m !=# 'char' + let end_idx = end_idx == coc#string#character_length(line) ? end_idx : end_idx + 1 + endif + return [sl - 1, start_idx, el - 1, end_idx] +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/dialog.vim b/vim-config/plugins/coc.nvim/autoload/coc/dialog.vim new file mode 100644 index 00000000..ecfa7b1c --- /dev/null +++ b/vim-config/plugins/coc.nvim/autoload/coc/dialog.vim @@ -0,0 +1,743 @@ +scriptencoding utf-8 +let s:is_vim = !has('nvim') +let s:root = expand(':h:h:h') +let s:prompt_win_bufnr = 0 +let s:list_win_bufnr = 0 +let s:prompt_win_width = get(g:, 'coc_prompt_win_width', 32) +let s:frames = ['ยท ', 'ยทยท ', 'ยทยทยท', ' ยทยท', ' ยท', ' '] +let s:sign_group = 'PopUpCocDialog' +let s:detail_bufnr = 0 + +" Float window aside pum +function! coc#dialog#create_pum_float(lines, config) abort + let winid = coc#float#get_float_by_kind('pumdetail') + if empty(a:lines) || !coc#pum#visible() + if winid + call coc#float#close(winid) + endif + return + endif + let pumbounding = coc#pum#info() + let border = get(a:config, 'border', []) + let pw = pumbounding['width'] + (pumbounding['border'] ? 0 : get(pumbounding, 'scrollbar', 0)) + let rp = &columns - pumbounding['col'] - pw + let showRight = pumbounding['col'] > rp ? 0 : 1 + let maxWidth = showRight ? coc#math#min(rp - 1, a:config['maxWidth']) : coc#math#min(pumbounding['col'] - 1, a:config['maxWidth']) + let bh = get(border, 0 ,0) + get(border, 2, 0) + let maxHeight = &lines - pumbounding['row'] - &cmdheight - 1 - bh + if maxWidth <= 2 || maxHeight < 1 + return v:null + endif + let width = 0 + for line in a:lines + let dw = max([1, strdisplaywidth(line)]) + let width = max([width, dw + 2]) + endfor + let width = float2nr(coc#math#min(maxWidth, width)) + let ch = coc#string#content_height(a:lines, width - 2) + let height = float2nr(coc#math#min(maxHeight, ch)) + let lines = map(a:lines, {_, s -> s =~# '^โ”€' ? repeat('โ”€', width - 2 + (s:is_vim && ch > height ? -1 : 0)) : s}) + let opts = { + \ 'lines': lines, + \ 'highlights': get(a:config, 'highlights', []), + \ 'relative': 'editor', + \ 'col': showRight ? pumbounding['col'] + pw : pumbounding['col'] - width, + \ 'row': pumbounding['row'], + \ 'height': height, + \ 'width': width - 2 + (s:is_vim && ch > height ? -1 : 0), + \ 'scrollinside': showRight ? 0 : 1, + \ 'codes': get(a:config, 'codes', []), + \ } + for key in ['border', 'highlight', 'borderhighlight', 'winblend', 'focusable', 'shadow', 'rounded'] + if has_key(a:config, key) + let opts[key] = a:config[key] + endif + endfor + call s:close_auto_hide_wins(winid) + let result = coc#float#create_float_win(winid, s:detail_bufnr, opts) + if empty(result) + return + endif + let s:detail_bufnr = result[1] + call setwinvar(result[0], 'kind', 'pumdetail') + if !s:is_vim + call coc#float#nvim_scrollbar(result[0]) + endif +endfunction + +" Float window below/above cursor +function! coc#dialog#create_cursor_float(winid, bufnr, lines, config) abort + if coc#prompt#activated() + return v:null + endif + let pumAlignTop = get(a:config, 'pumAlignTop', 0) + let modes = get(a:config, 'modes', ['n', 'i', 'ic', 's']) + let mode = mode() + let currbuf = bufnr('%') + let pos = [line('.'), col('.')] + if index(modes, mode) == -1 + return v:null + endif + if !s:is_vim && !has('nvim-0.5.0') && mode ==# 'i' + " helps to fix undo issue, don't know why. + call feedkeys("\u", 'n') + endif + if mode ==# 's' && has('patch-8.2.4969') && !has('patch-8.2.4996') + echohl WarningMsg | echon 'Popup not created to avoid issue #10466 on vim >= 8.2.4969' | echohl None + return v:null + endif + let dimension = coc#dialog#get_config_cursor(a:lines, a:config) + if empty(dimension) + return v:null + endif + if coc#pum#visible() && ((pumAlignTop && dimension['row'] <0)|| (!pumAlignTop && dimension['row'] > 0)) + return v:null + endif + let width = dimension['width'] + let lines = map(a:lines, {_, s -> s =~# '^โ”€' ? repeat('โ”€', width) : s}) + let config = extend(extend({'lines': lines, 'relative': 'cursor'}, a:config), dimension) + call s:close_auto_hide_wins(a:winid) + let res = coc#float#create_float_win(a:winid, a:bufnr, config) + if empty(res) + return v:null + endif + let alignTop = dimension['row'] < 0 + let winid = res[0] + let bufnr = res[1] + redraw + if has('nvim') + call coc#float#nvim_scrollbar(winid) + endif + return [currbuf, pos, winid, bufnr, alignTop] +endfunction + +" Use terminal buffer +function! coc#dialog#_create_prompt_vim(title, default, opts) abort + if !has('patch-8.2.0750') + throw 'Input box not supported on vim < 8.2.0750' + endif + execute 'hi link CocPopupTerminal '.get(a:opts, 'highlight', 'CocFloating') + let node = expand(get(g:, 'coc_node_path', 'node')) + let placeHolder = get(a:opts, 'placeHolder', '') + let opt = { + \ 'term_rows': 1, + \ 'hidden': 1, + \ 'term_finish': 'close', + \ 'norestore': 1, + \ 'term_highlight': 'CocPopupTerminal' + \ } + let bufnr = term_start([node, s:root . '/bin/prompt.js', a:default, empty(placeHolder) ? '' : placeHolder], opt) + call term_setapi(bufnr, 'Coc') + call setbufvar(bufnr, 'current', type(a:default) == v:t_string ? a:default : '') + let res = s:create_prompt_win(bufnr, a:title, a:default, a:opts) + if empty(res) + return + endif + let winid = res[0] + " call win_gotoid(winid) + call coc#util#do_autocmd('CocOpenFloatPrompt') + let pos = popup_getpos(winid) + " width height row col + let dimension = [pos['width'], pos['height'], pos['line'] - 1, pos['col'] - 1] + return [bufnr, winid, dimension] +endfunction + +" Use normal buffer on neovim +function! coc#dialog#_create_prompt_nvim(title, default, opts) abort + let result = s:create_prompt_win(s:prompt_win_bufnr, a:title, a:default, a:opts) + if empty(result) + return + endif + let winid = result[0] + let s:prompt_win_bufnr = result[1] + let bufnr = s:prompt_win_bufnr + call sign_unplace(s:sign_group, { 'buffer': s:prompt_win_bufnr }) + call nvim_set_current_win(winid) + inoremap + inoremap pumvisible() ? "\" : "\" + exe 'imap ' + exe 'nnoremap :call coc#float#close('.winid.')' + exe 'inoremap "\=coc#dialog#prompt_insert()\\"' + if get(a:opts, 'list', 0) + for key in ['', '', '', '', '', '', '', '', ''] + let escaped = key ==# '' ? '\' : substitute(key, '\(<\|>\)', '\\\1', 'g') + exe 'inoremap '.key.' call coc#rpc#notify("PromptKeyPress", ['.bufnr.', "'.escaped.'"])' + endfor + endif + let mode = mode() + if mode ==# 'n' + call feedkeys('A', 'int') + elseif mode ==# 'i' + call feedkeys("\", 'int') + endif + let placeHolder = get(a:opts, 'placeHolder', '') + if empty(a:default) && !empty(placeHolder) && has('nvim-0.5.0') + let src_id = coc#highlight#create_namespace('input-box') + call nvim_buf_set_extmark(bufnr, src_id, 0, 0, { + \ 'virt_text': [[placeHolder, 'CocInputBoxVirtualText']], + \ 'virt_text_pos': 'overlay', + \ }) + endif + call coc#util#do_autocmd('CocOpenFloatPrompt') + if !has('nvim-0.6.0') + redraw + endif + let id = coc#float#get_related(winid, 'border') + let pos = nvim_win_get_position(id) + let dimension = [nvim_win_get_width(id), nvim_win_get_height(id), pos[0], pos[1]] + return [bufnr, winid, dimension] +endfunction + +" Create float window for input +function! coc#dialog#create_prompt_win(title, default, opts) abort + call s:close_auto_hide_wins() + if s:is_vim + return coc#dialog#_create_prompt_vim(a:title, a:default, a:opts) + endif + return coc#dialog#_create_prompt_nvim(a:title, a:default, a:opts) +endfunction + +" Create list window under target window +function! coc#dialog#create_list(target, dimension, opts) abort + let maxHeight = get(a:opts, 'maxHeight', 10) + let height = max([1, len(get(a:opts, 'lines', []))]) + let height = min([maxHeight, height, &lines - &cmdheight - 1 - a:dimension['row'] + a:dimension['height']]) + let chars = get(a:opts, 'rounded', 1) ? ['โ•ฏ', 'โ•ฐ'] : ['โ”˜', 'โ””'] + let config = extend(copy(a:opts), { + \ 'relative': 'editor', + \ 'row': a:dimension['row'] + a:dimension['height'], + \ 'col': a:dimension['col'], + \ 'width': a:dimension['width'] - 2, + \ 'height': height, + \ 'border': [1, 1, 1, 1], + \ 'scrollinside': 1, + \ 'borderchars': extend(['โ”€', 'โ”‚', 'โ”€', 'โ”‚', 'โ”œ', 'โ”ค'], chars) + \ }) + let bufnr = 0 + let result = coc#float#create_float_win(0, s:list_win_bufnr, config) + if empty(result) + return + endif + let winid = result[0] + call coc#float#add_related(winid, a:target) + call setwinvar(winid, 'auto_height', get(a:opts, 'autoHeight', 1)) + call setwinvar(winid, 'max_height', maxHeight) + call setwinvar(winid, 'target_winid', a:target) + call setwinvar(winid, 'kind', 'list') + call coc#dialog#check_scroll_vim(a:target) + return result +endfunction + +" Create menu picker for pick single item +function! coc#dialog#create_menu(lines, config) abort + call s:close_auto_hide_wins() + let highlight = get(a:config, 'highlight', 'CocFloating') + let borderhighlight = get(a:config, 'borderhighlight', [highlight]) + let relative = get(a:config, 'relative', 'cursor') + let lines = a:lines + let content = get(a:config, 'content', '') + let maxWidth = get(a:config, 'maxWidth', 80) + let highlights = get(a:config, 'highlights', []) + let contentCount = 0 + if !empty(content) + let contentLines = coc#string#reflow(split(content, '\r\?\n'), maxWidth) + let contentCount = len(contentLines) + let lines = extend(contentLines, lines) + if !empty(highlights) + for item in highlights + let item['lnum'] = item['lnum'] + contentCount + endfor + endif + endif + let opts = { + \ 'lines': lines, + \ 'highlight': highlight, + \ 'title': get(a:config, 'title', ''), + \ 'borderhighlight': borderhighlight, + \ 'maxWidth': maxWidth, + \ 'maxHeight': get(a:config, 'maxHeight', 80), + \ 'rounded': get(a:config, 'rounded', 0), + \ 'border': [1, 1, 1, 1], + \ 'highlights': highlights, + \ 'relative': relative, + \ } + if relative ==# 'editor' + let dimension = coc#dialog#get_config_editor(lines, opts) + else + let dimension = coc#dialog#get_config_cursor(lines, opts) + endif + call extend(opts, dimension) + let ids = coc#float#create_float_win(0, s:prompt_win_bufnr, opts) + if empty(ids) + return + endif + let s:prompt_win_bufnr = ids[1] + call coc#dialog#set_cursor(ids[0], ids[1], contentCount + 1) + redraw + if has('nvim') + call coc#float#nvim_scrollbar(ids[0]) + endif + return [ids[0], ids[1], contentCount] +endfunction + +" Create dialog at center of screen +function! coc#dialog#create_dialog(lines, config) abort + call s:close_auto_hide_wins() + " dialog always have borders + let title = get(a:config, 'title', '') + let buttons = get(a:config, 'buttons', []) + let highlight = get(a:config, 'highlight', 'CocFloating') + let borderhighlight = get(a:config, 'borderhighlight', [highlight]) + let opts = { + \ 'title': title, + \ 'rounded': get(a:config, 'rounded', 0), + \ 'relative': 'editor', + \ 'border': [1,1,1,1], + \ 'close': get(a:config, 'close', 1), + \ 'highlight': highlight, + \ 'highlights': get(a:config, 'highlights', []), + \ 'buttons': buttons, + \ 'borderhighlight': borderhighlight, + \ 'getchar': get(a:config, 'getchar', 0) + \ } + call extend(opts, coc#dialog#get_config_editor(a:lines, a:config)) + let bufnr = coc#float#create_buf(0, a:lines) + let res = coc#float#create_float_win(0, bufnr, opts) + if empty(res) + return + endif + if get(a:config, 'cursorline', 0) + call coc#dialog#place_sign(bufnr, 1) + endif + if has('nvim') + redraw + call coc#float#nvim_scrollbar(res[0]) + endif + return res +endfunction + +function! coc#dialog#prompt_confirm(title, cb) abort + call s:close_auto_hide_wins() + if s:is_vim && exists('*popup_dialog') + try + call popup_dialog(a:title. ' (y/n)?', { + \ 'highlight': 'Normal', + \ 'filter': 'popup_filter_yesno', + \ 'callback': {id, res -> a:cb(v:null, res)}, + \ 'borderchars': get(g:, 'coc_borderchars', ['โ”€', 'โ”‚', 'โ”€', 'โ”‚', 'โ•ญ', 'โ•ฎ', 'โ•ฏ', 'โ•ฐ']), + \ 'borderhighlight': ['MoreMsg'] + \ }) + catch /.*/ + call a:cb(v:exception) + endtry + return + endif + let text = ' '. a:title . ' (y/n)? ' + let maxWidth = coc#math#min(78, &columns - 2) + let width = coc#math#min(maxWidth, strdisplaywidth(text)) + let maxHeight = &lines - &cmdheight - 1 + let height = coc#math#min(maxHeight, float2nr(ceil(str2float(string(strdisplaywidth(text)))/width))) + let arr = coc#float#create_float_win(0, s:prompt_win_bufnr, { + \ 'col': &columns/2 - width/2 - 1, + \ 'row': maxHeight/2 - height/2 - 1, + \ 'width': width, + \ 'height': height, + \ 'border': [1,1,1,1], + \ 'focusable': v:false, + \ 'relative': 'editor', + \ 'highlight': 'Normal', + \ 'borderhighlight': 'MoreMsg', + \ 'style': 'minimal', + \ 'lines': [text], + \ }) + if empty(arr) + call a:cb('Window create failed!') + return + endif + let winid = arr[0] + let s:prompt_win_bufnr = arr[1] + call sign_unplace(s:sign_group, { 'buffer': s:prompt_win_bufnr }) + let res = 0 + redraw + " same result as vim + while 1 + let key = nr2char(getchar()) + if key == "\" + let res = -1 + break + elseif key == "\" || key == 'n' || key == 'N' + let res = 0 + break + elseif key == 'y' || key == 'Y' + let res = 1 + break + endif + endw + call coc#float#close(winid) + call a:cb(v:null, res) +endfunction + +" works on neovim only +function! coc#dialog#get_prompt_win() abort + if s:prompt_win_bufnr == 0 + return -1 + endif + return get(win_findbuf(s:prompt_win_bufnr), 0, -1) +endfunction + +function! coc#dialog#get_config_editor(lines, config) abort + let title = get(a:config, 'title', '') + let maxheight = min([get(a:config, 'maxHeight', 78), &lines - &cmdheight - 6]) + let maxwidth = min([get(a:config, 'maxWidth', 78), &columns - 2]) + let buttons = get(a:config, 'buttons', []) + let minwidth = s:min_btns_width(buttons) + if maxheight <= 0 || maxwidth <= 0 || minwidth > maxwidth + throw 'Not enough spaces for float window' + endif + let ch = 0 + let width = min([strdisplaywidth(title) + 1, maxwidth]) + for line in a:lines + let dw = max([1, strdisplaywidth(line)]) + if dw < maxwidth && dw > width + let width = dw + elseif dw >= maxwidth + let width = maxwidth + endif + let ch += float2nr(ceil(str2float(string(dw))/maxwidth)) + endfor + let width = max([minwidth, width]) + let height = coc#math#min(ch ,maxheight) + return { + \ 'row': &lines/2 - (height + 4)/2, + \ 'col': &columns/2 - (width + 2)/2, + \ 'width': width, + \ 'height': height, + \ } +endfunction + +function! coc#dialog#prompt_insert() abort + let value = getline('.') + call coc#rpc#notify('PromptInsert', [value, bufnr('%')]) + return '' +endfunction + +" Dimension of window with lines relative to cursor +" Width & height excludes border & padding +function! coc#dialog#get_config_cursor(lines, config) abort + let preferTop = get(a:config, 'preferTop', 0) + let title = get(a:config, 'title', '') + let border = get(a:config, 'border', []) + if empty(border) && len(title) + let border = [1, 1, 1, 1] + endif + let bh = get(border, 0, 0) + get(border, 2, 0) + let vh = &lines - &cmdheight - 1 + if vh <= 0 + return v:null + endif + let maxWidth = coc#math#min(get(a:config, 'maxWidth', &columns - 1), &columns - 1) + if maxWidth < 3 + return v:null + endif + let maxHeight = coc#math#min(get(a:config, 'maxHeight', vh), vh) + let width = coc#math#min(40, strdisplaywidth(title)) + 3 + for line in a:lines + let dw = max([1, strdisplaywidth(line)]) + let width = max([width, dw + 2]) + endfor + let width = coc#math#min(maxWidth, width) + let ch = coc#string#content_height(a:lines, width - 2) + let [lineIdx, colIdx] = coc#cursor#screen_pos() + " How much we should move left + let offsetX = coc#math#min(get(a:config, 'offsetX', 0), colIdx) + let showTop = 0 + let hb = vh - lineIdx -1 + if lineIdx > bh + 2 && (preferTop || (lineIdx > hb && hb < ch + bh)) + let showTop = 1 + endif + let height = coc#math#min(maxHeight, ch + bh, showTop ? lineIdx - 1 : hb) + if height <= bh + return v:null + endif + let col = - max([offsetX, colIdx - (&columns - 1 - width)]) + let row = showTop ? - height + bh : 1 + return { + \ 'row': row, + \ 'col': col, + \ 'width': width - 2, + \ 'height': height - bh + \ } +endfunction + +function! coc#dialog#change_border_hl(winid, hlgroup) abort + if !hlexists(a:hlgroup) + return + endif + if s:is_vim + if coc#float#valid(a:winid) + call popup_setoptions(a:winid, {'borderhighlight': repeat([a:hlgroup], 4)}) + redraw + endif + else + let winid = coc#float#get_related(a:winid, 'border') + if winid > 0 + call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup) + endif + endif +endfunction + +function! coc#dialog#change_title(winid, title) abort + if s:is_vim + if coc#float#valid(a:winid) + call popup_setoptions(a:winid, {'title': a:title}) + redraw + endif + else + let winid = coc#float#get_related(a:winid, 'border') + if winid > 0 + let bufnr = winbufnr(winid) + let line = getbufline(bufnr, 1)[0] + let top = strcharpart(line, 0, 1) + \.repeat('โ”€', strchars(line) - 2) + \.strcharpart(line, strchars(line) - 1, 1) + if !empty(a:title) + let top = coc#string#compose(top, 1, a:title.' ') + endif + call nvim_buf_set_lines(bufnr, 0, 1, v:false, [top]) + endif + endif +endfunction + +function! coc#dialog#change_input_value(winid, bufnr, value) abort + if !coc#float#valid(a:winid) + return + endif + if win_getid() != a:winid + call win_gotoid(a:winid) + endif + if s:is_vim + " call timer_start(3000, { -> term_sendkeys(bufnr, "\\abcd")}) + call term_sendkeys(a:bufnr, "\\".a:value) + else + let mode = mode() + if mode ==# 'i' + call feedkeys("\", 'int') + else + call feedkeys("\A", 'int') + endif + " Use complete to replace text before + let saved_completeopt = &completeopt + if saved_completeopt =~ 'menuone' + noa set completeopt=menu + endif + noa call complete(1, [{ 'empty': 1, 'word': a:value }]) + if has('nvim-0.6.1') + call feedkeys("\\", 'in') + else + let g:coc_disable_space_report = 1 + call feedkeys("\\", 'in') + endif + execute 'noa set completeopt='.saved_completeopt + endif +endfunction + +function! coc#dialog#change_loading(winid, loading) abort + if coc#float#valid(a:winid) + let winid = coc#float#get_related(a:winid, 'loading') + if !a:loading && winid > 0 + call coc#float#close(winid) + endif + if a:loading && winid == 0 + let bufnr = s:create_loading_buf() + if s:is_vim + let pos = popup_getpos(a:winid) + let winid = popup_create(bufnr, { + \ 'line': pos['line'] + 1, + \ 'col': pos['col'] + pos['width'] - 4, + \ 'maxheight': 1, + \ 'maxwidth': 3, + \ 'zindex': 999, + \ 'highlight': get(popup_getoptions(a:winid), 'highlight', 'CocFloating') + \ }) + else + let pos = nvim_win_get_position(a:winid) + let width = nvim_win_get_width(a:winid) + let opts = { + \ 'relative': 'editor', + \ 'row': pos[0], + \ 'col': pos[1] + width - 3, + \ 'focusable': v:false, + \ 'width': 3, + \ 'height': 1, + \ 'style': 'minimal', + \ } + if has('nvim-0.5.1') + let opts['zindex'] = 900 + endif + let winid = nvim_open_win(bufnr, v:false, opts) + call setwinvar(winid, '&winhl', getwinvar(a:winid, '&winhl')) + endif + call setwinvar(winid, 'kind', 'loading') + call setbufvar(bufnr, 'target_winid', a:winid) + call setbufvar(bufnr, 'popup', winid) + call coc#float#add_related(winid, a:winid) + endif + endif +endfunction + +" Update list with new lines and highlights +function! coc#dialog#update_list(winid, bufnr, lines, highlights) abort + if coc#window#tabnr(a:winid) == tabpagenr() + if getwinvar(a:winid, 'auto_height', 0) + let row = coc#float#get_row(a:winid) + " core height + let height = max([1, len(copy(a:lines))]) + let height = min([getwinvar(a:winid, 'max_height', 10), height, &lines - &cmdheight - 1 - row]) + let curr = s:is_vim ? popup_getpos(a:winid)['core_height'] : nvim_win_get_height(a:winid) + let delta = height - curr + if delta != 0 + call coc#float#change_height(a:winid, delta) + endif + endif + call coc#compat#buf_set_lines(a:bufnr, 0, -1, a:lines) + call coc#highlight#add_highlights(a:winid, [], a:highlights) + if s:is_vim + let target = getwinvar(a:winid, 'target_winid', -1) + if target != -1 + call coc#dialog#check_scroll_vim(target) + endif + call win_execute(a:winid, 'exe 1') + endif + endif +endfunction + +" Fix width of prompt window same as list window on scrollbar change +function! coc#dialog#check_scroll_vim(winid) abort + if s:is_vim && coc#float#valid(a:winid) + let winid = coc#float#get_related(a:winid, 'list') + if winid + redraw + let pos = popup_getpos(winid) + let width = pos['width'] + (pos['scrollbar'] ? 1 : 0) + if width != popup_getpos(a:winid)['width'] + call popup_move(a:winid, { + \ 'minwidth': width - 2, + \ 'maxwidth': width - 2, + \ }) + endif + endif + endif +endfunction + +function! coc#dialog#set_cursor(winid, bufnr, line) abort + if s:is_vim + call coc#compat#execute(a:winid, 'exe '.a:line, 'silent!') + call popup_setoptions(a:winid, {'cursorline' : 1}) + call popup_setoptions(a:winid, {'cursorline' : 0}) + else + call nvim_win_set_cursor(a:winid, [a:line, 0]) + endif + call coc#dialog#place_sign(a:bufnr, a:line) +endfunction + +function! coc#dialog#place_sign(bufnr, line) abort + call sign_unplace(s:sign_group, { 'buffer': a:bufnr }) + if a:line > 0 + call sign_place(6, s:sign_group, 'CocCurrentLine', a:bufnr, {'lnum': a:line}) + endif +endfunction + +function! s:create_prompt_win(bufnr, title, default, opts) abort + let config = s:get_prompt_dimension(a:title, a:default, a:opts) + return coc#float#create_float_win(0, a:bufnr, extend(config, { + \ 'style': 'minimal', + \ 'border': get(a:opts, 'border', [1,1,1,1]), + \ 'rounded': get(a:opts, 'rounded', 1), + \ 'prompt': 1, + \ 'title': a:title, + \ 'lines': s:is_vim ? v:null : [a:default], + \ 'highlight': get(a:opts, 'highlight', 'CocFloating'), + \ 'borderhighlight': [get(a:opts, 'borderhighlight', 'CocFloating')], + \ })) +endfunction + +" Could be center(with optional marginTop) or cursor +function! s:get_prompt_dimension(title, default, opts) abort + let relative = get(a:opts, 'position', 'cursor') ==# 'cursor' ? 'cursor' : 'editor' + let curr = win_screenpos(winnr())[1] + wincol() - 2 + let minWidth = get(a:opts, 'minWidth', s:prompt_win_width) + let width = min([max([strwidth(a:default) + 2, strwidth(a:title) + 2, minWidth]), &columns - 2]) + if get(a:opts, 'maxWidth', 0) + let width = min([width, a:opts['maxWidth']]) + endif + if relative ==# 'cursor' + let [lineIdx, colIdx] = coc#cursor#screen_pos() + if width == &columns - 2 + let col = 0 - curr + else + let col = curr + width <= &columns - 2 ? 0 : curr + width - &columns + 2 + endif + let config = { + \ 'row': lineIdx == 0 ? 1 : 0, + \ 'col': colIdx == 0 ? 0 : col - 1, + \ } + else + let marginTop = get(a:opts, 'marginTop', v:null) + if marginTop is v:null + let row = (&lines - &cmdheight - 2) / 2 + else + let row = marginTop < 2 ? 1 : min([marginTop, &columns - &cmdheight]) + endif + let config = { + \ 'col': float2nr((&columns - width) / 2), + \ 'row': row - s:is_vim, + \ } + endif + return extend(config, {'relative': relative, 'width': width, 'height': 1}) +endfunction + +function! s:min_btns_width(buttons) abort + if empty(a:buttons) + return 0 + endif + let minwidth = len(a:buttons)*3 - 1 + for txt in a:buttons + let minwidth = minwidth + strdisplaywidth(txt) + endfor + return minwidth +endfunction + +" Close windows that should auto hide +function! s:close_auto_hide_wins(...) abort + let winids = coc#float#get_float_win_list() + let except = get(a:, 1, 0) + for id in winids + if except && id == except + continue + endif + if getwinvar(id, 'autohide', 0) + call coc#float#close(id) + endif + endfor +endfunction + +function! s:create_loading_buf() abort + let bufnr = coc#float#create_buf(0) + call s:change_loading_buf(bufnr, 0) + return bufnr +endfunction + +function! s:change_loading_buf(bufnr, idx) abort + if bufloaded(a:bufnr) + let target = getbufvar(a:bufnr, 'target_winid', v:null) + if !empty(target) && !coc#float#valid(target) + call coc#float#close(getbufvar(a:bufnr, 'popup')) + return + endif + let line = get(s:frames, a:idx, ' ') + call setbufline(a:bufnr, 1, line) + call coc#highlight#add_highlight(a:bufnr, -1, 'CocNotificationProgress', 0, 0, -1) + let idx = a:idx == len(s:frames) - 1 ? 0 : a:idx + 1 + call timer_start(100, { -> s:change_loading_buf(a:bufnr, idx)}) + endif +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/dict.vim b/vim-config/plugins/coc.nvim/autoload/coc/dict.vim new file mode 100644 index 00000000..00c494b6 --- /dev/null +++ b/vim-config/plugins/coc.nvim/autoload/coc/dict.vim @@ -0,0 +1,32 @@ +scriptencoding utf-8 + +function! coc#dict#equal(one, two) abort + for key in keys(a:one) + if a:one[key] != a:two[key] + return 0 + endif + endfor + return 1 +endfunction + +" Return new dict with keys removed +function! coc#dict#omit(dict, keys) abort + let res = {} + for key in keys(a:dict) + if index(a:keys, key) == -1 + let res[key] = a:dict[key] + endif + endfor + return res +endfunction + +" Return new dict with keys only +function! coc#dict#pick(dict, keys) abort + let res = {} + for key in keys(a:dict) + if index(a:keys, key) != -1 + let res[key] = a:dict[key] + endif + endfor + return res +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/float.vim b/vim-config/plugins/coc.nvim/autoload/coc/float.vim index 5cf6b8c3..4f0204a6 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/float.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/float.vim @@ -1,16 +1,12 @@ scriptencoding utf-8 let s:is_vim = !has('nvim') -let s:root = expand(':h:h:h') -let s:progresschars = get(g:, 'coc_progress_chars', ['โ–‘', 'โ–‡']) let s:borderchars = get(g:, 'coc_borderchars', ['โ”€', 'โ”‚', 'โ”€', 'โ”‚', 'โ”Œ', 'โ”', 'โ”˜', 'โ””']) +let s:rounded_borderchars = s:borderchars[0:3] + ['โ•ญ', 'โ•ฎ', 'โ•ฏ', 'โ•ฐ'] let s:borderjoinchars = get(g:, 'coc_border_joinchars', ['โ”ฌ', 'โ”ค', 'โ”ด', 'โ”œ']) -let s:prompt_win_width = get(g:, 'coc_prompt_win_width', 32) -let s:prompt_win_bufnr = 0 -let s:float_supported = exists('*nvim_open_win') || has('patch-8.1.1719') let s:popup_list_api = exists('*popup_list') -" Popup ids, used when popup_list() not exists +" Popup ids, used when popup_list() doesn't exist let s:popup_list = [] -" winvar: border array of numbers, button boolean +let s:pad_bufnr = -1 " Check visible float/popup exists. function! coc#float#has_float(...) abort @@ -26,15 +22,72 @@ function! coc#float#close_all(...) abort " ignore endtry endfor + return '' endfunction function! coc#float#jump() abort - if s:is_vim - return + if has('nvim') + let winids = coc#float#get_float_win_list() + if !empty(winids) + call win_gotoid(winids[0]) + endif endif - let winids = coc#float#get_float_win_list() - if !empty(winids) - call win_gotoid(winids[0]) +endfunction + +function! coc#float#valid(winid) abort + if a:winid <= 0 + return 0 + endif + if !s:is_vim + if !nvim_win_is_valid(a:winid) + return 0 + endif + return !empty(nvim_win_get_config(a:winid)['relative']) + endif + try + return !empty(popup_getpos(a:winid)) + catch /^Vim\%((\a\+)\)\=:E993/ + " not a popup window + return 0 + endtry +endfunction + +function! coc#float#get_height(winid) abort + if !s:is_vim + let borderwin = coc#float#get_related(a:winid, 'border') + if borderwin + return nvim_win_get_height(borderwin) + endif + return nvim_win_get_height(a:winid) + endif + return get(popup_getpos(a:winid), 'height', 0) +endfunction + +function! coc#float#change_height(winid, delta) abort + if s:is_vim + let curr = get(popup_getpos(a:winid), 'core_height', v:null) + if curr isnot v:null + call popup_move(a:winid, { + \ 'maxheight': max([1, curr + a:delta]), + \ 'minheight': max([1, curr + a:delta]), + \ }) + endif + else + let winids = copy(coc#window#get_var(a:winid, 'related', [])) + call filter(winids, 'index(["border","pad","scrollbar"],coc#window#get_var(v:val,"kind","")) >= 0') + call add(winids, a:winid) + for winid in winids + if coc#window#get_var(winid, 'kind', '') ==# 'border' + let bufnr = winbufnr(winid) + if a:delta > 0 + call appendbufline(bufnr, 1, repeat(getbufline(bufnr, 2), a:delta)) + else + call deletebufline(bufnr, 2, 2 - a:delta - 1) + endif + endif + let height = nvim_win_get_height(winid) + call nvim_win_set_height(winid, max([1, height + a:delta])) + endfor endif endfunction @@ -50,17 +103,32 @@ endfunction " - cursorline: (optional) enable cursorline when is 1. " - autohide: (optional) window should be closed on CursorMoved when is 1. " - highlight: (optional) highlight of window, default to 'CocFloating' -" - borderhighlight: (optional) should be array for border highlights, +" - borderhighlight: (optional) should be array or string for border highlights, " highlight all borders with first value. " - close: (optional) show close button when is 1. +" - highlights: (optional) highlight items. " - buttons: (optional) array of button text for create buttons at bottom. " - codes: (optional) list of CodeBlock. -" - winblend: winblend option for float window, neovim only. -" - shadow: use shadow as border style, neovim only. -" - focusable: neovim only, default to true. +" - winblend: (optional) winblend option for float window, neovim only. +" - shadow: (optional) use shadow as border style, neovim only. +" - focusable: (optional) neovim only, default to true. +" - scrollinside: (optional) neovim only, create scrollbar inside window. +" - rounded: (optional) use rounded borderchars, ignored when borderchars exists. +" - zindex: (optional) zindex of window, default 50. +" - borderchars: (optional) borderchars, should be length of 8 +" - nopad: (optional) not add pad when 1 +" - index: (optional) line index function! coc#float#create_float_win(winid, bufnr, config) abort let lines = get(a:config, 'lines', v:null) - let bufnr = coc#float#create_buf(a:bufnr, lines, 'hide') + let bufnr = a:bufnr + try + let bufnr = coc#float#create_buf(a:bufnr, lines, 'hide') + catch /E523:/ + " happens when using getchar() #3921 + return [] + endtry + let lnum = max([1, get(a:config, 'index', 0) + 1]) + let zindex = get(a:config, 'zindex', 50) " use exists if a:winid && coc#float#valid(a:winid) if s:is_vim @@ -73,21 +141,29 @@ function! coc#float#create_float_win(winid, bufnr, config) abort \ 'minheight': a:config['height'], \ 'maxwidth': a:config['width'], \ 'maxheight': a:config['height'], - \ 'cursorline': get(a:config, 'cursorline', 0), \ 'title': get(a:config, 'title', ''), + \ 'highlight': get(a:config, 'highlight', 'CocFloating'), + \ 'borderhighlight': [s:get_borderhighlight(a:config)], \ } if !s:empty_border(get(a:config, 'border', [])) let opts['border'] = a:config['border'] endif call popup_setoptions(a:winid, opts) + call win_execute(a:winid, 'exe '.lnum) call coc#float#vim_buttons(a:winid, a:config) call s:add_highlights(a:winid, a:config, 0) return [a:winid, winbufnr(a:winid)] else - let config = s:convert_config_nvim(a:config) + let config = s:convert_config_nvim(a:config, 0) + let hlgroup = get(a:config, 'highlight', 'CocFloating') + let current = getwinvar(a:winid, '&winhl', '') + let winhl = coc#util#merge_winhl(current, [['Normal', hlgroup], ['FoldColumn', hlgroup]]) + if winhl !=# current + call setwinvar(a:winid, '&winhl', winhl) + endif call nvim_win_set_buf(a:winid, bufnr) call nvim_win_set_config(a:winid, config) - call nvim_win_set_cursor(a:winid, [1, 0]) + call nvim_win_set_cursor(a:winid, [lnum, 0]) call coc#float#nvim_create_related(a:winid, config, a:config) call s:add_highlights(a:winid, a:config, 0) return [a:winid, bufnr] @@ -99,134 +175,80 @@ function! coc#float#create_float_win(winid, bufnr, config) abort let title = get(a:config, 'title', '') let buttons = get(a:config, 'buttons', []) let hlgroup = get(a:config, 'highlight', 'CocFloating') + let nopad = get(a:config, 'nopad', 0) + let border = s:empty_border(get(a:config, 'border', [])) ? [0, 0, 0, 0] : a:config['border'] let opts = { \ 'title': title, \ 'line': line, \ 'col': col, \ 'fixed': 1, - \ 'padding': empty(title) ? [0, 1, 0, 1] : [0, 0, 0, 0], - \ 'borderchars': s:borderchars, + \ 'padding': [0, !nopad && !border[1], 0, !nopad && !border[3]], + \ 'borderchars': s:get_borderchars(a:config), \ 'highlight': hlgroup, - \ 'cursorline': get(a:config, 'cursorline', 0), \ 'minwidth': a:config['width'], \ 'minheight': a:config['height'], \ 'maxwidth': a:config['width'], - \ 'maxheight': a:config['height'] + \ 'maxheight': a:config['height'], + \ 'close': get(a:config, 'close', 0) ? 'button' : 'none', + \ 'border': border, + \ 'zindex': zindex, + \ 'callback': { -> coc#float#on_close(winid)}, + \ 'borderhighlight': [s:get_borderhighlight(a:config)], + \ 'scrollbarhighlight': 'CocFloatSbar', + \ 'thumbhighlight': 'CocFloatThumb', \ } - if get(a:config, 'close', 0) - let opts['close'] = 'button' - endif - if !empty(get(a:config, 'borderhighlight', v:null)) - let borderhighlight = a:config['borderhighlight'] - let opts['borderhighlight'] = type(borderhighlight) == 3 - \ ? map(borderhighlight, 'coc#highlight#compose_hlgroup(v:val,"'.hlgroup.'")') - \ : [coc#highlight#compose_hlgroup(borderhighlight, hlgroup)] - endif - if !s:empty_border(get(a:config, 'border', [])) - let opts['border'] = a:config['border'] - endif let winid = popup_create(bufnr, opts) if !s:popup_list_api call add(s:popup_list, winid) endif - if winid == 0 - return [] - endif + call s:set_float_defaults(winid, a:config) + call win_execute(winid, 'exe '.lnum) call coc#float#vim_buttons(winid, a:config) - if has("patch-8.1.2281") - call setwinvar(winid, '&showbreak', 'NONE') - endif else - let config = s:convert_config_nvim(a:config) - let border = get(a:config, 'border', []) - if has('nvim-0.5.0') && get(a:config, 'shadow', 0) && empty(get(a:config, 'buttons', v:null)) && empty(get(border, 2, 0)) - let config['border'] = 'shadow' - endif + let config = s:convert_config_nvim(a:config, 1) noa let winid = nvim_open_win(bufnr, 0, config) - if winid == 0 + if winid is 0 return [] endif - let hlgroup = get(a:config, 'highlight', 'CocFloating') - call setwinvar(winid, '&winhl', 'Normal:'.hlgroup.',NormalNC:'.hlgroup.',FoldColumn:'.hlgroup) - call setwinvar(winid, '&signcolumn', 'no') - call setwinvar(winid, '&foldenable', 0) " cursorline highlight not work on old neovim - call setwinvar(winid, '&cursorline', 0) - call setwinvar(winid, 'border', get(a:config, 'border', [])) - if get(a:config, 'winblend', 0) - call setwinvar(winid, '&winblend', a:config['winblend']) - endif - " no left border - if s:empty_border(get(a:config, 'border', [])) || a:config['border'][3] == 0 - call setwinvar(winid, '&foldcolumn', 1) - else - call setwinvar(winid, '&foldcolumn', 0) - endif - call nvim_win_set_cursor(winid, [1, 0]) + call s:set_float_defaults(winid, a:config) + call nvim_win_set_cursor(winid, [lnum, 0]) call coc#float#nvim_create_related(winid, config, a:config) + call coc#float#nvim_set_winblend(winid, get(a:config, 'winblend', v:null)) endif - if get(a:config, 'autohide', 0) - call setwinvar(winid, 'autohide', 1) - endif - if s:is_vim || has('nvim-0.5.0') - call setwinvar(winid, '&scrolloff', 0) - endif - call setwinvar(winid, 'float', 1) - call setwinvar(winid, '&list', 0) - call setwinvar(winid, '&number', 0) - call setwinvar(winid, '&relativenumber', 0) - call setwinvar(winid, '&cursorcolumn', 0) - call setwinvar(winid, '&colorcolumn', 0) - call setwinvar(winid, '&wrap', 1) - call setwinvar(winid, '&linebreak', 1) - call setwinvar(winid, '&conceallevel', 0) - call s:add_highlights(winid, a:config, 0) + call s:add_highlights(winid, a:config, 1) let g:coc_last_float_win = winid call coc#util#do_autocmd('CocOpenFloat') return [winid, bufnr] endfunction -function! coc#float#valid(winid) abort - if a:winid <= 0 - return 0 - endif - if has('nvim') - return nvim_win_is_valid(a:winid) ? 1 : 0 - endif - return s:popup_visible(a:winid) -endfunction - function! coc#float#nvim_create_related(winid, config, opts) abort let related = getwinvar(a:winid, 'related', []) let exists = !empty(related) let border = get(a:opts, 'border', []) - let highlights = get(a:opts, 'borderhighlight', []) - let hlgroup = get(a:opts, 'highlight', 'CocFloating') - let borderhighlight = type(highlights) == 1 ? highlights : get(highlights, 0, 'CocFloating') - let borderhighlight = coc#highlight#compose_hlgroup(borderhighlight, hlgroup) - let title = get(a:opts, 'title', '') + let borderhighlight = s:get_borderhighlight(a:opts) let buttons = get(a:opts, 'buttons', []) - let pad = empty(border) || get(border, 1, 0) == 0 - let winblend = get(a:opts, 'winblend', 0) + let pad = !get(a:opts, 'nopad', 0) && (empty(border) || get(border, 1, 0) == 0) let shadow = get(a:opts, 'shadow', 0) if get(a:opts, 'close', 0) - call coc#float#nvim_close_btn(a:config, a:winid, border, borderhighlight, winblend, related) + call coc#float#nvim_close_btn(a:config, a:winid, border, borderhighlight, related) elseif exists call coc#float#close_related(a:winid, 'close') endif if !empty(buttons) - call coc#float#nvim_buttons(a:config, a:winid, buttons, get(border, 2, 0), pad, hlgroup, borderhighlight, winblend, shadow, related) + call coc#float#nvim_buttons(a:config, a:winid, buttons, get(a:opts, 'getchar', 0), get(border, 2, 0), pad, borderhighlight, shadow, related) elseif exists call coc#float#close_related(a:winid, 'buttons') endif if !s:empty_border(border) - call coc#float#nvim_border_win(a:config, a:winid, border, title, !empty(buttons), borderhighlight, winblend, shadow, related) + let borderchars = s:get_borderchars(a:opts) + call coc#float#nvim_border_win(a:config, borderchars, a:winid, border, get(a:opts, 'title', ''), !empty(buttons), borderhighlight, shadow, related) elseif exists call coc#float#close_related(a:winid, 'border') endif " Check right border if pad - call coc#float#nvim_right_pad(a:config, a:winid, hlgroup, winblend, related) + call coc#float#nvim_right_pad(a:config, a:winid, shadow, related) elseif exists call coc#float#close_related(a:winid, 'pad') endif @@ -234,13 +256,13 @@ function! coc#float#nvim_create_related(winid, config, opts) abort endfunction " border window for neovim, content config with border -function! coc#float#nvim_border_win(config, winid, border, title, hasbtn, hlgroup, winblend, shadow, related) abort +function! coc#float#nvim_border_win(config, borderchars, winid, border, title, hasbtn, hlgroup, shadow, related) abort let winid = coc#float#get_related(a:winid, 'border') let row = a:border[0] ? a:config['row'] - 1 : a:config['row'] let col = a:border[3] ? a:config['col'] - 1 : a:config['col'] let width = a:config['width'] + a:border[1] + a:border[3] let height = a:config['height'] + a:border[0] + a:border[2] + (a:hasbtn ? 2 : 0) - let lines = coc#float#create_border_lines(a:border, a:title, a:config['width'], a:config['height'], a:hasbtn) + let lines = coc#float#create_border_lines(a:border, a:borderchars, a:title, a:config['width'], a:config['height'], a:hasbtn) let bufnr = winid ? winbufnr(winid) : 0 let bufnr = coc#float#create_buf(bufnr, lines) let opt = { @@ -252,28 +274,25 @@ function! coc#float#nvim_border_win(config, winid, border, title, hasbtn, hlgrou \ 'focusable': v:false, \ 'style': 'minimal', \ } + if has_key(a:config, 'zindex') + let opt['zindex'] = a:config['zindex'] + endif if has('nvim-0.5.0') && a:shadow && !a:hasbtn && a:border[2] let opt['border'] = 'shadow' endif if winid call nvim_win_set_config(winid, opt) - call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup.',NormalNC:'.a:hlgroup) + call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup) else noa let winid = nvim_open_win(bufnr, 0, opt) - if winid - if a:winblend - call setwinvar(winid, '&winblend', a:winblend) - endif - call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup.',NormalNC:'.a:hlgroup) - call setwinvar(winid, 'target_winid', a:winid) - call setwinvar(winid, 'kind', 'border') - call add(a:related, winid) - endif + call setwinvar(winid, 'delta', -1) + let winhl = 'Normal:'.a:hlgroup + call s:nvim_add_related(winid, a:winid, 'border', winhl, a:related) endif endfunction " neovim only -function! coc#float#nvim_close_btn(config, winid, border, hlgroup, winblend, related) abort +function! coc#float#nvim_close_btn(config, winid, border, hlgroup, related) abort let winid = coc#float#get_related(a:winid, 'close') let config = { \ 'relative': a:config['relative'], @@ -284,31 +303,22 @@ function! coc#float#nvim_close_btn(config, winid, border, hlgroup, winblend, rel \ 'focusable': v:true, \ 'style': 'minimal', \ } - if has('nvim-0.5.0') - let config['zindex'] = 300 + if has_key(a:config, 'zindex') + let config['zindex'] = a:config['zindex'] + 2 endif if winid - call nvim_win_set_config(winid, config) + call nvim_win_set_config(winid, coc#dict#pick(config, ['relative', 'row', 'col'])) else let bufnr = coc#float#create_buf(0, ['X']) noa let winid = nvim_open_win(bufnr, 0, config) - if winid - call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup.',NormalNC:'.a:hlgroup) - call setwinvar(winid, 'target_winid', a:winid) - call setwinvar(winid, 'kind', 'close') - if a:winblend - call setwinvar(winid, '&winblend', a:winblend) - endif - call add(a:related, winid) - endif - call s:nvim_create_keymap(winid) + let winhl = 'Normal:'.a:hlgroup + call s:nvim_add_related(winid, a:winid, 'close', winhl, a:related) endif endfunction " Create padding window by config of current window & border config -function! coc#float#nvim_right_pad(config, winid, hlgroup, winblend, related) abort +function! coc#float#nvim_right_pad(config, winid, shadow, related) abort let winid = coc#float#get_related(a:winid, 'pad') - let bufnr = 0 let config = { \ 'relative': a:config['relative'], \ 'width': 1, @@ -318,36 +328,27 @@ function! coc#float#nvim_right_pad(config, winid, hlgroup, winblend, related) ab \ 'focusable': v:false, \ 'style': 'minimal', \ } - if has('nvim-0.5.0') - let config['zindex'] = 300 + if has_key(a:config, 'zindex') + let config['zindex'] = a:config['zindex'] + 1 endif - if winid && nvim_win_is_valid(winid) - let bufnr = nvim_win_get_buf(winid) - noa call nvim_win_close(winid, 1) + if has('nvim-0.5.0') && a:shadow + let config['border'] = 'shadow' endif - let bufnr = coc#float#create_buf(bufnr, repeat([''], a:config['height'])) - noa let winid = nvim_open_win(bufnr, 0, config) - if winid - " minimal not work - if !has('nvim-0.4.3') - call setwinvar(winid, '&colorcolumn', 0) - call setwinvar(winid, '&number', 0) - call setwinvar(winid, '&relativenumber', 0) - call setwinvar(winid, '&foldcolumn', 0) - call setwinvar(winid, '&signcolumn', 0) - endif - if a:winblend - call setwinvar(winid, '&winblend', a:winblend) + if winid && nvim_win_is_valid(winid) + if has('nvim-0.5.0') + call nvim_win_set_config(winid, coc#dict#pick(config, ['relative', 'row', 'col'])) + call nvim_win_set_height(winid, config['height']) + return endif - call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup.',NormalNC:'.a:hlgroup) - call setwinvar(winid, 'target_winid', a:winid) - call setwinvar(winid, 'kind', 'pad') - call add(a:related, winid) + noa call nvim_win_close(winid, 1) endif + let s:pad_bufnr = bufloaded(s:pad_bufnr) ? s:pad_bufnr : coc#float#create_buf(0, repeat([''], &lines), 'hide') + noa let winid = nvim_open_win(s:pad_bufnr, 0, config) + call s:nvim_add_related(winid, a:winid, 'pad', '', a:related) endfunction " draw buttons window for window with config -function! coc#float#nvim_buttons(config, winid, buttons, borderbottom, pad, hlgroup, borderhighlight, winblend, shadow, related) abort +function! coc#float#nvim_buttons(config, winid, buttons, getchar, borderbottom, pad, borderhighlight, shadow, related) abort let winid = coc#float#get_related(a:winid, 'buttons') let width = a:config['width'] + (a:pad ? 1 : 0) let config = { @@ -359,7 +360,7 @@ function! coc#float#nvim_buttons(config, winid, buttons, borderbottom, pad, hlgr \ 'focusable': 1, \ 'style': 'minimal', \ } - if has('nvim-0.5.0') + if has('nvim-0.5.1') let config['zindex'] = 300 if a:shadow let config['border'] = 'shadow' @@ -373,17 +374,11 @@ function! coc#float#nvim_buttons(config, winid, buttons, borderbottom, pad, hlgr let bufnr = s:create_btns_buffer(0, width, a:buttons, a:borderbottom) noa let winid = nvim_open_win(bufnr, 0, config) if winid - call setwinvar(winid, '&winhl', 'Normal:'.a:hlgroup.',NormalNC:'.a:hlgroup) - call setwinvar(winid, 'target_winid', a:winid) - call setwinvar(winid, 'kind', 'buttons') - if a:winblend - call setwinvar(winid, '&winblend', a:winblend) - endif - call add(a:related, winid) + call s:nvim_add_related(winid, a:winid, 'buttons', '', a:related) call s:nvim_create_keymap(winid) endif endif - if bufnr && a:hlgroup != a:borderhighlight + if bufnr call nvim_buf_clear_namespace(bufnr, -1, 0, -1) call nvim_buf_add_highlight(bufnr, 1, a:borderhighlight, 0, 0, -1) if a:borderbottom @@ -394,13 +389,51 @@ function! coc#float#nvim_buttons(config, winid, buttons, borderbottom, pad, hlgr for col in vcols call nvim_buf_add_highlight(bufnr, 1, a:borderhighlight, 1, col, col + 3) endfor + if a:getchar + let keys = s:gen_filter_keys(getbufline(bufnr, 2)[0]) + call matchaddpos('MoreMsg', map(keys[0], "[2,v:val]"), 99, -1, {'window': winid}) + call timer_start(10, {-> coc#float#getchar(winid, keys[1])}) + endif + endif +endfunction + +function! coc#float#getchar(winid, keys) abort + let ch = coc#prompt#getc() + let target = getwinvar(a:winid, 'target_winid', 0) + if ch ==# "\" + call coc#float#close(target) + return endif + if ch ==# "\" + if getwinvar(v:mouse_winid, 'kind', '') ==# 'close' + call coc#float#close(target) + return + endif + if v:mouse_winid == a:winid && v:mouse_lnum == 2 + let vcols = getbufvar(winbufnr(a:winid), 'vcols', []) + let col = v:mouse_col - 1 + if index(vcols, col) < 0 + let filtered = filter(vcols, 'v:val < col') + call coc#rpc#notify('FloatBtnClick', [winbufnr(target), len(filtered)]) + call coc#float#close(target) + return + endif + endif + else + let idx = index(a:keys, ch) + if idx >= 0 + call coc#rpc#notify('FloatBtnClick', [winbufnr(target), idx]) + call coc#float#close(target) + return + endif + endif + call coc#float#getchar(a:winid, a:keys) endfunction " Create or refresh scrollbar for winid " Need called on create, config, buffer change, scrolled function! coc#float#nvim_scrollbar(winid) abort - if !has('nvim-0.4.0') || getwinvar(a:winid, 'target_winid', 0) + if s:is_vim return endif let winids = nvim_tabpage_list_wins(nvim_get_current_tabpage()) @@ -422,13 +455,14 @@ function! coc#float#nvim_scrollbar(winid) abort let ch = coc#float#content_height(bufnr, cw, getwinvar(a:winid, '&wrap')) let closewin = coc#float#get_related(a:winid, 'close') let border = getwinvar(a:winid, 'border', []) + let scrollinside = getwinvar(a:winid, 'scrollinside', 0) && get(border, 1, 0) let winblend = getwinvar(a:winid, '&winblend', 0) let move_down = closewin && !get(border, 0, 0) let id = coc#float#get_related(a:winid, 'scrollbar') if ch <= height || height <= 1 " no scrollbar, remove exists if id - call s:close_win(id) + call s:close_win(id, 1) endif return endif @@ -440,15 +474,18 @@ function! coc#float#nvim_scrollbar(winid) abort let sbuf = coc#float#create_buf(sbuf, repeat([' '], height)) let opts = { \ 'row': move_down ? row + 1 : row, - \ 'col': column + width, + \ 'col': column + width - scrollinside, \ 'relative': relative, \ 'width': 1, \ 'height': height, \ 'focusable': v:false, \ 'style': 'minimal', \ } - if has('nvim-0.5.0') - let opts['zindex'] = 300 + if has_key(config, 'zindex') + let opts['zindex'] = config['zindex'] + 2 + endif + if has('nvim-0.5.0') && s:has_shadow(config) + let opts['border'] = 'shadow' endif if id call nvim_win_set_config(id, opts) @@ -462,9 +499,11 @@ function! coc#float#nvim_scrollbar(winid) abort endif call setwinvar(id, 'kind', 'scrollbar') call setwinvar(id, 'target_winid', a:winid) - call s:add_related(id, a:winid) + call coc#float#add_related(id, a:winid) + endif + if !scrollinside + call coc#float#nvim_scroll_adjust(a:winid) endif - call coc#float#nvim_scroll_adjust(a:winid) let thumb_height = max([1, float2nr(floor(height * (height + 0.0)/ch))]) let wininfo = getwininfo(a:winid)[0] let start = 0 @@ -483,27 +522,28 @@ function! coc#float#nvim_scrollbar(winid) abort call nvim_buf_clear_namespace(sbuf, -1, 0, -1) for idx in range(0, height - 1) if idx >= start && idx < start + thumb_height - call nvim_buf_add_highlight(sbuf, -1, 'PmenuThumb', idx, 0, 1) + call nvim_buf_add_highlight(sbuf, -1, 'CocFloatThumb', idx, 0, 1) else - call nvim_buf_add_highlight(sbuf, -1, 'PmenuSbar', idx, 0, 1) + call nvim_buf_add_highlight(sbuf, -1, 'CocFloatSbar', idx, 0, 1) endif endfor endfunction -function! coc#float#create_border_lines(border, title, width, height, hasbtn) abort +function! coc#float#create_border_lines(border, borderchars, title, width, height, hasbtn) abort + let borderchars = a:borderchars let list = [] if a:border[0] - let top = (a:border[3] ? s:borderchars[4]: '') - \.repeat(s:borderchars[0], a:width) - \.(a:border[1] ? s:borderchars[5] : '') + let top = (a:border[3] ? borderchars[4]: '') + \.repeat(borderchars[0], a:width) + \.(a:border[1] ? borderchars[5] : '') if !empty(a:title) - let top = coc#helper#str_compose(top, 1, a:title.' ') + let top = coc#string#compose(top, 1, a:title.' ') endif call add(list, top) endif - let mid = (a:border[3] ? s:borderchars[3]: '') + let mid = (a:border[3] ? borderchars[3]: '') \.repeat(' ', a:width) - \.(a:border[1] ? s:borderchars[1] : '') + \.(a:border[1] ? borderchars[1] : '') call extend(list, repeat([mid], a:height + (a:hasbtn ? 2 : 0))) if a:hasbtn let list[len(list) - 2] = (a:border[3] ? s:borderjoinchars[3]: '') @@ -511,159 +551,32 @@ function! coc#float#create_border_lines(border, title, width, height, hasbtn) ab \.(a:border[1] ? s:borderjoinchars[1] : '') endif if a:border[2] - let bot = (a:border[3] ? s:borderchars[7]: '') - \.repeat(s:borderchars[2], a:width) - \.(a:border[1] ? s:borderchars[6] : '') + let bot = (a:border[3] ? borderchars[7]: '') + \.repeat(borderchars[2], a:width) + \.(a:border[1] ? borderchars[6] : '') call add(list, bot) endif return list endfunction -" Get config, convert lines, create window, add highlights -function! coc#float#create_cursor_float(winid, bufnr, lines, config) abort - if !s:float_supported - return v:null - endif - if s:is_blocking() - return v:null - endif - let pumAlignTop = get(a:config, 'pumAlignTop', 0) - let modes = get(a:config, 'modes', ['n', 'i', 'ic', 's']) - let mode = mode() - let currbuf = bufnr('%') - let pos = [line('.'), col('.')] - if index(modes, mode) == -1 - return v:null - endif - if has('nvim') && mode ==# 'i' - " helps to fix undo issue, don't know why. - call feedkeys("\u", 'n') - endif - let dimension = coc#float#get_config_cursor(a:lines, a:config) - if empty(dimension) - return v:null - endif - if pumvisible() && ((pumAlignTop && dimension['row'] <0)|| (!pumAlignTop && dimension['row'] > 0)) - return v:null - endif - let width = dimension['width'] - let lines = map(a:lines, {_, s -> s =~# '^โ”€' ? repeat('โ”€', width) : s}) - let config = extend(extend({'lines': lines, 'relative': 'cursor'}, a:config), dimension) - call coc#float#close_auto_hide_wins(a:winid) - let res = coc#float#create_float_win(a:winid, a:bufnr, config) - if empty(res) - return v:null - endif - let alignTop = dimension['row'] < 0 - let winid = res[0] - let bufnr = res[1] - redraw - if has('nvim') - call coc#float#nvim_scrollbar(winid) - endif - return [currbuf, pos, winid, bufnr, alignTop] -endfunction - -" Create float window for input -function! coc#float#create_prompt_win(title, default, opts) abort - call coc#float#close_auto_hide_wins() - " Calculate col - let curr = win_screenpos(winnr())[1] + wincol() - 2 - let width = coc#helper#min(max([strdisplaywidth(a:default) + 2, s:prompt_win_width]), &columns - 2) - if width == &columns - 2 - let col = 0 - curr - else - let col = curr + width <= &columns - 2 ? 0 : &columns - s:prompt_win_width - endif - let [lineIdx, colIdx] = coc#cursor#screen_pos() - let bufnr = 0 - if has('nvim') - let bufnr = s:prompt_win_bufnr - else - execute 'hi link CocPopupTerminal '.get(a:opts, 'highlight', 'CocFloating') - let node = expand(get(g:, 'coc_node_path', 'node')) - let bufnr = term_start([node, s:root . '/bin/prompt.js', a:default], { - \ 'term_highlight': 'CocPopupTerminal', - \ 'hidden': 1, - \ 'term_finish': 'close' - \ }) - call term_setapi(bufnr, "Coc") - endif - let res = coc#float#create_float_win(0, bufnr, { - \ 'relative': 'cursor', - \ 'row': lineIdx == 0 ? 1 : 0, - \ 'col': colIdx == 0 ? 0 : col - 1, - \ 'width': width, - \ 'height': 1, - \ 'style': 'minimal', - \ 'border': [1,1,1,1], - \ 'prompt': 1, - \ 'title': a:title, - \ 'lines': s:is_vim ? v:null : [a:default], - \ 'highlight': get(a:opts, 'highlight', 'CocFloating'), - \ 'borderhighlight': [get(a:opts, 'borderhighlight', 'CocFloating')], - \ }) - if empty(res) || res[0] == 0 - return - endif - let winid = res[0] - let bufnr = res[1] - if has('nvim') - let s:prompt_win_bufnr = res[1] - execute 'sign unplace 6 buffer='.s:prompt_win_bufnr - call nvim_set_current_win(winid) - inoremap - inoremap pumvisible() ? "\" : "\" - exe 'imap ' - exe 'nnoremap :call coc#float#close('.winid.')' - exe 'inoremap "\=coc#float#prompt_insert(getline(''.''))\\"' - call feedkeys('A', 'in') - endif - call coc#util#do_autocmd('CocOpenFloatPrompt') - return [bufnr, winid] -endfunction - -function! coc#float#prompt_insert(text) abort - call coc#rpc#notify('PromptInsert', [a:text]) - return '' -endfunction - " Close float window by id -function! coc#float#close(winid) abort +function! coc#float#close(winid, ...) abort + let noautocmd = get(a:, 1, 0) call coc#float#close_related(a:winid) - call s:close_win(a:winid) + call s:close_win(a:winid, noautocmd) return 1 endfunction -" Float window id on current tab. -" return 0 if not found, used by test only -function! coc#float#get_float_win() abort - if has('nvim') - for i in range(1, winnr('$')) - let id = win_getid(i) - let config = nvim_win_get_config(id) - if (!empty(config) && config['focusable'] == v:true && !empty(config['relative'])) - if !getwinvar(id, 'button', 0) - return id - endif - endif - endfor - else - let ids = s:popup_list_api ? popup_list() : s:popup_list - return get(filter(ids, 's:popup_visible(v:val)'), 0, 0) - endif - return 0 -endfunction - +" Get visible float windows function! coc#float#get_float_win_list(...) abort let res = [] - let all = get(a:, 1, 0) + let list_all = get(a:, 1, 0) if s:is_vim if s:popup_list_api - return filter(popup_list(), 'popup_getpos(v:val)["visible"]'.(all ? '' : '&& getwinvar(v:val, "float", 0)')) + return filter(popup_list(), 'popup_getpos(v:val)["visible"]'.(list_all ? '' : '&& getwinvar(v:val, "float", 0)')) endif return filter(s:popup_list, 's:popup_visible(v:val)') - elseif has('nvim') && exists('*nvim_win_get_config') + else let res = [] for i in range(1, winnr('$')) let id = win_getid(i) @@ -672,7 +585,7 @@ function! coc#float#get_float_win_list(...) abort continue endif " ignore border & button window & others - if !all && !getwinvar(id, 'float', 0) + if list_all == 0 && !getwinvar(id, 'float', 0) continue endif call add(res, id) @@ -682,6 +595,25 @@ function! coc#float#get_float_win_list(...) abort return [] endfunction +function! coc#float#get_float_by_kind(kind) abort + if s:is_vim + if s:popup_list_api + return get(filter(popup_list(), 'popup_getpos(v:val)["visible"] && getwinvar(v:val, "kind", "") ==# "'.a:kind.'"'), 0, 0) + endif + return get(filter(s:popup_list, 's:popup_visible(v:val) && getwinvar(v:val, "kind", "") ==# "'.a:kind.'"'), 0, 0) + else + let res = [] + for i in range(1, winnr('$')) + let winid = win_getid(i) + let config = nvim_win_get_config(winid) + if !empty(config['relative']) && getwinvar(winid, 'kind', '') ==# a:kind + return winid + endif + endfor + endif + return 0 +endfunction + " Check if a float window is scrollable function! coc#float#scrollable(winid) abort let bufnr = winbufnr(a:winid) @@ -690,8 +622,8 @@ function! coc#float#scrollable(winid) abort endif if s:is_vim let pos = popup_getpos(a:winid) - if get(popup_getoptions(a:winid), 'scrollbar', 0) - return get(pos, 'scrollbar', 0) + if get(pos, 'scrollbar', 0) + return 1 endif let ch = coc#float#content_height(bufnr, pos['core_width'], getwinvar(a:winid, '&wrap')) return ch > pos['core_height'] @@ -699,7 +631,7 @@ function! coc#float#scrollable(winid) abort let height = nvim_win_get_height(a:winid) let width = nvim_win_get_width(a:winid) if width > 1 && getwinvar(a:winid, '&foldcolumn', 0) - " since we use foldcolumn for left pading + " since we use foldcolumn for left padding let width = width - 1 endif let ch = coc#float#content_height(bufnr, width, getwinvar(a:winid, '&wrap')) @@ -717,16 +649,12 @@ function! coc#float#scroll(forward, ...) throw 'coc#float#scroll() requires nvim >= 0.4.0 or vim >= 8.2.0750' endif let amount = get(a:, 1, 0) - let winids = filter(coc#float#get_float_win_list(), 'coc#float#scrollable(v:val)') + let winids = filter(coc#float#get_float_win_list(), 'coc#float#scrollable(v:val) && getwinvar(v:val,"kind","") !=# "pum"') if empty(winids) - return '' + return mode() =~ '^i' || mode() ==# 'v' ? "" : "\" endif for winid in winids - if s:is_vim - call coc#float#scroll_win(winid, a:forward, amount) - else - call timer_start(0, { -> coc#float#scroll_win(winid, a:forward, amount)}) - endif + call s:scroll_win(winid, a:forward, amount) endfor return mode() =~ '^i' || mode() ==# 'v' ? "" : "\" endfunction @@ -764,70 +692,15 @@ function! coc#float#scroll_win(winid, forward, amount) abort endif endfunction -function! s:popup_visible(id) abort - let pos = popup_getpos(a:id) - if !empty(pos) && get(pos, 'visible', 0) - return 1 - endif - return 0 -endfunction - -function! s:convert_config_nvim(config) abort - let valids = ['relative', 'win', 'anchor', 'width', 'height', 'bufpos', 'col', 'row', 'focusable', 'style'] - let result = coc#helper#dict_pick(a:config, valids) - let border = get(a:config, 'border', []) - if !s:empty_border(border) - if result['relative'] ==# 'cursor' && result['row'] < 0 - " move top when has bottom border - if get(border, 2, 0) - let result['row'] = result['row'] - 1 - endif - else - " move down when has top border - if get(border, 0, 0) && !get(a:config, 'prompt', 0) - let result['row'] = result['row'] + 1 - endif - endif - " move right when has left border - if get(border, 3, 0) - let result['col'] = result['col'] + 1 - endif - let result['width'] = float2nr(result['width'] + 1 - get(border,3, 0)) - else - let result['width'] = float2nr(result['width'] + 1) - endif - let result['height'] = float2nr(result['height']) - return result -endfunction - -" Close windows that could auto hide -function! coc#float#close_auto_hide_wins(...) abort - let winids = coc#float#get_float_win_list() - let except = get(a:, 1, 0) - for id in winids - if except && id == except - continue - endif - if getwinvar(id, 'autohide', 0) - call coc#float#close(id) - endif - endfor -endfunction - function! coc#float#content_height(bufnr, width, wrap) abort if !bufloaded(a:bufnr) return 0 endif if !a:wrap - return has('nvim') ? nvim_buf_line_count(a:bufnr) : len(getbufline(a:bufnr, 1, '$')) + return coc#compat#buf_line_count(a:bufnr) endif let lines = has('nvim') ? nvim_buf_get_lines(a:bufnr, 0, -1, 0) : getbufline(a:bufnr, 1, '$') - let total = 0 - for line in lines - let dw = max([1, strdisplaywidth(line)]) - let total += float2nr(ceil(str2float(string(dw))/a:width)) - endfor - return total + return coc#string#content_height(lines, a:width) endfunction function! coc#float#nvim_refresh_scrollbar(winid) abort @@ -837,29 +710,40 @@ function! coc#float#nvim_refresh_scrollbar(winid) abort endif endfunction +function! coc#float#on_close(winid) abort + let winids = coc#float#get_float_win_list() + for winid in winids + let target = getwinvar(winid, 'target_winid', -1) + if target == a:winid + call coc#float#close(winid) + endif + endfor +endfunction + " Close related windows, or specific kind function! coc#float#close_related(winid, ...) abort - let tabnr = coc#window#tabnr(a:winid) - if tabnr != -1 - let timer = gettabwinvar(tabnr, a:winid, 'timer', 0) - if timer - call timer_stop(timer) - endif - let kind = get(a:, 1, '') - let winids = gettabwinvar(tabnr, a:winid, 'related', []) - for id in winids - if s:is_vim + if !coc#float#valid(a:winid) + return + endif + let timer = coc#window#get_var(a:winid, 'timer', 0) + if timer + call timer_stop(timer) + endif + let kind = get(a:, 1, '') + let winids = coc#window#get_var(a:winid, 'related', []) + for id in winids + let curr = coc#window#get_var(id, 'kind', '') + if empty(kind) || curr ==# kind + if curr == 'list' + call coc#float#close(id, 1) + elseif s:is_vim " vim doesn't throw noa call popup_close(id) else - if empty(kind) || gettabwinvar(tabnr, id, 'kind', '') ==# kind - if nvim_win_is_valid(id) - noa call nvim_win_close(id, 1) - endif - endif + silent! noa call nvim_win_close(id, 1) endif - endfor - endif + endif + endfor endfunction " Close related windows if target window is not visible. @@ -868,11 +752,11 @@ function! coc#float#check_related() abort let ids = coc#float#get_float_win_list(1) for id in ids let target = getwinvar(id, 'target_winid', 0) - if (target && index(ids, target) == -1) || getwinvar(id, 'kind', '') == 'pum' + if target && index(ids, target) == -1 call add(invalids, id) endif endfor - if !s:popup_list_api + if s:is_vim && !s:popup_list_api let s:popup_list = filter(ids, "index(invalids, v:val) == -1") endif for id in invalids @@ -880,195 +764,7 @@ function! coc#float#check_related() abort endfor endfunction -" Dimension of window with lines relative to cursor -" Width & height excludes border & padding -function! coc#float#get_config_cursor(lines, config) abort - let preferTop = get(a:config, 'preferTop', 0) - let title = get(a:config, 'title', '') - let border = get(a:config, 'border', [0, 0, 0, 0]) - if s:empty_border(border) && len(title) - let border = [1, 1, 1, 1] - endif - let bh = get(border, 0, 0) + get(border, 2, 0) - let vh = &lines - &cmdheight - 1 - if vh <= 0 - return v:null - endif - let maxWidth = coc#helper#min(get(a:config, 'maxWidth', &columns - 1), &columns - 1) - if maxWidth < 3 - return v:null - endif - let maxHeight = coc#helper#min(get(a:config, 'maxHeight', vh), vh) - let ch = 0 - let width = coc#helper#min(40, strdisplaywidth(title)) + 3 - for line in a:lines - let dw = max([1, strdisplaywidth(line)]) - let width = max([width, dw + 2]) - let ch += float2nr(ceil(str2float(string(dw))/(maxWidth - 2))) - endfor - let width = coc#helper#min(maxWidth, width) - let [lineIdx, colIdx] = coc#cursor#screen_pos() - " How much we should move left - let offsetX = coc#helper#min(get(a:config, 'offsetX', 0), colIdx) - let showTop = 0 - let hb = vh - lineIdx -1 - if lineIdx > bh + 2 && (preferTop || (lineIdx > hb && hb < ch + bh)) - let showTop = 1 - endif - let height = coc#helper#min(maxHeight, ch + bh, showTop ? lineIdx - 1 : hb) - if height <= bh - return v:null - endif - let col = - max([offsetX, colIdx - (&columns - 1 - width)]) - let row = showTop ? - height + bh : 1 - return { - \ 'row': row, - \ 'col': col, - \ 'width': width - 2, - \ 'height': height - bh - \ } -endfunction - -function! coc#float#create_pum_float(winid, bufnr, lines, config) abort - if !pumvisible() || !s:float_supported - return v:null - endif - let pumbounding = a:config['pumbounding'] - let pw = pumbounding['width'] + get(pumbounding, 'scrollbar', 0) - let rp = &columns - pumbounding['col'] - pw - let showRight = pumbounding['col'] > rp ? 0 : 1 - let maxWidth = showRight ? coc#helper#min(rp - 1, a:config['maxWidth']) : coc#helper#min(pumbounding['col'] - 1, a:config['maxWidth']) - let border = get(a:config, 'border', []) - let bh = get(border, 0 ,0) + get(border, 2, 0) - let maxHeight = &lines - pumbounding['row'] - &cmdheight - 1 - bh - if maxWidth <= 2 || maxHeight < 1 - return v:null - endif - let ch = 0 - let width = 0 - for line in a:lines - let dw = max([1, strdisplaywidth(line)]) - let width = max([width, dw + 2]) - let ch += float2nr(ceil(str2float(string(dw))/(maxWidth - 2))) - endfor - let width = float2nr(coc#helper#min(maxWidth, width)) - let height = float2nr(coc#helper#min(maxHeight, ch)) - let lines = map(a:lines, {_, s -> s =~# '^โ”€' ? repeat('โ”€', width - 2 + (s:is_vim && ch > height ? -1 : 0)) : s}) - let opts = { - \ 'lines': lines, - \ 'relative': 'editor', - \ 'col': showRight ? pumbounding['col'] + pw : pumbounding['col'] - width - 1, - \ 'row': pumbounding['row'], - \ 'height': height, - \ 'width': width - 2 + (s:is_vim && ch > height ? -1 : 0), - \ 'codes': get(a:config, 'codes', []), - \ } - for key in ['border', 'highlight', 'borderhighlight', 'winblend', 'focusable', 'shadow'] - if has_key(a:config, key) - let opts[key] = a:config[key] - endif - endfor - call coc#float#close_auto_hide_wins(a:winid) - let res = coc#float#create_float_win(a:winid, a:bufnr, opts) - if empty(res) - return v:null - endif - call setwinvar(res[0], 'kind', 'pum') - if has('nvim') - call coc#float#nvim_scrollbar(res[0]) - endif - return res -endfunction - -function! s:empty_border(border) abort - if empty(a:border) - return 1 - endif - if a:border[0] == 0 && a:border[1] == 0 && a:border[2] == 0 && a:border[3] == 0 - return 1 - endif - return 0 -endfunction - " Show float window/popup for user confirm. -function! coc#float#prompt_confirm(title, cb) abort - if s:is_vim && exists('*popup_dialog') - try - call popup_dialog(a:title. ' (y/n)?', { - \ 'highlight': 'Normal', - \ 'filter': 'popup_filter_yesno', - \ 'callback': {id, res -> a:cb(v:null, res)}, - \ 'borderchars': s:borderchars, - \ 'borderhighlight': ['MoreMsg'] - \ }) - catch /.*/ - call a:cb(v:exception) - endtry - return - endif - if has('nvim-0.4.0') - let text = ' '. a:title . ' (y/n)? ' - let maxWidth = coc#helper#min(78, &columns - 2) - let width = coc#helper#min(maxWidth, strdisplaywidth(text)) - let maxHeight = &lines - &cmdheight - 1 - let height = coc#helper#min(maxHeight, float2nr(ceil(str2float(string(strdisplaywidth(text)))/width))) - call coc#float#close_auto_hide_wins() - let arr = coc#float#create_float_win(0, s:prompt_win_bufnr, { - \ 'col': &columns/2 - width/2 - 1, - \ 'row': maxHeight/2 - height/2 - 1, - \ 'width': width, - \ 'height': height, - \ 'border': [1,1,1,1], - \ 'focusable': v:false, - \ 'relative': 'editor', - \ 'highlight': 'Normal', - \ 'borderhighlight': ['MoreMsg'], - \ 'style': 'minimal', - \ 'lines': [text], - \ }) - if empty(arr) - call a:cb('Window create failed!') - return - endif - let winid = arr[0] - let s:prompt_win_bufnr = arr[1] - let res = 0 - redraw - " same result as vim - while 1 - let key = nr2char(getchar()) - if key == "\" - let res = -1 - break - elseif key == "\" || key == 'n' || key == 'N' - let res = 0 - break - elseif key == 'y' || key == 'Y' - let res = 1 - break - endif - endw - call coc#float#close(winid) - call a:cb(v:null, res) - " use relative editor since neovim doesn't support center position - elseif exists('*confirm') - let choice = confirm(a:title, "&Yes\n&No") - call a:cb(v:null, choice == 1) - else - echohl MoreMsg - echom a:title.' (y/n)' - echohl None - let confirm = nr2char(getchar()) - redraw! - if !(confirm ==? "y" || confirm ==? "\r") - echohl Moremsg | echo 'Cancelled.' | echohl None - return 0 - call a:cb(v:null, 0) - end - call a:cb(v:null, 1) - endif -endfunction - " Create buttons popup on vim function! coc#float#vim_buttons(winid, config) abort if !has('patch-8.2.0750') @@ -1079,7 +775,7 @@ function! coc#float#vim_buttons(winid, config) abort let btns = get(a:config, 'buttons', []) if empty(btns) if winid - call s:close_win(winid) + call s:close_win(winid, 1) " fix padding let opts = popup_getoptions(a:winid) let padding = get(opts, 'padding', v:null) @@ -1206,72 +902,27 @@ function! coc#float#vim_filter(winid, key, keys) abort return 0 endfunction -" Create dialog at center -function! coc#float#create_dialog(lines, config) abort - " dialog always have borders - let title = get(a:config, 'title', '') - let buttons = get(a:config, 'buttons', []) - let highlight = get(a:config, 'highlight', 'CocFloating') - let borderhighlight = get(a:config, 'borderhighlight', [highlight]) - let maxheight = coc#helper#min(get(a:config, 'maxHeight', 78), &lines - &cmdheight - 6) - let maxwidth = coc#helper#min(get(a:config, 'maxWidth', 78), &columns - 2) - let close = get(a:config, 'close', 1) - let minwidth = s:min_btns_width(buttons) - if maxheight <= 0 || maxwidth <= 0 || minwidth > maxwidth - throw 'Not enough spaces for dialog' - endif - let ch = 0 - let width = coc#helper#min(strdisplaywidth(title) + 1, maxwidth) - for line in a:lines - let dw = max([1, strdisplaywidth(line)]) - if dw < maxwidth && dw > width - let width = dw - elseif dw > maxwidth - let width = maxwidth - endif - let ch += float2nr(ceil(str2float(string(dw))/maxwidth)) - endfor - let width = max([minwidth, width]) - let height = coc#helper#min(ch ,maxheight) - let opts = { - \ 'relative': 'editor', - \ 'col': &columns/2 - (width + 2)/2, - \ 'row': &lines/2 - (height + 4)/2, - \ 'width': width, - \ 'height': height, - \ 'border': [1,1,1,1], - \ 'title': title, - \ 'close': close, - \ 'highlight': highlight, - \ 'buttons': buttons, - \ 'borderhighlight': borderhighlight, - \ } - if get(a:config, 'cursorline', 0) - let opts['cursorline'] = 1 - endif - let bufnr = coc#float#create_buf(0, a:lines) - call coc#float#close_auto_hide_wins() - let res = coc#float#create_float_win(0, bufnr, opts) - if empty(res) - return - endif - if has('nvim') - if get(a:config, 'cursorline', 0) - execute 'sign place 6 line=1 name=CocCurrentLine buffer='.bufnr - endif - redraw - call coc#float#nvim_scrollbar(res[0]) +function! coc#float#get_related(winid, kind, ...) abort + if coc#float#valid(a:winid) + for winid in coc#window#get_var(a:winid, 'related', []) + if coc#window#get_var(winid, 'kind', '') ==# a:kind + return winid + endif + endfor endif - return res + return get(a:, 1, 0) endfunction -function! coc#float#get_related(winid, kind) abort - for winid in getwinvar(a:winid, 'related', []) - if getwinvar(winid, 'kind', '') ==# a:kind - return winid +function! coc#float#get_row(winid) abort + let winid = s:is_vim ? a:winid : coc#float#get_related(a:winid, 'border', a:winid) + if coc#float#valid(winid) + if s:is_vim + let pos = popup_getpos(winid) + return pos['line'] - 1 endif - endfor - return 0 + let pos = nvim_win_get_position(winid) + return pos[0] + endif endfunction " Create temporarily buffer with optional lines and &bufhidden @@ -1283,180 +934,30 @@ function! coc#float#create_buf(bufnr, ...) abort noa let bufnr = bufadd('') noa call bufload(bufnr) call setbufvar(bufnr, '&buflisted', 0) + call setbufvar(bufnr, '&modeline', 0) + call setbufvar(bufnr, '&buftype', 'nofile') + call setbufvar(bufnr, '&swapfile', 0) else noa let bufnr = nvim_create_buf(v:false, v:true) endif let bufhidden = get(a:, 2, 'wipe') - call setbufvar(bufnr, '&buftype', 'nofile') call setbufvar(bufnr, '&bufhidden', bufhidden) - call setbufvar(bufnr, '&swapfile', 0) call setbufvar(bufnr, '&undolevels', -1) " neovim's bug call setbufvar(bufnr, '&modifiable', 1) endif let lines = get(a:, 1, v:null) - if type(lines) != 7 + if type(lines) == v:t_list if has('nvim') call nvim_buf_set_lines(bufnr, 0, -1, v:false, lines) else - silent call deletebufline(bufnr, 1, '$') - silent call setbufline(bufnr, 1, lines) + silent noa call setbufline(bufnr, 1, lines) + silent noa call deletebufline(bufnr, len(lines) + 1, '$') endif endif return bufnr endfunction -function! coc#float#create_menu(lines, config) abort - let highlight = get(a:config, 'highlight', 'CocFloating') - let borderhighlight = get(a:config, 'borderhighlight', [highlight]) - let opts = { - \ 'lines': a:lines, - \ 'highlight': highlight, - \ 'title': get(a:config, 'title', ''), - \ 'borderhighlight': borderhighlight, - \ 'maxWidth': get(a:config, 'maxWidth', 80), - \ 'maxHeight': get(a:config, 'maxHeight', 80), - \ 'border': [1, 1, 1, 1], - \ 'relative': 'cursor', - \ } - if s:is_vim - let opts['cursorline'] = 1 - endif - let dimension = coc#float#get_config_cursor(a:lines, opts) - call extend(opts, dimension) - call coc#float#close_auto_hide_wins() - let res = coc#float#create_float_win(0, s:prompt_win_bufnr, opts) - if empty(res) - return - endif - let s:prompt_win_bufnr = res[1] - redraw - if has('nvim') - call coc#float#nvim_scrollbar(res[0]) - execute 'sign unplace 6 buffer='.s:prompt_win_bufnr - execute 'sign place 6 line=1 name=CocCurrentLine buffer='.s:prompt_win_bufnr - endif - return res -endfunction - -" Notification always have border -" config including: -" - title: optional title. -" - close: default to 1 -" - borderhighlight: highlight group string -" - timeout: timeout in miniseconds -" - buttons: array of button text for create buttons at bottom. -" - top: default to 1 -" - right: default to 1 -" - maxHeight: default to 10 -" - maxWidth: default to 60 -" - highlight: highlight of window, default to 'CocFloating' -function! coc#float#create_notification(lines, config) abort - let close = get(a:config, 'close', 1) - let timeout = get(a:config, 'timeout', 0) - let borderhighlight = get(a:config, 'borderhighlight', 'CocFloating') - let highlight = get(a:config, 'highlight', 'CocFloating') - let title = get(a:config, 'title', '') - let top = get(a:config, 'top', 1) - let right = get(a:config, 'right', 1) - let buttons = get(a:config, 'buttons', []) - let maxHeight = get(a:config, 'maxHeight', 10) - let maxWidth = min([&columns - right - 10, get(a:config, 'maxWidth', 60)]) - let progress = get(a:config, 'progress', 0) - let minWidth = get(a:config, 'minWidth', 1) - let minWidth = max([minWidth, s:min_btns_width(buttons)]) - if &columns < right + 10 || minWidth > maxWidth - throw 'no enough spaces for notification' - endif - let width = min([maxWidth, max(map(a:lines + [title + ' '], "strdisplaywidth(v:val)"))]) - let width = max([minWidth, width]) - let height = 0 - for line in a:lines - let w = max([1, strdisplaywidth(line)]) - let height += float2nr(ceil(str2float(string(w))/width)) - endfor - let height = min([maxHeight, height, &lines - &cmdheight - 1]) - let col = &columns - right - width - 2 - let opts = { - \ 'row': top, - \ 'col': col, - \ 'lines': a:lines, - \ 'relative': 'editor', - \ 'width': width, - \ 'height': height, - \ 'highlight': highlight, - \ 'borderhighlight': [borderhighlight], - \ 'border': [1, 1, 1, 1], - \ 'title': title, - \ 'close': close, - \ 'buttons': buttons, - \ } - call coc#float#reflow(top + height + 2 + (empty(buttons) ? 0 : 2)) - let res = coc#float#create_float_win(0, 0, opts) - if empty(res) - return - endif - let [winid, bufnr] = res - call setwinvar(winid, 'kind', 'notification') - redraw - if has('nvim') - call coc#float#nvim_scrollbar(winid) - endif - if timeout - call timer_start(timeout, { -> coc#float#close(winid)}) - endif - if progress - let start = reltime() - let timer = timer_start(16, { -> s:update_progress(bufnr, width, reltimefloat(reltime(start)))}, { - \ 'repeat': -1 - \ }) - call setwinvar(winid, 'timer', timer) - endif - return res -endfunction - -" adjust position for notification windows -function! coc#float#reflow(top) abort - let winids = coc#float#get_float_win_list() - let optlist = [] - for winid in winids - if getwinvar(winid, 'kind', '') !=# 'notification' - continue - endif - call add(optlist, s:get_win_opts(winid)) - endfor - call sort(optlist, {a, b -> a['row'] - b['row']}) - "echo optlist - let top = a:top - for opts in optlist - if opts['row'] <= top - let changed = top + 1 - opts['row'] - let opts['row'] = top + 1 - call s:adjust_win_row(opts['winid'], changed) - endif - " adjust top - let top = opts['row'] + opts['height'] - endfor -endfunction - -" float/popup relative to current cursor position -function! coc#float#cursor_relative(winid) abort - if !coc#float#valid(a:winid) - return v:null - endif - let winid = win_getid() - if winid == a:winid - return v:null - endif - let [cursorLine, cursorCol] = coc#cursor#screen_pos() - if has('nvim') - let [row, col] = nvim_win_get_position(a:winid) - return {'row' : row - cursorLine, 'col' : col - cursorCol} - endif - let pos = popup_getpos(a:winid) - return {'row' : pos['line'] - cursorLine - 1, 'col' : pos['col'] - cursorCol - 1} -endfunction - " Change border window & close window when scrollbar is shown. function! coc#float#nvim_scroll_adjust(winid) abort let winid = coc#float#get_related(a:winid, 'border') @@ -1465,7 +966,7 @@ function! coc#float#nvim_scroll_adjust(winid) abort endif let bufnr = winbufnr(winid) let lines = nvim_buf_get_lines(bufnr, 0, -1, 0) - if len(lines) > 2 && coc#helper#last_character(lines[1]) ==# s:borderchars[1] + if len(lines) >= 2 let cw = nvim_win_get_width(a:winid) let width = nvim_win_get_width(winid) if width - cw != 1 + (strcharpart(lines[1], 0, 1) ==# s:borderchars[3] ? 1 : 0) @@ -1475,93 +976,100 @@ function! coc#float#nvim_scroll_adjust(winid) abort let lastline = len(lines) - 1 for i in range(0, lastline) let line = lines[i] - if i == 0 && strcharpart(lines[0], 0, 1) ==# s:borderchars[4] + if i == 0 let add = s:borderchars[0] - elseif i == lastline && strcharpart(lines[i], 0, 1) ==# s:borderchars[7] + elseif i == lastline let add = s:borderchars[2] else let add = ' ' endif let prev = strcharpart(line, 0, strchars(line) - 1) - let lines[i] = prev . add . coc#helper#last_character(line) + let lines[i] = prev . add . coc#string#last_character(line) endfor call nvim_buf_set_lines(bufnr, 0, -1, 0, lines) - let id = coc#float#get_related(a:winid, 'close') - if id - let [row, col] = nvim_win_get_position(id) - call nvim_win_set_config(id, { - \ 'relative': 'editor', - \ 'row': row, - \ 'col': col + 1, - \ }) + " Move right close button + if coc#window#get_var(a:winid, 'right', 0) == 0 + let id = coc#float#get_related(a:winid, 'close') + if id + let [row, col] = nvim_win_get_position(id) + call nvim_win_set_config(id, { + \ 'relative': 'editor', + \ 'row': row, + \ 'col': col + 1, + \ }) + endif + elseif has('nvim-0.6.0') + " Move winid and all related left by 1 + let winids = [a:winid] + coc#window#get_var(a:winid, 'related', []) + for winid in winids + if nvim_win_is_valid(winid) + if coc#window#get_var(winid, 'kind', '') != 'close' + let config = nvim_win_get_config(winid) + let [row, column] = [config.row, config.col] + call nvim_win_set_config(winid, { + \ 'row': row, + \ 'col': column - 1, + \ 'relative': 'editor', + \ }) + endif + endif + endfor endif endif endfunction -" move winid include relative windows. -function! s:adjust_win_row(winid, changed) abort - let ids = getwinvar(a:winid, 'related', []) - if s:is_vim - let pos = popup_getpos(a:winid) - if pos['line'] - 1 + a:changed + pos['height'] > &lines - &cmdheight - call coc#float#close(a:winid) - return - endif - call popup_move(a:winid, { - \ 'line': pos['line'] + a:changed - \ }) - for winid in ids - let winpos = popup_getpos(winid) - call popup_move(winid, { - \ 'line': winpos['line'] + a:changed - \ }) - endfor - else - let ids = [a:winid] + ids - " close it if it's fully shown - let borderwin = coc#float#get_related(a:winid, 'border') - let winid = borderwin == 0 ? a:winid : borderwin - let height = nvim_win_get_height(winid) - let pos = nvim_win_get_position(winid) - if pos[0] + a:changed + height > &lines - &cmdheight - call coc#float#close(a:winid) - return - endif - for winid in ids - let [row, col] = nvim_win_get_position(winid) - call nvim_win_set_config(winid, { - \ 'relative': 'editor', - \ 'row': row + a:changed, - \ 'col': col, - \ }) - endfor +function! coc#float#nvim_set_winblend(winid, winblend) abort + if a:winblend is v:null + return endif + call coc#window#set_var(a:winid, '&winblend', a:winblend) + for winid in coc#window#get_var(a:winid, 'related', []) + call coc#window#set_var(winid, '&winblend', a:winblend) + endfor endfunction -" winid, width, height, row, col (0 based). -" works on vim & neovim, check relative window -function! s:get_win_opts(winid) abort - if s:is_vim - let pos = popup_getpos(a:winid) - return { - \ 'winid': a:winid, - \ 'row': pos['line'] - 1, - \ 'col': pos['col'] - 1, - \ 'width': pos['width'], - \ 'height': pos['height'], - \ } +function! s:popup_visible(id) abort + let pos = popup_getpos(a:id) + if !empty(pos) && get(pos, 'visible', 0) + return 1 + endif + return 0 +endfunction + +function! s:convert_config_nvim(config, create) abort + let valids = ['relative', 'win', 'anchor', 'width', 'height', 'bufpos', 'col', 'row', 'focusable'] + let result = coc#dict#pick(a:config, valids) + let border = get(a:config, 'border', []) + if !s:empty_border(border) + if result['relative'] ==# 'cursor' && result['row'] < 0 + " move top when has bottom border + if get(border, 2, 0) + let result['row'] = result['row'] - 1 + endif + else + " move down when has top border + if get(border, 0, 0) && !get(a:config, 'prompt', 0) + let result['row'] = result['row'] + 1 + endif + endif + " move right when has left border + if get(border, 3, 0) + let result['col'] = result['col'] + 1 + endif + let result['width'] = float2nr(result['width'] + 1 - get(border,3, 0)) else - let borderwin = coc#float#get_related(a:winid, 'border') - let winid = borderwin == 0 ? a:winid : borderwin - let [row, col] = nvim_win_get_position(winid) - return { - \ 'winid': a:winid, - \ 'row': row, - \ 'col': col, - \ 'width': nvim_win_get_width(winid), - \ 'height': nvim_win_get_height(winid) - \ } + let result['width'] = float2nr(result['width'] + (get(a:config, 'nopad', 0) ? 0 : 1)) + endif + if has('nvim-0.5.0') && get(a:config, 'shadow', 0) && a:create + if empty(get(a:config, 'buttons', v:null)) && empty(get(border, 2, 0)) + let result['border'] = 'shadow' + endif + endif + if has('nvim-0.5.1') + let result['zindex'] = get(a:config, 'zindex', 50) endif + let result['height'] = float2nr(result['height']) + return result endfunction function! s:create_btns_buffer(bufnr, width, buttons, borderbottom) abort @@ -1612,7 +1120,7 @@ function! s:gen_filter_keys(line) abort if next if (nr >= 65 && nr <= 90) || (nr >= 97 && nr <= 122) let lc = tolower(ch) - if index(used, lc) < 0 && empty(maparg(lc, 'n')) + if index(used, lc) < 0 && (!s:is_vim || empty(maparg(lc, 'n'))) let col = len(strcharpart(a:line, 0, idx)) + 1 call add(used, lc) call add(cols, col) @@ -1628,7 +1136,7 @@ function! s:gen_filter_keys(line) abort return [cols, used] endfunction -function! s:close_win(winid) abort +function! s:close_win(winid, noautocmd) abort if a:winid <= 0 return endif @@ -1637,30 +1145,18 @@ function! s:close_win(winid) abort call popup_close(a:winid) else if nvim_win_is_valid(a:winid) - call nvim_win_close(a:winid, 1) + let prefix = a:noautocmd ? 'noa ': '' + exe prefix.'call nvim_win_close('.a:winid.', 1)' endif endif endfunction function! s:nvim_create_keymap(winid) abort - if a:winid == 0 - return - endif - if exists('*nvim_buf_set_keymap') - let bufnr = winbufnr(a:winid) - call nvim_buf_set_keymap(bufnr, 'n', '', ':call coc#float#nvim_float_click()', { + let bufnr = winbufnr(a:winid) + call nvim_buf_set_keymap(bufnr, 'n', '', ':call coc#float#nvim_float_click()', { \ 'silent': v:true, \ 'nowait': v:true \ }) - else - let curr = win_getid() - let m = mode() - if m == 'n' || m == 'i' || m == 'ic' - noa call win_gotoid(a:winid) - nnoremap :call coc#float#nvim_float_click() - noa call win_gotoid(curr) - endif - endif endfunction " getwininfo is buggy on neovim, use topline, width & height should for content @@ -1669,7 +1165,7 @@ function! s:nvim_get_botline(topline, height, width, bufnr) abort let botline = a:topline let count = 0 for i in range(0, len(lines) - 1) - let w = coc#helper#max(1, strdisplaywidth(lines[i])) + let w = max([1, strdisplaywidth(lines[i])]) let lh = float2nr(ceil(str2float(string(w))/a:width)) let count = count + lh let botline = a:topline + i @@ -1683,19 +1179,40 @@ endfunction " get popup position for vim8 based on config of neovim float window function! s:popup_position(config) abort let relative = get(a:config, 'relative', 'editor') + let border = get(a:config, 'border', [0, 0, 0, 0]) + let delta = get(border, 0, 0) + get(border, 2, 0) if relative ==# 'cursor' - return [s:popup_cursor(a:config['row']), s:popup_cursor(a:config['col'])] + if a:config['row'] < 0 + let delta = - delta + elseif a:config['row'] == 0 + let delta = - get(border, 0, 0) + else + let delta = 0 + endif + return [s:popup_cursor(a:config['row'] + delta), s:popup_cursor(a:config['col'])] endif return [a:config['row'] + 1, a:config['col'] + 1] endfunction -function! s:add_related(winid, target) abort - let arr = getwinvar(a:target, 'related', []) +function! coc#float#add_related(winid, target) abort + let arr = coc#window#get_var(a:target, 'related', []) if index(arr, a:winid) >= 0 return endif call add(arr, a:winid) - call setwinvar(a:target, 'related', arr) + call coc#window#set_var(a:target, 'related', arr) +endfunction + +function! coc#float#get_wininfo(winid) abort + if !coc#float#valid(a:winid) + throw 'Not valid float window: '.a:winid + endif + if s:is_vim + let pos = popup_getpos(a:winid) + return {'topline': pos['firstline'], 'botline': pos['lastline']} + endif + let info = getwininfo(a:winid)[0] + return {'topline': info['topline'], 'botline': info['botline']} endfunction function! s:popup_cursor(n) abort @@ -1708,13 +1225,6 @@ function! s:popup_cursor(n) abort return 'cursor+'.a:n endfunction -function! s:is_blocking() abort - if coc#prompt#activated() - return 1 - endif - return 0 -endfunction - " max firstline of lines, height > 0, width > 0 function! s:max_firstline(lines, height, width) abort let max = len(a:lines) @@ -1784,7 +1294,7 @@ endfunction function! s:get_options(winid) abort if has('nvim') let width = nvim_win_get_width(a:winid) - if getwinvar(a:winid, '&foldcolumn', 0) + if coc#window#get_var(a:winid, '&foldcolumn', 0) let width = width - 1 endif let info = getwininfo(a:winid)[0] @@ -1815,39 +1325,75 @@ function! s:win_setview(winid, topline, lnum) abort endif endfunction -function! s:min_btns_width(buttons) abort - if empty(a:buttons) - return 0 - endif - let minwidth = len(a:buttons)*3 - 1 - for txt in a:buttons - let minwidth = minwidth + strdisplaywidth(txt) - endfor - return minwidth -endfunction - -function! s:update_progress(bufnr, width, ts) abort - let duration = 5000 - " count of blocks - let width = float2nr((a:width + 0.0)/4) - let percent = (float2nr(a:ts*1000)%duration + 0.0)/duration - let line = repeat(s:progresschars[0], a:width) - let startIdx = float2nr(round(a:width * percent)) - let endIdx = startIdx + width - let delta = a:width - endIdx - if delta > 0 - let line = s:str_compose(line, startIdx, repeat(s:progresschars[1], width)) +function! s:set_float_defaults(winid, config) abort + if !s:is_vim + let hlgroup = get(a:config, 'highlight', 'CocFloating') + call setwinvar(a:winid, '&winhl', 'Normal:'.hlgroup.',FoldColumn:'.hlgroup) + call setwinvar(a:winid, 'border', get(a:config, 'border', [])) + call setwinvar(a:winid, 'scrollinside', get(a:config, 'scrollinside', 0)) + call setwinvar(a:winid, '&foldcolumn', s:nvim_get_foldcolumn(a:config)) + call setwinvar(a:winid, '&signcolumn', 'no') + call setwinvar(a:winid, '&cursorcolumn', 0) else - let inserted = repeat(s:progresschars[1], width + delta) - let line = s:str_compose(line, startIdx, inserted) - let line = s:str_compose(line, 0, repeat(s:progresschars[1], - delta)) + call setwinvar(a:winid, '&foldcolumn', 0) + endif + if !s:is_vim || !has("patch-8.2.3100") + call setwinvar(a:winid, '&number', 0) + call setwinvar(a:winid, '&relativenumber', 0) + call setwinvar(a:winid, '&cursorline', 0) + endif + call setwinvar(a:winid, '&foldenable', 0) + call setwinvar(a:winid, '&colorcolumn', '') + call setwinvar(a:winid, '&spell', 0) + call setwinvar(a:winid, '&linebreak', 1) + call setwinvar(a:winid, '&conceallevel', 0) + call setwinvar(a:winid, '&list', 0) + call setwinvar(a:winid, '&wrap', !get(a:config, 'cursorline', 0)) + if s:is_vim || has('nvim-0.5.0') + call setwinvar(a:winid, '&scrolloff', 0) + endif + if has('nvim-0.6.0') || has("patch-8.1.2281") + call setwinvar(a:winid, '&showbreak', 'NONE') endif - call setbufline(a:bufnr, 1, line) + if exists('*win_execute') + call win_execute(a:winid, 'setl fillchars+=eob:\ ') + endif + if get(a:config, 'autohide', 0) + call setwinvar(a:winid, 'autohide', 1) + endif + call setwinvar(a:winid, 'float', 1) endfunction -function! s:str_compose(line, idx, text) abort - let first = strcharpart(a:line, 0, a:idx) - return first.a:text.strcharpart(a:line, a:idx + strwidth(a:text)) +function! s:nvim_add_related(winid, target, kind, winhl, related) abort + if a:winid <= 0 + return + endif + " minimal not work + if !has('nvim-0.4.3') + call setwinvar(a:winid, '&colorcolumn', '') + call setwinvar(a:winid, '&number', 0) + call setwinvar(a:winid, '&relativenumber', 0) + call setwinvar(a:winid, '&foldcolumn', 0) + call setwinvar(a:winid, '&signcolumn', 0) + call setwinvar(a:winid, '&list', 0) + endif + let winhl = empty(a:winhl) ? coc#window#get_var(a:target, '&winhl', '') : a:winhl + call setwinvar(a:winid, '&winhl', winhl) + call setwinvar(a:winid, 'target_winid', a:target) + call setwinvar(a:winid, 'kind', a:kind) + call add(a:related, a:winid) +endfunction + +function! s:nvim_get_foldcolumn(config) abort + let nopad = get(a:config, 'nopad', 0) + if nopad + return 0 + endif + let border = get(a:config, 'border', v:null) + if border is 1 || (type(border) == v:t_list && get(border, 3, 0) == 1) + return 0 + endif + return 1 endfunction function! s:add_highlights(winid, config, create) abort @@ -1865,3 +1411,42 @@ function! s:add_highlights(winid, config, create) abort endfor call coc#highlight#add_highlights(a:winid, codes, highlights) endfunction + +function! s:empty_border(border) abort + if empty(a:border) || empty(filter(copy(a:border), 'v:val != 0')) + return 1 + endif + return 0 +endfunction + +function! s:get_borderchars(config) abort + let borderchars = get(a:config, 'borderchars', []) + if !empty(borderchars) + return borderchars + endif + return get(a:config, 'rounded', 0) ? s:rounded_borderchars : s:borderchars +endfunction + +function! s:scroll_win(winid, forward, amount) abort + if s:is_vim + call coc#float#scroll_win(a:winid, a:forward, a:amount) + else + call timer_start(0, { -> coc#float#scroll_win(a:winid, a:forward, a:amount)}) + endif +endfunction + +function! s:get_borderhighlight(config) abort + let hlgroup = get(a:config, 'highlight', 'CocFloating') + let borderhighlight = get(a:config, 'borderhighlight', v:null) + if empty(borderhighlight) + return hlgroup + endif + let highlight = type(borderhighlight) == 3 ? borderhighlight[0] : borderhighlight + return coc#highlight#compose_hlgroup(highlight, hlgroup) +endfunction + +function! s:has_shadow(config) abort + let border = get(a:config, 'border', []) + let filtered = filter(copy(border), 'type(v:val) == 3 && get(v:val, 1, "") ==# "FloatShadow"') + return len(filtered) > 0 +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/highlight.vim b/vim-config/plugins/coc.nvim/autoload/coc/highlight.vim index 21ed5d72..f506b3b0 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/highlight.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/highlight.vim @@ -1,134 +1,124 @@ scriptencoding utf-8 let s:is_vim = !has('nvim') -let s:clear_match_by_window = has('nvim-0.5.0') || has('patch-8.1.1084') -let s:prop_offset = get(g:, 'coc_text_prop_offset', 1000) +let s:nvim_50 = has('nvim-0.5.0') +let s:nvim_60 = has('nvim-0.6.0') +let s:clear_match_by_window = s:nvim_60 || s:is_vim +let s:set_extmark = has('nvim') && exists('*nvim_buf_set_extmark') let s:namespace_map = {} let s:ns_id = 1 +let s:diagnostic_hlgroups = ['CocErrorHighlight', 'CocWarningHighlight', 'CocInfoHighlight', 'CocHintHighlight', 'CocDeprecatedHighlight', 'CocUnusedHighlight'] +" Maximum count to highlight each time. +let g:coc_highlight_maximum_count = get(g:, 'coc_highlight_maximum_count', 100) +let s:term = &termguicolors == 0 && !has('gui_running') -if has('nvim-0.5.0') +if has('nvim-0.5.0') && s:clear_match_by_window == 0 try call getmatches(0) + let s:clear_match_by_window = 1 catch /^Vim\%((\a\+)\)\=:E118/ - let s:clear_match_by_window = 0 + " ignored endtry endif -" Get namespaced coc highlights from range of bufnr -" start - 0 based start line index -" end - 0 based end line index, could be -1 for last line (exclusive) -function! coc#highlight#get(bufnr, key, start, end) abort - if !has('nvim-0.5.0') && !exists('*prop_list') - throw 'Get highlights requires neovim 0.5.0 or vim support prop_list()' +" Update buffer region by region. +function! coc#highlight#buffer_update(bufnr, key, highlights, ...) abort + if !bufloaded(a:bufnr) + return endif - if !has_key(s:namespace_map, a:key) || !bufloaded(a:bufnr) - return {} + if empty(a:highlights) + call coc#highlight#clear_highlight(a:bufnr, a:key, 0, -1) + return endif - let ns = coc#highlight#create_namespace(a:key) - let current = {} - if has('nvim-0.5.0') - let end = a:end == -1 ? [-1, -1] : [a:end - 1, 0] - let markers = nvim_buf_get_extmarks(a:bufnr, ns, [a:start, 0], end, {'details': v:true}) - for [_, row, start_col, details] in markers - let delta = details['end_row'] - row - if delta > 1 || (delta == 1 && details['end_col'] != 0) - " Don't known neovim's api for multiple lines markers. - continue - endif - let lines = getbufline(a:bufnr, row + 1) - if empty(lines) - " It's possible that markers exceeded last line. - continue - endif - let text = lines[0] - let curr = get(current, string(row), []) - call add(curr, { - \ 'hlGroup': details['hl_group'], - \ 'lnum': row, - \ 'colStart': start_col, - \ 'colEnd': delta == 1 ? strlen(text) : details['end_col'] - \ }) - let current[string(row)] = curr - endfor - else - let id = s:prop_offset + ns - " we could only get textprops line by line - let end = a:end == -1 ? getbufinfo(a:bufnr)[0]['linecount'] : a:end - for line in range(a:start + 1, end) - let items = [] - for prop in prop_list(line, {'bufnr': a:bufnr, 'id': id}) - " vim have support for cross line text props, but we're not using - call add(items, { - \ 'hlGroup': s:prop_type_hlgroup(prop['type']), - \ 'lnum': line - 1, - \ 'colStart': prop['col'] - 1, - \ 'colEnd': prop['col'] - 1 + prop['length'] - (prop['end'] == 0 ? 1 : 0), - \ }) - endfor - if !empty(items) - let current[string(line - 1)] = items - endif - endfor + let priority = get(a:, 1, v:null) + let changedtick = getbufvar(a:bufnr, 'changedtick', 0) + if type(get(a:, 2, v:null)) == 0 && changedtick > a:2 + return endif - return current + let hls = map(copy(a:highlights), "{'hlGroup':v:val[0],'lnum':v:val[1],'colStart':v:val[2],'colEnd':v:val[3],'combine':get(v:val,4,1),'start_incl':get(v:val,5,0),'end_incl':get(v:val,6,0)}") + if len(hls) <= g:coc_highlight_maximum_count + call coc#highlight#update_highlights(a:bufnr, a:key, hls, 0, -1, priority) + return + endif + let linecount = coc#compat#buf_line_count(a:bufnr) + let groups = s:group_hls(hls, linecount) + call s:update_highlights_timer(a:bufnr, changedtick, a:key, priority, groups, 0) endfunction " Update highlights by check exists highlights. +" 0 based, end exclusive start and end function! coc#highlight#update_highlights(bufnr, key, highlights, ...) abort - let bufnr = a:bufnr - if a:bufnr == 0 - let bufnr = bufnr('%') - endif + let bufnr = a:bufnr == 0 ? bufnr('%') : a:bufnr if !bufloaded(bufnr) return endif let start = get(a:, 1, 0) let end = get(a:, 2, -1) + if end == 0 + return + endif + let linecount = coc#compat#buf_line_count(a:bufnr) + if end >= linecount + let end = -1 + endif if empty(a:highlights) call coc#highlight#clear_highlight(bufnr, a:key, start, end) return endif + let priority = get(a:, 3, v:null) let total = len(a:highlights) " index list that exists with current highlights let exists = [] let ns = coc#highlight#create_namespace(a:key) - let currIndex = 0 if has('nvim-0.5.0') || exists('*prop_list') - let current = coc#highlight#get(bufnr, a:key, start, end) - for lnum in sort(map(keys(current), 'str2nr(v:val)'), {a, b -> a - b}) - let items = current[lnum] - let indexes = [] - let nextIndex = currIndex - if currIndex != total - for item in items - for i in range(currIndex, total - 1) - let hi = a:highlights[i] - if hi['lnum'] > item['lnum'] - let nextIndex = i - break - endif - if coc#helper#obj_equal(item, hi) - call add(indexes, i) - let nextIndex = max([nextIndex, i + 1]) + let endLnum = end < 0 ? linecount - 1 : end - 1 + let firstLnum = a:highlights[0]['lnum'] + if firstLnum > start + call coc#highlight#clear_highlight(bufnr, a:key, start, firstLnum) + let start = firstLnum + endif + let lastLnum = a:highlights[total - 1]['lnum'] + if lastLnum < endLnum + call coc#highlight#clear_highlight(bufnr, a:key, lastLnum + 1, endLnum + 1) + let endLnum = lastLnum + endif + let current = coc#highlight#get_highlights(bufnr, a:key, start, endLnum) + let currIndex = 0 + if !empty(current) + for [lnum, items] in s:to_group(current) + let indexes = [] + let currIndexes = range(0, len(items) - 1) + let removeIndexes = [] + while currIndex != total + let hi = a:highlights[currIndex] + if hi['lnum'] == lnum + let findIndex = -1 + for idx in currIndexes + let item = items[idx] + if hi['hlGroup'] ==# item[0] && hi['colStart'] == item[2] && hi['colEnd'] == item[3] + call add(indexes, currIndex) + let findIndex = idx + break + elseif item[2] > hi['colStart'] + break + endif + endfor + if findIndex != -1 + call filter(currIndexes, 'v:val != '.findIndex) endif - endfor + elseif hi['lnum'] > lnum + break + endif + let currIndex = currIndex + 1 + endwhile + for idx in currIndexes + if s:is_vim + call prop_remove({'bufnr': bufnr, 'id': items[idx][4]}) + else + call nvim_buf_del_extmark(bufnr, ns, items[idx][4]) + endif endfor - endif - let currIndex = nextIndex - " all highlights of current line exists, not clear. - if len(indexes) == len(items) - let exists = exists + indexes - else - if has('nvim') - call nvim_buf_clear_namespace(bufnr, ns, lnum, lnum + 1) - else - call coc#api#call('buf_clear_namespace', [bufnr, ns, lnum, lnum + 1]) - endif - endif - endfor - if has('nvim') && end == -1 - let count = nvim_buf_line_count(bufnr) - " remove highlights exceed last line. - call nvim_buf_clear_namespace(bufnr, ns, count, -1) + call extend(exists, indexes) + endfor endif else call coc#highlight#clear_highlight(bufnr, a:key, start, end) @@ -137,70 +127,148 @@ function! coc#highlight#update_highlights(bufnr, key, highlights, ...) abort if !empty(exists) let indexes = filter(indexes, 'index(exists, v:val) == -1') endif - for i in indexes - let hi = a:highlights[i] - call coc#highlight#add_highlight(bufnr, ns, hi['hlGroup'], hi['lnum'], hi['colStart'], hi['colEnd']) + for idx in indexes + let hi = a:highlights[idx] + let opts = { + \ 'combine': get(hi, 'combine', 0), + \ 'start_incl': get(hi, 'start_incl', 0), + \ 'end_incl': get(hi, 'end_incl', 0), + \ } + if type(priority) == 0 + let opts['priority'] = s:get_priority(a:key, hi['hlGroup'], priority) + endif + call coc#highlight#add_highlight(bufnr, ns, hi['hlGroup'], hi['lnum'], hi['colStart'], hi['colEnd'], opts) endfor endfunction -function! coc#highlight#get_highlights(bufnr, key) abort - if !has_key(s:namespace_map, a:key) || !bufloaded(a:bufnr) +" Get list of highlights by range or all buffer. +" 0 based line, start_col and end_col +" 0 based start & end line, end inclusive. +function! coc#highlight#get_highlights(bufnr, key, ...) abort + if !bufloaded(a:bufnr) + return v:null + endif + if !has_key(s:namespace_map, a:key) return [] endif + let start = get(a:, 1, 0) + let end = get(a:, 2, -1) + if s:nvim_60 + return v:lua.require('coc.highlight').getHighlights(a:bufnr, a:key, start, end) + elseif s:nvim_50 + return luaeval( + \ 'require("coc.highlight").getHighlights(_A[1],_A[2],_A[3],_A[4])', + \ [a:bufnr, a:key, start, end] + \ ) + endif let res = [] let ns = s:namespace_map[a:key] if exists('*prop_list') - let lines = getbufline(a:bufnr, 1, '$') - let linecount = len(lines) - for line in range(1, linecount) - for prop in prop_list(line, {'bufnr': a:bufnr, 'id': s:prop_offset + ns}) + let types = coc#api#get_types(ns) + if empty(types) + return res + endif + " Could filter by end_lnum and types + if has('patch-8.2.3652') + let endLnum = end == -1 ? -1 : end + 1 + for prop in prop_list(start + 1, {'bufnr': a:bufnr, 'types': types, 'end_lnum': endLnum}) if prop['start'] == 0 || prop['end'] == 0 - " multi line tokens are not supported; simply ignore it + " multi line textprop are not supported, simply ignore it continue endif - let text = lines[line - 1] - call add(res, { - \ 'hlGroup': s:prop_type_hlgroup(prop['type']), - \ 'lnum': line - 1, - \ 'colStart': coc#helper#get_charactor(text, prop['col']), - \ 'colEnd': coc#helper#get_charactor(text, prop['col'] + prop['length']) - \ }) + let startCol = prop['col'] - 1 + let endCol = startCol + prop['length'] + call add(res, [s:prop_type_hlgroup(prop['type']), prop['lnum'] - 1, startCol, endCol, prop['id']]) endfor - endfor - elseif has('nvim-0.5.0') - let markers = nvim_buf_get_extmarks(a:bufnr, ns, 0, -1, {'details': v:true}) - let lines = getbufline(a:bufnr, 1, '$') - let total = len(lines) - for [_, line, start_col, details] in markers - if line >= total - " Could be markers exceed end of line - continue - endif - let text = lines[line] - let delta = details['end_row'] - line - if delta > 1 || (delta == 1 && details['end_col'] != 0) - " can't handle, single line only - continue + else + if end == -1 + let end = coc#compat#buf_line_count(a:bufnr) + else + let end = end + 1 endif - call add(res, { - \ 'hlGroup': details['hl_group'], - \ 'lnum': line, - \ 'colStart': coc#helper#get_charactor(text, start_col + 1), - \ 'colEnd': delta == 1 ? strchars(text) : coc#helper#get_charactor(text, details['end_col'] + 1) - \ }) - endfor + for line in range(start + 1, end) + for prop in prop_list(line, {'bufnr': a:bufnr}) + if index(types, prop['type']) == -1 || prop['start'] == 0 || prop['end'] == 0 + " multi line textprop are not supported, simply ignore it + continue + endif + let startCol = prop['col'] - 1 + let endCol = startCol + prop['length'] + call add(res, [s:prop_type_hlgroup(prop['type']), line - 1, startCol, endCol, prop['id']]) + endfor + endfor + endif else throw 'Get highlights requires neovim 0.5.0 or vim support prop_list' endif return res endfunction -" highlight LSP range, -function! coc#highlight#ranges(bufnr, key, hlGroup, ranges) abort +" Add multiple highlights to buffer. +" type HighlightItem = [hlGroup, lnum, colStart, colEnd, combine?, start_incl?, end_incl?] +function! coc#highlight#set(bufnr, key, highlights, priority) abort + if !bufloaded(a:bufnr) + return + endif + let ns = coc#highlight#create_namespace(a:key) + let g:c = 1 + if s:nvim_60 + call v:lua.require('coc.highlight').set(a:bufnr, ns, a:highlights, a:priority) + elseif s:nvim_50 + call luaeval( + \ 'require("coc.highlight").set(_A[1],_A[2],_A[3],_A[4])', + \ [a:bufnr, ns, a:highlights, a:priority] + \ ) + else + if len(a:highlights) > g:coc_highlight_maximum_count + call s:add_highlights_timer(a:bufnr, ns, a:highlights, a:priority) + else + call s:add_highlights(a:bufnr, ns, a:highlights, a:priority) + endif + endif +endfunction + +" Clear highlights by 0 based line numbers. +function! coc#highlight#clear(bufnr, key, lnums) abort + if !bufloaded(a:bufnr) || empty(a:lnums) + return + endif + let ns = coc#highlight#create_namespace(a:key) + for lnum in a:lnums + if has('nvim') + call nvim_buf_clear_namespace(a:bufnr, ns, lnum, lnum + 1) + else + call coc#api#exec('buf_clear_namespace', [a:bufnr, ns, lnum, lnum + 1]) + endif + endfor + " clear highlights in invalid line. + if has('nvim') + let linecount = nvim_buf_line_count(a:bufnr) + call nvim_buf_clear_namespace(a:bufnr, ns, linecount, -1) + endif +endfunction + +function! coc#highlight#del_markers(bufnr, key, ids) abort + if !bufloaded(a:bufnr) + return + endif + let ns = coc#highlight#create_namespace(a:key) + for id in a:ids + if s:is_vim + call prop_remove({'bufnr': a:bufnr, 'id': id}) + else + call nvim_buf_del_extmark(a:bufnr, ns, id) + endif + endfor +endfunction + +" highlight LSP range, opts contains 'combine' 'priority' 'start_incl' 'end_incl' +function! coc#highlight#ranges(bufnr, key, hlGroup, ranges, ...) abort let bufnr = a:bufnr == 0 ? bufnr('%') : a:bufnr if !bufloaded(bufnr) || !exists('*getbufline') return endif + let opts = get(a:, 1, {}) let synmaxcol = getbufvar(a:bufnr, '&synmaxcol', 1000) if synmaxcol == 0 let synmaxcol = 1000 @@ -219,22 +287,39 @@ function! coc#highlight#ranges(bufnr, key, hlGroup, ranges) abort if start['character'] > synmaxcol || end['character'] > synmaxcol continue endif - " TODO don't know how to count UTF16 code point, should work most cases. - let colStart = lnum == start['line'] + 1 ? strlen(strcharpart(line, 0, start['character'])) : 0 - let colEnd = lnum == end['line'] + 1 ? strlen(strcharpart(line, 0, end['character'])) : -1 + let colStart = lnum == start['line'] + 1 ? coc#string#byte_index(line, start['character']) : 0 + let colEnd = lnum == end['line'] + 1 ? coc#string#byte_index(line, end['character']) : strlen(line) if colStart == colEnd continue endif - call coc#highlight#add_highlight(bufnr, srcId, a:hlGroup, lnum - 1, colStart, colEnd) + call coc#highlight#add_highlight(bufnr, srcId, a:hlGroup, lnum - 1, colStart, colEnd, opts) endfor endfor endfunction -function! coc#highlight#add_highlight(bufnr, src_id, hl_group, line, col_start, col_end) abort - if has('nvim') - call nvim_buf_add_highlight(a:bufnr, a:src_id, a:hl_group, a:line, a:col_start, a:col_end) +function! coc#highlight#add_highlight(bufnr, src_id, hl_group, line, col_start, col_end, ...) abort + let opts = get(a:, 1, {}) + let priority = get(opts, 'priority', v:null) + if !s:is_vim + if s:set_extmark && a:src_id != -1 + " get(opts, 'start_incl', 0) ? v:true : v:false, + try + call nvim_buf_set_extmark(a:bufnr, a:src_id, a:line, a:col_start, { + \ 'end_col': a:col_end, + \ 'hl_group': a:hl_group, + \ 'hl_mode': get(opts, 'combine', 1) ? 'combine' : 'replace', + \ 'right_gravity': v:true, + \ 'end_right_gravity': v:false, + \ 'priority': type(priority) == 0 ? min([priority, 4096]) : 4096, + \ }) + catch /^Vim\%((\a\+)\)\=:E5555/ + " the end_col could be invalid, ignore this error + endtry + else + call nvim_buf_add_highlight(a:bufnr, a:src_id, a:hl_group, a:line, a:col_start, a:col_end) + endif else - call coc#api#call('buf_add_highlight', [a:bufnr, a:src_id, a:hl_group, a:line, a:col_start, a:col_end]) + call coc#api#exec('buf_add_highlight', [a:bufnr, a:src_id, a:hl_group, a:line, a:col_start, a:col_end, opts]) endif endfunction @@ -247,7 +332,7 @@ function! coc#highlight#clear_highlight(bufnr, key, start_line, end_line) abort if has('nvim') call nvim_buf_clear_namespace(a:bufnr, src_id, a:start_line, a:end_line) else - call coc#api#call('buf_clear_namespace', [a:bufnr, src_id, a:start_line, a:end_line]) + call coc#api#exec('buf_clear_namespace', [a:bufnr, src_id, a:start_line, a:end_line]) endif endfunction @@ -265,6 +350,9 @@ endfunction " endLine: number " } function! coc#highlight#add_highlights(winid, codes, highlights) abort + if get(g:, 'coc_node_env', '') ==# 'test' + call setwinvar(a:winid, 'highlights', a:highlights) + endif " clear highlights call coc#compat#execute(a:winid, 'syntax clear') let bufnr = winbufnr(a:winid) @@ -274,7 +362,9 @@ function! coc#highlight#add_highlights(winid, codes, highlights) abort endif if !empty(a:highlights) for item in a:highlights - call coc#highlight#add_highlight(bufnr, -1, item['hlGroup'], item['lnum'], item['colStart'], item['colEnd']) + let hlGroup = item['hlGroup'] + let opts = hlGroup =~# 'Search$' ? {'priority': 999, 'combine': 1} : {} + call coc#highlight#add_highlight(bufnr, -1, hlGroup, item['lnum'], item['colStart'], item['colEnd']) endfor endif endfunction @@ -320,17 +410,9 @@ function! coc#highlight#highlight_lines(winid, blocks) abort endif endfunction -" Copmpose hlGroups with foreground and background colors. -function! coc#highlight#compose_hlgroup(fgGroup, bgGroup) abort - let hlGroup = 'Fg'.a:fgGroup.'Bg'.a:bgGroup - if a:fgGroup ==# a:bgGroup - return a:fgGroup - endif - if hlexists(hlGroup) - return hlGroup - endif - let fgId = synIDtrans(hlID(a:fgGroup)) - let bgId = synIDtrans(hlID(a:bgGroup)) +function! coc#highlight#compose(fg, bg) abort + let fgId = synIDtrans(hlID(a:fg)) + let bgId = synIDtrans(hlID(a:bg)) let isGuiReversed = synIDattr(fgId, 'reverse', 'gui') !=# '1' || synIDattr(bgId, 'reverse', 'gui') !=# '1' let guifg = isGuiReversed ? synIDattr(fgId, 'fg', 'gui') : synIDattr(fgId, 'bg', 'gui') let guibg = isGuiReversed ? synIDattr(bgId, 'bg', 'gui') : synIDattr(bgId, 'fg', 'gui') @@ -340,7 +422,7 @@ function! coc#highlight#compose_hlgroup(fgGroup, bgGroup) abort let bold = synIDattr(fgId, 'bold') ==# '1' let italic = synIDattr(fgId, 'italic') ==# '1' let underline = synIDattr(fgId, 'underline') ==# '1' - let cmd = 'silent hi ' . hlGroup + let cmd = '' if !empty(guifg) let cmd .= ' guifg=' . guifg endif @@ -364,10 +446,110 @@ function! coc#highlight#compose_hlgroup(fgGroup, bgGroup) abort elseif underline let cmd .= ' cterm=underline gui=underline' endif - execute cmd + return cmd +endfunction + +function! coc#highlight#valid(hlGroup) abort + return hlexists(a:hlGroup) && execute('hi '.a:hlGroup, 'silent!') !~# ' cleared$' +endfunction + +" Compose hlGroups with foreground and background colors. +function! coc#highlight#compose_hlgroup(fgGroup, bgGroup) abort + let hlGroup = 'Fg'.a:fgGroup.'Bg'.a:bgGroup + if a:fgGroup ==# a:bgGroup + return a:fgGroup + endif + if coc#highlight#valid(hlGroup) + return hlGroup + endif + let cmd = coc#highlight#compose(a:fgGroup, a:bgGroup) + if empty(cmd) + return 'Normal' + endif + execute 'silent hi ' . hlGroup . cmd return hlGroup endfunction +" hlGroup id, key => 'fg' | 'bg', kind => 'cterm' | 'gui' +function! coc#highlight#get_color(id, key, kind) abort + if synIDattr(a:id, 'reverse', a:kind) !=# '1' + return synIDattr(a:id, a:key, a:kind) + endif + return synIDattr(a:id, a:key ==# 'bg' ? 'fg' : 'bg', a:kind) +endfunction + +function! coc#highlight#get_hl_command(id, key, cterm, gui) abort + let cterm = coc#highlight#get_color(a:id, a:key, 'cterm') + let gui = coc#highlight#get_color(a:id, a:key, 'gui') + let cmd = ' cterm'.a:key.'=' . (empty(cterm) ? a:cterm : cterm) + let cmd .= ' gui'.a:key.'=' . (empty(gui) ? a:gui : gui) + return cmd +endfunction + +function! coc#highlight#reversed(id) abort + let gui = has('gui_running') || &termguicolors == 1 + if synIDattr(synIDtrans(a:id), 'reverse', gui ? 'gui' : 'cterm') == '1' + return 1 + endif + return 0 +endfunction + +function! coc#highlight#get_contrast(group1, group2) abort + let normal = coc#highlight#get_hex_color(synIDtrans(hlID('Normal')), 'bg', '#000000') + let bg1 = coc#highlight#get_hex_color(synIDtrans(hlID(a:group1)), 'bg', normal) + let bg2 = coc#highlight#get_hex_color(synIDtrans(hlID(a:group2)), 'bg', normal) + return coc#color#hex_contrast(bg1, bg2) +endfunction + +" Darken or lighten background +function! coc#highlight#create_bg_command(group, amount) abort + let id = synIDtrans(hlID(a:group)) + let normal = coc#highlight#get_hex_color(synIDtrans(hlID('Normal')), 'bg', &background ==# 'dark' ? '#282828' : '#fefefe') + let bg = coc#highlight#get_hex_color(id, 'bg', normal) + let hex = a:amount > 0 ? coc#color#darken(bg, a:amount) : coc#color#lighten(bg, -a:amount) + + let ctermbg = coc#color#rgb2term(strpart(hex, 1)) + if s:term && !s:check_ctermbg(id, ctermbg) && abs(a:amount) < 20.0 + return coc#highlight#create_bg_command(a:group, a:amount * 2) + endif + return 'ctermbg=' . ctermbg.' guibg=' . hex +endfunction + +function! coc#highlight#get_hex_color(id, kind, fallback) abort + let attr = coc#highlight#get_color(a:id, a:kind, s:term ? 'cterm' : 'gui') + let hex = s:to_hex_color(attr, s:term) + if empty(hex) && !s:term + let attr = coc#highlight#get_color(a:id, a:kind, 'cterm') + let hex = s:to_hex_color(attr, 1) + endif + return empty(hex) ? a:fallback : hex +endfunction + +function! s:check_ctermbg(id, cterm) abort + let attr = coc#highlight#get_color(a:id, 'bg', 'cterm') + if empty(attr) + let attr = coc#highlight#get_color(synIDtrans(hlID('Normal')), 'bg', 'cterm') + endif + if attr ==# a:cterm + return 0 + endif + return 1 +endfunction + +function! s:to_hex_color(color, term) abort + if empty(a:color) + return '' + endif + if a:color =~# '^#\x\+$' + return a:color + endif + if a:term && a:color =~# '^\d\+$' + return coc#color#term2rgb(a:color) + endif + let hex = coc#color#nameToHex(tolower(a:color), a:term) + return empty(hex) ? '' : hex +endfunction + " add matches for winid, use 0 for current window. function! coc#highlight#match_ranges(winid, bufnr, ranges, hlGroup, priority) abort let winid = a:winid == 0 ? win_getid() : a:winid @@ -378,11 +560,7 @@ function! coc#highlight#match_ranges(winid, bufnr, ranges, hlGroup, priority) ab endif if !s:clear_match_by_window let curr = win_getid() - if has('nvim') - noa call nvim_set_current_win(winid) - else - noa call win_gotoid(winid) - endif + noa call win_gotoid(winid) endif let ids = [] for range in a:ranges @@ -395,8 +573,8 @@ function! coc#highlight#match_ranges(winid, bufnr, ranges, hlGroup, priority) ab if empty(line) continue endif - let colStart = lnum == start['line'] + 1 ? strlen(strcharpart(line, 0, start['character'])) + 1 : 1 - let colEnd = lnum == end['line'] + 1 ? strlen(strcharpart(line, 0, end['character'])) + 1 : strlen(line) + 1 + let colStart = lnum == start['line'] + 1 ? coc#string#byte_index(line, start['character']) + 1 : 1 + let colEnd = lnum == end['line'] + 1 ? coc#string#byte_index(line, end['character']) + 1 : strlen(line) + 1 if colStart == colEnd continue endif @@ -422,11 +600,7 @@ function! coc#highlight#match_ranges(winid, bufnr, ranges, hlGroup, priority) ab endif endfor if !s:clear_match_by_window - if has('nvim') - noa call nvim_set_current_win(curr) - else - noa call win_gotoid(curr) - endif + noa call win_gotoid(curr) endif return ids endfunction @@ -497,11 +671,16 @@ function! coc#highlight#clear_matches(winid, ids) endif endfunction -function! s:prop_type_hlgroup(type) abort - if a:type=~# '^CocHighlight' - return a:type[12:] - endif - return prop_type_get(a:type)['highlight'] +function! coc#highlight#clear_all() abort + for src_id in values(s:namespace_map) + for bufnr in map(getbufinfo({'bufloaded': 1}), 'v:val["bufnr"]') + if has('nvim') + call nvim_buf_clear_namespace(bufnr, src_id, 0, -1) + else + call coc#api#exec('buf_clear_namespace', [bufnr, src_id, 0, -1]) + endif + endfor + endfor endfunction function! coc#highlight#create_namespace(key) abort @@ -523,3 +702,110 @@ endfunction function! coc#highlight#get_syntax_name(lnum, col) return synIDattr(synIDtrans(synID(a:lnum,a:col,1)),"name") endfunction + +function! s:prop_type_hlgroup(type) abort + return substitute(a:type, '_\d\+$', '', '') +endfunction + +function! s:update_highlights_timer(bufnr, changedtick, key, priority, groups, idx) abort + if getbufvar(a:bufnr, 'changedtick', 0) != a:changedtick + return + endif + let group = get(a:groups, a:idx, v:null) + if empty(group) + return + endif + if empty(group['highlights']) + call coc#highlight#clear_highlight(a:bufnr, a:key, group['start'], group['end']) + else + call coc#highlight#update_highlights(a:bufnr, a:key, group['highlights'], group['start'], group['end'], a:priority) + endif + if a:idx < len(a:groups) - 1 + call timer_start(50, { -> s:update_highlights_timer(a:bufnr, a:changedtick, a:key, a:priority, a:groups, a:idx + 1)}) + endif +endfunction + +function! s:add_highlights_timer(bufnr, ns, highlights, priority) abort + let hls = [] + let next = [] + for i in range(0, len(a:highlights) - 1) + if i < g:coc_highlight_maximum_count + call add(hls, a:highlights[i]) + else + call add(next, a:highlights[i]) + endif + endfor + call s:add_highlights(a:bufnr, a:ns, hls, a:priority) + if len(next) + call timer_start(30, {->s:add_highlights_timer(a:bufnr, a:ns, next, a:priority)}) + endif +endfunction + +function! s:add_highlights(bufnr, ns, highlights, priority) abort + for item in a:highlights + let opts = { + \ 'priority': a:priority, + \ 'combine': get(item, 4, 1) ? 1 : 0, + \ 'start_incl': get(item, 5, 0) ? 1 : 0, + \ 'end_incl': get(item, 6, 0) ? 1 : 0, + \ } + call coc#highlight#add_highlight(a:bufnr, a:ns, item[0], item[1], item[2], item[3], opts) + endfor +endfunction + +function! s:to_group(items) abort + let res = [] + let before = v:null + for item in a:items + if empty(before) || before[0] != item[1] + let before = [item[1], [item]] + call add(res, before) + else + call add(before[1], item) + endif + endfor + return res +endfunction + +function! s:get_priority(key, hlGroup, priority) abort + if a:hlGroup ==# 'CocListSearch' + return 2048 + endif + if a:hlGroup ==# 'CocSearch' + return 999 + endif + if strpart(a:key, 0, 10) !=# 'diagnostic' + return a:priority + endif + return a:priority - index(s:diagnostic_hlgroups, a:hlGroup) +endfunction + +function! s:group_hls(hls, linecount) abort + " start, end, highlights + let groups = [] + if empty(a:hls) + call add(groups, {'start': 0, 'end': a:linecount, 'highlights': []}) + return groups + endif + let start = 0 + let highlights = [] + let lastLnum = -1 + for item in a:hls + let lnum = item['lnum'] + if lnum >= a:linecount + break + endif + if len(highlights) < g:coc_highlight_maximum_count || lnum == lastLnum + call add(highlights, item) + let lastLnum = lnum + else + call add(groups, {'start': start, 'end': lastLnum + 1, 'highlights': highlights}) + let highlights = [] + let start = lastLnum + 1 + call add(highlights, item) + let lastLnum = lnum + endif + endfor + call add(groups, {'start': start, 'end': a:linecount, 'highlights': highlights}) + return groups +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/list.vim b/vim-config/plugins/coc.nvim/autoload/coc/list.vim index b9be251d..11e1e99f 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/list.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/list.vim @@ -1,14 +1,23 @@ scriptencoding utf-8 let s:is_vim = !has('nvim') let s:prefix = '[List Preview]' +let s:sign_group = 'CocList' " filetype detect could be slow. let s:filetype_map = { - \ 'vim': 'vim', - \ 'ts': 'typescript', - \ 'js': 'javascript', - \ 'html': 'html', - \ 'css': 'css' - \ } + \ 'c': 'c', + \ 'py': 'python', + \ 'vim': 'vim', + \ 'ts': 'typescript', + \ 'js': 'javascript', + \ 'html': 'html', + \ 'css': 'css' + \ } +let s:pwinid = -1 +let s:pbufnr = -1 +let s:match_ns = coc#highlight#create_namespace('list-match') +let s:sign_range = 'CocCursorLine' +let s:sign_popup_range = 'PopUpCocList' +let s:current_line_hl = 'CocListCurrent' function! coc#list#getchar() abort return coc#prompt#getchar() @@ -31,9 +40,9 @@ function! coc#list#setlines(bufnr, lines, append) endfunction function! coc#list#options(...) - let list = ['--top', '--tab', '--normal', '--no-sort', '--input', '--strict', + let list = ['--top', '--tab', '--normal', '--no-sort', '--input=', '--strict', \ '--regex', '--interactive', '--number-select', '--auto-preview', - \ '--ignore-case', '--no-quit', '--first'] + \ '--ignore-case', '--no-quit', '--first', '--reverse', '--height='] if get(g:, 'coc_enabled', 0) let names = coc#rpc#request('listNames', []) call extend(list, names) @@ -53,10 +62,14 @@ endfunction function! coc#list#create(position, height, name, numberSelect) if a:position ==# 'tab' - execute 'silent tabe list:///'.a:name + call coc#ui#safe_open('silent tabe', 'list:///'.a:name) else - execute 'silent keepalt '.(a:position ==# 'top' ? '' : 'botright').a:height.'sp list:///'.a:name - execute 'resize '.a:height + call s:save_views(-1) + let height = max([1, a:height]) + let cmd = 'silent keepalt '.(a:position ==# 'top' ? '' : 'botright').height.'sp' + call coc#ui#safe_open(cmd, 'list:///'.a:name) + call s:set_height(height) + call s:restore_views() endif if a:numberSelect setl norelativenumber @@ -64,9 +77,9 @@ function! coc#list#create(position, height, name, numberSelect) else setl nonumber setl norelativenumber - setl signcolumn=yes endif - return [bufnr('%'), win_getid()] + setl colorcolumn="" + return [bufnr('%'), win_getid(), tabpagenr()] endfunction " close list windows @@ -82,25 +95,67 @@ endfunction function! coc#list#setup(source) let b:list_status = {} setl buftype=nofile nobuflisted nofen nowrap - setl norelativenumber bufhidden=wipe cursorline winfixheight + setl norelativenumber bufhidden=wipe nocursorline winfixheight setl tabstop=1 nolist nocursorcolumn undolevels=-1 setl signcolumn=auto + if s:is_vim + setl nocursorline + else + setl cursorline + setl winhighlight=CursorLine:CocListLine + endif if has('nvim-0.5.0') || has('patch-8.1.0864') setl scrolloff=0 endif - if exists('&cursorlineopt') - setl cursorlineopt=both - endif setl filetype=list syntax case ignore let source = a:source[8:] let name = toupper(source[0]).source[1:] execute 'syntax match Coc'.name.'Line /\v^.*$/' - nnoremap c + if !s:is_vim + " Repeat press and would invoke on vim + nnoremap c + endif +endfunction + +function! coc#list#close(winid, position, target_win, saved_height) abort + let tabnr = coc#window#tabnr(a:winid) + if a:position ==# 'tab' + if tabnr != -1 + call coc#list#close_preview(tabnr, 0) + endif + call coc#window#close(a:winid) + else + call s:save_views(a:winid) + if tabnr != -1 + call coc#list#close_preview(tabnr, 0) + endif + if type(a:target_win) == v:t_number + call win_gotoid(a:target_win) + endif + call coc#window#close(a:winid) + call s:restore_views() + if type(a:saved_height) == v:t_number + call coc#window#set_height(a:target_win, a:saved_height) + endif + " call coc#rpc#notify('Log', ["close", a:target_win, v]) + endif +endfunction + +function! coc#list#select(bufnr, line) abort + if s:is_vim && !empty(a:bufnr) && bufloaded(a:bufnr) + call sign_unplace(s:sign_group, { 'buffer': a:bufnr }) + if a:line > 0 + call sign_place(6, s:sign_group, s:current_line_hl, a:bufnr, {'lnum': a:line}) + endif + endif endfunction " Check if previewwindow exists on current tab. function! coc#list#has_preview() + if s:pwinid != -1 && coc#window#visible(s:pwinid) + return 1 + endif for i in range(1, winnr('$')) let preview = getwinvar(i, 'previewwindow', getwinvar(i, '&previewwindow', 0)) if preview @@ -112,11 +167,14 @@ endfunction " Get previewwindow from tabnr, use 0 for current tab function! coc#list#get_preview(...) abort + if s:pwinid != -1 && coc#window#visible(s:pwinid) + return s:pwinid + endif let tabnr = get(a:, 1, 0) == 0 ? tabpagenr() : a:1 let info = gettabinfo(tabnr) if !empty(info) for win in info[0]['windows'] - if getwinvar(win, 'previewwindow', 0) + if gettabwinvar(tabnr, win, 'previewwindow', 0) return win endif endfor @@ -125,11 +183,10 @@ function! coc#list#get_preview(...) abort endfunction function! coc#list#scroll_preview(dir) abort - let winnr = coc#list#has_preview() - if !winnr + let winid = coc#list#get_preview() + if winid == -1 return endif - let winid = win_getid(winnr) if exists('*win_execute') call win_execute(winid, "normal! ".(a:dir ==# 'up' ? "\" : "\")) else @@ -140,73 +197,99 @@ function! coc#list#scroll_preview(dir) abort endif endfunction -function! coc#list#restore(winid, height) - if has('nvim') && nvim_win_is_valid(a:winid) - call nvim_win_set_height(a:winid, a:height) - elseif s:is_vim && exists('*win_execute') - call win_execute(a:winid, 'noa resize '.a:height, 'silent!') - redraw +function! coc#list#close_preview(...) abort + let tabnr = get(a:, 1, tabpagenr()) + let winid = coc#list#get_preview(tabnr) + if winid != -1 + let keep = get(a:, 2, 1) && tabnr == tabpagenr() && !coc#window#is_float(winid) + if keep + call s:save_views(winid) + endif + call coc#window#close(winid) + if keep + call s:restore_views() + endif endif endfunction -function! coc#list#set_height(height) abort - if winnr('$') == 1| return | endif - execute 'resize '.a:height +function! s:get_preview_lines(lines, config) abort + if empty(a:lines) + if get(a:config, 'scheme', 'file') !=# 'file' + let bufnr = s:load_buffer(get(a:config, 'name', '')) + return bufnr == 0 ? [''] : getbufline(bufnr, 1, '$') + else + return [''] + endif + endif + return a:lines endfunction -function! coc#list#hide(original, height, winid) abort - let arr = win_id2tabwin(a:winid) - " close preview window - if !empty(arr) && arr[0] != 0 - silent! pclose! - let previewwin = coc#list#get_preview(arr[0]) - call coc#window#close(previewwin) - endif - if !empty(getwininfo(a:original)) - call win_gotoid(a:original) - endif - if a:winid - silent! call coc#window#close(a:winid) - endif - if !empty(a:height) && win_getid() == a:original - if exists('*nvim_win_set_height') - call nvim_win_set_height(a:original, a:height) - elseif win_getid() == a:original - execute 'resize '.a:height - endif +function! coc#list#float_preview(lines, config) abort + let position = get(a:config, 'position', 'bottom') + if position ==# 'tab' + throw 'unable to use float preview' + endif + let remain = 0 + let winrow = win_screenpos(winnr())[0] + if position ==# 'bottom' + let remain = winrow - 2 + else + let winbottom = winrow + winheight(winnr()) + let remain = &lines - &cmdheight - 1 - winbottom + endif + let lines = s:get_preview_lines(a:lines, a:config) + let height = s:get_preview_height(lines, a:config) + let height = min([remain, height + 2]) + if height < 0 + return endif + let row = position ==# 'bottom' ? winrow - 3 - height : winrow + winheight(winnr()) + let title = fnamemodify(get(a:config, 'name', ''), ':.') + let total = get(get(b:, 'list_status', {}), 'total', 0) + if !empty(total) + let title .= ' ('.line('.').'/'.total.')' + endif + let lnum = get(a:config, 'lnum', 1) + let opts = { + \ 'relative': 'editor', + \ 'width': winwidth(winnr()) - 2, + \ 'borderhighlight': 'MoreMsg', + \ 'highlight': 'Normal', + \ 'height': height, + \ 'col': 0, + \ 'index': lnum - 1, + \ 'row': row, + \ 'border': [1,1,1,1], + \ 'rounded': 1, + \ 'lines': lines, + \ 'scrollinside': 1, + \ 'title': title, + \ } + let result = coc#float#create_float_win(s:pwinid, s:pbufnr, opts) + if empty(result) + return + endif + let s:pwinid = result[0] + let s:pbufnr = result[1] + call setwinvar(s:pwinid, 'previewwindow', 1) + let topline = s:get_topline(a:config, lnum, height) + call coc#window#restview(s:pwinid, lnum, topline) + call s:preview_highlights(s:pwinid, s:pbufnr, a:config, 1) endfunction " Improve preview performance by reused window & buffer. " lines - list of lines -" config.position - could be 'below' 'top' 'tab'. +" config.position - could be 'bottom' 'top' 'tab'. " config.winid - id of original window. " config.name - (optional )name of preview buffer. " config.splitRight - (optional) split to right when 1. " config.lnum - (optional) current line number " config.filetype - (optional) filetype of lines. +" config.range - (optional) highlight range. with hlGroup. " config.hlGroup - (optional) highlight group. -" config.maxHeight - (optional) max height of window, valid for 'below' & 'top' position. +" config.maxHeight - (optional) max height of window, valid for 'bottom' & 'top' position. function! coc#list#preview(lines, config) abort - if s:is_vim && !exists('*win_execute') - throw 'win_execute function required for preview, please upgrade your vim.' - return - endif - let name = fnamemodify(get(a:config, 'name', ''), ':.') - let lines = a:lines - if empty(lines) - if get(a:config, 'scheme', 'file') != 'file' - let bufnr = s:load_buffer(name) - if bufnr != 0 - let lines = getbufline(bufnr, 1, '$') - else - let lines = [''] - endif - else - " Show empty lines so not close window. - let lines = [''] - endif - endif + let lines = s:get_preview_lines(a:lines, a:config) let winid = coc#list#get_preview(0) let bufnr = winid == -1 ? 0 : winbufnr(winid) " Try reuse buffer & window @@ -214,16 +297,8 @@ function! coc#list#preview(lines, config) abort if bufnr == 0 return endif - call setbufvar(bufnr, '&synmaxcol', 500) - let filetype = get(a:config, 'filetype', '') - let extname = matchstr(name, '\.\zs[^.]\+$') - if empty(filetype) && !empty(extname) - let filetype = get(s:filetype_map, extname, '') - endif - let range = get(a:config, 'range', v:null) - let hlGroup = get(a:config, 'hlGroup', 'Search') let lnum = get(a:config, 'lnum', 1) - let position = get(a:config, 'position', 'below') + let position = get(a:config, 'position', 'bottom') let original = get(a:config, 'winid', -1) if winid == -1 let change = position != 'tab' && get(a:config, 'splitRight', 0) @@ -241,19 +316,18 @@ function! coc#list#preview(lines, config) abort let winid = win_getid() else let mod = position == 'top' ? 'below' : 'above' - let height = s:get_height(lines, a:config) + let height = s:get_preview_height(lines, a:config) + call s:save_views(-1) execute 'noa '.mod.' sb +resize\ '.height.' '.bufnr + call s:restore_views() let winid = win_getid() endif - noa call winrestview({"lnum": lnum ,"topline":s:get_topline(a:config, lnum, winid)}) - call setwinvar(winid, '&signcolumn', 'no') - call setwinvar(winid, '&number', 1) - call setwinvar(winid, '&cursorline', 0) - call setwinvar(winid, '&relativenumber', 0) - call setwinvar(winid, 'previewwindow', 1) + call setbufvar(bufnr, '&synmaxcol', 500) + noa call winrestview({"lnum": lnum ,"topline":s:get_topline(a:config, lnum, winheight(winid))}) + call s:set_preview_options(winid) noa call win_gotoid(curr) else - let height = s:get_height(lines, a:config) + let height = s:get_preview_height(lines, a:config) if height > 0 if s:is_vim let curr = win_getid() @@ -261,43 +335,65 @@ function! coc#list#preview(lines, config) abort execute 'silent! noa resize '.height noa call win_gotoid(curr) else + call s:save_views(winid) call nvim_win_set_height(winid, height) + call s:restore_views() endif endif - call coc#compat#execute(winid, ['syntax clear', 'noa call winrestview({"lnum":'.lnum.',"topline":'.s:get_topline(a:config, lnum, winid).'})']) + call coc#window#restview(winid, lnum, s:get_topline(a:config, lnum, height)) endif - call setwinvar(winid, '&foldenable', 0) - if s:prefix.' '.name != bufname(bufnr) + call s:preview_highlights(winid, bufnr, a:config, 0) +endfunction + +function! s:preview_highlights(winid, bufnr, config, float) abort + let name = fnamemodify(get(a:config, 'name', ''), ':.') + let newname = s:prefix.' '.name + if newname !=# bufname(a:bufnr) if s:is_vim - call win_execute(winid, 'noa file '.fnameescape(s:prefix.' '.name), 'silent!') + call win_execute(a:winid, 'noa file '.fnameescape(newname), 'silent!') else - silent! noa call nvim_buf_set_name(bufnr, s:prefix.' '.name) + silent! noa call nvim_buf_set_name(a:bufnr, newname) endif endif + + let filetype = get(a:config, 'filetype', '') + let extname = matchstr(name, '\.\zs[^.]\+$') + if empty(filetype) && !empty(extname) + let filetype = get(s:filetype_map, extname, '') + endif " highlights + let sign_group = s:is_vim && a:float ? s:sign_popup_range : s:sign_range + call coc#compat#execute(a:winid, ['syntax clear', 'call clearmatches()']) + call sign_unplace(sign_group, {'buffer': a:bufnr}) + let lnum = get(a:config, 'lnum', 1) if !empty(filetype) let start = max([0, lnum - 300]) - let end = min([len(lines), lnum + 300]) - call coc#highlight#highlight_lines(winid, [{'filetype': filetype, 'startLine': start, 'endLine': end}]) - call coc#compat#execute(winid, 'syn sync fromstart') + let end = min([coc#compat#buf_line_count(a:bufnr), lnum + 300]) + call coc#highlight#highlight_lines(a:winid, [{'filetype': filetype, 'startLine': start, 'endLine': end}]) + call coc#compat#execute(a:winid, 'syn sync fromstart') else - call coc#compat#execute(winid, 'filetype detect') - let ft = getbufvar(bufnr, '&filetype', '') + call coc#compat#execute(a:winid, 'filetype detect') + let ft = getbufvar(a:bufnr, '&filetype', '') if !empty(extname) && !empty(ft) let s:filetype_map[extname] = ft endif endif - call sign_unplace('coc', {'buffer': bufnr}) - call coc#compat#execute(winid, 'call clearmatches()') + " selection range + let targetRange = get(a:config, 'targetRange', v:null) + if !empty(targetRange) + for lnum in range(targetRange['start']['line'] + 1, targetRange['end']['line'] + 1) + call sign_place(0, sign_group, s:current_line_hl, a:bufnr, {'lnum': lnum}) + endfor + endif + let range = get(a:config, 'range', v:null) if !empty(range) - call sign_place(1, 'coc', 'CocCurrentLine', bufnr, {'lnum': lnum}) - call coc#highlight#match_ranges(winid, bufnr, [range], hlGroup, 10) + let hlGroup = get(a:config, 'hlGroup', 'Search') + call coc#highlight#match_ranges(a:winid, a:bufnr, [range], hlGroup, 10) endif - redraw endfunction -function! s:get_height(lines, config) abort - if get(a:config, 'splitRight', 0) || get(a:config, 'position', 'below') == 'tab' +function! s:get_preview_height(lines, config) abort + if get(a:config, 'splitRight', 0) || get(a:config, 'position', 'bottom') == 'tab' return 0 endif let height = min([get(a:config, 'maxHeight', 10), len(a:lines), &lines - &cmdheight - 2]) @@ -313,12 +409,55 @@ function! s:load_buffer(name) abort return 0 endfunction -function! s:get_topline(config, lnum, winid) abort +function! s:get_topline(config, lnum, winheight) abort let toplineStyle = get(a:config, 'toplineStyle', 'offset') if toplineStyle == 'middle' - return max([1, a:lnum - winheight(a:winid)/2]) + return max([1, a:lnum - a:winheight/2]) endif - let toplineOffset = get(a:config, 'toplineOffset', 3) return max([1, a:lnum - toplineOffset]) endfunction + +function! s:set_preview_options(winid) abort + call setwinvar(a:winid, '&foldmethod', 'manual') + call setwinvar(a:winid, '&foldenable', 0) + call setwinvar(a:winid, '&signcolumn', 'no') + call setwinvar(a:winid, '&number', 1) + call setwinvar(a:winid, '&cursorline', 0) + call setwinvar(a:winid, '&relativenumber', 0) + call setwinvar(a:winid, 'previewwindow', 1) +endfunction + +" save views on current tabpage +function! s:save_views(exclude) abort + " Not work as expected when cursor becomes hidden + if s:is_vim + return + endif + for nr in range(1, winnr('$')) + let winid = win_getid(nr) + if winid != a:exclude && getwinvar(nr, 'previewwindow', 0) == 0 && !coc#window#is_float(winid) + call coc#compat#execute(winid, 'let w:coc_list_saved_view = winsaveview()') + endif + endfor +endfunction + +function! s:restore_views() abort + if s:is_vim + return + endif + for nr in range(1, winnr('$')) + let saved = getwinvar(nr, 'coc_list_saved_view', v:null) + if !empty(saved) + let winid = win_getid(nr) + call coc#compat#execute(winid, 'noa call winrestview(w:coc_list_saved_view) | unlet w:coc_list_saved_view') + endif + endfor +endfunction + +function! s:set_height(height) abort + let curr = winheight(0) + if curr != a:height + execute 'resize '.a:height + endif +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/math.vim b/vim-config/plugins/coc.nvim/autoload/coc/math.vim new file mode 100644 index 00000000..27757b94 --- /dev/null +++ b/vim-config/plugins/coc.nvim/autoload/coc/math.vim @@ -0,0 +1,11 @@ + +" support for float values +function! coc#math#min(first, ...) abort + let val = a:first + for i in range(0, len(a:000) - 1) + if a:000[i] < val + let val = a:000[i] + endif + endfor + return val +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/notify.vim b/vim-config/plugins/coc.nvim/autoload/coc/notify.vim new file mode 100644 index 00000000..419f36c8 --- /dev/null +++ b/vim-config/plugins/coc.nvim/autoload/coc/notify.vim @@ -0,0 +1,532 @@ +scriptencoding utf-8 +let s:is_vim = !has('nvim') +let s:utf = has('nvim') || &encoding =~# '^utf' +let s:error_icon = get(g:, 'coc_notify_error_icon', s:utf ? "\uf057" : 'E') +let s:warning_icon = get(g:, 'coc_notify_warning_icon', s:utf ? "\u26a0" : 'W') +let s:info_icon = get(g:, 'coc_notify_info_icon', s:utf ? "\uf06a" : 'I') +let s:interval = get(g:, 'coc_notify_interval', s:is_vim ? 50 : 20) +let s:phl = 'CocNotificationProgress' +let s:progress_char = 'โ”€' +let s:duration = 300.0 +let s:winids = [] + +" Valid notify winids on current tab +function! coc#notify#win_list() abort + call filter(s:winids, 'coc#float#valid(v:val)') + return filter(copy(s:winids), '!empty(getwinvar(v:val,"float"))') +endfunction + +function! coc#notify#close_all() abort + for winid in coc#notify#win_list() + call coc#notify#close(winid) + endfor +endfunction + +" Do action for winid or first notify window with actions. +function! coc#notify#do_action(...) abort + let winids = a:0 > 0 ? a:000 : coc#notify#win_list() + for winid in winids + if coc#float#valid(winid) && getwinvar(winid, 'closing', 0) != 1 + let actions = getwinvar(winid, 'actions', []) + if !empty(actions) + let items = map(copy(actions), '(v:key + 1).". ".v:val') + let msg = join(getbufline(winbufnr(winid), 1, '$'), ' ') + call coc#ui#quickpick(msg, items, {err, res -> s:on_action(err, res, winid) }) + break + endif + endif + endfor +endfunction + +" Copy notification contents +function! coc#notify#copy() abort + let lines = [] + for winid in coc#notify#win_list() + let key = getwinvar(winid, 'key', v:null) + if type(key) == v:t_string + call extend(lines, json_decode(key)['lines']) + endif + endfor + if empty(lines) + echohl WarningMsg | echon 'No content to copy' | echohl None + return + endif + call setreg('*', join(lines, "\n")) +endfunction + +" Show source name in window +function! coc#notify#show_sources() abort + if !exists('*getbufline') || !exists('*appendbufline') + throw "getbufline and appendbufline functions required, please upgrade your vim." + endif + let winids = filter(coc#notify#win_list(), 'coc#window#get_var(v:val,"closing") != 1') + for winid in winids + let key = getwinvar(winid, 'key', v:null) + if type(key) == v:t_string + let bufnr = winbufnr(winid) + let obj = json_decode(key) + let sourcename = get(obj, 'source', '') + let lnum = get(obj, 'kind', '') ==# 'progress' ? 1 : 0 + let content = get(getbufline(bufnr, lnum + 1), 0, '') + if empty(sourcename) || content ==# sourcename + continue + endif + call appendbufline(bufnr, lnum, sourcename) + call coc#highlight#add_highlight(bufnr, -1, 'Title', lnum, 0, -1) + call coc#float#scroll_win(winid, 0, 1) + endif + endfor + redra +endfunction + +function! coc#notify#close_by_source(source) abort + let winids = filter(coc#notify#win_list(), 'coc#window#get_var(v:val,"closing") != 1') + for winid in winids + let key = getwinvar(winid, 'key', v:null) + if type(key) == v:t_string + let obj = json_decode(key) + if get(obj, 'source', '') ==# a:source + call coc#notify#close(winid) + endif + endif + endfor +endfunction + +" Cancel auto hide +function! coc#notify#keep() abort + for winid in coc#notify#win_list() + call s:cancel(winid, 'close_timer') + endfor +endfunction + +" borderhighlight - border highlight [string] +" maxWidth - max content width, default 60 [number] +" minWidth - minimal width [number] +" maxHeight - max content height, default 10 [number] +" highlight - default highlight [string] +" winblend - winblend [number] +" timeout - auto close timeout, default 5000 [number] +" title - title text +" marginRight - margin right, default 10 [number] +" focusable - focusable [number] +" source - source name [string] +" kind - kind for create icon [string] +" actions - action names [string[]] +function! coc#notify#create(lines, config) abort + let actions = get(a:config, 'actions', []) + let key = json_encode(extend({'lines': a:lines}, a:config)) + let winid = s:find_win(key) + let kind = get(a:config, 'kind', '') + let row = 0 + if winid != -1 + let row = getwinvar(winid, 'top', 0) + call filter(s:winids, 'v:val != '.winid) + call coc#float#close(winid, 1) + let winid = v:null + endif + let opts = coc#dict#pick(a:config, ['highlight', 'borderhighlight', 'focusable', 'shadow']) + let border = has_key(opts, 'borderhighlight') ? [1, 1, 1, 1] : [] + let icon = s:get_icon(kind, get(a:config, 'highlight', 'CocFloating')) + let margin = get(a:config, 'marginRight', 10) + let maxWidth = min([&columns - margin - 2, get(a:config, 'maxWidth', 80)]) + if maxWidth <= 0 + throw 'No enough spaces for notification' + endif + let lines = map(copy(a:lines), 'tr(v:val, "\t", " ")') + if has_key(a:config, 'title') + if !empty(border) + let opts['title'] = a:config['title'] + else + let lines = [a:config['title']] + lines + endif + endif + let width = max(map(copy(lines), 'strwidth(v:val)')) + (empty(icon) ? 1 : 3) + if width > maxWidth + let lines = coc#string#reflow(lines, maxWidth) + let width = max(map(copy(lines), 'strwidth(v:val)')) + (empty(icon) ? 1 : 3) + endif + let highlights = [] + if !empty(icon) + let ic = icon['text'] + if empty(lines) + call add(lines, ic) + else + let lines[0] = ic.' '.lines[0] + endif + call add(highlights, {'lnum': 0, 'hlGroup': icon['hl'], 'colStart': 0, 'colEnd': strlen(ic)}) + endif + let actionText = join(actions, ' ') + call map(lines, 'v:key == 0 ? v:val : repeat(" ", '.(empty(icon) ? 0 : 2).').v:val') + let minWidth = get(a:config, 'minWidth', kind ==# 'progress' ? 30 : 10) + let width = max(extend(map(lines + [get(opts, 'title', '').' '], 'strwidth(v:val)'), [minWidth, strwidth(actionText) + 1])) + let width = min([maxWidth, width]) + let height = min([get(a:config, 'maxHeight', 3), len(lines)]) + if kind ==# 'progress' + let lines = [repeat(s:progress_char, width)] + lines + let height = height + 1 + endif + if !empty(actions) + let before = max([width - strwidth(actionText), 0]) + let lines = lines + [repeat(' ', before).actionText] + let height = height + 1 + call s:add_action_highlights(before, height - 1, highlights, actions) + endif + if row == 0 + let wintop = coc#notify#get_top() + let row = wintop - height - (empty(border) ? 0 : 2) - 1 + if !s:is_vim && !empty(border) + let row = row + 1 + endif + endif + let col = &columns - margin - width + if s:is_vim && !empty(border) + let col = col - 2 + endif + let winblend = 60 + " Avoid animate for transparent background. + if get(a:config, 'winblend', 30) == 0 && empty(synIDattr(synIDtrans(hlID(get(opts, 'highlight', 'CocFloating'))), 'bg', 'gui')) + let winblend = 0 + endif + call extend(opts, { + \ 'relative': 'editor', + \ 'width': width, + \ 'height': height, + \ 'col': col, + \ 'row': row + 1, + \ 'lines': lines, + \ 'rounded': 1, + \ 'highlights': highlights, + \ 'winblend': winblend, + \ 'border': border, + \ }) + let result = coc#float#create_float_win(0, 0, opts) + if empty(result) + throw 'Unable to create notify window' + endif + let winid = result[0] + let bufnr = result[1] + call setwinvar(winid, 'right', 1) + call setwinvar(winid, 'kind', 'notification') + call setwinvar(winid, 'top', row) + call setwinvar(winid, 'key', key) + call setwinvar(winid, 'actions', actions) + call setwinvar(winid, 'source', get(a:config, 'source', '')) + call setwinvar(winid, 'border', !empty(border)) + call coc#float#nvim_scrollbar(winid) + call add(s:winids, winid) + let from = {'row': opts['row'], 'winblend': opts['winblend']} + let to = {'row': row, 'winblend': get(a:config, 'winblend', 30)} + call timer_start(s:interval, { -> s:animate(winid, from, to, 0)}) + if kind ==# 'progress' + call timer_start(s:interval, { -> s:progress(winid, width, 0, -1)}) + endif + if !s:is_vim + call coc#compat#buf_add_keymap(bufnr, 'n', '', ':call coc#notify#nvim_click('.winid.')', { + \ 'silent': v:true, + \ 'nowait': v:true + \ }) + endif + " Enable auto close + if empty(actions) && kind !=# 'progress' + let timer = timer_start(get(a:config, 'timeout', 10000), { -> coc#notify#close(winid)}) + call setwinvar(winid, 'close_timer', timer) + endif + return [winid, bufnr] +endfunction + +function! coc#notify#nvim_click(winid) abort + if getwinvar(a:winid, 'closing', 0) + return + endif + call s:cancel(a:winid, 'close_timer') + let actions = getwinvar(a:winid, 'actions', []) + if !empty(actions) + let character = strpart(getline('.'), col('.') - 1, 1) + if character =~# '^\k' + let word = expand('') + let idx = index(actions, word) + if idx != -1 + call coc#rpc#notify('FloatBtnClick', [winbufnr(a:winid), idx]) + call coc#notify#close(a:winid) + endif + endif + endif +endfunction + +function! coc#notify#on_close(winid) abort + if index(s:winids, a:winid) >= 0 + call filter(s:winids, 'v:val != '.a:winid) + call coc#notify#reflow() + endif +endfunction + +function! coc#notify#get_top() abort + let mintop = min(map(coc#notify#win_list(), 'coc#notify#get_win_top(v:val)')) + if mintop != 0 + return mintop + endif + return &lines - &cmdheight - (&laststatus == 0 ? 0 : 1 ) +endfunction + +function! coc#notify#get_win_top(winid) abort + let row = getwinvar(a:winid, 'top', 0) + if row == 0 + return row + endif + return row - (s:is_vim ? 0 : getwinvar(a:winid, 'border', 0)) +endfunction + +" Close with timer +function! coc#notify#close(winid) abort + if !coc#float#valid(a:winid) || coc#window#get_var(a:winid, 'closing', 0) == 1 + return + endif + if !coc#window#visible(a:winid) + call coc#float#close(a:winid, 1) + return + endif + let row = coc#window#get_var(a:winid, 'top') + if type(row) != v:t_number + call coc#float#close(a:winid) + return + endif + call coc#window#set_var(a:winid, 'closing', 1) + call s:cancel(a:winid) + let winblend = coc#window#get_var(a:winid, 'winblend', 0) + let curr = s:is_vim ? {'row': row} : {'winblend': winblend} + let dest = s:is_vim ? {'row': row + 1} : {'winblend': winblend == 0 ? 0 : 60} + call s:animate(a:winid, curr, dest, 0, 1) +endfunction + +function! s:add_action_highlights(before, lnum, highlights, actions) abort + let colStart = a:before + for text in a:actions + let w = strwidth(text) + call add(a:highlights, { + \ 'lnum': a:lnum, + \ 'hlGroup': 'CocNotificationButton', + \ 'colStart': colStart, + \ 'colEnd': colStart + w + \ }) + let colStart = colStart + w + 1 + endfor +endfunction + +function! s:on_action(err, idx, winid) abort + if !empty(a:err) + throw a:err + endif + if a:idx > 0 + call coc#rpc#notify('FloatBtnClick', [winbufnr(a:winid), a:idx - 1]) + call coc#notify#close(a:winid) + endif +endfunction + +function! s:cancel(winid, ...) abort + let name = get(a:, 1, 'timer') + let timer = coc#window#get_var(a:winid, name) + if !empty(timer) + call timer_stop(timer) + call coc#window#set_var(a:winid, name, v:null) + endif +endfunction + +function! s:progress(winid, total, curr, index) abort + if !coc#float#valid(a:winid) + return + endif + if coc#window#visible(a:winid) + let total = a:total + let idx = float2nr(a:curr/5.0)%total + if idx != a:index + " update percent + let bufnr = winbufnr(a:winid) + let percent = coc#window#get_var(a:winid, 'percent') + if !empty(percent) + let width = strchars(get(getbufline(bufnr, 1), 0, '')) + let line = repeat(s:progress_char, width - 4).printf('%4s', percent) + let total = width - 4 + call setbufline(bufnr, 1, line) + endif + let message = coc#window#get_var(a:winid, 'message') + if !empty(message) + let linecount = coc#compat#buf_line_count(bufnr) + let hasAction = !empty(coc#window#get_var(a:winid, 'actions', [])) + if getbufvar(bufnr, 'message', 0) == 0 + call appendbufline(bufnr, linecount - hasAction, message) + call setbufvar(bufnr, 'message', 1) + call coc#float#change_height(a:winid, 1) + let tabnr = coc#window#tabnr(a:winid) + call coc#notify#reflow(tabnr) + else + call setbufline(bufnr, linecount - hasAction, message) + endif + endif + let bytes = strlen(s:progress_char) + call coc#highlight#clear_highlight(bufnr, -1, 0, 1) + let colStart = bytes * idx + if idx + 4 <= total + let colEnd = bytes * (idx + 4) + call coc#highlight#add_highlight(bufnr, -1, s:phl, 0, colStart, colEnd) + else + let colEnd = bytes * total + call coc#highlight#add_highlight(bufnr, -1, s:phl, 0, colStart, colEnd) + call coc#highlight#add_highlight(bufnr, -1, s:phl, 0, 0, bytes * (idx + 4 - total)) + endif + endif + call timer_start(s:interval, { -> s:progress(a:winid, total, a:curr + 1, idx)}) + else + " Not block CursorHold event + call timer_start(&updatetime + 100, { -> s:progress(a:winid, a:total, a:curr, a:index)}) + endif +endfunction + +" Optional row & winblend +function! s:config_win(winid, props) abort + let change_row = has_key(a:props, 'row') + if s:is_vim + if change_row + call popup_move(a:winid, {'line': a:props['row'] + 1}) + endif + else + if change_row + let [row, column] = nvim_win_get_position(a:winid) + call nvim_win_set_config(a:winid, { + \ 'row': a:props['row'], + \ 'col': column, + \ 'relative': 'editor', + \ }) + call s:nvim_move_related(a:winid, a:props['row']) + endif + call coc#float#nvim_set_winblend(a:winid, get(a:props, 'winblend', v:null)) + call coc#float#nvim_refresh_scrollbar(a:winid) + endif +endfunction + +function! s:nvim_move_related(winid, row) abort + let winids = coc#window#get_var(a:winid, 'related') + if empty(winids) + return + endif + for winid in winids + if nvim_win_is_valid(winid) + let [row, column] = nvim_win_get_position(winid) + let delta = coc#window#get_var(winid, 'delta', 0) + call nvim_win_set_config(winid, { + \ 'row': a:row + delta, + \ 'col': column, + \ 'relative': 'editor', + \ }) + endif + endfor +endfunction + +function! s:animate(winid, from, to, prev, ...) abort + if !coc#float#valid(a:winid) + return + endif + let curr = a:prev + s:interval + let percent = coc#math#min(curr / s:duration, 1) + let props = s:get_props(a:from, a:to, percent) + call s:config_win(a:winid, props) + let close = get(a:, 1, 0) + if percent < 1 + call timer_start(s:interval, { -> s:animate(a:winid, a:from, a:to, curr, close)}) + elseif close + call filter(s:winids, 'v:val != '.a:winid) + let tabnr = coc#window#tabnr(a:winid) + if tabnr != -1 + call coc#float#close(a:winid, 1) + call coc#notify#reflow(tabnr) + endif + endif +endfunction + +function! coc#notify#reflow(...) abort + let tabnr = get(a:, 1, tabpagenr()) + let winids = filter(copy(s:winids), 'coc#window#tabnr(v:val) == '.tabnr.' && coc#window#get_var(v:val,"closing") != 1') + if empty(winids) + return + endif + let animate = tabnr == tabpagenr() + let wins = map(copy(winids), {_, val -> { + \ 'winid': val, + \ 'row': coc#window#get_var(val,'top',0), + \ 'top': coc#window#get_var(val,'top',0) - (s:is_vim ? 0 : coc#window#get_var(val, 'border', 0)), + \ 'height': coc#float#get_height(val), + \ }}) + call sort(wins, {a, b -> b['top'] - a['top']}) + let bottom = &lines - &cmdheight - (&laststatus == 0 ? 0 : 1 ) + let moved = 0 + for item in wins + let winid = item['winid'] + let delta = bottom - (item['top'] + item['height'] + 1) + if delta != 0 + call s:cancel(winid) + let dest = item['row'] + delta + call coc#window#set_var(winid, 'top', dest) + if animate + call s:move_win_timer(winid, {'row': item['row']}, {'row': dest}, 0) + else + call s:config_win(winid, {'row': dest}) + endif + let moved = moved + delta + endif + let bottom = item['top'] + delta + endfor +endfunction + +function! s:move_win_timer(winid, from, to, curr) abort + if !coc#float#valid(a:winid) + return + endif + if coc#window#get_var(a:winid, 'closing', 0) == 1 + return + endif + let percent = coc#math#min(a:curr / s:duration, 1) + let next = a:curr + s:interval + if a:curr > 0 + call s:config_win(a:winid, s:get_props(a:from, a:to, percent)) + endif + if percent < 1 + let timer = timer_start(s:interval, { -> s:move_win_timer(a:winid, a:from, a:to, next)}) + call coc#window#set_var(a:winid, 'timer', timer) + endif +endfunction + +function! s:find_win(key) abort + for winid in coc#notify#win_list() + if getwinvar(winid, 'key', '') ==# a:key + return winid + endif + endfor + return -1 +endfunction + +function! s:get_icon(kind, bg) abort + if a:kind ==# 'info' + return {'text': s:info_icon, 'hl': coc#highlight#compose_hlgroup('CocInfoSign', a:bg)} + endif + if a:kind ==# 'warning' + return {'text': s:warning_icon, 'hl': coc#highlight#compose_hlgroup('CocWarningSign', a:bg)} + endif + if a:kind ==# 'error' + return {'text': s:error_icon, 'hl': coc#highlight#compose_hlgroup('CocErrorSign', a:bg)} + endif + return v:null +endfunction + +" percent should be float +function! s:get_props(from, to, percent) abort + let obj = {} + for key in keys(a:from) + let changed = a:to[key] - a:from[key] + if !s:is_vim && key ==# 'row' + " Could be float + let obj[key] = a:from[key] + changed * a:percent + else + let obj[key] = a:from[key] + float2nr(round(changed * a:percent)) + endif + endfor + return obj +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/prompt.vim b/vim-config/plugins/coc.nvim/autoload/coc/prompt.vim index cbe4a97b..b452f95b 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/prompt.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/prompt.vim @@ -83,7 +83,7 @@ let s:char_map = { function! coc#prompt#getc() abort let c = getchar() - return type(c) == type(0) ? nr2char(c) : c + return type(c) is 0 ? nr2char(c) : c endfunction function! coc#prompt#getchar() abort @@ -92,9 +92,13 @@ function! coc#prompt#getchar() abort return input endif "a language keymap is activated, so input must be resolved to the mapped values. - let partial_keymap = mapcheck(input, "l") - while partial_keymap !=# "" - let full_keymap = maparg(input, "l") + let partial_keymap = mapcheck(input, 'l') + while partial_keymap !=# '' + let dict = maparg(input, 'l', 0, 1) + if empty(dict) || get(dict, 'expr', 0) + return input + endif + let full_keymap = get(dict, 'rhs', '') if full_keymap ==# "" && len(input) >= 3 "HACK: assume there are no keymaps longer than 3. return input elseif full_keymap ==# partial_keymap @@ -109,7 +113,7 @@ function! coc#prompt#getchar() abort return input endif let input .= c - let partial_keymap = mapcheck(input, "l") + let partial_keymap = mapcheck(input, 'l') endwhile return input endfunction @@ -161,7 +165,9 @@ function! s:start_prompt() endwhile catch /^Vim:Interrupt$/ let s:activated = 0 - call coc#rpc#notify('InputChar', [s:current_session(), '']) + call coc#rpc#notify('InputChar', [s:current_session(), '', 0]) + let s:session_names = [] + call s:reset() return endtry let s:activated = 0 diff --git a/vim-config/plugins/coc.nvim/autoload/coc/pum.vim b/vim-config/plugins/coc.nvim/autoload/coc/pum.vim new file mode 100644 index 00000000..76be0430 --- /dev/null +++ b/vim-config/plugins/coc.nvim/autoload/coc/pum.vim @@ -0,0 +1,615 @@ +scriptencoding utf-8 +let s:is_vim = !has('nvim') +let s:pum_bufnr = 0 +let s:pum_winid = -1 +let s:pum_index = -1 +let s:pum_size = 0 +let s:inserted = 0 +let s:virtual_text = 0 +let s:virtual_text_ns = coc#highlight#create_namespace('pum-virtual') +let s:ignore = s:is_vim || has('nvim-0.5.0') ? "\" : "\\" +let s:hide_pum = has('nvim-0.6.1') || has('patch-8.2.3389') +let s:virtual_text_support = has('nvim-0.5.0') || has('patch-9.0.0067') +" bufnr, &indentkeys +let s:saved_indenetkeys = [] +let s:prop_id = 0 +let s:reversed = 0 +let s:check_hl_group = 0 +let s:start_col = -1 + +if s:is_vim && s:virtual_text_support + if empty(prop_type_get('CocPumVirtualText')) + call prop_type_add('CocPumVirtualText', {'highlight': 'CocPumVirtualText'}) + endif +endif + +function! coc#pum#visible() abort + if s:pum_winid == -1 + return 0 + endif + " getwinvar check current tab only. + return getwinvar(s:pum_winid, 'float', 0) == 1 +endfunction + +function! coc#pum#winid() abort + return s:pum_winid +endfunction + +function! coc#pum#close_detail() abort + let winid = coc#float#get_float_by_kind('pumdetail') + if winid + call coc#float#close(winid, 1) + endif +endfunction + +function! coc#pum#close(...) abort + if coc#pum#visible() + let kind = get(a:, 1, '') + if kind ==# 'cancel' + let input = getwinvar(s:pum_winid, 'input', '') + let s:pum_index = -1 + call s:insert_word(input, 1) + call s:on_pum_change(0) + doautocmd TextChangedI + elseif kind ==# 'confirm' + let words = getwinvar(s:pum_winid, 'words', []) + if s:pum_index >= 0 + let word = get(words, s:pum_index, '') + call s:insert_word(word, 1) + " have to restore here, so that TextChangedI can trigger indent. + call s:restore_indentkeys() + endif + doautocmd TextChangedI + endif + call s:close_pum() + if !get(a:, 2, 0) + call coc#rpc#notify('CompleteStop', [kind]) + endif + endif + return '' +endfunction + +function! coc#pum#select_confirm() abort + if coc#pum#visible() + if s:pum_index < 0 + let s:pum_index = 0 + call s:on_pum_change(0) + endif + call coc#pum#close('confirm') + endif + return '' +endfunction + +function! coc#pum#_close() abort + if coc#pum#visible() + call s:close_pum() + endif +endfunction + +function! coc#pum#_one_more() abort + if coc#pum#visible() + let parts = getwinvar(s:pum_winid, 'parts', []) + let start = strlen(parts[0]) + let input = strpart(getline('.'), start, col('.') - 1 - start) + let words = getwinvar(s:pum_winid, 'words', []) + let word = get(words, s:pum_index == -1 ? 0 : s:pum_index, '') + if !empty(word) && strcharpart(word, 0, strchars(input)) ==# input + let ch = strcharpart(word, strchars(input), 1) + if !empty(ch) + call feedkeys(ch, "int") + endif + endif + endif + return '' +endfunction + +function! coc#pum#_insert() abort + if coc#pum#visible() + if s:pum_index >= 0 + let words = getwinvar(s:pum_winid, 'words', []) + let word = get(words, s:pum_index, '') + call s:insert_word(word, 1) + call s:restore_indentkeys() + endif + doautocmd TextChangedI + call s:close_pum() + call coc#rpc#notify('CompleteStop', ['']) + endif + return '' +endfunction + +function! coc#pum#insert() abort + return "\=coc#pum#_insert()\" +endfunction + +" Add one more character from the matched complete item(or first one), +" the word should starts with input, the same as vim's CTRL-L behavior. +function! coc#pum#one_more() abort + return "\=coc#pum#_one_more()\" +endfunction + +function! coc#pum#next(insert) abort + return "\=coc#pum#_navigate(1,".a:insert.")\" +endfunction + +function! coc#pum#prev(insert) abort + return "\=coc#pum#_navigate(0,".a:insert.")\" +endfunction + +function! coc#pum#stop() abort + return "\=coc#pum#close()\" +endfunction + +function! coc#pum#cancel() abort + return "\=coc#pum#close('cancel')\" +endfunction + +function! coc#pum#confirm() abort + return "\=coc#pum#close('confirm')\" +endfunction + +function! coc#pum#select(index, insert, confirm) abort + if coc#pum#visible() + if a:index == -1 + call coc#pum#close('cancel') + return '' + endif + if a:index < 0 || a:index >= s:pum_size + throw 'index out of range ' . a:index + endif + call s:select_by_index(a:index, a:insert) + if a:confirm + call coc#pum#close('confirm') + endif + endif + return '' +endfunction + +function! coc#pum#info() abort + let bufnr = winbufnr(s:pum_winid) + let words = getwinvar(s:pum_winid, 'words', []) + let word = s:pum_index < 0 ? '' : get(words, s:pum_index, '') + let base = { + \ 'word': word, + \ 'index': s:pum_index, + \ 'size': s:pum_size, + \ 'startcol': s:start_col, + \ 'inserted': s:pum_index >=0 && s:inserted ? v:true : v:false, + \ 'reversed': s:reversed ? v:true : v:false, + \ } + if s:is_vim + let pos = popup_getpos(s:pum_winid) + let border = has_key(popup_getoptions(s:pum_winid), 'border') + let add = pos['scrollbar'] && border ? 1 : 0 + return extend(base, { + \ 'scrollbar': pos['scrollbar'], + \ 'row': pos['line'] - 1, + \ 'col': pos['col'] - 1, + \ 'width': pos['width'] + add, + \ 'height': pos['height'], + \ 'border': border, + \ }) + else + let scrollbar = coc#float#get_related(s:pum_winid, 'scrollbar') + let winid = coc#float#get_related(s:pum_winid, 'border', s:pum_winid) + let pos = nvim_win_get_position(winid) + return extend(base, { + \ 'scrollbar': scrollbar && nvim_win_is_valid(scrollbar) ? 1 : 0, + \ 'row': pos[0], + \ 'col': pos[1], + \ 'width': nvim_win_get_width(winid), + \ 'height': nvim_win_get_height(winid), + \ 'border': winid != s:pum_winid, + \ }) + endif +endfunction + +function! coc#pum#scroll(forward) abort + if coc#pum#visible() + let height = s:get_height(s:pum_winid) + if s:pum_size > height + call timer_start(1, { -> s:scroll_pum(a:forward, height, s:pum_size)}) + endif + endif + " Required on old version vim/neovim. + return s:ignore +endfunction + +function! s:get_height(winid) abort + if has('nvim') + return nvim_win_get_height(a:winid) + endif + return get(popup_getpos(a:winid), 'core_height', 0) +endfunction + +function! s:scroll_pum(forward, height, size) abort + let topline = s:get_topline(s:pum_winid) + if !a:forward && topline == 1 + if s:pum_index >= 0 + call s:select_line(s:pum_winid, 1) + call s:on_pum_change(1) + endif + return + endif + if a:forward && topline + a:height - 1 >= a:size + if s:pum_index >= 0 + call s:select_line(s:pum_winid, a:size) + call s:on_pum_change(1) + endif + return + endif + call coc#float#scroll_win(s:pum_winid, a:forward, a:height) + if s:pum_index >= 0 + let lnum = s:pum_index + 1 + let topline = s:get_topline(s:pum_winid) + if lnum >= topline && lnum <= topline + a:height - 1 + return + endif + call s:select_line(s:pum_winid, topline) + call s:on_pum_change(1) + endif +endfunction + +function! s:get_topline(winid) abort + if has('nvim') + let info = getwininfo(a:winid)[0] + return info['topline'] + else + let pos = popup_getpos(a:winid) + return pos['firstline'] + endif +endfunction + +function! coc#pum#_navigate(next, insert) abort + if coc#pum#visible() + call s:save_indentkeys() + let index = s:get_index(a:next) + call s:select_by_index(index, a:insert) + endif + return '' +endfunction + +function! s:select_by_index(index, insert) abort + let lnum = a:index == -1 ? 0 : s:index_to_lnum(a:index) + call s:set_cursor(s:pum_winid, lnum) + if !s:is_vim + call coc#float#nvim_scrollbar(s:pum_winid) + endif + if a:insert + let s:inserted = 1 + if a:index < 0 + let input = getwinvar(s:pum_winid, 'input', '') + call s:insert_word(input, 0) + call coc#pum#close_detail() + else + let words = getwinvar(s:pum_winid, 'words', []) + let word = get(words, a:index, '') + call s:insert_word(word, 0) + endif + " The current line is wrong when use feedkeys. + if !s:is_vim + doautocmd TextChangedP + endif + endif + call s:on_pum_change(1) +endfunction + +function! s:get_index(next) abort + if a:next + let index = s:pum_index + 1 == s:pum_size ? -1 : s:pum_index + 1 + else + let index = s:pum_index == -1 ? s:pum_size - 1 : s:pum_index - 1 + endif + return index +endfunction + +function! s:insert_word(word, finish) abort + if s:start_col != -1 && mode() ==# 'i' + " should not be used on finish to have correct line. + if s:is_vim && !a:finish + call coc#pum#repalce(s:start_col + 1, a:word, 1) + else + let saved_completeopt = &completeopt + noa set completeopt=menu + noa call complete(s:start_col + 1, [{ 'empty': v:true, 'word': a:word }]) + " exit complete state + if s:hide_pum + call feedkeys("\\", 'in') + else + let g:coc_disable_space_report = 1 + call feedkeys("\\", 'in') + endif + execute 'noa set completeopt='.saved_completeopt + endif + endif +endfunction + +" Replace from col to cursor col with new characters +function! coc#pum#repalce(col, insert, ...) abort + let insert = a:insert + let curr = getline('.') + let removed = strpart(curr, a:col - 1, col('.') - a:col) + let n = strchars(removed) + let start = coc#string#common_start(insert, removed) + let event = get(a:, 1, 0) + if start > 0 + let n = n - start + let insert = strcharpart(a:insert, start) + if empty(insert) && n == 0 && !event + let n = 1 + let insert = coc#string#last_character(a:insert) + endif + endif + let keys = repeat("\", n).insert + if len(keys) + if event + let previous =strpart(curr, 0, a:col - 1) + call coc#rpc#notify('PumInsert', [previous.a:insert]) + let g:coc_feeding_keys = 1 + endif + call feedkeys(keys, 'int') + endif +endfunction + +" create or update pum with lines, CompleteOption and config. +" return winid & dimension +function! coc#pum#create(lines, opt, config) abort + if mode() !=# 'i' || a:opt['line'] != line('.') + return + endif + let len = col('.') - a:opt['col'] - 1 + if len < 0 + return + endif + let input = len == 0 ? '' : strpart(getline('.'), a:opt['col'], len) + if input !=# a:opt['input'] + return + endif + let config = s:get_pum_dimension(a:lines, a:opt['col'], a:config) + if empty(config) + return + endif + let s:reversed = get(a:config, 'reverse', 0) && config['row'] < 0 + let s:virtual_text = s:virtual_text_support && a:opt['virtualText'] + let s:pum_size = len(a:lines) + let s:pum_index = a:opt['index'] + let lnum = s:index_to_lnum(s:pum_index) + call extend(config, { + \ 'lines': s:reversed ? reverse(copy(a:lines)) : a:lines, + \ 'relative': 'cursor', + \ 'nopad': 1, + \ 'cursorline': 1, + \ 'index': lnum - 1, + \ 'focusable': v:false + \ }) + call extend(config, coc#dict#pick(a:config, ['highlight', 'rounded', 'highlights', 'winblend', 'shadow', 'border', 'borderhighlight'])) + if s:reversed + for item in config['highlights'] + let item['lnum'] = s:pum_size - item['lnum'] - 1 + endfor + endif + if empty(get(config, 'winblend', 0)) && exists('&pumblend') + let config['winblend'] = &pumblend + endif + let result = coc#float#create_float_win(s:pum_winid, s:pum_bufnr, config) + if empty(result) + return + endif + let s:inserted = 0 + let s:pum_winid = result[0] + let s:pum_bufnr = result[1] + let s:start_col = a:opt['startcol'] + call setwinvar(s:pum_winid, 'above', config['row'] < 0) + let firstline = s:get_firstline(lnum, s:pum_size, config['height']) + if s:is_vim + call popup_setoptions(s:pum_winid, { 'firstline': firstline }) + else + call coc#compat#execute(s:pum_winid, 'call winrestview({"lnum":'.lnum.',"topline":'.firstline.'})') + endif + call coc#dialog#place_sign(s:pum_bufnr, s:pum_index == -1 ? 0 : lnum) + " content before col and content after cursor + let linetext = getline('.') + let parts = [strpart(linetext, 0, s:start_col), strpart(linetext, col('.') - 1)] + let input = strpart(getline('.'), s:start_col, col('.') - 1 - s:start_col) + call setwinvar(s:pum_winid, 'input', input) + call setwinvar(s:pum_winid, 'parts', parts) + call setwinvar(s:pum_winid, 'words', a:opt['words']) + call setwinvar(s:pum_winid, 'kind', 'pum') + if !s:is_vim + if s:pum_size > config['height'] + redraw + call coc#float#nvim_scrollbar(s:pum_winid) + else + call coc#float#close_related(s:pum_winid, 'scrollbar') + endif + endif + call s:on_pum_change(0) +endfunction + +function! s:save_indentkeys() abort + let bufnr = bufnr('%') + if !empty(&indentexpr) && get(s:saved_indenetkeys, 0, 0) != bufnr + let s:saved_indenetkeys = [bufnr, &indentkeys] + execute 'setl indentkeys=' + endif +endfunction + +function! s:get_firstline(lnum, total, height) abort + if a:lnum <= a:height + return 1 + endif + return min([a:total - a:height + 1, a:lnum - (a:height*2/3)]) +endfunction + +function! s:on_pum_change(move) abort + if s:virtual_text + if s:inserted + call s:clear_virtual_text() + else + call s:insert_virtual_text() + endif + endif + let ev = extend(coc#pum#info(), {'move': a:move ? v:true : v:false}) + call coc#rpc#notify('CocAutocmd', ['MenuPopupChanged', ev, win_screenpos(winnr())[0] + winline() - 2]) +endfunction + +function! s:index_to_lnum(index) abort + if s:reversed + if a:index <= 0 + return s:pum_size + endif + return s:pum_size - a:index + endif + return max([1, a:index + 1]) +endfunction + +function! s:get_pum_dimension(lines, col, config) abort + let linecount = len(a:lines) + let [lineIdx, colIdx] = coc#cursor#screen_pos() + let bh = empty(get(a:config, 'border', [])) ? 0 : 2 + let columns = &columns + let pumwidth = max([15, exists('&pumwidth') ? &pumwidth : 0]) + let width = min([columns, max([pumwidth, a:config['width']])]) + let vh = &lines - &cmdheight - 1 - !empty(&tabline) + if vh <= 0 + return v:null + endif + let pumheight = empty(&pumheight) ? vh : &pumheight + let showTop = getwinvar(s:pum_winid, 'above', v:null) + if type(showTop) != v:t_number + if vh - lineIdx - bh - 1 < min([pumheight, linecount]) && vh - lineIdx < min([10, vh/2]) + let showTop = 1 + else + let showTop = 0 + endif + endif + let height = showTop ? min([lineIdx - bh - !empty(&tabline), linecount, pumheight]) : min([vh - lineIdx - bh - 1, linecount, pumheight]) + if height <= 0 + return v:null + endif + " should use strdiplaywidth here + let text = strpart(getline('.'), a:col, col('.') - 1 - a:col) + let col = - strdisplaywidth(text, a:col) - 1 + let row = showTop ? - height : 1 + let delta = colIdx + col + if width > pumwidth && delta + width > columns + let width = max([columns - delta, pumwidth]) + endif + if delta < 0 + let col = col - delta + elseif delta + width > columns + let col = max([-colIdx, col - (delta + width - columns)]) + endif + return { + \ 'row': row, + \ 'col': col, + \ 'width': width, + \ 'height': height + \ } +endfunction + +" can't use coc#dialog#set_cursor on vim8, don't know why +function! s:set_cursor(winid, line) abort + if s:is_vim + let pos = popup_getpos(a:winid) + let core_height = pos['core_height'] + let lastline = pos['firstline'] + core_height - 1 + if a:line > lastline + call popup_setoptions(a:winid, { + \ 'firstline': pos['firstline'] + a:line - lastline, + \ }) + elseif a:line < pos['firstline'] + if s:reversed + call popup_setoptions(a:winid, { + \ 'firstline': a:line == 0 ? s:pum_size - core_height + 1 : a:line - core_height + 1, + \ }) + else + call popup_setoptions(a:winid, { + \ 'firstline': max([1, a:line]), + \ }) + endif + endif + endif + call s:select_line(a:winid, a:line) +endfunction + +function! s:select_line(winid, line) abort + let s:pum_index = s:reversed ? (a:line == 0 ? -1 : s:pum_size - a:line) : a:line - 1 + let lnum = s:reversed ? (a:line == 0 ? s:pum_size : a:line) : max([1, a:line]) + if s:is_vim + call coc#compat#execute(a:winid, 'exe '.lnum) + else + call nvim_win_set_cursor(a:winid, [lnum, 0]) + endif + call coc#dialog#place_sign(s:pum_bufnr, a:line == 0 ? 0 : lnum) +endfunction + +function! s:insert_virtual_text() abort + let bufnr = bufnr('%') + if !s:virtual_text || s:pum_index < 0 + call s:clear_virtual_text() + else + " Check if could create + let insert = '' + let line = line('.') - 1 + let words = getwinvar(s:pum_winid, 'words', []) + let word = get(words, s:pum_index, '') + let input = strpart(getline('.'), s:start_col, col('.') - 1 - s:start_col) + if strlen(word) > strlen(input) && strcharpart(word, 0, strchars(input)) ==# input + let insert = strcharpart(word, strchars(input)) + endif + if s:is_vim + if s:prop_id != 0 + call prop_remove({'id': s:prop_id}, line + 1, line + 1) + endif + if !empty(insert) + let s:prop_id = prop_add(line + 1, col('.'), { + \ 'text': insert, + \ 'type': 'CocPumVirtualText' + \ }) + endif + else + call nvim_buf_clear_namespace(bufnr, s:virtual_text_ns, line, line + 1) + if !empty(insert) + let opts = { + \ 'hl_mode': 'combine', + \ 'virt_text': [[insert, 'CocPumVirtualText']], + \ 'virt_text_pos': 'overlay', + \ 'virt_text_win_col': virtcol('.') - 1, + \ } + call nvim_buf_set_extmark(bufnr, s:virtual_text_ns, line, col('.') - 1, opts) + endif + endif + endif +endfunction + +function! s:clear_virtual_text() abort + if s:virtual_text_support + if s:is_vim + if s:prop_id != 0 + call prop_remove({'id': s:prop_id}) + endif + else + call nvim_buf_clear_namespace(bufnr('%'), s:virtual_text_ns, 0, -1) + endif + endif +endfunction + +function! s:close_pum() abort + call s:clear_virtual_text() + call coc#float#close(s:pum_winid, 1) + let s:pum_winid = 0 + let s:pum_size = 0 + let winid = coc#float#get_float_by_kind('pumdetail') + if winid + call coc#float#close(winid, 1) + endif + call s:restore_indentkeys() +endfunction + +function! s:restore_indentkeys() abort + if get(s:saved_indenetkeys, 0, 0) == bufnr('%') + call setbufvar(s:saved_indenetkeys[0], '&indentkeys', get(s:saved_indenetkeys, 1, '')) + let s:saved_indenetkeys = [] + endif +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/rpc.vim b/vim-config/plugins/coc.nvim/autoload/coc/rpc.vim index d985a561..c1db59b5 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/rpc.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/rpc.vim @@ -3,14 +3,60 @@ let s:is_win = has("win32") || has("win64") let s:client = v:null let s:name = 'coc' let s:is_vim = !has('nvim') +let s:chan_id = 0 +let s:root = expand(':h:h:h') function! coc#rpc#start_server() - if get(g:, 'coc_node_env', '') ==# 'test' - " server already started + let test = get(g:, 'coc_node_env', '') ==# 'test' + if test && !s:is_vim && !exists('$COC_NVIM_REMOTE_ADDRESS') + " server already started, chan_id could be available later let s:client = coc#client#create(s:name, []) - let s:client['running'] = 1 - let s:client['chan_id'] = get(g:, 'coc_node_channel_id', 0) - call dictwatcheradd(g:, 'coc_node_channel_id', function('s:ChannelSet')) + let s:client['running'] = s:chan_id != 0 + let s:client['chan_id'] = s:chan_id + return + endif + if exists('$COC_NVIM_REMOTE_ADDRESS') + let address = $COC_NVIM_REMOTE_ADDRESS + if s:is_vim + let s:client = coc#client#create(s:name, []) + " TODO don't know if vim support named pipe on windows. + let address = address =~# ':\d\+$' ? address : 'unix:'.address + let channel = ch_open(address, { + \ 'mode': 'json', + \ 'close_cb': {channel -> s:on_channel_close()}, + \ 'noblock': 1, + \ 'timeout': 1000, + \ }) + if ch_status(channel) == 'open' + let s:client['running'] = 1 + let s:client['channel'] = channel + endif + else + let s:client = coc#client#create(s:name, []) + try + let mode = address =~# ':\d\+$' ? 'tcp' : 'pipe' + let chan_id = sockconnect(mode, address, { 'rpc': 1 }) + if chan_id > 0 + let s:client['running'] = 1 + let s:client['chan_id'] = chan_id + endif + catch /connection\ refused/ + " ignroe + endtry + endif + if !s:client['running'] + echohl Error | echom '[coc.nvim] Unable connect to '.address.' from variable $COC_NVIM_REMOTE_ADDRESS' | echohl None + elseif !test + let logfile = exists('$NVIM_COC_LOG_FILE') ? $NVIM_COC_LOG_FILE : '' + let loglevel = exists('$NVIM_COC_LOG_LEVEL') ? $NVIM_COC_LOG_LEVEL : '' + let runtimepath = join(globpath(&runtimepath, "", 0, 1), ",") + let data = [s:root, coc#util#get_data_home(), coc#util#get_config_home(), logfile, loglevel, runtimepath] + if s:is_vim + call ch_sendraw(s:client['channel'], json_encode(data)."\n") + else + call call('rpcnotify', [s:client['chan_id'], 'init'] + data) + endif + endif return endif if empty(s:client) @@ -23,6 +69,7 @@ function! coc#rpc#start_server() if !coc#client#is_running('coc') call s:client['start']() endif + call s:check_vim_enter() endfunction function! coc#rpc#started() abort @@ -36,12 +83,18 @@ function! coc#rpc#ready() return 1 endfunction -function! s:ChannelSet(dict, key, val) - let chan_id = get(a:val, 'new', 0) - if empty(s:client) | return | endif - let s:client['running'] = 1 - let s:client['chan_id'] = chan_id - call dictwatcherdel(g:, 'coc_node_channel_id', function('s:ChannelSet')) +" Used for test on neovim only +function! coc#rpc#set_channel(chan_id) abort + let s:chan_id = a:chan_id + let s:client['running'] = a:chan_id != 0 + let s:client['chan_id'] = a:chan_id +endfunction + +function! coc#rpc#get_channel() abort + if empty(s:client) + return v:null + endif + return coc#client#get_channel(s:client) endfunction function! coc#rpc#kill() @@ -54,8 +107,16 @@ function! coc#rpc#kill() endif endfunction -function! coc#rpc#get_errors() - return split(execute('messages'), "\n") +function! coc#rpc#show_errors() + let client = coc#client#get_client('coc') + if !empty(client) + let lines = get(client, 'stderr', []) + keepalt new +setlocal\ buftype=nofile [Stderr of coc.nvim] + setl noswapfile wrap bufhidden=wipe nobuflisted nospell + call append(0, lines) + exe "normal! z" . len(lines) . "\" + exe "normal! gg" + endif endfunction function! coc#rpc#stop() @@ -77,15 +138,44 @@ function! coc#rpc#restart() if empty(s:client) call coc#rpc#start_server() else + call coc#highlight#clear_all() + call coc#ui#sign_unplace() call coc#float#close_all() + autocmd! coc_dynamic_autocmd + autocmd! coc_dynamic_content + autocmd! coc_dynamic_option call coc#rpc#request('detach', []) + let g:coc_service_initialized = 0 sleep 100m - let s:client['command'] = coc#util#job_command() - call coc#client#restart(s:name) + if exists('$COC_NVIM_REMOTE_ADDRESS') + call coc#rpc#close_connection() + sleep 100m + call coc#rpc#start_server() + else + let s:client['command'] = coc#util#job_command() + call coc#client#restart(s:name) + call s:check_vim_enter() + endif echohl MoreMsg | echom 'starting coc.nvim service' | echohl None endif endfunction +function! coc#rpc#close_connection() abort + let channel = coc#rpc#get_channel() + if channel == v:null + return + endif + if s:is_vim + " Unlike neovim, vim not close the socket as expected. + call ch_close(channel) + else + call chanclose(channel) + endif + let s:client['running'] = 0 + let s:client['channel'] = v:null + let s:client['chan_id'] = 0 +endfunction + function! coc#rpc#request(method, args) abort if !coc#rpc#ready() return '' @@ -126,3 +216,21 @@ function! coc#rpc#async_request(id, method, args) call coc#rpc#notify('nvim_async_response_event', [a:id, v:exception, v:null]) endtry endfunction + +function! s:check_vim_enter() abort + if s:client['running'] && v:vim_did_enter + call coc#rpc#notify('VimEnter', [coc#util#path_replace_patterns(), join(globpath(&runtimepath, "", 0, 1), ",")]) + endif +endfunction + +" Used on vim and remote address only +function! s:on_channel_close() abort + if get(g:, 'coc_node_env', '') !=# 'test' + echohl Error | echom '[coc.nvim] channel closed' | echohl None + endif + if !empty(s:client) + let s:client['running'] = 0 + let s:client['channel'] = v:null + let s:client['async_req_id'] = 1 + endif +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/snippet.vim b/vim-config/plugins/coc.nvim/autoload/coc/snippet.vim index bb63637e..d9375b21 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/snippet.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/snippet.vim @@ -1,6 +1,8 @@ scriptencoding utf-8 let s:is_vim = !has('nvim') let s:map_next = 1 +let s:map_prev = 1 +let s:cmd_mapping = has('nvim') || has('patch-8.2.1978') function! coc#snippet#_select_mappings() if !get(g:, 'coc_selectmode_mapping', 1) @@ -25,32 +27,66 @@ function! coc#snippet#_select_mappings() snoremap "_c endfunction -function! coc#snippet#show_choices(lnum, col, len, values) abort - let m = mode() - call cursor(a:lnum, a:col + a:len) - if m !=# 'i' | startinsert | endif - call timer_start(20, { -> coc#_do_complete(a:col - 1, a:values, 0)}) +function! coc#snippet#show_choices(lnum, col, position, input) abort + call coc#snippet#move(a:position) + call CocActionAsync('startCompletion', { 'source': '$words' }) redraw endfunction -function! coc#snippet#enable() +function! coc#snippet#enable(...) if get(b:, 'coc_snippet_active', 0) == 1 return endif + let complete = get(a:, 1, 0) let b:coc_snippet_active = 1 - silent! unlet g:coc_selected_text call coc#snippet#_select_mappings() let nextkey = get(g:, 'coc_snippet_next', '') let prevkey = get(g:, 'coc_snippet_prev', '') - if maparg(nextkey, 'i') =~# 'expand-jump' + if maparg(nextkey, 'i') =~# 'snippet' let s:map_next = 0 endif - if s:map_next - execute 'inoremap '.nextkey." =coc#rpc#request('snippetNext', [])" + if maparg(prevkey, 'i') =~# 'snippet' + let s:map_prev = 0 + endif + if !empty(nextkey) + if s:map_next + execute 'inoremap '.nextkey." =coc#snippet#jump(1, ".complete.")" + endif + execute 'snoremap '.nextkey." :call coc#snippet#jump(1, ".complete.")" + endif + if !empty(prevkey) + if s:map_prev + execute 'inoremap '.prevkey." =coc#snippet#jump(0, ".complete.")" + endif + execute 'snoremap '.prevkey." :call coc#snippet#jump(0, ".complete.")" endif - execute 'inoremap '.prevkey." =coc#rpc#request('snippetPrev', [])" - execute 'snoremap '.prevkey." :call coc#rpc#request('snippetPrev', [])" - execute 'snoremap '.nextkey." :call coc#rpc#request('snippetNext', [])" +endfunction + +function! coc#snippet#prev() abort + call coc#rpc#request('snippetPrev', []) + return '' +endfunction + +function! coc#snippet#next() abort + call coc#rpc#request('snippetNext', []) + return '' +endfunction + +function! coc#snippet#jump(direction, complete) abort + if a:direction == 1 && a:complete + if pumvisible() + let pre = exists('*complete_info') && complete_info()['selected'] == -1 ? "\" : '' + call feedkeys(pre."\", 'in') + return '' + endif + if coc#pum#visible() + " Discard the return value, otherwise weird characters will be inserted + call coc#pum#confirm() + return '' + endif + endif + call coc#rpc#request(a:direction == 1 ? 'snippetNext' : 'snippetPrev', []) + return '' endfunction function! coc#snippet#disable() @@ -63,7 +99,57 @@ function! coc#snippet#disable() if s:map_next silent! execute 'iunmap '.nextkey endif - silent! execute 'iunmap '.prevkey + if s:map_prev + silent! execute 'iunmap '.prevkey + endif silent! execute 'sunmap '.prevkey silent! execute 'sunmap '.nextkey endfunction + +function! coc#snippet#select(start, end, text) abort + if coc#pum#visible() + call coc#pum#close() + endif + if mode() == 's' + call feedkeys("\", 'in') + endif + if &selection ==# 'exclusive' + let cursor = coc#snippet#to_cursor(a:start) + call cursor([cursor[0], cursor[1]]) + let cmd = '' + let cmd .= mode()[0] ==# 'i' ? "\".(col('.') == 1 ? '' : 'l') : '' + let cmd .= printf('v%s', strchars(a:text) . 'l') + let cmd .= "\" + else + let cursor = coc#snippet#to_cursor(a:end) + call cursor([cursor[0], cursor[1] - 1]) + let len = strchars(a:text) - 1 + let cmd = '' + let cmd .= mode()[0] ==# 'i' ? "\l" : '' + let cmd .= printf('v%s', len > 0 ? len . 'h' : '') + let cmd .= "o\" + endif + call feedkeys(cmd, 'n') +endfunction + +function! coc#snippet#move(position) abort + let m = mode() + if m == 's' + call feedkeys("\", 'in') + endif + let pos = coc#snippet#to_cursor(a:position) + call cursor(pos) + if pos[1] > strlen(getline(pos[0])) + startinsert! + else + startinsert + endif +endfunction + +function! coc#snippet#to_cursor(position) abort + let line = getline(a:position.line + 1) + if line is v:null + return [a:position.line + 1, a:position.character + 1] + endif + return [a:position.line + 1, coc#string#byte_index(line, a:position.character) + 1] +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/string.vim b/vim-config/plugins/coc.nvim/autoload/coc/string.vim new file mode 100644 index 00000000..efe77e19 --- /dev/null +++ b/vim-config/plugins/coc.nvim/autoload/coc/string.vim @@ -0,0 +1,210 @@ +scriptencoding utf-8 + +function! coc#string#last_character(line) abort + return strcharpart(a:line, strchars(a:line) - 1, 1) +endfunction + +" Get utf16 code unit index from col (0 based) +function! coc#string#character_index(line, byteIdx) abort + if a:byteIdx <= 0 + return 0 + endif + let i = 0 + for char in split(strpart(a:line, 0, a:byteIdx), '\zs') + let i += char2nr(char) > 65535 ? 2 : 1 + endfor + return i +endfunction + +function! coc#string#common_start(text, other) abort + let arr = split(a:text, '\zs') + let other = split(a:other, '\zs') + let total = min([len(arr), len(other)]) + if total == 0 + return 0 + endif + for i in range(0, total - 1) + if arr[i] !=# other[i] + return i + endif + endfor + return total +endfunction + +" Convert utf16 character index to byte index +function! coc#string#byte_index(line, character) abort + if a:character <= 0 + return 0 + endif + " code unit index + let i = 0 + let len = 0 + for char in split(a:line, '\zs') + let i += char2nr(char) > 65535 ? 2 : 1 + let len += strlen(char) + if i >= a:character + break + endif + endfor + return len +endfunction + +" Get character count from start col and end col, 1 based +function! coc#string#get_char_count(text, start_col, end_col) abort + return strchars(strpart(a:text, a:start_col - 1, a:end_col - a:start_col)) +endfunction + +function! coc#string#character_length(text) abort + let i = 0 + for char in split(a:text, '\zs') + let i += char2nr(char) > 65535 ? 2 : 1 + endfor + return i +endfunction + +function! coc#string#reflow(lines, width) abort + let lines = [] + let currlen = 0 + let parts = [] + for line in a:lines + for part in split(line, '\s\+') + let w = strwidth(part) + if currlen + w + 1 >= a:width + if len(parts) > 0 + call add(lines, join(parts, ' ')) + endif + if w >= a:width + call add(lines, part) + let currlen = 0 + let parts = [] + else + let currlen = w + let parts = [part] + endif + continue + endif + call add(parts, part) + let currlen = currlen + w + 1 + endfor + endfor + if len(parts) > 0 + call add(lines, join(parts, ' ')) + endif + return empty(lines) ? [''] : lines +endfunction + +" Used when 'wrap' and 'linebreak' is enabled +function! coc#string#content_height(lines, width) abort + let len = 0 + let pattern = empty(&breakat) ? '.\zs' : '['.substitute(&breakat, '\([\[\]]\)', '\\\1', 'g').']\zs' + for line in a:lines + if strwidth(line) <= a:width + let len += 1 + else + let currlen = 0 + for part in split(line, pattern) + let wl = strwidth(part) + if currlen == 0 && wl > 0 + let len += 1 + endif + let delta = currlen + wl - a:width + if delta >= 0 + let len = len + (delta > 0) + let currlen = delta == 0 ? 0 : wl + if wl >= a:width + let currlen = wl%a:width + let len += float2nr(ceil(wl/(a:width + 0.0))) - (currlen == 0) + endif + else + let currlen = currlen + wl + endif + endfor + endif + endfor + return len +endfunction + +" get change between two lines +function! coc#string#diff(curr, previous, col) abort + let end = strpart(a:curr, a:col - 1) + let start = strpart(a:curr, 0, a:col -1) + let endOffset = 0 + let startOffset = 0 + let currLen = strchars(a:curr) + let prevLen = strchars(a:previous) + if len(end) + let endLen = strchars(end) + for i in range(min([prevLen, endLen])) + if strcharpart(end, endLen - 1 - i, 1) ==# strcharpart(a:previous, prevLen -1 -i, 1) + let endOffset = endOffset + 1 + else + break + endif + endfor + endif + let remain = endOffset == 0 ? a:previous : strcharpart(a:previous, 0, prevLen - endOffset) + if len(remain) + for i in range(min([strchars(remain), strchars(start)])) + if strcharpart(remain, i, 1) ==# strcharpart(start, i ,1) + let startOffset = startOffset + 1 + else + break + endif + endfor + endif + return { + \ 'start': startOffset, + \ 'end': prevLen - endOffset, + \ 'text': strcharpart(a:curr, startOffset, currLen - startOffset - endOffset) + \ } +endfunction + +function! coc#string#apply(content, diff) abort + let totalLen = strchars(a:content) + let endLen = totalLen - a:diff['end'] + return strcharpart(a:content, 0, a:diff['start']).a:diff['text'].strcharpart(a:content, a:diff['end'], endLen) +endfunction + +" insert inserted to line at position, use ... when result is too long +" line should only contains character has strwidth equals 1 +function! coc#string#compose(line, position, inserted) abort + let width = strwidth(a:line) + let text = a:inserted + let res = a:line + let need_truncate = a:position + strwidth(text) + 1 > width + if need_truncate + let remain = width - a:position - 3 + if remain < 2 + " use text for full line, use first & end of a:line, ignore position + let res = strcharpart(a:line, 0, 1) + let w = strwidth(res) + for i in range(strchars(text)) + let c = strcharpart(text, i, 1) + let a = strwidth(c) + if w + a <= width - 1 + let w = w + a + let res = res . c + endif + endfor + let res = res.strcharpart(a:line, w) + else + let res = strcharpart(a:line, 0, a:position) + let w = strwidth(res) + for i in range(strchars(text)) + let c = strcharpart(text, i, 1) + let a = strwidth(c) + if w + a <= width - 3 + let w = w + a + let res = res . c + endif + endfor + let res = res.'..' + let w = w + 2 + let res = res . strcharpart(a:line, w) + endif + else + let first = strcharpart(a:line, 0, a:position) + let res = first . text . strcharpart(a:line, a:position + strwidth(text)) + endif + return res +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/task.vim b/vim-config/plugins/coc.nvim/autoload/coc/task.vim index d5b6e1e2..80ff02fe 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/task.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/task.vim @@ -1,7 +1,7 @@ " ============================================================================ " Description: Manage long running tasks. " Author: Qiming Zhao -" Licence: MIT licence +" Licence: Anti 966 licence " Version: 0.1 " Last Modified: Dec 12, 2020 " ============================================================================ diff --git a/vim-config/plugins/coc.nvim/autoload/coc/terminal.vim b/vim-config/plugins/coc.nvim/autoload/coc/terminal.vim index 87423ef4..b0dbe6d4 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/terminal.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/terminal.vim @@ -4,12 +4,12 @@ let s:channel_map = {} let s:is_win = has('win32') || has('win64') " start terminal, return [bufnr, pid] -function! coc#terminal#start(cmd, cwd, env) abort +function! coc#terminal#start(cmd, cwd, env, strict) abort if s:is_vim && !has('terminal') throw 'terminal feature not supported by current vim.' endif let cwd = empty(a:cwd) ? getcwd() : a:cwd - execute 'belowright 8new +setl\ buftype=nofile' + execute 'belowright '.get(g:, 'coc_terminal_height', 8).'new +setl\ buftype=nofile' setl winfixheight setl norelativenumber setl nonumber @@ -33,6 +33,7 @@ function! coc#terminal#start(cmd, cwd, env) abort endif function! s:OnExit(status) closure + call coc#rpc#notify('CocAutocmd', ['TermExit', bufnr, a:status]) if a:status == 0 execute 'silent! bd! '.bufnr endif @@ -41,9 +42,10 @@ function! coc#terminal#start(cmd, cwd, env) abort if has('nvim') let job_id = termopen(a:cmd, { \ 'cwd': cwd, - \ 'pty': 1, + \ 'pty': v:true, \ 'on_exit': {job, status -> s:OnExit(status)}, \ 'env': env, + \ 'clear_env': a:strict ? v:true : v:false \ }) if !empty(original) && exists('*setenv') for key in keys(original) @@ -89,11 +91,9 @@ function! coc#terminal#send(bufnr, text, add_new_line) abort endif endif call chansend(chan, lines) - let winnr = bufwinnr(a:bufnr) - if winnr != -1 - exe 'noa '.winnr.'wincmd w' - exe 'noa normal! G' - exe 'noa '.wincmd p + let winid = bufwinid(a:bufnr) + if winid != -1 + call coc#compat#execute(winid, 'noa normal! G') endif else if !a:add_new_line diff --git a/vim-config/plugins/coc.nvim/autoload/coc/ui.vim b/vim-config/plugins/coc.nvim/autoload/coc/ui.vim new file mode 100644 index 00000000..ff45e0b4 --- /dev/null +++ b/vim-config/plugins/coc.nvim/autoload/coc/ui.vim @@ -0,0 +1,567 @@ +let s:is_vim = !has('nvim') +let s:is_win = has('win32') || has('win64') +let s:is_mac = has('mac') +let s:sign_api = exists('*sign_getplaced') && exists('*sign_place') +let s:sign_groups = [] +let s:outline_preview_bufnr = 0 + +" Check and +function! coc#ui#check_pum_keymappings(trigger) abort + if a:trigger !=# 'none' + for key in ['', '', '', ''] + let arg = maparg(key, 'i', 0, 1) + if get(arg, 'expr', 0) + let rhs = get(arg, 'rhs', '') + if rhs =~# '\"', 'coc#pum#next(1)', '') + let rhs = substitute(rhs, '\c"\\"', 'coc#pum#prev(1)', '') + let rhs = substitute(rhs, '\c"\\"', 'coc#pum#confirm()', '') + execute 'inoremap '.arg['lhs'].' '.rhs + endif + endif + endfor + endif +endfunction + +function! coc#ui#quickpick(title, items, cb) abort + if exists('*popup_menu') + function! s:QuickpickHandler(id, result) closure + call a:cb(v:null, a:result) + endfunction + function! s:QuickpickFilter(id, key) closure + for i in range(1, len(a:items)) + if a:key == string(i) + call popup_close(a:id, i) + return 1 + endif + endfor + " No shortcut, pass to generic filter + return popup_filter_menu(a:id, a:key) + endfunction + try + call popup_menu(a:items, { + \ 'title': a:title, + \ 'filter': function('s:QuickpickFilter'), + \ 'callback': function('s:QuickpickHandler'), + \ }) + redraw + catch /.*/ + call a:cb(v:exception) + endtry + else + let res = inputlist([a:title] + a:items) + call a:cb(v:null, res) + endif +endfunction + +" cmd, cwd +function! coc#ui#open_terminal(opts) abort + if s:is_vim && !exists('*term_start') + echohl WarningMsg | echon "Your vim doesn't have terminal support!" | echohl None + return + endif + if get(a:opts, 'position', 'bottom') ==# 'bottom' + let p = '5new' + else + let p = 'vnew' + endif + execute 'belowright '.p.' +setl\ buftype=nofile ' + setl buftype=nofile + setl winfixheight + setl norelativenumber + setl nonumber + setl bufhidden=wipe + if exists('#User#CocTerminalOpen') + exe 'doautocmd User CocTerminalOpen' + endif + let cmd = get(a:opts, 'cmd', '') + let autoclose = get(a:opts, 'autoclose', 1) + if empty(cmd) + throw 'command required!' + endif + let cwd = get(a:opts, 'cwd', getcwd()) + let keepfocus = get(a:opts, 'keepfocus', 0) + let bufnr = bufnr('%') + let Callback = get(a:opts, 'Callback', v:null) + + function! s:OnExit(status) closure + let content = join(getbufline(bufnr, 1, '$'), "\n") + if a:status == 0 && autoclose == 1 + execute 'silent! bd! '.bufnr + endif + if !empty(Callback) + call call(Callback, [a:status, bufnr, content]) + endif + endfunction + + if has('nvim') + call termopen(cmd, { + \ 'cwd': cwd, + \ 'on_exit': {job, status -> s:OnExit(status)}, + \}) + else + if s:is_win + let cmd = 'cmd.exe /C "'.cmd.'"' + endif + call term_start(cmd, { + \ 'cwd': cwd, + \ 'exit_cb': {job, status -> s:OnExit(status)}, + \ 'curwin': 1, + \}) + endif + if keepfocus + wincmd p + endif + return bufnr +endfunction + +" run command in terminal +function! coc#ui#run_terminal(opts, cb) + let cmd = get(a:opts, 'cmd', '') + if empty(cmd) + return a:cb('command required for terminal') + endif + let opts = { + \ 'cmd': cmd, + \ 'cwd': get(a:opts, 'cwd', getcwd()), + \ 'keepfocus': get(a:opts, 'keepfocus', 0), + \ 'Callback': {status, bufnr, content -> a:cb(v:null, {'success': status == 0 ? v:true : v:false, 'bufnr': bufnr, 'content': content})} + \} + call coc#ui#open_terminal(opts) +endfunction + +function! coc#ui#echo_hover(msg) + echohl MoreMsg + echo a:msg + echohl None + let g:coc_last_hover_message = a:msg +endfunction + +function! coc#ui#echo_messages(hl, msgs) + if a:hl !~# 'Error' && (mode() !~# '\v^(i|n)$') + return + endif + let msgs = filter(copy(a:msgs), '!empty(v:val)') + if empty(msgs) + return + endif + execute 'echohl '.a:hl + echo join(msgs, "\n") + echohl None +endfunction + +function! coc#ui#preview_info(lines, filetype, ...) abort + pclose + keepalt new +setlocal\ previewwindow|setlocal\ buftype=nofile|setlocal\ noswapfile|setlocal\ wrap [Document] + setl bufhidden=wipe + setl nobuflisted + setl nospell + exe 'setl filetype='.a:filetype + setl conceallevel=0 + setl nofoldenable + for command in a:000 + execute command + endfor + call append(0, a:lines) + exe "normal! z" . len(a:lines) . "\" + exe "normal! gg" + wincmd p +endfunction + +function! coc#ui#open_files(files) + let bufnrs = [] + " added on latest vim8 + if exists('*bufadd') && exists('*bufload') + for file in a:files + let file = fnamemodify(file, ':.') + if bufloaded(file) + call add(bufnrs, bufnr(file)) + else + let bufnr = bufadd(file) + call bufload(file) + call add(bufnrs, bufnr) + call setbufvar(bufnr, '&buflisted', 1) + endif + endfor + else + noa keepalt 1new +setl\ bufhidden=wipe + for file in a:files + let file = fnamemodify(file, ':.') + execute 'noa edit +setl\ bufhidden=hide '.fnameescape(file) + if &filetype ==# '' + filetype detect + endif + call add(bufnrs, bufnr('%')) + endfor + noa close + endif + doautocmd BufEnter + return bufnrs +endfunction + +function! coc#ui#echo_lines(lines) + echo join(a:lines, "\n") +endfunction + +function! coc#ui#echo_signatures(signatures) abort + if pumvisible() | return | endif + echo "" + for i in range(len(a:signatures)) + call s:echo_signature(a:signatures[i]) + if i != len(a:signatures) - 1 + echon "\n" + endif + endfor +endfunction + +function! s:echo_signature(parts) + for part in a:parts + let hl = get(part, 'type', 'Normal') + let text = get(part, 'text', '') + if !empty(text) + execute 'echohl '.hl + execute "echon '".substitute(text, "'", "''", 'g')."'" + echohl None + endif + endfor +endfunction + +function! coc#ui#iterm_open(dir) + return s:osascript( + \ 'if application "iTerm2" is not running', + \ 'error', + \ 'end if') && s:osascript( + \ 'tell application "iTerm2"', + \ 'tell current window', + \ 'create tab with default profile', + \ 'tell current session', + \ 'write text "cd ' . a:dir . '"', + \ 'write text "clear"', + \ 'activate', + \ 'end tell', + \ 'end tell', + \ 'end tell') +endfunction + +function! s:osascript(...) abort + let args = join(map(copy(a:000), '" -e ".shellescape(v:val)'), '') + call s:system('osascript'. args) + return !v:shell_error +endfunction + +function! s:system(cmd) + let output = system(a:cmd) + if v:shell_error && output !=# "" + echohl Error | echom output | echohl None + return + endif + return output +endfunction + +function! coc#ui#set_lines(bufnr, changedtick, original, replacement, start, end, changes, cursor, col) abort + if !bufloaded(a:bufnr) + return + endif + let delta = 0 + if !empty(a:col) + let delta = col('.') - a:col + endif + if getbufvar(a:bufnr, 'changedtick') > a:changedtick && bufnr('%') == a:bufnr + " try apply current line change + let lnum = line('.') + " change for current line + if a:end - a:start == 1 && a:end == lnum && len(a:replacement) == 1 + let idx = a:start - lnum + 1 + let previous = get(a:original, idx, 0) + if type(previous) == 1 + let content = getline('.') + if previous !=# content + let diff = coc#string#diff(content, previous, col('.')) + let changed = get(a:replacement, idx, 0) + if type(changed) == 1 && strcharpart(previous, 0, diff['end']) ==# strcharpart(changed, 0, diff['end']) + let applied = coc#string#apply(changed, diff) + let replacement = copy(a:replacement) + let replacement[idx] = applied + call coc#compat#buf_set_lines(a:bufnr, a:start, a:end, replacement) + return + endif + endif + endif + endif + endif + if exists('*nvim_buf_set_text') && !empty(a:changes) + for item in reverse(copy(a:changes)) + call nvim_buf_set_text(a:bufnr, item[1], item[2], item[3], item[4], item[0]) + endfor + else + call coc#compat#buf_set_lines(a:bufnr, a:start, a:end, a:replacement) + endif + if !empty(a:cursor) + call cursor(a:cursor[0], a:cursor[1] + delta) + endif +endfunction + +function! coc#ui#change_lines(bufnr, list) abort + if !bufloaded(a:bufnr) | return v:null | endif + undojoin + if exists('*setbufline') + for [lnum, line] in a:list + call setbufline(a:bufnr, lnum + 1, line) + endfor + elseif a:bufnr == bufnr('%') + for [lnum, line] in a:list + call setline(lnum + 1, line) + endfor + else + let bufnr = bufnr('%') + exe 'noa buffer '.a:bufnr + for [lnum, line] in a:list + call setline(lnum + 1, line) + endfor + exe 'noa buffer '.bufnr + endif +endfunction + +function! coc#ui#open_url(url) + if isdirectory(a:url) && $TERM_PROGRAM ==# "iTerm.app" + call coc#ui#iterm_open(a:url) + return + endif + if !empty(get(g:, 'coc_open_url_command', '')) + call system(g:coc_open_url_command.' '.a:url) + return + endif + if has('mac') && executable('open') + call system('open '.a:url) + return + endif + if executable('xdg-open') + call system('xdg-open '.a:url) + return + endif + call system('cmd /c start "" /b '. substitute(a:url, '&', '^&', 'g')) + if v:shell_error + echohl Error | echom 'Failed to open '.a:url | echohl None + return + endif +endfunction + +function! coc#ui#rename_file(oldPath, newPath, write) abort + let bufnr = bufnr(a:oldPath) + if bufnr == -1 + throw 'Unable to get bufnr of '.a:oldPath + endif + if a:oldPath =~? a:newPath && (s:is_mac || s:is_win) + return coc#ui#safe_rename(bufnr, a:oldPath, a:newPath, a:write) + endif + if bufloaded(a:newPath) + execute 'silent bdelete! '.bufnr(a:newPath) + endif + let current = bufnr == bufnr('%') + let bufname = fnamemodify(a:newPath, ":~:.") + let filepath = fnamemodify(bufname(bufnr), '%:p') + let winid = coc#compat#buf_win_id(bufnr) + let curr = -1 + if winid == -1 + let curr = win_getid() + let file = fnamemodify(bufname(bufnr), ':.') + execute 'keepalt tab drop '.fnameescape(bufname(bufnr)) + let winid = win_getid() + endif + call coc#compat#execute(winid, 'keepalt file '.fnameescape(bufname), 'silent') + call coc#compat#execute(winid, 'doautocmd BufEnter') + if a:write + call coc#compat#execute(winid, 'noa write!', 'silent') + call delete(filepath, '') + endif + if curr != -1 + call win_gotoid(curr) + endif + return bufnr +endfunction + +" System is case in sensitive and newPath have different case. +function! coc#ui#safe_rename(bufnr, oldPath, newPath, write) abort + let winid = win_getid() + let lines = getbufline(a:bufnr, 1, '$') + execute 'keepalt tab drop '.fnameescape(fnamemodify(a:oldPath, ':.')) + let view = winsaveview() + execute 'keepalt bwipeout! '.a:bufnr + if a:write + call delete(a:oldPath, '') + endif + execute 'keepalt edit '.fnameescape(fnamemodify(a:newPath, ':~:.')) + let bufnr = bufnr('%') + call coc#compat#buf_set_lines(bufnr, 0, -1, lines) + if a:write + execute 'noa write' + endif + call winrestview(view) + call win_gotoid(winid) + return bufnr +endfunction + +function! coc#ui#sign_unplace() abort + if exists('*sign_unplace') + for group in s:sign_groups + call sign_unplace(group) + endfor + endif +endfunction + +function! coc#ui#update_signs(bufnr, group, signs) abort + if !s:sign_api || !bufloaded(a:bufnr) + return + endif + call sign_unplace(a:group, {'buffer': a:bufnr}) + for def in a:signs + let opts = {'lnum': def['lnum']} + if has_key(def, 'priority') + let opts['priority'] = def['priority'] + endif + call sign_place(0, a:group, def['name'], a:bufnr, opts) + endfor +endfunction + +function! coc#ui#outline_preview(config) abort + let view_id = get(w:, 'cocViewId', '') + if view_id !=# 'OUTLINE' + return + endif + let wininfo = get(getwininfo(win_getid()), 0, v:null) + if empty(wininfo) + return + endif + let border = get(a:config, 'border', v:true) + let th = &lines - &cmdheight - 2 + let range = a:config['range'] + let height = min([range['end']['line'] - range['start']['line'] + 1, th - 4]) + let to_left = &columns - wininfo['wincol'] - wininfo['width'] < wininfo['wincol'] + let start_lnum = range['start']['line'] + 1 + let end_lnum = range['end']['line'] + 1 - start_lnum > &lines ? start_lnum + &lines : range['end']['line'] + 1 + let lines = getbufline(a:config['bufnr'], start_lnum, end_lnum) + let content_width = max(map(copy(lines), 'strdisplaywidth(v:val)')) + let width = min([content_width, a:config['maxWidth'], to_left ? wininfo['wincol'] - 3 : &columns - wininfo['wincol'] - wininfo['width']]) + let filetype = getbufvar(a:config['bufnr'], '&filetype') + let cursor_row = coc#cursor#screen_pos()[0] + let config = { + \ 'relative': 'editor', + \ 'row': cursor_row - 1 + height < th ? cursor_row - (border ? 1 : 0) : th - height - (border ? 1 : -1), + \ 'col': to_left ? wininfo['wincol'] - 4 - width : wininfo['wincol'] + wininfo['width'], + \ 'width': width, + \ 'height': height, + \ 'lines': lines, + \ 'border': border ? [1,1,1,1] : v:null, + \ 'rounded': get(a:config, 'rounded', 1) ? 1 : 0, + \ 'winblend': a:config['winblend'], + \ 'highlight': a:config['highlight'], + \ 'borderhighlight': a:config['borderhighlight'], + \ } + let winid = coc#float#get_float_by_kind('outline-preview') + let result = coc#float#create_float_win(winid, s:outline_preview_bufnr, config) + if empty(result) + return v:null + endif + call setwinvar(result[0], 'kind', 'outline-preview') + let s:outline_preview_bufnr = result[1] + if !empty(filetype) + call coc#compat#execute(result[0], 'setfiletype '.filetype) + endif + return result[1] +endfunction + +function! coc#ui#outline_close_preview() abort + let winid = coc#float#get_float_by_kind('outline-preview') + if winid + call coc#float#close(winid) + endif +endfunction + +" Ignore error from autocmd when file opened +function! coc#ui#safe_open(cmd, file) abort + let bufname = fnameescape(a:file) + try + execute a:cmd.' 'bufname + catch /.*/ + if bufname('%') != bufname + throw v:exception + endif + endtry +endfunction + +" Use noa to setloclist, avoid BufWinEnter autocmd +function! coc#ui#setloclist(nr, items, action, title) abort + if a:action ==# ' ' + let title = get(getloclist(a:nr, {'title': 1}), 'title', '') + let action = title ==# a:title ? 'r' : ' ' + noa call setloclist(a:nr, [], action, {'title': a:title, 'items': a:items}) + else + noa call setloclist(a:nr, [], a:action, {'title': a:title, 'items': a:items}) + endif +endfunction + +function! coc#ui#get_mouse() abort + if get(g:, 'coc_node_env', '') ==# 'test' + return get(g:, 'mouse_position', [win_getid(), line('.'), col('.')]) + endif + return [v:mouse_winid,v:mouse_lnum,v:mouse_col] +endfunction + +" viewId - identifier of tree view +" bufnr - bufnr tree view +" winid - winid of tree view +" bufname - bufname of tree view +" command - split command +" optional options - bufhidden, canSelectMany, winfixwidth +function! coc#ui#create_tree(opts) abort + let viewId = a:opts['viewId'] + let bufname = a:opts['bufname'] + let tabid = coc#util#tabnr_id(tabpagenr()) + let winid = s:get_tree_winid(a:opts) + let bufnr = a:opts['bufnr'] + if !bufloaded(bufnr) + let bufnr = -1 + endif + if winid != -1 + call win_gotoid(winid) + if bufnr('%') == bufnr + return [bufnr, winid, tabid] + elseif bufnr != -1 + execute 'silent keepalt buffer '.bufnr + else + execute 'silent keepalt edit +setl\ buftype=nofile '.bufname + call s:set_tree_defaults(a:opts) + endif + else + " need to split + let cmd = get(a:opts, 'command', 'belowright 30vs') + execute 'silent keepalt '.cmd.' +setl\ buftype=nofile '.bufname + call s:set_tree_defaults(a:opts) + let winid = win_getid() + endif + let w:cocViewId = viewId + return [winbufnr(winid), winid, tabid] +endfunction + +" valid window id or -1 +function! s:get_tree_winid(opts) abort + let viewId = a:opts['viewId'] + let winid = a:opts['winid'] + if winid != -1 && coc#window#visible(winid) + return winid + endif + if winid != -1 + call coc#compat#execute(winid, 'noa close!', 'silent!') + endif + return coc#window#find('cocViewId', viewId) +endfunction + +function! s:set_tree_defaults(opts) abort + let bufhidden = get(a:opts, 'bufhidden', 'wipe') + let signcolumn = get(a:opts, 'canSelectMany', v:false) ? 'yes' : 'no' + let winfixwidth = get(a:opts, 'winfixwidth', v:false) ? ' winfixwidth' : '' + execute 'setl bufhidden='.bufhidden.' signcolumn='.signcolumn.winfixwidth + setl nolist nonumber norelativenumber foldcolumn=0 + setl nocursorline nobuflisted wrap undolevels=-1 filetype=coctree nomodifiable noswapfile +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/util.vim b/vim-config/plugins/coc.nvim/autoload/coc/util.vim index f885b1ec..72648f55 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/util.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/util.vim @@ -2,39 +2,64 @@ scriptencoding utf-8 let s:root = expand(':h:h:h') let s:is_win = has('win32') || has('win64') let s:is_vim = !has('nvim') -let s:clear_match_by_id = has('nvim-0.5.0') || has('patch-8.1.1084') -let s:vim_api_version = 10 -let s:activate = "" -let s:quit = "" - -if has("gui_macvim") && has('gui_running') - let s:app = "MacVim" -elseif $TERM_PROGRAM ==# "Apple_Terminal" - let s:app = "Terminal" -elseif $TERM_PROGRAM ==# "iTerm.app" - let s:app = "iTerm2" -elseif has('mac') - let s:app = "System Events" - let s:quit = "quit" - let s:activate = 'activate' -endif +let s:vim_api_version = 34 + +function! coc#util#remote_fns(name) + let fns = ['init', 'complete', 'should_complete', 'refresh', 'get_startcol', 'on_complete', 'on_enter'] + let res = [] + for fn in fns + if exists('*coc#source#'.a:name.'#'.fn) + call add(res, fn) + endif + endfor + return res +endfunction + +function! coc#util#merge_winhl(curr, hls) abort + let highlightMap = {} + for parts in map(split(a:curr, ','), 'split(v:val, ":")') + if len(parts) == 2 + let highlightMap[parts[0]] = parts[1] + endif + endfor + for item in a:hls + let highlightMap[item[0]] = item[1] + endfor + return join(map(items(highlightMap), 'v:val[0].":".v:val[1]'), ',') +endfunction + +function! coc#util#do_complete(name, opt, cb) abort + let handler = 'coc#source#'.a:name.'#complete' + let l:Cb = {res -> a:cb(v:null, res)} + let args = [a:opt, l:Cb] + call call(handler, args) +endfunction + +function! coc#util#suggest_variables(bufnr) abort + return { + \ 'disable': getbufvar(a:bufnr, 'coc_suggest_disable', 0), + \ 'disabled_sources': getbufvar(a:bufnr, 'coc_disabled_sources', []), + \ 'blacklist': getbufvar(a:bufnr, 'coc_suggest_blacklist', []), + \ } +endfunction function! coc#util#api_version() abort return s:vim_api_version endfunction +function! coc#util#semantic_hlgroups() abort + let res = split(execute('hi'), "\n") + let filtered = filter(res, "v:val =~# '^CocSem' && v:val !~# ' cleared$'") + return map(filtered, "matchstr(v:val,'\\v^CocSem\\w+')") +endfunction + " get cursor position function! coc#util#cursor() - return [line('.') - 1, strchars(strpart(getline('.'), 0, col('.') - 1))] + return [line('.') - 1, coc#string#character_length(strpart(getline('.'), 0, col('.') - 1))] endfunction -function! coc#util#has_preview() - for i in range(1, winnr('$')) - if getwinvar(i, '&previewwindow') - return i - endif - endfor - return 0 +function! coc#util#change_info() abort + return {'lnum': line('.'), 'col': col('.'), 'line': getline('.'), 'changedtick': b:changedtick} endfunction function! coc#util#jumpTo(line, character) abort @@ -42,9 +67,29 @@ function! coc#util#jumpTo(line, character) abort call coc#cursor#move_to(a:line, a:character) endfunction +function! coc#util#root_patterns() abort + return coc#rpc#request('rootPatterns', [bufnr('%')]) +endfunction + +function! coc#util#get_config(key) abort + return coc#rpc#request('getConfig', [a:key]) +endfunction + +function! coc#util#open_terminal(opts) abort + return coc#ui#open_terminal(a:opts) +endfunction + +function! coc#util#synname() abort + return synIDattr(synID(line('.'), col('.') - 1, 1), 'name') +endfunction + +function! coc#util#setline(lnum, line) + keepjumps call setline(a:lnum, a:line) +endfunction + function! coc#util#path_replace_patterns() abort if has('win32unix') && exists('g:coc_cygqwin_path_prefixes') - echohl WarningMsg + echohl WarningMsg echon 'g:coc_cygqwin_path_prefixes is deprecated, use g:coc_uri_prefix_replace_patterns instead' echohl None return g:coc_cygqwin_path_prefixes @@ -71,9 +116,6 @@ function! coc#util#check_refresh(bufnr) if getbufvar(a:bufnr, 'coc_diagnostic_disable', 0) return 0 endif - if get(g: , 'EasyMotion_loaded', 0) - return EasyMotion#is_active() != 1 - endif return 1 endfunction @@ -97,25 +139,14 @@ function! coc#util#diagnostic_info(bufnr, checkInsert) abort return { \ 'bufnr': bufnr('%'), \ 'winid': winid, - \ 'lnum': line('.'), + \ 'lnum': winid == -1 ? -1 : coc#window#get_cursor(winid)[0], \ 'locationlist': locationlist \ } endfunction function! coc#util#open_file(cmd, file) - let file = fnameescape(a:file) - execute a:cmd .' '.file -endfunction - -function! coc#util#remote_fns(name) - let fns = ['init', 'complete', 'should_complete', 'refresh', 'get_startcol', 'on_complete', 'on_enter'] - let res = [] - for fn in fns - if exists('*coc#source#'.a:name.'#'.fn) - call add(res, fn) - endif - endfor - return res + execute a:cmd .' '.fnameescape(fnamemodify(a:file, ':~:.')) + return bufnr('%') endfunction function! coc#util#job_command() @@ -139,44 +170,39 @@ function! coc#util#job_command() return [node] + get(g:, 'coc_node_args', ['--no-warnings']) + [s:root.'/build/index.js'] endfunction -function! coc#util#echo_hover(msg) - echohl MoreMsg - echo a:msg - echohl None - let g:coc_last_hover_message = a:msg -endfunction - function! coc#util#jump(cmd, filepath, ...) abort if a:cmd != 'pedit' silent! normal! m' endif let path = a:filepath - if (has('win32unix')) + if has('win32unix') let path = substitute(a:filepath, '\v\\', '/', 'g') endif let file = fnamemodify(path, ":~:.") - if a:cmd == 'pedit' + if a:cmd ==# 'pedit' let extra = empty(get(a:, 1, [])) ? '' : '+'.(a:1[0] + 1) exe 'pedit '.extra.' '.fnameescape(file) return - elseif a:cmd == 'drop' + elseif a:cmd ==# 'drop' let dstbuf = bufadd(path) let binfo = getbufinfo(dstbuf) if len(binfo) == 1 && empty(binfo[0].windows) - exec 'buffer '.dstbuf + execute 'buffer '.dstbuf + let &buflisted = 1 else - exec 'drop '.fnameescape(file) + let saved = &wildignore + set wildignore= + execute 'drop '.fnameescape(file) + execute 'set wildignore='.saved endif + elseif a:cmd ==# 'edit' && bufloaded(file) + exe 'b '.bufnr(file) else - exe a:cmd.' '.fnameescape(file) + call s:safer_open(a:cmd, file) endif if !empty(get(a:, 1, [])) let line = getline(a:1[0] + 1) - " TODO need to use utf16 here - let col = byteidx(line, a:1[1]) + 1 - if col == 0 - let col = 999 - endif + let col = coc#string#byte_index(line, a:1[1]) + 1 call cursor(a:1[0] + 1, col) endif if &filetype ==# '' @@ -187,70 +213,40 @@ function! coc#util#jump(cmd, filepath, ...) abort endif endfunction -function! coc#util#echo_messages(hl, msgs) - if a:hl !~# 'Error' && (mode() !~# '\v^(i|n)$') - return - endif - let msgs = filter(copy(a:msgs), '!empty(v:val)') - if empty(msgs) - return - endif - execute 'echohl '.a:hl - echom a:msgs[0] - redraw - echo join(msgs, "\n") - echohl None -endfunction - -function! coc#util#echo_lines(lines) - echo join(a:lines, "\n") -endfunction +function! s:safer_open(cmd, file) abort + " How to support :pedit and :drop? + let is_supported_cmd = index(["edit", "split", "vsplit", "tabe"], a:cmd) >= 0 -function! coc#util#timer(method, args) - call timer_start(0, { -> s:Call(a:method, a:args)}) -endfunction + " Use special handling only for URI. + let looks_like_uri = match(a:file, "^.*://") >= 0 -function! s:Call(method, args) - try - call call(a:method, a:args) - redraw - catch /.*/ - return 0 - endtry -endfunction - -function! coc#util#get_bufoptions(bufnr, maxFileSize) abort - if !bufloaded(a:bufnr) | return v:null | endif - let bufname = bufname(a:bufnr) - let buftype = getbufvar(a:bufnr, '&buftype') - let winid = bufwinid(a:bufnr) - let size = -1 - if bufnr('%') == a:bufnr - let size = line2byte(line("$") + 1) - elseif !empty(bufname) - let size = getfsize(bufname) - endif - let lines = [] - if getbufvar(a:bufnr, 'coc_enabled', 1) && (buftype == '' || buftype == 'acwrite') && size < a:maxFileSize - let lines = getbufline(a:bufnr, 1, '$') + if looks_like_uri && is_supported_cmd && has('win32') && exists('*bufadd') + " Workaround a bug for Win32 paths. + " + " reference: + " - https://github.com/vim/vim/issues/541 + " - https://github.com/neoclide/coc-java/issues/82 + " - https://github.com/vim-jp/issues/issues/6 + let buf = bufadd(a:file) + if a:cmd != 'edit' + " Open split, tab, etc. by a:cmd. + execute a:cmd + endif + " Set current buffer to the file + exe 'keepjumps buffer ' . buf + else + if a:cmd =~# 'drop' + let saved = &wildignore + set wildignore= + execute a:cmd.' '.fnameescape(a:file) + execute 'set wildignore='.saved + else + execute a:cmd.' '.fnameescape(a:file) + endif endif - return { - \ 'bufname': bufname, - \ 'size': size, - \ 'buftype': buftype, - \ 'winid': winid, - \ 'previewwindow': v:false, - \ 'variables': s:variables(a:bufnr), - \ 'fullpath': empty(bufname) ? '' : fnamemodify(bufname, ':p'), - \ 'eol': getbufvar(a:bufnr, '&eol'), - \ 'filetype': getbufvar(a:bufnr, '&filetype'), - \ 'iskeyword': getbufvar(a:bufnr, '&iskeyword'), - \ 'changedtick': getbufvar(a:bufnr, 'changedtick'), - \ 'lines': lines, - \} endfunction -function! s:variables(bufnr) abort +function! coc#util#variables(bufnr) abort let info = getbufinfo(a:bufnr) let variables = empty(info) ? {} : copy(info[0]['variables']) for key in keys(variables) @@ -261,107 +257,6 @@ function! s:variables(bufnr) abort return variables endfunction -function! coc#util#root_patterns() abort - return coc#rpc#request('rootPatterns', [bufnr('%')]) -endfunction - -function! coc#util#get_config(key) abort - return coc#rpc#request('getConfig', [a:key]) -endfunction - -function! coc#util#preview_info(info, filetype, ...) abort - pclose - keepalt new +setlocal\ previewwindow|setlocal\ buftype=nofile|setlocal\ noswapfile|setlocal\ wrap [Document] - setl bufhidden=wipe - setl nobuflisted - setl nospell - exe 'setl filetype='.a:filetype - setl conceallevel=0 - setl nofoldenable - for command in a:000 - execute command - endfor - let lines = a:info - call append(0, lines) - exe "normal! z" . len(lines) . "\" - exe "normal! gg" - wincmd p -endfunction - -function! coc#util#get_config_home() - if !empty(get(g:, 'coc_config_home', '')) - return resolve(expand(g:coc_config_home)) - endif - if exists('$VIMCONFIG') - return resolve($VIMCONFIG) - endif - if has('nvim') - if exists('$XDG_CONFIG_HOME') - return resolve($XDG_CONFIG_HOME."/nvim") - endif - if s:is_win - return resolve($HOME.'/AppData/Local/nvim') - endif - return resolve($HOME.'/.config/nvim') - else - if s:is_win - return resolve($HOME."/vimfiles") - endif - return resolve($HOME.'/.vim') - endif -endfunction - -function! coc#util#get_data_home() - if !empty(get(g:, 'coc_data_home', '')) - let dir = resolve(expand(g:coc_data_home)) - else - if exists('$XDG_CONFIG_HOME') - let dir = resolve($XDG_CONFIG_HOME."/coc") - else - if s:is_win - let dir = resolve(expand('~/AppData/Local/coc')) - else - let dir = resolve(expand('~/.config/coc')) - endif - endif - endif - if !isdirectory(dir) - echohl MoreMsg | echom '[coc.nvim] creating data directory: '.dir | echohl None - call mkdir(dir, "p", 0755) - endif - return dir -endfunction - -function! coc#util#get_input() - let before = strpart(getline('.'), 0, col('.')-1) - if len(before) == 0 - return '' - endif - return matchstr(before, '\k*$') -endfunction - -function! coc#util#get_complete_option() - let pos = getcurpos() - let line = getline(pos[1]) - let input = matchstr(strpart(line, 0, pos[2] - 1), '\k*$') - let col = pos[2] - strlen(input) - let synname = synIDattr(synID(pos[1], col, 1), 'name') - return { - \ 'word': matchstr(strpart(line, col - 1), '^\k\+'), - \ 'input': empty(input) ? '' : input, - \ 'line': line, - \ 'filetype': &filetype, - \ 'filepath': expand('%:p'), - \ 'bufnr': bufnr('%'), - \ 'linenr': pos[1], - \ 'colnr' : pos[2], - \ 'col': col - 1, - \ 'synname': synname, - \ 'changedtick': b:changedtick, - \ 'blacklist': get(b:, 'coc_suggest_blacklist', []), - \} -endfunction - function! coc#util#with_callback(method, args, cb) function! s:Cb() closure try @@ -375,164 +270,34 @@ function! coc#util#with_callback(method, args, cb) call timer_start(timeout, {-> s:Cb() }) endfunction -function! coc#util#quickpick(title, items, cb) abort - if exists('*popup_menu') - function! s:QuickpickHandler(id, result) closure - call a:cb(v:null, a:result) - endfunction - function! s:QuickpickFilter(id, key) closure - for i in range(1, len(a:items)) - if a:key == string(i) - call popup_close(a:id, i) - return 1 - endif - endfor - " No shortcut, pass to generic filter - return popup_filter_menu(a:id, a:key) - endfunction - try - call popup_menu(a:items, { - \ 'title': a:title, - \ 'filter': function('s:QuickpickFilter'), - \ 'callback': function('s:QuickpickHandler'), - \ }) - redraw - catch /.*/ - call a:cb(v:exception) - endtry - else - let res = inputlist([a:title] + a:items) - call a:cb(v:null, res) - endif -endfunction - -function! coc#util#echo_signatures(signatures) abort - if pumvisible() | return | endif - echo "" - for i in range(len(a:signatures)) - call s:echo_signature(a:signatures[i]) - if i != len(a:signatures) - 1 - echon "\n" - endif - endfor -endfunction - -function! s:echo_signature(parts) - for part in a:parts - let hl = get(part, 'type', 'Normal') - let text = get(part, 'text', '') - if !empty(text) - execute 'echohl '.hl - execute "echon '".substitute(text, "'", "''", 'g')."'" - echohl None - endif - endfor -endfunction - -function! coc#util#setline(lnum, line) - keepjumps call setline(a:lnum, a:line) -endfunction - -" cmd, cwd -function! coc#util#open_terminal(opts) abort - if s:is_vim && !exists('*term_start') - echohl WarningMsg | echon "Your vim doesn't have terminal support!" | echohl None - return - endif - if get(a:opts, 'position', 'bottom') ==# 'bottom' - let p = '5new' - else - let p = 'vnew' - endif - execute 'belowright '.p.' +setl\ buftype=nofile ' - setl buftype=nofile - setl winfixheight - setl norelativenumber - setl nonumber - setl bufhidden=wipe - if exists('#User#CocTerminalOpen') - exe 'doautocmd User CocTerminalOpen' - endif - let cmd = get(a:opts, 'cmd', '') - let autoclose = get(a:opts, 'autoclose', 1) - if empty(cmd) - throw 'command required!' - endif - let cwd = get(a:opts, 'cwd', getcwd()) - let keepfocus = get(a:opts, 'keepfocus', 0) - let bufnr = bufnr('%') - let Callback = get(a:opts, 'Callback', v:null) - - function! s:OnExit(status) closure - let content = join(getbufline(bufnr, 1, '$'), "\n") - if a:status == 0 && autoclose == 1 - execute 'silent! bd! '.bufnr - endif - if !empty(Callback) - call call(Callback, [a:status, bufnr, content]) - endif - endfunction - - if has('nvim') - call termopen(cmd, { - \ 'cwd': cwd, - \ 'on_exit': {job, status -> s:OnExit(status)}, - \}) - else - if s:is_win - let cmd = 'cmd.exe /C "'.cmd.'"' - endif - call term_start(cmd, { - \ 'cwd': cwd, - \ 'exit_cb': {job, status -> s:OnExit(status)}, - \ 'curwin': 1, - \}) - endif - if keepfocus - wincmd p - endif - return bufnr -endfunction - -" run command in terminal -function! coc#util#run_terminal(opts, cb) - let cmd = get(a:opts, 'cmd', '') - if empty(cmd) - return a:cb('command required for terminal') - endif - let opts = { - \ 'cmd': cmd, - \ 'cwd': get(a:opts, 'cwd', getcwd()), - \ 'keepfocus': get(a:opts, 'keepfocus', 0), - \ 'Callback': {status, bufnr, content -> a:cb(v:null, {'success': status == 0 ? v:true : v:false, 'bufnr': bufnr, 'content': content})} - \} - call coc#util#open_terminal(opts) +function! coc#util#timer(method, args) + call timer_start(0, { -> s:Call(a:method, a:args)}) endfunction -function! coc#util#getpid() - if !has('win32unix') - return getpid() - endif - let cmd = 'cat /proc/' . getpid() . '/winpid' - return substitute(system(cmd), '\v\n', '', 'gi') +function! s:Call(method, args) + try + call call(a:method, a:args) + redraw + catch /.*/ + return 0 + endtry endfunction function! coc#util#vim_info() return { \ 'apiversion': s:vim_api_version, \ 'mode': mode(), + \ 'config': get(g:, 'coc_user_config', {}), \ 'floating': has('nvim') && exists('*nvim_open_win') ? v:true : v:false, \ 'extensionRoot': coc#util#extension_root(), \ 'globalExtensions': get(g:, 'coc_global_extensions', []), - \ 'config': get(g:, 'coc_user_config', {}), - \ 'pid': coc#util#getpid(), - \ 'columns': &columns, \ 'lines': &lines, + \ 'columns': &columns, \ 'cmdheight': &cmdheight, + \ 'pid': coc#util#getpid(), \ 'filetypeMap': get(g:, 'coc_filetype_map', {}), \ 'version': coc#util#version(), - \ 'completeOpt': &completeopt, - \ 'pumevent': exists('##MenuPopupChanged') || exists('##CompleteChanged'), + \ 'pumevent': 1, \ 'isVim': has('nvim') ? v:false : v:true, \ 'isCygwin': has('win32unix') ? v:true : v:false, \ 'isMacvim': has('gui_macvim') ? v:true : v:false, @@ -540,139 +305,42 @@ function! coc#util#vim_info() \ 'colorscheme': get(g:, 'colors_name', ''), \ 'workspaceFolders': get(g:, 'WorkspaceFolders', v:null), \ 'background': &background, - \ 'runtimepath': &runtimepath, + \ 'runtimepath': join(globpath(&runtimepath, '', 0, 1), ','), \ 'locationlist': get(g:,'coc_enable_locationlist', 1), \ 'progpath': v:progpath, \ 'guicursor': &guicursor, - \ 'updateHighlight': has('nvim-0.5.0') || exists('*prop_list') ? v:true : v:false, + \ 'pumwidth': exists('&pumwidth') ? &pumwidth : 15, + \ 'tabCount': tabpagenr('$'), + \ 'updateHighlight': has('nvim-0.5.0') || has('textprop') ? v:true : v:false, \ 'vimCommands': get(g:, 'coc_vim_commands', []), \ 'sign': exists('*sign_place') && exists('*sign_unplace'), - \ 'textprop': has('textprop') && has('patch-8.1.1719') && !has('nvim') ? v:true : v:false, - \ 'dialog': has('nvim-0.4.0') || has('patch-8.2.0750') ? v:true : v:false, - \ 'disabledSources': get(g:, 'coc_sources_disable_map', {}), + \ 'ambiguousIsNarrow': &ambiwidth ==# 'single' ? v:true : v:false, + \ 'textprop': has('textprop') ? v:true : v:false, + \ 'virtualText': has('nvim-0.5.0') || has('patch-9.0.0067') ? v:true : v:false, + \ 'dialog': 1, + \ 'semanticHighlights': coc#util#semantic_hlgroups() \} endfunction -function! coc#util#highlight_options() +function! coc#util#all_state() return { - \ 'colorscheme': get(g:, 'colors_name', ''), - \ 'background': &background, - \ 'runtimepath': &runtimepath, - \} -endfunction - -function! coc#util#set_lines(bufnr, changedtick, original, replacement, start, end) abort - if !bufloaded(a:bufnr) - return - endif - if getbufvar(a:bufnr, 'changedtick') != a:changedtick && bufnr('%') == a:bufnr - " try apply current line change - let lnum = line('.') - let idx = a:start - lnum + 1 - let previous = get(a:original, idx, 0) - if type(previous) == 1 - let content = getline('.') - if previous !=# content - let diff = coc#helper#str_diff(content, previous, col('.')) - let changed = get(a:replacement, idx, 0) - if type(changed) == 1 && strcharpart(previous, 0, diff['end']) ==# strcharpart(changed, 0, diff['end']) - let applied = coc#helper#str_apply(changed, diff) - let replacement = copy(a:replacement) - let replacement[idx] = applied - call coc#compat#buf_set_lines(a:bufnr, a:start, a:end, replacement) - return - endif - endif - endif - endif - call coc#compat#buf_set_lines(a:bufnr, a:start, a:end, a:replacement) -endfunction - -function! coc#util#change_lines(bufnr, list) abort - if !bufloaded(a:bufnr) | return v:null | endif - undojoin - if exists('*setbufline') - for [lnum, line] in a:list - call setbufline(a:bufnr, lnum + 1, line) - endfor - elseif a:bufnr == bufnr('%') - for [lnum, line] in a:list - call setline(lnum + 1, line) - endfor - else - let bufnr = bufnr('%') - exe 'noa buffer '.a:bufnr - for [lnum, line] in a:list - call setline(lnum + 1, line) - endfor - exe 'noa buffer '.bufnr - endif -endfunction - - -" used by vim -function! coc#util#get_buf_lines(bufnr, changedtick) - if !bufloaded(a:bufnr) - return v:null - endif - let changedtick = getbufvar(a:bufnr, 'changedtick') - if changedtick == a:changedtick - return v:null - endif - return { - \ 'lines': getbufline(a:bufnr, 1, '$'), - \ 'changedtick': getbufvar(a:bufnr, 'changedtick') + \ 'bufnr': bufnr('%'), + \ 'winid': win_getid(), + \ 'bufnrs': map(getbufinfo({'bufloaded': 1}),'v:val["bufnr"]'), + \ 'winids': map(getwininfo(),'v:val["winid"]'), \ } endfunction -" used for TextChangedI with InsertCharPre -function! coc#util#get_changeinfo() - return { - \ 'lnum': line('.'), - \ 'line': getline('.'), - \ 'changedtick': b:changedtick, - \} -endfunction - -function! coc#util#open_url(url) - if has('mac') && executable('open') - call system('open '.a:url) - return - endif - if executable('xdg-open') - call system('xdg-open '.a:url) - return - endif - call system('cmd /c start "" /b '. substitute(a:url, '&', '^&', 'g')) - if v:shell_error - echohl Error | echom 'Failed to open '.a:url | echohl None - return - endif -endfunction - function! coc#util#install() abort let yarncmd = get(g:, 'coc_install_yarn_cmd', executable('yarnpkg') ? 'yarnpkg' : 'yarn') - call coc#util#open_terminal({ + call coc#ui#open_terminal({ \ 'cwd': s:root, \ 'cmd': yarncmd.' install --frozen-lockfile --ignore-engines', \ 'autoclose': 0, \ }) endfunction -function! coc#util#do_complete(name, opt, cb) abort - let handler = 'coc#source#'.a:name.'#complete' - let l:Cb = {res -> a:cb(v:null, res)} - let args = [a:opt, l:Cb] - call call(handler, args) -endfunction - function! coc#util#extension_root() abort - if get(g:, 'coc_node_env', '') ==# 'test' - return s:root.'/src/__tests__/extensions' - endif - if !empty(get(g:, 'coc_extension_root', '')) - echohl Error | echon 'g:coc_extension_root not used any more, use g:coc_data_home instead' | echohl None - endif return coc#util#get_data_home().'/extensions' endfunction @@ -701,187 +369,316 @@ function! coc#util#do_autocmd(name) abort endif endfunction -function! coc#util#rebuild() - let dir = coc#util#extension_root() - if !isdirectory(dir) | return | endif - call coc#util#open_terminal({ - \ 'cwd': dir, - \ 'cmd': 'npm rebuild', - \ 'keepfocus': 1, - \}) -endfunction - -" [r, g, b] ['255', '255', '255'] -" return ['65535', '65535', '65535'] or return v:false to cancel -function! coc#util#pick_color(default_color) - if has('mac') - let default_color = map(a:default_color, {idx, val -> str2nr(val) * 65535 / 255 }) - " This is the AppleScript magic: - let s:ascrpt = ['-e "tell application \"' . s:app . '\""', - \ '-e "' . s:activate . '"', - \ "-e \"set AppleScript's text item delimiters to {\\\",\\\"}\"", - \ '-e "set theColor to (choose color default color {' . default_color[0] . ", " . default_color[1] . ", " . default_color[2] . '}) as text"', - \ '-e "' . s:quit . '"', - \ '-e "end tell"', - \ '-e "return theColor"'] - let res = trim(system("osascript " . join(s:ascrpt, ' ') . " 2>/dev/null")) - if empty(res) - return v:false - else - return split(trim(res), ',') - endif +function! coc#util#unmap(bufnr, keys) abort + if bufnr('%') == a:bufnr + for key in a:keys + exe 'silent! nunmap '.key + endfor endif +endfunction - let hex_color = printf('#%02x%02x%02x', a:default_color[0], a:default_color[1], a:default_color[2]) +function! coc#util#refactor_foldlevel(lnum) abort + if a:lnum <= 2 | return 0 | endif + let line = getline(a:lnum) + if line =~# '^\%u3000\s*$' | return 0 | endif + return 1 +endfunction - if has('unix') - if executable('zenity') - let res = trim(system('zenity --title="Select a color" --color-selection --color="' . hex_color . '" 2> /dev/null')) - if empty(res) - return v:false - else - " res format is rgb(255,255,255) - return map(split(res[4:-2], ','), {idx, val -> string(str2nr(trim(val)) * 65535 / 255)}) - endif - endif +function! coc#util#refactor_fold_text(lnum) abort + let range = '' + let info = get(b:line_infos, a:lnum, []) + if !empty(info) + let range = info[0].':'.info[1] endif + return trim(getline(a:lnum)[3:]).' '.range +endfunction - let rgb = v:false - if !has('python') - echohl Error | echom 'python support required, checkout :echo has(''python'')' | echohl None - return +" get tabsize & expandtab option +function! coc#util#get_format_opts(bufnr) abort + let bufnr = a:bufnr && bufloaded(a:bufnr) ? a:bufnr : bufnr('%') + let tabsize = getbufvar(bufnr, '&shiftwidth') + if tabsize == 0 + let tabsize = getbufvar(bufnr, '&tabstop') endif - try - execute 'py import gtk' - catch /.*/ - echohl Error | echom 'python gtk module not found' | echohl None - return - endtry -python << endpython - -import vim -import gtk, sys - -# message strings -wnd_title_insert = "Insert a color" - -csd = gtk.ColorSelectionDialog(wnd_title_insert) -cs = csd.colorsel + return { + \ 'tabsize': tabsize, + \ 'expandtab': getbufvar(bufnr, '&expandtab'), + \ 'insertFinalNewline': getbufvar(bufnr, '&eol'), + \ 'trimTrailingWhitespace': getbufvar(bufnr, 'coc_trim_trailing_whitespace', 0), + \ 'trimFinalNewlines': getbufvar(bufnr, 'coc_trim_final_newlines', 0) + \ } +endfunction -cs.set_current_color(gtk.gdk.color_parse(vim.eval("hex_color"))) +function! coc#util#get_editoroption(winid) abort + let info = get(getwininfo(a:winid), 0, v:null) + if empty(info) || coc#window#is_float(a:winid) + return v:null + endif + let bufnr = info['bufnr'] + let buftype = getbufvar(bufnr, '&buftype') + " avoid window for other purpose. + if buftype !=# '' && buftype !=# 'acwrite' + return v:null + endif + let tabSize = getbufvar(bufnr, '&shiftwidth') + if tabSize == 0 + let tabSize = getbufvar(bufnr, '&tabstop') + endif + return { + \ 'bufnr': bufnr, + \ 'winid': a:winid, + \ 'tabpageid': coc#util#tabnr_id(info['tabnr']), + \ 'winnr': winnr(), + \ 'visibleRanges': s:visible_ranges(a:winid), + \ 'tabSize': tabSize, + \ 'insertSpaces': getbufvar(bufnr, '&expandtab') ? v:true : v:false + \ } +endfunction -cs.set_current_alpha(65535) -cs.set_has_opacity_control(False) -# cs.set_has_palette(int(vim.eval("s:display_palette"))) +function! coc#util#tabnr_id(tabnr) abort + return s:is_vim ? coc#api#get_tabid(a:tabnr) : nvim_list_tabpages()[a:tabnr - 1] +endfunction -if csd.run()==gtk.RESPONSE_OK: - c = cs.get_current_color() - s = [str(int(c.red)),',',str(int(c.green)),',',str(int(c.blue))] - thecolor = ''.join(s) - vim.command(":let rgb = split('%s',',')" % thecolor) +function! coc#util#get_loaded_bufs() abort + return map(getbufinfo({'bufloaded': 1}),'v:val["bufnr"]') +endfunction -csd.destroy() +function! coc#util#editor_infos() abort + let result = [] + for info in getwininfo() + if !coc#window#is_float(info['winid']) + let bufnr = info['bufnr'] + let buftype = getbufvar(bufnr, '&buftype') + if buftype !=# '' && buftype !=# 'acwrite' + continue + endif + let bufname = bufname(bufnr) + call add(result, { + \ 'winid': info['winid'], + \ 'bufnr': bufnr, + \ 'tabid': coc#util#tabnr_id(info['tabnr']), + \ 'fullpath': empty(bufname) ? '' : fnamemodify(bufname, ':p'), + \ }) + endif + endfor + return result +endfunction -endpython - return rgb +function! coc#util#tabpages() abort + if s:is_vim + return coc#api#exec('list_tabpages', []) + endif + return nvim_list_tabpages() endfunction -function! coc#util#iterm_open(dir) - return s:osascript( - \ 'if application "iTerm2" is not running', - \ 'error', - \ 'end if') && s:osascript( - \ 'tell application "iTerm2"', - \ 'tell current window', - \ 'create tab with default profile', - \ 'tell current session', - \ 'write text "cd ' . a:dir . '"', - \ 'write text "clear"', - \ 'activate', - \ 'end tell', - \ 'end tell', - \ 'end tell') +function! coc#util#getpid() + if !has('win32unix') + return getpid() + endif + let cmd = 'cat /proc/' . getpid() . '/winpid' + return substitute(system(cmd), '\v\n', '', 'gi') endfunction -function! s:osascript(...) abort - let args = join(map(copy(a:000), '" -e ".shellescape(v:val)'), '') - call s:system('osascript'. args) - return !v:shell_error +" Get indentkeys for indent on TextChangedP, consider = for word indent only. +function! coc#util#get_indentkeys() abort + if empty(&indentexpr) + return '' + endif + if &indentkeys !~# '=' + return '' + endif + return &indentkeys endfunction -function! s:system(cmd) - let output = system(a:cmd) - if v:shell_error && output !=# "" - echohl Error | echom output | echohl None - return +function! coc#util#get_bufoptions(bufnr, max) abort + if !bufloaded(a:bufnr) | return v:null | endif + let bufname = bufname(a:bufnr) + let buftype = getbufvar(a:bufnr, '&buftype') + let size = coc#util#bufsize(a:bufnr) + let lines = v:null + if getbufvar(a:bufnr, 'coc_enabled', 1) + \ && (buftype == '' || buftype == 'acwrite' || getbufvar(a:bufnr, 'coc_force_attach', 0)) + \ && size != -2 + \ && size < a:max + let lines = getbufline(a:bufnr, 1, '$') endif - return output + return { + \ 'bufnr': a:bufnr, + \ 'size': size, + \ 'lines': lines, + \ 'winid': bufwinid(a:bufnr), + \ 'bufname': bufname, + \ 'buftype': buftype, + \ 'previewwindow': v:false, + \ 'eol': getbufvar(a:bufnr, '&eol'), + \ 'variables': coc#util#variables(a:bufnr), + \ 'filetype': getbufvar(a:bufnr, '&filetype'), + \ 'lisp': getbufvar(a:bufnr, '&lisp'), + \ 'iskeyword': getbufvar(a:bufnr, '&iskeyword'), + \ 'changedtick': getbufvar(a:bufnr, 'changedtick'), + \ 'fullpath': empty(bufname) ? '' : fnamemodify(bufname, ':p'), + \} endfunction -function! coc#util#unmap(bufnr, keys) abort +function! coc#util#bufsize(bufnr) abort if bufnr('%') == a:bufnr - for key in a:keys - exe 'silent! nunmap '.key - endfor + return line2byte(line("$") + 1) + endif + let bufname = bufname(a:bufnr) + if !getbufvar(a:bufnr, '&modified') && filereadable(bufname) + return getfsize(bufname) endif + return strlen(join(getbufline(a:bufnr, 1, '$'), '\n')) endfunction -function! coc#util#open_files(files) - let bufnrs = [] - " added on latest vim8 - if exists('*bufadd') && exists('*bufload') - for file in a:files - let file = fnamemodify(file, ':.') - if bufloaded(file) - call add(bufnrs, bufnr(file)) - else - let bufnr = bufadd(file) - call bufload(file) - call add(bufnrs, bufnr) - call setbufvar(bufnr, '&buflisted', 1) - endif - endfor +function! coc#util#get_config_home() + if !empty(get(g:, 'coc_config_home', '')) + return resolve(expand(g:coc_config_home)) + endif + if exists('$VIMCONFIG') + return resolve($VIMCONFIG) + endif + if has('nvim') + if exists('$XDG_CONFIG_HOME') + return resolve($XDG_CONFIG_HOME."/nvim") + endif + if s:is_win + return resolve($HOME.'/AppData/Local/nvim') + endif + return resolve($HOME.'/.config/nvim') + else + if s:is_win + return resolve($HOME."/vimfiles") + endif + return resolve($HOME.'/.vim') + endif +endfunction + +function! coc#util#get_data_home() + if get(g:, 'coc_node_env', '') ==# 'test' + return $COC_DATA_HOME + endif + if !empty(get(g:, 'coc_data_home', '')) + let dir = resolve(expand(g:coc_data_home)) else - noa keepalt 1new +setl\ bufhidden=wipe - for file in a:files - let file = fnamemodify(file, ':.') - execute 'noa edit +setl\ bufhidden=hide '.fnameescape(file) - if &filetype ==# '' - filetype detect + if exists('$XDG_CONFIG_HOME') + let dir = resolve($XDG_CONFIG_HOME."/coc") + else + if s:is_win + let dir = resolve(expand('~/AppData/Local/coc')) + else + let dir = resolve(expand('~/.config/coc')) endif - call add(bufnrs, bufnr('%')) - endfor - noa close + endif + endif + if !isdirectory(dir) + call coc#notify#create(['creating coc.nvim data directory: '.dir], { + \ 'borderhighlight': 'CocInfoSign', + \ 'timeout': 5000, + \ 'kind': 'info', + \ }) + call mkdir(dir, "p", 0755) endif - doautocmd BufEnter - return bufnrs + return dir endfunction -function! coc#util#refactor_foldlevel(lnum) abort - if a:lnum <= 2 | return 0 | endif - let line = getline(a:lnum) - if line =~# '^\%u3000\s*$' | return 0 | endif - return 1 +function! coc#util#get_complete_option() + let pos = getcurpos() + let line = getline(pos[1]) + let input = matchstr(strpart(line, 0, pos[2] - 1), '\k*$') + let col = pos[2] - strlen(input) + let position = { + \ 'line': line('.')-1, + \ 'character': coc#string#character_length(strpart(getline('.'), 0, col('.') - 1)) + \ } + let word = matchstr(strpart(line, col - 1), '^\k\+') + let followWord = len(word) > 0 ? strcharpart(word, strchars(input)) : '' + return { + \ 'word': word, + \ 'followWord': followWord, + \ 'position': position, + \ 'input': empty(input) ? '' : input, + \ 'line': line, + \ 'filetype': &filetype, + \ 'filepath': expand('%:p'), + \ 'bufnr': bufnr('%'), + \ 'linenr': pos[1], + \ 'colnr' : pos[2], + \ 'col': col - 1, + \ 'changedtick': b:changedtick, + \} endfunction -function! coc#util#refactor_fold_text(lnum) abort - let range = '' - let info = get(b:line_infos, a:lnum, []) - if !empty(info) - let range = info[0].':'.info[1] +" used by vim +function! coc#util#get_buf_lines(bufnr, changedtick) + if !bufloaded(a:bufnr) + return v:null endif - return trim(getline(a:lnum)[3:]).' '.range + let changedtick = getbufvar(a:bufnr, 'changedtick') + if changedtick == a:changedtick + return v:null + endif + return { + \ 'lines': getbufline(a:bufnr, 1, '$'), + \ 'changedtick': getbufvar(a:bufnr, 'changedtick') + \ } endfunction -" get tabsize & expandtab option -function! coc#util#get_format_opts(bufnr) abort - if a:bufnr && bufloaded(a:bufnr) - let tabsize = getbufvar(a:bufnr, '&shiftwidth') - if tabsize == 0 - let tabsize = getbufvar(a:bufnr, '&tabstop') - endif - return [tabsize, getbufvar(a:bufnr, '&expandtab')] +" used for TextChangedI with InsertCharPre +function! coc#util#get_changeinfo(bufnr) + if bufnr('%') == a:bufnr + return { + \ 'lnum': line('.'), + \ 'line': getline('.'), + \ 'changedtick': b:changedtick, + \} + endif + let winid = bufwinid(a:bufnr) + if winid != -1 + let ref = {} + call win_execute(winid, 'let ref = {"lnum": line("."), "line": getline("."), "changedtick": b:changedtick}') + return ref + endif + return v:null +endfunction + +" Get the valid position from line, character of current buffer +function! coc#util#valid_position(line, character) abort + let total = line('$') - 1 + if a:line > total + return [total, 0] endif - let tabsize = &shiftwidth == 0 ? &tabstop : &shiftwidth - return [tabsize, &expandtab] + let max = max([0, coc#string#character_length(getline(a:line + 1)) - (mode() ==# 'n' ? 1 : 0)]) + return a:character > max ? [a:line, max] : [a:line, a:character] +endfunction + +function! s:visible_ranges(winid) abort + let info = getwininfo(a:winid)[0] + let res = [] + if !has_key(info, 'topline') || !has_key(info, 'botline') + return res + endif + let begin = 0 + let curr = info['topline'] + let max = info['botline'] + if win_getid() != a:winid + return [[curr, max]] + endif + while curr <= max + let closedend = foldclosedend(curr) + if closedend == -1 + let begin = begin == 0 ? curr : begin + if curr == max + call add(res, [begin, curr]) + endif + let curr = curr + 1 + else + if begin != 0 + call add(res, [begin, curr - 1]) + let begin = closedend + 1 + endif + let curr = closedend + 1 + endif + endwhile + return res endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/vtext.vim b/vim-config/plugins/coc.nvim/autoload/coc/vtext.vim new file mode 100644 index 00000000..e9529336 --- /dev/null +++ b/vim-config/plugins/coc.nvim/autoload/coc/vtext.vim @@ -0,0 +1,91 @@ +let s:is_vim = !has('nvim') +let s:virtual_text_support = has('nvim-0.5.0') || has('patch-9.0.0067') +let s:text_options = has('patch-9.0.0121') || has('nvim-0.6.0') +let s:vim_above = has('patch-9.0.0438') + +" This function is called by buffer.setVirtualText +" opts.hl_mode default to 'combine'. +" opts.col vim only, no support on neovim, default to 0. +" opts.virt_text_win_col neovim only. +" opts.text_align could be 'after' 'right' 'below' 'above', converted on neovim. +" opts.text_wrap could be 'wrap' and 'truncate', vim9 only. +" opts.indent add indent when using 'above' and 'below' as text_align +function! coc#vtext#add(bufnr, src_id, line, blocks, opts) abort + if !s:virtual_text_support + return + endif + let align = get(a:opts, 'text_align', 'after') + let indent = '' + if get(a:opts, 'indent', 0) + let indent = matchstr(getline(a:line + 1), '^\s\+') + endif + if s:is_vim + let column = get(a:opts, 'col', 0) + if !has_key(a:opts, 'col') && align ==# 'after' + " add a whitespace, same as neovim. + let indent = ' ' + endif + let blocks = a:blocks + if !empty(a:blocks) && (align ==# 'above' || align ==# 'below') + " only first highlight can be used + let hl = a:blocks[0][1] + let text = join(map(copy(a:blocks), "v:val[0]"), '') + let blocks = [[text, hl]] + let column = 0 + endif + let first = 1 + let base = s:get_option_vim(align, column, get(a:opts, 'text_wrap', 'truncate')) + for [text, hl] in blocks + let type = coc#api#create_type(a:src_id, hl, a:opts) + let opts = extend({ 'text': text, 'type': type }, base) + if first && !empty(indent) + let opts['text'] = indent . text + endif + call prop_add(a:line + 1, column, opts) + let first = 0 + endfor + else + let opts = { 'hl_mode': get(a:opts, 'hl_mode', 'combine') } + if s:text_options + if align ==# 'above' || align ==# 'below' + let blocks = empty(indent) ? a:blocks : [[indent, 'Normal']] + a:blocks + let opts['virt_lines'] = [blocks] + if align ==# 'above' + let opts['virt_lines_above'] = v:true + endif + else + let opts['virt_text'] = a:blocks + if align ==# 'right' + let opts['virt_text_pos'] = 'right_align' + else + if type(get(a:opts, 'virt_text_win_col', v:null)) == 0 + let opts['virt_text_win_col'] = a:opts['virt_text_win_col'] + let opts['virt_text_pos'] = 'overlay' + else + " default to 'after' + let opts['virt_text_pos'] = 'eol' + endif + endif + endif + else + if has('nvim-0.5.1') && type(get(a:opts, 'virt_text_win_col', v:null)) == 0 + let opts['virt_text_win_col'] = a:opts['virt_text_win_col'] + let opts['virt_text_pos'] = 'overlay' + endif + endif + call nvim_buf_set_extmark(a:bufnr, a:src_id, a:line, 0, opts) + endif +endfunction + +function! s:get_option_vim(align, column, wrap) abort + let opts = {} + if s:text_options && a:column == 0 + if a:align ==# 'top' && !s:vim_above + let opts['text_align'] = 'right' + else + let opts['text_align'] = a:align + endif + let opts['text_wrap'] = a:wrap + endif + return opts +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/coc/window.vim b/vim-config/plugins/coc.nvim/autoload/coc/window.vim index 113d727f..ae44ddb4 100644 --- a/vim-config/plugins/coc.nvim/autoload/coc/window.vim +++ b/vim-config/plugins/coc.nvim/autoload/coc/window.vim @@ -1,13 +1,150 @@ +let g:coc_max_treeview_width = get(g:, 'coc_max_treeview_width', 40) +let s:is_vim = !has('nvim') + +" Get tabpagenr of winid, return -1 if window doesn't exist function! coc#window#tabnr(winid) abort + " getwininfo not work with popup on vim if exists('*win_execute') let ref = {} call win_execute(a:winid, 'let ref["out"] = tabpagenr()') return get(ref, 'out', -1) - elseif has('nvim') - let info = getwininfo(a:winid) - return empty(info) ? -1 : info[0]['tabnr'] + endif + let info = getwininfo(a:winid) + return empty(info) ? -1 : info[0]['tabnr'] +endfunction + +" (1, 0) based line, column +function! coc#window#get_cursor(winid) abort + if exists('*nvim_win_get_cursor') + return nvim_win_get_cursor(a:winid) + endif + if has('patch-8.2.1727') + let pos = getcurpos(a:winid) + return [pos[1], pos[2] - 1] + endif + return coc#api#exec('win_get_cursor', [a:winid]) +endfunction + +" Check if winid visible on current tabpage +function! coc#window#visible(winid) abort + if s:is_vim + if coc#window#tabnr(a:winid) != tabpagenr() + return 0 + endif + " Check possible hidden popup + try + return get(popup_getpos(a:winid), 'visible', 0) == 1 + catch /^Vim\%((\a\+)\)\=:E993/ + return 1 + endtry + endif + if !nvim_win_is_valid(a:winid) + return 0 + endif + return coc#window#tabnr(a:winid) == tabpagenr() +endfunction + +" winid is popup and shown +function! s:visible_popup(winid) abort + let popups = popup_list() + if index(popups, a:winid) != -1 + return get(popup_getpos(a:winid), 'visible', 0) == 1 + endif + return 0 +endfunction + +" Return v:null when name or window doesn't exist, +" 'getwinvar' only works on window of current tab +function! coc#window#get_var(winid, name, ...) abort + if !s:is_vim + try + if a:name =~# '^&' + return nvim_win_get_option(a:winid, a:name[1:]) + else + return nvim_win_get_var(a:winid, a:name) + endif + catch /E5555/ + return get(a:, 1, v:null) + endtry + else + try + return coc#api#exec('win_get_var', [a:winid, a:name, get(a:, 1, v:null)]) + catch /Invalid window id/ + return get(a:, 1, v:null) + endtry + endif +endfunction + +" Not throw like setwinvar +function! coc#window#set_var(winid, name, value) abort + try + if !s:is_vim + if a:name =~# '^&' + call nvim_win_set_option(a:winid, a:name[1:], a:value) + else + call nvim_win_set_var(a:winid, a:name, a:value) + endif + else + call coc#api#exec('win_set_var', [a:winid, a:name, a:value]) + endif + catch /Invalid window id/ + " ignore + endtry +endfunction + +function! coc#window#is_float(winid) abort + if s:is_vim + try + return !empty(popup_getpos(a:winid)) + catch /^Vim\%((\a\+)\)\=:E993/ + return 0 + endtry + else + let config = nvim_win_get_config(a:winid) + return !empty(config) && !empty(get(config, 'relative', '')) + endif +endfunction + +" Reset current lnum & topline of window +function! coc#window#restview(winid, lnum, topline) abort + if empty(getwininfo(a:winid)) + return + endif + if s:is_vim && s:visible_popup(a:winid) + call popup_setoptions(a:winid, {'firstline': a:topline}) + return + endif + call coc#compat#execute(a:winid, ['noa call winrestview({"lnum":'.a:lnum.',"topline":'.a:topline.'})']) +endfunction + +function! coc#window#set_height(winid, height) abort + if empty(getwininfo(a:winid)) + return + endif + if exists('*nvim_win_set_height') + call nvim_win_set_height(a:winid, a:height) else - throw 'win_execute() not exists, please upgrade your vim.' + call coc#compat#execute(a:winid, 'noa resize '.a:height, 'silent') + endif +endfunction + +function! coc#window#adjust_width(winid) abort + let bufnr = winbufnr(a:winid) + if bufloaded(bufnr) + let maxwidth = 0 + let lines = getbufline(bufnr, 1, '$') + if len(lines) > 2 + call coc#compat#execute(a:winid, 'setl nowrap') + for line in lines + let w = strwidth(line) + if w > maxwidth + let maxwidth = w + endif + endfor + endif + if maxwidth > winwidth(a:winid) + call coc#compat#execute(a:winid, 'vertical resize '.min([maxwidth, g:coc_max_treeview_width])) + endif endif endfunction @@ -22,12 +159,15 @@ function! coc#window#find(key, val) abort return -1 endfunction -" Make sure window exists -function! coc#window#gotoid(winid) abort - noa let res = win_gotoid(a:winid) - if res == 0 - throw 'Invalid window number' +" Visible buffer numbers +function! coc#window#bufnrs() abort + let winids = [] + if exists('*nvim_list_wins') + let winids = nvim_list_wins() + else + let winids = map(getwininfo(), 'v:val["winid"]') endif + return uniq(map(winids, 'winbufnr(v:val)')) endfunction " Avoid errors @@ -35,22 +175,36 @@ function! coc#window#close(winid) abort if empty(a:winid) || a:winid == -1 return endif + if coc#float#valid(a:winid) + call coc#float#close(a:winid) + return + endif if exists('*nvim_win_is_valid') && exists('*nvim_win_close') if nvim_win_is_valid(a:winid) call nvim_win_close(a:winid, 1) endif - elseif exists('*win_execute') - call coc#compat#execute(a:winid, 'noa close!', 'silent!') else - let curr = win_getid() - if curr == a:winid - silent! close! - else - let res = win_gotoid(a:winid) - if res - silent! close! - call win_gotoid(curr) - endif - endif + call coc#compat#execute(a:winid, 'noa close!', 'silent!') endif endfunction + +function! coc#window#visible_range(bufnr) abort + let winid = bufwinid(a:bufnr) + if winid == -1 + return v:null + endif + let info = getwininfo(winid)[0] + return [info['topline'], info['botline']] +endfunction + +function! coc#window#visible_ranges(bufnr) abort + let wins = gettabinfo(tabpagenr())[0]['windows'] + let res = [] + for id in wins + let info = getwininfo(id)[0] + if info['bufnr'] == a:bufnr + call add(res, [info['topline'], info['botline']]) + endif + endfor + return res +endfunction diff --git a/vim-config/plugins/coc.nvim/autoload/health/coc.vim b/vim-config/plugins/coc.nvim/autoload/health/coc.vim index 8daa6b80..24fbab41 100644 --- a/vim-config/plugins/coc.nvim/autoload/health/coc.vim +++ b/vim-config/plugins/coc.nvim/autoload/health/coc.vim @@ -1,12 +1,23 @@ scriptencoding utf-8 let s:root = expand(':h:h:h') -function! s:checkEnvironment() abort - let valid = 1 - if !has('nvim-0.3.0') - let valid = 0 - call health#report_error('Neovim version not satisfied, 0.3.0 and above required') +function! s:checkVim(test, name, patchlevel) abort + if a:test + if !has(a:patchlevel) + call health#report_error(a:name . ' version not satisfied, ' . a:patchlevel . ' and above required') + return 0 + else + call health#report_ok(a:name . ' version satisfied') + return 1 + endif endif + return 0 +endfunction + +function! s:checkEnvironment() abort + let valid + \ = s:checkVim(has('nvim'), 'nvim', 'nvim-0.4.0') + \ + s:checkVim(!has('nvim'), 'vim', 'patch-8.1.1719') let node = get(g:, 'coc_node_path', $COC_NODE_PATH == '' ? 'node' : $COC_NODE_PATH) if !executable(node) let valid = 0 @@ -21,9 +32,9 @@ function! s:checkEnvironment() abort if empty(ms) let valid = 0 call health#report_error('Unable to detect version of node, make sure your node executable is http://nodejs.org/') - elseif str2nr(ms[1]) < 12 || (str2nr(ms[1]) == 12 && str2nr(ms[2]) < 12) + elseif str2nr(ms[1]) < 14 || (str2nr(ms[1]) == 14 && str2nr(ms[2]) < 14) let valid = 0 - call health#report_warn('Node.js version '.trim(output).' < 12.12.0, please upgrade node.js') + call health#report_warn('Node.js version '.trim(output).' < 14.14.0, please upgrade node.js') endif if valid call health#report_ok('Environment check passed') @@ -33,6 +44,9 @@ function! s:checkEnvironment() abort silent pyx print("") catch /.*/ call health#report_warn('pyx command not work, some extensions may fail to work, checkout ":h pythonx"') + if has('nvim') + call health#report_warn('Install pynvim by command: pip install pynvim --upgrade') + endif endtry endif return valid @@ -66,7 +80,7 @@ function! s:checkAutocmd() endfor endfunction -function! s:checkInitailize() abort +function! s:checkInitialize() abort if coc#client#is_running('coc') call health#report_ok('Service started') return 1 @@ -81,6 +95,6 @@ endfunction function! health#coc#check() abort call s:checkEnvironment() call s:checkCommand() - call s:checkInitailize() + call s:checkInitialize() call s:checkAutocmd() endfunction diff --git a/vim-config/plugins/coc.nvim/bin/fuzzy.wasm b/vim-config/plugins/coc.nvim/bin/fuzzy.wasm new file mode 100755 index 00000000..d59592e5 Binary files /dev/null and b/vim-config/plugins/coc.nvim/bin/fuzzy.wasm differ diff --git a/vim-config/plugins/coc.nvim/bin/prompt.js b/vim-config/plugins/coc.nvim/bin/prompt.js index 2361a58e..c4549975 100644 --- a/vim-config/plugins/coc.nvim/bin/prompt.js +++ b/vim-config/plugins/coc.nvim/bin/prompt.js @@ -5,45 +5,90 @@ const readline = require("readline") const rl = readline.createInterface({ input: process.stdin, output: process.stdout, - escapeCodeTimeout: 0 + terminal: true, + escapeCodeTimeout: 0, + prompt: '' }) -rl.setPrompt('') + let value = process.argv[2] +let placeholder = process.argv[3] +let clear = false if (value) { rl.write(value) +} else if (placeholder) { + clear = true + rl.write('\x1B[90m' + placeholder + '\x1B[39m') + rl.write('', {ctrl: true, name: 'a'}) } rl.on('line', input => { - let text = input.replace(/"/g, '\\"') - console.log(createSequences(JSON.stringify(['call', 'CocPopupCallback', ['confirm', text]]))) + send(['confirm', clear ? '' : input]) process.exit() }) +let original_ttyWrite = rl._ttyWrite +rl._ttyWrite = function (code, key) { + if (key.name === 'enter') { + send(['send', '']) + return '' + } + original_ttyWrite.apply(rl, arguments) + if (clear && rl.line.includes('\x1B')) { + clear = false + rl.write('', {ctrl: true, name: 'k'}) + return + } + send(['change', rl.line]) +} + function createSequences(str) { return '\033]51;' + str + '\x07' } -process.stdin.on('keypress', (_, key) => { +function send(args) { + process.stdout.write(createSequences(JSON.stringify(['call', 'CocPopupCallback', args]))) +} + +process.stdin.on('keypress', (e, key) => { if (key) { let k = getKey(key) if (k == '') { return } - if (k == '') { - process.exit() - return - } if (k == '') { - console.log(createSequences(JSON.stringify(['call', 'CocPopupCallback', ['exit', '']]))) + send(['exit', '']) process.exit() - return } if (k) { - console.log(createSequences(JSON.stringify(['call', 'CocPopupCallback', ['send', k]]))) + send(['send', k]) + return } } }) function getKey(key) { + if (key.ctrl === true) { + if (key.name == 'n') { + return '' + } + if (key.name == 'p') { + return '' + } + if (key.name == 'j') { + return '' + } + if (key.name == 'k') { + return '' + } + if (key.name == 'f') { + return '' + } + if (key.name == 'b') { + return '' + } + if (key.sequence == '\x00') { + return '' + } + } if (key.sequence == '\u001b') { return '' } @@ -53,16 +98,6 @@ function getKey(key) { if (key.sequence == '\t') { return key.shift ? '' : '' } - // handle them can cause bug with terminal - // if (key.name == 'backspace') { - // return '' - // } - // if (key.name == 'left') { - // return '' - // } - // if (key.name == 'right') { - // return '' - // } if (key.name == 'up') { return '' } diff --git a/vim-config/plugins/coc.nvim/bin/strwidth.wasm b/vim-config/plugins/coc.nvim/bin/strwidth.wasm new file mode 100755 index 00000000..c5eb6264 Binary files /dev/null and b/vim-config/plugins/coc.nvim/bin/strwidth.wasm differ diff --git a/vim-config/plugins/coc.nvim/build/index.js b/vim-config/plugins/coc.nvim/build/index.js index ba483823..e68d9f23 100644 --- a/vim-config/plugins/coc.nvim/build/index.js +++ b/vim-config/plugins/coc.nvim/build/index.js @@ -1,68537 +1,280 @@ -(function () { - var v = process.version - var parts = v.slice(1).split('.') - var major = parseInt(parts[0], 10) - var minor = parseInt(parts[1], 10) - if (major < 12 || (major == 12 && minor < 12)) { - throw new Error('coc.nvim requires node >= v12.12.0, current version: ' + v) - } -})(); -var __create = Object.create; -var __defProp = Object.defineProperty; -var __defProps = Object.defineProperties; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropDescs = Object.getOwnPropertyDescriptors; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getOwnPropSymbols = Object.getOwnPropertySymbols; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __propIsEnum = Object.prototype.propertyIsEnumerable; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp.call(b, prop)) - __defNormalProp(a, prop, b[prop]); - if (__getOwnPropSymbols) - for (var prop of __getOwnPropSymbols(b)) { - if (__propIsEnum.call(b, prop)) - __defNormalProp(a, prop, b[prop]); - } - return a; -}; -var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); -var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[Object.keys(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - __markAsModule(target); - for (var name2 in all) - __defProp(target, name2, { get: all[name2], enumerable: true }); -}; -var __reExport = (target, module2, desc) => { - if (module2 && typeof module2 === "object" || typeof module2 === "function") { - for (let key of __getOwnPropNames(module2)) - if (!__hasOwnProp.call(target, key) && key !== "default") - __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable }); - } - return target; -}; -var __toModule = (module2) => { - return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2); -}; -var __decorateClass = (decorators, target, key, kind) => { - var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; - for (var i = decorators.length - 1, decorator; i >= 0; i--) - if (decorator = decorators[i]) - result = (kind ? decorator(target, key, result) : decorator(result)) || result; - if (kind && result) - __defProp(target, key, result); - return result; -}; - -// node_modules/ms/index.js -var require_ms = __commonJS({ - "node_modules/ms/index.js"(exports2, module2) { - var s = 1e3; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - module2.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === "string" && val.length > 0) { - return parse5(val); - } else if (type === "number" && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val)); - }; - function parse5(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || "ms").toLowerCase(); - switch (type) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y; - case "weeks": - case "week": - case "w": - return n * w; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return void 0; - } - } - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + "d"; - } - if (msAbs >= h) { - return Math.round(ms / h) + "h"; - } - if (msAbs >= m) { - return Math.round(ms / m) + "m"; - } - if (msAbs >= s) { - return Math.round(ms / s) + "s"; - } - return ms + "ms"; - } - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, "day"); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, "hour"); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, "minute"); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, "second"); - } - return ms + " ms"; - } - function plural(ms, msAbs, n, name2) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + " " + name2 + (isPlural ? "s" : ""); - } - } -}); - -// node_modules/debug/src/common.js -var require_common = __commonJS({ - "node_modules/debug/src/common.js"(exports2, module2) { - function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require_ms(); - createDebug.destroy = destroy; - Object.keys(env).forEach((key) => { - createDebug[key] = env[key]; - }); - createDebug.names = []; - createDebug.skips = []; - createDebug.formatters = {}; - function selectColor(namespace) { - let hash = 0; - for (let i = 0; i < namespace.length; i++) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; - } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug(...args) { - if (!debug.enabled) { - return; - } - const self2 = debug; - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self2.diff = ms; - self2.prev = prevTime; - self2.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== "string") { - args.unshift("%O"); - } - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format2) => { - if (match === "%%") { - return "%"; - } - index++; - const formatter2 = createDebug.formatters[format2]; - if (typeof formatter2 === "function") { - const val = args[index]; - match = formatter2.call(self2, val); - args.splice(index, 1); - index--; - } - return match; - }); - createDebug.formatArgs.call(self2, args); - const logFn = self2.log || createDebug.log; - logFn.apply(self2, args); - } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; - Object.defineProperty(debug, "enabled", { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - return enabledCache; - }, - set: (v) => { - enableOverride = v; - } - }); - if (typeof createDebug.init === "function") { - createDebug.init(debug); - } - return debug; - } - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - let i; - const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/); - const len = split.length; - for (i = 0; i < len; i++) { - if (!split[i]) { - continue; - } - namespaces = split[i].replace(/\*/g, ".*?"); - if (namespaces[0] === "-") { - createDebug.skips.push(new RegExp("^" + namespaces.substr(1) + "$")); - } else { - createDebug.names.push(new RegExp("^" + namespaces + "$")); - } - } - } - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace) - ].join(","); - createDebug.enable(""); - return namespaces; - } - function enabled(name2) { - if (name2[name2.length - 1] === "*") { - return true; - } - let i; - let len; - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name2)) { - return false; - } - } - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name2)) { - return true; - } - } - return false; - } - function toNamespace(regexp) { - return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*"); - } - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - function destroy() { - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - createDebug.enable(createDebug.load()); - return createDebug; - } - module2.exports = setup; - } -}); - -// node_modules/debug/src/browser.js -var require_browser = __commonJS({ - "node_modules/debug/src/browser.js"(exports2, module2) { - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load; - exports2.useColors = useColors; - exports2.storage = localstorage(); - exports2.destroy = (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - }; - })(); - exports2.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33" - ]; - function useColors() { - if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { - return true; - } - if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); - } - function formatArgs(args) { - args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); - if (!this.useColors) { - return; - } - const c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match) => { - if (match === "%%") { - return; - } - index++; - if (match === "%c") { - lastC = index; - } - }); - args.splice(lastC, 0, c); - } - exports2.log = console.debug || console.log || (() => { - }); - function save(namespaces) { - try { - if (namespaces) { - exports2.storage.setItem("debug", namespaces); - } else { - exports2.storage.removeItem("debug"); - } - } catch (error) { - } - } - function load() { - let r; - try { - r = exports2.storage.getItem("debug"); - } catch (error) { - } - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; - } - return r; - } - function localstorage() { - try { - return localStorage; - } catch (error) { - } - } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (error) { - return "[UnexpectedJSONParseError]: " + error.message; - } - }; - } -}); - -// node_modules/has-flag/index.js -var require_has_flag = __commonJS({ - "node_modules/has-flag/index.js"(exports2, module2) { - "use strict"; - module2.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf("--"); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); - }; - } -}); - -// node_modules/supports-color/index.js -var require_supports_color = __commonJS({ - "node_modules/supports-color/index.js"(exports2, module2) { - "use strict"; - var os10 = require("os"); - var tty = require("tty"); - var hasFlag = require_has_flag(); - var { env } = process; - var forceColor; - if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { - forceColor = 0; - } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { - forceColor = 1; - } - if ("FORCE_COLOR" in env) { - if (env.FORCE_COLOR === "true") { - forceColor = 1; - } else if (env.FORCE_COLOR === "false") { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } - } - function translateLevel(level) { - if (level === 0) { - return false; - } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; - } - function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } - if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { - return 3; - } - if (hasFlag("color=256")) { - return 2; - } - if (haveStream && !streamIsTTY && forceColor === void 0) { - return 0; - } - const min = forceColor || 0; - if (env.TERM === "dumb") { - return min; - } - if (process.platform === "win32") { - const osRelease = os10.release().split("."); - if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - return 1; - } - if ("CI" in env) { - if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { - return 1; - } - return min; - } - if ("TEAMCITY_VERSION" in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - if (env.COLORTERM === "truecolor") { - return 3; - } - if ("TERM_PROGRAM" in env) { - const version2 = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); - switch (env.TERM_PROGRAM) { - case "iTerm.app": - return version2 >= 3 ? 3 : 2; - case "Apple_Terminal": - return 2; - } - } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - if ("COLORTERM" in env) { - return 1; - } - return min; - } - function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); - } - module2.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) - }; - } -}); - -// node_modules/debug/src/node.js -var require_node = __commonJS({ - "node_modules/debug/src/node.js"(exports2, module2) { - var tty = require("tty"); - var util4 = require("util"); - exports2.init = init; - exports2.log = log; - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load; - exports2.useColors = useColors; - exports2.destroy = util4.deprecate(() => { - }, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - exports2.colors = [6, 2, 3, 4, 5, 1]; - try { - const supportsColor = require_supports_color(); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports2.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } - } catch (error) { - } - exports2.inspectOpts = Object.keys(process.env).filter((key) => { - return /^debug_/i.test(key); - }).reduce((obj, key) => { - const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === "null") { - val = null; - } else { - val = Number(val); - } - obj[prop] = val; - return obj; - }, {}); - function useColors() { - return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); - } - function formatArgs(args) { - const { namespace: name2, useColors: useColors2 } = this; - if (useColors2) { - const c = this.color; - const colorCode = "[3" + (c < 8 ? c : "8;5;" + c); - const prefix = ` ${colorCode};1m${name2} `; - args[0] = prefix + args[0].split("\n").join("\n" + prefix); - args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + ""); - } else { - args[0] = getDate() + name2 + " " + args[0]; - } - } - function getDate() { - if (exports2.inspectOpts.hideDate) { - return ""; - } - return new Date().toISOString() + " "; - } - function log(...args) { - return process.stderr.write(util4.format(...args) + "\n"); - } - function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - delete process.env.DEBUG; - } - } - function load() { - return process.env.DEBUG; - } - function init(debug) { - debug.inspectOpts = {}; - const keys = Object.keys(exports2.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; - } - } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util4.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); - }; - formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util4.inspect(v, this.inspectOpts); - }; - } -}); - -// node_modules/debug/src/index.js -var require_src = __commonJS({ - "node_modules/debug/src/index.js"(exports2, module2) { - if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { - module2.exports = require_browser(); - } else { - module2.exports = require_node(); - } - } -}); - -// node_modules/rfdc/index.js -var require_rfdc = __commonJS({ - "node_modules/rfdc/index.js"(exports2, module2) { - "use strict"; - module2.exports = rfdc; - function copyBuffer(cur) { - if (cur instanceof Buffer) { - return Buffer.from(cur); - } - return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length); - } - function rfdc(opts) { - opts = opts || {}; - if (opts.circles) - return rfdcCircles(opts); - return opts.proto ? cloneProto : clone; - function cloneArray(a, fn) { - var keys = Object.keys(a); - var a2 = new Array(keys.length); - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - var cur = a[k]; - if (typeof cur !== "object" || cur === null) { - a2[k] = cur; - } else if (cur instanceof Date) { - a2[k] = new Date(cur); - } else if (ArrayBuffer.isView(cur)) { - a2[k] = copyBuffer(cur); - } else { - a2[k] = fn(cur); - } - } - return a2; - } - function clone(o) { - if (typeof o !== "object" || o === null) - return o; - if (o instanceof Date) - return new Date(o); - if (Array.isArray(o)) - return cloneArray(o, clone); - if (o instanceof Map) - return new Map(cloneArray(Array.from(o), clone)); - if (o instanceof Set) - return new Set(cloneArray(Array.from(o), clone)); - var o2 = {}; - for (var k in o) { - if (Object.hasOwnProperty.call(o, k) === false) - continue; - var cur = o[k]; - if (typeof cur !== "object" || cur === null) { - o2[k] = cur; - } else if (cur instanceof Date) { - o2[k] = new Date(cur); - } else if (cur instanceof Map) { - o2[k] = new Map(cloneArray(Array.from(cur), clone)); - } else if (cur instanceof Set) { - o2[k] = new Set(cloneArray(Array.from(cur), clone)); - } else if (ArrayBuffer.isView(cur)) { - o2[k] = copyBuffer(cur); - } else { - o2[k] = clone(cur); - } - } - return o2; - } - function cloneProto(o) { - if (typeof o !== "object" || o === null) - return o; - if (o instanceof Date) - return new Date(o); - if (Array.isArray(o)) - return cloneArray(o, cloneProto); - if (o instanceof Map) - return new Map(cloneArray(Array.from(o), cloneProto)); - if (o instanceof Set) - return new Set(cloneArray(Array.from(o), cloneProto)); - var o2 = {}; - for (var k in o) { - var cur = o[k]; - if (typeof cur !== "object" || cur === null) { - o2[k] = cur; - } else if (cur instanceof Date) { - o2[k] = new Date(cur); - } else if (cur instanceof Map) { - o2[k] = new Map(cloneArray(Array.from(cur), cloneProto)); - } else if (cur instanceof Set) { - o2[k] = new Set(cloneArray(Array.from(cur), cloneProto)); - } else if (ArrayBuffer.isView(cur)) { - o2[k] = copyBuffer(cur); - } else { - o2[k] = cloneProto(cur); - } - } - return o2; - } - } - function rfdcCircles(opts) { - var refs = []; - var refsNew = []; - return opts.proto ? cloneProto : clone; - function cloneArray(a, fn) { - var keys = Object.keys(a); - var a2 = new Array(keys.length); - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - var cur = a[k]; - if (typeof cur !== "object" || cur === null) { - a2[k] = cur; - } else if (cur instanceof Date) { - a2[k] = new Date(cur); - } else if (ArrayBuffer.isView(cur)) { - a2[k] = copyBuffer(cur); - } else { - var index = refs.indexOf(cur); - if (index !== -1) { - a2[k] = refsNew[index]; - } else { - a2[k] = fn(cur); - } - } - } - return a2; - } - function clone(o) { - if (typeof o !== "object" || o === null) - return o; - if (o instanceof Date) - return new Date(o); - if (Array.isArray(o)) - return cloneArray(o, clone); - if (o instanceof Map) - return new Map(cloneArray(Array.from(o), clone)); - if (o instanceof Set) - return new Set(cloneArray(Array.from(o), clone)); - var o2 = {}; - refs.push(o); - refsNew.push(o2); - for (var k in o) { - if (Object.hasOwnProperty.call(o, k) === false) - continue; - var cur = o[k]; - if (typeof cur !== "object" || cur === null) { - o2[k] = cur; - } else if (cur instanceof Date) { - o2[k] = new Date(cur); - } else if (cur instanceof Map) { - o2[k] = new Map(cloneArray(Array.from(cur), clone)); - } else if (cur instanceof Set) { - o2[k] = new Set(cloneArray(Array.from(cur), clone)); - } else if (ArrayBuffer.isView(cur)) { - o2[k] = copyBuffer(cur); - } else { - var i = refs.indexOf(cur); - if (i !== -1) { - o2[k] = refsNew[i]; - } else { - o2[k] = clone(cur); - } - } - } - refs.pop(); - refsNew.pop(); - return o2; - } - function cloneProto(o) { - if (typeof o !== "object" || o === null) - return o; - if (o instanceof Date) - return new Date(o); - if (Array.isArray(o)) - return cloneArray(o, cloneProto); - if (o instanceof Map) - return new Map(cloneArray(Array.from(o), cloneProto)); - if (o instanceof Set) - return new Set(cloneArray(Array.from(o), cloneProto)); - var o2 = {}; - refs.push(o); - refsNew.push(o2); - for (var k in o) { - var cur = o[k]; - if (typeof cur !== "object" || cur === null) { - o2[k] = cur; - } else if (cur instanceof Date) { - o2[k] = new Date(cur); - } else if (cur instanceof Map) { - o2[k] = new Map(cloneArray(Array.from(cur), cloneProto)); - } else if (cur instanceof Set) { - o2[k] = new Set(cloneArray(Array.from(cur), cloneProto)); - } else if (ArrayBuffer.isView(cur)) { - o2[k] = copyBuffer(cur); - } else { - var i = refs.indexOf(cur); - if (i !== -1) { - o2[k] = refsNew[i]; - } else { - o2[k] = cloneProto(cur); - } - } - } - refs.pop(); - refsNew.pop(); - return o2; - } - } - } -}); - -// node_modules/log4js/lib/configuration.js -var require_configuration = __commonJS({ - "node_modules/log4js/lib/configuration.js"(exports2, module2) { - var util4 = require("util"); - var debug = require_src()("log4js:configuration"); - var preProcessingListeners = []; - var listeners = []; - var not = (thing) => !thing; - var anObject = (thing) => thing && typeof thing === "object" && !Array.isArray(thing); - var validIdentifier = (thing) => /^[A-Za-z][A-Za-z0-9_]*$/g.test(thing); - var anInteger = (thing) => thing && typeof thing === "number" && Number.isInteger(thing); - var addListener = (fn) => { - listeners.push(fn); - debug(`Added listener, now ${listeners.length} listeners`); - }; - var addPreProcessingListener = (fn) => { - preProcessingListeners.push(fn); - debug(`Added pre-processing listener, now ${preProcessingListeners.length} listeners`); - }; - var throwExceptionIf = (config, checks, message) => { - const tests = Array.isArray(checks) ? checks : [checks]; - tests.forEach((test) => { - if (test) { - throw new Error(`Problem with log4js configuration: (${util4.inspect(config, { depth: 5 })}) - ${message}`); - } - }); - }; - var configure = (candidate) => { - debug("New configuration to be validated: ", candidate); - throwExceptionIf(candidate, not(anObject(candidate)), "must be an object."); - debug(`Calling pre-processing listeners (${preProcessingListeners.length})`); - preProcessingListeners.forEach((listener) => listener(candidate)); - debug("Configuration pre-processing finished."); - debug(`Calling configuration listeners (${listeners.length})`); - listeners.forEach((listener) => listener(candidate)); - debug("Configuration finished."); - }; - module2.exports = { - configure, - addListener, - addPreProcessingListener, - throwExceptionIf, - anObject, - anInteger, - validIdentifier, - not - }; - } -}); - -// node_modules/date-format/lib/index.js -var require_lib = __commonJS({ - "node_modules/date-format/lib/index.js"(exports2, module2) { - "use strict"; - function padWithZeros(vNumber, width) { - var numAsString = vNumber.toString(); - while (numAsString.length < width) { - numAsString = "0" + numAsString; - } - return numAsString; - } - function addZero(vNumber) { - return padWithZeros(vNumber, 2); - } - function offset(timezoneOffset) { - var os10 = Math.abs(timezoneOffset); - var h = String(Math.floor(os10 / 60)); - var m = String(os10 % 60); - if (h.length === 1) { - h = "0" + h; - } - if (m.length === 1) { - m = "0" + m; - } - return timezoneOffset < 0 ? "+" + h + m : "-" + h + m; - } - function asString(format2, date) { - if (typeof format2 !== "string") { - date = format2; - format2 = module2.exports.ISO8601_FORMAT; - } - if (!date) { - date = module2.exports.now(); - } - var vDay = addZero(date.getDate()); - var vMonth = addZero(date.getMonth() + 1); - var vYearLong = addZero(date.getFullYear()); - var vYearShort = addZero(vYearLong.substring(2, 4)); - var vYear = format2.indexOf("yyyy") > -1 ? vYearLong : vYearShort; - var vHour = addZero(date.getHours()); - var vMinute = addZero(date.getMinutes()); - var vSecond = addZero(date.getSeconds()); - var vMillisecond = padWithZeros(date.getMilliseconds(), 3); - var vTimeZone = offset(date.getTimezoneOffset()); - var formatted = format2.replace(/dd/g, vDay).replace(/MM/g, vMonth).replace(/y{1,4}/g, vYear).replace(/hh/g, vHour).replace(/mm/g, vMinute).replace(/ss/g, vSecond).replace(/SSS/g, vMillisecond).replace(/O/g, vTimeZone); - return formatted; - } - function setDatePart(date, part, value, local) { - date["set" + (local ? "" : "UTC") + part](value); - } - function extractDateParts(pattern, str, missingValuesDate) { - var local = pattern.indexOf("O") < 0; - var matchers = [ - { - pattern: /y{1,4}/, - regexp: "\\d{1,4}", - fn: function(date2, value) { - setDatePart(date2, "FullYear", value, local); - } - }, - { - pattern: /MM/, - regexp: "\\d{1,2}", - fn: function(date2, value) { - setDatePart(date2, "Month", value - 1, local); - } - }, - { - pattern: /dd/, - regexp: "\\d{1,2}", - fn: function(date2, value) { - setDatePart(date2, "Date", value, local); - } - }, - { - pattern: /hh/, - regexp: "\\d{1,2}", - fn: function(date2, value) { - setDatePart(date2, "Hours", value, local); - } - }, - { - pattern: /mm/, - regexp: "\\d\\d", - fn: function(date2, value) { - setDatePart(date2, "Minutes", value, local); - } - }, - { - pattern: /ss/, - regexp: "\\d\\d", - fn: function(date2, value) { - setDatePart(date2, "Seconds", value, local); - } - }, - { - pattern: /SSS/, - regexp: "\\d\\d\\d", - fn: function(date2, value) { - setDatePart(date2, "Milliseconds", value, local); - } - }, - { - pattern: /O/, - regexp: "[+-]\\d{3,4}|Z", - fn: function(date2, value) { - if (value === "Z") { - value = 0; - } - var offset2 = Math.abs(value); - var timezoneOffset = (value > 0 ? -1 : 1) * (offset2 % 100 + Math.floor(offset2 / 100) * 60); - date2.setUTCMinutes(date2.getUTCMinutes() + timezoneOffset); - } - } - ]; - var parsedPattern = matchers.reduce(function(p, m) { - if (m.pattern.test(p.regexp)) { - m.index = p.regexp.match(m.pattern).index; - p.regexp = p.regexp.replace(m.pattern, "(" + m.regexp + ")"); - } else { - m.index = -1; - } - return p; - }, { regexp: pattern, index: [] }); - var dateFns = matchers.filter(function(m) { - return m.index > -1; - }); - dateFns.sort(function(a, b) { - return a.index - b.index; - }); - var matcher = new RegExp(parsedPattern.regexp); - var matches = matcher.exec(str); - if (matches) { - var date = missingValuesDate || module2.exports.now(); - dateFns.forEach(function(f, i) { - f.fn(date, matches[i + 1]); - }); - return date; - } - throw new Error("String '" + str + "' could not be parsed as '" + pattern + "'"); - } - function parse5(pattern, str, missingValuesDate) { - if (!pattern) { - throw new Error("pattern must be supplied"); - } - return extractDateParts(pattern, str, missingValuesDate); - } - function now() { - return new Date(); - } - module2.exports = asString; - module2.exports.asString = asString; - module2.exports.parse = parse5; - module2.exports.now = now; - module2.exports.ISO8601_FORMAT = "yyyy-MM-ddThh:mm:ss.SSS"; - module2.exports.ISO8601_WITH_TZ_OFFSET_FORMAT = "yyyy-MM-ddThh:mm:ss.SSSO"; - module2.exports.DATETIME_FORMAT = "dd MM yyyy hh:mm:ss.SSS"; - module2.exports.ABSOLUTETIME_FORMAT = "hh:mm:ss.SSS"; - } -}); - -// node_modules/log4js/lib/layouts.js -var require_layouts = __commonJS({ - "node_modules/log4js/lib/layouts.js"(exports2, module2) { - var dateFormat = require_lib(); - var os10 = require("os"); - var util4 = require("util"); - var path36 = require("path"); - var styles3 = { - bold: [1, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - white: [37, 39], - grey: [90, 39], - black: [90, 39], - blue: [34, 39], - cyan: [36, 39], - green: [32, 39], - magenta: [35, 39], - red: [91, 39], - yellow: [33, 39] - }; - function colorizeStart(style2) { - return style2 ? `[${styles3[style2][0]}m` : ""; - } - function colorizeEnd(style2) { - return style2 ? `[${styles3[style2][1]}m` : ""; - } - function colorize(str, style2) { - return colorizeStart(style2) + str + colorizeEnd(style2); - } - function timestampLevelAndCategory(loggingEvent, colour) { - return colorize(util4.format("[%s] [%s] %s - ", dateFormat.asString(loggingEvent.startTime), loggingEvent.level.toString(), loggingEvent.categoryName), colour); - } - function basicLayout(loggingEvent) { - return timestampLevelAndCategory(loggingEvent) + util4.format(...loggingEvent.data); - } - function colouredLayout(loggingEvent) { - return timestampLevelAndCategory(loggingEvent, loggingEvent.level.colour) + util4.format(...loggingEvent.data); - } - function messagePassThroughLayout(loggingEvent) { - return util4.format(...loggingEvent.data); - } - function dummyLayout(loggingEvent) { - return loggingEvent.data[0]; - } - function patternLayout(pattern, tokens) { - const TTCC_CONVERSION_PATTERN = "%r %p %c - %m%n"; - const regex = /%(-?[0-9]+)?(\.?-?[0-9]+)?([[\]cdhmnprzxXyflos%])(\{([^}]+)\})?|([^%]+)/; - pattern = pattern || TTCC_CONVERSION_PATTERN; - function categoryName(loggingEvent, specifier) { - let loggerName = loggingEvent.categoryName; - if (specifier) { - const precision = parseInt(specifier, 10); - const loggerNameBits = loggerName.split("."); - if (precision < loggerNameBits.length) { - loggerName = loggerNameBits.slice(loggerNameBits.length - precision).join("."); - } - } - return loggerName; - } - function formatAsDate(loggingEvent, specifier) { - let format2 = dateFormat.ISO8601_FORMAT; - if (specifier) { - format2 = specifier; - if (format2 === "ISO8601") { - format2 = dateFormat.ISO8601_FORMAT; - } else if (format2 === "ISO8601_WITH_TZ_OFFSET") { - format2 = dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT; - } else if (format2 === "ABSOLUTE") { - format2 = dateFormat.ABSOLUTETIME_FORMAT; - } else if (format2 === "DATE") { - format2 = dateFormat.DATETIME_FORMAT; - } - } - return dateFormat.asString(format2, loggingEvent.startTime); - } - function hostname() { - return os10.hostname().toString(); - } - function formatMessage(loggingEvent) { - return util4.format(...loggingEvent.data); - } - function endOfLine() { - return os10.EOL; - } - function logLevel(loggingEvent) { - return loggingEvent.level.toString(); - } - function startTime(loggingEvent) { - return dateFormat.asString("hh:mm:ss", loggingEvent.startTime); - } - function startColour(loggingEvent) { - return colorizeStart(loggingEvent.level.colour); - } - function endColour(loggingEvent) { - return colorizeEnd(loggingEvent.level.colour); - } - function percent() { - return "%"; - } - function pid(loggingEvent) { - return loggingEvent && loggingEvent.pid ? loggingEvent.pid.toString() : process.pid.toString(); - } - function clusterInfo() { - return pid(); - } - function userDefined(loggingEvent, specifier) { - if (typeof tokens[specifier] !== "undefined") { - return typeof tokens[specifier] === "function" ? tokens[specifier](loggingEvent) : tokens[specifier]; - } - return null; - } - function contextDefined(loggingEvent, specifier) { - const resolver = loggingEvent.context[specifier]; - if (typeof resolver !== "undefined") { - return typeof resolver === "function" ? resolver(loggingEvent) : resolver; - } - return null; - } - function fileName(loggingEvent, specifier) { - let filename = loggingEvent.fileName || ""; - if (specifier) { - const fileDepth = parseInt(specifier, 10); - const fileList = filename.split(path36.sep); - if (fileList.length > fileDepth) { - filename = fileList.slice(-fileDepth).join(path36.sep); - } - } - return filename; - } - function lineNumber(loggingEvent) { - return loggingEvent.lineNumber ? `${loggingEvent.lineNumber}` : ""; - } - function columnNumber(loggingEvent) { - return loggingEvent.columnNumber ? `${loggingEvent.columnNumber}` : ""; - } - function callStack(loggingEvent) { - return loggingEvent.callStack || ""; - } - const replacers = { - c: categoryName, - d: formatAsDate, - h: hostname, - m: formatMessage, - n: endOfLine, - p: logLevel, - r: startTime, - "[": startColour, - "]": endColour, - y: clusterInfo, - z: pid, - "%": percent, - x: userDefined, - X: contextDefined, - f: fileName, - l: lineNumber, - o: columnNumber, - s: callStack - }; - function replaceToken(conversionCharacter, loggingEvent, specifier) { - return replacers[conversionCharacter](loggingEvent, specifier); - } - function truncate(truncation, toTruncate) { - let len; - if (truncation) { - len = parseInt(truncation.substr(1), 10); - return len > 0 ? toTruncate.slice(0, len) : toTruncate.slice(len); - } - return toTruncate; - } - function pad2(padding, toPad) { - let len; - if (padding) { - if (padding.charAt(0) === "-") { - len = parseInt(padding.substr(1), 10); - while (toPad.length < len) { - toPad += " "; - } - } else { - len = parseInt(padding, 10); - while (toPad.length < len) { - toPad = ` ${toPad}`; - } - } - } - return toPad; - } - function truncateAndPad(toTruncAndPad, truncation, padding) { - let replacement = toTruncAndPad; - replacement = truncate(truncation, replacement); - replacement = pad2(padding, replacement); - return replacement; - } - return function(loggingEvent) { - let formattedString = ""; - let result; - let searchString = pattern; - while ((result = regex.exec(searchString)) !== null) { - const padding = result[1]; - const truncation = result[2]; - const conversionCharacter = result[3]; - const specifier = result[5]; - const text = result[6]; - if (text) { - formattedString += text.toString(); - } else { - const replacement = replaceToken(conversionCharacter, loggingEvent, specifier); - formattedString += truncateAndPad(replacement, truncation, padding); - } - searchString = searchString.substr(result.index + result[0].length); - } - return formattedString; - }; - } - var layoutMakers = { - messagePassThrough() { - return messagePassThroughLayout; - }, - basic() { - return basicLayout; - }, - colored() { - return colouredLayout; - }, - coloured() { - return colouredLayout; - }, - pattern(config) { - return patternLayout(config && config.pattern, config && config.tokens); - }, - dummy() { - return dummyLayout; - } - }; - module2.exports = { - basicLayout, - messagePassThroughLayout, - patternLayout, - colouredLayout, - coloredLayout: colouredLayout, - dummyLayout, - addLayout(name2, serializerGenerator) { - layoutMakers[name2] = serializerGenerator; - }, - layout(name2, config) { - return layoutMakers[name2] && layoutMakers[name2](config); - } - }; - } -}); - -// node_modules/log4js/lib/levels.js -var require_levels = __commonJS({ - "node_modules/log4js/lib/levels.js"(exports2, module2) { - var configuration = require_configuration(); - var validColours = [ - "white", - "grey", - "black", - "blue", - "cyan", - "green", - "magenta", - "red", - "yellow" - ]; - var Level = class { - constructor(level, levelStr, colour) { - this.level = level; - this.levelStr = levelStr; - this.colour = colour; - } - toString() { - return this.levelStr; - } - static getLevel(sArg, defaultLevel) { - if (!sArg) { - return defaultLevel; - } - if (sArg instanceof Level) { - return sArg; - } - if (sArg instanceof Object && sArg.levelStr) { - sArg = sArg.levelStr; - } - return Level[sArg.toString().toUpperCase()] || defaultLevel; - } - static addLevels(customLevels) { - if (customLevels) { - const levels = Object.keys(customLevels); - levels.forEach((l) => { - const levelStr = l.toUpperCase(); - Level[levelStr] = new Level(customLevels[l].value, levelStr, customLevels[l].colour); - const existingLevelIndex = Level.levels.findIndex((lvl) => lvl.levelStr === levelStr); - if (existingLevelIndex > -1) { - Level.levels[existingLevelIndex] = Level[levelStr]; - } else { - Level.levels.push(Level[levelStr]); - } - }); - Level.levels.sort((a, b) => a.level - b.level); - } - } - isLessThanOrEqualTo(otherLevel) { - if (typeof otherLevel === "string") { - otherLevel = Level.getLevel(otherLevel); - } - return this.level <= otherLevel.level; - } - isGreaterThanOrEqualTo(otherLevel) { - if (typeof otherLevel === "string") { - otherLevel = Level.getLevel(otherLevel); - } - return this.level >= otherLevel.level; - } - isEqualTo(otherLevel) { - if (typeof otherLevel === "string") { - otherLevel = Level.getLevel(otherLevel); - } - return this.level === otherLevel.level; - } - }; - Level.levels = []; - Level.addLevels({ - ALL: { value: Number.MIN_VALUE, colour: "grey" }, - TRACE: { value: 5e3, colour: "blue" }, - DEBUG: { value: 1e4, colour: "cyan" }, - INFO: { value: 2e4, colour: "green" }, - WARN: { value: 3e4, colour: "yellow" }, - ERROR: { value: 4e4, colour: "red" }, - FATAL: { value: 5e4, colour: "magenta" }, - MARK: { value: 9007199254740992, colour: "grey" }, - OFF: { value: Number.MAX_VALUE, colour: "grey" } - }); - configuration.addListener((config) => { - const levelConfig = config.levels; - if (levelConfig) { - configuration.throwExceptionIf(config, configuration.not(configuration.anObject(levelConfig)), "levels must be an object"); - const newLevels = Object.keys(levelConfig); - newLevels.forEach((l) => { - configuration.throwExceptionIf(config, configuration.not(configuration.validIdentifier(l)), `level name "${l}" is not a valid identifier (must start with a letter, only contain A-Z,a-z,0-9,_)`); - configuration.throwExceptionIf(config, configuration.not(configuration.anObject(levelConfig[l])), `level "${l}" must be an object`); - configuration.throwExceptionIf(config, configuration.not(levelConfig[l].value), `level "${l}" must have a 'value' property`); - configuration.throwExceptionIf(config, configuration.not(configuration.anInteger(levelConfig[l].value)), `level "${l}".value must have an integer value`); - configuration.throwExceptionIf(config, configuration.not(levelConfig[l].colour), `level "${l}" must have a 'colour' property`); - configuration.throwExceptionIf(config, configuration.not(validColours.indexOf(levelConfig[l].colour) > -1), `level "${l}".colour must be one of ${validColours.join(", ")}`); - }); - } - }); - configuration.addListener((config) => { - Level.addLevels(config.levels); - }); - module2.exports = Level; - } -}); - -// node_modules/flatted/esm/index.js -var esm_exports = {}; -__export(esm_exports, { - default: () => esm_default, - parse: () => parse, - stringify: () => stringify -}); -var Flatted, esm_default, parse, stringify; -var init_esm = __esm({ - "node_modules/flatted/esm/index.js"() { - Flatted = function(Primitive, primitive) { - var Flatted2 = { - parse: function parse5(text, reviver) { - var input = JSON.parse(text, Primitives).map(primitives); - var value = input[0]; - var $ = reviver || noop; - var tmp = typeof value === "object" && value ? revive(input, new Set(), value, $) : value; - return $.call({ "": tmp }, "", tmp); - }, - stringify: function stringify3(value, replacer, space) { - for (var firstRun, known = new Map(), input = [], output = [], $ = replacer && typeof replacer === typeof input ? function(k, v) { - if (k === "" || -1 < replacer.indexOf(k)) - return v; - } : replacer || noop, i = +set(known, input, $.call({ "": value }, "", value)), replace = function(key, value2) { - if (firstRun) { - firstRun = !firstRun; - return value2; - } - var after = $.call(this, key, value2); - switch (typeof after) { - case "object": - if (after === null) - return after; - case primitive: - return known.get(after) || set(known, input, after); - } - return after; - }; i < input.length; i++) { - firstRun = true; - output[i] = JSON.stringify(input[i], replace, space); - } - return "[" + output.join(",") + "]"; - } - }; - return Flatted2; - function noop(key, value) { - return value; - } - function revive(input, parsed, output, $) { - return Object.keys(output).reduce(function(output2, key) { - var value = output2[key]; - if (value instanceof Primitive) { - var tmp = input[value]; - if (typeof tmp === "object" && !parsed.has(tmp)) { - parsed.add(tmp); - output2[key] = $.call(output2, key, revive(input, parsed, tmp, $)); - } else { - output2[key] = $.call(output2, key, tmp); - } - } else - output2[key] = $.call(output2, key, value); - return output2; - }, output); - } - function set(known, input, value) { - var index = Primitive(input.push(value) - 1); - known.set(value, index); - return index; - } - function primitives(value) { - return value instanceof Primitive ? Primitive(value) : value; - } - function Primitives(key, value) { - return typeof value === primitive ? new Primitive(value) : value; - } - }(String, "string"); - esm_default = Flatted; - parse = Flatted.parse; - stringify = Flatted.stringify; - } -}); - -// node_modules/log4js/lib/LoggingEvent.js -var require_LoggingEvent = __commonJS({ - "node_modules/log4js/lib/LoggingEvent.js"(exports2, module2) { - var flatted = (init_esm(), esm_exports); - var levels = require_levels(); - var LoggingEvent = class { - constructor(categoryName, level, data, context, location) { - this.startTime = new Date(); - this.categoryName = categoryName; - this.data = data; - this.level = level; - this.context = Object.assign({}, context); - this.pid = process.pid; - if (location) { - this.functionName = location.functionName; - this.fileName = location.fileName; - this.lineNumber = location.lineNumber; - this.columnNumber = location.columnNumber; - this.callStack = location.callStack; - } - } - serialise() { - const logData = this.data.map((e) => { - if (e && e.message && e.stack) { - e = Object.assign({ message: e.message, stack: e.stack }, e); - } - return e; - }); - this.data = logData; - return flatted.stringify(this); - } - static deserialise(serialised) { - let event; - try { - const rehydratedEvent = flatted.parse(serialised); - rehydratedEvent.data = rehydratedEvent.data.map((e) => { - if (e && e.message && e.stack) { - const fakeError = new Error(e); - Object.keys(e).forEach((key) => { - fakeError[key] = e[key]; - }); - e = fakeError; - } - return e; - }); - event = new LoggingEvent(rehydratedEvent.categoryName, levels.getLevel(rehydratedEvent.level.levelStr), rehydratedEvent.data, rehydratedEvent.context); - event.startTime = new Date(rehydratedEvent.startTime); - event.pid = rehydratedEvent.pid; - event.cluster = rehydratedEvent.cluster; - } catch (e) { - event = new LoggingEvent("log4js", levels.ERROR, ["Unable to parse log:", serialised, "because: ", e]); - } - return event; - } - }; - module2.exports = LoggingEvent; - } -}); - -// node_modules/log4js/lib/clustering.js -var require_clustering = __commonJS({ - "node_modules/log4js/lib/clustering.js"(exports2, module2) { - var debug = require_src()("log4js:clustering"); - var LoggingEvent = require_LoggingEvent(); - var configuration = require_configuration(); - var disabled = false; - var cluster = null; - try { - cluster = require("cluster"); - } catch (e) { - debug("cluster module not present"); - disabled = true; - } - var listeners = []; - var pm2 = false; - var pm2InstanceVar = "NODE_APP_INSTANCE"; - var isPM2Master = () => pm2 && process.env[pm2InstanceVar] === "0"; - var isMaster = () => disabled || cluster.isMaster || isPM2Master(); - var sendToListeners = (logEvent) => { - listeners.forEach((l) => l(logEvent)); - }; - var receiver = (worker, message) => { - debug("cluster message received from worker ", worker, ": ", message); - if (worker.topic && worker.data) { - message = worker; - worker = void 0; - } - if (message && message.topic && message.topic === "log4js:message") { - debug("received message: ", message.data); - const logEvent = LoggingEvent.deserialise(message.data); - sendToListeners(logEvent); - } - }; - if (!disabled) { - configuration.addListener((config) => { - listeners.length = 0; - ({ - pm2, - disableClustering: disabled, - pm2InstanceVar = "NODE_APP_INSTANCE" - } = config); - debug(`clustering disabled ? ${disabled}`); - debug(`cluster.isMaster ? ${cluster && cluster.isMaster}`); - debug(`pm2 enabled ? ${pm2}`); - debug(`pm2InstanceVar = ${pm2InstanceVar}`); - debug(`process.env[${pm2InstanceVar}] = ${process.env[pm2InstanceVar]}`); - if (pm2) { - process.removeListener("message", receiver); - } - if (cluster && cluster.removeListener) { - cluster.removeListener("message", receiver); - } - if (disabled || config.disableClustering) { - debug("Not listening for cluster messages, because clustering disabled."); - } else if (isPM2Master()) { - debug("listening for PM2 broadcast messages"); - process.on("message", receiver); - } else if (cluster.isMaster) { - debug("listening for cluster messages"); - cluster.on("message", receiver); - } else { - debug("not listening for messages, because we are not a master process"); - } - }); - } - module2.exports = { - onlyOnMaster: (fn, notMaster) => isMaster() ? fn() : notMaster, - isMaster, - send: (msg) => { - if (isMaster()) { - sendToListeners(msg); - } else { - if (!pm2) { - msg.cluster = { - workerId: cluster.worker.id, - worker: process.pid - }; - } - process.send({ topic: "log4js:message", data: msg.serialise() }); - } - }, - onMessage: (listener) => { - listeners.push(listener); - } - }; - } -}); - -// node_modules/log4js/lib/appenders/adapters.js -var require_adapters = __commonJS({ - "node_modules/log4js/lib/appenders/adapters.js"(exports2, module2) { - function maxFileSizeUnitTransform(maxLogSize) { - if (typeof maxLogSize === "number" && Number.isInteger(maxLogSize)) { - return maxLogSize; - } - const units = { - K: 1024, - M: 1024 * 1024, - G: 1024 * 1024 * 1024 - }; - const validUnit = Object.keys(units); - const unit = maxLogSize.substr(maxLogSize.length - 1).toLocaleUpperCase(); - const value = maxLogSize.substring(0, maxLogSize.length - 1).trim(); - if (validUnit.indexOf(unit) < 0 || !Number.isInteger(Number(value))) { - throw Error(`maxLogSize: "${maxLogSize}" is invalid`); - } else { - return value * units[unit]; - } - } - function adapter(configAdapter, config) { - const newConfig = Object.assign({}, config); - Object.keys(configAdapter).forEach((key) => { - if (newConfig[key]) { - newConfig[key] = configAdapter[key](config[key]); - } - }); - return newConfig; - } - function fileAppenderAdapter(config) { - const configAdapter = { - maxLogSize: maxFileSizeUnitTransform - }; - return adapter(configAdapter, config); - } - var adapters = { - file: fileAppenderAdapter, - fileSync: fileAppenderAdapter - }; - module2.exports.modifyConfig = (config) => adapters[config.type] ? adapters[config.type](config) : config; - } -}); - -// node_modules/log4js/lib/appenders/console.js -var require_console = __commonJS({ - "node_modules/log4js/lib/appenders/console.js"(exports2, module2) { - var consoleLog = console.log.bind(console); - function consoleAppender(layout, timezoneOffset) { - return (loggingEvent) => { - consoleLog(layout(loggingEvent, timezoneOffset)); - }; - } - function configure(config, layouts) { - let layout = layouts.colouredLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - return consoleAppender(layout, config.timezoneOffset); - } - module2.exports.configure = configure; - } -}); - -// node_modules/log4js/lib/appenders/stdout.js -var require_stdout = __commonJS({ - "node_modules/log4js/lib/appenders/stdout.js"(exports2) { - function stdoutAppender(layout, timezoneOffset) { - return (loggingEvent) => { - process.stdout.write(`${layout(loggingEvent, timezoneOffset)} -`); - }; - } - function configure(config, layouts) { - let layout = layouts.colouredLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - return stdoutAppender(layout, config.timezoneOffset); - } - exports2.configure = configure; - } -}); - -// node_modules/log4js/lib/appenders/stderr.js -var require_stderr = __commonJS({ - "node_modules/log4js/lib/appenders/stderr.js"(exports2, module2) { - function stderrAppender(layout, timezoneOffset) { - return (loggingEvent) => { - process.stderr.write(`${layout(loggingEvent, timezoneOffset)} -`); - }; - } - function configure(config, layouts) { - let layout = layouts.colouredLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - return stderrAppender(layout, config.timezoneOffset); - } - module2.exports.configure = configure; - } -}); - -// node_modules/log4js/lib/appenders/logLevelFilter.js -var require_logLevelFilter = __commonJS({ - "node_modules/log4js/lib/appenders/logLevelFilter.js"(exports2, module2) { - function logLevelFilter(minLevelString, maxLevelString, appender, levels) { - const minLevel = levels.getLevel(minLevelString); - const maxLevel = levels.getLevel(maxLevelString, levels.FATAL); - return (logEvent) => { - const eventLevel = logEvent.level; - if (eventLevel.isGreaterThanOrEqualTo(minLevel) && eventLevel.isLessThanOrEqualTo(maxLevel)) { - appender(logEvent); - } - }; - } - function configure(config, layouts, findAppender, levels) { - const appender = findAppender(config.appender); - return logLevelFilter(config.level, config.maxLevel, appender, levels); - } - module2.exports.configure = configure; - } -}); - -// node_modules/log4js/lib/appenders/categoryFilter.js -var require_categoryFilter = __commonJS({ - "node_modules/log4js/lib/appenders/categoryFilter.js"(exports2, module2) { - var debug = require_src()("log4js:categoryFilter"); - function categoryFilter(excludes, appender) { - if (typeof excludes === "string") - excludes = [excludes]; - return (logEvent) => { - debug(`Checking ${logEvent.categoryName} against ${excludes}`); - if (excludes.indexOf(logEvent.categoryName) === -1) { - debug("Not excluded, sending to appender"); - appender(logEvent); - } - }; - } - function configure(config, layouts, findAppender) { - const appender = findAppender(config.appender); - return categoryFilter(config.exclude, appender); - } - module2.exports.configure = configure; - } -}); - -// node_modules/log4js/lib/appenders/noLogFilter.js -var require_noLogFilter = __commonJS({ - "node_modules/log4js/lib/appenders/noLogFilter.js"(exports2, module2) { - var debug = require_src()("log4js:noLogFilter"); - function removeNullOrEmptyRegexp(regexp) { - const filtered = regexp.filter((el) => el != null && el !== ""); - return filtered; - } - function noLogFilter(filters, appender) { - return (logEvent) => { - debug(`Checking data: ${logEvent.data} against filters: ${filters}`); - if (typeof filters === "string") { - filters = [filters]; - } - filters = removeNullOrEmptyRegexp(filters); - const regex = new RegExp(filters.join("|"), "i"); - if (filters.length === 0 || logEvent.data.findIndex((value) => regex.test(value)) < 0) { - debug("Not excluded, sending to appender"); - appender(logEvent); - } - }; - } - function configure(config, layouts, findAppender) { - const appender = findAppender(config.appender); - return noLogFilter(config.exclude, appender); - } - module2.exports.configure = configure; - } -}); - -// node_modules/universalify/index.js -var require_universalify = __commonJS({ - "node_modules/universalify/index.js"(exports2) { - "use strict"; - exports2.fromCallback = function(fn) { - return Object.defineProperty(function() { - if (typeof arguments[arguments.length - 1] === "function") - fn.apply(this, arguments); - else { - return new Promise((resolve3, reject) => { - arguments[arguments.length] = (err, res) => { - if (err) - return reject(err); - resolve3(res); - }; - arguments.length++; - fn.apply(this, arguments); - }); - } - }, "name", { value: fn.name }); - }; - exports2.fromPromise = function(fn) { - return Object.defineProperty(function() { - const cb = arguments[arguments.length - 1]; - if (typeof cb !== "function") - return fn.apply(this, arguments); - else - fn.apply(this, arguments).then((r) => cb(null, r), cb); - }, "name", { value: fn.name }); - }; - } -}); - -// node_modules/graceful-fs/polyfills.js -var require_polyfills = __commonJS({ - "node_modules/graceful-fs/polyfills.js"(exports2, module2) { - var constants = require("constants"); - var origCwd = process.cwd; - var cwd = null; - var platform3 = process.env.GRACEFUL_FS_PLATFORM || process.platform; - process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process); - return cwd; - }; - try { - process.cwd(); - } catch (er) { - } - if (typeof process.chdir === "function") { - chdir = process.chdir; - process.chdir = function(d) { - cwd = null; - chdir.call(process, d); - }; - if (Object.setPrototypeOf) - Object.setPrototypeOf(process.chdir, chdir); - } - var chdir; - module2.exports = patch; - function patch(fs27) { - if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs27); - } - if (!fs27.lutimes) { - patchLutimes(fs27); - } - fs27.chown = chownFix(fs27.chown); - fs27.fchown = chownFix(fs27.fchown); - fs27.lchown = chownFix(fs27.lchown); - fs27.chmod = chmodFix(fs27.chmod); - fs27.fchmod = chmodFix(fs27.fchmod); - fs27.lchmod = chmodFix(fs27.lchmod); - fs27.chownSync = chownFixSync(fs27.chownSync); - fs27.fchownSync = chownFixSync(fs27.fchownSync); - fs27.lchownSync = chownFixSync(fs27.lchownSync); - fs27.chmodSync = chmodFixSync(fs27.chmodSync); - fs27.fchmodSync = chmodFixSync(fs27.fchmodSync); - fs27.lchmodSync = chmodFixSync(fs27.lchmodSync); - fs27.stat = statFix(fs27.stat); - fs27.fstat = statFix(fs27.fstat); - fs27.lstat = statFix(fs27.lstat); - fs27.statSync = statFixSync(fs27.statSync); - fs27.fstatSync = statFixSync(fs27.fstatSync); - fs27.lstatSync = statFixSync(fs27.lstatSync); - if (!fs27.lchmod) { - fs27.lchmod = function(path36, mode, cb) { - if (cb) - process.nextTick(cb); - }; - fs27.lchmodSync = function() { - }; - } - if (!fs27.lchown) { - fs27.lchown = function(path36, uid, gid, cb) { - if (cb) - process.nextTick(cb); - }; - fs27.lchownSync = function() { - }; - } - if (platform3 === "win32") { - fs27.rename = function(fs$rename) { - return function(from, to, cb) { - var start = Date.now(); - var backoff = 0; - fs$rename(from, to, function CB(er) { - if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < 6e4) { - setTimeout(function() { - fs27.stat(to, function(stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er); - }); - }, backoff); - if (backoff < 100) - backoff += 10; - return; - } - if (cb) - cb(er); - }); - }; - }(fs27.rename); - } - fs27.read = function(fs$read) { - function read(fd, buffer, offset, length, position, callback_) { - var callback; - if (callback_ && typeof callback_ === "function") { - var eagCounter = 0; - callback = function(er, _, __) { - if (er && er.code === "EAGAIN" && eagCounter < 10) { - eagCounter++; - return fs$read.call(fs27, fd, buffer, offset, length, position, callback); - } - callback_.apply(this, arguments); - }; - } - return fs$read.call(fs27, fd, buffer, offset, length, position, callback); - } - if (Object.setPrototypeOf) - Object.setPrototypeOf(read, fs$read); - return read; - }(fs27.read); - fs27.readSync = function(fs$readSync) { - return function(fd, buffer, offset, length, position) { - var eagCounter = 0; - while (true) { - try { - return fs$readSync.call(fs27, fd, buffer, offset, length, position); - } catch (er) { - if (er.code === "EAGAIN" && eagCounter < 10) { - eagCounter++; - continue; - } - throw er; - } - } - }; - }(fs27.readSync); - function patchLchmod(fs28) { - fs28.lchmod = function(path36, mode, callback) { - fs28.open(path36, constants.O_WRONLY | constants.O_SYMLINK, mode, function(err, fd) { - if (err) { - if (callback) - callback(err); - return; - } - fs28.fchmod(fd, mode, function(err2) { - fs28.close(fd, function(err22) { - if (callback) - callback(err2 || err22); - }); - }); - }); - }; - fs28.lchmodSync = function(path36, mode) { - var fd = fs28.openSync(path36, constants.O_WRONLY | constants.O_SYMLINK, mode); - var threw = true; - var ret; - try { - ret = fs28.fchmodSync(fd, mode); - threw = false; - } finally { - if (threw) { - try { - fs28.closeSync(fd); - } catch (er) { - } - } else { - fs28.closeSync(fd); - } - } - return ret; - }; - } - function patchLutimes(fs28) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs28.lutimes = function(path36, at, mt, cb) { - fs28.open(path36, constants.O_SYMLINK, function(er, fd) { - if (er) { - if (cb) - cb(er); - return; - } - fs28.futimes(fd, at, mt, function(er2) { - fs28.close(fd, function(er22) { - if (cb) - cb(er2 || er22); - }); - }); - }); - }; - fs28.lutimesSync = function(path36, at, mt) { - var fd = fs28.openSync(path36, constants.O_SYMLINK); - var ret; - var threw = true; - try { - ret = fs28.futimesSync(fd, at, mt); - threw = false; - } finally { - if (threw) { - try { - fs28.closeSync(fd); - } catch (er) { - } - } else { - fs28.closeSync(fd); - } - } - return ret; - }; - } else { - fs28.lutimes = function(_a2, _b, _c, cb) { - if (cb) - process.nextTick(cb); - }; - fs28.lutimesSync = function() { - }; - } - } - function chmodFix(orig) { - if (!orig) - return orig; - return function(target, mode, cb) { - return orig.call(fs27, target, mode, function(er) { - if (chownErOk(er)) - er = null; - if (cb) - cb.apply(this, arguments); - }); - }; - } - function chmodFixSync(orig) { - if (!orig) - return orig; - return function(target, mode) { - try { - return orig.call(fs27, target, mode); - } catch (er) { - if (!chownErOk(er)) - throw er; - } - }; - } - function chownFix(orig) { - if (!orig) - return orig; - return function(target, uid, gid, cb) { - return orig.call(fs27, target, uid, gid, function(er) { - if (chownErOk(er)) - er = null; - if (cb) - cb.apply(this, arguments); - }); - }; - } - function chownFixSync(orig) { - if (!orig) - return orig; - return function(target, uid, gid) { - try { - return orig.call(fs27, target, uid, gid); - } catch (er) { - if (!chownErOk(er)) - throw er; - } - }; - } - function statFix(orig) { - if (!orig) - return orig; - return function(target, options, cb) { - if (typeof options === "function") { - cb = options; - options = null; - } - function callback(er, stats) { - if (stats) { - if (stats.uid < 0) - stats.uid += 4294967296; - if (stats.gid < 0) - stats.gid += 4294967296; - } - if (cb) - cb.apply(this, arguments); - } - return options ? orig.call(fs27, target, options, callback) : orig.call(fs27, target, callback); - }; - } - function statFixSync(orig) { - if (!orig) - return orig; - return function(target, options) { - var stats = options ? orig.call(fs27, target, options) : orig.call(fs27, target); - if (stats.uid < 0) - stats.uid += 4294967296; - if (stats.gid < 0) - stats.gid += 4294967296; - return stats; - }; - } - function chownErOk(er) { - if (!er) - return true; - if (er.code === "ENOSYS") - return true; - var nonroot = !process.getuid || process.getuid() !== 0; - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true; - } - return false; - } - } - } -}); - -// node_modules/graceful-fs/legacy-streams.js -var require_legacy_streams = __commonJS({ - "node_modules/graceful-fs/legacy-streams.js"(exports2, module2) { - var Stream = require("stream").Stream; - module2.exports = legacy; - function legacy(fs27) { - return { - ReadStream, - WriteStream - }; - function ReadStream(path36, options) { - if (!(this instanceof ReadStream)) - return new ReadStream(path36, options); - Stream.call(this); - var self2 = this; - this.path = path36; - this.fd = null; - this.readable = true; - this.paused = false; - this.flags = "r"; - this.mode = 438; - this.bufferSize = 64 * 1024; - options = options || {}; - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - if (this.encoding) - this.setEncoding(this.encoding); - if (this.start !== void 0) { - if (typeof this.start !== "number") { - throw TypeError("start must be a Number"); - } - if (this.end === void 0) { - this.end = Infinity; - } else if (typeof this.end !== "number") { - throw TypeError("end must be a Number"); - } - if (this.start > this.end) { - throw new Error("start must be <= end"); - } - this.pos = this.start; - } - if (this.fd !== null) { - process.nextTick(function() { - self2._read(); - }); - return; - } - fs27.open(this.path, this.flags, this.mode, function(err, fd) { - if (err) { - self2.emit("error", err); - self2.readable = false; - return; - } - self2.fd = fd; - self2.emit("open", fd); - self2._read(); - }); - } - function WriteStream(path36, options) { - if (!(this instanceof WriteStream)) - return new WriteStream(path36, options); - Stream.call(this); - this.path = path36; - this.fd = null; - this.writable = true; - this.flags = "w"; - this.encoding = "binary"; - this.mode = 438; - this.bytesWritten = 0; - options = options || {}; - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - if (this.start !== void 0) { - if (typeof this.start !== "number") { - throw TypeError("start must be a Number"); - } - if (this.start < 0) { - throw new Error("start must be >= zero"); - } - this.pos = this.start; - } - this.busy = false; - this._queue = []; - if (this.fd === null) { - this._open = fs27.open; - this._queue.push([this._open, this.path, this.flags, this.mode, void 0]); - this.flush(); - } - } - } - } -}); - -// node_modules/graceful-fs/clone.js -var require_clone = __commonJS({ - "node_modules/graceful-fs/clone.js"(exports2, module2) { - "use strict"; - module2.exports = clone; - var getPrototypeOf = Object.getPrototypeOf || function(obj) { - return obj.__proto__; - }; - function clone(obj) { - if (obj === null || typeof obj !== "object") - return obj; - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) }; - else - var copy = Object.create(null); - Object.getOwnPropertyNames(obj).forEach(function(key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)); - }); - return copy; - } - } -}); - -// node_modules/graceful-fs/graceful-fs.js -var require_graceful_fs = __commonJS({ - "node_modules/graceful-fs/graceful-fs.js"(exports2, module2) { - var fs27 = require("fs"); - var polyfills = require_polyfills(); - var legacy = require_legacy_streams(); - var clone = require_clone(); - var util4 = require("util"); - var gracefulQueue; - var previousSymbol; - if (typeof Symbol === "function" && typeof Symbol.for === "function") { - gracefulQueue = Symbol.for("graceful-fs.queue"); - previousSymbol = Symbol.for("graceful-fs.previous"); - } else { - gracefulQueue = "___graceful-fs.queue"; - previousSymbol = "___graceful-fs.previous"; - } - function noop() { - } - function publishQueue(context, queue2) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue2; - } - }); - } - var debug = noop; - if (util4.debuglog) - debug = util4.debuglog("gfs4"); - else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) - debug = function() { - var m = util4.format.apply(util4, arguments); - m = "GFS4: " + m.split(/\n/).join("\nGFS4: "); - console.error(m); - }; - if (!fs27[gracefulQueue]) { - queue = global[gracefulQueue] || []; - publishQueue(fs27, queue); - fs27.close = function(fs$close) { - function close(fd, cb) { - return fs$close.call(fs27, fd, function(err) { - if (!err) { - retry(); - } - if (typeof cb === "function") - cb.apply(this, arguments); - }); - } - Object.defineProperty(close, previousSymbol, { - value: fs$close - }); - return close; - }(fs27.close); - fs27.closeSync = function(fs$closeSync) { - function closeSync(fd) { - fs$closeSync.apply(fs27, arguments); - retry(); - } - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }); - return closeSync; - }(fs27.closeSync); - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) { - process.on("exit", function() { - debug(fs27[gracefulQueue]); - require("assert").equal(fs27[gracefulQueue].length, 0); - }); - } - } - var queue; - if (!global[gracefulQueue]) { - publishQueue(global, fs27[gracefulQueue]); - } - module2.exports = patch(clone(fs27)); - if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs27.__patched) { - module2.exports = patch(fs27); - fs27.__patched = true; - } - function patch(fs28) { - polyfills(fs28); - fs28.gracefulify = patch; - fs28.createReadStream = createReadStream; - fs28.createWriteStream = createWriteStream; - var fs$readFile = fs28.readFile; - fs28.readFile = readFile2; - function readFile2(path36, options, cb) { - if (typeof options === "function") - cb = options, options = null; - return go$readFile(path36, options, cb); - function go$readFile(path37, options2, cb2) { - return fs$readFile(path37, options2, function(err) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$readFile, [path37, options2, cb2]]); - else { - if (typeof cb2 === "function") - cb2.apply(this, arguments); - retry(); - } - }); - } - } - var fs$writeFile = fs28.writeFile; - fs28.writeFile = writeFile2; - function writeFile2(path36, data, options, cb) { - if (typeof options === "function") - cb = options, options = null; - return go$writeFile(path36, data, options, cb); - function go$writeFile(path37, data2, options2, cb2) { - return fs$writeFile(path37, data2, options2, function(err) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$writeFile, [path37, data2, options2, cb2]]); - else { - if (typeof cb2 === "function") - cb2.apply(this, arguments); - retry(); - } - }); - } - } - var fs$appendFile = fs28.appendFile; - if (fs$appendFile) - fs28.appendFile = appendFile; - function appendFile(path36, data, options, cb) { - if (typeof options === "function") - cb = options, options = null; - return go$appendFile(path36, data, options, cb); - function go$appendFile(path37, data2, options2, cb2) { - return fs$appendFile(path37, data2, options2, function(err) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$appendFile, [path37, data2, options2, cb2]]); - else { - if (typeof cb2 === "function") - cb2.apply(this, arguments); - retry(); - } - }); - } - } - var fs$copyFile = fs28.copyFile; - if (fs$copyFile) - fs28.copyFile = copyFile; - function copyFile(src, dest, flags, cb) { - if (typeof flags === "function") { - cb = flags; - flags = 0; - } - return fs$copyFile(src, dest, flags, function(err) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([fs$copyFile, [src, dest, flags, cb]]); - else { - if (typeof cb === "function") - cb.apply(this, arguments); - retry(); - } - }); - } - var fs$readdir = fs28.readdir; - fs28.readdir = readdir; - function readdir(path36, options, cb) { - var args = [path36]; - if (typeof options !== "function") { - args.push(options); - } else { - cb = options; - } - args.push(go$readdir$cb); - return go$readdir(args); - function go$readdir$cb(err, files) { - if (files && files.sort) - files.sort(); - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$readdir, [args]]); - else { - if (typeof cb === "function") - cb.apply(this, arguments); - retry(); - } - } - } - function go$readdir(args) { - return fs$readdir.apply(fs28, args); - } - if (process.version.substr(0, 4) === "v0.8") { - var legStreams = legacy(fs28); - ReadStream = legStreams.ReadStream; - WriteStream = legStreams.WriteStream; - } - var fs$ReadStream = fs28.ReadStream; - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype); - ReadStream.prototype.open = ReadStream$open; - } - var fs$WriteStream = fs28.WriteStream; - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype); - WriteStream.prototype.open = WriteStream$open; - } - Object.defineProperty(fs28, "ReadStream", { - get: function() { - return ReadStream; - }, - set: function(val) { - ReadStream = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(fs28, "WriteStream", { - get: function() { - return WriteStream; - }, - set: function(val) { - WriteStream = val; - }, - enumerable: true, - configurable: true - }); - var FileReadStream = ReadStream; - Object.defineProperty(fs28, "FileReadStream", { - get: function() { - return FileReadStream; - }, - set: function(val) { - FileReadStream = val; - }, - enumerable: true, - configurable: true - }); - var FileWriteStream = WriteStream; - Object.defineProperty(fs28, "FileWriteStream", { - get: function() { - return FileWriteStream; - }, - set: function(val) { - FileWriteStream = val; - }, - enumerable: true, - configurable: true - }); - function ReadStream(path36, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this; - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments); - } - function ReadStream$open() { - var that = this; - open(that.path, that.flags, that.mode, function(err, fd) { - if (err) { - if (that.autoClose) - that.destroy(); - that.emit("error", err); - } else { - that.fd = fd; - that.emit("open", fd); - that.read(); - } - }); - } - function WriteStream(path36, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this; - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments); - } - function WriteStream$open() { - var that = this; - open(that.path, that.flags, that.mode, function(err, fd) { - if (err) { - that.destroy(); - that.emit("error", err); - } else { - that.fd = fd; - that.emit("open", fd); - } - }); - } - function createReadStream(path36, options) { - return new fs28.ReadStream(path36, options); - } - function createWriteStream(path36, options) { - return new fs28.WriteStream(path36, options); - } - var fs$open = fs28.open; - fs28.open = open; - function open(path36, flags, mode, cb) { - if (typeof mode === "function") - cb = mode, mode = null; - return go$open(path36, flags, mode, cb); - function go$open(path37, flags2, mode2, cb2) { - return fs$open(path37, flags2, mode2, function(err, fd) { - if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$open, [path37, flags2, mode2, cb2]]); - else { - if (typeof cb2 === "function") - cb2.apply(this, arguments); - retry(); - } - }); - } - } - return fs28; - } - function enqueue(elem) { - debug("ENQUEUE", elem[0].name, elem[1]); - fs27[gracefulQueue].push(elem); - } - function retry() { - var elem = fs27[gracefulQueue].shift(); - if (elem) { - debug("RETRY", elem[0].name, elem[1]); - elem[0].apply(null, elem[1]); - } - } - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/fs/index.js -var require_fs = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/fs/index.js"(exports2) { - "use strict"; - var u = require_universalify().fromCallback; - var fs27 = require_graceful_fs(); - var api = [ - "access", - "appendFile", - "chmod", - "chown", - "close", - "copyFile", - "fchmod", - "fchown", - "fdatasync", - "fstat", - "fsync", - "ftruncate", - "futimes", - "lchown", - "lchmod", - "link", - "lstat", - "mkdir", - "mkdtemp", - "open", - "readFile", - "readdir", - "readlink", - "realpath", - "rename", - "rmdir", - "stat", - "symlink", - "truncate", - "unlink", - "utimes", - "writeFile" - ].filter((key) => { - return typeof fs27[key] === "function"; - }); - Object.keys(fs27).forEach((key) => { - if (key === "promises") { - return; - } - exports2[key] = fs27[key]; - }); - api.forEach((method) => { - exports2[method] = u(fs27[method]); - }); - exports2.exists = function(filename, callback) { - if (typeof callback === "function") { - return fs27.exists(filename, callback); - } - return new Promise((resolve3) => { - return fs27.exists(filename, resolve3); - }); - }; - exports2.read = function(fd, buffer, offset, length, position, callback) { - if (typeof callback === "function") { - return fs27.read(fd, buffer, offset, length, position, callback); - } - return new Promise((resolve3, reject) => { - fs27.read(fd, buffer, offset, length, position, (err, bytesRead, buffer2) => { - if (err) - return reject(err); - resolve3({ bytesRead, buffer: buffer2 }); - }); - }); - }; - exports2.write = function(fd, buffer, ...args) { - if (typeof args[args.length - 1] === "function") { - return fs27.write(fd, buffer, ...args); - } - return new Promise((resolve3, reject) => { - fs27.write(fd, buffer, ...args, (err, bytesWritten, buffer2) => { - if (err) - return reject(err); - resolve3({ bytesWritten, buffer: buffer2 }); - }); - }); - }; - if (typeof fs27.realpath.native === "function") { - exports2.realpath.native = u(fs27.realpath.native); - } - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/mkdirs/win32.js -var require_win32 = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/mkdirs/win32.js"(exports2, module2) { - "use strict"; - var path36 = require("path"); - function getRootPath(p) { - p = path36.normalize(path36.resolve(p)).split(path36.sep); - if (p.length > 0) - return p[0]; - return null; - } - var INVALID_PATH_CHARS = /[<>:"|?*]/; - function invalidWin32Path(p) { - const rp = getRootPath(p); - p = p.replace(rp, ""); - return INVALID_PATH_CHARS.test(p); - } - module2.exports = { - getRootPath, - invalidWin32Path - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/mkdirs/mkdirs.js -var require_mkdirs = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/mkdirs/mkdirs.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var invalidWin32Path = require_win32().invalidWin32Path; - var o777 = parseInt("0777", 8); - function mkdirs(p, opts, callback, made) { - if (typeof opts === "function") { - callback = opts; - opts = {}; - } else if (!opts || typeof opts !== "object") { - opts = { mode: opts }; - } - if (process.platform === "win32" && invalidWin32Path(p)) { - const errInval = new Error(p + " contains invalid WIN32 path characters."); - errInval.code = "EINVAL"; - return callback(errInval); - } - let mode = opts.mode; - const xfs = opts.fs || fs27; - if (mode === void 0) { - mode = o777 & ~process.umask(); - } - if (!made) - made = null; - callback = callback || function() { - }; - p = path36.resolve(p); - xfs.mkdir(p, mode, (er) => { - if (!er) { - made = made || p; - return callback(null, made); - } - switch (er.code) { - case "ENOENT": - if (path36.dirname(p) === p) - return callback(er); - mkdirs(path36.dirname(p), opts, (er2, made2) => { - if (er2) - callback(er2, made2); - else - mkdirs(p, opts, callback, made2); - }); - break; - default: - xfs.stat(p, (er2, stat) => { - if (er2 || !stat.isDirectory()) - callback(er, made); - else - callback(null, made); - }); - break; - } - }); - } - module2.exports = mkdirs; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/mkdirs/mkdirs-sync.js -var require_mkdirs_sync = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/mkdirs/mkdirs-sync.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var invalidWin32Path = require_win32().invalidWin32Path; - var o777 = parseInt("0777", 8); - function mkdirsSync(p, opts, made) { - if (!opts || typeof opts !== "object") { - opts = { mode: opts }; - } - let mode = opts.mode; - const xfs = opts.fs || fs27; - if (process.platform === "win32" && invalidWin32Path(p)) { - const errInval = new Error(p + " contains invalid WIN32 path characters."); - errInval.code = "EINVAL"; - throw errInval; - } - if (mode === void 0) { - mode = o777 & ~process.umask(); - } - if (!made) - made = null; - p = path36.resolve(p); - try { - xfs.mkdirSync(p, mode); - made = made || p; - } catch (err0) { - if (err0.code === "ENOENT") { - if (path36.dirname(p) === p) - throw err0; - made = mkdirsSync(path36.dirname(p), opts, made); - mkdirsSync(p, opts, made); - } else { - let stat; - try { - stat = xfs.statSync(p); - } catch (err1) { - throw err0; - } - if (!stat.isDirectory()) - throw err0; - } - } - return made; - } - module2.exports = mkdirsSync; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/mkdirs/index.js -var require_mkdirs2 = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/mkdirs/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - var mkdirs = u(require_mkdirs()); - var mkdirsSync = require_mkdirs_sync(); - module2.exports = { - mkdirs, - mkdirsSync, - mkdirp: mkdirs, - mkdirpSync: mkdirsSync, - ensureDir: mkdirs, - ensureDirSync: mkdirsSync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/util/utimes.js -var require_utimes = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/util/utimes.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var os10 = require("os"); - var path36 = require("path"); - function hasMillisResSync() { - let tmpfile = path36.join("millis-test-sync" + Date.now().toString() + Math.random().toString().slice(2)); - tmpfile = path36.join(os10.tmpdir(), tmpfile); - const d = new Date(1435410243862); - fs27.writeFileSync(tmpfile, "https://github.com/jprichardson/node-fs-extra/pull/141"); - const fd = fs27.openSync(tmpfile, "r+"); - fs27.futimesSync(fd, d, d); - fs27.closeSync(fd); - return fs27.statSync(tmpfile).mtime > 1435410243e3; - } - function hasMillisRes(callback) { - let tmpfile = path36.join("millis-test" + Date.now().toString() + Math.random().toString().slice(2)); - tmpfile = path36.join(os10.tmpdir(), tmpfile); - const d = new Date(1435410243862); - fs27.writeFile(tmpfile, "https://github.com/jprichardson/node-fs-extra/pull/141", (err) => { - if (err) - return callback(err); - fs27.open(tmpfile, "r+", (err2, fd) => { - if (err2) - return callback(err2); - fs27.futimes(fd, d, d, (err3) => { - if (err3) - return callback(err3); - fs27.close(fd, (err4) => { - if (err4) - return callback(err4); - fs27.stat(tmpfile, (err5, stats) => { - if (err5) - return callback(err5); - callback(null, stats.mtime > 1435410243e3); - }); - }); - }); - }); - }); - } - function timeRemoveMillis(timestamp) { - if (typeof timestamp === "number") { - return Math.floor(timestamp / 1e3) * 1e3; - } else if (timestamp instanceof Date) { - return new Date(Math.floor(timestamp.getTime() / 1e3) * 1e3); - } else { - throw new Error("fs-extra: timeRemoveMillis() unknown parameter type"); - } - } - function utimesMillis(path37, atime, mtime, callback) { - fs27.open(path37, "r+", (err, fd) => { - if (err) - return callback(err); - fs27.futimes(fd, atime, mtime, (futimesErr) => { - fs27.close(fd, (closeErr) => { - if (callback) - callback(futimesErr || closeErr); - }); - }); - }); - } - function utimesMillisSync(path37, atime, mtime) { - const fd = fs27.openSync(path37, "r+"); - fs27.futimesSync(fd, atime, mtime); - return fs27.closeSync(fd); - } - module2.exports = { - hasMillisRes, - hasMillisResSync, - timeRemoveMillis, - utimesMillis, - utimesMillisSync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/util/stat.js -var require_stat = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/util/stat.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var NODE_VERSION_MAJOR_WITH_BIGINT = 10; - var NODE_VERSION_MINOR_WITH_BIGINT = 5; - var NODE_VERSION_PATCH_WITH_BIGINT = 0; - var nodeVersion = process.versions.node.split("."); - var nodeVersionMajor = Number.parseInt(nodeVersion[0], 10); - var nodeVersionMinor = Number.parseInt(nodeVersion[1], 10); - var nodeVersionPatch = Number.parseInt(nodeVersion[2], 10); - function nodeSupportsBigInt() { - if (nodeVersionMajor > NODE_VERSION_MAJOR_WITH_BIGINT) { - return true; - } else if (nodeVersionMajor === NODE_VERSION_MAJOR_WITH_BIGINT) { - if (nodeVersionMinor > NODE_VERSION_MINOR_WITH_BIGINT) { - return true; - } else if (nodeVersionMinor === NODE_VERSION_MINOR_WITH_BIGINT) { - if (nodeVersionPatch >= NODE_VERSION_PATCH_WITH_BIGINT) { - return true; - } - } - } - return false; - } - function getStats(src, dest, cb) { - if (nodeSupportsBigInt()) { - fs27.stat(src, { bigint: true }, (err, srcStat) => { - if (err) - return cb(err); - fs27.stat(dest, { bigint: true }, (err2, destStat) => { - if (err2) { - if (err2.code === "ENOENT") - return cb(null, { srcStat, destStat: null }); - return cb(err2); - } - return cb(null, { srcStat, destStat }); - }); - }); - } else { - fs27.stat(src, (err, srcStat) => { - if (err) - return cb(err); - fs27.stat(dest, (err2, destStat) => { - if (err2) { - if (err2.code === "ENOENT") - return cb(null, { srcStat, destStat: null }); - return cb(err2); - } - return cb(null, { srcStat, destStat }); - }); - }); - } - } - function getStatsSync(src, dest) { - let srcStat, destStat; - if (nodeSupportsBigInt()) { - srcStat = fs27.statSync(src, { bigint: true }); - } else { - srcStat = fs27.statSync(src); - } - try { - if (nodeSupportsBigInt()) { - destStat = fs27.statSync(dest, { bigint: true }); - } else { - destStat = fs27.statSync(dest); - } - } catch (err) { - if (err.code === "ENOENT") - return { srcStat, destStat: null }; - throw err; - } - return { srcStat, destStat }; - } - function checkPaths(src, dest, funcName, cb) { - getStats(src, dest, (err, stats) => { - if (err) - return cb(err); - const { srcStat, destStat } = stats; - if (destStat && destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - return cb(new Error("Source and destination must not be the same.")); - } - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - return cb(new Error(errMsg(src, dest, funcName))); - } - return cb(null, { srcStat, destStat }); - }); - } - function checkPathsSync(src, dest, funcName) { - const { srcStat, destStat } = getStatsSync(src, dest); - if (destStat && destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - throw new Error("Source and destination must not be the same."); - } - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new Error(errMsg(src, dest, funcName)); - } - return { srcStat, destStat }; - } - function checkParentPaths(src, srcStat, dest, funcName, cb) { - const srcParent = path36.resolve(path36.dirname(src)); - const destParent = path36.resolve(path36.dirname(dest)); - if (destParent === srcParent || destParent === path36.parse(destParent).root) - return cb(); - if (nodeSupportsBigInt()) { - fs27.stat(destParent, { bigint: true }, (err, destStat) => { - if (err) { - if (err.code === "ENOENT") - return cb(); - return cb(err); - } - if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - return cb(new Error(errMsg(src, dest, funcName))); - } - return checkParentPaths(src, srcStat, destParent, funcName, cb); - }); - } else { - fs27.stat(destParent, (err, destStat) => { - if (err) { - if (err.code === "ENOENT") - return cb(); - return cb(err); - } - if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - return cb(new Error(errMsg(src, dest, funcName))); - } - return checkParentPaths(src, srcStat, destParent, funcName, cb); - }); - } - } - function checkParentPathsSync(src, srcStat, dest, funcName) { - const srcParent = path36.resolve(path36.dirname(src)); - const destParent = path36.resolve(path36.dirname(dest)); - if (destParent === srcParent || destParent === path36.parse(destParent).root) - return; - let destStat; - try { - if (nodeSupportsBigInt()) { - destStat = fs27.statSync(destParent, { bigint: true }); - } else { - destStat = fs27.statSync(destParent); - } - } catch (err) { - if (err.code === "ENOENT") - return; - throw err; - } - if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - throw new Error(errMsg(src, dest, funcName)); - } - return checkParentPathsSync(src, srcStat, destParent, funcName); - } - function isSrcSubdir(src, dest) { - const srcArr = path36.resolve(src).split(path36.sep).filter((i) => i); - const destArr = path36.resolve(dest).split(path36.sep).filter((i) => i); - return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true); - } - function errMsg(src, dest, funcName) { - return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`; - } - module2.exports = { - checkPaths, - checkPathsSync, - checkParentPaths, - checkParentPathsSync, - isSrcSubdir - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/util/buffer.js -var require_buffer = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/util/buffer.js"(exports2, module2) { - "use strict"; - module2.exports = function(size) { - if (typeof Buffer.allocUnsafe === "function") { - try { - return Buffer.allocUnsafe(size); - } catch (e) { - return new Buffer(size); - } - } - return new Buffer(size); - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/copy-sync/copy-sync.js -var require_copy_sync = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/copy-sync/copy-sync.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var mkdirpSync = require_mkdirs2().mkdirsSync; - var utimesSync = require_utimes().utimesMillisSync; - var stat = require_stat(); - function copySync(src, dest, opts) { - if (typeof opts === "function") { - opts = { filter: opts }; - } - opts = opts || {}; - opts.clobber = "clobber" in opts ? !!opts.clobber : true; - opts.overwrite = "overwrite" in opts ? !!opts.overwrite : opts.clobber; - if (opts.preserveTimestamps && process.arch === "ia32") { - console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended; - - see https://github.com/jprichardson/node-fs-extra/issues/269`); - } - const { srcStat, destStat } = stat.checkPathsSync(src, dest, "copy"); - stat.checkParentPathsSync(src, srcStat, dest, "copy"); - return handleFilterAndCopy(destStat, src, dest, opts); - } - function handleFilterAndCopy(destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) - return; - const destParent = path36.dirname(dest); - if (!fs27.existsSync(destParent)) - mkdirpSync(destParent); - return startCopy(destStat, src, dest, opts); - } - function startCopy(destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) - return; - return getStats(destStat, src, dest, opts); - } - function getStats(destStat, src, dest, opts) { - const statSync = opts.dereference ? fs27.statSync : fs27.lstatSync; - const srcStat = statSync(src); - if (srcStat.isDirectory()) - return onDir(srcStat, destStat, src, dest, opts); - else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) - return onFile(srcStat, destStat, src, dest, opts); - else if (srcStat.isSymbolicLink()) - return onLink(destStat, src, dest, opts); - } - function onFile(srcStat, destStat, src, dest, opts) { - if (!destStat) - return copyFile(srcStat, src, dest, opts); - return mayCopyFile(srcStat, src, dest, opts); - } - function mayCopyFile(srcStat, src, dest, opts) { - if (opts.overwrite) { - fs27.unlinkSync(dest); - return copyFile(srcStat, src, dest, opts); - } else if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`); - } - } - function copyFile(srcStat, src, dest, opts) { - if (typeof fs27.copyFileSync === "function") { - fs27.copyFileSync(src, dest); - fs27.chmodSync(dest, srcStat.mode); - if (opts.preserveTimestamps) { - return utimesSync(dest, srcStat.atime, srcStat.mtime); - } - return; - } - return copyFileFallback(srcStat, src, dest, opts); - } - function copyFileFallback(srcStat, src, dest, opts) { - const BUF_LENGTH = 64 * 1024; - const _buff = require_buffer()(BUF_LENGTH); - const fdr = fs27.openSync(src, "r"); - const fdw = fs27.openSync(dest, "w", srcStat.mode); - let pos = 0; - while (pos < srcStat.size) { - const bytesRead = fs27.readSync(fdr, _buff, 0, BUF_LENGTH, pos); - fs27.writeSync(fdw, _buff, 0, bytesRead); - pos += bytesRead; - } - if (opts.preserveTimestamps) - fs27.futimesSync(fdw, srcStat.atime, srcStat.mtime); - fs27.closeSync(fdr); - fs27.closeSync(fdw); - } - function onDir(srcStat, destStat, src, dest, opts) { - if (!destStat) - return mkDirAndCopy(srcStat, src, dest, opts); - if (destStat && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`); - } - return copyDir(src, dest, opts); - } - function mkDirAndCopy(srcStat, src, dest, opts) { - fs27.mkdirSync(dest); - copyDir(src, dest, opts); - return fs27.chmodSync(dest, srcStat.mode); - } - function copyDir(src, dest, opts) { - fs27.readdirSync(src).forEach((item) => copyDirItem(item, src, dest, opts)); - } - function copyDirItem(item, src, dest, opts) { - const srcItem = path36.join(src, item); - const destItem = path36.join(dest, item); - const { destStat } = stat.checkPathsSync(srcItem, destItem, "copy"); - return startCopy(destStat, srcItem, destItem, opts); - } - function onLink(destStat, src, dest, opts) { - let resolvedSrc = fs27.readlinkSync(src); - if (opts.dereference) { - resolvedSrc = path36.resolve(process.cwd(), resolvedSrc); - } - if (!destStat) { - return fs27.symlinkSync(resolvedSrc, dest); - } else { - let resolvedDest; - try { - resolvedDest = fs27.readlinkSync(dest); - } catch (err) { - if (err.code === "EINVAL" || err.code === "UNKNOWN") - return fs27.symlinkSync(resolvedSrc, dest); - throw err; - } - if (opts.dereference) { - resolvedDest = path36.resolve(process.cwd(), resolvedDest); - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`); - } - if (fs27.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`); - } - return copyLink(resolvedSrc, dest); - } - } - function copyLink(resolvedSrc, dest) { - fs27.unlinkSync(dest); - return fs27.symlinkSync(resolvedSrc, dest); - } - module2.exports = copySync; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/copy-sync/index.js -var require_copy_sync2 = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/copy-sync/index.js"(exports2, module2) { - "use strict"; - module2.exports = { - copySync: require_copy_sync() - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/path-exists/index.js -var require_path_exists = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/path-exists/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromPromise; - var fs27 = require_fs(); - function pathExists(path36) { - return fs27.access(path36).then(() => true).catch(() => false); - } - module2.exports = { - pathExists: u(pathExists), - pathExistsSync: fs27.existsSync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/copy/copy.js -var require_copy = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/copy/copy.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var mkdirp = require_mkdirs2().mkdirs; - var pathExists = require_path_exists().pathExists; - var utimes = require_utimes().utimesMillis; - var stat = require_stat(); - function copy(src, dest, opts, cb) { - if (typeof opts === "function" && !cb) { - cb = opts; - opts = {}; - } else if (typeof opts === "function") { - opts = { filter: opts }; - } - cb = cb || function() { - }; - opts = opts || {}; - opts.clobber = "clobber" in opts ? !!opts.clobber : true; - opts.overwrite = "overwrite" in opts ? !!opts.overwrite : opts.clobber; - if (opts.preserveTimestamps && process.arch === "ia32") { - console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended; - - see https://github.com/jprichardson/node-fs-extra/issues/269`); - } - stat.checkPaths(src, dest, "copy", (err, stats) => { - if (err) - return cb(err); - const { srcStat, destStat } = stats; - stat.checkParentPaths(src, srcStat, dest, "copy", (err2) => { - if (err2) - return cb(err2); - if (opts.filter) - return handleFilter(checkParentDir, destStat, src, dest, opts, cb); - return checkParentDir(destStat, src, dest, opts, cb); - }); - }); - } - function checkParentDir(destStat, src, dest, opts, cb) { - const destParent = path36.dirname(dest); - pathExists(destParent, (err, dirExists) => { - if (err) - return cb(err); - if (dirExists) - return startCopy(destStat, src, dest, opts, cb); - mkdirp(destParent, (err2) => { - if (err2) - return cb(err2); - return startCopy(destStat, src, dest, opts, cb); - }); - }); - } - function handleFilter(onInclude, destStat, src, dest, opts, cb) { - Promise.resolve(opts.filter(src, dest)).then((include) => { - if (include) - return onInclude(destStat, src, dest, opts, cb); - return cb(); - }, (error) => cb(error)); - } - function startCopy(destStat, src, dest, opts, cb) { - if (opts.filter) - return handleFilter(getStats, destStat, src, dest, opts, cb); - return getStats(destStat, src, dest, opts, cb); - } - function getStats(destStat, src, dest, opts, cb) { - const stat2 = opts.dereference ? fs27.stat : fs27.lstat; - stat2(src, (err, srcStat) => { - if (err) - return cb(err); - if (srcStat.isDirectory()) - return onDir(srcStat, destStat, src, dest, opts, cb); - else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) - return onFile(srcStat, destStat, src, dest, opts, cb); - else if (srcStat.isSymbolicLink()) - return onLink(destStat, src, dest, opts, cb); - }); - } - function onFile(srcStat, destStat, src, dest, opts, cb) { - if (!destStat) - return copyFile(srcStat, src, dest, opts, cb); - return mayCopyFile(srcStat, src, dest, opts, cb); - } - function mayCopyFile(srcStat, src, dest, opts, cb) { - if (opts.overwrite) { - fs27.unlink(dest, (err) => { - if (err) - return cb(err); - return copyFile(srcStat, src, dest, opts, cb); - }); - } else if (opts.errorOnExist) { - return cb(new Error(`'${dest}' already exists`)); - } else - return cb(); - } - function copyFile(srcStat, src, dest, opts, cb) { - if (typeof fs27.copyFile === "function") { - return fs27.copyFile(src, dest, (err) => { - if (err) - return cb(err); - return setDestModeAndTimestamps(srcStat, dest, opts, cb); - }); - } - return copyFileFallback(srcStat, src, dest, opts, cb); - } - function copyFileFallback(srcStat, src, dest, opts, cb) { - const rs = fs27.createReadStream(src); - rs.on("error", (err) => cb(err)).once("open", () => { - const ws = fs27.createWriteStream(dest, { mode: srcStat.mode }); - ws.on("error", (err) => cb(err)).on("open", () => rs.pipe(ws)).once("close", () => setDestModeAndTimestamps(srcStat, dest, opts, cb)); - }); - } - function setDestModeAndTimestamps(srcStat, dest, opts, cb) { - fs27.chmod(dest, srcStat.mode, (err) => { - if (err) - return cb(err); - if (opts.preserveTimestamps) { - return utimes(dest, srcStat.atime, srcStat.mtime, cb); - } - return cb(); - }); - } - function onDir(srcStat, destStat, src, dest, opts, cb) { - if (!destStat) - return mkDirAndCopy(srcStat, src, dest, opts, cb); - if (destStat && !destStat.isDirectory()) { - return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)); - } - return copyDir(src, dest, opts, cb); - } - function mkDirAndCopy(srcStat, src, dest, opts, cb) { - fs27.mkdir(dest, (err) => { - if (err) - return cb(err); - copyDir(src, dest, opts, (err2) => { - if (err2) - return cb(err2); - return fs27.chmod(dest, srcStat.mode, cb); - }); - }); - } - function copyDir(src, dest, opts, cb) { - fs27.readdir(src, (err, items) => { - if (err) - return cb(err); - return copyDirItems(items, src, dest, opts, cb); - }); - } - function copyDirItems(items, src, dest, opts, cb) { - const item = items.pop(); - if (!item) - return cb(); - return copyDirItem(items, item, src, dest, opts, cb); - } - function copyDirItem(items, item, src, dest, opts, cb) { - const srcItem = path36.join(src, item); - const destItem = path36.join(dest, item); - stat.checkPaths(srcItem, destItem, "copy", (err, stats) => { - if (err) - return cb(err); - const { destStat } = stats; - startCopy(destStat, srcItem, destItem, opts, (err2) => { - if (err2) - return cb(err2); - return copyDirItems(items, src, dest, opts, cb); - }); - }); - } - function onLink(destStat, src, dest, opts, cb) { - fs27.readlink(src, (err, resolvedSrc) => { - if (err) - return cb(err); - if (opts.dereference) { - resolvedSrc = path36.resolve(process.cwd(), resolvedSrc); - } - if (!destStat) { - return fs27.symlink(resolvedSrc, dest, cb); - } else { - fs27.readlink(dest, (err2, resolvedDest) => { - if (err2) { - if (err2.code === "EINVAL" || err2.code === "UNKNOWN") - return fs27.symlink(resolvedSrc, dest, cb); - return cb(err2); - } - if (opts.dereference) { - resolvedDest = path36.resolve(process.cwd(), resolvedDest); - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)); - } - if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)); - } - return copyLink(resolvedSrc, dest, cb); - }); - } - }); - } - function copyLink(resolvedSrc, dest, cb) { - fs27.unlink(dest, (err) => { - if (err) - return cb(err); - return fs27.symlink(resolvedSrc, dest, cb); - }); - } - module2.exports = copy; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/copy/index.js -var require_copy2 = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/copy/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - module2.exports = { - copy: u(require_copy()) - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/remove/rimraf.js -var require_rimraf = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/remove/rimraf.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var assert = require("assert"); - var isWindows4 = process.platform === "win32"; - function defaults2(options) { - const methods2 = [ - "unlink", - "chmod", - "stat", - "lstat", - "rmdir", - "readdir" - ]; - methods2.forEach((m) => { - options[m] = options[m] || fs27[m]; - m = m + "Sync"; - options[m] = options[m] || fs27[m]; - }); - options.maxBusyTries = options.maxBusyTries || 3; - } - function rimraf(p, options, cb) { - let busyTries = 0; - if (typeof options === "function") { - cb = options; - options = {}; - } - assert(p, "rimraf: missing path"); - assert.strictEqual(typeof p, "string", "rimraf: path should be a string"); - assert.strictEqual(typeof cb, "function", "rimraf: callback function required"); - assert(options, "rimraf: invalid options argument provided"); - assert.strictEqual(typeof options, "object", "rimraf: options should be object"); - defaults2(options); - rimraf_(p, options, function CB(er) { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { - busyTries++; - const time = busyTries * 100; - return setTimeout(() => rimraf_(p, options, CB), time); - } - if (er.code === "ENOENT") - er = null; - } - cb(er); - }); - } - function rimraf_(p, options, cb) { - assert(p); - assert(options); - assert(typeof cb === "function"); - options.lstat(p, (er, st) => { - if (er && er.code === "ENOENT") { - return cb(null); - } - if (er && er.code === "EPERM" && isWindows4) { - return fixWinEPERM(p, options, er, cb); - } - if (st && st.isDirectory()) { - return rmdir(p, options, er, cb); - } - options.unlink(p, (er2) => { - if (er2) { - if (er2.code === "ENOENT") { - return cb(null); - } - if (er2.code === "EPERM") { - return isWindows4 ? fixWinEPERM(p, options, er2, cb) : rmdir(p, options, er2, cb); - } - if (er2.code === "EISDIR") { - return rmdir(p, options, er2, cb); - } - } - return cb(er2); - }); - }); - } - function fixWinEPERM(p, options, er, cb) { - assert(p); - assert(options); - assert(typeof cb === "function"); - if (er) { - assert(er instanceof Error); - } - options.chmod(p, 438, (er2) => { - if (er2) { - cb(er2.code === "ENOENT" ? null : er); - } else { - options.stat(p, (er3, stats) => { - if (er3) { - cb(er3.code === "ENOENT" ? null : er); - } else if (stats.isDirectory()) { - rmdir(p, options, er, cb); - } else { - options.unlink(p, cb); - } - }); - } - }); - } - function fixWinEPERMSync(p, options, er) { - let stats; - assert(p); - assert(options); - if (er) { - assert(er instanceof Error); - } - try { - options.chmodSync(p, 438); - } catch (er2) { - if (er2.code === "ENOENT") { - return; - } else { - throw er; - } - } - try { - stats = options.statSync(p); - } catch (er3) { - if (er3.code === "ENOENT") { - return; - } else { - throw er; - } - } - if (stats.isDirectory()) { - rmdirSync(p, options, er); - } else { - options.unlinkSync(p); - } - } - function rmdir(p, options, originalEr, cb) { - assert(p); - assert(options); - if (originalEr) { - assert(originalEr instanceof Error); - } - assert(typeof cb === "function"); - options.rmdir(p, (er) => { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) { - rmkids(p, options, cb); - } else if (er && er.code === "ENOTDIR") { - cb(originalEr); - } else { - cb(er); - } - }); - } - function rmkids(p, options, cb) { - assert(p); - assert(options); - assert(typeof cb === "function"); - options.readdir(p, (er, files) => { - if (er) - return cb(er); - let n = files.length; - let errState; - if (n === 0) - return options.rmdir(p, cb); - files.forEach((f) => { - rimraf(path36.join(p, f), options, (er2) => { - if (errState) { - return; - } - if (er2) - return cb(errState = er2); - if (--n === 0) { - options.rmdir(p, cb); - } - }); - }); - }); - } - function rimrafSync(p, options) { - let st; - options = options || {}; - defaults2(options); - assert(p, "rimraf: missing path"); - assert.strictEqual(typeof p, "string", "rimraf: path should be a string"); - assert(options, "rimraf: missing options"); - assert.strictEqual(typeof options, "object", "rimraf: options should be object"); - try { - st = options.lstatSync(p); - } catch (er) { - if (er.code === "ENOENT") { - return; - } - if (er.code === "EPERM" && isWindows4) { - fixWinEPERMSync(p, options, er); - } - } - try { - if (st && st.isDirectory()) { - rmdirSync(p, options, null); - } else { - options.unlinkSync(p); - } - } catch (er) { - if (er.code === "ENOENT") { - return; - } else if (er.code === "EPERM") { - return isWindows4 ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er); - } else if (er.code !== "EISDIR") { - throw er; - } - rmdirSync(p, options, er); - } - } - function rmdirSync(p, options, originalEr) { - assert(p); - assert(options); - if (originalEr) { - assert(originalEr instanceof Error); - } - try { - options.rmdirSync(p); - } catch (er) { - if (er.code === "ENOTDIR") { - throw originalEr; - } else if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") { - rmkidsSync(p, options); - } else if (er.code !== "ENOENT") { - throw er; - } - } - } - function rmkidsSync(p, options) { - assert(p); - assert(options); - options.readdirSync(p).forEach((f) => rimrafSync(path36.join(p, f), options)); - if (isWindows4) { - const startTime = Date.now(); - do { - try { - const ret = options.rmdirSync(p, options); - return ret; - } catch (er) { - } - } while (Date.now() - startTime < 500); - } else { - const ret = options.rmdirSync(p, options); - return ret; - } - } - module2.exports = rimraf; - rimraf.sync = rimrafSync; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/remove/index.js -var require_remove = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/remove/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - var rimraf = require_rimraf(); - module2.exports = { - remove: u(rimraf), - removeSync: rimraf.sync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/empty/index.js -var require_empty = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/empty/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var mkdir = require_mkdirs2(); - var remove = require_remove(); - var emptyDir = u(function emptyDir2(dir, callback) { - callback = callback || function() { - }; - fs27.readdir(dir, (err, items) => { - if (err) - return mkdir.mkdirs(dir, callback); - items = items.map((item) => path36.join(dir, item)); - deleteItem(); - function deleteItem() { - const item = items.pop(); - if (!item) - return callback(); - remove.remove(item, (err2) => { - if (err2) - return callback(err2); - deleteItem(); - }); - } - }); - }); - function emptyDirSync(dir) { - let items; - try { - items = fs27.readdirSync(dir); - } catch (err) { - return mkdir.mkdirsSync(dir); - } - items.forEach((item) => { - item = path36.join(dir, item); - remove.removeSync(item); - }); - } - module2.exports = { - emptyDirSync, - emptydirSync: emptyDirSync, - emptyDir, - emptydir: emptyDir - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/ensure/file.js -var require_file = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/ensure/file.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - var path36 = require("path"); - var fs27 = require_graceful_fs(); - var mkdir = require_mkdirs2(); - var pathExists = require_path_exists().pathExists; - function createFile(file, callback) { - function makeFile() { - fs27.writeFile(file, "", (err) => { - if (err) - return callback(err); - callback(); - }); - } - fs27.stat(file, (err, stats) => { - if (!err && stats.isFile()) - return callback(); - const dir = path36.dirname(file); - pathExists(dir, (err2, dirExists) => { - if (err2) - return callback(err2); - if (dirExists) - return makeFile(); - mkdir.mkdirs(dir, (err3) => { - if (err3) - return callback(err3); - makeFile(); - }); - }); - }); - } - function createFileSync(file) { - let stats; - try { - stats = fs27.statSync(file); - } catch (e) { - } - if (stats && stats.isFile()) - return; - const dir = path36.dirname(file); - if (!fs27.existsSync(dir)) { - mkdir.mkdirsSync(dir); - } - fs27.writeFileSync(file, ""); - } - module2.exports = { - createFile: u(createFile), - createFileSync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/ensure/link.js -var require_link = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/ensure/link.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - var path36 = require("path"); - var fs27 = require_graceful_fs(); - var mkdir = require_mkdirs2(); - var pathExists = require_path_exists().pathExists; - function createLink(srcpath, dstpath, callback) { - function makeLink(srcpath2, dstpath2) { - fs27.link(srcpath2, dstpath2, (err) => { - if (err) - return callback(err); - callback(null); - }); - } - pathExists(dstpath, (err, destinationExists) => { - if (err) - return callback(err); - if (destinationExists) - return callback(null); - fs27.lstat(srcpath, (err2) => { - if (err2) { - err2.message = err2.message.replace("lstat", "ensureLink"); - return callback(err2); - } - const dir = path36.dirname(dstpath); - pathExists(dir, (err3, dirExists) => { - if (err3) - return callback(err3); - if (dirExists) - return makeLink(srcpath, dstpath); - mkdir.mkdirs(dir, (err4) => { - if (err4) - return callback(err4); - makeLink(srcpath, dstpath); - }); - }); - }); - }); - } - function createLinkSync(srcpath, dstpath) { - const destinationExists = fs27.existsSync(dstpath); - if (destinationExists) - return void 0; - try { - fs27.lstatSync(srcpath); - } catch (err) { - err.message = err.message.replace("lstat", "ensureLink"); - throw err; - } - const dir = path36.dirname(dstpath); - const dirExists = fs27.existsSync(dir); - if (dirExists) - return fs27.linkSync(srcpath, dstpath); - mkdir.mkdirsSync(dir); - return fs27.linkSync(srcpath, dstpath); - } - module2.exports = { - createLink: u(createLink), - createLinkSync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/ensure/symlink-paths.js -var require_symlink_paths = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/ensure/symlink-paths.js"(exports2, module2) { - "use strict"; - var path36 = require("path"); - var fs27 = require_graceful_fs(); - var pathExists = require_path_exists().pathExists; - function symlinkPaths(srcpath, dstpath, callback) { - if (path36.isAbsolute(srcpath)) { - return fs27.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace("lstat", "ensureSymlink"); - return callback(err); - } - return callback(null, { - "toCwd": srcpath, - "toDst": srcpath - }); - }); - } else { - const dstdir = path36.dirname(dstpath); - const relativeToDst = path36.join(dstdir, srcpath); - return pathExists(relativeToDst, (err, exists) => { - if (err) - return callback(err); - if (exists) { - return callback(null, { - "toCwd": relativeToDst, - "toDst": srcpath - }); - } else { - return fs27.lstat(srcpath, (err2) => { - if (err2) { - err2.message = err2.message.replace("lstat", "ensureSymlink"); - return callback(err2); - } - return callback(null, { - "toCwd": srcpath, - "toDst": path36.relative(dstdir, srcpath) - }); - }); - } - }); - } - } - function symlinkPathsSync(srcpath, dstpath) { - let exists; - if (path36.isAbsolute(srcpath)) { - exists = fs27.existsSync(srcpath); - if (!exists) - throw new Error("absolute srcpath does not exist"); - return { - "toCwd": srcpath, - "toDst": srcpath - }; - } else { - const dstdir = path36.dirname(dstpath); - const relativeToDst = path36.join(dstdir, srcpath); - exists = fs27.existsSync(relativeToDst); - if (exists) { - return { - "toCwd": relativeToDst, - "toDst": srcpath - }; - } else { - exists = fs27.existsSync(srcpath); - if (!exists) - throw new Error("relative srcpath does not exist"); - return { - "toCwd": srcpath, - "toDst": path36.relative(dstdir, srcpath) - }; - } - } - } - module2.exports = { - symlinkPaths, - symlinkPathsSync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/ensure/symlink-type.js -var require_symlink_type = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/ensure/symlink-type.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - function symlinkType(srcpath, type, callback) { - callback = typeof type === "function" ? type : callback; - type = typeof type === "function" ? false : type; - if (type) - return callback(null, type); - fs27.lstat(srcpath, (err, stats) => { - if (err) - return callback(null, "file"); - type = stats && stats.isDirectory() ? "dir" : "file"; - callback(null, type); - }); - } - function symlinkTypeSync(srcpath, type) { - let stats; - if (type) - return type; - try { - stats = fs27.lstatSync(srcpath); - } catch (e) { - return "file"; - } - return stats && stats.isDirectory() ? "dir" : "file"; - } - module2.exports = { - symlinkType, - symlinkTypeSync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/ensure/symlink.js -var require_symlink = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/ensure/symlink.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - var path36 = require("path"); - var fs27 = require_graceful_fs(); - var _mkdirs = require_mkdirs2(); - var mkdirs = _mkdirs.mkdirs; - var mkdirsSync = _mkdirs.mkdirsSync; - var _symlinkPaths = require_symlink_paths(); - var symlinkPaths = _symlinkPaths.symlinkPaths; - var symlinkPathsSync = _symlinkPaths.symlinkPathsSync; - var _symlinkType = require_symlink_type(); - var symlinkType = _symlinkType.symlinkType; - var symlinkTypeSync = _symlinkType.symlinkTypeSync; - var pathExists = require_path_exists().pathExists; - function createSymlink(srcpath, dstpath, type, callback) { - callback = typeof type === "function" ? type : callback; - type = typeof type === "function" ? false : type; - pathExists(dstpath, (err, destinationExists) => { - if (err) - return callback(err); - if (destinationExists) - return callback(null); - symlinkPaths(srcpath, dstpath, (err2, relative) => { - if (err2) - return callback(err2); - srcpath = relative.toDst; - symlinkType(relative.toCwd, type, (err3, type2) => { - if (err3) - return callback(err3); - const dir = path36.dirname(dstpath); - pathExists(dir, (err4, dirExists) => { - if (err4) - return callback(err4); - if (dirExists) - return fs27.symlink(srcpath, dstpath, type2, callback); - mkdirs(dir, (err5) => { - if (err5) - return callback(err5); - fs27.symlink(srcpath, dstpath, type2, callback); - }); - }); - }); - }); - }); - } - function createSymlinkSync(srcpath, dstpath, type) { - const destinationExists = fs27.existsSync(dstpath); - if (destinationExists) - return void 0; - const relative = symlinkPathsSync(srcpath, dstpath); - srcpath = relative.toDst; - type = symlinkTypeSync(relative.toCwd, type); - const dir = path36.dirname(dstpath); - const exists = fs27.existsSync(dir); - if (exists) - return fs27.symlinkSync(srcpath, dstpath, type); - mkdirsSync(dir); - return fs27.symlinkSync(srcpath, dstpath, type); - } - module2.exports = { - createSymlink: u(createSymlink), - createSymlinkSync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/ensure/index.js -var require_ensure = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/ensure/index.js"(exports2, module2) { - "use strict"; - var file = require_file(); - var link = require_link(); - var symlink = require_symlink(); - module2.exports = { - createFile: file.createFile, - createFileSync: file.createFileSync, - ensureFile: file.createFile, - ensureFileSync: file.createFileSync, - createLink: link.createLink, - createLinkSync: link.createLinkSync, - ensureLink: link.createLink, - ensureLinkSync: link.createLinkSync, - createSymlink: symlink.createSymlink, - createSymlinkSync: symlink.createSymlinkSync, - ensureSymlink: symlink.createSymlink, - ensureSymlinkSync: symlink.createSymlinkSync - }; - } -}); - -// node_modules/streamroller/node_modules/jsonfile/index.js -var require_jsonfile = __commonJS({ - "node_modules/streamroller/node_modules/jsonfile/index.js"(exports2, module2) { - var _fs; - try { - _fs = require_graceful_fs(); - } catch (_) { - _fs = require("fs"); - } - function readFile2(file, options, callback) { - if (callback == null) { - callback = options; - options = {}; - } - if (typeof options === "string") { - options = { encoding: options }; - } - options = options || {}; - var fs27 = options.fs || _fs; - var shouldThrow = true; - if ("throws" in options) { - shouldThrow = options.throws; - } - fs27.readFile(file, options, function(err, data) { - if (err) - return callback(err); - data = stripBom(data); - var obj; - try { - obj = JSON.parse(data, options ? options.reviver : null); - } catch (err2) { - if (shouldThrow) { - err2.message = file + ": " + err2.message; - return callback(err2); - } else { - return callback(null, null); - } - } - callback(null, obj); - }); - } - function readFileSync(file, options) { - options = options || {}; - if (typeof options === "string") { - options = { encoding: options }; - } - var fs27 = options.fs || _fs; - var shouldThrow = true; - if ("throws" in options) { - shouldThrow = options.throws; - } - try { - var content = fs27.readFileSync(file, options); - content = stripBom(content); - return JSON.parse(content, options.reviver); - } catch (err) { - if (shouldThrow) { - err.message = file + ": " + err.message; - throw err; - } else { - return null; - } - } - } - function stringify3(obj, options) { - var spaces; - var EOL2 = "\n"; - if (typeof options === "object" && options !== null) { - if (options.spaces) { - spaces = options.spaces; - } - if (options.EOL) { - EOL2 = options.EOL; - } - } - var str = JSON.stringify(obj, options ? options.replacer : null, spaces); - return str.replace(/\n/g, EOL2) + EOL2; - } - function writeFile2(file, obj, options, callback) { - if (callback == null) { - callback = options; - options = {}; - } - options = options || {}; - var fs27 = options.fs || _fs; - var str = ""; - try { - str = stringify3(obj, options); - } catch (err) { - if (callback) - callback(err, null); - return; - } - fs27.writeFile(file, str, options, callback); - } - function writeFileSync(file, obj, options) { - options = options || {}; - var fs27 = options.fs || _fs; - var str = stringify3(obj, options); - return fs27.writeFileSync(file, str, options); - } - function stripBom(content) { - if (Buffer.isBuffer(content)) - content = content.toString("utf8"); - content = content.replace(/^\uFEFF/, ""); - return content; - } - var jsonfile = { - readFile: readFile2, - readFileSync, - writeFile: writeFile2, - writeFileSync - }; - module2.exports = jsonfile; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/json/jsonfile.js -var require_jsonfile2 = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/json/jsonfile.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - var jsonFile = require_jsonfile(); - module2.exports = { - readJson: u(jsonFile.readFile), - readJsonSync: jsonFile.readFileSync, - writeJson: u(jsonFile.writeFile), - writeJsonSync: jsonFile.writeFileSync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/json/output-json.js -var require_output_json = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/json/output-json.js"(exports2, module2) { - "use strict"; - var path36 = require("path"); - var mkdir = require_mkdirs2(); - var pathExists = require_path_exists().pathExists; - var jsonFile = require_jsonfile2(); - function outputJson(file, data, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - const dir = path36.dirname(file); - pathExists(dir, (err, itDoes) => { - if (err) - return callback(err); - if (itDoes) - return jsonFile.writeJson(file, data, options, callback); - mkdir.mkdirs(dir, (err2) => { - if (err2) - return callback(err2); - jsonFile.writeJson(file, data, options, callback); - }); - }); - } - module2.exports = outputJson; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/json/output-json-sync.js -var require_output_json_sync = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/json/output-json-sync.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var mkdir = require_mkdirs2(); - var jsonFile = require_jsonfile2(); - function outputJsonSync(file, data, options) { - const dir = path36.dirname(file); - if (!fs27.existsSync(dir)) { - mkdir.mkdirsSync(dir); - } - jsonFile.writeJsonSync(file, data, options); - } - module2.exports = outputJsonSync; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/json/index.js -var require_json = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/json/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - var jsonFile = require_jsonfile2(); - jsonFile.outputJson = u(require_output_json()); - jsonFile.outputJsonSync = require_output_json_sync(); - jsonFile.outputJSON = jsonFile.outputJson; - jsonFile.outputJSONSync = jsonFile.outputJsonSync; - jsonFile.writeJSON = jsonFile.writeJson; - jsonFile.writeJSONSync = jsonFile.writeJsonSync; - jsonFile.readJSON = jsonFile.readJson; - jsonFile.readJSONSync = jsonFile.readJsonSync; - module2.exports = jsonFile; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/move-sync/move-sync.js -var require_move_sync = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/move-sync/move-sync.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var copySync = require_copy_sync2().copySync; - var removeSync = require_remove().removeSync; - var mkdirpSync = require_mkdirs2().mkdirpSync; - var stat = require_stat(); - function moveSync(src, dest, opts) { - opts = opts || {}; - const overwrite = opts.overwrite || opts.clobber || false; - const { srcStat } = stat.checkPathsSync(src, dest, "move"); - stat.checkParentPathsSync(src, srcStat, dest, "move"); - mkdirpSync(path36.dirname(dest)); - return doRename(src, dest, overwrite); - } - function doRename(src, dest, overwrite) { - if (overwrite) { - removeSync(dest); - return rename(src, dest, overwrite); - } - if (fs27.existsSync(dest)) - throw new Error("dest already exists."); - return rename(src, dest, overwrite); - } - function rename(src, dest, overwrite) { - try { - fs27.renameSync(src, dest); - } catch (err) { - if (err.code !== "EXDEV") - throw err; - return moveAcrossDevice(src, dest, overwrite); - } - } - function moveAcrossDevice(src, dest, overwrite) { - const opts = { - overwrite, - errorOnExist: true - }; - copySync(src, dest, opts); - return removeSync(src); - } - module2.exports = moveSync; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/move-sync/index.js -var require_move_sync2 = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/move-sync/index.js"(exports2, module2) { - "use strict"; - module2.exports = { - moveSync: require_move_sync() - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/move/move.js -var require_move = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/move/move.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var copy = require_copy2().copy; - var remove = require_remove().remove; - var mkdirp = require_mkdirs2().mkdirp; - var pathExists = require_path_exists().pathExists; - var stat = require_stat(); - function move(src, dest, opts, cb) { - if (typeof opts === "function") { - cb = opts; - opts = {}; - } - const overwrite = opts.overwrite || opts.clobber || false; - stat.checkPaths(src, dest, "move", (err, stats) => { - if (err) - return cb(err); - const { srcStat } = stats; - stat.checkParentPaths(src, srcStat, dest, "move", (err2) => { - if (err2) - return cb(err2); - mkdirp(path36.dirname(dest), (err3) => { - if (err3) - return cb(err3); - return doRename(src, dest, overwrite, cb); - }); - }); - }); - } - function doRename(src, dest, overwrite, cb) { - if (overwrite) { - return remove(dest, (err) => { - if (err) - return cb(err); - return rename(src, dest, overwrite, cb); - }); - } - pathExists(dest, (err, destExists) => { - if (err) - return cb(err); - if (destExists) - return cb(new Error("dest already exists.")); - return rename(src, dest, overwrite, cb); - }); - } - function rename(src, dest, overwrite, cb) { - fs27.rename(src, dest, (err) => { - if (!err) - return cb(); - if (err.code !== "EXDEV") - return cb(err); - return moveAcrossDevice(src, dest, overwrite, cb); - }); - } - function moveAcrossDevice(src, dest, overwrite, cb) { - const opts = { - overwrite, - errorOnExist: true - }; - copy(src, dest, opts, (err) => { - if (err) - return cb(err); - return remove(src, cb); - }); - } - module2.exports = move; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/move/index.js -var require_move2 = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/move/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - module2.exports = { - move: u(require_move()) - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/output/index.js -var require_output = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/output/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify().fromCallback; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var mkdir = require_mkdirs2(); - var pathExists = require_path_exists().pathExists; - function outputFile(file, data, encoding, callback) { - if (typeof encoding === "function") { - callback = encoding; - encoding = "utf8"; - } - const dir = path36.dirname(file); - pathExists(dir, (err, itDoes) => { - if (err) - return callback(err); - if (itDoes) - return fs27.writeFile(file, data, encoding, callback); - mkdir.mkdirs(dir, (err2) => { - if (err2) - return callback(err2); - fs27.writeFile(file, data, encoding, callback); - }); - }); - } - function outputFileSync(file, ...args) { - const dir = path36.dirname(file); - if (fs27.existsSync(dir)) { - return fs27.writeFileSync(file, ...args); - } - mkdir.mkdirsSync(dir); - fs27.writeFileSync(file, ...args); - } - module2.exports = { - outputFile: u(outputFile), - outputFileSync - }; - } -}); - -// node_modules/streamroller/node_modules/fs-extra/lib/index.js -var require_lib2 = __commonJS({ - "node_modules/streamroller/node_modules/fs-extra/lib/index.js"(exports2, module2) { - "use strict"; - module2.exports = Object.assign({}, require_fs(), require_copy_sync2(), require_copy2(), require_empty(), require_ensure(), require_json(), require_mkdirs2(), require_move_sync2(), require_move2(), require_output(), require_path_exists(), require_remove()); - var fs27 = require("fs"); - if (Object.getOwnPropertyDescriptor(fs27, "promises")) { - Object.defineProperty(module2.exports, "promises", { - get() { - return fs27.promises; - } - }); - } - } -}); - -// node_modules/streamroller/lib/now.js -var require_now = __commonJS({ - "node_modules/streamroller/lib/now.js"(exports2, module2) { - module2.exports = () => new Date(); - } -}); - -// node_modules/streamroller/node_modules/date-format/lib/index.js -var require_lib3 = __commonJS({ - "node_modules/streamroller/node_modules/date-format/lib/index.js"(exports2, module2) { - "use strict"; - function padWithZeros(vNumber, width) { - var numAsString = vNumber.toString(); - while (numAsString.length < width) { - numAsString = "0" + numAsString; - } - return numAsString; - } - function addZero(vNumber) { - return padWithZeros(vNumber, 2); - } - function offset(timezoneOffset) { - var os10 = Math.abs(timezoneOffset); - var h = String(Math.floor(os10 / 60)); - var m = String(os10 % 60); - if (h.length === 1) { - h = "0" + h; - } - if (m.length === 1) { - m = "0" + m; - } - return timezoneOffset < 0 ? "+" + h + m : "-" + h + m; - } - function datePart(date, displayUTC, part) { - return displayUTC ? date["getUTC" + part]() : date["get" + part](); - } - function asString(format2, date) { - if (typeof format2 !== "string") { - date = format2; - format2 = module2.exports.ISO8601_FORMAT; - } - if (!date) { - date = module2.exports.now(); - } - var displayUTC = format2.indexOf("O") > -1; - var vDay = addZero(datePart(date, displayUTC, "Date")); - var vMonth = addZero(datePart(date, displayUTC, "Month") + 1); - var vYearLong = addZero(datePart(date, displayUTC, "FullYear")); - var vYearShort = addZero(vYearLong.substring(2, 4)); - var vYear = format2.indexOf("yyyy") > -1 ? vYearLong : vYearShort; - var vHour = addZero(datePart(date, displayUTC, "Hours")); - var vMinute = addZero(datePart(date, displayUTC, "Minutes")); - var vSecond = addZero(datePart(date, displayUTC, "Seconds")); - var vMillisecond = padWithZeros(datePart(date, displayUTC, "Milliseconds"), 3); - var vTimeZone = offset(date.getTimezoneOffset()); - var formatted = format2.replace(/dd/g, vDay).replace(/MM/g, vMonth).replace(/y{1,4}/g, vYear).replace(/hh/g, vHour).replace(/mm/g, vMinute).replace(/ss/g, vSecond).replace(/SSS/g, vMillisecond).replace(/O/g, vTimeZone); - return formatted; - } - function extractDateParts(pattern, str, missingValuesDate) { - var matchers = [ - { - pattern: /y{1,4}/, - regexp: "\\d{1,4}", - fn: function(date2, value) { - date2.setFullYear(value); - } - }, - { - pattern: /MM/, - regexp: "\\d{1,2}", - fn: function(date2, value) { - date2.setMonth(value - 1); - } - }, - { - pattern: /dd/, - regexp: "\\d{1,2}", - fn: function(date2, value) { - date2.setDate(value); - } - }, - { - pattern: /hh/, - regexp: "\\d{1,2}", - fn: function(date2, value) { - date2.setHours(value); - } - }, - { - pattern: /mm/, - regexp: "\\d\\d", - fn: function(date2, value) { - date2.setMinutes(value); - } - }, - { - pattern: /ss/, - regexp: "\\d\\d", - fn: function(date2, value) { - date2.setSeconds(value); - } - }, - { - pattern: /SSS/, - regexp: "\\d\\d\\d", - fn: function(date2, value) { - date2.setMilliseconds(value); - } - }, - { - pattern: /O/, - regexp: "[+-]\\d{3,4}|Z", - fn: function(date2, value) { - if (value === "Z") { - value = 0; - } - var offset2 = Math.abs(value); - var minutes = offset2 % 100 + Math.floor(offset2 / 100) * 60; - date2.setMinutes(date2.getMinutes() + (value > 0 ? minutes : -minutes)); - } - } - ]; - var parsedPattern = matchers.reduce(function(p, m) { - if (m.pattern.test(p.regexp)) { - m.index = p.regexp.match(m.pattern).index; - p.regexp = p.regexp.replace(m.pattern, "(" + m.regexp + ")"); - } else { - m.index = -1; - } - return p; - }, { regexp: pattern, index: [] }); - var dateFns = matchers.filter(function(m) { - return m.index > -1; - }); - dateFns.sort(function(a, b) { - return a.index - b.index; - }); - var matcher = new RegExp(parsedPattern.regexp); - var matches = matcher.exec(str); - if (matches) { - var date = missingValuesDate || module2.exports.now(); - dateFns.forEach(function(f, i) { - f.fn(date, matches[i + 1]); - }); - return date; - } - throw new Error("String '" + str + "' could not be parsed as '" + pattern + "'"); - } - function parse5(pattern, str, missingValuesDate) { - if (!pattern) { - throw new Error("pattern must be supplied"); - } - return extractDateParts(pattern, str, missingValuesDate); - } - function now() { - return new Date(); - } - module2.exports = asString; - module2.exports.asString = asString; - module2.exports.parse = parse5; - module2.exports.now = now; - module2.exports.ISO8601_FORMAT = "yyyy-MM-ddThh:mm:ss.SSS"; - module2.exports.ISO8601_WITH_TZ_OFFSET_FORMAT = "yyyy-MM-ddThh:mm:ss.SSSO"; - module2.exports.DATETIME_FORMAT = "dd MM yyyy hh:mm:ss.SSS"; - module2.exports.ABSOLUTETIME_FORMAT = "hh:mm:ss.SSS"; - } -}); - -// node_modules/streamroller/lib/fileNameFormatter.js -var require_fileNameFormatter = __commonJS({ - "node_modules/streamroller/lib/fileNameFormatter.js"(exports2, module2) { - var debug = require_src()("streamroller:fileNameFormatter"); - var path36 = require("path"); - var FILENAME_SEP = "."; - var ZIP_EXT = ".gz"; - module2.exports = ({ - file, - keepFileExt, - needsIndex, - alwaysIncludeDate, - compress - }) => { - const dirAndName = path36.join(file.dir, file.name); - const ext = (f) => f + file.ext; - const index = (f, i, d) => (needsIndex || !d) && i ? f + FILENAME_SEP + i : f; - const date = (f, i, d) => { - return (i > 0 || alwaysIncludeDate) && d ? f + FILENAME_SEP + d : f; - }; - const gzip = (f, i) => i && compress ? f + ZIP_EXT : f; - const parts = keepFileExt ? [date, index, ext, gzip] : [ext, date, index, gzip]; - return ({ date: date2, index: index2 }) => { - debug(`_formatFileName: date=${date2}, index=${index2}`); - return parts.reduce((filename, part) => part(filename, index2, date2), dirAndName); - }; - }; - } -}); - -// node_modules/streamroller/lib/fileNameParser.js -var require_fileNameParser = __commonJS({ - "node_modules/streamroller/lib/fileNameParser.js"(exports2, module2) { - var debug = require_src()("streamroller:fileNameParser"); - var FILENAME_SEP = "."; - var ZIP_EXT = ".gz"; - var format2 = require_lib3(); - module2.exports = ({ file, keepFileExt, pattern }) => { - const zip = (f, p) => { - if (f.endsWith(ZIP_EXT)) { - debug("it is gzipped"); - p.isCompressed = true; - return f.slice(0, -1 * ZIP_EXT.length); - } - return f; - }; - const __NOT_MATCHING__ = "__NOT_MATCHING__"; - const extAtEnd = (f) => { - if (f.startsWith(file.name) && f.endsWith(file.ext)) { - debug("it starts and ends with the right things"); - return f.slice(file.name.length + 1, -1 * file.ext.length); - } - return __NOT_MATCHING__; - }; - const extInMiddle = (f) => { - if (f.startsWith(file.base)) { - debug("it starts with the right things"); - return f.slice(file.base.length + 1); - } - return __NOT_MATCHING__; - }; - const dateAndIndex = (f, p) => { - const items = f.split(FILENAME_SEP); - let indexStr = items[items.length - 1]; - debug("items: ", items, ", indexStr: ", indexStr); - let dateStr = f; - if (indexStr !== void 0 && indexStr.match(/^\d+$/)) { - dateStr = f.slice(0, -1 * (indexStr.length + 1)); - debug(`dateStr is ${dateStr}`); - if (pattern && !dateStr) { - dateStr = indexStr; - indexStr = "0"; - } - } else { - indexStr = "0"; - } - try { - const date = format2.parse(pattern, dateStr, new Date(0, 0)); - if (format2.asString(pattern, date) !== dateStr) - return f; - p.index = parseInt(indexStr, 10); - p.date = dateStr; - p.timestamp = date.getTime(); - return ""; - } catch (e) { - debug(`Problem parsing ${dateStr} as ${pattern}, error was: `, e); - return f; - } - }; - const index = (f, p) => { - if (f.match(/^\d+$/)) { - debug("it has an index"); - p.index = parseInt(f, 10); - return ""; - } - return f; - }; - let parts = [ - zip, - keepFileExt ? extAtEnd : extInMiddle, - pattern ? dateAndIndex : index - ]; - return (filename) => { - let result = { filename, index: 0, isCompressed: false }; - let whatsLeftOver = parts.reduce((remains, part) => part(remains, result), filename); - return whatsLeftOver ? null : result; - }; - }; - } -}); - -// node_modules/streamroller/lib/moveAndMaybeCompressFile.js -var require_moveAndMaybeCompressFile = __commonJS({ - "node_modules/streamroller/lib/moveAndMaybeCompressFile.js"(exports2, module2) { - var debug = require_src()("streamroller:moveAndMaybeCompressFile"); - var fs27 = require_lib2(); - var zlib = require("zlib"); - var moveAndMaybeCompressFile = async (sourceFilePath, targetFilePath, needCompress) => { - if (sourceFilePath === targetFilePath) { - debug(`moveAndMaybeCompressFile: source and target are the same, not doing anything`); - return; - } - if (await fs27.pathExists(sourceFilePath)) { - debug(`moveAndMaybeCompressFile: moving file from ${sourceFilePath} to ${targetFilePath} ${needCompress ? "with" : "without"} compress`); - if (needCompress) { - await new Promise((resolve3, reject) => { - fs27.createReadStream(sourceFilePath).pipe(zlib.createGzip()).pipe(fs27.createWriteStream(targetFilePath)).on("finish", () => { - debug(`moveAndMaybeCompressFile: finished compressing ${targetFilePath}, deleting ${sourceFilePath}`); - fs27.unlink(sourceFilePath).then(resolve3).catch(() => { - debug(`Deleting ${sourceFilePath} failed, truncating instead`); - fs27.truncate(sourceFilePath).then(resolve3).catch(reject); - }); - }); - }); - } else { - debug(`moveAndMaybeCompressFile: deleting file=${targetFilePath}, renaming ${sourceFilePath} to ${targetFilePath}`); - try { - await fs27.move(sourceFilePath, targetFilePath, { overwrite: true }); - } catch (e) { - debug(`moveAndMaybeCompressFile: error moving ${sourceFilePath} to ${targetFilePath}`, e); - debug(`Trying copy+truncate instead`); - await fs27.copy(sourceFilePath, targetFilePath, { overwrite: true }); - await fs27.truncate(sourceFilePath); - } - } - } - }; - module2.exports = moveAndMaybeCompressFile; - } -}); - -// node_modules/streamroller/lib/RollingFileWriteStream.js -var require_RollingFileWriteStream = __commonJS({ - "node_modules/streamroller/lib/RollingFileWriteStream.js"(exports2, module2) { - var debug = require_src()("streamroller:RollingFileWriteStream"); - var fs27 = require_lib2(); - var path36 = require("path"); - var newNow = require_now(); - var format2 = require_lib3(); - var { Writable } = require("stream"); - var fileNameFormatter = require_fileNameFormatter(); - var fileNameParser = require_fileNameParser(); - var moveAndMaybeCompressFile = require_moveAndMaybeCompressFile(); - var RollingFileWriteStream = class extends Writable { - constructor(filePath, options) { - debug(`constructor: creating RollingFileWriteStream. path=${filePath}`); - super(options); - this.options = this._parseOption(options); - this.fileObject = path36.parse(filePath); - if (this.fileObject.dir === "") { - this.fileObject = path36.parse(path36.join(process.cwd(), filePath)); - } - this.fileFormatter = fileNameFormatter({ - file: this.fileObject, - alwaysIncludeDate: this.options.alwaysIncludePattern, - needsIndex: this.options.maxSize < Number.MAX_SAFE_INTEGER, - compress: this.options.compress, - keepFileExt: this.options.keepFileExt - }); - this.fileNameParser = fileNameParser({ - file: this.fileObject, - keepFileExt: this.options.keepFileExt, - pattern: this.options.pattern - }); - this.state = { - currentSize: 0 - }; - if (this.options.pattern) { - this.state.currentDate = format2(this.options.pattern, newNow()); - } - this.filename = this.fileFormatter({ - index: 0, - date: this.state.currentDate - }); - if (["a", "a+", "as", "as+"].includes(this.options.flags)) { - this._setExistingSizeAndDate(); - } - debug(`constructor: create new file ${this.filename}, state=${JSON.stringify(this.state)}`); - this._renewWriteStream(); - } - _setExistingSizeAndDate() { - try { - const stats = fs27.statSync(this.filename); - this.state.currentSize = stats.size; - if (this.options.pattern) { - this.state.currentDate = format2(this.options.pattern, stats.mtime); - } - } catch (e) { - return; - } - } - _parseOption(rawOptions) { - const defaultOptions2 = { - maxSize: Number.MAX_SAFE_INTEGER, - numToKeep: Number.MAX_SAFE_INTEGER, - encoding: "utf8", - mode: parseInt("0644", 8), - flags: "a", - compress: false, - keepFileExt: false, - alwaysIncludePattern: false - }; - const options = Object.assign({}, defaultOptions2, rawOptions); - if (options.maxSize <= 0) { - throw new Error(`options.maxSize (${options.maxSize}) should be > 0`); - } - if (options.numToKeep <= 0) { - throw new Error(`options.numToKeep (${options.numToKeep}) should be > 0`); - } - debug(`_parseOption: creating stream with option=${JSON.stringify(options)}`); - return options; - } - _final(callback) { - this.currentFileStream.end("", this.options.encoding, callback); - } - _write(chunk, encoding, callback) { - this._shouldRoll().then(() => { - debug(`_write: writing chunk. file=${this.currentFileStream.path} state=${JSON.stringify(this.state)} chunk=${chunk}`); - this.currentFileStream.write(chunk, encoding, (e) => { - this.state.currentSize += chunk.length; - callback(e); - }); - }); - } - async _shouldRoll() { - if (this._dateChanged() || this._tooBig()) { - debug(`_shouldRoll: rolling because dateChanged? ${this._dateChanged()} or tooBig? ${this._tooBig()}`); - await this._roll(); - } - } - _dateChanged() { - return this.state.currentDate && this.state.currentDate !== format2(this.options.pattern, newNow()); - } - _tooBig() { - return this.state.currentSize >= this.options.maxSize; - } - _roll() { - debug(`_roll: closing the current stream`); - return new Promise((resolve3, reject) => { - this.currentFileStream.end("", this.options.encoding, () => { - this._moveOldFiles().then(resolve3).catch(reject); - }); - }); - } - async _moveOldFiles() { - const files = await this._getExistingFiles(); - const todaysFiles = this.state.currentDate ? files.filter((f) => f.date === this.state.currentDate) : files; - for (let i = todaysFiles.length; i >= 0; i--) { - debug(`_moveOldFiles: i = ${i}`); - const sourceFilePath = this.fileFormatter({ - date: this.state.currentDate, - index: i - }); - const targetFilePath = this.fileFormatter({ - date: this.state.currentDate, - index: i + 1 - }); - await moveAndMaybeCompressFile(sourceFilePath, targetFilePath, this.options.compress && i === 0); - } - this.state.currentSize = 0; - this.state.currentDate = this.state.currentDate ? format2(this.options.pattern, newNow()) : null; - debug(`_moveOldFiles: finished rolling files. state=${JSON.stringify(this.state)}`); - this._renewWriteStream(); - await new Promise((resolve3, reject) => { - this.currentFileStream.write("", "utf8", () => { - this._clean().then(resolve3).catch(reject); - }); - }); - } - async _getExistingFiles() { - const files = await fs27.readdir(this.fileObject.dir).catch(() => []); - debug(`_getExistingFiles: files=${files}`); - const existingFileDetails = files.map((n) => this.fileNameParser(n)).filter((n) => n); - const getKey = (n) => (n.timestamp ? n.timestamp : newNow().getTime()) - n.index; - existingFileDetails.sort((a, b) => getKey(a) - getKey(b)); - return existingFileDetails; - } - _renewWriteStream() { - fs27.ensureDirSync(this.fileObject.dir); - const filePath = this.fileFormatter({ - date: this.state.currentDate, - index: 0 - }); - const ops = { - flags: this.options.flags, - encoding: this.options.encoding, - mode: this.options.mode - }; - this.currentFileStream = fs27.createWriteStream(filePath, ops); - this.currentFileStream.on("error", (e) => { - this.emit("error", e); - }); - } - async _clean() { - const existingFileDetails = await this._getExistingFiles(); - debug(`_clean: numToKeep = ${this.options.numToKeep}, existingFiles = ${existingFileDetails.length}`); - debug("_clean: existing files are: ", existingFileDetails); - if (this._tooManyFiles(existingFileDetails.length)) { - const fileNamesToRemove = existingFileDetails.slice(0, existingFileDetails.length - this.options.numToKeep - 1).map((f) => path36.format({ dir: this.fileObject.dir, base: f.filename })); - await deleteFiles(fileNamesToRemove); - } - } - _tooManyFiles(numFiles) { - return this.options.numToKeep > 0 && numFiles > this.options.numToKeep; - } - }; - var deleteFiles = (fileNames) => { - debug(`deleteFiles: files to delete: ${fileNames}`); - return Promise.all(fileNames.map((f) => fs27.unlink(f).catch((e) => { - debug(`deleteFiles: error when unlinking ${f}, ignoring. Error was ${e}`); - }))); - }; - module2.exports = RollingFileWriteStream; - } -}); - -// node_modules/streamroller/lib/RollingFileStream.js -var require_RollingFileStream = __commonJS({ - "node_modules/streamroller/lib/RollingFileStream.js"(exports2, module2) { - var RollingFileWriteStream = require_RollingFileWriteStream(); - var RollingFileStream = class extends RollingFileWriteStream { - constructor(filename, size, backups, options) { - if (!options) { - options = {}; - } - if (size) { - options.maxSize = size; - } - if (!backups) { - backups = 1; - } - options.numToKeep = backups; - super(filename, options); - this.backups = this.options.numToKeep; - this.size = this.options.maxSize; - } - get theStream() { - return this.currentFileStream; - } - }; - module2.exports = RollingFileStream; - } -}); - -// node_modules/streamroller/lib/DateRollingFileStream.js -var require_DateRollingFileStream = __commonJS({ - "node_modules/streamroller/lib/DateRollingFileStream.js"(exports2, module2) { - var RollingFileWriteStream = require_RollingFileWriteStream(); - var DateRollingFileStream = class extends RollingFileWriteStream { - constructor(filename, pattern, options) { - if (pattern && typeof pattern === "object") { - options = pattern; - pattern = null; - } - if (!options) { - options = {}; - } - if (!pattern) { - pattern = "yyyy-MM-dd"; - } - if (options.daysToKeep) { - options.numToKeep = options.daysToKeep; - } - if (pattern.startsWith(".")) { - pattern = pattern.substring(1); - } - options.pattern = pattern; - super(filename, options); - this.mode = this.options.mode; - } - get theStream() { - return this.currentFileStream; - } - }; - module2.exports = DateRollingFileStream; - } -}); - -// node_modules/streamroller/lib/index.js -var require_lib4 = __commonJS({ - "node_modules/streamroller/lib/index.js"(exports2, module2) { - module2.exports = { - RollingFileWriteStream: require_RollingFileWriteStream(), - RollingFileStream: require_RollingFileStream(), - DateRollingFileStream: require_DateRollingFileStream() - }; - } -}); - -// node_modules/log4js/lib/appenders/file.js -var require_file2 = __commonJS({ - "node_modules/log4js/lib/appenders/file.js"(exports2, module2) { - var debug = require_src()("log4js:file"); - var path36 = require("path"); - var streams = require_lib4(); - var os10 = require("os"); - var eol = os10.EOL; - function openTheStream(file, fileSize, numFiles, options) { - const stream = new streams.RollingFileStream(file, fileSize, numFiles, options); - stream.on("error", (err) => { - console.error("log4js.fileAppender - Writing to file %s, error happened ", file, err); - }); - stream.on("drain", () => { - process.emit("log4js:pause", false); - }); - return stream; - } - function fileAppender(file, layout, logSize, numBackups, options, timezoneOffset) { - file = path36.normalize(file); - numBackups = numBackups === void 0 ? 5 : numBackups; - numBackups = numBackups === 0 ? 1 : numBackups; - debug("Creating file appender (", file, ", ", logSize, ", ", numBackups, ", ", options, ", ", timezoneOffset, ")"); - let writer = openTheStream(file, logSize, numBackups, options); - const app = function(loggingEvent) { - if (options.removeColor === true) { - const regex = /\x1b[[0-9;]*m/g; - loggingEvent.data = loggingEvent.data.map((d) => { - if (typeof d === "string") - return d.replace(regex, ""); - return d; - }); - } - if (!writer.write(layout(loggingEvent, timezoneOffset) + eol, "utf8")) { - process.emit("log4js:pause", true); - } - }; - app.reopen = function() { - writer.end(() => { - writer = openTheStream(file, logSize, numBackups, options); - }); - }; - app.sighupHandler = function() { - debug("SIGHUP handler called."); - app.reopen(); - }; - app.shutdown = function(complete) { - process.removeListener("SIGHUP", app.sighupHandler); - writer.end("", "utf-8", complete); - }; - process.on("SIGHUP", app.sighupHandler); - return app; - } - function configure(config, layouts) { - let layout = layouts.basicLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - return fileAppender(config.filename, layout, config.maxLogSize, config.backups, config, config.timezoneOffset); - } - module2.exports.configure = configure; - } -}); - -// node_modules/log4js/lib/appenders/dateFile.js -var require_dateFile = __commonJS({ - "node_modules/log4js/lib/appenders/dateFile.js"(exports2, module2) { - var streams = require_lib4(); - var os10 = require("os"); - var eol = os10.EOL; - function appender(filename, pattern, layout, options, timezoneOffset) { - options.maxSize = options.maxLogSize; - const logFile = new streams.DateRollingFileStream(filename, pattern, options); - logFile.on("drain", () => { - process.emit("log4js:pause", false); - }); - const app = function(logEvent) { - if (!logFile.write(layout(logEvent, timezoneOffset) + eol, "utf8")) { - process.emit("log4js:pause", true); - } - }; - app.shutdown = function(complete) { - logFile.write("", "utf-8", () => { - logFile.end(complete); - }); - }; - return app; - } - function configure(config, layouts) { - let layout = layouts.basicLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - if (!config.alwaysIncludePattern) { - config.alwaysIncludePattern = false; - } - return appender(config.filename, config.pattern, layout, config, config.timezoneOffset); - } - module2.exports.configure = configure; - } -}); - -// node_modules/log4js/lib/appenders/fileSync.js -var require_fileSync = __commonJS({ - "node_modules/log4js/lib/appenders/fileSync.js"(exports2, module2) { - var debug = require_src()("log4js:fileSync"); - var path36 = require("path"); - var fs27 = require("fs"); - var os10 = require("os"); - var eol = os10.EOL || "\n"; - function touchFile(file, options) { - if (fs27.existsSync(file)) { - return; - } - const id = fs27.openSync(file, options.flags, options.mode); - fs27.closeSync(id); - } - var RollingFileSync = class { - constructor(filename, size, backups, options) { - debug("In RollingFileStream"); - function throwErrorIfArgumentsAreNotValid() { - if (!filename || !size || size <= 0) { - throw new Error("You must specify a filename and file size"); - } - } - throwErrorIfArgumentsAreNotValid(); - this.filename = filename; - this.size = size; - this.backups = backups || 1; - this.options = options; - this.currentSize = 0; - function currentFileSize(file) { - let fileSize = 0; - try { - fileSize = fs27.statSync(file).size; - } catch (e) { - touchFile(file, options); - } - return fileSize; - } - this.currentSize = currentFileSize(this.filename); - } - shouldRoll() { - debug("should roll with current size %d, and max size %d", this.currentSize, this.size); - return this.currentSize >= this.size; - } - roll(filename) { - const that = this; - const nameMatcher = new RegExp(`^${path36.basename(filename)}`); - function justTheseFiles(item) { - return nameMatcher.test(item); - } - function index(filename_) { - return parseInt(filename_.substring(`${path36.basename(filename)}.`.length), 10) || 0; - } - function byIndex(a, b) { - if (index(a) > index(b)) { - return 1; - } - if (index(a) < index(b)) { - return -1; - } - return 0; - } - function increaseFileIndex(fileToRename) { - const idx = index(fileToRename); - debug(`Index of ${fileToRename} is ${idx}`); - if (idx < that.backups) { - try { - fs27.unlinkSync(`${filename}.${idx + 1}`); - } catch (e) { - } - debug(`Renaming ${fileToRename} -> ${filename}.${idx + 1}`); - fs27.renameSync(path36.join(path36.dirname(filename), fileToRename), `${filename}.${idx + 1}`); - } - } - function renameTheFiles() { - debug("Renaming the old files"); - const files = fs27.readdirSync(path36.dirname(filename)); - files.filter(justTheseFiles).sort(byIndex).reverse().forEach(increaseFileIndex); - } - debug("Rolling, rolling, rolling"); - renameTheFiles(); - } - write(chunk, encoding) { - const that = this; - function writeTheChunk() { - debug("writing the chunk to the file"); - that.currentSize += chunk.length; - fs27.appendFileSync(that.filename, chunk); - } - debug("in write"); - if (this.shouldRoll()) { - this.currentSize = 0; - this.roll(this.filename); - } - writeTheChunk(); - } - }; - function fileAppender(file, layout, logSize, numBackups, timezoneOffset, options) { - debug("fileSync appender created"); - file = path36.normalize(file); - numBackups = numBackups === void 0 ? 5 : numBackups; - numBackups = numBackups === 0 ? 1 : numBackups; - function openTheStream(filePath, fileSize, numFiles) { - let stream; - if (fileSize) { - stream = new RollingFileSync(filePath, fileSize, numFiles, options); - } else { - stream = ((f) => { - touchFile(f, options); - return { - write(data) { - fs27.appendFileSync(f, data); - } - }; - })(filePath); - } - return stream; - } - const logFile = openTheStream(file, logSize, numBackups); - return (loggingEvent) => { - logFile.write(layout(loggingEvent, timezoneOffset) + eol); - }; - } - function configure(config, layouts) { - let layout = layouts.basicLayout; - if (config.layout) { - layout = layouts.layout(config.layout.type, config.layout); - } - const options = { - flags: config.flags || "a", - encoding: config.encoding || "utf8", - mode: config.mode || 420 - }; - return fileAppender(config.filename, layout, config.maxLogSize, config.backups, config.timezoneOffset, options); - } - module2.exports.configure = configure; - } -}); - -// env-ns:node_modules/log4js/lib/appenders -var require_appenders = __commonJS({ - "env-ns:node_modules/log4js/lib/appenders"(exports2, module2) { - var path36 = require("path"); - var debug = require_src()("log4js:appenders"); - var configuration = require_configuration(); - var clustering = require_clustering(); - var levels = require_levels(); - var layouts = require_layouts(); - var adapters = require_adapters(); - var coreAppenders = new Map(); - coreAppenders.set("console", require_console()); - coreAppenders.set("stdout", require_stdout()); - coreAppenders.set("stderr", require_stderr()); - coreAppenders.set("logLevelFilter", require_logLevelFilter()); - coreAppenders.set("categoryFilter", require_categoryFilter()); - coreAppenders.set("noLogFilter", require_noLogFilter()); - coreAppenders.set("file", require_file2()); - coreAppenders.set("dateFile", require_dateFile()); - coreAppenders.set("fileSync", require_fileSync()); - var appenders = new Map(); - var tryLoading = (modulePath, config) => { - debug("Loading module from ", modulePath); - try { - return require(modulePath); - } catch (e) { - configuration.throwExceptionIf(config, e.code !== "MODULE_NOT_FOUND", `appender "${modulePath}" could not be loaded (error was: ${e})`); - return void 0; - } - }; - var loadAppenderModule = (type, config) => coreAppenders.get(type) || tryLoading(`./${type}`, config) || tryLoading(type, config) || "" || tryLoading(path36.join(process.cwd(), type), config); - var appendersLoading = new Set(); - var getAppender = (name2, config) => { - if (appenders.has(name2)) - return appenders.get(name2); - if (!config.appenders[name2]) - return false; - if (appendersLoading.has(name2)) - throw new Error(`Dependency loop detected for appender ${name2}.`); - appendersLoading.add(name2); - debug(`Creating appender ${name2}`); - const appender = createAppender(name2, config); - appendersLoading.delete(name2); - appenders.set(name2, appender); - return appender; - }; - var createAppender = (name2, config) => { - const appenderConfig = config.appenders[name2]; - const appenderModule = appenderConfig.type.configure ? appenderConfig.type : loadAppenderModule(appenderConfig.type, config); - configuration.throwExceptionIf(config, configuration.not(appenderModule), `appender "${name2}" is not valid (type "${appenderConfig.type}" could not be found)`); - if (appenderModule.appender) { - debug(`DEPRECATION: Appender ${appenderConfig.type} exports an appender function.`); - } - if (appenderModule.shutdown) { - debug(`DEPRECATION: Appender ${appenderConfig.type} exports a shutdown function.`); - } - debug(`${name2}: clustering.isMaster ? ${clustering.isMaster()}`); - debug(`${name2}: appenderModule is ${require("util").inspect(appenderModule)}`); - return clustering.onlyOnMaster(() => { - debug(`calling appenderModule.configure for ${name2} / ${appenderConfig.type}`); - return appenderModule.configure(adapters.modifyConfig(appenderConfig), layouts, (appender) => getAppender(appender, config), levels); - }, () => { - }); - }; - var setup = (config) => { - appenders.clear(); - appendersLoading.clear(); - const usedAppenders = []; - Object.values(config.categories).forEach((category) => { - usedAppenders.push(...category.appenders); - }); - Object.keys(config.appenders).forEach((name2) => { - if (usedAppenders.includes(name2) || config.appenders[name2].type === "tcp-server") { - getAppender(name2, config); - } - }); - }; - setup({ appenders: { out: { type: "stdout" } }, categories: { default: { appenders: ["out"], level: "trace" } } }); - configuration.addListener((config) => { - configuration.throwExceptionIf(config, configuration.not(configuration.anObject(config.appenders)), 'must have a property "appenders" of type object.'); - const appenderNames = Object.keys(config.appenders); - configuration.throwExceptionIf(config, configuration.not(appenderNames.length), "must define at least one appender."); - appenderNames.forEach((name2) => { - configuration.throwExceptionIf(config, configuration.not(config.appenders[name2].type), `appender "${name2}" is not valid (must be an object with property "type")`); - }); - }); - configuration.addListener(setup); - module2.exports = appenders; - } -}); - -// node_modules/log4js/lib/categories.js -var require_categories = __commonJS({ - "node_modules/log4js/lib/categories.js"(exports2, module2) { - var debug = require_src()("log4js:categories"); - var configuration = require_configuration(); - var levels = require_levels(); - var appenders = require_appenders(); - var categories = new Map(); - function inheritFromParent(config, category, categoryName) { - if (category.inherit === false) - return; - const lastDotIndex = categoryName.lastIndexOf("."); - if (lastDotIndex < 0) - return; - const parentCategoryName = categoryName.substring(0, lastDotIndex); - let parentCategory = config.categories[parentCategoryName]; - if (!parentCategory) { - parentCategory = { inherit: true, appenders: [] }; - } - inheritFromParent(config, parentCategory, parentCategoryName); - if (!config.categories[parentCategoryName] && parentCategory.appenders && parentCategory.appenders.length && parentCategory.level) { - config.categories[parentCategoryName] = parentCategory; - } - category.appenders = category.appenders || []; - category.level = category.level || parentCategory.level; - parentCategory.appenders.forEach((ap) => { - if (!category.appenders.includes(ap)) { - category.appenders.push(ap); - } - }); - category.parent = parentCategory; - } - function addCategoryInheritance(config) { - if (!config.categories) - return; - const categoryNames = Object.keys(config.categories); - categoryNames.forEach((name2) => { - const category = config.categories[name2]; - inheritFromParent(config, category, name2); - }); - } - configuration.addPreProcessingListener((config) => addCategoryInheritance(config)); - configuration.addListener((config) => { - configuration.throwExceptionIf(config, configuration.not(configuration.anObject(config.categories)), 'must have a property "categories" of type object.'); - const categoryNames = Object.keys(config.categories); - configuration.throwExceptionIf(config, configuration.not(categoryNames.length), "must define at least one category."); - categoryNames.forEach((name2) => { - const category = config.categories[name2]; - configuration.throwExceptionIf(config, [ - configuration.not(category.appenders), - configuration.not(category.level) - ], `category "${name2}" is not valid (must be an object with properties "appenders" and "level")`); - configuration.throwExceptionIf(config, configuration.not(Array.isArray(category.appenders)), `category "${name2}" is not valid (appenders must be an array of appender names)`); - configuration.throwExceptionIf(config, configuration.not(category.appenders.length), `category "${name2}" is not valid (appenders must contain at least one appender name)`); - if (Object.prototype.hasOwnProperty.call(category, "enableCallStack")) { - configuration.throwExceptionIf(config, typeof category.enableCallStack !== "boolean", `category "${name2}" is not valid (enableCallStack must be boolean type)`); - } - category.appenders.forEach((appender) => { - configuration.throwExceptionIf(config, configuration.not(appenders.get(appender)), `category "${name2}" is not valid (appender "${appender}" is not defined)`); - }); - configuration.throwExceptionIf(config, configuration.not(levels.getLevel(category.level)), `category "${name2}" is not valid (level "${category.level}" not recognised; valid levels are ${levels.levels.join(", ")})`); - }); - configuration.throwExceptionIf(config, configuration.not(config.categories.default), 'must define a "default" category.'); - }); - var setup = (config) => { - categories.clear(); - const categoryNames = Object.keys(config.categories); - categoryNames.forEach((name2) => { - const category = config.categories[name2]; - const categoryAppenders = []; - category.appenders.forEach((appender) => { - categoryAppenders.push(appenders.get(appender)); - debug(`Creating category ${name2}`); - categories.set(name2, { - appenders: categoryAppenders, - level: levels.getLevel(category.level), - enableCallStack: category.enableCallStack || false - }); - }); - }); - }; - setup({ categories: { default: { appenders: ["out"], level: "OFF" } } }); - configuration.addListener(setup); - var configForCategory = (category) => { - debug(`configForCategory: searching for config for ${category}`); - if (categories.has(category)) { - debug(`configForCategory: ${category} exists in config, returning it`); - return categories.get(category); - } - if (category.indexOf(".") > 0) { - debug(`configForCategory: ${category} has hierarchy, searching for parents`); - return configForCategory(category.substring(0, category.lastIndexOf("."))); - } - debug("configForCategory: returning config for default category"); - return configForCategory("default"); - }; - var appendersForCategory = (category) => configForCategory(category).appenders; - var getLevelForCategory = (category) => configForCategory(category).level; - var setLevelForCategory = (category, level) => { - let categoryConfig = categories.get(category); - debug(`setLevelForCategory: found ${categoryConfig} for ${category}`); - if (!categoryConfig) { - const sourceCategoryConfig = configForCategory(category); - debug(`setLevelForCategory: no config found for category, found ${sourceCategoryConfig} for parents of ${category}`); - categoryConfig = { appenders: sourceCategoryConfig.appenders }; - } - categoryConfig.level = level; - categories.set(category, categoryConfig); - }; - var getEnableCallStackForCategory = (category) => configForCategory(category).enableCallStack === true; - var setEnableCallStackForCategory = (category, useCallStack) => { - configForCategory(category).enableCallStack = useCallStack; - }; - module2.exports = { - appendersForCategory, - getLevelForCategory, - setLevelForCategory, - getEnableCallStackForCategory, - setEnableCallStackForCategory - }; - } -}); - -// node_modules/log4js/lib/logger.js -var require_logger = __commonJS({ - "node_modules/log4js/lib/logger.js"(exports2, module2) { - var debug = require_src()("log4js:logger"); - var LoggingEvent = require_LoggingEvent(); - var levels = require_levels(); - var clustering = require_clustering(); - var categories = require_categories(); - var configuration = require_configuration(); - var stackReg = /at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/; - function defaultParseCallStack(data, skipIdx = 4) { - const stacklines = data.stack.split("\n").slice(skipIdx); - const lineMatch = stackReg.exec(stacklines[0]); - if (lineMatch && lineMatch.length === 6) { - return { - functionName: lineMatch[1], - fileName: lineMatch[2], - lineNumber: parseInt(lineMatch[3], 10), - columnNumber: parseInt(lineMatch[4], 10), - callStack: stacklines.join("\n") - }; - } - return null; - } - var Logger2 = class { - constructor(name2) { - if (!name2) { - throw new Error("No category provided."); - } - this.category = name2; - this.context = {}; - this.parseCallStack = defaultParseCallStack; - debug(`Logger created (${this.category}, ${this.level})`); - } - get level() { - return levels.getLevel(categories.getLevelForCategory(this.category), levels.TRACE); - } - set level(level) { - categories.setLevelForCategory(this.category, levels.getLevel(level, this.level)); - } - get useCallStack() { - return categories.getEnableCallStackForCategory(this.category); - } - set useCallStack(bool) { - categories.setEnableCallStackForCategory(this.category, bool === true); - } - log(level, ...args) { - const logLevel = levels.getLevel(level, levels.INFO); - if (this.isLevelEnabled(logLevel)) { - this._log(logLevel, args); - } - } - isLevelEnabled(otherLevel) { - return this.level.isLessThanOrEqualTo(otherLevel); - } - _log(level, data) { - debug(`sending log data (${level}) to appenders`); - const loggingEvent = new LoggingEvent(this.category, level, data, this.context, this.useCallStack && this.parseCallStack(new Error())); - clustering.send(loggingEvent); - } - addContext(key, value) { - this.context[key] = value; - } - removeContext(key) { - delete this.context[key]; - } - clearContext() { - this.context = {}; - } - setParseCallStackFunction(parseFunction) { - this.parseCallStack = parseFunction; - } - }; - function addLevelMethods(target) { - const level = levels.getLevel(target); - const levelStrLower = level.toString().toLowerCase(); - const levelMethod = levelStrLower.replace(/_([a-z])/g, (g) => g[1].toUpperCase()); - const isLevelMethod = levelMethod[0].toUpperCase() + levelMethod.slice(1); - Logger2.prototype[`is${isLevelMethod}Enabled`] = function() { - return this.isLevelEnabled(level); - }; - Logger2.prototype[levelMethod] = function(...args) { - this.log(level, ...args); - }; - } - levels.levels.forEach(addLevelMethods); - configuration.addListener(() => { - levels.levels.forEach(addLevelMethods); - }); - module2.exports = Logger2; - } -}); - -// node_modules/log4js/lib/connect-logger.js -var require_connect_logger = __commonJS({ - "node_modules/log4js/lib/connect-logger.js"(exports2, module2) { - var levels = require_levels(); - var DEFAULT_FORMAT = ':remote-addr - - ":method :url HTTP/:http-version" :status :content-length ":referrer" ":user-agent"'; - function getUrl(req) { - return req.originalUrl || req.url; - } - function assembleTokens(req, res, customTokens) { - const arrayUniqueTokens = (array) => { - const a = array.concat(); - for (let i = 0; i < a.length; ++i) { - for (let j = i + 1; j < a.length; ++j) { - if (a[i].token == a[j].token) { - a.splice(j--, 1); - } - } - } - return a; - }; - const defaultTokens = []; - defaultTokens.push({ token: ":url", replacement: getUrl(req) }); - defaultTokens.push({ token: ":protocol", replacement: req.protocol }); - defaultTokens.push({ token: ":hostname", replacement: req.hostname }); - defaultTokens.push({ token: ":method", replacement: req.method }); - defaultTokens.push({ - token: ":status", - replacement: res.__statusCode || res.statusCode - }); - defaultTokens.push({ - token: ":response-time", - replacement: res.responseTime - }); - defaultTokens.push({ token: ":date", replacement: new Date().toUTCString() }); - defaultTokens.push({ - token: ":referrer", - replacement: req.headers.referer || req.headers.referrer || "" - }); - defaultTokens.push({ - token: ":http-version", - replacement: `${req.httpVersionMajor}.${req.httpVersionMinor}` - }); - defaultTokens.push({ - token: ":remote-addr", - replacement: req.headers["x-forwarded-for"] || req.ip || req._remoteAddress || req.socket && (req.socket.remoteAddress || req.socket.socket && req.socket.socket.remoteAddress) - }); - defaultTokens.push({ - token: ":user-agent", - replacement: req.headers["user-agent"] - }); - defaultTokens.push({ - token: ":content-length", - replacement: res.getHeader("content-length") || res.__headers && res.__headers["Content-Length"] || "-" - }); - defaultTokens.push({ - token: /:req\[([^\]]+)]/g, - replacement(_, field) { - return req.headers[field.toLowerCase()]; - } - }); - defaultTokens.push({ - token: /:res\[([^\]]+)]/g, - replacement(_, field) { - return res.getHeader(field.toLowerCase()) || res.__headers && res.__headers[field]; - } - }); - return arrayUniqueTokens(customTokens.concat(defaultTokens)); - } - function format2(str, tokens) { - for (let i = 0; i < tokens.length; i++) { - str = str.replace(tokens[i].token, tokens[i].replacement); - } - return str; - } - function createNoLogCondition(nolog) { - let regexp = null; - if (nolog instanceof RegExp) { - regexp = nolog; - } - if (typeof nolog === "string") { - regexp = new RegExp(nolog); - } - if (Array.isArray(nolog)) { - const regexpsAsStrings = nolog.map((reg) => reg.source ? reg.source : reg); - regexp = new RegExp(regexpsAsStrings.join("|")); - } - return regexp; - } - function matchRules(statusCode, currentLevel, ruleSet) { - let level = currentLevel; - if (ruleSet) { - const matchedRule = ruleSet.find((rule) => { - let ruleMatched = false; - if (rule.from && rule.to) { - ruleMatched = statusCode >= rule.from && statusCode <= rule.to; - } else { - ruleMatched = rule.codes.indexOf(statusCode) !== -1; - } - return ruleMatched; - }); - if (matchedRule) { - level = levels.getLevel(matchedRule.level, level); - } - } - return level; - } - module2.exports = function getLogger(logger4js, options) { - if (typeof options === "string" || typeof options === "function") { - options = { format: options }; - } else { - options = options || {}; - } - const thisLogger = logger4js; - let level = levels.getLevel(options.level, levels.INFO); - const fmt = options.format || DEFAULT_FORMAT; - const nolog = createNoLogCondition(options.nolog); - return (req, res, next) => { - if (req._logging) - return next(); - if (nolog && nolog.test(req.originalUrl)) - return next(); - if (thisLogger.isLevelEnabled(level) || options.level === "auto") { - const start = new Date(); - const { writeHead } = res; - req._logging = true; - res.writeHead = (code, headers) => { - res.writeHead = writeHead; - res.writeHead(code, headers); - res.__statusCode = code; - res.__headers = headers || {}; - }; - res.on("finish", () => { - res.responseTime = new Date() - start; - if (res.statusCode && options.level === "auto") { - level = levels.INFO; - if (res.statusCode >= 300) - level = levels.WARN; - if (res.statusCode >= 400) - level = levels.ERROR; - } - level = matchRules(res.statusCode, level, options.statusRules); - const combinedTokens = assembleTokens(req, res, options.tokens || []); - if (options.context) - thisLogger.addContext("res", res); - if (typeof fmt === "function") { - const line = fmt(req, res, (str) => format2(str, combinedTokens)); - if (line) - thisLogger.log(level, line); - } else { - thisLogger.log(level, format2(fmt, combinedTokens)); - } - if (options.context) - thisLogger.removeContext("res"); - }); - } - return next(); - }; - }; - } -}); - -// node_modules/log4js/lib/log4js.js -var require_log4js = __commonJS({ - "node_modules/log4js/lib/log4js.js"(exports2, module2) { - var debug = require_src()("log4js:main"); - var fs27 = require("fs"); - var deepClone2 = require_rfdc()({ proto: true }); - var configuration = require_configuration(); - var layouts = require_layouts(); - var levels = require_levels(); - var appenders = require_appenders(); - var categories = require_categories(); - var Logger2 = require_logger(); - var clustering = require_clustering(); - var connectLogger = require_connect_logger(); - var enabled = false; - function sendLogEventToAppender(logEvent) { - if (!enabled) - return; - debug("Received log event ", logEvent); - const categoryAppenders = categories.appendersForCategory(logEvent.categoryName); - categoryAppenders.forEach((appender) => { - appender(logEvent); - }); - } - function loadConfigurationFile(filename) { - debug(`Loading configuration from ${filename}`); - try { - return JSON.parse(fs27.readFileSync(filename, "utf8")); - } catch (e) { - throw new Error(`Problem reading config from file "${filename}". Error was ${e.message}`, e); - } - } - function configure(configurationFileOrObject) { - let configObject = configurationFileOrObject; - if (typeof configObject === "string") { - configObject = loadConfigurationFile(configurationFileOrObject); - } - debug(`Configuration is ${configObject}`); - configuration.configure(deepClone2(configObject)); - clustering.onMessage(sendLogEventToAppender); - enabled = true; - return log4js2; - } - function shutdown(cb) { - debug("Shutdown called. Disabling all log writing."); - enabled = false; - const appendersToCheck = Array.from(appenders.values()); - const shutdownFunctions = appendersToCheck.reduceRight((accum, next) => next.shutdown ? accum + 1 : accum, 0); - let completed = 0; - let error; - debug(`Found ${shutdownFunctions} appenders with shutdown functions.`); - function complete(err) { - error = error || err; - completed += 1; - debug(`Appender shutdowns complete: ${completed} / ${shutdownFunctions}`); - if (completed >= shutdownFunctions) { - debug("All shutdown functions completed."); - if (cb) { - cb(error); - } - } - } - if (shutdownFunctions === 0) { - debug("No appenders with shutdown functions found."); - return cb !== void 0 && cb(); - } - appendersToCheck.filter((a) => a.shutdown).forEach((a) => a.shutdown(complete)); - return null; - } - function getLogger(category) { - if (!enabled) { - configure(process.env.LOG4JS_CONFIG || { - appenders: { out: { type: "stdout" } }, - categories: { default: { appenders: ["out"], level: "OFF" } } - }); - } - return new Logger2(category || "default"); - } - var log4js2 = { - getLogger, - configure, - shutdown, - connectLogger, - levels, - addLayout: layouts.addLayout - }; - module2.exports = log4js2; - } -}); - -// node_modules/fs-extra/node_modules/universalify/index.js -var require_universalify2 = __commonJS({ - "node_modules/fs-extra/node_modules/universalify/index.js"(exports2) { - "use strict"; - exports2.fromCallback = function(fn) { - return Object.defineProperty(function(...args) { - if (typeof args[args.length - 1] === "function") - fn.apply(this, args); - else { - return new Promise((resolve3, reject) => { - fn.call(this, ...args, (err, res) => err != null ? reject(err) : resolve3(res)); - }); - } - }, "name", { value: fn.name }); - }; - exports2.fromPromise = function(fn) { - return Object.defineProperty(function(...args) { - const cb = args[args.length - 1]; - if (typeof cb !== "function") - return fn.apply(this, args); - else - fn.apply(this, args.slice(0, -1)).then((r) => cb(null, r), cb); - }, "name", { value: fn.name }); - }; - } -}); - -// node_modules/fs-extra/lib/fs/index.js -var require_fs2 = __commonJS({ - "node_modules/fs-extra/lib/fs/index.js"(exports2) { - "use strict"; - var u = require_universalify2().fromCallback; - var fs27 = require_graceful_fs(); - var api = [ - "access", - "appendFile", - "chmod", - "chown", - "close", - "copyFile", - "fchmod", - "fchown", - "fdatasync", - "fstat", - "fsync", - "ftruncate", - "futimes", - "lchmod", - "lchown", - "link", - "lstat", - "mkdir", - "mkdtemp", - "open", - "opendir", - "readdir", - "readFile", - "readlink", - "realpath", - "rename", - "rm", - "rmdir", - "stat", - "symlink", - "truncate", - "unlink", - "utimes", - "writeFile" - ].filter((key) => { - return typeof fs27[key] === "function"; - }); - Object.keys(fs27).forEach((key) => { - if (key === "promises") { - return; - } - exports2[key] = fs27[key]; - }); - api.forEach((method) => { - exports2[method] = u(fs27[method]); - }); - exports2.exists = function(filename, callback) { - if (typeof callback === "function") { - return fs27.exists(filename, callback); - } - return new Promise((resolve3) => { - return fs27.exists(filename, resolve3); - }); - }; - exports2.read = function(fd, buffer, offset, length, position, callback) { - if (typeof callback === "function") { - return fs27.read(fd, buffer, offset, length, position, callback); - } - return new Promise((resolve3, reject) => { - fs27.read(fd, buffer, offset, length, position, (err, bytesRead, buffer2) => { - if (err) - return reject(err); - resolve3({ bytesRead, buffer: buffer2 }); - }); - }); - }; - exports2.write = function(fd, buffer, ...args) { - if (typeof args[args.length - 1] === "function") { - return fs27.write(fd, buffer, ...args); - } - return new Promise((resolve3, reject) => { - fs27.write(fd, buffer, ...args, (err, bytesWritten, buffer2) => { - if (err) - return reject(err); - resolve3({ bytesWritten, buffer: buffer2 }); - }); - }); - }; - if (typeof fs27.writev === "function") { - exports2.writev = function(fd, buffers, ...args) { - if (typeof args[args.length - 1] === "function") { - return fs27.writev(fd, buffers, ...args); - } - return new Promise((resolve3, reject) => { - fs27.writev(fd, buffers, ...args, (err, bytesWritten, buffers2) => { - if (err) - return reject(err); - resolve3({ bytesWritten, buffers: buffers2 }); - }); - }); - }; - } - if (typeof fs27.realpath.native === "function") { - exports2.realpath.native = u(fs27.realpath.native); - } - } -}); - -// node_modules/at-least-node/index.js -var require_at_least_node = __commonJS({ - "node_modules/at-least-node/index.js"(exports2, module2) { - module2.exports = (r) => { - const n = process.versions.node.split(".").map((x) => parseInt(x, 10)); - r = r.split(".").map((x) => parseInt(x, 10)); - return n[0] > r[0] || n[0] === r[0] && (n[1] > r[1] || n[1] === r[1] && n[2] >= r[2]); - }; - } -}); - -// node_modules/fs-extra/lib/mkdirs/make-dir.js -var require_make_dir = __commonJS({ - "node_modules/fs-extra/lib/mkdirs/make-dir.js"(exports2, module2) { - "use strict"; - var fs27 = require_fs2(); - var path36 = require("path"); - var atLeastNode = require_at_least_node(); - var useNativeRecursiveOption = atLeastNode("10.12.0"); - var checkPath = (pth) => { - if (process.platform === "win32") { - const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path36.parse(pth).root, "")); - if (pathHasInvalidWinCharacters) { - const error = new Error(`Path contains invalid characters: ${pth}`); - error.code = "EINVAL"; - throw error; - } - } - }; - var processOptions = (options) => { - const defaults2 = { mode: 511 }; - if (typeof options === "number") - options = { mode: options }; - return __spreadValues(__spreadValues({}, defaults2), options); - }; - var permissionError = (pth) => { - const error = new Error(`operation not permitted, mkdir '${pth}'`); - error.code = "EPERM"; - error.errno = -4048; - error.path = pth; - error.syscall = "mkdir"; - return error; - }; - module2.exports.makeDir = async (input, options) => { - checkPath(input); - options = processOptions(options); - if (useNativeRecursiveOption) { - const pth = path36.resolve(input); - return fs27.mkdir(pth, { - mode: options.mode, - recursive: true - }); - } - const make = async (pth) => { - try { - await fs27.mkdir(pth, options.mode); - } catch (error) { - if (error.code === "EPERM") { - throw error; - } - if (error.code === "ENOENT") { - if (path36.dirname(pth) === pth) { - throw permissionError(pth); - } - if (error.message.includes("null bytes")) { - throw error; - } - await make(path36.dirname(pth)); - return make(pth); - } - try { - const stats = await fs27.stat(pth); - if (!stats.isDirectory()) { - throw new Error("The path is not a directory"); - } - } catch { - throw error; - } - } - }; - return make(path36.resolve(input)); - }; - module2.exports.makeDirSync = (input, options) => { - checkPath(input); - options = processOptions(options); - if (useNativeRecursiveOption) { - const pth = path36.resolve(input); - return fs27.mkdirSync(pth, { - mode: options.mode, - recursive: true - }); - } - const make = (pth) => { - try { - fs27.mkdirSync(pth, options.mode); - } catch (error) { - if (error.code === "EPERM") { - throw error; - } - if (error.code === "ENOENT") { - if (path36.dirname(pth) === pth) { - throw permissionError(pth); - } - if (error.message.includes("null bytes")) { - throw error; - } - make(path36.dirname(pth)); - return make(pth); - } - try { - if (!fs27.statSync(pth).isDirectory()) { - throw new Error("The path is not a directory"); - } - } catch { - throw error; - } - } - }; - return make(path36.resolve(input)); - }; - } -}); - -// node_modules/fs-extra/lib/mkdirs/index.js -var require_mkdirs3 = __commonJS({ - "node_modules/fs-extra/lib/mkdirs/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromPromise; - var { makeDir: _makeDir, makeDirSync } = require_make_dir(); - var makeDir = u(_makeDir); - module2.exports = { - mkdirs: makeDir, - mkdirsSync: makeDirSync, - mkdirp: makeDir, - mkdirpSync: makeDirSync, - ensureDir: makeDir, - ensureDirSync: makeDirSync - }; - } -}); - -// node_modules/fs-extra/lib/util/utimes.js -var require_utimes2 = __commonJS({ - "node_modules/fs-extra/lib/util/utimes.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - function utimesMillis(path36, atime, mtime, callback) { - fs27.open(path36, "r+", (err, fd) => { - if (err) - return callback(err); - fs27.futimes(fd, atime, mtime, (futimesErr) => { - fs27.close(fd, (closeErr) => { - if (callback) - callback(futimesErr || closeErr); - }); - }); - }); - } - function utimesMillisSync(path36, atime, mtime) { - const fd = fs27.openSync(path36, "r+"); - fs27.futimesSync(fd, atime, mtime); - return fs27.closeSync(fd); - } - module2.exports = { - utimesMillis, - utimesMillisSync - }; - } -}); - -// node_modules/fs-extra/lib/util/stat.js -var require_stat2 = __commonJS({ - "node_modules/fs-extra/lib/util/stat.js"(exports2, module2) { - "use strict"; - var fs27 = require_fs2(); - var path36 = require("path"); - var util4 = require("util"); - var atLeastNode = require_at_least_node(); - var nodeSupportsBigInt = atLeastNode("10.5.0"); - var stat = (file) => nodeSupportsBigInt ? fs27.stat(file, { bigint: true }) : fs27.stat(file); - var statSync = (file) => nodeSupportsBigInt ? fs27.statSync(file, { bigint: true }) : fs27.statSync(file); - function getStats(src, dest) { - return Promise.all([ - stat(src), - stat(dest).catch((err) => { - if (err.code === "ENOENT") - return null; - throw err; - }) - ]).then(([srcStat, destStat]) => ({ srcStat, destStat })); - } - function getStatsSync(src, dest) { - let destStat; - const srcStat = statSync(src); - try { - destStat = statSync(dest); - } catch (err) { - if (err.code === "ENOENT") - return { srcStat, destStat: null }; - throw err; - } - return { srcStat, destStat }; - } - function checkPaths(src, dest, funcName, cb) { - util4.callbackify(getStats)(src, dest, (err, stats) => { - if (err) - return cb(err); - const { srcStat, destStat } = stats; - if (destStat && areIdentical(srcStat, destStat)) { - return cb(new Error("Source and destination must not be the same.")); - } - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - return cb(new Error(errMsg(src, dest, funcName))); - } - return cb(null, { srcStat, destStat }); - }); - } - function checkPathsSync(src, dest, funcName) { - const { srcStat, destStat } = getStatsSync(src, dest); - if (destStat && areIdentical(srcStat, destStat)) { - throw new Error("Source and destination must not be the same."); - } - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new Error(errMsg(src, dest, funcName)); - } - return { srcStat, destStat }; - } - function checkParentPaths(src, srcStat, dest, funcName, cb) { - const srcParent = path36.resolve(path36.dirname(src)); - const destParent = path36.resolve(path36.dirname(dest)); - if (destParent === srcParent || destParent === path36.parse(destParent).root) - return cb(); - const callback = (err, destStat) => { - if (err) { - if (err.code === "ENOENT") - return cb(); - return cb(err); - } - if (areIdentical(srcStat, destStat)) { - return cb(new Error(errMsg(src, dest, funcName))); - } - return checkParentPaths(src, srcStat, destParent, funcName, cb); - }; - if (nodeSupportsBigInt) - fs27.stat(destParent, { bigint: true }, callback); - else - fs27.stat(destParent, callback); - } - function checkParentPathsSync(src, srcStat, dest, funcName) { - const srcParent = path36.resolve(path36.dirname(src)); - const destParent = path36.resolve(path36.dirname(dest)); - if (destParent === srcParent || destParent === path36.parse(destParent).root) - return; - let destStat; - try { - destStat = statSync(destParent); - } catch (err) { - if (err.code === "ENOENT") - return; - throw err; - } - if (areIdentical(srcStat, destStat)) { - throw new Error(errMsg(src, dest, funcName)); - } - return checkParentPathsSync(src, srcStat, destParent, funcName); - } - function areIdentical(srcStat, destStat) { - if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - if (nodeSupportsBigInt || destStat.ino < Number.MAX_SAFE_INTEGER) { - return true; - } - if (destStat.size === srcStat.size && destStat.mode === srcStat.mode && destStat.nlink === srcStat.nlink && destStat.atimeMs === srcStat.atimeMs && destStat.mtimeMs === srcStat.mtimeMs && destStat.ctimeMs === srcStat.ctimeMs && destStat.birthtimeMs === srcStat.birthtimeMs) { - return true; - } - } - return false; - } - function isSrcSubdir(src, dest) { - const srcArr = path36.resolve(src).split(path36.sep).filter((i) => i); - const destArr = path36.resolve(dest).split(path36.sep).filter((i) => i); - return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true); - } - function errMsg(src, dest, funcName) { - return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`; - } - module2.exports = { - checkPaths, - checkPathsSync, - checkParentPaths, - checkParentPathsSync, - isSrcSubdir - }; - } -}); - -// node_modules/fs-extra/lib/copy-sync/copy-sync.js -var require_copy_sync3 = __commonJS({ - "node_modules/fs-extra/lib/copy-sync/copy-sync.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var mkdirsSync = require_mkdirs3().mkdirsSync; - var utimesMillisSync = require_utimes2().utimesMillisSync; - var stat = require_stat2(); - function copySync(src, dest, opts) { - if (typeof opts === "function") { - opts = { filter: opts }; - } - opts = opts || {}; - opts.clobber = "clobber" in opts ? !!opts.clobber : true; - opts.overwrite = "overwrite" in opts ? !!opts.overwrite : opts.clobber; - if (opts.preserveTimestamps && process.arch === "ia32") { - console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended; - - see https://github.com/jprichardson/node-fs-extra/issues/269`); - } - const { srcStat, destStat } = stat.checkPathsSync(src, dest, "copy"); - stat.checkParentPathsSync(src, srcStat, dest, "copy"); - return handleFilterAndCopy(destStat, src, dest, opts); - } - function handleFilterAndCopy(destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) - return; - const destParent = path36.dirname(dest); - if (!fs27.existsSync(destParent)) - mkdirsSync(destParent); - return startCopy(destStat, src, dest, opts); - } - function startCopy(destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) - return; - return getStats(destStat, src, dest, opts); - } - function getStats(destStat, src, dest, opts) { - const statSync = opts.dereference ? fs27.statSync : fs27.lstatSync; - const srcStat = statSync(src); - if (srcStat.isDirectory()) - return onDir(srcStat, destStat, src, dest, opts); - else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) - return onFile(srcStat, destStat, src, dest, opts); - else if (srcStat.isSymbolicLink()) - return onLink(destStat, src, dest, opts); - } - function onFile(srcStat, destStat, src, dest, opts) { - if (!destStat) - return copyFile(srcStat, src, dest, opts); - return mayCopyFile(srcStat, src, dest, opts); - } - function mayCopyFile(srcStat, src, dest, opts) { - if (opts.overwrite) { - fs27.unlinkSync(dest); - return copyFile(srcStat, src, dest, opts); - } else if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`); - } - } - function copyFile(srcStat, src, dest, opts) { - fs27.copyFileSync(src, dest); - if (opts.preserveTimestamps) - handleTimestamps(srcStat.mode, src, dest); - return setDestMode(dest, srcStat.mode); - } - function handleTimestamps(srcMode, src, dest) { - if (fileIsNotWritable(srcMode)) - makeFileWritable(dest, srcMode); - return setDestTimestamps(src, dest); - } - function fileIsNotWritable(srcMode) { - return (srcMode & 128) === 0; - } - function makeFileWritable(dest, srcMode) { - return setDestMode(dest, srcMode | 128); - } - function setDestMode(dest, srcMode) { - return fs27.chmodSync(dest, srcMode); - } - function setDestTimestamps(src, dest) { - const updatedSrcStat = fs27.statSync(src); - return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime); - } - function onDir(srcStat, destStat, src, dest, opts) { - if (!destStat) - return mkDirAndCopy(srcStat.mode, src, dest, opts); - if (destStat && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`); - } - return copyDir(src, dest, opts); - } - function mkDirAndCopy(srcMode, src, dest, opts) { - fs27.mkdirSync(dest); - copyDir(src, dest, opts); - return setDestMode(dest, srcMode); - } - function copyDir(src, dest, opts) { - fs27.readdirSync(src).forEach((item) => copyDirItem(item, src, dest, opts)); - } - function copyDirItem(item, src, dest, opts) { - const srcItem = path36.join(src, item); - const destItem = path36.join(dest, item); - const { destStat } = stat.checkPathsSync(srcItem, destItem, "copy"); - return startCopy(destStat, srcItem, destItem, opts); - } - function onLink(destStat, src, dest, opts) { - let resolvedSrc = fs27.readlinkSync(src); - if (opts.dereference) { - resolvedSrc = path36.resolve(process.cwd(), resolvedSrc); - } - if (!destStat) { - return fs27.symlinkSync(resolvedSrc, dest); - } else { - let resolvedDest; - try { - resolvedDest = fs27.readlinkSync(dest); - } catch (err) { - if (err.code === "EINVAL" || err.code === "UNKNOWN") - return fs27.symlinkSync(resolvedSrc, dest); - throw err; - } - if (opts.dereference) { - resolvedDest = path36.resolve(process.cwd(), resolvedDest); - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`); - } - if (fs27.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`); - } - return copyLink(resolvedSrc, dest); - } - } - function copyLink(resolvedSrc, dest) { - fs27.unlinkSync(dest); - return fs27.symlinkSync(resolvedSrc, dest); - } - module2.exports = copySync; - } -}); - -// node_modules/fs-extra/lib/copy-sync/index.js -var require_copy_sync4 = __commonJS({ - "node_modules/fs-extra/lib/copy-sync/index.js"(exports2, module2) { - "use strict"; - module2.exports = { - copySync: require_copy_sync3() - }; - } -}); - -// node_modules/fs-extra/lib/path-exists/index.js -var require_path_exists2 = __commonJS({ - "node_modules/fs-extra/lib/path-exists/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromPromise; - var fs27 = require_fs2(); - function pathExists(path36) { - return fs27.access(path36).then(() => true).catch(() => false); - } - module2.exports = { - pathExists: u(pathExists), - pathExistsSync: fs27.existsSync - }; - } -}); - -// node_modules/fs-extra/lib/copy/copy.js -var require_copy3 = __commonJS({ - "node_modules/fs-extra/lib/copy/copy.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var mkdirs = require_mkdirs3().mkdirs; - var pathExists = require_path_exists2().pathExists; - var utimesMillis = require_utimes2().utimesMillis; - var stat = require_stat2(); - function copy(src, dest, opts, cb) { - if (typeof opts === "function" && !cb) { - cb = opts; - opts = {}; - } else if (typeof opts === "function") { - opts = { filter: opts }; - } - cb = cb || function() { - }; - opts = opts || {}; - opts.clobber = "clobber" in opts ? !!opts.clobber : true; - opts.overwrite = "overwrite" in opts ? !!opts.overwrite : opts.clobber; - if (opts.preserveTimestamps && process.arch === "ia32") { - console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended; - - see https://github.com/jprichardson/node-fs-extra/issues/269`); - } - stat.checkPaths(src, dest, "copy", (err, stats) => { - if (err) - return cb(err); - const { srcStat, destStat } = stats; - stat.checkParentPaths(src, srcStat, dest, "copy", (err2) => { - if (err2) - return cb(err2); - if (opts.filter) - return handleFilter(checkParentDir, destStat, src, dest, opts, cb); - return checkParentDir(destStat, src, dest, opts, cb); - }); - }); - } - function checkParentDir(destStat, src, dest, opts, cb) { - const destParent = path36.dirname(dest); - pathExists(destParent, (err, dirExists) => { - if (err) - return cb(err); - if (dirExists) - return startCopy(destStat, src, dest, opts, cb); - mkdirs(destParent, (err2) => { - if (err2) - return cb(err2); - return startCopy(destStat, src, dest, opts, cb); - }); - }); - } - function handleFilter(onInclude, destStat, src, dest, opts, cb) { - Promise.resolve(opts.filter(src, dest)).then((include) => { - if (include) - return onInclude(destStat, src, dest, opts, cb); - return cb(); - }, (error) => cb(error)); - } - function startCopy(destStat, src, dest, opts, cb) { - if (opts.filter) - return handleFilter(getStats, destStat, src, dest, opts, cb); - return getStats(destStat, src, dest, opts, cb); - } - function getStats(destStat, src, dest, opts, cb) { - const stat2 = opts.dereference ? fs27.stat : fs27.lstat; - stat2(src, (err, srcStat) => { - if (err) - return cb(err); - if (srcStat.isDirectory()) - return onDir(srcStat, destStat, src, dest, opts, cb); - else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) - return onFile(srcStat, destStat, src, dest, opts, cb); - else if (srcStat.isSymbolicLink()) - return onLink(destStat, src, dest, opts, cb); - }); - } - function onFile(srcStat, destStat, src, dest, opts, cb) { - if (!destStat) - return copyFile(srcStat, src, dest, opts, cb); - return mayCopyFile(srcStat, src, dest, opts, cb); - } - function mayCopyFile(srcStat, src, dest, opts, cb) { - if (opts.overwrite) { - fs27.unlink(dest, (err) => { - if (err) - return cb(err); - return copyFile(srcStat, src, dest, opts, cb); - }); - } else if (opts.errorOnExist) { - return cb(new Error(`'${dest}' already exists`)); - } else - return cb(); - } - function copyFile(srcStat, src, dest, opts, cb) { - fs27.copyFile(src, dest, (err) => { - if (err) - return cb(err); - if (opts.preserveTimestamps) - return handleTimestampsAndMode(srcStat.mode, src, dest, cb); - return setDestMode(dest, srcStat.mode, cb); - }); - } - function handleTimestampsAndMode(srcMode, src, dest, cb) { - if (fileIsNotWritable(srcMode)) { - return makeFileWritable(dest, srcMode, (err) => { - if (err) - return cb(err); - return setDestTimestampsAndMode(srcMode, src, dest, cb); - }); - } - return setDestTimestampsAndMode(srcMode, src, dest, cb); - } - function fileIsNotWritable(srcMode) { - return (srcMode & 128) === 0; - } - function makeFileWritable(dest, srcMode, cb) { - return setDestMode(dest, srcMode | 128, cb); - } - function setDestTimestampsAndMode(srcMode, src, dest, cb) { - setDestTimestamps(src, dest, (err) => { - if (err) - return cb(err); - return setDestMode(dest, srcMode, cb); - }); - } - function setDestMode(dest, srcMode, cb) { - return fs27.chmod(dest, srcMode, cb); - } - function setDestTimestamps(src, dest, cb) { - fs27.stat(src, (err, updatedSrcStat) => { - if (err) - return cb(err); - return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb); - }); - } - function onDir(srcStat, destStat, src, dest, opts, cb) { - if (!destStat) - return mkDirAndCopy(srcStat.mode, src, dest, opts, cb); - if (destStat && !destStat.isDirectory()) { - return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)); - } - return copyDir(src, dest, opts, cb); - } - function mkDirAndCopy(srcMode, src, dest, opts, cb) { - fs27.mkdir(dest, (err) => { - if (err) - return cb(err); - copyDir(src, dest, opts, (err2) => { - if (err2) - return cb(err2); - return setDestMode(dest, srcMode, cb); - }); - }); - } - function copyDir(src, dest, opts, cb) { - fs27.readdir(src, (err, items) => { - if (err) - return cb(err); - return copyDirItems(items, src, dest, opts, cb); - }); - } - function copyDirItems(items, src, dest, opts, cb) { - const item = items.pop(); - if (!item) - return cb(); - return copyDirItem(items, item, src, dest, opts, cb); - } - function copyDirItem(items, item, src, dest, opts, cb) { - const srcItem = path36.join(src, item); - const destItem = path36.join(dest, item); - stat.checkPaths(srcItem, destItem, "copy", (err, stats) => { - if (err) - return cb(err); - const { destStat } = stats; - startCopy(destStat, srcItem, destItem, opts, (err2) => { - if (err2) - return cb(err2); - return copyDirItems(items, src, dest, opts, cb); - }); - }); - } - function onLink(destStat, src, dest, opts, cb) { - fs27.readlink(src, (err, resolvedSrc) => { - if (err) - return cb(err); - if (opts.dereference) { - resolvedSrc = path36.resolve(process.cwd(), resolvedSrc); - } - if (!destStat) { - return fs27.symlink(resolvedSrc, dest, cb); - } else { - fs27.readlink(dest, (err2, resolvedDest) => { - if (err2) { - if (err2.code === "EINVAL" || err2.code === "UNKNOWN") - return fs27.symlink(resolvedSrc, dest, cb); - return cb(err2); - } - if (opts.dereference) { - resolvedDest = path36.resolve(process.cwd(), resolvedDest); - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)); - } - if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)); - } - return copyLink(resolvedSrc, dest, cb); - }); - } - }); - } - function copyLink(resolvedSrc, dest, cb) { - fs27.unlink(dest, (err) => { - if (err) - return cb(err); - return fs27.symlink(resolvedSrc, dest, cb); - }); - } - module2.exports = copy; - } -}); - -// node_modules/fs-extra/lib/copy/index.js -var require_copy4 = __commonJS({ - "node_modules/fs-extra/lib/copy/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromCallback; - module2.exports = { - copy: u(require_copy3()) - }; - } -}); - -// node_modules/fs-extra/lib/remove/rimraf.js -var require_rimraf2 = __commonJS({ - "node_modules/fs-extra/lib/remove/rimraf.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var assert = require("assert"); - var isWindows4 = process.platform === "win32"; - function defaults2(options) { - const methods2 = [ - "unlink", - "chmod", - "stat", - "lstat", - "rmdir", - "readdir" - ]; - methods2.forEach((m) => { - options[m] = options[m] || fs27[m]; - m = m + "Sync"; - options[m] = options[m] || fs27[m]; - }); - options.maxBusyTries = options.maxBusyTries || 3; - } - function rimraf(p, options, cb) { - let busyTries = 0; - if (typeof options === "function") { - cb = options; - options = {}; - } - assert(p, "rimraf: missing path"); - assert.strictEqual(typeof p, "string", "rimraf: path should be a string"); - assert.strictEqual(typeof cb, "function", "rimraf: callback function required"); - assert(options, "rimraf: invalid options argument provided"); - assert.strictEqual(typeof options, "object", "rimraf: options should be object"); - defaults2(options); - rimraf_(p, options, function CB(er) { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { - busyTries++; - const time = busyTries * 100; - return setTimeout(() => rimraf_(p, options, CB), time); - } - if (er.code === "ENOENT") - er = null; - } - cb(er); - }); - } - function rimraf_(p, options, cb) { - assert(p); - assert(options); - assert(typeof cb === "function"); - options.lstat(p, (er, st) => { - if (er && er.code === "ENOENT") { - return cb(null); - } - if (er && er.code === "EPERM" && isWindows4) { - return fixWinEPERM(p, options, er, cb); - } - if (st && st.isDirectory()) { - return rmdir(p, options, er, cb); - } - options.unlink(p, (er2) => { - if (er2) { - if (er2.code === "ENOENT") { - return cb(null); - } - if (er2.code === "EPERM") { - return isWindows4 ? fixWinEPERM(p, options, er2, cb) : rmdir(p, options, er2, cb); - } - if (er2.code === "EISDIR") { - return rmdir(p, options, er2, cb); - } - } - return cb(er2); - }); - }); - } - function fixWinEPERM(p, options, er, cb) { - assert(p); - assert(options); - assert(typeof cb === "function"); - options.chmod(p, 438, (er2) => { - if (er2) { - cb(er2.code === "ENOENT" ? null : er); - } else { - options.stat(p, (er3, stats) => { - if (er3) { - cb(er3.code === "ENOENT" ? null : er); - } else if (stats.isDirectory()) { - rmdir(p, options, er, cb); - } else { - options.unlink(p, cb); - } - }); - } - }); - } - function fixWinEPERMSync(p, options, er) { - let stats; - assert(p); - assert(options); - try { - options.chmodSync(p, 438); - } catch (er2) { - if (er2.code === "ENOENT") { - return; - } else { - throw er; - } - } - try { - stats = options.statSync(p); - } catch (er3) { - if (er3.code === "ENOENT") { - return; - } else { - throw er; - } - } - if (stats.isDirectory()) { - rmdirSync(p, options, er); - } else { - options.unlinkSync(p); - } - } - function rmdir(p, options, originalEr, cb) { - assert(p); - assert(options); - assert(typeof cb === "function"); - options.rmdir(p, (er) => { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) { - rmkids(p, options, cb); - } else if (er && er.code === "ENOTDIR") { - cb(originalEr); - } else { - cb(er); - } - }); - } - function rmkids(p, options, cb) { - assert(p); - assert(options); - assert(typeof cb === "function"); - options.readdir(p, (er, files) => { - if (er) - return cb(er); - let n = files.length; - let errState; - if (n === 0) - return options.rmdir(p, cb); - files.forEach((f) => { - rimraf(path36.join(p, f), options, (er2) => { - if (errState) { - return; - } - if (er2) - return cb(errState = er2); - if (--n === 0) { - options.rmdir(p, cb); - } - }); - }); - }); - } - function rimrafSync(p, options) { - let st; - options = options || {}; - defaults2(options); - assert(p, "rimraf: missing path"); - assert.strictEqual(typeof p, "string", "rimraf: path should be a string"); - assert(options, "rimraf: missing options"); - assert.strictEqual(typeof options, "object", "rimraf: options should be object"); - try { - st = options.lstatSync(p); - } catch (er) { - if (er.code === "ENOENT") { - return; - } - if (er.code === "EPERM" && isWindows4) { - fixWinEPERMSync(p, options, er); - } - } - try { - if (st && st.isDirectory()) { - rmdirSync(p, options, null); - } else { - options.unlinkSync(p); - } - } catch (er) { - if (er.code === "ENOENT") { - return; - } else if (er.code === "EPERM") { - return isWindows4 ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er); - } else if (er.code !== "EISDIR") { - throw er; - } - rmdirSync(p, options, er); - } - } - function rmdirSync(p, options, originalEr) { - assert(p); - assert(options); - try { - options.rmdirSync(p); - } catch (er) { - if (er.code === "ENOTDIR") { - throw originalEr; - } else if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") { - rmkidsSync(p, options); - } else if (er.code !== "ENOENT") { - throw er; - } - } - } - function rmkidsSync(p, options) { - assert(p); - assert(options); - options.readdirSync(p).forEach((f) => rimrafSync(path36.join(p, f), options)); - if (isWindows4) { - const startTime = Date.now(); - do { - try { - const ret = options.rmdirSync(p, options); - return ret; - } catch { - } - } while (Date.now() - startTime < 500); - } else { - const ret = options.rmdirSync(p, options); - return ret; - } - } - module2.exports = rimraf; - rimraf.sync = rimrafSync; - } -}); - -// node_modules/fs-extra/lib/remove/index.js -var require_remove2 = __commonJS({ - "node_modules/fs-extra/lib/remove/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromCallback; - var rimraf = require_rimraf2(); - module2.exports = { - remove: u(rimraf), - removeSync: rimraf.sync - }; - } -}); - -// node_modules/fs-extra/lib/empty/index.js -var require_empty2 = __commonJS({ - "node_modules/fs-extra/lib/empty/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromCallback; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var mkdir = require_mkdirs3(); - var remove = require_remove2(); - var emptyDir = u(function emptyDir2(dir, callback) { - callback = callback || function() { - }; - fs27.readdir(dir, (err, items) => { - if (err) - return mkdir.mkdirs(dir, callback); - items = items.map((item) => path36.join(dir, item)); - deleteItem(); - function deleteItem() { - const item = items.pop(); - if (!item) - return callback(); - remove.remove(item, (err2) => { - if (err2) - return callback(err2); - deleteItem(); - }); - } - }); - }); - function emptyDirSync(dir) { - let items; - try { - items = fs27.readdirSync(dir); - } catch { - return mkdir.mkdirsSync(dir); - } - items.forEach((item) => { - item = path36.join(dir, item); - remove.removeSync(item); - }); - } - module2.exports = { - emptyDirSync, - emptydirSync: emptyDirSync, - emptyDir, - emptydir: emptyDir - }; - } -}); - -// node_modules/fs-extra/lib/ensure/file.js -var require_file3 = __commonJS({ - "node_modules/fs-extra/lib/ensure/file.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromCallback; - var path36 = require("path"); - var fs27 = require_graceful_fs(); - var mkdir = require_mkdirs3(); - function createFile(file, callback) { - function makeFile() { - fs27.writeFile(file, "", (err) => { - if (err) - return callback(err); - callback(); - }); - } - fs27.stat(file, (err, stats) => { - if (!err && stats.isFile()) - return callback(); - const dir = path36.dirname(file); - fs27.stat(dir, (err2, stats2) => { - if (err2) { - if (err2.code === "ENOENT") { - return mkdir.mkdirs(dir, (err3) => { - if (err3) - return callback(err3); - makeFile(); - }); - } - return callback(err2); - } - if (stats2.isDirectory()) - makeFile(); - else { - fs27.readdir(dir, (err3) => { - if (err3) - return callback(err3); - }); - } - }); - }); - } - function createFileSync(file) { - let stats; - try { - stats = fs27.statSync(file); - } catch { - } - if (stats && stats.isFile()) - return; - const dir = path36.dirname(file); - try { - if (!fs27.statSync(dir).isDirectory()) { - fs27.readdirSync(dir); - } - } catch (err) { - if (err && err.code === "ENOENT") - mkdir.mkdirsSync(dir); - else - throw err; - } - fs27.writeFileSync(file, ""); - } - module2.exports = { - createFile: u(createFile), - createFileSync - }; - } -}); - -// node_modules/fs-extra/lib/ensure/link.js -var require_link2 = __commonJS({ - "node_modules/fs-extra/lib/ensure/link.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromCallback; - var path36 = require("path"); - var fs27 = require_graceful_fs(); - var mkdir = require_mkdirs3(); - var pathExists = require_path_exists2().pathExists; - function createLink(srcpath, dstpath, callback) { - function makeLink(srcpath2, dstpath2) { - fs27.link(srcpath2, dstpath2, (err) => { - if (err) - return callback(err); - callback(null); - }); - } - pathExists(dstpath, (err, destinationExists) => { - if (err) - return callback(err); - if (destinationExists) - return callback(null); - fs27.lstat(srcpath, (err2) => { - if (err2) { - err2.message = err2.message.replace("lstat", "ensureLink"); - return callback(err2); - } - const dir = path36.dirname(dstpath); - pathExists(dir, (err3, dirExists) => { - if (err3) - return callback(err3); - if (dirExists) - return makeLink(srcpath, dstpath); - mkdir.mkdirs(dir, (err4) => { - if (err4) - return callback(err4); - makeLink(srcpath, dstpath); - }); - }); - }); - }); - } - function createLinkSync(srcpath, dstpath) { - const destinationExists = fs27.existsSync(dstpath); - if (destinationExists) - return void 0; - try { - fs27.lstatSync(srcpath); - } catch (err) { - err.message = err.message.replace("lstat", "ensureLink"); - throw err; - } - const dir = path36.dirname(dstpath); - const dirExists = fs27.existsSync(dir); - if (dirExists) - return fs27.linkSync(srcpath, dstpath); - mkdir.mkdirsSync(dir); - return fs27.linkSync(srcpath, dstpath); - } - module2.exports = { - createLink: u(createLink), - createLinkSync - }; - } -}); - -// node_modules/fs-extra/lib/ensure/symlink-paths.js -var require_symlink_paths2 = __commonJS({ - "node_modules/fs-extra/lib/ensure/symlink-paths.js"(exports2, module2) { - "use strict"; - var path36 = require("path"); - var fs27 = require_graceful_fs(); - var pathExists = require_path_exists2().pathExists; - function symlinkPaths(srcpath, dstpath, callback) { - if (path36.isAbsolute(srcpath)) { - return fs27.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace("lstat", "ensureSymlink"); - return callback(err); - } - return callback(null, { - toCwd: srcpath, - toDst: srcpath - }); - }); - } else { - const dstdir = path36.dirname(dstpath); - const relativeToDst = path36.join(dstdir, srcpath); - return pathExists(relativeToDst, (err, exists) => { - if (err) - return callback(err); - if (exists) { - return callback(null, { - toCwd: relativeToDst, - toDst: srcpath - }); - } else { - return fs27.lstat(srcpath, (err2) => { - if (err2) { - err2.message = err2.message.replace("lstat", "ensureSymlink"); - return callback(err2); - } - return callback(null, { - toCwd: srcpath, - toDst: path36.relative(dstdir, srcpath) - }); - }); - } - }); - } - } - function symlinkPathsSync(srcpath, dstpath) { - let exists; - if (path36.isAbsolute(srcpath)) { - exists = fs27.existsSync(srcpath); - if (!exists) - throw new Error("absolute srcpath does not exist"); - return { - toCwd: srcpath, - toDst: srcpath - }; - } else { - const dstdir = path36.dirname(dstpath); - const relativeToDst = path36.join(dstdir, srcpath); - exists = fs27.existsSync(relativeToDst); - if (exists) { - return { - toCwd: relativeToDst, - toDst: srcpath - }; - } else { - exists = fs27.existsSync(srcpath); - if (!exists) - throw new Error("relative srcpath does not exist"); - return { - toCwd: srcpath, - toDst: path36.relative(dstdir, srcpath) - }; - } - } - } - module2.exports = { - symlinkPaths, - symlinkPathsSync - }; - } -}); - -// node_modules/fs-extra/lib/ensure/symlink-type.js -var require_symlink_type2 = __commonJS({ - "node_modules/fs-extra/lib/ensure/symlink-type.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - function symlinkType(srcpath, type, callback) { - callback = typeof type === "function" ? type : callback; - type = typeof type === "function" ? false : type; - if (type) - return callback(null, type); - fs27.lstat(srcpath, (err, stats) => { - if (err) - return callback(null, "file"); - type = stats && stats.isDirectory() ? "dir" : "file"; - callback(null, type); - }); - } - function symlinkTypeSync(srcpath, type) { - let stats; - if (type) - return type; - try { - stats = fs27.lstatSync(srcpath); - } catch { - return "file"; - } - return stats && stats.isDirectory() ? "dir" : "file"; - } - module2.exports = { - symlinkType, - symlinkTypeSync - }; - } -}); - -// node_modules/fs-extra/lib/ensure/symlink.js -var require_symlink2 = __commonJS({ - "node_modules/fs-extra/lib/ensure/symlink.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromCallback; - var path36 = require("path"); - var fs27 = require_graceful_fs(); - var _mkdirs = require_mkdirs3(); - var mkdirs = _mkdirs.mkdirs; - var mkdirsSync = _mkdirs.mkdirsSync; - var _symlinkPaths = require_symlink_paths2(); - var symlinkPaths = _symlinkPaths.symlinkPaths; - var symlinkPathsSync = _symlinkPaths.symlinkPathsSync; - var _symlinkType = require_symlink_type2(); - var symlinkType = _symlinkType.symlinkType; - var symlinkTypeSync = _symlinkType.symlinkTypeSync; - var pathExists = require_path_exists2().pathExists; - function createSymlink(srcpath, dstpath, type, callback) { - callback = typeof type === "function" ? type : callback; - type = typeof type === "function" ? false : type; - pathExists(dstpath, (err, destinationExists) => { - if (err) - return callback(err); - if (destinationExists) - return callback(null); - symlinkPaths(srcpath, dstpath, (err2, relative) => { - if (err2) - return callback(err2); - srcpath = relative.toDst; - symlinkType(relative.toCwd, type, (err3, type2) => { - if (err3) - return callback(err3); - const dir = path36.dirname(dstpath); - pathExists(dir, (err4, dirExists) => { - if (err4) - return callback(err4); - if (dirExists) - return fs27.symlink(srcpath, dstpath, type2, callback); - mkdirs(dir, (err5) => { - if (err5) - return callback(err5); - fs27.symlink(srcpath, dstpath, type2, callback); - }); - }); - }); - }); - }); - } - function createSymlinkSync(srcpath, dstpath, type) { - const destinationExists = fs27.existsSync(dstpath); - if (destinationExists) - return void 0; - const relative = symlinkPathsSync(srcpath, dstpath); - srcpath = relative.toDst; - type = symlinkTypeSync(relative.toCwd, type); - const dir = path36.dirname(dstpath); - const exists = fs27.existsSync(dir); - if (exists) - return fs27.symlinkSync(srcpath, dstpath, type); - mkdirsSync(dir); - return fs27.symlinkSync(srcpath, dstpath, type); - } - module2.exports = { - createSymlink: u(createSymlink), - createSymlinkSync - }; - } -}); - -// node_modules/fs-extra/lib/ensure/index.js -var require_ensure2 = __commonJS({ - "node_modules/fs-extra/lib/ensure/index.js"(exports2, module2) { - "use strict"; - var file = require_file3(); - var link = require_link2(); - var symlink = require_symlink2(); - module2.exports = { - createFile: file.createFile, - createFileSync: file.createFileSync, - ensureFile: file.createFile, - ensureFileSync: file.createFileSync, - createLink: link.createLink, - createLinkSync: link.createLinkSync, - ensureLink: link.createLink, - ensureLinkSync: link.createLinkSync, - createSymlink: symlink.createSymlink, - createSymlinkSync: symlink.createSymlinkSync, - ensureSymlink: symlink.createSymlink, - ensureSymlinkSync: symlink.createSymlinkSync - }; - } -}); - -// node_modules/jsonfile/node_modules/universalify/index.js -var require_universalify3 = __commonJS({ - "node_modules/jsonfile/node_modules/universalify/index.js"(exports2) { - "use strict"; - exports2.fromCallback = function(fn) { - return Object.defineProperty(function(...args) { - if (typeof args[args.length - 1] === "function") - fn.apply(this, args); - else { - return new Promise((resolve3, reject) => { - fn.call(this, ...args, (err, res) => err != null ? reject(err) : resolve3(res)); - }); - } - }, "name", { value: fn.name }); - }; - exports2.fromPromise = function(fn) { - return Object.defineProperty(function(...args) { - const cb = args[args.length - 1]; - if (typeof cb !== "function") - return fn.apply(this, args); - else - fn.apply(this, args.slice(0, -1)).then((r) => cb(null, r), cb); - }, "name", { value: fn.name }); - }; - } -}); - -// node_modules/jsonfile/utils.js -var require_utils = __commonJS({ - "node_modules/jsonfile/utils.js"(exports2, module2) { - function stringify3(obj, { EOL: EOL2 = "\n", finalEOL = true, replacer = null, spaces } = {}) { - const EOF = finalEOL ? EOL2 : ""; - const str = JSON.stringify(obj, replacer, spaces); - return str.replace(/\n/g, EOL2) + EOF; - } - function stripBom(content) { - if (Buffer.isBuffer(content)) - content = content.toString("utf8"); - return content.replace(/^\uFEFF/, ""); - } - module2.exports = { stringify: stringify3, stripBom }; - } -}); - -// node_modules/jsonfile/index.js -var require_jsonfile3 = __commonJS({ - "node_modules/jsonfile/index.js"(exports2, module2) { - var _fs; - try { - _fs = require_graceful_fs(); - } catch (_) { - _fs = require("fs"); - } - var universalify = require_universalify3(); - var { stringify: stringify3, stripBom } = require_utils(); - async function _readFile(file, options = {}) { - if (typeof options === "string") { - options = { encoding: options }; - } - const fs27 = options.fs || _fs; - const shouldThrow = "throws" in options ? options.throws : true; - let data = await universalify.fromCallback(fs27.readFile)(file, options); - data = stripBom(data); - let obj; - try { - obj = JSON.parse(data, options ? options.reviver : null); - } catch (err) { - if (shouldThrow) { - err.message = `${file}: ${err.message}`; - throw err; - } else { - return null; - } - } - return obj; - } - var readFile2 = universalify.fromPromise(_readFile); - function readFileSync(file, options = {}) { - if (typeof options === "string") { - options = { encoding: options }; - } - const fs27 = options.fs || _fs; - const shouldThrow = "throws" in options ? options.throws : true; - try { - let content = fs27.readFileSync(file, options); - content = stripBom(content); - return JSON.parse(content, options.reviver); - } catch (err) { - if (shouldThrow) { - err.message = `${file}: ${err.message}`; - throw err; - } else { - return null; - } - } - } - async function _writeFile(file, obj, options = {}) { - const fs27 = options.fs || _fs; - const str = stringify3(obj, options); - await universalify.fromCallback(fs27.writeFile)(file, str, options); - } - var writeFile2 = universalify.fromPromise(_writeFile); - function writeFileSync(file, obj, options = {}) { - const fs27 = options.fs || _fs; - const str = stringify3(obj, options); - return fs27.writeFileSync(file, str, options); - } - var jsonfile = { - readFile: readFile2, - readFileSync, - writeFile: writeFile2, - writeFileSync - }; - module2.exports = jsonfile; - } -}); - -// node_modules/fs-extra/lib/json/jsonfile.js -var require_jsonfile4 = __commonJS({ - "node_modules/fs-extra/lib/json/jsonfile.js"(exports2, module2) { - "use strict"; - var jsonFile = require_jsonfile3(); - module2.exports = { - readJson: jsonFile.readFile, - readJsonSync: jsonFile.readFileSync, - writeJson: jsonFile.writeFile, - writeJsonSync: jsonFile.writeFileSync - }; - } -}); - -// node_modules/fs-extra/lib/output/index.js -var require_output2 = __commonJS({ - "node_modules/fs-extra/lib/output/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromCallback; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var mkdir = require_mkdirs3(); - var pathExists = require_path_exists2().pathExists; - function outputFile(file, data, encoding, callback) { - if (typeof encoding === "function") { - callback = encoding; - encoding = "utf8"; - } - const dir = path36.dirname(file); - pathExists(dir, (err, itDoes) => { - if (err) - return callback(err); - if (itDoes) - return fs27.writeFile(file, data, encoding, callback); - mkdir.mkdirs(dir, (err2) => { - if (err2) - return callback(err2); - fs27.writeFile(file, data, encoding, callback); - }); - }); - } - function outputFileSync(file, ...args) { - const dir = path36.dirname(file); - if (fs27.existsSync(dir)) { - return fs27.writeFileSync(file, ...args); - } - mkdir.mkdirsSync(dir); - fs27.writeFileSync(file, ...args); - } - module2.exports = { - outputFile: u(outputFile), - outputFileSync - }; - } -}); - -// node_modules/fs-extra/lib/json/output-json.js -var require_output_json2 = __commonJS({ - "node_modules/fs-extra/lib/json/output-json.js"(exports2, module2) { - "use strict"; - var { stringify: stringify3 } = require_utils(); - var { outputFile } = require_output2(); - async function outputJson(file, data, options = {}) { - const str = stringify3(data, options); - await outputFile(file, str, options); - } - module2.exports = outputJson; - } -}); - -// node_modules/fs-extra/lib/json/output-json-sync.js -var require_output_json_sync2 = __commonJS({ - "node_modules/fs-extra/lib/json/output-json-sync.js"(exports2, module2) { - "use strict"; - var { stringify: stringify3 } = require_utils(); - var { outputFileSync } = require_output2(); - function outputJsonSync(file, data, options) { - const str = stringify3(data, options); - outputFileSync(file, str, options); - } - module2.exports = outputJsonSync; - } -}); - -// node_modules/fs-extra/lib/json/index.js -var require_json2 = __commonJS({ - "node_modules/fs-extra/lib/json/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromPromise; - var jsonFile = require_jsonfile4(); - jsonFile.outputJson = u(require_output_json2()); - jsonFile.outputJsonSync = require_output_json_sync2(); - jsonFile.outputJSON = jsonFile.outputJson; - jsonFile.outputJSONSync = jsonFile.outputJsonSync; - jsonFile.writeJSON = jsonFile.writeJson; - jsonFile.writeJSONSync = jsonFile.writeJsonSync; - jsonFile.readJSON = jsonFile.readJson; - jsonFile.readJSONSync = jsonFile.readJsonSync; - module2.exports = jsonFile; - } -}); - -// node_modules/fs-extra/lib/move-sync/move-sync.js -var require_move_sync3 = __commonJS({ - "node_modules/fs-extra/lib/move-sync/move-sync.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var copySync = require_copy_sync4().copySync; - var removeSync = require_remove2().removeSync; - var mkdirpSync = require_mkdirs3().mkdirpSync; - var stat = require_stat2(); - function moveSync(src, dest, opts) { - opts = opts || {}; - const overwrite = opts.overwrite || opts.clobber || false; - const { srcStat } = stat.checkPathsSync(src, dest, "move"); - stat.checkParentPathsSync(src, srcStat, dest, "move"); - mkdirpSync(path36.dirname(dest)); - return doRename(src, dest, overwrite); - } - function doRename(src, dest, overwrite) { - if (overwrite) { - removeSync(dest); - return rename(src, dest, overwrite); - } - if (fs27.existsSync(dest)) - throw new Error("dest already exists."); - return rename(src, dest, overwrite); - } - function rename(src, dest, overwrite) { - try { - fs27.renameSync(src, dest); - } catch (err) { - if (err.code !== "EXDEV") - throw err; - return moveAcrossDevice(src, dest, overwrite); - } - } - function moveAcrossDevice(src, dest, overwrite) { - const opts = { - overwrite, - errorOnExist: true - }; - copySync(src, dest, opts); - return removeSync(src); - } - module2.exports = moveSync; - } -}); - -// node_modules/fs-extra/lib/move-sync/index.js -var require_move_sync4 = __commonJS({ - "node_modules/fs-extra/lib/move-sync/index.js"(exports2, module2) { - "use strict"; - module2.exports = { - moveSync: require_move_sync3() - }; - } -}); - -// node_modules/fs-extra/lib/move/move.js -var require_move3 = __commonJS({ - "node_modules/fs-extra/lib/move/move.js"(exports2, module2) { - "use strict"; - var fs27 = require_graceful_fs(); - var path36 = require("path"); - var copy = require_copy4().copy; - var remove = require_remove2().remove; - var mkdirp = require_mkdirs3().mkdirp; - var pathExists = require_path_exists2().pathExists; - var stat = require_stat2(); - function move(src, dest, opts, cb) { - if (typeof opts === "function") { - cb = opts; - opts = {}; - } - const overwrite = opts.overwrite || opts.clobber || false; - stat.checkPaths(src, dest, "move", (err, stats) => { - if (err) - return cb(err); - const { srcStat } = stats; - stat.checkParentPaths(src, srcStat, dest, "move", (err2) => { - if (err2) - return cb(err2); - mkdirp(path36.dirname(dest), (err3) => { - if (err3) - return cb(err3); - return doRename(src, dest, overwrite, cb); - }); - }); - }); - } - function doRename(src, dest, overwrite, cb) { - if (overwrite) { - return remove(dest, (err) => { - if (err) - return cb(err); - return rename(src, dest, overwrite, cb); - }); - } - pathExists(dest, (err, destExists) => { - if (err) - return cb(err); - if (destExists) - return cb(new Error("dest already exists.")); - return rename(src, dest, overwrite, cb); - }); - } - function rename(src, dest, overwrite, cb) { - fs27.rename(src, dest, (err) => { - if (!err) - return cb(); - if (err.code !== "EXDEV") - return cb(err); - return moveAcrossDevice(src, dest, overwrite, cb); - }); - } - function moveAcrossDevice(src, dest, overwrite, cb) { - const opts = { - overwrite, - errorOnExist: true - }; - copy(src, dest, opts, (err) => { - if (err) - return cb(err); - return remove(src, cb); - }); - } - module2.exports = move; - } -}); - -// node_modules/fs-extra/lib/move/index.js -var require_move4 = __commonJS({ - "node_modules/fs-extra/lib/move/index.js"(exports2, module2) { - "use strict"; - var u = require_universalify2().fromCallback; - module2.exports = { - move: u(require_move3()) - }; - } -}); - -// node_modules/fs-extra/lib/index.js -var require_lib5 = __commonJS({ - "node_modules/fs-extra/lib/index.js"(exports2, module2) { - "use strict"; - module2.exports = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({}, require_fs2()), require_copy_sync4()), require_copy4()), require_empty2()), require_ensure2()), require_json2()), require_mkdirs3()), require_move_sync4()), require_move4()), require_output2()), require_path_exists2()), require_remove2()); - var fs27 = require("fs"); - if (Object.getOwnPropertyDescriptor(fs27, "promises")) { - Object.defineProperty(module2.exports, "promises", { - get() { - return fs27.promises; - } - }); - } - } -}); - -// src/util/logger.ts -var require_logger2 = __commonJS({ - "src/util/logger.ts"(exports2, module2) { - var import_fs38 = __toModule(require("fs")); - var import_log4js2 = __toModule(require_log4js()); - var import_path38 = __toModule(require("path")); - var import_os10 = __toModule(require("os")); - var import_fs_extra10 = __toModule(require_lib5()); - function getLogFile() { - let file = process.env.NVIM_COC_LOG_FILE; - if (file) - return file; - let dir = process.env.XDG_RUNTIME_DIR; - if (dir) { - try { - import_fs38.default.accessSync(dir, import_fs38.default.constants.R_OK | import_fs38.default.constants.W_OK); - return import_path38.default.join(dir, `coc-nvim-${process.pid}.log`); - } catch (err) { - } - } - let tmpdir = import_os10.default.tmpdir(); - dir = import_path38.default.join(tmpdir, `coc.nvim-${process.pid}`); - if (!import_fs38.default.existsSync(dir)) - (0, import_fs_extra10.mkdirpSync)(dir); - return import_path38.default.join(dir, `coc-nvim.log`); - } - var MAX_LOG_SIZE = 1024 * 1024; - var MAX_LOG_BACKUPS = 10; - var logfile = getLogFile(); - var level = process.env.NVIM_COC_LOG_LEVEL || "info"; - if (import_fs38.default.existsSync(logfile)) { - try { - import_fs38.default.writeFileSync(logfile, "", { encoding: "utf8", mode: 438 }); - } catch (e) { - } - } - import_log4js2.default.configure({ - disableClustering: true, - appenders: { - out: { - type: "file", - mode: 438, - filename: logfile, - maxLogSize: MAX_LOG_SIZE, - backups: MAX_LOG_BACKUPS, - layout: { - type: "pattern", - pattern: `%d{ISO8601} %p (pid:${process.pid}) [%c] - %m` - } - } - }, - categories: { - default: { appenders: ["out"], level } - } - }); - module2.exports = (name2 = "coc-nvim") => { - let logger113 = import_log4js2.default.getLogger(name2); - logger113.getLogFile = () => logfile; - return logger113; - }; - } -}); - -// src/util/extensions.ts -var require_extensions = __commonJS({ - "src/util/extensions.ts"() { - Promise.prototype.logError = function() { - this.catch((e) => { - require_logger2()("extensions").error(e); - }); - }; - } -}); - -// node_modules/msgpack-lite/lib/buffer-global.js -var require_buffer_global = __commonJS({ - "node_modules/msgpack-lite/lib/buffer-global.js"(exports2, module2) { - module2.exports = c(typeof Buffer !== "undefined" && Buffer) || c(exports2.Buffer) || c(typeof window !== "undefined" && window.Buffer) || exports2.Buffer; - function c(B) { - return B && B.isBuffer && B; - } - } -}); - -// node_modules/isarray/index.js -var require_isarray = __commonJS({ - "node_modules/isarray/index.js"(exports2, module2) { - var toString = {}.toString; - module2.exports = Array.isArray || function(arr) { - return toString.call(arr) == "[object Array]"; - }; - } -}); - -// node_modules/msgpack-lite/lib/bufferish-array.js -var require_bufferish_array = __commonJS({ - "node_modules/msgpack-lite/lib/bufferish-array.js"(exports2, module2) { - var Bufferish = require_bufferish(); - var exports2 = module2.exports = alloc(0); - exports2.alloc = alloc; - exports2.concat = Bufferish.concat; - exports2.from = from; - function alloc(size) { - return new Array(size); - } - function from(value) { - if (!Bufferish.isBuffer(value) && Bufferish.isView(value)) { - value = Bufferish.Uint8Array.from(value); - } else if (Bufferish.isArrayBuffer(value)) { - value = new Uint8Array(value); - } else if (typeof value === "string") { - return Bufferish.from.call(exports2, value); - } else if (typeof value === "number") { - throw new TypeError('"value" argument must not be a number'); - } - return Array.prototype.slice.call(value); - } - } -}); - -// node_modules/msgpack-lite/lib/bufferish-buffer.js -var require_bufferish_buffer = __commonJS({ - "node_modules/msgpack-lite/lib/bufferish-buffer.js"(exports2, module2) { - var Bufferish = require_bufferish(); - var Buffer4 = Bufferish.global; - var exports2 = module2.exports = Bufferish.hasBuffer ? alloc(0) : []; - exports2.alloc = Bufferish.hasBuffer && Buffer4.alloc || alloc; - exports2.concat = Bufferish.concat; - exports2.from = from; - function alloc(size) { - return new Buffer4(size); - } - function from(value) { - if (!Bufferish.isBuffer(value) && Bufferish.isView(value)) { - value = Bufferish.Uint8Array.from(value); - } else if (Bufferish.isArrayBuffer(value)) { - value = new Uint8Array(value); - } else if (typeof value === "string") { - return Bufferish.from.call(exports2, value); - } else if (typeof value === "number") { - throw new TypeError('"value" argument must not be a number'); - } - if (Buffer4.from && Buffer4.from.length !== 1) { - return Buffer4.from(value); - } else { - return new Buffer4(value); - } - } - } -}); - -// node_modules/msgpack-lite/lib/bufferish-uint8array.js -var require_bufferish_uint8array = __commonJS({ - "node_modules/msgpack-lite/lib/bufferish-uint8array.js"(exports2, module2) { - var Bufferish = require_bufferish(); - var exports2 = module2.exports = Bufferish.hasArrayBuffer ? alloc(0) : []; - exports2.alloc = alloc; - exports2.concat = Bufferish.concat; - exports2.from = from; - function alloc(size) { - return new Uint8Array(size); - } - function from(value) { - if (Bufferish.isView(value)) { - var byteOffset = value.byteOffset; - var byteLength2 = value.byteLength; - value = value.buffer; - if (value.byteLength !== byteLength2) { - if (value.slice) { - value = value.slice(byteOffset, byteOffset + byteLength2); - } else { - value = new Uint8Array(value); - if (value.byteLength !== byteLength2) { - value = Array.prototype.slice.call(value, byteOffset, byteOffset + byteLength2); - } - } - } - } else if (typeof value === "string") { - return Bufferish.from.call(exports2, value); - } else if (typeof value === "number") { - throw new TypeError('"value" argument must not be a number'); - } - return new Uint8Array(value); - } - } -}); - -// node_modules/msgpack-lite/lib/buffer-lite.js -var require_buffer_lite = __commonJS({ - "node_modules/msgpack-lite/lib/buffer-lite.js"(exports2) { - exports2.copy = copy; - exports2.toString = toString; - exports2.write = write; - function write(string2, offset) { - var buffer = this; - var index = offset || (offset |= 0); - var length = string2.length; - var chr = 0; - var i = 0; - while (i < length) { - chr = string2.charCodeAt(i++); - if (chr < 128) { - buffer[index++] = chr; - } else if (chr < 2048) { - buffer[index++] = 192 | chr >>> 6; - buffer[index++] = 128 | chr & 63; - } else if (chr < 55296 || chr > 57343) { - buffer[index++] = 224 | chr >>> 12; - buffer[index++] = 128 | chr >>> 6 & 63; - buffer[index++] = 128 | chr & 63; - } else { - chr = (chr - 55296 << 10 | string2.charCodeAt(i++) - 56320) + 65536; - buffer[index++] = 240 | chr >>> 18; - buffer[index++] = 128 | chr >>> 12 & 63; - buffer[index++] = 128 | chr >>> 6 & 63; - buffer[index++] = 128 | chr & 63; - } - } - return index - offset; - } - function toString(encoding, start, end) { - var buffer = this; - var index = start | 0; - if (!end) - end = buffer.length; - var string2 = ""; - var chr = 0; - while (index < end) { - chr = buffer[index++]; - if (chr < 128) { - string2 += String.fromCharCode(chr); - continue; - } - if ((chr & 224) === 192) { - chr = (chr & 31) << 6 | buffer[index++] & 63; - } else if ((chr & 240) === 224) { - chr = (chr & 15) << 12 | (buffer[index++] & 63) << 6 | buffer[index++] & 63; - } else if ((chr & 248) === 240) { - chr = (chr & 7) << 18 | (buffer[index++] & 63) << 12 | (buffer[index++] & 63) << 6 | buffer[index++] & 63; - } - if (chr >= 65536) { - chr -= 65536; - string2 += String.fromCharCode((chr >>> 10) + 55296, (chr & 1023) + 56320); - } else { - string2 += String.fromCharCode(chr); - } - } - return string2; - } - function copy(target, targetStart, start, end) { - var i; - if (!start) - start = 0; - if (!end && end !== 0) - end = this.length; - if (!targetStart) - targetStart = 0; - var len = end - start; - if (target === this && start < targetStart && targetStart < end) { - for (i = len - 1; i >= 0; i--) { - target[i + targetStart] = this[i + start]; - } - } else { - for (i = 0; i < len; i++) { - target[i + targetStart] = this[i + start]; - } - } - return len; - } - } -}); - -// node_modules/msgpack-lite/lib/bufferish-proto.js -var require_bufferish_proto = __commonJS({ - "node_modules/msgpack-lite/lib/bufferish-proto.js"(exports2) { - var BufferLite = require_buffer_lite(); - exports2.copy = copy; - exports2.slice = slice; - exports2.toString = toString; - exports2.write = gen("write"); - var Bufferish = require_bufferish(); - var Buffer4 = Bufferish.global; - var isBufferShim = Bufferish.hasBuffer && "TYPED_ARRAY_SUPPORT" in Buffer4; - var brokenTypedArray = isBufferShim && !Buffer4.TYPED_ARRAY_SUPPORT; - function copy(target, targetStart, start, end) { - var thisIsBuffer = Bufferish.isBuffer(this); - var targetIsBuffer = Bufferish.isBuffer(target); - if (thisIsBuffer && targetIsBuffer) { - return this.copy(target, targetStart, start, end); - } else if (!brokenTypedArray && !thisIsBuffer && !targetIsBuffer && Bufferish.isView(this) && Bufferish.isView(target)) { - var buffer = start || end != null ? slice.call(this, start, end) : this; - target.set(buffer, targetStart); - return buffer.length; - } else { - return BufferLite.copy.call(this, target, targetStart, start, end); - } - } - function slice(start, end) { - var f = this.slice || !brokenTypedArray && this.subarray; - if (f) - return f.call(this, start, end); - var target = Bufferish.alloc.call(this, end - start); - copy.call(this, target, 0, start, end); - return target; - } - function toString(encoding, start, end) { - var f = !isBufferShim && Bufferish.isBuffer(this) ? this.toString : BufferLite.toString; - return f.apply(this, arguments); - } - function gen(method) { - return wrap; - function wrap() { - var f = this[method] || BufferLite[method]; - return f.apply(this, arguments); - } - } - } -}); - -// node_modules/msgpack-lite/lib/bufferish.js -var require_bufferish = __commonJS({ - "node_modules/msgpack-lite/lib/bufferish.js"(exports2) { - var Buffer4 = exports2.global = require_buffer_global(); - var hasBuffer = exports2.hasBuffer = Buffer4 && !!Buffer4.isBuffer; - var hasArrayBuffer = exports2.hasArrayBuffer = typeof ArrayBuffer !== "undefined"; - var isArray = exports2.isArray = require_isarray(); - exports2.isArrayBuffer = hasArrayBuffer ? isArrayBuffer : _false; - var isBuffer = exports2.isBuffer = hasBuffer ? Buffer4.isBuffer : _false; - var isView = exports2.isView = hasArrayBuffer ? ArrayBuffer.isView || _is("ArrayBuffer", "buffer") : _false; - exports2.alloc = alloc; - exports2.concat = concat; - exports2.from = from; - var BufferArray = exports2.Array = require_bufferish_array(); - var BufferBuffer = exports2.Buffer = require_bufferish_buffer(); - var BufferUint8Array = exports2.Uint8Array = require_bufferish_uint8array(); - var BufferProto = exports2.prototype = require_bufferish_proto(); - function from(value) { - if (typeof value === "string") { - return fromString.call(this, value); - } else { - return auto(this).from(value); - } - } - function alloc(size) { - return auto(this).alloc(size); - } - function concat(list2, length) { - if (!length) { - length = 0; - Array.prototype.forEach.call(list2, dryrun); - } - var ref = this !== exports2 && this || list2[0]; - var result = alloc.call(ref, length); - var offset = 0; - Array.prototype.forEach.call(list2, append); - return result; - function dryrun(buffer) { - length += buffer.length; - } - function append(buffer) { - offset += BufferProto.copy.call(buffer, result, offset); - } - } - var _isArrayBuffer = _is("ArrayBuffer"); - function isArrayBuffer(value) { - return value instanceof ArrayBuffer || _isArrayBuffer(value); - } - function fromString(value) { - var expected = value.length * 3; - var that = alloc.call(this, expected); - var actual = BufferProto.write.call(that, value); - if (expected !== actual) { - that = BufferProto.slice.call(that, 0, actual); - } - return that; - } - function auto(that) { - return isBuffer(that) ? BufferBuffer : isView(that) ? BufferUint8Array : isArray(that) ? BufferArray : hasBuffer ? BufferBuffer : hasArrayBuffer ? BufferUint8Array : BufferArray; - } - function _false() { - return false; - } - function _is(name2, key) { - name2 = "[object " + name2 + "]"; - return function(value) { - return value != null && {}.toString.call(key ? value[key] : value) === name2; - }; - } - } -}); - -// node_modules/msgpack-lite/lib/ext-buffer.js -var require_ext_buffer = __commonJS({ - "node_modules/msgpack-lite/lib/ext-buffer.js"(exports2) { - exports2.ExtBuffer = ExtBuffer; - var Bufferish = require_bufferish(); - function ExtBuffer(buffer, type) { - if (!(this instanceof ExtBuffer)) - return new ExtBuffer(buffer, type); - this.buffer = Bufferish.from(buffer); - this.type = type; - } - } -}); - -// node_modules/msgpack-lite/lib/ext-packer.js -var require_ext_packer = __commonJS({ - "node_modules/msgpack-lite/lib/ext-packer.js"(exports2) { - exports2.setExtPackers = setExtPackers; - var Bufferish = require_bufferish(); - var Buffer4 = Bufferish.global; - var packTypedArray = Bufferish.Uint8Array.from; - var _encode; - var ERROR_COLUMNS = { name: 1, message: 1, stack: 1, columnNumber: 1, fileName: 1, lineNumber: 1 }; - function setExtPackers(codec) { - codec.addExtPacker(14, Error, [packError, encode]); - codec.addExtPacker(1, EvalError, [packError, encode]); - codec.addExtPacker(2, RangeError, [packError, encode]); - codec.addExtPacker(3, ReferenceError, [packError, encode]); - codec.addExtPacker(4, SyntaxError, [packError, encode]); - codec.addExtPacker(5, TypeError, [packError, encode]); - codec.addExtPacker(6, URIError, [packError, encode]); - codec.addExtPacker(10, RegExp, [packRegExp, encode]); - codec.addExtPacker(11, Boolean, [packValueOf, encode]); - codec.addExtPacker(12, String, [packValueOf, encode]); - codec.addExtPacker(13, Date, [Number, encode]); - codec.addExtPacker(15, Number, [packValueOf, encode]); - if (typeof Uint8Array !== "undefined") { - codec.addExtPacker(17, Int8Array, packTypedArray); - codec.addExtPacker(18, Uint8Array, packTypedArray); - codec.addExtPacker(19, Int16Array, packTypedArray); - codec.addExtPacker(20, Uint16Array, packTypedArray); - codec.addExtPacker(21, Int32Array, packTypedArray); - codec.addExtPacker(22, Uint32Array, packTypedArray); - codec.addExtPacker(23, Float32Array, packTypedArray); - if (typeof Float64Array !== "undefined") { - codec.addExtPacker(24, Float64Array, packTypedArray); - } - if (typeof Uint8ClampedArray !== "undefined") { - codec.addExtPacker(25, Uint8ClampedArray, packTypedArray); - } - codec.addExtPacker(26, ArrayBuffer, packTypedArray); - codec.addExtPacker(29, DataView, packTypedArray); - } - if (Bufferish.hasBuffer) { - codec.addExtPacker(27, Buffer4, Bufferish.from); - } - } - function encode(input) { - if (!_encode) - _encode = require_encode().encode; - return _encode(input); - } - function packValueOf(value) { - return value.valueOf(); - } - function packRegExp(value) { - value = RegExp.prototype.toString.call(value).split("/"); - value.shift(); - var out = [value.pop()]; - out.unshift(value.join("/")); - return out; - } - function packError(value) { - var out = {}; - for (var key in ERROR_COLUMNS) { - out[key] = value[key]; - } - return out; - } - } -}); - -// node_modules/int64-buffer/int64-buffer.js -var require_int64_buffer = __commonJS({ - "node_modules/int64-buffer/int64-buffer.js"(exports2) { - var Uint64BE; - var Int64BE; - var Uint64LE; - var Int64LE; - !function(exports3) { - var UNDEFINED = "undefined"; - var BUFFER = UNDEFINED !== typeof Buffer && Buffer; - var UINT8ARRAY = UNDEFINED !== typeof Uint8Array && Uint8Array; - var ARRAYBUFFER = UNDEFINED !== typeof ArrayBuffer && ArrayBuffer; - var ZERO = [0, 0, 0, 0, 0, 0, 0, 0]; - var isArray = Array.isArray || _isArray; - var BIT32 = 4294967296; - var BIT24 = 16777216; - var storage; - Uint64BE = factory("Uint64BE", true, true); - Int64BE = factory("Int64BE", true, false); - Uint64LE = factory("Uint64LE", false, true); - Int64LE = factory("Int64LE", false, false); - function factory(name2, bigendian, unsigned) { - var posH = bigendian ? 0 : 4; - var posL = bigendian ? 4 : 0; - var pos0 = bigendian ? 0 : 3; - var pos1 = bigendian ? 1 : 2; - var pos2 = bigendian ? 2 : 1; - var pos3 = bigendian ? 3 : 0; - var fromPositive = bigendian ? fromPositiveBE : fromPositiveLE; - var fromNegative = bigendian ? fromNegativeBE : fromNegativeLE; - var proto = Int64.prototype; - var isName = "is" + name2; - var _isInt64 = "_" + isName; - proto.buffer = void 0; - proto.offset = 0; - proto[_isInt64] = true; - proto.toNumber = toNumber; - proto.toString = toString; - proto.toJSON = toNumber; - proto.toArray = toArray; - if (BUFFER) - proto.toBuffer = toBuffer; - if (UINT8ARRAY) - proto.toArrayBuffer = toArrayBuffer; - Int64[isName] = isInt64; - exports3[name2] = Int64; - return Int64; - function Int64(buffer, offset, value, raddix) { - if (!(this instanceof Int64)) - return new Int64(buffer, offset, value, raddix); - return init(this, buffer, offset, value, raddix); - } - function isInt64(b) { - return !!(b && b[_isInt64]); - } - function init(that, buffer, offset, value, raddix) { - if (UINT8ARRAY && ARRAYBUFFER) { - if (buffer instanceof ARRAYBUFFER) - buffer = new UINT8ARRAY(buffer); - if (value instanceof ARRAYBUFFER) - value = new UINT8ARRAY(value); - } - if (!buffer && !offset && !value && !storage) { - that.buffer = newArray(ZERO, 0); - return; - } - if (!isValidBuffer(buffer, offset)) { - var _storage = storage || Array; - raddix = offset; - value = buffer; - offset = 0; - buffer = new _storage(8); - } - that.buffer = buffer; - that.offset = offset |= 0; - if (UNDEFINED === typeof value) - return; - if (typeof value === "string") { - fromString(buffer, offset, value, raddix || 10); - } else if (isValidBuffer(value, raddix)) { - fromArray(buffer, offset, value, raddix); - } else if (typeof raddix === "number") { - writeInt32(buffer, offset + posH, value); - writeInt32(buffer, offset + posL, raddix); - } else if (value > 0) { - fromPositive(buffer, offset, value); - } else if (value < 0) { - fromNegative(buffer, offset, value); - } else { - fromArray(buffer, offset, ZERO, 0); - } - } - function fromString(buffer, offset, str, raddix) { - var pos = 0; - var len = str.length; - var high = 0; - var low = 0; - if (str[0] === "-") - pos++; - var sign = pos; - while (pos < len) { - var chr = parseInt(str[pos++], raddix); - if (!(chr >= 0)) - break; - low = low * raddix + chr; - high = high * raddix + Math.floor(low / BIT32); - low %= BIT32; - } - if (sign) { - high = ~high; - if (low) { - low = BIT32 - low; - } else { - high++; - } - } - writeInt32(buffer, offset + posH, high); - writeInt32(buffer, offset + posL, low); - } - function toNumber() { - var buffer = this.buffer; - var offset = this.offset; - var high = readInt32(buffer, offset + posH); - var low = readInt32(buffer, offset + posL); - if (!unsigned) - high |= 0; - return high ? high * BIT32 + low : low; - } - function toString(radix) { - var buffer = this.buffer; - var offset = this.offset; - var high = readInt32(buffer, offset + posH); - var low = readInt32(buffer, offset + posL); - var str = ""; - var sign = !unsigned && high & 2147483648; - if (sign) { - high = ~high; - low = BIT32 - low; - } - radix = radix || 10; - while (1) { - var mod = high % radix * BIT32 + low; - high = Math.floor(high / radix); - low = Math.floor(mod / radix); - str = (mod % radix).toString(radix) + str; - if (!high && !low) - break; - } - if (sign) { - str = "-" + str; - } - return str; - } - function writeInt32(buffer, offset, value) { - buffer[offset + pos3] = value & 255; - value = value >> 8; - buffer[offset + pos2] = value & 255; - value = value >> 8; - buffer[offset + pos1] = value & 255; - value = value >> 8; - buffer[offset + pos0] = value & 255; - } - function readInt32(buffer, offset) { - return buffer[offset + pos0] * BIT24 + (buffer[offset + pos1] << 16) + (buffer[offset + pos2] << 8) + buffer[offset + pos3]; - } - } - function toArray(raw) { - var buffer = this.buffer; - var offset = this.offset; - storage = null; - if (raw !== false && offset === 0 && buffer.length === 8 && isArray(buffer)) - return buffer; - return newArray(buffer, offset); - } - function toBuffer(raw) { - var buffer = this.buffer; - var offset = this.offset; - storage = BUFFER; - if (raw !== false && offset === 0 && buffer.length === 8 && Buffer.isBuffer(buffer)) - return buffer; - var dest = new BUFFER(8); - fromArray(dest, 0, buffer, offset); - return dest; - } - function toArrayBuffer(raw) { - var buffer = this.buffer; - var offset = this.offset; - var arrbuf = buffer.buffer; - storage = UINT8ARRAY; - if (raw !== false && offset === 0 && arrbuf instanceof ARRAYBUFFER && arrbuf.byteLength === 8) - return arrbuf; - var dest = new UINT8ARRAY(8); - fromArray(dest, 0, buffer, offset); - return dest.buffer; - } - function isValidBuffer(buffer, offset) { - var len = buffer && buffer.length; - offset |= 0; - return len && offset + 8 <= len && typeof buffer[offset] !== "string"; - } - function fromArray(destbuf, destoff, srcbuf, srcoff) { - destoff |= 0; - srcoff |= 0; - for (var i = 0; i < 8; i++) { - destbuf[destoff++] = srcbuf[srcoff++] & 255; - } - } - function newArray(buffer, offset) { - return Array.prototype.slice.call(buffer, offset, offset + 8); - } - function fromPositiveBE(buffer, offset, value) { - var pos = offset + 8; - while (pos > offset) { - buffer[--pos] = value & 255; - value /= 256; - } - } - function fromNegativeBE(buffer, offset, value) { - var pos = offset + 8; - value++; - while (pos > offset) { - buffer[--pos] = -value & 255 ^ 255; - value /= 256; - } - } - function fromPositiveLE(buffer, offset, value) { - var end = offset + 8; - while (offset < end) { - buffer[offset++] = value & 255; - value /= 256; - } - } - function fromNegativeLE(buffer, offset, value) { - var end = offset + 8; - value++; - while (offset < end) { - buffer[offset++] = -value & 255 ^ 255; - value /= 256; - } - } - function _isArray(val) { - return !!val && Object.prototype.toString.call(val) == "[object Array]"; - } - }(typeof exports2 === "object" && typeof exports2.nodeName !== "string" ? exports2 : exports2 || {}); - } -}); - -// node_modules/ieee754/index.js -var require_ieee754 = __commonJS({ - "node_modules/ieee754/index.js"(exports2) { - exports2.read = function(buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? nBytes - 1 : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - i += d; - e = s & (1 << -nBits) - 1; - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) { - } - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) { - } - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - }; - exports2.write = function(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = isLE ? 0 : nBytes - 1; - var d = isLE ? 1 : -1; - var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - value = Math.abs(value); - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) { - } - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) { - } - buffer[offset + i - d] |= s * 128; - }; - } -}); - -// node_modules/msgpack-lite/lib/write-uint8.js -var require_write_uint8 = __commonJS({ - "node_modules/msgpack-lite/lib/write-uint8.js"(exports2) { - var constant = exports2.uint8 = new Array(256); - for (var i = 0; i <= 255; i++) { - constant[i] = write0(i); - } - function write0(type) { - return function(encoder) { - var offset = encoder.reserve(1); - encoder.buffer[offset] = type; - }; - } - } -}); - -// node_modules/msgpack-lite/lib/write-token.js -var require_write_token = __commonJS({ - "node_modules/msgpack-lite/lib/write-token.js"(exports2) { - var ieee754 = require_ieee754(); - var Int64Buffer = require_int64_buffer(); - var Uint64BE = Int64Buffer.Uint64BE; - var Int64BE = Int64Buffer.Int64BE; - var uint8 = require_write_uint8().uint8; - var Bufferish = require_bufferish(); - var Buffer4 = Bufferish.global; - var IS_BUFFER_SHIM = Bufferish.hasBuffer && "TYPED_ARRAY_SUPPORT" in Buffer4; - var NO_TYPED_ARRAY = IS_BUFFER_SHIM && !Buffer4.TYPED_ARRAY_SUPPORT; - var Buffer_prototype = Bufferish.hasBuffer && Buffer4.prototype || {}; - exports2.getWriteToken = getWriteToken; - function getWriteToken(options) { - if (options && options.uint8array) { - return init_uint8array(); - } else if (NO_TYPED_ARRAY || Bufferish.hasBuffer && options && options.safe) { - return init_safe(); - } else { - return init_token(); - } - } - function init_uint8array() { - var token = init_token(); - token[202] = writeN(202, 4, writeFloatBE); - token[203] = writeN(203, 8, writeDoubleBE); - return token; - } - function init_token() { - var token = uint8.slice(); - token[196] = write1(196); - token[197] = write2(197); - token[198] = write4(198); - token[199] = write1(199); - token[200] = write2(200); - token[201] = write4(201); - token[202] = writeN(202, 4, Buffer_prototype.writeFloatBE || writeFloatBE, true); - token[203] = writeN(203, 8, Buffer_prototype.writeDoubleBE || writeDoubleBE, true); - token[204] = write1(204); - token[205] = write2(205); - token[206] = write4(206); - token[207] = writeN(207, 8, writeUInt64BE); - token[208] = write1(208); - token[209] = write2(209); - token[210] = write4(210); - token[211] = writeN(211, 8, writeInt64BE); - token[217] = write1(217); - token[218] = write2(218); - token[219] = write4(219); - token[220] = write2(220); - token[221] = write4(221); - token[222] = write2(222); - token[223] = write4(223); - return token; - } - function init_safe() { - var token = uint8.slice(); - token[196] = writeN(196, 1, Buffer4.prototype.writeUInt8); - token[197] = writeN(197, 2, Buffer4.prototype.writeUInt16BE); - token[198] = writeN(198, 4, Buffer4.prototype.writeUInt32BE); - token[199] = writeN(199, 1, Buffer4.prototype.writeUInt8); - token[200] = writeN(200, 2, Buffer4.prototype.writeUInt16BE); - token[201] = writeN(201, 4, Buffer4.prototype.writeUInt32BE); - token[202] = writeN(202, 4, Buffer4.prototype.writeFloatBE); - token[203] = writeN(203, 8, Buffer4.prototype.writeDoubleBE); - token[204] = writeN(204, 1, Buffer4.prototype.writeUInt8); - token[205] = writeN(205, 2, Buffer4.prototype.writeUInt16BE); - token[206] = writeN(206, 4, Buffer4.prototype.writeUInt32BE); - token[207] = writeN(207, 8, writeUInt64BE); - token[208] = writeN(208, 1, Buffer4.prototype.writeInt8); - token[209] = writeN(209, 2, Buffer4.prototype.writeInt16BE); - token[210] = writeN(210, 4, Buffer4.prototype.writeInt32BE); - token[211] = writeN(211, 8, writeInt64BE); - token[217] = writeN(217, 1, Buffer4.prototype.writeUInt8); - token[218] = writeN(218, 2, Buffer4.prototype.writeUInt16BE); - token[219] = writeN(219, 4, Buffer4.prototype.writeUInt32BE); - token[220] = writeN(220, 2, Buffer4.prototype.writeUInt16BE); - token[221] = writeN(221, 4, Buffer4.prototype.writeUInt32BE); - token[222] = writeN(222, 2, Buffer4.prototype.writeUInt16BE); - token[223] = writeN(223, 4, Buffer4.prototype.writeUInt32BE); - return token; - } - function write1(type) { - return function(encoder, value) { - var offset = encoder.reserve(2); - var buffer = encoder.buffer; - buffer[offset++] = type; - buffer[offset] = value; - }; - } - function write2(type) { - return function(encoder, value) { - var offset = encoder.reserve(3); - var buffer = encoder.buffer; - buffer[offset++] = type; - buffer[offset++] = value >>> 8; - buffer[offset] = value; - }; - } - function write4(type) { - return function(encoder, value) { - var offset = encoder.reserve(5); - var buffer = encoder.buffer; - buffer[offset++] = type; - buffer[offset++] = value >>> 24; - buffer[offset++] = value >>> 16; - buffer[offset++] = value >>> 8; - buffer[offset] = value; - }; - } - function writeN(type, len, method, noAssert) { - return function(encoder, value) { - var offset = encoder.reserve(len + 1); - encoder.buffer[offset++] = type; - method.call(encoder.buffer, value, offset, noAssert); - }; - } - function writeUInt64BE(value, offset) { - new Uint64BE(this, offset, value); - } - function writeInt64BE(value, offset) { - new Int64BE(this, offset, value); - } - function writeFloatBE(value, offset) { - ieee754.write(this, value, offset, false, 23, 4); - } - function writeDoubleBE(value, offset) { - ieee754.write(this, value, offset, false, 52, 8); - } - } -}); - -// node_modules/msgpack-lite/lib/write-type.js -var require_write_type = __commonJS({ - "node_modules/msgpack-lite/lib/write-type.js"(exports2) { - var IS_ARRAY = require_isarray(); - var Int64Buffer = require_int64_buffer(); - var Uint64BE = Int64Buffer.Uint64BE; - var Int64BE = Int64Buffer.Int64BE; - var Bufferish = require_bufferish(); - var BufferProto = require_bufferish_proto(); - var WriteToken = require_write_token(); - var uint8 = require_write_uint8().uint8; - var ExtBuffer = require_ext_buffer().ExtBuffer; - var HAS_UINT8ARRAY = typeof Uint8Array !== "undefined"; - var HAS_MAP = typeof Map !== "undefined"; - var extmap = []; - extmap[1] = 212; - extmap[2] = 213; - extmap[4] = 214; - extmap[8] = 215; - extmap[16] = 216; - exports2.getWriteType = getWriteType; - function getWriteType(options) { - var token = WriteToken.getWriteToken(options); - var useraw = options && options.useraw; - var binarraybuffer = HAS_UINT8ARRAY && options && options.binarraybuffer; - var isBuffer = binarraybuffer ? Bufferish.isArrayBuffer : Bufferish.isBuffer; - var bin = binarraybuffer ? bin_arraybuffer : bin_buffer; - var usemap = HAS_MAP && options && options.usemap; - var map = usemap ? map_to_map : obj_to_map; - var writeType = { - "boolean": bool, - "function": nil, - "number": number2, - "object": useraw ? object_raw : object, - "string": _string(useraw ? raw_head_size : str_head_size), - "symbol": nil, - "undefined": nil - }; - return writeType; - function bool(encoder, value) { - var type = value ? 195 : 194; - token[type](encoder, value); - } - function number2(encoder, value) { - var ivalue = value | 0; - var type; - if (value !== ivalue) { - type = 203; - token[type](encoder, value); - return; - } else if (-32 <= ivalue && ivalue <= 127) { - type = ivalue & 255; - } else if (0 <= ivalue) { - type = ivalue <= 255 ? 204 : ivalue <= 65535 ? 205 : 206; - } else { - type = -128 <= ivalue ? 208 : -32768 <= ivalue ? 209 : 210; - } - token[type](encoder, ivalue); - } - function uint64(encoder, value) { - var type = 207; - token[type](encoder, value.toArray()); - } - function int64(encoder, value) { - var type = 211; - token[type](encoder, value.toArray()); - } - function str_head_size(length) { - return length < 32 ? 1 : length <= 255 ? 2 : length <= 65535 ? 3 : 5; - } - function raw_head_size(length) { - return length < 32 ? 1 : length <= 65535 ? 3 : 5; - } - function _string(head_size) { - return string2; - function string2(encoder, value) { - var length = value.length; - var maxsize = 5 + length * 3; - encoder.offset = encoder.reserve(maxsize); - var buffer = encoder.buffer; - var expected = head_size(length); - var start = encoder.offset + expected; - length = BufferProto.write.call(buffer, value, start); - var actual = head_size(length); - if (expected !== actual) { - var targetStart = start + actual - expected; - var end = start + length; - BufferProto.copy.call(buffer, buffer, targetStart, start, end); - } - var type = actual === 1 ? 160 + length : actual <= 3 ? 215 + actual : 219; - token[type](encoder, length); - encoder.offset += length; - } - } - function object(encoder, value) { - if (value === null) - return nil(encoder, value); - if (isBuffer(value)) - return bin(encoder, value); - if (IS_ARRAY(value)) - return array(encoder, value); - if (Uint64BE.isUint64BE(value)) - return uint64(encoder, value); - if (Int64BE.isInt64BE(value)) - return int64(encoder, value); - var packer = encoder.codec.getExtPacker(value); - if (packer) - value = packer(value); - if (value instanceof ExtBuffer) - return ext(encoder, value); - map(encoder, value); - } - function object_raw(encoder, value) { - if (isBuffer(value)) - return raw(encoder, value); - object(encoder, value); - } - function nil(encoder, value) { - var type = 192; - token[type](encoder, value); - } - function array(encoder, value) { - var length = value.length; - var type = length < 16 ? 144 + length : length <= 65535 ? 220 : 221; - token[type](encoder, length); - var encode = encoder.codec.encode; - for (var i = 0; i < length; i++) { - encode(encoder, value[i]); - } - } - function bin_buffer(encoder, value) { - var length = value.length; - var type = length < 255 ? 196 : length <= 65535 ? 197 : 198; - token[type](encoder, length); - encoder.send(value); - } - function bin_arraybuffer(encoder, value) { - bin_buffer(encoder, new Uint8Array(value)); - } - function ext(encoder, value) { - var buffer = value.buffer; - var length = buffer.length; - var type = extmap[length] || (length < 255 ? 199 : length <= 65535 ? 200 : 201); - token[type](encoder, length); - uint8[value.type](encoder); - encoder.send(buffer); - } - function obj_to_map(encoder, value) { - var keys = Object.keys(value); - var length = keys.length; - var type = length < 16 ? 128 + length : length <= 65535 ? 222 : 223; - token[type](encoder, length); - var encode = encoder.codec.encode; - keys.forEach(function(key) { - encode(encoder, key); - encode(encoder, value[key]); - }); - } - function map_to_map(encoder, value) { - if (!(value instanceof Map)) - return obj_to_map(encoder, value); - var length = value.size; - var type = length < 16 ? 128 + length : length <= 65535 ? 222 : 223; - token[type](encoder, length); - var encode = encoder.codec.encode; - value.forEach(function(val, key, m) { - encode(encoder, key); - encode(encoder, val); - }); - } - function raw(encoder, value) { - var length = value.length; - var type = length < 32 ? 160 + length : length <= 65535 ? 218 : 219; - token[type](encoder, length); - encoder.send(value); - } - } - } -}); - -// node_modules/msgpack-lite/lib/codec-base.js -var require_codec_base = __commonJS({ - "node_modules/msgpack-lite/lib/codec-base.js"(exports2) { - var IS_ARRAY = require_isarray(); - exports2.createCodec = createCodec; - exports2.install = install; - exports2.filter = filter; - var Bufferish = require_bufferish(); - function Codec(options) { - if (!(this instanceof Codec)) - return new Codec(options); - this.options = options; - this.init(); - } - Codec.prototype.init = function() { - var options = this.options; - if (options && options.uint8array) { - this.bufferish = Bufferish.Uint8Array; - } - return this; - }; - function install(props) { - for (var key in props) { - Codec.prototype[key] = add(Codec.prototype[key], props[key]); - } - } - function add(a, b) { - return a && b ? ab : a || b; - function ab() { - a.apply(this, arguments); - return b.apply(this, arguments); - } - } - function join2(filters) { - filters = filters.slice(); - return function(value) { - return filters.reduce(iterator, value); - }; - function iterator(value, filter2) { - return filter2(value); - } - } - function filter(filter2) { - return IS_ARRAY(filter2) ? join2(filter2) : filter2; - } - function createCodec(options) { - return new Codec(options); - } - exports2.preset = createCodec({ preset: true }); - } -}); - -// node_modules/msgpack-lite/lib/write-core.js -var require_write_core = __commonJS({ - "node_modules/msgpack-lite/lib/write-core.js"(exports2) { - var ExtBuffer = require_ext_buffer().ExtBuffer; - var ExtPacker = require_ext_packer(); - var WriteType = require_write_type(); - var CodecBase = require_codec_base(); - CodecBase.install({ - addExtPacker, - getExtPacker, - init - }); - exports2.preset = init.call(CodecBase.preset); - function getEncoder(options) { - var writeType = WriteType.getWriteType(options); - return encode; - function encode(encoder, value) { - var func2 = writeType[typeof value]; - if (!func2) - throw new Error('Unsupported type "' + typeof value + '": ' + value); - func2(encoder, value); - } - } - function init() { - var options = this.options; - this.encode = getEncoder(options); - if (options && options.preset) { - ExtPacker.setExtPackers(this); - } - return this; - } - function addExtPacker(etype, Class, packer) { - packer = CodecBase.filter(packer); - var name2 = Class.name; - if (name2 && name2 !== "Object") { - var packers = this.extPackers || (this.extPackers = {}); - packers[name2] = extPacker; - } else { - var list2 = this.extEncoderList || (this.extEncoderList = []); - list2.unshift([Class, extPacker]); - } - function extPacker(value) { - if (packer) - value = packer(value); - return new ExtBuffer(value, etype); - } - } - function getExtPacker(value) { - var packers = this.extPackers || (this.extPackers = {}); - var c = value.constructor; - var e = c && c.name && packers[c.name]; - if (e) - return e; - var list2 = this.extEncoderList || (this.extEncoderList = []); - var len = list2.length; - for (var i = 0; i < len; i++) { - var pair = list2[i]; - if (c === pair[0]) - return pair[1]; - } - } - } -}); - -// node_modules/msgpack-lite/lib/flex-buffer.js -var require_flex_buffer = __commonJS({ - "node_modules/msgpack-lite/lib/flex-buffer.js"(exports2) { - exports2.FlexDecoder = FlexDecoder; - exports2.FlexEncoder = FlexEncoder; - var Bufferish = require_bufferish(); - var MIN_BUFFER_SIZE = 2048; - var MAX_BUFFER_SIZE = 65536; - var BUFFER_SHORTAGE = "BUFFER_SHORTAGE"; - function FlexDecoder() { - if (!(this instanceof FlexDecoder)) - return new FlexDecoder(); - } - function FlexEncoder() { - if (!(this instanceof FlexEncoder)) - return new FlexEncoder(); - } - FlexDecoder.mixin = mixinFactory(getDecoderMethods()); - FlexDecoder.mixin(FlexDecoder.prototype); - FlexEncoder.mixin = mixinFactory(getEncoderMethods()); - FlexEncoder.mixin(FlexEncoder.prototype); - function getDecoderMethods() { - return { - bufferish: Bufferish, - write: write2, - fetch: fetch2, - flush, - push, - pull, - read, - reserve, - offset: 0 - }; - function write2(chunk) { - var prev = this.offset ? Bufferish.prototype.slice.call(this.buffer, this.offset) : this.buffer; - this.buffer = prev ? chunk ? this.bufferish.concat([prev, chunk]) : prev : chunk; - this.offset = 0; - } - function flush() { - while (this.offset < this.buffer.length) { - var start = this.offset; - var value; - try { - value = this.fetch(); - } catch (e) { - if (e && e.message != BUFFER_SHORTAGE) - throw e; - this.offset = start; - break; - } - this.push(value); - } - } - function reserve(length) { - var start = this.offset; - var end = start + length; - if (end > this.buffer.length) - throw new Error(BUFFER_SHORTAGE); - this.offset = end; - return start; - } - } - function getEncoderMethods() { - return { - bufferish: Bufferish, - write, - fetch: fetch3, - flush, - push, - pull: pull2, - read, - reserve, - send, - maxBufferSize: MAX_BUFFER_SIZE, - minBufferSize: MIN_BUFFER_SIZE, - offset: 0, - start: 0 - }; - function fetch3() { - var start = this.start; - if (start < this.offset) { - var end = this.start = this.offset; - return Bufferish.prototype.slice.call(this.buffer, start, end); - } - } - function flush() { - while (this.start < this.offset) { - var value = this.fetch(); - if (value) - this.push(value); - } - } - function pull2() { - var buffers = this.buffers || (this.buffers = []); - var chunk = buffers.length > 1 ? this.bufferish.concat(buffers) : buffers[0]; - buffers.length = 0; - return chunk; - } - function reserve(length) { - var req = length | 0; - if (this.buffer) { - var size = this.buffer.length; - var start = this.offset | 0; - var end = start + req; - if (end < size) { - this.offset = end; - return start; - } - this.flush(); - length = Math.max(length, Math.min(size * 2, this.maxBufferSize)); - } - length = Math.max(length, this.minBufferSize); - this.buffer = this.bufferish.alloc(length); - this.start = 0; - this.offset = req; - return 0; - } - function send(buffer) { - var length = buffer.length; - if (length > this.minBufferSize) { - this.flush(); - this.push(buffer); - } else { - var offset = this.reserve(length); - Bufferish.prototype.copy.call(buffer, this.buffer, offset); - } - } - } - function write() { - throw new Error("method not implemented: write()"); - } - function fetch2() { - throw new Error("method not implemented: fetch()"); - } - function read() { - var length = this.buffers && this.buffers.length; - if (!length) - return this.fetch(); - this.flush(); - return this.pull(); - } - function push(chunk) { - var buffers = this.buffers || (this.buffers = []); - buffers.push(chunk); - } - function pull() { - var buffers = this.buffers || (this.buffers = []); - return buffers.shift(); - } - function mixinFactory(source) { - return mixin2; - function mixin2(target) { - for (var key in source) { - target[key] = source[key]; - } - return target; - } - } - } -}); - -// node_modules/msgpack-lite/lib/encode-buffer.js -var require_encode_buffer = __commonJS({ - "node_modules/msgpack-lite/lib/encode-buffer.js"(exports2) { - exports2.EncodeBuffer = EncodeBuffer; - var preset = require_write_core().preset; - var FlexEncoder = require_flex_buffer().FlexEncoder; - FlexEncoder.mixin(EncodeBuffer.prototype); - function EncodeBuffer(options) { - if (!(this instanceof EncodeBuffer)) - return new EncodeBuffer(options); - if (options) { - this.options = options; - if (options.codec) { - var codec = this.codec = options.codec; - if (codec.bufferish) - this.bufferish = codec.bufferish; - } - } - } - EncodeBuffer.prototype.codec = preset; - EncodeBuffer.prototype.write = function(input) { - this.codec.encode(this, input); - }; - } -}); - -// node_modules/msgpack-lite/lib/encode.js -var require_encode = __commonJS({ - "node_modules/msgpack-lite/lib/encode.js"(exports2) { - exports2.encode = encode; - var EncodeBuffer = require_encode_buffer().EncodeBuffer; - function encode(input, options) { - var encoder = new EncodeBuffer(options); - encoder.write(input); - return encoder.read(); - } - } -}); - -// node_modules/msgpack-lite/lib/ext-unpacker.js -var require_ext_unpacker = __commonJS({ - "node_modules/msgpack-lite/lib/ext-unpacker.js"(exports2) { - exports2.setExtUnpackers = setExtUnpackers; - var Bufferish = require_bufferish(); - var Buffer4 = Bufferish.global; - var _decode; - var ERROR_COLUMNS = { name: 1, message: 1, stack: 1, columnNumber: 1, fileName: 1, lineNumber: 1 }; - function setExtUnpackers(codec) { - codec.addExtUnpacker(14, [decode, unpackError(Error)]); - codec.addExtUnpacker(1, [decode, unpackError(EvalError)]); - codec.addExtUnpacker(2, [decode, unpackError(RangeError)]); - codec.addExtUnpacker(3, [decode, unpackError(ReferenceError)]); - codec.addExtUnpacker(4, [decode, unpackError(SyntaxError)]); - codec.addExtUnpacker(5, [decode, unpackError(TypeError)]); - codec.addExtUnpacker(6, [decode, unpackError(URIError)]); - codec.addExtUnpacker(10, [decode, unpackRegExp]); - codec.addExtUnpacker(11, [decode, unpackClass(Boolean)]); - codec.addExtUnpacker(12, [decode, unpackClass(String)]); - codec.addExtUnpacker(13, [decode, unpackClass(Date)]); - codec.addExtUnpacker(15, [decode, unpackClass(Number)]); - if (typeof Uint8Array !== "undefined") { - codec.addExtUnpacker(17, unpackClass(Int8Array)); - codec.addExtUnpacker(18, unpackClass(Uint8Array)); - codec.addExtUnpacker(19, [unpackArrayBuffer, unpackClass(Int16Array)]); - codec.addExtUnpacker(20, [unpackArrayBuffer, unpackClass(Uint16Array)]); - codec.addExtUnpacker(21, [unpackArrayBuffer, unpackClass(Int32Array)]); - codec.addExtUnpacker(22, [unpackArrayBuffer, unpackClass(Uint32Array)]); - codec.addExtUnpacker(23, [unpackArrayBuffer, unpackClass(Float32Array)]); - if (typeof Float64Array !== "undefined") { - codec.addExtUnpacker(24, [unpackArrayBuffer, unpackClass(Float64Array)]); - } - if (typeof Uint8ClampedArray !== "undefined") { - codec.addExtUnpacker(25, unpackClass(Uint8ClampedArray)); - } - codec.addExtUnpacker(26, unpackArrayBuffer); - codec.addExtUnpacker(29, [unpackArrayBuffer, unpackClass(DataView)]); - } - if (Bufferish.hasBuffer) { - codec.addExtUnpacker(27, unpackClass(Buffer4)); - } - } - function decode(input) { - if (!_decode) - _decode = require_decode().decode; - return _decode(input); - } - function unpackRegExp(value) { - return RegExp.apply(null, value); - } - function unpackError(Class) { - return function(value) { - var out = new Class(); - for (var key in ERROR_COLUMNS) { - out[key] = value[key]; - } - return out; - }; - } - function unpackClass(Class) { - return function(value) { - return new Class(value); - }; - } - function unpackArrayBuffer(value) { - return new Uint8Array(value).buffer; - } - } -}); - -// node_modules/msgpack-lite/lib/read-format.js -var require_read_format = __commonJS({ - "node_modules/msgpack-lite/lib/read-format.js"(exports2) { - var ieee754 = require_ieee754(); - var Int64Buffer = require_int64_buffer(); - var Uint64BE = Int64Buffer.Uint64BE; - var Int64BE = Int64Buffer.Int64BE; - exports2.getReadFormat = getReadFormat; - exports2.readUint8 = uint8; - var Bufferish = require_bufferish(); - var BufferProto = require_bufferish_proto(); - var HAS_MAP = typeof Map !== "undefined"; - var NO_ASSERT = true; - function getReadFormat(options) { - var binarraybuffer = Bufferish.hasArrayBuffer && options && options.binarraybuffer; - var int64 = options && options.int64; - var usemap = HAS_MAP && options && options.usemap; - var readFormat = { - map: usemap ? map_to_map : map_to_obj, - array, - str, - bin: binarraybuffer ? bin_arraybuffer : bin_buffer, - ext, - uint8, - uint16, - uint32, - uint64: read(8, int64 ? readUInt64BE_int64 : readUInt64BE), - int8, - int16, - int32, - int64: read(8, int64 ? readInt64BE_int64 : readInt64BE), - float32: read(4, readFloatBE), - float64: read(8, readDoubleBE) - }; - return readFormat; - } - function map_to_obj(decoder, len) { - var value = {}; - var i; - var k = new Array(len); - var v = new Array(len); - var decode = decoder.codec.decode; - for (i = 0; i < len; i++) { - k[i] = decode(decoder); - v[i] = decode(decoder); - } - for (i = 0; i < len; i++) { - value[k[i]] = v[i]; - } - return value; - } - function map_to_map(decoder, len) { - var value = new Map(); - var i; - var k = new Array(len); - var v = new Array(len); - var decode = decoder.codec.decode; - for (i = 0; i < len; i++) { - k[i] = decode(decoder); - v[i] = decode(decoder); - } - for (i = 0; i < len; i++) { - value.set(k[i], v[i]); - } - return value; - } - function array(decoder, len) { - var value = new Array(len); - var decode = decoder.codec.decode; - for (var i = 0; i < len; i++) { - value[i] = decode(decoder); - } - return value; - } - function str(decoder, len) { - var start = decoder.reserve(len); - var end = start + len; - return BufferProto.toString.call(decoder.buffer, "utf-8", start, end); - } - function bin_buffer(decoder, len) { - var start = decoder.reserve(len); - var end = start + len; - var buf = BufferProto.slice.call(decoder.buffer, start, end); - return Bufferish.from(buf); - } - function bin_arraybuffer(decoder, len) { - var start = decoder.reserve(len); - var end = start + len; - var buf = BufferProto.slice.call(decoder.buffer, start, end); - return Bufferish.Uint8Array.from(buf).buffer; - } - function ext(decoder, len) { - var start = decoder.reserve(len + 1); - var type = decoder.buffer[start++]; - var end = start + len; - var unpack = decoder.codec.getExtUnpacker(type); - if (!unpack) - throw new Error("Invalid ext type: " + (type ? "0x" + type.toString(16) : type)); - var buf = BufferProto.slice.call(decoder.buffer, start, end); - return unpack(buf); - } - function uint8(decoder) { - var start = decoder.reserve(1); - return decoder.buffer[start]; - } - function int8(decoder) { - var start = decoder.reserve(1); - var value = decoder.buffer[start]; - return value & 128 ? value - 256 : value; - } - function uint16(decoder) { - var start = decoder.reserve(2); - var buffer = decoder.buffer; - return buffer[start++] << 8 | buffer[start]; - } - function int16(decoder) { - var start = decoder.reserve(2); - var buffer = decoder.buffer; - var value = buffer[start++] << 8 | buffer[start]; - return value & 32768 ? value - 65536 : value; - } - function uint32(decoder) { - var start = decoder.reserve(4); - var buffer = decoder.buffer; - return buffer[start++] * 16777216 + (buffer[start++] << 16) + (buffer[start++] << 8) + buffer[start]; - } - function int32(decoder) { - var start = decoder.reserve(4); - var buffer = decoder.buffer; - return buffer[start++] << 24 | buffer[start++] << 16 | buffer[start++] << 8 | buffer[start]; - } - function read(len, method) { - return function(decoder) { - var start = decoder.reserve(len); - return method.call(decoder.buffer, start, NO_ASSERT); - }; - } - function readUInt64BE(start) { - return new Uint64BE(this, start).toNumber(); - } - function readInt64BE(start) { - return new Int64BE(this, start).toNumber(); - } - function readUInt64BE_int64(start) { - return new Uint64BE(this, start); - } - function readInt64BE_int64(start) { - return new Int64BE(this, start); - } - function readFloatBE(start) { - return ieee754.read(this, start, false, 23, 4); - } - function readDoubleBE(start) { - return ieee754.read(this, start, false, 52, 8); - } - } -}); - -// node_modules/msgpack-lite/lib/read-token.js -var require_read_token = __commonJS({ - "node_modules/msgpack-lite/lib/read-token.js"(exports2) { - var ReadFormat = require_read_format(); - exports2.getReadToken = getReadToken; - function getReadToken(options) { - var format2 = ReadFormat.getReadFormat(options); - if (options && options.useraw) { - return init_useraw(format2); - } else { - return init_token(format2); - } - } - function init_token(format2) { - var i; - var token = new Array(256); - for (i = 0; i <= 127; i++) { - token[i] = constant(i); - } - for (i = 128; i <= 143; i++) { - token[i] = fix(i - 128, format2.map); - } - for (i = 144; i <= 159; i++) { - token[i] = fix(i - 144, format2.array); - } - for (i = 160; i <= 191; i++) { - token[i] = fix(i - 160, format2.str); - } - token[192] = constant(null); - token[193] = null; - token[194] = constant(false); - token[195] = constant(true); - token[196] = flex(format2.uint8, format2.bin); - token[197] = flex(format2.uint16, format2.bin); - token[198] = flex(format2.uint32, format2.bin); - token[199] = flex(format2.uint8, format2.ext); - token[200] = flex(format2.uint16, format2.ext); - token[201] = flex(format2.uint32, format2.ext); - token[202] = format2.float32; - token[203] = format2.float64; - token[204] = format2.uint8; - token[205] = format2.uint16; - token[206] = format2.uint32; - token[207] = format2.uint64; - token[208] = format2.int8; - token[209] = format2.int16; - token[210] = format2.int32; - token[211] = format2.int64; - token[212] = fix(1, format2.ext); - token[213] = fix(2, format2.ext); - token[214] = fix(4, format2.ext); - token[215] = fix(8, format2.ext); - token[216] = fix(16, format2.ext); - token[217] = flex(format2.uint8, format2.str); - token[218] = flex(format2.uint16, format2.str); - token[219] = flex(format2.uint32, format2.str); - token[220] = flex(format2.uint16, format2.array); - token[221] = flex(format2.uint32, format2.array); - token[222] = flex(format2.uint16, format2.map); - token[223] = flex(format2.uint32, format2.map); - for (i = 224; i <= 255; i++) { - token[i] = constant(i - 256); - } - return token; - } - function init_useraw(format2) { - var i; - var token = init_token(format2).slice(); - token[217] = token[196]; - token[218] = token[197]; - token[219] = token[198]; - for (i = 160; i <= 191; i++) { - token[i] = fix(i - 160, format2.bin); - } - return token; - } - function constant(value) { - return function() { - return value; - }; - } - function flex(lenFunc, decodeFunc) { - return function(decoder) { - var len = lenFunc(decoder); - return decodeFunc(decoder, len); - }; - } - function fix(len, method) { - return function(decoder) { - return method(decoder, len); - }; - } - } -}); - -// node_modules/msgpack-lite/lib/read-core.js -var require_read_core = __commonJS({ - "node_modules/msgpack-lite/lib/read-core.js"(exports2) { - var ExtBuffer = require_ext_buffer().ExtBuffer; - var ExtUnpacker = require_ext_unpacker(); - var readUint8 = require_read_format().readUint8; - var ReadToken = require_read_token(); - var CodecBase = require_codec_base(); - CodecBase.install({ - addExtUnpacker, - getExtUnpacker, - init - }); - exports2.preset = init.call(CodecBase.preset); - function getDecoder(options) { - var readToken = ReadToken.getReadToken(options); - return decode; - function decode(decoder) { - var type = readUint8(decoder); - var func2 = readToken[type]; - if (!func2) - throw new Error("Invalid type: " + (type ? "0x" + type.toString(16) : type)); - return func2(decoder); - } - } - function init() { - var options = this.options; - this.decode = getDecoder(options); - if (options && options.preset) { - ExtUnpacker.setExtUnpackers(this); - } - return this; - } - function addExtUnpacker(etype, unpacker) { - var unpackers = this.extUnpackers || (this.extUnpackers = []); - unpackers[etype] = CodecBase.filter(unpacker); - } - function getExtUnpacker(type) { - var unpackers = this.extUnpackers || (this.extUnpackers = []); - return unpackers[type] || extUnpacker; - function extUnpacker(buffer) { - return new ExtBuffer(buffer, type); - } - } - } -}); - -// node_modules/msgpack-lite/lib/decode-buffer.js -var require_decode_buffer = __commonJS({ - "node_modules/msgpack-lite/lib/decode-buffer.js"(exports2) { - exports2.DecodeBuffer = DecodeBuffer; - var preset = require_read_core().preset; - var FlexDecoder = require_flex_buffer().FlexDecoder; - FlexDecoder.mixin(DecodeBuffer.prototype); - function DecodeBuffer(options) { - if (!(this instanceof DecodeBuffer)) - return new DecodeBuffer(options); - if (options) { - this.options = options; - if (options.codec) { - var codec = this.codec = options.codec; - if (codec.bufferish) - this.bufferish = codec.bufferish; - } - } - } - DecodeBuffer.prototype.codec = preset; - DecodeBuffer.prototype.fetch = function() { - return this.codec.decode(this); - }; - } -}); - -// node_modules/msgpack-lite/lib/decode.js -var require_decode = __commonJS({ - "node_modules/msgpack-lite/lib/decode.js"(exports2) { - exports2.decode = decode; - var DecodeBuffer = require_decode_buffer().DecodeBuffer; - function decode(input, options) { - var decoder = new DecodeBuffer(options); - decoder.write(input); - return decoder.read(); - } - } -}); - -// node_modules/event-lite/event-lite.js -var require_event_lite = __commonJS({ - "node_modules/event-lite/event-lite.js"(exports2, module2) { - function EventLite() { - if (!(this instanceof EventLite)) - return new EventLite(); - } - (function(EventLite2) { - if (typeof module2 !== "undefined") - module2.exports = EventLite2; - var LISTENERS = "listeners"; - var methods2 = { - on, - once, - off, - emit - }; - mixin2(EventLite2.prototype); - EventLite2.mixin = mixin2; - function mixin2(target) { - for (var key in methods2) { - target[key] = methods2[key]; - } - return target; - } - function on(type, func2) { - getListeners(this, type).push(func2); - return this; - } - function once(type, func2) { - var that = this; - wrap.originalListener = func2; - getListeners(that, type).push(wrap); - return that; - function wrap() { - off.call(that, type, wrap); - func2.apply(this, arguments); - } - } - function off(type, func2) { - var that = this; - var listners; - if (!arguments.length) { - delete that[LISTENERS]; - } else if (!func2) { - listners = that[LISTENERS]; - if (listners) { - delete listners[type]; - if (!Object.keys(listners).length) - return off.call(that); - } - } else { - listners = getListeners(that, type, true); - if (listners) { - listners = listners.filter(ne); - if (!listners.length) - return off.call(that, type); - that[LISTENERS][type] = listners; - } - } - return that; - function ne(test) { - return test !== func2 && test.originalListener !== func2; - } - } - function emit(type, value) { - var that = this; - var listeners = getListeners(that, type, true); - if (!listeners) - return false; - var arglen = arguments.length; - if (arglen === 1) { - listeners.forEach(zeroarg); - } else if (arglen === 2) { - listeners.forEach(onearg); - } else { - var args = Array.prototype.slice.call(arguments, 1); - listeners.forEach(moreargs); - } - return !!listeners.length; - function zeroarg(func2) { - func2.call(that); - } - function onearg(func2) { - func2.call(that, value); - } - function moreargs(func2) { - func2.apply(that, args); - } - } - function getListeners(that, type, readonly) { - if (readonly && !that[LISTENERS]) - return; - var listeners = that[LISTENERS] || (that[LISTENERS] = {}); - return listeners[type] || (listeners[type] = []); - } - })(EventLite); - } -}); - -// node_modules/msgpack-lite/lib/encoder.js -var require_encoder = __commonJS({ - "node_modules/msgpack-lite/lib/encoder.js"(exports2) { - exports2.Encoder = Encoder; - var EventLite = require_event_lite(); - var EncodeBuffer = require_encode_buffer().EncodeBuffer; - function Encoder(options) { - if (!(this instanceof Encoder)) - return new Encoder(options); - EncodeBuffer.call(this, options); - } - Encoder.prototype = new EncodeBuffer(); - EventLite.mixin(Encoder.prototype); - Encoder.prototype.encode = function(chunk) { - this.write(chunk); - this.emit("data", this.read()); - }; - Encoder.prototype.end = function(chunk) { - if (arguments.length) - this.encode(chunk); - this.flush(); - this.emit("end"); - }; - } -}); - -// node_modules/msgpack-lite/lib/decoder.js -var require_decoder = __commonJS({ - "node_modules/msgpack-lite/lib/decoder.js"(exports2) { - exports2.Decoder = Decoder; - var EventLite = require_event_lite(); - var DecodeBuffer = require_decode_buffer().DecodeBuffer; - function Decoder(options) { - if (!(this instanceof Decoder)) - return new Decoder(options); - DecodeBuffer.call(this, options); - } - Decoder.prototype = new DecodeBuffer(); - EventLite.mixin(Decoder.prototype); - Decoder.prototype.decode = function(chunk) { - if (arguments.length) - this.write(chunk); - this.flush(); - }; - Decoder.prototype.push = function(chunk) { - this.emit("data", chunk); - }; - Decoder.prototype.end = function(chunk) { - this.decode(chunk); - this.emit("end"); - }; - } -}); - -// node_modules/msgpack-lite/lib/encode-stream.js -var require_encode_stream = __commonJS({ - "node_modules/msgpack-lite/lib/encode-stream.js"(exports2) { - exports2.createEncodeStream = EncodeStream; - var util4 = require("util"); - var Transform2 = require("stream").Transform; - var EncodeBuffer = require_encode_buffer().EncodeBuffer; - util4.inherits(EncodeStream, Transform2); - var DEFAULT_OPTIONS = { objectMode: true }; - function EncodeStream(options) { - if (!(this instanceof EncodeStream)) - return new EncodeStream(options); - if (options) { - options.objectMode = true; - } else { - options = DEFAULT_OPTIONS; - } - Transform2.call(this, options); - var stream = this; - var encoder = this.encoder = new EncodeBuffer(options); - encoder.push = function(chunk) { - stream.push(chunk); - }; - } - EncodeStream.prototype._transform = function(chunk, encoding, callback) { - this.encoder.write(chunk); - if (callback) - callback(); - }; - EncodeStream.prototype._flush = function(callback) { - this.encoder.flush(); - if (callback) - callback(); - }; - } -}); - -// node_modules/msgpack-lite/lib/decode-stream.js -var require_decode_stream = __commonJS({ - "node_modules/msgpack-lite/lib/decode-stream.js"(exports2) { - exports2.createDecodeStream = DecodeStream; - var util4 = require("util"); - var Transform2 = require("stream").Transform; - var DecodeBuffer = require_decode_buffer().DecodeBuffer; - util4.inherits(DecodeStream, Transform2); - var DEFAULT_OPTIONS = { objectMode: true }; - function DecodeStream(options) { - if (!(this instanceof DecodeStream)) - return new DecodeStream(options); - if (options) { - options.objectMode = true; - } else { - options = DEFAULT_OPTIONS; - } - Transform2.call(this, options); - var stream = this; - var decoder = this.decoder = new DecodeBuffer(options); - decoder.push = function(chunk) { - stream.push(chunk); - }; - } - DecodeStream.prototype._transform = function(chunk, encoding, callback) { - this.decoder.write(chunk); - this.decoder.flush(); - if (callback) - callback(); - }; - } -}); - -// node_modules/msgpack-lite/lib/ext.js -var require_ext = __commonJS({ - "node_modules/msgpack-lite/lib/ext.js"(exports2) { - require_read_core(); - require_write_core(); - exports2.createCodec = require_codec_base().createCodec; - } -}); - -// node_modules/msgpack-lite/lib/codec.js -var require_codec = __commonJS({ - "node_modules/msgpack-lite/lib/codec.js"(exports2) { - require_read_core(); - require_write_core(); - exports2.codec = { - preset: require_codec_base().preset - }; - } -}); - -// node_modules/msgpack-lite/index.js -var require_msgpack_lite = __commonJS({ - "node_modules/msgpack-lite/index.js"(exports2) { - exports2.encode = require_encode().encode; - exports2.decode = require_decode().decode; - exports2.Encoder = require_encoder().Encoder; - exports2.Decoder = require_decoder().Decoder; - exports2.createEncodeStream = require_encode_stream().createEncodeStream; - exports2.createDecodeStream = require_decode_stream().createDecodeStream; - exports2.createCodec = require_ext().createCodec; - exports2.codec = require_codec().codec; - } -}); - -// node_modules/@chemzqm/neovim/lib/utils/buffered.js -var require_buffered = __commonJS({ - "node_modules/@chemzqm/neovim/lib/utils/buffered.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var stream_1 = require("stream"); - var Buffered = class extends stream_1.Transform { - constructor() { - super({ - readableHighWaterMark: 10 * 1024 * 1024, - writableHighWaterMark: 10 * 1024 * 1024 - }); - this.chunks = null; - this.timer = null; - } - sendData() { - const { chunks } = this; - if (chunks) { - this.chunks = null; - const buf = Buffer.concat(chunks); - this.push(buf); - } - } - _transform(chunk, _encoding, callback) { - const { chunks, timer } = this; - const MIN_SIZE = Buffer.poolSize; - if (timer) - clearTimeout(timer); - if (chunk.length < MIN_SIZE) { - if (!chunks) - return callback(null, chunk); - chunks.push(chunk); - this.sendData(); - callback(); - } else { - if (!chunks) { - this.chunks = [chunk]; - } else { - chunks.push(chunk); - } - this.timer = setTimeout(this.sendData.bind(this), 20); - callback(); - } - } - _flush(callback) { - const { chunks } = this; - if (chunks) { - this.chunks = null; - const buf = Buffer.concat(chunks); - callback(null, buf); - } else { - callback(); - } - } - }; - exports2.default = Buffered; - } -}); - -// node_modules/@chemzqm/neovim/lib/api/Base.js -var require_Base = __commonJS({ - "node_modules/@chemzqm/neovim/lib/api/Base.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BaseApi = void 0; - var events_1 = require("events"); - var isVim7 = process.env.VIM_NODE_RPC == "1"; - var BaseApi = class extends events_1.EventEmitter { - constructor({ transport, data, client }) { - super(); - this.setTransport(transport); - this.data = data; - this.client = client; - } - setTransport(transport) { - this.transport = transport; - } - equals(other) { - try { - return String(this.data) === String(other.data); - } catch (e) { - return false; - } - } - async request(name2, args = []) { - let stack = Error().stack; - return new Promise((resolve3, reject) => { - this.transport.request(name2, this.getArgsByPrefix(args), (err, res) => { - if (err) { - let e = new Error(`request error ${name2} - ${err[1]}`); - e.stack = stack; - if (!name2.endsWith("get_var")) { - this.client.logError(`request error on "${name2}"`, args, err[1], stack); - } - reject(e); - } else { - resolve3(res); - } - }); - }); - } - getArgsByPrefix(args) { - if (this.prefix !== "nvim_" && args[0] != this) { - let id = isVim7 ? this.data : this; - return [id, ...args]; - } - return args; - } - getVar(name2) { - return this.request(`${this.prefix}get_var`, [name2]).then((res) => res, (_err) => { - return null; - }); - } - setVar(name2, value, isNotify = false) { - if (isNotify) { - this.notify(`${this.prefix}set_var`, [name2, value]); - return; - } - return this.request(`${this.prefix}set_var`, [name2, value]); - } - deleteVar(name2) { - this.notify(`${this.prefix}del_var`, [name2]); - } - getOption(name2) { - return this.request(`${this.prefix}get_option`, [name2]); - } - setOption(name2, value, isNotify) { - if (isNotify) { - this.notify(`${this.prefix}set_option`, [name2, value]); - return; - } - return this.request(`${this.prefix}set_option`, [name2, value]); - } - notify(name2, args = []) { - this.transport.notify(name2, this.getArgsByPrefix(args)); - } - }; - exports2.BaseApi = BaseApi; - } -}); - -// node_modules/@chemzqm/neovim/lib/api/Buffer.js -var require_Buffer = __commonJS({ - "node_modules/@chemzqm/neovim/lib/api/Buffer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Buffer = void 0; - var Base_1 = require_Base(); - var Buffer4 = class extends Base_1.BaseApi { - constructor() { - super(...arguments); - this.prefix = "nvim_buf_"; - } - async attach(sendBuffer = false, options = {}) { - return await this.request(`${this.prefix}attach`, [sendBuffer, options]); - } - async detach() { - return await this.request(`${this.prefix}detach`, []); - } - get id() { - return this.data; - } - get length() { - return this.request(`${this.prefix}line_count`, []); - } - get lines() { - return this.getLines(); - } - get changedtick() { - return this.request(`${this.prefix}get_changedtick`, []); - } - get commands() { - return this.getCommands(); - } - getCommands(options = {}) { - return this.request(`${this.prefix}get_commands`, [options]); - } - getLines({ start, end, strictIndexing } = { start: 0, end: -1, strictIndexing: true }) { - const indexing = typeof strictIndexing === "undefined" ? true : strictIndexing; - return this.request(`${this.prefix}get_lines`, [ - start, - end, - indexing - ]); - } - setLines(_lines, { start: _start, end: _end, strictIndexing } = { - strictIndexing: true - }, notify = false) { - const indexing = typeof strictIndexing === "undefined" ? true : strictIndexing; - const lines = typeof _lines === "string" ? [_lines] : _lines; - const end = typeof _end !== "undefined" ? _end : _start + 1; - const method = notify ? "notify" : "request"; - return this[method](`${this.prefix}set_lines`, [ - _start, - end, - indexing, - lines - ]); - } - setVirtualText(src_id, line, chunks, opts = {}) { - this.notify(`${this.prefix}set_virtual_text`, [ - src_id, - line, - chunks, - opts - ]); - return Promise.resolve(src_id); - } - insert(lines, start) { - return this.setLines(lines, { - start, - end: start, - strictIndexing: true - }); - } - replace(_lines, start) { - const lines = typeof _lines === "string" ? [_lines] : _lines; - return this.setLines(lines, { - start, - end: start + lines.length, - strictIndexing: false - }); - } - remove(start, end, strictIndexing = false) { - return this.setLines([], { start, end, strictIndexing }); - } - append(lines) { - return this.setLines(lines, { - start: -1, - end: -1, - strictIndexing: false - }); - } - get name() { - return this.request(`${this.prefix}get_name`, []); - } - setName(value) { - return this.request(`${this.prefix}set_name`, [value]); - } - get valid() { - return this.request(`${this.prefix}is_valid`, []); - } - mark(name2) { - return this.request(`${this.prefix}get_mark`, [name2]); - } - getKeymap(mode) { - return this.request(`${this.prefix}get_keymap`, [mode]); - } - setKeymap(mode, lhs, rhs, opts = {}) { - this.client.call("coc#compat#buf_add_keymap", [this.id, mode, lhs, rhs, opts], true); - } - get loaded() { - return this.request(`${this.prefix}is_loaded`, []); - } - getOffset(index) { - return this.request(`${this.prefix}get_offset`, [index]); - } - addHighlight({ hlGroup, line, colStart: _start, colEnd: _end, srcId: _srcId }) { - if (!hlGroup) - throw new Error("hlGroup should not empty"); - const colEnd = typeof _end !== "undefined" ? _end : -1; - const colStart = typeof _start !== "undefined" ? _start : -0; - const srcId = typeof _srcId !== "undefined" ? _srcId : -1; - const method = srcId == 0 ? "request" : "notify"; - let res = this[method](`${this.prefix}add_highlight`, [ - srcId, - hlGroup, - line, - colStart, - colEnd - ]); - return method === "request" ? res : Promise.resolve(null); - } - clearHighlight(args = {}) { - const defaults2 = { - srcId: -1, - lineStart: 0, - lineEnd: -1 - }; - const { srcId, lineStart, lineEnd } = Object.assign({}, defaults2, args); - return this.notify(`${this.prefix}clear_highlight`, [ - srcId, - lineStart, - lineEnd - ]); - } - highlightRanges(srcId, hlGroup, ranges) { - this.client.call("coc#highlight#ranges", [this.id, srcId, hlGroup, ranges], true); - } - clearNamespace(key, lineStart = 0, lineEnd = -1) { - this.client.call("coc#highlight#clear_highlight", [this.id, key, lineStart, lineEnd], true); - } - placeSign(sign) { - let opts = { lnum: sign.lnum }; - if (typeof sign.priority === "number") - opts.priority = sign.priority; - this.client.call("sign_place", [sign.id || 0, sign.group || "", sign.name, this.id, opts], true); - } - unplaceSign(opts) { - let details = { buffer: this.id }; - if (opts.id != null) - details.id = opts.id; - this.client.call("sign_unplace", [opts.group || "", details], true); - } - async getSigns(opts) { - let res = await this.client.call("sign_getplaced", [this.id, opts || {}]); - return res[0].signs; - } - async getHighlights(ns, start = 0, end = -1) { - let res = []; - let obj = await this.client.call("coc#highlight#get", [this.id, ns, start, end]); - for (let arr of Object.values(obj)) { - if (Array.isArray(arr)) { - res.push(...arr); - } - } - return res; - } - updateHighlights(ns, highlights, start = 0, end = -1) { - this.client.call("coc#highlight#update_highlights", [this.id, ns, highlights, start, end], true); - } - listen(eventName, cb, disposables) { - this.client.attachBufferEvent(this, eventName, cb); - if (disposables) { - disposables.push({ - dispose: () => { - this.client.detachBufferEvent(this, eventName, cb); - } - }); - } - } - }; - exports2.Buffer = Buffer4; - } -}); - -// node_modules/@chemzqm/neovim/lib/api/Window.js -var require_Window = __commonJS({ - "node_modules/@chemzqm/neovim/lib/api/Window.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Window = void 0; - var Base_1 = require_Base(); - var timers_1 = require("timers"); - var Window3 = class extends Base_1.BaseApi { - constructor() { - super(...arguments); - this.prefix = "nvim_win_"; - } - get id() { - return this.data; - } - get buffer() { - return this.request(`${this.prefix}get_buf`, []); - } - get tabpage() { - return this.request(`${this.prefix}get_tabpage`, []); - } - get cursor() { - return this.request(`${this.prefix}get_cursor`, []); - } - setCursor(pos, isNotify = false) { - let method = isNotify ? "notify" : "request"; - return this[method](`${this.prefix}set_cursor`, [pos]); - } - get height() { - return this.request(`${this.prefix}get_height`, []); - } - setHeight(height, isNotify = false) { - let method = isNotify ? "notify" : "request"; - return this[method](`${this.prefix}set_height`, [height]); - } - get width() { - return this.request(`${this.prefix}get_width`, []); - } - setWidth(width, isNotify = false) { - let method = isNotify ? "notify" : "request"; - return this[method](`${this.prefix}set_height`, [width]); - } - get position() { - return this.request(`${this.prefix}get_position`, []); - } - get row() { - return this.request(`${this.prefix}get_position`, []).then((position) => position[0]); - } - get col() { - return this.request(`${this.prefix}get_position`, []).then((position) => position[1]); - } - get valid() { - return this.request(`${this.prefix}is_valid`, []); - } - get number() { - return this.request(`${this.prefix}get_number`, []); - } - setConfig(options, isNotify) { - let method = isNotify ? "notify" : "request"; - return this[method](`${this.prefix}set_config`, [options]); - } - getConfig() { - return this.request(`${this.prefix}get_config`, []); - } - close(force, isNotify) { - if (isNotify) { - this.notify(`${this.prefix}close`, [force]); - let count = 0; - let interval = setInterval(() => { - if (count == 5) - return timers_1.clearInterval(interval); - this.request(`${this.prefix}is_valid`, []).then((valid) => { - if (!valid) { - timers_1.clearInterval(interval); - } else { - this.notify(`${this.prefix}close`, [force]); - } - }, () => { - timers_1.clearInterval(interval); - }); - count++; - }, 50); - return null; - } - return this.request(`${this.prefix}close`, [force]); - } - highlightRanges(hlGroup, ranges, priority = 10, isNotify) { - if (isNotify) { - this.client.call("coc#highlight#match_ranges", [this.id, 0, ranges, hlGroup, priority], true); - return void 0; - } - return this.client.call("coc#highlight#match_ranges", [this.id, 0, ranges, hlGroup, priority]); - } - clearMatchGroup(hlGroup) { - this.client.call("coc#highlight#clear_match_group", [this.id, hlGroup], true); - } - clearMatches(ids) { - this.client.call("coc#highlight#clear_matches", [this.id, ids], true); - } - }; - exports2.Window = Window3; - } -}); - -// node_modules/@chemzqm/neovim/lib/api/Tabpage.js -var require_Tabpage = __commonJS({ - "node_modules/@chemzqm/neovim/lib/api/Tabpage.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Tabpage = void 0; - var Base_1 = require_Base(); - var Tabpage = class extends Base_1.BaseApi { - constructor() { - super(...arguments); - this.prefix = "nvim_tabpage_"; - } - get windows() { - return this.request(`${this.prefix}list_wins`, []); - } - get window() { - return this.request(`${this.prefix}get_win`, []); - } - get valid() { - return this.request(`${this.prefix}is_valid`, []); - } - get number() { - return this.request(`${this.prefix}get_number`, []); - } - getOption() { - throw new Error("Tabpage does not have `getOption`"); - } - setOption() { - throw new Error("Tabpage does not have `setOption`"); - } - }; - exports2.Tabpage = Tabpage; - } -}); - -// node_modules/@chemzqm/neovim/lib/api/types.js -var require_types = __commonJS({ - "node_modules/@chemzqm/neovim/lib/api/types.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Metadata = exports2.ExtType = void 0; - var Buffer_1 = require_Buffer(); - var Window_1 = require_Window(); - var Tabpage_1 = require_Tabpage(); - var ExtType; - (function(ExtType2) { - ExtType2[ExtType2["Buffer"] = 0] = "Buffer"; - ExtType2[ExtType2["Window"] = 1] = "Window"; - ExtType2[ExtType2["Tabpage"] = 2] = "Tabpage"; - })(ExtType = exports2.ExtType || (exports2.ExtType = {})); - exports2.Metadata = [ - { - constructor: Buffer_1.Buffer, - name: "Buffer", - prefix: "nvim_buf_" - }, - { - constructor: Window_1.Window, - name: "Window", - prefix: "nvim_win_" - }, - { - constructor: Tabpage_1.Tabpage, - name: "Tabpage", - prefix: "nvim_tabpage_" - } - ]; - } -}); - -// node_modules/@chemzqm/neovim/lib/utils/logger.js -var require_logger3 = __commonJS({ - "node_modules/@chemzqm/neovim/lib/utils/logger.js"(exports2) { - "use strict"; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createLogger = void 0; - var fs_1 = __importDefault(require("fs")); - var os_1 = __importDefault(require("os")); - var path_1 = __importDefault(require("path")); - function getLogFile() { - let file = process.env.NODE_CLIENT_LOG_FILE; - if (file) - return file; - let dir = process.env.XDG_RUNTIME_DIR; - if (dir) - return path_1.default.join(dir, "node-client.log"); - return path_1.default.join(os_1.default.tmpdir(), `node-client-${process.pid}.log`); - } - var LOG_FILE_PATH = getLogFile(); - var level = process.env.NODE_CLIENT_LOG_LEVEL || "info"; - var invalid = process.getuid && process.getuid() == 0; - if (!invalid) { - try { - fs_1.default.mkdirSync(path_1.default.dirname(LOG_FILE_PATH), { recursive: true }); - fs_1.default.writeFileSync(LOG_FILE_PATH, "", { encoding: "utf8", mode: 438 }); - } catch (_e) { - invalid = true; - } - } - function toObject(arg) { - if (arg == null) { - return arg; - } - if (Array.isArray(arg)) { - return arg.map((o) => toObject(o)); - } - if (typeof arg == "object" && typeof arg.prefix == "string" && typeof arg.data == "number") { - return "[" + arg.prefix + arg.data + "]"; - } - return arg; - } - function toString(arg) { - if (arg == null) - return String(arg); - if (typeof arg == "object") - return JSON.stringify(arg, null, 2); - return String(arg); - } - function toTimeString(d) { - return `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}.${d.getMilliseconds()}`; - } - var Logger2 = class { - constructor(name2) { - this.name = name2; - } - get stream() { - if (invalid) - return null; - if (this._stream) - return this._stream; - this._stream = fs_1.default.createWriteStream(LOG_FILE_PATH, { encoding: "utf8" }); - return this._stream; - } - getText(level2, data, meta) { - let more = ""; - if (meta.length) { - let arr = toObject(meta); - more = " " + arr.map((o) => toString(o)); - } - return `${toTimeString(new Date())} ${level2.toUpperCase()} [${this.name}] - ${data}${more} -`; - } - debug(data, ...meta) { - if (level != "debug" || this.stream == null) - return; - this.stream.write(this.getText("debug", data, meta)); - } - info(data, ...meta) { - if (this.stream == null) - return; - this.stream.write(this.getText("info", data, meta)); - } - error(data, ...meta) { - if (this.stream == null) - return; - this.stream.write(this.getText("error", data, meta)); - } - trace(data, ...meta) { - if (level != "trace" || this.stream == null) - return; - this.stream.write(this.getText("trace", data, meta)); - } - }; - function createLogger3(name2) { - return new Logger2(name2); - } - exports2.createLogger = createLogger3; - } -}); - -// node_modules/@chemzqm/neovim/lib/transport/base.js -var require_base = __commonJS({ - "node_modules/@chemzqm/neovim/lib/transport/base.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var events_1 = require("events"); - var logger_1 = require_logger3(); - var debug = process.env.NODE_CLIENT_LOG_LEVEL == "debug"; - var logger113 = logger_1.createLogger("transport"); - var Transport3 = class extends events_1.EventEmitter { - constructor(logger114) { - super(); - this.logger = logger114; - this.pauseLevel = 0; - this.paused = new Map(); - } - debug(key, ...meta) { - if (!debug) - return; - logger113.debug(key, ...meta); - } - info(key, ...meta) { - logger113.info(key, ...meta); - } - debugMessage(msg) { - if (!debug) - return; - const msgType = msg[0]; - if (msgType == 0) { - logger113.debug("receive request:", msg.slice(1)); - } else if (msgType == 1) { - } else if (msgType == 2) { - logger113.debug("receive notification:", msg.slice(1)); - } else { - logger113.debug("unknown message:", msg); - } - } - pauseNotification() { - this.pauseLevel = this.pauseLevel + 1; - this.paused.set(this.pauseLevel, []); - } - cancelNotification() { - let { pauseLevel } = this; - if (pauseLevel > 0) { - this.paused.delete(pauseLevel); - this.pauseLevel = pauseLevel - 1; - } - } - resumeNotification(isNotify = false) { - let { pauseLevel } = this; - if (pauseLevel == 0) - return isNotify ? null : Promise.resolve([null, null]); - let stack = Error().stack; - this.pauseLevel = pauseLevel - 1; - let list2 = this.paused.get(pauseLevel); - this.paused.delete(pauseLevel); - if (list2 && list2.length) { - return new Promise((resolve3, reject) => { - if (!isNotify) { - return this.request("nvim_call_atomic", [list2], (err, res) => { - if (err) { - let e = new Error(`call_atomic error: ${err[1]}`); - e.stack = stack; - return reject(e); - } - if (Array.isArray(res) && res[1] != null) { - let [index, errType, message] = res[1]; - let [fname, args] = list2[index]; - this.logger.error(`request error ${errType} on "${fname}"`, args, message, stack); - } - resolve3(res); - }); - } - this.notify("nvim_call_atomic", [list2]); - resolve3(); - }); - } - return isNotify ? null : Promise.resolve([[], void 0]); - } - }; - exports2.default = Transport3; - } -}); - -// node_modules/@chemzqm/neovim/lib/transport/nvim.js -var require_nvim = __commonJS({ - "node_modules/@chemzqm/neovim/lib/transport/nvim.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { - return m[k]; - } }); - } : function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; - o[k2] = m[k]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - } : function(o, v) { - o["default"] = v; - }); - var __importStar = exports2 && exports2.__importStar || function(mod) { - if (mod && mod.__esModule) - return mod; - var result = {}; - if (mod != null) { - for (var k in mod) - if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) - __createBinding(result, mod, k); - } - __setModuleDefault(result, mod); - return result; - }; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NvimTransport = void 0; - var msgpack = __importStar(require_msgpack_lite()); - var buffered_1 = __importDefault(require_buffered()); - var types_1 = require_types(); - var base_1 = __importDefault(require_base()); - var NvimTransport = class extends base_1.default { - constructor(logger113) { - super(logger113); - this.pending = new Map(); - this.nextRequestId = 1; - this.attached = false; - const codec = this.setupCodec(); - this.encodeStream = msgpack.createEncodeStream({ codec }); - this.decodeStream = msgpack.createDecodeStream({ codec }); - this.decodeStream.on("data", (msg) => { - this.parseMessage(msg); - }); - this.decodeStream.on("end", () => { - this.detach(); - this.emit("detach"); - }); - } - parseMessage(msg) { - const msgType = msg[0]; - this.debugMessage(msg); - if (msgType === 0) { - this.emit("request", msg[2].toString(), msg[3], this.createResponse(msg[1])); - } else if (msgType === 1) { - const id = msg[1]; - const handler = this.pending.get(id); - if (handler) { - this.pending.delete(id); - let err = msg[2]; - if (err && err.length != 2) { - err = [0, err instanceof Error ? err.message : err]; - } - handler(err, msg[3]); - } - } else if (msgType === 2) { - this.emit("notification", msg[1].toString(), msg[2]); - } else { - console.error(`Invalid message type ${msgType}`); - } - } - setupCodec() { - const codec = msgpack.createCodec(); - types_1.Metadata.forEach(({ constructor }, id) => { - codec.addExtPacker(id, constructor, (obj) => msgpack.encode(obj.data)); - codec.addExtUnpacker(id, (data) => new constructor({ - transport: this, - client: this.client, - data: msgpack.decode(data) - })); - }); - this.codec = codec; - return this.codec; - } - attach(writer, reader, client) { - this.encodeStream = this.encodeStream.pipe(writer); - const buffered = new buffered_1.default(); - reader.pipe(buffered).pipe(this.decodeStream); - this.writer = writer; - this.reader = reader; - this.client = client; - this.attached = true; - } - detach() { - if (!this.attached) - return; - this.attached = false; - this.encodeStream.unpipe(this.writer); - this.reader.unpipe(this.decodeStream); - } - request(method, args, cb) { - if (!this.attached) - return; - let id = this.nextRequestId; - this.nextRequestId = this.nextRequestId + 1; - let startTs = Date.now(); - this.debug("request to nvim:", id, method, args); - this.encodeStream.write(msgpack.encode([0, id, method, args], { - codec: this.codec - })); - let stack = Error().stack; - let timer = setTimeout(() => { - this.debug(`request to vim blocked more than 1s: ${method}`, args, stack); - }, 1e3); - this.pending.set(id, (err, res) => { - clearTimeout(timer); - this.debug("response of nvim:", id, `${Date.now() - startTs}ms`, res, err); - cb(err, res); - }); - } - notify(method, args) { - if (!this.attached) - return; - if (this.pauseLevel != 0) { - let arr = this.paused.get(this.pauseLevel); - if (arr) { - arr.push([method, args]); - return; - } - } - this.debug("nvim notification:", method, args); - this.encodeStream.write(msgpack.encode([2, method, args], { - codec: this.codec - })); - } - send(arr) { - this.encodeStream.write(msgpack.encode(arr, { - codec: this.codec - })); - } - createResponse(requestId) { - let { encodeStream } = this; - let startTs = Date.now(); - let called = false; - let timer = setTimeout(() => { - this.debug(`request to client cost more than 1s`, requestId); - }, 1e3); - return { - send: (resp, isError) => { - clearTimeout(timer); - if (called || !this.attached) - return; - this.debug("response of client:", requestId, `${Date.now() - startTs}ms`, resp, isError == true); - called = true; - encodeStream.write(msgpack.encode([ - 1, - requestId, - isError ? resp : null, - !isError ? resp : null - ])); - } - }; - } - }; - exports2.NvimTransport = NvimTransport; - } -}); - -// node_modules/@chemzqm/neovim/lib/transport/connection.js -var require_connection = __commonJS({ - "node_modules/@chemzqm/neovim/lib/transport/connection.js"(exports2) { - "use strict"; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - var events_1 = __importDefault(require("events")); - var readline_1 = __importDefault(require("readline")); - var logger_1 = require_logger3(); - var logger113 = logger_1.createLogger("connection"); - var Connection = class extends events_1.default { - constructor(readable, writeable) { - super(); - this.readable = readable; - this.writeable = writeable; - const rl = readline_1.default.createInterface(this.readable); - rl.on("line", (line) => { - this.parseData(line); - }); - rl.on("close", () => { - logger113.error("connection closed"); - process.exit(0); - }); - } - parseData(str) { - if (str.length == 0) - return; - let arr; - try { - arr = JSON.parse(str); - } catch (e) { - console.error(`Invalid data from vim: ${str}`); - return; - } - let [id, obj] = arr; - if (id > 0) { - logger113.debug("received request:", id, obj); - this.emit("request", id, obj); - } else if (id == 0) { - logger113.debug("received notification:", obj); - this.emit("notification", obj); - } else { - logger113.debug("received response:", id, obj); - this.emit("response", id, obj); - } - } - response(requestId, data) { - this.send([requestId, data || null]); - } - notify(event, data) { - this.send([0, [event, data || null]]); - } - send(arr) { - logger113.debug("send to vim:", arr); - try { - this.writeable.write(JSON.stringify(arr) + "\n"); - } catch (e) { - logger113.error("Send error:", arr); - } - } - redraw(force = false) { - this.send(["redraw", force ? "force" : ""]); - } - command(cmd) { - this.send(["ex", cmd]); - } - expr(expr) { - this.send(["expr", expr]); - } - call(func2, args, requestId) { - if (!requestId) { - this.send(["call", func2, args]); - return; - } - this.send(["call", func2, args, requestId]); - } - dispose() { - this.removeAllListeners(); - } - }; - exports2.default = Connection; - } -}); - -// node_modules/@chemzqm/neovim/lib/transport/request.js -var require_request = __commonJS({ - "node_modules/@chemzqm/neovim/lib/transport/request.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var logger_1 = require_logger3(); - var logger113 = logger_1.createLogger("request"); - var debug = process.env.NODE_CLIENT_LOG_LEVEL == "debug"; - var func2 = process.env.COC_NVIM == "1" ? "coc#api#call" : "nvim#api#call"; - var Request = class { - constructor(connection, cb, id) { - this.connection = connection; - this.cb = cb; - this.id = id; - } - request(method, args = []) { - this.method = method; - this.args = args; - this.connection.call(func2, [method.slice(5), args], this.id); - } - callback(client, err, result) { - let { method, cb } = this; - if (debug && err) { - logger113.debug(`request ${this.method} error:`, err, this.args); - } - if (err) - return cb([0, err.toString()]); - switch (method) { - case "nvim_list_wins": - case "nvim_tabpage_list_wins": - return cb(null, result.map((o) => client.createWindow(o))); - case "nvim_tabpage_get_win": - case "nvim_get_current_win": - case "nvim_open_win": - return cb(null, client.createWindow(result)); - case "nvim_list_bufs": - return cb(null, result.map((o) => client.createBuffer(o))); - case "nvim_win_get_buf": - case "nvim_create_buf": - case "nvim_get_current_buf": - return cb(null, client.createBuffer(result)); - case "nvim_list_tabpages": - return cb(null, result.map((o) => client.createTabpage(o))); - case "nvim_get_current_tabpage": - return cb(null, client.createTabpage(result)); - default: - return cb(null, result); - } - } - }; - exports2.default = Request; - } -}); - -// node_modules/@chemzqm/neovim/lib/transport/vim.js -var require_vim = __commonJS({ - "node_modules/@chemzqm/neovim/lib/transport/vim.js"(exports2) { - "use strict"; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.VimTransport = void 0; - var base_1 = __importDefault(require_base()); - var connection_1 = __importDefault(require_connection()); - var request_1 = __importDefault(require_request()); - var VimTransport = class extends base_1.default { - constructor(logger113) { - super(logger113); - this.pending = new Map(); - this.nextRequestId = -1; - this.attached = false; - this.errText = ""; - this.outText = ""; - this.notifyMethod = process.env.COC_NVIM == "1" ? "coc#api#notify" : "nvim#api#notify"; - } - attach(writer, reader, client) { - let connection = this.connection = new connection_1.default(reader, writer); - this.attached = true; - this.client = client; - connection.on("request", (id, obj) => { - let [method, args] = obj; - this.emit("request", method, args, this.createResponse(id)); - }); - connection.on("notification", (obj) => { - let [event, args] = obj; - this.emit("notification", event.toString(), args); - }); - connection.on("response", (id, obj) => { - let req = this.pending.get(id); - if (req) { - this.pending.delete(id); - let err = null; - let result = null; - if (!Array.isArray(obj)) { - err = obj; - } else { - err = obj[0]; - result = obj[1]; - } - req.callback(this.client, err, result); - } - }); - } - send(arr) { - this.connection.send(arr); - } - detach() { - if (!this.attached) - return; - this.attached = false; - this.connection.dispose(); - } - request(method, args, cb) { - if (!this.attached) - return cb([0, "transport disconnected"]); - let id = this.nextRequestId; - this.nextRequestId = this.nextRequestId - 1; - let startTs = Date.now(); - this.debug("request to vim:", id, method, args); - let timer = setTimeout(() => { - this.debug(`request to vim cost more than 1s`, method, args); - }, 1e3); - let req = new request_1.default(this.connection, (err, res) => { - clearTimeout(timer); - this.debug(`response from vim cost:`, id, `${Date.now() - startTs}ms`); - cb(err, res); - }, id); - this.pending.set(id, req); - req.request(method, args); - } - notify(method, args) { - if (!this.attached) - return; - if (this.pauseLevel != 0) { - let arr = this.paused.get(this.pauseLevel); - if (arr) { - arr.push([method, args]); - return; - } - } - let fname = method.slice(5); - if (fname == "err_write") { - this.errText = this.errText + args[0].toString(); - return; - } - if (fname == "out_write") { - let msg = args[0].toString() || ""; - if (!msg.includes("\n")) { - this.outText = this.outText + msg; - } else { - let text = this.outText + args[0].toString(); - this.outText = ""; - this.connection.call(this.notifyMethod, [fname, [text]]); - } - return; - } - if (fname == "err_writeln") { - let text = this.errText + args[0].toString(); - this.errText = ""; - this.connection.call(this.notifyMethod, [fname, [text]]); - return; - } - this.connection.call(this.notifyMethod, [fname, args]); - } - createResponse(requestId) { - let called = false; - let { connection } = this; - let startTs = Date.now(); - let timer = setTimeout(() => { - this.debug(`request to client cost more than 1s`, requestId); - }, 1e3); - return { - send: (resp, isError) => { - clearTimeout(timer); - if (called || !this.attached) - return; - called = true; - let err = null; - if (isError) - err = typeof resp === "string" ? resp : resp.toString(); - this.debug("response of client cost:", requestId, `${Date.now() - startTs}ms`); - connection.response(requestId, [err, isError ? null : resp]); - } - }; - } - }; - exports2.VimTransport = VimTransport; - } -}); - -// node_modules/@chemzqm/neovim/lib/api/Neovim.js -var require_Neovim = __commonJS({ - "node_modules/@chemzqm/neovim/lib/api/Neovim.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Neovim = void 0; - var Base_1 = require_Base(); - var Buffer_1 = require_Buffer(); - var Tabpage_1 = require_Tabpage(); - var Window_1 = require_Window(); - var isVim7 = process.env.VIM_NODE_RPC == "1"; - var Neovim2 = class extends Base_1.BaseApi { - constructor() { - super(...arguments); - this.prefix = "nvim_"; - this.Buffer = Buffer_1.Buffer; - this.Window = Window_1.Window; - this.Tabpage = Tabpage_1.Tabpage; - } - getArgs(args) { - if (!args) - return []; - if (Array.isArray(args)) - return args; - return [args]; - } - get apiInfo() { - return this.request(`${this.prefix}get_api_info`); - } - get buffers() { - return this.request(`${this.prefix}list_bufs`); - } - get buffer() { - return this.request(`${this.prefix}get_current_buf`); - } - async setBuffer(buffer) { - await this.request(`${this.prefix}set_current_buf`, [buffer]); - } - get chans() { - return this.request(`${this.prefix}list_chans`); - } - getChanInfo(chan) { - return this.request(`${this.prefix}get_chan_info`, [chan]); - } - createNamespace(name2 = "") { - return this.request(`${this.prefix}create_namespace`, [name2]); - } - get namespaces() { - return this.request(`${this.prefix}get_namespaces`, []); - } - get commands() { - return this.getCommands(); - } - getCommands(options = {}) { - return this.request(`${this.prefix}get_commands`, [options]); - } - get tabpages() { - return this.request(`${this.prefix}list_tabpages`); - } - get tabpage() { - return this.request(`${this.prefix}get_current_tabpage`); - } - async setTabpage(tabpage) { - await this.request(`${this.prefix}set_current_tabpage`, [tabpage]); - } - get windows() { - return this.getWindows(); - } - get window() { - return this.request(`${this.prefix}get_current_win`); - } - getWindows() { - return this.request(`${this.prefix}list_wins`); - } - async setWindow(win) { - await this.request(`${this.prefix}set_current_win`, [win]); - } - get runtimePaths() { - return this.request(`${this.prefix}list_runtime_paths`); - } - setDirectory(dir) { - return this.request(`${this.prefix}set_current_dir`, [dir]); - } - get line() { - return this.getLine(); - } - createNewBuffer(listed = false, scratch = false) { - return this.request(`${this.prefix}create_buf`, [listed, scratch]); - } - openFloatWindow(buffer, enter, options) { - return this.request(`${this.prefix}open_win`, [buffer, enter, options]); - } - getLine() { - return this.request(`${this.prefix}get_current_line`); - } - setLine(line) { - return this.request(`${this.prefix}set_current_line`, [line]); - } - getKeymap(mode) { - return this.request(`${this.prefix}get_keymap`, [mode]); - } - get mode() { - return this.request(`${this.prefix}get_mode`); - } - get colorMap() { - return this.request(`${this.prefix}get_color_map`); - } - getColorByName(name2) { - return this.request(`${this.prefix}get_color_by_name`, [name2]); - } - getHighlight(nameOrId, isRgb = true) { - const functionName = typeof nameOrId === "string" ? "by_name" : "by_id"; - return this.request(`${this.prefix}get_hl_${functionName}`, [ - nameOrId, - isRgb - ]); - } - getHighlightByName(name2, isRgb = true) { - return this.request(`${this.prefix}get_hl_by_name`, [name2, isRgb]); - } - getHighlightById(id, isRgb = true) { - return this.request(`${this.prefix}get_hl_by_id`, [id, isRgb]); - } - deleteCurrentLine() { - return this.request(`${this.prefix}del_current_line`); - } - eval(expr) { - return this.request(`${this.prefix}eval`, [expr]); - } - lua(code, args = []) { - const _args = this.getArgs(args); - return this.request(`${this.prefix}execute_lua`, [code, _args]); - } - executeLua(code, args = []) { - return this.lua(code, args); - } - callDictFunction(dict, fname, args = []) { - const _args = this.getArgs(args); - return this.request(`${this.prefix}call_dict_function`, [ - dict, - fname, - _args - ]); - } - call(fname, args = [], isNotify) { - const _args = this.getArgs(args); - if (isNotify) { - this.notify(`${this.prefix}call_function`, [fname, _args]); - return null; - } - return this.request(`${this.prefix}call_function`, [fname, _args]); - } - callTimer(fname, args = [], isNotify) { - const _args = this.getArgs(args); - if (isNotify) { - this.notify(`${this.prefix}call_function`, ["coc#util#timer", [fname, _args]]); - return null; - } - if (isVim7) { - this.notify(`${this.prefix}call_function`, ["coc#util#timer", [fname, _args]]); - return new Promise((resolve3) => { - setTimeout(() => { - resolve3(null); - }, 20); - }); - } - return this.request(`${this.prefix}call_function`, ["coc#util#timer", [fname, _args]]); - } - callAsync(fname, args = []) { - const _args = this.getArgs(args); - return this.client.sendAsyncRequest(fname, _args); - } - callFunction(fname, args = []) { - return this.call(fname, args); - } - callAtomic(calls) { - return this.request(`${this.prefix}call_atomic`, [calls]); - } - command(arg, isNotify) { - if (isNotify) { - this.notify(`${this.prefix}command`, [arg]); - return null; - } - return this.request(`${this.prefix}command`, [arg]); - } - commandOutput(arg) { - return this.request(`${this.prefix}command_output`, [arg]); - } - getVvar(name2) { - return this.request(`${this.prefix}get_vvar`, [name2]); - } - feedKeys(keys, mode, escapeCsi) { - return this.request(`${this.prefix}feedkeys`, [keys, mode, escapeCsi]); - } - input(keys) { - return this.request(`${this.prefix}input`, [keys]); - } - parseExpression(expr, flags, highlight) { - return this.request(`${this.prefix}parse_expression`, [ - expr, - flags, - highlight - ]); - } - getProc(pid) { - return this.request(`${this.prefix}get_proc`, [pid]); - } - getProcChildren(pid) { - return this.request(`${this.prefix}get_proc_children`, [pid]); - } - replaceTermcodes(str, fromPart, doIt, special) { - return this.request(`${this.prefix}replace_termcodes`, [ - str, - fromPart, - doIt, - special - ]); - } - strWidth(str) { - return this.request(`${this.prefix}strwidth`, [str]); - } - outWrite(str) { - this.notify(`${this.prefix}out_write`, [str]); - } - outWriteLine(str) { - this.outWrite(`${str} -`); - } - errWrite(str) { - this.notify(`${this.prefix}err_write`, [str]); - } - errWriteLine(str) { - this.notify(`${this.prefix}err_writeln`, [str]); - } - get uis() { - return this.request(`${this.prefix}list_uis`); - } - uiAttach(width, height, options) { - return this.request(`${this.prefix}ui_attach`, [width, height, options]); - } - uiDetach() { - return this.request(`${this.prefix}ui_detach`, []); - } - uiTryResize(width, height) { - return this.request(`${this.prefix}ui_try_resize`, [width, height]); - } - uiSetOption(name2, value) { - return this.request(`${this.prefix}ui_set_option`, [name2, value]); - } - subscribe(event) { - return this.request(`${this.prefix}subscribe`, [event]); - } - unsubscribe(event) { - return this.request(`${this.prefix}unsubscribe`, [event]); - } - setClientInfo(name2, version2, type, methods2, attributes) { - this.notify(`${this.prefix}set_client_info`, [ - name2, - version2, - type, - methods2, - attributes - ]); - } - async quit() { - this.command("qa!", true); - if (this.transport) { - this.transport.detach(); - } - } - }; - exports2.Neovim = Neovim2; - } -}); - -// node_modules/@chemzqm/neovim/lib/api/client.js -var require_client = __commonJS({ - "node_modules/@chemzqm/neovim/lib/api/client.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NeovimClient = exports2.AsyncResponse = void 0; - var nvim_1 = require_nvim(); - var vim_1 = require_vim(); - var Neovim_1 = require_Neovim(); - var Buffer_1 = require_Buffer(); - var Window_1 = require_Window(); - var Tabpage_1 = require_Tabpage(); - var logger_1 = require_logger3(); - var logger113 = logger_1.createLogger("client"); - var isVim7 = process.env.VIM_NODE_RPC == "1"; - var AsyncResponse = class { - constructor(requestId, cb) { - this.requestId = requestId; - this.cb = cb; - this.finished = false; - } - finish(err, res) { - if (this.finished) - return; - this.finished = true; - if (err) { - this.cb(new Error(err)); - return; - } - this.cb(null, res); - } - }; - exports2.AsyncResponse = AsyncResponse; - var NeovimClient2 = class extends Neovim_1.Neovim { - constructor(logger114) { - super({}); - this.logger = logger114; - this.requestId = 1; - this.responses = new Map(); - this.attachedBuffers = new Map(); - Object.defineProperty(this, "client", { - value: this - }); - let transport = isVim7 ? new vim_1.VimTransport(logger114) : new nvim_1.NvimTransport(logger114); - this.setTransport(transport); - this.transportAttached = false; - this.handleRequest = this.handleRequest.bind(this); - this.handleNotification = this.handleNotification.bind(this); - } - echoError(msg) { - let prefix = process.env.COC_NVIM == "1" ? "[coc.nvim] " : ""; - if (typeof msg === "string") { - this.errWriteLine(prefix + msg); - this.logError(msg, Error().stack); - } else { - this.errWriteLine(prefix + msg.message + " use :CocOpenLog for details"); - this.logError(msg.message || "Unknown error", msg.stack); - } - } - logError(msg, ...args) { - if (!this.logger) - return; - this.logger.error(msg, ...args); - } - createBuffer(id) { - return new Buffer_1.Buffer({ - transport: this.transport, - data: id, - client: this - }); - } - createWindow(id) { - return new Window_1.Window({ - transport: this.transport, - data: id, - client: this - }); - } - createTabpage(id) { - return new Tabpage_1.Tabpage({ - transport: this.transport, - data: id, - client: this - }); - } - send(arr) { - this.transport.send(arr); - } - redrawVim(force) { - if (!isVim7) - return; - this.transport.send(["redraw", force ? "force" : ""]); - } - attach({ reader, writer }, requestApi = true) { - this.transport.attach(writer, reader, this); - this.transportAttached = true; - this.setupTransport(requestApi); - } - detach() { - this.transport.detach(); - this.transportAttached = false; - } - get isApiReady() { - return this.transportAttached && typeof this._channelId !== "undefined"; - } - get channelId() { - return this._isReady.then(() => { - return this._channelId; - }); - } - isAttached(bufnr) { - return this.attachedBuffers.has(bufnr); - } - handleRequest(method, args, resp) { - this.emit("request", method, args, resp); - } - sendAsyncRequest(method, args) { - let id = this.requestId; - this.requestId = id + 1; - this.notify("nvim_call_function", ["coc#rpc#async_request", [id, method, args || []]]); - return new Promise((resolve3, reject) => { - let response = new AsyncResponse(id, (err, res) => { - if (err) - return reject(err); - resolve3(res); - }); - this.responses.set(id, response); - }); - } - emitNotification(method, args) { - if (method.endsWith("_event")) { - if (method.startsWith("nvim_buf_")) { - const shortName = method.replace(/nvim_buf_(.*)_event/, "$1"); - const { id } = args[0]; - if (!this.attachedBuffers.has(id)) - return; - const bufferMap = this.attachedBuffers.get(id); - const cbs = bufferMap.get(shortName) || []; - cbs.forEach((cb) => cb(...args)); - if (shortName === "detach") { - this.attachedBuffers.delete(id); - } - return; - } - if (method.startsWith("nvim_async_request")) { - const [id, method2, arr] = args; - this.handleRequest(method2, arr, { - send: (resp, isError) => { - this.notify("nvim_call_function", ["coc#rpc#async_response", [id, resp, isError]]); - } - }); - } - if (method.startsWith("nvim_async_response")) { - const [id, err, res] = args; - const response = this.responses.get(id); - if (!response) { - console.error(`Response not found for request ${id}`); - return; - } - this.responses.delete(id); - response.finish(err, res); - return; - } - } else { - this.emit("notification", method, args); - } - } - handleNotification(method, args) { - this.emitNotification(method, args); - } - setupTransport(requestApi = true) { - if (!this.transportAttached) { - throw new Error("Not attached to input/output"); - } - this.transport.on("request", this.handleRequest); - this.transport.on("notification", this.handleNotification); - this.transport.on("detach", () => { - this.emit("disconnect"); - this.transport.removeAllListeners("request"); - this.transport.removeAllListeners("notification"); - this.transport.removeAllListeners("detach"); - }); - if (requestApi) { - this._isReady = this.generateApi(); - } else { - this._channelId = 0; - this._isReady = Promise.resolve(true); - } - } - requestApi() { - return new Promise((resolve3, reject) => { - this.transport.request("nvim_get_api_info", [], (err, res) => { - if (err) { - reject(new Error(Array.isArray(err) ? err[1] : err.message || err.toString())); - } else { - resolve3(res); - } - }); - }); - } - async generateApi() { - let results; - try { - results = await this.requestApi(); - } catch (err) { - console.error("Could not get vim api results"); - logger113.error(err); - } - if (results) { - try { - const [channelId, metadata] = results; - this.functions = metadata.functions.map((f) => f.name); - this._channelId = channelId; - return true; - } catch (err) { - logger113.error(err.stack); - return null; - } - } - return null; - } - attachBufferEvent(buffer, eventName, cb) { - const bufferMap = this.attachedBuffers.get(buffer.id) || new Map(); - const cbs = bufferMap.get(eventName) || []; - if (cbs.includes(cb)) - return; - cbs.push(cb); - bufferMap.set(eventName, cbs); - this.attachedBuffers.set(buffer.id, bufferMap); - return; - } - detachBufferEvent(buffer, eventName, cb) { - const bufferMap = this.attachedBuffers.get(buffer.id); - if (!bufferMap || !bufferMap.has(eventName)) - return; - const handlers = bufferMap.get(eventName).filter((handler) => handler !== cb); - bufferMap.set(eventName, handlers); - } - pauseNotification() { - this.transport.pauseNotification(); - let stack = Error().stack; - process.nextTick(() => { - if (this.transport.pauseLevel > 0) { - this.logError(`resumeNotification not called within same tick:`, stack); - } - }); - } - resumeNotification(cancel, notify) { - if (cancel) - return Promise.resolve(this.transport.cancelNotification()); - if (notify) { - return Promise.resolve(this.transport.resumeNotification(true)); - } - return Promise.resolve(this.transport.resumeNotification()); - } - hasFunction(name2) { - if (!this.functions) - return true; - return this.functions.indexOf(name2) !== -1; - } - }; - exports2.NeovimClient = NeovimClient2; - } -}); - -// node_modules/@chemzqm/neovim/lib/attach/attach.js -var require_attach = __commonJS({ - "node_modules/@chemzqm/neovim/lib/attach/attach.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.attach = void 0; - var net_1 = require("net"); - var client_1 = require_client(); - function attach3({ reader: _reader, writer: _writer, proc, socket }, logger113 = null, requestApi = true) { - let writer; - let reader; - let neovim; - if (socket) { - const client = net_1.createConnection(socket); - writer = client; - reader = client; - client.once("close", () => { - neovim.detach(); - }); - } else if (_reader && _writer) { - writer = _writer; - reader = _reader; - } else if (proc) { - writer = proc.stdin; - reader = proc.stdout; - proc.once("disconnect", () => { - neovim.detach(); - }); - } - writer.on("error", (err) => { - if (err.code == "EPIPE") { - neovim.detach(); - } - }); - if (writer && reader) { - neovim = new client_1.NeovimClient(logger113); - neovim.attach({ - writer, - reader - }, requestApi); - return neovim; - } - throw new Error("Invalid arguments, could not attach"); - } - exports2.attach = attach3; - } -}); - -// node_modules/@chemzqm/neovim/lib/api/index.js -var require_api = __commonJS({ - "node_modules/@chemzqm/neovim/lib/api/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Tabpage = exports2.Window = exports2.Buffer = exports2.NeovimClient = exports2.Neovim = void 0; - var client_1 = require_client(); - Object.defineProperty(exports2, "Neovim", { enumerable: true, get: function() { - return client_1.NeovimClient; - } }); - var client_2 = require_client(); - Object.defineProperty(exports2, "NeovimClient", { enumerable: true, get: function() { - return client_2.NeovimClient; - } }); - var Buffer_1 = require_Buffer(); - Object.defineProperty(exports2, "Buffer", { enumerable: true, get: function() { - return Buffer_1.Buffer; - } }); - var Window_1 = require_Window(); - Object.defineProperty(exports2, "Window", { enumerable: true, get: function() { - return Window_1.Window; - } }); - var Tabpage_1 = require_Tabpage(); - Object.defineProperty(exports2, "Tabpage", { enumerable: true, get: function() { - return Tabpage_1.Tabpage; - } }); - } -}); - -// node_modules/@chemzqm/neovim/lib/index.js -var require_lib6 = __commonJS({ - "node_modules/@chemzqm/neovim/lib/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Window = exports2.Tabpage = exports2.Buffer = exports2.NeovimClient = exports2.Neovim = exports2.attach = void 0; - var attach_1 = require_attach(); - Object.defineProperty(exports2, "attach", { enumerable: true, get: function() { - return attach_1.attach; - } }); - var index_1 = require_api(); - Object.defineProperty(exports2, "Neovim", { enumerable: true, get: function() { - return index_1.Neovim; - } }); - Object.defineProperty(exports2, "NeovimClient", { enumerable: true, get: function() { - return index_1.NeovimClient; - } }); - Object.defineProperty(exports2, "Buffer", { enumerable: true, get: function() { - return index_1.Buffer; - } }); - Object.defineProperty(exports2, "Tabpage", { enumerable: true, get: function() { - return index_1.Tabpage; - } }); - Object.defineProperty(exports2, "Window", { enumerable: true, get: function() { - return index_1.Window; - } }); - } -}); - -// node_modules/vscode-jsonrpc/lib/common/ral.js -var require_ral = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/ral.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var _ral; - function RAL2() { - if (_ral === void 0) { - throw new Error(`No runtime abstraction layer installed`); - } - return _ral; - } - (function(RAL3) { - function install(ral) { - if (ral === void 0) { - throw new Error(`No runtime abstraction layer provided`); - } - _ral = ral; - } - RAL3.install = install; - })(RAL2 || (RAL2 = {})); - exports2.default = RAL2; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/disposable.js -var require_disposable = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/disposable.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Disposable = void 0; - var Disposable80; - (function(Disposable81) { - function create(func2) { - return { - dispose: func2 - }; - } - Disposable81.create = create; - })(Disposable80 = exports2.Disposable || (exports2.Disposable = {})); - } -}); - -// node_modules/vscode-jsonrpc/lib/common/messageBuffer.js -var require_messageBuffer = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/messageBuffer.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbstractMessageBuffer = void 0; - var CR = 13; - var LF = 10; - var CRLF = "\r\n"; - var AbstractMessageBuffer = class { - constructor(encoding = "utf-8") { - this._encoding = encoding; - this._chunks = []; - this._totalLength = 0; - } - get encoding() { - return this._encoding; - } - append(chunk) { - const toAppend = typeof chunk === "string" ? this.fromString(chunk, this._encoding) : chunk; - this._chunks.push(toAppend); - this._totalLength += toAppend.byteLength; - } - tryReadHeaders() { - if (this._chunks.length === 0) { - return void 0; - } - let state = 0; - let chunkIndex = 0; - let offset = 0; - let chunkBytesRead = 0; - row: - while (chunkIndex < this._chunks.length) { - const chunk = this._chunks[chunkIndex]; - offset = 0; - column: - while (offset < chunk.length) { - const value = chunk[offset]; - switch (value) { - case CR: - switch (state) { - case 0: - state = 1; - break; - case 2: - state = 3; - break; - default: - state = 0; - } - break; - case LF: - switch (state) { - case 1: - state = 2; - break; - case 3: - state = 4; - offset++; - break row; - default: - state = 0; - } - break; - default: - state = 0; - } - offset++; - } - chunkBytesRead += chunk.byteLength; - chunkIndex++; - } - if (state !== 4) { - return void 0; - } - const buffer = this._read(chunkBytesRead + offset); - const result = new Map(); - const headers = this.toString(buffer, "ascii").split(CRLF); - if (headers.length < 2) { - return result; - } - for (let i = 0; i < headers.length - 2; i++) { - const header = headers[i]; - const index = header.indexOf(":"); - if (index === -1) { - throw new Error("Message header must separate key and value using :"); - } - const key = header.substr(0, index); - const value = header.substr(index + 1).trim(); - result.set(key, value); - } - return result; - } - tryReadBody(length) { - if (this._totalLength < length) { - return void 0; - } - return this._read(length); - } - get numberOfBytes() { - return this._totalLength; - } - _read(byteCount) { - if (byteCount === 0) { - return this.emptyBuffer(); - } - if (byteCount > this._totalLength) { - throw new Error(`Cannot read so many bytes!`); - } - if (this._chunks[0].byteLength === byteCount) { - const chunk = this._chunks[0]; - this._chunks.shift(); - this._totalLength -= byteCount; - return this.asNative(chunk); - } - if (this._chunks[0].byteLength > byteCount) { - const chunk = this._chunks[0]; - const result2 = this.asNative(chunk, byteCount); - this._chunks[0] = chunk.slice(byteCount); - this._totalLength -= byteCount; - return result2; - } - const result = this.allocNative(byteCount); - let resultOffset = 0; - let chunkIndex = 0; - while (byteCount > 0) { - const chunk = this._chunks[chunkIndex]; - if (chunk.byteLength > byteCount) { - const chunkPart = chunk.slice(0, byteCount); - result.set(chunkPart, resultOffset); - resultOffset += byteCount; - this._chunks[chunkIndex] = chunk.slice(byteCount); - this._totalLength -= byteCount; - byteCount -= byteCount; - } else { - result.set(chunk, resultOffset); - resultOffset += chunk.byteLength; - this._chunks.shift(); - this._totalLength -= chunk.byteLength; - byteCount -= chunk.byteLength; - } - } - return result; - } - }; - exports2.AbstractMessageBuffer = AbstractMessageBuffer; - } -}); - -// node_modules/vscode-jsonrpc/lib/node/ril.js -var require_ril = __commonJS({ - "node_modules/vscode-jsonrpc/lib/node/ril.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var ral_1 = require_ral(); - var util_1 = require("util"); - var disposable_1 = require_disposable(); - var messageBuffer_1 = require_messageBuffer(); - var MessageBuffer = class extends messageBuffer_1.AbstractMessageBuffer { - constructor(encoding = "utf-8") { - super(encoding); - } - emptyBuffer() { - return MessageBuffer.emptyBuffer; - } - fromString(value, encoding) { - return Buffer.from(value, encoding); - } - toString(value, encoding) { - if (value instanceof Buffer) { - return value.toString(encoding); - } else { - return new util_1.TextDecoder(encoding).decode(value); - } - } - asNative(buffer, length) { - if (length === void 0) { - return buffer instanceof Buffer ? buffer : Buffer.from(buffer); - } else { - return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length); - } - } - allocNative(length) { - return Buffer.allocUnsafe(length); - } - }; - MessageBuffer.emptyBuffer = Buffer.allocUnsafe(0); - var ReadableStreamWrapper = class { - constructor(stream) { - this.stream = stream; - } - onClose(listener) { - this.stream.on("close", listener); - return disposable_1.Disposable.create(() => this.stream.off("close", listener)); - } - onError(listener) { - this.stream.on("error", listener); - return disposable_1.Disposable.create(() => this.stream.off("error", listener)); - } - onEnd(listener) { - this.stream.on("end", listener); - return disposable_1.Disposable.create(() => this.stream.off("end", listener)); - } - onData(listener) { - this.stream.on("data", listener); - return disposable_1.Disposable.create(() => this.stream.off("data", listener)); - } - }; - var WritableStreamWrapper = class { - constructor(stream) { - this.stream = stream; - } - onClose(listener) { - this.stream.on("close", listener); - return disposable_1.Disposable.create(() => this.stream.off("close", listener)); - } - onError(listener) { - this.stream.on("error", listener); - return disposable_1.Disposable.create(() => this.stream.off("error", listener)); - } - onEnd(listener) { - this.stream.on("end", listener); - return disposable_1.Disposable.create(() => this.stream.off("end", listener)); - } - write(data, encoding) { - return new Promise((resolve3, reject) => { - const callback = (error) => { - if (error === void 0 || error === null) { - resolve3(); - } else { - reject(error); - } - }; - if (typeof data === "string") { - this.stream.write(data, encoding, callback); - } else { - this.stream.write(data, callback); - } - }); - } - end() { - this.stream.end(); - } - }; - var _ril = Object.freeze({ - messageBuffer: Object.freeze({ - create: (encoding) => new MessageBuffer(encoding) - }), - applicationJson: Object.freeze({ - encoder: Object.freeze({ - name: "application/json", - encode: (msg, options) => { - try { - return Promise.resolve(Buffer.from(JSON.stringify(msg, void 0, 0), options.charset)); - } catch (err) { - return Promise.reject(err); - } - } - }), - decoder: Object.freeze({ - name: "application/json", - decode: (buffer, options) => { - try { - if (buffer instanceof Buffer) { - return Promise.resolve(JSON.parse(buffer.toString(options.charset))); - } else { - return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer))); - } - } catch (err) { - return Promise.reject(err); - } - } - }) - }), - stream: Object.freeze({ - asReadableStream: (stream) => new ReadableStreamWrapper(stream), - asWritableStream: (stream) => new WritableStreamWrapper(stream) - }), - console, - timer: Object.freeze({ - setTimeout(callback, ms, ...args) { - return setTimeout(callback, ms, ...args); - }, - clearTimeout(handle) { - clearTimeout(handle); - }, - setImmediate(callback, ...args) { - return setImmediate(callback, ...args); - }, - clearImmediate(handle) { - clearImmediate(handle); - } - }) - }); - function RIL() { - return _ril; - } - (function(RIL2) { - function install() { - ral_1.default.install(_ril); - } - RIL2.install = install; - })(RIL || (RIL = {})); - exports2.default = RIL; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/is.js -var require_is = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/is.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.stringArray = exports2.array = exports2.func = exports2.error = exports2.number = exports2.string = exports2.boolean = void 0; - function boolean2(value) { - return value === true || value === false; - } - exports2.boolean = boolean2; - function string2(value) { - return typeof value === "string" || value instanceof String; - } - exports2.string = string2; - function number2(value) { - return typeof value === "number" || value instanceof Number; - } - exports2.number = number2; - function error(value) { - return value instanceof Error; - } - exports2.error = error; - function func2(value) { - return typeof value === "function"; - } - exports2.func = func2; - function array(value) { - return Array.isArray(value); - } - exports2.array = array; - function stringArray(value) { - return array(value) && value.every((elem) => string2(elem)); - } - exports2.stringArray = stringArray; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/messages.js -var require_messages = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/messages.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isResponseMessage = exports2.isNotificationMessage = exports2.isRequestMessage = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType = exports2.RequestType0 = exports2.AbstractMessageSignature = exports2.ParameterStructures = exports2.ResponseError = exports2.ErrorCodes = void 0; - var is = require_is(); - var ErrorCodes; - (function(ErrorCodes2) { - ErrorCodes2.ParseError = -32700; - ErrorCodes2.InvalidRequest = -32600; - ErrorCodes2.MethodNotFound = -32601; - ErrorCodes2.InvalidParams = -32602; - ErrorCodes2.InternalError = -32603; - ErrorCodes2.jsonrpcReservedErrorRangeStart = -32099; - ErrorCodes2.serverErrorStart = ErrorCodes2.jsonrpcReservedErrorRangeStart; - ErrorCodes2.MessageWriteError = -32099; - ErrorCodes2.MessageReadError = -32098; - ErrorCodes2.ServerNotInitialized = -32002; - ErrorCodes2.UnknownErrorCode = -32001; - ErrorCodes2.jsonrpcReservedErrorRangeEnd = -32e3; - ErrorCodes2.serverErrorEnd = ErrorCodes2.jsonrpcReservedErrorRangeEnd; - })(ErrorCodes = exports2.ErrorCodes || (exports2.ErrorCodes = {})); - var ResponseError2 = class extends Error { - constructor(code, message, data) { - super(message); - this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode; - this.data = data; - Object.setPrototypeOf(this, ResponseError2.prototype); - } - toJson() { - return { - code: this.code, - message: this.message, - data: this.data - }; - } - }; - exports2.ResponseError = ResponseError2; - var ParameterStructures = class { - constructor(kind) { - this.kind = kind; - } - static is(value) { - return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition; - } - toString() { - return this.kind; - } - }; - exports2.ParameterStructures = ParameterStructures; - ParameterStructures.auto = new ParameterStructures("auto"); - ParameterStructures.byPosition = new ParameterStructures("byPosition"); - ParameterStructures.byName = new ParameterStructures("byName"); - var AbstractMessageSignature = class { - constructor(method, numberOfParams) { - this.method = method; - this.numberOfParams = numberOfParams; - } - get parameterStructures() { - return ParameterStructures.auto; - } - }; - exports2.AbstractMessageSignature = AbstractMessageSignature; - var RequestType03 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 0); - } - }; - exports2.RequestType0 = RequestType03; - var RequestType3 = class extends AbstractMessageSignature { - constructor(method, _parameterStructures = ParameterStructures.auto) { - super(method, 1); - this._parameterStructures = _parameterStructures; - } - get parameterStructures() { - return this._parameterStructures; - } - }; - exports2.RequestType = RequestType3; - var RequestType1 = class extends AbstractMessageSignature { - constructor(method, _parameterStructures = ParameterStructures.auto) { - super(method, 1); - this._parameterStructures = _parameterStructures; - } - get parameterStructures() { - return this._parameterStructures; - } - }; - exports2.RequestType1 = RequestType1; - var RequestType22 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 2); - } - }; - exports2.RequestType2 = RequestType22; - var RequestType32 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 3); - } - }; - exports2.RequestType3 = RequestType32; - var RequestType4 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 4); - } - }; - exports2.RequestType4 = RequestType4; - var RequestType5 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 5); - } - }; - exports2.RequestType5 = RequestType5; - var RequestType6 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 6); - } - }; - exports2.RequestType6 = RequestType6; - var RequestType7 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 7); - } - }; - exports2.RequestType7 = RequestType7; - var RequestType8 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 8); - } - }; - exports2.RequestType8 = RequestType8; - var RequestType9 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 9); - } - }; - exports2.RequestType9 = RequestType9; - var NotificationType3 = class extends AbstractMessageSignature { - constructor(method, _parameterStructures = ParameterStructures.auto) { - super(method, 1); - this._parameterStructures = _parameterStructures; - } - get parameterStructures() { - return this._parameterStructures; - } - }; - exports2.NotificationType = NotificationType3; - var NotificationType03 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 0); - } - }; - exports2.NotificationType0 = NotificationType03; - var NotificationType1 = class extends AbstractMessageSignature { - constructor(method, _parameterStructures = ParameterStructures.auto) { - super(method, 1); - this._parameterStructures = _parameterStructures; - } - get parameterStructures() { - return this._parameterStructures; - } - }; - exports2.NotificationType1 = NotificationType1; - var NotificationType22 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 2); - } - }; - exports2.NotificationType2 = NotificationType22; - var NotificationType32 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 3); - } - }; - exports2.NotificationType3 = NotificationType32; - var NotificationType4 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 4); - } - }; - exports2.NotificationType4 = NotificationType4; - var NotificationType5 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 5); - } - }; - exports2.NotificationType5 = NotificationType5; - var NotificationType6 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 6); - } - }; - exports2.NotificationType6 = NotificationType6; - var NotificationType7 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 7); - } - }; - exports2.NotificationType7 = NotificationType7; - var NotificationType8 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 8); - } - }; - exports2.NotificationType8 = NotificationType8; - var NotificationType9 = class extends AbstractMessageSignature { - constructor(method) { - super(method, 9); - } - }; - exports2.NotificationType9 = NotificationType9; - function isRequestMessage(message) { - const candidate = message; - return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id)); - } - exports2.isRequestMessage = isRequestMessage; - function isNotificationMessage(message) { - const candidate = message; - return candidate && is.string(candidate.method) && message.id === void 0; - } - exports2.isNotificationMessage = isNotificationMessage; - function isResponseMessage(message) { - const candidate = message; - return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null); - } - exports2.isResponseMessage = isResponseMessage; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/events.js -var require_events = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/events.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Emitter = exports2.Event = void 0; - var ral_1 = require_ral(); - var Event27; - (function(Event28) { - const _disposable = { dispose() { - } }; - Event28.None = function() { - return _disposable; - }; - })(Event27 = exports2.Event || (exports2.Event = {})); - var CallbackList = class { - add(callback, context = null, bucket) { - if (!this._callbacks) { - this._callbacks = []; - this._contexts = []; - } - this._callbacks.push(callback); - this._contexts.push(context); - if (Array.isArray(bucket)) { - bucket.push({ dispose: () => this.remove(callback, context) }); - } - } - remove(callback, context = null) { - if (!this._callbacks) { - return; - } - let foundCallbackWithDifferentContext = false; - for (let i = 0, len = this._callbacks.length; i < len; i++) { - if (this._callbacks[i] === callback) { - if (this._contexts[i] === context) { - this._callbacks.splice(i, 1); - this._contexts.splice(i, 1); - return; - } else { - foundCallbackWithDifferentContext = true; - } - } - } - if (foundCallbackWithDifferentContext) { - throw new Error("When adding a listener with a context, you should remove it with the same context"); - } - } - invoke(...args) { - if (!this._callbacks) { - return []; - } - const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0); - for (let i = 0, len = callbacks.length; i < len; i++) { - try { - ret.push(callbacks[i].apply(contexts[i], args)); - } catch (e) { - ral_1.default().console.error(e); - } - } - return ret; - } - isEmpty() { - return !this._callbacks || this._callbacks.length === 0; - } - dispose() { - this._callbacks = void 0; - this._contexts = void 0; - } - }; - var Emitter28 = class { - constructor(_options) { - this._options = _options; - } - get event() { - if (!this._event) { - this._event = (listener, thisArgs, disposables) => { - if (!this._callbacks) { - this._callbacks = new CallbackList(); - } - if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) { - this._options.onFirstListenerAdd(this); - } - this._callbacks.add(listener, thisArgs); - const result = { - dispose: () => { - if (!this._callbacks) { - return; - } - this._callbacks.remove(listener, thisArgs); - result.dispose = Emitter28._noop; - if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) { - this._options.onLastListenerRemove(this); - } - } - }; - if (Array.isArray(disposables)) { - disposables.push(result); - } - return result; - }; - } - return this._event; - } - fire(event) { - if (this._callbacks) { - this._callbacks.invoke.call(this._callbacks, event); - } - } - dispose() { - if (this._callbacks) { - this._callbacks.dispose(); - this._callbacks = void 0; - } - } - }; - exports2.Emitter = Emitter28; - Emitter28._noop = function() { - }; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/cancellation.js -var require_cancellation = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/cancellation.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CancellationTokenSource = exports2.CancellationToken = void 0; - var ral_1 = require_ral(); - var Is7 = require_is(); - var events_1 = require_events(); - var CancellationToken53; - (function(CancellationToken54) { - CancellationToken54.None = Object.freeze({ - isCancellationRequested: false, - onCancellationRequested: events_1.Event.None - }); - CancellationToken54.Cancelled = Object.freeze({ - isCancellationRequested: true, - onCancellationRequested: events_1.Event.None - }); - function is(value) { - const candidate = value; - return candidate && (candidate === CancellationToken54.None || candidate === CancellationToken54.Cancelled || Is7.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested); - } - CancellationToken54.is = is; - })(CancellationToken53 = exports2.CancellationToken || (exports2.CancellationToken = {})); - var shortcutEvent = Object.freeze(function(callback, context) { - const handle = ral_1.default().timer.setTimeout(callback.bind(context), 0); - return { dispose() { - ral_1.default().timer.clearTimeout(handle); - } }; - }); - var MutableToken = class { - constructor() { - this._isCancelled = false; - } - cancel() { - if (!this._isCancelled) { - this._isCancelled = true; - if (this._emitter) { - this._emitter.fire(void 0); - this.dispose(); - } - } - } - get isCancellationRequested() { - return this._isCancelled; - } - get onCancellationRequested() { - if (this._isCancelled) { - return shortcutEvent; - } - if (!this._emitter) { - this._emitter = new events_1.Emitter(); - } - return this._emitter.event; - } - dispose() { - if (this._emitter) { - this._emitter.dispose(); - this._emitter = void 0; - } - } - }; - var CancellationTokenSource26 = class { - get token() { - if (!this._token) { - this._token = new MutableToken(); - } - return this._token; - } - cancel() { - if (!this._token) { - this._token = CancellationToken53.Cancelled; - } else { - this._token.cancel(); - } - } - dispose() { - if (!this._token) { - this._token = CancellationToken53.None; - } else if (this._token instanceof MutableToken) { - this._token.dispose(); - } - } - }; - exports2.CancellationTokenSource = CancellationTokenSource26; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/messageReader.js -var require_messageReader = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/messageReader.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = void 0; - var ral_1 = require_ral(); - var Is7 = require_is(); - var events_1 = require_events(); - var MessageReader2; - (function(MessageReader3) { - function is(value) { - let candidate = value; - return candidate && Is7.func(candidate.listen) && Is7.func(candidate.dispose) && Is7.func(candidate.onError) && Is7.func(candidate.onClose) && Is7.func(candidate.onPartialMessage); - } - MessageReader3.is = is; - })(MessageReader2 = exports2.MessageReader || (exports2.MessageReader = {})); - var AbstractMessageReader = class { - constructor() { - this.errorEmitter = new events_1.Emitter(); - this.closeEmitter = new events_1.Emitter(); - this.partialMessageEmitter = new events_1.Emitter(); - } - dispose() { - this.errorEmitter.dispose(); - this.closeEmitter.dispose(); - } - get onError() { - return this.errorEmitter.event; - } - fireError(error) { - this.errorEmitter.fire(this.asError(error)); - } - get onClose() { - return this.closeEmitter.event; - } - fireClose() { - this.closeEmitter.fire(void 0); - } - get onPartialMessage() { - return this.partialMessageEmitter.event; - } - firePartialMessage(info) { - this.partialMessageEmitter.fire(info); - } - asError(error) { - if (error instanceof Error) { - return error; - } else { - return new Error(`Reader received error. Reason: ${Is7.string(error.message) ? error.message : "unknown"}`); - } - } - }; - exports2.AbstractMessageReader = AbstractMessageReader; - var ResolvedMessageReaderOptions; - (function(ResolvedMessageReaderOptions2) { - function fromOptions(options) { - var _a2; - let charset; - let result; - let contentDecoder; - const contentDecoders = new Map(); - let contentTypeDecoder; - const contentTypeDecoders = new Map(); - if (options === void 0 || typeof options === "string") { - charset = options !== null && options !== void 0 ? options : "utf-8"; - } else { - charset = (_a2 = options.charset) !== null && _a2 !== void 0 ? _a2 : "utf-8"; - if (options.contentDecoder !== void 0) { - contentDecoder = options.contentDecoder; - contentDecoders.set(contentDecoder.name, contentDecoder); - } - if (options.contentDecoders !== void 0) { - for (const decoder of options.contentDecoders) { - contentDecoders.set(decoder.name, decoder); - } - } - if (options.contentTypeDecoder !== void 0) { - contentTypeDecoder = options.contentTypeDecoder; - contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder); - } - if (options.contentTypeDecoders !== void 0) { - for (const decoder of options.contentTypeDecoders) { - contentTypeDecoders.set(decoder.name, decoder); - } - } - } - if (contentTypeDecoder === void 0) { - contentTypeDecoder = ral_1.default().applicationJson.decoder; - contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder); - } - return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders }; - } - ResolvedMessageReaderOptions2.fromOptions = fromOptions; - })(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {})); - var ReadableStreamMessageReader = class extends AbstractMessageReader { - constructor(readable, options) { - super(); - this.readable = readable; - this.options = ResolvedMessageReaderOptions.fromOptions(options); - this.buffer = ral_1.default().messageBuffer.create(this.options.charset); - this._partialMessageTimeout = 1e4; - this.nextMessageLength = -1; - this.messageToken = 0; - } - set partialMessageTimeout(timeout) { - this._partialMessageTimeout = timeout; - } - get partialMessageTimeout() { - return this._partialMessageTimeout; - } - listen(callback) { - this.nextMessageLength = -1; - this.messageToken = 0; - this.partialMessageTimer = void 0; - this.callback = callback; - const result = this.readable.onData((data) => { - this.onData(data); - }); - this.readable.onError((error) => this.fireError(error)); - this.readable.onClose(() => this.fireClose()); - return result; - } - onData(data) { - this.buffer.append(data); - while (true) { - if (this.nextMessageLength === -1) { - const headers = this.buffer.tryReadHeaders(); - if (!headers) { - return; - } - const contentLength = headers.get("Content-Length"); - if (!contentLength) { - throw new Error("Header must provide a Content-Length property."); - } - const length = parseInt(contentLength); - if (isNaN(length)) { - throw new Error("Content-Length value must be a number."); - } - this.nextMessageLength = length; - } - const body = this.buffer.tryReadBody(this.nextMessageLength); - if (body === void 0) { - this.setPartialMessageTimer(); - return; - } - this.clearPartialMessageTimer(); - this.nextMessageLength = -1; - let p; - if (this.options.contentDecoder !== void 0) { - p = this.options.contentDecoder.decode(body); - } else { - p = Promise.resolve(body); - } - p.then((value) => { - this.options.contentTypeDecoder.decode(value, this.options).then((msg) => { - this.callback(msg); - }, (error) => { - this.fireError(error); - }); - }, (error) => { - this.fireError(error); - }); - } - } - clearPartialMessageTimer() { - if (this.partialMessageTimer) { - ral_1.default().timer.clearTimeout(this.partialMessageTimer); - this.partialMessageTimer = void 0; - } - } - setPartialMessageTimer() { - this.clearPartialMessageTimer(); - if (this._partialMessageTimeout <= 0) { - return; - } - this.partialMessageTimer = ral_1.default().timer.setTimeout((token, timeout) => { - this.partialMessageTimer = void 0; - if (token === this.messageToken) { - this.firePartialMessage({ messageToken: token, waitingTime: timeout }); - this.setPartialMessageTimer(); - } - }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout); - } - }; - exports2.ReadableStreamMessageReader = ReadableStreamMessageReader; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/semaphore.js -var require_semaphore = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/semaphore.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Semaphore = void 0; - var ral_1 = require_ral(); - var Semaphore = class { - constructor(capacity = 1) { - if (capacity <= 0) { - throw new Error("Capacity must be greater than 0"); - } - this._capacity = capacity; - this._active = 0; - this._waiting = []; - } - lock(thunk) { - return new Promise((resolve3, reject) => { - this._waiting.push({ thunk, resolve: resolve3, reject }); - this.runNext(); - }); - } - get active() { - return this._active; - } - runNext() { - if (this._waiting.length === 0 || this._active === this._capacity) { - return; - } - ral_1.default().timer.setImmediate(() => this.doRunNext()); - } - doRunNext() { - if (this._waiting.length === 0 || this._active === this._capacity) { - return; - } - const next = this._waiting.shift(); - this._active++; - if (this._active > this._capacity) { - throw new Error(`To many thunks active`); - } - try { - const result = next.thunk(); - if (result instanceof Promise) { - result.then((value) => { - this._active--; - next.resolve(value); - this.runNext(); - }, (err) => { - this._active--; - next.reject(err); - this.runNext(); - }); - } else { - this._active--; - next.resolve(result); - this.runNext(); - } - } catch (err) { - this._active--; - next.reject(err); - this.runNext(); - } - } - }; - exports2.Semaphore = Semaphore; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/messageWriter.js -var require_messageWriter = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/messageWriter.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = void 0; - var ral_1 = require_ral(); - var Is7 = require_is(); - var semaphore_1 = require_semaphore(); - var events_1 = require_events(); - var ContentLength = "Content-Length: "; - var CRLF = "\r\n"; - var MessageWriter2; - (function(MessageWriter3) { - function is(value) { - let candidate = value; - return candidate && Is7.func(candidate.dispose) && Is7.func(candidate.onClose) && Is7.func(candidate.onError) && Is7.func(candidate.write); - } - MessageWriter3.is = is; - })(MessageWriter2 = exports2.MessageWriter || (exports2.MessageWriter = {})); - var AbstractMessageWriter = class { - constructor() { - this.errorEmitter = new events_1.Emitter(); - this.closeEmitter = new events_1.Emitter(); - } - dispose() { - this.errorEmitter.dispose(); - this.closeEmitter.dispose(); - } - get onError() { - return this.errorEmitter.event; - } - fireError(error, message, count) { - this.errorEmitter.fire([this.asError(error), message, count]); - } - get onClose() { - return this.closeEmitter.event; - } - fireClose() { - this.closeEmitter.fire(void 0); - } - asError(error) { - if (error instanceof Error) { - return error; - } else { - return new Error(`Writer received error. Reason: ${Is7.string(error.message) ? error.message : "unknown"}`); - } - } - }; - exports2.AbstractMessageWriter = AbstractMessageWriter; - var ResolvedMessageWriterOptions; - (function(ResolvedMessageWriterOptions2) { - function fromOptions(options) { - var _a2, _b; - if (options === void 0 || typeof options === "string") { - return { charset: options !== null && options !== void 0 ? options : "utf-8", contentTypeEncoder: ral_1.default().applicationJson.encoder }; - } else { - return { charset: (_a2 = options.charset) !== null && _a2 !== void 0 ? _a2 : "utf-8", contentEncoder: options.contentEncoder, contentTypeEncoder: (_b = options.contentTypeEncoder) !== null && _b !== void 0 ? _b : ral_1.default().applicationJson.encoder }; - } - } - ResolvedMessageWriterOptions2.fromOptions = fromOptions; - })(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {})); - var WriteableStreamMessageWriter = class extends AbstractMessageWriter { - constructor(writable, options) { - super(); - this.writable = writable; - this.options = ResolvedMessageWriterOptions.fromOptions(options); - this.errorCount = 0; - this.writeSemaphore = new semaphore_1.Semaphore(1); - this.writable.onError((error) => this.fireError(error)); - this.writable.onClose(() => this.fireClose()); - } - async write(msg) { - return this.writeSemaphore.lock(async () => { - const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => { - if (this.options.contentEncoder !== void 0) { - return this.options.contentEncoder.encode(buffer); - } else { - return buffer; - } - }); - return payload.then((buffer) => { - const headers = []; - headers.push(ContentLength, buffer.byteLength.toString(), CRLF); - headers.push(CRLF); - return this.doWrite(msg, headers, buffer); - }, (error) => { - this.fireError(error); - throw error; - }); - }); - } - async doWrite(msg, headers, data) { - try { - await this.writable.write(headers.join(""), "ascii"); - return this.writable.write(data); - } catch (error) { - this.handleError(error, msg); - return Promise.reject(error); - } - } - handleError(error, msg) { - this.errorCount++; - this.fireError(error, msg, this.errorCount); - } - end() { - this.writable.end(); - } - }; - exports2.WriteableStreamMessageWriter = WriteableStreamMessageWriter; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/linkedMap.js -var require_linkedMap = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/linkedMap.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.LRUCache = exports2.LinkedMap = exports2.Touch = void 0; - var Touch; - (function(Touch2) { - Touch2.None = 0; - Touch2.First = 1; - Touch2.AsOld = Touch2.First; - Touch2.Last = 2; - Touch2.AsNew = Touch2.Last; - })(Touch = exports2.Touch || (exports2.Touch = {})); - var LinkedMap = class { - constructor() { - this[Symbol.toStringTag] = "LinkedMap"; - this._map = new Map(); - this._head = void 0; - this._tail = void 0; - this._size = 0; - this._state = 0; - } - clear() { - this._map.clear(); - this._head = void 0; - this._tail = void 0; - this._size = 0; - this._state++; - } - isEmpty() { - return !this._head && !this._tail; - } - get size() { - return this._size; - } - get first() { - var _a2; - return (_a2 = this._head) === null || _a2 === void 0 ? void 0 : _a2.value; - } - get last() { - var _a2; - return (_a2 = this._tail) === null || _a2 === void 0 ? void 0 : _a2.value; - } - has(key) { - return this._map.has(key); - } - get(key, touch = Touch.None) { - const item = this._map.get(key); - if (!item) { - return void 0; - } - if (touch !== Touch.None) { - this.touch(item, touch); - } - return item.value; - } - set(key, value, touch = Touch.None) { - let item = this._map.get(key); - if (item) { - item.value = value; - if (touch !== Touch.None) { - this.touch(item, touch); - } - } else { - item = { key, value, next: void 0, previous: void 0 }; - switch (touch) { - case Touch.None: - this.addItemLast(item); - break; - case Touch.First: - this.addItemFirst(item); - break; - case Touch.Last: - this.addItemLast(item); - break; - default: - this.addItemLast(item); - break; - } - this._map.set(key, item); - this._size++; - } - return this; - } - delete(key) { - return !!this.remove(key); - } - remove(key) { - const item = this._map.get(key); - if (!item) { - return void 0; - } - this._map.delete(key); - this.removeItem(item); - this._size--; - return item.value; - } - shift() { - if (!this._head && !this._tail) { - return void 0; - } - if (!this._head || !this._tail) { - throw new Error("Invalid list"); - } - const item = this._head; - this._map.delete(item.key); - this.removeItem(item); - this._size--; - return item.value; - } - forEach(callbackfn, thisArg) { - const state = this._state; - let current = this._head; - while (current) { - if (thisArg) { - callbackfn.bind(thisArg)(current.value, current.key, this); - } else { - callbackfn(current.value, current.key, this); - } - if (this._state !== state) { - throw new Error(`LinkedMap got modified during iteration.`); - } - current = current.next; - } - } - keys() { - const map = this; - const state = this._state; - let current = this._head; - const iterator = { - [Symbol.iterator]() { - return iterator; - }, - next() { - if (map._state !== state) { - throw new Error(`LinkedMap got modified during iteration.`); - } - if (current) { - const result = { value: current.key, done: false }; - current = current.next; - return result; - } else { - return { value: void 0, done: true }; - } - } - }; - return iterator; - } - values() { - const map = this; - const state = this._state; - let current = this._head; - const iterator = { - [Symbol.iterator]() { - return iterator; - }, - next() { - if (map._state !== state) { - throw new Error(`LinkedMap got modified during iteration.`); - } - if (current) { - const result = { value: current.value, done: false }; - current = current.next; - return result; - } else { - return { value: void 0, done: true }; - } - } - }; - return iterator; - } - entries() { - const map = this; - const state = this._state; - let current = this._head; - const iterator = { - [Symbol.iterator]() { - return iterator; - }, - next() { - if (map._state !== state) { - throw new Error(`LinkedMap got modified during iteration.`); - } - if (current) { - const result = { value: [current.key, current.value], done: false }; - current = current.next; - return result; - } else { - return { value: void 0, done: true }; - } - } - }; - return iterator; - } - [Symbol.iterator]() { - return this.entries(); - } - trimOld(newSize) { - if (newSize >= this.size) { - return; - } - if (newSize === 0) { - this.clear(); - return; - } - let current = this._head; - let currentSize = this.size; - while (current && currentSize > newSize) { - this._map.delete(current.key); - current = current.next; - currentSize--; - } - this._head = current; - this._size = currentSize; - if (current) { - current.previous = void 0; - } - this._state++; - } - addItemFirst(item) { - if (!this._head && !this._tail) { - this._tail = item; - } else if (!this._head) { - throw new Error("Invalid list"); - } else { - item.next = this._head; - this._head.previous = item; - } - this._head = item; - this._state++; - } - addItemLast(item) { - if (!this._head && !this._tail) { - this._head = item; - } else if (!this._tail) { - throw new Error("Invalid list"); - } else { - item.previous = this._tail; - this._tail.next = item; - } - this._tail = item; - this._state++; - } - removeItem(item) { - if (item === this._head && item === this._tail) { - this._head = void 0; - this._tail = void 0; - } else if (item === this._head) { - if (!item.next) { - throw new Error("Invalid list"); - } - item.next.previous = void 0; - this._head = item.next; - } else if (item === this._tail) { - if (!item.previous) { - throw new Error("Invalid list"); - } - item.previous.next = void 0; - this._tail = item.previous; - } else { - const next = item.next; - const previous = item.previous; - if (!next || !previous) { - throw new Error("Invalid list"); - } - next.previous = previous; - previous.next = next; - } - item.next = void 0; - item.previous = void 0; - this._state++; - } - touch(item, touch) { - if (!this._head || !this._tail) { - throw new Error("Invalid list"); - } - if (touch !== Touch.First && touch !== Touch.Last) { - return; - } - if (touch === Touch.First) { - if (item === this._head) { - return; - } - const next = item.next; - const previous = item.previous; - if (item === this._tail) { - previous.next = void 0; - this._tail = previous; - } else { - next.previous = previous; - previous.next = next; - } - item.previous = void 0; - item.next = this._head; - this._head.previous = item; - this._head = item; - this._state++; - } else if (touch === Touch.Last) { - if (item === this._tail) { - return; - } - const next = item.next; - const previous = item.previous; - if (item === this._head) { - next.previous = void 0; - this._head = next; - } else { - next.previous = previous; - previous.next = next; - } - item.next = void 0; - item.previous = this._tail; - this._tail.next = item; - this._tail = item; - this._state++; - } - } - toJSON() { - const data = []; - this.forEach((value, key) => { - data.push([key, value]); - }); - return data; - } - fromJSON(data) { - this.clear(); - for (const [key, value] of data) { - this.set(key, value); - } - } - }; - exports2.LinkedMap = LinkedMap; - var LRUCache = class extends LinkedMap { - constructor(limit, ratio = 1) { - super(); - this._limit = limit; - this._ratio = Math.min(Math.max(0, ratio), 1); - } - get limit() { - return this._limit; - } - set limit(limit) { - this._limit = limit; - this.checkTrim(); - } - get ratio() { - return this._ratio; - } - set ratio(ratio) { - this._ratio = Math.min(Math.max(0, ratio), 1); - this.checkTrim(); - } - get(key, touch = Touch.AsNew) { - return super.get(key, touch); - } - peek(key) { - return super.get(key, Touch.None); - } - set(key, value) { - super.set(key, value, Touch.Last); - this.checkTrim(); - return this; - } - checkTrim() { - if (this.size > this._limit) { - this.trimOld(Math.round(this._limit * this._ratio)); - } - } - }; - exports2.LRUCache = LRUCache; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/connection.js -var require_connection2 = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/connection.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createMessageConnection = exports2.ConnectionOptions = exports2.CancellationStrategy = exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.ConnectionStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.Trace = exports2.NullLogger = exports2.ProgressType = void 0; - var ral_1 = require_ral(); - var Is7 = require_is(); - var messages_1 = require_messages(); - var linkedMap_1 = require_linkedMap(); - var events_1 = require_events(); - var cancellation_1 = require_cancellation(); - var CancelNotification; - (function(CancelNotification2) { - CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest"); - })(CancelNotification || (CancelNotification = {})); - var ProgressNotification2; - (function(ProgressNotification3) { - ProgressNotification3.type = new messages_1.NotificationType("$/progress"); - })(ProgressNotification2 || (ProgressNotification2 = {})); - var ProgressType4 = class { - constructor() { - } - }; - exports2.ProgressType = ProgressType4; - var StarRequestHandler; - (function(StarRequestHandler2) { - function is(value) { - return Is7.func(value); - } - StarRequestHandler2.is = is; - })(StarRequestHandler || (StarRequestHandler = {})); - exports2.NullLogger = Object.freeze({ - error: () => { - }, - warn: () => { - }, - info: () => { - }, - log: () => { - } - }); - var Trace2; - (function(Trace3) { - Trace3[Trace3["Off"] = 0] = "Off"; - Trace3[Trace3["Messages"] = 1] = "Messages"; - Trace3[Trace3["Verbose"] = 2] = "Verbose"; - })(Trace2 = exports2.Trace || (exports2.Trace = {})); - (function(Trace3) { - function fromString(value) { - if (!Is7.string(value)) { - return Trace3.Off; - } - value = value.toLowerCase(); - switch (value) { - case "off": - return Trace3.Off; - case "messages": - return Trace3.Messages; - case "verbose": - return Trace3.Verbose; - default: - return Trace3.Off; - } - } - Trace3.fromString = fromString; - function toString(value) { - switch (value) { - case Trace3.Off: - return "off"; - case Trace3.Messages: - return "messages"; - case Trace3.Verbose: - return "verbose"; - default: - return "off"; - } - } - Trace3.toString = toString; - })(Trace2 = exports2.Trace || (exports2.Trace = {})); - var TraceFormat2; - (function(TraceFormat3) { - TraceFormat3["Text"] = "text"; - TraceFormat3["JSON"] = "json"; - })(TraceFormat2 = exports2.TraceFormat || (exports2.TraceFormat = {})); - (function(TraceFormat3) { - function fromString(value) { - value = value.toLowerCase(); - if (value === "json") { - return TraceFormat3.JSON; - } else { - return TraceFormat3.Text; - } - } - TraceFormat3.fromString = fromString; - })(TraceFormat2 = exports2.TraceFormat || (exports2.TraceFormat = {})); - var SetTraceNotification; - (function(SetTraceNotification2) { - SetTraceNotification2.type = new messages_1.NotificationType("$/setTrace"); - })(SetTraceNotification = exports2.SetTraceNotification || (exports2.SetTraceNotification = {})); - var LogTraceNotification; - (function(LogTraceNotification2) { - LogTraceNotification2.type = new messages_1.NotificationType("$/logTrace"); - })(LogTraceNotification = exports2.LogTraceNotification || (exports2.LogTraceNotification = {})); - var ConnectionErrors; - (function(ConnectionErrors2) { - ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed"; - ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed"; - ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening"; - })(ConnectionErrors = exports2.ConnectionErrors || (exports2.ConnectionErrors = {})); - var ConnectionError = class extends Error { - constructor(code, message) { - super(message); - this.code = code; - Object.setPrototypeOf(this, ConnectionError.prototype); - } - }; - exports2.ConnectionError = ConnectionError; - var ConnectionStrategy; - (function(ConnectionStrategy2) { - function is(value) { - const candidate = value; - return candidate && Is7.func(candidate.cancelUndispatched); - } - ConnectionStrategy2.is = is; - })(ConnectionStrategy = exports2.ConnectionStrategy || (exports2.ConnectionStrategy = {})); - var CancellationReceiverStrategy; - (function(CancellationReceiverStrategy2) { - CancellationReceiverStrategy2.Message = Object.freeze({ - createCancellationTokenSource(_) { - return new cancellation_1.CancellationTokenSource(); - } - }); - function is(value) { - const candidate = value; - return candidate && Is7.func(candidate.createCancellationTokenSource); - } - CancellationReceiverStrategy2.is = is; - })(CancellationReceiverStrategy = exports2.CancellationReceiverStrategy || (exports2.CancellationReceiverStrategy = {})); - var CancellationSenderStrategy; - (function(CancellationSenderStrategy2) { - CancellationSenderStrategy2.Message = Object.freeze({ - sendCancellation(conn, id) { - conn.sendNotification(CancelNotification.type, { id }); - }, - cleanup(_) { - } - }); - function is(value) { - const candidate = value; - return candidate && Is7.func(candidate.sendCancellation) && Is7.func(candidate.cleanup); - } - CancellationSenderStrategy2.is = is; - })(CancellationSenderStrategy = exports2.CancellationSenderStrategy || (exports2.CancellationSenderStrategy = {})); - var CancellationStrategy2; - (function(CancellationStrategy3) { - CancellationStrategy3.Message = Object.freeze({ - receiver: CancellationReceiverStrategy.Message, - sender: CancellationSenderStrategy.Message - }); - function is(value) { - const candidate = value; - return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender); - } - CancellationStrategy3.is = is; - })(CancellationStrategy2 = exports2.CancellationStrategy || (exports2.CancellationStrategy = {})); - var ConnectionOptions; - (function(ConnectionOptions2) { - function is(value) { - const candidate = value; - return candidate && (CancellationStrategy2.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy)); - } - ConnectionOptions2.is = is; - })(ConnectionOptions = exports2.ConnectionOptions || (exports2.ConnectionOptions = {})); - var ConnectionState; - (function(ConnectionState2) { - ConnectionState2[ConnectionState2["New"] = 1] = "New"; - ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening"; - ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed"; - ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed"; - })(ConnectionState || (ConnectionState = {})); - function createMessageConnection(messageReader, messageWriter, _logger, options) { - const logger113 = _logger !== void 0 ? _logger : exports2.NullLogger; - let sequenceNumber = 0; - let notificationSquenceNumber = 0; - let unknownResponseSquenceNumber = 0; - const version2 = "2.0"; - let starRequestHandler = void 0; - const requestHandlers = Object.create(null); - let starNotificationHandler = void 0; - const notificationHandlers = Object.create(null); - const progressHandlers = new Map(); - let timer; - let messageQueue = new linkedMap_1.LinkedMap(); - let responsePromises = Object.create(null); - let requestTokens = Object.create(null); - let trace = Trace2.Off; - let traceFormat = TraceFormat2.Text; - let tracer; - let state = ConnectionState.New; - const errorEmitter = new events_1.Emitter(); - const closeEmitter = new events_1.Emitter(); - const unhandledNotificationEmitter = new events_1.Emitter(); - const unhandledProgressEmitter = new events_1.Emitter(); - const disposeEmitter = new events_1.Emitter(); - const cancellationStrategy = options && options.cancellationStrategy ? options.cancellationStrategy : CancellationStrategy2.Message; - function createRequestQueueKey(id) { - if (id === null) { - throw new Error(`Can't send requests with id null since the response can't be correlated.`); - } - return "req-" + id.toString(); - } - function createResponseQueueKey(id) { - if (id === null) { - return "res-unknown-" + (++unknownResponseSquenceNumber).toString(); - } else { - return "res-" + id.toString(); - } - } - function createNotificationQueueKey() { - return "not-" + (++notificationSquenceNumber).toString(); - } - function addMessageToQueue(queue, message) { - if (messages_1.isRequestMessage(message)) { - queue.set(createRequestQueueKey(message.id), message); - } else if (messages_1.isResponseMessage(message)) { - queue.set(createResponseQueueKey(message.id), message); - } else { - queue.set(createNotificationQueueKey(), message); - } - } - function cancelUndispatched(_message) { - return void 0; - } - function isListening() { - return state === ConnectionState.Listening; - } - function isClosed() { - return state === ConnectionState.Closed; - } - function isDisposed() { - return state === ConnectionState.Disposed; - } - function closeHandler() { - if (state === ConnectionState.New || state === ConnectionState.Listening) { - state = ConnectionState.Closed; - closeEmitter.fire(void 0); - } - } - function readErrorHandler(error) { - errorEmitter.fire([error, void 0, void 0]); - } - function writeErrorHandler(data) { - errorEmitter.fire(data); - } - messageReader.onClose(closeHandler); - messageReader.onError(readErrorHandler); - messageWriter.onClose(closeHandler); - messageWriter.onError(writeErrorHandler); - function triggerMessageQueue() { - if (timer || messageQueue.size === 0) { - return; - } - timer = ral_1.default().timer.setImmediate(() => { - timer = void 0; - processMessageQueue(); - }); - } - function processMessageQueue() { - if (messageQueue.size === 0) { - return; - } - const message = messageQueue.shift(); - try { - if (messages_1.isRequestMessage(message)) { - handleRequest(message); - } else if (messages_1.isNotificationMessage(message)) { - handleNotification(message); - } else if (messages_1.isResponseMessage(message)) { - handleResponse(message); - } else { - handleInvalidMessage(message); - } - } finally { - triggerMessageQueue(); - } - } - const callback = (message) => { - try { - if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) { - const key = createRequestQueueKey(message.params.id); - const toCancel = messageQueue.get(key); - if (messages_1.isRequestMessage(toCancel)) { - const strategy = options === null || options === void 0 ? void 0 : options.connectionStrategy; - const response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel); - if (response && (response.error !== void 0 || response.result !== void 0)) { - messageQueue.delete(key); - response.id = toCancel.id; - traceSendingResponse(response, message.method, Date.now()); - messageWriter.write(response); - return; - } - } - } - addMessageToQueue(messageQueue, message); - } finally { - triggerMessageQueue(); - } - }; - function handleRequest(requestMessage) { - if (isDisposed()) { - return; - } - function reply(resultOrError, method, startTime2) { - const message = { - jsonrpc: version2, - id: requestMessage.id - }; - if (resultOrError instanceof messages_1.ResponseError) { - message.error = resultOrError.toJson(); - } else { - message.result = resultOrError === void 0 ? null : resultOrError; - } - traceSendingResponse(message, method, startTime2); - messageWriter.write(message); - } - function replyError(error, method, startTime2) { - const message = { - jsonrpc: version2, - id: requestMessage.id, - error: error.toJson() - }; - traceSendingResponse(message, method, startTime2); - messageWriter.write(message); - } - function replySuccess(result, method, startTime2) { - if (result === void 0) { - result = null; - } - const message = { - jsonrpc: version2, - id: requestMessage.id, - result - }; - traceSendingResponse(message, method, startTime2); - messageWriter.write(message); - } - traceReceivedRequest(requestMessage); - const element = requestHandlers[requestMessage.method]; - let type; - let requestHandler; - if (element) { - type = element.type; - requestHandler = element.handler; - } - const startTime = Date.now(); - if (requestHandler || starRequestHandler) { - const tokenKey = String(requestMessage.id); - const cancellationSource = cancellationStrategy.receiver.createCancellationTokenSource(tokenKey); - requestTokens[tokenKey] = cancellationSource; - try { - let handlerResult; - if (requestHandler) { - if (requestMessage.params === void 0) { - if (type !== void 0 && type.numberOfParams !== 0) { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but recevied none.`), requestMessage.method, startTime); - return; - } - handlerResult = requestHandler(cancellationSource.token); - } else if (Array.isArray(requestMessage.params)) { - if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byName) { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime); - return; - } - handlerResult = requestHandler(...requestMessage.params, cancellationSource.token); - } else { - if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime); - return; - } - handlerResult = requestHandler(requestMessage.params, cancellationSource.token); - } - } else if (starRequestHandler) { - handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token); - } - const promise = handlerResult; - if (!handlerResult) { - delete requestTokens[tokenKey]; - replySuccess(handlerResult, requestMessage.method, startTime); - } else if (promise.then) { - promise.then((resultOrError) => { - delete requestTokens[tokenKey]; - reply(resultOrError, requestMessage.method, startTime); - }, (error) => { - delete requestTokens[tokenKey]; - if (error instanceof messages_1.ResponseError) { - replyError(error, requestMessage.method, startTime); - } else if (error && Is7.string(error.message)) { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime); - } else { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime); - } - }); - } else { - delete requestTokens[tokenKey]; - reply(handlerResult, requestMessage.method, startTime); - } - } catch (error) { - delete requestTokens[tokenKey]; - if (error instanceof messages_1.ResponseError) { - reply(error, requestMessage.method, startTime); - } else if (error && Is7.string(error.message)) { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime); - } else { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime); - } - } - } else { - replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime); - } - } - function handleResponse(responseMessage) { - if (isDisposed()) { - return; - } - if (responseMessage.id === null) { - if (responseMessage.error) { - logger113.error(`Received response message without id: Error is: -${JSON.stringify(responseMessage.error, void 0, 4)}`); - } else { - logger113.error(`Received response message without id. No further error information provided.`); - } - } else { - const key = String(responseMessage.id); - const responsePromise = responsePromises[key]; - traceReceivedResponse(responseMessage, responsePromise); - if (responsePromise) { - delete responsePromises[key]; - try { - if (responseMessage.error) { - const error = responseMessage.error; - responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data)); - } else if (responseMessage.result !== void 0) { - responsePromise.resolve(responseMessage.result); - } else { - throw new Error("Should never happen."); - } - } catch (error) { - if (error.message) { - logger113.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`); - } else { - logger113.error(`Response handler '${responsePromise.method}' failed unexpectedly.`); - } - } - } - } - } - function handleNotification(message) { - if (isDisposed()) { - return; - } - let type = void 0; - let notificationHandler; - if (message.method === CancelNotification.type.method) { - notificationHandler = (params) => { - const id = params.id; - const source = requestTokens[String(id)]; - if (source) { - source.cancel(); - } - }; - } else { - const element = notificationHandlers[message.method]; - if (element) { - notificationHandler = element.handler; - type = element.type; - } - } - if (notificationHandler || starNotificationHandler) { - try { - traceReceivedNotification(message); - if (notificationHandler) { - if (message.params === void 0) { - if (type !== void 0) { - if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) { - logger113.error(`Notification ${message.method} defines ${type.numberOfParams} params but recevied none.`); - } - } - notificationHandler(); - } else if (Array.isArray(message.params)) { - if (type !== void 0) { - if (type.parameterStructures === messages_1.ParameterStructures.byName) { - logger113.error(`Notification ${message.method} defines parameters by name but received parameters by position`); - } - if (type.numberOfParams !== message.params.length) { - logger113.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${message.params.length} argumennts`); - } - } - notificationHandler(...message.params); - } else { - if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) { - logger113.error(`Notification ${message.method} defines parameters by position but received parameters by name`); - } - notificationHandler(message.params); - } - } else if (starNotificationHandler) { - starNotificationHandler(message.method, message.params); - } - } catch (error) { - if (error.message) { - logger113.error(`Notification handler '${message.method}' failed with message: ${error.message}`); - } else { - logger113.error(`Notification handler '${message.method}' failed unexpectedly.`); - } - } - } else { - unhandledNotificationEmitter.fire(message); - } - } - function handleInvalidMessage(message) { - if (!message) { - logger113.error("Received empty message."); - return; - } - logger113.error(`Received message which is neither a response nor a notification message: -${JSON.stringify(message, null, 4)}`); - const responseMessage = message; - if (Is7.string(responseMessage.id) || Is7.number(responseMessage.id)) { - const key = String(responseMessage.id); - const responseHandler = responsePromises[key]; - if (responseHandler) { - responseHandler.reject(new Error("The received response has neither a result nor an error property.")); - } - } - } - function traceSendingRequest(message) { - if (trace === Trace2.Off || !tracer) { - return; - } - if (traceFormat === TraceFormat2.Text) { - let data = void 0; - if (trace === Trace2.Verbose && message.params) { - data = `Params: ${JSON.stringify(message.params, null, 4)} - -`; - } - tracer.log(`Sending request '${message.method} - (${message.id})'.`, data); - } else { - logLSPMessage("send-request", message); - } - } - function traceSendingNotification(message) { - if (trace === Trace2.Off || !tracer) { - return; - } - if (traceFormat === TraceFormat2.Text) { - let data = void 0; - if (trace === Trace2.Verbose) { - if (message.params) { - data = `Params: ${JSON.stringify(message.params, null, 4)} - -`; - } else { - data = "No parameters provided.\n\n"; - } - } - tracer.log(`Sending notification '${message.method}'.`, data); - } else { - logLSPMessage("send-notification", message); - } - } - function traceSendingResponse(message, method, startTime) { - if (trace === Trace2.Off || !tracer) { - return; - } - if (traceFormat === TraceFormat2.Text) { - let data = void 0; - if (trace === Trace2.Verbose) { - if (message.error && message.error.data) { - data = `Error data: ${JSON.stringify(message.error.data, null, 4)} - -`; - } else { - if (message.result) { - data = `Result: ${JSON.stringify(message.result, null, 4)} - -`; - } else if (message.error === void 0) { - data = "No result returned.\n\n"; - } - } - } - tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data); - } else { - logLSPMessage("send-response", message); - } - } - function traceReceivedRequest(message) { - if (trace === Trace2.Off || !tracer) { - return; - } - if (traceFormat === TraceFormat2.Text) { - let data = void 0; - if (trace === Trace2.Verbose && message.params) { - data = `Params: ${JSON.stringify(message.params, null, 4)} - -`; - } - tracer.log(`Received request '${message.method} - (${message.id})'.`, data); - } else { - logLSPMessage("receive-request", message); - } - } - function traceReceivedNotification(message) { - if (trace === Trace2.Off || !tracer || message.method === LogTraceNotification.type.method) { - return; - } - if (traceFormat === TraceFormat2.Text) { - let data = void 0; - if (trace === Trace2.Verbose) { - if (message.params) { - data = `Params: ${JSON.stringify(message.params, null, 4)} - -`; - } else { - data = "No parameters provided.\n\n"; - } - } - tracer.log(`Received notification '${message.method}'.`, data); - } else { - logLSPMessage("receive-notification", message); - } - } - function traceReceivedResponse(message, responsePromise) { - if (trace === Trace2.Off || !tracer) { - return; - } - if (traceFormat === TraceFormat2.Text) { - let data = void 0; - if (trace === Trace2.Verbose) { - if (message.error && message.error.data) { - data = `Error data: ${JSON.stringify(message.error.data, null, 4)} - -`; - } else { - if (message.result) { - data = `Result: ${JSON.stringify(message.result, null, 4)} - -`; - } else if (message.error === void 0) { - data = "No result returned.\n\n"; - } - } - } - if (responsePromise) { - const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : ""; - tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data); - } else { - tracer.log(`Received response ${message.id} without active response promise.`, data); - } - } else { - logLSPMessage("receive-response", message); - } - } - function logLSPMessage(type, message) { - if (!tracer || trace === Trace2.Off) { - return; - } - const lspMessage = { - isLSPMessage: true, - type, - message, - timestamp: Date.now() - }; - tracer.log(lspMessage); - } - function throwIfClosedOrDisposed() { - if (isClosed()) { - throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed."); - } - if (isDisposed()) { - throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed."); - } - } - function throwIfListening() { - if (isListening()) { - throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening"); - } - } - function throwIfNotListening() { - if (!isListening()) { - throw new Error("Call listen() first."); - } - } - function undefinedToNull(param) { - if (param === void 0) { - return null; - } else { - return param; - } - } - function nullToUndefined(param) { - if (param === null) { - return void 0; - } else { - return param; - } - } - function isNamedParam(param) { - return param !== void 0 && param !== null && !Array.isArray(param) && typeof param === "object"; - } - function computeSingleParam(parameterStructures, param) { - switch (parameterStructures) { - case messages_1.ParameterStructures.auto: - if (isNamedParam(param)) { - return nullToUndefined(param); - } else { - return [undefinedToNull(param)]; - } - break; - case messages_1.ParameterStructures.byName: - if (!isNamedParam(param)) { - throw new Error(`Recevied parameters by name but param is not an object literal.`); - } - return nullToUndefined(param); - case messages_1.ParameterStructures.byPosition: - return [undefinedToNull(param)]; - default: - throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`); - } - } - function computeMessageParams(type, params) { - let result; - const numberOfParams = type.numberOfParams; - switch (numberOfParams) { - case 0: - result = void 0; - break; - case 1: - result = computeSingleParam(type.parameterStructures, params[0]); - break; - default: - result = []; - for (let i = 0; i < params.length && i < numberOfParams; i++) { - result.push(undefinedToNull(params[i])); - } - if (params.length < numberOfParams) { - for (let i = params.length; i < numberOfParams; i++) { - result.push(null); - } - } - break; - } - return result; - } - const connection = { - sendNotification: (type, ...args) => { - throwIfClosedOrDisposed(); - let method; - let messageParams; - if (Is7.string(type)) { - method = type; - const first = args[0]; - let paramStart = 0; - let parameterStructures = messages_1.ParameterStructures.auto; - if (messages_1.ParameterStructures.is(first)) { - paramStart = 1; - parameterStructures = first; - } - let paramEnd = args.length; - const numberOfParams = paramEnd - paramStart; - switch (numberOfParams) { - case 0: - messageParams = void 0; - break; - case 1: - messageParams = computeSingleParam(parameterStructures, args[paramStart]); - break; - default: - if (parameterStructures === messages_1.ParameterStructures.byName) { - throw new Error(`Recevied ${numberOfParams} parameters for 'by Name' notification parameter structure.`); - } - messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value)); - break; - } - } else { - const params = args; - method = type.method; - messageParams = computeMessageParams(type, params); - } - const notificationMessage = { - jsonrpc: version2, - method, - params: messageParams - }; - traceSendingNotification(notificationMessage); - messageWriter.write(notificationMessage); - }, - onNotification: (type, handler) => { - throwIfClosedOrDisposed(); - let method; - if (Is7.func(type)) { - starNotificationHandler = type; - } else if (handler) { - if (Is7.string(type)) { - method = type; - notificationHandlers[type] = { type: void 0, handler }; - } else { - method = type.method; - notificationHandlers[type.method] = { type, handler }; - } - } - return { - dispose: () => { - if (method !== void 0) { - delete notificationHandlers[method]; - } else { - starNotificationHandler = void 0; - } - } - }; - }, - onProgress: (_type, token, handler) => { - if (progressHandlers.has(token)) { - throw new Error(`Progress handler for token ${token} already registered`); - } - progressHandlers.set(token, handler); - return { - dispose: () => { - progressHandlers.delete(token); - } - }; - }, - sendProgress: (_type, token, value) => { - connection.sendNotification(ProgressNotification2.type, { token, value }); - }, - onUnhandledProgress: unhandledProgressEmitter.event, - sendRequest: (type, ...args) => { - throwIfClosedOrDisposed(); - throwIfNotListening(); - let method; - let messageParams; - let token = void 0; - if (Is7.string(type)) { - method = type; - const first = args[0]; - const last = args[args.length - 1]; - let paramStart = 0; - let parameterStructures = messages_1.ParameterStructures.auto; - if (messages_1.ParameterStructures.is(first)) { - paramStart = 1; - parameterStructures = first; - } - let paramEnd = args.length; - if (cancellation_1.CancellationToken.is(last)) { - paramEnd = paramEnd - 1; - token = last; - } - const numberOfParams = paramEnd - paramStart; - switch (numberOfParams) { - case 0: - messageParams = void 0; - break; - case 1: - messageParams = computeSingleParam(parameterStructures, args[paramStart]); - break; - default: - if (parameterStructures === messages_1.ParameterStructures.byName) { - throw new Error(`Recevied ${numberOfParams} parameters for 'by Name' request parameter structure.`); - } - messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value)); - break; - } - } else { - const params = args; - method = type.method; - messageParams = computeMessageParams(type, params); - const numberOfParams = type.numberOfParams; - token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : void 0; - } - const id = sequenceNumber++; - let disposable; - if (token) { - disposable = token.onCancellationRequested(() => { - cancellationStrategy.sender.sendCancellation(connection, id); - }); - } - const result = new Promise((resolve3, reject) => { - const requestMessage = { - jsonrpc: version2, - id, - method, - params: messageParams - }; - const resolveWithCleanup = (r) => { - resolve3(r); - cancellationStrategy.sender.cleanup(id); - disposable === null || disposable === void 0 ? void 0 : disposable.dispose(); - }; - const rejectWithCleanup = (r) => { - reject(r); - cancellationStrategy.sender.cleanup(id); - disposable === null || disposable === void 0 ? void 0 : disposable.dispose(); - }; - let responsePromise = { method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup }; - traceSendingRequest(requestMessage); - try { - messageWriter.write(requestMessage); - } catch (e) { - responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : "Unknown reason")); - responsePromise = null; - } - if (responsePromise) { - responsePromises[String(id)] = responsePromise; - } - }); - return result; - }, - onRequest: (type, handler) => { - throwIfClosedOrDisposed(); - let method = null; - if (StarRequestHandler.is(type)) { - method = void 0; - starRequestHandler = type; - } else if (Is7.string(type)) { - method = null; - if (handler !== void 0) { - method = type; - requestHandlers[type] = { handler, type: void 0 }; - } - } else { - if (handler !== void 0) { - method = type.method; - requestHandlers[type.method] = { type, handler }; - } - } - return { - dispose: () => { - if (method === null) { - return; - } - if (method !== void 0) { - delete requestHandlers[method]; - } else { - starRequestHandler = void 0; - } - } - }; - }, - trace: (_value, _tracer, sendNotificationOrTraceOptions) => { - let _sendNotification = false; - let _traceFormat = TraceFormat2.Text; - if (sendNotificationOrTraceOptions !== void 0) { - if (Is7.boolean(sendNotificationOrTraceOptions)) { - _sendNotification = sendNotificationOrTraceOptions; - } else { - _sendNotification = sendNotificationOrTraceOptions.sendNotification || false; - _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat2.Text; - } - } - trace = _value; - traceFormat = _traceFormat; - if (trace === Trace2.Off) { - tracer = void 0; - } else { - tracer = _tracer; - } - if (_sendNotification && !isClosed() && !isDisposed()) { - connection.sendNotification(SetTraceNotification.type, { value: Trace2.toString(_value) }); - } - }, - onError: errorEmitter.event, - onClose: closeEmitter.event, - onUnhandledNotification: unhandledNotificationEmitter.event, - onDispose: disposeEmitter.event, - end: () => { - messageWriter.end(); - }, - dispose: () => { - if (isDisposed()) { - return; - } - state = ConnectionState.Disposed; - disposeEmitter.fire(void 0); - const error = new Error("Connection got disposed."); - Object.keys(responsePromises).forEach((key) => { - responsePromises[key].reject(error); - }); - responsePromises = Object.create(null); - requestTokens = Object.create(null); - messageQueue = new linkedMap_1.LinkedMap(); - if (Is7.func(messageWriter.dispose)) { - messageWriter.dispose(); - } - if (Is7.func(messageReader.dispose)) { - messageReader.dispose(); - } - }, - listen: () => { - throwIfClosedOrDisposed(); - throwIfListening(); - state = ConnectionState.Listening; - messageReader.listen(callback); - }, - inspect: () => { - ral_1.default().console.log("inspect"); - } - }; - connection.onNotification(LogTraceNotification.type, (params) => { - if (trace === Trace2.Off || !tracer) { - return; - } - tracer.log(params.message, trace === Trace2.Verbose ? params.verbose : void 0); - }); - connection.onNotification(ProgressNotification2.type, (params) => { - const handler = progressHandlers.get(params.token); - if (handler) { - handler(params.value); - } else { - unhandledProgressEmitter.fire(params); - } - }); - return connection; - } - exports2.createMessageConnection = createMessageConnection; - } -}); - -// node_modules/vscode-jsonrpc/lib/common/api.js -var require_api2 = __commonJS({ - "node_modules/vscode-jsonrpc/lib/common/api.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.Trace = exports2.ProgressType = exports2.createMessageConnection = exports2.NullLogger = exports2.ConnectionOptions = exports2.ConnectionStrategy = exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = exports2.CancellationToken = exports2.CancellationTokenSource = exports2.Emitter = exports2.Event = exports2.Disposable = exports2.ParameterStructures = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.ErrorCodes = exports2.ResponseError = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType0 = exports2.RequestType = exports2.RAL = void 0; - exports2.CancellationStrategy = void 0; - var messages_1 = require_messages(); - Object.defineProperty(exports2, "RequestType", { enumerable: true, get: function() { - return messages_1.RequestType; - } }); - Object.defineProperty(exports2, "RequestType0", { enumerable: true, get: function() { - return messages_1.RequestType0; - } }); - Object.defineProperty(exports2, "RequestType1", { enumerable: true, get: function() { - return messages_1.RequestType1; - } }); - Object.defineProperty(exports2, "RequestType2", { enumerable: true, get: function() { - return messages_1.RequestType2; - } }); - Object.defineProperty(exports2, "RequestType3", { enumerable: true, get: function() { - return messages_1.RequestType3; - } }); - Object.defineProperty(exports2, "RequestType4", { enumerable: true, get: function() { - return messages_1.RequestType4; - } }); - Object.defineProperty(exports2, "RequestType5", { enumerable: true, get: function() { - return messages_1.RequestType5; - } }); - Object.defineProperty(exports2, "RequestType6", { enumerable: true, get: function() { - return messages_1.RequestType6; - } }); - Object.defineProperty(exports2, "RequestType7", { enumerable: true, get: function() { - return messages_1.RequestType7; - } }); - Object.defineProperty(exports2, "RequestType8", { enumerable: true, get: function() { - return messages_1.RequestType8; - } }); - Object.defineProperty(exports2, "RequestType9", { enumerable: true, get: function() { - return messages_1.RequestType9; - } }); - Object.defineProperty(exports2, "ResponseError", { enumerable: true, get: function() { - return messages_1.ResponseError; - } }); - Object.defineProperty(exports2, "ErrorCodes", { enumerable: true, get: function() { - return messages_1.ErrorCodes; - } }); - Object.defineProperty(exports2, "NotificationType", { enumerable: true, get: function() { - return messages_1.NotificationType; - } }); - Object.defineProperty(exports2, "NotificationType0", { enumerable: true, get: function() { - return messages_1.NotificationType0; - } }); - Object.defineProperty(exports2, "NotificationType1", { enumerable: true, get: function() { - return messages_1.NotificationType1; - } }); - Object.defineProperty(exports2, "NotificationType2", { enumerable: true, get: function() { - return messages_1.NotificationType2; - } }); - Object.defineProperty(exports2, "NotificationType3", { enumerable: true, get: function() { - return messages_1.NotificationType3; - } }); - Object.defineProperty(exports2, "NotificationType4", { enumerable: true, get: function() { - return messages_1.NotificationType4; - } }); - Object.defineProperty(exports2, "NotificationType5", { enumerable: true, get: function() { - return messages_1.NotificationType5; - } }); - Object.defineProperty(exports2, "NotificationType6", { enumerable: true, get: function() { - return messages_1.NotificationType6; - } }); - Object.defineProperty(exports2, "NotificationType7", { enumerable: true, get: function() { - return messages_1.NotificationType7; - } }); - Object.defineProperty(exports2, "NotificationType8", { enumerable: true, get: function() { - return messages_1.NotificationType8; - } }); - Object.defineProperty(exports2, "NotificationType9", { enumerable: true, get: function() { - return messages_1.NotificationType9; - } }); - Object.defineProperty(exports2, "ParameterStructures", { enumerable: true, get: function() { - return messages_1.ParameterStructures; - } }); - var disposable_1 = require_disposable(); - Object.defineProperty(exports2, "Disposable", { enumerable: true, get: function() { - return disposable_1.Disposable; - } }); - var events_1 = require_events(); - Object.defineProperty(exports2, "Event", { enumerable: true, get: function() { - return events_1.Event; - } }); - Object.defineProperty(exports2, "Emitter", { enumerable: true, get: function() { - return events_1.Emitter; - } }); - var cancellation_1 = require_cancellation(); - Object.defineProperty(exports2, "CancellationTokenSource", { enumerable: true, get: function() { - return cancellation_1.CancellationTokenSource; - } }); - Object.defineProperty(exports2, "CancellationToken", { enumerable: true, get: function() { - return cancellation_1.CancellationToken; - } }); - var messageReader_1 = require_messageReader(); - Object.defineProperty(exports2, "MessageReader", { enumerable: true, get: function() { - return messageReader_1.MessageReader; - } }); - Object.defineProperty(exports2, "AbstractMessageReader", { enumerable: true, get: function() { - return messageReader_1.AbstractMessageReader; - } }); - Object.defineProperty(exports2, "ReadableStreamMessageReader", { enumerable: true, get: function() { - return messageReader_1.ReadableStreamMessageReader; - } }); - var messageWriter_1 = require_messageWriter(); - Object.defineProperty(exports2, "MessageWriter", { enumerable: true, get: function() { - return messageWriter_1.MessageWriter; - } }); - Object.defineProperty(exports2, "AbstractMessageWriter", { enumerable: true, get: function() { - return messageWriter_1.AbstractMessageWriter; - } }); - Object.defineProperty(exports2, "WriteableStreamMessageWriter", { enumerable: true, get: function() { - return messageWriter_1.WriteableStreamMessageWriter; - } }); - var connection_1 = require_connection2(); - Object.defineProperty(exports2, "ConnectionStrategy", { enumerable: true, get: function() { - return connection_1.ConnectionStrategy; - } }); - Object.defineProperty(exports2, "ConnectionOptions", { enumerable: true, get: function() { - return connection_1.ConnectionOptions; - } }); - Object.defineProperty(exports2, "NullLogger", { enumerable: true, get: function() { - return connection_1.NullLogger; - } }); - Object.defineProperty(exports2, "createMessageConnection", { enumerable: true, get: function() { - return connection_1.createMessageConnection; - } }); - Object.defineProperty(exports2, "ProgressType", { enumerable: true, get: function() { - return connection_1.ProgressType; - } }); - Object.defineProperty(exports2, "Trace", { enumerable: true, get: function() { - return connection_1.Trace; - } }); - Object.defineProperty(exports2, "TraceFormat", { enumerable: true, get: function() { - return connection_1.TraceFormat; - } }); - Object.defineProperty(exports2, "SetTraceNotification", { enumerable: true, get: function() { - return connection_1.SetTraceNotification; - } }); - Object.defineProperty(exports2, "LogTraceNotification", { enumerable: true, get: function() { - return connection_1.LogTraceNotification; - } }); - Object.defineProperty(exports2, "ConnectionErrors", { enumerable: true, get: function() { - return connection_1.ConnectionErrors; - } }); - Object.defineProperty(exports2, "ConnectionError", { enumerable: true, get: function() { - return connection_1.ConnectionError; - } }); - Object.defineProperty(exports2, "CancellationReceiverStrategy", { enumerable: true, get: function() { - return connection_1.CancellationReceiverStrategy; - } }); - Object.defineProperty(exports2, "CancellationSenderStrategy", { enumerable: true, get: function() { - return connection_1.CancellationSenderStrategy; - } }); - Object.defineProperty(exports2, "CancellationStrategy", { enumerable: true, get: function() { - return connection_1.CancellationStrategy; - } }); - var ral_1 = require_ral(); - exports2.RAL = ral_1.default; - } -}); - -// node_modules/vscode-jsonrpc/lib/node/main.js -var require_main = __commonJS({ - "node_modules/vscode-jsonrpc/lib/node/main.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { - return m[k]; - } }); - } : function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; - o[k2] = m[k]; - }); - var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) - if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) - __createBinding(exports3, m, p); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createMessageConnection = exports2.createServerSocketTransport = exports2.createClientSocketTransport = exports2.createServerPipeTransport = exports2.createClientPipeTransport = exports2.generateRandomPipeName = exports2.StreamMessageWriter = exports2.StreamMessageReader = exports2.SocketMessageWriter = exports2.SocketMessageReader = exports2.IPCMessageWriter = exports2.IPCMessageReader = void 0; - var ril_1 = require_ril(); - ril_1.default.install(); - var api_1 = require_api2(); - var path36 = require("path"); - var os10 = require("os"); - var crypto_1 = require("crypto"); - var net_1 = require("net"); - __exportStar(require_api2(), exports2); - var IPCMessageReader2 = class extends api_1.AbstractMessageReader { - constructor(process2) { - super(); - this.process = process2; - let eventEmitter = this.process; - eventEmitter.on("error", (error) => this.fireError(error)); - eventEmitter.on("close", () => this.fireClose()); - } - listen(callback) { - this.process.on("message", callback); - return api_1.Disposable.create(() => this.process.off("message", callback)); - } - }; - exports2.IPCMessageReader = IPCMessageReader2; - var IPCMessageWriter2 = class extends api_1.AbstractMessageWriter { - constructor(process2) { - super(); - this.process = process2; - this.errorCount = 0; - let eventEmitter = this.process; - eventEmitter.on("error", (error) => this.fireError(error)); - eventEmitter.on("close", () => this.fireClose); - } - write(msg) { - try { - if (typeof this.process.send === "function") { - this.process.send(msg, void 0, void 0, (error) => { - if (error) { - this.errorCount++; - this.handleError(error, msg); - } else { - this.errorCount = 0; - } - }); - } - return Promise.resolve(); - } catch (error) { - this.handleError(error, msg); - return Promise.reject(error); - } - } - handleError(error, msg) { - this.errorCount++; - this.fireError(error, msg, this.errorCount); - } - end() { - } - }; - exports2.IPCMessageWriter = IPCMessageWriter2; - var SocketMessageReader = class extends api_1.ReadableStreamMessageReader { - constructor(socket, encoding = "utf-8") { - super(ril_1.default().stream.asReadableStream(socket), encoding); - } - }; - exports2.SocketMessageReader = SocketMessageReader; - var SocketMessageWriter = class extends api_1.WriteableStreamMessageWriter { - constructor(socket, options) { - super(ril_1.default().stream.asWritableStream(socket), options); - this.socket = socket; - } - dispose() { - super.dispose(); - this.socket.destroy(); - } - }; - exports2.SocketMessageWriter = SocketMessageWriter; - var StreamMessageReader2 = class extends api_1.ReadableStreamMessageReader { - constructor(readble, encoding) { - super(ril_1.default().stream.asReadableStream(readble), encoding); - } - }; - exports2.StreamMessageReader = StreamMessageReader2; - var StreamMessageWriter2 = class extends api_1.WriteableStreamMessageWriter { - constructor(writable, options) { - super(ril_1.default().stream.asWritableStream(writable), options); - } - }; - exports2.StreamMessageWriter = StreamMessageWriter2; - var XDG_RUNTIME_DIR = process.env["XDG_RUNTIME_DIR"]; - var safeIpcPathLengths = new Map([ - ["linux", 107], - ["darwin", 103] - ]); - function generateRandomPipeName2() { - const randomSuffix = crypto_1.randomBytes(21).toString("hex"); - if (process.platform === "win32") { - return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`; - } - let result; - if (XDG_RUNTIME_DIR) { - result = path36.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`); - } else { - result = path36.join(os10.tmpdir(), `vscode-${randomSuffix}.sock`); - } - const limit = safeIpcPathLengths.get(process.platform); - if (limit !== void 0 && result.length >= limit) { - ril_1.default().console.warn(`WARNING: IPC handle "${result}" is longer than ${limit} characters.`); - } - return result; - } - exports2.generateRandomPipeName = generateRandomPipeName2; - function createClientPipeTransport2(pipeName, encoding = "utf-8") { - let connectResolve; - const connected = new Promise((resolve3, _reject) => { - connectResolve = resolve3; - }); - return new Promise((resolve3, reject) => { - let server = net_1.createServer((socket) => { - server.close(); - connectResolve([ - new SocketMessageReader(socket, encoding), - new SocketMessageWriter(socket, encoding) - ]); - }); - server.on("error", reject); - server.listen(pipeName, () => { - server.removeListener("error", reject); - resolve3({ - onConnected: () => { - return connected; - } - }); - }); - }); - } - exports2.createClientPipeTransport = createClientPipeTransport2; - function createServerPipeTransport(pipeName, encoding = "utf-8") { - const socket = net_1.createConnection(pipeName); - return [ - new SocketMessageReader(socket, encoding), - new SocketMessageWriter(socket, encoding) - ]; - } - exports2.createServerPipeTransport = createServerPipeTransport; - function createClientSocketTransport2(port, encoding = "utf-8") { - let connectResolve; - const connected = new Promise((resolve3, _reject) => { - connectResolve = resolve3; - }); - return new Promise((resolve3, reject) => { - const server = net_1.createServer((socket) => { - server.close(); - connectResolve([ - new SocketMessageReader(socket, encoding), - new SocketMessageWriter(socket, encoding) - ]); - }); - server.on("error", reject); - server.listen(port, "127.0.0.1", () => { - server.removeListener("error", reject); - resolve3({ - onConnected: () => { - return connected; - } - }); - }); - }); - } - exports2.createClientSocketTransport = createClientSocketTransport2; - function createServerSocketTransport(port, encoding = "utf-8") { - const socket = net_1.createConnection(port, "127.0.0.1"); - return [ - new SocketMessageReader(socket, encoding), - new SocketMessageWriter(socket, encoding) - ]; - } - exports2.createServerSocketTransport = createServerSocketTransport; - function isReadableStream(value) { - const candidate = value; - return candidate.read !== void 0 && candidate.addListener !== void 0; - } - function isWritableStream(value) { - const candidate = value; - return candidate.write !== void 0 && candidate.addListener !== void 0; - } - function createMessageConnection(input, output, logger113, options) { - if (!logger113) { - logger113 = api_1.NullLogger; - } - const reader = isReadableStream(input) ? new StreamMessageReader2(input) : input; - const writer = isWritableStream(output) ? new StreamMessageWriter2(output) : output; - if (api_1.ConnectionStrategy.is(options)) { - options = { connectionStrategy: options }; - } - return api_1.createMessageConnection(reader, writer, logger113, options); - } - exports2.createMessageConnection = createMessageConnection; - } -}); - -// node_modules/vscode-jsonrpc/node.js -var require_node2 = __commonJS({ - "node_modules/vscode-jsonrpc/node.js"(exports2, module2) { - "use strict"; - module2.exports = require_main(); - } -}); - -// node_modules/vscode-languageserver-types/lib/esm/main.js -var main_exports = {}; -__export(main_exports, { - AnnotatedTextEdit: () => AnnotatedTextEdit, - ChangeAnnotation: () => ChangeAnnotation, - ChangeAnnotationIdentifier: () => ChangeAnnotationIdentifier, - CodeAction: () => CodeAction, - CodeActionContext: () => CodeActionContext, - CodeActionKind: () => CodeActionKind, - CodeDescription: () => CodeDescription, - CodeLens: () => CodeLens, - Color: () => Color, - ColorInformation: () => ColorInformation, - ColorPresentation: () => ColorPresentation, - Command: () => Command, - CompletionItem: () => CompletionItem, - CompletionItemKind: () => CompletionItemKind, - CompletionItemTag: () => CompletionItemTag, - CompletionList: () => CompletionList, - CreateFile: () => CreateFile, - DeleteFile: () => DeleteFile, - Diagnostic: () => Diagnostic, - DiagnosticRelatedInformation: () => DiagnosticRelatedInformation, - DiagnosticSeverity: () => DiagnosticSeverity, - DiagnosticTag: () => DiagnosticTag, - DocumentHighlight: () => DocumentHighlight, - DocumentHighlightKind: () => DocumentHighlightKind, - DocumentLink: () => DocumentLink, - DocumentSymbol: () => DocumentSymbol, - EOL: () => EOL, - FoldingRange: () => FoldingRange, - FoldingRangeKind: () => FoldingRangeKind, - FormattingOptions: () => FormattingOptions, - Hover: () => Hover, - InsertReplaceEdit: () => InsertReplaceEdit, - InsertTextFormat: () => InsertTextFormat, - InsertTextMode: () => InsertTextMode, - Location: () => Location, - LocationLink: () => LocationLink, - MarkedString: () => MarkedString, - MarkupContent: () => MarkupContent, - MarkupKind: () => MarkupKind, - OptionalVersionedTextDocumentIdentifier: () => OptionalVersionedTextDocumentIdentifier, - ParameterInformation: () => ParameterInformation, - Position: () => Position, - Range: () => Range, - RenameFile: () => RenameFile, - SelectionRange: () => SelectionRange, - SignatureInformation: () => SignatureInformation, - SymbolInformation: () => SymbolInformation, - SymbolKind: () => SymbolKind, - SymbolTag: () => SymbolTag, - TextDocument: () => TextDocument, - TextDocumentEdit: () => TextDocumentEdit, - TextDocumentIdentifier: () => TextDocumentIdentifier, - TextDocumentItem: () => TextDocumentItem, - TextEdit: () => TextEdit, - VersionedTextDocumentIdentifier: () => VersionedTextDocumentIdentifier, - WorkspaceChange: () => WorkspaceChange, - WorkspaceEdit: () => WorkspaceEdit, - integer: () => integer, - uinteger: () => uinteger -}); -var integer, uinteger, Position, Range, Location, LocationLink, Color, ColorInformation, ColorPresentation, FoldingRangeKind, FoldingRange, DiagnosticRelatedInformation, DiagnosticSeverity, DiagnosticTag, CodeDescription, Diagnostic, Command, TextEdit, ChangeAnnotation, ChangeAnnotationIdentifier, AnnotatedTextEdit, TextDocumentEdit, CreateFile, RenameFile, DeleteFile, WorkspaceEdit, TextEditChangeImpl, ChangeAnnotations, WorkspaceChange, TextDocumentIdentifier, VersionedTextDocumentIdentifier, OptionalVersionedTextDocumentIdentifier, TextDocumentItem, MarkupKind, MarkupContent, CompletionItemKind, InsertTextFormat, CompletionItemTag, InsertReplaceEdit, InsertTextMode, CompletionItem, CompletionList, MarkedString, Hover, ParameterInformation, SignatureInformation, DocumentHighlightKind, DocumentHighlight, SymbolKind, SymbolTag, SymbolInformation, DocumentSymbol, CodeActionKind, CodeActionContext, CodeAction, CodeLens, FormattingOptions, DocumentLink, SelectionRange, EOL, TextDocument, FullTextDocument, Is; -var init_main = __esm({ - "node_modules/vscode-languageserver-types/lib/esm/main.js"() { - "use strict"; - (function(integer2) { - integer2.MIN_VALUE = -2147483648; - integer2.MAX_VALUE = 2147483647; - })(integer || (integer = {})); - (function(uinteger3) { - uinteger3.MIN_VALUE = 0; - uinteger3.MAX_VALUE = 2147483647; - })(uinteger || (uinteger = {})); - (function(Position45) { - function create(line, character) { - if (line === Number.MAX_VALUE) { - line = uinteger.MAX_VALUE; - } - if (character === Number.MAX_VALUE) { - character = uinteger.MAX_VALUE; - } - return { line, character }; - } - Position45.create = create; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character); - } - Position45.is = is; - })(Position || (Position = {})); - (function(Range39) { - function create(one, two, three, four) { - if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) { - return { start: Position.create(one, two), end: Position.create(three, four) }; - } else if (Position.is(one) && Position.is(two)) { - return { start: one, end: two }; - } else { - throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]"); - } - } - Range39.create = create; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end); - } - Range39.is = is; - })(Range || (Range = {})); - (function(Location18) { - function create(uri, range) { - return { uri, range }; - } - Location18.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri)); - } - Location18.is = is; - })(Location || (Location = {})); - (function(LocationLink9) { - function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) { - return { targetUri, targetRange, targetSelectionRange, originSelectionRange }; - } - LocationLink9.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange)) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange)); - } - LocationLink9.is = is; - })(LocationLink || (LocationLink = {})); - (function(Color4) { - function create(red, green, blue2, alpha) { - return { - red, - green, - blue: blue2, - alpha - }; - } - Color4.create = create; - function is(value) { - var candidate = value; - return Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1); - } - Color4.is = is; - })(Color || (Color = {})); - (function(ColorInformation7) { - function create(range, color) { - return { - range, - color - }; - } - ColorInformation7.create = create; - function is(value) { - var candidate = value; - return Range.is(candidate.range) && Color.is(candidate.color); - } - ColorInformation7.is = is; - })(ColorInformation || (ColorInformation = {})); - (function(ColorPresentation5) { - function create(label, textEdit, additionalTextEdits) { - return { - label, - textEdit, - additionalTextEdits - }; - } - ColorPresentation5.create = create; - function is(value) { - var candidate = value; - return Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is)); - } - ColorPresentation5.is = is; - })(ColorPresentation || (ColorPresentation = {})); - (function(FoldingRangeKind2) { - FoldingRangeKind2["Comment"] = "comment"; - FoldingRangeKind2["Imports"] = "imports"; - FoldingRangeKind2["Region"] = "region"; - })(FoldingRangeKind || (FoldingRangeKind = {})); - (function(FoldingRange5) { - function create(startLine, endLine, startCharacter, endCharacter, kind) { - var result = { - startLine, - endLine - }; - if (Is.defined(startCharacter)) { - result.startCharacter = startCharacter; - } - if (Is.defined(endCharacter)) { - result.endCharacter = endCharacter; - } - if (Is.defined(kind)) { - result.kind = kind; - } - return result; - } - FoldingRange5.create = create; - function is(value) { - var candidate = value; - return Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind)); - } - FoldingRange5.is = is; - })(FoldingRange || (FoldingRange = {})); - (function(DiagnosticRelatedInformation2) { - function create(location, message) { - return { - location, - message - }; - } - DiagnosticRelatedInformation2.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message); - } - DiagnosticRelatedInformation2.is = is; - })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {})); - (function(DiagnosticSeverity7) { - DiagnosticSeverity7.Error = 1; - DiagnosticSeverity7.Warning = 2; - DiagnosticSeverity7.Information = 3; - DiagnosticSeverity7.Hint = 4; - })(DiagnosticSeverity || (DiagnosticSeverity = {})); - (function(DiagnosticTag6) { - DiagnosticTag6.Unnecessary = 1; - DiagnosticTag6.Deprecated = 2; - })(DiagnosticTag || (DiagnosticTag = {})); - (function(CodeDescription2) { - function is(value) { - var candidate = value; - return candidate !== void 0 && candidate !== null && Is.string(candidate.href); - } - CodeDescription2.is = is; - })(CodeDescription || (CodeDescription = {})); - (function(Diagnostic8) { - function create(range, message, severity, code, source, relatedInformation) { - var result = { range, message }; - if (Is.defined(severity)) { - result.severity = severity; - } - if (Is.defined(code)) { - result.code = code; - } - if (Is.defined(source)) { - result.source = source; - } - if (Is.defined(relatedInformation)) { - result.relatedInformation = relatedInformation; - } - return result; - } - Diagnostic8.create = create; - function is(value) { - var _a2; - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a2 = candidate.codeDescription) === null || _a2 === void 0 ? void 0 : _a2.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is)); - } - Diagnostic8.is = is; - })(Diagnostic || (Diagnostic = {})); - (function(Command5) { - function create(title, command) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var result = { title, command }; - if (Is.defined(args) && args.length > 0) { - result.arguments = args; - } - return result; - } - Command5.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command); - } - Command5.is = is; - })(Command || (Command = {})); - (function(TextEdit20) { - function replace(range, newText) { - return { range, newText }; - } - TextEdit20.replace = replace; - function insert(position, newText) { - return { range: { start: position, end: position }, newText }; - } - TextEdit20.insert = insert; - function del(range) { - return { range, newText: "" }; - } - TextEdit20.del = del; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range); - } - TextEdit20.is = is; - })(TextEdit || (TextEdit = {})); - (function(ChangeAnnotation2) { - function create(label, needsConfirmation, description) { - var result = { label }; - if (needsConfirmation !== void 0) { - result.needsConfirmation = needsConfirmation; - } - if (description !== void 0) { - result.description = description; - } - return result; - } - ChangeAnnotation2.create = create; - function is(value) { - var candidate = value; - return candidate !== void 0 && Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === void 0) && (Is.string(candidate.description) || candidate.description === void 0); - } - ChangeAnnotation2.is = is; - })(ChangeAnnotation || (ChangeAnnotation = {})); - (function(ChangeAnnotationIdentifier2) { - function is(value) { - var candidate = value; - return typeof candidate === "string"; - } - ChangeAnnotationIdentifier2.is = is; - })(ChangeAnnotationIdentifier || (ChangeAnnotationIdentifier = {})); - (function(AnnotatedTextEdit2) { - function replace(range, newText, annotation) { - return { range, newText, annotationId: annotation }; - } - AnnotatedTextEdit2.replace = replace; - function insert(position, newText, annotation) { - return { range: { start: position, end: position }, newText, annotationId: annotation }; - } - AnnotatedTextEdit2.insert = insert; - function del(range, annotation) { - return { range, newText: "", annotationId: annotation }; - } - AnnotatedTextEdit2.del = del; - function is(value) { - var candidate = value; - return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - AnnotatedTextEdit2.is = is; - })(AnnotatedTextEdit || (AnnotatedTextEdit = {})); - (function(TextDocumentEdit6) { - function create(textDocument, edits) { - return { textDocument, edits }; - } - TextDocumentEdit6.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits); - } - TextDocumentEdit6.is = is; - })(TextDocumentEdit || (TextDocumentEdit = {})); - (function(CreateFile3) { - function create(uri, options, annotation) { - var result = { - kind: "create", - uri - }; - if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) { - result.options = options; - } - if (annotation !== void 0) { - result.annotationId = annotation; - } - return result; - } - CreateFile3.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === "create" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - CreateFile3.is = is; - })(CreateFile || (CreateFile = {})); - (function(RenameFile3) { - function create(oldUri, newUri, options, annotation) { - var result = { - kind: "rename", - oldUri, - newUri - }; - if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) { - result.options = options; - } - if (annotation !== void 0) { - result.annotationId = annotation; - } - return result; - } - RenameFile3.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === "rename" && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - RenameFile3.is = is; - })(RenameFile || (RenameFile = {})); - (function(DeleteFile3) { - function create(uri, options, annotation) { - var result = { - kind: "delete", - uri - }; - if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) { - result.options = options; - } - if (annotation !== void 0) { - result.annotationId = annotation; - } - return result; - } - DeleteFile3.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === "delete" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - DeleteFile3.is = is; - })(DeleteFile || (DeleteFile = {})); - (function(WorkspaceEdit10) { - function is(value) { - var candidate = value; - return candidate && (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && (candidate.documentChanges === void 0 || candidate.documentChanges.every(function(change) { - if (Is.string(change.kind)) { - return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change); - } else { - return TextDocumentEdit.is(change); - } - })); - } - WorkspaceEdit10.is = is; - })(WorkspaceEdit || (WorkspaceEdit = {})); - TextEditChangeImpl = function() { - function TextEditChangeImpl2(edits, changeAnnotations) { - this.edits = edits; - this.changeAnnotations = changeAnnotations; - } - TextEditChangeImpl2.prototype.insert = function(position, newText, annotation) { - var edit2; - var id; - if (annotation === void 0) { - edit2 = TextEdit.insert(position, newText); - } else if (ChangeAnnotationIdentifier.is(annotation)) { - id = annotation; - edit2 = AnnotatedTextEdit.insert(position, newText, annotation); - } else { - this.assertChangeAnnotations(this.changeAnnotations); - id = this.changeAnnotations.manage(annotation); - edit2 = AnnotatedTextEdit.insert(position, newText, id); - } - this.edits.push(edit2); - if (id !== void 0) { - return id; - } - }; - TextEditChangeImpl2.prototype.replace = function(range, newText, annotation) { - var edit2; - var id; - if (annotation === void 0) { - edit2 = TextEdit.replace(range, newText); - } else if (ChangeAnnotationIdentifier.is(annotation)) { - id = annotation; - edit2 = AnnotatedTextEdit.replace(range, newText, annotation); - } else { - this.assertChangeAnnotations(this.changeAnnotations); - id = this.changeAnnotations.manage(annotation); - edit2 = AnnotatedTextEdit.replace(range, newText, id); - } - this.edits.push(edit2); - if (id !== void 0) { - return id; - } - }; - TextEditChangeImpl2.prototype.delete = function(range, annotation) { - var edit2; - var id; - if (annotation === void 0) { - edit2 = TextEdit.del(range); - } else if (ChangeAnnotationIdentifier.is(annotation)) { - id = annotation; - edit2 = AnnotatedTextEdit.del(range, annotation); - } else { - this.assertChangeAnnotations(this.changeAnnotations); - id = this.changeAnnotations.manage(annotation); - edit2 = AnnotatedTextEdit.del(range, id); - } - this.edits.push(edit2); - if (id !== void 0) { - return id; - } - }; - TextEditChangeImpl2.prototype.add = function(edit2) { - this.edits.push(edit2); - }; - TextEditChangeImpl2.prototype.all = function() { - return this.edits; - }; - TextEditChangeImpl2.prototype.clear = function() { - this.edits.splice(0, this.edits.length); - }; - TextEditChangeImpl2.prototype.assertChangeAnnotations = function(value) { - if (value === void 0) { - throw new Error("Text edit change is not configured to manage change annotations."); - } - }; - return TextEditChangeImpl2; - }(); - ChangeAnnotations = function() { - function ChangeAnnotations2(annotations) { - this._annotations = annotations === void 0 ? Object.create(null) : annotations; - this._counter = 0; - this._size = 0; - } - ChangeAnnotations2.prototype.all = function() { - return this._annotations; - }; - Object.defineProperty(ChangeAnnotations2.prototype, "size", { - get: function() { - return this._size; - }, - enumerable: false, - configurable: true - }); - ChangeAnnotations2.prototype.manage = function(idOrAnnotation, annotation) { - var id; - if (ChangeAnnotationIdentifier.is(idOrAnnotation)) { - id = idOrAnnotation; - } else { - id = this.nextId(); - annotation = idOrAnnotation; - } - if (this._annotations[id] !== void 0) { - throw new Error("Id " + id + " is already in use."); - } - if (annotation === void 0) { - throw new Error("No annotation provided for id " + id); - } - this._annotations[id] = annotation; - this._size++; - return id; - }; - ChangeAnnotations2.prototype.nextId = function() { - this._counter++; - return this._counter.toString(); - }; - return ChangeAnnotations2; - }(); - WorkspaceChange = function() { - function WorkspaceChange2(workspaceEdit) { - var _this = this; - this._textEditChanges = Object.create(null); - if (workspaceEdit !== void 0) { - this._workspaceEdit = workspaceEdit; - if (workspaceEdit.documentChanges) { - this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations); - workspaceEdit.changeAnnotations = this._changeAnnotations.all(); - workspaceEdit.documentChanges.forEach(function(change) { - if (TextDocumentEdit.is(change)) { - var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations); - _this._textEditChanges[change.textDocument.uri] = textEditChange; - } - }); - } else if (workspaceEdit.changes) { - Object.keys(workspaceEdit.changes).forEach(function(key) { - var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]); - _this._textEditChanges[key] = textEditChange; - }); - } - } else { - this._workspaceEdit = {}; - } - } - Object.defineProperty(WorkspaceChange2.prototype, "edit", { - get: function() { - this.initDocumentChanges(); - if (this._changeAnnotations !== void 0) { - if (this._changeAnnotations.size === 0) { - this._workspaceEdit.changeAnnotations = void 0; - } else { - this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); - } - } - return this._workspaceEdit; - }, - enumerable: false, - configurable: true - }); - WorkspaceChange2.prototype.getTextEditChange = function(key) { - if (OptionalVersionedTextDocumentIdentifier.is(key)) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === void 0) { - throw new Error("Workspace edit is not configured for document changes."); - } - var textDocument = { uri: key.uri, version: key.version }; - var result = this._textEditChanges[textDocument.uri]; - if (!result) { - var edits = []; - var textDocumentEdit = { - textDocument, - edits - }; - this._workspaceEdit.documentChanges.push(textDocumentEdit); - result = new TextEditChangeImpl(edits, this._changeAnnotations); - this._textEditChanges[textDocument.uri] = result; - } - return result; - } else { - this.initChanges(); - if (this._workspaceEdit.changes === void 0) { - throw new Error("Workspace edit is not configured for normal text edit changes."); - } - var result = this._textEditChanges[key]; - if (!result) { - var edits = []; - this._workspaceEdit.changes[key] = edits; - result = new TextEditChangeImpl(edits); - this._textEditChanges[key] = result; - } - return result; - } - }; - WorkspaceChange2.prototype.initDocumentChanges = function() { - if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) { - this._changeAnnotations = new ChangeAnnotations(); - this._workspaceEdit.documentChanges = []; - this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); - } - }; - WorkspaceChange2.prototype.initChanges = function() { - if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) { - this._workspaceEdit.changes = Object.create(null); - } - }; - WorkspaceChange2.prototype.createFile = function(uri, optionsOrAnnotation, options) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === void 0) { - throw new Error("Workspace edit is not configured for document changes."); - } - var annotation; - if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { - annotation = optionsOrAnnotation; - } else { - options = optionsOrAnnotation; - } - var operation; - var id; - if (annotation === void 0) { - operation = CreateFile.create(uri, options); - } else { - id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); - operation = CreateFile.create(uri, options, id); - } - this._workspaceEdit.documentChanges.push(operation); - if (id !== void 0) { - return id; - } - }; - WorkspaceChange2.prototype.renameFile = function(oldUri, newUri, optionsOrAnnotation, options) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === void 0) { - throw new Error("Workspace edit is not configured for document changes."); - } - var annotation; - if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { - annotation = optionsOrAnnotation; - } else { - options = optionsOrAnnotation; - } - var operation; - var id; - if (annotation === void 0) { - operation = RenameFile.create(oldUri, newUri, options); - } else { - id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); - operation = RenameFile.create(oldUri, newUri, options, id); - } - this._workspaceEdit.documentChanges.push(operation); - if (id !== void 0) { - return id; - } - }; - WorkspaceChange2.prototype.deleteFile = function(uri, optionsOrAnnotation, options) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === void 0) { - throw new Error("Workspace edit is not configured for document changes."); - } - var annotation; - if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { - annotation = optionsOrAnnotation; - } else { - options = optionsOrAnnotation; - } - var operation; - var id; - if (annotation === void 0) { - operation = DeleteFile.create(uri, options); - } else { - id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); - operation = DeleteFile.create(uri, options, id); - } - this._workspaceEdit.documentChanges.push(operation); - if (id !== void 0) { - return id; - } - }; - return WorkspaceChange2; - }(); - (function(TextDocumentIdentifier2) { - function create(uri) { - return { uri }; - } - TextDocumentIdentifier2.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri); - } - TextDocumentIdentifier2.is = is; - })(TextDocumentIdentifier || (TextDocumentIdentifier = {})); - (function(VersionedTextDocumentIdentifier2) { - function create(uri, version2) { - return { uri, version: version2 }; - } - VersionedTextDocumentIdentifier2.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version); - } - VersionedTextDocumentIdentifier2.is = is; - })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {})); - (function(OptionalVersionedTextDocumentIdentifier2) { - function create(uri, version2) { - return { uri, version: version2 }; - } - OptionalVersionedTextDocumentIdentifier2.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version)); - } - OptionalVersionedTextDocumentIdentifier2.is = is; - })(OptionalVersionedTextDocumentIdentifier || (OptionalVersionedTextDocumentIdentifier = {})); - (function(TextDocumentItem2) { - function create(uri, languageId, version2, text) { - return { uri, languageId, version: version2, text }; - } - TextDocumentItem2.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text); - } - TextDocumentItem2.is = is; - })(TextDocumentItem || (TextDocumentItem = {})); - (function(MarkupKind6) { - MarkupKind6.PlainText = "plaintext"; - MarkupKind6.Markdown = "markdown"; - })(MarkupKind || (MarkupKind = {})); - (function(MarkupKind6) { - function is(value) { - var candidate = value; - return candidate === MarkupKind6.PlainText || candidate === MarkupKind6.Markdown; - } - MarkupKind6.is = is; - })(MarkupKind || (MarkupKind = {})); - (function(MarkupContent7) { - function is(value) { - var candidate = value; - return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value); - } - MarkupContent7.is = is; - })(MarkupContent || (MarkupContent = {})); - (function(CompletionItemKind6) { - CompletionItemKind6.Text = 1; - CompletionItemKind6.Method = 2; - CompletionItemKind6.Function = 3; - CompletionItemKind6.Constructor = 4; - CompletionItemKind6.Field = 5; - CompletionItemKind6.Variable = 6; - CompletionItemKind6.Class = 7; - CompletionItemKind6.Interface = 8; - CompletionItemKind6.Module = 9; - CompletionItemKind6.Property = 10; - CompletionItemKind6.Unit = 11; - CompletionItemKind6.Value = 12; - CompletionItemKind6.Enum = 13; - CompletionItemKind6.Keyword = 14; - CompletionItemKind6.Snippet = 15; - CompletionItemKind6.Color = 16; - CompletionItemKind6.File = 17; - CompletionItemKind6.Reference = 18; - CompletionItemKind6.Folder = 19; - CompletionItemKind6.EnumMember = 20; - CompletionItemKind6.Constant = 21; - CompletionItemKind6.Struct = 22; - CompletionItemKind6.Event = 23; - CompletionItemKind6.Operator = 24; - CompletionItemKind6.TypeParameter = 25; - })(CompletionItemKind || (CompletionItemKind = {})); - (function(InsertTextFormat4) { - InsertTextFormat4.PlainText = 1; - InsertTextFormat4.Snippet = 2; - })(InsertTextFormat || (InsertTextFormat = {})); - (function(CompletionItemTag3) { - CompletionItemTag3.Deprecated = 1; - })(CompletionItemTag || (CompletionItemTag = {})); - (function(InsertReplaceEdit3) { - function create(newText, insert, replace) { - return { newText, insert, replace }; - } - InsertReplaceEdit3.create = create; - function is(value) { - var candidate = value; - return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace); - } - InsertReplaceEdit3.is = is; - })(InsertReplaceEdit || (InsertReplaceEdit = {})); - (function(InsertTextMode4) { - InsertTextMode4.asIs = 1; - InsertTextMode4.adjustIndentation = 2; - })(InsertTextMode || (InsertTextMode = {})); - (function(CompletionItem4) { - function create(label) { - return { label }; - } - CompletionItem4.create = create; - })(CompletionItem || (CompletionItem = {})); - (function(CompletionList4) { - function create(items, isIncomplete) { - return { items: items ? items : [], isIncomplete: !!isIncomplete }; - } - CompletionList4.create = create; - })(CompletionList || (CompletionList = {})); - (function(MarkedString3) { - function fromPlainText(plainText) { - return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); - } - MarkedString3.fromPlainText = fromPlainText; - function is(value) { - var candidate = value; - return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value); - } - MarkedString3.is = is; - })(MarkedString || (MarkedString = {})); - (function(Hover6) { - function is(value) { - var candidate = value; - return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range)); - } - Hover6.is = is; - })(Hover || (Hover = {})); - (function(ParameterInformation2) { - function create(label, documentation) { - return documentation ? { label, documentation } : { label }; - } - ParameterInformation2.create = create; - })(ParameterInformation || (ParameterInformation = {})); - (function(SignatureInformation2) { - function create(label, documentation) { - var parameters = []; - for (var _i = 2; _i < arguments.length; _i++) { - parameters[_i - 2] = arguments[_i]; - } - var result = { label }; - if (Is.defined(documentation)) { - result.documentation = documentation; - } - if (Is.defined(parameters)) { - result.parameters = parameters; - } else { - result.parameters = []; - } - return result; - } - SignatureInformation2.create = create; - })(SignatureInformation || (SignatureInformation = {})); - (function(DocumentHighlightKind4) { - DocumentHighlightKind4.Text = 1; - DocumentHighlightKind4.Read = 2; - DocumentHighlightKind4.Write = 3; - })(DocumentHighlightKind || (DocumentHighlightKind = {})); - (function(DocumentHighlight6) { - function create(range, kind) { - var result = { range }; - if (Is.number(kind)) { - result.kind = kind; - } - return result; - } - DocumentHighlight6.create = create; - })(DocumentHighlight || (DocumentHighlight = {})); - (function(SymbolKind7) { - SymbolKind7.File = 1; - SymbolKind7.Module = 2; - SymbolKind7.Namespace = 3; - SymbolKind7.Package = 4; - SymbolKind7.Class = 5; - SymbolKind7.Method = 6; - SymbolKind7.Property = 7; - SymbolKind7.Field = 8; - SymbolKind7.Constructor = 9; - SymbolKind7.Enum = 10; - SymbolKind7.Interface = 11; - SymbolKind7.Function = 12; - SymbolKind7.Variable = 13; - SymbolKind7.Constant = 14; - SymbolKind7.String = 15; - SymbolKind7.Number = 16; - SymbolKind7.Boolean = 17; - SymbolKind7.Array = 18; - SymbolKind7.Object = 19; - SymbolKind7.Key = 20; - SymbolKind7.Null = 21; - SymbolKind7.EnumMember = 22; - SymbolKind7.Struct = 23; - SymbolKind7.Event = 24; - SymbolKind7.Operator = 25; - SymbolKind7.TypeParameter = 26; - })(SymbolKind || (SymbolKind = {})); - (function(SymbolTag6) { - SymbolTag6.Deprecated = 1; - })(SymbolTag || (SymbolTag = {})); - (function(SymbolInformation8) { - function create(name2, kind, range, uri, containerName) { - var result = { - name: name2, - kind, - location: { uri, range } - }; - if (containerName) { - result.containerName = containerName; - } - return result; - } - SymbolInformation8.create = create; - })(SymbolInformation || (SymbolInformation = {})); - (function(DocumentSymbol8) { - function create(name2, detail, kind, range, selectionRange, children) { - var result = { - name: name2, - detail, - kind, - range, - selectionRange - }; - if (children !== void 0) { - result.children = children; - } - return result; - } - DocumentSymbol8.create = create; - function is(value) { - var candidate = value; - return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === void 0 || Is.string(candidate.detail)) && (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) && (candidate.children === void 0 || Array.isArray(candidate.children)) && (candidate.tags === void 0 || Array.isArray(candidate.tags)); - } - DocumentSymbol8.is = is; - })(DocumentSymbol || (DocumentSymbol = {})); - (function(CodeActionKind10) { - CodeActionKind10.Empty = ""; - CodeActionKind10.QuickFix = "quickfix"; - CodeActionKind10.Refactor = "refactor"; - CodeActionKind10.RefactorExtract = "refactor.extract"; - CodeActionKind10.RefactorInline = "refactor.inline"; - CodeActionKind10.RefactorRewrite = "refactor.rewrite"; - CodeActionKind10.Source = "source"; - CodeActionKind10.SourceOrganizeImports = "source.organizeImports"; - CodeActionKind10.SourceFixAll = "source.fixAll"; - })(CodeActionKind || (CodeActionKind = {})); - (function(CodeActionContext6) { - function create(diagnostics, only) { - var result = { diagnostics }; - if (only !== void 0 && only !== null) { - result.only = only; - } - return result; - } - CodeActionContext6.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string)); - } - CodeActionContext6.is = is; - })(CodeActionContext || (CodeActionContext = {})); - (function(CodeAction9) { - function create(title, kindOrCommandOrEdit, kind) { - var result = { title }; - var checkKind = true; - if (typeof kindOrCommandOrEdit === "string") { - checkKind = false; - result.kind = kindOrCommandOrEdit; - } else if (Command.is(kindOrCommandOrEdit)) { - result.command = kindOrCommandOrEdit; - } else { - result.edit = kindOrCommandOrEdit; - } - if (checkKind && kind !== void 0) { - result.kind = kind; - } - return result; - } - CodeAction9.create = create; - function is(value) { - var candidate = value; - return candidate && Is.string(candidate.title) && (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === void 0 || Is.string(candidate.kind)) && (candidate.edit !== void 0 || candidate.command !== void 0) && (candidate.command === void 0 || Command.is(candidate.command)) && (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) && (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit)); - } - CodeAction9.is = is; - })(CodeAction || (CodeAction = {})); - (function(CodeLens6) { - function create(range, data) { - var result = { range }; - if (Is.defined(data)) { - result.data = data; - } - return result; - } - CodeLens6.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command)); - } - CodeLens6.is = is; - })(CodeLens || (CodeLens = {})); - (function(FormattingOptions7) { - function create(tabSize, insertSpaces) { - return { tabSize, insertSpaces }; - } - FormattingOptions7.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces); - } - FormattingOptions7.is = is; - })(FormattingOptions || (FormattingOptions = {})); - (function(DocumentLink7) { - function create(range, target, data) { - return { range, target, data }; - } - DocumentLink7.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target)); - } - DocumentLink7.is = is; - })(DocumentLink || (DocumentLink = {})); - (function(SelectionRange6) { - function create(range, parent) { - return { range, parent }; - } - SelectionRange6.create = create; - function is(value) { - var candidate = value; - return candidate !== void 0 && Range.is(candidate.range) && (candidate.parent === void 0 || SelectionRange6.is(candidate.parent)); - } - SelectionRange6.is = is; - })(SelectionRange || (SelectionRange = {})); - EOL = ["\n", "\r\n", "\r"]; - (function(TextDocument5) { - function create(uri, languageId, version2, content) { - return new FullTextDocument(uri, languageId, version2, content); - } - TextDocument5.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false; - } - TextDocument5.is = is; - function applyEdits2(document2, edits) { - var text = document2.getText(); - var sortedEdits = mergeSort2(edits, function(a, b) { - var diff = a.range.start.line - b.range.start.line; - if (diff === 0) { - return a.range.start.character - b.range.start.character; - } - return diff; - }); - var lastModifiedOffset = text.length; - for (var i = sortedEdits.length - 1; i >= 0; i--) { - var e = sortedEdits[i]; - var startOffset = document2.offsetAt(e.range.start); - var endOffset = document2.offsetAt(e.range.end); - if (endOffset <= lastModifiedOffset) { - text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); - } else { - throw new Error("Overlapping edit"); - } - lastModifiedOffset = startOffset; - } - return text; - } - TextDocument5.applyEdits = applyEdits2; - function mergeSort2(data, compare) { - if (data.length <= 1) { - return data; - } - var p = data.length / 2 | 0; - var left = data.slice(0, p); - var right = data.slice(p); - mergeSort2(left, compare); - mergeSort2(right, compare); - var leftIdx = 0; - var rightIdx = 0; - var i = 0; - while (leftIdx < left.length && rightIdx < right.length) { - var ret = compare(left[leftIdx], right[rightIdx]); - if (ret <= 0) { - data[i++] = left[leftIdx++]; - } else { - data[i++] = right[rightIdx++]; - } - } - while (leftIdx < left.length) { - data[i++] = left[leftIdx++]; - } - while (rightIdx < right.length) { - data[i++] = right[rightIdx++]; - } - return data; - } - })(TextDocument || (TextDocument = {})); - FullTextDocument = function() { - function FullTextDocument3(uri, languageId, version2, content) { - this._uri = uri; - this._languageId = languageId; - this._version = version2; - this._content = content; - this._lineOffsets = void 0; - } - Object.defineProperty(FullTextDocument3.prototype, "uri", { - get: function() { - return this._uri; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(FullTextDocument3.prototype, "languageId", { - get: function() { - return this._languageId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(FullTextDocument3.prototype, "version", { - get: function() { - return this._version; - }, - enumerable: false, - configurable: true - }); - FullTextDocument3.prototype.getText = function(range) { - if (range) { - var start = this.offsetAt(range.start); - var end = this.offsetAt(range.end); - return this._content.substring(start, end); - } - return this._content; - }; - FullTextDocument3.prototype.update = function(event, version2) { - this._content = event.text; - this._version = version2; - this._lineOffsets = void 0; - }; - FullTextDocument3.prototype.getLineOffsets = function() { - if (this._lineOffsets === void 0) { - var lineOffsets = []; - var text = this._content; - var isLineStart = true; - for (var i = 0; i < text.length; i++) { - if (isLineStart) { - lineOffsets.push(i); - isLineStart = false; - } - var ch = text.charAt(i); - isLineStart = ch === "\r" || ch === "\n"; - if (ch === "\r" && i + 1 < text.length && text.charAt(i + 1) === "\n") { - i++; - } - } - if (isLineStart && text.length > 0) { - lineOffsets.push(text.length); - } - this._lineOffsets = lineOffsets; - } - return this._lineOffsets; - }; - FullTextDocument3.prototype.positionAt = function(offset) { - offset = Math.max(Math.min(offset, this._content.length), 0); - var lineOffsets = this.getLineOffsets(); - var low = 0, high = lineOffsets.length; - if (high === 0) { - return Position.create(0, offset); - } - while (low < high) { - var mid = Math.floor((low + high) / 2); - if (lineOffsets[mid] > offset) { - high = mid; - } else { - low = mid + 1; - } - } - var line = low - 1; - return Position.create(line, offset - lineOffsets[line]); - }; - FullTextDocument3.prototype.offsetAt = function(position) { - var lineOffsets = this.getLineOffsets(); - if (position.line >= lineOffsets.length) { - return this._content.length; - } else if (position.line < 0) { - return 0; - } - var lineOffset = lineOffsets[position.line]; - var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length; - return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); - }; - Object.defineProperty(FullTextDocument3.prototype, "lineCount", { - get: function() { - return this.getLineOffsets().length; - }, - enumerable: false, - configurable: true - }); - return FullTextDocument3; - }(); - (function(Is7) { - var toString = Object.prototype.toString; - function defined(value) { - return typeof value !== "undefined"; - } - Is7.defined = defined; - function undefined2(value) { - return typeof value === "undefined"; - } - Is7.undefined = undefined2; - function boolean2(value) { - return value === true || value === false; - } - Is7.boolean = boolean2; - function string2(value) { - return toString.call(value) === "[object String]"; - } - Is7.string = string2; - function number2(value) { - return toString.call(value) === "[object Number]"; - } - Is7.number = number2; - function numberRange(value, min, max) { - return toString.call(value) === "[object Number]" && min <= value && value <= max; - } - Is7.numberRange = numberRange; - function integer2(value) { - return toString.call(value) === "[object Number]" && -2147483648 <= value && value <= 2147483647; - } - Is7.integer = integer2; - function uinteger3(value) { - return toString.call(value) === "[object Number]" && 0 <= value && value <= 2147483647; - } - Is7.uinteger = uinteger3; - function func2(value) { - return toString.call(value) === "[object Function]"; - } - Is7.func = func2; - function objectLiteral2(value) { - return value !== null && typeof value === "object"; - } - Is7.objectLiteral = objectLiteral2; - function typedArray(value, check) { - return Array.isArray(value) && value.every(check); - } - Is7.typedArray = typedArray; - })(Is || (Is = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/messages.js -var require_messages2 = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/messages.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ProtocolNotificationType = exports2.ProtocolNotificationType0 = exports2.ProtocolRequestType = exports2.ProtocolRequestType0 = exports2.RegistrationType = void 0; - var vscode_jsonrpc_1 = require_main(); - var RegistrationType4 = class { - constructor(method) { - this.method = method; - } - }; - exports2.RegistrationType = RegistrationType4; - var ProtocolRequestType02 = class extends vscode_jsonrpc_1.RequestType0 { - constructor(method) { - super(method); - } - }; - exports2.ProtocolRequestType0 = ProtocolRequestType02; - var ProtocolRequestType3 = class extends vscode_jsonrpc_1.RequestType { - constructor(method) { - super(method, vscode_jsonrpc_1.ParameterStructures.byName); - } - }; - exports2.ProtocolRequestType = ProtocolRequestType3; - var ProtocolNotificationType02 = class extends vscode_jsonrpc_1.NotificationType0 { - constructor(method) { - super(method); - } - }; - exports2.ProtocolNotificationType0 = ProtocolNotificationType02; - var ProtocolNotificationType4 = class extends vscode_jsonrpc_1.NotificationType { - constructor(method) { - super(method, vscode_jsonrpc_1.ParameterStructures.byName); - } - }; - exports2.ProtocolNotificationType = ProtocolNotificationType4; - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/utils/is.js -var require_is2 = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/utils/is.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.objectLiteral = exports2.typedArray = exports2.stringArray = exports2.array = exports2.func = exports2.error = exports2.number = exports2.string = exports2.boolean = void 0; - function boolean2(value) { - return value === true || value === false; - } - exports2.boolean = boolean2; - function string2(value) { - return typeof value === "string" || value instanceof String; - } - exports2.string = string2; - function number2(value) { - return typeof value === "number" || value instanceof Number; - } - exports2.number = number2; - function error(value) { - return value instanceof Error; - } - exports2.error = error; - function func2(value) { - return typeof value === "function"; - } - exports2.func = func2; - function array(value) { - return Array.isArray(value); - } - exports2.array = array; - function stringArray(value) { - return array(value) && value.every((elem) => string2(elem)); - } - exports2.stringArray = stringArray; - function typedArray(value, check) { - return Array.isArray(value) && value.every(check); - } - exports2.typedArray = typedArray; - function objectLiteral2(value) { - return value !== null && typeof value === "object"; - } - exports2.objectLiteral = objectLiteral2; - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js -var require_protocol_implementation = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ImplementationRequest = void 0; - var messages_1 = require_messages2(); - var ImplementationRequest3; - (function(ImplementationRequest4) { - ImplementationRequest4.method = "textDocument/implementation"; - ImplementationRequest4.type = new messages_1.ProtocolRequestType(ImplementationRequest4.method); - })(ImplementationRequest3 = exports2.ImplementationRequest || (exports2.ImplementationRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js -var require_protocol_typeDefinition = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TypeDefinitionRequest = void 0; - var messages_1 = require_messages2(); - var TypeDefinitionRequest3; - (function(TypeDefinitionRequest4) { - TypeDefinitionRequest4.method = "textDocument/typeDefinition"; - TypeDefinitionRequest4.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest4.method); - })(TypeDefinitionRequest3 = exports2.TypeDefinitionRequest || (exports2.TypeDefinitionRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolders.js -var require_protocol_workspaceFolders = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolders.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = void 0; - var messages_1 = require_messages2(); - var WorkspaceFoldersRequest2; - (function(WorkspaceFoldersRequest3) { - WorkspaceFoldersRequest3.type = new messages_1.ProtocolRequestType0("workspace/workspaceFolders"); - })(WorkspaceFoldersRequest2 = exports2.WorkspaceFoldersRequest || (exports2.WorkspaceFoldersRequest = {})); - var DidChangeWorkspaceFoldersNotification2; - (function(DidChangeWorkspaceFoldersNotification3) { - DidChangeWorkspaceFoldersNotification3.type = new messages_1.ProtocolNotificationType("workspace/didChangeWorkspaceFolders"); - })(DidChangeWorkspaceFoldersNotification2 = exports2.DidChangeWorkspaceFoldersNotification || (exports2.DidChangeWorkspaceFoldersNotification = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js -var require_protocol_configuration = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ConfigurationRequest = void 0; - var messages_1 = require_messages2(); - var ConfigurationRequest2; - (function(ConfigurationRequest3) { - ConfigurationRequest3.type = new messages_1.ProtocolRequestType("workspace/configuration"); - })(ConfigurationRequest2 = exports2.ConfigurationRequest || (exports2.ConfigurationRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js -var require_protocol_colorProvider = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ColorPresentationRequest = exports2.DocumentColorRequest = void 0; - var messages_1 = require_messages2(); - var DocumentColorRequest3; - (function(DocumentColorRequest4) { - DocumentColorRequest4.method = "textDocument/documentColor"; - DocumentColorRequest4.type = new messages_1.ProtocolRequestType(DocumentColorRequest4.method); - })(DocumentColorRequest3 = exports2.DocumentColorRequest || (exports2.DocumentColorRequest = {})); - var ColorPresentationRequest2; - (function(ColorPresentationRequest3) { - ColorPresentationRequest3.type = new messages_1.ProtocolRequestType("textDocument/colorPresentation"); - })(ColorPresentationRequest2 = exports2.ColorPresentationRequest || (exports2.ColorPresentationRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js -var require_protocol_foldingRange = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.FoldingRangeRequest = exports2.FoldingRangeKind = void 0; - var messages_1 = require_messages2(); - var FoldingRangeKind2; - (function(FoldingRangeKind3) { - FoldingRangeKind3["Comment"] = "comment"; - FoldingRangeKind3["Imports"] = "imports"; - FoldingRangeKind3["Region"] = "region"; - })(FoldingRangeKind2 = exports2.FoldingRangeKind || (exports2.FoldingRangeKind = {})); - var FoldingRangeRequest3; - (function(FoldingRangeRequest4) { - FoldingRangeRequest4.method = "textDocument/foldingRange"; - FoldingRangeRequest4.type = new messages_1.ProtocolRequestType(FoldingRangeRequest4.method); - })(FoldingRangeRequest3 = exports2.FoldingRangeRequest || (exports2.FoldingRangeRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js -var require_protocol_declaration = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DeclarationRequest = void 0; - var messages_1 = require_messages2(); - var DeclarationRequest3; - (function(DeclarationRequest4) { - DeclarationRequest4.method = "textDocument/declaration"; - DeclarationRequest4.type = new messages_1.ProtocolRequestType(DeclarationRequest4.method); - })(DeclarationRequest3 = exports2.DeclarationRequest || (exports2.DeclarationRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js -var require_protocol_selectionRange = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SelectionRangeRequest = void 0; - var messages_1 = require_messages2(); - var SelectionRangeRequest3; - (function(SelectionRangeRequest4) { - SelectionRangeRequest4.method = "textDocument/selectionRange"; - SelectionRangeRequest4.type = new messages_1.ProtocolRequestType(SelectionRangeRequest4.method); - })(SelectionRangeRequest3 = exports2.SelectionRangeRequest || (exports2.SelectionRangeRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js -var require_protocol_progress = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = void 0; - var vscode_jsonrpc_1 = require_main(); - var messages_1 = require_messages2(); - var WorkDoneProgress3; - (function(WorkDoneProgress4) { - WorkDoneProgress4.type = new vscode_jsonrpc_1.ProgressType(); - function is(value) { - return value === WorkDoneProgress4.type; - } - WorkDoneProgress4.is = is; - })(WorkDoneProgress3 = exports2.WorkDoneProgress || (exports2.WorkDoneProgress = {})); - var WorkDoneProgressCreateRequest2; - (function(WorkDoneProgressCreateRequest3) { - WorkDoneProgressCreateRequest3.type = new messages_1.ProtocolRequestType("window/workDoneProgress/create"); - })(WorkDoneProgressCreateRequest2 = exports2.WorkDoneProgressCreateRequest || (exports2.WorkDoneProgressCreateRequest = {})); - var WorkDoneProgressCancelNotification; - (function(WorkDoneProgressCancelNotification2) { - WorkDoneProgressCancelNotification2.type = new messages_1.ProtocolNotificationType("window/workDoneProgress/cancel"); - })(WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCancelNotification || (exports2.WorkDoneProgressCancelNotification = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js -var require_protocol_callHierarchy = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.CallHierarchyPrepareRequest = void 0; - var messages_1 = require_messages2(); - var CallHierarchyPrepareRequest3; - (function(CallHierarchyPrepareRequest4) { - CallHierarchyPrepareRequest4.method = "textDocument/prepareCallHierarchy"; - CallHierarchyPrepareRequest4.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest4.method); - })(CallHierarchyPrepareRequest3 = exports2.CallHierarchyPrepareRequest || (exports2.CallHierarchyPrepareRequest = {})); - var CallHierarchyIncomingCallsRequest2; - (function(CallHierarchyIncomingCallsRequest3) { - CallHierarchyIncomingCallsRequest3.method = "callHierarchy/incomingCalls"; - CallHierarchyIncomingCallsRequest3.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest3.method); - })(CallHierarchyIncomingCallsRequest2 = exports2.CallHierarchyIncomingCallsRequest || (exports2.CallHierarchyIncomingCallsRequest = {})); - var CallHierarchyOutgoingCallsRequest2; - (function(CallHierarchyOutgoingCallsRequest3) { - CallHierarchyOutgoingCallsRequest3.method = "callHierarchy/outgoingCalls"; - CallHierarchyOutgoingCallsRequest3.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest3.method); - })(CallHierarchyOutgoingCallsRequest2 = exports2.CallHierarchyOutgoingCallsRequest || (exports2.CallHierarchyOutgoingCallsRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js -var require_protocol_semanticTokens = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.SemanticTokensRegistrationType = exports2.TokenFormat = exports2.SemanticTokens = exports2.SemanticTokenModifiers = exports2.SemanticTokenTypes = void 0; - var messages_1 = require_messages2(); - var SemanticTokenTypes2; - (function(SemanticTokenTypes3) { - SemanticTokenTypes3["namespace"] = "namespace"; - SemanticTokenTypes3["type"] = "type"; - SemanticTokenTypes3["class"] = "class"; - SemanticTokenTypes3["enum"] = "enum"; - SemanticTokenTypes3["interface"] = "interface"; - SemanticTokenTypes3["struct"] = "struct"; - SemanticTokenTypes3["typeParameter"] = "typeParameter"; - SemanticTokenTypes3["parameter"] = "parameter"; - SemanticTokenTypes3["variable"] = "variable"; - SemanticTokenTypes3["property"] = "property"; - SemanticTokenTypes3["enumMember"] = "enumMember"; - SemanticTokenTypes3["event"] = "event"; - SemanticTokenTypes3["function"] = "function"; - SemanticTokenTypes3["method"] = "method"; - SemanticTokenTypes3["macro"] = "macro"; - SemanticTokenTypes3["keyword"] = "keyword"; - SemanticTokenTypes3["modifier"] = "modifier"; - SemanticTokenTypes3["comment"] = "comment"; - SemanticTokenTypes3["string"] = "string"; - SemanticTokenTypes3["number"] = "number"; - SemanticTokenTypes3["regexp"] = "regexp"; - SemanticTokenTypes3["operator"] = "operator"; - })(SemanticTokenTypes2 = exports2.SemanticTokenTypes || (exports2.SemanticTokenTypes = {})); - var SemanticTokenModifiers2; - (function(SemanticTokenModifiers3) { - SemanticTokenModifiers3["declaration"] = "declaration"; - SemanticTokenModifiers3["definition"] = "definition"; - SemanticTokenModifiers3["readonly"] = "readonly"; - SemanticTokenModifiers3["static"] = "static"; - SemanticTokenModifiers3["deprecated"] = "deprecated"; - SemanticTokenModifiers3["abstract"] = "abstract"; - SemanticTokenModifiers3["async"] = "async"; - SemanticTokenModifiers3["modification"] = "modification"; - SemanticTokenModifiers3["documentation"] = "documentation"; - SemanticTokenModifiers3["defaultLibrary"] = "defaultLibrary"; - })(SemanticTokenModifiers2 = exports2.SemanticTokenModifiers || (exports2.SemanticTokenModifiers = {})); - var SemanticTokens6; - (function(SemanticTokens7) { - function is(value) { - const candidate = value; - return candidate !== void 0 && (candidate.resultId === void 0 || typeof candidate.resultId === "string") && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === "number"); - } - SemanticTokens7.is = is; - })(SemanticTokens6 = exports2.SemanticTokens || (exports2.SemanticTokens = {})); - var TokenFormat2; - (function(TokenFormat3) { - TokenFormat3.Relative = "relative"; - })(TokenFormat2 = exports2.TokenFormat || (exports2.TokenFormat = {})); - var SemanticTokensRegistrationType3; - (function(SemanticTokensRegistrationType4) { - SemanticTokensRegistrationType4.method = "textDocument/semanticTokens"; - SemanticTokensRegistrationType4.type = new messages_1.RegistrationType(SemanticTokensRegistrationType4.method); - })(SemanticTokensRegistrationType3 = exports2.SemanticTokensRegistrationType || (exports2.SemanticTokensRegistrationType = {})); - var SemanticTokensRequest2; - (function(SemanticTokensRequest3) { - SemanticTokensRequest3.method = "textDocument/semanticTokens/full"; - SemanticTokensRequest3.type = new messages_1.ProtocolRequestType(SemanticTokensRequest3.method); - })(SemanticTokensRequest2 = exports2.SemanticTokensRequest || (exports2.SemanticTokensRequest = {})); - var SemanticTokensDeltaRequest2; - (function(SemanticTokensDeltaRequest3) { - SemanticTokensDeltaRequest3.method = "textDocument/semanticTokens/full/delta"; - SemanticTokensDeltaRequest3.type = new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest3.method); - })(SemanticTokensDeltaRequest2 = exports2.SemanticTokensDeltaRequest || (exports2.SemanticTokensDeltaRequest = {})); - var SemanticTokensRangeRequest2; - (function(SemanticTokensRangeRequest3) { - SemanticTokensRangeRequest3.method = "textDocument/semanticTokens/range"; - SemanticTokensRangeRequest3.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest3.method); - })(SemanticTokensRangeRequest2 = exports2.SemanticTokensRangeRequest || (exports2.SemanticTokensRangeRequest = {})); - var SemanticTokensRefreshRequest2; - (function(SemanticTokensRefreshRequest3) { - SemanticTokensRefreshRequest3.method = `workspace/semanticTokens/refresh`; - SemanticTokensRefreshRequest3.type = new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest3.method); - })(SemanticTokensRefreshRequest2 = exports2.SemanticTokensRefreshRequest || (exports2.SemanticTokensRefreshRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js -var require_protocol_showDocument = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ShowDocumentRequest = void 0; - var messages_1 = require_messages2(); - var ShowDocumentRequest2; - (function(ShowDocumentRequest3) { - ShowDocumentRequest3.method = "window/showDocument"; - ShowDocumentRequest3.type = new messages_1.ProtocolRequestType(ShowDocumentRequest3.method); - })(ShowDocumentRequest2 = exports2.ShowDocumentRequest || (exports2.ShowDocumentRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js -var require_protocol_linkedEditingRange = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.LinkedEditingRangeRequest = void 0; - var messages_1 = require_messages2(); - var LinkedEditingRangeRequest3; - (function(LinkedEditingRangeRequest4) { - LinkedEditingRangeRequest4.method = "textDocument/linkedEditingRange"; - LinkedEditingRangeRequest4.type = new messages_1.ProtocolRequestType(LinkedEditingRangeRequest4.method); - })(LinkedEditingRangeRequest3 = exports2.LinkedEditingRangeRequest || (exports2.LinkedEditingRangeRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js -var require_protocol_fileOperations = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.DidRenameFilesNotification = exports2.WillRenameFilesRequest = exports2.DidCreateFilesNotification = exports2.WillCreateFilesRequest = exports2.FileOperationPatternKind = void 0; - var messages_1 = require_messages2(); - var FileOperationPatternKind2; - (function(FileOperationPatternKind3) { - FileOperationPatternKind3.file = "file"; - FileOperationPatternKind3.folder = "folder"; - })(FileOperationPatternKind2 = exports2.FileOperationPatternKind || (exports2.FileOperationPatternKind = {})); - var WillCreateFilesRequest3; - (function(WillCreateFilesRequest4) { - WillCreateFilesRequest4.method = "workspace/willCreateFiles"; - WillCreateFilesRequest4.type = new messages_1.ProtocolRequestType(WillCreateFilesRequest4.method); - })(WillCreateFilesRequest3 = exports2.WillCreateFilesRequest || (exports2.WillCreateFilesRequest = {})); - var DidCreateFilesNotification3; - (function(DidCreateFilesNotification4) { - DidCreateFilesNotification4.method = "workspace/didCreateFiles"; - DidCreateFilesNotification4.type = new messages_1.ProtocolNotificationType(DidCreateFilesNotification4.method); - })(DidCreateFilesNotification3 = exports2.DidCreateFilesNotification || (exports2.DidCreateFilesNotification = {})); - var WillRenameFilesRequest3; - (function(WillRenameFilesRequest4) { - WillRenameFilesRequest4.method = "workspace/willRenameFiles"; - WillRenameFilesRequest4.type = new messages_1.ProtocolRequestType(WillRenameFilesRequest4.method); - })(WillRenameFilesRequest3 = exports2.WillRenameFilesRequest || (exports2.WillRenameFilesRequest = {})); - var DidRenameFilesNotification3; - (function(DidRenameFilesNotification4) { - DidRenameFilesNotification4.method = "workspace/didRenameFiles"; - DidRenameFilesNotification4.type = new messages_1.ProtocolNotificationType(DidRenameFilesNotification4.method); - })(DidRenameFilesNotification3 = exports2.DidRenameFilesNotification || (exports2.DidRenameFilesNotification = {})); - var DidDeleteFilesNotification3; - (function(DidDeleteFilesNotification4) { - DidDeleteFilesNotification4.method = "workspace/didDeleteFiles"; - DidDeleteFilesNotification4.type = new messages_1.ProtocolNotificationType(DidDeleteFilesNotification4.method); - })(DidDeleteFilesNotification3 = exports2.DidDeleteFilesNotification || (exports2.DidDeleteFilesNotification = {})); - var WillDeleteFilesRequest3; - (function(WillDeleteFilesRequest4) { - WillDeleteFilesRequest4.method = "workspace/willDeleteFiles"; - WillDeleteFilesRequest4.type = new messages_1.ProtocolRequestType(WillDeleteFilesRequest4.method); - })(WillDeleteFilesRequest3 = exports2.WillDeleteFilesRequest || (exports2.WillDeleteFilesRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js -var require_protocol_moniker = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MonikerRequest = exports2.MonikerKind = exports2.UniquenessLevel = void 0; - var messages_1 = require_messages2(); - var UniquenessLevel; - (function(UniquenessLevel2) { - UniquenessLevel2["document"] = "document"; - UniquenessLevel2["project"] = "project"; - UniquenessLevel2["group"] = "group"; - UniquenessLevel2["scheme"] = "scheme"; - UniquenessLevel2["global"] = "global"; - })(UniquenessLevel = exports2.UniquenessLevel || (exports2.UniquenessLevel = {})); - var MonikerKind; - (function(MonikerKind2) { - MonikerKind2["import"] = "import"; - MonikerKind2["export"] = "export"; - MonikerKind2["local"] = "local"; - })(MonikerKind = exports2.MonikerKind || (exports2.MonikerKind = {})); - var MonikerRequest; - (function(MonikerRequest2) { - MonikerRequest2.method = "textDocument/moniker"; - MonikerRequest2.type = new messages_1.ProtocolRequestType(MonikerRequest2.method); - })(MonikerRequest = exports2.MonikerRequest || (exports2.MonikerRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/protocol.js -var require_protocol = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/protocol.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DocumentLinkRequest = exports2.CodeLensRefreshRequest = exports2.CodeLensResolveRequest = exports2.CodeLensRequest = exports2.WorkspaceSymbolRequest = exports2.CodeActionResolveRequest = exports2.CodeActionRequest = exports2.DocumentSymbolRequest = exports2.DocumentHighlightRequest = exports2.ReferencesRequest = exports2.DefinitionRequest = exports2.SignatureHelpRequest = exports2.SignatureHelpTriggerKind = exports2.HoverRequest = exports2.CompletionResolveRequest = exports2.CompletionRequest = exports2.CompletionTriggerKind = exports2.PublishDiagnosticsNotification = exports2.WatchKind = exports2.FileChangeType = exports2.DidChangeWatchedFilesNotification = exports2.WillSaveTextDocumentWaitUntilRequest = exports2.WillSaveTextDocumentNotification = exports2.TextDocumentSaveReason = exports2.DidSaveTextDocumentNotification = exports2.DidCloseTextDocumentNotification = exports2.DidChangeTextDocumentNotification = exports2.TextDocumentContentChangeEvent = exports2.DidOpenTextDocumentNotification = exports2.TextDocumentSyncKind = exports2.TelemetryEventNotification = exports2.LogMessageNotification = exports2.ShowMessageRequest = exports2.ShowMessageNotification = exports2.MessageType = exports2.DidChangeConfigurationNotification = exports2.ExitNotification = exports2.ShutdownRequest = exports2.InitializedNotification = exports2.InitializeError = exports2.InitializeRequest = exports2.WorkDoneProgressOptions = exports2.TextDocumentRegistrationOptions = exports2.StaticRegistrationOptions = exports2.FailureHandlingKind = exports2.ResourceOperationKind = exports2.UnregistrationRequest = exports2.RegistrationRequest = exports2.DocumentSelector = exports2.DocumentFilter = void 0; - exports2.MonikerRequest = exports2.MonikerKind = exports2.UniquenessLevel = exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.WillRenameFilesRequest = exports2.DidRenameFilesNotification = exports2.WillCreateFilesRequest = exports2.DidCreateFilesNotification = exports2.FileOperationPatternKind = exports2.LinkedEditingRangeRequest = exports2.ShowDocumentRequest = exports2.SemanticTokensRegistrationType = exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.TokenFormat = exports2.SemanticTokens = exports2.SemanticTokenModifiers = exports2.SemanticTokenTypes = exports2.CallHierarchyPrepareRequest = exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = exports2.SelectionRangeRequest = exports2.DeclarationRequest = exports2.FoldingRangeRequest = exports2.ColorPresentationRequest = exports2.DocumentColorRequest = exports2.ConfigurationRequest = exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = exports2.TypeDefinitionRequest = exports2.ImplementationRequest = exports2.ApplyWorkspaceEditRequest = exports2.ExecuteCommandRequest = exports2.PrepareRenameRequest = exports2.RenameRequest = exports2.PrepareSupportDefaultBehavior = exports2.DocumentOnTypeFormattingRequest = exports2.DocumentRangeFormattingRequest = exports2.DocumentFormattingRequest = exports2.DocumentLinkResolveRequest = void 0; - var Is7 = require_is2(); - var messages_1 = require_messages2(); - var protocol_implementation_1 = require_protocol_implementation(); - Object.defineProperty(exports2, "ImplementationRequest", { enumerable: true, get: function() { - return protocol_implementation_1.ImplementationRequest; - } }); - var protocol_typeDefinition_1 = require_protocol_typeDefinition(); - Object.defineProperty(exports2, "TypeDefinitionRequest", { enumerable: true, get: function() { - return protocol_typeDefinition_1.TypeDefinitionRequest; - } }); - var protocol_workspaceFolders_1 = require_protocol_workspaceFolders(); - Object.defineProperty(exports2, "WorkspaceFoldersRequest", { enumerable: true, get: function() { - return protocol_workspaceFolders_1.WorkspaceFoldersRequest; - } }); - Object.defineProperty(exports2, "DidChangeWorkspaceFoldersNotification", { enumerable: true, get: function() { - return protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification; - } }); - var protocol_configuration_1 = require_protocol_configuration(); - Object.defineProperty(exports2, "ConfigurationRequest", { enumerable: true, get: function() { - return protocol_configuration_1.ConfigurationRequest; - } }); - var protocol_colorProvider_1 = require_protocol_colorProvider(); - Object.defineProperty(exports2, "DocumentColorRequest", { enumerable: true, get: function() { - return protocol_colorProvider_1.DocumentColorRequest; - } }); - Object.defineProperty(exports2, "ColorPresentationRequest", { enumerable: true, get: function() { - return protocol_colorProvider_1.ColorPresentationRequest; - } }); - var protocol_foldingRange_1 = require_protocol_foldingRange(); - Object.defineProperty(exports2, "FoldingRangeRequest", { enumerable: true, get: function() { - return protocol_foldingRange_1.FoldingRangeRequest; - } }); - var protocol_declaration_1 = require_protocol_declaration(); - Object.defineProperty(exports2, "DeclarationRequest", { enumerable: true, get: function() { - return protocol_declaration_1.DeclarationRequest; - } }); - var protocol_selectionRange_1 = require_protocol_selectionRange(); - Object.defineProperty(exports2, "SelectionRangeRequest", { enumerable: true, get: function() { - return protocol_selectionRange_1.SelectionRangeRequest; - } }); - var protocol_progress_1 = require_protocol_progress(); - Object.defineProperty(exports2, "WorkDoneProgress", { enumerable: true, get: function() { - return protocol_progress_1.WorkDoneProgress; - } }); - Object.defineProperty(exports2, "WorkDoneProgressCreateRequest", { enumerable: true, get: function() { - return protocol_progress_1.WorkDoneProgressCreateRequest; - } }); - Object.defineProperty(exports2, "WorkDoneProgressCancelNotification", { enumerable: true, get: function() { - return protocol_progress_1.WorkDoneProgressCancelNotification; - } }); - var protocol_callHierarchy_1 = require_protocol_callHierarchy(); - Object.defineProperty(exports2, "CallHierarchyIncomingCallsRequest", { enumerable: true, get: function() { - return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest; - } }); - Object.defineProperty(exports2, "CallHierarchyOutgoingCallsRequest", { enumerable: true, get: function() { - return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest; - } }); - Object.defineProperty(exports2, "CallHierarchyPrepareRequest", { enumerable: true, get: function() { - return protocol_callHierarchy_1.CallHierarchyPrepareRequest; - } }); - var protocol_semanticTokens_1 = require_protocol_semanticTokens(); - Object.defineProperty(exports2, "SemanticTokenTypes", { enumerable: true, get: function() { - return protocol_semanticTokens_1.SemanticTokenTypes; - } }); - Object.defineProperty(exports2, "SemanticTokenModifiers", { enumerable: true, get: function() { - return protocol_semanticTokens_1.SemanticTokenModifiers; - } }); - Object.defineProperty(exports2, "SemanticTokens", { enumerable: true, get: function() { - return protocol_semanticTokens_1.SemanticTokens; - } }); - Object.defineProperty(exports2, "TokenFormat", { enumerable: true, get: function() { - return protocol_semanticTokens_1.TokenFormat; - } }); - Object.defineProperty(exports2, "SemanticTokensRequest", { enumerable: true, get: function() { - return protocol_semanticTokens_1.SemanticTokensRequest; - } }); - Object.defineProperty(exports2, "SemanticTokensDeltaRequest", { enumerable: true, get: function() { - return protocol_semanticTokens_1.SemanticTokensDeltaRequest; - } }); - Object.defineProperty(exports2, "SemanticTokensRangeRequest", { enumerable: true, get: function() { - return protocol_semanticTokens_1.SemanticTokensRangeRequest; - } }); - Object.defineProperty(exports2, "SemanticTokensRefreshRequest", { enumerable: true, get: function() { - return protocol_semanticTokens_1.SemanticTokensRefreshRequest; - } }); - Object.defineProperty(exports2, "SemanticTokensRegistrationType", { enumerable: true, get: function() { - return protocol_semanticTokens_1.SemanticTokensRegistrationType; - } }); - var protocol_showDocument_1 = require_protocol_showDocument(); - Object.defineProperty(exports2, "ShowDocumentRequest", { enumerable: true, get: function() { - return protocol_showDocument_1.ShowDocumentRequest; - } }); - var protocol_linkedEditingRange_1 = require_protocol_linkedEditingRange(); - Object.defineProperty(exports2, "LinkedEditingRangeRequest", { enumerable: true, get: function() { - return protocol_linkedEditingRange_1.LinkedEditingRangeRequest; - } }); - var protocol_fileOperations_1 = require_protocol_fileOperations(); - Object.defineProperty(exports2, "FileOperationPatternKind", { enumerable: true, get: function() { - return protocol_fileOperations_1.FileOperationPatternKind; - } }); - Object.defineProperty(exports2, "DidCreateFilesNotification", { enumerable: true, get: function() { - return protocol_fileOperations_1.DidCreateFilesNotification; - } }); - Object.defineProperty(exports2, "WillCreateFilesRequest", { enumerable: true, get: function() { - return protocol_fileOperations_1.WillCreateFilesRequest; - } }); - Object.defineProperty(exports2, "DidRenameFilesNotification", { enumerable: true, get: function() { - return protocol_fileOperations_1.DidRenameFilesNotification; - } }); - Object.defineProperty(exports2, "WillRenameFilesRequest", { enumerable: true, get: function() { - return protocol_fileOperations_1.WillRenameFilesRequest; - } }); - Object.defineProperty(exports2, "DidDeleteFilesNotification", { enumerable: true, get: function() { - return protocol_fileOperations_1.DidDeleteFilesNotification; - } }); - Object.defineProperty(exports2, "WillDeleteFilesRequest", { enumerable: true, get: function() { - return protocol_fileOperations_1.WillDeleteFilesRequest; - } }); - var protocol_moniker_1 = require_protocol_moniker(); - Object.defineProperty(exports2, "UniquenessLevel", { enumerable: true, get: function() { - return protocol_moniker_1.UniquenessLevel; - } }); - Object.defineProperty(exports2, "MonikerKind", { enumerable: true, get: function() { - return protocol_moniker_1.MonikerKind; - } }); - Object.defineProperty(exports2, "MonikerRequest", { enumerable: true, get: function() { - return protocol_moniker_1.MonikerRequest; - } }); - var DocumentFilter; - (function(DocumentFilter2) { - function is(value) { - const candidate = value; - return Is7.string(candidate.language) || Is7.string(candidate.scheme) || Is7.string(candidate.pattern); - } - DocumentFilter2.is = is; - })(DocumentFilter = exports2.DocumentFilter || (exports2.DocumentFilter = {})); - var DocumentSelector40; - (function(DocumentSelector41) { - function is(value) { - if (!Array.isArray(value)) { - return false; - } - for (let elem of value) { - if (!Is7.string(elem) && !DocumentFilter.is(elem)) { - return false; - } - } - return true; - } - DocumentSelector41.is = is; - })(DocumentSelector40 = exports2.DocumentSelector || (exports2.DocumentSelector = {})); - var RegistrationRequest2; - (function(RegistrationRequest3) { - RegistrationRequest3.type = new messages_1.ProtocolRequestType("client/registerCapability"); - })(RegistrationRequest2 = exports2.RegistrationRequest || (exports2.RegistrationRequest = {})); - var UnregistrationRequest2; - (function(UnregistrationRequest3) { - UnregistrationRequest3.type = new messages_1.ProtocolRequestType("client/unregisterCapability"); - })(UnregistrationRequest2 = exports2.UnregistrationRequest || (exports2.UnregistrationRequest = {})); - var ResourceOperationKind2; - (function(ResourceOperationKind3) { - ResourceOperationKind3.Create = "create"; - ResourceOperationKind3.Rename = "rename"; - ResourceOperationKind3.Delete = "delete"; - })(ResourceOperationKind2 = exports2.ResourceOperationKind || (exports2.ResourceOperationKind = {})); - var FailureHandlingKind2; - (function(FailureHandlingKind3) { - FailureHandlingKind3.Abort = "abort"; - FailureHandlingKind3.Transactional = "transactional"; - FailureHandlingKind3.TextOnlyTransactional = "textOnlyTransactional"; - FailureHandlingKind3.Undo = "undo"; - })(FailureHandlingKind2 = exports2.FailureHandlingKind || (exports2.FailureHandlingKind = {})); - var StaticRegistrationOptions2; - (function(StaticRegistrationOptions3) { - function hasId(value) { - const candidate = value; - return candidate && Is7.string(candidate.id) && candidate.id.length > 0; - } - StaticRegistrationOptions3.hasId = hasId; - })(StaticRegistrationOptions2 = exports2.StaticRegistrationOptions || (exports2.StaticRegistrationOptions = {})); - var TextDocumentRegistrationOptions2; - (function(TextDocumentRegistrationOptions3) { - function is(value) { - const candidate = value; - return candidate && (candidate.documentSelector === null || DocumentSelector40.is(candidate.documentSelector)); - } - TextDocumentRegistrationOptions3.is = is; - })(TextDocumentRegistrationOptions2 = exports2.TextDocumentRegistrationOptions || (exports2.TextDocumentRegistrationOptions = {})); - var WorkDoneProgressOptions2; - (function(WorkDoneProgressOptions3) { - function is(value) { - const candidate = value; - return Is7.objectLiteral(candidate) && (candidate.workDoneProgress === void 0 || Is7.boolean(candidate.workDoneProgress)); - } - WorkDoneProgressOptions3.is = is; - function hasWorkDoneProgress(value) { - const candidate = value; - return candidate && Is7.boolean(candidate.workDoneProgress); - } - WorkDoneProgressOptions3.hasWorkDoneProgress = hasWorkDoneProgress; - })(WorkDoneProgressOptions2 = exports2.WorkDoneProgressOptions || (exports2.WorkDoneProgressOptions = {})); - var InitializeRequest2; - (function(InitializeRequest3) { - InitializeRequest3.type = new messages_1.ProtocolRequestType("initialize"); - })(InitializeRequest2 = exports2.InitializeRequest || (exports2.InitializeRequest = {})); - var InitializeError2; - (function(InitializeError3) { - InitializeError3.unknownProtocolVersion = 1; - })(InitializeError2 = exports2.InitializeError || (exports2.InitializeError = {})); - var InitializedNotification2; - (function(InitializedNotification3) { - InitializedNotification3.type = new messages_1.ProtocolNotificationType("initialized"); - })(InitializedNotification2 = exports2.InitializedNotification || (exports2.InitializedNotification = {})); - var ShutdownRequest2; - (function(ShutdownRequest3) { - ShutdownRequest3.type = new messages_1.ProtocolRequestType0("shutdown"); - })(ShutdownRequest2 = exports2.ShutdownRequest || (exports2.ShutdownRequest = {})); - var ExitNotification2; - (function(ExitNotification3) { - ExitNotification3.type = new messages_1.ProtocolNotificationType0("exit"); - })(ExitNotification2 = exports2.ExitNotification || (exports2.ExitNotification = {})); - var DidChangeConfigurationNotification2; - (function(DidChangeConfigurationNotification3) { - DidChangeConfigurationNotification3.type = new messages_1.ProtocolNotificationType("workspace/didChangeConfiguration"); - })(DidChangeConfigurationNotification2 = exports2.DidChangeConfigurationNotification || (exports2.DidChangeConfigurationNotification = {})); - var MessageType2; - (function(MessageType3) { - MessageType3.Error = 1; - MessageType3.Warning = 2; - MessageType3.Info = 3; - MessageType3.Log = 4; - })(MessageType2 = exports2.MessageType || (exports2.MessageType = {})); - var ShowMessageNotification2; - (function(ShowMessageNotification3) { - ShowMessageNotification3.type = new messages_1.ProtocolNotificationType("window/showMessage"); - })(ShowMessageNotification2 = exports2.ShowMessageNotification || (exports2.ShowMessageNotification = {})); - var ShowMessageRequest2; - (function(ShowMessageRequest3) { - ShowMessageRequest3.type = new messages_1.ProtocolRequestType("window/showMessageRequest"); - })(ShowMessageRequest2 = exports2.ShowMessageRequest || (exports2.ShowMessageRequest = {})); - var LogMessageNotification2; - (function(LogMessageNotification3) { - LogMessageNotification3.type = new messages_1.ProtocolNotificationType("window/logMessage"); - })(LogMessageNotification2 = exports2.LogMessageNotification || (exports2.LogMessageNotification = {})); - var TelemetryEventNotification2; - (function(TelemetryEventNotification3) { - TelemetryEventNotification3.type = new messages_1.ProtocolNotificationType("telemetry/event"); - })(TelemetryEventNotification2 = exports2.TelemetryEventNotification || (exports2.TelemetryEventNotification = {})); - var TextDocumentSyncKind2; - (function(TextDocumentSyncKind3) { - TextDocumentSyncKind3.None = 0; - TextDocumentSyncKind3.Full = 1; - TextDocumentSyncKind3.Incremental = 2; - })(TextDocumentSyncKind2 = exports2.TextDocumentSyncKind || (exports2.TextDocumentSyncKind = {})); - var DidOpenTextDocumentNotification2; - (function(DidOpenTextDocumentNotification3) { - DidOpenTextDocumentNotification3.method = "textDocument/didOpen"; - DidOpenTextDocumentNotification3.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification3.method); - })(DidOpenTextDocumentNotification2 = exports2.DidOpenTextDocumentNotification || (exports2.DidOpenTextDocumentNotification = {})); - var TextDocumentContentChangeEvent2; - (function(TextDocumentContentChangeEvent3) { - function isIncremental(event) { - let candidate = event; - return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range !== void 0 && (candidate.rangeLength === void 0 || typeof candidate.rangeLength === "number"); - } - TextDocumentContentChangeEvent3.isIncremental = isIncremental; - function isFull(event) { - let candidate = event; - return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range === void 0 && candidate.rangeLength === void 0; - } - TextDocumentContentChangeEvent3.isFull = isFull; - })(TextDocumentContentChangeEvent2 = exports2.TextDocumentContentChangeEvent || (exports2.TextDocumentContentChangeEvent = {})); - var DidChangeTextDocumentNotification2; - (function(DidChangeTextDocumentNotification3) { - DidChangeTextDocumentNotification3.method = "textDocument/didChange"; - DidChangeTextDocumentNotification3.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification3.method); - })(DidChangeTextDocumentNotification2 = exports2.DidChangeTextDocumentNotification || (exports2.DidChangeTextDocumentNotification = {})); - var DidCloseTextDocumentNotification2; - (function(DidCloseTextDocumentNotification3) { - DidCloseTextDocumentNotification3.method = "textDocument/didClose"; - DidCloseTextDocumentNotification3.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification3.method); - })(DidCloseTextDocumentNotification2 = exports2.DidCloseTextDocumentNotification || (exports2.DidCloseTextDocumentNotification = {})); - var DidSaveTextDocumentNotification2; - (function(DidSaveTextDocumentNotification3) { - DidSaveTextDocumentNotification3.method = "textDocument/didSave"; - DidSaveTextDocumentNotification3.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification3.method); - })(DidSaveTextDocumentNotification2 = exports2.DidSaveTextDocumentNotification || (exports2.DidSaveTextDocumentNotification = {})); - var TextDocumentSaveReason2; - (function(TextDocumentSaveReason3) { - TextDocumentSaveReason3.Manual = 1; - TextDocumentSaveReason3.AfterDelay = 2; - TextDocumentSaveReason3.FocusOut = 3; - })(TextDocumentSaveReason2 = exports2.TextDocumentSaveReason || (exports2.TextDocumentSaveReason = {})); - var WillSaveTextDocumentNotification2; - (function(WillSaveTextDocumentNotification3) { - WillSaveTextDocumentNotification3.method = "textDocument/willSave"; - WillSaveTextDocumentNotification3.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification3.method); - })(WillSaveTextDocumentNotification2 = exports2.WillSaveTextDocumentNotification || (exports2.WillSaveTextDocumentNotification = {})); - var WillSaveTextDocumentWaitUntilRequest2; - (function(WillSaveTextDocumentWaitUntilRequest3) { - WillSaveTextDocumentWaitUntilRequest3.method = "textDocument/willSaveWaitUntil"; - WillSaveTextDocumentWaitUntilRequest3.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest3.method); - })(WillSaveTextDocumentWaitUntilRequest2 = exports2.WillSaveTextDocumentWaitUntilRequest || (exports2.WillSaveTextDocumentWaitUntilRequest = {})); - var DidChangeWatchedFilesNotification2; - (function(DidChangeWatchedFilesNotification3) { - DidChangeWatchedFilesNotification3.type = new messages_1.ProtocolNotificationType("workspace/didChangeWatchedFiles"); - })(DidChangeWatchedFilesNotification2 = exports2.DidChangeWatchedFilesNotification || (exports2.DidChangeWatchedFilesNotification = {})); - var FileChangeType3; - (function(FileChangeType4) { - FileChangeType4.Created = 1; - FileChangeType4.Changed = 2; - FileChangeType4.Deleted = 3; - })(FileChangeType3 = exports2.FileChangeType || (exports2.FileChangeType = {})); - var WatchKind2; - (function(WatchKind3) { - WatchKind3.Create = 1; - WatchKind3.Change = 2; - WatchKind3.Delete = 4; - })(WatchKind2 = exports2.WatchKind || (exports2.WatchKind = {})); - var PublishDiagnosticsNotification2; - (function(PublishDiagnosticsNotification3) { - PublishDiagnosticsNotification3.type = new messages_1.ProtocolNotificationType("textDocument/publishDiagnostics"); - })(PublishDiagnosticsNotification2 = exports2.PublishDiagnosticsNotification || (exports2.PublishDiagnosticsNotification = {})); - var CompletionTriggerKind3; - (function(CompletionTriggerKind4) { - CompletionTriggerKind4.Invoked = 1; - CompletionTriggerKind4.TriggerCharacter = 2; - CompletionTriggerKind4.TriggerForIncompleteCompletions = 3; - })(CompletionTriggerKind3 = exports2.CompletionTriggerKind || (exports2.CompletionTriggerKind = {})); - var CompletionRequest2; - (function(CompletionRequest3) { - CompletionRequest3.method = "textDocument/completion"; - CompletionRequest3.type = new messages_1.ProtocolRequestType(CompletionRequest3.method); - })(CompletionRequest2 = exports2.CompletionRequest || (exports2.CompletionRequest = {})); - var CompletionResolveRequest2; - (function(CompletionResolveRequest3) { - CompletionResolveRequest3.method = "completionItem/resolve"; - CompletionResolveRequest3.type = new messages_1.ProtocolRequestType(CompletionResolveRequest3.method); - })(CompletionResolveRequest2 = exports2.CompletionResolveRequest || (exports2.CompletionResolveRequest = {})); - var HoverRequest2; - (function(HoverRequest3) { - HoverRequest3.method = "textDocument/hover"; - HoverRequest3.type = new messages_1.ProtocolRequestType(HoverRequest3.method); - })(HoverRequest2 = exports2.HoverRequest || (exports2.HoverRequest = {})); - var SignatureHelpTriggerKind3; - (function(SignatureHelpTriggerKind4) { - SignatureHelpTriggerKind4.Invoked = 1; - SignatureHelpTriggerKind4.TriggerCharacter = 2; - SignatureHelpTriggerKind4.ContentChange = 3; - })(SignatureHelpTriggerKind3 = exports2.SignatureHelpTriggerKind || (exports2.SignatureHelpTriggerKind = {})); - var SignatureHelpRequest2; - (function(SignatureHelpRequest3) { - SignatureHelpRequest3.method = "textDocument/signatureHelp"; - SignatureHelpRequest3.type = new messages_1.ProtocolRequestType(SignatureHelpRequest3.method); - })(SignatureHelpRequest2 = exports2.SignatureHelpRequest || (exports2.SignatureHelpRequest = {})); - var DefinitionRequest2; - (function(DefinitionRequest3) { - DefinitionRequest3.method = "textDocument/definition"; - DefinitionRequest3.type = new messages_1.ProtocolRequestType(DefinitionRequest3.method); - })(DefinitionRequest2 = exports2.DefinitionRequest || (exports2.DefinitionRequest = {})); - var ReferencesRequest2; - (function(ReferencesRequest3) { - ReferencesRequest3.method = "textDocument/references"; - ReferencesRequest3.type = new messages_1.ProtocolRequestType(ReferencesRequest3.method); - })(ReferencesRequest2 = exports2.ReferencesRequest || (exports2.ReferencesRequest = {})); - var DocumentHighlightRequest2; - (function(DocumentHighlightRequest3) { - DocumentHighlightRequest3.method = "textDocument/documentHighlight"; - DocumentHighlightRequest3.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest3.method); - })(DocumentHighlightRequest2 = exports2.DocumentHighlightRequest || (exports2.DocumentHighlightRequest = {})); - var DocumentSymbolRequest2; - (function(DocumentSymbolRequest3) { - DocumentSymbolRequest3.method = "textDocument/documentSymbol"; - DocumentSymbolRequest3.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest3.method); - })(DocumentSymbolRequest2 = exports2.DocumentSymbolRequest || (exports2.DocumentSymbolRequest = {})); - var CodeActionRequest2; - (function(CodeActionRequest3) { - CodeActionRequest3.method = "textDocument/codeAction"; - CodeActionRequest3.type = new messages_1.ProtocolRequestType(CodeActionRequest3.method); - })(CodeActionRequest2 = exports2.CodeActionRequest || (exports2.CodeActionRequest = {})); - var CodeActionResolveRequest2; - (function(CodeActionResolveRequest3) { - CodeActionResolveRequest3.method = "codeAction/resolve"; - CodeActionResolveRequest3.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest3.method); - })(CodeActionResolveRequest2 = exports2.CodeActionResolveRequest || (exports2.CodeActionResolveRequest = {})); - var WorkspaceSymbolRequest2; - (function(WorkspaceSymbolRequest3) { - WorkspaceSymbolRequest3.method = "workspace/symbol"; - WorkspaceSymbolRequest3.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest3.method); - })(WorkspaceSymbolRequest2 = exports2.WorkspaceSymbolRequest || (exports2.WorkspaceSymbolRequest = {})); - var CodeLensRequest2; - (function(CodeLensRequest3) { - CodeLensRequest3.method = "textDocument/codeLens"; - CodeLensRequest3.type = new messages_1.ProtocolRequestType(CodeLensRequest3.method); - })(CodeLensRequest2 = exports2.CodeLensRequest || (exports2.CodeLensRequest = {})); - var CodeLensResolveRequest2; - (function(CodeLensResolveRequest3) { - CodeLensResolveRequest3.method = "codeLens/resolve"; - CodeLensResolveRequest3.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest3.method); - })(CodeLensResolveRequest2 = exports2.CodeLensResolveRequest || (exports2.CodeLensResolveRequest = {})); - var CodeLensRefreshRequest2; - (function(CodeLensRefreshRequest3) { - CodeLensRefreshRequest3.method = `workspace/codeLens/refresh`; - CodeLensRefreshRequest3.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest3.method); - })(CodeLensRefreshRequest2 = exports2.CodeLensRefreshRequest || (exports2.CodeLensRefreshRequest = {})); - var DocumentLinkRequest2; - (function(DocumentLinkRequest3) { - DocumentLinkRequest3.method = "textDocument/documentLink"; - DocumentLinkRequest3.type = new messages_1.ProtocolRequestType(DocumentLinkRequest3.method); - })(DocumentLinkRequest2 = exports2.DocumentLinkRequest || (exports2.DocumentLinkRequest = {})); - var DocumentLinkResolveRequest2; - (function(DocumentLinkResolveRequest3) { - DocumentLinkResolveRequest3.method = "documentLink/resolve"; - DocumentLinkResolveRequest3.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest3.method); - })(DocumentLinkResolveRequest2 = exports2.DocumentLinkResolveRequest || (exports2.DocumentLinkResolveRequest = {})); - var DocumentFormattingRequest2; - (function(DocumentFormattingRequest3) { - DocumentFormattingRequest3.method = "textDocument/formatting"; - DocumentFormattingRequest3.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest3.method); - })(DocumentFormattingRequest2 = exports2.DocumentFormattingRequest || (exports2.DocumentFormattingRequest = {})); - var DocumentRangeFormattingRequest2; - (function(DocumentRangeFormattingRequest3) { - DocumentRangeFormattingRequest3.method = "textDocument/rangeFormatting"; - DocumentRangeFormattingRequest3.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest3.method); - })(DocumentRangeFormattingRequest2 = exports2.DocumentRangeFormattingRequest || (exports2.DocumentRangeFormattingRequest = {})); - var DocumentOnTypeFormattingRequest2; - (function(DocumentOnTypeFormattingRequest3) { - DocumentOnTypeFormattingRequest3.method = "textDocument/onTypeFormatting"; - DocumentOnTypeFormattingRequest3.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest3.method); - })(DocumentOnTypeFormattingRequest2 = exports2.DocumentOnTypeFormattingRequest || (exports2.DocumentOnTypeFormattingRequest = {})); - var PrepareSupportDefaultBehavior; - (function(PrepareSupportDefaultBehavior2) { - PrepareSupportDefaultBehavior2.Identifier = 1; - })(PrepareSupportDefaultBehavior = exports2.PrepareSupportDefaultBehavior || (exports2.PrepareSupportDefaultBehavior = {})); - var RenameRequest2; - (function(RenameRequest3) { - RenameRequest3.method = "textDocument/rename"; - RenameRequest3.type = new messages_1.ProtocolRequestType(RenameRequest3.method); - })(RenameRequest2 = exports2.RenameRequest || (exports2.RenameRequest = {})); - var PrepareRenameRequest2; - (function(PrepareRenameRequest3) { - PrepareRenameRequest3.method = "textDocument/prepareRename"; - PrepareRenameRequest3.type = new messages_1.ProtocolRequestType(PrepareRenameRequest3.method); - })(PrepareRenameRequest2 = exports2.PrepareRenameRequest || (exports2.PrepareRenameRequest = {})); - var ExecuteCommandRequest2; - (function(ExecuteCommandRequest3) { - ExecuteCommandRequest3.type = new messages_1.ProtocolRequestType("workspace/executeCommand"); - })(ExecuteCommandRequest2 = exports2.ExecuteCommandRequest || (exports2.ExecuteCommandRequest = {})); - var ApplyWorkspaceEditRequest2; - (function(ApplyWorkspaceEditRequest3) { - ApplyWorkspaceEditRequest3.type = new messages_1.ProtocolRequestType("workspace/applyEdit"); - })(ApplyWorkspaceEditRequest2 = exports2.ApplyWorkspaceEditRequest || (exports2.ApplyWorkspaceEditRequest = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/connection.js -var require_connection3 = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/connection.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createProtocolConnection = void 0; - var vscode_jsonrpc_1 = require_main(); - function createProtocolConnection2(input, output, logger113, options) { - if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) { - options = { connectionStrategy: options }; - } - return vscode_jsonrpc_1.createMessageConnection(input, output, logger113, options); - } - exports2.createProtocolConnection = createProtocolConnection2; - } -}); - -// node_modules/vscode-languageserver-protocol/lib/common/api.js -var require_api3 = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/common/api.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { - return m[k]; - } }); - } : function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; - o[k2] = m[k]; - }); - var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) - if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) - __createBinding(exports3, m, p); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.LSPErrorCodes = exports2.createProtocolConnection = void 0; - __exportStar(require_main(), exports2); - __exportStar((init_main(), main_exports), exports2); - __exportStar(require_messages2(), exports2); - __exportStar(require_protocol(), exports2); - var connection_1 = require_connection3(); - Object.defineProperty(exports2, "createProtocolConnection", { enumerable: true, get: function() { - return connection_1.createProtocolConnection; - } }); - var LSPErrorCodes2; - (function(LSPErrorCodes3) { - LSPErrorCodes3.lspReservedErrorRangeStart = -32899; - LSPErrorCodes3.ContentModified = -32801; - LSPErrorCodes3.RequestCancelled = -32800; - LSPErrorCodes3.lspReservedErrorRangeEnd = -32800; - })(LSPErrorCodes2 = exports2.LSPErrorCodes || (exports2.LSPErrorCodes = {})); - } -}); - -// node_modules/vscode-languageserver-protocol/lib/node/main.js -var require_main2 = __commonJS({ - "node_modules/vscode-languageserver-protocol/lib/node/main.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { - return m[k]; - } }); - } : function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; - o[k2] = m[k]; - }); - var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) - if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) - __createBinding(exports3, m, p); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createProtocolConnection = void 0; - var node_1 = require_node2(); - __exportStar(require_node2(), exports2); - __exportStar(require_api3(), exports2); - function createProtocolConnection2(input, output, logger113, options) { - return node_1.createMessageConnection(input, output, logger113, options); - } - exports2.createProtocolConnection = createProtocolConnection2; - } -}); - -// node_modules/debounce/index.js -var require_debounce = __commonJS({ - "node_modules/debounce/index.js"(exports2, module2) { - function debounce15(func2, wait2, immediate) { - var timeout, args, context, timestamp, result; - if (wait2 == null) - wait2 = 100; - function later() { - var last = Date.now() - timestamp; - if (last < wait2 && last >= 0) { - timeout = setTimeout(later, wait2 - last); - } else { - timeout = null; - if (!immediate) { - result = func2.apply(context, args); - context = args = null; - } - } - } - ; - var debounced = function() { - context = this; - args = arguments; - timestamp = Date.now(); - var callNow = immediate && !timeout; - if (!timeout) - timeout = setTimeout(later, wait2); - if (callNow) { - result = func2.apply(context, args); - context = args = null; - } - return result; - }; - debounced.clear = function() { - if (timeout) { - clearTimeout(timeout); - timeout = null; - } - }; - debounced.flush = function() { - if (timeout) { - result = func2.apply(context, args); - context = args = null; - clearTimeout(timeout); - timeout = null; - } - }; - return debounced; - } - debounce15.debounce = debounce15; - module2.exports = debounce15; - } -}); - -// node_modules/rfc-3986/index.js -var require_rfc_3986 = __commonJS({ - "node_modules/rfc-3986/index.js"(exports2, module2) { - "use strict"; - var internals = { - rfc3986: {} - }; - internals.generate = function() { - var or = "|"; - var digit = "0-9"; - var digitOnly = "[" + digit + "]"; - var alpha = "a-zA-Z"; - var alphaOnly = "[" + alpha + "]"; - internals.rfc3986.cidr = digitOnly + or + "[1-2]" + digitOnly + or + "3[0-2]"; - var hexDigit = digit + "A-Fa-f"; - var hexDigitOnly = "[" + hexDigit + "]"; - var unreserved = alpha + digit + "-\\._~"; - var subDelims = "!\\$&'\\(\\)\\*\\+,;="; - var pctEncoded = "%" + hexDigit; - var pchar = unreserved + pctEncoded + subDelims + ":@"; - var pcharOnly = "[" + pchar + "]"; - var zeroPad = "0?"; - var decOctect = "(?:" + zeroPad + zeroPad + digitOnly + or + zeroPad + "[1-9]" + digitOnly + or + "1" + digitOnly + digitOnly + or + "2[0-4]" + digitOnly + or + "25[0-5])"; - internals.rfc3986.IPv4address = "(?:" + decOctect + "\\.){3}" + decOctect; - var h16 = hexDigitOnly + "{1,4}"; - var ls32 = "(?:" + h16 + ":" + h16 + "|" + internals.rfc3986.IPv4address + ")"; - var IPv6SixHex = "(?:" + h16 + ":){6}" + ls32; - var IPv6FiveHex = "::(?:" + h16 + ":){5}" + ls32; - var IPv6FourHex = "(?:" + h16 + ")?::(?:" + h16 + ":){4}" + ls32; - var IPv6ThreeHex = "(?:(?:" + h16 + ":){0,1}" + h16 + ")?::(?:" + h16 + ":){3}" + ls32; - var IPv6TwoHex = "(?:(?:" + h16 + ":){0,2}" + h16 + ")?::(?:" + h16 + ":){2}" + ls32; - var IPv6OneHex = "(?:(?:" + h16 + ":){0,3}" + h16 + ")?::" + h16 + ":" + ls32; - var IPv6NoneHex = "(?:(?:" + h16 + ":){0,4}" + h16 + ")?::" + ls32; - var IPv6NoneHex2 = "(?:(?:" + h16 + ":){0,5}" + h16 + ")?::" + h16; - var IPv6NoneHex3 = "(?:(?:" + h16 + ":){0,6}" + h16 + ")?::"; - internals.rfc3986.IPv6address = "(?:" + IPv6SixHex + or + IPv6FiveHex + or + IPv6FourHex + or + IPv6ThreeHex + or + IPv6TwoHex + or + IPv6OneHex + or + IPv6NoneHex + or + IPv6NoneHex2 + or + IPv6NoneHex3 + ")"; - internals.rfc3986.IPvFuture = "v" + hexDigitOnly + "+\\.[" + unreserved + subDelims + ":]+"; - internals.rfc3986.scheme = alphaOnly + "[" + alpha + digit + "+-\\.]*"; - var userinfo = "[" + unreserved + pctEncoded + subDelims + ":]*"; - internals.rfc3986.IPLiteral = "\\[(?:" + internals.rfc3986.IPv6address + or + internals.rfc3986.IPvFuture + ")\\]"; - var regName = "[" + unreserved + pctEncoded + subDelims + "]{0,255}"; - var host = "(?:" + internals.rfc3986.IPLiteral + or + internals.rfc3986.IPv4address + or + regName + ")"; - var port = digitOnly + "*"; - var authority = "(?:" + userinfo + "@)?" + host + "(?::" + port + ")?"; - var segment = pcharOnly + "*"; - var segmentNz = pcharOnly + "+"; - var pathAbEmpty = "(?:\\/" + segment + ")*"; - var pathAbsolute = "\\/(?:" + segmentNz + pathAbEmpty + ")?"; - var pathRootless = segmentNz + pathAbEmpty; - internals.rfc3986.hierPart = "(?:(?:\\/\\/" + authority + pathAbEmpty + ")" + or + pathAbsolute + or + pathRootless + ")"; - internals.rfc3986.query = "[" + pchar + "\\/\\?]*(?=#|$)"; - internals.rfc3986.fragment = "[" + pchar + "\\/\\?]*"; - internals.rfc3986.uri = "^(?:" + internals.rfc3986.scheme + ":" + internals.rfc3986.hierPart + ")(?:\\?" + internals.rfc3986.query + ")?(?:#" + internals.rfc3986.fragment + ")?$"; - }; - internals.generate(); - module2.exports = internals.rfc3986; - } -}); - -// node_modules/isuri/index.js -var require_isuri = __commonJS({ - "node_modules/isuri/index.js"(exports2, module2) { - "use strict"; - var rfc3986 = require_rfc_3986(); - function escapeRegex(string2) { - return string2.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, "\\$&"); - } - var internals = { - Uri: { - createUriRegex: function(options) { - options = options || {}; - if (typeof options !== "object" || Array.isArray(options)) { - throw new Error("options must be an object"); - } - var customScheme = ""; - if (options.scheme) { - if (!Array.isArray(options.scheme)) { - options.scheme = [options.scheme]; - } - if (options.scheme.length <= 0) { - throw new Error("scheme must have at least 1 scheme specified"); - } - for (var i = 0; i < options.scheme.length; ++i) { - var currentScheme = options.scheme[i]; - if (!(currentScheme instanceof RegExp || typeof currentScheme === "string")) { - throw new Error("scheme must only contain Regular Expressions or Strings"); - } - customScheme = customScheme + (customScheme ? "|" : ""); - if (currentScheme instanceof RegExp) { - customScheme = customScheme + currentScheme.source; - } else { - if (!/[a-zA-Z][a-zA-Z0-9+-\.]*/.test(currentScheme)) { - throw new Error("scheme at position " + i + " must be a valid scheme"); - } - customScheme = customScheme + escapeRegex(currentScheme); - } - } - } - var scheme = "(?:" + (customScheme || rfc3986.scheme) + ")"; - return new RegExp("^(?:" + scheme + ":" + rfc3986.hierPart + ")(?:\\?" + rfc3986.query + ")?(?:#" + rfc3986.fragment + ")?$"); - }, - uriRegex: new RegExp(rfc3986.uri) - } - }; - internals.Uri.isValid = function(val) { - return internals.Uri.uriRegex.test(val); - }; - module2.exports = { - createUriRegex: internals.Uri.createUriRegex, - uriRegex: internals.Uri.uriRegex, - isValid: internals.Uri.isValid - }; - } -}); - -// node_modules/vscode-uri/lib/esm/index.js -function _validateUri(ret, _strict) { - if (!ret.scheme && _strict) { - throw new Error('[UriError]: Scheme is missing: {scheme: "", authority: "' + ret.authority + '", path: "' + ret.path + '", query: "' + ret.query + '", fragment: "' + ret.fragment + '"}'); - } - if (ret.scheme && !_schemePattern.test(ret.scheme)) { - throw new Error("[UriError]: Scheme contains illegal characters."); - } - if (ret.path) { - if (ret.authority) { - if (!_singleSlashStart.test(ret.path)) { - throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character'); - } - } else { - if (_doubleSlashStart.test(ret.path)) { - throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")'); - } - } - } -} -function _schemeFix(scheme, _strict) { - if (!scheme && !_strict) { - return "file"; - } - return scheme; -} -function _referenceResolution(scheme, path36) { - switch (scheme) { - case "https": - case "http": - case "file": - if (!path36) { - path36 = _slash; - } else if (path36[0] !== _slash) { - path36 = _slash + path36; - } - break; - } - return path36; -} -function encodeURIComponentFast(uriComponent, allowSlash) { - var res = void 0; - var nativeEncodePos = -1; - for (var pos = 0; pos < uriComponent.length; pos++) { - var code = uriComponent.charCodeAt(pos); - if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 45 || code === 46 || code === 95 || code === 126 || allowSlash && code === 47) { - if (nativeEncodePos !== -1) { - res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); - nativeEncodePos = -1; - } - if (res !== void 0) { - res += uriComponent.charAt(pos); - } - } else { - if (res === void 0) { - res = uriComponent.substr(0, pos); - } - var escaped = encodeTable[code]; - if (escaped !== void 0) { - if (nativeEncodePos !== -1) { - res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); - nativeEncodePos = -1; - } - res += escaped; - } else if (nativeEncodePos === -1) { - nativeEncodePos = pos; - } - } - } - if (nativeEncodePos !== -1) { - res += encodeURIComponent(uriComponent.substring(nativeEncodePos)); - } - return res !== void 0 ? res : uriComponent; -} -function encodeURIComponentMinimal(path36) { - var res = void 0; - for (var pos = 0; pos < path36.length; pos++) { - var code = path36.charCodeAt(pos); - if (code === 35 || code === 63) { - if (res === void 0) { - res = path36.substr(0, pos); - } - res += encodeTable[code]; - } else { - if (res !== void 0) { - res += path36[pos]; - } - } - } - return res !== void 0 ? res : path36; -} -function uriToFsPath(uri, keepDriveLetterCasing) { - var value; - if (uri.authority && uri.path.length > 1 && uri.scheme === "file") { - value = "//" + uri.authority + uri.path; - } else if (uri.path.charCodeAt(0) === 47 && (uri.path.charCodeAt(1) >= 65 && uri.path.charCodeAt(1) <= 90 || uri.path.charCodeAt(1) >= 97 && uri.path.charCodeAt(1) <= 122) && uri.path.charCodeAt(2) === 58) { - if (!keepDriveLetterCasing) { - value = uri.path[1].toLowerCase() + uri.path.substr(2); - } else { - value = uri.path.substr(1); - } - } else { - value = uri.path; - } - if (isWindows) { - value = value.replace(/\//g, "\\"); - } - return value; -} -function _asFormatted(uri, skipEncoding) { - var encoder = !skipEncoding ? encodeURIComponentFast : encodeURIComponentMinimal; - var res = ""; - var scheme = uri.scheme, authority = uri.authority, path36 = uri.path, query = uri.query, fragment = uri.fragment; - if (scheme) { - res += scheme; - res += ":"; - } - if (authority || scheme === "file") { - res += _slash; - res += _slash; - } - if (authority) { - var idx = authority.indexOf("@"); - if (idx !== -1) { - var userinfo = authority.substr(0, idx); - authority = authority.substr(idx + 1); - idx = userinfo.indexOf(":"); - if (idx === -1) { - res += encoder(userinfo, false); - } else { - res += encoder(userinfo.substr(0, idx), false); - res += ":"; - res += encoder(userinfo.substr(idx + 1), false); - } - res += "@"; - } - authority = authority.toLowerCase(); - idx = authority.indexOf(":"); - if (idx === -1) { - res += encoder(authority, false); - } else { - res += encoder(authority.substr(0, idx), false); - res += authority.substr(idx); - } - } - if (path36) { - if (path36.length >= 3 && path36.charCodeAt(0) === 47 && path36.charCodeAt(2) === 58) { - var code = path36.charCodeAt(1); - if (code >= 65 && code <= 90) { - path36 = "/" + String.fromCharCode(code + 32) + ":" + path36.substr(3); - } - } else if (path36.length >= 2 && path36.charCodeAt(1) === 58) { - var code = path36.charCodeAt(0); - if (code >= 65 && code <= 90) { - path36 = String.fromCharCode(code + 32) + ":" + path36.substr(2); - } - } - res += encoder(path36, true); - } - if (query) { - res += "?"; - res += encoder(query, false); - } - if (fragment) { - res += "#"; - res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment; - } - return res; -} -function decodeURIComponentGraceful(str) { - try { - return decodeURIComponent(str); - } catch (_a2) { - if (str.length > 3) { - return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3)); - } else { - return str; - } - } -} -function percentDecode(str) { - if (!str.match(_rEncodedAsHex)) { - return str; - } - return str.replace(_rEncodedAsHex, function(match) { - return decodeURIComponentGraceful(match); - }); -} -var __extends, _a, isWindows, userAgent, _schemePattern, _singleSlashStart, _doubleSlashStart, _empty, _slash, _regexp, URI, _pathSepMarker, _URI, encodeTable, _rEncodedAsHex; -var init_esm2 = __esm({ - "node_modules/vscode-uri/lib/esm/index.js"() { - "use strict"; - __extends = function() { - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) - if (b2.hasOwnProperty(p)) - d2[p] = b2[p]; - }; - return extendStatics(d, b); - }; - return function(d, b) { - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - }(); - if (typeof process === "object") { - isWindows = process.platform === "win32"; - } else if (typeof navigator === "object") { - userAgent = navigator.userAgent; - isWindows = userAgent.indexOf("Windows") >= 0; - } - _schemePattern = /^\w[\w\d+.-]*$/; - _singleSlashStart = /^\//; - _doubleSlashStart = /^\/\//; - _empty = ""; - _slash = "/"; - _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; - URI = function() { - function URI2(schemeOrData, authority, path36, query, fragment, _strict) { - if (_strict === void 0) { - _strict = false; - } - if (typeof schemeOrData === "object") { - this.scheme = schemeOrData.scheme || _empty; - this.authority = schemeOrData.authority || _empty; - this.path = schemeOrData.path || _empty; - this.query = schemeOrData.query || _empty; - this.fragment = schemeOrData.fragment || _empty; - } else { - this.scheme = _schemeFix(schemeOrData, _strict); - this.authority = authority || _empty; - this.path = _referenceResolution(this.scheme, path36 || _empty); - this.query = query || _empty; - this.fragment = fragment || _empty; - _validateUri(this, _strict); - } - } - URI2.isUri = function(thing) { - if (thing instanceof URI2) { - return true; - } - if (!thing) { - return false; - } - return typeof thing.authority === "string" && typeof thing.fragment === "string" && typeof thing.path === "string" && typeof thing.query === "string" && typeof thing.scheme === "string" && typeof thing.fsPath === "function" && typeof thing.with === "function" && typeof thing.toString === "function"; - }; - Object.defineProperty(URI2.prototype, "fsPath", { - get: function() { - return uriToFsPath(this, false); - }, - enumerable: true, - configurable: true - }); - URI2.prototype.with = function(change) { - if (!change) { - return this; - } - var scheme = change.scheme, authority = change.authority, path36 = change.path, query = change.query, fragment = change.fragment; - if (scheme === void 0) { - scheme = this.scheme; - } else if (scheme === null) { - scheme = _empty; - } - if (authority === void 0) { - authority = this.authority; - } else if (authority === null) { - authority = _empty; - } - if (path36 === void 0) { - path36 = this.path; - } else if (path36 === null) { - path36 = _empty; - } - if (query === void 0) { - query = this.query; - } else if (query === null) { - query = _empty; - } - if (fragment === void 0) { - fragment = this.fragment; - } else if (fragment === null) { - fragment = _empty; - } - if (scheme === this.scheme && authority === this.authority && path36 === this.path && query === this.query && fragment === this.fragment) { - return this; - } - return new _URI(scheme, authority, path36, query, fragment); - }; - URI2.parse = function(value, _strict) { - if (_strict === void 0) { - _strict = false; - } - var match = _regexp.exec(value); - if (!match) { - return new _URI(_empty, _empty, _empty, _empty, _empty); - } - return new _URI(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict); - }; - URI2.file = function(path36) { - var authority = _empty; - if (isWindows) { - path36 = path36.replace(/\\/g, _slash); - } - if (path36[0] === _slash && path36[1] === _slash) { - var idx = path36.indexOf(_slash, 2); - if (idx === -1) { - authority = path36.substring(2); - path36 = _slash; - } else { - authority = path36.substring(2, idx); - path36 = path36.substring(idx) || _slash; - } - } - return new _URI("file", authority, path36, _empty, _empty); - }; - URI2.from = function(components) { - return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment); - }; - URI2.prototype.toString = function(skipEncoding) { - if (skipEncoding === void 0) { - skipEncoding = false; - } - return _asFormatted(this, skipEncoding); - }; - URI2.prototype.toJSON = function() { - return this; - }; - URI2.revive = function(data) { - if (!data) { - return data; - } else if (data instanceof URI2) { - return data; - } else { - var result = new _URI(data); - result._formatted = data.external; - result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null; - return result; - } - }; - return URI2; - }(); - _pathSepMarker = isWindows ? 1 : void 0; - _URI = function(_super) { - __extends(_URI2, _super); - function _URI2() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this._formatted = null; - _this._fsPath = null; - return _this; - } - Object.defineProperty(_URI2.prototype, "fsPath", { - get: function() { - if (!this._fsPath) { - this._fsPath = uriToFsPath(this, false); - } - return this._fsPath; - }, - enumerable: true, - configurable: true - }); - _URI2.prototype.toString = function(skipEncoding) { - if (skipEncoding === void 0) { - skipEncoding = false; - } - if (!skipEncoding) { - if (!this._formatted) { - this._formatted = _asFormatted(this, false); - } - return this._formatted; - } else { - return _asFormatted(this, true); - } - }; - _URI2.prototype.toJSON = function() { - var res = { - $mid: 1 - }; - if (this._fsPath) { - res.fsPath = this._fsPath; - res._sep = _pathSepMarker; - } - if (this._formatted) { - res.external = this._formatted; - } - if (this.path) { - res.path = this.path; - } - if (this.scheme) { - res.scheme = this.scheme; - } - if (this.authority) { - res.authority = this.authority; - } - if (this.query) { - res.query = this.query; - } - if (this.fragment) { - res.fragment = this.fragment; - } - return res; - }; - return _URI2; - }(URI); - encodeTable = (_a = {}, _a[58] = "%3A", _a[47] = "%2F", _a[63] = "%3F", _a[35] = "%23", _a[91] = "%5B", _a[93] = "%5D", _a[64] = "%40", _a[33] = "%21", _a[36] = "%24", _a[38] = "%26", _a[39] = "%27", _a[40] = "%28", _a[41] = "%29", _a[42] = "%2A", _a[43] = "%2B", _a[44] = "%2C", _a[59] = "%3B", _a[61] = "%3D", _a[32] = "%20", _a); - _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g; - } -}); - -// node_modules/isexe/windows.js -var require_windows = __commonJS({ - "node_modules/isexe/windows.js"(exports2, module2) { - module2.exports = isexe; - isexe.sync = sync; - var fs27 = require("fs"); - function checkPathExt(path36, options) { - var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT; - if (!pathext) { - return true; - } - pathext = pathext.split(";"); - if (pathext.indexOf("") !== -1) { - return true; - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase(); - if (p && path36.substr(-p.length).toLowerCase() === p) { - return true; - } - } - return false; - } - function checkStat(stat, path36, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false; - } - return checkPathExt(path36, options); - } - function isexe(path36, options, cb) { - fs27.stat(path36, function(er, stat) { - cb(er, er ? false : checkStat(stat, path36, options)); - }); - } - function sync(path36, options) { - return checkStat(fs27.statSync(path36), path36, options); - } - } -}); - -// node_modules/isexe/mode.js -var require_mode = __commonJS({ - "node_modules/isexe/mode.js"(exports2, module2) { - module2.exports = isexe; - isexe.sync = sync; - var fs27 = require("fs"); - function isexe(path36, options, cb) { - fs27.stat(path36, function(er, stat) { - cb(er, er ? false : checkStat(stat, options)); - }); - } - function sync(path36, options) { - return checkStat(fs27.statSync(path36), options); - } - function checkStat(stat, options) { - return stat.isFile() && checkMode(stat, options); - } - function checkMode(stat, options) { - var mod = stat.mode; - var uid = stat.uid; - var gid = stat.gid; - var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid(); - var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid(); - var u = parseInt("100", 8); - var g = parseInt("010", 8); - var o = parseInt("001", 8); - var ug = u | g; - var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0; - return ret; - } - } -}); - -// node_modules/isexe/index.js -var require_isexe = __commonJS({ - "node_modules/isexe/index.js"(exports2, module2) { - var fs27 = require("fs"); - var core; - if (process.platform === "win32" || global.TESTING_WINDOWS) { - core = require_windows(); - } else { - core = require_mode(); - } - module2.exports = isexe; - isexe.sync = sync; - function isexe(path36, options, cb) { - if (typeof options === "function") { - cb = options; - options = {}; - } - if (!cb) { - if (typeof Promise !== "function") { - throw new TypeError("callback not provided"); - } - return new Promise(function(resolve3, reject) { - isexe(path36, options || {}, function(er, is) { - if (er) { - reject(er); - } else { - resolve3(is); - } - }); - }); - } - core(path36, options || {}, function(er, is) { - if (er) { - if (er.code === "EACCES" || options && options.ignoreErrors) { - er = null; - is = false; - } - } - cb(er, is); - }); - } - function sync(path36, options) { - try { - return core.sync(path36, options || {}); - } catch (er) { - if (options && options.ignoreErrors || er.code === "EACCES") { - return false; - } else { - throw er; - } - } - } - } -}); - -// node_modules/which/which.js -var require_which = __commonJS({ - "node_modules/which/which.js"(exports2, module2) { - var isWindows4 = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys"; - var path36 = require("path"); - var COLON = isWindows4 ? ";" : ":"; - var isexe = require_isexe(); - var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" }); - var getPathInfo = (cmd, opt) => { - const colon = opt.colon || COLON; - const pathEnv = cmd.match(/\//) || isWindows4 && cmd.match(/\\/) ? [""] : [ - ...isWindows4 ? [process.cwd()] : [], - ...(opt.path || process.env.PATH || "").split(colon) - ]; - const pathExtExe = isWindows4 ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : ""; - const pathExt = isWindows4 ? pathExtExe.split(colon) : [""]; - if (isWindows4) { - if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") - pathExt.unshift(""); - } - return { - pathEnv, - pathExt, - pathExtExe - }; - }; - var which5 = (cmd, opt, cb) => { - if (typeof opt === "function") { - cb = opt; - opt = {}; - } - if (!opt) - opt = {}; - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); - const found = []; - const step = (i) => new Promise((resolve3, reject) => { - if (i === pathEnv.length) - return opt.all && found.length ? resolve3(found) : reject(getNotFoundError(cmd)); - const ppRaw = pathEnv[i]; - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; - const pCmd = path36.join(pathPart, cmd); - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; - resolve3(subStep(p, i, 0)); - }); - const subStep = (p, i, ii) => new Promise((resolve3, reject) => { - if (ii === pathExt.length) - return resolve3(step(i + 1)); - const ext = pathExt[ii]; - isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { - if (!er && is) { - if (opt.all) - found.push(p + ext); - else - return resolve3(p + ext); - } - return resolve3(subStep(p, i, ii + 1)); - }); - }); - return cb ? step(0).then((res) => cb(null, res), cb) : step(0); - }; - var whichSync = (cmd, opt) => { - opt = opt || {}; - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); - const found = []; - for (let i = 0; i < pathEnv.length; i++) { - const ppRaw = pathEnv[i]; - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; - const pCmd = path36.join(pathPart, cmd); - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; - for (let j = 0; j < pathExt.length; j++) { - const cur = p + pathExt[j]; - try { - const is = isexe.sync(cur, { pathExt: pathExtExe }); - if (is) { - if (opt.all) - found.push(cur); - else - return cur; - } - } catch (ex) { - } - } - } - if (opt.all && found.length) - return found; - if (opt.nothrow) - return null; - throw getNotFoundError(cmd); - }; - module2.exports = which5; - which5.sync = whichSync; - } -}); - -// src/util/platform.ts -var platform_exports = {}; -__export(platform_exports, { - OS: () => OS, - OperatingSystem: () => OperatingSystem, - Platform: () => Platform, - globals: () => globals, - isLinux: () => isLinux, - isMacintosh: () => isMacintosh, - isNative: () => isNative, - isWeb: () => isWeb, - isWindows: () => isWindows2, - language: () => language, - platform: () => platform -}); -var _isWindows, _isMacintosh, _isLinux, _isNative, _isWeb, language, Platform, _platform, isWindows2, isMacintosh, isLinux, isNative, isWeb, platform, _globals, globals, OperatingSystem, OS; -var init_platform = __esm({ - "src/util/platform.ts"() { - _isWindows = false; - _isMacintosh = false; - _isLinux = false; - _isNative = false; - _isWeb = false; - language = "en"; - if (typeof process === "object" && typeof process.nextTick === "function" && typeof process.platform === "string") { - _isWindows = process.platform === "win32"; - _isMacintosh = process.platform === "darwin"; - _isLinux = process.platform === "linux"; - _isNative = true; - } - (function(Platform2) { - Platform2[Platform2["Web"] = 0] = "Web"; - Platform2[Platform2["Mac"] = 1] = "Mac"; - Platform2[Platform2["Linux"] = 2] = "Linux"; - Platform2[Platform2["Windows"] = 3] = "Windows"; - })(Platform || (Platform = {})); - _platform = 0; - if (_isNative) { - if (_isMacintosh) { - _platform = 1; - } else if (_isWindows) { - _platform = 3; - } else if (_isLinux) { - _platform = 2; - } - } - isWindows2 = _isWindows; - isMacintosh = _isMacintosh; - isLinux = _isLinux; - isNative = _isNative; - isWeb = _isWeb; - platform = _platform; - _globals = typeof self === "object" ? self : typeof global === "object" ? global : {}; - globals = _globals; - (function(OperatingSystem2) { - OperatingSystem2[OperatingSystem2["Windows"] = 1] = "Windows"; - OperatingSystem2[OperatingSystem2["Macintosh"] = 2] = "Macintosh"; - OperatingSystem2[OperatingSystem2["Linux"] = 3] = "Linux"; - })(OperatingSystem || (OperatingSystem = {})); - OS = _isMacintosh ? 2 : _isWindows ? 1 : 3; - } -}); - -// src/util/index.ts -function isMarkdown(content) { - if (import_vscode_languageserver_protocol.MarkupContent.is(content) && content.kind == import_vscode_languageserver_protocol.MarkupKind.Markdown) { - return true; - } - return false; -} -function wait(ms) { - return new Promise((resolve3) => { - setTimeout(() => { - resolve3(void 0); - }, ms); - }); -} -function waitNextTick(fn) { - return new Promise((resolve3) => { - process.nextTick(() => { - fn(); - resolve3(void 0); - }); - }); -} -function getUri(fullpath, id, buftype, isCygwin) { - if (!fullpath) - return `untitled:${id}`; - if (isWindows2 && !isCygwin && !fullpath.startsWith("jdt://")) - fullpath = import_path.default.win32.normalize(fullpath); - if (import_path.default.isAbsolute(fullpath)) - return URI.file(fullpath).toString(); - if (import_isuri.default.isValid(fullpath)) - return URI.parse(fullpath).toString(); - if (buftype != "") - return `${buftype}:${id}`; - return `unknown:${id}`; -} -function disposeAll(disposables) { - while (disposables.length) { - const item = disposables.pop(); - if (item) { - item.dispose(); - } - } -} -function executable(command) { - try { - import_which.default.sync(command); - } catch (e) { - return false; - } - return true; -} -function runCommand(cmd, opts = {}, timeout) { - if (!isWindows2) { - opts.shell = opts.shell || process.env.SHELL; - } - opts.maxBuffer = 500 * 1024; - return new Promise((resolve3, reject) => { - let timer; - if (timeout) { - timer = setTimeout(() => { - reject(new Error(`timeout after ${timeout}s`)); - }, timeout * 1e3); - } - (0, import_child_process.exec)(cmd, opts, (err, stdout, stderr) => { - if (timer) - clearTimeout(timer); - if (err) { - reject(new Error(`exited with ${err.code} -${err} -${stderr}`)); - return; - } - resolve3(stdout); - }); - }); -} -function watchFile(filepath, onChange) { - let callback = (0, import_debounce.default)(onChange, 100); - try { - let watcher = import_fs.default.watch(filepath, { - persistent: true, - recursive: false, - encoding: "utf8" - }, () => { - callback(); - }); - return import_vscode_languageserver_protocol.Disposable.create(() => { - callback.clear(); - watcher.close(); - }); - } catch (e) { - return import_vscode_languageserver_protocol.Disposable.create(() => { - callback.clear(); - }); - } -} -function isRunning(pid) { - try { - let res = process.kill(pid, 0); - return res == true; - } catch (e) { - return e.code === "EPERM"; - } -} -function getKeymapModifier(mode) { - if (mode == "n" || mode == "o" || mode == "x" || mode == "v") - return ""; - if (mode == "i") - return ""; - if (mode == "s") - return ""; - return ""; -} -function concurrent(arr, fn, limit = 3) { - if (arr.length == 0) - return Promise.resolve(); - let finished = 0; - let total = arr.length; - let remain = arr.slice(); - return new Promise((resolve3) => { - let run = (val) => { - let cb = () => { - finished = finished + 1; - if (finished == total) { - resolve3(); - } else if (remain.length) { - let next = remain.shift(); - run(next); - } - }; - fn(val).then(cb, cb); - }; - for (let i = 0; i < Math.min(limit, remain.length); i++) { - let val = remain.shift(); - run(val); - } - }); -} -var import_child_process, import_debounce, import_fs, import_isuri, import_path, import_vscode_languageserver_protocol, import_which, logger, CONFIG_FILE_NAME; -var init_util = __esm({ - "src/util/index.ts"() { - import_child_process = __toModule(require("child_process")); - import_debounce = __toModule(require_debounce()); - import_fs = __toModule(require("fs")); - import_isuri = __toModule(require_isuri()); - import_path = __toModule(require("path")); - import_vscode_languageserver_protocol = __toModule(require_main2()); - init_esm2(); - import_which = __toModule(require_which()); - init_platform(); - logger = require_logger2()("util-index"); - CONFIG_FILE_NAME = "coc-settings.json"; - } -}); - -// src/util/is.ts -function vimCompleteItem(value) { - return value && typeof value.word === "string"; -} -function boolean(value) { - return typeof value === "boolean"; -} -function string(value) { - return typeof value === "string"; -} -function number(value) { - return typeof value === "number"; -} -function func(value) { - return typeof value == "function"; -} -function objectLiteral(obj) { - return obj != null && typeof obj === "object" && !Array.isArray(obj) && !(obj instanceof RegExp) && !(obj instanceof Date); -} -function emptyObject(obj) { - if (!objectLiteral(obj)) { - return false; - } - for (let key in obj) { - if (hasOwnProperty.call(obj, key)) { - return false; - } - } - return true; -} -var hasOwnProperty; -var init_is = __esm({ - "src/util/is.ts"() { - hasOwnProperty = Object.prototype.hasOwnProperty; - } -}); - -// src/util/object.ts -function isEmpty(obj) { - if (!obj) - return true; - if (Array.isArray(obj)) - return obj.length == 0; - return Object.keys(obj).length == 0; -} -function deepClone(obj) { - if (!obj || typeof obj !== "object") { - return obj; - } - if (obj instanceof RegExp) { - return obj; - } - const result = Array.isArray(obj) ? [] : {}; - Object.keys(obj).forEach((key) => { - if (obj[key] && typeof obj[key] === "object") { - result[key] = deepClone(obj[key]); - } else { - result[key] = obj[key]; - } - }); - return result; -} -function deepFreeze(obj) { - if (!obj || typeof obj !== "object") { - return obj; - } - const stack = [obj]; - while (stack.length > 0) { - let obj2 = stack.shift(); - Object.freeze(obj2); - for (const key in obj2) { - if (_hasOwnProperty.call(obj2, key)) { - let prop = obj2[key]; - if (typeof prop === "object" && !Object.isFrozen(prop)) { - stack.push(prop); - } - } - } - } - return obj; -} -function mixin(destination, source, overwrite = true) { - if (!objectLiteral(destination)) { - return source; - } - if (objectLiteral(source)) { - Object.keys(source).forEach((key) => { - if (key in destination) { - if (overwrite) { - if (objectLiteral(destination[key]) && objectLiteral(source[key])) { - mixin(destination[key], source[key], overwrite); - } else { - destination[key] = source[key]; - } - } - } else { - destination[key] = source[key]; - } - }); - } - return destination; -} -function equals(one, other) { - if (one === other) { - return true; - } - if (one === null || one === void 0 || other === null || other === void 0) { - return false; - } - if (typeof one !== typeof other) { - return false; - } - if (typeof one !== "object") { - return false; - } - if (Array.isArray(one) !== Array.isArray(other)) { - return false; - } - let i; - let key; - if (Array.isArray(one)) { - if (one.length !== other.length) { - return false; - } - for (i = 0; i < one.length; i++) { - if (!equals(one[i], other[i])) { - return false; - } - } - } else { - const oneKeys = []; - for (key in one) { - oneKeys.push(key); - } - oneKeys.sort(); - const otherKeys = []; - for (key in other) { - otherKeys.push(key); - } - otherKeys.sort(); - if (!equals(oneKeys, otherKeys)) { - return false; - } - for (i = 0; i < oneKeys.length; i++) { - if (!equals(one[oneKeys[i]], other[oneKeys[i]])) { - return false; - } - } - } - return true; -} -var _hasOwnProperty; -var init_object = __esm({ - "src/util/object.ts"() { - init_is(); - _hasOwnProperty = Object.prototype.hasOwnProperty; - } -}); - -// src/events.ts -var import_vscode_languageserver_protocol2, logger2, Events, events_default; -var init_events = __esm({ - "src/events.ts"() { - import_vscode_languageserver_protocol2 = __toModule(require_main2()); - init_util(); - init_object(); - logger2 = require_logger2()("events"); - Events = class { - constructor() { - this.handlers = new Map(); - this._lastChange = 0; - this._insertMode = false; - this._pumAlignTop = false; - } - get cursor() { - return this._cursor; - } - get pumAlignTop() { - return this._pumAlignTop; - } - get insertMode() { - return this._insertMode; - } - get lastChangeTs() { - return this._lastChange; - } - async fire(event, args) { - let cbs = this.handlers.get(event); - if (event == "InsertEnter") { - this._insertMode = true; - } else if (event == "InsertLeave") { - this._insertMode = false; - } else if (!this._insertMode && (event == "CursorHoldI" || event == "CursorMovedI")) { - this._insertMode = true; - void this.fire("InsertEnter", [args[0]]); - } else if (this._insertMode && (event == "CursorHold" || event == "CursorMoved")) { - this._insertMode = false; - this.fire("InsertLeave", [args[0]]).logError(); - } - if (event == "MenuPopupChanged") { - this._pumAlignTop = args[1] > args[0].row; - } - if (event == "InsertCharPre") { - this._latestInsert = { bufnr: args[1], character: args[0], timestamp: Date.now() }; - } - if (event == "TextChanged") { - this._lastChange = Date.now(); - } - if (event == "TextChangedI" || event == "TextChangedP") { - this._lastChange = Date.now(); - if (this._latestInsert) { - let insert = this._latestInsert; - this._latestInsert = void 0; - if (insert.bufnr == args[0] && Date.now() - insert.timestamp < 200 && args[1].pre.length) { - let character = args[1].pre.slice(-1); - process.nextTick(() => { - void this.fire("TextInsert", [...args, character]); - }); - } - } - } - if (event == "CursorMoved" || event == "CursorMovedI") { - let cursor = { - bufnr: args[0], - lnum: args[1][0], - col: args[1][1], - insert: event == "CursorMovedI" - }; - if (this._cursor && equals(this._cursor, cursor)) - return; - this._cursor = cursor; - } - if (cbs) { - try { - await Promise.all(cbs.map((fn) => fn(args))); - } catch (e) { - if (e.message && e.message.indexOf("transport disconnected") == -1) - return; - logger2.error(`Error on event: ${event}`, e.stack); - } - } - } - on(event, handler, thisArg, disposables) { - if (Array.isArray(event)) { - let arr = disposables || []; - for (let ev of event) { - this.on(ev, handler, thisArg, arr); - } - return import_vscode_languageserver_protocol2.Disposable.create(() => { - disposeAll(arr); - }); - } else { - let arr = this.handlers.get(event) || []; - let stack = Error().stack; - let wrappedhandler = (args) => new Promise((resolve3, reject) => { - let timer; - try { - Promise.resolve(handler.apply(thisArg || null, args)).then(() => { - if (timer) - clearTimeout(timer); - resolve3(void 0); - }, (e) => { - if (timer) - clearTimeout(timer); - reject(e); - }); - timer = setTimeout(() => { - logger2.warn(`Handler of ${event} blocked more than 2s:`, stack); - }, 2e3); - } catch (e) { - reject(e); - } - }); - arr.push(wrappedhandler); - this.handlers.set(event, arr); - let disposable = import_vscode_languageserver_protocol2.Disposable.create(() => { - let idx = arr.indexOf(wrappedhandler); - if (idx !== -1) { - arr.splice(idx, 1); - } - }); - if (disposables) { - disposables.push(disposable); - } - return disposable; - } - } - }; - events_default = new Events(); - } -}); - -// node_modules/marked/src/defaults.js -var require_defaults = __commonJS({ - "node_modules/marked/src/defaults.js"(exports2, module2) { - function getDefaults() { - return { - baseUrl: null, - breaks: false, - extensions: null, - gfm: true, - headerIds: true, - headerPrefix: "", - highlight: null, - langPrefix: "language-", - mangle: true, - pedantic: false, - renderer: null, - sanitize: false, - sanitizer: null, - silent: false, - smartLists: false, - smartypants: false, - tokenizer: null, - walkTokens: null, - xhtml: false - }; - } - function changeDefaults(newDefaults) { - module2.exports.defaults = newDefaults; - } - module2.exports = { - defaults: getDefaults(), - getDefaults, - changeDefaults - }; - } -}); - -// node_modules/marked/src/helpers.js -var require_helpers = __commonJS({ - "node_modules/marked/src/helpers.js"(exports2, module2) { - var escapeTest = /[&<>"']/; - var escapeReplace = /[&<>"']/g; - var escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/; - var escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g; - var escapeReplacements = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - }; - var getEscapeReplacement = (ch) => escapeReplacements[ch]; - function escape(html, encode) { - if (encode) { - if (escapeTest.test(html)) { - return html.replace(escapeReplace, getEscapeReplacement); - } - } else { - if (escapeTestNoEncode.test(html)) { - return html.replace(escapeReplaceNoEncode, getEscapeReplacement); - } - } - return html; - } - var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig; - function unescape2(html) { - return html.replace(unescapeTest, (_, n) => { - n = n.toLowerCase(); - if (n === "colon") - return ":"; - if (n.charAt(0) === "#") { - return n.charAt(1) === "x" ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1)); - } - return ""; - }); - } - var caret = /(^|[^\[])\^/g; - function edit2(regex, opt) { - regex = regex.source || regex; - opt = opt || ""; - const obj = { - replace: (name2, val) => { - val = val.source || val; - val = val.replace(caret, "$1"); - regex = regex.replace(name2, val); - return obj; - }, - getRegex: () => { - return new RegExp(regex, opt); - } - }; - return obj; - } - var nonWordAndColonTest = /[^\w:]/g; - var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; - function cleanUrl(sanitize, base, href) { - if (sanitize) { - let prot; - try { - prot = decodeURIComponent(unescape2(href)).replace(nonWordAndColonTest, "").toLowerCase(); - } catch (e) { - return null; - } - if (prot.indexOf("javascript:") === 0 || prot.indexOf("vbscript:") === 0 || prot.indexOf("data:") === 0) { - return null; - } - } - if (base && !originIndependentUrl.test(href)) { - href = resolveUrl(base, href); - } - try { - href = encodeURI(href).replace(/%25/g, "%"); - } catch (e) { - return null; - } - return href; - } - var baseUrls = {}; - var justDomain = /^[^:]+:\/*[^/]*$/; - var protocol = /^([^:]+:)[\s\S]*$/; - var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/; - function resolveUrl(base, href) { - if (!baseUrls[" " + base]) { - if (justDomain.test(base)) { - baseUrls[" " + base] = base + "/"; - } else { - baseUrls[" " + base] = rtrim(base, "/", true); - } - } - base = baseUrls[" " + base]; - const relativeBase = base.indexOf(":") === -1; - if (href.substring(0, 2) === "//") { - if (relativeBase) { - return href; - } - return base.replace(protocol, "$1") + href; - } else if (href.charAt(0) === "/") { - if (relativeBase) { - return href; - } - return base.replace(domain, "$1") + href; - } else { - return base + href; - } - } - var noopTest = { exec: function noopTest2() { - } }; - function merge(obj) { - let i = 1, target, key; - for (; i < arguments.length; i++) { - target = arguments[i]; - for (key in target) { - if (Object.prototype.hasOwnProperty.call(target, key)) { - obj[key] = target[key]; - } - } - } - return obj; - } - function splitCells(tableRow, count) { - const row = tableRow.replace(/\|/g, (match, offset, str) => { - let escaped = false, curr = offset; - while (--curr >= 0 && str[curr] === "\\") - escaped = !escaped; - if (escaped) { - return "|"; - } else { - return " |"; - } - }), cells = row.split(/ \|/); - let i = 0; - if (cells.length > count) { - cells.splice(count); - } else { - while (cells.length < count) - cells.push(""); - } - for (; i < cells.length; i++) { - cells[i] = cells[i].trim().replace(/\\\|/g, "|"); - } - return cells; - } - function rtrim(str, c, invert) { - const l = str.length; - if (l === 0) { - return ""; - } - let suffLen = 0; - while (suffLen < l) { - const currChar = str.charAt(l - suffLen - 1); - if (currChar === c && !invert) { - suffLen++; - } else if (currChar !== c && invert) { - suffLen++; - } else { - break; - } - } - return str.substr(0, l - suffLen); - } - function findClosingBracket(str, b) { - if (str.indexOf(b[1]) === -1) { - return -1; - } - const l = str.length; - let level = 0, i = 0; - for (; i < l; i++) { - if (str[i] === "\\") { - i++; - } else if (str[i] === b[0]) { - level++; - } else if (str[i] === b[1]) { - level--; - if (level < 0) { - return i; - } - } - } - return -1; - } - function checkSanitizeDeprecation(opt) { - if (opt && opt.sanitize && !opt.silent) { - console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options"); - } - } - function repeatString(pattern, count) { - if (count < 1) { - return ""; - } - let result = ""; - while (count > 1) { - if (count & 1) { - result += pattern; - } - count >>= 1; - pattern += pattern; - } - return result + pattern; - } - module2.exports = { - escape, - unescape: unescape2, - edit: edit2, - cleanUrl, - resolveUrl, - noopTest, - merge, - splitCells, - rtrim, - findClosingBracket, - checkSanitizeDeprecation, - repeatString - }; - } -}); - -// node_modules/marked/src/Tokenizer.js -var require_Tokenizer = __commonJS({ - "node_modules/marked/src/Tokenizer.js"(exports2, module2) { - var { defaults: defaults2 } = require_defaults(); - var { - rtrim, - splitCells, - escape, - findClosingBracket - } = require_helpers(); - function outputLink(cap, link, raw) { - const href = link.href; - const title = link.title ? escape(link.title) : null; - const text = cap[1].replace(/\\([\[\]])/g, "$1"); - if (cap[0].charAt(0) !== "!") { - return { - type: "link", - raw, - href, - title, - text - }; - } else { - return { - type: "image", - raw, - href, - title, - text: escape(text) - }; - } - } - function indentCodeCompensation(raw, text) { - const matchIndentToCode = raw.match(/^(\s+)(?:```)/); - if (matchIndentToCode === null) { - return text; - } - const indentToCode = matchIndentToCode[1]; - return text.split("\n").map((node) => { - const matchIndentInNode = node.match(/^\s+/); - if (matchIndentInNode === null) { - return node; - } - const [indentInNode] = matchIndentInNode; - if (indentInNode.length >= indentToCode.length) { - return node.slice(indentToCode.length); - } - return node; - }).join("\n"); - } - module2.exports = class Tokenizer { - constructor(options) { - this.options = options || defaults2; - } - space(src) { - const cap = this.rules.block.newline.exec(src); - if (cap) { - if (cap[0].length > 1) { - return { - type: "space", - raw: cap[0] - }; - } - return { raw: "\n" }; - } - } - code(src) { - const cap = this.rules.block.code.exec(src); - if (cap) { - const text = cap[0].replace(/^ {1,4}/gm, ""); - return { - type: "code", - raw: cap[0], - codeBlockStyle: "indented", - text: !this.options.pedantic ? rtrim(text, "\n") : text - }; - } - } - fences(src) { - const cap = this.rules.block.fences.exec(src); - if (cap) { - const raw = cap[0]; - const text = indentCodeCompensation(raw, cap[3] || ""); - return { - type: "code", - raw, - lang: cap[2] ? cap[2].trim() : cap[2], - text - }; - } - } - heading(src) { - const cap = this.rules.block.heading.exec(src); - if (cap) { - let text = cap[2].trim(); - if (/#$/.test(text)) { - const trimmed = rtrim(text, "#"); - if (this.options.pedantic) { - text = trimmed.trim(); - } else if (!trimmed || / $/.test(trimmed)) { - text = trimmed.trim(); - } - } - return { - type: "heading", - raw: cap[0], - depth: cap[1].length, - text - }; - } - } - nptable(src) { - const cap = this.rules.block.nptable.exec(src); - if (cap) { - const item = { - type: "table", - header: splitCells(cap[1].replace(/^ *| *\| *$/g, "")), - align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */), - cells: cap[3] ? cap[3].replace(/\n$/, "").split("\n") : [], - raw: cap[0] - }; - if (item.header.length === item.align.length) { - let l = item.align.length; - let i; - for (i = 0; i < l; i++) { - if (/^ *-+: *$/.test(item.align[i])) { - item.align[i] = "right"; - } else if (/^ *:-+: *$/.test(item.align[i])) { - item.align[i] = "center"; - } else if (/^ *:-+ *$/.test(item.align[i])) { - item.align[i] = "left"; - } else { - item.align[i] = null; - } - } - l = item.cells.length; - for (i = 0; i < l; i++) { - item.cells[i] = splitCells(item.cells[i], item.header.length); - } - return item; - } - } - } - hr(src) { - const cap = this.rules.block.hr.exec(src); - if (cap) { - return { - type: "hr", - raw: cap[0] - }; - } - } - blockquote(src) { - const cap = this.rules.block.blockquote.exec(src); - if (cap) { - const text = cap[0].replace(/^ *> ?/gm, ""); - return { - type: "blockquote", - raw: cap[0], - text - }; - } - } - list(src) { - const cap = this.rules.block.list.exec(src); - if (cap) { - let raw = cap[0]; - const bull = cap[2]; - const isordered = bull.length > 1; - const list2 = { - type: "list", - raw, - ordered: isordered, - start: isordered ? +bull.slice(0, -1) : "", - loose: false, - items: [] - }; - const itemMatch = cap[0].match(this.rules.block.item); - let next = false, item, space, bcurr, bnext, addBack, loose, istask, ischecked, endMatch; - let l = itemMatch.length; - bcurr = this.rules.block.listItemStart.exec(itemMatch[0]); - for (let i = 0; i < l; i++) { - item = itemMatch[i]; - raw = item; - if (!this.options.pedantic) { - endMatch = item.match(new RegExp("\\n\\s*\\n {0," + (bcurr[0].length - 1) + "}\\S")); - if (endMatch) { - addBack = item.length - endMatch.index + itemMatch.slice(i + 1).join("\n").length; - list2.raw = list2.raw.substring(0, list2.raw.length - addBack); - item = item.substring(0, endMatch.index); - raw = item; - l = i + 1; - } - } - if (i !== l - 1) { - bnext = this.rules.block.listItemStart.exec(itemMatch[i + 1]); - if (!this.options.pedantic ? bnext[1].length >= bcurr[0].length || bnext[1].length > 3 : bnext[1].length > bcurr[1].length) { - itemMatch.splice(i, 2, itemMatch[i] + (!this.options.pedantic && bnext[1].length < bcurr[0].length && !itemMatch[i].match(/\n$/) ? "" : "\n") + itemMatch[i + 1]); - i--; - l--; - continue; - } else if (!this.options.pedantic || this.options.smartLists ? bnext[2][bnext[2].length - 1] !== bull[bull.length - 1] : isordered === (bnext[2].length === 1)) { - addBack = itemMatch.slice(i + 1).join("\n").length; - list2.raw = list2.raw.substring(0, list2.raw.length - addBack); - i = l - 1; - } - bcurr = bnext; - } - space = item.length; - item = item.replace(/^ *([*+-]|\d+[.)]) ?/, ""); - if (~item.indexOf("\n ")) { - space -= item.length; - item = !this.options.pedantic ? item.replace(new RegExp("^ {1," + space + "}", "gm"), "") : item.replace(/^ {1,4}/gm, ""); - } - item = rtrim(item, "\n"); - if (i !== l - 1) { - raw = raw + "\n"; - } - loose = next || /\n\n(?!\s*$)/.test(raw); - if (i !== l - 1) { - next = raw.slice(-2) === "\n\n"; - if (!loose) - loose = next; - } - if (loose) { - list2.loose = true; - } - if (this.options.gfm) { - istask = /^\[[ xX]\] /.test(item); - ischecked = void 0; - if (istask) { - ischecked = item[1] !== " "; - item = item.replace(/^\[[ xX]\] +/, ""); - } - } - list2.items.push({ - type: "list_item", - raw, - task: istask, - checked: ischecked, - loose, - text: item - }); - } - return list2; - } - } - html(src) { - const cap = this.rules.block.html.exec(src); - if (cap) { - return { - type: this.options.sanitize ? "paragraph" : "html", - raw: cap[0], - pre: !this.options.sanitizer && (cap[1] === "pre" || cap[1] === "script" || cap[1] === "style"), - text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0] - }; - } - } - def(src) { - const cap = this.rules.block.def.exec(src); - if (cap) { - if (cap[3]) - cap[3] = cap[3].substring(1, cap[3].length - 1); - const tag = cap[1].toLowerCase().replace(/\s+/g, " "); - return { - type: "def", - tag, - raw: cap[0], - href: cap[2], - title: cap[3] - }; - } - } - table(src) { - const cap = this.rules.block.table.exec(src); - if (cap) { - const item = { - type: "table", - header: splitCells(cap[1].replace(/^ *| *\| *$/g, "")), - align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */), - cells: cap[3] ? cap[3].replace(/\n$/, "").split("\n") : [] - }; - if (item.header.length === item.align.length) { - item.raw = cap[0]; - let l = item.align.length; - let i; - for (i = 0; i < l; i++) { - if (/^ *-+: *$/.test(item.align[i])) { - item.align[i] = "right"; - } else if (/^ *:-+: *$/.test(item.align[i])) { - item.align[i] = "center"; - } else if (/^ *:-+ *$/.test(item.align[i])) { - item.align[i] = "left"; - } else { - item.align[i] = null; - } - } - l = item.cells.length; - for (i = 0; i < l; i++) { - item.cells[i] = splitCells(item.cells[i].replace(/^ *\| *| *\| *$/g, ""), item.header.length); - } - return item; - } - } - } - lheading(src) { - const cap = this.rules.block.lheading.exec(src); - if (cap) { - return { - type: "heading", - raw: cap[0], - depth: cap[2].charAt(0) === "=" ? 1 : 2, - text: cap[1] - }; - } - } - paragraph(src) { - const cap = this.rules.block.paragraph.exec(src); - if (cap) { - return { - type: "paragraph", - raw: cap[0], - text: cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1] - }; - } - } - text(src) { - const cap = this.rules.block.text.exec(src); - if (cap) { - return { - type: "text", - raw: cap[0], - text: cap[0] - }; - } - } - escape(src) { - const cap = this.rules.inline.escape.exec(src); - if (cap) { - return { - type: "escape", - raw: cap[0], - text: escape(cap[1]) - }; - } - } - tag(src, inLink, inRawBlock) { - const cap = this.rules.inline.tag.exec(src); - if (cap) { - if (!inLink && /^/i.test(cap[0])) { - inLink = false; - } - if (!inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { - inRawBlock = true; - } else if (inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { - inRawBlock = false; - } - return { - type: this.options.sanitize ? "text" : "html", - raw: cap[0], - inLink, - inRawBlock, - text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0] - }; - } - } - link(src) { - const cap = this.rules.inline.link.exec(src); - if (cap) { - const trimmedUrl = cap[2].trim(); - if (!this.options.pedantic && /^$/.test(trimmedUrl)) { - return; - } - const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\"); - if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { - return; - } - } else { - const lastParenIndex = findClosingBracket(cap[2], "()"); - if (lastParenIndex > -1) { - const start = cap[0].indexOf("!") === 0 ? 5 : 4; - const linkLen = start + cap[1].length + lastParenIndex; - cap[2] = cap[2].substring(0, lastParenIndex); - cap[0] = cap[0].substring(0, linkLen).trim(); - cap[3] = ""; - } - } - let href = cap[2]; - let title = ""; - if (this.options.pedantic) { - const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); - if (link) { - href = link[1]; - title = link[3]; - } - } else { - title = cap[3] ? cap[3].slice(1, -1) : ""; - } - href = href.trim(); - if (/^$/.test(trimmedUrl)) { - href = href.slice(1); - } else { - href = href.slice(1, -1); - } - } - return outputLink(cap, { - href: href ? href.replace(this.rules.inline._escapes, "$1") : href, - title: title ? title.replace(this.rules.inline._escapes, "$1") : title - }, cap[0]); - } - } - reflink(src, links2) { - let cap; - if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) { - let link = (cap[2] || cap[1]).replace(/\s+/g, " "); - link = links2[link.toLowerCase()]; - if (!link || !link.href) { - const text = cap[0].charAt(0); - return { - type: "text", - raw: text, - text - }; - } - return outputLink(cap, link, cap[0]); - } - } - emStrong(src, maskedSrc, prevChar = "") { - let match = this.rules.inline.emStrong.lDelim.exec(src); - if (!match) - return; - if (match[3] && prevChar.match(/[\p{L}\p{N}]/u)) - return; - const nextChar = match[1] || match[2] || ""; - if (!nextChar || nextChar && (prevChar === "" || this.rules.inline.punctuation.exec(prevChar))) { - const lLength = match[0].length - 1; - let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; - const endReg = match[0][0] === "*" ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd; - endReg.lastIndex = 0; - maskedSrc = maskedSrc.slice(-1 * src.length + lLength); - while ((match = endReg.exec(maskedSrc)) != null) { - rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6]; - if (!rDelim) - continue; - rLength = rDelim.length; - if (match[3] || match[4]) { - delimTotal += rLength; - continue; - } else if (match[5] || match[6]) { - if (lLength % 3 && !((lLength + rLength) % 3)) { - midDelimTotal += rLength; - continue; - } - } - delimTotal -= rLength; - if (delimTotal > 0) - continue; - rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); - if (Math.min(lLength, rLength) % 2) { - return { - type: "em", - raw: src.slice(0, lLength + match.index + rLength + 1), - text: src.slice(1, lLength + match.index + rLength) - }; - } - return { - type: "strong", - raw: src.slice(0, lLength + match.index + rLength + 1), - text: src.slice(2, lLength + match.index + rLength - 1) - }; - } - } - } - codespan(src) { - const cap = this.rules.inline.code.exec(src); - if (cap) { - let text = cap[2].replace(/\n/g, " "); - const hasNonSpaceChars = /[^ ]/.test(text); - const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text); - if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { - text = text.substring(1, text.length - 1); - } - text = escape(text, true); - return { - type: "codespan", - raw: cap[0], - text - }; - } - } - br(src) { - const cap = this.rules.inline.br.exec(src); - if (cap) { - return { - type: "br", - raw: cap[0] - }; - } - } - del(src) { - const cap = this.rules.inline.del.exec(src); - if (cap) { - return { - type: "del", - raw: cap[0], - text: cap[2] - }; - } - } - autolink(src, mangle) { - const cap = this.rules.inline.autolink.exec(src); - if (cap) { - let text, href; - if (cap[2] === "@") { - text = escape(this.options.mangle ? mangle(cap[1]) : cap[1]); - href = "mailto:" + text; - } else { - text = escape(cap[1]); - href = text; - } - return { - type: "link", - raw: cap[0], - text, - href, - tokens: [ - { - type: "text", - raw: text, - text - } - ] - }; - } - } - url(src, mangle) { - let cap; - if (cap = this.rules.inline.url.exec(src)) { - let text, href; - if (cap[2] === "@") { - text = escape(this.options.mangle ? mangle(cap[0]) : cap[0]); - href = "mailto:" + text; - } else { - let prevCapZero; - do { - prevCapZero = cap[0]; - cap[0] = this.rules.inline._backpedal.exec(cap[0])[0]; - } while (prevCapZero !== cap[0]); - text = escape(cap[0]); - if (cap[1] === "www.") { - href = "http://" + text; - } else { - href = text; - } - } - return { - type: "link", - raw: cap[0], - text, - href, - tokens: [ - { - type: "text", - raw: text, - text - } - ] - }; - } - } - inlineText(src, inRawBlock, smartypants) { - const cap = this.rules.inline.text.exec(src); - if (cap) { - let text; - if (inRawBlock) { - text = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0]; - } else { - text = escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]); - } - return { - type: "text", - raw: cap[0], - text - }; - } - } - }; - } -}); - -// node_modules/marked/src/rules.js -var require_rules = __commonJS({ - "node_modules/marked/src/rules.js"(exports2, module2) { - var { - noopTest, - edit: edit2, - merge - } = require_helpers(); - var block = { - newline: /^(?: *(?:\n|$))+/, - code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/, - fences: /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/, - hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/, - heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/, - blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/, - list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?! {0,3}bull )\n*|\s*$)/, - html: "^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))", - def: /^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/, - nptable: noopTest, - table: noopTest, - lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/, - _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html| +\n)[^\n]+)*)/, - text: /^[^\n]+/ - }; - block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/; - block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/; - block.def = edit2(block.def).replace("label", block._label).replace("title", block._title).getRegex(); - block.bullet = /(?:[*+-]|\d{1,9}[.)])/; - block.item = /^( *)(bull) ?[^\n]*(?:\n(?! *bull ?)[^\n]*)*/; - block.item = edit2(block.item, "gm").replace(/bull/g, block.bullet).getRegex(); - block.listItemStart = edit2(/^( *)(bull) */).replace("bull", block.bullet).getRegex(); - block.list = edit2(block.list).replace(/bull/g, block.bullet).replace("hr", "\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def", "\\n+(?=" + block.def.source + ")").getRegex(); - block._tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul"; - block._comment = /|$)/; - block.html = edit2(block.html, "i").replace("comment", block._comment).replace("tag", block._tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(); - block.paragraph = edit2(block._paragraph).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("|lheading", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex(); - block.blockquote = edit2(block.blockquote).replace("paragraph", block.paragraph).getRegex(); - block.normal = merge({}, block); - block.gfm = merge({}, block.normal, { - nptable: "^ *([^|\\n ].*\\|.*)\\n {0,3}([-:]+ *\\|[-| :]*)(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)", - table: "^ *\\|(.+)\\n {0,3}\\|?( *[-:]+[-| :]*)(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)" - }); - block.gfm.nptable = edit2(block.gfm.nptable).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex(); - block.gfm.table = edit2(block.gfm.table).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex(); - block.pedantic = merge({}, block.normal, { - html: edit2(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", block._comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), - def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, - heading: /^(#{1,6})(.*)(?:\n+|$)/, - fences: noopTest, - paragraph: edit2(block.normal._paragraph).replace("hr", block.hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", block.lheading).replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").getRegex() - }); - var inline = { - escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, - autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, - url: noopTest, - tag: "^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^", - link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/, - reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/, - nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/, - reflinkSearch: "reflink|nolink(?!\\()", - emStrong: { - lDelim: /^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/, - rDelimAst: /\_\_[^_*]*?\*[^_*]*?\_\_|[punct_](\*+)(?=[\s]|$)|[^punct*_\s](\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|[^punct*_\s](\*+)(?=[^punct*_\s])/, - rDelimUnd: /\*\*[^_*]*?\_[^_*]*?\*\*|[punct*](\_+)(?=[\s]|$)|[^punct*_\s](\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/ - }, - code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, - br: /^( {2,}|\\)\n(?!\s*$)/, - del: noopTest, - text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\?@\\[\\]`^{|}~"; - inline.punctuation = edit2(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex(); - inline.blockSkip = /\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g; - inline.escapedEmSt = /\\\*|\\_/g; - inline._comment = edit2(block._comment).replace("(?:-->|$)", "-->").getRegex(); - inline.emStrong.lDelim = edit2(inline.emStrong.lDelim).replace(/punct/g, inline._punctuation).getRegex(); - inline.emStrong.rDelimAst = edit2(inline.emStrong.rDelimAst, "g").replace(/punct/g, inline._punctuation).getRegex(); - inline.emStrong.rDelimUnd = edit2(inline.emStrong.rDelimUnd, "g").replace(/punct/g, inline._punctuation).getRegex(); - inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g; - inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/; - inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/; - inline.autolink = edit2(inline.autolink).replace("scheme", inline._scheme).replace("email", inline._email).getRegex(); - inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/; - inline.tag = edit2(inline.tag).replace("comment", inline._comment).replace("attribute", inline._attribute).getRegex(); - inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; - inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/; - inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/; - inline.link = edit2(inline.link).replace("label", inline._label).replace("href", inline._href).replace("title", inline._title).getRegex(); - inline.reflink = edit2(inline.reflink).replace("label", inline._label).getRegex(); - inline.reflinkSearch = edit2(inline.reflinkSearch, "g").replace("reflink", inline.reflink).replace("nolink", inline.nolink).getRegex(); - inline.normal = merge({}, inline); - inline.pedantic = merge({}, inline.normal, { - strong: { - start: /^__|\*\*/, - middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, - endAst: /\*\*(?!\*)/g, - endUnd: /__(?!_)/g - }, - em: { - start: /^_|\*/, - middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/, - endAst: /\*(?!\*)/g, - endUnd: /_(?!_)/g - }, - link: edit2(/^!?\[(label)\]\((.*?)\)/).replace("label", inline._label).getRegex(), - reflink: edit2(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", inline._label).getRegex() - }); - inline.gfm = merge({}, inline.normal, { - escape: edit2(inline.escape).replace("])", "~|])").getRegex(), - _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/, - url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, - _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/, - del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/, - text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\ 0.5) { - ch = "x" + ch.toString(16); - } - out += "&#" + ch + ";"; - } - return out; - } - module2.exports = class Lexer { - constructor(options) { - this.tokens = []; - this.tokens.links = Object.create(null); - this.options = options || defaults2; - this.options.tokenizer = this.options.tokenizer || new Tokenizer(); - this.tokenizer = this.options.tokenizer; - this.tokenizer.options = this.options; - const rules = { - block: block.normal, - inline: inline.normal - }; - if (this.options.pedantic) { - rules.block = block.pedantic; - rules.inline = inline.pedantic; - } else if (this.options.gfm) { - rules.block = block.gfm; - if (this.options.breaks) { - rules.inline = inline.breaks; - } else { - rules.inline = inline.gfm; - } - } - this.tokenizer.rules = rules; - } - static get rules() { - return { - block, - inline - }; - } - static lex(src, options) { - const lexer = new Lexer(options); - return lexer.lex(src); - } - static lexInline(src, options) { - const lexer = new Lexer(options); - return lexer.inlineTokens(src); - } - lex(src) { - src = src.replace(/\r\n|\r/g, "\n").replace(/\t/g, " "); - this.blockTokens(src, this.tokens, true); - this.inline(this.tokens); - return this.tokens; - } - blockTokens(src, tokens = [], top = true) { - if (this.options.pedantic) { - src = src.replace(/^ +$/gm, ""); - } - let token, i, l, lastToken, cutSrc, lastParagraphClipped; - while (src) { - if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some((extTokenizer) => { - if (token = extTokenizer.call(this, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - if (token = this.tokenizer.space(src)) { - src = src.substring(token.raw.length); - if (token.type) { - tokens.push(token); - } - continue; - } - if (token = this.tokenizer.code(src)) { - src = src.substring(token.raw.length); - lastToken = tokens[tokens.length - 1]; - if (lastToken && lastToken.type === "paragraph") { - lastToken.raw += "\n" + token.raw; - lastToken.text += "\n" + token.text; - } else { - tokens.push(token); - } - continue; - } - if (token = this.tokenizer.fences(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - if (token = this.tokenizer.heading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - if (token = this.tokenizer.nptable(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - if (token = this.tokenizer.hr(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - if (token = this.tokenizer.blockquote(src)) { - src = src.substring(token.raw.length); - token.tokens = this.blockTokens(token.text, [], top); - tokens.push(token); - continue; - } - if (token = this.tokenizer.list(src)) { - src = src.substring(token.raw.length); - l = token.items.length; - for (i = 0; i < l; i++) { - token.items[i].tokens = this.blockTokens(token.items[i].text, [], false); - } - tokens.push(token); - continue; - } - if (token = this.tokenizer.html(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - if (top && (token = this.tokenizer.def(src))) { - src = src.substring(token.raw.length); - if (!this.tokens.links[token.tag]) { - this.tokens.links[token.tag] = { - href: token.href, - title: token.title - }; - } - continue; - } - if (token = this.tokenizer.table(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - if (token = this.tokenizer.lheading(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - cutSrc = src; - if (this.options.extensions && this.options.extensions.startBlock) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startBlock.forEach(function(getStartIndex) { - tempStart = getStartIndex.call(this, tempSrc); - if (typeof tempStart === "number" && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (top && (token = this.tokenizer.paragraph(cutSrc))) { - lastToken = tokens[tokens.length - 1]; - if (lastParagraphClipped && lastToken.type === "paragraph") { - lastToken.raw += "\n" + token.raw; - lastToken.text += "\n" + token.text; - } else { - tokens.push(token); - } - lastParagraphClipped = cutSrc.length !== src.length; - src = src.substring(token.raw.length); - continue; - } - if (token = this.tokenizer.text(src)) { - src = src.substring(token.raw.length); - lastToken = tokens[tokens.length - 1]; - if (lastToken && lastToken.type === "text") { - lastToken.raw += "\n" + token.raw; - lastToken.text += "\n" + token.text; - } else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = "Infinite loop on byte: " + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } else { - throw new Error(errMsg); - } - } - } - return tokens; - } - inline(tokens) { - let i, j, k, l2, row, token; - const l = tokens.length; - for (i = 0; i < l; i++) { - token = tokens[i]; - switch (token.type) { - case "paragraph": - case "text": - case "heading": { - token.tokens = []; - this.inlineTokens(token.text, token.tokens); - break; - } - case "table": { - token.tokens = { - header: [], - cells: [] - }; - l2 = token.header.length; - for (j = 0; j < l2; j++) { - token.tokens.header[j] = []; - this.inlineTokens(token.header[j], token.tokens.header[j]); - } - l2 = token.cells.length; - for (j = 0; j < l2; j++) { - row = token.cells[j]; - token.tokens.cells[j] = []; - for (k = 0; k < row.length; k++) { - token.tokens.cells[j][k] = []; - this.inlineTokens(row[k], token.tokens.cells[j][k]); - } - } - break; - } - case "blockquote": { - this.inline(token.tokens); - break; - } - case "list": { - l2 = token.items.length; - for (j = 0; j < l2; j++) { - this.inline(token.items[j].tokens); - } - break; - } - default: { - } - } - } - return tokens; - } - inlineTokens(src, tokens = [], inLink = false, inRawBlock = false) { - let token, lastToken, cutSrc; - let maskedSrc = src; - let match; - let keepPrevChar, prevChar; - if (this.tokens.links) { - const links2 = Object.keys(this.tokens.links); - if (links2.length > 0) { - while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { - if (links2.includes(match[0].slice(match[0].lastIndexOf("[") + 1, -1))) { - maskedSrc = maskedSrc.slice(0, match.index) + "[" + repeatString("a", match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); - } - } - } - } - while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + "[" + repeatString("a", match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); - } - while ((match = this.tokenizer.rules.inline.escapedEmSt.exec(maskedSrc)) != null) { - maskedSrc = maskedSrc.slice(0, match.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex); - } - while (src) { - if (!keepPrevChar) { - prevChar = ""; - } - keepPrevChar = false; - if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some((extTokenizer) => { - if (token = extTokenizer.call(this, src, tokens)) { - src = src.substring(token.raw.length); - tokens.push(token); - return true; - } - return false; - })) { - continue; - } - if (token = this.tokenizer.escape(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - if (token = this.tokenizer.tag(src, inLink, inRawBlock)) { - src = src.substring(token.raw.length); - inLink = token.inLink; - inRawBlock = token.inRawBlock; - lastToken = tokens[tokens.length - 1]; - if (lastToken && token.type === "text" && lastToken.type === "text") { - lastToken.raw += token.raw; - lastToken.text += token.text; - } else { - tokens.push(token); - } - continue; - } - if (token = this.tokenizer.link(src)) { - src = src.substring(token.raw.length); - if (token.type === "link") { - token.tokens = this.inlineTokens(token.text, [], true, inRawBlock); - } - tokens.push(token); - continue; - } - if (token = this.tokenizer.reflink(src, this.tokens.links)) { - src = src.substring(token.raw.length); - lastToken = tokens[tokens.length - 1]; - if (token.type === "link") { - token.tokens = this.inlineTokens(token.text, [], true, inRawBlock); - tokens.push(token); - } else if (lastToken && token.type === "text" && lastToken.type === "text") { - lastToken.raw += token.raw; - lastToken.text += token.text; - } else { - tokens.push(token); - } - continue; - } - if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { - src = src.substring(token.raw.length); - token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock); - tokens.push(token); - continue; - } - if (token = this.tokenizer.codespan(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - if (token = this.tokenizer.br(src)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - if (token = this.tokenizer.del(src)) { - src = src.substring(token.raw.length); - token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock); - tokens.push(token); - continue; - } - if (token = this.tokenizer.autolink(src, mangle)) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - if (!inLink && (token = this.tokenizer.url(src, mangle))) { - src = src.substring(token.raw.length); - tokens.push(token); - continue; - } - cutSrc = src; - if (this.options.extensions && this.options.extensions.startInline) { - let startIndex = Infinity; - const tempSrc = src.slice(1); - let tempStart; - this.options.extensions.startInline.forEach(function(getStartIndex) { - tempStart = getStartIndex.call(this, tempSrc); - if (typeof tempStart === "number" && tempStart >= 0) { - startIndex = Math.min(startIndex, tempStart); - } - }); - if (startIndex < Infinity && startIndex >= 0) { - cutSrc = src.substring(0, startIndex + 1); - } - } - if (token = this.tokenizer.inlineText(cutSrc, inRawBlock, smartypants)) { - src = src.substring(token.raw.length); - if (token.raw.slice(-1) !== "_") { - prevChar = token.raw.slice(-1); - } - keepPrevChar = true; - lastToken = tokens[tokens.length - 1]; - if (lastToken && lastToken.type === "text") { - lastToken.raw += token.raw; - lastToken.text += token.text; - } else { - tokens.push(token); - } - continue; - } - if (src) { - const errMsg = "Infinite loop on byte: " + src.charCodeAt(0); - if (this.options.silent) { - console.error(errMsg); - break; - } else { - throw new Error(errMsg); - } - } - } - return tokens; - } - }; - } -}); - -// node_modules/marked/src/Renderer.js -var require_Renderer = __commonJS({ - "node_modules/marked/src/Renderer.js"(exports2, module2) { - var { defaults: defaults2 } = require_defaults(); - var { - cleanUrl, - escape - } = require_helpers(); - module2.exports = class Renderer { - constructor(options) { - this.options = options || defaults2; - } - code(code, infostring, escaped) { - const lang = (infostring || "").match(/\S*/)[0]; - if (this.options.highlight) { - const out = this.options.highlight(code, lang); - if (out != null && out !== code) { - escaped = true; - code = out; - } - } - code = code.replace(/\n$/, "") + "\n"; - if (!lang) { - return "
" + (escaped ? code : escape(code, true)) + "
\n"; - } - return '
' + (escaped ? code : escape(code, true)) + "
\n"; - } - blockquote(quote) { - return "
\n" + quote + "
\n"; - } - html(html) { - return html; - } - heading(text, level, raw, slugger) { - if (this.options.headerIds) { - return "' + text + "\n"; - } - return "" + text + "\n"; - } - hr() { - return this.options.xhtml ? "
\n" : "
\n"; - } - list(body, ordered, start) { - const type = ordered ? "ol" : "ul", startatt = ordered && start !== 1 ? ' start="' + start + '"' : ""; - return "<" + type + startatt + ">\n" + body + "\n"; - } - listitem(text) { - return "
  • " + text + "
  • \n"; - } - checkbox(checked) { - return " "; - } - paragraph(text) { - return "

    " + text + "

    \n"; - } - table(header, body) { - if (body) - body = "" + body + ""; - return "\n\n" + header + "\n" + body + "
    \n"; - } - tablerow(content) { - return "\n" + content + "\n"; - } - tablecell(content, flags) { - const type = flags.header ? "th" : "td"; - const tag = flags.align ? "<" + type + ' align="' + flags.align + '">' : "<" + type + ">"; - return tag + content + "\n"; - } - strong(text) { - return "" + text + ""; - } - em(text) { - return "" + text + ""; - } - codespan(text) { - return "" + text + ""; - } - br() { - return this.options.xhtml ? "
    " : "
    "; - } - del(text) { - return "" + text + ""; - } - link(href, title, text) { - href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); - if (href === null) { - return text; - } - let out = '
    "; - return out; - } - image(href, title, text) { - href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); - if (href === null) { - return text; - } - let out = '' + text + '" : ">"; - return out; - } - text(text) { - return text; - } - }; - } -}); - -// node_modules/marked/src/TextRenderer.js -var require_TextRenderer = __commonJS({ - "node_modules/marked/src/TextRenderer.js"(exports2, module2) { - module2.exports = class TextRenderer { - strong(text) { - return text; - } - em(text) { - return text; - } - codespan(text) { - return text; - } - del(text) { - return text; - } - html(text) { - return text; - } - text(text) { - return text; - } - link(href, title, text) { - return "" + text; - } - image(href, title, text) { - return "" + text; - } - br() { - return ""; - } - }; - } -}); - -// node_modules/marked/src/Slugger.js -var require_Slugger = __commonJS({ - "node_modules/marked/src/Slugger.js"(exports2, module2) { - module2.exports = class Slugger { - constructor() { - this.seen = {}; - } - serialize(value) { - return value.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig, "").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, "").replace(/\s/g, "-"); - } - getNextSafeSlug(originalSlug, isDryRun) { - let slug = originalSlug; - let occurenceAccumulator = 0; - if (this.seen.hasOwnProperty(slug)) { - occurenceAccumulator = this.seen[originalSlug]; - do { - occurenceAccumulator++; - slug = originalSlug + "-" + occurenceAccumulator; - } while (this.seen.hasOwnProperty(slug)); - } - if (!isDryRun) { - this.seen[originalSlug] = occurenceAccumulator; - this.seen[slug] = 0; - } - return slug; - } - slug(value, options = {}) { - const slug = this.serialize(value); - return this.getNextSafeSlug(slug, options.dryrun); - } - }; - } -}); - -// node_modules/marked/src/Parser.js -var require_Parser = __commonJS({ - "node_modules/marked/src/Parser.js"(exports2, module2) { - var Renderer2 = require_Renderer(); - var TextRenderer = require_TextRenderer(); - var Slugger = require_Slugger(); - var { defaults: defaults2 } = require_defaults(); - var { - unescape: unescape2 - } = require_helpers(); - module2.exports = class Parser { - constructor(options) { - this.options = options || defaults2; - this.options.renderer = this.options.renderer || new Renderer2(); - this.renderer = this.options.renderer; - this.renderer.options = this.options; - this.textRenderer = new TextRenderer(); - this.slugger = new Slugger(); - } - static parse(tokens, options) { - const parser2 = new Parser(options); - return parser2.parse(tokens); - } - static parseInline(tokens, options) { - const parser2 = new Parser(options); - return parser2.parseInline(tokens); - } - parse(tokens, top = true) { - let out = "", i, j, k, l2, l3, row, cell, header, body, token, ordered, start, loose, itemBody, item, checked, task, checkbox, ret; - const l = tokens.length; - for (i = 0; i < l; i++) { - token = tokens[i]; - if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) { - ret = this.options.extensions.renderers[token.type].call(this, token); - if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(token.type)) { - out += ret || ""; - continue; - } - } - switch (token.type) { - case "space": { - continue; - } - case "hr": { - out += this.renderer.hr(); - continue; - } - case "heading": { - out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape2(this.parseInline(token.tokens, this.textRenderer)), this.slugger); - continue; - } - case "code": { - out += this.renderer.code(token.text, token.lang, token.escaped); - continue; - } - case "table": { - header = ""; - cell = ""; - l2 = token.header.length; - for (j = 0; j < l2; j++) { - cell += this.renderer.tablecell(this.parseInline(token.tokens.header[j]), { header: true, align: token.align[j] }); - } - header += this.renderer.tablerow(cell); - body = ""; - l2 = token.cells.length; - for (j = 0; j < l2; j++) { - row = token.tokens.cells[j]; - cell = ""; - l3 = row.length; - for (k = 0; k < l3; k++) { - cell += this.renderer.tablecell(this.parseInline(row[k]), { header: false, align: token.align[k] }); - } - body += this.renderer.tablerow(cell); - } - out += this.renderer.table(header, body); - continue; - } - case "blockquote": { - body = this.parse(token.tokens); - out += this.renderer.blockquote(body); - continue; - } - case "list": { - ordered = token.ordered; - start = token.start; - loose = token.loose; - l2 = token.items.length; - body = ""; - for (j = 0; j < l2; j++) { - item = token.items[j]; - checked = item.checked; - task = item.task; - itemBody = ""; - if (item.task) { - checkbox = this.renderer.checkbox(checked); - if (loose) { - if (item.tokens.length > 0 && item.tokens[0].type === "text") { - item.tokens[0].text = checkbox + " " + item.tokens[0].text; - if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") { - item.tokens[0].tokens[0].text = checkbox + " " + item.tokens[0].tokens[0].text; - } - } else { - item.tokens.unshift({ - type: "text", - text: checkbox - }); - } - } else { - itemBody += checkbox; - } - } - itemBody += this.parse(item.tokens, loose); - body += this.renderer.listitem(itemBody, task, checked); - } - out += this.renderer.list(body, ordered, start); - continue; - } - case "html": { - out += this.renderer.html(token.text); - continue; - } - case "paragraph": { - out += this.renderer.paragraph(this.parseInline(token.tokens)); - continue; - } - case "text": { - body = token.tokens ? this.parseInline(token.tokens) : token.text; - while (i + 1 < l && tokens[i + 1].type === "text") { - token = tokens[++i]; - body += "\n" + (token.tokens ? this.parseInline(token.tokens) : token.text); - } - out += top ? this.renderer.paragraph(body) : body; - continue; - } - default: { - const errMsg = 'Token with "' + token.type + '" type was not found.'; - if (this.options.silent) { - console.error(errMsg); - return; - } else { - throw new Error(errMsg); - } - } - } - } - return out; - } - parseInline(tokens, renderer) { - renderer = renderer || this.renderer; - let out = "", i, token, ret; - const l = tokens.length; - for (i = 0; i < l; i++) { - token = tokens[i]; - if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) { - ret = this.options.extensions.renderers[token.type].call(this, token); - if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(token.type)) { - out += ret || ""; - continue; - } - } - switch (token.type) { - case "escape": { - out += renderer.text(token.text); - break; - } - case "html": { - out += renderer.html(token.text); - break; - } - case "link": { - out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer)); - break; - } - case "image": { - out += renderer.image(token.href, token.title, token.text); - break; - } - case "strong": { - out += renderer.strong(this.parseInline(token.tokens, renderer)); - break; - } - case "em": { - out += renderer.em(this.parseInline(token.tokens, renderer)); - break; - } - case "codespan": { - out += renderer.codespan(token.text); - break; - } - case "br": { - out += renderer.br(); - break; - } - case "del": { - out += renderer.del(this.parseInline(token.tokens, renderer)); - break; - } - case "text": { - out += renderer.text(token.text); - break; - } - default: { - const errMsg = 'Token with "' + token.type + '" type was not found.'; - if (this.options.silent) { - console.error(errMsg); - return; - } else { - throw new Error(errMsg); - } - } - } - } - return out; - } - }; - } -}); - -// node_modules/marked/src/marked.js -var require_marked = __commonJS({ - "node_modules/marked/src/marked.js"(exports2, module2) { - var Lexer = require_Lexer(); - var Parser = require_Parser(); - var Tokenizer = require_Tokenizer(); - var Renderer2 = require_Renderer(); - var TextRenderer = require_TextRenderer(); - var Slugger = require_Slugger(); - var { - merge, - checkSanitizeDeprecation, - escape - } = require_helpers(); - var { - getDefaults, - changeDefaults, - defaults: defaults2 - } = require_defaults(); - function marked2(src, opt, callback) { - if (typeof src === "undefined" || src === null) { - throw new Error("marked(): input parameter is undefined or null"); - } - if (typeof src !== "string") { - throw new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected"); - } - if (typeof opt === "function") { - callback = opt; - opt = null; - } - opt = merge({}, marked2.defaults, opt || {}); - checkSanitizeDeprecation(opt); - if (callback) { - const highlight = opt.highlight; - let tokens; - try { - tokens = Lexer.lex(src, opt); - } catch (e) { - return callback(e); - } - const done = function(err) { - let out; - if (!err) { - try { - if (opt.walkTokens) { - marked2.walkTokens(tokens, opt.walkTokens); - } - out = Parser.parse(tokens, opt); - } catch (e) { - err = e; - } - } - opt.highlight = highlight; - return err ? callback(err) : callback(null, out); - }; - if (!highlight || highlight.length < 3) { - return done(); - } - delete opt.highlight; - if (!tokens.length) - return done(); - let pending = 0; - marked2.walkTokens(tokens, function(token) { - if (token.type === "code") { - pending++; - setTimeout(() => { - highlight(token.text, token.lang, function(err, code) { - if (err) { - return done(err); - } - if (code != null && code !== token.text) { - token.text = code; - token.escaped = true; - } - pending--; - if (pending === 0) { - done(); - } - }); - }, 0); - } - }); - if (pending === 0) { - done(); - } - return; - } - try { - const tokens = Lexer.lex(src, opt); - if (opt.walkTokens) { - marked2.walkTokens(tokens, opt.walkTokens); - } - return Parser.parse(tokens, opt); - } catch (e) { - e.message += "\nPlease report this to https://github.com/markedjs/marked."; - if (opt.silent) { - return "

    An error occurred:

    " + escape(e.message + "", true) + "
    "; - } - throw e; - } - } - marked2.options = marked2.setOptions = function(opt) { - merge(marked2.defaults, opt); - changeDefaults(marked2.defaults); - return marked2; - }; - marked2.getDefaults = getDefaults; - marked2.defaults = defaults2; - marked2.use = function(...args) { - const opts = merge({}, ...args); - const extensions = marked2.defaults.extensions || { renderers: {}, childTokens: {} }; - let hasExtensions; - args.forEach((pack) => { - if (pack.extensions) { - hasExtensions = true; - pack.extensions.forEach((ext) => { - if (!ext.name) { - throw new Error("extension name required"); - } - if (ext.renderer) { - const prevRenderer = extensions.renderers ? extensions.renderers[ext.name] : null; - if (prevRenderer) { - extensions.renderers[ext.name] = function(...args2) { - let ret = ext.renderer.apply(this, args2); - if (ret === false) { - ret = prevRenderer.apply(this, args2); - } - return ret; - }; - } else { - extensions.renderers[ext.name] = ext.renderer; - } - } - if (ext.tokenizer) { - if (!ext.level || ext.level !== "block" && ext.level !== "inline") { - throw new Error("extension level must be 'block' or 'inline'"); - } - if (extensions[ext.level]) { - extensions[ext.level].unshift(ext.tokenizer); - } else { - extensions[ext.level] = [ext.tokenizer]; - } - if (ext.start) { - if (ext.level === "block") { - if (extensions.startBlock) { - extensions.startBlock.push(ext.start); - } else { - extensions.startBlock = [ext.start]; - } - } else if (ext.level === "inline") { - if (extensions.startInline) { - extensions.startInline.push(ext.start); - } else { - extensions.startInline = [ext.start]; - } - } - } - } - if (ext.childTokens) { - extensions.childTokens[ext.name] = ext.childTokens; - } - }); - } - if (pack.renderer) { - const renderer = marked2.defaults.renderer || new Renderer2(); - for (const prop in pack.renderer) { - const prevRenderer = renderer[prop]; - renderer[prop] = (...args2) => { - let ret = pack.renderer[prop].apply(renderer, args2); - if (ret === false) { - ret = prevRenderer.apply(renderer, args2); - } - return ret; - }; - } - opts.renderer = renderer; - } - if (pack.tokenizer) { - const tokenizer = marked2.defaults.tokenizer || new Tokenizer(); - for (const prop in pack.tokenizer) { - const prevTokenizer = tokenizer[prop]; - tokenizer[prop] = (...args2) => { - let ret = pack.tokenizer[prop].apply(tokenizer, args2); - if (ret === false) { - ret = prevTokenizer.apply(tokenizer, args2); - } - return ret; - }; - } - opts.tokenizer = tokenizer; - } - if (pack.walkTokens) { - const walkTokens = marked2.defaults.walkTokens; - opts.walkTokens = (token) => { - pack.walkTokens.call(this, token); - if (walkTokens) { - walkTokens(token); - } - }; - } - if (hasExtensions) { - opts.extensions = extensions; - } - marked2.setOptions(opts); - }); - }; - marked2.walkTokens = function(tokens, callback) { - for (const token of tokens) { - callback(token); - switch (token.type) { - case "table": { - for (const cell of token.tokens.header) { - marked2.walkTokens(cell, callback); - } - for (const row of token.tokens.cells) { - for (const cell of row) { - marked2.walkTokens(cell, callback); - } - } - break; - } - case "list": { - marked2.walkTokens(token.items, callback); - break; - } - default: { - if (marked2.defaults.extensions && marked2.defaults.extensions.childTokens && marked2.defaults.extensions.childTokens[token.type]) { - marked2.defaults.extensions.childTokens[token.type].forEach(function(childTokens) { - marked2.walkTokens(token[childTokens], callback); - }); - } else if (token.tokens) { - marked2.walkTokens(token.tokens, callback); - } - } - } - } - }; - marked2.parseInline = function(src, opt) { - if (typeof src === "undefined" || src === null) { - throw new Error("marked.parseInline(): input parameter is undefined or null"); - } - if (typeof src !== "string") { - throw new Error("marked.parseInline(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected"); - } - opt = merge({}, marked2.defaults, opt || {}); - checkSanitizeDeprecation(opt); - try { - const tokens = Lexer.lexInline(src, opt); - if (opt.walkTokens) { - marked2.walkTokens(tokens, opt.walkTokens); - } - return Parser.parseInline(tokens, opt); - } catch (e) { - e.message += "\nPlease report this to https://github.com/markedjs/marked."; - if (opt.silent) { - return "

    An error occurred:

    " + escape(e.message + "", true) + "
    "; - } - throw e; - } - }; - marked2.Parser = Parser; - marked2.parser = Parser.parse; - marked2.Renderer = Renderer2; - marked2.TextRenderer = TextRenderer; - marked2.Lexer = Lexer; - marked2.lexer = Lexer.lex; - marked2.Tokenizer = Tokenizer; - marked2.Slugger = Slugger; - marked2.parse = marked2; - module2.exports = marked2; - } -}); - -// node_modules/colors/lib/styles.js -var require_styles = __commonJS({ - "node_modules/colors/lib/styles.js"(exports2, module2) { - var styles3 = {}; - module2["exports"] = styles3; - var codes = { - reset: [0, 0], - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - grey: [90, 39], - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - blackBG: [40, 49], - redBG: [41, 49], - greenBG: [42, 49], - yellowBG: [43, 49], - blueBG: [44, 49], - magentaBG: [45, 49], - cyanBG: [46, 49], - whiteBG: [47, 49] - }; - Object.keys(codes).forEach(function(key) { - var val = codes[key]; - var style2 = styles3[key] = []; - style2.open = "[" + val[0] + "m"; - style2.close = "[" + val[1] + "m"; - }); - } -}); - -// node_modules/colors/lib/system/supports-colors.js -var require_supports_colors = __commonJS({ - "node_modules/colors/lib/system/supports-colors.js"(exports2, module2) { - var argv = process.argv; - module2.exports = function() { - if (argv.indexOf("--no-color") !== -1 || argv.indexOf("--color=false") !== -1) { - return false; - } - if (argv.indexOf("--color") !== -1 || argv.indexOf("--color=true") !== -1 || argv.indexOf("--color=always") !== -1) { - return true; - } - if (process.stdout && !process.stdout.isTTY) { - return false; - } - if (process.platform === "win32") { - return true; - } - if ("COLORTERM" in process.env) { - return true; - } - if (process.env.TERM === "dumb") { - return false; - } - if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { - return true; - } - return false; - }(); - } -}); - -// node_modules/colors/lib/custom/trap.js -var require_trap = __commonJS({ - "node_modules/colors/lib/custom/trap.js"(exports2, module2) { - module2["exports"] = function runTheTrap(text, options) { - var result = ""; - text = text || "Run the trap, drop the bass"; - text = text.split(""); - var trap = { - a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"], - b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"], - c: ["\xA9", "\u023B", "\u03FE"], - d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"], - e: ["\xCB", "\u0115", "\u018E", "\u0258", "\u03A3", "\u03BE", "\u04BC", "\u0A6C"], - f: ["\u04FA"], - g: ["\u0262"], - h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"], - i: ["\u0F0F"], - j: ["\u0134"], - k: ["\u0138", "\u04A0", "\u04C3", "\u051E"], - l: ["\u0139"], - m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"], - n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"], - o: ["\xD8", "\xF5", "\xF8", "\u01FE", "\u0298", "\u047A", "\u05DD", "\u06DD", "\u0E4F"], - p: ["\u01F7", "\u048E"], - q: ["\u09CD"], - r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"], - s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"], - t: ["\u0141", "\u0166", "\u0373"], - u: ["\u01B1", "\u054D"], - v: ["\u05D8"], - w: ["\u0428", "\u0460", "\u047C", "\u0D70"], - x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"], - y: ["\xA5", "\u04B0", "\u04CB"], - z: ["\u01B5", "\u0240"] - }; - text.forEach(function(c) { - c = c.toLowerCase(); - var chars = trap[c] || [" "]; - var rand = Math.floor(Math.random() * chars.length); - if (typeof trap[c] !== "undefined") { - result += trap[c][rand]; - } else { - result += c; - } - }); - return result; - }; - } -}); - -// node_modules/colors/lib/custom/zalgo.js -var require_zalgo = __commonJS({ - "node_modules/colors/lib/custom/zalgo.js"(exports2, module2) { - module2["exports"] = function zalgo(text, options) { - text = text || " he is here "; - var soul = { - "up": [ - "\u030D", - "\u030E", - "\u0304", - "\u0305", - "\u033F", - "\u0311", - "\u0306", - "\u0310", - "\u0352", - "\u0357", - "\u0351", - "\u0307", - "\u0308", - "\u030A", - "\u0342", - "\u0313", - "\u0308", - "\u034A", - "\u034B", - "\u034C", - "\u0303", - "\u0302", - "\u030C", - "\u0350", - "\u0300", - "\u0301", - "\u030B", - "\u030F", - "\u0312", - "\u0313", - "\u0314", - "\u033D", - "\u0309", - "\u0363", - "\u0364", - "\u0365", - "\u0366", - "\u0367", - "\u0368", - "\u0369", - "\u036A", - "\u036B", - "\u036C", - "\u036D", - "\u036E", - "\u036F", - "\u033E", - "\u035B", - "\u0346", - "\u031A" - ], - "down": [ - "\u0316", - "\u0317", - "\u0318", - "\u0319", - "\u031C", - "\u031D", - "\u031E", - "\u031F", - "\u0320", - "\u0324", - "\u0325", - "\u0326", - "\u0329", - "\u032A", - "\u032B", - "\u032C", - "\u032D", - "\u032E", - "\u032F", - "\u0330", - "\u0331", - "\u0332", - "\u0333", - "\u0339", - "\u033A", - "\u033B", - "\u033C", - "\u0345", - "\u0347", - "\u0348", - "\u0349", - "\u034D", - "\u034E", - "\u0353", - "\u0354", - "\u0355", - "\u0356", - "\u0359", - "\u035A", - "\u0323" - ], - "mid": [ - "\u0315", - "\u031B", - "\u0300", - "\u0301", - "\u0358", - "\u0321", - "\u0322", - "\u0327", - "\u0328", - "\u0334", - "\u0335", - "\u0336", - "\u035C", - "\u035D", - "\u035E", - "\u035F", - "\u0360", - "\u0362", - "\u0338", - "\u0337", - "\u0361", - " \u0489" - ] - }, all = [].concat(soul.up, soul.down, soul.mid), zalgo2 = {}; - function randomNumber(range) { - var r = Math.floor(Math.random() * range); - return r; - } - function is_char(character) { - var bool = false; - all.filter(function(i) { - bool = i === character; - }); - return bool; - } - function heComes(text2, options2) { - var result = "", counts, l; - options2 = options2 || {}; - options2["up"] = options2["up"] || true; - options2["mid"] = options2["mid"] || true; - options2["down"] = options2["down"] || true; - options2["size"] = options2["size"] || "maxi"; - text2 = text2.split(""); - for (l in text2) { - if (is_char(l)) { - continue; - } - result = result + text2[l]; - counts = { "up": 0, "down": 0, "mid": 0 }; - switch (options2.size) { - case "mini": - counts.up = randomNumber(8); - counts.min = randomNumber(2); - counts.down = randomNumber(8); - break; - case "maxi": - counts.up = randomNumber(16) + 3; - counts.min = randomNumber(4) + 1; - counts.down = randomNumber(64) + 3; - break; - default: - counts.up = randomNumber(8) + 1; - counts.mid = randomNumber(6) / 2; - counts.down = randomNumber(8) + 1; - break; - } - var arr = ["up", "mid", "down"]; - for (var d in arr) { - var index = arr[d]; - for (var i = 0; i <= counts[index]; i++) { - if (options2[index]) { - result = result + soul[index][randomNumber(soul[index].length)]; - } - } - } - } - return result; - } - return heComes(text); - }; - } -}); - -// node_modules/colors/lib/maps/america.js -var require_america = __commonJS({ - "node_modules/colors/lib/maps/america.js"(exports2, module2) { - var colors = require_colors(); - module2["exports"] = function() { - return function(letter, i, exploded) { - if (letter === " ") - return letter; - switch (i % 3) { - case 0: - return colors.red(letter); - case 1: - return colors.white(letter); - case 2: - return colors.blue(letter); - } - }; - }(); - } -}); - -// node_modules/colors/lib/maps/zebra.js -var require_zebra = __commonJS({ - "node_modules/colors/lib/maps/zebra.js"(exports2, module2) { - var colors = require_colors(); - module2["exports"] = function(letter, i, exploded) { - return i % 2 === 0 ? letter : colors.inverse(letter); - }; - } -}); - -// node_modules/colors/lib/maps/rainbow.js -var require_rainbow = __commonJS({ - "node_modules/colors/lib/maps/rainbow.js"(exports2, module2) { - var colors = require_colors(); - module2["exports"] = function() { - var rainbowColors = ["red", "yellow", "green", "blue", "magenta"]; - return function(letter, i, exploded) { - if (letter === " ") { - return letter; - } else { - return colors[rainbowColors[i++ % rainbowColors.length]](letter); - } - }; - }(); - } -}); - -// node_modules/colors/lib/maps/random.js -var require_random = __commonJS({ - "node_modules/colors/lib/maps/random.js"(exports2, module2) { - var colors = require_colors(); - module2["exports"] = function() { - var available = ["underline", "inverse", "grey", "yellow", "red", "green", "blue", "white", "cyan", "magenta"]; - return function(letter, i, exploded) { - return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 1))]](letter); - }; - }(); - } -}); - -// node_modules/colors/lib/colors.js -var require_colors = __commonJS({ - "node_modules/colors/lib/colors.js"(exports2, module2) { - var colors = {}; - module2["exports"] = colors; - colors.themes = {}; - var ansiStyles = colors.styles = require_styles(); - var defineProps = Object.defineProperties; - colors.supportsColor = require_supports_colors(); - if (typeof colors.enabled === "undefined") { - colors.enabled = colors.supportsColor; - } - colors.stripColors = colors.strip = function(str) { - return ("" + str).replace(/\x1B\[\d+m/g, ""); - }; - var stylize = colors.stylize = function stylize2(str, style2) { - return ansiStyles[style2].open + str + ansiStyles[style2].close; - }; - var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; - var escapeStringRegexp = function(str) { - if (typeof str !== "string") { - throw new TypeError("Expected a string"); - } - return str.replace(matchOperatorsRe, "\\$&"); - }; - function build(_styles) { - var builder = function builder2() { - return applyStyle.apply(builder2, arguments); - }; - builder._styles = _styles; - builder.__proto__ = proto; - return builder; - } - var styles3 = function() { - var ret = {}; - ansiStyles.grey = ansiStyles.gray; - Object.keys(ansiStyles).forEach(function(key) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), "g"); - ret[key] = { - get: function() { - return build(this._styles.concat(key)); - } - }; - }); - return ret; - }(); - var proto = defineProps(function colors2() { - }, styles3); - function applyStyle() { - var args = arguments; - var argsLen = args.length; - var str = argsLen !== 0 && String(arguments[0]); - if (argsLen > 1) { - for (var a = 1; a < argsLen; a++) { - str += " " + args[a]; - } - } - if (!colors.enabled || !str) { - return str; - } - var nestedStyles = this._styles; - var i = nestedStyles.length; - while (i--) { - var code = ansiStyles[nestedStyles[i]]; - str = code.open + str.replace(code.closeRe, code.open) + code.close; - } - return str; - } - function applyTheme(theme) { - for (var style2 in theme) { - (function(style3) { - colors[style3] = function(str) { - return colors[theme[style3]](str); - }; - })(style2); - } - } - colors.setTheme = function(theme) { - if (typeof theme === "string") { - try { - colors.themes[theme] = require(theme); - applyTheme(colors.themes[theme]); - return colors.themes[theme]; - } catch (err) { - console.log(err); - return err; - } - } else { - applyTheme(theme); - } - }; - function init() { - var ret = {}; - Object.keys(styles3).forEach(function(name2) { - ret[name2] = { - get: function() { - return build([name2]); - } - }; - }); - return ret; - } - var sequencer = function sequencer2(map2, str) { - var exploded = str.split(""), i = 0; - exploded = exploded.map(map2); - return exploded.join(""); - }; - colors.trap = require_trap(); - colors.zalgo = require_zalgo(); - colors.maps = {}; - colors.maps.america = require_america(); - colors.maps.zebra = require_zebra(); - colors.maps.rainbow = require_rainbow(); - colors.maps.random = require_random(); - for (var map in colors.maps) { - (function(map2) { - colors[map2] = function(str) { - return sequencer(colors.maps[map2], str); - }; - })(map); - } - defineProps(colors, init()); - } -}); - -// node_modules/colors/safe.js -var require_safe = __commonJS({ - "node_modules/colors/safe.js"(exports2, module2) { - var colors = require_colors(); - module2["exports"] = colors; - } -}); - -// node_modules/cli-table/lib/utils.js -var require_utils2 = __commonJS({ - "node_modules/cli-table/lib/utils.js"(exports2) { - exports2.repeat = function(str, times) { - return Array(times + 1).join(str); - }; - exports2.pad = function(str, len, pad2, dir) { - if (len + 1 >= str.length) - switch (dir) { - case "left": - str = Array(len + 1 - str.length).join(pad2) + str; - break; - case "both": - var right = Math.ceil((padlen = len - str.length) / 2); - var left = padlen - right; - str = Array(left + 1).join(pad2) + str + Array(right + 1).join(pad2); - break; - default: - str = str + Array(len + 1 - str.length).join(pad2); - } - ; - return str; - }; - exports2.truncate = function(str, length, chr) { - chr = chr || "\u2026"; - return str.length >= length ? str.substr(0, length - chr.length) + chr : str; - }; - function options(defaults2, opts) { - for (var p in opts) { - if (p === "__proto__" || p === "constructor" || p === "prototype") { - continue; - } - if (opts[p] && opts[p].constructor && opts[p].constructor === Object) { - defaults2[p] = defaults2[p] || {}; - options(defaults2[p], opts[p]); - } else { - defaults2[p] = opts[p]; - } - } - return defaults2; - } - exports2.options = options; - exports2.strlen = function(str) { - var code = /\u001b\[(?:\d*;){0,5}\d*m/g; - var stripped = ("" + str).replace(code, ""); - var split = stripped.split("\n"); - return split.reduce(function(memo, s) { - return s.length > memo ? s.length : memo; - }, 0); - }; - } -}); - -// node_modules/cli-table/lib/index.js -var require_lib7 = __commonJS({ - "node_modules/cli-table/lib/index.js"(exports2, module2) { - var colors = require_safe(); - var utils = require_utils2(); - var repeat2 = utils.repeat; - var truncate = utils.truncate; - var pad2 = utils.pad; - function Table2(options) { - this.options = utils.options({ - chars: { - "top": "\u2500", - "top-mid": "\u252C", - "top-left": "\u250C", - "top-right": "\u2510", - "bottom": "\u2500", - "bottom-mid": "\u2534", - "bottom-left": "\u2514", - "bottom-right": "\u2518", - "left": "\u2502", - "left-mid": "\u251C", - "mid": "\u2500", - "mid-mid": "\u253C", - "right": "\u2502", - "right-mid": "\u2524", - "middle": "\u2502" - }, - truncate: "\u2026", - colWidths: [], - colAligns: [], - style: { - "padding-left": 1, - "padding-right": 1, - head: ["red"], - border: ["grey"], - compact: false - }, - head: [] - }, options); - } - Table2.prototype.__proto__ = Array.prototype; - Table2.prototype.__defineGetter__("width", function() { - var str = this.toString().split("\n"); - if (str.length) - return str[0].length; - return 0; - }); - Table2.prototype.render; - Table2.prototype.toString = function() { - var ret = "", options = this.options, style2 = options.style, head = options.head, chars = options.chars, truncater = options.truncate, colWidths = options.colWidths || new Array(this.head.length), totalWidth = 0; - if (!head.length && !this.length) - return ""; - if (!colWidths.length) { - var all_rows = this.slice(0); - if (head.length) { - all_rows = all_rows.concat([head]); - } - ; - all_rows.forEach(function(cells) { - if (typeof cells === "object" && cells.length) { - extractColumnWidths(cells); - } else { - var header_cell = Object.keys(cells)[0], value_cell = cells[header_cell]; - colWidths[0] = Math.max(colWidths[0] || 0, get_width(header_cell) || 0); - if (typeof value_cell === "object" && value_cell.length) { - extractColumnWidths(value_cell, 1); - } else { - colWidths[1] = Math.max(colWidths[1] || 0, get_width(value_cell) || 0); - } - } - }); - } - ; - totalWidth = (colWidths.length == 1 ? colWidths[0] : colWidths.reduce(function(a, b) { - return a + b; - })) + colWidths.length + 1; - function extractColumnWidths(arr, offset) { - var offset = offset || 0; - arr.forEach(function(cell, i) { - colWidths[i + offset] = Math.max(colWidths[i + offset] || 0, get_width(cell) || 0); - }); - } - ; - function get_width(obj) { - return typeof obj == "object" && obj.width != void 0 ? obj.width : (typeof obj == "object" ? utils.strlen(obj.text) : utils.strlen(obj)) + (style2["padding-left"] || 0) + (style2["padding-right"] || 0); - } - function line(line2, left, right, intersection) { - var width = 0, line2 = left + repeat2(line2, totalWidth - 2) + right; - colWidths.forEach(function(w, i) { - if (i == colWidths.length - 1) - return; - width += w + 1; - line2 = line2.substr(0, width) + intersection + line2.substr(width + 1); - }); - return applyStyles(options.style.border, line2); - } - ; - function lineTop() { - var l2 = line(chars.top, chars["top-left"] || chars.top, chars["top-right"] || chars.top, chars["top-mid"]); - if (l2) - ret += l2 + "\n"; - } - ; - function generateRow(items, style3) { - var cells = [], max_height = 0; - if (!Array.isArray(items) && typeof items === "object") { - var key = Object.keys(items)[0], value = items[key], first_cell_head = true; - if (Array.isArray(value)) { - items = value; - items.unshift(key); - } else { - items = [key, value]; - } - } - items.forEach(function(item, i) { - var contents = item.toString().split("\n").reduce(function(memo, l2) { - memo.push(string2(l2, i)); - return memo; - }, []); - var height = contents.length; - if (height > max_height) { - max_height = height; - } - ; - cells.push({ contents, height }); - }); - var lines = new Array(max_height); - cells.forEach(function(cell, i) { - cell.contents.forEach(function(line2, j2) { - if (!lines[j2]) { - lines[j2] = []; - } - ; - if (style3 || first_cell_head && i === 0 && options.style.head) { - line2 = applyStyles(options.style.head, line2); - } - lines[j2].push(line2); - }); - for (var j = cell.height, l2 = max_height; j < l2; j++) { - if (!lines[j]) { - lines[j] = []; - } - ; - lines[j].push(string2("", i)); - } - }); - var ret2 = ""; - lines.forEach(function(line2, index) { - if (ret2.length > 0) { - ret2 += "\n" + applyStyles(options.style.border, chars.left); - } - ret2 += line2.join(applyStyles(options.style.border, chars.middle)) + applyStyles(options.style.border, chars.right); - }); - return applyStyles(options.style.border, chars.left) + ret2; - } - ; - function applyStyles(styles3, subject) { - if (!subject) - return ""; - styles3.forEach(function(style3) { - subject = colors[style3](subject); - }); - return subject; - } - ; - function string2(str, index) { - var str = String(typeof str == "object" && str.text ? str.text : str), length = utils.strlen(str), width = colWidths[index] - (style2["padding-left"] || 0) - (style2["padding-right"] || 0), align = options.colAligns[index] || "left"; - return repeat2(" ", style2["padding-left"] || 0) + (length == width ? str : length < width ? pad2(str, width + (str.length - length), " ", align == "left" ? "right" : align == "middle" ? "both" : "left") : truncater ? truncate(str, width, truncater) : str) + repeat2(" ", style2["padding-right"] || 0); - } - ; - if (head.length) { - lineTop(); - ret += generateRow(head, style2.head) + "\n"; - } - if (this.length) - this.forEach(function(cells, i) { - if (!head.length && i == 0) - lineTop(); - else { - if (!style2.compact || i < !!head.length ? 1 : cells.length == 0) { - var l2 = line(chars.mid, chars["left-mid"], chars["right-mid"], chars["mid-mid"]); - if (l2) - ret += l2 + "\n"; - } - } - if (cells.hasOwnProperty("length") && !cells.length) { - return; - } else { - ret += generateRow(cells) + "\n"; - } - ; - }); - var l = line(chars.bottom, chars["bottom-left"] || chars.bottom, chars["bottom-right"] || chars.bottom, chars["bottom-mid"]); - if (l) - ret += l; - else - ret = ret.slice(0, -1); - return ret; - }; - module2.exports = Table2; - module2.exports.version = "0.0.1"; - } -}); - -// node_modules/ansi-styles/index.js -var require_ansi_styles = __commonJS({ - "node_modules/ansi-styles/index.js"(exports2, module2) { - "use strict"; - var ANSI_BACKGROUND_OFFSET = 10; - var wrapAnsi256 = (offset = 0) => (code) => `[${38 + offset};5;${code}m`; - var wrapAnsi16m = (offset = 0) => (red, green, blue2) => `[${38 + offset};2;${red};${green};${blue2}m`; - function assembleStyles() { - const codes = new Map(); - const styles3 = { - modifier: { - reset: [0, 0], - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - overline: [53, 55], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - styles3.color.gray = styles3.color.blackBright; - styles3.bgColor.bgGray = styles3.bgColor.bgBlackBright; - styles3.color.grey = styles3.color.blackBright; - styles3.bgColor.bgGrey = styles3.bgColor.bgBlackBright; - for (const [groupName, group2] of Object.entries(styles3)) { - for (const [styleName, style2] of Object.entries(group2)) { - styles3[styleName] = { - open: `[${style2[0]}m`, - close: `[${style2[1]}m` - }; - group2[styleName] = styles3[styleName]; - codes.set(style2[0], style2[1]); - } - Object.defineProperty(styles3, groupName, { - value: group2, - enumerable: false - }); - } - Object.defineProperty(styles3, "codes", { - value: codes, - enumerable: false - }); - styles3.color.close = ""; - styles3.bgColor.close = ""; - styles3.color.ansi256 = wrapAnsi256(); - styles3.color.ansi16m = wrapAnsi16m(); - styles3.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); - styles3.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); - Object.defineProperties(styles3, { - rgbToAnsi256: { - value: (red, green, blue2) => { - if (red === green && green === blue2) { - if (red < 8) { - return 16; - } - if (red > 248) { - return 231; - } - return Math.round((red - 8) / 247 * 24) + 232; - } - return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue2 / 255 * 5); - }, - enumerable: false - }, - hexToRgb: { - value: (hex) => { - const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); - if (!matches) { - return [0, 0, 0]; - } - let { colorString } = matches.groups; - if (colorString.length === 3) { - colorString = colorString.split("").map((character) => character + character).join(""); - } - const integer2 = Number.parseInt(colorString, 16); - return [ - integer2 >> 16 & 255, - integer2 >> 8 & 255, - integer2 & 255 - ]; - }, - enumerable: false - }, - hexToAnsi256: { - value: (hex) => styles3.rgbToAnsi256(...styles3.hexToRgb(hex)), - enumerable: false - } - }); - return styles3; - } - Object.defineProperty(module2, "exports", { - enumerable: true, - get: assembleStyles - }); - } -}); - -// src/markdown/styles.ts -function gray(str) { - return `${import_ansi_styles.default.gray.open}${str}${import_ansi_styles.default.gray.close}`; -} -function magenta(str) { - return `${import_ansi_styles.default.magenta.open}${str}${import_ansi_styles.default.magenta.close}`; -} -function bold(str) { - return `${import_ansi_styles.default.bold.open}${str}${import_ansi_styles.default.bold.close}`; -} -function underline(str) { - return `${import_ansi_styles.default.underline.open}${str}${import_ansi_styles.default.underline.close}`; -} -function strikethrough(str) { - return `${import_ansi_styles.default.strikethrough.open}${str}${import_ansi_styles.default.strikethrough.close}`; -} -function italic(str) { - return `${import_ansi_styles.default.italic.open}${str}${import_ansi_styles.default.italic.close}`; -} -function yellow(str) { - return `${import_ansi_styles.default.yellow.open}${str}${import_ansi_styles.default.yellow.close}`; -} -function blue(str) { - return `${import_ansi_styles.default.blue.open}${str}${import_ansi_styles.default.blue.close}`; -} -var import_ansi_styles; -var init_styles = __esm({ - "src/markdown/styles.ts"() { - import_ansi_styles = __toModule(require_ansi_styles()); - } -}); - -// src/markdown/renderer.ts -function fixHardReturn(text, reflow) { - return reflow ? text.replace(HARD_RETURN, /\n/g) : text; -} -function sanitizeTab(tab, fallbackTab) { - if (typeof tab === "number") { - return new Array(tab + 1).join(" "); - } else if (typeof tab === "string" && isAllowedTabString(tab)) { - return tab; - } else { - return new Array(fallbackTab + 1).join(" "); - } -} -function isAllowedTabString(str) { - return TAB_ALLOWED_CHARACTERS.some(function(char) { - return str.match("^(" + char + ")+$"); - }); -} -function indentLines(indent, text) { - return text.replace(/(^|\n)(.+)/g, "$1" + indent + "$2"); -} -function indentify(indent, text) { - if (!text) - return text; - return indent + text.split("\n").join("\n" + indent); -} -function fixNestedLists(body, indent) { - let regex = new RegExp("(\\S(?: | )?)((?:" + indent + ")+)(" + POINT_REGEX + "(?:.*)+)$", "gm"); - return body.replace(regex, "$1\n" + indent + "$2$3"); -} -function toSpaces(str) { - return " ".repeat(str.length); -} -function bulletPointLine(indent, line) { - return isPointedLine(line, indent) ? line : toSpaces(BULLET_POINT) + line; -} -function bulletPointLines(lines, indent) { - let transform = bulletPointLine.bind(null, indent); - return lines.split("\n").filter(identity).map(transform).join("\n"); -} -function numberedLine(indent, line, num) { - return isPointedLine(line, indent) ? { - num: num + 1, - line: line.replace(BULLET_POINT, numberedPoint(num + 1)) - } : { - num, - line: toSpaces(numberedPoint(num)) + line - }; -} -function numberedLines(lines, indent) { - let transform = numberedLine.bind(null, indent); - let num = 0; - return lines.split("\n").filter(identity).map((line) => { - const numbered = transform(line, num); - num = numbered.num; - return numbered.line; - }).join("\n"); -} -function list(body, ordered, indent) { - body = body.trim(); - body = ordered ? numberedLines(body, indent) : bulletPointLines(body, indent); - return body; -} -function section(text) { - return text + "\n\n"; -} -function undoColon(str) { - return str.replace(COLON_REPLACER_REGEXP, ":"); -} -function generateTableRow(text, escape = null) { - if (!text) - return []; - escape = escape || identity; - let lines = escape(text).split("\n"); - let data = []; - lines.forEach(function(line) { - if (!line) - return; - let parsed = line.replace(TABLE_ROW_WRAP_REGEXP, "").split(TABLE_CELL_SPLIT); - data.push(parsed.splice(0, parsed.length - 1)); - }); - return data; -} -function escapeRegExp(str) { - return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); -} -function unescapeEntities(html) { - return html.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'"); -} -function identity(str) { - return str; -} -var import_cli_table, logger3, TABLE_CELL_SPLIT, TABLE_ROW_WRAP, TABLE_ROW_WRAP_REGEXP, COLON_REPLACER, COLON_REPLACER_REGEXP, TAB_ALLOWED_CHARACTERS, HARD_RETURN, defaultOptions, BULLET_POINT_REGEX, NUMBERED_POINT_REGEX, POINT_REGEX, isPointedLine, BULLET_POINT, numberedPoint, links, Renderer, renderer_default; -var init_renderer = __esm({ - "src/markdown/renderer.ts"() { - import_cli_table = __toModule(require_lib7()); - init_styles(); - logger3 = require_logger2()("markdown-renderer"); - TABLE_CELL_SPLIT = "^*||*^"; - TABLE_ROW_WRAP = "*|*|*|*"; - TABLE_ROW_WRAP_REGEXP = new RegExp(escapeRegExp(TABLE_ROW_WRAP), "g"); - COLON_REPLACER = "*#COLON|*"; - COLON_REPLACER_REGEXP = new RegExp(escapeRegExp(COLON_REPLACER), "g"); - TAB_ALLOWED_CHARACTERS = [" "]; - HARD_RETURN = "\r"; - defaultOptions = { - code: identity, - blockquote: identity, - html: gray, - heading: magenta, - firstHeading: magenta, - hr: identity, - listitem: identity, - list, - table: identity, - paragraph: identity, - strong: bold, - em: italic, - codespan: yellow, - del: strikethrough, - link: underline, - href: underline, - text: identity, - unescape: true, - emoji: false, - width: 80, - showSectionPrefix: true, - tab: 2, - tableOptions: {} - }; - BULLET_POINT_REGEX = "\\*"; - NUMBERED_POINT_REGEX = "\\d+\\."; - POINT_REGEX = "(?:" + [BULLET_POINT_REGEX, NUMBERED_POINT_REGEX].join("|") + ")"; - isPointedLine = function(line, indent) { - return line.match("^(?:" + indent + ")*" + POINT_REGEX); - }; - BULLET_POINT = "* "; - numberedPoint = function(n) { - return n + ". "; - }; - links = new Map(); - Renderer = class { - constructor(options = {}, highlightOptions = {}) { - this.options = options; - this.highlightOptions = highlightOptions; - this.o = Object.assign({}, defaultOptions, options); - this.tab = sanitizeTab(this.o.tab, defaultOptions.tab); - this.tableSettings = this.o.tableOptions; - this.unescape = this.o.unescape ? unescapeEntities : identity; - this.highlightOptions = highlightOptions || {}; - this.transform = this.compose(undoColon, this.unescape); - } - textLength(str) { - return str.replace(/\u001b\[(?:\d{1,3})(?:;\d{1,3})*m/g, "").length; - } - text(t) { - return this.o.text(t); - } - code(code, lang, _escaped) { - return "``` " + lang + "\n" + code + "\n```\n"; - } - blockquote(quote) { - return section(this.o.blockquote(indentify(this.tab, quote.trim()))); - } - html(html) { - return this.o.html(html); - } - heading(text, level, _raw) { - text = this.transform(text); - let prefix = this.o.showSectionPrefix ? new Array(level + 1).join("#") + " " : ""; - text = prefix + text; - return section(level === 1 ? this.o.firstHeading(text) : this.o.heading(text)); - } - hr() { - return `\u2500\u2500\u2500 -`; - } - list(body, ordered) { - body = this.o.list(body, ordered, this.tab); - return section(fixNestedLists(indentLines(this.tab, body), this.tab)); - } - listitem(text) { - let transform = this.compose(this.o.listitem, this.transform); - let isNested = text.indexOf("\n") !== -1; - if (isNested) - text = text.trim(); - return "\n" + BULLET_POINT + transform(text); - } - checkbox(checked) { - return "[" + (checked ? "X" : " ") + "] "; - } - paragraph(text) { - let transform = this.compose(this.o.paragraph, this.transform); - text = transform(text); - return section(text); - } - table(header, body) { - let table = new import_cli_table.default(Object.assign({}, { - head: generateTableRow(header)[0] - }, this.tableSettings)); - generateTableRow(body, this.transform).forEach(function(row) { - table.push(row); - }); - return section(this.o.table(table.toString())); - } - tablerow(content) { - return TABLE_ROW_WRAP + content + TABLE_ROW_WRAP + "\n"; - } - tablecell(content, _flags) { - return content + TABLE_CELL_SPLIT; - } - strong(text) { - return this.o.strong(text); - } - em(text) { - text = fixHardReturn(text, this.o.reflowText); - return this.o.em(text); - } - codespan(text) { - text = fixHardReturn(text, this.o.reflowText); - return this.o.codespan(text.replace(/:/g, COLON_REPLACER)); - } - br() { - return "\n"; - } - del(text) { - return this.o.del(text); - } - link(href, title, text) { - let prot; - if (this.options.sanitize) { - try { - prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g, "").toLowerCase(); - } catch (e) { - return ""; - } - if (prot.startsWith("javascript:")) { - return ""; - } - } - if (text && href && text != href) { - links.set(text, href); - } - if (text && text != href) - return blue(text); - let out = this.o.href(href); - return this.o.link(out); - } - image(href, title, text) { - if (typeof this.o.image === "function") { - return this.o.image(href, title, text); - } - let out = "![" + text; - if (title) - out += " \u2013 " + title; - return out + "](" + href + ")\n"; - } - compose(...funcs) { - return (...args) => { - for (let i = funcs.length; i-- > 0; ) { - args = [funcs[i].apply(this, args)]; - } - return args[0]; - }; - } - static getLinks() { - let res = []; - for (let [text, href] of links.entries()) { - res.push(`${blue(text)}: ${href}`); - } - links.clear(); - return res; - } - }; - renderer_default = Renderer; - } -}); - -// src/util/string.ts -function rangeParts(text, range) { - let { start, end } = range; - let lines = text.split(/\r?\n/); - let before = ""; - let after = ""; - let len = lines.length; - for (let i = 0; i < len; i++) { - let curr = lines[i]; - if (i < start.line) { - before += curr + "\n"; - continue; - } - if (i > end.line) { - after += curr + (i == len - 1 ? "" : "\n"); - continue; - } - if (i == start.line) { - before += curr.slice(0, start.character); - } - if (i == end.line) { - after += curr.slice(end.character) + (i == len - 1 ? "" : "\n"); - } - } - return [before, after]; -} -function byteLength(str) { - return Buffer.byteLength(str); -} -function upperFirst(str) { - return str ? str[0].toUpperCase() + str.slice(1) : ""; -} -function byteIndex(content, index) { - let s = content.slice(0, index); - return Buffer.byteLength(s); -} -function characterIndex(content, byteIndex2) { - let buf = Buffer.from(content, "utf8"); - return buf.slice(0, byteIndex2).toString("utf8").length; -} -function byteSlice(content, start, end) { - let buf = Buffer.from(content, "utf8"); - return buf.slice(start, end).toString("utf8"); -} -function isWord(character) { - let code = character.charCodeAt(0); - if (code > 128) - return false; - if (code == 95) - return true; - if (code >= 48 && code <= 57) - return true; - if (code >= 65 && code <= 90) - return true; - if (code >= 97 && code <= 122) - return true; - return false; -} -var init_string = __esm({ - "src/util/string.ts"() { - } -}); - -// src/util/ansiparse.ts -function parseAnsiHighlights(line, markdown = false) { - let items = ansiparse(line); - let highlights = []; - let newLabel = ""; - for (let item of items) { - if (!item.text) - continue; - let { foreground, background, bold: bold2, italic: italic2, underline: underline2 } = item; - let len = byteLength(newLabel); - if (foreground || background || bold2 || italic2 || underline2) { - let span = [len, len + byteLength(item.text)]; - let hlGroup = ""; - if (foreground && background) { - hlGroup = `CocList${upperFirst(foreground)}${upperFirst(background)}`; - } else if (foreground) { - if (markdown) { - if (foreground == "yellow") { - hlGroup = "CocMarkdownCode"; - } else if (foreground == "blue") { - hlGroup = "CocMarkdownLink"; - } else if (foreground == "magenta") { - hlGroup = "CocMarkdownHeader"; - } else { - hlGroup = `CocListFg${upperFirst(foreground)}`; - } - } else { - hlGroup = `CocListFg${upperFirst(foreground)}`; - } - } else if (background) { - hlGroup = `CocListBg${upperFirst(background)}`; - } else if (bold2) { - hlGroup = "CocBold"; - } else if (italic2) { - hlGroup = "CocItalic"; - } else if (underline2) { - hlGroup = "CocUnderline"; - } - highlights.push({ span, hlGroup }); - } - newLabel = newLabel + item.text; - } - return { line: newLabel, highlights }; -} -function ansiparse(str) { - let matchingControl = null; - let matchingData = null; - let matchingText = ""; - let ansiState = []; - let result = []; - let state = {}; - let eraseChar; - eraseChar = () => { - let index; - let text; - if (matchingText.length) { - matchingText = matchingText.substr(0, matchingText.length - 1); - } else if (result.length) { - index = result.length - 1; - text = result[index].text; - if (text.length === 1) { - result.pop(); - } else { - result[index].text = text.substr(0, text.length - 1); - } - } - }; - for (let i = 0; i < str.length; i++) { - if (matchingControl != null) { - if (matchingControl == "" && str[i] == "[") { - if (matchingText) { - state.text = matchingText; - result.push(state); - state = {}; - matchingText = ""; - } - if (matchingText == "" && (str[i + 1] == "m" || str[i + 1] == "K")) { - if (state.foreground || state.background) { - state.text = ""; - result.push(state); - } - state = {}; - } - matchingControl = null; - matchingData = ""; - } else { - matchingText += matchingControl + str[i]; - matchingControl = null; - } - continue; - } else if (matchingData != null) { - if (str[i] == ";") { - ansiState.push(matchingData); - matchingData = ""; - } else if (str[i] == "m" || str[i] == "K") { - ansiState.push(matchingData); - matchingData = null; - matchingText = ""; - ansiState.forEach((ansiCode) => { - if (foregroundColors[ansiCode]) { - state.foreground = foregroundColors[ansiCode]; - } else if (backgroundColors[ansiCode]) { - state.background = backgroundColors[ansiCode]; - } else if (ansiCode == 39) { - delete state.foreground; - } else if (ansiCode == 49) { - delete state.background; - } else if (styles2[ansiCode]) { - state[styles2[ansiCode]] = true; - } else if (ansiCode == 22) { - state.bold = false; - } else if (ansiCode == 23) { - state.italic = false; - } else if (ansiCode == 24) { - state.underline = false; - } - }); - ansiState = []; - } else { - matchingData += str[i]; - } - continue; - } - if (str[i] == "") { - matchingControl = str[i]; - } else if (str[i] == "\b") { - eraseChar(); - } else { - matchingText += str[i]; - } - } - if (matchingText) { - state.text = matchingText + (matchingControl ? matchingControl : ""); - result.push(state); - } - return result; -} -var foregroundColors, backgroundColors, styles2; -var init_ansiparse = __esm({ - "src/util/ansiparse.ts"() { - init_string(); - foregroundColors = { - 30: "black", - 31: "red", - 32: "green", - 33: "yellow", - 34: "blue", - 35: "magenta", - 36: "cyan", - 37: "white", - 90: "grey" - }; - backgroundColors = { - 40: "black", - 41: "red", - 42: "green", - 43: "yellow", - 44: "blue", - 45: "magenta", - 46: "cyan", - 47: "white" - }; - styles2 = { - 1: "bold", - 3: "italic", - 4: "underline" - }; - } -}); - -// node_modules/ansi-regex/index.js -var require_ansi_regex = __commonJS({ - "node_modules/ansi-regex/index.js"(exports2, module2) { - "use strict"; - module2.exports = ({ onlyFirst = false } = {}) => { - const pattern = [ - "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", - "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))" - ].join("|"); - return new RegExp(pattern, onlyFirst ? void 0 : "g"); - }; - } -}); - -// node_modules/strip-ansi/index.js -var require_strip_ansi = __commonJS({ - "node_modules/strip-ansi/index.js"(exports2, module2) { - "use strict"; - var ansiRegex = require_ansi_regex(); - module2.exports = (string2) => typeof string2 === "string" ? string2.replace(ansiRegex(), "") : string2; - } -}); - -// src/markdown/index.ts -function parseDocuments(docs, opts = {}) { - let lines = []; - let highlights = []; - let codes = []; - let idx = 0; - for (let doc of docs) { - let currline = lines.length; - let { content, filetype } = doc; - if (filetype == "markdown") { - let info = parseMarkdown(content, opts); - codes.push(...info.codes.map((o) => { - o.startLine = o.startLine + currline; - o.endLine = o.endLine + currline; - return o; - })); - highlights.push(...info.highlights.map((o) => { - o.lnum = o.lnum + currline; - return o; - })); - lines.push(...info.lines); - } else { - let parts = content.trim().split(/\r?\n/); - if (diagnosticFiletypes.includes(doc.filetype)) { - codes.push({ hlGroup: `Coc${filetype}Float`, startLine: currline, endLine: currline + parts.length }); - } else { - codes.push({ filetype: doc.filetype, startLine: currline, endLine: currline + parts.length }); - } - lines.push(...parts); - } - if (doc.active) { - let arr = getHighlightItems(content, currline, doc.active); - if (arr.length) - highlights.push(...arr); - } - if (idx != docs.length - 1) { - lines.push("\u2500"); - } - idx = idx + 1; - } - return { lines, highlights, codes }; -} -function getHighlightItems(content, currline, active) { - let res = []; - let [start, end] = active; - let lines = content.split(/\r?\n/); - let used = 0; - let inRange = false; - for (let i = 0; i < lines.length; i++) { - let line = lines[i]; - if (!inRange) { - if (used + line.length > start) { - inRange = true; - let colStart = byteLength(line.slice(0, start - used)); - if (used + line.length > end) { - let colEnd = byteLength(line.slice(0, end - used)); - inRange = false; - res.push({ colStart, colEnd, lnum: i + currline, hlGroup: "CocUnderline" }); - break; - } else { - let colEnd = byteLength(line); - res.push({ colStart, colEnd, lnum: i + currline, hlGroup: "CocUnderline" }); - } - } - } else { - if (used + line.length > end) { - let colEnd = byteLength(line.slice(0, end - used)); - res.push({ colStart: 0, colEnd, lnum: i + currline, hlGroup: "CocUnderline" }); - inRange = false; - break; - } else { - let colEnd = byteLength(line); - res.push({ colStart: 0, colEnd, lnum: i + currline, hlGroup: "CocUnderline" }); - } - } - used = used + line.length + 1; - } - return res; -} -function parseMarkdown(content, opts) { - import_marked.default.setOptions({ - renderer: new renderer_default(), - gfm: true - }); - let lines = []; - let highlights = []; - let codes = []; - let currline = 0; - let inCodeBlock = false; - let filetype; - let startLnum = 0; - let parsed = (0, import_marked.default)(content); - let links2 = renderer_default.getLinks(); - if (links2.length) { - parsed = parsed + "\n\n" + links2.join("\n"); - } - parsed = parsed.replace(/\s*$/, ""); - let parsedLines = parsed.split(/\n/); - for (let i = 0; i < parsedLines.length; i++) { - let line = parsedLines[i]; - if (!line.length) { - let pre = lines[lines.length - 1]; - if (pre && pre.length) { - lines.push(line); - currline++; - } - continue; - } - if (opts.excludeImages && line.indexOf("![") !== -1) { - line = line.replace(/\s*!\[.*?\]\(.*?\)/g, ""); - if (!(0, import_strip_ansi.default)(line).trim().length) - continue; - } - if (/\s*```\s*([A-Za-z0-9_,]+)?$/.test(line)) { - if (!inCodeBlock) { - let pre = parsedLines[i - 1]; - if (pre && /^\s*```\s*/.test(pre)) { - lines.push(""); - currline++; - } - inCodeBlock = true; - filetype = line.replace(/^\s*```\s*/, ""); - if (filetype == "js") - filetype = "javascript"; - if (filetype == "ts") - filetype = "typescript"; - if (filetype == "bash") - filetype = "sh"; - startLnum = currline; - } else { - inCodeBlock = false; - codes.push({ - filetype, - startLine: startLnum, - endLine: currline - }); - } - continue; - } - if (inCodeBlock) { - lines.push(line); - currline++; - continue; - } - let res = parseAnsiHighlights(line, true); - if (res.highlights) { - for (let hi of res.highlights) { - let { hlGroup, span } = hi; - highlights.push({ - hlGroup, - lnum: currline, - colStart: span[0], - colEnd: span[1] - }); - } - } - lines.push(res.line); - currline++; - } - return { lines, highlights, codes }; -} -var import_marked, import_strip_ansi, diagnosticFiletypes, logger4; -var init_markdown = __esm({ - "src/markdown/index.ts"() { - import_marked = __toModule(require_marked()); - init_renderer(); - init_ansiparse(); - init_string(); - import_strip_ansi = __toModule(require_strip_ansi()); - diagnosticFiletypes = ["Error", "Warning", "Info", "Hint"]; - logger4 = require_logger2()("markdown-index"); - } -}); - -// src/util/mutex.ts -var Mutex; -var init_mutex = __esm({ - "src/util/mutex.ts"() { - Mutex = class { - constructor() { - this.tasks = []; - this.count = 1; - } - sched() { - if (this.count > 0 && this.tasks.length > 0) { - this.count--; - let next = this.tasks.shift(); - next(); - } - } - get busy() { - return this.count == 0; - } - acquire() { - return new Promise((res) => { - let task = () => { - let released = false; - res(() => { - if (!released) { - released = true; - this.count++; - this.sched(); - } - }); - }; - this.tasks.push(task); - process.nextTick(this.sched.bind(this)); - }); - } - use(f) { - return this.acquire().then((release) => f().then((res) => { - release(); - return res; - }).catch((err) => { - release(); - throw err; - })); - } - }; - } -}); - -// src/model/floatFactory.ts -var import_debounce2, import_vscode_languageserver_protocol3, isVim, logger5, FloatFactory; -var init_floatFactory = __esm({ - "src/model/floatFactory.ts"() { - import_debounce2 = __toModule(require_debounce()); - import_vscode_languageserver_protocol3 = __toModule(require_main2()); - init_events(); - init_markdown(); - init_util(); - init_mutex(); - init_object(); - isVim = process.env.VIM_NODE_RPC == "1"; - logger5 = require_logger2()("model-float"); - FloatFactory = class { - constructor(nvim) { - this.nvim = nvim; - this.winid = 0; - this._bufnr = 0; - this.mutex = new Mutex(); - this.disposables = []; - this.onCursorMoved = (0, import_debounce2.default)(this._onCursorMoved.bind(this), 100); - } - bindEvents(autoHide, alignTop) { - let eventNames = ["InsertLeave", "InsertEnter", "BufEnter"]; - for (let ev of eventNames) { - events_default.on(ev, (bufnr) => { - if (bufnr == this._bufnr) - return; - this.close(); - }, null, this.disposables); - } - events_default.on("MenuPopupChanged", () => { - if (events_default.pumAlignTop == alignTop) { - this.close(); - } - }, null, this.disposables); - this.disposables.push(import_vscode_languageserver_protocol3.Disposable.create(() => { - this.onCursorMoved.clear(); - })); - events_default.on("CursorMoved", this.onCursorMoved.bind(this, autoHide), this, this.disposables); - events_default.on("CursorMovedI", this.onCursorMoved.bind(this, autoHide), this, this.disposables); - } - unbind() { - if (this.disposables.length) { - disposeAll(this.disposables); - this.disposables = []; - } - } - _onCursorMoved(autoHide, bufnr, cursor) { - if (bufnr == this._bufnr) - return; - if (bufnr == this.targetBufnr && equals(cursor, this.cursor)) { - return; - } - if (autoHide || bufnr != this.targetBufnr || !events_default.insertMode) { - this.close(); - return; - } - } - async create(docs, _allowSelection = false, offsetX = 0) { - await this.show(docs, { - offsetX - }); - } - applyFloatConfig(conf, opts) { - for (let key of Object.keys(opts)) { - if (key == "border") { - if (opts.border) - conf.border = [1, 1, 1, 1]; - continue; - } - conf[key] = opts[key]; - } - return conf; - } - async show(docs, config = {}) { - if (docs.length == 0 || docs.every((doc) => doc.content.length == 0)) { - this.close(); - return; - } - let curr = Date.now(); - let release = await this.mutex.acquire(); - try { - await this.createPopup(docs, config, curr); - release(); - } catch (e) { - this.nvim.echoError(e); - release(); - } - } - async createPopup(docs, opts, timestamp) { - docs = docs.filter((o) => o.content.trim().length > 0); - let { lines, codes, highlights } = parseDocuments(docs); - let config = { - pumAlignTop: events_default.pumAlignTop, - preferTop: typeof opts.preferTop === "boolean" ? opts.preferTop : false, - offsetX: opts.offsetX || 0, - title: opts.title || "", - close: opts.close ? 1 : 0, - codes, - highlights, - modes: opts.modes || ["n", "i", "ic", "s"] - }; - if (!isVim) { - if (typeof opts.winblend === "number") - config.winblend = opts.winblend; - if (opts.focusable != null) - config.focusable = opts.focusable ? 1 : 0; - if (opts.shadow) - config.shadow = 1; - } - if (opts.maxHeight) - config.maxHeight = opts.maxHeight; - if (opts.maxWidth) - config.maxWidth = opts.maxWidth; - if (opts.border && !opts.border.every((o) => o == 0)) { - config.border = opts.border; - } - if (opts.title && !config.border) - config.border = [1, 1, 1, 1]; - if (opts.highlight) - config.highlight = opts.highlight; - if (opts.borderhighlight) - config.borderhighlight = [opts.borderhighlight]; - if (opts.cursorline) - config.cursorline = 1; - let autoHide = opts.autoHide == false ? false : true; - if (autoHide) - config.autohide = 1; - this.unbind(); - let arr = await this.nvim.call("coc#float#create_cursor_float", [this.winid, this._bufnr, lines, config]); - this.nvim.redrawVim(); - if (!arr || arr.length == 0 || this.closeTs > timestamp) { - let winid2 = arr && arr.length > 0 ? arr[2] : this.winid; - if (winid2) { - this.winid = 0; - this.nvim.call("coc#float#close", [winid2], true); - this.nvim.redrawVim(); - } - return; - } - let [targetBufnr, cursor, winid, bufnr, alignTop] = arr; - this.winid = winid; - this._bufnr = bufnr; - this.targetBufnr = targetBufnr; - this.cursor = cursor; - this.bindEvents(autoHide, alignTop == 1); - } - close() { - let { winid, nvim } = this; - this.closeTs = Date.now(); - this.unbind(); - if (winid) { - this.winid = 0; - nvim.call("coc#float#close", [winid], true); - nvim.redrawVim(); - } - } - checkRetrigger(bufnr) { - if (this.winid && this.targetBufnr == bufnr) - return true; - return false; - } - get bufnr() { - return this._bufnr; - } - get buffer() { - return this.bufnr ? this.nvim.createBuffer(this.bufnr) : null; - } - get window() { - return this.winid ? this.nvim.createWindow(this.winid) : null; - } - async activated() { - if (!this.winid) - return false; - return await this.nvim.call("coc#float#valid", [this.winid]) != 0; - } - dispose() { - this.cursor = void 0; - this.close(); - } - }; - } -}); - -// src/util/position.ts -function rangeInRange(r, range) { - return positionInRange(r.start, range) === 0 && positionInRange(r.end, range) === 0; -} -function rangeOverlap(r, range) { - let { start, end } = r; - if (comparePosition(end, range.start) <= 0) { - return false; - } - if (comparePosition(start, range.end) >= 0) { - return false; - } - return true; -} -function rangeIntersect(r, range) { - if (positionInRange(r.start, range) == 0) { - return true; - } - if (positionInRange(r.end, range) == 0) { - return true; - } - if (rangeInRange(range, r)) { - return true; - } - return false; -} -function lineInRange(line, range) { - let { start, end } = range; - return line >= start.line && line <= end.line; -} -function emptyRange(range) { - let { start, end } = range; - return start.line == end.line && start.character == end.character; -} -function positionInRange(position, range) { - let { start, end } = range; - if (comparePosition(position, start) < 0) - return -1; - if (comparePosition(position, end) > 0) - return 1; - return 0; -} -function comparePosition(position, other) { - if (position.line > other.line) - return 1; - if (other.line == position.line && position.character > other.character) - return 1; - if (other.line == position.line && position.character == other.character) - return 0; - return -1; -} -function isSingleLine(range) { - return range.start.line == range.end.line; -} -function getChangedPosition(start, edit2) { - let { range, newText } = edit2; - if (comparePosition(range.end, start) <= 0) { - let lines = newText.split("\n"); - let lineCount = lines.length - (range.end.line - range.start.line) - 1; - let characterCount = 0; - if (range.end.line == start.line) { - let single = isSingleLine(range) && lineCount == 0; - let removed = single ? range.end.character - range.start.character : range.end.character; - let added = single ? newText.length : lines[lines.length - 1].length; - characterCount = added - removed; - } - return { line: lineCount, character: characterCount }; - } - return { line: 0, character: 0 }; -} -function adjustPosition(pos, edit2) { - let { range, newText } = edit2; - if (comparePosition(range.start, pos) > 1) - return pos; - let { start, end } = range; - let newLines = newText.split("\n"); - let delta = end.line - start.line - newLines.length + 1; - let lastLine = newLines[newLines.length - 1]; - let line = pos.line - delta; - if (pos.line != end.line) - return { line, character: pos.character }; - let pre = newLines.length == 1 && start.line != end.line ? start.character : 0; - let removed = start.line == end.line && newLines.length == 1 ? end.character - start.character : end.character; - let character = pre + pos.character + lastLine.length - removed; - return { - line, - character - }; -} -function positionToOffset(lines, line, character) { - let offset = 0; - for (let i = 0; i <= line; i++) { - if (i == line) { - offset += character; - } else { - offset += lines[i].length + 1; - } - } - return offset; -} -function editRange(range, text, edit2) { - if (!rangeInRange(edit2.range, range)) - return text; - let { start, end } = edit2.range; - let lines = text.split("\n"); - let character = start.line == range.start.line ? start.character - range.start.character : start.character; - let startOffset = positionToOffset(lines, start.line - range.start.line, character); - character = end.line == range.start.line ? end.character - range.start.character : end.character; - let endOffset = positionToOffset(lines, end.line - range.start.line, character); - return `${text.slice(0, startOffset)}${edit2.newText}${text.slice(endOffset, text.length)}`; -} -function getChangedFromEdits(start, edits) { - let changed = { line: 0, character: 0 }; - for (let edit2 of edits) { - let d = getChangedPosition(start, edit2); - changed = { line: changed.line + d.line, character: changed.character + d.character }; - } - return changed.line == 0 && changed.character == 0 ? null : changed; -} -var init_position = __esm({ - "src/util/position.ts"() { - } -}); - -// src/model/outputChannel.ts -var logger6, BufferChannel; -var init_outputChannel = __esm({ - "src/model/outputChannel.ts"() { - init_util(); - logger6 = require_logger2()("outpubChannel"); - BufferChannel = class { - constructor(name2, nvim, onDispose) { - this.name = name2; - this.nvim = nvim; - this.onDispose = onDispose; - this.lines = [""]; - this.disposables = []; - this._disposed = false; - this.created = false; - } - get content() { - return this.lines.join("\n"); - } - _append(value) { - let { nvim } = this; - let idx = this.lines.length - 1; - let newlines = value.split(/\r?\n/); - let lastline = this.lines[idx] + newlines[0]; - this.lines[idx] = lastline; - let append = newlines.slice(1); - this.lines = this.lines.concat(append); - if (!this.created) - return; - nvim.pauseNotification(); - nvim.call("setbufline", [this.bufname, "$", lastline], true); - if (append.length) { - nvim.call("appendbufline", [this.bufname, "$", append], true); - } - nvim.resumeNotification(false, true); - } - append(value) { - if (!this.validate()) - return; - this._append(value); - } - appendLine(value) { - if (!this.validate()) - return; - this._append(value + "\n"); - } - clear(keep) { - if (!this.validate()) - return; - let { nvim } = this; - this.lines = keep ? this.lines.slice(-keep) : []; - if (!this.created) - return; - nvim.pauseNotification(); - nvim.call("deletebufline", [this.bufname, 1, "$"], true); - if (this.lines.length) { - nvim.call("appendbufline", [this.bufname, "$", this.lines], true); - } - nvim.resumeNotification(false, true); - } - hide() { - this.created = false; - this.nvim.command(`exe 'silent! bd! '.fnameescape('${this.bufname}')`, true); - } - get bufname() { - return `output:///${this.name}`; - } - show(preserveFocus) { - let { nvim } = this; - nvim.pauseNotification(); - nvim.command(`exe 'vsplit '.fnameescape('${this.bufname}')`, true); - if (preserveFocus) { - nvim.command("wincmd p", true); - } - nvim.command("redraw", true); - nvim.resumeNotification(false, true); - this.created = true; - } - validate() { - return !this._disposed; - } - dispose() { - if (this.onDispose) - this.onDispose(); - this._disposed = true; - this.hide(); - this.lines = []; - disposeAll(this.disposables); - } - }; - } -}); - -// src/channels.ts -var logger7, Channels, channels_default; -var init_channels = __esm({ - "src/channels.ts"() { - init_outputChannel(); - init_events(); - logger7 = require_logger2()("channels"); - Channels = class { - constructor() { - this.outputChannels = new Map(); - this.bufnrs = new Map(); - this.disposable = events_default.on("BufUnload", (bufnr) => { - let name2 = this.bufnrs.get(bufnr); - if (name2) { - let channel = this.outputChannels.get(name2); - if (channel) - channel.created = false; - } - }); - } - getProvider(nvim) { - let provider = { - onDidChange: null, - provideTextDocumentContent: async (uri) => { - let channel = this.get(uri.path.slice(1)); - if (!channel) - return ""; - nvim.pauseNotification(); - nvim.call("bufnr", ["%"], true); - nvim.command("setlocal nospell nofoldenable nowrap noswapfile", true); - nvim.command("setlocal buftype=nofile bufhidden=hide", true); - nvim.command("setfiletype log", true); - let res = await nvim.resumeNotification(); - if (!res[1]) { - this.bufnrs.set(res[0][0], channel.name); - channel.created = true; - } - return channel.content; - } - }; - return provider; - } - get names() { - return Array.from(this.outputChannels.keys()); - } - get(channelName) { - return this.outputChannels.get(channelName); - } - create(name2, nvim) { - if (this.outputChannels.has(name2)) - return this.outputChannels.get(name2); - if (!/^[\w\s-.]+$/.test(name2)) - throw new Error(`Invalid channel name "${name2}", only word characters and white space allowed.`); - let channel = new BufferChannel(name2, nvim, () => { - this.outputChannels.delete(name2); - }); - this.outputChannels.set(name2, channel); - return channel; - } - show(name2, preserveFocus) { - let channel = this.outputChannels.get(name2); - if (!channel) - return; - channel.show(preserveFocus); - } - dispose() { - this.disposable.dispose(); - for (let channel of this.outputChannels.values()) { - channel.dispose(); - } - this.outputChannels.clear(); - } - }; - channels_default = new Channels(); - } -}); - -// src/model/dialog.ts -var logger8, Dialog; -var init_dialog = __esm({ - "src/model/dialog.ts"() { - init_events(); - init_util(); - logger8 = require_logger2()("model-dialog"); - Dialog = class { - constructor(nvim, config) { - this.nvim = nvim; - this.config = config; - this.disposables = []; - events_default.on("BufWinLeave", (bufnr) => { - if (bufnr == this.bufnr) { - this.dispose(); - if (config.callback) - config.callback(-1); - } - }, null, this.disposables); - events_default.on("FloatBtnClick", (bufnr, idx) => { - if (bufnr == this.bufnr) { - this.dispose(); - let btns = config == null ? void 0 : config.buttons.filter((o) => o.disabled != true); - if (config.callback) - config.callback(btns[idx].index); - } - }, null, this.disposables); - } - get lines() { - return [...this.config.content.split(/\r?\n/)]; - } - async show(preferences) { - let { nvim } = this; - let { title, close, buttons } = this.config; - let borderhighlight = this.config.borderhighlight || preferences.floatBorderHighlight; - let highlight = this.config.highlight || preferences.floatHighlight; - let opts = { maxwidth: preferences.maxWidth || 80 }; - if (title) - opts.title = title; - if (close || typeof close === "undefined") - opts.close = 1; - if (preferences.maxHeight) - opts.maxHeight = preferences.maxHeight; - if (preferences.maxWidth) - opts.maxWidth = preferences.maxWidth; - if (highlight) - opts.highlight = highlight; - if (borderhighlight) - opts.borderhighlight = [borderhighlight]; - if (buttons) - opts.buttons = buttons.filter((o) => !o.disabled).map((o) => o.text); - let res = await nvim.call("coc#float#create_dialog", [this.lines, opts]); - if (!res[1]) - return; - this.bufnr = res[1]; - nvim.command("redraw", true); - } - get winid() { - if (!this.bufnr) - return Promise.resolve(null); - return this.nvim.call("bufwinid", [this.bufnr]); - } - dispose() { - this.bufnr = void 0; - disposeAll(this.disposables); - this.disposables = []; - } - }; - } -}); - -// src/model/popup.ts -var isVim2, Popup; -var init_popup = __esm({ - "src/model/popup.ts"() { - isVim2 = process.env.VIM_NODE_RPC == "1"; - Popup = class { - constructor(nvim, winid, bufnr) { - this.nvim = nvim; - this.winid = winid; - this.bufnr = bufnr; - } - get valid() { - return this.nvim.call("coc#float#valid", [this.winid]).then((res) => { - return !!res; - }); - } - close() { - this.nvim.call("coc#float#close", [this.winid], true); - } - refreshScrollbar() { - if (!isVim2) - this.nvim.call("coc#float#nvim_scrollbar", [this.winid], true); - } - execute(cmd) { - this.nvim.call("coc#compat#execute", [this.winid, cmd], true); - } - async scrollForward() { - let { nvim, bufnr, winid } = this; - let buf = nvim.createBuffer(bufnr); - let total = await buf.length; - let botline; - if (!isVim2) { - let infos = await nvim.call("getwininfo", [winid]); - if (!infos || !infos.length) - return; - botline = infos[0].botline; - } else { - botline = await nvim.eval(`get(popup_getpos(${winid}), 'lastline', 0)`); - } - if (botline >= total || botline == 0) - return; - nvim.pauseNotification(); - this.setCursor(botline - 1); - this.execute(`silent! noa setl scrolloff=0`); - this.execute(`normal! ${botline}Gzt`); - this.refreshScrollbar(); - nvim.command("redraw", true); - nvim.resumeNotification(false, true); - } - async scrollBackward() { - let { nvim, winid } = this; - let topline; - if (!isVim2) { - let infos = await nvim.call("getwininfo", [winid]); - if (!infos || !infos.length) - return; - topline = infos[0].topline; - } else { - topline = await nvim.eval(`get(popup_getpos(${winid}), 'firstline', 0)`); - } - if (topline == 1) - return; - nvim.pauseNotification(); - this.setCursor(topline - 1); - this.execute(`normal! ${topline}Gzb`); - this.refreshScrollbar(); - nvim.command("redraw", true); - nvim.resumeNotification(false, true); - } - setCursor(index) { - let { nvim, bufnr, winid } = this; - if (isVim2) { - nvim.call("win_execute", [winid, `exe ${index + 1}`], true); - } else { - let win = nvim.createWindow(winid); - win.notify("nvim_win_set_cursor", [[index + 1, 0]]); - nvim.command(`sign unplace 6 buffer=${bufnr}`, true); - nvim.command(`sign place 6 line=${index + 1} name=CocCurrentLine buffer=${bufnr}`, true); - } - } - }; - } -}); - -// src/model/menu.ts -var import_vscode_languageserver_protocol4, logger9, Menu; -var init_menu = __esm({ - "src/model/menu.ts"() { - import_vscode_languageserver_protocol4 = __toModule(require_main2()); - init_events(); - init_util(); - init_popup(); - logger9 = require_logger2()("model-menu"); - Menu = class { - constructor(nvim, config, token) { - this.nvim = nvim; - this.config = config; - this.currIndex = 0; - this.disposables = []; - this.keyMappings = new Map(); - this._onDidClose = new import_vscode_languageserver_protocol4.Emitter(); - this.onDidClose = this._onDidClose.event; - this.total = config.items.length; - if (token) { - token.onCancellationRequested(() => { - var _a2; - (_a2 = this.win) == null ? void 0 : _a2.close(); - }); - } - this.disposables.push(this._onDidClose); - this.addKeymappings(); - } - attachEvents() { - events_default.on("InputChar", this.onInputChar.bind(this), null, this.disposables); - events_default.on("BufWinLeave", (bufnr) => { - if (bufnr == this.bufnr) { - this._onDidClose.fire(-1); - this.bufnr = void 0; - this.win = void 0; - this.dispose(); - } - }, null, this.disposables); - } - addKeymappings() { - let { nvim } = this; - this.addKeys(["", ""], () => { - this._onDidClose.fire(-1); - this.dispose(); - }); - this.addKeys(["\r", ""], () => { - this._onDidClose.fire(this.currIndex); - this.dispose(); - }); - let setCursorIndex = (idx) => { - var _a2; - if (!this.win) - return; - nvim.pauseNotification(); - this.setCursor(idx); - (_a2 = this.win) == null ? void 0 : _a2.refreshScrollbar(); - nvim.command("redraw", true); - nvim.resumeNotification(false, true); - }; - this.addKeys("", async () => { - var _a2; - await ((_a2 = this.win) == null ? void 0 : _a2.scrollForward()); - }); - this.addKeys("", async () => { - var _a2; - await ((_a2 = this.win) == null ? void 0 : _a2.scrollBackward()); - }); - this.addKeys(["j", "", "", ""], () => { - let idx = this.currIndex == this.total - 1 ? 0 : this.currIndex + 1; - setCursorIndex(idx); - }); - this.addKeys(["k", "", "", ""], () => { - let idx = this.currIndex == 0 ? this.total - 1 : this.currIndex - 1; - setCursorIndex(idx); - }); - this.addKeys(["g"], () => { - setCursorIndex(0); - }); - this.addKeys(["G"], () => { - setCursorIndex(this.total - 1); - }); - let timer; - let firstNumber; - this.addKeys(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], (character) => { - if (timer) - clearTimeout(timer); - let n = parseInt(character, 10); - if (isNaN(n) || n > this.total) - return; - if (firstNumber == null && n == 0) - return; - if (firstNumber) { - let count = firstNumber * 10 + n; - firstNumber = void 0; - this._onDidClose.fire(count - 1); - this.dispose(); - return; - } - if (this.total < 10 || n * 10 > this.total) { - this._onDidClose.fire(n - 1); - this.dispose(); - return; - } - timer = setTimeout(async () => { - this._onDidClose.fire(n - 1); - this.dispose(); - }, 200); - firstNumber = n; - }); - } - async show(preferences = {}) { - let { nvim } = this; - let { title, items } = this.config; - let opts = {}; - if (title) - opts.title = title; - if (preferences.maxHeight) - opts.maxHeight = preferences.maxHeight; - if (preferences.maxWidth) - opts.maxWidth = preferences.maxWidth; - if (preferences.floatHighlight) - opts.highlight = preferences.floatHighlight; - if (preferences.floatBorderHighlight) - opts.borderhighlight = [preferences.floatBorderHighlight]; - let lines = items.map((v, i) => { - if (i < 99) - return `${i + 1}. ${v}`; - return v; - }); - if (preferences.confirmKey && preferences.confirmKey != "") { - this.addKeys(preferences.confirmKey, () => { - this._onDidClose.fire(this.currIndex); - this.dispose(); - }); - } - let res = await nvim.call("coc#float#create_menu", [lines, opts]); - this.win = new Popup(nvim, res[0], res[1]); - this.bufnr = res[1]; - this.attachEvents(); - nvim.call("coc#prompt#start_prompt", ["menu"], true); - return res[0]; - } - get buffer() { - return this.bufnr ? this.nvim.createBuffer(this.bufnr) : void 0; - } - dispose() { - var _a2; - disposeAll(this.disposables); - this.disposables = []; - this.nvim.call("coc#prompt#stop_prompt", ["menu"], true); - (_a2 = this.win) == null ? void 0 : _a2.close(); - this.win = void 0; - } - async onInputChar(session, character) { - if (session != "menu" || !this.win) - return; - let fn = this.keyMappings.get(character); - if (fn) { - await Promise.resolve(fn(character)); - } else { - logger9.warn(`Ignored key press: ${character}`); - } - } - setCursor(index) { - if (!this.win) - return; - this.currIndex = index; - this.win.setCursor(index); - } - addKeys(keys, fn) { - if (Array.isArray(keys)) { - for (let key of keys) { - this.keyMappings.set(key, fn); - } - } else { - this.keyMappings.set(keys, fn); - } - } - }; - } -}); - -// src/model/notification.ts -var isVim3, logger10, Notification; -var init_notification = __esm({ - "src/model/notification.ts"() { - init_events(); - init_util(); - isVim3 = process.env.VIM_NODE_RPC == "1"; - logger10 = require_logger2()("model-notification"); - Notification = class { - constructor(nvim, config, attachEvents = true) { - this.nvim = nvim; - this.config = config; - this.disposables = []; - this._disposed = false; - if (attachEvents) { - events_default.on("BufWinLeave", (bufnr) => { - if (bufnr == this.bufnr) { - this.dispose(); - if (config.callback) - config.callback(-1); - } - }, null, this.disposables); - events_default.on("FloatBtnClick", (bufnr, idx) => { - if (bufnr == this.bufnr) { - this.dispose(); - let btns = config == null ? void 0 : config.buttons.filter((o) => o.disabled != true); - if (config.callback) - config.callback(btns[idx].index); - } - }, null, this.disposables); - } - } - get lines() { - return this.config.content.split(/\r?\n/); - } - async show(preferences) { - let { nvim } = this; - let { title, close, timeout, buttons, borderhighlight } = this.config; - let opts = Object.assign({}, preferences); - opts.close = close ? 1 : 0; - if (title) - opts.title = title; - if (borderhighlight) - opts.borderhighlight = borderhighlight; - if (buttons) - opts.buttons = buttons.filter((o) => !o.disabled).map((o) => o.text); - if (timeout) - opts.timeout = timeout; - let res = await nvim.call("coc#float#create_notification", [this.lines, opts]); - if (!res) - return false; - if (this._disposed) { - this.nvim.call("coc#float#close", [res[0]], true); - if (isVim3) - this.nvim.command("redraw", true); - } else { - this._winid = res[0]; - this.bufnr = res[1]; - } - return this._winid != void 0; - } - get winid() { - return this._winid; - } - dispose() { - if (this._disposed) - return; - this._disposed = true; - let { winid } = this; - if (winid) { - this.nvim.call("coc#float#close", [winid], true); - if (isVim3) - this.nvim.command("redraw", true); - } - this.bufnr = void 0; - this._winid = void 0; - disposeAll(this.disposables); - this.disposables = []; - } - }; - } -}); - -// src/model/picker.ts -var import_vscode_languageserver_protocol5, logger11, isVim4, Picker; -var init_picker = __esm({ - "src/model/picker.ts"() { - import_vscode_languageserver_protocol5 = __toModule(require_main2()); - init_events(); - init_util(); - init_string(); - init_popup(); - logger11 = require_logger2()("model-dialog"); - isVim4 = process.env.VIM_NODE_RPC == "1"; - Picker = class { - constructor(nvim, config, token) { - this.nvim = nvim; - this.config = config; - this.picked = new Set(); - this.currIndex = 0; - this.disposables = []; - this.keyMappings = new Map(); - this._onDidClose = new import_vscode_languageserver_protocol5.Emitter(); - this.onDidClose = this._onDidClose.event; - for (let i = 0; i < config.items.length; i++) { - let item = config.items[i]; - if (item.picked) - this.picked.add(i); - } - this.total = config.items.length; - if (token) { - token.onCancellationRequested(() => { - var _a2; - (_a2 = this.win) == null ? void 0 : _a2.close(); - }); - } - this.disposables.push(this._onDidClose); - this.addKeymappings(); - } - attachEvents() { - events_default.on("InputChar", this.onInputChar.bind(this), null, this.disposables); - events_default.on("BufWinLeave", (bufnr) => { - if (bufnr == this.bufnr) { - this._onDidClose.fire(void 0); - this.bufnr = void 0; - this.win = void 0; - this.dispose(); - } - }, null, this.disposables); - events_default.on("FloatBtnClick", (bufnr, idx) => { - if (bufnr == this.bufnr) { - if (idx == 0) { - let selected = Array.from(this.picked); - this._onDidClose.fire(selected.length ? selected : void 0); - } else { - this._onDidClose.fire(void 0); - } - this.dispose(); - } - }, null, this.disposables); - } - addKeymappings() { - let { nvim } = this; - const toggleSelect = (idx) => { - if (this.picked.has(idx)) { - this.picked.delete(idx); - } else { - this.picked.add(idx); - } - }; - this.addKeys("", async () => { - if (isVim4 || !this.win) - return; - let [winid, lnum, col] = await nvim.eval("[v:mouse_winid,v:mouse_lnum,v:mouse_col]"); - if (global.hasOwnProperty("__TEST__")) { - let res = await nvim.getVar("mouse_position"); - winid = res[0]; - lnum = res[1]; - col = res[2]; - } - nvim.pauseNotification(); - if (winid == this.win.winid) { - if (col <= 3) { - toggleSelect(lnum - 1); - this.changeLine(lnum - 1); - } else { - this.setCursor(lnum - 1); - } - } - nvim.call("win_gotoid", [winid], true); - nvim.call("cursor", [lnum, col], true); - nvim.call("coc#float#nvim_float_click", [], true); - nvim.command("redraw", true); - await nvim.resumeNotification(); - }); - this.addKeys(["", ""], () => { - this._onDidClose.fire(void 0); - this.dispose(); - }); - this.addKeys("", () => { - if (this.picked.size == 0) { - this._onDidClose.fire(void 0); - } else { - let selected = Array.from(this.picked); - this._onDidClose.fire(selected); - } - this.dispose(); - }); - let setCursorIndex = (idx) => { - nvim.pauseNotification(); - this.setCursor(idx); - this.win.refreshScrollbar(); - nvim.command("redraw", true); - nvim.resumeNotification(false, true); - }; - this.addKeys(["j", "", "", ""], () => { - let idx = this.currIndex == this.total - 1 ? 0 : this.currIndex + 1; - setCursorIndex(idx); - }); - this.addKeys(["k", "", "", ""], () => { - let idx = this.currIndex == 0 ? this.total - 1 : this.currIndex - 1; - setCursorIndex(idx); - }); - this.addKeys(["g"], () => { - setCursorIndex(0); - }); - this.addKeys(["G"], () => { - setCursorIndex(this.total - 1); - }); - this.addKeys(" ", async () => { - let idx = this.currIndex; - toggleSelect(idx); - nvim.pauseNotification(); - this.changeLine(idx); - if (this.currIndex != this.total - 1) { - this.setCursor(this.currIndex + 1); - } - nvim.command("redraw", true); - await nvim.resumeNotification(); - }); - this.addKeys("", async () => { - var _a2; - await ((_a2 = this.win) == null ? void 0 : _a2.scrollForward()); - }); - this.addKeys("", async () => { - var _a2; - await ((_a2 = this.win) == null ? void 0 : _a2.scrollBackward()); - }); - } - async show(preferences = {}) { - let { nvim } = this; - let { title, items } = this.config; - let opts = { close: 1, cursorline: 1 }; - if (preferences.maxHeight) - opts.maxHeight = preferences.maxHeight; - if (preferences.maxWidth) - opts.maxWidth = preferences.maxWidth; - if (title) - opts.title = title; - opts.close = 1; - opts.cursorline = 1; - if (preferences.floatHighlight) { - opts.highlight = preferences.floatHighlight; - } - if (preferences.floatBorderHighlight) { - opts.borderhighlight = [preferences.floatBorderHighlight]; - } - if (preferences.pickerButtons) { - let shortcut = preferences.pickerButtonShortcut; - opts.buttons = ["Submit" + (shortcut ? " " : ""), "Cancel" + (shortcut ? " " : "")]; - } - if (preferences.confirmKey && preferences.confirmKey != "") { - this.addKeys(preferences.confirmKey, () => { - this._onDidClose.fire(void 0); - this.dispose(); - }); - } - let lines = []; - let positions2 = []; - for (let i = 0; i < items.length; i++) { - let item = items[i]; - let line = `[${item.picked ? "x" : " "}] ${item.label}`; - positions2.push([i, byteLength(line)]); - if (item.description) - line = line + ` ${item.description}`; - lines.push(line); - } - let res = await nvim.call("coc#float#create_dialog", [lines, opts]); - this.win = new Popup(nvim, res[0], res[1]); - this.bufnr = res[1]; - this.attachEvents(); - let buf = nvim.createBuffer(this.bufnr); - nvim.pauseNotification(); - for (let pos of positions2) { - buf.addHighlight({ hlGroup: "Comment", line: pos[0], srcId: 1, colStart: pos[1], colEnd: -1 }); - } - nvim.command("redraw", true); - await nvim.resumeNotification(); - nvim.call("coc#prompt#start_prompt", ["picker"], true); - return res[0]; - } - get buffer() { - return this.bufnr ? this.nvim.createBuffer(this.bufnr) : void 0; - } - dispose() { - var _a2; - this.picked.clear(); - this.keyMappings.clear(); - disposeAll(this.disposables); - this.nvim.call("coc#prompt#stop_prompt", ["picker"], true); - (_a2 = this.win) == null ? void 0 : _a2.close(); - this.win = void 0; - } - async onInputChar(session, character) { - if (session != "picker" || !this.win) - return; - let fn = this.keyMappings.get(character); - if (fn) { - await Promise.resolve(fn(character)); - } else { - logger11.warn(`Ignored key press: ${character}`); - } - } - changeLine(index) { - let { nvim } = this; - let item = this.config.items[index]; - if (!item) - return; - let line = `[${this.picked.has(index) ? "x" : " "}] ${item.label}`; - let col = byteLength(line); - if (item.description) - line = line + ` ${item.description}`; - nvim.call("setbufline", [this.bufnr, index + 1, line], true); - if (!isVim4) { - let buf = nvim.createBuffer(this.bufnr); - buf.addHighlight({ hlGroup: "Comment", line: index, srcId: 1, colStart: col, colEnd: -1 }); - } - } - setCursor(index) { - if (!this.win) - return; - this.currIndex = index; - this.win.setCursor(index); - } - addKeys(keys, fn) { - if (Array.isArray(keys)) { - for (let key of keys) { - this.keyMappings.set(key, fn); - } - } else { - this.keyMappings.set(keys, fn); - } - } - }; - } -}); - -// src/model/progress.ts -var import_vscode_languageserver_protocol6, ProgressNotification; -var init_progress = __esm({ - "src/model/progress.ts"() { - init_notification(); - import_vscode_languageserver_protocol6 = __toModule(require_main2()); - init_events(); - ProgressNotification = class extends Notification { - constructor(nvim, option) { - super(nvim, { - content: "\n", - close: option.cancellable == true, - title: option.title - }, false); - this.option = option; - events_default.on("BufWinLeave", (bufnr) => { - if (bufnr == this.bufnr) { - if (this.tokenSource) { - this.tokenSource.cancel(); - } - this.dispose(); - } - }, null, this.disposables); - } - async show(preferences) { - let { task } = this.option; - let tokenSource = this.tokenSource = new import_vscode_languageserver_protocol6.CancellationTokenSource(); - this.disposables.push(tokenSource); - let total = 0; - let res = await new Promise((resolve3, reject) => { - tokenSource.token.onCancellationRequested(() => { - resolve3(void 0); - }); - super.show(Object.assign({ minWidth: preferences.minProgressWidth || 30, progress: 1 }, preferences)).then((shown) => { - if (!shown) - reject(new Error("Failed to create float window")); - }).catch(reject); - task({ - report: (p) => { - if (!this.bufnr) - return; - let text = ""; - if (p.message) - text += p.message.replace(/\r?\n/g, " "); - if (p.increment) { - total += p.increment; - text = text + (text.length ? ` ${total}%` : `${total}%`); - } - this.nvim.call("setbufline", [this.bufnr, 2, text], true); - } - }, tokenSource.token).then((res2) => { - if (this._disposed) - return; - setTimeout(() => { - this.dispose(); - }, 100); - resolve3(res2); - }, (err) => { - if (this._disposed) - return; - this.dispose(); - if (err instanceof Error) { - reject(err); - } else { - resolve3(void 0); - } - }); - }); - return res; - } - dispose() { - super.dispose(); - this.tokenSource = void 0; - } - }; - } -}); - -// node_modules/uuid/dist/esm-node/rng.js -function rng() { - return import_crypto.default.randomBytes(16); -} -var import_crypto; -var init_rng = __esm({ - "node_modules/uuid/dist/esm-node/rng.js"() { - import_crypto = __toModule(require("crypto")); - } -}); - -// node_modules/uuid/dist/esm-node/bytesToUuid.js -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; - return [bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], "-", bth[buf[i++]], bth[buf[i++]], "-", bth[buf[i++]], bth[buf[i++]], "-", bth[buf[i++]], bth[buf[i++]], "-", bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]].join(""); -} -var byteToHex, bytesToUuid_default; -var init_bytesToUuid = __esm({ - "node_modules/uuid/dist/esm-node/bytesToUuid.js"() { - byteToHex = []; - for (var i = 0; i < 256; ++i) { - byteToHex[i] = (i + 256).toString(16).substr(1); - } - bytesToUuid_default = bytesToUuid; - } -}); - -// node_modules/uuid/dist/esm-node/v1.js -function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; - options = options || {}; - var node = options.node || _nodeId; - var clockseq = options.clockseq !== void 0 ? options.clockseq : _clockseq; - if (node == null || clockseq == null) { - var seedBytes = options.random || (options.rng || rng)(); - if (node == null) { - node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } - if (clockseq == null) { - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383; - } - } - var msecs = options.msecs !== void 0 ? options.msecs : new Date().getTime(); - var nsecs = options.nsecs !== void 0 ? options.nsecs : _lastNSecs + 1; - var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4; - if (dt < 0 && options.clockseq === void 0) { - clockseq = clockseq + 1 & 16383; - } - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === void 0) { - nsecs = 0; - } - if (nsecs >= 1e4) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - msecs += 122192928e5; - var tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296; - b[i++] = tl >>> 24 & 255; - b[i++] = tl >>> 16 & 255; - b[i++] = tl >>> 8 & 255; - b[i++] = tl & 255; - var tmh = msecs / 4294967296 * 1e4 & 268435455; - b[i++] = tmh >>> 8 & 255; - b[i++] = tmh & 255; - b[i++] = tmh >>> 24 & 15 | 16; - b[i++] = tmh >>> 16 & 255; - b[i++] = clockseq >>> 8 | 128; - b[i++] = clockseq & 255; - for (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - return buf ? buf : bytesToUuid_default(b); -} -var _nodeId, _clockseq, _lastMSecs, _lastNSecs, v1_default; -var init_v1 = __esm({ - "node_modules/uuid/dist/esm-node/v1.js"() { - init_rng(); - init_bytesToUuid(); - _lastMSecs = 0; - _lastNSecs = 0; - v1_default = v1; - } -}); - -// node_modules/uuid/dist/esm-node/v4.js -function v4(options, buf, offset) { - var i = buf && offset || 0; - if (typeof options == "string") { - buf = options === "binary" ? new Array(16) : null; - options = null; - } - options = options || {}; - var rnds = options.random || (options.rng || rng)(); - rnds[6] = rnds[6] & 15 | 64; - rnds[8] = rnds[8] & 63 | 128; - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; - } - } - return buf || bytesToUuid_default(rnds); -} -var v4_default; -var init_v4 = __esm({ - "node_modules/uuid/dist/esm-node/v4.js"() { - init_rng(); - init_bytesToUuid(); - v4_default = v4; - } -}); - -// node_modules/uuid/dist/esm-node/index.js -var init_esm_node = __esm({ - "node_modules/uuid/dist/esm-node/index.js"() { - init_v1(); - init_v4(); - } -}); - -// src/model/status.ts -var logger12, frames, StatusLine; -var init_status = __esm({ - "src/model/status.ts"() { - init_esm_node(); - logger12 = require_logger2()("model-status"); - frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"]; - StatusLine = class { - constructor(nvim) { - this.nvim = nvim; - this.items = new Map(); - this.shownIds = new Set(); - this._text = ""; - this.interval = setInterval(() => { - this.setStatusText().logError(); - }, 100); - } - dispose() { - clearInterval(this.interval); - } - createStatusBarItem(priority = 0, isProgress = false) { - let uid = v1_default(); - let item = { - text: "", - priority, - isProgress, - show: () => { - this.shownIds.add(uid); - }, - hide: () => { - this.shownIds.delete(uid); - }, - dispose: () => { - this.shownIds.delete(uid); - this.items.delete(uid); - } - }; - this.items.set(uid, item); - return item; - } - getText() { - if (this.shownIds.size == 0) - return ""; - let d = new Date(); - let idx = Math.floor(d.getMilliseconds() / 100); - let text = ""; - let items = []; - for (let [id, item] of this.items) { - if (this.shownIds.has(id)) { - items.push(item); - } - } - items.sort((a, b) => a.priority - b.priority); - for (let item of items) { - if (!item.isProgress) { - text = `${text} ${item.text}`; - } else { - text = `${text} ${frames[idx]} ${item.text}`; - } - } - return text; - } - async setStatusText() { - let text = this.getText(); - let { nvim } = this; - if (text != this._text) { - this._text = text; - nvim.pauseNotification(); - this.nvim.setVar("coc_status", text, true); - this.nvim.call("coc#util#do_autocmd", ["CocStatusChange"], true); - await nvim.resumeNotification(false, true); - } - } - }; - } -}); - -// src/types.ts -var PatternType, SourceType, MessageLevel, ConfigurationTarget, ServiceStat, FileType; -var init_types = __esm({ - "src/types.ts"() { - (function(PatternType2) { - PatternType2[PatternType2["Buffer"] = 0] = "Buffer"; - PatternType2[PatternType2["LanguageServer"] = 1] = "LanguageServer"; - PatternType2[PatternType2["Global"] = 2] = "Global"; - })(PatternType || (PatternType = {})); - (function(SourceType2) { - SourceType2[SourceType2["Native"] = 0] = "Native"; - SourceType2[SourceType2["Remote"] = 1] = "Remote"; - SourceType2[SourceType2["Service"] = 2] = "Service"; - })(SourceType || (SourceType = {})); - (function(MessageLevel2) { - MessageLevel2[MessageLevel2["More"] = 0] = "More"; - MessageLevel2[MessageLevel2["Warning"] = 1] = "Warning"; - MessageLevel2[MessageLevel2["Error"] = 2] = "Error"; - })(MessageLevel || (MessageLevel = {})); - (function(ConfigurationTarget3) { - ConfigurationTarget3[ConfigurationTarget3["Global"] = 0] = "Global"; - ConfigurationTarget3[ConfigurationTarget3["User"] = 1] = "User"; - ConfigurationTarget3[ConfigurationTarget3["Workspace"] = 2] = "Workspace"; - })(ConfigurationTarget || (ConfigurationTarget = {})); - (function(ServiceStat2) { - ServiceStat2[ServiceStat2["Initial"] = 0] = "Initial"; - ServiceStat2[ServiceStat2["Starting"] = 1] = "Starting"; - ServiceStat2[ServiceStat2["StartFailed"] = 2] = "StartFailed"; - ServiceStat2[ServiceStat2["Running"] = 3] = "Running"; - ServiceStat2[ServiceStat2["Stopping"] = 4] = "Stopping"; - ServiceStat2[ServiceStat2["Stopped"] = 5] = "Stopped"; - })(ServiceStat || (ServiceStat = {})); - (function(FileType2) { - FileType2[FileType2["Unknown"] = 0] = "Unknown"; - FileType2[FileType2["File"] = 1] = "File"; - FileType2[FileType2["Directory"] = 2] = "Directory"; - FileType2[FileType2["SymbolicLink"] = 64] = "SymbolicLink"; - })(FileType || (FileType = {})); - } -}); - -// node_modules/bytes/index.js -var require_bytes = __commonJS({ - "node_modules/bytes/index.js"(exports2, module2) { - "use strict"; - module2.exports = bytes2; - module2.exports.format = format2; - module2.exports.parse = parse5; - var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; - var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5) - }; - var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; - function bytes2(value, options) { - if (typeof value === "string") { - return parse5(value); - } - if (typeof value === "number") { - return format2(value, options); - } - return null; - } - function format2(value, options) { - if (!Number.isFinite(value)) { - return null; - } - var mag = Math.abs(value); - var thousandsSeparator = options && options.thousandsSeparator || ""; - var unitSeparator = options && options.unitSeparator || ""; - var decimalPlaces = options && options.decimalPlaces !== void 0 ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = options && options.unit || ""; - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.pb) { - unit = "PB"; - } else if (mag >= map.tb) { - unit = "TB"; - } else if (mag >= map.gb) { - unit = "GB"; - } else if (mag >= map.mb) { - unit = "MB"; - } else if (mag >= map.kb) { - unit = "KB"; - } else { - unit = "B"; - } - } - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, "$1"); - } - if (thousandsSeparator) { - str = str.replace(formatThousandsRegExp, thousandsSeparator); - } - return str + unitSeparator + unit; - } - function parse5(val) { - if (typeof val === "number" && !isNaN(val)) { - return val; - } - if (typeof val !== "string") { - return null; - } - var results = parseRegExp.exec(val); - var floatValue; - var unit = "b"; - if (!results) { - floatValue = parseInt(val, 10); - unit = "b"; - } else { - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); - } - return Math.floor(map[unit] * floatValue); - } - } -}); - -// node_modules/fast-diff/diff.js -var require_diff = __commonJS({ - "node_modules/fast-diff/diff.js"(exports2, module2) { - var DIFF_DELETE = -1; - var DIFF_INSERT = 1; - var DIFF_EQUAL = 0; - function diff_main(text1, text2, cursor_pos, _fix_unicode) { - if (text1 === text2) { - if (text1) { - return [[DIFF_EQUAL, text1]]; - } - return []; - } - if (cursor_pos != null) { - var editdiff = find_cursor_edit_diff(text1, text2, cursor_pos); - if (editdiff) { - return editdiff; - } - } - var commonlength = diff_commonPrefix(text1, text2); - var commonprefix = text1.substring(0, commonlength); - text1 = text1.substring(commonlength); - text2 = text2.substring(commonlength); - commonlength = diff_commonSuffix(text1, text2); - var commonsuffix = text1.substring(text1.length - commonlength); - text1 = text1.substring(0, text1.length - commonlength); - text2 = text2.substring(0, text2.length - commonlength); - var diffs = diff_compute_(text1, text2); - if (commonprefix) { - diffs.unshift([DIFF_EQUAL, commonprefix]); - } - if (commonsuffix) { - diffs.push([DIFF_EQUAL, commonsuffix]); - } - diff_cleanupMerge(diffs, _fix_unicode); - return diffs; - } - function diff_compute_(text1, text2) { - var diffs; - if (!text1) { - return [[DIFF_INSERT, text2]]; - } - if (!text2) { - return [[DIFF_DELETE, text1]]; - } - var longtext = text1.length > text2.length ? text1 : text2; - var shorttext = text1.length > text2.length ? text2 : text1; - var i = longtext.indexOf(shorttext); - if (i !== -1) { - diffs = [ - [DIFF_INSERT, longtext.substring(0, i)], - [DIFF_EQUAL, shorttext], - [DIFF_INSERT, longtext.substring(i + shorttext.length)] - ]; - if (text1.length > text2.length) { - diffs[0][0] = diffs[2][0] = DIFF_DELETE; - } - return diffs; - } - if (shorttext.length === 1) { - return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; - } - var hm = diff_halfMatch_(text1, text2); - if (hm) { - var text1_a = hm[0]; - var text1_b = hm[1]; - var text2_a = hm[2]; - var text2_b = hm[3]; - var mid_common = hm[4]; - var diffs_a = diff_main(text1_a, text2_a); - var diffs_b = diff_main(text1_b, text2_b); - return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b); - } - return diff_bisect_(text1, text2); - } - function diff_bisect_(text1, text2) { - var text1_length = text1.length; - var text2_length = text2.length; - var max_d = Math.ceil((text1_length + text2_length) / 2); - var v_offset = max_d; - var v_length = 2 * max_d; - var v12 = new Array(v_length); - var v2 = new Array(v_length); - for (var x = 0; x < v_length; x++) { - v12[x] = -1; - v2[x] = -1; - } - v12[v_offset + 1] = 0; - v2[v_offset + 1] = 0; - var delta = text1_length - text2_length; - var front = delta % 2 !== 0; - var k1start = 0; - var k1end = 0; - var k2start = 0; - var k2end = 0; - for (var d = 0; d < max_d; d++) { - for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { - var k1_offset = v_offset + k1; - var x1; - if (k1 === -d || k1 !== d && v12[k1_offset - 1] < v12[k1_offset + 1]) { - x1 = v12[k1_offset + 1]; - } else { - x1 = v12[k1_offset - 1] + 1; - } - var y1 = x1 - k1; - while (x1 < text1_length && y1 < text2_length && text1.charAt(x1) === text2.charAt(y1)) { - x1++; - y1++; - } - v12[k1_offset] = x1; - if (x1 > text1_length) { - k1end += 2; - } else if (y1 > text2_length) { - k1start += 2; - } else if (front) { - var k2_offset = v_offset + delta - k1; - if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] !== -1) { - var x2 = text1_length - v2[k2_offset]; - if (x1 >= x2) { - return diff_bisectSplit_(text1, text2, x1, y1); - } - } - } - } - for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { - var k2_offset = v_offset + k2; - var x2; - if (k2 === -d || k2 !== d && v2[k2_offset - 1] < v2[k2_offset + 1]) { - x2 = v2[k2_offset + 1]; - } else { - x2 = v2[k2_offset - 1] + 1; - } - var y2 = x2 - k2; - while (x2 < text1_length && y2 < text2_length && text1.charAt(text1_length - x2 - 1) === text2.charAt(text2_length - y2 - 1)) { - x2++; - y2++; - } - v2[k2_offset] = x2; - if (x2 > text1_length) { - k2end += 2; - } else if (y2 > text2_length) { - k2start += 2; - } else if (!front) { - var k1_offset = v_offset + delta - k2; - if (k1_offset >= 0 && k1_offset < v_length && v12[k1_offset] !== -1) { - var x1 = v12[k1_offset]; - var y1 = v_offset + x1 - k1_offset; - x2 = text1_length - x2; - if (x1 >= x2) { - return diff_bisectSplit_(text1, text2, x1, y1); - } - } - } - } - } - return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; - } - function diff_bisectSplit_(text1, text2, x, y) { - var text1a = text1.substring(0, x); - var text2a = text2.substring(0, y); - var text1b = text1.substring(x); - var text2b = text2.substring(y); - var diffs = diff_main(text1a, text2a); - var diffsb = diff_main(text1b, text2b); - return diffs.concat(diffsb); - } - function diff_commonPrefix(text1, text2) { - if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { - return 0; - } - var pointermin = 0; - var pointermax = Math.min(text1.length, text2.length); - var pointermid = pointermax; - var pointerstart = 0; - while (pointermin < pointermid) { - if (text1.substring(pointerstart, pointermid) == text2.substring(pointerstart, pointermid)) { - pointermin = pointermid; - pointerstart = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); - } - if (is_surrogate_pair_start(text1.charCodeAt(pointermid - 1))) { - pointermid--; - } - return pointermid; - } - function diff_commonSuffix(text1, text2) { - if (!text1 || !text2 || text1.slice(-1) !== text2.slice(-1)) { - return 0; - } - var pointermin = 0; - var pointermax = Math.min(text1.length, text2.length); - var pointermid = pointermax; - var pointerend = 0; - while (pointermin < pointermid) { - if (text1.substring(text1.length - pointermid, text1.length - pointerend) == text2.substring(text2.length - pointermid, text2.length - pointerend)) { - pointermin = pointermid; - pointerend = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); - } - if (is_surrogate_pair_end(text1.charCodeAt(text1.length - pointermid))) { - pointermid--; - } - return pointermid; - } - function diff_halfMatch_(text1, text2) { - var longtext = text1.length > text2.length ? text1 : text2; - var shorttext = text1.length > text2.length ? text2 : text1; - if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { - return null; - } - function diff_halfMatchI_(longtext2, shorttext2, i) { - var seed = longtext2.substring(i, i + Math.floor(longtext2.length / 4)); - var j = -1; - var best_common = ""; - var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; - while ((j = shorttext2.indexOf(seed, j + 1)) !== -1) { - var prefixLength = diff_commonPrefix(longtext2.substring(i), shorttext2.substring(j)); - var suffixLength = diff_commonSuffix(longtext2.substring(0, i), shorttext2.substring(0, j)); - if (best_common.length < suffixLength + prefixLength) { - best_common = shorttext2.substring(j - suffixLength, j) + shorttext2.substring(j, j + prefixLength); - best_longtext_a = longtext2.substring(0, i - suffixLength); - best_longtext_b = longtext2.substring(i + prefixLength); - best_shorttext_a = shorttext2.substring(0, j - suffixLength); - best_shorttext_b = shorttext2.substring(j + prefixLength); - } - } - if (best_common.length * 2 >= longtext2.length) { - return [ - best_longtext_a, - best_longtext_b, - best_shorttext_a, - best_shorttext_b, - best_common - ]; - } else { - return null; - } - } - var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4)); - var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2)); - var hm; - if (!hm1 && !hm2) { - return null; - } else if (!hm2) { - hm = hm1; - } else if (!hm1) { - hm = hm2; - } else { - hm = hm1[4].length > hm2[4].length ? hm1 : hm2; - } - var text1_a, text1_b, text2_a, text2_b; - if (text1.length > text2.length) { - text1_a = hm[0]; - text1_b = hm[1]; - text2_a = hm[2]; - text2_b = hm[3]; - } else { - text2_a = hm[0]; - text2_b = hm[1]; - text1_a = hm[2]; - text1_b = hm[3]; - } - var mid_common = hm[4]; - return [text1_a, text1_b, text2_a, text2_b, mid_common]; - } - function diff_cleanupMerge(diffs, fix_unicode) { - diffs.push([DIFF_EQUAL, ""]); - var pointer = 0; - var count_delete = 0; - var count_insert = 0; - var text_delete = ""; - var text_insert = ""; - var commonlength; - while (pointer < diffs.length) { - if (pointer < diffs.length - 1 && !diffs[pointer][1]) { - diffs.splice(pointer, 1); - continue; - } - switch (diffs[pointer][0]) { - case DIFF_INSERT: - count_insert++; - text_insert += diffs[pointer][1]; - pointer++; - break; - case DIFF_DELETE: - count_delete++; - text_delete += diffs[pointer][1]; - pointer++; - break; - case DIFF_EQUAL: - var previous_equality = pointer - count_insert - count_delete - 1; - if (fix_unicode) { - if (previous_equality >= 0 && ends_with_pair_start(diffs[previous_equality][1])) { - var stray = diffs[previous_equality][1].slice(-1); - diffs[previous_equality][1] = diffs[previous_equality][1].slice(0, -1); - text_delete = stray + text_delete; - text_insert = stray + text_insert; - if (!diffs[previous_equality][1]) { - diffs.splice(previous_equality, 1); - pointer--; - var k = previous_equality - 1; - if (diffs[k] && diffs[k][0] === DIFF_INSERT) { - count_insert++; - text_insert = diffs[k][1] + text_insert; - k--; - } - if (diffs[k] && diffs[k][0] === DIFF_DELETE) { - count_delete++; - text_delete = diffs[k][1] + text_delete; - k--; - } - previous_equality = k; - } - } - if (starts_with_pair_end(diffs[pointer][1])) { - var stray = diffs[pointer][1].charAt(0); - diffs[pointer][1] = diffs[pointer][1].slice(1); - text_delete += stray; - text_insert += stray; - } - } - if (pointer < diffs.length - 1 && !diffs[pointer][1]) { - diffs.splice(pointer, 1); - break; - } - if (text_delete.length > 0 || text_insert.length > 0) { - if (text_delete.length > 0 && text_insert.length > 0) { - commonlength = diff_commonPrefix(text_insert, text_delete); - if (commonlength !== 0) { - if (previous_equality >= 0) { - diffs[previous_equality][1] += text_insert.substring(0, commonlength); - } else { - diffs.splice(0, 0, [DIFF_EQUAL, text_insert.substring(0, commonlength)]); - pointer++; - } - text_insert = text_insert.substring(commonlength); - text_delete = text_delete.substring(commonlength); - } - commonlength = diff_commonSuffix(text_insert, text_delete); - if (commonlength !== 0) { - diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; - text_insert = text_insert.substring(0, text_insert.length - commonlength); - text_delete = text_delete.substring(0, text_delete.length - commonlength); - } - } - var n = count_insert + count_delete; - if (text_delete.length === 0 && text_insert.length === 0) { - diffs.splice(pointer - n, n); - pointer = pointer - n; - } else if (text_delete.length === 0) { - diffs.splice(pointer - n, n, [DIFF_INSERT, text_insert]); - pointer = pointer - n + 1; - } else if (text_insert.length === 0) { - diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete]); - pointer = pointer - n + 1; - } else { - diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete], [DIFF_INSERT, text_insert]); - pointer = pointer - n + 2; - } - } - if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { - diffs[pointer - 1][1] += diffs[pointer][1]; - diffs.splice(pointer, 1); - } else { - pointer++; - } - count_insert = 0; - count_delete = 0; - text_delete = ""; - text_insert = ""; - break; - } - } - if (diffs[diffs.length - 1][1] === "") { - diffs.pop(); - } - var changes = false; - pointer = 1; - while (pointer < diffs.length - 1) { - if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { - if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) { - diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); - diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; - diffs.splice(pointer - 1, 1); - changes = true; - } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == diffs[pointer + 1][1]) { - diffs[pointer - 1][1] += diffs[pointer + 1][1]; - diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; - diffs.splice(pointer + 1, 1); - changes = true; - } - } - pointer++; - } - if (changes) { - diff_cleanupMerge(diffs, fix_unicode); - } - } - function is_surrogate_pair_start(charCode) { - return charCode >= 55296 && charCode <= 56319; - } - function is_surrogate_pair_end(charCode) { - return charCode >= 56320 && charCode <= 57343; - } - function starts_with_pair_end(str) { - return is_surrogate_pair_end(str.charCodeAt(0)); - } - function ends_with_pair_start(str) { - return is_surrogate_pair_start(str.charCodeAt(str.length - 1)); - } - function remove_empty_tuples(tuples) { - var ret = []; - for (var i = 0; i < tuples.length; i++) { - if (tuples[i][1].length > 0) { - ret.push(tuples[i]); - } - } - return ret; - } - function make_edit_splice(before, oldMiddle, newMiddle, after) { - if (ends_with_pair_start(before) || starts_with_pair_end(after)) { - return null; - } - return remove_empty_tuples([ - [DIFF_EQUAL, before], - [DIFF_DELETE, oldMiddle], - [DIFF_INSERT, newMiddle], - [DIFF_EQUAL, after] - ]); - } - function find_cursor_edit_diff(oldText, newText, cursor_pos) { - var oldRange = typeof cursor_pos === "number" ? { index: cursor_pos, length: 0 } : cursor_pos.oldRange; - var newRange = typeof cursor_pos === "number" ? null : cursor_pos.newRange; - var oldLength = oldText.length; - var newLength = newText.length; - if (oldRange.length === 0 && (newRange === null || newRange.length === 0)) { - var oldCursor = oldRange.index; - var oldBefore = oldText.slice(0, oldCursor); - var oldAfter = oldText.slice(oldCursor); - var maybeNewCursor = newRange ? newRange.index : null; - editBefore: { - var newCursor = oldCursor + newLength - oldLength; - if (maybeNewCursor !== null && maybeNewCursor !== newCursor) { - break editBefore; - } - if (newCursor < 0 || newCursor > newLength) { - break editBefore; - } - var newBefore = newText.slice(0, newCursor); - var newAfter = newText.slice(newCursor); - if (newAfter !== oldAfter) { - break editBefore; - } - var prefixLength = Math.min(oldCursor, newCursor); - var oldPrefix = oldBefore.slice(0, prefixLength); - var newPrefix = newBefore.slice(0, prefixLength); - if (oldPrefix !== newPrefix) { - break editBefore; - } - var oldMiddle = oldBefore.slice(prefixLength); - var newMiddle = newBefore.slice(prefixLength); - return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldAfter); - } - editAfter: { - if (maybeNewCursor !== null && maybeNewCursor !== oldCursor) { - break editAfter; - } - var cursor = oldCursor; - var newBefore = newText.slice(0, cursor); - var newAfter = newText.slice(cursor); - if (newBefore !== oldBefore) { - break editAfter; - } - var suffixLength = Math.min(oldLength - cursor, newLength - cursor); - var oldSuffix = oldAfter.slice(oldAfter.length - suffixLength); - var newSuffix = newAfter.slice(newAfter.length - suffixLength); - if (oldSuffix !== newSuffix) { - break editAfter; - } - var oldMiddle = oldAfter.slice(0, oldAfter.length - suffixLength); - var newMiddle = newAfter.slice(0, newAfter.length - suffixLength); - return make_edit_splice(oldBefore, oldMiddle, newMiddle, oldSuffix); - } - } - if (oldRange.length > 0 && newRange && newRange.length === 0) { - replaceRange: { - var oldPrefix = oldText.slice(0, oldRange.index); - var oldSuffix = oldText.slice(oldRange.index + oldRange.length); - var prefixLength = oldPrefix.length; - var suffixLength = oldSuffix.length; - if (newLength < prefixLength + suffixLength) { - break replaceRange; - } - var newPrefix = newText.slice(0, prefixLength); - var newSuffix = newText.slice(newLength - suffixLength); - if (oldPrefix !== newPrefix || oldSuffix !== newSuffix) { - break replaceRange; - } - var oldMiddle = oldText.slice(prefixLength, oldLength - suffixLength); - var newMiddle = newText.slice(prefixLength, newLength - suffixLength); - return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldSuffix); - } - } - return null; - } - function diff(text1, text2, cursor_pos) { - return diff_main(text1, text2, cursor_pos, true); - } - diff.INSERT = DIFF_INSERT; - diff.DELETE = DIFF_DELETE; - diff.EQUAL = DIFF_EQUAL; - module2.exports = diff; - } -}); - -// node_modules/vscode-languageserver-textdocument/lib/esm/main.js -function mergeSort(data, compare) { - if (data.length <= 1) { - return data; - } - var p = data.length / 2 | 0; - var left = data.slice(0, p); - var right = data.slice(p); - mergeSort(left, compare); - mergeSort(right, compare); - var leftIdx = 0; - var rightIdx = 0; - var i = 0; - while (leftIdx < left.length && rightIdx < right.length) { - var ret = compare(left[leftIdx], right[rightIdx]); - if (ret <= 0) { - data[i++] = left[leftIdx++]; - } else { - data[i++] = right[rightIdx++]; - } - } - while (leftIdx < left.length) { - data[i++] = left[leftIdx++]; - } - while (rightIdx < right.length) { - data[i++] = right[rightIdx++]; - } - return data; -} -function computeLineOffsets(text, isAtLineStart, textOffset) { - if (textOffset === void 0) { - textOffset = 0; - } - var result = isAtLineStart ? [textOffset] : []; - for (var i = 0; i < text.length; i++) { - var ch = text.charCodeAt(i); - if (ch === 13 || ch === 10) { - if (ch === 13 && i + 1 < text.length && text.charCodeAt(i + 1) === 10) { - i++; - } - result.push(textOffset + i + 1); - } - } - return result; -} -function getWellformedRange(range) { - var start = range.start; - var end = range.end; - if (start.line > end.line || start.line === end.line && start.character > end.character) { - return { start: end, end: start }; - } - return range; -} -function getWellformedEdit(textEdit) { - var range = getWellformedRange(textEdit.range); - if (range !== textEdit.range) { - return { newText: textEdit.newText, range }; - } - return textEdit; -} -var FullTextDocument2, TextDocument2; -var init_main2 = __esm({ - "node_modules/vscode-languageserver-textdocument/lib/esm/main.js"() { - "use strict"; - FullTextDocument2 = function() { - function FullTextDocument3(uri, languageId, version2, content) { - this._uri = uri; - this._languageId = languageId; - this._version = version2; - this._content = content; - this._lineOffsets = void 0; - } - Object.defineProperty(FullTextDocument3.prototype, "uri", { - get: function() { - return this._uri; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FullTextDocument3.prototype, "languageId", { - get: function() { - return this._languageId; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FullTextDocument3.prototype, "version", { - get: function() { - return this._version; - }, - enumerable: true, - configurable: true - }); - FullTextDocument3.prototype.getText = function(range) { - if (range) { - var start = this.offsetAt(range.start); - var end = this.offsetAt(range.end); - return this._content.substring(start, end); - } - return this._content; - }; - FullTextDocument3.prototype.update = function(changes, version2) { - for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) { - var change = changes_1[_i]; - if (FullTextDocument3.isIncremental(change)) { - var range = getWellformedRange(change.range); - var startOffset = this.offsetAt(range.start); - var endOffset = this.offsetAt(range.end); - this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length); - var startLine = Math.max(range.start.line, 0); - var endLine = Math.max(range.end.line, 0); - var lineOffsets = this._lineOffsets; - var addedLineOffsets = computeLineOffsets(change.text, false, startOffset); - if (endLine - startLine === addedLineOffsets.length) { - for (var i = 0, len = addedLineOffsets.length; i < len; i++) { - lineOffsets[i + startLine + 1] = addedLineOffsets[i]; - } - } else { - if (addedLineOffsets.length < 1e4) { - lineOffsets.splice.apply(lineOffsets, [startLine + 1, endLine - startLine].concat(addedLineOffsets)); - } else { - this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1)); - } - } - var diff = change.text.length - (endOffset - startOffset); - if (diff !== 0) { - for (var i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) { - lineOffsets[i] = lineOffsets[i] + diff; - } - } - } else if (FullTextDocument3.isFull(change)) { - this._content = change.text; - this._lineOffsets = void 0; - } else { - throw new Error("Unknown change event received"); - } - } - this._version = version2; - }; - FullTextDocument3.prototype.getLineOffsets = function() { - if (this._lineOffsets === void 0) { - this._lineOffsets = computeLineOffsets(this._content, true); - } - return this._lineOffsets; - }; - FullTextDocument3.prototype.positionAt = function(offset) { - offset = Math.max(Math.min(offset, this._content.length), 0); - var lineOffsets = this.getLineOffsets(); - var low = 0, high = lineOffsets.length; - if (high === 0) { - return { line: 0, character: offset }; - } - while (low < high) { - var mid = Math.floor((low + high) / 2); - if (lineOffsets[mid] > offset) { - high = mid; - } else { - low = mid + 1; - } - } - var line = low - 1; - return { line, character: offset - lineOffsets[line] }; - }; - FullTextDocument3.prototype.offsetAt = function(position) { - var lineOffsets = this.getLineOffsets(); - if (position.line >= lineOffsets.length) { - return this._content.length; - } else if (position.line < 0) { - return 0; - } - var lineOffset = lineOffsets[position.line]; - var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length; - return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); - }; - Object.defineProperty(FullTextDocument3.prototype, "lineCount", { - get: function() { - return this.getLineOffsets().length; - }, - enumerable: true, - configurable: true - }); - FullTextDocument3.isIncremental = function(event) { - var candidate = event; - return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range !== void 0 && (candidate.rangeLength === void 0 || typeof candidate.rangeLength === "number"); - }; - FullTextDocument3.isFull = function(event) { - var candidate = event; - return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range === void 0 && candidate.rangeLength === void 0; - }; - return FullTextDocument3; - }(); - (function(TextDocument5) { - function create(uri, languageId, version2, content) { - return new FullTextDocument2(uri, languageId, version2, content); - } - TextDocument5.create = create; - function update(document2, changes, version2) { - if (document2 instanceof FullTextDocument2) { - document2.update(changes, version2); - return document2; - } else { - throw new Error("TextDocument.update: document must be created by TextDocument.create"); - } - } - TextDocument5.update = update; - function applyEdits2(document2, edits) { - var text = document2.getText(); - var sortedEdits = mergeSort(edits.map(getWellformedEdit), function(a, b) { - var diff = a.range.start.line - b.range.start.line; - if (diff === 0) { - return a.range.start.character - b.range.start.character; - } - return diff; - }); - var lastModifiedOffset = 0; - var spans = []; - for (var _i = 0, sortedEdits_1 = sortedEdits; _i < sortedEdits_1.length; _i++) { - var e = sortedEdits_1[_i]; - var startOffset = document2.offsetAt(e.range.start); - if (startOffset < lastModifiedOffset) { - throw new Error("Overlapping edit"); - } else if (startOffset > lastModifiedOffset) { - spans.push(text.substring(lastModifiedOffset, startOffset)); - } - if (e.newText.length) { - spans.push(e.newText); - } - lastModifiedOffset = document2.offsetAt(e.range.end); - } - spans.push(text.substr(lastModifiedOffset)); - return spans.join(""); - } - TextDocument5.applyEdits = applyEdits2; - })(TextDocument2 || (TextDocument2 = {})); - } -}); - -// node_modules/jsonc-parser/lib/esm/impl/scanner.js -function createScanner(text, ignoreTrivia) { - if (ignoreTrivia === void 0) { - ignoreTrivia = false; - } - var len = text.length; - var pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0; - function scanHexDigits(count, exact) { - var digits = 0; - var value2 = 0; - while (digits < count || !exact) { - var ch = text.charCodeAt(pos); - if (ch >= 48 && ch <= 57) { - value2 = value2 * 16 + ch - 48; - } else if (ch >= 65 && ch <= 70) { - value2 = value2 * 16 + ch - 65 + 10; - } else if (ch >= 97 && ch <= 102) { - value2 = value2 * 16 + ch - 97 + 10; - } else { - break; - } - pos++; - digits++; - } - if (digits < count) { - value2 = -1; - } - return value2; - } - function setPosition(newPosition) { - pos = newPosition; - value = ""; - tokenOffset = 0; - token = 16; - scanError = 0; - } - function scanNumber() { - var start = pos; - if (text.charCodeAt(pos) === 48) { - pos++; - } else { - pos++; - while (pos < text.length && isDigit(text.charCodeAt(pos))) { - pos++; - } - } - if (pos < text.length && text.charCodeAt(pos) === 46) { - pos++; - if (pos < text.length && isDigit(text.charCodeAt(pos))) { - pos++; - while (pos < text.length && isDigit(text.charCodeAt(pos))) { - pos++; - } - } else { - scanError = 3; - return text.substring(start, pos); - } - } - var end = pos; - if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) { - pos++; - if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) { - pos++; - } - if (pos < text.length && isDigit(text.charCodeAt(pos))) { - pos++; - while (pos < text.length && isDigit(text.charCodeAt(pos))) { - pos++; - } - end = pos; - } else { - scanError = 3; - } - } - return text.substring(start, end); - } - function scanString() { - var result = "", start = pos; - while (true) { - if (pos >= len) { - result += text.substring(start, pos); - scanError = 2; - break; - } - var ch = text.charCodeAt(pos); - if (ch === 34) { - result += text.substring(start, pos); - pos++; - break; - } - if (ch === 92) { - result += text.substring(start, pos); - pos++; - if (pos >= len) { - scanError = 2; - break; - } - var ch2 = text.charCodeAt(pos++); - switch (ch2) { - case 34: - result += '"'; - break; - case 92: - result += "\\"; - break; - case 47: - result += "/"; - break; - case 98: - result += "\b"; - break; - case 102: - result += "\f"; - break; - case 110: - result += "\n"; - break; - case 114: - result += "\r"; - break; - case 116: - result += " "; - break; - case 117: - var ch3 = scanHexDigits(4, true); - if (ch3 >= 0) { - result += String.fromCharCode(ch3); - } else { - scanError = 4; - } - break; - default: - scanError = 5; - } - start = pos; - continue; - } - if (ch >= 0 && ch <= 31) { - if (isLineBreak(ch)) { - result += text.substring(start, pos); - scanError = 2; - break; - } else { - scanError = 6; - } - } - pos++; - } - return result; - } - function scanNext() { - value = ""; - scanError = 0; - tokenOffset = pos; - lineStartOffset = lineNumber; - prevTokenLineStartOffset = tokenLineStartOffset; - if (pos >= len) { - tokenOffset = len; - return token = 17; - } - var code = text.charCodeAt(pos); - if (isWhiteSpace(code)) { - do { - pos++; - value += String.fromCharCode(code); - code = text.charCodeAt(pos); - } while (isWhiteSpace(code)); - return token = 15; - } - if (isLineBreak(code)) { - pos++; - value += String.fromCharCode(code); - if (code === 13 && text.charCodeAt(pos) === 10) { - pos++; - value += "\n"; - } - lineNumber++; - tokenLineStartOffset = pos; - return token = 14; - } - switch (code) { - case 123: - pos++; - return token = 1; - case 125: - pos++; - return token = 2; - case 91: - pos++; - return token = 3; - case 93: - pos++; - return token = 4; - case 58: - pos++; - return token = 6; - case 44: - pos++; - return token = 5; - case 34: - pos++; - value = scanString(); - return token = 10; - case 47: - var start = pos - 1; - if (text.charCodeAt(pos + 1) === 47) { - pos += 2; - while (pos < len) { - if (isLineBreak(text.charCodeAt(pos))) { - break; - } - pos++; - } - value = text.substring(start, pos); - return token = 12; - } - if (text.charCodeAt(pos + 1) === 42) { - pos += 2; - var safeLength = len - 1; - var commentClosed = false; - while (pos < safeLength) { - var ch = text.charCodeAt(pos); - if (ch === 42 && text.charCodeAt(pos + 1) === 47) { - pos += 2; - commentClosed = true; - break; - } - pos++; - if (isLineBreak(ch)) { - if (ch === 13 && text.charCodeAt(pos) === 10) { - pos++; - } - lineNumber++; - tokenLineStartOffset = pos; - } - } - if (!commentClosed) { - pos++; - scanError = 1; - } - value = text.substring(start, pos); - return token = 13; - } - value += String.fromCharCode(code); - pos++; - return token = 16; - case 45: - value += String.fromCharCode(code); - pos++; - if (pos === len || !isDigit(text.charCodeAt(pos))) { - return token = 16; - } - case 48: - case 49: - case 50: - case 51: - case 52: - case 53: - case 54: - case 55: - case 56: - case 57: - value += scanNumber(); - return token = 11; - default: - while (pos < len && isUnknownContentCharacter(code)) { - pos++; - code = text.charCodeAt(pos); - } - if (tokenOffset !== pos) { - value = text.substring(tokenOffset, pos); - switch (value) { - case "true": - return token = 8; - case "false": - return token = 9; - case "null": - return token = 7; - } - return token = 16; - } - value += String.fromCharCode(code); - pos++; - return token = 16; - } - } - function isUnknownContentCharacter(code) { - if (isWhiteSpace(code) || isLineBreak(code)) { - return false; - } - switch (code) { - case 125: - case 93: - case 123: - case 91: - case 34: - case 58: - case 44: - case 47: - return false; - } - return true; - } - function scanNextNonTrivia() { - var result; - do { - result = scanNext(); - } while (result >= 12 && result <= 15); - return result; - } - return { - setPosition, - getPosition: function() { - return pos; - }, - scan: ignoreTrivia ? scanNextNonTrivia : scanNext, - getToken: function() { - return token; - }, - getTokenValue: function() { - return value; - }, - getTokenOffset: function() { - return tokenOffset; - }, - getTokenLength: function() { - return pos - tokenOffset; - }, - getTokenStartLine: function() { - return lineStartOffset; - }, - getTokenStartCharacter: function() { - return tokenOffset - prevTokenLineStartOffset; - }, - getTokenError: function() { - return scanError; - } - }; -} -function isWhiteSpace(ch) { - return ch === 32 || ch === 9 || ch === 11 || ch === 12 || ch === 160 || ch === 5760 || ch >= 8192 && ch <= 8203 || ch === 8239 || ch === 8287 || ch === 12288 || ch === 65279; -} -function isLineBreak(ch) { - return ch === 10 || ch === 13 || ch === 8232 || ch === 8233; -} -function isDigit(ch) { - return ch >= 48 && ch <= 57; -} -var init_scanner = __esm({ - "node_modules/jsonc-parser/lib/esm/impl/scanner.js"() { - "use strict"; - } -}); - -// node_modules/jsonc-parser/lib/esm/impl/format.js -function format(documentText, range, options) { - var initialIndentLevel; - var formatText; - var formatTextStart; - var rangeStart; - var rangeEnd; - if (range) { - rangeStart = range.offset; - rangeEnd = rangeStart + range.length; - formatTextStart = rangeStart; - while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) { - formatTextStart--; - } - var endOffset = rangeEnd; - while (endOffset < documentText.length && !isEOL(documentText, endOffset)) { - endOffset++; - } - formatText = documentText.substring(formatTextStart, endOffset); - initialIndentLevel = computeIndentLevel(formatText, options); - } else { - formatText = documentText; - initialIndentLevel = 0; - formatTextStart = 0; - rangeStart = 0; - rangeEnd = documentText.length; - } - var eol = getEOL(options, documentText); - var lineBreak = false; - var indentLevel = 0; - var indentValue; - if (options.insertSpaces) { - indentValue = repeat(" ", options.tabSize || 4); - } else { - indentValue = " "; - } - var scanner2 = createScanner(formatText, false); - var hasError = false; - function newLineAndIndent() { - return eol + repeat(indentValue, initialIndentLevel + indentLevel); - } - function scanNext() { - var token = scanner2.scan(); - lineBreak = false; - while (token === 15 || token === 14) { - lineBreak = lineBreak || token === 14; - token = scanner2.scan(); - } - hasError = token === 16 || scanner2.getTokenError() !== 0; - return token; - } - var editOperations = []; - function addEdit(text, startOffset, endOffset2) { - if (!hasError && (!range || startOffset < rangeEnd && endOffset2 > rangeStart) && documentText.substring(startOffset, endOffset2) !== text) { - editOperations.push({ offset: startOffset, length: endOffset2 - startOffset, content: text }); - } - } - var firstToken = scanNext(); - if (firstToken !== 17) { - var firstTokenStart = scanner2.getTokenOffset() + formatTextStart; - var initialIndent = repeat(indentValue, initialIndentLevel); - addEdit(initialIndent, formatTextStart, firstTokenStart); - } - while (firstToken !== 17) { - var firstTokenEnd = scanner2.getTokenOffset() + scanner2.getTokenLength() + formatTextStart; - var secondToken = scanNext(); - var replaceContent = ""; - var needsLineBreak = false; - while (!lineBreak && (secondToken === 12 || secondToken === 13)) { - var commentTokenStart = scanner2.getTokenOffset() + formatTextStart; - addEdit(" ", firstTokenEnd, commentTokenStart); - firstTokenEnd = scanner2.getTokenOffset() + scanner2.getTokenLength() + formatTextStart; - needsLineBreak = secondToken === 12; - replaceContent = needsLineBreak ? newLineAndIndent() : ""; - secondToken = scanNext(); - } - if (secondToken === 2) { - if (firstToken !== 1) { - indentLevel--; - replaceContent = newLineAndIndent(); - } - } else if (secondToken === 4) { - if (firstToken !== 3) { - indentLevel--; - replaceContent = newLineAndIndent(); - } - } else { - switch (firstToken) { - case 3: - case 1: - indentLevel++; - replaceContent = newLineAndIndent(); - break; - case 5: - case 12: - replaceContent = newLineAndIndent(); - break; - case 13: - if (lineBreak) { - replaceContent = newLineAndIndent(); - } else if (!needsLineBreak) { - replaceContent = " "; - } - break; - case 6: - if (!needsLineBreak) { - replaceContent = " "; - } - break; - case 10: - if (secondToken === 6) { - if (!needsLineBreak) { - replaceContent = ""; - } - break; - } - case 7: - case 8: - case 9: - case 11: - case 2: - case 4: - if (secondToken === 12 || secondToken === 13) { - if (!needsLineBreak) { - replaceContent = " "; - } - } else if (secondToken !== 5 && secondToken !== 17) { - hasError = true; - } - break; - case 16: - hasError = true; - break; - } - if (lineBreak && (secondToken === 12 || secondToken === 13)) { - replaceContent = newLineAndIndent(); - } - } - if (secondToken === 17) { - replaceContent = options.insertFinalNewline ? eol : ""; - } - var secondTokenStart = scanner2.getTokenOffset() + formatTextStart; - addEdit(replaceContent, firstTokenEnd, secondTokenStart); - firstToken = secondToken; - } - return editOperations; -} -function repeat(s, count) { - var result = ""; - for (var i = 0; i < count; i++) { - result += s; - } - return result; -} -function computeIndentLevel(content, options) { - var i = 0; - var nChars = 0; - var tabSize = options.tabSize || 4; - while (i < content.length) { - var ch = content.charAt(i); - if (ch === " ") { - nChars++; - } else if (ch === " ") { - nChars += tabSize; - } else { - break; - } - i++; - } - return Math.floor(nChars / tabSize); -} -function getEOL(options, text) { - for (var i = 0; i < text.length; i++) { - var ch = text.charAt(i); - if (ch === "\r") { - if (i + 1 < text.length && text.charAt(i + 1) === "\n") { - return "\r\n"; - } - return "\r"; - } else if (ch === "\n") { - return "\n"; - } - } - return options && options.eol || "\n"; -} -function isEOL(text, offset) { - return "\r\n".indexOf(text.charAt(offset)) !== -1; -} -var init_format = __esm({ - "node_modules/jsonc-parser/lib/esm/impl/format.js"() { - init_scanner(); - "use strict"; - } -}); - -// node_modules/jsonc-parser/lib/esm/impl/parser.js -function parse2(text, errors, options) { - if (errors === void 0) { - errors = []; - } - if (options === void 0) { - options = ParseOptions.DEFAULT; - } - var currentProperty = null; - var currentParent = []; - var previousParents = []; - function onValue(value) { - if (Array.isArray(currentParent)) { - currentParent.push(value); - } else if (currentProperty !== null) { - currentParent[currentProperty] = value; - } - } - var visitor = { - onObjectBegin: function() { - var object = {}; - onValue(object); - previousParents.push(currentParent); - currentParent = object; - currentProperty = null; - }, - onObjectProperty: function(name2) { - currentProperty = name2; - }, - onObjectEnd: function() { - currentParent = previousParents.pop(); - }, - onArrayBegin: function() { - var array = []; - onValue(array); - previousParents.push(currentParent); - currentParent = array; - currentProperty = null; - }, - onArrayEnd: function() { - currentParent = previousParents.pop(); - }, - onLiteralValue: onValue, - onError: function(error, offset, length) { - errors.push({ error, offset, length }); - } - }; - visit(text, visitor, options); - return currentParent[0]; -} -function parseTree(text, errors, options) { - if (errors === void 0) { - errors = []; - } - if (options === void 0) { - options = ParseOptions.DEFAULT; - } - var currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 }; - function ensurePropertyComplete(endOffset) { - if (currentParent.type === "property") { - currentParent.length = endOffset - currentParent.offset; - currentParent = currentParent.parent; - } - } - function onValue(valueNode) { - currentParent.children.push(valueNode); - return valueNode; - } - var visitor = { - onObjectBegin: function(offset) { - currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] }); - }, - onObjectProperty: function(name2, offset, length) { - currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] }); - currentParent.children.push({ type: "string", value: name2, offset, length, parent: currentParent }); - }, - onObjectEnd: function(offset, length) { - ensurePropertyComplete(offset + length); - currentParent.length = offset + length - currentParent.offset; - currentParent = currentParent.parent; - ensurePropertyComplete(offset + length); - }, - onArrayBegin: function(offset, length) { - currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] }); - }, - onArrayEnd: function(offset, length) { - currentParent.length = offset + length - currentParent.offset; - currentParent = currentParent.parent; - ensurePropertyComplete(offset + length); - }, - onLiteralValue: function(value, offset, length) { - onValue({ type: getNodeType(value), offset, length, parent: currentParent, value }); - ensurePropertyComplete(offset + length); - }, - onSeparator: function(sep, offset, length) { - if (currentParent.type === "property") { - if (sep === ":") { - currentParent.colonOffset = offset; - } else if (sep === ",") { - ensurePropertyComplete(offset); - } - } - }, - onError: function(error, offset, length) { - errors.push({ error, offset, length }); - } - }; - visit(text, visitor, options); - var result = currentParent.children[0]; - if (result) { - delete result.parent; - } - return result; -} -function findNodeAtLocation(root, path36) { - if (!root) { - return void 0; - } - var node = root; - for (var _i = 0, path_1 = path36; _i < path_1.length; _i++) { - var segment = path_1[_i]; - if (typeof segment === "string") { - if (node.type !== "object" || !Array.isArray(node.children)) { - return void 0; - } - var found = false; - for (var _a2 = 0, _b = node.children; _a2 < _b.length; _a2++) { - var propertyNode = _b[_a2]; - if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) { - node = propertyNode.children[1]; - found = true; - break; - } - } - if (!found) { - return void 0; - } - } else { - var index = segment; - if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) { - return void 0; - } - node = node.children[index]; - } - } - return node; -} -function visit(text, visitor, options) { - if (options === void 0) { - options = ParseOptions.DEFAULT; - } - var _scanner = createScanner(text, false); - function toNoArgVisit(visitFunction) { - return visitFunction ? function() { - return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); - } : function() { - return true; - }; - } - function toOneArgVisit(visitFunction) { - return visitFunction ? function(arg) { - return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); - } : function() { - return true; - }; - } - var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); - var disallowComments = options && options.disallowComments; - var allowTrailingComma = options && options.allowTrailingComma; - function scanNext() { - while (true) { - var token = _scanner.scan(); - switch (_scanner.getTokenError()) { - case 4: - handleError(14); - break; - case 5: - handleError(15); - break; - case 3: - handleError(13); - break; - case 1: - if (!disallowComments) { - handleError(11); - } - break; - case 2: - handleError(12); - break; - case 6: - handleError(16); - break; - } - switch (token) { - case 12: - case 13: - if (disallowComments) { - handleError(10); - } else { - onComment(); - } - break; - case 16: - handleError(1); - break; - case 15: - case 14: - break; - default: - return token; - } - } - } - function handleError(error, skipUntilAfter, skipUntil) { - if (skipUntilAfter === void 0) { - skipUntilAfter = []; - } - if (skipUntil === void 0) { - skipUntil = []; - } - onError(error); - if (skipUntilAfter.length + skipUntil.length > 0) { - var token = _scanner.getToken(); - while (token !== 17) { - if (skipUntilAfter.indexOf(token) !== -1) { - scanNext(); - break; - } else if (skipUntil.indexOf(token) !== -1) { - break; - } - token = scanNext(); - } - } - } - function parseString(isValue) { - var value = _scanner.getTokenValue(); - if (isValue) { - onLiteralValue(value); - } else { - onObjectProperty(value); - } - scanNext(); - return true; - } - function parseLiteral() { - switch (_scanner.getToken()) { - case 11: - var tokenValue = _scanner.getTokenValue(); - var value = Number(tokenValue); - if (isNaN(value)) { - handleError(2); - value = 0; - } - onLiteralValue(value); - break; - case 7: - onLiteralValue(null); - break; - case 8: - onLiteralValue(true); - break; - case 9: - onLiteralValue(false); - break; - default: - return false; - } - scanNext(); - return true; - } - function parseProperty() { - if (_scanner.getToken() !== 10) { - handleError(3, [], [2, 5]); - return false; - } - parseString(false); - if (_scanner.getToken() === 6) { - onSeparator(":"); - scanNext(); - if (!parseValue()) { - handleError(4, [], [2, 5]); - } - } else { - handleError(5, [], [2, 5]); - } - return true; - } - function parseObject() { - onObjectBegin(); - scanNext(); - var needsComma = false; - while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) { - if (_scanner.getToken() === 5) { - if (!needsComma) { - handleError(4, [], []); - } - onSeparator(","); - scanNext(); - if (_scanner.getToken() === 2 && allowTrailingComma) { - break; - } - } else if (needsComma) { - handleError(6, [], []); - } - if (!parseProperty()) { - handleError(4, [], [2, 5]); - } - needsComma = true; - } - onObjectEnd(); - if (_scanner.getToken() !== 2) { - handleError(7, [2], []); - } else { - scanNext(); - } - return true; - } - function parseArray() { - onArrayBegin(); - scanNext(); - var needsComma = false; - while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) { - if (_scanner.getToken() === 5) { - if (!needsComma) { - handleError(4, [], []); - } - onSeparator(","); - scanNext(); - if (_scanner.getToken() === 4 && allowTrailingComma) { - break; - } - } else if (needsComma) { - handleError(6, [], []); - } - if (!parseValue()) { - handleError(4, [], [4, 5]); - } - needsComma = true; - } - onArrayEnd(); - if (_scanner.getToken() !== 4) { - handleError(8, [4], []); - } else { - scanNext(); - } - return true; - } - function parseValue() { - switch (_scanner.getToken()) { - case 3: - return parseArray(); - case 1: - return parseObject(); - case 10: - return parseString(true); - default: - return parseLiteral(); - } - } - scanNext(); - if (_scanner.getToken() === 17) { - if (options.allowEmptyContent) { - return true; - } - handleError(4, [], []); - return false; - } - if (!parseValue()) { - handleError(4, [], []); - return false; - } - if (_scanner.getToken() !== 17) { - handleError(9, [], []); - } - return true; -} -function getNodeType(value) { - switch (typeof value) { - case "boolean": - return "boolean"; - case "number": - return "number"; - case "string": - return "string"; - case "object": { - if (!value) { - return "null"; - } else if (Array.isArray(value)) { - return "array"; - } - return "object"; - } - default: - return "null"; - } -} -var ParseOptions; -var init_parser = __esm({ - "node_modules/jsonc-parser/lib/esm/impl/parser.js"() { - init_scanner(); - "use strict"; - (function(ParseOptions2) { - ParseOptions2.DEFAULT = { - allowTrailingComma: false - }; - })(ParseOptions || (ParseOptions = {})); - } -}); - -// node_modules/jsonc-parser/lib/esm/impl/edit.js -function setProperty(text, originalPath, value, options) { - var _a2; - var path36 = originalPath.slice(); - var errors = []; - var root = parseTree(text, errors); - var parent = void 0; - var lastSegment = void 0; - while (path36.length > 0) { - lastSegment = path36.pop(); - parent = findNodeAtLocation(root, path36); - if (parent === void 0 && value !== void 0) { - if (typeof lastSegment === "string") { - value = (_a2 = {}, _a2[lastSegment] = value, _a2); - } else { - value = [value]; - } - } else { - break; - } - } - if (!parent) { - if (value === void 0) { - throw new Error("Can not delete in empty document"); - } - return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options); - } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) { - var existing = findNodeAtLocation(parent, [lastSegment]); - if (existing !== void 0) { - if (value === void 0) { - if (!existing.parent) { - throw new Error("Malformed AST"); - } - var propertyIndex = parent.children.indexOf(existing.parent); - var removeBegin = void 0; - var removeEnd = existing.parent.offset + existing.parent.length; - if (propertyIndex > 0) { - var previous = parent.children[propertyIndex - 1]; - removeBegin = previous.offset + previous.length; - } else { - removeBegin = parent.offset + 1; - if (parent.children.length > 1) { - var next = parent.children[1]; - removeEnd = next.offset; - } - } - return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, options); - } else { - return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options); - } - } else { - if (value === void 0) { - return []; - } - var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value); - var index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(function(p) { - return p.children[0].value; - })) : parent.children.length; - var edit2 = void 0; - if (index > 0) { - var previous = parent.children[index - 1]; - edit2 = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty }; - } else if (parent.children.length === 0) { - edit2 = { offset: parent.offset + 1, length: 0, content: newProperty }; - } else { - edit2 = { offset: parent.offset + 1, length: 0, content: newProperty + "," }; - } - return withFormatting(text, edit2, options); - } - } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) { - var insertIndex = lastSegment; - if (insertIndex === -1) { - var newProperty = "" + JSON.stringify(value); - var edit2 = void 0; - if (parent.children.length === 0) { - edit2 = { offset: parent.offset + 1, length: 0, content: newProperty }; - } else { - var previous = parent.children[parent.children.length - 1]; - edit2 = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty }; - } - return withFormatting(text, edit2, options); - } else if (value === void 0 && parent.children.length >= 0) { - var removalIndex = lastSegment; - var toRemove = parent.children[removalIndex]; - var edit2 = void 0; - if (parent.children.length === 1) { - edit2 = { offset: parent.offset + 1, length: parent.length - 2, content: "" }; - } else if (parent.children.length - 1 === removalIndex) { - var previous = parent.children[removalIndex - 1]; - var offset = previous.offset + previous.length; - var parentEndOffset = parent.offset + parent.length; - edit2 = { offset, length: parentEndOffset - 2 - offset, content: "" }; - } else { - edit2 = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" }; - } - return withFormatting(text, edit2, options); - } else if (value !== void 0) { - var edit2 = void 0; - var newProperty = "" + JSON.stringify(value); - if (!options.isArrayInsertion && parent.children.length > lastSegment) { - var toModify = parent.children[lastSegment]; - edit2 = { offset: toModify.offset, length: toModify.length, content: newProperty }; - } else if (parent.children.length === 0 || lastSegment === 0) { - edit2 = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," }; - } else { - var index = lastSegment > parent.children.length ? parent.children.length : lastSegment; - var previous = parent.children[index - 1]; - edit2 = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty }; - } - return withFormatting(text, edit2, options); - } else { - throw new Error("Can not " + (value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify") + " Array index " + insertIndex + " as length is not sufficient"); - } - } else { - throw new Error("Can not add " + (typeof lastSegment !== "number" ? "index" : "property") + " to parent of type " + parent.type); - } -} -function withFormatting(text, edit2, options) { - if (!options.formattingOptions) { - return [edit2]; - } - var newText = applyEdit(text, edit2); - var begin = edit2.offset; - var end = edit2.offset + edit2.content.length; - if (edit2.length === 0 || edit2.content.length === 0) { - while (begin > 0 && !isEOL(newText, begin - 1)) { - begin--; - } - while (end < newText.length && !isEOL(newText, end)) { - end++; - } - } - var edits = format(newText, { offset: begin, length: end - begin }, options.formattingOptions); - for (var i = edits.length - 1; i >= 0; i--) { - var edit_1 = edits[i]; - newText = applyEdit(newText, edit_1); - begin = Math.min(begin, edit_1.offset); - end = Math.max(end, edit_1.offset + edit_1.length); - end += edit_1.content.length - edit_1.length; - } - var editLength = text.length - (newText.length - end) - begin; - return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }]; -} -function applyEdit(text, edit2) { - return text.substring(0, edit2.offset) + edit2.content + text.substring(edit2.offset + edit2.length); -} -var init_edit = __esm({ - "node_modules/jsonc-parser/lib/esm/impl/edit.js"() { - init_format(); - init_parser(); - "use strict"; - } -}); - -// node_modules/jsonc-parser/lib/esm/main.js -function modify(text, path36, value, options) { - return setProperty(text, path36, value, options); -} -function applyEdits(text, edits) { - for (var i = edits.length - 1; i >= 0; i--) { - text = applyEdit(text, edits[i]); - } - return text; -} -var parse3; -var init_main3 = __esm({ - "node_modules/jsonc-parser/lib/esm/main.js"() { - init_format(); - init_edit(); - init_scanner(); - init_parser(); - "use strict"; - parse3 = parse2; - } -}); - -// src/configuration/util.ts -function parseContentFromFile(filepath, onError) { - if (!filepath || !import_fs2.default.existsSync(filepath)) - return { contents: {} }; - let content; - let uri = URI.file(filepath).toString(); - try { - content = import_fs2.default.readFileSync(filepath, "utf8"); - } catch (_e) { - content = ""; - } - let [errors, contents] = parseConfiguration(content); - if (errors && errors.length) { - onError(convertErrors(uri, content, errors)); - } - return { contents }; -} -function parseConfiguration(content) { - if (content.length == 0) - return [[], {}]; - let errors = []; - let data = parse3(content, errors, { allowTrailingComma: true }); - function addProperty(current, key, remains, value) { - if (remains.length == 0) { - current[key] = convert(value); - } else { - if (!current[key]) - current[key] = {}; - let o = current[key]; - let first = remains.shift(); - addProperty(o, first, remains, value); - } - } - function convert(obj, split = false) { - if (!objectLiteral(obj)) - return obj; - if (emptyObject(obj)) - return {}; - let dest = {}; - for (let key of Object.keys(obj)) { - if (split && key.includes(".")) { - let parts = key.split("."); - let first = parts.shift(); - addProperty(dest, first, parts, obj[key]); - } else { - dest[key] = convert(obj[key]); - } - } - return dest; - } - return [errors, convert(data, true)]; -} -function convertErrors(uri, content, errors) { - let items = []; - let document2 = TextDocument2.create(uri, "json", 0, content); - for (let err of errors) { - let msg = "parse error"; - switch (err.error) { - case 2: - msg = "invalid number"; - break; - case 8: - msg = "close brace expected"; - break; - case 5: - msg = "colon expected"; - break; - case 6: - msg = "comma expected"; - break; - case 9: - msg = "end of file expected"; - break; - case 16: - msg = "invaliad character"; - break; - case 10: - msg = "invalid commment token"; - break; - case 15: - msg = "invalid escape character"; - break; - case 1: - msg = "invalid symbol"; - break; - case 14: - msg = "invalid unicode"; - break; - case 3: - msg = "property name expected"; - break; - case 13: - msg = "unexpected end of number"; - break; - case 12: - msg = "unexpected end of string"; - break; - case 11: - msg = "unexpected end of comment"; - break; - case 4: - msg = "value expected"; - break; - default: - msg = "Unknwn error"; - break; - } - let range = { - start: document2.positionAt(err.offset), - end: document2.positionAt(err.offset + err.length) - }; - let loc = import_vscode_languageserver_protocol7.Location.create(uri, range); - items.push({ location: loc, message: msg }); - } - return items; -} -function addToValueTree(settingsTreeRoot, key, value, conflictReporter) { - const segments = key.split("."); - const last = segments.pop(); - let curr = settingsTreeRoot; - for (let i = 0; i < segments.length; i++) { - let s = segments[i]; - let obj = curr[s]; - switch (typeof obj) { - case "function": { - obj = curr[s] = {}; - break; - } - case "undefined": { - obj = curr[s] = {}; - break; - } - case "object": - break; - default: - conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join(".")} is ${JSON.stringify(obj)}`); - return; - } - curr = obj; - } - if (typeof curr === "object") { - curr[last] = value; - } else { - conflictReporter(`Ignoring ${key} as ${segments.join(".")} is ${JSON.stringify(curr)}`); - } -} -function removeFromValueTree(valueTree, key) { - const segments = key.split("."); - doRemoveFromValueTree(valueTree, segments); -} -function doRemoveFromValueTree(valueTree, segments) { - const first = segments.shift(); - if (segments.length === 0) { - delete valueTree[first]; - return; - } - if (Object.keys(valueTree).includes(first)) { - const value = valueTree[first]; - if (typeof value === "object" && !Array.isArray(value)) { - doRemoveFromValueTree(value, segments); - if (Object.keys(value).length === 0) { - delete valueTree[first]; - } - } - } -} -function getConfigurationValue(config, settingPath, defaultValue) { - function accessSetting(config2, path37) { - let current = config2; - for (let i = 0; i < path37.length; i++) { - if (typeof current !== "object" || current === null) { - return void 0; - } - current = current[path37[i]]; - } - return current; - } - const path36 = settingPath.split("."); - const result = accessSetting(config, path36); - return typeof result === "undefined" ? defaultValue : result; -} -function loadDefaultConfigurations() { - let file = import_path2.default.join(pluginRoot, "data/schema.json"); - if (!import_fs2.default.existsSync(file)) { - console.error("schema.json not found, reinstall coc.nvim to fix this!"); - return { contents: {} }; - } - let content = import_fs2.default.readFileSync(file, "utf8"); - let { properties } = JSON.parse(content); - let config = {}; - Object.keys(properties).forEach((key) => { - let value = properties[key].default; - if (value !== void 0) { - addToValueTree(config, key, value, (message) => { - logger13.error(message); - }); - } - }); - return { contents: config }; -} -function getKeys(obj, curr) { - let keys = []; - for (let key of Object.keys(obj)) { - let val = obj[key]; - let newKey = curr ? `${curr}.${key}` : key; - keys.push(newKey); - if (objectLiteral(val)) { - keys.push(...getKeys(val, newKey)); - } - } - return keys; -} -function getChangedKeys(from, to) { - let keys = []; - let fromKeys = getKeys(from); - let toKeys = getKeys(to); - const added = toKeys.filter((key) => !fromKeys.includes(key)); - const removed = fromKeys.filter((key) => !toKeys.includes(key)); - keys.push(...added); - keys.push(...removed); - for (const key of fromKeys) { - if (!toKeys.includes(key)) - continue; - const value1 = getConfigurationValue(from, key); - const value2 = getConfigurationValue(to, key); - if (!equals(value1, value2)) { - keys.push(key); - } - } - return keys; -} -var import_vscode_languageserver_protocol7, import_fs2, import_path2, logger13, pluginRoot; -var init_util2 = __esm({ - "src/configuration/util.ts"() { - import_vscode_languageserver_protocol7 = __toModule(require_main2()); - init_main2(); - init_main3(); - init_is(); - init_object(); - import_fs2 = __toModule(require("fs")); - init_esm2(); - import_path2 = __toModule(require("path")); - logger13 = require_logger2()("configuration-util"); - pluginRoot = false ? resolve(__dirname, "../..") : (0, import_path2.dirname)(__dirname); - } -}); - -// src/configuration/model.ts -var ConfigurationModel; -var init_model = __esm({ - "src/configuration/model.ts"() { - init_is(); - init_object(); - init_util2(); - ConfigurationModel = class { - constructor(_contents = {}) { - this._contents = _contents; - } - get contents() { - return this._contents; - } - clone() { - return new ConfigurationModel(deepClone(this._contents)); - } - getValue(section2) { - let res = section2 ? getConfigurationValue(this.contents, section2) : this.contents; - return res; - } - merge(...others) { - const contents = deepClone(this.contents); - for (const other of others) { - this.mergeContents(contents, other.contents); - } - return new ConfigurationModel(contents); - } - freeze() { - if (!Object.isFrozen(this._contents)) { - Object.freeze(this._contents); - } - return this; - } - mergeContents(source, target) { - for (const key of Object.keys(target)) { - if (key in source) { - if (objectLiteral(source[key]) && objectLiteral(target[key])) { - this.mergeContents(source[key], target[key]); - continue; - } - } - source[key] = deepClone(target[key]); - } - } - setValue(key, value) { - addToValueTree(this.contents, key, value, (message) => { - console.error(message); - }); - } - removeValue(key) { - removeFromValueTree(this.contents, key); - } - }; - } -}); - -// src/configuration/configuration.ts -var Configuration; -var init_configuration = __esm({ - "src/configuration/configuration.ts"() { - init_model(); - Configuration = class { - constructor(_defaultConfiguration, _userConfiguration, _workspaceConfiguration, _memoryConfiguration = new ConfigurationModel()) { - this._defaultConfiguration = _defaultConfiguration; - this._userConfiguration = _userConfiguration; - this._workspaceConfiguration = _workspaceConfiguration; - this._memoryConfiguration = _memoryConfiguration; - } - getConsolidateConfiguration() { - if (!this._consolidateConfiguration) { - this._consolidateConfiguration = this._defaultConfiguration.merge(this._userConfiguration, this._workspaceConfiguration, this._memoryConfiguration); - this._consolidateConfiguration = this._consolidateConfiguration.freeze(); - } - return this._consolidateConfiguration; - } - getValue(section2) { - let configuration = this.getConsolidateConfiguration(); - return configuration.getValue(section2); - } - inspect(key) { - const consolidateConfigurationModel = this.getConsolidateConfiguration(); - const { _workspaceConfiguration, _memoryConfiguration } = this; - return { - default: this._defaultConfiguration.freeze().getValue(key), - user: this._userConfiguration.freeze().getValue(key), - workspace: _workspaceConfiguration.freeze().getValue(key), - memory: _memoryConfiguration.freeze().getValue(key), - value: consolidateConfigurationModel.getValue(key) - }; - } - get defaults() { - return this._defaultConfiguration; - } - get user() { - return this._userConfiguration; - } - get workspace() { - return this._workspaceConfiguration; - } - toData() { - return { - defaults: { - contents: this._defaultConfiguration.contents - }, - user: { - contents: this._userConfiguration.contents - }, - workspace: { - contents: this._workspaceConfiguration.contents - } - }; - } - }; - } -}); - -// node_modules/concat-map/index.js -var require_concat_map = __commonJS({ - "node_modules/concat-map/index.js"(exports2, module2) { - module2.exports = function(xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) - res.push.apply(res, x); - else - res.push(x); - } - return res; - }; - var isArray = Array.isArray || function(xs) { - return Object.prototype.toString.call(xs) === "[object Array]"; - }; - } -}); - -// node_modules/balanced-match/index.js -var require_balanced_match = __commonJS({ - "node_modules/balanced-match/index.js"(exports2, module2) { - "use strict"; - module2.exports = balanced; - function balanced(a, b, str) { - if (a instanceof RegExp) - a = maybeMatch(a, str); - if (b instanceof RegExp) - b = maybeMatch(b, str); - var r = range(a, b, str); - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; - } - function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; - } - balanced.range = range; - function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; - if (ai >= 0 && bi > 0) { - if (a === b) { - return [ai, bi]; - } - begs = []; - left = str.length; - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [begs.pop(), bi]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - bi = str.indexOf(b, i + 1); - } - i = ai < bi && ai >= 0 ? ai : bi; - } - if (begs.length) { - result = [left, right]; - } - } - return result; - } - } -}); - -// node_modules/brace-expansion/index.js -var require_brace_expansion = __commonJS({ - "node_modules/brace-expansion/index.js"(exports2, module2) { - var concatMap = require_concat_map(); - var balanced = require_balanced_match(); - module2.exports = expandTop; - var escSlash = "\0SLASH" + Math.random() + "\0"; - var escOpen = "\0OPEN" + Math.random() + "\0"; - var escClose = "\0CLOSE" + Math.random() + "\0"; - var escComma = "\0COMMA" + Math.random() + "\0"; - var escPeriod = "\0PERIOD" + Math.random() + "\0"; - function numeric(str) { - return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); - } - function escapeBraces(str) { - return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod); - } - function unescapeBraces(str) { - return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join("."); - } - function parseCommaParts(str) { - if (!str) - return [""]; - var parts = []; - var m = balanced("{", "}", str); - if (!m) - return str.split(","); - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(","); - p[p.length - 1] += "{" + body + "}"; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length - 1] += postParts.shift(); - p.push.apply(p, postParts); - } - parts.push.apply(parts, p); - return parts; - } - function expandTop(str) { - if (!str) - return []; - if (str.substr(0, 2) === "{}") { - str = "\\{\\}" + str.substr(2); - } - return expand(escapeBraces(str), true).map(unescapeBraces); - } - function embrace(str) { - return "{" + str + "}"; - } - function isPadded(el) { - return /^-?0\d/.test(el); - } - function lte(i, y) { - return i <= y; - } - function gte(i, y) { - return i >= y; - } - function expand(str, isTop) { - var expansions = []; - var m = balanced("{", "}", str); - if (!m || /\$$/.test(m.pre)) - return [str]; - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(",") >= 0; - if (!isSequence && !isOptions) { - if (m.post.match(/,.*\}/)) { - str = m.pre + "{" + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length ? expand(m.post, false) : [""]; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } - var pre = m.pre; - var post = m.post.length ? expand(m.post, false) : [""]; - var N; - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length); - var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad2 = n.some(isPadded); - N = []; - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === "\\") - c = ""; - } else { - c = String(i); - if (pad2) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join("0"); - if (i < 0) - c = "-" + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { - return expand(el, false); - }); - } - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } - return expansions; - } - } -}); - -// node_modules/minimatch/minimatch.js -var require_minimatch = __commonJS({ - "node_modules/minimatch/minimatch.js"(exports2, module2) { - module2.exports = minimatch8; - minimatch8.Minimatch = Minimatch2; - var path36 = { sep: "/" }; - try { - path36 = require("path"); - } catch (er) { - } - var GLOBSTAR = minimatch8.GLOBSTAR = Minimatch2.GLOBSTAR = {}; - var expand = require_brace_expansion(); - var plTypes = { - "!": { open: "(?:(?!(?:", close: "))[^/]*?)" }, - "?": { open: "(?:", close: ")?" }, - "+": { open: "(?:", close: ")+" }, - "*": { open: "(?:", close: ")*" }, - "@": { open: "(?:", close: ")" } - }; - var qmark = "[^/]"; - var star = qmark + "*?"; - var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?"; - var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; - var reSpecials = charSet("().*{}+?[]^$\\!"); - function charSet(s) { - return s.split("").reduce(function(set, c) { - set[c] = true; - return set; - }, {}); - } - var slashSplit = /\/+/; - minimatch8.filter = filter; - function filter(pattern, options) { - options = options || {}; - return function(p, i, list2) { - return minimatch8(p, pattern, options); - }; - } - function ext(a, b) { - a = a || {}; - b = b || {}; - var t = {}; - Object.keys(b).forEach(function(k) { - t[k] = b[k]; - }); - Object.keys(a).forEach(function(k) { - t[k] = a[k]; - }); - return t; - } - minimatch8.defaults = function(def) { - if (!def || !Object.keys(def).length) - return minimatch8; - var orig = minimatch8; - var m = function minimatch9(p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)); - }; - m.Minimatch = function Minimatch3(pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)); - }; - return m; - }; - Minimatch2.defaults = function(def) { - if (!def || !Object.keys(def).length) - return Minimatch2; - return minimatch8.defaults(def).Minimatch; - }; - function minimatch8(p, pattern, options) { - if (typeof pattern !== "string") { - throw new TypeError("glob pattern string required"); - } - if (!options) - options = {}; - if (!options.nocomment && pattern.charAt(0) === "#") { - return false; - } - if (pattern.trim() === "") - return p === ""; - return new Minimatch2(pattern, options).match(p); - } - function Minimatch2(pattern, options) { - if (!(this instanceof Minimatch2)) { - return new Minimatch2(pattern, options); - } - if (typeof pattern !== "string") { - throw new TypeError("glob pattern string required"); - } - if (!options) - options = {}; - pattern = pattern.trim(); - if (path36.sep !== "/") { - pattern = pattern.split(path36.sep).join("/"); - } - this.options = options; - this.set = []; - this.pattern = pattern; - this.regexp = null; - this.negate = false; - this.comment = false; - this.empty = false; - this.make(); - } - Minimatch2.prototype.debug = function() { - }; - Minimatch2.prototype.make = make; - function make() { - if (this._made) - return; - var pattern = this.pattern; - var options = this.options; - if (!options.nocomment && pattern.charAt(0) === "#") { - this.comment = true; - return; - } - if (!pattern) { - this.empty = true; - return; - } - this.parseNegate(); - var set = this.globSet = this.braceExpand(); - if (options.debug) - this.debug = console.error; - this.debug(this.pattern, set); - set = this.globParts = set.map(function(s) { - return s.split(slashSplit); - }); - this.debug(this.pattern, set); - set = set.map(function(s, si, set2) { - return s.map(this.parse, this); - }, this); - this.debug(this.pattern, set); - set = set.filter(function(s) { - return s.indexOf(false) === -1; - }); - this.debug(this.pattern, set); - this.set = set; - } - Minimatch2.prototype.parseNegate = parseNegate; - function parseNegate() { - var pattern = this.pattern; - var negate = false; - var options = this.options; - var negateOffset = 0; - if (options.nonegate) - return; - for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) { - negate = !negate; - negateOffset++; - } - if (negateOffset) - this.pattern = pattern.substr(negateOffset); - this.negate = negate; - } - minimatch8.braceExpand = function(pattern, options) { - return braceExpand(pattern, options); - }; - Minimatch2.prototype.braceExpand = braceExpand; - function braceExpand(pattern, options) { - if (!options) { - if (this instanceof Minimatch2) { - options = this.options; - } else { - options = {}; - } - } - pattern = typeof pattern === "undefined" ? this.pattern : pattern; - if (typeof pattern === "undefined") { - throw new TypeError("undefined pattern"); - } - if (options.nobrace || !pattern.match(/\{.*\}/)) { - return [pattern]; - } - return expand(pattern); - } - Minimatch2.prototype.parse = parse5; - var SUBPARSE = {}; - function parse5(pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError("pattern is too long"); - } - var options = this.options; - if (!options.noglobstar && pattern === "**") - return GLOBSTAR; - if (pattern === "") - return ""; - var re = ""; - var hasMagic = !!options.nocase; - var escaping = false; - var patternListStack = []; - var negativeLists = []; - var stateChar; - var inClass = false; - var reClassStart = -1; - var classStart = -1; - var patternStart = pattern.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)"; - var self2 = this; - function clearStateChar() { - if (stateChar) { - switch (stateChar) { - case "*": - re += star; - hasMagic = true; - break; - case "?": - re += qmark; - hasMagic = true; - break; - default: - re += "\\" + stateChar; - break; - } - self2.debug("clearStateChar %j %j", stateChar, re); - stateChar = false; - } - } - for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) { - this.debug("%s %s %s %j", pattern, i, re, c); - if (escaping && reSpecials[c]) { - re += "\\" + c; - escaping = false; - continue; - } - switch (c) { - case "/": - return false; - case "\\": - clearStateChar(); - escaping = true; - continue; - case "?": - case "*": - case "+": - case "@": - case "!": - this.debug("%s %s %s %j <-- stateChar", pattern, i, re, c); - if (inClass) { - this.debug(" in class"); - if (c === "!" && i === classStart + 1) - c = "^"; - re += c; - continue; - } - self2.debug("call clearStateChar %j", stateChar); - clearStateChar(); - stateChar = c; - if (options.noext) - clearStateChar(); - continue; - case "(": - if (inClass) { - re += "("; - continue; - } - if (!stateChar) { - re += "\\("; - continue; - } - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }); - re += stateChar === "!" ? "(?:(?!(?:" : "(?:"; - this.debug("plType %j %j", stateChar, re); - stateChar = false; - continue; - case ")": - if (inClass || !patternListStack.length) { - re += "\\)"; - continue; - } - clearStateChar(); - hasMagic = true; - var pl = patternListStack.pop(); - re += pl.close; - if (pl.type === "!") { - negativeLists.push(pl); - } - pl.reEnd = re.length; - continue; - case "|": - if (inClass || !patternListStack.length || escaping) { - re += "\\|"; - escaping = false; - continue; - } - clearStateChar(); - re += "|"; - continue; - case "[": - clearStateChar(); - if (inClass) { - re += "\\" + c; - continue; - } - inClass = true; - classStart = i; - reClassStart = re.length; - re += c; - continue; - case "]": - if (i === classStart + 1 || !inClass) { - re += "\\" + c; - escaping = false; - continue; - } - if (inClass) { - var cs = pattern.substring(classStart + 1, i); - try { - RegExp("[" + cs + "]"); - } catch (er) { - var sp = this.parse(cs, SUBPARSE); - re = re.substr(0, reClassStart) + "\\[" + sp[0] + "\\]"; - hasMagic = hasMagic || sp[1]; - inClass = false; - continue; - } - } - hasMagic = true; - inClass = false; - re += c; - continue; - default: - clearStateChar(); - if (escaping) { - escaping = false; - } else if (reSpecials[c] && !(c === "^" && inClass)) { - re += "\\"; - } - re += c; - } - } - if (inClass) { - cs = pattern.substr(classStart + 1); - sp = this.parse(cs, SUBPARSE); - re = re.substr(0, reClassStart) + "\\[" + sp[0]; - hasMagic = hasMagic || sp[1]; - } - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length); - this.debug("setting tail", re, pl); - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function(_, $1, $2) { - if (!$2) { - $2 = "\\"; - } - return $1 + $1 + $2 + "|"; - }); - this.debug("tail=%j\n %s", tail, tail, pl, re); - var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type; - hasMagic = true; - re = re.slice(0, pl.reStart) + t + "\\(" + tail; - } - clearStateChar(); - if (escaping) { - re += "\\\\"; - } - var addPatternStart = false; - switch (re.charAt(0)) { - case ".": - case "[": - case "(": - addPatternStart = true; - } - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n]; - var nlBefore = re.slice(0, nl.reStart); - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8); - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd); - var nlAfter = re.slice(nl.reEnd); - nlLast += nlAfter; - var openParensBefore = nlBefore.split("(").length - 1; - var cleanAfter = nlAfter; - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, ""); - } - nlAfter = cleanAfter; - var dollar = ""; - if (nlAfter === "" && isSub !== SUBPARSE) { - dollar = "$"; - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast; - re = newRe; - } - if (re !== "" && hasMagic) { - re = "(?=.)" + re; - } - if (addPatternStart) { - re = patternStart + re; - } - if (isSub === SUBPARSE) { - return [re, hasMagic]; - } - if (!hasMagic) { - return globUnescape(pattern); - } - var flags = options.nocase ? "i" : ""; - try { - var regExp = new RegExp("^" + re + "$", flags); - } catch (er) { - return new RegExp("$."); - } - regExp._glob = pattern; - regExp._src = re; - return regExp; - } - minimatch8.makeRe = function(pattern, options) { - return new Minimatch2(pattern, options || {}).makeRe(); - }; - Minimatch2.prototype.makeRe = makeRe; - function makeRe() { - if (this.regexp || this.regexp === false) - return this.regexp; - var set = this.set; - if (!set.length) { - this.regexp = false; - return this.regexp; - } - var options = this.options; - var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot; - var flags = options.nocase ? "i" : ""; - var re = set.map(function(pattern) { - return pattern.map(function(p) { - return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src; - }).join("\\/"); - }).join("|"); - re = "^(?:" + re + ")$"; - if (this.negate) - re = "^(?!" + re + ").*$"; - try { - this.regexp = new RegExp(re, flags); - } catch (ex) { - this.regexp = false; - } - return this.regexp; - } - minimatch8.match = function(list2, pattern, options) { - options = options || {}; - var mm = new Minimatch2(pattern, options); - list2 = list2.filter(function(f) { - return mm.match(f); - }); - if (mm.options.nonull && !list2.length) { - list2.push(pattern); - } - return list2; - }; - Minimatch2.prototype.match = match; - function match(f, partial) { - this.debug("match", f, this.pattern); - if (this.comment) - return false; - if (this.empty) - return f === ""; - if (f === "/" && partial) - return true; - var options = this.options; - if (path36.sep !== "/") { - f = f.split(path36.sep).join("/"); - } - f = f.split(slashSplit); - this.debug(this.pattern, "split", f); - var set = this.set; - this.debug(this.pattern, "set", set); - var filename; - var i; - for (i = f.length - 1; i >= 0; i--) { - filename = f[i]; - if (filename) - break; - } - for (i = 0; i < set.length; i++) { - var pattern = set[i]; - var file = f; - if (options.matchBase && pattern.length === 1) { - file = [filename]; - } - var hit = this.matchOne(file, pattern, partial); - if (hit) { - if (options.flipNegate) - return true; - return !this.negate; - } - } - if (options.flipNegate) - return false; - return this.negate; - } - Minimatch2.prototype.matchOne = function(file, pattern, partial) { - var options = this.options; - this.debug("matchOne", { "this": this, file, pattern }); - this.debug("matchOne", file.length, pattern.length); - for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { - this.debug("matchOne loop"); - var p = pattern[pi]; - var f = file[fi]; - this.debug(pattern, p, f); - if (p === false) - return false; - if (p === GLOBSTAR) { - this.debug("GLOBSTAR", [pattern, p, f]); - var fr = fi; - var pr = pi + 1; - if (pr === pl) { - this.debug("** at the end"); - for (; fi < fl; fi++) { - if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") - return false; - } - return true; - } - while (fr < fl) { - var swallowee = file[fr]; - this.debug("\nglobstar while", file, fr, pattern, pr, swallowee); - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug("globstar found match!", fr, fl, swallowee); - return true; - } else { - if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") { - this.debug("dot detected!", file, fr, pattern, pr); - break; - } - this.debug("globstar swallow a segment, and continue"); - fr++; - } - } - if (partial) { - this.debug("\n>>> no match, partial?", file, fr, pattern, pr); - if (fr === fl) - return true; - } - return false; - } - var hit; - if (typeof p === "string") { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase(); - } else { - hit = f === p; - } - this.debug("string match", p, f, hit); - } else { - hit = f.match(p); - this.debug("pattern match", p, f, hit); - } - if (!hit) - return false; - } - if (fi === fl && pi === pl) { - return true; - } else if (fi === fl) { - return partial; - } else if (pi === pl) { - var emptyFileEnd = fi === fl - 1 && file[fi] === ""; - return emptyFileEnd; - } - throw new Error("wtf?"); - }; - function globUnescape(s) { - return s.replace(/\\(.)/g, "$1"); - } - function regExpEscape(s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); - } - } -}); - -// src/util/fs.ts -async function statAsync(filepath) { - let stat = null; - try { - stat = await import_fs_extra.default.stat(filepath); - } catch (e) { - } - return stat; -} -function renameAsync(oldPath, newPath) { - return new Promise((resolve3, reject) => { - import_fs_extra.default.rename(oldPath, newPath, (err) => { - if (err) - return reject(err); - resolve3(); - }); - }); -} -function resolveRoot(folder, subs, cwd, bottomup = false, checkCwd = true) { - let home = import_os.default.homedir(); - let dir = fixDriver(folder); - if (isParentFolder(dir, home, true)) - return null; - if (checkCwd && cwd && isParentFolder(cwd, dir, true) && inDirectory(cwd, subs)) - return cwd; - let parts = dir.split(import_path3.default.sep); - if (bottomup) { - while (parts.length > 0) { - let dir2 = parts.join(import_path3.default.sep); - if (dir2 == home) { - break; - } - if (dir2 != home && inDirectory(dir2, subs)) { - return dir2; - } - parts.pop(); - } - return null; - } else { - let curr = [parts.shift()]; - for (let part of parts) { - curr.push(part); - let dir2 = curr.join(import_path3.default.sep); - if (dir2 != home && inDirectory(dir2, subs)) { - return dir2; - } - } - return null; - } -} -function inDirectory(dir, subs) { - try { - let files = import_fs_extra.default.readdirSync(dir); - for (let pattern of subs) { - let is_wildcard = pattern.includes("*"); - let res = is_wildcard ? import_minimatch.default.match(files, pattern, { nobrace: true, noext: true, nocomment: true, nonegate: true, dot: true }).length !== 0 : files.includes(pattern); - if (res) - return true; - } - } catch (e) { - } - return false; -} -function findUp(name2, cwd) { - let root = import_path3.default.parse(cwd).root; - let subs = Array.isArray(name2) ? name2 : [name2]; - while (cwd && cwd !== root) { - let find = inDirectory(cwd, subs); - if (find) { - for (let sub of subs) { - let filepath = import_path3.default.join(cwd, sub); - if (import_fs_extra.default.existsSync(filepath)) { - return filepath; - } - } - } - cwd = import_path3.default.dirname(cwd); - } - return null; -} -function readFile(fullpath, encoding) { - return new Promise((resolve3, reject) => { - import_fs_extra.default.readFile(fullpath, encoding, (err, content) => { - if (err) - reject(err); - resolve3(content); - }); - }); -} -function getFileLineCount(filepath) { - let i; - let count = 0; - return new Promise((resolve3, reject) => { - import_fs_extra.default.createReadStream(filepath).on("error", (e) => reject(e)).on("data", (chunk) => { - for (i = 0; i < chunk.length; ++i) - if (chunk[i] == 10) - count++; - }).on("end", () => resolve3(count)); - }); -} -function readFileLines(fullpath, start, end) { - if (!import_fs_extra.default.existsSync(fullpath)) { - return Promise.reject(new Error(`file does not exist: ${fullpath}`)); - } - let res = []; - const rl = import_readline.default.createInterface({ - input: import_fs_extra.default.createReadStream(fullpath, { encoding: "utf8" }), - crlfDelay: Infinity, - terminal: false - }); - let n = 0; - return new Promise((resolve3, reject) => { - rl.on("line", (line) => { - if (n == 0 && line.startsWith("\uFEFF")) { - line = line.slice(1); - } - if (n >= start && n <= end) { - res.push(line); - } - if (n == end) { - rl.close(); - } - n = n + 1; - }); - rl.on("close", () => { - resolve3(res); - }); - rl.on("error", reject); - }); -} -function readFileLine(fullpath, count) { - if (!import_fs_extra.default.existsSync(fullpath)) { - return Promise.reject(new Error(`file does not exist: ${fullpath}`)); - } - const rl = import_readline.default.createInterface({ - input: import_fs_extra.default.createReadStream(fullpath, { encoding: "utf8" }), - crlfDelay: Infinity, - terminal: false - }); - let n = 0; - return new Promise((resolve3, reject) => { - rl.on("line", (line) => { - if (n == count) { - if (n == 0 && line.startsWith("\uFEFF")) { - line = line.slice(1); - } - rl.close(); - resolve3(line); - return; - } - n = n + 1; - }); - rl.on("error", reject); - }); -} -async function writeFile(fullpath, content) { - await import_fs_extra.default.writeFile(fullpath, content, { encoding: "utf8" }); -} -function isFile(uri) { - return uri.startsWith("file:"); -} -function isParentFolder(folder, filepath, checkEqual = false) { - let pdir = fixDriver(import_path3.default.resolve(import_path3.default.normalize(folder))); - let dir = fixDriver(import_path3.default.resolve(import_path3.default.normalize(filepath))); - if (pdir == "//") - pdir = "/"; - if (pdir == dir) - return checkEqual ? true : false; - if (pdir.endsWith(import_path3.default.sep)) - return dir.startsWith(pdir); - return dir.startsWith(pdir) && dir[pdir.length] == import_path3.default.sep; -} -function fixDriver(filepath) { - if (import_os.default.platform() != "win32" || filepath[1] != ":") - return filepath; - return filepath[0].toUpperCase() + filepath.slice(1); -} -var import_child_process2, import_fs_extra, import_net, import_os, import_path3, import_readline, import_util9, import_minimatch, logger14; -var init_fs = __esm({ - "src/util/fs.ts"() { - import_child_process2 = __toModule(require("child_process")); - import_fs_extra = __toModule(require_lib5()); - import_net = __toModule(require("net")); - import_os = __toModule(require("os")); - import_path3 = __toModule(require("path")); - import_readline = __toModule(require("readline")); - import_util9 = __toModule(require("util")); - import_minimatch = __toModule(require_minimatch()); - logger14 = require_logger2()("util-fs"); - } -}); - -// src/configuration/index.ts -function lookUp(tree, key) { - if (key) { - if (tree && tree.hasOwnProperty(key)) - return tree[key]; - const parts = key.split("."); - let node = tree; - for (let i = 0; node && i < parts.length; i++) { - node = node[parts[i]]; - } - return node; - } - return tree; -} -var import_os2, import_fs3, import_path4, import_vscode_languageserver_protocol8, logger15, Configurations; -var init_configuration2 = __esm({ - "src/configuration/index.ts"() { - import_os2 = __toModule(require("os")); - import_fs3 = __toModule(require("fs")); - import_path4 = __toModule(require("path")); - import_vscode_languageserver_protocol8 = __toModule(require_main2()); - init_esm2(); - init_types(); - init_object(); - init_util(); - init_configuration(); - init_model(); - init_util2(); - init_is(); - init_fs(); - logger15 = require_logger2()("configurations"); - Configurations = class { - constructor(userConfigFile, _proxy) { - this.userConfigFile = userConfigFile; - this._proxy = _proxy; - this._errorItems = []; - this._folderConfigurations = new Map(); - this._onError = new import_vscode_languageserver_protocol8.Emitter(); - this._onChange = new import_vscode_languageserver_protocol8.Emitter(); - this.disposables = []; - this.onError = this._onError.event; - this.onDidChange = this._onChange.event; - let user = this.parseContentFromFile(userConfigFile); - let data = { - defaults: loadDefaultConfigurations(), - user, - workspace: { contents: {} } - }; - this._configuration = Configurations.parse(data); - this.watchFile(userConfigFile, ConfigurationTarget.User); - let folderConfigFile = import_path4.default.join(process.cwd(), `.vim/${CONFIG_FILE_NAME}`); - if (folderConfigFile != userConfigFile && import_fs3.default.existsSync(folderConfigFile)) { - this.addFolderFile(folderConfigFile); - } - } - parseContentFromFile(filepath) { - if (!filepath) - return { contents: {} }; - let uri = URI.file(filepath).toString(); - this._errorItems = this._errorItems.filter((o) => o.location.uri != uri); - let res = parseContentFromFile(filepath, (errors) => { - this._errorItems.push(...errors); - }); - this._onError.fire(this._errorItems); - return res; - } - get errorItems() { - return this._errorItems; - } - get foldConfigurations() { - return this._folderConfigurations; - } - extendsDefaults(props) { - let { defaults: defaults2 } = this._configuration; - let { contents } = defaults2; - contents = deepClone(contents); - Object.keys(props).forEach((key) => { - addToValueTree(contents, key, props[key], (msg) => { - logger15.error(msg); - }); - }); - let data = { - defaults: { contents }, - user: this._configuration.user, - workspace: this._configuration.workspace - }; - this._configuration = Configurations.parse(data); - } - updateUserConfig(props) { - if (!props || Object.keys(props).length == 0) - return; - let { user } = this._configuration; - let model = user.clone(); - Object.keys(props).forEach((key) => { - let val = props[key]; - if (val === void 0) { - model.removeValue(key); - } else if (objectLiteral(val)) { - for (let k of Object.keys(val)) { - model.setValue(`${key}.${k}`, val[k]); - } - } else { - model.setValue(key, val); - } - }); - this.changeConfiguration(ConfigurationTarget.User, model); - } - get defaults() { - return this._configuration.defaults; - } - get user() { - return this._configuration.user; - } - get workspace() { - return this._configuration.workspace; - } - addFolderFile(filepath) { - let { _folderConfigurations } = this; - if (_folderConfigurations.has(filepath)) - return; - if (import_path4.default.resolve(filepath, "../..") == import_os2.default.homedir()) - return; - let model = this.parseContentFromFile(filepath); - this.watchFile(filepath, ConfigurationTarget.Workspace); - this.changeConfiguration(ConfigurationTarget.Workspace, model, filepath); - } - watchFile(filepath, target) { - if (!import_fs3.default.existsSync(filepath) || global.hasOwnProperty("__TEST__")) - return; - let disposable = watchFile(filepath, () => { - let model = this.parseContentFromFile(filepath); - this.changeConfiguration(target, model, filepath); - }); - this.disposables.push(disposable); - } - changeConfiguration(target, model, configFile) { - let { defaults: defaults2, user, workspace } = this._configuration; - let { workspaceConfigFile } = this; - let data = { - defaults: target == ConfigurationTarget.Global ? model : defaults2, - user: target == ConfigurationTarget.User ? model : user, - workspace: target == ConfigurationTarget.Workspace ? model : workspace - }; - let configuration = Configurations.parse(data); - let changed = getChangedKeys(this._configuration.getValue(), configuration.getValue()); - if (target == ConfigurationTarget.Workspace && configFile) { - this._folderConfigurations.set(configFile, new ConfigurationModel(model.contents)); - this.workspaceConfigFile = configFile; - } - if (changed.length == 0) - return; - this._configuration = configuration; - this._onChange.fire({ - affectsConfiguration: (section2, resource) => { - if (!resource || target != ConfigurationTarget.Workspace) - return changed.includes(section2); - let u = URI.parse(resource); - if (u.scheme !== "file") - return changed.includes(section2); - let filepath = u.fsPath; - let preRoot = workspaceConfigFile ? import_path4.default.resolve(workspaceConfigFile, "../..") : ""; - if (configFile && !isParentFolder(preRoot, filepath, true) && !isParentFolder(import_path4.default.resolve(configFile, "../.."), filepath)) { - return false; - } - return changed.includes(section2); - } - }); - } - setFolderConfiguration(uri) { - let u = URI.parse(uri); - if (u.scheme != "file") - return; - let filepath = u.fsPath; - for (let [configFile, model] of this.foldConfigurations) { - let root = import_path4.default.resolve(configFile, "../.."); - if (isParentFolder(root, filepath, true) && this.workspaceConfigFile != configFile) { - this.changeConfiguration(ConfigurationTarget.Workspace, model, configFile); - break; - } - } - } - hasFolderConfiguration(filepath) { - let { folders } = this; - return folders.findIndex((f) => isParentFolder(f, filepath, true)) !== -1; - } - getConfigFile(target) { - if (target == ConfigurationTarget.Global) - return null; - if (target == ConfigurationTarget.User) - return this.userConfigFile; - return this.workspaceConfigFile; - } - get folders() { - let res = []; - let { _folderConfigurations } = this; - for (let folder of _folderConfigurations.keys()) { - res.push(import_path4.default.resolve(folder, "../..")); - } - return res; - } - get configuration() { - return this._configuration; - } - getConfiguration(section2, resource) { - let configuration; - if (resource) { - let { defaults: defaults2, user } = this._configuration; - configuration = new Configuration(defaults2, user, this.getFolderConfiguration(resource)); - } else { - configuration = this._configuration; - } - const config = Object.freeze(lookUp(configuration.getValue(null), section2)); - const result = { - has(key) { - return typeof lookUp(config, key) !== "undefined"; - }, - get: (key, defaultValue) => { - let result2 = lookUp(config, key); - if (result2 == null) - return defaultValue; - return result2; - }, - update: (key, value, isUser = false) => { - let s = section2 ? `${section2}.${key}` : key; - let target = isUser ? ConfigurationTarget.User : ConfigurationTarget.Workspace; - let model = target == ConfigurationTarget.User ? this.user.clone() : this.workspace.clone(); - if (value == void 0) { - model.removeValue(s); - } else { - model.setValue(s, value); - } - if (target == ConfigurationTarget.Workspace && !this.workspaceConfigFile && this._proxy) { - let file = this.workspaceConfigFile = this._proxy.workspaceConfigFile; - if (!import_fs3.default.existsSync(file)) { - let folder = import_path4.default.dirname(file); - if (!import_fs3.default.existsSync(folder)) - import_fs3.default.mkdirSync(folder); - import_fs3.default.writeFileSync(file, "{}", { encoding: "utf8" }); - } - } - this.changeConfiguration(target, model, target == ConfigurationTarget.Workspace ? this.workspaceConfigFile : this.userConfigFile); - if (this._proxy && !global.hasOwnProperty("__TEST__")) { - if (value == void 0) { - this._proxy.$removeConfigurationOption(target, s); - } else { - this._proxy.$updateConfigurationOption(target, s, value); - } - } - }, - inspect: (key) => { - key = section2 ? `${section2}.${key}` : key; - const config2 = this._configuration.inspect(key); - if (config2) { - return { - key, - defaultValue: config2.default, - globalValue: config2.user, - workspaceValue: config2.workspace - }; - } - return void 0; - } - }; - Object.defineProperty(result, "has", { - enumerable: false - }); - Object.defineProperty(result, "get", { - enumerable: false - }); - Object.defineProperty(result, "update", { - enumerable: false - }); - Object.defineProperty(result, "inspect", { - enumerable: false - }); - if (typeof config === "object") { - mixin(result, config, false); - } - return deepFreeze(result); - } - getFolderConfiguration(uri) { - let u = URI.parse(uri); - if (u.scheme != "file") - return new ConfigurationModel(); - let filepath = u.fsPath; - for (let [configFile, model] of this.foldConfigurations) { - let root = import_path4.default.resolve(configFile, "../.."); - if (isParentFolder(root, filepath, true)) - return model; - } - return new ConfigurationModel(); - } - checkFolderConfiguration(uri) { - let u = URI.parse(uri); - if (u.scheme != "file") - return; - let rootPath = import_path4.default.dirname(u.fsPath); - if (!this.hasFolderConfiguration(rootPath)) { - let folder = findUp(".vim", rootPath); - if (folder && folder != import_os2.default.homedir()) { - let file = import_path4.default.join(folder, CONFIG_FILE_NAME); - if (import_fs3.default.existsSync(file)) { - this.addFolderFile(file); - } - } - } else { - this.setFolderConfiguration(uri); - } - } - static parse(data) { - const defaultConfiguration = new ConfigurationModel(data.defaults.contents); - const userConfiguration = new ConfigurationModel(data.user.contents); - const workspaceConfiguration = new ConfigurationModel(data.workspace.contents); - return new Configuration(defaultConfiguration, userConfiguration, workspaceConfiguration, new ConfigurationModel()); - } - dispose() { - disposeAll(this.disposables); - } - }; - } -}); - -// src/configuration/shape.ts -var import_fs5, import_path5, logger16, ConfigurationProxy; -var init_shape = __esm({ - "src/configuration/shape.ts"() { - import_fs5 = __toModule(require("fs")); - init_main3(); - import_path5 = __toModule(require("path")); - init_esm2(); - init_util(); - logger16 = require_logger2()("configuration-shape"); - ConfigurationProxy = class { - constructor(workspace) { - this.workspace = workspace; - } - get nvim() { - return this.workspace.nvim; - } - async modifyConfiguration(target, key, value) { - let { nvim, workspace } = this; - let file = workspace.getConfigFile(target); - if (!file) - return; - let formattingOptions = { tabSize: 2, insertSpaces: true }; - let content = import_fs5.default.readFileSync(file, "utf8"); - value = value == null ? void 0 : value; - let edits = modify(content, [key], value, { formattingOptions }); - content = applyEdits(content, edits); - import_fs5.default.writeFileSync(file, content, "utf8"); - let doc = workspace.getDocument(URI.file(file).toString()); - if (doc) - nvim.command("checktime", true); - return; - } - get workspaceConfigFile() { - let folder = import_path5.default.join(this.workspace.root, ".vim"); - return import_path5.default.join(folder, CONFIG_FILE_NAME); - } - $updateConfigurationOption(target, key, value) { - this.modifyConfiguration(target, key, value).logError(); - } - $removeConfigurationOption(target, key) { - this.modifyConfiguration(target, key).logError(); - } - }; - } -}); - -// src/model/db.ts -var import_fs_extra2, import_path6, DB; -var init_db = __esm({ - "src/model/db.ts"() { - import_fs_extra2 = __toModule(require_lib5()); - import_path6 = __toModule(require("path")); - DB = class { - constructor(filepath) { - this.filepath = filepath; - } - fetch(key) { - let obj = this.load(); - if (!key) - return obj; - let parts = key.split("."); - for (let part of parts) { - if (typeof obj[part] == "undefined") { - return void 0; - } - obj = obj[part]; - } - return obj; - } - exists(key) { - let obj = this.load(); - let parts = key.split("."); - for (let part of parts) { - if (typeof obj[part] == "undefined") { - return false; - } - obj = obj[part]; - } - return true; - } - delete(key) { - let obj = this.load(); - let origin = obj; - let parts = key.split("."); - let len = parts.length; - for (let i = 0; i < len; i++) { - if (typeof obj[parts[i]] == "undefined") { - break; - } - if (i == len - 1) { - delete obj[parts[i]]; - import_fs_extra2.default.writeFileSync(this.filepath, JSON.stringify(origin, null, 2), "utf8"); - break; - } - obj = obj[parts[i]]; - } - } - push(key, data) { - let origin = this.load() || {}; - let obj = origin; - let parts = key.split("."); - let len = parts.length; - if (obj == null) { - let dir = import_path6.default.dirname(this.filepath); - import_fs_extra2.default.mkdirpSync(dir); - obj = origin; - } - for (let i = 0; i < len; i++) { - let key2 = parts[i]; - if (i == len - 1) { - obj[key2] = data; - import_fs_extra2.default.writeFileSync(this.filepath, JSON.stringify(origin, null, 2)); - break; - } - if (typeof obj[key2] == "undefined") { - obj[key2] = {}; - obj = obj[key2]; - } else { - obj = obj[key2]; - } - } - } - load() { - let dir = import_path6.default.dirname(this.filepath); - let stat = import_fs_extra2.default.statSync(dir); - if (!stat || !stat.isDirectory()) { - import_fs_extra2.default.mkdirpSync(dir); - import_fs_extra2.default.writeFileSync(this.filepath, "{}", "utf8"); - return {}; - } - try { - let content = import_fs_extra2.default.readFileSync(this.filepath, "utf8"); - return JSON.parse(content.trim()); - } catch (e) { - import_fs_extra2.default.writeFileSync(this.filepath, "{}", "utf8"); - return {}; - } - } - clear() { - let stat = import_fs_extra2.default.statSync(this.filepath); - if (!stat || !stat.isFile()) - return; - import_fs_extra2.default.writeFileSync(this.filepath, "{}", "utf8"); - } - destroy() { - if (import_fs_extra2.default.existsSync(this.filepath)) { - import_fs_extra2.default.unlinkSync(this.filepath); - } - } - }; - } -}); - -// src/util/diff.ts -function diffLines(oldLines, newLines, startLine) { - let endOffset = 0; - let startOffset = 0; - let parts = oldLines.slice(startLine + 1); - for (let i = 0; i < Math.min(parts.length, newLines.length); i++) { - if (parts[parts.length - 1 - i] == newLines[newLines.length - 1 - i]) { - endOffset = endOffset + 1; - } else { - break; - } - } - for (let i = 0; i <= Math.min(startLine, newLines.length - 1 - endOffset); i++) { - if (oldLines[i] == newLines[i]) { - startOffset = startOffset + 1; - } else { - break; - } - } - let replacement = newLines.slice(startOffset, newLines.length - endOffset); - let end = oldLines.length - endOffset; - if (end > startOffset && replacement.length) { - let offset = 0; - for (let i = 0; i < Math.min(replacement.length, end - startOffset); i++) { - if (replacement[i] == oldLines[startOffset + i]) { - offset = offset + 1; - } else { - break; - } - } - if (offset) { - return { - start: startOffset + offset, - end, - replacement: replacement.slice(offset) - }; - } - } - return { - start: startOffset, - end, - replacement - }; -} -function getChange(oldStr, newStr, cursorEnd) { - let ol = oldStr.length; - let nl = newStr.length; - let max = Math.min(ol, nl); - let newText = ""; - let startOffset = 0; - let endOffset = -1; - let shouldLimit = false; - for (let i = 0; i <= max; i++) { - if (cursorEnd != null && i == cursorEnd) { - endOffset = i; - shouldLimit = true; - break; - } - if (oldStr[ol - i - 1] != newStr[nl - i - 1]) { - endOffset = i; - break; - } - } - if (endOffset == -1) - return null; - let remain = max - endOffset; - if (remain == 0) { - startOffset = 0; - } else { - for (let i = 0; i <= remain; i++) { - if (oldStr[i] != newStr[i] || i == remain) { - startOffset = i; - break; - } - } - } - remain = remain - startOffset; - if (shouldLimit && remain > 0) { - let end2 = endOffset; - for (let i = 0; i < remain; i++) { - let oc = oldStr[ol - end2 - 1 - i]; - let nc = newStr[nl - end2 - 1 - i]; - if (oc == nc) { - endOffset = endOffset + 1; - } else { - break; - } - } - } - let end = ol - endOffset; - if (ol == nl && startOffset == end) - return null; - newText = newStr.slice(startOffset, nl - endOffset); - if (startOffset == end) { - let pre = startOffset == 0 ? "" : newStr[startOffset - 1]; - if (pre && pre != "\n" && oldStr[startOffset] == "\n" && newText.startsWith("\n")) { - return { start: startOffset + 1, end: end + 1, newText: newText.slice(1) + "\n" }; - } - } - return { start: startOffset, end, newText }; -} -function patchLine(from, to, fill = " ") { - if (from == to) - return to; - let idx = to.indexOf(from); - if (idx !== -1) - return fill.repeat(idx) + from; - let result = (0, import_fast_diff.default)(from, to); - let str = ""; - for (let item of result) { - if (item[0] == import_fast_diff.default.DELETE) { - return to; - } else if (item[0] == import_fast_diff.default.INSERT) { - str = str + fill.repeat(byteLength(item[1])); - } else { - str = str + item[1]; - } - } - return str; -} -var import_fast_diff, logger17; -var init_diff = __esm({ - "src/util/diff.ts"() { - import_fast_diff = __toModule(require_diff()); - init_string(); - logger17 = require_logger2()("util-diff"); - } -}); - -// src/model/chars.ts -var logger18, Range3, Chars; -var init_chars = __esm({ - "src/model/chars.ts"() { - logger18 = require_logger2()("model-chars"); - Range3 = class { - constructor(start, end) { - this.start = start; - this.end = end ? end : start; - } - static fromKeywordOption(keywordOption) { - let parts = keywordOption.split(","); - let ranges = []; - for (let part of parts) { - if (part == "@") { - ranges.push(new Range3(65, 90)); - ranges.push(new Range3(97, 122)); - } else if (part == "@-@") { - ranges.push(new Range3(64)); - } else if (/^([A-Za-z])-([A-Za-z])$/.test(part)) { - let ms = part.match(/^([A-Za-z])-([A-Za-z])$/); - ranges.push(new Range3(ms[1].charCodeAt(0), ms[2].charCodeAt(0))); - } else if (/^\d+-\d+$/.test(part)) { - let ms = part.match(/^(\d+)-(\d+)$/); - ranges.push(new Range3(Number(ms[1]), Number(ms[2]))); - } else if (/^\d+$/.test(part)) { - ranges.push(new Range3(Number(part))); - } else { - let c = part.charCodeAt(0); - if (!ranges.some((o) => o.contains(c))) { - ranges.push(new Range3(c)); - } - } - } - return ranges; - } - contains(c) { - return c >= this.start && c <= this.end; - } - }; - Chars = class { - constructor(keywordOption) { - this.ranges = []; - if (keywordOption) - this.ranges = Range3.fromKeywordOption(keywordOption); - } - addKeyword(ch) { - let c = ch.charCodeAt(0); - let { ranges } = this; - if (!ranges.some((o) => o.contains(c))) { - ranges.push(new Range3(c)); - } - } - clone() { - let chars = new Chars(); - chars.ranges = this.ranges.slice(); - return chars; - } - setKeywordOption(keywordOption) { - this.ranges = Range3.fromKeywordOption(keywordOption); - } - matchKeywords(content, min = 3) { - let length = content.length; - if (length == 0) - return []; - let res = new Set(); - let str = ""; - let len = 0; - for (let i = 0; i < length; i++) { - let ch = content[i]; - let code = ch.codePointAt(0); - if (len == 0 && code == 45) - continue; - let isKeyword = this.isKeywordCode(code); - if (isKeyword) { - if (len == 48) - continue; - str = str + ch; - len = len + 1; - } else { - if (len >= min && len < 48) - res.add(str); - str = ""; - len = 0; - } - } - if (len != 0) - res.add(str); - return Array.from(res); - } - isKeywordCode(code) { - if (code > 255) - return true; - if (code < 33) - return false; - return this.ranges.some((r) => r.contains(code)); - } - isKeywordChar(ch) { - let { ranges } = this; - let c = ch.charCodeAt(0); - if (c > 255) - return true; - if (c < 33) - return false; - return ranges.some((r) => r.contains(c)); - } - isKeyword(word) { - let { ranges } = this; - for (let i = 0, l = word.length; i < l; i++) { - let ch = word.charCodeAt(i); - if (ch > 255) - return false; - if (ranges.some((r) => r.contains(ch))) - continue; - return false; - } - return true; - } - }; - } -}); - -// src/model/textdocument.ts -function computeLineOffsets2(text, isAtLineStart, textOffset = 0) { - const result = isAtLineStart ? [textOffset] : []; - for (let i = 0; i < text.length; i++) { - let ch = text.charCodeAt(i); - if (ch === 13 || ch === 10) { - if (ch === 13 && i + 1 < text.length && text.charCodeAt(i + 1) === 10) { - i++; - } - result.push(textOffset + i + 1); - } - } - return result; -} -var LinesTextDocument; -var init_textdocument = __esm({ - "src/model/textdocument.ts"() { - LinesTextDocument = class { - constructor(uri, languageId, version2, lines, eol) { - this.uri = uri; - this.languageId = languageId; - this.version = version2; - this.lines = lines; - this.eol = eol; - } - get _content() { - return this.lines.join("\n") + (this.eol ? "\n" : ""); - } - get lineCount() { - return this.lines.length + (this.eol ? 1 : 0); - } - getText(range) { - if (range) { - const start = this.offsetAt(range.start); - const end = this.offsetAt(range.end); - return this._content.substring(start, end); - } - return this._content; - } - positionAt(offset) { - offset = Math.max(Math.min(offset, this._content.length), 0); - let lineOffsets = this.getLineOffsets(); - let low = 0; - let high = lineOffsets.length; - if (high === 0) { - return { line: 0, character: offset }; - } - while (low < high) { - let mid = Math.floor((low + high) / 2); - if (lineOffsets[mid] > offset) { - high = mid; - } else { - low = mid + 1; - } - } - let line = low - 1; - return { line, character: offset - lineOffsets[line] }; - } - offsetAt(position) { - let lineOffsets = this.getLineOffsets(); - if (position.line >= lineOffsets.length) { - return this._content.length; - } else if (position.line < 0) { - return 0; - } - let lineOffset = lineOffsets[position.line]; - let nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length; - return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); - } - getLineOffsets() { - if (this._lineOffsets === void 0) { - this._lineOffsets = computeLineOffsets2(this._content, true); - } - return this._lineOffsets; - } - }; - } -}); - -// src/model/document.ts -var import_debounce3, import_vscode_languageserver_protocol9, logger19, Document; -var init_document = __esm({ - "src/model/document.ts"() { - import_debounce3 = __toModule(require_debounce()); - import_vscode_languageserver_protocol9 = __toModule(require_main2()); - init_main2(); - init_esm2(); - init_events(); - init_diff(); - init_util(); - init_object(); - init_position(); - init_string(); - init_chars(); - init_textdocument(); - logger19 = require_logger2()("model-document"); - Document = class { - constructor(buffer, env, maxFileSize) { - this.buffer = buffer; - this.env = env; - this.maxFileSize = maxFileSize; - this.isIgnored = false; - this.size = 0; - this.eol = true; - this.lines = []; - this._attached = false; - this._previewwindow = false; - this._winid = -1; - this._words = []; - this._onDocumentChange = new import_vscode_languageserver_protocol9.Emitter(); - this._onDocumentDetach = new import_vscode_languageserver_protocol9.Emitter(); - this.disposables = []; - this.onDocumentChange = this._onDocumentChange.event; - this.onDocumentDetach = this._onDocumentDetach.event; - this.fireContentChanges = (0, import_debounce3.default)(() => { - this._fireContentChanges(); - }, 300); - this.fetchContent = (0, import_debounce3.default)(() => { - void this._fetchContent(); - }, 100); - } - get content() { - return this.syncLines.join("\n") + (this.eol ? "\n" : ""); - } - get attached() { - return this._attached; - } - get bufnr() { - return this.buffer.id; - } - get filetype() { - return this._filetype; - } - get uri() { - return this._uri; - } - get shouldAttach() { - let { buftype, maxFileSize } = this; - if (!this.getVar("enabled", true)) - return false; - if (this.uri.endsWith("%5BCommand%20Line%5D")) - return true; - if (this.size == -2) - return false; - if (maxFileSize && this.size > maxFileSize) - return false; - return buftype == "" || buftype == "acwrite"; - } - get isCommandLine() { - return this.uri && this.uri.endsWith("%5BCommand%20Line%5D"); - } - get enabled() { - return this.getVar("enabled", true); - } - get words() { - return this._words; - } - convertFiletype(filetype) { - switch (filetype) { - case "javascript.jsx": - return "javascriptreact"; - case "typescript.jsx": - case "typescript.tsx": - return "typescriptreact"; - case "tex": - return "latex"; - default: { - let map = this.env.filetypeMap; - return map[filetype] || filetype; - } - } - } - get changedtick() { - return this._changedtick; - } - get schema() { - return URI.parse(this.uri).scheme; - } - get lineCount() { - return this.lines.length; - } - get winid() { - return this._winid; - } - get previewwindow() { - return this._previewwindow; - } - async init(nvim, token) { - this.nvim = nvim; - let opts = await nvim.call("coc#util#get_bufoptions", [this.bufnr, this.maxFileSize]); - if (opts == null) - return false; - let buftype = this.buftype = opts.buftype; - this._previewwindow = opts.previewwindow; - this._winid = opts.winid; - this.size = typeof opts.size == "number" ? opts.size : 0; - this.variables = opts.variables || {}; - this._changedtick = opts.changedtick; - this.eol = opts.eol == 1; - this._uri = getUri(opts.fullpath, this.bufnr, buftype, this.env.isCygwin); - if (token.isCancellationRequested) - return false; - if (this.shouldAttach) { - this.lines = opts.lines; - let res = await this.attach(); - if (!res) - return false; - this._attached = true; - } - this._filetype = this.convertFiletype(opts.filetype); - this.setIskeyword(opts.iskeyword); - this.createTextDocument(1, this.lines); - if (token.isCancellationRequested) { - this.detach(); - return false; - } - return true; - } - async attach() { - let attached = await this.buffer.attach(true); - if (!attached) - return false; - let lines = this.lines; - this.buffer.listen("lines", (buf, tick, firstline, lastline, linedata) => { - if (buf.id !== this.bufnr || !this._attached || tick == null) - return; - if (tick > this._changedtick) { - this._changedtick = tick; - lines = [...lines.slice(0, firstline), ...linedata, ...lines.slice(lastline)]; - this.lines = lines; - this.fireContentChanges(); - } - }, this.disposables); - this.buffer.listen("detach", async (buf) => { - lines = []; - this._onDocumentDetach.fire(buf.id); - }, this.disposables); - return true; - } - get dirty() { - if (this.lines === this.syncLines) - return false; - return !equals(this.lines, this.syncLines); - } - _fireContentChanges() { - let { cursor } = events_default; - if (!this.dirty) - return; - let textDocument = this._textDocument; - let endOffset = null; - if (cursor && cursor.bufnr == this.bufnr) { - endOffset = this.getEndOffset(cursor.lnum, cursor.col, cursor.insert); - } - let content = this.getDocumentContent(); - let change = getChange(textDocument.getText(), content, endOffset); - if (change == null) - return; - let start = textDocument.positionAt(change.start); - let end = textDocument.positionAt(change.end); - let original = textDocument.getText(import_vscode_languageserver_protocol9.Range.create(start, end)); - this.createTextDocument(this.version + 1, this.lines); - let changes = [{ - range: { start, end }, - rangeLength: change.end - change.start, - text: change.newText - }]; - this._onDocumentChange.fire({ - bufnr: this.bufnr, - original, - originalLines: textDocument.lines, - textDocument: { version: this.version, uri: this.uri }, - contentChanges: changes - }); - this._words = this.chars.matchKeywords(content); - } - async applyEdits(edits) { - if (!Array.isArray(arguments[0]) && Array.isArray(arguments[1])) { - edits = arguments[1]; - } - if (edits.length == 0) - return; - let textDocument = TextDocument2.create(this.uri, this.filetype, 1, this.getDocumentContent()); - let applied = TextDocument2.applyEdits(textDocument, edits); - let content; - if (this.eol) { - if (applied.endsWith("\r\n")) { - content = applied.slice(0, -2); - } else { - content = applied.endsWith("\n") ? applied.slice(0, -1) : applied; - } - } else { - content = applied; - } - let lines = this.lines; - let newLines = content.split(/\r?\n/); - if (!equals(lines, newLines)) { - let lnums = edits.map((o) => o.range.start.line); - let d = diffLines(lines, newLines, Math.min.apply(null, lnums)); - let original = lines.slice(d.start, d.end); - this.nvim.call("coc#util#set_lines", [this.bufnr, this._changedtick, original, d.replacement, d.start, d.end], true); - if (this.env.isVim) - this.nvim.command("redraw", true); - await waitNextTick(() => { - this.lines = newLines; - this._forceSync(); - }); - } - } - async changeLines(lines) { - let filtered = []; - let newLines = this.lines.slice(); - for (let [lnum, text] of lines) { - if (newLines[lnum] != text) { - filtered.push([lnum, text]); - newLines[lnum] = text; - } - } - if (!filtered.length) - return; - this.nvim.call("coc#util#change_lines", [this.bufnr, filtered], true); - if (this.env.isVim) - this.nvim.command("redraw", true); - this.lines = newLines; - this._forceSync(); - } - _forceSync() { - this.fireContentChanges.clear(); - this._fireContentChanges(); - } - forceSync() { - if (global.hasOwnProperty("__TEST__")) { - this._forceSync(); - } - } - getOffset(lnum, col) { - return this.textDocument.offsetAt({ - line: lnum - 1, - character: col - }); - } - isWord(word) { - return this.chars.isKeyword(word); - } - getMoreWords() { - let res = []; - let { words, chars } = this; - if (!chars.isKeywordChar("-")) - return res; - for (let word of words) { - word = word.replace(/^-+/, ""); - if (word.includes("-")) { - let parts = word.split("-"); - for (let part of parts) { - if (part.length > 2 && !res.includes(part) && !words.includes(part)) { - res.push(part); - } - } - } - } - return res; - } - getWordRangeAtPosition(position, extraChars, current = true) { - let chars = this.chars.clone(); - if (extraChars && extraChars.length) { - for (let ch of extraChars) { - chars.addKeyword(ch); - } - } - let line = this.getline(position.line, current); - if (line.length == 0 || position.character >= line.length) - return null; - if (!chars.isKeywordChar(line[position.character])) - return null; - let start = position.character; - let end = position.character + 1; - if (!chars.isKeywordChar(line[start])) { - return import_vscode_languageserver_protocol9.Range.create(position, { line: position.line, character: position.character + 1 }); - } - while (start >= 0) { - let ch = line[start - 1]; - if (!ch || !chars.isKeyword(ch)) - break; - start = start - 1; - } - while (end <= line.length) { - let ch = line[end]; - if (!ch || !chars.isKeywordChar(ch)) - break; - end = end + 1; - } - return import_vscode_languageserver_protocol9.Range.create(position.line, start, position.line, end); - } - get textDocument() { - return this._textDocument; - } - get syncLines() { - return this._textDocument.lines; - } - get version() { - return this._textDocument.version; - } - createTextDocument(version2, lines) { - let { uri, filetype, eol } = this; - this._textDocument = new LinesTextDocument(uri, filetype, version2, lines, eol); - } - async _fetchContent(sync) { - if (!this.env.isVim || !this._attached) - return; - let { nvim, bufnr, changedtick } = this; - let o = await nvim.call("coc#util#get_buf_lines", [bufnr, changedtick]); - if (o) { - this._changedtick = o.changedtick; - this.lines = o.lines; - if (sync) { - this._forceSync(); - } else { - this.fireContentChanges(); - } - } - } - async patchChange(currentLine) { - if (!this._attached) - return; - if (this.env.isVim) { - if (currentLine) { - let change = await this.nvim.call("coc#util#get_changeinfo", []); - if (change.changedtick < this._changedtick) - return; - let { lnum, line, changedtick } = change; - let newLines = this.lines.slice(); - this._changedtick = changedtick; - if (newLines[lnum - 1] == line) - return; - newLines[lnum - 1] = line; - this.lines = newLines; - this._forceSync(); - } else { - this.fetchContent.clear(); - await this._fetchContent(true); - } - } else { - this._changedtick = await this.buffer.getVar("changedtick"); - this._forceSync(); - } - } - getSymbolRanges(word) { - let { version: version2, filetype, uri } = this; - let textDocument = new LinesTextDocument(uri, filetype, version2, this.lines, this.eol); - let res = []; - let content = textDocument.getText(); - let str = ""; - for (let i = 0, l = content.length; i < l; i++) { - let ch = content[i]; - if (ch == "-" && str.length == 0) { - continue; - } - let isKeyword = this.chars.isKeywordChar(ch); - if (isKeyword) { - str = str + ch; - } - if (str.length > 0 && !isKeyword && str == word) { - res.push(import_vscode_languageserver_protocol9.Range.create(textDocument.positionAt(i - str.length), textDocument.positionAt(i))); - } - if (!isKeyword) { - str = ""; - } - } - return res; - } - fixStartcol(position, valids) { - let line = this.getline(position.line); - if (!line) - return null; - let { character } = position; - let start = line.slice(0, character); - let col = byteLength(start); - let { chars } = this; - for (let i = start.length - 1; i >= 0; i--) { - let c = start[i]; - if (c == " ") - break; - if (!chars.isKeywordChar(c) && !valids.includes(c)) { - break; - } - col = col - byteLength(c); - } - return col; - } - addHighlights(items, hlGroup, range) { - let { start, end } = range; - if (emptyRange(range)) - return; - for (let line = start.line; line <= end.line; line++) { - const text = this.getline(line, false); - let colStart = line == start.line ? byteIndex(text, start.character) : 0; - let colEnd = line == end.line ? byteIndex(text, end.character) : global.Buffer.byteLength(text); - if (colStart >= colEnd) - continue; - items.push({ hlGroup, lnum: line, colStart, colEnd }); - } - } - getline(line, current = true) { - if (current) - return this.lines[line] || ""; - return this.syncLines[line] || ""; - } - getLines(start, end) { - return this.lines.slice(start, end); - } - getDocumentContent() { - let content = this.lines.join("\n"); - return this.eol ? content + "\n" : content; - } - getVar(key, defaultValue) { - let val = this.variables[`coc_${key}`]; - return val === void 0 ? defaultValue : val; - } - getPosition(lnum, col) { - let line = this.getline(lnum - 1); - if (!line || col == 0) - return { line: lnum - 1, character: 0 }; - let pre = byteSlice(line, 0, col - 1); - return { line: lnum - 1, character: pre.length }; - } - getEndOffset(lnum, col, insert) { - let total = 0; - let len = this.lines.length; - for (let i = lnum - 1; i < len; i++) { - let line = this.lines[i]; - let l = line.length; - if (i == lnum - 1 && l != 0) { - let buf = global.Buffer.from(line, "utf8"); - let isEnd = buf.byteLength <= col - 1; - if (!isEnd) { - total = total + buf.slice(col - 1, buf.length).toString("utf8").length; - if (!insert) - total = total - 1; - } - } else { - total = total + l; - } - if (!this.eol && i == len - 1) - break; - total = total + 1; - } - return total; - } - setFiletype(filetype) { - this._filetype = this.convertFiletype(filetype); - let lines = this._textDocument.lines; - this._textDocument = new LinesTextDocument(this.uri, this.filetype, 1, lines, this.eol); - } - setIskeyword(iskeyword) { - let chars = this.chars = new Chars(iskeyword); - let additional = this.getVar("additional_keywords", []); - if (additional && Array.isArray(additional)) { - for (let ch of additional) { - chars.addKeyword(ch); - } - } - let lines = this.lines.length > 3e4 ? this.lines.slice(0, 3e4) : this.lines; - this._words = this.chars.matchKeywords(lines.join("\n")); - } - detach() { - this._attached = false; - disposeAll(this.disposables); - this.disposables = []; - this.fetchContent.clear(); - this.fireContentChanges.clear(); - this._onDocumentChange.dispose(); - this._onDocumentDetach.dispose(); - } - async synchronize() { - let { changedtick } = this; - await this.patchChange(); - if (changedtick != this.changedtick) { - await wait(50); - } - } - getLocalifyBonus(sp, ep) { - let res = new Map(); - let { chars } = this; - let startLine = Math.max(0, sp.line - 100); - let endLine = Math.min(this.lineCount, sp.line + 100); - let content = this.lines.slice(startLine, endLine).join("\n"); - sp = import_vscode_languageserver_protocol9.Position.create(sp.line - startLine, sp.character); - ep = import_vscode_languageserver_protocol9.Position.create(ep.line - startLine, ep.character); - let doc = TextDocument2.create(this.uri, this.filetype, 1, content); - let headCount = doc.offsetAt(sp); - let len = content.length; - let tailCount = len - doc.offsetAt(ep); - let start = 0; - let preKeyword = false; - for (let i = 0; i < headCount; i++) { - let iskeyword = chars.isKeyword(content[i]); - if (!preKeyword && iskeyword) { - start = i; - } else if (preKeyword && (!iskeyword || i == headCount - 1)) { - if (i - start > 1) { - let str = content.slice(start, i); - res.set(str, i / headCount); - } - } - preKeyword = iskeyword; - } - start = len - tailCount; - preKeyword = false; - for (let i = start; i < content.length; i++) { - let iskeyword = chars.isKeyword(content[i]); - if (!preKeyword && iskeyword) { - start = i; - } else if (preKeyword && (!iskeyword || i == len - 1)) { - if (i - start > 1) { - let end = i == len - 1 ? i + 1 : i; - let str = content.slice(start, end); - let score5 = res.get(str) || 0; - res.set(str, Math.max(score5, (len - i + (end - start)) / tailCount)); - } - } - preKeyword = iskeyword; - } - return res; - } - }; - } -}); - -// src/util/array.ts -function splitArray(array, fn) { - let res = [[], []]; - for (let item of array) { - if (fn(item)) { - res[0].push(item); - } else { - res[1].push(item); - } - } - return res; -} -function group(array, size) { - let len = array.length; - let res = []; - for (let i = 0; i < Math.ceil(len / size); i++) { - res.push(array.slice(i * size, (i + 1) * size)); - } - return res; -} -function distinct(array, keyFn) { - if (!keyFn) { - return array.filter((element, position) => array.indexOf(element) === position); - } - const seen = Object.create(null); - return array.filter((elem) => { - const key = keyFn(elem); - if (seen[key]) { - return false; - } - seen[key] = true; - return true; - }); -} -var init_array = __esm({ - "src/util/array.ts"() { - } -}); - -// src/model/fileSystemWatcher.ts -var import_vscode_languageserver_protocol10, import_minimatch2, import_path7, logger20, FileSystemWatcher; -var init_fileSystemWatcher = __esm({ - "src/model/fileSystemWatcher.ts"() { - import_vscode_languageserver_protocol10 = __toModule(require_main2()); - init_esm2(); - import_minimatch2 = __toModule(require_minimatch()); - import_path7 = __toModule(require("path")); - init_util(); - init_array(); - logger20 = require_logger2()("filesystem-watcher"); - FileSystemWatcher = class { - constructor(clientPromise, globPattern, ignoreCreateEvents, ignoreChangeEvents, ignoreDeleteEvents) { - this.globPattern = globPattern; - this.ignoreCreateEvents = ignoreCreateEvents; - this.ignoreChangeEvents = ignoreChangeEvents; - this.ignoreDeleteEvents = ignoreDeleteEvents; - this._onDidCreate = new import_vscode_languageserver_protocol10.Emitter(); - this._onDidChange = new import_vscode_languageserver_protocol10.Emitter(); - this._onDidDelete = new import_vscode_languageserver_protocol10.Emitter(); - this._onDidRename = new import_vscode_languageserver_protocol10.Emitter(); - this.onDidCreate = this._onDidCreate.event; - this.onDidChange = this._onDidChange.event; - this.onDidDelete = this._onDidDelete.event; - this.onDidRename = this._onDidRename.event; - this.disposables = []; - if (!clientPromise) - return; - clientPromise.then((client) => { - if (client) - return this.listen(client); - }).catch((error) => { - logger20.error("watchman initialize failed"); - logger20.error(error.stack); - }); - } - async listen(client) { - let { - globPattern, - ignoreCreateEvents, - ignoreChangeEvents, - ignoreDeleteEvents - } = this; - let disposable = await client.subscribe(globPattern, (change) => { - let { root, files } = change; - files = files.filter((f) => f.type == "f" && (0, import_minimatch2.default)(f.name, globPattern, { dot: true })); - for (let file of files) { - let uri = URI.file(import_path7.default.join(root, file.name)); - if (!file.exists) { - if (!ignoreDeleteEvents) - this._onDidDelete.fire(uri); - } else { - if (file.new === true) { - if (!ignoreCreateEvents) - this._onDidCreate.fire(uri); - } else { - if (!ignoreChangeEvents) - this._onDidChange.fire(uri); - } - } - } - if (files.length == 2 && !files[0].exists && files[1].exists) { - let oldFile = files[0]; - let newFile = files[1]; - if (oldFile.size == newFile.size) { - this._onDidRename.fire({ - oldUri: URI.file(import_path7.default.join(root, oldFile.name)), - newUri: URI.file(import_path7.default.join(root, newFile.name)) - }); - } - } - if (files.length >= 2) { - let [oldFiles, newFiles] = splitArray(files, (o) => o.exists === false); - if (oldFiles.length == newFiles.length) { - for (let oldFile of oldFiles) { - let newFile = newFiles.find((o) => o.size == oldFile.size && o.mtime_ms == oldFile.mtime_ms); - if (newFile) { - this._onDidRename.fire({ - oldUri: URI.file(import_path7.default.join(root, oldFile.name)), - newUri: URI.file(import_path7.default.join(root, newFile.name)) - }); - } - } - } - } - }); - this.disposables.push(disposable); - return disposable; - } - dispose() { - disposeAll(this.disposables); - } - }; - } -}); - -// src/model/mru.ts -var import_path8, import_fs_extra3, Mru; -var init_mru = __esm({ - "src/model/mru.ts"() { - import_path8 = __toModule(require("path")); - import_fs_extra3 = __toModule(require_lib5()); - Mru = class { - constructor(name2, base) { - this.name = name2; - this.file = import_path8.default.join(base || process.env.COC_DATA_HOME, name2); - } - async load() { - let dir = import_path8.default.dirname(this.file); - try { - import_fs_extra3.default.mkdirpSync(dir); - if (!import_fs_extra3.default.existsSync(this.file)) { - import_fs_extra3.default.writeFileSync(this.file, "", "utf8"); - } - let content = await import_fs_extra3.default.readFile(this.file, "utf8"); - content = content.trim(); - return content.length ? content.trim().split("\n") : []; - } catch (e) { - return []; - } - } - async add(item) { - let items = await this.load(); - let idx = items.indexOf(item); - if (idx !== -1) - items.splice(idx, 1); - items.unshift(item); - import_fs_extra3.default.writeFileSync(this.file, items.join("\n"), "utf8"); - } - async remove(item) { - let items = await this.load(); - let idx = items.indexOf(item); - if (idx !== -1) { - items.splice(idx, 1); - import_fs_extra3.default.writeFileSync(this.file, items.join("\n"), "utf8"); - } - } - async clean() { - try { - await import_fs_extra3.default.unlink(this.file); - } catch (e) { - } - } - }; - } -}); - -// src/util/decorator.ts -function memorize(_target, key, descriptor) { - let fn = descriptor.value; - if (typeof fn !== "function") - return; - let memoKey = "$" + key; - descriptor.value = function(...args) { - if (this.hasOwnProperty(memoKey)) - return Promise.resolve(this[memoKey]); - return new Promise((resolve3, reject) => { - Promise.resolve(fn.apply(this, args)).then((res) => { - this[memoKey] = res; - resolve3(res); - }, (e) => { - reject(e); - }); - }); - }; -} -var logger21; -var init_decorator = __esm({ - "src/util/decorator.ts"() { - logger21 = require_logger2()("util-decorator"); - } -}); - -// src/model/resolver.ts -var import_path9, import_fs6, import_strip_ansi2, logger22, Resolver; -var init_resolver = __esm({ - "src/model/resolver.ts"() { - import_path9 = __toModule(require("path")); - import_fs6 = __toModule(require("fs")); - init_util(); - init_fs(); - init_decorator(); - import_strip_ansi2 = __toModule(require_strip_ansi()); - logger22 = require_logger2()("model-resolver"); - Resolver = class { - get nodeFolder() { - if (!executable("npm")) - return Promise.resolve(""); - return runCommand("npm --loglevel silent root -g", {}, 3e3).then((root) => { - return (0, import_strip_ansi2.default)(root).trim(); - }); - } - get yarnFolder() { - if (!executable("yarnpkg")) - return Promise.resolve(""); - return runCommand("yarnpkg global dir", {}, 3e3).then((root) => { - let folder = import_path9.default.join((0, import_strip_ansi2.default)(root).trim(), "node_modules"); - let exists = import_fs6.default.existsSync(folder); - return exists ? folder : ""; - }); - } - async resolveModule(mod) { - let nodeFolder = await this.nodeFolder; - let yarnFolder = await this.yarnFolder; - if (yarnFolder) { - let s = await statAsync(import_path9.default.join(yarnFolder, mod, "package.json")); - if (s && s.isFile()) - return import_path9.default.join(yarnFolder, mod); - } - if (nodeFolder) { - let s = await statAsync(import_path9.default.join(nodeFolder, mod, "package.json")); - if (s && s.isFile()) - return import_path9.default.join(nodeFolder, mod); - } - return null; - } - }; - __decorateClass([ - memorize - ], Resolver.prototype, "nodeFolder", 1); - __decorateClass([ - memorize - ], Resolver.prototype, "yarnFolder", 1); - } -}); - -// src/model/task.ts -var import_vscode_languageserver_protocol11, Task; -var init_task = __esm({ - "src/model/task.ts"() { - init_events(); - import_vscode_languageserver_protocol11 = __toModule(require_main2()); - init_util(); - Task = class { - constructor(nvim, id) { - this.nvim = nvim; - this.id = id; - this.disposables = []; - this._onExit = new import_vscode_languageserver_protocol11.Emitter(); - this._onStderr = new import_vscode_languageserver_protocol11.Emitter(); - this._onStdout = new import_vscode_languageserver_protocol11.Emitter(); - this.onExit = this._onExit.event; - this.onStdout = this._onStdout.event; - this.onStderr = this._onStderr.event; - events_default.on("TaskExit", (id2, code) => { - if (id2 == this.id) { - this._onExit.fire(code); - } - }, null, this.disposables); - events_default.on("TaskStderr", (id2, lines) => { - if (id2 == this.id) { - this._onStderr.fire(lines); - } - }, null, this.disposables); - let stdout = []; - let timer; - events_default.on("TaskStdout", (id2, lines) => { - if (id2 == this.id) { - if (timer) - clearTimeout(timer); - stdout.push(...lines); - timer = setTimeout(() => { - this._onStdout.fire(stdout); - stdout = []; - }, 100); - } - }, null, this.disposables); - } - async start(opts) { - let { nvim } = this; - return await nvim.call("coc#task#start", [this.id, opts]); - } - async stop() { - let { nvim } = this; - await nvim.call("coc#task#stop", [this.id]); - } - get running() { - let { nvim } = this; - return nvim.call("coc#task#running", [this.id]); - } - dispose() { - let { nvim } = this; - nvim.call("coc#task#stop", [this.id], true); - this._onStdout.dispose(); - this._onStderr.dispose(); - this._onExit.dispose(); - disposeAll(this.disposables); - } - }; - } -}); - -// src/model/terminal.ts -var logger23, TerminalModel; -var init_terminal = __esm({ - "src/model/terminal.ts"() { - logger23 = require_logger2()("model-terminal"); - TerminalModel = class { - constructor(cmd, args, nvim, _name) { - this.cmd = cmd; - this.args = args; - this.nvim = nvim; - this._name = _name; - this.pid = 0; - } - async start(cwd, env) { - let { nvim } = this; - let cmd = [this.cmd, ...this.args]; - let [bufnr, pid] = await nvim.call("coc#terminal#start", [cmd, cwd, env || {}]); - this.bufnr = bufnr; - this.pid = pid; - } - get name() { - return this._name || this.cmd; - } - get processId() { - return Promise.resolve(this.pid); - } - sendText(text, addNewLine = true) { - if (!this.bufnr) - return; - this.nvim.call("coc#terminal#send", [this.bufnr, text, addNewLine], true); - } - async show(preserveFocus) { - let { bufnr, nvim } = this; - if (!bufnr) - return; - let [loaded, winid, curr] = await nvim.eval(`[bufloaded(${bufnr}),bufwinid(${bufnr}),win_getid()]`); - if (!loaded) - return false; - if (curr == winid) - return true; - nvim.pauseNotification(); - if (winid == -1) { - nvim.command(`below ${bufnr}sb`, true); - nvim.command("resize 8", true); - nvim.call("coc#util#do_autocmd", ["CocTerminalOpen"], true); - } else { - nvim.call("win_gotoid", [winid], true); - } - nvim.command("normal! G", true); - if (preserveFocus) { - nvim.command("wincmd p", true); - } - await nvim.resumeNotification(); - return true; - } - async hide() { - let { bufnr, nvim } = this; - if (!bufnr) - return; - let winnr = await nvim.call("bufwinnr", bufnr); - if (winnr == -1) - return; - await nvim.command(`${winnr}close!`); - } - dispose() { - let { bufnr, nvim } = this; - if (!bufnr) - return; - nvim.call("coc#terminal#close", [bufnr], true); - } - }; - } -}); - -// src/model/bufferSync.ts -var BufferSync; -var init_bufferSync = __esm({ - "src/model/bufferSync.ts"() { - init_util(); - BufferSync = class { - constructor(_create, workspace) { - this._create = _create; - this.workspace = workspace; - this.disposables = []; - this.itemsMap = new Map(); - let { disposables } = this; - for (let doc of workspace.documents) { - this.create(doc); - } - workspace.onDidOpenTextDocument((e) => { - let doc = workspace.getDocument(e.bufnr); - if (doc) - this.create(doc); - }, null, disposables); - workspace.onDidChangeTextDocument((e) => { - this.onChange(e); - }, null, disposables); - workspace.onDidCloseTextDocument((e) => { - this.delete(e.bufnr); - }, null, disposables); - } - get items() { - return Array.from(this.itemsMap.values()).map((x) => x.item); - } - getItem(bufnr) { - var _a2; - if (typeof bufnr === "number") { - return (_a2 = this.itemsMap.get(bufnr)) == null ? void 0 : _a2.item; - } - let o = Array.from(this.itemsMap.values()).find((v) => { - return v.uri == bufnr; - }); - return o ? o.item : void 0; - } - create(doc) { - if (!doc || doc.isCommandLine || !doc.attached) - return; - let o = this.itemsMap.get(doc.bufnr); - if (o) - o.item.dispose(); - let item = this._create(doc); - if (item) - this.itemsMap.set(doc.bufnr, { uri: doc.uri, item }); - } - onChange(e) { - let o = this.itemsMap.get(e.bufnr); - if (o && typeof o.item.onChange == "function") { - o.item.onChange(e); - } - } - delete(bufnr) { - let o = this.itemsMap.get(bufnr); - if (o) { - this.itemsMap.delete(bufnr); - o.item.dispose(); - } - } - reset() { - for (let o of this.itemsMap.values()) { - o.item.dispose(); - } - this.itemsMap.clear(); - } - dispose() { - disposeAll(this.disposables); - for (let o of this.itemsMap.values()) { - o.item.dispose(); - } - this.itemsMap.clear(); - } - }; - } -}); - -// src/util/match.ts -function score(selector, uri, languageId) { - if (Array.isArray(selector)) { - let ret = 0; - for (const filter of selector) { - const value = score(filter, uri, languageId); - if (value === 10) { - return value; - } - if (value > ret) { - ret = value; - } - } - return ret; - } else if (typeof selector === "string") { - if (selector === "*") { - return 5; - } else if (selector === languageId) { - return 10; - } else { - return 0; - } - } else if (selector) { - let u = URI.parse(uri); - const { language: language2, pattern, scheme } = selector; - let ret = 0; - if (scheme) { - if (scheme === u.scheme) { - ret = 5; - } else if (scheme === "*") { - ret = 3; - } else { - return 0; - } - } - if (language2) { - if (language2 === languageId) { - ret = 10; - } else if (language2 === "*") { - ret = Math.max(ret, 5); - } else { - return 0; - } - } - if (pattern) { - let caseInsensitive = isWindows2 || isMacintosh; - let p = caseInsensitive ? pattern.toLowerCase() : pattern; - let f = caseInsensitive ? u.fsPath.toLowerCase() : u.fsPath; - if (p === f || (0, import_minimatch3.default)(f, p, { dot: true })) { - ret = 5; - } else { - return 0; - } - } - return ret; - } else { - return 0; - } -} -var import_minimatch3; -var init_match = __esm({ - "src/util/match.ts"() { - import_minimatch3 = __toModule(require_minimatch()); - init_esm2(); - init_platform(); - } -}); - -// node_modules/node-int64/Int64.js -var require_Int64 = __commonJS({ - "node_modules/node-int64/Int64.js"(exports2, module2) { - var VAL32 = 4294967296; - var _HEX = []; - for (var i = 0; i < 256; i++) { - _HEX[i] = (i > 15 ? "" : "0") + i.toString(16); - } - var Int64 = module2.exports = function(a1, a2) { - if (a1 instanceof Buffer) { - this.buffer = a1; - this.offset = a2 || 0; - } else if (Object.prototype.toString.call(a1) == "[object Uint8Array]") { - this.buffer = new Buffer(a1); - this.offset = a2 || 0; - } else { - this.buffer = this.buffer || new Buffer(8); - this.offset = 0; - this.setValue.apply(this, arguments); - } - }; - Int64.MAX_INT = Math.pow(2, 53); - Int64.MIN_INT = -Math.pow(2, 53); - Int64.prototype = { - constructor: Int64, - _2scomp: function() { - var b = this.buffer, o = this.offset, carry = 1; - for (var i2 = o + 7; i2 >= o; i2--) { - var v = (b[i2] ^ 255) + carry; - b[i2] = v & 255; - carry = v >> 8; - } - }, - setValue: function(hi, lo) { - var negate = false; - if (arguments.length == 1) { - if (typeof hi == "number") { - negate = hi < 0; - hi = Math.abs(hi); - lo = hi % VAL32; - hi = hi / VAL32; - if (hi > VAL32) - throw new RangeError(hi + " is outside Int64 range"); - hi = hi | 0; - } else if (typeof hi == "string") { - hi = (hi + "").replace(/^0x/, ""); - lo = hi.substr(-8); - hi = hi.length > 8 ? hi.substr(0, hi.length - 8) : ""; - hi = parseInt(hi, 16); - lo = parseInt(lo, 16); - } else { - throw new Error(hi + " must be a Number or String"); - } - } - var b = this.buffer, o = this.offset; - for (var i2 = 7; i2 >= 0; i2--) { - b[o + i2] = lo & 255; - lo = i2 == 4 ? hi : lo >>> 8; - } - if (negate) - this._2scomp(); - }, - toNumber: function(allowImprecise) { - var b = this.buffer, o = this.offset; - var negate = b[o] & 128, x = 0, carry = 1; - for (var i2 = 7, m = 1; i2 >= 0; i2--, m *= 256) { - var v = b[o + i2]; - if (negate) { - v = (v ^ 255) + carry; - carry = v >> 8; - v = v & 255; - } - x += v * m; - } - if (!allowImprecise && x >= Int64.MAX_INT) { - return negate ? -Infinity : Infinity; - } - return negate ? -x : x; - }, - valueOf: function() { - return this.toNumber(false); - }, - toString: function(radix) { - return this.valueOf().toString(radix || 10); - }, - toOctetString: function(sep) { - var out = new Array(8); - var b = this.buffer, o = this.offset; - for (var i2 = 0; i2 < 8; i2++) { - out[i2] = _HEX[b[o + i2]]; - } - return out.join(sep || ""); - }, - toBuffer: function(rawBuffer) { - if (rawBuffer && this.offset === 0) - return this.buffer; - var out = new Buffer(8); - this.buffer.copy(out, 0, this.offset, this.offset + 8); - return out; - }, - copy: function(targetBuffer, targetOffset) { - this.buffer.copy(targetBuffer, targetOffset || 0, this.offset, this.offset + 8); - }, - compare: function(other) { - if ((this.buffer[this.offset] & 128) != (other.buffer[other.offset] & 128)) { - return other.buffer[other.offset] - this.buffer[this.offset]; - } - for (var i2 = 0; i2 < 8; i2++) { - if (this.buffer[this.offset + i2] !== other.buffer[other.offset + i2]) { - return this.buffer[this.offset + i2] - other.buffer[other.offset + i2]; - } - } - return 0; - }, - equals: function(other) { - return this.compare(other) === 0; - }, - inspect: function() { - return "[Int64 value:" + this + " octets:" + this.toOctetString(" ") + "]"; - } - }; - } -}); - -// node_modules/bser/index.js -var require_bser = __commonJS({ - "node_modules/bser/index.js"(exports2) { - var EE = require("events").EventEmitter; - var util4 = require("util"); - var os10 = require("os"); - var assert = require("assert"); - var Int64 = require_Int64(); - var isBigEndian = os10.endianness() == "BE"; - function nextPow2(size) { - return Math.pow(2, Math.ceil(Math.log(size) / Math.LN2)); - } - function Accumulator(initsize) { - this.buf = Buffer.alloc(nextPow2(initsize || 8192)); - this.readOffset = 0; - this.writeOffset = 0; - } - exports2.Accumulator = Accumulator; - Accumulator.prototype.writeAvail = function() { - return this.buf.length - this.writeOffset; - }; - Accumulator.prototype.readAvail = function() { - return this.writeOffset - this.readOffset; - }; - Accumulator.prototype.reserve = function(size) { - if (size < this.writeAvail()) { - return; - } - if (this.readOffset > 0) { - this.buf.copy(this.buf, 0, this.readOffset, this.writeOffset); - this.writeOffset -= this.readOffset; - this.readOffset = 0; - } - if (size < this.writeAvail()) { - return; - } - var buf = Buffer.alloc(nextPow2(this.buf.length + size - this.writeAvail())); - this.buf.copy(buf); - this.buf = buf; - }; - Accumulator.prototype.append = function(buf) { - if (Buffer.isBuffer(buf)) { - this.reserve(buf.length); - buf.copy(this.buf, this.writeOffset, 0, buf.length); - this.writeOffset += buf.length; - } else { - var size = Buffer.byteLength(buf); - this.reserve(size); - this.buf.write(buf, this.writeOffset); - this.writeOffset += size; - } - }; - Accumulator.prototype.assertReadableSize = function(size) { - if (this.readAvail() < size) { - throw new Error("wanted to read " + size + " bytes but only have " + this.readAvail()); - } - }; - Accumulator.prototype.peekString = function(size) { - this.assertReadableSize(size); - return this.buf.toString("utf-8", this.readOffset, this.readOffset + size); - }; - Accumulator.prototype.readString = function(size) { - var str = this.peekString(size); - this.readOffset += size; - return str; - }; - Accumulator.prototype.peekInt = function(size) { - this.assertReadableSize(size); - switch (size) { - case 1: - return this.buf.readInt8(this.readOffset, size); - case 2: - return isBigEndian ? this.buf.readInt16BE(this.readOffset, size) : this.buf.readInt16LE(this.readOffset, size); - case 4: - return isBigEndian ? this.buf.readInt32BE(this.readOffset, size) : this.buf.readInt32LE(this.readOffset, size); - case 8: - var big = this.buf.slice(this.readOffset, this.readOffset + 8); - if (isBigEndian) { - return new Int64(big); - } - return new Int64(byteswap64(big)); - default: - throw new Error("invalid integer size " + size); - } - }; - Accumulator.prototype.readInt = function(bytes2) { - var ival = this.peekInt(bytes2); - if (ival instanceof Int64 && isFinite(ival.valueOf())) { - ival = ival.valueOf(); - } - this.readOffset += bytes2; - return ival; - }; - Accumulator.prototype.peekDouble = function() { - this.assertReadableSize(8); - return isBigEndian ? this.buf.readDoubleBE(this.readOffset) : this.buf.readDoubleLE(this.readOffset); - }; - Accumulator.prototype.readDouble = function() { - var dval = this.peekDouble(); - this.readOffset += 8; - return dval; - }; - Accumulator.prototype.readAdvance = function(size) { - if (size > 0) { - this.assertReadableSize(size); - } else if (size < 0 && this.readOffset + size < 0) { - throw new Error("advance with negative offset " + size + " would seek off the start of the buffer"); - } - this.readOffset += size; - }; - Accumulator.prototype.writeByte = function(value) { - this.reserve(1); - this.buf.writeInt8(value, this.writeOffset); - ++this.writeOffset; - }; - Accumulator.prototype.writeInt = function(value, size) { - this.reserve(size); - switch (size) { - case 1: - this.buf.writeInt8(value, this.writeOffset); - break; - case 2: - if (isBigEndian) { - this.buf.writeInt16BE(value, this.writeOffset); - } else { - this.buf.writeInt16LE(value, this.writeOffset); - } - break; - case 4: - if (isBigEndian) { - this.buf.writeInt32BE(value, this.writeOffset); - } else { - this.buf.writeInt32LE(value, this.writeOffset); - } - break; - default: - throw new Error("unsupported integer size " + size); - } - this.writeOffset += size; - }; - Accumulator.prototype.writeDouble = function(value) { - this.reserve(8); - if (isBigEndian) { - this.buf.writeDoubleBE(value, this.writeOffset); - } else { - this.buf.writeDoubleLE(value, this.writeOffset); - } - this.writeOffset += 8; - }; - var BSER_ARRAY = 0; - var BSER_OBJECT = 1; - var BSER_STRING = 2; - var BSER_INT8 = 3; - var BSER_INT16 = 4; - var BSER_INT32 = 5; - var BSER_INT64 = 6; - var BSER_REAL = 7; - var BSER_TRUE = 8; - var BSER_FALSE = 9; - var BSER_NULL = 10; - var BSER_TEMPLATE = 11; - var BSER_SKIP = 12; - var ST_NEED_PDU = 0; - var ST_FILL_PDU = 1; - var MAX_INT8 = 127; - var MAX_INT16 = 32767; - var MAX_INT32 = 2147483647; - function BunserBuf() { - EE.call(this); - this.buf = new Accumulator(); - this.state = ST_NEED_PDU; - } - util4.inherits(BunserBuf, EE); - exports2.BunserBuf = BunserBuf; - BunserBuf.prototype.append = function(buf, synchronous) { - if (synchronous) { - this.buf.append(buf); - return this.process(synchronous); - } - try { - this.buf.append(buf); - } catch (err) { - this.emit("error", err); - return; - } - this.processLater(); - }; - BunserBuf.prototype.processLater = function() { - var self2 = this; - process.nextTick(function() { - try { - self2.process(false); - } catch (err) { - self2.emit("error", err); - } - }); - }; - BunserBuf.prototype.process = function(synchronous) { - if (this.state == ST_NEED_PDU) { - if (this.buf.readAvail() < 2) { - return; - } - this.expectCode(0); - this.expectCode(1); - this.pduLen = this.decodeInt(true); - if (this.pduLen === false) { - this.buf.readAdvance(-2); - return; - } - this.buf.reserve(this.pduLen); - this.state = ST_FILL_PDU; - } - if (this.state == ST_FILL_PDU) { - if (this.buf.readAvail() < this.pduLen) { - return; - } - var val = this.decodeAny(); - if (synchronous) { - return val; - } - this.emit("value", val); - this.state = ST_NEED_PDU; - } - if (!synchronous && this.buf.readAvail() > 0) { - this.processLater(); - } - }; - BunserBuf.prototype.raise = function(reason) { - throw new Error(reason + ", in Buffer of length " + this.buf.buf.length + " (" + this.buf.readAvail() + " readable) at offset " + this.buf.readOffset + " buffer: " + JSON.stringify(this.buf.buf.slice(this.buf.readOffset, this.buf.readOffset + 32).toJSON())); - }; - BunserBuf.prototype.expectCode = function(expected) { - var code = this.buf.readInt(1); - if (code != expected) { - this.raise("expected bser opcode " + expected + " but got " + code); - } - }; - BunserBuf.prototype.decodeAny = function() { - var code = this.buf.peekInt(1); - switch (code) { - case BSER_INT8: - case BSER_INT16: - case BSER_INT32: - case BSER_INT64: - return this.decodeInt(); - case BSER_REAL: - this.buf.readAdvance(1); - return this.buf.readDouble(); - case BSER_TRUE: - this.buf.readAdvance(1); - return true; - case BSER_FALSE: - this.buf.readAdvance(1); - return false; - case BSER_NULL: - this.buf.readAdvance(1); - return null; - case BSER_STRING: - return this.decodeString(); - case BSER_ARRAY: - return this.decodeArray(); - case BSER_OBJECT: - return this.decodeObject(); - case BSER_TEMPLATE: - return this.decodeTemplate(); - default: - this.raise("unhandled bser opcode " + code); - } - }; - BunserBuf.prototype.decodeArray = function() { - this.expectCode(BSER_ARRAY); - var nitems = this.decodeInt(); - var arr = []; - for (var i = 0; i < nitems; ++i) { - arr.push(this.decodeAny()); - } - return arr; - }; - BunserBuf.prototype.decodeObject = function() { - this.expectCode(BSER_OBJECT); - var nitems = this.decodeInt(); - var res = {}; - for (var i = 0; i < nitems; ++i) { - var key = this.decodeString(); - var val = this.decodeAny(); - res[key] = val; - } - return res; - }; - BunserBuf.prototype.decodeTemplate = function() { - this.expectCode(BSER_TEMPLATE); - var keys = this.decodeArray(); - var nitems = this.decodeInt(); - var arr = []; - for (var i = 0; i < nitems; ++i) { - var obj = {}; - for (var keyidx = 0; keyidx < keys.length; ++keyidx) { - if (this.buf.peekInt(1) == BSER_SKIP) { - this.buf.readAdvance(1); - continue; - } - var val = this.decodeAny(); - obj[keys[keyidx]] = val; - } - arr.push(obj); - } - return arr; - }; - BunserBuf.prototype.decodeString = function() { - this.expectCode(BSER_STRING); - var len = this.decodeInt(); - return this.buf.readString(len); - }; - BunserBuf.prototype.decodeInt = function(relaxSizeAsserts) { - if (relaxSizeAsserts && this.buf.readAvail() < 1) { - return false; - } else { - this.buf.assertReadableSize(1); - } - var code = this.buf.peekInt(1); - var size = 0; - switch (code) { - case BSER_INT8: - size = 1; - break; - case BSER_INT16: - size = 2; - break; - case BSER_INT32: - size = 4; - break; - case BSER_INT64: - size = 8; - break; - default: - this.raise("invalid bser int encoding " + code); - } - if (relaxSizeAsserts && this.buf.readAvail() < 1 + size) { - return false; - } - this.buf.readAdvance(1); - return this.buf.readInt(size); - }; - function loadFromBuffer(input) { - var buf = new BunserBuf(); - var result = buf.append(input, true); - if (buf.buf.readAvail()) { - throw Error("excess data found after input buffer, use BunserBuf instead"); - } - if (typeof result === "undefined") { - throw Error("no bser found in string and no error raised!?"); - } - return result; - } - exports2.loadFromBuffer = loadFromBuffer; - function byteswap64(buf) { - var swap = Buffer.alloc(buf.length); - for (var i = 0; i < buf.length; i++) { - swap[i] = buf[buf.length - 1 - i]; - } - return swap; - } - function dump_int64(buf, val) { - var be = val.toBuffer(); - if (isBigEndian) { - buf.writeByte(BSER_INT64); - buf.append(be); - return; - } - var le = byteswap64(be); - buf.writeByte(BSER_INT64); - buf.append(le); - } - function dump_int(buf, val) { - var abs = Math.abs(val); - if (abs <= MAX_INT8) { - buf.writeByte(BSER_INT8); - buf.writeInt(val, 1); - } else if (abs <= MAX_INT16) { - buf.writeByte(BSER_INT16); - buf.writeInt(val, 2); - } else if (abs <= MAX_INT32) { - buf.writeByte(BSER_INT32); - buf.writeInt(val, 4); - } else { - dump_int64(buf, new Int64(val)); - } - } - function dump_any(buf, val) { - switch (typeof val) { - case "number": - if (isFinite(val) && Math.floor(val) === val) { - dump_int(buf, val); - } else { - buf.writeByte(BSER_REAL); - buf.writeDouble(val); - } - return; - case "string": - buf.writeByte(BSER_STRING); - dump_int(buf, Buffer.byteLength(val)); - buf.append(val); - return; - case "boolean": - buf.writeByte(val ? BSER_TRUE : BSER_FALSE); - return; - case "object": - if (val === null) { - buf.writeByte(BSER_NULL); - return; - } - if (val instanceof Int64) { - dump_int64(buf, val); - return; - } - if (Array.isArray(val)) { - buf.writeByte(BSER_ARRAY); - dump_int(buf, val.length); - for (var i = 0; i < val.length; ++i) { - dump_any(buf, val[i]); - } - return; - } - buf.writeByte(BSER_OBJECT); - var keys = Object.keys(val); - var num_keys = keys.length; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var v = val[key]; - if (typeof v == "undefined") { - num_keys--; - } - } - dump_int(buf, num_keys); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var v = val[key]; - if (typeof v == "undefined") { - continue; - } - dump_any(buf, key); - try { - dump_any(buf, v); - } catch (e) { - throw new Error(e.message + " (while serializing object property with name `" + key + "')"); - } - } - return; - default: - throw new Error("cannot serialize type " + typeof val + " to BSER"); - } - } - function dumpToBuffer(val) { - var buf = new Accumulator(); - buf.writeByte(0); - buf.writeByte(1); - buf.writeByte(BSER_INT32); - buf.writeInt(0, 4); - dump_any(buf, val); - var off = buf.writeOffset; - var len = off - 7; - buf.writeOffset = 3; - buf.writeInt(len, 4); - buf.writeOffset = off; - return buf.buf.slice(0, off); - } - exports2.dumpToBuffer = dumpToBuffer; - } -}); - -// node_modules/fb-watchman/index.js -var require_fb_watchman = __commonJS({ - "node_modules/fb-watchman/index.js"(exports2, module2) { - "use strict"; - var net3 = require("net"); - var EE = require("events").EventEmitter; - var util4 = require("util"); - var childProcess = require("child_process"); - var bser = require_bser(); - var unilateralTags = ["subscription", "log"]; - function Client2(options) { - var self2 = this; - EE.call(this); - this.watchmanBinaryPath = "watchman"; - if (options && options.watchmanBinaryPath) { - this.watchmanBinaryPath = options.watchmanBinaryPath.trim(); - } - ; - this.commands = []; - } - util4.inherits(Client2, EE); - module2.exports.Client = Client2; - Client2.prototype.sendNextCommand = function() { - if (this.currentCommand) { - return; - } - this.currentCommand = this.commands.shift(); - if (!this.currentCommand) { - return; - } - this.socket.write(bser.dumpToBuffer(this.currentCommand.cmd)); - }; - Client2.prototype.cancelCommands = function(why) { - var error = new Error(why); - var cmds = this.commands; - this.commands = []; - if (this.currentCommand) { - cmds.unshift(this.currentCommand); - this.currentCommand = null; - } - cmds.forEach(function(cmd) { - cmd.cb(error); - }); - }; - Client2.prototype.connect = function() { - var self2 = this; - function makeSock(sockname) { - self2.bunser = new bser.BunserBuf(); - self2.bunser.on("value", function(obj) { - var unilateral = false; - for (var i = 0; i < unilateralTags.length; i++) { - var tag = unilateralTags[i]; - if (tag in obj) { - unilateral = tag; - } - } - if (unilateral) { - self2.emit(unilateral, obj); - } else if (self2.currentCommand) { - var cmd = self2.currentCommand; - self2.currentCommand = null; - if ("error" in obj) { - var error = new Error(obj.error); - error.watchmanResponse = obj; - cmd.cb(error); - } else { - cmd.cb(null, obj); - } - } - self2.sendNextCommand(); - }); - self2.bunser.on("error", function(err) { - self2.emit("error", err); - }); - self2.socket = net3.createConnection(sockname); - self2.socket.on("connect", function() { - self2.connecting = false; - self2.emit("connect"); - self2.sendNextCommand(); - }); - self2.socket.on("error", function(err) { - self2.connecting = false; - self2.emit("error", err); - }); - self2.socket.on("data", function(buf) { - if (self2.bunser) { - self2.bunser.append(buf); - } - }); - self2.socket.on("end", function() { - self2.socket = null; - self2.bunser = null; - self2.cancelCommands("The watchman connection was closed"); - self2.emit("end"); - }); - } - if (process.env.WATCHMAN_SOCK) { - makeSock(process.env.WATCHMAN_SOCK); - return; - } - var args = ["--no-pretty", "get-sockname"]; - var proc = null; - var spawnFailed = false; - function spawnError(error) { - if (spawnFailed) { - return; - } - spawnFailed = true; - if (error.errno === "EACCES") { - error.message = "The Watchman CLI is installed but cannot be spawned because of a permission problem"; - } else if (error.errno === "ENOENT") { - error.message = "Watchman was not found in PATH. See https://facebook.github.io/watchman/docs/install.html for installation instructions"; - } - console.error("Watchman: ", error.message); - self2.emit("error", error); - } - try { - proc = childProcess.spawn(this.watchmanBinaryPath, args, { - stdio: ["ignore", "pipe", "pipe"] - }); - } catch (error) { - spawnError(error); - return; - } - var stdout = []; - var stderr = []; - proc.stdout.on("data", function(data) { - stdout.push(data); - }); - proc.stderr.on("data", function(data) { - data = data.toString("utf8"); - stderr.push(data); - console.error(data); - }); - proc.on("error", function(error) { - spawnError(error); - }); - proc.on("close", function(code, signal) { - if (code !== 0) { - spawnError(new Error(self2.watchmanBinaryPath + " " + args.join(" ") + " returned with exit code=" + code + ", signal=" + signal + ", stderr= " + stderr.join(""))); - return; - } - try { - var obj = JSON.parse(stdout.join("")); - if ("error" in obj) { - var error = new Error(obj.error); - error.watchmanResponse = obj; - self2.emit("error", error); - return; - } - makeSock(obj.sockname); - } catch (e) { - self2.emit("error", e); - } - }); - }; - Client2.prototype.command = function(args, done) { - done = done || function() { - }; - this.commands.push({ cmd: args, cb: done }); - if (!this.socket) { - if (!this.connecting) { - this.connecting = true; - this.connect(); - return; - } - return; - } - this.sendNextCommand(); - }; - var cap_versions = { - "cmd-watch-del-all": "3.1.1", - "cmd-watch-project": "3.1", - "relative_root": "3.3", - "term-dirname": "3.1", - "term-idirname": "3.1", - "wildmatch": "3.7" - }; - function vers_compare(a, b) { - a = a.split("."); - b = b.split("."); - for (var i = 0; i < 3; i++) { - var d = parseInt(a[i] || "0") - parseInt(b[i] || "0"); - if (d != 0) { - return d; - } - } - return 0; - } - function have_cap(vers, name2) { - if (name2 in cap_versions) { - return vers_compare(vers, cap_versions[name2]) >= 0; - } - return false; - } - Client2.prototype._synthesizeCapabilityCheck = function(resp, optional, required) { - resp.capabilities = {}; - var version2 = resp.version; - optional.forEach(function(name2) { - resp.capabilities[name2] = have_cap(version2, name2); - }); - required.forEach(function(name2) { - var have = have_cap(version2, name2); - resp.capabilities[name2] = have; - if (!have) { - resp.error = "client required capability `" + name2 + "` is not supported by this server"; - } - }); - return resp; - }; - Client2.prototype.capabilityCheck = function(caps, done) { - var optional = caps.optional || []; - var required = caps.required || []; - var self2 = this; - this.command(["version", { - optional, - required - }], function(error, resp) { - if (error) { - done(error); - return; - } - if (!("capabilities" in resp)) { - resp = self2._synthesizeCapabilityCheck(resp, optional, required); - if (resp.error) { - error = new Error(resp.error); - error.watchmanResponse = resp; - done(error); - return; - } - } - done(null, resp); - }); - }; - Client2.prototype.end = function() { - this.cancelCommands("The client was ended"); - if (this.socket) { - this.socket.end(); - this.socket = null; - } - this.bunser = null; - }; - } -}); - -// src/watchman.ts -function isValidWatchRoot(root) { - if (root == "/" || root == "/tmp" || root == "/private/tmp") - return false; - if (root.toLowerCase() === import_os3.default.homedir().toLowerCase()) - return false; - if (import_path10.default.parse(root).base == root) - return false; - if (root.startsWith("/tmp/") || root.startsWith("/private/tmp/")) - return false; - if (isParentFolder(import_os3.default.tmpdir(), root, true)) - return false; - return true; -} -var import_fb_watchman, import_os3, import_path10, import_vscode_languageserver_protocol12, import_minimatch4, logger24, requiredCapabilities, clientsMap, Watchman; -var init_watchman = __esm({ - "src/watchman.ts"() { - import_fb_watchman = __toModule(require_fb_watchman()); - import_os3 = __toModule(require("os")); - import_path10 = __toModule(require("path")); - init_esm_node(); - import_vscode_languageserver_protocol12 = __toModule(require_main2()); - import_minimatch4 = __toModule(require_minimatch()); - init_fs(); - logger24 = require_logger2()("watchman"); - requiredCapabilities = ["relative_root", "cmd-watch-project", "wildmatch", "field-new"]; - clientsMap = new Map(); - Watchman = class { - constructor(binaryPath, channel) { - this.channel = channel; - this._disposed = false; - this.client = new import_fb_watchman.default.Client({ - watchmanBinaryPath: binaryPath - }); - this.client.setMaxListeners(300); - } - checkCapability() { - let { client } = this; - return new Promise((resolve3, reject) => { - client.capabilityCheck({ - optional: [], - required: requiredCapabilities - }, (error, resp) => { - if (error) - return reject(error); - let { capabilities } = resp; - for (let key of Object.keys(capabilities)) { - if (!capabilities[key]) - return resolve3(false); - } - resolve3(true); - }); - }); - } - async watchProject(root) { - try { - let resp = await this.command(["watch-project", root]); - let { watch, warning, relative_path } = resp; - if (warning) - logger24.warn(warning); - this.watch = watch; - this.relative_path = relative_path; - logger24.info(`watchman watching project: ${root}`); - this.appendOutput(`watchman watching project: ${root}`); - } catch (e) { - logger24.error(e); - return false; - } - return true; - } - command(args) { - return new Promise((resolve3, reject) => { - this.client.command(args, (error, resp) => { - if (error) - return reject(error); - resolve3(resp); - }); - }); - } - async subscribe(globPattern, cb) { - let { watch, relative_path } = this; - if (!watch) { - this.appendOutput(`watchman not watching: ${watch}`, "Error"); - return null; - } - let { clock } = await this.command(["clock", watch]); - let uid = v1_default(); - let sub = { - expression: ["allof", ["match", "**/*", "wholename"]], - fields: ["name", "size", "new", "exists", "type", "mtime_ms", "ctime_ms"], - since: clock - }; - let root = watch; - if (relative_path) { - sub.relative_root = relative_path; - root = import_path10.default.join(watch, relative_path); - } - let { subscribe } = await this.command(["subscribe", watch, uid, sub]); - if (global.hasOwnProperty("__TEST__")) - global.subscribe = subscribe; - this.appendOutput(`subscribing "${globPattern}" in ${root}`); - this.client.on("subscription", (resp) => { - if (!resp || resp.subscription != uid) - return; - let { files } = resp; - if (!files) - return; - files = files.filter((f) => f.type == "f" && (0, import_minimatch4.default)(f.name, globPattern, { dot: true })); - if (!files.length) - return; - let ev = Object.assign({}, resp); - if (this.relative_path) - ev.root = import_path10.default.resolve(resp.root, this.relative_path); - this.appendOutput(`file change detected: ${JSON.stringify(ev, null, 2)}`); - cb(ev); - }); - return import_vscode_languageserver_protocol12.Disposable.create(() => this.unsubscribe(subscribe)); - } - unsubscribe(subscription) { - if (this._disposed) - return Promise.resolve(); - let { watch } = this; - if (!watch) - return; - this.appendOutput(`unsubscribe "${subscription}" in: ${watch}`); - return this.command(["unsubscribe", watch, subscription]).catch((e) => { - logger24.error(e); - }); - } - dispose() { - if (this._disposed) - return; - this._disposed = true; - this.client.removeAllListeners(); - this.client.end(); - } - appendOutput(message, type = "Info") { - if (this.channel) { - this.channel.appendLine(`[${type} - ${new Date().toLocaleTimeString()}] ${message}`); - } - } - static dispose() { - for (let promise of clientsMap.values()) { - promise.then((client) => { - client.dispose(); - }, (_e) => { - }); - } - } - static createClient(binaryPath, root, channel) { - if (!isValidWatchRoot(root)) - return null; - let client = clientsMap.get(root); - if (client) - return client; - let promise = new Promise(async (resolve3, reject) => { - try { - let watchman2 = new Watchman(binaryPath, channel); - let valid = await watchman2.checkCapability(); - if (!valid) - return resolve3(null); - let watching = await watchman2.watchProject(root); - if (!watching) - return resolve3(null); - resolve3(watchman2); - } catch (e) { - reject(e); - } - }); - clientsMap.set(root, promise); - return promise; - } - }; - } -}); - -// package.json -var version; -var init_package = __esm({ - "package.json"() { - version = "0.0.80"; - } -}); - -// src/workspace.ts -var import_bytes, import_fast_diff2, import_fs_extra4, import_os4, import_path11, import_vscode_languageserver_protocol13, import_which2, APIVERSION, logger25, NAME_SPACE, methods, Workspace, workspace_default; -var init_workspace = __esm({ - "src/workspace.ts"() { - import_bytes = __toModule(require_bytes()); - import_fast_diff2 = __toModule(require_diff()); - import_fs_extra4 = __toModule(require_lib5()); - import_os4 = __toModule(require("os")); - import_path11 = __toModule(require("path")); - init_esm_node(); - import_vscode_languageserver_protocol13 = __toModule(require_main2()); - init_esm2(); - import_which2 = __toModule(require_which()); - init_channels(); - init_configuration2(); - init_shape(); - init_events(); - init_db(); - init_document(); - init_fileSystemWatcher(); - init_mru(); - init_resolver(); - init_task(); - init_terminal(); - init_bufferSync(); - init_types(); - init_array(); - init_fs(); - init_util(); - init_match(); - init_position(); - init_string(); - init_watchman(); - init_window(); - init_package(); - APIVERSION = 10; - logger25 = require_logger2()("workspace"); - NAME_SPACE = 2e3; - methods = [ - "showMessage", - "runTerminalCommand", - "openTerminal", - "showQuickpick", - "menuPick", - "openLocalConfig", - "showPrompt", - "createStatusBarItem", - "createOutputChannel", - "showOutputChannel", - "requestInput", - "echoLines", - "getCursorPosition", - "moveTo", - "getOffset" - ]; - Workspace = class { - constructor() { - this.keymaps = new Map(); - this.resolver = new Resolver(); - this.rootPatterns = new Map(); - this._workspaceFolders = []; - this._insertMode = false; - this._cwd = process.cwd(); - this._initialized = false; - this._attached = false; - this.buffers = new Map(); - this.autocmdMaxId = 0; - this.autocmds = new Map(); - this.terminals = new Map(); - this.creatingSources = new Map(); - this.schemeProviderMap = new Map(); - this.namespaceMap = new Map(); - this.disposables = []; - this.watchedOptions = new Set(); - this._dynAutocmd = false; - this._disposed = false; - this._onDidOpenDocument = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidCloseDocument = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidChangeDocument = new import_vscode_languageserver_protocol13.Emitter(); - this._onWillSaveDocument = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidSaveDocument = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidChangeWorkspaceFolders = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidChangeConfiguration = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidWorkspaceInitialized = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidOpenTerminal = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidCloseTerminal = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidRuntimePathChange = new import_vscode_languageserver_protocol13.Emitter(); - this.onDidCloseTerminal = this._onDidCloseTerminal.event; - this.onDidOpenTerminal = this._onDidOpenTerminal.event; - this.onDidChangeWorkspaceFolders = this._onDidChangeWorkspaceFolders.event; - this.onDidOpenTextDocument = this._onDidOpenDocument.event; - this.onDidCloseTextDocument = this._onDidCloseDocument.event; - this.onDidChangeTextDocument = this._onDidChangeDocument.event; - this.onWillSaveTextDocument = this._onWillSaveDocument.event; - this.onDidSaveTextDocument = this._onDidSaveDocument.event; - this.onDidChangeConfiguration = this._onDidChangeConfiguration.event; - this.onDidWorkspaceInitialized = this._onDidWorkspaceInitialized.event; - this.onDidRuntimePathChange = this._onDidRuntimePathChange.event; - this._onDidCreateFiles = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidRenameFiles = new import_vscode_languageserver_protocol13.Emitter(); - this._onDidDeleteFiles = new import_vscode_languageserver_protocol13.Emitter(); - this._onWillCreateFiles = new import_vscode_languageserver_protocol13.Emitter(); - this._onWillRenameFiles = new import_vscode_languageserver_protocol13.Emitter(); - this._onWillDeleteFiles = new import_vscode_languageserver_protocol13.Emitter(); - this.onDidCreateFiles = this._onDidCreateFiles.event; - this.onDidRenameFiles = this._onDidRenameFiles.event; - this.onDidDeleteFiles = this._onDidDeleteFiles.event; - this.onWillCreateFiles = this._onWillCreateFiles.event; - this.onWillRenameFiles = this._onWillRenameFiles.event; - this.onWillDeleteFiles = this._onWillDeleteFiles.event; - this.version = version; - this.configurations = this.createConfigurations(); - let cwd = process.cwd(); - if (cwd != import_os4.default.homedir() && inDirectory(cwd, [".vim"])) { - this._workspaceFolders.push({ - uri: URI.file(cwd).toString(), - name: import_path11.default.basename(cwd) - }); - } - } - async init() { - let { nvim } = this; - for (let method of methods) { - Object.defineProperty(this, method, { - get: () => { - return (...args) => { - return window_default[method].apply(window_default, args); - }; - } - }); - } - this._env = await nvim.call("coc#util#vim_info"); - if (this._env.apiversion != APIVERSION) { - console.error(`API version ${this._env.apiversion} is not ${APIVERSION}, please build coc.nvim by 'yarn install' after pull source code.`); - process.exit(); - } - this._insertMode = this._env.mode.startsWith("insert"); - if (this._env.workspaceFolders && Array.isArray(this._env.workspaceFolders)) { - this._workspaceFolders = this._env.workspaceFolders.map((f) => ({ - uri: URI.file(f).toString(), - name: import_path11.default.dirname(f) - })); - } - this.configurations.updateUserConfig(this._env.config); - let preferences = this.getConfiguration("coc.preferences"); - let maxFileSize = preferences.get("maxFileSize", "10MB"); - this.maxFileSize = import_bytes.default.parse(maxFileSize); - events_default.on(["InsertEnter", "CursorMovedI"], () => { - this._insertMode = true; - }, null, this.disposables); - events_default.on(["InsertLeave", "CursorMoved"], () => { - this._insertMode = false; - }, null, this.disposables); - events_default.on("BufEnter", this.onBufEnter, this, this.disposables); - events_default.on("CursorMoved", this.checkCurrentBuffer, this, this.disposables); - events_default.on("CursorMovedI", this.checkCurrentBuffer, this, this.disposables); - events_default.on("DirChanged", this.onDirChanged, this, this.disposables); - events_default.on("BufCreate", this.onBufCreate, this, this.disposables); - events_default.on("BufUnload", this.onBufUnload, this, this.disposables); - events_default.on("TermOpen", this.onBufCreate, this, this.disposables); - events_default.on("TermClose", this.onBufUnload, this, this.disposables); - events_default.on("BufWritePost", this.onBufWritePost, this, this.disposables); - events_default.on("BufWritePre", this.onBufWritePre, this, this.disposables); - events_default.on("FileType", this.onFileTypeChange, this, this.disposables); - events_default.on("CursorHold", this.checkCurrentBuffer, this, this.disposables); - events_default.on("TextChanged", this.checkBuffer, this, this.disposables); - events_default.on("BufReadCmd", this.onBufReadCmd, this, this.disposables); - events_default.on("VimResized", (columns, lines) => { - Object.assign(this._env, { columns, lines }); - }, null, this.disposables); - await this.attach(); - this.attachChangedEvents(); - this.configurations.onDidChange((e) => { - this._onDidChangeConfiguration.fire(e); - }, null, this.disposables); - this.watchOption("runtimepath", (oldValue, newValue) => { - let result = (0, import_fast_diff2.default)(oldValue, newValue); - for (let [changeType, value] of result) { - if (changeType == 1) { - let paths = value.replace(/,$/, "").split(","); - this._onDidRuntimePathChange.fire(paths); - } - } - this._env.runtimepath = newValue; - }, this.disposables); - this.watchGlobal("coc_sources_disable_map", async (_, newValue) => { - this.env.disabledSources = newValue; - }); - this.disposables.push(this.registerTextDocumentContentProvider("output", channels_default.getProvider(nvim))); - } - getConfigFile(target) { - return this.configurations.getConfigFile(target); - } - registerAutocmd(autocmd) { - this.autocmdMaxId += 1; - let id = this.autocmdMaxId; - this.autocmds.set(id, autocmd); - this.setupDynamicAutocmd(); - return import_vscode_languageserver_protocol13.Disposable.create(() => { - this.autocmds.delete(id); - this.setupDynamicAutocmd(); - }); - } - watchOption(key, callback, disposables) { - let watching = this.watchedOptions.has(key); - if (!watching) { - this.watchedOptions.add(key); - this.setupDynamicAutocmd(); - } - let disposable = events_default.on("OptionSet", async (changed, oldValue, newValue) => { - if (changed == key && callback) { - await Promise.resolve(callback(oldValue, newValue)); - } - }); - if (disposables) { - disposables.push(import_vscode_languageserver_protocol13.Disposable.create(() => { - disposable.dispose(); - if (watching) - return; - this.watchedOptions.delete(key); - this.setupDynamicAutocmd(); - })); - } - } - watchGlobal(key, callback, disposables) { - let { nvim } = this; - nvim.call("coc#_watch", key, true); - let disposable = events_default.on("GlobalChange", async (changed, oldValue, newValue) => { - if (changed == key && callback) { - await Promise.resolve(callback(oldValue, newValue)); - } - }); - if (disposables) { - disposables.push(import_vscode_languageserver_protocol13.Disposable.create(() => { - disposable.dispose(); - nvim.call("coc#_unwatch", key, true); - })); - } - } - get cwd() { - return this._cwd; - } - get env() { - return this._env; - } - get root() { - return this._root || this.cwd; - } - get rootPath() { - return this.root; - } - get workspaceFolders() { - return this._workspaceFolders; - } - get uri() { - let { bufnr } = this; - if (bufnr) { - let document2 = this.getDocument(bufnr); - if (document2 && document2.schema == "file") { - return document2.uri; - } - } - return null; - } - get workspaceFolder() { - let { rootPath } = this; - if (rootPath == import_os4.default.homedir()) - return null; - return { - uri: URI.file(rootPath).toString(), - name: import_path11.default.basename(rootPath) - }; - } - get textDocuments() { - let docs = []; - for (let b of this.buffers.values()) { - docs.push(b.textDocument); - } - return docs; - } - get documents() { - return Array.from(this.buffers.values()); - } - createNameSpace(name2 = "") { - if (this.namespaceMap.has(name2)) - return this.namespaceMap.get(name2); - NAME_SPACE = NAME_SPACE + 1; - this.namespaceMap.set(name2, NAME_SPACE); - return NAME_SPACE; - } - get channelNames() { - return channels_default.names; - } - get pluginRoot() { - return import_path11.default.dirname(__dirname); - } - get isVim() { - return this._env.isVim; - } - get isNvim() { - return !this._env.isVim; - } - get completeOpt() { - return this._env.completeOpt; - } - get initialized() { - return this._initialized; - } - get ready() { - if (this._initialized) - return Promise.resolve(); - return new Promise((resolve3) => { - let disposable = this.onDidWorkspaceInitialized(() => { - disposable.dispose(); - resolve3(); - }); - }); - } - get filetypes() { - let res = new Set(); - for (let doc of this.documents) { - res.add(doc.filetype); - } - return res; - } - match(selector, document2) { - return score(selector, document2.uri, document2.languageId); - } - async findUp(filename) { - let { cwd } = this; - let filepath = await this.nvim.call("expand", "%:p"); - filepath = import_path11.default.normalize(filepath); - let isFile2 = filepath && import_path11.default.isAbsolute(filepath); - if (isFile2 && !isParentFolder(cwd, filepath, true)) { - return findUp(filename, import_path11.default.dirname(filepath)); - } - let res = findUp(filename, cwd); - if (res && res != import_os4.default.homedir()) - return res; - if (isFile2) - return findUp(filename, import_path11.default.dirname(filepath)); - return null; - } - async resolveRootFolder(uri, patterns) { - let { cwd } = this; - if (uri.scheme != "file") - return cwd; - let filepath = import_path11.default.normalize(uri.fsPath); - let dir = import_path11.default.dirname(filepath); - return resolveRoot(dir, patterns) || dir; - } - createFileSystemWatcher(globPattern, ignoreCreate, ignoreChange, ignoreDelete) { - let watchmanPath = global.hasOwnProperty("__TEST__") ? null : this.getWatchmanPath(); - let channel = watchmanPath ? window_default.createOutputChannel("watchman") : null; - let promise = watchmanPath ? Watchman.createClient(watchmanPath, this.root, channel) : Promise.resolve(null); - let watcher = new FileSystemWatcher(promise, globPattern, !!ignoreCreate, !!ignoreChange, !!ignoreDelete); - return watcher; - } - getWatchmanPath() { - const preferences = this.getConfiguration("coc.preferences"); - let watchmanPath = preferences.get("watchmanPath", "watchman"); - try { - return import_which2.default.sync(watchmanPath); - } catch (e) { - return null; - } - } - getConfiguration(section2, resource) { - return this.configurations.getConfiguration(section2, resource); - } - getDocument(uri) { - if (typeof uri === "number") { - return this.buffers.get(uri); - } - const caseInsensitive = platform_exports.isWindows || platform_exports.isMacintosh; - uri = URI.parse(uri).toString(); - for (let doc of this.buffers.values()) { - if (!doc) - continue; - if (doc.uri === uri) - return doc; - if (import_path11.default.resolve(doc.uri) === import_path11.default.resolve(uri)) - return doc; - if (caseInsensitive && doc.uri.toLowerCase() === uri.toLowerCase()) - return doc; - } - return null; - } - async applyEdit(edit2) { - let { nvim } = this; - let { documentChanges, changes } = edit2; - let [bufnr, cursor] = await nvim.eval('[bufnr("%"),coc#cursor#position()]'); - let document2 = this.getDocument(bufnr); - let uri = document2 ? document2.uri : null; - let currEdits = null; - let locations = []; - let changeCount = 0; - const preferences = this.getConfiguration("coc.preferences"); - let promptUser = !global.hasOwnProperty("__TEST__") && preferences.get("promptWorkspaceEdit", true); - let listTarget = preferences.get("listOfWorkspaceEdit", "quickfix"); - try { - if (documentChanges && documentChanges.length) { - let changedUris = this.getChangedUris(documentChanges); - changeCount = changedUris.length; - if (promptUser) { - let diskCount = changedUris.reduce((p, c) => { - return p + (this.getDocument(c) == null ? 1 : 0); - }, 0); - if (diskCount) { - let res = await window_default.showPrompt(`${diskCount} documents on disk would be loaded for change, confirm?`); - if (!res) - return; - } - } - let changedMap = new Map(); - for (const change of documentChanges) { - if (import_vscode_languageserver_protocol13.TextDocumentEdit.is(change)) { - let { textDocument, edits } = change; - let doc = await this.loadFile(textDocument.uri); - if (textDocument.uri == uri) - currEdits = edits; - await doc.applyEdits(edits); - for (let edit3 of edits) { - locations.push({ uri: doc.uri, range: edit3.range }); - } - } else if (import_vscode_languageserver_protocol13.CreateFile.is(change)) { - let file = URI.parse(change.uri).fsPath; - await this.createFile(file, change.options); - } else if (import_vscode_languageserver_protocol13.RenameFile.is(change)) { - changedMap.set(change.oldUri, change.newUri); - await this.renameFile(URI.parse(change.oldUri).fsPath, URI.parse(change.newUri).fsPath, change.options); - } else if (import_vscode_languageserver_protocol13.DeleteFile.is(change)) { - await this.deleteFile(URI.parse(change.uri).fsPath, change.options); - } - } - if (changedMap.size) { - locations.forEach((location) => { - let newUri = changedMap.get(location.uri); - if (newUri) - location.uri = newUri; - }); - } - } else if (changes) { - let uris = Object.keys(changes); - let unloaded = uris.filter((uri2) => this.getDocument(uri2) == null); - if (unloaded.length) { - if (promptUser) { - let res = await window_default.showPrompt(`${unloaded.length} documents on disk would be loaded for change, confirm?`); - if (!res) - return; - } - await this.loadFiles(unloaded); - } - for (let uri2 of Object.keys(changes)) { - let document3 = this.getDocument(uri2); - if (URI.parse(uri2).toString() == uri2) - currEdits = changes[uri2]; - let edits = changes[uri2]; - for (let edit3 of edits) { - locations.push({ uri: document3.uri, range: edit3.range }); - } - await document3.applyEdits(edits); - } - changeCount = uris.length; - } - if (currEdits) { - let changed = getChangedFromEdits({ line: cursor[0], character: cursor[1] }, currEdits); - if (changed) - await window_default.moveTo({ - line: cursor[0] + changed.line, - character: cursor[1] + changed.character - }); - } - if (locations.length) { - let items = await Promise.all(locations.map((loc) => this.getQuickfixItem(loc))); - let silent = locations.every((l) => l.uri == uri); - if (listTarget == "quickfix") { - await this.nvim.call("setqflist", [items]); - if (!silent) - window_default.showMessage(`changed ${changeCount} buffers, use :wa to save changes to disk and :copen to open quickfix list`, "more"); - } else if (listTarget == "location") { - await nvim.setVar("coc_jump_locations", items); - if (!silent) - window_default.showMessage(`changed ${changeCount} buffers, use :wa to save changes to disk and :CocList location to manage changed locations`, "more"); - } - } - } catch (e) { - logger25.error("Error on applyEdits:", edit2, e); - window_default.showMessage(`Error on applyEdits: ${e.message}`, "error"); - return false; - } - await wait(50); - return true; - } - async getQuickfixItem(loc, text, type = "", module2) { - if (import_vscode_languageserver_protocol13.LocationLink.is(loc)) { - loc = import_vscode_languageserver_protocol13.Location.create(loc.targetUri, loc.targetRange); - } - let doc = this.getDocument(loc.uri); - let { uri, range } = loc; - let { line, character } = range.start; - let sl = range.start.line; - let sc = range.start.character; - let el = range.end.line; - let ec = range.end.character; - let u = URI.parse(uri); - let bufnr = doc ? doc.bufnr : -1; - if (!text && u.scheme == "file") { - text = await this.getLine(uri, line); - character = byteIndex(text, character); - } - let item = { - uri, - filename: u.scheme == "file" ? u.fsPath : uri, - lnum: sl + 1, - end_lnum: el + 1, - col: sc + 1, - end_col: ec + 1, - text: text || "", - range - }; - if (module2) - item.module = module2; - if (type) - item.type = type; - if (bufnr != -1) - item.bufnr = bufnr; - return item; - } - createMru(name2) { - return new Mru(name2); - } - async getSelectedRange(mode, document2) { - let { nvim } = this; - if (mode === "line") { - let line = await nvim.call("line", ["."]); - let content = document2.getline(line - 1); - if (!content.length) - return null; - return import_vscode_languageserver_protocol13.Range.create(line - 1, 0, line, 0); - } - if (mode === "cursor") { - let [line, character] = await nvim.eval("coc#cursor#position()"); - return import_vscode_languageserver_protocol13.Range.create(line, character, line, character); - } - if (!["v", "V", "char", "line", ""].includes(mode)) { - throw new Error(`Mode '${mode}' not supported`); - } - let isVisual = ["v", "V", ""].includes(mode); - let [, sl, sc] = await nvim.call("getpos", isVisual ? `'<` : `'[`); - let [, el, ec] = await nvim.call("getpos", isVisual ? `'>` : `']`); - let range = import_vscode_languageserver_protocol13.Range.create(document2.getPosition(sl, sc), document2.getPosition(el, ec)); - if (mode == "v" || mode == "") { - range.end.character = range.end.character + 1; - } - return range; - } - async selectRange(range) { - let { nvim } = this; - let { start, end } = range; - let [bufnr, ve, selection] = await nvim.eval(`[bufnr('%'), &virtualedit, &selection]`); - let doc = this.getDocument(bufnr); - if (!doc || !doc.attached) - return; - let line = doc.getline(start.line); - let col = line ? byteLength(line.slice(0, start.character)) : 0; - let endLine = doc.getline(end.line); - let endCol = endLine ? byteLength(endLine.slice(0, end.character)) : 0; - let move_cmd = ""; - let resetVirtualEdit = false; - move_cmd += "v"; - endCol = await nvim.eval(`virtcol([${end.line + 1}, ${endCol}])`); - if (selection == "inclusive") { - if (end.character == 0) { - move_cmd += `${end.line}G`; - } else { - move_cmd += `${end.line + 1}G${endCol}|`; - } - } else if (selection == "old") { - move_cmd += `${end.line + 1}G${endCol}|`; - } else { - move_cmd += `${end.line + 1}G${endCol + 1}|`; - } - col = await nvim.eval(`virtcol([${start.line + 1}, ${col}])`); - move_cmd += `o${start.line + 1}G${col + 1}|o`; - nvim.pauseNotification(); - if (ve != "onemore") { - resetVirtualEdit = true; - nvim.setOption("virtualedit", "onemore", true); - } - nvim.command(`noa call cursor(${start.line + 1},${col + (move_cmd == "a" ? 0 : 1)})`, true); - nvim.command(`normal! ${move_cmd}`, true); - if (resetVirtualEdit) - nvim.setOption("virtualedit", ve, true); - if (this.isVim) - nvim.command("redraw", true); - await nvim.resumeNotification(); - } - async showLocations(locations) { - let items = await Promise.all(locations.map((loc) => this.getQuickfixItem(loc))); - let { nvim } = this; - const preferences = this.getConfiguration("coc.preferences"); - if (preferences.get("useQuickfixForLocations", false)) { - let openCommand = await nvim.getVar("coc_quickfix_open_command"); - if (typeof openCommand != "string") { - openCommand = items.length < 10 ? `copen ${items.length}` : "copen"; - } - nvim.pauseNotification(); - nvim.call("setqflist", [items], true); - nvim.command(openCommand, true); - nvim.resumeNotification(false, true); - } else { - await nvim.setVar("coc_jump_locations", items); - if (this.env.locationlist) { - nvim.command("CocList --normal --auto-preview location", true); - } else { - nvim.call("coc#util#do_autocmd", ["CocLocationsChange"], true); - } - } - } - async getLine(uri, line) { - let document2 = this.getDocument(uri); - if (document2) - return document2.getline(line) || ""; - if (!uri.startsWith("file:")) - return ""; - let fsPath = URI.parse(uri).fsPath; - if (!import_fs_extra4.default.existsSync(fsPath)) - return ""; - return await readFileLine(fsPath, line); - } - getWorkspaceFolder(uri) { - this.workspaceFolders.sort((a, b) => b.uri.length - a.uri.length); - let filepath = URI.parse(uri).fsPath; - return this.workspaceFolders.find((folder) => isParentFolder(URI.parse(folder.uri).fsPath, filepath, true)); - } - async readFile(uri) { - let document2 = this.getDocument(uri); - if (document2) { - await document2.patchChange(); - return document2.content; - } - let u = URI.parse(uri); - if (u.scheme != "file") - return ""; - let lines = await this.nvim.call("readfile", [u.fsPath]); - return lines.join("\n") + "\n"; - } - get document() { - return new Promise((resolve3, reject) => { - this.nvim.buffer.then((buf) => { - let bufnr = buf.id; - this.bufnr = bufnr; - if (this.buffers.has(bufnr)) { - resolve3(this.buffers.get(bufnr)); - return; - } - this.onBufCreate(bufnr).catch(reject); - let disposable = this.onDidOpenTextDocument((doc) => { - disposable.dispose(); - resolve3(this.getDocument(doc.uri)); - }); - }, reject); - }); - } - async getCurrentState() { - let document2 = await this.document; - let position = await window_default.getCursorPosition(); - return { - document: document2.textDocument, - position - }; - } - async getFormatOptions(uri) { - let doc; - if (uri) - doc = this.getDocument(uri); - let bufnr = doc ? doc.bufnr : 0; - let [tabSize, insertSpaces] = await this.nvim.call("coc#util#get_format_opts", [bufnr]); - return { - tabSize, - insertSpaces: insertSpaces == 1 - }; - } - async jumpTo(uri, position, openCommand) { - const preferences = this.getConfiguration("coc.preferences"); - let jumpCommand = openCommand || preferences.get("jumpCommand", "edit"); - let { nvim } = this; - let doc = this.getDocument(uri); - let bufnr = doc ? doc.bufnr : -1; - if (bufnr != -1 && jumpCommand == "edit") { - nvim.pauseNotification(); - nvim.command(`silent! normal! m'`, true); - nvim.command(`buffer ${bufnr}`, true); - if (position) { - let line = doc.getline(position.line); - let col = byteLength(line.slice(0, position.character)) + 1; - nvim.call("cursor", [position.line + 1, col], true); - } - if (this.isVim) - nvim.command("redraw", true); - await nvim.resumeNotification(); - } else { - let { fsPath, scheme } = URI.parse(uri); - let pos = position == null ? null : [position.line, position.character]; - if (scheme == "file") { - let bufname = fixDriver(import_path11.default.normalize(fsPath)); - await this.nvim.call("coc#util#jump", [jumpCommand, bufname, pos]); - } else { - if (import_os4.default.platform() == "win32") { - uri = uri.replace(/\/?/, "?"); - } - await this.nvim.call("coc#util#jump", [jumpCommand, uri, pos]); - } - } - } - async createFile(filepath, opts = {}) { - let stat = await statAsync(filepath); - if (stat && !opts.overwrite && !opts.ignoreIfExists) { - window_default.showMessage(`${filepath} already exists!`, "error"); - return; - } - if (!stat || opts.overwrite) { - if (filepath.endsWith("/")) { - try { - filepath = this.expand(filepath); - await import_fs_extra4.default.mkdirp(filepath); - } catch (e) { - window_default.showMessage(`Can't create ${filepath}: ${e.message}`, "error"); - } - } else { - let uri = URI.file(filepath).toString(); - let doc = this.getDocument(uri); - if (doc) - return; - if (!import_fs_extra4.default.existsSync(import_path11.default.dirname(filepath))) { - import_fs_extra4.default.mkdirpSync(import_path11.default.dirname(filepath)); - } - import_fs_extra4.default.writeFileSync(filepath, "", "utf8"); - await this.loadFile(uri); - } - } - } - async loadFile(uri) { - let doc = this.getDocument(uri); - if (doc) - return doc; - let { nvim } = this; - let filepath = uri.startsWith("file") ? URI.parse(uri).fsPath : uri; - nvim.call("coc#util#open_files", [[filepath]], true); - return await new Promise((resolve3, reject) => { - let disposable = this.onDidOpenTextDocument((textDocument) => { - let fsPath = URI.parse(textDocument.uri).fsPath; - if (textDocument.uri == uri || fsPath == filepath) { - clearTimeout(timer); - disposable.dispose(); - resolve3(this.getDocument(uri)); - } - }); - let timer = setTimeout(() => { - disposable.dispose(); - reject(new Error(`Create document ${uri} timeout after 1s.`)); - }, 1e3); - }); - } - async loadFiles(uris) { - uris = uris.filter((uri) => this.getDocument(uri) == null); - if (!uris.length) - return; - let bufnrs = await this.nvim.call("coc#util#open_files", [uris.map((u) => URI.parse(u).fsPath)]); - let create = bufnrs.filter((bufnr) => this.getDocument(bufnr) == null); - if (!create.length) - return; - return new Promise((resolve3, reject) => { - let timer = setTimeout(() => { - disposable.dispose(); - reject(new Error(`Create document timeout after 2s.`)); - }, 2e3); - let disposable = this.onDidOpenTextDocument(() => { - if (uris.every((uri) => this.getDocument(uri) != null)) { - clearTimeout(timer); - disposable.dispose(); - resolve3(); - } - }); - }); - } - async renameFile(oldPath, newPath, opts = {}) { - let { overwrite, ignoreIfExists } = opts; - let { nvim } = this; - try { - let stat = await statAsync(newPath); - if (stat && !overwrite && !ignoreIfExists) { - throw new Error(`${newPath} already exists`); - } - if (!stat || overwrite) { - let uri = URI.file(oldPath).toString(); - let newUri = URI.file(newPath).toString(); - let doc = this.getDocument(uri); - if (doc != null) { - let isCurrent = doc.bufnr == this.bufnr; - let newDoc = this.getDocument(newUri); - if (newDoc) - await this.nvim.command(`silent ${newDoc.bufnr}bwipeout!`); - let content = doc.getDocumentContent(); - await import_fs_extra4.default.writeFile(newPath, content, "utf8"); - if (!isCurrent) { - await nvim.call("coc#util#open_files", [[newPath]]); - await nvim.command(`silent ${doc.bufnr}bwipeout!`); - } else { - let view = await nvim.call("winsaveview"); - nvim.pauseNotification(); - nvim.call("coc#util#open_file", ["keepalt edit", newPath], true); - nvim.command(`silent ${doc.bufnr}bwipeout!`, true); - nvim.call("winrestview", [view], true); - await nvim.resumeNotification(); - } - await import_fs_extra4.default.unlink(oldPath); - } else { - await renameAsync(oldPath, newPath); - } - } - } catch (e) { - window_default.showMessage(`Rename error: ${e.message}`, "error"); - } - } - async deleteFile(filepath, opts = {}) { - let { ignoreIfNotExists, recursive } = opts; - let stat = await statAsync(filepath.replace(/\/$/, "")); - let isDir = stat && stat.isDirectory(); - if (filepath.endsWith("/") && !isDir) { - window_default.showMessage(`${filepath} is not directory`, "error"); - return; - } - if (!stat && !ignoreIfNotExists) { - window_default.showMessage(`${filepath} not exists`, "error"); - return; - } - if (stat == null) - return; - if (isDir && !recursive) { - window_default.showMessage(`Can't remove directory, recursive not set`, "error"); - return; - } - try { - if (isDir && recursive) { - await import_fs_extra4.default.remove(filepath); - } else if (isDir) { - await import_fs_extra4.default.rmdir(filepath); - } else { - await import_fs_extra4.default.unlink(filepath); - } - if (!isDir) { - let uri = URI.file(filepath).toString(); - let doc = this.getDocument(uri); - if (doc) - await this.nvim.command(`silent! bwipeout! ${doc.bufnr}`); - } - } catch (e) { - window_default.showMessage(`Error on delete ${filepath}: ${e.message}`, "error"); - } - } - async openResource(uri) { - let { nvim } = this; - if (uri.startsWith("http")) { - await nvim.call("coc#util#open_url", uri); - return; - } - let wildignore = await nvim.getOption("wildignore"); - await nvim.setOption("wildignore", ""); - await this.jumpTo(uri); - await nvim.setOption("wildignore", wildignore); - } - async resolveModule(name2) { - return await this.resolver.resolveModule(name2); - } - async runCommand(cmd, cwd, timeout) { - cwd = cwd || this.cwd; - return runCommand(cmd, { cwd }, timeout); - } - expand(filepath) { - if (!filepath) - return filepath; - if (filepath.startsWith("~")) { - filepath = import_os4.default.homedir() + filepath.slice(1); - } - if (filepath.includes("$")) { - let doc = this.getDocument(this.bufnr); - let fsPath = doc ? URI.parse(doc.uri).fsPath : ""; - filepath = filepath.replace(/\$\{(.*?)\}/g, (match, name2) => { - if (name2.startsWith("env:")) { - let key = name2.split(":")[1]; - let val = key ? process.env[key] : ""; - return val; - } - switch (name2) { - case "workspace": - case "workspaceRoot": - case "workspaceFolder": - return this.root; - case "workspaceFolderBasename": - return import_path11.default.dirname(this.root); - case "cwd": - return this.cwd; - case "file": - return fsPath; - case "fileDirname": - return fsPath ? import_path11.default.dirname(fsPath) : ""; - case "fileExtname": - return fsPath ? import_path11.default.extname(fsPath) : ""; - case "fileBasename": - return fsPath ? import_path11.default.basename(fsPath) : ""; - case "fileBasenameNoExtension": { - let basename = fsPath ? import_path11.default.basename(fsPath) : ""; - return basename ? basename.slice(0, basename.length - import_path11.default.extname(basename).length) : ""; - } - default: - return match; - } - }); - filepath = filepath.replace(/\$[\w]+/g, (match) => { - if (match == "$HOME") - return import_os4.default.homedir(); - return process.env[match.slice(1)] || match; - }); - } - return filepath; - } - async createTerminal(opts) { - let cmd = opts.shellPath; - let args = opts.shellArgs; - if (!cmd) - cmd = await this.nvim.getOption("shell"); - let terminal = new TerminalModel(cmd, args || [], this.nvim, opts.name); - await terminal.start(opts.cwd || this.cwd, opts.env); - this.terminals.set(terminal.bufnr, terminal); - this._onDidOpenTerminal.fire(terminal); - return terminal; - } - async callAsync(method, args) { - if (this.isNvim) - return await this.nvim.call(method, args); - return await this.nvim.callAsync("coc#util#with_callback", [method, args]); - } - registerTextDocumentContentProvider(scheme, provider) { - this.schemeProviderMap.set(scheme, provider); - this.setupDynamicAutocmd(); - let disposables = []; - if (provider.onDidChange) { - provider.onDidChange(async (uri) => { - let doc = this.getDocument(uri.toString()); - if (doc) { - let { buffer } = doc; - let tokenSource = new import_vscode_languageserver_protocol13.CancellationTokenSource(); - let content = await Promise.resolve(provider.provideTextDocumentContent(uri, tokenSource.token)); - await buffer.setLines(content.split(/\r?\n/), { - start: 0, - end: -1, - strictIndexing: false - }); - } - }, null, disposables); - } - return import_vscode_languageserver_protocol13.Disposable.create(() => { - this.schemeProviderMap.delete(scheme); - disposeAll(disposables); - this.setupDynamicAutocmd(); - }); - } - registerKeymap(modes, key, fn, opts = {}) { - if (!key) - throw new Error(`Invalid key ${key} of registerKeymap`); - if (this.keymaps.has(key)) - throw new Error(`${key} already exists.`); - opts = Object.assign({ sync: true, cancel: true, silent: true, repeat: false }, opts); - let { nvim } = this; - this.keymaps.set(key, [fn, !!opts.repeat]); - let method = opts.sync ? "request" : "notify"; - let silent = opts.silent ? "" : ""; - for (let m of modes) { - if (m == "i") { - nvim.command(`inoremap ${silent} (coc-${key}) coc#_insert_key('${method}', '${key}', ${opts.cancel ? 1 : 0})`, true); - } else { - let modify2 = getKeymapModifier(m); - nvim.command(`${m}noremap ${silent} (coc-${key}) :${modify2}call coc#rpc#${method}('doKeymap', ['${key}'])`, true); - } - } - return import_vscode_languageserver_protocol13.Disposable.create(() => { - this.keymaps.delete(key); - for (let m of modes) { - nvim.command(`${m}unmap (coc-${key})`, true); - } - }); - } - registerExprKeymap(mode, key, fn, buffer = false) { - if (!key) - return; - let id = `${mode}${global.Buffer.from(key).toString("base64")}${buffer ? "1" : "0"}`; - let { nvim } = this; - this.keymaps.set(id, [fn, false]); - if (mode == "i") { - nvim.command(`inoremap ${buffer ? "" : ""} ${key} coc#_insert_key('request', '${id}')`, true); - } else { - nvim.command(`${mode}noremap ${buffer ? "" : ""} ${key} coc#rpc#request('doKeymap', ['${id}'])`, true); - } - return import_vscode_languageserver_protocol13.Disposable.create(() => { - this.keymaps.delete(id); - nvim.command(`${mode}unmap ${buffer ? "" : ""} ${key}`, true); - }); - } - registerLocalKeymap(mode, key, fn, notify = false) { - let id = v1_default(); - let { nvim, bufnr } = this; - this.keymaps.set(id, [fn, false]); - let method = notify ? "notify" : "request"; - let modify2 = getKeymapModifier(mode); - let escaped = key.startsWith("<") && key.endsWith(">") ? `{${key.slice(1, -1)}}` : key; - if (this.isNvim && !global.hasOwnProperty("__TEST__")) { - nvim.call("nvim_buf_set_keymap", [0, mode, key, `:${modify2}call coc#rpc#${method}('doKeymap', ['${id}', '', '${escaped}'])`, { - silent: true, - nowait: true - }], true); - } else { - let cmd = `${mode}noremap ${key} :${modify2}call coc#rpc#${method}('doKeymap', ['${id}', '', '${escaped}'])`; - nvim.command(cmd, true); - } - return import_vscode_languageserver_protocol13.Disposable.create(() => { - this.keymaps.delete(id); - nvim.call("coc#compat#buf_del_keymap", [bufnr, mode, key], true); - }); - } - createDatabase(name2) { - let root; - if (global.hasOwnProperty("__TEST__")) { - root = import_path11.default.join(import_os4.default.tmpdir(), `coc-${process.pid}`); - import_fs_extra4.default.mkdirpSync(root); - } else { - root = import_path11.default.dirname(this.env.extensionRoot); - } - let filepath = import_path11.default.join(root, name2 + ".json"); - return new DB(filepath); - } - createTask(id) { - return new Task(this.nvim, id); - } - registerBufferSync(create) { - return new BufferSync(create, this); - } - setupDynamicAutocmd(initialize = false) { - if (!initialize && !this._dynAutocmd) - return; - this._dynAutocmd = true; - let schemes = this.schemeProviderMap.keys(); - let cmds = []; - for (let scheme of schemes) { - cmds.push(`autocmd BufReadCmd,FileReadCmd,SourceCmd ${scheme}:/* call coc#rpc#request('CocAutocmd', ['BufReadCmd','${scheme}', expand('')])`); - } - for (let [id, autocmd] of this.autocmds.entries()) { - let args = autocmd.arglist && autocmd.arglist.length ? ", " + autocmd.arglist.join(", ") : ""; - let event = Array.isArray(autocmd.event) ? autocmd.event.join(",") : autocmd.event; - let pattern = autocmd.pattern != null ? autocmd.pattern : "*"; - if (/\buser\b/i.test(event)) { - pattern = ""; - } - cmds.push(`autocmd ${event} ${pattern} call coc#rpc#${autocmd.request ? "request" : "notify"}('doAutocmd', [${id}${args}])`); - } - for (let key of this.watchedOptions) { - cmds.push(`autocmd OptionSet ${key} call coc#rpc#notify('OptionSet',[expand(''), v:option_old, v:option_new])`); - } - let content = ` -augroup coc_dynamic_autocmd - autocmd! - ${cmds.join("\n ")} -augroup end`; - try { - let dir = import_path11.default.join(process.env.TMPDIR || import_os4.default.tmpdir(), `coc.nvim-${process.pid}`); - if (!import_fs_extra4.default.existsSync(dir)) - import_fs_extra4.default.mkdirpSync(dir); - let filepath = import_path11.default.join(dir, `coc-${process.pid}.vim`); - import_fs_extra4.default.writeFileSync(filepath, content, "utf8"); - let cmd = `source ${filepath}`; - if (this.env.isCygwin && platform_exports.isWindows) { - cmd = `execute "source" . substitute(system('cygpath ${filepath.replace(/\\/g, "/")}'), '\\n', '', 'g')`; - } - this.nvim.command(cmd).logError(); - } catch (e) { - window_default.showMessage(`Can't create tmp file: ${e.message}`, "error"); - } - } - async onBufReadCmd(scheme, uri) { - let provider = this.schemeProviderMap.get(scheme); - if (!provider) { - window_default.showMessage(`Provider for ${scheme} not found`, "error"); - return; - } - let tokenSource = new import_vscode_languageserver_protocol13.CancellationTokenSource(); - let content = await Promise.resolve(provider.provideTextDocumentContent(URI.parse(uri), tokenSource.token)); - let buf = await this.nvim.buffer; - await buf.setLines(content.split(/\r?\n/), { - start: 0, - end: -1, - strictIndexing: false - }); - setTimeout(async () => { - await events_default.fire("BufCreate", [buf.id]); - }, 30); - } - async attach() { - if (this._attached) - return; - this._attached = true; - let [bufs, bufnr, winid] = await this.nvim.eval(`[map(getbufinfo({'bufloaded': 1}),'v:val["bufnr"]'),bufnr('%'),win_getid()]`); - this.bufnr = bufnr; - await Promise.all(bufs.map((buf) => this.onBufCreate(buf))); - if (!this._initialized) { - this._onDidWorkspaceInitialized.fire(void 0); - this._initialized = true; - } - await events_default.fire("BufEnter", [bufnr]); - await events_default.fire("BufWinEnter", [bufnr, winid]); - } - getChangedUris(documentChanges) { - let uris = new Set(); - let createUris = new Set(); - for (let change of documentChanges) { - if (import_vscode_languageserver_protocol13.TextDocumentEdit.is(change)) { - let { textDocument } = change; - let { uri, version: version2 } = textDocument; - uris.add(uri); - if (version2 != null && version2 > 0) { - let doc = this.getDocument(uri); - if (!doc) { - throw new Error(`${uri} not loaded`); - } - if (doc.version != version2) { - throw new Error(`${uri} changed before apply edit`); - } - } - } else if (import_vscode_languageserver_protocol13.CreateFile.is(change) || import_vscode_languageserver_protocol13.DeleteFile.is(change)) { - if (!isFile(change.uri)) { - throw new Error(`change of scheme ${change.uri} not supported`); - } - createUris.add(change.uri); - uris.add(change.uri); - } else if (import_vscode_languageserver_protocol13.RenameFile.is(change)) { - if (!isFile(change.oldUri) || !isFile(change.newUri)) { - throw new Error(`change of scheme ${change.oldUri} not supported`); - } - let newFile = URI.parse(change.newUri).fsPath; - if (import_fs_extra4.default.existsSync(newFile)) { - throw new Error(`file "${newFile}" already exists for rename`); - } - uris.add(change.oldUri); - } else { - throw new Error(`Invalid document change: ${JSON.stringify(change, null, 2)}`); - } - } - return Array.from(uris); - } - createConfigurations() { - let home = import_path11.default.normalize(process.env.COC_VIMCONFIG) || import_path11.default.join(import_os4.default.homedir(), ".vim"); - let userConfigFile = import_path11.default.join(home, CONFIG_FILE_NAME); - return new Configurations(userConfigFile, new ConfigurationProxy(this)); - } - attachChangedEvents() { - if (this.isVim) { - const onChange = (bufnr) => { - let doc = this.getDocument(bufnr); - if (doc && doc.attached) - doc.fetchContent(); - }; - events_default.on("TextChangedP", onChange, null, this.disposables); - events_default.on("TextChangedI", onChange, null, this.disposables); - events_default.on("TextChanged", onChange, null, this.disposables); - } - } - async onBufCreate(buf) { - let buffer = typeof buf === "number" ? this.nvim.createBuffer(buf) : buf; - let bufnr = buffer.id; - if (this.creatingSources.has(bufnr)) - return; - let document2 = this.getDocument(bufnr); - let source = new import_vscode_languageserver_protocol13.CancellationTokenSource(); - try { - if (document2) - this.onBufUnload(bufnr, true); - document2 = new Document(buffer, this._env, this.maxFileSize); - let token = source.token; - this.creatingSources.set(bufnr, source); - let created = await document2.init(this.nvim, token); - if (!created) - document2 = null; - } catch (e) { - logger25.error("Error on create buffer:", e); - document2 = null; - } - if (this.creatingSources.get(bufnr) == source) { - source.dispose(); - this.creatingSources.delete(bufnr); - } - if (!document2 || !document2.textDocument) - return; - this.buffers.set(bufnr, document2); - if (document2.attached) { - document2.onDocumentDetach((bufnr2) => { - let doc = this.getDocument(bufnr2); - if (doc) - this.onBufUnload(doc.bufnr); - }); - } - if (document2.buftype == "" && document2.schema == "file") { - this.configurations.checkFolderConfiguration(document2.uri); - let config = this.getConfiguration("workspace"); - let filetypes = config.get("ignoredFiletypes", []); - if (!filetypes.includes(document2.filetype)) { - let root = this.resolveRoot(document2); - if (root) { - this.addWorkspaceFolder(root); - if (this.bufnr == buffer.id) { - this._root = root; - } - } - } - } - if (document2.enabled) { - let textDocument = Object.assign(document2.textDocument, { bufnr }); - this._onDidOpenDocument.fire(textDocument); - document2.onDocumentChange((e) => this._onDidChangeDocument.fire(e)); - } - logger25.debug("buffer created", buffer.id); - } - onBufEnter(bufnr) { - this.bufnr = bufnr; - let doc = this.getDocument(bufnr); - if (doc) { - this.configurations.setFolderConfiguration(doc.uri); - let workspaceFolder = this.getWorkspaceFolder(doc.uri); - if (workspaceFolder) - this._root = URI.parse(workspaceFolder.uri).fsPath; - } - } - async checkCurrentBuffer(bufnr) { - this.bufnr = bufnr; - await this.checkBuffer(bufnr); - } - onBufWritePost(bufnr) { - let doc = this.buffers.get(bufnr); - if (!doc) - return; - this._onDidSaveDocument.fire(doc.textDocument); - } - onBufUnload(bufnr, recreate = false) { - logger25.debug("buffer unload", bufnr); - if (!recreate) { - let source = this.creatingSources.get(bufnr); - if (source) { - source.cancel(); - this.creatingSources.delete(bufnr); - } - } - if (this.terminals.has(bufnr)) { - let terminal = this.terminals.get(bufnr); - this._onDidCloseTerminal.fire(terminal); - this.terminals.delete(bufnr); - } - let doc = this.buffers.get(bufnr); - if (doc) { - let textDocument = Object.assign(doc.textDocument, { bufnr }); - this._onDidCloseDocument.fire(textDocument); - this.buffers.delete(bufnr); - doc.detach(); - } - } - async onBufWritePre(bufnr) { - let doc = this.buffers.get(bufnr); - if (!doc || !doc.attached) - return; - await doc.synchronize(); - let firing = true; - let thenables = []; - let event = { - document: doc.textDocument, - reason: import_vscode_languageserver_protocol13.TextDocumentSaveReason.Manual, - waitUntil: (thenable) => { - if (!firing) { - logger25.error(`Can't call waitUntil in async manner:`, Error().stack); - window_default.showMessage(`waitUntil can't be used in async manner, check log for details`, "error"); - } else { - thenables.push(thenable); - } - } - }; - this._onWillSaveDocument.fire(event); - firing = false; - let total = thenables.length; - if (total) { - let promise = new Promise((resolve3) => { - const preferences = this.getConfiguration("coc.preferences"); - const willSaveHandlerTimeout = preferences.get("willSaveHandlerTimeout", 500); - let timer = setTimeout(() => { - window_default.showMessage(`Will save handler timeout after ${willSaveHandlerTimeout}ms`, "warning"); - resolve3(void 0); - }, willSaveHandlerTimeout); - let i = 0; - let called = false; - for (let p of thenables) { - let cb = (res) => { - if (called) - return; - called = true; - clearTimeout(timer); - resolve3(res); - }; - p.then((res) => { - if (Array.isArray(res) && res.length && import_vscode_languageserver_protocol13.TextEdit.is(res[0])) { - return cb(res); - } - i = i + 1; - if (i == total) - cb(void 0); - }, () => { - i = i + 1; - if (i == total) - cb(void 0); - }); - } - }); - let edits = await promise; - if (edits) - await doc.applyEdits(edits); - } - } - onDirChanged(cwd) { - if (cwd == this._cwd) - return; - this._cwd = cwd; - } - onFileTypeChange(filetype, bufnr) { - let doc = this.getDocument(bufnr); - if (!doc) - return; - let converted = doc.convertFiletype(filetype); - if (converted == doc.filetype) - return; - let textDocument = Object.assign(doc.textDocument, { bufnr }); - this._onDidCloseDocument.fire(textDocument); - doc.setFiletype(filetype); - this._onDidOpenDocument.fire(Object.assign(doc.textDocument, { bufnr })); - } - async checkBuffer(bufnr) { - if (this._disposed || !bufnr) - return; - let doc = this.getDocument(bufnr); - if (!doc && !this.creatingSources.has(bufnr)) - await this.onBufCreate(bufnr); - } - resolveRoot(document2) { - let types = [PatternType.Buffer, PatternType.LanguageServer, PatternType.Global]; - let u = URI.parse(document2.uri); - let dir = import_path11.default.dirname(u.fsPath); - let { cwd } = this; - let config = this.getConfiguration("workspace"); - let bottomUpFileTypes = config.get("bottomUpFiletypes", []); - let checkCwd = config.get("workspaceFolderCheckCwd", true); - for (let patternType of types) { - let patterns = this.getRootPatterns(document2, patternType); - if (patterns && patterns.length) { - let isBottomUp = bottomUpFileTypes.includes(document2.filetype); - let root = resolveRoot(dir, patterns, cwd, isBottomUp, checkCwd); - if (root) - return root; - } - } - if (this.cwd != import_os4.default.homedir() && isParentFolder(this.cwd, dir, true)) - return this.cwd; - return null; - } - getRootPatterns(document2, patternType) { - let { uri } = document2; - if (patternType == PatternType.Buffer) - return document2.getVar("root_patterns", []) || []; - if (patternType == PatternType.LanguageServer) - return this.getServerRootPatterns(document2.filetype); - const preferences = this.getConfiguration("coc.preferences", uri); - return preferences.get("rootPatterns", [".git", ".hg", ".projections.json"]).slice(); - } - async renameCurrent() { - let { nvim } = this; - let bufnr = await nvim.call("bufnr", "%"); - let cwd = await nvim.call("getcwd"); - let doc = this.getDocument(bufnr); - if (!doc || doc.buftype != "" || doc.schema != "file") { - nvim.errWriteLine("current buffer is not file."); - return; - } - let oldPath = URI.parse(doc.uri).fsPath; - let newPath = await nvim.callAsync("coc#util#with_callback", ["input", ["New path: ", oldPath, "file"]]); - newPath = newPath ? newPath.trim() : null; - if (newPath == oldPath || !newPath) - return; - let lines = await doc.buffer.lines; - let exists = import_fs_extra4.default.existsSync(oldPath); - if (exists) { - let modified = await nvim.eval("&modified"); - if (modified) - await nvim.command("noa w"); - if (oldPath.toLowerCase() != newPath.toLowerCase() && import_fs_extra4.default.existsSync(newPath)) { - let overwrite = await window_default.showPrompt(`${newPath} exists, overwrite?`); - if (!overwrite) - return; - import_fs_extra4.default.unlinkSync(newPath); - } - import_fs_extra4.default.renameSync(oldPath, newPath); - } - this._onWillRenameFiles.fire({ - files: [{ newUri: URI.parse(newPath), oldUri: URI.parse(oldPath) }], - waitUntil: async (thenable) => { - const edit2 = await Promise.resolve(thenable); - if (edit2 && import_vscode_languageserver_protocol13.WorkspaceEdit.is(edit2)) { - await this.applyEdit(edit2); - } - } - }); - this._onDidRenameFiles.fire({ - files: [{ newUri: URI.parse(newPath), oldUri: URI.parse(oldPath) }] - }); - let filepath = isParentFolder(cwd, newPath) ? import_path11.default.relative(cwd, newPath) : newPath; - let view = await nvim.call("winsaveview"); - nvim.pauseNotification(); - if (oldPath.toLowerCase() == newPath.toLowerCase()) { - nvim.command(`keepalt ${bufnr}bwipeout!`, true); - nvim.call("coc#util#open_file", ["keepalt edit", filepath], true); - } else { - nvim.call("coc#util#open_file", ["keepalt edit", filepath], true); - nvim.command(`${bufnr}bwipeout!`, true); - } - if (!exists && lines.join("\n") != "\n") { - nvim.call("append", [0, lines], true); - nvim.command("normal! Gdd", true); - } - nvim.call("winrestview", [view], true); - await nvim.resumeNotification(); - } - get folderPaths() { - return this.workspaceFolders.map((f) => URI.parse(f.uri).fsPath); - } - get floatSupported() { - let { env } = this; - return env.floating || env.textprop; - } - removeWorkspaceFolder(fsPath) { - let idx = this._workspaceFolders.findIndex((f) => URI.parse(f.uri).fsPath == fsPath); - if (idx != -1) { - let folder = this._workspaceFolders[idx]; - this._workspaceFolders.splice(idx, 1); - this._onDidChangeWorkspaceFolders.fire({ - removed: [folder], - added: [] - }); - } - } - renameWorkspaceFolder(oldPath, newPath) { - let idx = this._workspaceFolders.findIndex((f) => URI.parse(f.uri).fsPath == oldPath); - if (idx == -1) - return; - let removed = this._workspaceFolders[idx]; - let added = { - uri: URI.file(newPath).toString(), - name: import_path11.default.dirname(newPath) - }; - this._workspaceFolders.splice(idx, 1); - this._workspaceFolders.push(added); - this._onDidChangeWorkspaceFolders.fire({ - removed: [removed], - added: [added] - }); - } - addRootPattern(filetype, rootPatterns) { - let patterns = this.rootPatterns.get(filetype) || []; - for (let p of rootPatterns) { - if (!patterns.includes(p)) { - patterns.push(p); - } - } - this.rootPatterns.set(filetype, patterns); - } - get insertMode() { - return this._insertMode; - } - async detach() { - if (!this._attached) - return; - this._attached = false; - channels_default.dispose(); - for (let bufnr of this.buffers.keys()) { - await events_default.fire("BufUnload", [bufnr]); - } - } - dispose() { - this._disposed = true; - for (let doc of this.documents) { - doc.detach(); - } - disposeAll(this.disposables); - Watchman.dispose(); - this.configurations.dispose(); - this.buffers.clear(); - } - addWorkspaceFolder(rootPath) { - if (rootPath == import_os4.default.homedir()) - return; - let { _workspaceFolders } = this; - let uri = URI.file(rootPath).toString(); - let workspaceFolder = { uri, name: import_path11.default.basename(rootPath) }; - if (_workspaceFolders.findIndex((o) => o.uri == uri) == -1) { - _workspaceFolders.push(workspaceFolder); - if (this._initialized) { - this._onDidChangeWorkspaceFolders.fire({ - added: [workspaceFolder], - removed: [] - }); - } - } - return workspaceFolder; - } - getServerRootPatterns(filetype) { - let lspConfig = this.getConfiguration().get("languageserver", {}); - let patterns = []; - for (let key of Object.keys(lspConfig)) { - let config = lspConfig[key]; - let { filetypes, rootPatterns } = config; - if (Array.isArray(filetypes) && rootPatterns && filetypes.includes(filetype)) { - patterns.push(...rootPatterns); - } - } - patterns = patterns.concat(this.rootPatterns.get(filetype) || []); - return patterns.length ? distinct(patterns) : null; - } - }; - workspace_default = new Workspace(); - } -}); - -// src/util/fzy.ts -function islower(s) { - return s.toLowerCase() === s; -} -function isupper(s) { - return s.toUpperCase() === s; -} -function precompute_bonus(haystack) { - let m = haystack.length; - let match_bonus = new Array(m); - let last_ch = "/"; - for (let i = 0; i < m; i++) { - let ch = haystack[i]; - if (last_ch === "/") { - match_bonus[i] = SCORE_MATCH_SLASH; - } else if (last_ch === "-" || last_ch === "_" || last_ch === " ") { - match_bonus[i] = SCORE_MATCH_WORD; - } else if (last_ch === ".") { - match_bonus[i] = SCORE_MATCH_DOT; - } else if (islower(last_ch) && isupper(ch)) { - match_bonus[i] = SCORE_MATCH_CAPITAL; - } else { - match_bonus[i] = 0; - } - last_ch = ch; - } - return match_bonus; -} -function compute(needle, haystack, D, M) { - let n = needle.length; - let m = haystack.length; - let lower_needle = needle.toLowerCase(); - let lower_haystack = haystack.toLowerCase(); - let match_bonus = precompute_bonus(haystack); - for (let i = 0; i < n; i++) { - D[i] = new Array(m); - M[i] = new Array(m); - let prev_score = SCORE_MIN; - let gap_score = i === n - 1 ? SCORE_GAP_TRAILING : SCORE_GAP_INNER; - for (let j = 0; j < m; j++) { - if (lower_needle[i] === lower_haystack[j]) { - let score5 = SCORE_MIN; - if (!i) { - score5 = j * SCORE_GAP_LEADING + match_bonus[j]; - } else if (j) { - score5 = Math.max(M[i - 1][j - 1] + match_bonus[j], D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE); - } - D[i][j] = score5; - M[i][j] = prev_score = Math.max(score5, prev_score + gap_score); - } else { - D[i][j] = SCORE_MIN; - M[i][j] = prev_score = prev_score + gap_score; - } - } - } -} -function score2(needle, haystack) { - let n = needle.length; - let m = haystack.length; - if (!n || !m) - return SCORE_MIN; - if (n === m) { - return SCORE_MAX; - } - if (m > 1024) { - return SCORE_MIN; - } - let D = new Array(n); - let M = new Array(n); - compute(needle, haystack, D, M); - return M[n - 1][m - 1]; -} -function groupPositions(arr) { - let res = []; - for (let i = 0; i < arr.length; i++) { - let last = res.length ? res[res.length - 1] : void 0; - let curr = arr[i]; - if (last && curr == last[1]) { - last[1] = curr + 1; - } else { - res.push([curr, curr + 1]); - } - } - return res; -} -function positions(needle, haystack) { - let n = needle.length; - let m = haystack.length; - let positions2 = new Array(n); - if (!n || !m) - return positions2; - if (n === m) { - for (let i = 0; i < n; i++) - positions2[i] = i; - return positions2; - } - if (m > 1024) { - return positions2; - } - let D = new Array(n); - let M = new Array(n); - compute(needle, haystack, D, M); - let match_required = false; - for (let i = n - 1, j = m - 1; i >= 0; i--) { - for (; j >= 0; j--) { - if (D[i][j] !== SCORE_MIN && (match_required || D[i][j] === M[i][j])) { - match_required = i && j && M[i][j] === D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE; - positions2[i] = j--; - break; - } - } - } - return positions2; -} -function hasMatch(needle, haystack) { - needle = needle.toLowerCase(); - haystack = haystack.toLowerCase(); - let l = needle.length; - for (let i = 0, j = 0; i < l; i += 1) { - j = haystack.indexOf(needle[i], j) + 1; - if (j === 0) - return false; - } - return true; -} -var SCORE_MIN, SCORE_MAX, SCORE_GAP_LEADING, SCORE_GAP_TRAILING, SCORE_GAP_INNER, SCORE_MATCH_CONSECUTIVE, SCORE_MATCH_SLASH, SCORE_MATCH_WORD, SCORE_MATCH_CAPITAL, SCORE_MATCH_DOT; -var init_fzy = __esm({ - "src/util/fzy.ts"() { - SCORE_MIN = -Infinity; - SCORE_MAX = Infinity; - SCORE_GAP_LEADING = -5e-3; - SCORE_GAP_TRAILING = -5e-3; - SCORE_GAP_INNER = -0.01; - SCORE_MATCH_CONSECUTIVE = 1; - SCORE_MATCH_SLASH = 0.9; - SCORE_MATCH_WORD = 0.8; - SCORE_MATCH_CAPITAL = 0.7; - SCORE_MATCH_DOT = 0.6; - } -}); - -// src/tree/filter.ts -var import_vscode_languageserver_protocol14, sessionKey, Filter; -var init_filter = __esm({ - "src/tree/filter.ts"() { - init_events(); - import_vscode_languageserver_protocol14 = __toModule(require_main2()); - init_util(); - sessionKey = "filter"; - Filter = class { - constructor(nvim, keys) { - this.nvim = nvim; - this._activated = false; - this.history = []; - this.disposables = []; - this._onDidUpdate = new import_vscode_languageserver_protocol14.Emitter(); - this._onDidExit = new import_vscode_languageserver_protocol14.Emitter(); - this._onDidKeyPress = new import_vscode_languageserver_protocol14.Emitter(); - this.onDidKeyPress = this._onDidKeyPress.event; - this.onDidUpdate = this._onDidUpdate.event; - this.onDidExit = this._onDidExit.event; - this.text = ""; - events_default.on("InputChar", (session, character) => { - if (session !== sessionKey || !this._activated) - return; - if (!keys.includes(character)) { - if (character.length == 1) { - this.text = this.text + character; - this._onDidUpdate.fire(this.text); - return; - } - if (character == "") { - this.text = this.text.slice(0, -1); - this._onDidUpdate.fire(this.text); - return; - } - if (character == "") { - this.text = ""; - this._onDidUpdate.fire(this.text); - return; - } - if (character == "") { - let idx = this.history.indexOf(this.text); - let text = this.history[idx + 1] || this.history[0]; - if (text) { - this.text = text; - this._onDidUpdate.fire(this.text); - } - return; - } - if (character == "") { - let idx = this.history.indexOf(this.text); - let text = this.history[idx - 1] || this.history[this.history.length - 1]; - if (text) { - this.text = text; - this._onDidUpdate.fire(this.text); - } - } - if (character == "" || character == "") { - this.deactivate(); - return; - } - } - this._onDidKeyPress.fire(character); - }, null, this.disposables); - } - active() { - if (this._activated) - return; - this._activated = true; - this.text = ""; - this.nvim.call("coc#prompt#start_prompt", [sessionKey], true); - } - deactivate(node) { - if (!this._activated) - return; - this.nvim.call("coc#prompt#stop_prompt", [sessionKey], true); - this._activated = false; - let { text } = this; - this.text = ""; - this._onDidExit.fire(node); - if (text && !this.history.includes(text)) { - this.history.push(text); - } - } - get activated() { - return this._activated; - } - dispose() { - this.deactivate(); - this.history = []; - this._onDidKeyPress.dispose(); - this._onDidUpdate.dispose(); - this._onDidExit.dispose(); - disposeAll(this.disposables); - } - }; - } -}); - -// src/tree/TreeItem.ts -var import_path12, TreeItemLabel, TreeItemCollapsibleState, TreeItem; -var init_TreeItem = __esm({ - "src/tree/TreeItem.ts"() { - init_esm2(); - import_path12 = __toModule(require("path")); - (function(TreeItemLabel3) { - function is(obj) { - return typeof obj.label == "string"; - } - TreeItemLabel3.is = is; - })(TreeItemLabel || (TreeItemLabel = {})); - (function(TreeItemCollapsibleState2) { - TreeItemCollapsibleState2[TreeItemCollapsibleState2["None"] = 0] = "None"; - TreeItemCollapsibleState2[TreeItemCollapsibleState2["Collapsed"] = 1] = "Collapsed"; - TreeItemCollapsibleState2[TreeItemCollapsibleState2["Expanded"] = 2] = "Expanded"; - })(TreeItemCollapsibleState || (TreeItemCollapsibleState = {})); - TreeItem = class { - constructor(label, collapsibleState = 0) { - this.collapsibleState = collapsibleState; - if (URI.isUri(label)) { - this.resourceUri = label; - this.label = import_path12.default.basename(label.path); - this.id = label.toString(); - } else { - this.label = label; - } - } - }; - } -}); - -// src/tree/TreeView.ts -var TreeView_exports = {}; -__export(TreeView_exports, { - default: () => BasicTreeView -}); -var import_vscode_languageserver_protocol15, logger26, highlightNamespace, signOffset, globalId, BasicTreeView; -var init_TreeView = __esm({ - "src/tree/TreeView.ts"() { - import_vscode_languageserver_protocol15 = __toModule(require_main2()); - init_commands2(); - init_events(); - init_floatFactory(); - init_util(); - init_mutex(); - init_object(); - init_string(); - init_fzy(); - init_workspace(); - init_window(); - init_filter(); - init_TreeItem(); - logger26 = require_logger2()("BasicTreeView"); - highlightNamespace = "tree"; - signOffset = 3e3; - globalId = 1; - BasicTreeView = class { - constructor(viewId, opts) { - this.viewId = viewId; - this._selection = []; - this._onDidExpandElement = new import_vscode_languageserver_protocol15.Emitter(); - this._onDidCollapseElement = new import_vscode_languageserver_protocol15.Emitter(); - this._onDidChangeSelection = new import_vscode_languageserver_protocol15.Emitter(); - this._onDidChangeVisibility = new import_vscode_languageserver_protocol15.Emitter(); - this.onDidExpandElement = this._onDidExpandElement.event; - this.onDidCollapseElement = this._onDidCollapseElement.event; - this.onDidChangeSelection = this._onDidChangeSelection.event; - this.onDidChangeVisibility = this._onDidChangeVisibility.event; - this.retryTimers = 0; - this.renderedItems = []; - this.nodesMap = new Map(); - this.mutex = new Mutex(); - this.disposables = []; - this.lineState = { titleCount: 0, messageCount: 0 }; - this.loadConfiguration(); - workspace_default.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables); - if (opts.enableFilter) { - this.filter = new Filter(this.nvim, [this.keys.selectNext, this.keys.selectPrevious, this.keys.invoke]); - } - this.tooltipFactory = new FloatFactory(workspace_default.nvim); - this.canSelectMany = !!opts.canSelectMany; - this.provider = opts.treeDataProvider; - this.leafIndent = opts.disableLeafIndent !== true; - this.winfixwidth = opts.winfixwidth !== false; - let message; - Object.defineProperty(this, "message", { - set: (msg) => { - message = msg ? msg.replace(/\r?\n/g, " ") : void 0; - this.updateHeadLines(); - }, - get: () => { - return message; - } - }); - let title = viewId.replace(/\r?\n/g, " "); - Object.defineProperty(this, "title", { - set: (newTitle) => { - title = newTitle ? newTitle.replace(/\r?\n/g, " ") : void 0; - this.updateHeadLines(); - }, - get: () => { - return title; - } - }); - let description; - Object.defineProperty(this, "description", { - set: (desc) => { - description = desc ? desc.replace(/\r?\n/g, " ") : void 0; - this.updateHeadLines(); - }, - get: () => { - return description; - } - }); - let filterText; - Object.defineProperty(this, "filterText", { - set: (text) => { - let { titleCount, messageCount } = this.lineState; - let start = titleCount + messageCount; - if (text != null) { - let highlights = [{ - lnum: start, - colStart: byteLength(text), - colEnd: byteLength(text) + 1, - hlGroup: "Cursor" - }]; - this.renderedItems = []; - this.updateUI([text + " "], highlights, start, -1, true); - void this.doFilter(text); - } else if (filterText != null) { - this.updateUI([], [], start, start + 1); - } - filterText = text; - }, - get: () => { - return filterText; - } - }); - if (this.provider.onDidChangeTreeData) { - this.provider.onDidChangeTreeData(this.onDataChange, this, this.disposables); - } - events_default.on("BufUnload", (bufnr) => { - if (bufnr != this.bufnr) - return; - this.winid = void 0; - this.bufnr = void 0; - this._onDidChangeVisibility.fire({ visible: false }); - this.dispose(); - }, null, this.disposables); - events_default.on("CursorHold", async (bufnr) => { - if (bufnr != this.bufnr) - return; - await this.onHover(); - }, null, this.disposables); - events_default.on(["CursorMoved", "BufEnter"], () => { - this.cancelResolve(); - }, null, this.disposables); - events_default.on("WinEnter", (winid) => { - var _a2; - if (winid != this.windowId || !((_a2 = this.filter) == null ? void 0 : _a2.activated)) - return; - let buf = this.nvim.createBuffer(this.bufnr); - let line = this.startLnum - 1; - let len = this.filterText ? this.filterText.length : 0; - let range = import_vscode_languageserver_protocol15.Range.create(line, len, line, len + 1); - buf.highlightRanges(highlightNamespace, "Cursor", [range]); - this.nvim.call("coc#prompt#start_prompt", [sessionKey], true); - this.redraw(); - }, null, this.disposables); - events_default.on("WinLeave", (winid) => { - var _a2; - if (winid != this.windowId || !((_a2 = this.filter) == null ? void 0 : _a2.activated)) - return; - let buf = this.nvim.createBuffer(this.bufnr); - this.nvim.call("coc#prompt#stop_prompt", [sessionKey], true); - buf.clearNamespace(highlightNamespace, this.startLnum - 1, this.startLnum); - }, null, this.disposables); - this.disposables.push(this._onDidChangeVisibility, this._onDidChangeSelection, this._onDidCollapseElement, this._onDidExpandElement); - if (this.filter) { - this.filter.onDidExit((node) => { - this.nodesMap.clear(); - this.filterText = void 0; - this.itemsToFilter = void 0; - if (node && typeof this.provider.getParent === "function") { - this.renderedItems = []; - void this.reveal(node, { focus: true }); - } else { - this.clearSelection(); - void this.render(); - } - }); - this.filter.onDidUpdate((text) => { - this.filterText = text; - }); - this.filter.onDidKeyPress(async (character) => { - var _a2, _b; - let items = this.renderedItems; - if (!(items == null ? void 0 : items.length)) - return; - let curr = this.selection[0]; - if (character == "" || character == this.keys.selectPrevious) { - let idx = items.findIndex((o) => o.node == curr); - let index = idx == -1 || idx == 0 ? items.length - 1 : idx - 1; - let node = (_a2 = items[index]) == null ? void 0 : _a2.node; - if (node) - this.selectItem(node, true); - } - if (character == "" || character == this.keys.selectNext) { - let idx = items.findIndex((o) => o.node == curr); - let index = idx == -1 || idx == items.length - 1 ? 0 : idx + 1; - let node = (_b = items[index]) == null ? void 0 : _b.node; - if (node) - this.selectItem(node, true); - } - if (character == "" || character == this.keys.invoke) { - if (!curr) - return; - await this.invokeCommand(curr); - this.filter.deactivate(curr); - } - }); - } - } - get windowId() { - return this.winid; - } - get startLnum() { - let filterCount = this.filterText == null ? 0 : 1; - return this.lineState.messageCount + this.lineState.titleCount + filterCount; - } - get nvim() { - return workspace_default.nvim; - } - loadConfiguration(e) { - if (!e || e.affectsConfiguration("tree")) { - let config = workspace_default.getConfiguration("tree"); - this.config = { - openedIcon: config.get("openedIcon", " "), - closedIcon: config.get("closedIcon", " ") - }; - this.keys = { - close: config.get("key.close"), - invoke: config.get("key.invoke"), - toggle: config.get("key.toggle"), - actions: config.get("key.actions"), - collapseAll: config.get("key.collapseAll"), - toggleSelection: config.get("key.toggleSelection"), - activeFilter: config.get("key.activeFilter"), - selectNext: config.get("key.selectNext"), - selectPrevious: config.get("key.selectPrevious") - }; - if (e) { - void this.render(); - } - } - } - async doFilter(text) { - let items = []; - let index = 0; - let release = await this.mutex.acquire(); - try { - if (!this.itemsToFilter) { - let itemsToFilter = []; - const addNodes = async (nodes2) => { - for (let n of nodes2) { - itemsToFilter.push(n); - let arr = await Promise.resolve(this.provider.getChildren(n)); - if (arr == null ? void 0 : arr.length) - await addNodes(arr); - } - }; - let nodes = await Promise.resolve(this.provider.getChildren()); - await addNodes(nodes); - this.itemsToFilter = itemsToFilter; - } - for (let n of this.itemsToFilter) { - let item = await this.getTreeItem(n); - let label = TreeItemLabel.is(item.label) ? item.label.label : item.label; - if (!text || hasMatch(text, label)) { - let idxs = text ? positions(text, label) : []; - item.collapsibleState = TreeItemCollapsibleState.None; - item.label = { label, highlights: text ? groupPositions(idxs) : [] }; - let { line, highlights: highlights2 } = this.getRenderedLine(item, index, 0); - items.push({ - level: 0, - node: n, - line, - index, - score: text ? score2(text, label) : 0, - highlights: highlights2 - }); - index += 1; - } - } - items.sort((a, b) => { - if (a.score != b.score) - return b.score - a.score; - return a.index - b.index; - }); - let lnum = this.startLnum; - let highlights = []; - let renderedItems = this.renderedItems = items.map((o, idx) => { - highlights.push(...o.highlights.map((h) => { - h.lnum = lnum + idx; - return h; - })); - delete o.index; - delete o.score; - delete o.highlights; - return o; - }); - this.updateUI(renderedItems.map((o) => o.line), highlights, lnum, -1, true); - if (renderedItems.length) { - this.selectItem(renderedItems[0].node, true); - } else { - this.clearSelection(); - } - this.redraw(); - release(); - } catch (e) { - release(); - logger26.error(`Error on tree filter: ${e.message}`, e); - } - } - async onHover() { - let { nvim } = this; - let lnum = await nvim.call("line", ["."]); - let element = this.getElementByLnum(lnum - 1); - if (!element) - return; - let obj = this.nodesMap.get(element); - if (!obj) - return; - let item = obj.item; - if (!obj.resolved) { - item = await this.resolveItem(element, item); - if (!item) - return; - } - if (!item.tooltip || !this.bufnr) - return; - let isMarkdown2 = import_vscode_languageserver_protocol15.MarkupContent.is(item.tooltip) && item.tooltip.kind == import_vscode_languageserver_protocol15.MarkupKind.Markdown; - let doc = { - filetype: isMarkdown2 ? "markdown" : "txt", - content: import_vscode_languageserver_protocol15.MarkupContent.is(item.tooltip) ? item.tooltip.value : item.tooltip - }; - await this.tooltipFactory.show([doc], { modes: ["n"] }); - } - async onClick(element) { - let { nvim } = this; - let [line, col] = await nvim.eval(`[getline('.'),col('.')]`); - let pre = byteSlice(line, 0, col - 1); - let character = line[pre.length]; - if (!character) - return; - let { openedIcon, closedIcon } = this.config; - if (/^\s*$/.test(pre) && [openedIcon, closedIcon].includes(character)) { - await this.toggleExpand(element); - } else { - await this.invokeCommand(element); - } - } - async invokeCommand(element) { - let obj = this.nodesMap.get(element); - if (!obj) - return; - this.selectItem(element); - let item = obj.item; - if (!item.command) { - item = await this.resolveItem(element, item); - if (!item) - return; - } - if (!item.command) - throw new Error(`Failed to resolve command from TreeItem.`); - await commands_default.execute(item.command); - } - async invokeActions(element) { - this.selectItem(element); - if (typeof this.provider.resolveActions !== "function") { - await window_default.showWarningMessage("No actions"); - return; - } - let obj = this.nodesMap.get(element); - let actions = await Promise.resolve(this.provider.resolveActions(obj.item, element)); - if (!actions || actions.length == 0) { - await window_default.showWarningMessage("No actions available"); - return; - } - let keys = actions.map((o) => o.title); - let res = await window_default.showMenuPicker(keys, "Choose action"); - if (res == -1) - return; - await Promise.resolve(actions[res].handler(element)); - } - async onDataChange(node) { - var _a2; - if ((_a2 = this.filter) == null ? void 0 : _a2.activated) { - this.itemsToFilter = void 0; - await this.doFilter(this.filterText); - return; - } - this.clearSelection(); - if (!node) { - await this.render(); - return; - } - let release = await this.mutex.acquire(); - try { - let items = this.renderedItems; - let idx = items.findIndex((o) => o.node === node); - if (idx != -1 && this.bufnr) { - let obj = items[idx]; - let level = obj.level; - let removeCount = 0; - for (let i = idx; i < items.length; i++) { - let o = items[i]; - if (i == idx || o && o.level > level) { - removeCount += 1; - } - } - let appendItems = []; - let highlights = []; - let start = idx + this.startLnum; - await this.appendTreeNode(node, level, start, appendItems, highlights); - items.splice(idx, removeCount, ...appendItems); - this.updateUI(appendItems.map((o) => o.line), highlights, start, start + removeCount); - } - release(); - } catch (e) { - let errMsg = `Error on tree refresh: ${e.message}`; - logger26.error(errMsg, e); - this.nvim.errWriteLine("[coc.nvim] " + errMsg); - release(); - } - } - async resolveItem(element, item) { - if (typeof this.provider.resolveTreeItem === "function") { - let tokenSource = this.resolveTokenSource = new import_vscode_languageserver_protocol15.CancellationTokenSource(); - let token = tokenSource.token; - item = await Promise.resolve(this.provider.resolveTreeItem(item, element, token)); - tokenSource.dispose(); - this.resolveTokenSource = void 0; - if (token.isCancellationRequested) - return void 0; - } - this.nodesMap.set(element, { item, resolved: true }); - return item; - } - get visible() { - return this.winid != null; - } - get selection() { - return this._selection.slice(); - } - async checkLines() { - if (!this.bufnr) - return; - let buf = this.nvim.createBuffer(this.bufnr); - let curr = await buf.lines; - let { titleCount, messageCount } = this.lineState; - curr = curr.slice(titleCount + messageCount); - let lines = this.renderedItems.map((o) => o.line); - return equals(curr, lines); - } - async toggleExpand(element) { - let o = this.nodesMap.get(element); - if (!o) - return; - let treeItem = o.item; - let lnum = this.getItemLnum(element); - let nodeIdx = lnum - this.startLnum; - let obj = this.renderedItems[nodeIdx]; - if (!obj || treeItem.collapsibleState == TreeItemCollapsibleState.None) { - if (typeof this.provider.getParent === "function") { - let node = await Promise.resolve(this.provider.getParent(element)); - if (node) { - await this.toggleExpand(node); - this.focusItem(node); - } - } - return; - } - let removeCount = 0; - if (treeItem.collapsibleState == TreeItemCollapsibleState.Expanded) { - let level = obj.level; - for (let i = nodeIdx + 1; i < this.renderedItems.length; i++) { - let o2 = this.renderedItems[i]; - if (!o2 || o2.level <= level) - break; - removeCount += 1; - } - treeItem.collapsibleState = TreeItemCollapsibleState.Collapsed; - } else if (treeItem.collapsibleState == TreeItemCollapsibleState.Collapsed) { - treeItem.collapsibleState = TreeItemCollapsibleState.Expanded; - } - let newItems = []; - let newHighlights = []; - await this.appendTreeNode(obj.node, obj.level, lnum, newItems, newHighlights); - this.renderedItems.splice(nodeIdx, removeCount + 1, ...newItems); - this.updateUI(newItems.map((o2) => o2.line), newHighlights, lnum, lnum + removeCount + 1); - this.refreshSigns(); - if (treeItem.collapsibleState == TreeItemCollapsibleState.Collapsed) { - this._onDidCollapseElement.fire({ element }); - } else { - this._onDidExpandElement.fire({ element }); - } - } - toggleSelection(element) { - let idx = this._selection.findIndex((o) => o === element); - if (idx !== -1) { - this.unselectItem(idx); - } else { - this.selectItem(element); - } - } - clearSelection() { - if (!this.bufnr) - return; - this._selection = []; - let buf = this.nvim.createBuffer(this.bufnr); - buf.unplaceSign({ group: "CocTree" }); - this._onDidChangeSelection.fire({ selection: [] }); - } - selectItem(item, forceSingle, noRedraw) { - let { nvim } = this; - if (!this.bufnr || !workspace_default.env.sign) - return; - let row = this.getItemLnum(item); - if (row == null) - return; - let buf = nvim.createBuffer(this.bufnr); - let exists = this._selection.includes(item); - if (!this.canSelectMany || forceSingle) { - this._selection = [item]; - } else if (!exists) { - this._selection.push(item); - } - nvim.pauseNotification(); - if (!this.canSelectMany || forceSingle) { - buf.unplaceSign({ group: "CocTree" }); - } - nvim.call("coc#compat#execute", [this.winid, `exe ${row + 1}`], true); - buf.placeSign({ id: signOffset + row, lnum: row + 1, name: "CocTreeSelected", group: "CocTree" }); - if (!noRedraw) - this.redraw(); - void nvim.resumeNotification(false, true); - if (!exists) - this._onDidChangeSelection.fire({ selection: this._selection }); - } - unselectItem(idx) { - let item = this._selection[idx]; - let row = this.getItemLnum(item); - if (row == null || !this.bufnr || !workspace_default.env.sign) - return; - this._selection.splice(idx, 1); - let buf = this.nvim.createBuffer(this.bufnr); - buf.unplaceSign({ group: "CocTree", id: signOffset + row }); - this._onDidChangeSelection.fire({ selection: this._selection }); - } - focusItem(element) { - if (!this.winid) - return; - let lnum = this.getItemLnum(element); - if (lnum == null) - return; - this.nvim.call("coc#compat#execute", [this.winid, `exe ${lnum + 1}`], true); - } - getElementByLnum(lnum) { - let item = this.renderedItems[lnum - this.startLnum]; - return item ? item.node : void 0; - } - getItemLnum(item) { - let idx = this.renderedItems.findIndex((o) => o.node === item); - if (idx == -1) - return void 0; - return this.startLnum + idx; - } - async getTreeItem(element) { - let exists; - let resolved = false; - let obj = this.nodesMap.get(element); - if (obj != null) { - exists = obj.item; - resolved = obj.resolved; - } - let item = await Promise.resolve(this.provider.getTreeItem(element)); - if (item.id && !exists) { - for (let obj2 of this.nodesMap.values()) { - if (obj2.item.id === item.id) { - resolved = obj2.resolved; - exists = obj2.item; - break; - } - } - } - if (exists && exists.collapsibleState != TreeItemCollapsibleState.None && item.collapsibleState != TreeItemCollapsibleState.None) { - item.collapsibleState = exists.collapsibleState; - } - this.nodesMap.set(element, { item, resolved }); - return item; - } - getRenderedLine(treeItem, lnum, level) { - let { openedIcon, closedIcon } = this.config; - const highlights = []; - const { label, deprecated, description } = treeItem; - let prefix = " ".repeat(level); - const addHighlight = (text, hlGroup) => { - let colStart = byteLength(prefix); - highlights.push({ - lnum, - hlGroup, - colStart, - colEnd: colStart + byteLength(text) - }); - }; - switch (treeItem.collapsibleState) { - case TreeItemCollapsibleState.Expanded: { - addHighlight(openedIcon, "CocTreeOpenClose"); - prefix += openedIcon + " "; - break; - } - case TreeItemCollapsibleState.Collapsed: { - addHighlight(closedIcon, "CocTreeOpenClose"); - prefix += closedIcon + " "; - break; - } - default: - prefix += this.leafIndent ? " " : ""; - } - if (treeItem.icon) { - let { text, hlGroup } = treeItem.icon; - addHighlight(text, hlGroup); - prefix += text + " "; - } - if (TreeItemLabel.is(label) && Array.isArray(label.highlights)) { - let colStart = byteLength(prefix); - for (let o of label.highlights) { - highlights.push({ - lnum, - hlGroup: "Search", - colStart: colStart + o[0], - colEnd: colStart + o[1] - }); - } - } - let labelText = typeof label === "string" ? label : label.label; - if (deprecated) { - addHighlight(labelText, "CocDeprecatedHighlight"); - } - prefix += labelText; - if (description && description.indexOf("\n") == -1) { - prefix += " "; - addHighlight(description, "CocTreeDescription"); - prefix += description; - } - return { line: prefix, highlights }; - } - async appendTreeNode(element, level, lnum, items, highlights) { - let takes = 1; - let treeItem = await this.getTreeItem(element); - let res = this.getRenderedLine(treeItem, lnum, level); - highlights.push(...res.highlights); - items.push({ level, line: res.line, node: element }); - if (treeItem.collapsibleState == TreeItemCollapsibleState.Expanded) { - let l = level + 1; - let children = await Promise.resolve(this.provider.getChildren(element)) || []; - for (let el of children) { - let n = await this.appendTreeNode(el, l, lnum + takes, items, highlights); - takes = takes + n; - } - } - return takes; - } - updateUI(lines, highlights, start = 0, end = -1, noRedraw = false) { - if (!this.bufnr) - return; - let { nvim } = this; - let buf = nvim.createBuffer(this.bufnr); - nvim.pauseNotification(); - buf.setOption("modifiable", true, true); - void buf.setLines(lines, { start, end, strictIndexing: false }, true); - if (highlights.length) { - let highlightEnd = end == -1 ? -1 : start + lines.length; - nvim.call("coc#highlight#update_highlights", [this.bufnr, highlightNamespace, highlights, start, highlightEnd], true); - } - buf.setOption("modifiable", false, true); - if (!noRedraw) - this.redraw(); - void nvim.resumeNotification(false, true); - } - async reveal(element, options = {}) { - var _a2; - if ((_a2 = this.filter) == null ? void 0 : _a2.activated) - return; - let isShown = this.getItemLnum(element) != null; - let { select, focus, expand } = options; - let curr = element; - if (typeof this.provider.getParent !== "function") { - throw new Error("missing getParent function from provider for reveal."); - } - if (!isShown) { - while (curr) { - let parentNode = await Promise.resolve(this.provider.getParent(curr)); - if (parentNode) { - let item = await this.getTreeItem(parentNode); - item.collapsibleState = TreeItemCollapsibleState.Expanded; - curr = parentNode; - } else { - break; - } - } - } - if (expand) { - let item = await this.getTreeItem(element); - if (item.collapsibleState == TreeItemCollapsibleState.None) - return; - item.collapsibleState = TreeItemCollapsibleState.Expanded; - if (typeof expand === "number" && expand > 1) { - let curr2 = Math.min(expand, 2); - let nodes = await Promise.resolve(this.provider.getChildren(element)); - while ((nodes == null ? void 0 : nodes.length) > 0) { - let arr = []; - for (let n of nodes) { - let item2 = await this.getTreeItem(n); - if (item2.collapsibleState == TreeItemCollapsibleState.None) - continue; - item2.collapsibleState = TreeItemCollapsibleState.Expanded; - if (curr2 > 1) { - let res = await Promise.resolve(this.provider.getChildren(n)); - arr.push(...res); - } - } - nodes = arr; - curr2 = curr2 - 1; - } - } - } - if (!isShown || expand) { - await this.render(); - } - if (select !== false) - this.selectItem(element); - if (focus) - this.focusItem(element); - } - updateHeadLines(initialize = false) { - let { titleCount, messageCount } = this.lineState; - let end = initialize ? -1 : titleCount + messageCount; - let lines = []; - let highlights = []; - try { - if (this.message) { - highlights.push({ hlGroup: "MoreMsg", colStart: 0, colEnd: byteLength(this.message), lnum: 0 }); - lines.push(this.message); - lines.push(""); - } - if (this.title) { - highlights.push({ hlGroup: "CocTreeTitle", colStart: 0, colEnd: byteLength(this.title), lnum: lines.length }); - if (this.description) { - let colStart = byteLength(this.title) + 1; - highlights.push({ hlGroup: "Comment", colStart, colEnd: colStart + byteLength(this.description), lnum: lines.length }); - } - lines.push(this.title + (this.description ? " " + this.description : "")); - } - this.lineState.messageCount = this.message ? 2 : 0; - this.lineState.titleCount = this.title ? 1 : 0; - this.updateUI(lines, highlights, 0, end); - if (!initialize) { - this.refreshSigns(); - } - } catch (e) { - this.nvim.errWriteLine("[coc.nvim] Error on update head lines:" + e.message); - logger26.error("Error on update head lines:", e); - } - } - refreshSigns() { - let { selection, nvim, bufnr } = this; - if (!selection.length || !bufnr || !workspace_default.env.sign) - return; - let buf = nvim.createBuffer(bufnr); - nvim.pauseNotification(); - buf.unplaceSign({ group: "CocTree" }); - for (let n of selection) { - let row = this.getItemLnum(n); - if (row == null) - continue; - buf.placeSign({ id: signOffset + row, lnum: row + 1, name: "CocTreeSelected", group: "CocTree" }); - } - void nvim.resumeNotification(false, true); - } - async render() { - if (!this.bufnr) - return; - let release = await this.mutex.acquire(); - try { - let lines = []; - let highlights = []; - let { startLnum } = this; - let nodes = await Promise.resolve(this.provider.getChildren()); - let level = 0; - let lnum = startLnum; - let renderedItems = []; - if (!(nodes == null ? void 0 : nodes.length)) { - this.message = "No results"; - } else { - for (let node of nodes) { - let n = await this.appendTreeNode(node, level, lnum, renderedItems, highlights); - lnum += n; - } - } - lines.push(...renderedItems.map((o) => o.line)); - this.renderedItems = renderedItems; - let delta = this.startLnum - startLnum; - if (delta) - highlights.forEach((o) => o.lnum = o.lnum + delta); - this.updateUI(lines, highlights, this.startLnum, -1); - this.retryTimers = 0; - release(); - } catch (e) { - this.renderedItems = []; - this.nodesMap.clear(); - this.lineState = { titleCount: 0, messageCount: 1 }; - release(); - let errMsg = `${e.message}`.replace(/\r?\n/g, " "); - this.updateUI([errMsg], [{ hlGroup: "WarningMsg", colStart: 0, colEnd: byteLength(errMsg), lnum: 0 }]); - if (this.retryTimers == 5) - return; - this.timer = setTimeout(() => { - this.retryTimers = this.retryTimers + 1; - void this.render(); - }, 500); - } - } - async show(splitCommand = "belowright 30vs") { - if (this.bufnr || this._creating) - return; - this._creating = true; - let { nvim } = this; - this.originalWin = await nvim.call("win_getid"); - let winid = await nvim.call("coc#window#find", ["cocViewId", this.viewId]); - let id = globalId; - globalId = globalId + 1; - nvim.pauseNotification(); - if (winid != -1) { - nvim.call("win_gotoid", [winid], true); - nvim.command(`silent edit +setl\\ buftype=nofile CocTree${id}`, true); - } else { - nvim.command(`silent keepalt ${splitCommand} +setl\\ buftype=nofile CocTree${id}`, true); - } - nvim.command("setl bufhidden=wipe nolist nonumber norelativenumber foldcolumn=0", true); - nvim.command(`setl signcolumn=${this.canSelectMany ? "yes" : "no"}${this.winfixwidth ? " winfixwidth" : ""}`, true); - nvim.command("setl nocursorline nobuflisted wrap undolevels=-1 filetype=coctree nomodifiable noswapfile", true); - nvim.command(`let w:cocViewId = "${this.viewId.replace(/"/g, '\\"')}"`, true); - nvim.call("bufnr", ["%"], true); - nvim.call("win_getid", [], true); - let res = await nvim.resumeNotification(); - if (res[1]) - throw new Error(`Error on buffer create:` + JSON.stringify(res[1])); - this._onDidChangeVisibility.fire({ visible: true }); - this.registerKeymaps(); - let arr = res[0]; - this.bufnr = arr[arr.length - 2]; - this.winid = arr[arr.length - 1]; - this._creating = false; - this.updateHeadLines(true); - void this.render(); - } - registerKeymaps() { - let { toggleSelection, actions, close, invoke, toggle, collapseAll, activeFilter } = this.keys; - let { nvim } = this; - const regist4 = (mode, key, fn, notify = false) => { - this.disposables.push(workspace_default.registerLocalKeymap(mode, key, async () => { - let lnum = await nvim.call("line", ["."]); - let element = this.getElementByLnum(lnum - 1); - if (element && !this.nodesMap.has(element)) - return; - await Promise.resolve(fn(element)); - }, notify)); - }; - this.disposables.push(workspace_default.registerLocalKeymap("n", "", () => { - nvim.call("win_gotoid", [this.originalWin], true); - }, true)); - regist4("n", "", async (element) => { - if (element) - await this.onClick(element); - }); - this.filter && activeFilter && regist4("n", activeFilter, async () => { - this.nvim.command(`exe ${this.startLnum}`, true); - this.filter.active(); - this.filterText = ""; - }, true); - toggleSelection && regist4("n", toggleSelection, async (element) => { - if (element) - this.toggleSelection(element); - }); - invoke && regist4("n", invoke, async (element) => { - if (element) - await this.invokeCommand(element); - }, true); - actions && regist4("n", actions, async (element) => { - if (element) - await this.invokeActions(element); - }, true); - toggle && regist4("n", toggle, async (element) => { - if (element) - await this.toggleExpand(element); - }, true); - collapseAll && regist4("n", collapseAll, async () => { - for (let obj of this.nodesMap.values()) { - let item = obj.item; - if (item.collapsibleState == TreeItemCollapsibleState.Expanded) { - item.collapsibleState = TreeItemCollapsibleState.Collapsed; - } - } - await this.render(); - }); - close && regist4("n", close, async () => { - this.hide(); - }, true); - } - hide() { - if (!this.bufnr) - return; - this.nvim.command(`bd! ${this.bufnr}`, true); - this.redraw(); - this._onDidChangeVisibility.fire({ visible: false }); - this.bufnr = void 0; - this.winid = void 0; - } - redraw() { - var _a2; - if (workspace_default.isVim || ((_a2 = this.filter) == null ? void 0 : _a2.activated)) { - this.nvim.command("redraw", true); - } - } - cancelResolve() { - if (this.resolveTokenSource) { - this.resolveTokenSource.cancel(); - this.resolveTokenSource = void 0; - } - } - dispose() { - var _a2; - if (!this.provider) - return; - if (this.timer) { - clearTimeout(this.timer); - this.timer = void 0; - } - (_a2 = this.filter) == null ? void 0 : _a2.dispose(); - this._selection = []; - this.hide(); - this.itemsToFilter = []; - this.cancelResolve(); - this.tooltipFactory.dispose(); - this.renderedItems = []; - this.nodesMap.clear(); - this.provider = void 0; - disposeAll(this.disposables); - } - }; - } -}); - -// src/window.ts -var import_fs10, import_os5, import_path13, import_vscode_languageserver_protocol16, logger27, Window, window_default; -var init_window = __esm({ - "src/window.ts"() { - import_fs10 = __toModule(require("fs")); - import_os5 = __toModule(require("os")); - import_path13 = __toModule(require("path")); - import_vscode_languageserver_protocol16 = __toModule(require_main2()); - init_esm2(); - init_channels(); - init_events(); - init_dialog(); - init_menu(); - init_notification(); - init_picker(); - init_progress(); - init_status(); - init_types(); - init_util(); - init_mutex(); - init_platform(); - init_workspace(); - logger27 = require_logger2()("window"); - Window = class { - constructor() { - this.mutex = new Mutex(); - } - get nvim() { - return workspace_default.nvim; - } - dispose() { - var _a2; - (_a2 = this.statusLine) == null ? void 0 : _a2.dispose(); - } - showMessage(msg, messageType = "more") { - if (this.mutex.busy || !this.nvim) - return; - let { messageLevel } = this; - let method = process.env.VIM_NODE_RPC == "1" ? "callTimer" : "call"; - if (global.hasOwnProperty("__TEST__")) - logger27.info(msg); - let hl = "Error"; - let level = MessageLevel.Error; - switch (messageType) { - case "more": - level = MessageLevel.More; - hl = "MoreMsg"; - break; - case "warning": - level = MessageLevel.Warning; - hl = "WarningMsg"; - break; - } - if (level >= messageLevel) { - this.nvim[method]("coc#util#echo_messages", [hl, ("[coc.nvim] " + msg).split("\n")], true); - } - } - async runTerminalCommand(cmd, cwd, keepfocus = false) { - cwd = cwd || workspace_default.cwd; - return await this.nvim.callAsync("coc#util#run_terminal", { cmd, cwd, keepfocus: keepfocus ? 1 : 0 }); - } - async openTerminal(cmd, opts = {}) { - let bufnr = await this.nvim.call("coc#util#open_terminal", __spreadValues({ cmd }, opts)); - return bufnr; - } - async showQuickpick(items, placeholder = "Choose by number") { - let release = await this.mutex.acquire(); - try { - let title = placeholder + ":"; - items = items.map((s, idx) => `${idx + 1}. ${s}`); - let res = await this.nvim.callAsync("coc#util#quickpick", [title, items.map((s) => s.trim())]); - release(); - let n = parseInt(res, 10); - if (isNaN(n) || n <= 0 || n > items.length) - return -1; - return n - 1; - } catch (e) { - release(); - return -1; - } - } - async showMenuPicker(items, title, token) { - if (workspace_default.env.dialog) { - let release = await this.mutex.acquire(); - if (token && token.isCancellationRequested) { - release(); - return -1; - } - try { - let menu = new Menu(this.nvim, { items: items.map((s) => s.trim()), title }, token); - let promise = new Promise((resolve3) => { - menu.onDidClose((selected) => { - resolve3(selected); - }); - }); - await menu.show(this.dialogPreference); - let res = await promise; - release(); - return res; - } catch (e) { - logger27.error(`Error on showMenuPicker:`, e); - release(); - } - } - return await this.showQuickpick(items); - } - async openLocalConfig() { - let { root } = workspace_default; - if (root == import_os5.default.homedir()) { - this.showMessage(`Can't create local config in home directory`, "warning"); - return; - } - let dir = import_path13.default.join(root, ".vim"); - if (!import_fs10.default.existsSync(dir)) { - let res = await this.showPrompt(`Would you like to create folder'${root}/.vim'?`); - if (!res) - return; - import_fs10.default.mkdirSync(dir); - } - await workspace_default.jumpTo(URI.file(import_path13.default.join(dir, CONFIG_FILE_NAME)).toString()); - } - async showPrompt(title) { - let release = await this.mutex.acquire(); - try { - let res = await this.nvim.callAsync("coc#float#prompt_confirm", [title]); - release(); - return res == 1; - } catch (e) { - release(); - return false; - } - } - async showDialog(config) { - if (!this.checkDialog()) - return null; - let dialog = new Dialog(this.nvim, config); - await dialog.show(this.dialogPreference); - return dialog; - } - async requestInput(title, defaultValue) { - let { nvim } = this; - const preferences = workspace_default.getConfiguration("coc.preferences"); - if (workspace_default.env.dialog && preferences.get("promptInput", true) && !isWindows2) { - let release = await this.mutex.acquire(); - let preferences2 = this.dialogPreference; - try { - let opts = {}; - if (preferences2.floatHighlight) - opts.highlight = preferences2.floatHighlight; - if (preferences2.floatBorderHighlight) - opts.borderhighlight = preferences2.floatBorderHighlight; - let arr = await nvim.call("coc#float#create_prompt_win", [title, defaultValue || "", opts]); - let [bufnr, winid] = arr; - let res = await new Promise((resolve3) => { - let disposables = []; - events_default.on("BufWinLeave", (nr) => { - if (nr == bufnr) { - disposeAll(disposables); - resolve3(null); - } - }, null, disposables); - events_default.on("PromptInsert", async (value) => { - disposeAll(disposables); - await nvim.call("coc#float#close", [winid]); - if (!value) { - this.showMessage("Empty word, canceled", "warning"); - resolve3(null); - } else { - resolve3(value); - } - }, null, disposables); - }); - release(); - return res; - } catch (e) { - logger27.error("Error on requestInput:", e); - release(); - } - } else { - let res = await workspace_default.callAsync("input", [title + ": ", defaultValue || ""]); - nvim.command("normal! :", true); - if (!res) { - this.showMessage("Empty word, canceled", "warning"); - return null; - } - return res; - } - } - createStatusBarItem(priority = 0, option = {}) { - if (!workspace_default.env) { - let fn = () => { - }; - return { text: "", show: fn, dispose: fn, hide: fn, priority: 0, isProgress: false }; - } - if (!this.statusLine) { - this.statusLine = new StatusLine(this.nvim); - } - return this.statusLine.createStatusBarItem(priority, option.progress || false); - } - createOutputChannel(name2) { - return channels_default.create(name2, this.nvim); - } - showOutputChannel(name2, preserveFocus) { - channels_default.show(name2, preserveFocus); - } - async echoLines(lines, truncate = false) { - let { nvim } = this; - let cmdHeight = workspace_default.env.cmdheight; - if (lines.length > cmdHeight && truncate) { - lines = lines.slice(0, cmdHeight); - } - let maxLen = workspace_default.env.columns - 12; - lines = lines.map((line) => { - line = line.replace(/\n/g, " "); - if (truncate) - line = line.slice(0, maxLen); - return line; - }); - if (truncate && lines.length == cmdHeight) { - let last = lines[lines.length - 1]; - lines[cmdHeight - 1] = `${last.length == maxLen ? last.slice(0, -4) : last} ...`; - } - await nvim.call("coc#util#echo_lines", [lines]); - } - async getCursorPosition() { - let [line, content] = await this.nvim.eval(`[line('.')-1, strpart(getline('.'), 0, col('.') - 1)]`); - return import_vscode_languageserver_protocol16.Position.create(line, content.length); - } - async moveTo(position) { - await this.nvim.call("coc#cursor#move_to", [position.line, position.character]); - if (workspace_default.env.isVim) - this.nvim.command("redraw", true); - } - async getOffset() { - return await this.nvim.call("coc#cursor#char_offset"); - } - async getCursorScreenPosition() { - let [row, col] = await this.nvim.call("coc#cursor#screen_pos"); - return { row, col }; - } - async showPickerDialog(items, title, token) { - if (!this.checkDialog()) - return void 0; - let release = await this.mutex.acquire(); - if (token && token.isCancellationRequested) { - release(); - return void 0; - } - try { - let useString = typeof items[0] === "string"; - let picker = new Picker(this.nvim, { - title, - items: useString ? items.map((s) => { - return { label: s }; - }) : items - }, token); - let promise = new Promise((resolve3) => { - picker.onDidClose((selected) => { - resolve3(selected); - }); - }); - await picker.show(this.dialogPreference); - let picked = await promise; - let res = picked == void 0 ? void 0 : items.filter((_, i) => picked.includes(i)); - release(); - return res; - } catch (e) { - logger27.error(`Error on showPickerDialog:`, e); - release(); - } - } - async showInformationMessage(message, ...items) { - if (!this.enableMessageDialog) - return await this.showConfirm(message, items, "Info"); - let texts = typeof items[0] === "string" ? items : items.map((s) => s.title); - let idx = await this.createNotification("CocInfoFloat", message, texts); - return idx == -1 ? void 0 : items[idx]; - } - async showWarningMessage(message, ...items) { - if (!this.enableMessageDialog) - return await this.showConfirm(message, items, "Warning"); - let texts = typeof items[0] === "string" ? items : items.map((s) => s.title); - let idx = await this.createNotification("CocWarningFloat", message, texts); - return idx == -1 ? void 0 : items[idx]; - } - async showErrorMessage(message, ...items) { - if (!this.enableMessageDialog) - return await this.showConfirm(message, items, "Error"); - let texts = typeof items[0] === "string" ? items : items.map((s) => s.title); - let idx = await this.createNotification("CocErrorFloat", message, texts); - return idx == -1 ? void 0 : items[idx]; - } - async showNotification(config) { - if (!this.checkDialog()) - return false; - let notification = new Notification(this.nvim, config); - return await notification.show(this.notificationPreference); - } - async showConfirm(message, items, kind) { - if (!items || items.length == 0) { - let msgType = kind == "Info" ? "more" : kind == "Error" ? "error" : "warning"; - this.showMessage(message, msgType); - return void 0; - } - let titles = typeof items[0] === "string" ? items.slice() : items.map((o) => o.title); - let choices = titles.map((s, i) => `${i + 1}${s}`); - let res = await this.nvim.callAsync("coc#util#with_callback", ["confirm", [message, choices.join("\n"), 0, kind]]); - return items[res - 1]; - } - async withProgress(options, task) { - if (!this.checkDialog()) - return void 0; - let progress = new ProgressNotification(this.nvim, { - task, - title: options.title, - cancellable: options.cancellable - }); - return await progress.show(this.notificationPreference); - } - createTreeView(viewId, options) { - const BasicTreeView2 = (init_TreeView(), TreeView_exports).default; - return new BasicTreeView2(viewId, options); - } - createNotification(borderhighlight, message, items) { - return new Promise((resolve3) => { - let config = { - content: message, - borderhighlight, - close: true, - buttons: items.map((s, index) => { - return { text: s, index }; - }), - callback: (idx) => { - resolve3(idx); - } - }; - let notification = new Notification(this.nvim, config); - notification.show(this.notificationPreference).then((shown) => { - if (!shown) { - logger27.error("Unable to open notification window"); - resolve3(-1); - } - if (!items.length) - resolve3(-1); - }, (e) => { - logger27.error("Unable to open notification window", e); - resolve3(-1); - }); - }); - } - get dialogPreference() { - let config = workspace_default.getConfiguration("dialog"); - return { - maxWidth: config.get("maxWidth"), - maxHeight: config.get("maxHeight"), - floatHighlight: config.get("floatHighlight"), - floatBorderHighlight: config.get("floatBorderHighlight"), - pickerButtons: config.get("pickerButtons"), - pickerButtonShortcut: config.get("pickerButtonShortcut"), - confirmKey: config.get("confirmKey") - }; - } - get notificationPreference() { - let config = workspace_default.getConfiguration("notification"); - return { - top: config.get("marginTop"), - right: config.get("marginRight"), - maxWidth: config.get("maxWidth"), - maxHeight: config.get("maxHeight"), - highlight: config.get("highlightGroup"), - minProgressWidth: config.get("minProgressWidth") - }; - } - checkDialog() { - if (workspace_default.env.dialog) - return true; - this.showMessage("Dialog requires vim >= 8.2.0750 or neovim >= 0.4.0, please upgrade your vim", "warning"); - return false; - } - get enableMessageDialog() { - if (!workspace_default.env.dialog) - return false; - let config = workspace_default.getConfiguration("coc.preferences"); - return config.get("enableMessageDialog", false); - } - get messageLevel() { - let config = workspace_default.getConfiguration("coc.preferences"); - let level = config.get("messageLevel", "more"); - switch (level) { - case "error": - return MessageLevel.Error; - case "warning": - return MessageLevel.Warning; - default: - return MessageLevel.More; - } - } - }; - window_default = new Window(); - } -}); - -// src/diagnostic/util.ts -function getSeverityName(severity) { - switch (severity) { - case import_vscode_languageserver_protocol17.DiagnosticSeverity.Warning: - return "Warning"; - case import_vscode_languageserver_protocol17.DiagnosticSeverity.Information: - return "Information"; - case import_vscode_languageserver_protocol17.DiagnosticSeverity.Hint: - return "Hint"; - default: - return "Error"; - } -} -function getSeverityType(severity) { - switch (severity) { - case import_vscode_languageserver_protocol17.DiagnosticSeverity.Warning: - return "W"; - case import_vscode_languageserver_protocol17.DiagnosticSeverity.Information: - return "I"; - case import_vscode_languageserver_protocol17.DiagnosticSeverity.Hint: - return "I"; - default: - return "E"; - } -} -function severityLevel(level) { - switch (level) { - case "hint": - return import_vscode_languageserver_protocol17.DiagnosticSeverity.Hint; - case "information": - return import_vscode_languageserver_protocol17.DiagnosticSeverity.Information; - case "warning": - return import_vscode_languageserver_protocol17.DiagnosticSeverity.Warning; - case "error": - return import_vscode_languageserver_protocol17.DiagnosticSeverity.Error; - default: - return import_vscode_languageserver_protocol17.DiagnosticSeverity.Hint; - } -} -function getNameFromSeverity(severity) { - switch (severity) { - case import_vscode_languageserver_protocol17.DiagnosticSeverity.Error: - return "CocError"; - case import_vscode_languageserver_protocol17.DiagnosticSeverity.Warning: - return "CocWarning"; - case import_vscode_languageserver_protocol17.DiagnosticSeverity.Information: - return "CocInfo"; - case import_vscode_languageserver_protocol17.DiagnosticSeverity.Hint: - return "CocHint"; - default: - return "CocError"; - } -} -function getLocationListItem(bufnr, diagnostic) { - let { start, end } = diagnostic.range; - let owner = diagnostic.source || "coc.nvim"; - let msg = diagnostic.message.split("\n")[0]; - let type = getSeverityName(diagnostic.severity).slice(0, 1).toUpperCase(); - return { - bufnr, - lnum: start.line + 1, - end_lnum: end.line + 1, - col: start.character + 1, - end_col: end.character + 1, - text: `[${owner}${diagnostic.code ? " " + diagnostic.code : ""}] ${msg} [${type}]`, - type - }; -} -var import_vscode_languageserver_protocol17; -var init_util3 = __esm({ - "src/diagnostic/util.ts"() { - import_vscode_languageserver_protocol17 = __toModule(require_main2()); - } -}); - -// src/diagnostic/buffer.ts -function sortDiagnostics(a, b) { - if ((a.severity || 1) != (b.severity || 1)) { - return (a.severity || 1) - (b.severity || 1); - } - let d = comparePosition(a.range.start, b.range.start); - if (d != 0) - return d; - return a.source > b.source ? 1 : -1; -} -function getHighlightGroup(diagnostic) { - let tags = diagnostic.tags || []; - if (tags.includes(import_vscode_languageserver_protocol18.DiagnosticTag.Deprecated)) { - return DiagnosticHighlight.Deprecated; - } - if (tags.includes(import_vscode_languageserver_protocol18.DiagnosticTag.Unnecessary)) { - return DiagnosticHighlight.Unused; - } - switch (diagnostic.severity) { - case import_vscode_languageserver_protocol18.DiagnosticSeverity.Warning: - return DiagnosticHighlight.Warning; - case import_vscode_languageserver_protocol18.DiagnosticSeverity.Information: - return DiagnosticHighlight.Information; - case import_vscode_languageserver_protocol18.DiagnosticSeverity.Hint: - return DiagnosticHighlight.Hint; - default: - return DiagnosticHighlight.Error; - } -} -var import_vscode_languageserver_protocol18, isVim5, logger28, signGroup, highlightNamespace2, hlGroups, DiagnosticHighlight, DiagnosticBuffer; -var init_buffer = __esm({ - "src/diagnostic/buffer.ts"() { - init_mutex(); - import_vscode_languageserver_protocol18 = __toModule(require_main2()); - init_object(); - init_position(); - init_workspace(); - init_events(); - init_util3(); - isVim5 = process.env.VIM_NODE_RPC == "1"; - logger28 = require_logger2()("diagnostic-buffer"); - signGroup = "CocDiagnostic"; - highlightNamespace2 = "diagnostic"; - hlGroups = ["CocErrorHighlight", "CocWarningHighlight", "CocInfoHighlight", "CocHintHighlight", "CocDeprecatedHighlight", "CocUnusedHighlight"]; - (function(DiagnosticHighlight2) { - DiagnosticHighlight2["Error"] = "CocErrorHighlight"; - DiagnosticHighlight2["Warning"] = "CocWarningHighlight"; - DiagnosticHighlight2["Information"] = "CocInfoHighlight"; - DiagnosticHighlight2["Hint"] = "CocHintHighlight"; - DiagnosticHighlight2["Deprecated"] = "CocDeprecatedHighlight"; - DiagnosticHighlight2["Unused"] = "CocUnusedHighlight"; - })(DiagnosticHighlight || (DiagnosticHighlight = {})); - DiagnosticBuffer = class { - constructor(nvim, bufnr, uri, config, onRefresh) { - this.nvim = nvim; - this.bufnr = bufnr; - this.uri = uri; - this.config = config; - this.onRefresh = onRefresh; - this.diagnosticsMap = new Map(); - this.mutex = new Mutex(); - this._disposed = false; - } - get displayByAle() { - return this.config.displayByAle; - } - clearHighlight(collection) { - this.buffer.clearNamespace(highlightNamespace2 + collection); - } - clearSigns(collection) { - this.buffer.unplaceSign({ group: signGroup + collection }); - } - get diagnostics() { - let res = []; - for (let diags of this.diagnosticsMap.values()) { - res.push(...diags); - } - return res; - } - get buffer() { - return this.nvim.createBuffer(this.bufnr); - } - refreshAle(collection, diagnostics) { - let aleItems = diagnostics.map((o) => { - let range = o.range; - return { - text: o.message, - code: o.code, - lnum: range.start.line + 1, - col: range.start.character + 1, - end_lnum: range.end.line + 1, - end_col: range.end.character, - type: getSeverityType(o.severity) - }; - }); - let method = global.hasOwnProperty("__TEST__") ? "MockAleResults" : "ale#other_source#ShowResults"; - this.nvim.call(method, [this.bufnr, "coc" + collection, aleItems], true); - } - async refresh(diagnosticsMap, force) { - let release = await this.mutex.acquire(); - try { - await this._refresh(diagnosticsMap, force === true); - release(); - } catch (e) { - release(); - this.nvim.echoError(e); - } - } - async _refresh(diagnosticsMap, force) { - let { refreshOnInsertMode } = this.config; - let { nvim } = this; - let checkInsert = !this.displayByAle && !refreshOnInsertMode; - if (events_default.insertMode && checkInsert) - return; - let info = await nvim.call("coc#util#diagnostic_info", [this.bufnr, checkInsert]); - if (!info || this._disposed) - return; - if (this.displayByAle) { - nvim.pauseNotification(); - for (let [collection, diagnostics] of Object.entries(diagnosticsMap)) { - this.diagnosticsMap.set(collection, []); - this.refreshAle(collection, diagnostics); - } - await nvim.resumeNotification(); - } else { - let changed = false; - let redraw = false; - nvim.pauseNotification(); - for (let [collection, diagnostics] of Object.entries(diagnosticsMap)) { - let prev = this.diagnosticsMap.get(collection) || []; - this.diagnosticsMap.set(collection, diagnostics); - if (!equals(prev, diagnostics)) { - changed = true; - redraw = true; - this.addSigns(collection, diagnostics); - this.updateHighlights(collection, diagnostics); - } else if (prev.length && force) { - redraw = true; - this.updateHighlights(collection, diagnostics); - } - } - if (changed) { - this.showVirtualText(info.lnum, info.bufnr); - this.updateLocationList(info.winid, info.locationlist); - this.setDiagnosticInfo(); - } - if (isVim5 && redraw) - this.nvim.command("redraw", true); - await this.nvim.resumeNotification(); - } - this.onRefresh(this.diagnostics); - } - updateLocationList(winid, title) { - if (!this.config.locationlistUpdate || winid == -1 || title !== "Diagnostics of coc") - return; - let items = []; - let { diagnostics } = this; - diagnostics.sort(sortDiagnostics); - for (let diagnostic of diagnostics) { - let item = getLocationListItem(this.bufnr, diagnostic); - items.push(item); - } - this.nvim.call("setloclist", [winid, [], "r", { title: "Diagnostics of coc", items }], true); - } - addSigns(collection, diagnostics) { - if (!this.config.enableSign) - return; - let group2 = signGroup + collection; - this.buffer.unplaceSign({ group: group2 }); - let signsMap = new Map(); - for (let diagnostic of diagnostics) { - let { range, severity } = diagnostic; - let line = range.start.line; - let exists = signsMap.get(line) || []; - if (exists.includes(severity)) { - continue; - } - exists.push(severity); - signsMap.set(line, exists); - let priority = this.config.signPriority + 4 - severity; - let name2 = getNameFromSeverity(severity); - this.buffer.placeSign({ name: name2, lnum: line + 1, group: group2, priority }); - } - } - setDiagnosticInfo() { - let lnums = [0, 0, 0, 0]; - let info = { error: 0, warning: 0, information: 0, hint: 0, lnums }; - for (let diagnostics of this.diagnosticsMap.values()) { - for (let diagnostic of diagnostics) { - let lnum = diagnostic.range.start.line + 1; - switch (diagnostic.severity) { - case import_vscode_languageserver_protocol18.DiagnosticSeverity.Warning: - info.warning = info.warning + 1; - lnums[1] = lnums[1] ? Math.min(lnums[1], lnum) : lnum; - break; - case import_vscode_languageserver_protocol18.DiagnosticSeverity.Information: - info.information = info.information + 1; - lnums[2] = lnums[2] ? Math.min(lnums[2], lnum) : lnum; - break; - case import_vscode_languageserver_protocol18.DiagnosticSeverity.Hint: - info.hint = info.hint + 1; - lnums[3] = lnums[3] ? Math.min(lnums[3], lnum) : lnum; - break; - default: - lnums[0] = lnums[0] ? Math.min(lnums[0], lnum) : lnum; - info.error = info.error + 1; - } - } - } - let buf = this.nvim.createBuffer(this.bufnr); - buf.setVar("coc_diagnostic_info", info, true); - this.nvim.call("coc#util#do_autocmd", ["CocDiagnosticChange"], true); - } - showVirtualText(lnum, bufnr) { - if (!this.config.virtualText) - return; - let { virtualTextSrcId, virtualTextPrefix, virtualTextCurrentLineOnly } = this.config; - let { diagnostics, buffer } = this; - if (virtualTextCurrentLineOnly) { - if (bufnr && this.bufnr != bufnr) - return; - diagnostics = diagnostics.filter((d) => { - let { start, end } = d.range; - return start.line <= lnum - 1 && end.line >= lnum - 1; - }); - } - diagnostics.sort(sortDiagnostics); - buffer.clearNamespace(virtualTextSrcId); - for (let i = diagnostics.length - 1; i >= 0; i--) { - let diagnostic = diagnostics[i]; - let { line } = diagnostic.range.start; - let highlight = getNameFromSeverity(diagnostic.severity) + "VirtualText"; - let msg = diagnostic.message.split(/\n/).map((l) => l.trim()).filter((l) => l.length > 0).slice(0, this.config.virtualTextLines).join(this.config.virtualTextLineSeparator); - void buffer.setVirtualText(virtualTextSrcId, line, [[virtualTextPrefix + msg, highlight]], {}); - } - } - updateHighlights(collection, diagnostics) { - if (!diagnostics.length) { - this.clearHighlight(collection); - } else { - let items = this.getHighlightItems(diagnostics); - this.buffer.updateHighlights(highlightNamespace2 + collection, items); - } - } - getHighlightItems(diagnostics) { - let doc = workspace_default.getDocument(this.bufnr); - if (!doc) - return []; - let res = []; - for (let diagnostic of diagnostics.slice(0, this.config.highlighLimit)) { - let hlGroup = getHighlightGroup(diagnostic); - doc.addHighlights(res, hlGroup, diagnostic.range); - } - res.sort((a, b) => { - if (a.lnum != b.lnum) - return a.lnum - b.lnum; - if (a.colStart != b.colStart) - return a.colStart - b.colStart; - return hlGroups.indexOf(b.hlGroup) - hlGroups.indexOf(a.hlGroup); - }); - return res; - } - clear() { - let { nvim } = this; - let collections = Array.from(this.diagnosticsMap.keys()); - this.diagnosticsMap.clear(); - if (this.displayByAle) { - for (let collection of collections) { - let method = global.hasOwnProperty("__TEST__") ? "MockAleResults" : "ale#other_source#ShowResults"; - this.nvim.call(method, [this.bufnr, collection, []], true); - } - } else { - nvim.pauseNotification(); - for (let collection of collections) { - this.clearHighlight(collection); - this.clearSigns(collection); - } - if (this.config.virtualText) { - this.buffer.clearNamespace(this.config.virtualTextSrcId); - } - this.buffer.deleteVar("coc_diagnostic_info"); - void nvim.resumeNotification(false, true); - } - } - getDiagnosticsAt(pos, checkCurrentLine) { - let diagnostics = []; - for (let diags of this.diagnosticsMap.values()) { - if (checkCurrentLine) { - diagnostics.push(...diags.filter((o) => lineInRange(pos.line, o.range))); - } else { - diagnostics.push(...diags.filter((o) => positionInRange(pos, o.range) == 0)); - } - } - diagnostics.sort(sortDiagnostics); - return diagnostics; - } - async isEnabled() { - if (this._disposed) - return false; - let buf = this.nvim.createBuffer(this.bufnr); - let res = await buf.getVar("coc_diagnostic_disable"); - return res != 1; - } - dispose() { - this._disposed = true; - this.clear(); - } - }; - } -}); - -// src/diagnostic/collection.ts -var import_vscode_languageserver_protocol19, logger29, DiagnosticCollection; -var init_collection = __esm({ - "src/diagnostic/collection.ts"() { - import_vscode_languageserver_protocol19 = __toModule(require_main2()); - init_esm2(); - init_workspace(); - logger29 = require_logger2()("diagnostic-collection"); - DiagnosticCollection = class { - constructor(name2, onDispose) { - this.name = name2; - this.onDispose = onDispose; - this.diagnosticsMap = new Map(); - this._onDidDiagnosticsChange = new import_vscode_languageserver_protocol19.Emitter(); - this.onDidDiagnosticsChange = this._onDidDiagnosticsChange.event; - } - set(entries, diagnostics) { - let diagnosticsPerFile = new Map(); - if (!Array.isArray(entries)) { - let doc = workspace_default.getDocument(entries); - let uri = doc ? doc.uri : entries; - diagnosticsPerFile.set(uri, diagnostics || []); - } else { - for (let item of entries) { - let [uri, diagnostics2] = item; - let doc = workspace_default.getDocument(uri); - uri = doc ? doc.uri : uri; - if (diagnostics2 == null) { - diagnostics2 = []; - } else { - diagnostics2 = (diagnosticsPerFile.get(uri) || []).concat(diagnostics2); - } - diagnosticsPerFile.set(uri, diagnostics2); - } - } - for (let item of diagnosticsPerFile) { - let [uri, diagnostics2] = item; - uri = URI.parse(uri).toString(); - diagnostics2.forEach((o) => { - o.range = o.range || import_vscode_languageserver_protocol19.Range.create(0, 0, 0, 0); - o.message = o.message || ""; - o.source = o.source || this.name; - }); - this.diagnosticsMap.set(uri, diagnostics2); - this._onDidDiagnosticsChange.fire(uri); - } - } - delete(uri) { - this.diagnosticsMap.delete(uri); - this._onDidDiagnosticsChange.fire(uri); - } - clear() { - let uris = this.diagnosticsMap.keys(); - this.diagnosticsMap.clear(); - for (let uri of uris) { - this._onDidDiagnosticsChange.fire(uri); - } - } - forEach(callback, thisArg) { - for (let uri of this.diagnosticsMap.keys()) { - let diagnostics = this.diagnosticsMap.get(uri); - callback.call(thisArg, uri, diagnostics, this); - } - } - get(uri) { - let arr = this.diagnosticsMap.get(uri); - return arr == null ? [] : arr; - } - has(uri) { - return this.diagnosticsMap.has(uri); - } - dispose() { - this.clear(); - if (this.onDispose) - this.onDispose(); - this._onDidDiagnosticsChange.dispose(); - } - }; - } -}); - -// src/diagnostic/manager.ts -var import_debounce4, import_vscode_languageserver_protocol20, logger30, DiagnosticManager, manager_default; -var init_manager = __esm({ - "src/diagnostic/manager.ts"() { - import_debounce4 = __toModule(require_debounce()); - import_vscode_languageserver_protocol20 = __toModule(require_main2()); - init_esm2(); - init_events(); - init_floatFactory(); - init_util(); - init_position(); - init_window(); - init_workspace(); - init_buffer(); - init_collection(); - init_util3(); - logger30 = require_logger2()("diagnostic-manager"); - DiagnosticManager = class { - constructor() { - this.enabled = true; - this._onDidRefresh = new import_vscode_languageserver_protocol20.Emitter(); - this.onDidRefresh = this._onDidRefresh.event; - this.collections = []; - this.disposables = []; - } - init() { - this.setConfiguration(); - workspace_default.onDidChangeConfiguration((e) => { - this.setConfiguration(e); - }, null, this.disposables); - this.floatFactory = new FloatFactory(this.nvim); - this.buffers = workspace_default.registerBufferSync((doc) => { - if (doc.buftype !== "") - return void 0; - let buf = new DiagnosticBuffer(this.nvim, doc.bufnr, doc.uri, this.config, (diagnostics) => { - this._onDidRefresh.fire({ diagnostics, uri: buf.uri, bufnr: buf.bufnr }); - if (["never", "jump"].includes(this.config.enableMessage)) - return; - if (events_default.insertMode) - return; - this.echoMessage(true).logError(); - }); - let collections = this.getCollections(doc.uri); - if (this.enabled && collections.length) { - let diagnostics = this.getDiagnostics(doc.uri); - void buf.refresh(diagnostics); - } - return buf; - }); - workspace_default.onDidCloseTextDocument((e) => { - for (let collection of this.collections) { - collection.delete(e.uri); - } - }, null, this.disposables); - events_default.on("CursorMoved", (bufnr) => { - if (this.config.enableMessage != "always") - return; - if (!this.buffers.getItem(bufnr)) - return; - if (this.timer) - clearTimeout(this.timer); - this.timer = setTimeout(async () => { - await this.echoMessage(true); - }, this.config.messageDelay); - }, null, this.disposables); - let fn = (0, import_debounce4.default)((bufnr, cursor) => { - if (!this.config.virtualTextCurrentLineOnly) - return; - let buf = this.buffers.getItem(bufnr); - if (buf) - buf.showVirtualText(cursor[0]); - }, 100); - events_default.on("CursorMoved", fn, null, this.disposables); - this.disposables.push(import_vscode_languageserver_protocol20.Disposable.create(() => { - fn.clear(); - })); - let timer; - events_default.on("InsertLeave", async (bufnr) => { - if (this.config.refreshOnInsertMode || !this.autoRefresh) - return; - let doc = workspace_default.getDocument(bufnr); - if (!(doc == null ? void 0 : doc.attached)) - return; - doc._forceSync(); - timer = setTimeout(() => { - if (events_default.insertMode) - return; - for (let buf of this.buffers.items) { - void buf.refresh(this.getDiagnostics(buf.uri), false); - } - }, Math.max(0, 500 - Date.now() + events_default.lastChangeTs)); - }, null, this.disposables); - let clear = () => { - if (timer) - clearTimeout(timer); - }; - this.disposables.push({ dispose: clear }); - events_default.on("InsertEnter", clear, null, this.disposables); - events_default.on("BufEnter", async () => { - if (this.timer) - clearTimeout(this.timer); - }, null, this.disposables); - let errorItems = workspace_default.configurations.errorItems; - this.setConfigurationErrors(errorItems); - workspace_default.configurations.onError((items) => { - this.setConfigurationErrors(items); - }, null, this.disposables); - } - defineSigns() { - let { nvim } = this; - let { enableHighlightLineNumber, enableSign } = this.config; - if (!enableSign) - return; - nvim.pauseNotification(); - for (let kind of ["Error", "Warning", "Info", "Hint"]) { - let signText = this.config[kind.toLowerCase() + "Sign"]; - let cmd = `sign define Coc${kind} linehl=Coc${kind}Line`; - if (signText) - cmd += ` texthl=Coc${kind}Sign text=${signText}`; - if (enableHighlightLineNumber) - cmd += ` numhl=Coc${kind}Sign`; - nvim.command(cmd, true); - } - void nvim.resumeNotification(false, true); - } - async setLocationlist(bufnr) { - let buf = this.buffers.getItem(bufnr); - let diagnosticsMap = buf ? this.getDiagnostics(buf.uri) : {}; - let items = []; - for (let diagnostics of Object.values(diagnosticsMap)) { - for (let diagnostic of diagnostics) { - let item = getLocationListItem(bufnr, diagnostic); - items.push(item); - } - } - let curr = await this.nvim.call("getloclist", [0, { title: 1 }]); - let action = curr.title && curr.title.indexOf("Diagnostics of coc") != -1 ? "r" : " "; - await this.nvim.call("setloclist", [0, [], action, { title: "Diagnostics of coc", items }]); - } - setConfigurationErrors(errorItems) { - let collection = this.create("config"); - if (errorItems == null ? void 0 : errorItems.length) { - let entries = new Map(); - for (let item of errorItems) { - let { uri } = item.location; - let diagnostics = entries.get(uri) || []; - diagnostics.push(import_vscode_languageserver_protocol20.Diagnostic.create(item.location.range, item.message, import_vscode_languageserver_protocol20.DiagnosticSeverity.Error)); - entries.set(uri, diagnostics); - } - collection.set(Array.from(entries)); - } else { - collection.clear(); - } - } - create(name2) { - let collection = this.getCollectionByName(name2); - if (collection) - return collection; - collection = new DiagnosticCollection(name2, () => { - let idx = this.collections.findIndex((o) => o == collection); - if (idx !== -1) - this.collections.splice(idx, 1); - }); - this.collections.push(collection); - collection.onDidDiagnosticsChange((uri) => { - let buf = this.buffers.getItem(uri); - if (!this.autoRefresh || !buf) - return; - if (events_default.insertMode && !this.config.refreshOnInsertMode) - return; - void buf.refresh(this.getDiagnostics(uri, name2), true); - }); - return collection; - } - getSortedRanges(uri, severity) { - let collections = this.getCollections(uri); - let res = []; - let level = severity ? severityLevel(severity) : 0; - for (let collection of collections) { - let diagnostics = collection.get(uri); - if (level) { - diagnostics = diagnostics.filter((o) => o.severity == level); - } else { - let minLevel = this.config.level; - if (minLevel && minLevel < import_vscode_languageserver_protocol20.DiagnosticSeverity.Hint) { - diagnostics = diagnostics.filter((o) => { - if (o.severity && o.severity > minLevel) { - return false; - } - return true; - }); - } - } - let ranges = diagnostics.map((o) => o.range); - res.push(...ranges); - } - res.sort((a, b) => { - if (a.start.line != b.start.line) { - return a.start.line - b.start.line; - } - return a.start.character - b.start.character; - }); - return res; - } - getDiagnostics(uri, collection) { - let res = {}; - let collections = collection ? [this.getCollectionByName(collection)] : this.getCollections(uri); - let { level, showUnused, showDeprecated } = this.config; - for (let collection2 of collections) { - if (!collection2) - continue; - let items = collection2.get(uri) || []; - if (items.length) { - items = items.filter((d) => { - var _a2, _b; - if (level && d.severity && d.severity > level) { - return false; - } - if (!showUnused && ((_a2 = d.tags) == null ? void 0 : _a2.includes(import_vscode_languageserver_protocol20.DiagnosticTag.Unnecessary))) { - return false; - } - if (!showDeprecated && ((_b = d.tags) == null ? void 0 : _b.includes(import_vscode_languageserver_protocol20.DiagnosticTag.Deprecated))) { - return false; - } - return true; - }); - items.sort((a, b) => { - return comparePosition(a.range.start, b.range.start); - }); - } - res[collection2.name] = items; - } - return res; - } - getDiagnosticsInRange(document2, range) { - let collections = this.getCollections(document2.uri); - let res = []; - for (let collection of collections) { - let items = collection.get(document2.uri); - if (!items) - continue; - for (let item of items) { - if (rangeIntersect(item.range, range)) { - res.push(item); - } - } - } - return res; - } - async preview() { - let diagnostics = await this.getCurrentDiagnostics(); - if (diagnostics.length == 0) { - this.nvim.command("pclose", true); - return; - } - let lines = []; - for (let diagnostic of diagnostics) { - let { source, code, severity, message } = diagnostic; - let s = getSeverityName(severity)[0]; - lines.push(`[${source}${code ? " " + code : ""}] [${s}]`); - lines.push(...message.split(/\r?\n/)); - lines.push(""); - } - this.nvim.call("coc#util#preview_info", [lines, "txt"], true); - } - async jumpPrevious(severity) { - let buffer = await this.nvim.buffer; - let document2 = workspace_default.getDocument(buffer.id); - if (!document2) - return; - let curpos = await window_default.getCursorPosition(); - let ranges = this.getSortedRanges(document2.uri, severity); - let pos; - for (let i = ranges.length - 1; i >= 0; i--) { - let end = ranges[i].end; - if (comparePosition(end, curpos) < 0) { - pos = ranges[i].start; - break; - } else if (i == 0) { - let wrapscan = await this.nvim.getOption("wrapscan"); - if (wrapscan) - pos = ranges[ranges.length - 1].start; - } - } - if (pos) { - await window_default.moveTo(pos); - if (this.config.enableMessage == "never") - return; - await this.echoMessage(false); - } - } - async jumpNext(severity) { - let buffer = await this.nvim.buffer; - let document2 = workspace_default.getDocument(buffer.id); - let curpos = await window_default.getCursorPosition(); - let ranges = this.getSortedRanges(document2.uri, severity); - let pos; - for (let i = 0; i <= ranges.length - 1; i++) { - let start = ranges[i].start; - if (comparePosition(start, curpos) > 0) { - pos = ranges[i].start; - break; - } else if (i == ranges.length - 1) { - let wrapscan = await this.nvim.getOption("wrapscan"); - if (wrapscan) - pos = ranges[0].start; - } - } - if (pos) { - await window_default.moveTo(pos); - if (this.config.enableMessage == "never") - return; - await this.echoMessage(false); - } - } - getDiagnosticList() { - let res = []; - const { level, showUnused, showDeprecated } = this.config; - for (let collection of this.collections) { - collection.forEach((uri, diagnostics) => { - var _a2, _b; - let file = URI.parse(uri).fsPath; - for (let diagnostic of diagnostics) { - if (diagnostic.severity && diagnostic.severity > level) { - continue; - } - if (!showUnused && ((_a2 = diagnostic.tags) == null ? void 0 : _a2.includes(import_vscode_languageserver_protocol20.DiagnosticTag.Unnecessary))) { - continue; - } - if (!showDeprecated && ((_b = diagnostic.tags) == null ? void 0 : _b.includes(import_vscode_languageserver_protocol20.DiagnosticTag.Deprecated))) { - continue; - } - let { start, end } = diagnostic.range; - let o = { - file, - lnum: start.line + 1, - end_lnum: end.line + 1, - col: start.character + 1, - end_col: end.character + 1, - code: diagnostic.code, - source: diagnostic.source || collection.name, - message: diagnostic.message, - severity: getSeverityName(diagnostic.severity), - level: diagnostic.severity || 0, - location: import_vscode_languageserver_protocol20.Location.create(uri, diagnostic.range) - }; - res.push(o); - } - }); - } - res.sort((a, b) => { - if (a.level !== b.level) { - return a.level - b.level; - } - if (a.file !== b.file) { - return a.file > b.file ? 1 : -1; - } else { - if (a.lnum != b.lnum) { - return a.lnum - b.lnum; - } - return a.col - b.col; - } - }); - return res; - } - getDiagnosticsAt(bufnr, cursor, atEnd = false, lastline = false) { - let buffer = this.buffers.getItem(bufnr); - if (!buffer) - return []; - let pos = import_vscode_languageserver_protocol20.Position.create(cursor[0], cursor[1]); - let res = buffer.getDiagnosticsAt(pos, this.config.checkCurrentLine); - if (this.config.checkCurrentLine || res.length) - return res; - if (atEnd) { - pos = import_vscode_languageserver_protocol20.Position.create(cursor[0], cursor[1] + 1); - res = buffer.getDiagnosticsAt(pos, false); - if (res.length) - return res; - } - if (lastline && cursor[1] == 0) { - pos = import_vscode_languageserver_protocol20.Position.create(cursor[0] + 1, 0); - res = buffer.getDiagnosticsAt(pos, false); - } - return res; - } - async getCurrentDiagnostics() { - let [bufnr, cursor, eol, lastline] = await this.nvim.eval(`[bufnr("%"),coc#cursor#position(),col('.')==col('$')-1,line('.')==line('$')]`); - return this.getDiagnosticsAt(bufnr, cursor, eol == 1, lastline == 1); - } - async echoMessage(truncate = false) { - const config = this.config; - if (!this.enabled || config.displayByAle) - return; - if (this.timer) - clearTimeout(this.timer); - let useFloat = config.messageTarget == "float"; - let [filetype, mode] = await this.nvim.eval(`[&filetype,mode()]`); - if (mode != "n") - return; - let diagnostics = await this.getCurrentDiagnostics(); - if (diagnostics.length == 0) { - if (useFloat) - this.floatFactory.close(); - return; - } - if (truncate && workspace_default.insertMode) - return; - let docs = []; - let ft = ""; - if (Object.keys(config.filetypeMap).length > 0) { - const defaultFiletype = config.filetypeMap["default"] || ""; - ft = config.filetypeMap[filetype] || (defaultFiletype == "bufferType" ? filetype : defaultFiletype); - } - diagnostics.forEach((diagnostic) => { - let { source, code, severity, message } = diagnostic; - let s = getSeverityName(severity)[0]; - const codeStr = code ? " " + code : ""; - const str = config.format.replace("%source", source).replace("%code", codeStr).replace("%severity", s).replace("%message", message); - let filetype2 = "Error"; - if (ft === "") { - switch (severity) { - case import_vscode_languageserver_protocol20.DiagnosticSeverity.Hint: - filetype2 = "Hint"; - break; - case import_vscode_languageserver_protocol20.DiagnosticSeverity.Warning: - filetype2 = "Warning"; - break; - case import_vscode_languageserver_protocol20.DiagnosticSeverity.Information: - filetype2 = "Info"; - break; - } - } else { - filetype2 = ft; - } - docs.push({ filetype: filetype2, content: str }); - }); - if (useFloat) { - let config2 = this.floatFactory.applyFloatConfig({ modes: ["n"], maxWidth: 80 }, this.config.floatConfig); - await this.floatFactory.show(docs, config2); - } else { - let lines = docs.map((d) => d.content).join("\n").split(/\r?\n/); - if (lines.length) { - await this.nvim.command('echo ""'); - await window_default.echoLines(lines, truncate); - } - } - } - async jumpRelated() { - let diagnostics = await this.getCurrentDiagnostics(); - if (!diagnostics) - return; - let diagnostic = diagnostics.find((o) => o.relatedInformation != null); - if (!diagnostic) - return; - let locations = diagnostic.relatedInformation.map((o) => o.location); - if (locations.length == 1) { - await workspace_default.jumpTo(locations[0].uri, locations[0].range.start); - } else if (locations.length > 1) { - await workspace_default.showLocations(locations); - } - } - reset() { - if (this.timer) { - clearTimeout(this.timer); - } - this.buffers.reset(); - for (let collection of this.collections) { - collection.dispose(); - } - this.collections = []; - } - dispose() { - var _a2; - this.buffers.dispose(); - if (this.timer) { - clearTimeout(this.timer); - } - for (let collection of this.collections) { - collection.dispose(); - } - (_a2 = this.floatFactory) == null ? void 0 : _a2.close(); - this.collections = []; - disposeAll(this.disposables); - } - get nvim() { - return workspace_default.nvim; - } - setConfiguration(event) { - if (event && !event.affectsConfiguration("diagnostic")) - return; - let config = workspace_default.getConfiguration("diagnostic"); - let messageTarget = config.get("messageTarget", "float"); - if (messageTarget == "float" && !workspace_default.env.floating && !workspace_default.env.textprop) { - messageTarget = "echo"; - } - let enableHighlightLineNumber = config.get("enableHighlightLineNumber", true); - if (!workspace_default.isNvim) - enableHighlightLineNumber = false; - this.config = { - floatConfig: config.get("floatConfig", {}), - messageTarget, - enableHighlightLineNumber, - highlighLimit: config.get("highlighLimit", 1e3), - autoRefresh: config.get("autoRefresh", true), - virtualTextSrcId: workspace_default.createNameSpace("diagnostic-virtualText"), - checkCurrentLine: config.get("checkCurrentLine", false), - enableSign: workspace_default.env.sign && config.get("enableSign", true), - locationlistUpdate: config.get("locationlistUpdate", true), - enableMessage: config.get("enableMessage", "always"), - messageDelay: config.get("messageDelay", 200), - virtualText: config.get("virtualText", false) && this.nvim.hasFunction("nvim_buf_set_virtual_text"), - virtualTextCurrentLineOnly: config.get("virtualTextCurrentLineOnly", true), - virtualTextPrefix: config.get("virtualTextPrefix", " "), - virtualTextLineSeparator: config.get("virtualTextLineSeparator", " \\ "), - virtualTextLines: config.get("virtualTextLines", 3), - displayByAle: config.get("displayByAle", false), - level: severityLevel(config.get("level", "hint")), - signPriority: config.get("signPriority", 10), - errorSign: config.get("errorSign", ">>"), - warningSign: config.get("warningSign", ">>"), - infoSign: config.get("infoSign", ">>"), - hintSign: config.get("hintSign", ">>"), - refreshOnInsertMode: config.get("refreshOnInsertMode", false), - filetypeMap: config.get("filetypeMap", {}), - showUnused: config.get("showUnused", true), - showDeprecated: config.get("showDeprecated", true), - format: config.get("format", "[%source%code] [%severity] %message") - }; - this.enabled = config.get("enable", true); - this.defineSigns(); - } - getCollectionByName(name2) { - return this.collections.find((o) => o.name == name2); - } - getCollections(uri) { - return this.collections.filter((c) => c.has(uri)); - } - toggleDiagnostic() { - let { enabled } = this; - this.enabled = !enabled; - for (let buf of this.buffers.items) { - if (this.enabled) { - void this.refreshBuffer(buf.uri, true); - } else { - buf.clear(); - } - } - } - async toggleDiagnosticBuffer(bufnr) { - if (!this.enabled) - return; - let buf = this.buffers.getItem(bufnr); - if (buf) { - let isEnabled = await buf.isEnabled(); - await this.nvim.call("setbufvar", [bufnr, "coc_diagnostic_disable", isEnabled ? 1 : 0]); - if (isEnabled) { - buf.clear(); - } else { - void this.refreshBuffer(bufnr, true); - } - } - } - get autoRefresh() { - return this.enabled && this.config.autoRefresh; - } - async refreshBuffer(uri, force = false) { - let buf = this.buffers.getItem(uri); - if (!buf) - return false; - await buf.refresh(this.getDiagnostics(buf.uri), force); - return true; - } - refresh(bufnr) { - if (!bufnr) { - for (let item of this.buffers.items) { - void this.refreshBuffer(item.uri, true); - } - } else { - let item = this.buffers.getItem(bufnr); - if (item) { - void this.refreshBuffer(item.uri, true); - } - } - } - }; - manager_default = new DiagnosticManager(); - } -}); - -// src/util/charCode.ts -var CharCode; -var init_charCode = __esm({ - "src/util/charCode.ts"() { - (function(CharCode2) { - CharCode2[CharCode2["Null"] = 0] = "Null"; - CharCode2[CharCode2["Backspace"] = 8] = "Backspace"; - CharCode2[CharCode2["Tab"] = 9] = "Tab"; - CharCode2[CharCode2["LineFeed"] = 10] = "LineFeed"; - CharCode2[CharCode2["CarriageReturn"] = 13] = "CarriageReturn"; - CharCode2[CharCode2["Space"] = 32] = "Space"; - CharCode2[CharCode2["ExclamationMark"] = 33] = "ExclamationMark"; - CharCode2[CharCode2["DoubleQuote"] = 34] = "DoubleQuote"; - CharCode2[CharCode2["Hash"] = 35] = "Hash"; - CharCode2[CharCode2["DollarSign"] = 36] = "DollarSign"; - CharCode2[CharCode2["PercentSign"] = 37] = "PercentSign"; - CharCode2[CharCode2["Ampersand"] = 38] = "Ampersand"; - CharCode2[CharCode2["SingleQuote"] = 39] = "SingleQuote"; - CharCode2[CharCode2["OpenParen"] = 40] = "OpenParen"; - CharCode2[CharCode2["CloseParen"] = 41] = "CloseParen"; - CharCode2[CharCode2["Asterisk"] = 42] = "Asterisk"; - CharCode2[CharCode2["Plus"] = 43] = "Plus"; - CharCode2[CharCode2["Comma"] = 44] = "Comma"; - CharCode2[CharCode2["Dash"] = 45] = "Dash"; - CharCode2[CharCode2["Period"] = 46] = "Period"; - CharCode2[CharCode2["Slash"] = 47] = "Slash"; - CharCode2[CharCode2["Digit0"] = 48] = "Digit0"; - CharCode2[CharCode2["Digit1"] = 49] = "Digit1"; - CharCode2[CharCode2["Digit2"] = 50] = "Digit2"; - CharCode2[CharCode2["Digit3"] = 51] = "Digit3"; - CharCode2[CharCode2["Digit4"] = 52] = "Digit4"; - CharCode2[CharCode2["Digit5"] = 53] = "Digit5"; - CharCode2[CharCode2["Digit6"] = 54] = "Digit6"; - CharCode2[CharCode2["Digit7"] = 55] = "Digit7"; - CharCode2[CharCode2["Digit8"] = 56] = "Digit8"; - CharCode2[CharCode2["Digit9"] = 57] = "Digit9"; - CharCode2[CharCode2["Colon"] = 58] = "Colon"; - CharCode2[CharCode2["Semicolon"] = 59] = "Semicolon"; - CharCode2[CharCode2["LessThan"] = 60] = "LessThan"; - CharCode2[CharCode2["Equals"] = 61] = "Equals"; - CharCode2[CharCode2["GreaterThan"] = 62] = "GreaterThan"; - CharCode2[CharCode2["QuestionMark"] = 63] = "QuestionMark"; - CharCode2[CharCode2["AtSign"] = 64] = "AtSign"; - CharCode2[CharCode2["A"] = 65] = "A"; - CharCode2[CharCode2["B"] = 66] = "B"; - CharCode2[CharCode2["C"] = 67] = "C"; - CharCode2[CharCode2["D"] = 68] = "D"; - CharCode2[CharCode2["E"] = 69] = "E"; - CharCode2[CharCode2["F"] = 70] = "F"; - CharCode2[CharCode2["G"] = 71] = "G"; - CharCode2[CharCode2["H"] = 72] = "H"; - CharCode2[CharCode2["I"] = 73] = "I"; - CharCode2[CharCode2["J"] = 74] = "J"; - CharCode2[CharCode2["K"] = 75] = "K"; - CharCode2[CharCode2["L"] = 76] = "L"; - CharCode2[CharCode2["M"] = 77] = "M"; - CharCode2[CharCode2["N"] = 78] = "N"; - CharCode2[CharCode2["O"] = 79] = "O"; - CharCode2[CharCode2["P"] = 80] = "P"; - CharCode2[CharCode2["Q"] = 81] = "Q"; - CharCode2[CharCode2["R"] = 82] = "R"; - CharCode2[CharCode2["S"] = 83] = "S"; - CharCode2[CharCode2["T"] = 84] = "T"; - CharCode2[CharCode2["U"] = 85] = "U"; - CharCode2[CharCode2["V"] = 86] = "V"; - CharCode2[CharCode2["W"] = 87] = "W"; - CharCode2[CharCode2["X"] = 88] = "X"; - CharCode2[CharCode2["Y"] = 89] = "Y"; - CharCode2[CharCode2["Z"] = 90] = "Z"; - CharCode2[CharCode2["OpenSquareBracket"] = 91] = "OpenSquareBracket"; - CharCode2[CharCode2["Backslash"] = 92] = "Backslash"; - CharCode2[CharCode2["CloseSquareBracket"] = 93] = "CloseSquareBracket"; - CharCode2[CharCode2["Caret"] = 94] = "Caret"; - CharCode2[CharCode2["Underline"] = 95] = "Underline"; - CharCode2[CharCode2["BackTick"] = 96] = "BackTick"; - CharCode2[CharCode2["a"] = 97] = "a"; - CharCode2[CharCode2["b"] = 98] = "b"; - CharCode2[CharCode2["c"] = 99] = "c"; - CharCode2[CharCode2["d"] = 100] = "d"; - CharCode2[CharCode2["e"] = 101] = "e"; - CharCode2[CharCode2["f"] = 102] = "f"; - CharCode2[CharCode2["g"] = 103] = "g"; - CharCode2[CharCode2["h"] = 104] = "h"; - CharCode2[CharCode2["i"] = 105] = "i"; - CharCode2[CharCode2["j"] = 106] = "j"; - CharCode2[CharCode2["k"] = 107] = "k"; - CharCode2[CharCode2["l"] = 108] = "l"; - CharCode2[CharCode2["m"] = 109] = "m"; - CharCode2[CharCode2["n"] = 110] = "n"; - CharCode2[CharCode2["o"] = 111] = "o"; - CharCode2[CharCode2["p"] = 112] = "p"; - CharCode2[CharCode2["q"] = 113] = "q"; - CharCode2[CharCode2["r"] = 114] = "r"; - CharCode2[CharCode2["s"] = 115] = "s"; - CharCode2[CharCode2["t"] = 116] = "t"; - CharCode2[CharCode2["u"] = 117] = "u"; - CharCode2[CharCode2["v"] = 118] = "v"; - CharCode2[CharCode2["w"] = 119] = "w"; - CharCode2[CharCode2["x"] = 120] = "x"; - CharCode2[CharCode2["y"] = 121] = "y"; - CharCode2[CharCode2["z"] = 122] = "z"; - CharCode2[CharCode2["OpenCurlyBrace"] = 123] = "OpenCurlyBrace"; - CharCode2[CharCode2["Pipe"] = 124] = "Pipe"; - CharCode2[CharCode2["CloseCurlyBrace"] = 125] = "CloseCurlyBrace"; - CharCode2[CharCode2["Tilde"] = 126] = "Tilde"; - CharCode2[CharCode2["U_Combining_Grave_Accent"] = 768] = "U_Combining_Grave_Accent"; - CharCode2[CharCode2["U_Combining_Acute_Accent"] = 769] = "U_Combining_Acute_Accent"; - CharCode2[CharCode2["U_Combining_Circumflex_Accent"] = 770] = "U_Combining_Circumflex_Accent"; - CharCode2[CharCode2["U_Combining_Tilde"] = 771] = "U_Combining_Tilde"; - CharCode2[CharCode2["U_Combining_Macron"] = 772] = "U_Combining_Macron"; - CharCode2[CharCode2["U_Combining_Overline"] = 773] = "U_Combining_Overline"; - CharCode2[CharCode2["U_Combining_Breve"] = 774] = "U_Combining_Breve"; - CharCode2[CharCode2["U_Combining_Dot_Above"] = 775] = "U_Combining_Dot_Above"; - CharCode2[CharCode2["U_Combining_Diaeresis"] = 776] = "U_Combining_Diaeresis"; - CharCode2[CharCode2["U_Combining_Hook_Above"] = 777] = "U_Combining_Hook_Above"; - CharCode2[CharCode2["U_Combining_Ring_Above"] = 778] = "U_Combining_Ring_Above"; - CharCode2[CharCode2["U_Combining_Double_Acute_Accent"] = 779] = "U_Combining_Double_Acute_Accent"; - CharCode2[CharCode2["U_Combining_Caron"] = 780] = "U_Combining_Caron"; - CharCode2[CharCode2["U_Combining_Vertical_Line_Above"] = 781] = "U_Combining_Vertical_Line_Above"; - CharCode2[CharCode2["U_Combining_Double_Vertical_Line_Above"] = 782] = "U_Combining_Double_Vertical_Line_Above"; - CharCode2[CharCode2["U_Combining_Double_Grave_Accent"] = 783] = "U_Combining_Double_Grave_Accent"; - CharCode2[CharCode2["U_Combining_Candrabindu"] = 784] = "U_Combining_Candrabindu"; - CharCode2[CharCode2["U_Combining_Inverted_Breve"] = 785] = "U_Combining_Inverted_Breve"; - CharCode2[CharCode2["U_Combining_Turned_Comma_Above"] = 786] = "U_Combining_Turned_Comma_Above"; - CharCode2[CharCode2["U_Combining_Comma_Above"] = 787] = "U_Combining_Comma_Above"; - CharCode2[CharCode2["U_Combining_Reversed_Comma_Above"] = 788] = "U_Combining_Reversed_Comma_Above"; - CharCode2[CharCode2["U_Combining_Comma_Above_Right"] = 789] = "U_Combining_Comma_Above_Right"; - CharCode2[CharCode2["U_Combining_Grave_Accent_Below"] = 790] = "U_Combining_Grave_Accent_Below"; - CharCode2[CharCode2["U_Combining_Acute_Accent_Below"] = 791] = "U_Combining_Acute_Accent_Below"; - CharCode2[CharCode2["U_Combining_Left_Tack_Below"] = 792] = "U_Combining_Left_Tack_Below"; - CharCode2[CharCode2["U_Combining_Right_Tack_Below"] = 793] = "U_Combining_Right_Tack_Below"; - CharCode2[CharCode2["U_Combining_Left_Angle_Above"] = 794] = "U_Combining_Left_Angle_Above"; - CharCode2[CharCode2["U_Combining_Horn"] = 795] = "U_Combining_Horn"; - CharCode2[CharCode2["U_Combining_Left_Half_Ring_Below"] = 796] = "U_Combining_Left_Half_Ring_Below"; - CharCode2[CharCode2["U_Combining_Up_Tack_Below"] = 797] = "U_Combining_Up_Tack_Below"; - CharCode2[CharCode2["U_Combining_Down_Tack_Below"] = 798] = "U_Combining_Down_Tack_Below"; - CharCode2[CharCode2["U_Combining_Plus_Sign_Below"] = 799] = "U_Combining_Plus_Sign_Below"; - CharCode2[CharCode2["U_Combining_Minus_Sign_Below"] = 800] = "U_Combining_Minus_Sign_Below"; - CharCode2[CharCode2["U_Combining_Palatalized_Hook_Below"] = 801] = "U_Combining_Palatalized_Hook_Below"; - CharCode2[CharCode2["U_Combining_Retroflex_Hook_Below"] = 802] = "U_Combining_Retroflex_Hook_Below"; - CharCode2[CharCode2["U_Combining_Dot_Below"] = 803] = "U_Combining_Dot_Below"; - CharCode2[CharCode2["U_Combining_Diaeresis_Below"] = 804] = "U_Combining_Diaeresis_Below"; - CharCode2[CharCode2["U_Combining_Ring_Below"] = 805] = "U_Combining_Ring_Below"; - CharCode2[CharCode2["U_Combining_Comma_Below"] = 806] = "U_Combining_Comma_Below"; - CharCode2[CharCode2["U_Combining_Cedilla"] = 807] = "U_Combining_Cedilla"; - CharCode2[CharCode2["U_Combining_Ogonek"] = 808] = "U_Combining_Ogonek"; - CharCode2[CharCode2["U_Combining_Vertical_Line_Below"] = 809] = "U_Combining_Vertical_Line_Below"; - CharCode2[CharCode2["U_Combining_Bridge_Below"] = 810] = "U_Combining_Bridge_Below"; - CharCode2[CharCode2["U_Combining_Inverted_Double_Arch_Below"] = 811] = "U_Combining_Inverted_Double_Arch_Below"; - CharCode2[CharCode2["U_Combining_Caron_Below"] = 812] = "U_Combining_Caron_Below"; - CharCode2[CharCode2["U_Combining_Circumflex_Accent_Below"] = 813] = "U_Combining_Circumflex_Accent_Below"; - CharCode2[CharCode2["U_Combining_Breve_Below"] = 814] = "U_Combining_Breve_Below"; - CharCode2[CharCode2["U_Combining_Inverted_Breve_Below"] = 815] = "U_Combining_Inverted_Breve_Below"; - CharCode2[CharCode2["U_Combining_Tilde_Below"] = 816] = "U_Combining_Tilde_Below"; - CharCode2[CharCode2["U_Combining_Macron_Below"] = 817] = "U_Combining_Macron_Below"; - CharCode2[CharCode2["U_Combining_Low_Line"] = 818] = "U_Combining_Low_Line"; - CharCode2[CharCode2["U_Combining_Double_Low_Line"] = 819] = "U_Combining_Double_Low_Line"; - CharCode2[CharCode2["U_Combining_Tilde_Overlay"] = 820] = "U_Combining_Tilde_Overlay"; - CharCode2[CharCode2["U_Combining_Short_Stroke_Overlay"] = 821] = "U_Combining_Short_Stroke_Overlay"; - CharCode2[CharCode2["U_Combining_Long_Stroke_Overlay"] = 822] = "U_Combining_Long_Stroke_Overlay"; - CharCode2[CharCode2["U_Combining_Short_Solidus_Overlay"] = 823] = "U_Combining_Short_Solidus_Overlay"; - CharCode2[CharCode2["U_Combining_Long_Solidus_Overlay"] = 824] = "U_Combining_Long_Solidus_Overlay"; - CharCode2[CharCode2["U_Combining_Right_Half_Ring_Below"] = 825] = "U_Combining_Right_Half_Ring_Below"; - CharCode2[CharCode2["U_Combining_Inverted_Bridge_Below"] = 826] = "U_Combining_Inverted_Bridge_Below"; - CharCode2[CharCode2["U_Combining_Square_Below"] = 827] = "U_Combining_Square_Below"; - CharCode2[CharCode2["U_Combining_Seagull_Below"] = 828] = "U_Combining_Seagull_Below"; - CharCode2[CharCode2["U_Combining_X_Above"] = 829] = "U_Combining_X_Above"; - CharCode2[CharCode2["U_Combining_Vertical_Tilde"] = 830] = "U_Combining_Vertical_Tilde"; - CharCode2[CharCode2["U_Combining_Double_Overline"] = 831] = "U_Combining_Double_Overline"; - CharCode2[CharCode2["U_Combining_Grave_Tone_Mark"] = 832] = "U_Combining_Grave_Tone_Mark"; - CharCode2[CharCode2["U_Combining_Acute_Tone_Mark"] = 833] = "U_Combining_Acute_Tone_Mark"; - CharCode2[CharCode2["U_Combining_Greek_Perispomeni"] = 834] = "U_Combining_Greek_Perispomeni"; - CharCode2[CharCode2["U_Combining_Greek_Koronis"] = 835] = "U_Combining_Greek_Koronis"; - CharCode2[CharCode2["U_Combining_Greek_Dialytika_Tonos"] = 836] = "U_Combining_Greek_Dialytika_Tonos"; - CharCode2[CharCode2["U_Combining_Greek_Ypogegrammeni"] = 837] = "U_Combining_Greek_Ypogegrammeni"; - CharCode2[CharCode2["U_Combining_Bridge_Above"] = 838] = "U_Combining_Bridge_Above"; - CharCode2[CharCode2["U_Combining_Equals_Sign_Below"] = 839] = "U_Combining_Equals_Sign_Below"; - CharCode2[CharCode2["U_Combining_Double_Vertical_Line_Below"] = 840] = "U_Combining_Double_Vertical_Line_Below"; - CharCode2[CharCode2["U_Combining_Left_Angle_Below"] = 841] = "U_Combining_Left_Angle_Below"; - CharCode2[CharCode2["U_Combining_Not_Tilde_Above"] = 842] = "U_Combining_Not_Tilde_Above"; - CharCode2[CharCode2["U_Combining_Homothetic_Above"] = 843] = "U_Combining_Homothetic_Above"; - CharCode2[CharCode2["U_Combining_Almost_Equal_To_Above"] = 844] = "U_Combining_Almost_Equal_To_Above"; - CharCode2[CharCode2["U_Combining_Left_Right_Arrow_Below"] = 845] = "U_Combining_Left_Right_Arrow_Below"; - CharCode2[CharCode2["U_Combining_Upwards_Arrow_Below"] = 846] = "U_Combining_Upwards_Arrow_Below"; - CharCode2[CharCode2["U_Combining_Grapheme_Joiner"] = 847] = "U_Combining_Grapheme_Joiner"; - CharCode2[CharCode2["U_Combining_Right_Arrowhead_Above"] = 848] = "U_Combining_Right_Arrowhead_Above"; - CharCode2[CharCode2["U_Combining_Left_Half_Ring_Above"] = 849] = "U_Combining_Left_Half_Ring_Above"; - CharCode2[CharCode2["U_Combining_Fermata"] = 850] = "U_Combining_Fermata"; - CharCode2[CharCode2["U_Combining_X_Below"] = 851] = "U_Combining_X_Below"; - CharCode2[CharCode2["U_Combining_Left_Arrowhead_Below"] = 852] = "U_Combining_Left_Arrowhead_Below"; - CharCode2[CharCode2["U_Combining_Right_Arrowhead_Below"] = 853] = "U_Combining_Right_Arrowhead_Below"; - CharCode2[CharCode2["U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below"] = 854] = "U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below"; - CharCode2[CharCode2["U_Combining_Right_Half_Ring_Above"] = 855] = "U_Combining_Right_Half_Ring_Above"; - CharCode2[CharCode2["U_Combining_Dot_Above_Right"] = 856] = "U_Combining_Dot_Above_Right"; - CharCode2[CharCode2["U_Combining_Asterisk_Below"] = 857] = "U_Combining_Asterisk_Below"; - CharCode2[CharCode2["U_Combining_Double_Ring_Below"] = 858] = "U_Combining_Double_Ring_Below"; - CharCode2[CharCode2["U_Combining_Zigzag_Above"] = 859] = "U_Combining_Zigzag_Above"; - CharCode2[CharCode2["U_Combining_Double_Breve_Below"] = 860] = "U_Combining_Double_Breve_Below"; - CharCode2[CharCode2["U_Combining_Double_Breve"] = 861] = "U_Combining_Double_Breve"; - CharCode2[CharCode2["U_Combining_Double_Macron"] = 862] = "U_Combining_Double_Macron"; - CharCode2[CharCode2["U_Combining_Double_Macron_Below"] = 863] = "U_Combining_Double_Macron_Below"; - CharCode2[CharCode2["U_Combining_Double_Tilde"] = 864] = "U_Combining_Double_Tilde"; - CharCode2[CharCode2["U_Combining_Double_Inverted_Breve"] = 865] = "U_Combining_Double_Inverted_Breve"; - CharCode2[CharCode2["U_Combining_Double_Rightwards_Arrow_Below"] = 866] = "U_Combining_Double_Rightwards_Arrow_Below"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_A"] = 867] = "U_Combining_Latin_Small_Letter_A"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_E"] = 868] = "U_Combining_Latin_Small_Letter_E"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_I"] = 869] = "U_Combining_Latin_Small_Letter_I"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_O"] = 870] = "U_Combining_Latin_Small_Letter_O"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_U"] = 871] = "U_Combining_Latin_Small_Letter_U"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_C"] = 872] = "U_Combining_Latin_Small_Letter_C"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_D"] = 873] = "U_Combining_Latin_Small_Letter_D"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_H"] = 874] = "U_Combining_Latin_Small_Letter_H"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_M"] = 875] = "U_Combining_Latin_Small_Letter_M"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_R"] = 876] = "U_Combining_Latin_Small_Letter_R"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_T"] = 877] = "U_Combining_Latin_Small_Letter_T"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_V"] = 878] = "U_Combining_Latin_Small_Letter_V"; - CharCode2[CharCode2["U_Combining_Latin_Small_Letter_X"] = 879] = "U_Combining_Latin_Small_Letter_X"; - CharCode2[CharCode2["LINE_SEPARATOR_2028"] = 8232] = "LINE_SEPARATOR_2028"; - CharCode2[CharCode2["U_CIRCUMFLEX"] = 94] = "U_CIRCUMFLEX"; - CharCode2[CharCode2["U_GRAVE_ACCENT"] = 96] = "U_GRAVE_ACCENT"; - CharCode2[CharCode2["U_DIAERESIS"] = 168] = "U_DIAERESIS"; - CharCode2[CharCode2["U_MACRON"] = 175] = "U_MACRON"; - CharCode2[CharCode2["U_ACUTE_ACCENT"] = 180] = "U_ACUTE_ACCENT"; - CharCode2[CharCode2["U_CEDILLA"] = 184] = "U_CEDILLA"; - CharCode2[CharCode2["U_MODIFIER_LETTER_LEFT_ARROWHEAD"] = 706] = "U_MODIFIER_LETTER_LEFT_ARROWHEAD"; - CharCode2[CharCode2["U_MODIFIER_LETTER_RIGHT_ARROWHEAD"] = 707] = "U_MODIFIER_LETTER_RIGHT_ARROWHEAD"; - CharCode2[CharCode2["U_MODIFIER_LETTER_UP_ARROWHEAD"] = 708] = "U_MODIFIER_LETTER_UP_ARROWHEAD"; - CharCode2[CharCode2["U_MODIFIER_LETTER_DOWN_ARROWHEAD"] = 709] = "U_MODIFIER_LETTER_DOWN_ARROWHEAD"; - CharCode2[CharCode2["U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING"] = 722] = "U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING"; - CharCode2[CharCode2["U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING"] = 723] = "U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING"; - CharCode2[CharCode2["U_MODIFIER_LETTER_UP_TACK"] = 724] = "U_MODIFIER_LETTER_UP_TACK"; - CharCode2[CharCode2["U_MODIFIER_LETTER_DOWN_TACK"] = 725] = "U_MODIFIER_LETTER_DOWN_TACK"; - CharCode2[CharCode2["U_MODIFIER_LETTER_PLUS_SIGN"] = 726] = "U_MODIFIER_LETTER_PLUS_SIGN"; - CharCode2[CharCode2["U_MODIFIER_LETTER_MINUS_SIGN"] = 727] = "U_MODIFIER_LETTER_MINUS_SIGN"; - CharCode2[CharCode2["U_BREVE"] = 728] = "U_BREVE"; - CharCode2[CharCode2["U_DOT_ABOVE"] = 729] = "U_DOT_ABOVE"; - CharCode2[CharCode2["U_RING_ABOVE"] = 730] = "U_RING_ABOVE"; - CharCode2[CharCode2["U_OGONEK"] = 731] = "U_OGONEK"; - CharCode2[CharCode2["U_SMALL_TILDE"] = 732] = "U_SMALL_TILDE"; - CharCode2[CharCode2["U_DOUBLE_ACUTE_ACCENT"] = 733] = "U_DOUBLE_ACUTE_ACCENT"; - CharCode2[CharCode2["U_MODIFIER_LETTER_RHOTIC_HOOK"] = 734] = "U_MODIFIER_LETTER_RHOTIC_HOOK"; - CharCode2[CharCode2["U_MODIFIER_LETTER_CROSS_ACCENT"] = 735] = "U_MODIFIER_LETTER_CROSS_ACCENT"; - CharCode2[CharCode2["U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR"] = 741] = "U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR"; - CharCode2[CharCode2["U_MODIFIER_LETTER_HIGH_TONE_BAR"] = 742] = "U_MODIFIER_LETTER_HIGH_TONE_BAR"; - CharCode2[CharCode2["U_MODIFIER_LETTER_MID_TONE_BAR"] = 743] = "U_MODIFIER_LETTER_MID_TONE_BAR"; - CharCode2[CharCode2["U_MODIFIER_LETTER_LOW_TONE_BAR"] = 744] = "U_MODIFIER_LETTER_LOW_TONE_BAR"; - CharCode2[CharCode2["U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR"] = 745] = "U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR"; - CharCode2[CharCode2["U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK"] = 746] = "U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK"; - CharCode2[CharCode2["U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK"] = 747] = "U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK"; - CharCode2[CharCode2["U_MODIFIER_LETTER_UNASPIRATED"] = 749] = "U_MODIFIER_LETTER_UNASPIRATED"; - CharCode2[CharCode2["U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD"] = 751] = "U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD"; - CharCode2[CharCode2["U_MODIFIER_LETTER_LOW_UP_ARROWHEAD"] = 752] = "U_MODIFIER_LETTER_LOW_UP_ARROWHEAD"; - CharCode2[CharCode2["U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD"] = 753] = "U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD"; - CharCode2[CharCode2["U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD"] = 754] = "U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD"; - CharCode2[CharCode2["U_MODIFIER_LETTER_LOW_RING"] = 755] = "U_MODIFIER_LETTER_LOW_RING"; - CharCode2[CharCode2["U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT"] = 756] = "U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT"; - CharCode2[CharCode2["U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT"] = 757] = "U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT"; - CharCode2[CharCode2["U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT"] = 758] = "U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT"; - CharCode2[CharCode2["U_MODIFIER_LETTER_LOW_TILDE"] = 759] = "U_MODIFIER_LETTER_LOW_TILDE"; - CharCode2[CharCode2["U_MODIFIER_LETTER_RAISED_COLON"] = 760] = "U_MODIFIER_LETTER_RAISED_COLON"; - CharCode2[CharCode2["U_MODIFIER_LETTER_BEGIN_HIGH_TONE"] = 761] = "U_MODIFIER_LETTER_BEGIN_HIGH_TONE"; - CharCode2[CharCode2["U_MODIFIER_LETTER_END_HIGH_TONE"] = 762] = "U_MODIFIER_LETTER_END_HIGH_TONE"; - CharCode2[CharCode2["U_MODIFIER_LETTER_BEGIN_LOW_TONE"] = 763] = "U_MODIFIER_LETTER_BEGIN_LOW_TONE"; - CharCode2[CharCode2["U_MODIFIER_LETTER_END_LOW_TONE"] = 764] = "U_MODIFIER_LETTER_END_LOW_TONE"; - CharCode2[CharCode2["U_MODIFIER_LETTER_SHELF"] = 765] = "U_MODIFIER_LETTER_SHELF"; - CharCode2[CharCode2["U_MODIFIER_LETTER_OPEN_SHELF"] = 766] = "U_MODIFIER_LETTER_OPEN_SHELF"; - CharCode2[CharCode2["U_MODIFIER_LETTER_LOW_LEFT_ARROW"] = 767] = "U_MODIFIER_LETTER_LOW_LEFT_ARROW"; - CharCode2[CharCode2["U_GREEK_LOWER_NUMERAL_SIGN"] = 885] = "U_GREEK_LOWER_NUMERAL_SIGN"; - CharCode2[CharCode2["U_GREEK_TONOS"] = 900] = "U_GREEK_TONOS"; - CharCode2[CharCode2["U_GREEK_DIALYTIKA_TONOS"] = 901] = "U_GREEK_DIALYTIKA_TONOS"; - CharCode2[CharCode2["U_GREEK_KORONIS"] = 8125] = "U_GREEK_KORONIS"; - CharCode2[CharCode2["U_GREEK_PSILI"] = 8127] = "U_GREEK_PSILI"; - CharCode2[CharCode2["U_GREEK_PERISPOMENI"] = 8128] = "U_GREEK_PERISPOMENI"; - CharCode2[CharCode2["U_GREEK_DIALYTIKA_AND_PERISPOMENI"] = 8129] = "U_GREEK_DIALYTIKA_AND_PERISPOMENI"; - CharCode2[CharCode2["U_GREEK_PSILI_AND_VARIA"] = 8141] = "U_GREEK_PSILI_AND_VARIA"; - CharCode2[CharCode2["U_GREEK_PSILI_AND_OXIA"] = 8142] = "U_GREEK_PSILI_AND_OXIA"; - CharCode2[CharCode2["U_GREEK_PSILI_AND_PERISPOMENI"] = 8143] = "U_GREEK_PSILI_AND_PERISPOMENI"; - CharCode2[CharCode2["U_GREEK_DASIA_AND_VARIA"] = 8157] = "U_GREEK_DASIA_AND_VARIA"; - CharCode2[CharCode2["U_GREEK_DASIA_AND_OXIA"] = 8158] = "U_GREEK_DASIA_AND_OXIA"; - CharCode2[CharCode2["U_GREEK_DASIA_AND_PERISPOMENI"] = 8159] = "U_GREEK_DASIA_AND_PERISPOMENI"; - CharCode2[CharCode2["U_GREEK_DIALYTIKA_AND_VARIA"] = 8173] = "U_GREEK_DIALYTIKA_AND_VARIA"; - CharCode2[CharCode2["U_GREEK_DIALYTIKA_AND_OXIA"] = 8174] = "U_GREEK_DIALYTIKA_AND_OXIA"; - CharCode2[CharCode2["U_GREEK_VARIA"] = 8175] = "U_GREEK_VARIA"; - CharCode2[CharCode2["U_GREEK_OXIA"] = 8189] = "U_GREEK_OXIA"; - CharCode2[CharCode2["U_GREEK_DASIA"] = 8190] = "U_GREEK_DASIA"; - CharCode2[CharCode2["U_OVERLINE"] = 8254] = "U_OVERLINE"; - CharCode2[CharCode2["UTF8_BOM"] = 65279] = "UTF8_BOM"; - })(CharCode || (CharCode = {})); - } -}); - -// src/snippets/parser.ts -function walk(marker, visitor) { - const stack = [...marker]; - while (stack.length > 0) { - const marker2 = stack.shift(); - const recurse = visitor(marker2); - if (!recurse) { - break; - } - stack.unshift(...marker2.children); - } -} -var logger31, TokenType, _Scanner, Scanner, Marker, Text, TransformableMarker, Placeholder, Choice, Transform, FormatString, Variable, TextmateSnippet, SnippetParser; -var init_parser2 = __esm({ - "src/snippets/parser.ts"() { - init_charCode(); - init_string(); - logger31 = require_logger2()("snippets-parser"); - (function(TokenType2) { - TokenType2[TokenType2["Dollar"] = 0] = "Dollar"; - TokenType2[TokenType2["Colon"] = 1] = "Colon"; - TokenType2[TokenType2["Comma"] = 2] = "Comma"; - TokenType2[TokenType2["CurlyOpen"] = 3] = "CurlyOpen"; - TokenType2[TokenType2["CurlyClose"] = 4] = "CurlyClose"; - TokenType2[TokenType2["Backslash"] = 5] = "Backslash"; - TokenType2[TokenType2["Forwardslash"] = 6] = "Forwardslash"; - TokenType2[TokenType2["Pipe"] = 7] = "Pipe"; - TokenType2[TokenType2["Int"] = 8] = "Int"; - TokenType2[TokenType2["VariableName"] = 9] = "VariableName"; - TokenType2[TokenType2["Format"] = 10] = "Format"; - TokenType2[TokenType2["Plus"] = 11] = "Plus"; - TokenType2[TokenType2["Dash"] = 12] = "Dash"; - TokenType2[TokenType2["QuestionMark"] = 13] = "QuestionMark"; - TokenType2[TokenType2["EOF"] = 14] = "EOF"; - })(TokenType || (TokenType = {})); - _Scanner = class { - static isDigitCharacter(ch) { - return ch >= CharCode.Digit0 && ch <= CharCode.Digit9; - } - static isVariableCharacter(ch) { - return ch === CharCode.Underline || ch >= CharCode.a && ch <= CharCode.z || ch >= CharCode.A && ch <= CharCode.Z; - } - constructor() { - this.text(""); - } - text(value) { - this.value = value; - this.pos = 0; - } - tokenText(token) { - return this.value.substr(token.pos, token.len); - } - next() { - if (this.pos >= this.value.length) { - return { type: 14, pos: this.pos, len: 0 }; - } - let pos = this.pos; - let len = 0; - let ch = this.value.charCodeAt(pos); - let type; - type = _Scanner._table[ch]; - if (typeof type === "number") { - this.pos += 1; - return { type, pos, len: 1 }; - } - if (_Scanner.isDigitCharacter(ch)) { - type = 8; - do { - len += 1; - ch = this.value.charCodeAt(pos + len); - } while (_Scanner.isDigitCharacter(ch)); - this.pos += len; - return { type, pos, len }; - } - if (_Scanner.isVariableCharacter(ch)) { - type = 9; - do { - ch = this.value.charCodeAt(pos + ++len); - } while (_Scanner.isVariableCharacter(ch) || _Scanner.isDigitCharacter(ch)); - this.pos += len; - return { type, pos, len }; - } - type = 10; - do { - len += 1; - ch = this.value.charCodeAt(pos + len); - } while (!isNaN(ch) && typeof _Scanner._table[ch] === "undefined" && !_Scanner.isDigitCharacter(ch) && !_Scanner.isVariableCharacter(ch)); - this.pos += len; - return { type, pos, len }; - } - }; - Scanner = _Scanner; - Scanner._table = { - [CharCode.DollarSign]: 0, - [CharCode.Colon]: 1, - [CharCode.Comma]: 2, - [CharCode.OpenCurlyBrace]: 3, - [CharCode.CloseCurlyBrace]: 4, - [CharCode.Backslash]: 5, - [CharCode.Slash]: 6, - [CharCode.Pipe]: 7, - [CharCode.Plus]: 11, - [CharCode.Dash]: 12, - [CharCode.QuestionMark]: 13 - }; - Marker = class { - constructor() { - this._children = []; - } - appendChild(child) { - if (child instanceof Text && this._children[this._children.length - 1] instanceof Text) { - this._children[this._children.length - 1].value += child.value; - } else { - child.parent = this; - this._children.push(child); - } - return this; - } - setOnlyChild(child) { - child.parent = this; - this._children = [child]; - } - replace(child, others) { - const { parent } = child; - const idx = parent.children.indexOf(child); - const newChildren = parent.children.slice(0); - newChildren.splice(idx, 1, ...others); - parent._children = newChildren; - (function _fixParent(children, parent2) { - for (const child2 of children) { - child2.parent = parent2; - _fixParent(child2.children, child2); - } - })(others, parent); - } - get children() { - return this._children; - } - get snippet() { - let candidate = this; - while (true) { - if (!candidate) { - return void 0; - } - if (candidate instanceof TextmateSnippet) { - return candidate; - } - candidate = candidate.parent; - } - } - toString() { - return this.children.reduce((prev, cur) => prev + cur.toString(), ""); - } - len() { - return 0; - } - get next() { - let { parent } = this; - let { children } = parent; - let idx = children.indexOf(this); - return children[idx + 1]; - } - }; - Text = class extends Marker { - constructor(value) { - super(); - this.value = value; - } - static escape(value) { - return value.replace(/\$|}|\\/g, "\\$&"); - } - toString() { - return this.value; - } - toTextmateString() { - return Text.escape(this.value); - } - len() { - return this.value.length; - } - clone() { - return new Text(this.value); - } - }; - TransformableMarker = class extends Marker { - }; - Placeholder = class extends TransformableMarker { - constructor(index) { - super(); - this.index = index; - } - static compareByIndex(a, b) { - if (a.index === b.index) { - return 0; - } else if (a.isFinalTabstop) { - return 1; - } else if (b.isFinalTabstop) { - return -1; - } else if (a.index < b.index) { - return -1; - } else if (a.index > b.index) { - return 1; - } else { - return 0; - } - } - get isFinalTabstop() { - return this.index === 0; - } - get choice() { - return this._children.length === 1 && this._children[0] instanceof Choice ? this._children[0] : void 0; - } - toTextmateString() { - let transformString = ""; - if (this.transform) { - transformString = this.transform.toTextmateString(); - } - if (this.children.length === 0 && !this.transform) { - return `$${this.index}`; - } else if (this.children.length === 0) { - return `\${${this.index}${transformString}}`; - } else if (this.choice) { - return `\${${this.index}|${this.choice.toTextmateString()}|${transformString}}`; - } else { - return `\${${this.index}:${this.children.map((child) => child.toTextmateString()).join("")}${transformString}}`; - } - } - clone() { - let ret = new Placeholder(this.index); - if (this.transform) { - ret.transform = this.transform.clone(); - } - ret._children = this.children.map((child) => child.clone()); - return ret; - } - }; - Choice = class extends Marker { - constructor() { - super(...arguments); - this.options = []; - } - appendChild(marker) { - if (marker instanceof Text) { - marker.parent = this; - this.options.push(marker); - } - return this; - } - toString() { - return this.options[0].value; - } - toTextmateString() { - return this.options.map((option) => option.value.replace(/\||,/g, "\\$&")).join(","); - } - len() { - return this.options[0].len(); - } - clone() { - let ret = new Choice(); - for (let opt of this.options) { - ret.appendChild(opt); - } - return ret; - } - }; - Transform = class extends Marker { - resolve(value) { - let didMatch = false; - let ret = value.replace(this.regexp, (...args) => { - didMatch = true; - return this._replace(args.slice(0, -2)); - }); - if (!didMatch && this._children.some((child) => child instanceof FormatString && Boolean(child.elseValue))) { - ret = this._replace([]); - } - return ret; - } - _replace(groups) { - let ret = ""; - for (const marker of this._children) { - if (marker instanceof FormatString) { - let value = groups[marker.index] || ""; - value = marker.resolve(value); - ret += value; - } else { - ret += marker.toString(); - } - } - return ret; - } - toString() { - return ""; - } - toTextmateString() { - return `/${this.regexp.source}/${this.children.map((c) => c.toTextmateString())}/${(this.regexp.ignoreCase ? "i" : "") + (this.regexp.global ? "g" : "")}`; - } - clone() { - let ret = new Transform(); - ret.regexp = new RegExp(this.regexp.source, "" + (this.regexp.ignoreCase ? "i" : "") + (this.regexp.global ? "g" : "")); - ret._children = this.children.map((child) => child.clone()); - return ret; - } - }; - FormatString = class extends Marker { - constructor(index, shorthandName, ifValue, elseValue) { - super(); - this.index = index; - this.shorthandName = shorthandName; - this.ifValue = ifValue; - this.elseValue = elseValue; - } - resolve(value) { - if (this.shorthandName === "upcase") { - return !value ? "" : value.toLocaleUpperCase(); - } else if (this.shorthandName === "downcase") { - return !value ? "" : value.toLocaleLowerCase(); - } else if (this.shorthandName === "capitalize") { - return !value ? "" : value[0].toLocaleUpperCase() + value.substr(1); - } else if (this.shorthandName === "pascalcase") { - return !value ? "" : this._toPascalCase(value); - } else if (Boolean(value) && typeof this.ifValue === "string") { - return this.ifValue; - } else if (!value && typeof this.elseValue === "string") { - return this.elseValue; - } else { - return value || ""; - } - } - _toPascalCase(value) { - const match = value.match(/[a-z]+/gi); - if (!match) { - return value; - } - return match.map((word) => word.charAt(0).toUpperCase() + word.substr(1).toLowerCase()).join(""); - } - toTextmateString() { - let value = "${"; - value += this.index; - if (this.shorthandName) { - value += `:/${this.shorthandName}`; - } else if (this.ifValue && this.elseValue) { - value += `:?${this.ifValue}:${this.elseValue}`; - } else if (this.ifValue) { - value += `:+${this.ifValue}`; - } else if (this.elseValue) { - value += `:-${this.elseValue}`; - } - value += "}"; - return value; - } - clone() { - let ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue); - return ret; - } - }; - Variable = class extends TransformableMarker { - constructor(name2) { - super(); - this.name = name2; - } - async resolve(resolver) { - let value = await resolver.resolve(this); - if (value && value.includes("\n")) { - let indent = ""; - this.snippet.walk((m) => { - if (m == this) { - return false; - } - if (m instanceof Text) { - let lines2 = m.toString().split(/\r?\n/); - indent = lines2[lines2.length - 1].match(/^\s*/)[0]; - } - return true; - }); - let lines = value.split("\n"); - let indents = lines.filter((s) => s.length > 0).map((s) => s.match(/^\s*/)[0]); - let minIndent = indents.length == 0 ? "" : indents.reduce((p, c) => p.length < c.length ? p : c); - let newLines = lines.map((s, i) => i == 0 || s.length == 0 || !s.startsWith(minIndent) ? s : indent + s.slice(minIndent.length)); - value = newLines.join("\n"); - } - if (this.transform) { - value = this.transform.resolve(value || ""); - } - if (value !== void 0) { - this._children = [new Text(value)]; - return true; - } - return false; - } - toTextmateString() { - let transformString = ""; - if (this.transform) { - transformString = this.transform.toTextmateString(); - } - if (this.children.length === 0) { - return `\${${this.name}${transformString}}`; - } else { - return `\${${this.name}:${this.children.map((child) => child.toTextmateString()).join("")}${transformString}}`; - } - } - clone() { - const ret = new Variable(this.name); - if (this.transform) { - ret.transform = this.transform.clone(); - } - ret._children = this.children.map((child) => child.clone()); - return ret; - } - }; - TextmateSnippet = class extends Marker { - get placeholderInfo() { - if (!this._placeholders) { - this._variables = []; - let all = []; - let last; - this.walk((candidate) => { - if (candidate instanceof Placeholder) { - all.push(candidate); - last = !last || last.index < candidate.index ? candidate : last; - } else if (candidate instanceof Variable) { - let first = candidate.name.charCodeAt(0); - if (first < 65 || first > 90) { - this._variables.push(candidate); - } - } - return true; - }); - this._placeholders = { all, last }; - } - return this._placeholders; - } - get variables() { - return this._variables; - } - get placeholders() { - const { all } = this.placeholderInfo; - return all; - } - get maxIndexNumber() { - let { placeholders } = this; - return placeholders.reduce((curr, p) => Math.max(curr, p.index), 0); - } - get minIndexNumber() { - let { placeholders } = this; - let nums = placeholders.map((p) => p.index); - nums.sort((a, b) => a - b); - if (nums.length > 1 && nums[0] == 0) - return nums[1]; - return nums[0] || 0; - } - insertSnippet(snippet, id, range) { - let placeholder = this.placeholders[id]; - if (!placeholder) - return; - let { index } = placeholder; - let [before, after] = rangeParts(placeholder.toString(), range); - let nested = new SnippetParser().parse(snippet, true); - let maxIndexAdded = nested.maxIndexNumber + 1; - let indexes = []; - for (let p of nested.placeholders) { - if (p.isFinalTabstop) { - p.index = maxIndexAdded + index; - } else { - p.index = p.index + index; - } - indexes.push(p.index); - } - this.walk((m) => { - if (m instanceof Placeholder && m.index > index) { - m.index = m.index + maxIndexAdded; - } - return true; - }); - let children = nested.children; - if (before) - children.unshift(new Text(before)); - if (after) - children.push(new Text(after)); - this.replace(placeholder, children); - return Math.min.apply(null, indexes); - } - updatePlaceholder(id, val) { - const placeholder = this.placeholders[id]; - for (let p of this.placeholders) { - if (p.index == placeholder.index) { - let child = p.children[0]; - let newText = p.transform ? p.transform.resolve(val) : val; - if (child) { - p.setOnlyChild(new Text(newText)); - } else { - p.appendChild(new Text(newText)); - } - } - } - this._placeholders = void 0; - } - updateVariable(id, val) { - const find = this.variables[id - this.maxIndexNumber - 1]; - if (find) { - let variables = this.variables.filter((o) => o.name == find.name); - for (let variable of variables) { - let newText = variable.transform ? variable.transform.resolve(val) : val; - variable.setOnlyChild(new Text(newText)); - } - } - } - getPlaceholderText(id, value) { - const placeholder = this.placeholders[id]; - if (!placeholder) - return value; - return placeholder.transform ? placeholder.transform.resolve(value) : value; - } - offset(marker) { - let pos = 0; - let found = false; - this.walk((candidate) => { - if (candidate === marker) { - found = true; - return false; - } - pos += candidate.len(); - return true; - }); - if (!found) { - return -1; - } - return pos; - } - fullLen(marker) { - let ret = 0; - walk([marker], (marker2) => { - ret += marker2.len(); - return true; - }); - return ret; - } - enclosingPlaceholders(placeholder) { - let ret = []; - let { parent } = placeholder; - while (parent) { - if (parent instanceof Placeholder) { - ret.push(parent); - } - parent = parent.parent; - } - return ret; - } - async resolveVariables(resolver) { - let items = []; - this.walk((candidate) => { - if (candidate instanceof Variable) { - items.push(candidate); - } - return true; - }); - await Promise.all(items.map((o) => o.resolve(resolver))); - } - appendChild(child) { - this._placeholders = void 0; - return super.appendChild(child); - } - replace(child, others) { - this._placeholders = void 0; - return super.replace(child, others); - } - toTextmateString() { - return this.children.reduce((prev, cur) => prev + cur.toTextmateString(), ""); - } - clone() { - let ret = new TextmateSnippet(); - this._children = this.children.map((child) => child.clone()); - return ret; - } - walk(visitor) { - walk(this.children, visitor); - } - }; - SnippetParser = class { - constructor() { - this._scanner = new Scanner(); - } - static escape(value) { - return value.replace(/\$|}|\\/g, "\\$&"); - } - text(value) { - return this.parse(value).toString(); - } - parse(value, insertFinalTabstop) { - this._scanner.text(value); - this._token = this._scanner.next(); - const snippet = new TextmateSnippet(); - while (this._parse(snippet)) { - } - const placeholderDefaultValues = new Map(); - const incompletePlaceholders = []; - snippet.walk((marker) => { - if (marker instanceof Placeholder) { - if (marker.isFinalTabstop) { - placeholderDefaultValues.set(0, void 0); - } else if (!placeholderDefaultValues.has(marker.index) && marker.children.length > 0) { - placeholderDefaultValues.set(marker.index, marker.children); - } else { - incompletePlaceholders.push(marker); - } - } - return true; - }); - for (const placeholder of incompletePlaceholders) { - if (placeholderDefaultValues.has(placeholder.index)) { - const clone = new Placeholder(placeholder.index); - clone.transform = placeholder.transform; - for (const child of placeholderDefaultValues.get(placeholder.index)) { - let marker = child.clone(); - if (clone.transform) { - if (marker instanceof Text) { - marker = new Text(clone.transform.resolve(marker.value)); - } else { - for (let child2 of marker.children) { - if (child2 instanceof Text) { - marker.replace(child2, [new Text(clone.transform.resolve(child2.value))]); - break; - } - } - } - } - clone.appendChild(marker); - } - snippet.replace(placeholder, [clone]); - } - } - if (!placeholderDefaultValues.has(0) && insertFinalTabstop) { - snippet.appendChild(new Placeholder(0)); - } - return snippet; - } - _accept(type, value) { - if (type === void 0 || this._token.type === type) { - let ret = !value ? true : this._scanner.tokenText(this._token); - this._token = this._scanner.next(); - return ret; - } - return false; - } - _backTo(token) { - this._scanner.pos = token.pos + token.len; - this._token = token; - return false; - } - _until(type) { - if (this._token.type === 14) { - return false; - } - let start = this._token; - while (this._token.type !== type) { - this._token = this._scanner.next(); - if (this._token.type === 14) { - return false; - } - } - let value = this._scanner.value.substring(start.pos, this._token.pos); - this._token = this._scanner.next(); - return value; - } - _parse(marker) { - return this._parseEscaped(marker) || this._parseTabstopOrVariableName(marker) || this._parseComplexPlaceholder(marker) || this._parseComplexVariable(marker) || this._parseAnything(marker); - } - _parseEscaped(marker) { - let value; - if (value = this._accept(5, true)) { - value = this._accept(0, true) || this._accept(4, true) || this._accept(5, true) || value; - marker.appendChild(new Text(value)); - return true; - } - return false; - } - _parseTabstopOrVariableName(parent) { - let value; - const token = this._token; - const match = this._accept(0) && (value = this._accept(9, true) || this._accept(8, true)); - if (!match) { - return this._backTo(token); - } - parent.appendChild(/^\d+$/.test(value) ? new Placeholder(Number(value)) : new Variable(value)); - return true; - } - _parseComplexPlaceholder(parent) { - let index; - const token = this._token; - const match = this._accept(0) && this._accept(3) && (index = this._accept(8, true)); - if (!match) { - return this._backTo(token); - } - const placeholder = new Placeholder(Number(index)); - if (this._accept(1)) { - while (true) { - if (this._accept(4)) { - parent.appendChild(placeholder); - return true; - } - if (this._parse(placeholder)) { - continue; - } - parent.appendChild(new Text("${" + index + ":")); - placeholder.children.forEach(parent.appendChild, parent); - return true; - } - } else if (placeholder.index > 0 && this._accept(7)) { - const choice = new Choice(); - while (true) { - if (this._parseChoiceElement(choice)) { - if (this._accept(2)) { - continue; - } - if (this._accept(7)) { - placeholder.appendChild(choice); - if (this._accept(4)) { - parent.appendChild(placeholder); - return true; - } - } - } - this._backTo(token); - return false; - } - } else if (this._accept(6)) { - if (this._parseTransform(placeholder)) { - parent.appendChild(placeholder); - return true; - } - this._backTo(token); - return false; - } else if (this._accept(4)) { - parent.appendChild(placeholder); - return true; - } else { - return this._backTo(token); - } - } - _parseChoiceElement(parent) { - const token = this._token; - const values = []; - while (true) { - if (this._token.type === 2 || this._token.type === 7) { - break; - } - let value; - if (value = this._accept(5, true)) { - value = this._accept(2, true) || this._accept(7, true) || this._accept(5, true) || value; - } else { - value = this._accept(void 0, true); - } - if (!value) { - this._backTo(token); - return false; - } - values.push(value); - } - if (values.length === 0) { - this._backTo(token); - return false; - } - parent.appendChild(new Text(values.join(""))); - return true; - } - _parseComplexVariable(parent) { - let name2; - const token = this._token; - const match = this._accept(0) && this._accept(3) && (name2 = this._accept(9, true)); - if (!match) { - return this._backTo(token); - } - const variable = new Variable(name2); - if (this._accept(1)) { - while (true) { - if (this._accept(4)) { - parent.appendChild(variable); - return true; - } - if (this._parse(variable)) { - continue; - } - parent.appendChild(new Text("${" + name2 + ":")); - variable.children.forEach(parent.appendChild, parent); - return true; - } - } else if (this._accept(6)) { - if (this._parseTransform(variable)) { - parent.appendChild(variable); - return true; - } - this._backTo(token); - return false; - } else if (this._accept(4)) { - parent.appendChild(variable); - return true; - } else { - return this._backTo(token); - } - } - _parseTransform(parent) { - let transform = new Transform(); - let regexValue = ""; - let regexOptions = ""; - while (true) { - if (this._accept(6)) { - break; - } - let escaped; - if (escaped = this._accept(5, true)) { - escaped = this._accept(6, true) || escaped; - regexValue += escaped; - continue; - } - if (this._token.type !== 14) { - regexValue += this._accept(void 0, true); - continue; - } - return false; - } - while (true) { - if (this._accept(6)) { - break; - } - let escaped; - if (escaped = this._accept(5, true)) { - escaped = this._accept(6, true) || escaped; - transform.appendChild(new Text(escaped)); - continue; - } - if (this._parseFormatString(transform) || this._parseAnything(transform)) { - let text = transform.children[0]; - if (text && text.value && text.value.includes("\\n")) { - text.value = text.value.replace(/\\n/g, "\n"); - } - continue; - } - return false; - } - while (true) { - if (this._accept(4)) { - break; - } - if (this._token.type !== 14) { - regexOptions += this._accept(void 0, true); - continue; - } - return false; - } - try { - transform.regexp = new RegExp(regexValue, regexOptions); - } catch (e) { - return false; - } - parent.transform = transform; - return true; - } - _parseFormatString(parent) { - const token = this._token; - if (!this._accept(0)) { - return false; - } - let complex = false; - if (this._accept(3)) { - complex = true; - } - let index = this._accept(8, true); - if (!index) { - this._backTo(token); - return false; - } else if (!complex) { - parent.appendChild(new FormatString(Number(index))); - return true; - } else if (this._accept(4)) { - parent.appendChild(new FormatString(Number(index))); - return true; - } else if (!this._accept(1)) { - this._backTo(token); - return false; - } - if (this._accept(6)) { - let shorthand = this._accept(9, true); - if (!shorthand || !this._accept(4)) { - this._backTo(token); - return false; - } else { - parent.appendChild(new FormatString(Number(index), shorthand)); - return true; - } - } else if (this._accept(11)) { - let ifValue = this._until(4); - if (ifValue) { - parent.appendChild(new FormatString(Number(index), void 0, ifValue, void 0)); - return true; - } - } else if (this._accept(12)) { - let elseValue = this._until(4); - if (elseValue) { - parent.appendChild(new FormatString(Number(index), void 0, void 0, elseValue)); - return true; - } - } else if (this._accept(13)) { - let ifValue = this._until(1); - if (ifValue) { - let elseValue = this._until(4); - if (elseValue) { - parent.appendChild(new FormatString(Number(index), void 0, ifValue, elseValue)); - return true; - } - } - } else { - let elseValue = this._until(4); - if (elseValue) { - parent.appendChild(new FormatString(Number(index), void 0, void 0, elseValue)); - return true; - } - } - this._backTo(token); - return false; - } - _parseAnything(marker) { - if (this._token.type !== 14) { - let text = this._scanner.tokenText(this._token); - marker.appendChild(new Text(text)); - this._accept(void 0); - return true; - } - return false; - } - }; - } -}); - -// node_modules/semver/internal/constants.js -var require_constants = __commonJS({ - "node_modules/semver/internal/constants.js"(exports2, module2) { - var SEMVER_SPEC_VERSION = "2.0.0"; - var MAX_LENGTH = 256; - var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; - var MAX_SAFE_COMPONENT_LENGTH = 16; - module2.exports = { - SEMVER_SPEC_VERSION, - MAX_LENGTH, - MAX_SAFE_INTEGER, - MAX_SAFE_COMPONENT_LENGTH - }; - } -}); - -// node_modules/semver/internal/debug.js -var require_debug = __commonJS({ - "node_modules/semver/internal/debug.js"(exports2, module2) { - var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { - }; - module2.exports = debug; - } -}); - -// node_modules/semver/internal/re.js -var require_re = __commonJS({ - "node_modules/semver/internal/re.js"(exports2, module2) { - var { MAX_SAFE_COMPONENT_LENGTH } = require_constants(); - var debug = require_debug(); - exports2 = module2.exports = {}; - var re = exports2.re = []; - var src = exports2.src = []; - var t = exports2.t = {}; - var R = 0; - var createToken = (name2, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name2] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? "g" : void 0); - }; - createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); - createToken("NUMERICIDENTIFIERLOOSE", "[0-9]+"); - createToken("NONNUMERICIDENTIFIER", "\\d*[a-zA-Z-][a-zA-Z0-9-]*"); - createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`); - createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`); - createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`); - createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); - createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - createToken("BUILDIDENTIFIER", "[0-9A-Za-z-]+"); - createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); - createToken("FULL", `^${src[t.FULLPLAIN]}$`); - createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); - createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`); - createToken("GTLT", "((?:<|>)?=?)"); - createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`); - createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`); - createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - createToken("COERCE", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:$|[^\\d])`); - createToken("COERCERTL", src[t.COERCE], true); - createToken("LONETILDE", "(?:~>?)"); - createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports2.tildeTrimReplace = "$1~"; - createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - createToken("LONECARET", "(?:\\^)"); - createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports2.caretTrimReplace = "$1^"; - createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports2.comparatorTrimReplace = "$1$2$3"; - createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`); - createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`); - createToken("STAR", "(<|>)?=?\\s*\\*"); - createToken("GTE0", "^\\s*>=\\s*0.0.0\\s*$"); - createToken("GTE0PRE", "^\\s*>=\\s*0.0.0-0\\s*$"); - } -}); - -// node_modules/semver/internal/parse-options.js -var require_parse_options = __commonJS({ - "node_modules/semver/internal/parse-options.js"(exports2, module2) { - var opts = ["includePrerelease", "loose", "rtl"]; - var parseOptions = (options) => !options ? {} : typeof options !== "object" ? { loose: true } : opts.filter((k) => options[k]).reduce((options2, k) => { - options2[k] = true; - return options2; - }, {}); - module2.exports = parseOptions; - } -}); - -// node_modules/semver/internal/identifiers.js -var require_identifiers = __commonJS({ - "node_modules/semver/internal/identifiers.js"(exports2, module2) { - var numeric = /^[0-9]+$/; - var compareIdentifiers = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); - if (anum && bnum) { - a = +a; - b = +b; - } - return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; - }; - var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); - module2.exports = { - compareIdentifiers, - rcompareIdentifiers - }; - } -}); - -// node_modules/semver/classes/semver.js -var require_semver = __commonJS({ - "node_modules/semver/classes/semver.js"(exports2, module2) { - var debug = require_debug(); - var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants(); - var { re, t } = require_re(); - var parseOptions = require_parse_options(); - var { compareIdentifiers } = require_identifiers(); - var SemVer = class { - constructor(version2, options) { - options = parseOptions(options); - if (version2 instanceof SemVer) { - if (version2.loose === !!options.loose && version2.includePrerelease === !!options.includePrerelease) { - return version2; - } else { - version2 = version2.version; - } - } else if (typeof version2 !== "string") { - throw new TypeError(`Invalid Version: ${version2}`); - } - if (version2.length > MAX_LENGTH) { - throw new TypeError(`version is longer than ${MAX_LENGTH} characters`); - } - debug("SemVer", version2, options); - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - const m = version2.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); - if (!m) { - throw new TypeError(`Invalid Version: ${version2}`); - } - this.raw = version2; - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError("Invalid major version"); - } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError("Invalid minor version"); - } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError("Invalid patch version"); - } - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split(".").map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num; - } - } - return id; - }); - } - this.build = m[5] ? m[5].split(".") : []; - this.format(); - } - format() { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join(".")}`; - } - return this.version; - } - toString() { - return this.version; - } - compare(other) { - debug("SemVer.compare", this.version, this.options, other); - if (!(other instanceof SemVer)) { - if (typeof other === "string" && other === this.version) { - return 0; - } - other = new SemVer(other, this.options); - } - if (other.version === this.version) { - return 0; - } - return this.compareMain(other) || this.comparePre(other); - } - compareMain(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); - } - return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); - } - comparePre(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); - } - if (this.prerelease.length && !other.prerelease.length) { - return -1; - } else if (!this.prerelease.length && other.prerelease.length) { - return 1; - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0; - } - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug("prerelease compare", i, a, b); - if (a === void 0 && b === void 0) { - return 0; - } else if (b === void 0) { - return 1; - } else if (a === void 0) { - return -1; - } else if (a === b) { - continue; - } else { - return compareIdentifiers(a, b); - } - } while (++i); - } - compareBuild(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); - } - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug("prerelease compare", i, a, b); - if (a === void 0 && b === void 0) { - return 0; - } else if (b === void 0) { - return 1; - } else if (a === void 0) { - return -1; - } else if (a === b) { - continue; - } else { - return compareIdentifiers(a, b); - } - } while (++i); - } - inc(release, identifier) { - switch (release) { - case "premajor": - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc("pre", identifier); - break; - case "preminor": - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc("pre", identifier); - break; - case "prepatch": - this.prerelease.length = 0; - this.inc("patch", identifier); - this.inc("pre", identifier); - break; - case "prerelease": - if (this.prerelease.length === 0) { - this.inc("patch", identifier); - } - this.inc("pre", identifier); - break; - case "major": - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - case "minor": - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break; - case "patch": - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break; - case "pre": - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === "number") { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) { - this.prerelease.push(0); - } - } - if (identifier) { - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; - } - } - break; - default: - throw new Error(`invalid increment argument: ${release}`); - } - this.format(); - this.raw = this.version; - return this; - } - }; - module2.exports = SemVer; - } -}); - -// node_modules/semver/functions/parse.js -var require_parse = __commonJS({ - "node_modules/semver/functions/parse.js"(exports2, module2) { - var { MAX_LENGTH } = require_constants(); - var { re, t } = require_re(); - var SemVer = require_semver(); - var parseOptions = require_parse_options(); - var parse5 = (version2, options) => { - options = parseOptions(options); - if (version2 instanceof SemVer) { - return version2; - } - if (typeof version2 !== "string") { - return null; - } - if (version2.length > MAX_LENGTH) { - return null; - } - const r = options.loose ? re[t.LOOSE] : re[t.FULL]; - if (!r.test(version2)) { - return null; - } - try { - return new SemVer(version2, options); - } catch (er) { - return null; - } - }; - module2.exports = parse5; - } -}); - -// node_modules/semver/functions/valid.js -var require_valid = __commonJS({ - "node_modules/semver/functions/valid.js"(exports2, module2) { - var parse5 = require_parse(); - var valid = (version2, options) => { - const v = parse5(version2, options); - return v ? v.version : null; - }; - module2.exports = valid; - } -}); - -// node_modules/semver/functions/clean.js -var require_clean = __commonJS({ - "node_modules/semver/functions/clean.js"(exports2, module2) { - var parse5 = require_parse(); - var clean = (version2, options) => { - const s = parse5(version2.trim().replace(/^[=v]+/, ""), options); - return s ? s.version : null; - }; - module2.exports = clean; - } -}); - -// node_modules/semver/functions/inc.js -var require_inc = __commonJS({ - "node_modules/semver/functions/inc.js"(exports2, module2) { - var SemVer = require_semver(); - var inc = (version2, release, options, identifier) => { - if (typeof options === "string") { - identifier = options; - options = void 0; - } - try { - return new SemVer(version2, options).inc(release, identifier).version; - } catch (er) { - return null; - } - }; - module2.exports = inc; - } -}); - -// node_modules/semver/functions/compare.js -var require_compare = __commonJS({ - "node_modules/semver/functions/compare.js"(exports2, module2) { - var SemVer = require_semver(); - var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)); - module2.exports = compare; - } -}); - -// node_modules/semver/functions/eq.js -var require_eq = __commonJS({ - "node_modules/semver/functions/eq.js"(exports2, module2) { - var compare = require_compare(); - var eq = (a, b, loose) => compare(a, b, loose) === 0; - module2.exports = eq; - } -}); - -// node_modules/semver/functions/diff.js -var require_diff2 = __commonJS({ - "node_modules/semver/functions/diff.js"(exports2, module2) { - var parse5 = require_parse(); - var eq = require_eq(); - var diff = (version1, version2) => { - if (eq(version1, version2)) { - return null; - } else { - const v12 = parse5(version1); - const v2 = parse5(version2); - const hasPre = v12.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? "pre" : ""; - const defaultResult = hasPre ? "prerelease" : ""; - for (const key in v12) { - if (key === "major" || key === "minor" || key === "patch") { - if (v12[key] !== v2[key]) { - return prefix + key; - } - } - } - return defaultResult; - } - }; - module2.exports = diff; - } -}); - -// node_modules/semver/functions/major.js -var require_major = __commonJS({ - "node_modules/semver/functions/major.js"(exports2, module2) { - var SemVer = require_semver(); - var major = (a, loose) => new SemVer(a, loose).major; - module2.exports = major; - } -}); - -// node_modules/semver/functions/minor.js -var require_minor = __commonJS({ - "node_modules/semver/functions/minor.js"(exports2, module2) { - var SemVer = require_semver(); - var minor = (a, loose) => new SemVer(a, loose).minor; - module2.exports = minor; - } -}); - -// node_modules/semver/functions/patch.js -var require_patch = __commonJS({ - "node_modules/semver/functions/patch.js"(exports2, module2) { - var SemVer = require_semver(); - var patch = (a, loose) => new SemVer(a, loose).patch; - module2.exports = patch; - } -}); - -// node_modules/semver/functions/prerelease.js -var require_prerelease = __commonJS({ - "node_modules/semver/functions/prerelease.js"(exports2, module2) { - var parse5 = require_parse(); - var prerelease = (version2, options) => { - const parsed = parse5(version2, options); - return parsed && parsed.prerelease.length ? parsed.prerelease : null; - }; - module2.exports = prerelease; - } -}); - -// node_modules/semver/functions/rcompare.js -var require_rcompare = __commonJS({ - "node_modules/semver/functions/rcompare.js"(exports2, module2) { - var compare = require_compare(); - var rcompare = (a, b, loose) => compare(b, a, loose); - module2.exports = rcompare; - } -}); - -// node_modules/semver/functions/compare-loose.js -var require_compare_loose = __commonJS({ - "node_modules/semver/functions/compare-loose.js"(exports2, module2) { - var compare = require_compare(); - var compareLoose = (a, b) => compare(a, b, true); - module2.exports = compareLoose; - } -}); - -// node_modules/semver/functions/compare-build.js -var require_compare_build = __commonJS({ - "node_modules/semver/functions/compare-build.js"(exports2, module2) { - var SemVer = require_semver(); - var compareBuild = (a, b, loose) => { - const versionA = new SemVer(a, loose); - const versionB = new SemVer(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB); - }; - module2.exports = compareBuild; - } -}); - -// node_modules/semver/functions/sort.js -var require_sort = __commonJS({ - "node_modules/semver/functions/sort.js"(exports2, module2) { - var compareBuild = require_compare_build(); - var sort = (list2, loose) => list2.sort((a, b) => compareBuild(a, b, loose)); - module2.exports = sort; - } -}); - -// node_modules/semver/functions/rsort.js -var require_rsort = __commonJS({ - "node_modules/semver/functions/rsort.js"(exports2, module2) { - var compareBuild = require_compare_build(); - var rsort = (list2, loose) => list2.sort((a, b) => compareBuild(b, a, loose)); - module2.exports = rsort; - } -}); - -// node_modules/semver/functions/gt.js -var require_gt = __commonJS({ - "node_modules/semver/functions/gt.js"(exports2, module2) { - var compare = require_compare(); - var gt = (a, b, loose) => compare(a, b, loose) > 0; - module2.exports = gt; - } -}); - -// node_modules/semver/functions/lt.js -var require_lt = __commonJS({ - "node_modules/semver/functions/lt.js"(exports2, module2) { - var compare = require_compare(); - var lt = (a, b, loose) => compare(a, b, loose) < 0; - module2.exports = lt; - } -}); - -// node_modules/semver/functions/neq.js -var require_neq = __commonJS({ - "node_modules/semver/functions/neq.js"(exports2, module2) { - var compare = require_compare(); - var neq = (a, b, loose) => compare(a, b, loose) !== 0; - module2.exports = neq; - } -}); - -// node_modules/semver/functions/gte.js -var require_gte = __commonJS({ - "node_modules/semver/functions/gte.js"(exports2, module2) { - var compare = require_compare(); - var gte = (a, b, loose) => compare(a, b, loose) >= 0; - module2.exports = gte; - } -}); - -// node_modules/semver/functions/lte.js -var require_lte = __commonJS({ - "node_modules/semver/functions/lte.js"(exports2, module2) { - var compare = require_compare(); - var lte = (a, b, loose) => compare(a, b, loose) <= 0; - module2.exports = lte; - } -}); - -// node_modules/semver/functions/cmp.js -var require_cmp = __commonJS({ - "node_modules/semver/functions/cmp.js"(exports2, module2) { - var eq = require_eq(); - var neq = require_neq(); - var gt = require_gt(); - var gte = require_gte(); - var lt = require_lt(); - var lte = require_lte(); - var cmp = (a, op, b, loose) => { - switch (op) { - case "===": - if (typeof a === "object") - a = a.version; - if (typeof b === "object") - b = b.version; - return a === b; - case "!==": - if (typeof a === "object") - a = a.version; - if (typeof b === "object") - b = b.version; - return a !== b; - case "": - case "=": - case "==": - return eq(a, b, loose); - case "!=": - return neq(a, b, loose); - case ">": - return gt(a, b, loose); - case ">=": - return gte(a, b, loose); - case "<": - return lt(a, b, loose); - case "<=": - return lte(a, b, loose); - default: - throw new TypeError(`Invalid operator: ${op}`); - } - }; - module2.exports = cmp; - } -}); - -// node_modules/semver/functions/coerce.js -var require_coerce = __commonJS({ - "node_modules/semver/functions/coerce.js"(exports2, module2) { - var SemVer = require_semver(); - var parse5 = require_parse(); - var { re, t } = require_re(); - var coerce = (version2, options) => { - if (version2 instanceof SemVer) { - return version2; - } - if (typeof version2 === "number") { - version2 = String(version2); - } - if (typeof version2 !== "string") { - return null; - } - options = options || {}; - let match = null; - if (!options.rtl) { - match = version2.match(re[t.COERCE]); - } else { - let next; - while ((next = re[t.COERCERTL].exec(version2)) && (!match || match.index + match[0].length !== version2.length)) { - if (!match || next.index + next[0].length !== match.index + match[0].length) { - match = next; - } - re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; - } - re[t.COERCERTL].lastIndex = -1; - } - if (match === null) - return null; - return parse5(`${match[2]}.${match[3] || "0"}.${match[4] || "0"}`, options); - }; - module2.exports = coerce; - } -}); - -// node_modules/yallist/iterator.js -var require_iterator = __commonJS({ - "node_modules/yallist/iterator.js"(exports2, module2) { - "use strict"; - module2.exports = function(Yallist) { - Yallist.prototype[Symbol.iterator] = function* () { - for (let walker = this.head; walker; walker = walker.next) { - yield walker.value; - } - }; - }; - } -}); - -// node_modules/yallist/yallist.js -var require_yallist = __commonJS({ - "node_modules/yallist/yallist.js"(exports2, module2) { - "use strict"; - module2.exports = Yallist; - Yallist.Node = Node; - Yallist.create = Yallist; - function Yallist(list2) { - var self2 = this; - if (!(self2 instanceof Yallist)) { - self2 = new Yallist(); - } - self2.tail = null; - self2.head = null; - self2.length = 0; - if (list2 && typeof list2.forEach === "function") { - list2.forEach(function(item) { - self2.push(item); - }); - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self2.push(arguments[i]); - } - } - return self2; - } - Yallist.prototype.removeNode = function(node) { - if (node.list !== this) { - throw new Error("removing node which does not belong to this list"); - } - var next = node.next; - var prev = node.prev; - if (next) { - next.prev = prev; - } - if (prev) { - prev.next = next; - } - if (node === this.head) { - this.head = next; - } - if (node === this.tail) { - this.tail = prev; - } - node.list.length--; - node.next = null; - node.prev = null; - node.list = null; - return next; - }; - Yallist.prototype.unshiftNode = function(node) { - if (node === this.head) { - return; - } - if (node.list) { - node.list.removeNode(node); - } - var head = this.head; - node.list = this; - node.next = head; - if (head) { - head.prev = node; - } - this.head = node; - if (!this.tail) { - this.tail = node; - } - this.length++; - }; - Yallist.prototype.pushNode = function(node) { - if (node === this.tail) { - return; - } - if (node.list) { - node.list.removeNode(node); - } - var tail = this.tail; - node.list = this; - node.prev = tail; - if (tail) { - tail.next = node; - } - this.tail = node; - if (!this.head) { - this.head = node; - } - this.length++; - }; - Yallist.prototype.push = function() { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]); - } - return this.length; - }; - Yallist.prototype.unshift = function() { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]); - } - return this.length; - }; - Yallist.prototype.pop = function() { - if (!this.tail) { - return void 0; - } - var res = this.tail.value; - this.tail = this.tail.prev; - if (this.tail) { - this.tail.next = null; - } else { - this.head = null; - } - this.length--; - return res; - }; - Yallist.prototype.shift = function() { - if (!this.head) { - return void 0; - } - var res = this.head.value; - this.head = this.head.next; - if (this.head) { - this.head.prev = null; - } else { - this.tail = null; - } - this.length--; - return res; - }; - Yallist.prototype.forEach = function(fn, thisp) { - thisp = thisp || this; - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this); - walker = walker.next; - } - }; - Yallist.prototype.forEachReverse = function(fn, thisp) { - thisp = thisp || this; - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this); - walker = walker.prev; - } - }; - Yallist.prototype.get = function(n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - walker = walker.next; - } - if (i === n && walker !== null) { - return walker.value; - } - }; - Yallist.prototype.getReverse = function(n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - walker = walker.prev; - } - if (i === n && walker !== null) { - return walker.value; - } - }; - Yallist.prototype.map = function(fn, thisp) { - thisp = thisp || this; - var res = new Yallist(); - for (var walker = this.head; walker !== null; ) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.next; - } - return res; - }; - Yallist.prototype.mapReverse = function(fn, thisp) { - thisp = thisp || this; - var res = new Yallist(); - for (var walker = this.tail; walker !== null; ) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.prev; - } - return res; - }; - Yallist.prototype.reduce = function(fn, initial) { - var acc; - var walker = this.head; - if (arguments.length > 1) { - acc = initial; - } else if (this.head) { - walker = this.head.next; - acc = this.head.value; - } else { - throw new TypeError("Reduce of empty list with no initial value"); - } - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i); - walker = walker.next; - } - return acc; - }; - Yallist.prototype.reduceReverse = function(fn, initial) { - var acc; - var walker = this.tail; - if (arguments.length > 1) { - acc = initial; - } else if (this.tail) { - walker = this.tail.prev; - acc = this.tail.value; - } else { - throw new TypeError("Reduce of empty list with no initial value"); - } - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i); - walker = walker.prev; - } - return acc; - }; - Yallist.prototype.toArray = function() { - var arr = new Array(this.length); - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.next; - } - return arr; - }; - Yallist.prototype.toArrayReverse = function() { - var arr = new Array(this.length); - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.prev; - } - return arr; - }; - Yallist.prototype.slice = function(from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist(); - if (to < from || to < 0) { - return ret; - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next; - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value); - } - return ret; - }; - Yallist.prototype.sliceReverse = function(from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist(); - if (to < from || to < 0) { - return ret; - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev; - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value); - } - return ret; - }; - Yallist.prototype.splice = function(start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1; - } - if (start < 0) { - start = this.length + start; - } - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next; - } - var ret = []; - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value); - walker = this.removeNode(walker); - } - if (walker === null) { - walker = this.tail; - } - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev; - } - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]); - } - return ret; - }; - Yallist.prototype.reverse = function() { - var head = this.head; - var tail = this.tail; - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev; - walker.prev = walker.next; - walker.next = p; - } - this.head = tail; - this.tail = head; - return this; - }; - function insert(self2, node, value) { - var inserted = node === self2.head ? new Node(value, null, node, self2) : new Node(value, node, node.next, self2); - if (inserted.next === null) { - self2.tail = inserted; - } - if (inserted.prev === null) { - self2.head = inserted; - } - self2.length++; - return inserted; - } - function push(self2, item) { - self2.tail = new Node(item, self2.tail, null, self2); - if (!self2.head) { - self2.head = self2.tail; - } - self2.length++; - } - function unshift(self2, item) { - self2.head = new Node(item, null, self2.head, self2); - if (!self2.tail) { - self2.tail = self2.head; - } - self2.length++; - } - function Node(value, prev, next, list2) { - if (!(this instanceof Node)) { - return new Node(value, prev, next, list2); - } - this.list = list2; - this.value = value; - if (prev) { - prev.next = this; - this.prev = prev; - } else { - this.prev = null; - } - if (next) { - next.prev = this; - this.next = next; - } else { - this.next = null; - } - } - try { - require_iterator()(Yallist); - } catch (er) { - } - } -}); - -// node_modules/lru-cache/index.js -var require_lru_cache = __commonJS({ - "node_modules/lru-cache/index.js"(exports2, module2) { - "use strict"; - var Yallist = require_yallist(); - var MAX = Symbol("max"); - var LENGTH = Symbol("length"); - var LENGTH_CALCULATOR = Symbol("lengthCalculator"); - var ALLOW_STALE = Symbol("allowStale"); - var MAX_AGE = Symbol("maxAge"); - var DISPOSE = Symbol("dispose"); - var NO_DISPOSE_ON_SET = Symbol("noDisposeOnSet"); - var LRU_LIST = Symbol("lruList"); - var CACHE = Symbol("cache"); - var UPDATE_AGE_ON_GET = Symbol("updateAgeOnGet"); - var naiveLength = () => 1; - var LRUCache = class { - constructor(options) { - if (typeof options === "number") - options = { max: options }; - if (!options) - options = {}; - if (options.max && (typeof options.max !== "number" || options.max < 0)) - throw new TypeError("max must be a non-negative number"); - const max = this[MAX] = options.max || Infinity; - const lc = options.length || naiveLength; - this[LENGTH_CALCULATOR] = typeof lc !== "function" ? naiveLength : lc; - this[ALLOW_STALE] = options.stale || false; - if (options.maxAge && typeof options.maxAge !== "number") - throw new TypeError("maxAge must be a number"); - this[MAX_AGE] = options.maxAge || 0; - this[DISPOSE] = options.dispose; - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; - this.reset(); - } - set max(mL) { - if (typeof mL !== "number" || mL < 0) - throw new TypeError("max must be a non-negative number"); - this[MAX] = mL || Infinity; - trim(this); - } - get max() { - return this[MAX]; - } - set allowStale(allowStale) { - this[ALLOW_STALE] = !!allowStale; - } - get allowStale() { - return this[ALLOW_STALE]; - } - set maxAge(mA) { - if (typeof mA !== "number") - throw new TypeError("maxAge must be a non-negative number"); - this[MAX_AGE] = mA; - trim(this); - } - get maxAge() { - return this[MAX_AGE]; - } - set lengthCalculator(lC) { - if (typeof lC !== "function") - lC = naiveLength; - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC; - this[LENGTH] = 0; - this[LRU_LIST].forEach((hit) => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); - this[LENGTH] += hit.length; - }); - } - trim(this); - } - get lengthCalculator() { - return this[LENGTH_CALCULATOR]; - } - get length() { - return this[LENGTH]; - } - get itemCount() { - return this[LRU_LIST].length; - } - rforEach(fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].tail; walker !== null; ) { - const prev = walker.prev; - forEachStep(this, fn, walker, thisp); - walker = prev; - } - } - forEach(fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].head; walker !== null; ) { - const next = walker.next; - forEachStep(this, fn, walker, thisp); - walker = next; - } - } - keys() { - return this[LRU_LIST].toArray().map((k) => k.key); - } - values() { - return this[LRU_LIST].toArray().map((k) => k.value); - } - reset() { - if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { - this[LRU_LIST].forEach((hit) => this[DISPOSE](hit.key, hit.value)); - } - this[CACHE] = new Map(); - this[LRU_LIST] = new Yallist(); - this[LENGTH] = 0; - } - dump() { - return this[LRU_LIST].map((hit) => isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter((h) => h); - } - dumpLru() { - return this[LRU_LIST]; - } - set(key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE]; - if (maxAge && typeof maxAge !== "number") - throw new TypeError("maxAge must be a number"); - const now = maxAge ? Date.now() : 0; - const len = this[LENGTH_CALCULATOR](value, key); - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)); - return false; - } - const node = this[CACHE].get(key); - const item = node.value; - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value); - } - item.now = now; - item.maxAge = maxAge; - item.value = value; - this[LENGTH] += len - item.length; - item.length = len; - this.get(key); - trim(this); - return true; - } - const hit = new Entry(key, value, len, now, maxAge); - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value); - return false; - } - this[LENGTH] += hit.length; - this[LRU_LIST].unshift(hit); - this[CACHE].set(key, this[LRU_LIST].head); - trim(this); - return true; - } - has(key) { - if (!this[CACHE].has(key)) - return false; - const hit = this[CACHE].get(key).value; - return !isStale(this, hit); - } - get(key) { - return get(this, key, true); - } - peek(key) { - return get(this, key, false); - } - pop() { - const node = this[LRU_LIST].tail; - if (!node) - return null; - del(this, node); - return node.value; - } - del(key) { - del(this, this[CACHE].get(key)); - } - load(arr) { - this.reset(); - const now = Date.now(); - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l]; - const expiresAt = hit.e || 0; - if (expiresAt === 0) - this.set(hit.k, hit.v); - else { - const maxAge = expiresAt - now; - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge); - } - } - } - } - prune() { - this[CACHE].forEach((value, key) => get(this, key, false)); - } - }; - var get = (self2, key, doUse) => { - const node = self2[CACHE].get(key); - if (node) { - const hit = node.value; - if (isStale(self2, hit)) { - del(self2, node); - if (!self2[ALLOW_STALE]) - return void 0; - } else { - if (doUse) { - if (self2[UPDATE_AGE_ON_GET]) - node.value.now = Date.now(); - self2[LRU_LIST].unshiftNode(node); - } - } - return hit.value; - } - }; - var isStale = (self2, hit) => { - if (!hit || !hit.maxAge && !self2[MAX_AGE]) - return false; - const diff = Date.now() - hit.now; - return hit.maxAge ? diff > hit.maxAge : self2[MAX_AGE] && diff > self2[MAX_AGE]; - }; - var trim = (self2) => { - if (self2[LENGTH] > self2[MAX]) { - for (let walker = self2[LRU_LIST].tail; self2[LENGTH] > self2[MAX] && walker !== null; ) { - const prev = walker.prev; - del(self2, walker); - walker = prev; - } - } - }; - var del = (self2, node) => { - if (node) { - const hit = node.value; - if (self2[DISPOSE]) - self2[DISPOSE](hit.key, hit.value); - self2[LENGTH] -= hit.length; - self2[CACHE].delete(hit.key); - self2[LRU_LIST].removeNode(node); - } - }; - var Entry = class { - constructor(key, value, length, now, maxAge) { - this.key = key; - this.value = value; - this.length = length; - this.now = now; - this.maxAge = maxAge || 0; - } - }; - var forEachStep = (self2, fn, node, thisp) => { - let hit = node.value; - if (isStale(self2, hit)) { - del(self2, node); - if (!self2[ALLOW_STALE]) - hit = void 0; - } - if (hit) - fn.call(thisp, hit.value, hit.key, self2); - }; - module2.exports = LRUCache; - } -}); - -// node_modules/semver/classes/range.js -var require_range = __commonJS({ - "node_modules/semver/classes/range.js"(exports2, module2) { - var Range39 = class { - constructor(range, options) { - options = parseOptions(options); - if (range instanceof Range39) { - if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { - return range; - } else { - return new Range39(range.raw, options); - } - } - if (range instanceof Comparator) { - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this; - } - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - this.raw = range; - this.set = range.split(/\s*\|\|\s*/).map((range2) => this.parseRange(range2.trim())).filter((c) => c.length); - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`); - } - if (this.set.length > 1) { - const first = this.set[0]; - this.set = this.set.filter((c) => !isNullSet(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c]; - break; - } - } - } - } - this.format(); - } - format() { - this.range = this.set.map((comps) => { - return comps.join(" ").trim(); - }).join("||").trim(); - return this.range; - } - toString() { - return this.range; - } - parseRange(range) { - range = range.trim(); - const memoOpts = Object.keys(this.options).join(","); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); - if (cached) - return cached; - const loose = this.options.loose; - const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug("hyphen replace", range); - range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace); - debug("comparator trim", range, re[t.COMPARATORTRIM]); - range = range.replace(re[t.TILDETRIM], tildeTrimReplace); - range = range.replace(re[t.CARETTRIM], caretTrimReplace); - range = range.split(/\s+/).join(" "); - const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; - const rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)).filter(this.options.loose ? (comp) => !!comp.match(compRe) : () => true).map((comp) => new Comparator(comp, this.options)); - const l = rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet(comp)) - return [comp]; - rangeMap.set(comp.value, comp); - } - if (rangeMap.size > 1 && rangeMap.has("")) - rangeMap.delete(""); - const result = [...rangeMap.values()]; - cache.set(memoKey, result); - return result; - } - intersects(range, options) { - if (!(range instanceof Range39)) { - throw new TypeError("a Range is required"); - } - return this.set.some((thisComparators) => { - return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { - return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options); - }); - }); - }); - }); - } - test(version2) { - if (!version2) { - return false; - } - if (typeof version2 === "string") { - try { - version2 = new SemVer(version2, this.options); - } catch (er) { - return false; - } - } - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version2, this.options)) { - return true; - } - } - return false; - } - }; - module2.exports = Range39; - var LRU = require_lru_cache(); - var cache = new LRU({ max: 1e3 }); - var parseOptions = require_parse_options(); - var Comparator = require_comparator(); - var debug = require_debug(); - var SemVer = require_semver(); - var { - re, - t, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = require_re(); - var isNullSet = (c) => c.value === "<0.0.0-0"; - var isAny = (c) => c.value === ""; - var isSatisfiable = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options); - }); - testComparator = remainingComparators.pop(); - } - return result; - }; - var parseComparator = (comp, options) => { - debug("comp", comp, options); - comp = replaceCarets(comp, options); - debug("caret", comp); - comp = replaceTildes(comp, options); - debug("tildes", comp); - comp = replaceXRanges(comp, options); - debug("xrange", comp); - comp = replaceStars(comp, options); - debug("stars", comp); - return comp; - }; - var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; - var replaceTildes = (comp, options) => comp.trim().split(/\s+/).map((comp2) => { - return replaceTilde(comp2, options); - }).join(" "); - var replaceTilde = (comp, options) => { - const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug("tilde", comp, _, M, m, p, pr); - let ret; - if (isX(M)) { - ret = ""; - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug("replaceTilde pr", pr); - ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; - } - debug("tilde return", ret); - return ret; - }); - }; - var replaceCarets = (comp, options) => comp.trim().split(/\s+/).map((comp2) => { - return replaceCaret(comp2, options); - }).join(" "); - var replaceCaret = (comp, options) => { - debug("caret", comp, options); - const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; - const z = options.includePrerelease ? "-0" : ""; - return comp.replace(r, (_, M, m, p, pr) => { - debug("caret", comp, _, M, m, p, pr); - let ret; - if (isX(M)) { - ret = ""; - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { - if (M === "0") { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug("replaceCaret pr", pr); - if (M === "0") { - if (m === "0") { - ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; - } - } else { - debug("no pr"); - if (M === "0") { - if (m === "0") { - ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; - } - } - debug("caret return", ret); - return ret; - }); - }; - var replaceXRanges = (comp, options) => { - debug("replaceXRanges", comp, options); - return comp.split(/\s+/).map((comp2) => { - return replaceXRange(comp2, options); - }).join(" "); - }; - var replaceXRange = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug("xRange", comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); - const anyX = xp; - if (gtlt === "=" && anyX) { - gtlt = ""; - } - pr = options.includePrerelease ? "-0" : ""; - if (xM) { - if (gtlt === ">" || gtlt === "<") { - ret = "<0.0.0-0"; - } else { - ret = "*"; - } - } else if (gtlt && anyX) { - if (xm) { - m = 0; - } - p = 0; - if (gtlt === ">") { - gtlt = ">="; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === "<=") { - gtlt = "<"; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; - } - } - if (gtlt === "<") - pr = "-0"; - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; - } - debug("xRange return", ret); - return ret; - }); - }; - var replaceStars = (comp, options) => { - debug("replaceStars", comp, options); - return comp.trim().replace(re[t.STAR], ""); - }; - var replaceGTE0 = (comp, options) => { - debug("replaceGTE0", comp, options); - return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], ""); - }; - var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { - from = ""; - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? "-0" : ""}`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? "-0" : ""}`; - } - if (isX(tM)) { - to = ""; - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } - return `${from} ${to}`.trim(); - }; - var testSet = (set, version2, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version2)) { - return false; - } - } - if (version2.prerelease.length && !options.includePrerelease) { - for (let i = 0; i < set.length; i++) { - debug(set[i].semver); - if (set[i].semver === Comparator.ANY) { - continue; - } - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version2.major && allowed.minor === version2.minor && allowed.patch === version2.patch) { - return true; - } - } - } - return false; - } - return true; - }; - } -}); - -// node_modules/semver/classes/comparator.js -var require_comparator = __commonJS({ - "node_modules/semver/classes/comparator.js"(exports2, module2) { - var ANY = Symbol("SemVer ANY"); - var Comparator = class { - static get ANY() { - return ANY; - } - constructor(comp, options) { - options = parseOptions(options); - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp; - } else { - comp = comp.value; - } - } - debug("comparator", comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - if (this.semver === ANY) { - this.value = ""; - } else { - this.value = this.operator + this.semver.version; - } - debug("comp", this); - } - parse(comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; - const m = comp.match(r); - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`); - } - this.operator = m[1] !== void 0 ? m[1] : ""; - if (this.operator === "=") { - this.operator = ""; - } - if (!m[2]) { - this.semver = ANY; - } else { - this.semver = new SemVer(m[2], this.options.loose); - } - } - toString() { - return this.value; - } - test(version2) { - debug("Comparator.test", version2, this.options.loose); - if (this.semver === ANY || version2 === ANY) { - return true; - } - if (typeof version2 === "string") { - try { - version2 = new SemVer(version2, this.options); - } catch (er) { - return false; - } - } - return cmp(version2, this.operator, this.semver, this.options); - } - intersects(comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError("a Comparator is required"); - } - if (!options || typeof options !== "object") { - options = { - loose: !!options, - includePrerelease: false - }; - } - if (this.operator === "") { - if (this.value === "") { - return true; - } - return new Range39(comp.value, options).test(this.value); - } else if (comp.operator === "") { - if (comp.value === "") { - return true; - } - return new Range39(this.value, options).test(comp.semver); - } - const sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">"); - const sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<"); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<="); - const oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && (this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<"); - const oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && (this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">"); - return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; - } - }; - module2.exports = Comparator; - var parseOptions = require_parse_options(); - var { re, t } = require_re(); - var cmp = require_cmp(); - var debug = require_debug(); - var SemVer = require_semver(); - var Range39 = require_range(); - } -}); - -// node_modules/semver/functions/satisfies.js -var require_satisfies = __commonJS({ - "node_modules/semver/functions/satisfies.js"(exports2, module2) { - var Range39 = require_range(); - var satisfies = (version2, range, options) => { - try { - range = new Range39(range, options); - } catch (er) { - return false; - } - return range.test(version2); - }; - module2.exports = satisfies; - } -}); - -// node_modules/semver/ranges/to-comparators.js -var require_to_comparators = __commonJS({ - "node_modules/semver/ranges/to-comparators.js"(exports2, module2) { - var Range39 = require_range(); - var toComparators = (range, options) => new Range39(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" ")); - module2.exports = toComparators; - } -}); - -// node_modules/semver/ranges/max-satisfying.js -var require_max_satisfying = __commonJS({ - "node_modules/semver/ranges/max-satisfying.js"(exports2, module2) { - var SemVer = require_semver(); - var Range39 = require_range(); - var maxSatisfying = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range39(range, options); - } catch (er) { - return null; - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - if (!max || maxSV.compare(v) === -1) { - max = v; - maxSV = new SemVer(max, options); - } - } - }); - return max; - }; - module2.exports = maxSatisfying; - } -}); - -// node_modules/semver/ranges/min-satisfying.js -var require_min_satisfying = __commonJS({ - "node_modules/semver/ranges/min-satisfying.js"(exports2, module2) { - var SemVer = require_semver(); - var Range39 = require_range(); - var minSatisfying = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range39(range, options); - } catch (er) { - return null; - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - if (!min || minSV.compare(v) === 1) { - min = v; - minSV = new SemVer(min, options); - } - } - }); - return min; - }; - module2.exports = minSatisfying; - } -}); - -// node_modules/semver/ranges/min-version.js -var require_min_version = __commonJS({ - "node_modules/semver/ranges/min-version.js"(exports2, module2) { - var SemVer = require_semver(); - var Range39 = require_range(); - var gt = require_gt(); - var minVersion = (range, loose) => { - range = new Range39(range, loose); - let minver = new SemVer("0.0.0"); - if (range.test(minver)) { - return minver; - } - minver = new SemVer("0.0.0-0"); - if (range.test(minver)) { - return minver; - } - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - let setMin = null; - comparators.forEach((comparator) => { - const compver = new SemVer(comparator.semver.version); - switch (comparator.operator) { - case ">": - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - case "": - case ">=": - if (!setMin || gt(compver, setMin)) { - setMin = compver; - } - break; - case "<": - case "<=": - break; - default: - throw new Error(`Unexpected operation: ${comparator.operator}`); - } - }); - if (setMin && (!minver || gt(minver, setMin))) - minver = setMin; - } - if (minver && range.test(minver)) { - return minver; - } - return null; - }; - module2.exports = minVersion; - } -}); - -// node_modules/semver/ranges/valid.js -var require_valid2 = __commonJS({ - "node_modules/semver/ranges/valid.js"(exports2, module2) { - var Range39 = require_range(); - var validRange = (range, options) => { - try { - return new Range39(range, options).range || "*"; - } catch (er) { - return null; - } - }; - module2.exports = validRange; - } -}); - -// node_modules/semver/ranges/outside.js -var require_outside = __commonJS({ - "node_modules/semver/ranges/outside.js"(exports2, module2) { - var SemVer = require_semver(); - var Comparator = require_comparator(); - var { ANY } = Comparator; - var Range39 = require_range(); - var satisfies = require_satisfies(); - var gt = require_gt(); - var lt = require_lt(); - var lte = require_lte(); - var gte = require_gte(); - var outside = (version2, range, hilo, options) => { - version2 = new SemVer(version2, options); - range = new Range39(range, options); - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case ">": - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = ">"; - ecomp = ">="; - break; - case "<": - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = "<"; - ecomp = "<="; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } - if (satisfies(version2, range, options)) { - return false; - } - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - let high = null; - let low = null; - comparators.forEach((comparator) => { - if (comparator.semver === ANY) { - comparator = new Comparator(">=0.0.0"); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); - if (high.operator === comp || high.operator === ecomp) { - return false; - } - if ((!low.operator || low.operator === comp) && ltefn(version2, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version2, low.semver)) { - return false; - } - } - return true; - }; - module2.exports = outside; - } -}); - -// node_modules/semver/ranges/gtr.js -var require_gtr = __commonJS({ - "node_modules/semver/ranges/gtr.js"(exports2, module2) { - var outside = require_outside(); - var gtr = (version2, range, options) => outside(version2, range, ">", options); - module2.exports = gtr; - } -}); - -// node_modules/semver/ranges/ltr.js -var require_ltr = __commonJS({ - "node_modules/semver/ranges/ltr.js"(exports2, module2) { - var outside = require_outside(); - var ltr = (version2, range, options) => outside(version2, range, "<", options); - module2.exports = ltr; - } -}); - -// node_modules/semver/ranges/intersects.js -var require_intersects = __commonJS({ - "node_modules/semver/ranges/intersects.js"(exports2, module2) { - var Range39 = require_range(); - var intersects = (r1, r2, options) => { - r1 = new Range39(r1, options); - r2 = new Range39(r2, options); - return r1.intersects(r2); - }; - module2.exports = intersects; - } -}); - -// node_modules/semver/ranges/simplify.js -var require_simplify = __commonJS({ - "node_modules/semver/ranges/simplify.js"(exports2, module2) { - var satisfies = require_satisfies(); - var compare = require_compare(); - module2.exports = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare(a, b, options)); - for (const version2 of v) { - const included = satisfies(version2, range, options); - if (included) { - prev = version2; - if (!min) - min = version2; - } else { - if (prev) { - set.push([min, prev]); - } - prev = null; - min = null; - } - } - if (min) - set.push([min, null]); - const ranges = []; - for (const [min2, max] of set) { - if (min2 === max) - ranges.push(min2); - else if (!max && min2 === v[0]) - ranges.push("*"); - else if (!max) - ranges.push(`>=${min2}`); - else if (min2 === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min2} - ${max}`); - } - const simplified = ranges.join(" || "); - const original = typeof range.raw === "string" ? range.raw : String(range); - return simplified.length < original.length ? simplified : range; - }; - } -}); - -// node_modules/semver/ranges/subset.js -var require_subset = __commonJS({ - "node_modules/semver/ranges/subset.js"(exports2, module2) { - var Range39 = require_range(); - var Comparator = require_comparator(); - var { ANY } = Comparator; - var satisfies = require_satisfies(); - var compare = require_compare(); - var subset = (sub, dom, options = {}) => { - if (sub === dom) - return true; - sub = new Range39(sub, options); - dom = new Range39(dom, options); - let sawNonNull = false; - OUTER: - for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER; - } - if (sawNonNull) - return false; - } - return true; - }; - var simpleSubset = (sub, dom, options) => { - if (sub === dom) - return true; - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) - return true; - else if (options.includePrerelease) - sub = [new Comparator(">=0.0.0-0")]; - else - sub = [new Comparator(">=0.0.0")]; - } - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) - return true; - else - dom = [new Comparator(">=0.0.0")]; - } - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === ">" || c.operator === ">=") - gt = higherGT(gt, c, options); - else if (c.operator === "<" || c.operator === "<=") - lt = lowerLT(lt, c, options); - else - eqSet.add(c.semver); - } - if (eqSet.size > 1) - return null; - let gtltComp; - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null; - else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) - return null; - } - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) - return null; - if (lt && !satisfies(eq, String(lt), options)) - return null; - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false; - } - return true; - } - let higher, lower; - let hasDomLT, hasDomGT; - let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">="; - hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<="; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; - } - } - if (c.operator === ">" || c.operator === ">=") { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false; - } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options)) - return false; - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; - } - } - if (c.operator === "<" || c.operator === "<=") { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false; - } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options)) - return false; - } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false; - } - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false; - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false; - if (needDomGTPre || needDomLTPre) - return false; - return true; - }; - var higherGT = (a, b, options) => { - if (!a) - return b; - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a; - }; - var lowerLT = (a, b, options) => { - if (!a) - return b; - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a; - }; - module2.exports = subset; - } -}); - -// node_modules/semver/index.js -var require_semver2 = __commonJS({ - "node_modules/semver/index.js"(exports2, module2) { - var internalRe = require_re(); - module2.exports = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: require_constants().SEMVER_SPEC_VERSION, - SemVer: require_semver(), - compareIdentifiers: require_identifiers().compareIdentifiers, - rcompareIdentifiers: require_identifiers().rcompareIdentifiers, - parse: require_parse(), - valid: require_valid(), - clean: require_clean(), - inc: require_inc(), - diff: require_diff2(), - major: require_major(), - minor: require_minor(), - patch: require_patch(), - prerelease: require_prerelease(), - compare: require_compare(), - rcompare: require_rcompare(), - compareLoose: require_compare_loose(), - compareBuild: require_compare_build(), - sort: require_sort(), - rsort: require_rsort(), - gt: require_gt(), - lt: require_lt(), - eq: require_eq(), - neq: require_neq(), - gte: require_gte(), - lte: require_lte(), - cmp: require_cmp(), - coerce: require_coerce(), - Comparator: require_comparator(), - Range: require_range(), - satisfies: require_satisfies(), - toComparators: require_to_comparators(), - maxSatisfying: require_max_satisfying(), - minSatisfying: require_min_satisfying(), - minVersion: require_min_version(), - validRange: require_valid2(), - outside: require_outside(), - gtr: require_gtr(), - ltr: require_ltr(), - intersects: require_intersects(), - simplifyRange: require_simplify(), - subset: require_subset() - }; - } -}); - -// src/model/installBuffer.ts -var import_events16, logger32, State, InstallBuffer; -var init_installBuffer = __esm({ - "src/model/installBuffer.ts"() { - import_events16 = __toModule(require("events")); - init_status(); - logger32 = require_logger2()("model-installBuffer"); - (function(State3) { - State3[State3["Waiting"] = 0] = "Waiting"; - State3[State3["Faild"] = 1] = "Faild"; - State3[State3["Progressing"] = 2] = "Progressing"; - State3[State3["Success"] = 3] = "Success"; - })(State || (State = {})); - InstallBuffer = class extends import_events16.EventEmitter { - constructor(isUpdate = false, isSync = false, channel = void 0) { - super(); - this.isUpdate = isUpdate; - this.isSync = isSync; - this.channel = channel; - this.statMap = new Map(); - this.messagesMap = new Map(); - this.names = []; - } - setExtensions(names) { - this.statMap.clear(); - this.names = names; - for (let name2 of names) { - this.statMap.set(name2, 0); - } - } - addMessage(name2, msg, isProgress = false) { - if (isProgress && this.channel) - return; - let lines = this.messagesMap.get(name2) || []; - this.messagesMap.set(name2, lines.concat(msg.trim().split(/\r?\n/))); - if (this.channel) - this.channel.appendLine(`[${name2}] ${msg}`); - } - startProgress(names) { - for (let name2 of names) { - this.statMap.set(name2, 2); - } - } - finishProgress(name2, succeed = true) { - if (this.channel) { - if (succeed) { - this.channel.appendLine(`[${name2}] install succeed!`); - } else { - this.channel.appendLine(`[${name2}] install failed!`); - } - } - this.statMap.set(name2, succeed ? 3 : 1); - } - get remains() { - let count = 0; - for (let name2 of this.names) { - let stat = this.statMap.get(name2); - if (![3, 1].includes(stat)) { - count = count + 1; - } - } - return count; - } - getLines() { - let lines = []; - for (let name2 of this.names) { - let state = this.statMap.get(name2); - let processText = "*"; - switch (state) { - case 2: { - let d = new Date(); - let idx = Math.floor(d.getMilliseconds() / 100); - processText = frames[idx]; - break; - } - case 1: - processText = "\u2717"; - break; - case 3: - processText = "\u2713"; - break; - } - let msgs = this.messagesMap.get(name2) || []; - lines.push(`- ${processText} ${name2} ${msgs.length ? msgs[msgs.length - 1] : ""}`); - } - return lines; - } - getMessages(line) { - if (line <= 1) - return []; - let name2 = this.names[line - 2]; - if (!name2) - return []; - return this.messagesMap.get(name2); - } - draw(nvim, buffer) { - let { remains } = this; - let first = remains == 0 ? `${this.isUpdate ? "Update" : "Install"} finished` : `Installing, ${remains} remains...`; - let lines = [first, "", ...this.getLines()]; - buffer.setLines(lines, { start: 0, end: -1, strictIndexing: false }, true); - if (remains == 0 && this.interval) { - clearInterval(this.interval); - this.interval = null; - } - if (process.env.VIM_NODE_RPC) { - nvim.command("redraw", true); - } - } - highlight(nvim) { - nvim.call("matchadd", ["CocListFgCyan", "^\\-\\s\\zs\\*"], true); - nvim.call("matchadd", ["CocListFgGreen", "^\\-\\s\\zs\u2713"], true); - nvim.call("matchadd", ["CocListFgRed", "^\\-\\s\\zs\u2717"], true); - nvim.call("matchadd", ["CocListFgYellow", "^-.\\{3\\}\\zs\\S\\+"], true); - } - async show(nvim) { - let { isSync } = this; - if (this.channel) - return; - nvim.pauseNotification(); - nvim.command(isSync ? "enew" : "vs +enew", true); - nvim.call("bufnr", ["%"], true); - nvim.command("setl buftype=nofile bufhidden=wipe noswapfile nobuflisted wrap undolevels=-1", true); - if (!isSync) { - nvim.command("nnoremap q :q", true); - } - this.highlight(nvim); - let res = await nvim.resumeNotification(); - let bufnr = res && res[1] == null ? res[0][1] : null; - if (!bufnr) - return; - this.bufnr = bufnr; - let buffer = nvim.createBuffer(bufnr); - this.interval = setInterval(() => { - this.draw(nvim, buffer); - }, 100); - } - dispose() { - if (this.interval) { - clearInterval(this.interval); - } - } - }; - } -}); - -// node_modules/ini/ini.js -var require_ini = __commonJS({ - "node_modules/ini/ini.js"(exports2) { - exports2.parse = exports2.decode = decode; - exports2.stringify = exports2.encode = encode; - exports2.safe = safe; - exports2.unsafe = unsafe; - var eol = typeof process !== "undefined" && process.platform === "win32" ? "\r\n" : "\n"; - function encode(obj, opt) { - var children = []; - var out = ""; - if (typeof opt === "string") { - opt = { - section: opt, - whitespace: false - }; - } else { - opt = opt || {}; - opt.whitespace = opt.whitespace === true; - } - var separator = opt.whitespace ? " = " : "="; - Object.keys(obj).forEach(function(k, _, __) { - var val = obj[k]; - if (val && Array.isArray(val)) { - val.forEach(function(item) { - out += safe(k + "[]") + separator + safe(item) + "\n"; - }); - } else if (val && typeof val === "object") - children.push(k); - else - out += safe(k) + separator + safe(val) + eol; - }); - if (opt.section && out.length) - out = "[" + safe(opt.section) + "]" + eol + out; - children.forEach(function(k, _, __) { - var nk = dotSplit(k).join("\\."); - var section2 = (opt.section ? opt.section + "." : "") + nk; - var child = encode(obj[k], { - section: section2, - whitespace: opt.whitespace - }); - if (out.length && child.length) - out += eol; - out += child; - }); - return out; - } - function dotSplit(str) { - return str.replace(/\1/g, "LITERAL\\1LITERAL").replace(/\\\./g, "").split(/\./).map(function(part) { - return part.replace(/\1/g, "\\.").replace(/\2LITERAL\\1LITERAL\2/g, ""); - }); - } - function decode(str) { - var out = {}; - var p = out; - var section2 = null; - var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i; - var lines = str.split(/[\r\n]+/g); - lines.forEach(function(line, _, __) { - if (!line || line.match(/^\s*[;#]/)) - return; - var match = line.match(re); - if (!match) - return; - if (match[1] !== void 0) { - section2 = unsafe(match[1]); - if (section2 === "__proto__") { - p = {}; - return; - } - p = out[section2] = out[section2] || {}; - return; - } - var key = unsafe(match[2]); - if (key === "__proto__") - return; - var value = match[3] ? unsafe(match[4]) : true; - switch (value) { - case "true": - case "false": - case "null": - value = JSON.parse(value); - } - if (key.length > 2 && key.slice(-2) === "[]") { - key = key.substring(0, key.length - 2); - if (key === "__proto__") - return; - if (!p[key]) - p[key] = []; - else if (!Array.isArray(p[key])) - p[key] = [p[key]]; - } - if (Array.isArray(p[key])) - p[key].push(value); - else - p[key] = value; - }); - Object.keys(out).filter(function(k, _, __) { - if (!out[k] || typeof out[k] !== "object" || Array.isArray(out[k])) - return false; - var parts = dotSplit(k); - var p2 = out; - var l = parts.pop(); - var nl = l.replace(/\\\./g, "."); - parts.forEach(function(part, _2, __2) { - if (part === "__proto__") - return; - if (!p2[part] || typeof p2[part] !== "object") - p2[part] = {}; - p2 = p2[part]; - }); - if (p2 === out && nl === l) - return false; - p2[nl] = out[k]; - return true; - }).forEach(function(del, _, __) { - delete out[del]; - }); - return out; - } - function isQuoted(val) { - return val.charAt(0) === '"' && val.slice(-1) === '"' || val.charAt(0) === "'" && val.slice(-1) === "'"; - } - function safe(val) { - return typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || val.length > 1 && isQuoted(val) || val !== val.trim() ? JSON.stringify(val) : val.replace(/;/g, "\\;").replace(/#/g, "\\#"); - } - function unsafe(val, doUnesc) { - val = (val || "").trim(); - if (isQuoted(val)) { - if (val.charAt(0) === "'") - val = val.substr(1, val.length - 2); - try { - val = JSON.parse(val); - } catch (_) { - } - } else { - var esc = false; - var unesc = ""; - for (var i = 0, l = val.length; i < l; i++) { - var c = val.charAt(i); - if (esc) { - if ("\\;#".indexOf(c) !== -1) - unesc += c; - else - unesc += "\\" + c; - esc = false; - } else if (";#".indexOf(c) !== -1) - break; - else if (c === "\\") - esc = true; - else - unesc += c; - } - if (esc) - unesc += "\\"; - return unesc.trim(); - } - return val; - } - } -}); - -// node_modules/rc/node_modules/strip-json-comments/index.js -var require_strip_json_comments = __commonJS({ - "node_modules/rc/node_modules/strip-json-comments/index.js"(exports2, module2) { - "use strict"; - var singleComment = 1; - var multiComment = 2; - function stripWithoutWhitespace() { - return ""; - } - function stripWithWhitespace(str, start, end) { - return str.slice(start, end).replace(/\S/g, " "); - } - module2.exports = function(str, opts) { - opts = opts || {}; - var currentChar; - var nextChar; - var insideString = false; - var insideComment = false; - var offset = 0; - var ret = ""; - var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; - for (var i = 0; i < str.length; i++) { - currentChar = str[i]; - nextChar = str[i + 1]; - if (!insideComment && currentChar === '"') { - var escaped = str[i - 1] === "\\" && str[i - 2] !== "\\"; - if (!escaped) { - insideString = !insideString; - } - } - if (insideString) { - continue; - } - if (!insideComment && currentChar + nextChar === "//") { - ret += str.slice(offset, i); - offset = i; - insideComment = singleComment; - i++; - } else if (insideComment === singleComment && currentChar + nextChar === "\r\n") { - i++; - insideComment = false; - ret += strip(str, offset, i); - offset = i; - continue; - } else if (insideComment === singleComment && currentChar === "\n") { - insideComment = false; - ret += strip(str, offset, i); - offset = i; - } else if (!insideComment && currentChar + nextChar === "/*") { - ret += str.slice(offset, i); - offset = i; - insideComment = multiComment; - i++; - continue; - } else if (insideComment === multiComment && currentChar + nextChar === "*/") { - i++; - insideComment = false; - ret += strip(str, offset, i + 1); - offset = i + 1; - continue; - } - } - return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset)); - }; - } -}); - -// node_modules/rc/lib/utils.js -var require_utils3 = __commonJS({ - "node_modules/rc/lib/utils.js"(exports2) { - "use strict"; - var fs27 = require("fs"); - var ini = require_ini(); - var path36 = require("path"); - var stripJsonComments = require_strip_json_comments(); - var parse5 = exports2.parse = function(content) { - if (/^\s*{/.test(content)) - return JSON.parse(stripJsonComments(content)); - return ini.parse(content); - }; - var file = exports2.file = function() { - var args = [].slice.call(arguments).filter(function(arg) { - return arg != null; - }); - for (var i in args) - if (typeof args[i] !== "string") - return; - var file2 = path36.join.apply(null, args); - var content; - try { - return fs27.readFileSync(file2, "utf-8"); - } catch (err) { - return; - } - }; - var json = exports2.json = function() { - var content = file.apply(null, arguments); - return content ? parse5(content) : null; - }; - var env = exports2.env = function(prefix, env2) { - env2 = env2 || process.env; - var obj = {}; - var l = prefix.length; - for (var k in env2) { - if (k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) { - var keypath = k.substring(l).split("__"); - var _emptyStringIndex; - while ((_emptyStringIndex = keypath.indexOf("")) > -1) { - keypath.splice(_emptyStringIndex, 1); - } - var cursor = obj; - keypath.forEach(function _buildSubObj(_subkey, i) { - if (!_subkey || typeof cursor !== "object") - return; - if (i === keypath.length - 1) - cursor[_subkey] = env2[k]; - if (cursor[_subkey] === void 0) - cursor[_subkey] = {}; - cursor = cursor[_subkey]; - }); - } - } - return obj; - }; - var find = exports2.find = function() { - var rel = path36.join.apply(null, [].slice.call(arguments)); - function find2(start, rel2) { - var file2 = path36.join(start, rel2); - try { - fs27.statSync(file2); - return file2; - } catch (err) { - if (path36.dirname(start) !== start) - return find2(path36.dirname(start), rel2); - } - } - return find2(process.cwd(), rel); - }; - } -}); - -// node_modules/deep-extend/lib/deep-extend.js -var require_deep_extend = __commonJS({ - "node_modules/deep-extend/lib/deep-extend.js"(exports2, module2) { - "use strict"; - function isSpecificValue(val) { - return val instanceof Buffer || val instanceof Date || val instanceof RegExp ? true : false; - } - function cloneSpecificValue(val) { - if (val instanceof Buffer) { - var x = Buffer.alloc ? Buffer.alloc(val.length) : new Buffer(val.length); - val.copy(x); - return x; - } else if (val instanceof Date) { - return new Date(val.getTime()); - } else if (val instanceof RegExp) { - return new RegExp(val); - } else { - throw new Error("Unexpected situation"); - } - } - function deepCloneArray(arr) { - var clone = []; - arr.forEach(function(item, index) { - if (typeof item === "object" && item !== null) { - if (Array.isArray(item)) { - clone[index] = deepCloneArray(item); - } else if (isSpecificValue(item)) { - clone[index] = cloneSpecificValue(item); - } else { - clone[index] = deepExtend({}, item); - } - } else { - clone[index] = item; - } - }); - return clone; - } - function safeGetProperty(object, property) { - return property === "__proto__" ? void 0 : object[property]; - } - var deepExtend = module2.exports = function() { - if (arguments.length < 1 || typeof arguments[0] !== "object") { - return false; - } - if (arguments.length < 2) { - return arguments[0]; - } - var target = arguments[0]; - var args = Array.prototype.slice.call(arguments, 1); - var val, src, clone; - args.forEach(function(obj) { - if (typeof obj !== "object" || obj === null || Array.isArray(obj)) { - return; - } - Object.keys(obj).forEach(function(key) { - src = safeGetProperty(target, key); - val = safeGetProperty(obj, key); - if (val === target) { - return; - } else if (typeof val !== "object" || val === null) { - target[key] = val; - return; - } else if (Array.isArray(val)) { - target[key] = deepCloneArray(val); - return; - } else if (isSpecificValue(val)) { - target[key] = cloneSpecificValue(val); - return; - } else if (typeof src !== "object" || src === null || Array.isArray(src)) { - target[key] = deepExtend({}, val); - return; - } else { - target[key] = deepExtend(src, val); - return; - } - }); - }); - return target; - }; - } -}); - -// node_modules/minimist/index.js -var require_minimist = __commonJS({ - "node_modules/minimist/index.js"(exports2, module2) { - module2.exports = function(args, opts) { - if (!opts) - opts = {}; - var flags = { bools: {}, strings: {}, unknownFn: null }; - if (typeof opts["unknown"] === "function") { - flags.unknownFn = opts["unknown"]; - } - if (typeof opts["boolean"] === "boolean" && opts["boolean"]) { - flags.allBools = true; - } else { - [].concat(opts["boolean"]).filter(Boolean).forEach(function(key2) { - flags.bools[key2] = true; - }); - } - var aliases = {}; - Object.keys(opts.alias || {}).forEach(function(key2) { - aliases[key2] = [].concat(opts.alias[key2]); - aliases[key2].forEach(function(x) { - aliases[x] = [key2].concat(aliases[key2].filter(function(y) { - return x !== y; - })); - }); - }); - [].concat(opts.string).filter(Boolean).forEach(function(key2) { - flags.strings[key2] = true; - if (aliases[key2]) { - flags.strings[aliases[key2]] = true; - } - }); - var defaults2 = opts["default"] || {}; - var argv = { _: [] }; - Object.keys(flags.bools).forEach(function(key2) { - setArg(key2, defaults2[key2] === void 0 ? false : defaults2[key2]); - }); - var notFlags = []; - if (args.indexOf("--") !== -1) { - notFlags = args.slice(args.indexOf("--") + 1); - args = args.slice(0, args.indexOf("--")); - } - function argDefined(key2, arg2) { - return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2]; - } - function setArg(key2, val, arg2) { - if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) { - if (flags.unknownFn(arg2) === false) - return; - } - var value2 = !flags.strings[key2] && isNumber(val) ? Number(val) : val; - setKey(argv, key2.split("."), value2); - (aliases[key2] || []).forEach(function(x) { - setKey(argv, x.split("."), value2); - }); - } - function setKey(obj, keys, value2) { - var o = obj; - for (var i2 = 0; i2 < keys.length - 1; i2++) { - var key2 = keys[i2]; - if (key2 === "__proto__") - return; - if (o[key2] === void 0) - o[key2] = {}; - if (o[key2] === Object.prototype || o[key2] === Number.prototype || o[key2] === String.prototype) - o[key2] = {}; - if (o[key2] === Array.prototype) - o[key2] = []; - o = o[key2]; - } - var key2 = keys[keys.length - 1]; - if (key2 === "__proto__") - return; - if (o === Object.prototype || o === Number.prototype || o === String.prototype) - o = {}; - if (o === Array.prototype) - o = []; - if (o[key2] === void 0 || flags.bools[key2] || typeof o[key2] === "boolean") { - o[key2] = value2; - } else if (Array.isArray(o[key2])) { - o[key2].push(value2); - } else { - o[key2] = [o[key2], value2]; - } - } - function aliasIsBoolean(key2) { - return aliases[key2].some(function(x) { - return flags.bools[x]; - }); - } - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (/^--.+=/.test(arg)) { - var m = arg.match(/^--([^=]+)=([\s\S]*)$/); - var key = m[1]; - var value = m[2]; - if (flags.bools[key]) { - value = value !== "false"; - } - setArg(key, value, arg); - } else if (/^--no-.+/.test(arg)) { - var key = arg.match(/^--no-(.+)/)[1]; - setArg(key, false, arg); - } else if (/^--.+/.test(arg)) { - var key = arg.match(/^--(.+)/)[1]; - var next = args[i + 1]; - if (next !== void 0 && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) { - setArg(key, next, arg); - i++; - } else if (/^(true|false)$/.test(next)) { - setArg(key, next === "true", arg); - i++; - } else { - setArg(key, flags.strings[key] ? "" : true, arg); - } - } else if (/^-[^-]+/.test(arg)) { - var letters = arg.slice(1, -1).split(""); - var broken = false; - for (var j = 0; j < letters.length; j++) { - var next = arg.slice(j + 2); - if (next === "-") { - setArg(letters[j], next, arg); - continue; - } - if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { - setArg(letters[j], next.split("=")[1], arg); - broken = true; - break; - } - if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { - setArg(letters[j], next, arg); - broken = true; - break; - } - if (letters[j + 1] && letters[j + 1].match(/\W/)) { - setArg(letters[j], arg.slice(j + 2), arg); - broken = true; - break; - } else { - setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg); - } - } - var key = arg.slice(-1)[0]; - if (!broken && key !== "-") { - if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) { - setArg(key, args[i + 1], arg); - i++; - } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) { - setArg(key, args[i + 1] === "true", arg); - i++; - } else { - setArg(key, flags.strings[key] ? "" : true, arg); - } - } - } else { - if (!flags.unknownFn || flags.unknownFn(arg) !== false) { - argv._.push(flags.strings["_"] || !isNumber(arg) ? arg : Number(arg)); - } - if (opts.stopEarly) { - argv._.push.apply(argv._, args.slice(i + 1)); - break; - } - } - } - Object.keys(defaults2).forEach(function(key2) { - if (!hasKey(argv, key2.split("."))) { - setKey(argv, key2.split("."), defaults2[key2]); - (aliases[key2] || []).forEach(function(x) { - setKey(argv, x.split("."), defaults2[key2]); - }); - } - }); - if (opts["--"]) { - argv["--"] = new Array(); - notFlags.forEach(function(key2) { - argv["--"].push(key2); - }); - } else { - notFlags.forEach(function(key2) { - argv._.push(key2); - }); - } - return argv; - }; - function hasKey(obj, keys) { - var o = obj; - keys.slice(0, -1).forEach(function(key2) { - o = o[key2] || {}; - }); - var key = keys[keys.length - 1]; - return key in o; - } - function isNumber(x) { - if (typeof x === "number") - return true; - if (/^0x[0-9a-f]+$/i.test(x)) - return true; - return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); - } - } -}); - -// node_modules/rc/index.js -var require_rc = __commonJS({ - "node_modules/rc/index.js"(exports2, module2) { - var cc = require_utils3(); - var join2 = require("path").join; - var deepExtend = require_deep_extend(); - var etc = "/etc"; - var win = process.platform === "win32"; - var home = win ? process.env.USERPROFILE : process.env.HOME; - module2.exports = function(name2, defaults2, argv, parse5) { - if (typeof name2 !== "string") - throw new Error("rc(name): name *must* be string"); - if (!argv) - argv = require_minimist()(process.argv.slice(2)); - defaults2 = (typeof defaults2 === "string" ? cc.json(defaults2) : defaults2) || {}; - parse5 = parse5 || cc.parse; - var env = cc.env(name2 + "_"); - var configs = [defaults2]; - var configFiles = []; - function addConfigFile(file) { - if (configFiles.indexOf(file) >= 0) - return; - var fileConfig = cc.file(file); - if (fileConfig) { - configs.push(parse5(fileConfig)); - configFiles.push(file); - } - } - if (!win) - [ - join2(etc, name2, "config"), - join2(etc, name2 + "rc") - ].forEach(addConfigFile); - if (home) - [ - join2(home, ".config", name2, "config"), - join2(home, ".config", name2), - join2(home, "." + name2, "config"), - join2(home, "." + name2 + "rc") - ].forEach(addConfigFile); - addConfigFile(cc.find("." + name2 + "rc")); - if (env.config) - addConfigFile(env.config); - if (argv.config) - addConfigFile(argv.config); - return deepExtend.apply(null, configs.concat([ - env, - argv, - configFiles.length ? { configs: configFiles, config: configFiles[configFiles.length - 1] } : void 0 - ])); - }; - } -}); - -// node_modules/safe-buffer/index.js -var require_safe_buffer = __commonJS({ - "node_modules/safe-buffer/index.js"(exports2, module2) { - var buffer = require("buffer"); - var Buffer4 = buffer.Buffer; - function copyProps(src, dst) { - for (var key in src) { - dst[key] = src[key]; - } - } - if (Buffer4.from && Buffer4.alloc && Buffer4.allocUnsafe && Buffer4.allocUnsafeSlow) { - module2.exports = buffer; - } else { - copyProps(buffer, exports2); - exports2.Buffer = SafeBuffer; - } - function SafeBuffer(arg, encodingOrOffset, length) { - return Buffer4(arg, encodingOrOffset, length); - } - copyProps(Buffer4, SafeBuffer); - SafeBuffer.from = function(arg, encodingOrOffset, length) { - if (typeof arg === "number") { - throw new TypeError("Argument must not be a number"); - } - return Buffer4(arg, encodingOrOffset, length); - }; - SafeBuffer.alloc = function(size, fill, encoding) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - var buf = Buffer4(size); - if (fill !== void 0) { - if (typeof encoding === "string") { - buf.fill(fill, encoding); - } else { - buf.fill(fill); - } - } else { - buf.fill(0); - } - return buf; - }; - SafeBuffer.allocUnsafe = function(size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return Buffer4(size); - }; - SafeBuffer.allocUnsafeSlow = function(size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return buffer.SlowBuffer(size); - }; - } -}); - -// node_modules/content-disposition/index.js -var require_content_disposition = __commonJS({ - "node_modules/content-disposition/index.js"(exports2, module2) { - "use strict"; - module2.exports = contentDisposition2; - module2.exports.parse = parse5; - var basename = require("path").basename; - var Buffer4 = require_safe_buffer().Buffer; - var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g; - var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/; - var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g; - var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g; - var QESC_REGEXP = /\\([\u0000-\u007f])/g; - var QUOTE_REGEXP = /([\\"])/g; - var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g; - var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/; - var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/; - var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/; - var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/; - function contentDisposition2(filename, options) { - var opts = options || {}; - var type = opts.type || "attachment"; - var params = createparams(filename, opts.fallback); - return format2(new ContentDisposition(type, params)); - } - function createparams(filename, fallback) { - if (filename === void 0) { - return; - } - var params = {}; - if (typeof filename !== "string") { - throw new TypeError("filename must be a string"); - } - if (fallback === void 0) { - fallback = true; - } - if (typeof fallback !== "string" && typeof fallback !== "boolean") { - throw new TypeError("fallback must be a string or boolean"); - } - if (typeof fallback === "string" && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError("fallback must be ISO-8859-1 string"); - } - var name2 = basename(filename); - var isQuotedString = TEXT_REGEXP.test(name2); - var fallbackName = typeof fallback !== "string" ? fallback && getlatin1(name2) : basename(fallback); - var hasFallback = typeof fallbackName === "string" && fallbackName !== name2; - if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name2)) { - params["filename*"] = name2; - } - if (isQuotedString || hasFallback) { - params.filename = hasFallback ? fallbackName : name2; - } - return params; - } - function format2(obj) { - var parameters = obj.parameters; - var type = obj.type; - if (!type || typeof type !== "string" || !TOKEN_REGEXP.test(type)) { - throw new TypeError("invalid type"); - } - var string2 = String(type).toLowerCase(); - if (parameters && typeof parameters === "object") { - var param; - var params = Object.keys(parameters).sort(); - for (var i = 0; i < params.length; i++) { - param = params[i]; - var val = param.substr(-1) === "*" ? ustring(parameters[param]) : qstring(parameters[param]); - string2 += "; " + param + "=" + val; - } - } - return string2; - } - function decodefield(str) { - var match = EXT_VALUE_REGEXP.exec(str); - if (!match) { - throw new TypeError("invalid extended field value"); - } - var charset = match[1].toLowerCase(); - var encoded = match[2]; - var value; - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode); - switch (charset) { - case "iso-8859-1": - value = getlatin1(binary); - break; - case "utf-8": - value = Buffer4.from(binary, "binary").toString("utf8"); - break; - default: - throw new TypeError("unsupported charset in extended field"); - } - return value; - } - function getlatin1(val) { - return String(val).replace(NON_LATIN1_REGEXP, "?"); - } - function parse5(string2) { - if (!string2 || typeof string2 !== "string") { - throw new TypeError("argument string is required"); - } - var match = DISPOSITION_TYPE_REGEXP.exec(string2); - if (!match) { - throw new TypeError("invalid type format"); - } - var index = match[0].length; - var type = match[1].toLowerCase(); - var key; - var names = []; - var params = {}; - var value; - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ";" ? index - 1 : index; - while (match = PARAM_REGEXP.exec(string2)) { - if (match.index !== index) { - throw new TypeError("invalid parameter format"); - } - index += match[0].length; - key = match[1].toLowerCase(); - value = match[2]; - if (names.indexOf(key) !== -1) { - throw new TypeError("invalid duplicate parameter"); - } - names.push(key); - if (key.indexOf("*") + 1 === key.length) { - key = key.slice(0, -1); - value = decodefield(value); - params[key] = value; - continue; - } - if (typeof params[key] === "string") { - continue; - } - if (value[0] === '"') { - value = value.substr(1, value.length - 2).replace(QESC_REGEXP, "$1"); - } - params[key] = value; - } - if (index !== -1 && index !== string2.length) { - throw new TypeError("invalid parameter format"); - } - return new ContentDisposition(type, params); - } - function pdecode(str, hex) { - return String.fromCharCode(parseInt(hex, 16)); - } - function pencode(char) { - return "%" + String(char).charCodeAt(0).toString(16).toUpperCase(); - } - function qstring(val) { - var str = String(val); - return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"'; - } - function ustring(val) { - var str = String(val); - var encoded = encodeURIComponent(str).replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode); - return "UTF-8''" + encoded; - } - function ContentDisposition(type, parameters) { - this.type = type; - this.parameters = parameters; - } - } -}); - -// node_modules/follow-redirects/debug.js -var require_debug2 = __commonJS({ - "node_modules/follow-redirects/debug.js"(exports2, module2) { - var debug; - module2.exports = function() { - if (!debug) { - try { - debug = require_src()("follow-redirects"); - } catch (error) { - debug = function() { - }; - } - } - debug.apply(null, arguments); - }; - } -}); - -// node_modules/follow-redirects/index.js -var require_follow_redirects = __commonJS({ - "node_modules/follow-redirects/index.js"(exports2, module2) { - var url = require("url"); - var URL = url.URL; - var http3 = require("http"); - var https3 = require("https"); - var Writable = require("stream").Writable; - var assert = require("assert"); - var debug = require_debug2(); - var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; - var eventHandlers = Object.create(null); - events.forEach(function(event) { - eventHandlers[event] = function(arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; - }); - var RedirectionError = createErrorType("ERR_FR_REDIRECTION_FAILURE", ""); - var TooManyRedirectsError = createErrorType("ERR_FR_TOO_MANY_REDIRECTS", "Maximum number of redirects exceeded"); - var MaxBodyLengthExceededError = createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED", "Request body larger than maxBodyLength limit"); - var WriteAfterEndError = createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); - function RedirectableRequest(options, responseCallback) { - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; - if (responseCallback) { - this.on("response", responseCallback); - } - var self2 = this; - this._onNativeResponse = function(response) { - self2._processResponse(response); - }; - this._performRequest(); - } - RedirectableRequest.prototype = Object.create(Writable.prototype); - RedirectableRequest.prototype.abort = function() { - abortRequest(this._currentRequest); - this.emit("abort"); - }; - RedirectableRequest.prototype.write = function(data, encoding, callback) { - if (this._ending) { - throw new WriteAfterEndError(); - } - if (!(typeof data === "string" || typeof data === "object" && "length" in data)) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data, encoding }); - this._currentRequest.write(data, encoding, callback); - } else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } - }; - RedirectableRequest.prototype.end = function(data, encoding, callback) { - if (typeof data === "function") { - callback = data; - data = encoding = null; - } else if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } else { - var self2 = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function() { - self2._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } - }; - RedirectableRequest.prototype.setHeader = function(name2, value) { - this._options.headers[name2] = value; - this._currentRequest.setHeader(name2, value); - }; - RedirectableRequest.prototype.removeHeader = function(name2) { - delete this._options.headers[name2]; - this._currentRequest.removeHeader(name2); - }; - RedirectableRequest.prototype.setTimeout = function(msecs, callback) { - var self2 = this; - if (callback) { - this.on("timeout", callback); - } - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } - function startTimer(socket) { - if (self2._timeout) { - clearTimeout(self2._timeout); - } - self2._timeout = setTimeout(function() { - self2.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } - function clearTimer() { - clearTimeout(this._timeout); - if (callback) { - self2.removeListener("timeout", callback); - } - if (!this.socket) { - self2._currentRequest.removeListener("socket", startTimer); - } - } - if (this.socket) { - startTimer(this.socket); - } else { - this._currentRequest.once("socket", startTimer); - } - this.on("socket", destroyOnTimeout); - this.once("response", clearTimer); - this.once("error", clearTimer); - return this; - }; - [ - "flushHeaders", - "getHeader", - "setNoDelay", - "setSocketKeepAlive" - ].forEach(function(method) { - RedirectableRequest.prototype[method] = function(a, b) { - return this._currentRequest[method](a, b); - }; - }); - ["aborted", "connection", "socket"].forEach(function(property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function() { - return this._currentRequest[property]; - } - }); - }); - RedirectableRequest.prototype._sanitizeOptions = function(options) { - if (!options.headers) { - options.headers = {}; - } - if (options.host) { - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } - }; - RedirectableRequest.prototype._performRequest = function() { - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - this.emit("error", new TypeError("Unsupported protocol " + protocol)); - return; - } - if (this._options.agents) { - var scheme = protocol.substr(0, protocol.length - 1); - this._options.agent = this._options.agents[scheme]; - } - var request2 = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse); - this._currentUrl = url.format(this._options); - request2._redirectable = this; - for (var e = 0; e < events.length; e++) { - request2.on(events[e], eventHandlers[events[e]]); - } - if (this._isRedirect) { - var i = 0; - var self2 = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - if (request2 === self2._currentRequest) { - if (error) { - self2.emit("error", error); - } else if (i < buffers.length) { - var buffer = buffers[i++]; - if (!request2.finished) { - request2.write(buffer.data, buffer.encoding, writeNext); - } - } else if (self2._ended) { - request2.end(); - } - } - })(); - } - }; - RedirectableRequest.prototype._processResponse = function(response) { - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode - }); - } - var location = response.headers.location; - if (location && this._options.followRedirects !== false && statusCode >= 300 && statusCode < 400) { - abortRequest(this._currentRequest); - response.destroy(); - if (++this._redirectCount > this._options.maxRedirects) { - this.emit("error", new TooManyRedirectsError()); - return; - } - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) || url.parse(this._currentUrl).hostname; - var redirectUrl = url.resolve(this._currentUrl, location); - debug("redirecting to", redirectUrl); - this._isRedirect = true; - var redirectUrlParts = url.parse(redirectUrl); - Object.assign(this._options, redirectUrlParts); - if (redirectUrlParts.hostname !== previousHostName) { - removeMatchingHeaders(/^authorization$/i, this._options.headers); - } - if (typeof this._options.beforeRedirect === "function") { - var responseDetails = { headers: response.headers }; - try { - this._options.beforeRedirect.call(null, this._options, responseDetails); - } catch (err) { - this.emit("error", err); - return; - } - this._sanitizeOptions(this._options); - } - try { - this._performRequest(); - } catch (cause) { - var error = new RedirectionError("Redirected request failed: " + cause.message); - error.cause = cause; - this.emit("error", error); - } - } else { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - this._requestBodyBuffers = []; - } - }; - function wrap(protocols) { - var exports3 = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024 - }; - var nativeProtocols = {}; - Object.keys(protocols).forEach(function(scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports3[scheme] = Object.create(nativeProtocol); - function request2(input, options, callback) { - if (typeof input === "string") { - var urlStr = input; - try { - input = urlToOptions(new URL(urlStr)); - } catch (err) { - input = url.parse(urlStr); - } - } else if (URL && input instanceof URL) { - input = urlToOptions(input); - } else { - callback = options; - options = input; - input = { protocol }; - } - if (typeof options === "function") { - callback = options; - options = null; - } - options = Object.assign({ - maxRedirects: exports3.maxRedirects, - maxBodyLength: exports3.maxBodyLength - }, input, options); - options.nativeProtocols = nativeProtocols; - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - Object.defineProperties(wrappedProtocol, { - request: { value: request2, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true } - }); - }); - return exports3; - } - function noop() { - } - function urlToOptions(urlObject) { - var options = { - protocol: urlObject.protocol, - hostname: urlObject.hostname.startsWith("[") ? urlObject.hostname.slice(1, -1) : urlObject.hostname, - hash: urlObject.hash, - search: urlObject.search, - pathname: urlObject.pathname, - path: urlObject.pathname + urlObject.search, - href: urlObject.href - }; - if (urlObject.port !== "") { - options.port = Number(urlObject.port); - } - return options; - } - function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } - } - return lastValue; - } - function createErrorType(code, defaultMessage) { - function CustomError(message) { - Error.captureStackTrace(this, this.constructor); - this.message = message || defaultMessage; - } - CustomError.prototype = new Error(); - CustomError.prototype.constructor = CustomError; - CustomError.prototype.name = "Error [" + code + "]"; - CustomError.prototype.code = code; - return CustomError; - } - function abortRequest(request2) { - for (var e = 0; e < events.length; e++) { - request2.removeListener(events[e], eventHandlers[events[e]]); - } - request2.on("error", noop); - request2.abort(); - } - module2.exports = wrap({ http: http3, https: https3 }); - module2.exports.wrap = wrap; - } -}); - -// node_modules/tar/lib/high-level-opt.js -var require_high_level_opt = __commonJS({ - "node_modules/tar/lib/high-level-opt.js"(exports2, module2) { - "use strict"; - var argmap = new Map([ - ["C", "cwd"], - ["f", "file"], - ["z", "gzip"], - ["P", "preservePaths"], - ["U", "unlink"], - ["strip-components", "strip"], - ["stripComponents", "strip"], - ["keep-newer", "newer"], - ["keepNewer", "newer"], - ["keep-newer-files", "newer"], - ["keepNewerFiles", "newer"], - ["k", "keep"], - ["keep-existing", "keep"], - ["keepExisting", "keep"], - ["m", "noMtime"], - ["no-mtime", "noMtime"], - ["p", "preserveOwner"], - ["L", "follow"], - ["h", "follow"] - ]); - module2.exports = (opt) => opt ? Object.keys(opt).map((k) => [ - argmap.has(k) ? argmap.get(k) : k, - opt[k] - ]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {}; - } -}); - -// node_modules/minipass/index.js -var require_minipass = __commonJS({ - "node_modules/minipass/index.js"(exports2, module2) { - "use strict"; - var EE = require("events"); - var Stream = require("stream"); - var Yallist = require_yallist(); - var SD = require("string_decoder").StringDecoder; - var EOF = Symbol("EOF"); - var MAYBE_EMIT_END = Symbol("maybeEmitEnd"); - var EMITTED_END = Symbol("emittedEnd"); - var EMITTING_END = Symbol("emittingEnd"); - var CLOSED = Symbol("closed"); - var READ = Symbol("read"); - var FLUSH = Symbol("flush"); - var FLUSHCHUNK = Symbol("flushChunk"); - var ENCODING = Symbol("encoding"); - var DECODER = Symbol("decoder"); - var FLOWING = Symbol("flowing"); - var PAUSED = Symbol("paused"); - var RESUME = Symbol("resume"); - var BUFFERLENGTH = Symbol("bufferLength"); - var BUFFERPUSH = Symbol("bufferPush"); - var BUFFERSHIFT = Symbol("bufferShift"); - var OBJECTMODE = Symbol("objectMode"); - var DESTROYED = Symbol("destroyed"); - var doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== "1"; - var ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol("asyncIterator not implemented"); - var ITERATOR = doIter && Symbol.iterator || Symbol("iterator not implemented"); - var isEndish = (ev) => ev === "end" || ev === "finish" || ev === "prefinish"; - var isArrayBuffer = (b) => b instanceof ArrayBuffer || typeof b === "object" && b.constructor && b.constructor.name === "ArrayBuffer" && b.byteLength >= 0; - var isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b); - module2.exports = class Minipass extends Stream { - constructor(options) { - super(); - this[FLOWING] = false; - this[PAUSED] = false; - this.pipes = new Yallist(); - this.buffer = new Yallist(); - this[OBJECTMODE] = options && options.objectMode || false; - if (this[OBJECTMODE]) - this[ENCODING] = null; - else - this[ENCODING] = options && options.encoding || null; - if (this[ENCODING] === "buffer") - this[ENCODING] = null; - this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null; - this[EOF] = false; - this[EMITTED_END] = false; - this[EMITTING_END] = false; - this[CLOSED] = false; - this.writable = true; - this.readable = true; - this[BUFFERLENGTH] = 0; - this[DESTROYED] = false; - } - get bufferLength() { - return this[BUFFERLENGTH]; - } - get encoding() { - return this[ENCODING]; - } - set encoding(enc) { - if (this[OBJECTMODE]) - throw new Error("cannot set encoding in objectMode"); - if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) - throw new Error("cannot change encoding"); - if (this[ENCODING] !== enc) { - this[DECODER] = enc ? new SD(enc) : null; - if (this.buffer.length) - this.buffer = this.buffer.map((chunk) => this[DECODER].write(chunk)); - } - this[ENCODING] = enc; - } - setEncoding(enc) { - this.encoding = enc; - } - get objectMode() { - return this[OBJECTMODE]; - } - set objectMode(om) { - this[OBJECTMODE] = this[OBJECTMODE] || !!om; - } - write(chunk, encoding, cb) { - if (this[EOF]) - throw new Error("write after end"); - if (this[DESTROYED]) { - this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" })); - return true; - } - if (typeof encoding === "function") - cb = encoding, encoding = "utf8"; - if (!encoding) - encoding = "utf8"; - if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { - if (isArrayBufferView(chunk)) - chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); - else if (isArrayBuffer(chunk)) - chunk = Buffer.from(chunk); - else if (typeof chunk !== "string") - this.objectMode = true; - } - if (!this.objectMode && !chunk.length) { - if (this[BUFFERLENGTH] !== 0) - this.emit("readable"); - if (cb) - cb(); - return this.flowing; - } - if (typeof chunk === "string" && !this[OBJECTMODE] && !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { - chunk = Buffer.from(chunk, encoding); - } - if (Buffer.isBuffer(chunk) && this[ENCODING]) - chunk = this[DECODER].write(chunk); - if (this.flowing) { - if (this[BUFFERLENGTH] !== 0) - this[FLUSH](true); - this.emit("data", chunk); - } else - this[BUFFERPUSH](chunk); - if (this[BUFFERLENGTH] !== 0) - this.emit("readable"); - if (cb) - cb(); - return this.flowing; - } - read(n) { - if (this[DESTROYED]) - return null; - try { - if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) - return null; - if (this[OBJECTMODE]) - n = null; - if (this.buffer.length > 1 && !this[OBJECTMODE]) { - if (this.encoding) - this.buffer = new Yallist([ - Array.from(this.buffer).join("") - ]); - else - this.buffer = new Yallist([ - Buffer.concat(Array.from(this.buffer), this[BUFFERLENGTH]) - ]); - } - return this[READ](n || null, this.buffer.head.value); - } finally { - this[MAYBE_EMIT_END](); - } - } - [READ](n, chunk) { - if (n === chunk.length || n === null) - this[BUFFERSHIFT](); - else { - this.buffer.head.value = chunk.slice(n); - chunk = chunk.slice(0, n); - this[BUFFERLENGTH] -= n; - } - this.emit("data", chunk); - if (!this.buffer.length && !this[EOF]) - this.emit("drain"); - return chunk; - } - end(chunk, encoding, cb) { - if (typeof chunk === "function") - cb = chunk, chunk = null; - if (typeof encoding === "function") - cb = encoding, encoding = "utf8"; - if (chunk) - this.write(chunk, encoding); - if (cb) - this.once("end", cb); - this[EOF] = true; - this.writable = false; - if (this.flowing || !this[PAUSED]) - this[MAYBE_EMIT_END](); - return this; - } - [RESUME]() { - if (this[DESTROYED]) - return; - this[PAUSED] = false; - this[FLOWING] = true; - this.emit("resume"); - if (this.buffer.length) - this[FLUSH](); - else if (this[EOF]) - this[MAYBE_EMIT_END](); - else - this.emit("drain"); - } - resume() { - return this[RESUME](); - } - pause() { - this[FLOWING] = false; - this[PAUSED] = true; - } - get destroyed() { - return this[DESTROYED]; - } - get flowing() { - return this[FLOWING]; - } - get paused() { - return this[PAUSED]; - } - [BUFFERPUSH](chunk) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] += 1; - else - this[BUFFERLENGTH] += chunk.length; - return this.buffer.push(chunk); - } - [BUFFERSHIFT]() { - if (this.buffer.length) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] -= 1; - else - this[BUFFERLENGTH] -= this.buffer.head.value.length; - } - return this.buffer.shift(); - } - [FLUSH](noDrain) { - do { - } while (this[FLUSHCHUNK](this[BUFFERSHIFT]())); - if (!noDrain && !this.buffer.length && !this[EOF]) - this.emit("drain"); - } - [FLUSHCHUNK](chunk) { - return chunk ? (this.emit("data", chunk), this.flowing) : false; - } - pipe(dest, opts) { - if (this[DESTROYED]) - return; - const ended = this[EMITTED_END]; - opts = opts || {}; - if (dest === process.stdout || dest === process.stderr) - opts.end = false; - else - opts.end = opts.end !== false; - const p = { dest, opts, ondrain: (_) => this[RESUME]() }; - this.pipes.push(p); - dest.on("drain", p.ondrain); - this[RESUME](); - if (ended && p.opts.end) - p.dest.end(); - return dest; - } - addListener(ev, fn) { - return this.on(ev, fn); - } - on(ev, fn) { - try { - return super.on(ev, fn); - } finally { - if (ev === "data" && !this.pipes.length && !this.flowing) - this[RESUME](); - else if (isEndish(ev) && this[EMITTED_END]) { - super.emit(ev); - this.removeAllListeners(ev); - } - } - } - get emittedEnd() { - return this[EMITTED_END]; - } - [MAYBE_EMIT_END]() { - if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { - this[EMITTING_END] = true; - this.emit("end"); - this.emit("prefinish"); - this.emit("finish"); - if (this[CLOSED]) - this.emit("close"); - this[EMITTING_END] = false; - } - } - emit(ev, data) { - if (ev !== "error" && ev !== "close" && ev !== DESTROYED && this[DESTROYED]) - return; - else if (ev === "data") { - if (!data) - return; - if (this.pipes.length) - this.pipes.forEach((p) => p.dest.write(data) === false && this.pause()); - } else if (ev === "end") { - if (this[EMITTED_END] === true) - return; - this[EMITTED_END] = true; - this.readable = false; - if (this[DECODER]) { - data = this[DECODER].end(); - if (data) { - this.pipes.forEach((p) => p.dest.write(data)); - super.emit("data", data); - } - } - this.pipes.forEach((p) => { - p.dest.removeListener("drain", p.ondrain); - if (p.opts.end) - p.dest.end(); - }); - } else if (ev === "close") { - this[CLOSED] = true; - if (!this[EMITTED_END] && !this[DESTROYED]) - return; - } - const args = new Array(arguments.length); - args[0] = ev; - args[1] = data; - if (arguments.length > 2) { - for (let i = 2; i < arguments.length; i++) { - args[i] = arguments[i]; - } - } - try { - return super.emit.apply(this, args); - } finally { - if (!isEndish(ev)) - this[MAYBE_EMIT_END](); - else - this.removeAllListeners(ev); - } - } - collect() { - const buf = []; - if (!this[OBJECTMODE]) - buf.dataLength = 0; - const p = this.promise(); - this.on("data", (c) => { - buf.push(c); - if (!this[OBJECTMODE]) - buf.dataLength += c.length; - }); - return p.then(() => buf); - } - concat() { - return this[OBJECTMODE] ? Promise.reject(new Error("cannot concat in objectMode")) : this.collect().then((buf) => this[OBJECTMODE] ? Promise.reject(new Error("cannot concat in objectMode")) : this[ENCODING] ? buf.join("") : Buffer.concat(buf, buf.dataLength)); - } - promise() { - return new Promise((resolve3, reject) => { - this.on(DESTROYED, () => reject(new Error("stream destroyed"))); - this.on("end", () => resolve3()); - this.on("error", (er) => reject(er)); - }); - } - [ASYNCITERATOR]() { - const next = () => { - const res = this.read(); - if (res !== null) - return Promise.resolve({ done: false, value: res }); - if (this[EOF]) - return Promise.resolve({ done: true }); - let resolve3 = null; - let reject = null; - const onerr = (er) => { - this.removeListener("data", ondata); - this.removeListener("end", onend); - reject(er); - }; - const ondata = (value) => { - this.removeListener("error", onerr); - this.removeListener("end", onend); - this.pause(); - resolve3({ value, done: !!this[EOF] }); - }; - const onend = () => { - this.removeListener("error", onerr); - this.removeListener("data", ondata); - resolve3({ done: true }); - }; - const ondestroy = () => onerr(new Error("stream destroyed")); - return new Promise((res2, rej) => { - reject = rej; - resolve3 = res2; - this.once(DESTROYED, ondestroy); - this.once("error", onerr); - this.once("end", onend); - this.once("data", ondata); - }); - }; - return { next }; - } - [ITERATOR]() { - const next = () => { - const value = this.read(); - const done = value === null; - return { value, done }; - }; - return { next }; - } - destroy(er) { - if (this[DESTROYED]) { - if (er) - this.emit("error", er); - else - this.emit(DESTROYED); - return this; - } - this[DESTROYED] = true; - this.buffer = new Yallist(); - this[BUFFERLENGTH] = 0; - if (typeof this.close === "function" && !this[CLOSED]) - this.close(); - if (er) - this.emit("error", er); - else - this.emit(DESTROYED); - return this; - } - static isStream(s) { - return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && (typeof s.pipe === "function" || typeof s.write === "function" && typeof s.end === "function")); - } - }; - } -}); - -// node_modules/minizlib/constants.js -var require_constants2 = __commonJS({ - "node_modules/minizlib/constants.js"(exports2, module2) { - var realZlibConstants = require("zlib").constants || { ZLIB_VERNUM: 4736 }; - module2.exports = Object.freeze(Object.assign(Object.create(null), { - Z_NO_FLUSH: 0, - Z_PARTIAL_FLUSH: 1, - Z_SYNC_FLUSH: 2, - Z_FULL_FLUSH: 3, - Z_FINISH: 4, - Z_BLOCK: 5, - Z_OK: 0, - Z_STREAM_END: 1, - Z_NEED_DICT: 2, - Z_ERRNO: -1, - Z_STREAM_ERROR: -2, - Z_DATA_ERROR: -3, - Z_MEM_ERROR: -4, - Z_BUF_ERROR: -5, - Z_VERSION_ERROR: -6, - Z_NO_COMPRESSION: 0, - Z_BEST_SPEED: 1, - Z_BEST_COMPRESSION: 9, - Z_DEFAULT_COMPRESSION: -1, - Z_FILTERED: 1, - Z_HUFFMAN_ONLY: 2, - Z_RLE: 3, - Z_FIXED: 4, - Z_DEFAULT_STRATEGY: 0, - DEFLATE: 1, - INFLATE: 2, - GZIP: 3, - GUNZIP: 4, - DEFLATERAW: 5, - INFLATERAW: 6, - UNZIP: 7, - BROTLI_DECODE: 8, - BROTLI_ENCODE: 9, - Z_MIN_WINDOWBITS: 8, - Z_MAX_WINDOWBITS: 15, - Z_DEFAULT_WINDOWBITS: 15, - Z_MIN_CHUNK: 64, - Z_MAX_CHUNK: Infinity, - Z_DEFAULT_CHUNK: 16384, - Z_MIN_MEMLEVEL: 1, - Z_MAX_MEMLEVEL: 9, - Z_DEFAULT_MEMLEVEL: 8, - Z_MIN_LEVEL: -1, - Z_MAX_LEVEL: 9, - Z_DEFAULT_LEVEL: -1, - BROTLI_OPERATION_PROCESS: 0, - BROTLI_OPERATION_FLUSH: 1, - BROTLI_OPERATION_FINISH: 2, - BROTLI_OPERATION_EMIT_METADATA: 3, - BROTLI_MODE_GENERIC: 0, - BROTLI_MODE_TEXT: 1, - BROTLI_MODE_FONT: 2, - BROTLI_DEFAULT_MODE: 0, - BROTLI_MIN_QUALITY: 0, - BROTLI_MAX_QUALITY: 11, - BROTLI_DEFAULT_QUALITY: 11, - BROTLI_MIN_WINDOW_BITS: 10, - BROTLI_MAX_WINDOW_BITS: 24, - BROTLI_LARGE_MAX_WINDOW_BITS: 30, - BROTLI_DEFAULT_WINDOW: 22, - BROTLI_MIN_INPUT_BLOCK_BITS: 16, - BROTLI_MAX_INPUT_BLOCK_BITS: 24, - BROTLI_PARAM_MODE: 0, - BROTLI_PARAM_QUALITY: 1, - BROTLI_PARAM_LGWIN: 2, - BROTLI_PARAM_LGBLOCK: 3, - BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, - BROTLI_PARAM_SIZE_HINT: 5, - BROTLI_PARAM_LARGE_WINDOW: 6, - BROTLI_PARAM_NPOSTFIX: 7, - BROTLI_PARAM_NDIRECT: 8, - BROTLI_DECODER_RESULT_ERROR: 0, - BROTLI_DECODER_RESULT_SUCCESS: 1, - BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, - BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, - BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, - BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, - BROTLI_DECODER_NO_ERROR: 0, - BROTLI_DECODER_SUCCESS: 1, - BROTLI_DECODER_NEEDS_MORE_INPUT: 2, - BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, - BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, - BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, - BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, - BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, - BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, - BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, - BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, - BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, - BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, - BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, - BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, - BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, - BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, - BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, - BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, - BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, - BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, - BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, - BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, - BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, - BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, - BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, - BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, - BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, - BROTLI_DECODER_ERROR_UNREACHABLE: -31 - }, realZlibConstants)); - } -}); - -// node_modules/minizlib/index.js -var require_minizlib = __commonJS({ - "node_modules/minizlib/index.js"(exports2) { - "use strict"; - var assert = require("assert"); - var Buffer4 = require("buffer").Buffer; - var realZlib = require("zlib"); - var constants = exports2.constants = require_constants2(); - var Minipass = require_minipass(); - var OriginalBufferConcat = Buffer4.concat; - var _superWrite = Symbol("_superWrite"); - var ZlibError = class extends Error { - constructor(err) { - super("zlib: " + err.message); - this.code = err.code; - this.errno = err.errno; - if (!this.code) - this.code = "ZLIB_ERROR"; - this.message = "zlib: " + err.message; - Error.captureStackTrace(this, this.constructor); - } - get name() { - return "ZlibError"; - } - }; - var _opts = Symbol("opts"); - var _flushFlag = Symbol("flushFlag"); - var _finishFlushFlag = Symbol("finishFlushFlag"); - var _fullFlushFlag = Symbol("fullFlushFlag"); - var _handle = Symbol("handle"); - var _onError = Symbol("onError"); - var _sawError = Symbol("sawError"); - var _level = Symbol("level"); - var _strategy = Symbol("strategy"); - var _ended = Symbol("ended"); - var _defaultFullFlush = Symbol("_defaultFullFlush"); - var ZlibBase = class extends Minipass { - constructor(opts, mode) { - if (!opts || typeof opts !== "object") - throw new TypeError("invalid options for ZlibBase constructor"); - super(opts); - this[_sawError] = false; - this[_ended] = false; - this[_opts] = opts; - this[_flushFlag] = opts.flush; - this[_finishFlushFlag] = opts.finishFlush; - try { - this[_handle] = new realZlib[mode](opts); - } catch (er) { - throw new ZlibError(er); - } - this[_onError] = (err) => { - if (this[_sawError]) - return; - this[_sawError] = true; - this.close(); - this.emit("error", err); - }; - this[_handle].on("error", (er) => this[_onError](new ZlibError(er))); - this.once("end", () => this.close); - } - close() { - if (this[_handle]) { - this[_handle].close(); - this[_handle] = null; - this.emit("close"); - } - } - reset() { - if (!this[_sawError]) { - assert(this[_handle], "zlib binding closed"); - return this[_handle].reset(); - } - } - flush(flushFlag) { - if (this.ended) - return; - if (typeof flushFlag !== "number") - flushFlag = this[_fullFlushFlag]; - this.write(Object.assign(Buffer4.alloc(0), { [_flushFlag]: flushFlag })); - } - end(chunk, encoding, cb) { - if (chunk) - this.write(chunk, encoding); - this.flush(this[_finishFlushFlag]); - this[_ended] = true; - return super.end(null, null, cb); - } - get ended() { - return this[_ended]; - } - write(chunk, encoding, cb) { - if (typeof encoding === "function") - cb = encoding, encoding = "utf8"; - if (typeof chunk === "string") - chunk = Buffer4.from(chunk, encoding); - if (this[_sawError]) - return; - assert(this[_handle], "zlib binding closed"); - const nativeHandle = this[_handle]._handle; - const originalNativeClose = nativeHandle.close; - nativeHandle.close = () => { - }; - const originalClose = this[_handle].close; - this[_handle].close = () => { - }; - Buffer4.concat = (args) => args; - let result; - try { - const flushFlag = typeof chunk[_flushFlag] === "number" ? chunk[_flushFlag] : this[_flushFlag]; - result = this[_handle]._processChunk(chunk, flushFlag); - Buffer4.concat = OriginalBufferConcat; - } catch (err) { - Buffer4.concat = OriginalBufferConcat; - this[_onError](new ZlibError(err)); - } finally { - if (this[_handle]) { - this[_handle]._handle = nativeHandle; - nativeHandle.close = originalNativeClose; - this[_handle].close = originalClose; - this[_handle].removeAllListeners("error"); - } - } - if (this[_handle]) - this[_handle].on("error", (er) => this[_onError](new ZlibError(er))); - let writeReturn; - if (result) { - if (Array.isArray(result) && result.length > 0) { - writeReturn = this[_superWrite](Buffer4.from(result[0])); - for (let i = 1; i < result.length; i++) { - writeReturn = this[_superWrite](result[i]); - } - } else { - writeReturn = this[_superWrite](Buffer4.from(result)); - } - } - if (cb) - cb(); - return writeReturn; - } - [_superWrite](data) { - return super.write(data); - } - }; - var Zlib = class extends ZlibBase { - constructor(opts, mode) { - opts = opts || {}; - opts.flush = opts.flush || constants.Z_NO_FLUSH; - opts.finishFlush = opts.finishFlush || constants.Z_FINISH; - super(opts, mode); - this[_fullFlushFlag] = constants.Z_FULL_FLUSH; - this[_level] = opts.level; - this[_strategy] = opts.strategy; - } - params(level, strategy) { - if (this[_sawError]) - return; - if (!this[_handle]) - throw new Error("cannot switch params when binding is closed"); - if (!this[_handle].params) - throw new Error("not supported in this implementation"); - if (this[_level] !== level || this[_strategy] !== strategy) { - this.flush(constants.Z_SYNC_FLUSH); - assert(this[_handle], "zlib binding closed"); - const origFlush = this[_handle].flush; - this[_handle].flush = (flushFlag, cb) => { - this.flush(flushFlag); - cb(); - }; - try { - this[_handle].params(level, strategy); - } finally { - this[_handle].flush = origFlush; - } - if (this[_handle]) { - this[_level] = level; - this[_strategy] = strategy; - } - } - } - }; - var Deflate = class extends Zlib { - constructor(opts) { - super(opts, "Deflate"); - } - }; - var Inflate = class extends Zlib { - constructor(opts) { - super(opts, "Inflate"); - } - }; - var _portable = Symbol("_portable"); - var Gzip = class extends Zlib { - constructor(opts) { - super(opts, "Gzip"); - this[_portable] = opts && !!opts.portable; - } - [_superWrite](data) { - if (!this[_portable]) - return super[_superWrite](data); - this[_portable] = false; - data[9] = 255; - return super[_superWrite](data); - } - }; - var Gunzip = class extends Zlib { - constructor(opts) { - super(opts, "Gunzip"); - } - }; - var DeflateRaw = class extends Zlib { - constructor(opts) { - super(opts, "DeflateRaw"); - } - }; - var InflateRaw = class extends Zlib { - constructor(opts) { - super(opts, "InflateRaw"); - } - }; - var Unzip = class extends Zlib { - constructor(opts) { - super(opts, "Unzip"); - } - }; - var Brotli = class extends ZlibBase { - constructor(opts, mode) { - opts = opts || {}; - opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS; - opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH; - super(opts, mode); - this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH; - } - }; - var BrotliCompress = class extends Brotli { - constructor(opts) { - super(opts, "BrotliCompress"); - } - }; - var BrotliDecompress = class extends Brotli { - constructor(opts) { - super(opts, "BrotliDecompress"); - } - }; - exports2.Deflate = Deflate; - exports2.Inflate = Inflate; - exports2.Gzip = Gzip; - exports2.Gunzip = Gunzip; - exports2.DeflateRaw = DeflateRaw; - exports2.InflateRaw = InflateRaw; - exports2.Unzip = Unzip; - if (typeof realZlib.BrotliCompress === "function") { - exports2.BrotliCompress = BrotliCompress; - exports2.BrotliDecompress = BrotliDecompress; - } else { - exports2.BrotliCompress = exports2.BrotliDecompress = class { - constructor() { - throw new Error("Brotli is not supported in this version of Node.js"); - } - }; - } - } -}); - -// node_modules/tar/lib/normalize-windows-path.js -var require_normalize_windows_path = __commonJS({ - "node_modules/tar/lib/normalize-windows-path.js"(exports2, module2) { - var platform3 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; - module2.exports = platform3 !== "win32" ? (p) => p : (p) => p && p.replace(/\\/g, "/"); - } -}); - -// node_modules/tar/lib/read-entry.js -var require_read_entry = __commonJS({ - "node_modules/tar/lib/read-entry.js"(exports2, module2) { - "use strict"; - var MiniPass = require_minipass(); - var normPath = require_normalize_windows_path(); - var SLURP = Symbol("slurp"); - module2.exports = class ReadEntry extends MiniPass { - constructor(header, ex, gex) { - super(); - this.pause(); - this.extended = ex; - this.globalExtended = gex; - this.header = header; - this.startBlockSize = 512 * Math.ceil(header.size / 512); - this.blockRemain = this.startBlockSize; - this.remain = header.size; - this.type = header.type; - this.meta = false; - this.ignore = false; - switch (this.type) { - case "File": - case "OldFile": - case "Link": - case "SymbolicLink": - case "CharacterDevice": - case "BlockDevice": - case "Directory": - case "FIFO": - case "ContiguousFile": - case "GNUDumpDir": - break; - case "NextFileHasLongLinkpath": - case "NextFileHasLongPath": - case "OldGnuLongPath": - case "GlobalExtendedHeader": - case "ExtendedHeader": - case "OldExtendedHeader": - this.meta = true; - break; - default: - this.ignore = true; - } - this.path = normPath(header.path); - this.mode = header.mode; - if (this.mode) - this.mode = this.mode & 4095; - this.uid = header.uid; - this.gid = header.gid; - this.uname = header.uname; - this.gname = header.gname; - this.size = header.size; - this.mtime = header.mtime; - this.atime = header.atime; - this.ctime = header.ctime; - this.linkpath = normPath(header.linkpath); - this.uname = header.uname; - this.gname = header.gname; - if (ex) - this[SLURP](ex); - if (gex) - this[SLURP](gex, true); - } - write(data) { - const writeLen = data.length; - if (writeLen > this.blockRemain) - throw new Error("writing more to entry than is appropriate"); - const r = this.remain; - const br = this.blockRemain; - this.remain = Math.max(0, r - writeLen); - this.blockRemain = Math.max(0, br - writeLen); - if (this.ignore) - return true; - if (r >= writeLen) - return super.write(data); - return super.write(data.slice(0, r)); - } - [SLURP](ex, global2) { - for (const k in ex) { - if (ex[k] !== null && ex[k] !== void 0 && !(global2 && k === "path")) - this[k] = k === "path" || k === "linkpath" ? normPath(ex[k]) : ex[k]; - } - } - }; - } -}); - -// node_modules/tar/lib/types.js -var require_types2 = __commonJS({ - "node_modules/tar/lib/types.js"(exports2) { - "use strict"; - exports2.name = new Map([ - ["0", "File"], - ["", "OldFile"], - ["1", "Link"], - ["2", "SymbolicLink"], - ["3", "CharacterDevice"], - ["4", "BlockDevice"], - ["5", "Directory"], - ["6", "FIFO"], - ["7", "ContiguousFile"], - ["g", "GlobalExtendedHeader"], - ["x", "ExtendedHeader"], - ["A", "SolarisACL"], - ["D", "GNUDumpDir"], - ["I", "Inode"], - ["K", "NextFileHasLongLinkpath"], - ["L", "NextFileHasLongPath"], - ["M", "ContinuationFile"], - ["N", "OldGnuLongPath"], - ["S", "SparseFile"], - ["V", "TapeVolumeHeader"], - ["X", "OldExtendedHeader"] - ]); - exports2.code = new Map(Array.from(exports2.name).map((kv) => [kv[1], kv[0]])); - } -}); - -// node_modules/tar/lib/large-numbers.js -var require_large_numbers = __commonJS({ - "node_modules/tar/lib/large-numbers.js"(exports2, module2) { - "use strict"; - var encode = (num, buf) => { - if (!Number.isSafeInteger(num)) - throw Error("cannot encode number outside of javascript safe integer range"); - else if (num < 0) - encodeNegative(num, buf); - else - encodePositive(num, buf); - return buf; - }; - var encodePositive = (num, buf) => { - buf[0] = 128; - for (var i = buf.length; i > 1; i--) { - buf[i - 1] = num & 255; - num = Math.floor(num / 256); - } - }; - var encodeNegative = (num, buf) => { - buf[0] = 255; - var flipped = false; - num = num * -1; - for (var i = buf.length; i > 1; i--) { - var byte = num & 255; - num = Math.floor(num / 256); - if (flipped) - buf[i - 1] = onesComp(byte); - else if (byte === 0) - buf[i - 1] = 0; - else { - flipped = true; - buf[i - 1] = twosComp(byte); - } - } - }; - var parse5 = (buf) => { - const pre = buf[0]; - const value = pre === 128 ? pos(buf.slice(1, buf.length)) : pre === 255 ? twos(buf) : null; - if (value === null) - throw Error("invalid base256 encoding"); - if (!Number.isSafeInteger(value)) - throw Error("parsed number outside of javascript safe integer range"); - return value; - }; - var twos = (buf) => { - var len = buf.length; - var sum = 0; - var flipped = false; - for (var i = len - 1; i > -1; i--) { - var byte = buf[i]; - var f; - if (flipped) - f = onesComp(byte); - else if (byte === 0) - f = byte; - else { - flipped = true; - f = twosComp(byte); - } - if (f !== 0) - sum -= f * Math.pow(256, len - i - 1); - } - return sum; - }; - var pos = (buf) => { - var len = buf.length; - var sum = 0; - for (var i = len - 1; i > -1; i--) { - var byte = buf[i]; - if (byte !== 0) - sum += byte * Math.pow(256, len - i - 1); - } - return sum; - }; - var onesComp = (byte) => (255 ^ byte) & 255; - var twosComp = (byte) => (255 ^ byte) + 1 & 255; - module2.exports = { - encode, - parse: parse5 - }; - } -}); - -// node_modules/tar/lib/header.js -var require_header = __commonJS({ - "node_modules/tar/lib/header.js"(exports2, module2) { - "use strict"; - var types = require_types2(); - var pathModule = require("path").posix; - var large = require_large_numbers(); - var SLURP = Symbol("slurp"); - var TYPE = Symbol("type"); - var Header = class { - constructor(data, off, ex, gex) { - this.cksumValid = false; - this.needPax = false; - this.nullBlock = false; - this.block = null; - this.path = null; - this.mode = null; - this.uid = null; - this.gid = null; - this.size = null; - this.mtime = null; - this.cksum = null; - this[TYPE] = "0"; - this.linkpath = null; - this.uname = null; - this.gname = null; - this.devmaj = 0; - this.devmin = 0; - this.atime = null; - this.ctime = null; - if (Buffer.isBuffer(data)) - this.decode(data, off || 0, ex, gex); - else if (data) - this.set(data); - } - decode(buf, off, ex, gex) { - if (!off) - off = 0; - if (!buf || !(buf.length >= off + 512)) - throw new Error("need 512 bytes for header"); - this.path = decString(buf, off, 100); - this.mode = decNumber(buf, off + 100, 8); - this.uid = decNumber(buf, off + 108, 8); - this.gid = decNumber(buf, off + 116, 8); - this.size = decNumber(buf, off + 124, 12); - this.mtime = decDate(buf, off + 136, 12); - this.cksum = decNumber(buf, off + 148, 12); - this[SLURP](ex); - this[SLURP](gex, true); - this[TYPE] = decString(buf, off + 156, 1); - if (this[TYPE] === "") - this[TYPE] = "0"; - if (this[TYPE] === "0" && this.path.substr(-1) === "/") - this[TYPE] = "5"; - if (this[TYPE] === "5") - this.size = 0; - this.linkpath = decString(buf, off + 157, 100); - if (buf.slice(off + 257, off + 265).toString() === "ustar\x0000") { - this.uname = decString(buf, off + 265, 32); - this.gname = decString(buf, off + 297, 32); - this.devmaj = decNumber(buf, off + 329, 8); - this.devmin = decNumber(buf, off + 337, 8); - if (buf[off + 475] !== 0) { - const prefix = decString(buf, off + 345, 155); - this.path = prefix + "/" + this.path; - } else { - const prefix = decString(buf, off + 345, 130); - if (prefix) - this.path = prefix + "/" + this.path; - this.atime = decDate(buf, off + 476, 12); - this.ctime = decDate(buf, off + 488, 12); - } - } - let sum = 8 * 32; - for (let i = off; i < off + 148; i++) - sum += buf[i]; - for (let i = off + 156; i < off + 512; i++) - sum += buf[i]; - this.cksumValid = sum === this.cksum; - if (this.cksum === null && sum === 8 * 32) - this.nullBlock = true; - } - [SLURP](ex, global2) { - for (const k in ex) { - if (ex[k] !== null && ex[k] !== void 0 && !(global2 && k === "path")) - this[k] = ex[k]; - } - } - encode(buf, off) { - if (!buf) { - buf = this.block = Buffer.alloc(512); - off = 0; - } - if (!off) - off = 0; - if (!(buf.length >= off + 512)) - throw new Error("need 512 bytes for header"); - const prefixSize = this.ctime || this.atime ? 130 : 155; - const split = splitPrefix(this.path || "", prefixSize); - const path36 = split[0]; - const prefix = split[1]; - this.needPax = split[2]; - this.needPax = encString(buf, off, 100, path36) || this.needPax; - this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax; - this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax; - this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax; - this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax; - this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax; - buf[off + 156] = this[TYPE].charCodeAt(0); - this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax; - buf.write("ustar\x0000", off + 257, 8); - this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax; - this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax; - this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax; - this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax; - this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax; - if (buf[off + 475] !== 0) - this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax; - else { - this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax; - this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax; - this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax; - } - let sum = 8 * 32; - for (let i = off; i < off + 148; i++) - sum += buf[i]; - for (let i = off + 156; i < off + 512; i++) - sum += buf[i]; - this.cksum = sum; - encNumber(buf, off + 148, 8, this.cksum); - this.cksumValid = true; - return this.needPax; - } - set(data) { - for (const i in data) { - if (data[i] !== null && data[i] !== void 0) - this[i] = data[i]; - } - } - get type() { - return types.name.get(this[TYPE]) || this[TYPE]; - } - get typeKey() { - return this[TYPE]; - } - set type(type) { - if (types.code.has(type)) - this[TYPE] = types.code.get(type); - else - this[TYPE] = type; - } - }; - var splitPrefix = (p, prefixSize) => { - const pathSize = 100; - let pp = p; - let prefix = ""; - let ret; - const root = pathModule.parse(p).root || "."; - if (Buffer.byteLength(pp) < pathSize) - ret = [pp, prefix, false]; - else { - prefix = pathModule.dirname(pp); - pp = pathModule.basename(pp); - do { - if (Buffer.byteLength(pp) <= pathSize && Buffer.byteLength(prefix) <= prefixSize) - ret = [pp, prefix, false]; - else if (Buffer.byteLength(pp) > pathSize && Buffer.byteLength(prefix) <= prefixSize) - ret = [pp.substr(0, pathSize - 1), prefix, true]; - else { - pp = pathModule.join(pathModule.basename(prefix), pp); - prefix = pathModule.dirname(prefix); - } - } while (prefix !== root && !ret); - if (!ret) - ret = [p.substr(0, pathSize - 1), "", true]; - } - return ret; - }; - var decString = (buf, off, size) => buf.slice(off, off + size).toString("utf8").replace(/\0.*/, ""); - var decDate = (buf, off, size) => numToDate(decNumber(buf, off, size)); - var numToDate = (num) => num === null ? null : new Date(num * 1e3); - var decNumber = (buf, off, size) => buf[off] & 128 ? large.parse(buf.slice(off, off + size)) : decSmallNumber(buf, off, size); - var nanNull = (value) => isNaN(value) ? null : value; - var decSmallNumber = (buf, off, size) => nanNull(parseInt(buf.slice(off, off + size).toString("utf8").replace(/\0.*$/, "").trim(), 8)); - var MAXNUM = { - 12: 8589934591, - 8: 2097151 - }; - var encNumber = (buf, off, size, number2) => number2 === null ? false : number2 > MAXNUM[size] || number2 < 0 ? (large.encode(number2, buf.slice(off, off + size)), true) : (encSmallNumber(buf, off, size, number2), false); - var encSmallNumber = (buf, off, size, number2) => buf.write(octalString(number2, size), off, size, "ascii"); - var octalString = (number2, size) => padOctal(Math.floor(number2).toString(8), size); - var padOctal = (string2, size) => (string2.length === size - 1 ? string2 : new Array(size - string2.length - 1).join("0") + string2 + " ") + "\0"; - var encDate = (buf, off, size, date) => date === null ? false : encNumber(buf, off, size, date.getTime() / 1e3); - var NULLS = new Array(156).join("\0"); - var encString = (buf, off, size, string2) => string2 === null ? false : (buf.write(string2 + NULLS, off, size, "utf8"), string2.length !== Buffer.byteLength(string2) || string2.length > size); - module2.exports = Header; - } -}); - -// node_modules/tar/lib/pax.js -var require_pax = __commonJS({ - "node_modules/tar/lib/pax.js"(exports2, module2) { - "use strict"; - var Header = require_header(); - var path36 = require("path"); - var Pax = class { - constructor(obj, global2) { - this.atime = obj.atime || null; - this.charset = obj.charset || null; - this.comment = obj.comment || null; - this.ctime = obj.ctime || null; - this.gid = obj.gid || null; - this.gname = obj.gname || null; - this.linkpath = obj.linkpath || null; - this.mtime = obj.mtime || null; - this.path = obj.path || null; - this.size = obj.size || null; - this.uid = obj.uid || null; - this.uname = obj.uname || null; - this.dev = obj.dev || null; - this.ino = obj.ino || null; - this.nlink = obj.nlink || null; - this.global = global2 || false; - } - encode() { - const body = this.encodeBody(); - if (body === "") - return null; - const bodyLen = Buffer.byteLength(body); - const bufLen = 512 * Math.ceil(1 + bodyLen / 512); - const buf = Buffer.allocUnsafe(bufLen); - for (let i = 0; i < 512; i++) - buf[i] = 0; - new Header({ - path: ("PaxHeader/" + path36.basename(this.path)).slice(0, 99), - mode: this.mode || 420, - uid: this.uid || null, - gid: this.gid || null, - size: bodyLen, - mtime: this.mtime || null, - type: this.global ? "GlobalExtendedHeader" : "ExtendedHeader", - linkpath: "", - uname: this.uname || "", - gname: this.gname || "", - devmaj: 0, - devmin: 0, - atime: this.atime || null, - ctime: this.ctime || null - }).encode(buf); - buf.write(body, 512, bodyLen, "utf8"); - for (let i = bodyLen + 512; i < buf.length; i++) - buf[i] = 0; - return buf; - } - encodeBody() { - return this.encodeField("path") + this.encodeField("ctime") + this.encodeField("atime") + this.encodeField("dev") + this.encodeField("ino") + this.encodeField("nlink") + this.encodeField("charset") + this.encodeField("comment") + this.encodeField("gid") + this.encodeField("gname") + this.encodeField("linkpath") + this.encodeField("mtime") + this.encodeField("size") + this.encodeField("uid") + this.encodeField("uname"); - } - encodeField(field) { - if (this[field] === null || this[field] === void 0) - return ""; - const v = this[field] instanceof Date ? this[field].getTime() / 1e3 : this[field]; - const s = " " + (field === "dev" || field === "ino" || field === "nlink" ? "SCHILY." : "") + field + "=" + v + "\n"; - const byteLen = Buffer.byteLength(s); - let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1; - if (byteLen + digits >= Math.pow(10, digits)) - digits += 1; - const len = digits + byteLen; - return len + s; - } - }; - Pax.parse = (string2, ex, g) => new Pax(merge(parseKV(string2), ex), g); - var merge = (a, b) => b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a; - var parseKV = (string2) => string2.replace(/\n$/, "").split("\n").reduce(parseKVLine, Object.create(null)); - var parseKVLine = (set, line) => { - const n = parseInt(line, 10); - if (n !== Buffer.byteLength(line) + 1) - return set; - line = line.substr((n + " ").length); - const kv = line.split("="); - const k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, "$1"); - if (!k) - return set; - const v = kv.join("="); - set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) ? new Date(v * 1e3) : /^[0-9]+$/.test(v) ? +v : v; - return set; - }; - module2.exports = Pax; - } -}); - -// node_modules/tar/lib/strip-trailing-slashes.js -var require_strip_trailing_slashes = __commonJS({ - "node_modules/tar/lib/strip-trailing-slashes.js"(exports2, module2) { - module2.exports = (str) => { - let i = str.length - 1; - let slashesStart = -1; - while (i > -1 && str.charAt(i) === "/") { - slashesStart = i; - i--; - } - return slashesStart === -1 ? str : str.slice(0, slashesStart); - }; - } -}); - -// node_modules/tar/lib/warn-mixin.js -var require_warn_mixin = __commonJS({ - "node_modules/tar/lib/warn-mixin.js"(exports2, module2) { - "use strict"; - module2.exports = (Base) => class extends Base { - warn(code, message, data = {}) { - if (this.file) - data.file = this.file; - if (this.cwd) - data.cwd = this.cwd; - data.code = message instanceof Error && message.code || code; - data.tarCode = code; - if (!this.strict && data.recoverable !== false) { - if (message instanceof Error) { - data = Object.assign(message, data); - message = message.message; - } - this.emit("warn", data.tarCode, message, data); - } else if (message instanceof Error) - this.emit("error", Object.assign(message, data)); - else - this.emit("error", Object.assign(new Error(`${code}: ${message}`), data)); - } - }; - } -}); - -// node_modules/tar/lib/winchars.js -var require_winchars = __commonJS({ - "node_modules/tar/lib/winchars.js"(exports2, module2) { - "use strict"; - var raw = [ - "|", - "<", - ">", - "?", - ":" - ]; - var win = raw.map((char) => String.fromCharCode(61440 + char.charCodeAt(0))); - var toWin = new Map(raw.map((char, i) => [char, win[i]])); - var toRaw = new Map(win.map((char, i) => [char, raw[i]])); - module2.exports = { - encode: (s) => raw.reduce((s2, c) => s2.split(c).join(toWin.get(c)), s), - decode: (s) => win.reduce((s2, c) => s2.split(c).join(toRaw.get(c)), s) - }; - } -}); - -// node_modules/tar/lib/strip-absolute-path.js -var require_strip_absolute_path = __commonJS({ - "node_modules/tar/lib/strip-absolute-path.js"(exports2, module2) { - var { isAbsolute, parse: parse5 } = require("path").win32; - module2.exports = (path36) => { - let r = ""; - let parsed = parse5(path36); - while (isAbsolute(path36) || parsed.root) { - const root = path36.charAt(0) === "/" && path36.slice(0, 4) !== "//?/" ? "/" : parsed.root; - path36 = path36.substr(root.length); - r += root; - parsed = parse5(path36); - } - return [r, path36]; - }; - } -}); - -// node_modules/tar/lib/mode-fix.js -var require_mode_fix = __commonJS({ - "node_modules/tar/lib/mode-fix.js"(exports2, module2) { - "use strict"; - module2.exports = (mode, isDir, portable) => { - mode &= 4095; - if (portable) - mode = (mode | 384) & ~18; - if (isDir) { - if (mode & 256) - mode |= 64; - if (mode & 32) - mode |= 8; - if (mode & 4) - mode |= 1; - } - return mode; - }; - } -}); - -// node_modules/tar/lib/write-entry.js -var require_write_entry = __commonJS({ - "node_modules/tar/lib/write-entry.js"(exports2, module2) { - "use strict"; - var MiniPass = require_minipass(); - var Pax = require_pax(); - var Header = require_header(); - var fs27 = require("fs"); - var path36 = require("path"); - var normPath = require_normalize_windows_path(); - var stripSlash = require_strip_trailing_slashes(); - var prefixPath = (path37, prefix) => { - if (!prefix) - return normPath(path37); - path37 = normPath(path37).replace(/^\.(\/|$)/, ""); - return stripSlash(prefix) + "/" + path37; - }; - var maxReadSize = 16 * 1024 * 1024; - var PROCESS = Symbol("process"); - var FILE = Symbol("file"); - var DIRECTORY = Symbol("directory"); - var SYMLINK = Symbol("symlink"); - var HARDLINK = Symbol("hardlink"); - var HEADER = Symbol("header"); - var READ = Symbol("read"); - var LSTAT = Symbol("lstat"); - var ONLSTAT = Symbol("onlstat"); - var ONREAD = Symbol("onread"); - var ONREADLINK = Symbol("onreadlink"); - var OPENFILE = Symbol("openfile"); - var ONOPENFILE = Symbol("onopenfile"); - var CLOSE = Symbol("close"); - var MODE = Symbol("mode"); - var AWAITDRAIN = Symbol("awaitDrain"); - var ONDRAIN = Symbol("ondrain"); - var PREFIX = Symbol("prefix"); - var HAD_ERROR = Symbol("hadError"); - var warner = require_warn_mixin(); - var winchars = require_winchars(); - var stripAbsolutePath = require_strip_absolute_path(); - var modeFix = require_mode_fix(); - var WriteEntry = warner(class WriteEntry extends MiniPass { - constructor(p, opt) { - opt = opt || {}; - super(opt); - if (typeof p !== "string") - throw new TypeError("path is required"); - this.path = normPath(p); - this.portable = !!opt.portable; - this.myuid = process.getuid && process.getuid() || 0; - this.myuser = process.env.USER || ""; - this.maxReadSize = opt.maxReadSize || maxReadSize; - this.linkCache = opt.linkCache || new Map(); - this.statCache = opt.statCache || new Map(); - this.preservePaths = !!opt.preservePaths; - this.cwd = normPath(opt.cwd || process.cwd()); - this.strict = !!opt.strict; - this.noPax = !!opt.noPax; - this.noMtime = !!opt.noMtime; - this.mtime = opt.mtime || null; - this.prefix = opt.prefix ? normPath(opt.prefix) : null; - this.fd = null; - this.blockLen = null; - this.blockRemain = null; - this.buf = null; - this.offset = null; - this.length = null; - this.pos = null; - this.remain = null; - if (typeof opt.onwarn === "function") - this.on("warn", opt.onwarn); - let pathWarn = false; - if (!this.preservePaths) { - const [root, stripped] = stripAbsolutePath(this.path); - if (root) { - this.path = stripped; - pathWarn = root; - } - } - this.win32 = !!opt.win32 || process.platform === "win32"; - if (this.win32) { - this.path = winchars.decode(this.path.replace(/\\/g, "/")); - p = p.replace(/\\/g, "/"); - } - this.absolute = normPath(opt.absolute || path36.resolve(this.cwd, p)); - if (this.path === "") - this.path = "./"; - if (pathWarn) { - this.warn("TAR_ENTRY_INFO", `stripping ${pathWarn} from absolute path`, { - entry: this, - path: pathWarn + this.path - }); - } - if (this.statCache.has(this.absolute)) - this[ONLSTAT](this.statCache.get(this.absolute)); - else - this[LSTAT](); - } - emit(ev, ...data) { - if (ev === "error") - this[HAD_ERROR] = true; - return super.emit(ev, ...data); - } - [LSTAT]() { - fs27.lstat(this.absolute, (er, stat) => { - if (er) - return this.emit("error", er); - this[ONLSTAT](stat); - }); - } - [ONLSTAT](stat) { - this.statCache.set(this.absolute, stat); - this.stat = stat; - if (!stat.isFile()) - stat.size = 0; - this.type = getType(stat); - this.emit("stat", stat); - this[PROCESS](); - } - [PROCESS]() { - switch (this.type) { - case "File": - return this[FILE](); - case "Directory": - return this[DIRECTORY](); - case "SymbolicLink": - return this[SYMLINK](); - default: - return this.end(); - } - } - [MODE](mode) { - return modeFix(mode, this.type === "Directory", this.portable); - } - [PREFIX](path37) { - return prefixPath(path37, this.prefix); - } - [HEADER]() { - if (this.type === "Directory" && this.portable) - this.noMtime = true; - this.header = new Header({ - path: this[PREFIX](this.path), - linkpath: this.type === "Link" ? this[PREFIX](this.linkpath) : this.linkpath, - mode: this[MODE](this.stat.mode), - uid: this.portable ? null : this.stat.uid, - gid: this.portable ? null : this.stat.gid, - size: this.stat.size, - mtime: this.noMtime ? null : this.mtime || this.stat.mtime, - type: this.type, - uname: this.portable ? null : this.stat.uid === this.myuid ? this.myuser : "", - atime: this.portable ? null : this.stat.atime, - ctime: this.portable ? null : this.stat.ctime - }); - if (this.header.encode() && !this.noPax) { - super.write(new Pax({ - atime: this.portable ? null : this.header.atime, - ctime: this.portable ? null : this.header.ctime, - gid: this.portable ? null : this.header.gid, - mtime: this.noMtime ? null : this.mtime || this.header.mtime, - path: this[PREFIX](this.path), - linkpath: this.type === "Link" ? this[PREFIX](this.linkpath) : this.linkpath, - size: this.header.size, - uid: this.portable ? null : this.header.uid, - uname: this.portable ? null : this.header.uname, - dev: this.portable ? null : this.stat.dev, - ino: this.portable ? null : this.stat.ino, - nlink: this.portable ? null : this.stat.nlink - }).encode()); - } - super.write(this.header.block); - } - [DIRECTORY]() { - if (this.path.substr(-1) !== "/") - this.path += "/"; - this.stat.size = 0; - this[HEADER](); - this.end(); - } - [SYMLINK]() { - fs27.readlink(this.absolute, (er, linkpath) => { - if (er) - return this.emit("error", er); - this[ONREADLINK](linkpath); - }); - } - [ONREADLINK](linkpath) { - this.linkpath = normPath(linkpath); - this[HEADER](); - this.end(); - } - [HARDLINK](linkpath) { - this.type = "Link"; - this.linkpath = normPath(path36.relative(this.cwd, linkpath)); - this.stat.size = 0; - this[HEADER](); - this.end(); - } - [FILE]() { - if (this.stat.nlink > 1) { - const linkKey = this.stat.dev + ":" + this.stat.ino; - if (this.linkCache.has(linkKey)) { - const linkpath = this.linkCache.get(linkKey); - if (linkpath.indexOf(this.cwd) === 0) - return this[HARDLINK](linkpath); - } - this.linkCache.set(linkKey, this.absolute); - } - this[HEADER](); - if (this.stat.size === 0) - return this.end(); - this[OPENFILE](); - } - [OPENFILE]() { - fs27.open(this.absolute, "r", (er, fd) => { - if (er) - return this.emit("error", er); - this[ONOPENFILE](fd); - }); - } - [ONOPENFILE](fd) { - this.fd = fd; - if (this[HAD_ERROR]) - return this[CLOSE](); - this.blockLen = 512 * Math.ceil(this.stat.size / 512); - this.blockRemain = this.blockLen; - const bufLen = Math.min(this.blockLen, this.maxReadSize); - this.buf = Buffer.allocUnsafe(bufLen); - this.offset = 0; - this.pos = 0; - this.remain = this.stat.size; - this.length = this.buf.length; - this[READ](); - } - [READ]() { - const { fd, buf, offset, length, pos } = this; - fs27.read(fd, buf, offset, length, pos, (er, bytesRead) => { - if (er) { - return this[CLOSE](() => this.emit("error", er)); - } - this[ONREAD](bytesRead); - }); - } - [CLOSE](cb) { - fs27.close(this.fd, cb); - } - [ONREAD](bytesRead) { - if (bytesRead <= 0 && this.remain > 0) { - const er = new Error("encountered unexpected EOF"); - er.path = this.absolute; - er.syscall = "read"; - er.code = "EOF"; - return this[CLOSE](() => this.emit("error", er)); - } - if (bytesRead > this.remain) { - const er = new Error("did not encounter expected EOF"); - er.path = this.absolute; - er.syscall = "read"; - er.code = "EOF"; - return this[CLOSE](() => this.emit("error", er)); - } - if (bytesRead === this.remain) { - for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) { - this.buf[i + this.offset] = 0; - bytesRead++; - this.remain++; - } - } - const writeBuf = this.offset === 0 && bytesRead === this.buf.length ? this.buf : this.buf.slice(this.offset, this.offset + bytesRead); - const flushed = this.write(writeBuf); - if (!flushed) - this[AWAITDRAIN](() => this[ONDRAIN]()); - else - this[ONDRAIN](); - } - [AWAITDRAIN](cb) { - this.once("drain", cb); - } - write(writeBuf) { - if (this.blockRemain < writeBuf.length) { - const er = new Error("writing more data than expected"); - er.path = this.absolute; - return this.emit("error", er); - } - this.remain -= writeBuf.length; - this.blockRemain -= writeBuf.length; - this.pos += writeBuf.length; - this.offset += writeBuf.length; - return super.write(writeBuf); - } - [ONDRAIN]() { - if (!this.remain) { - if (this.blockRemain) - super.write(Buffer.alloc(this.blockRemain)); - return this[CLOSE]((er) => er ? this.emit("error", er) : this.end()); - } - if (this.offset >= this.length) { - this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)); - this.offset = 0; - } - this.length = this.buf.length - this.offset; - this[READ](); - } - }); - var WriteEntrySync = class extends WriteEntry { - [LSTAT]() { - this[ONLSTAT](fs27.lstatSync(this.absolute)); - } - [SYMLINK]() { - this[ONREADLINK](fs27.readlinkSync(this.absolute)); - } - [OPENFILE]() { - this[ONOPENFILE](fs27.openSync(this.absolute, "r")); - } - [READ]() { - let threw = true; - try { - const { fd, buf, offset, length, pos } = this; - const bytesRead = fs27.readSync(fd, buf, offset, length, pos); - this[ONREAD](bytesRead); - threw = false; - } finally { - if (threw) { - try { - this[CLOSE](() => { - }); - } catch (er) { - } - } - } - } - [AWAITDRAIN](cb) { - cb(); - } - [CLOSE](cb) { - fs27.closeSync(this.fd); - cb(); - } - }; - var WriteEntryTar = warner(class WriteEntryTar extends MiniPass { - constructor(readEntry, opt) { - opt = opt || {}; - super(opt); - this.preservePaths = !!opt.preservePaths; - this.portable = !!opt.portable; - this.strict = !!opt.strict; - this.noPax = !!opt.noPax; - this.noMtime = !!opt.noMtime; - this.readEntry = readEntry; - this.type = readEntry.type; - if (this.type === "Directory" && this.portable) - this.noMtime = true; - this.prefix = opt.prefix || null; - this.path = normPath(readEntry.path); - this.mode = this[MODE](readEntry.mode); - this.uid = this.portable ? null : readEntry.uid; - this.gid = this.portable ? null : readEntry.gid; - this.uname = this.portable ? null : readEntry.uname; - this.gname = this.portable ? null : readEntry.gname; - this.size = readEntry.size; - this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime; - this.atime = this.portable ? null : readEntry.atime; - this.ctime = this.portable ? null : readEntry.ctime; - this.linkpath = normPath(readEntry.linkpath); - if (typeof opt.onwarn === "function") - this.on("warn", opt.onwarn); - let pathWarn = false; - if (!this.preservePaths) { - const [root, stripped] = stripAbsolutePath(this.path); - if (root) { - this.path = stripped; - pathWarn = root; - } - } - this.remain = readEntry.size; - this.blockRemain = readEntry.startBlockSize; - this.header = new Header({ - path: this[PREFIX](this.path), - linkpath: this.type === "Link" ? this[PREFIX](this.linkpath) : this.linkpath, - mode: this.mode, - uid: this.portable ? null : this.uid, - gid: this.portable ? null : this.gid, - size: this.size, - mtime: this.noMtime ? null : this.mtime, - type: this.type, - uname: this.portable ? null : this.uname, - atime: this.portable ? null : this.atime, - ctime: this.portable ? null : this.ctime - }); - if (pathWarn) { - this.warn("TAR_ENTRY_INFO", `stripping ${pathWarn} from absolute path`, { - entry: this, - path: pathWarn + this.path - }); - } - if (this.header.encode() && !this.noPax) { - super.write(new Pax({ - atime: this.portable ? null : this.atime, - ctime: this.portable ? null : this.ctime, - gid: this.portable ? null : this.gid, - mtime: this.noMtime ? null : this.mtime, - path: this[PREFIX](this.path), - linkpath: this.type === "Link" ? this[PREFIX](this.linkpath) : this.linkpath, - size: this.size, - uid: this.portable ? null : this.uid, - uname: this.portable ? null : this.uname, - dev: this.portable ? null : this.readEntry.dev, - ino: this.portable ? null : this.readEntry.ino, - nlink: this.portable ? null : this.readEntry.nlink - }).encode()); - } - super.write(this.header.block); - readEntry.pipe(this); - } - [PREFIX](path37) { - return prefixPath(path37, this.prefix); - } - [MODE](mode) { - return modeFix(mode, this.type === "Directory", this.portable); - } - write(data) { - const writeLen = data.length; - if (writeLen > this.blockRemain) - throw new Error("writing more to entry than is appropriate"); - this.blockRemain -= writeLen; - return super.write(data); - } - end() { - if (this.blockRemain) - super.write(Buffer.alloc(this.blockRemain)); - return super.end(); - } - }); - WriteEntry.Sync = WriteEntrySync; - WriteEntry.Tar = WriteEntryTar; - var getType = (stat) => stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : "Unsupported"; - module2.exports = WriteEntry; - } -}); - -// node_modules/tar/lib/pack.js -var require_pack = __commonJS({ - "node_modules/tar/lib/pack.js"(exports2, module2) { - "use strict"; - var PackJob = class { - constructor(path37, absolute) { - this.path = path37 || "./"; - this.absolute = absolute; - this.entry = null; - this.stat = null; - this.readdir = null; - this.pending = false; - this.ignore = false; - this.piped = false; - } - }; - var MiniPass = require_minipass(); - var zlib = require_minizlib(); - var ReadEntry = require_read_entry(); - var WriteEntry = require_write_entry(); - var WriteEntrySync = WriteEntry.Sync; - var WriteEntryTar = WriteEntry.Tar; - var Yallist = require_yallist(); - var EOF = Buffer.alloc(1024); - var ONSTAT = Symbol("onStat"); - var ENDED = Symbol("ended"); - var QUEUE = Symbol("queue"); - var CURRENT = Symbol("current"); - var PROCESS = Symbol("process"); - var PROCESSING = Symbol("processing"); - var PROCESSJOB = Symbol("processJob"); - var JOBS = Symbol("jobs"); - var JOBDONE = Symbol("jobDone"); - var ADDFSENTRY = Symbol("addFSEntry"); - var ADDTARENTRY = Symbol("addTarEntry"); - var STAT = Symbol("stat"); - var READDIR = Symbol("readdir"); - var ONREADDIR = Symbol("onreaddir"); - var PIPE = Symbol("pipe"); - var ENTRY = Symbol("entry"); - var ENTRYOPT = Symbol("entryOpt"); - var WRITEENTRYCLASS = Symbol("writeEntryClass"); - var WRITE = Symbol("write"); - var ONDRAIN = Symbol("ondrain"); - var fs27 = require("fs"); - var path36 = require("path"); - var warner = require_warn_mixin(); - var normPath = require_normalize_windows_path(); - var Pack = warner(class Pack extends MiniPass { - constructor(opt) { - super(opt); - opt = opt || Object.create(null); - this.opt = opt; - this.file = opt.file || ""; - this.cwd = opt.cwd || process.cwd(); - this.maxReadSize = opt.maxReadSize; - this.preservePaths = !!opt.preservePaths; - this.strict = !!opt.strict; - this.noPax = !!opt.noPax; - this.prefix = normPath(opt.prefix || ""); - this.linkCache = opt.linkCache || new Map(); - this.statCache = opt.statCache || new Map(); - this.readdirCache = opt.readdirCache || new Map(); - this[WRITEENTRYCLASS] = WriteEntry; - if (typeof opt.onwarn === "function") - this.on("warn", opt.onwarn); - this.portable = !!opt.portable; - this.zip = null; - if (opt.gzip) { - if (typeof opt.gzip !== "object") - opt.gzip = {}; - if (this.portable) - opt.gzip.portable = true; - this.zip = new zlib.Gzip(opt.gzip); - this.zip.on("data", (chunk) => super.write(chunk)); - this.zip.on("end", (_) => super.end()); - this.zip.on("drain", (_) => this[ONDRAIN]()); - this.on("resume", (_) => this.zip.resume()); - } else - this.on("drain", this[ONDRAIN]); - this.noDirRecurse = !!opt.noDirRecurse; - this.follow = !!opt.follow; - this.noMtime = !!opt.noMtime; - this.mtime = opt.mtime || null; - this.filter = typeof opt.filter === "function" ? opt.filter : (_) => true; - this[QUEUE] = new Yallist(); - this[JOBS] = 0; - this.jobs = +opt.jobs || 4; - this[PROCESSING] = false; - this[ENDED] = false; - } - [WRITE](chunk) { - return super.write(chunk); - } - add(path37) { - this.write(path37); - return this; - } - end(path37) { - if (path37) - this.write(path37); - this[ENDED] = true; - this[PROCESS](); - return this; - } - write(path37) { - if (this[ENDED]) - throw new Error("write after end"); - if (path37 instanceof ReadEntry) - this[ADDTARENTRY](path37); - else - this[ADDFSENTRY](path37); - return this.flowing; - } - [ADDTARENTRY](p) { - const absolute = normPath(path36.resolve(this.cwd, p.path)); - if (!this.filter(p.path, p)) - p.resume(); - else { - const job = new PackJob(p.path, absolute, false); - job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)); - job.entry.on("end", (_) => this[JOBDONE](job)); - this[JOBS] += 1; - this[QUEUE].push(job); - } - this[PROCESS](); - } - [ADDFSENTRY](p) { - const absolute = normPath(path36.resolve(this.cwd, p)); - this[QUEUE].push(new PackJob(p, absolute)); - this[PROCESS](); - } - [STAT](job) { - job.pending = true; - this[JOBS] += 1; - const stat = this.follow ? "stat" : "lstat"; - fs27[stat](job.absolute, (er, stat2) => { - job.pending = false; - this[JOBS] -= 1; - if (er) - this.emit("error", er); - else - this[ONSTAT](job, stat2); - }); - } - [ONSTAT](job, stat) { - this.statCache.set(job.absolute, stat); - job.stat = stat; - if (!this.filter(job.path, stat)) - job.ignore = true; - this[PROCESS](); - } - [READDIR](job) { - job.pending = true; - this[JOBS] += 1; - fs27.readdir(job.absolute, (er, entries) => { - job.pending = false; - this[JOBS] -= 1; - if (er) - return this.emit("error", er); - this[ONREADDIR](job, entries); - }); - } - [ONREADDIR](job, entries) { - this.readdirCache.set(job.absolute, entries); - job.readdir = entries; - this[PROCESS](); - } - [PROCESS]() { - if (this[PROCESSING]) - return; - this[PROCESSING] = true; - for (let w = this[QUEUE].head; w !== null && this[JOBS] < this.jobs; w = w.next) { - this[PROCESSJOB](w.value); - if (w.value.ignore) { - const p = w.next; - this[QUEUE].removeNode(w); - w.next = p; - } - } - this[PROCESSING] = false; - if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { - if (this.zip) - this.zip.end(EOF); - else { - super.write(EOF); - super.end(); - } - } - } - get [CURRENT]() { - return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value; - } - [JOBDONE](job) { - this[QUEUE].shift(); - this[JOBS] -= 1; - this[PROCESS](); - } - [PROCESSJOB](job) { - if (job.pending) - return; - if (job.entry) { - if (job === this[CURRENT] && !job.piped) - this[PIPE](job); - return; - } - if (!job.stat) { - if (this.statCache.has(job.absolute)) - this[ONSTAT](job, this.statCache.get(job.absolute)); - else - this[STAT](job); - } - if (!job.stat) - return; - if (job.ignore) - return; - if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { - if (this.readdirCache.has(job.absolute)) - this[ONREADDIR](job, this.readdirCache.get(job.absolute)); - else - this[READDIR](job); - if (!job.readdir) - return; - } - job.entry = this[ENTRY](job); - if (!job.entry) { - job.ignore = true; - return; - } - if (job === this[CURRENT] && !job.piped) - this[PIPE](job); - } - [ENTRYOPT](job) { - return { - onwarn: (code, msg, data) => this.warn(code, msg, data), - noPax: this.noPax, - cwd: this.cwd, - absolute: job.absolute, - preservePaths: this.preservePaths, - maxReadSize: this.maxReadSize, - strict: this.strict, - portable: this.portable, - linkCache: this.linkCache, - statCache: this.statCache, - noMtime: this.noMtime, - mtime: this.mtime, - prefix: this.prefix - }; - } - [ENTRY](job) { - this[JOBS] += 1; - try { - return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)).on("end", () => this[JOBDONE](job)).on("error", (er) => this.emit("error", er)); - } catch (er) { - this.emit("error", er); - } - } - [ONDRAIN]() { - if (this[CURRENT] && this[CURRENT].entry) - this[CURRENT].entry.resume(); - } - [PIPE](job) { - job.piped = true; - if (job.readdir) { - job.readdir.forEach((entry) => { - const p = job.path; - const base = p === "./" ? "" : p.replace(/\/*$/, "/"); - this[ADDFSENTRY](base + entry); - }); - } - const source = job.entry; - const zip = this.zip; - if (zip) { - source.on("data", (chunk) => { - if (!zip.write(chunk)) - source.pause(); - }); - } else { - source.on("data", (chunk) => { - if (!super.write(chunk)) - source.pause(); - }); - } - } - pause() { - if (this.zip) - this.zip.pause(); - return super.pause(); - } - }); - var PackSync = class extends Pack { - constructor(opt) { - super(opt); - this[WRITEENTRYCLASS] = WriteEntrySync; - } - pause() { - } - resume() { - } - [STAT](job) { - const stat = this.follow ? "statSync" : "lstatSync"; - this[ONSTAT](job, fs27[stat](job.absolute)); - } - [READDIR](job, stat) { - this[ONREADDIR](job, fs27.readdirSync(job.absolute)); - } - [PIPE](job) { - const source = job.entry; - const zip = this.zip; - if (job.readdir) { - job.readdir.forEach((entry) => { - const p = job.path; - const base = p === "./" ? "" : p.replace(/\/*$/, "/"); - this[ADDFSENTRY](base + entry); - }); - } - if (zip) { - source.on("data", (chunk) => { - zip.write(chunk); - }); - } else { - source.on("data", (chunk) => { - super[WRITE](chunk); - }); - } - } - }; - Pack.Sync = PackSync; - module2.exports = Pack; - } -}); - -// node_modules/fs-minipass/index.js -var require_fs_minipass = __commonJS({ - "node_modules/fs-minipass/index.js"(exports2) { - "use strict"; - var MiniPass = require_minipass(); - var EE = require("events").EventEmitter; - var fs27 = require("fs"); - var writev = fs27.writev; - if (!writev) { - const binding = process.binding("fs"); - const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback; - writev = (fd, iovec, pos, cb) => { - const done = (er, bw) => cb(er, bw, iovec); - const req = new FSReqWrap(); - req.oncomplete = done; - binding.writeBuffers(fd, iovec, pos, req); - }; - } - var _autoClose = Symbol("_autoClose"); - var _close = Symbol("_close"); - var _ended = Symbol("_ended"); - var _fd = Symbol("_fd"); - var _finished = Symbol("_finished"); - var _flags = Symbol("_flags"); - var _flush = Symbol("_flush"); - var _handleChunk = Symbol("_handleChunk"); - var _makeBuf = Symbol("_makeBuf"); - var _mode = Symbol("_mode"); - var _needDrain = Symbol("_needDrain"); - var _onerror = Symbol("_onerror"); - var _onopen = Symbol("_onopen"); - var _onread = Symbol("_onread"); - var _onwrite = Symbol("_onwrite"); - var _open = Symbol("_open"); - var _path = Symbol("_path"); - var _pos = Symbol("_pos"); - var _queue = Symbol("_queue"); - var _read = Symbol("_read"); - var _readSize = Symbol("_readSize"); - var _reading = Symbol("_reading"); - var _remain = Symbol("_remain"); - var _size = Symbol("_size"); - var _write = Symbol("_write"); - var _writing = Symbol("_writing"); - var _defaultFlag = Symbol("_defaultFlag"); - var _errored = Symbol("_errored"); - var ReadStream = class extends MiniPass { - constructor(path36, opt) { - opt = opt || {}; - super(opt); - this.readable = true; - this.writable = false; - if (typeof path36 !== "string") - throw new TypeError("path must be a string"); - this[_errored] = false; - this[_fd] = typeof opt.fd === "number" ? opt.fd : null; - this[_path] = path36; - this[_readSize] = opt.readSize || 16 * 1024 * 1024; - this[_reading] = false; - this[_size] = typeof opt.size === "number" ? opt.size : Infinity; - this[_remain] = this[_size]; - this[_autoClose] = typeof opt.autoClose === "boolean" ? opt.autoClose : true; - if (typeof this[_fd] === "number") - this[_read](); - else - this[_open](); - } - get fd() { - return this[_fd]; - } - get path() { - return this[_path]; - } - write() { - throw new TypeError("this is a readable stream"); - } - end() { - throw new TypeError("this is a readable stream"); - } - [_open]() { - fs27.open(this[_path], "r", (er, fd) => this[_onopen](er, fd)); - } - [_onopen](er, fd) { - if (er) - this[_onerror](er); - else { - this[_fd] = fd; - this.emit("open", fd); - this[_read](); - } - } - [_makeBuf]() { - return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])); - } - [_read]() { - if (!this[_reading]) { - this[_reading] = true; - const buf = this[_makeBuf](); - if (buf.length === 0) - return process.nextTick(() => this[_onread](null, 0, buf)); - fs27.read(this[_fd], buf, 0, buf.length, null, (er, br, buf2) => this[_onread](er, br, buf2)); - } - } - [_onread](er, br, buf) { - this[_reading] = false; - if (er) - this[_onerror](er); - else if (this[_handleChunk](br, buf)) - this[_read](); - } - [_close]() { - if (this[_autoClose] && typeof this[_fd] === "number") { - const fd = this[_fd]; - this[_fd] = null; - fs27.close(fd, (er) => er ? this.emit("error", er) : this.emit("close")); - } - } - [_onerror](er) { - this[_reading] = true; - this[_close](); - this.emit("error", er); - } - [_handleChunk](br, buf) { - let ret = false; - this[_remain] -= br; - if (br > 0) - ret = super.write(br < buf.length ? buf.slice(0, br) : buf); - if (br === 0 || this[_remain] <= 0) { - ret = false; - this[_close](); - super.end(); - } - return ret; - } - emit(ev, data) { - switch (ev) { - case "prefinish": - case "finish": - break; - case "drain": - if (typeof this[_fd] === "number") - this[_read](); - break; - case "error": - if (this[_errored]) - return; - this[_errored] = true; - return super.emit(ev, data); - default: - return super.emit(ev, data); - } - } - }; - var ReadStreamSync = class extends ReadStream { - [_open]() { - let threw = true; - try { - this[_onopen](null, fs27.openSync(this[_path], "r")); - threw = false; - } finally { - if (threw) - this[_close](); - } - } - [_read]() { - let threw = true; - try { - if (!this[_reading]) { - this[_reading] = true; - do { - const buf = this[_makeBuf](); - const br = buf.length === 0 ? 0 : fs27.readSync(this[_fd], buf, 0, buf.length, null); - if (!this[_handleChunk](br, buf)) - break; - } while (true); - this[_reading] = false; - } - threw = false; - } finally { - if (threw) - this[_close](); - } - } - [_close]() { - if (this[_autoClose] && typeof this[_fd] === "number") { - const fd = this[_fd]; - this[_fd] = null; - fs27.closeSync(fd); - this.emit("close"); - } - } - }; - var WriteStream = class extends EE { - constructor(path36, opt) { - opt = opt || {}; - super(opt); - this.readable = false; - this.writable = true; - this[_errored] = false; - this[_writing] = false; - this[_ended] = false; - this[_needDrain] = false; - this[_queue] = []; - this[_path] = path36; - this[_fd] = typeof opt.fd === "number" ? opt.fd : null; - this[_mode] = opt.mode === void 0 ? 438 : opt.mode; - this[_pos] = typeof opt.start === "number" ? opt.start : null; - this[_autoClose] = typeof opt.autoClose === "boolean" ? opt.autoClose : true; - const defaultFlag = this[_pos] !== null ? "r+" : "w"; - this[_defaultFlag] = opt.flags === void 0; - this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags; - if (this[_fd] === null) - this[_open](); - } - emit(ev, data) { - if (ev === "error") { - if (this[_errored]) - return; - this[_errored] = true; - } - return super.emit(ev, data); - } - get fd() { - return this[_fd]; - } - get path() { - return this[_path]; - } - [_onerror](er) { - this[_close](); - this[_writing] = true; - this.emit("error", er); - } - [_open]() { - fs27.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)); - } - [_onopen](er, fd) { - if (this[_defaultFlag] && this[_flags] === "r+" && er && er.code === "ENOENT") { - this[_flags] = "w"; - this[_open](); - } else if (er) - this[_onerror](er); - else { - this[_fd] = fd; - this.emit("open", fd); - this[_flush](); - } - } - end(buf, enc) { - if (buf) - this.write(buf, enc); - this[_ended] = true; - if (!this[_writing] && !this[_queue].length && typeof this[_fd] === "number") - this[_onwrite](null, 0); - return this; - } - write(buf, enc) { - if (typeof buf === "string") - buf = Buffer.from(buf, enc); - if (this[_ended]) { - this.emit("error", new Error("write() after end()")); - return false; - } - if (this[_fd] === null || this[_writing] || this[_queue].length) { - this[_queue].push(buf); - this[_needDrain] = true; - return false; - } - this[_writing] = true; - this[_write](buf); - return true; - } - [_write](buf) { - fs27.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)); - } - [_onwrite](er, bw) { - if (er) - this[_onerror](er); - else { - if (this[_pos] !== null) - this[_pos] += bw; - if (this[_queue].length) - this[_flush](); - else { - this[_writing] = false; - if (this[_ended] && !this[_finished]) { - this[_finished] = true; - this[_close](); - this.emit("finish"); - } else if (this[_needDrain]) { - this[_needDrain] = false; - this.emit("drain"); - } - } - } - } - [_flush]() { - if (this[_queue].length === 0) { - if (this[_ended]) - this[_onwrite](null, 0); - } else if (this[_queue].length === 1) - this[_write](this[_queue].pop()); - else { - const iovec = this[_queue]; - this[_queue] = []; - writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)); - } - } - [_close]() { - if (this[_autoClose] && typeof this[_fd] === "number") { - const fd = this[_fd]; - this[_fd] = null; - fs27.close(fd, (er) => er ? this.emit("error", er) : this.emit("close")); - } - } - }; - var WriteStreamSync = class extends WriteStream { - [_open]() { - let fd; - if (this[_defaultFlag] && this[_flags] === "r+") { - try { - fd = fs27.openSync(this[_path], this[_flags], this[_mode]); - } catch (er) { - if (er.code === "ENOENT") { - this[_flags] = "w"; - return this[_open](); - } else - throw er; - } - } else - fd = fs27.openSync(this[_path], this[_flags], this[_mode]); - this[_onopen](null, fd); - } - [_close]() { - if (this[_autoClose] && typeof this[_fd] === "number") { - const fd = this[_fd]; - this[_fd] = null; - fs27.closeSync(fd); - this.emit("close"); - } - } - [_write](buf) { - let threw = true; - try { - this[_onwrite](null, fs27.writeSync(this[_fd], buf, 0, buf.length, this[_pos])); - threw = false; - } finally { - if (threw) - try { - this[_close](); - } catch (_) { - } - } - } - }; - exports2.ReadStream = ReadStream; - exports2.ReadStreamSync = ReadStreamSync; - exports2.WriteStream = WriteStream; - exports2.WriteStreamSync = WriteStreamSync; - } -}); - -// node_modules/tar/lib/parse.js -var require_parse2 = __commonJS({ - "node_modules/tar/lib/parse.js"(exports2, module2) { - "use strict"; - var warner = require_warn_mixin(); - var Header = require_header(); - var EE = require("events"); - var Yallist = require_yallist(); - var maxMetaEntrySize = 1024 * 1024; - var Entry = require_read_entry(); - var Pax = require_pax(); - var zlib = require_minizlib(); - var gzipHeader = Buffer.from([31, 139]); - var STATE = Symbol("state"); - var WRITEENTRY = Symbol("writeEntry"); - var READENTRY = Symbol("readEntry"); - var NEXTENTRY = Symbol("nextEntry"); - var PROCESSENTRY = Symbol("processEntry"); - var EX = Symbol("extendedHeader"); - var GEX = Symbol("globalExtendedHeader"); - var META = Symbol("meta"); - var EMITMETA = Symbol("emitMeta"); - var BUFFER = Symbol("buffer"); - var QUEUE = Symbol("queue"); - var ENDED = Symbol("ended"); - var EMITTEDEND = Symbol("emittedEnd"); - var EMIT = Symbol("emit"); - var UNZIP = Symbol("unzip"); - var CONSUMECHUNK = Symbol("consumeChunk"); - var CONSUMECHUNKSUB = Symbol("consumeChunkSub"); - var CONSUMEBODY = Symbol("consumeBody"); - var CONSUMEMETA = Symbol("consumeMeta"); - var CONSUMEHEADER = Symbol("consumeHeader"); - var CONSUMING = Symbol("consuming"); - var BUFFERCONCAT = Symbol("bufferConcat"); - var MAYBEEND = Symbol("maybeEnd"); - var WRITING = Symbol("writing"); - var ABORTED = Symbol("aborted"); - var DONE = Symbol("onDone"); - var SAW_VALID_ENTRY = Symbol("sawValidEntry"); - var SAW_NULL_BLOCK = Symbol("sawNullBlock"); - var SAW_EOF = Symbol("sawEOF"); - var noop = (_) => true; - module2.exports = warner(class Parser extends EE { - constructor(opt) { - opt = opt || {}; - super(opt); - this.file = opt.file || ""; - this[SAW_VALID_ENTRY] = null; - this.on(DONE, (_) => { - if (this[STATE] === "begin" || this[SAW_VALID_ENTRY] === false) { - this.warn("TAR_BAD_ARCHIVE", "Unrecognized archive format"); - } - }); - if (opt.ondone) - this.on(DONE, opt.ondone); - else { - this.on(DONE, (_) => { - this.emit("prefinish"); - this.emit("finish"); - this.emit("end"); - this.emit("close"); - }); - } - this.strict = !!opt.strict; - this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize; - this.filter = typeof opt.filter === "function" ? opt.filter : noop; - this.writable = true; - this.readable = false; - this[QUEUE] = new Yallist(); - this[BUFFER] = null; - this[READENTRY] = null; - this[WRITEENTRY] = null; - this[STATE] = "begin"; - this[META] = ""; - this[EX] = null; - this[GEX] = null; - this[ENDED] = false; - this[UNZIP] = null; - this[ABORTED] = false; - this[SAW_NULL_BLOCK] = false; - this[SAW_EOF] = false; - if (typeof opt.onwarn === "function") - this.on("warn", opt.onwarn); - if (typeof opt.onentry === "function") - this.on("entry", opt.onentry); - } - [CONSUMEHEADER](chunk, position) { - if (this[SAW_VALID_ENTRY] === null) - this[SAW_VALID_ENTRY] = false; - let header; - try { - header = new Header(chunk, position, this[EX], this[GEX]); - } catch (er) { - return this.warn("TAR_ENTRY_INVALID", er); - } - if (header.nullBlock) { - if (this[SAW_NULL_BLOCK]) { - this[SAW_EOF] = true; - if (this[STATE] === "begin") - this[STATE] = "header"; - this[EMIT]("eof"); - } else { - this[SAW_NULL_BLOCK] = true; - this[EMIT]("nullBlock"); - } - } else { - this[SAW_NULL_BLOCK] = false; - if (!header.cksumValid) - this.warn("TAR_ENTRY_INVALID", "checksum failure", { header }); - else if (!header.path) - this.warn("TAR_ENTRY_INVALID", "path is required", { header }); - else { - const type = header.type; - if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) - this.warn("TAR_ENTRY_INVALID", "linkpath required", { header }); - else if (!/^(Symbolic)?Link$/.test(type) && header.linkpath) - this.warn("TAR_ENTRY_INVALID", "linkpath forbidden", { header }); - else { - const entry = this[WRITEENTRY] = new Entry(header, this[EX], this[GEX]); - if (!this[SAW_VALID_ENTRY]) { - if (entry.remain) { - const onend = () => { - if (!entry.invalid) - this[SAW_VALID_ENTRY] = true; - }; - entry.on("end", onend); - } else - this[SAW_VALID_ENTRY] = true; - } - if (entry.meta) { - if (entry.size > this.maxMetaEntrySize) { - entry.ignore = true; - this[EMIT]("ignoredEntry", entry); - this[STATE] = "ignore"; - entry.resume(); - } else if (entry.size > 0) { - this[META] = ""; - entry.on("data", (c) => this[META] += c); - this[STATE] = "meta"; - } - } else { - this[EX] = null; - entry.ignore = entry.ignore || !this.filter(entry.path, entry); - if (entry.ignore) { - this[EMIT]("ignoredEntry", entry); - this[STATE] = entry.remain ? "ignore" : "header"; - entry.resume(); - } else { - if (entry.remain) - this[STATE] = "body"; - else { - this[STATE] = "header"; - entry.end(); - } - if (!this[READENTRY]) { - this[QUEUE].push(entry); - this[NEXTENTRY](); - } else - this[QUEUE].push(entry); - } - } - } - } - } - } - [PROCESSENTRY](entry) { - let go = true; - if (!entry) { - this[READENTRY] = null; - go = false; - } else if (Array.isArray(entry)) - this.emit.apply(this, entry); - else { - this[READENTRY] = entry; - this.emit("entry", entry); - if (!entry.emittedEnd) { - entry.on("end", (_) => this[NEXTENTRY]()); - go = false; - } - } - return go; - } - [NEXTENTRY]() { - do { - } while (this[PROCESSENTRY](this[QUEUE].shift())); - if (!this[QUEUE].length) { - const re = this[READENTRY]; - const drainNow = !re || re.flowing || re.size === re.remain; - if (drainNow) { - if (!this[WRITING]) - this.emit("drain"); - } else - re.once("drain", (_) => this.emit("drain")); - } - } - [CONSUMEBODY](chunk, position) { - const entry = this[WRITEENTRY]; - const br = entry.blockRemain; - const c = br >= chunk.length && position === 0 ? chunk : chunk.slice(position, position + br); - entry.write(c); - if (!entry.blockRemain) { - this[STATE] = "header"; - this[WRITEENTRY] = null; - entry.end(); - } - return c.length; - } - [CONSUMEMETA](chunk, position) { - const entry = this[WRITEENTRY]; - const ret = this[CONSUMEBODY](chunk, position); - if (!this[WRITEENTRY]) - this[EMITMETA](entry); - return ret; - } - [EMIT](ev, data, extra) { - if (!this[QUEUE].length && !this[READENTRY]) - this.emit(ev, data, extra); - else - this[QUEUE].push([ev, data, extra]); - } - [EMITMETA](entry) { - this[EMIT]("meta", this[META]); - switch (entry.type) { - case "ExtendedHeader": - case "OldExtendedHeader": - this[EX] = Pax.parse(this[META], this[EX], false); - break; - case "GlobalExtendedHeader": - this[GEX] = Pax.parse(this[META], this[GEX], true); - break; - case "NextFileHasLongPath": - case "OldGnuLongPath": - this[EX] = this[EX] || Object.create(null); - this[EX].path = this[META].replace(/\0.*/, ""); - break; - case "NextFileHasLongLinkpath": - this[EX] = this[EX] || Object.create(null); - this[EX].linkpath = this[META].replace(/\0.*/, ""); - break; - default: - throw new Error("unknown meta: " + entry.type); - } - } - abort(error) { - this[ABORTED] = true; - this.emit("abort", error); - this.warn("TAR_ABORT", error, { recoverable: false }); - } - write(chunk) { - if (this[ABORTED]) - return; - if (this[UNZIP] === null && chunk) { - if (this[BUFFER]) { - chunk = Buffer.concat([this[BUFFER], chunk]); - this[BUFFER] = null; - } - if (chunk.length < gzipHeader.length) { - this[BUFFER] = chunk; - return true; - } - for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) { - if (chunk[i] !== gzipHeader[i]) - this[UNZIP] = false; - } - if (this[UNZIP] === null) { - const ended = this[ENDED]; - this[ENDED] = false; - this[UNZIP] = new zlib.Unzip(); - this[UNZIP].on("data", (chunk2) => this[CONSUMECHUNK](chunk2)); - this[UNZIP].on("error", (er) => this.abort(er)); - this[UNZIP].on("end", (_) => { - this[ENDED] = true; - this[CONSUMECHUNK](); - }); - this[WRITING] = true; - const ret2 = this[UNZIP][ended ? "end" : "write"](chunk); - this[WRITING] = false; - return ret2; - } - } - this[WRITING] = true; - if (this[UNZIP]) - this[UNZIP].write(chunk); - else - this[CONSUMECHUNK](chunk); - this[WRITING] = false; - const ret = this[QUEUE].length ? false : this[READENTRY] ? this[READENTRY].flowing : true; - if (!ret && !this[QUEUE].length) - this[READENTRY].once("drain", (_) => this.emit("drain")); - return ret; - } - [BUFFERCONCAT](c) { - if (c && !this[ABORTED]) - this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c; - } - [MAYBEEND]() { - if (this[ENDED] && !this[EMITTEDEND] && !this[ABORTED] && !this[CONSUMING]) { - this[EMITTEDEND] = true; - const entry = this[WRITEENTRY]; - if (entry && entry.blockRemain) { - const have = this[BUFFER] ? this[BUFFER].length : 0; - this.warn("TAR_BAD_ARCHIVE", `Truncated input (needed ${entry.blockRemain} more bytes, only ${have} available)`, { entry }); - if (this[BUFFER]) - entry.write(this[BUFFER]); - entry.end(); - } - this[EMIT](DONE); - } - } - [CONSUMECHUNK](chunk) { - if (this[CONSUMING]) - this[BUFFERCONCAT](chunk); - else if (!chunk && !this[BUFFER]) - this[MAYBEEND](); - else { - this[CONSUMING] = true; - if (this[BUFFER]) { - this[BUFFERCONCAT](chunk); - const c = this[BUFFER]; - this[BUFFER] = null; - this[CONSUMECHUNKSUB](c); - } else - this[CONSUMECHUNKSUB](chunk); - while (this[BUFFER] && this[BUFFER].length >= 512 && !this[ABORTED] && !this[SAW_EOF]) { - const c = this[BUFFER]; - this[BUFFER] = null; - this[CONSUMECHUNKSUB](c); - } - this[CONSUMING] = false; - } - if (!this[BUFFER] || this[ENDED]) - this[MAYBEEND](); - } - [CONSUMECHUNKSUB](chunk) { - let position = 0; - const length = chunk.length; - while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { - switch (this[STATE]) { - case "begin": - case "header": - this[CONSUMEHEADER](chunk, position); - position += 512; - break; - case "ignore": - case "body": - position += this[CONSUMEBODY](chunk, position); - break; - case "meta": - position += this[CONSUMEMETA](chunk, position); - break; - default: - throw new Error("invalid state: " + this[STATE]); - } - } - if (position < length) { - if (this[BUFFER]) - this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]); - else - this[BUFFER] = chunk.slice(position); - } - } - end(chunk) { - if (!this[ABORTED]) { - if (this[UNZIP]) - this[UNZIP].end(chunk); - else { - this[ENDED] = true; - this.write(chunk); - } - } - } - }); - } -}); - -// node_modules/tar/lib/list.js -var require_list = __commonJS({ - "node_modules/tar/lib/list.js"(exports2, module2) { - "use strict"; - var hlo = require_high_level_opt(); - var Parser = require_parse2(); - var fs27 = require("fs"); - var fsm = require_fs_minipass(); - var path36 = require("path"); - var stripSlash = require_strip_trailing_slashes(); - module2.exports = (opt_, files, cb) => { - if (typeof opt_ === "function") - cb = opt_, files = null, opt_ = {}; - else if (Array.isArray(opt_)) - files = opt_, opt_ = {}; - if (typeof files === "function") - cb = files, files = null; - if (!files) - files = []; - else - files = Array.from(files); - const opt = hlo(opt_); - if (opt.sync && typeof cb === "function") - throw new TypeError("callback not supported for sync tar functions"); - if (!opt.file && typeof cb === "function") - throw new TypeError("callback only supported with file option"); - if (files.length) - filesFilter(opt, files); - if (!opt.noResume) - onentryFunction(opt); - return opt.file && opt.sync ? listFileSync(opt) : opt.file ? listFile(opt, cb) : list2(opt); - }; - var onentryFunction = (opt) => { - const onentry = opt.onentry; - opt.onentry = onentry ? (e) => { - onentry(e); - e.resume(); - } : (e) => e.resume(); - }; - var filesFilter = (opt, files) => { - const map = new Map(files.map((f) => [stripSlash(f), true])); - const filter = opt.filter; - const mapHas = (file, r) => { - const root = r || path36.parse(file).root || "."; - const ret = file === root ? false : map.has(file) ? map.get(file) : mapHas(path36.dirname(file), root); - map.set(file, ret); - return ret; - }; - opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) : (file) => mapHas(stripSlash(file)); - }; - var listFileSync = (opt) => { - const p = list2(opt); - const file = opt.file; - let threw = true; - let fd; - try { - const stat = fs27.statSync(file); - const readSize = opt.maxReadSize || 16 * 1024 * 1024; - if (stat.size < readSize) - p.end(fs27.readFileSync(file)); - else { - let pos = 0; - const buf = Buffer.allocUnsafe(readSize); - fd = fs27.openSync(file, "r"); - while (pos < stat.size) { - const bytesRead = fs27.readSync(fd, buf, 0, readSize, pos); - pos += bytesRead; - p.write(buf.slice(0, bytesRead)); - } - p.end(); - } - threw = false; - } finally { - if (threw && fd) { - try { - fs27.closeSync(fd); - } catch (er) { - } - } - } - }; - var listFile = (opt, cb) => { - const parse5 = new Parser(opt); - const readSize = opt.maxReadSize || 16 * 1024 * 1024; - const file = opt.file; - const p = new Promise((resolve3, reject) => { - parse5.on("error", reject); - parse5.on("end", resolve3); - fs27.stat(file, (er, stat) => { - if (er) - reject(er); - else { - const stream = new fsm.ReadStream(file, { - readSize, - size: stat.size - }); - stream.on("error", reject); - stream.pipe(parse5); - } - }); - }); - return cb ? p.then(cb, cb) : p; - }; - var list2 = (opt) => new Parser(opt); - } -}); - -// node_modules/tar/lib/create.js -var require_create = __commonJS({ - "node_modules/tar/lib/create.js"(exports2, module2) { - "use strict"; - var hlo = require_high_level_opt(); - var Pack = require_pack(); - var fsm = require_fs_minipass(); - var t = require_list(); - var path36 = require("path"); - module2.exports = (opt_, files, cb) => { - if (typeof files === "function") - cb = files; - if (Array.isArray(opt_)) - files = opt_, opt_ = {}; - if (!files || !Array.isArray(files) || !files.length) - throw new TypeError("no files or directories specified"); - files = Array.from(files); - const opt = hlo(opt_); - if (opt.sync && typeof cb === "function") - throw new TypeError("callback not supported for sync tar functions"); - if (!opt.file && typeof cb === "function") - throw new TypeError("callback only supported with file option"); - return opt.file && opt.sync ? createFileSync(opt, files) : opt.file ? createFile(opt, files, cb) : opt.sync ? createSync(opt, files) : create(opt, files); - }; - var createFileSync = (opt, files) => { - const p = new Pack.Sync(opt); - const stream = new fsm.WriteStreamSync(opt.file, { - mode: opt.mode || 438 - }); - p.pipe(stream); - addFilesSync(p, files); - }; - var createFile = (opt, files, cb) => { - const p = new Pack(opt); - const stream = new fsm.WriteStream(opt.file, { - mode: opt.mode || 438 - }); - p.pipe(stream); - const promise = new Promise((res, rej) => { - stream.on("error", rej); - stream.on("close", res); - p.on("error", rej); - }); - addFilesAsync(p, files); - return cb ? promise.then(cb, cb) : promise; - }; - var addFilesSync = (p, files) => { - files.forEach((file) => { - if (file.charAt(0) === "@") { - t({ - file: path36.resolve(p.cwd, file.substr(1)), - sync: true, - noResume: true, - onentry: (entry) => p.add(entry) - }); - } else - p.add(file); - }); - p.end(); - }; - var addFilesAsync = (p, files) => { - while (files.length) { - const file = files.shift(); - if (file.charAt(0) === "@") { - return t({ - file: path36.resolve(p.cwd, file.substr(1)), - noResume: true, - onentry: (entry) => p.add(entry) - }).then((_) => addFilesAsync(p, files)); - } else - p.add(file); - } - p.end(); - }; - var createSync = (opt, files) => { - const p = new Pack.Sync(opt); - addFilesSync(p, files); - return p; - }; - var create = (opt, files) => { - const p = new Pack(opt); - addFilesAsync(p, files); - return p; - }; - } -}); - -// node_modules/tar/lib/replace.js -var require_replace = __commonJS({ - "node_modules/tar/lib/replace.js"(exports2, module2) { - "use strict"; - var hlo = require_high_level_opt(); - var Pack = require_pack(); - var fs27 = require("fs"); - var fsm = require_fs_minipass(); - var t = require_list(); - var path36 = require("path"); - var Header = require_header(); - module2.exports = (opt_, files, cb) => { - const opt = hlo(opt_); - if (!opt.file) - throw new TypeError("file is required"); - if (opt.gzip) - throw new TypeError("cannot append to compressed archives"); - if (!files || !Array.isArray(files) || !files.length) - throw new TypeError("no files or directories specified"); - files = Array.from(files); - return opt.sync ? replaceSync(opt, files) : replace(opt, files, cb); - }; - var replaceSync = (opt, files) => { - const p = new Pack.Sync(opt); - let threw = true; - let fd; - let position; - try { - try { - fd = fs27.openSync(opt.file, "r+"); - } catch (er) { - if (er.code === "ENOENT") - fd = fs27.openSync(opt.file, "w+"); - else - throw er; - } - const st = fs27.fstatSync(fd); - const headBuf = Buffer.alloc(512); - POSITION: - for (position = 0; position < st.size; position += 512) { - for (let bufPos = 0, bytes2 = 0; bufPos < 512; bufPos += bytes2) { - bytes2 = fs27.readSync(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos); - if (position === 0 && headBuf[0] === 31 && headBuf[1] === 139) - throw new Error("cannot append to compressed archives"); - if (!bytes2) - break POSITION; - } - const h = new Header(headBuf); - if (!h.cksumValid) - break; - const entryBlockSize = 512 * Math.ceil(h.size / 512); - if (position + entryBlockSize + 512 > st.size) - break; - position += entryBlockSize; - if (opt.mtimeCache) - opt.mtimeCache.set(h.path, h.mtime); - } - threw = false; - streamSync(opt, p, position, fd, files); - } finally { - if (threw) { - try { - fs27.closeSync(fd); - } catch (er) { - } - } - } - }; - var streamSync = (opt, p, position, fd, files) => { - const stream = new fsm.WriteStreamSync(opt.file, { - fd, - start: position - }); - p.pipe(stream); - addFilesSync(p, files); - }; - var replace = (opt, files, cb) => { - files = Array.from(files); - const p = new Pack(opt); - const getPos = (fd, size, cb_) => { - const cb2 = (er, pos) => { - if (er) - fs27.close(fd, (_) => cb_(er)); - else - cb_(null, pos); - }; - let position = 0; - if (size === 0) - return cb2(null, 0); - let bufPos = 0; - const headBuf = Buffer.alloc(512); - const onread = (er, bytes2) => { - if (er) - return cb2(er); - bufPos += bytes2; - if (bufPos < 512 && bytes2) { - return fs27.read(fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread); - } - if (position === 0 && headBuf[0] === 31 && headBuf[1] === 139) - return cb2(new Error("cannot append to compressed archives")); - if (bufPos < 512) - return cb2(null, position); - const h = new Header(headBuf); - if (!h.cksumValid) - return cb2(null, position); - const entryBlockSize = 512 * Math.ceil(h.size / 512); - if (position + entryBlockSize + 512 > size) - return cb2(null, position); - position += entryBlockSize + 512; - if (position >= size) - return cb2(null, position); - if (opt.mtimeCache) - opt.mtimeCache.set(h.path, h.mtime); - bufPos = 0; - fs27.read(fd, headBuf, 0, 512, position, onread); - }; - fs27.read(fd, headBuf, 0, 512, position, onread); - }; - const promise = new Promise((resolve3, reject) => { - p.on("error", reject); - let flag = "r+"; - const onopen = (er, fd) => { - if (er && er.code === "ENOENT" && flag === "r+") { - flag = "w+"; - return fs27.open(opt.file, flag, onopen); - } - if (er) - return reject(er); - fs27.fstat(fd, (er2, st) => { - if (er2) - return fs27.close(fd, () => reject(er2)); - getPos(fd, st.size, (er3, position) => { - if (er3) - return reject(er3); - const stream = new fsm.WriteStream(opt.file, { - fd, - start: position - }); - p.pipe(stream); - stream.on("error", reject); - stream.on("close", resolve3); - addFilesAsync(p, files); - }); - }); - }; - fs27.open(opt.file, flag, onopen); - }); - return cb ? promise.then(cb, cb) : promise; - }; - var addFilesSync = (p, files) => { - files.forEach((file) => { - if (file.charAt(0) === "@") { - t({ - file: path36.resolve(p.cwd, file.substr(1)), - sync: true, - noResume: true, - onentry: (entry) => p.add(entry) - }); - } else - p.add(file); - }); - p.end(); - }; - var addFilesAsync = (p, files) => { - while (files.length) { - const file = files.shift(); - if (file.charAt(0) === "@") { - return t({ - file: path36.resolve(p.cwd, file.substr(1)), - noResume: true, - onentry: (entry) => p.add(entry) - }).then((_) => addFilesAsync(p, files)); - } else - p.add(file); - } - p.end(); - }; - } -}); - -// node_modules/tar/lib/update.js -var require_update = __commonJS({ - "node_modules/tar/lib/update.js"(exports2, module2) { - "use strict"; - var hlo = require_high_level_opt(); - var r = require_replace(); - module2.exports = (opt_, files, cb) => { - const opt = hlo(opt_); - if (!opt.file) - throw new TypeError("file is required"); - if (opt.gzip) - throw new TypeError("cannot append to compressed archives"); - if (!files || !Array.isArray(files) || !files.length) - throw new TypeError("no files or directories specified"); - files = Array.from(files); - mtimeFilter(opt); - return r(opt, files, cb); - }; - var mtimeFilter = (opt) => { - const filter = opt.filter; - if (!opt.mtimeCache) - opt.mtimeCache = new Map(); - opt.filter = filter ? (path36, stat) => filter(path36, stat) && !(opt.mtimeCache.get(path36) > stat.mtime) : (path36, stat) => !(opt.mtimeCache.get(path36) > stat.mtime); - }; - } -}); - -// node_modules/tar/node_modules/mkdirp/lib/opts-arg.js -var require_opts_arg = __commonJS({ - "node_modules/tar/node_modules/mkdirp/lib/opts-arg.js"(exports2, module2) { - var { promisify } = require("util"); - var fs27 = require("fs"); - var optsArg = (opts) => { - if (!opts) - opts = { mode: 511, fs: fs27 }; - else if (typeof opts === "object") - opts = __spreadValues({ mode: 511, fs: fs27 }, opts); - else if (typeof opts === "number") - opts = { mode: opts, fs: fs27 }; - else if (typeof opts === "string") - opts = { mode: parseInt(opts, 8), fs: fs27 }; - else - throw new TypeError("invalid options argument"); - opts.mkdir = opts.mkdir || opts.fs.mkdir || fs27.mkdir; - opts.mkdirAsync = promisify(opts.mkdir); - opts.stat = opts.stat || opts.fs.stat || fs27.stat; - opts.statAsync = promisify(opts.stat); - opts.statSync = opts.statSync || opts.fs.statSync || fs27.statSync; - opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs27.mkdirSync; - return opts; - }; - module2.exports = optsArg; - } -}); - -// node_modules/tar/node_modules/mkdirp/lib/path-arg.js -var require_path_arg = __commonJS({ - "node_modules/tar/node_modules/mkdirp/lib/path-arg.js"(exports2, module2) { - var platform3 = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform; - var { resolve: resolve3, parse: parse5 } = require("path"); - var pathArg = (path36) => { - if (/\0/.test(path36)) { - throw Object.assign(new TypeError("path must be a string without null bytes"), { - path: path36, - code: "ERR_INVALID_ARG_VALUE" - }); - } - path36 = resolve3(path36); - if (platform3 === "win32") { - const badWinChars = /[*|"<>?:]/; - const { root } = parse5(path36); - if (badWinChars.test(path36.substr(root.length))) { - throw Object.assign(new Error("Illegal characters in path."), { - path: path36, - code: "EINVAL" - }); - } - } - return path36; - }; - module2.exports = pathArg; - } -}); - -// node_modules/tar/node_modules/mkdirp/lib/find-made.js -var require_find_made = __commonJS({ - "node_modules/tar/node_modules/mkdirp/lib/find-made.js"(exports2, module2) { - var { dirname: dirname3 } = require("path"); - var findMade = (opts, parent, path36 = void 0) => { - if (path36 === parent) - return Promise.resolve(); - return opts.statAsync(parent).then((st) => st.isDirectory() ? path36 : void 0, (er) => er.code === "ENOENT" ? findMade(opts, dirname3(parent), parent) : void 0); - }; - var findMadeSync = (opts, parent, path36 = void 0) => { - if (path36 === parent) - return void 0; - try { - return opts.statSync(parent).isDirectory() ? path36 : void 0; - } catch (er) { - return er.code === "ENOENT" ? findMadeSync(opts, dirname3(parent), parent) : void 0; - } - }; - module2.exports = { findMade, findMadeSync }; - } -}); - -// node_modules/tar/node_modules/mkdirp/lib/mkdirp-manual.js -var require_mkdirp_manual = __commonJS({ - "node_modules/tar/node_modules/mkdirp/lib/mkdirp-manual.js"(exports2, module2) { - var { dirname: dirname3 } = require("path"); - var mkdirpManual = (path36, opts, made) => { - opts.recursive = false; - const parent = dirname3(path36); - if (parent === path36) { - return opts.mkdirAsync(path36, opts).catch((er) => { - if (er.code !== "EISDIR") - throw er; - }); - } - return opts.mkdirAsync(path36, opts).then(() => made || path36, (er) => { - if (er.code === "ENOENT") - return mkdirpManual(parent, opts).then((made2) => mkdirpManual(path36, opts, made2)); - if (er.code !== "EEXIST" && er.code !== "EROFS") - throw er; - return opts.statAsync(path36).then((st) => { - if (st.isDirectory()) - return made; - else - throw er; - }, () => { - throw er; - }); - }); - }; - var mkdirpManualSync = (path36, opts, made) => { - const parent = dirname3(path36); - opts.recursive = false; - if (parent === path36) { - try { - return opts.mkdirSync(path36, opts); - } catch (er) { - if (er.code !== "EISDIR") - throw er; - else - return; - } - } - try { - opts.mkdirSync(path36, opts); - return made || path36; - } catch (er) { - if (er.code === "ENOENT") - return mkdirpManualSync(path36, opts, mkdirpManualSync(parent, opts, made)); - if (er.code !== "EEXIST" && er.code !== "EROFS") - throw er; - try { - if (!opts.statSync(path36).isDirectory()) - throw er; - } catch (_) { - throw er; - } - } - }; - module2.exports = { mkdirpManual, mkdirpManualSync }; - } -}); - -// node_modules/tar/node_modules/mkdirp/lib/mkdirp-native.js -var require_mkdirp_native = __commonJS({ - "node_modules/tar/node_modules/mkdirp/lib/mkdirp-native.js"(exports2, module2) { - var { dirname: dirname3 } = require("path"); - var { findMade, findMadeSync } = require_find_made(); - var { mkdirpManual, mkdirpManualSync } = require_mkdirp_manual(); - var mkdirpNative = (path36, opts) => { - opts.recursive = true; - const parent = dirname3(path36); - if (parent === path36) - return opts.mkdirAsync(path36, opts); - return findMade(opts, path36).then((made) => opts.mkdirAsync(path36, opts).then(() => made).catch((er) => { - if (er.code === "ENOENT") - return mkdirpManual(path36, opts); - else - throw er; - })); - }; - var mkdirpNativeSync = (path36, opts) => { - opts.recursive = true; - const parent = dirname3(path36); - if (parent === path36) - return opts.mkdirSync(path36, opts); - const made = findMadeSync(opts, path36); - try { - opts.mkdirSync(path36, opts); - return made; - } catch (er) { - if (er.code === "ENOENT") - return mkdirpManualSync(path36, opts); - else - throw er; - } - }; - module2.exports = { mkdirpNative, mkdirpNativeSync }; - } -}); - -// node_modules/tar/node_modules/mkdirp/lib/use-native.js -var require_use_native = __commonJS({ - "node_modules/tar/node_modules/mkdirp/lib/use-native.js"(exports2, module2) { - var fs27 = require("fs"); - var version2 = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version; - var versArr = version2.replace(/^v/, "").split("."); - var hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12; - var useNative = !hasNative ? () => false : (opts) => opts.mkdir === fs27.mkdir; - var useNativeSync = !hasNative ? () => false : (opts) => opts.mkdirSync === fs27.mkdirSync; - module2.exports = { useNative, useNativeSync }; - } -}); - -// node_modules/tar/node_modules/mkdirp/index.js -var require_mkdirp = __commonJS({ - "node_modules/tar/node_modules/mkdirp/index.js"(exports2, module2) { - var optsArg = require_opts_arg(); - var pathArg = require_path_arg(); - var { mkdirpNative, mkdirpNativeSync } = require_mkdirp_native(); - var { mkdirpManual, mkdirpManualSync } = require_mkdirp_manual(); - var { useNative, useNativeSync } = require_use_native(); - var mkdirp = (path36, opts) => { - path36 = pathArg(path36); - opts = optsArg(opts); - return useNative(opts) ? mkdirpNative(path36, opts) : mkdirpManual(path36, opts); - }; - var mkdirpSync = (path36, opts) => { - path36 = pathArg(path36); - opts = optsArg(opts); - return useNativeSync(opts) ? mkdirpNativeSync(path36, opts) : mkdirpManualSync(path36, opts); - }; - mkdirp.sync = mkdirpSync; - mkdirp.native = (path36, opts) => mkdirpNative(pathArg(path36), optsArg(opts)); - mkdirp.manual = (path36, opts) => mkdirpManual(pathArg(path36), optsArg(opts)); - mkdirp.nativeSync = (path36, opts) => mkdirpNativeSync(pathArg(path36), optsArg(opts)); - mkdirp.manualSync = (path36, opts) => mkdirpManualSync(pathArg(path36), optsArg(opts)); - module2.exports = mkdirp; - } -}); - -// node_modules/chownr/chownr.js -var require_chownr = __commonJS({ - "node_modules/chownr/chownr.js"(exports2, module2) { - "use strict"; - var fs27 = require("fs"); - var path36 = require("path"); - var LCHOWN = fs27.lchown ? "lchown" : "chown"; - var LCHOWNSYNC = fs27.lchownSync ? "lchownSync" : "chownSync"; - var needEISDIRHandled = fs27.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/); - var lchownSync = (path37, uid, gid) => { - try { - return fs27[LCHOWNSYNC](path37, uid, gid); - } catch (er) { - if (er.code !== "ENOENT") - throw er; - } - }; - var chownSync = (path37, uid, gid) => { - try { - return fs27.chownSync(path37, uid, gid); - } catch (er) { - if (er.code !== "ENOENT") - throw er; - } - }; - var handleEISDIR = needEISDIRHandled ? (path37, uid, gid, cb) => (er) => { - if (!er || er.code !== "EISDIR") - cb(er); - else - fs27.chown(path37, uid, gid, cb); - } : (_, __, ___, cb) => cb; - var handleEISDirSync = needEISDIRHandled ? (path37, uid, gid) => { - try { - return lchownSync(path37, uid, gid); - } catch (er) { - if (er.code !== "EISDIR") - throw er; - chownSync(path37, uid, gid); - } - } : (path37, uid, gid) => lchownSync(path37, uid, gid); - var nodeVersion = process.version; - var readdir = (path37, options, cb) => fs27.readdir(path37, options, cb); - var readdirSync = (path37, options) => fs27.readdirSync(path37, options); - if (/^v4\./.test(nodeVersion)) - readdir = (path37, options, cb) => fs27.readdir(path37, cb); - var chown = (cpath, uid, gid, cb) => { - fs27[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, (er) => { - cb(er && er.code !== "ENOENT" ? er : null); - })); - }; - var chownrKid = (p, child, uid, gid, cb) => { - if (typeof child === "string") - return fs27.lstat(path36.resolve(p, child), (er, stats) => { - if (er) - return cb(er.code !== "ENOENT" ? er : null); - stats.name = child; - chownrKid(p, stats, uid, gid, cb); - }); - if (child.isDirectory()) { - chownr(path36.resolve(p, child.name), uid, gid, (er) => { - if (er) - return cb(er); - const cpath = path36.resolve(p, child.name); - chown(cpath, uid, gid, cb); - }); - } else { - const cpath = path36.resolve(p, child.name); - chown(cpath, uid, gid, cb); - } - }; - var chownr = (p, uid, gid, cb) => { - readdir(p, { withFileTypes: true }, (er, children) => { - if (er) { - if (er.code === "ENOENT") - return cb(); - else if (er.code !== "ENOTDIR" && er.code !== "ENOTSUP") - return cb(er); - } - if (er || !children.length) - return chown(p, uid, gid, cb); - let len = children.length; - let errState = null; - const then = (er2) => { - if (errState) - return; - if (er2) - return cb(errState = er2); - if (--len === 0) - return chown(p, uid, gid, cb); - }; - children.forEach((child) => chownrKid(p, child, uid, gid, then)); - }); - }; - var chownrKidSync = (p, child, uid, gid) => { - if (typeof child === "string") { - try { - const stats = fs27.lstatSync(path36.resolve(p, child)); - stats.name = child; - child = stats; - } catch (er) { - if (er.code === "ENOENT") - return; - else - throw er; - } - } - if (child.isDirectory()) - chownrSync(path36.resolve(p, child.name), uid, gid); - handleEISDirSync(path36.resolve(p, child.name), uid, gid); - }; - var chownrSync = (p, uid, gid) => { - let children; - try { - children = readdirSync(p, { withFileTypes: true }); - } catch (er) { - if (er.code === "ENOENT") - return; - else if (er.code === "ENOTDIR" || er.code === "ENOTSUP") - return handleEISDirSync(p, uid, gid); - else - throw er; - } - if (children && children.length) - children.forEach((child) => chownrKidSync(p, child, uid, gid)); - return handleEISDirSync(p, uid, gid); - }; - module2.exports = chownr; - chownr.sync = chownrSync; - } -}); - -// node_modules/tar/lib/mkdir.js -var require_mkdir = __commonJS({ - "node_modules/tar/lib/mkdir.js"(exports2, module2) { - "use strict"; - var mkdirp = require_mkdirp(); - var fs27 = require("fs"); - var path36 = require("path"); - var chownr = require_chownr(); - var normPath = require_normalize_windows_path(); - var SymlinkError = class extends Error { - constructor(symlink, path37) { - super("Cannot extract through symbolic link"); - this.path = path37; - this.symlink = symlink; - } - get name() { - return "SylinkError"; - } - }; - var CwdError = class extends Error { - constructor(path37, code) { - super(code + ": Cannot cd into '" + path37 + "'"); - this.path = path37; - this.code = code; - } - get name() { - return "CwdError"; - } - }; - var cGet = (cache, key) => cache.get(normPath(key)); - var cSet = (cache, key, val) => cache.set(normPath(key), val); - var checkCwd = (dir, cb) => { - fs27.stat(dir, (er, st) => { - if (er || !st.isDirectory()) - er = new CwdError(dir, er && er.code || "ENOTDIR"); - cb(er); - }); - }; - module2.exports = (dir, opt, cb) => { - dir = normPath(dir); - const umask = opt.umask; - const mode = opt.mode | 448; - const needChmod = (mode & umask) !== 0; - const uid = opt.uid; - const gid = opt.gid; - const doChown = typeof uid === "number" && typeof gid === "number" && (uid !== opt.processUid || gid !== opt.processGid); - const preserve = opt.preserve; - const unlink = opt.unlink; - const cache = opt.cache; - const cwd = normPath(opt.cwd); - const done = (er, created) => { - if (er) - cb(er); - else { - cSet(cache, dir, true); - if (created && doChown) - chownr(created, uid, gid, (er2) => done(er2)); - else if (needChmod) - fs27.chmod(dir, mode, cb); - else - cb(); - } - }; - if (cache && cGet(cache, dir) === true) - return done(); - if (dir === cwd) - return checkCwd(dir, done); - if (preserve) - return mkdirp(dir, { mode }).then((made) => done(null, made), done); - const sub = normPath(path36.relative(cwd, dir)); - const parts = sub.split("/"); - mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done); - }; - var mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { - if (!parts.length) - return cb(null, created); - const p = parts.shift(); - const part = normPath(path36.resolve(base + "/" + p)); - if (cGet(cache, part)) - return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb); - fs27.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)); - }; - var onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => (er) => { - if (er) { - fs27.lstat(part, (statEr, st) => { - if (statEr) { - statEr.path = statEr.path && normPath(statEr.path); - cb(statEr); - } else if (st.isDirectory()) - mkdir_(part, parts, mode, cache, unlink, cwd, created, cb); - else if (unlink) { - fs27.unlink(part, (er2) => { - if (er2) - return cb(er2); - fs27.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)); - }); - } else if (st.isSymbolicLink()) - return cb(new SymlinkError(part, part + "/" + parts.join("/"))); - else - cb(er); - }); - } else { - created = created || part; - mkdir_(part, parts, mode, cache, unlink, cwd, created, cb); - } - }; - var checkCwdSync = (dir) => { - let ok = false; - let code = "ENOTDIR"; - try { - ok = fs27.statSync(dir).isDirectory(); - } catch (er) { - code = er.code; - } finally { - if (!ok) - throw new CwdError(dir, code); - } - }; - module2.exports.sync = (dir, opt) => { - dir = normPath(dir); - const umask = opt.umask; - const mode = opt.mode | 448; - const needChmod = (mode & umask) !== 0; - const uid = opt.uid; - const gid = opt.gid; - const doChown = typeof uid === "number" && typeof gid === "number" && (uid !== opt.processUid || gid !== opt.processGid); - const preserve = opt.preserve; - const unlink = opt.unlink; - const cache = opt.cache; - const cwd = normPath(opt.cwd); - const done = (created2) => { - cSet(cache, dir, true); - if (created2 && doChown) - chownr.sync(created2, uid, gid); - if (needChmod) - fs27.chmodSync(dir, mode); - }; - if (cache && cGet(cache, dir) === true) - return done(); - if (dir === cwd) { - checkCwdSync(cwd); - return done(); - } - if (preserve) - return done(mkdirp.sync(dir, mode)); - const sub = normPath(path36.relative(cwd, dir)); - const parts = sub.split("/"); - let created = null; - for (let p = parts.shift(), part = cwd; p && (part += "/" + p); p = parts.shift()) { - part = normPath(path36.resolve(part)); - if (cGet(cache, part)) - continue; - try { - fs27.mkdirSync(part, mode); - created = created || part; - cSet(cache, part, true); - } catch (er) { - const st = fs27.lstatSync(part); - if (st.isDirectory()) { - cSet(cache, part, true); - continue; - } else if (unlink) { - fs27.unlinkSync(part); - fs27.mkdirSync(part, mode); - created = created || part; - cSet(cache, part, true); - continue; - } else if (st.isSymbolicLink()) - return new SymlinkError(part, part + "/" + parts.join("/")); - } - } - return done(created); - }; - } -}); - -// node_modules/tar/lib/normalize-unicode.js -var require_normalize_unicode = __commonJS({ - "node_modules/tar/lib/normalize-unicode.js"(exports2, module2) { - var normalizeCache = Object.create(null); - var { hasOwnProperty: hasOwnProperty3 } = Object.prototype; - module2.exports = (s) => { - if (!hasOwnProperty3.call(normalizeCache, s)) - normalizeCache[s] = s.normalize("NFKD"); - return normalizeCache[s]; - }; - } -}); - -// node_modules/tar/lib/path-reservations.js -var require_path_reservations = __commonJS({ - "node_modules/tar/lib/path-reservations.js"(exports2, module2) { - var assert = require("assert"); - var normalize = require_normalize_unicode(); - var stripSlashes = require_strip_trailing_slashes(); - var { join: join2 } = require("path"); - var platform3 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; - var isWindows4 = platform3 === "win32"; - module2.exports = () => { - const queues = new Map(); - const reservations = new Map(); - const getDirs = (path36) => { - const dirs = path36.split("/").slice(0, -1).reduce((set, path37) => { - if (set.length) - path37 = join2(set[set.length - 1], path37); - set.push(path37 || "/"); - return set; - }, []); - return dirs; - }; - const running = new Set(); - const getQueues = (fn) => { - const res = reservations.get(fn); - if (!res) - throw new Error("function does not have any path reservations"); - return { - paths: res.paths.map((path36) => queues.get(path36)), - dirs: [...res.dirs].map((path36) => queues.get(path36)) - }; - }; - const check = (fn) => { - const { paths, dirs } = getQueues(fn); - return paths.every((q) => q[0] === fn) && dirs.every((q) => q[0] instanceof Set && q[0].has(fn)); - }; - const run = (fn) => { - if (running.has(fn) || !check(fn)) - return false; - running.add(fn); - fn(() => clear(fn)); - return true; - }; - const clear = (fn) => { - if (!running.has(fn)) - return false; - const { paths, dirs } = reservations.get(fn); - const next = new Set(); - paths.forEach((path36) => { - const q = queues.get(path36); - assert.equal(q[0], fn); - if (q.length === 1) - queues.delete(path36); - else { - q.shift(); - if (typeof q[0] === "function") - next.add(q[0]); - else - q[0].forEach((fn2) => next.add(fn2)); - } - }); - dirs.forEach((dir) => { - const q = queues.get(dir); - assert(q[0] instanceof Set); - if (q[0].size === 1 && q.length === 1) - queues.delete(dir); - else if (q[0].size === 1) { - q.shift(); - next.add(q[0]); - } else - q[0].delete(fn); - }); - running.delete(fn); - next.forEach((fn2) => run(fn2)); - return true; - }; - const reserve = (paths, fn) => { - paths = isWindows4 ? ["win32 parallelization disabled"] : paths.map((p) => { - return normalize(stripSlashes(join2(p))).toLowerCase(); - }); - const dirs = new Set(paths.map((path36) => getDirs(path36)).reduce((a, b) => a.concat(b))); - reservations.set(fn, { dirs, paths }); - paths.forEach((path36) => { - const q = queues.get(path36); - if (!q) - queues.set(path36, [fn]); - else - q.push(fn); - }); - dirs.forEach((dir) => { - const q = queues.get(dir); - if (!q) - queues.set(dir, [new Set([fn])]); - else if (q[q.length - 1] instanceof Set) - q[q.length - 1].add(fn); - else - q.push(new Set([fn])); - }); - return run(fn); - }; - return { check, reserve }; - }; - } -}); - -// node_modules/tar/lib/get-write-flag.js -var require_get_write_flag = __commonJS({ - "node_modules/tar/lib/get-write-flag.js"(exports2, module2) { - var platform3 = process.env.__FAKE_PLATFORM__ || process.platform; - var isWindows4 = platform3 === "win32"; - var fs27 = global.__FAKE_TESTING_FS__ || require("fs"); - var { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs27.constants; - var fMapEnabled = isWindows4 && !!UV_FS_O_FILEMAP; - var fMapLimit = 512 * 1024; - var fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY; - module2.exports = !fMapEnabled ? () => "w" : (size) => size < fMapLimit ? fMapFlag : "w"; - } -}); - -// node_modules/tar/lib/unpack.js -var require_unpack = __commonJS({ - "node_modules/tar/lib/unpack.js"(exports2, module2) { - "use strict"; - var assert = require("assert"); - var Parser = require_parse2(); - var fs27 = require("fs"); - var fsm = require_fs_minipass(); - var path36 = require("path"); - var mkdir = require_mkdir(); - var wc = require_winchars(); - var pathReservations = require_path_reservations(); - var stripAbsolutePath = require_strip_absolute_path(); - var normPath = require_normalize_windows_path(); - var stripSlash = require_strip_trailing_slashes(); - var normalize = require_normalize_unicode(); - var ONENTRY = Symbol("onEntry"); - var CHECKFS = Symbol("checkFs"); - var CHECKFS2 = Symbol("checkFs2"); - var PRUNECACHE = Symbol("pruneCache"); - var ISREUSABLE = Symbol("isReusable"); - var MAKEFS = Symbol("makeFs"); - var FILE = Symbol("file"); - var DIRECTORY = Symbol("directory"); - var LINK = Symbol("link"); - var SYMLINK = Symbol("symlink"); - var HARDLINK = Symbol("hardlink"); - var UNSUPPORTED = Symbol("unsupported"); - var CHECKPATH = Symbol("checkPath"); - var MKDIR = Symbol("mkdir"); - var ONERROR = Symbol("onError"); - var PENDING = Symbol("pending"); - var PEND = Symbol("pend"); - var UNPEND = Symbol("unpend"); - var ENDED = Symbol("ended"); - var MAYBECLOSE = Symbol("maybeClose"); - var SKIP = Symbol("skip"); - var DOCHOWN = Symbol("doChown"); - var UID = Symbol("uid"); - var GID = Symbol("gid"); - var CHECKED_CWD = Symbol("checkedCwd"); - var crypto2 = require("crypto"); - var getFlag = require_get_write_flag(); - var platform3 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; - var isWindows4 = platform3 === "win32"; - var unlinkFile = (path37, cb) => { - if (!isWindows4) - return fs27.unlink(path37, cb); - const name2 = path37 + ".DELETE." + crypto2.randomBytes(16).toString("hex"); - fs27.rename(path37, name2, (er) => { - if (er) - return cb(er); - fs27.unlink(name2, cb); - }); - }; - var unlinkFileSync = (path37) => { - if (!isWindows4) - return fs27.unlinkSync(path37); - const name2 = path37 + ".DELETE." + crypto2.randomBytes(16).toString("hex"); - fs27.renameSync(path37, name2); - fs27.unlinkSync(name2); - }; - var uint32 = (a, b, c) => a === a >>> 0 ? a : b === b >>> 0 ? b : c; - var cacheKeyNormalize = (path37) => normalize(stripSlash(normPath(path37))).toLowerCase(); - var pruneCache = (cache, abs) => { - abs = cacheKeyNormalize(abs); - for (const path37 of cache.keys()) { - const pnorm = cacheKeyNormalize(path37); - if (pnorm === abs || pnorm.indexOf(abs + "/") === 0) - cache.delete(path37); - } - }; - var dropCache = (cache) => { - for (const key of cache.keys()) - cache.delete(key); - }; - var Unpack = class extends Parser { - constructor(opt) { - if (!opt) - opt = {}; - opt.ondone = (_) => { - this[ENDED] = true; - this[MAYBECLOSE](); - }; - super(opt); - this[CHECKED_CWD] = false; - this.reservations = pathReservations(); - this.transform = typeof opt.transform === "function" ? opt.transform : null; - this.writable = true; - this.readable = false; - this[PENDING] = 0; - this[ENDED] = false; - this.dirCache = opt.dirCache || new Map(); - if (typeof opt.uid === "number" || typeof opt.gid === "number") { - if (typeof opt.uid !== "number" || typeof opt.gid !== "number") - throw new TypeError("cannot set owner without number uid and gid"); - if (opt.preserveOwner) { - throw new TypeError("cannot preserve owner in archive and also set owner explicitly"); - } - this.uid = opt.uid; - this.gid = opt.gid; - this.setOwner = true; - } else { - this.uid = null; - this.gid = null; - this.setOwner = false; - } - if (opt.preserveOwner === void 0 && typeof opt.uid !== "number") - this.preserveOwner = process.getuid && process.getuid() === 0; - else - this.preserveOwner = !!opt.preserveOwner; - this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? process.getuid() : null; - this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? process.getgid() : null; - this.forceChown = opt.forceChown === true; - this.win32 = !!opt.win32 || isWindows4; - this.newer = !!opt.newer; - this.keep = !!opt.keep; - this.noMtime = !!opt.noMtime; - this.preservePaths = !!opt.preservePaths; - this.unlink = !!opt.unlink; - this.cwd = normPath(path36.resolve(opt.cwd || process.cwd())); - this.strip = +opt.strip || 0; - this.processUmask = opt.noChmod ? 0 : process.umask(); - this.umask = typeof opt.umask === "number" ? opt.umask : this.processUmask; - this.dmode = opt.dmode || 511 & ~this.umask; - this.fmode = opt.fmode || 438 & ~this.umask; - this.on("entry", (entry) => this[ONENTRY](entry)); - } - warn(code, msg, data = {}) { - if (code === "TAR_BAD_ARCHIVE" || code === "TAR_ABORT") - data.recoverable = false; - return super.warn(code, msg, data); - } - [MAYBECLOSE]() { - if (this[ENDED] && this[PENDING] === 0) { - this.emit("prefinish"); - this.emit("finish"); - this.emit("end"); - this.emit("close"); - } - } - [CHECKPATH](entry) { - if (this.strip) { - const parts = normPath(entry.path).split("/"); - if (parts.length < this.strip) - return false; - entry.path = parts.slice(this.strip).join("/"); - if (entry.type === "Link") { - const linkparts = normPath(entry.linkpath).split("/"); - if (linkparts.length >= this.strip) - entry.linkpath = linkparts.slice(this.strip).join("/"); - else - return false; - } - } - if (!this.preservePaths) { - const p = normPath(entry.path); - const parts = p.split("/"); - if (parts.includes("..") || isWindows4 && /^[a-z]:\.\.$/i.test(parts[0])) { - this.warn("TAR_ENTRY_ERROR", `path contains '..'`, { - entry, - path: p - }); - return false; - } - const [root, stripped] = stripAbsolutePath(p); - if (root) { - entry.path = stripped; - this.warn("TAR_ENTRY_INFO", `stripping ${root} from absolute path`, { - entry, - path: p - }); - } - } - if (path36.isAbsolute(entry.path)) - entry.absolute = normPath(path36.resolve(entry.path)); - else - entry.absolute = normPath(path36.resolve(this.cwd, entry.path)); - if (!this.preservePaths && entry.absolute.indexOf(this.cwd + "/") !== 0 && entry.absolute !== this.cwd) { - this.warn("TAR_ENTRY_ERROR", "path escaped extraction target", { - entry, - path: normPath(entry.path), - resolvedPath: entry.absolute, - cwd: this.cwd - }); - return false; - } - if (entry.absolute === this.cwd && entry.type !== "Directory" && entry.type !== "GNUDumpDir") - return false; - if (this.win32) { - const { root: aRoot } = path36.win32.parse(entry.absolute); - entry.absolute = aRoot + wc.encode(entry.absolute.substr(aRoot.length)); - const { root: pRoot } = path36.win32.parse(entry.path); - entry.path = pRoot + wc.encode(entry.path.substr(pRoot.length)); - } - return true; - } - [ONENTRY](entry) { - if (!this[CHECKPATH](entry)) - return entry.resume(); - assert.equal(typeof entry.absolute, "string"); - switch (entry.type) { - case "Directory": - case "GNUDumpDir": - if (entry.mode) - entry.mode = entry.mode | 448; - case "File": - case "OldFile": - case "ContiguousFile": - case "Link": - case "SymbolicLink": - return this[CHECKFS](entry); - case "CharacterDevice": - case "BlockDevice": - case "FIFO": - default: - return this[UNSUPPORTED](entry); - } - } - [ONERROR](er, entry) { - if (er.name === "CwdError") - this.emit("error", er); - else { - this.warn("TAR_ENTRY_ERROR", er, { entry }); - this[UNPEND](); - entry.resume(); - } - } - [MKDIR](dir, mode, cb) { - mkdir(normPath(dir), { - uid: this.uid, - gid: this.gid, - processUid: this.processUid, - processGid: this.processGid, - umask: this.processUmask, - preserve: this.preservePaths, - unlink: this.unlink, - cache: this.dirCache, - cwd: this.cwd, - mode, - noChmod: this.noChmod - }, cb); - } - [DOCHOWN](entry) { - return this.forceChown || this.preserveOwner && (typeof entry.uid === "number" && entry.uid !== this.processUid || typeof entry.gid === "number" && entry.gid !== this.processGid) || (typeof this.uid === "number" && this.uid !== this.processUid || typeof this.gid === "number" && this.gid !== this.processGid); - } - [UID](entry) { - return uint32(this.uid, entry.uid, this.processUid); - } - [GID](entry) { - return uint32(this.gid, entry.gid, this.processGid); - } - [FILE](entry, fullyDone) { - const mode = entry.mode & 4095 || this.fmode; - const stream = new fsm.WriteStream(entry.absolute, { - flags: getFlag(entry.size), - mode, - autoClose: false - }); - stream.on("error", (er) => { - if (stream.fd) - fs27.close(stream.fd, () => { - }); - stream.write = () => true; - this[ONERROR](er, entry); - fullyDone(); - }); - let actions = 1; - const done = (er) => { - if (er) { - if (stream.fd) - fs27.close(stream.fd, () => { - }); - this[ONERROR](er, entry); - fullyDone(); - return; - } - if (--actions === 0) { - fs27.close(stream.fd, (er2) => { - if (er2) - this[ONERROR](er2, entry); - else - this[UNPEND](); - fullyDone(); - }); - } - }; - stream.on("finish", (_) => { - const abs = entry.absolute; - const fd = stream.fd; - if (entry.mtime && !this.noMtime) { - actions++; - const atime = entry.atime || new Date(); - const mtime = entry.mtime; - fs27.futimes(fd, atime, mtime, (er) => er ? fs27.utimes(abs, atime, mtime, (er2) => done(er2 && er)) : done()); - } - if (this[DOCHOWN](entry)) { - actions++; - const uid = this[UID](entry); - const gid = this[GID](entry); - fs27.fchown(fd, uid, gid, (er) => er ? fs27.chown(abs, uid, gid, (er2) => done(er2 && er)) : done()); - } - done(); - }); - const tx = this.transform ? this.transform(entry) || entry : entry; - if (tx !== entry) { - tx.on("error", (er) => { - this[ONERROR](er, entry); - fullyDone(); - }); - entry.pipe(tx); - } - tx.pipe(stream); - } - [DIRECTORY](entry, fullyDone) { - const mode = entry.mode & 4095 || this.dmode; - this[MKDIR](entry.absolute, mode, (er) => { - if (er) { - this[ONERROR](er, entry); - fullyDone(); - return; - } - let actions = 1; - const done = (_) => { - if (--actions === 0) { - fullyDone(); - this[UNPEND](); - entry.resume(); - } - }; - if (entry.mtime && !this.noMtime) { - actions++; - fs27.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, done); - } - if (this[DOCHOWN](entry)) { - actions++; - fs27.chown(entry.absolute, this[UID](entry), this[GID](entry), done); - } - done(); - }); - } - [UNSUPPORTED](entry) { - entry.unsupported = true; - this.warn("TAR_ENTRY_UNSUPPORTED", `unsupported entry type: ${entry.type}`, { entry }); - entry.resume(); - } - [SYMLINK](entry, done) { - this[LINK](entry, entry.linkpath, "symlink", done); - } - [HARDLINK](entry, done) { - const linkpath = normPath(path36.resolve(this.cwd, entry.linkpath)); - this[LINK](entry, linkpath, "link", done); - } - [PEND]() { - this[PENDING]++; - } - [UNPEND]() { - this[PENDING]--; - this[MAYBECLOSE](); - } - [SKIP](entry) { - this[UNPEND](); - entry.resume(); - } - [ISREUSABLE](entry, st) { - return entry.type === "File" && !this.unlink && st.isFile() && st.nlink <= 1 && !isWindows4; - } - [CHECKFS](entry) { - this[PEND](); - const paths = [entry.path]; - if (entry.linkpath) - paths.push(entry.linkpath); - this.reservations.reserve(paths, (done) => this[CHECKFS2](entry, done)); - } - [PRUNECACHE](entry) { - if (entry.type === "SymbolicLink") - dropCache(this.dirCache); - else if (entry.type !== "Directory") - pruneCache(this.dirCache, entry.absolute); - } - [CHECKFS2](entry, fullyDone) { - this[PRUNECACHE](entry); - const done = (er) => { - this[PRUNECACHE](entry); - fullyDone(er); - }; - const checkCwd = () => { - this[MKDIR](this.cwd, this.dmode, (er) => { - if (er) { - this[ONERROR](er, entry); - done(); - return; - } - this[CHECKED_CWD] = true; - start(); - }); - }; - const start = () => { - if (entry.absolute !== this.cwd) { - const parent = normPath(path36.dirname(entry.absolute)); - if (parent !== this.cwd) { - return this[MKDIR](parent, this.dmode, (er) => { - if (er) { - this[ONERROR](er, entry); - done(); - return; - } - afterMakeParent(); - }); - } - } - afterMakeParent(); - }; - const afterMakeParent = () => { - fs27.lstat(entry.absolute, (lstatEr, st) => { - if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { - this[SKIP](entry); - done(); - return; - } - if (lstatEr || this[ISREUSABLE](entry, st)) - return this[MAKEFS](null, entry, done); - if (st.isDirectory()) { - if (entry.type === "Directory") { - const needChmod = !this.noChmod && entry.mode && (st.mode & 4095) !== entry.mode; - const afterChmod = (er) => this[MAKEFS](er, entry, done); - if (!needChmod) - return afterChmod(); - return fs27.chmod(entry.absolute, entry.mode, afterChmod); - } - if (entry.absolute !== this.cwd) { - return fs27.rmdir(entry.absolute, (er) => this[MAKEFS](er, entry, done)); - } - } - if (entry.absolute === this.cwd) - return this[MAKEFS](null, entry, done); - unlinkFile(entry.absolute, (er) => this[MAKEFS](er, entry, done)); - }); - }; - if (this[CHECKED_CWD]) - start(); - else - checkCwd(); - } - [MAKEFS](er, entry, done) { - if (er) { - this[ONERROR](er, entry); - done(); - return; - } - switch (entry.type) { - case "File": - case "OldFile": - case "ContiguousFile": - return this[FILE](entry, done); - case "Link": - return this[HARDLINK](entry, done); - case "SymbolicLink": - return this[SYMLINK](entry, done); - case "Directory": - case "GNUDumpDir": - return this[DIRECTORY](entry, done); - } - } - [LINK](entry, linkpath, link, done) { - fs27[link](linkpath, entry.absolute, (er) => { - if (er) - this[ONERROR](er, entry); - else { - this[UNPEND](); - entry.resume(); - } - done(); - }); - } - }; - var callSync = (fn) => { - try { - return [null, fn()]; - } catch (er) { - return [er, null]; - } - }; - var UnpackSync = class extends Unpack { - [MAKEFS](er, entry) { - return super[MAKEFS](er, entry, () => { - }); - } - [CHECKFS](entry) { - this[PRUNECACHE](entry); - if (!this[CHECKED_CWD]) { - const er2 = this[MKDIR](this.cwd, this.dmode); - if (er2) - return this[ONERROR](er2, entry); - this[CHECKED_CWD] = true; - } - if (entry.absolute !== this.cwd) { - const parent = normPath(path36.dirname(entry.absolute)); - if (parent !== this.cwd) { - const mkParent = this[MKDIR](parent, this.dmode); - if (mkParent) - return this[ONERROR](mkParent, entry); - } - } - const [lstatEr, st] = callSync(() => fs27.lstatSync(entry.absolute)); - if (st && (this.keep || this.newer && st.mtime > entry.mtime)) - return this[SKIP](entry); - if (lstatEr || this[ISREUSABLE](entry, st)) - return this[MAKEFS](null, entry); - if (st.isDirectory()) { - if (entry.type === "Directory") { - const needChmod = !this.noChmod && entry.mode && (st.mode & 4095) !== entry.mode; - const [er3] = needChmod ? callSync(() => { - fs27.chmodSync(entry.absolute, entry.mode); - }) : []; - return this[MAKEFS](er3, entry); - } - const [er2] = callSync(() => fs27.rmdirSync(entry.absolute)); - this[MAKEFS](er2, entry); - } - const [er] = entry.absolute === this.cwd ? [] : callSync(() => unlinkFileSync(entry.absolute)); - this[MAKEFS](er, entry); - } - [FILE](entry, done) { - const mode = entry.mode & 4095 || this.fmode; - const oner = (er) => { - let closeError; - try { - fs27.closeSync(fd); - } catch (e) { - closeError = e; - } - if (er || closeError) - this[ONERROR](er || closeError, entry); - done(); - }; - let fd; - try { - fd = fs27.openSync(entry.absolute, getFlag(entry.size), mode); - } catch (er) { - return oner(er); - } - const tx = this.transform ? this.transform(entry) || entry : entry; - if (tx !== entry) { - tx.on("error", (er) => this[ONERROR](er, entry)); - entry.pipe(tx); - } - tx.on("data", (chunk) => { - try { - fs27.writeSync(fd, chunk, 0, chunk.length); - } catch (er) { - oner(er); - } - }); - tx.on("end", (_) => { - let er = null; - if (entry.mtime && !this.noMtime) { - const atime = entry.atime || new Date(); - const mtime = entry.mtime; - try { - fs27.futimesSync(fd, atime, mtime); - } catch (futimeser) { - try { - fs27.utimesSync(entry.absolute, atime, mtime); - } catch (utimeser) { - er = futimeser; - } - } - } - if (this[DOCHOWN](entry)) { - const uid = this[UID](entry); - const gid = this[GID](entry); - try { - fs27.fchownSync(fd, uid, gid); - } catch (fchowner) { - try { - fs27.chownSync(entry.absolute, uid, gid); - } catch (chowner) { - er = er || fchowner; - } - } - } - oner(er); - }); - } - [DIRECTORY](entry, done) { - const mode = entry.mode & 4095 || this.dmode; - const er = this[MKDIR](entry.absolute, mode); - if (er) { - this[ONERROR](er, entry); - done(); - return; - } - if (entry.mtime && !this.noMtime) { - try { - fs27.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime); - } catch (er2) { - } - } - if (this[DOCHOWN](entry)) { - try { - fs27.chownSync(entry.absolute, this[UID](entry), this[GID](entry)); - } catch (er2) { - } - } - done(); - entry.resume(); - } - [MKDIR](dir, mode) { - try { - return mkdir.sync(normPath(dir), { - uid: this.uid, - gid: this.gid, - processUid: this.processUid, - processGid: this.processGid, - umask: this.processUmask, - preserve: this.preservePaths, - unlink: this.unlink, - cache: this.dirCache, - cwd: this.cwd, - mode - }); - } catch (er) { - return er; - } - } - [LINK](entry, linkpath, link, done) { - try { - fs27[link + "Sync"](linkpath, entry.absolute); - done(); - entry.resume(); - } catch (er) { - return this[ONERROR](er, entry); - } - } - }; - Unpack.Sync = UnpackSync; - module2.exports = Unpack; - } -}); - -// node_modules/tar/lib/extract.js -var require_extract = __commonJS({ - "node_modules/tar/lib/extract.js"(exports2, module2) { - "use strict"; - var hlo = require_high_level_opt(); - var Unpack = require_unpack(); - var fs27 = require("fs"); - var fsm = require_fs_minipass(); - var path36 = require("path"); - var stripSlash = require_strip_trailing_slashes(); - module2.exports = (opt_, files, cb) => { - if (typeof opt_ === "function") - cb = opt_, files = null, opt_ = {}; - else if (Array.isArray(opt_)) - files = opt_, opt_ = {}; - if (typeof files === "function") - cb = files, files = null; - if (!files) - files = []; - else - files = Array.from(files); - const opt = hlo(opt_); - if (opt.sync && typeof cb === "function") - throw new TypeError("callback not supported for sync tar functions"); - if (!opt.file && typeof cb === "function") - throw new TypeError("callback only supported with file option"); - if (files.length) - filesFilter(opt, files); - return opt.file && opt.sync ? extractFileSync(opt) : opt.file ? extractFile(opt, cb) : opt.sync ? extractSync(opt) : extract(opt); - }; - var filesFilter = (opt, files) => { - const map = new Map(files.map((f) => [stripSlash(f), true])); - const filter = opt.filter; - const mapHas = (file, r) => { - const root = r || path36.parse(file).root || "."; - const ret = file === root ? false : map.has(file) ? map.get(file) : mapHas(path36.dirname(file), root); - map.set(file, ret); - return ret; - }; - opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) : (file) => mapHas(stripSlash(file)); - }; - var extractFileSync = (opt) => { - const u = new Unpack.Sync(opt); - const file = opt.file; - const stat = fs27.statSync(file); - const readSize = opt.maxReadSize || 16 * 1024 * 1024; - const stream = new fsm.ReadStreamSync(file, { - readSize, - size: stat.size - }); - stream.pipe(u); - }; - var extractFile = (opt, cb) => { - const u = new Unpack(opt); - const readSize = opt.maxReadSize || 16 * 1024 * 1024; - const file = opt.file; - const p = new Promise((resolve3, reject) => { - u.on("error", reject); - u.on("close", resolve3); - fs27.stat(file, (er, stat) => { - if (er) - reject(er); - else { - const stream = new fsm.ReadStream(file, { - readSize, - size: stat.size - }); - stream.on("error", reject); - stream.pipe(u); - } - }); - }); - return cb ? p.then(cb, cb) : p; - }; - var extractSync = (opt) => new Unpack.Sync(opt); - var extract = (opt) => new Unpack(opt); - } -}); - -// node_modules/tar/index.js -var require_tar = __commonJS({ - "node_modules/tar/index.js"(exports2) { - "use strict"; - exports2.c = exports2.create = require_create(); - exports2.r = exports2.replace = require_replace(); - exports2.t = exports2.list = require_list(); - exports2.u = exports2.update = require_update(); - exports2.x = exports2.extract = require_extract(); - exports2.Pack = require_pack(); - exports2.Unpack = require_unpack(); - exports2.Parse = require_parse2(); - exports2.ReadEntry = require_read_entry(); - exports2.WriteEntry = require_write_entry(); - exports2.Header = require_header(); - exports2.Pax = require_pax(); - exports2.types = require_types2(); - } -}); - -// node_modules/traverse/index.js -var require_traverse = __commonJS({ - "node_modules/traverse/index.js"(exports2, module2) { - module2.exports = Traverse; - function Traverse(obj) { - if (!(this instanceof Traverse)) - return new Traverse(obj); - this.value = obj; - } - Traverse.prototype.get = function(ps) { - var node = this.value; - for (var i = 0; i < ps.length; i++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) { - node = void 0; - break; - } - node = node[key]; - } - return node; - }; - Traverse.prototype.set = function(ps, value) { - var node = this.value; - for (var i = 0; i < ps.length - 1; i++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) - node[key] = {}; - node = node[key]; - } - node[ps[i]] = value; - return value; - }; - Traverse.prototype.map = function(cb) { - return walk2(this.value, cb, true); - }; - Traverse.prototype.forEach = function(cb) { - this.value = walk2(this.value, cb, false); - return this.value; - }; - Traverse.prototype.reduce = function(cb, init) { - var skip = arguments.length === 1; - var acc = skip ? this.value : init; - this.forEach(function(x) { - if (!this.isRoot || !skip) { - acc = cb.call(this, acc, x); - } - }); - return acc; - }; - Traverse.prototype.deepEqual = function(obj) { - if (arguments.length !== 1) { - throw new Error("deepEqual requires exactly one object to compare against"); - } - var equal = true; - var node = obj; - this.forEach(function(y) { - var notEqual = function() { - equal = false; - return void 0; - }.bind(this); - if (!this.isRoot) { - if (typeof node !== "object") - return notEqual(); - node = node[this.key]; - } - var x = node; - this.post(function() { - node = x; - }); - var toS = function(o) { - return Object.prototype.toString.call(o); - }; - if (this.circular) { - if (Traverse(obj).get(this.circular.path) !== x) - notEqual(); - } else if (typeof x !== typeof y) { - notEqual(); - } else if (x === null || y === null || x === void 0 || y === void 0) { - if (x !== y) - notEqual(); - } else if (x.__proto__ !== y.__proto__) { - notEqual(); - } else if (x === y) { - } else if (typeof x === "function") { - if (x instanceof RegExp) { - if (x.toString() != y.toString()) - notEqual(); - } else if (x !== y) - notEqual(); - } else if (typeof x === "object") { - if (toS(y) === "[object Arguments]" || toS(x) === "[object Arguments]") { - if (toS(x) !== toS(y)) { - notEqual(); - } - } else if (x instanceof Date || y instanceof Date) { - if (!(x instanceof Date) || !(y instanceof Date) || x.getTime() !== y.getTime()) { - notEqual(); - } - } else { - var kx = Object.keys(x); - var ky = Object.keys(y); - if (kx.length !== ky.length) - return notEqual(); - for (var i = 0; i < kx.length; i++) { - var k = kx[i]; - if (!Object.hasOwnProperty.call(y, k)) { - notEqual(); - } - } - } - } - }); - return equal; - }; - Traverse.prototype.paths = function() { - var acc = []; - this.forEach(function(x) { - acc.push(this.path); - }); - return acc; - }; - Traverse.prototype.nodes = function() { - var acc = []; - this.forEach(function(x) { - acc.push(this.node); - }); - return acc; - }; - Traverse.prototype.clone = function() { - var parents = [], nodes = []; - return function clone(src) { - for (var i = 0; i < parents.length; i++) { - if (parents[i] === src) { - return nodes[i]; - } - } - if (typeof src === "object" && src !== null) { - var dst = copy(src); - parents.push(src); - nodes.push(dst); - Object.keys(src).forEach(function(key) { - dst[key] = clone(src[key]); - }); - parents.pop(); - nodes.pop(); - return dst; - } else { - return src; - } - }(this.value); - }; - function walk2(root, cb, immutable) { - var path36 = []; - var parents = []; - var alive = true; - return function walker(node_) { - var node = immutable ? copy(node_) : node_; - var modifiers = {}; - var state = { - node, - node_, - path: [].concat(path36), - parent: parents.slice(-1)[0], - key: path36.slice(-1)[0], - isRoot: path36.length === 0, - level: path36.length, - circular: null, - update: function(x) { - if (!state.isRoot) { - state.parent.node[state.key] = x; - } - state.node = x; - }, - "delete": function() { - delete state.parent.node[state.key]; - }, - remove: function() { - if (Array.isArray(state.parent.node)) { - state.parent.node.splice(state.key, 1); - } else { - delete state.parent.node[state.key]; - } - }, - before: function(f) { - modifiers.before = f; - }, - after: function(f) { - modifiers.after = f; - }, - pre: function(f) { - modifiers.pre = f; - }, - post: function(f) { - modifiers.post = f; - }, - stop: function() { - alive = false; - } - }; - if (!alive) - return state; - if (typeof node === "object" && node !== null) { - state.isLeaf = Object.keys(node).length == 0; - for (var i = 0; i < parents.length; i++) { - if (parents[i].node_ === node_) { - state.circular = parents[i]; - break; - } - } - } else { - state.isLeaf = true; - } - state.notLeaf = !state.isLeaf; - state.notRoot = !state.isRoot; - var ret = cb.call(state, state.node); - if (ret !== void 0 && state.update) - state.update(ret); - if (modifiers.before) - modifiers.before.call(state, state.node); - if (typeof state.node == "object" && state.node !== null && !state.circular) { - parents.push(state); - var keys = Object.keys(state.node); - keys.forEach(function(key, i2) { - path36.push(key); - if (modifiers.pre) - modifiers.pre.call(state, state.node[key], key); - var child = walker(state.node[key]); - if (immutable && Object.hasOwnProperty.call(state.node, key)) { - state.node[key] = child.node; - } - child.isLast = i2 == keys.length - 1; - child.isFirst = i2 == 0; - if (modifiers.post) - modifiers.post.call(state, child); - path36.pop(); - }); - parents.pop(); - } - if (modifiers.after) - modifiers.after.call(state, state.node); - return state; - }(root).node; - } - Object.keys(Traverse.prototype).forEach(function(key) { - Traverse[key] = function(obj) { - var args = [].slice.call(arguments, 1); - var t = Traverse(obj); - return t[key].apply(t, args); - }; - }); - function copy(src) { - if (typeof src === "object" && src !== null) { - var dst; - if (Array.isArray(src)) { - dst = []; - } else if (src instanceof Date) { - dst = new Date(src); - } else if (src instanceof Boolean) { - dst = new Boolean(src); - } else if (src instanceof Number) { - dst = new Number(src); - } else if (src instanceof String) { - dst = new String(src); - } else { - dst = Object.create(Object.getPrototypeOf(src)); - } - Object.keys(src).forEach(function(key) { - dst[key] = src[key]; - }); - return dst; - } else - return src; - } - } -}); - -// node_modules/chainsaw/index.js -var require_chainsaw = __commonJS({ - "node_modules/chainsaw/index.js"(exports2, module2) { - var Traverse = require_traverse(); - var EventEmitter8 = require("events").EventEmitter; - module2.exports = Chainsaw; - function Chainsaw(builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== void 0) - saw.handlers = r; - saw.record(); - return saw.chain(); - } - Chainsaw.light = function ChainsawLight(builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== void 0) - saw.handlers = r; - return saw.chain(); - }; - Chainsaw.saw = function(builder, handlers) { - var saw = new EventEmitter8(); - saw.handlers = handlers; - saw.actions = []; - saw.chain = function() { - var ch = Traverse(saw.handlers).map(function(node) { - if (this.isRoot) - return node; - var ps = this.path; - if (typeof node === "function") { - this.update(function() { - saw.actions.push({ - path: ps, - args: [].slice.call(arguments) - }); - return ch; - }); - } - }); - process.nextTick(function() { - saw.emit("begin"); - saw.next(); - }); - return ch; - }; - saw.pop = function() { - return saw.actions.shift(); - }; - saw.next = function() { - var action = saw.pop(); - if (!action) { - saw.emit("end"); - } else if (!action.trap) { - var node = saw.handlers; - action.path.forEach(function(key) { - node = node[key]; - }); - node.apply(saw.handlers, action.args); - } - }; - saw.nest = function(cb) { - var args = [].slice.call(arguments, 1); - var autonext = true; - if (typeof cb === "boolean") { - var autonext = cb; - cb = args.shift(); - } - var s = Chainsaw.saw(builder, {}); - var r = builder.call(s.handlers, s); - if (r !== void 0) - s.handlers = r; - if (typeof saw.step !== "undefined") { - s.record(); - } - cb.apply(s.chain(), args); - if (autonext !== false) - s.on("end", saw.next); - }; - saw.record = function() { - upgradeChainsaw(saw); - }; - ["trap", "down", "jump"].forEach(function(method) { - saw[method] = function() { - throw new Error("To use the trap, down and jump features, please call record() first to start recording actions."); - }; - }); - return saw; - }; - function upgradeChainsaw(saw) { - saw.step = 0; - saw.pop = function() { - return saw.actions[saw.step++]; - }; - saw.trap = function(name2, cb) { - var ps = Array.isArray(name2) ? name2 : [name2]; - saw.actions.push({ - path: ps, - step: saw.step, - cb, - trap: true - }); - }; - saw.down = function(name2) { - var ps = (Array.isArray(name2) ? name2 : [name2]).join("/"); - var i = saw.actions.slice(saw.step).map(function(x) { - if (x.trap && x.step <= saw.step) - return false; - return x.path.join("/") == ps; - }).indexOf(true); - if (i >= 0) - saw.step += i; - else - saw.step = saw.actions.length; - var act = saw.actions[saw.step - 1]; - if (act && act.trap) { - saw.step = act.step; - act.cb(); - } else - saw.next(); - }; - saw.jump = function(step) { - saw.step = step; - saw.next(); - }; - } - } -}); - -// node_modules/buffers/index.js -var require_buffers = __commonJS({ - "node_modules/buffers/index.js"(exports2, module2) { - module2.exports = Buffers; - function Buffers(bufs) { - if (!(this instanceof Buffers)) - return new Buffers(bufs); - this.buffers = bufs || []; - this.length = this.buffers.reduce(function(size, buf) { - return size + buf.length; - }, 0); - } - Buffers.prototype.push = function() { - for (var i = 0; i < arguments.length; i++) { - if (!Buffer.isBuffer(arguments[i])) { - throw new TypeError("Tried to push a non-buffer"); - } - } - for (var i = 0; i < arguments.length; i++) { - var buf = arguments[i]; - this.buffers.push(buf); - this.length += buf.length; - } - return this.length; - }; - Buffers.prototype.unshift = function() { - for (var i = 0; i < arguments.length; i++) { - if (!Buffer.isBuffer(arguments[i])) { - throw new TypeError("Tried to unshift a non-buffer"); - } - } - for (var i = 0; i < arguments.length; i++) { - var buf = arguments[i]; - this.buffers.unshift(buf); - this.length += buf.length; - } - return this.length; - }; - Buffers.prototype.copy = function(dst, dStart, start, end) { - return this.slice(start, end).copy(dst, dStart, 0, end - start); - }; - Buffers.prototype.splice = function(i, howMany) { - var buffers = this.buffers; - var index = i >= 0 ? i : this.length - i; - var reps = [].slice.call(arguments, 2); - if (howMany === void 0) { - howMany = this.length - index; - } else if (howMany > this.length - index) { - howMany = this.length - index; - } - for (var i = 0; i < reps.length; i++) { - this.length += reps[i].length; - } - var removed = new Buffers(); - var bytes2 = 0; - var startBytes = 0; - for (var ii = 0; ii < buffers.length && startBytes + buffers[ii].length < index; ii++) { - startBytes += buffers[ii].length; - } - if (index - startBytes > 0) { - var start = index - startBytes; - if (start + howMany < buffers[ii].length) { - removed.push(buffers[ii].slice(start, start + howMany)); - var orig = buffers[ii]; - var buf0 = new Buffer(start); - for (var i = 0; i < start; i++) { - buf0[i] = orig[i]; - } - var buf1 = new Buffer(orig.length - start - howMany); - for (var i = start + howMany; i < orig.length; i++) { - buf1[i - howMany - start] = orig[i]; - } - if (reps.length > 0) { - var reps_ = reps.slice(); - reps_.unshift(buf0); - reps_.push(buf1); - buffers.splice.apply(buffers, [ii, 1].concat(reps_)); - ii += reps_.length; - reps = []; - } else { - buffers.splice(ii, 1, buf0, buf1); - ii += 2; - } - } else { - removed.push(buffers[ii].slice(start)); - buffers[ii] = buffers[ii].slice(0, start); - ii++; - } - } - if (reps.length > 0) { - buffers.splice.apply(buffers, [ii, 0].concat(reps)); - ii += reps.length; - } - while (removed.length < howMany) { - var buf = buffers[ii]; - var len = buf.length; - var take = Math.min(len, howMany - removed.length); - if (take === len) { - removed.push(buf); - buffers.splice(ii, 1); - } else { - removed.push(buf.slice(0, take)); - buffers[ii] = buffers[ii].slice(take); - } - } - this.length -= removed.length; - return removed; - }; - Buffers.prototype.slice = function(i, j) { - var buffers = this.buffers; - if (j === void 0) - j = this.length; - if (i === void 0) - i = 0; - if (j > this.length) - j = this.length; - var startBytes = 0; - for (var si = 0; si < buffers.length && startBytes + buffers[si].length <= i; si++) { - startBytes += buffers[si].length; - } - var target = new Buffer(j - i); - var ti = 0; - for (var ii = si; ti < j - i && ii < buffers.length; ii++) { - var len = buffers[ii].length; - var start = ti === 0 ? i - startBytes : 0; - var end = ti + len >= j - i ? Math.min(start + (j - i) - ti, len) : len; - buffers[ii].copy(target, ti, start, end); - ti += end - start; - } - return target; - }; - Buffers.prototype.pos = function(i) { - if (i < 0 || i >= this.length) - throw new Error("oob"); - var l = i, bi = 0, bu = null; - for (; ; ) { - bu = this.buffers[bi]; - if (l < bu.length) { - return { buf: bi, offset: l }; - } else { - l -= bu.length; - } - bi++; - } - }; - Buffers.prototype.get = function get(i) { - var pos = this.pos(i); - return this.buffers[pos.buf].get(pos.offset); - }; - Buffers.prototype.set = function set(i, b) { - var pos = this.pos(i); - return this.buffers[pos.buf].set(pos.offset, b); - }; - Buffers.prototype.indexOf = function(needle, offset) { - if (typeof needle === "string") { - needle = new Buffer(needle); - } else if (needle instanceof Buffer) { - } else { - throw new Error("Invalid type for a search string"); - } - if (!needle.length) { - return 0; - } - if (!this.length) { - return -1; - } - var i = 0, j = 0, match = 0, mstart, pos = 0; - if (offset) { - var p = this.pos(offset); - i = p.buf; - j = p.offset; - pos = offset; - } - for (; ; ) { - while (j >= this.buffers[i].length) { - j = 0; - i++; - if (i >= this.buffers.length) { - return -1; - } - } - var char = this.buffers[i][j]; - if (char == needle[match]) { - if (match == 0) { - mstart = { - i, - j, - pos - }; - } - match++; - if (match == needle.length) { - return mstart.pos; - } - } else if (match != 0) { - i = mstart.i; - j = mstart.j; - pos = mstart.pos; - match = 0; - } - j++; - pos++; - } - }; - Buffers.prototype.toBuffer = function() { - return this.slice(); - }; - Buffers.prototype.toString = function(encoding, start, end) { - return this.slice(start, end).toString(encoding); - }; - } -}); - -// node_modules/binary/lib/vars.js -var require_vars = __commonJS({ - "node_modules/binary/lib/vars.js"(exports2, module2) { - module2.exports = function(store) { - function getset(name2, value) { - var node = vars.store; - var keys = name2.split("."); - keys.slice(0, -1).forEach(function(k) { - if (node[k] === void 0) - node[k] = {}; - node = node[k]; - }); - var key = keys[keys.length - 1]; - if (arguments.length == 1) { - return node[key]; - } else { - return node[key] = value; - } - } - var vars = { - get: function(name2) { - return getset(name2); - }, - set: function(name2, value) { - return getset(name2, value); - }, - store: store || {} - }; - return vars; - }; - } -}); - -// node_modules/binary/index.js -var require_binary = __commonJS({ - "node_modules/binary/index.js"(exports2, module2) { - var Chainsaw = require_chainsaw(); - var EventEmitter8 = require("events").EventEmitter; - var Buffers = require_buffers(); - var Vars = require_vars(); - var Stream = require("stream").Stream; - exports2 = module2.exports = function(bufOrEm, eventName) { - if (Buffer.isBuffer(bufOrEm)) { - return exports2.parse(bufOrEm); - } - var s = exports2.stream(); - if (bufOrEm && bufOrEm.pipe) { - bufOrEm.pipe(s); - } else if (bufOrEm) { - bufOrEm.on(eventName || "data", function(buf) { - s.write(buf); - }); - bufOrEm.on("end", function() { - s.end(); - }); - } - return s; - }; - exports2.stream = function(input) { - if (input) - return exports2.apply(null, arguments); - var pending = null; - function getBytes(bytes2, cb, skip) { - pending = { - bytes: bytes2, - skip, - cb: function(buf) { - pending = null; - cb(buf); - } - }; - dispatch(); - } - var offset = null; - function dispatch() { - if (!pending) { - if (caughtEnd) - done = true; - return; - } - if (typeof pending === "function") { - pending(); - } else { - var bytes2 = offset + pending.bytes; - if (buffers.length >= bytes2) { - var buf; - if (offset == null) { - buf = buffers.splice(0, bytes2); - if (!pending.skip) { - buf = buf.slice(); - } - } else { - if (!pending.skip) { - buf = buffers.slice(offset, bytes2); - } - offset = bytes2; - } - if (pending.skip) { - pending.cb(); - } else { - pending.cb(buf); - } - } - } - } - function builder(saw) { - function next() { - if (!done) - saw.next(); - } - var self2 = words(function(bytes2, cb) { - return function(name2) { - getBytes(bytes2, function(buf) { - vars.set(name2, cb(buf)); - next(); - }); - }; - }); - self2.tap = function(cb) { - saw.nest(cb, vars.store); - }; - self2.into = function(key, cb) { - if (!vars.get(key)) - vars.set(key, {}); - var parent = vars; - vars = Vars(parent.get(key)); - saw.nest(function() { - cb.apply(this, arguments); - this.tap(function() { - vars = parent; - }); - }, vars.store); - }; - self2.flush = function() { - vars.store = {}; - next(); - }; - self2.loop = function(cb) { - var end = false; - saw.nest(false, function loop() { - this.vars = vars.store; - cb.call(this, function() { - end = true; - next(); - }, vars.store); - this.tap(function() { - if (end) - saw.next(); - else - loop.call(this); - }.bind(this)); - }, vars.store); - }; - self2.buffer = function(name2, bytes2) { - if (typeof bytes2 === "string") { - bytes2 = vars.get(bytes2); - } - getBytes(bytes2, function(buf) { - vars.set(name2, buf); - next(); - }); - }; - self2.skip = function(bytes2) { - if (typeof bytes2 === "string") { - bytes2 = vars.get(bytes2); - } - getBytes(bytes2, function() { - next(); - }); - }; - self2.scan = function find(name2, search) { - if (typeof search === "string") { - search = new Buffer(search); - } else if (!Buffer.isBuffer(search)) { - throw new Error("search must be a Buffer or a string"); - } - var taken = 0; - pending = function() { - var pos = buffers.indexOf(search, offset + taken); - var i = pos - offset - taken; - if (pos !== -1) { - pending = null; - if (offset != null) { - vars.set(name2, buffers.slice(offset, offset + taken + i)); - offset += taken + i + search.length; - } else { - vars.set(name2, buffers.slice(0, taken + i)); - buffers.splice(0, taken + i + search.length); - } - next(); - dispatch(); - } else { - i = Math.max(buffers.length - search.length - offset - taken, 0); - } - taken += i; - }; - dispatch(); - }; - self2.peek = function(cb) { - offset = 0; - saw.nest(function() { - cb.call(this, vars.store); - this.tap(function() { - offset = null; - }); - }); - }; - return self2; - } - ; - var stream = Chainsaw.light(builder); - stream.writable = true; - var buffers = Buffers(); - stream.write = function(buf) { - buffers.push(buf); - dispatch(); - }; - var vars = Vars(); - var done = false, caughtEnd = false; - stream.end = function() { - caughtEnd = true; - }; - stream.pipe = Stream.prototype.pipe; - Object.getOwnPropertyNames(EventEmitter8.prototype).forEach(function(name2) { - stream[name2] = EventEmitter8.prototype[name2]; - }); - return stream; - }; - exports2.parse = function parse5(buffer) { - var self2 = words(function(bytes2, cb) { - return function(name2) { - if (offset + bytes2 <= buffer.length) { - var buf = buffer.slice(offset, offset + bytes2); - offset += bytes2; - vars.set(name2, cb(buf)); - } else { - vars.set(name2, null); - } - return self2; - }; - }); - var offset = 0; - var vars = Vars(); - self2.vars = vars.store; - self2.tap = function(cb) { - cb.call(self2, vars.store); - return self2; - }; - self2.into = function(key, cb) { - if (!vars.get(key)) { - vars.set(key, {}); - } - var parent = vars; - vars = Vars(parent.get(key)); - cb.call(self2, vars.store); - vars = parent; - return self2; - }; - self2.loop = function(cb) { - var end = false; - var ender = function() { - end = true; - }; - while (end === false) { - cb.call(self2, ender, vars.store); - } - return self2; - }; - self2.buffer = function(name2, size) { - if (typeof size === "string") { - size = vars.get(size); - } - var buf = buffer.slice(offset, Math.min(buffer.length, offset + size)); - offset += size; - vars.set(name2, buf); - return self2; - }; - self2.skip = function(bytes2) { - if (typeof bytes2 === "string") { - bytes2 = vars.get(bytes2); - } - offset += bytes2; - return self2; - }; - self2.scan = function(name2, search) { - if (typeof search === "string") { - search = new Buffer(search); - } else if (!Buffer.isBuffer(search)) { - throw new Error("search must be a Buffer or a string"); - } - vars.set(name2, null); - for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) { - for (var j = 0; j < search.length && buffer[offset + i + j] === search[j]; j++) - ; - if (j === search.length) - break; - } - vars.set(name2, buffer.slice(offset, offset + i)); - offset += i + search.length; - return self2; - }; - self2.peek = function(cb) { - var was = offset; - cb.call(self2, vars.store); - offset = was; - return self2; - }; - self2.flush = function() { - vars.store = {}; - return self2; - }; - self2.eof = function() { - return offset >= buffer.length; - }; - return self2; - }; - function decodeLEu(bytes2) { - var acc = 0; - for (var i = 0; i < bytes2.length; i++) { - acc += Math.pow(256, i) * bytes2[i]; - } - return acc; - } - function decodeBEu(bytes2) { - var acc = 0; - for (var i = 0; i < bytes2.length; i++) { - acc += Math.pow(256, bytes2.length - i - 1) * bytes2[i]; - } - return acc; - } - function decodeBEs(bytes2) { - var val = decodeBEu(bytes2); - if ((bytes2[0] & 128) == 128) { - val -= Math.pow(256, bytes2.length); - } - return val; - } - function decodeLEs(bytes2) { - var val = decodeLEu(bytes2); - if ((bytes2[bytes2.length - 1] & 128) == 128) { - val -= Math.pow(256, bytes2.length); - } - return val; - } - function words(decode) { - var self2 = {}; - [1, 2, 4, 8].forEach(function(bytes2) { - var bits = bytes2 * 8; - self2["word" + bits + "le"] = self2["word" + bits + "lu"] = decode(bytes2, decodeLEu); - self2["word" + bits + "ls"] = decode(bytes2, decodeLEs); - self2["word" + bits + "be"] = self2["word" + bits + "bu"] = decode(bytes2, decodeBEu); - self2["word" + bits + "bs"] = decode(bytes2, decodeBEs); - }); - self2.word8 = self2.word8u = self2.word8be; - self2.word8s = self2.word8bs; - return self2; - } - } -}); - -// node_modules/unzip-stream/lib/matcher-stream.js -var require_matcher_stream = __commonJS({ - "node_modules/unzip-stream/lib/matcher-stream.js"(exports2, module2) { - var Transform2 = require("stream").Transform; - var util4 = require("util"); - function MatcherStream(patternDesc, matchFn) { - if (!(this instanceof MatcherStream)) { - return new MatcherStream(); - } - Transform2.call(this); - var p = typeof patternDesc === "object" ? patternDesc.pattern : patternDesc; - this.pattern = Buffer.isBuffer(p) ? p : Buffer.from(p); - this.requiredLength = this.pattern.length; - if (patternDesc.requiredExtraSize) - this.requiredLength += patternDesc.requiredExtraSize; - this.data = new Buffer(""); - this.bytesSoFar = 0; - this.matchFn = matchFn; - } - util4.inherits(MatcherStream, Transform2); - MatcherStream.prototype.checkDataChunk = function(ignoreMatchZero) { - var enoughData = this.data.length >= this.requiredLength; - if (!enoughData) { - return; - } - var matchIndex = this.data.indexOf(this.pattern, ignoreMatchZero ? 1 : 0); - if (matchIndex >= 0 && matchIndex + this.requiredLength > this.data.length) { - if (matchIndex > 0) { - var packet = this.data.slice(0, matchIndex); - this.push(packet); - this.bytesSoFar += matchIndex; - this.data = this.data.slice(matchIndex); - } - return; - } - if (matchIndex === -1) { - var packetLen = this.data.length - this.requiredLength + 1; - var packet = this.data.slice(0, packetLen); - this.push(packet); - this.bytesSoFar += packetLen; - this.data = this.data.slice(packetLen); - return; - } - if (matchIndex > 0) { - var packet = this.data.slice(0, matchIndex); - this.data = this.data.slice(matchIndex); - this.push(packet); - this.bytesSoFar += matchIndex; - } - var finished = this.matchFn ? this.matchFn(this.data, this.bytesSoFar) : true; - if (finished) { - this.data = new Buffer(""); - return; - } - return true; - }; - MatcherStream.prototype._transform = function(chunk, encoding, cb) { - this.data = Buffer.concat([this.data, chunk]); - var firstIteration = true; - while (this.checkDataChunk(!firstIteration)) { - firstIteration = false; - } - cb(); - }; - MatcherStream.prototype._flush = function(cb) { - if (this.data.length > 0) { - var firstIteration = true; - while (this.checkDataChunk(!firstIteration)) { - firstIteration = false; - } - } - if (this.data.length > 0) { - this.push(this.data); - this.data = null; - } - cb(); - }; - module2.exports = MatcherStream; - } -}); - -// node_modules/unzip-stream/lib/entry.js -var require_entry = __commonJS({ - "node_modules/unzip-stream/lib/entry.js"(exports2, module2) { - "use strict"; - var stream = require("stream"); - var inherits = require("util").inherits; - function Entry() { - if (!(this instanceof Entry)) { - return new Entry(); - } - stream.PassThrough.call(this); - this.path = null; - this.type = null; - this.isDirectory = false; - } - inherits(Entry, stream.PassThrough); - Entry.prototype.autodrain = function() { - return this.pipe(new stream.Transform({ transform: function(d, e, cb) { - cb(); - } })); - }; - module2.exports = Entry; - } -}); - -// node_modules/unzip-stream/lib/unzip-stream.js -var require_unzip_stream = __commonJS({ - "node_modules/unzip-stream/lib/unzip-stream.js"(exports2, module2) { - "use strict"; - var binary = require_binary(); - var stream = require("stream"); - var util4 = require("util"); - var zlib = require("zlib"); - var MatcherStream = require_matcher_stream(); - var Entry = require_entry(); - var states = { - STREAM_START: 0, - START: 1, - LOCAL_FILE_HEADER: 2, - LOCAL_FILE_HEADER_SUFFIX: 3, - FILE_DATA: 4, - FILE_DATA_END: 5, - DATA_DESCRIPTOR: 6, - CENTRAL_DIRECTORY_FILE_HEADER: 7, - CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX: 8, - CDIR64_END: 9, - CDIR64_END_DATA_SECTOR: 10, - CDIR64_LOCATOR: 11, - CENTRAL_DIRECTORY_END: 12, - CENTRAL_DIRECTORY_END_COMMENT: 13, - TRAILING_JUNK: 14, - ERROR: 99 - }; - var FOUR_GIGS = 4294967296; - var SIG_LOCAL_FILE_HEADER = 67324752; - var SIG_DATA_DESCRIPTOR = 134695760; - var SIG_CDIR_RECORD = 33639248; - var SIG_CDIR64_RECORD_END = 101075792; - var SIG_CDIR64_LOCATOR_END = 117853008; - var SIG_CDIR_RECORD_END = 101010256; - function UnzipStream(options) { - if (!(this instanceof UnzipStream)) { - return new UnzipStream(options); - } - stream.Transform.call(this); - this.options = options || {}; - this.data = new Buffer(""); - this.state = states.STREAM_START; - this.skippedBytes = 0; - this.parsedEntity = null; - this.outStreamInfo = {}; - } - util4.inherits(UnzipStream, stream.Transform); - UnzipStream.prototype.processDataChunk = function(chunk) { - var requiredLength; - switch (this.state) { - case states.STREAM_START: - case states.START: - requiredLength = 4; - break; - case states.LOCAL_FILE_HEADER: - requiredLength = 26; - break; - case states.LOCAL_FILE_HEADER_SUFFIX: - requiredLength = this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength; - break; - case states.DATA_DESCRIPTOR: - requiredLength = 12; - break; - case states.CENTRAL_DIRECTORY_FILE_HEADER: - requiredLength = 42; - break; - case states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX: - requiredLength = this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength + this.parsedEntity.fileCommentLength; - break; - case states.CDIR64_END: - requiredLength = 52; - break; - case states.CDIR64_END_DATA_SECTOR: - requiredLength = this.parsedEntity.centralDirectoryRecordSize - 44; - break; - case states.CDIR64_LOCATOR: - requiredLength = 16; - break; - case states.CENTRAL_DIRECTORY_END: - requiredLength = 18; - break; - case states.CENTRAL_DIRECTORY_END_COMMENT: - requiredLength = this.parsedEntity.commentLength; - break; - case states.FILE_DATA: - return 0; - case states.FILE_DATA_END: - return 0; - case states.TRAILING_JUNK: - if (this.options.debug) - console.log("found", chunk.length, "bytes of TRAILING_JUNK"); - return chunk.length; - default: - return chunk.length; - } - var chunkLength = chunk.length; - if (chunkLength < requiredLength) { - return 0; - } - switch (this.state) { - case states.STREAM_START: - case states.START: - var signature = chunk.readUInt32LE(0); - switch (signature) { - case SIG_LOCAL_FILE_HEADER: - this.state = states.LOCAL_FILE_HEADER; - break; - case SIG_CDIR_RECORD: - this.state = states.CENTRAL_DIRECTORY_FILE_HEADER; - break; - case SIG_CDIR64_RECORD_END: - this.state = states.CDIR64_END; - break; - case SIG_CDIR64_LOCATOR_END: - this.state = states.CDIR64_LOCATOR; - break; - case SIG_CDIR_RECORD_END: - this.state = states.CENTRAL_DIRECTORY_END; - break; - default: - var isStreamStart = this.state === states.STREAM_START; - if (!isStreamStart && (signature & 65535) !== 19280 && this.skippedBytes < 26) { - var remaining = signature; - var toSkip = 4; - for (var i = 1; i < 4 && remaining !== 0; i++) { - remaining = remaining >>> 8; - if ((remaining & 255) === 80) { - toSkip = i; - break; - } - } - this.skippedBytes += toSkip; - if (this.options.debug) - console.log("Skipped", this.skippedBytes, "bytes"); - return toSkip; - } - this.state = states.ERROR; - var errMsg = isStreamStart ? "Not a valid zip file" : "Invalid signature in zip file"; - if (this.options.debug) { - var sig = chunk.readUInt32LE(0); - var asString; - try { - asString = chunk.slice(0, 4).toString(); - } catch (e) { - } - console.log("Unexpected signature in zip file: 0x" + sig.toString(16), '"' + asString + '", skipped', this.skippedBytes, "bytes"); - } - this.emit("error", new Error(errMsg)); - return chunk.length; - } - this.skippedBytes = 0; - return requiredLength; - case states.LOCAL_FILE_HEADER: - this.parsedEntity = this._readFile(chunk); - this.state = states.LOCAL_FILE_HEADER_SUFFIX; - return requiredLength; - case states.LOCAL_FILE_HEADER_SUFFIX: - var entry = new Entry(); - var isUtf8 = (this.parsedEntity.flags & 2048) !== 0; - entry.path = this._decodeString(chunk.slice(0, this.parsedEntity.fileNameLength), isUtf8); - var extraDataBuffer = chunk.slice(this.parsedEntity.fileNameLength, this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength); - var extra = this._readExtraFields(extraDataBuffer); - if (extra && extra.parsed) { - if (extra.parsed.path && !isUtf8) { - entry.path = extra.parsed.path; - } - if (Number.isFinite(extra.parsed.uncompressedSize) && this.parsedEntity.uncompressedSize === FOUR_GIGS - 1) { - this.parsedEntity.uncompressedSize = extra.parsed.uncompressedSize; - } - if (Number.isFinite(extra.parsed.compressedSize) && this.parsedEntity.compressedSize === FOUR_GIGS - 1) { - this.parsedEntity.compressedSize = extra.parsed.compressedSize; - } - } - this.parsedEntity.extra = extra.parsed || {}; - if (this.options.debug) { - const debugObj = Object.assign({}, this.parsedEntity, { - path: entry.path, - flags: "0x" + this.parsedEntity.flags.toString(16), - extraFields: extra && extra.debug - }); - console.log("decoded LOCAL_FILE_HEADER:", JSON.stringify(debugObj, null, 2)); - } - this._prepareOutStream(this.parsedEntity, entry); - this.emit("entry", entry); - this.state = states.FILE_DATA; - return requiredLength; - case states.CENTRAL_DIRECTORY_FILE_HEADER: - this.parsedEntity = this._readCentralDirectoryEntry(chunk); - this.state = states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX; - return requiredLength; - case states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX: - var isUtf8 = (this.parsedEntity.flags & 2048) !== 0; - var path36 = this._decodeString(chunk.slice(0, this.parsedEntity.fileNameLength), isUtf8); - var extraDataBuffer = chunk.slice(this.parsedEntity.fileNameLength, this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength); - var extra = this._readExtraFields(extraDataBuffer); - if (extra && extra.parsed && extra.parsed.path && !isUtf8) { - path36 = extra.parsed.path; - } - this.parsedEntity.extra = extra.parsed; - var isUnix = (this.parsedEntity.versionMadeBy & 65280) >> 8 === 3; - var unixAttrs, isSymlink; - if (isUnix) { - unixAttrs = this.parsedEntity.externalFileAttributes >>> 16; - var fileType = unixAttrs >>> 12; - isSymlink = (fileType & 10) === 10; - } - if (this.options.debug) { - const debugObj = Object.assign({}, this.parsedEntity, { - path: path36, - flags: "0x" + this.parsedEntity.flags.toString(16), - unixAttrs: unixAttrs && "0" + unixAttrs.toString(8), - isSymlink, - extraFields: extra.debug - }); - console.log("decoded CENTRAL_DIRECTORY_FILE_HEADER:", JSON.stringify(debugObj, null, 2)); - } - this.state = states.START; - return requiredLength; - case states.CDIR64_END: - this.parsedEntity = this._readEndOfCentralDirectory64(chunk); - if (this.options.debug) { - console.log("decoded CDIR64_END_RECORD:", this.parsedEntity); - } - this.state = states.CDIR64_END_DATA_SECTOR; - return requiredLength; - case states.CDIR64_END_DATA_SECTOR: - this.state = states.START; - return requiredLength; - case states.CDIR64_LOCATOR: - this.state = states.START; - return requiredLength; - case states.CENTRAL_DIRECTORY_END: - this.parsedEntity = this._readEndOfCentralDirectory(chunk); - if (this.options.debug) { - console.log("decoded CENTRAL_DIRECTORY_END:", this.parsedEntity); - } - this.state = states.CENTRAL_DIRECTORY_END_COMMENT; - return requiredLength; - case states.CENTRAL_DIRECTORY_END_COMMENT: - if (this.options.debug) { - console.log("decoded CENTRAL_DIRECTORY_END_COMMENT:", chunk.slice(0, requiredLength).toString()); - } - this.state = states.TRAILING_JUNK; - return requiredLength; - case states.ERROR: - return chunk.length; - default: - console.log("didn't handle state #", this.state, "discarding"); - return chunk.length; - } - }; - UnzipStream.prototype._prepareOutStream = function(vars, entry) { - var self2 = this; - var isDirectory = vars.uncompressedSize === 0 && /[\/\\]$/.test(entry.path); - entry.path = entry.path.replace(/^([/\\]*[.]+[/\\]+)*[/\\]*/, ""); - entry.type = isDirectory ? "Directory" : "File"; - entry.isDirectory = isDirectory; - var fileSizeKnown = !(vars.flags & 8); - if (fileSizeKnown) { - entry.size = vars.uncompressedSize; - } - var isVersionSupported = vars.versionsNeededToExtract <= 45; - this.outStreamInfo = { - stream: null, - limit: fileSizeKnown ? vars.compressedSize : -1, - written: 0 - }; - if (!fileSizeKnown) { - var pattern = new Buffer(4); - pattern.writeUInt32LE(SIG_DATA_DESCRIPTOR, 0); - var zip64Mode = vars.extra.zip64Mode; - var extraSize = zip64Mode ? 20 : 12; - var searchPattern = { - pattern, - requiredExtraSize: extraSize - }; - var matcherStream = new MatcherStream(searchPattern, function(matchedChunk, sizeSoFar) { - var vars2 = self2._readDataDescriptor(matchedChunk, zip64Mode); - var compressedSizeMatches = vars2.compressedSize === sizeSoFar; - if (!zip64Mode && !compressedSizeMatches && sizeSoFar >= FOUR_GIGS) { - var overflown = sizeSoFar - FOUR_GIGS; - while (overflown >= 0) { - compressedSizeMatches = vars2.compressedSize === overflown; - if (compressedSizeMatches) - break; - overflown -= FOUR_GIGS; - } - } - if (!compressedSizeMatches) { - return; - } - self2.state = states.FILE_DATA_END; - var sliceOffset = zip64Mode ? 24 : 16; - if (self2.data.length > 0) { - self2.data = Buffer.concat([matchedChunk.slice(sliceOffset), self2.data]); - } else { - self2.data = matchedChunk.slice(sliceOffset); - } - return true; - }); - this.outStreamInfo.stream = matcherStream; - } else { - this.outStreamInfo.stream = new stream.PassThrough(); - } - var isEncrypted = vars.flags & 1 || vars.flags & 64; - if (isEncrypted || !isVersionSupported) { - var message = isEncrypted ? "Encrypted files are not supported!" : "Zip version " + Math.floor(vars.versionsNeededToExtract / 10) + "." + vars.versionsNeededToExtract % 10 + " is not supported"; - entry.skip = true; - setImmediate(() => { - entry.emit("error", new Error(message)); - }); - this.outStreamInfo.stream.pipe(new Entry().autodrain()); - return; - } - var isCompressed = vars.compressionMethod > 0; - if (isCompressed) { - var inflater = zlib.createInflateRaw(); - inflater.on("error", function(err) { - self2.state = states.ERROR; - self2.emit("error", err); - }); - this.outStreamInfo.stream.pipe(inflater).pipe(entry); - } else { - this.outStreamInfo.stream.pipe(entry); - } - if (this._drainAllEntries) { - entry.autodrain(); - } - }; - UnzipStream.prototype._readFile = function(data) { - var vars = binary.parse(data).word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars; - return vars; - }; - UnzipStream.prototype._readExtraFields = function(data) { - var extra = {}; - var result = { parsed: extra }; - if (this.options.debug) { - result.debug = []; - } - var index = 0; - while (index < data.length) { - var vars = binary.parse(data).skip(index).word16lu("extraId").word16lu("extraSize").vars; - index += 4; - var fieldType = void 0; - switch (vars.extraId) { - case 1: - fieldType = "Zip64 extended information extra field"; - var z64vars = binary.parse(data.slice(index, index + vars.extraSize)).word64lu("uncompressedSize").word64lu("compressedSize").word64lu("offsetToLocalHeader").word32lu("diskStartNumber").vars; - if (z64vars.uncompressedSize !== null) { - extra.uncompressedSize = z64vars.uncompressedSize; - } - if (z64vars.compressedSize !== null) { - extra.compressedSize = z64vars.compressedSize; - } - extra.zip64Mode = true; - break; - case 10: - fieldType = "NTFS extra field"; - break; - case 21589: - fieldType = "extended timestamp"; - var timestampFields = data.readUInt8(index); - var offset = 1; - if (vars.extraSize >= offset + 4 && timestampFields & 1) { - extra.mtime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - } - if (vars.extraSize >= offset + 4 && timestampFields & 2) { - extra.atime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - } - if (vars.extraSize >= offset + 4 && timestampFields & 4) { - extra.ctime = new Date(data.readUInt32LE(index + offset) * 1e3); - } - break; - case 28789: - fieldType = "Info-ZIP Unicode Path Extra Field"; - var fieldVer = data.readUInt8(index); - if (fieldVer === 1) { - var offset = 1; - var nameCrc32 = data.readUInt32LE(index + offset); - offset += 4; - var pathBuffer = data.slice(index + offset); - extra.path = pathBuffer.toString(); - } - break; - case 13: - case 22613: - fieldType = vars.extraId === 13 ? "PKWARE Unix" : "Info-ZIP UNIX (type 1)"; - var offset = 0; - if (vars.extraSize >= 8) { - var atime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - var mtime = new Date(data.readUInt32LE(index + offset) * 1e3); - offset += 4; - extra.atime = atime; - extra.mtime = mtime; - if (vars.extraSize >= 12) { - var uid = data.readUInt16LE(index + offset); - offset += 2; - var gid = data.readUInt16LE(index + offset); - offset += 2; - extra.uid = uid; - extra.gid = gid; - } - } - break; - case 30805: - fieldType = "Info-ZIP UNIX (type 2)"; - var offset = 0; - if (vars.extraSize >= 4) { - var uid = data.readUInt16LE(index + offset); - offset += 2; - var gid = data.readUInt16LE(index + offset); - offset += 2; - extra.uid = uid; - extra.gid = gid; - } - break; - case 30837: - fieldType = "Info-ZIP New Unix"; - var offset = 0; - var extraVer = data.readUInt8(index); - offset += 1; - if (extraVer === 1) { - var uidSize = data.readUInt8(index + offset); - offset += 1; - if (uidSize <= 6) { - extra.uid = data.readUIntLE(index + offset, uidSize); - } - offset += uidSize; - var gidSize = data.readUInt8(index + offset); - offset += 1; - if (gidSize <= 6) { - extra.gid = data.readUIntLE(index + offset, gidSize); - } - } - break; - case 30062: - fieldType = "ASi Unix"; - var offset = 0; - if (vars.extraSize >= 14) { - var crc = data.readUInt32LE(index + offset); - offset += 4; - var mode = data.readUInt16LE(index + offset); - offset += 2; - var sizdev = data.readUInt32LE(index + offset); - offset += 4; - var uid = data.readUInt16LE(index + offset); - offset += 2; - var gid = data.readUInt16LE(index + offset); - offset += 2; - extra.mode = mode; - extra.uid = uid; - extra.gid = gid; - if (vars.extraSize > 14) { - var start = index + offset; - var end = index + vars.extraSize - 14; - var symlinkName = this._decodeString(data.slice(start, end)); - extra.symlink = symlinkName; - } - } - break; - } - if (this.options.debug) { - result.debug.push({ - extraId: "0x" + vars.extraId.toString(16), - description: fieldType, - data: data.slice(index, index + vars.extraSize).inspect() - }); - } - index += vars.extraSize; - } - return result; - }; - UnzipStream.prototype._readDataDescriptor = function(data, zip64Mode) { - if (zip64Mode) { - var vars = binary.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word64lu("compressedSize").word64lu("uncompressedSize").vars; - return vars; - } - var vars = binary.parse(data).word32lu("dataDescriptorSignature").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").vars; - return vars; - }; - UnzipStream.prototype._readCentralDirectoryEntry = function(data) { - var vars = binary.parse(data).word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars; - return vars; - }; - UnzipStream.prototype._readEndOfCentralDirectory64 = function(data) { - var vars = binary.parse(data).word64lu("centralDirectoryRecordSize").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskNumberWithCentralDirectoryStart").word64lu("centralDirectoryEntries").word64lu("totalCentralDirectoryEntries").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars; - return vars; - }; - UnzipStream.prototype._readEndOfCentralDirectory = function(data) { - var vars = binary.parse(data).word16lu("diskNumber").word16lu("diskStart").word16lu("centralDirectoryEntries").word16lu("totalCentralDirectoryEntries").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars; - return vars; - }; - var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0 "; - UnzipStream.prototype._decodeString = function(buffer, isUtf8) { - if (isUtf8) { - return buffer.toString("utf8"); - } - if (this.options.decodeString) { - return this.options.decodeString(buffer); - } - let result = ""; - for (var i = 0; i < buffer.length; i++) { - result += cp437[buffer[i]]; - } - return result; - }; - UnzipStream.prototype._parseOrOutput = function(encoding, cb) { - var consume; - while ((consume = this.processDataChunk(this.data)) > 0) { - this.data = this.data.slice(consume); - if (this.data.length === 0) - break; - } - if (this.state === states.FILE_DATA) { - if (this.outStreamInfo.limit >= 0) { - var remaining = this.outStreamInfo.limit - this.outStreamInfo.written; - var packet; - if (remaining < this.data.length) { - packet = this.data.slice(0, remaining); - this.data = this.data.slice(remaining); - } else { - packet = this.data; - this.data = new Buffer(""); - } - this.outStreamInfo.written += packet.length; - if (this.outStreamInfo.limit === this.outStreamInfo.written) { - this.state = states.START; - this.outStreamInfo.stream.end(packet, encoding, cb); - } else { - this.outStreamInfo.stream.write(packet, encoding, cb); - } - } else { - var packet = this.data; - this.data = new Buffer(""); - this.outStreamInfo.written += packet.length; - var outputStream = this.outStreamInfo.stream; - outputStream.write(packet, encoding, () => { - if (this.state === states.FILE_DATA_END) { - this.state = states.START; - return outputStream.end(cb); - } - cb(); - }); - } - return; - } - cb(); - }; - UnzipStream.prototype.drainAll = function() { - this._drainAllEntries = true; - }; - UnzipStream.prototype._transform = function(chunk, encoding, cb) { - var self2 = this; - if (self2.data.length > 0) { - self2.data = Buffer.concat([self2.data, chunk]); - } else { - self2.data = chunk; - } - var startDataLength = self2.data.length; - var done = function() { - if (self2.data.length > 0 && self2.data.length < startDataLength) { - startDataLength = self2.data.length; - self2._parseOrOutput(encoding, done); - return; - } - cb(); - }; - self2._parseOrOutput(encoding, done); - }; - UnzipStream.prototype._flush = function(cb) { - var self2 = this; - if (self2.data.length > 0) { - self2._parseOrOutput("buffer", function() { - if (self2.data.length > 0) - return setImmediate(function() { - self2._flush(cb); - }); - cb(); - }); - return; - } - if (self2.state === states.FILE_DATA) { - return cb(new Error("Stream finished in an invalid state, uncompression failed")); - } - setImmediate(cb); - }; - module2.exports = UnzipStream; - } -}); - -// node_modules/unzip-stream/lib/parser-stream.js -var require_parser_stream = __commonJS({ - "node_modules/unzip-stream/lib/parser-stream.js"(exports2, module2) { - var Transform2 = require("stream").Transform; - var util4 = require("util"); - var UnzipStream = require_unzip_stream(); - function ParserStream(opts) { - if (!(this instanceof ParserStream)) { - return new ParserStream(opts); - } - var transformOpts = opts || {}; - Transform2.call(this, { readableObjectMode: true }); - this.opts = opts || {}; - this.unzipStream = new UnzipStream(this.opts); - var self2 = this; - this.unzipStream.on("entry", function(entry) { - self2.push(entry); - }); - this.unzipStream.on("error", function(error) { - self2.emit("error", error); - }); - } - util4.inherits(ParserStream, Transform2); - ParserStream.prototype._transform = function(chunk, encoding, cb) { - this.unzipStream.write(chunk, encoding, cb); - }; - ParserStream.prototype._flush = function(cb) { - var self2 = this; - this.unzipStream.end(function() { - process.nextTick(function() { - self2.emit("close"); - }); - cb(); - }); - }; - ParserStream.prototype.on = function(eventName, fn) { - if (eventName === "entry") { - return Transform2.prototype.on.call(this, "data", fn); - } - return Transform2.prototype.on.call(this, eventName, fn); - }; - ParserStream.prototype.drainAll = function() { - this.unzipStream.drainAll(); - return this.pipe(new Transform2({ objectMode: true, transform: function(d, e, cb) { - cb(); - } })); - }; - module2.exports = ParserStream; - } -}); - -// node_modules/mkdirp/index.js -var require_mkdirp2 = __commonJS({ - "node_modules/mkdirp/index.js"(exports2, module2) { - var path36 = require("path"); - var fs27 = require("fs"); - var _0777 = parseInt("0777", 8); - module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - function mkdirP(p, opts, f, made) { - if (typeof opts === "function") { - f = opts; - opts = {}; - } else if (!opts || typeof opts !== "object") { - opts = { mode: opts }; - } - var mode = opts.mode; - var xfs = opts.fs || fs27; - if (mode === void 0) { - mode = _0777; - } - if (!made) - made = null; - var cb = f || function() { - }; - p = path36.resolve(p); - xfs.mkdir(p, mode, function(er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case "ENOENT": - if (path36.dirname(p) === p) - return cb(er); - mkdirP(path36.dirname(p), opts, function(er2, made2) { - if (er2) - cb(er2, made2); - else - mkdirP(p, opts, cb, made2); - }); - break; - default: - xfs.stat(p, function(er2, stat) { - if (er2 || !stat.isDirectory()) - cb(er, made); - else - cb(null, made); - }); - break; - } - }); - } - mkdirP.sync = function sync(p, opts, made) { - if (!opts || typeof opts !== "object") { - opts = { mode: opts }; - } - var mode = opts.mode; - var xfs = opts.fs || fs27; - if (mode === void 0) { - mode = _0777; - } - if (!made) - made = null; - p = path36.resolve(p); - try { - xfs.mkdirSync(p, mode); - made = made || p; - } catch (err0) { - switch (err0.code) { - case "ENOENT": - made = sync(path36.dirname(p), opts, made); - sync(p, opts, made); - break; - default: - var stat; - try { - stat = xfs.statSync(p); - } catch (err1) { - throw err0; - } - if (!stat.isDirectory()) - throw err0; - break; - } - } - return made; - }; - } -}); - -// node_modules/unzip-stream/lib/extract.js -var require_extract2 = __commonJS({ - "node_modules/unzip-stream/lib/extract.js"(exports2, module2) { - var fs27 = require("fs"); - var path36 = require("path"); - var util4 = require("util"); - var mkdirp = require_mkdirp2(); - var Transform2 = require("stream").Transform; - var UnzipStream = require_unzip_stream(); - function Extract(opts) { - if (!(this instanceof Extract)) - return new Extract(opts); - Transform2.call(this); - this.opts = opts || {}; - this.unzipStream = new UnzipStream(this.opts); - this.unfinishedEntries = 0; - this.afterFlushWait = false; - this.createdDirectories = {}; - var self2 = this; - this.unzipStream.on("entry", this._processEntry.bind(this)); - this.unzipStream.on("error", function(error) { - self2.emit("error", error); - }); - } - util4.inherits(Extract, Transform2); - Extract.prototype._transform = function(chunk, encoding, cb) { - this.unzipStream.write(chunk, encoding, cb); - }; - Extract.prototype._flush = function(cb) { - var self2 = this; - var allDone = function() { - process.nextTick(function() { - self2.emit("close"); - }); - cb(); - }; - this.unzipStream.end(function() { - if (self2.unfinishedEntries > 0) { - self2.afterFlushWait = true; - return self2.on("await-finished", allDone); - } - allDone(); - }); - }; - Extract.prototype._processEntry = function(entry) { - var self2 = this; - var destPath = path36.join(this.opts.path, entry.path); - var directory = entry.isDirectory ? destPath : path36.dirname(destPath); - this.unfinishedEntries++; - var writeFileFn = function() { - var pipedStream = fs27.createWriteStream(destPath); - pipedStream.on("close", function() { - self2.unfinishedEntries--; - self2._notifyAwaiter(); - }); - pipedStream.on("error", function(error) { - self2.emit("error", error); - }); - entry.pipe(pipedStream); - }; - if (this.createdDirectories[directory] || directory === ".") { - return writeFileFn(); - } - mkdirp(directory, function(err) { - if (err) - return self2.emit("error", err); - self2.createdDirectories[directory] = true; - if (entry.isDirectory) { - self2.unfinishedEntries--; - self2._notifyAwaiter(); - return; - } - writeFileFn(); - }); - }; - Extract.prototype._notifyAwaiter = function() { - if (this.afterFlushWait && this.unfinishedEntries === 0) { - this.emit("await-finished"); - this.afterFlushWait = false; - } - }; - module2.exports = Extract; - } -}); - -// node_modules/unzip-stream/unzip.js -var require_unzip = __commonJS({ - "node_modules/unzip-stream/unzip.js"(exports2) { - "use strict"; - exports2.Parse = require_parser_stream(); - exports2.Extract = require_extract2(); - } -}); - -// node_modules/@tootallnate/once/dist/index.js -var require_dist = __commonJS({ - "node_modules/@tootallnate/once/dist/index.js"(exports2, module2) { - "use strict"; - function noop() { - } - function once(emitter, name2) { - const o = once.spread(emitter, name2); - const r = o.then((args) => args[0]); - r.cancel = o.cancel; - return r; - } - (function(once2) { - function spread(emitter, name2) { - let c = null; - const p = new Promise((resolve3, reject) => { - function cancel() { - emitter.removeListener(name2, onEvent); - emitter.removeListener("error", onError); - p.cancel = noop; - } - function onEvent(...args) { - cancel(); - resolve3(args); - } - function onError(err) { - cancel(); - reject(err); - } - c = cancel; - emitter.on(name2, onEvent); - emitter.on("error", onError); - }); - if (!c) { - throw new TypeError("Could not get `cancel()` function"); - } - p.cancel = c; - return p; - } - once2.spread = spread; - })(once || (once = {})); - module2.exports = once; - } -}); - -// node_modules/agent-base/dist/src/promisify.js -var require_promisify = __commonJS({ - "node_modules/agent-base/dist/src/promisify.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function promisify(fn) { - return function(req, opts) { - return new Promise((resolve3, reject) => { - fn.call(this, req, opts, (err, rtn) => { - if (err) { - reject(err); - } else { - resolve3(rtn); - } - }); - }); - }; - } - exports2.default = promisify; - } -}); - -// node_modules/agent-base/dist/src/index.js -var require_src2 = __commonJS({ - "node_modules/agent-base/dist/src/index.js"(exports2, module2) { - "use strict"; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - var events_1 = require("events"); - var debug_1 = __importDefault(require_src()); - var promisify_1 = __importDefault(require_promisify()); - var debug = debug_1.default("agent-base"); - function isAgent(v) { - return Boolean(v) && typeof v.addRequest === "function"; - } - function isSecureEndpoint() { - const { stack } = new Error(); - if (typeof stack !== "string") - return false; - return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); - } - function createAgent(callback, opts) { - return new createAgent.Agent(callback, opts); - } - (function(createAgent2) { - class Agent extends events_1.EventEmitter { - constructor(callback, _opts) { - super(); - let opts = _opts; - if (typeof callback === "function") { - this.callback = callback; - } else if (callback) { - opts = callback; - } - this.timeout = null; - if (opts && typeof opts.timeout === "number") { - this.timeout = opts.timeout; - } - this.maxFreeSockets = 1; - this.maxSockets = 1; - this.maxTotalSockets = Infinity; - this.sockets = {}; - this.freeSockets = {}; - this.requests = {}; - this.options = {}; - } - get defaultPort() { - if (typeof this.explicitDefaultPort === "number") { - return this.explicitDefaultPort; - } - return isSecureEndpoint() ? 443 : 80; - } - set defaultPort(v) { - this.explicitDefaultPort = v; - } - get protocol() { - if (typeof this.explicitProtocol === "string") { - return this.explicitProtocol; - } - return isSecureEndpoint() ? "https:" : "http:"; - } - set protocol(v) { - this.explicitProtocol = v; - } - callback(req, opts, fn) { - throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); - } - addRequest(req, _opts) { - const opts = Object.assign({}, _opts); - if (typeof opts.secureEndpoint !== "boolean") { - opts.secureEndpoint = isSecureEndpoint(); - } - if (opts.host == null) { - opts.host = "localhost"; - } - if (opts.port == null) { - opts.port = opts.secureEndpoint ? 443 : 80; - } - if (opts.protocol == null) { - opts.protocol = opts.secureEndpoint ? "https:" : "http:"; - } - if (opts.host && opts.path) { - delete opts.path; - } - delete opts.agent; - delete opts.hostname; - delete opts._defaultAgent; - delete opts.defaultPort; - delete opts.createConnection; - req._last = true; - req.shouldKeepAlive = false; - let timedOut = false; - let timeoutId = null; - const timeoutMs = opts.timeout || this.timeout; - const onerror = (err) => { - if (req._hadError) - return; - req.emit("error", err); - req._hadError = true; - }; - const ontimeout = () => { - timeoutId = null; - timedOut = true; - const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); - err.code = "ETIMEOUT"; - onerror(err); - }; - const callbackError = (err) => { - if (timedOut) - return; - if (timeoutId !== null) { - clearTimeout(timeoutId); - timeoutId = null; - } - onerror(err); - }; - const onsocket = (socket) => { - if (timedOut) - return; - if (timeoutId != null) { - clearTimeout(timeoutId); - timeoutId = null; - } - if (isAgent(socket)) { - debug("Callback returned another Agent instance %o", socket.constructor.name); - socket.addRequest(req, opts); - return; - } - if (socket) { - socket.once("free", () => { - this.freeSocket(socket, opts); - }); - req.onSocket(socket); - return; - } - const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); - onerror(err); - }; - if (typeof this.callback !== "function") { - onerror(new Error("`callback` is not defined")); - return; - } - if (!this.promisifiedCallback) { - if (this.callback.length >= 3) { - debug("Converting legacy callback function to promise"); - this.promisifiedCallback = promisify_1.default(this.callback); - } else { - this.promisifiedCallback = this.callback; - } - } - if (typeof timeoutMs === "number" && timeoutMs > 0) { - timeoutId = setTimeout(ontimeout, timeoutMs); - } - if ("port" in opts && typeof opts.port !== "number") { - opts.port = Number(opts.port); - } - try { - debug("Resolving socket for %o request: %o", opts.protocol, `${req.method} ${req.path}`); - Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); - } catch (err) { - Promise.reject(err).catch(callbackError); - } - } - freeSocket(socket, opts) { - debug("Freeing socket %o %o", socket.constructor.name, opts); - socket.destroy(); - } - destroy() { - debug("Destroying agent %o", this.constructor.name); - } - } - createAgent2.Agent = Agent; - createAgent2.prototype = createAgent2.Agent.prototype; - })(createAgent || (createAgent = {})); - module2.exports = createAgent; - } -}); - -// node_modules/http-proxy-agent/dist/agent.js -var require_agent = __commonJS({ - "node_modules/http-proxy-agent/dist/agent.js"(exports2) { - "use strict"; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve3) { - resolve3(value); - }); - } - return new (P || (P = Promise))(function(resolve3, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve3(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - var net_1 = __importDefault(require("net")); - var tls_1 = __importDefault(require("tls")); - var url_1 = __importDefault(require("url")); - var debug_1 = __importDefault(require_src()); - var once_1 = __importDefault(require_dist()); - var agent_base_1 = require_src2(); - var debug = debug_1.default("http-proxy-agent"); - function isHTTPS(protocol) { - return typeof protocol === "string" ? /^https:?$/i.test(protocol) : false; - } - var HttpProxyAgent2 = class extends agent_base_1.Agent { - constructor(_opts) { - let opts; - if (typeof _opts === "string") { - opts = url_1.default.parse(_opts); - } else { - opts = _opts; - } - if (!opts) { - throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!"); - } - debug("Creating new HttpProxyAgent instance: %o", opts); - super(opts); - const proxy = Object.assign({}, opts); - this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); - proxy.host = proxy.hostname || proxy.host; - if (typeof proxy.port === "string") { - proxy.port = parseInt(proxy.port, 10); - } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; - } - if (proxy.host && proxy.path) { - delete proxy.path; - delete proxy.pathname; - } - this.proxy = proxy; - } - callback(req, opts) { - return __awaiter(this, void 0, void 0, function* () { - const { proxy, secureProxy } = this; - const parsed = url_1.default.parse(req.path); - if (!parsed.protocol) { - parsed.protocol = "http:"; - } - if (!parsed.hostname) { - parsed.hostname = opts.hostname || opts.host || null; - } - if (parsed.port == null && typeof opts.port) { - parsed.port = String(opts.port); - } - if (parsed.port === "80") { - delete parsed.port; - } - req.path = url_1.default.format(parsed); - if (proxy.auth) { - req.setHeader("Proxy-Authorization", `Basic ${Buffer.from(proxy.auth).toString("base64")}`); - } - let socket; - if (secureProxy) { - debug("Creating `tls.Socket`: %o", proxy); - socket = tls_1.default.connect(proxy); - } else { - debug("Creating `net.Socket`: %o", proxy); - socket = net_1.default.connect(proxy); - } - if (req._header) { - let first; - let endOfHeaders; - debug("Regenerating stored HTTP header string for request"); - req._header = null; - req._implicitHeader(); - if (req.output && req.output.length > 0) { - debug("Patching connection write() output buffer with updated header"); - first = req.output[0]; - endOfHeaders = first.indexOf("\r\n\r\n") + 4; - req.output[0] = req._header + first.substring(endOfHeaders); - debug("Output buffer: %o", req.output); - } else if (req.outputData && req.outputData.length > 0) { - debug("Patching connection write() output buffer with updated header"); - first = req.outputData[0].data; - endOfHeaders = first.indexOf("\r\n\r\n") + 4; - req.outputData[0].data = req._header + first.substring(endOfHeaders); - debug("Output buffer: %o", req.outputData[0].data); - } - } - yield once_1.default(socket, "connect"); - return socket; - }); - } - }; - exports2.default = HttpProxyAgent2; - } -}); - -// node_modules/http-proxy-agent/dist/index.js -var require_dist2 = __commonJS({ - "node_modules/http-proxy-agent/dist/index.js"(exports2, module2) { - "use strict"; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - var agent_1 = __importDefault(require_agent()); - function createHttpProxyAgent2(opts) { - return new agent_1.default(opts); - } - (function(createHttpProxyAgent3) { - createHttpProxyAgent3.HttpProxyAgent = agent_1.default; - createHttpProxyAgent3.prototype = agent_1.default.prototype; - })(createHttpProxyAgent2 || (createHttpProxyAgent2 = {})); - module2.exports = createHttpProxyAgent2; - } -}); - -// node_modules/https-proxy-agent/dist/parse-proxy-response.js -var require_parse_proxy_response = __commonJS({ - "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { - "use strict"; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - var debug_1 = __importDefault(require_src()); - var debug = debug_1.default("https-proxy-agent:parse-proxy-response"); - function parseProxyResponse(socket) { - return new Promise((resolve3, reject) => { - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once("readable", read); - } - function cleanup() { - socket.removeListener("end", onend); - socket.removeListener("error", onerror); - socket.removeListener("close", onclose); - socket.removeListener("readable", read); - } - function onclose(err) { - debug("onclose had error %o", err); - } - function onend() { - debug("onend"); - } - function onerror(err) { - cleanup(); - debug("onerror %o", err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf("\r\n\r\n"); - if (endOfHeaders === -1) { - debug("have not received end of HTTP headers yet..."); - read(); - return; - } - const firstLine = buffered.toString("ascii", 0, buffered.indexOf("\r\n")); - const statusCode = +firstLine.split(" ")[1]; - debug("got proxy server response: %o", firstLine); - resolve3({ - statusCode, - buffered - }); - } - socket.on("error", onerror); - socket.on("close", onclose); - socket.on("end", onend); - read(); - }); - } - exports2.default = parseProxyResponse; - } -}); - -// node_modules/https-proxy-agent/dist/agent.js -var require_agent2 = __commonJS({ - "node_modules/https-proxy-agent/dist/agent.js"(exports2) { - "use strict"; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve3) { - resolve3(value); - }); - } - return new (P || (P = Promise))(function(resolve3, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve3(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - var net_1 = __importDefault(require("net")); - var tls_1 = __importDefault(require("tls")); - var url_1 = __importDefault(require("url")); - var assert_1 = __importDefault(require("assert")); - var debug_1 = __importDefault(require_src()); - var agent_base_1 = require_src2(); - var parse_proxy_response_1 = __importDefault(require_parse_proxy_response()); - var debug = debug_1.default("https-proxy-agent:agent"); - var HttpsProxyAgent2 = class extends agent_base_1.Agent { - constructor(_opts) { - let opts; - if (typeof _opts === "string") { - opts = url_1.default.parse(_opts); - } else { - opts = _opts; - } - if (!opts) { - throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!"); - } - debug("creating new HttpsProxyAgent instance: %o", opts); - super(opts); - const proxy = Object.assign({}, opts); - this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); - proxy.host = proxy.hostname || proxy.host; - if (typeof proxy.port === "string") { - proxy.port = parseInt(proxy.port, 10); - } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; - } - if (this.secureProxy && !("ALPNProtocols" in proxy)) { - proxy.ALPNProtocols = ["http 1.1"]; - } - if (proxy.host && proxy.path) { - delete proxy.path; - delete proxy.pathname; - } - this.proxy = proxy; - } - callback(req, opts) { - return __awaiter(this, void 0, void 0, function* () { - const { proxy, secureProxy } = this; - let socket; - if (secureProxy) { - debug("Creating `tls.Socket`: %o", proxy); - socket = tls_1.default.connect(proxy); - } else { - debug("Creating `net.Socket`: %o", proxy); - socket = net_1.default.connect(proxy); - } - const headers = Object.assign({}, proxy.headers); - const hostname = `${opts.host}:${opts.port}`; - let payload = `CONNECT ${hostname} HTTP/1.1\r -`; - if (proxy.auth) { - headers["Proxy-Authorization"] = `Basic ${Buffer.from(proxy.auth).toString("base64")}`; - } - let { host, port, secureEndpoint } = opts; - if (!isDefaultPort(port, secureEndpoint)) { - host += `:${port}`; - } - headers.Host = host; - headers.Connection = "close"; - for (const name2 of Object.keys(headers)) { - payload += `${name2}: ${headers[name2]}\r -`; - } - const proxyResponsePromise = parse_proxy_response_1.default(socket); - socket.write(`${payload}\r -`); - const { statusCode, buffered } = yield proxyResponsePromise; - if (statusCode === 200) { - req.once("socket", resume); - if (opts.secureEndpoint) { - const servername = opts.servername || opts.host; - if (!servername) { - throw new Error('Could not determine "servername"'); - } - debug("Upgrading socket connection to TLS"); - return tls_1.default.connect(Object.assign(Object.assign({}, omit2(opts, "host", "hostname", "path", "port")), { - socket, - servername - })); - } - return socket; - } - socket.destroy(); - const fakeSocket = new net_1.default.Socket(); - fakeSocket.readable = true; - req.once("socket", (s) => { - debug("replaying proxy buffer for failed request"); - assert_1.default(s.listenerCount("data") > 0); - s.push(buffered); - s.push(null); - }); - return fakeSocket; - }); - } - }; - exports2.default = HttpsProxyAgent2; - function resume(socket) { - socket.resume(); - } - function isDefaultPort(port, secure) { - return Boolean(!secure && port === 80 || secure && port === 443); - } - function isHTTPS(protocol) { - return typeof protocol === "string" ? /^https:?$/i.test(protocol) : false; - } - function omit2(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - } -}); - -// node_modules/https-proxy-agent/dist/index.js -var require_dist3 = __commonJS({ - "node_modules/https-proxy-agent/dist/index.js"(exports2, module2) { - "use strict"; - var __importDefault = exports2 && exports2.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - var agent_1 = __importDefault(require_agent2()); - function createHttpsProxyAgent2(opts) { - return new agent_1.default(opts); - } - (function(createHttpsProxyAgent3) { - createHttpsProxyAgent3.HttpsProxyAgent = agent_1.default; - createHttpsProxyAgent3.prototype = agent_1.default.prototype; - })(createHttpsProxyAgent2 || (createHttpsProxyAgent2 = {})); - module2.exports = createHttpsProxyAgent2; - } -}); - -// node_modules/mimic-response/index.js -var require_mimic_response = __commonJS({ - "node_modules/mimic-response/index.js"(exports2, module2) { - "use strict"; - var knownProperties = [ - "aborted", - "complete", - "headers", - "httpVersion", - "httpVersionMinor", - "httpVersionMajor", - "method", - "rawHeaders", - "rawTrailers", - "setTimeout", - "socket", - "statusCode", - "statusMessage", - "trailers", - "url" - ]; - module2.exports = (fromStream, toStream) => { - if (toStream._readableState.autoDestroy) { - throw new Error("The second stream must have the `autoDestroy` option set to `false`"); - } - const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties)); - const properties = {}; - for (const property of fromProperties) { - if (property in toStream) { - continue; - } - properties[property] = { - get() { - const value = fromStream[property]; - const isFunction = typeof value === "function"; - return isFunction ? value.bind(fromStream) : value; - }, - set(value) { - fromStream[property] = value; - }, - enumerable: true, - configurable: false - }; - } - Object.defineProperties(toStream, properties); - fromStream.once("aborted", () => { - toStream.destroy(); - toStream.emit("aborted"); - }); - fromStream.once("close", () => { - if (fromStream.complete) { - if (toStream.readable) { - toStream.once("end", () => { - toStream.emit("close"); - }); - } else { - toStream.emit("close"); - } - } else { - toStream.emit("close"); - } - }); - return toStream; - }; - } -}); - -// node_modules/decompress-response/index.js -var require_decompress_response = __commonJS({ - "node_modules/decompress-response/index.js"(exports2, module2) { - "use strict"; - var { Transform: Transform2, PassThrough } = require("stream"); - var zlib = require("zlib"); - var mimicResponse = require_mimic_response(); - module2.exports = (response) => { - const contentEncoding = (response.headers["content-encoding"] || "").toLowerCase(); - if (!["gzip", "deflate", "br"].includes(contentEncoding)) { - return response; - } - const isBrotli = contentEncoding === "br"; - if (isBrotli && typeof zlib.createBrotliDecompress !== "function") { - response.destroy(new Error("Brotli is not supported on Node.js < 12")); - return response; - } - let isEmpty2 = true; - const checker = new Transform2({ - transform(data, _encoding, callback) { - isEmpty2 = false; - callback(null, data); - }, - flush(callback) { - callback(); - } - }); - const finalStream = new PassThrough({ - autoDestroy: false, - destroy(error, callback) { - response.destroy(); - callback(error); - } - }); - const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); - decompressStream.once("error", (error) => { - if (isEmpty2 && !response.readable) { - finalStream.end(); - return; - } - finalStream.destroy(error); - }); - mimicResponse(response, finalStream); - response.pipe(checker).pipe(decompressStream).pipe(finalStream); - return finalStream; - }; - } -}); - -// src/model/fetch.ts -function getSystemProxyURI(endpoint) { - let env; - if (endpoint.protocol === "http:") { - env = process.env.HTTP_PROXY || process.env.http_proxy || null; - } else if (endpoint.protocol === "https:") { - env = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null; - } - let noProxy = process.env.NO_PROXY || process.env.no_proxy; - if (noProxy === "*") { - env = null; - } else if (noProxy) { - const hostname = endpoint.hostname.replace(/^\.*/, ".").toLowerCase(); - const port = endpoint.port || endpoint.protocol.startsWith("https") ? "443" : "80"; - const noProxyList = noProxy.split(","); - for (let i = 0, len = noProxyList.length; i < len; i++) { - let noProxyItem = noProxyList[i].trim().toLowerCase(); - if (noProxyItem.includes(":")) { - let noProxyItemParts = noProxyItem.split(":", 2); - let noProxyHost = noProxyItemParts[0].replace(/^\.*/, "."); - let noProxyPort = noProxyItemParts[1]; - if (port === noProxyPort && hostname.endsWith(noProxyHost)) { - env = null; - break; - } - } else { - noProxyItem = noProxyItem.replace(/^\.*/, "."); - if (hostname.endsWith(noProxyItem)) { - env = null; - break; - } - } - } - } - return env; -} -function getAgent(endpoint, options) { - let proxy = options.proxyUrl || getSystemProxyURI(endpoint); - if (proxy) { - const proxyEndpoint = (0, import_url.parse)(proxy); - if (!/^https?:$/.test(proxyEndpoint.protocol)) { - return null; - } - let opts = { - host: proxyEndpoint.hostname, - port: proxyEndpoint.port ? Number(proxyEndpoint.port) : proxyEndpoint.protocol === "https" ? "443" : "80", - auth: proxyEndpoint.auth, - rejectUnauthorized: typeof options.strictSSL === "boolean" ? options.strictSSL : true - }; - logger33.info(`Using proxy ${proxy} from ${options.proxyUrl ? "configuration" : "system environment"} for ${endpoint.hostname}:`); - return endpoint.protocol === "http:" ? (0, import_http_proxy_agent.default)(opts) : (0, import_https_proxy_agent.default)(opts); - } - return null; -} -function resolveRequestOptions(url, options = {}) { - let config = workspace_default.getConfiguration("http"); - let { data } = options; - let dataType = getDataType(data); - let proxyOptions = { - proxyUrl: config.get("proxy", ""), - strictSSL: config.get("proxyStrictSSL", true), - proxyAuthorization: config.get("proxyAuthorization", null), - proxyCA: config.get("proxyCA", null) - }; - if (options.query && !url.includes("?")) { - url = `${url}?${(0, import_querystring.stringify)(options.query)}`; - } - let headers = Object.assign(options.headers || {}, { "Proxy-Authorization": proxyOptions.proxyAuthorization }); - let endpoint = (0, import_url.parse)(url); - let agent = getAgent(endpoint, proxyOptions); - let opts = { - method: options.method || "GET", - hostname: endpoint.hostname, - port: endpoint.port ? parseInt(endpoint.port, 10) : endpoint.protocol === "https:" ? 443 : 80, - path: endpoint.path, - agent, - rejectUnauthorized: proxyOptions.strictSSL, - maxRedirects: 3, - headers: Object.assign({ - "User-Agent": "Mozilla/5.0 (X11; Linux x86_64)", - "Accept-Encoding": "gzip, deflate" - }, headers) - }; - if (proxyOptions.proxyCA) { - opts.ca = import_fs11.default.readFileSync(proxyOptions.proxyCA); - } - if (dataType == "object") { - opts.headers["Content-Type"] = "application/json"; - } else if (dataType == "string") { - opts.headers["Content-Type"] = "text/plain"; - } - if (options.user && options.password) { - opts.auth = options.user + ":" + options.password; - } - if (options.timeout) { - opts.timeout = options.timeout; - } - if (options.buffer) - opts.buffer = true; - return opts; -} -function request(url, data, opts, token) { - let mod = url.startsWith("https:") ? import_follow_redirects.https : import_follow_redirects.http; - return new Promise((resolve3, reject) => { - if (token) { - let disposable = token.onCancellationRequested(() => { - disposable.dispose(); - req.destroy(new Error("request aborted")); - }); - } - const req = mod.request(opts, (res) => { - let readable = res; - if (res.statusCode >= 200 && res.statusCode < 300 || res.statusCode === 1223) { - let headers = res.headers || {}; - let chunks = []; - let contentType = headers["content-type"] || ""; - readable = (0, import_decompress_response.default)(res); - readable.on("data", (chunk) => { - chunks.push(chunk); - }); - readable.on("end", () => { - let buf = Buffer.concat(chunks); - if (!opts.buffer && (contentType.startsWith("application/json") || contentType.startsWith("text/"))) { - let ms = contentType.match(/charset=(\S+)/); - let encoding = ms ? ms[1] : "utf8"; - let rawData = buf.toString(encoding); - if (!contentType.includes("application/json")) { - resolve3(rawData); - } else { - try { - const parsedData = JSON.parse(rawData); - resolve3(parsedData); - } catch (e) { - reject(new Error(`Parse response error: ${e}`)); - } - } - } else { - resolve3(buf); - } - }); - readable.on("error", (err) => { - reject(new Error(`Unable to connect ${url}: ${err.message}`)); - }); - } else { - reject(new Error(`Bad response from ${url}: ${res.statusCode}`)); - } - }); - req.on("error", reject); - req.on("timeout", () => { - req.destroy(new Error(`Request timeout after ${opts.timeout}ms`)); - }); - if (data) { - if (typeof data === "string" || Buffer.isBuffer(data)) { - req.write(data); - } else { - req.write(JSON.stringify(data)); - } - } - if (opts.timeout) { - req.setTimeout(opts.timeout); - } - req.end(); - }); -} -function getDataType(data) { - if (data === null) - return "null"; - if (data === void 0) - return "undefined"; - if (typeof data == "string") - return "string"; - if (Buffer.isBuffer(data)) - return "buffer"; - if (Array.isArray(data) || objectLiteral(data)) - return "object"; - return "unknown"; -} -function fetch(url, options = {}, token) { - let opts = resolveRequestOptions(url, options); - return request(url, options.data, opts, token).catch((err) => { - logger33.error(`Fetch error for ${url}:`, opts, err); - if (opts.agent && opts.agent.proxy) { - let { proxy } = opts.agent; - throw new Error(`Request failed using proxy ${proxy.host}: ${err.message}`); - } else { - throw err; - } - }); -} -var import_follow_redirects, import_url, import_fs11, import_querystring, import_http_proxy_agent, import_https_proxy_agent, import_decompress_response, logger33; -var init_fetch = __esm({ - "src/model/fetch.ts"() { - import_follow_redirects = __toModule(require_follow_redirects()); - import_url = __toModule(require("url")); - import_fs11 = __toModule(require("fs")); - init_is(); - init_workspace(); - import_querystring = __toModule(require("querystring")); - import_http_proxy_agent = __toModule(require_dist2()); - import_https_proxy_agent = __toModule(require_dist3()); - import_decompress_response = __toModule(require_decompress_response()); - logger33 = require_logger2()("model-fetch"); - } -}); - -// src/model/download.ts -function download(url, options, token) { - let { dest, onProgress, extract } = options; - if (!dest || !import_path14.default.isAbsolute(dest)) { - throw new Error(`Expect absolute file path for dest option.`); - } - let stat; - try { - stat = import_fs_extra5.default.statSync(dest); - } catch (_e) { - import_fs_extra5.default.mkdirpSync(dest); - } - if (stat && !stat.isDirectory()) { - throw new Error(`${dest} exists, but not directory!`); - } - let mod = url.startsWith("https") ? import_follow_redirects2.https : import_follow_redirects2.http; - let opts = resolveRequestOptions(url, options); - let extname = import_path14.default.extname(url); - return new Promise((resolve3, reject) => { - if (token) { - let disposable = token.onCancellationRequested(() => { - disposable.dispose(); - req.destroy(new Error("request aborted")); - }); - } - const req = mod.request(opts, (res) => { - var _a2, _b; - if (res.statusCode >= 200 && res.statusCode < 300 || res.statusCode === 1223) { - let headers = res.headers || {}; - let dispositionHeader = headers["content-disposition"]; - if (!extname && dispositionHeader) { - let disposition = import_content_disposition.default.parse(dispositionHeader); - if ((_a2 = disposition.parameters) == null ? void 0 : _a2.filename) { - extname = import_path14.default.extname(disposition.parameters.filename); - } - } - if (extract === true) { - if (extname === ".zip" || headers["content-type"] == "application/zip") { - extract = "unzip"; - } else if (extname == ".tgz") { - extract = "untar"; - } else { - reject(new Error(`Unable to extract for ${url}`)); - return; - } - } - let total = Number(headers["content-length"]); - let cur = 0; - if (!isNaN(total)) { - res.on("data", (chunk) => { - cur += chunk.length; - let percent = (cur / total * 100).toFixed(1); - if (onProgress) { - onProgress(percent); - } else { - logger34.info(`Download ${url} progress ${percent}%`); - } - }); - } - res.on("error", (err) => { - reject(new Error(`Unable to connect ${url}: ${err.message}`)); - }); - res.on("end", () => { - logger34.info("Download completed:", url); - }); - let stream; - if (extract === "untar") { - stream = res.pipe(import_tar.default.x({ strip: (_b = options.strip) != null ? _b : 1, C: dest })); - } else if (extract === "unzip") { - stream = res.pipe(import_unzip_stream.default.Extract({ path: dest })); - } else { - dest = import_path14.default.join(dest, `${v1_default()}${extname}`); - stream = res.pipe(import_fs_extra5.default.createWriteStream(dest)); - } - stream.on("finish", () => { - logger34.info(`Downloaded ${url} => ${dest}`); - setTimeout(() => { - resolve3(dest); - }, 100); - }); - stream.on("error", reject); - } else { - reject(new Error(`Invalid response from ${url}: ${res.statusCode}`)); - } - }); - req.on("error", reject); - req.on("timeout", () => { - req.destroy(new Error(`request timeout after ${options.timeout}ms`)); - }); - if (options.timeout) { - req.setTimeout(options.timeout); - } - req.end(); - }); -} -var import_content_disposition, import_follow_redirects2, import_fs_extra5, import_path14, import_tar, import_unzip_stream, logger34; -var init_download = __esm({ - "src/model/download.ts"() { - import_content_disposition = __toModule(require_content_disposition()); - import_follow_redirects2 = __toModule(require_follow_redirects()); - import_fs_extra5 = __toModule(require_lib5()); - import_path14 = __toModule(require("path")); - import_tar = __toModule(require_tar()); - import_unzip_stream = __toModule(require_unzip()); - init_esm_node(); - init_fetch(); - logger34 = require_logger2()("model-download"); - } -}); - -// src/model/installer.ts -function registryUrl(scope = "coc.nvim") { - const result = (0, import_rc.default)("npm", { registry: "https://registry.npmjs.org/" }); - const registry = result[`${scope}:registry`] || result.config_registry || result.registry; - return registry.endsWith("/") ? registry : registry + "/"; -} -function createInstallerFactory(npm, root) { - return (def) => new Installer(root, npm, def); -} -var import_events17, import_child_process3, import_readline2, import_fs_extra6, import_os6, import_path15, import_rc, import_semver, logger35, Installer; -var init_installer = __esm({ - "src/model/installer.ts"() { - import_events17 = __toModule(require("events")); - import_child_process3 = __toModule(require("child_process")); - init_main3(); - import_readline2 = __toModule(require("readline")); - import_fs_extra6 = __toModule(require_lib5()); - import_os6 = __toModule(require("os")); - import_path15 = __toModule(require("path")); - import_rc = __toModule(require_rc()); - import_semver = __toModule(require_semver2()); - init_workspace(); - init_download(); - init_fetch(); - init_fs(); - logger35 = require_logger2()("model-installer"); - Installer = class extends import_events17.EventEmitter { - constructor(root, npm, def) { - super(); - this.root = root; - this.npm = npm; - this.def = def; - if (!import_fs_extra6.default.existsSync(root)) - import_fs_extra6.default.mkdirpSync(root); - if (/^https?:/.test(def)) { - this.url = def; - } else { - if (def.startsWith("@")) { - const idx = def.indexOf("@", 1); - if (idx > 1) { - this.name = def.substring(0, idx); - this.version = def.substring(idx + 1); - } else { - this.name = def; - } - } else { - if (def.includes("@")) { - let [name2, version2] = def.split("@", 2); - this.name = name2; - this.version = version2; - } else { - this.name = def; - } - } - } - } - get info() { - return { name: this.name, version: this.version }; - } - async install() { - this.log(`Using npm from: ${this.npm}`); - let info = await this.getInfo(); - logger35.info(`Fetched info of ${this.def}`, info); - let { name: name2 } = info; - let required = info["engines.coc"] ? info["engines.coc"].replace(/^\^/, ">=") : ""; - if (required && !import_semver.default.satisfies(workspace_default.version, required)) { - throw new Error(`${name2} ${info.version} requires coc.nvim >= ${required}, please update coc.nvim.`); - } - await this.doInstall(info); - return name2; - } - async update(url) { - this.url = url; - let folder = import_path15.default.join(this.root, this.name); - let stat = await import_fs_extra6.default.lstat(folder); - if (stat.isSymbolicLink()) { - this.log(`Skipped update for symbol link`); - return; - } - let version2; - if (import_fs_extra6.default.existsSync(import_path15.default.join(folder, "package.json"))) { - let content = await import_fs_extra6.default.readFile(import_path15.default.join(folder, "package.json"), "utf8"); - version2 = JSON.parse(content).version; - } - this.log(`Using npm from: ${this.npm}`); - let info = await this.getInfo(); - if (version2 && info.version && import_semver.default.gte(version2, info.version)) { - this.log(`Current version ${version2} is up to date.`); - return; - } - let required = info["engines.coc"] ? info["engines.coc"].replace(/^\^/, ">=") : ""; - if (required && !import_semver.default.satisfies(workspace_default.version, required)) { - throw new Error(`${info.version} requires coc.nvim ${required}, please update coc.nvim.`); - } - await this.doInstall(info); - let jsonFile = import_path15.default.join(this.root, info.name, "package.json"); - if (import_fs_extra6.default.existsSync(jsonFile)) { - this.log(`Updated to v${info.version}`); - return import_path15.default.dirname(jsonFile); - } else { - throw new Error(`Package.json not found: ${jsonFile}`); - } - } - async doInstall(info) { - let folder = import_path15.default.join(this.root, info.name); - if (import_fs_extra6.default.existsSync(folder)) { - let stat2 = import_fs_extra6.default.statSync(folder); - if (!stat2.isDirectory()) { - this.log(`${folder} is not directory skipped install`); - return; - } - } - let tmpFolder = await import_fs_extra6.default.mkdtemp(import_path15.default.join(import_os6.default.tmpdir(), `${info.name.replace("/", "-")}-`)); - let url = info["dist.tarball"]; - this.log(`Downloading from ${url}`); - await download(url, { dest: tmpFolder, onProgress: (p) => this.log(`Download progress ${p}%`, true), extract: "untar" }); - this.log(`Extension download at ${tmpFolder}`); - let content = await import_fs_extra6.default.readFile(import_path15.default.join(tmpFolder, "package.json"), "utf8"); - let { dependencies } = JSON.parse(content); - if (dependencies && Object.keys(dependencies).length) { - let p = new Promise((resolve3, reject) => { - let args = ["install", "--ignore-scripts", "--no-lockfile", "--production", "--no-global"]; - if (url.startsWith("https://github.com")) { - args = ["install"]; - } - if ((this.npm.endsWith("npm") || this.npm.endsWith("npm.CMD")) && !this.npm.endsWith("pnpm")) { - args.push("--legacy-peer-deps"); - } - if (this.npm.endsWith("yarn")) { - args.push("--ignore-engines"); - } - this.log(`Installing dependencies by: ${this.npm} ${args.join(" ")}.`); - const child = (0, import_child_process3.spawn)(this.npm, args, { - cwd: tmpFolder - }); - const rl = import_readline2.default.createInterface({ - input: child.stdout - }); - rl.on("line", (line) => { - this.log(`[npm] ${line}`, true); - }); - child.stderr.setEncoding("utf8"); - child.stdout.setEncoding("utf8"); - child.on("error", reject); - let err = ""; - child.stderr.on("data", (data) => { - err += data; - }); - child.on("exit", (code) => { - if (code) { - if (err) - this.log(err); - reject(new Error(`${this.npm} install exited with ${code}`)); - return; - } - resolve3(); - }); - }); - await p; - } - let jsonFile = import_path15.default.resolve(this.root, global.hasOwnProperty("__TEST__") ? "" : "..", "package.json"); - let errors = []; - let obj = parse3(import_fs_extra6.default.readFileSync(jsonFile, "utf8"), errors, { allowTrailingComma: true }); - if (errors && errors.length > 0) { - throw new Error(`Error on load ${jsonFile}`); - } - obj.dependencies = obj.dependencies || {}; - if (this.url) { - obj.dependencies[info.name] = this.url; - } else { - obj.dependencies[info.name] = ">=" + info.version; - } - const sortedObj = { dependencies: {} }; - Object.keys(obj.dependencies).sort().forEach((k) => { - sortedObj.dependencies[k] = obj.dependencies[k]; - }); - let stat = await statAsync(folder); - if (stat) { - if (stat.isDirectory()) { - import_fs_extra6.default.removeSync(folder); - } else { - import_fs_extra6.default.unlinkSync(folder); - } - } - await import_fs_extra6.default.move(tmpFolder, folder, { overwrite: true }); - await import_fs_extra6.default.writeFile(jsonFile, JSON.stringify(sortedObj, null, 2), { encoding: "utf8" }); - this.log(`Update package.json at ${jsonFile}`); - this.log(`Installed extension ${this.name}@${info.version} at ${folder}`); - } - async getInfo() { - if (this.url) - return await this.getInfoFromUri(); - let registry = registryUrl(); - this.log(`Get info from ${registry}`); - let buffer = await fetch(registry + this.name, { timeout: 1e4, buffer: true }); - let res = JSON.parse(buffer.toString()); - if (!this.version) - this.version = res["dist-tags"]["latest"]; - let obj = res["versions"][this.version]; - if (!obj) - throw new Error(`${this.def} doesn't exists in ${registry}.`); - let requiredVersion = obj["engines"] && obj["engines"]["coc"]; - if (!requiredVersion) { - throw new Error(`${this.def} is not valid coc extension, "engines" field with coc property required.`); - } - return { - "dist.tarball": obj["dist"]["tarball"], - "engines.coc": requiredVersion, - version: obj["version"], - name: res.name - }; - } - async getInfoFromUri() { - let { url } = this; - if (!url.includes("github.com")) { - throw new Error(`"${url}" is not supported, coc.nvim support github.com only`); - } - url = url.replace(/\/$/, ""); - let branch = "master"; - if (url.includes("@")) { - let idx = url.indexOf("@"); - branch = url.substr(idx + 1); - url = url.substring(0, idx); - } - let fileUrl = url.replace("github.com", "raw.githubusercontent.com") + `/${branch}/package.json`; - this.log(`Get info from ${fileUrl}`); - let content = await fetch(fileUrl, { timeout: 1e4 }); - let obj = typeof content == "string" ? JSON.parse(content) : content; - this.name = obj.name; - return { - "dist.tarball": `${url}/archive/${branch}.tar.gz`, - "engines.coc": obj["engines"] ? obj["engines"]["coc"] : null, - name: obj.name, - version: obj.version - }; - } - log(msg, isProgress = false) { - logger35.info(msg); - this.emit("message", msg, isProgress); - } - }; - } -}); - -// src/model/memos.ts -var import_fs13, logger36, Memos; -var init_memos = __esm({ - "src/model/memos.ts"() { - import_fs13 = __toModule(require("fs")); - init_object(); - logger36 = require_logger2()("model-memos"); - Memos = class { - constructor(filepath) { - this.filepath = filepath; - if (!import_fs13.default.existsSync(filepath)) { - import_fs13.default.writeFileSync(filepath, "{}", "utf8"); - } - } - fetchContent(id, key) { - try { - let content = import_fs13.default.readFileSync(this.filepath, "utf8"); - let res = JSON.parse(content); - let obj = res[id]; - if (!obj) - return void 0; - return obj[key]; - } catch (e) { - return void 0; - } - } - async update(id, key, value) { - let { filepath } = this; - try { - let content = import_fs13.default.readFileSync(filepath, "utf8"); - let current = content ? JSON.parse(content) : {}; - current[id] = current[id] || {}; - if (value !== void 0) { - current[id][key] = deepClone(value); - } else { - delete current[id][key]; - } - content = JSON.stringify(current, null, 2); - import_fs13.default.writeFileSync(filepath, content, "utf8"); - } catch (e) { - logger36.error(`Error on update memos:`, e); - } - } - createMemento(id) { - return { - get: (key, defaultValue) => { - let res = this.fetchContent(id, key); - return res === void 0 ? defaultValue : res; - }, - update: async (key, value) => { - await this.update(id, key, value); - } - }; - } - }; - } -}); - -// src/util/lodash.ts -function defaults(obj, ...sources) { - obj = Object(obj); - sources.forEach((source) => { - if (source != null) { - source = Object(source); - for (const key in source) { - const value = obj[key]; - if (value === void 0 || value === objectProto[key] && !hasOwnProperty2.call(obj, key)) { - obj[key] = source[key]; - } - } - } - }); - return obj; -} -function omit(obj, properties) { - let o = {}; - for (let key of Object.keys(obj)) { - if (!properties.includes(key)) { - o[key] = obj[key]; - } - } - return o; -} -var objectProto, hasOwnProperty2; -var init_lodash = __esm({ - "src/util/lodash.ts"() { - objectProto = Object.prototype; - hasOwnProperty2 = objectProto.hasOwnProperty; - } -}); - -// src/provider/manager.ts -function addLocation(arr, location) { - let { range, uri } = location; - if (arr.find((o) => o.uri == uri && equals(o.range, range)) != null) - return; - arr.push(location); -} -var import_vscode_languageserver_protocol21, logger37, Manager; -var init_manager2 = __esm({ - "src/provider/manager.ts"() { - import_vscode_languageserver_protocol21 = __toModule(require_main2()); - init_workspace(); - init_object(); - logger37 = require_logger2()("provider-manager"); - Manager = class { - constructor() { - this.providers = new Set(); - } - hasProvider(document2) { - return this.getProvider(document2) != null; - } - getProvider(document2) { - let currScore = 0; - let providerItem; - for (let item of this.providers) { - let { selector, priority } = item; - let score5 = workspace_default.match(selector, document2); - if (score5 == 0) - continue; - if (typeof priority == "number") { - score5 = priority; - } - if (score5 < currScore) - continue; - currScore = score5; - providerItem = item; - } - return providerItem; - } - getProviderById(id) { - let item = Array.from(this.providers).find((o) => o.id == id); - return item ? item.provider : null; - } - getProviders(document2) { - let items = Array.from(this.providers); - items = items.filter((item) => workspace_default.match(item.selector, document2) > 0); - return items.sort((a, b) => workspace_default.match(b.selector, document2) - workspace_default.match(a.selector, document2)); - } - toLocations(arr) { - let res = []; - for (let def of arr) { - if (!def) - continue; - if (import_vscode_languageserver_protocol21.Location.is(def)) { - addLocation(res, def); - } else if (Array.isArray(def)) { - for (let d of def) { - if (import_vscode_languageserver_protocol21.Location.is(d)) { - addLocation(res, d); - } else if (import_vscode_languageserver_protocol21.LocationLink.is(d)) { - let { targetUri, targetSelectionRange, targetRange } = d; - addLocation(res, import_vscode_languageserver_protocol21.Location.create(targetUri, targetSelectionRange || targetRange)); - } - } - } else { - logger37.error(`Bad definition`, def); - } - } - return res; - } - }; - } -}); - -// src/provider/callHierarchyManager.ts -var import_vscode_languageserver_protocol22, CallHierarchyManager; -var init_callHierarchyManager = __esm({ - "src/provider/callHierarchyManager.ts"() { - import_vscode_languageserver_protocol22 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - CallHierarchyManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol22.Disposable.create(() => { - this.providers.delete(item); - }); - } - async prepareCallHierarchy(document2, position, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - if (provider.prepareCallHierarchy === null) - return null; - return await Promise.resolve(provider.prepareCallHierarchy(document2, position, token)); - } - async provideCallHierarchyOutgoingCalls(document2, item, token) { - let providerItem = this.getProvider(document2); - if (!providerItem) - return null; - let { provider } = providerItem; - if (provider.provideCallHierarchyOutgoingCalls === null) - return null; - return await Promise.resolve(provider.provideCallHierarchyOutgoingCalls(item, token)); - } - async provideCallHierarchyIncomingCalls(document2, item, token) { - let providerItem = this.getProvider(document2); - if (!providerItem) - return null; - let { provider } = providerItem; - if (provider.provideCallHierarchyIncomingCalls(item, token) === null) - return null; - return await Promise.resolve(provider.provideCallHierarchyIncomingCalls(item, token)); - } - }; - } -}); - -// src/provider/codeActionManager.ts -var import_vscode_languageserver_protocol23, logger38, CodeActionManager; -var init_codeActionManager = __esm({ - "src/provider/codeActionManager.ts"() { - import_vscode_languageserver_protocol23 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - logger38 = require_logger2()("codeActionManager"); - CodeActionManager = class extends Manager { - constructor() { - super(...arguments); - this.providerMap = new WeakMap(); - } - register(selector, provider, clientId, codeActionKinds) { - let item = { - id: v4_default(), - selector, - provider, - kinds: codeActionKinds, - clientId - }; - this.providers.add(item); - return import_vscode_languageserver_protocol23.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideCodeActions(document2, range, context, token) { - let providers = this.getProviders(document2); - if (!providers.length) - return null; - if (context.only) { - let { only } = context; - providers = providers.filter((p) => { - if (p.kinds && !p.kinds.some((kind) => only.includes(kind))) { - return false; - } - return true; - }); - } - let res = []; - await Promise.all(providers.map((item) => { - let { provider, id } = item; - return Promise.resolve(provider.provideCodeActions(document2, range, context, token)).then((actions) => { - if (!actions || actions.length == 0) - return; - for (let action of actions) { - if (import_vscode_languageserver_protocol23.Command.is(action)) { - let codeAction = { - title: action.title, - command: action - }; - res.push(codeAction); - this.providerMap.set(codeAction, id); - } else { - if (context.only) { - if (!action.kind) - continue; - let found = false; - for (let only of context.only) { - if (action.kind.startsWith(only)) { - found = true; - break; - } - } - if (!found) - continue; - } - let idx = res.findIndex((o) => o.title == action.title); - if (idx == -1) { - this.providerMap.set(action, id); - res.push(action); - } - } - } - }); - })); - return res; - } - async resolveCodeAction(codeAction, token) { - if (codeAction.edit != null) - return codeAction; - let id = this.providerMap.get(codeAction); - if (!id) - throw new Error(`provider id not found from codeAction`); - let provider = this.getProviderById(id); - if (!provider || typeof provider.resolveCodeAction !== "function") { - return codeAction; - } - let resolved = await Promise.resolve(provider.resolveCodeAction(codeAction, token)); - if (resolved) - this.providerMap.set(resolved, id); - return resolved || codeAction; - } - }; - } -}); - -// src/provider/codeLensManager.ts -var import_vscode_languageserver_protocol24, CodeLensManager; -var init_codeLensManager = __esm({ - "src/provider/codeLensManager.ts"() { - import_vscode_languageserver_protocol24 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - init_lodash(); - CodeLensManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol24.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideCodeLenses(document2, token) { - let providers = this.getProviders(document2); - if (!providers.length) - return null; - let arr = await Promise.all(providers.map((item) => { - let { provider, id } = item; - return Promise.resolve(provider.provideCodeLenses(document2, token)).then((res) => { - if (Array.isArray(res)) { - for (let item2 of res) { - item2.source = id; - } - } - return res; - }); - })); - return [].concat(...arr); - } - async resolveCodeLens(codeLens, token) { - if (codeLens.command) - return codeLens; - let { source } = codeLens; - let provider = this.getProviderById(source); - if (!provider || typeof provider.resolveCodeLens != "function") { - return codeLens; - } - let res = await Promise.resolve(provider.resolveCodeLens(omit(codeLens, ["source"]), token)); - Object.assign(codeLens, res); - return codeLens; - } - }; - } -}); - -// src/provider/declarationManager.ts -var import_vscode_languageserver_protocol25, logger39, DeclarationManager; -var init_declarationManager = __esm({ - "src/provider/declarationManager.ts"() { - import_vscode_languageserver_protocol25 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - logger39 = require_logger2()("definitionManager"); - DeclarationManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol25.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideDeclaration(document2, position, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - return await Promise.resolve(provider.provideDeclaration(document2, position, token)); - } - }; - } -}); - -// src/provider/definitionManager.ts -var import_vscode_languageserver_protocol26, logger40, DefinitionManager; -var init_definitionManager = __esm({ - "src/provider/definitionManager.ts"() { - import_vscode_languageserver_protocol26 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - init_object(); - logger40 = require_logger2()("definitionManager"); - DefinitionManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol26.Disposable.create(() => { - this.providers.delete(item); - }); - } - async getDefinitions(document2, position, token) { - const providers = this.getProviders(document2); - if (!providers.length) - return []; - const arr = await Promise.all(providers.map((item) => { - const { provider } = item; - return Promise.resolve(provider.provideDefinition(document2, position, token)); - })); - return arr; - } - async provideDefinition(document2, position, token) { - const arr = await this.getDefinitions(document2, position, token); - return this.toLocations(arr); - } - async provideDefinitionLinks(document2, position, token) { - const arr = await this.getDefinitions(document2, position, token); - const defs = []; - for (const def of arr) { - if (!Array.isArray(def)) - continue; - for (const val of def) { - if (import_vscode_languageserver_protocol26.LocationLink.is(val)) { - let idx = defs.findIndex((o) => o.targetUri == val.targetUri && equals(o.targetRange, val.targetRange)); - if (idx == -1) - defs.push(val); - } - } - } - return defs; - } - }; - } -}); - -// src/provider/documentColorManager.ts -var import_vscode_languageserver_protocol27, DocumentColorManager; -var init_documentColorManager = __esm({ - "src/provider/documentColorManager.ts"() { - import_vscode_languageserver_protocol27 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - DocumentColorManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol27.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideDocumentColors(document2, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - let res = await Promise.resolve(provider.provideDocumentColors(document2, token)); - return res; - } - async provideColorPresentations(colorInformation, document2, token) { - let { range, color } = colorInformation; - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - let res = await Promise.resolve(provider.provideColorPresentations(color, { document: document2, range }, token)); - return res; - } - }; - } -}); - -// src/provider/documentHighlightManager.ts -var import_vscode_languageserver_protocol28, DocumentHighlightManager; -var init_documentHighlightManager = __esm({ - "src/provider/documentHighlightManager.ts"() { - import_vscode_languageserver_protocol28 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - DocumentHighlightManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol28.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideDocumentHighlights(document2, position, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - return await Promise.resolve(provider.provideDocumentHighlights(document2, position, token)); - } - }; - } -}); - -// src/provider/documentLinkManager.ts -var import_vscode_languageserver_protocol29, DocumentLinkManager; -var init_documentLinkManager = __esm({ - "src/provider/documentLinkManager.ts"() { - import_vscode_languageserver_protocol29 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - DocumentLinkManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol29.Disposable.create(() => { - this.providers.delete(item); - }); - } - async _provideDocumentLinks(item, document2, token) { - let { provider, id } = item; - let items = await Promise.resolve(provider.provideDocumentLinks(document2, token)); - if (!items || !items.length) - return []; - items.forEach((item2) => { - item2.data = item2.data || {}; - item2.data.source = id; - }); - return items; - } - async provideDocumentLinks(document2, token) { - let items = this.getProviders(document2); - if (items.length == 0) - return []; - const arr = await Promise.all(items.map((item) => this._provideDocumentLinks(item, document2, token))); - return [].concat(...arr); - } - async resolveDocumentLink(link, token) { - let { data } = link; - if (!data || !data.source) - return null; - for (let item of this.providers) { - if (item.id == data.source) { - let { provider } = item; - link = await Promise.resolve(provider.resolveDocumentLink(link, token)); - return link; - } - } - return null; - } - }; - } -}); - -// src/provider/documentSymbolManager.ts -var import_vscode_languageserver_protocol30, DocumentSymbolManager; -var init_documentSymbolManager = __esm({ - "src/provider/documentSymbolManager.ts"() { - import_vscode_languageserver_protocol30 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - DocumentSymbolManager = class extends Manager { - register(selector, provider, displayName) { - let item = { - id: v4_default(), - displayName, - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol30.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideDocumentSymbols(document2, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - return await Promise.resolve(provider.provideDocumentSymbols(document2, token)) || []; - } - }; - } -}); - -// src/provider/foldingRangeManager.ts -var import_vscode_languageserver_protocol31, FoldingRangeManager; -var init_foldingRangeManager = __esm({ - "src/provider/foldingRangeManager.ts"() { - import_vscode_languageserver_protocol31 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - FoldingRangeManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol31.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideFoldingRanges(document2, context, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - return await Promise.resolve(provider.provideFoldingRanges(document2, context, token)) || []; - } - }; - } -}); - -// src/provider/formatManager.ts -var import_vscode_languageserver_protocol32, FormatManager; -var init_formatManager = __esm({ - "src/provider/formatManager.ts"() { - import_vscode_languageserver_protocol32 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - FormatManager = class extends Manager { - register(selector, provider, priority = 0) { - let item = { - id: v4_default(), - selector, - priority, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol32.Disposable.create(() => { - this.providers.delete(item); - }); - } - handles(doc) { - return this.getProvider(doc) != null; - } - async provideDocumentFormattingEdits(document2, options, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - return await Promise.resolve(provider.provideDocumentFormattingEdits(document2, options, token)); - } - }; - } -}); - -// src/provider/formatRangeManager.ts -var import_vscode_languageserver_protocol33, FormatRangeManager; -var init_formatRangeManager = __esm({ - "src/provider/formatRangeManager.ts"() { - import_vscode_languageserver_protocol33 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - FormatRangeManager = class extends Manager { - register(selector, provider, priority = 0) { - let item = { - id: v4_default(), - selector, - provider, - priority - }; - this.providers.add(item); - return import_vscode_languageserver_protocol33.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideDocumentRangeFormattingEdits(document2, range, options, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - return await Promise.resolve(provider.provideDocumentRangeFormattingEdits(document2, range, options, token)); - } - }; - } -}); - -// src/provider/hoverManager.ts -var import_vscode_languageserver_protocol34, HoverManager; -var init_hoverManager = __esm({ - "src/provider/hoverManager.ts"() { - import_vscode_languageserver_protocol34 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - HoverManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol34.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideHover(document2, position, token) { - let items = this.getProviders(document2); - if (items.length === 0) - return null; - let res = []; - for (let i = 0, len = items.length; i < len; i += 1) { - const item = items[i]; - let hover = await Promise.resolve(item.provider.provideHover(document2, position, token)); - if (hover && hover.contents != "") - res.push(hover); - } - return res; - } - }; - } -}); - -// src/provider/implementationManager.ts -var import_vscode_languageserver_protocol35, ImplementationManager; -var init_implementationManager = __esm({ - "src/provider/implementationManager.ts"() { - import_vscode_languageserver_protocol35 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - ImplementationManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol35.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideReferences(document2, position, token) { - let providers = this.getProviders(document2); - if (!providers.length) - return null; - let arr = await Promise.all(providers.map((item) => { - let { provider } = item; - return Promise.resolve(provider.provideImplementation(document2, position, token)); - })); - return this.toLocations(arr); - } - }; - } -}); - -// src/provider/linkedEditingRangeManager.ts -var import_vscode_languageserver_protocol36, logger41, LinkedEditingRangeManager; -var init_linkedEditingRangeManager = __esm({ - "src/provider/linkedEditingRangeManager.ts"() { - init_esm_node(); - import_vscode_languageserver_protocol36 = __toModule(require_main2()); - init_manager2(); - logger41 = require_logger2()("linkedEditingManager"); - LinkedEditingRangeManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol36.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideLinkedEditingRanges(document2, position, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - if (!provider.provideLinkedEditingRanges) - return null; - return await Promise.resolve(provider.provideLinkedEditingRanges(document2, position, token)); - } - }; - } -}); - -// src/provider/onTypeFormatManager.ts -var import_vscode_languageserver_protocol37, logger42, OnTypeFormatManager; -var init_onTypeFormatManager = __esm({ - "src/provider/onTypeFormatManager.ts"() { - import_vscode_languageserver_protocol37 = __toModule(require_main2()); - init_workspace(); - logger42 = require_logger2()("onTypeFormatManager"); - OnTypeFormatManager = class { - constructor() { - this.providers = new Set(); - } - register(selector, provider, triggerCharacters) { - let item = { - triggerCharacters, - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol37.Disposable.create(() => { - this.providers.delete(item); - }); - } - hasProvider(document2) { - for (let o of this.providers) { - let { selector } = o; - if (workspace_default.match(selector, document2) > 0) { - return true; - } - } - return false; - } - getProvider(document2, triggerCharacter) { - for (let o of this.providers) { - let { triggerCharacters, selector } = o; - if (workspace_default.match(selector, document2) > 0 && triggerCharacters.includes(triggerCharacter)) { - return o.provider; - } - } - return null; - } - async onCharacterType(character, document2, position, token) { - let provider = this.getProvider(document2, character); - if (!provider) - return; - let formatOpts = await workspace_default.getFormatOptions(document2.uri); - return await Promise.resolve(provider.provideOnTypeFormattingEdits(document2, position, character, formatOpts, token)); - } - }; - } -}); - -// src/provider/referenceManager.ts -var import_vscode_languageserver_protocol38, ReferenceManager; -var init_referenceManager = __esm({ - "src/provider/referenceManager.ts"() { - import_vscode_languageserver_protocol38 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - ReferenceManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol38.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideReferences(document2, position, context, token) { - let providers = this.getProviders(document2); - if (!providers.length) - return null; - let arr = await Promise.all(providers.map((item) => { - let { provider } = item; - return Promise.resolve(provider.provideReferences(document2, position, context, token)); - })); - return this.toLocations(arr); - } - }; - } -}); - -// src/provider/renameManager.ts -var import_vscode_languageserver_protocol39, RenameManager; -var init_renameManager = __esm({ - "src/provider/renameManager.ts"() { - import_vscode_languageserver_protocol39 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - RenameManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol39.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideRenameEdits(document2, position, newName, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - return await Promise.resolve(provider.provideRenameEdits(document2, position, newName, token)); - } - async prepareRename(document2, position, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - if (provider.prepareRename == null) - return null; - let res = await Promise.resolve(provider.prepareRename(document2, position, token)); - if (res == null) - return false; - return res; - } - }; - } -}); - -// src/provider/selectionRangeManager.ts -var import_vscode_languageserver_protocol40, SelectionRangeManager; -var init_selectionRangeManager = __esm({ - "src/provider/selectionRangeManager.ts"() { - import_vscode_languageserver_protocol40 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - SelectionRangeManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol40.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideSelectionRanges(document2, positions2, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - let ranges = await Promise.resolve(provider.provideSelectionRanges(document2, positions2, token)); - if (!ranges || ranges.length == 0) - return []; - for (let i = 0; i < ranges.length - 1; i++) { - let r = ranges[i]; - if (!r.parent) - r.parent = ranges[i + 1]; - } - return ranges; - } - }; - } -}); - -// src/provider/semanticTokensManager.ts -var import_vscode_languageserver_protocol41, logger43, SemanticTokensManager; -var init_semanticTokensManager = __esm({ - "src/provider/semanticTokensManager.ts"() { - init_esm_node(); - import_vscode_languageserver_protocol41 = __toModule(require_main2()); - init_manager2(); - logger43 = require_logger2()("semanticTokensManager"); - SemanticTokensManager = class extends Manager { - constructor() { - super(...arguments); - this.resolvedProvider = new Map(); - } - register(selector, provider, legend, onChange) { - let id = v4_default(); - let item = { - id, - selector, - legend, - provider - }; - this.providers.add(item); - let disposable; - if (typeof provider.onDidChangeSemanticTokens === "function") { - disposable = provider.onDidChangeSemanticTokens(() => { - onChange(); - }); - } - return import_vscode_languageserver_protocol41.Disposable.create(() => { - disposable == null ? void 0 : disposable.dispose(); - for (let [uri, providerId] of this.resolvedProvider.entries()) { - if (providerId == id) { - this.resolvedProvider.delete(uri); - } - } - this.providers.delete(item); - }); - } - getLegend(document2) { - const item = this.getProvider(document2); - if (!item) - return; - this.resolvedProvider.set(document2.uri, item.id); - return item.legend; - } - resolveProvider(document2) { - var _a2; - let id = this.resolvedProvider.get(document2.uri); - if (id) - return this.getProviderById(id); - return (_a2 = this.getProvider(document2)) == null ? void 0 : _a2.provider; - } - hasSemanticTokensEdits(document2) { - let provider = this.resolveProvider(document2); - if (!provider) - return false; - return typeof provider.provideDocumentSemanticTokensEdits === "function"; - } - async provideDocumentSemanticTokens(document2, token) { - let provider = this.resolveProvider(document2); - if (!provider || typeof provider.provideDocumentSemanticTokens !== "function") - return null; - return await Promise.resolve(provider.provideDocumentSemanticTokens(document2, token)); - } - async provideDocumentSemanticTokensEdits(document2, previousResultId, token) { - let provider = this.resolveProvider(document2); - if (!provider || typeof provider.provideDocumentSemanticTokensEdits !== "function") - return null; - return await Promise.resolve(provider.provideDocumentSemanticTokensEdits(document2, previousResultId, token)); - } - }; - } -}); - -// src/provider/semanticTokensRangeManager.ts -var import_vscode_languageserver_protocol42, logger44, SemanticTokensRangeManager; -var init_semanticTokensRangeManager = __esm({ - "src/provider/semanticTokensRangeManager.ts"() { - init_esm_node(); - import_vscode_languageserver_protocol42 = __toModule(require_main2()); - init_manager2(); - logger44 = require_logger2()("semanticTokensRangeManager"); - SemanticTokensRangeManager = class extends Manager { - register(selector, provider, legend) { - let item = { - id: v4_default(), - selector, - legend, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol42.Disposable.create(() => { - this.providers.delete(item); - }); - } - getLegend(document2) { - const item = this.getProvider(document2); - if (!item) - return; - return item.legend; - } - async provideDocumentRangeSemanticTokens(document2, range, token) { - let item = this.getProvider(document2); - if (!item) - return null; - let { provider } = item; - if (provider.provideDocumentRangeSemanticTokens === null) - return null; - return await Promise.resolve(provider.provideDocumentRangeSemanticTokens(document2, range, token)); - } - }; - } -}); - -// src/provider/signatureManager.ts -var import_vscode_languageserver_protocol43, SignatureManager; -var init_signatureManager = __esm({ - "src/provider/signatureManager.ts"() { - import_vscode_languageserver_protocol43 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - SignatureManager = class extends Manager { - register(selector, provider, triggerCharacters) { - let characters = triggerCharacters.reduce((p, c) => p.concat(c.length == 1 ? [c] : c.split(/\s*/g)), []); - let item = { - id: v4_default(), - selector, - provider, - triggerCharacters: characters - }; - this.providers.add(item); - return import_vscode_languageserver_protocol43.Disposable.create(() => { - this.providers.delete(item); - }); - } - shouldTrigger(document2, triggerCharacter) { - let item = this.getProvider(document2); - if (!item) - return false; - let { triggerCharacters } = item; - return triggerCharacters && triggerCharacters.indexOf(triggerCharacter) != -1; - } - async provideSignatureHelp(document2, position, token, context) { - let item = this.getProvider(document2); - if (!item) - return null; - let res = await Promise.resolve(item.provider.provideSignatureHelp(document2, position, token, context)); - if (res && res.signatures && res.signatures.length) - return res; - return null; - } - }; - } -}); - -// src/provider/typeDefinitionManager.ts -var import_vscode_languageserver_protocol44, TypeDefinitionManager; -var init_typeDefinitionManager = __esm({ - "src/provider/typeDefinitionManager.ts"() { - import_vscode_languageserver_protocol44 = __toModule(require_main2()); - init_manager2(); - init_esm_node(); - TypeDefinitionManager = class extends Manager { - register(selector, provider) { - let item = { - id: v4_default(), - selector, - provider - }; - this.providers.add(item); - return import_vscode_languageserver_protocol44.Disposable.create(() => { - this.providers.delete(item); - }); - } - async provideTypeDefinition(document2, position, token) { - let providers = this.getProviders(document2); - if (!providers.length) - return null; - let arr = await Promise.all(providers.map((item) => { - let { provider } = item; - return Promise.resolve(provider.provideTypeDefinition(document2, position, token)); - })); - return this.toLocations(arr); - } - }; - } -}); - -// src/provider/workspaceSymbolsManager.ts -var import_vscode_languageserver_protocol45, WorkspaceSymbolManager; -var init_workspaceSymbolsManager = __esm({ - "src/provider/workspaceSymbolsManager.ts"() { - init_esm_node(); - import_vscode_languageserver_protocol45 = __toModule(require_main2()); - WorkspaceSymbolManager = class { - constructor() { - this.providers = new Map(); - } - register(provider) { - let id = v4_default(); - this.providers.set(id, provider); - return import_vscode_languageserver_protocol45.Disposable.create(() => { - this.providers.delete(id); - }); - } - async provideWorkspaceSymbols(query, token) { - let entries = Array.from(this.providers.entries()); - if (!entries.length) - return []; - let res = []; - await Promise.all(entries.map((o) => { - let [id, p] = o; - return Promise.resolve(p.provideWorkspaceSymbols(query, token)).then((list2) => { - if (list2) - res.push(...list2.map((item) => Object.assign({ source: id }, item))); - }); - })); - return res; - } - async resolveWorkspaceSymbol(symbolInfo, token) { - let provider = this.providers.get(symbolInfo.source); - if (!provider) - return; - if (typeof provider.resolveWorkspaceSymbol != "function") { - return Promise.resolve(symbolInfo); - } - return await Promise.resolve(provider.resolveWorkspaceSymbol(symbolInfo, token)); - } - hasProvider() { - return this.providers.size > 0; - } - }; - } -}); - -// src/languages.ts -var import_vscode_languageserver_protocol46, logger45, Languages, languages_default; -var init_languages = __esm({ - "src/languages.ts"() { - import_vscode_languageserver_protocol46 = __toModule(require_main2()); - init_manager(); - init_callHierarchyManager(); - init_codeActionManager(); - init_codeLensManager(); - init_declarationManager(); - init_definitionManager(); - init_documentColorManager(); - init_documentHighlightManager(); - init_documentLinkManager(); - init_documentSymbolManager(); - init_foldingRangeManager(); - init_formatManager(); - init_formatRangeManager(); - init_hoverManager(); - init_implementationManager(); - init_linkedEditingRangeManager(); - init_onTypeFormatManager(); - init_referenceManager(); - init_renameManager(); - init_selectionRangeManager(); - init_semanticTokensManager(); - init_semanticTokensRangeManager(); - init_signatureManager(); - init_typeDefinitionManager(); - init_workspaceSymbolsManager(); - logger45 = require_logger2()("languages"); - Languages = class { - constructor() { - this._onDidSemanticTokensRefresh = new import_vscode_languageserver_protocol46.Emitter(); - this.onDidSemanticTokensRefresh = this._onDidSemanticTokensRefresh.event; - this.onTypeFormatManager = new OnTypeFormatManager(); - this.documentLinkManager = new DocumentLinkManager(); - this.documentColorManager = new DocumentColorManager(); - this.foldingRangeManager = new FoldingRangeManager(); - this.renameManager = new RenameManager(); - this.formatManager = new FormatManager(); - this.codeActionManager = new CodeActionManager(); - this.workspaceSymbolsManager = new WorkspaceSymbolManager(); - this.formatRangeManager = new FormatRangeManager(); - this.hoverManager = new HoverManager(); - this.signatureManager = new SignatureManager(); - this.documentSymbolManager = new DocumentSymbolManager(); - this.documentHighlightManager = new DocumentHighlightManager(); - this.definitionManager = new DefinitionManager(); - this.declarationManager = new DeclarationManager(); - this.typeDefinitionManager = new TypeDefinitionManager(); - this.referenceManager = new ReferenceManager(); - this.implementationManager = new ImplementationManager(); - this.codeLensManager = new CodeLensManager(); - this.selectionRangeManager = new SelectionRangeManager(); - this.callHierarchyManager = new CallHierarchyManager(); - this.semanticTokensManager = new SemanticTokensManager(); - this.semanticTokensRangeManager = new SemanticTokensRangeManager(); - this.linkedEditingManager = new LinkedEditingRangeManager(); - this.cancelTokenSource = new import_vscode_languageserver_protocol46.CancellationTokenSource(); - } - hasFormatProvider(doc) { - if (this.formatManager.hasProvider(doc)) { - return true; - } - if (this.formatRangeManager.hasProvider(doc)) { - return true; - } - return false; - } - registerOnTypeFormattingEditProvider(selector, provider, triggerCharacters) { - return this.onTypeFormatManager.register(selector, provider, triggerCharacters); - } - registerCompletionItemProvider(name2, shortcut, selector, provider, triggerCharacters = [], priority, allCommitCharacters) { - selector = typeof selector == "string" ? [{ language: selector }] : selector; - let sources = (init_sources2(), sources_exports).default; - return sources.createLanguageSource(name2, shortcut, selector, provider, triggerCharacters, priority, allCommitCharacters); - } - registerCodeActionProvider(selector, provider, clientId, codeActionKinds) { - return this.codeActionManager.register(selector, provider, clientId, codeActionKinds); - } - registerHoverProvider(selector, provider) { - return this.hoverManager.register(selector, provider); - } - registerSelectionRangeProvider(selector, provider) { - return this.selectionRangeManager.register(selector, provider); - } - registerSignatureHelpProvider(selector, provider, triggerCharacters) { - return this.signatureManager.register(selector, provider, triggerCharacters); - } - registerDocumentSymbolProvider(selector, provider, metadata) { - return this.documentSymbolManager.register(selector, provider, metadata == null ? void 0 : metadata.label); - } - registerFoldingRangeProvider(selector, provider) { - return this.foldingRangeManager.register(selector, provider); - } - registerDocumentHighlightProvider(selector, provider) { - return this.documentHighlightManager.register(selector, provider); - } - registerCodeLensProvider(selector, provider) { - return this.codeLensManager.register(selector, provider); - } - registerDocumentLinkProvider(selector, provider) { - return this.documentLinkManager.register(selector, provider); - } - registerDocumentColorProvider(selector, provider) { - return this.documentColorManager.register(selector, provider); - } - registerDefinitionProvider(selector, provider) { - return this.definitionManager.register(selector, provider); - } - registerDeclarationProvider(selector, provider) { - return this.declarationManager.register(selector, provider); - } - registerTypeDefinitionProvider(selector, provider) { - return this.typeDefinitionManager.register(selector, provider); - } - registerImplementationProvider(selector, provider) { - return this.implementationManager.register(selector, provider); - } - registerReferencesProvider(selector, provider) { - return this.referenceManager.register(selector, provider); - } - registerRenameProvider(selector, provider) { - return this.renameManager.register(selector, provider); - } - registerWorkspaceSymbolProvider(provider) { - if (arguments.length > 1 && typeof arguments[1].provideWorkspaceSymbols === "function") { - provider = arguments[1]; - } - return this.workspaceSymbolsManager.register(provider); - } - registerDocumentFormatProvider(selector, provider, priority = 0) { - return this.formatManager.register(selector, provider, priority); - } - registerDocumentRangeFormatProvider(selector, provider, priority = 0) { - return this.formatRangeManager.register(selector, provider, priority); - } - registerCallHierarchyProvider(selector, provider) { - return this.callHierarchyManager.register(selector, provider); - } - registerDocumentSemanticTokensProvider(selector, provider, legend) { - this._onDidSemanticTokensRefresh.fire(selector); - return this.semanticTokensManager.register(selector, provider, legend, () => { - this._onDidSemanticTokensRefresh.fire(selector); - }); - } - registerDocumentRangeSemanticTokensProvider(selector, provider, legend) { - this._onDidSemanticTokensRefresh.fire(selector); - return this.semanticTokensRangeManager.register(selector, provider, legend); - } - registerLinkedEditingRangeProvider(selector, provider) { - return this.linkedEditingManager.register(selector, provider); - } - shouldTriggerSignatureHelp(document2, triggerCharacter) { - return this.signatureManager.shouldTrigger(document2, triggerCharacter); - } - async getHover(document2, position, token) { - return await this.hoverManager.provideHover(document2, position, token); - } - async getSignatureHelp(document2, position, token, context) { - return await this.signatureManager.provideSignatureHelp(document2, position, token, context); - } - async getDefinition(document2, position, token) { - if (!this.definitionManager.hasProvider(document2)) - return null; - return await this.definitionManager.provideDefinition(document2, position, token); - } - async getDefinitionLinks(document2, position, token) { - if (!this.definitionManager.hasProvider(document2)) - return null; - return await this.definitionManager.provideDefinitionLinks(document2, position, token); - } - async getDeclaration(document2, position, token) { - if (!this.declarationManager.hasProvider(document2)) - return null; - return await this.declarationManager.provideDeclaration(document2, position, token); - } - async getTypeDefinition(document2, position, token) { - if (!this.typeDefinitionManager.hasProvider(document2)) - return null; - return await this.typeDefinitionManager.provideTypeDefinition(document2, position, token); - } - async getImplementation(document2, position, token) { - if (!this.implementationManager.hasProvider(document2)) - return null; - return await this.implementationManager.provideReferences(document2, position, token); - } - async getReferences(document2, context, position, token) { - if (!this.referenceManager.hasProvider(document2)) - return null; - return await this.referenceManager.provideReferences(document2, position, context, token); - } - async getDocumentSymbol(document2, token) { - return await this.documentSymbolManager.provideDocumentSymbols(document2, token); - } - async getSelectionRanges(document2, positions2, token) { - return await this.selectionRangeManager.provideSelectionRanges(document2, positions2, token); - } - async getWorkspaceSymbols(query, token) { - query = query || ""; - return await this.workspaceSymbolsManager.provideWorkspaceSymbols(query, token); - } - async resolveWorkspaceSymbol(symbol, token) { - return await this.workspaceSymbolsManager.resolveWorkspaceSymbol(symbol, token); - } - async prepareRename(document2, position, token) { - return await this.renameManager.prepareRename(document2, position, token); - } - async provideRenameEdits(document2, position, newName, token) { - return await this.renameManager.provideRenameEdits(document2, position, newName, token); - } - async provideDocumentFormattingEdits(document2, options, token) { - if (!this.formatManager.hasProvider(document2)) { - let hasRangeFormater = this.formatRangeManager.hasProvider(document2); - if (!hasRangeFormater) - return null; - let end = document2.positionAt(document2.getText().length); - let range = import_vscode_languageserver_protocol46.Range.create(import_vscode_languageserver_protocol46.Position.create(0, 0), end); - return await this.provideDocumentRangeFormattingEdits(document2, range, options, token); - } - return await this.formatManager.provideDocumentFormattingEdits(document2, options, token); - } - async provideDocumentRangeFormattingEdits(document2, range, options, token) { - if (!this.formatRangeManager.hasProvider(document2)) - return null; - return await this.formatRangeManager.provideDocumentRangeFormattingEdits(document2, range, options, token); - } - async getCodeActions(document2, range, context, token) { - return await this.codeActionManager.provideCodeActions(document2, range, context, token); - } - async getDocumentHighLight(document2, position, token) { - return await this.documentHighlightManager.provideDocumentHighlights(document2, position, token); - } - async getDocumentLinks(document2, token) { - if (!this.documentLinkManager.hasProvider(document2)) { - return null; - } - return await this.documentLinkManager.provideDocumentLinks(document2, token) || []; - } - async resolveDocumentLink(link) { - return await this.documentLinkManager.resolveDocumentLink(link, this.token); - } - async provideDocumentColors(document2, token) { - return await this.documentColorManager.provideDocumentColors(document2, token); - } - async provideFoldingRanges(document2, context, token) { - if (!this.foldingRangeManager.hasProvider(document2)) { - return null; - } - return await this.foldingRangeManager.provideFoldingRanges(document2, context, token); - } - async provideColorPresentations(color, document2, token) { - return await this.documentColorManager.provideColorPresentations(color, document2, token); - } - async getCodeLens(document2, token) { - return await this.codeLensManager.provideCodeLenses(document2, token); - } - async resolveCodeLens(codeLens, token) { - if (codeLens.command != null) - return codeLens; - return await this.codeLensManager.resolveCodeLens(codeLens, token); - } - async resolveCodeAction(codeAction, token) { - return await this.codeActionManager.resolveCodeAction(codeAction, token); - } - async provideDocumentOnTypeEdits(character, document2, position, token) { - return this.onTypeFormatManager.onCharacterType(character, document2, position, token); - } - canFormatOnType(character, document2) { - return this.onTypeFormatManager.getProvider(document2, character) != null; - } - async prepareCallHierarchy(document2, position, token) { - return this.callHierarchyManager.prepareCallHierarchy(document2, position, token); - } - async provideIncomingCalls(document2, item, token) { - return this.callHierarchyManager.provideCallHierarchyIncomingCalls(document2, item, token); - } - async provideOutgoingCalls(document2, item, token) { - return this.callHierarchyManager.provideCallHierarchyOutgoingCalls(document2, item, token); - } - getLegend(document2, range) { - if (range) - return this.semanticTokensRangeManager.getLegend(document2); - return this.semanticTokensManager.getLegend(document2); - } - hasSemanticTokensEdits(document2) { - return this.semanticTokensManager.hasSemanticTokensEdits(document2); - } - async provideDocumentSemanticTokens(document2, token) { - return this.semanticTokensManager.provideDocumentSemanticTokens(document2, token); - } - async provideDocumentSemanticTokensEdits(document2, previousResultId, token) { - return this.semanticTokensManager.provideDocumentSemanticTokensEdits(document2, previousResultId, token); - } - async provideDocumentRangeSemanticTokens(document2, range, token) { - return this.semanticTokensRangeManager.provideDocumentRangeSemanticTokens(document2, range, token); - } - hasLinkedEditing(document2) { - return this.linkedEditingManager.hasProvider(document2); - } - async provideLinkedEdits(document2, position, token) { - return this.linkedEditingManager.provideLinkedEditingRanges(document2, position, token); - } - hasProvider(id, document2) { - switch (id) { - case "formatOnType": - return this.onTypeFormatManager.hasProvider(document2); - case "rename": - return this.renameManager.hasProvider(document2); - case "onTypeEdit": - return this.onTypeFormatManager.hasProvider(document2); - case "documentLink": - return this.documentLinkManager.hasProvider(document2); - case "documentColor": - return this.documentColorManager.hasProvider(document2); - case "foldingRange": - return this.foldingRangeManager.hasProvider(document2); - case "format": - return this.formatManager.hasProvider(document2) || this.formatRangeManager.hasProvider(document2); - case "codeAction": - return this.codeActionManager.hasProvider(document2); - case "workspaceSymbols": - return this.workspaceSymbolsManager.hasProvider(); - case "formatRange": - return this.formatRangeManager.hasProvider(document2); - case "hover": - return this.hoverManager.hasProvider(document2); - case "signature": - return this.signatureManager.hasProvider(document2); - case "documentSymbol": - return this.documentSymbolManager.hasProvider(document2); - case "documentHighlight": - return this.documentHighlightManager.hasProvider(document2); - case "definition": - return this.definitionManager.hasProvider(document2); - case "declaration": - return this.declarationManager.hasProvider(document2); - case "typeDefinition": - return this.typeDefinitionManager.hasProvider(document2); - case "reference": - return this.referenceManager.hasProvider(document2); - case "implementation": - return this.implementationManager.hasProvider(document2); - case "codeLens": - return this.codeLensManager.hasProvider(document2); - case "selectionRange": - return this.selectionRangeManager.hasProvider(document2); - case "callHierarchy": - return this.callHierarchyManager.hasProvider(document2); - case "semanticTokens": - return this.semanticTokensManager.hasProvider(document2); - case "linkedEditing": - return this.linkedEditingManager.hasProvider(document2); - default: - throw new Error(`Invalid provider name: ${id}`); - } - } - createDiagnosticCollection(owner) { - return manager_default.create(owner); - } - get token() { - this.cancelTokenSource = new import_vscode_languageserver_protocol46.CancellationTokenSource(); - return this.cancelTokenSource.token; - } - }; - languages_default = new Languages(); - } -}); - -// src/model/highligher.ts -var Highlighter; -var init_highligher = __esm({ - "src/model/highligher.ts"() { - init_ansiparse(); - init_string(); - Highlighter = class { - constructor() { - this.lines = []; - this.highlights = []; - } - addLine(line, hlGroup) { - if (line.includes("\n")) { - for (let content of line.split(/\r?\n/)) { - this.addLine(content, hlGroup); - } - return; - } - if (hlGroup) { - this.highlights.push({ - lnum: this.lines.length, - colStart: line.match(/^\s*/)[0].length, - colEnd: byteLength(line), - hlGroup - }); - } - if (line.includes("")) { - let res = parseAnsiHighlights(line); - for (let hl of res.highlights) { - let { span, hlGroup: hlGroup2 } = hl; - if (span[0] != span[1]) { - this.highlights.push({ - lnum: this.lines.length, - colStart: span[0], - colEnd: span[1], - hlGroup: hlGroup2 - }); - } - } - this.lines.push(res.line); - } else { - this.lines.push(line); - } - } - addLines(lines) { - this.lines.push(...lines); - } - addTexts(items) { - this.addLines(""); - for (let item of items) { - this.addText(item.text, item.hlGroup); - } - } - addText(text, hlGroup) { - let { lines } = this; - let pre = lines[lines.length - 1] || ""; - if (hlGroup) { - let colStart = byteLength(pre); - this.highlights.push({ - lnum: lines.length ? lines.length - 1 : 0, - colStart, - colEnd: colStart + byteLength(text), - hlGroup - }); - } - if (lines.length) { - lines[lines.length - 1] = `${pre}${text}`; - } else { - lines.push(text); - } - } - get length() { - return this.lines.length; - } - getline(line) { - return this.lines[line] || ""; - } - render(buffer, start = 0, end = -1) { - buffer.setLines(this.lines, { start, end, strictIndexing: false }, true); - for (let item of this.highlights) { - buffer.addHighlight({ - hlGroup: item.hlGroup, - colStart: item.colStart, - colEnd: item.colEnd == null ? -1 : item.colEnd, - line: start + item.lnum, - srcId: -1 - }); - } - } - }; - } -}); - -// node_modules/vscode-languageserver-protocol/node.js -var require_node3 = __commonJS({ - "node_modules/vscode-languageserver-protocol/node.js"(exports2, module2) { - "use strict"; - module2.exports = require_main2(); - } -}); - -// src/util/processes.ts -function terminate(process2, cwd) { - if (process2.killed) - return; - if (isWindows3) { - try { - let options = { - stdio: ["pipe", "pipe", "ignore"] - }; - if (cwd) { - options.cwd = cwd; - } - cp.execFileSync("taskkill", ["/T", "/F", "/PID", process2.pid.toString()], options); - return true; - } catch (err) { - return false; - } - } else if (isLinux2 || isMacintosh2) { - try { - let filepath = (0, import_path16.join)(pluginRoot2, "bin/terminateProcess.sh"); - if (!import_fs14.default.existsSync(filepath)) { - console.error(`"${filepath}" not found`); - return false; - } - let result = cp.spawnSync(filepath, [process2.pid.toString()]); - return result.error ? false : true; - } catch (err) { - return false; - } - } else { - process2.kill("SIGKILL"); - return true; - } -} -var cp, import_path16, import_fs14, isWindows3, isMacintosh2, isLinux2, pluginRoot2; -var init_processes = __esm({ - "src/util/processes.ts"() { - cp = __toModule(require("child_process")); - import_path16 = __toModule(require("path")); - import_fs14 = __toModule(require("fs")); - isWindows3 = process.platform === "win32"; - isMacintosh2 = process.platform === "darwin"; - isLinux2 = process.platform === "linux"; - pluginRoot2 = false ? resolve2(__dirname, "../..") : (0, import_path16.dirname)(__dirname); - } -}); - -// src/language-client/progressPart.ts -var import_vscode_languageserver_protocol47, logger46, ProgressPart; -var init_progressPart = __esm({ - "src/language-client/progressPart.ts"() { - import_vscode_languageserver_protocol47 = __toModule(require_main2()); - init_util(); - init_window(); - "use strict"; - logger46 = require_logger2()("language-client-progressPart"); - ProgressPart = class { - constructor(client, token, done) { - this.client = client; - this.token = token; - this.disposables = []; - this._cancelled = false; - this.statusBarItem = window_default.createStatusBarItem(99, { progress: true }); - this.disposables.push(client.onProgress(import_vscode_languageserver_protocol47.WorkDoneProgress.type, this.token, (value) => { - switch (value.kind) { - case "begin": - this.begin(value); - break; - case "report": - this.report(value); - break; - case "end": - this.done(value.message); - done && done(this); - break; - } - })); - } - begin(params) { - if (typeof this.title === "string") - return; - this.title = params.title; - this.report(params); - } - report(params) { - let statusBarItem = this.statusBarItem; - let parts = []; - if (this.title) - parts.push(this.title); - if (typeof params.percentage == "number") - parts.push(params.percentage.toFixed(0) + "%"); - if (params.message) - parts.push(params.message); - statusBarItem.text = parts.join(" "); - statusBarItem.show(); - } - cancel() { - if (this._cancelled) - return; - this._cancelled = true; - disposeAll(this.disposables); - } - done(message) { - if (this._cancelled) - return; - const statusBarItem = this.statusBarItem; - statusBarItem.text = `${this.title} ${message || "finished"}`; - setTimeout(() => { - statusBarItem.dispose(); - }, 300); - this.cancel(); - } - }; - } -}); - -// src/language-client/utils/async.ts -var import_vscode_languageserver_protocol48, Delayer; -var init_async = __esm({ - "src/language-client/utils/async.ts"() { - import_vscode_languageserver_protocol48 = __toModule(require_main2()); - Delayer = class { - constructor(defaultDelay) { - this.defaultDelay = defaultDelay; - this.timeout = void 0; - this.completionPromise = void 0; - this.onSuccess = void 0; - this.task = void 0; - } - trigger(task, delay = this.defaultDelay) { - this.task = task; - if (delay >= 0) { - this.cancelTimeout(); - } - if (!this.completionPromise) { - this.completionPromise = new Promise((resolve3) => { - this.onSuccess = resolve3; - }).then(() => { - this.completionPromise = void 0; - this.onSuccess = void 0; - let result = this.task(); - this.task = void 0; - return result; - }); - } - if (delay >= 0 || this.timeout === void 0) { - this.timeout = (0, import_vscode_languageserver_protocol48.RAL)().timer.setTimeout(() => { - this.timeout = void 0; - this.onSuccess(void 0); - }, delay >= 0 ? delay : this.defaultDelay); - } - return this.completionPromise; - } - forceDelivery() { - if (!this.completionPromise) { - return void 0; - } - this.cancelTimeout(); - let result = this.task(); - this.completionPromise = void 0; - this.onSuccess = void 0; - this.task = void 0; - return result; - } - isTriggered() { - return this.timeout !== void 0; - } - cancel() { - this.cancelTimeout(); - this.completionPromise = void 0; - } - dispose() { - this.cancelTimeout(); - } - cancelTimeout() { - if (this.timeout !== void 0) { - (0, import_vscode_languageserver_protocol48.RAL)().timer.clearTimeout(this.timeout); - this.timeout = void 0; - } - } - }; - } -}); - -// src/language-client/utils/converter.ts -function convertToTextDocumentItem(document2) { - return { - uri: document2.uri, - languageId: document2.languageId, - version: document2.version, - text: document2.getText() - }; -} -function asCloseTextDocumentParams(document2) { - return { - textDocument: { - uri: document2.uri - } - }; -} -function asChangeTextDocumentParams(document2) { - let result = { - textDocument: { - uri: document2.uri, - version: document2.version - }, - contentChanges: [{ text: document2.getText() }] - }; - return result; -} -function asWillSaveTextDocumentParams(event) { - return { - textDocument: asVersionedTextDocumentIdentifier(event.document), - reason: event.reason - }; -} -function asVersionedTextDocumentIdentifier(textDocument) { - return { - uri: textDocument.uri, - version: textDocument.version - }; -} -function asSaveTextDocumentParams(document2, includeText) { - let result = { - textDocument: asVersionedTextDocumentIdentifier(document2) - }; - if (includeText) { - result.text = document2.getText(); - } - return result; -} -function asUri(resource) { - return resource.toString(); -} -function asCompletionParams(textDocument, position, context) { - return { - textDocument: { - uri: textDocument.uri - }, - position, - context: omit(context, ["option"]) - }; -} -function asTextDocumentPositionParams(textDocument, position) { - return { - textDocument: { - uri: textDocument.uri - }, - position - }; -} -function asSignatureHelpParams(textDocument, position, context) { - return { - textDocument: asTextDocumentIdentifier(textDocument), - position, - context - }; -} -function asTextDocumentIdentifier(textDocument) { - return { - uri: textDocument.uri - }; -} -function asReferenceParams(textDocument, position, options) { - return { - textDocument: { - uri: textDocument.uri - }, - position, - context: { includeDeclaration: options.includeDeclaration } - }; -} -function asDocumentSymbolParams(textDocument) { - return { - textDocument: { - uri: textDocument.uri - } - }; -} -function asCodeLensParams(textDocument) { - return { - textDocument: { - uri: textDocument.uri - } - }; -} -var init_converter = __esm({ - "src/language-client/utils/converter.ts"() { - init_lodash(); - } -}); - -// src/language-client/utils/uuid.ts -function generateUuid() { - return v4_default(); -} -var init_uuid = __esm({ - "src/language-client/utils/uuid.ts"() { - init_esm_node(); - } -}); - -// src/language-client/client.ts -function createConnection(input, output, errorHandler, closeHandler, options) { - let logger113 = new ConsoleLogger(); - let connection = (0, import_vscode_languageserver_protocol49.createProtocolConnection)(input, output, logger113, options); - connection.onError((data) => { - errorHandler(data[0], data[1], data[2]); - }); - connection.onClose(closeHandler); - let result = { - listen: () => connection.listen(), - sendRequest: (type, ...params) => connection.sendRequest(string(type) ? type : type.method, ...params), - onRequest: (type, handler) => connection.onRequest(string(type) ? type : type.method, handler), - sendNotification: (type, params) => connection.sendNotification(string(type) ? type : type.method, params), - onNotification: (type, handler) => connection.onNotification(string(type) ? type : type.method, handler), - onProgress: connection.onProgress, - sendProgress: connection.sendProgress, - trace: (value, tracer, sendNotificationOrTraceOptions) => { - const defaultTraceOptions = { - sendNotification: false, - traceFormat: import_vscode_languageserver_protocol49.TraceFormat.Text - }; - if (sendNotificationOrTraceOptions === void 0) { - connection.trace(value, tracer, defaultTraceOptions); - } else if (boolean(sendNotificationOrTraceOptions)) { - connection.trace(value, tracer, sendNotificationOrTraceOptions); - } else { - connection.trace(value, tracer, sendNotificationOrTraceOptions); - } - }, - initialize: (params) => connection.sendRequest(import_vscode_languageserver_protocol49.InitializeRequest.type, params), - shutdown: () => connection.sendRequest(import_vscode_languageserver_protocol49.ShutdownRequest.type, void 0), - exit: () => connection.sendNotification(import_vscode_languageserver_protocol49.ExitNotification.type), - onLogMessage: (handler) => connection.onNotification(import_vscode_languageserver_protocol49.LogMessageNotification.type, handler), - onShowMessage: (handler) => connection.onNotification(import_vscode_languageserver_protocol49.ShowMessageNotification.type, handler), - onTelemetry: (handler) => connection.onNotification(import_vscode_languageserver_protocol49.TelemetryEventNotification.type, handler), - didChangeConfiguration: (params) => connection.sendNotification(import_vscode_languageserver_protocol49.DidChangeConfigurationNotification.type, params), - didChangeWatchedFiles: (params) => connection.sendNotification(import_vscode_languageserver_protocol49.DidChangeWatchedFilesNotification.type, params), - didOpenTextDocument: (params) => connection.sendNotification(import_vscode_languageserver_protocol49.DidOpenTextDocumentNotification.type, params), - didChangeTextDocument: (params) => connection.sendNotification(import_vscode_languageserver_protocol49.DidChangeTextDocumentNotification.type, params), - didCloseTextDocument: (params) => connection.sendNotification(import_vscode_languageserver_protocol49.DidCloseTextDocumentNotification.type, params), - didSaveTextDocument: (params) => connection.sendNotification(import_vscode_languageserver_protocol49.DidSaveTextDocumentNotification.type, params), - onDiagnostics: (handler) => connection.onNotification(import_vscode_languageserver_protocol49.PublishDiagnosticsNotification.type, handler), - dispose: () => connection.dispose() - }; - return result; -} -function ensure(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -var import_path17, import_vscode_languageserver_protocol49, import_os7, logger47, ConsoleLogger, NullLogger, ErrorAction, CloseAction, DefaultErrorHandler, RevealOutputChannelOn, State2, ClientState, SupportedSymbolKinds, SupportedCompletionItemKinds, SupportedSymbolTags, DynamicFeature, DocumentNotifications, DidOpenTextDocumentFeature, DidCloseTextDocumentFeature, DidChangeTextDocumentFeature, WillSaveFeature, WillSaveWaitUntilFeature, DidSaveTextDocumentFeature, FileSystemWatcherFeature, TextDocumentFeature, WorkspaceFeature, CompletionItemFeature, HoverFeature, SignatureHelpFeature, DefinitionFeature, ReferencesFeature, DocumentHighlightFeature, DocumentSymbolFeature, WorkspaceSymbolFeature, CodeActionFeature, CodeLensFeature, DocumentFormattingFeature, DocumentRangeFormattingFeature, DocumentOnTypeFormattingFeature, RenameFeature, DocumentLinkFeature, ConfigurationFeature, ExecuteCommandFeature, MessageTransports, OnReady, BaseLanguageClient; -var init_client = __esm({ - "src/language-client/client.ts"() { - import_path17 = __toModule(require("path")); - import_vscode_languageserver_protocol49 = __toModule(require_main2()); - init_esm2(); - init_commands2(); - init_languages(); - init_fs(); - init_is(); - init_lodash(); - init_window(); - init_workspace(); - init_sources2(); - init_progressPart(); - init_async(); - import_os7 = __toModule(require("os")); - init_converter(); - init_uuid(); - logger47 = require_logger2()("language-client-client"); - ConsoleLogger = class { - error(message) { - logger47.error(message); - } - warn(message) { - logger47.warn(message); - } - info(message) { - logger47.info(message); - } - log(message) { - logger47.log(message); - } - }; - NullLogger = class { - error(_message) { - } - warn(_message) { - } - info(_message) { - } - log(_message) { - } - }; - (function(ErrorAction2) { - ErrorAction2[ErrorAction2["Continue"] = 1] = "Continue"; - ErrorAction2[ErrorAction2["Shutdown"] = 2] = "Shutdown"; - })(ErrorAction || (ErrorAction = {})); - (function(CloseAction2) { - CloseAction2[CloseAction2["DoNotRestart"] = 1] = "DoNotRestart"; - CloseAction2[CloseAction2["Restart"] = 2] = "Restart"; - })(CloseAction || (CloseAction = {})); - DefaultErrorHandler = class { - constructor(name2, maxRestartCount) { - this.name = name2; - this.maxRestartCount = maxRestartCount; - this.restarts = []; - } - error(_error, _message, count) { - if (count && count <= 3) { - return 1; - } - return 2; - } - closed() { - this.restarts.push(Date.now()); - if (this.restarts.length < this.maxRestartCount) { - return 2; - } else { - let diff = this.restarts[this.restarts.length - 1] - this.restarts[0]; - if (diff <= 3 * 60 * 1e3) { - window_default.showMessage(`The "${this.name}" server crashed ${this.maxRestartCount} times in the last 3 minutes. The server will not be restarted.`, "error"); - return 1; - } else { - this.restarts.shift(); - return 2; - } - } - } - }; - (function(RevealOutputChannelOn2) { - RevealOutputChannelOn2[RevealOutputChannelOn2["Info"] = 1] = "Info"; - RevealOutputChannelOn2[RevealOutputChannelOn2["Warn"] = 2] = "Warn"; - RevealOutputChannelOn2[RevealOutputChannelOn2["Error"] = 3] = "Error"; - RevealOutputChannelOn2[RevealOutputChannelOn2["Never"] = 4] = "Never"; - })(RevealOutputChannelOn || (RevealOutputChannelOn = {})); - (function(State3) { - State3[State3["Stopped"] = 1] = "Stopped"; - State3[State3["Running"] = 2] = "Running"; - State3[State3["Starting"] = 3] = "Starting"; - })(State2 || (State2 = {})); - (function(ClientState2) { - ClientState2[ClientState2["Initial"] = 0] = "Initial"; - ClientState2[ClientState2["Starting"] = 1] = "Starting"; - ClientState2[ClientState2["StartFailed"] = 2] = "StartFailed"; - ClientState2[ClientState2["Running"] = 3] = "Running"; - ClientState2[ClientState2["Stopping"] = 4] = "Stopping"; - ClientState2[ClientState2["Stopped"] = 5] = "Stopped"; - })(ClientState || (ClientState = {})); - SupportedSymbolKinds = [ - import_vscode_languageserver_protocol49.SymbolKind.File, - import_vscode_languageserver_protocol49.SymbolKind.Module, - import_vscode_languageserver_protocol49.SymbolKind.Namespace, - import_vscode_languageserver_protocol49.SymbolKind.Package, - import_vscode_languageserver_protocol49.SymbolKind.Class, - import_vscode_languageserver_protocol49.SymbolKind.Method, - import_vscode_languageserver_protocol49.SymbolKind.Property, - import_vscode_languageserver_protocol49.SymbolKind.Field, - import_vscode_languageserver_protocol49.SymbolKind.Constructor, - import_vscode_languageserver_protocol49.SymbolKind.Enum, - import_vscode_languageserver_protocol49.SymbolKind.Interface, - import_vscode_languageserver_protocol49.SymbolKind.Function, - import_vscode_languageserver_protocol49.SymbolKind.Variable, - import_vscode_languageserver_protocol49.SymbolKind.Constant, - import_vscode_languageserver_protocol49.SymbolKind.String, - import_vscode_languageserver_protocol49.SymbolKind.Number, - import_vscode_languageserver_protocol49.SymbolKind.Boolean, - import_vscode_languageserver_protocol49.SymbolKind.Array, - import_vscode_languageserver_protocol49.SymbolKind.Object, - import_vscode_languageserver_protocol49.SymbolKind.Key, - import_vscode_languageserver_protocol49.SymbolKind.Null, - import_vscode_languageserver_protocol49.SymbolKind.EnumMember, - import_vscode_languageserver_protocol49.SymbolKind.Struct, - import_vscode_languageserver_protocol49.SymbolKind.Event, - import_vscode_languageserver_protocol49.SymbolKind.Operator, - import_vscode_languageserver_protocol49.SymbolKind.TypeParameter - ]; - SupportedCompletionItemKinds = [ - import_vscode_languageserver_protocol49.CompletionItemKind.Text, - import_vscode_languageserver_protocol49.CompletionItemKind.Method, - import_vscode_languageserver_protocol49.CompletionItemKind.Function, - import_vscode_languageserver_protocol49.CompletionItemKind.Constructor, - import_vscode_languageserver_protocol49.CompletionItemKind.Field, - import_vscode_languageserver_protocol49.CompletionItemKind.Variable, - import_vscode_languageserver_protocol49.CompletionItemKind.Class, - import_vscode_languageserver_protocol49.CompletionItemKind.Interface, - import_vscode_languageserver_protocol49.CompletionItemKind.Module, - import_vscode_languageserver_protocol49.CompletionItemKind.Property, - import_vscode_languageserver_protocol49.CompletionItemKind.Unit, - import_vscode_languageserver_protocol49.CompletionItemKind.Value, - import_vscode_languageserver_protocol49.CompletionItemKind.Enum, - import_vscode_languageserver_protocol49.CompletionItemKind.Keyword, - import_vscode_languageserver_protocol49.CompletionItemKind.Snippet, - import_vscode_languageserver_protocol49.CompletionItemKind.Color, - import_vscode_languageserver_protocol49.CompletionItemKind.File, - import_vscode_languageserver_protocol49.CompletionItemKind.Reference, - import_vscode_languageserver_protocol49.CompletionItemKind.Folder, - import_vscode_languageserver_protocol49.CompletionItemKind.EnumMember, - import_vscode_languageserver_protocol49.CompletionItemKind.Constant, - import_vscode_languageserver_protocol49.CompletionItemKind.Struct, - import_vscode_languageserver_protocol49.CompletionItemKind.Event, - import_vscode_languageserver_protocol49.CompletionItemKind.Operator, - import_vscode_languageserver_protocol49.CompletionItemKind.TypeParameter - ]; - SupportedSymbolTags = [ - import_vscode_languageserver_protocol49.SymbolTag.Deprecated - ]; - (function(DynamicFeature3) { - function is(value) { - let candidate = value; - return candidate && func(candidate.register) && func(candidate.unregister) && func(candidate.dispose) && candidate.registrationType !== void 0; - } - DynamicFeature3.is = is; - })(DynamicFeature || (DynamicFeature = {})); - DocumentNotifications = class { - constructor(_client, _event, _type, _middleware, _createParams, _selectorFilter) { - this._client = _client; - this._event = _event; - this._type = _type; - this._middleware = _middleware; - this._createParams = _createParams; - this._selectorFilter = _selectorFilter; - this._selectors = new Map(); - } - static textDocumentFilter(selectors, textDocument) { - for (const selector of selectors) { - if (workspace_default.match(selector, textDocument) > 0) { - return true; - } - } - return false; - } - register(data) { - if (!data.registerOptions.documentSelector) { - return; - } - if (!this._listener) { - this._listener = this._event(this.callback, this); - } - this._selectors.set(data.id, data.registerOptions.documentSelector); - } - callback(data) { - if (!this._selectorFilter || this._selectorFilter(this._selectors.values(), data)) { - if (this._middleware) { - this._middleware(data, (data2) => this._client.sendNotification(this._type, this._createParams(data2))); - } else { - this._client.sendNotification(this._type, this._createParams(data)); - } - this.notificationSent(data); - } - } - notificationSent(_data) { - } - unregister(id) { - this._selectors.delete(id); - if (this._selectors.size === 0 && this._listener) { - this._listener.dispose(); - this._listener = void 0; - } - } - dispose() { - this._selectors.clear(); - if (this._listener) { - this._listener.dispose(); - this._listener = void 0; - } - } - getProvider(document2) { - for (const selector of this._selectors.values()) { - if (workspace_default.match(selector, document2)) { - return { - send: (data) => { - this.callback(data); - } - }; - } - } - return void 0; - } - }; - DidOpenTextDocumentFeature = class extends DocumentNotifications { - constructor(client, _syncedDocuments) { - super(client, workspace_default.onDidOpenTextDocument, import_vscode_languageserver_protocol49.DidOpenTextDocumentNotification.type, client.clientOptions.middleware.didOpen, (textDocument) => { - return { textDocument: convertToTextDocumentItem(textDocument) }; - }, DocumentNotifications.textDocumentFilter); - this._syncedDocuments = _syncedDocuments; - } - get registrationType() { - return import_vscode_languageserver_protocol49.DidOpenTextDocumentNotification.type; - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "textDocument"), "synchronization").dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; - if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { - this.register({ - id: generateUuid(), - registerOptions: { documentSelector } - }); - } - } - register(data) { - super.register(data); - if (!data.registerOptions.documentSelector) { - return; - } - let documentSelector = data.registerOptions.documentSelector; - workspace_default.textDocuments.forEach((textDocument) => { - let uri = textDocument.uri.toString(); - if (this._syncedDocuments.has(uri)) { - return; - } - if (workspace_default.match(documentSelector, textDocument) > 0) { - let middleware = this._client.clientOptions.middleware; - let didOpen = (textDocument2) => { - this._client.sendNotification(this._type, this._createParams(textDocument2)); - }; - if (middleware.didOpen) { - middleware.didOpen(textDocument, didOpen); - } else { - didOpen(textDocument); - } - this._syncedDocuments.set(uri, textDocument); - } - }); - } - notificationSent(textDocument) { - super.notificationSent(textDocument); - this._syncedDocuments.set(textDocument.uri.toString(), textDocument); - } - }; - DidCloseTextDocumentFeature = class extends DocumentNotifications { - constructor(client, _syncedDocuments) { - super(client, workspace_default.onDidCloseTextDocument, import_vscode_languageserver_protocol49.DidCloseTextDocumentNotification.type, client.clientOptions.middleware.didClose, (textDocument) => asCloseTextDocumentParams(textDocument), DocumentNotifications.textDocumentFilter); - this._syncedDocuments = _syncedDocuments; - } - get registrationType() { - return import_vscode_languageserver_protocol49.DidCloseTextDocumentNotification.type; - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "textDocument"), "synchronization").dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; - if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { - this.register({ - id: generateUuid(), - registerOptions: { documentSelector } - }); - } - } - notificationSent(textDocument) { - super.notificationSent(textDocument); - this._syncedDocuments.delete(textDocument.uri.toString()); - } - unregister(id) { - let selector = this._selectors.get(id); - super.unregister(id); - let selectors = this._selectors.values(); - this._syncedDocuments.forEach((textDocument) => { - if (workspace_default.match(selector, textDocument) > 0 && !this._selectorFilter(selectors, textDocument)) { - let middleware = this._client.clientOptions.middleware; - let didClose = (textDocument2) => { - this._client.sendNotification(this._type, this._createParams(textDocument2)); - }; - this._syncedDocuments.delete(textDocument.uri.toString()); - if (middleware.didClose) { - middleware.didClose(textDocument, didClose); - } else { - didClose(textDocument); - } - } - }); - } - }; - DidChangeTextDocumentFeature = class { - constructor(_client) { - this._client = _client; - this._changeData = new Map(); - } - get registrationType() { - return import_vscode_languageserver_protocol49.DidChangeTextDocumentNotification.type; - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "textDocument"), "synchronization").dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; - if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.change !== void 0 && textDocumentSyncOptions.change !== import_vscode_languageserver_protocol49.TextDocumentSyncKind.None) { - this.register({ - id: generateUuid(), - registerOptions: Object.assign({}, { documentSelector }, { syncKind: textDocumentSyncOptions.change }) - }); - } - } - register(data) { - if (!data.registerOptions.documentSelector) { - return; - } - if (!this._listener) { - this._listener = workspace_default.onDidChangeTextDocument(this.callback, this); - } - this._changeData.set(data.id, { - documentSelector: data.registerOptions.documentSelector, - syncKind: data.registerOptions.syncKind - }); - } - callback(event) { - if (event.contentChanges.length === 0) { - return; - } - let doc = workspace_default.getDocument(event.textDocument.uri); - if (!doc) - return; - let { textDocument } = doc; - for (const changeData of this._changeData.values()) { - if (workspace_default.match(changeData.documentSelector, textDocument) > 0) { - let middleware = this._client.clientOptions.middleware; - if (changeData.syncKind === import_vscode_languageserver_protocol49.TextDocumentSyncKind.Incremental) { - if (middleware.didChange) { - middleware.didChange(event, () => this._client.sendNotification(import_vscode_languageserver_protocol49.DidChangeTextDocumentNotification.type, omit(event, ["bufnr", "original"]))); - } else { - this._client.sendNotification(import_vscode_languageserver_protocol49.DidChangeTextDocumentNotification.type, omit(event, ["bufnr", "original"])); - } - } else if (changeData.syncKind === import_vscode_languageserver_protocol49.TextDocumentSyncKind.Full) { - let didChange = (event2) => { - let { textDocument: textDocument2 } = workspace_default.getDocument(event2.textDocument.uri); - this._client.sendNotification(import_vscode_languageserver_protocol49.DidChangeTextDocumentNotification.type, asChangeTextDocumentParams(textDocument2)); - }; - if (middleware.didChange) { - middleware.didChange(event, didChange); - } else { - didChange(event); - } - } - } - } - } - unregister(id) { - this._changeData.delete(id); - if (this._changeData.size === 0 && this._listener) { - this._listener.dispose(); - this._listener = void 0; - } - } - dispose() { - this._changeData.clear(); - if (this._listener) { - this._listener.dispose(); - this._listener = void 0; - } - } - getProvider(document2) { - for (const changeData of this._changeData.values()) { - if (workspace_default.match(changeData.documentSelector, document2)) { - return { - send: (event) => { - this.callback(event); - } - }; - } - } - return void 0; - } - }; - WillSaveFeature = class extends DocumentNotifications { - constructor(client) { - super(client, workspace_default.onWillSaveTextDocument, import_vscode_languageserver_protocol49.WillSaveTextDocumentNotification.type, client.clientOptions.middleware.willSave, (willSaveEvent) => asWillSaveTextDocumentParams(willSaveEvent), (selectors, willSaveEvent) => DocumentNotifications.textDocumentFilter(selectors, willSaveEvent.document)); - } - get registrationType() { - return import_vscode_languageserver_protocol49.WillSaveTextDocumentNotification.type; - } - fillClientCapabilities(capabilities) { - let value = ensure(ensure(capabilities, "textDocument"), "synchronization"); - value.willSave = true; - } - initialize(capabilities, documentSelector) { - let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; - if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSave) { - this.register({ - id: generateUuid(), - registerOptions: { documentSelector } - }); - } - } - }; - WillSaveWaitUntilFeature = class { - constructor(_client) { - this._client = _client; - this._selectors = new Map(); - } - get registrationType() { - return import_vscode_languageserver_protocol49.WillSaveTextDocumentWaitUntilRequest.type; - } - fillClientCapabilities(capabilities) { - let value = ensure(ensure(capabilities, "textDocument"), "synchronization"); - value.willSaveWaitUntil = true; - } - initialize(capabilities, documentSelector) { - let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; - if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSaveWaitUntil) { - this.register({ - id: generateUuid(), - registerOptions: { documentSelector } - }); - } - } - register(data) { - if (!data.registerOptions.documentSelector) { - return; - } - if (!this._listener) { - this._listener = workspace_default.onWillSaveTextDocument(this.callback, this); - } - this._selectors.set(data.id, data.registerOptions.documentSelector); - } - callback(event) { - if (DocumentNotifications.textDocumentFilter(this._selectors.values(), event.document)) { - let middleware = this._client.clientOptions.middleware; - let willSaveWaitUntil = (event2) => { - return this._client.sendRequest(import_vscode_languageserver_protocol49.WillSaveTextDocumentWaitUntilRequest.type, asWillSaveTextDocumentParams(event2)).then((edits) => { - return edits ? edits : []; - }, (e) => { - window_default.showMessage(`Error on willSaveWaitUntil: ${e}`, "error"); - logger47.error(e); - return []; - }); - }; - event.waitUntil(middleware.willSaveWaitUntil ? middleware.willSaveWaitUntil(event, willSaveWaitUntil) : willSaveWaitUntil(event)); - } - } - unregister(id) { - this._selectors.delete(id); - if (this._selectors.size === 0 && this._listener) { - this._listener.dispose(); - this._listener = void 0; - } - } - dispose() { - this._selectors.clear(); - if (this._listener) { - this._listener.dispose(); - this._listener = void 0; - } - } - }; - DidSaveTextDocumentFeature = class extends DocumentNotifications { - constructor(client) { - super(client, workspace_default.onDidSaveTextDocument, import_vscode_languageserver_protocol49.DidSaveTextDocumentNotification.type, client.clientOptions.middleware.didSave, (textDocument) => asSaveTextDocumentParams(textDocument, this._includeText), DocumentNotifications.textDocumentFilter); - this._includeText = false; - } - get registrationType() { - return import_vscode_languageserver_protocol49.DidSaveTextDocumentNotification.type; - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "textDocument"), "synchronization").didSave = true; - } - initialize(capabilities, documentSelector) { - const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; - if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.save) { - const saveOptions = typeof textDocumentSyncOptions.save === "boolean" ? { includeText: false } : { includeText: !!textDocumentSyncOptions.save.includeText }; - this.register({ - id: generateUuid(), - registerOptions: Object.assign({}, { documentSelector }, saveOptions) - }); - } - } - register(data) { - this._includeText = !!data.registerOptions.includeText; - super.register(data); - } - }; - FileSystemWatcherFeature = class { - constructor(_client, _notifyFileEvent) { - this._notifyFileEvent = _notifyFileEvent; - this._watchers = new Map(); - } - get registrationType() { - return import_vscode_languageserver_protocol49.DidChangeWatchedFilesNotification.type; - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "workspace"), "didChangeWatchedFiles").dynamicRegistration = true; - } - initialize(_capabilities, _documentSelector) { - } - register(data) { - if (!Array.isArray(data.registerOptions.watchers)) { - return; - } - let disposables = []; - for (let watcher of data.registerOptions.watchers) { - if (!string(watcher.globPattern)) { - continue; - } - let watchCreate = true, watchChange = true, watchDelete = true; - if (watcher.kind != null) { - watchCreate = (watcher.kind & import_vscode_languageserver_protocol49.WatchKind.Create) !== 0; - watchChange = (watcher.kind & import_vscode_languageserver_protocol49.WatchKind.Change) != 0; - watchDelete = (watcher.kind & import_vscode_languageserver_protocol49.WatchKind.Delete) != 0; - } - let fileSystemWatcher = workspace_default.createFileSystemWatcher(watcher.globPattern, !watchCreate, !watchChange, !watchDelete); - this.hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, disposables); - disposables.push(fileSystemWatcher); - } - this._watchers.set(data.id, disposables); - } - registerRaw(id, fileSystemWatchers) { - let disposables = []; - for (let fileSystemWatcher of fileSystemWatchers) { - disposables.push(fileSystemWatcher); - this.hookListeners(fileSystemWatcher, true, true, true, disposables); - } - this._watchers.set(id, disposables); - } - hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, listeners) { - if (watchCreate) { - fileSystemWatcher.onDidCreate((resource) => this._notifyFileEvent({ - uri: asUri(resource), - type: import_vscode_languageserver_protocol49.FileChangeType.Created - }), null, listeners); - } - if (watchChange) { - fileSystemWatcher.onDidChange((resource) => this._notifyFileEvent({ - uri: asUri(resource), - type: import_vscode_languageserver_protocol49.FileChangeType.Changed - }), null, listeners); - } - if (watchDelete) { - fileSystemWatcher.onDidDelete((resource) => this._notifyFileEvent({ - uri: asUri(resource), - type: import_vscode_languageserver_protocol49.FileChangeType.Deleted - }), null, listeners); - } - } - unregister(id) { - let disposables = this._watchers.get(id); - if (disposables) { - for (let disposable of disposables) { - disposable.dispose(); - } - } - } - dispose() { - this._watchers.forEach((disposables) => { - for (let disposable of disposables) { - disposable.dispose(); - } - }); - this._watchers.clear(); - } - }; - TextDocumentFeature = class { - constructor(_client, _registrationType) { - this._client = _client; - this._registrationType = _registrationType; - this._registrations = new Map(); - } - get registrationType() { - return this._registrationType; - } - register(data) { - if (!data.registerOptions.documentSelector) { - return; - } - let registration = this.registerLanguageProvider(data.registerOptions); - this._registrations.set(data.id, { disposable: registration[0], data, provider: registration[1] }); - } - unregister(id) { - let registration = this._registrations.get(id); - if (registration) { - registration.disposable.dispose(); - } - } - dispose() { - this._registrations.forEach((value) => { - value.disposable.dispose(); - }); - this._registrations.clear(); - } - getRegistration(documentSelector, capability) { - if (!capability) { - return [void 0, void 0]; - } else if (import_vscode_languageserver_protocol49.TextDocumentRegistrationOptions.is(capability)) { - const id = import_vscode_languageserver_protocol49.StaticRegistrationOptions.hasId(capability) ? capability.id : generateUuid(); - const selector = capability.documentSelector || documentSelector; - if (selector) { - return [id, Object.assign({}, capability, { documentSelector: selector })]; - } - } else if (boolean(capability) && capability === true || import_vscode_languageserver_protocol49.WorkDoneProgressOptions.is(capability)) { - if (!documentSelector) { - return [void 0, void 0]; - } - let options = boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector }); - return [generateUuid(), options]; - } - return [void 0, void 0]; - } - getRegistrationOptions(documentSelector, capability) { - if (!documentSelector || !capability) { - return void 0; - } - return boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector }); - } - getProvider(textDocument) { - for (const registration of this._registrations.values()) { - let selector = registration.data.registerOptions.documentSelector; - if (selector !== null && workspace_default.match(selector, textDocument) > 0) { - return registration.provider; - } - } - return void 0; - } - getAllProviders() { - const result = []; - for (const item of this._registrations.values()) { - result.push(item.provider); - } - return result; - } - }; - WorkspaceFeature = class { - constructor(_client, _registrationType) { - this._client = _client; - this._registrationType = _registrationType; - this._registrations = new Map(); - } - get registrationType() { - return this._registrationType; - } - register(data) { - const registration = this.registerLanguageProvider(data.registerOptions); - this._registrations.set(data.id, { disposable: registration[0], provider: registration[1] }); - } - unregister(id) { - const registration = this._registrations.get(id); - if (registration) - registration.disposable.dispose(); - } - dispose() { - this._registrations.forEach((value) => { - value.disposable.dispose(); - }); - this._registrations.clear(); - } - getProviders() { - const result = []; - for (const registration of this._registrations.values()) { - result.push(registration.provider); - } - return result; - } - }; - CompletionItemFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.CompletionRequest.type); - } - fillClientCapabilities(capabilities) { - let snippetSupport = this._client.clientOptions.disableSnippetCompletion !== true; - let completion = ensure(ensure(capabilities, "textDocument"), "completion"); - completion.dynamicRegistration = true; - completion.contextSupport = true; - completion.completionItem = { - snippetSupport, - commitCharactersSupport: true, - documentationFormat: this._client.supporedMarkupKind, - deprecatedSupport: true, - preselectSupport: true, - insertReplaceSupport: true, - tagSupport: { valueSet: [import_vscode_languageserver_protocol49.CompletionItemTag.Deprecated] }, - resolveSupport: { properties: ["documentation", "detail", "additionalTextEdits"] }, - insertTextModeSupport: { valueSet: [import_vscode_languageserver_protocol49.InsertTextMode.asIs, import_vscode_languageserver_protocol49.InsertTextMode.adjustIndentation] } - }; - completion.completionItemKind = { valueSet: SupportedCompletionItemKinds }; - } - initialize(capabilities, documentSelector) { - this.index = 0; - const options = this.getRegistrationOptions(documentSelector, capabilities.completionProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - let triggerCharacters = options.triggerCharacters || []; - let allCommitCharacters = options.allCommitCharacters || []; - let priority = options.priority; - const provider = { - provideCompletionItems: (document2, position, token, context) => { - const client = this._client; - const middleware = this._client.clientOptions.middleware; - const provideCompletionItems = (document3, position2, context2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.CompletionRequest.type, asCompletionParams(document3, position2, context2), token2).then((result) => result, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.CompletionRequest.type, token2, error, null); - }); - }; - return middleware.provideCompletionItem ? middleware.provideCompletionItem(document2, position, context, token, provideCompletionItems) : provideCompletionItems(document2, position, context, token); - }, - resolveCompletionItem: options.resolveProvider ? (item, token) => { - const client = this._client; - const middleware = this._client.clientOptions.middleware; - const resolveCompletionItem = (item2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.CompletionResolveRequest.type, item2, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.CompletionResolveRequest.type, token2, error, item2); - }); - }; - return middleware.resolveCompletionItem ? middleware.resolveCompletionItem(item, token, resolveCompletionItem) : resolveCompletionItem(item, token); - } : void 0 - }; - let name2 = this._client.id + (this.index ? "-" + this.index : ""); - sources_default.removeSource(name2); - const disposable = languages_default.registerCompletionItemProvider(name2, "LS", options.documentSelector || this._client.clientOptions.documentSelector, provider, triggerCharacters, priority, allCommitCharacters); - this.index = this.index + 1; - return [disposable, provider]; - } - }; - HoverFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.HoverRequest.type); - } - fillClientCapabilities(capabilities) { - const hoverCapability = ensure(ensure(capabilities, "textDocument"), "hover"); - hoverCapability.dynamicRegistration = true; - hoverCapability.contentFormat = this._client.supporedMarkupKind; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.hoverProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideHover: (document2, position, token) => { - const client = this._client; - const provideHover = (document3, position2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.HoverRequest.type, asTextDocumentPositionParams(document3, position2), token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.HoverRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideHover ? middleware.provideHover(document2, position, token, provideHover) : provideHover(document2, position, token); - } - }; - return [languages_default.registerHoverProvider(options.documentSelector, provider), provider]; - } - }; - SignatureHelpFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.SignatureHelpRequest.type); - } - fillClientCapabilities(capabilities) { - let config = ensure(ensure(capabilities, "textDocument"), "signatureHelp"); - config.dynamicRegistration = true; - config.contextSupport = true; - config.signatureInformation = { - documentationFormat: this._client.supporedMarkupKind, - activeParameterSupport: true, - parameterInformation: { - labelOffsetSupport: true - } - }; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.signatureHelpProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideSignatureHelp: (document2, position, token, context) => { - const client = this._client; - const providerSignatureHelp = (document3, position2, context2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.SignatureHelpRequest.type, asSignatureHelpParams(document3, position2, context2), token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.SignatureHelpRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideSignatureHelp ? middleware.provideSignatureHelp(document2, position, context, token, providerSignatureHelp) : providerSignatureHelp(document2, position, context, token); - } - }; - const triggerCharacters = options.triggerCharacters || []; - const disposable = languages_default.registerSignatureHelpProvider(options.documentSelector, provider, triggerCharacters); - return [disposable, provider]; - } - }; - DefinitionFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.DefinitionRequest.type); - } - fillClientCapabilities(capabilities) { - let definitionSupport = ensure(ensure(capabilities, "textDocument"), "definition"); - definitionSupport.dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.definitionProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideDefinition: (document2, position, token) => { - const client = this._client; - const provideDefinition = (document3, position2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.DefinitionRequest.type, asTextDocumentPositionParams(document3, position2), token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.DefinitionRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideDefinition ? middleware.provideDefinition(document2, position, token, provideDefinition) : provideDefinition(document2, position, token); - } - }; - return [languages_default.registerDefinitionProvider(options.documentSelector, provider), provider]; - } - }; - ReferencesFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.ReferencesRequest.type); - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "textDocument"), "references").dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.referencesProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideReferences: (document2, position, options2, token) => { - const client = this._client; - const _providerReferences = (document3, position2, options3, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.ReferencesRequest.type, asReferenceParams(document3, position2, options3), token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.ReferencesRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideReferences ? middleware.provideReferences(document2, position, options2, token, _providerReferences) : _providerReferences(document2, position, options2, token); - } - }; - return [languages_default.registerReferencesProvider(options.documentSelector, provider), provider]; - } - }; - DocumentHighlightFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.DocumentHighlightRequest.type); - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "textDocument"), "documentHighlight").dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentHighlightProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideDocumentHighlights: (document2, position, token) => { - const client = this._client; - const _provideDocumentHighlights = (document3, position2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.DocumentHighlightRequest.type, asTextDocumentPositionParams(document3, position2), token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.DocumentHighlightRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideDocumentHighlights ? middleware.provideDocumentHighlights(document2, position, token, _provideDocumentHighlights) : _provideDocumentHighlights(document2, position, token); - } - }; - return [languages_default.registerDocumentHighlightProvider(options.documentSelector, provider), provider]; - } - }; - DocumentSymbolFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.DocumentSymbolRequest.type); - } - fillClientCapabilities(capabilities) { - let symbolCapabilities = ensure(ensure(capabilities, "textDocument"), "documentSymbol"); - symbolCapabilities.dynamicRegistration = true; - symbolCapabilities.symbolKind = { - valueSet: SupportedSymbolKinds - }; - symbolCapabilities.hierarchicalDocumentSymbolSupport = true; - symbolCapabilities.tagSupport = { - valueSet: SupportedSymbolTags - }; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentSymbolProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideDocumentSymbols: (document2, token) => { - const client = this._client; - const _provideDocumentSymbols = (document3, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.DocumentSymbolRequest.type, asDocumentSymbolParams(document3), token2).then((data) => { - if (data === null) { - return void 0; - } - if (data.length === 0) { - return []; - } else { - let element = data[0]; - if (import_vscode_languageserver_protocol49.DocumentSymbol.is(element)) { - return data; - } else { - return data; - } - } - }, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.DocumentSymbolRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideDocumentSymbols ? middleware.provideDocumentSymbols(document2, token, _provideDocumentSymbols) : _provideDocumentSymbols(document2, token); - } - }; - const metadata = options.label ? { label: options.label } : void 0; - return [languages_default.registerDocumentSymbolProvider(options.documentSelector, provider, metadata), provider]; - } - }; - WorkspaceSymbolFeature = class extends WorkspaceFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.WorkspaceSymbolRequest.type); - } - fillClientCapabilities(capabilities) { - let symbolCapabilities = ensure(ensure(capabilities, "workspace"), "symbol"); - symbolCapabilities.dynamicRegistration = true; - symbolCapabilities.symbolKind = { - valueSet: SupportedSymbolKinds - }; - symbolCapabilities.tagSupport = { - valueSet: SupportedSymbolTags - }; - } - initialize(capabilities) { - if (!capabilities.workspaceSymbolProvider) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: capabilities.workspaceSymbolProvider === true ? { workDoneProgress: false } : capabilities.workspaceSymbolProvider - }); - } - registerLanguageProvider(_options) { - const provider = { - provideWorkspaceSymbols: (query, token) => { - const client = this._client; - const provideWorkspaceSymbols = (query2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.WorkspaceSymbolRequest.type, { query: query2 }, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.WorkspaceSymbolRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideWorkspaceSymbols ? middleware.provideWorkspaceSymbols(query, token, provideWorkspaceSymbols) : provideWorkspaceSymbols(query, token); - } - }; - return [languages_default.registerWorkspaceSymbolProvider(provider), provider]; - } - }; - CodeActionFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.CodeActionRequest.type); - this.disposables = []; - } - fillClientCapabilities(capabilities) { - const cap = ensure(ensure(capabilities, "textDocument"), "codeAction"); - cap.dynamicRegistration = true; - cap.isPreferredSupport = true; - cap.disabledSupport = true; - cap.dataSupport = true; - cap.honorsChangeAnnotations = false; - cap.resolveSupport = { - properties: ["edit"] - }; - cap.codeActionLiteralSupport = { - codeActionKind: { - valueSet: [ - import_vscode_languageserver_protocol49.CodeActionKind.Empty, - import_vscode_languageserver_protocol49.CodeActionKind.QuickFix, - import_vscode_languageserver_protocol49.CodeActionKind.Refactor, - import_vscode_languageserver_protocol49.CodeActionKind.RefactorExtract, - import_vscode_languageserver_protocol49.CodeActionKind.RefactorInline, - import_vscode_languageserver_protocol49.CodeActionKind.RefactorRewrite, - import_vscode_languageserver_protocol49.CodeActionKind.Source, - import_vscode_languageserver_protocol49.CodeActionKind.SourceOrganizeImports - ] - } - }; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.codeActionProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const registCommand = (id) => { - if (commands_default.has(id)) - return; - const client = this._client; - const executeCommand = (command, args) => { - const params = { - command, - arguments: args - }; - return client.sendRequest(import_vscode_languageserver_protocol49.ExecuteCommandRequest.type, params).then(void 0, (error) => { - client.handleFailedRequest(import_vscode_languageserver_protocol49.ExecuteCommandRequest.type, void 0, error, void 0); - throw error; - }); - }; - const middleware = client.clientOptions.middleware; - this.disposables.push(commands_default.registerCommand(id, (...args) => { - return middleware.executeCommand ? middleware.executeCommand(id, args, executeCommand) : executeCommand(id, args); - }, null, true)); - }; - const provider = { - provideCodeActions: (document2, range, context, token) => { - const client = this._client; - const _provideCodeActions = (document3, range2, context2, token2) => { - const params = { - textDocument: { - uri: document3.uri - }, - range: range2, - context: context2 - }; - return client.sendRequest(import_vscode_languageserver_protocol49.CodeActionRequest.type, params, token2).then((values) => { - if (values === null) { - return void 0; - } - values.forEach((val) => { - var _a2; - let cmd = import_vscode_languageserver_protocol49.Command.is(val) ? val.command : (_a2 = val.command) == null ? void 0 : _a2.command; - if (cmd && !commands_default.has(cmd)) - registCommand(cmd); - }); - return values; - }, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.CodeActionRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideCodeActions ? middleware.provideCodeActions(document2, range, context, token, _provideCodeActions) : _provideCodeActions(document2, range, context, token); - }, - resolveCodeAction: options.resolveProvider ? (item, token) => { - const client = this._client; - const middleware = this._client.clientOptions.middleware; - const resolveCodeAction = (item2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.CodeActionResolveRequest.type, item2, token2).then((values) => values, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.CodeActionResolveRequest.type, token2, error, item2); - }); - }; - return middleware.resolveCodeAction ? middleware.resolveCodeAction(item, token, resolveCodeAction) : resolveCodeAction(item, token); - } : void 0 - }; - return [languages_default.registerCodeActionProvider(options.documentSelector, provider, this._client.id, options.codeActionKinds), provider]; - } - dispose() { - this.disposables.forEach((o) => { - o.dispose(); - }); - this.disposables = []; - super.dispose(); - } - }; - CodeLensFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.CodeLensRequest.type); - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "textDocument"), "codeLens").dynamicRegistration = true; - ensure(ensure(capabilities, "workspace"), "codeLens").refreshSupport = true; - } - initialize(capabilities, documentSelector) { - const client = this._client; - client.onRequest(import_vscode_languageserver_protocol49.CodeLensRefreshRequest.type, async () => { - for (const provider of this.getAllProviders()) { - provider.onDidChangeCodeLensEmitter.fire(); - } - }); - const options = this.getRegistrationOptions(documentSelector, capabilities.codeLensProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const emitter = new import_vscode_languageserver_protocol49.Emitter(); - const provider = { - onDidChangeCodeLenses: emitter.event, - provideCodeLenses: (document2, token) => { - const client = this._client; - const provideCodeLenses = (document3, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.CodeLensRequest.type, asCodeLensParams(document3), token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.CodeLensRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideCodeLenses ? middleware.provideCodeLenses(document2, token, provideCodeLenses) : provideCodeLenses(document2, token); - }, - resolveCodeLens: options.resolveProvider ? (codeLens, token) => { - const client = this._client; - const resolveCodeLens = (codeLens2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.CodeLensResolveRequest.type, codeLens2, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.CodeLensResolveRequest.type, token2, error, codeLens2); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.resolveCodeLens ? middleware.resolveCodeLens(codeLens, token, resolveCodeLens) : resolveCodeLens(codeLens, token); - } : void 0 - }; - return [languages_default.registerCodeLensProvider(options.documentSelector, provider), { provider, onDidChangeCodeLensEmitter: emitter }]; - } - }; - DocumentFormattingFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.DocumentFormattingRequest.type); - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "textDocument"), "formatting").dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentFormattingProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideDocumentFormattingEdits: (document2, options2, token) => { - const client = this._client; - const provideDocumentFormattingEdits = (document3, options3, token2) => { - const params = { - textDocument: { uri: document3.uri }, - options: options3 - }; - return client.sendRequest(import_vscode_languageserver_protocol49.DocumentFormattingRequest.type, params, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.DocumentFormattingRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideDocumentFormattingEdits ? middleware.provideDocumentFormattingEdits(document2, options2, token, provideDocumentFormattingEdits) : provideDocumentFormattingEdits(document2, options2, token); - } - }; - return [ - languages_default.registerDocumentFormatProvider(options.documentSelector, provider, this._client.clientOptions.formatterPriority), - provider - ]; - } - }; - DocumentRangeFormattingFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.DocumentRangeFormattingRequest.type); - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "textDocument"), "rangeFormatting").dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentRangeFormattingProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideDocumentRangeFormattingEdits: (document2, range, options2, token) => { - const client = this._client; - const provideDocumentRangeFormattingEdits = (document3, range2, options3, token2) => { - const params = { - textDocument: { uri: document3.uri }, - range: range2, - options: options3 - }; - return client.sendRequest(import_vscode_languageserver_protocol49.DocumentRangeFormattingRequest.type, params, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.DocumentRangeFormattingRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideDocumentRangeFormattingEdits ? middleware.provideDocumentRangeFormattingEdits(document2, range, options2, token, provideDocumentRangeFormattingEdits) : provideDocumentRangeFormattingEdits(document2, range, options2, token); - } - }; - return [languages_default.registerDocumentRangeFormatProvider(options.documentSelector, provider), provider]; - } - }; - DocumentOnTypeFormattingFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.DocumentOnTypeFormattingRequest.type); - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "textDocument"), "onTypeFormatting").dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentOnTypeFormattingProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideOnTypeFormattingEdits: (document2, position, ch, options2, token) => { - const client = this._client; - const provideOnTypeFormattingEdits = (document3, position2, ch2, options3, token2) => { - const params = { - textDocument: asVersionedTextDocumentIdentifier(document3), - position: position2, - ch: ch2, - options: options3 - }; - return client.sendRequest(import_vscode_languageserver_protocol49.DocumentOnTypeFormattingRequest.type, params, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.DocumentOnTypeFormattingRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideOnTypeFormattingEdits ? middleware.provideOnTypeFormattingEdits(document2, position, ch, options2, token, provideOnTypeFormattingEdits) : provideOnTypeFormattingEdits(document2, position, ch, options2, token); - } - }; - const moreTriggerCharacter = options.moreTriggerCharacter || []; - const characters = [options.firstTriggerCharacter, ...moreTriggerCharacter]; - return [languages_default.registerOnTypeFormattingEditProvider(options.documentSelector, provider, characters), provider]; - } - }; - RenameFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.RenameRequest.type); - } - fillClientCapabilities(capabilities) { - let rename = ensure(ensure(capabilities, "textDocument"), "rename"); - rename.dynamicRegistration = true; - rename.prepareSupport = true; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.renameProvider); - if (!options) { - return; - } - if (boolean(capabilities.renameProvider)) { - options.prepareProvider = false; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideRenameEdits: (document2, position, newName, token) => { - const client = this._client; - const provideRenameEdits = (document3, position2, newName2, token2) => { - const params = { - textDocument: { uri: document3.uri }, - position: position2, - newName: newName2 - }; - return client.sendRequest(import_vscode_languageserver_protocol49.RenameRequest.type, params, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.RenameRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideRenameEdits ? middleware.provideRenameEdits(document2, position, newName, token, provideRenameEdits) : provideRenameEdits(document2, position, newName, token); - }, - prepareRename: options.prepareProvider ? (document2, position, token) => { - const client = this._client; - const prepareRename = (document3, position2, token2) => { - const params = { - textDocument: asTextDocumentIdentifier(document3), - position: position2 - }; - return client.sendRequest(import_vscode_languageserver_protocol49.PrepareRenameRequest.type, params, token2).then((result) => { - if (import_vscode_languageserver_protocol49.Range.is(result)) { - return result; - } else if (this.isDefaultBehavior(result)) { - return result.defaultBehavior === true ? null : Promise.reject(new Error(`The element can't be renamed.`)); - } else if (result && import_vscode_languageserver_protocol49.Range.is(result.range)) { - return { - range: result.range, - placeholder: result.placeholder - }; - } - return Promise.reject(new Error(`The element can't be renamed.`)); - }, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.PrepareRenameRequest.type, token2, error, void 0); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.prepareRename ? middleware.prepareRename(document2, position, token, prepareRename) : prepareRename(document2, position, token); - } : void 0 - }; - return [languages_default.registerRenameProvider(options.documentSelector, provider), provider]; - } - isDefaultBehavior(value) { - const candidate = value; - return candidate && boolean(candidate.defaultBehavior); - } - }; - DocumentLinkFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol49.DocumentLinkRequest.type); - } - fillClientCapabilities(capabilities) { - const documentLinkCapabilities = ensure(ensure(capabilities, "textDocument"), "documentLink"); - documentLinkCapabilities.dynamicRegistration = true; - documentLinkCapabilities.tooltipSupport = true; - } - initialize(capabilities, documentSelector) { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentLinkProvider); - if (!options) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: options - }); - } - registerLanguageProvider(options) { - const provider = { - provideDocumentLinks: (document2, token) => { - const client = this._client; - const provideDocumentLinks = (document3, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.DocumentLinkRequest.type, { - textDocument: { uri: document3.uri } - }, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.DocumentLinkRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideDocumentLinks ? middleware.provideDocumentLinks(document2, token, provideDocumentLinks) : provideDocumentLinks(document2, token); - }, - resolveDocumentLink: options.resolveProvider ? (link, token) => { - const client = this._client; - let resolveDocumentLink = (link2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol49.DocumentLinkResolveRequest.type, link2, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol49.DocumentLinkResolveRequest.type, token2, error, link2); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.resolveDocumentLink ? middleware.resolveDocumentLink(link, token, resolveDocumentLink) : resolveDocumentLink(link, token); - } : void 0 - }; - return [languages_default.registerDocumentLinkProvider(options.documentSelector, provider), provider]; - } - }; - ConfigurationFeature = class { - constructor(_client) { - this._client = _client; - this._listeners = new Map(); - } - get registrationType() { - return import_vscode_languageserver_protocol49.DidChangeConfigurationNotification.type; - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "workspace"), "didChangeConfiguration").dynamicRegistration = true; - } - initialize() { - var _a2; - let section2 = (_a2 = this._client.clientOptions.synchronize) == null ? void 0 : _a2.configurationSection; - if (section2 !== void 0) { - this.register({ - id: generateUuid(), - registerOptions: { - section: section2 - } - }); - } - } - register(data) { - let { section: section2 } = data.registerOptions; - let disposable = workspace_default.onDidChangeConfiguration((event) => { - if (typeof section2 == "string" && !event.affectsConfiguration(section2)) { - return; - } - if (Array.isArray(section2) && !section2.some((v) => event.affectsConfiguration(v))) { - return; - } - if (section2 != void 0) { - this.onDidChangeConfiguration(data.registerOptions.section); - } - }); - this._listeners.set(data.id, disposable); - if (string(section2) && section2.endsWith(".settings")) { - let settings = this.getConfiguredSettings(section2); - if (!settings || emptyObject(settings)) - return; - } - if (section2 != void 0) { - this.onDidChangeConfiguration(data.registerOptions.section); - } - } - unregister(id) { - let disposable = this._listeners.get(id); - if (disposable) { - this._listeners.delete(id); - disposable.dispose(); - } - } - dispose() { - for (let disposable of this._listeners.values()) { - disposable.dispose(); - } - this._listeners.clear(); - } - onDidChangeConfiguration(configurationSection) { - let isConfigured = typeof configurationSection === "string" && configurationSection.startsWith("languageserver."); - let sections; - if (string(configurationSection)) { - sections = [configurationSection]; - } else { - sections = configurationSection; - } - let didChangeConfiguration = (sections2) => { - if (sections2 === void 0) { - this._client.sendNotification(import_vscode_languageserver_protocol49.DidChangeConfigurationNotification.type, { settings: null }); - return; - } - this._client.sendNotification(import_vscode_languageserver_protocol49.DidChangeConfigurationNotification.type, { - settings: isConfigured ? this.getConfiguredSettings(sections2[0]) : this.extractSettingsInformation(sections2) - }); - }; - let middleware = this.getMiddleware(); - middleware ? middleware(sections, didChangeConfiguration) : didChangeConfiguration(sections); - } - getConfiguredSettings(key) { - let len = ".settings".length; - let config = workspace_default.getConfiguration(key.slice(0, -len)); - return config.get("settings", {}); - } - extractSettingsInformation(keys) { - function ensurePath(config, path36) { - let current = config; - for (let i = 0; i < path36.length - 1; i++) { - let obj = current[path36[i]]; - if (!obj) { - obj = Object.create(null); - current[path36[i]] = obj; - } - current = obj; - } - return current; - } - let result = Object.create(null); - for (let i = 0; i < keys.length; i++) { - let key = keys[i]; - let index = key.indexOf("."); - let config = null; - if (index >= 0) { - config = workspace_default.getConfiguration(key.substr(0, index)).get(key.substr(index + 1)); - } else { - config = workspace_default.getConfiguration(key); - } - if (config) { - let path36 = keys[i].split("."); - ensurePath(result, path36)[path36[path36.length - 1]] = config; - } - } - return result; - } - getMiddleware() { - let middleware = this._client.clientOptions.middleware; - if (middleware.workspace && middleware.workspace.didChangeConfiguration) { - return middleware.workspace.didChangeConfiguration; - } else { - return void 0; - } - } - }; - ExecuteCommandFeature = class { - constructor(_client) { - this._client = _client; - this._commands = new Map(); - } - get registrationType() { - return import_vscode_languageserver_protocol49.ExecuteCommandRequest.type; - } - fillClientCapabilities(capabilities) { - ensure(ensure(capabilities, "workspace"), "executeCommand").dynamicRegistration = true; - } - initialize(capabilities) { - if (!capabilities.executeCommandProvider) { - return; - } - this.register({ - id: generateUuid(), - registerOptions: Object.assign({}, capabilities.executeCommandProvider) - }); - } - register(data) { - const client = this._client; - const middleware = client.clientOptions.middleware; - const executeCommand = (command, args) => { - const params = { - command, - arguments: args - }; - return client.sendRequest(import_vscode_languageserver_protocol49.ExecuteCommandRequest.type, params).then(void 0, (error) => { - client.handleFailedRequest(import_vscode_languageserver_protocol49.ExecuteCommandRequest.type, void 0, error, void 0); - throw error; - }); - }; - if (data.registerOptions.commands) { - let disposables = []; - for (const command of data.registerOptions.commands) { - disposables.push(commands_default.registerCommand(command, (...args) => { - return middleware.executeCommand ? middleware.executeCommand(command, args, executeCommand) : executeCommand(command, args); - }, null, true)); - } - this._commands.set(data.id, disposables); - } - } - unregister(id) { - let disposables = this._commands.get(id); - if (disposables) { - disposables.forEach((disposable) => disposable.dispose()); - } - } - dispose() { - this._commands.forEach((value) => { - value.forEach((disposable) => disposable.dispose()); - }); - this._commands.clear(); - } - }; - (function(MessageTransports2) { - function is(value) { - let candidate = value; - return candidate && import_vscode_languageserver_protocol49.MessageReader.is(value.reader) && import_vscode_languageserver_protocol49.MessageWriter.is(value.writer); - } - MessageTransports2.is = is; - })(MessageTransports || (MessageTransports = {})); - OnReady = class { - constructor(_resolve, _reject) { - this._resolve = _resolve; - this._reject = _reject; - this._used = false; - } - get isUsed() { - return this._used; - } - resolve() { - this._used = true; - this._resolve(); - } - reject(error) { - this._used = true; - this._reject(error); - } - }; - BaseLanguageClient = class { - constructor(id, name2, clientOptions) { - this._features = []; - this._dynamicFeatures = new Map(); - var _a2; - this._id = id; - this._name = name2; - if (clientOptions.outputChannel) { - this._outputChannel = clientOptions.outputChannel; - } else { - this._outputChannel = void 0; - } - let disableSnippetCompletion = false; - let suggest = workspace_default.getConfiguration("suggest"); - if (suggest.get("snippetsSupport", true) === false || clientOptions.disableSnippetCompletion) { - disableSnippetCompletion = true; - } - const markdown = { isTrusted: false }; - if (clientOptions.markdown !== void 0 && clientOptions.markdown.isTrusted === true) { - markdown.isTrusted = true; - } - this._clientOptions = { - disableWorkspaceFolders: clientOptions.disableWorkspaceFolders, - disableSnippetCompletion, - disableDynamicRegister: clientOptions.disableDynamicRegister, - disableDiagnostics: clientOptions.disableDiagnostics, - disableCompletion: clientOptions.disableCompletion, - formatterPriority: clientOptions.formatterPriority, - ignoredRootPaths: clientOptions.ignoredRootPaths, - documentSelector: clientOptions.documentSelector || [], - synchronize: clientOptions.synchronize || {}, - diagnosticCollectionName: clientOptions.diagnosticCollectionName, - outputChannelName: clientOptions.outputChannelName || this._id, - revealOutputChannelOn: clientOptions.revealOutputChannelOn || 4, - stdioEncoding: clientOptions.stdioEncoding || "utf8", - initializationOptions: clientOptions.initializationOptions, - initializationFailedHandler: clientOptions.initializationFailedHandler, - progressOnInitialization: !!clientOptions.progressOnInitialization, - errorHandler: clientOptions.errorHandler || this.createDefaultErrorHandler((_a2 = clientOptions.connectionOptions) == null ? void 0 : _a2.maxRestartCount), - middleware: clientOptions.middleware || {}, - workspaceFolder: clientOptions.workspaceFolder, - connectionOptions: clientOptions.connectionOptions, - markdown - }; - this.state = 0; - this._connectionPromise = void 0; - this._resolvedConnection = void 0; - this._initializeResult = void 0; - this._listeners = void 0; - this._providers = void 0; - this._diagnostics = void 0; - this._fileEvents = []; - this._fileEventDelayer = new Delayer(250); - this._onReady = new Promise((resolve3, reject) => { - this._onReadyCallbacks = new OnReady(resolve3, reject); - }); - this._onStop = void 0; - this._stateChangeEmitter = new import_vscode_languageserver_protocol49.Emitter(); - this._trace = import_vscode_languageserver_protocol49.Trace.Off; - this._tracer = { - log: (messageOrDataObject, data) => { - if (string(messageOrDataObject)) { - this.logTrace(messageOrDataObject, data); - } else { - this.logObjectTrace(messageOrDataObject); - } - } - }; - this._syncedDocuments = new Map(); - let preferences = workspace_default.getConfiguration("coc.preferences"); - this._markdownSupport = preferences.get("enableMarkdown", true); - this.registerBuiltinFeatures(); - } - get supporedMarkupKind() { - if (this._markdownSupport) - return [import_vscode_languageserver_protocol49.MarkupKind.Markdown, import_vscode_languageserver_protocol49.MarkupKind.PlainText]; - return [import_vscode_languageserver_protocol49.MarkupKind.PlainText]; - } - get state() { - return this._state; - } - get id() { - return this._id; - } - get name() { - return this._name; - } - set state(value) { - let oldState = this.getPublicState(); - this._state = value; - let newState = this.getPublicState(); - if (newState !== oldState) { - this._stateChangeEmitter.fire({ oldState, newState }); - } - } - getPublicState() { - if (this.state === 3) { - return 2; - } else if (this.state === 1) { - return 3; - } else { - return 1; - } - } - get initializeResult() { - return this._initializeResult; - } - sendRequest(type, ...params) { - if (!this.isConnectionActive()) { - throw new Error("Language client is not ready yet"); - } - try { - return this._resolvedConnection.sendRequest(type, ...params); - } catch (error) { - this.error(`Sending request ${string(type) ? type : type.method} failed.`, error); - throw error; - } - } - onRequest(type, handler) { - if (!this.isConnectionActive()) { - throw new Error("Language client is not ready yet"); - } - try { - return this._resolvedConnection.onRequest(type, handler); - } catch (error) { - this.error(`Registering request handler ${string(type) ? type : type.method} failed.`, error); - throw error; - } - } - sendNotification(type, params) { - if (!this.isConnectionActive()) { - throw new Error("Language client is not ready yet"); - } - try { - this._resolvedConnection.sendNotification(type, params); - } catch (error) { - this.error(`Sending notification ${string(type) ? type : type.method} failed.`, error); - throw error; - } - } - onNotification(type, handler) { - if (!this.isConnectionActive()) { - throw new Error("Language client is not ready yet"); - } - try { - return this._resolvedConnection.onNotification(type, handler); - } catch (error) { - this.error(`Registering notification handler ${string(type) ? type : type.method} failed.`, error); - throw error; - } - } - onProgress(type, token, handler) { - if (!this.isConnectionActive()) { - throw new Error("Language client is not ready yet"); - } - try { - if (type == import_vscode_languageserver_protocol49.WorkDoneProgress.type) { - const handleWorkDoneProgress = this._clientOptions.middleware.handleWorkDoneProgress; - if (handleWorkDoneProgress !== void 0) { - return this._resolvedConnection.onProgress(type, token, (params) => { - handleWorkDoneProgress(token, params, () => handler(params)); - }); - } - } - return this._resolvedConnection.onProgress(type, token, handler); - } catch (error) { - this.error(`Registering progress handler for token ${token} failed.`, error); - throw error; - } - } - sendProgress(type, token, value) { - if (!this.isConnectionActive()) { - throw new Error("Language client is not ready yet"); - } - try { - this._resolvedConnection.sendProgress(type, token, value); - } catch (error) { - this.error(`Sending progress for token ${token} failed.`, error); - throw error; - } - } - get clientOptions() { - return this._clientOptions; - } - get onDidChangeState() { - return this._stateChangeEmitter.event; - } - get outputChannel() { - if (!this._outputChannel) { - let { outputChannelName } = this._clientOptions; - this._outputChannel = window_default.createOutputChannel(outputChannelName ? outputChannelName : this._name); - } - return this._outputChannel; - } - get diagnostics() { - return this._diagnostics; - } - createDefaultErrorHandler(maxRestartCount) { - return new DefaultErrorHandler(this._id, maxRestartCount != null ? maxRestartCount : 4); - } - set trace(value) { - this._trace = value; - this.onReady().then(() => { - this.resolveConnection().then((connection) => { - connection.trace(this._trace, this._tracer, { - sendNotification: false, - traceFormat: this._traceFormat - }); - }); - }, () => { - }); - } - logObjectTrace(data) { - if (data.isLSPMessage && data.type) { - this.outputChannel.append(`[LSP - ${new Date().toLocaleTimeString()}] `); - } else { - this.outputChannel.append(`[Trace - ${new Date().toLocaleTimeString()}] `); - } - if (data) { - this.outputChannel.appendLine(`${JSON.stringify(data)}`); - } - } - data2String(data) { - if (data instanceof import_vscode_languageserver_protocol49.ResponseError) { - const responseError = data; - return ` Message: ${responseError.message} - Code: ${responseError.code} ${responseError.data ? "\n" + responseError.data.toString() : ""}`; - } - if (data instanceof Error) { - if (string(data.stack)) { - return data.stack; - } - return data.message; - } - if (string(data)) { - return data; - } - return data.toString(); - } - _appendOutput(type, message, data) { - let level = 3; - switch (type) { - case "Info": - level = 1; - break; - case "Warn": - level = 2; - break; - } - this.outputChannel.appendLine(`[${type} - ${new Date().toLocaleTimeString()}] ${message}`); - let dataString; - if (data) { - dataString = this.data2String(data); - this.outputChannel.appendLine(dataString); - } - if (this._clientOptions.revealOutputChannelOn <= level) { - this.outputChannel.show(true); - } - } - info(message, data) { - this._appendOutput("Info", message, data); - } - warn(message, data) { - this._appendOutput("Warn", message, data); - } - error(message, data) { - this._appendOutput("Error", message, data); - } - logTrace(message, data) { - this.outputChannel.appendLine(`[Trace - ${new Date().toLocaleTimeString()}] ${message}`); - if (data) { - this.outputChannel.appendLine(this.data2String(data)); - } - } - needsStart() { - return this.state === 0 || this.state === 4 || this.state === 5; - } - needsStop() { - return this.state === 1 || this.state === 3; - } - onReady() { - return this._onReady; - } - get started() { - return this.state != 0; - } - isConnectionActive() { - return this.state === 3 && !!this._resolvedConnection; - } - start() { - if (this._onReadyCallbacks.isUsed) { - this._onReady = new Promise((resolve3, reject) => { - this._onReadyCallbacks = new OnReady(resolve3, reject); - }); - } - this._listeners = []; - this._providers = []; - if (!this._diagnostics) { - let opts = this._clientOptions; - let name2 = opts.diagnosticCollectionName ? opts.diagnosticCollectionName : this._id; - this._diagnostics = languages_default.createDiagnosticCollection(name2); - } - this.state = 1; - this.resolveConnection().then((connection) => { - connection.onLogMessage((message) => { - let kind; - switch (message.type) { - case import_vscode_languageserver_protocol49.MessageType.Error: - kind = "error"; - this.error(message.message); - break; - case import_vscode_languageserver_protocol49.MessageType.Warning: - kind = "warning"; - this.warn(message.message); - break; - case import_vscode_languageserver_protocol49.MessageType.Info: - kind = "info"; - this.info(message.message); - break; - default: - kind = "log"; - this.outputChannel.appendLine(message.message); - } - if (global.hasOwnProperty("__TEST__")) { - console.log(`[${kind}] ${message.message}`); - return; - } - }); - connection.onShowMessage((message) => { - switch (message.type) { - case import_vscode_languageserver_protocol49.MessageType.Error: - window_default.showErrorMessage(message.message); - break; - case import_vscode_languageserver_protocol49.MessageType.Warning: - window_default.showWarningMessage(message.message); - break; - case import_vscode_languageserver_protocol49.MessageType.Info: - window_default.showInformationMessage(message.message); - break; - default: - window_default.showInformationMessage(message.message); - } - }); - connection.onRequest(import_vscode_languageserver_protocol49.ShowMessageRequest.type, (params) => { - let messageFunc; - switch (params.type) { - case import_vscode_languageserver_protocol49.MessageType.Error: - messageFunc = window_default.showErrorMessage.bind(window_default); - break; - case import_vscode_languageserver_protocol49.MessageType.Warning: - messageFunc = window_default.showWarningMessage.bind(window_default); - break; - case import_vscode_languageserver_protocol49.MessageType.Info: - messageFunc = window_default.showInformationMessage.bind(window_default); - break; - default: - messageFunc = window_default.showInformationMessage.bind(window_default); - } - let actions = params.actions || []; - return messageFunc(params.message, ...actions); - }); - connection.onRequest(import_vscode_languageserver_protocol49.ShowDocumentRequest.type, async (params) => { - var _a2; - const showDocument = async (params2) => { - var _a3; - try { - if (params2.external === true) { - await workspace_default.openResource(params2.uri); - return { success: true }; - } else { - if (params2.selection) { - params2.selection.start; - } - await workspace_default.jumpTo(params2.uri, (_a3 = params2.selection) == null ? void 0 : _a3.start); - return { success: true }; - } - } catch (error) { - return { success: true }; - } - }; - const middleware = (_a2 = this._clientOptions.middleware.window) == null ? void 0 : _a2.showDocument; - if (middleware !== void 0) { - return middleware(params, showDocument); - } else { - return showDocument(params); - } - }); - connection.onTelemetry((_data) => { - }); - connection.listen(); - return this.initialize(connection); - }).then(void 0, (error) => { - this.state = 2; - this._onReadyCallbacks.reject(error); - this.error("Starting client failed ", error); - }); - return import_vscode_languageserver_protocol49.Disposable.create(() => { - if (this.needsStop()) { - this.stop(); - } - }); - } - resolveConnection() { - if (!this._connectionPromise) { - this._connectionPromise = this.createConnection(); - } - return this._connectionPromise; - } - resolveRootPath() { - if (this._clientOptions.workspaceFolder) { - return URI.parse(this._clientOptions.workspaceFolder.uri).fsPath; - } - let { ignoredRootPaths } = this._clientOptions; - let config = workspace_default.getConfiguration(this.id); - let rootPatterns = config.get("rootPatterns", []); - let required = config.get("requireRootPattern", false); - let resolved; - if (rootPatterns && rootPatterns.length) { - let doc = workspace_default.getDocument(workspace_default.bufnr); - if (doc && doc.schema == "file") { - let dir = import_path17.default.dirname(URI.parse(doc.uri).fsPath); - resolved = resolveRoot(dir, rootPatterns, workspace_default.cwd); - } - } - if (required && !resolved) - return false; - let rootPath = resolved || workspace_default.rootPath || workspace_default.cwd; - if (rootPath === import_os7.default.homedir() || ignoredRootPaths && ignoredRootPaths.includes(rootPath)) { - this.warn(`Ignored rootPath ${rootPath} of client "${this._id}"`); - return null; - } - return rootPath; - } - initialize(connection) { - this.refreshTrace(connection, false); - let { initializationOptions, progressOnInitialization } = this._clientOptions; - let rootPath = this.resolveRootPath(); - if (rootPath === false) { - console.warn(`required root pattern not found, server not started.`); - return; - } - let initParams = { - processId: process.pid, - rootPath: rootPath ? rootPath : null, - rootUri: rootPath ? asUri(URI.file(rootPath)) : null, - capabilities: this.computeClientCapabilities(), - initializationOptions: func(initializationOptions) ? initializationOptions() : initializationOptions, - trace: import_vscode_languageserver_protocol49.Trace.toString(this._trace), - workspaceFolders: null, - locale: this.getLocale(), - clientInfo: { - name: "coc.nvim", - version: workspace_default.version - } - }; - this.fillInitializeParams(initParams); - if (progressOnInitialization) { - const token = generateUuid(); - initParams.workDoneToken = token; - const part = new ProgressPart(connection, token); - part.begin({ title: `initializing ${this.id}`, kind: "begin" }); - return this.doInitialize(connection, initParams).then((result) => { - part.done(); - return result; - }, (error) => { - part.cancel(); - throw error; - }); - } else { - return this.doInitialize(connection, initParams); - } - } - doInitialize(connection, initParams) { - return connection.initialize(initParams).then((result) => { - this._resolvedConnection = connection; - this._initializeResult = result; - this.state = 3; - let textDocumentSyncOptions = void 0; - if (number(result.capabilities.textDocumentSync)) { - if (result.capabilities.textDocumentSync === import_vscode_languageserver_protocol49.TextDocumentSyncKind.None) { - textDocumentSyncOptions = { - openClose: false, - change: import_vscode_languageserver_protocol49.TextDocumentSyncKind.None, - save: void 0 - }; - } else { - textDocumentSyncOptions = { - openClose: true, - change: result.capabilities.textDocumentSync, - save: { - includeText: false - } - }; - } - } else if (result.capabilities.textDocumentSync != null && result.capabilities.textDocumentSync !== void 0) { - textDocumentSyncOptions = result.capabilities.textDocumentSync; - } - this._capabilities = Object.assign({}, result.capabilities, { - resolvedTextDocumentSync: textDocumentSyncOptions - }); - if (!this._clientOptions.disableDiagnostics) { - connection.onDiagnostics((params) => this.handleDiagnostics(params)); - } - connection.onRequest(import_vscode_languageserver_protocol49.RegistrationRequest.type, (params) => this.handleRegistrationRequest(params)); - connection.onRequest("client/registerFeature", (params) => this.handleRegistrationRequest(params)); - connection.onRequest(import_vscode_languageserver_protocol49.UnregistrationRequest.type, (params) => this.handleUnregistrationRequest(params)); - connection.onRequest("client/unregisterFeature", (params) => this.handleUnregistrationRequest(params)); - connection.onRequest(import_vscode_languageserver_protocol49.ApplyWorkspaceEditRequest.type, (params) => this.handleApplyWorkspaceEdit(params)); - connection.sendNotification(import_vscode_languageserver_protocol49.InitializedNotification.type, {}); - this.hookFileEvents(connection); - this.hookConfigurationChanged(connection); - this.initializeFeatures(connection); - this._onReadyCallbacks.resolve(); - return result; - }).then(void 0, (error) => { - if (this._clientOptions.initializationFailedHandler) { - if (this._clientOptions.initializationFailedHandler(error)) { - this.initialize(connection); - } else { - this.stop(); - this._onReadyCallbacks.reject(error); - } - } else if (error instanceof import_vscode_languageserver_protocol49.ResponseError && error.data && error.data.retry) { - window_default.showPrompt(error.message + " Retry?").then((confirmed) => { - if (confirmed) { - this.initialize(connection); - } else { - this.stop(); - this._onReadyCallbacks.reject(error); - } - }); - } else { - if (error && error.message) { - window_default.showMessage(error.message, "error"); - } - this.error("Server initialization failed.", error); - this.stop(); - this._onReadyCallbacks.reject(error); - } - throw error; - }); - } - stop() { - this._initializeResult = void 0; - if (!this._connectionPromise) { - this.state = 5; - return Promise.resolve(); - } - if (this.state === 4 && this._onStop) { - return this._onStop; - } - this.state = 4; - this.cleanUp(); - return this._onStop = this.resolveConnection().then((connection) => { - return connection.shutdown().then(() => { - connection.exit(); - connection.dispose(); - this.state = 5; - this.cleanUpChannel(); - this._onStop = void 0; - this._connectionPromise = void 0; - this._resolvedConnection = void 0; - }); - }).catch((e) => { - logger47.error("Error on stop languageserver:", e); - this.state = 5; - this.cleanUpChannel(); - this._onStop = void 0; - this._connectionPromise = void 0; - this._resolvedConnection = void 0; - }); - } - cleanUp(channel = true, diagnostics = true) { - if (this._listeners) { - this._listeners.forEach((listener) => listener.dispose()); - this._listeners = void 0; - } - if (this._providers) { - this._providers.forEach((provider) => provider.dispose()); - this._providers = void 0; - } - for (let feature of this._features.values()) { - if (typeof feature.dispose === "function") { - feature.dispose(); - } else { - logger47.error(`Feature can't be disposed`, feature); - } - } - if (this._syncedDocuments) { - this._syncedDocuments.clear(); - } - if (channel) { - this.cleanUpChannel(); - } - if (this._diagnostics) { - if (diagnostics) { - this._diagnostics.dispose(); - this._diagnostics = void 0; - } else { - this._diagnostics.clear(); - } - } - } - cleanUpChannel() { - if (this._outputChannel) { - this._outputChannel.dispose(); - this._outputChannel = void 0; - } - } - notifyFileEvent(event) { - var _a2; - const client = this; - function didChangeWatchedFile(event2) { - client._fileEvents.push(event2); - client._fileEventDelayer.trigger(() => { - client.onReady().then(() => { - client.resolveConnection().then((connection) => { - if (client.isConnectionActive()) { - connection.didChangeWatchedFiles({ changes: client._fileEvents }); - } - client._fileEvents = []; - }); - }, (error) => { - client.error(`Notify file events failed.`, error); - }); - }); - } - const workSpaceMiddleware = (_a2 = this.clientOptions.middleware) == null ? void 0 : _a2.workspace; - (workSpaceMiddleware == null ? void 0 : workSpaceMiddleware.didChangeWatchedFile) ? workSpaceMiddleware.didChangeWatchedFile(event, didChangeWatchedFile) : didChangeWatchedFile(event); - } - handleDiagnostics(params) { - if (!this._diagnostics) { - return; - } - let { uri, diagnostics } = params; - let middleware = this.clientOptions.middleware.handleDiagnostics; - if (middleware) { - middleware(uri, diagnostics, (uri2, diagnostics2) => this.setDiagnostics(uri2, diagnostics2)); - } else { - this.setDiagnostics(uri, diagnostics); - } - } - setDiagnostics(uri, diagnostics) { - var _a2; - if (!this._diagnostics) { - return; - } - const separate = workspace_default.getConfiguration("diagnostic").get("separateRelatedInformationAsDiagnostics"); - if (separate && diagnostics.length > 0) { - const entries = new Map(); - entries.set(uri, diagnostics); - for (const diagnostic of diagnostics) { - if ((_a2 = diagnostic.relatedInformation) == null ? void 0 : _a2.length) { - let message = `${diagnostic.message} +"use strict"; +global.__starttime = Date.now(); +global.__isMain = require.main === module; +"use strict";var L6=Object.create;var hb=Object.defineProperty;var F6=Object.getOwnPropertyDescriptor;var M6=Object.getOwnPropertyNames;var j6=Object.getPrototypeOf,O6=Object.prototype.hasOwnProperty;var D=(n,e)=>()=>(n&&(e=n(n=0)),e);var w=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ls=(n,e)=>{for(var t in e)hb(n,t,{get:e[t],enumerable:!0})},dI=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of M6(e))!O6.call(n,r)&&r!==t&&hb(n,r,{get:()=>e[r],enumerable:!(i=F6(e,r))||i.enumerable});return n};var Lr=(n,e,t)=>(t=n!=null?L6(j6(n)):{},dI(e||!n||!n.__esModule?hb(t,"default",{value:n,enumerable:!0}):t,n)),No=n=>dI(hb({},"__esModule",{value:!0}),n);var fI=w((Mbe,pI)=>{"use strict";var hI=(n=0)=>e=>`\x1B[${38+n};5;${e}m`,gI=(n=0)=>(e,t,i)=>`\x1B[${38+n};2;${e};${t};${i}m`;function A6(){let n=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[t,i]of Object.entries(e)){for(let[r,o]of Object.entries(i))e[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},i[r]=e[r],n.set(o[0],o[1]);Object.defineProperty(e,t,{value:i,enumerable:!1})}return Object.defineProperty(e,"codes",{value:n,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",e.color.ansi256=hI(),e.color.ansi16m=gI(),e.bgColor.ansi256=hI(10),e.bgColor.ansi16m=gI(10),Object.defineProperties(e,{rgbToAnsi256:{value:(t,i,r)=>t===i&&i===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(i/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value:t=>{let i=/(?[a-f\d]{6}|[a-f\d]{3})/i.exec(t.toString(16));if(!i)return[0,0,0];let{colorString:r}=i.groups;r.length===3&&(r=r.split("").map(s=>s+s).join(""));let o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:t=>e.rgbToAnsi256(...e.hexToRgb(t)),enumerable:!1}}),e}Object.defineProperty(pI,"exports",{enumerable:!0,get:A6})});var aS=w((jbe,mI)=>{function sS(n,e,t){var i,r,o,s,a;e==null&&(e=100);function l(){var c=Date.now()-s;c=0?i=setTimeout(l,e-c):(i=null,t||(a=n.apply(o,r),o=r=null))}var u=function(){o=this,r=arguments,s=Date.now();var c=t&&!i;return i||(i=setTimeout(l,e)),c&&(a=n.apply(o,r),o=r=null),a};return u.clear=function(){i&&(clearTimeout(i),i=null)},u.flush=function(){i&&(a=n.apply(o,r),o=r=null,clearTimeout(i),i=null)},u}sS.debounce=sS;mI.exports=sS});var bI=w(lS=>{var Ba=require("path"),Ms=process.platform==="win32",Fs=require("fs"),N6=process.env.NODE_DEBUG&&/fs/.test(process.env.NODE_DEBUG);function H6(){var n;if(N6){var e=new Error;n=t}else n=i;return n;function t(r){r&&(e.message=r.message,r=e,i(r))}function i(r){if(r){if(process.throwDeprecation)throw r;if(!process.noDeprecation){var o="fs: missing callback "+(r.stack||r.message);process.traceDeprecation?console.trace(o):console.error(o)}}}}function B6(n){return typeof n=="function"?n:H6()}var Obe=Ba.normalize;Ms?Ho=/(.*?)(?:[\/\\]+|$)/g:Ho=/(.*?)(?:[\/]+|$)/g;var Ho;Ms?Fd=/^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/:Fd=/^[\/]*/;var Fd;lS.realpathSync=function(e,t){if(e=Ba.resolve(e),t&&Object.prototype.hasOwnProperty.call(t,e))return t[e];var i=e,r={},o={},s,a,l,u;c();function c(){var b=Fd.exec(e);s=b[0].length,a=b[0],l=b[0],u="",Ms&&!o[l]&&(Fs.lstatSync(l),o[l]=!0)}for(;s=e.length)return t&&(t[r]=e),i(null,e);Ho.lastIndex=a;var b=Ho.exec(e);return c=l,l+=b[0],u=c+b[1],a=Ho.lastIndex,s[u]||t&&t[u]===u?process.nextTick(h):t&&Object.prototype.hasOwnProperty.call(t,u)?m(t[u]):Fs.lstat(u,g)}function g(b,v){if(b)return i(b);if(!v.isSymbolicLink())return s[u]=!0,t&&(t[u]=u),process.nextTick(h);if(!Ms){var x=v.dev.toString(32)+":"+v.ino.toString(32);if(o.hasOwnProperty(x))return f(null,o[x],u)}Fs.stat(u,function(C){if(C)return i(C);Fs.readlink(u,function(k,T){Ms||(o[x]=T),f(k,T)})})}function f(b,v,x){if(b)return i(b);var C=Ba.resolve(c,v);t&&(t[x]=C),m(C)}function m(b){e=Ba.resolve(b,e.slice(a)),d()}}});var hS=w((Nbe,xI)=>{xI.exports=js;js.realpath=js;js.sync=dS;js.realpathSync=dS;js.monkeypatch=W6;js.unmonkeypatch=Y6;var wu=require("fs"),uS=wu.realpath,cS=wu.realpathSync,q6=process.version,yI=/^v[0-5]\./.test(q6),vI=bI();function wI(n){return n&&n.syscall==="realpath"&&(n.code==="ELOOP"||n.code==="ENOMEM"||n.code==="ENAMETOOLONG")}function js(n,e,t){if(yI)return uS(n,e,t);typeof e=="function"&&(t=e,e=null),uS(n,e,function(i,r){wI(i)?vI.realpath(n,e,t):t(i,r)})}function dS(n,e){if(yI)return cS(n,e);try{return cS(n,e)}catch(t){if(wI(t))return vI.realpathSync(n,e);throw t}}function W6(){wu.realpath=js,wu.realpathSync=dS}function Y6(){wu.realpath=uS,wu.realpathSync=cS}});var SI=w((Hbe,CI)=>{CI.exports=function(n,e){for(var t=[],i=0;i{"use strict";PI.exports=TI;function TI(n,e,t){n instanceof RegExp&&(n=DI(n,t)),e instanceof RegExp&&(e=DI(e,t));var i=kI(n,e,t);return i&&{start:i[0],end:i[1],pre:t.slice(0,i[0]),body:t.slice(i[0]+n.length,i[1]),post:t.slice(i[1]+e.length)}}function DI(n,e){var t=e.match(n);return t?t[0]:null}TI.range=kI;function kI(n,e,t){var i,r,o,s,a,l=t.indexOf(n),u=t.indexOf(e,l+1),c=l;if(l>=0&&u>0){if(n===e)return[l,u];for(i=[],o=t.length;c>=0&&!a;)c==l?(i.push(c),l=t.indexOf(n,c+1)):i.length==1?a=[i.pop(),u]:(r=i.pop(),r=0?l:u;i.length&&(a=[o,s])}return a}});var jI=w((qbe,MI)=>{var J6=SI(),RI=gS();MI.exports=X6;var _I="\0SLASH"+Math.random()+"\0",EI="\0OPEN"+Math.random()+"\0",fS="\0CLOSE"+Math.random()+"\0",II="\0COMMA"+Math.random()+"\0",LI="\0PERIOD"+Math.random()+"\0";function pS(n){return parseInt(n,10)==n?parseInt(n,10):n.charCodeAt(0)}function $6(n){return n.split("\\\\").join(_I).split("\\{").join(EI).split("\\}").join(fS).split("\\,").join(II).split("\\.").join(LI)}function U6(n){return n.split(_I).join("\\").split(EI).join("{").split(fS).join("}").split(II).join(",").split(LI).join(".")}function FI(n){if(!n)return[""];var e=[],t=RI("{","}",n);if(!t)return n.split(",");var i=t.pre,r=t.body,o=t.post,s=i.split(",");s[s.length-1]+="{"+r+"}";var a=FI(o);return o.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),e.push.apply(e,s),e}function X6(n){return n?(n.substr(0,2)==="{}"&&(n="\\{\\}"+n.substr(2)),xu($6(n),!0).map(U6)):[]}function G6(n){return"{"+n+"}"}function z6(n){return/^-?0\d/.test(n)}function K6(n,e){return n<=e}function Q6(n,e){return n>=e}function xu(n,e){var t=[],i=RI("{","}",n);if(!i||/\$$/.test(i.pre))return[n];var r=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),o=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),s=r||o,a=i.body.indexOf(",")>=0;if(!s&&!a)return i.post.match(/,.*\}/)?(n=i.pre+"{"+i.body+fS+i.post,xu(n)):[n];var l;if(s)l=i.body.split(/\.\./);else if(l=FI(i.body),l.length===1&&(l=xu(l[0],!1).map(G6),l.length===1)){var c=i.post.length?xu(i.post,!1):[""];return c.map(function(K){return i.pre+l[0]+K})}var u=i.pre,c=i.post.length?xu(i.post,!1):[""],d;if(s){var h=pS(l[0]),g=pS(l[1]),f=Math.max(l[0].length,l[1].length),m=l.length==3?Math.abs(pS(l[2])):1,b=K6,v=g0){var j=new Array(T+1).join("0");C<0?k="-"+j+k.slice(1):k=j+k}}d.push(k)}}else d=J6(l,function(Y){return xu(Y,!1)});for(var N=0;N{BI.exports=Wn;Wn.Minimatch=Wi;var Md=function(){try{return require("path")}catch{}}()||{sep:"/"};Wn.sep=Md.sep;var yS=Wn.GLOBSTAR=Wi.GLOBSTAR={},V6=jI(),OI={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},mS="[^/]",bS=mS+"*?",e5="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",t5="(?:(?!(?:\\/|^)\\.).)*?",AI=i5("().*{}+?[]^$\\!");function i5(n){return n.split("").reduce(function(e,t){return e[t]=!0,e},{})}var NI=/\/+/;Wn.filter=n5;function n5(n,e){return e=e||{},function(t,i,r){return Wn(t,n,e)}}function Os(n,e){e=e||{};var t={};return Object.keys(n).forEach(function(i){t[i]=n[i]}),Object.keys(e).forEach(function(i){t[i]=e[i]}),t}Wn.defaults=function(n){if(!n||typeof n!="object"||!Object.keys(n).length)return Wn;var e=Wn,t=function(r,o,s){return e(r,o,Os(n,s))};return t.Minimatch=function(r,o){return new e.Minimatch(r,Os(n,o))},t.Minimatch.defaults=function(r){return e.defaults(Os(n,r)).Minimatch},t.filter=function(r,o){return e.filter(r,Os(n,o))},t.defaults=function(r){return e.defaults(Os(n,r))},t.makeRe=function(r,o){return e.makeRe(r,Os(n,o))},t.braceExpand=function(r,o){return e.braceExpand(r,Os(n,o))},t.match=function(i,r,o){return e.match(i,r,Os(n,o))},t};Wi.defaults=function(n){return Wn.defaults(n).Minimatch};function Wn(n,e,t){return pb(e),t||(t={}),!t.nocomment&&e.charAt(0)==="#"?!1:new Wi(e,t).match(n)}function Wi(n,e){if(!(this instanceof Wi))return new Wi(n,e);pb(n),e||(e={}),n=n.trim(),!e.allowWindowsEscape&&Md.sep!=="/"&&(n=n.split(Md.sep).join("/")),this.options=e,this.set=[],this.pattern=n,this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.make()}Wi.prototype.debug=function(){};Wi.prototype.make=r5;function r5(){var n=this.pattern,e=this.options;if(!e.nocomment&&n.charAt(0)==="#"){this.comment=!0;return}if(!n){this.empty=!0;return}this.parseNegate();var t=this.globSet=this.braceExpand();e.debug&&(this.debug=function(){console.error.apply(console,arguments)}),this.debug(this.pattern,t),t=this.globParts=t.map(function(i){return i.split(NI)}),this.debug(this.pattern,t),t=t.map(function(i,r,o){return i.map(this.parse,this)},this),this.debug(this.pattern,t),t=t.filter(function(i){return i.indexOf(!1)===-1}),this.debug(this.pattern,t),this.set=t}Wi.prototype.parseNegate=o5;function o5(){var n=this.pattern,e=!1,t=this.options,i=0;if(!t.nonegate){for(var r=0,o=n.length;r"u"?this.pattern:n,pb(n),e.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:V6(n)}var s5=1024*64,pb=function(n){if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>s5)throw new TypeError("pattern is too long")};Wi.prototype.parse=a5;var gb={};function a5(n,e){pb(n);var t=this.options;if(n==="**")if(t.noglobstar)n="*";else return yS;if(n==="")return"";var i="",r=!!t.nocase,o=!1,s=[],a=[],l,u=!1,c=-1,d=-1,h=n.charAt(0)==="."?"":t.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",g=this;function f(){if(l){switch(l){case"*":i+=bS,r=!0;break;case"?":i+=mS,r=!0;break;default:i+="\\"+l;break}g.debug("clearStateChar %j %j",l,i),l=!1}}for(var m=0,b=n.length,v;m-1;X--){var se=a[X],Y=i.slice(0,se.reStart),K=i.slice(se.reStart,se.reEnd-8),B=i.slice(se.reEnd-8,se.reEnd),ge=i.slice(se.reEnd);B+=ge;var ye=Y.split("(").length-1,Fe=ge;for(m=0;m"u"&&(t=this.partial),this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;var i=this.options;Md.sep!=="/"&&(e=e.split(Md.sep).join("/")),e=e.split(NI),this.debug(this.pattern,"split",e);var r=this.set;this.debug(this.pattern,"set",r);var o,s;for(s=e.length-1;s>=0&&(o=e[s],!o);s--);for(s=0;s>> no match, partial?`,n,c,e,d),c===s))}var g;if(typeof l=="string"?(g=u===l,this.debug("string match",l,u,g)):(g=u.match(l),this.debug("pattern match",l,u,g)),!g)return!1}if(r===s&&o===a)return!0;if(r===s)return t;if(o===a)return r===s-1&&n[r]==="";throw new Error("wtf?")};function u5(n){return n.replace(/\\(.)/g,"$1")}function c5(n){return n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var qI=w((Ybe,vS)=>{typeof Object.create=="function"?vS.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:vS.exports=function(e,t){if(t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}}});var WI=w((Zbe,xS)=>{try{if(wS=require("util"),typeof wS.inherits!="function")throw"";xS.exports=wS.inherits}catch{xS.exports=qI()}var wS});var bb=w((Jbe,mb)=>{"use strict";function YI(n){return n.charAt(0)==="/"}function ZI(n){var e=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,t=e.exec(n),i=t[1]||"",r=Boolean(i&&i.charAt(1)!==":");return Boolean(t[2]||r)}mb.exports=process.platform==="win32"?ZI:YI;mb.exports.posix=YI;mb.exports.win32=ZI});var SS=w(As=>{As.setopts=m5;As.ownProp=JI;As.makeAbs=jd;As.finish=b5;As.mark=y5;As.isIgnored=UI;As.childrenIgnored=v5;function JI(n,e){return Object.prototype.hasOwnProperty.call(n,e)}var d5=require("fs"),Cu=require("path"),h5=fb(),$I=bb(),CS=h5.Minimatch;function g5(n,e){return n.localeCompare(e,"en")}function p5(n,e){n.ignore=e.ignore||[],Array.isArray(n.ignore)||(n.ignore=[n.ignore]),n.ignore.length&&(n.ignore=n.ignore.map(f5))}function f5(n){var e=null;if(n.slice(-3)==="/**"){var t=n.replace(/(\/\*\*)+$/,"");e=new CS(t,{dot:!0})}return{matcher:new CS(n,{dot:!0}),gmatcher:e}}function m5(n,e,t){if(t||(t={}),t.matchBase&&e.indexOf("/")===-1){if(t.noglobstar)throw new Error("base matching requires globstar");e="**/"+e}n.silent=!!t.silent,n.pattern=e,n.strict=t.strict!==!1,n.realpath=!!t.realpath,n.realpathCache=t.realpathCache||Object.create(null),n.follow=!!t.follow,n.dot=!!t.dot,n.mark=!!t.mark,n.nodir=!!t.nodir,n.nodir&&(n.mark=!0),n.sync=!!t.sync,n.nounique=!!t.nounique,n.nonull=!!t.nonull,n.nosort=!!t.nosort,n.nocase=!!t.nocase,n.stat=!!t.stat,n.noprocess=!!t.noprocess,n.absolute=!!t.absolute,n.fs=t.fs||d5,n.maxLength=t.maxLength||1/0,n.cache=t.cache||Object.create(null),n.statCache=t.statCache||Object.create(null),n.symlinks=t.symlinks||Object.create(null),p5(n,t),n.changedCwd=!1;var i=process.cwd();JI(t,"cwd")?(n.cwd=Cu.resolve(t.cwd),n.changedCwd=n.cwd!==i):n.cwd=i,n.root=t.root||Cu.resolve(n.cwd,"/"),n.root=Cu.resolve(n.root),process.platform==="win32"&&(n.root=n.root.replace(/\\/g,"/")),n.cwdAbs=$I(n.cwd)?n.cwd:jd(n,n.cwd),process.platform==="win32"&&(n.cwdAbs=n.cwdAbs.replace(/\\/g,"/")),n.nomount=!!t.nomount,t.nonegate=!0,t.nocomment=!0,t.allowWindowsEscape=!1,n.minimatch=new CS(e,t),n.options=n.minimatch.options}function b5(n){for(var e=n.nounique,t=e?[]:Object.create(null),i=0,r=n.matches.length;i{KI.exports=zI;zI.GlobSync=Si;var w5=hS(),XI=fb(),Ube=XI.Minimatch,Xbe=kS().Glob,Gbe=require("util"),DS=require("path"),GI=require("assert"),yb=bb(),qa=SS(),x5=qa.setopts,TS=qa.ownProp,C5=qa.childrenIgnored,S5=qa.isIgnored;function zI(n,e){if(typeof e=="function"||arguments.length===3)throw new TypeError(`callback provided to sync glob +See: https://github.com/isaacs/node-glob/issues/167`);return new Si(n,e).found}function Si(n,e){if(!n)throw new Error("must provide pattern");if(typeof e=="function"||arguments.length===3)throw new TypeError(`callback provided to sync glob +See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof Si))return new Si(n,e);if(x5(this,n,e),this.noprocess)return this;var t=this.minimatch.set.length;this.matches=new Array(t);for(var i=0;ithis.maxLength)return!1;if(!this.stat&&TS(this.cache,e)){var s=this.cache[e];if(Array.isArray(s)&&(s="DIR"),!t||s==="DIR")return s;if(t&&s==="FILE")return!1}var i,r=this.statCache[e];if(!r){var o;try{o=this.fs.lstatSync(e)}catch(a){if(a&&(a.code==="ENOENT"||a.code==="ENOTDIR"))return this.statCache[e]=!1,!1}if(o&&o.isSymbolicLink())try{r=this.fs.statSync(e)}catch{r=o}else r=o}this.statCache[e]=r;var s=!0;return r&&(s=r.isDirectory()?"DIR":"FILE"),this.cache[e]=this.cache[e]||s,t&&s==="FILE"?!1:s};Si.prototype._mark=function(n){return qa.mark(this,n)};Si.prototype._makeAbs=function(n){return qa.makeAbs(this,n)}});var PS=w((Kbe,eL)=>{eL.exports=VI;function VI(n,e){if(n&&e)return VI(n)(e);if(typeof n!="function")throw new TypeError("need wrapper function");return Object.keys(n).forEach(function(i){t[i]=n[i]}),t;function t(){for(var i=new Array(arguments.length),r=0;r{var tL=PS();RS.exports=tL(vb);RS.exports.strict=tL(iL);vb.proto=vb(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return vb(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return iL(this)},configurable:!0})});function vb(n){var e=function(){return e.called?e.value:(e.called=!0,e.value=n.apply(this,arguments))};return e.called=!1,e}function iL(n){var e=function(){if(e.called)throw new Error(e.onceError);return e.called=!0,e.value=n.apply(this,arguments)},t=n.name||"Function wrapped with `once`";return e.onceError=t+" shouldn't be called more than once",e.called=!1,e}});var rL=w((Vbe,nL)=>{var D5=PS(),Od=Object.create(null),T5=_S();nL.exports=D5(k5);function k5(n,e){return Od[n]?(Od[n].push(e),null):(Od[n]=[e],P5(n))}function P5(n){return T5(function e(){var t=Od[n],i=t.length,r=R5(arguments);try{for(var o=0;oi?(t.splice(0,i),process.nextTick(function(){e.apply(null,r)})):delete Od[n]}})}function R5(n){for(var e=n.length,t=[],i=0;i{sL.exports=Wa;var _5=hS(),oL=fb(),eye=oL.Minimatch,E5=WI(),I5=require("events").EventEmitter,ES=require("path"),IS=require("assert"),Ad=bb(),FS=QI(),Ya=SS(),L5=Ya.setopts,LS=Ya.ownProp,MS=rL(),tye=require("util"),F5=Ya.childrenIgnored,M5=Ya.isIgnored,j5=_S();function Wa(n,e,t){if(typeof e=="function"&&(t=e,e={}),e||(e={}),e.sync){if(t)throw new TypeError("callback provided to sync glob");return FS(n,e)}return new yt(n,e,t)}Wa.sync=FS;var O5=Wa.GlobSync=FS.GlobSync;Wa.glob=Wa;function A5(n,e){if(e===null||typeof e!="object")return n;for(var t=Object.keys(e),i=t.length;i--;)n[t[i]]=e[t[i]];return n}Wa.hasMagic=function(n,e){var t=A5({},e);t.noprocess=!0;var i=new yt(n,t),r=i.minimatch.set;if(!n)return!1;if(r.length>1)return!0;for(var o=0;othis.maxLength)return e();if(!this.stat&&LS(this.cache,t)){var r=this.cache[t];if(Array.isArray(r)&&(r="DIR"),!i||r==="DIR")return e(null,r);if(i&&r==="FILE")return e()}var o,s=this.statCache[t];if(s!==void 0){if(s===!1)return e(null,s);var a=s.isDirectory()?"DIR":"FILE";return i&&a==="FILE"?e():e(null,a,s)}var l=this,u=MS("stat\0"+t,c);u&&l.fs.lstat(t,u);function c(d,h){if(h&&h.isSymbolicLink())return l.fs.stat(t,function(g,f){g?l._stat2(n,t,null,h,e):l._stat2(n,t,g,f,e)});l._stat2(n,t,d,h,e)}};yt.prototype._stat2=function(n,e,t,i,r){if(t&&(t.code==="ENOENT"||t.code==="ENOTDIR"))return this.statCache[e]=!1,r();var o=n.slice(-1)==="/";if(this.statCache[e]=i,e.slice(-1)==="/"&&i&&!i.isDirectory())return r(null,!1,i);var s=!0;return i&&(s=i.isDirectory()?"DIR":"FILE"),this.cache[e]=this.cache[e]||s,o&&s==="FILE"?r():r(null,s,i)}});var lL=w((nye,aL)=>{var H5=typeof process=="object"&&process&&process.platform==="win32";aL.exports=H5?{sep:"\\"}:{sep:"/"}});var mL=w((rye,fL)=>{var uL=gS();fL.exports=W5;var cL="\0SLASH"+Math.random()+"\0",dL="\0OPEN"+Math.random()+"\0",OS="\0CLOSE"+Math.random()+"\0",hL="\0COMMA"+Math.random()+"\0",gL="\0PERIOD"+Math.random()+"\0";function jS(n){return parseInt(n,10)==n?parseInt(n,10):n.charCodeAt(0)}function B5(n){return n.split("\\\\").join(cL).split("\\{").join(dL).split("\\}").join(OS).split("\\,").join(hL).split("\\.").join(gL)}function q5(n){return n.split(cL).join("\\").split(dL).join("{").split(OS).join("}").split(hL).join(",").split(gL).join(".")}function pL(n){if(!n)return[""];var e=[],t=uL("{","}",n);if(!t)return n.split(",");var i=t.pre,r=t.body,o=t.post,s=i.split(",");s[s.length-1]+="{"+r+"}";var a=pL(o);return o.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),e.push.apply(e,s),e}function W5(n){return n?(n.substr(0,2)==="{}"&&(n="\\{\\}"+n.substr(2)),Nd(B5(n),!0).map(q5)):[]}function Y5(n){return"{"+n+"}"}function Z5(n){return/^-?0\d/.test(n)}function J5(n,e){return n<=e}function $5(n,e){return n>=e}function Nd(n,e){var t=[],i=uL("{","}",n);if(!i)return[n];var r=i.pre,o=i.post.length?Nd(i.post,!1):[""];if(/\$$/.test(i.pre))for(var s=0;s=0;if(!c&&!d)return i.post.match(/,.*\}/)?(n=i.pre+"{"+i.body+OS+i.post,Nd(n)):[n];var h;if(c)h=i.body.split(/\.\./);else if(h=pL(i.body),h.length===1&&(h=Nd(h[0],!1).map(Y5),h.length===1))return o.map(function(Y){return i.pre+h[0]+Y});var g;if(c){var f=jS(h[0]),m=jS(h[1]),b=Math.max(h[0].length,h[1].length),v=h.length==3?Math.abs(jS(h[2])):1,x=J5,C=m0){var X=new Array(N+1).join("0");T<0?j="-"+X+j.slice(1):j=X+j}}g.push(j)}}else{g=[];for(var se=0;se{var Yn=qS.exports=(n,e,t={})=>(wb(e),!t.nocomment&&e.charAt(0)==="#"?!1:new Su(e,t).match(n));qS.exports=Yn;var HS=lL();Yn.sep=HS.sep;var Fr=Symbol("globstar **");Yn.GLOBSTAR=Fr;var U5=mL(),bL={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},BS="[^/]",AS=BS+"*?",X5="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",G5="(?:(?!(?:\\/|^)\\.).)*?",wL=n=>n.split("").reduce((e,t)=>(e[t]=!0,e),{}),yL=wL("().*{}+?[]^$\\!"),z5=wL("[.("),vL=/\/+/;Yn.filter=(n,e={})=>(t,i,r)=>Yn(t,n,e);var Ns=(n,e={})=>{let t={};return Object.keys(n).forEach(i=>t[i]=n[i]),Object.keys(e).forEach(i=>t[i]=e[i]),t};Yn.defaults=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return Yn;let e=Yn,t=(i,r,o)=>e(i,r,Ns(n,o));return t.Minimatch=class extends e.Minimatch{constructor(r,o){super(r,Ns(n,o))}},t.Minimatch.defaults=i=>e.defaults(Ns(n,i)).Minimatch,t.filter=(i,r)=>e.filter(i,Ns(n,r)),t.defaults=i=>e.defaults(Ns(n,i)),t.makeRe=(i,r)=>e.makeRe(i,Ns(n,r)),t.braceExpand=(i,r)=>e.braceExpand(i,Ns(n,r)),t.match=(i,r,o)=>e.match(i,r,Ns(n,o)),t};Yn.braceExpand=(n,e)=>xL(n,e);var xL=(n,e={})=>(wb(n),e.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:U5(n)),K5=1024*64,wb=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>K5)throw new TypeError("pattern is too long")},NS=Symbol("subparse");Yn.makeRe=(n,e)=>new Su(n,e||{}).makeRe();Yn.match=(n,e,t={})=>{let i=new Su(e,t);return n=n.filter(r=>i.match(r)),i.options.nonull&&!n.length&&n.push(e),n};var Q5=n=>n.replace(/\\(.)/g,"$1"),V5=n=>n.replace(/\\([^-\]])/g,"$1"),e8=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),t8=n=>n.replace(/[[\]\\]/g,"\\$&"),Su=class{constructor(e,t){wb(e),t||(t={}),this.options=t,this.set=[],this.pattern=e,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.make()}debug(){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate();let i=this.globSet=this.braceExpand();t.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,i),i=this.globParts=i.map(r=>r.split(vL)),this.debug(this.pattern,i),i=i.map((r,o,s)=>r.map(this.parse,this)),this.debug(this.pattern,i),i=i.filter(r=>r.indexOf(!1)===-1),this.debug(this.pattern,i),this.set=i}parseNegate(){if(this.options.nonegate)return;let e=this.pattern,t=!1,i=0;for(let r=0;r>> no match, partial?`,e,d,t,h),d===a))}var f;if(typeof u=="string"?(f=c===u,this.debug("string match",u,c,f)):(f=c.match(u),this.debug("pattern match",u,c,f)),!f)return!1}if(o===a&&s===l)return!0;if(o===a)return i;if(s===l)return o===a-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return xL(this.pattern,this.options)}parse(e,t){wb(e);let i=this.options;if(e==="**")if(i.noglobstar)e="*";else return Fr;if(e==="")return"";let r="",o=!!i.nocase,s=!1,a=[],l=[],u,c=!1,d=-1,h=-1,g,f,m,b=e.charAt(0)==="."?"":i.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",v=()=>{if(u){switch(u){case"*":r+=AS,o=!0;break;case"?":r+=BS,o=!0;break;default:r+="\\"+u;break}this.debug("clearStateChar %j %j",u,r),u=!1}};for(let k=0,T;k(X||(X="\\"),N+N+X+"|")),this.debug(`tail=%j + %s`,k,k,f,r);let T=f.type==="*"?AS:f.type==="?"?BS:"\\"+f.type;o=!0,r=r.slice(0,f.reStart)+T+"\\("+k}v(),s&&(r+="\\\\");let x=z5[r.charAt(0)];for(let k=l.length-1;k>-1;k--){let T=l[k],j=r.slice(0,T.reStart),N=r.slice(T.reStart,T.reEnd-8),X=r.slice(T.reEnd),se=r.slice(T.reEnd-8,T.reEnd)+X,Y=j.split("(").length-1,K=X;for(let ge=0;ge(s=s.map(a=>typeof a=="string"?e8(a):a===Fr?Fr:a._src).reduce((a,l)=>(a[a.length-1]===Fr&&l===Fr||a.push(l),a),[]),s.forEach((a,l)=>{a!==Fr||s[l-1]===Fr||(l===0?s.length>1?s[l+1]="(?:\\/|"+i+"\\/)?"+s[l+1]:s[l]=i:l===s.length-1?s[l-1]+="(?:\\/|"+i+")?":(s[l-1]+="(?:\\/|\\/"+i+"\\/)"+s[l+1],s[l+1]=Fr))}),s.filter(a=>a!==Fr).join("/"))).join("|");o="^(?:"+o+")$",this.negate&&(o="^(?!"+o+").*$");try{this.regexp=new RegExp(o,r)}catch{this.regexp=!1}return this.regexp}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let i=this.options;HS.sep!=="/"&&(e=e.split(HS.sep).join("/")),e=e.split(vL),this.debug(this.pattern,"split",e);let r=this.set;this.debug(this.pattern,"set",r);let o;for(let s=e.length-1;s>=0&&(o=e[s],!o);s--);for(let s=0;s{kL.exports=TL;TL.sync=n8;var SL=require("fs");function i8(n,e){var t=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!t||(t=t.split(";"),t.indexOf("")!==-1))return!0;for(var i=0;i{IL.exports=_L;_L.sync=r8;var RL=require("fs");function _L(n,e,t){RL.stat(n,function(i,r){t(i,i?!1:EL(r,e))})}function r8(n,e){return EL(RL.statSync(n),e)}function EL(n,e){return n.isFile()&&o8(n,e)}function o8(n,e){var t=n.mode,i=n.uid,r=n.gid,o=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),s=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),l=parseInt("010",8),u=parseInt("001",8),c=a|l,d=t&u||t&l&&r===s||t&a&&i===o||t&c&&o===0;return d}});var ML=w((cye,FL)=>{var uye=require("fs"),xb;process.platform==="win32"||global.TESTING_WINDOWS?xb=PL():xb=LL();FL.exports=WS;WS.sync=s8;function WS(n,e,t){if(typeof e=="function"&&(t=e,e={}),!t){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(i,r){WS(n,e||{},function(o,s){o?r(o):i(s)})})}xb(n,e||{},function(i,r){i&&(i.code==="EACCES"||e&&e.ignoreErrors)&&(i=null,r=!1),t(i,r)})}function s8(n,e){try{return xb.sync(n,e||{})}catch(t){if(e&&e.ignoreErrors||t.code==="EACCES")return!1;throw t}}});var qL=w((dye,BL)=>{var Du=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",jL=require("path"),a8=Du?";":":",OL=ML(),AL=n=>Object.assign(new Error(`not found: ${n}`),{code:"ENOENT"}),NL=(n,e)=>{let t=e.colon||a8,i=n.match(/\//)||Du&&n.match(/\\/)?[""]:[...Du?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(t)],r=Du?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",o=Du?r.split(t):[""];return Du&&n.indexOf(".")!==-1&&o[0]!==""&&o.unshift(""),{pathEnv:i,pathExt:o,pathExtExe:r}},HL=(n,e,t)=>{typeof e=="function"&&(t=e,e={}),e||(e={});let{pathEnv:i,pathExt:r,pathExtExe:o}=NL(n,e),s=[],a=u=>new Promise((c,d)=>{if(u===i.length)return e.all&&s.length?c(s):d(AL(n));let h=i[u],g=/^".*"$/.test(h)?h.slice(1,-1):h,f=jL.join(g,n),m=!g&&/^\.[\\\/]/.test(n)?n.slice(0,2)+f:f;c(l(m,u,0))}),l=(u,c,d)=>new Promise((h,g)=>{if(d===r.length)return h(a(c+1));let f=r[d];OL(u+f,{pathExt:o},(m,b)=>{if(!m&&b)if(e.all)s.push(u+f);else return h(u+f);return h(l(u,c,d+1))})});return t?a(0).then(u=>t(null,u),t):a(0)},l8=(n,e)=>{e=e||{};let{pathEnv:t,pathExt:i,pathExtExe:r}=NL(n,e),o=[];for(let s=0;s{var u8="2.0.0",c8=Number.MAX_SAFE_INTEGER||9007199254740991,d8=16;WL.exports={SEMVER_SPEC_VERSION:u8,MAX_LENGTH:256,MAX_SAFE_INTEGER:c8,MAX_SAFE_COMPONENT_LENGTH:d8}});var Bd=w((gye,YL)=>{var h8=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...n)=>console.error("SEMVER",...n):()=>{};YL.exports=h8});var Za=w((Hs,ZL)=>{var{MAX_SAFE_COMPONENT_LENGTH:YS}=Hd(),g8=Bd();Hs=ZL.exports={};var p8=Hs.re=[],ve=Hs.src=[],we=Hs.t={},f8=0,Qe=(n,e,t)=>{let i=f8++;g8(n,i,e),we[n]=i,ve[i]=e,p8[i]=new RegExp(e,t?"g":void 0)};Qe("NUMERICIDENTIFIER","0|[1-9]\\d*");Qe("NUMERICIDENTIFIERLOOSE","[0-9]+");Qe("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*");Qe("MAINVERSION",`(${ve[we.NUMERICIDENTIFIER]})\\.(${ve[we.NUMERICIDENTIFIER]})\\.(${ve[we.NUMERICIDENTIFIER]})`);Qe("MAINVERSIONLOOSE",`(${ve[we.NUMERICIDENTIFIERLOOSE]})\\.(${ve[we.NUMERICIDENTIFIERLOOSE]})\\.(${ve[we.NUMERICIDENTIFIERLOOSE]})`);Qe("PRERELEASEIDENTIFIER",`(?:${ve[we.NUMERICIDENTIFIER]}|${ve[we.NONNUMERICIDENTIFIER]})`);Qe("PRERELEASEIDENTIFIERLOOSE",`(?:${ve[we.NUMERICIDENTIFIERLOOSE]}|${ve[we.NONNUMERICIDENTIFIER]})`);Qe("PRERELEASE",`(?:-(${ve[we.PRERELEASEIDENTIFIER]}(?:\\.${ve[we.PRERELEASEIDENTIFIER]})*))`);Qe("PRERELEASELOOSE",`(?:-?(${ve[we.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${ve[we.PRERELEASEIDENTIFIERLOOSE]})*))`);Qe("BUILDIDENTIFIER","[0-9A-Za-z-]+");Qe("BUILD",`(?:\\+(${ve[we.BUILDIDENTIFIER]}(?:\\.${ve[we.BUILDIDENTIFIER]})*))`);Qe("FULLPLAIN",`v?${ve[we.MAINVERSION]}${ve[we.PRERELEASE]}?${ve[we.BUILD]}?`);Qe("FULL",`^${ve[we.FULLPLAIN]}$`);Qe("LOOSEPLAIN",`[v=\\s]*${ve[we.MAINVERSIONLOOSE]}${ve[we.PRERELEASELOOSE]}?${ve[we.BUILD]}?`);Qe("LOOSE",`^${ve[we.LOOSEPLAIN]}$`);Qe("GTLT","((?:<|>)?=?)");Qe("XRANGEIDENTIFIERLOOSE",`${ve[we.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Qe("XRANGEIDENTIFIER",`${ve[we.NUMERICIDENTIFIER]}|x|X|\\*`);Qe("XRANGEPLAIN",`[v=\\s]*(${ve[we.XRANGEIDENTIFIER]})(?:\\.(${ve[we.XRANGEIDENTIFIER]})(?:\\.(${ve[we.XRANGEIDENTIFIER]})(?:${ve[we.PRERELEASE]})?${ve[we.BUILD]}?)?)?`);Qe("XRANGEPLAINLOOSE",`[v=\\s]*(${ve[we.XRANGEIDENTIFIERLOOSE]})(?:\\.(${ve[we.XRANGEIDENTIFIERLOOSE]})(?:\\.(${ve[we.XRANGEIDENTIFIERLOOSE]})(?:${ve[we.PRERELEASELOOSE]})?${ve[we.BUILD]}?)?)?`);Qe("XRANGE",`^${ve[we.GTLT]}\\s*${ve[we.XRANGEPLAIN]}$`);Qe("XRANGELOOSE",`^${ve[we.GTLT]}\\s*${ve[we.XRANGEPLAINLOOSE]}$`);Qe("COERCE",`(^|[^\\d])(\\d{1,${YS}})(?:\\.(\\d{1,${YS}}))?(?:\\.(\\d{1,${YS}}))?(?:$|[^\\d])`);Qe("COERCERTL",ve[we.COERCE],!0);Qe("LONETILDE","(?:~>?)");Qe("TILDETRIM",`(\\s*)${ve[we.LONETILDE]}\\s+`,!0);Hs.tildeTrimReplace="$1~";Qe("TILDE",`^${ve[we.LONETILDE]}${ve[we.XRANGEPLAIN]}$`);Qe("TILDELOOSE",`^${ve[we.LONETILDE]}${ve[we.XRANGEPLAINLOOSE]}$`);Qe("LONECARET","(?:\\^)");Qe("CARETTRIM",`(\\s*)${ve[we.LONECARET]}\\s+`,!0);Hs.caretTrimReplace="$1^";Qe("CARET",`^${ve[we.LONECARET]}${ve[we.XRANGEPLAIN]}$`);Qe("CARETLOOSE",`^${ve[we.LONECARET]}${ve[we.XRANGEPLAINLOOSE]}$`);Qe("COMPARATORLOOSE",`^${ve[we.GTLT]}\\s*(${ve[we.LOOSEPLAIN]})$|^$`);Qe("COMPARATOR",`^${ve[we.GTLT]}\\s*(${ve[we.FULLPLAIN]})$|^$`);Qe("COMPARATORTRIM",`(\\s*)${ve[we.GTLT]}\\s*(${ve[we.LOOSEPLAIN]}|${ve[we.XRANGEPLAIN]})`,!0);Hs.comparatorTrimReplace="$1$2$3";Qe("HYPHENRANGE",`^\\s*(${ve[we.XRANGEPLAIN]})\\s+-\\s+(${ve[we.XRANGEPLAIN]})\\s*$`);Qe("HYPHENRANGELOOSE",`^\\s*(${ve[we.XRANGEPLAINLOOSE]})\\s+-\\s+(${ve[we.XRANGEPLAINLOOSE]})\\s*$`);Qe("STAR","(<|>)?=?\\s*\\*");Qe("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");Qe("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var qd=w((pye,JL)=>{var m8=["includePrerelease","loose","rtl"],b8=n=>n?typeof n!="object"?{loose:!0}:m8.filter(e=>n[e]).reduce((e,t)=>(e[t]=!0,e),{}):{};JL.exports=b8});var ZS=w((fye,XL)=>{var $L=/^[0-9]+$/,UL=(n,e)=>{let t=$L.test(n),i=$L.test(e);return t&&i&&(n=+n,e=+e),n===e?0:t&&!i?-1:i&&!t?1:nUL(e,n);XL.exports={compareIdentifiers:UL,rcompareIdentifiers:y8}});var Vi=w((mye,QL)=>{var Cb=Bd(),{MAX_LENGTH:GL,MAX_SAFE_INTEGER:Sb}=Hd(),{re:zL,t:KL}=Za(),v8=qd(),{compareIdentifiers:Tu}=ZS(),Zn=class{constructor(e,t){if(t=v8(t),e instanceof Zn){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid Version: ${e}`);if(e.length>GL)throw new TypeError(`version is longer than ${GL} characters`);Cb("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let i=e.trim().match(t.loose?zL[KL.LOOSE]:zL[KL.FULL]);if(!i)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>Sb||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Sb||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Sb||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(r=>{if(/^[0-9]+$/.test(r)){let o=+r;if(o>=0&&o=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);i===-1&&this.prerelease.push(0)}t&&(Tu(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error(`invalid increment argument: ${e}`)}return this.format(),this.raw=this.version,this}};QL.exports=Zn});var Ja=w((bye,iF)=>{var{MAX_LENGTH:w8}=Hd(),{re:VL,t:eF}=Za(),tF=Vi(),x8=qd(),C8=(n,e)=>{if(e=x8(e),n instanceof tF)return n;if(typeof n!="string"||n.length>w8||!(e.loose?VL[eF.LOOSE]:VL[eF.FULL]).test(n))return null;try{return new tF(n,e)}catch{return null}};iF.exports=C8});var rF=w((yye,nF)=>{var S8=Ja(),D8=(n,e)=>{let t=S8(n,e);return t?t.version:null};nF.exports=D8});var sF=w((vye,oF)=>{var T8=Ja(),k8=(n,e)=>{let t=T8(n.trim().replace(/^[=v]+/,""),e);return t?t.version:null};oF.exports=k8});var uF=w((wye,lF)=>{var aF=Vi(),P8=(n,e,t,i)=>{typeof t=="string"&&(i=t,t=void 0);try{return new aF(n instanceof aF?n.version:n,t).inc(e,i).version}catch{return null}};lF.exports=P8});var rr=w((xye,dF)=>{var cF=Vi(),R8=(n,e,t)=>new cF(n,t).compare(new cF(e,t));dF.exports=R8});var Db=w((Cye,hF)=>{var _8=rr(),E8=(n,e,t)=>_8(n,e,t)===0;hF.exports=E8});var fF=w((Sye,pF)=>{var gF=Ja(),I8=Db(),L8=(n,e)=>{if(I8(n,e))return null;{let t=gF(n),i=gF(e),r=t.prerelease.length||i.prerelease.length,o=r?"pre":"",s=r?"prerelease":"";for(let a in t)if((a==="major"||a==="minor"||a==="patch")&&t[a]!==i[a])return o+a;return s}};pF.exports=L8});var bF=w((Dye,mF)=>{var F8=Vi(),M8=(n,e)=>new F8(n,e).major;mF.exports=M8});var vF=w((Tye,yF)=>{var j8=Vi(),O8=(n,e)=>new j8(n,e).minor;yF.exports=O8});var xF=w((kye,wF)=>{var A8=Vi(),N8=(n,e)=>new A8(n,e).patch;wF.exports=N8});var SF=w((Pye,CF)=>{var H8=Ja(),B8=(n,e)=>{let t=H8(n,e);return t&&t.prerelease.length?t.prerelease:null};CF.exports=B8});var TF=w((Rye,DF)=>{var q8=rr(),W8=(n,e,t)=>q8(e,n,t);DF.exports=W8});var PF=w((_ye,kF)=>{var Y8=rr(),Z8=(n,e)=>Y8(n,e,!0);kF.exports=Z8});var Tb=w((Eye,_F)=>{var RF=Vi(),J8=(n,e,t)=>{let i=new RF(n,t),r=new RF(e,t);return i.compare(r)||i.compareBuild(r)};_F.exports=J8});var IF=w((Iye,EF)=>{var $8=Tb(),U8=(n,e)=>n.sort((t,i)=>$8(t,i,e));EF.exports=U8});var FF=w((Lye,LF)=>{var X8=Tb(),G8=(n,e)=>n.sort((t,i)=>X8(i,t,e));LF.exports=G8});var Wd=w((Fye,MF)=>{var z8=rr(),K8=(n,e,t)=>z8(n,e,t)>0;MF.exports=K8});var kb=w((Mye,jF)=>{var Q8=rr(),V8=(n,e,t)=>Q8(n,e,t)<0;jF.exports=V8});var JS=w((jye,OF)=>{var e7=rr(),t7=(n,e,t)=>e7(n,e,t)!==0;OF.exports=t7});var Pb=w((Oye,AF)=>{var i7=rr(),n7=(n,e,t)=>i7(n,e,t)>=0;AF.exports=n7});var Rb=w((Aye,NF)=>{var r7=rr(),o7=(n,e,t)=>r7(n,e,t)<=0;NF.exports=o7});var $S=w((Nye,HF)=>{var s7=Db(),a7=JS(),l7=Wd(),u7=Pb(),c7=kb(),d7=Rb(),h7=(n,e,t,i)=>{switch(e){case"===":return typeof n=="object"&&(n=n.version),typeof t=="object"&&(t=t.version),n===t;case"!==":return typeof n=="object"&&(n=n.version),typeof t=="object"&&(t=t.version),n!==t;case"":case"=":case"==":return s7(n,t,i);case"!=":return a7(n,t,i);case">":return l7(n,t,i);case">=":return u7(n,t,i);case"<":return c7(n,t,i);case"<=":return d7(n,t,i);default:throw new TypeError(`Invalid operator: ${e}`)}};HF.exports=h7});var qF=w((Hye,BF)=>{var g7=Vi(),p7=Ja(),{re:_b,t:Eb}=Za(),f7=(n,e)=>{if(n instanceof g7)return n;if(typeof n=="number"&&(n=String(n)),typeof n!="string")return null;e=e||{};let t=null;if(!e.rtl)t=n.match(_b[Eb.COERCE]);else{let i;for(;(i=_b[Eb.COERCERTL].exec(n))&&(!t||t.index+t[0].length!==n.length);)(!t||i.index+i[0].length!==t.index+t[0].length)&&(t=i),_b[Eb.COERCERTL].lastIndex=i.index+i[1].length+i[2].length;_b[Eb.COERCERTL].lastIndex=-1}return t===null?null:p7(`${t[2]}.${t[3]||"0"}.${t[4]||"0"}`,e)};BF.exports=f7});var YF=w((Bye,WF)=>{"use strict";WF.exports=function(n){n.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}});var Ib=w((qye,ZF)=>{"use strict";ZF.exports=ht;ht.Node=$a;ht.create=ht;function ht(n){var e=this;if(e instanceof ht||(e=new ht),e.tail=null,e.head=null,e.length=0,n&&typeof n.forEach=="function")n.forEach(function(r){e.push(r)});else if(arguments.length>0)for(var t=0,i=arguments.length;t1)t=e;else if(this.head)i=this.head.next,t=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var r=0;i!==null;r++)t=n(t,i.value,r),i=i.next;return t};ht.prototype.reduceReverse=function(n,e){var t,i=this.tail;if(arguments.length>1)t=e;else if(this.tail)i=this.tail.prev,t=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var r=this.length-1;i!==null;r--)t=n(t,i.value,r),i=i.prev;return t};ht.prototype.toArray=function(){for(var n=new Array(this.length),e=0,t=this.head;t!==null;e++)n[e]=t.value,t=t.next;return n};ht.prototype.toArrayReverse=function(){for(var n=new Array(this.length),e=0,t=this.tail;t!==null;e++)n[e]=t.value,t=t.prev;return n};ht.prototype.slice=function(n,e){e=e||this.length,e<0&&(e+=this.length),n=n||0,n<0&&(n+=this.length);var t=new ht;if(ethis.length&&(e=this.length);for(var i=0,r=this.head;r!==null&&ithis.length&&(e=this.length);for(var i=this.length,r=this.tail;r!==null&&i>e;i--)r=r.prev;for(;r!==null&&i>n;i--,r=r.prev)t.push(r.value);return t};ht.prototype.splice=function(n,e,...t){n>this.length&&(n=this.length-1),n<0&&(n=this.length+n);for(var i=0,r=this.head;r!==null&&i{"use strict";var v7=Ib(),Ua=Symbol("max"),qo=Symbol("length"),ku=Symbol("lengthCalculator"),Zd=Symbol("allowStale"),Xa=Symbol("maxAge"),Bo=Symbol("dispose"),JF=Symbol("noDisposeOnSet"),Ei=Symbol("lruList"),Mr=Symbol("cache"),UF=Symbol("updateAgeOnGet"),US=()=>1,GS=class{constructor(e){if(typeof e=="number"&&(e={max:e}),e||(e={}),e.max&&(typeof e.max!="number"||e.max<0))throw new TypeError("max must be a non-negative number");let t=this[Ua]=e.max||1/0,i=e.length||US;if(this[ku]=typeof i!="function"?US:i,this[Zd]=e.stale||!1,e.maxAge&&typeof e.maxAge!="number")throw new TypeError("maxAge must be a number");this[Xa]=e.maxAge||0,this[Bo]=e.dispose,this[JF]=e.noDisposeOnSet||!1,this[UF]=e.updateAgeOnGet||!1,this.reset()}set max(e){if(typeof e!="number"||e<0)throw new TypeError("max must be a non-negative number");this[Ua]=e||1/0,Yd(this)}get max(){return this[Ua]}set allowStale(e){this[Zd]=!!e}get allowStale(){return this[Zd]}set maxAge(e){if(typeof e!="number")throw new TypeError("maxAge must be a non-negative number");this[Xa]=e,Yd(this)}get maxAge(){return this[Xa]}set lengthCalculator(e){typeof e!="function"&&(e=US),e!==this[ku]&&(this[ku]=e,this[qo]=0,this[Ei].forEach(t=>{t.length=this[ku](t.value,t.key),this[qo]+=t.length})),Yd(this)}get lengthCalculator(){return this[ku]}get length(){return this[qo]}get itemCount(){return this[Ei].length}rforEach(e,t){t=t||this;for(let i=this[Ei].tail;i!==null;){let r=i.prev;$F(this,e,i,t),i=r}}forEach(e,t){t=t||this;for(let i=this[Ei].head;i!==null;){let r=i.next;$F(this,e,i,t),i=r}}keys(){return this[Ei].toArray().map(e=>e.key)}values(){return this[Ei].toArray().map(e=>e.value)}reset(){this[Bo]&&this[Ei]&&this[Ei].length&&this[Ei].forEach(e=>this[Bo](e.key,e.value)),this[Mr]=new Map,this[Ei]=new v7,this[qo]=0}dump(){return this[Ei].map(e=>Lb(this,e)?!1:{k:e.key,v:e.value,e:e.now+(e.maxAge||0)}).toArray().filter(e=>e)}dumpLru(){return this[Ei]}set(e,t,i){if(i=i||this[Xa],i&&typeof i!="number")throw new TypeError("maxAge must be a number");let r=i?Date.now():0,o=this[ku](t,e);if(this[Mr].has(e)){if(o>this[Ua])return Pu(this,this[Mr].get(e)),!1;let l=this[Mr].get(e).value;return this[Bo]&&(this[JF]||this[Bo](e,l.value)),l.now=r,l.maxAge=i,l.value=t,this[qo]+=o-l.length,l.length=o,this.get(e),Yd(this),!0}let s=new zS(e,t,o,r,i);return s.length>this[Ua]?(this[Bo]&&this[Bo](e,t),!1):(this[qo]+=s.length,this[Ei].unshift(s),this[Mr].set(e,this[Ei].head),Yd(this),!0)}has(e){if(!this[Mr].has(e))return!1;let t=this[Mr].get(e).value;return!Lb(this,t)}get(e){return XS(this,e,!0)}peek(e){return XS(this,e,!1)}pop(){let e=this[Ei].tail;return e?(Pu(this,e),e.value):null}del(e){Pu(this,this[Mr].get(e))}load(e){this.reset();let t=Date.now();for(let i=e.length-1;i>=0;i--){let r=e[i],o=r.e||0;if(o===0)this.set(r.k,r.v);else{let s=o-t;s>0&&this.set(r.k,r.v,s)}}}prune(){this[Mr].forEach((e,t)=>XS(this,t,!1))}},XS=(n,e,t)=>{let i=n[Mr].get(e);if(i){let r=i.value;if(Lb(n,r)){if(Pu(n,i),!n[Zd])return}else t&&(n[UF]&&(i.value.now=Date.now()),n[Ei].unshiftNode(i));return r.value}},Lb=(n,e)=>{if(!e||!e.maxAge&&!n[Xa])return!1;let t=Date.now()-e.now;return e.maxAge?t>e.maxAge:n[Xa]&&t>n[Xa]},Yd=n=>{if(n[qo]>n[Ua])for(let e=n[Ei].tail;n[qo]>n[Ua]&&e!==null;){let t=e.prev;Pu(n,e),e=t}},Pu=(n,e)=>{if(e){let t=e.value;n[Bo]&&n[Bo](t.key,t.value),n[qo]-=t.length,n[Mr].delete(t.key),n[Ei].removeNode(e)}},zS=class{constructor(e,t,i,r,o){this.key=e,this.value=t,this.length=i,this.now=r,this.maxAge=o||0}},$F=(n,e,t,i)=>{let r=t.value;Lb(n,r)&&(Pu(n,t),n[Zd]||(r=void 0)),r&&e.call(i,r.value,r.key,n)};XF.exports=GS});var or=w((Yye,VF)=>{var Ga=class{constructor(e,t){if(t=x7(t),e instanceof Ga)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new Ga(e.raw,t);if(e instanceof KS)return this.raw=e.value,this.set=[[e]],this.format(),this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split("||").map(i=>this.parseRange(i.trim())).filter(i=>i.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${e}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter(r=>!KF(r[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let r of this.set)if(r.length===1&&k7(r[0])){this.set=[r];break}}}this.format()}format(){return this.range=this.set.map(e=>e.join(" ").trim()).join("||").trim(),this.range}toString(){return this.range}parseRange(e){e=e.trim();let i=`parseRange:${Object.keys(this.options).join(",")}:${e}`,r=zF.get(i);if(r)return r;let o=this.options.loose,s=o?Tn[hn.HYPHENRANGELOOSE]:Tn[hn.HYPHENRANGE];e=e.replace(s,O7(this.options.includePrerelease)),Kt("hyphen replace",e),e=e.replace(Tn[hn.COMPARATORTRIM],S7),Kt("comparator trim",e),e=e.replace(Tn[hn.TILDETRIM],D7),e=e.replace(Tn[hn.CARETTRIM],T7),e=e.split(/\s+/).join(" ");let a=e.split(" ").map(d=>P7(d,this.options)).join(" ").split(/\s+/).map(d=>j7(d,this.options));o&&(a=a.filter(d=>(Kt("loose invalid filter",d,this.options),!!d.match(Tn[hn.COMPARATORLOOSE])))),Kt("range list",a);let l=new Map,u=a.map(d=>new KS(d,this.options));for(let d of u){if(KF(d))return[d];l.set(d.value,d)}l.size>1&&l.has("")&&l.delete("");let c=[...l.values()];return zF.set(i,c),c}intersects(e,t){if(!(e instanceof Ga))throw new TypeError("a Range is required");return this.set.some(i=>QF(i,t)&&e.set.some(r=>QF(r,t)&&i.every(o=>r.every(s=>o.intersects(s,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new C7(e,this.options)}catch{return!1}for(let t=0;tn.value==="<0.0.0-0",k7=n=>n.value==="",QF=(n,e)=>{let t=!0,i=n.slice(),r=i.pop();for(;t&&i.length;)t=i.every(o=>r.intersects(o,e)),r=i.pop();return t},P7=(n,e)=>(Kt("comp",n,e),n=E7(n,e),Kt("caret",n),n=R7(n,e),Kt("tildes",n),n=L7(n,e),Kt("xrange",n),n=M7(n,e),Kt("stars",n),n),gn=n=>!n||n.toLowerCase()==="x"||n==="*",R7=(n,e)=>n.trim().split(/\s+/).map(t=>_7(t,e)).join(" "),_7=(n,e)=>{let t=e.loose?Tn[hn.TILDELOOSE]:Tn[hn.TILDE];return n.replace(t,(i,r,o,s,a)=>{Kt("tilde",n,i,r,o,s,a);let l;return gn(r)?l="":gn(o)?l=`>=${r}.0.0 <${+r+1}.0.0-0`:gn(s)?l=`>=${r}.${o}.0 <${r}.${+o+1}.0-0`:a?(Kt("replaceTilde pr",a),l=`>=${r}.${o}.${s}-${a} <${r}.${+o+1}.0-0`):l=`>=${r}.${o}.${s} <${r}.${+o+1}.0-0`,Kt("tilde return",l),l})},E7=(n,e)=>n.trim().split(/\s+/).map(t=>I7(t,e)).join(" "),I7=(n,e)=>{Kt("caret",n,e);let t=e.loose?Tn[hn.CARETLOOSE]:Tn[hn.CARET],i=e.includePrerelease?"-0":"";return n.replace(t,(r,o,s,a,l)=>{Kt("caret",n,r,o,s,a,l);let u;return gn(o)?u="":gn(s)?u=`>=${o}.0.0${i} <${+o+1}.0.0-0`:gn(a)?o==="0"?u=`>=${o}.${s}.0${i} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.0${i} <${+o+1}.0.0-0`:l?(Kt("replaceCaret pr",l),o==="0"?s==="0"?u=`>=${o}.${s}.${a}-${l} <${o}.${s}.${+a+1}-0`:u=`>=${o}.${s}.${a}-${l} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.${a}-${l} <${+o+1}.0.0-0`):(Kt("no pr"),o==="0"?s==="0"?u=`>=${o}.${s}.${a}${i} <${o}.${s}.${+a+1}-0`:u=`>=${o}.${s}.${a}${i} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.${a} <${+o+1}.0.0-0`),Kt("caret return",u),u})},L7=(n,e)=>(Kt("replaceXRanges",n,e),n.split(/\s+/).map(t=>F7(t,e)).join(" ")),F7=(n,e)=>{n=n.trim();let t=e.loose?Tn[hn.XRANGELOOSE]:Tn[hn.XRANGE];return n.replace(t,(i,r,o,s,a,l)=>{Kt("xRange",n,i,r,o,s,a,l);let u=gn(o),c=u||gn(s),d=c||gn(a),h=d;return r==="="&&h&&(r=""),l=e.includePrerelease?"-0":"",u?r===">"||r==="<"?i="<0.0.0-0":i="*":r&&h?(c&&(s=0),a=0,r===">"?(r=">=",c?(o=+o+1,s=0,a=0):(s=+s+1,a=0)):r==="<="&&(r="<",c?o=+o+1:s=+s+1),r==="<"&&(l="-0"),i=`${r+o}.${s}.${a}${l}`):c?i=`>=${o}.0.0${l} <${+o+1}.0.0-0`:d&&(i=`>=${o}.${s}.0${l} <${o}.${+s+1}.0-0`),Kt("xRange return",i),i})},M7=(n,e)=>(Kt("replaceStars",n,e),n.trim().replace(Tn[hn.STAR],"")),j7=(n,e)=>(Kt("replaceGTE0",n,e),n.trim().replace(Tn[e.includePrerelease?hn.GTE0PRE:hn.GTE0],"")),O7=n=>(e,t,i,r,o,s,a,l,u,c,d,h,g)=>(gn(i)?t="":gn(r)?t=`>=${i}.0.0${n?"-0":""}`:gn(o)?t=`>=${i}.${r}.0${n?"-0":""}`:s?t=`>=${t}`:t=`>=${t}${n?"-0":""}`,gn(u)?l="":gn(c)?l=`<${+u+1}.0.0-0`:gn(d)?l=`<${u}.${+c+1}.0-0`:h?l=`<=${u}.${c}.${d}-${h}`:n?l=`<${u}.${c}.${+d+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),A7=(n,e,t)=>{for(let i=0;i0){let r=n[i].semver;if(r.major===e.major&&r.minor===e.minor&&r.patch===e.patch)return!0}return!1}return!0}});var Jd=w((Zye,rM)=>{var $d=Symbol("SemVer ANY"),Ru=class{static get ANY(){return $d}constructor(e,t){if(t=N7(t),e instanceof Ru){if(e.loose===!!t.loose)return e;e=e.value}VS("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===$d?this.value="":this.value=this.operator+this.semver.version,VS("comp",this)}parse(e){let t=this.options.loose?eM[tM.COMPARATORLOOSE]:eM[tM.COMPARATOR],i=e.match(t);if(!i)throw new TypeError(`Invalid comparator: ${e}`);this.operator=i[1]!==void 0?i[1]:"",this.operator==="="&&(this.operator=""),i[2]?this.semver=new iM(i[2],this.options.loose):this.semver=$d}toString(){return this.value}test(e){if(VS("Comparator.test",e,this.options.loose),this.semver===$d||e===$d)return!0;if(typeof e=="string")try{e=new iM(e,this.options)}catch{return!1}return QS(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof Ru))throw new TypeError("a Comparator is required");if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),this.operator==="")return this.value===""?!0:new nM(e.value,t).test(this.value);if(e.operator==="")return e.value===""?!0:new nM(this.value,t).test(e.semver);let i=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">"),r=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<"),o=this.semver.version===e.semver.version,s=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),a=QS(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),l=QS(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return i||r||o&&s||a||l}};rM.exports=Ru;var N7=qd(),{re:eM,t:tM}=Za(),QS=$S(),VS=Bd(),iM=Vi(),nM=or()});var Ud=w((Jye,oM)=>{var H7=or(),B7=(n,e,t)=>{try{e=new H7(e,t)}catch{return!1}return e.test(n)};oM.exports=B7});var aM=w(($ye,sM)=>{var q7=or(),W7=(n,e)=>new q7(n,e).set.map(t=>t.map(i=>i.value).join(" ").trim().split(" "));sM.exports=W7});var uM=w((Uye,lM)=>{var Y7=Vi(),Z7=or(),J7=(n,e,t)=>{let i=null,r=null,o=null;try{o=new Z7(e,t)}catch{return null}return n.forEach(s=>{o.test(s)&&(!i||r.compare(s)===-1)&&(i=s,r=new Y7(i,t))}),i};lM.exports=J7});var dM=w((Xye,cM)=>{var $7=Vi(),U7=or(),X7=(n,e,t)=>{let i=null,r=null,o=null;try{o=new U7(e,t)}catch{return null}return n.forEach(s=>{o.test(s)&&(!i||r.compare(s)===1)&&(i=s,r=new $7(i,t))}),i};cM.exports=X7});var pM=w((Gye,gM)=>{var eD=Vi(),G7=or(),hM=Wd(),z7=(n,e)=>{n=new G7(n,e);let t=new eD("0.0.0");if(n.test(t)||(t=new eD("0.0.0-0"),n.test(t)))return t;t=null;for(let i=0;i{let a=new eD(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||hM(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),o&&(!t||hM(t,o))&&(t=o)}return t&&n.test(t)?t:null};gM.exports=z7});var mM=w((zye,fM)=>{var K7=or(),Q7=(n,e)=>{try{return new K7(n,e).range||"*"}catch{return null}};fM.exports=Q7});var Fb=w((Kye,wM)=>{var V7=Vi(),vM=Jd(),{ANY:e9}=vM,t9=or(),i9=Ud(),bM=Wd(),yM=kb(),n9=Rb(),r9=Pb(),o9=(n,e,t,i)=>{n=new V7(n,i),e=new t9(e,i);let r,o,s,a,l;switch(t){case">":r=bM,o=n9,s=yM,a=">",l=">=";break;case"<":r=yM,o=r9,s=bM,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(i9(n,e,i))return!1;for(let u=0;u{g.semver===e9&&(g=new vM(">=0.0.0")),d=d||g,h=h||g,r(g.semver,d.semver,i)?d=g:s(g.semver,h.semver,i)&&(h=g)}),d.operator===a||d.operator===l||(!h.operator||h.operator===a)&&o(n,h.semver))return!1;if(h.operator===l&&s(n,h.semver))return!1}return!0};wM.exports=o9});var CM=w((Qye,xM)=>{var s9=Fb(),a9=(n,e,t)=>s9(n,e,">",t);xM.exports=a9});var DM=w((Vye,SM)=>{var l9=Fb(),u9=(n,e,t)=>l9(n,e,"<",t);SM.exports=u9});var PM=w((eve,kM)=>{var TM=or(),c9=(n,e,t)=>(n=new TM(n,t),e=new TM(e,t),n.intersects(e));kM.exports=c9});var _M=w((tve,RM)=>{var d9=Ud(),h9=rr();RM.exports=(n,e,t)=>{let i=[],r=null,o=null,s=n.sort((c,d)=>h9(c,d,t));for(let c of s)d9(c,e,t)?(o=c,r||(r=c)):(o&&i.push([r,o]),o=null,r=null);r&&i.push([r,null]);let a=[];for(let[c,d]of i)c===d?a.push(c):!d&&c===s[0]?a.push("*"):d?c===s[0]?a.push(`<=${d}`):a.push(`${c} - ${d}`):a.push(`>=${c}`);let l=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length{var EM=or(),Mb=Jd(),{ANY:tD}=Mb,Xd=Ud(),iD=rr(),g9=(n,e,t={})=>{if(n===e)return!0;n=new EM(n,t),e=new EM(e,t);let i=!1;e:for(let r of n.set){for(let o of e.set){let s=p9(r,o,t);if(i=i||s!==null,s)continue e}if(i)return!1}return!0},p9=(n,e,t)=>{if(n===e)return!0;if(n.length===1&&n[0].semver===tD){if(e.length===1&&e[0].semver===tD)return!0;t.includePrerelease?n=[new Mb(">=0.0.0-0")]:n=[new Mb(">=0.0.0")]}if(e.length===1&&e[0].semver===tD){if(t.includePrerelease)return!0;e=[new Mb(">=0.0.0")]}let i=new Set,r,o;for(let g of n)g.operator===">"||g.operator===">="?r=IM(r,g,t):g.operator==="<"||g.operator==="<="?o=LM(o,g,t):i.add(g.semver);if(i.size>1)return null;let s;if(r&&o){if(s=iD(r.semver,o.semver,t),s>0)return null;if(s===0&&(r.operator!==">="||o.operator!=="<="))return null}for(let g of i){if(r&&!Xd(g,String(r),t)||o&&!Xd(g,String(o),t))return null;for(let f of e)if(!Xd(g,String(f),t))return!1;return!0}let a,l,u,c,d=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1,h=r&&!t.includePrerelease&&r.semver.prerelease.length?r.semver:!1;d&&d.prerelease.length===1&&o.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let g of e){if(c=c||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",r){if(h&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===h.major&&g.semver.minor===h.minor&&g.semver.patch===h.patch&&(h=!1),g.operator===">"||g.operator===">="){if(a=IM(r,g,t),a===g&&a!==r)return!1}else if(r.operator===">="&&!Xd(r.semver,String(g),t))return!1}if(o){if(d&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===d.major&&g.semver.minor===d.minor&&g.semver.patch===d.patch&&(d=!1),g.operator==="<"||g.operator==="<="){if(l=LM(o,g,t),l===g&&l!==o)return!1}else if(o.operator==="<="&&!Xd(o.semver,String(g),t))return!1}if(!g.operator&&(o||r)&&s!==0)return!1}return!(r&&u&&!o&&s!==0||o&&c&&!r&&s!==0||h||d)},IM=(n,e,t)=>{if(!n)return e;let i=iD(n.semver,e.semver,t);return i>0?n:i<0||e.operator===">"&&n.operator===">="?e:n},LM=(n,e,t)=>{if(!n)return e;let i=iD(n.semver,e.semver,t);return i<0?n:i>0||e.operator==="<"&&n.operator==="<="?e:n};FM.exports=g9});var AM=w((nve,OM)=>{var nD=Za(),f9=Hd(),m9=Vi(),jM=ZS(),b9=Ja(),y9=rF(),v9=sF(),w9=uF(),x9=fF(),C9=bF(),S9=vF(),D9=xF(),T9=SF(),k9=rr(),P9=TF(),R9=PF(),_9=Tb(),E9=IF(),I9=FF(),L9=Wd(),F9=kb(),M9=Db(),j9=JS(),O9=Pb(),A9=Rb(),N9=$S(),H9=qF(),B9=Jd(),q9=or(),W9=Ud(),Y9=aM(),Z9=uM(),J9=dM(),$9=pM(),U9=mM(),X9=Fb(),G9=CM(),z9=DM(),K9=PM(),Q9=_M(),V9=MM();OM.exports={parse:b9,valid:y9,clean:v9,inc:w9,diff:x9,major:C9,minor:S9,patch:D9,prerelease:T9,compare:k9,rcompare:P9,compareLoose:R9,compareBuild:_9,sort:E9,rsort:I9,gt:L9,lt:F9,eq:M9,neq:j9,gte:O9,lte:A9,cmp:N9,coerce:H9,Comparator:B9,Range:q9,satisfies:W9,toComparators:Y9,maxSatisfying:Z9,minSatisfying:J9,minVersion:$9,validRange:U9,outside:X9,gtr:G9,ltr:z9,intersects:K9,simplifyRange:Q9,subset:V9,SemVer:m9,re:nD.re,src:nD.src,tokens:nD.t,SEMVER_SPEC_VERSION:f9.SEMVER_SPEC_VERSION,compareIdentifiers:jM.compareIdentifiers,rcompareIdentifiers:jM.rcompareIdentifiers}});var HM=w((rve,NM)=>{"use strict";NM.exports=({onlyFirst:n=!1}={})=>{let e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(e,n?void 0:"g")}});var jb=w((ove,BM)=>{"use strict";var eee=HM();BM.exports=n=>typeof n=="string"?n.replace(eee(),""):n});var XM=w((sve,UM)=>{var uo=-1,jr=1,kn=0;function Gd(n,e,t,i){if(n===e)return n?[[kn,n]]:[];if(t!=null){var r=oee(n,e,t);if(r)return r}var o=oD(n,e),s=n.substring(0,o);n=n.substring(o),e=e.substring(o),o=sD(n,e);var a=n.substring(n.length-o);n=n.substring(0,n.length-o),e=e.substring(0,e.length-o);var l=tee(n,e);return s&&l.unshift([kn,s]),a&&l.push([kn,a]),WM(l,i),l}function tee(n,e){var t;if(!n)return[[jr,e]];if(!e)return[[uo,n]];var i=n.length>e.length?n:e,r=n.length>e.length?e:n,o=i.indexOf(r);if(o!==-1)return t=[[jr,i.substring(0,o)],[kn,r],[jr,i.substring(o+r.length)]],n.length>e.length&&(t[0][0]=t[2][0]=uo),t;if(r.length===1)return[[uo,n],[jr,e]];var s=nee(n,e);if(s){var a=s[0],l=s[1],u=s[2],c=s[3],d=s[4],h=Gd(a,u),g=Gd(l,c);return h.concat([[kn,d]],g)}return iee(n,e)}function iee(n,e){for(var t=n.length,i=e.length,r=Math.ceil((t+i)/2),o=r,s=2*r,a=new Array(s),l=new Array(s),u=0;ut)g+=2;else if(k>i)h+=2;else if(d){var T=o+c-v;if(T>=0&&T=j)return qM(n,e,C,k)}}}for(var N=-b+f;N<=b-m;N+=2){var T=o+N,j;N===-b||N!==b&&l[T-1]t)m+=2;else if(X>i)f+=2;else if(!d){var x=o+c-N;if(x>=0&&x=j)return qM(n,e,C,k)}}}}return[[uo,n],[jr,e]]}function qM(n,e,t,i){var r=n.substring(0,t),o=e.substring(0,i),s=n.substring(t),a=e.substring(i),l=Gd(r,o),u=Gd(s,a);return l.concat(u)}function oD(n,e){if(!n||!e||n.charAt(0)!==e.charAt(0))return 0;for(var t=0,i=Math.min(n.length,e.length),r=i,o=0;te.length?n:e,i=n.length>e.length?e:n;if(t.length<4||i.length*2=g.length?[C,k,T,j,x]:null}var o=r(t,i,Math.ceil(t.length/4)),s=r(t,i,Math.ceil(t.length/2)),a;if(!o&&!s)return null;s?o?a=o[4].length>s[4].length?o:s:a=s:a=o;var l,u,c,d;n.length>e.length?(l=a[0],u=a[1],c=a[2],d=a[3]):(c=a[0],d=a[1],l=a[2],u=a[3]);var h=a[4];return[l,u,c,d,h]}function WM(n,e){n.push([kn,""]);for(var t=0,i=0,r=0,o="",s="",a;t=0&&$M(n[l][1])){var u=n[l][1].slice(-1);if(n[l][1]=n[l][1].slice(0,-1),o=u+o,s=u+s,!n[l][1]){n.splice(l,1),t--;var c=l-1;n[c]&&n[c][0]===jr&&(r++,s=n[c][1]+s,c--),n[c]&&n[c][0]===uo&&(i++,o=n[c][1]+o,c--),l=c}}if(JM(n[t][1])){var u=n[t][1].charAt(0);n[t][1]=n[t][1].slice(1),o+=u,s+=u}}if(t0||s.length>0){o.length>0&&s.length>0&&(a=oD(s,o),a!==0&&(l>=0?n[l][1]+=s.substring(0,a):(n.splice(0,0,[kn,s.substring(0,a)]),t++),s=s.substring(a),o=o.substring(a)),a=sD(s,o),a!==0&&(n[t][1]=s.substring(s.length-a)+n[t][1],s=s.substring(0,s.length-a),o=o.substring(0,o.length-a)));var d=r+i;o.length===0&&s.length===0?(n.splice(t-d,d),t=t-d):o.length===0?(n.splice(t-d,d,[jr,s]),t=t-d+1):s.length===0?(n.splice(t-d,d,[uo,o]),t=t-d+1):(n.splice(t-d,d,[uo,o],[jr,s]),t=t-d+2)}t!==0&&n[t-1][0]===kn?(n[t-1][1]+=n[t][1],n.splice(t,1)):t++,r=0,i=0,o="",s="";break}}n[n.length-1][1]===""&&n.pop();var h=!1;for(t=1;t=55296&&n<=56319}function ZM(n){return n>=56320&&n<=57343}function JM(n){return ZM(n.charCodeAt(0))}function $M(n){return YM(n.charCodeAt(n.length-1))}function ree(n){for(var e=[],t=0;t0&&e.push(n[t]);return e}function rD(n,e,t,i){return $M(n)||JM(i)?null:ree([[kn,n],[uo,e],[jr,t],[kn,i]])}function oee(n,e,t){var i=typeof t=="number"?{index:t,length:0}:t.oldRange,r=typeof t=="number"?null:t.newRange,o=n.length,s=e.length;if(i.length===0&&(r===null||r.length===0)){var a=i.index,l=n.slice(0,a),u=n.slice(a),c=r?r.index:null;e:{var d=a+s-o;if(c!==null&&c!==d||d<0||d>s)break e;var h=e.slice(0,d),g=e.slice(d);if(g!==u)break e;var f=Math.min(a,d),m=l.slice(0,f),b=h.slice(0,f);if(m!==b)break e;var v=l.slice(f),x=h.slice(f);return rD(m,v,x,u)}e:{if(c!==null&&c!==a)break e;var C=a,h=e.slice(0,C),g=e.slice(C);if(h!==l)break e;var k=Math.min(o-C,s-C),T=u.slice(u.length-k),j=g.slice(g.length-k);if(T!==j)break e;var v=u.slice(0,u.length-k),x=g.slice(0,g.length-k);return rD(l,v,x,T)}}if(i.length>0&&r&&r.length===0){e:{var m=n.slice(0,i.index),T=n.slice(i.index+i.length),f=m.length,k=T.length;if(s{GM.exports=["\0","","","","","","","\x07","\b"," ",` +`,"\v","\f","\r","","","","","","","","","","","","","","\x1B","","","",""," ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/","0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","[","\\","]","^","_","`","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","{","|","}","~","\x7F","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""," ","!","C/","PS","$?","Y=","|","SS",'"',"(c)","a","<<","!","","(r)","-","deg","+-","2","3","'","u","P","*",",","1","o",">>","1/4","1/2","3/4","?","A","A","A","A","A","A","AE","C","E","E","E","E","I","I","I","I","D","N","O","O","O","O","O","x","O","U","U","U","U","U","Th","ss","a","a","a","a","a","a","ae","c","e","e","e","e","i","i","i","i","d","n","o","o","o","o","o","/","o","u","u","u","u","y","th","y"]});var QM=w((lve,KM)=>{KM.exports=["A","a","A","a","A","a","C","c","C","c","C","c","C","c","D","d","D","d","E","e","E","e","E","e","E","e","E","e","G","g","G","g","G","g","G","g","H","h","H","h","I","i","I","i","I","i","I","i","I","i","IJ","","J","j","K","k","k","L","l","L","l","L","l","L","l","L","l","N","n","N","n","N","n","'n","ng","NG","O","o","O","o","O","o","OE","oe","R","r","R","r","R","r","S","s","S","s","S","s","S","s","T","t","T","t","T","t","U","u","U","u","U","u","U","u","U","u","U","u","W","w","Y","y","Y","Z","z","Z","z","Z","z","s","b","B","B","b","6","6","O","C","c","D","D","D","d","d","3","@","E","F","f","G","G","hv","I","I","K","k","l","l","W","N","n","O","O","o","OI","oi","P","p","YR","2","2","SH","sh","t","T","t","T","U","u","Y","V","Y","y","Z","z","ZH","ZH","zh","zh","2","5","5","ts","w","|","||","|=","!","DZ","Dz","dz","LJ","Lj","lj","NJ","Nj","nj","A","a","I","i","O","o","U","u","U","u","U","u","U","u","U","u","@","A","a","A","a","AE","ae","G","g","G","g","K","k","O","o","O","o","ZH","zh","j","DZ","D","dz","G","g","HV","W","N","n","A","a","AE","ae","O","o"]});var ej=w((uve,VM)=>{VM.exports=["A","a","A","a","E","e","E","e","I","i","I","i","O","o","O","o","R","r","R","r","U","u","U","u","S","s","T","t","Y","y","H","h","[?]","[?]","OU","ou","Z","z","A","a","E","e","O","o","O","o","O","o","O","o","Y","y","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","a","a","a","b","o","c","d","d","e","@","@","e","e","e","e","j","g","g","g","g","u","Y","h","h","i","i","I","l","l","l","lZ","W","W","m","n","n","n","o","OE","O","F","R","R","R","R","r","r","R","R","R","s","S","j","S","S","t","t","U","U","v","^","W","Y","Y","z","z","Z","Z","?","?","?","C","@","B","E","G","H","j","k","L","q","?","?","dz","dZ","dz","ts","tS","tC","fN","ls","lz","WW","]]","[?]","[?]","k","h","j","r","r","r","r","w","y","'",'"',"`","'","`","`","'","?","?","<",">","^","V","^","V","'","-","/","\\",",","_","\\","/",":",".","`","'","^","V","+","-","V",".","@",",","~",'"',"R","X","G","l","s","x","?","","","","","","","","V","=",'"',"[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var ij=w((cve,tj)=>{tj.exports=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","'",",","[?]","[?]","[?]","[?]","","[?]","[?]","[?]","?","[?]","[?]","[?]","[?]","[?]","","","A",";","E","E","I","[?]","O","[?]","U","O","I","A","B","G","D","E","Z","E","Th","I","K","L","M","N","Ks","O","P","R","[?]","S","T","U","Ph","Kh","Ps","O","I","U","a","e","e","i","u","a","b","g","d","e","z","e","th","i","k","l","m","n","x","o","p","r","s","s","t","u","ph","kh","ps","o","i","u","o","u","o","[?]","b","th","U","U","U","ph","p","&","[?]","[?]","St","st","W","w","Q","q","Sp","sp","Sh","sh","F","f","Kh","kh","H","h","G","g","CH","ch","Ti","ti","k","r","c","j","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var rj=w((dve,nj)=>{nj.exports=["Ie","Io","Dj","Gj","Ie","Dz","I","Yi","J","Lj","Nj","Tsh","Kj","I","U","Dzh","A","B","V","G","D","Ie","Zh","Z","I","I","K","L","M","N","O","P","R","S","T","U","F","Kh","Ts","Ch","Sh","Shch","","Y","'","E","Iu","Ia","a","b","v","gh","d","ie","zh","z","i","i","k","l","m","n","o","p","r","s","t","u","f","kh","ts","ch","sh","shch","","y","'","e","iu","ia","ie","io","dj","gj","ie","dz","i","yi","j","lj","nj","tsh","kj","i","u","dzh","O","o","E","e","Ie","ie","E","e","Ie","ie","O","o","Io","io","Ks","ks","Ps","ps","F","f","Y","y","Y","y","u","u","O","o","O","o","Ot","ot","Q","q","*1000*","","","","","[?]","*100.000*","*1.000.000*","[?]","[?]",'"','"',"R'","r'","G'","g'","G'","g'","G'","g'","Zh'","zh'","Z'","z'","K'","k'","K'","k'","K'","k'","K'","k'","N'","n'","Ng","ng","P'","p'","Kh","kh","S'","s'","T'","t'","U","u","U'","u'","Kh'","kh'","Tts","tts","Ch'","ch'","Ch'","ch'","H","h","Ch","ch","Ch'","ch'","`","Zh","zh","K'","k'","[?]","[?]","N'","n'","[?]","[?]","Ch","ch","[?]","[?]","[?]","a","a","A","a","Ae","ae","Ie","ie","@","@","@","@","Zh","zh","Z","z","Dz","dz","I","i","I","i","O","o","O","o","O","o","E","e","U","u","U","u","U","u","Ch","ch","[?]","[?]","Y","y","[?]","[?]","[?]","[?]","[?]"]});var sj=w((hve,oj)=>{oj.exports=["[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","A","B","G","D","E","Z","E","E","T`","Zh","I","L","Kh","Ts","K","H","Dz","Gh","Ch","M","Y","N","Sh","O","Ch`","P","J","Rh","S","V","T","R","Ts`","W","P`","K`","O","F","[?]","[?]","<","'","/","!",",","?",".","[?]","a","b","g","d","e","z","e","e","t`","zh","i","l","kh","ts","k","h","dz","gh","ch","m","y","n","sh","o","ch`","p","j","rh","s","v","t","r","ts`","w","p`","k`","o","f","ew","[?]",".","-","[?]","[?]","[?]","[?]","[?]","[?]","","","","","","","","","","","","","","","","","","[?]","","","","","","","","","","","","","","@","e","a","o","i","e","e","a","a","o","[?]","u","'","","","","","","",":","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","","b","g","d","h","v","z","kh","t","y","k","k","l","m","m","n","n","s","`","p","p","ts","ts","q","r","sh","t","[?]","[?]","[?]","[?]","[?]","V","oy","i","'",'"',"[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var lj=w((gve,aj)=>{aj.exports=["[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]",",","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]",";","[?]","[?]","[?]","?","[?]","","a","'","w'","","y'","","b","@","t","th","j","H","kh","d","dh","r","z","s","sh","S","D","T","Z","aa","G","[?]","[?]","[?]","[?]","[?]","","f","q","k","l","m","n","h","w","~","y","an","un","in","a","u","i","W","","","'","'","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","0","1","2","3","4","5","6","7","8","9","%",".",",","*","[?]","[?]","","'","'","'","","'","'w","'u","'y","tt","tth","b","t","T","p","th","bh","'h","H","ny","dy","H","ch","cch","dd","D","D","Dt","dh","ddh","d","D","D","rr","R","R","R","R","R","R","j","R","S","S","S","S","S","T","GH","F","F","F","v","f","ph","Q","Q","kh","k","K","K","ng","K","g","G","N","G","G","G","L","L","L","L","N","N","N","N","N","h","Ch","hy","h","H","@","W","oe","oe","u","yu","yu","W","v","y","Y","Y","W","","","y","y'",".","ae","","","","","","","","@","#","","","","","","","","","","","^","","","","","[?]","[?]","0","1","2","3","4","5","6","7","8","9","Sh","D","Gh","&","+m"]});var cj=w((pve,uj)=>{uj.exports=["//","/",",","!","!","-",",",",",";","?","~","{","}","*","[?]","","'","","b","g","g","d","d","h","w","z","H","t","t","y","yh","k","l","m","n","s","s","`","p","p","S","q","r","sh","t","[?]","[?]","[?]","a","a","a","A","A","A","e","e","e","E","i","i","u","u","u","o","","`","'","","","X","Q","@","@","|","+","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","h","sh","n","r","b","L","k","'","v","m","f","dh","th","l","g","ny","s","d","z","t","y","p","j","ch","tt","hh","kh","th","z","sh","s","d","t","z","`","gh","q","w","a","aa","i","ee","u","oo","e","ey","o","oa","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var hj=w((fve,dj)=>{dj.exports=["[?]","N","N","H","[?]","a","aa","i","ii","u","uu","R","L","eN","e","e","ai","oN","o","o","au","k","kh","g","gh","ng","c","ch","j","jh","ny","tt","tth","dd","ddh","nn","t","th","d","dh","n","nnn","p","ph","b","bh","m","y","r","rr","l","l","lll","v","sh","ss","s","h","[?]","[?]","'","'","aa","i","ii","u","uu","R","RR","eN","e","e","ai","oN","o","o","au","","[?]","[?]","AUM","'","'","`","'","[?]","[?]","[?]","q","khh","ghh","z","dddh","rh","f","yy","RR","LL","L","LL"," / "," // ","0","1","2","3","4","5","6","7","8","9",".","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","N","N","H","[?]","a","aa","i","ii","u","uu","R","RR","[?]","[?]","e","ai","[?]","[?]","o","au","k","kh","g","gh","ng","c","ch","j","jh","ny","tt","tth","dd","ddh","nn","t","th","d","dh","n","[?]","p","ph","b","bh","m","y","r","[?]","l","[?]","[?]","[?]","sh","ss","s","h","[?]","[?]","'","[?]","aa","i","ii","u","uu","R","RR","[?]","[?]","e","ai","[?]","[?]","o","au","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","+","[?]","[?]","[?]","[?]","rr","rh","[?]","yy","RR","LL","L","LL","[?]","[?]","0","1","2","3","4","5","6","7","8","9","r'","r`","Rs","Rs","1/","2/","3/","4/"," 1 - 1/","/16","","[?]","[?]","[?]","[?]"]});var pj=w((mve,gj)=>{gj.exports=["[?]","[?]","N","[?]","[?]","a","aa","i","ii","u","uu","[?]","[?]","[?]","[?]","ee","ai","[?]","[?]","oo","au","k","kh","g","gh","ng","c","ch","j","jh","ny","tt","tth","dd","ddh","nn","t","th","d","dh","n","[?]","p","ph","b","bb","m","y","r","[?]","l","ll","[?]","v","sh","[?]","s","h","[?]","[?]","'","[?]","aa","i","ii","u","uu","[?]","[?]","[?]","[?]","ee","ai","[?]","[?]","oo","au","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","khh","ghh","z","rr","[?]","f","[?]","[?]","[?]","[?]","[?]","[?]","[?]","0","1","2","3","4","5","6","7","8","9","N","H","","","G.E.O.","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","N","N","H","[?]","a","aa","i","ii","u","uu","R","[?]","eN","[?]","e","ai","oN","[?]","o","au","k","kh","g","gh","ng","c","ch","j","jh","ny","tt","tth","dd","ddh","nn","t","th","d","dh","n","[?]","p","ph","b","bh","m","ya","r","[?]","l","ll","[?]","v","sh","ss","s","h","[?]","[?]","'","'","aa","i","ii","u","uu","R","RR","eN","[?]","e","ai","oN","[?]","o","au","","[?]","[?]","AUM","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","RR","[?]","[?]","[?]","[?]","[?]","0","1","2","3","4","5","6","7","8","9","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var mj=w((bve,fj)=>{fj.exports=["[?]","N","N","H","[?]","a","aa","i","ii","u","uu","R","L","[?]","[?]","e","ai","[?]","[?]","o","au","k","kh","g","gh","ng","c","ch","j","jh","ny","tt","tth","dd","ddh","nn","t","th","d","dh","n","[?]","p","ph","b","bh","m","y","r","[?]","l","ll","[?]","","sh","ss","s","h","[?]","[?]","'","'","aa","i","ii","u","uu","R","[?]","[?]","[?]","e","ai","[?]","[?]","o","au","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","+","+","[?]","[?]","[?]","[?]","rr","rh","[?]","yy","RR","LL","[?]","[?]","[?]","[?]","0","1","2","3","4","5","6","7","8","9","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","N","H","[?]","a","aa","i","ii","u","uu","[?]","[?]","[?]","e","ee","ai","[?]","o","oo","au","k","[?]","[?]","[?]","ng","c","[?]","j","[?]","ny","tt","[?]","[?]","[?]","nn","t","[?]","[?]","[?]","n","nnn","p","[?]","[?]","[?]","m","y","r","rr","l","ll","lll","v","[?]","ss","s","h","[?]","[?]","[?]","[?]","aa","i","ii","u","uu","[?]","[?]","[?]","e","ee","ai","[?]","o","oo","au","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","+","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","0","1","2","3","4","5","6","7","8","9","+10+","+100+","+1000+","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var yj=w((yve,bj)=>{bj.exports=["[?]","N","N","H","[?]","a","aa","i","ii","u","uu","R","L","[?]","e","ee","ai","[?]","o","oo","au","k","kh","g","gh","ng","c","ch","j","jh","ny","tt","tth","dd","ddh","nn","t","th","d","dh","n","[?]","p","ph","b","bh","m","y","r","rr","l","ll","[?]","v","sh","ss","s","h","[?]","[?]","[?]","[?]","aa","i","ii","u","uu","R","RR","[?]","e","ee","ai","[?]","o","oo","au","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","+","+","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","RR","LL","[?]","[?]","[?]","[?]","0","1","2","3","4","5","6","7","8","9","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","N","H","[?]","a","aa","i","ii","u","uu","R","L","[?]","e","ee","ai","[?]","o","oo","au","k","kh","g","gh","ng","c","ch","j","jh","ny","tt","tth","dd","ddh","nn","t","th","d","dh","n","[?]","p","ph","b","bh","m","y","r","rr","l","ll","[?]","v","sh","ss","s","h","[?]","[?]","[?]","[?]","aa","i","ii","u","uu","R","RR","[?]","e","ee","ai","[?]","o","oo","au","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","+","+","[?]","[?]","[?]","[?]","[?]","[?]","[?]","lll","[?]","RR","LL","[?]","[?]","[?]","[?]","0","1","2","3","4","5","6","7","8","9","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var wj=w((vve,vj)=>{vj.exports=["[?]","[?]","N","H","[?]","a","aa","i","ii","u","uu","R","L","[?]","e","ee","ai","[?]","o","oo","au","k","kh","g","gh","ng","c","ch","j","jh","ny","tt","tth","dd","ddh","nn","t","th","d","dh","n","[?]","p","ph","b","bh","m","y","r","rr","l","ll","lll","v","sh","ss","s","h","[?]","[?]","[?]","[?]","aa","i","ii","u","uu","R","[?]","[?]","e","ee","ai","","o","oo","au","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","+","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","RR","LL","[?]","[?]","[?]","[?]","0","1","2","3","4","5","6","7","8","9","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","N","H","[?]","a","aa","ae","aae","i","ii","u","uu","R","RR","L","LL","e","ee","ai","o","oo","au","[?]","[?]","[?]","k","kh","g","gh","ng","nng","c","ch","j","jh","ny","jny","nyj","tt","tth","dd","ddh","nn","nndd","t","th","d","dh","n","[?]","nd","p","ph","b","bh","m","mb","y","r","[?]","l","[?]","[?]","v","sh","ss","s","h","ll","f","[?]","[?]","[?]","","[?]","[?]","[?]","[?]","aa","ae","aae","i","ii","u","[?]","uu","[?]","R","e","ee","ai","o","oo","au","L","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","RR","LL"," . ","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var Cj=w((wve,xj)=>{xj.exports=["[?]","k","kh","kh","kh","kh","kh","ng","cch","ch","ch","ch","ch","y","d","t","th","th","th","n","d","t","th","th","th","n","b","p","ph","f","ph","f","ph","m","y","r","R","l","L","w","s","s","s","h","l","`","h","~","a","a","aa","am","i","ii","ue","uue","u","uu","'","[?]","[?]","[?]","[?]","Bh.","e","ae","o","ai","ai","ao","+","","","","","","","M",""," * ","0","1","2","3","4","5","6","7","8","9"," // "," /// ","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","k","kh","[?]","kh","[?]","[?]","ng","ch","[?]","s","[?]","[?]","ny","[?]","[?]","[?]","[?]","[?]","[?]","d","h","th","th","[?]","n","b","p","ph","f","ph","f","[?]","m","y","r","[?]","l","[?]","w","[?]","[?]","s","h","[?]","`","","~","a","","aa","am","i","ii","y","yy","u","uu","[?]","o","l","ny","[?]","[?]","e","ei","o","ay","ai","[?]","+","[?]","","","","","","M","[?]","[?]","0","1","2","3","4","5","6","7","8","9","[?]","[?]","hn","hm","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var Dj=w((xve,Sj)=>{Sj.exports=["AUM","","","","","","",""," // "," * ","","-"," / "," / "," // "," -/ "," +/ "," X/ "," /XX/ "," /X/ ",", ","","","","","","","","","","","","0","1","2","3","4","5","6","7","8","9",".5","1.5","2.5","3.5","4.5","5.5","6.5","7.5","8.5","-.5","+","*","^","_","","~","[?]","]","[[","]]","","","k","kh","g","gh","ng","c","ch","j","[?]","ny","tt","tth","dd","ddh","nn","t","th","d","dh","n","p","ph","b","bh","m","ts","tsh","dz","dzh","w","zh","z","'","y","r","l","sh","ssh","s","h","a","kss","r","[?]","[?]","[?]","[?]","[?]","[?]","aa","i","ii","u","uu","R","RR","L","LL","e","ee","o","oo","M","H","i","ii","","","","","","","","","","","[?]","[?]","[?]","[?]","k","kh","g","gh","ng","c","ch","j","[?]","ny","tt","tth","dd","ddh","nn","t","th","d","dh","n","p","ph","b","bh","m","ts","tsh","dz","dzh","w","zh","z","'","y","r","l","sh","ss","s","h","a","kss","w","y","r","[?]","X"," :X: "," /O/ "," /o/ "," \\o\\ "," (O) ","","","","","","","","","","[?]","[?]","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var kj=w((Cve,Tj)=>{Tj.exports=["k","kh","g","gh","ng","c","ch","j","jh","ny","nny","tt","tth","dd","ddh","nn","tt","th","d","dh","n","p","ph","b","bh","m","y","r","l","w","s","h","ll","a","[?]","i","ii","u","uu","e","[?]","o","au","[?]","aa","i","ii","u","uu","e","ai","[?]","[?]","[?]","N","'",":","","[?]","[?]","[?]","[?]","[?]","[?]","0","1","2","3","4","5","6","7","8","9"," / "," // ","n*","r*","l*","e*","sh","ss","R","RR","L","LL","R","RR","L","LL","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","A","B","G","D","E","V","Z","T`","I","K","L","M","N","O","P","Zh","R","S","T","U","P`","K`","G'","Q","Sh","Ch`","C`","Z'","C","Ch","X","J","H","E","Y","W","Xh","OE","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","a","b","g","d","e","v","z","t`","i","k","l","m","n","o","p","zh","r","s","t","u","p`","k`","g'","q","sh","ch`","c`","z'","c","ch","x","j","h","e","y","w","xh","oe","f","[?]","[?]","[?]","[?]"," // ","[?]","[?]","[?]"]});var Rj=w((Sve,Pj)=>{Pj.exports=["g","gg","n","d","dd","r","m","b","bb","s","ss","","j","jj","c","k","t","p","h","ng","nn","nd","nb","dg","rn","rr","rh","rN","mb","mN","bg","bn","","bs","bsg","bst","bsb","bss","bsj","bj","bc","bt","bp","bN","bbN","sg","sn","sd","sr","sm","sb","sbg","sss","s","sj","sc","sk","st","sp","sh","","","","","Z","g","d","m","b","s","Z","","j","c","t","p","N","j","","","","","ck","ch","","","pb","pN","hh","Q","[?]","[?]","[?]","[?]","[?]","","","a","ae","ya","yae","eo","e","yeo","ye","o","wa","wae","oe","yo","u","weo","we","wi","yu","eu","yi","i","a-o","a-u","ya-o","ya-yo","eo-o","eo-u","eo-eu","yeo-o","yeo-u","o-eo","o-e","o-ye","o-o","o-u","yo-ya","yo-yae","yo-yeo","yo-o","yo-i","u-a","u-ae","u-eo-eu","u-ye","u-u","yu-a","yu-eo","yu-e","yu-yeo","yu-ye","yu-u","yu-i","eu-u","eu-eu","yi-u","i-a","i-ya","i-o","i-u","i-eu","i-U","U","U-eo","U-u","U-i","UU","[?]","[?]","[?]","[?]","[?]","g","gg","gs","n","nj","nh","d","l","lg","lm","lb","ls","lt","lp","lh","m","b","bs","s","ss","ng","j","c","k","t","p","h","gl","gsg","ng","nd","ns","nZ","nt","dg","tl","lgs","ln","ld","lth","ll","lmg","lms","lbs","lbh","rNp","lss","lZ","lk","lQ","mg","ml","mb","ms","mss","mZ","mc","mh","mN","bl","bp","ph","pN","sg","sd","sl","sb","Z","g","ss","","kh","N","Ns","NZ","pb","pN","hn","hl","hm","hb","Q","[?]","[?]","[?]","[?]","[?]"]});var Ej=w((Dve,_j)=>{_j.exports=["ha","hu","hi","haa","hee","he","ho","[?]","la","lu","li","laa","lee","le","lo","lwa","hha","hhu","hhi","hhaa","hhee","hhe","hho","hhwa","ma","mu","mi","maa","mee","me","mo","mwa","sza","szu","szi","szaa","szee","sze","szo","szwa","ra","ru","ri","raa","ree","re","ro","rwa","sa","su","si","saa","see","se","so","swa","sha","shu","shi","shaa","shee","she","sho","shwa","qa","qu","qi","qaa","qee","qe","qo","[?]","qwa","[?]","qwi","qwaa","qwee","qwe","[?]","[?]","qha","qhu","qhi","qhaa","qhee","qhe","qho","[?]","qhwa","[?]","qhwi","qhwaa","qhwee","qhwe","[?]","[?]","ba","bu","bi","baa","bee","be","bo","bwa","va","vu","vi","vaa","vee","ve","vo","vwa","ta","tu","ti","taa","tee","te","to","twa","ca","cu","ci","caa","cee","ce","co","cwa","xa","xu","xi","xaa","xee","xe","xo","[?]","xwa","[?]","xwi","xwaa","xwee","xwe","[?]","[?]","na","nu","ni","naa","nee","ne","no","nwa","nya","nyu","nyi","nyaa","nyee","nye","nyo","nywa","'a","'u","[?]","'aa","'ee","'e","'o","'wa","ka","ku","ki","kaa","kee","ke","ko","[?]","kwa","[?]","kwi","kwaa","kwee","kwe","[?]","[?]","kxa","kxu","kxi","kxaa","kxee","kxe","kxo","[?]","kxwa","[?]","kxwi","kxwaa","kxwee","kxwe","[?]","[?]","wa","wu","wi","waa","wee","we","wo","[?]","`a","`u","`i","`aa","`ee","`e","`o","[?]","za","zu","zi","zaa","zee","ze","zo","zwa","zha","zhu","zhi","zhaa","zhee","zhe","zho","zhwa","ya","yu","yi","yaa","yee","ye","yo","[?]","da","du","di","daa","dee","de","do","dwa","dda","ddu","ddi","ddaa","ddee","dde","ddo","ddwa"]});var Lj=w((Tve,Ij)=>{Ij.exports=["ja","ju","ji","jaa","jee","je","jo","jwa","ga","gu","gi","gaa","gee","ge","go","[?]","gwa","[?]","gwi","gwaa","gwee","gwe","[?]","[?]","gga","ggu","ggi","ggaa","ggee","gge","ggo","[?]","tha","thu","thi","thaa","thee","the","tho","thwa","cha","chu","chi","chaa","chee","che","cho","chwa","pha","phu","phi","phaa","phee","phe","pho","phwa","tsa","tsu","tsi","tsaa","tsee","tse","tso","tswa","tza","tzu","tzi","tzaa","tzee","tze","tzo","[?]","fa","fu","fi","faa","fee","fe","fo","fwa","pa","pu","pi","paa","pee","pe","po","pwa","rya","mya","fya","[?]","[?]","[?]","[?]","[?]","[?]"," ",".",",",";",":",":: ","?","//","1","2","3","4","5","6","7","8","9","10+","20+","30+","40+","50+","60+","70+","80+","90+","100+","10,000+","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","a","e","i","o","u","v","ga","ka","ge","gi","go","gu","gv","ha","he","hi","ho","hu","hv","la","le","li","lo","lu","lv","ma","me","mi","mo","mu","na","hna","nah","ne","ni","no","nu","nv","qua","que","qui","quo","quu","quv","sa","s","se","si","so","su","sv","da","ta","de","te","di","ti","do","du","dv","dla","tla","tle","tli","tlo","tlu","tlv","tsa","tse","tsi","tso","tsu","tsv","wa","we","wi","wo","wu","wv","ya","ye","yi","yo","yu","yv","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var Mj=w((kve,Fj)=>{Fj.exports=["[?]","e","aai","i","ii","o","oo","oo","ee","i","a","aa","we","we","wi","wi","wii","wii","wo","wo","woo","woo","woo","wa","wa","waa","waa","waa","ai","w","'","t","k","sh","s","n","w","n","[?]","w","c","?","l","en","in","on","an","pe","paai","pi","pii","po","poo","poo","hee","hi","pa","paa","pwe","pwe","pwi","pwi","pwii","pwii","pwo","pwo","pwoo","pwoo","pwa","pwa","pwaa","pwaa","pwaa","p","p","h","te","taai","ti","tii","to","too","too","dee","di","ta","taa","twe","twe","twi","twi","twii","twii","two","two","twoo","twoo","twa","twa","twaa","twaa","twaa","t","tte","tti","tto","tta","ke","kaai","ki","kii","ko","koo","koo","ka","kaa","kwe","kwe","kwi","kwi","kwii","kwii","kwo","kwo","kwoo","kwoo","kwa","kwa","kwaa","kwaa","kwaa","k","kw","keh","kih","koh","kah","ce","caai","ci","cii","co","coo","coo","ca","caa","cwe","cwe","cwi","cwi","cwii","cwii","cwo","cwo","cwoo","cwoo","cwa","cwa","cwaa","cwaa","cwaa","c","th","me","maai","mi","mii","mo","moo","moo","ma","maa","mwe","mwe","mwi","mwi","mwii","mwii","mwo","mwo","mwoo","mwoo","mwa","mwa","mwaa","mwaa","mwaa","m","m","mh","m","m","ne","naai","ni","nii","no","noo","noo","na","naa","nwe","nwe","nwa","nwa","nwaa","nwaa","nwaa","n","ng","nh","le","laai","li","lii","lo","loo","loo","la","laa","lwe","lwe","lwi","lwi","lwii","lwii","lwo","lwo","lwoo","lwoo","lwa","lwa","lwaa","lwaa","l","l","l","se","saai","si","sii","so","soo","soo","sa","saa","swe","swe","swi","swi","swii","swii","swo","swo","swoo","swoo"]});var Oj=w((Pve,jj)=>{jj.exports=["swa","swa","swaa","swaa","swaa","s","s","sw","s","sk","skw","sW","spwa","stwa","skwa","scwa","she","shi","shii","sho","shoo","sha","shaa","shwe","shwe","shwi","shwi","shwii","shwii","shwo","shwo","shwoo","shwoo","shwa","shwa","shwaa","shwaa","sh","ye","yaai","yi","yii","yo","yoo","yoo","ya","yaa","ywe","ywe","ywi","ywi","ywii","ywii","ywo","ywo","ywoo","ywoo","ywa","ywa","ywaa","ywaa","ywaa","y","y","y","yi","re","re","le","raai","ri","rii","ro","roo","lo","ra","raa","la","rwaa","rwaa","r","r","r","fe","faai","fi","fii","fo","foo","fa","faa","fwaa","fwaa","f","the","the","thi","thi","thii","thii","tho","thoo","tha","thaa","thwaa","thwaa","th","tthe","tthi","ttho","ttha","tth","tye","tyi","tyo","tya","he","hi","hii","ho","hoo","ha","haa","h","h","hk","qaai","qi","qii","qo","qoo","qa","qaa","q","tlhe","tlhi","tlho","tlha","re","ri","ro","ra","ngaai","ngi","ngii","ngo","ngoo","nga","ngaa","ng","nng","she","shi","sho","sha","the","thi","tho","tha","th","lhi","lhii","lho","lhoo","lha","lhaa","lh","the","thi","thii","tho","thoo","tha","thaa","th","b","e","i","o","a","we","wi","wo","wa","ne","ni","no","na","ke","ki","ko","ka","he","hi","ho","ha","ghu","gho","ghe","ghee","ghi","gha","ru","ro","re","ree","ri","ra","wu","wo","we","wee","wi","wa","hwu","hwo","hwe","hwee","hwi","hwa","thu","tho","the","thee","thi","tha","ttu","tto","tte","ttee","tti","tta","pu","po","pe","pee","pi","pa","p","gu","go","ge","gee","gi","ga","khu","kho","khe","khee","khi","kha","kku","kko","kke","kkee","kki"]});var Nj=w((Rve,Aj)=>{Aj.exports=["kka","kk","nu","no","ne","nee","ni","na","mu","mo","me","mee","mi","ma","yu","yo","ye","yee","yi","ya","ju","ju","jo","je","jee","ji","ji","ja","jju","jjo","jje","jjee","jji","jja","lu","lo","le","lee","li","la","dlu","dlo","dle","dlee","dli","dla","lhu","lho","lhe","lhee","lhi","lha","tlhu","tlho","tlhe","tlhee","tlhi","tlha","tlu","tlo","tle","tlee","tli","tla","zu","zo","ze","zee","zi","za","z","z","dzu","dzo","dze","dzee","dzi","dza","su","so","se","see","si","sa","shu","sho","she","shee","shi","sha","sh","tsu","tso","tse","tsee","tsi","tsa","chu","cho","che","chee","chi","cha","ttsu","ttso","ttse","ttsee","ttsi","ttsa","X",".","qai","ngai","nngi","nngii","nngo","nngoo","nnga","nngaa","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"," ","b","l","f","s","n","h","d","t","c","q","m","g","ng","z","r","a","o","u","e","i","ch","th","ph","p","x","p","<",">","[?]","[?]","[?]","f","v","u","yr","y","w","th","th","a","o","ac","ae","o","o","o","oe","on","r","k","c","k","g","ng","g","g","w","h","h","h","h","n","n","n","i","e","j","g","ae","a","eo","p","z","s","s","s","c","z","t","t","d","b","b","p","p","e","m","m","m","l","l","ng","ng","d","o","ear","ior","qu","qu","qu","s","yr","yr","yr","q","x",".",":","+","17","18","19","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var Bj=w((_ve,Hj)=>{Hj.exports=["[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","k","kh","g","gh","ng","c","ch","j","jh","ny","t","tth","d","ddh","nn","t","th","d","dh","n","p","ph","b","bh","m","y","r","l","v","sh","ss","s","h","l","q","a","aa","i","ii","u","uk","uu","uuv","ry","ryy","ly","lyy","e","ai","oo","oo","au","a","aa","aa","i","ii","y","yy","u","uu","ua","oe","ya","ie","e","ae","ai","oo","au","M","H","a`","","","","r","","!","","","","","","."," // ",":","+","++"," * "," /// ","KR","'","[?]","[?]","[?]","0","1","2","3","4","5","6","7","8","9","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var Wj=w((Eve,qj)=>{qj.exports=[" @ "," ... ",", ",". ",": "," // ","","-",", ",". ","","","","","","[?]","0","1","2","3","4","5","6","7","8","9","[?]","[?]","[?]","[?]","[?]","[?]","a","e","i","o","u","O","U","ee","n","ng","b","p","q","g","m","l","s","sh","t","d","ch","j","y","r","w","f","k","kha","ts","z","h","zr","lh","zh","ch","-","e","i","o","u","O","U","ng","b","p","q","g","m","t","d","ch","j","ts","y","w","k","g","h","jy","ny","dz","e","i","iy","U","u","ng","k","g","h","p","sh","t","d","j","f","g","h","ts","z","r","ch","zh","i","k","r","f","zh","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","H","X","W","M"," 3 "," 333 ","a","i","k","ng","c","tt","tth","dd","nn","t","d","p","ph","ss","zh","z","a","t","zh","gh","ng","c","jh","tta","ddh","t","dh","ss","cy","zh","z","u","y","bh","'","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var Zj=w((Ive,Yj)=>{Yj.exports=["A","a","B","b","B","b","B","b","C","c","D","d","D","d","D","d","D","d","D","d","E","e","E","e","E","e","E","e","E","e","F","f","G","g","H","h","H","h","H","h","H","h","H","h","I","i","I","i","K","k","K","k","K","k","L","l","L","l","L","l","L","l","M","m","M","m","M","m","N","n","N","n","N","n","N","n","O","o","O","o","O","o","O","o","P","p","P","p","R","r","R","r","R","r","R","r","S","s","S","s","S","s","S","s","S","s","T","t","T","t","T","t","T","t","U","u","U","u","U","u","U","u","U","u","V","v","V","v","W","w","W","w","W","w","W","w","W","w","X","x","X","x","Y","y","Z","z","Z","z","Z","z","h","t","w","y","a","S","[?]","[?]","[?]","[?]","A","a","A","a","A","a","A","a","A","a","A","a","A","a","A","a","A","a","A","a","A","a","A","a","E","e","E","e","E","e","E","e","E","e","E","e","E","e","E","e","I","i","I","i","O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o","O","o","U","u","U","u","U","u","U","u","U","u","U","u","U","u","Y","y","Y","y","Y","y","Y","y","[?]","[?]","[?]","[?]","[?]"]});var $j=w((Lve,Jj)=>{Jj.exports=["a","a","a","a","a","a","a","a","A","A","A","A","A","A","A","A","e","e","e","e","e","e","[?]","[?]","E","E","E","E","E","E","[?]","[?]","e","e","e","e","e","e","e","e","E","E","E","E","E","E","E","E","i","i","i","i","i","i","i","i","I","I","I","I","I","I","I","I","o","o","o","o","o","o","[?]","[?]","O","O","O","O","O","O","[?]","[?]","u","u","u","u","u","u","u","u","[?]","U","[?]","U","[?]","U","[?]","U","o","o","o","o","o","o","o","o","O","O","O","O","O","O","O","O","a","a","e","e","e","e","i","i","o","o","u","u","o","o","[?]","[?]","a","a","a","a","a","a","a","a","A","A","A","A","A","A","A","A","e","e","e","e","e","e","e","e","E","E","E","E","E","E","E","E","o","o","o","o","o","o","o","o","O","O","O","O","O","O","O","O","a","a","a","a","a","[?]","a","a","A","A","A","A","A","'","i","'","~",'"~',"e","e","e","[?]","e","e","E","E","E","E","E","'`","''","'~","i","i","i","i","[?]","[?]","i","i","I","I","I","I","[?]","`'","`'","`~","u","u","u","u","R","R","u","u","U","U","U","U","R",'"`',`"'`,"`","[?]","[?]","o","o","o","[?]","o","o","O","O","O","O","O","'","`"]});var Xj=w((Fve,Uj)=>{Uj.exports=[" "," "," "," "," "," "," "," "," "," "," "," ","","","","","-","-","-","-","--","--","||","_","'","'",",","'",'"','"',",,",'"',"+","++","*","*>",".","..","...",".",` +`,` + +`,"","","","",""," ","%0","%00","'","''","'''","`","``","```","^","<",">","*","!!","!?","-","_","-","^","***","--","/","-[","]-","[?]","?!","!?","7","PP","(]","[)","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","","","","","","","0","","","","4","5","6","7","8","9","+","-","=","(",")","n","0","1","2","3","4","5","6","7","8","9","+","-","=","(",")","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","ECU","CL","Cr","FF","L","mil","N","Pts","Rs","W","NS","D","EU","K","T","Dr","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","","","","","","","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var zj=w((Mve,Gj)=>{Gj.exports=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"," 1/3 "," 2/3 "," 1/5 "," 2/5 "," 3/5 "," 4/5 "," 1/6 "," 5/6 "," 1/8 "," 3/8 "," 5/8 "," 7/8 "," 1/","I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","L","C","D","M","i","ii","iii","iv","v","vi","vii","viii","ix","x","xi","xii","l","c","d","m","(D","D)","((|))",")","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","-","|","-","|","-","|","\\","/","\\","/","-","-","~","~","-","|","-","|","-","-","-","|","-","|","|","-","-","-","-","-","-","|","|","|","|","|","|","|","^","V","\\","=","V","^","-","-","|","|","-","-","|","|","=","|","=","=","|","=","|","=","=","=","=","=","=","|","=","|","=","|","\\","/","\\","/","=","=","~","~","|","|","-","|","-","|","-","-","-","|","-","|","|","|","|","|","|","|","-","\\","\\","|","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var Qj=w((jve,Kj)=>{Kj.exports=["[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var eO=w((Ove,Vj)=>{Vj.exports=["[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var iO=w((Ave,tO)=>{tO.exports=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var rO=w((Nve,nO)=>{nO.exports=["-","-","|","|","-","-","|","|","-","-","|","|","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","-","-","|","|","-","|","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","/","\\","X","-","|","-","|","-","|","-","|","-","|","-","|","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","-","|","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","^","^","^","^",">",">",">",">",">",">","V","V","V","V","<","<","<","<","<","<","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","*","#","#","#","#","#","^","^","^","O","#","#","#","#","#","#","#","#","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var sO=w((Hve,oO)=>{oO.exports=["","","","","","","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var lO=w((Bve,aO)=>{aO.exports=["[?]","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var cO=w((qve,uO)=>{uO.exports=[" ","a","1","b","'","k","2","l","@","c","i","f","/","m","s","p",'"',"e","3","h","9","o","6","r","^","d","j","g",">","n","t","q",",","*","5","<","-","u","8","v",".","%","[","$","+","x","!","&",";",":","4","\\","0","z","7","(","_","?","w","]","#","y",")","=","[d7]","[d17]","[d27]","[d127]","[d37]","[d137]","[d237]","[d1237]","[d47]","[d147]","[d247]","[d1247]","[d347]","[d1347]","[d2347]","[d12347]","[d57]","[d157]","[d257]","[d1257]","[d357]","[d1357]","[d2357]","[d12357]","[d457]","[d1457]","[d2457]","[d12457]","[d3457]","[d13457]","[d23457]","[d123457]","[d67]","[d167]","[d267]","[d1267]","[d367]","[d1367]","[d2367]","[d12367]","[d467]","[d1467]","[d2467]","[d12467]","[d3467]","[d13467]","[d23467]","[d123467]","[d567]","[d1567]","[d2567]","[d12567]","[d3567]","[d13567]","[d23567]","[d123567]","[d4567]","[d14567]","[d24567]","[d124567]","[d34567]","[d134567]","[d234567]","[d1234567]","[d8]","[d18]","[d28]","[d128]","[d38]","[d138]","[d238]","[d1238]","[d48]","[d148]","[d248]","[d1248]","[d348]","[d1348]","[d2348]","[d12348]","[d58]","[d158]","[d258]","[d1258]","[d358]","[d1358]","[d2358]","[d12358]","[d458]","[d1458]","[d2458]","[d12458]","[d3458]","[d13458]","[d23458]","[d123458]","[d68]","[d168]","[d268]","[d1268]","[d368]","[d1368]","[d2368]","[d12368]","[d468]","[d1468]","[d2468]","[d12468]","[d3468]","[d13468]","[d23468]","[d123468]","[d568]","[d1568]","[d2568]","[d12568]","[d3568]","[d13568]","[d23568]","[d123568]","[d4568]","[d14568]","[d24568]","[d124568]","[d34568]","[d134568]","[d234568]","[d1234568]","[d78]","[d178]","[d278]","[d1278]","[d378]","[d1378]","[d2378]","[d12378]","[d478]","[d1478]","[d2478]","[d12478]","[d3478]","[d13478]","[d23478]","[d123478]","[d578]","[d1578]","[d2578]","[d12578]","[d3578]","[d13578]","[d23578]","[d123578]","[d4578]","[d14578]","[d24578]","[d124578]","[d34578]","[d134578]","[d234578]","[d1234578]","[d678]","[d1678]","[d2678]","[d12678]","[d3678]","[d13678]","[d23678]","[d123678]","[d4678]","[d14678]","[d24678]","[d124678]","[d34678]","[d134678]","[d234678]","[d1234678]","[d5678]","[d15678]","[d25678]","[d125678]","[d35678]","[d135678]","[d235678]","[d1235678]","[d45678]","[d145678]","[d245678]","[d1245678]","[d345678]","[d1345678]","[d2345678]","[d12345678]"]});var hO=w((Wve,dO)=>{dO.exports=["[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?]","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var pO=w((Yve,gO)=>{gO.exports=["[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?]","[?]","[?]"]});var mO=w((Zve,fO)=>{fO.exports=[" ",", ",". ",'"',"[JIS]",'"',"/","0","<","> ","<<",">> ","[","] ","{","} ","[(",")] ","@","X ","[","] ","[[","]] ","((",")) ","[[","]] ","~ ","``","''",",,","@","1","2","3","4","5","6","7","8","9","","","","","","","~","+","+","+","+","","@"," // ","+10+","+20+","+30+","[?]","[?]","[?]","","","[?]","a","a","i","i","u","u","e","e","o","o","ka","ga","ki","gi","ku","gu","ke","ge","ko","go","sa","za","si","zi","su","zu","se","ze","so","zo","ta","da","ti","di","tu","tu","du","te","de","to","do","na","ni","nu","ne","no","ha","ba","pa","hi","bi","pi","hu","bu","pu","he","be","pe","ho","bo","po","ma","mi","mu","me","mo","ya","ya","yu","yu","yo","yo","ra","ri","ru","re","ro","wa","wa","wi","we","wo","n","vu","[?]","[?]","[?]","[?]","","","","",'"','"',"[?]","[?]","a","a","i","i","u","u","e","e","o","o","ka","ga","ki","gi","ku","gu","ke","ge","ko","go","sa","za","si","zi","su","zu","se","ze","so","zo","ta","da","ti","di","tu","tu","du","te","de","to","do","na","ni","nu","ne","no","ha","ba","pa","hi","bi","pi","hu","bu","pu","he","be","pe","ho","bo","po","ma","mi","mu","me","mo","ya","ya","yu","yu","yo","yo","ra","ri","ru","re","ro","wa","wa","wi","we","wo","n","vu","ka","ke","va","vi","ve","vo","","",'"','"']});var yO=w((Jve,bO)=>{bO.exports=["[?]","[?]","[?]","[?]","[?]","B","P","M","F","D","T","N","L","G","K","H","J","Q","X","ZH","CH","SH","R","Z","C","S","A","O","E","EH","AI","EI","AU","OU","AN","EN","ANG","ENG","ER","I","U","IU","V","NG","GN","[?]","[?]","[?]","[?]","g","gg","gs","n","nj","nh","d","dd","r","lg","lm","lb","ls","lt","lp","rh","m","b","bb","bs","s","ss","","j","jj","c","k","t","p","h","a","ae","ya","yae","eo","e","yeo","ye","o","wa","wae","oe","yo","u","weo","we","wi","yu","eu","yi","i","","nn","nd","ns","nZ","lgs","ld","lbs","lZ","lQ","mb","ms","mZ","mN","bg","","bsg","bst","bj","bt","bN","bbN","sg","sn","sd","sb","sj","Z","","N","Ns","NZ","pN","hh","Q","yo-ya","yo-yae","yo-i","yu-yeo","yu-ye","yu-i","U","U-i","[?]","","","","","","","","","","","","","","","","","BU","ZI","JI","GU","EE","ENN","OO","ONN","IR","ANN","INN","UNN","IM","NGG","AINN","AUNN","AM","OM","ONG","INNN","P","T","K","H","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var wO=w(($ve,vO)=>{vO.exports=["(g)","(n)","(d)","(r)","(m)","(b)","(s)","()","(j)","(c)","(k)","(t)","(p)","(h)","(ga)","(na)","(da)","(ra)","(ma)","(ba)","(sa)","(a)","(ja)","(ca)","(ka)","(ta)","(pa)","(ha)","(ju)","[?]","[?]","[?]","(1) ","(2) ","(3) ","(4) ","(5) ","(6) ","(7) ","(8) ","(9) ","(10) ","(Yue) ","(Huo) ","(Shui) ","(Mu) ","(Jin) ","(Tu) ","(Ri) ","(Zhu) ","(You) ","(She) ","(Ming) ","(Te) ","(Cai) ","(Zhu) ","(Lao) ","(Dai) ","(Hu) ","(Xue) ","(Jian) ","(Qi) ","(Zi) ","(Xie) ","(Ji) ","(Xiu) ","<<",">>","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","(g)","(n)","(d)","(r)","(m)","(b)","(s)","()","(j)","(c)","(k)","(t)","(p)","(h)","(ga)","(na)","(da)","(ra)","(ma)","(ba)","(sa)","(a)","(ja)","(ca)","(ka)","(ta)","(pa)","(ha)","[?]","[?]","[?]","KIS ","(1) ","(2) ","(3) ","(4) ","(5) ","(6) ","(7) ","(8) ","(9) ","(10) ","(Yue) ","(Huo) ","(Shui) ","(Mu) ","(Jin) ","(Tu) ","(Ri) ","(Zhu) ","(You) ","(She) ","(Ming) ","(Te) ","(Cai) ","(Zhu) ","(Lao) ","(Mi) ","(Nan) ","(Nu) ","(Shi) ","(You) ","(Yin) ","(Zhu) ","(Xiang) ","(Xiu) ","(Xie) ","(Zheng) ","(Shang) ","(Zhong) ","(Xia) ","(Zuo) ","(You) ","(Yi) ","(Zong) ","(Xue) ","(Jian) ","(Qi) ","(Zi) ","(Xie) ","(Ye) ","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","1M","2M","3M","4M","5M","6M","7M","8M","9M","10M","11M","12M","[?]","[?]","[?]","[?]","a","i","u","u","o","ka","ki","ku","ke","ko","sa","si","su","se","so","ta","ti","tu","te","to","na","ni","nu","ne","no","ha","hi","hu","he","ho","ma","mi","mu","me","mo","ya","yu","yo","ra","ri","ru","re","ro","wa","wi","we","wo"]});var CO=w((Uve,xO)=>{xO.exports=["apartment","alpha","ampere","are","inning","inch","won","escudo","acre","ounce","ohm","kai-ri","carat","calorie","gallon","gamma","giga","guinea","curie","guilder","kilo","kilogram","kilometer","kilowatt","gram","gram ton","cruzeiro","krone","case","koruna","co-op","cycle","centime","shilling","centi","cent","dozen","desi","dollar","ton","nano","knot","heights","percent","parts","barrel","piaster","picul","pico","building","farad","feet","bushel","franc","hectare","peso","pfennig","hertz","pence","page","beta","point","volt","hon","pound","hall","horn","micro","mile","mach","mark","mansion","micron","milli","millibar","mega","megaton","meter","yard","yard","yuan","liter","lira","rupee","ruble","rem","roentgen","watt","0h","1h","2h","3h","4h","5h","6h","7h","8h","9h","10h","11h","12h","13h","14h","15h","16h","17h","18h","19h","20h","21h","22h","23h","24h","HPA","da","AU","bar","oV","pc","[?]","[?]","[?]","[?]","Heisei","Syouwa","Taisyou","Meiji","Inc.","pA","nA","microamp","mA","kA","kB","MB","GB","cal","kcal","pF","nF","microFarad","microgram","mg","kg","Hz","kHz","MHz","GHz","THz","microliter","ml","dl","kl","fm","nm","micrometer","mm","cm","km","mm^2","cm^2","m^2","km^2","mm^4","cm^3","m^3","km^3","m/s","m/s^2","Pa","kPa","MPa","GPa","rad","rad/s","rad/s^2","ps","ns","microsecond","ms","pV","nV","microvolt","mV","kV","MV","pW","nW","microwatt","mW","kW","MW","kOhm","MOhm","a.m.","Bq","cc","cd","C/kg","Co.","dB","Gy","ha","HP","in","K.K.","KM","kt","lm","ln","log","lx","mb","mil","mol","pH","p.m.","PPM","PR","sr","Sv","Wb","[?]","[?]","1d","2d","3d","4d","5d","6d","7d","8d","9d","10d","11d","12d","13d","14d","15d","16d","17d","18d","19d","20d","21d","22d","23d","24d","25d","26d","27d","28d","29d","30d","31d"]});var DO=w((Xve,SO)=>{SO.exports=["[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?] ","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var kO=w((Gve,TO)=>{TO.exports=["Yi ","Ding ","Kao ","Qi ","Shang ","Xia ","[?] ","Mo ","Zhang ","San ","Shang ","Xia ","Ji ","Bu ","Yu ","Mian ","Gai ","Chou ","Chou ","Zhuan ","Qie ","Pi ","Shi ","Shi ","Qiu ","Bing ","Ye ","Cong ","Dong ","Si ","Cheng ","Diu ","Qiu ","Liang ","Diu ","You ","Liang ","Yan ","Bing ","Sang ","Gun ","Jiu ","Ge ","Ya ","Qiang ","Zhong ","Ji ","Jie ","Feng ","Guan ","Chuan ","Chan ","Lin ","Zhuo ","Zhu ","Ha ","Wan ","Dan ","Wei ","Zhu ","Jing ","Li ","Ju ","Pie ","Fu ","Yi ","Yi ","Nai ","Shime ","Jiu ","Jiu ","Zhe ","Yao ","Yi ","[?] ","Zhi ","Wu ","Zha ","Hu ","Fa ","Le ","Zhong ","Ping ","Pang ","Qiao ","Hu ","Guai ","Cheng ","Cheng ","Yi ","Yin ","[?] ","Mie ","Jiu ","Qi ","Ye ","Xi ","Xiang ","Gai ","Diu ","Hal ","[?] ","Shu ","Twul ","Shi ","Ji ","Nang ","Jia ","Kel ","Shi ","[?] ","Ol ","Mai ","Luan ","Cal ","Ru ","Xue ","Yan ","Fu ","Sha ","Na ","Gan ","Sol ","El ","Cwul ","[?] ","Gan ","Chi ","Gui ","Gan ","Luan ","Lin ","Yi ","Jue ","Liao ","Ma ","Yu ","Zheng ","Shi ","Shi ","Er ","Chu ","Yu ","Yu ","Yu ","Yun ","Hu ","Qi ","Wu ","Jing ","Si ","Sui ","Gen ","Gen ","Ya ","Xie ","Ya ","Qi ","Ya ","Ji ","Tou ","Wang ","Kang ","Ta ","Jiao ","Hai ","Yi ","Chan ","Heng ","Mu ","[?] ","Xiang ","Jing ","Ting ","Liang ","Xiang ","Jing ","Ye ","Qin ","Bo ","You ","Xie ","Dan ","Lian ","Duo ","Wei ","Ren ","Ren ","Ji ","La ","Wang ","Yi ","Shi ","Ren ","Le ","Ding ","Ze ","Jin ","Pu ","Chou ","Ba ","Zhang ","Jin ","Jie ","Bing ","Reng ","Cong ","Fo ","San ","Lun ","Sya ","Cang ","Zi ","Shi ","Ta ","Zhang ","Fu ","Xian ","Xian ","Tuo ","Hong ","Tong ","Ren ","Qian ","Gan ","Yi ","Di ","Dai ","Ling ","Yi ","Chao ","Chang ","Sa ","[?] ","Yi ","Mu ","Men ","Ren ","Jia ","Chao ","Yang ","Qian ","Zhong ","Pi ","Wan ","Wu ","Jian ","Jie ","Yao ","Feng ","Cang ","Ren ","Wang ","Fen ","Di ","Fang "]});var RO=w((zve,PO)=>{PO.exports=["Zhong ","Qi ","Pei ","Yu ","Diao ","Dun ","Wen ","Yi ","Xin ","Kang ","Yi ","Ji ","Ai ","Wu ","Ji ","Fu ","Fa ","Xiu ","Jin ","Bei ","Dan ","Fu ","Tang ","Zhong ","You ","Huo ","Hui ","Yu ","Cui ","Chuan ","San ","Wei ","Chuan ","Che ","Ya ","Xian ","Shang ","Chang ","Lun ","Cang ","Xun ","Xin ","Wei ","Zhu ","[?] ","Xuan ","Nu ","Bo ","Gu ","Ni ","Ni ","Xie ","Ban ","Xu ","Ling ","Zhou ","Shen ","Qu ","Si ","Beng ","Si ","Jia ","Pi ","Yi ","Si ","Ai ","Zheng ","Dian ","Han ","Mai ","Dan ","Zhu ","Bu ","Qu ","Bi ","Shao ","Ci ","Wei ","Di ","Zhu ","Zuo ","You ","Yang ","Ti ","Zhan ","He ","Bi ","Tuo ","She ","Yu ","Yi ","Fo ","Zuo ","Kou ","Ning ","Tong ","Ni ","Xuan ","Qu ","Yong ","Wa ","Qian ","[?] ","Ka ","[?] ","Pei ","Huai ","He ","Lao ","Xiang ","Ge ","Yang ","Bai ","Fa ","Ming ","Jia ","Er ","Bing ","Ji ","Hen ","Huo ","Gui ","Quan ","Tiao ","Jiao ","Ci ","Yi ","Shi ","Xing ","Shen ","Tuo ","Kan ","Zhi ","Gai ","Lai ","Yi ","Chi ","Kua ","Guang ","Li ","Yin ","Shi ","Mi ","Zhu ","Xu ","You ","An ","Lu ","Mou ","Er ","Lun ","Tong ","Cha ","Chi ","Xun ","Gong ","Zhou ","Yi ","Ru ","Jian ","Xia ","Jia ","Zai ","Lu ","Ko ","Jiao ","Zhen ","Ce ","Qiao ","Kuai ","Chai ","Ning ","Nong ","Jin ","Wu ","Hou ","Jiong ","Cheng ","Zhen ","Zuo ","Chou ","Qin ","Lu ","Ju ","Shu ","Ting ","Shen ","Tuo ","Bo ","Nan ","Hao ","Bian ","Tui ","Yu ","Xi ","Cu ","E ","Qiu ","Xu ","Kuang ","Ku ","Wu ","Jun ","Yi ","Fu ","Lang ","Zu ","Qiao ","Li ","Yong ","Hun ","Jing ","Xian ","San ","Pai ","Su ","Fu ","Xi ","Li ","Fu ","Ping ","Bao ","Yu ","Si ","Xia ","Xin ","Xiu ","Yu ","Ti ","Che ","Chou ","[?] ","Yan ","Lia ","Li ","Lai ","[?] ","Jian ","Xiu ","Fu ","He ","Ju ","Xiao ","Pai ","Jian ","Biao ","Chu ","Fei ","Feng ","Ya ","An ","Bei ","Yu ","Xin ","Bi ","Jian "]});var EO=w((Kve,_O)=>{_O.exports=["Chang ","Chi ","Bing ","Zan ","Yao ","Cui ","Lia ","Wan ","Lai ","Cang ","Zong ","Ge ","Guan ","Bei ","Tian ","Shu ","Shu ","Men ","Dao ","Tan ","Jue ","Chui ","Xing ","Peng ","Tang ","Hou ","Yi ","Qi ","Ti ","Gan ","Jing ","Jie ","Sui ","Chang ","Jie ","Fang ","Zhi ","Kong ","Juan ","Zong ","Ju ","Qian ","Ni ","Lun ","Zhuo ","Wei ","Luo ","Song ","Leng ","Hun ","Dong ","Zi ","Ben ","Wu ","Ju ","Nai ","Cai ","Jian ","Zhai ","Ye ","Zhi ","Sha ","Qing ","[?] ","Ying ","Cheng ","Jian ","Yan ","Nuan ","Zhong ","Chun ","Jia ","Jie ","Wei ","Yu ","Bing ","Ruo ","Ti ","Wei ","Pian ","Yan ","Feng ","Tang ","Wo ","E ","Xie ","Che ","Sheng ","Kan ","Di ","Zuo ","Cha ","Ting ","Bei ","Ye ","Huang ","Yao ","Zhan ","Chou ","Yan ","You ","Jian ","Xu ","Zha ","Ci ","Fu ","Bi ","Zhi ","Zong ","Mian ","Ji ","Yi ","Xie ","Xun ","Si ","Duan ","Ce ","Zhen ","Ou ","Tou ","Tou ","Bei ","Za ","Lu ","Jie ","Wei ","Fen ","Chang ","Gui ","Sou ","Zhi ","Su ","Xia ","Fu ","Yuan ","Rong ","Li ","Ru ","Yun ","Gou ","Ma ","Bang ","Dian ","Tang ","Hao ","Jie ","Xi ","Shan ","Qian ","Jue ","Cang ","Chu ","San ","Bei ","Xiao ","Yong ","Yao ","Tan ","Suo ","Yang ","Fa ","Bing ","Jia ","Dai ","Zai ","Tang ","[?] ","Bin ","Chu ","Nuo ","Can ","Lei ","Cui ","Yong ","Zao ","Zong ","Peng ","Song ","Ao ","Chuan ","Yu ","Zhai ","Cou ","Shang ","Qiang ","Jing ","Chi ","Sha ","Han ","Zhang ","Qing ","Yan ","Di ","Xi ","Lu ","Bei ","Piao ","Jin ","Lian ","Lu ","Man ","Qian ","Xian ","Tan ","Ying ","Dong ","Zhuan ","Xiang ","Shan ","Qiao ","Jiong ","Tui ","Zun ","Pu ","Xi ","Lao ","Chang ","Guang ","Liao ","Qi ","Deng ","Chan ","Wei ","Ji ","Fan ","Hui ","Chuan ","Jian ","Dan ","Jiao ","Jiu ","Seng ","Fen ","Xian ","Jue ","E ","Jiao ","Jian ","Tong ","Lin ","Bo ","Gu ","[?] ","Su ","Xian ","Jiang ","Min ","Ye ","Jin ","Jia ","Qiao ","Pi ","Feng ","Zhou ","Ai ","Sai "]});var LO=w((Qve,IO)=>{IO.exports=["Yi ","Jun ","Nong ","Chan ","Yi ","Dang ","Jing ","Xuan ","Kuai ","Jian ","Chu ","Dan ","Jiao ","Sha ","Zai ","[?] ","Bin ","An ","Ru ","Tai ","Chou ","Chai ","Lan ","Ni ","Jin ","Qian ","Meng ","Wu ","Ning ","Qiong ","Ni ","Chang ","Lie ","Lei ","Lu ","Kuang ","Bao ","Du ","Biao ","Zan ","Zhi ","Si ","You ","Hao ","Chen ","Chen ","Li ","Teng ","Wei ","Long ","Chu ","Chan ","Rang ","Shu ","Hui ","Li ","Luo ","Zan ","Nuo ","Tang ","Yan ","Lei ","Nang ","Er ","Wu ","Yun ","Zan ","Yuan ","Xiong ","Chong ","Zhao ","Xiong ","Xian ","Guang ","Dui ","Ke ","Dui ","Mian ","Tu ","Chang ","Er ","Dui ","Er ","Xin ","Tu ","Si ","Yan ","Yan ","Shi ","Shi ","Dang ","Qian ","Dou ","Fen ","Mao ","Shen ","Dou ","Bai ","Jing ","Li ","Huang ","Ru ","Wang ","Nei ","Quan ","Liang ","Yu ","Ba ","Gong ","Liu ","Xi ","[?] ","Lan ","Gong ","Tian ","Guan ","Xing ","Bing ","Qi ","Ju ","Dian ","Zi ","Ppwun ","Yang ","Jian ","Shou ","Ji ","Yi ","Ji ","Chan ","Jiong ","Mao ","Ran ","Nei ","Yuan ","Mao ","Gang ","Ran ","Ce ","Jiong ","Ce ","Zai ","Gua ","Jiong ","Mao ","Zhou ","Mou ","Gou ","Xu ","Mian ","Mi ","Rong ","Yin ","Xie ","Kan ","Jun ","Nong ","Yi ","Mi ","Shi ","Guan ","Meng ","Zhong ","Ju ","Yuan ","Ming ","Kou ","Lam ","Fu ","Xie ","Mi ","Bing ","Dong ","Tai ","Gang ","Feng ","Bing ","Hu ","Chong ","Jue ","Hu ","Kuang ","Ye ","Leng ","Pan ","Fu ","Min ","Dong ","Xian ","Lie ","Xia ","Jian ","Jing ","Shu ","Mei ","Tu ","Qi ","Gu ","Zhun ","Song ","Jing ","Liang ","Qing ","Diao ","Ling ","Dong ","Gan ","Jian ","Yin ","Cou ","Yi ","Li ","Cang ","Ming ","Zhuen ","Cui ","Si ","Duo ","Jin ","Lin ","Lin ","Ning ","Xi ","Du ","Ji ","Fan ","Fan ","Fan ","Feng ","Ju ","Chu ","Tako ","Feng ","Mok ","Ci ","Fu ","Feng ","Ping ","Feng ","Kai ","Huang ","Kai ","Gan ","Deng ","Ping ","Qu ","Xiong ","Kuai ","Tu ","Ao ","Chu ","Ji ","Dang ","Han ","Han ","Zao "]});var MO=w((Vve,FO)=>{FO.exports=["Dao ","Diao ","Dao ","Ren ","Ren ","Chuang ","Fen ","Qie ","Yi ","Ji ","Kan ","Qian ","Cun ","Chu ","Wen ","Ji ","Dan ","Xing ","Hua ","Wan ","Jue ","Li ","Yue ","Lie ","Liu ","Ze ","Gang ","Chuang ","Fu ","Chu ","Qu ","Ju ","Shan ","Min ","Ling ","Zhong ","Pan ","Bie ","Jie ","Jie ","Bao ","Li ","Shan ","Bie ","Chan ","Jing ","Gua ","Gen ","Dao ","Chuang ","Kui ","Ku ","Duo ","Er ","Zhi ","Shua ","Quan ","Cha ","Ci ","Ke ","Jie ","Gui ","Ci ","Gui ","Kai ","Duo ","Ji ","Ti ","Jing ","Lou ","Gen ","Ze ","Yuan ","Cuo ","Xue ","Ke ","La ","Qian ","Cha ","Chuang ","Gua ","Jian ","Cuo ","Li ","Ti ","Fei ","Pou ","Chan ","Qi ","Chuang ","Zi ","Gang ","Wan ","Bo ","Ji ","Duo ","Qing ","Yan ","Zhuo ","Jian ","Ji ","Bo ","Yan ","Ju ","Huo ","Sheng ","Jian ","Duo ","Duan ","Wu ","Gua ","Fu ","Sheng ","Jian ","Ge ","Zha ","Kai ","Chuang ","Juan ","Chan ","Tuan ","Lu ","Li ","Fou ","Shan ","Piao ","Kou ","Jiao ","Gua ","Qiao ","Jue ","Hua ","Zha ","Zhuo ","Lian ","Ju ","Pi ","Liu ","Gui ","Jiao ","Gui ","Jian ","Jian ","Tang ","Huo ","Ji ","Jian ","Yi ","Jian ","Zhi ","Chan ","Cuan ","Mo ","Li ","Zhu ","Li ","Ya ","Quan ","Ban ","Gong ","Jia ","Wu ","Mai ","Lie ","Jin ","Keng ","Xie ","Zhi ","Dong ","Zhu ","Nu ","Jie ","Qu ","Shao ","Yi ","Zhu ","Miao ","Li ","Jing ","Lao ","Lao ","Juan ","Kou ","Yang ","Wa ","Xiao ","Mou ","Kuang ","Jie ","Lie ","He ","Shi ","Ke ","Jing ","Hao ","Bo ","Min ","Chi ","Lang ","Yong ","Yong ","Mian ","Ke ","Xun ","Juan ","Qing ","Lu ","Pou ","Meng ","Lai ","Le ","Kai ","Mian ","Dong ","Xu ","Xu ","Kan ","Wu ","Yi ","Xun ","Weng ","Sheng ","Lao ","Mu ","Lu ","Piao ","Shi ","Ji ","Qin ","Qiang ","Jiao ","Quan ","Yang ","Yi ","Jue ","Fan ","Juan ","Tong ","Ju ","Dan ","Xie ","Mai ","Xun ","Xun ","Lu ","Li ","Che ","Rang ","Quan ","Bao ","Shao ","Yun ","Jiu ","Bao ","Gou ","Wu "]});var OO=w((ewe,jO)=>{jO.exports=["Yun ","Mwun ","Nay ","Gai ","Gai ","Bao ","Cong ","[?] ","Xiong ","Peng ","Ju ","Tao ","Ge ","Pu ","An ","Pao ","Fu ","Gong ","Da ","Jiu ","Qiong ","Bi ","Hua ","Bei ","Nao ","Chi ","Fang ","Jiu ","Yi ","Za ","Jiang ","Kang ","Jiang ","Kuang ","Hu ","Xia ","Qu ","Bian ","Gui ","Qie ","Zang ","Kuang ","Fei ","Hu ","Tou ","Gui ","Gui ","Hui ","Dan ","Gui ","Lian ","Lian ","Suan ","Du ","Jiu ","Qu ","Xi ","Pi ","Qu ","Yi ","Qia ","Yan ","Bian ","Ni ","Qu ","Shi ","Xin ","Qian ","Nian ","Sa ","Zu ","Sheng ","Wu ","Hui ","Ban ","Shi ","Xi ","Wan ","Hua ","Xie ","Wan ","Bei ","Zu ","Zhuo ","Xie ","Dan ","Mai ","Nan ","Dan ","Ji ","Bo ","Shuai ","Bu ","Kuang ","Bian ","Bu ","Zhan ","Qia ","Lu ","You ","Lu ","Xi ","Gua ","Wo ","Xie ","Jie ","Jie ","Wei ","Ang ","Qiong ","Zhi ","Mao ","Yin ","Wei ","Shao ","Ji ","Que ","Luan ","Shi ","Juan ","Xie ","Xu ","Jin ","Que ","Wu ","Ji ","E ","Qing ","Xi ","[?] ","Han ","Zhan ","E ","Ting ","Li ","Zhe ","Han ","Li ","Ya ","Ya ","Yan ","She ","Zhi ","Zha ","Pang ","[?] ","He ","Ya ","Zhi ","Ce ","Pang ","Ti ","Li ","She ","Hou ","Ting ","Zui ","Cuo ","Fei ","Yuan ","Ce ","Yuan ","Xiang ","Yan ","Li ","Jue ","Sha ","Dian ","Chu ","Jiu ","Qin ","Ao ","Gui ","Yan ","Si ","Li ","Chang ","Lan ","Li ","Yan ","Yan ","Yuan ","Si ","Gong ","Lin ","Qiu ","Qu ","Qu ","Uk ","Lei ","Du ","Xian ","Zhuan ","San ","Can ","Can ","Can ","Can ","Ai ","Dai ","You ","Cha ","Ji ","You ","Shuang ","Fan ","Shou ","Guai ","Ba ","Fa ","Ruo ","Shi ","Shu ","Zhuo ","Qu ","Shou ","Bian ","Xu ","Jia ","Pan ","Sou ","Gao ","Wei ","Sou ","Die ","Rui ","Cong ","Kou ","Gu ","Ju ","Ling ","Gua ","Tao ","Kou ","Zhi ","Jiao ","Zhao ","Ba ","Ding ","Ke ","Tai ","Chi ","Shi ","You ","Qiu ","Po ","Xie ","Hao ","Si ","Tan ","Chi ","Le ","Diao ","Ji ","[?] ","Hong "]});var NO=w((twe,AO)=>{AO.exports=["Mie ","Xu ","Mang ","Chi ","Ge ","Xuan ","Yao ","Zi ","He ","Ji ","Diao ","Cun ","Tong ","Ming ","Hou ","Li ","Tu ","Xiang ","Zha ","Xia ","Ye ","Lu ","A ","Ma ","Ou ","Xue ","Yi ","Jun ","Chou ","Lin ","Tun ","Yin ","Fei ","Bi ","Qin ","Qin ","Jie ","Bu ","Fou ","Ba ","Dun ","Fen ","E ","Han ","Ting ","Hang ","Shun ","Qi ","Hong ","Zhi ","Shen ","Wu ","Wu ","Chao ","Ne ","Xue ","Xi ","Chui ","Dou ","Wen ","Hou ","Ou ","Wu ","Gao ","Ya ","Jun ","Lu ","E ","Ge ","Mei ","Ai ","Qi ","Cheng ","Wu ","Gao ","Fu ","Jiao ","Hong ","Chi ","Sheng ","Ne ","Tun ","Fu ","Yi ","Dai ","Ou ","Li ","Bai ","Yuan ","Kuai ","[?] ","Qiang ","Wu ","E ","Shi ","Quan ","Pen ","Wen ","Ni ","M ","Ling ","Ran ","You ","Di ","Zhou ","Shi ","Zhou ","Tie ","Xi ","Yi ","Qi ","Ping ","Zi ","Gu ","Zi ","Wei ","Xu ","He ","Nao ","Xia ","Pei ","Yi ","Xiao ","Shen ","Hu ","Ming ","Da ","Qu ","Ju ","Gem ","Za ","Tuo ","Duo ","Pou ","Pao ","Bi ","Fu ","Yang ","He ","Zha ","He ","Hai ","Jiu ","Yong ","Fu ","Que ","Zhou ","Wa ","Ka ","Gu ","Ka ","Zuo ","Bu ","Long ","Dong ","Ning ","Tha ","Si ","Xian ","Huo ","Qi ","Er ","E ","Guang ","Zha ","Xi ","Yi ","Lie ","Zi ","Mie ","Mi ","Zhi ","Yao ","Ji ","Zhou ","Ge ","Shuai ","Zan ","Xiao ","Ke ","Hui ","Kua ","Huai ","Tao ","Xian ","E ","Xuan ","Xiu ","Wai ","Yan ","Lao ","Yi ","Ai ","Pin ","Shen ","Tong ","Hong ","Xiong ","Chi ","Wa ","Ha ","Zai ","Yu ","Di ","Pai ","Xiang ","Ai ","Hen ","Kuang ","Ya ","Da ","Xiao ","Bi ","Yue ","[?] ","Hua ","Sasou ","Kuai ","Duo ","[?] ","Ji ","Nong ","Mou ","Yo ","Hao ","Yuan ","Long ","Pou ","Mang ","Ge ","E ","Chi ","Shao ","Li ","Na ","Zu ","He ","Ku ","Xiao ","Xian ","Lao ","Bo ","Zhe ","Zha ","Liang ","Ba ","Mie ","Le ","Sui ","Fou ","Bu ","Han ","Heng ","Geng ","Shuo ","Ge "]});var BO=w((iwe,HO)=>{HO.exports=["You ","Yan ","Gu ","Gu ","Bai ","Han ","Suo ","Chun ","Yi ","Ai ","Jia ","Tu ","Xian ","Huan ","Li ","Xi ","Tang ","Zuo ","Qiu ","Che ","Wu ","Zao ","Ya ","Dou ","Qi ","Di ","Qin ","Ma ","Mal ","Hong ","Dou ","Kes ","Lao ","Liang ","Suo ","Zao ","Huan ","Lang ","Sha ","Ji ","Zuo ","Wo ","Feng ","Yin ","Hu ","Qi ","Shou ","Wei ","Shua ","Chang ","Er ","Li ","Qiang ","An ","Jie ","Yo ","Nian ","Yu ","Tian ","Lai ","Sha ","Xi ","Tuo ","Hu ","Ai ","Zhou ","Nou ","Ken ","Zhuo ","Zhuo ","Shang ","Di ","Heng ","Lan ","A ","Xiao ","Xiang ","Tun ","Wu ","Wen ","Cui ","Sha ","Hu ","Qi ","Qi ","Tao ","Dan ","Dan ","Ye ","Zi ","Bi ","Cui ","Chuo ","He ","Ya ","Qi ","Zhe ","Pei ","Liang ","Xian ","Pi ","Sha ","La ","Ze ","Qing ","Gua ","Pa ","Zhe ","Se ","Zhuan ","Nie ","Guo ","Luo ","Yan ","Di ","Quan ","Tan ","Bo ","Ding ","Lang ","Xiao ","[?] ","Tang ","Chi ","Ti ","An ","Jiu ","Dan ","Ke ","Yong ","Wei ","Nan ","Shan ","Yu ","Zhe ","La ","Jie ","Hou ","Han ","Die ","Zhou ","Chai ","Wai ","Re ","Yu ","Yin ","Zan ","Yao ","Wo ","Mian ","Hu ","Yun ","Chuan ","Hui ","Huan ","Huan ","Xi ","He ","Ji ","Kui ","Zhong ","Wei ","Sha ","Xu ","Huang ","Du ","Nie ","Xuan ","Liang ","Yu ","Sang ","Chi ","Qiao ","Yan ","Dan ","Pen ","Can ","Li ","Yo ","Zha ","Wei ","Miao ","Ying ","Pen ","Phos ","Kui ","Xi ","Yu ","Jie ","Lou ","Ku ","Sao ","Huo ","Ti ","Yao ","He ","A ","Xiu ","Qiang ","Se ","Yong ","Su ","Hong ","Xie ","Yi ","Suo ","Ma ","Cha ","Hai ","Ke ","Ta ","Sang ","Tian ","Ru ","Sou ","Wa ","Ji ","Pang ","Wu ","Xian ","Shi ","Ge ","Zi ","Jie ","Luo ","Weng ","Wa ","Si ","Chi ","Hao ","Suo ","Jia ","Hai ","Suo ","Qin ","Nie ","He ","Cis ","Sai ","Ng ","Ge ","Na ","Dia ","Ai ","[?] ","Tong ","Bi ","Ao ","Ao ","Lian ","Cui ","Zhe ","Mo ","Sou ","Sou ","Tan "]});var WO=w((nwe,qO)=>{qO.exports=["Di ","Qi ","Jiao ","Chong ","Jiao ","Kai ","Tan ","San ","Cao ","Jia ","Ai ","Xiao ","Piao ","Lou ","Ga ","Gu ","Xiao ","Hu ","Hui ","Guo ","Ou ","Xian ","Ze ","Chang ","Xu ","Po ","De ","Ma ","Ma ","Hu ","Lei ","Du ","Ga ","Tang ","Ye ","Beng ","Ying ","Saai ","Jiao ","Mi ","Xiao ","Hua ","Mai ","Ran ","Zuo ","Peng ","Lao ","Xiao ","Ji ","Zhu ","Chao ","Kui ","Zui ","Xiao ","Si ","Hao ","Fu ","Liao ","Qiao ","Xi ","Xiu ","Tan ","Tan ","Mo ","Xun ","E ","Zun ","Fan ","Chi ","Hui ","Zan ","Chuang ","Cu ","Dan ","Yu ","Tun ","Cheng ","Jiao ","Ye ","Xi ","Qi ","Hao ","Lian ","Xu ","Deng ","Hui ","Yin ","Pu ","Jue ","Qin ","Xun ","Nie ","Lu ","Si ","Yan ","Ying ","Da ","Dan ","Yu ","Zhou ","Jin ","Nong ","Yue ","Hui ","Qi ","E ","Zao ","Yi ","Shi ","Jiao ","Yuan ","Ai ","Yong ","Jue ","Kuai ","Yu ","Pen ","Dao ","Ge ","Xin ","Dun ","Dang ","Sin ","Sai ","Pi ","Pi ","Yin ","Zui ","Ning ","Di ","Lan ","Ta ","Huo ","Ru ","Hao ","Xia ","Ya ","Duo ","Xi ","Chou ","Ji ","Jin ","Hao ","Ti ","Chang ","[?] ","[?] ","Ca ","Ti ","Lu ","Hui ","Bo ","You ","Nie ","Yin ","Hu ","Mo ","Huang ","Zhe ","Li ","Liu ","Haai ","Nang ","Xiao ","Mo ","Yan ","Li ","Lu ","Long ","Fu ","Dan ","Chen ","Pin ","Pi ","Xiang ","Huo ","Mo ","Xi ","Duo ","Ku ","Yan ","Chan ","Ying ","Rang ","Dian ","La ","Ta ","Xiao ","Jiao ","Chuo ","Huan ","Huo ","Zhuan ","Nie ","Xiao ","Ca ","Li ","Chan ","Chai ","Li ","Yi ","Luo ","Nang ","Zan ","Su ","Xi ","So ","Jian ","Za ","Zhu ","Lan ","Nie ","Nang ","[?] ","[?] ","Wei ","Hui ","Yin ","Qiu ","Si ","Nin ","Jian ","Hui ","Xin ","Yin ","Nan ","Tuan ","Tuan ","Dun ","Kang ","Yuan ","Jiong ","Pian ","Yun ","Cong ","Hu ","Hui ","Yuan ","You ","Guo ","Kun ","Cong ","Wei ","Tu ","Wei ","Lun ","Guo ","Qun ","Ri ","Ling ","Gu ","Guo ","Tai ","Guo ","Tu ","You "]});var ZO=w((rwe,YO)=>{YO.exports=["Guo ","Yin ","Hun ","Pu ","Yu ","Han ","Yuan ","Lun ","Quan ","Yu ","Qing ","Guo ","Chuan ","Wei ","Yuan ","Quan ","Ku ","Fu ","Yuan ","Yuan ","E ","Tu ","Tu ","Tu ","Tuan ","Lue ","Hui ","Yi ","Yuan ","Luan ","Luan ","Tu ","Ya ","Tu ","Ting ","Sheng ","Pu ","Lu ","Iri ","Ya ","Zai ","Wei ","Ge ","Yu ","Wu ","Gui ","Pi ","Yi ","Di ","Qian ","Qian ","Zhen ","Zhuo ","Dang ","Qia ","Akutsu ","Yama ","Kuang ","Chang ","Qi ","Nie ","Mo ","Ji ","Jia ","Zhi ","Zhi ","Ban ","Xun ","Tou ","Qin ","Fen ","Jun ","Keng ","Tun ","Fang ","Fen ","Ben ","Tan ","Kan ","Pi ","Zuo ","Keng ","Bi ","Xing ","Di ","Jing ","Ji ","Kuai ","Di ","Jing ","Jian ","Tan ","Li ","Ba ","Wu ","Fen ","Zhui ","Po ","Pan ","Tang ","Kun ","Qu ","Tan ","Zhi ","Tuo ","Gan ","Ping ","Dian ","Gua ","Ni ","Tai ","Pi ","Jiong ","Yang ","Fo ","Ao ","Liu ","Qiu ","Mu ","Ke ","Gou ","Xue ","Ba ","Chi ","Che ","Ling ","Zhu ","Fu ","Hu ","Zhi ","Chui ","La ","Long ","Long ","Lu ","Ao ","Tay ","Pao ","[?] ","Xing ","Dong ","Ji ","Ke ","Lu ","Ci ","Chi ","Lei ","Gai ","Yin ","Hou ","Dui ","Zhao ","Fu ","Guang ","Yao ","Duo ","Duo ","Gui ","Cha ","Yang ","Yin ","Fa ","Gou ","Yuan ","Die ","Xie ","Ken ","Jiong ","Shou ","E ","Ha ","Dian ","Hong ","Wu ","Kua ","[?] ","Tao ","Dang ","Kai ","Gake ","Nao ","An ","Xing ","Xian ","Huan ","Bang ","Pei ","Ba ","Yi ","Yin ","Han ","Xu ","Chui ","Cen ","Geng ","Ai ","Peng ","Fang ","Que ","Yong ","Xun ","Jia ","Di ","Mai ","Lang ","Xuan ","Cheng ","Yan ","Jin ","Zhe ","Lei ","Lie ","Bu ","Cheng ","Gomi ","Bu ","Shi ","Xun ","Guo ","Jiong ","Ye ","Nian ","Di ","Yu ","Bu ","Ya ","Juan ","Sui ","Pi ","Cheng ","Wan ","Ju ","Lun ","Zheng ","Kong ","Chong ","Dong ","Dai ","Tan ","An ","Cai ","Shu ","Beng ","Kan ","Zhi ","Duo ","Yi ","Zhi ","Yi ","Pei ","Ji ","Zhun ","Qi ","Sao ","Ju ","Ni "]});var $O=w((owe,JO)=>{JO.exports=["Ku ","Ke ","Tang ","Kun ","Ni ","Jian ","Dui ","Jin ","Gang ","Yu ","E ","Peng ","Gu ","Tu ","Leng ","[?] ","Ya ","Qian ","[?] ","An ","[?] ","Duo ","Nao ","Tu ","Cheng ","Yin ","Hun ","Bi ","Lian ","Guo ","Die ","Zhuan ","Hou ","Bao ","Bao ","Yu ","Di ","Mao ","Jie ","Ruan ","E ","Geng ","Kan ","Zong ","Yu ","Huang ","E ","Yao ","Yan ","Bao ","Ji ","Mei ","Chang ","Du ","Tuo ","Yin ","Feng ","Zhong ","Jie ","Zhen ","Feng ","Gang ","Chuan ","Jian ","Pyeng ","Toride ","Xiang ","Huang ","Leng ","Duan ","[?] ","Xuan ","Ji ","Ji ","Kuai ","Ying ","Ta ","Cheng ","Yong ","Kai ","Su ","Su ","Shi ","Mi ","Ta ","Weng ","Cheng ","Tu ","Tang ","Que ","Zhong ","Li ","Peng ","Bang ","Sai ","Zang ","Dui ","Tian ","Wu ","Cheng ","Xun ","Ge ","Zhen ","Ai ","Gong ","Yan ","Kan ","Tian ","Yuan ","Wen ","Xie ","Liu ","Ama ","Lang ","Chang ","Peng ","Beng ","Chen ","Cu ","Lu ","Ou ","Qian ","Mei ","Mo ","Zhuan ","Shuang ","Shu ","Lou ","Chi ","Man ","Biao ","Jing ","Qi ","Shu ","Di ","Zhang ","Kan ","Yong ","Dian ","Chen ","Zhi ","Xi ","Guo ","Qiang ","Jin ","Di ","Shang ","Mu ","Cui ","Yan ","Ta ","Zeng ","Qi ","Qiang ","Liang ","[?] ","Zhui ","Qiao ","Zeng ","Xu ","Shan ","Shan ","Ba ","Pu ","Kuai ","Dong ","Fan ","Que ","Mo ","Dun ","Dun ","Dun ","Di ","Sheng ","Duo ","Duo ","Tan ","Deng ","Wu ","Fen ","Huang ","Tan ","Da ","Ye ","Sho ","Mama ","Yu ","Qiang ","Ji ","Qiao ","Ken ","Yi ","Pi ","Bi ","Dian ","Jiang ","Ye ","Yong ","Bo ","Tan ","Lan ","Ju ","Huai ","Dang ","Rang ","Qian ","Xun ","Lan ","Xi ","He ","Ai ","Ya ","Dao ","Hao ","Ruan ","Mama ","Lei ","Kuang ","Lu ","Yan ","Tan ","Wei ","Huai ","Long ","Long ","Rui ","Li ","Lin ","Rang ","Ten ","Xun ","Yan ","Lei ","Ba ","[?] ","Shi ","Ren ","[?] ","Zhuang ","Zhuang ","Sheng ","Yi ","Mai ","Ke ","Zhu ","Zhuang ","Hu ","Hu ","Kun ","Yi ","Hu ","Xu ","Kun ","Shou ","Mang ","Zun "]});var XO=w((swe,UO)=>{UO.exports=["Shou ","Yi ","Zhi ","Gu ","Chu ","Jiang ","Feng ","Bei ","Cay ","Bian ","Sui ","Qun ","Ling ","Fu ","Zuo ","Xia ","Xiong ","[?] ","Nao ","Xia ","Kui ","Xi ","Wai ","Yuan ","Mao ","Su ","Duo ","Duo ","Ye ","Qing ","Uys ","Gou ","Gou ","Qi ","Meng ","Meng ","Yin ","Huo ","Chen ","Da ","Ze ","Tian ","Tai ","Fu ","Guai ","Yao ","Yang ","Hang ","Gao ","Shi ","Ben ","Tai ","Tou ","Yan ","Bi ","Yi ","Kua ","Jia ","Duo ","Kwu ","Kuang ","Yun ","Jia ","Pa ","En ","Lian ","Huan ","Di ","Yan ","Pao ","Quan ","Qi ","Nai ","Feng ","Xie ","Fen ","Dian ","[?] ","Kui ","Zou ","Huan ","Qi ","Kai ","Zha ","Ben ","Yi ","Jiang ","Tao ","Zang ","Ben ","Xi ","Xiang ","Fei ","Diao ","Xun ","Keng ","Dian ","Ao ","She ","Weng ","Pan ","Ao ","Wu ","Ao ","Jiang ","Lian ","Duo ","Yun ","Jiang ","Shi ","Fen ","Huo ","Bi ","Lian ","Duo ","Nu ","Nu ","Ding ","Nai ","Qian ","Jian ","Ta ","Jiu ","Nan ","Cha ","Hao ","Xian ","Fan ","Ji ","Shuo ","Ru ","Fei ","Wang ","Hong ","Zhuang ","Fu ","Ma ","Dan ","Ren ","Fu ","Jing ","Yan ","Xie ","Wen ","Zhong ","Pa ","Du ","Ji ","Keng ","Zhong ","Yao ","Jin ","Yun ","Miao ","Pei ","Shi ","Yue ","Zhuang ","Niu ","Yan ","Na ","Xin ","Fen ","Bi ","Yu ","Tuo ","Feng ","Yuan ","Fang ","Wu ","Yu ","Gui ","Du ","Ba ","Ni ","Zhou ","Zhuo ","Zhao ","Da ","Nai ","Yuan ","Tou ","Xuan ","Zhi ","E ","Mei ","Mo ","Qi ","Bi ","Shen ","Qie ","E ","He ","Xu ","Fa ","Zheng ","Min ","Ban ","Mu ","Fu ","Ling ","Zi ","Zi ","Shi ","Ran ","Shan ","Yang ","Man ","Jie ","Gu ","Si ","Xing ","Wei ","Zi ","Ju ","Shan ","Pin ","Ren ","Yao ","Tong ","Jiang ","Shu ","Ji ","Gai ","Shang ","Kuo ","Juan ","Jiao ","Gou ","Mu ","Jian ","Jian ","Yi ","Nian ","Zhi ","Ji ","Ji ","Xian ","Heng ","Guang ","Jun ","Kua ","Yan ","Ming ","Lie ","Pei ","Yan ","You ","Yan ","Cha ","Shen ","Yin ","Chi ","Gui ","Quan ","Zi "]});var zO=w((awe,GO)=>{GO.exports=["Song ","Wei ","Hong ","Wa ","Lou ","Ya ","Rao ","Jiao ","Luan ","Ping ","Xian ","Shao ","Li ","Cheng ","Xiao ","Mang ","Fu ","Suo ","Wu ","Wei ","Ke ","Lai ","Chuo ","Ding ","Niang ","Xing ","Nan ","Yu ","Nuo ","Pei ","Nei ","Juan ","Shen ","Zhi ","Han ","Di ","Zhuang ","E ","Pin ","Tui ","Han ","Mian ","Wu ","Yan ","Wu ","Xi ","Yan ","Yu ","Si ","Yu ","Wa ","[?] ","Xian ","Ju ","Qu ","Shui ","Qi ","Xian ","Zhui ","Dong ","Chang ","Lu ","Ai ","E ","E ","Lou ","Mian ","Cong ","Pou ","Ju ","Po ","Cai ","Ding ","Wan ","Biao ","Xiao ","Shu ","Qi ","Hui ","Fu ","E ","Wo ","Tan ","Fei ","Wei ","Jie ","Tian ","Ni ","Quan ","Jing ","Hun ","Jing ","Qian ","Dian ","Xing ","Hu ","Wa ","Lai ","Bi ","Yin ","Chou ","Chuo ","Fu ","Jing ","Lun ","Yan ","Lan ","Kun ","Yin ","Ya ","Ju ","Li ","Dian ","Xian ","Hwa ","Hua ","Ying ","Chan ","Shen ","Ting ","Dang ","Yao ","Wu ","Nan ","Ruo ","Jia ","Tou ","Xu ","Yu ","Wei ","Ti ","Rou ","Mei ","Dan ","Ruan ","Qin ","Hui ","Wu ","Qian ","Chun ","Mao ","Fu ","Jie ","Duan ","Xi ","Zhong ","Mei ","Huang ","Mian ","An ","Ying ","Xuan ","Jie ","Wei ","Mei ","Yuan ","Zhen ","Qiu ","Ti ","Xie ","Tuo ","Lian ","Mao ","Ran ","Si ","Pian ","Wei ","Wa ","Jiu ","Hu ","Ao ","[?] ","Bou ","Xu ","Tou ","Gui ","Zou ","Yao ","Pi ","Xi ","Yuan ","Ying ","Rong ","Ru ","Chi ","Liu ","Mei ","Pan ","Ao ","Ma ","Gou ","Kui ","Qin ","Jia ","Sao ","Zhen ","Yuan ","Cha ","Yong ","Ming ","Ying ","Ji ","Su ","Niao ","Xian ","Tao ","Pang ","Lang ","Nao ","Bao ","Ai ","Pi ","Pin ","Yi ","Piao ","Yu ","Lei ","Xuan ","Man ","Yi ","Zhang ","Kang ","Yong ","Ni ","Li ","Di ","Gui ","Yan ","Jin ","Zhuan ","Chang ","Ce ","Han ","Nen ","Lao ","Mo ","Zhe ","Hu ","Hu ","Ao ","Nen ","Qiang ","Ma ","Pie ","Gu ","Wu ","Jiao ","Tuo ","Zhan ","Mao ","Xian ","Xian ","Mo ","Liao ","Lian ","Hua "]});var QO=w((lwe,KO)=>{KO.exports=["Gui ","Deng ","Zhi ","Xu ","Yi ","Hua ","Xi ","Hui ","Rao ","Xi ","Yan ","Chan ","Jiao ","Mei ","Fan ","Fan ","Xian ","Yi ","Wei ","Jiao ","Fu ","Shi ","Bi ","Shan ","Sui ","Qiang ","Lian ","Huan ","Xin ","Niao ","Dong ","Yi ","Can ","Ai ","Niang ","Neng ","Ma ","Tiao ","Chou ","Jin ","Ci ","Yu ","Pin ","Yong ","Xu ","Nai ","Yan ","Tai ","Ying ","Can ","Niao ","Wo ","Ying ","Mian ","Kaka ","Ma ","Shen ","Xing ","Ni ","Du ","Liu ","Yuan ","Lan ","Yan ","Shuang ","Ling ","Jiao ","Niang ","Lan ","Xian ","Ying ","Shuang ","Shuai ","Quan ","Mi ","Li ","Luan ","Yan ","Zhu ","Lan ","Zi ","Jie ","Jue ","Jue ","Kong ","Yun ","Zi ","Zi ","Cun ","Sun ","Fu ","Bei ","Zi ","Xiao ","Xin ","Meng ","Si ","Tai ","Bao ","Ji ","Gu ","Nu ","Xue ","[?] ","Zhuan ","Hai ","Luan ","Sun ","Huai ","Mie ","Cong ","Qian ","Shu ","Chan ","Ya ","Zi ","Ni ","Fu ","Zi ","Li ","Xue ","Bo ","Ru ","Lai ","Nie ","Nie ","Ying ","Luan ","Mian ","Zhu ","Rong ","Ta ","Gui ","Zhai ","Qiong ","Yu ","Shou ","An ","Tu ","Song ","Wan ","Rou ","Yao ","Hong ","Yi ","Jing ","Zhun ","Mi ","Zhu ","Dang ","Hong ","Zong ","Guan ","Zhou ","Ding ","Wan ","Yi ","Bao ","Shi ","Shi ","Chong ","Shen ","Ke ","Xuan ","Shi ","You ","Huan ","Yi ","Tiao ","Shi ","Xian ","Gong ","Cheng ","Qun ","Gong ","Xiao ","Zai ","Zha ","Bao ","Hai ","Yan ","Xiao ","Jia ","Shen ","Chen ","Rong ","Huang ","Mi ","Kou ","Kuan ","Bin ","Su ","Cai ","Zan ","Ji ","Yuan ","Ji ","Yin ","Mi ","Kou ","Qing ","Que ","Zhen ","Jian ","Fu ","Ning ","Bing ","Huan ","Mei ","Qin ","Han ","Yu ","Shi ","Ning ","Qin ","Ning ","Zhi ","Yu ","Bao ","Kuan ","Ning ","Qin ","Mo ","Cha ","Ju ","Gua ","Qin ","Hu ","Wu ","Liao ","Shi ","Zhu ","Zhai ","Shen ","Wei ","Xie ","Kuan ","Hui ","Liao ","Jun ","Huan ","Yi ","Yi ","Bao ","Qin ","Chong ","Bao ","Feng ","Cun ","Dui ","Si ","Xun ","Dao ","Lu ","Dui ","Shou "]});var e1=w((uwe,VO)=>{VO.exports=["Po ","Feng ","Zhuan ","Fu ","She ","Ke ","Jiang ","Jiang ","Zhuan ","Wei ","Zun ","Xun ","Shu ","Dui ","Dao ","Xiao ","Ji ","Shao ","Er ","Er ","Er ","Ga ","Jian ","Shu ","Chen ","Shang ","Shang ","Mo ","Ga ","Chang ","Liao ","Xian ","Xian ","[?] ","Wang ","Wang ","You ","Liao ","Liao ","Yao ","Mang ","Wang ","Wang ","Wang ","Ga ","Yao ","Duo ","Kui ","Zhong ","Jiu ","Gan ","Gu ","Gan ","Tui ","Gan ","Gan ","Shi ","Yin ","Chi ","Kao ","Ni ","Jin ","Wei ","Niao ","Ju ","Pi ","Ceng ","Xi ","Bi ","Ju ","Jie ","Tian ","Qu ","Ti ","Jie ","Wu ","Diao ","Shi ","Shi ","Ping ","Ji ","Xie ","Chen ","Xi ","Ni ","Zhan ","Xi ","[?] ","Man ","E ","Lou ","Ping ","Ti ","Fei ","Shu ","Xie ","Tu ","Lu ","Lu ","Xi ","Ceng ","Lu ","Ju ","Xie ","Ju ","Jue ","Liao ","Jue ","Shu ","Xi ","Che ","Tun ","Ni ","Shan ","[?] ","Xian ","Li ","Xue ","Nata ","[?] ","Long ","Yi ","Qi ","Ren ","Wu ","Han ","Shen ","Yu ","Chu ","Sui ","Qi ","[?] ","Yue ","Ban ","Yao ","Ang ","Ya ","Wu ","Jie ","E ","Ji ","Qian ","Fen ","Yuan ","Qi ","Cen ","Qian ","Qi ","Cha ","Jie ","Qu ","Gang ","Xian ","Ao ","Lan ","Dao ","Ba ","Zuo ","Zuo ","Yang ","Ju ","Gang ","Ke ","Gou ","Xue ","Bei ","Li ","Tiao ","Ju ","Yan ","Fu ","Xiu ","Jia ","Ling ","Tuo ","Pei ","You ","Dai ","Kuang ","Yue ","Qu ","Hu ","Po ","Min ","An ","Tiao ","Ling ","Chi ","Yuri ","Dong ","Cem ","Kui ","Xiu ","Mao ","Tong ","Xue ","Yi ","Kura ","He ","Ke ","Luo ","E ","Fu ","Xun ","Die ","Lu ","An ","Er ","Gai ","Quan ","Tong ","Yi ","Mu ","Shi ","An ","Wei ","Hu ","Zhi ","Mi ","Li ","Ji ","Tong ","Wei ","You ","Sang ","Xia ","Li ","Yao ","Jiao ","Zheng ","Luan ","Jiao ","E ","E ","Yu ","Ye ","Bu ","Qiao ","Qun ","Feng ","Feng ","Nao ","Li ","You ","Xian ","Hong ","Dao ","Shen ","Cheng ","Tu ","Geng ","Jun ","Hao ","Xia ","Yin ","Yu "]});var i1=w((cwe,t1)=>{t1.exports=["Lang ","Kan ","Lao ","Lai ","Xian ","Que ","Kong ","Chong ","Chong ","Ta ","Lin ","Hua ","Ju ","Lai ","Qi ","Min ","Kun ","Kun ","Zu ","Gu ","Cui ","Ya ","Ya ","Gang ","Lun ","Lun ","Leng ","Jue ","Duo ","Zheng ","Guo ","Yin ","Dong ","Han ","Zheng ","Wei ","Yao ","Pi ","Yan ","Song ","Jie ","Beng ","Zu ","Jue ","Dong ","Zhan ","Gu ","Yin ","[?] ","Ze ","Huang ","Yu ","Wei ","Yang ","Feng ","Qiu ","Dun ","Ti ","Yi ","Zhi ","Shi ","Zai ","Yao ","E ","Zhu ","Kan ","Lu ","Yan ","Mei ","Gan ","Ji ","Ji ","Huan ","Ting ","Sheng ","Mei ","Qian ","Wu ","Yu ","Zong ","Lan ","Jue ","Yan ","Yan ","Wei ","Zong ","Cha ","Sui ","Rong ","Yamashina ","Qin ","Yu ","Kewashii ","Lou ","Tu ","Dui ","Xi ","Weng ","Cang ","Dang ","Hong ","Jie ","Ai ","Liu ","Wu ","Song ","Qiao ","Zi ","Wei ","Beng ","Dian ","Cuo ","Qian ","Yong ","Nie ","Cuo ","Ji ","[?] ","Tao ","Song ","Zong ","Jiang ","Liao ","Kang ","Chan ","Die ","Cen ","Ding ","Tu ","Lou ","Zhang ","Zhan ","Zhan ","Ao ","Cao ","Qu ","Qiang ","Zui ","Zui ","Dao ","Dao ","Xi ","Yu ","Bo ","Long ","Xiang ","Ceng ","Bo ","Qin ","Jiao ","Yan ","Lao ","Zhan ","Lin ","Liao ","Liao ","Jin ","Deng ","Duo ","Zun ","Jiao ","Gui ","Yao ","Qiao ","Yao ","Jue ","Zhan ","Yi ","Xue ","Nao ","Ye ","Ye ","Yi ","E ","Xian ","Ji ","Xie ","Ke ","Xi ","Di ","Ao ","Zui ","[?] ","Ni ","Rong ","Dao ","Ling ","Za ","Yu ","Yue ","Yin ","[?] ","Jie ","Li ","Sui ","Long ","Long ","Dian ","Ying ","Xi ","Ju ","Chan ","Ying ","Kui ","Yan ","Wei ","Nao ","Quan ","Chao ","Cuan ","Luan ","Dian ","Dian ","[?] ","Yan ","Yan ","Yan ","Nao ","Yan ","Chuan ","Gui ","Chuan ","Zhou ","Huang ","Jing ","Xun ","Chao ","Chao ","Lie ","Gong ","Zuo ","Qiao ","Ju ","Gong ","Kek ","Wu ","Pwu ","Pwu ","Chai ","Qiu ","Qiu ","Ji ","Yi ","Si ","Ba ","Zhi ","Zhao ","Xiang ","Yi ","Jin ","Xun ","Juan ","Phas ","Xun ","Jin ","Fu "]});var r1=w((dwe,n1)=>{n1.exports=["Za ","Bi ","Shi ","Bu ","Ding ","Shuai ","Fan ","Nie ","Shi ","Fen ","Pa ","Zhi ","Xi ","Hu ","Dan ","Wei ","Zhang ","Tang ","Dai ","Ma ","Pei ","Pa ","Tie ","Fu ","Lian ","Zhi ","Zhou ","Bo ","Zhi ","Di ","Mo ","Yi ","Yi ","Ping ","Qia ","Juan ","Ru ","Shuai ","Dai ","Zheng ","Shui ","Qiao ","Zhen ","Shi ","Qun ","Xi ","Bang ","Dai ","Gui ","Chou ","Ping ","Zhang ","Sha ","Wan ","Dai ","Wei ","Chang ","Sha ","Qi ","Ze ","Guo ","Mao ","Du ","Hou ","Zheng ","Xu ","Mi ","Wei ","Wo ","Fu ","Yi ","Bang ","Ping ","Tazuna ","Gong ","Pan ","Huang ","Dao ","Mi ","Jia ","Teng ","Hui ","Zhong ","Shan ","Man ","Mu ","Biao ","Guo ","Ze ","Mu ","Bang ","Zhang ","Jiong ","Chan ","Fu ","Zhi ","Hu ","Fan ","Chuang ","Bi ","Hei ","[?] ","Mi ","Qiao ","Chan ","Fen ","Meng ","Bang ","Chou ","Mie ","Chu ","Jie ","Xian ","Lan ","Gan ","Ping ","Nian ","Qian ","Bing ","Bing ","Xing ","Gan ","Yao ","Huan ","You ","You ","Ji ","Yan ","Pi ","Ting ","Ze ","Guang ","Zhuang ","Mo ","Qing ","Bi ","Qin ","Dun ","Chuang ","Gui ","Ya ","Bai ","Jie ","Xu ","Lu ","Wu ","[?] ","Ku ","Ying ","Di ","Pao ","Dian ","Ya ","Miao ","Geng ","Ci ","Fu ","Tong ","Pang ","Fei ","Xiang ","Yi ","Zhi ","Tiao ","Zhi ","Xiu ","Du ","Zuo ","Xiao ","Tu ","Gui ","Ku ","Pang ","Ting ","You ","Bu ","Ding ","Cheng ","Lai ","Bei ","Ji ","An ","Shu ","Kang ","Yong ","Tuo ","Song ","Shu ","Qing ","Yu ","Yu ","Miao ","Sou ","Ce ","Xiang ","Fei ","Jiu ","He ","Hui ","Liu ","Sha ","Lian ","Lang ","Sou ","Jian ","Pou ","Qing ","Jiu ","Jiu ","Qin ","Ao ","Kuo ","Lou ","Yin ","Liao ","Dai ","Lu ","Yi ","Chu ","Chan ","Tu ","Si ","Xin ","Miao ","Chang ","Wu ","Fei ","Guang ","Koc ","Kuai ","Bi ","Qiang ","Xie ","Lin ","Lin ","Liao ","Lu ","[?] ","Ying ","Xian ","Ting ","Yong ","Li ","Ting ","Yin ","Xun ","Yan ","Ting ","Di ","Po ","Jian ","Hui ","Nai ","Hui ","Gong ","Nian "]});var s1=w((hwe,o1)=>{o1.exports=["Kai ","Bian ","Yi ","Qi ","Nong ","Fen ","Ju ","Yan ","Yi ","Zang ","Bi ","Yi ","Yi ","Er ","San ","Shi ","Er ","Shi ","Shi ","Gong ","Diao ","Yin ","Hu ","Fu ","Hong ","Wu ","Tui ","Chi ","Jiang ","Ba ","Shen ","Di ","Zhang ","Jue ","Tao ","Fu ","Di ","Mi ","Xian ","Hu ","Chao ","Nu ","Jing ","Zhen ","Yi ","Mi ","Quan ","Wan ","Shao ","Ruo ","Xuan ","Jing ","Dun ","Zhang ","Jiang ","Qiang ","Peng ","Dan ","Qiang ","Bi ","Bi ","She ","Dan ","Jian ","Gou ","Sei ","Fa ","Bi ","Kou ","Nagi ","Bie ","Xiao ","Dan ","Kuo ","Qiang ","Hong ","Mi ","Kuo ","Wan ","Jue ","Ji ","Ji ","Gui ","Dang ","Lu ","Lu ","Tuan ","Hui ","Zhi ","Hui ","Hui ","Yi ","Yi ","Yi ","Yi ","Huo ","Huo ","Shan ","Xing ","Wen ","Tong ","Yan ","Yan ","Yu ","Chi ","Cai ","Biao ","Diao ","Bin ","Peng ","Yong ","Piao ","Zhang ","Ying ","Chi ","Chi ","Zhuo ","Tuo ","Ji ","Pang ","Zhong ","Yi ","Wang ","Che ","Bi ","Chi ","Ling ","Fu ","Wang ","Zheng ","Cu ","Wang ","Jing ","Dai ","Xi ","Xun ","Hen ","Yang ","Huai ","Lu ","Hou ","Wa ","Cheng ","Zhi ","Xu ","Jing ","Tu ","Cong ","[?] ","Lai ","Cong ","De ","Pai ","Xi ","[?] ","Qi ","Chang ","Zhi ","Cong ","Zhou ","Lai ","Yu ","Xie ","Jie ","Jian ","Chi ","Jia ","Bian ","Huang ","Fu ","Xun ","Wei ","Pang ","Yao ","Wei ","Xi ","Zheng ","Piao ","Chi ","De ","Zheng ","Zheng ","Bie ","De ","Chong ","Che ","Jiao ","Wei ","Jiao ","Hui ","Mei ","Long ","Xiang ","Bao ","Qu ","Xin ","Shu ","Bi ","Yi ","Le ","Ren ","Dao ","Ding ","Gai ","Ji ","Ren ","Ren ","Chan ","Tan ","Te ","Te ","Gan ","Qi ","Shi ","Cun ","Zhi ","Wang ","Mang ","Xi ","Fan ","Ying ","Tian ","Min ","Min ","Zhong ","Chong ","Wu ","Ji ","Wu ","Xi ","Ye ","You ","Wan ","Cong ","Zhong ","Kuai ","Yu ","Bian ","Zhi ","Qi ","Cui ","Chen ","Tai ","Tun ","Qian ","Nian ","Hun ","Xiong ","Niu ","Wang ","Xian ","Xin ","Kang ","Hu ","Kai ","Fen "]});var l1=w((gwe,a1)=>{a1.exports=["Huai ","Tai ","Song ","Wu ","Ou ","Chang ","Chuang ","Ju ","Yi ","Bao ","Chao ","Min ","Pei ","Zuo ","Zen ","Yang ","Kou ","Ban ","Nu ","Nao ","Zheng ","Pa ","Bu ","Tie ","Gu ","Hu ","Ju ","Da ","Lian ","Si ","Chou ","Di ","Dai ","Yi ","Tu ","You ","Fu ","Ji ","Peng ","Xing ","Yuan ","Ni ","Guai ","Fu ","Xi ","Bi ","You ","Qie ","Xuan ","Cong ","Bing ","Huang ","Xu ","Chu ","Pi ","Xi ","Xi ","Tan ","Koraeru ","Zong ","Dui ","[?] ","Ki ","Yi ","Chi ","Ren ","Xun ","Shi ","Xi ","Lao ","Heng ","Kuang ","Mu ","Zhi ","Xie ","Lian ","Tiao ","Huang ","Die ","Hao ","Kong ","Gui ","Heng ","Xi ","Xiao ","Shu ","S ","Kua ","Qiu ","Yang ","Hui ","Hui ","Chi ","Jia ","Yi ","Xiong ","Guai ","Lin ","Hui ","Zi ","Xu ","Chi ","Xiang ","Nu ","Hen ","En ","Ke ","Tong ","Tian ","Gong ","Quan ","Xi ","Qia ","Yue ","Peng ","Ken ","De ","Hui ","E ","Kyuu ","Tong ","Yan ","Kai ","Ce ","Nao ","Yun ","Mang ","Yong ","Yong ","Yuan ","Pi ","Kun ","Qiao ","Yue ","Yu ","Yu ","Jie ","Xi ","Zhe ","Lin ","Ti ","Han ","Hao ","Qie ","Ti ","Bu ","Yi ","Qian ","Hui ","Xi ","Bei ","Man ","Yi ","Heng ","Song ","Quan ","Cheng ","Hui ","Wu ","Wu ","You ","Li ","Liang ","Huan ","Cong ","Yi ","Yue ","Li ","Nin ","Nao ","E ","Que ","Xuan ","Qian ","Wu ","Min ","Cong ","Fei ","Bei ","Duo ","Cui ","Chang ","Men ","Li ","Ji ","Guan ","Guan ","Xing ","Dao ","Qi ","Kong ","Tian ","Lun ","Xi ","Kan ","Kun ","Ni ","Qing ","Chou ","Dun ","Guo ","Chan ","Liang ","Wan ","Yuan ","Jin ","Ji ","Lin ","Yu ","Huo ","He ","Quan ","Tan ","Ti ","Ti ","Nie ","Wang ","Chuo ","Bu ","Hun ","Xi ","Tang ","Xin ","Wei ","Hui ","E ","Rui ","Zong ","Jian ","Yong ","Dian ","Ju ","Can ","Cheng ","De ","Bei ","Qie ","Can ","Dan ","Guan ","Duo ","Nao ","Yun ","Xiang ","Zhui ","Die ","Huang ","Chun ","Qiong ","Re ","Xing ","Ce ","Bian ","Hun ","Zong ","Ti "]});var c1=w((pwe,u1)=>{u1.exports=["Qiao ","Chou ","Bei ","Xuan ","Wei ","Ge ","Qian ","Wei ","Yu ","Yu ","Bi ","Xuan ","Huan ","Min ","Bi ","Yi ","Mian ","Yong ","Kai ","Dang ","Yin ","E ","Chen ","Mou ","Ke ","Ke ","Yu ","Ai ","Qie ","Yan ","Nuo ","Gan ","Yun ","Zong ","Sai ","Leng ","Fen ","[?] ","Kui ","Kui ","Que ","Gong ","Yun ","Su ","Su ","Qi ","Yao ","Song ","Huang ","Ji ","Gu ","Ju ","Chuang ","Ni ","Xie ","Kai ","Zheng ","Yong ","Cao ","Sun ","Shen ","Bo ","Kai ","Yuan ","Xie ","Hun ","Yong ","Yang ","Li ","Sao ","Tao ","Yin ","Ci ","Xu ","Qian ","Tai ","Huang ","Yun ","Shen ","Ming ","[?] ","She ","Cong ","Piao ","Mo ","Mu ","Guo ","Chi ","Can ","Can ","Can ","Cui ","Min ","Te ","Zhang ","Tong ","Ao ","Shuang ","Man ","Guan ","Que ","Zao ","Jiu ","Hui ","Kai ","Lian ","Ou ","Song ","Jin ","Yin ","Lu ","Shang ","Wei ","Tuan ","Man ","Qian ","She ","Yong ","Qing ","Kang ","Di ","Zhi ","Lou ","Juan ","Qi ","Qi ","Yu ","Ping ","Liao ","Cong ","You ","Chong ","Zhi ","Tong ","Cheng ","Qi ","Qu ","Peng ","Bei ","Bie ","Chun ","Jiao ","Zeng ","Chi ","Lian ","Ping ","Kui ","Hui ","Qiao ","Cheng ","Yin ","Yin ","Xi ","Xi ","Dan ","Tan ","Duo ","Dui ","Dui ","Su ","Jue ","Ce ","Xiao ","Fan ","Fen ","Lao ","Lao ","Chong ","Han ","Qi ","Xian ","Min ","Jing ","Liao ","Wu ","Can ","Jue ","Cu ","Xian ","Tan ","Sheng ","Pi ","Yi ","Chu ","Xian ","Nao ","Dan ","Tan ","Jing ","Song ","Han ","Jiao ","Wai ","Huan ","Dong ","Qin ","Qin ","Qu ","Cao ","Ken ","Xie ","Ying ","Ao ","Mao ","Yi ","Lin ","Se ","Jun ","Huai ","Men ","Lan ","Ai ","Lin ","Yan ","Gua ","Xia ","Chi ","Yu ","Yin ","Dai ","Meng ","Ai ","Meng ","Dui ","Qi ","Mo ","Lan ","Men ","Chou ","Zhi ","Nuo ","Nuo ","Yan ","Yang ","Bo ","Zhi ","Kuang ","Kuang ","You ","Fu ","Liu ","Mie ","Cheng ","[?] ","Chan ","Meng ","Lan ","Huai ","Xuan ","Rang ","Chan ","Ji ","Ju ","Huan ","She ","Yi "]});var h1=w((fwe,d1)=>{d1.exports=["Lian ","Nan ","Mi ","Tang ","Jue ","Gang ","Gang ","Gang ","Ge ","Yue ","Wu ","Jian ","Xu ","Shu ","Rong ","Xi ","Cheng ","Wo ","Jie ","Ge ","Jian ","Qiang ","Huo ","Qiang ","Zhan ","Dong ","Qi ","Jia ","Die ","Zei ","Jia ","Ji ","Shi ","Kan ","Ji ","Kui ","Gai ","Deng ","Zhan ","Chuang ","Ge ","Jian ","Jie ","Yu ","Jian ","Yan ","Lu ","Xi ","Zhan ","Xi ","Xi ","Chuo ","Dai ","Qu ","Hu ","Hu ","Hu ","E ","Shi ","Li ","Mao ","Hu ","Li ","Fang ","Suo ","Bian ","Dian ","Jiong ","Shang ","Yi ","Yi ","Shan ","Hu ","Fei ","Yan ","Shou ","T ","Cai ","Zha ","Qiu ","Le ","Bu ","Ba ","Da ","Reng ","Fu ","Hameru ","Zai ","Tuo ","Zhang ","Diao ","Kang ","Yu ","Ku ","Han ","Shen ","Cha ","Yi ","Gu ","Kou ","Wu ","Tuo ","Qian ","Zhi ","Ren ","Kuo ","Men ","Sao ","Yang ","Niu ","Ban ","Che ","Rao ","Xi ","Qian ","Ban ","Jia ","Yu ","Fu ","Ao ","Xi ","Pi ","Zhi ","Zi ","E ","Dun ","Zhao ","Cheng ","Ji ","Yan ","Kuang ","Bian ","Chao ","Ju ","Wen ","Hu ","Yue ","Jue ","Ba ","Qin ","Zhen ","Zheng ","Yun ","Wan ","Nu ","Yi ","Shu ","Zhua ","Pou ","Tou ","Dou ","Kang ","Zhe ","Pou ","Fu ","Pao ","Ba ","Ao ","Ze ","Tuan ","Kou ","Lun ","Qiang ","[?] ","Hu ","Bao ","Bing ","Zhi ","Peng ","Tan ","Pu ","Pi ","Tai ","Yao ","Zhen ","Zha ","Yang ","Bao ","He ","Ni ","Yi ","Di ","Chi ","Pi ","Za ","Mo ","Mo ","Shen ","Ya ","Chou ","Qu ","Min ","Chu ","Jia ","Fu ","Zhan ","Zhu ","Dan ","Chai ","Mu ","Nian ","La ","Fu ","Pao ","Ban ","Pai ","Ling ","Na ","Guai ","Qian ","Ju ","Tuo ","Ba ","Tuo ","Tuo ","Ao ","Ju ","Zhuo ","Pan ","Zhao ","Bai ","Bai ","Di ","Ni ","Ju ","Kuo ","Long ","Jian ","[?] ","Yong ","Lan ","Ning ","Bo ","Ze ","Qian ","Hen ","Gua ","Shi ","Jie ","Zheng ","Nin ","Gong ","Gong ","Quan ","Shuan ","Cun ","Zan ","Kao ","Chi ","Xie ","Ce ","Hui ","Pin ","Zhuai ","Shi ","Na "]});var p1=w((mwe,g1)=>{g1.exports=["Bo ","Chi ","Gua ","Zhi ","Kuo ","Duo ","Duo ","Zhi ","Qie ","An ","Nong ","Zhen ","Ge ","Jiao ","Ku ","Dong ","Ru ","Tiao ","Lie ","Zha ","Lu ","Die ","Wa ","Jue ","Mushiru ","Ju ","Zhi ","Luan ","Ya ","Zhua ","Ta ","Xie ","Nao ","Dang ","Jiao ","Zheng ","Ji ","Hui ","Xun ","Ku ","Ai ","Tuo ","Nuo ","Cuo ","Bo ","Geng ","Ti ","Zhen ","Cheng ","Suo ","Suo ","Keng ","Mei ","Long ","Ju ","Peng ","Jian ","Yi ","Ting ","Shan ","Nuo ","Wan ","Xie ","Cha ","Feng ","Jiao ","Wu ","Jun ","Jiu ","Tong ","Kun ","Huo ","Tu ","Zhuo ","Pou ","Le ","Ba ","Han ","Shao ","Nie ","Juan ","Ze ","Song ","Ye ","Jue ","Bu ","Huan ","Bu ","Zun ","Yi ","Zhai ","Lu ","Sou ","Tuo ","Lao ","Sun ","Bang ","Jian ","Huan ","Dao ","[?] ","Wan ","Qin ","Peng ","She ","Lie ","Min ","Men ","Fu ","Bai ","Ju ","Dao ","Wo ","Ai ","Juan ","Yue ","Zong ","Chen ","Chui ","Jie ","Tu ","Ben ","Na ","Nian ","Nuo ","Zu ","Wo ","Xi ","Xian ","Cheng ","Dian ","Sao ","Lun ","Qing ","Gang ","Duo ","Shou ","Diao ","Pou ","Di ","Zhang ","Gun ","Ji ","Tao ","Qia ","Qi ","Pai ","Shu ","Qian ","Ling ","Yi ","Ya ","Jue ","Zheng ","Liang ","Gua ","Yi ","Huo ","Shan ","Zheng ","Lue ","Cai ","Tan ","Che ","Bing ","Jie ","Ti ","Kong ","Tui ","Yan ","Cuo ","Zou ","Ju ","Tian ","Qian ","Ken ","Bai ","Shou ","Jie ","Lu ","Guo ","Haba ","[?] ","Zhi ","Dan ","Mang ","Xian ","Sao ","Guan ","Peng ","Yuan ","Nuo ","Jian ","Zhen ","Jiu ","Jian ","Yu ","Yan ","Kui ","Nan ","Hong ","Rou ","Pi ","Wei ","Sai ","Zou ","Xuan ","Miao ","Ti ","Nie ","Cha ","Shi ","Zong ","Zhen ","Yi ","Shun ","Heng ","Bian ","Yang ","Huan ","Yan ","Zuan ","An ","Xu ","Ya ","Wo ","Ke ","Chuai ","Ji ","Ti ","La ","La ","Cheng ","Kai ","Jiu ","Jiu ","Tu ","Jie ","Hui ","Geng ","Chong ","Shuo ","She ","Xie ","Yuan ","Qian ","Ye ","Cha ","Zha ","Bei ","Yao ","[?] ","[?] ","Lan ","Wen ","Qin "]});var m1=w((bwe,f1)=>{f1.exports=["Chan ","Ge ","Lou ","Zong ","Geng ","Jiao ","Gou ","Qin ","Yong ","Que ","Chou ","Chi ","Zhan ","Sun ","Sun ","Bo ","Chu ","Rong ","Beng ","Cuo ","Sao ","Ke ","Yao ","Dao ","Zhi ","Nu ","Xie ","Jian ","Sou ","Qiu ","Gao ","Xian ","Shuo ","Sang ","Jin ","Mie ","E ","Chui ","Nuo ","Shan ","Ta ","Jie ","Tang ","Pan ","Ban ","Da ","Li ","Tao ","Hu ","Zhi ","Wa ","Xia ","Qian ","Wen ","Qiang ","Tian ","Zhen ","E ","Xi ","Nuo ","Quan ","Cha ","Zha ","Ge ","Wu ","En ","She ","Kang ","She ","Shu ","Bai ","Yao ","Bin ","Sou ","Tan ","Sa ","Chan ","Suo ","Liao ","Chong ","Chuang ","Guo ","Bing ","Feng ","Shuai ","Di ","Qi ","Sou ","Zhai ","Lian ","Tang ","Chi ","Guan ","Lu ","Luo ","Lou ","Zong ","Gai ","Hu ","Zha ","Chuang ","Tang ","Hua ","Cui ","Nai ","Mo ","Jiang ","Gui ","Ying ","Zhi ","Ao ","Zhi ","Nie ","Man ","Shan ","Kou ","Shu ","Suo ","Tuan ","Jiao ","Mo ","Mo ","Zhe ","Xian ","Keng ","Piao ","Jiang ","Yin ","Gou ","Qian ","Lue ","Ji ","Ying ","Jue ","Pie ","Pie ","Lao ","Dun ","Xian ","Ruan ","Kui ","Zan ","Yi ","Xun ","Cheng ","Cheng ","Sa ","Nao ","Heng ","Si ","Qian ","Huang ","Da ","Zun ","Nian ","Lin ","Zheng ","Hui ","Zhuang ","Jiao ","Ji ","Cao ","Dan ","Dan ","Che ","Bo ","Che ","Jue ","Xiao ","Liao ","Ben ","Fu ","Qiao ","Bo ","Cuo ","Zhuo ","Zhuan ","Tuo ","Pu ","Qin ","Dun ","Nian ","[?] ","Xie ","Lu ","Jiao ","Cuan ","Ta ","Han ","Qiao ","Zhua ","Jian ","Gan ","Yong ","Lei ","Kuo ","Lu ","Shan ","Zhuo ","Ze ","Pu ","Chuo ","Ji ","Dang ","Suo ","Cao ","Qing ","Jing ","Huan ","Jie ","Qin ","Kuai ","Dan ","Xi ","Ge ","Pi ","Bo ","Ao ","Ju ","Ye ","[?] ","Mang ","Sou ","Mi ","Ji ","Tai ","Zhuo ","Dao ","Xing ","Lan ","Ca ","Ju ","Ye ","Ru ","Ye ","Ye ","Ni ","Hu ","Ji ","Bin ","Ning ","Ge ","Zhi ","Jie ","Kuo ","Mo ","Jian ","Xie ","Lie ","Tan ","Bai ","Sou ","Lu ","Lue ","Rao ","Zhi "]});var y1=w((ywe,b1)=>{b1.exports=["Pan ","Yang ","Lei ","Sa ","Shu ","Zan ","Nian ","Xian ","Jun ","Huo ","Li ","La ","Han ","Ying ","Lu ","Long ","Qian ","Qian ","Zan ","Qian ","Lan ","San ","Ying ","Mei ","Rang ","Chan ","[?] ","Cuan ","Xi ","She ","Luo ","Jun ","Mi ","Li ","Zan ","Luan ","Tan ","Zuan ","Li ","Dian ","Wa ","Dang ","Jiao ","Jue ","Lan ","Li ","Nang ","Zhi ","Gui ","Gui ","Qi ","Xin ","Pu ","Sui ","Shou ","Kao ","You ","Gai ","Yi ","Gong ","Gan ","Ban ","Fang ","Zheng ","Bo ","Dian ","Kou ","Min ","Wu ","Gu ","He ","Ce ","Xiao ","Mi ","Chu ","Ge ","Di ","Xu ","Jiao ","Min ","Chen ","Jiu ","Zhen ","Duo ","Yu ","Chi ","Ao ","Bai ","Xu ","Jiao ","Duo ","Lian ","Nie ","Bi ","Chang ","Dian ","Duo ","Yi ","Gan ","San ","Ke ","Yan ","Dun ","Qi ","Dou ","Xiao ","Duo ","Jiao ","Jing ","Yang ","Xia ","Min ","Shu ","Ai ","Qiao ","Ai ","Zheng ","Di ","Zhen ","Fu ","Shu ","Liao ","Qu ","Xiong ","Xi ","Jiao ","Sen ","Jiao ","Zhuo ","Yi ","Lian ","Bi ","Li ","Xiao ","Xiao ","Wen ","Xue ","Qi ","Qi ","Zhai ","Bin ","Jue ","Zhai ","[?] ","Fei ","Ban ","Ban ","Lan ","Yu ","Lan ","Wei ","Dou ","Sheng ","Liao ","Jia ","Hu ","Xie ","Jia ","Yu ","Zhen ","Jiao ","Wo ","Tou ","Chu ","Jin ","Chi ","Yin ","Fu ","Qiang ","Zhan ","Qu ","Zhuo ","Zhan ","Duan ","Zhuo ","Si ","Xin ","Zhuo ","Zhuo ","Qin ","Lin ","Zhuo ","Chu ","Duan ","Zhu ","Fang ","Xie ","Hang ","Yu ","Shi ","Pei ","You ","Mye ","Pang ","Qi ","Zhan ","Mao ","Lu ","Pei ","Pi ","Liu ","Fu ","Fang ","Xuan ","Jing ","Jing ","Ni ","Zu ","Zhao ","Yi ","Liu ","Shao ","Jian ","Es ","Yi ","Qi ","Zhi ","Fan ","Piao ","Fan ","Zhan ","Guai ","Sui ","Yu ","Wu ","Ji ","Ji ","Ji ","Huo ","Ri ","Dan ","Jiu ","Zhi ","Zao ","Xie ","Tiao ","Xun ","Xu ","Xu ","Xu ","Gan ","Han ","Tai ","Di ","Xu ","Chan ","Shi ","Kuang ","Yang ","Shi ","Wang ","Min ","Min ","Tun ","Chun ","Wu "]});var w1=w((vwe,v1)=>{v1.exports=["Yun ","Bei ","Ang ","Ze ","Ban ","Jie ","Kun ","Sheng ","Hu ","Fang ","Hao ","Gui ","Chang ","Xuan ","Ming ","Hun ","Fen ","Qin ","Hu ","Yi ","Xi ","Xin ","Yan ","Ze ","Fang ","Tan ","Shen ","Ju ","Yang ","Zan ","Bing ","Xing ","Ying ","Xuan ","Pei ","Zhen ","Ling ","Chun ","Hao ","Mei ","Zuo ","Mo ","Bian ","Xu ","Hun ","Zhao ","Zong ","Shi ","Shi ","Yu ","Fei ","Die ","Mao ","Ni ","Chang ","Wen ","Dong ","Ai ","Bing ","Ang ","Zhou ","Long ","Xian ","Kuang ","Tiao ","Chao ","Shi ","Huang ","Huang ","Xuan ","Kui ","Xu ","Jiao ","Jin ","Zhi ","Jin ","Shang ","Tong ","Hong ","Yan ","Gai ","Xiang ","Shai ","Xiao ","Ye ","Yun ","Hui ","Han ","Han ","Jun ","Wan ","Xian ","Kun ","Zhou ","Xi ","Cheng ","Sheng ","Bu ","Zhe ","Zhe ","Wu ","Han ","Hui ","Hao ","Chen ","Wan ","Tian ","Zhuo ","Zui ","Zhou ","Pu ","Jing ","Xi ","Shan ","Yi ","Xi ","Qing ","Qi ","Jing ","Gui ","Zhen ","Yi ","Zhi ","An ","Wan ","Lin ","Liang ","Chang ","Wang ","Xiao ","Zan ","Hi ","Xuan ","Xuan ","Yi ","Xia ","Yun ","Hui ","Fu ","Min ","Kui ","He ","Ying ","Du ","Wei ","Shu ","Qing ","Mao ","Nan ","Jian ","Nuan ","An ","Yang ","Chun ","Yao ","Suo ","Jin ","Ming ","Jiao ","Kai ","Gao ","Weng ","Chang ","Qi ","Hao ","Yan ","Li ","Ai ","Ji ","Gui ","Men ","Zan ","Xie ","Hao ","Mu ","Mo ","Cong ","Ni ","Zhang ","Hui ","Bao ","Han ","Xuan ","Chuan ","Liao ","Xian ","Dan ","Jing ","Pie ","Lin ","Tun ","Xi ","Yi ","Ji ","Huang ","Tai ","Ye ","Ye ","Li ","Tan ","Tong ","Xiao ","Fei ","Qin ","Zhao ","Hao ","Yi ","Xiang ","Xing ","Sen ","Jiao ","Bao ","Jing ","Yian ","Ai ","Ye ","Ru ","Shu ","Meng ","Xun ","Yao ","Pu ","Li ","Chen ","Kuang ","Die ","[?] ","Yan ","Huo ","Lu ","Xi ","Rong ","Long ","Nang ","Luo ","Luan ","Shai ","Tang ","Yan ","Chu ","Yue ","Yue ","Qu ","Yi ","Geng ","Ye ","Hu ","He ","Shu ","Cao ","Cao ","Noboru ","Man ","Ceng ","Ceng ","Ti "]});var C1=w((wwe,x1)=>{x1.exports=["Zui ","Can ","Xu ","Hui ","Yin ","Qie ","Fen ","Pi ","Yue ","You ","Ruan ","Peng ","Ban ","Fu ","Ling ","Fei ","Qu ","[?] ","Nu ","Tiao ","Shuo ","Zhen ","Lang ","Lang ","Juan ","Ming ","Huang ","Wang ","Tun ","Zhao ","Ji ","Qi ","Ying ","Zong ","Wang ","Tong ","Lang ","[?] ","Meng ","Long ","Mu ","Deng ","Wei ","Mo ","Ben ","Zha ","Zhu ","Zhu ","[?] ","Zhu ","Ren ","Ba ","Po ","Duo ","Duo ","Dao ","Li ","Qiu ","Ji ","Jiu ","Bi ","Xiu ","Ting ","Ci ","Sha ","Eburi ","Za ","Quan ","Qian ","Yu ","Gan ","Wu ","Cha ","Shan ","Xun ","Fan ","Wu ","Zi ","Li ","Xing ","Cai ","Cun ","Ren ","Shao ","Tuo ","Di ","Zhang ","Mang ","Chi ","Yi ","Gu ","Gong ","Du ","Yi ","Qi ","Shu ","Gang ","Tiao ","Moku ","Soma ","Tochi ","Lai ","Sugi ","Mang ","Yang ","Ma ","Miao ","Si ","Yuan ","Hang ","Fei ","Bei ","Jie ","Dong ","Gao ","Yao ","Xian ","Chu ","Qun ","Pa ","Shu ","Hua ","Xin ","Chou ","Zhu ","Chou ","Song ","Ban ","Song ","Ji ","Yue ","Jin ","Gou ","Ji ","Mao ","Pi ","Bi ","Wang ","Ang ","Fang ","Fen ","Yi ","Fu ","Nan ","Xi ","Hu ","Ya ","Dou ","Xun ","Zhen ","Yao ","Lin ","Rui ","E ","Mei ","Zhao ","Guo ","Zhi ","Cong ","Yun ","Waku ","Dou ","Shu ","Zao ","[?] ","Li ","Haze ","Jian ","Cheng ","Matsu ","Qiang ","Feng ","Nan ","Xiao ","Xian ","Ku ","Ping ","Yi ","Xi ","Zhi ","Guai ","Xiao ","Jia ","Jia ","Gou ","Fu ","Mo ","Yi ","Ye ","Ye ","Shi ","Nie ","Bi ","Duo ","Yi ","Ling ","Bing ","Ni ","La ","He ","Pan ","Fan ","Zhong ","Dai ","Ci ","Yang ","Fu ","Bo ","Mou ","Gan ","Qi ","Ran ","Rou ","Mao ","Zhao ","Song ","Zhe ","Xia ","You ","Shen ","Ju ","Tuo ","Zuo ","Nan ","Ning ","Yong ","Di ","Zhi ","Zha ","Cha ","Dan ","Gu ","Pu ","Jiu ","Ao ","Fu ","Jian ","Bo ","Duo ","Ke ","Nai ","Zhu ","Bi ","Liu ","Chai ","Zha ","Si ","Zhu ","Pei ","Shi ","Guai ","Cha ","Yao ","Jue ","Jiu ","Shi "]});var D1=w((xwe,S1)=>{S1.exports=["Zhi ","Liu ","Mei ","Hoy ","Rong ","Zha ","[?] ","Biao ","Zhan ","Jie ","Long ","Dong ","Lu ","Sayng ","Li ","Lan ","Yong ","Shu ","Xun ","Shuan ","Qi ","Zhen ","Qi ","Li ","Yi ","Xiang ","Zhen ","Li ","Su ","Gua ","Kan ","Bing ","Ren ","Xiao ","Bo ","Ren ","Bing ","Zi ","Chou ","Yi ","Jie ","Xu ","Zhu ","Jian ","Zui ","Er ","Er ","You ","Fa ","Gong ","Kao ","Lao ","Zhan ","Li ","Yin ","Yang ","He ","Gen ","Zhi ","Chi ","Ge ","Zai ","Luan ","Fu ","Jie ","Hang ","Gui ","Tao ","Guang ","Wei ","Kuang ","Ru ","An ","An ","Juan ","Yi ","Zhuo ","Ku ","Zhi ","Qiong ","Tong ","Sang ","Sang ","Huan ","Jie ","Jiu ","Xue ","Duo ","Zhui ","Yu ","Zan ","Kasei ","Ying ","Masu ","[?] ","Zhan ","Ya ","Nao ","Zhen ","Dang ","Qi ","Qiao ","Hua ","Kuai ","Jiang ","Zhuang ","Xun ","Suo ","Sha ","Zhen ","Bei ","Ting ","Gua ","Jing ","Bo ","Ben ","Fu ","Rui ","Tong ","Jue ","Xi ","Lang ","Liu ","Feng ","Qi ","Wen ","Jun ","Gan ","Cu ","Liang ","Qiu ","Ting ","You ","Mei ","Bang ","Long ","Peng ","Zhuang ","Di ","Xuan ","Tu ","Zao ","Ao ","Gu ","Bi ","Di ","Han ","Zi ","Zhi ","Ren ","Bei ","Geng ","Jian ","Huan ","Wan ","Nuo ","Jia ","Tiao ","Ji ","Xiao ","Lu ","Huan ","Shao ","Cen ","Fen ","Song ","Meng ","Wu ","Li ","Li ","Dou ","Cen ","Ying ","Suo ","Ju ","Ti ","Jie ","Kun ","Zhuo ","Shu ","Chan ","Fan ","Wei ","Jing ","Li ","Bing ","Fumoto ","Shikimi ","Tao ","Zhi ","Lai ","Lian ","Jian ","Zhuo ","Ling ","Li ","Qi ","Bing ","Zhun ","Cong ","Qian ","Mian ","Qi ","Qi ","Cai ","Gun ","Chan ","Te ","Fei ","Pai ","Bang ","Pou ","Hun ","Zong ","Cheng ","Zao ","Ji ","Li ","Peng ","Yu ","Yu ","Gu ","Hun ","Dong ","Tang ","Gang ","Wang ","Di ","Xi ","Fan ","Cheng ","Zhan ","Qi ","Yuan ","Yan ","Yu ","Quan ","Yi ","Sen ","Ren ","Chui ","Leng ","Qi ","Zhuo ","Fu ","Ke ","Lai ","Zou ","Zou ","Zhuo ","Guan ","Fen ","Fen ","Chen ","Qiong ","Nie "]});var k1=w((Cwe,T1)=>{T1.exports=["Wan ","Guo ","Lu ","Hao ","Jie ","Yi ","Chou ","Ju ","Ju ","Cheng ","Zuo ","Liang ","Qiang ","Zhi ","Zhui ","Ya ","Ju ","Bei ","Jiao ","Zhuo ","Zi ","Bin ","Peng ","Ding ","Chu ","Chang ","Kunugi ","Momiji ","Jian ","Gui ","Xi ","Du ","Qian ","Kunugi ","Soko ","Shide ","Luo ","Zhi ","Ken ","Myeng ","Tafu ","[?] ","Peng ","Zhan ","[?] ","Tuo ","Sen ","Duo ","Ye ","Fou ","Wei ","Wei ","Duan ","Jia ","Zong ","Jian ","Yi ","Shen ","Xi ","Yan ","Yan ","Chuan ","Zhan ","Chun ","Yu ","He ","Zha ","Wo ","Pian ","Bi ","Yao ","Huo ","Xu ","Ruo ","Yang ","La ","Yan ","Ben ","Hun ","Kui ","Jie ","Kui ","Si ","Feng ","Xie ","Tuo ","Zhi ","Jian ","Mu ","Mao ","Chu ","Hu ","Hu ","Lian ","Leng ","Ting ","Nan ","Yu ","You ","Mei ","Song ","Xuan ","Xuan ","Ying ","Zhen ","Pian ","Ye ","Ji ","Jie ","Ye ","Chu ","Shun ","Yu ","Cou ","Wei ","Mei ","Di ","Ji ","Jie ","Kai ","Qiu ","Ying ","Rou ","Heng ","Lou ","Le ","Hazou ","Katsura ","Pin ","Muro ","Gai ","Tan ","Lan ","Yun ","Yu ","Chen ","Lu ","Ju ","Sakaki ","[?] ","Pi ","Xie ","Jia ","Yi ","Zhan ","Fu ","Nai ","Mi ","Lang ","Rong ","Gu ","Jian ","Ju ","Ta ","Yao ","Zhen ","Bang ","Sha ","Yuan ","Zi ","Ming ","Su ","Jia ","Yao ","Jie ","Huang ","Gan ","Fei ","Zha ","Qian ","Ma ","Sun ","Yuan ","Xie ","Rong ","Shi ","Zhi ","Cui ","Yun ","Ting ","Liu ","Rong ","Tang ","Que ","Zhai ","Si ","Sheng ","Ta ","Ke ","Xi ","Gu ","Qi ","Kao ","Gao ","Sun ","Pan ","Tao ","Ge ","Xun ","Dian ","Nou ","Ji ","Shuo ","Gou ","Chui ","Qiang ","Cha ","Qian ","Huai ","Mei ","Xu ","Gang ","Gao ","Zhuo ","Tuo ","Hashi ","Yang ","Dian ","Jia ","Jian ","Zui ","Kashi ","Ori ","Bin ","Zhu ","[?] ","Xi ","Qi ","Lian ","Hui ","Yong ","Qian ","Guo ","Gai ","Gai ","Tuan ","Hua ","Cu ","Sen ","Cui ","Beng ","You ","Hu ","Jiang ","Hu ","Huan ","Kui ","Yi ","Nie ","Gao ","Kang ","Gui ","Gui ","Cao ","Man ","Jin "]});var R1=w((Swe,P1)=>{P1.exports=["Di ","Zhuang ","Le ","Lang ","Chen ","Cong ","Li ","Xiu ","Qing ","Shuang ","Fan ","Tong ","Guan ","Ji ","Suo ","Lei ","Lu ","Liang ","Mi ","Lou ","Chao ","Su ","Ke ","Shu ","Tang ","Biao ","Lu ","Jiu ","Shu ","Zha ","Shu ","Zhang ","Men ","Mo ","Niao ","Yang ","Tiao ","Peng ","Zhu ","Sha ","Xi ","Quan ","Heng ","Jian ","Cong ","[?] ","Hokuso ","Qiang ","Tara ","Ying ","Er ","Xin ","Zhi ","Qiao ","Zui ","Cong ","Pu ","Shu ","Hua ","Kui ","Zhen ","Zun ","Yue ","Zhan ","Xi ","Xun ","Dian ","Fa ","Gan ","Mo ","Wu ","Qiao ","Nao ","Lin ","Liu ","Qiao ","Xian ","Run ","Fan ","Zhan ","Tuo ","Lao ","Yun ","Shun ","Tui ","Cheng ","Tang ","Meng ","Ju ","Cheng ","Su ","Jue ","Jue ","Tan ","Hui ","Ji ","Nuo ","Xiang ","Tuo ","Ning ","Rui ","Zhu ","Chuang ","Zeng ","Fen ","Qiong ","Ran ","Heng ","Cen ","Gu ","Liu ","Lao ","Gao ","Chu ","Zusa ","Nude ","Ca ","San ","Ji ","Dou ","Shou ","Lu ","[?] ","[?] ","Yuan ","Ta ","Shu ","Jiang ","Tan ","Lin ","Nong ","Yin ","Xi ","Sui ","Shan ","Zui ","Xuan ","Cheng ","Gan ","Ju ","Zui ","Yi ","Qin ","Pu ","Yan ","Lei ","Feng ","Hui ","Dang ","Ji ","Sui ","Bo ","Bi ","Ding ","Chu ","Zhua ","Kuai ","Ji ","Jie ","Jia ","Qing ","Zhe ","Jian ","Qiang ","Dao ","Yi ","Biao ","Song ","She ","Lin ","Kunugi ","Cha ","Meng ","Yin ","Tao ","Tai ","Mian ","Qi ","Toan ","Bin ","Huo ","Ji ","Qian ","Mi ","Ning ","Yi ","Gao ","Jian ","Yin ","Er ","Qing ","Yan ","Qi ","Mi ","Zhao ","Gui ","Chun ","Ji ","Kui ","Po ","Deng ","Chu ","[?] ","Mian ","You ","Zhi ","Guang ","Qian ","Lei ","Lei ","Sa ","Lu ","Li ","Cuan ","Lu ","Mie ","Hui ","Ou ","Lu ","Jie ","Gao ","Du ","Yuan ","Li ","Fei ","Zhuo ","Sou ","Lian ","Tamo ","Chu ","[?] ","Zhu ","Lu ","Yan ","Li ","Zhu ","Chen ","Jie ","E ","Su ","Huai ","Nie ","Yu ","Long ","Lai ","[?] ","Xian ","Kwi ","Ju ","Xiao ","Ling ","Ying ","Jian ","Yin ","You ","Ying "]});var E1=w((Dwe,_1)=>{_1.exports=["Xiang ","Nong ","Bo ","Chan ","Lan ","Ju ","Shuang ","She ","Wei ","Cong ","Quan ","Qu ","Cang ","[?] ","Yu ","Luo ","Li ","Zan ","Luan ","Dang ","Jue ","Em ","Lan ","Lan ","Zhu ","Lei ","Li ","Ba ","Nang ","Yu ","Ling ","Tsuki ","Qian ","Ci ","Huan ","Xin ","Yu ","Yu ","Qian ","Ou ","Xu ","Chao ","Chu ","Chi ","Kai ","Yi ","Jue ","Xi ","Xu ","Xia ","Yu ","Kuai ","Lang ","Kuan ","Shuo ","Xi ","Ai ","Yi ","Qi ","Hu ","Chi ","Qin ","Kuan ","Kan ","Kuan ","Kan ","Chuan ","Sha ","Gua ","Yin ","Xin ","Xie ","Yu ","Qian ","Xiao ","Yi ","Ge ","Wu ","Tan ","Jin ","Ou ","Hu ","Ti ","Huan ","Xu ","Pen ","Xi ","Xiao ","Xu ","Xi ","Sen ","Lian ","Chu ","Yi ","Kan ","Yu ","Chuo ","Huan ","Zhi ","Zheng ","Ci ","Bu ","Wu ","Qi ","Bu ","Bu ","Wai ","Ju ","Qian ","Chi ","Se ","Chi ","Se ","Zhong ","Sui ","Sui ","Li ","Cuo ","Yu ","Li ","Gui ","Dai ","Dai ","Si ","Jian ","Zhe ","Mo ","Mo ","Yao ","Mo ","Cu ","Yang ","Tian ","Sheng ","Dai ","Shang ","Xu ","Xun ","Shu ","Can ","Jue ","Piao ","Qia ","Qiu ","Su ","Qing ","Yun ","Lian ","Yi ","Fou ","Zhi ","Ye ","Can ","Hun ","Dan ","Ji ","Ye ","Zhen ","Yun ","Wen ","Chou ","Bin ","Ti ","Jin ","Shang ","Yin ","Diao ","Cu ","Hui ","Cuan ","Yi ","Dan ","Du ","Jiang ","Lian ","Bin ","Du ","Tsukusu ","Jian ","Shu ","Ou ","Duan ","Zhu ","Yin ","Qing ","Yi ","Sha ","Que ","Ke ","Yao ","Jun ","Dian ","Hui ","Hui ","Gu ","Que ","Ji ","Yi ","Ou ","Hui ","Duan ","Yi ","Xiao ","Wu ","Guan ","Mu ","Mei ","Mei ","Ai ","Zuo ","Du ","Yu ","Bi ","Bi ","Bi ","Pi ","Pi ","Bi ","Chan ","Mao ","[?] ","[?] ","Pu ","Mushiru ","Jia ","Zhan ","Sai ","Mu ","Tuo ","Xun ","Er ","Rong ","Xian ","Ju ","Mu ","Hao ","Qiu ","Dou ","Mushiru ","Tan ","Pei ","Ju ","Duo ","Cui ","Bi ","San ","[?] ","Mao ","Sui ","Yu ","Yu ","Tuo ","He ","Jian ","Ta ","San "]});var L1=w((Twe,I1)=>{I1.exports=["Lu ","Mu ","Li ","Tong ","Rong ","Chang ","Pu ","Luo ","Zhan ","Sao ","Zhan ","Meng ","Luo ","Qu ","Die ","Shi ","Di ","Min ","Jue ","Mang ","Qi ","Pie ","Nai ","Qi ","Dao ","Xian ","Chuan ","Fen ","Ri ","Nei ","[?] ","Fu ","Shen ","Dong ","Qing ","Qi ","Yin ","Xi ","Hai ","Yang ","An ","Ya ","Ke ","Qing ","Ya ","Dong ","Dan ","Lu ","Qing ","Yang ","Yun ","Yun ","Shui ","San ","Zheng ","Bing ","Yong ","Dang ","Shitamizu ","Le ","Ni ","Tun ","Fan ","Gui ","Ting ","Zhi ","Qiu ","Bin ","Ze ","Mian ","Cuan ","Hui ","Diao ","Yi ","Cha ","Zhuo ","Chuan ","Wan ","Fan ","Dai ","Xi ","Tuo ","Mang ","Qiu ","Qi ","Shan ","Pai ","Han ","Qian ","Wu ","Wu ","Xun ","Si ","Ru ","Gong ","Jiang ","Chi ","Wu ","Tsuchi ","[?] ","Tang ","Zhi ","Chi ","Qian ","Mi ","Yu ","Wang ","Qing ","Jing ","Rui ","Jun ","Hong ","Tai ","Quan ","Ji ","Bian ","Bian ","Gan ","Wen ","Zhong ","Fang ","Xiong ","Jue ","Hang ","Niou ","Qi ","Fen ","Xu ","Xu ","Qin ","Yi ","Wo ","Yun ","Yuan ","Hang ","Yan ","Chen ","Chen ","Dan ","You ","Dun ","Hu ","Huo ","Qie ","Mu ","Rou ","Mei ","Ta ","Mian ","Wu ","Chong ","Tian ","Bi ","Sha ","Zhi ","Pei ","Pan ","Zhui ","Za ","Gou ","Liu ","Mei ","Ze ","Feng ","Ou ","Li ","Lun ","Cang ","Feng ","Wei ","Hu ","Mo ","Mei ","Shu ","Ju ","Zan ","Tuo ","Tuo ","Tuo ","He ","Li ","Mi ","Yi ","Fa ","Fei ","You ","Tian ","Zhi ","Zhao ","Gu ","Zhan ","Yan ","Si ","Kuang ","Jiong ","Ju ","Xie ","Qiu ","Yi ","Jia ","Zhong ","Quan ","Bo ","Hui ","Mi ","Ben ","Zhuo ","Chu ","Le ","You ","Gu ","Hong ","Gan ","Fa ","Mao ","Si ","Hu ","Ping ","Ci ","Fan ","Chi ","Su ","Ning ","Cheng ","Ling ","Pao ","Bo ","Qi ","Si ","Ni ","Ju ","Yue ","Zhu ","Sheng ","Lei ","Xuan ","Xue ","Fu ","Pan ","Min ","Tai ","Yang ","Ji ","Yong ","Guan ","Beng ","Xue ","Long ","Lu ","[?] ","Bo ","Xie ","Po ","Ze ","Jing ","Yin "]});var M1=w((kwe,F1)=>{F1.exports=["Zhou ","Ji ","Yi ","Hui ","Hui ","Zui ","Cheng ","Yin ","Wei ","Hou ","Jian ","Yang ","Lie ","Si ","Ji ","Er ","Xing ","Fu ","Sa ","Suo ","Zhi ","Yin ","Wu ","Xi ","Kao ","Zhu ","Jiang ","Luo ","[?] ","An ","Dong ","Yi ","Mou ","Lei ","Yi ","Mi ","Quan ","Jin ","Mo ","Wei ","Xiao ","Xie ","Hong ","Xu ","Shuo ","Kuang ","Tao ","Qie ","Ju ","Er ","Zhou ","Ru ","Ping ","Xun ","Xiong ","Zhi ","Guang ","Huan ","Ming ","Huo ","Wa ","Qia ","Pai ","Wu ","Qu ","Liu ","Yi ","Jia ","Jing ","Qian ","Jiang ","Jiao ","Cheng ","Shi ","Zhuo ","Ce ","Pal ","Kuai ","Ji ","Liu ","Chan ","Hun ","Hu ","Nong ","Xun ","Jin ","Lie ","Qiu ","Wei ","Zhe ","Jun ","Han ","Bang ","Mang ","Zhuo ","You ","Xi ","Bo ","Dou ","Wan ","Hong ","Yi ","Pu ","Ying ","Lan ","Hao ","Lang ","Han ","Li ","Geng ","Fu ","Wu ","Lian ","Chun ","Feng ","Yi ","Yu ","Tong ","Lao ","Hai ","Jin ","Jia ","Chong ","Weng ","Mei ","Sui ","Cheng ","Pei ","Xian ","Shen ","Tu ","Kun ","Pin ","Nie ","Han ","Jing ","Xiao ","She ","Nian ","Tu ","Yong ","Xiao ","Xian ","Ting ","E ","Su ","Tun ","Juan ","Cen ","Ti ","Li ","Shui ","Si ","Lei ","Shui ","Tao ","Du ","Lao ","Lai ","Lian ","Wei ","Wo ","Yun ","Huan ","Di ","[?] ","Run ","Jian ","Zhang ","Se ","Fu ","Guan ","Xing ","Shou ","Shuan ","Ya ","Chuo ","Zhang ","Ye ","Kong ","Wo ","Han ","Tuo ","Dong ","He ","Wo ","Ju ","Gan ","Liang ","Hun ","Ta ","Zhuo ","Dian ","Qie ","De ","Juan ","Zi ","Xi ","Yao ","Qi ","Gu ","Guo ","Han ","Lin ","Tang ","Zhou ","Peng ","Hao ","Chang ","Shu ","Qi ","Fang ","Chi ","Lu ","Nao ","Ju ","Tao ","Cong ","Lei ","Zhi ","Peng ","Fei ","Song ","Tian ","Pi ","Dan ","Yu ","Ni ","Yu ","Lu ","Gan ","Mi ","Jing ","Ling ","Lun ","Yin ","Cui ","Qu ","Huai ","Yu ","Nian ","Shen ","Piao ","Chun ","Wa ","Yuan ","Lai ","Hun ","Qing ","Yan ","Qian ","Tian ","Miao ","Zhi ","Yin ","Mi "]});var O1=w((Pwe,j1)=>{j1.exports=["Ben ","Yuan ","Wen ","Re ","Fei ","Qing ","Yuan ","Ke ","Ji ","She ","Yuan ","Shibui ","Lu ","Zi ","Du ","[?] ","Jian ","Min ","Pi ","Tani ","Yu ","Yuan ","Shen ","Shen ","Rou ","Huan ","Zhu ","Jian ","Nuan ","Yu ","Qiu ","Ting ","Qu ","Du ","Feng ","Zha ","Bo ","Wo ","Wo ","Di ","Wei ","Wen ","Ru ","Xie ","Ce ","Wei ","Ge ","Gang ","Yan ","Hong ","Xuan ","Mi ","Ke ","Mao ","Ying ","Yan ","You ","Hong ","Miao ","Xing ","Mei ","Zai ","Hun ","Nai ","Kui ","Shi ","E ","Pai ","Mei ","Lian ","Qi ","Qi ","Mei ","Tian ","Cou ","Wei ","Can ","Tuan ","Mian ","Hui ","Mo ","Xu ","Ji ","Pen ","Jian ","Jian ","Hu ","Feng ","Xiang ","Yi ","Yin ","Zhan ","Shi ","Jie ","Cheng ","Huang ","Tan ","Yu ","Bi ","Min ","Shi ","Tu ","Sheng ","Yong ","Qu ","Zhong ","Suei ","Jiu ","Jiao ","Qiou ","Yin ","Tang ","Long ","Huo ","Yuan ","Nan ","Ban ","You ","Quan ","Chui ","Liang ","Chan ","Yan ","Chun ","Nie ","Zi ","Wan ","Shi ","Man ","Ying ","Ratsu ","Kui ","[?] ","Jian ","Xu ","Lu ","Gui ","Gai ","[?] ","[?] ","Po ","Jin ","Gui ","Tang ","Yuan ","Suo ","Yuan ","Lian ","Yao ","Meng ","Zhun ","Sheng ","Ke ","Tai ","Da ","Wa ","Liu ","Gou ","Sao ","Ming ","Zha ","Shi ","Yi ","Lun ","Ma ","Pu ","Wei ","Li ","Cai ","Wu ","Xi ","Wen ","Qiang ","Ze ","Shi ","Su ","Yi ","Zhen ","Sou ","Yun ","Xiu ","Yin ","Rong ","Hun ","Su ","Su ","Ni ","Ta ","Shi ","Ru ","Wei ","Pan ","Chu ","Chu ","Pang ","Weng ","Cang ","Mie ","He ","Dian ","Hao ","Huang ","Xi ","Zi ","Di ","Zhi ","Ying ","Fu ","Jie ","Hua ","Ge ","Zi ","Tao ","Teng ","Sui ","Bi ","Jiao ","Hui ","Gun ","Yin ","Gao ","Long ","Zhi ","Yan ","She ","Man ","Ying ","Chun ","Lu ","Lan ","Luan ","[?] ","Bin ","Tan ","Yu ","Sou ","Hu ","Bi ","Biao ","Zhi ","Jiang ","Kou ","Shen ","Shang ","Di ","Mi ","Ao ","Lu ","Hu ","Hu ","You ","Chan ","Fan ","Yong ","Gun ","Man "]});var N1=w((Rwe,A1)=>{A1.exports=["Qing ","Yu ","Piao ","Ji ","Ya ","Jiao ","Qi ","Xi ","Ji ","Lu ","Lu ","Long ","Jin ","Guo ","Cong ","Lou ","Zhi ","Gai ","Qiang ","Li ","Yan ","Cao ","Jiao ","Cong ","Qun ","Tuan ","Ou ","Teng ","Ye ","Xi ","Mi ","Tang ","Mo ","Shang ","Han ","Lian ","Lan ","Wa ","Li ","Qian ","Feng ","Xuan ","Yi ","Man ","Zi ","Mang ","Kang ","Lei ","Peng ","Shu ","Zhang ","Zhang ","Chong ","Xu ","Huan ","Kuo ","Jian ","Yan ","Chuang ","Liao ","Cui ","Ti ","Yang ","Jiang ","Cong ","Ying ","Hong ","Xun ","Shu ","Guan ","Ying ","Xiao ","[?] ","[?] ","Xu ","Lian ","Zhi ","Wei ","Pi ","Jue ","Jiao ","Po ","Dang ","Hui ","Jie ","Wu ","Pa ","Ji ","Pan ","Gui ","Xiao ","Qian ","Qian ","Xi ","Lu ","Xi ","Xuan ","Dun ","Huang ","Min ","Run ","Su ","Liao ","Zhen ","Zhong ","Yi ","Di ","Wan ","Dan ","Tan ","Chao ","Xun ","Kui ","Yie ","Shao ","Tu ","Zhu ","San ","Hei ","Bi ","Shan ","Chan ","Chan ","Shu ","Tong ","Pu ","Lin ","Wei ","Se ","Se ","Cheng ","Jiong ","Cheng ","Hua ","Jiao ","Lao ","Che ","Gan ","Cun ","Heng ","Si ","Shu ","Peng ","Han ","Yun ","Liu ","Hong ","Fu ","Hao ","He ","Xian ","Jian ","Shan ","Xi ","Oki ","[?] ","Lan ","[?] ","Yu ","Lin ","Min ","Zao ","Dang ","Wan ","Ze ","Xie ","Yu ","Li ","Shi ","Xue ","Ling ","Man ","Zi ","Yong ","Kuai ","Can ","Lian ","Dian ","Ye ","Ao ","Huan ","Zhen ","Chan ","Man ","Dan ","Dan ","Yi ","Sui ","Pi ","Ju ","Ta ","Qin ","Ji ","Zhuo ","Lian ","Nong ","Guo ","Jin ","Fen ","Se ","Ji ","Sui ","Hui ","Chu ","Ta ","Song ","Ding ","[?] ","Zhu ","Lai ","Bin ","Lian ","Mi ","Shi ","Shu ","Mi ","Ning ","Ying ","Ying ","Meng ","Jin ","Qi ","Pi ","Ji ","Hao ","Ru ","Zui ","Wo ","Tao ","Yin ","Yin ","Dui ","Ci ","Huo ","Jing ","Lan ","Jun ","Ai ","Pu ","Zhuo ","Wei ","Bin ","Gu ","Qian ","Xing ","Hama ","Kuo ","Fei ","[?] ","Boku ","Jian ","Wei ","Luo ","Zan ","Lu ","Li "]});var B1=w((_we,H1)=>{H1.exports=["You ","Yang ","Lu ","Si ","Jie ","Ying ","Du ","Wang ","Hui ","Xie ","Pan ","Shen ","Biao ","Chan ","Mo ","Liu ","Jian ","Pu ","Se ","Cheng ","Gu ","Bin ","Huo ","Xian ","Lu ","Qin ","Han ","Ying ","Yong ","Li ","Jing ","Xiao ","Ying ","Sui ","Wei ","Xie ","Huai ","Hao ","Zhu ","Long ","Lai ","Dui ","Fan ","Hu ","Lai ","[?] ","[?] ","Ying ","Mi ","Ji ","Lian ","Jian ","Ying ","Fen ","Lin ","Yi ","Jian ","Yue ","Chan ","Dai ","Rang ","Jian ","Lan ","Fan ","Shuang ","Yuan ","Zhuo ","Feng ","She ","Lei ","Lan ","Cong ","Qu ","Yong ","Qian ","Fa ","Guan ","Que ","Yan ","Hao ","Hyeng ","Sa ","Zan ","Luan ","Yan ","Li ","Mi ","Shan ","Tan ","Dang ","Jiao ","Chan ","[?] ","Hao ","Ba ","Zhu ","Lan ","Lan ","Nang ","Wan ","Luan ","Xun ","Xian ","Yan ","Gan ","Yan ","Yu ","Huo ","Si ","Mie ","Guang ","Deng ","Hui ","Xiao ","Xiao ","Hu ","Hong ","Ling ","Zao ","Zhuan ","Jiu ","Zha ","Xie ","Chi ","Zhuo ","Zai ","Zai ","Can ","Yang ","Qi ","Zhong ","Fen ","Niu ","Jiong ","Wen ","Po ","Yi ","Lu ","Chui ","Pi ","Kai ","Pan ","Yan ","Kai ","Pang ","Mu ","Chao ","Liao ","Gui ","Kang ","Tun ","Guang ","Xin ","Zhi ","Guang ","Guang ","Wei ","Qiang ","[?] ","Da ","Xia ","Zheng ","Zhu ","Ke ","Zhao ","Fu ","Ba ","Duo ","Duo ","Ling ","Zhuo ","Xuan ","Ju ","Tan ","Pao ","Jiong ","Pao ","Tai ","Tai ","Bing ","Yang ","Tong ","Han ","Zhu ","Zha ","Dian ","Wei ","Shi ","Lian ","Chi ","Huang ","[?] ","Hu ","Shuo ","Lan ","Jing ","Jiao ","Xu ","Xing ","Quan ","Lie ","Huan ","Yang ","Xiao ","Xiu ","Xian ","Yin ","Wu ","Zhou ","Yao ","Shi ","Wei ","Tong ","Xue ","Zai ","Kai ","Hong ","Luo ","Xia ","Zhu ","Xuan ","Zheng ","Po ","Yan ","Hui ","Guang ","Zhe ","Hui ","Kao ","[?] ","Fan ","Shao ","Ye ","Hui ","[?] ","Tang ","Jin ","Re ","[?] ","Xi ","Fu ","Jiong ","Che ","Pu ","Jing ","Zhuo ","Ting ","Wan ","Hai ","Peng ","Lang ","Shan ","Hu ","Feng ","Chi ","Rong "]});var W1=w((Ewe,q1)=>{q1.exports=["Hu ","Xi ","Shu ","He ","Xun ","Ku ","Jue ","Xiao ","Xi ","Yan ","Han ","Zhuang ","Jun ","Di ","Xie ","Ji ","Wu ","[?] ","[?] ","Han ","Yan ","Huan ","Men ","Ju ","Chou ","Bei ","Fen ","Lin ","Kun ","Hun ","Tun ","Xi ","Cui ","Wu ","Hong ","Ju ","Fu ","Wo ","Jiao ","Cong ","Feng ","Ping ","Qiong ","Ruo ","Xi ","Qiong ","Xin ","Zhuo ","Yan ","Yan ","Yi ","Jue ","Yu ","Gang ","Ran ","Pi ","Gu ","[?] ","Sheng ","Chang ","Shao ","[?] ","[?] ","[?] ","[?] ","Chen ","He ","Kui ","Zhong ","Duan ","Xia ","Hui ","Feng ","Lian ","Xuan ","Xing ","Huang ","Jiao ","Jian ","Bi ","Ying ","Zhu ","Wei ","Tuan ","Tian ","Xi ","Nuan ","Nuan ","Chan ","Yan ","Jiong ","Jiong ","Yu ","Mei ","Sha ","Wei ","Ye ","Xin ","Qiong ","Rou ","Mei ","Huan ","Xu ","Zhao ","Wei ","Fan ","Qiu ","Sui ","Yang ","Lie ","Zhu ","Jie ","Gao ","Gua ","Bao ","Hu ","Yun ","Xia ","[?] ","[?] ","Bian ","Gou ","Tui ","Tang ","Chao ","Shan ","N ","Bo ","Huang ","Xie ","Xi ","Wu ","Xi ","Yun ","He ","He ","Xi ","Yun ","Xiong ","Nai ","Shan ","Qiong ","Yao ","Xun ","Mi ","Lian ","Ying ","Wen ","Rong ","Oozutsu ","[?] ","Qiang ","Liu ","Xi ","Bi ","Biao ","Zong ","Lu ","Jian ","Shou ","Yi ","Lou ","Feng ","Sui ","Yi ","Tong ","Jue ","Zong ","Yun ","Hu ","Yi ","Zhi ","Ao ","Wei ","Liao ","Han ","Ou ","Re ","Jiong ","Man ","[?] ","Shang ","Cuan ","Zeng ","Jian ","Xi ","Xi ","Xi ","Yi ","Xiao ","Chi ","Huang ","Chan ","Ye ","Qian ","Ran ","Yan ","Xian ","Qiao ","Zun ","Deng ","Dun ","Shen ","Jiao ","Fen ","Si ","Liao ","Yu ","Lin ","Tong ","Shao ","Fen ","Fan ","Yan ","Xun ","Lan ","Mei ","Tang ","Yi ","Jing ","Men ","[?] ","[?] ","Ying ","Yu ","Yi ","Xue ","Lan ","Tai ","Zao ","Can ","Sui ","Xi ","Que ","Cong ","Lian ","Hui ","Zhu ","Xie ","Ling ","Wei ","Yi ","Xie ","Zhao ","Hui ","Tatsu ","Nung ","Lan ","Ru ","Xian ","Kao ","Xun ","Jin ","Chou ","Chou ","Yao "]});var Z1=w((Iwe,Y1)=>{Y1.exports=["He ","Lan ","Biao ","Rong ","Li ","Mo ","Bao ","Ruo ","Lu ","La ","Ao ","Xun ","Kuang ","Shuo ","[?] ","Li ","Lu ","Jue ","Liao ","Yan ","Xi ","Xie ","Long ","Ye ","[?] ","Rang ","Yue ","Lan ","Cong ","Jue ","Tong ","Guan ","[?] ","Che ","Mi ","Tang ","Lan ","Zhu ","[?] ","Ling ","Cuan ","Yu ","Zhua ","Tsumekanmuri ","Pa ","Zheng ","Pao ","Cheng ","Yuan ","Ai ","Wei ","[?] ","Jue ","Jue ","Fu ","Ye ","Ba ","Die ","Ye ","Yao ","Zu ","Shuang ","Er ","Qiang ","Chuang ","Ge ","Zang ","Die ","Qiang ","Yong ","Qiang ","Pian ","Ban ","Pan ","Shao ","Jian ","Pai ","Du ","Chuang ","Tou ","Zha ","Bian ","Die ","Bang ","Bo ","Chuang ","You ","[?] ","Du ","Ya ","Cheng ","Niu ","Ushihen ","Pin ","Jiu ","Mou ","Tuo ","Mu ","Lao ","Ren ","Mang ","Fang ","Mao ","Mu ","Gang ","Wu ","Yan ","Ge ","Bei ","Si ","Jian ","Gu ","You ","Ge ","Sheng ","Mu ","Di ","Qian ","Quan ","Quan ","Zi ","Te ","Xi ","Mang ","Keng ","Qian ","Wu ","Gu ","Xi ","Li ","Li ","Pou ","Ji ","Gang ","Zhi ","Ben ","Quan ","Run ","Du ","Ju ","Jia ","Jian ","Feng ","Pian ","Ke ","Ju ","Kao ","Chu ","Xi ","Bei ","Luo ","Jie ","Ma ","San ","Wei ","Li ","Dun ","Tong ","[?] ","Jiang ","Ikenie ","Li ","Du ","Lie ","Pi ","Piao ","Bao ","Xi ","Chou ","Wei ","Kui ","Chou ","Quan ","Fan ","Ba ","Fan ","Qiu ","Ji ","Cai ","Chuo ","An ","Jie ","Zhuang ","Guang ","Ma ","You ","Kang ","Bo ","Hou ","Ya ","Yin ","Huan ","Zhuang ","Yun ","Kuang ","Niu ","Di ","Qing ","Zhong ","Mu ","Bei ","Pi ","Ju ","Ni ","Sheng ","Pao ","Xia ","Tuo ","Hu ","Ling ","Fei ","Pi ","Ni ","Ao ","You ","Gou ","Yue ","Ju ","Dan ","Po ","Gu ","Xian ","Ning ","Huan ","Hen ","Jiao ","He ","Zhao ","Ji ","Xun ","Shan ","Ta ","Rong ","Shou ","Tong ","Lao ","Du ","Xia ","Shi ","Hua ","Zheng ","Yu ","Sun ","Yu ","Bi ","Mang ","Xi ","Juan ","Li ","Xia ","Yin ","Suan ","Lang ","Bei ","Zhi ","Yan "]});var $1=w((Lwe,J1)=>{J1.exports=["Sha ","Li ","Han ","Xian ","Jing ","Pai ","Fei ","Yao ","Ba ","Qi ","Ni ","Biao ","Yin ","Lai ","Xi ","Jian ","Qiang ","Kun ","Yan ","Guo ","Zong ","Mi ","Chang ","Yi ","Zhi ","Zheng ","Ya ","Meng ","Cai ","Cu ","She ","Kari ","Cen ","Luo ","Hu ","Zong ","Ji ","Wei ","Feng ","Wo ","Yuan ","Xing ","Zhu ","Mao ","Wei ","Yuan ","Xian ","Tuan ","Ya ","Nao ","Xie ","Jia ","Hou ","Bian ","You ","You ","Mei ","Zha ","Yao ","Sun ","Bo ","Ming ","Hua ","Yuan ","Sou ","Ma ","Yuan ","Dai ","Yu ","Shi ","Hao ","[?] ","Yi ","Zhen ","Chuang ","Hao ","Man ","Jing ","Jiang ","Mu ","Zhang ","Chan ","Ao ","Ao ","Hao ","Cui ","Fen ","Jue ","Bi ","Bi ","Huang ","Pu ","Lin ","Yu ","Tong ","Yao ","Liao ","Shuo ","Xiao ","Swu ","Ton ","Xi ","Ge ","Juan ","Du ","Hui ","Kuai ","Xian ","Xie ","Ta ","Xian ","Xun ","Ning ","Pin ","Huo ","Nou ","Meng ","Lie ","Nao ","Guang ","Shou ","Lu ","Ta ","Xian ","Mi ","Rang ","Huan ","Nao ","Luo ","Xian ","Qi ","Jue ","Xuan ","Miao ","Zi ","Lu ","Lu ","Yu ","Su ","Wang ","Qiu ","Ga ","Ding ","Le ","Ba ","Ji ","Hong ","Di ","Quan ","Gan ","Jiu ","Yu ","Ji ","Yu ","Yang ","Ma ","Gong ","Wu ","Fu ","Wen ","Jie ","Ya ","Fen ","Bian ","Beng ","Yue ","Jue ","Yun ","Jue ","Wan ","Jian ","Mei ","Dan ","Pi ","Wei ","Huan ","Xian ","Qiang ","Ling ","Dai ","Yi ","An ","Ping ","Dian ","Fu ","Xuan ","Xi ","Bo ","Ci ","Gou ","Jia ","Shao ","Po ","Ci ","Ke ","Ran ","Sheng ","Shen ","Yi ","Zu ","Jia ","Min ","Shan ","Liu ","Bi ","Zhen ","Zhen ","Jue ","Fa ","Long ","Jin ","Jiao ","Jian ","Li ","Guang ","Xian ","Zhou ","Gong ","Yan ","Xiu ","Yang ","Xu ","Luo ","Su ","Zhu ","Qin ","Ken ","Xun ","Bao ","Er ","Xiang ","Yao ","Xia ","Heng ","Gui ","Chong ","Xu ","Ban ","Pei ","[?] ","Dang ","Ei ","Hun ","Wen ","E ","Cheng ","Ti ","Wu ","Wu ","Cheng ","Jun ","Mei ","Bei ","Ting ","Xian ","Chuo "]});var X1=w((Fwe,U1)=>{U1.exports=["Han ","Xuan ","Yan ","Qiu ","Quan ","Lang ","Li ","Xiu ","Fu ","Liu ","Ye ","Xi ","Ling ","Li ","Jin ","Lian ","Suo ","Chiisai ","[?] ","Wan ","Dian ","Pin ","Zhan ","Cui ","Min ","Yu ","Ju ","Chen ","Lai ","Wen ","Sheng ","Wei ","Dian ","Chu ","Zhuo ","Pei ","Cheng ","Hu ","Qi ","E ","Kun ","Chang ","Qi ","Beng ","Wan ","Lu ","Cong ","Guan ","Yan ","Diao ","Bei ","Lin ","Qin ","Pi ","Pa ","Que ","Zhuo ","Qin ","Fa ","[?] ","Qiong ","Du ","Jie ","Hun ","Yu ","Mao ","Mei ","Chun ","Xuan ","Ti ","Xing ","Dai ","Rou ","Min ","Zhen ","Wei ","Ruan ","Huan ","Jie ","Chuan ","Jian ","Zhuan ","Yang ","Lian ","Quan ","Xia ","Duan ","Yuan ","Ye ","Nao ","Hu ","Ying ","Yu ","Huang ","Rui ","Se ","Liu ","Shi ","Rong ","Suo ","Yao ","Wen ","Wu ","Jin ","Jin ","Ying ","Ma ","Tao ","Liu ","Tang ","Li ","Lang ","Gui ","Zhen ","Qiang ","Cuo ","Jue ","Zhao ","Yao ","Ai ","Bin ","Tu ","Chang ","Kun ","Zhuan ","Cong ","Jin ","Yi ","Cui ","Cong ","Qi ","Li ","Ying ","Suo ","Qiu ","Xuan ","Ao ","Lian ","Man ","Zhang ","Yin ","[?] ","Ying ","Zhi ","Lu ","Wu ","Deng ","Xiou ","Zeng ","Xun ","Qu ","Dang ","Lin ","Liao ","Qiong ","Su ","Huang ","Gui ","Pu ","Jing ","Fan ","Jin ","Liu ","Ji ","[?] ","Jing ","Ai ","Bi ","Can ","Qu ","Zao ","Dang ","Jiao ","Gun ","Tan ","Hui ","Huan ","Se ","Sui ","Tian ","[?] ","Yu ","Jin ","Lu ","Bin ","Shou ","Wen ","Zui ","Lan ","Xi ","Ji ","Xuan ","Ruan ","Huo ","Gai ","Lei ","Du ","Li ","Zhi ","Rou ","Li ","Zan ","Qiong ","Zhe ","Gui ","Sui ","La ","Long ","Lu ","Li ","Zan ","Lan ","Ying ","Mi ","Xiang ","Xi ","Guan ","Dao ","Zan ","Huan ","Gua ","Bo ","Die ","Bao ","Hu ","Zhi ","Piao ","Ban ","Rang ","Li ","Wa ","Dekaguramu ","Jiang ","Qian ","Fan ","Pen ","Fang ","Dan ","Weng ","Ou ","Deshiguramu ","Miriguramu ","Thon ","Hu ","Ling ","Yi ","Ping ","Ci ","Hekutogura ","Juan ","Chang ","Chi ","Sarake ","Dang ","Meng ","Pou "]});var z1=w((Mwe,G1)=>{G1.exports=["Zhui ","Ping ","Bian ","Zhou ","Zhen ","Senchigura ","Ci ","Ying ","Qi ","Xian ","Lou ","Di ","Ou ","Meng ","Zhuan ","Peng ","Lin ","Zeng ","Wu ","Pi ","Dan ","Weng ","Ying ","Yan ","Gan ","Dai ","Shen ","Tian ","Tian ","Han ","Chang ","Sheng ","Qing ","Sheng ","Chan ","Chan ","Rui ","Sheng ","Su ","Sen ","Yong ","Shuai ","Lu ","Fu ","Yong ","Beng ","Feng ","Ning ","Tian ","You ","Jia ","Shen ","Zha ","Dian ","Fu ","Nan ","Dian ","Ping ","Ting ","Hua ","Ting ","Quan ","Zi ","Meng ","Bi ","Qi ","Liu ","Xun ","Liu ","Chang ","Mu ","Yun ","Fan ","Fu ","Geng ","Tian ","Jie ","Jie ","Quan ","Wei ","Fu ","Tian ","Mu ","Tap ","Pan ","Jiang ","Wa ","Da ","Nan ","Liu ","Ben ","Zhen ","Chu ","Mu ","Mu ","Ce ","Cen ","Gai ","Bi ","Da ","Zhi ","Lue ","Qi ","Lue ","Pan ","Kesa ","Fan ","Hua ","Yu ","Yu ","Mu ","Jun ","Yi ","Liu ","Yu ","Die ","Chou ","Hua ","Dang ","Chuo ","Ji ","Wan ","Jiang ","Sheng ","Chang ","Tuan ","Lei ","Ji ","Cha ","Liu ","Tatamu ","Tuan ","Lin ","Jiang ","Jiang ","Chou ","Bo ","Die ","Die ","Pi ","Nie ","Dan ","Shu ","Shu ","Zhi ","Yi ","Chuang ","Nai ","Ding ","Bi ","Jie ","Liao ","Gong ","Ge ","Jiu ","Zhou ","Xia ","Shan ","Xu ","Nue ","Li ","Yang ","Chen ","You ","Ba ","Jie ","Jue ","Zhi ","Xia ","Cui ","Bi ","Yi ","Li ","Zong ","Chuang ","Feng ","Zhu ","Pao ","Pi ","Gan ","Ke ","Ci ","Xie ","Qi ","Dan ","Zhen ","Fa ","Zhi ","Teng ","Ju ","Ji ","Fei ","Qu ","Dian ","Jia ","Xian ","Cha ","Bing ","Ni ","Zheng ","Yong ","Jing ","Quan ","Chong ","Tong ","Yi ","Kai ","Wei ","Hui ","Duo ","Yang ","Chi ","Zhi ","Hen ","Ya ","Mei ","Dou ","Jing ","Xiao ","Tong ","Tu ","Mang ","Pi ","Xiao ","Suan ","Pu ","Li ","Zhi ","Cuo ","Duo ","Wu ","Sha ","Lao ","Shou ","Huan ","Xian ","Yi ","Peng ","Zhang ","Guan ","Tan ","Fei ","Ma ","Lin ","Chi ","Ji ","Dian ","An ","Chi ","Bi ","Bei ","Min ","Gu ","Dui ","E ","Wei "]});var Q1=w((jwe,K1)=>{K1.exports=["Yu ","Cui ","Ya ","Zhu ","Cu ","Dan ","Shen ","Zhung ","Ji ","Yu ","Hou ","Feng ","La ","Yang ","Shen ","Tu ","Yu ","Gua ","Wen ","Huan ","Ku ","Jia ","Yin ","Yi ","Lu ","Sao ","Jue ","Chi ","Xi ","Guan ","Yi ","Wen ","Ji ","Chuang ","Ban ","Lei ","Liu ","Chai ","Shou ","Nue ","Dian ","Da ","Pie ","Tan ","Zhang ","Biao ","Shen ","Cu ","Luo ","Yi ","Zong ","Chou ","Zhang ","Zhai ","Sou ","Suo ","Que ","Diao ","Lou ","Lu ","Mo ","Jin ","Yin ","Ying ","Huang ","Fu ","Liao ","Long ","Qiao ","Liu ","Lao ","Xian ","Fei ","Dan ","Yin ","He ","Yan ","Ban ","Xian ","Guan ","Guai ","Nong ","Yu ","Wei ","Yi ","Yong ","Pi ","Lei ","Li ","Shu ","Dan ","Lin ","Dian ","Lin ","Lai ","Pie ","Ji ","Chi ","Yang ","Xian ","Jie ","Zheng ","[?] ","Li ","Huo ","Lai ","Shaku ","Dian ","Xian ","Ying ","Yin ","Qu ","Yong ","Tan ","Dian ","Luo ","Luan ","Luan ","Bo ","[?] ","Gui ","Po ","Fa ","Deng ","Fa ","Bai ","Bai ","Qie ","Bi ","Zao ","Zao ","Mao ","De ","Pa ","Jie ","Huang ","Gui ","Ci ","Ling ","Gao ","Mo ","Ji ","Jiao ","Peng ","Gao ","Ai ","E ","Hao ","Han ","Bi ","Wan ","Chou ","Qian ","Xi ","Ai ","Jiong ","Hao ","Huang ","Hao ","Ze ","Cui ","Hao ","Xiao ","Ye ","Po ","Hao ","Jiao ","Ai ","Xing ","Huang ","Li ","Piao ","He ","Jiao ","Pi ","Gan ","Pao ","Zhou ","Jun ","Qiu ","Cun ","Que ","Zha ","Gu ","Jun ","Jun ","Zhou ","Zha ","Gu ","Zhan ","Du ","Min ","Qi ","Ying ","Yu ","Bei ","Zhao ","Zhong ","Pen ","He ","Ying ","He ","Yi ","Bo ","Wan ","He ","Ang ","Zhan ","Yan ","Jian ","He ","Yu ","Kui ","Fan ","Gai ","Dao ","Pan ","Fu ","Qiu ","Sheng ","Dao ","Lu ","Zhan ","Meng ","Li ","Jin ","Xu ","Jian ","Pan ","Guan ","An ","Lu ","Shu ","Zhou ","Dang ","An ","Gu ","Li ","Mu ","Cheng ","Gan ","Xu ","Mang ","Mang ","Zhi ","Qi ","Ruan ","Tian ","Xiang ","Dun ","Xin ","Xi ","Pan ","Feng ","Dun ","Min "]});var eA=w((Owe,V1)=>{V1.exports=["Ming ","Sheng ","Shi ","Yun ","Mian ","Pan ","Fang ","Miao ","Dan ","Mei ","Mao ","Kan ","Xian ","Ou ","Shi ","Yang ","Zheng ","Yao ","Shen ","Huo ","Da ","Zhen ","Kuang ","Ju ","Shen ","Chi ","Sheng ","Mei ","Mo ","Zhu ","Zhen ","Zhen ","Mian ","Di ","Yuan ","Die ","Yi ","Zi ","Zi ","Chao ","Zha ","Xuan ","Bing ","Mi ","Long ","Sui ","Dong ","Mi ","Die ","Yi ","Er ","Ming ","Xuan ","Chi ","Kuang ","Juan ","Mou ","Zhen ","Tiao ","Yang ","Yan ","Mo ","Zhong ","Mai ","Zhao ","Zheng ","Mei ","Jun ","Shao ","Han ","Huan ","Di ","Cheng ","Cuo ","Juan ","E ","Wan ","Xian ","Xi ","Kun ","Lai ","Jian ","Shan ","Tian ","Hun ","Wan ","Ling ","Shi ","Qiong ","Lie ","Yai ","Jing ","Zheng ","Li ","Lai ","Sui ","Juan ","Shui ","Sui ","Du ","Bi ","Bi ","Mu ","Hun ","Ni ","Lu ","Yi ","Jie ","Cai ","Zhou ","Yu ","Hun ","Ma ","Xia ","Xing ","Xi ","Gun ","Cai ","Chun ","Jian ","Mei ","Du ","Hou ","Xuan ","Ti ","Kui ","Gao ","Rui ","Mou ","Xu ","Fa ","Wen ","Miao ","Chou ","Kui ","Mi ","Weng ","Kou ","Dang ","Chen ","Ke ","Sou ","Xia ","Qiong ","Mao ","Ming ","Man ","Shui ","Ze ","Zhang ","Yi ","Diao ","Ou ","Mo ","Shun ","Cong ","Lou ","Chi ","Man ","Piao ","Cheng ","Ji ","Meng ","[?] ","Run ","Pie ","Xi ","Qiao ","Pu ","Zhu ","Deng ","Shen ","Shun ","Liao ","Che ","Xian ","Kan ","Ye ","Xu ","Tong ","Mou ","Lin ","Kui ","Xian ","Ye ","Ai ","Hui ","Zhan ","Jian ","Gu ","Zhao ","Qu ","Wei ","Chou ","Sao ","Ning ","Xun ","Yao ","Huo ","Meng ","Mian ","Bin ","Mian ","Li ","Kuang ","Jue ","Xuan ","Mian ","Huo ","Lu ","Meng ","Long ","Guan ","Man ","Xi ","Chu ","Tang ","Kan ","Zhu ","Mao ","Jin ","Lin ","Yu ","Shuo ","Ce ","Jue ","Shi ","Yi ","Shen ","Zhi ","Hou ","Shen ","Ying ","Ju ","Zhou ","Jiao ","Cuo ","Duan ","Ai ","Jiao ","Zeng ","Huo ","Bai ","Shi ","Ding ","Qi ","Ji ","Zi ","Gan ","Wu ","Tuo ","Ku ","Qiang ","Xi ","Fan ","Kuang "]});var iA=w((Awe,tA)=>{tA.exports=["Dang ","Ma ","Sha ","Dan ","Jue ","Li ","Fu ","Min ","Nuo ","Huo ","Kang ","Zhi ","Qi ","Kan ","Jie ","Fen ","E ","Ya ","Pi ","Zhe ","Yan ","Sui ","Zhuan ","Che ","Dun ","Pan ","Yan ","[?] ","Feng ","Fa ","Mo ","Zha ","Qu ","Yu ","Luo ","Tuo ","Tuo ","Di ","Zhai ","Zhen ","Ai ","Fei ","Mu ","Zhu ","Li ","Bian ","Nu ","Ping ","Peng ","Ling ","Pao ","Le ","Po ","Bo ","Po ","Shen ","Za ","Nuo ","Li ","Long ","Tong ","[?] ","Li ","Aragane ","Chu ","Keng ","Quan ","Zhu ","Kuang ","Huo ","E ","Nao ","Jia ","Lu ","Wei ","Ai ","Luo ","Ken ","Xing ","Yan ","Tong ","Peng ","Xi ","[?] ","Hong ","Shuo ","Xia ","Qiao ","[?] ","Wei ","Qiao ","[?] ","Keng ","Xiao ","Que ","Chan ","Lang ","Hong ","Yu ","Xiao ","Xia ","Mang ","Long ","Iong ","Che ","Che ","E ","Liu ","Ying ","Mang ","Que ","Yan ","Sha ","Kun ","Yu ","[?] ","Kaki ","Lu ","Chen ","Jian ","Nue ","Song ","Zhuo ","Keng ","Peng ","Yan ","Zhui ","Kong ","Ceng ","Qi ","Zong ","Qing ","Lin ","Jun ","Bo ","Ding ","Min ","Diao ","Jian ","He ","Lu ","Ai ","Sui ","Que ","Ling ","Bei ","Yin ","Dui ","Wu ","Qi ","Lun ","Wan ","Dian ","Gang ","Pei ","Qi ","Chen ","Ruan ","Yan ","Die ","Ding ","Du ","Tuo ","Jie ","Ying ","Bian ","Ke ","Bi ","Wei ","Shuo ","Zhen ","Duan ","Xia ","Dang ","Ti ","Nao ","Peng ","Jian ","Di ","Tan ","Cha ","Seki ","Qi ","[?] ","Feng ","Xuan ","Que ","Que ","Ma ","Gong ","Nian ","Su ","E ","Ci ","Liu ","Si ","Tang ","Bang ","Hua ","Pi ","Wei ","Sang ","Lei ","Cuo ","Zhen ","Xia ","Qi ","Lian ","Pan ","Wei ","Yun ","Dui ","Zhe ","Ke ","La ","[?] ","Qing ","Gun ","Zhuan ","Chan ","Qi ","Ao ","Peng ","Lu ","Lu ","Kan ","Qiang ","Chen ","Yin ","Lei ","Biao ","Qi ","Mo ","Qi ","Cui ","Zong ","Qing ","Chuo ","[?] ","Ji ","Shan ","Lao ","Qu ","Zeng ","Deng ","Jian ","Xi ","Lin ","Ding ","Dian ","Huang ","Pan ","Za ","Qiao ","Di ","Li "]});var rA=w((Nwe,nA)=>{nA.exports=["Tani ","Jiao ","[?] ","Zhang ","Qiao ","Dun ","Xian ","Yu ","Zhui ","He ","Huo ","Zhai ","Lei ","Ke ","Chu ","Ji ","Que ","Dang ","Yi ","Jiang ","Pi ","Pi ","Yu ","Pin ","Qi ","Ai ","Kai ","Jian ","Yu ","Ruan ","Meng ","Pao ","Ci ","[?] ","[?] ","Mie ","Ca ","Xian ","Kuang ","Lei ","Lei ","Zhi ","Li ","Li ","Fan ","Que ","Pao ","Ying ","Li ","Long ","Long ","Mo ","Bo ","Shuang ","Guan ","Lan ","Zan ","Yan ","Shi ","Shi ","Li ","Reng ","She ","Yue ","Si ","Qi ","Ta ","Ma ","Xie ","Xian ","Xian ","Zhi ","Qi ","Zhi ","Beng ","Dui ","Zhong ","[?] ","Yi ","Shi ","You ","Zhi ","Tiao ","Fu ","Fu ","Mi ","Zu ","Zhi ","Suan ","Mei ","Zuo ","Qu ","Hu ","Zhu ","Shen ","Sui ","Ci ","Chai ","Mi ","Lu ","Yu ","Xiang ","Wu ","Tiao ","Piao ","Zhu ","Gui ","Xia ","Zhi ","Ji ","Gao ","Zhen ","Gao ","Shui ","Jin ","Chen ","Gai ","Kun ","Di ","Dao ","Huo ","Tao ","Qi ","Gu ","Guan ","Zui ","Ling ","Lu ","Bing ","Jin ","Dao ","Zhi ","Lu ","Shan ","Bei ","Zhe ","Hui ","You ","Xi ","Yin ","Zi ","Huo ","Zhen ","Fu ","Yuan ","Wu ","Xian ","Yang ","Ti ","Yi ","Mei ","Si ","Di ","[?] ","Zhuo ","Zhen ","Yong ","Ji ","Gao ","Tang ","Si ","Ma ","Ta ","[?] ","Xuan ","Qi ","Yu ","Xi ","Ji ","Si ","Chan ","Tan ","Kuai ","Sui ","Li ","Nong ","Ni ","Dao ","Li ","Rang ","Yue ","Ti ","Zan ","Lei ","Rou ","Yu ","Yu ","Chi ","Xie ","Qin ","He ","Tu ","Xiu ","Si ","Ren ","Tu ","Zi ","Cha ","Gan ","Yi ","Xian ","Bing ","Nian ","Qiu ","Qiu ","Chong ","Fen ","Hao ","Yun ","Ke ","Miao ","Zhi ","Geng ","Bi ","Zhi ","Yu ","Mi ","Ku ","Ban ","Pi ","Ni ","Li ","You ","Zu ","Pi ","Ba ","Ling ","Mo ","Cheng ","Nian ","Qin ","Yang ","Zuo ","Zhi ","Zhi ","Shu ","Ju ","Zi ","Huo ","Ji ","Cheng ","Tong ","Zhi ","Huo ","He ","Yin ","Zi ","Zhi ","Jie ","Ren ","Du ","Yi ","Zhu ","Hui ","Nong ","Fu "]});var sA=w((Hwe,oA)=>{oA.exports=["Xi ","Kao ","Lang ","Fu ","Ze ","Shui ","Lu ","Kun ","Gan ","Geng ","Ti ","Cheng ","Tu ","Shao ","Shui ","Ya ","Lun ","Lu ","Gu ","Zuo ","Ren ","Zhun ","Bang ","Bai ","Ji ","Zhi ","Zhi ","Kun ","Leng ","Peng ","Ke ","Bing ","Chou ","Zu ","Yu ","Su ","Lue ","[?] ","Yi ","Xi ","Bian ","Ji ","Fu ","Bi ","Nuo ","Jie ","Zhong ","Zong ","Xu ","Cheng ","Dao ","Wen ","Lian ","Zi ","Yu ","Ji ","Xu ","Zhen ","Zhi ","Dao ","Jia ","Ji ","Gao ","Gao ","Gu ","Rong ","Sui ","You ","Ji ","Kang ","Mu ","Shan ","Men ","Zhi ","Ji ","Lu ","Su ","Ji ","Ying ","Wen ","Qiu ","Se ","[?] ","Yi ","Huang ","Qie ","Ji ","Sui ","Xiao ","Pu ","Jiao ","Zhuo ","Tong ","Sai ","Lu ","Sui ","Nong ","Se ","Hui ","Rang ","Nuo ","Yu ","Bin ","Ji ","Tui ","Wen ","Cheng ","Huo ","Gong ","Lu ","Biao ","[?] ","Rang ","Zhuo ","Li ","Zan ","Xue ","Wa ","Jiu ","Qiong ","Xi ","Qiong ","Kong ","Yu ","Sen ","Jing ","Yao ","Chuan ","Zhun ","Tu ","Lao ","Qie ","Zhai ","Yao ","Bian ","Bao ","Yao ","Bing ","Wa ","Zhu ","Jiao ","Qiao ","Diao ","Wu ","Gui ","Yao ","Zhi ","Chuang ","Yao ","Tiao ","Jiao ","Chuang ","Jiong ","Xiao ","Cheng ","Kou ","Cuan ","Wo ","Dan ","Ku ","Ke ","Zhui ","Xu ","Su ","Guan ","Kui ","Dou ","[?] ","Yin ","Wo ","Wa ","Ya ","Yu ","Ju ","Qiong ","Yao ","Yao ","Tiao ","Chao ","Yu ","Tian ","Diao ","Ju ","Liao ","Xi ","Wu ","Kui ","Chuang ","Zhao ","[?] ","Kuan ","Long ","Cheng ","Cui ","Piao ","Zao ","Cuan ","Qiao ","Qiong ","Dou ","Zao ","Long ","Qie ","Li ","Chu ","Shi ","Fou ","Qian ","Chu ","Hong ","Qi ","Qian ","Gong ","Shi ","Shu ","Miao ","Ju ","Zhan ","Zhu ","Ling ","Long ","Bing ","Jing ","Jing ","Zhang ","Yi ","Si ","Jun ","Hong ","Tong ","Song ","Jing ","Diao ","Yi ","Shu ","Jing ","Qu ","Jie ","Ping ","Duan ","Shao ","Zhuan ","Ceng ","Deng ","Cui ","Huai ","Jing ","Kan ","Jing ","Zhu ","Zhu ","Le ","Peng ","Yu ","Chi ","Gan "]});var lA=w((Bwe,aA)=>{aA.exports=["Mang ","Zhu ","Utsubo ","Du ","Ji ","Xiao ","Ba ","Suan ","Ji ","Zhen ","Zhao ","Sun ","Ya ","Zhui ","Yuan ","Hu ","Gang ","Xiao ","Cen ","Pi ","Bi ","Jian ","Yi ","Dong ","Shan ","Sheng ","Xia ","Di ","Zhu ","Na ","Chi ","Gu ","Li ","Qie ","Min ","Bao ","Tiao ","Si ","Fu ","Ce ","Ben ","Pei ","Da ","Zi ","Di ","Ling ","Ze ","Nu ","Fu ","Gou ","Fan ","Jia ","Ge ","Fan ","Shi ","Mao ","Po ","Sey ","Jian ","Qiong ","Long ","Souke ","Bian ","Luo ","Gui ","Qu ","Chi ","Yin ","Yao ","Xian ","Bi ","Qiong ","Gua ","Deng ","Jiao ","Jin ","Quan ","Sun ","Ru ","Fa ","Kuang ","Zhu ","Tong ","Ji ","Da ","Xing ","Ce ","Zhong ","Kou ","Lai ","Bi ","Shai ","Dang ","Zheng ","Ce ","Fu ","Yun ","Tu ","Pa ","Li ","Lang ","Ju ","Guan ","Jian ","Han ","Tong ","Xia ","Zhi ","Cheng ","Suan ","Shi ","Zhu ","Zuo ","Xiao ","Shao ","Ting ","Ce ","Yan ","Gao ","Kuai ","Gan ","Chou ","Kago ","Gang ","Yun ","O ","Qian ","Xiao ","Jian ","Pu ","Lai ","Zou ","Bi ","Bi ","Bi ","Ge ","Chi ","Guai ","Yu ","Jian ","Zhao ","Gu ","Chi ","Zheng ","Jing ","Sha ","Zhou ","Lu ","Bo ","Ji ","Lin ","Suan ","Jun ","Fu ","Zha ","Gu ","Kong ","Qian ","Quan ","Jun ","Chui ","Guan ","Yuan ","Ce ","Ju ","Bo ","Ze ","Qie ","Tuo ","Luo ","Dan ","Xiao ","Ruo ","Jian ","Xuan ","Bian ","Sun ","Xiang ","Xian ","Ping ","Zhen ","Sheng ","Hu ","Shi ","Zhu ","Yue ","Chun ","Lu ","Wu ","Dong ","Xiao ","Ji ","Jie ","Huang ","Xing ","Mei ","Fan ","Chui ","Zhuan ","Pian ","Feng ","Zhu ","Hong ","Qie ","Hou ","Qiu ","Miao ","Qian ","[?] ","Kui ","Sik ","Lou ","Yun ","He ","Tang ","Yue ","Chou ","Gao ","Fei ","Ruo ","Zheng ","Gou ","Nie ","Qian ","Xiao ","Cuan ","Gong ","Pang ","Du ","Li ","Bi ","Zhuo ","Chu ","Shai ","Chi ","Zhu ","Qiang ","Long ","Lan ","Jian ","Bu ","Li ","Hui ","Bi ","Di ","Cong ","Yan ","Peng ","Sen ","Zhuan ","Pai ","Piao ","Dou ","Yu ","Mie ","Zhuan "]});var cA=w((qwe,uA)=>{uA.exports=["Ze ","Xi ","Guo ","Yi ","Hu ","Chan ","Kou ","Cu ","Ping ","Chou ","Ji ","Gui ","Su ","Lou ","Zha ","Lu ","Nian ","Suo ","Cuan ","Sasara ","Suo ","Le ","Duan ","Yana ","Xiao ","Bo ","Mi ","Si ","Dang ","Liao ","Dan ","Dian ","Fu ","Jian ","Min ","Kui ","Dai ","Qiao ","Deng ","Huang ","Sun ","Lao ","Zan ","Xiao ","Du ","Shi ","Zan ","[?] ","Pai ","Hata ","Pai ","Gan ","Ju ","Du ","Lu ","Yan ","Bo ","Dang ","Sai ","Ke ","Long ","Qian ","Lian ","Bo ","Zhou ","Lai ","[?] ","Lan ","Kui ","Yu ","Yue ","Hao ","Zhen ","Tai ","Ti ","Mi ","Chou ","Ji ","[?] ","Hata ","Teng ","Zhuan ","Zhou ","Fan ","Sou ","Zhou ","Kuji ","Zhuo ","Teng ","Lu ","Lu ","Jian ","Tuo ","Ying ","Yu ","Lai ","Long ","Shinshi ","Lian ","Lan ","Qian ","Yue ","Zhong ","Qu ","Lian ","Bian ","Duan ","Zuan ","Li ","Si ","Luo ","Ying ","Yue ","Zhuo ","Xu ","Mi ","Di ","Fan ","Shen ","Zhe ","Shen ","Nu ","Xie ","Lei ","Xian ","Zi ","Ni ","Cun ","[?] ","Qian ","Kume ","Bi ","Ban ","Wu ","Sha ","Kang ","Rou ","Fen ","Bi ","Cui ","[?] ","Li ","Chi ","Nukamiso ","Ro ","Ba ","Li ","Gan ","Ju ","Po ","Mo ","Cu ","Nian ","Zhou ","Li ","Su ","Tiao ","Li ","Qi ","Su ","Hong ","Tong ","Zi ","Ce ","Yue ","Zhou ","Lin ","Zhuang ","Bai ","[?] ","Fen ","Ji ","[?] ","Sukumo ","Liang ","Xian ","Fu ","Liang ","Can ","Geng ","Li ","Yue ","Lu ","Ju ","Qi ","Cui ","Bai ","Zhang ","Lin ","Zong ","Jing ","Guo ","Kouji ","San ","San ","Tang ","Bian ","Rou ","Mian ","Hou ","Xu ","Zong ","Hu ","Jian ","Zan ","Ci ","Li ","Xie ","Fu ","Ni ","Bei ","Gu ","Xiu ","Gao ","Tang ","Qiu ","Sukumo ","Cao ","Zhuang ","Tang ","Mi ","San ","Fen ","Zao ","Kang ","Jiang ","Mo ","San ","San ","Nuo ","Xi ","Liang ","Jiang ","Kuai ","Bo ","Huan ","[?] ","Zong ","Xian ","Nuo ","Tuan ","Nie ","Li ","Zuo ","Di ","Nie ","Tiao ","Lan ","Mi ","Jiao ","Jiu ","Xi ","Gong ","Zheng ","Jiu ","You "]});var hA=w((Wwe,dA)=>{dA.exports=["Ji ","Cha ","Zhou ","Xun ","Yue ","Hong ","Yu ","He ","Wan ","Ren ","Wen ","Wen ","Qiu ","Na ","Zi ","Tou ","Niu ","Fou ","Jie ","Shu ","Chun ","Pi ","Yin ","Sha ","Hong ","Zhi ","Ji ","Fen ","Yun ","Ren ","Dan ","Jin ","Su ","Fang ","Suo ","Cui ","Jiu ","Zha ","Kinu ","Jin ","Fu ","Zhi ","Ci ","Zi ","Chou ","Hong ","Zha ","Lei ","Xi ","Fu ","Xie ","Shen ","Bei ","Zhu ","Qu ","Ling ","Zhu ","Shao ","Gan ","Yang ","Fu ","Tuo ","Zhen ","Dai ","Zhuo ","Shi ","Zhong ","Xian ","Zu ","Jiong ","Ban ","Ju ","Mo ","Shu ","Zui ","Wata ","Jing ","Ren ","Heng ","Xie ","Jie ","Zhu ","Chou ","Gua ","Bai ","Jue ","Kuang ","Hu ","Ci ","Geng ","Geng ","Tao ","Xie ","Ku ","Jiao ","Quan ","Gai ","Luo ","Xuan ","Bing ","Xian ","Fu ","Gei ","Tong ","Rong ","Tiao ","Yin ","Lei ","Xie ","Quan ","Xu ","Lun ","Die ","Tong ","Si ","Jiang ","Xiang ","Hui ","Jue ","Zhi ","Jian ","Juan ","Chi ","Mian ","Zhen ","Lu ","Cheng ","Qiu ","Shu ","Bang ","Tong ","Xiao ","Wan ","Qin ","Geng ","Xiu ","Ti ","Xiu ","Xie ","Hong ","Xi ","Fu ","Ting ","Sui ","Dui ","Kun ","Fu ","Jing ","Hu ","Zhi ","Yan ","Jiong ","Feng ","Ji ","Sok ","Kase ","Zong ","Lin ","Duo ","Li ","Lu ","Liang ","Chou ","Quan ","Shao ","Qi ","Qi ","Zhun ","Qi ","Wan ","Qian ","Xian ","Shou ","Wei ","Qi ","Tao ","Wan ","Gang ","Wang ","Beng ","Zhui ","Cai ","Guo ","Cui ","Lun ","Liu ","Qi ","Zhan ","Bei ","Chuo ","Ling ","Mian ","Qi ","Qie ","Tan ","Zong ","Gun ","Zou ","Yi ","Zi ","Xing ","Liang ","Jin ","Fei ","Rui ","Min ","Yu ","Zong ","Fan ","Lu ","Xu ","Yingl ","Zhang ","Kasuri ","Xu ","Xiang ","Jian ","Ke ","Xian ","Ruan ","Mian ","Qi ","Duan ","Zhong ","Di ","Min ","Miao ","Yuan ","Xie ","Bao ","Si ","Qiu ","Bian ","Huan ","Geng ","Cong ","Mian ","Wei ","Fu ","Wei ","Yu ","Gou ","Miao ","Xie ","Lian ","Zong ","Bian ","Yun ","Yin ","Ti ","Gua ","Zhi ","Yun ","Cheng ","Chan ","Dai "]});var pA=w((Ywe,gA)=>{gA.exports=["Xia ","Yuan ","Zong ","Xu ","Nawa ","Odoshi ","Geng ","Sen ","Ying ","Jin ","Yi ","Zhui ","Ni ","Bang ","Gu ","Pan ","Zhou ","Jian ","Cuo ","Quan ","Shuang ","Yun ","Xia ","Shuai ","Xi ","Rong ","Tao ","Fu ","Yun ","Zhen ","Gao ","Ru ","Hu ","Zai ","Teng ","Xian ","Su ","Zhen ","Zong ","Tao ","Horo ","Cai ","Bi ","Feng ","Cu ","Li ","Suo ","Yin ","Xi ","Zong ","Lei ","Zhuan ","Qian ","Man ","Zhi ","Lu ","Mo ","Piao ","Lian ","Mi ","Xuan ","Zong ","Ji ","Shan ","Sui ","Fan ","Shuai ","Beng ","Yi ","Sao ","Mou ","Zhou ","Qiang ","Hun ","Sem ","Xi ","Jung ","Xiu ","Ran ","Xuan ","Hui ","Qiao ","Zeng ","Zuo ","Zhi ","Shan ","San ","Lin ","Yu ","Fan ","Liao ","Chuo ","Zun ","Jian ","Rao ","Chan ","Rui ","Xiu ","Hui ","Hua ","Zuan ","Xi ","Qiang ","Un ","Da ","Sheng ","Hui ","Xi ","Se ","Jian ","Jiang ","Huan ","Zao ","Cong ","Jie ","Jiao ","Bo ","Chan ","Yi ","Nao ","Sui ","Yi ","Shai ","Xu ","Ji ","Bin ","Qian ","Lan ","Pu ","Xun ","Zuan ","Qi ","Peng ","Li ","Mo ","Lei ","Xie ","Zuan ","Kuang ","You ","Xu ","Lei ","Xian ","Chan ","Kou ","Lu ","Chan ","Ying ","Cai ","Xiang ","Xian ","Zui ","Zuan ","Luo ","Xi ","Dao ","Lan ","Lei ","Lian ","Si ","Jiu ","Yu ","Hong ","Zhou ","Xian ","He ","Yue ","Ji ","Wan ","Kuang ","Ji ","Ren ","Wei ","Yun ","Hong ","Chun ","Pi ","Sha ","Gang ","Na ","Ren ","Zong ","Lun ","Fen ","Zhi ","Wen ","Fang ","Zhu ","Yin ","Niu ","Shu ","Xian ","Gan ","Xie ","Fu ","Lian ","Zu ","Shen ","Xi ","Zhi ","Zhong ","Zhou ","Ban ","Fu ","Zhuo ","Shao ","Yi ","Jing ","Dai ","Bang ","Rong ","Jie ","Ku ","Rao ","Die ","Heng ","Hui ","Gei ","Xuan ","Jiang ","Luo ","Jue ","Jiao ","Tong ","Geng ","Xiao ","Juan ","Xiu ","Xi ","Sui ","Tao ","Ji ","Ti ","Ji ","Xu ","Ling ","[?] ","Xu ","Qi ","Fei ","Chuo ","Zhang ","Gun ","Sheng ","Wei ","Mian ","Shou ","Beng ","Chou ","Tao ","Liu ","Quan ","Zong ","Zhan ","Wan ","Lu "]});var mA=w((Zwe,fA)=>{fA.exports=["Zhui ","Zi ","Ke ","Xiang ","Jian ","Mian ","Lan ","Ti ","Miao ","Qi ","Yun ","Hui ","Si ","Duo ","Duan ","Bian ","Xian ","Gou ","Zhui ","Huan ","Di ","Lu ","Bian ","Min ","Yuan ","Jin ","Fu ","Ru ","Zhen ","Feng ","Shuai ","Gao ","Chan ","Li ","Yi ","Jian ","Bin ","Piao ","Man ","Lei ","Ying ","Suo ","Mou ","Sao ","Xie ","Liao ","Shan ","Zeng ","Jiang ","Qian ","Zao ","Huan ","Jiao ","Zuan ","Fou ","Xie ","Gang ","Fou ","Que ","Fou ","Kaakeru ","Bo ","Ping ","Hou ","[?] ","Gang ","Ying ","Ying ","Qing ","Xia ","Guan ","Zun ","Tan ","Chang ","Qi ","Weng ","Ying ","Lei ","Tan ","Lu ","Guan ","Wang ","Wang ","Gang ","Wang ","Han ","[?] ","Luo ","Fu ","Mi ","Fa ","Gu ","Zhu ","Ju ","Mao ","Gu ","Min ","Gang ","Ba ","Gua ","Ti ","Juan ","Fu ","Lin ","Yan ","Zhao ","Zui ","Gua ","Zhuo ","Yu ","Zhi ","An ","Fa ","Nan ","Shu ","Si ","Pi ","Ma ","Liu ","Ba ","Fa ","Li ","Chao ","Wei ","Bi ","Ji ","Zeng ","Tong ","Liu ","Ji ","Juan ","Mi ","Zhao ","Luo ","Pi ","Ji ","Ji ","Luan ","Yang ","Mie ","Qiang ","Ta ","Mei ","Yang ","You ","You ","Fen ","Ba ","Gao ","Yang ","Gu ","Qiang ","Zang ","Gao ","Ling ","Yi ","Zhu ","Di ","Xiu ","Qian ","Yi ","Xian ","Rong ","Qun ","Qun ","Qian ","Huan ","Zui ","Xian ","Yi ","Yashinau ","Qiang ","Xian ","Yu ","Geng ","Jie ","Tang ","Yuan ","Xi ","Fan ","Shan ","Fen ","Shan ","Lian ","Lei ","Geng ","Nou ","Qiang ","Chan ","Yu ","Gong ","Yi ","Chong ","Weng ","Fen ","Hong ","Chi ","Chi ","Cui ","Fu ","Xia ","Pen ","Yi ","La ","Yi ","Pi ","Ling ","Liu ","Zhi ","Qu ","Xi ","Xie ","Xiang ","Xi ","Xi ","Qi ","Qiao ","Hui ","Hui ","Xiao ","Se ","Hong ","Jiang ","Di ","Cui ","Fei ","Tao ","Sha ","Chi ","Zhu ","Jian ","Xuan ","Shi ","Pian ","Zong ","Wan ","Hui ","Hou ","He ","He ","Han ","Ao ","Piao ","Yi ","Lian ","Qu ","[?] ","Lin ","Pen ","Qiao ","Ao ","Fan ","Yi ","Hui ","Xuan ","Dao "]});var yA=w((Jwe,bA)=>{bA.exports=["Yao ","Lao ","[?] ","Kao ","Mao ","Zhe ","Qi ","Gou ","Gou ","Gou ","Die ","Die ","Er ","Shua ","Ruan ","Er ","Nai ","Zhuan ","Lei ","Ting ","Zi ","Geng ","Chao ","Hao ","Yun ","Pa ","Pi ","Chi ","Si ","Chu ","Jia ","Ju ","He ","Chu ","Lao ","Lun ","Ji ","Tang ","Ou ","Lou ","Nou ","Gou ","Pang ","Ze ","Lou ","Ji ","Lao ","Huo ","You ","Mo ","Huai ","Er ","Zhe ","Ting ","Ye ","Da ","Song ","Qin ","Yun ","Chi ","Dan ","Dan ","Hong ","Geng ","Zhi ","[?] ","Nie ","Dan ","Zhen ","Che ","Ling ","Zheng ","You ","Wa ","Liao ","Long ","Zhi ","Ning ","Tiao ","Er ","Ya ","Die ","Gua ","[?] ","Lian ","Hao ","Sheng ","Lie ","Pin ","Jing ","Ju ","Bi ","Di ","Guo ","Wen ","Xu ","Ping ","Cong ","Shikato ","[?] ","Ting ","Yu ","Cong ","Kui ","Tsuraneru ","Kui ","Cong ","Lian ","Weng ","Kui ","Lian ","Lian ","Cong ","Ao ","Sheng ","Song ","Ting ","Kui ","Nie ","Zhi ","Dan ","Ning ","Qie ","Ji ","Ting ","Ting ","Long ","Yu ","Yu ","Zhao ","Si ","Su ","Yi ","Su ","Si ","Zhao ","Zhao ","Rou ","Yi ","Le ","Ji ","Qiu ","Ken ","Cao ","Ge ","Di ","Huan ","Huang ","Yi ","Ren ","Xiao ","Ru ","Zhou ","Yuan ","Du ","Gang ","Rong ","Gan ","Cha ","Wo ","Chang ","Gu ","Zhi ","Han ","Fu ","Fei ","Fen ","Pei ","Pang ","Jian ","Fang ","Zhun ","You ","Na ","Hang ","Ken ","Ran ","Gong ","Yu ","Wen ","Yao ","Jin ","Pi ","Qian ","Xi ","Xi ","Fei ","Ken ","Jing ","Tai ","Shen ","Zhong ","Zhang ","Xie ","Shen ","Wei ","Zhou ","Die ","Dan ","Fei ","Ba ","Bo ","Qu ","Tian ","Bei ","Gua ","Tai ","Zi ","Ku ","Zhi ","Ni ","Ping ","Zi ","Fu ","Pang ","Zhen ","Xian ","Zuo ","Pei ","Jia ","Sheng ","Zhi ","Bao ","Mu ","Qu ","Hu ","Ke ","Yi ","Yin ","Xu ","Yang ","Long ","Dong ","Ka ","Lu ","Jing ","Nu ","Yan ","Pang ","Kua ","Yi ","Guang ","Gai ","Ge ","Dong ","Zhi ","Xiao ","Xiong ","Xiong ","Er ","E ","Xing ","Pian ","Neng ","Zi ","Gui "]});var wA=w(($we,vA)=>{vA.exports=["Cheng ","Tiao ","Zhi ","Cui ","Mei ","Xie ","Cui ","Xie ","Mo ","Mai ","Ji ","Obiyaakasu ","[?] ","Kuai ","Sa ","Zang ","Qi ","Nao ","Mi ","Nong ","Luan ","Wan ","Bo ","Wen ","Guan ","Qiu ","Jiao ","Jing ","Rou ","Heng ","Cuo ","Lie ","Shan ","Ting ","Mei ","Chun ","Shen ","Xie ","De ","Zui ","Cu ","Xiu ","Xin ","Tuo ","Pao ","Cheng ","Nei ","Fu ","Dou ","Tuo ","Niao ","Noy ","Pi ","Gu ","Gua ","Li ","Lian ","Zhang ","Cui ","Jie ","Liang ","Zhou ","Pi ","Biao ","Lun ","Pian ","Guo ","Kui ","Chui ","Dan ","Tian ","Nei ","Jing ","Jie ","La ","Yi ","An ","Ren ","Shen ","Chuo ","Fu ","Fu ","Ju ","Fei ","Qiang ","Wan ","Dong ","Pi ","Guo ","Zong ","Ding ","Wu ","Mei ","Ruan ","Zhuan ","Zhi ","Cou ","Gua ","Ou ","Di ","An ","Xing ","Nao ","Yu ","Chuan ","Nan ","Yun ","Zhong ","Rou ","E ","Sai ","Tu ","Yao ","Jian ","Wei ","Jiao ","Yu ","Jia ","Duan ","Bi ","Chang ","Fu ","Xian ","Ni ","Mian ","Wa ","Teng ","Tui ","Bang ","Qian ","Lu ","Wa ","Sou ","Tang ","Su ","Zhui ","Ge ","Yi ","Bo ","Liao ","Ji ","Pi ","Xie ","Gao ","Lu ","Bin ","Ou ","Chang ","Lu ","Guo ","Pang ","Chuai ","Piao ","Jiang ","Fu ","Tang ","Mo ","Xi ","Zhuan ","Lu ","Jiao ","Ying ","Lu ","Zhi ","Tara ","Chun ","Lian ","Tong ","Peng ","Ni ","Zha ","Liao ","Cui ","Gui ","Xiao ","Teng ","Fan ","Zhi ","Jiao ","Shan ","Wu ","Cui ","Run ","Xiang ","Sui ","Fen ","Ying ","Tan ","Zhua ","Dan ","Kuai ","Nong ","Tun ","Lian ","Bi ","Yong ","Jue ","Chu ","Yi ","Juan ","La ","Lian ","Sao ","Tun ","Gu ","Qi ","Cui ","Bin ","Xun ","Ru ","Huo ","Zang ","Xian ","Biao ","Xing ","Kuan ","La ","Yan ","Lu ","Huo ","Zang ","Luo ","Qu ","Zang ","Luan ","Ni ","Zang ","Chen ","Qian ","Wo ","Guang ","Zang ","Lin ","Guang ","Zi ","Jiao ","Nie ","Chou ","Ji ","Gao ","Chou ","Mian ","Nie ","Zhi ","Zhi ","Ge ","Jian ","Die ","Zhi ","Xiu ","Tai ","Zhen ","Jiu ","Xian ","Yu ","Cha "]});var CA=w((Uwe,xA)=>{xA.exports=["Yao ","Yu ","Chong ","Xi ","Xi ","Jiu ","Yu ","Yu ","Xing ","Ju ","Jiu ","Xin ","She ","She ","Yadoru ","Jiu ","Shi ","Tan ","Shu ","Shi ","Tian ","Dan ","Pu ","Pu ","Guan ","Hua ","Tan ","Chuan ","Shun ","Xia ","Wu ","Zhou ","Dao ","Gang ","Shan ","Yi ","[?] ","Pa ","Tai ","Fan ","Ban ","Chuan ","Hang ","Fang ","Ban ","Que ","Hesaki ","Zhong ","Jian ","Cang ","Ling ","Zhu ","Ze ","Duo ","Bo ","Xian ","Ge ","Chuan ","Jia ","Lu ","Hong ","Pang ","Xi ","[?] ","Fu ","Zao ","Feng ","Li ","Shao ","Yu ","Lang ","Ting ","[?] ","Wei ","Bo ","Meng ","Nian ","Ju ","Huang ","Shou ","Zong ","Bian ","Mao ","Die ","[?] ","Bang ","Cha ","Yi ","Sao ","Cang ","Cao ","Lou ","Dai ","Sori ","Yao ","Tong ","Yofune ","Dang ","Tan ","Lu ","Yi ","Jie ","Jian ","Huo ","Meng ","Qi ","Lu ","Lu ","Chan ","Shuang ","Gen ","Liang ","Jian ","Jian ","Se ","Yan ","Fu ","Ping ","Yan ","Yan ","Cao ","Cao ","Yi ","Le ","Ting ","Qiu ","Ai ","Nai ","Tiao ","Jiao ","Jie ","Peng ","Wan ","Yi ","Chai ","Mian ","Mie ","Gan ","Qian ","Yu ","Yu ","Shuo ","Qiong ","Tu ","Xia ","Qi ","Mang ","Zi ","Hui ","Sui ","Zhi ","Xiang ","Bi ","Fu ","Tun ","Wei ","Wu ","Zhi ","Qi ","Shan ","Wen ","Qian ","Ren ","Fou ","Kou ","Jie ","Lu ","Xu ","Ji ","Qin ","Qi ","Yuan ","Fen ","Ba ","Rui ","Xin ","Ji ","Hua ","Hua ","Fang ","Wu ","Jue ","Gou ","Zhi ","Yun ","Qin ","Ao ","Chu ","Mao ","Ya ","Fei ","Reng ","Hang ","Cong ","Yin ","You ","Bian ","Yi ","Susa ","Wei ","Li ","Pi ","E ","Xian ","Chang ","Cang ","Meng ","Su ","Yi ","Yuan ","Ran ","Ling ","Tai ","Tiao ","Di ","Miao ","Qiong ","Li ","Yong ","Ke ","Mu ","Pei ","Bao ","Gou ","Min ","Yi ","Yi ","Ju ","Pi ","Ruo ","Ku ","Zhu ","Ni ","Bo ","Bing ","Shan ","Qiu ","Yao ","Xian ","Ben ","Hong ","Ying ","Zha ","Dong ","Ju ","Die ","Nie ","Gan ","Hu ","Ping ","Mei ","Fu ","Sheng ","Gu ","Bi ","Wei "]});var DA=w((Xwe,SA)=>{SA.exports=["Fu ","Zhuo ","Mao ","Fan ","Qie ","Mao ","Mao ","Ba ","Zi ","Mo ","Zi ","Di ","Chi ","Ji ","Jing ","Long ","[?] ","Niao ","[?] ","Xue ","Ying ","Qiong ","Ge ","Ming ","Li ","Rong ","Yin ","Gen ","Qian ","Chai ","Chen ","Yu ","Xiu ","Zi ","Lie ","Wu ","Ji ","Kui ","Ce ","Chong ","Ci ","Gou ","Guang ","Mang ","Chi ","Jiao ","Jiao ","Fu ","Yu ","Zhu ","Zi ","Jiang ","Hui ","Yin ","Cha ","Fa ","Rong ","Ru ","Chong ","Mang ","Tong ","Zhong ","[?] ","Zhu ","Xun ","Huan ","Kua ","Quan ","Gai ","Da ","Jing ","Xing ","Quan ","Cao ","Jing ","Er ","An ","Shou ","Chi ","Ren ","Jian ","Ti ","Huang ","Ping ","Li ","Jin ","Lao ","Shu ","Zhuang ","Da ","Jia ","Rao ","Bi ","Ze ","Qiao ","Hui ","Qi ","Dang ","[?] ","Rong ","Hun ","Ying ","Luo ","Ying ","Xun ","Jin ","Sun ","Yin ","Mai ","Hong ","Zhou ","Yao ","Du ","Wei ","Chu ","Dou ","Fu ","Ren ","Yin ","He ","Bi ","Bu ","Yun ","Di ","Tu ","Sui ","Sui ","Cheng ","Chen ","Wu ","Bie ","Xi ","Geng ","Li ","Fu ","Zhu ","Mo ","Li ","Zhuang ","Ji ","Duo ","Qiu ","Sha ","Suo ","Chen ","Feng ","Ju ","Mei ","Meng ","Xing ","Jing ","Che ","Xin ","Jun ","Yan ","Ting ","Diao ","Cuo ","Wan ","Han ","You ","Cuo ","Jia ","Wang ","You ","Niu ","Shao ","Xian ","Lang ","Fu ","E ","Mo ","Wen ","Jie ","Nan ","Mu ","Kan ","Lai ","Lian ","Shi ","Wo ","Usagi ","Lian ","Huo ","You ","Ying ","Ying ","Nuc ","Chun ","Mang ","Mang ","Ci ","Wan ","Jing ","Di ","Qu ","Dong ","Jian ","Zou ","Gu ","La ","Lu ","Ju ","Wei ","Jun ","Nie ","Kun ","He ","Pu ","Zi ","Gao ","Guo ","Fu ","Lun ","Chang ","Chou ","Song ","Chui ","Zhan ","Men ","Cai ","Ba ","Li ","Tu ","Bo ","Han ","Bao ","Qin ","Juan ","Xi ","Qin ","Di ","Jie ","Pu ","Dang ","Jin ","Zhao ","Tai ","Geng ","Hua ","Gu ","Ling ","Fei ","Jin ","An ","Wang ","Beng ","Zhou ","Yan ","Ju ","Jian ","Lin ","Tan ","Shu ","Tian ","Dao "]});var kA=w((Gwe,TA)=>{TA.exports=["Hu ","Qi ","He ","Cui ","Tao ","Chun ","Bei ","Chang ","Huan ","Fei ","Lai ","Qi ","Meng ","Ping ","Wei ","Dan ","Sha ","Huan ","Yan ","Yi ","Tiao ","Qi ","Wan ","Ce ","Nai ","Kutabireru ","Tuo ","Jiu ","Tie ","Luo ","[?] ","[?] ","Meng ","[?] ","Yaji ","[?] ","Ying ","Ying ","Ying ","Xiao ","Sa ","Qiu ","Ke ","Xiang ","Wan ","Yu ","Yu ","Fu ","Lian ","Xuan ","Yuan ","Nan ","Ze ","Wo ","Chun ","Xiao ","Yu ","Pian ","Mao ","An ","E ","Luo ","Ying ","Huo ","Gua ","Jiang ","Mian ","Zuo ","Zuo ","Ju ","Bao ","Rou ","Xi ","Xie ","An ","Qu ","Jian ","Fu ","Lu ","Jing ","Pen ","Feng ","Hong ","Hong ","Hou ","Yan ","Tu ","Zhu ","Zi ","Xiang ","Shen ","Ge ","Jie ","Jing ","Mi ","Huang ","Shen ","Pu ","Gai ","Dong ","Zhou ","Qian ","Wei ","Bo ","Wei ","Pa ","Ji ","Hu ","Zang ","Jia ","Duan ","Yao ","Jun ","Cong ","Quan ","Wei ","Xian ","Kui ","Ting ","Hun ","Xi ","Shi ","Qi ","Lan ","Zong ","Yao ","Yuan ","Mei ","Yun ","Shu ","Di ","Zhuan ","Guan ","Sukumo ","Xue ","Chan ","Kai ","Kui ","[?] ","Jiang ","Lou ","Wei ","Pai ","[?] ","Sou ","Yin ","Shi ","Chun ","Shi ","Yun ","Zhen ","Lang ","Nu ","Meng ","He ","Que ","Suan ","Yuan ","Li ","Ju ","Xi ","Pang ","Chu ","Xu ","Tu ","Liu ","Wo ","Zhen ","Qian ","Zu ","Po ","Cuo ","Yuan ","Chu ","Yu ","Kuai ","Pan ","Pu ","Pu ","Na ","Shuo ","Xi ","Fen ","Yun ","Zheng ","Jian ","Ji ","Ruo ","Cang ","En ","Mi ","Hao ","Sun ","Zhen ","Ming ","Sou ","Xu ","Liu ","Xi ","Gu ","Lang ","Rong ","Weng ","Gai ","Cuo ","Shi ","Tang ","Luo ","Ru ","Suo ","Xian ","Bei ","Yao ","Gui ","Bi ","Zong ","Gun ","Za ","Xiu ","Ce ","Hai ","Lan ","[?] ","Ji ","Li ","Can ","Lang ","Yu ","[?] ","Ying ","Mo ","Diao ","Tiao ","Mao ","Tong ","Zhu ","Peng ","An ","Lian ","Cong ","Xi ","Ping ","Qiu ","Jin ","Chun ","Jie ","Wei ","Tui ","Cao ","Yu ","Yi ","Ji ","Liao ","Bi ","Lu ","Su "]});var RA=w((zwe,PA)=>{PA.exports=["Bu ","Zhang ","Luo ","Jiang ","Man ","Yan ","Ling ","Ji ","Piao ","Gun ","Han ","Di ","Su ","Lu ","She ","Shang ","Di ","Mie ","Xun ","Man ","Bo ","Di ","Cuo ","Zhe ","Sen ","Xuan ","Wei ","Hu ","Ao ","Mi ","Lou ","Cu ","Zhong ","Cai ","Po ","Jiang ","Mi ","Cong ","Niao ","Hui ","Jun ","Yin ","Jian ","Yan ","Shu ","Yin ","Kui ","Chen ","Hu ","Sha ","Kou ","Qian ","Ma ","Zang ","Sonoko ","Qiang ","Dou ","Lian ","Lin ","Kou ","Ai ","Bi ","Li ","Wei ","Ji ","Xun ","Sheng ","Fan ","Meng ","Ou ","Chan ","Dian ","Xun ","Jiao ","Rui ","Rui ","Lei ","Yu ","Qiao ","Chu ","Hua ","Jian ","Mai ","Yun ","Bao ","You ","Qu ","Lu ","Rao ","Hui ","E ","Teng ","Fei ","Jue ","Zui ","Fa ","Ru ","Fen ","Kui ","Shun ","Rui ","Ya ","Xu ","Fu ","Jue ","Dang ","Wu ","Tong ","Si ","Xiao ","Xi ","Long ","Yun ","[?] ","Qi ","Jian ","Yun ","Sun ","Ling ","Yu ","Xia ","Yong ","Ji ","Hong ","Si ","Nong ","Lei ","Xuan ","Yun ","Yu ","Xi ","Hao ","Bo ","Hao ","Ai ","Wei ","Hui ","Wei ","Ji ","Ci ","Xiang ","Luan ","Mie ","Yi ","Leng ","Jiang ","Can ","Shen ","Qiang ","Lian ","Ke ","Yuan ","Da ","Ti ","Tang ","Xie ","Bi ","Zhan ","Sun ","Lian ","Fan ","Ding ","Jie ","Gu ","Xie ","Shu ","Jian ","Kao ","Hong ","Sa ","Xin ","Xun ","Yao ","Hie ","Sou ","Shu ","Xun ","Dui ","Pin ","Wei ","Neng ","Chou ","Mai ","Ru ","Piao ","Tai ","Qi ","Zao ","Chen ","Zhen ","Er ","Ni ","Ying ","Gao ","Cong ","Xiao ","Qi ","Fa ","Jian ","Xu ","Kui ","Jie ","Bian ","Diao ","Mi ","Lan ","Jin ","Cang ","Miao ","Qiong ","Qie ","Xian ","[?] ","Ou ","Xian ","Su ","Lu ","Yi ","Xu ","Xie ","Li ","Yi ","La ","Lei ","Xiao ","Di ","Zhi ","Bei ","Teng ","Yao ","Mo ","Huan ","Piao ","Fan ","Sou ","Tan ","Tui ","Qiong ","Qiao ","Wei ","Liu ","Hui ","[?] ","Gao ","Yun ","[?] ","Li ","Shu ","Chu ","Ai ","Lin ","Zao ","Xuan ","Chen ","Lai ","Huo "]});var EA=w((Kwe,_A)=>{_A.exports=["Tuo ","Wu ","Rui ","Rui ","Qi ","Heng ","Lu ","Su ","Tui ","Mang ","Yun ","Pin ","Yu ","Xun ","Ji ","Jiong ","Xian ","Mo ","Hagi ","Su ","Jiong ","[?] ","Nie ","Bo ","Rang ","Yi ","Xian ","Yu ","Ju ","Lian ","Lian ","Yin ","Qiang ","Ying ","Long ","Tong ","Wei ","Yue ","Ling ","Qu ","Yao ","Fan ","Mi ","Lan ","Kui ","Lan ","Ji ","Dang ","Katsura ","Lei ","Lei ","Hua ","Feng ","Zhi ","Wei ","Kui ","Zhan ","Huai ","Li ","Ji ","Mi ","Lei ","Huai ","Luo ","Ji ","Kui ","Lu ","Jian ","San ","[?] ","Lei ","Quan ","Xiao ","Yi ","Luan ","Men ","Bie ","Hu ","Hu ","Lu ","Nue ","Lu ","Si ","Xiao ","Qian ","Chu ","Hu ","Xu ","Cuo ","Fu ","Xu ","Xu ","Lu ","Hu ","Yu ","Hao ","Jiao ","Ju ","Guo ","Bao ","Yan ","Zhan ","Zhan ","Kui ","Ban ","Xi ","Shu ","Chong ","Qiu ","Diao ","Ji ","Qiu ","Cheng ","Shi ","[?] ","Di ","Zhe ","She ","Yu ","Gan ","Zi ","Hong ","Hui ","Meng ","Ge ","Sui ","Xia ","Chai ","Shi ","Yi ","Ma ","Xiang ","Fang ","E ","Pa ","Chi ","Qian ","Wen ","Wen ","Rui ","Bang ","Bi ","Yue ","Yue ","Jun ","Qi ","Ran ","Yin ","Qi ","Tian ","Yuan ","Jue ","Hui ","Qin ","Qi ","Zhong ","Ya ","Ci ","Mu ","Wang ","Fen ","Fen ","Hang ","Gong ","Zao ","Fu ","Ran ","Jie ","Fu ","Chi ","Dou ","Piao ","Xian ","Ni ","Te ","Qiu ","You ","Zha ","Ping ","Chi ","You ","He ","Han ","Ju ","Li ","Fu ","Ran ","Zha ","Gou ","Pi ","Bo ","Xian ","Zhu ","Diao ","Bie ","Bing ","Gu ","Ran ","Qu ","She ","Tie ","Ling ","Gu ","Dan ","Gu ","Ying ","Li ","Cheng ","Qu ","Mou ","Ge ","Ci ","Hui ","Hui ","Mang ","Fu ","Yang ","Wa ","Lie ","Zhu ","Yi ","Xian ","Kuo ","Jiao ","Li ","Yi ","Ping ","Ji ","Ha ","She ","Yi ","Wang ","Mo ","Qiong ","Qie ","Gui ","Gong ","Zhi ","Man ","Ebi ","Zhi ","Jia ","Rao ","Si ","Qi ","Xing ","Lie ","Qiu ","Shao ","Yong ","Jia ","Shui ","Che ","Bai ","E ","Han "]});var LA=w((Qwe,IA)=>{IA.exports=["Shu ","Xuan ","Feng ","Shen ","Zhen ","Fu ","Xian ","Zhe ","Wu ","Fu ","Li ","Lang ","Bi ","Chu ","Yuan ","You ","Jie ","Dan ","Yan ","Ting ","Dian ","Shui ","Hui ","Gua ","Zhi ","Song ","Fei ","Ju ","Mi ","Qi ","Qi ","Yu ","Jun ","Zha ","Meng ","Qiang ","Si ","Xi ","Lun ","Li ","Die ","Tiao ","Tao ","Kun ","Gan ","Han ","Yu ","Bang ","Fei ","Pi ","Wei ","Dun ","Yi ","Yuan ","Su ","Quan ","Qian ","Rui ","Ni ","Qing ","Wei ","Liang ","Guo ","Wan ","Dong ","E ","Ban ","Di ","Wang ","Can ","Yang ","Ying ","Guo ","Chan ","[?] ","La ","Ke ","Ji ","He ","Ting ","Mai ","Xu ","Mian ","Yu ","Jie ","Shi ","Xuan ","Huang ","Yan ","Bian ","Rou ","Wei ","Fu ","Yuan ","Mei ","Wei ","Fu ","Ruan ","Xie ","You ","Qiu ","Mao ","Xia ","Ying ","Shi ","Chong ","Tang ","Zhu ","Zong ","Ti ","Fu ","Yuan ","Hui ","Meng ","La ","Du ","Hu ","Qiu ","Die ","Li ","Gua ","Yun ","Ju ","Nan ","Lou ","Qun ","Rong ","Ying ","Jiang ","[?] ","Lang ","Pang ","Si ","Xi ","Ci ","Xi ","Yuan ","Weng ","Lian ","Sou ","Ban ","Rong ","Rong ","Ji ","Wu ","Qiu ","Han ","Qin ","Yi ","Bi ","Hua ","Tang ","Yi ","Du ","Nai ","He ","Hu ","Hui ","Ma ","Ming ","Yi ","Wen ","Ying ","Teng ","Yu ","Cang ","So ","Ebi ","Man ","[?] ","Shang ","Zhe ","Cao ","Chi ","Di ","Ao ","Lu ","Wei ","Zhi ","Tang ","Chen ","Piao ","Qu ","Pi ","Yu ","Jian ","Luo ","Lou ","Qin ","Zhong ","Yin ","Jiang ","Shuai ","Wen ","Jiao ","Wan ","Zhi ","Zhe ","Ma ","Ma ","Guo ","Liu ","Mao ","Xi ","Cong ","Li ","Man ","Xiao ","Kamakiri ","Zhang ","Mang ","Xiang ","Mo ","Zui ","Si ","Qiu ","Te ","Zhi ","Peng ","Peng ","Jiao ","Qu ","Bie ","Liao ","Pan ","Gui ","Xi ","Ji ","Zhuan ","Huang ","Fei ","Lao ","Jue ","Jue ","Hui ","Yin ","Chan ","Jiao ","Shan ","Rao ","Xiao ","Mou ","Chong ","Xun ","Si ","[?] ","Cheng ","Dang ","Li ","Xie ","Shan ","Yi ","Jing ","Da ","Chan ","Qi "]});var MA=w((Vwe,FA)=>{FA.exports=["Ci ","Xiang ","She ","Luo ","Qin ","Ying ","Chai ","Li ","Ze ","Xuan ","Lian ","Zhu ","Ze ","Xie ","Mang ","Xie ","Qi ","Rong ","Jian ","Meng ","Hao ","Ruan ","Huo ","Zhuo ","Jie ","Bin ","He ","Mie ","Fan ","Lei ","Jie ","La ","Mi ","Li ","Chun ","Li ","Qiu ","Nie ","Lu ","Du ","Xiao ","Zhu ","Long ","Li ","Long ","Feng ","Ye ","Beng ","Shang ","Gu ","Juan ","Ying ","[?] ","Xi ","Can ","Qu ","Quan ","Du ","Can ","Man ","Jue ","Jie ","Zhu ","Zha ","Xie ","Huang ","Niu ","Pei ","Nu ","Xin ","Zhong ","Mo ","Er ","Ke ","Mie ","Xi ","Xing ","Yan ","Kan ","Yuan ","[?] ","Ling ","Xuan ","Shu ","Xian ","Tong ","Long ","Jie ","Xian ","Ya ","Hu ","Wei ","Dao ","Chong ","Wei ","Dao ","Zhun ","Heng ","Qu ","Yi ","Yi ","Bu ","Gan ","Yu ","Biao ","Cha ","Yi ","Shan ","Chen ","Fu ","Gun ","Fen ","Shuai ","Jie ","Na ","Zhong ","Dan ","Ri ","Zhong ","Zhong ","Xie ","Qi ","Xie ","Ran ","Zhi ","Ren ","Qin ","Jin ","Jun ","Yuan ","Mei ","Chai ","Ao ","Niao ","Hui ","Ran ","Jia ","Tuo ","Ling ","Dai ","Bao ","Pao ","Yao ","Zuo ","Bi ","Shao ","Tan ","Ju ","He ","Shu ","Xiu ","Zhen ","Yi ","Pa ","Bo ","Di ","Wa ","Fu ","Gun ","Zhi ","Zhi ","Ran ","Pan ","Yi ","Mao ","Tuo ","Na ","Kou ","Xian ","Chan ","Qu ","Bei ","Gun ","Xi ","Ne ","Bo ","Horo ","Fu ","Yi ","Chi ","Ku ","Ren ","Jiang ","Jia ","Cun ","Mo ","Jie ","Er ","Luo ","Ru ","Zhu ","Gui ","Yin ","Cai ","Lie ","Kamishimo ","Yuki ","Zhuang ","Dang ","[?] ","Kun ","Ken ","Niao ","Shu ","Jia ","Kun ","Cheng ","Li ","Juan ","Shen ","Pou ","Ge ","Yi ","Yu ","Zhen ","Liu ","Qiu ","Qun ","Ji ","Yi ","Bu ","Zhuang ","Shui ","Sha ","Qun ","Li ","Lian ","Lian ","Ku ","Jian ","Fou ","Chan ","Bi ","Gun ","Tao ","Yuan ","Ling ","Chi ","Chang ","Chou ","Duo ","Biao ","Liang ","Chang ","Pei ","Pei ","Fei ","Yuan ","Luo ","Guo ","Yan ","Du ","Xi ","Zhi ","Ju ","Qi "]});var OA=w((exe,jA)=>{jA.exports=["Ji ","Zhi ","Gua ","Ken ","Che ","Ti ","Ti ","Fu ","Chong ","Xie ","Bian ","Die ","Kun ","Duan ","Xiu ","Xiu ","He ","Yuan ","Bao ","Bao ","Fu ","Yu ","Tuan ","Yan ","Hui ","Bei ","Chu ","Lu ","Ena ","Hitoe ","Yun ","Da ","Gou ","Da ","Huai ","Rong ","Yuan ","Ru ","Nai ","Jiong ","Suo ","Ban ","Tun ","Chi ","Sang ","Niao ","Ying ","Jie ","Qian ","Huai ","Ku ","Lian ","Bao ","Li ","Zhe ","Shi ","Lu ","Yi ","Die ","Xie ","Xian ","Wei ","Biao ","Cao ","Ji ","Jiang ","Sen ","Bao ","Xiang ","Chihaya ","Pu ","Jian ","Zhuan ","Jian ","Zui ","Ji ","Dan ","Za ","Fan ","Bo ","Xiang ","Xin ","Bie ","Rao ","Man ","Lan ","Ao ","Duo ","Gui ","Cao ","Sui ","Nong ","Chan ","Lian ","Bi ","Jin ","Dang ","Shu ","Tan ","Bi ","Lan ","Pu ","Ru ","Zhi ","[?] ","Shu ","Wa ","Shi ","Bai ","Xie ","Bo ","Chen ","Lai ","Long ","Xi ","Xian ","Lan ","Zhe ","Dai ","Tasuki ","Zan ","Shi ","Jian ","Pan ","Yi ","Ran ","Ya ","Xi ","Xi ","Yao ","Feng ","Tan ","[?] ","Biao ","Fu ","Ba ","He ","Ji ","Ji ","Jian ","Guan ","Bian ","Yan ","Gui ","Jue ","Pian ","Mao ","Mi ","Mi ","Mie ","Shi ","Si ","Zhan ","Luo ","Jue ","Mi ","Tiao ","Lian ","Yao ","Zhi ","Jun ","Xi ","Shan ","Wei ","Xi ","Tian ","Yu ","Lan ","E ","Du ","Qin ","Pang ","Ji ","Ming ","Ying ","Gou ","Qu ","Zhan ","Jin ","Guan ","Deng ","Jian ","Luo ","Qu ","Jian ","Wei ","Jue ","Qu ","Luo ","Lan ","Shen ","Di ","Guan ","Jian ","Guan ","Yan ","Gui ","Mi ","Shi ","Zhan ","Lan ","Jue ","Ji ","Xi ","Di ","Tian ","Yu ","Gou ","Jin ","Qu ","Jiao ","Jiu ","Jin ","Cu ","Jue ","Zhi ","Chao ","Ji ","Gu ","Dan ","Zui ","Di ","Shang ","Hua ","Quan ","Ge ","Chi ","Jie ","Gui ","Gong ","Hong ","Jie ","Hun ","Qiu ","Xing ","Su ","Ni ","Ji ","Lu ","Zhi ","Zha ","Bi ","Xing ","Hu ","Shang ","Gong ","Zhi ","Xue ","Chu ","Xi ","Yi ","Lu ","Jue ","Xi ","Yan ","Xi "]});var NA=w((txe,AA)=>{AA.exports=["Yan ","Yan ","Ding ","Fu ","Qiu ","Qiu ","Jiao ","Hong ","Ji ","Fan ","Xun ","Diao ","Hong ","Cha ","Tao ","Xu ","Jie ","Yi ","Ren ","Xun ","Yin ","Shan ","Qi ","Tuo ","Ji ","Xun ","Yin ","E ","Fen ","Ya ","Yao ","Song ","Shen ","Yin ","Xin ","Jue ","Xiao ","Ne ","Chen ","You ","Zhi ","Xiong ","Fang ","Xin ","Chao ","She ","Xian ","Sha ","Tun ","Xu ","Yi ","Yi ","Su ","Chi ","He ","Shen ","He ","Xu ","Zhen ","Zhu ","Zheng ","Gou ","Zi ","Zi ","Zhan ","Gu ","Fu ","Quan ","Die ","Ling ","Di ","Yang ","Li ","Nao ","Pan ","Zhou ","Gan ","Yi ","Ju ","Ao ","Zha ","Tuo ","Yi ","Qu ","Zhao ","Ping ","Bi ","Xiong ","Qu ","Ba ","Da ","Zu ","Tao ","Zhu ","Ci ","Zhe ","Yong ","Xu ","Xun ","Yi ","Huang ","He ","Shi ","Cha ","Jiao ","Shi ","Hen ","Cha ","Gou ","Gui ","Quan ","Hui ","Jie ","Hua ","Gai ","Xiang ","Wei ","Shen ","Chou ","Tong ","Mi ","Zhan ","Ming ","E ","Hui ","Yan ","Xiong ","Gua ","Er ","Beng ","Tiao ","Chi ","Lei ","Zhu ","Kuang ","Kua ","Wu ","Yu ","Teng ","Ji ","Zhi ","Ren ","Su ","Lang ","E ","Kuang ","E ","Shi ","Ting ","Dan ","Bo ","Chan ","You ","Heng ","Qiao ","Qin ","Shua ","An ","Yu ","Xiao ","Cheng ","Jie ","Xian ","Wu ","Wu ","Gao ","Song ","Pu ","Hui ","Jing ","Shuo ","Zhen ","Shuo ","Du ","Yasashi ","Chang ","Shui ","Jie ","Ke ","Qu ","Cong ","Xiao ","Sui ","Wang ","Xuan ","Fei ","Chi ","Ta ","Yi ","Na ","Yin ","Diao ","Pi ","Chuo ","Chan ","Chen ","Zhun ","Ji ","Qi ","Tan ","Zhui ","Wei ","Ju ","Qing ","Jian ","Zheng ","Ze ","Zou ","Qian ","Zhuo ","Liang ","Jian ","Zhu ","Hao ","Lun ","Shen ","Biao ","Huai ","Pian ","Yu ","Die ","Xu ","Pian ","Shi ","Xuan ","Shi ","Hun ","Hua ","E ","Zhong ","Di ","Xie ","Fu ","Pu ","Ting ","Jian ","Qi ","Yu ","Zi ","Chuan ","Xi ","Hui ","Yin ","An ","Xian ","Nan ","Chen ","Feng ","Zhu ","Yang ","Yan ","Heng ","Xuan ","Ge ","Nuo ","Qi "]});var BA=w((ixe,HA)=>{HA.exports=["Mou ","Ye ","Wei ","[?] ","Teng ","Zou ","Shan ","Jian ","Bo ","Ku ","Huang ","Huo ","Ge ","Ying ","Mi ","Xiao ","Mi ","Xi ","Qiang ","Chen ","Nue ","Ti ","Su ","Bang ","Chi ","Qian ","Shi ","Jiang ","Yuan ","Xie ","Xue ","Tao ","Yao ","Yao ","[?] ","Yu ","Biao ","Cong ","Qing ","Li ","Mo ","Mo ","Shang ","Zhe ","Miu ","Jian ","Ze ","Jie ","Lian ","Lou ","Can ","Ou ","Guan ","Xi ","Zhuo ","Ao ","Ao ","Jin ","Zhe ","Yi ","Hu ","Jiang ","Man ","Chao ","Han ","Hua ","Chan ","Xu ","Zeng ","Se ","Xi ","She ","Dui ","Zheng ","Nao ","Lan ","E ","Ying ","Jue ","Ji ","Zun ","Jiao ","Bo ","Hui ","Zhuan ","Mu ","Zen ","Zha ","Shi ","Qiao ","Tan ","Zen ","Pu ","Sheng ","Xuan ","Zao ","Tan ","Dang ","Sui ","Qian ","Ji ","Jiao ","Jing ","Lian ","Nou ","Yi ","Ai ","Zhan ","Pi ","Hui ","Hua ","Yi ","Yi ","Shan ","Rang ","Nou ","Qian ","Zhui ","Ta ","Hu ","Zhou ","Hao ","Ye ","Ying ","Jian ","Yu ","Jian ","Hui ","Du ","Zhe ","Xuan ","Zan ","Lei ","Shen ","Wei ","Chan ","Li ","Yi ","Bian ","Zhe ","Yan ","E ","Chou ","Wei ","Chou ","Yao ","Chan ","Rang ","Yin ","Lan ","Chen ","Huo ","Zhe ","Huan ","Zan ","Yi ","Dang ","Zhan ","Yan ","Du ","Yan ","Ji ","Ding ","Fu ","Ren ","Ji ","Jie ","Hong ","Tao ","Rang ","Shan ","Qi ","Tuo ","Xun ","Yi ","Xun ","Ji ","Ren ","Jiang ","Hui ","Ou ","Ju ","Ya ","Ne ","Xu ","E ","Lun ","Xiong ","Song ","Feng ","She ","Fang ","Jue ","Zheng ","Gu ","He ","Ping ","Zu ","Shi ","Xiong ","Zha ","Su ","Zhen ","Di ","Zou ","Ci ","Qu ","Zhao ","Bi ","Yi ","Yi ","Kuang ","Lei ","Shi ","Gua ","Shi ","Jie ","Hui ","Cheng ","Zhu ","Shen ","Hua ","Dan ","Gou ","Quan ","Gui ","Xun ","Yi ","Zheng ","Gai ","Xiang ","Cha ","Hun ","Xu ","Zhou ","Jie ","Wu ","Yu ","Qiao ","Wu ","Gao ","You ","Hui ","Kuang ","Shuo ","Song ","Ai ","Qing ","Zhu ","Zou ","Nuo ","Du ","Zhuo ","Fei ","Ke ","Wei "]});var WA=w((nxe,qA)=>{qA.exports=["Yu ","Shui ","Shen ","Diao ","Chan ","Liang ","Zhun ","Sui ","Tan ","Shen ","Yi ","Mou ","Chen ","Die ","Huang ","Jian ","Xie ","Nue ","Ye ","Wei ","E ","Yu ","Xuan ","Chan ","Zi ","An ","Yan ","Di ","Mi ","Pian ","Xu ","Mo ","Dang ","Su ","Xie ","Yao ","Bang ","Shi ","Qian ","Mi ","Jin ","Man ","Zhe ","Jian ","Miu ","Tan ","Zen ","Qiao ","Lan ","Pu ","Jue ","Yan ","Qian ","Zhan ","Chen ","Gu ","Qian ","Hong ","Xia ","Jue ","Hong ","Han ","Hong ","Xi ","Xi ","Huo ","Liao ","Han ","Du ","Long ","Dou ","Jiang ","Qi ","Shi ","Li ","Deng ","Wan ","Bi ","Shu ","Xian ","Feng ","Zhi ","Zhi ","Yan ","Yan ","Shi ","Chu ","Hui ","Tun ","Yi ","Tun ","Yi ","Jian ","Ba ","Hou ","E ","Cu ","Xiang ","Huan ","Jian ","Ken ","Gai ","Qu ","Fu ","Xi ","Bin ","Hao ","Yu ","Zhu ","Jia ","[?] ","Xi ","Bo ","Wen ","Huan ","Bin ","Di ","Zong ","Fen ","Yi ","Zhi ","Bao ","Chai ","Han ","Pi ","Na ","Pi ","Gou ","Na ","You ","Diao ","Mo ","Si ","Xiu ","Huan ","Kun ","He ","He ","Mo ","Han ","Mao ","Li ","Ni ","Bi ","Yu ","Jia ","Tuan ","Mao ","Pi ","Xi ","E ","Ju ","Mo ","Chu ","Tan ","Huan ","Jue ","Bei ","Zhen ","Yuan ","Fu ","Cai ","Gong ","Te ","Yi ","Hang ","Wan ","Pin ","Huo ","Fan ","Tan ","Guan ","Ze ","Zhi ","Er ","Zhu ","Shi ","Bi ","Zi ","Er ","Gui ","Pian ","Bian ","Mai ","Dai ","Sheng ","Kuang ","Fei ","Tie ","Yi ","Chi ","Mao ","He ","Bi ","Lu ","Ren ","Hui ","Gai ","Pian ","Zi ","Jia ","Xu ","Zei ","Jiao ","Gai ","Zang ","Jian ","Ying ","Xun ","Zhen ","She ","Bin ","Bin ","Qiu ","She ","Chuan ","Zang ","Zhou ","Lai ","Zan ","Si ","Chen ","Shang ","Tian ","Pei ","Geng ","Xian ","Mai ","Jian ","Sui ","Fu ","Tan ","Cong ","Cong ","Zhi ","Ji ","Zhang ","Du ","Jin ","Xiong ","Shun ","Yun ","Bao ","Zai ","Lai ","Feng ","Cang ","Ji ","Sheng ","Ai ","Zhuan ","Fu ","Gou ","Sai ","Ze ","Liao "]});var ZA=w((rxe,YA)=>{YA.exports=["Wei ","Bai ","Chen ","Zhuan ","Zhi ","Zhui ","Biao ","Yun ","Zeng ","Tan ","Zan ","Yan ","[?] ","Shan ","Wan ","Ying ","Jin ","Gan ","Xian ","Zang ","Bi ","Du ","Shu ","Yan ","[?] ","Xuan ","Long ","Gan ","Zang ","Bei ","Zhen ","Fu ","Yuan ","Gong ","Cai ","Ze ","Xian ","Bai ","Zhang ","Huo ","Zhi ","Fan ","Tan ","Pin ","Bian ","Gou ","Zhu ","Guan ","Er ","Jian ","Bi ","Shi ","Tie ","Gui ","Kuang ","Dai ","Mao ","Fei ","He ","Yi ","Zei ","Zhi ","Jia ","Hui ","Zi ","Ren ","Lu ","Zang ","Zi ","Gai ","Jin ","Qiu ","Zhen ","Lai ","She ","Fu ","Du ","Ji ","Shu ","Shang ","Si ","Bi ","Zhou ","Geng ","Pei ","Tan ","Lai ","Feng ","Zhui ","Fu ","Zhuan ","Sai ","Ze ","Yan ","Zan ","Yun ","Zeng ","Shan ","Ying ","Gan ","Chi ","Xi ","She ","Nan ","Xiong ","Xi ","Cheng ","He ","Cheng ","Zhe ","Xia ","Tang ","Zou ","Zou ","Li ","Jiu ","Fu ","Zhao ","Gan ","Qi ","Shan ","Qiong ","Qin ","Xian ","Ci ","Jue ","Qin ","Chi ","Ci ","Chen ","Chen ","Die ","Ju ","Chao ","Di ","Se ","Zhan ","Zhu ","Yue ","Qu ","Jie ","Chi ","Chu ","Gua ","Xue ","Ci ","Tiao ","Duo ","Lie ","Gan ","Suo ","Cu ","Xi ","Zhao ","Su ","Yin ","Ju ","Jian ","Que ","Tang ","Chuo ","Cui ","Lu ","Qu ","Dang ","Qiu ","Zi ","Ti ","Qu ","Chi ","Huang ","Qiao ","Qiao ","Yao ","Zao ","Ti ","[?] ","Zan ","Zan ","Zu ","Pa ","Bao ","Ku ","Ke ","Dun ","Jue ","Fu ","Chen ","Jian ","Fang ","Zhi ","Sa ","Yue ","Pa ","Qi ","Yue ","Qiang ","Tuo ","Tai ","Yi ","Nian ","Ling ","Mei ","Ba ","Die ","Ku ","Tuo ","Jia ","Ci ","Pao ","Qia ","Zhu ","Ju ","Die ","Zhi ","Fu ","Pan ","Ju ","Shan ","Bo ","Ni ","Ju ","Li ","Gen ","Yi ","Ji ","Dai ","Xian ","Jiao ","Duo ","Zhu ","Zhuan ","Kua ","Zhuai ","Gui ","Qiong ","Kui ","Xiang ","Chi ","Lu ","Beng ","Zhi ","Jia ","Tiao ","Cai ","Jian ","Ta ","Qiao ","Bi ","Xian ","Duo ","Ji ","Ju ","Ji ","Shu ","Tu "]});var $A=w((oxe,JA)=>{JA.exports=["Chu ","Jing ","Nie ","Xiao ","Bo ","Chi ","Qun ","Mou ","Shu ","Lang ","Yong ","Jiao ","Chou ","Qiao ","[?] ","Ta ","Jian ","Qi ","Wo ","Wei ","Zhuo ","Jie ","Ji ","Nie ","Ju ","Ju ","Lun ","Lu ","Leng ","Huai ","Ju ","Chi ","Wan ","Quan ","Ti ","Bo ","Zu ","Qie ","Ji ","Cu ","Zong ","Cai ","Zong ","Peng ","Zhi ","Zheng ","Dian ","Zhi ","Yu ","Duo ","Dun ","Chun ","Yong ","Zhong ","Di ","Zhe ","Chen ","Chuai ","Jian ","Gua ","Tang ","Ju ","Fu ","Zu ","Die ","Pian ","Rou ","Nuo ","Ti ","Cha ","Tui ","Jian ","Dao ","Cuo ","Xi ","Ta ","Qiang ","Zhan ","Dian ","Ti ","Ji ","Nie ","Man ","Liu ","Zhan ","Bi ","Chong ","Lu ","Liao ","Cu ","Tang ","Dai ","Suo ","Xi ","Kui ","Ji ","Zhi ","Qiang ","Di ","Man ","Zong ","Lian ","Beng ","Zao ","Nian ","Bie ","Tui ","Ju ","Deng ","Ceng ","Xian ","Fan ","Chu ","Zhong ","Dun ","Bo ","Cu ","Zu ","Jue ","Jue ","Lin ","Ta ","Qiao ","Qiao ","Pu ","Liao ","Dun ","Cuan ","Kuang ","Zao ","Ta ","Bi ","Bi ","Zhu ","Ju ","Chu ","Qiao ","Dun ","Chou ","Ji ","Wu ","Yue ","Nian ","Lin ","Lie ","Zhi ","Li ","Zhi ","Chan ","Chu ","Duan ","Wei ","Long ","Lin ","Xian ","Wei ","Zuan ","Lan ","Xie ","Rang ","Xie ","Nie ","Ta ","Qu ","Jie ","Cuan ","Zuan ","Xi ","Kui ","Jue ","Lin ","Shen ","Gong ","Dan ","Segare ","Qu ","Ti ","Duo ","Duo ","Gong ","Lang ","Nerau ","Luo ","Ai ","Ji ","Ju ","Tang ","Utsuke ","[?] ","Yan ","Shitsuke ","Kang ","Qu ","Lou ","Lao ","Tuo ","Zhi ","Yagate ","Ti ","Dao ","Yagate ","Yu ","Che ","Ya ","Gui ","Jun ","Wei ","Yue ","Xin ","Di ","Xuan ","Fan ","Ren ","Shan ","Qiang ","Shu ","Tun ","Chen ","Dai ","E ","Na ","Qi ","Mao ","Ruan ","Ren ","Fan ","Zhuan ","Hong ","Hu ","Qu ","Huang ","Di ","Ling ","Dai ","Ao ","Zhen ","Fan ","Kuang ","Ang ","Peng ","Bei ","Gu ","Ku ","Pao ","Zhu ","Rong ","E ","Ba ","Zhou ","Zhi ","Yao ","Ke ","Yi ","Qing ","Shi ","Ping "]});var XA=w((sxe,UA)=>{UA.exports=["Er ","Qiong ","Ju ","Jiao ","Guang ","Lu ","Kai ","Quan ","Zhou ","Zai ","Zhi ","She ","Liang ","Yu ","Shao ","You ","Huan ","Yun ","Zhe ","Wan ","Fu ","Qing ","Zhou ","Ni ","Ling ","Zhe ","Zhan ","Liang ","Zi ","Hui ","Wang ","Chuo ","Guo ","Kan ","Yi ","Peng ","Qian ","Gun ","Nian ","Pian ","Guan ","Bei ","Lun ","Pai ","Liang ","Ruan ","Rou ","Ji ","Yang ","Xian ","Chuan ","Cou ","Qun ","Ge ","You ","Hong ","Shu ","Fu ","Zi ","Fu ","Wen ","Ben ","Zhan ","Yu ","Wen ","Tao ","Gu ","Zhen ","Xia ","Yuan ","Lu ","Jiu ","Chao ","Zhuan ","Wei ","Hun ","Sori ","Che ","Jiao ","Zhan ","Pu ","Lao ","Fen ","Fan ","Lin ","Ge ","Se ","Kan ","Huan ","Yi ","Ji ","Dui ","Er ","Yu ","Xian ","Hong ","Lei ","Pei ","Li ","Li ","Lu ","Lin ","Che ","Ya ","Gui ","Xuan ","Di ","Ren ","Zhuan ","E ","Lun ","Ruan ","Hong ","Ku ","Ke ","Lu ","Zhou ","Zhi ","Yi ","Hu ","Zhen ","Li ","Yao ","Qing ","Shi ","Zai ","Zhi ","Jiao ","Zhou ","Quan ","Lu ","Jiao ","Zhe ","Fu ","Liang ","Nian ","Bei ","Hui ","Gun ","Wang ","Liang ","Chuo ","Zi ","Cou ","Fu ","Ji ","Wen ","Shu ","Pei ","Yuan ","Xia ","Zhan ","Lu ","Che ","Lin ","Xin ","Gu ","Ci ","Ci ","Pi ","Zui ","Bian ","La ","La ","Ci ","Xue ","Ban ","Bian ","Bian ","Bian ","[?] ","Bian ","Ban ","Ci ","Bian ","Bian ","Chen ","Ru ","Nong ","Nong ","Zhen ","Chuo ","Chuo ","Suberu ","Reng ","Bian ","Bian ","Sip ","Ip ","Liao ","Da ","Chan ","Gan ","Qian ","Yu ","Yu ","Qi ","Xun ","Yi ","Guo ","Mai ","Qi ","Za ","Wang ","Jia ","Zhun ","Ying ","Ti ","Yun ","Jin ","Hang ","Ya ","Fan ","Wu ","Da ","E ","Huan ","Zhe ","Totemo ","Jin ","Yuan ","Wei ","Lian ","Chi ","Che ","Ni ","Tiao ","Zhi ","Yi ","Jiong ","Jia ","Chen ","Dai ","Er ","Di ","Po ","Wang ","Die ","Ze ","Tao ","Shu ","Tuo ","Kep ","Jing ","Hui ","Tong ","You ","Mi ","Beng ","Ji ","Nai ","Yi ","Jie ","Zhui ","Lie ","Xun "]});var zA=w((axe,GA)=>{GA.exports=["Tui ","Song ","Gua ","Tao ","Pang ","Hou ","Ni ","Dun ","Jiong ","Xuan ","Xun ","Bu ","You ","Xiao ","Qiu ","Tou ","Zhu ","Qiu ","Di ","Di ","Tu ","Jing ","Ti ","Dou ","Yi ","Zhe ","Tong ","Guang ","Wu ","Shi ","Cheng ","Su ","Zao ","Qun ","Feng ","Lian ","Suo ","Hui ","Li ","Sako ","Lai ","Ben ","Cuo ","Jue ","Beng ","Huan ","Dai ","Lu ","You ","Zhou ","Jin ","Yu ","Chuo ","Kui ","Wei ","Ti ","Yi ","Da ","Yuan ","Luo ","Bi ","Nuo ","Yu ","Dang ","Sui ","Dun ","Sui ","Yan ","Chuan ","Chi ","Ti ","Yu ","Shi ","Zhen ","You ","Yun ","E ","Bian ","Guo ","E ","Xia ","Huang ","Qiu ","Dao ","Da ","Wei ","Appare ","Yi ","Gou ","Yao ","Chu ","Liu ","Xun ","Ta ","Di ","Chi ","Yuan ","Su ","Ta ","Qian ","[?] ","Yao ","Guan ","Zhang ","Ao ","Shi ","Ce ","Chi ","Su ","Zao ","Zhe ","Dun ","Di ","Lou ","Chi ","Cuo ","Lin ","Zun ","Rao ","Qian ","Xuan ","Yu ","Yi ","Wu ","Liao ","Ju ","Shi ","Bi ","Yao ","Mai ","Xie ","Sui ","Huan ","Zhan ","Teng ","Er ","Miao ","Bian ","Bian ","La ","Li ","Yuan ","Yao ","Luo ","Li ","Yi ","Ting ","Deng ","Qi ","Yong ","Shan ","Han ","Yu ","Mang ","Ru ","Qiong ","[?] ","Kuang ","Fu ","Kang ","Bin ","Fang ","Xing ","Na ","Xin ","Shen ","Bang ","Yuan ","Cun ","Huo ","Xie ","Bang ","Wu ","Ju ","You ","Han ","Tai ","Qiu ","Bi ","Pei ","Bing ","Shao ","Bei ","Wa ","Di ","Zou ","Ye ","Lin ","Kuang ","Gui ","Zhu ","Shi ","Ku ","Yu ","Gai ","Ge ","Xi ","Zhi ","Ji ","Xun ","Hou ","Xing ","Jiao ","Xi ","Gui ","Nuo ","Lang ","Jia ","Kuai ","Zheng ","Otoko ","Yun ","Yan ","Cheng ","Dou ","Chi ","Lu ","Fu ","Wu ","Fu ","Gao ","Hao ","Lang ","Jia ","Geng ","Jun ","Ying ","Bo ","Xi ","Bei ","Li ","Yun ","Bu ","Xiao ","Qi ","Pi ","Qing ","Guo ","Zhou ","Tan ","Zou ","Ping ","Lai ","Ni ","Chen ","You ","Bu ","Xiang ","Dan ","Ju ","Yong ","Qiao ","Yi ","Du ","Yan ","Mei "]});var QA=w((lxe,KA)=>{KA.exports=["Ruo ","Bei ","E ","Yu ","Juan ","Yu ","Yun ","Hou ","Kui ","Xiang ","Xiang ","Sou ","Tang ","Ming ","Xi ","Ru ","Chu ","Zi ","Zou ","Ju ","Wu ","Xiang ","Yun ","Hao ","Yong ","Bi ","Mo ","Chao ","Fu ","Liao ","Yin ","Zhuan ","Hu ","Qiao ","Yan ","Zhang ","Fan ","Qiao ","Xu ","Deng ","Bi ","Xin ","Bi ","Ceng ","Wei ","Zheng ","Mao ","Shan ","Lin ","Po ","Dan ","Meng ","Ye ","Cao ","Kuai ","Feng ","Meng ","Zou ","Kuang ","Lian ","Zan ","Chan ","You ","Qi ","Yan ","Chan ","Zan ","Ling ","Huan ","Xi ","Feng ","Zan ","Li ","You ","Ding ","Qiu ","Zhuo ","Pei ","Zhou ","Yi ","Hang ","Yu ","Jiu ","Yan ","Zui ","Mao ","Dan ","Xu ","Tou ","Zhen ","Fen ","Sakenomoto ","[?] ","Yun ","Tai ","Tian ","Qia ","Tuo ","Zuo ","Han ","Gu ","Su ","Po ","Chou ","Zai ","Ming ","Luo ","Chuo ","Chou ","You ","Tong ","Zhi ","Xian ","Jiang ","Cheng ","Yin ","Tu ","Xiao ","Mei ","Ku ","Suan ","Lei ","Pu ","Zui ","Hai ","Yan ","Xi ","Niang ","Wei ","Lu ","Lan ","Yan ","Tao ","Pei ","Zhan ","Chun ","Tan ","Zui ","Chuo ","Cu ","Kun ","Ti ","Mian ","Du ","Hu ","Xu ","Xing ","Tan ","Jiu ","Chun ","Yun ","Po ","Ke ","Sou ","Mi ","Quan ","Chou ","Cuo ","Yun ","Yong ","Ang ","Zha ","Hai ","Tang ","Jiang ","Piao ","Shan ","Yu ","Li ","Zao ","Lao ","Yi ","Jiang ","Pu ","Jiao ","Xi ","Tan ","Po ","Nong ","Yi ","Li ","Ju ","Jiao ","Yi ","Niang ","Ru ","Xun ","Chou ","Yan ","Ling ","Mi ","Mi ","Niang ","Xin ","Jiao ","Xi ","Mi ","Yan ","Bian ","Cai ","Shi ","You ","Shi ","Shi ","Li ","Zhong ","Ye ","Liang ","Li ","Jin ","Jin ","Qiu ","Yi ","Diao ","Dao ","Zhao ","Ding ","Po ","Qiu ","He ","Fu ","Zhen ","Zhi ","Ba ","Luan ","Fu ","Nai ","Diao ","Shan ","Qiao ","Kou ","Chuan ","Zi ","Fan ","Yu ","Hua ","Han ","Gong ","Qi ","Mang ","Ri ","Di ","Si ","Xi ","Yi ","Chai ","Shi ","Tu ","Xi ","Nu ","Qian ","Ishiyumi ","Jian ","Pi ","Ye ","Yin "]});var eN=w((uxe,VA)=>{VA.exports=["Ba ","Fang ","Chen ","Xing ","Tou ","Yue ","Yan ","Fu ","Pi ","Na ","Xin ","E ","Jue ","Dun ","Gou ","Yin ","Qian ","Ban ","Ji ","Ren ","Chao ","Niu ","Fen ","Yun ","Ji ","Qin ","Pi ","Guo ","Hong ","Yin ","Jun ","Shi ","Yi ","Zhong ","Nie ","Gai ","Ri ","Huo ","Tai ","Kang ","Habaki ","Irori ","Ngaak ","[?] ","Duo ","Zi ","Ni ","Tu ","Shi ","Min ","Gu ","E ","Ling ","Bing ","Yi ","Gu ","Ba ","Pi ","Yu ","Si ","Zuo ","Bu ","You ","Dian ","Jia ","Zhen ","Shi ","Shi ","Tie ","Ju ","Zhan ","Shi ","She ","Xuan ","Zhao ","Bao ","He ","Bi ","Sheng ","Chu ","Shi ","Bo ","Zhu ","Chi ","Za ","Po ","Tong ","Qian ","Fu ","Zhai ","Liu ","Qian ","Fu ","Li ","Yue ","Pi ","Yang ","Ban ","Bo ","Jie ","Gou ","Shu ","Zheng ","Mu ","Ni ","Nie ","Di ","Jia ","Mu ","Dan ","Shen ","Yi ","Si ","Kuang ","Ka ","Bei ","Jian ","Tong ","Xing ","Hong ","Jiao ","Chi ","Er ","Ge ","Bing ","Shi ","Mou ","Jia ","Yin ","Jun ","Zhou ","Chong ","Shang ","Tong ","Mo ","Lei ","Ji ","Yu ","Xu ","Ren ","Zun ","Zhi ","Qiong ","Shan ","Chi ","Xian ","Xing ","Quan ","Pi ","Tie ","Zhu ","Hou ","Ming ","Kua ","Yao ","Xian ","Xian ","Xiu ","Jun ","Cha ","Lao ","Ji ","Pi ","Ru ","Mi ","Yi ","Yin ","Guang ","An ","Diou ","You ","Se ","Kao ","Qian ","Luan ","Kasugai ","Ai ","Diao ","Han ","Rui ","Shi ","Keng ","Qiu ","Xiao ","Zhe ","Xiu ","Zang ","Ti ","Cuo ","Gua ","Gong ","Zhong ","Dou ","Lu ","Mei ","Lang ","Wan ","Xin ","Yun ","Bei ","Wu ","Su ","Yu ","Chan ","Ting ","Bo ","Han ","Jia ","Hong ","Cuan ","Feng ","Chan ","Wan ","Zhi ","Si ","Xuan ","Wu ","Wu ","Tiao ","Gong ","Zhuo ","Lue ","Xing ","Qian ","Shen ","Han ","Lue ","Xie ","Chu ","Zheng ","Ju ","Xian ","Tie ","Mang ","Pu ","Li ","Pan ","Rui ","Cheng ","Gao ","Li ","Te ","Pyeng ","Zhu ","[?] ","Tu ","Liu ","Zui ","Ju ","Chang ","Yuan ","Jian ","Gang ","Diao ","Tao ","Chang "]});var iN=w((cxe,tN)=>{tN.exports=["Lun ","Kua ","Ling ","Bei ","Lu ","Li ","Qiang ","Pou ","Juan ","Min ","Zui ","Peng ","An ","Pi ","Xian ","Ya ","Zhui ","Lei ","A ","Kong ","Ta ","Kun ","Du ","Wei ","Chui ","Zi ","Zheng ","Ben ","Nie ","Cong ","Qun ","Tan ","Ding ","Qi ","Qian ","Zhuo ","Qi ","Yu ","Jin ","Guan ","Mao ","Chang ","Tian ","Xi ","Lian ","Tao ","Gu ","Cuo ","Shu ","Zhen ","Lu ","Meng ","Lu ","Hua ","Biao ","Ga ","Lai ","Ken ","Kazari ","Bu ","Nai ","Wan ","Zan ","[?] ","De ","Xian ","[?] ","Huo ","Liang ","[?] ","Men ","Kai ","Ying ","Di ","Lian ","Guo ","Xian ","Du ","Tu ","Wei ","Cong ","Fu ","Rou ","Ji ","E ","Rou ","Chen ","Ti ","Zha ","Hong ","Yang ","Duan ","Xia ","Yu ","Keng ","Xing ","Huang ","Wei ","Fu ","Zhao ","Cha ","Qie ","She ","Hong ","Kui ","Tian ","Mou ","Qiao ","Qiao ","Hou ","Tou ","Cong ","Huan ","Ye ","Min ","Jian ","Duan ","Jian ","Song ","Kui ","Hu ","Xuan ","Duo ","Jie ","Zhen ","Bian ","Zhong ","Zi ","Xiu ","Ye ","Mei ","Pai ","Ai ","Jie ","[?] ","Mei ","Chuo ","Ta ","Bang ","Xia ","Lian ","Suo ","Xi ","Liu ","Zu ","Ye ","Nou ","Weng ","Rong ","Tang ","Suo ","Qiang ","Ge ","Shuo ","Chui ","Bo ","Pan ","Sa ","Bi ","Sang ","Gang ","Zi ","Wu ","Ying ","Huang ","Tiao ","Liu ","Kai ","Sun ","Sha ","Sou ","Wan ","Hao ","Zhen ","Zhen ","Luo ","Yi ","Yuan ","Tang ","Nie ","Xi ","Jia ","Ge ","Ma ","Juan ","Kasugai ","Habaki ","Suo ","[?] ","[?] ","[?] ","Na ","Lu ","Suo ","Ou ","Zu ","Tuan ","Xiu ","Guan ","Xuan ","Lian ","Shou ","Ao ","Man ","Mo ","Luo ","Bi ","Wei ","Liu ","Di ","Qiao ","Cong ","Yi ","Lu ","Ao ","Keng ","Qiang ","Cui ","Qi ","Chang ","Tang ","Man ","Yong ","Chan ","Feng ","Jing ","Biao ","Shu ","Lou ","Xiu ","Cong ","Long ","Zan ","Jian ","Cao ","Li ","Xia ","Xi ","Kang ","[?] ","Beng ","[?] ","[?] ","Zheng ","Lu ","Hua ","Ji ","Pu ","Hui ","Qiang ","Po ","Lin ","Suo ","Xiu ","San ","Cheng "]});var rN=w((dxe,nN)=>{nN.exports=["Kui ","Si ","Liu ","Nao ","Heng ","Pie ","Sui ","Fan ","Qiao ","Quan ","Yang ","Tang ","Xiang ","Jue ","Jiao ","Zun ","Liao ","Jie ","Lao ","Dui ","Tan ","Zan ","Ji ","Jian ","Zhong ","Deng ","Ya ","Ying ","Dui ","Jue ","Nou ","Ti ","Pu ","Tie ","[?] ","[?] ","Ding ","Shan ","Kai ","Jian ","Fei ","Sui ","Lu ","Juan ","Hui ","Yu ","Lian ","Zhuo ","Qiao ","Qian ","Zhuo ","Lei ","Bi ","Tie ","Huan ","Ye ","Duo ","Guo ","Dang ","Ju ","Fen ","Da ","Bei ","Yi ","Ai ","Zong ","Xun ","Diao ","Zhu ","Heng ","Zhui ","Ji ","Nie ","Ta ","Huo ","Qing ","Bin ","Ying ","Kui ","Ning ","Xu ","Jian ","Jian ","Yari ","Cha ","Zhi ","Mie ","Li ","Lei ","Ji ","Zuan ","Kuang ","Shang ","Peng ","La ","Du ","Shuo ","Chuo ","Lu ","Biao ","Bao ","Lu ","[?] ","[?] ","Long ","E ","Lu ","Xin ","Jian ","Lan ","Bo ","Jian ","Yao ","Chan ","Xiang ","Jian ","Xi ","Guan ","Cang ","Nie ","Lei ","Cuan ","Qu ","Pan ","Luo ","Zuan ","Luan ","Zao ","Nie ","Jue ","Tang ","Shu ","Lan ","Jin ","Qiu ","Yi ","Zhen ","Ding ","Zhao ","Po ","Diao ","Tu ","Qian ","Chuan ","Shan ","Ji ","Fan ","Diao ","Men ","Nu ","Xi ","Chai ","Xing ","Gai ","Bu ","Tai ","Ju ","Dun ","Chao ","Zhong ","Na ","Bei ","Gang ","Ban ","Qian ","Yao ","Qin ","Jun ","Wu ","Gou ","Kang ","Fang ","Huo ","Tou ","Niu ","Ba ","Yu ","Qian ","Zheng ","Qian ","Gu ","Bo ","E ","Po ","Bu ","Ba ","Yue ","Zuan ","Mu ","Dan ","Jia ","Dian ","You ","Tie ","Bo ","Ling ","Shuo ","Qian ","Liu ","Bao ","Shi ","Xuan ","She ","Bi ","Ni ","Pi ","Duo ","Xing ","Kao ","Lao ","Er ","Mang ","Ya ","You ","Cheng ","Jia ","Ye ","Nao ","Zhi ","Dang ","Tong ","Lu ","Diao ","Yin ","Kai ","Zha ","Zhu ","Xian ","Ting ","Diu ","Xian ","Hua ","Quan ","Sha ","Jia ","Yao ","Ge ","Ming ","Zheng ","Se ","Jiao ","Yi ","Chan ","Chong ","Tang ","An ","Yin ","Ru ","Zhu ","Lao ","Pu ","Wu ","Lai ","Te ","Lian ","Keng "]});var sN=w((hxe,oN)=>{oN.exports=["Xiao ","Suo ","Li ","Zheng ","Chu ","Guo ","Gao ","Tie ","Xiu ","Cuo ","Lue ","Feng ","Xin ","Liu ","Kai ","Jian ","Rui ","Ti ","Lang ","Qian ","Ju ","A ","Qiang ","Duo ","Tian ","Cuo ","Mao ","Ben ","Qi ","De ","Kua ","Kun ","Chang ","Xi ","Gu ","Luo ","Chui ","Zhui ","Jin ","Zhi ","Xian ","Juan ","Huo ","Pou ","Tan ","Ding ","Jian ","Ju ","Meng ","Zi ","Qie ","Ying ","Kai ","Qiang ","Song ","E ","Cha ","Qiao ","Zhong ","Duan ","Sou ","Huang ","Huan ","Ai ","Du ","Mei ","Lou ","Zi ","Fei ","Mei ","Mo ","Zhen ","Bo ","Ge ","Nie ","Tang ","Juan ","Nie ","Na ","Liu ","Hao ","Bang ","Yi ","Jia ","Bin ","Rong ","Biao ","Tang ","Man ","Luo ","Beng ","Yong ","Jing ","Di ","Zu ","Xuan ","Liu ","Tan ","Jue ","Liao ","Pu ","Lu ","Dui ","Lan ","Pu ","Cuan ","Qiang ","Deng ","Huo ","Lei ","Huan ","Zhuo ","Lian ","Yi ","Cha ","Biao ","La ","Chan ","Xiang ","Chang ","Chang ","Jiu ","Ao ","Die ","Qu ","Liao ","Mi ","Chang ","Men ","Ma ","Shuan ","Shan ","Huo ","Men ","Yan ","Bi ","Han ","Bi ","San ","Kai ","Kang ","Beng ","Hong ","Run ","San ","Xian ","Xian ","Jian ","Min ","Xia ","Yuru ","Dou ","Zha ","Nao ","Jian ","Peng ","Xia ","Ling ","Bian ","Bi ","Run ","He ","Guan ","Ge ","Ge ","Fa ","Chu ","Hong ","Gui ","Min ","Se ","Kun ","Lang ","Lu ","Ting ","Sha ","Ju ","Yue ","Yue ","Chan ","Qu ","Lin ","Chang ","Shai ","Kun ","Yan ","Min ","Yan ","E ","Hun ","Yu ","Wen ","Xiang ","Bao ","Xiang ","Qu ","Yao ","Wen ","Ban ","An ","Wei ","Yin ","Kuo ","Que ","Lan ","Du ","[?] ","Phwung ","Tian ","Nie ","Ta ","Kai ","He ","Que ","Chuang ","Guan ","Dou ","Qi ","Kui ","Tang ","Guan ","Piao ","Kan ","Xi ","Hui ","Chan ","Pi ","Dang ","Huan ","Ta ","Wen ","[?] ","Men ","Shuan ","Shan ","Yan ","Han ","Bi ","Wen ","Chuang ","Run ","Wei ","Xian ","Hong ","Jian ","Min ","Kang ","Men ","Zha ","Nao ","Gui ","Wen ","Ta ","Min ","Lu ","Kai "]});var lN=w((gxe,aN)=>{aN.exports=["Fa ","Ge ","He ","Kun ","Jiu ","Yue ","Lang ","Du ","Yu ","Yan ","Chang ","Xi ","Wen ","Hun ","Yan ","E ","Chan ","Lan ","Qu ","Hui ","Kuo ","Que ","Ge ","Tian ","Ta ","Que ","Kan ","Huan ","Fu ","Fu ","Le ","Dui ","Xin ","Qian ","Wu ","Yi ","Tuo ","Yin ","Yang ","Dou ","E ","Sheng ","Ban ","Pei ","Keng ","Yun ","Ruan ","Zhi ","Pi ","Jing ","Fang ","Yang ","Yin ","Zhen ","Jie ","Cheng ","E ","Qu ","Di ","Zu ","Zuo ","Dian ","Ling ","A ","Tuo ","Tuo ","Po ","Bing ","Fu ","Ji ","Lu ","Long ","Chen ","Xing ","Duo ","Lou ","Mo ","Jiang ","Shu ","Duo ","Xian ","Er ","Gui ","Yu ","Gai ","Shan ","Xun ","Qiao ","Xing ","Chun ","Fu ","Bi ","Xia ","Shan ","Sheng ","Zhi ","Pu ","Dou ","Yuan ","Zhen ","Chu ","Xian ","Tou ","Nie ","Yun ","Xian ","Pei ","Pei ","Zou ","Yi ","Dui ","Lun ","Yin ","Ju ","Chui ","Chen ","Pi ","Ling ","Tao ","Xian ","Lu ","Sheng ","Xian ","Yin ","Zhu ","Yang ","Reng ","Shan ","Chong ","Yan ","Yin ","Yu ","Ti ","Yu ","Long ","Wei ","Wei ","Nie ","Dui ","Sui ","An ","Huang ","Jie ","Sui ","Yin ","Gai ","Yan ","Hui ","Ge ","Yun ","Wu ","Wei ","Ai ","Xi ","Tang ","Ji ","Zhang ","Dao ","Ao ","Xi ","Yin ","[?] ","Rao ","Lin ","Tui ","Deng ","Pi ","Sui ","Sui ","Yu ","Xian ","Fen ","Ni ","Er ","Ji ","Dao ","Xi ","Yin ","E ","Hui ","Long ","Xi ","Li ","Li ","Li ","Zhui ","He ","Zhi ","Zhun ","Jun ","Nan ","Yi ","Que ","Yan ","Qian ","Ya ","Xiong ","Ya ","Ji ","Gu ","Huan ","Zhi ","Gou ","Jun ","Ci ","Yong ","Ju ","Chu ","Hu ","Za ","Luo ","Yu ","Chou ","Diao ","Sui ","Han ","Huo ","Shuang ","Guan ","Chu ","Za ","Yong ","Ji ","Xi ","Chou ","Liu ","Li ","Nan ","Xue ","Za ","Ji ","Ji ","Yu ","Yu ","Xue ","Na ","Fou ","Se ","Mu ","Wen ","Fen ","Pang ","Yun ","Li ","Li ","Ang ","Ling ","Lei ","An ","Bao ","Meng ","Dian ","Dang ","Xing ","Wu ","Zhao "]});var cN=w((pxe,uN)=>{uN.exports=["Xu ","Ji ","Mu ","Chen ","Xiao ","Zha ","Ting ","Zhen ","Pei ","Mei ","Ling ","Qi ","Chou ","Huo ","Sha ","Fei ","Weng ","Zhan ","Yin ","Ni ","Chou ","Tun ","Lin ","[?] ","Dong ","Ying ","Wu ","Ling ","Shuang ","Ling ","Xia ","Hong ","Yin ","Mo ","Mai ","Yun ","Liu ","Meng ","Bin ","Wu ","Wei ","Huo ","Yin ","Xi ","Yi ","Ai ","Dan ","Deng ","Xian ","Yu ","Lu ","Long ","Dai ","Ji ","Pang ","Yang ","Ba ","Pi ","Wei ","[?] ","Xi ","Ji ","Mai ","Meng ","Meng ","Lei ","Li ","Huo ","Ai ","Fei ","Dai ","Long ","Ling ","Ai ","Feng ","Li ","Bao ","[?] ","He ","He ","Bing ","Qing ","Qing ","Jing ","Tian ","Zhen ","Jing ","Cheng ","Qing ","Jing ","Jing ","Dian ","Jing ","Tian ","Fei ","Fei ","Kao ","Mi ","Mian ","Mian ","Pao ","Ye ","Tian ","Hui ","Ye ","Ge ","Ding ","Cha ","Jian ","Ren ","Di ","Du ","Wu ","Ren ","Qin ","Jin ","Xue ","Niu ","Ba ","Yin ","Sa ","Na ","Mo ","Zu ","Da ","Ban ","Yi ","Yao ","Tao ","Tuo ","Jia ","Hong ","Pao ","Yang ","Tomo ","Yin ","Jia ","Tao ","Ji ","Xie ","An ","An ","Hen ","Gong ","Kohaze ","Da ","Qiao ","Ting ","Wan ","Ying ","Sui ","Tiao ","Qiao ","Xuan ","Kong ","Beng ","Ta ","Zhang ","Bing ","Kuo ","Ju ","La ","Xie ","Rou ","Bang ","Yi ","Qiu ","Qiu ","He ","Xiao ","Mu ","Ju ","Jian ","Bian ","Di ","Jian ","On ","Tao ","Gou ","Ta ","Bei ","Xie ","Pan ","Ge ","Bi ","Kuo ","Tang ","Lou ","Gui ","Qiao ","Xue ","Ji ","Jian ","Jiang ","Chan ","Da ","Huo ","Xian ","Qian ","Du ","Wa ","Jian ","Lan ","Wei ","Ren ","Fu ","Mei ","Juan ","Ge ","Wei ","Qiao ","Han ","Chang ","[?] ","Rou ","Xun ","She ","Wei ","Ge ","Bei ","Tao ","Gou ","Yun ","[?] ","Bi ","Wei ","Hui ","Du ","Wa ","Du ","Wei ","Ren ","Fu ","Han ","Wei ","Yun ","Tao ","Jiu ","Jiu ","Xian ","Xie ","Xian ","Ji ","Yin ","Za ","Yun ","Shao ","Le ","Peng ","Heng ","Ying ","Yun ","Peng ","Yin ","Yin ","Xiang "]});var hN=w((fxe,dN)=>{dN.exports=["Hu ","Ye ","Ding ","Qing ","Pan ","Xiang ","Shun ","Han ","Xu ","Yi ","Xu ","Gu ","Song ","Kui ","Qi ","Hang ","Yu ","Wan ","Ban ","Dun ","Di ","Dan ","Pan ","Po ","Ling ","Ce ","Jing ","Lei ","He ","Qiao ","E ","E ","Wei ","Jie ","Gua ","Shen ","Yi ","Shen ","Hai ","Dui ","Pian ","Ping ","Lei ","Fu ","Jia ","Tou ","Hui ","Kui ","Jia ","Le ","Tian ","Cheng ","Ying ","Jun ","Hu ","Han ","Jing ","Tui ","Tui ","Pin ","Lai ","Tui ","Zi ","Zi ","Chui ","Ding ","Lai ","Yan ","Han ","Jian ","Ke ","Cui ","Jiong ","Qin ","Yi ","Sai ","Ti ","E ","E ","Yan ","Hun ","Kan ","Yong ","Zhuan ","Yan ","Xian ","Xin ","Yi ","Yuan ","Sang ","Dian ","Dian ","Jiang ","Ku ","Lei ","Liao ","Piao ","Yi ","Man ","Qi ","Rao ","Hao ","Qiao ","Gu ","Xun ","Qian ","Hui ","Zhan ","Ru ","Hong ","Bin ","Xian ","Pin ","Lu ","Lan ","Nie ","Quan ","Ye ","Ding ","Qing ","Han ","Xiang ","Shun ","Xu ","Xu ","Wan ","Gu ","Dun ","Qi ","Ban ","Song ","Hang ","Yu ","Lu ","Ling ","Po ","Jing ","Jie ","Jia ","Tian ","Han ","Ying ","Jiong ","Hai ","Yi ","Pin ","Hui ","Tui ","Han ","Ying ","Ying ","Ke ","Ti ","Yong ","E ","Zhuan ","Yan ","E ","Nie ","Man ","Dian ","Sang ","Hao ","Lei ","Zhan ","Ru ","Pin ","Quan ","Feng ","Biao ","Oroshi ","Fu ","Xia ","Zhan ","Biao ","Sa ","Ba ","Tai ","Lie ","Gua ","Xuan ","Shao ","Ju ","Bi ","Si ","Wei ","Yang ","Yao ","Sou ","Kai ","Sao ","Fan ","Liu ","Xi ","Liao ","Piao ","Piao ","Liu ","Biao ","Biao ","Biao ","Liao ","[?] ","Se ","Feng ","Biao ","Feng ","Yang ","Zhan ","Biao ","Sa ","Ju ","Si ","Sou ","Yao ","Liu ","Piao ","Biao ","Biao ","Fei ","Fan ","Fei ","Fei ","Shi ","Shi ","Can ","Ji ","Ding ","Si ","Tuo ","Zhan ","Sun ","Xiang ","Tun ","Ren ","Yu ","Juan ","Chi ","Yin ","Fan ","Fan ","Sun ","Yin ","Zhu ","Yi ","Zhai ","Bi ","Jie ","Tao ","Liu ","Ci ","Tie ","Si ","Bao ","Shi ","Duo "]});var pN=w((mxe,gN)=>{gN.exports=["Hai ","Ren ","Tian ","Jiao ","Jia ","Bing ","Yao ","Tong ","Ci ","Xiang ","Yang ","Yang ","Er ","Yan ","Le ","Yi ","Can ","Bo ","Nei ","E ","Bu ","Jun ","Dou ","Su ","Yu ","Shi ","Yao ","Hun ","Guo ","Shi ","Jian ","Zhui ","Bing ","Xian ","Bu ","Ye ","Tan ","Fei ","Zhang ","Wei ","Guan ","E ","Nuan ","Hun ","Hu ","Huang ","Tie ","Hui ","Jian ","Hou ","He ","Xing ","Fen ","Wei ","Gu ","Cha ","Song ","Tang ","Bo ","Gao ","Xi ","Kui ","Liu ","Sou ","Tao ","Ye ","Yun ","Mo ","Tang ","Man ","Bi ","Yu ","Xiu ","Jin ","San ","Kui ","Zhuan ","Shan ","Chi ","Dan ","Yi ","Ji ","Rao ","Cheng ","Yong ","Tao ","Hui ","Xiang ","Zhan ","Fen ","Hai ","Meng ","Yan ","Mo ","Chan ","Xiang ","Luo ","Zuan ","Nang ","Shi ","Ding ","Ji ","Tuo ","Xing ","Tun ","Xi ","Ren ","Yu ","Chi ","Fan ","Yin ","Jian ","Shi ","Bao ","Si ","Duo ","Yi ","Er ","Rao ","Xiang ","Jia ","Le ","Jiao ","Yi ","Bing ","Bo ","Dou ","E ","Yu ","Nei ","Jun ","Guo ","Hun ","Xian ","Guan ","Cha ","Kui ","Gu ","Sou ","Chan ","Ye ","Mo ","Bo ","Liu ","Xiu ","Jin ","Man ","San ","Zhuan ","Nang ","Shou ","Kui ","Guo ","Xiang ","Fen ","Ba ","Ni ","Bi ","Bo ","Tu ","Han ","Fei ","Jian ","An ","Ai ","Fu ","Xian ","Wen ","Xin ","Fen ","Bin ","Xing ","Ma ","Yu ","Feng ","Han ","Di ","Tuo ","Tuo ","Chi ","Xun ","Zhu ","Zhi ","Pei ","Xin ","Ri ","Sa ","Yin ","Wen ","Zhi ","Dan ","Lu ","You ","Bo ","Bao ","Kuai ","Tuo ","Yi ","Qu ","[?] ","Qu ","Jiong ","Bo ","Zhao ","Yuan ","Peng ","Zhou ","Ju ","Zhu ","Nu ","Ju ","Pi ","Zang ","Jia ","Ling ","Zhen ","Tai ","Fu ","Yang ","Shi ","Bi ","Tuo ","Tuo ","Si ","Liu ","Ma ","Pian ","Tao ","Zhi ","Rong ","Teng ","Dong ","Xun ","Quan ","Shen ","Jiong ","Er ","Hai ","Bo ","Zhu ","Yin ","Luo ","Shuu ","Dan ","Xie ","Liu ","Ju ","Song ","Qin ","Mang ","Liang ","Han ","Tu ","Xuan ","Tui ","Jun "]});var mN=w((bxe,fN)=>{fN.exports=["E ","Cheng ","Xin ","Ai ","Lu ","Zhui ","Zhou ","She ","Pian ","Kun ","Tao ","Lai ","Zong ","Ke ","Qi ","Qi ","Yan ","Fei ","Sao ","Yan ","Jie ","Yao ","Wu ","Pian ","Cong ","Pian ","Qian ","Fei ","Huang ","Jian ","Huo ","Yu ","Ti ","Quan ","Xia ","Zong ","Kui ","Rou ","Si ","Gua ","Tuo ","Kui ","Sou ","Qian ","Cheng ","Zhi ","Liu ","Pang ","Teng ","Xi ","Cao ","Du ","Yan ","Yuan ","Zou ","Sao ","Shan ","Li ","Zhi ","Shuang ","Lu ","Xi ","Luo ","Zhang ","Mo ","Ao ","Can ","Piao ","Cong ","Qu ","Bi ","Zhi ","Yu ","Xu ","Hua ","Bo ","Su ","Xiao ","Lin ","Chan ","Dun ","Liu ","Tuo ","Zeng ","Tan ","Jiao ","Tie ","Yan ","Luo ","Zhan ","Jing ","Yi ","Ye ","Tuo ","Bin ","Zou ","Yan ","Peng ","Lu ","Teng ","Xiang ","Ji ","Shuang ","Ju ","Xi ","Huan ","Li ","Biao ","Ma ","Yu ","Tuo ","Xun ","Chi ","Qu ","Ri ","Bo ","Lu ","Zang ","Shi ","Si ","Fu ","Ju ","Zou ","Zhu ","Tuo ","Nu ","Jia ","Yi ","Tai ","Xiao ","Ma ","Yin ","Jiao ","Hua ","Luo ","Hai ","Pian ","Biao ","Li ","Cheng ","Yan ","Xin ","Qin ","Jun ","Qi ","Qi ","Ke ","Zhui ","Zong ","Su ","Can ","Pian ","Zhi ","Kui ","Sao ","Wu ","Ao ","Liu ","Qian ","Shan ","Piao ","Luo ","Cong ","Chan ","Zou ","Ji ","Shuang ","Xiang ","Gu ","Wei ","Wei ","Wei ","Yu ","Gan ","Yi ","Ang ","Tou ","Xie ","Bao ","Bi ","Chi ","Ti ","Di ","Ku ","Hai ","Qiao ","Gou ","Kua ","Ge ","Tui ","Geng ","Pian ","Bi ","Ke ","Ka ","Yu ","Sui ","Lou ","Bo ","Xiao ","Pang ","Bo ","Ci ","Kuan ","Bin ","Mo ","Liao ","Lou ","Nao ","Du ","Zang ","Sui ","Ti ","Bin ","Kuan ","Lu ","Gao ","Gao ","Qiao ","Kao ","Qiao ","Lao ","Zao ","Biao ","Kun ","Kun ","Ti ","Fang ","Xiu ","Ran ","Mao ","Dan ","Kun ","Bin ","Fa ","Tiao ","Peng ","Zi ","Fa ","Ran ","Ti ","Pao ","Pi ","Mao ","Fu ","Er ","Rong ","Qu ","Gong ","Xiu ","Gua ","Ji ","Peng ","Zhua ","Shao ","Sha "]});var yN=w((yxe,bN)=>{bN.exports=["Ti ","Li ","Bin ","Zong ","Ti ","Peng ","Song ","Zheng ","Quan ","Zong ","Shun ","Jian ","Duo ","Hu ","La ","Jiu ","Qi ","Lian ","Zhen ","Bin ","Peng ","Mo ","San ","Man ","Man ","Seng ","Xu ","Lie ","Qian ","Qian ","Nong ","Huan ","Kuai ","Ning ","Bin ","Lie ","Rang ","Dou ","Dou ","Nao ","Hong ","Xi ","Dou ","Han ","Dou ","Dou ","Jiu ","Chang ","Yu ","Yu ","Li ","Juan ","Fu ","Qian ","Gui ","Zong ","Liu ","Gui ","Shang ","Yu ","Gui ","Mei ","Ji ","Qi ","Jie ","Kui ","Hun ","Ba ","Po ","Mei ","Xu ","Yan ","Xiao ","Liang ","Yu ","Tui ","Qi ","Wang ","Liang ","Wei ","Jian ","Chi ","Piao ","Bi ","Mo ","Ji ","Xu ","Chou ","Yan ","Zhan ","Yu ","Dao ","Ren ","Ji ","Eri ","Gong ","Tuo ","Diao ","Ji ","Xu ","E ","E ","Sha ","Hang ","Tun ","Mo ","Jie ","Shen ","Fan ","Yuan ","Bi ","Lu ","Wen ","Hu ","Lu ","Za ","Fang ","Fen ","Na ","You ","Namazu ","Todo ","He ","Xia ","Qu ","Han ","Pi ","Ling ","Tuo ","Bo ","Qiu ","Ping ","Fu ","Bi ","Ji ","Wei ","Ju ","Diao ","Bo ","You ","Gun ","Pi ","Nian ","Xing ","Tai ","Bao ","Fu ","Zha ","Ju ","Gu ","Kajika ","Tong ","[?] ","Ta ","Jie ","Shu ","Hou ","Xiang ","Er ","An ","Wei ","Tiao ","Zhu ","Yin ","Lie ","Luo ","Tong ","Yi ","Qi ","Bing ","Wei ","Jiao ","Bu ","Gui ","Xian ","Ge ","Hui ","Bora ","Mate ","Kao ","Gori ","Duo ","Jun ","Ti ","Man ","Xiao ","Za ","Sha ","Qin ","Yu ","Nei ","Zhe ","Gun ","Geng ","Su ","Wu ","Qiu ","Ting ","Fu ","Wan ","You ","Li ","Sha ","Sha ","Gao ","Meng ","Ugui ","Asari ","Subashiri ","Kazunoko ","Yong ","Ni ","Zi ","Qi ","Qing ","Xiang ","Nei ","Chun ","Ji ","Diao ","Qie ","Gu ","Zhou ","Dong ","Lai ","Fei ","Ni ","Yi ","Kun ","Lu ","Jiu ","Chang ","Jing ","Lun ","Ling ","Zou ","Li ","Meng ","Zong ","Zhi ","Nian ","Shachi ","Dojou ","Sukesou ","Shi ","Shen ","Hun ","Shi ","Hou ","Xing ","Zhu ","La ","Zong ","Ji ","Bian ","Bian "]});var wN=w((vxe,vN)=>{vN.exports=["Huan ","Quan ","Ze ","Wei ","Wei ","Yu ","Qun ","Rou ","Die ","Huang ","Lian ","Yan ","Qiu ","Qiu ","Jian ","Bi ","E ","Yang ","Fu ","Sai ","Jian ","Xia ","Tuo ","Hu ","Muroaji ","Ruo ","Haraka ","Wen ","Jian ","Hao ","Wu ","Fang ","Sao ","Liu ","Ma ","Shi ","Shi ","Yin ","Z ","Teng ","Ta ","Yao ","Ge ","Rong ","Qian ","Qi ","Wen ","Ruo ","Hatahata ","Lian ","Ao ","Le ","Hui ","Min ","Ji ","Tiao ","Qu ","Jian ","Sao ","Man ","Xi ","Qiu ","Biao ","Ji ","Ji ","Zhu ","Jiang ","Qiu ","Zhuan ","Yong ","Zhang ","Kang ","Xue ","Bie ","Jue ","Qu ","Xiang ","Bo ","Jiao ","Xun ","Su ","Huang ","Zun ","Shan ","Shan ","Fan ","Jue ","Lin ","Xun ","Miao ","Xi ","Eso ","Kyou ","Fen ","Guan ","Hou ","Kuai ","Zei ","Sao ","Zhan ","Gan ","Gui ","Sheng ","Li ","Chang ","Hatahata ","Shiira ","Mutsu ","Ru ","Ji ","Xu ","Huo ","Shiira ","Li ","Lie ","Li ","Mie ","Zhen ","Xiang ","E ","Lu ","Guan ","Li ","Xian ","Yu ","Dao ","Ji ","You ","Tun ","Lu ","Fang ","Ba ","He ","Bo ","Ping ","Nian ","Lu ","You ","Zha ","Fu ","Bo ","Bao ","Hou ","Pi ","Tai ","Gui ","Jie ","Kao ","Wei ","Er ","Tong ","Ze ","Hou ","Kuai ","Ji ","Jiao ","Xian ","Za ","Xiang ","Xun ","Geng ","Li ","Lian ","Jian ","Li ","Shi ","Tiao ","Gun ","Sha ","Wan ","Jun ","Ji ","Yong ","Qing ","Ling ","Qi ","Zou ","Fei ","Kun ","Chang ","Gu ","Ni ","Nian ","Diao ","Jing ","Shen ","Shi ","Zi ","Fen ","Die ","Bi ","Chang ","Shi ","Wen ","Wei ","Sai ","E ","Qiu ","Fu ","Huang ","Quan ","Jiang ","Bian ","Sao ","Ao ","Qi ","Ta ","Yin ","Yao ","Fang ","Jian ","Le ","Biao ","Xue ","Bie ","Man ","Min ","Yong ","Wei ","Xi ","Jue ","Shan ","Lin ","Zun ","Huo ","Gan ","Li ","Zhan ","Guan ","Niao ","Yi ","Fu ","Li ","Jiu ","Bu ","Yan ","Fu ","Diao ","Ji ","Feng ","Nio ","Gan ","Shi ","Feng ","Ming ","Bao ","Yuan ","Zhi ","Hu ","Qin ","Fu ","Fen ","Wen ","Jian ","Shi ","Yu "]});var CN=w((wxe,xN)=>{xN.exports=["Fou ","Yiao ","Jue ","Jue ","Pi ","Huan ","Zhen ","Bao ","Yan ","Ya ","Zheng ","Fang ","Feng ","Wen ","Ou ","Te ","Jia ","Nu ","Ling ","Mie ","Fu ","Tuo ","Wen ","Li ","Bian ","Zhi ","Ge ","Yuan ","Zi ","Qu ","Xiao ","Zhi ","Dan ","Ju ","You ","Gu ","Zhong ","Yu ","Yang ","Rong ","Ya ","Tie ","Yu ","Shigi ","Ying ","Zhui ","Wu ","Er ","Gua ","Ai ","Zhi ","Yan ","Heng ","Jiao ","Ji ","Lie ","Zhu ","Ren ","Yi ","Hong ","Luo ","Ru ","Mou ","Ge ","Ren ","Jiao ","Xiu ","Zhou ","Zhi ","Luo ","Chidori ","Toki ","Ten ","Luan ","Jia ","Ji ","Yu ","Huan ","Tuo ","Bu ","Wu ","Juan ","Yu ","Bo ","Xun ","Xun ","Bi ","Xi ","Jun ","Ju ","Tu ","Jing ","Ti ","E ","E ","Kuang ","Hu ","Wu ","Shen ","Lai ","Ikaruga ","Kakesu ","Lu ","Ping ","Shu ","Fu ","An ","Zhao ","Peng ","Qin ","Qian ","Bei ","Diao ","Lu ","Que ","Jian ","Ju ","Tu ","Ya ","Yuan ","Qi ","Li ","Ye ","Zhui ","Kong ","Zhui ","Kun ","Sheng ","Qi ","Jing ","Yi ","Yi ","Jing ","Zi ","Lai ","Dong ","Qi ","Chun ","Geng ","Ju ","Qu ","Isuka ","Kikuitadaki ","Ji ","Shu ","[?] ","Chi ","Miao ","Rou ","An ","Qiu ","Ti ","Hu ","Ti ","E ","Jie ","Mao ","Fu ","Chun ","Tu ","Yan ","He ","Yuan ","Pian ","Yun ","Mei ","Hu ","Ying ","Dun ","Mu ","Ju ","Tsugumi ","Cang ","Fang ","Gu ","Ying ","Yuan ","Xuan ","Weng ","Shi ","He ","Chu ","Tang ","Xia ","Ruo ","Liu ","Ji ","Gu ","Jian ","Zhun ","Han ","Zi ","Zi ","Ni ","Yao ","Yan ","Ji ","Li ","Tian ","Kou ","Ti ","Ti ","Ni ","Tu ","Ma ","Jiao ","Gao ","Tian ","Chen ","Li ","Zhuan ","Zhe ","Ao ","Yao ","Yi ","Ou ","Chi ","Zhi ","Liao ","Rong ","Lou ","Bi ","Shuang ","Zhuo ","Yu ","Wu ","Jue ","Yin ","Quan ","Si ","Jiao ","Yi ","Hua ","Bi ","Ying ","Su ","Huang ","Fan ","Jiao ","Liao ","Yan ","Kao ","Jiu ","Xian ","Xian ","Tu ","Mai ","Zun ","Yu ","Ying ","Lu ","Tuan ","Xian ","Xue ","Yi ","Pi "]});var DN=w((xxe,SN)=>{SN.exports=["Shu ","Luo ","Qi ","Yi ","Ji ","Zhe ","Yu ","Zhan ","Ye ","Yang ","Pi ","Ning ","Huo ","Mi ","Ying ","Meng ","Di ","Yue ","Yu ","Lei ","Bao ","Lu ","He ","Long ","Shuang ","Yue ","Ying ","Guan ","Qu ","Li ","Luan ","Niao ","Jiu ","Ji ","Yuan ","Ming ","Shi ","Ou ","Ya ","Cang ","Bao ","Zhen ","Gu ","Dong ","Lu ","Ya ","Xiao ","Yang ","Ling ","Zhi ","Qu ","Yuan ","Xue ","Tuo ","Si ","Zhi ","Er ","Gua ","Xiu ","Heng ","Zhou ","Ge ","Luan ","Hong ","Wu ","Bo ","Li ","Juan ","Hu ","E ","Yu ","Xian ","Ti ","Wu ","Que ","Miao ","An ","Kun ","Bei ","Peng ","Qian ","Chun ","Geng ","Yuan ","Su ","Hu ","He ","E ","Gu ","Qiu ","Zi ","Mei ","Mu ","Ni ","Yao ","Weng ","Liu ","Ji ","Ni ","Jian ","He ","Yi ","Ying ","Zhe ","Liao ","Liao ","Jiao ","Jiu ","Yu ","Lu ","Xuan ","Zhan ","Ying ","Huo ","Meng ","Guan ","Shuang ","Lu ","Jin ","Ling ","Jian ","Xian ","Cuo ","Jian ","Jian ","Yan ","Cuo ","Lu ","You ","Cu ","Ji ","Biao ","Cu ","Biao ","Zhu ","Jun ","Zhu ","Jian ","Mi ","Mi ","Wu ","Liu ","Chen ","Jun ","Lin ","Ni ","Qi ","Lu ","Jiu ","Jun ","Jing ","Li ","Xiang ","Yan ","Jia ","Mi ","Li ","She ","Zhang ","Lin ","Jing ","Ji ","Ling ","Yan ","Cu ","Mai ","Mai ","Ge ","Chao ","Fu ","Mian ","Mian ","Fu ","Pao ","Qu ","Qu ","Mou ","Fu ","Xian ","Lai ","Qu ","Mian ","[?] ","Feng ","Fu ","Qu ","Mian ","Ma ","Mo ","Mo ","Hui ","Ma ","Zou ","Nen ","Fen ","Huang ","Huang ","Jin ","Guang ","Tian ","Tou ","Heng ","Xi ","Kuang ","Heng ","Shu ","Li ","Nian ","Chi ","Hei ","Hei ","Yi ","Qian ","Dan ","Xi ","Tuan ","Mo ","Mo ","Qian ","Dai ","Chu ","You ","Dian ","Yi ","Xia ","Yan ","Qu ","Mei ","Yan ","Jing ","Yu ","Li ","Dang ","Du ","Can ","Yin ","An ","Yan ","Tan ","An ","Zhen ","Dai ","Can ","Yi ","Mei ","Dan ","Yan ","Du ","Lu ","Zhi ","Fen ","Fu ","Fu ","Min ","Min ","Yuan "]});var kN=w((Cxe,TN)=>{TN.exports=["Cu ","Qu ","Chao ","Wa ","Zhu ","Zhi ","Mang ","Ao ","Bie ","Tuo ","Bi ","Yuan ","Chao ","Tuo ","Ding ","Mi ","Nai ","Ding ","Zi ","Gu ","Gu ","Dong ","Fen ","Tao ","Yuan ","Pi ","Chang ","Gao ","Qi ","Yuan ","Tang ","Teng ","Shu ","Shu ","Fen ","Fei ","Wen ","Ba ","Diao ","Tuo ","Tong ","Qu ","Sheng ","Shi ","You ","Shi ","Ting ","Wu ","Nian ","Jing ","Hun ","Ju ","Yan ","Tu ","Ti ","Xi ","Xian ","Yan ","Lei ","Bi ","Yao ","Qiu ","Han ","Wu ","Wu ","Hou ","Xi ","Ge ","Zha ","Xiu ","Weng ","Zha ","Nong ","Nang ","Qi ","Zhai ","Ji ","Zi ","Ji ","Ji ","Qi ","Ji ","Chi ","Chen ","Chen ","He ","Ya ","Ken ","Xie ","Pao ","Cuo ","Shi ","Zi ","Chi ","Nian ","Ju ","Tiao ","Ling ","Ling ","Chu ","Quan ","Xie ","Ken ","Nie ","Jiu ","Yao ","Chuo ","Kun ","Yu ","Chu ","Yi ","Ni ","Cuo ","Zou ","Qu ","Nen ","Xian ","Ou ","E ","Wo ","Yi ","Chuo ","Zou ","Dian ","Chu ","Jin ","Ya ","Chi ","Chen ","He ","Ken ","Ju ","Ling ","Pao ","Tiao ","Zi ","Ken ","Yu ","Chuo ","Qu ","Wo ","Long ","Pang ","Gong ","Pang ","Yan ","Long ","Long ","Gong ","Kan ","Ta ","Ling ","Ta ","Long ","Gong ","Kan ","Gui ","Qiu ","Bie ","Gui ","Yue ","Chui ","He ","Jue ","Xie ","Yu ","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var RN=w((Sxe,PN)=>{PN.exports=["it","ix","i","ip","iet","iex","ie","iep","at","ax","a","ap","uox","uo","uop","ot","ox","o","op","ex","e","wu","bit","bix","bi","bip","biet","biex","bie","biep","bat","bax","ba","bap","buox","buo","buop","bot","box","bo","bop","bex","be","bep","but","bux","bu","bup","burx","bur","byt","byx","by","byp","byrx","byr","pit","pix","pi","pip","piex","pie","piep","pat","pax","pa","pap","puox","puo","puop","pot","pox","po","pop","put","pux","pu","pup","purx","pur","pyt","pyx","py","pyp","pyrx","pyr","bbit","bbix","bbi","bbip","bbiet","bbiex","bbie","bbiep","bbat","bbax","bba","bbap","bbuox","bbuo","bbuop","bbot","bbox","bbo","bbop","bbex","bbe","bbep","bbut","bbux","bbu","bbup","bburx","bbur","bbyt","bbyx","bby","bbyp","nbit","nbix","nbi","nbip","nbiex","nbie","nbiep","nbat","nbax","nba","nbap","nbot","nbox","nbo","nbop","nbut","nbux","nbu","nbup","nburx","nbur","nbyt","nbyx","nby","nbyp","nbyrx","nbyr","hmit","hmix","hmi","hmip","hmiex","hmie","hmiep","hmat","hmax","hma","hmap","hmuox","hmuo","hmuop","hmot","hmox","hmo","hmop","hmut","hmux","hmu","hmup","hmurx","hmur","hmyx","hmy","hmyp","hmyrx","hmyr","mit","mix","mi","mip","miex","mie","miep","mat","max","ma","map","muot","muox","muo","muop","mot","mox","mo","mop","mex","me","mut","mux","mu","mup","murx","mur","myt","myx","my","myp","fit","fix","fi","fip","fat","fax","fa","fap","fox","fo","fop","fut","fux","fu","fup","furx","fur","fyt","fyx","fy","fyp","vit","vix","vi","vip","viet","viex","vie","viep","vat","vax","va","vap","vot","vox","vo","vop","vex","vep","vut","vux","vu","vup","vurx","vur","vyt","vyx","vy","vyp","vyrx","vyr"]});var EN=w((Dxe,_N)=>{_N.exports=["dit","dix","di","dip","diex","die","diep","dat","dax","da","dap","duox","duo","dot","dox","do","dop","dex","de","dep","dut","dux","du","dup","durx","dur","tit","tix","ti","tip","tiex","tie","tiep","tat","tax","ta","tap","tuot","tuox","tuo","tuop","tot","tox","to","top","tex","te","tep","tut","tux","tu","tup","turx","tur","ddit","ddix","ddi","ddip","ddiex","ddie","ddiep","ddat","ddax","dda","ddap","dduox","dduo","dduop","ddot","ddox","ddo","ddop","ddex","dde","ddep","ddut","ddux","ddu","ddup","ddurx","ddur","ndit","ndix","ndi","ndip","ndiex","ndie","ndat","ndax","nda","ndap","ndot","ndox","ndo","ndop","ndex","nde","ndep","ndut","ndux","ndu","ndup","ndurx","ndur","hnit","hnix","hni","hnip","hniet","hniex","hnie","hniep","hnat","hnax","hna","hnap","hnuox","hnuo","hnot","hnox","hnop","hnex","hne","hnep","hnut","nit","nix","ni","nip","niex","nie","niep","nax","na","nap","nuox","nuo","nuop","not","nox","no","nop","nex","ne","nep","nut","nux","nu","nup","nurx","nur","hlit","hlix","hli","hlip","hliex","hlie","hliep","hlat","hlax","hla","hlap","hluox","hluo","hluop","hlox","hlo","hlop","hlex","hle","hlep","hlut","hlux","hlu","hlup","hlurx","hlur","hlyt","hlyx","hly","hlyp","hlyrx","hlyr","lit","lix","li","lip","liet","liex","lie","liep","lat","lax","la","lap","luot","luox","luo","luop","lot","lox","lo","lop","lex","le","lep","lut","lux","lu","lup","lurx","lur","lyt","lyx","ly","lyp","lyrx","lyr","git","gix","gi","gip","giet","giex","gie","giep","gat","gax","ga","gap","guot","guox","guo","guop","got","gox","go","gop","get","gex","ge","gep","gut","gux","gu","gup","gurx","gur","kit","kix","ki","kip","kiex","kie","kiep","kat"]});var LN=w((Txe,IN)=>{IN.exports=["kax","ka","kap","kuox","kuo","kuop","kot","kox","ko","kop","ket","kex","ke","kep","kut","kux","ku","kup","kurx","kur","ggit","ggix","ggi","ggiex","ggie","ggiep","ggat","ggax","gga","ggap","gguot","gguox","gguo","gguop","ggot","ggox","ggo","ggop","gget","ggex","gge","ggep","ggut","ggux","ggu","ggup","ggurx","ggur","mgiex","mgie","mgat","mgax","mga","mgap","mguox","mguo","mguop","mgot","mgox","mgo","mgop","mgex","mge","mgep","mgut","mgux","mgu","mgup","mgurx","mgur","hxit","hxix","hxi","hxip","hxiet","hxiex","hxie","hxiep","hxat","hxax","hxa","hxap","hxuot","hxuox","hxuo","hxuop","hxot","hxox","hxo","hxop","hxex","hxe","hxep","ngiex","ngie","ngiep","ngat","ngax","nga","ngap","nguot","nguox","nguo","ngot","ngox","ngo","ngop","ngex","nge","ngep","hit","hiex","hie","hat","hax","ha","hap","huot","huox","huo","huop","hot","hox","ho","hop","hex","he","hep","wat","wax","wa","wap","wuox","wuo","wuop","wox","wo","wop","wex","we","wep","zit","zix","zi","zip","ziex","zie","ziep","zat","zax","za","zap","zuox","zuo","zuop","zot","zox","zo","zop","zex","ze","zep","zut","zux","zu","zup","zurx","zur","zyt","zyx","zy","zyp","zyrx","zyr","cit","cix","ci","cip","ciet","ciex","cie","ciep","cat","cax","ca","cap","cuox","cuo","cuop","cot","cox","co","cop","cex","ce","cep","cut","cux","cu","cup","curx","cur","cyt","cyx","cy","cyp","cyrx","cyr","zzit","zzix","zzi","zzip","zziet","zziex","zzie","zziep","zzat","zzax","zza","zzap","zzox","zzo","zzop","zzex","zze","zzep","zzux","zzu","zzup","zzurx","zzur","zzyt","zzyx","zzy","zzyp","zzyrx","zzyr","nzit","nzix","nzi","nzip","nziex","nzie","nziep","nzat","nzax","nza","nzap","nzuox","nzuo","nzox","nzop","nzex","nze","nzux","nzu"]});var MN=w((kxe,FN)=>{FN.exports=["nzup","nzurx","nzur","nzyt","nzyx","nzy","nzyp","nzyrx","nzyr","sit","six","si","sip","siex","sie","siep","sat","sax","sa","sap","suox","suo","suop","sot","sox","so","sop","sex","se","sep","sut","sux","su","sup","surx","sur","syt","syx","sy","syp","syrx","syr","ssit","ssix","ssi","ssip","ssiex","ssie","ssiep","ssat","ssax","ssa","ssap","ssot","ssox","sso","ssop","ssex","sse","ssep","ssut","ssux","ssu","ssup","ssyt","ssyx","ssy","ssyp","ssyrx","ssyr","zhat","zhax","zha","zhap","zhuox","zhuo","zhuop","zhot","zhox","zho","zhop","zhet","zhex","zhe","zhep","zhut","zhux","zhu","zhup","zhurx","zhur","zhyt","zhyx","zhy","zhyp","zhyrx","zhyr","chat","chax","cha","chap","chuot","chuox","chuo","chuop","chot","chox","cho","chop","chet","chex","che","chep","chux","chu","chup","churx","chur","chyt","chyx","chy","chyp","chyrx","chyr","rrax","rra","rruox","rruo","rrot","rrox","rro","rrop","rret","rrex","rre","rrep","rrut","rrux","rru","rrup","rrurx","rrur","rryt","rryx","rry","rryp","rryrx","rryr","nrat","nrax","nra","nrap","nrox","nro","nrop","nret","nrex","nre","nrep","nrut","nrux","nru","nrup","nrurx","nrur","nryt","nryx","nry","nryp","nryrx","nryr","shat","shax","sha","shap","shuox","shuo","shuop","shot","shox","sho","shop","shet","shex","she","shep","shut","shux","shu","shup","shurx","shur","shyt","shyx","shy","shyp","shyrx","shyr","rat","rax","ra","rap","ruox","ruo","ruop","rot","rox","ro","rop","rex","re","rep","rut","rux","ru","rup","rurx","rur","ryt","ryx","ry","ryp","ryrx","ryr","jit","jix","ji","jip","jiet","jiex","jie","jiep","juot","juox","juo","juop","jot","jox","jo","jop","jut","jux","ju","jup","jurx","jur","jyt","jyx","jy","jyp","jyrx","jyr","qit","qix","qi","qip"]});var ON=w((Pxe,jN)=>{jN.exports=["qiet","qiex","qie","qiep","quot","quox","quo","quop","qot","qox","qo","qop","qut","qux","qu","qup","qurx","qur","qyt","qyx","qy","qyp","qyrx","qyr","jjit","jjix","jji","jjip","jjiet","jjiex","jjie","jjiep","jjuox","jjuo","jjuop","jjot","jjox","jjo","jjop","jjut","jjux","jju","jjup","jjurx","jjur","jjyt","jjyx","jjy","jjyp","njit","njix","nji","njip","njiet","njiex","njie","njiep","njuox","njuo","njot","njox","njo","njop","njux","nju","njup","njurx","njur","njyt","njyx","njy","njyp","njyrx","njyr","nyit","nyix","nyi","nyip","nyiet","nyiex","nyie","nyiep","nyuox","nyuo","nyuop","nyot","nyox","nyo","nyop","nyut","nyux","nyu","nyup","xit","xix","xi","xip","xiet","xiex","xie","xiep","xuox","xuo","xot","xox","xo","xop","xyt","xyx","xy","xyp","xyrx","xyr","yit","yix","yi","yip","yiet","yiex","yie","yiep","yuot","yuox","yuo","yuop","yot","yox","yo","yop","yut","yux","yu","yup","yurx","yur","yyt","yyx","yy","yyp","yyrx","yyr","[?]","[?]","[?]","Qot","Li","Kit","Nyip","Cyp","Ssi","Ggop","Gep","Mi","Hxit","Lyr","Bbut","Mop","Yo","Put","Hxuo","Tat","Ga","[?]","[?]","Ddur","Bur","Gguo","Nyop","Tu","Op","Jjut","Zot","Pyt","Hmo","Yit","Vur","Shy","Vep","Za","Jo","[?]","Jjy","Got","Jjie","Wo","Du","Shur","Lie","Cy","Cuop","Cip","Hxop","Shat","[?]","Shop","Che","Zziet","[?]","Ke","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var NN=w((Rxe,AN)=>{AN.exports=["ga","gag","gagg","gags","gan","ganj","ganh","gad","gal","galg","galm","galb","gals","galt","galp","galh","gam","gab","gabs","gas","gass","gang","gaj","gac","gak","gat","gap","gah","gae","gaeg","gaegg","gaegs","gaen","gaenj","gaenh","gaed","gael","gaelg","gaelm","gaelb","gaels","gaelt","gaelp","gaelh","gaem","gaeb","gaebs","gaes","gaess","gaeng","gaej","gaec","gaek","gaet","gaep","gaeh","gya","gyag","gyagg","gyags","gyan","gyanj","gyanh","gyad","gyal","gyalg","gyalm","gyalb","gyals","gyalt","gyalp","gyalh","gyam","gyab","gyabs","gyas","gyass","gyang","gyaj","gyac","gyak","gyat","gyap","gyah","gyae","gyaeg","gyaegg","gyaegs","gyaen","gyaenj","gyaenh","gyaed","gyael","gyaelg","gyaelm","gyaelb","gyaels","gyaelt","gyaelp","gyaelh","gyaem","gyaeb","gyaebs","gyaes","gyaess","gyaeng","gyaej","gyaec","gyaek","gyaet","gyaep","gyaeh","geo","geog","geogg","geogs","geon","geonj","geonh","geod","geol","geolg","geolm","geolb","geols","geolt","geolp","geolh","geom","geob","geobs","geos","geoss","geong","geoj","geoc","geok","geot","geop","geoh","ge","geg","gegg","gegs","gen","genj","genh","ged","gel","gelg","gelm","gelb","gels","gelt","gelp","gelh","gem","geb","gebs","ges","gess","geng","gej","gec","gek","get","gep","geh","gyeo","gyeog","gyeogg","gyeogs","gyeon","gyeonj","gyeonh","gyeod","gyeol","gyeolg","gyeolm","gyeolb","gyeols","gyeolt","gyeolp","gyeolh","gyeom","gyeob","gyeobs","gyeos","gyeoss","gyeong","gyeoj","gyeoc","gyeok","gyeot","gyeop","gyeoh","gye","gyeg","gyegg","gyegs","gyen","gyenj","gyenh","gyed","gyel","gyelg","gyelm","gyelb","gyels","gyelt","gyelp","gyelh","gyem","gyeb","gyebs","gyes","gyess","gyeng","gyej","gyec","gyek","gyet","gyep","gyeh","go","gog","gogg","gogs","gon","gonj","gonh","god","gol","golg","golm","golb","gols","golt","golp","golh","gom","gob","gobs","gos","goss","gong","goj","goc","gok","got","gop","goh","gwa","gwag","gwagg","gwags"]});var BN=w((_xe,HN)=>{HN.exports=["gwan","gwanj","gwanh","gwad","gwal","gwalg","gwalm","gwalb","gwals","gwalt","gwalp","gwalh","gwam","gwab","gwabs","gwas","gwass","gwang","gwaj","gwac","gwak","gwat","gwap","gwah","gwae","gwaeg","gwaegg","gwaegs","gwaen","gwaenj","gwaenh","gwaed","gwael","gwaelg","gwaelm","gwaelb","gwaels","gwaelt","gwaelp","gwaelh","gwaem","gwaeb","gwaebs","gwaes","gwaess","gwaeng","gwaej","gwaec","gwaek","gwaet","gwaep","gwaeh","goe","goeg","goegg","goegs","goen","goenj","goenh","goed","goel","goelg","goelm","goelb","goels","goelt","goelp","goelh","goem","goeb","goebs","goes","goess","goeng","goej","goec","goek","goet","goep","goeh","gyo","gyog","gyogg","gyogs","gyon","gyonj","gyonh","gyod","gyol","gyolg","gyolm","gyolb","gyols","gyolt","gyolp","gyolh","gyom","gyob","gyobs","gyos","gyoss","gyong","gyoj","gyoc","gyok","gyot","gyop","gyoh","gu","gug","gugg","gugs","gun","gunj","gunh","gud","gul","gulg","gulm","gulb","guls","gult","gulp","gulh","gum","gub","gubs","gus","guss","gung","guj","guc","guk","gut","gup","guh","gweo","gweog","gweogg","gweogs","gweon","gweonj","gweonh","gweod","gweol","gweolg","gweolm","gweolb","gweols","gweolt","gweolp","gweolh","gweom","gweob","gweobs","gweos","gweoss","gweong","gweoj","gweoc","gweok","gweot","gweop","gweoh","gwe","gweg","gwegg","gwegs","gwen","gwenj","gwenh","gwed","gwel","gwelg","gwelm","gwelb","gwels","gwelt","gwelp","gwelh","gwem","gweb","gwebs","gwes","gwess","gweng","gwej","gwec","gwek","gwet","gwep","gweh","gwi","gwig","gwigg","gwigs","gwin","gwinj","gwinh","gwid","gwil","gwilg","gwilm","gwilb","gwils","gwilt","gwilp","gwilh","gwim","gwib","gwibs","gwis","gwiss","gwing","gwij","gwic","gwik","gwit","gwip","gwih","gyu","gyug","gyugg","gyugs","gyun","gyunj","gyunh","gyud","gyul","gyulg","gyulm","gyulb","gyuls","gyult","gyulp","gyulh","gyum","gyub","gyubs","gyus","gyuss","gyung","gyuj","gyuc","gyuk","gyut","gyup","gyuh","geu","geug","geugg","geugs","geun","geunj","geunh","geud"]});var WN=w((Exe,qN)=>{qN.exports=["geul","geulg","geulm","geulb","geuls","geult","geulp","geulh","geum","geub","geubs","geus","geuss","geung","geuj","geuc","geuk","geut","geup","geuh","gyi","gyig","gyigg","gyigs","gyin","gyinj","gyinh","gyid","gyil","gyilg","gyilm","gyilb","gyils","gyilt","gyilp","gyilh","gyim","gyib","gyibs","gyis","gyiss","gying","gyij","gyic","gyik","gyit","gyip","gyih","gi","gig","gigg","gigs","gin","ginj","ginh","gid","gil","gilg","gilm","gilb","gils","gilt","gilp","gilh","gim","gib","gibs","gis","giss","ging","gij","gic","gik","git","gip","gih","gga","ggag","ggagg","ggags","ggan","gganj","gganh","ggad","ggal","ggalg","ggalm","ggalb","ggals","ggalt","ggalp","ggalh","ggam","ggab","ggabs","ggas","ggass","ggang","ggaj","ggac","ggak","ggat","ggap","ggah","ggae","ggaeg","ggaegg","ggaegs","ggaen","ggaenj","ggaenh","ggaed","ggael","ggaelg","ggaelm","ggaelb","ggaels","ggaelt","ggaelp","ggaelh","ggaem","ggaeb","ggaebs","ggaes","ggaess","ggaeng","ggaej","ggaec","ggaek","ggaet","ggaep","ggaeh","ggya","ggyag","ggyagg","ggyags","ggyan","ggyanj","ggyanh","ggyad","ggyal","ggyalg","ggyalm","ggyalb","ggyals","ggyalt","ggyalp","ggyalh","ggyam","ggyab","ggyabs","ggyas","ggyass","ggyang","ggyaj","ggyac","ggyak","ggyat","ggyap","ggyah","ggyae","ggyaeg","ggyaegg","ggyaegs","ggyaen","ggyaenj","ggyaenh","ggyaed","ggyael","ggyaelg","ggyaelm","ggyaelb","ggyaels","ggyaelt","ggyaelp","ggyaelh","ggyaem","ggyaeb","ggyaebs","ggyaes","ggyaess","ggyaeng","ggyaej","ggyaec","ggyaek","ggyaet","ggyaep","ggyaeh","ggeo","ggeog","ggeogg","ggeogs","ggeon","ggeonj","ggeonh","ggeod","ggeol","ggeolg","ggeolm","ggeolb","ggeols","ggeolt","ggeolp","ggeolh","ggeom","ggeob","ggeobs","ggeos","ggeoss","ggeong","ggeoj","ggeoc","ggeok","ggeot","ggeop","ggeoh","gge","ggeg","ggegg","ggegs","ggen","ggenj","ggenh","gged","ggel","ggelg","ggelm","ggelb","ggels","ggelt","ggelp","ggelh","ggem","ggeb","ggebs","gges","ggess","ggeng","ggej","ggec","ggek","gget","ggep","ggeh","ggyeo","ggyeog","ggyeogg","ggyeogs","ggyeon","ggyeonj","ggyeonh","ggyeod","ggyeol","ggyeolg","ggyeolm","ggyeolb"]});var ZN=w((Ixe,YN)=>{YN.exports=["ggyeols","ggyeolt","ggyeolp","ggyeolh","ggyeom","ggyeob","ggyeobs","ggyeos","ggyeoss","ggyeong","ggyeoj","ggyeoc","ggyeok","ggyeot","ggyeop","ggyeoh","ggye","ggyeg","ggyegg","ggyegs","ggyen","ggyenj","ggyenh","ggyed","ggyel","ggyelg","ggyelm","ggyelb","ggyels","ggyelt","ggyelp","ggyelh","ggyem","ggyeb","ggyebs","ggyes","ggyess","ggyeng","ggyej","ggyec","ggyek","ggyet","ggyep","ggyeh","ggo","ggog","ggogg","ggogs","ggon","ggonj","ggonh","ggod","ggol","ggolg","ggolm","ggolb","ggols","ggolt","ggolp","ggolh","ggom","ggob","ggobs","ggos","ggoss","ggong","ggoj","ggoc","ggok","ggot","ggop","ggoh","ggwa","ggwag","ggwagg","ggwags","ggwan","ggwanj","ggwanh","ggwad","ggwal","ggwalg","ggwalm","ggwalb","ggwals","ggwalt","ggwalp","ggwalh","ggwam","ggwab","ggwabs","ggwas","ggwass","ggwang","ggwaj","ggwac","ggwak","ggwat","ggwap","ggwah","ggwae","ggwaeg","ggwaegg","ggwaegs","ggwaen","ggwaenj","ggwaenh","ggwaed","ggwael","ggwaelg","ggwaelm","ggwaelb","ggwaels","ggwaelt","ggwaelp","ggwaelh","ggwaem","ggwaeb","ggwaebs","ggwaes","ggwaess","ggwaeng","ggwaej","ggwaec","ggwaek","ggwaet","ggwaep","ggwaeh","ggoe","ggoeg","ggoegg","ggoegs","ggoen","ggoenj","ggoenh","ggoed","ggoel","ggoelg","ggoelm","ggoelb","ggoels","ggoelt","ggoelp","ggoelh","ggoem","ggoeb","ggoebs","ggoes","ggoess","ggoeng","ggoej","ggoec","ggoek","ggoet","ggoep","ggoeh","ggyo","ggyog","ggyogg","ggyogs","ggyon","ggyonj","ggyonh","ggyod","ggyol","ggyolg","ggyolm","ggyolb","ggyols","ggyolt","ggyolp","ggyolh","ggyom","ggyob","ggyobs","ggyos","ggyoss","ggyong","ggyoj","ggyoc","ggyok","ggyot","ggyop","ggyoh","ggu","ggug","ggugg","ggugs","ggun","ggunj","ggunh","ggud","ggul","ggulg","ggulm","ggulb","gguls","ggult","ggulp","ggulh","ggum","ggub","ggubs","ggus","gguss","ggung","gguj","gguc","gguk","ggut","ggup","gguh","ggweo","ggweog","ggweogg","ggweogs","ggweon","ggweonj","ggweonh","ggweod","ggweol","ggweolg","ggweolm","ggweolb","ggweols","ggweolt","ggweolp","ggweolh","ggweom","ggweob","ggweobs","ggweos","ggweoss","ggweong","ggweoj","ggweoc","ggweok","ggweot","ggweop","ggweoh","ggwe","ggweg","ggwegg","ggwegs","ggwen","ggwenj","ggwenh","ggwed","ggwel","ggwelg","ggwelm","ggwelb","ggwels","ggwelt","ggwelp","ggwelh"]});var $N=w((Lxe,JN)=>{JN.exports=["ggwem","ggweb","ggwebs","ggwes","ggwess","ggweng","ggwej","ggwec","ggwek","ggwet","ggwep","ggweh","ggwi","ggwig","ggwigg","ggwigs","ggwin","ggwinj","ggwinh","ggwid","ggwil","ggwilg","ggwilm","ggwilb","ggwils","ggwilt","ggwilp","ggwilh","ggwim","ggwib","ggwibs","ggwis","ggwiss","ggwing","ggwij","ggwic","ggwik","ggwit","ggwip","ggwih","ggyu","ggyug","ggyugg","ggyugs","ggyun","ggyunj","ggyunh","ggyud","ggyul","ggyulg","ggyulm","ggyulb","ggyuls","ggyult","ggyulp","ggyulh","ggyum","ggyub","ggyubs","ggyus","ggyuss","ggyung","ggyuj","ggyuc","ggyuk","ggyut","ggyup","ggyuh","ggeu","ggeug","ggeugg","ggeugs","ggeun","ggeunj","ggeunh","ggeud","ggeul","ggeulg","ggeulm","ggeulb","ggeuls","ggeult","ggeulp","ggeulh","ggeum","ggeub","ggeubs","ggeus","ggeuss","ggeung","ggeuj","ggeuc","ggeuk","ggeut","ggeup","ggeuh","ggyi","ggyig","ggyigg","ggyigs","ggyin","ggyinj","ggyinh","ggyid","ggyil","ggyilg","ggyilm","ggyilb","ggyils","ggyilt","ggyilp","ggyilh","ggyim","ggyib","ggyibs","ggyis","ggyiss","ggying","ggyij","ggyic","ggyik","ggyit","ggyip","ggyih","ggi","ggig","ggigg","ggigs","ggin","gginj","gginh","ggid","ggil","ggilg","ggilm","ggilb","ggils","ggilt","ggilp","ggilh","ggim","ggib","ggibs","ggis","ggiss","gging","ggij","ggic","ggik","ggit","ggip","ggih","na","nag","nagg","nags","nan","nanj","nanh","nad","nal","nalg","nalm","nalb","nals","nalt","nalp","nalh","nam","nab","nabs","nas","nass","nang","naj","nac","nak","nat","nap","nah","nae","naeg","naegg","naegs","naen","naenj","naenh","naed","nael","naelg","naelm","naelb","naels","naelt","naelp","naelh","naem","naeb","naebs","naes","naess","naeng","naej","naec","naek","naet","naep","naeh","nya","nyag","nyagg","nyags","nyan","nyanj","nyanh","nyad","nyal","nyalg","nyalm","nyalb","nyals","nyalt","nyalp","nyalh","nyam","nyab","nyabs","nyas","nyass","nyang","nyaj","nyac","nyak","nyat","nyap","nyah","nyae","nyaeg","nyaegg","nyaegs","nyaen","nyaenj","nyaenh","nyaed","nyael","nyaelg","nyaelm","nyaelb","nyaels","nyaelt","nyaelp","nyaelh","nyaem","nyaeb","nyaebs","nyaes"]});var XN=w((Fxe,UN)=>{UN.exports=["nyaess","nyaeng","nyaej","nyaec","nyaek","nyaet","nyaep","nyaeh","neo","neog","neogg","neogs","neon","neonj","neonh","neod","neol","neolg","neolm","neolb","neols","neolt","neolp","neolh","neom","neob","neobs","neos","neoss","neong","neoj","neoc","neok","neot","neop","neoh","ne","neg","negg","negs","nen","nenj","nenh","ned","nel","nelg","nelm","nelb","nels","nelt","nelp","nelh","nem","neb","nebs","nes","ness","neng","nej","nec","nek","net","nep","neh","nyeo","nyeog","nyeogg","nyeogs","nyeon","nyeonj","nyeonh","nyeod","nyeol","nyeolg","nyeolm","nyeolb","nyeols","nyeolt","nyeolp","nyeolh","nyeom","nyeob","nyeobs","nyeos","nyeoss","nyeong","nyeoj","nyeoc","nyeok","nyeot","nyeop","nyeoh","nye","nyeg","nyegg","nyegs","nyen","nyenj","nyenh","nyed","nyel","nyelg","nyelm","nyelb","nyels","nyelt","nyelp","nyelh","nyem","nyeb","nyebs","nyes","nyess","nyeng","nyej","nyec","nyek","nyet","nyep","nyeh","no","nog","nogg","nogs","non","nonj","nonh","nod","nol","nolg","nolm","nolb","nols","nolt","nolp","nolh","nom","nob","nobs","nos","noss","nong","noj","noc","nok","not","nop","noh","nwa","nwag","nwagg","nwags","nwan","nwanj","nwanh","nwad","nwal","nwalg","nwalm","nwalb","nwals","nwalt","nwalp","nwalh","nwam","nwab","nwabs","nwas","nwass","nwang","nwaj","nwac","nwak","nwat","nwap","nwah","nwae","nwaeg","nwaegg","nwaegs","nwaen","nwaenj","nwaenh","nwaed","nwael","nwaelg","nwaelm","nwaelb","nwaels","nwaelt","nwaelp","nwaelh","nwaem","nwaeb","nwaebs","nwaes","nwaess","nwaeng","nwaej","nwaec","nwaek","nwaet","nwaep","nwaeh","noe","noeg","noegg","noegs","noen","noenj","noenh","noed","noel","noelg","noelm","noelb","noels","noelt","noelp","noelh","noem","noeb","noebs","noes","noess","noeng","noej","noec","noek","noet","noep","noeh","nyo","nyog","nyogg","nyogs","nyon","nyonj","nyonh","nyod","nyol","nyolg","nyolm","nyolb","nyols","nyolt","nyolp","nyolh","nyom","nyob","nyobs","nyos","nyoss","nyong","nyoj","nyoc"]});var zN=w((Mxe,GN)=>{GN.exports=["nyok","nyot","nyop","nyoh","nu","nug","nugg","nugs","nun","nunj","nunh","nud","nul","nulg","nulm","nulb","nuls","nult","nulp","nulh","num","nub","nubs","nus","nuss","nung","nuj","nuc","nuk","nut","nup","nuh","nweo","nweog","nweogg","nweogs","nweon","nweonj","nweonh","nweod","nweol","nweolg","nweolm","nweolb","nweols","nweolt","nweolp","nweolh","nweom","nweob","nweobs","nweos","nweoss","nweong","nweoj","nweoc","nweok","nweot","nweop","nweoh","nwe","nweg","nwegg","nwegs","nwen","nwenj","nwenh","nwed","nwel","nwelg","nwelm","nwelb","nwels","nwelt","nwelp","nwelh","nwem","nweb","nwebs","nwes","nwess","nweng","nwej","nwec","nwek","nwet","nwep","nweh","nwi","nwig","nwigg","nwigs","nwin","nwinj","nwinh","nwid","nwil","nwilg","nwilm","nwilb","nwils","nwilt","nwilp","nwilh","nwim","nwib","nwibs","nwis","nwiss","nwing","nwij","nwic","nwik","nwit","nwip","nwih","nyu","nyug","nyugg","nyugs","nyun","nyunj","nyunh","nyud","nyul","nyulg","nyulm","nyulb","nyuls","nyult","nyulp","nyulh","nyum","nyub","nyubs","nyus","nyuss","nyung","nyuj","nyuc","nyuk","nyut","nyup","nyuh","neu","neug","neugg","neugs","neun","neunj","neunh","neud","neul","neulg","neulm","neulb","neuls","neult","neulp","neulh","neum","neub","neubs","neus","neuss","neung","neuj","neuc","neuk","neut","neup","neuh","nyi","nyig","nyigg","nyigs","nyin","nyinj","nyinh","nyid","nyil","nyilg","nyilm","nyilb","nyils","nyilt","nyilp","nyilh","nyim","nyib","nyibs","nyis","nyiss","nying","nyij","nyic","nyik","nyit","nyip","nyih","ni","nig","nigg","nigs","nin","ninj","ninh","nid","nil","nilg","nilm","nilb","nils","nilt","nilp","nilh","nim","nib","nibs","nis","niss","ning","nij","nic","nik","nit","nip","nih","da","dag","dagg","dags","dan","danj","danh","dad","dal","dalg","dalm","dalb","dals","dalt","dalp","dalh","dam","dab","dabs","das","dass","dang","daj","dac","dak","dat","dap","dah"]});var QN=w((jxe,KN)=>{KN.exports=["dae","daeg","daegg","daegs","daen","daenj","daenh","daed","dael","daelg","daelm","daelb","daels","daelt","daelp","daelh","daem","daeb","daebs","daes","daess","daeng","daej","daec","daek","daet","daep","daeh","dya","dyag","dyagg","dyags","dyan","dyanj","dyanh","dyad","dyal","dyalg","dyalm","dyalb","dyals","dyalt","dyalp","dyalh","dyam","dyab","dyabs","dyas","dyass","dyang","dyaj","dyac","dyak","dyat","dyap","dyah","dyae","dyaeg","dyaegg","dyaegs","dyaen","dyaenj","dyaenh","dyaed","dyael","dyaelg","dyaelm","dyaelb","dyaels","dyaelt","dyaelp","dyaelh","dyaem","dyaeb","dyaebs","dyaes","dyaess","dyaeng","dyaej","dyaec","dyaek","dyaet","dyaep","dyaeh","deo","deog","deogg","deogs","deon","deonj","deonh","deod","deol","deolg","deolm","deolb","deols","deolt","deolp","deolh","deom","deob","deobs","deos","deoss","deong","deoj","deoc","deok","deot","deop","deoh","de","deg","degg","degs","den","denj","denh","ded","del","delg","delm","delb","dels","delt","delp","delh","dem","deb","debs","des","dess","deng","dej","dec","dek","det","dep","deh","dyeo","dyeog","dyeogg","dyeogs","dyeon","dyeonj","dyeonh","dyeod","dyeol","dyeolg","dyeolm","dyeolb","dyeols","dyeolt","dyeolp","dyeolh","dyeom","dyeob","dyeobs","dyeos","dyeoss","dyeong","dyeoj","dyeoc","dyeok","dyeot","dyeop","dyeoh","dye","dyeg","dyegg","dyegs","dyen","dyenj","dyenh","dyed","dyel","dyelg","dyelm","dyelb","dyels","dyelt","dyelp","dyelh","dyem","dyeb","dyebs","dyes","dyess","dyeng","dyej","dyec","dyek","dyet","dyep","dyeh","do","dog","dogg","dogs","don","donj","donh","dod","dol","dolg","dolm","dolb","dols","dolt","dolp","dolh","dom","dob","dobs","dos","doss","dong","doj","doc","dok","dot","dop","doh","dwa","dwag","dwagg","dwags","dwan","dwanj","dwanh","dwad","dwal","dwalg","dwalm","dwalb","dwals","dwalt","dwalp","dwalh","dwam","dwab","dwabs","dwas","dwass","dwang","dwaj","dwac","dwak","dwat","dwap","dwah","dwae","dwaeg","dwaegg","dwaegs"]});var eH=w((Oxe,VN)=>{VN.exports=["dwaen","dwaenj","dwaenh","dwaed","dwael","dwaelg","dwaelm","dwaelb","dwaels","dwaelt","dwaelp","dwaelh","dwaem","dwaeb","dwaebs","dwaes","dwaess","dwaeng","dwaej","dwaec","dwaek","dwaet","dwaep","dwaeh","doe","doeg","doegg","doegs","doen","doenj","doenh","doed","doel","doelg","doelm","doelb","doels","doelt","doelp","doelh","doem","doeb","doebs","does","doess","doeng","doej","doec","doek","doet","doep","doeh","dyo","dyog","dyogg","dyogs","dyon","dyonj","dyonh","dyod","dyol","dyolg","dyolm","dyolb","dyols","dyolt","dyolp","dyolh","dyom","dyob","dyobs","dyos","dyoss","dyong","dyoj","dyoc","dyok","dyot","dyop","dyoh","du","dug","dugg","dugs","dun","dunj","dunh","dud","dul","dulg","dulm","dulb","duls","dult","dulp","dulh","dum","dub","dubs","dus","duss","dung","duj","duc","duk","dut","dup","duh","dweo","dweog","dweogg","dweogs","dweon","dweonj","dweonh","dweod","dweol","dweolg","dweolm","dweolb","dweols","dweolt","dweolp","dweolh","dweom","dweob","dweobs","dweos","dweoss","dweong","dweoj","dweoc","dweok","dweot","dweop","dweoh","dwe","dweg","dwegg","dwegs","dwen","dwenj","dwenh","dwed","dwel","dwelg","dwelm","dwelb","dwels","dwelt","dwelp","dwelh","dwem","dweb","dwebs","dwes","dwess","dweng","dwej","dwec","dwek","dwet","dwep","dweh","dwi","dwig","dwigg","dwigs","dwin","dwinj","dwinh","dwid","dwil","dwilg","dwilm","dwilb","dwils","dwilt","dwilp","dwilh","dwim","dwib","dwibs","dwis","dwiss","dwing","dwij","dwic","dwik","dwit","dwip","dwih","dyu","dyug","dyugg","dyugs","dyun","dyunj","dyunh","dyud","dyul","dyulg","dyulm","dyulb","dyuls","dyult","dyulp","dyulh","dyum","dyub","dyubs","dyus","dyuss","dyung","dyuj","dyuc","dyuk","dyut","dyup","dyuh","deu","deug","deugg","deugs","deun","deunj","deunh","deud","deul","deulg","deulm","deulb","deuls","deult","deulp","deulh","deum","deub","deubs","deus","deuss","deung","deuj","deuc","deuk","deut","deup","deuh","dyi","dyig","dyigg","dyigs","dyin","dyinj","dyinh","dyid"]});var iH=w((Axe,tH)=>{tH.exports=["dyil","dyilg","dyilm","dyilb","dyils","dyilt","dyilp","dyilh","dyim","dyib","dyibs","dyis","dyiss","dying","dyij","dyic","dyik","dyit","dyip","dyih","di","dig","digg","digs","din","dinj","dinh","did","dil","dilg","dilm","dilb","dils","dilt","dilp","dilh","dim","dib","dibs","dis","diss","ding","dij","dic","dik","dit","dip","dih","dda","ddag","ddagg","ddags","ddan","ddanj","ddanh","ddad","ddal","ddalg","ddalm","ddalb","ddals","ddalt","ddalp","ddalh","ddam","ddab","ddabs","ddas","ddass","ddang","ddaj","ddac","ddak","ddat","ddap","ddah","ddae","ddaeg","ddaegg","ddaegs","ddaen","ddaenj","ddaenh","ddaed","ddael","ddaelg","ddaelm","ddaelb","ddaels","ddaelt","ddaelp","ddaelh","ddaem","ddaeb","ddaebs","ddaes","ddaess","ddaeng","ddaej","ddaec","ddaek","ddaet","ddaep","ddaeh","ddya","ddyag","ddyagg","ddyags","ddyan","ddyanj","ddyanh","ddyad","ddyal","ddyalg","ddyalm","ddyalb","ddyals","ddyalt","ddyalp","ddyalh","ddyam","ddyab","ddyabs","ddyas","ddyass","ddyang","ddyaj","ddyac","ddyak","ddyat","ddyap","ddyah","ddyae","ddyaeg","ddyaegg","ddyaegs","ddyaen","ddyaenj","ddyaenh","ddyaed","ddyael","ddyaelg","ddyaelm","ddyaelb","ddyaels","ddyaelt","ddyaelp","ddyaelh","ddyaem","ddyaeb","ddyaebs","ddyaes","ddyaess","ddyaeng","ddyaej","ddyaec","ddyaek","ddyaet","ddyaep","ddyaeh","ddeo","ddeog","ddeogg","ddeogs","ddeon","ddeonj","ddeonh","ddeod","ddeol","ddeolg","ddeolm","ddeolb","ddeols","ddeolt","ddeolp","ddeolh","ddeom","ddeob","ddeobs","ddeos","ddeoss","ddeong","ddeoj","ddeoc","ddeok","ddeot","ddeop","ddeoh","dde","ddeg","ddegg","ddegs","dden","ddenj","ddenh","dded","ddel","ddelg","ddelm","ddelb","ddels","ddelt","ddelp","ddelh","ddem","ddeb","ddebs","ddes","ddess","ddeng","ddej","ddec","ddek","ddet","ddep","ddeh","ddyeo","ddyeog","ddyeogg","ddyeogs","ddyeon","ddyeonj","ddyeonh","ddyeod","ddyeol","ddyeolg","ddyeolm","ddyeolb","ddyeols","ddyeolt","ddyeolp","ddyeolh","ddyeom","ddyeob","ddyeobs","ddyeos","ddyeoss","ddyeong","ddyeoj","ddyeoc","ddyeok","ddyeot","ddyeop","ddyeoh","ddye","ddyeg","ddyegg","ddyegs","ddyen","ddyenj","ddyenh","ddyed","ddyel","ddyelg","ddyelm","ddyelb"]});var rH=w((Nxe,nH)=>{nH.exports=["ddyels","ddyelt","ddyelp","ddyelh","ddyem","ddyeb","ddyebs","ddyes","ddyess","ddyeng","ddyej","ddyec","ddyek","ddyet","ddyep","ddyeh","ddo","ddog","ddogg","ddogs","ddon","ddonj","ddonh","ddod","ddol","ddolg","ddolm","ddolb","ddols","ddolt","ddolp","ddolh","ddom","ddob","ddobs","ddos","ddoss","ddong","ddoj","ddoc","ddok","ddot","ddop","ddoh","ddwa","ddwag","ddwagg","ddwags","ddwan","ddwanj","ddwanh","ddwad","ddwal","ddwalg","ddwalm","ddwalb","ddwals","ddwalt","ddwalp","ddwalh","ddwam","ddwab","ddwabs","ddwas","ddwass","ddwang","ddwaj","ddwac","ddwak","ddwat","ddwap","ddwah","ddwae","ddwaeg","ddwaegg","ddwaegs","ddwaen","ddwaenj","ddwaenh","ddwaed","ddwael","ddwaelg","ddwaelm","ddwaelb","ddwaels","ddwaelt","ddwaelp","ddwaelh","ddwaem","ddwaeb","ddwaebs","ddwaes","ddwaess","ddwaeng","ddwaej","ddwaec","ddwaek","ddwaet","ddwaep","ddwaeh","ddoe","ddoeg","ddoegg","ddoegs","ddoen","ddoenj","ddoenh","ddoed","ddoel","ddoelg","ddoelm","ddoelb","ddoels","ddoelt","ddoelp","ddoelh","ddoem","ddoeb","ddoebs","ddoes","ddoess","ddoeng","ddoej","ddoec","ddoek","ddoet","ddoep","ddoeh","ddyo","ddyog","ddyogg","ddyogs","ddyon","ddyonj","ddyonh","ddyod","ddyol","ddyolg","ddyolm","ddyolb","ddyols","ddyolt","ddyolp","ddyolh","ddyom","ddyob","ddyobs","ddyos","ddyoss","ddyong","ddyoj","ddyoc","ddyok","ddyot","ddyop","ddyoh","ddu","ddug","ddugg","ddugs","ddun","ddunj","ddunh","ddud","ddul","ddulg","ddulm","ddulb","dduls","ddult","ddulp","ddulh","ddum","ddub","ddubs","ddus","dduss","ddung","dduj","dduc","dduk","ddut","ddup","dduh","ddweo","ddweog","ddweogg","ddweogs","ddweon","ddweonj","ddweonh","ddweod","ddweol","ddweolg","ddweolm","ddweolb","ddweols","ddweolt","ddweolp","ddweolh","ddweom","ddweob","ddweobs","ddweos","ddweoss","ddweong","ddweoj","ddweoc","ddweok","ddweot","ddweop","ddweoh","ddwe","ddweg","ddwegg","ddwegs","ddwen","ddwenj","ddwenh","ddwed","ddwel","ddwelg","ddwelm","ddwelb","ddwels","ddwelt","ddwelp","ddwelh","ddwem","ddweb","ddwebs","ddwes","ddwess","ddweng","ddwej","ddwec","ddwek","ddwet","ddwep","ddweh","ddwi","ddwig","ddwigg","ddwigs","ddwin","ddwinj","ddwinh","ddwid","ddwil","ddwilg","ddwilm","ddwilb","ddwils","ddwilt","ddwilp","ddwilh"]});var sH=w((Hxe,oH)=>{oH.exports=["ddwim","ddwib","ddwibs","ddwis","ddwiss","ddwing","ddwij","ddwic","ddwik","ddwit","ddwip","ddwih","ddyu","ddyug","ddyugg","ddyugs","ddyun","ddyunj","ddyunh","ddyud","ddyul","ddyulg","ddyulm","ddyulb","ddyuls","ddyult","ddyulp","ddyulh","ddyum","ddyub","ddyubs","ddyus","ddyuss","ddyung","ddyuj","ddyuc","ddyuk","ddyut","ddyup","ddyuh","ddeu","ddeug","ddeugg","ddeugs","ddeun","ddeunj","ddeunh","ddeud","ddeul","ddeulg","ddeulm","ddeulb","ddeuls","ddeult","ddeulp","ddeulh","ddeum","ddeub","ddeubs","ddeus","ddeuss","ddeung","ddeuj","ddeuc","ddeuk","ddeut","ddeup","ddeuh","ddyi","ddyig","ddyigg","ddyigs","ddyin","ddyinj","ddyinh","ddyid","ddyil","ddyilg","ddyilm","ddyilb","ddyils","ddyilt","ddyilp","ddyilh","ddyim","ddyib","ddyibs","ddyis","ddyiss","ddying","ddyij","ddyic","ddyik","ddyit","ddyip","ddyih","ddi","ddig","ddigg","ddigs","ddin","ddinj","ddinh","ddid","ddil","ddilg","ddilm","ddilb","ddils","ddilt","ddilp","ddilh","ddim","ddib","ddibs","ddis","ddiss","dding","ddij","ddic","ddik","ddit","ddip","ddih","ra","rag","ragg","rags","ran","ranj","ranh","rad","ral","ralg","ralm","ralb","rals","ralt","ralp","ralh","ram","rab","rabs","ras","rass","rang","raj","rac","rak","rat","rap","rah","rae","raeg","raegg","raegs","raen","raenj","raenh","raed","rael","raelg","raelm","raelb","raels","raelt","raelp","raelh","raem","raeb","raebs","raes","raess","raeng","raej","raec","raek","raet","raep","raeh","rya","ryag","ryagg","ryags","ryan","ryanj","ryanh","ryad","ryal","ryalg","ryalm","ryalb","ryals","ryalt","ryalp","ryalh","ryam","ryab","ryabs","ryas","ryass","ryang","ryaj","ryac","ryak","ryat","ryap","ryah","ryae","ryaeg","ryaegg","ryaegs","ryaen","ryaenj","ryaenh","ryaed","ryael","ryaelg","ryaelm","ryaelb","ryaels","ryaelt","ryaelp","ryaelh","ryaem","ryaeb","ryaebs","ryaes","ryaess","ryaeng","ryaej","ryaec","ryaek","ryaet","ryaep","ryaeh","reo","reog","reogg","reogs","reon","reonj","reonh","reod","reol","reolg","reolm","reolb","reols","reolt","reolp","reolh","reom","reob","reobs","reos"]});var lH=w((Bxe,aH)=>{aH.exports=["reoss","reong","reoj","reoc","reok","reot","reop","reoh","re","reg","regg","regs","ren","renj","renh","red","rel","relg","relm","relb","rels","relt","relp","relh","rem","reb","rebs","res","ress","reng","rej","rec","rek","ret","rep","reh","ryeo","ryeog","ryeogg","ryeogs","ryeon","ryeonj","ryeonh","ryeod","ryeol","ryeolg","ryeolm","ryeolb","ryeols","ryeolt","ryeolp","ryeolh","ryeom","ryeob","ryeobs","ryeos","ryeoss","ryeong","ryeoj","ryeoc","ryeok","ryeot","ryeop","ryeoh","rye","ryeg","ryegg","ryegs","ryen","ryenj","ryenh","ryed","ryel","ryelg","ryelm","ryelb","ryels","ryelt","ryelp","ryelh","ryem","ryeb","ryebs","ryes","ryess","ryeng","ryej","ryec","ryek","ryet","ryep","ryeh","ro","rog","rogg","rogs","ron","ronj","ronh","rod","rol","rolg","rolm","rolb","rols","rolt","rolp","rolh","rom","rob","robs","ros","ross","rong","roj","roc","rok","rot","rop","roh","rwa","rwag","rwagg","rwags","rwan","rwanj","rwanh","rwad","rwal","rwalg","rwalm","rwalb","rwals","rwalt","rwalp","rwalh","rwam","rwab","rwabs","rwas","rwass","rwang","rwaj","rwac","rwak","rwat","rwap","rwah","rwae","rwaeg","rwaegg","rwaegs","rwaen","rwaenj","rwaenh","rwaed","rwael","rwaelg","rwaelm","rwaelb","rwaels","rwaelt","rwaelp","rwaelh","rwaem","rwaeb","rwaebs","rwaes","rwaess","rwaeng","rwaej","rwaec","rwaek","rwaet","rwaep","rwaeh","roe","roeg","roegg","roegs","roen","roenj","roenh","roed","roel","roelg","roelm","roelb","roels","roelt","roelp","roelh","roem","roeb","roebs","roes","roess","roeng","roej","roec","roek","roet","roep","roeh","ryo","ryog","ryogg","ryogs","ryon","ryonj","ryonh","ryod","ryol","ryolg","ryolm","ryolb","ryols","ryolt","ryolp","ryolh","ryom","ryob","ryobs","ryos","ryoss","ryong","ryoj","ryoc","ryok","ryot","ryop","ryoh","ru","rug","rugg","rugs","run","runj","runh","rud","rul","rulg","rulm","rulb","ruls","rult","rulp","rulh","rum","rub","rubs","rus","russ","rung","ruj","ruc"]});var cH=w((qxe,uH)=>{uH.exports=["ruk","rut","rup","ruh","rweo","rweog","rweogg","rweogs","rweon","rweonj","rweonh","rweod","rweol","rweolg","rweolm","rweolb","rweols","rweolt","rweolp","rweolh","rweom","rweob","rweobs","rweos","rweoss","rweong","rweoj","rweoc","rweok","rweot","rweop","rweoh","rwe","rweg","rwegg","rwegs","rwen","rwenj","rwenh","rwed","rwel","rwelg","rwelm","rwelb","rwels","rwelt","rwelp","rwelh","rwem","rweb","rwebs","rwes","rwess","rweng","rwej","rwec","rwek","rwet","rwep","rweh","rwi","rwig","rwigg","rwigs","rwin","rwinj","rwinh","rwid","rwil","rwilg","rwilm","rwilb","rwils","rwilt","rwilp","rwilh","rwim","rwib","rwibs","rwis","rwiss","rwing","rwij","rwic","rwik","rwit","rwip","rwih","ryu","ryug","ryugg","ryugs","ryun","ryunj","ryunh","ryud","ryul","ryulg","ryulm","ryulb","ryuls","ryult","ryulp","ryulh","ryum","ryub","ryubs","ryus","ryuss","ryung","ryuj","ryuc","ryuk","ryut","ryup","ryuh","reu","reug","reugg","reugs","reun","reunj","reunh","reud","reul","reulg","reulm","reulb","reuls","reult","reulp","reulh","reum","reub","reubs","reus","reuss","reung","reuj","reuc","reuk","reut","reup","reuh","ryi","ryig","ryigg","ryigs","ryin","ryinj","ryinh","ryid","ryil","ryilg","ryilm","ryilb","ryils","ryilt","ryilp","ryilh","ryim","ryib","ryibs","ryis","ryiss","rying","ryij","ryic","ryik","ryit","ryip","ryih","ri","rig","rigg","rigs","rin","rinj","rinh","rid","ril","rilg","rilm","rilb","rils","rilt","rilp","rilh","rim","rib","ribs","ris","riss","ring","rij","ric","rik","rit","rip","rih","ma","mag","magg","mags","man","manj","manh","mad","mal","malg","malm","malb","mals","malt","malp","malh","mam","mab","mabs","mas","mass","mang","maj","mac","mak","mat","map","mah","mae","maeg","maegg","maegs","maen","maenj","maenh","maed","mael","maelg","maelm","maelb","maels","maelt","maelp","maelh","maem","maeb","maebs","maes","maess","maeng","maej","maec","maek","maet","maep","maeh"]});var hH=w((Wxe,dH)=>{dH.exports=["mya","myag","myagg","myags","myan","myanj","myanh","myad","myal","myalg","myalm","myalb","myals","myalt","myalp","myalh","myam","myab","myabs","myas","myass","myang","myaj","myac","myak","myat","myap","myah","myae","myaeg","myaegg","myaegs","myaen","myaenj","myaenh","myaed","myael","myaelg","myaelm","myaelb","myaels","myaelt","myaelp","myaelh","myaem","myaeb","myaebs","myaes","myaess","myaeng","myaej","myaec","myaek","myaet","myaep","myaeh","meo","meog","meogg","meogs","meon","meonj","meonh","meod","meol","meolg","meolm","meolb","meols","meolt","meolp","meolh","meom","meob","meobs","meos","meoss","meong","meoj","meoc","meok","meot","meop","meoh","me","meg","megg","megs","men","menj","menh","med","mel","melg","melm","melb","mels","melt","melp","melh","mem","meb","mebs","mes","mess","meng","mej","mec","mek","met","mep","meh","myeo","myeog","myeogg","myeogs","myeon","myeonj","myeonh","myeod","myeol","myeolg","myeolm","myeolb","myeols","myeolt","myeolp","myeolh","myeom","myeob","myeobs","myeos","myeoss","myeong","myeoj","myeoc","myeok","myeot","myeop","myeoh","mye","myeg","myegg","myegs","myen","myenj","myenh","myed","myel","myelg","myelm","myelb","myels","myelt","myelp","myelh","myem","myeb","myebs","myes","myess","myeng","myej","myec","myek","myet","myep","myeh","mo","mog","mogg","mogs","mon","monj","monh","mod","mol","molg","molm","molb","mols","molt","molp","molh","mom","mob","mobs","mos","moss","mong","moj","moc","mok","mot","mop","moh","mwa","mwag","mwagg","mwags","mwan","mwanj","mwanh","mwad","mwal","mwalg","mwalm","mwalb","mwals","mwalt","mwalp","mwalh","mwam","mwab","mwabs","mwas","mwass","mwang","mwaj","mwac","mwak","mwat","mwap","mwah","mwae","mwaeg","mwaegg","mwaegs","mwaen","mwaenj","mwaenh","mwaed","mwael","mwaelg","mwaelm","mwaelb","mwaels","mwaelt","mwaelp","mwaelh","mwaem","mwaeb","mwaebs","mwaes","mwaess","mwaeng","mwaej","mwaec","mwaek","mwaet","mwaep","mwaeh","moe","moeg","moegg","moegs"]});var pH=w((Yxe,gH)=>{gH.exports=["moen","moenj","moenh","moed","moel","moelg","moelm","moelb","moels","moelt","moelp","moelh","moem","moeb","moebs","moes","moess","moeng","moej","moec","moek","moet","moep","moeh","myo","myog","myogg","myogs","myon","myonj","myonh","myod","myol","myolg","myolm","myolb","myols","myolt","myolp","myolh","myom","myob","myobs","myos","myoss","myong","myoj","myoc","myok","myot","myop","myoh","mu","mug","mugg","mugs","mun","munj","munh","mud","mul","mulg","mulm","mulb","muls","mult","mulp","mulh","mum","mub","mubs","mus","muss","mung","muj","muc","muk","mut","mup","muh","mweo","mweog","mweogg","mweogs","mweon","mweonj","mweonh","mweod","mweol","mweolg","mweolm","mweolb","mweols","mweolt","mweolp","mweolh","mweom","mweob","mweobs","mweos","mweoss","mweong","mweoj","mweoc","mweok","mweot","mweop","mweoh","mwe","mweg","mwegg","mwegs","mwen","mwenj","mwenh","mwed","mwel","mwelg","mwelm","mwelb","mwels","mwelt","mwelp","mwelh","mwem","mweb","mwebs","mwes","mwess","mweng","mwej","mwec","mwek","mwet","mwep","mweh","mwi","mwig","mwigg","mwigs","mwin","mwinj","mwinh","mwid","mwil","mwilg","mwilm","mwilb","mwils","mwilt","mwilp","mwilh","mwim","mwib","mwibs","mwis","mwiss","mwing","mwij","mwic","mwik","mwit","mwip","mwih","myu","myug","myugg","myugs","myun","myunj","myunh","myud","myul","myulg","myulm","myulb","myuls","myult","myulp","myulh","myum","myub","myubs","myus","myuss","myung","myuj","myuc","myuk","myut","myup","myuh","meu","meug","meugg","meugs","meun","meunj","meunh","meud","meul","meulg","meulm","meulb","meuls","meult","meulp","meulh","meum","meub","meubs","meus","meuss","meung","meuj","meuc","meuk","meut","meup","meuh","myi","myig","myigg","myigs","myin","myinj","myinh","myid","myil","myilg","myilm","myilb","myils","myilt","myilp","myilh","myim","myib","myibs","myis","myiss","mying","myij","myic","myik","myit","myip","myih","mi","mig","migg","migs","min","minj","minh","mid"]});var mH=w((Zxe,fH)=>{fH.exports=["mil","milg","milm","milb","mils","milt","milp","milh","mim","mib","mibs","mis","miss","ming","mij","mic","mik","mit","mip","mih","ba","bag","bagg","bags","ban","banj","banh","bad","bal","balg","balm","balb","bals","balt","balp","balh","bam","bab","babs","bas","bass","bang","baj","bac","bak","bat","bap","bah","bae","baeg","baegg","baegs","baen","baenj","baenh","baed","bael","baelg","baelm","baelb","baels","baelt","baelp","baelh","baem","baeb","baebs","baes","baess","baeng","baej","baec","baek","baet","baep","baeh","bya","byag","byagg","byags","byan","byanj","byanh","byad","byal","byalg","byalm","byalb","byals","byalt","byalp","byalh","byam","byab","byabs","byas","byass","byang","byaj","byac","byak","byat","byap","byah","byae","byaeg","byaegg","byaegs","byaen","byaenj","byaenh","byaed","byael","byaelg","byaelm","byaelb","byaels","byaelt","byaelp","byaelh","byaem","byaeb","byaebs","byaes","byaess","byaeng","byaej","byaec","byaek","byaet","byaep","byaeh","beo","beog","beogg","beogs","beon","beonj","beonh","beod","beol","beolg","beolm","beolb","beols","beolt","beolp","beolh","beom","beob","beobs","beos","beoss","beong","beoj","beoc","beok","beot","beop","beoh","be","beg","begg","begs","ben","benj","benh","bed","bel","belg","belm","belb","bels","belt","belp","belh","bem","beb","bebs","bes","bess","beng","bej","bec","bek","bet","bep","beh","byeo","byeog","byeogg","byeogs","byeon","byeonj","byeonh","byeod","byeol","byeolg","byeolm","byeolb","byeols","byeolt","byeolp","byeolh","byeom","byeob","byeobs","byeos","byeoss","byeong","byeoj","byeoc","byeok","byeot","byeop","byeoh","bye","byeg","byegg","byegs","byen","byenj","byenh","byed","byel","byelg","byelm","byelb","byels","byelt","byelp","byelh","byem","byeb","byebs","byes","byess","byeng","byej","byec","byek","byet","byep","byeh","bo","bog","bogg","bogs","bon","bonj","bonh","bod","bol","bolg","bolm","bolb"]});var yH=w((Jxe,bH)=>{bH.exports=["bols","bolt","bolp","bolh","bom","bob","bobs","bos","boss","bong","boj","boc","bok","bot","bop","boh","bwa","bwag","bwagg","bwags","bwan","bwanj","bwanh","bwad","bwal","bwalg","bwalm","bwalb","bwals","bwalt","bwalp","bwalh","bwam","bwab","bwabs","bwas","bwass","bwang","bwaj","bwac","bwak","bwat","bwap","bwah","bwae","bwaeg","bwaegg","bwaegs","bwaen","bwaenj","bwaenh","bwaed","bwael","bwaelg","bwaelm","bwaelb","bwaels","bwaelt","bwaelp","bwaelh","bwaem","bwaeb","bwaebs","bwaes","bwaess","bwaeng","bwaej","bwaec","bwaek","bwaet","bwaep","bwaeh","boe","boeg","boegg","boegs","boen","boenj","boenh","boed","boel","boelg","boelm","boelb","boels","boelt","boelp","boelh","boem","boeb","boebs","boes","boess","boeng","boej","boec","boek","boet","boep","boeh","byo","byog","byogg","byogs","byon","byonj","byonh","byod","byol","byolg","byolm","byolb","byols","byolt","byolp","byolh","byom","byob","byobs","byos","byoss","byong","byoj","byoc","byok","byot","byop","byoh","bu","bug","bugg","bugs","bun","bunj","bunh","bud","bul","bulg","bulm","bulb","buls","bult","bulp","bulh","bum","bub","bubs","bus","buss","bung","buj","buc","buk","but","bup","buh","bweo","bweog","bweogg","bweogs","bweon","bweonj","bweonh","bweod","bweol","bweolg","bweolm","bweolb","bweols","bweolt","bweolp","bweolh","bweom","bweob","bweobs","bweos","bweoss","bweong","bweoj","bweoc","bweok","bweot","bweop","bweoh","bwe","bweg","bwegg","bwegs","bwen","bwenj","bwenh","bwed","bwel","bwelg","bwelm","bwelb","bwels","bwelt","bwelp","bwelh","bwem","bweb","bwebs","bwes","bwess","bweng","bwej","bwec","bwek","bwet","bwep","bweh","bwi","bwig","bwigg","bwigs","bwin","bwinj","bwinh","bwid","bwil","bwilg","bwilm","bwilb","bwils","bwilt","bwilp","bwilh","bwim","bwib","bwibs","bwis","bwiss","bwing","bwij","bwic","bwik","bwit","bwip","bwih","byu","byug","byugg","byugs","byun","byunj","byunh","byud","byul","byulg","byulm","byulb","byuls","byult","byulp","byulh"]});var wH=w(($xe,vH)=>{vH.exports=["byum","byub","byubs","byus","byuss","byung","byuj","byuc","byuk","byut","byup","byuh","beu","beug","beugg","beugs","beun","beunj","beunh","beud","beul","beulg","beulm","beulb","beuls","beult","beulp","beulh","beum","beub","beubs","beus","beuss","beung","beuj","beuc","beuk","beut","beup","beuh","byi","byig","byigg","byigs","byin","byinj","byinh","byid","byil","byilg","byilm","byilb","byils","byilt","byilp","byilh","byim","byib","byibs","byis","byiss","bying","byij","byic","byik","byit","byip","byih","bi","big","bigg","bigs","bin","binj","binh","bid","bil","bilg","bilm","bilb","bils","bilt","bilp","bilh","bim","bib","bibs","bis","biss","bing","bij","bic","bik","bit","bip","bih","bba","bbag","bbagg","bbags","bban","bbanj","bbanh","bbad","bbal","bbalg","bbalm","bbalb","bbals","bbalt","bbalp","bbalh","bbam","bbab","bbabs","bbas","bbass","bbang","bbaj","bbac","bbak","bbat","bbap","bbah","bbae","bbaeg","bbaegg","bbaegs","bbaen","bbaenj","bbaenh","bbaed","bbael","bbaelg","bbaelm","bbaelb","bbaels","bbaelt","bbaelp","bbaelh","bbaem","bbaeb","bbaebs","bbaes","bbaess","bbaeng","bbaej","bbaec","bbaek","bbaet","bbaep","bbaeh","bbya","bbyag","bbyagg","bbyags","bbyan","bbyanj","bbyanh","bbyad","bbyal","bbyalg","bbyalm","bbyalb","bbyals","bbyalt","bbyalp","bbyalh","bbyam","bbyab","bbyabs","bbyas","bbyass","bbyang","bbyaj","bbyac","bbyak","bbyat","bbyap","bbyah","bbyae","bbyaeg","bbyaegg","bbyaegs","bbyaen","bbyaenj","bbyaenh","bbyaed","bbyael","bbyaelg","bbyaelm","bbyaelb","bbyaels","bbyaelt","bbyaelp","bbyaelh","bbyaem","bbyaeb","bbyaebs","bbyaes","bbyaess","bbyaeng","bbyaej","bbyaec","bbyaek","bbyaet","bbyaep","bbyaeh","bbeo","bbeog","bbeogg","bbeogs","bbeon","bbeonj","bbeonh","bbeod","bbeol","bbeolg","bbeolm","bbeolb","bbeols","bbeolt","bbeolp","bbeolh","bbeom","bbeob","bbeobs","bbeos","bbeoss","bbeong","bbeoj","bbeoc","bbeok","bbeot","bbeop","bbeoh","bbe","bbeg","bbegg","bbegs","bben","bbenj","bbenh","bbed","bbel","bbelg","bbelm","bbelb","bbels","bbelt","bbelp","bbelh","bbem","bbeb","bbebs","bbes"]});var CH=w((Uxe,xH)=>{xH.exports=["bbess","bbeng","bbej","bbec","bbek","bbet","bbep","bbeh","bbyeo","bbyeog","bbyeogg","bbyeogs","bbyeon","bbyeonj","bbyeonh","bbyeod","bbyeol","bbyeolg","bbyeolm","bbyeolb","bbyeols","bbyeolt","bbyeolp","bbyeolh","bbyeom","bbyeob","bbyeobs","bbyeos","bbyeoss","bbyeong","bbyeoj","bbyeoc","bbyeok","bbyeot","bbyeop","bbyeoh","bbye","bbyeg","bbyegg","bbyegs","bbyen","bbyenj","bbyenh","bbyed","bbyel","bbyelg","bbyelm","bbyelb","bbyels","bbyelt","bbyelp","bbyelh","bbyem","bbyeb","bbyebs","bbyes","bbyess","bbyeng","bbyej","bbyec","bbyek","bbyet","bbyep","bbyeh","bbo","bbog","bbogg","bbogs","bbon","bbonj","bbonh","bbod","bbol","bbolg","bbolm","bbolb","bbols","bbolt","bbolp","bbolh","bbom","bbob","bbobs","bbos","bboss","bbong","bboj","bboc","bbok","bbot","bbop","bboh","bbwa","bbwag","bbwagg","bbwags","bbwan","bbwanj","bbwanh","bbwad","bbwal","bbwalg","bbwalm","bbwalb","bbwals","bbwalt","bbwalp","bbwalh","bbwam","bbwab","bbwabs","bbwas","bbwass","bbwang","bbwaj","bbwac","bbwak","bbwat","bbwap","bbwah","bbwae","bbwaeg","bbwaegg","bbwaegs","bbwaen","bbwaenj","bbwaenh","bbwaed","bbwael","bbwaelg","bbwaelm","bbwaelb","bbwaels","bbwaelt","bbwaelp","bbwaelh","bbwaem","bbwaeb","bbwaebs","bbwaes","bbwaess","bbwaeng","bbwaej","bbwaec","bbwaek","bbwaet","bbwaep","bbwaeh","bboe","bboeg","bboegg","bboegs","bboen","bboenj","bboenh","bboed","bboel","bboelg","bboelm","bboelb","bboels","bboelt","bboelp","bboelh","bboem","bboeb","bboebs","bboes","bboess","bboeng","bboej","bboec","bboek","bboet","bboep","bboeh","bbyo","bbyog","bbyogg","bbyogs","bbyon","bbyonj","bbyonh","bbyod","bbyol","bbyolg","bbyolm","bbyolb","bbyols","bbyolt","bbyolp","bbyolh","bbyom","bbyob","bbyobs","bbyos","bbyoss","bbyong","bbyoj","bbyoc","bbyok","bbyot","bbyop","bbyoh","bbu","bbug","bbugg","bbugs","bbun","bbunj","bbunh","bbud","bbul","bbulg","bbulm","bbulb","bbuls","bbult","bbulp","bbulh","bbum","bbub","bbubs","bbus","bbuss","bbung","bbuj","bbuc","bbuk","bbut","bbup","bbuh","bbweo","bbweog","bbweogg","bbweogs","bbweon","bbweonj","bbweonh","bbweod","bbweol","bbweolg","bbweolm","bbweolb","bbweols","bbweolt","bbweolp","bbweolh","bbweom","bbweob","bbweobs","bbweos","bbweoss","bbweong","bbweoj","bbweoc"]});var DH=w((Xxe,SH)=>{SH.exports=["bbweok","bbweot","bbweop","bbweoh","bbwe","bbweg","bbwegg","bbwegs","bbwen","bbwenj","bbwenh","bbwed","bbwel","bbwelg","bbwelm","bbwelb","bbwels","bbwelt","bbwelp","bbwelh","bbwem","bbweb","bbwebs","bbwes","bbwess","bbweng","bbwej","bbwec","bbwek","bbwet","bbwep","bbweh","bbwi","bbwig","bbwigg","bbwigs","bbwin","bbwinj","bbwinh","bbwid","bbwil","bbwilg","bbwilm","bbwilb","bbwils","bbwilt","bbwilp","bbwilh","bbwim","bbwib","bbwibs","bbwis","bbwiss","bbwing","bbwij","bbwic","bbwik","bbwit","bbwip","bbwih","bbyu","bbyug","bbyugg","bbyugs","bbyun","bbyunj","bbyunh","bbyud","bbyul","bbyulg","bbyulm","bbyulb","bbyuls","bbyult","bbyulp","bbyulh","bbyum","bbyub","bbyubs","bbyus","bbyuss","bbyung","bbyuj","bbyuc","bbyuk","bbyut","bbyup","bbyuh","bbeu","bbeug","bbeugg","bbeugs","bbeun","bbeunj","bbeunh","bbeud","bbeul","bbeulg","bbeulm","bbeulb","bbeuls","bbeult","bbeulp","bbeulh","bbeum","bbeub","bbeubs","bbeus","bbeuss","bbeung","bbeuj","bbeuc","bbeuk","bbeut","bbeup","bbeuh","bbyi","bbyig","bbyigg","bbyigs","bbyin","bbyinj","bbyinh","bbyid","bbyil","bbyilg","bbyilm","bbyilb","bbyils","bbyilt","bbyilp","bbyilh","bbyim","bbyib","bbyibs","bbyis","bbyiss","bbying","bbyij","bbyic","bbyik","bbyit","bbyip","bbyih","bbi","bbig","bbigg","bbigs","bbin","bbinj","bbinh","bbid","bbil","bbilg","bbilm","bbilb","bbils","bbilt","bbilp","bbilh","bbim","bbib","bbibs","bbis","bbiss","bbing","bbij","bbic","bbik","bbit","bbip","bbih","sa","sag","sagg","sags","san","sanj","sanh","sad","sal","salg","salm","salb","sals","salt","salp","salh","sam","sab","sabs","sas","sass","sang","saj","sac","sak","sat","sap","sah","sae","saeg","saegg","saegs","saen","saenj","saenh","saed","sael","saelg","saelm","saelb","saels","saelt","saelp","saelh","saem","saeb","saebs","saes","saess","saeng","saej","saec","saek","saet","saep","saeh","sya","syag","syagg","syags","syan","syanj","syanh","syad","syal","syalg","syalm","syalb","syals","syalt","syalp","syalh","syam","syab","syabs","syas","syass","syang","syaj","syac","syak","syat","syap","syah"]});var kH=w((Gxe,TH)=>{TH.exports=["syae","syaeg","syaegg","syaegs","syaen","syaenj","syaenh","syaed","syael","syaelg","syaelm","syaelb","syaels","syaelt","syaelp","syaelh","syaem","syaeb","syaebs","syaes","syaess","syaeng","syaej","syaec","syaek","syaet","syaep","syaeh","seo","seog","seogg","seogs","seon","seonj","seonh","seod","seol","seolg","seolm","seolb","seols","seolt","seolp","seolh","seom","seob","seobs","seos","seoss","seong","seoj","seoc","seok","seot","seop","seoh","se","seg","segg","segs","sen","senj","senh","sed","sel","selg","selm","selb","sels","selt","selp","selh","sem","seb","sebs","ses","sess","seng","sej","sec","sek","set","sep","seh","syeo","syeog","syeogg","syeogs","syeon","syeonj","syeonh","syeod","syeol","syeolg","syeolm","syeolb","syeols","syeolt","syeolp","syeolh","syeom","syeob","syeobs","syeos","syeoss","syeong","syeoj","syeoc","syeok","syeot","syeop","syeoh","sye","syeg","syegg","syegs","syen","syenj","syenh","syed","syel","syelg","syelm","syelb","syels","syelt","syelp","syelh","syem","syeb","syebs","syes","syess","syeng","syej","syec","syek","syet","syep","syeh","so","sog","sogg","sogs","son","sonj","sonh","sod","sol","solg","solm","solb","sols","solt","solp","solh","som","sob","sobs","sos","soss","song","soj","soc","sok","sot","sop","soh","swa","swag","swagg","swags","swan","swanj","swanh","swad","swal","swalg","swalm","swalb","swals","swalt","swalp","swalh","swam","swab","swabs","swas","swass","swang","swaj","swac","swak","swat","swap","swah","swae","swaeg","swaegg","swaegs","swaen","swaenj","swaenh","swaed","swael","swaelg","swaelm","swaelb","swaels","swaelt","swaelp","swaelh","swaem","swaeb","swaebs","swaes","swaess","swaeng","swaej","swaec","swaek","swaet","swaep","swaeh","soe","soeg","soegg","soegs","soen","soenj","soenh","soed","soel","soelg","soelm","soelb","soels","soelt","soelp","soelh","soem","soeb","soebs","soes","soess","soeng","soej","soec","soek","soet","soep","soeh","syo","syog","syogg","syogs"]});var RH=w((zxe,PH)=>{PH.exports=["syon","syonj","syonh","syod","syol","syolg","syolm","syolb","syols","syolt","syolp","syolh","syom","syob","syobs","syos","syoss","syong","syoj","syoc","syok","syot","syop","syoh","su","sug","sugg","sugs","sun","sunj","sunh","sud","sul","sulg","sulm","sulb","suls","sult","sulp","sulh","sum","sub","subs","sus","suss","sung","suj","suc","suk","sut","sup","suh","sweo","sweog","sweogg","sweogs","sweon","sweonj","sweonh","sweod","sweol","sweolg","sweolm","sweolb","sweols","sweolt","sweolp","sweolh","sweom","sweob","sweobs","sweos","sweoss","sweong","sweoj","sweoc","sweok","sweot","sweop","sweoh","swe","sweg","swegg","swegs","swen","swenj","swenh","swed","swel","swelg","swelm","swelb","swels","swelt","swelp","swelh","swem","sweb","swebs","swes","swess","sweng","swej","swec","swek","swet","swep","sweh","swi","swig","swigg","swigs","swin","swinj","swinh","swid","swil","swilg","swilm","swilb","swils","swilt","swilp","swilh","swim","swib","swibs","swis","swiss","swing","swij","swic","swik","swit","swip","swih","syu","syug","syugg","syugs","syun","syunj","syunh","syud","syul","syulg","syulm","syulb","syuls","syult","syulp","syulh","syum","syub","syubs","syus","syuss","syung","syuj","syuc","syuk","syut","syup","syuh","seu","seug","seugg","seugs","seun","seunj","seunh","seud","seul","seulg","seulm","seulb","seuls","seult","seulp","seulh","seum","seub","seubs","seus","seuss","seung","seuj","seuc","seuk","seut","seup","seuh","syi","syig","syigg","syigs","syin","syinj","syinh","syid","syil","syilg","syilm","syilb","syils","syilt","syilp","syilh","syim","syib","syibs","syis","syiss","sying","syij","syic","syik","syit","syip","syih","si","sig","sigg","sigs","sin","sinj","sinh","sid","sil","silg","silm","silb","sils","silt","silp","silh","sim","sib","sibs","sis","siss","sing","sij","sic","sik","sit","sip","sih","ssa","ssag","ssagg","ssags","ssan","ssanj","ssanh","ssad"]});var EH=w((Kxe,_H)=>{_H.exports=["ssal","ssalg","ssalm","ssalb","ssals","ssalt","ssalp","ssalh","ssam","ssab","ssabs","ssas","ssass","ssang","ssaj","ssac","ssak","ssat","ssap","ssah","ssae","ssaeg","ssaegg","ssaegs","ssaen","ssaenj","ssaenh","ssaed","ssael","ssaelg","ssaelm","ssaelb","ssaels","ssaelt","ssaelp","ssaelh","ssaem","ssaeb","ssaebs","ssaes","ssaess","ssaeng","ssaej","ssaec","ssaek","ssaet","ssaep","ssaeh","ssya","ssyag","ssyagg","ssyags","ssyan","ssyanj","ssyanh","ssyad","ssyal","ssyalg","ssyalm","ssyalb","ssyals","ssyalt","ssyalp","ssyalh","ssyam","ssyab","ssyabs","ssyas","ssyass","ssyang","ssyaj","ssyac","ssyak","ssyat","ssyap","ssyah","ssyae","ssyaeg","ssyaegg","ssyaegs","ssyaen","ssyaenj","ssyaenh","ssyaed","ssyael","ssyaelg","ssyaelm","ssyaelb","ssyaels","ssyaelt","ssyaelp","ssyaelh","ssyaem","ssyaeb","ssyaebs","ssyaes","ssyaess","ssyaeng","ssyaej","ssyaec","ssyaek","ssyaet","ssyaep","ssyaeh","sseo","sseog","sseogg","sseogs","sseon","sseonj","sseonh","sseod","sseol","sseolg","sseolm","sseolb","sseols","sseolt","sseolp","sseolh","sseom","sseob","sseobs","sseos","sseoss","sseong","sseoj","sseoc","sseok","sseot","sseop","sseoh","sse","sseg","ssegg","ssegs","ssen","ssenj","ssenh","ssed","ssel","sselg","sselm","sselb","ssels","sselt","sselp","sselh","ssem","sseb","ssebs","sses","ssess","sseng","ssej","ssec","ssek","sset","ssep","sseh","ssyeo","ssyeog","ssyeogg","ssyeogs","ssyeon","ssyeonj","ssyeonh","ssyeod","ssyeol","ssyeolg","ssyeolm","ssyeolb","ssyeols","ssyeolt","ssyeolp","ssyeolh","ssyeom","ssyeob","ssyeobs","ssyeos","ssyeoss","ssyeong","ssyeoj","ssyeoc","ssyeok","ssyeot","ssyeop","ssyeoh","ssye","ssyeg","ssyegg","ssyegs","ssyen","ssyenj","ssyenh","ssyed","ssyel","ssyelg","ssyelm","ssyelb","ssyels","ssyelt","ssyelp","ssyelh","ssyem","ssyeb","ssyebs","ssyes","ssyess","ssyeng","ssyej","ssyec","ssyek","ssyet","ssyep","ssyeh","sso","ssog","ssogg","ssogs","sson","ssonj","ssonh","ssod","ssol","ssolg","ssolm","ssolb","ssols","ssolt","ssolp","ssolh","ssom","ssob","ssobs","ssos","ssoss","ssong","ssoj","ssoc","ssok","ssot","ssop","ssoh","sswa","sswag","sswagg","sswags","sswan","sswanj","sswanh","sswad","sswal","sswalg","sswalm","sswalb"]});var LH=w((Qxe,IH)=>{IH.exports=["sswals","sswalt","sswalp","sswalh","sswam","sswab","sswabs","sswas","sswass","sswang","sswaj","sswac","sswak","sswat","sswap","sswah","sswae","sswaeg","sswaegg","sswaegs","sswaen","sswaenj","sswaenh","sswaed","sswael","sswaelg","sswaelm","sswaelb","sswaels","sswaelt","sswaelp","sswaelh","sswaem","sswaeb","sswaebs","sswaes","sswaess","sswaeng","sswaej","sswaec","sswaek","sswaet","sswaep","sswaeh","ssoe","ssoeg","ssoegg","ssoegs","ssoen","ssoenj","ssoenh","ssoed","ssoel","ssoelg","ssoelm","ssoelb","ssoels","ssoelt","ssoelp","ssoelh","ssoem","ssoeb","ssoebs","ssoes","ssoess","ssoeng","ssoej","ssoec","ssoek","ssoet","ssoep","ssoeh","ssyo","ssyog","ssyogg","ssyogs","ssyon","ssyonj","ssyonh","ssyod","ssyol","ssyolg","ssyolm","ssyolb","ssyols","ssyolt","ssyolp","ssyolh","ssyom","ssyob","ssyobs","ssyos","ssyoss","ssyong","ssyoj","ssyoc","ssyok","ssyot","ssyop","ssyoh","ssu","ssug","ssugg","ssugs","ssun","ssunj","ssunh","ssud","ssul","ssulg","ssulm","ssulb","ssuls","ssult","ssulp","ssulh","ssum","ssub","ssubs","ssus","ssuss","ssung","ssuj","ssuc","ssuk","ssut","ssup","ssuh","ssweo","ssweog","ssweogg","ssweogs","ssweon","ssweonj","ssweonh","ssweod","ssweol","ssweolg","ssweolm","ssweolb","ssweols","ssweolt","ssweolp","ssweolh","ssweom","ssweob","ssweobs","ssweos","ssweoss","ssweong","ssweoj","ssweoc","ssweok","ssweot","ssweop","ssweoh","sswe","ssweg","sswegg","sswegs","sswen","sswenj","sswenh","sswed","sswel","sswelg","sswelm","sswelb","sswels","sswelt","sswelp","sswelh","sswem","ssweb","sswebs","sswes","sswess","ssweng","sswej","sswec","sswek","sswet","sswep","ssweh","sswi","sswig","sswigg","sswigs","sswin","sswinj","sswinh","sswid","sswil","sswilg","sswilm","sswilb","sswils","sswilt","sswilp","sswilh","sswim","sswib","sswibs","sswis","sswiss","sswing","sswij","sswic","sswik","sswit","sswip","sswih","ssyu","ssyug","ssyugg","ssyugs","ssyun","ssyunj","ssyunh","ssyud","ssyul","ssyulg","ssyulm","ssyulb","ssyuls","ssyult","ssyulp","ssyulh","ssyum","ssyub","ssyubs","ssyus","ssyuss","ssyung","ssyuj","ssyuc","ssyuk","ssyut","ssyup","ssyuh","sseu","sseug","sseugg","sseugs","sseun","sseunj","sseunh","sseud","sseul","sseulg","sseulm","sseulb","sseuls","sseult","sseulp","sseulh"]});var MH=w((Vxe,FH)=>{FH.exports=["sseum","sseub","sseubs","sseus","sseuss","sseung","sseuj","sseuc","sseuk","sseut","sseup","sseuh","ssyi","ssyig","ssyigg","ssyigs","ssyin","ssyinj","ssyinh","ssyid","ssyil","ssyilg","ssyilm","ssyilb","ssyils","ssyilt","ssyilp","ssyilh","ssyim","ssyib","ssyibs","ssyis","ssyiss","ssying","ssyij","ssyic","ssyik","ssyit","ssyip","ssyih","ssi","ssig","ssigg","ssigs","ssin","ssinj","ssinh","ssid","ssil","ssilg","ssilm","ssilb","ssils","ssilt","ssilp","ssilh","ssim","ssib","ssibs","ssis","ssiss","ssing","ssij","ssic","ssik","ssit","ssip","ssih","a","ag","agg","ags","an","anj","anh","ad","al","alg","alm","alb","als","alt","alp","alh","am","ab","abs","as","ass","ang","aj","ac","ak","at","ap","ah","ae","aeg","aegg","aegs","aen","aenj","aenh","aed","ael","aelg","aelm","aelb","aels","aelt","aelp","aelh","aem","aeb","aebs","aes","aess","aeng","aej","aec","aek","aet","aep","aeh","ya","yag","yagg","yags","yan","yanj","yanh","yad","yal","yalg","yalm","yalb","yals","yalt","yalp","yalh","yam","yab","yabs","yas","yass","yang","yaj","yac","yak","yat","yap","yah","yae","yaeg","yaegg","yaegs","yaen","yaenj","yaenh","yaed","yael","yaelg","yaelm","yaelb","yaels","yaelt","yaelp","yaelh","yaem","yaeb","yaebs","yaes","yaess","yaeng","yaej","yaec","yaek","yaet","yaep","yaeh","eo","eog","eogg","eogs","eon","eonj","eonh","eod","eol","eolg","eolm","eolb","eols","eolt","eolp","eolh","eom","eob","eobs","eos","eoss","eong","eoj","eoc","eok","eot","eop","eoh","e","eg","egg","egs","en","enj","enh","ed","el","elg","elm","elb","els","elt","elp","elh","em","eb","ebs","es","ess","eng","ej","ec","ek","et","ep","eh","yeo","yeog","yeogg","yeogs","yeon","yeonj","yeonh","yeod","yeol","yeolg","yeolm","yeolb","yeols","yeolt","yeolp","yeolh","yeom","yeob","yeobs","yeos"]});var OH=w((eCe,jH)=>{jH.exports=["yeoss","yeong","yeoj","yeoc","yeok","yeot","yeop","yeoh","ye","yeg","yegg","yegs","yen","yenj","yenh","yed","yel","yelg","yelm","yelb","yels","yelt","yelp","yelh","yem","yeb","yebs","yes","yess","yeng","yej","yec","yek","yet","yep","yeh","o","og","ogg","ogs","on","onj","onh","od","ol","olg","olm","olb","ols","olt","olp","olh","om","ob","obs","os","oss","ong","oj","oc","ok","ot","op","oh","wa","wag","wagg","wags","wan","wanj","wanh","wad","wal","walg","walm","walb","wals","walt","walp","walh","wam","wab","wabs","was","wass","wang","waj","wac","wak","wat","wap","wah","wae","waeg","waegg","waegs","waen","waenj","waenh","waed","wael","waelg","waelm","waelb","waels","waelt","waelp","waelh","waem","waeb","waebs","waes","waess","waeng","waej","waec","waek","waet","waep","waeh","oe","oeg","oegg","oegs","oen","oenj","oenh","oed","oel","oelg","oelm","oelb","oels","oelt","oelp","oelh","oem","oeb","oebs","oes","oess","oeng","oej","oec","oek","oet","oep","oeh","yo","yog","yogg","yogs","yon","yonj","yonh","yod","yol","yolg","yolm","yolb","yols","yolt","yolp","yolh","yom","yob","yobs","yos","yoss","yong","yoj","yoc","yok","yot","yop","yoh","u","ug","ugg","ugs","un","unj","unh","ud","ul","ulg","ulm","ulb","uls","ult","ulp","ulh","um","ub","ubs","us","uss","ung","uj","uc","uk","ut","up","uh","weo","weog","weogg","weogs","weon","weonj","weonh","weod","weol","weolg","weolm","weolb","weols","weolt","weolp","weolh","weom","weob","weobs","weos","weoss","weong","weoj","weoc","weok","weot","weop","weoh","we","weg","wegg","wegs","wen","wenj","wenh","wed","wel","welg","welm","welb","wels","welt","welp","welh","wem","web","webs","wes","wess","weng","wej","wec"]});var NH=w((tCe,AH)=>{AH.exports=["wek","wet","wep","weh","wi","wig","wigg","wigs","win","winj","winh","wid","wil","wilg","wilm","wilb","wils","wilt","wilp","wilh","wim","wib","wibs","wis","wiss","wing","wij","wic","wik","wit","wip","wih","yu","yug","yugg","yugs","yun","yunj","yunh","yud","yul","yulg","yulm","yulb","yuls","yult","yulp","yulh","yum","yub","yubs","yus","yuss","yung","yuj","yuc","yuk","yut","yup","yuh","eu","eug","eugg","eugs","eun","eunj","eunh","eud","eul","eulg","eulm","eulb","euls","eult","eulp","eulh","eum","eub","eubs","eus","euss","eung","euj","euc","euk","eut","eup","euh","yi","yig","yigg","yigs","yin","yinj","yinh","yid","yil","yilg","yilm","yilb","yils","yilt","yilp","yilh","yim","yib","yibs","yis","yiss","ying","yij","yic","yik","yit","yip","yih","i","ig","igg","igs","in","inj","inh","id","il","ilg","ilm","ilb","ils","ilt","ilp","ilh","im","ib","ibs","is","iss","ing","ij","ic","ik","it","ip","ih","ja","jag","jagg","jags","jan","janj","janh","jad","jal","jalg","jalm","jalb","jals","jalt","jalp","jalh","jam","jab","jabs","jas","jass","jang","jaj","jac","jak","jat","jap","jah","jae","jaeg","jaegg","jaegs","jaen","jaenj","jaenh","jaed","jael","jaelg","jaelm","jaelb","jaels","jaelt","jaelp","jaelh","jaem","jaeb","jaebs","jaes","jaess","jaeng","jaej","jaec","jaek","jaet","jaep","jaeh","jya","jyag","jyagg","jyags","jyan","jyanj","jyanh","jyad","jyal","jyalg","jyalm","jyalb","jyals","jyalt","jyalp","jyalh","jyam","jyab","jyabs","jyas","jyass","jyang","jyaj","jyac","jyak","jyat","jyap","jyah","jyae","jyaeg","jyaegg","jyaegs","jyaen","jyaenj","jyaenh","jyaed","jyael","jyaelg","jyaelm","jyaelb","jyaels","jyaelt","jyaelp","jyaelh","jyaem","jyaeb","jyaebs","jyaes","jyaess","jyaeng","jyaej","jyaec","jyaek","jyaet","jyaep","jyaeh"]});var BH=w((iCe,HH)=>{HH.exports=["jeo","jeog","jeogg","jeogs","jeon","jeonj","jeonh","jeod","jeol","jeolg","jeolm","jeolb","jeols","jeolt","jeolp","jeolh","jeom","jeob","jeobs","jeos","jeoss","jeong","jeoj","jeoc","jeok","jeot","jeop","jeoh","je","jeg","jegg","jegs","jen","jenj","jenh","jed","jel","jelg","jelm","jelb","jels","jelt","jelp","jelh","jem","jeb","jebs","jes","jess","jeng","jej","jec","jek","jet","jep","jeh","jyeo","jyeog","jyeogg","jyeogs","jyeon","jyeonj","jyeonh","jyeod","jyeol","jyeolg","jyeolm","jyeolb","jyeols","jyeolt","jyeolp","jyeolh","jyeom","jyeob","jyeobs","jyeos","jyeoss","jyeong","jyeoj","jyeoc","jyeok","jyeot","jyeop","jyeoh","jye","jyeg","jyegg","jyegs","jyen","jyenj","jyenh","jyed","jyel","jyelg","jyelm","jyelb","jyels","jyelt","jyelp","jyelh","jyem","jyeb","jyebs","jyes","jyess","jyeng","jyej","jyec","jyek","jyet","jyep","jyeh","jo","jog","jogg","jogs","jon","jonj","jonh","jod","jol","jolg","jolm","jolb","jols","jolt","jolp","jolh","jom","job","jobs","jos","joss","jong","joj","joc","jok","jot","jop","joh","jwa","jwag","jwagg","jwags","jwan","jwanj","jwanh","jwad","jwal","jwalg","jwalm","jwalb","jwals","jwalt","jwalp","jwalh","jwam","jwab","jwabs","jwas","jwass","jwang","jwaj","jwac","jwak","jwat","jwap","jwah","jwae","jwaeg","jwaegg","jwaegs","jwaen","jwaenj","jwaenh","jwaed","jwael","jwaelg","jwaelm","jwaelb","jwaels","jwaelt","jwaelp","jwaelh","jwaem","jwaeb","jwaebs","jwaes","jwaess","jwaeng","jwaej","jwaec","jwaek","jwaet","jwaep","jwaeh","joe","joeg","joegg","joegs","joen","joenj","joenh","joed","joel","joelg","joelm","joelb","joels","joelt","joelp","joelh","joem","joeb","joebs","joes","joess","joeng","joej","joec","joek","joet","joep","joeh","jyo","jyog","jyogg","jyogs","jyon","jyonj","jyonh","jyod","jyol","jyolg","jyolm","jyolb","jyols","jyolt","jyolp","jyolh","jyom","jyob","jyobs","jyos","jyoss","jyong","jyoj","jyoc","jyok","jyot","jyop","jyoh","ju","jug","jugg","jugs"]});var WH=w((nCe,qH)=>{qH.exports=["jun","junj","junh","jud","jul","julg","julm","julb","juls","jult","julp","julh","jum","jub","jubs","jus","juss","jung","juj","juc","juk","jut","jup","juh","jweo","jweog","jweogg","jweogs","jweon","jweonj","jweonh","jweod","jweol","jweolg","jweolm","jweolb","jweols","jweolt","jweolp","jweolh","jweom","jweob","jweobs","jweos","jweoss","jweong","jweoj","jweoc","jweok","jweot","jweop","jweoh","jwe","jweg","jwegg","jwegs","jwen","jwenj","jwenh","jwed","jwel","jwelg","jwelm","jwelb","jwels","jwelt","jwelp","jwelh","jwem","jweb","jwebs","jwes","jwess","jweng","jwej","jwec","jwek","jwet","jwep","jweh","jwi","jwig","jwigg","jwigs","jwin","jwinj","jwinh","jwid","jwil","jwilg","jwilm","jwilb","jwils","jwilt","jwilp","jwilh","jwim","jwib","jwibs","jwis","jwiss","jwing","jwij","jwic","jwik","jwit","jwip","jwih","jyu","jyug","jyugg","jyugs","jyun","jyunj","jyunh","jyud","jyul","jyulg","jyulm","jyulb","jyuls","jyult","jyulp","jyulh","jyum","jyub","jyubs","jyus","jyuss","jyung","jyuj","jyuc","jyuk","jyut","jyup","jyuh","jeu","jeug","jeugg","jeugs","jeun","jeunj","jeunh","jeud","jeul","jeulg","jeulm","jeulb","jeuls","jeult","jeulp","jeulh","jeum","jeub","jeubs","jeus","jeuss","jeung","jeuj","jeuc","jeuk","jeut","jeup","jeuh","jyi","jyig","jyigg","jyigs","jyin","jyinj","jyinh","jyid","jyil","jyilg","jyilm","jyilb","jyils","jyilt","jyilp","jyilh","jyim","jyib","jyibs","jyis","jyiss","jying","jyij","jyic","jyik","jyit","jyip","jyih","ji","jig","jigg","jigs","jin","jinj","jinh","jid","jil","jilg","jilm","jilb","jils","jilt","jilp","jilh","jim","jib","jibs","jis","jiss","jing","jij","jic","jik","jit","jip","jih","jja","jjag","jjagg","jjags","jjan","jjanj","jjanh","jjad","jjal","jjalg","jjalm","jjalb","jjals","jjalt","jjalp","jjalh","jjam","jjab","jjabs","jjas","jjass","jjang","jjaj","jjac","jjak","jjat","jjap","jjah","jjae","jjaeg","jjaegg","jjaegs","jjaen","jjaenj","jjaenh","jjaed"]});var ZH=w((rCe,YH)=>{YH.exports=["jjael","jjaelg","jjaelm","jjaelb","jjaels","jjaelt","jjaelp","jjaelh","jjaem","jjaeb","jjaebs","jjaes","jjaess","jjaeng","jjaej","jjaec","jjaek","jjaet","jjaep","jjaeh","jjya","jjyag","jjyagg","jjyags","jjyan","jjyanj","jjyanh","jjyad","jjyal","jjyalg","jjyalm","jjyalb","jjyals","jjyalt","jjyalp","jjyalh","jjyam","jjyab","jjyabs","jjyas","jjyass","jjyang","jjyaj","jjyac","jjyak","jjyat","jjyap","jjyah","jjyae","jjyaeg","jjyaegg","jjyaegs","jjyaen","jjyaenj","jjyaenh","jjyaed","jjyael","jjyaelg","jjyaelm","jjyaelb","jjyaels","jjyaelt","jjyaelp","jjyaelh","jjyaem","jjyaeb","jjyaebs","jjyaes","jjyaess","jjyaeng","jjyaej","jjyaec","jjyaek","jjyaet","jjyaep","jjyaeh","jjeo","jjeog","jjeogg","jjeogs","jjeon","jjeonj","jjeonh","jjeod","jjeol","jjeolg","jjeolm","jjeolb","jjeols","jjeolt","jjeolp","jjeolh","jjeom","jjeob","jjeobs","jjeos","jjeoss","jjeong","jjeoj","jjeoc","jjeok","jjeot","jjeop","jjeoh","jje","jjeg","jjegg","jjegs","jjen","jjenj","jjenh","jjed","jjel","jjelg","jjelm","jjelb","jjels","jjelt","jjelp","jjelh","jjem","jjeb","jjebs","jjes","jjess","jjeng","jjej","jjec","jjek","jjet","jjep","jjeh","jjyeo","jjyeog","jjyeogg","jjyeogs","jjyeon","jjyeonj","jjyeonh","jjyeod","jjyeol","jjyeolg","jjyeolm","jjyeolb","jjyeols","jjyeolt","jjyeolp","jjyeolh","jjyeom","jjyeob","jjyeobs","jjyeos","jjyeoss","jjyeong","jjyeoj","jjyeoc","jjyeok","jjyeot","jjyeop","jjyeoh","jjye","jjyeg","jjyegg","jjyegs","jjyen","jjyenj","jjyenh","jjyed","jjyel","jjyelg","jjyelm","jjyelb","jjyels","jjyelt","jjyelp","jjyelh","jjyem","jjyeb","jjyebs","jjyes","jjyess","jjyeng","jjyej","jjyec","jjyek","jjyet","jjyep","jjyeh","jjo","jjog","jjogg","jjogs","jjon","jjonj","jjonh","jjod","jjol","jjolg","jjolm","jjolb","jjols","jjolt","jjolp","jjolh","jjom","jjob","jjobs","jjos","jjoss","jjong","jjoj","jjoc","jjok","jjot","jjop","jjoh","jjwa","jjwag","jjwagg","jjwags","jjwan","jjwanj","jjwanh","jjwad","jjwal","jjwalg","jjwalm","jjwalb","jjwals","jjwalt","jjwalp","jjwalh","jjwam","jjwab","jjwabs","jjwas","jjwass","jjwang","jjwaj","jjwac","jjwak","jjwat","jjwap","jjwah","jjwae","jjwaeg","jjwaegg","jjwaegs","jjwaen","jjwaenj","jjwaenh","jjwaed","jjwael","jjwaelg","jjwaelm","jjwaelb"]});var $H=w((oCe,JH)=>{JH.exports=["jjwaels","jjwaelt","jjwaelp","jjwaelh","jjwaem","jjwaeb","jjwaebs","jjwaes","jjwaess","jjwaeng","jjwaej","jjwaec","jjwaek","jjwaet","jjwaep","jjwaeh","jjoe","jjoeg","jjoegg","jjoegs","jjoen","jjoenj","jjoenh","jjoed","jjoel","jjoelg","jjoelm","jjoelb","jjoels","jjoelt","jjoelp","jjoelh","jjoem","jjoeb","jjoebs","jjoes","jjoess","jjoeng","jjoej","jjoec","jjoek","jjoet","jjoep","jjoeh","jjyo","jjyog","jjyogg","jjyogs","jjyon","jjyonj","jjyonh","jjyod","jjyol","jjyolg","jjyolm","jjyolb","jjyols","jjyolt","jjyolp","jjyolh","jjyom","jjyob","jjyobs","jjyos","jjyoss","jjyong","jjyoj","jjyoc","jjyok","jjyot","jjyop","jjyoh","jju","jjug","jjugg","jjugs","jjun","jjunj","jjunh","jjud","jjul","jjulg","jjulm","jjulb","jjuls","jjult","jjulp","jjulh","jjum","jjub","jjubs","jjus","jjuss","jjung","jjuj","jjuc","jjuk","jjut","jjup","jjuh","jjweo","jjweog","jjweogg","jjweogs","jjweon","jjweonj","jjweonh","jjweod","jjweol","jjweolg","jjweolm","jjweolb","jjweols","jjweolt","jjweolp","jjweolh","jjweom","jjweob","jjweobs","jjweos","jjweoss","jjweong","jjweoj","jjweoc","jjweok","jjweot","jjweop","jjweoh","jjwe","jjweg","jjwegg","jjwegs","jjwen","jjwenj","jjwenh","jjwed","jjwel","jjwelg","jjwelm","jjwelb","jjwels","jjwelt","jjwelp","jjwelh","jjwem","jjweb","jjwebs","jjwes","jjwess","jjweng","jjwej","jjwec","jjwek","jjwet","jjwep","jjweh","jjwi","jjwig","jjwigg","jjwigs","jjwin","jjwinj","jjwinh","jjwid","jjwil","jjwilg","jjwilm","jjwilb","jjwils","jjwilt","jjwilp","jjwilh","jjwim","jjwib","jjwibs","jjwis","jjwiss","jjwing","jjwij","jjwic","jjwik","jjwit","jjwip","jjwih","jjyu","jjyug","jjyugg","jjyugs","jjyun","jjyunj","jjyunh","jjyud","jjyul","jjyulg","jjyulm","jjyulb","jjyuls","jjyult","jjyulp","jjyulh","jjyum","jjyub","jjyubs","jjyus","jjyuss","jjyung","jjyuj","jjyuc","jjyuk","jjyut","jjyup","jjyuh","jjeu","jjeug","jjeugg","jjeugs","jjeun","jjeunj","jjeunh","jjeud","jjeul","jjeulg","jjeulm","jjeulb","jjeuls","jjeult","jjeulp","jjeulh","jjeum","jjeub","jjeubs","jjeus","jjeuss","jjeung","jjeuj","jjeuc","jjeuk","jjeut","jjeup","jjeuh","jjyi","jjyig","jjyigg","jjyigs","jjyin","jjyinj","jjyinh","jjyid","jjyil","jjyilg","jjyilm","jjyilb","jjyils","jjyilt","jjyilp","jjyilh"]});var XH=w((sCe,UH)=>{UH.exports=["jjyim","jjyib","jjyibs","jjyis","jjyiss","jjying","jjyij","jjyic","jjyik","jjyit","jjyip","jjyih","jji","jjig","jjigg","jjigs","jjin","jjinj","jjinh","jjid","jjil","jjilg","jjilm","jjilb","jjils","jjilt","jjilp","jjilh","jjim","jjib","jjibs","jjis","jjiss","jjing","jjij","jjic","jjik","jjit","jjip","jjih","ca","cag","cagg","cags","can","canj","canh","cad","cal","calg","calm","calb","cals","calt","calp","calh","cam","cab","cabs","cas","cass","cang","caj","cac","cak","cat","cap","cah","cae","caeg","caegg","caegs","caen","caenj","caenh","caed","cael","caelg","caelm","caelb","caels","caelt","caelp","caelh","caem","caeb","caebs","caes","caess","caeng","caej","caec","caek","caet","caep","caeh","cya","cyag","cyagg","cyags","cyan","cyanj","cyanh","cyad","cyal","cyalg","cyalm","cyalb","cyals","cyalt","cyalp","cyalh","cyam","cyab","cyabs","cyas","cyass","cyang","cyaj","cyac","cyak","cyat","cyap","cyah","cyae","cyaeg","cyaegg","cyaegs","cyaen","cyaenj","cyaenh","cyaed","cyael","cyaelg","cyaelm","cyaelb","cyaels","cyaelt","cyaelp","cyaelh","cyaem","cyaeb","cyaebs","cyaes","cyaess","cyaeng","cyaej","cyaec","cyaek","cyaet","cyaep","cyaeh","ceo","ceog","ceogg","ceogs","ceon","ceonj","ceonh","ceod","ceol","ceolg","ceolm","ceolb","ceols","ceolt","ceolp","ceolh","ceom","ceob","ceobs","ceos","ceoss","ceong","ceoj","ceoc","ceok","ceot","ceop","ceoh","ce","ceg","cegg","cegs","cen","cenj","cenh","ced","cel","celg","celm","celb","cels","celt","celp","celh","cem","ceb","cebs","ces","cess","ceng","cej","cec","cek","cet","cep","ceh","cyeo","cyeog","cyeogg","cyeogs","cyeon","cyeonj","cyeonh","cyeod","cyeol","cyeolg","cyeolm","cyeolb","cyeols","cyeolt","cyeolp","cyeolh","cyeom","cyeob","cyeobs","cyeos","cyeoss","cyeong","cyeoj","cyeoc","cyeok","cyeot","cyeop","cyeoh","cye","cyeg","cyegg","cyegs","cyen","cyenj","cyenh","cyed","cyel","cyelg","cyelm","cyelb","cyels","cyelt","cyelp","cyelh","cyem","cyeb","cyebs","cyes"]});var zH=w((aCe,GH)=>{GH.exports=["cyess","cyeng","cyej","cyec","cyek","cyet","cyep","cyeh","co","cog","cogg","cogs","con","conj","conh","cod","col","colg","colm","colb","cols","colt","colp","colh","com","cob","cobs","cos","coss","cong","coj","coc","cok","cot","cop","coh","cwa","cwag","cwagg","cwags","cwan","cwanj","cwanh","cwad","cwal","cwalg","cwalm","cwalb","cwals","cwalt","cwalp","cwalh","cwam","cwab","cwabs","cwas","cwass","cwang","cwaj","cwac","cwak","cwat","cwap","cwah","cwae","cwaeg","cwaegg","cwaegs","cwaen","cwaenj","cwaenh","cwaed","cwael","cwaelg","cwaelm","cwaelb","cwaels","cwaelt","cwaelp","cwaelh","cwaem","cwaeb","cwaebs","cwaes","cwaess","cwaeng","cwaej","cwaec","cwaek","cwaet","cwaep","cwaeh","coe","coeg","coegg","coegs","coen","coenj","coenh","coed","coel","coelg","coelm","coelb","coels","coelt","coelp","coelh","coem","coeb","coebs","coes","coess","coeng","coej","coec","coek","coet","coep","coeh","cyo","cyog","cyogg","cyogs","cyon","cyonj","cyonh","cyod","cyol","cyolg","cyolm","cyolb","cyols","cyolt","cyolp","cyolh","cyom","cyob","cyobs","cyos","cyoss","cyong","cyoj","cyoc","cyok","cyot","cyop","cyoh","cu","cug","cugg","cugs","cun","cunj","cunh","cud","cul","culg","culm","culb","culs","cult","culp","culh","cum","cub","cubs","cus","cuss","cung","cuj","cuc","cuk","cut","cup","cuh","cweo","cweog","cweogg","cweogs","cweon","cweonj","cweonh","cweod","cweol","cweolg","cweolm","cweolb","cweols","cweolt","cweolp","cweolh","cweom","cweob","cweobs","cweos","cweoss","cweong","cweoj","cweoc","cweok","cweot","cweop","cweoh","cwe","cweg","cwegg","cwegs","cwen","cwenj","cwenh","cwed","cwel","cwelg","cwelm","cwelb","cwels","cwelt","cwelp","cwelh","cwem","cweb","cwebs","cwes","cwess","cweng","cwej","cwec","cwek","cwet","cwep","cweh","cwi","cwig","cwigg","cwigs","cwin","cwinj","cwinh","cwid","cwil","cwilg","cwilm","cwilb","cwils","cwilt","cwilp","cwilh","cwim","cwib","cwibs","cwis","cwiss","cwing","cwij","cwic"]});var QH=w((lCe,KH)=>{KH.exports=["cwik","cwit","cwip","cwih","cyu","cyug","cyugg","cyugs","cyun","cyunj","cyunh","cyud","cyul","cyulg","cyulm","cyulb","cyuls","cyult","cyulp","cyulh","cyum","cyub","cyubs","cyus","cyuss","cyung","cyuj","cyuc","cyuk","cyut","cyup","cyuh","ceu","ceug","ceugg","ceugs","ceun","ceunj","ceunh","ceud","ceul","ceulg","ceulm","ceulb","ceuls","ceult","ceulp","ceulh","ceum","ceub","ceubs","ceus","ceuss","ceung","ceuj","ceuc","ceuk","ceut","ceup","ceuh","cyi","cyig","cyigg","cyigs","cyin","cyinj","cyinh","cyid","cyil","cyilg","cyilm","cyilb","cyils","cyilt","cyilp","cyilh","cyim","cyib","cyibs","cyis","cyiss","cying","cyij","cyic","cyik","cyit","cyip","cyih","ci","cig","cigg","cigs","cin","cinj","cinh","cid","cil","cilg","cilm","cilb","cils","cilt","cilp","cilh","cim","cib","cibs","cis","ciss","cing","cij","cic","cik","cit","cip","cih","ka","kag","kagg","kags","kan","kanj","kanh","kad","kal","kalg","kalm","kalb","kals","kalt","kalp","kalh","kam","kab","kabs","kas","kass","kang","kaj","kac","kak","kat","kap","kah","kae","kaeg","kaegg","kaegs","kaen","kaenj","kaenh","kaed","kael","kaelg","kaelm","kaelb","kaels","kaelt","kaelp","kaelh","kaem","kaeb","kaebs","kaes","kaess","kaeng","kaej","kaec","kaek","kaet","kaep","kaeh","kya","kyag","kyagg","kyags","kyan","kyanj","kyanh","kyad","kyal","kyalg","kyalm","kyalb","kyals","kyalt","kyalp","kyalh","kyam","kyab","kyabs","kyas","kyass","kyang","kyaj","kyac","kyak","kyat","kyap","kyah","kyae","kyaeg","kyaegg","kyaegs","kyaen","kyaenj","kyaenh","kyaed","kyael","kyaelg","kyaelm","kyaelb","kyaels","kyaelt","kyaelp","kyaelh","kyaem","kyaeb","kyaebs","kyaes","kyaess","kyaeng","kyaej","kyaec","kyaek","kyaet","kyaep","kyaeh","keo","keog","keogg","keogs","keon","keonj","keonh","keod","keol","keolg","keolm","keolb","keols","keolt","keolp","keolh","keom","keob","keobs","keos","keoss","keong","keoj","keoc","keok","keot","keop","keoh"]});var eB=w((uCe,VH)=>{VH.exports=["ke","keg","kegg","kegs","ken","kenj","kenh","ked","kel","kelg","kelm","kelb","kels","kelt","kelp","kelh","kem","keb","kebs","kes","kess","keng","kej","kec","kek","ket","kep","keh","kyeo","kyeog","kyeogg","kyeogs","kyeon","kyeonj","kyeonh","kyeod","kyeol","kyeolg","kyeolm","kyeolb","kyeols","kyeolt","kyeolp","kyeolh","kyeom","kyeob","kyeobs","kyeos","kyeoss","kyeong","kyeoj","kyeoc","kyeok","kyeot","kyeop","kyeoh","kye","kyeg","kyegg","kyegs","kyen","kyenj","kyenh","kyed","kyel","kyelg","kyelm","kyelb","kyels","kyelt","kyelp","kyelh","kyem","kyeb","kyebs","kyes","kyess","kyeng","kyej","kyec","kyek","kyet","kyep","kyeh","ko","kog","kogg","kogs","kon","konj","konh","kod","kol","kolg","kolm","kolb","kols","kolt","kolp","kolh","kom","kob","kobs","kos","koss","kong","koj","koc","kok","kot","kop","koh","kwa","kwag","kwagg","kwags","kwan","kwanj","kwanh","kwad","kwal","kwalg","kwalm","kwalb","kwals","kwalt","kwalp","kwalh","kwam","kwab","kwabs","kwas","kwass","kwang","kwaj","kwac","kwak","kwat","kwap","kwah","kwae","kwaeg","kwaegg","kwaegs","kwaen","kwaenj","kwaenh","kwaed","kwael","kwaelg","kwaelm","kwaelb","kwaels","kwaelt","kwaelp","kwaelh","kwaem","kwaeb","kwaebs","kwaes","kwaess","kwaeng","kwaej","kwaec","kwaek","kwaet","kwaep","kwaeh","koe","koeg","koegg","koegs","koen","koenj","koenh","koed","koel","koelg","koelm","koelb","koels","koelt","koelp","koelh","koem","koeb","koebs","koes","koess","koeng","koej","koec","koek","koet","koep","koeh","kyo","kyog","kyogg","kyogs","kyon","kyonj","kyonh","kyod","kyol","kyolg","kyolm","kyolb","kyols","kyolt","kyolp","kyolh","kyom","kyob","kyobs","kyos","kyoss","kyong","kyoj","kyoc","kyok","kyot","kyop","kyoh","ku","kug","kugg","kugs","kun","kunj","kunh","kud","kul","kulg","kulm","kulb","kuls","kult","kulp","kulh","kum","kub","kubs","kus","kuss","kung","kuj","kuc","kuk","kut","kup","kuh","kweo","kweog","kweogg","kweogs"]});var iB=w((cCe,tB)=>{tB.exports=["kweon","kweonj","kweonh","kweod","kweol","kweolg","kweolm","kweolb","kweols","kweolt","kweolp","kweolh","kweom","kweob","kweobs","kweos","kweoss","kweong","kweoj","kweoc","kweok","kweot","kweop","kweoh","kwe","kweg","kwegg","kwegs","kwen","kwenj","kwenh","kwed","kwel","kwelg","kwelm","kwelb","kwels","kwelt","kwelp","kwelh","kwem","kweb","kwebs","kwes","kwess","kweng","kwej","kwec","kwek","kwet","kwep","kweh","kwi","kwig","kwigg","kwigs","kwin","kwinj","kwinh","kwid","kwil","kwilg","kwilm","kwilb","kwils","kwilt","kwilp","kwilh","kwim","kwib","kwibs","kwis","kwiss","kwing","kwij","kwic","kwik","kwit","kwip","kwih","kyu","kyug","kyugg","kyugs","kyun","kyunj","kyunh","kyud","kyul","kyulg","kyulm","kyulb","kyuls","kyult","kyulp","kyulh","kyum","kyub","kyubs","kyus","kyuss","kyung","kyuj","kyuc","kyuk","kyut","kyup","kyuh","keu","keug","keugg","keugs","keun","keunj","keunh","keud","keul","keulg","keulm","keulb","keuls","keult","keulp","keulh","keum","keub","keubs","keus","keuss","keung","keuj","keuc","keuk","keut","keup","keuh","kyi","kyig","kyigg","kyigs","kyin","kyinj","kyinh","kyid","kyil","kyilg","kyilm","kyilb","kyils","kyilt","kyilp","kyilh","kyim","kyib","kyibs","kyis","kyiss","kying","kyij","kyic","kyik","kyit","kyip","kyih","ki","kig","kigg","kigs","kin","kinj","kinh","kid","kil","kilg","kilm","kilb","kils","kilt","kilp","kilh","kim","kib","kibs","kis","kiss","king","kij","kic","kik","kit","kip","kih","ta","tag","tagg","tags","tan","tanj","tanh","tad","tal","talg","talm","talb","tals","talt","talp","talh","tam","tab","tabs","tas","tass","tang","taj","tac","tak","tat","tap","tah","tae","taeg","taegg","taegs","taen","taenj","taenh","taed","tael","taelg","taelm","taelb","taels","taelt","taelp","taelh","taem","taeb","taebs","taes","taess","taeng","taej","taec","taek","taet","taep","taeh","tya","tyag","tyagg","tyags","tyan","tyanj","tyanh","tyad"]});var rB=w((dCe,nB)=>{nB.exports=["tyal","tyalg","tyalm","tyalb","tyals","tyalt","tyalp","tyalh","tyam","tyab","tyabs","tyas","tyass","tyang","tyaj","tyac","tyak","tyat","tyap","tyah","tyae","tyaeg","tyaegg","tyaegs","tyaen","tyaenj","tyaenh","tyaed","tyael","tyaelg","tyaelm","tyaelb","tyaels","tyaelt","tyaelp","tyaelh","tyaem","tyaeb","tyaebs","tyaes","tyaess","tyaeng","tyaej","tyaec","tyaek","tyaet","tyaep","tyaeh","teo","teog","teogg","teogs","teon","teonj","teonh","teod","teol","teolg","teolm","teolb","teols","teolt","teolp","teolh","teom","teob","teobs","teos","teoss","teong","teoj","teoc","teok","teot","teop","teoh","te","teg","tegg","tegs","ten","tenj","tenh","ted","tel","telg","telm","telb","tels","telt","telp","telh","tem","teb","tebs","tes","tess","teng","tej","tec","tek","tet","tep","teh","tyeo","tyeog","tyeogg","tyeogs","tyeon","tyeonj","tyeonh","tyeod","tyeol","tyeolg","tyeolm","tyeolb","tyeols","tyeolt","tyeolp","tyeolh","tyeom","tyeob","tyeobs","tyeos","tyeoss","tyeong","tyeoj","tyeoc","tyeok","tyeot","tyeop","tyeoh","tye","tyeg","tyegg","tyegs","tyen","tyenj","tyenh","tyed","tyel","tyelg","tyelm","tyelb","tyels","tyelt","tyelp","tyelh","tyem","tyeb","tyebs","tyes","tyess","tyeng","tyej","tyec","tyek","tyet","tyep","tyeh","to","tog","togg","togs","ton","tonj","tonh","tod","tol","tolg","tolm","tolb","tols","tolt","tolp","tolh","tom","tob","tobs","tos","toss","tong","toj","toc","tok","tot","top","toh","twa","twag","twagg","twags","twan","twanj","twanh","twad","twal","twalg","twalm","twalb","twals","twalt","twalp","twalh","twam","twab","twabs","twas","twass","twang","twaj","twac","twak","twat","twap","twah","twae","twaeg","twaegg","twaegs","twaen","twaenj","twaenh","twaed","twael","twaelg","twaelm","twaelb","twaels","twaelt","twaelp","twaelh","twaem","twaeb","twaebs","twaes","twaess","twaeng","twaej","twaec","twaek","twaet","twaep","twaeh","toe","toeg","toegg","toegs","toen","toenj","toenh","toed","toel","toelg","toelm","toelb"]});var sB=w((hCe,oB)=>{oB.exports=["toels","toelt","toelp","toelh","toem","toeb","toebs","toes","toess","toeng","toej","toec","toek","toet","toep","toeh","tyo","tyog","tyogg","tyogs","tyon","tyonj","tyonh","tyod","tyol","tyolg","tyolm","tyolb","tyols","tyolt","tyolp","tyolh","tyom","tyob","tyobs","tyos","tyoss","tyong","tyoj","tyoc","tyok","tyot","tyop","tyoh","tu","tug","tugg","tugs","tun","tunj","tunh","tud","tul","tulg","tulm","tulb","tuls","tult","tulp","tulh","tum","tub","tubs","tus","tuss","tung","tuj","tuc","tuk","tut","tup","tuh","tweo","tweog","tweogg","tweogs","tweon","tweonj","tweonh","tweod","tweol","tweolg","tweolm","tweolb","tweols","tweolt","tweolp","tweolh","tweom","tweob","tweobs","tweos","tweoss","tweong","tweoj","tweoc","tweok","tweot","tweop","tweoh","twe","tweg","twegg","twegs","twen","twenj","twenh","twed","twel","twelg","twelm","twelb","twels","twelt","twelp","twelh","twem","tweb","twebs","twes","twess","tweng","twej","twec","twek","twet","twep","tweh","twi","twig","twigg","twigs","twin","twinj","twinh","twid","twil","twilg","twilm","twilb","twils","twilt","twilp","twilh","twim","twib","twibs","twis","twiss","twing","twij","twic","twik","twit","twip","twih","tyu","tyug","tyugg","tyugs","tyun","tyunj","tyunh","tyud","tyul","tyulg","tyulm","tyulb","tyuls","tyult","tyulp","tyulh","tyum","tyub","tyubs","tyus","tyuss","tyung","tyuj","tyuc","tyuk","tyut","tyup","tyuh","teu","teug","teugg","teugs","teun","teunj","teunh","teud","teul","teulg","teulm","teulb","teuls","teult","teulp","teulh","teum","teub","teubs","teus","teuss","teung","teuj","teuc","teuk","teut","teup","teuh","tyi","tyig","tyigg","tyigs","tyin","tyinj","tyinh","tyid","tyil","tyilg","tyilm","tyilb","tyils","tyilt","tyilp","tyilh","tyim","tyib","tyibs","tyis","tyiss","tying","tyij","tyic","tyik","tyit","tyip","tyih","ti","tig","tigg","tigs","tin","tinj","tinh","tid","til","tilg","tilm","tilb","tils","tilt","tilp","tilh"]});var lB=w((gCe,aB)=>{aB.exports=["tim","tib","tibs","tis","tiss","ting","tij","tic","tik","tit","tip","tih","pa","pag","pagg","pags","pan","panj","panh","pad","pal","palg","palm","palb","pals","palt","palp","palh","pam","pab","pabs","pas","pass","pang","paj","pac","pak","pat","pap","pah","pae","paeg","paegg","paegs","paen","paenj","paenh","paed","pael","paelg","paelm","paelb","paels","paelt","paelp","paelh","paem","paeb","paebs","paes","paess","paeng","paej","paec","paek","paet","paep","paeh","pya","pyag","pyagg","pyags","pyan","pyanj","pyanh","pyad","pyal","pyalg","pyalm","pyalb","pyals","pyalt","pyalp","pyalh","pyam","pyab","pyabs","pyas","pyass","pyang","pyaj","pyac","pyak","pyat","pyap","pyah","pyae","pyaeg","pyaegg","pyaegs","pyaen","pyaenj","pyaenh","pyaed","pyael","pyaelg","pyaelm","pyaelb","pyaels","pyaelt","pyaelp","pyaelh","pyaem","pyaeb","pyaebs","pyaes","pyaess","pyaeng","pyaej","pyaec","pyaek","pyaet","pyaep","pyaeh","peo","peog","peogg","peogs","peon","peonj","peonh","peod","peol","peolg","peolm","peolb","peols","peolt","peolp","peolh","peom","peob","peobs","peos","peoss","peong","peoj","peoc","peok","peot","peop","peoh","pe","peg","pegg","pegs","pen","penj","penh","ped","pel","pelg","pelm","pelb","pels","pelt","pelp","pelh","pem","peb","pebs","pes","pess","peng","pej","pec","pek","pet","pep","peh","pyeo","pyeog","pyeogg","pyeogs","pyeon","pyeonj","pyeonh","pyeod","pyeol","pyeolg","pyeolm","pyeolb","pyeols","pyeolt","pyeolp","pyeolh","pyeom","pyeob","pyeobs","pyeos","pyeoss","pyeong","pyeoj","pyeoc","pyeok","pyeot","pyeop","pyeoh","pye","pyeg","pyegg","pyegs","pyen","pyenj","pyenh","pyed","pyel","pyelg","pyelm","pyelb","pyels","pyelt","pyelp","pyelh","pyem","pyeb","pyebs","pyes","pyess","pyeng","pyej","pyec","pyek","pyet","pyep","pyeh","po","pog","pogg","pogs","pon","ponj","ponh","pod","pol","polg","polm","polb","pols","polt","polp","polh","pom","pob","pobs","pos"]});var cB=w((pCe,uB)=>{uB.exports=["poss","pong","poj","poc","pok","pot","pop","poh","pwa","pwag","pwagg","pwags","pwan","pwanj","pwanh","pwad","pwal","pwalg","pwalm","pwalb","pwals","pwalt","pwalp","pwalh","pwam","pwab","pwabs","pwas","pwass","pwang","pwaj","pwac","pwak","pwat","pwap","pwah","pwae","pwaeg","pwaegg","pwaegs","pwaen","pwaenj","pwaenh","pwaed","pwael","pwaelg","pwaelm","pwaelb","pwaels","pwaelt","pwaelp","pwaelh","pwaem","pwaeb","pwaebs","pwaes","pwaess","pwaeng","pwaej","pwaec","pwaek","pwaet","pwaep","pwaeh","poe","poeg","poegg","poegs","poen","poenj","poenh","poed","poel","poelg","poelm","poelb","poels","poelt","poelp","poelh","poem","poeb","poebs","poes","poess","poeng","poej","poec","poek","poet","poep","poeh","pyo","pyog","pyogg","pyogs","pyon","pyonj","pyonh","pyod","pyol","pyolg","pyolm","pyolb","pyols","pyolt","pyolp","pyolh","pyom","pyob","pyobs","pyos","pyoss","pyong","pyoj","pyoc","pyok","pyot","pyop","pyoh","pu","pug","pugg","pugs","pun","punj","punh","pud","pul","pulg","pulm","pulb","puls","pult","pulp","pulh","pum","pub","pubs","pus","puss","pung","puj","puc","puk","put","pup","puh","pweo","pweog","pweogg","pweogs","pweon","pweonj","pweonh","pweod","pweol","pweolg","pweolm","pweolb","pweols","pweolt","pweolp","pweolh","pweom","pweob","pweobs","pweos","pweoss","pweong","pweoj","pweoc","pweok","pweot","pweop","pweoh","pwe","pweg","pwegg","pwegs","pwen","pwenj","pwenh","pwed","pwel","pwelg","pwelm","pwelb","pwels","pwelt","pwelp","pwelh","pwem","pweb","pwebs","pwes","pwess","pweng","pwej","pwec","pwek","pwet","pwep","pweh","pwi","pwig","pwigg","pwigs","pwin","pwinj","pwinh","pwid","pwil","pwilg","pwilm","pwilb","pwils","pwilt","pwilp","pwilh","pwim","pwib","pwibs","pwis","pwiss","pwing","pwij","pwic","pwik","pwit","pwip","pwih","pyu","pyug","pyugg","pyugs","pyun","pyunj","pyunh","pyud","pyul","pyulg","pyulm","pyulb","pyuls","pyult","pyulp","pyulh","pyum","pyub","pyubs","pyus","pyuss","pyung","pyuj","pyuc"]});var hB=w((fCe,dB)=>{dB.exports=["pyuk","pyut","pyup","pyuh","peu","peug","peugg","peugs","peun","peunj","peunh","peud","peul","peulg","peulm","peulb","peuls","peult","peulp","peulh","peum","peub","peubs","peus","peuss","peung","peuj","peuc","peuk","peut","peup","peuh","pyi","pyig","pyigg","pyigs","pyin","pyinj","pyinh","pyid","pyil","pyilg","pyilm","pyilb","pyils","pyilt","pyilp","pyilh","pyim","pyib","pyibs","pyis","pyiss","pying","pyij","pyic","pyik","pyit","pyip","pyih","pi","pig","pigg","pigs","pin","pinj","pinh","pid","pil","pilg","pilm","pilb","pils","pilt","pilp","pilh","pim","pib","pibs","pis","piss","ping","pij","pic","pik","pit","pip","pih","ha","hag","hagg","hags","han","hanj","hanh","had","hal","halg","halm","halb","hals","halt","halp","halh","ham","hab","habs","has","hass","hang","haj","hac","hak","hat","hap","hah","hae","haeg","haegg","haegs","haen","haenj","haenh","haed","hael","haelg","haelm","haelb","haels","haelt","haelp","haelh","haem","haeb","haebs","haes","haess","haeng","haej","haec","haek","haet","haep","haeh","hya","hyag","hyagg","hyags","hyan","hyanj","hyanh","hyad","hyal","hyalg","hyalm","hyalb","hyals","hyalt","hyalp","hyalh","hyam","hyab","hyabs","hyas","hyass","hyang","hyaj","hyac","hyak","hyat","hyap","hyah","hyae","hyaeg","hyaegg","hyaegs","hyaen","hyaenj","hyaenh","hyaed","hyael","hyaelg","hyaelm","hyaelb","hyaels","hyaelt","hyaelp","hyaelh","hyaem","hyaeb","hyaebs","hyaes","hyaess","hyaeng","hyaej","hyaec","hyaek","hyaet","hyaep","hyaeh","heo","heog","heogg","heogs","heon","heonj","heonh","heod","heol","heolg","heolm","heolb","heols","heolt","heolp","heolh","heom","heob","heobs","heos","heoss","heong","heoj","heoc","heok","heot","heop","heoh","he","heg","hegg","hegs","hen","henj","henh","hed","hel","helg","helm","helb","hels","helt","help","helh","hem","heb","hebs","hes","hess","heng","hej","hec","hek","het","hep","heh"]});var pB=w((mCe,gB)=>{gB.exports=["hyeo","hyeog","hyeogg","hyeogs","hyeon","hyeonj","hyeonh","hyeod","hyeol","hyeolg","hyeolm","hyeolb","hyeols","hyeolt","hyeolp","hyeolh","hyeom","hyeob","hyeobs","hyeos","hyeoss","hyeong","hyeoj","hyeoc","hyeok","hyeot","hyeop","hyeoh","hye","hyeg","hyegg","hyegs","hyen","hyenj","hyenh","hyed","hyel","hyelg","hyelm","hyelb","hyels","hyelt","hyelp","hyelh","hyem","hyeb","hyebs","hyes","hyess","hyeng","hyej","hyec","hyek","hyet","hyep","hyeh","ho","hog","hogg","hogs","hon","honj","honh","hod","hol","holg","holm","holb","hols","holt","holp","holh","hom","hob","hobs","hos","hoss","hong","hoj","hoc","hok","hot","hop","hoh","hwa","hwag","hwagg","hwags","hwan","hwanj","hwanh","hwad","hwal","hwalg","hwalm","hwalb","hwals","hwalt","hwalp","hwalh","hwam","hwab","hwabs","hwas","hwass","hwang","hwaj","hwac","hwak","hwat","hwap","hwah","hwae","hwaeg","hwaegg","hwaegs","hwaen","hwaenj","hwaenh","hwaed","hwael","hwaelg","hwaelm","hwaelb","hwaels","hwaelt","hwaelp","hwaelh","hwaem","hwaeb","hwaebs","hwaes","hwaess","hwaeng","hwaej","hwaec","hwaek","hwaet","hwaep","hwaeh","hoe","hoeg","hoegg","hoegs","hoen","hoenj","hoenh","hoed","hoel","hoelg","hoelm","hoelb","hoels","hoelt","hoelp","hoelh","hoem","hoeb","hoebs","hoes","hoess","hoeng","hoej","hoec","hoek","hoet","hoep","hoeh","hyo","hyog","hyogg","hyogs","hyon","hyonj","hyonh","hyod","hyol","hyolg","hyolm","hyolb","hyols","hyolt","hyolp","hyolh","hyom","hyob","hyobs","hyos","hyoss","hyong","hyoj","hyoc","hyok","hyot","hyop","hyoh","hu","hug","hugg","hugs","hun","hunj","hunh","hud","hul","hulg","hulm","hulb","huls","hult","hulp","hulh","hum","hub","hubs","hus","huss","hung","huj","huc","huk","hut","hup","huh","hweo","hweog","hweogg","hweogs","hweon","hweonj","hweonh","hweod","hweol","hweolg","hweolm","hweolb","hweols","hweolt","hweolp","hweolh","hweom","hweob","hweobs","hweos","hweoss","hweong","hweoj","hweoc","hweok","hweot","hweop","hweoh","hwe","hweg","hwegg","hwegs"]});var mB=w((bCe,fB)=>{fB.exports=["hwen","hwenj","hwenh","hwed","hwel","hwelg","hwelm","hwelb","hwels","hwelt","hwelp","hwelh","hwem","hweb","hwebs","hwes","hwess","hweng","hwej","hwec","hwek","hwet","hwep","hweh","hwi","hwig","hwigg","hwigs","hwin","hwinj","hwinh","hwid","hwil","hwilg","hwilm","hwilb","hwils","hwilt","hwilp","hwilh","hwim","hwib","hwibs","hwis","hwiss","hwing","hwij","hwic","hwik","hwit","hwip","hwih","hyu","hyug","hyugg","hyugs","hyun","hyunj","hyunh","hyud","hyul","hyulg","hyulm","hyulb","hyuls","hyult","hyulp","hyulh","hyum","hyub","hyubs","hyus","hyuss","hyung","hyuj","hyuc","hyuk","hyut","hyup","hyuh","heu","heug","heugg","heugs","heun","heunj","heunh","heud","heul","heulg","heulm","heulb","heuls","heult","heulp","heulh","heum","heub","heubs","heus","heuss","heung","heuj","heuc","heuk","heut","heup","heuh","hyi","hyig","hyigg","hyigs","hyin","hyinj","hyinh","hyid","hyil","hyilg","hyilm","hyilb","hyils","hyilt","hyilp","hyilh","hyim","hyib","hyibs","hyis","hyiss","hying","hyij","hyic","hyik","hyit","hyip","hyih","hi","hig","higg","higs","hin","hinj","hinh","hid","hil","hilg","hilm","hilb","hils","hilt","hilp","hilh","him","hib","hibs","his","hiss","hing","hij","hic","hik","hit","hip","hih","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var yB=w((yCe,bB)=>{bB.exports=["Kay ","Kayng ","Ke ","Ko ","Kol ","Koc ","Kwi ","Kwi ","Kyun ","Kul ","Kum ","Na ","Na ","Na ","La ","Na ","Na ","Na ","Na ","Na ","Nak ","Nak ","Nak ","Nak ","Nak ","Nak ","Nak ","Nan ","Nan ","Nan ","Nan ","Nan ","Nan ","Nam ","Nam ","Nam ","Nam ","Nap ","Nap ","Nap ","Nang ","Nang ","Nang ","Nang ","Nang ","Nay ","Nayng ","No ","No ","No ","No ","No ","No ","No ","No ","No ","No ","No ","No ","Nok ","Nok ","Nok ","Nok ","Nok ","Nok ","Non ","Nong ","Nong ","Nong ","Nong ","Noy ","Noy ","Noy ","Noy ","Nwu ","Nwu ","Nwu ","Nwu ","Nwu ","Nwu ","Nwu ","Nwu ","Nuk ","Nuk ","Num ","Nung ","Nung ","Nung ","Nung ","Nung ","Twu ","La ","Lak ","Lak ","Lan ","Lyeng ","Lo ","Lyul ","Li ","Pey ","Pen ","Pyen ","Pwu ","Pwul ","Pi ","Sak ","Sak ","Sam ","Sayk ","Sayng ","Sep ","Sey ","Sway ","Sin ","Sim ","Sip ","Ya ","Yak ","Yak ","Yang ","Yang ","Yang ","Yang ","Yang ","Yang ","Yang ","Yang ","Ye ","Ye ","Ye ","Ye ","Ye ","Ye ","Ye ","Ye ","Ye ","Ye ","Ye ","Yek ","Yek ","Yek ","Yek ","Yen ","Yen ","Yen ","Yen ","Yen ","Yen ","Yen ","Yen ","Yen ","Yen ","Yen ","Yen ","Yen ","Yen ","Yel ","Yel ","Yel ","Yel ","Yel ","Yel ","Yem ","Yem ","Yem ","Yem ","Yem ","Yep ","Yeng ","Yeng ","Yeng ","Yeng ","Yeng ","Yeng ","Yeng ","Yeng ","Yeng ","Yeng ","Yeng ","Yeng ","Yeng ","Yey ","Yey ","Yey ","Yey ","O ","Yo ","Yo ","Yo ","Yo ","Yo ","Yo ","Yo ","Yo ","Yo ","Yo ","Yong ","Wun ","Wen ","Yu ","Yu ","Yu ","Yu ","Yu ","Yu ","Yu ","Yu ","Yu ","Yu ","Yuk ","Yuk ","Yuk ","Yun ","Yun ","Yun ","Yun ","Yul ","Yul ","Yul ","Yul ","Yung ","I ","I ","I ","I ","I ","I ","I ","I ","I ","I ","I ","I ","I ","I ","Ik ","Ik ","In ","In ","In ","In ","In ","In ","In ","Im ","Im ","Im ","Ip ","Ip ","Ip ","Cang ","Cek ","Ci ","Cip ","Cha ","Chek "]});var wB=w((vCe,vB)=>{vB.exports=["Chey ","Thak ","Thak ","Thang ","Thayk ","Thong ","Pho ","Phok ","Hang ","Hang ","Hyen ","Hwak ","Wu ","Huo ","[?] ","[?] ","Zhong ","[?] ","Qing ","[?] ","[?] ","Xi ","Zhu ","Yi ","Li ","Shen ","Xiang ","Fu ","Jing ","Jing ","Yu ","[?] ","Hagi ","[?] ","Zhu ","[?] ","[?] ","Yi ","Du ","[?] ","[?] ","[?] ","Fan ","Si ","Guan ","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]"]});var CB=w((wCe,xB)=>{xB.exports=["ff","fi","fl","ffi","ffl","st","st","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","mn","me","mi","vn","mkh","[?]","[?]","[?]","[?]","[?]","yi","","ay","`","","d","h","k","l","m","m","t","+","sh","s","sh","s","a","a","","b","g","d","h","v","z","[?]","t","y","k","k","l","[?]","l","[?]","n","n","[?]","p","p","[?]","ts","ts","r","sh","t","vo","b","k","p","l","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""]});var DB=w((xCe,SB)=>{SB.exports=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""]});var kB=w((CCe,TB)=>{TB.exports=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","","","","","","","","","","","","","[?]","[?]","[?]"]});var RB=w((SCe,PB)=>{PB.exports=["[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","","","","~","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","..","--","-","_","_","(",") ","{","} ","[","] ","[(",")] ","<<",">> ","<","> ","[","] ","{","}","[?]","[?]","[?]","[?]","","","","","","","",",",",",".","",";",":","?","!","-","(",")","{","}","{","}","#","&","*","+","-","<",">","=","","\\","$","%","@","[?]","[?]","[?]","[?]","","","","[?]","","[?]","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","[?]","[?]",""]});var EB=w((DCe,_B)=>{_B.exports=["[?]","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/","0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","[","\\","]","^","_","`","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","{","|","}","~","[?]","[?]",".","[","]",",","*","wo","a","i","u","e","o","ya","yu","yo","tu","+","a","i","u","e","o","ka","ki","ku","ke","ko","sa","si","su","se","so","ta","ti","tu","te","to","na","ni","nu","ne","no","ha","hi","hu","he","ho","ma","mi","mu","me","mo","ya","yu","yo","ra","ri","ru","re","ro","wa","n",":",";","","g","gg","gs","n","nj","nh","d","dd","r","lg","lm","lb","ls","lt","lp","rh","m","b","bb","bs","s","ss","","j","jj","c","k","t","p","h","[?]","[?]","[?]","a","ae","ya","yae","eo","e","[?]","[?]","yeo","ye","o","wa","wae","oe","[?]","[?]","yo","u","weo","we","wi","yu","[?]","[?]","eu","yi","i","[?]","[?]","[?]","/C","PS","!","-","|","Y=","W=","[?]","|","-","|","-","|","#","O","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","[?]","{","|","}","","","",""]});var LB=w((TCe,IB)=>{"use strict";var L={},see=/(?![\x00-\x7F]|[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3})./g;IB.exports=function(n){return n.replace(see,aee)};function aee(n){var e=uee(n);if(e>65535)return"_";var t=e>>8,i=e&255;if(t>24&&t<30||t>215&&t<249)return"";if(!L[t])switch(lee(t)){case"00":L[t]=zM();break;case"01":L[t]=QM();break;case"02":L[t]=ej();break;case"03":L[t]=ij();break;case"04":L[t]=rj();break;case"05":L[t]=sj();break;case"06":L[t]=lj();break;case"07":L[t]=cj();break;case"09":L[t]=hj();break;case"0a":L[t]=pj();break;case"0b":L[t]=mj();break;case"0c":L[t]=yj();break;case"0d":L[t]=wj();break;case"0e":L[t]=Cj();break;case"0f":L[t]=Dj();break;case"10":L[t]=kj();break;case"11":L[t]=Rj();break;case"12":L[t]=Ej();break;case"13":L[t]=Lj();break;case"14":L[t]=Mj();break;case"15":L[t]=Oj();break;case"16":L[t]=Nj();break;case"17":L[t]=Bj();break;case"18":L[t]=Wj();break;case"1e":L[t]=Zj();break;case"1f":L[t]=$j();break;case"20":L[t]=Xj();break;case"21":L[t]=zj();break;case"22":L[t]=Qj();break;case"23":L[t]=eO();break;case"24":L[t]=iO();break;case"25":L[t]=rO();break;case"26":L[t]=sO();break;case"27":L[t]=lO();break;case"28":L[t]=cO();break;case"2e":L[t]=hO();break;case"2f":L[t]=pO();break;case"30":L[t]=mO();break;case"31":L[t]=yO();break;case"32":L[t]=wO();break;case"33":L[t]=CO();break;case"4d":L[t]=DO();break;case"4e":L[t]=kO();break;case"4f":L[t]=RO();break;case"50":L[t]=EO();break;case"51":L[t]=LO();break;case"52":L[t]=MO();break;case"53":L[t]=OO();break;case"54":L[t]=NO();break;case"55":L[t]=BO();break;case"56":L[t]=WO();break;case"57":L[t]=ZO();break;case"58":L[t]=$O();break;case"59":L[t]=XO();break;case"5a":L[t]=zO();break;case"5b":L[t]=QO();break;case"5c":L[t]=e1();break;case"5d":L[t]=i1();break;case"5e":L[t]=r1();break;case"5f":L[t]=s1();break;case"60":L[t]=l1();break;case"61":L[t]=c1();break;case"62":L[t]=h1();break;case"63":L[t]=p1();break;case"64":L[t]=m1();break;case"65":L[t]=y1();break;case"66":L[t]=w1();break;case"67":L[t]=C1();break;case"68":L[t]=D1();break;case"69":L[t]=k1();break;case"6a":L[t]=R1();break;case"6b":L[t]=E1();break;case"6c":L[t]=L1();break;case"6d":L[t]=M1();break;case"6e":L[t]=O1();break;case"6f":L[t]=N1();break;case"70":L[t]=B1();break;case"71":L[t]=W1();break;case"72":L[t]=Z1();break;case"73":L[t]=$1();break;case"74":L[t]=X1();break;case"75":L[t]=z1();break;case"76":L[t]=Q1();break;case"77":L[t]=eA();break;case"78":L[t]=iA();break;case"79":L[t]=rA();break;case"7a":L[t]=sA();break;case"7b":L[t]=lA();break;case"7c":L[t]=cA();break;case"7d":L[t]=hA();break;case"7e":L[t]=pA();break;case"7f":L[t]=mA();break;case"80":L[t]=yA();break;case"81":L[t]=wA();break;case"82":L[t]=CA();break;case"83":L[t]=DA();break;case"84":L[t]=kA();break;case"85":L[t]=RA();break;case"86":L[t]=EA();break;case"87":L[t]=LA();break;case"88":L[t]=MA();break;case"89":L[t]=OA();break;case"8a":L[t]=NA();break;case"8b":L[t]=BA();break;case"8c":L[t]=WA();break;case"8d":L[t]=ZA();break;case"8e":L[t]=$A();break;case"8f":L[t]=XA();break;case"90":L[t]=zA();break;case"91":L[t]=QA();break;case"92":L[t]=eN();break;case"93":L[t]=iN();break;case"94":L[t]=rN();break;case"95":L[t]=sN();break;case"96":L[t]=lN();break;case"97":L[t]=cN();break;case"98":L[t]=hN();break;case"99":L[t]=pN();break;case"9a":L[t]=mN();break;case"9b":L[t]=yN();break;case"9c":L[t]=wN();break;case"9d":L[t]=CN();break;case"9e":L[t]=DN();break;case"9f":L[t]=kN();break;case"a0":L[t]=RN();break;case"a1":L[t]=EN();break;case"a2":L[t]=LN();break;case"a3":L[t]=MN();break;case"a4":L[t]=ON();break;case"ac":L[t]=NN();break;case"ad":L[t]=BN();break;case"ae":L[t]=WN();break;case"af":L[t]=ZN();break;case"b0":L[t]=$N();break;case"b1":L[t]=XN();break;case"b2":L[t]=zN();break;case"b3":L[t]=QN();break;case"b4":L[t]=eH();break;case"b5":L[t]=iH();break;case"b6":L[t]=rH();break;case"b7":L[t]=sH();break;case"b8":L[t]=lH();break;case"b9":L[t]=cH();break;case"ba":L[t]=hH();break;case"bb":L[t]=pH();break;case"bc":L[t]=mH();break;case"bd":L[t]=yH();break;case"be":L[t]=wH();break;case"bf":L[t]=CH();break;case"c0":L[t]=DH();break;case"c1":L[t]=kH();break;case"c2":L[t]=RH();break;case"c3":L[t]=EH();break;case"c4":L[t]=LH();break;case"c5":L[t]=MH();break;case"c6":L[t]=OH();break;case"c7":L[t]=NH();break;case"c8":L[t]=BH();break;case"c9":L[t]=WH();break;case"ca":L[t]=ZH();break;case"cb":L[t]=$H();break;case"cc":L[t]=XH();break;case"cd":L[t]=zH();break;case"ce":L[t]=QH();break;case"cf":L[t]=eB();break;case"d0":L[t]=iB();break;case"d1":L[t]=rB();break;case"d2":L[t]=sB();break;case"d3":L[t]=lB();break;case"d4":L[t]=cB();break;case"d5":L[t]=hB();break;case"d6":L[t]=pB();break;case"d7":L[t]=mB();break;case"f9":L[t]=yB();break;case"fa":L[t]=wB();break;case"fb":L[t]=CB();break;case"fc":L[t]=DB();break;case"fd":L[t]=kB();break;case"fe":L[t]=RB();break;case"ff":L[t]=EB();break;default:return""}return L[t][i]}function lee(n){return(n+256).toString(16).substr(-2)}function uee(n){for(var e,t,i,r,o,s,a;Array.isArray(n);)n=n[0];switch(n.length){case 1:return co(n);case 2:return e=co(n.substr(0,1)),t=co(n.substr(1,1)),o=(e&3)<<6|t&63,s=(e&28)>>2,s<<8|o;case 3:return e=co(n.substr(0,1)),t=co(n.substr(1,1)),i=co(n.substr(2,1)),o=(t&3)<<6|i&63,s=(e&15)<<4|(t&60)>>2,s<<8|o;default:return e=co(n.substr(0,1)),t=co(n.substr(1,1)),i=co(n.substr(2,1)),r=co(n.substr(3,1)),o=(i&3)<<6|r&63,s=(t&15)<<4|(i&60)>>2,a=(e&7)<<5|(t&48)>>4,a<<16|s<<8|o}}function co(n){var e=n+"",t=e.charCodeAt(0);if(55296<=t&&t<=56319){var i=t;if(e.length===1)return t;var r=e.charCodeAt(1);return(i-55296)*1024+(r-56320)+65536}return 56320<=t&&t<=57343,t}});var ot,F,R,Pt,Ab,Yi,ft,ho,pn,Nb,ni,go,sr,aD,FB,Hb,fi,za,de=D(()=>{"use strict";ot=require("util"),F=require("fs"),R=require("path"),Pt=require("os"),Ab=require("crypto"),Yi=fI(),ft=aS(),ho=require("readline"),pn=require("child_process"),Nb=kS(),ni=CL(),go=qL(),sr=AM(),aD=require("vm"),FB=require("net"),Hb=jb(),fi=XM(),za=LB()});function OB(n){switch(n.toLowerCase()){case"trace":return 0;case"debug":return 1;case"info":return 2;case"error":return 4;case"warn":case"warning":return 3;case"off":return 5;default:return 2}}function MB(n,e=2,t=!1,i=!1){let r="";for(let o=0;o0?" ":"")+s}return r}function jB(n){switch(n){case 1:return"DEBUG";case 4:return"ERROR";case 2:return"INFO";case 0:return"TRACE";case 3:return"WARN"}return""}function Kd(n){return`${zd(n.getHours())}:${zd(n.getMinutes())}:${zd(n.getSeconds())}.${pee(n.getMilliseconds())}`}var cee,dee,hee,gee,zd,pee,lD,Bb,uD=D(()=>{"use strict";de();cee=5*1024*1024,dee="\x1B[33m",hee="\x1B[39m",gee=2,zd=n=>n<10?`0${n}`:n.toString(),pee=n=>n<10?`00${n}`:n<100?`0${n}`:n.toString();lD=class{constructor(){this.level=gee}setLevel(e){this.level!==e&&(this.level=e)}getLevel(){return this.level}},Bb=class extends lD{constructor(t,i,r){super();this.fsPath=t;this.backupIndex=1;this.useConsole=!1;this.loggers=new Map;this.config=Object.assign({userFormatters:!0,color:!1,depth:2,showHidden:!1},r),this.setLevel(i),this.promise=this.initialize()}switchConsole(){this.useConsole=!this.useConsole}format(t){let{color:i,showHidden:r,depth:o}=this.config;return MB(t,o,i,r)}createLogger(t){let i=this.loggers.has(t)?this.loggers.get(t):{category:t,mark:()=>{},getLevel:()=>this.getLevel(),trace:(...r)=>{this.level<=0&&this._log(0,t,r,this.getCurrentTimestamp())},debug:(...r)=>{this.level<=1&&this._log(1,t,r,this.getCurrentTimestamp())},log:(...r)=>{this.level<=2&&this._log(2,t,r,this.getCurrentTimestamp())},info:(...r)=>{this.level<=2&&this._log(2,t,r,this.getCurrentTimestamp())},warn:(...r)=>{this.level<=3&&this._log(3,t,r,this.getCurrentTimestamp())},error:(...r)=>{this.level<=4&&this._log(4,t,r,this.getCurrentTimestamp())},fatal:(...r)=>{this.level<=4&&this._log(4,t,r,this.getCurrentTimestamp())},flush:()=>this.promise};return this.loggers.set(t,i),i}async initialize(){return Promise.resolve()}shouldBackup(t){return t>cee}_log(t,i,r,o){if(this.useConsole)console[t===4?"error":"log"](`${jB(t)} [${i}]`,MB(r,null,!0));else{let s=this.format(r);this.promise=this.promise.then(()=>(async()=>{let l;this.config.userFormatters!==!1?l=`${[o,jB(t),`(pid:${process.pid})`,`[${i}]`].join(" ")} - ${s} +`:l=s,await(0,ot.promisify)(F.appendFile)(this.fsPath,l,{encoding:"utf8",flag:"a+"});let u=await(0,ot.promisify)(F.stat)(this.fsPath);if(this.shouldBackup(u.size)){let c=this.getBackupResource();await(0,ot.promisify)(F.rename)(this.fsPath,c)}})()).catch(a=>{!global.REVISION&&console.error(a)})}}getCurrentTimestamp(){let t=new Date;return`${t.getFullYear()}-${zd(t.getMonth()+1)}-${zd(t.getDate())}T${Kd(t)}`}getBackupResource(){return this.backupIndex=this.backupIndex>5?1:this.backupIndex,R.join(R.dirname(this.fsPath),`${R.basename(this.fsPath)}_${this.backupIndex++}`)}}});function pe(n,e){return n}function Ie(n,e){return n??e}function Zi(n){return n<=0?Promise.resolve(void 0):new Promise(e=>{setTimeout(()=>{e(void 0)},n).unref()})}function qb(n,e){return new Promise(t=>{let i=e.onCancellationRequested(()=>{clearTimeout(r),t(!0)}),r=setTimeout(()=>{i.dispose(),t(!1)},n);r.unref()})}function AB(){return new Promise(n=>{process.nextTick(()=>{n(void 0)})})}function ar(){return new Promise(n=>{setImmediate(()=>{n(void 0)})})}function Wb(n,e){let t,i=r=>{t&&clearTimeout(t),t=setTimeout(()=>{n()},r??e),t.unref()};return Object.defineProperty(i,"clear",{get:()=>()=>{clearTimeout(t)}}),i}function Vd(n,e,t=3){if(n.length==0)return Promise.resolve();let i=0,r=n.length,o=n.slice();return new Promise(s=>{let a=l=>{let u=()=>{if(i=i+1,i==r)s();else if(o.length){let c=o.shift();a(c)}};e(l).then(u,u)};for(let l=0;l{"use strict";Qd=new Map([["<",">"],[">","<"],["{","}"],["[","]"],["(",")"]])});var dD={};Ls(dD,{createLogger:()=>Z,emptyFile:()=>HB,getLoggerFile:()=>Yb,getTimestamp:()=>Kd,logger:()=>BB,resolveLogFilepath:()=>NB});function NB(){let n=process.env.NVIM_COC_LOG_FILE;if(n)return n;let e=process.env.XDG_RUNTIME_DIR;if(e)try{return F.accessSync(e,F.constants.R_OK|F.constants.W_OK),R.join(e,`coc-nvim-${process.pid}.log`)}catch{}let t=Pt.tmpdir();return e=R.join(t,`coc.nvim-${process.pid}`),F.mkdirSync(e,{recursive:!0}),R.join(e,"coc-nvim.log")}function HB(n){if(F.existsSync(n))try{F.writeFileSync(n,"",{encoding:"utf8",mode:438})}catch{}}function Yb(){return cD}function Z(n="coc.nvim"){return BB.createLogger(n)}var cD,fee,BB,xe=D(()=>{"use strict";uD();de();te();uD();cD=NB();HB(cD);fee=pe(process.env.NVIM_COC_LOG_LEVEL||"info","off"),BB=new Bb(cD,OB(fee),{color:!global.REVISION&&process.platform!=="win32",userFormatters:!0})});var WB=w((gD,qB)=>{qB.exports=hD(typeof Buffer<"u"&&Buffer)||hD(gD.Buffer)||hD(typeof window<"u"&&window.Buffer)||gD.Buffer;function hD(n){return n&&n.isBuffer&&n}});var JB=w((Eu,ZB)=>{var _u=Jn(),Eu=ZB.exports=YB(0);Eu.alloc=YB;Eu.concat=_u.concat;Eu.from=mee;function YB(n){return new Array(n)}function mee(n){if(!_u.isBuffer(n)&&_u.isView(n))n=_u.Uint8Array.from(n);else if(_u.isArrayBuffer(n))n=new Uint8Array(n);else{if(typeof n=="string")return _u.from.call(Eu,n);if(typeof n=="number")throw new TypeError('"value" argument must not be a number')}return Array.prototype.slice.call(n)}});var XB=w((Lu,UB)=>{var Wo=Jn(),Iu=Wo.global,Lu=UB.exports=Wo.hasBuffer?$B(0):[];Lu.alloc=Wo.hasBuffer&&Iu.alloc||$B;Lu.concat=Wo.concat;Lu.from=bee;function $B(n){return Iu.alloc(n)}function bee(n){if(!Wo.isBuffer(n)&&Wo.isView(n))n=Wo.Uint8Array.from(n);else if(Wo.isArrayBuffer(n))n=new Uint8Array(n);else{if(typeof n=="string")return Wo.from.call(Lu,n);if(typeof n=="number")throw new TypeError('"value" argument must not be a number')}return Iu.from&&Iu.from.length!==1?Iu.from(n):new Iu(n)}});var KB=w((Fu,zB)=>{var Zb=Jn(),Fu=zB.exports=Zb.hasArrayBuffer?GB(0):[];Fu.alloc=GB;Fu.concat=Zb.concat;Fu.from=yee;function GB(n){return new Uint8Array(n)}function yee(n){if(Zb.isView(n)){var e=n.byteOffset,t=n.byteLength;n=n.buffer,n.byteLength!==t&&(n.slice?n=n.slice(e,e+t):(n=new Uint8Array(n),n.byteLength!==t&&(n=Array.prototype.slice.call(n,e,e+t))))}else{if(typeof n=="string")return Zb.from.call(Fu,n);if(typeof n=="number")throw new TypeError('"value" argument must not be a number')}return new Uint8Array(n)}});var QB=w(Jb=>{Jb.copy=xee;Jb.toString=wee;Jb.write=vee;function vee(n,e){for(var t=this,i=e||(e|=0),r=n.length,o=0,s=0;s>>6,t[i++]=128|o&63):o<55296||o>57343?(t[i++]=224|o>>>12,t[i++]=128|o>>>6&63,t[i++]=128|o&63):(o=(o-55296<<10|n.charCodeAt(s++)-56320)+65536,t[i++]=240|o>>>18,t[i++]=128|o>>>12&63,t[i++]=128|o>>>6&63,t[i++]=128|o&63);return i-e}function wee(n,e,t){var i=this,r=e|0;t||(t=i.length);for(var o="",s=0;r=65536?(s-=65536,o+=String.fromCharCode((s>>>10)+55296,(s&1023)+56320)):o+=String.fromCharCode(s)}return o}function xee(n,e,t,i){var r;t||(t=0),!i&&i!==0&&(i=this.length),e||(e=0);var o=i-t;if(n===this&&t=0;r--)n[r+e]=this[r+t];else for(r=0;r{var pD=QB();eh.copy=iq;eh.slice=nq;eh.toString=Cee;eh.write=See("write");var Bs=Jn(),VB=Bs.global,eq=Bs.hasBuffer&&"TYPED_ARRAY_SUPPORT"in VB,tq=eq&&!VB.TYPED_ARRAY_SUPPORT;function iq(n,e,t,i){var r=Bs.isBuffer(this),o=Bs.isBuffer(n);if(r&&o)return this.copy(n,e,t,i);if(!tq&&!r&&!o&&Bs.isView(this)&&Bs.isView(n)){var s=t||i!=null?nq.call(this,t,i):this;return n.set(s,e),s.length}else return pD.copy.call(this,n,e,t,i)}function nq(n,e){var t=this.slice||!tq&&this.subarray;if(t)return t.call(this,n,e);var i=Bs.alloc.call(this,e-n);return iq.call(this,i,0,n,e),i}function Cee(n,e,t){var i=!eq&&Bs.isBuffer(this)?this.toString:pD.toString;return i.apply(this,arguments)}function See(n){return e;function e(){var t=this[n]||pD[n];return t.apply(this,arguments)}}});var Jn=w(fn=>{var fD=fn.global=WB(),aq=fn.hasBuffer=fD&&!!fD.isBuffer,bD=fn.hasArrayBuffer=typeof ArrayBuffer<"u";fn.isArrayBuffer=bD?_ee:vD;var Dee=fn.isBuffer=aq?fD.isBuffer:vD,Tee=fn.isView=bD?ArrayBuffer.isView||uq("ArrayBuffer","buffer"):vD;fn.alloc=yD;fn.concat=Pee;fn.from=kee;var rq=fn.Array=JB(),oq=fn.Buffer=XB(),sq=fn.Uint8Array=KB(),mD=fn.prototype=$b();function kee(n){return typeof n=="string"?Eee.call(this,n):lq(this).from(n)}function yD(n){return lq(this).alloc(n)}function Pee(n,e){e||(e=0,Array.prototype.forEach.call(n,o));var t=this!==fn&&this||n[0],i=yD.call(t,e),r=0;return Array.prototype.forEach.call(n,s),i;function o(a){e+=a.length}function s(a){r+=mD.copy.call(a,i,r)}}var Ree=uq("ArrayBuffer");function _ee(n){return n instanceof ArrayBuffer||Ree(n)}function Eee(n){var e=n.length*3,t=yD.call(this,e),i=mD.write.call(t,n);return e!==i&&(t=mD.slice.call(t,0,i)),t}function lq(n){return Dee(n)?oq:Tee(n)?sq:Array.isArray(n)?rq:aq?oq:bD?sq:rq}function vD(){return!1}function uq(n,e){return n="[object "+n+"]",function(t){return t!=null&&{}.toString.call(e?t[e]:t)===n}}});var Ub=w(cq=>{cq.ExtBuffer=wD;var Iee=Jn();function wD(n,e){if(!(this instanceof wD))return new wD(n,e);this.buffer=Iee.from(n),this.type=e}});var hq=w(dq=>{dq.setExtPackers=Mee;var Xb=Jn(),Lee=Xb.global,Or=Xb.Uint8Array.from,xD,Fee={name:1,message:1,stack:1,columnNumber:1,fileName:1,lineNumber:1};function Mee(n){n.addExtPacker(14,Error,[Ka,lr]),n.addExtPacker(1,EvalError,[Ka,lr]),n.addExtPacker(2,RangeError,[Ka,lr]),n.addExtPacker(3,ReferenceError,[Ka,lr]),n.addExtPacker(4,SyntaxError,[Ka,lr]),n.addExtPacker(5,TypeError,[Ka,lr]),n.addExtPacker(6,URIError,[Ka,lr]),n.addExtPacker(10,RegExp,[jee,lr]),n.addExtPacker(11,Boolean,[CD,lr]),n.addExtPacker(12,String,[CD,lr]),n.addExtPacker(13,Date,[Number,lr]),n.addExtPacker(15,Number,[CD,lr]),typeof Uint8Array<"u"&&(n.addExtPacker(17,Int8Array,Or),n.addExtPacker(18,Uint8Array,Or),n.addExtPacker(19,Int16Array,Or),n.addExtPacker(20,Uint16Array,Or),n.addExtPacker(21,Int32Array,Or),n.addExtPacker(22,Uint32Array,Or),n.addExtPacker(23,Float32Array,Or),typeof Float64Array<"u"&&n.addExtPacker(24,Float64Array,Or),typeof Uint8ClampedArray<"u"&&n.addExtPacker(25,Uint8ClampedArray,Or),n.addExtPacker(26,ArrayBuffer,Or),n.addExtPacker(29,DataView,Or)),Xb.hasBuffer&&n.addExtPacker(27,Lee,Xb.from)}function lr(n){return xD||(xD=SD().encode),xD(n)}function CD(n){return n.valueOf()}function jee(n){n=RegExp.prototype.toString.call(n).split("/"),n.shift();var e=[n.pop()];return e.unshift(n.join("/")),e}function Ka(n){var e={};for(var t in Fee)e[t]=n[t];return e}});var Gb=w(th=>{var Oee,Aee,Nee,Hee;(function(n){var e="undefined",t=e!==typeof Buffer&&Buffer,i=e!==typeof Uint8Array&&Uint8Array,r=e!==typeof ArrayBuffer&&ArrayBuffer,o=[0,0,0,0,0,0,0,0],s=Array.isArray||T,a=4294967296,l=16777216,u;Oee=c("Uint64BE",!0,!0),Aee=c("Int64BE",!0,!1),Nee=c("Uint64LE",!1,!0),Hee=c("Int64LE",!1,!1);function c(j,N,X){var se=N?0:4,Y=N?4:0,K=N?0:3,B=N?1:2,ge=N?2:1,ye=N?3:0,Fe=N?v:C,$=N?x:k,H=Te.prototype,z="is"+j,ee="_"+z;return H.buffer=void 0,H.offset=0,H[ee]=!0,H.toNumber=Ri,H.toString=Hn,H.toJSON=Ri,H.toArray=d,t&&(H.toBuffer=h),i&&(H.toArrayBuffer=g),Te[z]=Ze,n[j]=Te,Te;function Te(at,Ve,et,ze){return this instanceof Te?Ee(this,at,Ve,et,ze):new Te(at,Ve,et,ze)}function Ze(at){return!!(at&&at[ee])}function Ee(at,Ve,et,ze,xi){if(i&&r&&(Ve instanceof r&&(Ve=new i(Ve)),ze instanceof r&&(ze=new i(ze))),!Ve&&!et&&!ze&&!u){at.buffer=b(o,0);return}if(!f(Ve,et)){var Ir=u||Array;xi=et,ze=Ve,et=0,Ve=new Ir(8)}at.buffer=Ve,at.offset=et|=0,e!==typeof ze&&(typeof ze=="string"?Cn(Ve,et,ze,xi||10):f(ze,xi)?m(Ve,et,ze,xi):typeof xi=="number"?(Er(Ve,et+se,ze),Er(Ve,et+Y,xi)):ze>0?Fe(Ve,et,ze):ze<0?$(Ve,et,ze):m(Ve,et,o,0))}function Cn(at,Ve,et,ze){var xi=0,Ir=et.length,Sn=0,qn=0;et[0]==="-"&&xi++;for(var Ed=xi;xi=0))break;qn=qn*ze+db,Sn=Sn*ze+Math.floor(qn/a),qn%=a}Ed&&(Sn=~Sn,qn?qn=a-qn:Sn++),Er(at,Ve+se,Sn),Er(at,Ve+Y,qn)}function Ri(){var at=this.buffer,Ve=this.offset,et=Bn(at,Ve+se),ze=Bn(at,Ve+Y);return X||(et|=0),et?et*a+ze:ze}function Hn(at){var Ve=this.buffer,et=this.offset,ze=Bn(Ve,et+se),xi=Bn(Ve,et+Y),Ir="",Sn=!X&&ze&2147483648;for(Sn&&(ze=~ze,xi=a-xi),at=at||10;;){var qn=ze%at*a+xi;if(ze=Math.floor(ze/at),xi=Math.floor(qn/at),Ir=(qn%at).toString(at)+Ir,!ze&&!xi)break}return Sn&&(Ir="-"+Ir),Ir}function Er(at,Ve,et){at[Ve+ye]=et&255,et=et>>8,at[Ve+ge]=et&255,et=et>>8,at[Ve+B]=et&255,et=et>>8,at[Ve+K]=et&255}function Bn(at,Ve){return at[Ve+K]*l+(at[Ve+B]<<16)+(at[Ve+ge]<<8)+at[Ve+ye]}}function d(j){var N=this.buffer,X=this.offset;return u=null,j!==!1&&X===0&&N.length===8&&s(N)?N:b(N,X)}function h(j){var N=this.buffer,X=this.offset;if(u=t,j!==!1&&X===0&&N.length===8&&Buffer.isBuffer(N))return N;var se=new t(8);return m(se,0,N,X),se}function g(j){var N=this.buffer,X=this.offset,se=N.buffer;if(u=i,j!==!1&&X===0&&se instanceof r&&se.byteLength===8)return se;var Y=new i(8);return m(Y,0,N,X),Y.buffer}function f(j,N){var X=j&&j.length;return N|=0,X&&N+8<=X&&typeof j[N]!="string"}function m(j,N,X,se){N|=0,se|=0;for(var Y=0;Y<8;Y++)j[N++]=X[se++]&255}function b(j,N){return Array.prototype.slice.call(j,N,N+8)}function v(j,N,X){for(var se=N+8;se>N;)j[--se]=X&255,X/=256}function x(j,N,X){var se=N+8;for(X++;se>N;)j[--se]=-X&255^255,X/=256}function C(j,N,X){for(var se=N+8;N{DD.read=function(n,e,t,i,r){var o,s,a=r*8-i-1,l=(1<>1,c=-7,d=t?r-1:0,h=t?-1:1,g=n[e+d];for(d+=h,o=g&(1<<-c)-1,g>>=-c,c+=a;c>0;o=o*256+n[e+d],d+=h,c-=8);for(s=o&(1<<-c)-1,o>>=-c,c+=i;c>0;s=s*256+n[e+d],d+=h,c-=8);if(o===0)o=1-u;else{if(o===l)return s?NaN:(g?-1:1)*(1/0);s=s+Math.pow(2,i),o=o-u}return(g?-1:1)*s*Math.pow(2,o-i)};DD.write=function(n,e,t,i,r,o){var s,a,l,u=o*8-r-1,c=(1<>1,h=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=i?0:o-1,f=i?1:-1,m=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=c):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+d>=1?e+=h/l:e+=h*Math.pow(2,1-d),e*l>=2&&(s++,l/=2),s+d>=c?(a=0,s=c):s+d>=1?(a=(e*l-1)*Math.pow(2,r),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,r),s=0));r>=8;n[t+g]=a&255,g+=f,a/=256,r-=8);for(s=s<0;n[t+g]=s&255,g+=f,s/=256,u-=8);n[t+g-f]|=m*128}});var kD=w(gq=>{var Bee=gq.uint8=new Array(256);for(ih=0;ih<=255;ih++)Bee[ih]=qee(ih);var ih;function qee(n){return function(e){var t=e.reserve(1);e.buffer[t]=n}}});var Dq=w(Sq=>{var fq=TD(),mq=Gb(),Wee=mq.Uint64BE,Yee=mq.Int64BE,bq=kD().uint8,zb=Jn(),Jt=zb.global,Zee=zb.hasBuffer&&"TYPED_ARRAY_SUPPORT"in Jt,Jee=Zee&&!Jt.TYPED_ARRAY_SUPPORT,pq=zb.hasBuffer&&Jt.prototype||{};Sq.getWriteToken=$ee;function $ee(n){return n&&n.uint8array?Uee():Jee||zb.hasBuffer&&n&&n.safe?Xee():yq()}function Uee(){var n=yq();return n[202]=wt(202,4,xq),n[203]=wt(203,8,Cq),n}function yq(){var n=bq.slice();return n[196]=nh(196),n[197]=Qa(197),n[198]=Va(198),n[199]=nh(199),n[200]=Qa(200),n[201]=Va(201),n[202]=wt(202,4,pq.writeFloatBE||xq,!0),n[203]=wt(203,8,pq.writeDoubleBE||Cq,!0),n[204]=nh(204),n[205]=Qa(205),n[206]=Va(206),n[207]=wt(207,8,vq),n[208]=nh(208),n[209]=Qa(209),n[210]=Va(210),n[211]=wt(211,8,wq),n[217]=nh(217),n[218]=Qa(218),n[219]=Va(219),n[220]=Qa(220),n[221]=Va(221),n[222]=Qa(222),n[223]=Va(223),n}function Xee(){var n=bq.slice();return n[196]=wt(196,1,Jt.prototype.writeUInt8),n[197]=wt(197,2,Jt.prototype.writeUInt16BE),n[198]=wt(198,4,Jt.prototype.writeUInt32BE),n[199]=wt(199,1,Jt.prototype.writeUInt8),n[200]=wt(200,2,Jt.prototype.writeUInt16BE),n[201]=wt(201,4,Jt.prototype.writeUInt32BE),n[202]=wt(202,4,Jt.prototype.writeFloatBE),n[203]=wt(203,8,Jt.prototype.writeDoubleBE),n[204]=wt(204,1,Jt.prototype.writeUInt8),n[205]=wt(205,2,Jt.prototype.writeUInt16BE),n[206]=wt(206,4,Jt.prototype.writeUInt32BE),n[207]=wt(207,8,vq),n[208]=wt(208,1,Jt.prototype.writeInt8),n[209]=wt(209,2,Jt.prototype.writeInt16BE),n[210]=wt(210,4,Jt.prototype.writeInt32BE),n[211]=wt(211,8,wq),n[217]=wt(217,1,Jt.prototype.writeUInt8),n[218]=wt(218,2,Jt.prototype.writeUInt16BE),n[219]=wt(219,4,Jt.prototype.writeUInt32BE),n[220]=wt(220,2,Jt.prototype.writeUInt16BE),n[221]=wt(221,4,Jt.prototype.writeUInt32BE),n[222]=wt(222,2,Jt.prototype.writeUInt16BE),n[223]=wt(223,4,Jt.prototype.writeUInt32BE),n}function nh(n){return function(e,t){var i=e.reserve(2),r=e.buffer;r[i++]=n,r[i]=t}}function Qa(n){return function(e,t){var i=e.reserve(3),r=e.buffer;r[i++]=n,r[i++]=t>>>8,r[i]=t}}function Va(n){return function(e,t){var i=e.reserve(5),r=e.buffer;r[i++]=n,r[i++]=t>>>24,r[i++]=t>>>16,r[i++]=t>>>8,r[i]=t}}function wt(n,e,t,i){return function(r,o){var s=r.reserve(e+1);r.buffer[s++]=n,t.call(r.buffer,o,s,i)}}function vq(n,e){new Wee(this,e,n)}function wq(n,e){new Yee(this,e,n)}function xq(n,e){fq.write(this,n,e,!1,23,4)}function Cq(n,e){fq.write(this,n,e,!1,52,8)}});var _q=w(Rq=>{var Pq=Gb(),Gee=Pq.Uint64BE,zee=Pq.Int64BE,Tq=Jn(),kq=$b(),Kee=Dq(),Qee=kD().uint8,Vee=Ub().ExtBuffer,ete=typeof Uint8Array<"u",tte=typeof Map<"u",Mu=[];Mu[1]=212;Mu[2]=213;Mu[4]=214;Mu[8]=215;Mu[16]=216;Rq.getWriteType=ite;function ite(n){var e=Kee.getWriteToken(n),t=n&&n.useraw,i=ete&&n&&n.binarraybuffer,r=i?Tq.isArrayBuffer:Tq.isBuffer,o=i?T:k,s=tte&&n&&n.usemap,a=s?X:N,l={boolean:u,function:x,number:c,object:t?v:b,string:m(t?f:g),symbol:x,undefined:x};return l;function u(Y,K){var B=K?195:194;e[B](Y,K)}function c(Y,K){var B=K|0,ge;if(K!==B){ge=203,e[ge](Y,K);return}else-32<=B&&B<=127?ge=B&255:0<=B?ge=B<=255?204:B<=65535?205:206:ge=-128<=B?208:-32768<=B?209:210;e[ge](Y,B)}function d(Y,K){var B=207;e[B](Y,K.toArray())}function h(Y,K){var B=211;e[B](Y,K.toArray())}function g(Y){return Y<32?1:Y<=255?2:Y<=65535?3:5}function f(Y){return Y<32?1:Y<=65535?3:5}function m(Y){return K;function K(B,ge){var ye=ge.length,Fe=5+ye*3;B.offset=B.reserve(Fe);var $=B.buffer,H=Y(ye),z=B.offset+H;ye=kq.write.call($,ge,z);var ee=Y(ye);if(H!==ee){var Te=z+ee-H,Ze=z+ye;kq.copy.call($,$,Te,z,Ze)}var Ee=ee===1?160+ye:ee<=3?215+ee:219;e[Ee](B,ye),B.offset+=ye}}function b(Y,K){if(K===null)return x(Y,K);if(r(K))return o(Y,K);if(Array.isArray(K))return C(Y,K);if(Gee.isUint64BE(K))return d(Y,K);if(zee.isInt64BE(K))return h(Y,K);var B=Y.codec.getExtPacker(K);if(B&&(K=B(K)),K instanceof Vee)return j(Y,K);a(Y,K)}function v(Y,K){if(r(K))return se(Y,K);b(Y,K)}function x(Y,K){var B=192;e[B](Y,K)}function C(Y,K){var B=K.length,ge=B<16?144+B:B<=65535?220:221;e[ge](Y,B);for(var ye=Y.codec.encode,Fe=0;Fe{rh.createCodec=Eq;rh.install=rte;rh.filter=ate;var nte=Jn();function ju(n){if(!(this instanceof ju))return new ju(n);this.options=n,this.init()}ju.prototype.init=function(){var n=this.options;return n&&n.uint8array&&(this.bufferish=nte.Uint8Array),this};function rte(n){for(var e in n)ju.prototype[e]=ote(ju.prototype[e],n[e])}function ote(n,e){return n&&e?t:n||e;function t(){return n.apply(this,arguments),e.apply(this,arguments)}}function ste(n){return n=n.slice(),function(t){return n.reduce(e,t)};function e(t,i){return i(t)}}function ate(n){return Array.isArray(n)?ste(n):n}function Eq(n){return new ju(n)}rh.preset=Eq({preset:!0})});var Kb=w(Lq=>{var lte=Ub().ExtBuffer,ute=hq(),cte=_q(),PD=oh();PD.install({addExtPacker:hte,getExtPacker:gte,init:Iq});Lq.preset=Iq.call(PD.preset);function dte(n){var e=cte.getWriteType(n);return t;function t(i,r){var o=e[typeof r];if(!o)throw new Error('Unsupported type "'+typeof r+'": '+r);o(i,r)}}function Iq(){var n=this.options;return this.encode=dte(n),n&&n.preset&&ute.setExtPackers(this),this}function hte(n,e,t){t=PD.filter(t);var i=e.name;if(i&&i!=="Object"){var r=this.extPackers||(this.extPackers={});r[i]=s}else{var o=this.extEncoderList||(this.extEncoderList=[]);o.unshift([e,s])}function s(a){return t&&(a=t(a)),new lte(a,n)}}function gte(n){var e=this.extPackers||(this.extPackers={}),t=n.constructor,i=t&&t.name&&e[t.name];if(i)return i;for(var r=this.extEncoderList||(this.extEncoderList=[]),o=r.length,s=0;s{RD.FlexDecoder=Ou;RD.FlexEncoder=Au;var sh=Jn(),pte=2048,fte=65536,Fq="BUFFER_SHORTAGE";function Ou(){if(!(this instanceof Ou))return new Ou}function Au(){if(!(this instanceof Au))return new Au}Ou.mixin=Oq(mte());Ou.mixin(Ou.prototype);Au.mixin=Oq(bte());Au.mixin(Au.prototype);function mte(){return{bufferish:sh,write:n,fetch:vte,flush:e,push:jq,pull:wte,read:Mq,reserve:t,offset:0};function n(i){var r=this.offset?sh.prototype.slice.call(this.buffer,this.offset):this.buffer;this.buffer=r?i?this.bufferish.concat([r,i]):r:i,this.offset=0}function e(){for(;this.offsetthis.buffer.length)throw new Error(Fq);return this.offset=o,r}}function bte(){return{bufferish:sh,write:yte,fetch:n,flush:e,push:jq,pull:t,read:Mq,reserve:i,send:r,maxBufferSize:fte,minBufferSize:pte,offset:0,start:0};function n(){var o=this.start;if(o1?this.bufferish.concat(o):o[0];return o.length=0,s}function i(o){var s=o|0;if(this.buffer){var a=this.buffer.length,l=this.offset|0,u=l+s;if(uthis.minBufferSize)this.flush(),this.push(o);else{var a=this.reserve(s);sh.prototype.copy.call(o,this.buffer,a)}}}function yte(){throw new Error("method not implemented: write()")}function vte(){throw new Error("method not implemented: fetch()")}function Mq(){var n=this.buffers&&this.buffers.length;return n?(this.flush(),this.pull()):this.fetch()}function jq(n){var e=this.buffers||(this.buffers=[]);e.push(n)}function wte(){var n=this.buffers||(this.buffers=[]);return n.shift()}function Oq(n){return e;function e(t){for(var i in n)t[i]=n[i];return t}}});var Qb=w(Aq=>{Aq.EncodeBuffer=Nu;var xte=Kb().preset,Cte=_D().FlexEncoder;Cte.mixin(Nu.prototype);function Nu(n){if(!(this instanceof Nu))return new Nu(n);if(n&&(this.options=n,n.codec)){var e=this.codec=n.codec;e.bufferish&&(this.bufferish=e.bufferish)}}Nu.prototype.codec=xte;Nu.prototype.write=function(n){this.codec.encode(this,n)}});var SD=w(Nq=>{Nq.encode=Dte;var Ste=Qb().EncodeBuffer;function Dte(n,e){var t=new Ste(e);return t.write(n),t.read()}});var qq=w(Bq=>{Bq.setExtUnpackers=Pte;var Hq=Jn(),Tte=Hq.global,ED,kte={name:1,message:1,stack:1,columnNumber:1,fileName:1,lineNumber:1};function Pte(n){n.addExtUnpacker(14,[ur,el(Error)]),n.addExtUnpacker(1,[ur,el(EvalError)]),n.addExtUnpacker(2,[ur,el(RangeError)]),n.addExtUnpacker(3,[ur,el(ReferenceError)]),n.addExtUnpacker(4,[ur,el(SyntaxError)]),n.addExtUnpacker(5,[ur,el(TypeError)]),n.addExtUnpacker(6,[ur,el(URIError)]),n.addExtUnpacker(10,[ur,Rte]),n.addExtUnpacker(11,[ur,mn(Boolean)]),n.addExtUnpacker(12,[ur,mn(String)]),n.addExtUnpacker(13,[ur,mn(Date)]),n.addExtUnpacker(15,[ur,mn(Number)]),typeof Uint8Array<"u"&&(n.addExtUnpacker(17,mn(Int8Array)),n.addExtUnpacker(18,mn(Uint8Array)),n.addExtUnpacker(19,[qs,mn(Int16Array)]),n.addExtUnpacker(20,[qs,mn(Uint16Array)]),n.addExtUnpacker(21,[qs,mn(Int32Array)]),n.addExtUnpacker(22,[qs,mn(Uint32Array)]),n.addExtUnpacker(23,[qs,mn(Float32Array)]),typeof Float64Array<"u"&&n.addExtUnpacker(24,[qs,mn(Float64Array)]),typeof Uint8ClampedArray<"u"&&n.addExtUnpacker(25,mn(Uint8ClampedArray)),n.addExtUnpacker(26,qs),n.addExtUnpacker(29,[qs,mn(DataView)])),Hq.hasBuffer&&n.addExtUnpacker(27,mn(Tte))}function ur(n){return ED||(ED=ID().decode),ED(n)}function Rte(n){return RegExp.apply(null,n)}function el(n){return function(e){var t=new n;for(var i in kte)t[i]=e[i];return t}}function mn(n){return function(e){return new n(e)}}function qs(n){return new Uint8Array(n).buffer}});var MD=w(FD=>{var Wq=TD(),Yq=Gb(),Zq=Yq.Uint64BE,Jq=Yq.Int64BE;FD.getReadFormat=Ite;FD.readUint8=$q;var LD=Jn(),ey=$b(),_te=typeof Map<"u",Ete=!0;function Ite(n){var e=LD.hasArrayBuffer&&n&&n.binarraybuffer,t=n&&n.int64,i=_te&&n&&n.usemap,r={map:i?Fte:Lte,array:Mte,str:jte,bin:e?Ate:Ote,ext:Nte,uint8:$q,uint16:Bte,uint32:Wte,uint64:Vb(8,t?$te:Zte),int8:Hte,int16:qte,int32:Yte,int64:Vb(8,t?Ute:Jte),float32:Vb(4,Xte),float64:Vb(8,Gte)};return r}function Lte(n,e){var t={},i,r=new Array(e),o=new Array(e),s=n.codec.decode;for(i=0;i{var zte=MD();Xq.getReadToken=Kte;function Kte(n){var e=zte.getReadFormat(n);return n&&n.useraw?Qte(e):Uq(e)}function Uq(n){var e,t=new Array(256);for(e=0;e<=127;e++)t[e]=ah(e);for(e=128;e<=143;e++)t[e]=Yo(e-128,n.map);for(e=144;e<=159;e++)t[e]=Yo(e-144,n.array);for(e=160;e<=191;e++)t[e]=Yo(e-160,n.str);for(t[192]=ah(null),t[193]=null,t[194]=ah(!1),t[195]=ah(!0),t[196]=$n(n.uint8,n.bin),t[197]=$n(n.uint16,n.bin),t[198]=$n(n.uint32,n.bin),t[199]=$n(n.uint8,n.ext),t[200]=$n(n.uint16,n.ext),t[201]=$n(n.uint32,n.ext),t[202]=n.float32,t[203]=n.float64,t[204]=n.uint8,t[205]=n.uint16,t[206]=n.uint32,t[207]=n.uint64,t[208]=n.int8,t[209]=n.int16,t[210]=n.int32,t[211]=n.int64,t[212]=Yo(1,n.ext),t[213]=Yo(2,n.ext),t[214]=Yo(4,n.ext),t[215]=Yo(8,n.ext),t[216]=Yo(16,n.ext),t[217]=$n(n.uint8,n.str),t[218]=$n(n.uint16,n.str),t[219]=$n(n.uint32,n.str),t[220]=$n(n.uint16,n.array),t[221]=$n(n.uint32,n.array),t[222]=$n(n.uint16,n.map),t[223]=$n(n.uint32,n.map),e=224;e<=255;e++)t[e]=ah(e-256);return t}function Qte(n){var e,t=Uq(n).slice();for(t[217]=t[196],t[218]=t[197],t[219]=t[198],e=160;e<=191;e++)t[e]=Yo(e-160,n.bin);return t}function ah(n){return function(){return n}}function $n(n,e){return function(t){var i=n(t);return e(t,i)}}function Yo(n,e){return function(t){return e(t,n)}}});var ty=w(Kq=>{var Vte=Ub().ExtBuffer,eie=qq(),tie=MD().readUint8,iie=Gq(),jD=oh();jD.install({addExtUnpacker:rie,getExtUnpacker:oie,init:zq});Kq.preset=zq.call(jD.preset);function nie(n){var e=iie.getReadToken(n);return t;function t(i){var r=tie(i),o=e[r];if(!o)throw new Error("Invalid type: "+(r&&"0x"+r.toString(16)));return o(i)}}function zq(){var n=this.options;return this.decode=nie(n),n&&n.preset&&eie.setExtUnpackers(this),this}function rie(n,e){var t=this.extUnpackers||(this.extUnpackers=[]);t[n]=jD.filter(e)}function oie(n){var e=this.extUnpackers||(this.extUnpackers=[]);return e[n]||t;function t(i){return new Vte(i,n)}}});var iy=w(Qq=>{Qq.DecodeBuffer=Hu;var sie=ty().preset,aie=_D().FlexDecoder;aie.mixin(Hu.prototype);function Hu(n){if(!(this instanceof Hu))return new Hu(n);if(n&&(this.options=n,n.codec)){var e=this.codec=n.codec;e.bufferish&&(this.bufferish=e.bufferish)}}Hu.prototype.codec=sie;Hu.prototype.fetch=function(){return this.codec.decode(this)}});var ID=w(Vq=>{Vq.decode=uie;var lie=iy().DecodeBuffer;function uie(n,e){var t=new lie(e);return t.write(n),t.read()}});var iW=w(tW=>{tW.Encoder=Bu;var eW=Qb().EncodeBuffer;function Bu(n){if(!(this instanceof Bu))return new Bu(n);eW.call(this,n)}Bu.prototype=new eW;Bu.prototype.encode=function(n){this.write(n)};Bu.prototype.end=function(n){arguments.length&&this.encode(n),this.flush()}});var oW=w(rW=>{rW.Decoder=qu;var nW=iy().DecodeBuffer;function qu(n){if(!(this instanceof qu))return new qu(n);nW.call(this,n)}qu.prototype=new nW;qu.prototype.decode=function(n){arguments.length&&this.write(n),this.flush()};qu.prototype.end=function(n){this.decode(n)}});var lW=w(aW=>{aW.createEncodeStream=Wu;var cie=require("util"),sW=require("stream").Transform,die=Qb().EncodeBuffer;cie.inherits(Wu,sW);var hie={objectMode:!0};function Wu(n){if(!(this instanceof Wu))return new Wu(n);n?n.objectMode=!0:n=hie,sW.call(this,n);var e=this,t=this.encoder=new die(n);t.push=function(i){e.push(i)}}Wu.prototype._transform=function(n,e,t){this.encoder.write(n),t&&t()};Wu.prototype._flush=function(n){this.encoder.flush(),n&&n()}});var dW=w(cW=>{cW.createDecodeStream=lh;var gie=require("util"),uW=require("stream").Transform,pie=iy().DecodeBuffer;gie.inherits(lh,uW);var fie={objectMode:!0};function lh(n){if(!(this instanceof lh))return new lh(n);n?n.objectMode=!0:n=fie,uW.call(this,n);var e=this,t=this.decoder=new pie(n);t.push=function(i){e.push(i)}}lh.prototype._transform=function(n,e,t){this.decoder.write(n),this.decoder.flush(),t&&t()}});var gW=w(hW=>{ty();Kb();hW.createCodec=oh().createCodec});var fW=w(pW=>{ty();Kb();pW.codec={preset:oh().preset}});var mW=w(Zo=>{Zo.encode=SD().encode;Zo.decode=ID().decode;Zo.Encoder=iW().Encoder;Zo.Decoder=oW().Decoder;Zo.createEncodeStream=lW().createEncodeStream;Zo.createDecodeStream=dW().createDecodeStream;Zo.createCodec=gW().createCodec;Zo.codec=fW().codec});var uh=w(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});ny.BaseApi=void 0;var OD=class{constructor({data:e,client:t}){this.data=e,t?this.client=t:Object.defineProperty(this,"client",{value:this})}get transport(){return this.client._transport}equals(e){try{return String(this.data)===String(e.data)}catch{return!1}}async request(e,t=[]){return Error.captureStackTrace(t),new Promise((i,r)=>{this.transport.request(e,this.getArgsByPrefix(t),(o,s)=>{if(o){let a=new Error(o[1]);if(!e.endsWith("get_var")){let l=t.stack;a.stack=`Error: request error on "${e}" - ${o[1]} +`+l.split(/\r?\n/).slice(3).join(` +`),this.client.logError(`request error on "${e}"`,t,a)}r(a)}else i(s)})})}getArgsByPrefix(e){return this.prefix!=="nvim_"&&e[0]!=this?[this.transport.isVim?this.data:this,...e]:e}getVar(e){return this.request(`${this.prefix}get_var`,[e]).then(t=>t,t=>null)}setVar(e,t,i=!1){if(i){this.notify(`${this.prefix}set_var`,[e,t]);return}return this.request(`${this.prefix}set_var`,[e,t])}deleteVar(e){this.notify(`${this.prefix}del_var`,[e])}getOption(e){return this.request(`${this.prefix}get_option`,[e])}setOption(e,t,i){if(i){this.notify(`${this.prefix}set_option`,[e,t]);return}return this.request(`${this.prefix}set_option`,[e,t])}notify(e,t=[]){this.transport.notify(e,this.getArgsByPrefix(t))}toJSON(){var e;return(e=this.data)!==null&&e!==void 0?e:0}};ny.BaseApi=OD});var oy=w(ry=>{"use strict";Object.defineProperty(ry,"__esModule",{value:!0});ry.Buffer=void 0;var mie=uh(),AD=class extends mie.BaseApi{constructor(){super(...arguments),this.prefix="nvim_buf_"}async attach(e=!1,t={}){return await this.request(`${this.prefix}attach`,[e,t])}async detach(){return await this.request(`${this.prefix}detach`,[])}get id(){return this.data}get length(){return this.request(`${this.prefix}line_count`,[])}get lines(){return this.getLines()}get changedtick(){return this.request(`${this.prefix}get_changedtick`,[])}get commands(){return this.getCommands()}getCommands(e={}){return this.request(`${this.prefix}get_commands`,[e])}getLines({start:e,end:t,strictIndexing:i}={start:0,end:-1,strictIndexing:!0}){let r=typeof i>"u"?!0:i;return this.request(`${this.prefix}get_lines`,[e,t,r])}setLines(e,t,i=!1){let{start:r,end:o,strictIndexing:s}=t??{};r=r??0,o=o??r+1;let a=s??!0;return this[i?"notify":"request"](`${this.prefix}set_lines`,[r,o,a,typeof e=="string"?[e]:e])}setVirtualText(e,t,i,r={}){return this.client.call("coc#vtext#add",[this.id,e,t,i,r],!0),Promise.resolve(e)}deleteExtMark(e,t){this.notify(`${this.prefix}del_extmark`,[e,t])}async getExtMarkById(e,t,i={}){return this.request(`${this.prefix}get_extmark_by_id`,[e,t,i])}async getExtMarks(e,t,i,r={}){return this.request(`${this.prefix}get_extmarks`,[e,t,i,r])}setExtMark(e,t,i,r={}){this.notify(`${this.prefix}set_extmark`,[e,t,i,r])}insert(e,t){return this.setLines(e,{start:t,end:t,strictIndexing:!0})}replace(e,t){let i=typeof e=="string"?[e]:e;return this.setLines(i,{start:t,end:t+i.length,strictIndexing:!1})}remove(e,t,i=!1){return this.setLines([],{start:e,end:t,strictIndexing:i})}append(e){return this.setLines(e,{start:-1,end:-1,strictIndexing:!1})}get name(){return this.request(`${this.prefix}get_name`,[])}setName(e){return this.request(`${this.prefix}set_name`,[e])}get valid(){return this.request(`${this.prefix}is_valid`,[])}mark(e){return this.request(`${this.prefix}get_mark`,[e])}getKeymap(e){return this.request(`${this.prefix}get_keymap`,[e])}setKeymap(e,t,i,r={}){let o=r.expr?Object.assign({replace_keycodes:!0},r):r;this.notify(`${this.prefix}set_keymap`,[e,t,i,o])}deleteKeymap(e,t){this.notify(`${this.prefix}del_keymap`,[e,t])}get loaded(){return this.request(`${this.prefix}is_loaded`,[])}getOffset(e){return this.request(`${this.prefix}get_offset`,[e])}addHighlight({hlGroup:e,line:t,colStart:i,colEnd:r,srcId:o}){if(!e)throw new Error("hlGroup should not empty");let s=typeof r<"u"?r:-1,a=typeof i<"u"?i:-0,l=typeof o<"u"?o:-1,u=l==0?"request":"notify",c=this[u](`${this.prefix}add_highlight`,[l,e,t,a,s]);return u==="request"?c:Promise.resolve(null)}clearHighlight(e={}){let t={srcId:-1,lineStart:0,lineEnd:-1},{srcId:i,lineStart:r,lineEnd:o}=Object.assign({},t,e);return this.notify(`${this.prefix}clear_highlight`,[i,r,o])}highlightRanges(e,t,i){this.client.call("coc#highlight#ranges",[this.id,e,t,i],!0)}clearNamespace(e,t=0,i=-1){this.client.call("coc#highlight#clear_highlight",[this.id,e,t,i],!0)}placeSign(e){let t={lnum:e.lnum};typeof e.priority=="number"&&(t.priority=e.priority),this.client.call("sign_place",[e.id||0,e.group||"",e.name,this.id,t],!0)}unplaceSign(e){let t={buffer:this.id};e.id!=null&&(t.id=e.id),this.client.call("sign_unplace",[e.group||"",t],!0)}async getSigns(e){return(await this.client.call("sign_getplaced",[this.id,e||{}]))[0].signs}async getHighlights(e,t=0,i=-1){let r=[],o=await this.client.call("coc#highlight#get_highlights",[this.id,e,t,i]);for(let s of o)r.push({hlGroup:s[0],lnum:s[1],colStart:s[2],colEnd:s[3],id:s[4]});return r}updateHighlights(e,t,i={}){if(typeof i=="number"){this.client.logError("Bad option for buffer.updateHighlights()",new Error);return}let r=typeof i.start=="number"?i.start:0,o=typeof i.end=="number"?i.end:-1,s=typeof i.changedtick=="number"?i.changedtick:null,a=typeof i.priority=="number"?i.priority:null;if(r==0&&o==-1){let l=t.map(u=>[u.hlGroup,u.lnum,u.colStart,u.colEnd,u.combine===!1?0:1,u.start_incl?1:0,u.end_incl?1:0]);this.client.call("coc#highlight#buffer_update",[this.id,e,l,a,s],!0);return}this.client.call("coc#highlight#update_highlights",[this.id,e,t,r,o,a,s],!0)}listen(e,t,i){this.client.attachBufferEvent(this.id,e,t),i&&i.push({dispose:()=>{this.client.detachBufferEvent(this.id,e,t)}})}};ry.Buffer=AD});var ay=w(sy=>{"use strict";Object.defineProperty(sy,"__esModule",{value:!0});sy.Window=void 0;var bie=uh(),ND=class extends bie.BaseApi{constructor(){super(...arguments),this.prefix="nvim_win_"}get id(){return this.data}setBuffer(e){return this.request(`${this.prefix}set_buf`,[e])}get buffer(){return this.request(`${this.prefix}get_buf`,[])}get tabpage(){return this.request(`${this.prefix}get_tabpage`,[])}get cursor(){return this.request(`${this.prefix}get_cursor`,[])}setCursor(e,t=!1){return this[t?"notify":"request"](`${this.prefix}set_cursor`,[e])}get height(){return this.request(`${this.prefix}get_height`,[])}setHeight(e,t=!1){return this[t?"notify":"request"](`${this.prefix}set_height`,[e])}get width(){return this.request(`${this.prefix}get_width`,[])}setWidth(e,t=!1){return this[t?"notify":"request"](`${this.prefix}set_width`,[e])}get position(){return this.request(`${this.prefix}get_position`,[])}get row(){return this.request(`${this.prefix}get_position`,[]).then(e=>e[0])}get col(){return this.request(`${this.prefix}get_position`,[]).then(e=>e[1])}get valid(){return this.request(`${this.prefix}is_valid`,[])}get number(){return this.request(`${this.prefix}get_number`,[])}setConfig(e,t){return this[t?"notify":"request"](`${this.prefix}set_config`,[e])}getConfig(){return this.request(`${this.prefix}get_config`,[])}close(e,t){return t?(this.notify(`${this.prefix}close`,[e]),null):this.request(`${this.prefix}close`,[e])}highlightRanges(e,t,i=10,r){if(r){this.client.call("coc#highlight#match_ranges",[this.id,0,t,e,i],!0);return}return this.client.call("coc#highlight#match_ranges",[this.id,0,t,e,i])}clearMatchGroup(e){this.client.call("coc#highlight#clear_match_group",[this.id,e],!0)}clearMatches(e){this.client.call("coc#highlight#clear_matches",[this.id,e],!0)}};sy.Window=ND});var uy=w(ly=>{"use strict";Object.defineProperty(ly,"__esModule",{value:!0});ly.Tabpage=void 0;var yie=uh(),HD=class extends yie.BaseApi{constructor(){super(...arguments),this.prefix="nvim_tabpage_"}get id(){return this.data}get windows(){return this.request(`${this.prefix}list_wins`,[])}get window(){return this.request(`${this.prefix}get_win`,[])}get valid(){return this.request(`${this.prefix}is_valid`,[])}get number(){return this.request(`${this.prefix}get_number`,[])}getOption(){throw new Error("Tabpage does not have `getOption`")}setOption(){throw new Error("Tabpage does not have `setOption`")}};ly.Tabpage=HD});var bW=w(tl=>{"use strict";Object.defineProperty(tl,"__esModule",{value:!0});tl.Metadata=tl.ExtType=void 0;var vie=oy(),wie=ay(),xie=uy(),Cie;(function(n){n[n.Buffer=0]="Buffer",n[n.Window=1]="Window",n[n.Tabpage=2]="Tabpage"})(Cie=tl.ExtType||(tl.ExtType={}));tl.Metadata=[{constructor:vie.Buffer,name:"Buffer",prefix:"nvim_buf_"},{constructor:wie.Window,name:"Window",prefix:"nvim_win_"},{constructor:xie.Tabpage,name:"Tabpage",prefix:"nvim_tabpage_"}]});var vW=w(qD=>{"use strict";Object.defineProperty(qD,"__esModule",{value:!0});var Sie=require("stream"),Die=Buffer.poolSize,yW=10*1024*1024,BD=class extends Sie.Transform{constructor(){super({readableHighWaterMark:yW,writableHighWaterMark:yW}),this.chunks=null,this.timer=null}sendData(){let{chunks:e}=this;e&&(this.chunks=null,this.push(Buffer.concat(e)))}_transform(e,t,i){let{chunks:r,timer:o}=this;if(o&&clearTimeout(o),e.length{"use strict";var UD=cr&&cr.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(cr,"__esModule",{value:!0});cr.createLogger=cr.level=cr.nullLogger=void 0;var YD=UD(require("fs")),Tie=UD(require("os")),ZD=UD(require("path")),kie=require("util"),Yu=process.env.COC_NODE_CLIENT_DEBUG=="1"&&process.env.COC_TESTER=="1";cr.nullLogger={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},trace:()=>{}};function Pie(){let n=process.env.NODE_CLIENT_LOG_FILE;if(n)return n;let e=process.env.XDG_RUNTIME_DIR;return e?ZD.default.join(e,"node-client.log"):ZD.default.join(Tie.default.tmpdir(),`node-client-${process.pid}.log`)}var JD=Pie();cr.level=Yu?"debug":process.env.NODE_CLIENT_LOG_LEVEL||"info";var il=!Yu&&process.getuid&&process.getuid()==0;if(!il&&!Yu)try{YD.default.mkdirSync(ZD.default.dirname(JD),{recursive:!0}),YD.default.writeFileSync(JD,"",{encoding:"utf8",mode:438})}catch{il=!0}function wW(n){return n==null?n:Array.isArray(n)?n.map(e=>wW(e)):typeof n=="object"&&typeof n.prefix=="string"&&typeof n.data=="number"?"["+n.prefix+n.data+"]":n}function Rie(n){return Yu?(0,kie.inspect)(n,{depth:null,colors:!0,compact:!1}):n==null?String(n):typeof n=="object"?JSON.stringify(n,null,2):String(n)}var WD=n=>n<10?`0${n}`:n.toString(),_ie=n=>n<10?`00${n}`:n<100?`0${n}`:n.toString();function Eie(n){return`${WD(n.getHours())}:${WD(n.getMinutes())}:${WD(n.getSeconds())}.${_ie(n.getMilliseconds())}`}var $D=class{constructor(e){this.name=e}get stream(){return this._stream?this._stream:(Yu?this._stream=process.stdout:this._stream=YD.default.createWriteStream(JD,{encoding:"utf8"}),this._stream)}getText(e,t,i){let r="";return i.length&&(r=" "+wW(i).map(s=>Rie(s)).join(", ")),`${Eie(new Date)} ${e.toUpperCase()} [${this.name}] - ${t}${r} +`}debug(e,...t){cr.level!="debug"||il||this.stream.write(this.getText("debug",e,t))}info(e,...t){il||this.stream.write(this.getText("info",e,t))}warn(e,...t){il||this.stream.write(this.getText("warn",e,t))}error(e,...t){if(il)return;(Yu?process.stderr:this.stream).write(this.getText("error",e,t))}trace(e,...t){cr.level!="trace"||il||this.stream.write(this.getText("trace",e,t))}};function Iie(n){return new $D(n)}cr.createLogger=Iie});var zD=w(GD=>{"use strict";Object.defineProperty(GD,"__esModule",{value:!0});var Lie=require("events"),CW=cy(),xW=CW.level==="debug",ch=(0,CW.createLogger)("transport"),XD=class extends Lie.EventEmitter{constructor(e,t){super(),this.logger=e,this.isVim=t,this.pauseLevel=0,this.paused=new Map}debug(e,...t){!xW||ch.debug(e,...t)}info(e,...t){ch.info(e,...t)}debugMessage(e){if(!xW)return;let t=e[0];t==0?ch.debug("receive request:",e.slice(1)):t==1||(t==2?ch.debug("receive notification:",e.slice(1)):ch.debug("unknown message:",e))}pauseNotification(){this.pauseLevel=this.pauseLevel+1,this.paused.set(this.pauseLevel,[])}cancelNotification(){let{pauseLevel:e}=this;e>0&&(this.paused.delete(e),this.pauseLevel=e-1)}resumeNotification(e=!1){let{pauseLevel:t}=this;if(t==0)return e?null:Promise.resolve([[],null]);let i={};Error.captureStackTrace(i),this.pauseLevel=t-1;let r=this.paused.get(t);return this.paused.delete(t),r&&r.length?new Promise((o,s)=>{if(!e)return this.request("nvim_call_atomic",[r],(a,l)=>{if(a){let u=new Error(`call_atomic error: ${a[1]}`);return u.stack=i.stack.replace(/^Error/,`Error: ${u.message}`),s(u)}if(Array.isArray(l)&&l[1]!=null){let[u,c,d]=l[1],[h,g]=r[u],f=new Error(`call_atomic request error on "${h}": ${d}`);return f.stack=i.stack.replace(/^Error/,`Error: ${f.message}`),this.logger.error(`call_atomic request error ${c} on "${h}"`,g,d,f),s(f)}o(l)});this.notify("nvim_call_atomic",[r]),o(void 0)}):e?null:Promise.resolve([[],void 0])}};GD.default=XD});var DW=w(dr=>{"use strict";var Fie=dr&&dr.__createBinding||(Object.create?function(n,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,i,r)}:function(n,e,t,i){i===void 0&&(i=t),n[i]=e[t]}),Mie=dr&&dr.__setModuleDefault||(Object.create?function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}:function(n,e){n.default=e}),jie=dr&&dr.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&Fie(e,n,t);return Mie(e,n),e},SW=dr&&dr.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(dr,"__esModule",{value:!0});dr.NvimTransport=void 0;var Jo=jie(mW()),Oie=bW(),Aie=SW(vW()),Nie=SW(zD()),KD=class extends Nie.default{constructor(e){super(e,!1),this.pending=new Map,this.nextRequestId=1,this.attached=!1;let t=this.setupCodec();this.encodeStream=Jo.createEncodeStream({codec:t}),this.decodeStream=Jo.createDecodeStream({codec:t}),this.decodeStream.on("data",i=>{this.parseMessage(i)}),this.decodeStream.on("end",()=>{this.detach(),this.emit("detach")})}parseMessage(e){let t=e[0];if(this.debugMessage(e),t===0){let i=e[2].toString();this.emit("request",i,e[3],this.createResponse(i,e[1]))}else if(t===1){let i=e[1],r=this.pending.get(i);if(r){this.pending.delete(i);let o=e[2];o&&o.length!=2&&(o=[0,o.toString()]),r(o,e[3])}}else t===2?this.emit("notification",e[1].toString(),e[2]):console.error(`Invalid message type ${t}`)}setupCodec(){let e=Jo.createCodec();return Oie.Metadata.forEach(({constructor:t},i)=>{e.addExtPacker(i,t,r=>Jo.encode(r.data)),e.addExtUnpacker(i,r=>new t({client:this.client,data:Jo.decode(r)}))}),this.codec=e,this.codec}attach(e,t,i){this.encodeStream=this.encodeStream.pipe(e);let r=new Aie.default;t.pipe(r).pipe(this.decodeStream),this.writer=e,this.reader=t,this.client=i,this.attached=!0}detach(){if(!!this.attached){this.attached=!1,this.encodeStream.unpipe(this.writer),this.reader.unpipe(this.decodeStream);for(let e of this.pending.values())e([0,"transport disconnected"]);this.pending.clear()}}request(e,t,i){if(!this.attached)return i([0,"transport disconnected"]);let r=this.nextRequestId;this.nextRequestId=this.nextRequestId+1;let o=Date.now();this.debug("request to nvim:",r,e,t),this.encodeStream.write(Jo.encode([0,r,e,t],{codec:this.codec})),this.pending.set(r,(s,a)=>{this.debug("response of nvim:",r,Date.now()-o,a,s),i(s,a)})}notify(e,t){if(!!this.attached){if(this.pauseLevel!=0){let i=this.paused.get(this.pauseLevel);if(i){i.push([e,t]);return}}this.debug("nvim notification:",e,t),this.encodeStream.write(Jo.encode([2,e,t],{codec:this.codec}))}}send(e){this.encodeStream.write(Jo.encode(e,{codec:this.codec}))}createResponse(e,t){let{encodeStream:i}=this,r=Date.now(),o=!1,s=setTimeout(()=>{this.debug("request to client cost more than 1s",t)},1e3);return{send:(a,l)=>{clearTimeout(s),!(o||!this.attached)&&(this.debug("response of client:",t,`${Date.now()-r}ms`,a,l==!0),o=!0,i.write(Jo.encode([1,t,l?a:null,l?null:a])))}}}};dr.NvimTransport=KD});var dh=w(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});Zu.isTester=Zu.isCocNvim=void 0;Zu.isCocNvim=!0;Zu.isTester=process.env.COC_TESTER=="1"});var TW=w(gh=>{"use strict";var Hie=gh&&gh.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(gh,"__esModule",{value:!0});var Bie=Hie(require("events")),qie=cy(),hh=(0,qie.createLogger)("connection"),Wie=10,QD=class extends Bie.default{constructor(e,t){super(),this.writeable=t;let i=[],r=!1;e.once("data",a=>{if(!Buffer.isBuffer(a))throw new Error("Vim connection expect buffer from readable stream.")});let o=a=>{let l=0,u=a.byteLength;for(let c=0;c{hh.warn("readable stream closed.")};e.on("close",s),this.clean=()=>{e.off("data",o),e.off("close",s)}}parseData(e){if(e.length==0)return;let t;try{t=JSON.parse(e)}catch{console.error(`Invalid data from vim: ${e}`);return}let[i,r]=t;i>0?(hh.debug("received request:",i,r),this.emit("request",i,r)):i==0?(hh.debug("received notification:",r),this.emit("notification",r)):(hh.debug("received response:",i,r),this.emit("response",i,r))}response(e,t){this.send([e,t||null])}notify(e,t){this.send([0,[e,t||null]])}send(e){hh.debug("send to vim:",e),this.writeable.write(JSON.stringify(e)+` +`)}redraw(e){this.send(["redraw",e?"force":""])}command(e){this.send(["ex",e])}expr(e){this.send(["expr",e])}call(e,t,i){if(typeof i=="number"){this.send(["call",e,t,i]);return}this.send(["call",e,t])}dispose(){typeof this.clean=="function"&&(this.clean(),this.clean=void 0),this.removeAllListeners()}};gh.default=QD});var kW=w(eT=>{"use strict";Object.defineProperty(eT,"__esModule",{value:!0});var Yie=dh(),Zie=Yie.isCocNvim?"coc#api#call":"nvim#api#call",VD=class{constructor(e,t,i){this.connection=e,this.cb=t,this.id=i}request(e,t=[]){this.method=e,this.connection.call(Zie,[e.slice(5),t],this.id)}callback(e,t,i){let{method:r,cb:o}=this;if(t)return o([0,t.toString()]);switch(r){case"nvim_list_wins":case"nvim_tabpage_list_wins":return o(null,i.map(s=>e.createWindow(s)));case"nvim_tabpage_get_win":case"nvim_get_current_win":case"nvim_open_win":return o(null,e.createWindow(i));case"nvim_list_bufs":return o(null,i.map(s=>e.createBuffer(s)));case"nvim_win_get_buf":case"nvim_create_buf":case"nvim_get_current_buf":return o(null,e.createBuffer(i));case"nvim_list_tabpages":return o(null,i.map(s=>e.createTabpage(s)));case"nvim_win_get_tabpage":case"nvim_get_current_tabpage":return o(null,e.createTabpage(i));default:return o(null,i)}}};eT.default=VD});var PW=w(Ju=>{"use strict";var iT=Ju&&Ju.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Ju,"__esModule",{value:!0});Ju.VimTransport=void 0;var Jie=dh(),$ie=iT(zD()),Uie=iT(TW()),Xie=iT(kW()),tT=class extends $ie.default{constructor(e){super(e,!0),this.pending=new Map,this.nextRequestId=-1,this.attached=!1,this.errText="",this.outText="",this.notifyMethod=Jie.isCocNvim?"coc#api#notify":"nvim#api#notify"}attach(e,t,i){let r=this.connection=new Uie.default(t,e);this.attached=!0,this.client=i,r.on("request",(o,s)=>{let[a,l]=s;this.emit("request",a,l,this.createResponse(a,o))}),r.on("notification",o=>{let[s,a]=o;this.emit("notification",s.toString(),a)}),r.on("response",(o,s)=>{let a=this.pending.get(o);if(a){this.pending.delete(o);let l=null,u=null;Array.isArray(s)?(l=s[0],u=s[1]):l=s,a.callback(this.client,l,u)}})}send(e){this.connection.send(e)}detach(){if(!!this.attached){this.attached=!1,this.connection.dispose();for(let e of this.pending.values())e.callback(this.client,"connection disconnected",null);this.pending.clear()}}request(e,t,i){if(!this.attached)return i([0,"transport disconnected"]);let r=this.nextRequestId;this.nextRequestId=this.nextRequestId-1;let o=new Xie.default(this.connection,(s,a)=>{i(s,a)},r);this.pending.set(r,o),o.request(e,t)}notify(e,t){if(!this.attached)return;if(this.pauseLevel!=0){let r=this.paused.get(this.pauseLevel);if(r){r.push([e,t]);return}}let i=e.slice(5);if(i=="err_write"){this.errText=this.errText+t[0].toString();return}if(i=="out_write"){let r=t[0].toString()||"";if(!r.includes(` +`))this.outText=this.outText+r;else{let o=this.outText+t[0].toString();this.outText="",this.connection.call(this.notifyMethod,[i,[o]])}return}if(i=="err_writeln"){let r=this.errText+t[0].toString();this.errText="",this.connection.call(this.notifyMethod,[i,[r]]);return}this.connection.call(this.notifyMethod,[i,t])}createResponse(e,t){let i=!1,{connection:r}=this;return{send:(o,s)=>{if(i||!this.attached)return;i=!0;let a=null;s&&(a=typeof o=="string"?o:o.toString()),r.response(t,[a,s?null:o])}}}};Ju.VimTransport=tT});var RW=w(dy=>{"use strict";Object.defineProperty(dy,"__esModule",{value:!0});dy.Neovim=void 0;var Gie=uh(),zie=dh();function ph(n){return n?Array.isArray(n)?n:[n]:[]}var nT=class extends Gie.BaseApi{constructor(){super(...arguments),this.prefix="nvim_"}get apiInfo(){return this.request(`${this.prefix}get_api_info`)}get buffers(){return this.request(`${this.prefix}list_bufs`)}get buffer(){return this.request(`${this.prefix}get_current_buf`)}async setBuffer(e){await this.request(`${this.prefix}set_current_buf`,[e])}get chans(){return this.request(`${this.prefix}list_chans`)}getChanInfo(e){return this.request(`${this.prefix}get_chan_info`,[e])}createNamespace(e=""){return zie.isCocNvim?(e=e.startsWith("coc-")?e.slice(4):e,this.request(`${this.prefix}call_function`,["coc#highlight#create_namespace",[e]])):this.request(`${this.prefix}create_namespace`,[e])}get namespaces(){return this.request(`${this.prefix}get_namespaces`,[])}get commands(){return this.getCommands()}getCommands(e={}){return this.request(`${this.prefix}get_commands`,[e])}get tabpages(){return this.request(`${this.prefix}list_tabpages`)}get tabpage(){return this.request(`${this.prefix}get_current_tabpage`)}async setTabpage(e){await this.request(`${this.prefix}set_current_tabpage`,[e])}get windows(){return this.getWindows()}get window(){return this.request(`${this.prefix}get_current_win`)}getWindows(){return this.request(`${this.prefix}list_wins`)}async setWindow(e){await this.request(`${this.prefix}set_current_win`,[e])}get runtimePaths(){return this.request(`${this.prefix}list_runtime_paths`)}setDirectory(e){return this.request(`${this.prefix}set_current_dir`,[e])}get line(){return this.getLine()}createNewBuffer(e=!1,t=!1){return this.request(`${this.prefix}create_buf`,[e,t])}openFloatWindow(e,t,i){return this.request(`${this.prefix}open_win`,[e,t,i])}getLine(){return this.request(`${this.prefix}get_current_line`)}setLine(e){return this.request(`${this.prefix}set_current_line`,[e])}getKeymap(e){return this.request(`${this.prefix}get_keymap`,[e])}setKeymap(e,t,i,r={}){let o=r.expr?Object.assign({replace_keycodes:!0},r):r;this.notify(`${this.prefix}set_keymap`,[e,t,i,o])}deleteKeymap(e,t){this.notify(`${this.prefix}del_keymap`,[e,t])}get mode(){return this.request(`${this.prefix}get_mode`)}get colorMap(){return this.request(`${this.prefix}get_color_map`)}getColorByName(e){return this.request(`${this.prefix}get_color_by_name`,[e])}getHighlight(e,t=!0){let i=typeof e=="string"?"by_name":"by_id";return this.request(`${this.prefix}get_hl_${i}`,[e,t])}getHighlightByName(e,t=!0){return this.request(`${this.prefix}get_hl_by_name`,[e,t])}getHighlightById(e,t=!0){return this.request(`${this.prefix}get_hl_by_id`,[e,t])}deleteCurrentLine(){return this.request(`${this.prefix}del_current_line`)}eval(e){return this.request(`${this.prefix}eval`,[e])}lua(e,t=[]){return this.request(`${this.prefix}exec_lua`,[e,t])}executeLua(e,t=[]){let i=ph(t);return this.lua(e,i)}callDictFunction(e,t,i=[]){let r=ph(i);return this.request(`${this.prefix}call_dict_function`,[e,t,r])}call(e,t=[],i){let r=ph(t);return i?(this.notify(`${this.prefix}call_function`,[e,r]),null):this.request(`${this.prefix}call_function`,[e,r])}callTimer(e,t=[],i){let r=ph(t);return i?(this.notify(`${this.prefix}call_function`,["coc#util#timer",[e,r]]),null):this.transport.isVim?(this.notify(`${this.prefix}call_function`,["coc#util#timer",[e,r]]),new Promise(o=>{setTimeout(()=>{o(null)},20)})):this.request(`${this.prefix}call_function`,["coc#util#timer",[e,r]])}callAsync(e,t=[]){let i=ph(t);return this.client.sendAsyncRequest(e,i)}callFunction(e,t=[]){return this.call(e,t)}callAtomic(e){return this.request(`${this.prefix}call_atomic`,[e])}command(e,t){return t?(this.notify(`${this.prefix}command`,[e]),null):this.request(`${this.prefix}command`,[e])}commandOutput(e){return this.request(`${this.prefix}command_output`,[e])}exec(e,t=!1){return this.request(`${this.prefix}exec`,[e,t])}getVvar(e){return this.request(`${this.prefix}get_vvar`,[e])}feedKeys(e,t,i){return this.request(`${this.prefix}feedkeys`,[e,t,i])}input(e){return this.request(`${this.prefix}input`,[e])}inputMouse(e,t,i,r,o,s=0){return this.request(`${this.prefix}input_mouse`,[e,t,i,s,r,o])}parseExpression(e,t,i){return this.request(`${this.prefix}parse_expression`,[e,t,i])}getProc(e){return this.request(`${this.prefix}get_proc`,[e])}getProcChildren(e){return this.request(`${this.prefix}get_proc_children`,[e])}replaceTermcodes(e,t,i,r){return this.request(`${this.prefix}replace_termcodes`,[e,t,i,r])}strWidth(e){return this.request(`${this.prefix}strwidth`,[e])}outWrite(e){this.notify(`${this.prefix}out_write`,[e])}outWriteLine(e){this.outWrite(`${e} +`)}errWrite(e){this.notify(`${this.prefix}err_write`,[e])}errWriteLine(e){this.notify(`${this.prefix}err_writeln`,[e])}get uis(){return this.request(`${this.prefix}list_uis`)}uiAttach(e,t,i){return this.request(`${this.prefix}ui_attach`,[e,t,i])}uiDetach(){return this.request(`${this.prefix}ui_detach`,[])}uiTryResize(e,t){return this.request(`${this.prefix}ui_try_resize`,[e,t])}uiSetOption(e,t){return this.request(`${this.prefix}ui_set_option`,[e,t])}subscribe(e){return this.request(`${this.prefix}subscribe`,[e])}unsubscribe(e){return this.request(`${this.prefix}unsubscribe`,[e])}setClientInfo(e,t,i,r,o){this.notify(`${this.prefix}set_client_info`,[e,t,i,r,o])}async quit(){this.command("qa!",!0),this.transport&&this.transport.detach()}};dy.Neovim=nT});var fy=w($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});$u.NeovimClient=$u.AsyncResponse=void 0;var Kie=DW(),Qie=PW(),hy=dh(),Vie=oy(),ene=RW(),tne=uy(),ine=ay(),nne=require("events"),rne=["nvim_buf_attach","nvim_get_mode","nvim_list_runtime_paths","nvim_win_del_var","nvim_create_buf","nvim_exec","nvim_tabpage_list_wins","nvim_buf_del_var","nvim_buf_get_mark","nvim_tabpage_set_var","nvim_create_namespace","nvim_win_get_position","nvim_win_set_height","nvim_call_atomic","nvim_buf_detach","nvim_buf_line_count","nvim_set_current_buf","nvim_set_current_dir","nvim_get_var","nvim_del_current_line","nvim_win_set_width","nvim_out_write","nvim_win_is_valid","nvim_set_current_win","nvim_get_current_tabpage","nvim_tabpage_is_valid","nvim_set_var","nvim_win_get_height","nvim_win_get_buf","nvim_win_get_width","nvim_buf_set_name","nvim_subscribe","nvim_get_current_win","nvim_feedkeys","nvim_get_vvar","nvim_tabpage_get_number","nvim_get_current_buf","nvim_win_get_option","nvim_win_get_cursor","nvim_get_current_line","nvim_win_get_var","nvim_buf_get_var","nvim_set_current_tabpage","nvim_buf_clear_namespace","nvim_err_write","nvim_del_var","nvim_call_dict_function","nvim_set_current_line","nvim_get_api_info","nvim_unsubscribe","nvim_get_option","nvim_list_wins","nvim_set_client_info","nvim_win_set_cursor","nvim_win_set_option","nvim_eval","nvim_tabpage_get_var","nvim_buf_get_option","nvim_tabpage_del_var","nvim_buf_get_name","nvim_list_bufs","nvim_win_set_buf","nvim_win_close","nvim_command_output","nvim_command","nvim_tabpage_get_win","nvim_win_set_var","nvim_buf_add_highlight","nvim_buf_set_var","nvim_win_get_number","nvim_strwidth","nvim_buf_set_lines","nvim_err_writeln","nvim_buf_set_option","nvim_list_tabpages","nvim_set_option","nvim_buf_get_lines","nvim_buf_get_changedtick","nvim_win_get_tabpage","nvim_call_function","nvim_buf_is_valid"],gy=class{constructor(e,t){this.requestId=e,this.cb=t,this.finished=!1}finish(e,t){if(!this.finished){if(this.finished=!0,e){this.cb(new Error(e));return}this.cb(null,t)}}};$u.AsyncResponse=gy;function one(n,e){e.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(i=>{Object.defineProperty(n.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i)||Object.create(null))})})}var py=class extends ene.Neovim{constructor(e,t){super({}),this.logger=e,this.isVim=t,this.requestId=1,this.responses=new Map,this.attachedBuffers=new Map,this._transport=t?new Qie.VimTransport(e):new Kie.NvimTransport(e),this.handleRequest=this.handleRequest.bind(this),this.handleNotification=this.handleNotification.bind(this)}get transport(){return this._transport}echoError(e){let t=hy.isCocNvim?"[coc.nvim] ":"";e instanceof Error?(hy.isTester||this.errWriteLine(t+e.message+" use :CocOpenLog for details"),this.logError(e.message||"Unknown error",e)):(hy.isTester||this.errWriteLine(t+e),this.logError(e.toString(),new Error))}logError(e,...t){hy.isTester&&console.error(e,...t),this.logger&&this.logger.error(e,...t)}createBuffer(e){return new Vie.Buffer({data:e,client:this})}createWindow(e){return new ine.Window({data:e,client:this})}createTabpage(e){return new tne.Tabpage({data:e,client:this})}redrawVim(e){!this.isVim||this.transport.notify("nvim_command",["redraw"+(e?"!":"")])}attach({reader:e,writer:t},i=!0){this.transport.attach(t,e,this),this.transport.on("request",this.handleRequest),this.transport.on("notification",this.handleNotification),this.transport.on("detach",()=>{this.emit("disconnect"),this.transport.removeAllListeners("request"),this.transport.removeAllListeners("notification"),this.transport.removeAllListeners("detach")}),i?this._isReady=this.generateApi().catch(r=>(this.logger.error(r),!1)):(this._channelId=-1,this._isReady=Promise.resolve(!0))}detach(){this.attachedBuffers.clear(),this.transport.detach(),this.removeAllListeners()}get channelId(){return this._isReady.then(()=>this._channelId)}handleRequest(e,t,i){this.emit("request",e,t,i)}sendAsyncRequest(e,t){let i=this.requestId;return this.requestId=i+1,this.notify("nvim_call_function",["coc#rpc#async_request",[i,e,t||[]]]),new Promise((r,o)=>{let s=new gy(i,(a,l)=>{if(a)return o(a);r(l)});this.responses.set(i,s)})}handleNotification(e,t){if(e.endsWith("_event")){if(e.startsWith("nvim_buf_")){let i=e.replace(/nvim_buf_(.*)_event/,"$1"),{id:r}=t[0];if(!this.attachedBuffers.has(r))return;(this.attachedBuffers.get(r).get(i)||[]).forEach(a=>a(...t)),i==="detach"&&this.attachedBuffers.delete(r);return}if(e=="nvim_async_request_event"){let[i,r,o]=t;this.handleRequest(r,o,{send:(s,a)=>{this.notify("nvim_call_function",["coc#rpc#async_response",[i,s,a]])}});return}if(e=="nvim_async_response_event"){let[i,r,o]=t,s=this.responses.get(i);if(!s){this.logError(`Response not found for request ${i}`);return}this.responses.delete(i),s.finish(r,o);return}if(e==="nvim_error_event"){this.logger.error("Error event from nvim:",t[0],t[1]),this.emit("vim_error",t[1]);return}this.logger.warn(`Unhandled event: ${e}`,t)}else this.emit("notification",e,t)}requestApi(){return new Promise((e,t)=>{this.transport.request("nvim_get_api_info",[],(i,r)=>{i?t(new Error(Array.isArray(i)?i[1]:i.message||i.toString())):e(r)})})}async generateApi(){let e=await this.requestApi(),[t,i]=e;return this._channelId=t,!0}attachBufferEvent(e,t,i){let r=this.attachedBuffers.get(e)||new Map,o=r.get(t)||[];o.includes(i)||(o.push(i),r.set(t,o),this.attachedBuffers.set(e,r))}detachBufferEvent(e,t,i){let r=this.attachedBuffers.get(e);if(!r||!r.has(t))return;let o=r.get(t).filter(s=>s!==i);r.set(t,o)}pauseNotification(){let e={};Error.captureStackTrace(e),this.transport.pauseLevel!=0&&this.logError("Nested nvim.pauseNotification() detected, please avoid it:",e.stack),this.transport.pauseNotification(),process.nextTick(()=>{this.transport.pauseLevel>0&&this.logError("resumeNotification not called within same tick:",e.stack)})}resumeNotification(e,t){return this.isVim&&e&&this.transport.notify("nvim_command",["redraw"]),t?(this.transport.resumeNotification(!0),Promise.resolve(null)):this.transport.resumeNotification()}hasFunction(e){return this.isVim?rne.includes(e):!0}};$u.NeovimClient=py;one(py,[nne.EventEmitter])});var _W=w(my=>{"use strict";Object.defineProperty(my,"__esModule",{value:!0});my.attach=void 0;var sne=require("net"),ane=fy(),lne=cy();function une({reader:n,writer:e,proc:t,socket:i},r=null,o=!0){let s,a,l;if(r||(r=lne.nullLogger),i){let u=(0,sne.createConnection)(i);s=u,a=u,u.once("close",()=>{l.detach()})}else n&&e?(s=e,a=n):t&&(s=t.stdin,a=t.stdout,t.once("disconnect",()=>{l.detach()}));if(s.on("error",u=>{u.code=="EPIPE"&&l.detach()}),s&&a)return l=new ane.NeovimClient(r,process.env.VIM_NODE_RPC=="1"),l.attach({writer:s,reader:a},o),l;throw new Error("Invalid arguments, could not attach")}my.attach=une});var EW=w(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.Tabpage=hr.Window=hr.Buffer=hr.NeovimClient=hr.Neovim=void 0;var cne=fy();Object.defineProperty(hr,"Neovim",{enumerable:!0,get:function(){return cne.NeovimClient}});var dne=fy();Object.defineProperty(hr,"NeovimClient",{enumerable:!0,get:function(){return dne.NeovimClient}});var hne=oy();Object.defineProperty(hr,"Buffer",{enumerable:!0,get:function(){return hne.Buffer}});var gne=ay();Object.defineProperty(hr,"Window",{enumerable:!0,get:function(){return gne.Window}});var pne=uy();Object.defineProperty(hr,"Tabpage",{enumerable:!0,get:function(){return pne.Tabpage}})});var IW=w(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.Window=gr.Tabpage=gr.Buffer=gr.Neovim=gr.attach=void 0;var fne=_W();Object.defineProperty(gr,"attach",{enumerable:!0,get:function(){return fne.attach}});var by=EW();Object.defineProperty(gr,"Neovim",{enumerable:!0,get:function(){return by.Neovim}});Object.defineProperty(gr,"Buffer",{enumerable:!0,get:function(){return by.Buffer}});Object.defineProperty(gr,"Tabpage",{enumerable:!0,get:function(){return by.Tabpage}});Object.defineProperty(gr,"Window",{enumerable:!0,get:function(){return by.Window}})});var LW,O,PSe,Je=D(()=>{(()=>{"use strict";var n={470:r=>{function o(l){if(typeof l!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(l))}function s(l,u){for(var c,d="",h=0,g=-1,f=0,m=0;m<=l.length;++m){if(m2){var b=d.lastIndexOf("/");if(b!==d.length-1){b===-1?(d="",h=0):h=(d=d.slice(0,b)).length-1-d.lastIndexOf("/"),g=m,f=0;continue}}else if(d.length===2||d.length===1){d="",h=0,g=m,f=0;continue}}u&&(d.length>0?d+="/..":d="..",h=2)}else d.length>0?d+="/"+l.slice(g+1,m):d=l.slice(g+1,m),h=m-g-1;g=m,f=0}else c===46&&f!==-1?++f:f=-1}return d}var a={resolve:function(){for(var l,u="",c=!1,d=arguments.length-1;d>=-1&&!c;d--){var h;d>=0?h=arguments[d]:(l===void 0&&(l=process.cwd()),h=l),o(h),h.length!==0&&(u=h+"/"+u,c=h.charCodeAt(0)===47)}return u=s(u,!c),c?u.length>0?"/"+u:"/":u.length>0?u:"."},normalize:function(l){if(o(l),l.length===0)return".";var u=l.charCodeAt(0)===47,c=l.charCodeAt(l.length-1)===47;return(l=s(l,!u)).length!==0||u||(l="."),l.length>0&&c&&(l+="/"),u?"/"+l:l},isAbsolute:function(l){return o(l),l.length>0&&l.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var l,u=0;u0&&(l===void 0?l=c:l+="/"+c)}return l===void 0?".":a.normalize(l)},relative:function(l,u){if(o(l),o(u),l===u||(l=a.resolve(l))===(u=a.resolve(u)))return"";for(var c=1;cm){if(u.charCodeAt(g+v)===47)return u.slice(g+v+1);if(v===0)return u.slice(g+v)}else h>m&&(l.charCodeAt(c+v)===47?b=v:v===0&&(b=0));break}var x=l.charCodeAt(c+v);if(x!==u.charCodeAt(g+v))break;x===47&&(b=v)}var C="";for(v=c+b+1;v<=d;++v)v!==d&&l.charCodeAt(v)!==47||(C.length===0?C+="..":C+="/..");return C.length>0?C+u.slice(g+b):(g+=b,u.charCodeAt(g)===47&&++g,u.slice(g))},_makeLong:function(l){return l},dirname:function(l){if(o(l),l.length===0)return".";for(var u=l.charCodeAt(0),c=u===47,d=-1,h=!0,g=l.length-1;g>=1;--g)if((u=l.charCodeAt(g))===47){if(!h){d=g;break}}else h=!1;return d===-1?c?"/":".":c&&d===1?"//":l.slice(0,d)},basename:function(l,u){if(u!==void 0&&typeof u!="string")throw new TypeError('"ext" argument must be a string');o(l);var c,d=0,h=-1,g=!0;if(u!==void 0&&u.length>0&&u.length<=l.length){if(u.length===l.length&&u===l)return"";var f=u.length-1,m=-1;for(c=l.length-1;c>=0;--c){var b=l.charCodeAt(c);if(b===47){if(!g){d=c+1;break}}else m===-1&&(g=!1,m=c+1),f>=0&&(b===u.charCodeAt(f)?--f==-1&&(h=c):(f=-1,h=m))}return d===h?h=m:h===-1&&(h=l.length),l.slice(d,h)}for(c=l.length-1;c>=0;--c)if(l.charCodeAt(c)===47){if(!g){d=c+1;break}}else h===-1&&(g=!1,h=c+1);return h===-1?"":l.slice(d,h)},extname:function(l){o(l);for(var u=-1,c=0,d=-1,h=!0,g=0,f=l.length-1;f>=0;--f){var m=l.charCodeAt(f);if(m!==47)d===-1&&(h=!1,d=f+1),m===46?u===-1?u=f:g!==1&&(g=1):u!==-1&&(g=-1);else if(!h){c=f+1;break}}return u===-1||d===-1||g===0||g===1&&u===d-1&&u===c+1?"":l.slice(u,d)},format:function(l){if(l===null||typeof l!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof l);return function(u,c){var d=c.dir||c.root,h=c.base||(c.name||"")+(c.ext||"");return d?d===c.root?d+h:d+"/"+h:h}(0,l)},parse:function(l){o(l);var u={root:"",dir:"",base:"",ext:"",name:""};if(l.length===0)return u;var c,d=l.charCodeAt(0),h=d===47;h?(u.root="/",c=1):c=0;for(var g=-1,f=0,m=-1,b=!0,v=l.length-1,x=0;v>=c;--v)if((d=l.charCodeAt(v))!==47)m===-1&&(b=!1,m=v+1),d===46?g===-1?g=v:x!==1&&(x=1):g!==-1&&(x=-1);else if(!b){f=v+1;break}return g===-1||m===-1||x===0||x===1&&g===m-1&&g===f+1?m!==-1&&(u.base=u.name=f===0&&h?l.slice(1,m):l.slice(f,m)):(f===0&&h?(u.name=l.slice(1,g),u.base=l.slice(1,m)):(u.name=l.slice(f,g),u.base=l.slice(f,m)),u.ext=l.slice(g,m)),f>0?u.dir=l.slice(0,f-1):h&&(u.dir="/"),u},sep:"/",delimiter:":",win32:null,posix:null};a.posix=a,r.exports=a}},e={};function t(r){var o=e[r];if(o!==void 0)return o.exports;var s=e[r]={exports:{}};return n[r](s,s.exports,t),s.exports}t.d=(r,o)=>{for(var s in o)t.o(o,s)&&!t.o(r,s)&&Object.defineProperty(r,s,{enumerable:!0,get:o[s]})},t.o=(r,o)=>Object.prototype.hasOwnProperty.call(r,o),t.r=r=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})};var i={};(()=>{var r;if(t.r(i),t.d(i,{URI:()=>b,Utils:()=>K}),typeof process=="object")r=process.platform==="win32";else if(typeof navigator=="object"){var o=navigator.userAgent;r=o.indexOf("Windows")>=0}var s,a,l=(s=function($,H){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(z,ee){z.__proto__=ee}||function(z,ee){for(var Te in ee)Object.prototype.hasOwnProperty.call(ee,Te)&&(z[Te]=ee[Te])},s($,H)},function($,H){if(typeof H!="function"&&H!==null)throw new TypeError("Class extends value "+String(H)+" is not a constructor or null");function z(){this.constructor=$}s($,H),$.prototype=H===null?Object.create(H):(z.prototype=H.prototype,new z)}),u=/^\w[\w\d+.-]*$/,c=/^\//,d=/^\/\//;function h($,H){if(!$.scheme&&H)throw new Error('[UriError]: Scheme is missing: {scheme: "", authority: "'.concat($.authority,'", path: "').concat($.path,'", query: "').concat($.query,'", fragment: "').concat($.fragment,'"}'));if($.scheme&&!u.test($.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if($.path){if($.authority){if(!c.test($.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(d.test($.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}var g="",f="/",m=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,b=function(){function $(H,z,ee,Te,Ze,Ee){Ee===void 0&&(Ee=!1),typeof H=="object"?(this.scheme=H.scheme||g,this.authority=H.authority||g,this.path=H.path||g,this.query=H.query||g,this.fragment=H.fragment||g):(this.scheme=function(Cn,Ri){return Cn||Ri?Cn:"file"}(H,Ee),this.authority=z||g,this.path=function(Cn,Ri){switch(Cn){case"https":case"http":case"file":Ri?Ri[0]!==f&&(Ri=f+Ri):Ri=f}return Ri}(this.scheme,ee||g),this.query=Te||g,this.fragment=Ze||g,h(this,Ee))}return $.isUri=function(H){return H instanceof $||!!H&&typeof H.authority=="string"&&typeof H.fragment=="string"&&typeof H.path=="string"&&typeof H.query=="string"&&typeof H.scheme=="string"&&typeof H.fsPath=="string"&&typeof H.with=="function"&&typeof H.toString=="function"},Object.defineProperty($.prototype,"fsPath",{get:function(){return j(this,!1)},enumerable:!1,configurable:!0}),$.prototype.with=function(H){if(!H)return this;var z=H.scheme,ee=H.authority,Te=H.path,Ze=H.query,Ee=H.fragment;return z===void 0?z=this.scheme:z===null&&(z=g),ee===void 0?ee=this.authority:ee===null&&(ee=g),Te===void 0?Te=this.path:Te===null&&(Te=g),Ze===void 0?Ze=this.query:Ze===null&&(Ze=g),Ee===void 0?Ee=this.fragment:Ee===null&&(Ee=g),z===this.scheme&&ee===this.authority&&Te===this.path&&Ze===this.query&&Ee===this.fragment?this:new x(z,ee,Te,Ze,Ee)},$.parse=function(H,z){z===void 0&&(z=!1);var ee=m.exec(H);return ee?new x(ee[2]||g,Y(ee[4]||g),Y(ee[5]||g),Y(ee[7]||g),Y(ee[9]||g),z):new x(g,g,g,g,g)},$.file=function(H){var z=g;if(r&&(H=H.replace(/\\/g,f)),H[0]===f&&H[1]===f){var ee=H.indexOf(f,2);ee===-1?(z=H.substring(2),H=f):(z=H.substring(2,ee),H=H.substring(ee)||f)}return new x("file",z,H,g,g)},$.from=function(H){var z=new x(H.scheme,H.authority,H.path,H.query,H.fragment);return h(z,!0),z},$.prototype.toString=function(H){return H===void 0&&(H=!1),N(this,H)},$.prototype.toJSON=function(){return this},$.revive=function(H){if(H){if(H instanceof $)return H;var z=new x(H);return z._formatted=H.external,z._fsPath=H._sep===v?H.fsPath:null,z}return H},$}(),v=r?1:void 0,x=function($){function H(){var z=$!==null&&$.apply(this,arguments)||this;return z._formatted=null,z._fsPath=null,z}return l(H,$),Object.defineProperty(H.prototype,"fsPath",{get:function(){return this._fsPath||(this._fsPath=j(this,!1)),this._fsPath},enumerable:!1,configurable:!0}),H.prototype.toString=function(z){return z===void 0&&(z=!1),z?N(this,!0):(this._formatted||(this._formatted=N(this,!1)),this._formatted)},H.prototype.toJSON=function(){var z={$mid:1};return this._fsPath&&(z.fsPath=this._fsPath,z._sep=v),this._formatted&&(z.external=this._formatted),this.path&&(z.path=this.path),this.scheme&&(z.scheme=this.scheme),this.authority&&(z.authority=this.authority),this.query&&(z.query=this.query),this.fragment&&(z.fragment=this.fragment),z},H}(b),C=((a={})[58]="%3A",a[47]="%2F",a[63]="%3F",a[35]="%23",a[91]="%5B",a[93]="%5D",a[64]="%40",a[33]="%21",a[36]="%24",a[38]="%26",a[39]="%27",a[40]="%28",a[41]="%29",a[42]="%2A",a[43]="%2B",a[44]="%2C",a[59]="%3B",a[61]="%3D",a[32]="%20",a);function k($,H,z){for(var ee=void 0,Te=-1,Ze=0;Ze<$.length;Ze++){var Ee=$.charCodeAt(Ze);if(Ee>=97&&Ee<=122||Ee>=65&&Ee<=90||Ee>=48&&Ee<=57||Ee===45||Ee===46||Ee===95||Ee===126||H&&Ee===47||z&&Ee===91||z&&Ee===93||z&&Ee===58)Te!==-1&&(ee+=encodeURIComponent($.substring(Te,Ze)),Te=-1),ee!==void 0&&(ee+=$.charAt(Ze));else{ee===void 0&&(ee=$.substr(0,Ze));var Cn=C[Ee];Cn!==void 0?(Te!==-1&&(ee+=encodeURIComponent($.substring(Te,Ze)),Te=-1),ee+=Cn):Te===-1&&(Te=Ze)}}return Te!==-1&&(ee+=encodeURIComponent($.substring(Te))),ee!==void 0?ee:$}function T($){for(var H=void 0,z=0;z<$.length;z++){var ee=$.charCodeAt(z);ee===35||ee===63?(H===void 0&&(H=$.substr(0,z)),H+=C[ee]):H!==void 0&&(H+=$[z])}return H!==void 0?H:$}function j($,H){var z;return z=$.authority&&$.path.length>1&&$.scheme==="file"?"//".concat($.authority).concat($.path):$.path.charCodeAt(0)===47&&($.path.charCodeAt(1)>=65&&$.path.charCodeAt(1)<=90||$.path.charCodeAt(1)>=97&&$.path.charCodeAt(1)<=122)&&$.path.charCodeAt(2)===58?H?$.path.substr(1):$.path[1].toLowerCase()+$.path.substr(2):$.path,r&&(z=z.replace(/\//g,"\\")),z}function N($,H){var z=H?T:k,ee="",Te=$.scheme,Ze=$.authority,Ee=$.path,Cn=$.query,Ri=$.fragment;if(Te&&(ee+=Te,ee+=":"),(Ze||Te==="file")&&(ee+=f,ee+=f),Ze){var Hn=Ze.indexOf("@");if(Hn!==-1){var Er=Ze.substr(0,Hn);Ze=Ze.substr(Hn+1),(Hn=Er.lastIndexOf(":"))===-1?ee+=z(Er,!1,!1):(ee+=z(Er.substr(0,Hn),!1,!1),ee+=":",ee+=z(Er.substr(Hn+1),!1,!0)),ee+="@"}(Hn=(Ze=Ze.toLowerCase()).lastIndexOf(":"))===-1?ee+=z(Ze,!1,!0):(ee+=z(Ze.substr(0,Hn),!1,!0),ee+=Ze.substr(Hn))}if(Ee){if(Ee.length>=3&&Ee.charCodeAt(0)===47&&Ee.charCodeAt(2)===58)(Bn=Ee.charCodeAt(1))>=65&&Bn<=90&&(Ee="/".concat(String.fromCharCode(Bn+32),":").concat(Ee.substr(3)));else if(Ee.length>=2&&Ee.charCodeAt(1)===58){var Bn;(Bn=Ee.charCodeAt(0))>=65&&Bn<=90&&(Ee="".concat(String.fromCharCode(Bn+32),":").concat(Ee.substr(2)))}ee+=z(Ee,!0,!1)}return Cn&&(ee+="?",ee+=z(Cn,!1,!1)),Ri&&(ee+="#",ee+=H?Ri:k(Ri,!1,!1)),ee}function X($){try{return decodeURIComponent($)}catch{return $.length>3?$.substr(0,3)+X($.substr(3)):$}}var se=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function Y($){return $.match(se)?$.replace(se,function(H){return X(H)}):$}var K,B=t(470),ge=function($,H,z){if(z||arguments.length===2)for(var ee,Te=0,Ze=H.length;Te{"use strict";rT="Canceled",Rt=class extends Error{constructor(){super(rT),this.name=this.message}};fh=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,fh.prototype);debugger}}});function Cy(n){try{return new OW.URL(n),!0}catch{return!1}}function mh(n){return!(!n||!$e(n.title)||!$e(n.command)||n.command.length==0)}function bh(n){return n!=null&&n.kind=="markdown"}function aT(n){return n&&typeof n.label=="string"}function AW(n){return!Array.isArray(n)&&Array.isArray(n.items)}function Pn(n){return typeof n=="boolean"}function $e(n){return typeof n=="string"}function $t(n){return typeof n=="number"}function tt(n){return typeof n=="function"}function xt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}var OW,Xe=D(()=>{"use strict";OW=require("url")});function Sy(n){return n?Array.isArray(n)?n.length==0:Object.keys(n).length==0:!0}function Ue(n){return n??{}}function NW(n){let e={};return Object.entries(n).forEach(([t,i])=>{i!==void 0&&(e[t]=i)}),e}function yh(n,e){return Object.entries(n).forEach(([t,i])=>{e(n,t),Array.isArray(i)?i.forEach(r=>{xt(r)&&yh(r,e)}):xt(i)&&yh(i,e)}),n}function Li(n){if(!n||typeof n!="object"||n instanceof RegExp)return n;let e=Array.isArray(n)?[]:{};return Object.keys(n).forEach(t=>{n[t]&&typeof n[t]=="object"?e[t]=Li(n[t]):e[t]=n[t]}),e}function Rn(n,e){return bne.call(n,e)}function Dy(n){if(!n||typeof n!="object")return n;let e=[n];for(;e.length>0;){let t=e.shift();Object.freeze(t);for(let i of Object.keys(t)){let r=t[i];typeof r=="object"&&!Object.isFrozen(r)&&e.push(r)}}return n}function lT(n,e,t=!0){return xt(n)?(xt(e)&&Object.keys(e).forEach(i=>{i in n?t&&(xt(n[i])&&xt(e[i])?lT(n[i],e[i],t):n[i]=e[i]):n[i]=e[i]}),n):e}function Me(n,e){if(n===e)return!0;if(n==null||e===null||e===void 0||typeof n!=typeof e||typeof n!="object"||Array.isArray(n)!==Array.isArray(e))return!1;let t,i;if(Array.isArray(n)){if(n.length!==e.length)return!1;for(t=0;t{"use strict";Xe();bne=Object.prototype.hasOwnProperty});var $o=w(dT=>{"use strict";Object.defineProperty(dT,"__esModule",{value:!0});var uT;function cT(){if(uT===void 0)throw new Error("No runtime abstraction layer installed");return uT}(function(n){function e(t){if(t===void 0)throw new Error("No runtime abstraction layer provided");uT=t}n.install=e})(cT||(cT={}));dT.default=cT});var hT=w(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});vh.Disposable=void 0;var yne;(function(n){function e(t){return{dispose:t}}n.create=e})(yne=vh.Disposable||(vh.Disposable={}))});var HW=w(Ty=>{"use strict";Object.defineProperty(Ty,"__esModule",{value:!0});Ty.AbstractMessageBuffer=void 0;var vne=13,wne=10,xne=`\r +`,gT=class{constructor(e="utf-8"){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){let t=typeof e=="string"?this.fromString(e,this._encoding):e;this._chunks.push(t),this._totalLength+=t.byteLength}tryReadHeaders(){if(this._chunks.length===0)return;let e=0,t=0,i=0,r=0;e:for(;tthis._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===e){let o=this._chunks[0];return this._chunks.shift(),this._totalLength-=e,this.asNative(o)}if(this._chunks[0].byteLength>e){let o=this._chunks[0],s=this.asNative(o,e);return this._chunks[0]=o.slice(e),this._totalLength-=e,s}let t=this.allocNative(e),i=0,r=0;for(;e>0;){let o=this._chunks[r];if(o.byteLength>e){let s=o.slice(0,e);t.set(s,i),i+=e,this._chunks[r]=o.slice(e),this._totalLength-=e,e-=e}else t.set(o,i),i+=o.byteLength,this._chunks.shift(),this._totalLength-=o.byteLength,e-=o.byteLength}return t}};Ty.AbstractMessageBuffer=gT});var WW=w(bT=>{"use strict";Object.defineProperty(bT,"__esModule",{value:!0});var Cne=$o(),BW=require("util"),nl=hT(),Sne=HW(),Uu=class extends Sne.AbstractMessageBuffer{constructor(e="utf-8"){super(e)}emptyBuffer(){return Uu.emptyBuffer}fromString(e,t){return Buffer.from(e,t)}toString(e,t){return e instanceof Buffer?e.toString(t):new BW.TextDecoder(t).decode(e)}asNative(e,t){return t===void 0?e instanceof Buffer?e:Buffer.from(e):e instanceof Buffer?e.slice(0,t):Buffer.from(e,0,t)}allocNative(e){return Buffer.allocUnsafe(e)}};Uu.emptyBuffer=Buffer.allocUnsafe(0);var pT=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),nl.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),nl.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),nl.Disposable.create(()=>this.stream.off("end",e))}onData(e){return this.stream.on("data",e),nl.Disposable.create(()=>this.stream.off("data",e))}},fT=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),nl.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),nl.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),nl.Disposable.create(()=>this.stream.off("end",e))}write(e,t){return new Promise((i,r)=>{let o=s=>{s==null?i():r(s)};typeof e=="string"?this.stream.write(e,t,o):this.stream.write(e,o)})}end(){this.stream.end()}},qW=Object.freeze({messageBuffer:Object.freeze({create:n=>new Uu(n)}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:(n,e)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(n,void 0,0),e.charset))}catch(t){return Promise.reject(t)}}}),decoder:Object.freeze({name:"application/json",decode:(n,e)=>{try{return n instanceof Buffer?Promise.resolve(JSON.parse(n.toString(e.charset))):Promise.resolve(JSON.parse(new BW.TextDecoder(e.charset).decode(n)))}catch(t){return Promise.reject(t)}}})}),stream:Object.freeze({asReadableStream:n=>new pT(n),asWritableStream:n=>new fT(n)}),console,timer:Object.freeze({setTimeout(n,e,...t){let i=setTimeout(n,e,...t);return{dispose:()=>clearTimeout(i)}},setImmediate(n,...e){let t=setImmediate(n,...e);return{dispose:()=>clearImmediate(t)}},setInterval(n,e,...t){let i=setInterval(n,e,...t);return{dispose:()=>clearInterval(i)}}})});function mT(){return qW}(function(n){function e(){Cne.default.install(qW)}n.install=e})(mT||(mT={}));bT.default=mT});var Xu=w(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.stringArray=en.array=en.func=en.error=en.number=en.string=en.boolean=void 0;function Dne(n){return n===!0||n===!1}en.boolean=Dne;function YW(n){return typeof n=="string"||n instanceof String}en.string=YW;function Tne(n){return typeof n=="number"||n instanceof Number}en.number=Tne;function kne(n){return n instanceof Error}en.error=kne;function Pne(n){return typeof n=="function"}en.func=Pne;function ZW(n){return Array.isArray(n)}en.array=ZW;function Rne(n){return ZW(n)&&n.every(e=>YW(e))}en.stringArray=Rne});var BT=w(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.Message=ke.NotificationType9=ke.NotificationType8=ke.NotificationType7=ke.NotificationType6=ke.NotificationType5=ke.NotificationType4=ke.NotificationType3=ke.NotificationType2=ke.NotificationType1=ke.NotificationType0=ke.NotificationType=ke.RequestType9=ke.RequestType8=ke.RequestType7=ke.RequestType6=ke.RequestType5=ke.RequestType4=ke.RequestType3=ke.RequestType2=ke.RequestType1=ke.RequestType=ke.RequestType0=ke.AbstractMessageSignature=ke.ParameterStructures=ke.ResponseError=ke.ErrorCodes=void 0;var rl=Xu(),JW;(function(n){n.ParseError=-32700,n.InvalidRequest=-32600,n.MethodNotFound=-32601,n.InvalidParams=-32602,n.InternalError=-32603,n.jsonrpcReservedErrorRangeStart=-32099,n.serverErrorStart=-32099,n.MessageWriteError=-32099,n.MessageReadError=-32098,n.PendingResponseRejected=-32097,n.ConnectionInactive=-32096,n.ServerNotInitialized=-32002,n.UnknownErrorCode=-32001,n.jsonrpcReservedErrorRangeEnd=-32e3,n.serverErrorEnd=-32e3})(JW=ke.ErrorCodes||(ke.ErrorCodes={}));var wh=class extends Error{constructor(e,t,i){super(t),this.code=rl.number(e)?e:JW.UnknownErrorCode,this.data=i,Object.setPrototypeOf(this,wh.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};ke.ResponseError=wh;var Fi=class{constructor(e){this.kind=e}static is(e){return e===Fi.auto||e===Fi.byName||e===Fi.byPosition}toString(){return this.kind}};ke.ParameterStructures=Fi;Fi.auto=new Fi("auto");Fi.byPosition=new Fi("byPosition");Fi.byName=new Fi("byName");var Wt=class{constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return Fi.auto}};ke.AbstractMessageSignature=Wt;var yT=class extends Wt{constructor(e){super(e,0)}};ke.RequestType0=yT;var vT=class extends Wt{constructor(e,t=Fi.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};ke.RequestType=vT;var wT=class extends Wt{constructor(e,t=Fi.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};ke.RequestType1=wT;var xT=class extends Wt{constructor(e){super(e,2)}};ke.RequestType2=xT;var CT=class extends Wt{constructor(e){super(e,3)}};ke.RequestType3=CT;var ST=class extends Wt{constructor(e){super(e,4)}};ke.RequestType4=ST;var DT=class extends Wt{constructor(e){super(e,5)}};ke.RequestType5=DT;var TT=class extends Wt{constructor(e){super(e,6)}};ke.RequestType6=TT;var kT=class extends Wt{constructor(e){super(e,7)}};ke.RequestType7=kT;var PT=class extends Wt{constructor(e){super(e,8)}};ke.RequestType8=PT;var RT=class extends Wt{constructor(e){super(e,9)}};ke.RequestType9=RT;var _T=class extends Wt{constructor(e,t=Fi.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};ke.NotificationType=_T;var ET=class extends Wt{constructor(e){super(e,0)}};ke.NotificationType0=ET;var IT=class extends Wt{constructor(e,t=Fi.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};ke.NotificationType1=IT;var LT=class extends Wt{constructor(e){super(e,2)}};ke.NotificationType2=LT;var FT=class extends Wt{constructor(e){super(e,3)}};ke.NotificationType3=FT;var MT=class extends Wt{constructor(e){super(e,4)}};ke.NotificationType4=MT;var jT=class extends Wt{constructor(e){super(e,5)}};ke.NotificationType5=jT;var OT=class extends Wt{constructor(e){super(e,6)}};ke.NotificationType6=OT;var AT=class extends Wt{constructor(e){super(e,7)}};ke.NotificationType7=AT;var NT=class extends Wt{constructor(e){super(e,8)}};ke.NotificationType8=NT;var HT=class extends Wt{constructor(e){super(e,9)}};ke.NotificationType9=HT;var _ne;(function(n){function e(r){let o=r;return o&&rl.string(o.method)&&(rl.string(o.id)||rl.number(o.id))}n.isRequest=e;function t(r){let o=r;return o&&rl.string(o.method)&&r.id===void 0}n.isNotification=t;function i(r){let o=r;return o&&(o.result!==void 0||!!o.error)&&(rl.string(o.id)||rl.number(o.id)||o.id===null)}n.isResponse=i})(_ne=ke.Message||(ke.Message={}))});var WT=w(Uo=>{"use strict";var $W;Object.defineProperty(Uo,"__esModule",{value:!0});Uo.LRUCache=Uo.LinkedMap=Uo.Touch=void 0;var bn;(function(n){n.None=0,n.First=1,n.AsOld=n.First,n.Last=2,n.AsNew=n.Last})(bn=Uo.Touch||(Uo.Touch={}));var ky=class{constructor(){this[$W]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){var e;return(e=this._head)==null?void 0:e.value}get last(){var e;return(e=this._tail)==null?void 0:e.value}has(e){return this._map.has(e)}get(e,t=bn.None){let i=this._map.get(e);if(!!i)return t!==bn.None&&this.touch(i,t),i.value}set(e,t,i=bn.None){let r=this._map.get(e);if(r)r.value=t,i!==bn.None&&this.touch(r,i);else{switch(r={key:e,value:t,next:void 0,previous:void 0},i){case bn.None:this.addItemLast(r);break;case bn.First:this.addItemFirst(r);break;case bn.Last:this.addItemLast(r);break;default:this.addItemLast(r);break}this._map.set(e,r),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){let t=this._map.get(e);if(!!t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){let i=this._state,r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==i)throw new Error("LinkedMap got modified during iteration.");r=r.next}}keys(){let e=this._state,t=this._head,i={[Symbol.iterator]:()=>i,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let r={value:t.key,done:!1};return t=t.next,r}else return{value:void 0,done:!0}}};return i}values(){let e=this._state,t=this._head,i={[Symbol.iterator]:()=>i,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let r={value:t.value,done:!1};return t=t.next,r}else return{value:void 0,done:!0}}};return i}entries(){let e=this._state,t=this._head,i={[Symbol.iterator]:()=>i,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let r={value:[t.key,t.value],done:!1};return t=t.next,r}else return{value:void 0,done:!0}}};return i}[($W=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(e===0){this.clear();return}let t=this._head,i=this.size;for(;t&&i>e;)this._map.delete(t.key),t=t.next,i--;this._head=t,this._size=i,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(!this._head&&!this._tail)this._tail=e;else if(this._head)e.next=this._head,this._head.previous=e;else throw new Error("Invalid list");this._head=e,this._state++}addItemLast(e){if(!this._head&&!this._tail)this._head=e;else if(this._tail)e.previous=this._tail,this._tail.next=e;else throw new Error("Invalid list");this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw new Error("Invalid list");e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw new Error("Invalid list");e.previous.next=void 0,this._tail=e.previous}else{let t=e.next,i=e.previous;if(!t||!i)throw new Error("Invalid list");t.previous=i,i.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(t!==bn.First&&t!==bn.Last)){if(t===bn.First){if(e===this._head)return;let i=e.next,r=e.previous;e===this._tail?(r.next=void 0,this._tail=r):(i.previous=r,r.next=i),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(t===bn.Last){if(e===this._tail)return;let i=e.next,r=e.previous;e===this._head?(i.previous=void 0,this._head=i):(i.previous=r,r.next=i),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}}toJSON(){let e=[];return this.forEach((t,i)=>{e.push([i,t])}),e}fromJSON(e){this.clear();for(let[t,i]of e)this.set(t,i)}};Uo.LinkedMap=ky;var qT=class extends ky{constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,t=bn.AsNew){return super.get(e,t)}peek(e){return super.get(e,bn.None)}set(e,t){return super.set(e,t,bn.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}};Uo.LRUCache=qT});var zu=w(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});ol.Emitter=ol.Event=void 0;var Ene=$o(),Ine;(function(n){let e={dispose(){}};n.None=function(){return e}})(Ine=ol.Event||(ol.Event={}));var YT=class{add(e,t=null,i){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(i)&&i.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!this._callbacks)return;let i=!1;for(let r=0,o=this._callbacks.length;r{this._callbacks||(this._callbacks=new YT),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(e,t);let r={dispose:()=>{!this._callbacks||(this._callbacks.remove(e,t),r.dispose=Gu._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(i)&&i.push(r),r}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};ol.Emitter=Gu;Gu._noop=function(){}});var UT=w(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.CancellationTokenSource=sl.CancellationToken=void 0;var Lne=$o(),Fne=Xu(),ZT=zu(),JT;(function(n){n.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:ZT.Event.None}),n.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:ZT.Event.None});function e(t){let i=t;return i&&(i===n.None||i===n.Cancelled||Fne.boolean(i.isCancellationRequested)&&!!i.onCancellationRequested)}n.is=e})(JT=sl.CancellationToken||(sl.CancellationToken={}));var Mne=Object.freeze(function(n,e){let t=(0,Lne.default)().timer.setTimeout(n.bind(e),0);return{dispose(){t.dispose()}}}),Py=class{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Mne:(this._emitter||(this._emitter=new ZT.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},$T=class{get token(){return this._token||(this._token=new Py),this._token}cancel(){this._token?this._token.cancel():this._token=JT.Cancelled}dispose(){this._token?this._token instanceof Py&&this._token.dispose():this._token=JT.None}};sl.CancellationTokenSource=$T});var UW=w(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.ReadableStreamMessageReader=Xo.AbstractMessageReader=Xo.MessageReader=void 0;var GT=$o(),Ku=Xu(),XT=zu(),jne;(function(n){function e(t){let i=t;return i&&Ku.func(i.listen)&&Ku.func(i.dispose)&&Ku.func(i.onError)&&Ku.func(i.onClose)&&Ku.func(i.onPartialMessage)}n.is=e})(jne=Xo.MessageReader||(Xo.MessageReader={}));var Ry=class{constructor(){this.errorEmitter=new XT.Emitter,this.closeEmitter=new XT.Emitter,this.partialMessageEmitter=new XT.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:new Error(`Reader received error. Reason: ${Ku.string(e.message)?e.message:"unknown"}`)}};Xo.AbstractMessageReader=Ry;var zT;(function(n){function e(t){let i,r,o,s=new Map,a,l=new Map;if(t===void 0||typeof t=="string")i=t??"utf-8";else{if(i=t.charset??"utf-8",t.contentDecoder!==void 0&&(o=t.contentDecoder,s.set(o.name,o)),t.contentDecoders!==void 0)for(let u of t.contentDecoders)s.set(u.name,u);if(t.contentTypeDecoder!==void 0&&(a=t.contentTypeDecoder,l.set(a.name,a)),t.contentTypeDecoders!==void 0)for(let u of t.contentTypeDecoders)l.set(u.name,u)}return a===void 0&&(a=(0,GT.default)().applicationJson.decoder,l.set(a.name,a)),{charset:i,contentDecoder:o,contentDecoders:s,contentTypeDecoder:a,contentTypeDecoders:l}}n.fromOptions=e})(zT||(zT={}));var KT=class extends Ry{constructor(e,t){super(),this.readable=e,this.options=zT.fromOptions(t),this.buffer=(0,GT.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;let t=this.readable.onData(i=>{this.onData(i)});return this.readable.onError(i=>this.fireError(i)),this.readable.onClose(()=>this.fireClose()),t}onData(e){for(this.buffer.append(e);;){if(this.nextMessageLength===-1){let r=this.buffer.tryReadHeaders();if(!r)return;let o=r.get("Content-Length");if(!o)throw new Error("Header must provide a Content-Length property.");let s=parseInt(o);if(isNaN(s))throw new Error("Content-Length value must be a number.");this.nextMessageLength=s}let t=this.buffer.tryReadBody(this.nextMessageLength);if(t===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1;let i;this.options.contentDecoder!==void 0?i=this.options.contentDecoder.decode(t):i=Promise.resolve(t),i.then(r=>{this.options.contentTypeDecoder.decode(r,this.options).then(o=>{this.callback(o)},o=>{this.fireError(o)})},r=>{this.fireError(r)})}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,GT.default)().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}};Xo.ReadableStreamMessageReader=KT});var XW=w(_y=>{"use strict";Object.defineProperty(_y,"__esModule",{value:!0});_y.Semaphore=void 0;var One=$o(),QT=class{constructor(e=1){if(e<=0)throw new Error("Capacity must be greater than 0");this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((t,i)=>{this._waiting.push({thunk:e,resolve:t,reject:i}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,One.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw new Error("To many thunks active");try{let t=e.thunk();t instanceof Promise?t.then(i=>{this._active--,e.resolve(i),this.runNext()},i=>{this._active--,e.reject(i),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}};_y.Semaphore=QT});var QW=w(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.WriteableStreamMessageWriter=Go.AbstractMessageWriter=Go.MessageWriter=void 0;var GW=$o(),xh=Xu(),Ane=XW(),zW=zu(),Nne="Content-Length: ",KW=`\r +`,Hne;(function(n){function e(t){let i=t;return i&&xh.func(i.dispose)&&xh.func(i.onClose)&&xh.func(i.onError)&&xh.func(i.write)}n.is=e})(Hne=Go.MessageWriter||(Go.MessageWriter={}));var Ey=class{constructor(){this.errorEmitter=new zW.Emitter,this.closeEmitter=new zW.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,t,i){this.errorEmitter.fire([this.asError(e),t,i])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(e){return e instanceof Error?e:new Error(`Writer received error. Reason: ${xh.string(e.message)?e.message:"unknown"}`)}};Go.AbstractMessageWriter=Ey;var VT;(function(n){function e(t){return t===void 0||typeof t=="string"?{charset:t??"utf-8",contentTypeEncoder:(0,GW.default)().applicationJson.encoder}:{charset:t.charset??"utf-8",contentEncoder:t.contentEncoder,contentTypeEncoder:t.contentTypeEncoder??(0,GW.default)().applicationJson.encoder}}n.fromOptions=e})(VT||(VT={}));var ek=class extends Ey{constructor(e,t){super(),this.writable=e,this.options=VT.fromOptions(t),this.errorCount=0,this.writeSemaphore=new Ane.Semaphore(1),this.writable.onError(i=>this.fireError(i)),this.writable.onClose(()=>this.fireClose())}async write(e){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(e,this.options).then(i=>this.options.contentEncoder!==void 0?this.options.contentEncoder.encode(i):i).then(i=>{let r=[];return r.push(Nne,i.byteLength.toString(),KW),r.push(KW),this.doWrite(e,r,i)},i=>{throw this.fireError(i),i}))}async doWrite(e,t,i){try{return await this.writable.write(t.join(""),"ascii"),this.writable.write(i)}catch(r){return this.handleError(r,e),Promise.reject(r)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){this.writable.end()}};Go.WriteableStreamMessageWriter=ek});var rY=w(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.createMessageConnection=Oe.ConnectionOptions=Oe.CancellationStrategy=Oe.CancellationSenderStrategy=Oe.CancellationReceiverStrategy=Oe.ConnectionStrategy=Oe.ConnectionError=Oe.ConnectionErrors=Oe.LogTraceNotification=Oe.SetTraceNotification=Oe.TraceFormat=Oe.TraceValues=Oe.Trace=Oe.NullLogger=Oe.ProgressType=Oe.ProgressToken=void 0;var VW=$o(),Di=Xu(),qe=BT(),eY=WT(),Ch=zu(),tk=UT(),Dh;(function(n){n.type=new qe.NotificationType("$/cancelRequest")})(Dh||(Dh={}));var tY;(function(n){function e(t){return typeof t=="string"||typeof t=="number"}n.is=e})(tY=Oe.ProgressToken||(Oe.ProgressToken={}));var Sh;(function(n){n.type=new qe.NotificationType("$/progress")})(Sh||(Sh={}));var ik=class{constructor(){}};Oe.ProgressType=ik;var nk;(function(n){function e(t){return Di.func(t)}n.is=e})(nk||(nk={}));Oe.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}});var Ct;(function(n){n[n.Off=0]="Off",n[n.Messages=1]="Messages",n[n.Compact=2]="Compact",n[n.Verbose=3]="Verbose"})(Ct=Oe.Trace||(Oe.Trace={}));var Bne;(function(n){n.Off="off",n.Messages="messages",n.Compact="compact",n.Verbose="verbose"})(Bne=Oe.TraceValues||(Oe.TraceValues={}));(function(n){function e(i){if(!Di.string(i))return n.Off;switch(i=i.toLowerCase(),i){case"off":return n.Off;case"messages":return n.Messages;case"compact":return n.Compact;case"verbose":return n.Verbose;default:return n.Off}}n.fromString=e;function t(i){switch(i){case n.Off:return"off";case n.Messages:return"messages";case n.Compact:return"compact";case n.Verbose:return"verbose";default:return"off"}}n.toString=t})(Ct=Oe.Trace||(Oe.Trace={}));var Ar;(function(n){n.Text="text",n.JSON="json"})(Ar=Oe.TraceFormat||(Oe.TraceFormat={}));(function(n){function e(t){return Di.string(t)?(t=t.toLowerCase(),t==="json"?n.JSON:n.Text):n.Text}n.fromString=e})(Ar=Oe.TraceFormat||(Oe.TraceFormat={}));var iY;(function(n){n.type=new qe.NotificationType("$/setTrace")})(iY=Oe.SetTraceNotification||(Oe.SetTraceNotification={}));var rk;(function(n){n.type=new qe.NotificationType("$/logTrace")})(rk=Oe.LogTraceNotification||(Oe.LogTraceNotification={}));var Iy;(function(n){n[n.Closed=1]="Closed",n[n.Disposed=2]="Disposed",n[n.AlreadyListening=3]="AlreadyListening"})(Iy=Oe.ConnectionErrors||(Oe.ConnectionErrors={}));var Ws=class extends Error{constructor(e,t){super(t),this.code=e,Object.setPrototypeOf(this,Ws.prototype)}};Oe.ConnectionError=Ws;var nY;(function(n){function e(t){let i=t;return i&&Di.func(i.cancelUndispatched)}n.is=e})(nY=Oe.ConnectionStrategy||(Oe.ConnectionStrategy={}));var ok;(function(n){n.Message=Object.freeze({createCancellationTokenSource(t){return new tk.CancellationTokenSource}});function e(t){let i=t;return i&&Di.func(i.createCancellationTokenSource)}n.is=e})(ok=Oe.CancellationReceiverStrategy||(Oe.CancellationReceiverStrategy={}));var sk;(function(n){n.Message=Object.freeze({sendCancellation(t,i){return t.sendNotification(Dh.type,{id:i})},cleanup(t){}});function e(t){let i=t;return i&&Di.func(i.sendCancellation)&&Di.func(i.cleanup)}n.is=e})(sk=Oe.CancellationSenderStrategy||(Oe.CancellationSenderStrategy={}));var ak;(function(n){n.Message=Object.freeze({receiver:ok.Message,sender:sk.Message});function e(t){let i=t;return i&&ok.is(i.receiver)&&sk.is(i.sender)}n.is=e})(ak=Oe.CancellationStrategy||(Oe.CancellationStrategy={}));var qne;(function(n){function e(t){let i=t;return i&&(ak.is(i.cancellationStrategy)||nY.is(i.connectionStrategy))}n.is=e})(qne=Oe.ConnectionOptions||(Oe.ConnectionOptions={}));var Nr;(function(n){n[n.New=1]="New",n[n.Listening=2]="Listening",n[n.Closed=3]="Closed",n[n.Disposed=4]="Disposed"})(Nr||(Nr={}));function Wne(n,e,t,i){let r=t!==void 0?t:Oe.NullLogger,o=0,s=0,a=0,l="2.0",u,c=new Map,d,h=new Map,g=new Map,f,m=new eY.LinkedMap,b=new Map,v=new Set,x=new Map,C=Ct.Off,k=Ar.Text,T,j=Nr.New,N=new Ch.Emitter,X=new Ch.Emitter,se=new Ch.Emitter,Y=new Ch.Emitter,K=new Ch.Emitter,B=i&&i.cancellationStrategy?i.cancellationStrategy:ak.Message;function ge(E){if(E===null)throw new Error("Can't send requests with id null since the response can't be correlated.");return"req-"+E.toString()}function ye(E){return E===null?"res-unknown-"+(++a).toString():"res-"+E.toString()}function Fe(){return"not-"+(++s).toString()}function $(E,G){qe.Message.isRequest(G)?E.set(ge(G.id),G):qe.Message.isResponse(G)?E.set(ye(G.id),G):E.set(Fe(),G)}function H(E){}function z(){return j===Nr.Listening}function ee(){return j===Nr.Closed}function Te(){return j===Nr.Disposed}function Ze(){(j===Nr.New||j===Nr.Listening)&&(j=Nr.Closed,X.fire(void 0))}function Ee(E){N.fire([E,void 0,void 0])}function Cn(E){N.fire(E)}n.onClose(Ze),n.onError(Ee),e.onClose(Ze),e.onError(Cn);function Ri(){f||m.size===0||(f=(0,VW.default)().timer.setImmediate(()=>{f=void 0,Hn()}))}function Hn(){if(m.size===0)return;let E=m.shift();try{qe.Message.isRequest(E)?Bn(E):qe.Message.isNotification(E)?Ve(E):qe.Message.isResponse(E)?at(E):et(E)}finally{Ri()}}let Er=E=>{try{if(qe.Message.isNotification(E)&&E.method===Dh.type.method){let G=E.params.id,ce=ge(G),Ce=m.get(ce);if(qe.Message.isRequest(Ce)){let qt=i==null?void 0:i.connectionStrategy,Ot=qt&&qt.cancelUndispatched?qt.cancelUndispatched(Ce,H):void 0;if(Ot&&(Ot.error!==void 0||Ot.result!==void 0)){m.delete(ce),x.delete(G),Ot.id=Ce.id,Sn(Ot,E.method,Date.now()),e.write(Ot).catch(()=>r.error("Sending response for canceled message failed."));return}}let Bt=x.get(G);if(Bt!==void 0){Bt.cancel(),Ed(E);return}else v.add(G)}$(m,E)}finally{Ri()}};function Bn(E){if(Te())return;function G(ct,zt,bt){let Ci={jsonrpc:l,id:E.id};ct instanceof qe.ResponseError?Ci.error=ct.toJson():Ci.result=ct===void 0?null:ct,Sn(Ci,zt,bt),e.write(Ci).catch(()=>r.error("Sending response failed."))}function ce(ct,zt,bt){let Ci={jsonrpc:l,id:E.id,error:ct.toJson()};Sn(Ci,zt,bt),e.write(Ci).catch(()=>r.error("Sending response failed."))}function Ce(ct,zt,bt){ct===void 0&&(ct=null);let Ci={jsonrpc:l,id:E.id,result:ct};Sn(Ci,zt,bt),e.write(Ci).catch(()=>r.error("Sending response failed."))}qn(E);let Bt=c.get(E.method),qt,Ot;Bt&&(qt=Bt.type,Ot=Bt.handler);let _i=Date.now();if(Ot||u){let ct=E.id??String(Date.now()),zt=B.receiver.createCancellationTokenSource(ct);E.id!==null&&v.has(E.id)&&zt.cancel(),E.id!==null&&x.set(ct,zt);try{let bt;if(Ot)if(E.params===void 0){if(qt!==void 0&&qt.numberOfParams!==0){ce(new qe.ResponseError(qe.ErrorCodes.InvalidParams,`Request ${E.method} defines ${qt.numberOfParams} params but received none.`),E.method,_i);return}bt=Ot(zt.token)}else if(Array.isArray(E.params)){if(qt!==void 0&&qt.parameterStructures===qe.ParameterStructures.byName){ce(new qe.ResponseError(qe.ErrorCodes.InvalidParams,`Request ${E.method} defines parameters by name but received parameters by position`),E.method,_i);return}bt=Ot(...E.params,zt.token)}else{if(qt!==void 0&&qt.parameterStructures===qe.ParameterStructures.byPosition){ce(new qe.ResponseError(qe.ErrorCodes.InvalidParams,`Request ${E.method} defines parameters by position but received parameters by name`),E.method,_i);return}bt=Ot(E.params,zt.token)}else u&&(bt=u(E.method,E.params,zt.token));let Ci=bt;bt?Ci.then?Ci.then(Dn=>{x.delete(ct),G(Dn,E.method,_i)},Dn=>{x.delete(ct),Dn instanceof qe.ResponseError?ce(Dn,E.method,_i):Dn&&Di.string(Dn.message)?ce(new qe.ResponseError(qe.ErrorCodes.InternalError,`Request ${E.method} failed with message: ${Dn.message}`),E.method,_i):ce(new qe.ResponseError(qe.ErrorCodes.InternalError,`Request ${E.method} failed unexpectedly without providing any details.`),E.method,_i)}):(x.delete(ct),G(bt,E.method,_i)):(x.delete(ct),Ce(bt,E.method,_i))}catch(bt){x.delete(ct),bt instanceof qe.ResponseError?G(bt,E.method,_i):bt&&Di.string(bt.message)?ce(new qe.ResponseError(qe.ErrorCodes.InternalError,`Request ${E.method} failed with message: ${bt.message}`),E.method,_i):ce(new qe.ResponseError(qe.ErrorCodes.InternalError,`Request ${E.method} failed unexpectedly without providing any details.`),E.method,_i)}}else ce(new qe.ResponseError(qe.ErrorCodes.MethodNotFound,`Unhandled method ${E.method}`),E.method,_i)}function at(E){if(!Te())if(E.id===null)E.error?r.error(`Received response message without id: Error is: +${JSON.stringify(E.error,void 0,4)}`):r.error("Received response message without id. No further error information provided.");else{let G=E.id,ce=b.get(G);if(db(E,ce),ce!==void 0){b.delete(G);try{if(E.error){let Ce=E.error;ce.reject(new qe.ResponseError(Ce.code,Ce.message,Ce.data))}else if(E.result!==void 0)ce.resolve(E.result);else throw new Error("Should never happen.")}catch(Ce){Ce.message?r.error(`Response handler '${ce.method}' failed with message: ${Ce.message}`):r.error(`Response handler '${ce.method}' failed unexpectedly.`)}}}}function Ve(E){if(Te())return;let G,ce;if(E.method===Dh.type.method){let Ce=E.params.id;v.delete(Ce),Ed(E);return}else{let Ce=h.get(E.method);Ce&&(ce=Ce.handler,G=Ce.type)}if(ce||d)try{if(Ed(E),ce)if(E.params===void 0)G!==void 0&&G.numberOfParams!==0&&G.parameterStructures!==qe.ParameterStructures.byName&&r.error(`Notification ${E.method} defines ${G.numberOfParams} params but received none.`),ce();else if(Array.isArray(E.params)){let Ce=E.params;E.method===Sh.type.method&&Ce.length===2&&tY.is(Ce[0])?ce({token:Ce[0],value:Ce[1]}):(G!==void 0&&(G.parameterStructures===qe.ParameterStructures.byName&&r.error(`Notification ${E.method} defines parameters by name but received parameters by position`),G.numberOfParams!==E.params.length&&r.error(`Notification ${E.method} defines ${G.numberOfParams} params but received ${Ce.length} arguments`)),ce(...Ce))}else G!==void 0&&G.parameterStructures===qe.ParameterStructures.byPosition&&r.error(`Notification ${E.method} defines parameters by position but received parameters by name`),ce(E.params);else d&&d(E.method,E.params)}catch(Ce){Ce.message?r.error(`Notification handler '${E.method}' failed with message: ${Ce.message}`):r.error(`Notification handler '${E.method}' failed unexpectedly.`)}else se.fire(E)}function et(E){if(!E){r.error("Received empty message.");return}r.error(`Received message which is neither a response nor a notification message: +${JSON.stringify(E,null,4)}`);let G=E;if(Di.string(G.id)||Di.number(G.id)){let ce=G.id,Ce=b.get(ce);Ce&&Ce.reject(new Error("The received response has neither a result nor an error property."))}}function ze(E){if(E!=null)switch(C){case Ct.Verbose:return JSON.stringify(E,null,4);case Ct.Compact:return JSON.stringify(E);default:return}}function xi(E){if(!(C===Ct.Off||!T))if(k===Ar.Text){let G;(C===Ct.Verbose||C===Ct.Compact)&&E.params&&(G=`Params: ${ze(E.params)} + +`),T.log(`Sending request '${E.method} - (${E.id})'.`,G)}else yu("send-request",E)}function Ir(E){if(!(C===Ct.Off||!T))if(k===Ar.Text){let G;(C===Ct.Verbose||C===Ct.Compact)&&(E.params?G=`Params: ${ze(E.params)} + +`:G=`No parameters provided. + +`),T.log(`Sending notification '${E.method}'.`,G)}else yu("send-notification",E)}function Sn(E,G,ce){if(!(C===Ct.Off||!T))if(k===Ar.Text){let Ce;(C===Ct.Verbose||C===Ct.Compact)&&(E.error&&E.error.data?Ce=`Error data: ${ze(E.error.data)} + +`:E.result?Ce=`Result: ${ze(E.result)} + +`:E.error===void 0&&(Ce=`No result returned. + +`)),T.log(`Sending response '${G} - (${E.id})'. Processing request took ${Date.now()-ce}ms`,Ce)}else yu("send-response",E)}function qn(E){if(!(C===Ct.Off||!T))if(k===Ar.Text){let G;(C===Ct.Verbose||C===Ct.Compact)&&E.params&&(G=`Params: ${ze(E.params)} + +`),T.log(`Received request '${E.method} - (${E.id})'.`,G)}else yu("receive-request",E)}function Ed(E){if(!(C===Ct.Off||!T||E.method===rk.type.method))if(k===Ar.Text){let G;(C===Ct.Verbose||C===Ct.Compact)&&(E.params?G=`Params: ${ze(E.params)} + +`:G=`No parameters provided. + +`),T.log(`Received notification '${E.method}'.`,G)}else yu("receive-notification",E)}function db(E,G){if(!(C===Ct.Off||!T))if(k===Ar.Text){let ce;if((C===Ct.Verbose||C===Ct.Compact)&&(E.error&&E.error.data?ce=`Error data: ${ze(E.error.data)} + +`:E.result?ce=`Result: ${ze(E.result)} + +`:E.error===void 0&&(ce=`No result returned. + +`)),G){let Ce=E.error?` Request failed: ${E.error.message} (${E.error.code}).`:"";T.log(`Received response '${G.method} - (${E.id})' in ${Date.now()-G.timerStart}ms.${Ce}`,ce)}else T.log(`Received response ${E.id} without active response promise.`,ce)}else yu("receive-response",E)}function yu(E,G){if(!T||C===Ct.Off)return;let ce={isLSPMessage:!0,type:E,message:G,timestamp:Date.now()};T.log(ce)}function Id(){if(ee())throw new Ws(Iy.Closed,"Connection is closed.");if(Te())throw new Ws(Iy.Disposed,"Connection is disposed.")}function E6(){if(z())throw new Ws(Iy.AlreadyListening,"Connection is already listening")}function I6(){if(!z())throw new Error("Call listen() first.")}function Ld(E){return E===void 0?null:E}function lI(E){if(E!==null)return E}function uI(E){return E!=null&&!Array.isArray(E)&&typeof E=="object"}function oS(E,G){switch(E){case qe.ParameterStructures.auto:return uI(G)?lI(G):[Ld(G)];case qe.ParameterStructures.byName:if(!uI(G))throw new Error("Received parameters by name but param is not an object literal.");return lI(G);case qe.ParameterStructures.byPosition:return[Ld(G)];default:throw new Error(`Unknown parameter structure ${E.toString()}`)}}function cI(E,G){let ce,Ce=E.numberOfParams;switch(Ce){case 0:ce=void 0;break;case 1:ce=oS(E.parameterStructures,G[0]);break;default:ce=[];for(let Bt=0;Bt{Id();let ce,Ce;if(Di.string(E)){ce=E;let qt=G[0],Ot=0,_i=qe.ParameterStructures.auto;qe.ParameterStructures.is(qt)&&(Ot=1,_i=qt);let ct=G.length,zt=ct-Ot;switch(zt){case 0:Ce=void 0;break;case 1:Ce=oS(_i,G[Ot]);break;default:if(_i===qe.ParameterStructures.byName)throw new Error(`Received ${zt} parameters for 'by Name' notification parameter structure.`);Ce=G.slice(Ot,ct).map(bt=>Ld(bt));break}}else{let qt=G;ce=E.method,Ce=cI(E,qt)}let Bt={jsonrpc:l,method:ce,params:Ce};return Ir(Bt),e.write(Bt).catch(()=>r.error("Sending notification failed."))},onNotification:(E,G)=>{Id();let ce;return Di.func(E)?d=E:G&&(Di.string(E)?(ce=E,h.set(E,{type:void 0,handler:G})):(ce=E.method,h.set(E.method,{type:E,handler:G}))),{dispose:()=>{ce!==void 0?h.delete(ce):d=void 0}}},onProgress:(E,G,ce)=>{if(g.has(G))throw new Error(`Progress handler for token ${G} already registered`);return g.set(G,ce),{dispose:()=>{g.delete(G)}}},sendProgress:(E,G,ce)=>vu.sendNotification(Sh.type,{token:G,value:ce}),onUnhandledProgress:Y.event,sendRequest:(E,...G)=>{Id(),I6();let ce,Ce,Bt;if(Di.string(E)){ce=E;let ct=G[0],zt=G[G.length-1],bt=0,Ci=qe.ParameterStructures.auto;qe.ParameterStructures.is(ct)&&(bt=1,Ci=ct);let Dn=G.length;tk.CancellationToken.is(zt)&&(Dn=Dn-1,Bt=zt);let Ha=Dn-bt;switch(Ha){case 0:Ce=void 0;break;case 1:Ce=oS(Ci,G[bt]);break;default:if(Ci===qe.ParameterStructures.byName)throw new Error(`Received ${Ha} parameters for 'by Name' request parameter structure.`);Ce=G.slice(bt,Dn).map(Is=>Ld(Is));break}}else{let ct=G;ce=E.method,Ce=cI(E,ct);let zt=E.numberOfParams;Bt=tk.CancellationToken.is(ct[zt])?ct[zt]:void 0}let qt=o++,Ot;return Bt&&(Ot=Bt.onCancellationRequested(()=>{let ct=B.sender.sendCancellation(vu,qt);return ct===void 0?(r.log(`Received no promise from cancellation strategy when cancelling id ${qt}`),Promise.resolve()):ct.catch(()=>{r.log(`Sending cancellation messages for id ${qt} failed`)})})),new Promise((ct,zt)=>{let bt={jsonrpc:l,id:qt,method:ce,params:Ce},Ci=Is=>{ct(Is),B.sender.cleanup(qt),Ot==null||Ot.dispose()},Dn=Is=>{zt(Is),B.sender.cleanup(qt),Ot==null||Ot.dispose()},Ha={method:ce,timerStart:Date.now(),resolve:Ci,reject:Dn};xi(bt);try{e.write(bt).catch(()=>r.error("Sending request failed."))}catch(Is){Ha.reject(new qe.ResponseError(qe.ErrorCodes.MessageWriteError,Is.message?Is.message:"Unknown reason")),Ha=null}Ha&&b.set(qt,Ha)})},onRequest:(E,G)=>{Id();let ce=null;return nk.is(E)?(ce=void 0,u=E):Di.string(E)?(ce=null,G!==void 0&&(ce=E,c.set(E,{handler:G,type:void 0}))):G!==void 0&&(ce=E.method,c.set(E.method,{type:E,handler:G})),{dispose:()=>{ce!==null&&(ce!==void 0?c.delete(ce):u=void 0)}}},hasPendingResponse:()=>b.size>0,trace:async(E,G,ce)=>{let Ce=!1,Bt=Ar.Text;ce!==void 0&&(Di.boolean(ce)?Ce=ce:(Ce=ce.sendNotification||!1,Bt=ce.traceFormat||Ar.Text)),C=E,k=Bt,C===Ct.Off?T=void 0:T=G,Ce&&!ee()&&!Te()&&await vu.sendNotification(iY.type,{value:Ct.toString(E)})},onError:N.event,onClose:X.event,onUnhandledNotification:se.event,onDispose:K.event,end:()=>{e.end()},dispose:()=>{if(Te())return;j=Nr.Disposed,K.fire(void 0);let E=new qe.ResponseError(qe.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let G of b.values())G.reject(E);b=new Map,x=new Map,v=new Set,m=new eY.LinkedMap,Di.func(e.dispose)&&e.dispose(),Di.func(n.dispose)&&n.dispose()},listen:()=>{Id(),E6(),j=Nr.Listening,n.listen(Er)},inspect:()=>{(0,VW.default)().console.log("inspect")}};return vu.onNotification(rk.type,E=>{if(C===Ct.Off||!T)return;let G=C===Ct.Verbose||C===Ct.Compact;T.log(E.message,G?E.verbose:void 0)}),vu.onNotification(Sh.type,E=>{let G=g.get(E.token);G?G(E.value):Y.fire(E)}),vu}Oe.createMessageConnection=Wne});var dk=w(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.TraceFormat=J.TraceValues=J.Trace=J.ProgressType=J.ProgressToken=J.createMessageConnection=J.NullLogger=J.ConnectionOptions=J.ConnectionStrategy=J.WriteableStreamMessageWriter=J.AbstractMessageWriter=J.MessageWriter=J.ReadableStreamMessageReader=J.AbstractMessageReader=J.MessageReader=J.CancellationToken=J.CancellationTokenSource=J.Emitter=J.Event=J.Disposable=J.LRUCache=J.Touch=J.LinkedMap=J.ParameterStructures=J.NotificationType9=J.NotificationType8=J.NotificationType7=J.NotificationType6=J.NotificationType5=J.NotificationType4=J.NotificationType3=J.NotificationType2=J.NotificationType1=J.NotificationType0=J.NotificationType=J.ErrorCodes=J.ResponseError=J.RequestType9=J.RequestType8=J.RequestType7=J.RequestType6=J.RequestType5=J.RequestType4=J.RequestType3=J.RequestType2=J.RequestType1=J.RequestType0=J.RequestType=J.Message=J.RAL=void 0;J.CancellationStrategy=J.CancellationSenderStrategy=J.CancellationReceiverStrategy=J.ConnectionError=J.ConnectionErrors=J.LogTraceNotification=J.SetTraceNotification=void 0;var At=BT();Object.defineProperty(J,"Message",{enumerable:!0,get:function(){return At.Message}});Object.defineProperty(J,"RequestType",{enumerable:!0,get:function(){return At.RequestType}});Object.defineProperty(J,"RequestType0",{enumerable:!0,get:function(){return At.RequestType0}});Object.defineProperty(J,"RequestType1",{enumerable:!0,get:function(){return At.RequestType1}});Object.defineProperty(J,"RequestType2",{enumerable:!0,get:function(){return At.RequestType2}});Object.defineProperty(J,"RequestType3",{enumerable:!0,get:function(){return At.RequestType3}});Object.defineProperty(J,"RequestType4",{enumerable:!0,get:function(){return At.RequestType4}});Object.defineProperty(J,"RequestType5",{enumerable:!0,get:function(){return At.RequestType5}});Object.defineProperty(J,"RequestType6",{enumerable:!0,get:function(){return At.RequestType6}});Object.defineProperty(J,"RequestType7",{enumerable:!0,get:function(){return At.RequestType7}});Object.defineProperty(J,"RequestType8",{enumerable:!0,get:function(){return At.RequestType8}});Object.defineProperty(J,"RequestType9",{enumerable:!0,get:function(){return At.RequestType9}});Object.defineProperty(J,"ResponseError",{enumerable:!0,get:function(){return At.ResponseError}});Object.defineProperty(J,"ErrorCodes",{enumerable:!0,get:function(){return At.ErrorCodes}});Object.defineProperty(J,"NotificationType",{enumerable:!0,get:function(){return At.NotificationType}});Object.defineProperty(J,"NotificationType0",{enumerable:!0,get:function(){return At.NotificationType0}});Object.defineProperty(J,"NotificationType1",{enumerable:!0,get:function(){return At.NotificationType1}});Object.defineProperty(J,"NotificationType2",{enumerable:!0,get:function(){return At.NotificationType2}});Object.defineProperty(J,"NotificationType3",{enumerable:!0,get:function(){return At.NotificationType3}});Object.defineProperty(J,"NotificationType4",{enumerable:!0,get:function(){return At.NotificationType4}});Object.defineProperty(J,"NotificationType5",{enumerable:!0,get:function(){return At.NotificationType5}});Object.defineProperty(J,"NotificationType6",{enumerable:!0,get:function(){return At.NotificationType6}});Object.defineProperty(J,"NotificationType7",{enumerable:!0,get:function(){return At.NotificationType7}});Object.defineProperty(J,"NotificationType8",{enumerable:!0,get:function(){return At.NotificationType8}});Object.defineProperty(J,"NotificationType9",{enumerable:!0,get:function(){return At.NotificationType9}});Object.defineProperty(J,"ParameterStructures",{enumerable:!0,get:function(){return At.ParameterStructures}});var lk=WT();Object.defineProperty(J,"LinkedMap",{enumerable:!0,get:function(){return lk.LinkedMap}});Object.defineProperty(J,"LRUCache",{enumerable:!0,get:function(){return lk.LRUCache}});Object.defineProperty(J,"Touch",{enumerable:!0,get:function(){return lk.Touch}});var Yne=hT();Object.defineProperty(J,"Disposable",{enumerable:!0,get:function(){return Yne.Disposable}});var oY=zu();Object.defineProperty(J,"Event",{enumerable:!0,get:function(){return oY.Event}});Object.defineProperty(J,"Emitter",{enumerable:!0,get:function(){return oY.Emitter}});var sY=UT();Object.defineProperty(J,"CancellationTokenSource",{enumerable:!0,get:function(){return sY.CancellationTokenSource}});Object.defineProperty(J,"CancellationToken",{enumerable:!0,get:function(){return sY.CancellationToken}});var uk=UW();Object.defineProperty(J,"MessageReader",{enumerable:!0,get:function(){return uk.MessageReader}});Object.defineProperty(J,"AbstractMessageReader",{enumerable:!0,get:function(){return uk.AbstractMessageReader}});Object.defineProperty(J,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return uk.ReadableStreamMessageReader}});var ck=QW();Object.defineProperty(J,"MessageWriter",{enumerable:!0,get:function(){return ck.MessageWriter}});Object.defineProperty(J,"AbstractMessageWriter",{enumerable:!0,get:function(){return ck.AbstractMessageWriter}});Object.defineProperty(J,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return ck.WriteableStreamMessageWriter}});var tn=rY();Object.defineProperty(J,"ConnectionStrategy",{enumerable:!0,get:function(){return tn.ConnectionStrategy}});Object.defineProperty(J,"ConnectionOptions",{enumerable:!0,get:function(){return tn.ConnectionOptions}});Object.defineProperty(J,"NullLogger",{enumerable:!0,get:function(){return tn.NullLogger}});Object.defineProperty(J,"createMessageConnection",{enumerable:!0,get:function(){return tn.createMessageConnection}});Object.defineProperty(J,"ProgressToken",{enumerable:!0,get:function(){return tn.ProgressToken}});Object.defineProperty(J,"ProgressType",{enumerable:!0,get:function(){return tn.ProgressType}});Object.defineProperty(J,"Trace",{enumerable:!0,get:function(){return tn.Trace}});Object.defineProperty(J,"TraceValues",{enumerable:!0,get:function(){return tn.TraceValues}});Object.defineProperty(J,"TraceFormat",{enumerable:!0,get:function(){return tn.TraceFormat}});Object.defineProperty(J,"SetTraceNotification",{enumerable:!0,get:function(){return tn.SetTraceNotification}});Object.defineProperty(J,"LogTraceNotification",{enumerable:!0,get:function(){return tn.LogTraceNotification}});Object.defineProperty(J,"ConnectionErrors",{enumerable:!0,get:function(){return tn.ConnectionErrors}});Object.defineProperty(J,"ConnectionError",{enumerable:!0,get:function(){return tn.ConnectionError}});Object.defineProperty(J,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return tn.CancellationReceiverStrategy}});Object.defineProperty(J,"CancellationSenderStrategy",{enumerable:!0,get:function(){return tn.CancellationSenderStrategy}});Object.defineProperty(J,"CancellationStrategy",{enumerable:!0,get:function(){return tn.CancellationStrategy}});var Zne=$o();J.RAL=Zne.default});var ul=w(mt=>{"use strict";var Jne=mt&&mt.__createBinding||(Object.create?function(n,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,i,r)}:function(n,e,t,i){i===void 0&&(i=t),n[i]=e[t]}),$ne=mt&&mt.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Jne(e,n,t)};Object.defineProperty(mt,"__esModule",{value:!0});mt.createMessageConnection=mt.createServerSocketTransport=mt.createClientSocketTransport=mt.createServerPipeTransport=mt.createClientPipeTransport=mt.generateRandomPipeName=mt.StreamMessageWriter=mt.StreamMessageReader=mt.SocketMessageWriter=mt.SocketMessageReader=mt.IPCMessageWriter=mt.IPCMessageReader=void 0;var Qu=WW();Qu.default.install();var po=dk(),aY=require("path"),Une=require("os"),Xne=require("crypto"),My=require("net");$ne(dk(),mt);var hk=class extends po.AbstractMessageReader{constructor(e){super(),this.process=e;let t=this.process;t.on("error",i=>this.fireError(i)),t.on("close",()=>this.fireClose())}listen(e){return this.process.on("message",e),po.Disposable.create(()=>this.process.off("message",e))}};mt.IPCMessageReader=hk;var gk=class extends po.AbstractMessageWriter{constructor(e){super(),this.process=e,this.errorCount=0;let t=this.process;t.on("error",i=>this.fireError(i)),t.on("close",()=>this.fireClose)}write(e){try{return typeof this.process.send=="function"&&this.process.send(e,void 0,void 0,t=>{t?(this.errorCount++,this.handleError(t,e)):this.errorCount=0}),Promise.resolve()}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}};mt.IPCMessageWriter=gk;var al=class extends po.ReadableStreamMessageReader{constructor(e,t="utf-8"){super((0,Qu.default)().stream.asReadableStream(e),t)}};mt.SocketMessageReader=al;var ll=class extends po.WriteableStreamMessageWriter{constructor(e,t){super((0,Qu.default)().stream.asWritableStream(e),t),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}};mt.SocketMessageWriter=ll;var Ly=class extends po.ReadableStreamMessageReader{constructor(e,t){super((0,Qu.default)().stream.asReadableStream(e),t)}};mt.StreamMessageReader=Ly;var Fy=class extends po.WriteableStreamMessageWriter{constructor(e,t){super((0,Qu.default)().stream.asWritableStream(e),t)}};mt.StreamMessageWriter=Fy;var lY=process.env.XDG_RUNTIME_DIR,Gne=new Map([["linux",107],["darwin",103]]);function zne(){let n=(0,Xne.randomBytes)(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${n}-sock`;let e;lY?e=aY.join(lY,`vscode-ipc-${n}.sock`):e=aY.join(Une.tmpdir(),`vscode-${n}.sock`);let t=Gne.get(process.platform);return t!==void 0&&e.length>=t&&(0,Qu.default)().console.warn(`WARNING: IPC handle "${e}" is longer than ${t} characters.`),e}mt.generateRandomPipeName=zne;function Kne(n,e="utf-8"){let t,i=new Promise((r,o)=>{t=r});return new Promise((r,o)=>{let s=(0,My.createServer)(a=>{s.close(),t([new al(a,e),new ll(a,e)])});s.on("error",o),s.listen(n,()=>{s.removeListener("error",o),r({onConnected:()=>i})})})}mt.createClientPipeTransport=Kne;function Qne(n,e="utf-8"){let t=(0,My.createConnection)(n);return[new al(t,e),new ll(t,e)]}mt.createServerPipeTransport=Qne;function Vne(n,e="utf-8"){let t,i=new Promise((r,o)=>{t=r});return new Promise((r,o)=>{let s=(0,My.createServer)(a=>{s.close(),t([new al(a,e),new ll(a,e)])});s.on("error",o),s.listen(n,"127.0.0.1",()=>{s.removeListener("error",o),r({onConnected:()=>i})})})}mt.createClientSocketTransport=Vne;function ere(n,e="utf-8"){let t=(0,My.createConnection)(n,"127.0.0.1");return[new al(t,e),new ll(t,e)]}mt.createServerSocketTransport=ere;function tre(n){let e=n;return e.read!==void 0&&e.addListener!==void 0}function ire(n){let e=n;return e.write!==void 0&&e.addListener!==void 0}function nre(n,e,t,i){t||(t=po.NullLogger);let r=tre(n)?new Ly(n):n,o=ire(e)?new Fy(e):e;return po.ConnectionStrategy.is(i)&&(i={connectionStrategy:i}),(0,po.createMessageConnection)(r,o,t,i)}mt.createMessageConnection=nre});var pk=w((JSe,uY)=>{"use strict";uY.exports=ul()});var Ay={};Ls(Ay,{AnnotatedTextEdit:()=>_n,ChangeAnnotation:()=>zo,ChangeAnnotationIdentifier:()=>Ti,CodeAction:()=>Zh,CodeActionContext:()=>Yh,CodeActionKind:()=>ri,CodeActionTriggerKind:()=>es,CodeDescription:()=>Ih,CodeLens:()=>Jh,Color:()=>Vu,ColorInformation:()=>Ph,ColorPresentation:()=>Rh,Command:()=>En,CompletionItem:()=>Oh,CompletionItemKind:()=>ie,CompletionItemLabelDetails:()=>jh,CompletionItemTag:()=>Ko,CompletionList:()=>Ah,CreateFile:()=>Un,DeleteFile:()=>In,Diagnostic:()=>Hr,DiagnosticRelatedInformation:()=>ec,DiagnosticSeverity:()=>it,DiagnosticTag:()=>Ji,DocumentHighlight:()=>Bh,DocumentHighlightKind:()=>Zs,DocumentLink:()=>pl,DocumentSymbol:()=>Js,DocumentUri:()=>Th,EOL:()=>rre,FoldingRange:()=>Eh,FoldingRangeKind:()=>_h,FormattingOptions:()=>$h,Hover:()=>Vo,InlayHint:()=>Qh,InlayHintKind:()=>Br,InlayHintLabelPart:()=>tc,InlineValueContext:()=>Kh,InlineValueEvaluatableExpression:()=>zh,InlineValueText:()=>Xh,InlineValueVariableLookup:()=>Gh,InsertReplaceEdit:()=>gl,InsertTextFormat:()=>hl,InsertTextMode:()=>mr,Location:()=>Ke,LocationLink:()=>pr,MarkedString:()=>Qo,MarkupContent:()=>Ln,MarkupKind:()=>fr,OptionalVersionedTextDocumentIdentifier:()=>dl,ParameterInformation:()=>Nh,Position:()=>Q,Range:()=>M,RenameFile:()=>Xn,SelectionRange:()=>Uh,SemanticTokenModifiers:()=>nn,SemanticTokenTypes:()=>St,SemanticTokens:()=>$s,SignatureInformation:()=>Hh,SymbolInformation:()=>qh,SymbolKind:()=>De,SymbolTag:()=>$i,TextDocument:()=>fk,TextDocumentEdit:()=>Qt,TextDocumentIdentifier:()=>Lh,TextDocumentItem:()=>Mh,TextEdit:()=>Ye,URI:()=>Oy,VersionedTextDocumentIdentifier:()=>Fh,WorkspaceChange:()=>mk,WorkspaceEdit:()=>Ys,WorkspaceFolder:()=>Vh,WorkspaceSymbol:()=>Wh,integer:()=>kh,uinteger:()=>cl});var Th,Oy,kh,cl,Q,M,Ke,pr,Vu,Ph,Rh,_h,Eh,ec,it,Ji,Ih,Hr,En,Ye,zo,Ti,_n,Qt,Un,Xn,In,Ys,jy,cY,mk,Lh,Fh,dl,Mh,fr,Ln,ie,hl,Ko,gl,mr,jh,Oh,Ah,Qo,Vo,Nh,Hh,Zs,Bh,De,$i,qh,Wh,Js,ri,es,Yh,Zh,Jh,$h,pl,Uh,St,nn,$s,Xh,Gh,zh,Kh,Br,tc,Qh,Vh,rre,fk,ore,A,ae=D(()=>{"use strict";(function(n){function e(t){return typeof t=="string"}n.is=e})(Th||(Th={}));(function(n){function e(t){return typeof t=="string"}n.is=e})(Oy||(Oy={}));(function(n){n.MIN_VALUE=-2147483648,n.MAX_VALUE=2147483647;function e(t){return typeof t=="number"&&n.MIN_VALUE<=t&&t<=n.MAX_VALUE}n.is=e})(kh||(kh={}));(function(n){n.MIN_VALUE=0,n.MAX_VALUE=2147483647;function e(t){return typeof t=="number"&&n.MIN_VALUE<=t&&t<=n.MAX_VALUE}n.is=e})(cl||(cl={}));(function(n){function e(i,r){return i===Number.MAX_VALUE&&(i=cl.MAX_VALUE),r===Number.MAX_VALUE&&(r=cl.MAX_VALUE),{line:i,character:r}}n.create=e;function t(i){var r=i;return A.objectLiteral(r)&&A.uinteger(r.line)&&A.uinteger(r.character)}n.is=t})(Q||(Q={}));(function(n){function e(i,r,o,s){if(A.uinteger(i)&&A.uinteger(r)&&A.uinteger(o)&&A.uinteger(s))return{start:Q.create(i,r),end:Q.create(o,s)};if(Q.is(i)&&Q.is(r))return{start:i,end:r};throw new Error("Range#create called with invalid arguments[".concat(i,", ").concat(r,", ").concat(o,", ").concat(s,"]"))}n.create=e;function t(i){var r=i;return A.objectLiteral(r)&&Q.is(r.start)&&Q.is(r.end)}n.is=t})(M||(M={}));(function(n){function e(i,r){return{uri:i,range:r}}n.create=e;function t(i){var r=i;return A.objectLiteral(r)&&M.is(r.range)&&(A.string(r.uri)||A.undefined(r.uri))}n.is=t})(Ke||(Ke={}));(function(n){function e(i,r,o,s){return{targetUri:i,targetRange:r,targetSelectionRange:o,originSelectionRange:s}}n.create=e;function t(i){var r=i;return A.objectLiteral(r)&&M.is(r.targetRange)&&A.string(r.targetUri)&&M.is(r.targetSelectionRange)&&(M.is(r.originSelectionRange)||A.undefined(r.originSelectionRange))}n.is=t})(pr||(pr={}));(function(n){function e(i,r,o,s){return{red:i,green:r,blue:o,alpha:s}}n.create=e;function t(i){var r=i;return A.objectLiteral(r)&&A.numberRange(r.red,0,1)&&A.numberRange(r.green,0,1)&&A.numberRange(r.blue,0,1)&&A.numberRange(r.alpha,0,1)}n.is=t})(Vu||(Vu={}));(function(n){function e(i,r){return{range:i,color:r}}n.create=e;function t(i){var r=i;return A.objectLiteral(r)&&M.is(r.range)&&Vu.is(r.color)}n.is=t})(Ph||(Ph={}));(function(n){function e(i,r,o){return{label:i,textEdit:r,additionalTextEdits:o}}n.create=e;function t(i){var r=i;return A.objectLiteral(r)&&A.string(r.label)&&(A.undefined(r.textEdit)||Ye.is(r))&&(A.undefined(r.additionalTextEdits)||A.typedArray(r.additionalTextEdits,Ye.is))}n.is=t})(Rh||(Rh={}));(function(n){n.Comment="comment",n.Imports="imports",n.Region="region"})(_h||(_h={}));(function(n){function e(i,r,o,s,a,l){var u={startLine:i,endLine:r};return A.defined(o)&&(u.startCharacter=o),A.defined(s)&&(u.endCharacter=s),A.defined(a)&&(u.kind=a),A.defined(l)&&(u.collapsedText=l),u}n.create=e;function t(i){var r=i;return A.objectLiteral(r)&&A.uinteger(r.startLine)&&A.uinteger(r.startLine)&&(A.undefined(r.startCharacter)||A.uinteger(r.startCharacter))&&(A.undefined(r.endCharacter)||A.uinteger(r.endCharacter))&&(A.undefined(r.kind)||A.string(r.kind))}n.is=t})(Eh||(Eh={}));(function(n){function e(i,r){return{location:i,message:r}}n.create=e;function t(i){var r=i;return A.defined(r)&&Ke.is(r.location)&&A.string(r.message)}n.is=t})(ec||(ec={}));(function(n){n.Error=1,n.Warning=2,n.Information=3,n.Hint=4})(it||(it={}));(function(n){n.Unnecessary=1,n.Deprecated=2})(Ji||(Ji={}));(function(n){function e(t){var i=t;return A.objectLiteral(i)&&A.string(i.href)}n.is=e})(Ih||(Ih={}));(function(n){function e(i,r,o,s,a,l){var u={range:i,message:r};return A.defined(o)&&(u.severity=o),A.defined(s)&&(u.code=s),A.defined(a)&&(u.source=a),A.defined(l)&&(u.relatedInformation=l),u}n.create=e;function t(i){var r,o=i;return A.defined(o)&&M.is(o.range)&&A.string(o.message)&&(A.number(o.severity)||A.undefined(o.severity))&&(A.integer(o.code)||A.string(o.code)||A.undefined(o.code))&&(A.undefined(o.codeDescription)||A.string((r=o.codeDescription)===null||r===void 0?void 0:r.href))&&(A.string(o.source)||A.undefined(o.source))&&(A.undefined(o.relatedInformation)||A.typedArray(o.relatedInformation,ec.is))}n.is=t})(Hr||(Hr={}));(function(n){function e(i,r){for(var o=[],s=2;s0&&(a.arguments=o),a}n.create=e;function t(i){var r=i;return A.defined(r)&&A.string(r.title)&&A.string(r.command)}n.is=t})(En||(En={}));(function(n){function e(o,s){return{range:o,newText:s}}n.replace=e;function t(o,s){return{range:{start:o,end:o},newText:s}}n.insert=t;function i(o){return{range:o,newText:""}}n.del=i;function r(o){var s=o;return A.objectLiteral(s)&&A.string(s.newText)&&M.is(s.range)}n.is=r})(Ye||(Ye={}));(function(n){function e(i,r,o){var s={label:i};return r!==void 0&&(s.needsConfirmation=r),o!==void 0&&(s.description=o),s}n.create=e;function t(i){var r=i;return A.objectLiteral(r)&&A.string(r.label)&&(A.boolean(r.needsConfirmation)||r.needsConfirmation===void 0)&&(A.string(r.description)||r.description===void 0)}n.is=t})(zo||(zo={}));(function(n){function e(t){var i=t;return A.string(i)}n.is=e})(Ti||(Ti={}));(function(n){function e(o,s,a){return{range:o,newText:s,annotationId:a}}n.replace=e;function t(o,s,a){return{range:{start:o,end:o},newText:s,annotationId:a}}n.insert=t;function i(o,s){return{range:o,newText:"",annotationId:s}}n.del=i;function r(o){var s=o;return Ye.is(s)&&(zo.is(s.annotationId)||Ti.is(s.annotationId))}n.is=r})(_n||(_n={}));(function(n){function e(i,r){return{textDocument:i,edits:r}}n.create=e;function t(i){var r=i;return A.defined(r)&&dl.is(r.textDocument)&&Array.isArray(r.edits)}n.is=t})(Qt||(Qt={}));(function(n){function e(i,r,o){var s={kind:"create",uri:i};return r!==void 0&&(r.overwrite!==void 0||r.ignoreIfExists!==void 0)&&(s.options=r),o!==void 0&&(s.annotationId=o),s}n.create=e;function t(i){var r=i;return r&&r.kind==="create"&&A.string(r.uri)&&(r.options===void 0||(r.options.overwrite===void 0||A.boolean(r.options.overwrite))&&(r.options.ignoreIfExists===void 0||A.boolean(r.options.ignoreIfExists)))&&(r.annotationId===void 0||Ti.is(r.annotationId))}n.is=t})(Un||(Un={}));(function(n){function e(i,r,o,s){var a={kind:"rename",oldUri:i,newUri:r};return o!==void 0&&(o.overwrite!==void 0||o.ignoreIfExists!==void 0)&&(a.options=o),s!==void 0&&(a.annotationId=s),a}n.create=e;function t(i){var r=i;return r&&r.kind==="rename"&&A.string(r.oldUri)&&A.string(r.newUri)&&(r.options===void 0||(r.options.overwrite===void 0||A.boolean(r.options.overwrite))&&(r.options.ignoreIfExists===void 0||A.boolean(r.options.ignoreIfExists)))&&(r.annotationId===void 0||Ti.is(r.annotationId))}n.is=t})(Xn||(Xn={}));(function(n){function e(i,r,o){var s={kind:"delete",uri:i};return r!==void 0&&(r.recursive!==void 0||r.ignoreIfNotExists!==void 0)&&(s.options=r),o!==void 0&&(s.annotationId=o),s}n.create=e;function t(i){var r=i;return r&&r.kind==="delete"&&A.string(r.uri)&&(r.options===void 0||(r.options.recursive===void 0||A.boolean(r.options.recursive))&&(r.options.ignoreIfNotExists===void 0||A.boolean(r.options.ignoreIfNotExists)))&&(r.annotationId===void 0||Ti.is(r.annotationId))}n.is=t})(In||(In={}));(function(n){function e(t){var i=t;return i&&(i.changes!==void 0||i.documentChanges!==void 0)&&(i.documentChanges===void 0||i.documentChanges.every(function(r){return A.string(r.kind)?Un.is(r)||Xn.is(r)||In.is(r):Qt.is(r)}))}n.is=e})(Ys||(Ys={}));jy=function(){function n(e,t){this.edits=e,this.changeAnnotations=t}return n.prototype.insert=function(e,t,i){var r,o;if(i===void 0?r=Ye.insert(e,t):Ti.is(i)?(o=i,r=_n.insert(e,t,i)):(this.assertChangeAnnotations(this.changeAnnotations),o=this.changeAnnotations.manage(i),r=_n.insert(e,t,o)),this.edits.push(r),o!==void 0)return o},n.prototype.replace=function(e,t,i){var r,o;if(i===void 0?r=Ye.replace(e,t):Ti.is(i)?(o=i,r=_n.replace(e,t,i)):(this.assertChangeAnnotations(this.changeAnnotations),o=this.changeAnnotations.manage(i),r=_n.replace(e,t,o)),this.edits.push(r),o!==void 0)return o},n.prototype.delete=function(e,t){var i,r;if(t===void 0?i=Ye.del(e):Ti.is(t)?(r=t,i=_n.del(e,t)):(this.assertChangeAnnotations(this.changeAnnotations),r=this.changeAnnotations.manage(t),i=_n.del(e,r)),this.edits.push(i),r!==void 0)return r},n.prototype.add=function(e){this.edits.push(e)},n.prototype.all=function(){return this.edits},n.prototype.clear=function(){this.edits.splice(0,this.edits.length)},n.prototype.assertChangeAnnotations=function(e){if(e===void 0)throw new Error("Text edit change is not configured to manage change annotations.")},n}(),cY=function(){function n(e){this._annotations=e===void 0?Object.create(null):e,this._counter=0,this._size=0}return n.prototype.all=function(){return this._annotations},Object.defineProperty(n.prototype,"size",{get:function(){return this._size},enumerable:!1,configurable:!0}),n.prototype.manage=function(e,t){var i;if(Ti.is(e)?i=e:(i=this.nextId(),t=e),this._annotations[i]!==void 0)throw new Error("Id ".concat(i," is already in use."));if(t===void 0)throw new Error("No annotation provided for id ".concat(i));return this._annotations[i]=t,this._size++,i},n.prototype.nextId=function(){return this._counter++,this._counter.toString()},n}(),mk=function(){function n(e){var t=this;this._textEditChanges=Object.create(null),e!==void 0?(this._workspaceEdit=e,e.documentChanges?(this._changeAnnotations=new cY(e.changeAnnotations),e.changeAnnotations=this._changeAnnotations.all(),e.documentChanges.forEach(function(i){if(Qt.is(i)){var r=new jy(i.edits,t._changeAnnotations);t._textEditChanges[i.textDocument.uri]=r}})):e.changes&&Object.keys(e.changes).forEach(function(i){var r=new jy(e.changes[i]);t._textEditChanges[i]=r})):this._workspaceEdit={}}return Object.defineProperty(n.prototype,"edit",{get:function(){return this.initDocumentChanges(),this._changeAnnotations!==void 0&&(this._changeAnnotations.size===0?this._workspaceEdit.changeAnnotations=void 0:this._workspaceEdit.changeAnnotations=this._changeAnnotations.all()),this._workspaceEdit},enumerable:!1,configurable:!0}),n.prototype.getTextEditChange=function(e){if(dl.is(e)){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");var t={uri:e.uri,version:e.version},i=this._textEditChanges[t.uri];if(!i){var r=[],o={textDocument:t,edits:r};this._workspaceEdit.documentChanges.push(o),i=new jy(r,this._changeAnnotations),this._textEditChanges[t.uri]=i}return i}else{if(this.initChanges(),this._workspaceEdit.changes===void 0)throw new Error("Workspace edit is not configured for normal text edit changes.");var i=this._textEditChanges[e];if(!i){var r=[];this._workspaceEdit.changes[e]=r,i=new jy(r),this._textEditChanges[e]=i}return i}},n.prototype.initDocumentChanges=function(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._changeAnnotations=new cY,this._workspaceEdit.documentChanges=[],this._workspaceEdit.changeAnnotations=this._changeAnnotations.all())},n.prototype.initChanges=function(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._workspaceEdit.changes=Object.create(null))},n.prototype.createFile=function(e,t,i){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");var r;zo.is(t)||Ti.is(t)?r=t:i=t;var o,s;if(r===void 0?o=Un.create(e,i):(s=Ti.is(r)?r:this._changeAnnotations.manage(r),o=Un.create(e,i,s)),this._workspaceEdit.documentChanges.push(o),s!==void 0)return s},n.prototype.renameFile=function(e,t,i,r){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");var o;zo.is(i)||Ti.is(i)?o=i:r=i;var s,a;if(o===void 0?s=Xn.create(e,t,r):(a=Ti.is(o)?o:this._changeAnnotations.manage(o),s=Xn.create(e,t,r,a)),this._workspaceEdit.documentChanges.push(s),a!==void 0)return a},n.prototype.deleteFile=function(e,t,i){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");var r;zo.is(t)||Ti.is(t)?r=t:i=t;var o,s;if(r===void 0?o=In.create(e,i):(s=Ti.is(r)?r:this._changeAnnotations.manage(r),o=In.create(e,i,s)),this._workspaceEdit.documentChanges.push(o),s!==void 0)return s},n}();(function(n){function e(i){return{uri:i}}n.create=e;function t(i){var r=i;return A.defined(r)&&A.string(r.uri)}n.is=t})(Lh||(Lh={}));(function(n){function e(i,r){return{uri:i,version:r}}n.create=e;function t(i){var r=i;return A.defined(r)&&A.string(r.uri)&&A.integer(r.version)}n.is=t})(Fh||(Fh={}));(function(n){function e(i,r){return{uri:i,version:r}}n.create=e;function t(i){var r=i;return A.defined(r)&&A.string(r.uri)&&(r.version===null||A.integer(r.version))}n.is=t})(dl||(dl={}));(function(n){function e(i,r,o,s){return{uri:i,languageId:r,version:o,text:s}}n.create=e;function t(i){var r=i;return A.defined(r)&&A.string(r.uri)&&A.string(r.languageId)&&A.integer(r.version)&&A.string(r.text)}n.is=t})(Mh||(Mh={}));(function(n){n.PlainText="plaintext",n.Markdown="markdown";function e(t){var i=t;return i===n.PlainText||i===n.Markdown}n.is=e})(fr||(fr={}));(function(n){function e(t){var i=t;return A.objectLiteral(t)&&fr.is(i.kind)&&A.string(i.value)}n.is=e})(Ln||(Ln={}));(function(n){n.Text=1,n.Method=2,n.Function=3,n.Constructor=4,n.Field=5,n.Variable=6,n.Class=7,n.Interface=8,n.Module=9,n.Property=10,n.Unit=11,n.Value=12,n.Enum=13,n.Keyword=14,n.Snippet=15,n.Color=16,n.File=17,n.Reference=18,n.Folder=19,n.EnumMember=20,n.Constant=21,n.Struct=22,n.Event=23,n.Operator=24,n.TypeParameter=25})(ie||(ie={}));(function(n){n.PlainText=1,n.Snippet=2})(hl||(hl={}));(function(n){n.Deprecated=1})(Ko||(Ko={}));(function(n){function e(i,r,o){return{newText:i,insert:r,replace:o}}n.create=e;function t(i){var r=i;return r&&A.string(r.newText)&&M.is(r.insert)&&M.is(r.replace)}n.is=t})(gl||(gl={}));(function(n){n.asIs=1,n.adjustIndentation=2})(mr||(mr={}));(function(n){function e(t){var i=t;return i&&(A.string(i.detail)||i.detail===void 0)&&(A.string(i.description)||i.description===void 0)}n.is=e})(jh||(jh={}));(function(n){function e(t){return{label:t}}n.create=e})(Oh||(Oh={}));(function(n){function e(t,i){return{items:t||[],isIncomplete:!!i}}n.create=e})(Ah||(Ah={}));(function(n){function e(i){return i.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}n.fromPlainText=e;function t(i){var r=i;return A.string(r)||A.objectLiteral(r)&&A.string(r.language)&&A.string(r.value)}n.is=t})(Qo||(Qo={}));(function(n){function e(t){var i=t;return!!i&&A.objectLiteral(i)&&(Ln.is(i.contents)||Qo.is(i.contents)||A.typedArray(i.contents,Qo.is))&&(t.range===void 0||M.is(t.range))}n.is=e})(Vo||(Vo={}));(function(n){function e(t,i){return i?{label:t,documentation:i}:{label:t}}n.create=e})(Nh||(Nh={}));(function(n){function e(t,i){for(var r=[],o=2;o=0;c--){var d=l[c],h=o.offsetAt(d.range.start),g=o.offsetAt(d.range.end);if(g<=u)a=a.substring(0,h)+d.newText+a.substring(g,a.length);else throw new Error("Overlapping edit");u=h}return a}n.applyEdits=i;function r(o,s){if(o.length<=1)return o;var a=o.length/2|0,l=o.slice(0,a),u=o.slice(a);r(l,s),r(u,s);for(var c=0,d=0,h=0;c0&&e.push(t.length),this._lineOffsets=e}return this._lineOffsets},n.prototype.positionAt=function(e){e=Math.max(Math.min(e,this._content.length),0);var t=this.getLineOffsets(),i=0,r=t.length;if(r===0)return Q.create(0,e);for(;ie?r=o:i=o+1}var s=i-1;return Q.create(s,e-t[s])},n.prototype.offsetAt=function(e){var t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;var i=t[e.line],r=e.line+1"u"}n.undefined=i;function r(g){return g===!0||g===!1}n.boolean=r;function o(g){return e.call(g)==="[object String]"}n.string=o;function s(g){return e.call(g)==="[object Number]"}n.number=s;function a(g,f,m){return e.call(g)==="[object Number]"&&f<=g&&g<=m}n.numberRange=a;function l(g){return e.call(g)==="[object Number]"&&-2147483648<=g&&g<=2147483647}n.integer=l;function u(g){return e.call(g)==="[object Number]"&&0<=g&&g<=2147483647}n.uinteger=u;function c(g){return e.call(g)==="[object Function]"}n.func=c;function d(g){return g!==null&&typeof g=="object"}n.objectLiteral=d;function h(g,f){return Array.isArray(g)&&g.every(f)}n.typedArray=h})(A||(A={}))});var Vt=w(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.ProtocolNotificationType=yn.ProtocolNotificationType0=yn.ProtocolRequestType=yn.ProtocolRequestType0=yn.RegistrationType=yn.MessageDirection=void 0;var ic=ul(),sre;(function(n){n.clientToServer="clientToServer",n.serverToClient="serverToClient",n.both="both"})(sre=yn.MessageDirection||(yn.MessageDirection={}));var bk=class{constructor(e){this.method=e}};yn.RegistrationType=bk;var yk=class extends ic.RequestType0{constructor(e){super(e)}};yn.ProtocolRequestType0=yk;var vk=class extends ic.RequestType{constructor(e){super(e,ic.ParameterStructures.byName)}};yn.ProtocolRequestType=vk;var wk=class extends ic.NotificationType0{constructor(e){super(e)}};yn.ProtocolNotificationType0=wk;var xk=class extends ic.NotificationType{constructor(e){super(e,ic.ParameterStructures.byName)}};yn.ProtocolNotificationType=xk});var Ny=w(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.objectLiteral=mi.typedArray=mi.stringArray=mi.array=mi.func=mi.error=mi.number=mi.string=mi.boolean=void 0;function are(n){return n===!0||n===!1}mi.boolean=are;function dY(n){return typeof n=="string"||n instanceof String}mi.string=dY;function lre(n){return typeof n=="number"||n instanceof Number}mi.number=lre;function ure(n){return n instanceof Error}mi.error=ure;function cre(n){return typeof n=="function"}mi.func=cre;function hY(n){return Array.isArray(n)}mi.array=hY;function dre(n){return hY(n)&&n.every(e=>dY(e))}mi.stringArray=dre;function hre(n,e){return Array.isArray(n)&&n.every(e)}mi.typedArray=hre;function gre(n){return n!==null&&typeof n=="object"}mi.objectLiteral=gre});var pY=w(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});eg.ImplementationRequest=void 0;var gY=Vt(),pre;(function(n){n.method="textDocument/implementation",n.messageDirection=gY.MessageDirection.clientToServer,n.type=new gY.ProtocolRequestType(n.method)})(pre=eg.ImplementationRequest||(eg.ImplementationRequest={}))});var mY=w(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});tg.TypeDefinitionRequest=void 0;var fY=Vt(),fre;(function(n){n.method="textDocument/typeDefinition",n.messageDirection=fY.MessageDirection.clientToServer,n.type=new fY.ProtocolRequestType(n.method)})(fre=tg.TypeDefinitionRequest||(tg.TypeDefinitionRequest={}))});var bY=w(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.DidChangeWorkspaceFoldersNotification=Us.WorkspaceFoldersRequest=void 0;var Hy=Vt(),mre;(function(n){n.method="workspace/workspaceFolders",n.messageDirection=Hy.MessageDirection.serverToClient,n.type=new Hy.ProtocolRequestType0(n.method)})(mre=Us.WorkspaceFoldersRequest||(Us.WorkspaceFoldersRequest={}));var bre;(function(n){n.method="workspace/didChangeWorkspaceFolders",n.messageDirection=Hy.MessageDirection.clientToServer,n.type=new Hy.ProtocolNotificationType(n.method)})(bre=Us.DidChangeWorkspaceFoldersNotification||(Us.DidChangeWorkspaceFoldersNotification={}))});var vY=w(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});ig.ConfigurationRequest=void 0;var yY=Vt(),yre;(function(n){n.method="workspace/configuration",n.messageDirection=yY.MessageDirection.serverToClient,n.type=new yY.ProtocolRequestType(n.method)})(yre=ig.ConfigurationRequest||(ig.ConfigurationRequest={}))});var wY=w(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.ColorPresentationRequest=Xs.DocumentColorRequest=void 0;var By=Vt(),vre;(function(n){n.method="textDocument/documentColor",n.messageDirection=By.MessageDirection.clientToServer,n.type=new By.ProtocolRequestType(n.method)})(vre=Xs.DocumentColorRequest||(Xs.DocumentColorRequest={}));var wre;(function(n){n.method="textDocument/colorPresentation",n.messageDirection=By.MessageDirection.clientToServer,n.type=new By.ProtocolRequestType(n.method)})(wre=Xs.ColorPresentationRequest||(Xs.ColorPresentationRequest={}))});var CY=w(ng=>{"use strict";Object.defineProperty(ng,"__esModule",{value:!0});ng.FoldingRangeRequest=void 0;var xY=Vt(),xre;(function(n){n.method="textDocument/foldingRange",n.messageDirection=xY.MessageDirection.clientToServer,n.type=new xY.ProtocolRequestType(n.method)})(xre=ng.FoldingRangeRequest||(ng.FoldingRangeRequest={}))});var DY=w(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});rg.DeclarationRequest=void 0;var SY=Vt(),Cre;(function(n){n.method="textDocument/declaration",n.messageDirection=SY.MessageDirection.clientToServer,n.type=new SY.ProtocolRequestType(n.method)})(Cre=rg.DeclarationRequest||(rg.DeclarationRequest={}))});var kY=w(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});og.SelectionRangeRequest=void 0;var TY=Vt(),Sre;(function(n){n.method="textDocument/selectionRange",n.messageDirection=TY.MessageDirection.clientToServer,n.type=new TY.ProtocolRequestType(n.method)})(Sre=og.SelectionRangeRequest||(og.SelectionRangeRequest={}))});var PY=w(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.WorkDoneProgressCancelNotification=qr.WorkDoneProgressCreateRequest=qr.WorkDoneProgress=void 0;var Dre=ul(),qy=Vt(),Tre;(function(n){n.type=new Dre.ProgressType;function e(t){return t===n.type}n.is=e})(Tre=qr.WorkDoneProgress||(qr.WorkDoneProgress={}));var kre;(function(n){n.method="window/workDoneProgress/create",n.messageDirection=qy.MessageDirection.serverToClient,n.type=new qy.ProtocolRequestType(n.method)})(kre=qr.WorkDoneProgressCreateRequest||(qr.WorkDoneProgressCreateRequest={}));var Pre;(function(n){n.method="window/workDoneProgress/cancel",n.messageDirection=qy.MessageDirection.clientToServer,n.type=new qy.ProtocolNotificationType(n.method)})(Pre=qr.WorkDoneProgressCancelNotification||(qr.WorkDoneProgressCancelNotification={}))});var RY=w(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.CallHierarchyOutgoingCallsRequest=Wr.CallHierarchyIncomingCallsRequest=Wr.CallHierarchyPrepareRequest=void 0;var nc=Vt(),Rre;(function(n){n.method="textDocument/prepareCallHierarchy",n.messageDirection=nc.MessageDirection.clientToServer,n.type=new nc.ProtocolRequestType(n.method)})(Rre=Wr.CallHierarchyPrepareRequest||(Wr.CallHierarchyPrepareRequest={}));var _re;(function(n){n.method="callHierarchy/incomingCalls",n.messageDirection=nc.MessageDirection.clientToServer,n.type=new nc.ProtocolRequestType(n.method)})(_re=Wr.CallHierarchyIncomingCallsRequest||(Wr.CallHierarchyIncomingCallsRequest={}));var Ere;(function(n){n.method="callHierarchy/outgoingCalls",n.messageDirection=nc.MessageDirection.clientToServer,n.type=new nc.ProtocolRequestType(n.method)})(Ere=Wr.CallHierarchyOutgoingCallsRequest||(Wr.CallHierarchyOutgoingCallsRequest={}))});var _Y=w(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.SemanticTokensRefreshRequest=bi.SemanticTokensRangeRequest=bi.SemanticTokensDeltaRequest=bi.SemanticTokensRequest=bi.SemanticTokensRegistrationType=bi.TokenFormat=void 0;var ts=Vt(),Ire;(function(n){n.Relative="relative"})(Ire=bi.TokenFormat||(bi.TokenFormat={}));var Wy;(function(n){n.method="textDocument/semanticTokens",n.type=new ts.RegistrationType(n.method)})(Wy=bi.SemanticTokensRegistrationType||(bi.SemanticTokensRegistrationType={}));var Lre;(function(n){n.method="textDocument/semanticTokens/full",n.messageDirection=ts.MessageDirection.clientToServer,n.type=new ts.ProtocolRequestType(n.method),n.registrationMethod=Wy.method})(Lre=bi.SemanticTokensRequest||(bi.SemanticTokensRequest={}));var Fre;(function(n){n.method="textDocument/semanticTokens/full/delta",n.messageDirection=ts.MessageDirection.clientToServer,n.type=new ts.ProtocolRequestType(n.method),n.registrationMethod=Wy.method})(Fre=bi.SemanticTokensDeltaRequest||(bi.SemanticTokensDeltaRequest={}));var Mre;(function(n){n.method="textDocument/semanticTokens/range",n.messageDirection=ts.MessageDirection.clientToServer,n.type=new ts.ProtocolRequestType(n.method),n.registrationMethod=Wy.method})(Mre=bi.SemanticTokensRangeRequest||(bi.SemanticTokensRangeRequest={}));var jre;(function(n){n.method="workspace/semanticTokens/refresh",n.messageDirection=ts.MessageDirection.clientToServer,n.type=new ts.ProtocolRequestType0(n.method)})(jre=bi.SemanticTokensRefreshRequest||(bi.SemanticTokensRefreshRequest={}))});var IY=w(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});sg.ShowDocumentRequest=void 0;var EY=Vt(),Ore;(function(n){n.method="window/showDocument",n.messageDirection=EY.MessageDirection.serverToClient,n.type=new EY.ProtocolRequestType(n.method)})(Ore=sg.ShowDocumentRequest||(sg.ShowDocumentRequest={}))});var FY=w(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});ag.LinkedEditingRangeRequest=void 0;var LY=Vt(),Are;(function(n){n.method="textDocument/linkedEditingRange",n.messageDirection=LY.MessageDirection.clientToServer,n.type=new LY.ProtocolRequestType(n.method)})(Are=ag.LinkedEditingRangeRequest||(ag.LinkedEditingRangeRequest={}))});var MY=w(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.WillDeleteFilesRequest=ei.DidDeleteFilesNotification=ei.DidRenameFilesNotification=ei.WillRenameFilesRequest=ei.DidCreateFilesNotification=ei.WillCreateFilesRequest=ei.FileOperationPatternKind=void 0;var br=Vt(),Nre;(function(n){n.file="file",n.folder="folder"})(Nre=ei.FileOperationPatternKind||(ei.FileOperationPatternKind={}));var Hre;(function(n){n.method="workspace/willCreateFiles",n.messageDirection=br.MessageDirection.clientToServer,n.type=new br.ProtocolRequestType(n.method)})(Hre=ei.WillCreateFilesRequest||(ei.WillCreateFilesRequest={}));var Bre;(function(n){n.method="workspace/didCreateFiles",n.messageDirection=br.MessageDirection.clientToServer,n.type=new br.ProtocolNotificationType(n.method)})(Bre=ei.DidCreateFilesNotification||(ei.DidCreateFilesNotification={}));var qre;(function(n){n.method="workspace/willRenameFiles",n.messageDirection=br.MessageDirection.clientToServer,n.type=new br.ProtocolRequestType(n.method)})(qre=ei.WillRenameFilesRequest||(ei.WillRenameFilesRequest={}));var Wre;(function(n){n.method="workspace/didRenameFiles",n.messageDirection=br.MessageDirection.clientToServer,n.type=new br.ProtocolNotificationType(n.method)})(Wre=ei.DidRenameFilesNotification||(ei.DidRenameFilesNotification={}));var Yre;(function(n){n.method="workspace/didDeleteFiles",n.messageDirection=br.MessageDirection.clientToServer,n.type=new br.ProtocolNotificationType(n.method)})(Yre=ei.DidDeleteFilesNotification||(ei.DidDeleteFilesNotification={}));var Zre;(function(n){n.method="workspace/willDeleteFiles",n.messageDirection=br.MessageDirection.clientToServer,n.type=new br.ProtocolRequestType(n.method)})(Zre=ei.WillDeleteFilesRequest||(ei.WillDeleteFilesRequest={}))});var OY=w(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.MonikerRequest=Yr.MonikerKind=Yr.UniquenessLevel=void 0;var jY=Vt(),Jre;(function(n){n.document="document",n.project="project",n.group="group",n.scheme="scheme",n.global="global"})(Jre=Yr.UniquenessLevel||(Yr.UniquenessLevel={}));var $re;(function(n){n.$import="import",n.$export="export",n.local="local"})($re=Yr.MonikerKind||(Yr.MonikerKind={}));var Ure;(function(n){n.method="textDocument/moniker",n.messageDirection=jY.MessageDirection.clientToServer,n.type=new jY.ProtocolRequestType(n.method)})(Ure=Yr.MonikerRequest||(Yr.MonikerRequest={}))});var AY=w(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.TypeHierarchySubtypesRequest=Zr.TypeHierarchySupertypesRequest=Zr.TypeHierarchyPrepareRequest=void 0;var rc=Vt(),Xre;(function(n){n.method="textDocument/prepareTypeHierarchy",n.messageDirection=rc.MessageDirection.clientToServer,n.type=new rc.ProtocolRequestType(n.method)})(Xre=Zr.TypeHierarchyPrepareRequest||(Zr.TypeHierarchyPrepareRequest={}));var Gre;(function(n){n.method="typeHierarchy/supertypes",n.messageDirection=rc.MessageDirection.clientToServer,n.type=new rc.ProtocolRequestType(n.method)})(Gre=Zr.TypeHierarchySupertypesRequest||(Zr.TypeHierarchySupertypesRequest={}));var zre;(function(n){n.method="typeHierarchy/subtypes",n.messageDirection=rc.MessageDirection.clientToServer,n.type=new rc.ProtocolRequestType(n.method)})(zre=Zr.TypeHierarchySubtypesRequest||(Zr.TypeHierarchySubtypesRequest={}))});var NY=w(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.InlineValueRefreshRequest=Gs.InlineValueRequest=void 0;var Yy=Vt(),Kre;(function(n){n.method="textDocument/inlineValue",n.messageDirection=Yy.MessageDirection.clientToServer,n.type=new Yy.ProtocolRequestType(n.method)})(Kre=Gs.InlineValueRequest||(Gs.InlineValueRequest={}));var Qre;(function(n){n.method="workspace/inlineValue/refresh",n.messageDirection=Yy.MessageDirection.clientToServer,n.type=new Yy.ProtocolRequestType0(n.method)})(Qre=Gs.InlineValueRefreshRequest||(Gs.InlineValueRefreshRequest={}))});var HY=w(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.InlayHintRefreshRequest=Jr.InlayHintResolveRequest=Jr.InlayHintRequest=void 0;var oc=Vt(),Vre;(function(n){n.method="textDocument/inlayHint",n.messageDirection=oc.MessageDirection.clientToServer,n.type=new oc.ProtocolRequestType(n.method)})(Vre=Jr.InlayHintRequest||(Jr.InlayHintRequest={}));var eoe;(function(n){n.method="inlayHint/resolve",n.messageDirection=oc.MessageDirection.clientToServer,n.type=new oc.ProtocolRequestType(n.method)})(eoe=Jr.InlayHintResolveRequest||(Jr.InlayHintResolveRequest={}));var toe;(function(n){n.method="workspace/inlayHint/refresh",n.messageDirection=oc.MessageDirection.clientToServer,n.type=new oc.ProtocolRequestType0(n.method)})(toe=Jr.InlayHintRefreshRequest||(Jr.InlayHintRefreshRequest={}))});var qY=w(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.DiagnosticRefreshRequest=Ui.WorkspaceDiagnosticRequest=Ui.DocumentDiagnosticRequest=Ui.DocumentDiagnosticReportKind=Ui.DiagnosticServerCancellationData=void 0;var BY=ul(),ioe=Ny(),sc=Vt(),noe;(function(n){function e(t){let i=t;return i&&ioe.boolean(i.retriggerRequest)}n.is=e})(noe=Ui.DiagnosticServerCancellationData||(Ui.DiagnosticServerCancellationData={}));var roe;(function(n){n.Full="full",n.Unchanged="unchanged"})(roe=Ui.DocumentDiagnosticReportKind||(Ui.DocumentDiagnosticReportKind={}));var ooe;(function(n){n.method="textDocument/diagnostic",n.messageDirection=sc.MessageDirection.clientToServer,n.type=new sc.ProtocolRequestType(n.method),n.partialResult=new BY.ProgressType})(ooe=Ui.DocumentDiagnosticRequest||(Ui.DocumentDiagnosticRequest={}));var soe;(function(n){n.method="workspace/diagnostic",n.messageDirection=sc.MessageDirection.clientToServer,n.type=new sc.ProtocolRequestType(n.method),n.partialResult=new BY.ProgressType})(soe=Ui.WorkspaceDiagnosticRequest||(Ui.WorkspaceDiagnosticRequest={}));var aoe;(function(n){n.method="workspace/diagnostic/refresh",n.messageDirection=sc.MessageDirection.clientToServer,n.type=new sc.ProtocolRequestType0(n.method)})(aoe=Ui.DiagnosticRefreshRequest||(Ui.DiagnosticRefreshRequest={}))});var ZY=w(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.DidCloseNotebookDocumentNotification=gt.DidSaveNotebookDocumentNotification=gt.DidChangeNotebookDocumentNotification=gt.NotebookCellArrayChange=gt.DidOpenNotebookDocumentNotification=gt.NotebookDocumentSyncRegistrationType=gt.NotebookDocument=gt.NotebookCell=gt.ExecutionSummary=gt.NotebookCellKind=void 0;var lg=(ae(),No(Ay)),$r=Ny(),fo=Vt(),WY;(function(n){n.Markup=1,n.Code=2;function e(t){return t===1||t===2}n.is=e})(WY=gt.NotebookCellKind||(gt.NotebookCellKind={}));var YY;(function(n){function e(r,o){let s={executionOrder:r};return(o===!0||o===!1)&&(s.success=o),s}n.create=e;function t(r){let o=r;return $r.objectLiteral(o)&&lg.uinteger.is(o.executionOrder)&&(o.success===void 0||$r.boolean(o.success))}n.is=t;function i(r,o){return r===o?!0:r==null||o===null||o===void 0?!1:r.executionOrder===o.executionOrder&&r.success===o.success}n.equals=i})(YY=gt.ExecutionSummary||(gt.ExecutionSummary={}));var Ck;(function(n){function e(o,s){return{kind:o,document:s}}n.create=e;function t(o){let s=o;return $r.objectLiteral(s)&&WY.is(s.kind)&&lg.DocumentUri.is(s.document)&&(s.metadata===void 0||$r.objectLiteral(s.metadata))}n.is=t;function i(o,s){let a=new Set;return o.document!==s.document&&a.add("document"),o.kind!==s.kind&&a.add("kind"),o.executionSummary!==s.executionSummary&&a.add("executionSummary"),(o.metadata!==void 0||s.metadata!==void 0)&&!r(o.metadata,s.metadata)&&a.add("metadata"),(o.executionSummary!==void 0||s.executionSummary!==void 0)&&!YY.equals(o.executionSummary,s.executionSummary)&&a.add("executionSummary"),a}n.diff=i;function r(o,s){if(o===s)return!0;if(o==null||s===null||s===void 0||typeof o!=typeof s||typeof o!="object")return!1;let a=Array.isArray(o),l=Array.isArray(s);if(a!==l)return!1;if(a&&l){if(o.length!==s.length)return!1;for(let u=0;u{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.WorkspaceSymbolRequest=S.CodeActionResolveRequest=S.CodeActionRequest=S.DocumentSymbolRequest=S.DocumentHighlightRequest=S.ReferencesRequest=S.DefinitionRequest=S.SignatureHelpRequest=S.SignatureHelpTriggerKind=S.HoverRequest=S.CompletionResolveRequest=S.CompletionRequest=S.CompletionTriggerKind=S.PublishDiagnosticsNotification=S.WatchKind=S.RelativePattern=S.FileChangeType=S.DidChangeWatchedFilesNotification=S.WillSaveTextDocumentWaitUntilRequest=S.WillSaveTextDocumentNotification=S.TextDocumentSaveReason=S.DidSaveTextDocumentNotification=S.DidCloseTextDocumentNotification=S.DidChangeTextDocumentNotification=S.TextDocumentContentChangeEvent=S.DidOpenTextDocumentNotification=S.TextDocumentSyncKind=S.TelemetryEventNotification=S.LogMessageNotification=S.ShowMessageRequest=S.ShowMessageNotification=S.MessageType=S.DidChangeConfigurationNotification=S.ExitNotification=S.ShutdownRequest=S.InitializedNotification=S.InitializeErrorCodes=S.InitializeRequest=S.WorkDoneProgressOptions=S.TextDocumentRegistrationOptions=S.StaticRegistrationOptions=S.PositionEncodingKind=S.FailureHandlingKind=S.ResourceOperationKind=S.UnregistrationRequest=S.RegistrationRequest=S.DocumentSelector=S.NotebookCellTextDocumentFilter=S.NotebookDocumentFilter=S.TextDocumentFilter=void 0;S.TypeHierarchySubtypesRequest=S.TypeHierarchyPrepareRequest=S.MonikerRequest=S.MonikerKind=S.UniquenessLevel=S.WillDeleteFilesRequest=S.DidDeleteFilesNotification=S.WillRenameFilesRequest=S.DidRenameFilesNotification=S.WillCreateFilesRequest=S.DidCreateFilesNotification=S.FileOperationPatternKind=S.LinkedEditingRangeRequest=S.ShowDocumentRequest=S.SemanticTokensRegistrationType=S.SemanticTokensRefreshRequest=S.SemanticTokensRangeRequest=S.SemanticTokensDeltaRequest=S.SemanticTokensRequest=S.TokenFormat=S.CallHierarchyPrepareRequest=S.CallHierarchyOutgoingCallsRequest=S.CallHierarchyIncomingCallsRequest=S.WorkDoneProgressCancelNotification=S.WorkDoneProgressCreateRequest=S.WorkDoneProgress=S.SelectionRangeRequest=S.DeclarationRequest=S.FoldingRangeRequest=S.ColorPresentationRequest=S.DocumentColorRequest=S.ConfigurationRequest=S.DidChangeWorkspaceFoldersNotification=S.WorkspaceFoldersRequest=S.TypeDefinitionRequest=S.ImplementationRequest=S.ApplyWorkspaceEditRequest=S.ExecuteCommandRequest=S.PrepareRenameRequest=S.RenameRequest=S.PrepareSupportDefaultBehavior=S.DocumentOnTypeFormattingRequest=S.DocumentRangeFormattingRequest=S.DocumentFormattingRequest=S.DocumentLinkResolveRequest=S.DocumentLinkRequest=S.CodeLensRefreshRequest=S.CodeLensResolveRequest=S.CodeLensRequest=S.WorkspaceSymbolResolveRequest=void 0;S.DidCloseNotebookDocumentNotification=S.DidSaveNotebookDocumentNotification=S.DidChangeNotebookDocumentNotification=S.NotebookCellArrayChange=S.DidOpenNotebookDocumentNotification=S.NotebookDocumentSyncRegistrationType=S.NotebookDocument=S.NotebookCell=S.ExecutionSummary=S.NotebookCellKind=S.DiagnosticRefreshRequest=S.WorkspaceDiagnosticRequest=S.DocumentDiagnosticRequest=S.DocumentDiagnosticReportKind=S.DiagnosticServerCancellationData=S.InlayHintRefreshRequest=S.InlayHintResolveRequest=S.InlayHintRequest=S.InlineValueRefreshRequest=S.InlineValueRequest=S.TypeHierarchySupertypesRequest=void 0;var ne=Vt(),JY=(ae(),No(Ay)),Xi=Ny(),poe=pY();Object.defineProperty(S,"ImplementationRequest",{enumerable:!0,get:function(){return poe.ImplementationRequest}});var foe=mY();Object.defineProperty(S,"TypeDefinitionRequest",{enumerable:!0,get:function(){return foe.TypeDefinitionRequest}});var $Y=bY();Object.defineProperty(S,"WorkspaceFoldersRequest",{enumerable:!0,get:function(){return $Y.WorkspaceFoldersRequest}});Object.defineProperty(S,"DidChangeWorkspaceFoldersNotification",{enumerable:!0,get:function(){return $Y.DidChangeWorkspaceFoldersNotification}});var moe=vY();Object.defineProperty(S,"ConfigurationRequest",{enumerable:!0,get:function(){return moe.ConfigurationRequest}});var UY=wY();Object.defineProperty(S,"DocumentColorRequest",{enumerable:!0,get:function(){return UY.DocumentColorRequest}});Object.defineProperty(S,"ColorPresentationRequest",{enumerable:!0,get:function(){return UY.ColorPresentationRequest}});var boe=CY();Object.defineProperty(S,"FoldingRangeRequest",{enumerable:!0,get:function(){return boe.FoldingRangeRequest}});var yoe=DY();Object.defineProperty(S,"DeclarationRequest",{enumerable:!0,get:function(){return yoe.DeclarationRequest}});var voe=kY();Object.defineProperty(S,"SelectionRangeRequest",{enumerable:!0,get:function(){return voe.SelectionRangeRequest}});var Sk=PY();Object.defineProperty(S,"WorkDoneProgress",{enumerable:!0,get:function(){return Sk.WorkDoneProgress}});Object.defineProperty(S,"WorkDoneProgressCreateRequest",{enumerable:!0,get:function(){return Sk.WorkDoneProgressCreateRequest}});Object.defineProperty(S,"WorkDoneProgressCancelNotification",{enumerable:!0,get:function(){return Sk.WorkDoneProgressCancelNotification}});var Dk=RY();Object.defineProperty(S,"CallHierarchyIncomingCallsRequest",{enumerable:!0,get:function(){return Dk.CallHierarchyIncomingCallsRequest}});Object.defineProperty(S,"CallHierarchyOutgoingCallsRequest",{enumerable:!0,get:function(){return Dk.CallHierarchyOutgoingCallsRequest}});Object.defineProperty(S,"CallHierarchyPrepareRequest",{enumerable:!0,get:function(){return Dk.CallHierarchyPrepareRequest}});var ac=_Y();Object.defineProperty(S,"TokenFormat",{enumerable:!0,get:function(){return ac.TokenFormat}});Object.defineProperty(S,"SemanticTokensRequest",{enumerable:!0,get:function(){return ac.SemanticTokensRequest}});Object.defineProperty(S,"SemanticTokensDeltaRequest",{enumerable:!0,get:function(){return ac.SemanticTokensDeltaRequest}});Object.defineProperty(S,"SemanticTokensRangeRequest",{enumerable:!0,get:function(){return ac.SemanticTokensRangeRequest}});Object.defineProperty(S,"SemanticTokensRefreshRequest",{enumerable:!0,get:function(){return ac.SemanticTokensRefreshRequest}});Object.defineProperty(S,"SemanticTokensRegistrationType",{enumerable:!0,get:function(){return ac.SemanticTokensRegistrationType}});var woe=IY();Object.defineProperty(S,"ShowDocumentRequest",{enumerable:!0,get:function(){return woe.ShowDocumentRequest}});var xoe=FY();Object.defineProperty(S,"LinkedEditingRangeRequest",{enumerable:!0,get:function(){return xoe.LinkedEditingRangeRequest}});var fl=MY();Object.defineProperty(S,"FileOperationPatternKind",{enumerable:!0,get:function(){return fl.FileOperationPatternKind}});Object.defineProperty(S,"DidCreateFilesNotification",{enumerable:!0,get:function(){return fl.DidCreateFilesNotification}});Object.defineProperty(S,"WillCreateFilesRequest",{enumerable:!0,get:function(){return fl.WillCreateFilesRequest}});Object.defineProperty(S,"DidRenameFilesNotification",{enumerable:!0,get:function(){return fl.DidRenameFilesNotification}});Object.defineProperty(S,"WillRenameFilesRequest",{enumerable:!0,get:function(){return fl.WillRenameFilesRequest}});Object.defineProperty(S,"DidDeleteFilesNotification",{enumerable:!0,get:function(){return fl.DidDeleteFilesNotification}});Object.defineProperty(S,"WillDeleteFilesRequest",{enumerable:!0,get:function(){return fl.WillDeleteFilesRequest}});var Tk=OY();Object.defineProperty(S,"UniquenessLevel",{enumerable:!0,get:function(){return Tk.UniquenessLevel}});Object.defineProperty(S,"MonikerKind",{enumerable:!0,get:function(){return Tk.MonikerKind}});Object.defineProperty(S,"MonikerRequest",{enumerable:!0,get:function(){return Tk.MonikerRequest}});var kk=AY();Object.defineProperty(S,"TypeHierarchyPrepareRequest",{enumerable:!0,get:function(){return kk.TypeHierarchyPrepareRequest}});Object.defineProperty(S,"TypeHierarchySubtypesRequest",{enumerable:!0,get:function(){return kk.TypeHierarchySubtypesRequest}});Object.defineProperty(S,"TypeHierarchySupertypesRequest",{enumerable:!0,get:function(){return kk.TypeHierarchySupertypesRequest}});var XY=NY();Object.defineProperty(S,"InlineValueRequest",{enumerable:!0,get:function(){return XY.InlineValueRequest}});Object.defineProperty(S,"InlineValueRefreshRequest",{enumerable:!0,get:function(){return XY.InlineValueRefreshRequest}});var Pk=HY();Object.defineProperty(S,"InlayHintRequest",{enumerable:!0,get:function(){return Pk.InlayHintRequest}});Object.defineProperty(S,"InlayHintResolveRequest",{enumerable:!0,get:function(){return Pk.InlayHintResolveRequest}});Object.defineProperty(S,"InlayHintRefreshRequest",{enumerable:!0,get:function(){return Pk.InlayHintRefreshRequest}});var cg=qY();Object.defineProperty(S,"DiagnosticServerCancellationData",{enumerable:!0,get:function(){return cg.DiagnosticServerCancellationData}});Object.defineProperty(S,"DocumentDiagnosticReportKind",{enumerable:!0,get:function(){return cg.DocumentDiagnosticReportKind}});Object.defineProperty(S,"DocumentDiagnosticRequest",{enumerable:!0,get:function(){return cg.DocumentDiagnosticRequest}});Object.defineProperty(S,"WorkspaceDiagnosticRequest",{enumerable:!0,get:function(){return cg.WorkspaceDiagnosticRequest}});Object.defineProperty(S,"DiagnosticRefreshRequest",{enumerable:!0,get:function(){return cg.DiagnosticRefreshRequest}});var mo=ZY();Object.defineProperty(S,"NotebookCellKind",{enumerable:!0,get:function(){return mo.NotebookCellKind}});Object.defineProperty(S,"ExecutionSummary",{enumerable:!0,get:function(){return mo.ExecutionSummary}});Object.defineProperty(S,"NotebookCell",{enumerable:!0,get:function(){return mo.NotebookCell}});Object.defineProperty(S,"NotebookDocument",{enumerable:!0,get:function(){return mo.NotebookDocument}});Object.defineProperty(S,"NotebookDocumentSyncRegistrationType",{enumerable:!0,get:function(){return mo.NotebookDocumentSyncRegistrationType}});Object.defineProperty(S,"DidOpenNotebookDocumentNotification",{enumerable:!0,get:function(){return mo.DidOpenNotebookDocumentNotification}});Object.defineProperty(S,"NotebookCellArrayChange",{enumerable:!0,get:function(){return mo.NotebookCellArrayChange}});Object.defineProperty(S,"DidChangeNotebookDocumentNotification",{enumerable:!0,get:function(){return mo.DidChangeNotebookDocumentNotification}});Object.defineProperty(S,"DidSaveNotebookDocumentNotification",{enumerable:!0,get:function(){return mo.DidSaveNotebookDocumentNotification}});Object.defineProperty(S,"DidCloseNotebookDocumentNotification",{enumerable:!0,get:function(){return mo.DidCloseNotebookDocumentNotification}});var GY;(function(n){function e(t){let i=t;return Xi.string(i.language)||Xi.string(i.scheme)||Xi.string(i.pattern)}n.is=e})(GY=S.TextDocumentFilter||(S.TextDocumentFilter={}));var zY;(function(n){function e(t){let i=t;return Xi.objectLiteral(i)&&(Xi.string(i.notebookType)||Xi.string(i.scheme)||Xi.string(i.pattern))}n.is=e})(zY=S.NotebookDocumentFilter||(S.NotebookDocumentFilter={}));var KY;(function(n){function e(t){let i=t;return Xi.objectLiteral(i)&&(Xi.string(i.notebook)||zY.is(i.notebook))&&(i.language===void 0||Xi.string(i.language))}n.is=e})(KY=S.NotebookCellTextDocumentFilter||(S.NotebookCellTextDocumentFilter={}));var QY;(function(n){function e(t){if(!Array.isArray(t))return!1;for(let i of t)if(!Xi.string(i)&&!GY.is(i)&&!KY.is(i))return!1;return!0}n.is=e})(QY=S.DocumentSelector||(S.DocumentSelector={}));var Coe;(function(n){n.method="client/registerCapability",n.messageDirection=ne.MessageDirection.serverToClient,n.type=new ne.ProtocolRequestType(n.method)})(Coe=S.RegistrationRequest||(S.RegistrationRequest={}));var Soe;(function(n){n.method="client/unregisterCapability",n.messageDirection=ne.MessageDirection.serverToClient,n.type=new ne.ProtocolRequestType(n.method)})(Soe=S.UnregistrationRequest||(S.UnregistrationRequest={}));var Doe;(function(n){n.Create="create",n.Rename="rename",n.Delete="delete"})(Doe=S.ResourceOperationKind||(S.ResourceOperationKind={}));var Toe;(function(n){n.Abort="abort",n.Transactional="transactional",n.TextOnlyTransactional="textOnlyTransactional",n.Undo="undo"})(Toe=S.FailureHandlingKind||(S.FailureHandlingKind={}));var koe;(function(n){n.UTF8="utf-8",n.UTF16="utf-16",n.UTF32="utf-32"})(koe=S.PositionEncodingKind||(S.PositionEncodingKind={}));var Poe;(function(n){function e(t){let i=t;return i&&Xi.string(i.id)&&i.id.length>0}n.hasId=e})(Poe=S.StaticRegistrationOptions||(S.StaticRegistrationOptions={}));var Roe;(function(n){function e(t){let i=t;return i&&(i.documentSelector===null||QY.is(i.documentSelector))}n.is=e})(Roe=S.TextDocumentRegistrationOptions||(S.TextDocumentRegistrationOptions={}));var _oe;(function(n){function e(i){let r=i;return Xi.objectLiteral(r)&&(r.workDoneProgress===void 0||Xi.boolean(r.workDoneProgress))}n.is=e;function t(i){let r=i;return r&&Xi.boolean(r.workDoneProgress)}n.hasWorkDoneProgress=t})(_oe=S.WorkDoneProgressOptions||(S.WorkDoneProgressOptions={}));var Eoe;(function(n){n.method="initialize",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(Eoe=S.InitializeRequest||(S.InitializeRequest={}));var Ioe;(function(n){n.unknownProtocolVersion=1})(Ioe=S.InitializeErrorCodes||(S.InitializeErrorCodes={}));var Loe;(function(n){n.method="initialized",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolNotificationType(n.method)})(Loe=S.InitializedNotification||(S.InitializedNotification={}));var Foe;(function(n){n.method="shutdown",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType0(n.method)})(Foe=S.ShutdownRequest||(S.ShutdownRequest={}));var Moe;(function(n){n.method="exit",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolNotificationType0(n.method)})(Moe=S.ExitNotification||(S.ExitNotification={}));var joe;(function(n){n.method="workspace/didChangeConfiguration",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolNotificationType(n.method)})(joe=S.DidChangeConfigurationNotification||(S.DidChangeConfigurationNotification={}));var Ooe;(function(n){n.Error=1,n.Warning=2,n.Info=3,n.Log=4})(Ooe=S.MessageType||(S.MessageType={}));var Aoe;(function(n){n.method="window/showMessage",n.messageDirection=ne.MessageDirection.serverToClient,n.type=new ne.ProtocolNotificationType(n.method)})(Aoe=S.ShowMessageNotification||(S.ShowMessageNotification={}));var Noe;(function(n){n.method="window/showMessageRequest",n.messageDirection=ne.MessageDirection.serverToClient,n.type=new ne.ProtocolRequestType(n.method)})(Noe=S.ShowMessageRequest||(S.ShowMessageRequest={}));var Hoe;(function(n){n.method="window/logMessage",n.messageDirection=ne.MessageDirection.serverToClient,n.type=new ne.ProtocolNotificationType(n.method)})(Hoe=S.LogMessageNotification||(S.LogMessageNotification={}));var Boe;(function(n){n.method="telemetry/event",n.messageDirection=ne.MessageDirection.serverToClient,n.type=new ne.ProtocolNotificationType(n.method)})(Boe=S.TelemetryEventNotification||(S.TelemetryEventNotification={}));var qoe;(function(n){n.None=0,n.Full=1,n.Incremental=2})(qoe=S.TextDocumentSyncKind||(S.TextDocumentSyncKind={}));var Woe;(function(n){n.method="textDocument/didOpen",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolNotificationType(n.method)})(Woe=S.DidOpenTextDocumentNotification||(S.DidOpenTextDocumentNotification={}));var Yoe;(function(n){function e(i){let r=i;return r!=null&&typeof r.text=="string"&&r.range!==void 0&&(r.rangeLength===void 0||typeof r.rangeLength=="number")}n.isIncremental=e;function t(i){let r=i;return r!=null&&typeof r.text=="string"&&r.range===void 0&&r.rangeLength===void 0}n.isFull=t})(Yoe=S.TextDocumentContentChangeEvent||(S.TextDocumentContentChangeEvent={}));var Zoe;(function(n){n.method="textDocument/didChange",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolNotificationType(n.method)})(Zoe=S.DidChangeTextDocumentNotification||(S.DidChangeTextDocumentNotification={}));var Joe;(function(n){n.method="textDocument/didClose",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolNotificationType(n.method)})(Joe=S.DidCloseTextDocumentNotification||(S.DidCloseTextDocumentNotification={}));var $oe;(function(n){n.method="textDocument/didSave",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolNotificationType(n.method)})($oe=S.DidSaveTextDocumentNotification||(S.DidSaveTextDocumentNotification={}));var Uoe;(function(n){n.Manual=1,n.AfterDelay=2,n.FocusOut=3})(Uoe=S.TextDocumentSaveReason||(S.TextDocumentSaveReason={}));var Xoe;(function(n){n.method="textDocument/willSave",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolNotificationType(n.method)})(Xoe=S.WillSaveTextDocumentNotification||(S.WillSaveTextDocumentNotification={}));var Goe;(function(n){n.method="textDocument/willSaveWaitUntil",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(Goe=S.WillSaveTextDocumentWaitUntilRequest||(S.WillSaveTextDocumentWaitUntilRequest={}));var zoe;(function(n){n.method="workspace/didChangeWatchedFiles",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolNotificationType(n.method)})(zoe=S.DidChangeWatchedFilesNotification||(S.DidChangeWatchedFilesNotification={}));var Koe;(function(n){n.Created=1,n.Changed=2,n.Deleted=3})(Koe=S.FileChangeType||(S.FileChangeType={}));var Qoe;(function(n){function e(t){let i=t;return Xi.objectLiteral(i)&&(JY.URI.is(i.baseUri)||JY.WorkspaceFolder.is(i.baseUri))&&Xi.string(i.pattern)}n.is=e})(Qoe=S.RelativePattern||(S.RelativePattern={}));var Voe;(function(n){n.Create=1,n.Change=2,n.Delete=4})(Voe=S.WatchKind||(S.WatchKind={}));var ese;(function(n){n.method="textDocument/publishDiagnostics",n.messageDirection=ne.MessageDirection.serverToClient,n.type=new ne.ProtocolNotificationType(n.method)})(ese=S.PublishDiagnosticsNotification||(S.PublishDiagnosticsNotification={}));var tse;(function(n){n.Invoked=1,n.TriggerCharacter=2,n.TriggerForIncompleteCompletions=3})(tse=S.CompletionTriggerKind||(S.CompletionTriggerKind={}));var ise;(function(n){n.method="textDocument/completion",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(ise=S.CompletionRequest||(S.CompletionRequest={}));var nse;(function(n){n.method="completionItem/resolve",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(nse=S.CompletionResolveRequest||(S.CompletionResolveRequest={}));var rse;(function(n){n.method="textDocument/hover",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(rse=S.HoverRequest||(S.HoverRequest={}));var ose;(function(n){n.Invoked=1,n.TriggerCharacter=2,n.ContentChange=3})(ose=S.SignatureHelpTriggerKind||(S.SignatureHelpTriggerKind={}));var sse;(function(n){n.method="textDocument/signatureHelp",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(sse=S.SignatureHelpRequest||(S.SignatureHelpRequest={}));var ase;(function(n){n.method="textDocument/definition",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(ase=S.DefinitionRequest||(S.DefinitionRequest={}));var lse;(function(n){n.method="textDocument/references",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(lse=S.ReferencesRequest||(S.ReferencesRequest={}));var use;(function(n){n.method="textDocument/documentHighlight",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(use=S.DocumentHighlightRequest||(S.DocumentHighlightRequest={}));var cse;(function(n){n.method="textDocument/documentSymbol",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(cse=S.DocumentSymbolRequest||(S.DocumentSymbolRequest={}));var dse;(function(n){n.method="textDocument/codeAction",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(dse=S.CodeActionRequest||(S.CodeActionRequest={}));var hse;(function(n){n.method="codeAction/resolve",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(hse=S.CodeActionResolveRequest||(S.CodeActionResolveRequest={}));var gse;(function(n){n.method="workspace/symbol",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(gse=S.WorkspaceSymbolRequest||(S.WorkspaceSymbolRequest={}));var pse;(function(n){n.method="workspaceSymbol/resolve",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(pse=S.WorkspaceSymbolResolveRequest||(S.WorkspaceSymbolResolveRequest={}));var fse;(function(n){n.method="textDocument/codeLens",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(fse=S.CodeLensRequest||(S.CodeLensRequest={}));var mse;(function(n){n.method="codeLens/resolve",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(mse=S.CodeLensResolveRequest||(S.CodeLensResolveRequest={}));var bse;(function(n){n.method="workspace/codeLens/refresh",n.messageDirection=ne.MessageDirection.serverToClient,n.type=new ne.ProtocolRequestType0(n.method)})(bse=S.CodeLensRefreshRequest||(S.CodeLensRefreshRequest={}));var yse;(function(n){n.method="textDocument/documentLink",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(yse=S.DocumentLinkRequest||(S.DocumentLinkRequest={}));var vse;(function(n){n.method="documentLink/resolve",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(vse=S.DocumentLinkResolveRequest||(S.DocumentLinkResolveRequest={}));var wse;(function(n){n.method="textDocument/formatting",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(wse=S.DocumentFormattingRequest||(S.DocumentFormattingRequest={}));var xse;(function(n){n.method="textDocument/rangeFormatting",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(xse=S.DocumentRangeFormattingRequest||(S.DocumentRangeFormattingRequest={}));var Cse;(function(n){n.method="textDocument/onTypeFormatting",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(Cse=S.DocumentOnTypeFormattingRequest||(S.DocumentOnTypeFormattingRequest={}));var Sse;(function(n){n.Identifier=1})(Sse=S.PrepareSupportDefaultBehavior||(S.PrepareSupportDefaultBehavior={}));var Dse;(function(n){n.method="textDocument/rename",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(Dse=S.RenameRequest||(S.RenameRequest={}));var Tse;(function(n){n.method="textDocument/prepareRename",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(Tse=S.PrepareRenameRequest||(S.PrepareRenameRequest={}));var kse;(function(n){n.method="workspace/executeCommand",n.messageDirection=ne.MessageDirection.clientToServer,n.type=new ne.ProtocolRequestType(n.method)})(kse=S.ExecuteCommandRequest||(S.ExecuteCommandRequest={}));var Pse;(function(n){n.method="workspace/applyEdit",n.messageDirection=ne.MessageDirection.serverToClient,n.type=new ne.ProtocolRequestType("workspace/applyEdit")})(Pse=S.ApplyWorkspaceEditRequest||(S.ApplyWorkspaceEditRequest={}))});var tZ=w(Zy=>{"use strict";Object.defineProperty(Zy,"__esModule",{value:!0});Zy.createProtocolConnection=void 0;var eZ=ul();function Rse(n,e,t,i){return eZ.ConnectionStrategy.is(i)&&(i={connectionStrategy:i}),(0,eZ.createMessageConnection)(n,e,t,i)}Zy.createProtocolConnection=Rse});var iZ=w(vn=>{"use strict";var _se=vn&&vn.__createBinding||(Object.create?function(n,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,i,r)}:function(n,e,t,i){i===void 0&&(i=t),n[i]=e[t]}),Jy=vn&&vn.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&_se(e,n,t)};Object.defineProperty(vn,"__esModule",{value:!0});vn.LSPErrorCodes=vn.createProtocolConnection=void 0;Jy(ul(),vn);Jy((ae(),No(Ay)),vn);Jy(Vt(),vn);Jy(VY(),vn);var Ese=tZ();Object.defineProperty(vn,"createProtocolConnection",{enumerable:!0,get:function(){return Ese.createProtocolConnection}});var Ise;(function(n){n.lspReservedErrorRangeStart=-32899,n.RequestFailed=-32803,n.ServerCancelled=-32802,n.ContentModified=-32801,n.RequestCancelled=-32800,n.lspReservedErrorRangeEnd=-32800})(Ise=vn.LSPErrorCodes||(vn.LSPErrorCodes={}))});var rZ=w(bo=>{"use strict";var Lse=bo&&bo.__createBinding||(Object.create?function(n,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,i,r)}:function(n,e,t,i){i===void 0&&(i=t),n[i]=e[t]}),nZ=bo&&bo.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Lse(e,n,t)};Object.defineProperty(bo,"__esModule",{value:!0});bo.createProtocolConnection=void 0;var Fse=pk();nZ(pk(),bo);nZ(iZ(),bo);function Mse(n,e,t,i){return(0,Fse.createMessageConnection)(n,e,t,i)}bo.createProtocolConnection=Mse});var sZ=w((yDe,oZ)=>{"use strict";oZ.exports=rZ()});var p,U=D(()=>{"use strict";p=Lr(sZ())});function le(n){return Array.isArray(n)?n:n==null?[]:[n]}function re(n){return!Array.isArray(n)||n.length===0}function jse(n,e){return ne[1]?-1:0}function dg(n,e){let t=0,i=e.length-1;for(;t<=i;){let r=(t+i)/2|0,o=jse(n,e[r]);if(o<0)t=r+1;else if(o>0)i=r-1;else return!0}return!1}function aZ(n,e,t){return Ose(n.length,i=>t(n[i],e))}function Ose(n,e){let t=0,i=n-1;for(;t<=i;){let r=(t+i)/2|0,o=e(r);if(o<0)t=r+1;else if(o>0)i=r-1;else return r}return-(t+1)}function hg(n,e){for(let t of e)if(n.includes(t))return!0;return!1}function $y(n,e){let t=[[],[]];for(let i of n)e(i)?t[0].push(i):t[1].push(i);return t}function lZ(n,e){let t=[[],[]];return n.forEach(i=>{e(i)?t[0].push(i):t[1].push(i)}),t}function yi(n,e){if(!e)return n.filter((i,r)=>n.indexOf(i)===r);let t=Object.create(null);return n.filter(i=>{let r=e(i);return t[r]?!1:(t[r]=!0,!0)})}var Re=D(()=>{"use strict"});var gg=D(()=>{"use strict"});function yr(n){return n instanceof Error?n.message:n.toString()}function uZ(n){let e=parseInt(n,10);return isNaN(e)?void 0:e}function oe(n){return n??""}function Ek(n){return global.Buffer.from(n).toString("base64")}function cZ(n){return dg(n,Bse)?!0:n===95||n===46||n===64}function dZ(n){return n>=127462&&n<=127487||n===8986||n===8987||n===9200||n===9203||n>=9728&&n<=10175||n===11088||n===11093||n>=127744&&n<=128591||n>=128640&&n<=128764||n>=128992&&n<=129008||n>=129280&&n<=129535||n>=129648&&n<=129782}function hZ(n,e){let t=[];for(let i=0;i=55296&&n<=56319}function Xy(n){return n>=56320&&n<=57343}function ue(n,e=0){if(e===0)return Buffer.byteLength(n,Hse);let t=0,i=0;for(let r of n){let o=r.codePointAt(0);i>=e&&(t+=Gy(o)),i+=o>=_k?2:1}return t}function nt(n,e){let t=0,i,r,o=Math.min(e,n.length);for(let s=0;s0?n[0].toUpperCase()+n.slice(1):""}function Ut(n,e){if(e==0)return 0;let t=0,i=0;for(let r of n){let o=r.codePointAt(0);if(o>=_k?(t+=2,i+=4):(t+=1,i+=Gy(o)),i>=e)break}return t}function Gy(n){return n=65&&n<=90||n>=97&&n<=122}function gZ(n,e){return e&&n.endsWith(` +`)?n.slice(0,-1).split(` +`):n.split(` +`)}function qse(n){for(let e=0,t=n.length;e=65&&i<=90)return!0}return!1}function Wse(n,e){if(n===e)return!0;let t=e.charCodeAt(0);return t>=65&&t<=90&&t+32===n.charCodeAt(0)}function pZ(n,e){if(n.length>e.length)return-1;if(n.length===0)return 0;if(!qse(n))return e.toLowerCase().indexOf(n);let t=n.length,i=0;for(let r=0;r0&&(r=r-i,i=0)}return-1}function zs(n,e){e=e??n.length;let t=new Uint8Array(e),i=!0,r;for(let o=0;o1&&(i=!1),t[o]=a,r=s}return o=>{if(o===0)return 0;if(i)return Math.min(o,e);let s=0;for(let a=0;a{"use strict";Re();gg();Ase=128,Nse=2048,_k=65536,Hse="utf8",Bse=[[48,57],[65,90],[97,122]]});function Zse(n){return!!(n instanceof Rt||n instanceof Error&&n.message.includes("transport disconnected"))}var fZ,Yse,Ik,_,Pe=D(()=>{"use strict";xe();te();Ii();Xe();Be();U();fe();fZ=Z("events"),Yse=["BufWritePre"],Ik=class{constructor(){this.handlers=new Map;this._bufnr=1;this._recentInserts=[];this._lastChange=0;this._insertMode=!1;this._pumAlignTop=!1;this._pumVisible=!1;this._completing=!1;this._requesting=!1;this._ready=!1;this.timeout=1e3}set requesting(e){this._requesting=e}get requesting(){return this._requesting}get ready(){return this._ready}set completing(e){this._completing=e,this._pumVisible=e}get completing(){return this._completing}get cursor(){return this._cursor??{bufnr:this._bufnr,col:1,lnum:1,insert:!1}}get bufnr(){return this._bufnr}get pumvisible(){return this._pumVisible}get pumAlignTop(){return this._pumAlignTop}get insertMode(){return this._insertMode}get lastChangeTs(){return this._lastChange}race(e,t){let i=[];return new Promise(r=>{if($t(t)){let o=setTimeout(()=>{W(i),r(void 0)},t);i.push(p.Disposable.create(()=>{clearTimeout(o)}))}else p.CancellationToken.is(t)&&t.onCancellationRequested(()=>{W(i),r(void 0)},null,i);e.forEach(o=>{this.on(o,(...s)=>{W(i),r({name:o,args:s})},null,i)})})}async fire(e,t){if(e==="ready")this._ready=!0;else if(e=="InsertEnter")this._insertMode=!0;else if(e=="InsertLeave")this._last_pum_insert=void 0,this._insertMode=!1,this._pumVisible=!1,this._recentInserts=[];else if(e=="CursorHoldI"||e=="CursorMovedI")this._bufnr=t[0],this._insertMode||(this._insertMode=!0,this.fire("InsertEnter",[t[0]]));else if(e=="CursorHold"||e=="CursorMoved")this._bufnr=t[0],this._insertMode&&(this._insertMode=!1,this.fire("InsertLeave",[t[0]]));else if(e=="MenuPopupChanged")this._pumVisible=!0,this._pumAlignTop=t[1]>t[0].row;else if(e=="InsertCharPre")this._recentInserts.push([t[1],t[0]]);else if(e=="TextChanged")this._lastChange=Date.now();else if(e=="BufEnter")this._bufnr=t[0];else if(e=="TextChangedI"||e=="TextChangedP"){let r=t[1],o=Xt(r.line??"",0,r.col-1),s;if(this._last_pum_insert!=null&&this._last_pum_insert==o?(s=[],e="TextChangedP"):s=this._recentInserts.filter(a=>a[0]==t[0]),this._last_pum_insert=void 0,this._bufnr=t[0],this._recentInserts=[],this._lastChange=Date.now(),r.pre=o,this._cursor=Object.freeze({bufnr:t[0],lnum:r.lnum,col:r.col,insert:!0}),s.length&&o.length){let a=o.slice(-1);s.findIndex(l=>l[1]==a)!==-1&&(r.insertChar=a,process.nextTick(()=>{this.fire("TextInsert",[...t,a])}))}}else if(e=="PumInsert"){this._last_pum_insert=t[0];return}if(e=="CursorMoved"||e=="CursorMovedI"){t.push(this._recentInserts.length>0);let r={bufnr:t[0],lnum:t[1][0],col:t[1][1],insert:e=="CursorMovedI"};if(this._last_pum_insert&&ue(this._last_pum_insert)+1==r.col||this._cursor&&Me(this._cursor,r))return;this._cursor=r}let i=this.handlers.get(e);if(i!=null&&i.length){let r=i.slice(),o=Yse.includes(e);await Promise.allSettled(r.map(s=>(async()=>{let l;o&&(l=setTimeout(()=>{console.error(`Slow "${e}" handler detected`,s.stack),fZ.error(`Slow "${e}" handler detected`,s.stack)},this.timeout));try{await s(t)}catch(u){Zse(u)||fZ.error(`Error on event: ${e}`,u)}clearTimeout(l)})()))}}on(e,t,i,r){if(Array.isArray(e)){let o=r||[];for(let s of e)this.on(s,t,i,o);return p.Disposable.create(()=>{W(o)})}else{let o=this.handlers.get(e)||[],s=l=>new Promise((u,c)=>{try{Promise.resolve(t.apply(i??null,l)).then(()=>{u(void 0)},d=>{c(d)})}catch(d){c(d)}});Error.captureStackTrace(s),o.push(s),this.handlers.set(e,o);let a=p.Disposable.create(()=>{let l=o.indexOf(s);l!==-1&&o.splice(l,1)});return Array.isArray(r)&&r.push(a),a}}};_=new Ik});var mZ=w((LDe,Jse)=>{Jse.exports={name:"coc.nvim-master",version:"0.0.82",description:"LSP based intellisense engine for neovim & vim8.",main:"./build/index.js",engines:{node:">=14.14.0"},type:"commonjs",scripts:{lint:"eslint . --ext .ts --quiet","lint:typecheck":"tsc -p tsconfig.json",build:"node esbuild.js",test:"./node_modules/.bin/jest --forceExit","test-build":"./node_modules/.bin/jest --coverage --forceExit",prepare:"node esbuild.js"},repository:{type:"git",url:"git+https://github.com/neoclide/coc.nvim.git"},keywords:["complete","neovim"],author:"Qiming Zhao ",bugs:{url:"https://github.com/neoclide/coc.nvim/issues"},homepage:"https://github.com/neoclide/coc.nvim#readme",jest:{globals:{__TEST__:!0},projects:[""],watchman:!1,clearMocks:!0,globalSetup:"./jest.js",testEnvironment:"node",coveragePathIgnorePatterns:["/src/__tests__/*"],moduleFileExtensions:["ts","tsx","json","js"],transform:{"^.+\\.tsx?$":["@swc/jest"]},testRegex:"src/__tests__/.*\\.(test|spec)\\.ts$",coverageReporters:["text","lcov"],coverageDirectory:"./coverage/"},devDependencies:{"@swc/core":"^1.3.21","@swc/jest":"^0.2.23","@types/bser":"^2.0.1","@types/cli-table":"^0.3.0","@types/debounce":"^3.0.0","@types/fb-watchman":"^2.0.0","@types/follow-redirects":"^1.14.1","@types/glob":"^7.2.0","@types/jest":"^27.0.3","@types/marked":"^4.0.1","@types/minimatch":"^5.1.2","@types/mkdirp":"^1.0.1","@types/node":"14.14","@types/semver":"^7.3.4","@types/tar":"^4.0.5","@types/unidecode":"^0.1.1","@types/uuid":"^8.3.0","@types/which":"^1.3.2","@typescript-eslint/eslint-plugin":"^5.44.0","@typescript-eslint/parser":"^5.44.0",browserslist:"^4.21.4",bser:"^2.1.1",esbuild:"^0.15.13",eslint:"^8.28.0","eslint-plugin-jest":"^27.1.5","eslint-plugin-jsdoc":"^39.6.2",jest:"29.3.1",typescript:"^4.9.3","vscode-languageserver":"^8.0.2"},dependencies:{"@chemzqm/neovim":"^6.1.1","ansi-styles":"^5.0.0",bytes:"^3.1.0","caniuse-lite":"^1.0.30001431","cli-table":"^0.3.4","content-disposition":"^0.5.3",debounce:"^1.2.0","decompress-response":"^6.0.0","fast-diff":"^1.2.0","fb-watchman":"^2.0.1","follow-redirects":"^1.15.2",glob:"^7.2.0","http-proxy-agent":"^5.0.0","https-proxy-agent":"^5.0.0","jsonc-parser":"^3.0.0",marked:"^4.0.12",minimatch:"^5.1.0",semver:"^7.3.2","strip-ansi":"^6.0.0",tar:"^6.1.9",tslib:"^2.0.3",unidecode:"^0.1.8","unzip-stream":"^0.3.1",uuid:"^7.0.3","vscode-languageserver-protocol":"^3.17.2","vscode-languageserver-textdocument":"^1.0.5","vscode-languageserver-types":"^3.17.2","vscode-uri":"^3.0.3",which:"^2.0.2"}}});var bZ,ml,bl,vi,Lk,pg,fg,Fk,Gn,yZ,yo,vZ,Yt=D(()=>{"use strict";bZ=Lr(mZ());te();de();ml=128,bl=bZ.version,vi=process.env.VIM_NODE_RPC=="1",Lk=34,pg="CocFloating",fg="coc-settings.json",Fk=Ie(process.env.COC_VIMCONFIG,R.join(Pt.homedir(),".vim")),Gn=Ie(process.env.COC_DATA_HOME,R.join(Pt.homedir(),".config/coc")),yZ=R.join(R.normalize(Fk),fg),yo=pe(R.dirname(__dirname),R.resolve(__dirname,"../..")),vZ="watchman"});function bg(n,e=!1){let t=n.length,i=0,r="",o=0,s=16,a=0,l=0,u=0,c=0,d=0;function h(C,k){let T=0,j=0;for(;T=48&&N<=57)j=j*16+N-48;else if(N>=65&&N<=70)j=j*16+N-65+10;else if(N>=97&&N<=102)j=j*16+N-97+10;else break;i++,T++}return T=t){C+=n.substring(k,i),d=2;break}let T=n.charCodeAt(i);if(T===34){C+=n.substring(k,i),i++;break}if(T===92){if(C+=n.substring(k,i),i++,i>=t){d=2;break}switch(n.charCodeAt(i++)){case 34:C+='"';break;case 92:C+="\\";break;case 47:C+="/";break;case 98:C+="\b";break;case 102:C+="\f";break;case 110:C+=` +`;break;case 114:C+="\r";break;case 116:C+=" ";break;case 117:let N=h(4,!0);N>=0?C+=String.fromCharCode(N):d=4;break;default:d=5}k=i;continue}if(T>=0&&T<=31)if(mg(T)){C+=n.substring(k,i),d=2;break}else d=6;i++}return C}function b(){if(r="",d=0,o=i,l=a,c=u,i>=t)return o=t,s=17;let C=n.charCodeAt(i);if(Mk(C)){do i++,r+=String.fromCharCode(C),C=n.charCodeAt(i);while(Mk(C));return s=15}if(mg(C))return i++,r+=String.fromCharCode(C),C===13&&n.charCodeAt(i)===10&&(i++,r+=` +`),a++,u=i,s=14;switch(C){case 123:return i++,s=1;case 125:return i++,s=2;case 91:return i++,s=3;case 93:return i++,s=4;case 58:return i++,s=6;case 44:return i++,s=5;case 34:return i++,r=m(),s=10;case 47:let k=i-1;if(n.charCodeAt(i+1)===47){for(i+=2;i=12&&C<=15);return C}return{setPosition:g,getPosition:()=>i,scan:e?x:b,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>o,getTokenLength:()=>i-o,getTokenStartLine:()=>l,getTokenStartCharacter:()=>o-c,getTokenError:()=>d}}function Mk(n){return n===32||n===9}function mg(n){return n===10||n===13}function uc(n){return n>=48&&n<=57}var wZ,zy=D(()=>{"use strict";(function(n){n[n.lineFeed=10]="lineFeed",n[n.carriageReturn=13]="carriageReturn",n[n.space=32]="space",n[n._0=48]="_0",n[n._1=49]="_1",n[n._2=50]="_2",n[n._3=51]="_3",n[n._4=52]="_4",n[n._5=53]="_5",n[n._6=54]="_6",n[n._7=55]="_7",n[n._8=56]="_8",n[n._9=57]="_9",n[n.a=97]="a",n[n.b=98]="b",n[n.c=99]="c",n[n.d=100]="d",n[n.e=101]="e",n[n.f=102]="f",n[n.g=103]="g",n[n.h=104]="h",n[n.i=105]="i",n[n.j=106]="j",n[n.k=107]="k",n[n.l=108]="l",n[n.m=109]="m",n[n.n=110]="n",n[n.o=111]="o",n[n.p=112]="p",n[n.q=113]="q",n[n.r=114]="r",n[n.s=115]="s",n[n.t=116]="t",n[n.u=117]="u",n[n.v=118]="v",n[n.w=119]="w",n[n.x=120]="x",n[n.y=121]="y",n[n.z=122]="z",n[n.A=65]="A",n[n.B=66]="B",n[n.C=67]="C",n[n.D=68]="D",n[n.E=69]="E",n[n.F=70]="F",n[n.G=71]="G",n[n.H=72]="H",n[n.I=73]="I",n[n.J=74]="J",n[n.K=75]="K",n[n.L=76]="L",n[n.M=77]="M",n[n.N=78]="N",n[n.O=79]="O",n[n.P=80]="P",n[n.Q=81]="Q",n[n.R=82]="R",n[n.S=83]="S",n[n.T=84]="T",n[n.U=85]="U",n[n.V=86]="V",n[n.W=87]="W",n[n.X=88]="X",n[n.Y=89]="Y",n[n.Z=90]="Z",n[n.asterisk=42]="asterisk",n[n.backslash=92]="backslash",n[n.closeBrace=125]="closeBrace",n[n.closeBracket=93]="closeBracket",n[n.colon=58]="colon",n[n.comma=44]="comma",n[n.dot=46]="dot",n[n.doubleQuote=34]="doubleQuote",n[n.minus=45]="minus",n[n.openBrace=123]="openBrace",n[n.openBracket=91]="openBracket",n[n.plus=43]="plus",n[n.slash=47]="slash",n[n.formFeed=12]="formFeed",n[n.tab=9]="tab"})(wZ||(wZ={}))});function jk(n,e,t){let i,r,o,s,a;if(e){for(s=e.offset,a=s+e.length,o=s;o>0&&!yg(n,o-1);)o--;let C=a;for(;C1?cc(l,u)+cc(d,i+c):l+cc(d,i+c)}function m(){let C=h.scan();for(u=0;C===15||C===14;)C===14&&t.keepLines?u+=1:C===14&&(u=1),C=h.scan();return g=C===16||h.getTokenError()!==0,C}let b=[];function v(C,k,T){!g&&(!e||ks)&&n.substring(k,T)!==C&&b.push({offset:k,length:T-k,content:C})}let x=m();if(t.keepLines&&u>0&&v(cc(l,u),0,0),x!==17){let C=h.getTokenOffset()+o,k=cc(d,i);v(k,o,C)}for(;x!==17;){let C=h.getTokenOffset()+h.getTokenLength()+o,k=m(),T="",j=!1;for(;u===0&&(k===12||k===13);){let X=h.getTokenOffset()+o;v(" ",C,X),C=h.getTokenOffset()+h.getTokenLength()+o,j=k===12,T=j?f():"",k=m()}if(k===2)x!==1&&c--,t.keepLines&&u>0||!t.keepLines&&x!==1?T=f():t.keepLines&&(T=" ");else if(k===4)x!==3&&c--,t.keepLines&&u>0||!t.keepLines&&x!==3?T=f():t.keepLines&&(T=" ");else{switch(x){case 3:case 1:c++,t.keepLines&&u>0||!t.keepLines?T=f():T=" ";break;case 5:t.keepLines&&u>0||!t.keepLines?T=f():T=" ";break;case 12:T=f();break;case 13:u>0?T=f():j||(T=" ");break;case 6:t.keepLines&&u>0?T=f():j||(T=" ");break;case 10:t.keepLines&&u>0?T=f():k===6&&!j&&(T="");break;case 7:case 8:case 9:case 11:case 2:case 4:t.keepLines&&u>0?T=f():(k===12||k===13)&&!j?T=" ":k!==5&&k!==17&&(g=!0);break;case 16:g=!0;break}u>0&&(k===12||k===13)&&(T=f())}k===17&&(t.keepLines&&u>0?T=f():T=t.insertFinalNewline?l:"");let N=h.getTokenOffset()+o;v(T,C,N),x=k}return b}function cc(n,e){let t="";for(let i=0;i{"use strict";zy()});function xZ(n,e=[],t=vg.DEFAULT){let i=null,r=[],o=[];function s(l){Array.isArray(r)?r.push(l):i!==null&&(r[i]=l)}return Qy(n,{onObjectBegin:()=>{let l={};s(l),o.push(r),r=l,i=null},onObjectProperty:l=>{i=l},onObjectEnd:()=>{r=o.pop()},onArrayBegin:()=>{let l=[];s(l),o.push(r),r=l,i=null},onArrayEnd:()=>{r=o.pop()},onLiteralValue:s,onError:(l,u,c)=>{e.push({error:l,offset:u,length:c})}},t),r[0]}function Ak(n,e=[],t=vg.DEFAULT){let i={type:"array",offset:-1,length:-1,children:[],parent:void 0};function r(l){i.type==="property"&&(i.length=l-i.offset,i=i.parent)}function o(l){return i.children.push(l),l}Qy(n,{onObjectBegin:l=>{i=o({type:"object",offset:l,length:-1,parent:i,children:[]})},onObjectProperty:(l,u,c)=>{i=o({type:"property",offset:u,length:-1,parent:i,children:[]}),i.children.push({type:"string",value:l,offset:u,length:c,parent:i})},onObjectEnd:(l,u)=>{r(l+u),i.length=l+u-i.offset,i=i.parent,r(l+u)},onArrayBegin:(l,u)=>{i=o({type:"array",offset:l,length:-1,parent:i,children:[]})},onArrayEnd:(l,u)=>{i.length=l+u-i.offset,i=i.parent,r(l+u)},onLiteralValue:(l,u,c)=>{o({type:zse(l),offset:u,length:c,parent:i,value:l}),r(u+c)},onSeparator:(l,u,c)=>{i.type==="property"&&(l===":"?i.colonOffset=u:l===","&&r(u))},onError:(l,u,c)=>{e.push({error:l,offset:u,length:c})}},t);let a=i.children[0];return a&&delete a.parent,a}function Ky(n,e){if(!n)return;let t=n;for(let i of e)if(typeof i=="string"){if(t.type!=="object"||!Array.isArray(t.children))return;let r=!1;for(let o of t.children)if(Array.isArray(o.children)&&o.children[0].value===i&&o.children.length===2){t=o.children[1],r=!0;break}if(!r)return}else{let r=i;if(t.type!=="array"||r<0||!Array.isArray(t.children)||r>=t.children.length)return;t=t.children[r]}return t}function Qy(n,e,t=vg.DEFAULT){let i=bg(n,!1),r=[];function o(B){return B?()=>B(i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter()):()=>!0}function s(B){return B?()=>B(i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter(),()=>r.slice()):()=>!0}function a(B){return B?ge=>B(ge,i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter()):()=>!0}function l(B){return B?ge=>B(ge,i.getTokenOffset(),i.getTokenLength(),i.getTokenStartLine(),i.getTokenStartCharacter(),()=>r.slice()):()=>!0}let u=s(e.onObjectBegin),c=l(e.onObjectProperty),d=o(e.onObjectEnd),h=s(e.onArrayBegin),g=o(e.onArrayEnd),f=l(e.onLiteralValue),m=a(e.onSeparator),b=o(e.onComment),v=a(e.onError),x=t&&t.disallowComments,C=t&&t.allowTrailingComma;function k(){for(;;){let B=i.scan();switch(i.getTokenError()){case 4:T(14);break;case 5:T(15);break;case 3:T(13);break;case 1:x||T(11);break;case 2:T(12);break;case 6:T(16);break}switch(B){case 12:case 13:x?T(10):b();break;case 16:T(1);break;case 15:case 14:break;default:return B}}}function T(B,ge=[],ye=[]){if(v(B),ge.length+ye.length>0){let Fe=i.getToken();for(;Fe!==17;){if(ge.indexOf(Fe)!==-1){k();break}else if(ye.indexOf(Fe)!==-1)break;Fe=k()}}}function j(B){let ge=i.getTokenValue();return B?f(ge):(c(ge),r.push(ge)),k(),!0}function N(){switch(i.getToken()){case 11:let B=i.getTokenValue(),ge=Number(B);isNaN(ge)&&(T(2),ge=0),f(ge);break;case 7:f(null);break;case 8:f(!0);break;case 9:f(!1);break;default:return!1}return k(),!0}function X(){return i.getToken()!==10?(T(3,[],[2,5]),!1):(j(!1),i.getToken()===6?(m(":"),k(),K()||T(4,[],[2,5])):T(5,[],[2,5]),r.pop(),!0)}function se(){u(),k();let B=!1;for(;i.getToken()!==2&&i.getToken()!==17;){if(i.getToken()===5){if(B||T(4,[],[]),m(","),k(),i.getToken()===2&&C)break}else B&&T(6,[],[]);X()||T(4,[],[2,5]),B=!0}return d(),i.getToken()!==2?T(7,[2],[]):k(),!0}function Y(){h(),k();let B=!0,ge=!1;for(;i.getToken()!==4&&i.getToken()!==17;){if(i.getToken()===5){if(ge||T(4,[],[]),m(","),k(),i.getToken()===4&&C)break}else ge&&T(6,[],[]);B?(r.push(0),B=!1):r[r.length-1]++,K()||T(4,[],[4,5]),ge=!0}return g(),B||r.pop(),i.getToken()!==4?T(8,[4],[]):k(),!0}function K(){switch(i.getToken()){case 3:return Y();case 1:return se();case 10:return j(!0);default:return N()}}return k(),i.getToken()===17?t.allowEmptyContent?!0:(T(4,[],[]),!1):K()?(i.getToken()!==17&&T(9,[],[]),!0):(T(4,[],[]),!1)}function zse(n){switch(typeof n){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(n){if(Array.isArray(n))return"array"}else return"null";return"object"}default:return"null"}}var vg,Nk=D(()=>{"use strict";zy();(function(n){n.DEFAULT={allowTrailingComma:!1}})(vg||(vg={}))});function CZ(n,e,t,i){let r=e.slice(),s=Ak(n,[]),a,l;for(;r.length>0&&(l=r.pop(),a=Ky(s,r),a===void 0&&t!==void 0);)typeof l=="string"?t={[l]:t}:t=[t];if(a)if(a.type==="object"&&typeof l=="string"&&Array.isArray(a.children)){let u=Ky(a,[l]);if(u!==void 0)if(t===void 0){if(!u.parent)throw new Error("Malformed AST");let c=a.children.indexOf(u.parent),d,h=u.parent.offset+u.parent.length;if(c>0){let g=a.children[c-1];d=g.offset+g.length}else d=a.offset+1,a.children.length>1&&(h=a.children[1].offset);return yl(n,{offset:d,length:h-d,content:""},i)}else return yl(n,{offset:u.offset,length:u.length,content:JSON.stringify(t)},i);else{if(t===void 0)return[];let c=`${JSON.stringify(l)}: ${JSON.stringify(t)}`,d=i.getInsertionIndex?i.getInsertionIndex(a.children.map(g=>g.children[0].value)):a.children.length,h;if(d>0){let g=a.children[d-1];h={offset:g.offset+g.length,length:0,content:","+c}}else a.children.length===0?h={offset:a.offset+1,length:0,content:c}:h={offset:a.offset+1,length:0,content:c+","};return yl(n,h,i)}}else if(a.type==="array"&&typeof l=="number"&&Array.isArray(a.children)){let u=l;if(u===-1){let c=`${JSON.stringify(t)}`,d;if(a.children.length===0)d={offset:a.offset+1,length:0,content:c};else{let h=a.children[a.children.length-1];d={offset:h.offset+h.length,length:0,content:","+c}}return yl(n,d,i)}else if(t===void 0&&a.children.length>=0){let c=l,d=a.children[c],h;if(a.children.length===1)h={offset:a.offset+1,length:a.length-2,content:""};else if(a.children.length-1===c){let g=a.children[c-1],f=g.offset+g.length,m=a.offset+a.length;h={offset:f,length:m-2-f,content:""}}else h={offset:d.offset,length:a.children[c+1].offset-d.offset,content:""};return yl(n,h,i)}else if(t!==void 0){let c,d=`${JSON.stringify(t)}`;if(!i.isArrayInsertion&&a.children.length>l){let h=a.children[l];c={offset:h.offset,length:h.length,content:d}}else if(a.children.length===0||l===0)c={offset:a.offset+1,length:0,content:a.children.length===0?d:d+","};else{let h=l>a.children.length?a.children.length:l,g=a.children[h-1];c={offset:g.offset+g.length,length:0,content:","+d}}return yl(n,c,i)}else throw new Error(`Can not ${t===void 0?"remove":i.isArrayInsertion?"insert":"modify"} Array index ${u} as length is not sufficient`)}else throw new Error(`Can not add ${typeof l!="number"?"index":"property"} to parent of type ${a.type}`);else{if(t===void 0)throw new Error("Can not delete in empty document");return yl(n,{offset:s?s.offset:0,length:s?s.length:0,content:JSON.stringify(t)},i)}}function yl(n,e,t){if(!t.formattingOptions)return[e];let i=Vy(n,e),r=e.offset,o=e.offset+e.content.length;if(e.length===0||e.content.length===0){for(;r>0&&!yg(i,r-1);)r--;for(;o=0;l--){let u=s[l];i=Vy(i,u),r=Math.min(r,u.offset),o=Math.max(o,u.offset+u.length),o+=u.content.length-u.length}let a=n.length-(i.length-o)-r;return[{offset:r,length:a,content:i.substring(r,o)}]}function Vy(n,e){return n.substring(0,e.offset)+e.content+n.substring(e.offset+e.length)}var SZ=D(()=>{"use strict";Ok();Nk()});function _Z(n){switch(n){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return""}function EZ(n,e,t,i){return CZ(n,e,t,i)}function IZ(n,e){let t=e.slice(0).sort((r,o)=>{let s=r.offset-o.offset;return s===0?r.length-o.length:s}),i=n.length;for(let r=t.length-1;r>=0;r--){let o=t[r];if(o.offset+o.length<=i)n=Vy(n,o);else throw new Error("Overlapping edit");i=o.offset}return n}var DZ,TZ,PZ,RZ,kZ,wg=D(()=>{"use strict";Ok();SZ();zy();Nk();(function(n){n[n.None=0]="None",n[n.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",n[n.UnexpectedEndOfString=2]="UnexpectedEndOfString",n[n.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",n[n.InvalidUnicode=4]="InvalidUnicode",n[n.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",n[n.InvalidCharacter=6]="InvalidCharacter"})(DZ||(DZ={}));(function(n){n[n.OpenBraceToken=1]="OpenBraceToken",n[n.CloseBraceToken=2]="CloseBraceToken",n[n.OpenBracketToken=3]="OpenBracketToken",n[n.CloseBracketToken=4]="CloseBracketToken",n[n.CommaToken=5]="CommaToken",n[n.ColonToken=6]="ColonToken",n[n.NullKeyword=7]="NullKeyword",n[n.TrueKeyword=8]="TrueKeyword",n[n.FalseKeyword=9]="FalseKeyword",n[n.StringLiteral=10]="StringLiteral",n[n.NumericLiteral=11]="NumericLiteral",n[n.LineCommentTrivia=12]="LineCommentTrivia",n[n.BlockCommentTrivia=13]="BlockCommentTrivia",n[n.LineBreakTrivia=14]="LineBreakTrivia",n[n.Trivia=15]="Trivia",n[n.Unknown=16]="Unknown",n[n.EOF=17]="EOF"})(TZ||(TZ={}));PZ=xZ,RZ=Qy;(function(n){n[n.InvalidSymbol=1]="InvalidSymbol",n[n.InvalidNumberFormat=2]="InvalidNumberFormat",n[n.PropertyNameExpected=3]="PropertyNameExpected",n[n.ValueExpected=4]="ValueExpected",n[n.ColonExpected=5]="ColonExpected",n[n.CommaExpected=6]="CommaExpected",n[n.CloseBraceExpected=7]="CloseBraceExpected",n[n.CloseBracketExpected=8]="CloseBracketExpected",n[n.EndOfFileExpected=9]="EndOfFileExpected",n[n.InvalidCommentToken=10]="InvalidCommentToken",n[n.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",n[n.UnexpectedEndOfString=12]="UnexpectedEndOfString",n[n.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",n[n.InvalidUnicode=14]="InvalidUnicode",n[n.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",n[n.InvalidCharacter=16]="InvalidCharacter"})(kZ||(kZ={}))});function Vse(n){let{platform:e}=n;return e==="win32"?3:e==="darwin"?1:e==="linux"?2:4}var Hk,Bk,Ur,vl,wl=D(()=>{"use strict";Hk=Vse(process),Bk=Hk,Ur=Hk===3,vl=Hk===1});function dc(n,e,t=!1){let i=ft(e,100);try{let r=F.watch(n,{persistent:!0,recursive:!1,encoding:"utf8"},()=>{i()});return t&&setTimeout(e,10),p.Disposable.create(()=>{i.clear(),r.close()})}catch{return p.Disposable.create(()=>{i.clear()})}}function Xr(n){try{let e=[],t=F.readFileSync(n,"utf8"),i=PZ(t,e,{allowTrailingComma:!0});return e.length>0&&FZ.error(`Error on parse json file ${n}`,e),i??{}}catch{return{}}}function Ks(n,e){let t=R.dirname(n);F.existsSync(t)||(F.mkdirSync(t,{recursive:!0}),FZ.info(`Creating directory ${t}`)),F.writeFileSync(n,JSON.stringify(Ue(e),null,2),"utf8")}async function Fn(n){let e=null;try{e=await(0,ot.promisify)(F.stat)(n)}catch{}return e}function hc(n){return!n||!R.isAbsolute(n)||!F.existsSync(n)?!1:F.statSync(n).isDirectory()}async function Zk(n){if(!!n)try{await(0,ot.promisify)(F.rm)(n,{force:!0,recursive:!0})}catch{return}}async function Jk(n){try{let e=await(0,ot.promisify)(F.lstat)(n);return e.isFile()?1:e.isDirectory()?2:e.isSymbolicLink()?64:0}catch{return}}async function MZ(n){if(!n)return!1;let e=await Fn(n);if(!e||!e.isFile())return!1;let t=null;try{let{stdout:r}=await(0,ot.promisify)(LZ)("git rev-parse --show-toplevel",{cwd:R.dirname(n)});t=r.trim()}catch{}if(!t)return!1;let i=R.relative(t,n);try{let{stdout:r}=await(0,ot.promisify)(LZ)(`git check-ignore ${i}`,{cwd:t});return r.trim()==i}catch{}return!1}function Wk(n,e){return re(e)?!1:e.some(t=>ni(n,t,{dot:!0}))}function xg(n,e,t,i=!1,r=!0,o=[]){let s=Mi(n);if(r&&t&&dt(t,s,!0)&&!Wk(t,o)&&Yk(t,e))return t;let a=s.split(R.sep);if(i){for(;a.length>0;){let l=a.join(R.sep);if(!Wk(l,o)&&Yk(l,e))return l;a.pop()}return null}else{let l=[a.shift()];for(let u of a){l.push(u);let c=l.join(R.sep);if(!Wk(c,o)&&Yk(c,e))return c}return null}}function jZ(n,e,t){return new Promise((i,r)=>{if(re(e))return i(!1);let o;t&&(o=t.onCancellationRequested(()=>{l.abort(),r(new Rt)}));let s=!1,a=e.length==1?e[0]:`{${e.join(",")}}`,l=Nb(a,{nosort:!0,ignore:["node_modules/**",".git/**"],dot:!0,cwd:n,nodir:!0,absolute:!1},u=>{o&&o.dispose(),i(s)});l.on("match",()=>{o&&o.dispose(),s=!0,l.abort(),i(!0)}),l.on("end",()=>{o&&o.dispose(),i(s)})})}function Yk(n,e){try{let t=F.readdirSync(n);for(let i of e)if(i.includes("*")?ni.match(t,i,{nobrace:!0,noext:!0,nocomment:!0,nonegate:!0,dot:!0}).length!==0:t.includes(i))return!0}catch{}return!1}function eae(n,e){try{let t=F.readdirSync(n);for(let i of e)if(i.includes("*")){let o=t.filter(ni.filter(i,{nobrace:!0,noext:!0,nocomment:!0,nonegate:!0,dot:!0}));if(o.length>0)return o[0]}else{let o=t.find(s=>s===i);if(o)return o}}catch{}}function gc(n,e){let t=R.parse(e).root,i=le(n);for(;e&&e!==t;){let r=eae(e,i);if(r)return R.join(e,r);e=R.dirname(e)}return null}function Cg(n,e){return new Promise((t,i)=>{F.readFile(n,e,(r,o)=>{r&&i(r),t(o)})})}function OZ(n){let e,t=0;return new Promise((i,r)=>{F.createReadStream(n).on("error",o=>r(o)).on("data",o=>{for(e=0;ei(t))})}function Qs(n,e,t){if(!F.existsSync(n))return Promise.reject(new Error(`file does not exist: ${n}`));let i=[],r=F.createReadStream(n,{encoding:"utf8"}),o=ho.createInterface({input:r,crlfDelay:1/0,terminal:!1}),s=0;return new Promise((a,l)=>{o.on("line",u=>{s>=e&&s<=t&&i.push(u),s==t&&o.close(),s=s+1}),o.on("close",()=>{a(i),r.close()}),o.on("error",l)})}function AZ(n,e){if(!F.existsSync(n))return Promise.reject(new Error(`file does not exist: ${n}`));let t=F.createReadStream(n,{encoding:"utf8"}),i=ho.createInterface({input:t,crlfDelay:1/0,terminal:!1}),r=0,o="";return new Promise((s,a)=>{i.on("line",l=>{r==e&&(o=l,i.close(),t.close()),r=r+1}),i.on("close",()=>{s(o)}),i.on("error",a)})}async function NZ(n,e,t){let i=O.file(n).toString();if(!F.existsSync(n))return Ke.create(i,M.create(0,0,0,0));let r=ho.createInterface({input:F.createReadStream(n,{encoding:"utf8"})}),o=0,s=await new Promise(a=>{let l=!1;r.on("line",u=>{if(u.includes(e)){l=!0,r.removeAllListeners(),r.close(),a(u);return}o=o+1}),r.on("close",()=>{l||a(void 0)})});if(s!=null){let a=t==null?0:s.indexOf(t);a==0&&(a=s.match(/^\s*/)[0].length);let l=Q.create(o,a+(t?t.length:0));return Ke.create(i,M.create(Q.create(o,a),l))}return Ke.create(i,M.create(0,0,0,0))}function ai(n,e,t){return t=typeof t=="boolean"?t:Ur||vl,!n||!e?!1:(n=Mi(n),e=Mi(e),t?n.toLowerCase()===e.toLowerCase():n===e)}function tae(n,e,t=Ur||vl){return t?n.toLowerCase().startsWith(e.toLowerCase()):n.startsWith(e)}async function Sg(n,e){await(0,ot.promisify)(F.writeFile)(n,e,{encoding:"utf8"})}function Dg(n){return n.startsWith("file:")}function Mi(n){return O.file(R.resolve(R.normalize(n))).fsPath}function dt(n,e,t=!1){let i=Mi(n),r=Mi(e);return ai(i,r)?!!t:tae(r,i)&&r[i.length]==R.sep}var FZ,LZ,ev,st=D(()=>{"use strict";wg();ae();Je();xe();de();U();Re();Ii();de();Be();wl();FZ=Z("util-fs"),LZ=pn.exec,ev=(r=>(r[r.Unknown=0]="Unknown",r[r.File=1]="File",r[r.Directory=2]="Directory",r[r.SymbolicLink=64]="SymbolicLink",r))(ev||{})});var Gr,Tg=D(()=>{"use strict";Re();Yt();st();de();Gr=class{constructor(e,t,i=5e3){this.maximum=i;this.file=R.join(t||Gn,e);let r=R.dirname(this.file);F.mkdirSync(r,{recursive:!0})}async load(){try{let e=await Qs(this.file,0,this.maximum);if(e.length>this.maximum){let t=e.slice(0,this.maximum);return await Sg(this.file,t.join(` +`)),yi(t)}return yi(e)}catch{return[]}}loadSync(){try{let e=F.readFileSync(this.file,"utf8");return e=e.trim(),e.length?e.trim().split(` +`):[]}catch{return[]}}async add(e){let t;try{t=F.readFileSync(this.file),t[0]===239&&t[1]===187&&t[2]===191&&(t=t.slice(3)),t=Buffer.concat([Buffer.from(e,"utf8"),new Uint8Array([10]),t])}catch{t=Buffer.concat([Buffer.from(e,"utf8"),new Uint8Array([10])])}await(0,ot.promisify)(F.writeFile)(this.file,t)}async remove(e){let t=await this.load(),i=t.length;t=t.filter(r=>r!=e),t.length!=i&&await Sg(this.file,t.join(` +`))}async clean(){try{await(0,ot.promisify)(F.unlink)(this.file)}catch{}}}});var kg,vo=D(()=>{"use strict";kg=(i=>(i[i.Global=1]="Global",i[i.Workspace=2]="Workspace",i[i.WorkspaceFolder=3]="WorkspaceFolder",i))(kg||{})});function rae(n,e,t){return nae.some(i=>n.startsWith(i))?1:e==="application"?1:e==="window"?2:e==="resource"||e==="machine-overridable"?3:e==="language-overridable"?4:t}function tv(n,e=2){let t={};for(let[i,r]of Object.entries(Ue(n))){let o=Li(r);o.scope=rae(i,r.scope,e),t[i]=o}return t}var $k,li,nae,wo=D(()=>{"use strict";vo();Ii();Xe();Be();$k=class{constructor(){this.data=new Map}add(e,t){yy(typeof e=="string"),yy(xt(t)),yy(!this.data.has(e)),this.data.set(e,t)}knows(e){return this.data.has(e)}as(e){return this.data.get(e)||null}},li=new $k,nae=["coc.source.","list.source."]});function zk(){let n={};for(let e of Gk.getExtensions().extensions){let t=e.definitions;Object.entries(Ue(t)).forEach(([i,r])=>{n[i]=r})}return n}function oae(n){return n&&typeof n.filetype=="string"&&!re(n.patterns)}function sae(n){return n&&typeof n.command=="string"&&typeof n.title=="string"}function HZ(n){let e={};if(Array.isArray(n))for(let t of n)Object.assign(e,Ue(t.properties));else xt(n.properties)&&(e=n.properties);return e}function xl(n,e=2){let t=n.split(/\r?\n/).slice(e)[0];if(!t)return;t=t.replace(/^\s*at\s*/,"");let i;if(t.endsWith(")")){let s=t.match(/(\((.*?):\d+:\d+\))$/);s&&(i=s[2])}else{let s=t.match(/(.*?):\d+:\d+$/);s&&(i=s[1])}if(!i)return;let r=Array.from(Gk.getExtensions().extensions),o=r.find(s=>ai(oe(s.filepath),i));if(o||(o=r.find(s=>dt(s.directory,i)),o))return o.name;if(dt(yo,i))return"coc.nvim"}var ns,Xk,Gk,rs=D(()=>{"use strict";Re();Yt();st();Xe();Be();wo();fe();ns={ExtensionContribution:"base.contributions.extensions"},Xk=class{constructor(){this.extensionsById=new Map}get onCommands(){let e=[];for(let t of this.extensionsById.values()){let{commands:i,onCommands:r}=t;for(let o of r)if(typeof o=="string"){let s=i.find(l=>l.command===o),a=s==null?"":s.title;e.push({id:o,title:a})}}return e}getCommandTitle(e){for(let t of this.extensionsById.values())for(let i of le(t.commands))if(i.command===e)return i.title}get commands(){let e=[];for(let t of this.extensionsById.values())e.push(...le(t.commands).filter(sae));return e}getRootPatternsByFiletype(e){let t=[];for(let i of this.extensionsById.values())for(let r of le(i.rootPatterns).filter(oae))r.filetype===e&&t.push(...r.patterns.filter(o=>typeof o=="string"));return t}unregistExtension(e){this.extensionsById.delete(e)}registerExtension(e,t){this.extensionsById.set(e,t)}getExtension(e){return this.extensionsById.get(e)}getExtensions(){return{extensions:this.extensionsById.values()}}},Gk=new Xk;li.add(ns.ExtensionContribution,Gk)});var aae,Kk,lae,Qk,V,Dt=D(()=>{"use strict";Pe();xe();Tg();Re();rs();U();wo();fe();aae=Z("commands"),Kk=class{constructor(e,t,i,r){this.id=e;this.impl=t;this.thisArg=i;this.internal=r}execute(...e){let{impl:t,thisArg:i}=this;return t.apply(i,le(e))}dispose(){this.thisArg=null,this.impl=null}},lae=li.as(ns.ExtensionContribution),Qk=class{constructor(){this.commands=new Map;this.titles=new Map;this.mru=new Gr("commands")}get commandList(){let e=[];for(let t of this.commands.values())if(!t.internal){let{id:i}=t,r=this.titles.get(i)??lae.getCommandTitle(i);e.push({id:i,title:oe(r)})}return e}dispose(){for(let e of this.commands.values())e.dispose();this.commands.clear()}execute(e){return this.executeCommand(e.command,...e.arguments??[])}register(e,t,i){for(let r of Array.isArray(e.id)?e.id:[e.id])this.registerCommand(r,e.execute,e,t),i&&this.titles.set(r,i);return e}has(e){return this.commands.has(e)}unregister(e){let t=this.commands.get(e);!t||(t.dispose(),this.commands.delete(e))}registerCommand(e,t,i,r=!1){return e.startsWith("_")&&(r=!0),this.commands.has(e)&&aae.warn(`Command ${e} already registered`),this.commands.set(e,new Kk(e,t,i,r)),p.Disposable.create(()=>{this.commands.delete(e)})}executeCommand(e,...t){let i=this.commands.get(e);if(!i)throw new Error(`Command: ${e} not found`);return Promise.resolve(i.execute.apply(i,t))}async fireCommand(e,...t){await _.fire("Command",[e]);let i=Date.now(),r=await this.executeCommand(e,...t);return t.length==0&&await this.addRecent(e,_.lastChangeTs>i),r}async addRecent(e,t){await this.mru.add(e),t&&this.nvim.command('silent! call repeat#set("\\(coc-command-repeat)", -1)',!0)}async repeatCommand(){let t=(await this.mru.load())[0];t&&(await this.executeCommand(t),await this.nvim.command('silent! call repeat#set("\\(coc-command-repeat)", -1)'))}},V=new Qk});function rn(n,e=0){return $t(n)?n:e}function Vk(n){return n?1:0}function eP(n,e,t){return Math.min(Math.max(n,e),t)}var Vs=D(()=>{"use strict";Xe()});var Pg,BZ=D(()=>{"use strict";Pg=class{constructor(e,t,i){this.name=e;this.nvim=t;this.onDispose=i;this.lines=[""];this._disposed=!1;this.created=!1;if(!/^[\w\s-.]+$/.test(e))throw new Error(`Invalid channel name "${e}", only word characters and white space allowed.`)}get content(){return this.lines.join(` +`)}_append(e){let{nvim:t}=this;if(!t)return;let i=this.lines.length-1,r=e.split(/\r?\n/),o=this.lines[i]+r[0];this.lines[i]=o;let s=r.slice(1);this.lines=this.lines.concat(s),this.created&&(t.pauseNotification(),t.call("setbufline",[this.bufname,"$",o],!0),s.length&&t.call("appendbufline",[this.bufname,"$",s],!0),t.resumeNotification(!1,!0))}append(e){!this.validate()||this._append(e)}appendLine(e){!this.validate()||this._append(e+` +`)}clear(e){let{nvim:t}=this;!this.validate()||!t||(this.lines=e?this.lines.slice(-e):[],this.created&&(t.pauseNotification(),t.call("deletebufline",[this.bufname,1,"$"],!0),this.lines.length&&t.call("appendbufline",[this.bufname,"$",this.lines],!0),t.resumeNotification(!0,!0)))}hide(){this.created=!1,this.nvim&&this.nvim.command(`exe 'silent! bd! '.fnameescape('${this.bufname}')`,!0)}get bufname(){return`output:///${this.name}`}show(e,t="vs"){let{nvim:i}=this;!i||(i.pauseNotification(),i.command(`exe '${t} '.fnameescape('${this.bufname}')`,!0),e&&i.command("wincmd p",!0),i.resumeNotification(!0,!0),this.created=!0)}validate(){return!this._disposed}dispose(){this.onDispose&&this.onDispose(),this._disposed=!0,this.hide(),this.lines=[]}}});var tP,os,iv=D(()=>{"use strict";Pe();BZ();tP=class{constructor(){this.outputChannels=new Map;this.bufnrs=new Map;this.disposable=_.on("BufUnload",e=>{let t=this.bufnrs.get(e);if(t){let i=this.outputChannels.get(t);i&&(i.created=!1)}})}getProvider(e){return{onDidChange:null,provideTextDocumentContent:async i=>{let r=this.get(i.path.slice(1));if(!r)return"";e.pauseNotification(),e.call("bufnr",["%"],!0),e.command("setlocal nospell nofoldenable nowrap noswapfile",!0),e.command("setlocal buftype=nofile bufhidden=hide",!0),e.command("setfiletype log",!0);let o=await e.resumeNotification();return this.bufnrs.set(o[0][0],r.name),r.created=!0,r.content}}}get names(){return Array.from(this.outputChannels.keys())}get(e){return this.outputChannels.get(e)}create(e,t){if(this.outputChannels.has(e))return this.outputChannels.get(e);let i=new Pg(e,t,()=>{this.outputChannels.delete(e)});return this.outputChannels.set(e,i),i}show(e,t,i){let r=this.outputChannels.get(e);!r||r.show(i,t)}dispose(){this.disposable.dispose();for(let e of this.outputChannels.values())e.dispose();this.outputChannels.clear()}},os=new tP});var nv,qZ=D(()=>{"use strict";U();Pe();te();Re();nv=class{constructor(e,t){this.nvim=e;this.config=t;this.disposables=[];this._onDidClose=new p.Emitter;this.onDidClose=this._onDidClose.event;_.on("BufWinLeave",r=>{r==this.bufnr&&(this.dispose(),t.callback&&t.callback(-1))},null,this.disposables);let i=le(t.buttons).filter(r=>r.disabled!=!0);_.on("FloatBtnClick",(r,o)=>{r==this.bufnr&&(this.dispose(),t.callback&&t.callback(i[o].index))},null,this.disposables)}get lines(){return[...this.config.content.split(/\r?\n/)]}async show(e){let{nvim:t}=this,{title:i,close:r,highlights:o,buttons:s}=this.config,a=this.config.borderhighlight||e.floatBorderHighlight,l=this.config.highlight||e.floatHighlight,u={maxwidth:e.maxWidth||80};i&&(u.title=i),(r||typeof r>"u")&&(u.close=1),e.maxHeight&&(u.maxHeight=e.maxHeight),e.maxWidth&&(u.maxWidth=e.maxWidth),l&&(u.highlight=l),o&&(u.highlights=o),a&&(u.borderhighlight=[a]),s&&(u.buttons=s.filter(h=>!h.disabled).map(h=>h.text)),e.rounded&&(u.rounded=1),Array.isArray(u.buttons)&&(u.getchar=1);let[c,d]=await t.call("coc#dialog#create_dialog",[this.lines,u]);this.bufnr=d,t.command("redraw",!0)}get winid(){return this.bufnr?this.nvim.call("bufwinid",[this.bufnr]):Promise.resolve(null)}dispose(){this._onDidClose.fire(),this.bufnr=void 0,W(this.disposables),this.disposables=[]}}});var ea,iP=D(()=>{"use strict";U();Pe();te();Be();fe();ea=class{constructor(e,t){this.nvim=e;this.disposables=[];this.accepted=!1;this._disposed=!1;this._dimension=[0,0,0,0];this._onDidFinish=new p.Emitter;this._onDidChange=new p.Emitter;this.clear=!1;this.onDidFinish=this._onDidFinish.event;this.onDidChange=this._onDidChange.event;this._input=t,this.disposables.push(this._onDidFinish),this.disposables.push(this._onDidChange);let i;Object.defineProperty(this,"title",{set:s=>{i=s,this._winid&&e.call("coc#dialog#change_title",[this._winid,s],!0)},get:()=>i});let r=!1;Object.defineProperty(this,"loading",{set:s=>{r=s,this._winid&&e.call("coc#dialog#change_loading",[this._winid,s],!0)},get:()=>r});let o;Object.defineProperty(this,"borderhighlight",{set:s=>{o=s,this._winid&&e.call("coc#dialog#change_border_hl",[this._winid,s],!0)},get:()=>o}),Object.defineProperty(this,"value",{set:s=>{s=oe(s),s!==this._input&&(this.clearVirtualText(),this._input=s,this.nvim.call("coc#dialog#change_input_value",[this.winid,this.bufnr,s],!0),this._onDidChange.fire(s))},get:()=>this._input}),_.on("BufWinLeave",s=>{s==this._bufnr&&(this._winid=void 0,this.dispose())},null,this.disposables),_.on("PromptInsert",(s,a)=>{a==this._bufnr&&(this._input=s,this.accepted=!0,this.dispose())},null,this.disposables),_.on("TextChangedI",(s,a)=>{s==this._bufnr&&this._input!==a.line&&(this.clearVirtualText(),this._input=a.line,this._onDidChange.fire(a.line))},null,this.disposables)}clearVirtualText(){this.clear&&this.bufnr&&(this.clear=!1,this.nvim.createBuffer(this.bufnr).clearNamespace("input-box"))}get dimension(){let{_dimension:e}=this;return{width:e[0],height:e[1],row:e[2],col:e[3]}}get bufnr(){return this._bufnr}get winid(){return this._winid}async show(e,t){this.title=e,this.borderhighlight=t.borderhighlight??"CocFloating",this.loading=!1,t.placeHolder&&!this._input&&!this.nvim.isVim&&(this.clear=!0);let i=NW(t),r=await this.nvim.call("coc#dialog#create_prompt_win",[e,this._input,i]);if(!r)throw new Error("Unable to open input window");return this._bufnr=r[0],this._winid=r[1],this._dimension=r[2],!0}dispose(){this._disposed||(this._disposed=!0,this.nvim.call("coc#float#close",[this._winid??-1],!0),this._onDidFinish.fire(this.accepted?this._input:null),this._winid=void 0,this._bufnr=void 0,W(this.disposables))}}});var ss,rv=D(()=>{"use strict";Yt();ss=class{constructor(e,t,i,r,o=0){this.nvim=e;this.winid=t;this.bufnr=i;this.linecount=r;this._currIndex=o}get currIndex(){return this._currIndex}close(){this.nvim.call("coc#float#close",[this.winid],!0)}refreshScrollbar(){vi||this.nvim.call("coc#float#nvim_scrollbar",[this.winid],!0)}execute(e){this.nvim.call("coc#compat#execute",[this.winid,e],!0)}async getWininfo(){return await this.nvim.call("coc#float#get_wininfo",[this.winid])}async scrollForward(){let{nvim:e,bufnr:t}=this,r=await e.createBuffer(t).length,{botline:o}=await this.getWininfo();o>=r||o==0||(e.pauseNotification(),this.setCursor(o-1),this.execute("silent! noa setl scrolloff=0"),this.execute(`normal! ${o}Gzt`),this.refreshScrollbar(),e.command("redraw",!0),e.resumeNotification(!1,!0))}async scrollBackward(){let{nvim:e}=this,{topline:t}=await this.getWininfo();t!=1&&(e.pauseNotification(),this.setCursor(t-1),this.execute(`normal! ${t}Gzb`),this.refreshScrollbar(),e.command("redraw",!0),e.resumeNotification(!1,!0))}setCursor(e,t=!1){let{nvim:i,bufnr:r,winid:o,linecount:s}=this;e<0?e=0:e>s-1&&(e=s-1),this._currIndex=e,i.call("coc#dialog#set_cursor",[o,r,e+1],!0),t&&(this.refreshScrollbar(),i.command("redraw",!0))}}});function ov(n){return n?typeof n.text=="string":!1}function uae(n){return n<99?`${n+1}. `:" "}var Rg,WZ=D(()=>{"use strict";U();Pe();te();fe();rv();Rg=class{constructor(e,t,i){this.nvim=e;this.config=t;this.currIndex=0;this.contentHeight=0;this.disposables=[];this.keyMappings=new Map;this.shortcutIndexes=new Set;this._disposed=!1;this._onDidClose=new p.Emitter;this.onDidClose=this._onDidClose.event;this.total=t.items.length,i&&i.onCancellationRequested(()=>{this._onDidClose.fire(-1),this.dispose()}),this.disposables.push(this._onDidClose),this.addKeymappings()}attachEvents(){_.on("InputChar",this.onInputChar.bind(this),null,this.disposables),_.on("BufWinLeave",e=>{e==this.bufnr&&(this._onDidClose.fire(-1),this.dispose())},null,this.disposables)}addKeymappings(){let{nvim:e}=this;this.addKeys(["",""],()=>{this._onDidClose.fire(-1),this.dispose()}),this.addKeys(["\r",""],()=>{this.selectCurrent()});let t=s=>{e.pauseNotification(),this.setCursor(s+this.contentHeight),this.win.refreshScrollbar(),e.command("redraw",!0),e.resumeNotification(!1,!0)};this.addKeys("",async()=>{await this.win.scrollForward()}),this.addKeys("",async()=>{await this.win.scrollBackward()}),this.addKeys(["j","","",""],()=>{let s=this.currIndex==this.total-1?0:this.currIndex+1;t(s)}),this.addKeys(["k","","",""],()=>{let s=this.currIndex==0?this.total-1:this.currIndex-1;t(s)}),this.addKeys(["g"],()=>{t(0)}),this.addKeys(["G"],()=>{t(this.total-1)});let i,r,o=s=>{this.isDisabled(s)||(this._onDidClose.fire(s),this.dispose())};this.addKeys(["0","1","2","3","4","5","6","7","8","9"],s=>{i&&clearTimeout(i);let a=parseInt(s,10);if(!(isNaN(a)||a>this.total)&&!(r==null&&a==0)){if(r){let l=r*10+a;r=void 0,o(l-1);return}if(this.total<10||a*10>this.total){o(a-1);return}i=setTimeout(async()=>{o(a-1)},200),r=a}}),this.config.shortcuts&&this.addShortcuts(o)}addShortcuts(e){let{items:t}=this.config;t.map(r=>ov(r)?r.text:r).forEach((r,o)=>{if(r.length){let s=r[0];lc(s.charCodeAt(0))&&!this.keyMappings.has(s)&&(this.shortcutIndexes.add(o),this.addKeys(s,()=>{e(o)}))}})}isDisabled(e){let{items:t}=this.config,i=t[e];return!!(ov(i)&&i.disabled)}async show(e={}){let{nvim:t,shortcutIndexes:i}=this,{title:r,items:o,borderhighlight:s,position:a,content:l}=this.config,u={};r&&(u.title=r),a==="center"&&(u.relative="editor"),e.maxHeight&&(u.maxHeight=e.maxHeight),e.maxWidth&&(u.maxWidth=e.maxWidth),e.floatHighlight&&(u.highlight=e.floatHighlight),s?u.borderhighlight=s:e.floatBorderHighlight&&(u.borderhighlight=e.floatBorderHighlight),e.rounded&&(u.rounded=1),typeof l=="string"&&(u.content=l),e.confirmKey&&this.addKeys(e.confirmKey,()=>{this.selectCurrent()});let c=[],d=o.map((m,b)=>{let v=ov(m)?m.text:m,x=uae(b);return i.has(b)&&c.push({lnum:b,hlGroup:e.shortcutHighlight||"MoreMsg",colStart:ue(x),colEnd:ue(x)+1}),x+v.trim()});d.forEach((m,b)=>{let v=o[b];ov(v)&&v.disabled&&c.push({hlGroup:"CocDisabled",lnum:b,colStart:0,colEnd:ue(m)})}),c.length&&(u.highlights=c);let[h,g,f]=await t.call("coc#dialog#create_menu",[d,u]);t.command("redraw",!0),!this._disposed&&(this.win=new ss(t,h,g,d.length+f,f),this.bufnr=g,this.contentHeight=f,this.attachEvents(),t.call("coc#prompt#start_prompt",["menu"],!0))}selectCurrent(){if(this.isDisabled(this.currIndex)){let e=this.config.items[this.currIndex];e.disabled.reason&&this.nvim.outWriteLine(`Item disabled: ${e.disabled.reason}`);return}this._onDidClose.fire(this.currIndex),this.dispose()}get buffer(){return this.bufnr?this.nvim.createBuffer(this.bufnr):void 0}dispose(){var e;this._disposed||(this._disposed=!0,W(this.disposables),this.shortcutIndexes.clear(),this.keyMappings.clear(),this.nvim.call("coc#prompt#stop_prompt",["menu"],!0),(e=this.win)==null||e.close(),this.bufnr=void 0,this.win=void 0)}async onInputChar(e,t){if(e!="menu"||!this.win)return;let i=this.keyMappings.get(t);i&&await Promise.resolve(i(t))}setCursor(e){this.currIndex=e-this.contentHeight,this.win.setCursor(e)}addKeys(e,t){if(Array.isArray(e))for(let i of e)this.keyMappings.set(i,t);else this.keyMappings.set(e,t)}}});function YZ(n){return n.map(e=>typeof e=="string"?{label:e}:e)}var _g,ZZ=D(()=>{"use strict";Pe();te();U();fe();rv();_g=class{constructor(e,t,i){this.nvim=e;this.config=t;this.picked=new Set;this.disposables=[];this.keyMappings=new Map;this._onDidClose=new p.Emitter;this.onDidClose=this._onDidClose.event;for(let r=0;r{var r;(r=this.win)==null||r.close()}),this.disposables.push(this._onDidClose)}get currIndex(){return this.win?this.win.currIndex:0}attachEvents(){_.on("InputChar",this.onInputChar.bind(this),null,this.disposables),_.on("BufWinLeave",e=>{e==this.bufnr&&(this._onDidClose.fire(void 0),this.bufnr=void 0,this.win=void 0,this.dispose())},null,this.disposables),_.on("FloatBtnClick",(e,t)=>{if(e==this.bufnr){if(t==0){let i=Array.from(this.picked);this._onDidClose.fire(i.length>0?i:void 0)}else this._onDidClose.fire(void 0);this.dispose()}},null,this.disposables),this.addKeymappings()}addKeymappings(){let{nvim:e}=this,t=i=>{this.picked.has(i)?this.picked.delete(i):this.picked.add(i)};this.addKeys("",async()=>{let[i,r,o]=await e.call("coc#ui#get_mouse");e.pauseNotification(),i==this.win.winid&&(o<=3?(t(r-1),this.changeLine(r-1)):this.win.setCursor(r-1)),e.call("win_gotoid",[i],!0),e.call("cursor",[r,o],!0),e.call("coc#float#nvim_float_click",[],!0),e.command("redraw",!0),await e.resumeNotification()}),this.addKeys(["",""],()=>{this._onDidClose.fire(void 0),this.dispose()}),this.addKeys("",()=>{if(this.picked.size==0)this._onDidClose.fire(void 0);else{let i=Array.from(this.picked);this._onDidClose.fire(i)}this.dispose()}),this.addKeys(["j","","",""],()=>{this.win.setCursor(this.currIndex+1,!0)}),this.addKeys(["k","","",""],()=>{this.win.setCursor(this.currIndex-1,!0)}),this.addKeys(["g"],()=>{this.win.setCursor(0,!0)}),this.addKeys(["G"],()=>{this.win.setCursor(this.total-1,!0)}),this.addKeys(" ",async()=>{let i=this.currIndex;t(i),e.pauseNotification(),this.changeLine(i),this.win.setCursor(this.currIndex+1),e.command("redraw",!0),await e.resumeNotification()}),this.addKeys("",async()=>{await this.win.scrollForward()}),this.addKeys("",async()=>{await this.win.scrollBackward()})}async show(e={}){let{nvim:t}=this,{title:i,items:r}=this.config,o={close:1,cursorline:1};if(e.maxHeight&&(o.maxHeight=e.maxHeight),e.maxWidth&&(o.maxWidth=e.maxWidth),i&&(o.title=i),e.floatHighlight&&(o.highlight=e.floatHighlight),e.floatBorderHighlight&&(o.borderhighlight=[e.floatBorderHighlight]),e.pickerButtons){let u=e.pickerButtonShortcut;o.buttons=["Submit"+(u?" ":""),"Cancel"+(u?" ":"")]}e.rounded&&(o.rounded=1),e.confirmKey&&e.confirmKey!=""&&this.addKeys(e.confirmKey,()=>{this._onDidClose.fire(void 0),this.dispose()});let s=[],a=[];for(let u=0;u=3){let u=Math.min(7,n.length-1);for(let c=t+1;cl[0])&&(l=h))}}}return l}function Sl(n,e,t,i,r,o,s={boostFullMatch:!0,firstMatchCanBeWeak:!1}){let a=n.length>ta?ta:n.length,l=i.length>ta?ta:i.length;if(t>=a||o>=l||a-t>l-o||!hae(e,t,a,r,o,l,!0))return;gae(a,l,t,o,e,r);let u=1,c=1,d=t,h=o,g=[!1];for(u=1,d=t;dx,se=X?Cl[u][c-1]+(as[u][c-1]>0?-5:0):0,Y=h>x+1&&as[u][c-1]>0,K=Y?Cl[u][c-2]+(as[u][c-2]>0?-5:0):0;Y&&(!X||K>=se)&&(!j||K>=N)?(Cl[u][c]=K,sv[u][c]=3,as[u][c]=0):X&&(!j||se>=N)?(Cl[u][c]=se,sv[u][c]=2,as[u][c]=0):(Cl[u][c]=N,sv[u][c]=1,as[u][c]=as[u-1][c-1]+1)}}if(!g[0]&&!s.firstMatchCanBeWeak)return;u--,c--;let f=[Cl[u][c],o],m=0,b=0;for(;u>=1;){let x=c;do{let C=sv[u][x];if(C===3)x=x-2;else if(C===2)x=x-1;else break}while(x>=1);m>1&&e[t+u-1]===r[o+c-1]&&!lv(x+o-1,i,r)&&m+1>as[u][x]&&(x=c),x===c?m++:m=1,b||(b=x),u--,c=x-1,f.push(c)}l===a&&s.boostFullMatch&&(f[0]+=2);let v=b-a;return f[0]-=v,f}function na(n,e,t,i,r,o,s){let a=Math.min(13,n.length);for(;t1&&t===i&&(c[0]=!0),h||(h=lv(s,r,o)||av(o,s-1)||JZ(o,s-1)),t===i?s>l&&(d-=h?3:5):u?d+=h?2:0:d+=h?0:1,s+1===a&&(d-=h?3:5),d}function av(n,e){let t=n.codePointAt(e);switch(t){case 95:case 45:case 46:case 32:case 47:case 92:case 39:case 34:case 58:case 36:case 60:case 62:case 40:case 41:case 91:case 93:case 123:case 125:return!0;case void 0:return!1;default:return!!dZ(t)}}function JZ(n,e){if(e<0||e>=n.length)return!1;switch(n.charCodeAt(e)){case 32:case 9:return!0;default:return!1}}function hae(n,e,t,i,r,o,s=!1){for(;e=t&&a>=i;)r[s]===o[a]&&(nP[s]=a,s--),a--}function pae(n,e){if(e+1>=n.length)return;let t=n[e],i=n[e+1];if(t!==i)return n.slice(0,e)+i+t+n.slice(e+2)}var ta,UZ,nP,as,Cl,sv,pc=D(()=>{"use strict";gg();fe();ta=128;UZ=$Z(2*ta),nP=$Z(2*ta),as=rP(),Cl=rP(),sv=rP()});async function XZ(){let n=await(0,ot.promisify)(F.readFile)(fae);return(await global.WebAssembly.instantiate(n,{env:{}})).instance.exports}function cv(n,e){let t=[];for(let i of dv(n,e,2))t.push(i);return t}function*dv(n,e,t=0,i=Number.MAX_SAFE_INTEGER){let r=e.length;if(r<=t)return;let o=zs(n,Math.min(e[t]+1,i)),s,a;for(let l=r-1;l>=t;l--){let u=e[l];if(u>=i){s!=null&&(yield[o(s),o(a+1)]);break}if(a!=null){let c=u-a;if(c==1)a=u;else if(c>1)yield[o(s),o(a+1)],s=u;else{yield[o(s),o(a+1)];break}}else s=u;a=u,l==t&&(yield[o(s),o(a+1)])}}function*mae(n,e,t){t=t?Math.min(t,n.length):n.length;let i=zs(n,Math.min(n.length,4096)),r,o,s=e.length;for(let a=0;a=t){r!=null&&(yield[i(r),i(o+1)]);break}if(o!=null){let u=l-o;if(u==1)o=l;else if(u>1)yield[i(r),i(o+1)],r=l;else{yield[i(r),i(o+1)];break}}else r=l;o=l,a==s-1&&(yield[i(r),i(o+1)])}}var fae,uv,Eg=D(()=>{"use strict";Yt();pc();de();fe();fae=R.join(yo,"bin/fuzzy.wasm");uv=class{constructor(e){this.exports=e;this.patternLength=0;this.matchSeq=!1;this.sizes=[2048,1024,1024]}matchSpans(e,t,i){return mae(e,t,i)}matchScoreSpans(e,t){return dv(e,t,2)}createScoreFunction(e,t,i,r){let o=e.toLowerCase(),s;return r==="any"?s=na:r==="aggressive"?s=ia:s=Sl,(a,l=0)=>s(e,o,t,a,a.toLowerCase(),l,i)}getSizes(){return this.sizes}setPattern(e,t=!1){if(e.length>256&&(e=e.slice(0,256)),this.matchSeq=t,this.patternLength=t?e.length:e.replace(/(\s|\t)/g,"").length,this.patternPtr==null){let{malloc:s}=this.exports,{sizes:a}=this;this.contentPtr=s(a[0]),this.patternPtr=s(a[1]),this.resultPtr=s(a[2])}let i=Buffer.from(e,"utf8"),r=i.length,o=new Uint8Array(this.exports.memory.buffer,this.patternPtr,r+1);o.set(i),o[r]=0}changeContent(e){let{sizes:t}=this;e.length>4096&&(e=e.slice(0,4096));let i=Buffer.from(e,"utf8"),r=i.length;if(r>t[0]){let{malloc:s,free:a}=this.exports;a(this.contentPtr);let l=r+1;this.contentPtr=s(l),t[0]=l}let o=new Uint8Array(this.exports.memory.buffer,this.contentPtr,r+1);o.set(i),o[r]=0}match(e){if(this.patternPtr==null)throw new Error("setPattern not called before match");if(this.patternLength===0)return{score:100,positions:new Uint32Array};this.changeContent(e);let{fuzzyMatch:t,memory:i}=this.exports,{resultPtr:r}=this,o=t(this.contentPtr,this.patternPtr,r,this.matchSeq?1:0);if(!o)return;let s=new Uint32Array(i.buffer,r,this.patternLength);return{score:o,positions:s.slice()}}matchHighlights(e,t){let i=this.match(e);if(!i)return;let r=[];for(let o of this.matchSpans(e,i.positions))r.push({span:o,hlGroup:t});return{score:i.score,highlights:r}}free(){let e=[this.contentPtr,this.patternPtr,this.resultPtr],{free:t}=this.exports;e.forEach(i=>{i!=null&&t(i)}),this.contentPtr=this.patternPtr=this.resultPtr=void 0}}});async function yae(){let n=await(0,ot.promisify)(F.readFile)(bae);return(await global.WebAssembly.instantiate(n,{env:{}})).instance.exports}var bae,hv,ra,oP=D(()=>{"use strict";Yt();de();bae=R.join(yo,"bin/strwidth.wasm");ra=class{constructor(e){this.exports=e;this.cache=new Map;this.bytes=new Uint8Array(e.memory.buffer),this.contentPtr=e.malloc(4096)}setAmbw(e){this.exports.setAmbw(e?1:0),this.cache.clear()}getWidth(e,t=!1){let i=e.length;if(i===0)return 0;if(i>4095&&(e=e.slice(0,4095)),t&&this.cache.has(e))return this.cache.get(e);let{contentPtr:r}=this,o=Buffer.from(e,"utf8"),s=o.length;this.bytes.set(o,r),this.bytes[r+s]=0;let a=this.exports.strWidth(r);return t&&this.cache.set(e,a),a}static async create(){if(hv)return hv;let e=await yae();return hv=new ra(e),hv}}});var Uke,fc,GZ=D(()=>{"use strict";Pe();xe();te();Re();pc();U();fe();Eg();iP();rv();oP();Uke=Z("quickpick"),fc=class{constructor(e,t={}){this.nvim=e;this.preferences=t;this.canSelectMany=!1;this.matchOnDescription=!1;this.maxHeight=10;this.filteredItems=[];this.disposables=[];this._changed=!1;this._onDidFinish=new p.Emitter;this._onDidChangeSelection=new p.Emitter;this._onDidChangeValue=new p.Emitter;this.onDidFinish=this._onDidFinish.event;this.onDidChangeSelection=this._onDidChangeSelection.event;this.onDidChangeValue=this._onDidChangeValue.event;let i=[],r=this.input=new ea(this.nvim,"");t.maxHeight&&(this.maxHeight=t.maxHeight),Object.defineProperty(this,"items",{set:o=>{i=le(o),this.selectedItems=i.filter(s=>s.picked),this.filterItems("")},get:()=>i}),Object.defineProperty(this,"activeItems",{set:o=>{i=le(o),this.filteredItems=i,this.showFilteredItems()},get:()=>this.filteredItems}),Object.defineProperty(this,"value",{set:o=>{this.input.value=o},get:()=>this.input.value}),Object.defineProperty(this,"title",{set:o=>{r.title=oe(o)},get:()=>r.title??""}),Object.defineProperty(this,"loading",{set:o=>{r.loading=o},get:()=>r.loading}),r.onDidChange(o=>{if(this._changed=!1,this._onDidChangeValue.fire(o),this._changed){this._changed=!1;return}this.filterItems(o)},this),r.onDidFinish(this.onFinish,this)}get maxWidth(){return this.preferences.maxWidth??80}get currIndex(){return this.win?this.win.currIndex:0}get buffer(){return this.bufnr?this.nvim.createBuffer(this.bufnr):void 0}get winid(){var e;return(e=this.win)==null?void 0:e.winid}setCursor(e){var t;(t=this.win)==null||t.setCursor(e,!0)}attachEvents(e){_.on("BufWinLeave",t=>{t==this.bufnr&&(this.bufnr=void 0,this.win=void 0)},null,this.disposables),_.on("PromptKeyPress",async(t,i)=>{t==e&&(i==""?await this.win.scrollForward():i==""?await this.win.scrollBackward():["","",""].includes(i)?this.setCursor(this.currIndex+1):["","",""].includes(i)?this.setCursor(this.currIndex-1):this.canSelectMany&&i==""&&this.toggePicked(this.currIndex))},null,this.disposables)}async show(){let{nvim:e,items:t,input:i,width:r,preferences:o,maxHeight:s}=this,{lines:a,highlights:l}=this.buildList(t,i.value),u;if(typeof r=="number")u=Math.min(r,this.maxWidth);else{let g=await ra.create();u=Math.max(40,Math.min(80,a.reduce((f,m)=>Math.max(f,g.getWidth(m)),0)))}let c=!!o.rounded;await i.show(this.title,{position:"center",placeHolder:this.placeHolder,marginTop:10,border:[1,1,0,1],list:!0,rounded:c,minWidth:u,maxWidth:this.maxWidth,highlight:o.floatHighlight,borderhighlight:o.floatBorderHighlight});let d={lines:a,rounded:c,maxHeight:s,highlights:l};o.floatHighlight&&(d.highlight=o.floatHighlight),o.floatBorderHighlight&&(d.borderhighlight=o.floatBorderHighlight);let h=await e.call("coc#dialog#create_list",[i.winid,i.dimension,d]);if(!h)throw new Error("Unable to open list window.");this.win=new ss(e,h[0],h[1],a.length),this.win.refreshScrollbar(),this.bufnr=h[1],this.setCursor(0),this.attachEvents(i.bufnr)}buildList(e,t,i=!1){let{selectedItems:r,canSelectMany:o}=this,s=[],a=[],l=t.length===0,u=t.toLowerCase(),c=i?na:ia,d=o?4:0;for(let m=0;mm.score!=b.score?b.score-m.score:m.index-b.index);let f=(m,b,v,x)=>({lnum:m,colStart:b[0]+x,colEnd:b[1]+x,hlGroup:v});return a.forEach((m,b)=>{h.push(m.line),m.spans.forEach(v=>{g.push(f(b,v,"CocSearch",d))}),m.descriptionSpan&&g.push(f(b,m.descriptionSpan,"Comment",0)),s.push(e[m.index])}),this.filteredItems=s,{lines:h,highlights:g}}_filter(e,t,i=!1){if(!this.win)return;this._changed=!0;let{lines:r,highlights:o}=this.buildList(e,t,i);this.nvim.call("coc#dialog#update_list",[this.win.winid,this.win.bufnr,r,o],!0),this.win.linecount=r.length,this.setCursor(0)}filterItems(e){this._filter(this.items,e)}showFilteredItems(){let{input:e,filteredItems:t}=this;this._filter(t,e.value,!0)}onFinish(e){let t=e==null?null:this.getSelectedItems();!this.canSelectMany&&e!==void 0&&!re(t)&&this._onDidChangeSelection.fire(t),this.nvim.call("coc#float#close",[this.winid],!0),setTimeout(()=>{this._onDidFinish.fire(t),this.dispose()},30)}getSelectedItems(){let{canSelectMany:e}=this;return e?this.selectedItems:le(this.filteredItems[this.currIndex])}toggePicked(e){let{nvim:t,filteredItems:i,selectedItems:r}=this,o=i[e];if(!o)return;let s=r.indexOf(o);s!=-1?r.splice(s,1):r.push(o);let a=s==-1?"x":" ";t.pauseNotification(),this.win.execute(`normal! ^1lr${a}`),this.win.setCursor(this.win.currIndex+1),t.resumeNotification(!0,!0),this._onDidChangeSelection.fire(r)}toFilterText(e){let{label:t,description:i}=e,{canSelectMany:r}=this,o=`${r?" ":""}${t.replace(/\r?\n/,"")}`;return this.matchOnDescription?o+" "+(i??""):o}dispose(){var e;this.bufnr=void 0,this.input.dispose(),(e=this.win)==null||e.close(),this._onDidFinish.dispose(),this._onDidChangeSelection.dispose(),W(this.disposables)}}});var ji,ls=D(()=>{"use strict";ji=class{constructor(){this.tasks=[];this.count=1}sched(){this.count>0&&this.tasks.length>0&&(this.count--,this.tasks.shift()())}reset(){this.tasks=[],this.count=1}get busy(){return this.count==0}acquire(){return new Promise(e=>{let t=()=>{let i=!1;e(()=>{i||(i=!0,this.count++,this.sched())})};this.tasks.push(t),process.nextTick(this.sched.bind(this))})}use(e){return this.acquire().then(t=>e().then(i=>(t(),i)).catch(i=>{throw t(),i}))}}});function zZ(n){try{return process.kill(n,0)==!0}catch(e){return e.code==="EPERM"}}function Dl(n){try{go.sync(n)}catch{return!1}return!0}function xo(n,e={},t,i=Bk===3){return i||(e.shell=e.shell||process.env.SHELL),e.maxBuffer=500*1024,new Promise((r,o)=>{let s,a;t&&(s=setTimeout(()=>{a.kill("SIGKILL"),o(new Rt)},t*1e3)),a=pn.exec(n,e,(l,u,c)=>{if(s&&clearTimeout(s),l){o(new Error(`exited with ${l.code} +${l} +${c}`));return}r(u)})})}function gv(n,e,t=Bk){if(!n.killed)if(t===3)try{let i={stdio:["pipe","pipe","ignore"]};return e&&(i.cwd=e),pn.execFileSync("taskkill",["/T","/F","/PID",n.pid.toString()],i),!0}catch{return!1}else if(t===2||t===1)try{let i=R.join(yo,"bin/terminateProcess.sh");return!pn.spawnSync(i,[n.pid.toString()]).error}catch{return!1}else return n.kill("SIGKILL"),!0}var Tl=D(()=>{"use strict";Yt();Ii();de();wl()});var sP,Ig,KZ=D(()=>{"use strict";de();st();Tl();sP=Lr(jb()),Ig=class{get nodeFolder(){return Dl("npm")?this._npmFolder?Promise.resolve(this._npmFolder):xo("npm --loglevel silent root -g",{},3e3).then(e=>(this._npmFolder=(0,sP.default)(e).trim(),this._npmFolder)):Promise.resolve("")}get yarnFolder(){return Dl("yarnpkg")?this._yarnFolder?Promise.resolve(this._yarnFolder):xo("yarnpkg global dir",{},3e3).then(e=>{let t=R.join((0,sP.default)(e).trim(),"node_modules"),i=F.existsSync(t);return i&&(this._yarnFolder=t),i?t:""}):Promise.resolve("")}async resolveModule(e){let t=await this.nodeFolder,i=await this.yarnFolder;if(i){let r=await Fn(R.join(i,e,"package.json"));if(r&&r.isFile())return R.join(i,e)}if(t){let r=await Fn(R.join(t,e,"package.json"));if(r&&r.isFile())return R.join(t,e)}return null}}});function fv(n,e){if(!e.startsWith("nvim-")&&!e.startsWith("patch-"))throw new Error("Feature param could only starts with nvim and patch");if(!n.isVim&&e.startsWith("patch-")||n.isVim&&e.startsWith("nvim-"))return!1;if(n.isVim){let[t,i,r,o]=n.version.match(/^(\d)(\d{2})(\d+)$/),s=`${i}.${parseInt(r,10)}.${parseInt(o,10)}`;return sr.gte(s,e.slice(6))}return sr.gte(n.version,e.slice(5))}async function mv(n,e,t){return vi?await n.callAsync("coc#util#with_callback",[e,t]):await n.call(e,t)}function QZ(n=""){return aP.has(n)?aP.get(n):(pv=pv+1,aP.set(n,pv),pv)}function VZ(n){let t=n.getConfiguration("coc.preferences").get("watchmanPath","watchman");try{return go.sync(t)}catch{return null}}async function eJ(n,e,t){let i=await n.call("expand","%:p");i=R.normalize(i);let r=i&&R.isAbsolute(i);if(r&&!dt(e,i,!0))return gc(t,R.dirname(i));let o=gc(t,e);return o&&o!=Pt.homedir()?o:r?gc(t,R.dirname(i)):null}function tJ(n){return vae.resolveModule(n)}function lP(n,e,t){if(Array.isArray(n)){let i=0;for(let r of n){let o=lP(r,e,t);if(o===10)return o;o>i&&(i=o)}return i}else{if(typeof n=="string")return n==="*"?5:n===t?10:0;if(n&&p.TextDocumentFilter.is(n)){let i=O.parse(e),{language:r,pattern:o,scheme:s}=n,a=0;if(s)if(s===i.scheme)a=5;else if(s==="*")a=3;else return 0;if(r)if(r===t)a=10;else if(r==="*")a=Math.max(a,5);else return 0;if(o){let l=Ur||vl,u=l?o.toLowerCase():o,c=l?i.fsPath.toLowerCase():i.fsPath;if(u===c||ni(c,u,{dot:!0}))a=5;else return 0}return a}else return 0}}var pv,vae,aP,uP=D(()=>{"use strict";Je();KZ();Yt();st();de();wl();U();pv=2e3,vae=new Ig,aP=new Map});function lJ(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}function wae(n){mc=n}function Gi(n,e){if(e){if(uJ.test(n))return n.replace(xae,iJ)}else if(cJ.test(n))return n.replace(Cae,iJ);return n}function dJ(n){return n.replace(Dae,(e,t)=>(t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}function Lt(n,e){n=typeof n=="string"?n:n.source,e=e||"";let t={replace:(i,r)=>(r=r.source||r,r=r.replace(Tae,"$1"),n=n.replace(i,r),t),getRegex:()=>new RegExp(n,e)};return t}function nJ(n,e,t){if(n){let i;try{i=decodeURIComponent(dJ(t)).replace(kae,"").toLowerCase()}catch{return null}if(i.indexOf("javascript:")===0||i.indexOf("vbscript:")===0||i.indexOf("data:")===0)return null}e&&!Pae.test(t)&&(t=Iae(e,t));try{t=encodeURI(t).replace(/%25/g,"%")}catch{return null}return t}function Iae(n,e){bv[" "+n]||(Rae.test(n)?bv[" "+n]=n+"/":bv[" "+n]=yv(n,"/",!0)),n=bv[" "+n];let t=n.indexOf(":")===-1;return e.substring(0,2)==="//"?t?e:n.replace(_ae,"$1")+e:e.charAt(0)==="/"?t?e:n.replace(Eae,"$1")+e:n+e}function Kr(n){let e=1,t,i;for(;e{let l=!1,u=s;for(;--u>=0&&a[u]==="\\";)l=!l;return l?"|":" |"}),i=t.split(/ \|/),r=0;if(i[0].trim()||i.shift(),i.length>0&&!i[i.length-1].trim()&&i.pop(),i.length>e)i.splice(e);else for(;i.length1;)e&1&&(t+=n),e>>=1,n+=n;return t+n}function sJ(n,e,t,i){let r=e.href,o=e.title?Gi(e.title):null,s=n[1].replace(/\\([\[\]])/g,"$1");if(n[0].charAt(0)!=="!"){i.state.inLink=!0;let a={type:"link",raw:t,href:r,title:o,text:s,tokens:i.inlineTokens(s)};return i.state.inLink=!1,a}return{type:"image",raw:t,href:r,title:o,text:Gi(s)}}function Fae(n,e){let t=n.match(/^(\s+)(?:```)/);if(t===null)return e;let i=t[1];return e.split(` +`).map(r=>{let o=r.match(/^\s+/);if(o===null)return r;let[s]=o;return s.length>=i.length?r.slice(i.length):r}).join(` +`)}function Mae(n){return n.replace(/---/g,"\u2014").replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201C").replace(/"/g,"\u201D").replace(/\.{3}/g,"\u2026")}function aJ(n){let e="",t,i,r=n.length;for(t=0;t.5&&(i="x"+i.toString(16)),e+="&#"+i+";";return e}function Ae(n,e,t){if(typeof n>"u"||n===null)throw new Error("marked(): input parameter is undefined or null");if(typeof n!="string")throw new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected");if(typeof e=="function"&&(t=e,e=null),e=Kr({},Ae.defaults,e||{}),hJ(e),t){let r=e.highlight,o;try{o=zr.lex(n,e)}catch(l){return t(l)}let s=function(l){let u;if(!l)try{e.walkTokens&&Ae.walkTokens(o,e.walkTokens),u=vr.parse(o,e)}catch(c){l=c}return e.highlight=r,l?t(l):t(null,u)};if(!r||r.length<3||(delete e.highlight,!o.length))return s();let a=0;Ae.walkTokens(o,function(l){l.type==="code"&&(a++,setTimeout(()=>{r(l.text,l.lang,function(u,c){if(u)return s(u);c!=null&&c!==l.text&&(l.text=c,l.escaped=!0),a--,a===0&&s()})},0))}),a===0&&s();return}function i(r){if(r.message+=` +Please report this to https://github.com/markedjs/marked.`,e.silent)return"

    An error occurred:

    "+Gi(r.message+"",!0)+"
    ";throw r}try{let r=zr.lex(n,e);if(e.walkTokens){if(e.async)return Promise.all(Ae.walkTokens(r,e.walkTokens)).then(()=>vr.parse(r,e)).catch(i);Ae.walkTokens(r,e.walkTokens)}return vr.parse(r,e)}catch(r){i(r)}}var mc,uJ,xae,cJ,Cae,Sae,iJ,Dae,Tae,kae,Pae,bv,Rae,_ae,Eae,vv,Lg,je,be,zr,Fg,wv,xv,vr,hPe,gPe,pPe,fPe,mPe,bPe,yPe,gJ=D(()=>{mc=lJ();uJ=/[&<>"']/,xae=new RegExp(uJ.source,"g"),cJ=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Cae=new RegExp(cJ.source,"g"),Sae={"&":"&","<":"<",">":">",'"':""","'":"'"},iJ=n=>Sae[n];Dae=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;Tae=/(^|[^\[])\^/g;kae=/[^\w:]/g,Pae=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;bv={},Rae=/^[^:]+:\/*[^/]*$/,_ae=/^([^:]+:)[\s\S]*$/,Eae=/^([^:]+:\/*[^/]*)[\s\S]*$/;vv={exec:function(){}};Lg=class{constructor(e){this.options=e||mc}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?i:yv(i,` +`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],r=Fae(i,t[3]||"");return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline._escapes,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(/#$/.test(i)){let r=yv(i,"#");(this.options.pedantic||!r||/ $/.test(r))&&(i=r.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=t[0].replace(/^ *>[ \t]?/gm,""),r=this.lexer.state.top;this.lexer.state.top=!0;let o=this.lexer.blockTokens(i);return this.lexer.state.top=r,{type:"blockquote",raw:t[0],tokens:o,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i,r,o,s,a,l,u,c,d,h,g,f,m=t[1].trim(),b=m.length>1,v={type:"list",raw:"",ordered:b,start:b?+m.slice(0,-1):"",loose:!1,items:[]};m=b?`\\d{1,9}\\${m.slice(-1)}`:`\\${m}`,this.options.pedantic&&(m=b?m:"[*+-]");let x=new RegExp(`^( {0,3}${m})((?:[ ][^\\n]*)?(?:\\n|$))`);for(;e&&(f=!1,!(!(t=x.exec(e))||this.rules.block.hr.test(e)));){if(i=t[0],e=e.substring(i.length),c=t[2].split(` +`,1)[0],d=e.split(` +`,1)[0],this.options.pedantic?(s=2,g=c.trimLeft()):(s=t[2].search(/[^ ]/),s=s>4?1:s,g=c.slice(s),s+=t[1].length),l=!1,!c&&/^ *$/.test(d)&&(i+=d+` +`,e=e.substring(d.length+1),f=!0),!f){let k=new RegExp(`^ {0,${Math.min(3,s-1)}}(?:[*+-]|\\d{1,9}[.)])((?: [^\\n]*)?(?:\\n|$))`),T=new RegExp(`^ {0,${Math.min(3,s-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),j=new RegExp(`^ {0,${Math.min(3,s-1)}}(?:\`\`\`|~~~)`),N=new RegExp(`^ {0,${Math.min(3,s-1)}}#`);for(;e&&(h=e.split(` +`,1)[0],c=h,this.options.pedantic&&(c=c.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!(j.test(c)||N.test(c)||k.test(c)||T.test(e)));){if(c.search(/[^ ]/)>=s||!c.trim())g+=` +`+c.slice(s);else if(!l)g+=` +`+c;else break;!l&&!c.trim()&&(l=!0),i+=h+` +`,e=e.substring(h.length+1)}}v.loose||(u?v.loose=!0:/\n *\n *$/.test(i)&&(u=!0)),this.options.gfm&&(r=/^\[[ xX]\] /.exec(g),r&&(o=r[0]!=="[ ] ",g=g.replace(/^\[[ xX]\] +/,""))),v.items.push({type:"list_item",raw:i,task:!!r,checked:o,loose:!1,text:g}),v.raw+=i}v.items[v.items.length-1].raw=i.trimRight(),v.items[v.items.length-1].text=g.trimRight(),v.raw=v.raw.trimRight();let C=v.items.length;for(a=0;aj.type==="space"),T=k.length>0&&k.some(j=>/\n.*\n/.test(j.raw));v.loose=T}if(v.loose)for(a=0;a$/,"$1").replace(this.rules.inline._escapes,"$1"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline._escapes,"$1"):t[3];return{type:"def",tag:i,raw:t[0],href:r,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(t){let i={type:"table",header:rJ(t[1]).map(r=>({text:r})),align:t[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split(` +`):[]};if(i.header.length===i.align.length){i.raw=t[0];let r=i.align.length,o,s,a,l;for(o=0;o({text:u}));for(r=i.header.length,s=0;s/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(t[0]):Gi(t[0]):t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&/^$/.test(i))return;let s=yv(i.slice(0,-1),"\\");if((i.length-s.length)%2===0)return}else{let s=Lae(t[2],"()");if(s>-1){let l=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,l).trim(),t[3]=""}}let r=t[2],o="";if(this.options.pedantic){let s=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(r);s&&(r=s[1],o=s[3])}else o=t[3]?t[3].slice(1,-1):"";return r=r.trim(),/^$/.test(i)?r=r.slice(1):r=r.slice(1,-1)),sJ(t,{href:r&&r.replace(this.rules.inline._escapes,"$1"),title:o&&o.replace(this.rules.inline._escapes,"$1")},t[0],this.lexer)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let r=(i[2]||i[1]).replace(/\s+/g," ");if(r=t[r.toLowerCase()],!r){let o=i[0].charAt(0);return{type:"text",raw:o,text:o}}return sJ(i,r,i[0],this.lexer)}}emStrong(e,t,i=""){let r=this.rules.inline.emStrong.lDelim.exec(e);if(!r||r[3]&&i.match(/[\p{L}\p{N}]/u))return;let o=r[1]||r[2]||"";if(!o||o&&(i===""||this.rules.inline.punctuation.exec(i))){let s=r[0].length-1,a,l,u=s,c=0,d=r[0][0]==="*"?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+s);(r=d.exec(t))!=null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(l=a.length,r[3]||r[4]){u+=l;continue}else if((r[5]||r[6])&&s%3&&!((s+l)%3)){c+=l;continue}if(u-=l,u>0)continue;l=Math.min(l,l+u+c);let h=e.slice(0,s+r.index+(r[0].length-a.length)+l);if(Math.min(s,l)%2){let f=h.slice(1,-1);return{type:"em",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}let g=h.slice(2,-2);return{type:"strong",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(/\n/g," "),r=/[^ ]/.test(i),o=/^ /.test(i)&&/ $/.test(i);return r&&o&&(i=i.substring(1,i.length-1)),i=Gi(i,!0),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e,t){let i=this.rules.inline.autolink.exec(e);if(i){let r,o;return i[2]==="@"?(r=Gi(this.options.mangle?t(i[1]):i[1]),o="mailto:"+r):(r=Gi(i[1]),o=r),{type:"link",raw:i[0],text:r,href:o,tokens:[{type:"text",raw:r,text:r}]}}}url(e,t){let i;if(i=this.rules.inline.url.exec(e)){let r,o;if(i[2]==="@")r=Gi(this.options.mangle?t(i[0]):i[0]),o="mailto:"+r;else{let s;do s=i[0],i[0]=this.rules.inline._backpedal.exec(i[0])[0];while(s!==i[0]);r=Gi(i[0]),i[1]==="www."?o="http://"+i[0]:o=i[0]}return{type:"link",raw:i[0],text:r,href:o,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e,t){let i=this.rules.inline.text.exec(e);if(i){let r;return this.lexer.state.inRawBlock?r=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(i[0]):Gi(i[0]):i[0]:r=Gi(this.options.smartypants?t(i[0]):i[0]),{type:"text",raw:i[0],text:r}}}},je={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:vv,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/};je._label=/(?!\s*\])(?:\\.|[^\[\]\\])+/;je._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;je.def=Lt(je.def).replace("label",je._label).replace("title",je._title).getRegex();je.bullet=/(?:[*+-]|\d{1,9}[.)])/;je.listItemStart=Lt(/^( *)(bull) */).replace("bull",je.bullet).getRegex();je.list=Lt(je.list).replace(/bull/g,je.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+je.def.source+")").getRegex();je._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";je._comment=/|$)/;je.html=Lt(je.html,"i").replace("comment",je._comment).replace("tag",je._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();je.paragraph=Lt(je._paragraph).replace("hr",je.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",je._tag).getRegex();je.blockquote=Lt(je.blockquote).replace("paragraph",je.paragraph).getRegex();je.normal=Kr({},je);je.gfm=Kr({},je.normal,{table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"});je.gfm.table=Lt(je.gfm.table).replace("hr",je.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",je._tag).getRegex();je.gfm.paragraph=Lt(je._paragraph).replace("hr",je.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",je.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",je._tag).getRegex();je.pedantic=Kr({},je.normal,{html:Lt(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",je._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:vv,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Lt(je.normal._paragraph).replace("hr",je.hr).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",je.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()});be={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:vv,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:vv,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\?@\\[\\]`^{|}~";be.punctuation=Lt(be.punctuation).replace(/punctuation/g,be._punctuation).getRegex();be.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g;be.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g;be._comment=Lt(je._comment).replace("(?:-->|$)","-->").getRegex();be.emStrong.lDelim=Lt(be.emStrong.lDelim).replace(/punct/g,be._punctuation).getRegex();be.emStrong.rDelimAst=Lt(be.emStrong.rDelimAst,"g").replace(/punct/g,be._punctuation).getRegex();be.emStrong.rDelimUnd=Lt(be.emStrong.rDelimUnd,"g").replace(/punct/g,be._punctuation).getRegex();be._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;be._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;be._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;be.autolink=Lt(be.autolink).replace("scheme",be._scheme).replace("email",be._email).getRegex();be._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;be.tag=Lt(be.tag).replace("comment",be._comment).replace("attribute",be._attribute).getRegex();be._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;be._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;be._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;be.link=Lt(be.link).replace("label",be._label).replace("href",be._href).replace("title",be._title).getRegex();be.reflink=Lt(be.reflink).replace("label",be._label).replace("ref",je._label).getRegex();be.nolink=Lt(be.nolink).replace("ref",je._label).getRegex();be.reflinkSearch=Lt(be.reflinkSearch,"g").replace("reflink",be.reflink).replace("nolink",be.nolink).getRegex();be.normal=Kr({},be);be.pedantic=Kr({},be.normal,{strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:Lt(/^!?\[(label)\]\((.*?)\)/).replace("label",be._label).getRegex(),reflink:Lt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",be._label).getRegex()});be.gfm=Kr({},be.normal,{escape:Lt(be.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\l+" ".repeat(u.length));let i,r,o,s;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(a=>(i=a.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))){if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length),i.raw.length===1&&t.length>0?t[t.length-1].raw+=` +`:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length),r=t[t.length-1],r&&(r.type==="paragraph"||r.type==="text")?(r.raw+=` +`+i.raw,r.text+=` +`+i.text,this.inlineQueue[this.inlineQueue.length-1].src=r.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length),r=t[t.length-1],r&&(r.type==="paragraph"||r.type==="text")?(r.raw+=` +`+i.raw,r.text+=` +`+i.raw,this.inlineQueue[this.inlineQueue.length-1].src=r.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title});continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(o=e,this.options.extensions&&this.options.extensions.startBlock){let a=1/0,l=e.slice(1),u;this.options.extensions.startBlock.forEach(function(c){u=c.call({lexer:this},l),typeof u=="number"&&u>=0&&(a=Math.min(a,u))}),a<1/0&&a>=0&&(o=e.substring(0,a+1))}if(this.state.top&&(i=this.tokenizer.paragraph(o))){r=t[t.length-1],s&&r.type==="paragraph"?(r.raw+=` +`+i.raw,r.text+=` +`+i.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=r.text):t.push(i),s=o.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length),r=t[t.length-1],r&&r.type==="text"?(r.raw+=` +`+i.raw,r.text+=` +`+i.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=r.text):t.push(i);continue}if(e){let a="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw new Error(a)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let i,r,o,s=e,a,l,u;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)c.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,a.index)+"["+oJ("a",a[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)s=s.slice(0,a.index)+"["+oJ("a",a[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(a=this.tokenizer.rules.inline.escapedEmSt.exec(s))!=null;)s=s.slice(0,a.index+a[0].length-2)+"++"+s.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;e;)if(l||(u=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(c=>(i=c.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))){if(i=this.tokenizer.escape(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.tag(e)){e=e.substring(i.raw.length),r=t[t.length-1],r&&i.type==="text"&&r.type==="text"?(r.raw+=i.raw,r.text+=i.text):t.push(i);continue}if(i=this.tokenizer.link(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(i.raw.length),r=t[t.length-1],r&&i.type==="text"&&r.type==="text"?(r.raw+=i.raw,r.text+=i.text):t.push(i);continue}if(i=this.tokenizer.emStrong(e,s,u)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.codespan(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.br(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.del(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.autolink(e,aJ)){e=e.substring(i.raw.length),t.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(e,aJ))){e=e.substring(i.raw.length),t.push(i);continue}if(o=e,this.options.extensions&&this.options.extensions.startInline){let c=1/0,d=e.slice(1),h;this.options.extensions.startInline.forEach(function(g){h=g.call({lexer:this},d),typeof h=="number"&&h>=0&&(c=Math.min(c,h))}),c<1/0&&c>=0&&(o=e.substring(0,c+1))}if(i=this.tokenizer.inlineText(o,Mae)){e=e.substring(i.raw.length),i.raw.slice(-1)!=="_"&&(u=i.raw.slice(-1)),l=!0,r=t[t.length-1],r&&r.type==="text"?(r.raw+=i.raw,r.text+=i.text):t.push(i);continue}if(e){let c="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return t}},Fg=class{constructor(e){this.options=e||mc}code(e,t,i){let r=(t||"").match(/\S*/)[0];if(this.options.highlight){let o=this.options.highlight(e,r);o!=null&&o!==e&&(i=!0,e=o)}return e=e.replace(/\n$/,"")+` +`,r?'
    '+(i?e:Gi(e,!0))+`
    +`:"
    "+(i?e:Gi(e,!0))+`
    +`}blockquote(e){return`
    +${e}
    +`}html(e){return e}heading(e,t,i,r){if(this.options.headerIds){let o=this.options.headerPrefix+r.slug(i);return`${e} +`}return`${e} +`}hr(){return this.options.xhtml?`
    +`:`
    +`}list(e,t,i){let r=t?"ol":"ul",o=t&&i!==1?' start="'+i+'"':"";return"<"+r+o+`> +`+e+" +`}listitem(e){return`
  • ${e}
  • +`}checkbox(e){return" "}paragraph(e){return`

    ${e}

    +`}table(e,t){return t&&(t=`${t}`),` + +`+e+` +`+t+`
    +`}tablerow(e){return` +${e} +`}tablecell(e,t){let i=t.header?"th":"td";return(t.align?`<${i} align="${t.align}">`:`<${i}>`)+e+` +`}strong(e){return`${e}`}em(e){return`${e}`}codespan(e){return`${e}`}br(){return this.options.xhtml?"
    ":"
    "}del(e){return`${e}`}link(e,t,i){if(e=nJ(this.options.sanitize,this.options.baseUrl,e),e===null)return i;let r='
    ",r}image(e,t,i){if(e=nJ(this.options.sanitize,this.options.baseUrl,e),e===null)return i;let r=`${i}":">",r}text(e){return e}},wv=class{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,i){return""+i}image(e,t,i){return""+i}br(){return""}},xv=class{constructor(){this.seen={}}serialize(e){return e.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(e,t){let i=e,r=0;if(this.seen.hasOwnProperty(i)){r=this.seen[e];do r++,i=e+"-"+r;while(this.seen.hasOwnProperty(i))}return t||(this.seen[e]=r,this.seen[i]=0),i}slug(e,t={}){let i=this.serialize(e);return this.getNextSafeSlug(i,t.dryrun)}},vr=class{constructor(e){this.options=e||mc,this.options.renderer=this.options.renderer||new Fg,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new wv,this.slugger=new xv}static parse(e,t){return new vr(t).parse(e)}static parseInline(e,t){return new vr(t).parseInline(e)}parse(e,t=!0){let i="",r,o,s,a,l,u,c,d,h,g,f,m,b,v,x,C,k,T,j,N=e.length;for(r=0;r0&&x.tokens[0].type==="paragraph"?(x.tokens[0].text=T+" "+x.tokens[0].text,x.tokens[0].tokens&&x.tokens[0].tokens.length>0&&x.tokens[0].tokens[0].type==="text"&&(x.tokens[0].tokens[0].text=T+" "+x.tokens[0].tokens[0].text)):x.tokens.unshift({type:"text",text:T}):v+=T),v+=this.parse(x.tokens,b),h+=this.renderer.listitem(v,k,C);i+=this.renderer.list(h,f,m);continue}case"html":{i+=this.renderer.html(g.text);continue}case"paragraph":{i+=this.renderer.paragraph(this.parseInline(g.tokens));continue}case"text":{for(h=g.tokens?this.parseInline(g.tokens):g.text;r+1{let i=Kr({},t);if(i.async=Ae.defaults.async||i.async,t.extensions&&(t.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if(r.renderer){let o=e.renderers[r.name];o?e.renderers[r.name]=function(...s){let a=r.renderer.apply(this,s);return a===!1&&(a=o.apply(this,s)),a}:e.renderers[r.name]=r.renderer}if(r.tokenizer){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");e[r.level]?e[r.level].unshift(r.tokenizer):e[r.level]=[r.tokenizer],r.start&&(r.level==="block"?e.startBlock?e.startBlock.push(r.start):e.startBlock=[r.start]:r.level==="inline"&&(e.startInline?e.startInline.push(r.start):e.startInline=[r.start]))}r.childTokens&&(e.childTokens[r.name]=r.childTokens)}),i.extensions=e),t.renderer){let r=Ae.defaults.renderer||new Fg;for(let o in t.renderer){let s=r[o];r[o]=(...a)=>{let l=t.renderer[o].apply(r,a);return l===!1&&(l=s.apply(r,a)),l}}i.renderer=r}if(t.tokenizer){let r=Ae.defaults.tokenizer||new Lg;for(let o in t.tokenizer){let s=r[o];r[o]=(...a)=>{let l=t.tokenizer[o].apply(r,a);return l===!1&&(l=s.apply(r,a)),l}}i.tokenizer=r}if(t.walkTokens){let r=Ae.defaults.walkTokens;i.walkTokens=function(o){let s=[];return s.push(t.walkTokens.call(this,o)),r&&(s=s.concat(r.call(this,o))),s}}Ae.setOptions(i)})};Ae.walkTokens=function(n,e){let t=[];for(let i of n)switch(t=t.concat(e.call(Ae,i)),i.type){case"table":{for(let r of i.header)t=t.concat(Ae.walkTokens(r.tokens,e));for(let r of i.rows)for(let o of r)t=t.concat(Ae.walkTokens(o.tokens,e));break}case"list":{t=t.concat(Ae.walkTokens(i.items,e));break}default:Ae.defaults.extensions&&Ae.defaults.extensions.childTokens&&Ae.defaults.extensions.childTokens[i.type]?Ae.defaults.extensions.childTokens[i.type].forEach(function(r){t=t.concat(Ae.walkTokens(i[r],e))}):i.tokens&&(t=t.concat(Ae.walkTokens(i.tokens,e)))}return t};Ae.parseInline=function(n,e){if(typeof n>"u"||n===null)throw new Error("marked.parseInline(): input parameter is undefined or null");if(typeof n!="string")throw new Error("marked.parseInline(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected");e=Kr({},Ae.defaults,e||{}),hJ(e);try{let t=zr.lexInline(n,e);return e.walkTokens&&Ae.walkTokens(t,e.walkTokens),vr.parseInline(t,e)}catch(t){if(t.message+=` +Please report this to https://github.com/markedjs/marked.`,e.silent)return"

    An error occurred:

    "+Gi(t.message+"",!0)+"
    ";throw t}};Ae.Parser=vr;Ae.parser=vr.parse;Ae.Renderer=Fg;Ae.TextRenderer=wv;Ae.Lexer=zr;Ae.lexer=zr.lex;Ae.Tokenizer=Lg;Ae.Slugger=xv;Ae.parse=Ae;hPe=Ae.options,gPe=Ae.setOptions,pPe=Ae.use,fPe=Ae.walkTokens,mPe=Ae.parseInline,bPe=vr.parse,yPe=zr.lex});function bc(n,e=!1){let t=Mg(n),i=[],r="";for(let o of t){if(!o.text)continue;let{foreground:s,background:a}=o,l=ue(r),u=[l,l+ue(o.text)];if(s&&a){let c=`CocList${is(s)}${is(a)}`;i.push({span:u,hlGroup:c})}else if(s){let c;e?s=="yellow"?c="CocMarkdownCode":s=="blue"?c="CocMarkdownLink":s=="magenta"?c="CocMarkdownHeader":c=`CocListFg${is(s)}`:c=`CocListFg${is(s)}`,i.push({span:u,hlGroup:c})}else if(a){let c=`CocListBg${is(a)}`;i.push({span:u,hlGroup:c})}o.bold?i.push({span:u,hlGroup:"CocBold"}):o.italic?i.push({span:u,hlGroup:"CocItalic"}):o.underline?i.push({span:u,hlGroup:"CocUnderline"}):o.strikethrough&&i.push({span:u,hlGroup:"CocStrikeThrough"}),r=r+o.text}return{line:r,highlights:i}}function Mg(n){let e=null,t=null,i="",r=[],o=[],s={},a;a=()=>{let l,u;i.length?i=i.substr(0,i.length-1):o.length&&(l=o.length-1,u=o[l].text,u.length===1?o.pop():o[l].text=u.substr(0,u.length-1))};for(let l=0;l{pJ[u]?s.foreground=pJ[u]:fJ[u]?s.background=fJ[u]:u==39?delete s.foreground:u==49?delete s.background:mJ[u]?s[mJ[u]]=!0:u==22?s.bold=!1:u==23?s.italic=!1:u==24?s.underline=!1:u==29&&(s.strikethrough=!1)}),r=[]):t+=n[l];continue}n[l]=="\x1B"?e=n[l]:n[l]=="\b"?a():i+=n[l]}return i&&(s.text=i+oe(e),o.push(s)),o}var pJ,fJ,mJ,yc=D(()=>{"use strict";fe();pJ={30:"black",31:"red",32:"green",33:"yellow",34:"blue",35:"magenta",36:"cyan",37:"white",90:"grey"},fJ={40:"black",41:"red",42:"green",43:"yellow",44:"blue",45:"magenta",46:"cyan",47:"white"},mJ={1:"bold",3:"italic",4:"underline",9:"strikethrough"}});function bJ(n){return`${Yi.gray.open}${n}${Yi.gray.close}`}function cP(n){return`${Yi.magenta.open}${n}${Yi.magenta.close}`}function yJ(n){return`${Yi.bold.open}${n}${Yi.bold.close}`}function dP(n){return`${Yi.underline.open}${n}${Yi.underline.close}`}function vJ(n){return`${Yi.strikethrough.open}${n}${Yi.strikethrough.close}`}function wJ(n){return`${Yi.italic.open}${n}${Yi.italic.close}`}function xJ(n){return`${Yi.yellow.open}${n}${Yi.yellow.close}`}function hP(n){return`${Yi.blue.open}${n}${Yi.blue.close}`}var CJ=D(()=>{"use strict";de()});var kJ=w((SPe,TJ)=>{var DJ={};TJ.exports=DJ;var SJ={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(SJ).forEach(function(n){var e=SJ[n],t=DJ[n]=[];t.open="\x1B["+e[0]+"m",t.close="\x1B["+e[1]+"m"})});var RJ=w((DPe,PJ)=>{var jg=process.argv;PJ.exports=function(){return jg.indexOf("--no-color")!==-1||jg.indexOf("--color=false")!==-1?!1:jg.indexOf("--color")!==-1||jg.indexOf("--color=true")!==-1||jg.indexOf("--color=always")!==-1?!0:process.stdout&&!process.stdout.isTTY?!1:process.platform==="win32"||"COLORTERM"in process.env?!0:process.env.TERM==="dumb"?!1:!!/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)}()});var EJ=w((TPe,_J)=>{_J.exports=function(e,t){var i="";e=e||"Run the trap, drop the bass",e=e.split("");var r={a:["@","\u0104","\u023A","\u0245","\u0394","\u039B","\u0414"],b:["\xDF","\u0181","\u0243","\u026E","\u03B2","\u0E3F"],c:["\xA9","\u023B","\u03FE"],d:["\xD0","\u018A","\u0500","\u0501","\u0502","\u0503"],e:["\xCB","\u0115","\u018E","\u0258","\u03A3","\u03BE","\u04BC","\u0A6C"],f:["\u04FA"],g:["\u0262"],h:["\u0126","\u0195","\u04A2","\u04BA","\u04C7","\u050A"],i:["\u0F0F"],j:["\u0134"],k:["\u0138","\u04A0","\u04C3","\u051E"],l:["\u0139"],m:["\u028D","\u04CD","\u04CE","\u0520","\u0521","\u0D69"],n:["\xD1","\u014B","\u019D","\u0376","\u03A0","\u048A"],o:["\xD8","\xF5","\xF8","\u01FE","\u0298","\u047A","\u05DD","\u06DD","\u0E4F"],p:["\u01F7","\u048E"],q:["\u09CD"],r:["\xAE","\u01A6","\u0210","\u024C","\u0280","\u042F"],s:["\xA7","\u03DE","\u03DF","\u03E8"],t:["\u0141","\u0166","\u0373"],u:["\u01B1","\u054D"],v:["\u05D8"],w:["\u0428","\u0460","\u047C","\u0D70"],x:["\u04B2","\u04FE","\u04FC","\u04FD"],y:["\xA5","\u04B0","\u04CB"],z:["\u01B5","\u0240"]};return e.forEach(function(o){o=o.toLowerCase();var s=r[o]||[" "],a=Math.floor(Math.random()*s.length);typeof r[o]<"u"?i+=r[o][a]:i+=o}),i}});var LJ=w((kPe,IJ)=>{IJ.exports=function(e,t){e=e||" he is here ";var i={up:["\u030D","\u030E","\u0304","\u0305","\u033F","\u0311","\u0306","\u0310","\u0352","\u0357","\u0351","\u0307","\u0308","\u030A","\u0342","\u0313","\u0308","\u034A","\u034B","\u034C","\u0303","\u0302","\u030C","\u0350","\u0300","\u0301","\u030B","\u030F","\u0312","\u0313","\u0314","\u033D","\u0309","\u0363","\u0364","\u0365","\u0366","\u0367","\u0368","\u0369","\u036A","\u036B","\u036C","\u036D","\u036E","\u036F","\u033E","\u035B","\u0346","\u031A"],down:["\u0316","\u0317","\u0318","\u0319","\u031C","\u031D","\u031E","\u031F","\u0320","\u0324","\u0325","\u0326","\u0329","\u032A","\u032B","\u032C","\u032D","\u032E","\u032F","\u0330","\u0331","\u0332","\u0333","\u0339","\u033A","\u033B","\u033C","\u0345","\u0347","\u0348","\u0349","\u034D","\u034E","\u0353","\u0354","\u0355","\u0356","\u0359","\u035A","\u0323"],mid:["\u0315","\u031B","\u0300","\u0301","\u0358","\u0321","\u0322","\u0327","\u0328","\u0334","\u0335","\u0336","\u035C","\u035D","\u035E","\u035F","\u0360","\u0362","\u0338","\u0337","\u0361"," \u0489"]},r=[].concat(i.up,i.down,i.mid),o={};function s(u){var c=Math.floor(Math.random()*u);return c}function a(u){var c=!1;return r.filter(function(d){c=d===u}),c}function l(u,c){var d="",h,g;c=c||{},c.up=c.up||!0,c.mid=c.mid||!0,c.down=c.down||!0,c.size=c.size||"maxi",u=u.split("");for(g in u)if(!a(g)){switch(d=d+u[g],h={up:0,down:0,mid:0},c.size){case"mini":h.up=s(8),h.min=s(2),h.down=s(8);break;case"maxi":h.up=s(16)+3,h.min=s(4)+1,h.down=s(64)+3;break;default:h.up=s(8)+1,h.mid=s(6)/2,h.down=s(8)+1;break}var f=["up","mid","down"];for(var m in f)for(var b=f[m],v=0;v<=h[b];v++)c[b]&&(d=d+i[b][s(i[b].length)])}return d}return l(e)}});var MJ=w((PPe,FJ)=>{var gP=vc();FJ.exports=function(){return function(n,e,t){if(n===" ")return n;switch(e%3){case 0:return gP.red(n);case 1:return gP.white(n);case 2:return gP.blue(n)}}}()});var OJ=w((RPe,jJ)=>{var Oae=vc();jJ.exports=function(n,e,t){return e%2===0?n:Oae.inverse(n)}});var NJ=w((_Pe,AJ)=>{var Aae=vc();AJ.exports=function(){var n=["red","yellow","green","blue","magenta"];return function(e,t,i){return e===" "?e:Aae[n[t++%n.length]](e)}}()});var BJ=w((EPe,HJ)=>{var Nae=vc();HJ.exports=function(){var n=["underline","inverse","grey","yellow","red","green","blue","white","cyan","magenta"];return function(e,t,i){return e===" "?e:Nae[n[Math.round(Math.random()*(n.length-1))]](e)}}()});var vc=w((LPe,$J)=>{var _t={};$J.exports=_t;_t.themes={};var oa=_t.styles=kJ(),YJ=Object.defineProperties;_t.supportsColor=RJ();typeof _t.enabled>"u"&&(_t.enabled=_t.supportsColor);_t.stripColors=_t.strip=function(n){return(""+n).replace(/\x1B\[\d+m/g,"")};var IPe=_t.stylize=function(e,t){return oa[t].open+e+oa[t].close},Hae=/[|\\{}()[\]^$+*?.]/g,Bae=function(n){if(typeof n!="string")throw new TypeError("Expected a string");return n.replace(Hae,"\\$&")};function ZJ(n){var e=function t(){return Wae.apply(t,arguments)};return e._styles=n,e.__proto__=qae,e}var JJ=function(){var n={};return oa.grey=oa.gray,Object.keys(oa).forEach(function(e){oa[e].closeRe=new RegExp(Bae(oa[e].close),"g"),n[e]={get:function(){return ZJ(this._styles.concat(e))}}}),n}(),qae=YJ(function(){},JJ);function Wae(){var n=arguments,e=n.length,t=e!==0&&String(arguments[0]);if(e>1)for(var i=1;i{var Jae=vc();UJ.exports=Jae});var zJ=w(wc=>{wc.repeat=function(n,e){return Array(e+1).join(n)};wc.pad=function(n,e,t,i){if(e+1>=n.length)switch(i){case"left":n=Array(e+1-n.length).join(t)+n;break;case"both":var r=Math.ceil((padlen=e-n.length)/2),o=padlen-r;n=Array(o+1).join(t)+n+Array(r+1).join(t);break;default:n=n+Array(e+1-n.length).join(t)}return n};wc.truncate=function(n,e,t){return t=t||"\u2026",n.length>=e?n.substr(0,e-t.length)+t:n};function GJ(n,e){for(var t in e)t==="__proto__"||t==="constructor"||t==="prototype"||(e[t]&&e[t].constructor&&e[t].constructor===Object?(n[t]=n[t]||{},GJ(n[t],e[t])):n[t]=e[t]);return n}wc.options=GJ;wc.strlen=function(n){var e=/\u001b\[(?:\d*;){0,5}\d*m/g,t=(""+n).replace(e,""),i=t.split(` +`);return i.reduce(function(r,o){return o.length>r?o.length:r},0)}});var KJ=w((jPe,fP)=>{var $ae=XJ(),kl=zJ(),pP=kl.repeat,Uae=kl.truncate,Xae=kl.pad;function Og(n){if(this.options=kl.options({chars:{top:"\u2500","top-mid":"\u252C","top-left":"\u250C","top-right":"\u2510",bottom:"\u2500","bottom-mid":"\u2534","bottom-left":"\u2514","bottom-right":"\u2518",left:"\u2502","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u253C",right:"\u2502","right-mid":"\u2524",middle:"\u2502"},truncate:"\u2026",colWidths:[],colAligns:[],style:{"padding-left":1,"padding-right":1,head:["red"],border:["grey"],compact:!1},head:[]},n),n&&n.rows)for(var e=0;ek&&(k=ge),C.push({contents:B,height:ge})});var X=new Array(k);C.forEach(function(Y,K){Y.contents.forEach(function(ye,Fe){X[Fe]||(X[Fe]=[]),(x||N&&K===0&&e.style.head)&&(ye=f(e.style.head,ye)),X[Fe].push(ye)});for(var B=Y.height,ge=k;B0&&(se+=` +`+f(e.style.border,r.left)),se+=Y.join(f(e.style.border,r.middle))+f(e.style.border,r.right)}),f(e.style.border,r.left)+se}function f(v,x){return x?(v.forEach(function(C){x=$ae[C](x)}),x):""}function m(C,x){var C=String(typeof C=="object"&&C.text?C.text:C),k=kl.strlen(C),T=s[x]-(t["padding-left"]||0)-(t["padding-right"]||0),j=e.colAligns[x]||"left";return pP(" ",t["padding-left"]||0)+(k==T?C:k]+)>)/ig,""))}function QJ(n,e){return e?n.replace(Kae,` +`):n}function ele(n,e){return e.replace(/(^|\n)(.+)/g,"$1"+n+"$2")}function tle(n,e){return e&&n+e.split(` +`).join(` +`+n)}function rle(n,e){let t=new RegExp("(\\S(?: | )?)((?:"+e+")+)("+n$+"(?:.*)+)$","gm");return n.replace(t,`$1 +`+e+"$2$3")}function o$(n){return" ".repeat(n.length)}function ole(n,e){return r$(e,n)?e:o$(vP)+e}function sle(n,e){let t=ole.bind(null,e);return n.split(` +`).filter(Co).map(t).join(` +`)}function ale(n,e,t){return r$(e,n)?{num:t+1,line:e.replace(vP,VJ(t+1))}:{num:t,line:o$(VJ(t))+e}}function lle(n,e){let t=ale.bind(null,e),i=0;return n.split(` +`).filter(Co).map(r=>{let o=t(r,i);return i=o.num,o.line}).join(` +`)}function ule(n,e,t){return n=n.trim(),n=e?lle(n,t):sle(n,t),n}function Ag(n){return n+` + +`}function cle(n){return n.replace(zae,":")}function e$(n,e=null){if(!n)return[];e=e||Co;let t=e(n).split(` +`),i=[];return t.forEach(function(r){if(!r)return;let o=r.replace(Gae,"").split(t$);i.push(o.splice(0,o.length-1))}),i}function s$(n){return n.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}function dle(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}var t$,bP,Gae,i$,zae,Kae,Vae,ile,nle,n$,r$,vP,VJ,mP,yP,wP,a$=D(()=>{"use strict";Be();CJ();t$="^*||*^",bP="*|*|*|*",Gae=new RegExp(s$(bP),"g"),i$="*#COLON|*",zae=new RegExp(s$(i$),"g"),Kae=/\r/g;Vae={code:Co,blockquote:Co,html:Qae,heading:cP,firstHeading:cP,hr:Co,listitem:Co,list:ule,table:Co,paragraph:Co,strong:yJ,em:wJ,codespan:xJ,del:vJ,link:dP,href:dP,text:Co,unescape:!0,emoji:!1,width:80,showSectionPrefix:!1,tab:2,tableOptions:{}};ile="\\*",nle="\\d+\\.",n$="(?:"+[ile,nle].join("|")+")";r$=function(n,e){return n.match("^(?:"+e+")*"+n$)!=null};vP="* ";VJ=function(n){return n+". "};mP=new Map,yP=class{constructor(e={},t={}){this.options=e;this.highlightOptions=t;this.o=Object.assign({},Vae,e),this.tab=" ",this.tableSettings=this.o.tableOptions,this.unescape=dle,this.highlightOptions=Ue(t),this.transform=this.compose(cle,this.unescape)}text(e){return this.o.text(e)}code(e,t,i){return"``` "+t+` +`+e+"\n```\n"}blockquote(e){return Ag(this.o.blockquote(tle(this.tab,e.trim())))}html(e){return this.o.html(e)}heading(e,t,i){return e=this.transform(e),Ag(t===1?this.o.firstHeading(e):this.o.heading(e))}hr(){return`\u2500\u2500\u2500 +`}list(e,t){return e=this.o.list(e,t,this.tab),Ag(rle(ele(this.tab,e),this.tab))}listitem(e){let t=this.compose(this.o.listitem,this.transform);return e.indexOf(` +`)!==-1&&(e=e.trim()),` +`+vP+t(e)}checkbox(e){return"["+(e?"X":" ")+"] "}paragraph(e){return e=this.compose(this.o.paragraph,this.transform)(e),Ag(e)}table(e,t){let i=KJ(),r=new i(Object.assign({},{head:e$(e)[0]},this.tableSettings));return e$(t,this.transform).forEach(function(o){r.push(o)}),Ag(this.o.table(r.toString()))}tablerow(e){return bP+e+bP+` +`}tablecell(e,t){return e+t$}strong(e){return this.o.strong(e)}em(e){return e=QJ(e,this.o.reflowText),this.o.em(e)}codespan(e){return e=QJ(e,this.o.reflowText),this.o.codespan(e.replace(/:/g,i$))}br(){return` +`}del(e){return this.o.del(e)}link(e,t,i){let r;try{r=decodeURIComponent(unescape(e)).replace(/[^\w:]/g,"").toLowerCase()}catch{return""}if(r.startsWith("javascript:"))return"";if(i&&e&&i!=e&&mP.set(i,e),i&&i!=e)return hP(i);let o=this.o.href(e);return this.o.link(o)}image(e,t,i){return"!["+i+"]("+e+")"}compose(...e){return(...t)=>{for(let i=e.length;i-- >0;)t=[e[i].apply(this,t)];return t[0]}}static getLinks(){let e=[];for(let[t,i]of mP.entries())e.push(`${hP(t)}: ${i}`);return mP.clear(),e}},wP=yP});function ble(n){if(!n)return fle;let e=hle[n];return $e(e)?e:n}function Sv(n,e={}){let t=[],i=[],r=[],o=0;for(let s of n){let a=t.length,{content:l,filetype:u}=s,c=s.highlights;if(u==gle){let d=vle(l,e);r.push(...d.codes.map(h=>(h.startLine=h.startLine+a,h.endLine=h.endLine+a,h))),i.push(...d.highlights.map(h=>(h.lnum=h.lnum+a,h))),t.push(...d.lines)}else{let d=l.trim().split(/\r?\n/),h=l$[s.filetype];$e(h)?r.push({hlGroup:h,startLine:a,endLine:a+d.length}):r.push({filetype:s.filetype,startLine:a,endLine:a+d.length}),t.push(...d)}if(Array.isArray(c)&&i.push(...c.map(d=>Object.assign({},d,{lnum:d.lnum+a}))),Array.isArray(s.active)){let d=yle(l,a,s.active);d.length&&i.push(...d)}o!=n.length-1&&(i.push({lnum:t.length,hlGroup:u$,colStart:0,colEnd:-1}),t.push(c$)),o=o+1}return{lines:t,highlights:i,codes:r}}function yle(n,e,t){let i=[],[r,o]=t,s=n.split(/\r?\n/),a=0,l=!1;for(let u=0;uo){let d=nt(c,o-a);i.push({colStart:0,colEnd:d,lnum:u+e,hlGroup:Cv}),l=!1;break}else{let d=ue(c);i.push({colStart:0,colEnd:d,lnum:u+e,hlGroup:Cv})}else if(a+c.length>r){l=!0;let d=nt(c,r-a);if(a+c.length>o){let h=nt(c,o-a);l=!1,i.push({colStart:d,colEnd:h,lnum:u+e,hlGroup:Cv});break}else{let h=ue(c);i.push({colStart:d,colEnd:h,lnum:u+e,hlGroup:Cv})}}a=a+c.length+1}return i}function vle(n,e){Ae.setOptions({renderer:new wP,gfm:!0,breaks:Pn(e.breaks)?e.breaks:!0});let t=[],i=[],r=[],o=0,s=!1,a,l=0,u=Ae(n),c=wP.getLinks();u=u.replace(/\s*$/,""),c.length&&(u=u+` + +`+c.join(` +`));let d=u.split(/\n/);for(let h=0;h{"use strict";gJ();yc();Xe();de();fe();a$();l$=(r=>(r.Error="CocErrorFloat",r.Warning="CocWarningFloat",r.Info="CocInfoFloat",r.Hint="CocHintFloat",r))(l$||{}),hle={js:"javascript",ts:"typescript",bash:"sh"},Cv="CocFloatActive",u$="CocFloatDividingLine",gle="markdown",ple="```",fle="txt",c$="\u2500",mle="\u2500\u2500\u2500"});var wle,Pl,CP=D(()=>{"use strict";de();Pe();xP();te();Re();ls();Be();U();Yt();wle=pe(100,10),Pl=class{constructor(e){this.nvim=e;this.winid=0;this._bufnr=0;this.mutex=new ji;this.disposables=[];this.onCursorMoved=ft(this._onCursorMoved.bind(this),wle)}bindEvents(e,t){let i=["InsertLeave","InsertEnter","BufEnter"];for(let r of i)_.on(r,o=>{o!=this._bufnr&&this.close()},null,this.disposables);_.on("MenuPopupChanged",()=>{_.pumAlignTop==t&&this.close()},null,this.disposables),this.disposables.push(p.Disposable.create(()=>{this.onCursorMoved.clear()})),_.on("CursorMoved",this.onCursorMoved.bind(this,e),this,this.disposables),_.on("CursorMovedI",this.onCursorMoved.bind(this,e),this,this.disposables)}unbind(){this.disposables.length&&(W(this.disposables),this.disposables=[])}_onCursorMoved(e,t,i){if(t!=this._bufnr&&!(t==this.targetBufnr&&Me(i,this.cursor))&&(t!=this.targetBufnr||!_.insertMode||e)){this.close();return}}async create(e,t=!1,i=0){await this.show(e,{offsetX:i})}async show(e,t={}){if(e.length==0||e.every(o=>o.content.length==0)){this.close();return}let i=Date.now(),r=await this.mutex.acquire();try{await this.createPopup(e,t,i),r()}catch(o){this.nvim.echoError(o),r()}}async createPopup(e,t,i){e=e.filter(m=>m.content.trim().length>0);let{lines:r,codes:o,highlights:s}=Sv(e,{excludeImages:t.excludeImages,breaks:t.breaks}),a={codes:o,highlights:s,pumAlignTop:_.pumAlignTop,preferTop:typeof t.preferTop=="boolean"?t.preferTop:!1,offsetX:t.offsetX||0,title:t.title||"",close:t.close?1:0,rounded:t.rounded?1:0,modes:t.modes||["n","i","ic","s"],zindex:1};vi||(typeof t.winblend=="number"&&(a.winblend=t.winblend),t.focusable!=null&&(a.focusable=t.focusable?1:0),t.shadow&&(a.shadow=1)),t.maxHeight&&(a.maxHeight=t.maxHeight),t.maxWidth&&(a.maxWidth=t.maxWidth),t.border===!0?a.border=[1,1,1,1]:Array.isArray(t.border)&&!t.border.every(m=>m==0)&&(a.border=t.border.slice(0,4),a.rounded=t.rounded?1:0),t.highlight&&(a.highlight=t.highlight),t.borderhighlight&&(a.borderhighlight=t.borderhighlight),t.cursorline&&(a.cursorline=1);let l=t.autoHide!==!1;l&&(a.autohide=1),this.unbind();let u=await this.nvim.call("coc#dialog#create_cursor_float",[this.winid,this._bufnr,r,a]);if(this.nvim.redrawVim(),re(u)||this.closeTs>i){let m=u&&u.length>0?u[2]:this.winid;m&&(this.winid=0,this.nvim.call("coc#float#close",[m],!0),this.nvim.redrawVim());return}let[c,d,h,g,f]=u;this.winid=h,this._bufnr=g,this.targetBufnr=c,this.cursor=d,this.bindEvents(l,f==1)}close(){let{winid:e,nvim:t}=this;this.closeTs=Date.now(),this.unbind(),e&&(this.winid=0,t.call("coc#float#close",[e],!0),t.redrawVim())}checkRetrigger(e){return!!(this.winid&&this.targetBufnr==e)}get bufnr(){return this._bufnr}get buffer(){return this.bufnr?this.nvim.createBuffer(this.bufnr):null}get window(){return this.winid?this.nvim.createWindow(this.winid):null}async activated(){return this.winid?await this.nvim.call("coc#float#valid",[this.winid])!=0:!1}dispose(){this.cursor=void 0,this.onCursorMoved.clear(),this.close()}}});async function Ng(n){let[e,t]=await n.eval("[line('.')-1, strpart(getline('.'), 0, col('.') - 1)]");return Q.create(e,t.length)}async function Dv(n){let[e,t,i]=await n.eval("[getline('.'), line('.'), strpart(getline('.'), 0, col('.') - 1)]");return{text:e,line:t-1,character:i.length}}function d$(n,e,t){let i=Object.assign({},t,e),r=new Pl(n);return{get window(){return r.window},show:(o,s)=>r.show(o,s?Object.assign({},i,s):i),activated:()=>r.activated(),dispose:()=>{r.dispose()},checkRetrigger:o=>r.checkRetrigger(o),close:()=>{r.close()}}}async function h$(n,e){return await n.callAsync("coc#dialog#prompt_confirm",[e])==1}async function g$(n,e,t){await n.call("coc#cursor#move_to",[e.line,e.character]),t&&n.command("redraw",!0)}async function p$(n){return await n.call("coc#cursor#char_offset")}async function f$(n){let[e,t]=await n.call("coc#cursor#screen_pos");return{row:e,col:t}}async function m$(n,e,t,i=!1){let r=e.cmdheight;t.length>r&&i&&(t=t.slice(0,r));let o=e.columns-12;if(t=t.map(s=>(s=s.replace(/\n/g," "),i&&(s=s.slice(0,o)),s)),i&&t.length==r){let s=t[t.length-1];t[r-1]=`${s.length>=o?s.slice(0,-4):s} ...`}await n.call("coc#ui#echo_lines",[t])}function b$(n,e,t,i){let r="Error",o=2;switch(t){case"more":o=0,r="MoreMsg";break;case"warning":o=1,r="WarningMsg";break}o>=Cle(i)&&n[vi?"callTimer":"call"]("coc#ui#echo_messages",[r,("[coc.nvim] "+e).split(` +`)],!0)}function Cle(n){switch(n){case"error":return 2;case"warning":return 1;default:return 0}}async function y$(n,e){if(e==="currline"){let i=await n.call("line",["."]);return M.create(i-1,0,i,0)}if(e==="cursor"){let i=await Ng(n);return M.create(i,i)}let t=await n.call("coc#cursor#get_selection",[xle.includes(e)?1:0]);return!t||t[0]==-1?null:M.create(t[0],t[1],t[2],t[3])}async function v$(n,e,t){let{start:i,end:r}=e,[o,s]=await n.eval(`[getline(${i.line+1}),getline(${r.line+1})]`),a=o.length>0?nt(o,i.character):0,l,u,c=r.character==0;if(c){u=r.line==0?0:r.line-1;let d=await n.call("getline",[u+1]);l=ue(d)}else u=r.line,l=s.length>0?nt(s,r.character):0;n.pauseNotification(),n.command(`noa call cursor(${i.line+1},${a+1})`,!0),n.command("normal! v",!0),n.command(`noa call cursor(${u+1},${l})`,!0),c&&n.command("normal! $",!0),await n.resumeNotification(t)}var xle,Rl=D(()=>{"use strict";ae();CP();Yt();fe();xle=["char","line","block"]});var Tv,x$=D(()=>{"use strict";Pe();qZ();iP();WZ();ZZ();GZ();te();Re();Yt();ls();Vs();wl();U();fe();uP();Rl();Tv=class{constructor(){this.mutex=new ji}async showDialog(e){return await this.mutex.use(async()=>{let t=new nv(this.nvim,e);return await t.show(this.dialogPreference),t})}async showPrompt(e){return await this.mutex.use(()=>h$(this.nvim,e))}async createQuickPick(e){return await this.mutex.use(async()=>{let t=new fc(this.nvim,this.dialogPreference);return Object.assign(t,e),t})}async showMenuPicker(e,t,i){return await this.mutex.use(async()=>{if(i&&i.isCancellationRequested)return-1;t=t||{},typeof t=="string"&&(t={title:t});let r=new Rg(this.nvim,{items:e,...t},i),o=new Promise(s=>{r.onDidClose(a=>{_.race(["BufHidden"],20).finally(()=>{s(a)})})});return await r.show(this.dialogPreference),await o})}async showQuickPick(e,t,i=p.CancellationToken.None){if(re(e))return;t=Ie(t,{});let r=await Promise.resolve(e),o=r.some(s=>typeof s=="string");return await this.mutex.use(()=>new Promise((s,a)=>{if(i.isCancellationRequested)return s(void 0);let l=new fc(this.nvim,this.dialogPreference);l.items=r.map(u=>typeof u=="string"?{label:u}:u),l.title=oe(t.title),l.placeHolder=t.placeholder,l.canSelectMany=!!t.canPickMany,l.matchOnDescription=t.matchOnDescription,l.onDidFinish(u=>{if(u==null)return s(void 0);let c=o?u.map(d=>d.label):u;if(t.canPickMany)return s(c);s(c[0])}),l.show().catch(a)}))}async showPickerDialog(e,t,i){return await this.mutex.use(async()=>{if(i&&i.isCancellationRequested)return;let r=new _g(this.nvim,{title:t,items:YZ(e)},i),o=new Promise(a=>{r.onDidClose(l=>{a(l)})});await r.show(this.dialogPreference);let s=await o;return s==null?void 0:e.filter((a,l)=>s.includes(l))})}async requestInput(e,t,i,r){let{nvim:o}=this,s=this.configuration.get("coc.preferences.promptInput"),a=!vi||fv(t,"patch-8.2.750")&&!Ur;return s&&a?await this.mutex.use(async()=>{let l=new ea(o,oe(i));return await l.show(e,Object.assign(this.inputPreference,Ie(r,{}))),await new Promise(u=>{l.onDidFinish(c=>{setTimeout(()=>{u(c)},20)})})}):await this.mutex.use(async()=>{let l=await mv(this.nvim,"input",[e+": ",oe(i)]);return o.command("normal! :",!0),l})}async createInputBox(e,t,i){let r=new ea(this.nvim,oe(t));return await r.show(e,Object.assign(this.inputPreference,Ie(i,{}))),r}get inputPreference(){let e=this.configuration.get("dialog");return{rounded:!!e.rounded,maxWidth:rn(e.maxWidth,80),highlight:Ie(e.floatHighlight,pg),borderhighlight:Ie(e.floatBorderHighlight,pg)}}get dialogPreference(){let e=this.configuration.get("dialog");return{rounded:!!e.rounded,maxWidth:rn(e.maxWidth,80),maxHeight:e.maxHeight,floatHighlight:Ie(e.floatHighlight,pg),floatBorderHighlight:Ie(e.floatBorderHighlight,pg),pickerButtons:e.pickerButtons,pickerButtonShortcut:e.pickerButtonShortcut,confirmKey:oe(e.confirmKey),shortcutHighlight:oe(e.shortcutHighlight)}}}});function kv(n){return[n.hlGroup,n.lnum,n.colStart,n.colEnd,n.combine?1:0,n.start_incl?1:0,n.end_incl?1:0]}function C$(n,e){let t=[n.hlGroup,n.lnum,n.colStart,n.colEnd];return Me(t,e.slice(0,4))}var Pv,S$=D(()=>{"use strict";te();Be();Pv=class{async diffHighlights(e,t,i,r,o){let s=[e,t];Array.isArray(r)&&s.push(r[0],r[1]-1);let a=await this.nvim.call("coc#highlight#get_highlights",s);if(!a||(o==null?void 0:o.isCancellationRequested))return null;i.sort((m,b)=>m.lnum-b.lnum);let l=[],u=[],c=[],d=0,h=i.length-1,g=0,f=new Map;if(a.forEach(m=>{g=Math.max(g,m[1]);let b=f.get(m[1]);b?b.push(m):f.set(m[1],[m])}),a.length>0){let m=Array.isArray(r)?r[0]:0;for(let b=m;b<=g;b++){let v=Ie(f.get(b),[]),x=[];for(let C=d;C<=h;C++){let k=i[C];if(k.lnum==b)d=C+1,x.push(k);else{d=C;break}}if(x.length==0)v.length>0&&(this.checkMarkers?u.push(...v.map(C=>C[4])):l.push(b));else if(v.length==0)c.push(...x.map(C=>kv(C)));else if(this.checkMarkers){let C=0,k=Math.min(v.length,x.length);for(;CT[4])),c.push(...x.slice(C).map(T=>kv(T)))}else(x.length!=v.length||!x.every((C,k)=>C$(C,v[k])))&&(l.push(b),c.push(...x.map(C=>kv(C))))}}for(let m=d;m<=h;m++)c.push(kv(i[m]));return{remove:l,add:c,removeMarkers:u}}async applyDiffHighlights(e,t,i,r,o=!1){let{nvim:s}=this,{remove:a,add:l,removeMarkers:u}=r;a.length===0&&l.length===0&&u.length===0||(s.pauseNotification(),u.length&&s.call("coc#highlight#del_markers",[e,t,u],!0),a.length&&s.call("coc#highlight#clear",[e,t,a],!0),l.length&&s.call("coc#highlight#set",[e,t,l,i],!0),o?s.resumeNotification(!0,!0):await s.resumeNotification(!0))}}});function D$(n){return n.map((e,t)=>({text:e,index:t}))}function T$(n){return n.map(e=>typeof e=="string"?e:e.title)}var sa,SP=D(()=>{"use strict";Pe();te();Re();sa=class{constructor(e,t,i=!0){this.nvim=e;this.config=t;this.disposables=[];if(i){_.on("BufWinLeave",o=>{o==this.bufnr&&(this.dispose(),t.callback&&t.callback(-1))},null,this.disposables);let r=le(t.buttons).filter(o=>o.disabled!=!0);_.on("FloatBtnClick",(o,s)=>{o==this.bufnr&&(this.dispose(),t.callback&&t.callback(r[s].index))},null,this.disposables)}}get lines(){return this.config.content?this.config.content.split(/\r?\n/):[]}async show(e){let{nvim:t}=this,{buttons:i,kind:r,title:o}=this.config,s=Object.assign({},e);if(s.kind=r??"",o&&(s.title=o),e.border&&(s.borderhighlight=r?`CocNotification${r[0].toUpperCase()}${r.slice(1)}`:e.highlight),Array.isArray(i)){let l=i.filter(u=>!u.disabled).map(u=>u.text);l.length&&(s.actions=l)}let a=await t.call("coc#notify#create",[this.lines,s]);this._winid=a[0],this.bufnr=a[1]}get winid(){return this._winid}dispose(){let{winid:e}=this;e&&(this.nvim.call("coc#notify#close",[e],!0),this.nvim.redrawVim()),this.bufnr=void 0,this._winid=void 0,W(this.disposables)}}});function k$(n,e,t){let i=[];return n&&i.push(n),e&&i.push(e),t&&i.push(t+"%"),i.join(" ")}var Sle,Hg,P$=D(()=>{"use strict";Pe();xe();U();SP();Sle=Z("model-progress");Hg=class extends sa{constructor(t,i){let r=[{index:0,text:"Cancel"}];super(t,{kind:"progress",title:i.title,buttons:i.cancellable?r:void 0},!1);this.option=i;this._onDidFinish=new p.Emitter;this.onDidFinish=this._onDidFinish.event;this.cancelProgress=t=>{t==this.bufnr&&this.tokenSource&&this.tokenSource.cancel()};this.disposables.push(this._onDidFinish),_.on("BufWinLeave",this.cancelProgress,null,this.disposables),i.cancellable&&_.on("FloatBtnClick",(o,s)=>{s==r.findIndex(a=>a.text=="Cancel")&&this.cancelProgress(o)},null,this.disposables)}async show(t){let{task:i}=this.option,r=this.tokenSource=new p.CancellationTokenSource;this.disposables.push(r);let o=0;this.config.buttons||!t.disabled?await super.show(t):Sle.warn('progress window disabled by "notification.disabledProgressSources"'),i({report:s=>{if(!this.winid)return;let{nvim:a}=this;s.increment&&(o+=s.increment,a.call("coc#window#set_var",[this.winid,"percent",`${o}%`],!0)),s.message&&a.call("coc#window#set_var",[this.winid,"message",s.message.replace(/\r?\n/g," ")],!0)}},r.token).then(s=>{this._onDidFinish.fire(s),this.dispose()},s=>{s&&this.nvim.echoError(s),this._onDidFinish.fire(void 0),this.dispose()})}}});var Rv,R$=D(()=>{"use strict";SP();P$();te();rs();Vs();U();fe();Rl();Rv=class{constructor(e){this.dialogs=e}async _showMessage(e,t,i,r){if(!this.enableMessageDialog)return await this.showConfirm(t,i,e);if(i.length>0){let o=xl(r);return await this.showMessagePicker(`Choose action (${o})`,t,`Coc${e}Float`,i)}await this.createNotification(e.toLowerCase(),t,[],r)}createNotification(e,t,i,r){return new Promise((o,s)=>{let a={kind:e,content:t,buttons:D$(i),callback:u=>{o(u)}};new sa(this.nvim,a).show(this.getNotificationPreference(r)).catch(s)})}async showMessagePicker(e,t,i,r){let o=r.map(a=>typeof a=="string"?a:a.title),s=await this.dialogs.showMenuPicker(o,{position:"center",content:t,title:e.replace(/\r?\n/," "),borderhighlight:i});return r[s]}async showConfirm(e,t,i){if(!t||t.length==0){let a=i=="Info"?"more":i=="Error"?"error":"warning";this.echoMessages(e,a);return}let o=T$(t).map((a,l)=>`${l+1}${a}`),s=await this.nvim.callAsync("coc#util#with_callback",["confirm",[e,o.join(` +`),0,i]]);return t[s-1]}echoMessages(e,t){let i=this.configuration.get("coc.preferences.messageLevel","more");b$(this.nvim,e,t,i)}async showNotification(e,t){await new sa(this.nvim,e).show(this.getNotificationPreference(t))}async withProgress(e,t){let i=this.configuration.get("notification"),r=Error().stack;if(i.statusLineProgress)return await this.createStatusLineProgress(e,t);let o=new Hg(this.nvim,{task:t,title:e.title,cancellable:e.cancellable}),s=rn(i.minProgressWidth,30),a=new Promise(l=>{o.onDidFinish(l)});return await o.show(Object.assign(this.getNotificationPreference(r,e.source),{minWidth:s})),await a}async createStatusLineProgress(e,t){let{title:i}=e,r=this.statusLine.createStatusBarItem(0,!0);r.text=oe(i),r.show();let o=0,s=await t({report:a=>{a.increment&&(o+=a.increment),r.text=k$(i,a.message,o)}},p.CancellationToken.None);return r.dispose(),s}get enableMessageDialog(){return this.configuration.get("coc.preferences.enableMessageDialog",!1)}getNotificationPreference(e,t){t||(t=xl(e));let i=this.configuration.get("notification"),r=Ie(i.disabledProgressSources,[]),o=Array.isArray(r)&&(r.includes("*")||r.includes(t));return{border:i.border,focusable:i.focusable,marginRight:rn(i.marginRight,10),timeout:rn(i.timeout,1e4),maxWidth:rn(i.maxWidth,60),maxHeight:rn(i.maxHeight,10),highlight:i.highlightGroup,winblend:rn(i.winblend,30),disabled:o,source:t}}}});var _v,_$=D(()=>{"use strict";_v=class{constructor(e,t,i,r,o){this.cmd=e;this.args=t;this.nvim=i;this._name=r;this.strictEnv=o;this.pid=0}async start(e,t){let{nvim:i}=this,r=[this.cmd,...this.args],[o,s]=await i.call("coc#terminal#start",[r,e,t||{},!!this.strictEnv]);this.bufnr=o,this.pid=s}onExit(e){this.exitStatus={code:e===-1?void 0:e}}get name(){return this._name||this.cmd}get processId(){return Promise.resolve(this.pid)}sendText(e,t=!0){!this.bufnr||this.nvim.call("coc#terminal#send",[this.bufnr,e,t],!0)}async show(e){let{bufnr:t,nvim:i}=this;if(!t)return!1;let[r,o,s]=await i.eval(`[bufloaded(${t}),win_getid(),win_findbuf(${t})]`);if(!r)return!1;let a=s[0];return a&&o==a||(i.pauseNotification(),a?i.call("win_gotoid",[a],!0):(i.command(`below ${t}sb`,!0),i.command("resize 8",!0),i.call("coc#util#do_autocmd",["CocTerminalOpen"],!0)),i.command("normal! G",!0),e&&i.command("wincmd p",!0),await i.resumeNotification()),!0}async hide(){let{bufnr:e,nvim:t}=this;!e||await t.eval(`coc#window#close(bufwinid(${e}))`)}dispose(){this.exitStatus||(this.exitStatus={code:void 0});let{bufnr:e,nvim:t}=this;!e||(this.bufnr=void 0,t.call("coc#terminal#close",[e],!0))}}});var Bg,E$=D(()=>{"use strict";Pe();_$();te();Be();U();Bg=class{constructor(){this._terminals=new Map;this.disposables=[];this._onDidOpenTerminal=new p.Emitter;this._onDidCloseTerminal=new p.Emitter;this.onDidCloseTerminal=this._onDidCloseTerminal.event;this.onDidOpenTerminal=this._onDidOpenTerminal.event;_.on("BufUnload",e=>{if(this._terminals.has(e)){let t=this._terminals.get(e);this._onDidCloseTerminal.fire(t),this._terminals.delete(e)}},null,this.disposables),_.on("TermExit",(e,t)=>{let i=this._terminals.get(e);i&&(i.onExit(t),i.dispose())},null,this.disposables)}get terminals(){return Array.from(this._terminals.values())}async createTerminal(e,t){let i=t.cwd,r=t.shellPath,o=t.shellArgs;r||(r=await e.getOption("shell")),i||(i=await e.call("getcwd"));let s=new _v(r,o||[],e,t.name,t.strictEnv);return await s.start(i,t.env),this._terminals.set(s.bufnr,s),this._onDidOpenTerminal.fire(s),s}async runTerminalCommand(e,t,i,r=!1){return await e.callAsync("coc#ui#run_terminal",{cmd:t,cwd:i,keepfocus:r?1:0})}async openTerminal(e,t,i){return await e.call("coc#ui#open_terminal",{cmd:t,...Ue(i)})}reset(){for(let e of this._terminals.values())e.dispose();this._terminals.clear()}dispose(){this._onDidOpenTerminal.dispose(),this._onDidCloseTerminal.dispose(),W(this.disposables),this.reset()}}});var I$=w((p_e,Dle)=>{Dle.exports={description:"Configuration file for coc.nvim",additionalProperties:!1,definitions:{floatConfig:{type:"object",properties:{border:{type:"boolean",default:!1,description:"Set to true to use borders."},rounded:{type:"boolean",default:!1,description:"Use rounded borders when border is true."},highlight:{type:"string",default:"CocFloating",description:"Background highlight group of float window."},title:{type:"string",default:"",description:"Title used by float window."},borderhighlight:{type:"string",default:"CocFloating",description:"Border highlight group of float window."},close:{type:"boolean",default:!1,description:"Set to true to draw close icon"},maxWidth:{type:"integer",description:"Maximum width of float window, include border."},maxHeight:{type:"integer",minimum:2,description:"Maximum height of float window, include border."},focusable:{type:"boolean",default:!0,description:"Enable focus by user actions (wincmds, mouse events), neovim only."},shadow:{type:"boolean",default:!1,description:"Drop shadow effect by blending with the background, neovim only."},winblend:{type:"integer",default:0,minimum:0,maximum:100,description:"Enables pseudo-transparency by set 'winblend' option of window, neovim only."}}},"languageserver.enable":{type:"boolean",description:"Enable the languageserver, restart coc.nvim required after change.",default:!0},"languageserver.filetypes":{type:"array",default:[],description:"Supported filetypes, add * in array for all filetypes.",items:{type:"string"}},"languageserver.cwd":{type:"string",default:"",description:"Working directory of languageserver, absolute path or relative to workspace folder, use workspace root by default"},"languageserver.settings":{type:"object",default:{},description:"Settings of languageserver"},"languageserver.initializationOptions":{type:"object",default:{},description:"initializationOptions passed to languageserver"},"languageserver.env":{type:"object",default:null,description:"Environment variables for child process."},"languageserver.stdioEncoding":{type:"string",default:"utf8",description:"Encoding used for stdio of child process."},"languageserver.rootPatterns":{type:"array",default:[],description:"Root patterns used to resolve rootPath from current file, default to workspace root",items:{type:"string"}},"languageserver.requireRootPattern":{type:"boolean",default:!1,description:"If true, doesn't start server when root pattern not found."},"languageserver.ignoredRootPaths":{type:"array",default:[],description:"Absolute root paths that language server should not use as rootPath, higher priority than rootPatterns.",items:{type:"string"}},"languageserver.additionalSchemes":{type:"array",default:[],description:"Additional URI schemes, default schemes including file & untitled.",items:{type:"string"}},"languageserver.revealOutputChannelOn":{type:"string",default:"never",description:"Configure message level to show the output channel buffer",enum:["info","warn","error","never"]},"languageserver.progressOnInitialization":{type:"boolean",default:!1,description:"Enable progress report on languageserver initialize."},"languageserver.trace.server":{type:"string",default:"off",enum:["off","messages","verbose"],description:"Trace level of communication between server and client"},"languageserver.trace.server.verbosity":{type:"string",default:"off",enum:["off","messages","verbose"],description:"Trace level of communication between server and client"},"languageserver.trace.server.format":{type:"string",default:"text",enum:["text","json"],description:"Text format of trace messages."},"languageserver.disableDynamicRegister":{type:"boolean",default:!1,description:"Disable dynamic registerCapability feature for this languageserver to avoid duplicate feature registration."},"languageserver.disableSnippetCompletion":{type:"boolean",default:!1,description:"Disable completion snippet feature for this languageserver, the languageserver may not respect it."},"languageserver.disabledFeatures":{type:"array",default:[],description:"Disabled features for this languageserver.",items:{type:"string",enum:["completion","configuration","workspaceFolders","diagnostics","willSave","willSaveUntil","didSaveTextDocument","fileSystemWatcher","hover","signatureHelp","definition","references","documentHighlight","documentSymbol","workspaceSymbol","codeAction","codeLens","formatting","documentFormatting","documentRangeFormatting","documentOnTypeFormatting","rename","documentLink","executeCommand","pullConfiguration","typeDefinition","implementation","declaration","color","foldingRange","selectionRange","progress","callHierarchy","linkedEditing","inlayHint","inlineValue","typeHierarchy","pullDiagnostic","fileEvents","semanticTokens"]}},"languageserver.formatterPriority":{type:"number",default:0,description:"Priority of this languageserver's formatter."},languageServerSocket:{type:"object",required:["port","filetypes"],additionalProperties:!1,properties:{port:{type:"integer",description:"Port number of socket server"},host:{type:"string",default:"127.0.0.1",description:"Host of server"},enable:{$ref:"#/definitions/languageserver.enable"},disableSnippetCompletion:{$ref:"#/definitions/languageserver.disableSnippetCompletion"},disableDynamicRegister:{$ref:"#/definitions/languageserver.disableDynamicRegister"},disabledFeatures:{$ref:"#/definitions/languageserver.disabledFeatures"},formatterPriority:{$ref:"#/definitions/languageserver.formatterPriority"},rootPatterns:{$ref:"#/definitions/languageserver.rootPatterns"},requireRootPattern:{$ref:"#/definitions/languageserver.requireRootPattern"},ignoredRootPaths:{$ref:"#/definitions/languageserver.ignoredRootPaths"},filetypes:{$ref:"#/definitions/languageserver.filetypes"},additionalSchemes:{$ref:"#/definitions/languageserver.additionalSchemes"},revealOutputChannelOn:{$ref:"#/definitions/languageserver.revealOutputChannelOn"},progressOnInitialization:{$ref:"#/definitions/languageserver.progressOnInitialization"},initializationOptions:{$ref:"#/definitions/languageserver.initializationOptions"},settings:{$ref:"#/definitions/languageserver.settings"},stdioEncoding:{$ref:"#/definitions/languageserver.stdioEncoding"},"trace.server":{$ref:"#/definitions/languageserver.trace.server"},"trace.server.verbosity":{$ref:"#/definitions/languageserver.trace.server.verbosity"},"trace.server.format":{$ref:"#/definitions/languageserver.trace.server.format"}}},languageServerModule:{type:"object",required:["module","filetypes"],additionalProperties:!1,properties:{module:{type:"string",default:"",description:"Absolute path of Javascript file, should works in IPC mode"},args:{type:"array",default:[],description:"Extra arguments of module",items:{type:"string"}},runtime:{type:"string",default:"",description:"Absolute path of node runtime."},execArgv:{type:"array",default:[],description:'ARGV passed to node when using module, normally used for debugging, ex: ["--nolazy", "--inspect-brk=6045"]',items:{type:"string"}},transport:{type:"string",default:"ipc",description:"Transport kind used by server, could be 'ipc', 'stdio', 'socket' and 'pipe'",enum:["ipc","stdio","socket","pipe"]},transportPort:{type:"integer",description:"Port number used when transport is 'socket'"},enable:{$ref:"#/definitions/languageserver.enable"},disableSnippetCompletion:{$ref:"#/definitions/languageserver.disableSnippetCompletion"},disableDynamicRegister:{$ref:"#/definitions/languageserver.disableDynamicRegister"},disabledFeatures:{$ref:"#/definitions/languageserver.disabledFeatures"},formatterPriority:{$ref:"#/definitions/languageserver.formatterPriority"},rootPatterns:{$ref:"#/definitions/languageserver.rootPatterns"},requireRootPattern:{$ref:"#/definitions/languageserver.requireRootPattern"},ignoredRootPaths:{$ref:"#/definitions/languageserver.ignoredRootPaths"},filetypes:{$ref:"#/definitions/languageserver.filetypes"},additionalSchemes:{$ref:"#/definitions/languageserver.additionalSchemes"},revealOutputChannelOn:{$ref:"#/definitions/languageserver.revealOutputChannelOn"},progressOnInitialization:{$ref:"#/definitions/languageserver.progressOnInitialization"},initializationOptions:{$ref:"#/definitions/languageserver.initializationOptions"},settings:{$ref:"#/definitions/languageserver.settings"},stdioEncoding:{$ref:"#/definitions/languageserver.stdioEncoding"},"trace.server":{$ref:"#/definitions/languageserver.trace.server"},"trace.server.verbosity":{$ref:"#/definitions/languageserver.trace.server.verbosity"},"trace.server.format":{$ref:"#/definitions/languageserver.trace.server.format"}}},languageServerCommand:{type:"object",required:["command","filetypes"],additionalProperties:!1,properties:{command:{type:"string",default:"",description:"Executable in $PATH to start languageserver, should not used with module"},args:{type:"array",default:[],description:"Arguments of command",items:{type:"string"}},detached:{type:"boolean",default:!1,description:"Detach the languageserver process"},shell:{type:"boolean",default:!1,description:"Use shell for process"},enable:{$ref:"#/definitions/languageserver.enable"},disableSnippetCompletion:{$ref:"#/definitions/languageserver.disableSnippetCompletion"},disableDynamicRegister:{$ref:"#/definitions/languageserver.disableDynamicRegister"},disabledFeatures:{$ref:"#/definitions/languageserver.disabledFeatures"},formatterPriority:{$ref:"#/definitions/languageserver.formatterPriority"},rootPatterns:{$ref:"#/definitions/languageserver.rootPatterns"},requireRootPattern:{$ref:"#/definitions/languageserver.requireRootPattern"},ignoredRootPaths:{$ref:"#/definitions/languageserver.ignoredRootPaths"},filetypes:{$ref:"#/definitions/languageserver.filetypes"},additionalSchemes:{$ref:"#/definitions/languageserver.additionalSchemes"},revealOutputChannelOn:{$ref:"#/definitions/languageserver.revealOutputChannelOn"},progressOnInitialization:{$ref:"#/definitions/languageserver.progressOnInitialization"},initializationOptions:{$ref:"#/definitions/languageserver.initializationOptions"},settings:{$ref:"#/definitions/languageserver.settings"},stdioEncoding:{$ref:"#/definitions/languageserver.stdioEncoding"},"trace.server":{$ref:"#/definitions/languageserver.trace.server"},"trace.server.verbosity":{$ref:"#/definitions/languageserver.trace.server.verbosity"},"trace.server.format":{$ref:"#/definitions/languageserver.trace.server.format"}}}},properties:{"callHierarchy.enableTooltip":{type:"boolean",scope:"application",default:!0,description:"Enable tooltip to show relative filepath of call hierarchy."},"callHierarchy.openCommand":{type:"string",scope:"application",default:"edit",description:"Open command for callHierarchy tree view."},"callHierarchy.splitCommand":{type:"string",scope:"application",default:"botright 30vs",description:"Window split command used by callHierarchy tree view."},"coc.preferences.rootPatterns":{type:["array","null"],default:null,scope:"application",description:"Root patterns to resolve workspaceFolder from parent folders of opened files, resolved from up to down.",deprecationMessage:"Use 'workspace.rootPatterns' instead.",items:{type:"string"}},"coc.preferences.bracketEnterImprove":{type:"boolean",scope:"language-overridable",description:"Improve enter inside bracket `<> {} [] ()` by add new empty line below and place cursor to it. Works with `coc#on_enter()`",default:!0},"coc.preferences.currentFunctionSymbolAutoUpdate":{type:"boolean",scope:"language-overridable",description:"Automatically update the value of b:coc_current_function on CursorHold event",default:!1},"coc.preferences.enableLinkedEditing":{type:"boolean",scope:"language-overridable",default:!1,description:"Enable linked editing support."},"coc.preferences.enableMarkdown":{type:"boolean",scope:"application",description:"Tell the language server that markdown text format is supported, note that markdown text may not rendered as expected.",default:!0},"coc.preferences.enableMessageDialog":{type:"boolean",scope:"application",default:!1,description:"Enable messages shown in notification dialog."},"coc.preferences.excludeImageLinksInMarkdownDocument":{type:"boolean",description:"Exclude image links from markdown text in float window.",scope:"application",default:!0},"coc.preferences.enableGFMBreaksInMarkdownDocument":{type:"boolean",description:"Exclude GFM breaks in markdown document.",scope:"application",default:!0},"coc.preferences.extensionUpdateCheck":{type:"string",scope:"application",default:"never",description:"Interval for check extension update, could be daily, weekly, never",enum:["daily","weekly","never"]},"coc.preferences.floatActions":{type:"boolean",scope:"application",description:"Set to false to disable float/popup support for actions menu.",default:!0},"coc.preferences.formatOnSave":{type:"boolean",description:"Set to true to enable formatting on save.",scope:"language-overridable",default:!1},"coc.preferences.formatOnSaveFiletypes":{type:["null","array"],scope:"resource",default:null,description:"Filetypes that should run format on save.",deprecationMessage:"Use coc.preferences.formatOnSave as language override configuration instead, see :h coc-configuration-scope",items:{type:"string"}},"coc.preferences.formatOnType":{type:"boolean",description:"Set to true to enable formatting on typing.",scope:"language-overridable",default:!1},"coc.preferences.formatOnTypeFiletypes":{type:["null","array"],default:null,scope:"resource",description:"Filetypes that should run format on typing, only works when `coc.preferences.formatOnType` is `true`",deprecationMessage:"Use coc.preferences.formatOnType as language override configuration instead, see :h coc-configuration-scope",items:{type:"string"}},"coc.preferences.jumpCommand":{anyOf:[{type:"string",enum:["edit","split","vsplit","tabe","drop","tab drop","pedit"]},{type:"string",minimum:1}],scope:"application",description:"Command used for location jump, like goto definition, goto references etc. Can be also a custom command that gives file as an argument.",default:"edit"},"coc.preferences.maxFileSize":{type:"string",scope:"application",default:"10MB",description:"Maximum file size in bytes that coc.nvim should handle, default '10MB'"},"coc.preferences.messageLevel":{type:"string",scope:"application",description:"Message level for filter echoed messages, could be 'more', 'warning' and 'error'",default:"more",enum:["more","warning","error"]},"coc.preferences.promptInput":{type:"boolean",description:"Use prompt buffer in float window for user input.",scope:"application",default:!0},"coc.preferences.renameFillCurrent":{type:"boolean",scope:"application",default:!0,description:"Disable to stop Refactor-Rename float/popup window from populating with old name in the New Name field."},"coc.preferences.silentAutoupdate":{type:"boolean",description:"Not open split window with update status when performing auto update.",scope:"application",default:!0},"coc.preferences.useQuickfixForLocations":{type:"boolean",scope:"application",description:`Use vim's quickfix list for jump locations, + need restart on change.`,default:!1},"coc.preferences.watchmanPath":{type:"string",scope:"application",description:"executable path for https://facebook.github.io/watchman/, detected from $PATH by default",default:null},"coc.preferences.willSaveHandlerTimeout":{type:"integer",scope:"application",default:500,minimum:200,maximum:5e3,description:"Will save handler timeout"},"coc.source.around.disableSyntaxes":{type:"array",default:[],scope:"application",items:{type:"string"}},"coc.source.around.enable":{type:"boolean",scope:"application",default:!0},"coc.source.around.priority":{type:"integer",scope:"application",default:1},"coc.source.around.shortcut":{type:"string",scope:"application",default:"A"},"coc.source.buffer.disableSyntaxes":{type:"array",default:[],scope:"application",items:{type:"string"}},"coc.source.buffer.enable":{type:"boolean",scope:"application",default:!0},"coc.source.buffer.ignoreGitignore":{type:"boolean",default:!0,scope:"application",description:"Ignore git ignored files for buffer words"},"coc.source.buffer.priority":{type:"integer",scope:"application",default:1},"coc.source.buffer.shortcut":{type:"string",scope:"application",default:"B"},"coc.source.file.disableSyntaxes":{type:"array",default:[],scope:"application",items:{type:"string"}},"coc.source.file.enable":{type:"boolean",scope:"application",default:!0},"coc.source.file.ignoreHidden":{type:"boolean",scope:"application",default:!0,description:"Ignore completion for hidden files"},"coc.source.file.ignorePatterns":{type:"array",scope:"application",default:[],description:"Ignore patterns of matcher",items:{type:"string"}},"coc.source.file.priority":{type:"integer",scope:"application",default:10},"coc.source.file.shortcut":{type:"string",scope:"application",default:"F"},"coc.source.file.triggerCharacters":{type:"array",default:["/","\\"],scope:"application",items:{type:"string"}},"coc.source.file.trimSameExts":{type:"array",scope:"application",default:[".ts",".js"],description:"Trim same extension on file completion",items:{type:"string"}},"codeLens.enable":{type:"boolean",scope:"language-overridable",description:"Enable codeLens feature, require neovim with set virtual text feature.",default:!1},"codeLens.position":{type:"string",scope:"resource",enum:["top","eol","right_align"],description:"Position of codeLens, requires nvim >= 0.6.0",default:"top"},"codeLens.separator":{type:"string",scope:"resource",description:"Separator text for codeLens in virtual text",default:""},"codeLens.subseparator":{type:"string",scope:"resource",description:"Subseparator between codeLenses in virtual text",default:" | "},"colors.enable":{type:"boolean",scope:"language-overridable",description:"Enable colors highlight feature, for termainal vim, 'termguicolors' option should be enabled and the termainal support gui colors.",default:!1},"colors.filetypes":{type:["array","null"],default:null,scope:"resource",deprecationMessage:"Use colors.enable as language override configuration instead, see :h coc-configuration-scope",description:'Filetypes that should be enabled for colors highlight feature, use "*" for all filetypes.',items:{type:"string"}},"colors.highlightPriority":{type:"number",scope:"application",description:"Priority for colors highlights, works on vim8 and neovim >= 0.6.0",default:1e3,maximum:4096},"cursors.cancelKey":{type:"string",scope:"application",default:"",description:"Key used for cancel cursors session."},"cursors.nextKey":{type:"string",scope:"application",default:"",description:"Key used for jump to next cursors position."},"cursors.previousKey":{type:"string",scope:"application",default:"",description:"Key used for jump to previous cursors position."},"cursors.wrapscan":{type:"boolean",scope:"application",default:!0,description:"Searches wrap around the first or last cursors range."},"diagnostic.autoRefresh":{type:"boolean",scope:"language-overridable",description:"Enable automatically refresh diagnostics, use diagnosticRefresh action when it's disabled.",default:!0},"diagnostic.checkCurrentLine":{type:"boolean",scope:"language-overridable",description:"When enabled, show all diagnostics of current line if there are none at the current position.",default:!1},"diagnostic.displayByAle":{type:"boolean",scope:"language-overridable",description:"Use Ale for display diagnostics in vim, will disable coc for display diagnostics, restart required on change.",default:!1},"diagnostic.enable":{type:"boolean",scope:"language-overridable",description:"Set to false to disable diagnostic display",default:!0},"diagnostic.enableHighlightLineNumber":{type:"boolean",scope:"application",default:!0,description:"Enable highlighting line numbers for diagnostics, only works with neovim."},"diagnostic.enableMessage":{type:"string",scope:"application",default:"always",description:"When to enable show messages of diagnostics.",enum:["always","jump","never"]},"diagnostic.enableSign":{type:"boolean",scope:"language-overridable",default:!0,description:"Enable signs for diagnostics."},"diagnostic.errorSign":{type:"string",scope:"application",description:"Text of error sign",default:">>"},"diagnostic.filetypeMap":{type:"object",scope:"application",description:'A map between buffer filetype and the filetype assigned to diagnostics. To syntax highlight diagnostics with their parent buffer type use `"default": "bufferType"`',default:{}},"diagnostic.floatConfig":{type:"object",scope:"application",description:"Configure float window style of diagnostic message.",allOf:[{$ref:"#/definitions/floatConfig"}],additionalProperties:!1,properties:{border:{},rounded:{},highlight:{},borderhighlight:{},title:{},close:{},maxHeight:{},maxWidth:{},winblend:{},focusable:{},shadow:{}}},"diagnostic.format":{type:"string",scope:"language-overridable",description:"Define the diagnostic format that shown in float window or echoed, available parts: source, code, severity, message",default:"%message (%source%code)"},"diagnostic.highlightLimit":{type:"number",scope:"language-overridable",description:"Limit count for highlighted diagnostics, too many diagnostic highlights could make vim stop responding",default:1e3},"diagnostic.highlightPriority":{type:"number",scope:"language-overridable",description:"Priority for diagnostic highlights, works on vim8 and neovim >= 0.6.0",default:4096,maximum:4096,minimum:110},"diagnostic.hintSign":{type:"string",scope:"application",description:"Text of hint sign",default:">>"},"diagnostic.infoSign":{type:"string",scope:"application",description:"Text of info sign",default:">>"},"diagnostic.level":{type:"string",scope:"resource",description:"Used for filter diagnostics by diagnostic severity.",default:"hint",enum:["hint","information","warning","error"]},"diagnostic.locationlistLevel":{type:["string","null"],scope:"language-overridable",description:"Filter diagnostics in locationlist.",default:null,enum:["hint","information","warning","error"]},"diagnostic.locationlistUpdate":{type:"boolean",scope:"language-overridable",description:"Update locationlist on diagnostics change, only works with locationlist opened by :CocDiagnostics command and first window of associated buffer.",default:!0},"diagnostic.messageDelay":{type:"number",scope:"application",description:"How long to wait (in milliseconds) before displaying the diagnostic message with echo or float",default:200},"diagnostic.messageLevel":{type:["string","null"],scope:"language-overridable",description:"Filter diagnostic message in float window/popup.",default:null,enum:["hint","information","warning","error"]},"diagnostic.messageTarget":{type:"string",scope:"language-overridable",description:"Diagnostic message target.",default:"float",enum:["echo","float"]},"diagnostic.refreshOnInsertMode":{type:"boolean",scope:"language-overridable",description:"Enable diagnostic refresh on insert mode, default false.",default:!1},"diagnostic.separateRelatedInformationAsDiagnostics":{type:"boolean",default:!1,scope:"application",description:"Separate related information as diagnostics."},"diagnostic.showDeprecated":{type:"boolean",default:!0,scope:"language-overridable",description:"Show diagnostics with deprecated tag."},"diagnostic.showUnused":{type:"boolean",default:!0,scope:"language-overridable",description:"Show diagnostics with unused tag, affects highlight, sign, virtual text, message"},"diagnostic.signLevel":{type:["string","null"],scope:"language-overridable",description:"Filter diagnostics displayed in signcolumn.",default:null,enum:["hint","information","warning","error"]},"diagnostic.signPriority":{type:"number",scope:"resource",description:"Priority of diagnostic signs, default to 10",default:10},"diagnostic.virtualText":{type:"boolean",scope:"language-overridable",description:"Use virtual text to display diagnostics, requires neovim >= 0.5.0 or vim >= 9.0.0067.",default:!1},"diagnostic.virtualTextAlign":{type:"string",scope:"language-overridable",description:"Position of virtual text, default 'after'. Vim9 only",default:"after",enum:["after","right","below"]},"diagnostic.virtualTextCurrentLineOnly":{type:"boolean",scope:"language-overridable",description:"Only show virtualText diagnostic on current cursor line",default:!0},"diagnostic.virtualTextFormat":{type:"string",scope:"language-overridable",description:"Define the virtual text diagnostic format, available parts: source, code, severity, message",default:"%message"},"diagnostic.virtualTextLevel":{type:["string","null"],scope:"language-overridable",description:"Filter diagnostic message in virtual text by level",default:null,enum:["hint","information","warning","error"]},"diagnostic.virtualTextLimitInOneLine":{type:"integer",scope:"language-overridable",minimum:1,description:"The maximum number of diagnostic messages to disaply in one line",default:999},"diagnostic.virtualTextLineSeparator":{type:"string",scope:"language-overridable",description:"The text that will mark a line end from the diagnostic message",default:" \\ "},"diagnostic.virtualTextLines":{type:"number",scope:"language-overridable",description:"The number of non empty lines from a diagnostic to display",default:3},"diagnostic.virtualTextPrefix":{type:"string",scope:"language-overridable",description:"The prefix added virtual text diagnostics",default:" "},"diagnostic.virtualTextWinCol":{type:["number","null"],scope:"language-overridable",description:"Window column number to align virtual text, neovim only.",default:null},"diagnostic.warningSign":{type:"string",scope:"application",description:"Text of warning sign",default:"\u26A0"},"dialog.confirmKey":{type:"string",default:"",scope:"application",description:"Confirm key for confirm selection used by menu and picker, you can always use to cancel."},"dialog.floatBorderHighlight":{type:["string","null"],default:null,scope:"application",description:"Highlight group for border of dialog window/popup, default to 'CocFloating'"},"dialog.floatHighlight":{type:["string","null"],default:null,scope:"application",description:"Highlight group for dialog window/popup, default to 'CocFloating'"},"dialog.maxHeight":{type:"number",default:30,scope:"application",description:"Maximum height of dialog window."},"dialog.maxWidth":{type:"number",default:80,scope:"application",description:"Maximum width of dialog window."},"dialog.pickerButtonShortcut":{type:"boolean",default:!0,scope:"application",description:"Show shortcut in buttons of picker dialog window/popup, used when dialog.pickerButtons is true."},"dialog.pickerButtons":{type:"boolean",default:!0,scope:"application",description:"Show buttons for picker dialog window/popup."},"dialog.rounded":{type:"boolean",default:!0,scope:"application",description:"use rounded border for dialog window."},"dialog.shortcutHighlight":{type:"string",default:"MoreMsg",scope:"application",description:"Highlight group for shortcut character in menu dialog, default to 'MoreMsg'"},"documentHighlight.priority":{type:"number",default:-1,scope:"resource",description:"Match priority used by document highlight, see ':h matchadd'"},"documentHighlight.timeout":{type:"integer",default:300,minimum:200,maximum:5e3,scope:"resource",description:"Timeout for document highlight, in milliseconds."},"floatFactory.floatConfig":{type:"object",scope:"application",description:"Configure default style float window/popup created by float factory (created around cursor and automatically closed)",allOf:[{$ref:"#/definitions/floatConfig"}],additionalProperties:!1,properties:{border:{},rounded:{},highlight:{},borderhighlight:{},title:{},close:{},maxWidth:{},maxHeight:{},winblend:{},focusable:{},shadow:{}}},"hover.autoHide":{type:"boolean",scope:"application",default:!0,description:"Automatically hide hover float window on CursorMove or InsertEnter."},"hover.floatConfig":{type:"object",scope:"application",description:"Configure float window style of hover documents.",allOf:[{$ref:"#/definitions/floatConfig"}],additionalProperties:!1,properties:{border:{},rounded:{},highlight:{},borderhighlight:{},title:{},close:{},maxHeight:{},maxWidth:{},winblend:{},focusable:{},shadow:{}}},"hover.previewMaxHeight":{type:"number",scope:"resource",default:12,description:"Max height of preview window for hover."},"hover.target":{type:"string",default:"float",scope:"resource",description:"Target to show hover information, default is floating window when possible.",enum:["preview","echo","float"]},"http.proxy":{type:"string",default:"",pattern:"^https?://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$",description:"The proxy setting to use. If not set, will be inherited from the `http_proxy` and `https_proxy` environment variables.",scope:"application"},"http.proxyAuthorization":{type:["null","string"],description:"The value to send as the `Proxy-Authorization` header for every network request.",default:null,scope:"application"},"http.proxyCA":{type:"string",description:"CA (file) to use as Certificate Authority",default:null,scope:"application"},"http.proxyStrictSSL":{type:"boolean",description:"Controls whether the proxy server certificate should be verified against the list of supplied CAs",default:!0,scope:"application"},"inlayHint.enable":{type:"boolean",default:!0,scope:"language-overridable",description:"Enable inlay hint support"},"inlayHint.enableParameter":{type:"boolean",scope:"language-overridable",default:!0,description:"Enable inlay hints for parameters."},"inlayHint.display":{type:"boolean",scope:"language-overridable",default:!0,description:"Display inlay hints."},"inlayHint.filetypes":{type:["array","null"],scope:"application",description:"Filetypes that enable inlayHint, all filetypes are enabled by default",deprecationMessage:"Use inlayHint.enable with language scope instead, see :h coc-configuration-scope",default:null,items:{type:"string"}},"inlayHint.parameterSeparator":{type:"string",scope:"language-overridable",default:"",description:"Separator for parameter inlay hint, neovim only."},"inlayHint.refreshOnInsertMode":{type:"boolean",default:!1,scope:"language-overridable",description:"Refresh inlayHints on insert mode."},"inlayHint.subSeparator":{type:"string",scope:"language-overridable",default:" ",description:"Separator for chained inlay hints, neovim only."},"inlayHint.typeSeparator":{type:"string",scope:"language-overridable",default:"",description:"Separator for type inlay hint, neovim only."},"links.enable":{type:"boolean",scope:"language-overridable",description:"Enable document links",default:!0},"links.tooltip":{type:"boolean",scope:"application",description:"Show tooltip of link under cursor on CursorHold.",default:!1},"links.highlight":{type:"boolean",scope:"application",description:"Use CocLink highlight group to highlight links",default:!1},"list.floatPreview":{type:"boolean",default:!1,scope:"application",description:"Enable preview with float window/popup, default: `false`"},"list.alignColumns":{type:"boolean",default:!1,scope:"application",description:"Whether to align lists in columns, default: `false`"},"list.extendedSearchMode":{type:"boolean",scope:"application",default:!0,description:"Enable extended search mode which allows multiple search patterns delimited by spaces."},"list.height":{type:"number",scope:"application",default:10,description:"Height of split list window."},"list.indicator":{type:"string",default:">",scope:"application",description:"The character used as first character in prompt line."},"list.insertMappings":{type:"object",scope:"application",default:{},description:"Custom keymappings on insert mode."},"list.interactiveDebounceTime":{type:"number",default:100,scope:"application",description:"Debounce time for input change on interactive mode."},"list.limitLines":{type:["number","null"],scope:"application",default:null,description:"Limit lines for list buffer."},"list.maxPreviewHeight":{type:"number",scope:"application",default:12,description:"Max height for preview window of list."},"list.menuAction":{type:"boolean",default:!1,scope:"application",description:"Use menu picker instead of confirm() for choose action."},"list.nextKeymap":{type:"string",scope:"application",default:"",description:"Key used for select next line on insert mode."},"list.normalMappings":{type:"object",scope:"application",default:{},description:"Custom keymappings on normal mode."},"list.previewHighlightGroup":{type:"string",scope:"application",default:"Search",description:"Highlight group used for highlight the range in preview window."},"list.previewSplitRight":{type:"boolean",scope:"application",default:!1,description:"Use vsplit for preview window."},"list.previewToplineOffset":{type:"number",scope:"application",default:3,description:"Topline offset for list previews"},"list.previewToplineStyle":{type:"string",scope:"application",default:"offset",description:"Topline style for list previews",enum:["offset","middle"]},"list.previousKeymap":{type:"string",scope:"application",default:"",description:"Key used for select previous line on insert mode."},"list.selectedSignText":{type:"string",scope:"application",default:"*",description:"Sign text for selected lines."},"list.signOffset":{type:"number",scope:"application",default:900,description:"Sign offset of list, should be different from other plugins."},"list.smartCase":{type:"boolean",default:!1,scope:"application",description:"Use smartcase match for fuzzy match and strict match, --ignore-case will be ignored, may not affect interactive list."},"list.source.diagnostics.includeCode":{type:"boolean",scope:"application",description:"Whether to show the diagnostic code in the list.",default:!0},"list.source.diagnostics.pathFormat":{type:"string",scope:"application",description:"Decide how the filepath is shown in the list.",enum:["full","short","filename","hidden"],default:"full"},"list.source.outline.ctagsFiletypes":{type:"array",scope:"application",default:[],description:"Filetypes that should use ctags for outline instead of language server.",items:{type:"string"}},"list.source.symbols.excludes":{type:"array",scope:"application",default:[],description:"Patterns of minimatch for filepath to exclude from symbols list.",items:{type:"string"}},"list.statusLineSegments":{type:["array","null"],scope:"application",default:['%#CocListMode#-- %{coc#list#status("mode")} --%*','%{coc#list#status("loading")}','%{coc#list#status("args")}','(%L/%{coc#list#status("total")})',"%=",'%#CocListPath# %{coc#list#status("cwd")} %l/%L%*'],items:{types:"string"},description:"An array of statusline segments that will be used to draw the status line for list windows."},"notification.statusLineProgress":{type:"boolean",default:!0,scope:"application",description:"Show progress notification in status line, instead of float window/popup."},"notification.border":{type:"boolean",default:!0,scope:"application",description:"Enable rounded border for notification windows."},"notification.disabledProgressSources":{type:"array",default:[],scope:"application",description:"Sources that should be disabled for message progress, use * to disable all message only progresses",items:{type:"string"}},"notification.focusable":{type:"boolean",default:!0,scope:"application",description:"Enable focus by user actions (wincmds, mouse events), neovim only."},"notification.highlightGroup":{type:"string",default:"Normal",scope:"application",description:"Highlight group of notification dialog."},"notification.marginRight":{type:"integer",default:10,scope:"application",description:"Margin right to the right of editor window."},"notification.maxHeight":{type:"integer",default:10,scope:"application",description:"Maximum content height of notification dialog."},"notification.maxWidth":{type:"integer",default:60,scope:"application",description:"Maximum content width of notification dialog."},"notification.minProgressWidth":{type:"integer",default:30,scope:"application",description:"Minimal with of progress notification."},"notification.timeout":{type:"integer",default:1e4,scope:"application",description:"Timeout for auto close notifications, in milliseconds."},"notification.winblend":{type:"integer",default:30,minimum:0,maximum:100,scope:"application",description:"Winblend option of notification window, neovim only."},"npm.binPath":{type:"string",scope:"application",default:"npm",description:"Command or absolute path to npm or yarn."},"outline.autoPreview":{type:"boolean",scope:"application",default:!1,description:"Enable auto preview on cursor move."},"outline.autoWidth":{type:"boolean",scope:"application",default:!0,description:"Automatically increase window width to avoid wrapped lines."},"outline.checkBufferSwitch":{type:"boolean",scope:"application",default:!0,description:"Recreate outline view after user changed to another buffer on current tab."},"outline.codeActionKinds":{type:"array",scope:"application",default:["","quickfix","refactor"],description:"Filter code actions in actions menu by kinds.",items:{type:"string",enum:["","quickfix","refactor","source"]}},"outline.detailAsDescription":{type:"boolean",scope:"application",default:!0,description:"Show detail as description aside with label, when false detail will be shown in tooltip on cursor hold."},"outline.expandLevel":{type:"number",scope:"application",default:1,description:"Expand level of tree nodes."},"outline.followCursor":{type:"boolean",scope:"application",default:!0,description:"Reveal item in outline tree on cursor hold."},"outline.keepWindow":{type:"boolean",scope:"application",default:!1,description:"Jump back to original window after outline is shown."},"outline.previewBorder":{type:"boolean",scope:"application",default:!0,description:"Use border for preview window."},"outline.previewBorderHighlightGroup":{type:"string",scope:"application",default:"Normal",description:"Border highlight group of preview window."},"outline.previewBorderRounded":{type:"boolean",scope:"application",default:!1,description:"Use rounded border for preview window."},"outline.previewHighlightGroup":{type:"string",scope:"application",default:"Normal",description:"Highlight group of preview window."},"outline.previewMaxWidth":{type:"number",scope:"application",default:80,description:"Max width of preview window."},"outline.previewWinblend":{type:"integer",scope:"application",default:0,minimum:0,maximum:100,description:"Enables pseudo-transparency by set 'winblend' option of window, neovim only."},"outline.showLineNumber":{type:"boolean",scope:"application",default:!0,description:"Show line number of symbols."},"outline.sortBy":{type:"string",scope:"application",default:"category",description:"Sort method for symbols.",enum:["position","name","category"]},"outline.splitCommand":{type:"string",scope:"application",default:"botright 30vs",description:"Window split command used by outline."},"outline.switchSortKey":{type:"string",scope:"application",default:"",description:"The key used to switch sort method for symbols provider of current tree view."},"outline.togglePreviewKey":{type:"string",scope:"application",default:"p",description:"The key used to toggle auto preview feature."},"pullDiagnostic.ignored":{type:"array",default:[],scope:"application",description:"Minimatch patterns to match full filepath that should be ignored for pullDiagnostic.",items:{type:"string"}},"pullDiagnostic.onChange":{type:"boolean",default:!0,scope:"language-overridable",description:"Whether to pull for diagnostics on document change."},"pullDiagnostic.onSave":{type:"boolean",default:!1,scope:"language-overridable",description:"Whether to pull for diagnostics on document save."},"pullDiagnostic.workspace":{type:"boolean",default:!0,scope:"application",description:"Whether to pull for workspace diagnostics when possible."},"refactor.afterContext":{type:"number",scope:"application",default:3,description:"Print num lines of trailing context after each match."},"refactor.beforeContext":{type:"number",scope:"application",default:3,description:"Print num lines of leading context before each match."},"refactor.openCommand":{type:"string",scope:"application",description:"Open command for refactor window.",default:"vsplit"},"refactor.saveToFile":{type:"boolean",scope:"application",description:"Save changed buffer to file when write refactor buffer with ':noa wa' command.",default:!0},"refactor.showMenu":{type:"string",scope:"application",default:"",description:"Refactor buffer local mapping to bring up menu for this chunk."},"semanticTokens.combinedModifiers":{type:"array",scope:"language-overridable",description:"Semantic token modifiers that should have highlight combined with syntax highlights.",default:["deprecated"],items:{type:"string"}},"semanticTokens.enable":{type:"boolean",default:!1,scope:"language-overridable",description:"Enable semantic tokens support"},"semanticTokens.filetypes":{type:["array","null"],scope:"resource",description:'Filetypes that enable semantic tokens highlighting or ["*"] for any filetype',deprecationMessage:"Use semanticTokens.enable configuration with language scope instead, see :h coc-configuration-scope",default:null,items:{type:"string"}},"semanticTokens.highlightPriority":{type:"number",scope:"language-overridable",description:"Priority for semantic tokens highlight.",default:2048,maximum:4096},"semanticTokens.incrementTypes":{type:"array",scope:"language-overridable",description:"Semantic token types that should increase highlight when insert at the start and end position of token.",default:["variable","string","parameter"],items:{type:"string"}},"signature.enable":{type:"boolean",scope:"language-overridable",description:"Enable show signature help when trigger character typed.",default:!0},"signature.floatConfig":{type:"object",scope:"application",description:"Configure float window style of signature documents.",allOf:[{$ref:"#/definitions/floatConfig"}],additionalProperties:!1,properties:{border:{},rounded:{},highlight:{},borderhighlight:{},title:{},close:{},maxHeight:{},maxWidth:{},winblend:{},focusable:{},shadow:{}}},"signature.hideOnTextChange":{type:"boolean",scope:"language-overridable",description:"Hide signature float window when text changed on insert mode.",default:!1},"signature.preferShownAbove":{type:"boolean",scope:"application",description:"Show signature help float window above cursor when possible, require restart service on change.",default:!0},"signature.target":{type:"string",scope:"language-overridable",description:"Target of signature help, use float when possible by default.",default:"float",enum:["float","echo"]},"signature.triggerSignatureWait":{type:"integer",scope:"language-overridable",default:500,minimum:200,maximum:1e3,description:"Timeout for trigger signature help, in milliseconds."},"snippet.highlight":{type:"boolean",scope:"resource",description:"Use highlight group 'CocSnippetVisual' to highlight placeholders with same index of current one.",default:!1},"snippet.nextPlaceholderOnDelete":{type:"boolean",scope:"resource",description:"Automatically jump to the next placeholder when the current one is completely deleted.",default:!1},"snippet.statusText":{type:"string",scope:"application",default:"SNIP",description:"Text shown in statusline to indicate snippet session is activated."},"suggest.acceptSuggestionOnCommitCharacter":{type:"boolean",default:!1,scope:"language-overridable",description:"Controls whether suggestions should be accepted on commit characters. For example, in JavaScript, the semi-colon (`;`) can be a commit character that accepts a suggestion and types that character."},"suggest.asciiCharactersOnly":{type:"boolean",description:"Trigger suggest with ASCII characters only",scope:"language-overridable",default:!1},"suggest.asciiMatch":{type:"boolean",description:"Convert unicode characters to ascii for match",scope:"language-overridable",default:!0},"suggest.autoTrigger":{type:"string",scope:"language-overridable",default:"always",description:"How should completion be triggered",enum:["always","trigger","none"]},"suggest.completionItemKindLabels":{type:"object",default:{},scope:"application",description:"Set custom labels to completion items' kinds.",properties:{text:{type:"string"},method:{type:"string"},function:{type:"string"},constructor:{type:"string"},field:{type:"string"},variable:{type:"string"},class:{type:"string"},interface:{type:"string"},module:{type:"string"},property:{type:"string"},unit:{type:"string"},value:{type:"string"},enum:{type:"string"},keyword:{type:"string"},snippet:{type:"string"},color:{type:"string"},file:{type:"string"},reference:{type:"string"},folder:{type:"string"},enumMember:{type:"string"},constant:{type:"string"},struct:{type:"string"},event:{type:"string"},operator:{type:"string"},typeParameter:{type:"string"},default:{type:"string"}},additionalProperties:!1},"suggest.defaultSortMethod":{type:"string",description:"Default sorting behavior for suggested completion items.",default:"length",scope:"language-overridable",enum:["length","alphabetical","none"]},"suggest.detailField":{type:"string",scope:"application",default:"preview",description:"Where to show the detail text of CompleteItem from LS.",enum:["abbr","preview"]},"suggest.detailMaxLength":{type:"number",scope:"application",description:"Max length of detail that should be shown in popup menu.",deprecationMessage:"Use suggest.labelMaxLength instead.",default:100},"suggest.enableFloat":{type:"boolean",scope:"language-overridable",description:"Enable float window with documentation aside with popupmenu.",default:!0},"suggest.enablePreselect":{type:"boolean",scope:"application",description:"Enable preselect feature of LSP, works when suggest.noselect is false.",default:!0},"suggest.filterGraceful":{type:"boolean",description:"Controls whether filtering and sorting suggestions accounts for small typos.",scope:"language-overridable",default:!0},"suggest.floatConfig":{type:"object",scope:"application",description:"Configure style of popup menu and documentation window of completion.",allOf:[{$ref:"#/definitions/floatConfig"}],additionalProperties:!1,properties:{border:{},rounded:{},highlight:{},borderhighlight:{},maxWidth:{},winblend:{},shadow:{}}},"suggest.formatItems":{type:"array",scope:"application",items:{enum:["abbr","menu","kind","shortcut"]},contains:{enum:["abbr"]},uniqueItems:!0,description:"Items shown in popup menu in order.",default:["abbr","menu","kind","shortcut"]},"suggest.highPrioritySourceLimit":{type:"integer",minimum:1,maximum:100,scope:"language-overridable",description:"Max items count for source priority bigger than or equal to 90."},"suggest.insertMode":{type:"string",scope:"language-overridable",default:"replace",description:"Controls whether words are overwritten when accepting completions.",enum:["insert","replace"]},"suggest.ignoreRegexps":{type:"array",scope:"language-overridable",items:{type:"string"},description:"Regexps to ignore when trigger suggest",default:[]},"suggest.invalidInsertCharacters":{type:"array",items:{type:"string"},scope:"application",description:"Invalid character for strip valid word when inserting text of complete item.",default:["\r",` +`]},"suggest.labelMaxLength":{type:"number",scope:"application",description:"Max length of abbr that shown as label of complete item.",default:200},"suggest.languageSourcePriority":{type:"number",default:99,scope:"language-overridable",description:"Priority of language sources."},"suggest.localityBonus":{type:"boolean",description:"Controls whether sorting favors words that appear close to the cursor.",scope:"language-overridable",default:!0},"suggest.lowPrioritySourceLimit":{type:"integer",minimum:1,maximum:100,scope:"language-overridable",description:"Max items count for source priority lower than 90."},"suggest.maxCompleteItemCount":{type:"number",default:256,scope:"language-overridable",description:"Maximum number of complete items shown in vim"},"suggest.minTriggerInputLength":{type:"integer",default:1,scope:"language-overridable",description:"Minimal input length for trigger completion, default 1"},"suggest.noselect":{type:"boolean",scope:"application",description:"Not make vim select first item on popupmenu shown",default:!1},"suggest.preferCompleteThanJumpPlaceholder":{type:"boolean",description:"Confirm completion instead of jump to next placeholder when completion is activated.",scope:"resource",default:!1},"suggest.pumFloatConfig":{type:["object","null"],scope:"application",description:"Configure style of popup menu, suggest.floatConfig is used when not specified.",allOf:[{$ref:"#/definitions/floatConfig"}],additionalProperties:!1,default:null,properties:{border:{},rounded:{},highlight:{},borderhighlight:{},winblend:{},shadow:{}}},"suggest.removeDuplicateItems":{type:"boolean",description:"Remove completion items with duplicated word for all sources, snippet items are excluded.",scope:"language-overridable",default:!1},"suggest.reversePumAboveCursor":{type:"boolean",scope:"application",description:"Reverse order of complete items when pum shown above cursor.",default:!1},"suggest.selection":{type:"string",scope:"application",default:"first",description:"Controls how suggestions are pre-selected when showing the suggest list.",enum:["first","recentlyUsed","recentlyUsedByPrefix"]},"suggest.snippetIndicator":{type:"string",default:"~",scope:"application",description:"The character used in abbr of complete item to indicate the item could be expand as snippet."},"suggest.snippetsSupport":{type:"boolean",scope:"language-overridable",description:"Set to false to disable snippets support of completion.",default:!0},"suggest.timeout":{type:"integer",default:5e3,minimum:500,maximum:15e3,scope:"language-overridable",description:"Timeout for completion, in milliseconds."},"suggest.triggerAfterInsertEnter":{type:"boolean",description:"Trigger completion after InsertEnter, auto trigger should be 'always' to enable this option",scope:"language-overridable",default:!1},"suggest.triggerCompletionWait":{type:"integer",default:0,minimum:0,maximum:50,scope:"language-overridable",description:"Wait time between text change and completion start, cancel completion when text changed during wait."},"suggest.virtualText":{type:"boolean",scope:"application",description:"Show virtual text for insert word of selected item, requires neovim >= 0.5.0 or vim >= 9.0.0067",default:!1},"tree.closedIcon":{type:"string",scope:"application",default:"+",description:"Closed icon of tree view."},"tree.key.actions":{type:"string",scope:"application",default:"",description:"Trigger key to invoke actions."},"tree.key.activeFilter":{type:"string",scope:"application",default:"f",description:"Trigger key active filter."},"tree.key.close":{type:"string",scope:"application",default:"",description:"Trigger key to dispose the tree and close tree window."},"tree.key.collapseAll":{type:"string",scope:"application",default:"M",description:"Trigger key to collapse all tree node."},"tree.key.invoke":{type:"string",scope:"application",default:"",description:"Trigger key to invoke default command of current node or selection."},"tree.key.selectNext":{type:"string",scope:"application",default:"",description:"Trigger key to select next item during filter."},"tree.key.selectPrevious":{type:"string",scope:"application",default:"",description:"Trigger key to select previous item during filter."},"tree.key.toggle":{type:"string",scope:"application",default:"t",description:"Trigger key to toggle expand state of tree node, does nothing with leaf node."},"tree.key.toggleSelection":{type:"string",scope:"application",default:"",description:"Trigger key to select/unselect item"},"tree.openedIcon":{type:"string",scope:"application",default:"-",description:"Opened icon of tree view."},"typeHierarchy.enableTooltip":{type:"boolean",scope:"application",default:!0,description:"Enable tooltip to show relative filepath of type hierarchy."},"typeHierarchy.openCommand":{type:"string",scope:"application",default:"edit",description:"Open command for type hierarchy tree view."},"typeHierarchy.splitCommand":{type:"string",scope:"application",default:"botright 30vs",description:"Window split command used by type hierarchy tree view."},"workspace.rootPatterns":{type:"array",default:[".git",".hg",".projections.json"],scope:"application",description:"Root patterns to resolve workspaceFolder from parent folders of opened files, resolved from up to down.",items:{type:"string"}},"workspace.bottomUpFiletypes":{type:"array",default:[],scope:"application",description:'Filetypes that should have workspace folder should resolved from base directory of file, or ["*"] for any filetype.',items:{type:"string"}},"workspace.ignoredFiletypes":{type:"array",default:[],scope:"application",description:"Filetypes that should be ignored for workspace folder resolve.",items:{type:"string"}},"workspace.ignoredFolders":{type:"array",default:["$HOME"],scope:"application",description:"List of folders that should not be resolved as workspace folder, environment variables and minimatch patterns can be used.",items:{type:"string"}},"workspace.openOutputCommand":{type:"string",default:"vs",scope:"resource",description:"Command used to open output channel."},"workspace.openResourceCommand":{type:"string",default:"tab drop",scope:"application",description:"Command to open files that not loaded, load files as hidden buffers when empty."},"workspace.workspaceFolderCheckCwd":{type:"boolean",default:!0,scope:"application",description:"Whether the current working directory should be used first when checking patterns match for workspace folder."},"workspace.workspaceFolderFallbackCwd":{type:"boolean",default:!0,scope:"application",description:"Use current working directory as workspace folder when no root patterns resolved."},languageserver:{type:"object",default:{},scope:"resource",description:"Dictionary of languageservers, key is used as id of languageserver, restart coc.nvim required after change.",patternProperties:{"^[_a-zA-Z]+$":{oneOf:[{$ref:"#/definitions/languageServerModule"},{$ref:"#/definitions/languageServerCommand"},{$ref:"#/definitions/languageServerSocket"}]}}}}}});var qg,DP,Tle,TP=D(()=>{"use strict";U();wo();qg={JSONContribution:"base.contributions.json"},DP=class{constructor(){this._onDidChangeSchema=new p.Emitter;this.onDidChangeSchema=this._onDidChangeSchema.event;this.schemasById={}}registerSchema(e,t){this.schemasById[e]=t,this._onDidChangeSchema.fire(e)}notifySchemaChanged(e){this._onDidChangeSchema.fire(e)}getSchemaContributions(){return{schemas:this.schemasById}}},Tle=new DP;li.add(qg.JSONContribution,Tle)});function kP(n,e){if(n.length<=1)return n;var t=n.length/2|0,i=n.slice(0,t),r=n.slice(t);kP(i,e),kP(r,e);for(var o=0,s=0,a=0;ot.line||e.line===t.line&&e.character>t.character?{start:t,end:e}:n}function Ple(n){var e=M$(n.range);return e!==n.range?{newText:n.newText,range:e}:n}var kle,L$,Qr,Wg=D(()=>{"use strict";kle=function(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,o;ie?r=o:i=o+1}var s=i-1;return{line:s,character:e-t[s]}},n.prototype.offsetAt=function(e){var t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;var i=t[e.line],r=e.line+1l&&u.push(s.substring(l,g)),h.newText.length&&u.push(h.newText),l=r.offsetAt(h.range.end)}return u.push(s.substr(l)),u.join("")}n.applyEdits=i})(Qr||(Qr={}))});function _le(n){return n.replace(/\$\{(.*?)\}/g,(e,t)=>{if(t.startsWith("env:")){let i=t.split(":")[1];return process.env[i]??e}switch(t){case"userHome":return Pt.homedir();case"cwd":return process.cwd();default:return e}})}function PP(n){if(n==null)return n;if(typeof n=="string")return _le(n);if(Array.isArray(n))return n.map(e=>PP(e));if(xt(n)){for(let e of Object.keys(n))n[e]=PP(n[e]);return n}return n}function A$(n){let e;switch(n){case 1:e=1;break;case 2:e=2;break;default:e=3}return e}function Iv(n){let e;if(typeof n=="string")e={resource:n};else if(O.isUri(n))e={resource:n.toString()};else if(n!=null){let t=n.uri,i=n.languageId;e={resource:t,overrideIdentifier:i}}return e}function Lv(n){let e=[];if(Zg.test(n)){let t=j$.exec(n);for(;t!=null&&t.length;){let i=t[1].trim();i&&e.push(i),t=j$.exec(n)}}return yi(e)}function N$(n){let e={};for(let t of Object.keys(n))if(t.indexOf(".")==-1)e[t]=n[t];else{let i=t.split("."),r=e,o=i.length;for(let s=0;s"u"?t:o}function xc(n){if(n){if(Array.isArray(n))return n.map(xc);if(typeof n=="object"){let e=Object.create(null);for(let t in n)e[t]=xc(n[t]);return e}}return n}function _P(n,e){let t=n?e?n.keys.filter(o=>e.keys.indexOf(o)===-1):[...n.keys]:[],i=e?n?e.keys.filter(o=>n.keys.indexOf(o)===-1):[...e.keys]:[],r=[];if(n&&e){for(let o of e.keys)if(n.keys.indexOf(o)!==-1){let s=Yg(e.contents,o),a=Yg(n.contents,o);Me(s,a)||r.push(o)}}return{added:t,removed:i,updated:r}}function W$(n){switch(Array.isArray(n)?n[0]:n){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};default:return null}}function Fv(n,e){if(e){if(n&&Rn(n,e))return n[e];let t=e.split("."),i=n;for(let r=0;i&&r{"use strict";wg();Wg();ae();Je();Re();Xe();de();Be();vo();Rle="file:///1",O$="\\[([^\\]]+)\\]",j$=new RegExp(O$,"g"),Ev=`^(${O$})+$`,Zg=new RegExp(Ev)});var oi,$g=D(()=>{"use strict";Re();Xe();Be();aa();oi=class{constructor(e={},t=[],i=[]){this._contents=e;this._keys=t;this._overrides=i;this.frozen=!1;this.overrideConfigurations=new Map}get contents(){return this.checkAndFreeze(this._contents)}get overrides(){return this.checkAndFreeze(this._overrides)}get keys(){return this.checkAndFreeze(this._keys)}get isFrozen(){return this.frozen}checkAndFreeze(e){return this.frozen&&!Object.isFrozen(e)?Dy(e):e}isEmpty(){return this._keys.length===0&&Object.keys(this._contents).length===0&&this._overrides.length===0}clone(){return new oi(Li(this._contents),[...this.keys],Li(this.overrides))}toJSON(){return{contents:this.contents,overrides:this.overrides,keys:this.keys}}getValue(e){return e?Yg(this.contents,e):this.contents}getOverrideValue(e,t){let i=this.getContentsForOverrideIdentifier(t);return i?e?Yg(i,e):i:void 0}getKeysForOverrideIdentifier(e){let t=[];for(let i of this.overrides)i.identifiers.includes(e)&&t.push(...i.keys);return yi(t)}getAllOverrideIdentifiers(){let e=[];for(let t of this.overrides)e.push(...t.identifiers);return yi(e)}override(e){let t=this.overrideConfigurations.get(e);return t||(t=this.createOverrideConfigurationModel(e),this.overrideConfigurations.set(e,t)),t}merge(...e){let t=Li(this._contents),i=Li(this._overrides),r=[...this._keys];for(let o of e)if(!o.isEmpty()){this.mergeContents(t,o.contents);for(let s of o.overrides){let[a]=i.filter(l=>Me(l.identifiers,s.identifiers));a?(this.mergeContents(a.contents,s.contents),a.keys.push(...s.keys),a.keys=yi(a.keys)):i.push(Li(s))}for(let s of o.keys)r.indexOf(s)===-1&&r.push(s)}return new oi(t,r,i)}freeze(){return this.frozen=!0,this}mergeContents(e,t){for(let i of Object.keys(t)){if(i in e&&xt(e[i])&&xt(t[i])){this.mergeContents(e[i],t[i]);continue}e[i]=Li(t[i])}}setValue(e,t){this.addKey(e),Cc(this.contents,e,t,i=>{console.error(i)})}removeValue(e){this.removeKey(e)&&B$(this.contents,e)}addKey(e){let t=this.keys.length;for(let i=0;i{o&&(i?this.mergeContents(i,o):i=Li(o))};for(let o of this.overrides)Me(o.identifiers,[e])?t=o.contents:o.identifiers.includes(e)&&r(o.contents);return r(t),i}}});function Sc(n,e){let{added:t,removed:i,updated:r}=_P(e,n),o=[],s=(n==null?void 0:n.getAllOverrideIdentifiers())??[],a=(e==null?void 0:e.getAllOverrideIdentifiers())??[];if(e){let l=a.filter(u=>!s.includes(u));for(let u of l)o.push([u,e.getKeysForOverrideIdentifier(u)])}if(n){let l=s.filter(u=>!a.includes(u));for(let u of l)o.push([u,n.getKeysForOverrideIdentifier(u)])}if(e&&n){for(let l of s)if(a.includes(l)){let u=_P({contents:n.getOverrideValue(void 0,l)||{},keys:n.getKeysForOverrideIdentifier(l)},{contents:e.getOverrideValue(void 0,l)||{},keys:e.getKeysForOverrideIdentifier(l)});o.push([l,[...u.added,...u.removed,...u.updated]])}}return{added:t,removed:i,updated:r,overrides:o}}var Mv,la,EP=D(()=>{"use strict";Je();vo();Re();st();Be();$g();aa();Mv=class{constructor(){this._folderConfigurations=new Map}get keys(){return this._folderConfigurations.keys()}has(e){for(let t of this.keys)if(ai(e,t))return!0;return!1}set(e,t){let i=Mi(e);this._folderConfigurations.set(i,t)}get(e){let t=Mi(e);return this._folderConfigurations.get(t)}delete(e){let t=Mi(e);this._folderConfigurations.delete(t)}forEach(e){this._folderConfigurations.forEach(e)}getConfigurationByResource(e){let t=O.parse(e);if(t.scheme!=="file")return;let i=Array.from(this._folderConfigurations.keys());i.sort((o,s)=>s.length-o.length);let r=t.fsPath;for(let o of i)if(dt(o,r,!0))return{folder:o,model:this._folderConfigurations.get(o)}}},la=class{constructor(e,t,i=new oi,r=new Mv,o=new oi){this._defaultConfiguration=e;this._userConfiguration=t;this._workspaceConfiguration=i;this._folderConfigurations=r;this._memoryConfiguration=o;this._workspaceConsolidatedConfiguration=null;this._resolvedFolderConfigurations=new Map;this._memoryConfigurationByResource=new Map}updateValue(e,t,i={}){let r;i.resource?(r=this._memoryConfigurationByResource.get(i.resource),r||(r=new oi,this._memoryConfigurationByResource.set(i.resource,r))):r=this._memoryConfiguration,t===void 0?r.removeValue(e):r.setValue(e,t),i.resource||(this._workspaceConsolidatedConfiguration=null)}hasFolder(e){return this._folderConfigurations.has(e)}addFolderConfiguration(e,t,i){this._folderConfigurations.set(e,t),i&&this._resolvedFolderConfigurations.set(i,e)}deleteFolderConfiguration(e){this._folderConfigurations.delete(e)}getWorkspaceConsolidateConfiguration(){return this._workspaceConsolidatedConfiguration||(this._workspaceConsolidatedConfiguration=this._defaultConfiguration.merge(this._userConfiguration,this._workspaceConfiguration,this._memoryConfiguration),this._workspaceConsolidatedConfiguration=this._workspaceConsolidatedConfiguration.freeze()),this._workspaceConsolidatedConfiguration}getFolderConfigurationModelForResource(e){let t=this._resolvedFolderConfigurations.get(e);if(t)return this._folderConfigurations.get(t);let i=this._folderConfigurations.getConfigurationByResource(e);if(!!i)return this._resolvedFolderConfigurations.set(e,i.folder),i.model}resolveFolder(e){let t=this._resolvedFolderConfigurations.get(e);if(t)return t;let i=Array.from(this._folderConfigurations.keys);i.sort((r,o)=>o.length-r.length);for(let r of i)if(dt(r,O.parse(e).fsPath,!0))return this._resolvedFolderConfigurations.set(e,r),r}getConsolidatedConfigurationModel(e){let t=this.getWorkspaceConsolidateConfiguration();if(e.resource){let i=this.getFolderConfigurationModelForResource(e.resource);i&&(t=t.merge(i));let r=this._memoryConfigurationByResource.get(e.resource);r&&(t=t.merge(r))}return e.overrideIdentifier&&(t=t.override(e.overrideIdentifier)),t}getValue(e,t){return this.getConsolidatedConfigurationModel(t).getValue(e)}inspect(e,t){let i=this.getConsolidatedConfigurationModel(t),r=this.getFolderConfigurationModelForResource(t.resource),o=t.resource?this._memoryConfigurationByResource.get(t.resource)||this._memoryConfiguration:this._memoryConfiguration,s=t.overrideIdentifier?this._defaultConfiguration.freeze().override(t.overrideIdentifier).getValue(e):this._defaultConfiguration.freeze().getValue(e),a=t.overrideIdentifier?this._userConfiguration.freeze().override(t.overrideIdentifier).getValue(e):this._userConfiguration.freeze().getValue(e),l=t.overrideIdentifier?this._workspaceConfiguration.freeze().override(t.overrideIdentifier).getValue(e):this._workspaceConfiguration.freeze().getValue(e),u=r?t.overrideIdentifier?r.freeze().override(t.overrideIdentifier).getValue(e):r.freeze().getValue(e):void 0,c=t.overrideIdentifier?o.override(t.overrideIdentifier).getValue(e):o.getValue(e),d=i.getValue(e),h=yi(i.overrides.map(g=>g.identifiers).flat()).filter(g=>i.getOverrideValue(e,g)!==void 0);return{defaultValue:s,userValue:a,workspaceValue:l,workspaceFolderValue:u,memoryValue:c,value:d,default:s!==void 0?{value:this._defaultConfiguration.freeze().getValue(e),override:t.overrideIdentifier?this._defaultConfiguration.freeze().getOverrideValue(e,t.overrideIdentifier):void 0}:void 0,user:a!==void 0?{value:this._userConfiguration.freeze().getValue(e),override:t.overrideIdentifier?this._userConfiguration.freeze().getOverrideValue(e,t.overrideIdentifier):void 0}:void 0,workspace:l!==void 0?{value:this._workspaceConfiguration.freeze().getValue(e),override:t.overrideIdentifier?this._workspaceConfiguration.freeze().getOverrideValue(e,t.overrideIdentifier):void 0}:void 0,workspaceFolder:u!==void 0?{value:r==null?void 0:r.freeze().getValue(e),override:t.overrideIdentifier?r==null?void 0:r.freeze().getOverrideValue(e,t.overrideIdentifier):void 0}:void 0,memory:c!==void 0?{value:o.getValue(e),override:t.overrideIdentifier?o.getOverrideValue(e,t.overrideIdentifier):void 0}:void 0,overrideIdentifiers:h.length?h:void 0}}get defaults(){return this._defaultConfiguration}get user(){return this._userConfiguration}get workspace(){return this._workspaceConfiguration}get memory(){return this._memoryConfiguration}getConfigurationModel(e,t){switch(e){case 0:return this._defaultConfiguration;case 1:return this._userConfiguration;case 2:return this._workspaceConfiguration;case 3:return this._folderConfigurations.get(t)??new oi;default:return this._memoryConfiguration}}updateFolderConfiguration(e,t){this._folderConfigurations.set(e,t)}updateUserConfiguration(e){this._userConfiguration=e,this._workspaceConsolidatedConfiguration=null}updateWorkspaceConfiguration(e){this._workspaceConfiguration=e,this._workspaceConsolidatedConfiguration=null}updateDefaultConfiguration(e){this._defaultConfiguration=e,this._workspaceConsolidatedConfiguration=null}updateMemoryConfiguration(e){this._memoryConfiguration=e,this._workspaceConsolidatedConfiguration=null}compareAndUpdateMemoryConfiguration(e){let{added:t,updated:i,removed:r,overrides:o}=Sc(this._memoryConfiguration,e),s=[...t,...i,...r];return s.length&&this.updateMemoryConfiguration(e),{keys:s,overrides:o}}compareAndUpdateUserConfiguration(e){let{added:t,updated:i,removed:r,overrides:o}=Sc(this._userConfiguration,e),s=[...t,...i,...r];return s.length&&this.updateUserConfiguration(e),{keys:s,overrides:o}}compareAndUpdateDefaultConfiguration(e,t){let i=[];if(!t){let{added:r,updated:o,removed:s}=Sc(this._defaultConfiguration,e);t=[...r,...o,...s]}for(let r of t)for(let o of Lv(r)){let s=this._defaultConfiguration.getKeysForOverrideIdentifier(o),a=e.getKeysForOverrideIdentifier(o),l=[...a.filter(u=>s.indexOf(u)===-1),...s.filter(u=>a.indexOf(u)===-1),...s.filter(u=>!Me(this._defaultConfiguration.override(o).getValue(u),e.override(o).getValue(u)))];i.push([o,l])}return this.updateDefaultConfiguration(e),{keys:t,overrides:i}}compareAndUpdateWorkspaceConfiguration(e){let{added:t,updated:i,removed:r,overrides:o}=Sc(this._workspaceConfiguration,e),s=[...t,...i,...r];return s.length&&this.updateWorkspaceConfiguration(e),{keys:s,overrides:o}}compareAndUpdateFolderConfiguration(e,t){let i=this._folderConfigurations.get(e),{added:r,updated:o,removed:s,overrides:a}=Sc(i,t),l=[...r,...o,...s];return(l.length||!i)&&this.updateFolderConfiguration(e,t),{keys:l,overrides:a}}compareAndDeleteFolderConfiguration(e){let t=this._folderConfigurations.get(e);if(!t)return;this.deleteFolderConfiguration(e);let{added:i,updated:r,removed:o,overrides:s}=Sc(t,void 0);return{keys:[...i,...r,...o],overrides:s}}allKeys(){let e=new Set;return this._defaultConfiguration.freeze().keys.forEach(t=>e.add(t)),this._userConfiguration.freeze().keys.forEach(t=>e.add(t)),this._workspaceConfiguration.freeze().keys.forEach(t=>e.add(t)),this._folderConfigurations.forEach(t=>t.freeze().keys.forEach(i=>e.add(i))),[...e.values()]}toData(){let{_defaultConfiguration:e,_userConfiguration:t,_workspaceConfiguration:i,_folderConfigurations:r}=this,o=[];return r.forEach((s,a)=>{o.push([a,s.toJSON()])}),{defaults:e.toJSON(),user:t.toJSON(),workspace:i.toJSON(),folders:o}}static parse(e){let t=this.parseConfigurationModel(e.defaults),i=this.parseConfigurationModel(e.user),r=this.parseConfigurationModel(e.workspace),o=new Mv;return e.folders.forEach(s=>{o.set(s[0],this.parseConfigurationModel(s[1]))}),new la(t,i,r,o)}static parseConfigurationModel(e){return new oi(e.contents,e.keys,e.overrides).freeze()}}});var jv,Y$=D(()=>{"use strict";Be();EP();$g();aa();jv=class{constructor(e,t,i){this.change=e;this.previous=t;this.currentConfiguration=i;this._previousConfiguration=void 0;let r=new Set;e.keys.forEach(s=>r.add(s)),e.overrides.forEach(([,s])=>s.forEach(a=>r.add(a))),this.affectedKeys=[...r.values()];let o=new oi;this.affectedKeys.forEach(s=>o.setValue(s,{})),this.affectedKeysTree=o.contents}get previousConfiguration(){return!this._previousConfiguration&&this.previous&&(this._previousConfiguration=la.parse(this.previous)),this._previousConfiguration}affectsConfiguration(e,t){let i=t?Iv(t):void 0;if(this.doesAffectedKeysTreeContains(this.affectedKeysTree,e)){if(i){let r=this.previousConfiguration?this.previousConfiguration.getValue(e,i):void 0,o=this.currentConfiguration.getValue(e,i);return!Me(r,o)}return!0}return!1}doesAffectedKeysTreeContains(e,t){let i=Jg({[t]:!0},()=>{}),r;for(;typeof i=="object"&&(r=Object.keys(i)[0]);){if(e=e[r],!e)return!1;i=i[r]}return!0}}});var cEe,Ov,Z$=D(()=>{"use strict";wg();ae();xe();$g();aa();cEe=Z("parser"),Ov=class{constructor(e){this._name=e;this._raw=null;this._configurationModel=null;this._parseErrors=[]}get configurationModel(){return this._configurationModel||new oi}get errors(){return this._parseErrors}parse(e,t){if(e!=null){let i=this.doParseContent(e);this.parseRaw(i,t)}}parseRaw(e,t){this._raw=e;let{contents:i,keys:r,overrides:o}=this.doParseRaw(e,t);this._configurationModel=new oi(i,r,o)}doParseContent(e){let t={},i=null,r=[],o=[],s=[];function a(u){Array.isArray(r)?r.push(u):i!==null&&(r[i]=u)}let l={onObjectBegin:()=>{let u={};a(u),o.push(r),r=u,i=null},onObjectProperty:u=>{i=u},onObjectEnd:()=>{r=o.pop()},onArrayBegin:()=>{let u=[];a(u),o.push(r),r=u,i=null},onArrayEnd:()=>{r=o.pop()},onLiteralValue:a,onError:(u,c,d)=>{s.push({error:u,length:d,offset:c})}};if(e)try{RZ(e,l,{allowTrailingComma:!0,allowEmptyContent:!0}),t=r[0]??{},s.length>0&&(this._parseErrors=H$(e,s))}catch(u){this._parseErrors=[{range:M.create(0,0,0,0),message:`Error on parse configuration file ${this._name}: ${u}`}]}return t}doParseRaw(e,t){let i=a=>{console.error(`Conflict in settings file ${this._name}: ${a}`)},r=Jg(e,i,!0),o=Object.keys(e),s=this.toOverrides(e,i);return{contents:r,keys:o,overrides:s,restricted:[]}}toOverrides(e,t){let i=[];for(let r of Object.keys(e))if(Zg.test(r)){let o={};for(let s in e[r])o[s]=e[r][s];i.push({identifiers:Lv(r),keys:Object.keys(o),contents:Jg(o,t,!0)})}return i}}});function Ile(n,e=void 0){return n.trim()?Zg.test(n)?`Cannot register ${n}. This matches property pattern '\\\\[.*\\\\]$' for describing language specific editor settings`:J$.getConfigurationProperties()[n]!==void 0?`Cannot register '${n}'. This property is already registered.`:null:"Cannot register an empty property"}var Ele,Il,El,_l,Ug,Av,IP,J$,Nv=D(()=>{"use strict";Re();TP();Be();U();wo();vo();aa();Ele=["log-path","logPath"],Il={Configuration:"base.contributions.configuration"},El={properties:{},patternProperties:{}},_l={properties:{},patternProperties:{}},Ug="vscode://schemas/settings/resourceLanguage",Av=li.as(qg.JSONContribution),IP=class{constructor(){this._onDidSchemaChange=new p.Emitter;this.onDidSchemaChange=this._onDidSchemaChange.event;this._onDidUpdateConfiguration=new p.Emitter;this.onDidUpdateConfiguration=this._onDidUpdateConfiguration.event;this.resourceLanguageSettingsSchema={properties:{},patternProperties:{},additionalProperties:!1,errorMessage:"Unknown coc.nvim configuration property",allowTrailingCommas:!0,allowComments:!0},this.configurationProperties={},this.excludedConfigurationProperties={},Av.registerSchema(Ug,this.resourceLanguageSettingsSchema),this.registerOverridePropertyPatternKey()}registerConfiguration(e,t=!0){this.registerConfigurations([e],t)}registerConfigurations(e,t=!0){let i=this.doRegisterConfigurations(e,t);Av.notifySchemaChanged(Ug),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:i})}deregisterConfigurations(e){let t=this.doDeregisterConfigurations(e);Av.notifySchemaChanged(Ug),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:t})}updateConfigurations({add:e,remove:t}){let i=[];i.push(...this.doDeregisterConfigurations(t)),i.push(...this.doRegisterConfigurations(e,!1)),Av.notifySchemaChanged(Ug),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:yi(i)})}doRegisterConfigurations(e,t){let i=[];return e.forEach(r=>{i.push(...this.validateAndRegisterProperties(r,t,r.extensionInfo)),this.registerJSONConfiguration(r)}),i}doDeregisterConfigurations(e){let t=[],i=r=>{for(let o in Ue(r.properties))t.push(o),delete this.configurationProperties[o],this.removeFromSchema(o,r.properties[o])};for(let r of e)i(r);return t}validateAndRegisterProperties(e,t,i,r=1){r=e.scope==null?r:e.scope;let o=[],s=e.properties;for(let a in Ue(s)){let l=s[a];if(t&&Ile(a,l)){delete s[a];continue}if(l.source=i,l.defaultDefaultValue=s[a].default,this.updatePropertyDefaultValue(a,l),l.scope=l.scope==null?r:l.scope,i&&(l.description=(l.description?`${l.description} +`:"")+`From ${i.id}`),l.hasOwnProperty("included")&&!l.included){this.excludedConfigurationProperties[a]=s[a],delete s[a];continue}else this.configurationProperties[a]=s[a];!s[a].deprecationMessage&&s[a].markdownDeprecationMessage&&(s[a].deprecationMessage=s[a].markdownDeprecationMessage),o.push(a)}return o}getConfigurationProperties(){return this.configurationProperties}getExcludedConfigurationProperties(){return this.excludedConfigurationProperties}registerJSONConfiguration(e){(i=>{let r=i.properties;for(let o in Ue(r))this.updateSchema(o,r[o])})(e)}updateSchema(e,t){switch(El.properties[e]=t,t.scope){case 2:case 3:_l.properties[e]=t;break;case 4:_l.properties[e]=t,this.resourceLanguageSettingsSchema.properties[e]=t;break}}removeFromSchema(e,t){switch(delete El.properties[e],t.scope){case 2:case 3:case 4:delete _l.properties[e],delete this.resourceLanguageSettingsSchema.properties[e];break}}registerOverridePropertyPatternKey(){let e={type:"object",description:"Configure editor settings to be overridden for a language.",errorMessage:"This setting does not support per-language configuration.",$ref:Ug};El.patternProperties[Ev]=e,_l.patternProperties[Ev]=e}updatePropertyDefaultValue(e,t){let i=t.defaultDefaultValue;typeof i>"u"&&!Ele.some(r=>e.includes(r))&&(i=W$(t.type)),t.default=i,t.defaultValueSource=void 0}},J$=new IP;li.add(Il.Configuration,J$)});var Hv,LP,Lle,Fle,Mle,ua,Xg,$$=D(()=>{"use strict";Je();Hv=Lr(I$());xe();te();Re();Yt();rs();st();Xe();TP();de();Be();U();wo();EP();Y$();$g();Z$();Nv();vo();aa();LP=Z("configurations"),Lle="vscode://schemas/settings/user",Fle="vscode://schemas/settings/folder",Mle=li.as(qg.JSONContribution),ua=li.as(Il.Configuration),Xg=class{constructor(e,t,i=!1,r=process.cwd()){this.userConfigFile=e;this._proxy=t;this.noWatch=i;this._watchedFiles=new Set;this._errors=new Map;this._onError=new p.Emitter;this._onChange=new p.Emitter;this.disposables=[];this._initialized=!1;this.cached=[];this.onError=this._onError.event;this.onDidChange=this._onChange.event;let o=this.loadDefaultConfigurations(),s=this.parseConfigurationModel(this.userConfigFile);this._configuration=new la(o,s),this.watchFile(this.userConfigFile,1);let a=this.folderToConfigfile(r);a&&this.addFolderFile(a,!0),this._initialConfiguration=this.getConfiguration(void 0,null)}get initialConfiguration(){return this._initialConfiguration}get markdownPreference(){let e=this._initialConfiguration.get("coc.preferences");return{excludeImages:e.excludeImageLinksInMarkdownDocument,breaks:e.enableGFMBreaksInMarkdownDocument}}get errors(){return this._errors}get configuration(){return this._configuration}flushConfigurations(){this._initialized=!0,ua.registerConfigurations(this.cached),this.cached=[]}updateConfigurations(e,t){this._initialized?re(t)?ua.registerConfigurations(e):ua.updateConfigurations({add:e,remove:t}):this.cached.push(...e)}loadDefaultConfigurations(){let e={properties:tv(Hv.default.properties)};ua.registerConfiguration(e),ua.onDidUpdateConfiguration(s=>{if(s.properties.length===0)return;let a=ua.getConfigurationProperties(),l=[],u=Object.create(null),c=[];for(let h of s.properties){let g=a[h];if(g){c.push(h);let f=g.default;Cc(u,h,f,m=>{LP.error(`Conflict configuration: ${m}`)})}else l.push(h)}let d=this._configuration.defaults.merge(new oi(u,c));l.forEach(h=>{d.removeValue(h)}),this._initialized?this.changeConfiguration(0,d,void 0,s.properties):(this._configuration.updateDefaultConfiguration(d),this._initialConfiguration=this.getConfiguration(void 0,null))},null,this.disposables);let t=ua.getConfigurationProperties(),i={},r=[];return Object.keys(t).forEach(s=>{let a=t[s].default;r.push(s),Cc(i,s,a,void 0)}),new oi(i,r)}getDescription(e){let t=El.properties[e];return t?t.description:void 0}getJSONSchema(e){if(e===Lle)return{properties:El.properties,patternProperties:El.patternProperties,definitions:Object.assign(zk(),Hv.default.definitions),additionalProperties:!1,allowTrailingCommas:!0,allowComments:!0};if(e===Fle)return{properties:_l.properties,patternProperties:_l.patternProperties,definitions:Object.assign(zk(),Hv.default.definitions),errorMessage:"Configuration property may not work as folder configuration",additionalProperties:!1,allowTrailingCommas:!0,allowComments:!0};let t=Mle.getSchemaContributions().schemas;if(Rn(t,e))return t[e]}parseConfigurationModel(e){if(!e||!F.existsSync(e))return new oi;let t=new Ov(e),i=F.readFileSync(e,"utf8"),r=O.file(e).toString();return t.parse(i),re(t.errors)?(this._errors.delete(r),this._onError.fire({uri:r,diagnostics:[]})):(this._errors.set(r,t.errors),this._onError.fire({uri:r,diagnostics:t.errors})),t.configurationModel}folderToConfigfile(e){if(ai(e,Pt.homedir()))return;let t=R.join(e,`.vim/${fg}`);if(!ai(t,this.userConfigFile))return t}updateMemoryConfig(e){let t=Object.keys(e);if(!e||t.length==0)return;let i=this._configuration.memory.clone(),r=ua.getConfigurationProperties();t.forEach(o=>{let s=e[o];if(s===void 0)i.removeValue(o);else if(r[o]!=null)i.setValue(o,s);else if(xt(s))for(let a of Object.keys(s))i.setValue(`${o}.${a}`,s[a]);else i.setValue(o,s)}),this.changeConfiguration(4,i,void 0,t)}addFolderFile(e,t=!1,i){let r=Mi(R.resolve(e,"../.."));if(this._configuration.hasFolder(r)||!F.existsSync(e))return!1;this.watchFile(e,3);let o=this.parseConfigurationModel(e);return this._configuration.addFolderConfiguration(r,o,i),LP.info(`Add folder configuration from ${t?"cwd":"file"}:`,e),!0}watchFile(e,t){if(!F.existsSync(e)||this._watchedFiles.has(e)||this.noWatch)return;this._watchedFiles.add(e);let i=3?Mi(R.resolve(e,"../..")):void 0,r=dc(e,()=>{let o=this.parseConfigurationModel(e);this.changeConfiguration(t,o,i)});this.disposables.push(r)}changeConfiguration(e,t,i,r){let o=e===0&&r&&r.every(c=>c.startsWith("list.source")),s=this._configuration,a=o?void 0:s.toData(),l;if(e===0?l=s.compareAndUpdateDefaultConfiguration(t,r):e===1?l=s.compareAndUpdateUserConfiguration(t):e===2?l=s.compareAndUpdateWorkspaceConfiguration(t):e===3?l=s.compareAndUpdateFolderConfiguration(i,t):l=s.compareAndUpdateMemoryConfiguration(t),!l||l.keys.length==0||(e!==3&&(this._initialConfiguration=this.getConfiguration(void 0,null)),o))return;let u=new jv(l,a,s);u.source=e,this._onChange.fire(u)}getDefaultResource(){var t;let e=(t=this._proxy)==null?void 0:t.root;if(!!e)return O.file(e).toString()}getConfiguration(e,t){let i=this._configuration,r=t?Iv(t):{resource:t===null?void 0:this.getDefaultResource()},o=Object.freeze(Fv(i.getValue(void 0,r),e)),s={has(a){return typeof Fv(o,a)<"u"},get:(a,l)=>{let u=Fv(o,a);return u??l},update:(a,l,u=!1)=>{var b;let c=r.resource,d=e?`${e}.${a}`:a,h;typeof u=="boolean"?h=u?1:3:h=A$(u);let g;if(h===3&&(g=this._configuration.resolveFolder(c)??this.resolveWorkspaceFolderForResource(c),!g)){console.error(`Unable to locate workspace folder configuration for ${c}`),LP.error("Unable to locate workspace folder configuration",c,Error().stack);return}let f=this._configuration.getConfigurationModel(h,g).clone();l===void 0?f.removeValue(d):f.setValue(d,l),this.changeConfiguration(h,f,g);let m;return h===3?m=this.folderToConfigfile(g):h===1&&(m=this.userConfigFile),m?(b=this._proxy)==null?void 0:b.modifyConfiguration(m,d,l):Promise.resolve()},inspect:a=>{a=e?`${e}.${a}`:a;let l=this._configuration.inspect(a,r);return{key:a,defaultValue:l.defaultValue,globalValue:l.userValue,workspaceValue:l.workspaceValue,workspaceFolderValue:l.workspaceFolderValue}}};return Object.defineProperty(s,"has",{enumerable:!1}),Object.defineProperty(s,"get",{enumerable:!1}),Object.defineProperty(s,"update",{enumerable:!1}),Object.defineProperty(s,"inspect",{enumerable:!1}),typeof o=="object"&&lT(s,o,!1),Dy(s)}locateFolderConfigution(e){let t=this._configuration.resolveFolder(e);if(t)return!0;let i=O.parse(e);if(i.scheme!=="file")return!1;let r=t=gc(".vim",i.fsPath);if(!r)return!1;t=R.dirname(r);let o=this.folderToConfigfile(t);return o?(this.addFolderFile(o,!1,e),!0):!1}resolveWorkspaceFolderForResource(e){if(this._proxy&&typeof this._proxy.getWorkspaceFolder=="function"){let t=this._proxy.getWorkspaceFolder(e);if(!t)return;let i=t.fsPath,r=this.folderToConfigfile(i);if(r)return F.existsSync(r)||(F.mkdirSync(R.dirname(r),{recursive:!0}),F.writeFileSync(r,"{}","utf8")),this.addFolderFile(r,!1,e),i}}reset(){this._errors.clear();let e=new oi;this.changeConfiguration(4,e,void 0)}dispose(){this._onError.dispose(),this._onChange.dispose(),W(this.disposables)}}});var jle,Gg,U$=D(()=>{"use strict";wg();Je();xe();de();jle=Z("configuration-shape"),Gg=class{constructor(e,t=!1){this.resolver=e;this._test=t}get root(){return this.resolver.root}async modifyConfiguration(e,t,i){if(this._test)return;jle.info(`modify configuration file: ${e}`,t,i);let r=R.dirname(e),o={tabSize:2,insertSpaces:!0};F.existsSync(r)||F.mkdirSync(r,{recursive:!0});let s=F.readFileSync(e,{encoding:"utf8",flag:"a+"});s=s||"{}";let a=EZ(s,[t],i,{formattingOptions:o});s=IZ(s,a),F.writeFileSync(e,s,{encoding:"utf8"})}getWorkspaceFolder(e){if(typeof this.resolver.getWorkspaceFolder=="function"){let t=this.resolver.getWorkspaceFolder(e);if(t)return O.parse(t.uri)}}}});function G$(n,e){let t=re(e.arglist)?"":", "+e.arglist.join(", "),i=Array.isArray(e.event)?e.event.join(","):e.event,r=e.pattern!=null?e.pattern:"*";/\buser\b/i.test(i)&&(r="");let o=e.request?"request":"notify";return`autocmd! ${FP} ${i} ${r} call coc#rpc#${o}('doAutocmd', [${n}${t}])`}var d0e,X$,FP,zg,z$=D(()=>{"use strict";xe();te();Re();U();d0e=Z("core-autocmds"),X$=0,FP="coc_dynamic_autocmd",zg=class{constructor(){this.autocmds=new Map;this.disposables=[]}attach(e,t){this.nvim=e,this.env=t}async doAutocmd(e,t){let i=this.autocmds.get(e);i&&await Promise.resolve(i.callback.apply(i.thisArg,t))}registerAutocmd(e){X$+=1;let t=X$;return this.autocmds.set(t,e),this.nvim.command(G$(t,e),!0),p.Disposable.create(()=>{this.autocmds.delete(t),this.resetDynamicAutocmd()})}resetDynamicAutocmd(){let{nvim:e}=this;e.pauseNotification(),e.command(`autocmd! ${FP}`,!0);for(let[t,i]of this.autocmds.entries())e.command(G$(t,i),!0);e.resumeNotification(!1,!0)}dispose(){this.nvim.command(`autocmd! ${FP}`,!0),W(this.disposables)}}});function K$(n){let e=`call coc#rpc#request('CocAutocmd', ['BufReadCmd','${n}', expand('')])`;return`autocmd! coc_dynamic_content BufReadCmd,FileReadCmd,SourceCmd ${n}:/* ${e}`}var Kg,Q$=D(()=>{"use strict";Je();Pe();te();U();Kg=class{constructor(e){this.documents=e;this.disposables=[];this.providers=new Map;this._onDidProviderChange=new p.Emitter;this.onDidProviderChange=this._onDidProviderChange.event}attach(e){this.nvim=e,_.on("BufReadCmd",this.onBufReadCmd,this,this.disposables)}get schemes(){return Array.from(this.providers.keys())}async onBufReadCmd(e,t){let i=this.providers.get(e);if(!i)return;let r=new p.CancellationTokenSource,o=await Promise.resolve(i.provideTextDocumentContent(O.parse(t),r.token)),s=await this.nvim.buffer;await s.setLines(o.split(/\r?\n/),{start:0,end:-1,strictIndexing:!1}),process.nextTick(()=>{_.fire("BufCreate",[s.id])})}resetAutocmds(){let{nvim:e,schemes:t}=this;e.pauseNotification(),e.command("autocmd! coc_dynamic_content BufReadCmd,FileReadCmd,SourceCmd *",!0);for(let i of t)e.command(K$(i),!0);e.resumeNotification(!1,!0)}registerTextDocumentContentProvider(e,t){this.providers.set(e,t),this._onDidProviderChange.fire();let i=[];return t.onDidChange&&t.onDidChange(async r=>{let{buffer:o}=this.documents.getDocument(r.toString()),s=new p.CancellationTokenSource,a=await Promise.resolve(t.provideTextDocumentContent(r,s.token));await o.setLines(a.split(/\r?\n/),{start:0,end:-1,strictIndexing:!1}),this.nvim.command("if &filetype ==# '' | filetype detect | endif",!0)},null,i),this.nvim.command(K$(e),!0),p.Disposable.create(()=>{this.providers.delete(e),W(i),this.resetAutocmds(),this._onDidProviderChange.fire()})}dispose(){W(this.disposables),this._onDidProviderChange.dispose(),this.providers.clear()}}});function V$(n,e,t){let i=0,r=0,o=n.slice(t+1);for(let l=0;lr&&s.length){let l=0;for(let u=0;u=b&&v!==m&&(v+=1);let x=0;for(let T=0;T0?d.join(` +`)+` +`:"";if(!(h.length===0&&a===r-c))return Ye.replace(M.create(a,0,r-c,0),h)}var MP=D(()=>{"use strict";ae();de();fe()});function ti(n,e){return Ft(n.start,e)===0&&Ft(n.end,e)===0}function iU(n,e){return Bv(n.start,e.start)?Bv(n.end,e.end):!1}function Bv(n,e){return n.line===e.line&&n.character===e.character}function Dc(n,e){let t=n.start.line|0,i=e.start.line|0;if(t===i){let r=n.start.character|0,o=e.start.character|0;if(r===o){let s=n.end.line|0,a=e.end.line|0;if(s===a){let l=n.end.character|0,u=e.end.character|0;return l-u}return s-a}return r-o}return t-i}function nU(n,e){let{start:t,end:i}=n;if(t.line>i.line||t.line===i.line&&t.character>i.character){let o=t;t=i,i=o}t=Q.create(Math.max(0,t.line),Math.max(0,t.character));let r=Math.max(0,i.character);return typeof e=="number"&&r>e&&(r=e),i=Q.create(Math.max(0,i.line),r),{start:t,end:i}}function qv(n,e){return Ge(n.end,e.start)==0||Ge(e.end,n.start)==0}function Tc(n,e){let{start:t,end:i}=n;return!(Ge(i,e.start)<=0||Ge(t,e.end)>=0)}function Ll(n,e){return!!(Ft(n.start,e)==0||Ft(n.end,e)==0||ti(e,n))}function rU(n,e){let{line:t,character:i}=e,{start:r,end:o}=n,s=o.line==r.line?o.character+i:o.character;return M.create(r.line+t,i+r.character,o.line+t,s)}function oU(n,e){let{start:t,end:i}=e;return n>=t.line&&n<=i.line}function Gt(n){let{start:e,end:t}=n;return e.line==t.line&&e.character==t.character}function Ft(n,e){let{start:t,end:i}=e;return Ge(n,t)<0?-1:Ge(n,i)>0?1:0}function Ge(n,e){return n.line>e.line||e.line==n.line&&n.character>e.character?1:e.line==n.line&&n.character==e.character?0:-1}function sU(n){return n.start.line==n.end.line}function on(n,e){let t=e.split(/\r?\n/),i=t.length,r=t[i-1],o=i==1?n.character+e.length:r.length;return Q.create(n.line+i-1,o)}var Tt=D(()=>{"use strict";ae()});function aU(n){let{start:e,end:t}=n.range;return n.newText.endsWith(` +`)&&e.line==t.line&&e.character==0&&t.character==0?e.line-1:e.line}function ca(n){let{newText:e}=n,t=Wv(n.range),i=t.end.line-t.start.line;return e.split(/\r?\n/).length-i-1}function Wv(n){let e=n.start,t=n.end;return e.line>t.line||e.line===t.line&&e.character>t.character?{start:t,end:e}:n}function jP(n,e){if(n.length<=1)return n;let t=n.length/2|0,i=n.slice(0,t),r=n.slice(t);jP(i,e),jP(r,e);let o=0,s=0,a=0;for(;o{let i=e.range.start.line-t.range.start.line;return i===0?e.range.start.character-t.range.start.character:i})}function lU(n){let{changes:e,documentChanges:t}=n;return!(t&&t.length||e&&Object.keys(e).length)}function uU(n,e){let{changes:t,documentChanges:i}=e;if(t){let r=t[n];return r?r.map(o=>o.range):void 0}else if(Array.isArray(i)){for(let r of i)if(Qt.is(r)&&r.textDocument.uri==n)return r.edits.map(o=>o.range)}}function cU(n,e){let t=[],i=r=>{var o;r&&!t.includes(r)&&((o=e[r])==null?void 0:o.needsConfirmation)&&t.push(r)};for(let r of n)Qt.is(r)?r.edits.forEach(o=>{i(o.annotationId)}):i(r.annotationId);return t}function Ole(n,e){return!!(_n.is(n)&&e.includes(n.annotationId))}function dU(n,e){let t=[];return n.forEach(i=>{if(Qt.is(i)){let r=i.edits.filter(o=>!Ole(o,e));r.length>0&&t.push({textDocument:i.textDocument,edits:r})}else e.includes(i.annotationId)||t.push(i)}),t}function hU(n){let e;return Qt.is(n)?_n.is(n.edits[0])&&(e=n.edits[0].annotationId):e=n.annotationId,e}function gU(n){if(n.documentChanges)return n.documentChanges;let e=[];for(let[t,i]of Object.entries(Ue(n.changes)))e.push({textDocument:{uri:t,version:null},edits:i});return e}function pU(n,e){let t=[],i=n.end,r=i.line>0&&i.character==0,o;for(let s=0;s0){let h=t[t.length-1];h.newText=l,o=void 0;continue}o=void 0}l.includes("\r")&&(l=l.replace(/\r\n/g,` +`));let d=Ge(u.end,i);if(d>0&&(u.end={line:i.line,character:i.character}),n.getText(u)!==l){if(d===0&&r&&!Gt(u)&&l.endsWith(` +`)){l=l.slice(0,-1);let h=n.lines[i.line-1];u.end=Q.create(i.line-1,h.length)}else l.length==0&&(o=u.start);t.push({range:u,newText:l})}}return OP(t)}function fU(n,e){if(re(e))return;if(e.length==1){let{start:s,end:a}=e[0].range,{lines:l}=n,u=l[s.line]??"",c=l[a.line]??"",d=u.substring(0,s.character)+e[0].newText+c.substring(a.character);return a.line>=l.length&&n.eol?d==""?[...l.slice(0,s.line)]:(d.endsWith(` +`)&&(d=d.slice(0,-1)),[...l.slice(0,s.line),...d.split(` +`)]):[...l.slice(0,s.line),...d.split(` +`),...l.slice(a.line+1)]}let t=n.getText(),i=0,r=[];for(let s of e){let a=n.offsetAt(s.range.start);if(ai&&r.push(t.substring(i,a)),s.newText.length&&r.push(s.newText),i=n.offsetAt(s.range.end)}r.push(t.substring(i));let o=r.join("");if(o!==t)return gZ(o,n.eol)}function mU(n,e){return e.map(t=>{let{start:i,end:r}=t.range,o=oe(n[i.line]),s=nt(o,i.character),a=r.line==i.line?o:oe(n[r.line]),l=nt(a,r.character),{newText:u}=t;return[u.length>0?u.split(` +`):[],i.line,s,r.line,l]})}function Yv(n,e){let{range:t,newText:i}=e;if(Ge(t.end,n)<=0){let r=i.split(` +`),o=r.length-(t.end.line-t.start.line)-1,s=n.character;if(t.end.line==n.line){let a=r[r.length-1].length;r.length>1?s=a+s-t.end.character:s=t.start.character+a+s-t.end.character}return{line:o,character:s-n.character}}return{line:0,character:0}}function Zv(n,e){let{line:t,character:i}=n,{range:r,newText:o}=e,{end:s}=r,a=o.split(` +`),l=a.length-(s.line-r.start.line)-1,u=r.end.line-n.line;if(u>0)return{line:t,character:i};if(u<0)return{line:t+l,character:i};if(a.length>1){let d=a[a.length-1].length;return{line:t+l,character:d+i-s.character}}let c=r.start.character-r.end.character;return{line:t+l,character:c+o.length+i}}function Jv(n,e){let t=Q.create(n.line,n.character),i=!1;for(let r=e.length-1;r>=0;r--){let o=e[r];if(i){t.line+=ca(o);continue}Ge(o.range.end,t)>0||(o.range.end.line==t.line?t=Zv(t,o):(i=!0,t.line+=ca(o)))}return t}function AP(n,e){let t=0;for(let i of e){let r=Wv(i.range);Ge(r.end,n)<=0&&(t+=ca(i))}return t}function bU(n,e,t){let i=n[0].range.start,r=n[n.length-1].range.end,o=e.length-r.line,s=(e[r.line]??"").length-r.character,a=t.length-o,l=(t[a]??"").length-s,u=Ale(i,Q.create(a,l),t);return Ye.replace(M.create(i,r),u)}function Ale(n,e,t){if(n.line===e.line)return oe(t[n.line]).slice(n.character,e.character);let i=[];for(let r=n.line;r<=e.line;r++){let o=t[r]??"";r===n.line?i.push(o.slice(n.character)):r===e.line?i.push(o.slice(0,e.character)):i.push(o)}return i.join(` +`)}var wr=D(()=>{"use strict";ae();Re();Be();Tt();fe()});function HP(n){if(/^\d+$/.test(n))return parseInt(n,10);if(n.length>0)return n.charCodeAt(0)}function BP(n,e){return n=NP}function*qle(n){if(Intl===void 0||typeof Intl.Segmenter!="function"){yield n;return}let e=[],t=new Intl.Segmenter("cn",{granularity:"word"}).segment(n);for(let i of t)i.isWordLike&&(yield i.segment);return e}function Wle(n){let e=[],t=0,i=0,r=n.length;for(;t{"use strict";ae();te();Re();Be();fe();Nle=[[257,893],[895,902],[904,1369],[1376,1416],[1418,1469],[1471,1471],[1473,1474],[1476,1522],[1525,1547],[1549,1562],[1564,1566],[1568,1641],[1646,1747],[1749,1791],[1806,2403],[2406,2415],[2417,3571],[3573,3662],[3664,3673],[3676,3843],[3859,3897],[3902,3972],[3974,4169],[4176,4346],[4348,4960],[4969,5740],[5743,5759],[5761,5786],[5789,5866],[5870,5940],[5943,6099],[6109,6143],[6155,8191],[10240,10495],[10649,10711],[10716,10747],[10750,11775],[11904,12287],[12321,12335],[12337,12348],[12350,64829],[64832,65071],[65132,65279],[65296,65305],[65313,65338],[65345,65370],[65382,65535]],Hle=65535,Ble=/[\u4e00-\u9fa5]/,NP=19968;kc=class{constructor(e=[],t=!1){this.ranges=e;this.wordChars=t}clone(){return new kc(this.ranges.slice(),this.wordChars)}add(e,t){let i=0,r=0;if(t!=null&&tt)break;if(r++,st){t=a;break}}this.ranges.splice(i,r,[e,t])}exclude(e,t){if(t!=null&&tt)break;if(r++,at){o.push([t+1,l]);break}}r==0&&o.length==0||this.ranges.splice(i,r,...o)}flatten(){return this.ranges.reduce((e,t)=>e.concat(t),[])}includes(e){return e>256&&this.wordChars?dg(e,Nle):dg(e,this.ranges)}static fromKeywordOption(e){let t=new kc;for(let i of Wle(e)){let r=i.length>1&&i.startsWith("^"),o=r?"exclude":"add";if(r&&(i=i.slice(1)),i==="@"&&!r)t.wordChars=!0,t[o](65,90),t[o](97,122),t[o](192,255);else if(i=="@-@")t[o]("@".charCodeAt(0));else if(i.length==1||/^\d+$/.test(i))t[o](HP(i));else if(i.includes("-")){let s=i.split("-",2),a=HP(s[0]),l=HP(s[1]);if(a===void 0||l===void 0)continue;t[o](a,l)}}return t}},Pc=class{constructor(e){this.ranges=kc.fromKeywordOption(e)}addKeyword(e){this.ranges.add(e.codePointAt(0))}clone(){let e=new Pc("");return e.ranges=this.ranges.clone(),e}isKeywordCode(e){return e===32||e>Hle||Uy(e)?!1:this.ranges.includes(e)}isKeywordChar(e){let t=e.charCodeAt(0);return this.isKeywordCode(t)}isKeyword(e){for(let t=0,i=e.length;ti&&(e=e.slice(0,i),o=i);for(let[s,a]of this.iterateWords(e)){if(a-s15){if(i&&i.isCancellationRequested)break;await ar(),a=Date.now()}for(let[d,h]of this.iterateWords(u)){let g=u.slice(d,h),f=Rn(s,g)?s[g]:[];f.push(M.create(l,d+c,l,h+c)),s[g]=f}}return s}}});var $v,yU=D(()=>{"use strict";ae();$v=class{constructor(e,t,i){this._line=e,this._text=t,this._isLastLine=i}get lineNumber(){return this._line}get text(){return this._text}get range(){return M.create(this._line,0,this._line,this._text.length)}get rangeIncludingLineBreak(){return this._isLastLine?this.range:M.create(this._line,0,this._line+1,0)}get firstNonWhitespaceCharacterIndex(){return/^(\s*)/.exec(this._text)[1].length}get isEmptyOrWhitespace(){return this.firstNonWhitespaceCharacterIndex===this._text.length}}});function Yle(n,e){let t=[],i=0;for(let r of n)t.push(i),i+=r.length+1;return e&&t.push(i),t}var Rc,vU=D(()=>{"use strict";ae();fe();yU();Rc=class{constructor(e,t,i,r,o,s){this.uri=e;this.languageId=t;this.version=i;this.lines=r;this.bufnr=o;this.eol=s}get content(){return this._content||(this._content=this.lines.join(` +`)+(this.eol?` +`:"")),this._content}get length(){if(!this._content){let e=this.lines.reduce((t,i)=>t+i.length+1,0);return this.eol?e:e-1}return this._content.length}get end(){let e=this.lineCount-1;return this.eol?Q.create(e,0):Q.create(e,this.lines[e].length)}get lineCount(){return this.lines.length+(this.eol?1:0)}getText(e){if(e){let{start:t,end:i}=e;return t.line===i.line?t.character===i.character?"":oe(this.lines[t.line]).substring(t.character,i.character):this.content.substring(this.offsetAt(e.start),this.offsetAt(e.end))}return this.content}lineAt(e){let t=Q.is(e)?e.line:e;if(typeof t!="number"||t<0||t>=this.lineCount||Math.floor(t)!==t)throw new Error("Illegal value for `line`");return new $v(t,this.lines[t]??"",t===this.lineCount-1)}positionAt(e){e=Math.max(Math.min(e,this.content.length),0);let t=this.getLineOffsets(),i=0,r=t.length;if(r===0)return{line:0,character:e};for(;ie?r=s:i=s+1}let o=i-1;return{line:o,character:e-t[o]}}offsetAt(e){let t=this.getLineOffsets();if(e.line>=t.length)return this.content.length;if(e.line<0)return 0;let i=t[e.line],r=e.line+1{"use strict";xU=require("buffer");ae();Je();Pe();Yt();MP();te();Xe();de();Be();Tt();U();fe();wr();qP();vU();wU=pe(150,15),Qg=class{constructor(e,t,i,r){this.buffer=e;this.env=t;this.nvim=i;this.isIgnored=!1;this.eol=!0;this._disposed=!1;this._attached=!1;this._notAttachReason="";this._previewwindow=!1;this._winid=-1;this.disposables=[];this.lines=[];this._onDocumentChange=new p.Emitter;this.onDocumentChange=this._onDocumentChange.event;this.fireContentChanges=ft(()=>{this._fireContentChanges()},wU),this.fetchContent=ft(()=>{this._fetchContent()},wU),this.init(r)}get content(){return this.syncLines.join(` +`)+(this.eol?` +`:"")}get attached(){return this._attached}get textDocument(){return this._textDocument}get syncLines(){return this._textDocument.lines}get version(){return this._textDocument.version}get bufnr(){return this.buffer.id}get bufname(){return this._bufname}get filetype(){return this._filetype}get uri(){return this._uri}get isCommandLine(){return this.uri&&this.uri.endsWith("%5BCommand%20Line%5D")}get languageId(){let{_filetype:e}=this;return e.includes(".")?e.match(/(.*?)\./)[1]:e}get changedtick(){return this._changedtick}convertFiletype(e){switch(e){case"javascript.jsx":return"javascriptreact";case"typescript.jsx":case"typescript.tsx":return"typescriptreact";case"tex":return"latex";default:{let t=this.env.filetypeMap;return String(t[e]||e)}}}get schema(){return O.parse(this.uri).scheme}get lineCount(){return this.lines.length}get winid(){return this._winid}get previewwindow(){return this._previewwindow}init(e){let t=this.buftype=e.buftype;this._bufname=e.bufname,this._previewwindow=!!e.previewwindow,this._winid=e.winid,this.variables=Ue(e.variables),this._changedtick=e.changedtick,this.eol=e.eol==1,this._uri=Zle(e.fullpath,this.bufnr,t,this.env.isCygwin),Array.isArray(e.lines)?(this.lines=e.lines,this._noFetch=!0,this._attached=!0,this.attach()):this._notAttachReason=Jle(t,this.variables.coc_enabled,e.size),this._filetype=this.convertFiletype(e.filetype),this.setIskeyword(e.iskeyword,e.lisp),this.createTextDocument(1,this.lines)}get notAttachReason(){return this._notAttachReason}attach(){if(vi)return;let e=this.lines;this.buffer.attach(!0).then(t=>{t||WP(this.bufnr)},t=>{WP(this.bufnr)}),this.buffer.listen("lines",(t,i,r,o,s)=>{if(i&&i>this._changedtick){if(this._changedtick=i,e=[...e.slice(0,r),...s,...o==-1?[]:e.slice(o)],e.length==0&&(e=[""]),this.lines=e,_c(t.id),_.pumvisible)return;this.fireContentChanges()}},this.disposables),this.buffer.listen("detach",()=>{WP(this.bufnr)},this.disposables)}get dirty(){return this.lines!==this.syncLines}get hasChanged(){return this.dirty?!Me(this.lines,this.syncLines):!1}_fireContentChanges(e){if(this.lines===this.syncLines)return;let t=this._textDocument,i=[];if(!e){let{cursor:s}=_,a;if(s.bufnr==this.bufnr){let l=this.lines[s.lnum-1]??"";a=Q.create(s.lnum-1,Ut(l,s.col-1))}e=tU(t.lines,this.lines,a,s.insert)}let r;e?(r=t.getText(e.range),i.push({range:e.range,text:e.newText,rangeLength:r.length})):r="";let o=this.createTextDocument(this.version+(e?1:0),this.lines);this._onDocumentChange.fire(Object.freeze({bufnr:this.bufnr,original:r,originalLines:t.lines,textDocument:{version:o.version,uri:this.uri},contentChanges:i}))}async applyEdits(e,t=!1,i=!1){if(Array.isArray(arguments[1])&&(e=arguments[1]),!this._attached||e.length===0)return;this._forceSync();let r=this.textDocument;e=pU(r,e);let o=fU(r,e);if(!o)return;let s=r.lines,a=V$(s,o,aU(e[0])),l=a.start===a.end&&a.start===s.length,u=s.slice(a.start,a.end),c=[];e.length<200&&a.start!==a.end&&e[e.length-1].range.end.line0?` +`:""))}async changeLines(e){let t=[],i=this.lines.slice();for(let[r,o]of e)i[r]!=o&&(t.push([r,o]),i[r]=o);!t.length||(this.nvim.call("coc#ui#change_lines",[this.bufnr,t],!0),this.nvim.redrawVim(),this.lines=i,_c(this.bufnr),this._forceSync())}_forceSync(){this.fireContentChanges.clear(),this._fireContentChanges()}forceSync(){}getOffset(e,t){return this.textDocument.offsetAt({line:e-1,character:t})}isWord(e){return this.chars.isKeyword(e)}getStartWord(e){let t=0;for(;t=0;){let u=o[a-1];if(!u||!r.isKeywordChar(u))break;a=a-1}for(;l<=o.length;){let u=o[l];if(!u||!r.isKeywordChar(u))break;l=l+1}return M.create(e.line,a,e.line,l)}createTextDocument(e,t){let{uri:i,languageId:r,eol:o}=this;return this._textDocument=new Rc(i,r,e,t,this.bufnr,o)}getSymbolRanges(e){let{version:t,filetype:i,uri:r}=this,o=new Rc(r,i,t,this.lines,this.bufnr,this.eol),s=[],a=o.getText(),l="";for(let u=0,c=a.length;u0&&!h&&l==e&&s.push(M.create(o.positionAt(u-l.length),o.positionAt(u))),h||(l="")}return s}fixStartcol(e,t){let i=this.getline(e.line);if(!i)return 0;let{character:r}=e,o=i.slice(0,r),s=ue(o),{chars:a}=this;for(let l=o.length-1;l>=0;l--){let u=o[l];if(!a.isKeywordChar(u)&&!t.includes(u))break;s=s-ue(u)}return s}addHighlights(e,t,i,r={}){let{start:o,end:s}=i;if(!Gt(i))for(let a=o.line;a<=s.line;a++){let l=this.getline(a,!1),u=a==o.line?nt(l,o.character):0,c=a==s.line?nt(l,s.character):xU.Buffer.byteLength(l);u>=c||e.push(Object.assign({hlGroup:t,lnum:a,colStart:u,colEnd:c},r))}}getline(e,t=!0){return t?this.lines[e]||"":this.syncLines[e]||""}getLines(e,t){return this.lines.slice(e??0,t??this.lines.length)}getDocumentContent(){let e=this.lines.join(` +`);return this.eol?e+` +`:e}getVar(e,t){let i=this.variables[`coc_${e}`];return i===void 0?t:i}getPosition(e,t){let i=this.getline(e-1);if(!i||t==0)return{line:e-1,character:0};let r=Xt(i,0,t-1);return{line:e-1,character:r.length}}setFiletype(e){this._filetype=this.convertFiletype(e);let t=this._textDocument.lines;this._textDocument=new Rc(this.uri,this.languageId,1,t,this.bufnr,this.eol)}setIskeyword(e,t){let i=this.chars=new Pc(e),r=this.getVar("additional_keywords",[]);if(t&&i.addKeyword("-"),r&&Array.isArray(r))for(let o of r)i.addKeyword(o)}detach(){W(this.disposables),!this._disposed&&(this._disposed=!0,this._attached=!1,this.lines=[],this.fetchContent.clear(),this.fireContentChanges.clear(),this._onDocumentChange.dispose())}async synchronize(){if(!this.attached)return;let{changedtick:e}=this;await this.patchChange(),e!=this.changedtick&&await Zi(50)}async patchChange(e){if(!!this._attached)if(vi)if(e){let t=await this.nvim.call("coc#util#get_changeinfo",[this.bufnr]);if(!t||t.changedtick{"use strict";Uv.exports=Gle;Uv.exports.format=SU;Uv.exports.parse=DU;var $le=/\B(?=(\d{3})+(?!\d))/g,Ule=/(?:\.0*|(\.[^0]+)0+)$/,da={b:1,kb:1<<10,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},Xle=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function Gle(n,e){return typeof n=="string"?DU(n):typeof n=="number"?SU(n,e):null}function SU(n,e){if(!Number.isFinite(n))return null;var t=Math.abs(n),i=e&&e.thousandsSeparator||"",r=e&&e.unitSeparator||"",o=e&&e.decimalPlaces!==void 0?e.decimalPlaces:2,s=Boolean(e&&e.fixedDecimals),a=e&&e.unit||"";(!a||!da[a.toLowerCase()])&&(t>=da.pb?a="PB":t>=da.tb?a="TB":t>=da.gb?a="GB":t>=da.mb?a="MB":t>=da.kb?a="KB":a="B");var l=n/da[a.toLowerCase()],u=l.toFixed(o);return s||(u=u.replace(Ule,"$1")),i&&(u=u.split(".").map(function(c,d){return d===0?c.replace($le,i):c}).join(".")),u+r+a}function DU(n){if(typeof n=="number"&&!isNaN(n))return n;if(typeof n!="string")return null;var e=Xle.exec(n),t,i="b";return e?(t=parseFloat(e[1]),i=e[4].toLowerCase()):(t=parseInt(n,10),i="b"),isNaN(t)?null:Math.floor(da[i]*t)}});var Xv,zle,Vg,kU=D(()=>{"use strict";ae();Je();Pe();xe();CU();te();st();de();wl();U();fe();Xv=Z("core-documents"),zle=Mi(process.cwd()),Vg=class{constructor(e,t){this.configurations=e;this.workspaceFolder=t;this._attached=!1;this._currentResolve=!1;this.disposables=[];this.creating=new Map;this.buffers=new Map;this.resolves=[];this._onDidOpenTextDocument=new p.Emitter;this._onDidCloseDocument=new p.Emitter;this._onDidChangeDocument=new p.Emitter;this._onDidSaveDocument=new p.Emitter;this._onWillSaveDocument=new p.Emitter;this.onDidOpenTextDocument=this._onDidOpenTextDocument.event;this.onDidCloseDocument=this._onDidCloseDocument.event;this.onDidChangeDocument=this._onDidChangeDocument.event;this.onDidSaveTextDocument=this._onDidSaveDocument.event;this.onWillSaveTextDocument=this._onWillSaveDocument.event;this._cwd=zle,this.getConfiguration(),this.configurations.onDidChange(this.getConfiguration,this,this.disposables)}async attach(e,t){if(this._attached)return;this.nvim=e,this._env=t,this._attached=!0;let{bufnrs:i,bufnr:r}=await this.nvim.call("coc#util#all_state");this._bufnr=r,await Promise.all(i.map(s=>this.createDocument(s))),_.on("BufDetach",this.onBufDetach,this,this.disposables),_.on("BufRename",async s=>{this.detachBuffer(s),await this.createDocument(s)},null,this.disposables),_.on("DirChanged",s=>{this._cwd=Mi(s)},null,this.disposables);let o=s=>{this._bufnr=s,this.createDocument(s)};_.on("CursorMoved",o,null,this.disposables),_.on("CursorMovedI",o,null,this.disposables),_.on("BufUnload",this.onBufUnload,this,this.disposables),_.on("BufEnter",this.onBufEnter,this,this.disposables),_.on("BufCreate",this.onBufCreate,this,this.disposables),_.on("TermOpen",this.onBufCreate,this,this.disposables),_.on("BufWritePost",this.onBufWritePost,this,this.disposables),_.on("BufWritePre",this.onBufWritePre,this,this.disposables),_.on("FileType",this.onFileTypeChange,this,this.disposables),_.on("BufEnter",s=>{this.createDocument(s)},null,this.disposables),this._env.isVim&&["TextChangedP","TextChangedI","TextChanged"].forEach(s=>{_.on(s,(a,l)=>{let u=this.buffers.get(a);u&&u.attached&&u.onTextChange(s,l)},null,this.disposables)})}getConfiguration(e){if(!e||e.affectsConfiguration("coc.preferences")){let t=this.configurations.initialConfiguration.get("coc.preferences"),i=TU();this.config={maxFileSize:i.parse(t.maxFileSize),willSaveHandlerTimeout:Ie(t.willSaveHandlerTimeout,500),useQuickfixForLocations:t.useQuickfixForLocations}}}get bufnr(){return this._bufnr}get root(){return this._root}get cwd(){return this._cwd}get documents(){return Array.from(this.buffers.values()).filter(e=>e.attached)}*attached(e){for(let t of this.buffers.values())!t.attached||e&&t.schema!==e||(yield t)}get bufnrs(){return this.buffers.keys()}detach(){this._attached=!1;for(let e of this.buffers.keys())this.onBufUnload(e)}resolveRoot(e,t=!1){let i=this.getDocument(this.bufnr),r;if(i&&i.schema=="file"){let o=R.dirname(O.parse(i.uri).fsPath);r=xg(o,e,this.cwd)}else r=xg(this.cwd,e);if(t&&!r)throw new Error("Required root pattern not resolved.");return r}get textDocuments(){let e=[];for(let t of this.buffers.values())t.attached&&e.push(t.textDocument);return e}getDocument(e){if(typeof e=="number")return this.buffers.get(e);let t=Ur||vl;e=O.parse(e).toString();for(let i of this.buffers.values())if(i.uri===e||t&&i.uri.toLowerCase()===e.toLowerCase())return i;return null}expand(e){if(e.startsWith("~")&&(e=Pt.homedir()+e.slice(1)),e.includes("$")){let t=this.getDocument(this.bufnr),i=t?O.parse(t.uri).fsPath:"",r=this._root||this._cwd;e=e.replace(/\$\{(.*?)\}/g,(o,s)=>{if(s.startsWith("env:")){let a=s.split(":")[1];return a?process.env[a]:""}switch(s){case"userHome":return Pt.homedir();case"workspace":case"workspaceRoot":case"workspaceFolder":return r;case"workspaceFolderBasename":return R.basename(r);case"cwd":return this._cwd;case"file":return i;case"fileDirname":return i?R.dirname(i):"";case"fileExtname":return i?R.extname(i):"";case"fileBasename":return i?R.basename(i):"";case"fileBasenameNoExtension":{let a=i?R.basename(i):"";return a?a.slice(0,a.length-R.extname(a).length):""}default:return o}}),e=e.replace(/\$[\w]+/g,o=>o=="$HOME"?Pt.homedir():process.env[o.slice(1)]||o)}return e}get document(){return this._currentResolve?new Promise(e=>{this.resolves.push(e)}):(this._currentResolve=!0,new Promise(e=>{this.nvim.eval(`coc#util#get_bufoptions(bufnr("%"),${this.config.maxFileSize})`).then(t=>{let i;t!=null&&(this.creating.delete(t.bufnr),i=this._createDocument(t)),this.resolveCurrent(i),e(i),this._currentResolve=!1},()=>{e(void 0),this._currentResolve=!1})}))}resolveCurrent(e){if(this.resolves.length>0)for(;this.resolves.length;){let t=this.resolves.pop();t&&t(e)}}get uri(){let{bufnr:e}=this;if(e){let t=this.getDocument(e);if(t)return t.uri}return null}get filetypes(){let e=new Set;for(let t of this.attached())e.add(t.filetype);return e}getLanguageId(e){let t=R.extname(e);if(!t)return"";for(let i of this.attached()){let r=O.parse(i.uri).fsPath;if(R.extname(r)==t)return i.languageId}return""}async getLines(e){let t=this.getDocument(e);if(t)return t.textDocument.lines;let i=O.parse(e);if(i.scheme!=="file")return[];try{return(await Cg(i.fsPath,"utf8")).split(/\r?\n/)}catch{return[]}}get languageIds(){let e=new Set;for(let t of this.attached())e.add(t.languageId);return e}async getFormatOptions(e){let t;e&&(t=this.getDocument(e));let i=t?t.bufnr:0,r=await this.nvim.call("coc#util#get_format_opts",[i]),o={tabSize:r.tabsize,insertSpaces:r.expandtab==1};return o.insertFinalNewline=r.insertFinalNewline==1,r.trimTrailingWhitespace&&(o.trimTrailingWhitespace=!0),r.trimFinalNewlines&&(o.trimFinalNewlines=!0),o}async createDocument(e){let t=this.buffers.get(e);if(t)return t;if(this.creating.has(e))return await this.creating.get(e);let i=new Promise(r=>{this.nvim.call("coc#util#get_bufoptions",[e,this.config.maxFileSize]).then(o=>{if(!this.creating.has(e)){r(void 0);return}if(this.creating.delete(e),!o){r(void 0);return}t=this._createDocument(o),r(t)},()=>{this.creating.delete(e),r(void 0)})});return this.creating.set(e,i),await i}async onBufCreate(e){this.onBufUnload(e),await this.createDocument(e)}_createDocument(e){let{bufnr:t}=e;if(this.buffers.has(t))return this.buffers.get(t);let i=this.nvim.createBuffer(t),r=new Qg(i,this._env,this.nvim,e);if(e.size>this.config.maxFileSize&&Xv.warn(`buffer ${e.bufnr} size exceed maxFileSize ${this.config.maxFileSize}, not attached.`),this.buffers.set(t,r),r.attached){if(r.schema=="file"){this.configurations.locateFolderConfigution(r.uri);let o=this.workspaceFolder.resolveRoot(r,this._cwd,!0,this.expand.bind(this));o&&t==this._bufnr&&this.changeRoot(o)}this._onDidOpenTextDocument.fire(r.textDocument),r.onDocumentChange(o=>this._onDidChangeDocument.fire(o))}return Xv.debug("buffer created",t,r.attached,r.uri),r}onBufEnter(e){this._bufnr=e;let t=this.buffers.get(e);if(t){let i=this.workspaceFolder.getWorkspaceFolder(O.parse(t.uri));i&&(this._root=O.parse(i.uri).fsPath)}}onBufUnload(e){this.creating.delete(e),this.onBufDetach(e,!1)}async onBufDetach(e,t=!0){this.detachBuffer(e),t&&await this.nvim.call("bufloaded",[e])&&await this.createDocument(e)}detachBuffer(e){let t=this.buffers.get(e);!t||(Xv.debug("document detach",e,t.uri),this._onDidCloseDocument.fire(t.textDocument),this.buffers.delete(e),t.detach())}async onBufWritePost(e,t){let i=this.buffers.get(e);i&&(i.changedtick!=t&&await i.patchChange(),this._onDidSaveDocument.fire(i.textDocument))}async onBufWritePre(e,t,i){let r=this.buffers.get(e);if(!r||!r.attached||r.bufname!=t&&(this.detachBuffer(e),r=await this.createDocument(e),!r.attached))return;r.changedtick!=i?await r.synchronize():await r.patchChange();let o=!0,s=[],a={document:r.textDocument,reason:p.TextDocumentSaveReason.Manual,waitUntil:u=>{o?s.push(u):this.nvim.echoError("waitUntil can't be used in async manner, check log for details")}};this._onWillSaveDocument.fire(a),o=!1;let l=s.length;if(l){let c=await new Promise(d=>{let h=this.config.willSaveHandlerTimeout,g=setTimeout(()=>{this.nvim.outWriteLine(`Will save handler timeout after ${h}ms`),d(void 0)},h),f=0,m=!1;for(let b of s){let v=x=>{m||(m=!0,clearTimeout(g),d(x))};b.then(x=>{if(Array.isArray(x)&&x.length&&Ye.is(x[0]))return v(x);f=f+1,f==l&&v(void 0)},x=>{Xv.error("Error on will save handler:",x),f=f+1,f==l&&v(void 0)})}});c&&await r.applyEdits(c,!1,this.bufnr===r.bufnr)}}onFileTypeChange(e,t){let i=this.getDocument(t);!i||i.convertFiletype(e)==i.filetype||(this._onDidCloseDocument.fire(i.textDocument),i.setFiletype(e),this._onDidOpenTextDocument.fire(i.textDocument))}async getQuickfixList(e){let t={},i=e.reduce((r,o)=>{let s=O.parse(o.uri);return s.scheme=="file"&&!r.includes(s.fsPath)&&!this.getDocument(o.uri)&&r.push(s.fsPath),r},[]);return await Promise.all(i.map(r=>new Promise(o=>{Cg(r,"utf8").then(s=>{t[r]=s.split(/\r?\n/),o(void 0)},()=>{o()})}))),await Promise.all(e.map(r=>{let{uri:o,range:s}=r,{fsPath:a}=O.parse(o),l,u=t[a];return u&&(l=u[s.start.line]),this.getQuickfixItem(r,l)}))}async showLocations(e){let{nvim:t}=this,i=await this.getQuickfixList(e);if(this.config.useQuickfixForLocations){let r=await t.getVar("coc_quickfix_open_command");typeof r!="string"&&(r=i.length<10?`copen ${i.length}`:"copen"),t.pauseNotification(),t.call("setqflist",[i],!0),t.command(r,!0),t.resumeNotification(!1,!0)}else await t.setVar("coc_jump_locations",i),this._env.locationlist?t.command("CocList --normal --auto-preview location",!0):t.call("coc#util#do_autocmd",["CocLocationsChange"],!0)}async getQuickfixItem(e,t,i="",r){let o=e.targetRange;pr.is(e)&&(e=Ke.create(e.targetUri,e.targetRange));let s=this.getDocument(e.uri),{uri:a,range:l}=e,{start:u,end:c}=l,d=O.parse(a);!t&&d.scheme=="file"&&(t=await this.getLine(a,u.line));let h=u.line==c.line?t:await this.getLine(a,c.line),g={uri:a,filename:d.scheme=="file"?d.fsPath:a,lnum:u.line+1,end_lnum:c.line+1,col:t?nt(t,u.character)+1:u.character+1,end_col:h?nt(h,c.character)+1:c.character+1,text:t||"",range:l};return o&&(g.targetRange=o),r&&(g.module=r),i&&(g.type=i),s&&(g.bufnr=s.bufnr),g}async getLine(e,t){let i=this.getDocument(e);if(i&&i.attached)return i.getline(t)||"";if(!e.startsWith("file:"))return"";let r=O.parse(e).fsPath;return F.existsSync(r)?await AZ(r,t):""}async readFile(e){let t=this.getDocument(e);if(t)return await t.patchChange(),t.content;let i=O.parse(e);return i.scheme!="file"?"":(await this.nvim.call("readfile",[i.fsPath])).join(` +`)+` +`}reset(){this.creating.clear();for(let e of this.buffers.keys())this.onBufUnload(e);this.buffers.clear(),this.changeRoot(process.cwd())}changeRoot(e){this._root=Mi(e)}dispose(){for(let e of this.buffers.keys())this.onBufUnload(e);this._attached=!1,this.buffers.clear(),W(this.disposables)}}});function Qle(n,e){let{document:t,uri:i}=n;if(t.bufnr!=e.bufnr)return!1;let r=O.parse(i);return r.scheme==="file"?!ai(r.fsPath,e.fullpath):!1}var Kle,ep,PU=D(()=>{"use strict";ae();Je();Pe();xe();st();U();Kle=Z("core-editors");ep=class{constructor(e){this.documents=e;this.disposables=[];this.editors=new Map;this.tabIds=new Set;this._onDidTabClose=new p.Emitter;this._onDidChangeActiveTextEditor=new p.Emitter;this._onDidChangeVisibleTextEditors=new p.Emitter;this.onDidTabClose=this._onDidTabClose.event;this.onDidChangeActiveTextEditor=this._onDidChangeActiveTextEditor.event;this.onDidChangeVisibleTextEditors=this._onDidChangeVisibleTextEditors.event}get activeTextEditor(){return this.editors.get(this.winid)}get visibleTextEditors(){return Array.from(this.editors.values())}isVisible(e){for(let t of this.editors.values())if(t.bufnr==e)return!0;return!1}onChangeCurrent(e){let t=e.id;t!==this.previousId&&(this.previousId=t,this._onDidChangeActiveTextEditor.fire(e))}async attach(e){this.nvim=e;let[t,i]=await e.eval("[win_getid(),coc#util#editor_infos()]");this.winid=t,await Promise.allSettled(i.map(r=>this.createTextEditor(r.winid))),_.on("BufUnload",r=>{for(let[o,s]of this.editors.entries())r==s.bufnr&&this.editors.delete(o)},null,this.disposables),_.on("CursorHold",this.checkEditors,this,this.disposables),_.on("TabNew",r=>{this.tabIds.add(r)},null,this.disposables),_.on("TabClosed",this.checkTabs,this,this.disposables),_.on("WinEnter",r=>{this.winid=r;let o=this.editors.get(r);o&&this.onChangeCurrent(o)},null,this.disposables),_.on("WinClosed",r=>{this.editors.has(r)&&(this.editors.delete(r),this._onDidChangeVisibleTextEditors.fire(this.visibleTextEditors))},null,this.disposables),_.on("BufWinEnter",async(r,o)=>{this.winid=o,await this.createTextEditor(o)&&this._onDidChangeVisibleTextEditors.fire(this.visibleTextEditors)},null,this.disposables)}checkTabs(e){let t=!1;for(let i of this.editors.values())e.includes(i.tabpageid)||(t=!0,this.editors.delete(i.winid));for(let i of Array.from(this.tabIds))e.includes(i)||this._onDidTabClose.fire(i);this.tabIds=new Set(e),t&&this._onDidChangeVisibleTextEditors.fire(this.visibleTextEditors)}checkUnloadedBuffers(e){for(let t of this.documents.bufnrs)e.includes(t)||_.fire("BufUnload",[t])}async checkEditors(){let[e,t,i]=await this.nvim.eval("[win_getid(),coc#util#get_loaded_bufs(),coc#util#editor_infos()]");this.winid=e,this.checkUnloadedBuffers(t);let r=!1,o=new Set;for(let s of i){let a=this.editors.get(s.winid),l=!1;a?Qle(a,s)?(await _.fire("BufRename",[s.bufnr]),l=!0):(a.document.bufnr!=s.bufnr||a.tabpageid!=s.tabid)&&(l=!0):l=!0,l&&(await this.createTextEditor(s.winid),r=!0),o.add(s.winid)}this.cleanupEditors(o)&&(r=!0),r&&this._onDidChangeVisibleTextEditors.fire(this.visibleTextEditors)}cleanupEditors(e){let t=!1;for(let i of Array.from(this.editors.keys()))e.has(i)||(t=!0,this.editors.delete(i));return t}async createTextEditor(e){let{documents:t,nvim:i}=this,r=await i.call("coc#util#get_editoroption",[e]);if(!r)return!1;this.tabIds.add(r.tabpageid);let o=t.getDocument(r.bufnr);if(o&&o.attached){let s=this.fromOptions(r);return this.editors.set(e,s),e==this.winid&&this.onChangeCurrent(s),Kle.debug("editor created winid & bufnr & tabpageid: ",e,r.bufnr,r.tabpageid),!0}else this.editors.delete(r.winid);return!1}fromOptions(e){let{visibleRanges:t,bufnr:i}=e,r=this.documents.getDocument(i);return{id:`${e.tabpageid}-${e.winid}-${r.uri}`,tabpageid:e.tabpageid,winid:e.winid,winnr:e.winnr,uri:r.uri,bufnr:r.bufnr,document:r,visibleRanges:t.map(o=>M.create(o[0]-1,0,o[1],0)),options:{tabSize:e.tabSize,insertSpaces:!!e.insertSpaces}}}}});var zi,ha=D(()=>{"use strict";yc();fe();zi=class{constructor(){this.lines=[];this._highlights=[]}addLine(e,t){if(e.includes(` +`)){for(let i of e.split(/\r?\n/))this.addLine(i,t);return}if(t&&this._highlights.push({lnum:this.lines.length,colStart:e.match(/^\s*/)[0].length,colEnd:ue(e),hlGroup:t}),e.includes("\x1B")){let i=bc(e);for(let r of i.highlights){let{span:o,hlGroup:s}=r;this._highlights.push({lnum:this.lines.length,colStart:o[0],colEnd:o[1],hlGroup:s})}this.lines.push(i.line)}else this.lines.push(e)}addLines(e){this.lines.push(...e)}addTexts(e){let t=this.lines.length,i="";for(let r of e){let o=ue(i);r.hlGroup&&this._highlights.push({lnum:t,colStart:o,colEnd:o+ue(r.text),hlGroup:r.hlGroup}),i+=r.text}this.lines.push(i)}addText(e,t){if(!e)return;let{lines:i}=this,r=i[i.length-1]||"";if(e.includes(` +`)){let o=e.split(` +`);this.addText(o[0],t);for(let s of o.slice(1))this.addLine(s,t);return}if(t){let o=ue(r);this._highlights.push({lnum:i.length?i.length-1:0,colStart:o,colEnd:o+ue(e),hlGroup:t})}i.length?i[i.length-1]=`${r}${e}`:i.push(e)}get length(){return this.lines.length}getline(e){return this.lines[e]||""}get highlights(){return this._highlights}get content(){return this.lines.join(` +`)}render(e,t=0,i=-1){e.setLines(this.lines,{start:t,end:i,strictIndexing:!1},!0);for(let r of this._highlights)e.addHighlight({hlGroup:r.hlGroup,colStart:r.colStart,colEnd:r.colEnd,line:t+r.lnum,srcId:-1})}}});function eue(n,e){if(typeof n.lnum!="number")return;let t=n.lnum;if(e){let i=OP(e.edits);t=Jv(Q.create(t-1,0),i).line+1}return t}function tue(n,e){var i;let t=new Map;for(let r of n){let o=hU(r)??null,s=o?(i=e[o])==null?void 0:i.label:null,a=t.get(s);a?a.push(r):t.set(s,[r])}return t}var Vle,tp,RU=D(()=>{"use strict";ae();Je();Pe();te();Re();st();de();wr();ha();Vle=0,tp=class{constructor(e,t){this.nvim=e;this.keymaps=t;this.disposables=[];this.items=[];this.renameMap=new Map;_.on("BufUnload",i=>{i==this.bufnr&&this.dispose()},null,this.disposables)}addFile(e,t,i){this.items.push({index:t.length,filepath:e,lnum:i})}async show(e){let{nvim:t}=this,i=Vle++;t.pauseNotification(),t.command(`tabe +setl\\ buftype=nofile CocWorkspaceEdit${i}`,!0),t.command("setl bufhidden=wipe nolist",!0),t.command("setl nobuflisted wrap undolevels=-1 filetype=cocedits noswapfile",!0),await t.resumeNotification(!0);let r=await t.buffer,o=await t.call("getcwd");this.bufnr=r.id;let s=d=>{let h=O.parse(d).fsPath;return dt(o,h,!0)?R.relative(o,h):h},a=d=>R.isAbsolute(d)?d:R.join(o,d),l=new zi,u=le(e.edit.documentChanges),c=tue(u,e.edit.changeAnnotations??{});for(let[d,h]of c.entries()){d&&(l.addLine(d,"MoreMsg"),l.addLine(""));for(let g of h)if(Qt.is(g)){let f=e.changes[g.textDocument.uri],m=s(g.textDocument.uri);l.addTexts([{text:"Change",hlGroup:"Title"},{text:" "},{text:m,hlGroup:"Directory"},{text:`:${f.lnum}`,hlGroup:"LineNr"}]),this.addFile(m,l,f.lnum),l.addLine(""),this.addChangedLines(l,f,m,f.lnum),l.addLine("")}else if(Un.is(g)||In.is(g)){let f=In.is(g)?"Delete":"Create",m=s(g.uri);l.addTexts([{text:f,hlGroup:"Title"},{text:" "},{text:m,hlGroup:"Directory"}]),this.addFile(m,l),l.addLine("")}else if(Xn.is(g)){let f=s(g.oldUri),m=s(g.newUri);l.addTexts([{text:"Rename",hlGroup:"Title"},{text:" "},{text:f,hlGroup:"Directory"},{text:"->",hlGroup:"Comment"},{text:m,hlGroup:"Directory"}]),this.renameMap.set(f,m),this.addFile(m,l),l.addLine("")}}t.pauseNotification(),l.render(r),r.setOption("modifiable",!1,!0),await t.resumeNotification(!0),this.disposables.push(this.keymaps.registerLocalKeymap(r.id,"n","",async()=>{let d=await t.call("line","."),h=await t.call("col","."),g;for(let C=this.items.length-1;C>=0;C--){let k=this.items[C];if(d>=k.index){g=k;break}}if(!g)return;let f=O.file(a(g.filepath)).toString(),m=this.renameMap.has(g.filepath)?this.renameMap.get(g.filepath):g.filepath;await t.call("coc#util#open_file",["tab drop",a(m)]);let v=le(e.edit.documentChanges).find(C=>Qt.is(C)&&C.textDocument.uri==f),x=eue(g,v);x!==void 0&&await t.call("cursor",[x,h]),t.redrawVim()},!0)),this.disposables.push(this.keymaps.registerLocalKeymap(r.id,"n","",async()=>{t.command("bwipeout!",!0)},!0))}addChangedLines(e,t,i,r){let o=fi(t.oldLines.join(` +`),t.newLines.join(` +`));for(let s=0;s{"use strict";ae();Je();Pe();xe();RU();Ii();st();de();U();fe();wr();iue=Z("core-files"),ip=class{constructor(e,t,i,r){this.documents=e;this.configurations=t;this.workspaceFolderControl=i;this.keymaps=r;this.operationTimeout=500;this._onDidCreateFiles=new p.Emitter;this._onDidRenameFiles=new p.Emitter;this._onDidDeleteFiles=new p.Emitter;this._onWillCreateFiles=new p.Emitter;this._onWillRenameFiles=new p.Emitter;this._onWillDeleteFiles=new p.Emitter;this.onDidCreateFiles=this._onDidCreateFiles.event;this.onDidRenameFiles=this._onDidRenameFiles.event;this.onDidDeleteFiles=this._onDidDeleteFiles.event;this.onWillCreateFiles=this._onWillCreateFiles.event;this.onWillRenameFiles=this._onWillRenameFiles.event;this.onWillDeleteFiles=this._onWillDeleteFiles.event}attach(e,t,i){this.nvim=e,this.env=t,this.window=i}async openTextDocument(e){e=typeof e=="string"?O.file(e):e;let t=this.documents.getDocument(e.toString());if(t)return await this.jumpTo(e,null,"drop"),t;let i=e.scheme;if(i=="file"){if(!F.existsSync(e.fsPath))throw wy(e.fsPath);F.accessSync(e.fsPath,F.constants.R_OK)}return i=="untitled"?(await this.nvim.call("coc#util#open_file",["tab drop",e.path]),await this.documents.document):await this.loadResource(e.toString())}async jumpTo(e,t,i){i||(i=this.configurations.initialConfiguration.get("coc.preferences.jumpCommand","edit"));let{nvim:r}=this,o=e instanceof O?e:O.parse(e),s=this.documents.getDocument(o.with({fragment:""}).toString()),a=s?s.bufnr:-1;if(!t&&o.scheme==="file"&&o.fragment){let l=o.fragment.split(","),u=parseInt(l[0],10);if(!isNaN(u)){let c=l.length>0&&/^\d+$/.test(l[1])?parseInt(l[1],10):void 0;t=Q.create(u-1,c==null?0:c-1)}}if(a!=-1&&i=="edit"){if(r.pauseNotification(),r.command("silent! normal! m'",!0),r.command(`buffer ${a}`,!0),r.command("if &filetype ==# '' | filetype detect | endif",!0),t){let l=s.getline(t.line),u=nt(l,t.character)+1;r.call("cursor",[t.line+1,u],!0)}await r.resumeNotification(!0)}else{let{fsPath:l,scheme:u}=o,c=t==null?null:[t.line,t.character];if(u=="file"){let d=Mi(l);await this.nvim.call("coc#util#jump",[i,d,c])}else await this.nvim.call("coc#util#jump",[i,e.toString(),c])}}async openResource(e){let{nvim:t}=this,i=O.parse(e);if(/^https?/.test(i.scheme)){await t.call("coc#ui#open_url",e);return}await this.jumpTo(e),await this.documents.document}async loadResource(e,t){let i=this.documents.getDocument(e);if(i)return i;t||(t=this.configurations.getConfiguration("workspace").get("openResourceCommand","tab drop"));let r=O.parse(e),o=r.scheme==="file"?r.fsPath:e,s;if(t){let a=await this.nvim.call("win_getid");s=await this.nvim.call("coc#util#open_file",[t,o]),await this.nvim.call("win_gotoid",[a])}else s=(await this.nvim.call("coc#ui#open_files",[[o]]))[0];return await this.documents.createDocument(s)}async loadResources(e){let{documents:t}=this,i=e.map(o=>{let s=O.parse(o);return s.scheme=="file"?s.fsPath:o}),r=await this.nvim.call("coc#ui#open_files",[i]);return await Promise.all(r.map(o=>t.createDocument(o)))}async createFile(e,t={},i){let{nvim:r}=this,o=F.existsSync(e);if(o&&!t.overwrite&&!t.ignoreIfExists)throw sT(e);if(!o||t.overwrite){let s=new p.CancellationTokenSource;await this.fireWaitUntilEvent(this._onWillCreateFiles,{files:[O.file(e)],token:s.token},i),s.cancel();let a=R.dirname(e);if(!F.existsSync(a)){let c,d=a;for(;![".","/",R.parse(a).root].includes(d);){if(F.existsSync(R.dirname(d))){c=d;break}d=R.dirname(d)}F.mkdirSync(a,{recursive:!0}),i&&i.push(()=>{F.rmSync(c,{force:!0,recursive:!0})})}F.writeFileSync(e,"","utf8"),i&&i.push(async()=>{F.rmSync(e,{force:!0,recursive:!0})});let u=(await this.loadResource(e)).bufnr;i&&i.push(()=>(_.fire("BufUnload",[u]),r.command(`silent! bd! ${u}`))),this._onDidCreateFiles.fire({files:[O.file(e)]})}}async deleteFile(e,t={},i){let{ignoreIfNotExists:r,recursive:o}=t,s=await Fn(e),a=s&&s.isDirectory();if(!s&&!r)throw wy(e);if(s==null)return;let l=O.file(e);if(await this.fireWaitUntilEvent(this._onWillDeleteFiles,{files:[l]},i),!a){let d=await this.nvim.call("bufnr",[e]);d&&(_.fire("BufUnload",[d]),await this.nvim.command(`silent! bwipeout ${d}`),i&&i.push(()=>this.loadResource(l.toString())))}let u=R.join(Pt.tmpdir(),"coc-"+process.pid);F.mkdirSync(u,{recursive:!0});let c=Ab.createHash("md5").update(e).digest("hex");if(a&&o){let d=R.join(u,c),h=R.dirname(e);F.renameSync(e,d),i&&i.push(async()=>{F.mkdirSync(h,{recursive:!0}),F.renameSync(d,e)})}else if(a)F.rmdirSync(e),i&&i.push(()=>{F.mkdirSync(e)});else{let d=R.join(u,c),h=R.dirname(e);F.renameSync(e,d),i&&i.push(()=>{F.mkdirSync(h,{recursive:!0}),F.renameSync(d,e)})}this._onDidDeleteFiles.fire({files:[l]})}async renameFile(e,t,i={},r){let{nvim:o}=this,{overwrite:s,ignoreIfExists:a}=i;if(t===e)return;let l=F.existsSync(t);if(l&&a&&!s)return;if(l&&!s)throw sT(t);let u=await Fn(e),c=u&&u.isDirectory()?0:await o.call("bufloaded",[e]);if(!c&&!u)throw wy(e);let d={newUri:O.parse(t),oldUri:O.parse(e)};if(i.skipEvent||await this.fireWaitUntilEvent(this._onWillRenameFiles,{files:[d]},r),c){let h=await o.call("coc#ui#rename_file",[e,t,u!=null]);await this.documents.onBufCreate(h)}else{if(u!=null&&u.isDirectory())for(let h of this.documents.attached("file")){let g=O.parse(h.uri);if(dt(e,g.fsPath,!1)){let f=g.fsPath.replace(e,t),m=await o.call("coc#ui#rename_file",[g.fsPath,f,!1]);await this.documents.onBufCreate(m)}}F.renameSync(e,t)}r&&r.push(()=>this.renameFile(t,e,{skipEvent:!0})),i.skipEvent||this._onDidRenameFiles.fire({files:[d]})}async promptAnotations(e,t){let i=t?cU(e,t):[],r=[];for(let o of i){let s=t[o];await this.window.showMenuPicker(["Yes","No"],{position:"center",title:"Confirm edits",content:s.label+(s.description?" "+s.description:"")})!==0&&r.push(o)}return r}async applyEdit(e,t){let i=gU(e),r=[],o=!1;try{let s=await this.promptAnotations(i,e.changeAnnotations);s.length>0&&(i=dU(i,s));let a={},l=await this.documents.document,u=l?l.uri:void 0;o=i.every(c=>Qt.is(c)&&c.textDocument.uri===u),this.validateChanges(i);for(let c of i)if(Qt.is(c)){let{textDocument:d,edits:h}=c,{uri:g}=d,f=await this.loadResource(g),m=await f.applyEdits(h,!1,g===u);if(m){let b=f.version,{newText:v,range:x}=m;a[g]={uri:g,lnum:x.start.line+1,newLines:f.getLines(x.start.line,x.end.line),oldLines:v.endsWith(` +`)?v.slice(0,-1).split(` +`):v.split(` +`)},r.push(async()=>{let C=this.documents.getDocument(g);!C||!C.attached||C.version!==b||(await C.applyEdits([m]),d.version=C.version)})}}else Un.is(c)?await this.createFile(Gv(c.uri),c.options,r):In.is(c)?await this.deleteFile(Gv(c.uri),c.options,r):Xn.is(c)&&await this.renameFile(Gv(c.oldUri),Gv(c.newUri),c.options,r);if(r.length===0)return!0;t||(this.editState={edit:{documentChanges:i,changeAnnotations:e.changeAnnotations},changes:a,recovers:r,applied:!0}),this.nvim.redrawVim()}catch(s){return iue.error("Error on applyEdits:",e,s),t||this.window.showErrorMessage(`Error on applyEdits: ${s}`),await this.undoChanges(r),!1}return t||o||this.window.showInformationMessage("Use ':wa' to save changes or ':CocCommand workspace.inspectEdit' to inspect."),!0}async undoChanges(e){for(;e.length>0;){let t=e.pop();await Promise.resolve(t())}}async inspectEdit(){if(!this.editState){this.window.showWarningMessage("No workspace edit to inspect");return}await new tp(this.nvim,this.keymaps).show(this.editState)}async undoWorkspaceEdit(){let{editState:e}=this;if(!e||!e.applied){this.window.showWarningMessage("No workspace edit to undo");return}e.applied=!1,await this.undoChanges(e.recovers)}async redoWorkspaceEdit(){let{editState:e}=this;if(!e||e.applied){this.window.showWarningMessage("No workspace edit to redo");return}this.editState=void 0,await this.applyEdit(e.edit)}validateChanges(e){let{documents:t}=this;for(let i of e)if(Qt.is(i)){let{uri:r,version:o}=i.textDocument,s=t.getDocument(r);if(typeof o=="number"&&o>0){if(!s)throw FW(r);if(s.version!=o)throw new Error(`${r} changed before apply edit`)}else if(!s&&!Dg(r))throw xy(O.parse(r).scheme)}else if(Un.is(i)||In.is(i)){if(!Dg(i.uri))throw xy(i.uri)}else if(Xn.is(i)&&(!Dg(i.oldUri)||!Dg(i.newUri)))throw xy(i.oldUri)}async findFiles(e,t,i,r){let o=this.workspaceFolderControl.workspaceFolders;if((r==null?void 0:r.isCancellationRequested)||!o.length||i===0)return[];i=i??1/0;let s=o.map(u=>O.parse(u.uri).fsPath);if(typeof e!="string"){let u=e.baseUri.fsPath;s=s.filter(c=>dt(u,c,!0))}let a=typeof e=="string"?e:e.pattern,l=[];for(let u of s){if(l.length>=i)break;let c=await(0,ot.promisify)(Nb)(a,{dot:!0,cwd:u,nodir:!0,absolute:!1});if(r!=null&&r.isCancellationRequested)return[];for(let d of c)if(!(t&&nue(u,d,t))&&(l.push(O.file(R.join(u,d))),l.length===i))break}return l}async fireWaitUntilEvent(e,t,i){let r=!0,o=[];e.fire({...t,waitUntil:s=>{if(!r)throw jW("waitUntil");let a=new Promise(u=>{setTimeout(u,this.operationTimeout)}),l=Promise.race([s,a]).then(u=>{if(u&&Ys.is(u))return this.applyEdit(u,!0)});o.push(l)}}),r=!1,await Promise.all(o)}}});function np(){return EU.default.randomBytes(16)}var EU,YP=D(()=>{EU=Lr(require("crypto"))});function rue(n,e){var t=e||0,i=IU;return[i[n[t++]],i[n[t++]],i[n[t++]],i[n[t++]],"-",i[n[t++]],i[n[t++]],"-",i[n[t++]],i[n[t++]],"-",i[n[t++]],i[n[t++]],"-",i[n[t++]],i[n[t++]],i[n[t++]],i[n[t++]],i[n[t++]],i[n[t++]]].join("")}var IU,rp,zv,ZP=D(()=>{IU=[];for(rp=0;rp<256;++rp)IU[rp]=(rp+256).toString(16).substr(1);zv=rue});function oue(n,e,t){var i=e&&t||0,r=e||[];n=n||{};var o=n.node||LU,s=n.clockseq!==void 0?n.clockseq:JP;if(o==null||s==null){var a=n.random||(n.rng||np)();o==null&&(o=LU=[a[0]|1,a[1],a[2],a[3],a[4],a[5]]),s==null&&(s=JP=(a[6]<<8|a[7])&16383)}var l=n.msecs!==void 0?n.msecs:new Date().getTime(),u=n.nsecs!==void 0?n.nsecs:UP+1,c=l-$P+(u-UP)/1e4;if(c<0&&n.clockseq===void 0&&(s=s+1&16383),(c<0||l>$P)&&n.nsecs===void 0&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");$P=l,UP=u,JP=s,l+=122192928e5;var d=((l&268435455)*1e4+u)%4294967296;r[i++]=d>>>24&255,r[i++]=d>>>16&255,r[i++]=d>>>8&255,r[i++]=d&255;var h=l/4294967296*1e4&268435455;r[i++]=h>>>8&255,r[i++]=h&255,r[i++]=h>>>24&15|16,r[i++]=h>>>16&255,r[i++]=s>>>8|128,r[i++]=s&255;for(var g=0;g<6;++g)r[i+g]=o[g];return e||zv(r)}var LU,JP,$P,UP,Fl,FU=D(()=>{YP();ZP();$P=0,UP=0;Fl=oue});function sue(n,e,t){var i=e&&t||0;typeof n=="string"&&(e=n==="binary"?new Array(16):null,n=null),n=n||{};var r=n.random||(n.rng||np)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e)for(var o=0;o<16;++o)e[i+o]=r[o];return e||zv(r)}var me,MU=D(()=>{YP();ZP();me=sue});var rt=D(()=>{FU();MU()});var AU=w((ELe,OU)=>{var XP=4294967296,jU=[];for(Ec=0;Ec<256;Ec++)jU[Ec]=(Ec>15?"":"0")+Ec.toString(16);var Ec,op=OU.exports=function(n,e){n instanceof Buffer?(this.buffer=n,this.offset=e||0):Object.prototype.toString.call(n)=="[object Uint8Array]"?(this.buffer=new Buffer(n),this.offset=e||0):(this.buffer=this.buffer||new Buffer(8),this.offset=0,this.setValue.apply(this,arguments))};op.MAX_INT=Math.pow(2,53);op.MIN_INT=-Math.pow(2,53);op.prototype={constructor:op,_2scomp:function(){for(var n=this.buffer,e=this.offset,t=1,i=e+7;i>=e;i--){var r=(n[i]^255)+t;n[i]=r&255,t=r>>8}},setValue:function(n,e){var t=!1;if(arguments.length==1)if(typeof n=="number"){if(t=n<0,n=Math.abs(n),e=n%XP,n=n/XP,n>XP)throw new RangeError(n+" is outside Int64 range");n=n|0}else if(typeof n=="string")n=(n+"").replace(/^0x/,""),e=n.substr(-8),n=n.length>8?n.substr(0,n.length-8):"",n=parseInt(n,16),e=parseInt(e,16);else throw new Error(n+" must be a Number or String");for(var i=this.buffer,r=this.offset,o=7;o>=0;o--)i[r+o]=e&255,e=o==4?n:e>>>8;t&&this._2scomp()},toNumber:function(n){for(var e=this.buffer,t=this.offset,i=e[t]&128,r=0,o=1,s=7,a=1;s>=0;s--,a*=256){var l=e[t+s];i&&(l=(l^255)+o,o=l>>8,l=l&255),r+=l*a}return!n&&r>=op.MAX_INT?i?-1/0:1/0:i?-r:r},valueOf:function(){return this.toNumber(!1)},toString:function(n){return this.valueOf().toString(n||10)},toOctetString:function(n){for(var e=new Array(8),t=this.buffer,i=this.offset,r=0;r<8;r++)e[r]=jU[t[i+r]];return e.join(n||"")},toBuffer:function(n){if(n&&this.offset===0)return this.buffer;var e=new Buffer(8);return this.buffer.copy(e,0,this.offset,this.offset+8),e},copy:function(n,e){this.buffer.copy(n,e||0,this.offset,this.offset+8)},compare:function(n){if((this.buffer[this.offset]&128)!=(n.buffer[n.offset]&128))return n.buffer[n.offset]-this.buffer[this.offset];for(var e=0;e<8;e++)if(this.buffer[this.offset+e]!==n.buffer[n.offset+e])return this.buffer[this.offset+e]-n.buffer[n.offset+e];return 0},equals:function(n){return this.compare(n)===0},inspect:function(){return"[Int64 value:"+this+" octets:"+this.toOctetString(" ")+"]"}}});var XU=w(ap=>{var HU=require("events").EventEmitter,aue=require("util"),lue=require("os"),ILe=require("assert"),sp=AU(),ga=lue.endianness()=="BE";function BU(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function Oi(n){this.buf=Buffer.alloc(BU(n||8192)),this.readOffset=0,this.writeOffset=0}ap.Accumulator=Oi;Oi.prototype.writeAvail=function(){return this.buf.length-this.writeOffset};Oi.prototype.readAvail=function(){return this.writeOffset-this.readOffset};Oi.prototype.reserve=function(n){if(!(n0&&(this.buf.copy(this.buf,0,this.readOffset,this.writeOffset),this.writeOffset-=this.readOffset,this.readOffset=0),!(n0)this.assertReadableSize(n);else if(n<0&&this.readOffset+n<0)throw new Error("advance with negative offset "+n+" would seek off the start of the buffer");this.readOffset+=n};Oi.prototype.writeByte=function(n){this.reserve(1),this.buf.writeInt8(n,this.writeOffset),++this.writeOffset};Oi.prototype.writeInt=function(n,e){switch(this.reserve(e),e){case 1:this.buf.writeInt8(n,this.writeOffset);break;case 2:ga?this.buf.writeInt16BE(n,this.writeOffset):this.buf.writeInt16LE(n,this.writeOffset);break;case 4:ga?this.buf.writeInt32BE(n,this.writeOffset):this.buf.writeInt32LE(n,this.writeOffset);break;default:throw new Error("unsupported integer size "+e)}this.writeOffset+=e};Oi.prototype.writeDouble=function(n){this.reserve(8),ga?this.buf.writeDoubleBE(n,this.writeOffset):this.buf.writeDoubleLE(n,this.writeOffset),this.writeOffset+=8};var zP=0,KP=1,QP=2,VP=3,eR=4,ew=5,Vv=6,qU=7,WU=8,YU=9,ZU=10,JU=11,uue=12,GP=0,NU=1,cue=127,due=32767,hue=2147483647;function Mn(){HU.call(this),this.buf=new Oi,this.state=GP}aue.inherits(Mn,HU);ap.BunserBuf=Mn;Mn.prototype.append=function(n,e){if(e)return this.buf.append(n),this.process(e);try{this.buf.append(n)}catch(t){this.emit("error",t);return}this.processLater()};Mn.prototype.processLater=function(){var n=this;process.nextTick(function(){try{n.process(!1)}catch(e){n.emit("error",e)}})};Mn.prototype.process=function(n){if(this.state==GP){if(this.buf.readAvail()<2)return;if(this.expectCode(0),this.expectCode(1),this.pduLen=this.decodeInt(!0),this.pduLen===!1){this.buf.readAdvance(-2);return}this.buf.reserve(this.pduLen),this.state=NU}if(this.state==NU){if(this.buf.readAvail()0&&this.processLater()};Mn.prototype.raise=function(n){throw new Error(n+", in Buffer of length "+this.buf.buf.length+" ("+this.buf.readAvail()+" readable) at offset "+this.buf.readOffset+" buffer: "+JSON.stringify(this.buf.buf.slice(this.buf.readOffset,this.buf.readOffset+32).toJSON()))};Mn.prototype.expectCode=function(n){var e=this.buf.readInt(1);e!=n&&this.raise("expected bser opcode "+n+" but got "+e)};Mn.prototype.decodeAny=function(){var n=this.buf.peekInt(1);switch(n){case VP:case eR:case ew:case Vv:return this.decodeInt();case qU:return this.buf.readAdvance(1),this.buf.readDouble();case WU:return this.buf.readAdvance(1),!0;case YU:return this.buf.readAdvance(1),!1;case ZU:return this.buf.readAdvance(1),null;case QP:return this.decodeString();case zP:return this.decodeArray();case KP:return this.decodeObject();case JU:return this.decodeTemplate();default:this.raise("unhandled bser opcode "+n)}};Mn.prototype.decodeArray=function(){this.expectCode(zP);for(var n=this.decodeInt(),e=[],t=0;t"u")throw Error("no bser found in string and no error raised!?");return t}ap.loadFromBuffer=gue;function $U(n){for(var e=Buffer.alloc(n.length),t=0;t"u"&&r--}Kv(n,r);for(var t=0;t"u")){Qv(n,o);try{Qv(n,s)}catch(c){throw new Error(c.message+" (while serializing object property with name `"+o+"')")}}}return;default:throw new Error("cannot serialize type "+typeof e+" to BSER")}}function pue(n){var e=new Oi;e.writeByte(0),e.writeByte(1),e.writeByte(ew),e.writeInt(0,4),Qv(e,n);var t=e.writeOffset,i=t-7;return e.writeOffset=3,e.writeInt(i,4),e.writeOffset=t,e.buf.slice(0,t)}ap.dumpToBuffer=pue});var tX=w((FLe,eX)=>{"use strict";var fue=require("net"),QU=require("events").EventEmitter,mue=require("util"),bue=require("child_process"),VU=XU(),GU=["subscription","log"];function us(n){var e=this;QU.call(this),this.watchmanBinaryPath="watchman",n&&n.watchmanBinaryPath&&(this.watchmanBinaryPath=n.watchmanBinaryPath.trim()),this.commands=[]}mue.inherits(us,QU);eX.exports.Client=us;us.prototype.sendNextCommand=function(){this.currentCommand||(this.currentCommand=this.commands.shift(),this.currentCommand&&this.socket.write(VU.dumpToBuffer(this.currentCommand.cmd)))};us.prototype.cancelCommands=function(n){var e=new Error(n),t=this.commands;this.commands=[],this.currentCommand&&(t.unshift(this.currentCommand),this.currentCommand=null),t.forEach(function(i){i.cb(e)})};us.prototype.connect=function(){var n=this;function e(l){n.bunser=new VU.BunserBuf,n.bunser.on("value",function(u){for(var c=!1,d=0;d=0:!1}us.prototype._synthesizeCapabilityCheck=function(n,e,t){n.capabilities={};var i=n.version;return e.forEach(function(r){n.capabilities[r]=KU(i,r)}),t.forEach(function(r){var o=KU(i,r);n.capabilities[r]=o,o||(n.error="client required capability `"+r+"` is not supported by this server")}),n};us.prototype.capabilityCheck=function(n,e){var t=n.optional||[],i=n.required||[],r=this;this.command(["version",{optional:t,required:i}],function(o,s){if(o){e(o);return}if(!("capabilities"in s)&&(s=r._synthesizeCapabilityCheck(s,t,i),s.error)){o=new Error(s.error),o.watchmanResponse=s,e(o);return}e(null,s)})};us.prototype.end=function(){this.cancelCommands("The client was ended"),this.socket&&(this.socket.end(),this.socket=null),this.bunser=null}});function wue(n){return!(n=="/"||n=="/tmp"||n=="/private/tmp"||dt(n,Pt.homedir(),!0)||R.parse(n).base==n||n.startsWith("/tmp/")||n.startsWith("/private/tmp/")||dt(Pt.tmpdir(),n,!0))}var tR,vue,cs,iR=D(()=>{"use strict";rt();xe();st();de();tR=Z("core-watchman"),vue=["relative_root","cmd-watch-project","wildmatch","field-new"],cs=class{constructor(e,t){this.channel=t;this._disposed=!1;let i=tX();this.client=new i.Client({watchmanBinaryPath:e}),this.client.setMaxListeners(300)}checkCapability(){let{client:e}=this;return new Promise((t,i)=>{e.capabilityCheck({optional:[],required:vue},(r,o)=>{if(r)return t(!1);let{capabilities:s}=o;for(let a of Object.keys(s))if(!s[a])return t(!1);t(!0)})})}async watchProject(e){let t=await this.command(["watch-project",e]),{watch:i,warning:r,relative_path:o}=t;return i?(r&&tR.warn(r),this.watch=i,this.relative_path=o,tR.info(`watchman watching project: ${e}`),this.appendOutput(`watchman watching project: ${e}`),!0):!1}command(e){return new Promise((t,i)=>{this.client.command(e,(r,o)=>{if(r)return i(r);t(o)})})}async subscribe(e,t){let{watch:i,relative_path:r}=this;if(!i)throw new Error("watchman not watching");let{clock:o}=await this.command(["clock",i]),s=Fl(),a={expression:["allof",["match","**/*","wholename"]],fields:["name","size","new","exists","type","mtime_ms","ctime_ms"],since:o},l=i;if(r&&(a.relative_root=r,l=R.join(i,r)),!this.client)return;let{subscribe:u}=await this.command(["subscribe",i,s,a]);return this.appendOutput(`subscribing "${e}" in ${l}`),this.client.on("subscription",c=>{if(!c||c.subscription!=s)return;let{files:d}=c;if(!d||(d=d.filter(g=>g.type=="f"&&ni(g.name,e,{dot:!0})),!d.length))return;let h=Object.assign({},c);this.relative_path&&(h.root=R.resolve(c.root,this.relative_path)),this.appendOutput(`file change detected: ${JSON.stringify(h,null,2)}`),t(h)}),{dispose:()=>{this.unsubscribe(u)},subscribe:u}}unsubscribe(e){if(this._disposed)return Promise.resolve();let{watch:t}=this;if(!!t)return this.appendOutput(`unsubscribe "${e}" in: ${t}`),this.command(["unsubscribe",t,e]).catch(i=>{var r;(r=i.message)!=null&&r.includes("The client was ended")&&tR.error(i)})}dispose(){this._disposed||(this._disposed=!0,this.client&&(this.client.end(),this.client=void 0))}appendOutput(e,t="Info"){this.channel&&this.channel.appendLine(`[${t} - ${new Date().toLocaleTimeString()}] ${e}`)}static async createClient(e,t,i){if(!wue(t))throw new Error(`Watch for ${t} is ignored`);let r;try{if(r=new cs(e,i),!await r.checkCapability())throw new Error("required capabilities do not exist.");if(!await r.watchProject(t))throw new Error("unable to watch");return r}catch(o){throw r&&r.dispose(),o}}}});var xue,lp,Ic,nR,iX=D(()=>{"use strict";Je();xe();te();Re();st();de();U();iR();xue=Z("fileSystemWatcher"),lp=class{constructor(e,t){this.workspaceFolder=e;this.watchmanPath=t;this.clientsMap=new Map;this.disposables=[];this.creating=new Set;this._onDidCreateClient=new p.Emitter;this.disabled=!1;this.onDidCreateClient=this._onDidCreateClient.event}attach(e){this.channel=e;let t=i=>{let r=O.parse(i.uri).fsPath;this.createClient(r)};this.workspaceFolder.workspaceFolders.forEach(i=>{t(i)}),this.workspaceFolder.onDidChangeWorkspaceFolders(i=>{i.added.forEach(r=>{t(r)}),i.removed.forEach(r=>{let o=O.parse(r.uri).fsPath,s=this.clientsMap.get(o);s&&(this.clientsMap.delete(o),s.dispose())})},null,this.disposables)}waitClient(e){return this.clientsMap.has(e)?Promise.resolve():new Promise(t=>{let i=this.onDidCreateClient(r=>{r==e&&(i.dispose(),t())})})}async createClient(e){if(!(this.watchmanPath==null||this.has(e)||this.disabled))try{let t=await this.getWatchmanPath();this.creating.add(e);let i=await cs.createClient(t,e,this.channel);this.creating.delete(e),this.clientsMap.set(e,i);for(let r of lp.watchers)r.listen(e,i);this._onDidCreateClient.fire(e)}catch(t){this.creating.delete(e),this.channel&&this.channel.appendLine(`Error on create watchman client: ${t}`)}}async getWatchmanPath(){let e=this.watchmanPath;return process.env.WATCHMAN_SOCK||(e=await go(this.watchmanPath,{all:!1})),e}has(e){let t=Array.from(this.clientsMap.keys());return t.push(...this.creating),t.some(i=>ai(i,e))}createFileSystemWatcher(e,t,i,r){let o=new nR(e,t,i,r),s=typeof e=="string"?void 0:e.baseUri.fsPath;for(let[a,l]of this.clientsMap.entries())s&&dt(a,s,!0)&&(s=void 0),o.listen(a,l);return s&&this.createClient(s),lp.watchers.add(o),o}dispose(){this._onDidCreateClient.dispose();for(let e of this.clientsMap.values())e&&e.dispose();this.clientsMap.clear(),lp.watchers.clear(),W(this.disposables)}},Ic=lp;Ic.watchers=new Set;nR=class{constructor(e,t,i,r){this.globPattern=e;this.ignoreCreateEvents=t;this.ignoreChangeEvents=i;this.ignoreDeleteEvents=r;this._onDidCreate=new p.Emitter;this._onDidChange=new p.Emitter;this._onDidDelete=new p.Emitter;this._onDidRename=new p.Emitter;this.disposables=[];this._disposed=!1;this.onDidCreate=this._onDidCreate.event;this.onDidChange=this._onDidChange.event;this.onDidDelete=this._onDidDelete.event;this.onDidRename=this._onDidRename.event;this._onDidListen=new p.Emitter;this.onDidListen=this._onDidListen.event}listen(e,t){let{globPattern:i,ignoreCreateEvents:r,ignoreChangeEvents:o,ignoreDeleteEvents:s}=this,a,l;if(typeof i=="string")a=i;else if(a=i.pattern,l=i.baseUri.fsPath,!dt(e,l,!0))return;let u=c=>{let{root:d,files:h}=c;l&&!ai(d,l)?h=h.filter(g=>{if(g.type!="f")return!1;let f=R.join(d,g.name);return dt(l,f)?ni(R.relative(l,f),a,{dot:!0}):!1}):h=h.filter(g=>g.type=="f"&&ni(g.name,a,{dot:!0}));for(let g of h){let f=O.file(R.join(d,g.name));g.exists?g.new===!0?r||this._onDidCreate.fire(f):o||this._onDidChange.fire(f):s||this._onDidDelete.fire(f)}if(h.length==2&&h[0].exists!==h[1].exists){let g=h.find(m=>m.exists!==!0),f=h.find(m=>m.exists===!0);g.size==f.size&&this._onDidRename.fire({oldUri:O.file(R.join(d,g.name)),newUri:O.file(R.join(d,f.name))})}if(h.length>2&&h.length%2==0){let[g,f]=$y(h,m=>m.exists===!1);if(g.length==f.length)for(let m of g){let b=f.find(v=>v.size==m.size&&v.mtime_ms==m.mtime_ms);b&&this._onDidRename.fire({oldUri:O.file(R.join(d,m.name)),newUri:O.file(R.join(d,b.name))})}}};t.subscribe(a,u).then(c=>{if(!!c){if(this._onDidListen.fire(),this.subscribe=c.subscribe,this._disposed)return c.dispose();this.disposables.push(c)}},c=>{c instanceof Error&&c.message.includes("client was ended")||xue.error(`Error on subscribe ${a}`,c)})}dispose(){this._disposed=!0,Ic.watchers.delete(this),this._onDidRename.dispose(),this._onDidCreate.dispose(),this._onDidChange.dispose(),W(this.disposables)}}});function nX(n){return n=="n"||n=="o"||n=="x"||n=="v"?"":n=="i"?"":n=="s"?"":""}function Sue(n){return typeof n=="number"?n:_.bufnr}var Cue,up,rX=D(()=>{"use strict";Pe();xe();U();fe();Cue=Z("core-keymaps");up=class{constructor(){this.keymaps=new Map}attach(e){this.nvim=e}async doKeymap(e,t){let i=this.keymaps.get(e)??this.keymaps.get("coc-"+e);if(!i)return Cue.error(`keymap for ${e} not found`),t;let[r,o]=i,s=await Promise.resolve(r());return o&&await this.nvim.command(`silent! call repeat#set("\\(coc-${e})", -1)`),s??t}registerKeymap(e,t,i,r={}){if(!t)throw new Error(`Invalid key ${t} of registerKeymap`);let o=`coc-${t}`;if(this.keymaps.has(o))throw new Error(`${t} already exists.`);let s=`(${o})`;r=Object.assign({sync:!0,cancel:!0,silent:!0,repeat:!1},r);let{nvim:a}=this;this.keymaps.set(o,[i,!!r.repeat]);let l=r.sync?"request":"notify",u=r.cancel?1:0;for(let c of e)c=="i"?a.setKeymap(c,s,`coc#_insert_key('${l}', '${o}', ${u})`,{expr:!0,noremap:!0,silent:r.silent}):a.setKeymap(c,s,`:${nX(c)}call coc#rpc#${l}('doKeymap', ['${o}'])`,{noremap:!0,silent:r.silent});return p.Disposable.create(()=>{this.keymaps.delete(o);for(let c of e)a.deleteKeymap(c,s)})}registerExprKeymap(e,t,i,r=!1){let o=Sue(r),s=`${e}-${Ek(t)}${r?`-${o}`:""}`,{nvim:a}=this,l=e=="i"?`coc#_insert_key('request', '${s}')`:`coc#rpc#request('doKeymap', ['${s}'])`,u={noremap:!0,silent:!0,expr:!0,nowait:!0};return r?a.createBuffer(o).setKeymap(e,t,l,u):a.setKeymap(e,t,l,u),this.keymaps.set(s,[i,!1]),p.Disposable.create(()=>{this.keymaps.delete(s),r?a.createBuffer(o).deleteKeymap(e,t):a.deleteKeymap(e,t)})}registerLocalKeymap(e,t,i,r,o){let{nvim:s}=this,a=s.createBuffer(e),l=`local-${e}-${t}-${Ek(i)}`;this.keymaps.set(l,[r,!1]);let u=o?"notify":"request",c=nX(t);return a.setKeymap(t,i,`:${c}call coc#rpc#${u}('doKeymap', ['${l}'])`,{silent:!0,nowait:!0,noremap:!0}),p.Disposable.create(()=>{this.keymaps.delete(l),a.deleteKeymap(t,i)})}}});var oX,cp,sX=D(()=>{"use strict";Pe();xe();te();U();fe();oX=Z("watchers"),cp=class{constructor(){this.optionCallbacks=new Map;this.globalCallbacks=new Map;this.disposables=[];this._onDidRuntimePathChange=new p.Emitter;this.onDidRuntimePathChange=this._onDidRuntimePathChange.event;_.on("OptionSet",async(e,t,i)=>{let r=Array.from(this.optionCallbacks.get(e)??[]);await Promise.allSettled(r.map(o=>(async()=>{try{await Promise.resolve(o(t,i))}catch(s){this.nvim.errWriteLine(`Error on OptionSet '${e}': ${yr(s)}`),oX.error("Error on OptionSet callback:",s)}})()))},null,this.disposables),_.on("GlobalChange",async(e,t,i)=>{let r=Array.from(this.globalCallbacks.get(e)??[]);await Promise.allSettled(r.map(o=>(async()=>{try{await Promise.resolve(o(t,i))}catch(s){this.nvim.errWriteLine(`Error on GlobalChange '${e}': ${yr(s)}`),oX.error("Error on GlobalChange callback:",s)}})()))},null,this.disposables)}get options(){return Array.from(this.optionCallbacks.keys())}attach(e,t){this.nvim=e,this.env=t,this.watchOption("runtimepath",(i,r)=>{let o=i.split(","),a=r.split(",").filter(l=>!o.includes(l));a.length>0&&this._onDidRuntimePathChange.fire(a),this.env.runtimepath=r},this.disposables)}watchOption(e,t,i){let r=this.optionCallbacks.get(e);r||(r=new Set,this.optionCallbacks.set(e,r)),r.add(t);let o=`autocmd! coc_dynamic_option OptionSet ${e} call coc#rpc#notify('OptionSet',[expand(''), v:option_old, v:option_new])`;this.nvim.command(o,!0);let s=p.Disposable.create(()=>{let a=this.optionCallbacks.get(e);a.delete(t),a.size===0&&this.nvim.command(`autocmd! coc_dynamic_option OptionSet ${e}`,!0)});return i&&i.push(s),s}watchGlobal(e,t,i){let{nvim:r}=this,o=this.globalCallbacks.get(e);o||(o=new Set,this.globalCallbacks.set(e,o)),o.add(t),r.call("coc#_watch",e,!0);let s=p.Disposable.create(()=>{let a=this.globalCallbacks.get(e);a.delete(t),a.size===0&&r.call("coc#_unwatch",e,!0)});return i&&i.push(s),s}dispose(){W(this.disposables),this._onDidRuntimePathChange.dispose()}}});function dp(n){if(!(!n||!R.isAbsolute(n)))return{name:R.basename(n),uri:O.file(n).toString()}}var tw,Due,Tue,kue,Pue,hp,iw=D(()=>{"use strict";Je();Pe();xe();te();Re();Ii();rs();st();de();Be();U();wo();tw=(i=>(i[i.Buffer=0]="Buffer",i[i.LanguageServer=1]="LanguageServer",i[i.Global=2]="Global",i))(tw||{}),Due=Z("core-workspaceFolder"),Tue=[0,1,2],kue=pe(5e3,50);Pue=li.as(ns.ExtensionContribution),hp=class{constructor(e){this.configurations=e;this._onDidChangeWorkspaceFolders=new p.Emitter;this.onDidChangeWorkspaceFolders=this._onDidChangeWorkspaceFolders.event;this.rootPatterns=new Map;this._workspaceFolders=[];this._tokenSources=new Set;_.on("VimLeavePre",this.cancelAll,this),this.updateConfiguration(!0),this.configurations.onDidChange(t=>{(t.affectsConfiguration("workspace")||t.affectsConfiguration("coc.preferences"))&&this.updateConfiguration(!1)})}updateConfiguration(e){let t=this.configurations.initialConfiguration,i=t.get("workspace"),r=t.get("coc.preferences.rootPatterns");if(this.config={rootPatterns:re(r)?le(i.rootPatterns):r,ignoredFiletypes:le(i.ignoredFiletypes),bottomUpFiletypes:le(i.bottomUpFiletypes),ignoredFolders:le(i.ignoredFolders),workspaceFolderCheckCwd:!!i.workspaceFolderCheckCwd,workspaceFolderFallbackCwd:!!i.workspaceFolderFallbackCwd},e){let o=t.get("languageserver",{});this.addServerRootPatterns(o)}}addServerRootPatterns(e){for(let t of Object.keys(Ue(e))){let i=e[t],{filetypes:r,rootPatterns:o}=i;Array.isArray(r)&&!re(o)&&r.filter(s=>typeof s=="string").forEach(s=>{this.addRootPattern(s,o)})}}cancelAll(){for(let e of this._tokenSources)e.cancel()}setWorkspaceFolders(e){if(!e||!Array.isArray(e))return;let t=e.map(i=>dp(i));this._workspaceFolders=t.filter(i=>i!=null)}getWorkspaceFolder(e){if(e.scheme!=="file")return;let t=Array.from(this._workspaceFolders).map(o=>O.parse(o.uri).fsPath);t.sort((o,s)=>s.length-o.length);let i=e.fsPath,r=t.find(o=>dt(o,i,!0));return dp(r)}getRelativePath(e,t){let i,r="";if(typeof e=="string"?(i=O.file(e),r=e):typeof e<"u"&&(i=e,r=e.fsPath),!i)return r;let o=this.getWorkspaceFolder(i);if(!o)return r;typeof t>"u"&&this._workspaceFolders&&(t=this._workspaceFolders.length>1);let s=R.relative(O.parse(o.uri).fsPath,i.fsPath);return s=s==""?i.fsPath:s,t&&o.name&&(s=`${o.name}/${s}`),s}get workspaceFolders(){return this._workspaceFolders}addRootPattern(e,t){let i=this.rootPatterns.get(e)??[];for(let r of t)i.includes(r)||i.push(r);this.rootPatterns.set(e,i)}resolveRoot(e,t,i,r){if(e.buftype!==""||e.schema!=="file")return null;let o=O.parse(e.uri),s=this.getWorkspaceFolder(o);if(s)return O.parse(s.uri).fsPath;let a=R.dirname(o.fsPath),{ignoredFiletypes:l,ignoredFolders:u,workspaceFolderCheckCwd:c,workspaceFolderFallbackCwd:d,bottomUpFiletypes:h}=this.config;if(l!=null&&l.includes(e.filetype))return null;u=Array.isArray(u)?u.filter(f=>f&&f.length>0).map(f=>r(f)):[];let g=null;for(let f of Tue){let m=this.getRootPatterns(e,f);if(m&&m.length){let b=h.includes("*")||h.includes(e.filetype),v=xg(a,m,t,b,c,u);if(v){g=v;break}}}return d&&!g&&!u.includes(t)&&dt(t,a,!0)&&(g=t),g&&this.addWorkspaceFolder(g,i),g}addWorkspaceFolder(e,t){let i=dp(e);if(!!i)return this._workspaceFolders.findIndex(r=>r.uri==i.uri)==-1&&(this._workspaceFolders.push(i),t&&this._onDidChangeWorkspaceFolders.fire({added:[i],removed:[]})),i}renameWorkspaceFolder(e,t){let i=dp(t);if(!i)return;let r=this._workspaceFolders.findIndex(s=>O.parse(s.uri).fsPath==e);if(r==-1)return;let o=this.workspaceFolders[r];this._workspaceFolders.splice(r,1,i),this._onDidChangeWorkspaceFolders.fire({removed:[o],added:[i]})}removeWorkspaceFolder(e){let t=dp(e);if(!t)return;let i=this._workspaceFolders.findIndex(r=>r.uri==t.uri);i!=-1&&(this._workspaceFolders.splice(i,1),this._onDidChangeWorkspaceFolders.fire({removed:[t],added:[]}))}getRootPatterns(e,t){return t==0?e.getVar("root_patterns",[])||[]:t==1?this.getServerRootPatterns(e.languageId):this.config.rootPatterns}reset(){this.rootPatterns.clear(),this._workspaceFolders=[]}getServerRootPatterns(e){let t=Pue.getRootPatternsByFiletype(e);return t=t.concat(le(this.rootPatterns.get(e))),yi(t)}checkFolder(e,t,i){return jZ(e,t,i)}async checkPatterns(e,t){if(re(e))return!1;let i=e.map(u=>O.parse(u.uri).fsPath),r=!1,o=new p.CancellationTokenSource;this._tokenSources.add(o);let s=o.token,a=setTimeout(()=>{o.cancel()},kue),l=await Promise.allSettled(i.map(u=>this.checkFolder(u,t,s).then(c=>{this._tokenSources.delete(o),c&&(r=!0,clearTimeout(a),o.cancel())})));return clearTimeout(a),l.forEach(u=>{u.status==="rejected"&&!vy(u.reason)&&Due.error("checkPatterns error:",t,u.reason)}),r}}});var gp,aX=D(()=>{"use strict";Pe();te();gp=class{constructor(e,t){this._create=e;this.disposables=[];this.itemsMap=new Map;let{disposables:i}=this;for(let r of t.attached())this.create(r);t.onDidOpenTextDocument(r=>{this.create(t.getDocument(r.bufnr))},null,i),t.onDidChangeDocument(r=>{this.onChange(r)},null,i),t.onDidCloseDocument(r=>{this.delete(r.bufnr)},null,i),_.on("LinesChanged",r=>{let o=this.itemsMap.get(r);o&&typeof o.item.onTextChange=="function"&&o.item.onTextChange()},null,i)}get items(){return Array.from(this.itemsMap.values()).map(e=>e.item)}getItem(e){var i;if(typeof e=="number")return(i=this.itemsMap.get(e))==null?void 0:i.item;let t=Array.from(this.itemsMap.values()).find(r=>r.uri==e);return t?t.item:void 0}create(e){let t=this.itemsMap.get(e.bufnr);t&&t.item.dispose();let i=this._create(e);i&&this.itemsMap.set(e.bufnr,{uri:e.uri,item:i})}onChange(e){let t=this.itemsMap.get(e.bufnr);t&&typeof t.item.onChange=="function"&&t.item.onChange(e)}delete(e){let t=this.itemsMap.get(e);t&&(t.item.dispose(),this.itemsMap.delete(e))}reset(){for(let e of this.itemsMap.values())e.item.dispose();this.itemsMap.clear()}dispose(){W(this.disposables);for(let e of this.itemsMap.values())e.item.dispose();this._create=void 0,this.itemsMap.clear()}}});var pp,lX=D(()=>{"use strict";de();Be();pp=class{constructor(e){this.filepath=e}fetch(e){let t=this.load();if(!e)return t;let i=e.split(".");for(let r of i){if(typeof t[r]>"u")return;t=t[r]}return t}exists(e){let t=this.load(),i=e.split(".");for(let r of i){if(typeof t[r]>"u")return!1;t=t[r]}return!0}delete(e){let t=this.load(),i=t,r=e.split("."),o=r.length;for(let s=0;s"u");s++){if(s==o-1){delete t[r[s]],F.writeFileSync(this.filepath,JSON.stringify(i,null,2),"utf8");break}t=t[r[s]]}}push(e,t){let i=Ue(this.load()),r=i,o=e.split("."),s=o.length;for(let a=0;a"u"&&(r[l]={}),r=r[l]}}load(){let e=R.dirname(this.filepath);if(!F.existsSync(e))return F.mkdirSync(e,{recursive:!0}),F.writeFileSync(this.filepath,"{}","utf8"),{};try{let i=F.readFileSync(this.filepath,"utf8");return JSON.parse(i.trim())}catch{return F.writeFileSync(this.filepath,"{}","utf8"),{}}}clear(){!F.existsSync(this.filepath)||F.writeFileSync(this.filepath,"{}","utf8")}destroy(){F.existsSync(this.filepath)&&F.unlinkSync(this.filepath)}}});var rR,fp,oR=D(()=>{"use strict";rt();rR=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],fp=class{constructor(){this.items=new Map;this.shownIds=new Set;this._text="";this.interval=setInterval(()=>{this.setStatusText()},100).unref()}dispose(){this.items.clear(),this.shownIds.clear(),clearInterval(this.interval)}reset(){this.items.clear(),this.shownIds.clear()}createStatusBarItem(e,t=!1){let i=Fl(),r={text:"",priority:e,isProgress:t,show:()=>{this.shownIds.add(i),this.setStatusText()},hide:()=>{this.shownIds.delete(i),this.setStatusText()},dispose:()=>{this.shownIds.delete(i),this.items.delete(i),this.setStatusText()}};return this.items.set(i,r),r}getText(){if(this.shownIds.size==0)return"";let e=new Date,t=Math.floor(e.getMilliseconds()/100),i="",r=[];for(let[o,s]of this.items)this.shownIds.has(o)&&r.push(s);r.sort((o,s)=>o.priority-s.priority);for(let o of r)o.isProgress?i=`${i} ${rR[t]} ${o.text}`:i=`${i} ${o.text}`;return i}setStatusText(){let e=this.getText(),{nvim:t}=this;e!=this._text&&t&&(this._text=e,t.pauseNotification(),this.nvim.setVar("coc_status",e,!0),this.nvim.call("coc#util#do_autocmd",["CocStatusChange"],!0),t.resumeNotification(!1,!0))}}});var mp,uX=D(()=>{"use strict";Pe();te();U();mp=class{constructor(e,t){this.nvim=e;this.id=t;this.disposables=[];this._onExit=new p.Emitter;this._onStderr=new p.Emitter;this._onStdout=new p.Emitter;this.onExit=this._onExit.event;this.onStdout=this._onStdout.event;this.onStderr=this._onStderr.event;_.on("TaskExit",(i,r)=>{i==this.id&&this._onExit.fire(r)},null,this.disposables),_.on("TaskStderr",(i,r)=>{i==this.id&&this._onStderr.fire(r)},null,this.disposables),_.on("TaskStdout",(i,r)=>{i==this.id&&this._onStdout.fire(r)},null,this.disposables)}async start(e){let{nvim:t}=this;return await t.call("coc#task#start",[this.id,e])}async stop(){let{nvim:e}=this;await e.call("coc#task#stop",[this.id])}get running(){let{nvim:e}=this;return e.call("coc#task#running",[this.id])}dispose(){let{nvim:e}=this;e.call("coc#task#stop",[this.id],!0),this._onStdout.dispose(),this._onStderr.dispose(),this._onExit.dispose(),W(this.disposables)}}});var sR,Rue,aR,y,he=D(()=>{"use strict";Je();$$();U$();z$();iv();Q$();kU();PU();_U();iX();uP();rX();Rl();sX();iw();Pe();xe();aX();lX();Eg();Tg();oR();oP();uX();Yt();rs();de();Be();Tl();sR=Z("workspace"),Rue=["showMessage","runTerminalCommand","openTerminal","showQuickpick","menuPick","openLocalConfig","showPrompt","createStatusBarItem","createOutputChannel","showOutputChannel","requestInput","echoLines","getCursorPosition","moveTo","getOffset","getSelectedRange","selectRange","createTerminal"],aR=class{constructor(){this.statusLine=new fp;XZ().then(o=>{this.fuzzyExports=o}),ra.create().then(o=>{this.strWdith=o}),_.on("VimResized",(o,s)=>{Object.assign(Ue(this.env),{columns:o,lines:s})}),Object.defineProperty(this.statusLine,"nvim",{get:()=>this.nvim});let e=this.configurations=new Xg(yZ,new Gg(this));this.workspaceFolderControl=new hp(this.configurations);let t=this.documentsManager=new Vg(this.configurations,this.workspaceFolderControl);this.contentProvider=new Kg(t),this.watchers=new cp,this.autocmds=new zg,this.keymaps=new up,this.files=new ip(t,this.configurations,this.workspaceFolderControl,this.keymaps),this.editors=new ep(t),this.onDidRuntimePathChange=this.watchers.onDidRuntimePathChange,this.onDidChangeWorkspaceFolders=this.workspaceFolderControl.onDidChangeWorkspaceFolders,this.onDidChangeConfiguration=this.configurations.onDidChange,this.onDidOpenTextDocument=t.onDidOpenTextDocument,this.onDidChangeTextDocument=t.onDidChangeDocument,this.onDidCloseTextDocument=t.onDidCloseDocument,this.onDidSaveTextDocument=t.onDidSaveTextDocument,this.onWillSaveTextDocument=t.onWillSaveTextDocument,this.onDidCreateFiles=this.files.onDidCreateFiles,this.onDidRenameFiles=this.files.onDidRenameFiles,this.onDidDeleteFiles=this.files.onDidDeleteFiles,this.onWillCreateFiles=this.files.onWillCreateFiles,this.onWillRenameFiles=this.files.onWillRenameFiles,this.onWillDeleteFiles=this.files.onWillDeleteFiles;let r=e.initialConfiguration.get("coc.preferences").watchmanPath??vZ;this.fileSystemWatchers=new Ic(this.workspaceFolderControl,r)}get initialConfiguration(){return this.configurations.initialConfiguration}async init(e){let{nvim:t}=this;for(let o of Rue)Object.defineProperty(this,o,{get:()=>(...s)=>{let a=` +`+Error().stack.split(` +`).slice(2,4).join(` +`);return sR.warn(`workspace.${o} is deprecated, please use window.${o} instead.`,a),e[o].apply(e,s)}});for(let o of["onDidOpenTerminal","onDidCloseTerminal"])Object.defineProperty(this,o,{get:()=>{let s=` +`+Error().stack.split(` +`).slice(2,4).join(` +`);return sR.warn(`workspace.${o} is deprecated, please use window.${o} instead.`,s),e[o]}});let i=this._env=await t.call("coc#util#vim_info");e.init(i),this.checkVersion(Lk),this.configurations.updateMemoryConfig(this._env.config),this.workspaceFolderControl.setWorkspaceFolders(this._env.workspaceFolders),this.workspaceFolderControl.onDidChangeWorkspaceFolders(()=>{t.setVar("WorkspaceFolders",this.folderPaths,!0)}),this.files.attach(t,i,e),this.contentProvider.attach(t),this.keymaps.attach(t),this.autocmds.attach(t,i),this.watchers.attach(t,i),await this.documentsManager.attach(this.nvim,this._env),await this.editors.attach(t);let r=os.create("watchman",t);this.fileSystemWatchers.attach(r),this.strWdith&&this.strWdith.setAmbw(!i.ambiguousIsNarrow)}checkVersion(e){this._env.apiversion!=e&&this.nvim.echoError(`API version ${this._env.apiversion} is not ${Lk}, please build coc.nvim by 'yarn install' after pull source code.`)}getDisplayWidth(e,t=!1){return this.strWdith.getWidth(e,t)}get version(){return bl}get cwd(){return this.documentsManager.cwd}get env(){return this._env}get root(){return this.documentsManager.root||this.cwd}get rootPath(){return this.root}get bufnr(){return this.documentsManager.bufnr}get insertMode(){return _.insertMode}get floatSupported(){return!0}get uri(){return this.documentsManager.uri}get workspaceFolder(){return this.workspaceFolders[0]}get textDocuments(){return this.documentsManager.textDocuments}get documents(){return this.documentsManager.documents}get document(){return this.documentsManager.document}get workspaceFolders(){return this.workspaceFolderControl.workspaceFolders}checkPatterns(e,t){return this.workspaceFolderControl.checkPatterns(t??this.workspaceFolderControl.workspaceFolders,e)}get folderPaths(){return this.workspaceFolders.map(e=>O.parse(e.uri).fsPath)}get channelNames(){return os.names}get pluginRoot(){return yo}get isVim(){return this._env.isVim}get isNvim(){return!this._env.isVim}get completeOpt(){return""}get filetypes(){return this.documentsManager.filetypes}get languageIds(){return this.documentsManager.languageIds}createNameSpace(e){return QZ(e)}has(e){return fv(this.env,e)}registerAutocmd(e){if(e.request&&e.event!=="BufWritePre"){let t=xl(Error().stack);sR.warn(`Extension "${t}" registered synchronized autocmd "${e.event}", which could be slow.`)}return this.autocmds.registerAutocmd(e)}watchOption(e,t,i){return this.watchers.watchOption(e,t,i)}watchGlobal(e,t,i){let r=t??function(){};return this.watchers.watchGlobal(e,r,i)}match(e,t){return lP(e,t.uri,t.languageId)}createFileSystemWatcher(e,t,i,r){return this.fileSystemWatchers.createFileSystemWatcher(e,t,i,r)}createFuzzyMatch(){return new uv(this.fuzzyExports)}getWatchmanPath(){return VZ(this.configurations)}getConfiguration(e,t){return this.configurations.getConfiguration(e,t)}resolveJSONSchema(e){return this.configurations.getJSONSchema(e)}getDocument(e){return this.documentsManager.getDocument(e)}hasDocument(e,t){let i=this.documentsManager.getDocument(e);return i!=null&&(t!=null?i.version==t:!0)}getUri(e,t=""){let i=this.documentsManager.getDocument(e);return i?i.uri:t}isAttached(e){let t=this.documentsManager.getDocument(e);return t!=null&&t.attached}getAttachedDocument(e){let t=this.getDocument(e);if(!t)throw new Error(`Buffer ${e} not created.`);if(!t.attached)throw new Error(`Buffer ${e} not attached, ${t.notAttachReason}`);return t}getQuickfixItem(e,t,i="",r){return this.documentsManager.getQuickfixItem(e,t,i,r)}createMru(e){return new Gr(e)}async getQuickfixList(e){return this.documentsManager.getQuickfixList(e)}async showLocations(e){await this.documentsManager.showLocations(e)}getLine(e,t){return this.documentsManager.getLine(e,t)}getWorkspaceFolder(e){return this.workspaceFolderControl.getWorkspaceFolder(O.parse(e))}readFile(e){return this.documentsManager.readFile(e)}async getCurrentState(){let e=await this.document,t=await Ng(this.nvim);return{document:e.textDocument,position:t}}async getFormatOptions(e){return this.documentsManager.getFormatOptions(e)}resolveModule(e){return tJ(e)}async runCommand(e,t,i){return xo(e,{cwd:t??this.cwd},i)}expand(e){return this.documentsManager.expand(e)}async callAsync(e,t){return await mv(this.nvim,e,t)}registerTextDocumentContentProvider(e,t){return this.contentProvider.registerTextDocumentContentProvider(e,t)}registerKeymap(e,t,i,r={}){return this.keymaps.registerKeymap(e,t,i,r)}registerExprKeymap(e,t,i,r=!1){return this.keymaps.registerExprKeymap(e,t,i,r)}registerLocalKeymap(e,t,i,r,o=!1){return typeof arguments[0]=="string"&&(e=this.bufnr,t=arguments[0],i=arguments[1],r=arguments[2],o=arguments[3]??!1),this.keymaps.registerLocalKeymap(e,t,i,r,o)}createTask(e){return new mp(this.nvim,e)}createDatabase(e){return new pp(R.join(Gn,e+".json"))}registerBufferSync(e){return new gp(e,this.documentsManager)}async attach(){await this.documentsManager.attach(this.nvim,this._env)}jumpTo(e,t,i){return this.files.jumpTo(e,t,i)}findUp(e){return eJ(this.nvim,this.cwd,e)}applyEdit(e){return this.files.applyEdit(e)}createFile(e,t={}){return this.files.createFile(e,t)}loadFile(e,t){return this.files.loadResource(e,t)}async loadFiles(e){return this.files.loadResources(e)}async renameFile(e,t,i={}){await this.files.renameFile(e,t,i)}async deleteFile(e,t={}){await this.files.deleteFile(e,t)}async openResource(e){await this.files.openResource(e)}async computeWordRanges(e,t,i){let r=this.getDocument(e);return r?await r.chars.computeWordRanges(r.textDocument.lines,t,i):null}openTextDocument(e){return this.files.openTextDocument(e)}getRelativePath(e,t){return this.workspaceFolderControl.getRelativePath(e,t)}async findFiles(e,t,i,r){return this.files.findFiles(e,t,i,r)}detach(){this.documentsManager.detach()}reset(){this.statusLine.reset(),this.configurations.reset(),this.workspaceFolderControl.reset(),this.documentsManager.reset()}dispose(){this.autocmds.dispose(),this.statusLine.dispose(),this.watchers.dispose(),this.contentProvider.dispose(),this.documentsManager.dispose(),this.configurations.dispose()}},y=new aR});var Lc,lR,bp,cX=D(()=>{"use strict";Pe();U();te();Lc="filter",lR=class{constructor(){this.history=[]}next(e){let t=this.history.indexOf(e);return this.history[t+1]??this.history[0]}previous(e){let t=this.history.indexOf(e);return this.history[t-1]??this.history[this.history.length-1]}add(e){let t=this.history.indexOf(e);t!==-1&&this.history.splice(t,1),this.history.unshift(e)}toJSON(){return`[${this.history.join(",")}]`}},bp=class{constructor(e,t){this.nvim=e;this._activated=!1;this.history=new lR;this.disposables=[];this._onDidUpdate=new p.Emitter;this._onDidExit=new p.Emitter;this._onDidKeyPress=new p.Emitter;this.onDidKeyPress=this._onDidKeyPress.event;this.onDidUpdate=this._onDidUpdate.event;this.onDidExit=this._onDidExit.event;this.text="",_.on("InputChar",(i,r)=>{if(!(i!==Lc||!this._activated)){if(!t.includes(r)){if(r.length==1){this.text=this.text+r,this._onDidUpdate.fire(this.text);return}if(r==""||r==""){this.text=this.text.slice(0,-1),this._onDidUpdate.fire(this.text);return}if(r==""){this.text="",this._onDidUpdate.fire(this.text);return}if(r==""){let o=this.history.next(this.text);o&&(this.text=o,this._onDidUpdate.fire(this.text));return}if(r==""){let o=this.history.previous(this.text);o&&(this.text=o,this._onDidUpdate.fire(this.text))}if(r==""||r==""){this.deactivate();return}}this._onDidKeyPress.fire(r)}},null,this.disposables)}active(){this._activated=!0,this.text="",this.nvim.call("coc#prompt#start_prompt",[Lc],!0)}deactivate(e){if(!this._activated)return;this.nvim.call("coc#prompt#stop_prompt",[Lc],!0),this._activated=!1;let{text:t}=this;this.text="",this._onDidExit.fire(e),this.history.add(t)}get activated(){return this._activated}dispose(){this.deactivate(),this._onDidKeyPress.dispose(),this._onDidUpdate.dispose(),this._onDidExit.dispose(),W(this.disposables)}}});function uR(n){return yp.is(n.label)?n.label.label:n.label}var yp,Ml,Vr,vp=D(()=>{"use strict";Je();de();(e=>{function n(t){return typeof t.label=="string"}e.is=n})(yp||(yp={}));Ml=(i=>(i[i.None=0]="None",i[i.Collapsed=1]="Collapsed",i[i.Expanded=2]="Expanded",i))(Ml||{}),Vr=class{constructor(e,t=0){this.collapsibleState=t;O.isUri(e)?(this.resourceUri=e,this.label=R.basename(e.path),this.id=e.toString()):this.label=e}}});var hX={};Ls(hX,{default:()=>So});var dX,_ue,Eue,cR,dR,hR,So,wp=D(()=>{"use strict";ae();Dt();Pe();xe();Eg();te();Re();pc();ls();Be();U();fe();We();he();cX();vp();dX=Z("BasicTreeView"),_ue=pe(500,10),Eue=pe(5,1),cR="tree",dR=3e3,hR=1,So=class{constructor(e,t){this.viewId=e;this.opts=t;this._selection=[];this._keymapDefs=[];this._onDispose=new p.Emitter;this._onDidRefrash=new p.Emitter;this._onDidExpandElement=new p.Emitter;this._onDidCollapseElement=new p.Emitter;this._onDidChangeSelection=new p.Emitter;this._onDidChangeVisibility=new p.Emitter;this._onDidFilterStateChange=new p.Emitter;this._onDidCursorMoved=new p.Emitter;this.onDidRefrash=this._onDidRefrash.event;this.onDispose=this._onDispose.event;this.onDidExpandElement=this._onDidExpandElement.event;this.onDidCollapseElement=this._onDidCollapseElement.event;this.onDidChangeSelection=this._onDidChangeSelection.event;this.onDidChangeVisibility=this._onDidChangeVisibility.event;this.onDidFilterStateChange=this._onDidFilterStateChange.event;this.onDidCursorMoved=this._onDidCursorMoved.event;this.retryTimers=0;this.renderedItems=[];this.nodesMap=new Map;this.mutex=new ji;this.disposables=[];this.lineState={titleCount:0,messageCount:0};this.loadConfiguration(),y.onDidChangeConfiguration(this.loadConfiguration,this,this.disposables),t.enableFilter&&(this.filter=new bp(this.nvim,[this.keys.selectNext,this.keys.selectPrevious,this.keys.invoke]));let i=hR;hR=hR+1,this.bufname=`CocTree${i}`,this.tooltipFactory=P.createFloatFactory({modes:["n"]}),this.provider=t.treeDataProvider,this.leafIndent=t.disableLeafIndent!==!0,this.winfixwidth=t.winfixwidth!==!1,this.autoWidth=t.autoWidth===!0;let r;Object.defineProperty(this,"message",{set:l=>{r=l?l.replace(/\r?\n/g," "):void 0,this.updateHeadLines()},get:()=>r});let o=e.replace(/\r?\n/g," ");Object.defineProperty(this,"title",{set:l=>{o=l?l.replace(/\r?\n/g," "):void 0,this.updateHeadLines()},get:()=>o});let s;Object.defineProperty(this,"description",{set:l=>{s=l?l.replace(/\r?\n/g," "):void 0,this.updateHeadLines()},get:()=>s});let a;Object.defineProperty(this,"filterText",{set:l=>{let{titleCount:u,messageCount:c}=this.lineState,d=u+c;if(l!=null){let h=[{lnum:d,colStart:ue(l),colEnd:ue(l)+1,hlGroup:"Cursor"}];this.renderedItems=[],this.updateUI([l+" "],h,d,-1,!0),this.doFilter(l)}else a!=null&&this.updateUI([],[],d,d+1);a=l},get:()=>a}),this.provider.onDidChangeTreeData&&this.provider.onDidChangeTreeData(this.onDataChange,this,this.disposables),_.on("BufUnload",l=>{if(l!=this.bufnr)return;let u=this.winid!=null;this.winid=void 0,this.bufnr=void 0,u&&this._onDidChangeVisibility.fire({visible:!1}),this.dispose()},null,this.disposables),_.on("WinClosed",l=>{this.winid===l&&(this.winid=void 0,this._onDidChangeVisibility.fire({visible:!1}))},null,this.disposables),_.on("BufWinLeave",(l,u)=>{l==this.bufnr&&u==this.winid&&(this.winid=void 0,this._onDidChangeVisibility.fire({visible:!1}))},null,this.disposables),P.onDidTabClose(l=>{this._targetTabId===l&&this.dispose()},null,this.disposables),_.on("CursorHold",async(l,u)=>{l==this.bufnr&&await this.onHover(u[0])},null,this.disposables),_.on(["CursorMoved","BufEnter"],()=>{this.cancelResolve()},null,this.disposables),_.on("CursorMoved",(l,u)=>{if(l==this.bufnr){let c=this.getElementByLnum(u[0]-1);this._onDidCursorMoved.fire(c)}},null,this.disposables),_.on("WinEnter",l=>{if(l!=this.windowId||!this.filtering)return;let u=this.nvim.createBuffer(this.bufnr),c=this.startLnum-1,d=oe(this.filterText).length,h=M.create(c,d,c,d+1);u.highlightRanges(cR,"Cursor",[h]),this.nvim.call("coc#prompt#start_prompt",[Lc],!0),this.redraw()},null,this.disposables),_.on("WinLeave",l=>{if(l!=this.windowId||!this.filtering)return;let u=this.nvim.createBuffer(this.bufnr);this.nvim.call("coc#prompt#stop_prompt",[Lc],!0),u.clearNamespace(cR,this.startLnum-1,this.startLnum)},null,this.disposables),this.disposables.push(this._onDidChangeVisibility,this._onDidCursorMoved,this._onDidChangeSelection,this._onDidCollapseElement,this._onDidExpandElement),this.filter&&(this.filter.onDidExit(l=>{this.nodesMap.clear(),this.filterText=void 0,this.itemsToFilter=void 0,l&&typeof this.provider.getParent=="function"?(this.renderedItems=[],this.reveal(l,{focus:!0})):(this.clearSelection(),this.render()),this._onDidFilterStateChange.fire(!1)}),this.filter.onDidUpdate(l=>{this.filterText=l}),this.filter.onDidKeyPress(async l=>{var d,h;let u=le(this.renderedItems),c=this.selection[0];if(l==""||l==this.keys.selectPrevious){let g=u.findIndex(b=>b.node==c),f=g==-1||g==0?u.length-1:g-1,m=(d=u[f])==null?void 0:d.node;m&&this.selectItem(m,!0)}if(l==""||l==this.keys.selectNext){let g=u.findIndex(b=>b.node==c),f=g==-1||g==u.length-1?0:g+1,m=(h=u[f])==null?void 0:h.node;m&&this.selectItem(m,!0)}if(l==""||l==this.keys.invoke){if(!c)return;await this.invokeCommand(c),this.filter.deactivate(c)}}))}get windowId(){return this.winid}get targetTabId(){return this._targetTabId}get targetWinId(){return this._targetWinId}get targetBufnr(){return this._targetBufnr}get startLnum(){let e=this.filterText==null?0:1;return this.lineState.messageCount+this.lineState.titleCount+e}get nvim(){return y.nvim}get filtering(){return this.filter!=null&&this.filter.activated}loadConfiguration(e){if(!e||e.affectsConfiguration("tree")){let t=y.getConfiguration("tree",null);this.config={openedIcon:t.get("openedIcon"," "),closedIcon:t.get("closedIcon"," ")},this.keys={close:t.get("key.close"),invoke:t.get("key.invoke"),toggle:t.get("key.toggle"),actions:t.get("key.actions"),collapseAll:t.get("key.collapseAll"),toggleSelection:t.get("key.toggleSelection"),activeFilter:t.get("key.activeFilter"),selectNext:t.get("key.selectNext"),selectPrevious:t.get("key.selectPrevious")},e&&this.visible&&this.render()}}async doFilter(e){let t=[],i=0,r=await this.mutex.acquire();try{if(!this.itemsToFilter){let c=[],d=async g=>{for(let f of g){c.push(f);let m=await Promise.resolve(this.provider.getChildren(f));re(m)||await d(m)}},h=await Promise.resolve(this.provider.getChildren());await d(h),this.itemsToFilter=c}let o=e.toLowerCase(),s=e.length===0;for(let c of this.itemsToFilter){let d=await this.getTreeItem(c),h=uR(d),g=0;if(s)d.label={label:h,highlights:[]};else{let b=ia(e,o,0,h,h.toLowerCase(),0,{boostFullMatch:!0,firstMatchCanBeWeak:!0});if(!b)continue;g=b[0],d.label={label:h,highlights:cv(h,b)}}d.collapsibleState=0;let{line:f,highlights:m}=this.getRenderedLine(d,i,0);t.push({level:0,node:c,line:f,index:i,score:g,highlights:m}),i+=1}t.sort((c,d)=>c.score!=d.score?d.score-c.score:c.index-d.index);let a=this.startLnum,l=[],u=this.renderedItems=t.map((c,d)=>(l.push(...c.highlights.map(h=>(h.lnum=a+d,h))),delete c.index,delete c.score,delete c.highlights,c));this.updateUI(u.map(c=>c.line),l,a,-1,!0),u.length?this.selectItem(u[0].node,!0):this.clearSelection(),this.redraw(),r()}catch(o){r(),dX.error("Error on tree filter:",o)}}async onHover(e){let t=this.getElementByLnum(e-1);if(!t||!this.nodesMap.has(t))return;let i=this.nodesMap.get(t),r=i.item;if(!r.tooltip&&!i.resolved&&(r=await this.resolveItem(t,r)),!r.tooltip)return;let s={filetype:Ln.is(r.tooltip)&&r.tooltip.kind==fr.Markdown?"markdown":"txt",content:Ln.is(r.tooltip)?r.tooltip.value:r.tooltip};await this.tooltipFactory.show([s])}async onClick(e){let{nvim:t}=this,[i,r]=await t.eval("[getline('.'),col('.')]"),o=Xt(i,0,r-1),s=i[o.length],{openedIcon:a,closedIcon:l}=this.config;/^\s*$/.test(o)&&[a,l].includes(s)?await this.toggleExpand(e):await this.invokeCommand(e)}async invokeCommand(e){let t=this.nodesMap.get(e);if(!t)return;this.selectItem(e);let i=t.item;if(i.command||(i=await this.resolveItem(e,i)),!i||!i.command)throw new Error("Failed to resolve command from TreeItem.");await V.execute(i.command)}async invokeActions(e){if(!e)return;if(this.selectItem(e),typeof this.provider.resolveActions!="function"){await P.showWarningMessage("No actions");return}let t=this.nodesMap.get(e),i=await Promise.resolve(this.provider.resolveActions(t.item,e));if(!i||i.length==0){await P.showWarningMessage("No actions available");return}let r=i.map(s=>s.title),o=await P.showMenuPicker(r,"Choose action");o!=-1&&await Promise.resolve(i[o].handler(e))}async onDataChange(e){if(this.filtering){this.itemsToFilter=void 0,await this.doFilter(oe(this.filterText));return}if(this.clearSelection(),!e){await this.render();return}let t=await this.mutex.acquire();try{let i=this.renderedItems,r=i.findIndex(o=>o.node===e);if(r!=-1&&this.bufnr){let s=i[r].level,a=0;for(let d=r;ds)&&(a+=1)}let l=[],u=[],c=r+this.startLnum;await this.appendTreeNode(e,s,c,l,u),i.splice(r,a,...l),this.updateUI(l.map(d=>d.line),u,c,c+a)}t()}catch(i){let r=`Error on tree refresh: ${i}`;dX.error(r,i),this.nvim.errWriteLine("[coc.nvim] "+r),t()}}async resolveItem(e,t){if(typeof this.provider.resolveTreeItem=="function"){let i=this.resolveTokenSource=new p.CancellationTokenSource,r=i.token;if(t=await Promise.resolve(this.provider.resolveTreeItem(t,e,r)),i.dispose(),this.resolveTokenSource=void 0,r.isCancellationRequested)return}return this.nodesMap.set(e,{item:t,resolved:!0}),t}get visible(){return this.bufnr?this.winid!=null:!1}get valid(){return typeof this.bufnr=="number"}get selection(){return this._selection.slice()}async checkLines(){if(!this.bufnr)return!1;let t=await this.nvim.createBuffer(this.bufnr).lines,{titleCount:i,messageCount:r}=this.lineState;t=t.slice(i+r);let o=this.renderedItems.map(s=>s.line);return Me(t,o)}async toggleExpand(e){let t=this.nodesMap.get(e);if(!t)return;let i=t.item,r=this.getItemLnum(e),o=r-this.startLnum,s=this.renderedItems[o];if(!s||i.collapsibleState==0){if(typeof this.provider.getParent=="function"){let c=await Promise.resolve(this.provider.getParent(e));c&&(await this.toggleExpand(c),this.focusItem(c))}return}let a=0;if(i.collapsibleState==2){let c=s.level;for(let d=o+1;dc.line),u,r,r+a+1),this.refreshSigns(),i.collapsibleState==1?this._onDidCollapseElement.fire({element:e}):this._onDidExpandElement.fire({element:e})}toggleSelection(e){if(!e)return;let t=this._selection.findIndex(i=>i===e);t!==-1?this.unselectItem(t):this.selectItem(e)}clearSelection(){if(!this.bufnr)return;this._selection=[],this.nvim.createBuffer(this.bufnr).unplaceSign({group:"CocTree"}),this._onDidChangeSelection.fire({selection:[]})}selectItem(e,t,i){let{nvim:r}=this,o=this.getItemLnum(e);if(o==null||!this.bufnr)return;let s=r.createBuffer(this.bufnr),a=this._selection.includes(e);!this.opts.canSelectMany||t?this._selection=[e]:a||this._selection.push(e),r.pauseNotification(),(!this.opts.canSelectMany||t)&&s.unplaceSign({group:"CocTree"}),r.call("coc#compat#execute",[this.winid,`normal! ${o+1}G`],!0),s.placeSign({id:dR+o,lnum:o+1,name:"CocTreeSelected",group:"CocTree"}),i||this.redraw(),r.resumeNotification(!1,!0),a||this._onDidChangeSelection.fire({selection:this._selection})}unselectItem(e){let t=this._selection[e],i=this.getItemLnum(t);if(i==null||!this.bufnr)return;this._selection.splice(e,1),this.nvim.createBuffer(this.bufnr).unplaceSign({group:"CocTree",id:dR+i}),this._onDidChangeSelection.fire({selection:this._selection})}focusItem(e){if(!this.winid)return;let t=this.getItemLnum(e);t!=null&&this.nvim.call("coc#compat#execute",[this.winid,`exe ${t+1}`],!0)}getElementByLnum(e){let t=this.renderedItems[e-this.startLnum];return t?t.node:void 0}getItemLnum(e){let t=this.renderedItems.findIndex(i=>i.node===e);if(t!=-1)return this.startLnum+t}async getTreeItem(e){let t,i=!1,r=this.nodesMap.get(e);r!=null&&(t=r.item,i=r.resolved);let o=await Promise.resolve(this.provider.getTreeItem(e));return t&&t.collapsibleState!=0&&o.collapsibleState!=0&&(o.collapsibleState=t.collapsibleState),this.nodesMap.set(e,{item:o,resolved:i}),o}getRenderedLine(e,t,i){let{openedIcon:r,closedIcon:o}=this.config,s=[],{label:a,deprecated:l,description:u}=e,c=" ".repeat(i),d=(g,f)=>{let m=ue(c);s.push({lnum:t,hlGroup:f,colStart:m,colEnd:m+ue(g)})};switch(e.collapsibleState){case 2:{d(r,"CocTreeOpenClose"),c+=r+" ";break}case 1:{d(o,"CocTreeOpenClose"),c+=o+" ";break}default:c+=this.leafIndent?" ":""}if(e.icon){let{text:g,hlGroup:f}=e.icon;d(g,f),c+=g+" "}if(yp.is(a)&&Array.isArray(a.highlights)){let g=ue(c);for(let f of a.highlights)s.push({lnum:t,hlGroup:"CocSearch",colStart:g+f[0],colEnd:g+f[1]})}let h=uR(e);return l&&d(h,"CocDeprecatedHighlight"),c+=h,u&&u.indexOf(` +`)==-1&&(c+=" ",d(u,"CocTreeDescription"),c+=u),{line:c,highlights:s}}async appendTreeNode(e,t,i,r,o){let s=1,a=await this.getTreeItem(e),l=this.getRenderedLine(a,i,t);if(o.push(...l.highlights),r.push({level:t,line:l.line,node:e}),a.collapsibleState==2){let u=t+1,c=await Promise.resolve(this.provider.getChildren(e));for(let d of le(c)){let h=await this.appendTreeNode(d,u,i+s,r,o);s=s+h}}return s}updateUI(e,t,i=0,r=-1,o=!1){if(!this.bufnr)return;let{nvim:s,winid:a}=this,l=s.createBuffer(this.bufnr);if(s.pauseNotification(),l.setOption("modifiable",!0,!0),l.setLines(e,{start:i,end:r,strictIndexing:!1},!0),this.autoWidth&&this.nvim.call("coc#window#adjust_width",[a],!0),t.length){let u=r==-1?-1:i+e.length;s.call("coc#highlight#update_highlights",[this.bufnr,cR,t,i,u],!0)}l.setOption("modifiable",!1,!0),o||this.redraw(),s.resumeNotification(!1,!0)}async reveal(e,t={}){if(this.filtering)return;let i=this.getItemLnum(e)!=null,{select:r,focus:o,expand:s}=t,a=e;if(typeof this.provider.getParent!="function")throw new Error("missing getParent function from provider for reveal.");if(!i)for(;a;){let l=await Promise.resolve(this.provider.getParent(a));if(l){let u=await this.getTreeItem(l);u.collapsibleState=2,a=l}else break}if(s){let l=await this.getTreeItem(e);if(l.collapsibleState!=0&&(l.collapsibleState=2,typeof s=="boolean"&&(s=1),s>1)){let u=Math.min(s,2),c=await Promise.resolve(this.provider.getChildren(e));for(;!re(c);){let d=[];for(let h of c){let g=await this.getTreeItem(h);if(g.collapsibleState!=0&&(g.collapsibleState=2,u>1)){let f=await Promise.resolve(this.provider.getChildren(h));d.push(...f)}}c=d,u=u-1}}}(!i||s)&&await this.render(),r!==!1&&this.selectItem(e),o&&this.focusItem(e)}updateHeadLines(e=!1){let{titleCount:t,messageCount:i}=this.lineState,r=e?-1:t+i,o=[],s=[];if(this.message&&(s.push({hlGroup:"MoreMsg",colStart:0,colEnd:ue(this.message),lnum:0}),o.push(this.message),o.push("")),this.title){if(s.push({hlGroup:"CocTreeTitle",colStart:0,colEnd:ue(this.title),lnum:o.length}),this.description){let a=ue(this.title)+1;s.push({hlGroup:"Comment",colStart:a,colEnd:a+ue(this.description),lnum:o.length})}o.push(this.title+(this.description?" "+this.description:""))}this.lineState.messageCount=this.message?2:0,this.lineState.titleCount=this.title?1:0,this.updateUI(o,s,0,r),e||this.refreshSigns()}refreshSigns(){let{selection:e,nvim:t,bufnr:i}=this;if(!e.length||!i)return;let r=t.createBuffer(i);t.pauseNotification(),r.unplaceSign({group:"CocTree"});for(let o of e){let s=this.getItemLnum(o);s!=null&&r.placeSign({id:dR+s,lnum:s+1,name:"CocTreeSelected",group:"CocTree"})}t.resumeNotification(!1,!0)}async render(){if(!this.bufnr)return;let e=await this.mutex.acquire();try{let t=[],i=[],{startLnum:r}=this,o=await Promise.resolve(this.provider.getChildren()),s=0,a=r,l=[];if(re(o))this.message="No results";else{this.message=="No results"&&(this.message="");for(let c of o){let d=await this.appendTreeNode(c,s,a,l,i);a+=d}}t.push(...l.map(c=>c.line)),this.renderedItems=l;let u=this.startLnum-r;i.forEach(c=>c.lnum=c.lnum+u),this.updateUI(t,i,this.startLnum,-1),this._onDidRefrash.fire(),this.retryTimers=0,e()}catch(t){this.renderedItems=[],this.nodesMap.clear(),this.lineState={titleCount:0,messageCount:1},e();let i=`${t}`.replace(/\r?\n/g," ");if(this.updateUI([i],[{hlGroup:"WarningMsg",colStart:0,colEnd:ue(i),lnum:0}]),this.retryTimers==Eue)return;this.timer=setTimeout(()=>{this.retryTimers=this.retryTimers+1,this.render()},_ue)}}async show(e="belowright 30vs",t=!0){let{nvim:i}=this,[r,o]=await i.eval('[bufnr("%"),win_getid()]');this._targetBufnr=r,this._targetWinId=o;let s={command:e,bufname:this.bufname,viewId:this.viewId.replace(/"/g,'\\"'),bufnr:Ie(this.bufnr,-1),winid:Ie(this.winid,-1),bufhidden:Ie(this.opts.bufhidden,"wipe"),canSelectMany:this.opts.canSelectMany===!0,winfixwidth:this.winfixwidth===!0},[a,l,u]=await i.call("coc#ui#create_tree",[s]);if(this.bufnr=a,this.winid=l,this._targetTabId=u,l!=s.winid&&this._onDidChangeVisibility.fire({visible:!0}),a==s.bufnr)return!0;this.registerKeymaps(),this.updateHeadLines(!0);let c=this.render();return t&&await c,!0}registerLocalKeymap(e,t,i,r=!1){this.bufnr?this.addLocalKeymap(e,t,i,r):this._keymapDefs.push({mode:e,key:t,fn:i,notify:r})}addLocalKeymap(e,t,i,r=!0){!t||y.registerLocalKeymap(this.bufnr,e,t,async()=>{let o=await this.nvim.call("line",["."]),s=this.getElementByLnum(o-1);await Promise.resolve(i(s))},r)}registerKeymaps(){let{toggleSelection:e,actions:t,close:i,invoke:r,toggle:o,collapseAll:s,activeFilter:a}=this.keys,{nvim:l,_keymapDefs:u}=this;for(this.disposables.push(y.registerLocalKeymap(this.bufnr,"n","",()=>{l.call("win_gotoid",[this._targetWinId],!0)},!0)),this.addLocalKeymap("n","",async c=>{c&&await this.onClick(c)}),this.filter&&this.addLocalKeymap("n",a,async()=>{this.nvim.command(`exe ${this.startLnum}`,!0),this.filter.active(),this.filterText="",this._onDidFilterStateChange.fire(!0)}),this.addLocalKeymap("n",e,c=>this.toggleSelection(c)),this.addLocalKeymap("n",r,c=>this.invokeCommand(c)),this.addLocalKeymap("n",t,c=>this.invokeActions(c)),this.addLocalKeymap("n",o,c=>this.toggleExpand(c)),this.addLocalKeymap("n",s,()=>this.collapseAll()),this.addLocalKeymap("n",i,()=>this.hide());u.length;){let c=u.pop();this.addLocalKeymap(c.mode,c.key,c.fn,c.notify)}}hide(){this.nvim.call("coc#window#close",[this.winid],!0),this.redraw(),this.winid=void 0,this._onDidChangeVisibility.fire({visible:!1})}redraw(){var e;(y.isVim||((e=this.filter)==null?void 0:e.activated))&&this.nvim.command("redraw",!0)}async collapseAll(){for(let e of this.nodesMap.values()){let t=e.item;t.collapsibleState==2&&(t.collapsibleState=1)}await this.render()}cancelResolve(){this.resolveTokenSource&&(this.resolveTokenSource.cancel(),this.resolveTokenSource=void 0)}dispose(){var t;if(!this.provider)return;this.timer&&clearTimeout(this.timer),this.cancelResolve();let{bufnr:e}=this;this.winid&&this._onDidChangeVisibility.fire({visible:!1}),e&&this.nvim.command(`silent! bwipeout! ${e}`,!0),this._keymapDefs=[],this.winid=void 0,this.bufnr=void 0,(t=this.filter)==null||t.dispose(),this._selection=[],this.itemsToFilter=[],this.tooltipFactory.dispose(),this.renderedItems=[],this.nodesMap.clear(),this.provider=void 0,this._onDispose.fire(),this._onDispose.dispose(),W(this.disposables)}}});var gR,P,We=D(()=>{"use strict";iv();x$();S$();R$();E$();Rl();Be();U();gR=class{constructor(){this.highlights=new Pv;this.terminalManager=new Bg;this.dialogs=new Tv;this.notifications=new Rv(this.dialogs),Object.defineProperty(this.highlights,"nvim",{get:()=>this.nvim}),Object.defineProperty(this.dialogs,"nvim",{get:()=>this.nvim}),Object.defineProperty(this.dialogs,"configuration",{get:()=>this.workspace.initialConfiguration}),Object.defineProperty(this.notifications,"nvim",{get:()=>this.nvim}),Object.defineProperty(this.notifications,"configuration",{get:()=>this.workspace.initialConfiguration}),Object.defineProperty(this.notifications,"statusLine",{get:()=>this.workspace.statusLine})}init(e){this.highlights.checkMarkers=this.workspace.has("nvim-0.5.1")||e.isVim}get activeTextEditor(){return this.workspace.editors.activeTextEditor}get visibleTextEditors(){return this.workspace.editors.visibleTextEditors}get onDidTabClose(){return this.workspace.editors.onDidTabClose}get onDidChangeActiveTextEditor(){return this.workspace.editors.onDidChangeActiveTextEditor}get onDidChangeVisibleTextEditors(){return this.workspace.editors.onDidChangeVisibleTextEditors}get terminals(){return this.terminalManager.terminals}get onDidOpenTerminal(){return this.terminalManager.onDidOpenTerminal}get onDidCloseTerminal(){return this.terminalManager.onDidCloseTerminal}async createTerminal(e){return await this.terminalManager.createTerminal(this.nvim,e)}async runTerminalCommand(e,t,i=!1){return await this.terminalManager.runTerminalCommand(this.nvim,e,t??this.workspace.cwd,i)}async openTerminal(e,t){return await this.terminalManager.openTerminal(this.nvim,e,t)}showMessage(e,t="more"){this.notifications.echoMessages(e,t)}createOutputChannel(e){return os.create(e,this.nvim)}showOutputChannel(e,t){let i=this.configuration.get("workspace.openOutputCommand","vs");os.show(e,i,t)}async echoLines(e,t=!1){await m$(this.nvim,this.workspace.env,e,t)}getCursorPosition(){return Ng(this.nvim)}async moveTo(e){await g$(this.nvim,e,this.workspace.env.isVim)}getSelectedRange(e){return y$(this.nvim,e)}async selectRange(e){await v$(this.nvim,e,this.nvim.isVim)}getOffset(){return p$(this.nvim)}getCursorScreenPosition(){return f$(this.nvim)}createTreeView(e,t){let i=(wp(),No(hX)).default;return new i(e,t)}createStatusBarItem(e=0,t={}){return this.workspace.statusLine.createStatusBarItem(e,t.progress)}async diffHighlights(e,t,i,r,o){return this.highlights.diffHighlights(e,t,i,r,o)}createFloatFactory(e){let t=this.workspace.initialConfiguration,i=Ue(t.get("floatFactory.floatConfig")),r=this.workspace.configurations.markdownPreference;return d$(this.workspace.nvim,Object.assign({...r,maxWidth:80},e),i)}async showQuickpick(e,t="Choose by number"){return await this.showMenuPicker(e,{title:t,position:"center"})}async showQuickPick(e,t,i=p.CancellationToken.None){return await this.dialogs.showQuickPick(e,t,i)}async createQuickPick(e={}){return await this.dialogs.createQuickPick(e)}async showMenuPicker(e,t,i){return await this.dialogs.showMenuPicker(e,t,i)}async showPrompt(e){return await this.dialogs.showPrompt(e)}async showDialog(e){return await this.dialogs.showDialog(e)}async requestInput(e,t,i){return await this.dialogs.requestInput(e,this.workspace.env,t,i)}async createInputBox(e,t,i){return await this.dialogs.createInputBox(e,t,i)}async showPickerDialog(e,t,i){return await this.dialogs.showPickerDialog(e,t,i)}async showInformationMessage(e,...t){let i=Error().stack;return await this.notifications._showMessage("Info",e,t,i)}async showWarningMessage(e,...t){let i=Error().stack;return await this.notifications._showMessage("Warning",e,t,i)}async showErrorMessage(e,...t){let i=Error().stack;return await this.notifications._showMessage("Error",e,t,i)}async showNotification(e){let t=Error().stack;await this.notifications.showNotification(e,t)}async withProgress(e,t){return this.notifications.withProgress(e,t)}async applyDiffHighlights(e,t,i,r,o=!1){return this.highlights.applyDiffHighlights(e,t,i,r,o)}get configuration(){return this.workspace.initialConfiguration}dispose(){this.terminalManager.dispose()}},P=new gR});var Fc,pa=D(()=>{"use strict";Fc=(i=>(i[i.Native=0]="Native",i[i.Remote=1]="Remote",i[i.Service=2]="Service",i))(Fc||{})});async function pX(n,e,t,i){if(e=="vim")return(await n.eval(t)).toString();if(e=="shell")return(await(0,ot.promisify)(gX.exec)(t)).stdout.replace(/\s*$/,"");let r=[`snip._reset("${xp(i)}")`];r.push(...t.split(/\r?\n/).map(s=>s.replace(/\t/g," "))),await Mc(n,r);let o=await n.call("pyxeval","str(snip.rv)");return oe(o)}function nw(n){let{range:e,regex:t,line:i}=n,r=[];if(t&&e!=null){let o=i.slice(e.start.character,e.end.character);r.push(`pattern = re.compile("${xp(t)}")`),r.push(`match = pattern.search("${xp(o)}")`)}else r.push("match = None");return r.join(` +`)}function fX(n){let{range:e,context:t,line:i}=n,r=["import re, os, vim, string, random",`path = vim.eval('expand("%:p")') or ""`,"fn = os.path.basename(path)"];t?(r.push("snip = ContextSnippet()"),r.push(`context = ${t}`)):r.push("context = True");let o=`(${e.start.line},${Buffer.byteLength(i.slice(0,e.start.character))})`,s=`(${e.start.line},${Buffer.byteLength(i.slice(0,e.end.character))})`,a=i.match(/^\s*/)[0];return r.push(`snip = SnippetUtil("${xp(a)}", ${o}, ${s}, context)`),r}async function Mc(n,e){try{await n.command(`pyx ${Iue(e.join(` +`))}`)}catch(t){let i=new Error(t.message);throw i.stack=`Error on execute python code: +${e.join(` +`)} +`+t.stack,i}}function Cp(n){let e=Object.keys(n);if(e.length==0)return"t = ()";let t=Math.max.apply(null,e.map(r=>Number(r))),i=new Array(t).fill('""');for(let[r,o]of Object.entries(n))i[r]=`"${xp(o)}"`;return`t = (${i.join(",")},)`}function Iue(n,e=!1){if(!vi&&e===!1)return n;let t=["import traceback, vim","vim.vars['errmsg'] = ''","try:"];return t.push(...n.split(` +`).map(i=>" "+i)),t.push("except Exception as e:"),t.push(" vim.vars['errmsg'] = traceback.format_exc()"),t.join(` +`)}function xp(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\t/g,"\\t").replace(/\n/g,"\\n")}function mX(n){if(n.indexOf("\\z")!==-1)throw new Error("pattern \\z not supported");if(n.indexOf("(?s)")!==-1)throw new Error("pattern (?s) not supported");if(n.indexOf("(?x)")!==-1)throw new Error("pattern (?x) not supported");if(n.indexOf(` +`)!==-1)throw new Error("pattern \\n not supported");if(Fue.test(n))throw new Error("pattern (?id/name)yes-pattern|no-pattern not supported");return n.replace(Aue,(e,t)=>e.startsWith("(?#")?"":e.startsWith("(?P<")?"(?"+e.slice(3):e.startsWith("(?P=")?`\\k<${t}>`:"^")}var gX,Lue,Fue,Mue,jue,Oue,Aue,pR=D(()=>{"use strict";gX=require("child_process");Yt();de();fe();Lue=/\\A/,Fue=/\(\?\(\w+\).+\|/,Mue=/\(\?#.*?\)/,jue=/\(\?P<\w+>.*?\)/,Oue=/\(\?P=(\w+)\)/,Aue=new RegExp(`${Mue.source}|${Lue.source}|${jue.source}|${Oue.source}`,"g")});function yX(n,e){let t=[...n];for(;t.length>0;){let i=t.shift();if(!e(i))break;t.unshift(...i.children)}}function que(n,e=[]){let t="",i=n.length,r=0,o=!1,s=!1;for(;r{"use strict";xe();te();Re();gg();de();fe();pR();Nue=Z("snippets-parser"),bX=["VISUAL","YANK","UUID"],Hue=["d","g","i","m","s","u","y"],eo=class{static isDigitCharacter(e){return e>=48&&e<=57}static isVariableCharacter(e){return e===95||e>=97&&e<=122||e>=65&&e<=90}constructor(){this.text("")}text(e){this.value=e,this.pos=0}tokenText(e){return this.value.substr(e.pos,e.len)}next(){if(this.pos>=this.value.length)return{type:14,pos:this.pos,len:0};let e=this.pos,t=0,i=this.value.charCodeAt(e),r;if(r=eo._table[i],typeof r=="number")return this.pos+=1,{type:r,pos:e,len:1};if(eo.isDigitCharacter(i)){r=8;do t+=1,i=this.value.charCodeAt(e+t);while(eo.isDigitCharacter(i));return this.pos+=t,{type:r,pos:e,len:t}}if(eo.isVariableCharacter(i)){r=9;do i=this.value.charCodeAt(e+ ++t);while(eo.isVariableCharacter(i)||eo.isDigitCharacter(i));return this.pos+=t,{type:r,pos:e,len:t}}r=10;do t+=1,i=this.value.charCodeAt(e+t);while(!isNaN(i)&&typeof eo._table[i]>"u"&&!eo.isDigitCharacter(i)&&!eo.isVariableCharacter(i));return this.pos+=t,{type:r,pos:e,len:t}}},rw=eo;rw._table={[36]:0,[58]:1,[44]:2,[123]:3,[125]:4,[92]:5,[47]:6,[124]:7,[43]:11,[45]:12,[63]:13,[40]:15,[41]:16,[96]:17,[33]:18};To=class{constructor(){this._children=[]}appendChild(e){return e instanceof Mt&&this._children[this._children.length-1]instanceof Mt?this._children[this._children.length-1].value+=e.value:(e.parent=this,this._children.push(e)),this}setOnlyChild(e){e.parent=this,this._children=[e]}replaceChildren(e){for(let t of e)t.parent=this;this._children=e}get children(){return this._children}get snippet(){let e=this;for(;;){if(!e)return;if(e instanceof Ac)return e;e=e.parent}}toString(){return this.children.reduce((e,t)=>e+t.toString(),"")}len(){return 0}},Mt=class extends To{constructor(t){super();this.value=t}static escape(t){return t.replace(/\$|}|\\/g,"\\$&")}toString(){return this.value}toTextmateString(){return Mt.escape(this.value)}len(){return this.value.length}clone(){return new Mt(this.value)}},Do=class extends To{constructor(t,i,r){super();this.code=t;this.kind=i;this._value="";this._related=[];if(i==="python"){let{_related:o}=this,s,a=/\bt\[(\d+)\]/g;for(;s=a.exec(t),s!=null;){let l=parseInt(s[1],10);o.includes(l)||o.push(l)}}typeof r=="string"&&(this._value=r)}get related(){return this._related}update(t){if(this.kind!=="python")return;let i=new Set;this.code=this.code.replace(/\bt\[(\d+)\]/g,(r,o)=>{let s=Number(o),a=t.has(s)?t.get(s):s;return i.add(a),`t[${a}]`}),this._related=Array.from(i)}get index(){if(this.parent instanceof kt)return this.parent.index}async resolve(t){if(!this.code.length)return;let i=await pX(t,this.kind,this.code,Ie(this._value,""));i!=null&&(this._value=i)}len(){return this._value.length}toString(){return this._value}get value(){return this._value}toTextmateString(){let t="";return this.kind=="python"?t="!p ":this.kind=="shell"?t="":this.kind=="vim"&&(t="!v "),"`"+t+this.code+"`"}clone(){return new Do(this.code,this.kind,this.value)}},ow=class extends To{},kt=class extends ow{constructor(t){super();this.index=t;this.primary=!1}get isFinalTabstop(){return this.index===0}get choice(){return this._children.length===1&&this._children[0]instanceof jc?this._children[0]:void 0}toTextmateString(){let t="";return this.transform&&(t=this.transform.toTextmateString()),this.children.length===0&&!this.transform?`$${this.index}`:this.children.length===0||this.children.length==1&&this.children[0].toTextmateString()==""?`\${${this.index}${t}}`:this.choice?`\${${this.index}|${this.choice.toTextmateString()}|${t}}`:`\${${this.index}:${this.children.map(i=>i.toTextmateString()).join("")}${t}}`}clone(){let t=new kt(this.index);return this.transform&&(t.transform=this.transform.clone()),t._children=this.children.map(i=>i.clone()),t}},jc=class extends To{constructor(){super(...arguments);this.options=[]}appendChild(t){return t instanceof Mt&&(t.parent=this,this.options.push(t)),this}toString(){return this.options[0].value}toTextmateString(){return this.options.map(t=>t.value.replace(/\||,/g,"\\$&")).join(",")}len(){return this.options[0].len()}clone(){let t=new jc;for(let i of this.options)t.appendChild(i);return t}},Sp=class extends To{constructor(){super(...arguments);this.ascii=!1;this.ultisnip=!1}resolve(t){let i=!1,r=t.replace(this.regexp,(...o)=>(i=!0,this._replace(o.slice(0,-2))));return!i&&this._children.some(o=>o instanceof zn&&Boolean(o.elseValue))&&(r=this._replace([])),r}_replace(t){let i="",r=[];for(let o of this._children)if(o instanceof zn){let s=o.resolve(t[o.index]||"");if(this.ultisnip&&s.indexOf("\\")!==-1){let a=i.length;r.push(...hZ(s,"\\").map(l=>l+a))}i+=s}else o instanceof Oc?i+=o.resolve(t[o.index]):i+=o.toString();return this.ascii&&(i=za(i)),this.ultisnip?que(i,r):i}toString(){return""}toTextmateString(){let t=this.children.map(i=>i.toTextmateString()).join("");return this.ultisnip&&(t=t.replace(/\\\\(\w)/g,(i,r)=>["u","l","U","L","E","n","t"].includes(r)?"\\"+r:i)),`/${this.regexp.source}/${t}/${(this.regexp.ignoreCase?"i":"")+(this.regexp.global?"g":"")}`}clone(){let t=new Sp;return t.regexp=new RegExp(this.regexp.source,(this.regexp.ignoreCase?"i":"")+(this.regexp.global?"g":"")),t._children=this.children.map(i=>i.clone()),t}},Oc=class extends To{constructor(t,i,r){super();this.index=t;this.ifValue=i;this.elseValue=r}resolve(t){return t?this.ifValue:this.elseValue}toTextmateString(){return"(?"+this.index+":"+this.ifValue+(this.elseValue?":"+this.elseValue:"")+")"}clone(){return new Oc(this.index,this.ifValue,this.elseValue)}},zn=class extends To{constructor(t,i,r,o){super();this.index=t;this.shorthandName=i;this.ifValue=r;this.elseValue=o}resolve(t){return this.shorthandName==="upcase"?t?t.toLocaleUpperCase():"":this.shorthandName==="downcase"?t?t.toLocaleLowerCase():"":this.shorthandName==="capitalize"?t?t[0].toLocaleUpperCase()+t.substr(1):"":this.shorthandName==="pascalcase"?t?this._toPascalCase(t):"":Boolean(t)&&typeof this.ifValue=="string"?this.ifValue:!t&&typeof this.elseValue=="string"?this.elseValue:t||""}_toPascalCase(t){let i=t.match(/[a-z]+/gi);return i?i.map(r=>r.charAt(0).toUpperCase()+r.substr(1).toLowerCase()).join(""):t}toTextmateString(){let t="${";return t+=this.index,this.shorthandName?t+=`:/${this.shorthandName}`:this.ifValue&&this.elseValue?t+=`:?${this.ifValue}:${this.elseValue}`:this.ifValue?t+=`:+${this.ifValue}`:this.elseValue&&(t+=`:-${this.elseValue}`),t+="}",t}clone(){return new zn(this.index,this.shorthandName,this.ifValue,this.elseValue)}},to=class extends ow{constructor(t,i=!1){super();this.name=t;this._resolved=i}get resolved(){return this._resolved}async resolve(t){let i=await t.resolve(this);if(this._resolved=!0,i&&i.includes(` +`)){let r="";this.snippet.walk(u=>{if(u==this)return!1;if(u instanceof Mt){let c=u.toString().split(/\r?\n/);r=c[c.length-1].match(/^\s*/)[0]}return!0});let o=i.split(` +`),a=o.filter(u=>u.length>0).map(u=>u.match(/^\s*/)[0]).reduce((u,c)=>uc==0||u.length==0||!u.startsWith(" ".repeat(a))?u:r+u.slice(a)).join(` +`)}return this.transform&&(i=this.transform.resolve(oe(i))),i!=null?(this._children=[new Mt(i.toString())],!0):!1}toTextmateString(){let t="";return this.transform&&(t=this.transform.toTextmateString()),this.children.length===0?`\${${this.name}${t}}`:`\${${this.name}:${this.children.map(i=>i.toTextmateString()).join("")}${t}}`}clone(){let t=new to(this.name,this.resolved);return this.transform&&(t.transform=this.transform.clone()),t._children=this.children.map(i=>i.clone()),t}};Ac=class extends To{constructor(t){super();this.ultisnip=t===!0}get hasPython(){return this.ultisnip?this.pyBlocks.length>0:!1}get hasCodeBlock(){if(!this.ultisnip)return!1;let{pyBlocks:t,otherBlocks:i}=this;return t.length>0||i.length>0}get values(){if(this._values)return this._values;let t={},i=0;this.placeholders.forEach(r=>{i=Math.max(r.index,i),r.transform==null&&(r.primary||t[r.index]===void 0)&&(t[r.index]=r.toString())});for(let r=0;r<=i;r++)t[r]===void 0&&(t[r]="");return this._values=t,t}get orderedPyIndexBlocks(){let t=[],i=this.pyBlocks.filter(a=>typeof a.index=="number");if(i.length===0)return t;let r=i.map(a=>a.index),o=[],s=a=>{let{related:l}=a;return l.length==0||l.every(u=>!r.includes(u)||o.includes(u))?(o.push(a.index),t.push(a),!0):!1};for(;i.length>0;){let a=!1;for(let l of i)s(l)&&(a=!0);if(!a)break;i=i.filter(l=>!o.includes(l.index))}return t}async evalCodeBlocks(t,i){let{pyBlocks:r,otherBlocks:o}=this;if(await Promise.all(o.map(s=>{let a=s.value;return s.resolve(t).then(()=>{s.parent instanceof kt&&a!==s.value&&this.onPlaceholderUpdate(s.parent)})})),r.length){let s=Cp(this.values);await Mc(t,[...i,s]);for(let l of r){let u=l.value;await l.resolve(t),u!==l.value&&l.parent instanceof kt&&(this.onPlaceholderUpdate(l.parent),await Mc(t,[Cp(this.values)]))}for(let l of this.orderedPyIndexBlocks)await this.updatePyIndexBlock(t,l);let a=r.filter(l=>l.index===void 0&&l.related.length>0);for(let l of a)await l.resolve(t)}}async updatePythonCodes(t,i){let r;if(i instanceof kt)r=i.index;else{for(;i.parent;){if(i instanceof kt){r=i.index;break}i=i.parent}if(r===void 0)return}let o=this.getDependentPyIndexBlocks(r);await Mc(t,[Cp(this.values)]);for(let a of o)await this.updatePyIndexBlock(t,a);let s=this.pyBlocks.filter(a=>a.index===void 0&&a.related.length>0);for(let a of s)await a.resolve(t)}getDependentPyIndexBlocks(t){let i=[],r=[],o=this.pyBlocks.filter(a=>typeof a.index=="number"),s=a=>{let l=o.filter(u=>!r.includes(u.index)&&u.related.includes(a));l.length>0&&(i.push(...l),l.forEach(u=>{s(u.index)}))};return s(t),i}async updatePyIndexBlock(t,i){let r=i.value;await i.resolve(t),r!==i.value&&(i.parent instanceof kt&&this.onPlaceholderUpdate(i.parent),await Mc(t,[Cp(this.values)]))}get placeholderInfo(){if(!this._placeholders){let t=[],i=[],r=[],o=[];this.walk(s=>{if(s instanceof kt)o.push(s);else if(s instanceof to){let a=s.name.charCodeAt(0);(a<65||a>90)&&t.push(s)}else s instanceof Do&&(s.kind==="python"?i.push(s):r.push(s));return!0}),this._placeholders={placeholders:o,pyBlocks:i,otherBlocks:r,variables:t}}return this._placeholders}get variables(){return this.placeholderInfo.variables}get placeholders(){return this.placeholderInfo.placeholders}get pyBlocks(){return this.placeholderInfo.pyBlocks}get otherBlocks(){return this.placeholderInfo.otherBlocks}get maxIndexNumber(){let{placeholders:t}=this;return t.reduce((i,r)=>Math.max(i,r.index),0)}get first(){let{placeholders:t,variables:i}=this,[r,o]=lZ(t.filter(s=>!s.transform),s=>s.index!==0);if(r.length){let s=Math.min.apply(null,r.map(l=>l.index)),a=r.filter(l=>l.index==s);return a.find(l=>l.primary)??a[0]}return i.length?i[0]:o.find(s=>s.primary)??o[0]}insertSnippet(t,i,r,o){let s=i instanceof kt?i.index:this.maxIndexNumber+1,[a,l]=r,u=o?nw(o):void 0,c=new ds(!!o,u).parse(t,!0),d=c.maxIndexNumber+1,h=new Map;for(let b of c.placeholders){let v=b.index;b.isFinalTabstop?b.index=d+s:b.index=b.index+s,h.set(v,b.index)}o&&c.pyBlocks.forEach(b=>{b.update(h)});let g=new Map;this.walk(b=>{if(b instanceof kt&&b.index>s){let v=b.index;b.index=b.index+d,g.set(v,b.index)}return!0}),this.hasPython&&this.walk(b=>(b instanceof Do&&b.update(g),!0));let f=c.first,m=c.children.slice();return a&&m.unshift(new Mt(a)),l&&m.push(new Mt(l)),this.replace(i,m),f}async update(t,i,r){this.resetMarker(i,r),this.hasPython&&await this.updatePythonCodes(t,i)}deleteText(t,i){let r=0,o,s=t+i,a=0;if(this.walk(g=>{let f=g.len();return g instanceof Mt&&t>=r&&r+f>=s?(o=g,a=t-r,!1):(r+=f,!0)}),!o)return!1;let l=o.parent,u=o.value,c=u.slice(0,a)+u.slice(a+i),d=l.children.slice(),h=d.indexOf(o);return d.splice(h,1,new Mt(c)),l.replaceChildren(d),!0}resetMarker(t,i){let r;t instanceof kt?r=this.placeholders.filter(o=>o.index==t.index):r=this.variables.filter(o=>o.name==t.name);for(let o of r){let s=o.transform?o.transform.resolve(i):i;o.setOnlyChild(new Mt(s||""))}this.synchronizeParents(r),this.reset()}onPlaceholderUpdate(t){let i=t.toString(),r;t instanceof kt?(this.values[t.index]=i,r=this.placeholders.filter(o=>o.index==t.index)):r=this.variables.filter(o=>o.name==t.name);for(let o of r){if(o===t)continue;let s=o.transform?o.transform.resolve(i):i;o.setOnlyChild(new Mt(oe(s)))}this.synchronizeParents(r)}synchronizeParents(t){let i=[];t.forEach(r=>{let o=r.parent;o instanceof kt&&!i.includes(o)&&i.push(o)}),i.forEach(r=>{this.onPlaceholderUpdate(r)})}offset(t){let i=0,r=!1;return this.walk(o=>o===t?(r=!0,!1):(i+=o.len(),!0)),r?i:-1}fullLen(t){let i=0;return yX([t],r=>(i+=r.len(),!0)),i}getTextBefore(t,i){let r="",o=s=>{let a=s.parent;if(!a)return;let l="";for(let u of a.children){if(u===s)break;l=l+u.toString()}r=l+r,a!=i&&o(a)};return o(t),r}enclosingPlaceholders(t){let i=[],{parent:r}=t;for(;r;)r instanceof kt&&i.push(r),r=r.parent;return i}async resolveVariables(t){let i=[];this.walk(r=>(r instanceof to&&!r.resolved&&i.push(r),!0)),i.length&&(await Promise.all(i.map(r=>r.resolve(t))),this.synchronizeParents(i))}appendChild(t){return this.reset(),super.appendChild(t)}replace(t,i){t.replaceChildren(i),(t instanceof kt||t instanceof to)&&this.onPlaceholderUpdate(t),this.reset()}reset(){this._placeholders=void 0,this._values=void 0}toTextmateString(){return this.children.reduce((t,i)=>t+i.toTextmateString(),"")}clone(){let t=new Ac(this.ultisnip);return t._children=this.children.map(i=>i.clone()),t}walk(t){yX(this.children,t)}},ds=class{constructor(e,t){this.ultisnip=e;this.matchCode=t;this._scanner=new rw}static escape(e){return e.replace(/\$|}|\\/g,"\\$&")}static isPlainText(e){let t=new ds().parse(e.replace(/\$0$/,""),!1);return t.children.length==1&&t.children[0]instanceof Mt}text(e){return this.parse(e,!1).toString()}parse(e,t){this._scanner.text(e),this._token=this._scanner.next();let i=new Ac(this.ultisnip);for(;this._parse(i););let r=new Map,o=[],s=[],a=!1;i.walk(c=>(c instanceof kt&&(c.index==0&&(a=!0),c.children.some(d=>d instanceof kt)?s.push(c):!r.has(c.index)&&c.children.length>0?(c.primary=!0,r.set(c.index,c.toString())):o.push(c)),!0));let l=s.map(c=>c.index);for(let c of o)if(r.has(c.index)){let d=r.get(c.index),h=new Mt(c.transform?c.transform.resolve(d):d);c.setOnlyChild(h)}else if(!l.includes(c.index))if(c.transform){let d=new Mt(c.transform.resolve(""));c.setOnlyChild(d)}else c.primary=!0,r.set(c.index,"");let u=()=>{let c=new Set;for(let d of s)if(d.children.every(h=>!(h instanceof kt)||r.has(h.index))){let h=d.toString();r.set(d.index,h);for(let g of o.filter(f=>f.index==d.index)){let f=new Mt(g.transform?g.transform.resolve(h):h);g.setOnlyChild(f)}c.add(d.index)}s=s.filter(d=>!c.has(d.index)),!(s.length==0||!c.size)&&u()};return u(),!a&&t&&i.appendChild(new kt(0)),i}_accept(e,t){if(e===void 0||this._token.type===e){let i=t?this._scanner.tokenText(this._token):!0;return this._token=this._scanner.next(),i}return!1}_backTo(e){return this._scanner.pos=e.pos+e.len,this._token=e,!1}_until(e,t=!1){if(this._token.type===14)return!1;let i=this._token,r;for(;this._token.type!==e||t&&r&&r.type===5;)if(t&&(r=this._token),this._token=this._scanner.next(),this._token.type===14)return!1;let o=this._scanner.value.substring(i.pos,this._token.pos);return this._token=this._scanner.next(),o}_parse(e){return this._parseEscaped(e)||this._parseCodeBlock(e)||this._parseTabstopOrVariableName(e)||this._parseComplexPlaceholder(e)||this._parseComplexVariable(e)||this._parseAnything(e)}_parseEscaped(e){let t;return(t=this._accept(5,!0))?(t=this._accept(0,!0)||this._accept(4,!0)||this._accept(5,!0)||this.ultisnip&&this._accept(3,!0)||this.ultisnip&&this._accept(17,!0)||t,e.appendChild(new Mt(t)),!0):!1}_parseTabstopOrVariableName(e){let t,i=this._token;return this._accept(0)&&(t=this._accept(9,!0)||this._accept(8,!0))?(/^\d+$/.test(t)?e.appendChild(new kt(Number(t))):this.ultisnip&&!bX.includes(t)?e.appendChild(new Mt("$"+t)):e.appendChild(new to(t)),!0):this._backTo(i)}_parseComplexPlaceholder(e){let t,i=this._token;if(!(this._accept(0)&&this._accept(3)&&(t=this._accept(8,!0))))return this._backTo(i);let o=new kt(Number(t));if(this._accept(1))for(;;){if(this._accept(4))return e.appendChild(o),!0;if(!this._parse(o))return e.appendChild(new Mt("${"+t+":")),o.children.forEach(e.appendChild,e),!0}else if(o.index>0&&this._accept(7)){let s=new jc;for(;;){if(this._parseChoiceElement(s)){if(this._accept(2))continue;if(this._accept(7)&&(o.appendChild(s),this._accept(4)))return e.appendChild(o),!0}return this._backTo(i),!1}}else return this._accept(6)?this._parseTransform(o)?(e.appendChild(o),!0):(this._backTo(i),!1):this._accept(4)?(e.appendChild(o),!0):this._backTo(i)}_parseChoiceElement(e){let t=this._token,i=[];for(;!(this._token.type===2||this._token.type===7);){let r;if((r=this._accept(5,!0))?r=this._accept(2,!0)||this._accept(7,!0)||this._accept(5,!0)||r:r=this._accept(void 0,!0),!r)return this._backTo(t),!1;i.push(r)}return i.length===0?(this._backTo(t),!1):(e.appendChild(new Mt(i.join(""))),!0)}_parseComplexVariable(e){let t,i=this._token;if(!(this._accept(0)&&this._accept(3)&&(t=this._accept(9,!0))))return this._backTo(i);if(this.ultisnip&&!bX.includes(t))return this._backTo(i);let o=new to(t);if(this._accept(1))for(;;){if(this._accept(4))return e.appendChild(o),!0;if(!this._parse(o))return e.appendChild(new Mt("${"+t+":")),o.children.forEach(e.appendChild,e),!0}else return this._accept(6)?this._parseTransform(o)?(e.appendChild(o),!0):(this._backTo(i),!1):this._accept(4)?(e.appendChild(o),!0):this._backTo(i)}_parseTransform(e){let t=new Sp;t.ultisnip=this.ultisnip===!0;let i="",r="";for(;!this._accept(6);){let s;if(s=this._accept(5,!0)){s=this._accept(6,!0)||s,i+=s;continue}if(this._token.type!==14){i+=this._accept(void 0,!0);continue}return!1}for(;!this._accept(6);){let s;if(s=this._accept(5,!0)){s=this._accept(5,!0)||this._accept(6,!0)||s,t.appendChild(new Mt(s));continue}if(!(this._parseFormatString(t)||this._parseConditionString(t)||this._parseAnything(t)))return!1}let o=!1;for(;!this._accept(4);){if(this._token.type!==14){let s=this._accept(void 0,!0);s=="a"?o=!0:(Hue.includes(s)||Nue.error(`Unknown regex option: ${s}`),r+=s);continue}return!1}try{o&&(t.ascii=!0),this.ultisnip&&(i=mX(i)),t.regexp=new RegExp(i,r)}catch{return!1}return e.transform=t,!0}_parseConditionString(e){if(!this.ultisnip)return!1;let t=this._token;if(!this._accept(15))return!1;if(!this._accept(13))return this._backTo(t),!1;let i=this._accept(8,!0);if(!i)return this._backTo(t),!1;if(!this._accept(1))return this._backTo(t),!1;let r=this._until(16,!0);if(r){let o=0;for(;o!/^\s*$/.test(u)),!s.length)return!0;let a=s[0].match(/^\s*/)[0];a.length&&s.every(u=>u.startsWith(a))&&(s=s.map(u=>u.slice(a.length))),a==" "&&s[0].startsWith(a)&&(s[0]=s[0].slice(1));let l=new Do(o+s.join(` +`),"python");e.appendChild(l)}return!0}}return this._backTo(t),!1}_parseAnything(e){if(this._token.type!==14){let t=this._scanner.tokenText(this._token);return e.appendChild(new Mt(t)),this._accept(void 0),!0}return!1}},Bue=[":","(",")","{","}"]});var Yue,Dp,Tp,fR=D(()=>{"use strict";Dp=class{constructor(){this[Yue]="LinkedMap";this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){var e;return(e=this._head)==null?void 0:e.value}get last(){var e;return(e=this._tail)==null?void 0:e.value}has(e){return this._map.has(e)}get(e,t=0){let i=this._map.get(e);if(!!i)return t!==0&&this.touch(i,t),i.value}set(e,t,i=0){let r=this._map.get(e);if(r)r.value=t,i!==0&&this.touch(r,i);else{switch(r={key:e,value:t,next:void 0,previous:void 0},i){case 0:this.addItemLast(r);break;case 1:this.addItemFirst(r);break;case 2:this.addItemLast(r);break;default:this.addItemLast(r);break}this._map.set(e,r),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){let t=this._map.get(e);if(!!t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){let i=this._state,r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==i)throw new Error("LinkedMap got modified during iteration.");r=r.next}}keys(){let e=this,t=this._state,i=this._head,r={[Symbol.iterator](){return r},next(){if(e._state!==t)throw new Error("LinkedMap got modified during iteration.");if(i){let o={value:i.key,done:!1};return i=i.next,o}else return{value:void 0,done:!0}}};return r}values(){let e=this,t=this._state,i=this._head,r={[Symbol.iterator](){return r},next(){if(e._state!==t)throw new Error("LinkedMap got modified during iteration.");if(i){let o={value:i.value,done:!1};return i=i.next,o}else return{value:void 0,done:!0}}};return r}entries(){let e=this,t=this._state,i=this._head,r={[Symbol.iterator](){return r},next(){if(e._state!==t)throw new Error("LinkedMap got modified during iteration.");if(i){let o={value:[i.key,i.value],done:!1};return i=i.next,o}else return{value:void 0,done:!0}}};return r}[(Yue=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e===0){this.clear();return}let t=this._head,i=this.size;for(;t&&i>e;)this._map.delete(t.key),t=t.next,i--;this._head=t,this._size=i,t&&(t.previous=void 0),this._state++}addItemFirst(e){!this._head&&!this._tail?this._tail=e:(e.next=this._head,this._head.previous=e),this._head=e,this._state++}addItemLast(e){!this._head&&!this._tail?this._head=e:(e.previous=this._tail,this._tail.next=e),this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head)e.next.previous=void 0,this._head=e.next;else if(e===this._tail)e.previous.next=void 0,this._tail=e.previous;else{let t=e.next,i=e.previous;t.previous=i,i.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!(t!==1&&t!==2))if(t===1){if(e===this._head)return;let i=e.next,r=e.previous;e===this._tail?(r.next=void 0,this._tail=r):(i.previous=r,r.next=i),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else{if(e===this._tail)return;let i=e.next,r=e.previous;e===this._head?(i.previous=void 0,this._head=i):(i.previous=r,r.next=i),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}toJSON(){let e=[];return this.forEach((t,i)=>{e.push([i,t])}),e}fromJSON(e){this.clear();for(let[t,i]of e)this.set(t,i)}},Tp=class extends Dp{constructor(t,i=1){super();this._limit=t,this._ratio=Math.min(Math.max(0,i),1)}get limit(){return this._limit}set limit(t){this._limit=t,this.checkTrim()}get ratio(){return this._ratio}set ratio(t){this._ratio=Math.min(Math.max(0,t),1),this.checkTrim()}get(t,i=2){return super.get(t,i)}peek(t){return super.get(t,0)}set(t,i){return super.set(t,i,2),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}}});function DX(n){return n.length>0&&n.charCodeAt(0){try{return new RegExp(t).test(e)}catch{return!1}})}function EX(n){return new Map([[ie.Text,n.text??"v"],[ie.Method,n.method??"f"],[ie.Function,n.function??"f"],[ie.Constructor,typeof n.constructor=="function"?"f":n["constructor"]??""],[ie.Field,n.field??"m"],[ie.Variable,n.variable??"v"],[ie.Class,n.class??"C"],[ie.Interface,n.interface??"I"],[ie.Module,n.module??"M"],[ie.Property,n.property??"m"],[ie.Unit,n.unit??"U"],[ie.Value,n.value??"v"],[ie.Enum,n.enum??"E"],[ie.Keyword,n.keyword??"k"],[ie.Snippet,n.snippet??"S"],[ie.Color,n.color??"v"],[ie.File,n.file??"F"],[ie.Reference,n.reference??"r"],[ie.Folder,n.folder??"F"],[ie.EnumMember,n.enumMember??"m"],[ie.Constant,n.constant??"v"],[ie.Struct,n.struct??"S"],[ie.Event,n.event??"E"],[ie.Operator,n.operator??"O"],[ie.TypeParameter,n.typeParameter??"T"]])}function IX(n,e,t,i){let{pre:r}=t;if(r.length===0||r[r.length-1]===" "||r.length=0;o--){let s=e.charCodeAt(o);if(!Xue(n,s,t)||r!==void 0&&!BP(r,s))break;i+=1,r=s}return i==0?"":e.slice(-i)}function Xue(n,e,t){return!(!n.isKeywordCode(e)||Xy(e)||t&&e>=255)}function FX(n,e){let{filterText:t,abbr:i}=e,r=i.indexOf(t);if(r==-1)return-1;let o=r==0?0:nt(i,r);return n+o}function Gue(n){return n?!n.detail&&!n.description:!0}function kp(n,e){return(n.insertTextFormat??e.insertTextFormat)===hl.Snippet}function zue(n,e){return kp(n,e)||!re(n.additionalTextEdits)}function MX(n,e){for(let t=0;tt&&(o.start.character=t),o}function CX(n){let e=n.filterText,t=n.source.name,i=n.kind??"";return`${e}|${t}|${i}`}var SX,Zue,vX,Jue,wX,xX,$ue,aw,lw,jl=D(()=>{"use strict";ae();qP();sw();Re();gg();Yt();Xe();fR();de();Be();fe();pa();SX=[10,13],Zue="$",vX="?",Jue=1114111,wX=100,xX="CocSymbolDefault",$ue={[ie.Text]:"CocSymbolText",[ie.Method]:"CocSymbolMethod",[ie.Function]:"CocSymbolFunction",[ie.Constructor]:"CocSymbolConstructor",[ie.Field]:"CocSymbolField",[ie.Variable]:"CocSymbolVariable",[ie.Class]:"CocSymbolClass",[ie.Interface]:"CocSymbolInterface",[ie.Module]:"CocSymbolModule",[ie.Property]:"CocSymbolProperty",[ie.Unit]:"CocSymbolUnit",[ie.Value]:"CocSymbolValue",[ie.Enum]:"CocSymbolEnum",[ie.Keyword]:"CocSymbolKeyword",[ie.Snippet]:"CocSymbolSnippet",[ie.Color]:"CocSymbolColor",[ie.File]:"CocSymbolFile",[ie.Reference]:"CocSymbolReference",[ie.Folder]:"CocSymbolFolder",[ie.EnumMember]:"CocSymbolEnumMember",[ie.Constant]:"CocSymbolConstant",[ie.Struct]:"CocSymbolStruct",[ie.Event]:"CocSymbolEvent",[ie.Operator]:"CocSymbolOperator",[ie.TypeParameter]:"CocSymbolTypeParameter"};aw=class{constructor(e,t,i){this.inputStart=e;this.option=t;this.opt=i;this.previousCache=new Map;this.postCache=new Map;this.minCharacter=Number.MAX_SAFE_INTEGER;this.character=i.position.character,this.inputLen=i.position.character-e}getPrevious(e){if(this.previousCache.has(e))return this.previousCache.get(e);let t=this.opt.line.slice(e,this.inputStart);return this.previousCache.set(e,t),t}getAfter(e){if(this.postCache.has(e))return this.postCache.get(e);let t=this.opt.line.slice(this.character,e);return this.postCache.set(e,t),t}fixFollow(e,t,i){if(t||i<=this.character)return e;let r=this.getAfter(i);return e.length-this.inputLen>r.length&&e.endsWith(r)?e.slice(0,-r.length):e}getDelta(e,t){if(te.source?1:-1}function AX(n){let e=n.tags||[];if(e.includes(Ji.Deprecated))return"CocDeprecatedHighlight";if(e.includes(Ji.Unnecessary))return"CocUnusedHighlight";switch(n.severity){case it.Warning:return"CocWarningHighlight";case it.Information:return"CocInfoHighlight";case it.Hint:return"CocHintHighlight";default:return"CocErrorHighlight"}}function NX(n,e){let t=[],{range:i}=e;for(let r of n){let o=r.range;if(!Tc(i,o)){if(Ge(o.start,i.end)>0){let s=Zv(o.start,e),a=Zv(o.end,e);s.line>=0&&s.character>=0&&a.line>=0&&a.character>=0&&(r.range=M.create(s,a))}t.push(r)}}return t}var wR=D(()=>{"use strict";ae();Tt();fe();wr()});var HX,BX,qX,Vue,WX,Rp,Nc,hw,YX=D(()=>{"use strict";ae();Pe();te();Re();Tt();U();We();he();wR();HX="CocDiagnostic",BX="diagnostic",qX=["CocErrorHighlight","CocWarningHighlight","CocInfoHighlight","CocHintHighlight","CocDeprecatedHighlight","CocUnusedHighlight"],Vue=pe(50,10),WX=pe("ale#other_source#ShowResults","MockAleResults"),hw=class{constructor(e,t){this.nvim=e;this.doc=t;this.diagnosticsMap=new Map;this._disposed=!1;this._dirties=new Set;this._refreshing=!1;this._onDidRefresh=new p.Emitter;this.onDidRefresh=this._onDidRefresh.event;this.loadConfiguration();let i,r=()=>{clearTimeout(i),this._refreshing=!0,i=setTimeout(()=>{this._refreshing=!1,this._autoRefresh&&this._refresh(!0)},Vue)};r.clear=()=>{this._refreshing=!1,clearTimeout(i)},this.refreshHighlights=r}get _autoRefresh(){return this.config.enable&&this.config.autoRefresh&&this.dirty&&!this.doc.hasChanged}get config(){return this._config}loadConfiguration(){let e=y.getConfiguration("diagnostic",this.doc),t=this._config&&e.enable!=this._config.enable;this._config={enable:e.get("enable",!0),floatConfig:e.get("floatConfig",{}),messageTarget:e.get("messageTarget","float"),enableHighlightLineNumber:e.get("enableHighlightLineNumber",!0),highlightLimit:e.get("highlightLimit",1e3),highlightPriority:e.get("highlightPriority"),autoRefresh:e.get("autoRefresh",!0),checkCurrentLine:e.get("checkCurrentLine",!1),enableSign:y.env.sign&&e.get("enableSign",!0),locationlistUpdate:e.get("locationlistUpdate",!0),enableMessage:e.get("enableMessage","always"),virtualText:e.get("virtualText",!1),virtualTextAlign:e.get("virtualTextAlign","after"),virtualTextWinCol:e.get("virtualTextWinCol",null),virtualTextCurrentLineOnly:e.get("virtualTextCurrentLineOnly"),virtualTextPrefix:e.get("virtualTextPrefix"," "),virtualTextFormat:e.get("virtualTextFormat","%message"),virtualTextLimitInOneLine:e.get("virtualTextLimitInOneLine",999),virtualTextLineSeparator:e.get("virtualTextLineSeparator"," \\ "),virtualTextLines:e.get("virtualTextLines",3),displayByAle:e.get("displayByAle",!1),level:hs(e.get("level","hint")),locationlistLevel:hs(e.get("locationlistLevel")),signLevel:hs(e.get("signLevel")),virtualTextLevel:hs(e.get("virtualTextLevel")),messageLevel:hs(e.get("messageLevel")),signPriority:e.get("signPriority",10),refreshOnInsertMode:e.get("refreshOnInsertMode",!1),filetypeMap:e.get("filetypeMap",{}),showUnused:e.get("showUnused",!0),showDeprecated:e.get("showDeprecated",!0),format:e.get("format","[%source%code] [%severity] %message")},this._config.virtualText&&!Rp&&this.nvim.createNamespace("coc-diagnostic-virtualText").then(i=>{Rp=i}),t&&(this.config.enable?this._refresh(!1):this.clear())}async setState(e){this._config.enable!=e&&(this._config.enable=e,e?await this._refresh(!1):this.clear())}get dirty(){return this._dirties.size>0}get bufnr(){return this.doc.bufnr}get uri(){return this.doc.uri}onChange(e){let t=e.contentChanges;if(t.length>0){let i=Ye.replace(t[0].range,t[0].text);for(let[r,o]of this.diagnosticsMap.entries()){let s=NX(o,i);this.diagnosticsMap.set(r,s)}this._dirties=new Set(this.diagnosticsMap.keys())}!this.config.autoRefresh||this.refreshHighlights()}onTextChange(){this._dirties=new Set(this.diagnosticsMap.keys()),this.refreshHighlights.clear()}get displayByAle(){return this._config.displayByAle}clearHighlight(e){this.buffer.clearNamespace(BX+e)}clearSigns(e){this.buffer.unplaceSign({group:HX+e})}get diagnostics(){let e=[];for(let t of this.diagnosticsMap.values())e.push(...t);return e}get buffer(){return this.nvim.createBuffer(this.bufnr)}refreshAle(e,t){let i=t.map(r=>{let o=r.range;return{text:r.message,code:r.code,lnum:o.start.line+1,col:o.start.character+1,end_lnum:o.end.line+1,end_col:o.end.character,type:jX(r.severity)}});this.nvim.call(WX,[this.bufnr,"coc"+e,i],!0)}async update(e,t){let{diagnosticsMap:i}=this,r=i.get(e);if(!this._dirties.has(e)&&re(t)&&re(r))return;if(i.set(e,t),this.checkFloat(),!this.config.enable||t.length>0&&this._refreshing){this._dirties.add(e);return}let o=await this.getDiagnosticInfo(t.length===0);if(!o||o.winid==-1){this._dirties.add(e);return}let s=new Map;s.set(e,t),this.refresh(s,o)}async checkFloat(){if(y.bufnr!=this.bufnr||!Nc)return;let e=await P.getCursorPosition();this.getDiagnosticsAtPosition(e).length==0&&Nc.close()}async reset(e){this.refreshHighlights.clear();let{diagnosticsMap:t}=this;for(let i of t.keys())re(e[i])&&(e[i]=[]);for(let[i,r]of Object.entries(e))t.set(i,r);this._dirties=new Set(t.keys()),await this._refresh(!1)}async onCursorHold(e,t){if(this.config.enableMessage!=="always")return;let i=this.doc.getPosition(e,t);await this.echoMessage(!0,i)}async echoMessage(e=!1,t){let i=this.config;if(!i.enable||i.enableMessage==="never"||i.displayByAle)return!1;let r=i.messageTarget=="float",o=this.getDiagnosticsAtPosition(t);if(i.messageLevel&&(o=o.filter(s=>s.severity&&s.severity<=i.messageLevel)),r)await this.showFloat(o);else{let s=[];o.forEach(a=>{s.push(cw(i.format,a))}),s.length&&(await this.nvim.command('echo ""'),await P.echoLines(s,e))}return!0}async showVirtualTextCurrentLine(e){let{config:t}=this;return!t.virtualTextCurrentLineOnly||_.insertMode&&!t.refreshOnInsertMode||!await this.isEnabled()?!1:(this.showVirtualText(e),!0)}async showFloat(e){if(this.config.messageTarget!=="float")return!1;if(Nc||(Nc=P.createFloatFactory({modes:["n"],autoHide:!0})),e.length==0)return Nc.close(),!1;if(_.insertMode)return!1;let t=this.config,i="",r=[];if(Object.keys(t.filetypeMap).length>0){let o=this.doc.filetype,s=t.filetypeMap.default||"";i=t.filetypeMap[o]||(s=="bufferType"?o:s)}return e.forEach(o=>{var a;let s="Error";if(i==="")switch(o.severity){case it.Hint:s="Hint";break;case it.Warning:s="Warning";break;case it.Information:s="Info";break}else s=i;r.push({filetype:s,content:cw(t.format,o)}),(a=o.codeDescription)!=null&&a.href&&r.push({filetype:"txt",content:o.codeDescription.href})}),await Nc.show(r,this.config.floatConfig),!0}async getDiagnosticInfo(e){let{refreshOnInsertMode:t}=this._config,{nvim:i,bufnr:r}=this,o=!t;if(e)o=!1;else if(_.insertMode&&!t)return;return await i.call("coc#util#diagnostic_info",[r,o])}refresh(e,t){let{nvim:i,displayByAle:r}=this;for(let o of e.keys())this._dirties.delete(o);if(r){i.pauseNotification();for(let[o,s]of e.entries())this.refreshAle(o,s);i.resumeNotification(!0,!0)}else{let o=[];i.pauseNotification();for(let[s,a]of e.entries())a.length==0&&o.push(s),this.addSigns(s,a),this.updateHighlights(s,a);this.showVirtualText(t.lnum),this.updateLocationList(t.winid,t.locationlist),this.setDiagnosticInfo(),i.resumeNotification(!0,!0),o.forEach(s=>{this.diagnosticsMap.delete(s)})}this._onDidRefresh.fire(this.diagnostics)}updateLocationList(e,t){if(!this._config.locationlistUpdate||e==-1||t!=="Diagnostics of coc")return;let i=this.toLocationListItems(this.diagnostics);this.nvim.call("coc#ui#setloclist",[e,i,"r","Diagnostics of coc"],!0)}toLocationListItems(e){let{locationlistLevel:t}=this._config,i=[],r=this.doc.textDocument.lines;e.sort(dw);for(let o of e)t&&o.severity&&o.severity>t||i.push(OX(this.bufnr,o,r));return i}addSigns(e,t){let{enableSign:i,signLevel:r}=this._config;if(!i)return;let o=HX+e,s=[],a=new Map;for(let l of t){let{range:u,severity:c}=l;if(!c||r&&c>r)continue;let d=u.start.line,h=a.get(d)||[];if(h.includes(c))continue;h.push(c),a.set(d,h);let g=this._config.signPriority+4-c;s.push({name:vR(c),lnum:d+1,priority:g})}this.nvim.call("coc#ui#update_signs",[this.bufnr,o,s],!0)}setDiagnosticInfo(){let e=[0,0,0,0],t={error:0,warning:0,information:0,hint:0,lnums:e};for(let r of this.diagnosticsMap.values())for(let o of r){let s=o.range.start.line+1;switch(o.severity){case it.Warning:t.warning=t.warning+1,e[1]=e[1]?Math.min(e[1],s):s;break;case it.Information:t.information=t.information+1,e[2]=e[2]?Math.min(e[2],s):s;break;case it.Hint:t.hint=t.hint+1,e[3]=e[3]?Math.min(e[3],s):s;break;default:e[0]=e[0]?Math.min(e[0],s):s,t.error=t.error+1}}this.nvim.createBuffer(this.bufnr).setVar("coc_diagnostic_info",t,!0),this.nvim.call("coc#util#do_autocmd",["CocDiagnosticChange"],!0)}showVirtualText(e){let{_config:t}=this,{virtualText:i,virtualTextLevel:r}=t;if(!i||e<0)return;let{virtualTextPrefix:o,virtualTextLimitInOneLine:s,virtualTextCurrentLineOnly:a}=this._config,{diagnostics:l,buffer:u}=this;a&&(l=l.filter(h=>{let{start:g,end:f}=h.range;return g.line<=e-1&&f.line>=e-1})),l.sort(dw),u.clearNamespace(Rp);let c=new Map,d={text_align:t.virtualTextAlign,virt_text_win_col:t.virtualTextWinCol};for(let h=l.length-1;h>=0;h--){let g=l[h];if(r&&g.severity&&g.severity>r)continue;let{line:f}=g.range.start,m=vR(g.severity)+"VirtualText",b=g.message.split(/\n/).map(x=>x.trim()).filter(x=>x.length>0).slice(0,this._config.virtualTextLines).join(this._config.virtualTextLineSeparator),v=c.get(f)??[];v.unshift([o+cw(this._config.virtualTextFormat,{...g,message:b}),m]),c.set(f,v)}for(let[h,g]of c.entries())u.setVirtualText(Rp,h,g.slice(0,s),d)}updateHighlights(e,t){if(!t.length)this.clearHighlight(e);else{let i=this.getHighlightItems(t),r=this._config.highlightPriority;this.buffer.updateHighlights(BX+e,i,{priority:r})}}async _refresh(e){let t=await this.getDiagnosticInfo(!e);if(!t||t.winid==-1||!this.config.enable)return;let{_dirties:i}=this;if(e){let r=new Map;for(let[o,s]of this.diagnosticsMap.entries())!i.has(o)||r.set(o,s);this.refresh(r,t)}else this.refresh(this.diagnosticsMap,t)}getHighlightItems(e){let t=[];for(let i=0;ii.lnum!=r.lnum?i.lnum-r.lnum:i.colStart!=r.colStart?i.colStart-r.colStart:qX.indexOf(r.hlGroup)-qX.indexOf(i.hlGroup)),t}clear(){let{nvim:e}=this,t=Array.from(this.diagnosticsMap.keys());if(this.refreshHighlights.clear(),this._dirties.clear(),this.displayByAle)for(let i of t)this.nvim.call(WX,[this.bufnr,i,[]],!0);else{e.pauseNotification(),this.buffer.deleteVar("coc_diagnostic_info");for(let i of t)this.clearHighlight(i),this.clearSigns(i);this._config.virtualText&&this.buffer.clearNamespace(Rp),e.resumeNotification(!0,!0)}}getDiagnosticsAt(e,t){let i=[];for(let r of this.diagnosticsMap.values())t?i.push(...r.filter(o=>oU(e.line,o.range))):i.push(...r.filter(o=>Ft(e,o.range)==0));return i.sort(dw),i}getDiagnosticsAtPosition(e){let{config:t,doc:i}=this,r=this.getDiagnosticsAt(e,t.checkCurrentLine);if(t.checkCurrentLine||r.length)return r;let o=i.getline(e.line).length;return e.character+1==o&&(r=this.getDiagnosticsAt(Q.create(e.line,e.character+1),!1),r.length)||e.line===i.lineCount-1&&e.character==0&&(e=Q.create(e.line+1,0),r=this.getDiagnosticsAt(e,!0)),r}async isEnabled(){return this._disposed||!this.config.enable?!1:await this.nvim.createBuffer(this.bufnr).getVar("coc_diagnostic_disable")!=1}dispose(){this.clear(),this.diagnosticsMap.clear(),this._onDidRefresh.dispose(),this._disposed=!0}}});var ece,_p,ZX=D(()=>{"use strict";ae();Je();Re();U();he();ece=[Ji.Deprecated,Ji.Unnecessary],_p=class{constructor(e,t){this.name=e;this.onDispose=t;this.diagnosticsMap=new Map;this._onDidDiagnosticsChange=new p.Emitter;this.onDidDiagnosticsChange=this._onDidDiagnosticsChange.event}set(e,t){let i=new Map;if(Array.isArray(e))for(let r of e){let[o,s]=r,a=y.getDocument(o);o=a?a.uri:o,s==null?s=[]:s=(i.get(o)||[]).concat(s),i.set(o,s)}else{let r=y.getDocument(e),o=r?r.uri:e;i.set(o,t||[])}for(let r of i){let[o,s]=r;o=O.parse(o).toString(),s.forEach(a=>{a.range=a.range??M.create(0,0,0,0),a.message=a.message??"",a.source=a.source||this.name,!a.severity&&Array.isArray(a.tags)&&hg(a.tags,ece)&&(a.severity=it.Hint)}),this.diagnosticsMap.set(o,s),this._onDidDiagnosticsChange.fire(o)}}delete(e){this.diagnosticsMap.delete(e),this._onDidDiagnosticsChange.fire(e)}clear(){let e=Array.from(this.diagnosticsMap.keys());e=e.filter(t=>this.diagnosticsMap.get(t).length>0),this.diagnosticsMap.clear();for(let t of e)this._onDidDiagnosticsChange.fire(t)}forEach(e,t){for(let i of this.diagnosticsMap.keys()){let r=this.diagnosticsMap.get(i);e.call(t,i,r,this)}}entries(){return this.diagnosticsMap.entries()}get(e){let t=this.diagnosticsMap.get(e);return t==null?[]:t.slice()}has(e){return this.diagnosticsMap.has(e)}dispose(){this.clear(),this.onDispose&&this.onDispose(),this._onDidDiagnosticsChange.dispose()}}});var xR,ui,Hc=D(()=>{"use strict";ae();Je();Dt();Pe();te();Re();Yt();st();Tt();U();fe();We();he();YX();ZX();wR();xR=class{constructor(){this._onDidRefresh=new p.Emitter;this.onDidRefresh=this._onDidRefresh.event;this.enabled=!0;this.collections=[];this.disposables=[]}init(){V.register({id:"workspace.diagnosticRelated",execute:()=>this.jumpRelated()},!1,"jump to related locations of current diagnostic."),this.defineSigns(y.initialConfiguration.get("diagnostic")),this.buffers=y.registerBufferSync(t=>{let i=new hw(this.nvim,t);i.onDidRefresh(o=>{this._onDidRefresh.fire({diagnostics:o,uri:i.uri,bufnr:i.bufnr})});let r=this.getDiagnostics(i);return Object.keys(r).length>0&&i.config.autoRefresh&&i.reset(r),i}),y.onDidChangeConfiguration(t=>{if(this.buffers&&t.affectsConfiguration("diagnostic"))for(let i of this.buffers.items)i.loadConfiguration()},null,this.disposables);let e=y.initialConfiguration.get("diagnostic");_.on("CursorMoved",(t,i)=>{this.messageTimer&&clearTimeout(this.messageTimer),this.messageTimer=setTimeout(()=>{let r=this.buffers.getItem(t);r==null||r.dirty||Promise.allSettled([r.onCursorHold(i[0],i[1]),r.showVirtualTextCurrentLine(i[0])])},e.messageDelay)},null,this.disposables),_.on(["InsertEnter","BufEnter"],()=>{clearTimeout(this.messageTimer)},null,this.disposables),_.on("InsertLeave",t=>{let i=this.buffers.getItem(t);if(!(!i||i.config.refreshOnInsertMode))for(let r of this.buffers.items)r.refreshHighlights()},null,this.disposables),_.on("BufWinEnter",t=>{let i=this.buffers.getItem(t);i&&i.refreshHighlights()},null,this.disposables),this.checkConfigurationErrors(),y.configurations.onError(t=>{this.create("config").set(t.uri,t.diagnostics)},null,this.disposables)}checkConfigurationErrors(){let e=y.configurations.errors;if(!re(e)){let t=this.create("config");for(let[i,r]of e.entries()){let o=O.parse(i).fsPath;P.showErrorMessage(`Error detected for config file ${o}, please check diagnostics list.`),t.set(i,r)}}}defineSigns(e){let{nvim:t}=this;t.pauseNotification();for(let i of["Error","Warning","Info","Hint"]){let r=`sign define Coc${i} linehl=Coc${i}Line`,o=e[i.toLowerCase()+"Sign"];o&&(r+=` texthl=Coc${i}Sign text=${o}`),!vi&&e.enableHighlightLineNumber&&(r+=` numhl=Coc${i}Sign`),t.command(r,!0)}t.resumeNotification(!1,!0)}getItem(e){return this.buffers.getItem(e)}async setLocationlist(e){let t=y.getAttachedDocument(e),i=this.buffers.getItem(t.bufnr),r=[];for(let s of Object.values(this.getDiagnostics(i)))r.push(...s);let o=i.toLocationListItems(r);await this.nvim.call("coc#ui#setloclist",[0,o," ","Diagnostics of coc"])}create(e){let t=this.getCollectionByName(e);return t||(t=new _p(e,()=>{let i=this.collections.findIndex(r=>r==t);i!==-1&&this.collections.splice(i,1)}),this.collections.push(t),t.onDidDiagnosticsChange(i=>{var o;let r=(o=this.buffers)==null?void 0:o.getItem(i);r&&r.config.autoRefresh&&r.update(e,this.getDiagnosticsByCollection(r,t))}),t)}getSortedRanges(e,t,i){let r=this.getCollections(e),o=[],s=i?hs(i):0;for(let a of r){let l=a.get(e);s?l=l.filter(c=>c.severity==s):t&&t!(c.severity&&c.severity>t)));let u=l.map(c=>c.range);o.push(...u)}return o.sort((a,l)=>a.start.line!=l.start.line?a.start.line-l.start.line:a.start.character-l.start.character),o}getDiagnostics(e){let t={};for(let i of this.collections)!i.has(e.uri)||(t[i.name]=this.getDiagnosticsByCollection(e,i));return t}getDiagnosticsByCollection(e,t){let{level:i,showUnused:r,showDeprecated:o}=e.config,s=t.get(e.uri)??[];return s.length&&(s=s.filter(a=>{var l,u;return!(i&&a.severity&&a.severity>i||!r&&((l=a.tags)==null?void 0:l.includes(Ji.Unnecessary))||!o&&((u=a.tags)==null?void 0:u.includes(Ji.Deprecated)))}),s.sort((a,l)=>Ge(a.range.start,l.range.start))),s}getDiagnosticsInRange(e,t){let i=[];for(let r of this.collections)for(let o of r.get(e.uri)??[])Ll(o.range,t)&&i.push(o);return i}async preview(){let e=await this.getCurrentDiagnostics();if(e.length==0){this.nvim.command("pclose",!0);return}let t=[];for(let i of e){let{source:r,code:o,severity:s,message:a}=i,l=Pp(s)[0];t.push(`[${r}${o?" "+o:""}] [${l}]`),t.push(...a.split(/\r?\n/)),t.push("")}this.nvim.call("coc#ui#preview_info",[t,"txt"],!0)}async prepareJump(e){let t=await this.nvim.call("bufnr",["%"]),i=this.buffers.getItem(t);if(!i)return;let r=this.getSortedRanges(i.uri,i.config.level,e);if(re(r))return;let o=await P.getCursorPosition(),s=await this.nvim.getOption("wrapscan");return{item:i,curpos:o,wrapscan:s!=0,ranges:r}}async jumpPrevious(e){let t=await this.prepareJump(e);if(!t)return;let{curpos:i,item:r,wrapscan:o,ranges:s}=t,a;for(let l=s.length-1;l>=0;l--){let u=s[l].end;if(Ge(u,i)<0){a=s[l].start;break}}!a&&o&&(a=s[s.length-1].start),a?(await P.moveTo(a),await r.echoMessage(!1,a)):P.showWarningMessage("No more diagnostic before cursor position")}async jumpNext(e){let t=await this.prepareJump(e);if(!t)return;let{curpos:i,item:r,wrapscan:o,ranges:s}=t,a;for(let l=0;l<=s.length-1;l++){let u=s[l].start;if(Ge(u,i)>0){let c=await this.nvim.call("coc#util#valid_position",[u.line,u.character]);if((c[0]!=u.line||c[1]!=u.character)&&Ge(Q.create(c[0],c[1]),i)<=0)continue;a=Q.create(c[0],c[1]);break}}!a&&o&&(a=s[0].start),a?(await P.moveTo(a),await r.echoMessage(!1,a)):P.showWarningMessage("No more diagnostic after cursor position")}async getDiagnosticList(){let e=[],t=y.getConfiguration("diagnostic"),i=hs(t.get("level","hint"));for(let r of this.collections)for(let[o,s]of r.entries()){if(s.length==0)continue;let a=O.parse(o),l=y.getDocument(o),u=l&&l.attached?l.textDocument.lines:void 0;if(!u&&a.scheme==="file")try{let c=s.reduce((d,h)=>Math.max(h.range.end.line,d),0);u=await Qs(a.fsPath,0,c)}catch{}for(let c of s){if(c.severity&&c.severity>i)continue;let{start:d,end:h}=c.range,g={file:a.fsPath,lnum:d.line+1,end_lnum:h.line+1,col:Array.isArray(u)?nt(u[d.line]??"",d.character)+1:d.character+1,end_col:Array.isArray(u)?nt(u[h.line]??"",h.character)+1:h.character+1,code:c.code,source:c.source??r.name,message:c.message,severity:Pp(c.severity),level:c.severity??0,location:Ke.create(o,c.range)};e.push(g)}}return e.sort((r,o)=>r.level!==o.level?r.level-o.level:r.file!==o.file?r.file>o.file?1:-1:r.lnum!=o.lnum?r.lnum-o.lnum:r.col-o.col),e}async getBufferAndPosition(){let[e,t,i]=await this.nvim.eval(`[bufnr("%"),line('.'),col('.')]`),r=this.buffers.getItem(e);if(!r)return;let o=r.doc.getPosition(t,i);return[r,o]}async getCurrentDiagnostics(){let e=await this.getBufferAndPosition();if(!!e)return e[0].getDiagnosticsAtPosition(e[1])}async echoCurrentMessage(){let e=await this.getBufferAndPosition();if(!e)return;let[t,i]=e;await t.echoMessage(!1,i)}async jumpRelated(){let t=(await this.getCurrentDiagnostics()).find(r=>r.relatedInformation!=null),i=t?t.relatedInformation.map(r=>r.location):[];i.length==1?await y.jumpTo(i[0].uri,i[0].range.start):i.length>1?await y.showLocations(i):P.showWarningMessage("No related information found.")}reset(){clearTimeout(this.messageTimer),this.buffers.reset();for(let e of this.collections)e.dispose();this.collections=[]}dispose(){clearTimeout(this.messageTimer),this.buffers.dispose();for(let e of this.collections)e.dispose();this.collections=[],W(this.disposables)}get nvim(){return y.nvim}getCollectionByName(e){return this.collections.find(t=>t.name==e)}getCollections(e){return this.collections.filter(t=>t.has(e))}async toggleDiagnostic(e){this.enabled=e==null?!this.enabled:e!=0,await Promise.allSettled(this.buffers.items.map(t=>t.setState(this.enabled)))}async toggleDiagnosticBuffer(e,t){e=e??y.bufnr;let i=this.buffers.getItem(e);if(i){let r=t==null?await i.isEnabled():t==0;await this.nvim.call("setbufvar",[e,"coc_diagnostic_disable",r?1:0]),await i.setState(!r)}}async refreshBuffer(e){let t=this.buffers.getItem(e);return t?(await t.reset(this.getDiagnostics(t)),!0):!1}async refresh(e){let t;if(!e)t=this.buffers.items;else{let i=this.buffers.getItem(e);t=i?[i]:[]}for(let i of t)await this.refreshBuffer(i.uri)}},ui=new xR});function CR(n,e){if(Ke.is(e)){let{range:t,uri:i}=e;if(n.find(r=>r.uri==i&&Me(r.range,t))!=null)return;n.push(e)}else if(e&&typeof e.targetUri=="string"){let{targetUri:t,targetSelectionRange:i,targetRange:r}=e;if(n.find(o=>o.uri==t&&Me(o.range,i))!=null)return;n.push({uri:t,range:i,targetRange:r})}}var tce,_e,Et=D(()=>{"use strict";ae();xe();Be();U();he();tce=Z("provider-manager"),_e=class{constructor(){this.providers=new Set}hasProvider(e){return this.getProvider(e)!=null}addProvider(e){return this.providers.add(e),p.Disposable.create(()=>{this.providers.delete(e)})}handleResults(e,t){e.forEach(i=>{i.status==="rejected"&&tce.error(`Provider error on ${t}:`,i.reason)})}getProvider(e){let t=0,i;for(let r of this.providers){let{selector:o,priority:s}=r,a=y.match(o,e);a!=0&&(typeof s=="number"&&s>0&&(a=a+s),!(ai.id==e);return t?t.provider:null}getProviders(e){let t=Array.from(this.providers);return t=t.filter(i=>y.match(i.selector,e)>0),t.sort((i,r)=>y.match(r.selector,e)-y.match(i.selector,e))}addLocation(e,t){if(Array.isArray(t))for(let i of t)(Ke.is(i)||i&&typeof i.targetUri=="string")&&CR(e,i);else Ke.is(t)&&CR(e,t)}}});var Ep,JX=D(()=>{"use strict";rt();Et();Ep=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async prepareCallHierarchy(e,t,i){let r=this.getProvider(e);if(!r)return null;let{provider:o}=r;return await Promise.resolve(o.prepareCallHierarchy(e,t,i))}async provideCallHierarchyOutgoingCalls(e,t,i){let r=this.getProvider(e);if(!r)return null;let{provider:o}=r;return await Promise.resolve(o.provideCallHierarchyOutgoingCalls(t,i))}async provideCallHierarchyIncomingCalls(e,t,i){let r=this.getProvider(e);if(!r)return null;let{provider:o}=r;return await Promise.resolve(o.provideCallHierarchyIncomingCalls(t,i))}}});function UX(n,...e){return n=Object(n),e.forEach(t=>{if(t!=null){t=Object(t);for(let i in t){let r=n[i];(r===void 0||r===$X[i]&&!ice.call(n,i))&&(n[i]=t[i])}}}),n}function ci(n,e){let t={};for(let i of Object.keys(n))e.includes(i)||(t[i]=n[i]);return t}var $X,ice,io=D(()=>{"use strict";$X=Object.prototype,ice=$X.hasOwnProperty});function XX(n,e){return n.some(t=>e===t||e.startsWith(t+"."))}function nce(n,e){return re(n)?!0:En.is(e)?!1:XX(n,e.kind)}var Ip,GX=D(()=>{"use strict";rt();ae();Re();Xe();io();Et();Ip=class extends _e{register(e,t,i,r){return this.addProvider({id:me(),selector:e,provider:t,kinds:r,clientId:i})}async provideCodeActions(e,t,i,r){let o=this.getProviders(e),s=re(i.only)?void 0:i.only;s&&(o=o.filter(c=>!(Array.isArray(c.kinds)&&!c.kinds.some(d=>XX(s,d)))));let a=[],l=[],u=await Promise.allSettled(o.map(c=>{let{provider:d,id:h}=c;return(async()=>{let f=await Promise.resolve(d.provideCodeActions(e,t,i,r));if(!re(f)){for(let m of f)if(!(l.includes(m.title)||!nce(s,m))){if(En.is(m)){let b={title:m.title,command:m,providerId:h};a.push(b)}else a.push(Object.assign({providerId:h},m));l.push(m.title)}}})()}));return this.handleResults(u,"provideCodeActions"),a}async resolveCodeAction(e,t){if(e.edit!=null||e.providerId==null)return e;let i=this.getProviderById(e.providerId);return!i||!tt(i.resolveCodeAction)?e:await Promise.resolve(i.resolveCodeAction(ci(e,["providerId"]),t))??e}}});var Lp,zX=D(()=>{"use strict";rt();io();Et();Xe();Lp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideCodeLenses(e,t){let i=this.getProviders(e),r=[],o=await Promise.allSettled(i.map(s=>{let{provider:a,id:l}=s;return Promise.resolve(a.provideCodeLenses(e,t)).then(u=>{if(Array.isArray(u))for(let c of u)r.push(Object.assign({source:l},c))})}));return this.handleResults(o,"provideCodeLenses"),r}async resolveCodeLens(e,t){if(mh(e.command))return e;let i=this.getProviderById(e.source);if(!i||typeof i.resolveCodeLens!="function")return e;let r=await Promise.resolve(i.resolveCodeLens(ci(e,["source"]),t));return Object.assign(e,r),e}}});var Fp,KX=D(()=>{"use strict";rt();Et();Fp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideDeclaration(e,t,i){let r=this.getProviders(e),o=[],s=await Promise.allSettled(r.map(a=>Promise.resolve(a.provider.provideDeclaration(e,t,i)).then(l=>{this.addLocation(o,l)})));return this.handleResults(s,"provideDeclaration"),o}}});var Mp,QX=D(()=>{"use strict";rt();ae();Et();Mp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideDefinition(e,t,i){let r=this.getProviders(e),o=[],s=await Promise.allSettled(r.map(a=>Promise.resolve(a.provider.provideDefinition(e,t,i)).then(l=>{this.addLocation(o,l)})));return this.handleResults(s,"provideDefinition"),o}async provideDefinitionLinks(e,t,i){let r=this.getProviders(e),o=[],s=await Promise.allSettled(r.map(a=>Promise.resolve(a.provider.provideDefinition(e,t,i)).then(l=>{Array.isArray(l)&&l.forEach(u=>{pr.is(u)&&o.push(u)})})));return this.handleResults(s,"provideDefinition"),o}}});var jp,VX=D(()=>{"use strict";rt();Be();Et();jp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideDocumentColors(e,t){let i=this.getProviders(e),r=[],o=await Promise.allSettled(i.map(s=>{let{id:a}=s;return Promise.resolve(s.provider.provideDocumentColors(e,t)).then(l=>{let u=r.length==0;if(Array.isArray(l))for(let c of l)(u||!r.some(d=>Me(d.range,c.range)))&&r.push(Object.assign({source:a},c))})}));return this.handleResults(o,"provideDocumentColors"),r}async provideColorPresentations(e,t,i){let r=this.getProviders(t),{range:o,color:s}=e;for(let a of r){let l=await Promise.resolve(a.provider.provideColorPresentations(s,{document:t,range:o},i));if(l)return l}return null}}});var Op,e2=D(()=>{"use strict";rt();Et();Op=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideDocumentHighlights(e,t,i){let r=this.getProviders(e),o=null;for(let s of r)try{if(o=await Promise.resolve(s.provider.provideDocumentHighlights(e,t,i)),o!=null)break}catch(a){this.handleResults([{status:"rejected",reason:a}],"provideDocumentHighlights")}return o}}});function t2(n){return`${n.start.line},${n.start.character},${n.end.line},${n.end.character}`}var Ap,i2=D(()=>{"use strict";rt();io();Et();Ap=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideDocumentLinks(e,t){let i=this.getProviders(e);if(i.length==0)return null;let r=[],o=new Set,s=await Promise.allSettled(i.map(async a=>{let{id:l,provider:u}=a,c=await u.provideDocumentLinks(e,t);if(Array.isArray(c)){let d=r.length>0;c.forEach(h=>{if(d){let g=t2(h.range);o.has(g)||(o.add(g),r.push(Object.assign({source:l},h)))}else i.length>1&&o.add(t2(h.range)),r.push(Object.assign({source:l},h))})}}));return this.handleResults(s,"provideDocumentLinks"),r}async resolveDocumentLink(e,t){let i=this.getProviderById(e.source);if(typeof i.resolveDocumentLink=="function"){let r=await Promise.resolve(i.resolveDocumentLink(ci(e,["source"]),t));r&&Object.assign(e,r)}return e}}});function rce(n){n=n.slice().sort((i,r)=>Dc(i.location.range,r.location.range));let e=[],t=[];for(let i of n){let r={name:oe(i.name),kind:i.kind,tags:le(i.tags),detail:"",range:i.location.range,selectionRange:i.location.range};for(i.deprecated&&r.tags.push($i.Deprecated);;){if(t.length===0){t.push(r),e.push(r);break}let o=t[t.length-1];if(ti(r.range,o.range)&&!iU(o.range,r.range)){o.children=le(o.children),o.children.push(r),t.push(r);break}t.pop()}}return e}var Np,n2=D(()=>{"use strict";rt();ae();Re();Tt();fe();Et();Np=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}getMetaData(e){let t=this.getProvider(e);return t?t.provider.meta??{}:null}async provideDocumentSymbols(e,t){let i=this.getProvider(e);if(!i)return null;let r=[],o=await Promise.allSettled([i].map(s=>Promise.resolve(s.provider.provideDocumentSymbols(e,t)).then(a=>{!t.isCancellationRequested&&!re(a)&&(Js.is(a[0])?r=a:r=rce(a))})));return this.handleResults(o,"provideDocumentSymbols"),r}}});function r2(n,e){for(let t of e)if(n>=t.startLine){if(n<=t.endLine)return t;continue}else break}var Hp,o2=D(()=>{"use strict";rt();Et();Hp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideFoldingRanges(e,t,i){let r=this.getProviders(e),o=[],s=await Promise.allSettled(r.map(a=>Promise.resolve(a.provider.provideFoldingRanges(e,t,i)).then(l=>{if(Array.isArray(l)&&l.length>0){if(o.length==0)o.push(...l);else for(let u of l){let c=r2(u.startLine,o);if((c==null?void 0:c.startLine)===u.startLine)continue;let d=r2(u.endLine,o);c===d&&o.push(u)}o.sort((u,c)=>u.startLine-c.startLine)}})));return this.handleResults(s,"provideFoldingRanges"),o}}});var Bp,s2=D(()=>{"use strict";rt();Et();Bp=class extends _e{register(e,t,i){return this.addProvider({id:me(),selector:e,priority:i,provider:t})}async provideDocumentFormattingEdits(e,t,i){let r=this.getProvider(e);if(!r)return null;let{provider:o}=r;return await Promise.resolve(o.provideDocumentFormattingEdits(e,t,i))}}});var qp,a2=D(()=>{"use strict";rt();Et();qp=class extends _e{register(e,t,i){return this.addProvider({id:me(),selector:e,provider:t,priority:i})}async provideDocumentRangeFormattingEdits(e,t,i,r){let o=this.getProvider(e);if(!o)return null;let{provider:s}=o;return await Promise.resolve(s.provideDocumentRangeFormattingEdits(e,t,i,r))}}});var Wp,l2=D(()=>{"use strict";rt();ae();Be();Et();Wp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideHover(e,t,i){let r=this.getProviders(e),o=[],s=await Promise.allSettled(r.map(a=>Promise.resolve(a.provider.provideHover(e,t,i)).then(l=>{!Vo.is(l)||o.findIndex(u=>Me(u.contents,l.contents))==-1&&o.push(l)})));return this.handleResults(s,"provideHover"),o}}});var Yp,u2=D(()=>{"use strict";rt();Et();Yp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideImplementations(e,t,i){let r=this.getProviders(e),o=[],s=await Promise.allSettled(r.map(a=>Promise.resolve(a.provider.provideImplementation(e,t,i)).then(l=>{this.addLocation(o,l)})));return this.handleResults(s,"provideImplementations"),o}}});function oce(n,e){return Ge(n.position,e.position)!==0?!1:Jp(n)===Jp(e)}function sce(n){return!n||!Q.is(n.position)||n.label==null?!1:typeof n.label!="string"?Array.isArray(n.label)&&n.label.every(e=>typeof e.value=="string"):!0}function ace(n,e){return n.label.length===0||Array.isArray(n.label)&&n.label.every(t=>t.value.length===0)?(c2.warn("INVALID inlay hint, empty label",n),!1):sce(n)?!(e&&Ft(n.position,e)!==0):(c2.warn("INVALID inlay hint",n),!1)}function Jp(n){return typeof n.label=="string"?n.label:n.label.map(e=>e.value).join("")}var c2,Zp,SR=D(()=>{"use strict";rt();ae();xe();Tt();Et();c2=Z("inlayHintManger"),Zp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideInlayHints(e,t,i){let r=this.getProviders(e),o=[];return await Promise.all(r.map(s=>{let{id:a,provider:l}=s;return Promise.resolve(l.provideInlayHints(e,t,i)).then(u=>{if(!Array.isArray(u)||i.isCancellationRequested)return;let c=o.length==0;for(let d of u)!ace(d,t)||!c&&o.findIndex(h=>oce(h,d))!=-1||o.push({providerId:a,...d})})})),o}async resolveInlayHint(e,t){let i=this.getProviderById(e.providerId);if(!i||typeof i.resolveInlayHint!="function"||e.resolved===!0)return e;let r=await Promise.resolve(i.resolveInlayHint(e,t));return t.isCancellationRequested?e:Object.assign(e,r,{resolved:!0})}}});var $p,d2=D(()=>{"use strict";rt();Be();Et();$p=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideInlineValues(e,t,i,r){let o=this.getProviders(e),s=[],a=await Promise.allSettled(o.map(l=>Promise.resolve(l.provider.provideInlineValues(e,t,i,r)).then(u=>{if(!Array.isArray(u))return;let c=s.length===0;for(let d of u)(c||s.every(h=>!Me(h,d)))&&s.push(d)})));return this.handleResults(a,"provideInlineValues"),s}}});var FAe,Up,h2=D(()=>{"use strict";rt();xe();Et();FAe=Z("linkedEditingManager"),Up=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideLinkedEditingRanges(e,t,i){let r=this.getProviders(e);for(let o of r){let s=await Promise.resolve(o.provider.provideLinkedEditingRanges(e,t,i));if(s!=null)return s}return null}}});var Xp,g2=D(()=>{"use strict";rt();he();Et();Xp=class extends _e{register(e,t,i){return this.addProvider({id:me(),selector:e,provider:t,triggerCharacters:i??[]})}couldTrigger(e,t){for(let i of this.providers){let{triggerCharacters:r,selector:o}=i;if(y.match(o,e)>0&&r.includes(t))return i.provider}return null}async onCharacterType(e,t,i,r){let s=this.getProviders(t).find(l=>l.triggerCharacters.includes(e));if(!s)return null;let a=await y.getFormatOptions(t.uri);return await Promise.resolve(s.provider.provideOnTypeFormattingEdits(t,i,e,a,r))}}});var Gp,p2=D(()=>{"use strict";rt();Et();Gp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideReferences(e,t,i,r){let o=this.getProviders(e),s=[],a=await Promise.allSettled(o.map(l=>Promise.resolve(l.provider.provideReferences(e,t,i,r)).then(u=>{this.addLocation(s,u)})));return this.handleResults(a,"provideReferences"),s}}});var zp,f2=D(()=>{"use strict";rt();Et();zp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideRenameEdits(e,t,i,r){let o=this.getProviders(e),s=null;for(let a of o){try{s=await Promise.resolve(a.provider.provideRenameEdits(e,t,i,r))}catch(l){this.handleResults([{status:"rejected",reason:l}],"provideRenameEdits")}if(s!=null)break}return s}async prepareRename(e,t,i){let r=this.getProviders(e);if(r=r.filter(o=>typeof o.provider.prepareRename=="function"),r.length===0)return null;for(let o of r){let s=await Promise.resolve(o.provider.prepareRename(e,t,i));if(s!=null)return s}return!1}}});var Kp,m2=D(()=>{"use strict";rt();Be();Tt();Et();Kp=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideSelectionRanges(e,t,i){let r=this.getProviders(e);if(r.length===0)return null;let o=[],s=await Promise.allSettled(r.map(l=>Promise.resolve(l.provider.provideSelectionRanges(e,t,i)).then(u=>{Array.isArray(u)&&u.length>0&&o.push(u)})));if(this.handleResults(s,"provideSelectionRanges"),o.length===0)return null;let a=o[0];if(o.length>1)for(let l=1;l<=o.length-1;l++){let u=a[0].range,c=a[a.length-1].range,d=o[l],h=d.length;ti(c,d[0].range)&&!Me(c,d[0].range)?a.push(...d):ti(d[h-1].range,u)&&!Me(d[h-1].range,u)&&a.unshift(...d)}for(let l=0;l{"use strict";rt();Et();Qp=class extends _e{register(e,t,i){return this.addProvider({id:me(),selector:e,provider:t,legend:i})}getLegend(e){let t=this.getProvider(e);if(!!t)return t.legend}hasSemanticTokensEdits(e){var i;let t=(i=this.getProvider(e))==null?void 0:i.provider;return t?typeof t.provideDocumentSemanticTokensEdits=="function":!1}async provideDocumentSemanticTokens(e,t){var r;let i=(r=this.getProvider(e))==null?void 0:r.provider;return!i||typeof i.provideDocumentSemanticTokens!="function"?null:await Promise.resolve(i.provideDocumentSemanticTokens(e,t))}async provideDocumentSemanticTokensEdits(e,t,i){let r=this.getProvider(e);return!r||typeof r.provider.provideDocumentSemanticTokensEdits!="function"?null:await Promise.resolve(r.provider.provideDocumentSemanticTokensEdits(e,t,i))}}});var Vp,y2=D(()=>{"use strict";rt();Et();Vp=class extends _e{register(e,t,i){return this.addProvider({id:me(),selector:e,legend:i,provider:t})}getLegend(e){let t=this.getProvider(e);if(!!t)return t.legend}async provideDocumentRangeSemanticTokens(e,t,i){let r=this.getProvider(e);if(!r)return null;let{provider:o}=r;return await Promise.resolve(o.provideDocumentRangeSemanticTokens(e,t,i))}}});var ef,v2=D(()=>{"use strict";rt();Re();Et();ef=class extends _e{register(e,t,i){i=re(i)?[]:i;let r=i.reduce((o,s)=>o.concat(s.length==1?[s]:s.split(/\s*/g)),[]);return this.addProvider({id:me(),selector:e,provider:t,triggerCharacters:r})}shouldTrigger(e,t){let i=this.getProviders(e);if(i.length===0)return!1;for(let r of i)if(r.triggerCharacters.includes(t))return!0;return!1}async provideSignatureHelp(e,t,i,r){let o=this.getProviders(e);for(let s of o){let a=await Promise.resolve(s.provider.provideSignatureHelp(e,t,i,r));if(a&&a.signatures&&a.signatures.length>0)return a}return null}}});var tf,w2=D(()=>{"use strict";rt();Et();tf=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async provideTypeDefinition(e,t,i){let r=this.getProviders(e),o=[],s=await Promise.allSettled(r.map(a=>Promise.resolve(a.provider.provideTypeDefinition(e,t,i)).then(l=>{this.addLocation(o,l)})));return this.handleResults(s,"provideTypeDefinition"),o}}});var x2,nf,C2=D(()=>{"use strict";rt();io();Et();x2=["source"],nf=class extends _e{register(e,t){return this.addProvider({id:me(),selector:e,provider:t})}async prepareTypeHierarchy(e,t,i){let r=this.getProviders(e),o=[],s=await Promise.allSettled(r.map(a=>{let{provider:l,id:u}=a;return(async()=>{let c=await Promise.resolve(l.prepareTypeHierarchy(e,t,i));if(Array.isArray(c)){let d=o.length===0;c.forEach(h=>{(d||o.every(g=>g.name!==h.name))&&o.push(Object.assign({source:u},h))})}})()}));return this.handleResults(s,"prepareTypeHierarchy"),o}async provideTypeHierarchySupertypes(e,t){let{source:i}=e,r=this.getProviderById(i);return r?await Promise.resolve(r.provideTypeHierarchySupertypes(ci(e,x2),t)).then(o=>Array.isArray(o)?o.map(s=>Object.assign({source:i},s)):[]):[]}async provideTypeHierarchySubtypes(e,t){let{source:i}=e,r=this.getProviderById(i);return r?await Promise.resolve(r.provideTypeHierarchySubtypes(ci(e,x2),t)).then(o=>Array.isArray(o)?o.map(s=>Object.assign({source:i},s)):[]):[]}}});var rf,S2=D(()=>{"use strict";rt();Et();rf=class extends _e{register(e){return this.addProvider({id:me(),selector:[{language:"*"}],provider:e})}async provideWorkspaceSymbols(e,t){let i=Array.from(this.providers),r=[],o=await Promise.allSettled(i.map(s=>{let{id:a,provider:l}=s;return Promise.resolve(l.provideWorkspaceSymbols(e,t)).then(u=>{u&&r.push(...u.map(c=>Object.assign({source:a},c)))})}));return this.handleResults(o,"provideWorkspaceSymbols"),r}async resolveWorkspaceSymbol(e,t){let i=this.getProviderById(e.source);return!i||typeof i.resolveWorkspaceSymbol!="function"?e:i.resolveWorkspaceSymbol(e,t)}hasProvider(){return this.providers.size>0}}});var T2=w((mNe,D2)=>{"use strict";var lce=["aborted","complete","headers","httpVersion","httpVersionMinor","httpVersionMajor","method","rawHeaders","rawTrailers","setTimeout","socket","statusCode","statusMessage","trailers","url"];D2.exports=(n,e)=>{if(e._readableState.autoDestroy)throw new Error("The second stream must have the `autoDestroy` option set to `false`");let t=new Set(Object.keys(n).concat(lce)),i={};for(let r of t)r in e||(i[r]={get(){let o=n[r];return typeof o=="function"?o.bind(n):o},set(o){n[r]=o},enumerable:!0,configurable:!1});return Object.defineProperties(e,i),n.once("aborted",()=>{e.destroy(),e.emit("aborted")}),n.once("close",()=>{n.complete&&e.readable?e.once("end",()=>{e.emit("close")}):e.emit("close")}),e}});var P2=w((bNe,k2)=>{"use strict";var{Transform:uce,PassThrough:cce}=require("stream"),DR=require("zlib"),dce=T2();k2.exports=n=>{let e=(n.headers["content-encoding"]||"").toLowerCase();if(!["gzip","deflate","br"].includes(e))return n;let t=e==="br";if(t&&typeof DR.createBrotliDecompress!="function")return n.destroy(new Error("Brotli is not supported on Node.js < 12")),n;let i=!0,r=new uce({transform(a,l,u){i=!1,u(null,a)},flush(a){a()}}),o=new cce({autoDestroy:!1,destroy(a,l){n.destroy(),l(a)}}),s=t?DR.createBrotliDecompress():DR.createUnzip();return s.once("error",a=>{if(i&&!n.readable){o.end();return}o.destroy(a)}),dce(n,o),n.pipe(r).pipe(s).pipe(o),o}});var _2=w((yNe,R2)=>{var Bc=1e3,qc=Bc*60,Wc=qc*60,Ol=Wc*24,hce=Ol*7,gce=Ol*365.25;R2.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return pce(n);if(t==="number"&&isFinite(n))return e.long?mce(n):fce(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function pce(n){if(n=String(n),!(n.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(!!e){var t=parseFloat(e[1]),i=(e[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return t*gce;case"weeks":case"week":case"w":return t*hce;case"days":case"day":case"d":return t*Ol;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Wc;case"minutes":case"minute":case"mins":case"min":case"m":return t*qc;case"seconds":case"second":case"secs":case"sec":case"s":return t*Bc;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function fce(n){var e=Math.abs(n);return e>=Ol?Math.round(n/Ol)+"d":e>=Wc?Math.round(n/Wc)+"h":e>=qc?Math.round(n/qc)+"m":e>=Bc?Math.round(n/Bc)+"s":n+"ms"}function mce(n){var e=Math.abs(n);return e>=Ol?gw(n,e,Ol,"day"):e>=Wc?gw(n,e,Wc,"hour"):e>=qc?gw(n,e,qc,"minute"):e>=Bc?gw(n,e,Bc,"second"):n+" ms"}function gw(n,e,t,i){var r=e>=t*1.5;return Math.round(n/t)+" "+i+(r?"s":"")}});var TR=w((vNe,E2)=>{function bce(n){t.debug=t,t.default=t,t.coerce=l,t.disable=o,t.enable=r,t.enabled=s,t.humanize=_2(),t.destroy=u,Object.keys(n).forEach(c=>{t[c]=n[c]}),t.names=[],t.skips=[],t.formatters={};function e(c){let d=0;for(let h=0;h{if(j==="%%")return"%";k++;let X=t.formatters[N];if(typeof X=="function"){let se=b[k];j=X.call(v,se),b.splice(k,1),k--}return j}),t.formatArgs.call(v,b),(v.log||t.log).apply(v,b)}return m.namespace=c,m.useColors=t.useColors(),m.color=t.selectColor(c),m.extend=i,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(g!==t.namespaces&&(g=t.namespaces,f=t.enabled(c)),f),set:b=>{h=b}}),typeof t.init=="function"&&t.init(m),m}function i(c,d){let h=t(this.namespace+(typeof d>"u"?":":d)+c);return h.log=this.log,h}function r(c){t.save(c),t.namespaces=c,t.names=[],t.skips=[];let d,h=(typeof c=="string"?c:"").split(/[\s,]+/),g=h.length;for(d=0;d"-"+d)].join(",");return t.enable(""),c}function s(c){if(c[c.length-1]==="*")return!0;let d,h;for(d=0,h=t.skips.length;d{Kn.formatArgs=vce;Kn.save=wce;Kn.load=xce;Kn.useColors=yce;Kn.storage=Cce();Kn.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Kn.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function yce(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function vce(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+pw.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,i=0;n[0].replace(/%[a-zA-Z%]/g,r=>{r!=="%%"&&(t++,r==="%c"&&(i=t))}),n.splice(i,0,e)}Kn.log=console.debug||console.log||(()=>{});function wce(n){try{n?Kn.storage.setItem("debug",n):Kn.storage.removeItem("debug")}catch{}}function xce(){let n;try{n=Kn.storage.getItem("debug")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Cce(){try{return localStorage}catch{}}pw.exports=TR()(Kn);var{formatters:Sce}=pw.exports;Sce.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var F2=w((wNe,L2)=>{"use strict";L2.exports=(n,e=process.argv)=>{let t=n.startsWith("-")?"":n.length===1?"-":"--",i=e.indexOf(t+n),r=e.indexOf("--");return i!==-1&&(r===-1||i{"use strict";var Dce=require("os"),M2=require("tty"),xr=F2(),{env:Ai}=process,fa;xr("no-color")||xr("no-colors")||xr("color=false")||xr("color=never")?fa=0:(xr("color")||xr("colors")||xr("color=true")||xr("color=always"))&&(fa=1);"FORCE_COLOR"in Ai&&(Ai.FORCE_COLOR==="true"?fa=1:Ai.FORCE_COLOR==="false"?fa=0:fa=Ai.FORCE_COLOR.length===0?1:Math.min(parseInt(Ai.FORCE_COLOR,10),3));function kR(n){return n===0?!1:{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function PR(n,e){if(fa===0)return 0;if(xr("color=16m")||xr("color=full")||xr("color=truecolor"))return 3;if(xr("color=256"))return 2;if(n&&!e&&fa===void 0)return 0;let t=fa||0;if(Ai.TERM==="dumb")return t;if(process.platform==="win32"){let i=Dce.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in Ai)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(i=>i in Ai)||Ai.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in Ai)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ai.TEAMCITY_VERSION)?1:0;if(Ai.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Ai){let i=parseInt((Ai.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ai.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ai.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ai.TERM)||"COLORTERM"in Ai?1:t}function Tce(n){let e=PR(n,n&&n.isTTY);return kR(e)}j2.exports={supportsColor:Tce,stdout:kR(PR(!0,M2.isatty(1))),stderr:kR(PR(!0,M2.isatty(2)))}});var N2=w((Ki,mw)=>{var kce=require("tty"),fw=require("util");Ki.init=Fce;Ki.log=Ece;Ki.formatArgs=Rce;Ki.save=Ice;Ki.load=Lce;Ki.useColors=Pce;Ki.destroy=fw.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ki.colors=[6,2,3,4,5,1];try{let n=O2();n&&(n.stderr||n).level>=2&&(Ki.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}Ki.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(r,o)=>o.toUpperCase()),i=process.env[e];return/^(yes|on|true|enabled)$/i.test(i)?i=!0:/^(no|off|false|disabled)$/i.test(i)?i=!1:i==="null"?i=null:i=Number(i),n[t]=i,n},{});function Pce(){return"colors"in Ki.inspectOpts?Boolean(Ki.inspectOpts.colors):kce.isatty(process.stderr.fd)}function Rce(n){let{namespace:e,useColors:t}=this;if(t){let i=this.color,r="\x1B[3"+(i<8?i:"8;5;"+i),o=` ${r};1m${e} \x1B[0m`;n[0]=o+n[0].split(` +`).join(` +`+o),n.push(r+"m+"+mw.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=_ce()+e+" "+n[0]}function _ce(){return Ki.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Ece(...n){return process.stderr.write(fw.format(...n)+` +`)}function Ice(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function Lce(){return process.env.DEBUG}function Fce(n){n.inspectOpts={};let e=Object.keys(Ki.inspectOpts);for(let t=0;te.trim()).join(" ")};A2.O=function(n){return this.inspectOpts.colors=this.useColors,fw.inspect(n,this.inspectOpts)}});var Yc=w((CNe,RR)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?RR.exports=I2():RR.exports=N2()});var B2=w((SNe,H2)=>{var of;H2.exports=function(){if(!of){try{of=Yc()("follow-redirects")}catch{}typeof of!="function"&&(of=function(){})}of.apply(null,arguments)}});var X2=w((DNe,FR)=>{var Al=require("url"),_R=Al.URL,Mce=require("http"),jce=require("https"),Y2=require("stream").Writable,Z2=require("assert"),J2=B2(),IR=["abort","aborted","connect","error","socket","timeout"],LR=Object.create(null);IR.forEach(function(n){LR[n]=function(e,t,i){this._redirectable.emit(n,e,t,i)}});var Oce=af("ERR_INVALID_URL","Invalid URL",TypeError),q2=af("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),Ace=af("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded"),Nce=af("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),Hce=af("ERR_STREAM_WRITE_AFTER_END","write after end");function Qn(n,e){Y2.call(this),this._sanitizeOptions(n),this._options=n,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],e&&this.on("response",e);var t=this;this._onNativeResponse=function(i){t._processResponse(i)},this._performRequest()}Qn.prototype=Object.create(Y2.prototype);Qn.prototype.abort=function(){U2(this._currentRequest),this.emit("abort")};Qn.prototype.write=function(n,e,t){if(this._ending)throw new Hce;if(!Nl(n)&&!Wce(n))throw new TypeError("data should be a string, Buffer or Uint8Array");if(sf(e)&&(t=e,e=null),n.length===0){t&&t();return}this._requestBodyLength+n.length<=this._options.maxBodyLength?(this._requestBodyLength+=n.length,this._requestBodyBuffers.push({data:n,encoding:e}),this._currentRequest.write(n,e,t)):(this.emit("error",new Nce),this.abort())};Qn.prototype.end=function(n,e,t){if(sf(n)?(t=n,n=e=null):sf(e)&&(t=e,e=null),!n)this._ended=this._ending=!0,this._currentRequest.end(null,null,t);else{var i=this,r=this._currentRequest;this.write(n,e,function(){i._ended=!0,r.end(null,null,t)}),this._ending=!0}};Qn.prototype.setHeader=function(n,e){this._options.headers[n]=e,this._currentRequest.setHeader(n,e)};Qn.prototype.removeHeader=function(n){delete this._options.headers[n],this._currentRequest.removeHeader(n)};Qn.prototype.setTimeout=function(n,e){var t=this;function i(s){s.setTimeout(n),s.removeListener("timeout",s.destroy),s.addListener("timeout",s.destroy)}function r(s){t._timeout&&clearTimeout(t._timeout),t._timeout=setTimeout(function(){t.emit("timeout"),o()},n),i(s)}function o(){t._timeout&&(clearTimeout(t._timeout),t._timeout=null),t.removeListener("abort",o),t.removeListener("error",o),t.removeListener("response",o),e&&t.removeListener("timeout",e),t.socket||t._currentRequest.removeListener("socket",r)}return e&&this.on("timeout",e),this.socket?r(this.socket):this._currentRequest.once("socket",r),this.on("socket",i),this.on("abort",o),this.on("error",o),this.on("response",o),this};["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(n){Qn.prototype[n]=function(e,t){return this._currentRequest[n](e,t)}});["aborted","connection","socket"].forEach(function(n){Object.defineProperty(Qn.prototype,n,{get:function(){return this._currentRequest[n]}})});Qn.prototype._sanitizeOptions=function(n){if(n.headers||(n.headers={}),n.host&&(n.hostname||(n.hostname=n.host),delete n.host),!n.pathname&&n.path){var e=n.path.indexOf("?");e<0?n.pathname=n.path:(n.pathname=n.path.substring(0,e),n.search=n.path.substring(e))}};Qn.prototype._performRequest=function(){var n=this._options.protocol,e=this._options.nativeProtocols[n];if(!e){this.emit("error",new TypeError("Unsupported protocol "+n));return}if(this._options.agents){var t=n.slice(0,-1);this._options.agent=this._options.agents[t]}var i=this._currentRequest=e.request(this._options,this._onNativeResponse);i._redirectable=this;for(var r of IR)i.on(r,LR[r]);if(this._currentUrl=/^\//.test(this._options.path)?Al.format(this._options):this._options.path,this._isRedirect){var o=0,s=this,a=this._requestBodyBuffers;(function l(u){if(i===s._currentRequest)if(u)s.emit("error",u);else if(o=400){n.responseUrl=this._currentUrl,n.redirects=this._redirects,this.emit("response",n),this._requestBodyBuffers=[];return}if(U2(this._currentRequest),n.destroy(),++this._redirectCount>this._options.maxRedirects){this.emit("error",new Ace);return}var i,r=this._options.beforeRedirect;r&&(i=Object.assign({Host:n.req.getHeader("host")},this._options.headers));var o=this._options.method;((e===301||e===302)&&this._options.method==="POST"||e===303&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],ER(/^content-/i,this._options.headers));var s=ER(/^host$/i,this._options.headers),a=Al.parse(this._currentUrl),l=s||a.host,u=/^\w+:/.test(t)?this._currentUrl:Al.format(Object.assign(a,{host:l})),c;try{c=Al.resolve(u,t)}catch(f){this.emit("error",new q2({cause:f}));return}J2("redirecting to",c),this._isRedirect=!0;var d=Al.parse(c);if(Object.assign(this._options,d),(d.protocol!==a.protocol&&d.protocol!=="https:"||d.host!==l&&!qce(d.host,l))&&ER(/^(?:authorization|cookie)$/i,this._options.headers),sf(r)){var h={headers:n.headers,statusCode:e},g={url:u,method:o,headers:i};try{r(this._options,h,g)}catch(f){this.emit("error",f);return}this._sanitizeOptions(this._options)}try{this._performRequest()}catch(f){this.emit("error",new q2({cause:f}))}};function $2(n){var e={maxRedirects:21,maxBodyLength:10485760},t={};return Object.keys(n).forEach(function(i){var r=i+":",o=t[r]=n[i],s=e[i]=Object.create(o);function a(u,c,d){if(Nl(u)){var h;try{h=W2(new _R(u))}catch{h=Al.parse(u)}if(!Nl(h.protocol))throw new Oce({input:u});u=h}else _R&&u instanceof _R?u=W2(u):(d=c,c=u,u={protocol:r});return sf(c)&&(d=c,c=null),c=Object.assign({maxRedirects:e.maxRedirects,maxBodyLength:e.maxBodyLength},u,c),c.nativeProtocols=t,!Nl(c.host)&&!Nl(c.hostname)&&(c.hostname="::1"),Z2.equal(c.protocol,r,"protocol mismatch"),J2("options",c),new Qn(c,d)}function l(u,c,d){var h=s.request(u,c,d);return h.end(),h}Object.defineProperties(s,{request:{value:a,configurable:!0,enumerable:!0,writable:!0},get:{value:l,configurable:!0,enumerable:!0,writable:!0}})}),e}function Bce(){}function W2(n){var e={protocol:n.protocol,hostname:n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,hash:n.hash,search:n.search,pathname:n.pathname,path:n.pathname+n.search,href:n.href};return n.port!==""&&(e.port=Number(n.port)),e}function ER(n,e){var t;for(var i in e)n.test(i)&&(t=e[i],delete e[i]);return t===null||typeof t>"u"?void 0:String(t).trim()}function af(n,e,t){function i(r){Error.captureStackTrace(this,this.constructor),Object.assign(this,r||{}),this.code=n,this.message=this.cause?e+": "+this.cause.message:e}return i.prototype=new(t||Error),i.prototype.constructor=i,i.prototype.name="Error ["+n+"]",i}function U2(n){for(var e of IR)n.removeListener(e,LR[e]);n.on("error",Bce),n.abort()}function qce(n,e){Z2(Nl(n)&&Nl(e));var t=n.length-e.length-1;return t>0&&n[t]==="."&&n.endsWith(e)}function Nl(n){return typeof n=="string"||n instanceof String}function sf(n){return typeof n=="function"}function Wce(n){return typeof n=="object"&&"length"in n}FR.exports=$2({http:Mce,https:jce});FR.exports.wrap=$2});var G2=w(MR=>{"use strict";Object.defineProperty(MR,"__esModule",{value:!0});function Yce(n,e,{signal:t}={}){return new Promise((i,r)=>{function o(){t==null||t.removeEventListener("abort",o),n.removeListener(e,s),n.removeListener("error",a)}function s(...l){o(),i(l)}function a(l){o(),r(l)}t==null||t.addEventListener("abort",o),n.on(e,s),n.on("error",a)})}MR.default=Yce});var z2=w(jR=>{"use strict";Object.defineProperty(jR,"__esModule",{value:!0});function Zce(n){return function(e,t){return new Promise((i,r)=>{n.call(this,e,t,(o,s)=>{o?r(o):i(s)})})}}jR.default=Zce});var NR=w((AR,Q2)=>{"use strict";var K2=AR&&AR.__importDefault||function(n){return n&&n.__esModule?n:{default:n}},Jce=require("events"),$ce=K2(Yc()),Uce=K2(z2()),lf=$ce.default("agent-base");function Xce(n){return Boolean(n)&&typeof n.addRequest=="function"}function OR(){let{stack:n}=new Error;return typeof n!="string"?!1:n.split(` +`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function bw(n,e){return new bw.Agent(n,e)}(function(n){class e extends Jce.EventEmitter{constructor(i,r){super();let o=r;typeof i=="function"?this.callback=i:i&&(o=i),this.timeout=null,o&&typeof o.timeout=="number"&&(this.timeout=o.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=1/0,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return typeof this.explicitDefaultPort=="number"?this.explicitDefaultPort:OR()?443:80}set defaultPort(i){this.explicitDefaultPort=i}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:OR()?"https:":"http:"}set protocol(i){this.explicitProtocol=i}callback(i,r,o){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(i,r){let o=Object.assign({},r);typeof o.secureEndpoint!="boolean"&&(o.secureEndpoint=OR()),o.host==null&&(o.host="localhost"),o.port==null&&(o.port=o.secureEndpoint?443:80),o.protocol==null&&(o.protocol=o.secureEndpoint?"https:":"http:"),o.host&&o.path&&delete o.path,delete o.agent,delete o.hostname,delete o._defaultAgent,delete o.defaultPort,delete o.createConnection,i._last=!0,i.shouldKeepAlive=!1;let s=!1,a=null,l=o.timeout||this.timeout,u=g=>{i._hadError||(i.emit("error",g),i._hadError=!0)},c=()=>{a=null,s=!0;let g=new Error(`A "socket" was not created for HTTP request before ${l}ms`);g.code="ETIMEOUT",u(g)},d=g=>{s||(a!==null&&(clearTimeout(a),a=null),u(g))},h=g=>{if(s)return;if(a!=null&&(clearTimeout(a),a=null),Xce(g)){lf("Callback returned another Agent instance %o",g.constructor.name),g.addRequest(i,o);return}if(g){g.once("free",()=>{this.freeSocket(g,o)}),i.onSocket(g);return}let f=new Error(`no Duplex stream was returned to agent-base for \`${i.method} ${i.path}\``);u(f)};if(typeof this.callback!="function"){u(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(lf("Converting legacy callback function to promise"),this.promisifiedCallback=Uce.default(this.callback)):this.promisifiedCallback=this.callback),typeof l=="number"&&l>0&&(a=setTimeout(c,l)),"port"in o&&typeof o.port!="number"&&(o.port=Number(o.port));try{lf("Resolving socket for %o request: %o",o.protocol,`${i.method} ${i.path}`),Promise.resolve(this.promisifiedCallback(i,o)).then(h,d)}catch(g){Promise.reject(g).catch(d)}}freeSocket(i,r){lf("Freeing socket %o %o",i.constructor.name,r),i.destroy()}destroy(){lf("Destroying agent %o",this.constructor.name)}}n.Agent=e,n.prototype=n.Agent.prototype})(bw||(bw={}));Q2.exports=bw});var V2=w(Hl=>{"use strict";var Gce=Hl&&Hl.__awaiter||function(n,e,t,i){function r(o){return o instanceof t?o:new t(function(s){s(o)})}return new(t||(t=Promise))(function(o,s){function a(c){try{u(i.next(c))}catch(d){s(d)}}function l(c){try{u(i.throw(c))}catch(d){s(d)}}function u(c){c.done?o(c.value):r(c.value).then(a,l)}u((i=i.apply(n,e||[])).next())})},uf=Hl&&Hl.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Hl,"__esModule",{value:!0});var zce=uf(require("net")),Kce=uf(require("tls")),HR=uf(require("url")),Qce=uf(Yc()),Vce=uf(G2()),ede=NR(),ma=(0,Qce.default)("http-proxy-agent");function tde(n){return typeof n=="string"?/^https:?$/i.test(n):!1}var BR=class extends ede.Agent{constructor(e){let t;if(typeof e=="string"?t=HR.default.parse(e):t=e,!t)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");ma("Creating new HttpProxyAgent instance: %o",t),super(t);let i=Object.assign({},t);this.secureProxy=t.secureProxy||tde(i.protocol),i.host=i.hostname||i.host,typeof i.port=="string"&&(i.port=parseInt(i.port,10)),!i.port&&i.host&&(i.port=this.secureProxy?443:80),i.host&&i.path&&(delete i.path,delete i.pathname),this.proxy=i}callback(e,t){return Gce(this,void 0,void 0,function*(){let{proxy:i,secureProxy:r}=this,o=HR.default.parse(e.path);o.protocol||(o.protocol="http:"),o.hostname||(o.hostname=t.hostname||t.host||null),o.port==null&&typeof t.port&&(o.port=String(t.port)),o.port==="80"&&(o.port=""),e.path=HR.default.format(o),i.auth&&e.setHeader("Proxy-Authorization",`Basic ${Buffer.from(i.auth).toString("base64")}`);let s;if(r?(ma("Creating `tls.Socket`: %o",i),s=Kce.default.connect(i)):(ma("Creating `net.Socket`: %o",i),s=zce.default.connect(i)),e._header){let a,l;ma("Regenerating stored HTTP header string for request"),e._header=null,e._implicitHeader(),e.output&&e.output.length>0?(ma("Patching connection write() output buffer with updated header"),a=e.output[0],l=a.indexOf(`\r +\r +`)+4,e.output[0]=e._header+a.substring(l),ma("Output buffer: %o",e.output)):e.outputData&&e.outputData.length>0&&(ma("Patching connection write() output buffer with updated header"),a=e.outputData[0].data,l=a.indexOf(`\r +\r +`)+4,e.outputData[0].data=e._header+a.substring(l),ma("Output buffer: %o",e.outputData[0].data))}return yield(0,Vce.default)(s,"connect"),s})}};Hl.default=BR});var tG=w((YR,eG)=>{"use strict";var ide=YR&&YR.__importDefault||function(n){return n&&n.__esModule?n:{default:n}},qR=ide(V2());function WR(n){return new qR.default(n)}(function(n){n.HttpProxyAgent=qR.default,n.prototype=qR.default.prototype})(WR||(WR={}));eG.exports=WR});var iG=w(df=>{"use strict";var nde=df&&df.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(df,"__esModule",{value:!0});var rde=nde(Yc()),cf=rde.default("https-proxy-agent:parse-proxy-response");function ode(n){return new Promise((e,t)=>{let i=0,r=[];function o(){let d=n.read();d?c(d):n.once("readable",o)}function s(){n.removeListener("end",l),n.removeListener("error",u),n.removeListener("close",a),n.removeListener("readable",o)}function a(d){cf("onclose had error %o",d)}function l(){cf("onend")}function u(d){s(),cf("onerror %o",d),t(d)}function c(d){r.push(d),i+=d.length;let h=Buffer.concat(r,i);if(h.indexOf(`\r +\r +`)===-1){cf("have not received end of HTTP headers yet..."),o();return}let f=h.toString("ascii",0,h.indexOf(`\r +`)),m=+f.split(" ")[1];cf("got proxy server response: %o",f),e({statusCode:m,buffered:h})}n.on("error",u),n.on("close",a),n.on("end",l),o()})}df.default=ode});var oG=w(Bl=>{"use strict";var sde=Bl&&Bl.__awaiter||function(n,e,t,i){function r(o){return o instanceof t?o:new t(function(s){s(o)})}return new(t||(t=Promise))(function(o,s){function a(c){try{u(i.next(c))}catch(d){s(d)}}function l(c){try{u(i.throw(c))}catch(d){s(d)}}function u(c){c.done?o(c.value):r(c.value).then(a,l)}u((i=i.apply(n,e||[])).next())})},Zc=Bl&&Bl.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Bl,"__esModule",{value:!0});var nG=Zc(require("net")),rG=Zc(require("tls")),ade=Zc(require("url")),lde=Zc(require("assert")),ude=Zc(Yc()),cde=NR(),dde=Zc(iG()),hf=ude.default("https-proxy-agent:agent"),ZR=class extends cde.Agent{constructor(e){let t;if(typeof e=="string"?t=ade.default.parse(e):t=e,!t)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");hf("creating new HttpsProxyAgent instance: %o",t),super(t);let i=Object.assign({},t);this.secureProxy=t.secureProxy||pde(i.protocol),i.host=i.hostname||i.host,typeof i.port=="string"&&(i.port=parseInt(i.port,10)),!i.port&&i.host&&(i.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in i)&&(i.ALPNProtocols=["http 1.1"]),i.host&&i.path&&(delete i.path,delete i.pathname),this.proxy=i}callback(e,t){return sde(this,void 0,void 0,function*(){let{proxy:i,secureProxy:r}=this,o;r?(hf("Creating `tls.Socket`: %o",i),o=rG.default.connect(i)):(hf("Creating `net.Socket`: %o",i),o=nG.default.connect(i));let s=Object.assign({},i.headers),l=`CONNECT ${`${t.host}:${t.port}`} HTTP/1.1\r +`;i.auth&&(s["Proxy-Authorization"]=`Basic ${Buffer.from(i.auth).toString("base64")}`);let{host:u,port:c,secureEndpoint:d}=t;gde(c,d)||(u+=`:${c}`),s.Host=u,s.Connection="close";for(let b of Object.keys(s))l+=`${b}: ${s[b]}\r +`;let h=dde.default(o);o.write(`${l}\r +`);let{statusCode:g,buffered:f}=yield h;if(g===200){if(e.once("socket",hde),t.secureEndpoint){hf("Upgrading socket connection to TLS");let b=t.servername||t.host;return rG.default.connect(Object.assign(Object.assign({},fde(t,"host","hostname","path","port")),{socket:o,servername:b}))}return o}o.destroy();let m=new nG.default.Socket({writable:!1});return m.readable=!0,e.once("socket",b=>{hf("replaying proxy buffer for failed request"),lde.default(b.listenerCount("data")>0),b.push(f),b.push(null)}),m})}};Bl.default=ZR;function hde(n){n.resume()}function gde(n,e){return Boolean(!e&&n===80||e&&n===443)}function pde(n){return typeof n=="string"?/^https:?$/i.test(n):!1}function fde(n,...e){let t={},i;for(i in n)e.includes(i)||(t[i]=n[i]);return t}});var aG=w((UR,sG)=>{"use strict";var mde=UR&&UR.__importDefault||function(n){return n&&n.__esModule?n:{default:n}},JR=mde(oG());function $R(n){return new JR.default(n)}(function(n){n.HttpsProxyAgent=JR.default,n.prototype=JR.default.prototype})($R||($R={}));sG.exports=$R});function GR(n){return n.protocol==="https:"?vw.https:vw.http}function bde(n){return typeof n=="string"||Buffer.isBuffer(n)?n:JSON.stringify(n)}function zR(n){if(n instanceof yw.URL)return n;let e=new yw.URL(n);if(!["https:","http:"].includes(e.protocol))throw new Error(`Not valid protocol with ${n}, should be http: or https:`);return e}function KR(n,e){return n&&(n=typeof n=="number"?n:parseInt(n,10),!isNaN(n))?n:e.startsWith("https")?443:80}function yde(n){return n===null?"null":n===void 0?"undefined":typeof n=="string"?"string":Buffer.isBuffer(n)?"buffer":Array.isArray(n)||xt(n)?"object":"unknown"}function vde(n,e=process.env){let t=e.NO_PROXY??e.no_proxy;if(t==="*")return null;if(t){let r=n.hostname.replace(/^\.*/,".").toLowerCase(),o=KR(n.port,n.protocol).toString(),s=t.split(",");for(let a=0,l=s.length;a{if(i){let u=i.onCancellationRequested(()=>{u.dispose(),l.destroy(new Rt)})}let a,l=r.request(t,u=>{let c=u;if(u.statusCode>=200&&u.statusCode<300||u.statusCode===1223){let d=u.headers,h=[],g=oe(d["content-type"]);c=(0,lG.default)(u),c.on("data",f=>{h.push(f)}),c.on("end",()=>{clearTimeout(a);let f=Buffer.concat(h);if(!t.buffer&&(g.startsWith("application/json")||g.startsWith("text/"))){let m=g.match(/charset=(\S+)/),b=m?m[1]:"utf8",v=f.toString(b);if(!g.includes("application/json"))o(v);else try{let x=JSON.parse(v);o(x)}catch(x){s(new Error(`Parse response error: ${x}`))}}else o(f)}),c.on("error",f=>{s(new Error(`Connection error to ${n}: ${f.message}`))})}else s(new Error(`Bad response from ${n}: ${u.statusCode}`))});l.on("error",u=>{t.agent&&u.code=="ECONNRESET"?a=setTimeout(()=>{s(u)},XR):s(u)}),l.on("timeout",()=>{l.destroy(new Error(`Request timeout after ${t.timeout}ms`))}),e&&l.write(bde(e)),t.timeout&&l.setTimeout(t.timeout),l.end()})}function gf(n,e={},t){let i=zR(n),r=QR(i,e);return xde(i,e.data,r,t).catch(o=>{if(hG.error(`Fetch error for ${i}:`,r,o),r.agent&&r.agent.proxy){let{proxy:s}=r.agent;throw new Error(`Request failed using proxy ${s.host}: ${o.message}`)}else throw o})}var lG,vw,uG,cG,dG,yw,hG,XR,ww=D(()=>{"use strict";lG=Lr(P2()),vw=Lr(X2()),uG=Lr(tG()),cG=Lr(aG()),dG=require("querystring"),yw=require("url");xe();Ii();Xe();de();he();fe();te();hG=Z("model-fetch"),XR=pe(500,50)});var fG=w((VR,pG)=>{var xw=require("buffer"),ko=xw.Buffer;function gG(n,e){for(var t in n)e[t]=n[t]}ko.from&&ko.alloc&&ko.allocUnsafe&&ko.allocUnsafeSlow?pG.exports=xw:(gG(xw,VR),VR.Buffer=ql);function ql(n,e,t){return ko(n,e,t)}ql.prototype=Object.create(ko.prototype);gG(ko,ql);ql.from=function(n,e,t){if(typeof n=="number")throw new TypeError("Argument must not be a number");return ko(n,e,t)};ql.alloc=function(n,e,t){if(typeof n!="number")throw new TypeError("Argument must be a number");var i=ko(n);return e!==void 0?typeof t=="string"?i.fill(e,t):i.fill(e):i.fill(0),i};ql.allocUnsafe=function(n){if(typeof n!="number")throw new TypeError("Argument must be a number");return ko(n)};ql.allocUnsafeSlow=function(n){if(typeof n!="number")throw new TypeError("Argument must be a number");return xw.SlowBuffer(n)}});var xG=w((qNe,e_)=>{"use strict";e_.exports=Lde;e_.exports.parse=Ode;var mG=require("path").basename,Cde=fG().Buffer,Sde=/[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g,Dde=/%[0-9A-Fa-f]{2}/,Tde=/%([0-9A-Fa-f]{2})/g,yG=/[^\x20-\x7e\xa0-\xff]/g,kde=/\\([\u0000-\u007f])/g,Pde=/([\\"])/g,bG=/;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g,Rde=/^[\x20-\x7e\x80-\xff]+$/,_de=/^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/,Ede=/^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/,Ide=/^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/;function Lde(n,e){var t=e||{},i=t.type||"attachment",r=Fde(n,t.fallback);return Mde(new wG(i,r))}function Fde(n,e){if(n!==void 0){var t={};if(typeof n!="string")throw new TypeError("filename must be a string");if(e===void 0&&(e=!0),typeof e!="string"&&typeof e!="boolean")throw new TypeError("fallback must be a string or boolean");if(typeof e=="string"&&yG.test(e))throw new TypeError("fallback must be ISO-8859-1 string");var i=mG(n),r=Rde.test(i),o=typeof e!="string"?e&&vG(i):mG(e),s=typeof o=="string"&&o!==i;return(s||!r||Dde.test(i))&&(t["filename*"]=i),(r||s)&&(t.filename=s?o:i),t}}function Mde(n){var e=n.parameters,t=n.type;if(!t||typeof t!="string"||!_de.test(t))throw new TypeError("invalid type");var i=String(t).toLowerCase();if(e&&typeof e=="object")for(var r,o=Object.keys(e).sort(),s=0;s{"use strict";var CG=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"]]);SG.exports=n=>n?Object.keys(n).map(e=>[CG.has(e)?CG.get(e):e,n[e]]).reduce((e,t)=>(e[t[0]]=t[1],e),Object.create(null)):{}});var Pw=w((YNe,LG)=>{"use strict";var DG=typeof process=="object"&&process?process:{stdout:null,stderr:null},qde=require("events"),TG=require("stream"),kG=require("string_decoder").StringDecoder,gs=Symbol("EOF"),ps=Symbol("maybeEmitEnd"),ba=Symbol("emittedEnd"),Cw=Symbol("emittingEnd"),pf=Symbol("emittedError"),Sw=Symbol("closed"),PG=Symbol("read"),Dw=Symbol("flush"),RG=Symbol("flushChunk"),jn=Symbol("encoding"),fs=Symbol("decoder"),Tw=Symbol("flowing"),ff=Symbol("paused"),$c=Symbol("resume"),di=Symbol("buffer"),Po=Symbol("pipes"),Ni=Symbol("bufferLength"),t_=Symbol("bufferPush"),i_=Symbol("bufferShift"),sn=Symbol("objectMode"),an=Symbol("destroyed"),n_=Symbol("emitData"),_G=Symbol("emitEnd"),r_=Symbol("emitEnd2"),ms=Symbol("async"),mf=n=>Promise.resolve().then(n),EG=global._MP_NO_ITERATOR_SYMBOLS_!=="1",Wde=EG&&Symbol.asyncIterator||Symbol("asyncIterator not implemented"),Yde=EG&&Symbol.iterator||Symbol("iterator not implemented"),Zde=n=>n==="end"||n==="finish"||n==="prefinish",Jde=n=>n instanceof ArrayBuffer||typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,$de=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),kw=class{constructor(e,t,i){this.src=e,this.dest=t,this.opts=i,this.ondrain=()=>e[$c](),t.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},o_=class extends kw{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,i){super(e,t,i),this.proxyErrors=r=>t.emit("error",r),e.on("error",this.proxyErrors)}};LG.exports=class IG extends TG{constructor(e){super(),this[Tw]=!1,this[ff]=!1,this[Po]=[],this[di]=[],this[sn]=e&&e.objectMode||!1,this[sn]?this[jn]=null:this[jn]=e&&e.encoding||null,this[jn]==="buffer"&&(this[jn]=null),this[ms]=e&&!!e.async||!1,this[fs]=this[jn]?new kG(this[jn]):null,this[gs]=!1,this[ba]=!1,this[Cw]=!1,this[Sw]=!1,this[pf]=null,this.writable=!0,this.readable=!0,this[Ni]=0,this[an]=!1,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[di]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Po]})}get bufferLength(){return this[Ni]}get encoding(){return this[jn]}set encoding(e){if(this[sn])throw new Error("cannot set encoding in objectMode");if(this[jn]&&e!==this[jn]&&(this[fs]&&this[fs].lastNeed||this[Ni]))throw new Error("cannot change encoding");this[jn]!==e&&(this[fs]=e?new kG(e):null,this[di].length&&(this[di]=this[di].map(t=>this[fs].write(t)))),this[jn]=e}setEncoding(e){this.encoding=e}get objectMode(){return this[sn]}set objectMode(e){this[sn]=this[sn]||!!e}get async(){return this[ms]}set async(e){this[ms]=this[ms]||!!e}write(e,t,i){if(this[gs])throw new Error("write after end");if(this[an])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(i=t,t="utf8"),t||(t="utf8");let r=this[ms]?mf:o=>o();return!this[sn]&&!Buffer.isBuffer(e)&&($de(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):Jde(e)?e=Buffer.from(e):typeof e!="string"&&(this.objectMode=!0)),this[sn]?(this.flowing&&this[Ni]!==0&&this[Dw](!0),this.flowing?this.emit("data",e):this[t_](e),this[Ni]!==0&&this.emit("readable"),i&&r(i),this.flowing):e.length?(typeof e=="string"&&!(t===this[jn]&&!this[fs].lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[jn]&&(e=this[fs].write(e)),this.flowing&&this[Ni]!==0&&this[Dw](!0),this.flowing?this.emit("data",e):this[t_](e),this[Ni]!==0&&this.emit("readable"),i&&r(i),this.flowing):(this[Ni]!==0&&this.emit("readable"),i&&r(i),this.flowing)}read(e){if(this[an])return null;if(this[Ni]===0||e===0||e>this[Ni])return this[ps](),null;this[sn]&&(e=null),this[di].length>1&&!this[sn]&&(this.encoding?this[di]=[this[di].join("")]:this[di]=[Buffer.concat(this[di],this[Ni])]);let t=this[PG](e||null,this[di][0]);return this[ps](),t}[PG](e,t){return e===t.length||e===null?this[i_]():(this[di][0]=t.slice(e),t=t.slice(0,e),this[Ni]-=e),this.emit("data",t),!this[di].length&&!this[gs]&&this.emit("drain"),t}end(e,t,i){return typeof e=="function"&&(i=e,e=null),typeof t=="function"&&(i=t,t="utf8"),e&&this.write(e,t),i&&this.once("end",i),this[gs]=!0,this.writable=!1,(this.flowing||!this[ff])&&this[ps](),this}[$c](){this[an]||(this[ff]=!1,this[Tw]=!0,this.emit("resume"),this[di].length?this[Dw]():this[gs]?this[ps]():this.emit("drain"))}resume(){return this[$c]()}pause(){this[Tw]=!1,this[ff]=!0}get destroyed(){return this[an]}get flowing(){return this[Tw]}get paused(){return this[ff]}[t_](e){this[sn]?this[Ni]+=1:this[Ni]+=e.length,this[di].push(e)}[i_](){return this[di].length&&(this[sn]?this[Ni]-=1:this[Ni]-=this[di][0].length),this[di].shift()}[Dw](e){do;while(this[RG](this[i_]()));!e&&!this[di].length&&!this[gs]&&this.emit("drain")}[RG](e){return e?(this.emit("data",e),this.flowing):!1}pipe(e,t){if(this[an])return;let i=this[ba];return t=t||{},e===DG.stdout||e===DG.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,i?t.end&&e.end():(this[Po].push(t.proxyErrors?new o_(this,e,t):new kw(this,e,t)),this[ms]?mf(()=>this[$c]()):this[$c]()),e}unpipe(e){let t=this[Po].find(i=>i.dest===e);t&&(this[Po].splice(this[Po].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let i=super.on(e,t);return e==="data"&&!this[Po].length&&!this.flowing?this[$c]():e==="readable"&&this[Ni]!==0?super.emit("readable"):Zde(e)&&this[ba]?(super.emit(e),this.removeAllListeners(e)):e==="error"&&this[pf]&&(this[ms]?mf(()=>t.call(this,this[pf])):t.call(this,this[pf])),i}get emittedEnd(){return this[ba]}[ps](){!this[Cw]&&!this[ba]&&!this[an]&&this[di].length===0&&this[gs]&&(this[Cw]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Sw]&&this.emit("close"),this[Cw]=!1)}emit(e,t,...i){if(e!=="error"&&e!=="close"&&e!==an&&this[an])return;if(e==="data")return t?this[ms]?mf(()=>this[n_](t)):this[n_](t):!1;if(e==="end")return this[_G]();if(e==="close"){if(this[Sw]=!0,!this[ba]&&!this[an])return;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(e==="error"){this[pf]=t;let o=super.emit("error",t);return this[ps](),o}else if(e==="resume"){let o=super.emit("resume");return this[ps](),o}else if(e==="finish"||e==="prefinish"){let o=super.emit(e);return this.removeAllListeners(e),o}let r=super.emit(e,t,...i);return this[ps](),r}[n_](e){for(let i of this[Po])i.dest.write(e)===!1&&this.pause();let t=super.emit("data",e);return this[ps](),t}[_G](){this[ba]||(this[ba]=!0,this.readable=!1,this[ms]?mf(()=>this[r_]()):this[r_]())}[r_](){if(this[fs]){let t=this[fs].end();if(t){for(let i of this[Po])i.dest.write(t);super.emit("data",t)}}for(let t of this[Po])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}collect(){let e=[];this[sn]||(e.dataLength=0);let t=this.promise();return this.on("data",i=>{e.push(i),this[sn]||(e.dataLength+=i.length)}),t.then(()=>e)}concat(){return this[sn]?Promise.reject(new Error("cannot concat in objectMode")):this.collect().then(e=>this[sn]?Promise.reject(new Error("cannot concat in objectMode")):this[jn]?e.join(""):Buffer.concat(e,e.dataLength))}promise(){return new Promise((e,t)=>{this.on(an,()=>t(new Error("stream destroyed"))),this.on("error",i=>t(i)),this.on("end",()=>e())})}[Wde](){return{next:()=>{let t=this.read();if(t!==null)return Promise.resolve({done:!1,value:t});if(this[gs])return Promise.resolve({done:!0});let i=null,r=null,o=u=>{this.removeListener("data",s),this.removeListener("end",a),r(u)},s=u=>{this.removeListener("error",o),this.removeListener("end",a),this.pause(),i({value:u,done:!!this[gs]})},a=()=>{this.removeListener("error",o),this.removeListener("data",s),i({done:!0})},l=()=>o(new Error("stream destroyed"));return new Promise((u,c)=>{r=c,i=u,this.once(an,l),this.once("error",o),this.once("end",a),this.once("data",s)})}}}[Yde](){return{next:()=>{let t=this.read();return{value:t,done:t===null}}}}destroy(e){return this[an]?(e?this.emit("error",e):this.emit(an),this):(this[an]=!0,this[di].length=0,this[Ni]=0,typeof this.close=="function"&&!this[Sw]&&this.close(),e?this.emit("error",e):this.emit(an),this)}static isStream(e){return!!e&&(e instanceof IG||e instanceof TG||e instanceof qde&&(typeof e.pipe=="function"||typeof e.write=="function"&&typeof e.end=="function"))}}});var MG=w((ZNe,FG)=>{var Ude=require("zlib").constants||{ZLIB_VERNUM:4736};FG.exports=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Ude))});var d_=w((JNe,YG)=>{"use strict";var jG=typeof process=="object"&&process?process:{stdout:null,stderr:null},Xde=require("events"),OG=require("stream"),AG=require("string_decoder").StringDecoder,bs=Symbol("EOF"),ys=Symbol("maybeEmitEnd"),ya=Symbol("emittedEnd"),Rw=Symbol("emittingEnd"),bf=Symbol("emittedError"),_w=Symbol("closed"),NG=Symbol("read"),Ew=Symbol("flush"),HG=Symbol("flushChunk"),On=Symbol("encoding"),vs=Symbol("decoder"),Iw=Symbol("flowing"),yf=Symbol("paused"),Uc=Symbol("resume"),Hi=Symbol("bufferLength"),s_=Symbol("bufferPush"),a_=Symbol("bufferShift"),ln=Symbol("objectMode"),un=Symbol("destroyed"),l_=Symbol("emitData"),BG=Symbol("emitEnd"),u_=Symbol("emitEnd2"),ws=Symbol("async"),vf=n=>Promise.resolve().then(n),qG=global._MP_NO_ITERATOR_SYMBOLS_!=="1",Gde=qG&&Symbol.asyncIterator||Symbol("asyncIterator not implemented"),zde=qG&&Symbol.iterator||Symbol("iterator not implemented"),Kde=n=>n==="end"||n==="finish"||n==="prefinish",Qde=n=>n instanceof ArrayBuffer||typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,Vde=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),Lw=class{constructor(e,t,i){this.src=e,this.dest=t,this.opts=i,this.ondrain=()=>e[Uc](),t.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},c_=class extends Lw{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,i){super(e,t,i),this.proxyErrors=r=>t.emit("error",r),e.on("error",this.proxyErrors)}};YG.exports=class WG extends OG{constructor(e){super(),this[Iw]=!1,this[yf]=!1,this.pipes=[],this.buffer=[],this[ln]=e&&e.objectMode||!1,this[ln]?this[On]=null:this[On]=e&&e.encoding||null,this[On]==="buffer"&&(this[On]=null),this[ws]=e&&!!e.async||!1,this[vs]=this[On]?new AG(this[On]):null,this[bs]=!1,this[ya]=!1,this[Rw]=!1,this[_w]=!1,this[bf]=null,this.writable=!0,this.readable=!0,this[Hi]=0,this[un]=!1}get bufferLength(){return this[Hi]}get encoding(){return this[On]}set encoding(e){if(this[ln])throw new Error("cannot set encoding in objectMode");if(this[On]&&e!==this[On]&&(this[vs]&&this[vs].lastNeed||this[Hi]))throw new Error("cannot change encoding");this[On]!==e&&(this[vs]=e?new AG(e):null,this.buffer.length&&(this.buffer=this.buffer.map(t=>this[vs].write(t)))),this[On]=e}setEncoding(e){this.encoding=e}get objectMode(){return this[ln]}set objectMode(e){this[ln]=this[ln]||!!e}get async(){return this[ws]}set async(e){this[ws]=this[ws]||!!e}write(e,t,i){if(this[bs])throw new Error("write after end");if(this[un])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(i=t,t="utf8"),t||(t="utf8");let r=this[ws]?vf:o=>o();return!this[ln]&&!Buffer.isBuffer(e)&&(Vde(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):Qde(e)?e=Buffer.from(e):typeof e!="string"&&(this.objectMode=!0)),this[ln]?(this.flowing&&this[Hi]!==0&&this[Ew](!0),this.flowing?this.emit("data",e):this[s_](e),this[Hi]!==0&&this.emit("readable"),i&&r(i),this.flowing):e.length?(typeof e=="string"&&!(t===this[On]&&!this[vs].lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[On]&&(e=this[vs].write(e)),this.flowing&&this[Hi]!==0&&this[Ew](!0),this.flowing?this.emit("data",e):this[s_](e),this[Hi]!==0&&this.emit("readable"),i&&r(i),this.flowing):(this[Hi]!==0&&this.emit("readable"),i&&r(i),this.flowing)}read(e){if(this[un])return null;if(this[Hi]===0||e===0||e>this[Hi])return this[ys](),null;this[ln]&&(e=null),this.buffer.length>1&&!this[ln]&&(this.encoding?this.buffer=[this.buffer.join("")]:this.buffer=[Buffer.concat(this.buffer,this[Hi])]);let t=this[NG](e||null,this.buffer[0]);return this[ys](),t}[NG](e,t){return e===t.length||e===null?this[a_]():(this.buffer[0]=t.slice(e),t=t.slice(0,e),this[Hi]-=e),this.emit("data",t),!this.buffer.length&&!this[bs]&&this.emit("drain"),t}end(e,t,i){return typeof e=="function"&&(i=e,e=null),typeof t=="function"&&(i=t,t="utf8"),e&&this.write(e,t),i&&this.once("end",i),this[bs]=!0,this.writable=!1,(this.flowing||!this[yf])&&this[ys](),this}[Uc](){this[un]||(this[yf]=!1,this[Iw]=!0,this.emit("resume"),this.buffer.length?this[Ew]():this[bs]?this[ys]():this.emit("drain"))}resume(){return this[Uc]()}pause(){this[Iw]=!1,this[yf]=!0}get destroyed(){return this[un]}get flowing(){return this[Iw]}get paused(){return this[yf]}[s_](e){this[ln]?this[Hi]+=1:this[Hi]+=e.length,this.buffer.push(e)}[a_](){return this.buffer.length&&(this[ln]?this[Hi]-=1:this[Hi]-=this.buffer[0].length),this.buffer.shift()}[Ew](e){do;while(this[HG](this[a_]()));!e&&!this.buffer.length&&!this[bs]&&this.emit("drain")}[HG](e){return e?(this.emit("data",e),this.flowing):!1}pipe(e,t){if(this[un])return;let i=this[ya];return t=t||{},e===jG.stdout||e===jG.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,i?t.end&&e.end():(this.pipes.push(t.proxyErrors?new c_(this,e,t):new Lw(this,e,t)),this[ws]?vf(()=>this[Uc]()):this[Uc]()),e}unpipe(e){let t=this.pipes.find(i=>i.dest===e);t&&(this.pipes.splice(this.pipes.indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let i=super.on(e,t);return e==="data"&&!this.pipes.length&&!this.flowing?this[Uc]():e==="readable"&&this[Hi]!==0?super.emit("readable"):Kde(e)&&this[ya]?(super.emit(e),this.removeAllListeners(e)):e==="error"&&this[bf]&&(this[ws]?vf(()=>t.call(this,this[bf])):t.call(this,this[bf])),i}get emittedEnd(){return this[ya]}[ys](){!this[Rw]&&!this[ya]&&!this[un]&&this.buffer.length===0&&this[bs]&&(this[Rw]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[_w]&&this.emit("close"),this[Rw]=!1)}emit(e,t,...i){if(e!=="error"&&e!=="close"&&e!==un&&this[un])return;if(e==="data")return t?this[ws]?vf(()=>this[l_](t)):this[l_](t):!1;if(e==="end")return this[BG]();if(e==="close"){if(this[_w]=!0,!this[ya]&&!this[un])return;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(e==="error"){this[bf]=t;let o=super.emit("error",t);return this[ys](),o}else if(e==="resume"){let o=super.emit("resume");return this[ys](),o}else if(e==="finish"||e==="prefinish"){let o=super.emit(e);return this.removeAllListeners(e),o}let r=super.emit(e,t,...i);return this[ys](),r}[l_](e){for(let i of this.pipes)i.dest.write(e)===!1&&this.pause();let t=super.emit("data",e);return this[ys](),t}[BG](){this[ya]||(this[ya]=!0,this.readable=!1,this[ws]?vf(()=>this[u_]()):this[u_]())}[u_](){if(this[vs]){let t=this[vs].end();if(t){for(let i of this.pipes)i.dest.write(t);super.emit("data",t)}}for(let t of this.pipes)t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}collect(){let e=[];this[ln]||(e.dataLength=0);let t=this.promise();return this.on("data",i=>{e.push(i),this[ln]||(e.dataLength+=i.length)}),t.then(()=>e)}concat(){return this[ln]?Promise.reject(new Error("cannot concat in objectMode")):this.collect().then(e=>this[ln]?Promise.reject(new Error("cannot concat in objectMode")):this[On]?e.join(""):Buffer.concat(e,e.dataLength))}promise(){return new Promise((e,t)=>{this.on(un,()=>t(new Error("stream destroyed"))),this.on("error",i=>t(i)),this.on("end",()=>e())})}[Gde](){return{next:()=>{let t=this.read();if(t!==null)return Promise.resolve({done:!1,value:t});if(this[bs])return Promise.resolve({done:!0});let i=null,r=null,o=u=>{this.removeListener("data",s),this.removeListener("end",a),r(u)},s=u=>{this.removeListener("error",o),this.removeListener("end",a),this.pause(),i({value:u,done:!!this[bs]})},a=()=>{this.removeListener("error",o),this.removeListener("data",s),i({done:!0})},l=()=>o(new Error("stream destroyed"));return new Promise((u,c)=>{r=c,i=u,this.once(un,l),this.once("error",o),this.once("end",a),this.once("data",s)})}}}[zde](){return{next:()=>{let t=this.read();return{value:t,done:t===null}}}}destroy(e){return this[un]?(e?this.emit("error",e):this.emit(un),this):(this[un]=!0,this.buffer.length=0,this[Hi]=0,typeof this.close=="function"&&!this[_w]&&this.close(),e?this.emit("error",e):this.emit(un),this)}static isStream(e){return!!e&&(e instanceof WG||e instanceof OG||e instanceof Xde&&(typeof e.pipe=="function"||typeof e.write=="function"&&typeof e.end=="function"))}}});var P_=w(Vn=>{"use strict";var m_=require("assert"),va=require("buffer").Buffer,$G=require("zlib"),Wl=Vn.constants=MG(),ehe=d_(),ZG=va.concat,Yl=Symbol("_superWrite"),Gc=class extends Error{constructor(e){super("zlib: "+e.message),this.code=e.code,this.errno=e.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+e.message,Error.captureStackTrace(this,this.constructor)}get name(){return"ZlibError"}},the=Symbol("opts"),wf=Symbol("flushFlag"),JG=Symbol("finishFlushFlag"),k_=Symbol("fullFlushFlag"),Nt=Symbol("handle"),Fw=Symbol("onError"),Xc=Symbol("sawError"),h_=Symbol("level"),g_=Symbol("strategy"),p_=Symbol("ended"),$Ne=Symbol("_defaultFullFlush"),Mw=class extends ehe{constructor(e,t){if(!e||typeof e!="object")throw new TypeError("invalid options for ZlibBase constructor");super(e),this[Xc]=!1,this[p_]=!1,this[the]=e,this[wf]=e.flush,this[JG]=e.finishFlush;try{this[Nt]=new $G[t](e)}catch(i){throw new Gc(i)}this[Fw]=i=>{this[Xc]||(this[Xc]=!0,this.close(),this.emit("error",i))},this[Nt].on("error",i=>this[Fw](new Gc(i))),this.once("end",()=>this.close)}close(){this[Nt]&&(this[Nt].close(),this[Nt]=null,this.emit("close"))}reset(){if(!this[Xc])return m_(this[Nt],"zlib binding closed"),this[Nt].reset()}flush(e){this.ended||(typeof e!="number"&&(e=this[k_]),this.write(Object.assign(va.alloc(0),{[wf]:e})))}end(e,t,i){return e&&this.write(e,t),this.flush(this[JG]),this[p_]=!0,super.end(null,null,i)}get ended(){return this[p_]}write(e,t,i){if(typeof t=="function"&&(i=t,t="utf8"),typeof e=="string"&&(e=va.from(e,t)),this[Xc])return;m_(this[Nt],"zlib binding closed");let r=this[Nt]._handle,o=r.close;r.close=()=>{};let s=this[Nt].close;this[Nt].close=()=>{},va.concat=u=>u;let a;try{let u=typeof e[wf]=="number"?e[wf]:this[wf];a=this[Nt]._processChunk(e,u),va.concat=ZG}catch(u){va.concat=ZG,this[Fw](new Gc(u))}finally{this[Nt]&&(this[Nt]._handle=r,r.close=o,this[Nt].close=s,this[Nt].removeAllListeners("error"))}this[Nt]&&this[Nt].on("error",u=>this[Fw](new Gc(u)));let l;if(a)if(Array.isArray(a)&&a.length>0){l=this[Yl](va.from(a[0]));for(let u=1;u{this.flush(r),o()};try{this[Nt].params(e,t)}finally{this[Nt].flush=i}this[Nt]&&(this[h_]=e,this[g_]=t)}}}},b_=class extends xs{constructor(e){super(e,"Deflate")}},y_=class extends xs{constructor(e){super(e,"Inflate")}},f_=Symbol("_portable"),v_=class extends xs{constructor(e){super(e,"Gzip"),this[f_]=e&&!!e.portable}[Yl](e){return this[f_]?(this[f_]=!1,e[9]=255,super[Yl](e)):super[Yl](e)}},w_=class extends xs{constructor(e){super(e,"Gunzip")}},x_=class extends xs{constructor(e){super(e,"DeflateRaw")}},C_=class extends xs{constructor(e){super(e,"InflateRaw")}},S_=class extends xs{constructor(e){super(e,"Unzip")}},jw=class extends Mw{constructor(e,t){e=e||{},e.flush=e.flush||Wl.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||Wl.BROTLI_OPERATION_FINISH,super(e,t),this[k_]=Wl.BROTLI_OPERATION_FLUSH}},D_=class extends jw{constructor(e){super(e,"BrotliCompress")}},T_=class extends jw{constructor(e){super(e,"BrotliDecompress")}};Vn.Deflate=b_;Vn.Inflate=y_;Vn.Gzip=v_;Vn.Gunzip=w_;Vn.DeflateRaw=x_;Vn.InflateRaw=C_;Vn.Unzip=S_;typeof $G.BrotliCompress=="function"?(Vn.BrotliCompress=D_,Vn.BrotliDecompress=T_):Vn.BrotliCompress=Vn.BrotliDecompress=class{constructor(){throw new Error("Brotli is not supported in this version of Node.js")}}});var zc=w((GNe,UG)=>{var ihe=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;UG.exports=ihe!=="win32"?n=>n:n=>n&&n.replace(/\\/g,"/")});var Ow=w((KNe,XG)=>{"use strict";var nhe=Pw(),R_=zc(),__=Symbol("slurp");XG.exports=class extends nhe{constructor(e,t,i){switch(super(),this.pause(),this.extended=t,this.globalExtended=i,this.header=e,this.startBlockSize=512*Math.ceil(e.size/512),this.blockRemain=this.startBlockSize,this.remain=e.size,this.type=e.type,this.meta=!1,this.ignore=!1,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}this.path=R_(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=e.size,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=R_(e.linkpath),this.uname=e.uname,this.gname=e.gname,t&&this[__](t),i&&this[__](i,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,r=this.blockRemain;return this.remain=Math.max(0,i-t),this.blockRemain=Math.max(0,r-t),this.ignore?!0:i>=t?super.write(e):super.write(e.slice(0,i))}[__](e,t){for(let i in e)e[i]!==null&&e[i]!==void 0&&!(t&&i==="path")&&(this[i]=i==="path"||i==="linkpath"?R_(e[i]):e[i])}}});var E_=w(Aw=>{"use strict";Aw.name=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]);Aw.code=new Map(Array.from(Aw.name).map(n=>[n[1],n[0]]))});var QG=w((VNe,KG)=>{"use strict";var rhe=(n,e)=>{if(Number.isSafeInteger(n))n<0?she(n,e):ohe(n,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},ohe=(n,e)=>{e[0]=128;for(var t=e.length;t>1;t--)e[t-1]=n&255,n=Math.floor(n/256)},she=(n,e)=>{e[0]=255;var t=!1;n=n*-1;for(var i=e.length;i>1;i--){var r=n&255;n=Math.floor(n/256),t?e[i-1]=GG(r):r===0?e[i-1]=0:(t=!0,e[i-1]=zG(r))}},ahe=n=>{let e=n[0],t=e===128?uhe(n.slice(1,n.length)):e===255?lhe(n):null;if(t===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(t))throw Error("parsed number outside of javascript safe integer range");return t},lhe=n=>{for(var e=n.length,t=0,i=!1,r=e-1;r>-1;r--){var o=n[r],s;i?s=GG(o):o===0?s=o:(i=!0,s=zG(o)),s!==0&&(t-=s*Math.pow(256,e-r-1))}return t},uhe=n=>{for(var e=n.length,t=0,i=e-1;i>-1;i--){var r=n[i];r!==0&&(t+=r*Math.pow(256,e-i-1))}return t},GG=n=>(255^n)&255,zG=n=>(255^n)+1&255;KG.exports={encode:rhe,parse:ahe}});var Qc=w((eHe,ez)=>{"use strict";var I_=E_(),Kc=require("path").posix,VG=QG(),L_=Symbol("slurp"),er=Symbol("type"),j_=class{constructor(e,t,i,r){this.cksumValid=!1,this.needPax=!1,this.nullBlock=!1,this.block=null,this.path=null,this.mode=null,this.uid=null,this.gid=null,this.size=null,this.mtime=null,this.cksum=null,this[er]="0",this.linkpath=null,this.uname=null,this.gname=null,this.devmaj=0,this.devmin=0,this.atime=null,this.ctime=null,Buffer.isBuffer(e)?this.decode(e,t||0,i,r):e&&this.set(e)}decode(e,t,i,r){if(t||(t=0),!e||!(e.length>=t+512))throw new Error("need 512 bytes for header");if(this.path=Zl(e,t,100),this.mode=wa(e,t+100,8),this.uid=wa(e,t+108,8),this.gid=wa(e,t+116,8),this.size=wa(e,t+124,12),this.mtime=F_(e,t+136,12),this.cksum=wa(e,t+148,12),this[L_](i),this[L_](r,!0),this[er]=Zl(e,t+156,1),this[er]===""&&(this[er]="0"),this[er]==="0"&&this.path.slice(-1)==="/"&&(this[er]="5"),this[er]==="5"&&(this.size=0),this.linkpath=Zl(e,t+157,100),e.slice(t+257,t+265).toString()==="ustar\x0000")if(this.uname=Zl(e,t+265,32),this.gname=Zl(e,t+297,32),this.devmaj=wa(e,t+329,8),this.devmin=wa(e,t+337,8),e[t+475]!==0){let s=Zl(e,t+345,155);this.path=s+"/"+this.path}else{let s=Zl(e,t+345,130);s&&(this.path=s+"/"+this.path),this.atime=F_(e,t+476,12),this.ctime=F_(e,t+488,12)}let o=8*32;for(let s=t;s=t+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,r=che(this.path||"",i),o=r[0],s=r[1];this.needPax=r[2],this.needPax=Jl(e,t,100,o)||this.needPax,this.needPax=xa(e,t+100,8,this.mode)||this.needPax,this.needPax=xa(e,t+108,8,this.uid)||this.needPax,this.needPax=xa(e,t+116,8,this.gid)||this.needPax,this.needPax=xa(e,t+124,12,this.size)||this.needPax,this.needPax=M_(e,t+136,12,this.mtime)||this.needPax,e[t+156]=this[er].charCodeAt(0),this.needPax=Jl(e,t+157,100,this.linkpath)||this.needPax,e.write("ustar\x0000",t+257,8),this.needPax=Jl(e,t+265,32,this.uname)||this.needPax,this.needPax=Jl(e,t+297,32,this.gname)||this.needPax,this.needPax=xa(e,t+329,8,this.devmaj)||this.needPax,this.needPax=xa(e,t+337,8,this.devmin)||this.needPax,this.needPax=Jl(e,t+345,i,s)||this.needPax,e[t+475]!==0?this.needPax=Jl(e,t+345,155,s)||this.needPax:(this.needPax=Jl(e,t+345,130,s)||this.needPax,this.needPax=M_(e,t+476,12,this.atime)||this.needPax,this.needPax=M_(e,t+488,12,this.ctime)||this.needPax);let a=8*32;for(let l=t;l{let i=n,r="",o,s=Kc.parse(n).root||".";if(Buffer.byteLength(i)<100)o=[i,r,!1];else{r=Kc.dirname(i),i=Kc.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(r)<=e?o=[i,r,!1]:Buffer.byteLength(i)>100&&Buffer.byteLength(r)<=e?o=[i.slice(0,100-1),r,!0]:(i=Kc.join(Kc.basename(r),i),r=Kc.dirname(r));while(r!==s&&!o);o||(o=[n.slice(0,100-1),"",!0])}return o},Zl=(n,e,t)=>n.slice(e,e+t).toString("utf8").replace(/\0.*/,""),F_=(n,e,t)=>dhe(wa(n,e,t)),dhe=n=>n===null?null:new Date(n*1e3),wa=(n,e,t)=>n[e]&128?VG.parse(n.slice(e,e+t)):ghe(n,e,t),hhe=n=>isNaN(n)?null:n,ghe=(n,e,t)=>hhe(parseInt(n.slice(e,e+t).toString("utf8").replace(/\0.*$/,"").trim(),8)),phe={12:8589934591,8:2097151},xa=(n,e,t,i)=>i===null?!1:i>phe[t]||i<0?(VG.encode(i,n.slice(e,e+t)),!0):(fhe(n,e,t,i),!1),fhe=(n,e,t,i)=>n.write(mhe(i,t),e,t,"ascii"),mhe=(n,e)=>bhe(Math.floor(n).toString(8),e),bhe=(n,e)=>(n.length===e-1?n:new Array(e-n.length-1).join("0")+n+" ")+"\0",M_=(n,e,t,i)=>i===null?!1:xa(n,e,t,i.getTime()/1e3),yhe=new Array(156).join("\0"),Jl=(n,e,t,i)=>i===null?!1:(n.write(i+yhe,e,t,"utf8"),i.length!==Buffer.byteLength(i)||i.length>t);ez.exports=j_});var Nw=w((tHe,tz)=>{"use strict";var vhe=Qc(),whe=require("path"),xf=class{constructor(e,t){this.atime=e.atime||null,this.charset=e.charset||null,this.comment=e.comment||null,this.ctime=e.ctime||null,this.gid=e.gid||null,this.gname=e.gname||null,this.linkpath=e.linkpath||null,this.mtime=e.mtime||null,this.path=e.path||null,this.size=e.size||null,this.uid=e.uid||null,this.uname=e.uname||null,this.dev=e.dev||null,this.ino=e.ino||null,this.nlink=e.nlink||null,this.global=t||!1}encode(){let e=this.encodeBody();if(e==="")return null;let t=Buffer.byteLength(e),i=512*Math.ceil(1+t/512),r=Buffer.allocUnsafe(i);for(let o=0;o<512;o++)r[o]=0;new vhe({path:("PaxHeader/"+whe.basename(this.path)).slice(0,99),mode:this.mode||420,uid:this.uid||null,gid:this.gid||null,size:t,mtime:this.mtime||null,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime||null,ctime:this.ctime||null}).encode(r),r.write(e,512,t,"utf8");for(let o=t+512;o=Math.pow(10,o)&&(o+=1),o+r+i}};xf.parse=(n,e,t)=>new xf(xhe(Che(n),e),t);var xhe=(n,e)=>e?Object.keys(n).reduce((t,i)=>(t[i]=n[i],t),e):n,Che=n=>n.replace(/\n$/,"").split(` +`).reduce(She,Object.create(null)),She=(n,e)=>{let t=parseInt(e,10);if(t!==Buffer.byteLength(e)+1)return n;e=e.slice((t+" ").length);let i=e.split("="),r=i.shift().replace(/^SCHILY\.(dev|ino|nlink)/,"$1");if(!r)return n;let o=i.join("=");return n[r]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(r)?new Date(o*1e3):/^[0-9]+$/.test(o)?+o:o,n};tz.exports=xf});var Vc=w((iHe,iz)=>{iz.exports=n=>{let e=n.length-1,t=-1;for(;e>-1&&n.charAt(e)==="/";)t=e,e--;return t===-1?n:n.slice(0,t)}});var Hw=w((nHe,nz)=>{"use strict";nz.exports=n=>class extends n{warn(e,t,i={}){this.file&&(i.file=this.file),this.cwd&&(i.cwd=this.cwd),i.code=t instanceof Error&&t.code||e,i.tarCode=e,!this.strict&&i.recoverable!==!1?(t instanceof Error&&(i=Object.assign(t,i),t=t.message),this.emit("warn",i.tarCode,t,i)):t instanceof Error?this.emit("error",Object.assign(t,i)):this.emit("error",Object.assign(new Error(`${e}: ${t}`),i))}}});var A_=w((oHe,rz)=>{"use strict";var Bw=["|","<",">","?",":"],O_=Bw.map(n=>String.fromCharCode(61440+n.charCodeAt(0))),Dhe=new Map(Bw.map((n,e)=>[n,O_[e]])),The=new Map(O_.map((n,e)=>[n,Bw[e]]));rz.exports={encode:n=>Bw.reduce((e,t)=>e.split(t).join(Dhe.get(t)),n),decode:n=>O_.reduce((e,t)=>e.split(t).join(The.get(t)),n)}});var N_=w((sHe,sz)=>{var{isAbsolute:khe,parse:oz}=require("path").win32;sz.exports=n=>{let e="",t=oz(n);for(;khe(n)||t.root;){let i=n.charAt(0)==="/"&&n.slice(0,4)!=="//?/"?"/":t.root;n=n.slice(i.length),e+=i,t=oz(n)}return[e,n]}});var lz=w((aHe,az)=>{"use strict";az.exports=(n,e,t)=>(n&=4095,t&&(n=(n|384)&-19),e&&(n&256&&(n|=64),n&32&&(n|=8),n&4&&(n|=1)),n)});var X_=w((cHe,Cz)=>{"use strict";var fz=Pw(),mz=Nw(),bz=Qc(),_o=require("fs"),uz=require("path"),Ro=zc(),Phe=Vc(),yz=(n,e)=>e?(n=Ro(n).replace(/^\.(\/|$)/,""),Phe(e)+"/"+n):Ro(n),Rhe=16*1024*1024,cz=Symbol("process"),dz=Symbol("file"),hz=Symbol("directory"),B_=Symbol("symlink"),gz=Symbol("hardlink"),Cf=Symbol("header"),qw=Symbol("read"),q_=Symbol("lstat"),Ww=Symbol("onlstat"),W_=Symbol("onread"),Y_=Symbol("onreadlink"),Z_=Symbol("openfile"),J_=Symbol("onopenfile"),Ca=Symbol("close"),Yw=Symbol("mode"),$_=Symbol("awaitDrain"),H_=Symbol("ondrain"),Eo=Symbol("prefix"),pz=Symbol("hadError"),vz=Hw(),_he=A_(),wz=N_(),xz=lz(),Zw=vz(class extends fz{constructor(e,t){if(t=t||{},super(t),typeof e!="string")throw new TypeError("path is required");this.path=Ro(e),this.portable=!!t.portable,this.myuid=process.getuid&&process.getuid()||0,this.myuser=process.env.USER||"",this.maxReadSize=t.maxReadSize||Rhe,this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.preservePaths=!!t.preservePaths,this.cwd=Ro(t.cwd||process.cwd()),this.strict=!!t.strict,this.noPax=!!t.noPax,this.noMtime=!!t.noMtime,this.mtime=t.mtime||null,this.prefix=t.prefix?Ro(t.prefix):null,this.fd=null,this.blockLen=null,this.blockRemain=null,this.buf=null,this.offset=null,this.length=null,this.pos=null,this.remain=null,typeof t.onwarn=="function"&&this.on("warn",t.onwarn);let i=!1;if(!this.preservePaths){let[r,o]=wz(this.path);r&&(this.path=o,i=r)}this.win32=!!t.win32||process.platform==="win32",this.win32&&(this.path=_he.decode(this.path.replace(/\\/g,"/")),e=e.replace(/\\/g,"/")),this.absolute=Ro(t.absolute||uz.resolve(this.cwd,e)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.statCache.has(this.absolute)?this[Ww](this.statCache.get(this.absolute)):this[q_]()}emit(e,...t){return e==="error"&&(this[pz]=!0),super.emit(e,...t)}[q_](){_o.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[Ww](t)})}[Ww](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=Ihe(e),this.emit("stat",e),this[cz]()}[cz](){switch(this.type){case"File":return this[dz]();case"Directory":return this[hz]();case"SymbolicLink":return this[B_]();default:return this.end()}}[Yw](e){return xz(e,this.type==="Directory",this.portable)}[Eo](e){return yz(e,this.prefix)}[Cf](){this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.header=new bz({path:this[Eo](this.path),linkpath:this.type==="Link"?this[Eo](this.linkpath):this.linkpath,mode:this[Yw](this.stat.mode),uid:this.portable?null:this.stat.uid,gid:this.portable?null:this.stat.gid,size:this.stat.size,mtime:this.noMtime?null:this.mtime||this.stat.mtime,type:this.type,uname:this.portable?null:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?null:this.stat.atime,ctime:this.portable?null:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new mz({atime:this.portable?null:this.header.atime,ctime:this.portable?null:this.header.ctime,gid:this.portable?null:this.header.gid,mtime:this.noMtime?null:this.mtime||this.header.mtime,path:this[Eo](this.path),linkpath:this.type==="Link"?this[Eo](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?null:this.header.uid,uname:this.portable?null:this.header.uname,dev:this.portable?null:this.stat.dev,ino:this.portable?null:this.stat.ino,nlink:this.portable?null:this.stat.nlink}).encode()),super.write(this.header.block)}[hz](){this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Cf](),this.end()}[B_](){_o.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[Y_](t)})}[Y_](e){this.linkpath=Ro(e),this[Cf](),this.end()}[gz](e){this.type="Link",this.linkpath=Ro(uz.relative(this.cwd,e)),this.stat.size=0,this[Cf](),this.end()}[dz](){if(this.stat.nlink>1){let e=this.stat.dev+":"+this.stat.ino;if(this.linkCache.has(e)){let t=this.linkCache.get(e);if(t.indexOf(this.cwd)===0)return this[gz](t)}this.linkCache.set(e,this.absolute)}if(this[Cf](),this.stat.size===0)return this.end();this[Z_]()}[Z_](){_o.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[J_](t)})}[J_](e){if(this.fd=e,this[pz])return this[Ca]();this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[qw]()}[qw](){let{fd:e,buf:t,offset:i,length:r,pos:o}=this;_o.read(e,t,i,r,o,(s,a)=>{if(s)return this[Ca](()=>this.emit("error",s));this[W_](a)})}[Ca](e){_o.close(this.fd,e)}[W_](e){if(e<=0&&this.remain>0){let r=new Error("encountered unexpected EOF");return r.path=this.absolute,r.syscall="read",r.code="EOF",this[Ca](()=>this.emit("error",r))}if(e>this.remain){let r=new Error("did not encounter expected EOF");return r.path=this.absolute,r.syscall="read",r.code="EOF",this[Ca](()=>this.emit("error",r))}if(e===this.remain)for(let r=e;rthis[H_]())}[$_](e){this.once("drain",e)}write(e){if(this.blockRemaine?this.emit("error",e):this.end());this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[qw]()}}),U_=class extends Zw{[q_](){this[Ww](_o.lstatSync(this.absolute))}[B_](){this[Y_](_o.readlinkSync(this.absolute))}[Z_](){this[J_](_o.openSync(this.absolute,"r"))}[qw](){let e=!0;try{let{fd:t,buf:i,offset:r,length:o,pos:s}=this,a=_o.readSync(t,i,r,o,s);this[W_](a),e=!1}finally{if(e)try{this[Ca](()=>{})}catch{}}}[$_](e){e()}[Ca](e){_o.closeSync(this.fd),e()}},Ehe=vz(class extends fz{constructor(e,t){t=t||{},super(t),this.preservePaths=!!t.preservePaths,this.portable=!!t.portable,this.strict=!!t.strict,this.noPax=!!t.noPax,this.noMtime=!!t.noMtime,this.readEntry=e,this.type=e.type,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=t.prefix||null,this.path=Ro(e.path),this.mode=this[Yw](e.mode),this.uid=this.portable?null:e.uid,this.gid=this.portable?null:e.gid,this.uname=this.portable?null:e.uname,this.gname=this.portable?null:e.gname,this.size=e.size,this.mtime=this.noMtime?null:t.mtime||e.mtime,this.atime=this.portable?null:e.atime,this.ctime=this.portable?null:e.ctime,this.linkpath=Ro(e.linkpath),typeof t.onwarn=="function"&&this.on("warn",t.onwarn);let i=!1;if(!this.preservePaths){let[r,o]=wz(this.path);r&&(this.path=o,i=r)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.header=new bz({path:this[Eo](this.path),linkpath:this.type==="Link"?this[Eo](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?null:this.uid,gid:this.portable?null:this.gid,size:this.size,mtime:this.noMtime?null:this.mtime,type:this.type,uname:this.portable?null:this.uname,atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new mz({atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime,gid:this.portable?null:this.gid,mtime:this.noMtime?null:this.mtime,path:this[Eo](this.path),linkpath:this.type==="Link"?this[Eo](this.linkpath):this.linkpath,size:this.size,uid:this.portable?null:this.uid,uname:this.portable?null:this.uname,dev:this.portable?null:this.readEntry.dev,ino:this.portable?null:this.readEntry.ino,nlink:this.portable?null:this.readEntry.nlink}).encode()),super.write(this.header.block),e.pipe(this)}[Eo](e){return yz(e,this.prefix)}[Yw](e){return xz(e,this.type==="Directory",this.portable)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=t,super.write(e)}end(){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),super.end()}});Zw.Sync=U_;Zw.Tar=Ehe;var Ihe=n=>n.isFile()?"File":n.isDirectory()?"Directory":n.isSymbolicLink()?"SymbolicLink":"Unsupported";Cz.exports=Zw});var Vw=w((hHe,_z)=>{"use strict";var Kw=class{constructor(e,t){this.path=e||"./",this.absolute=t,this.entry=null,this.stat=null,this.readdir=null,this.pending=!1,this.ignore=!1,this.piped=!1}},Lhe=Pw(),Fhe=P_(),Mhe=Ow(),nE=X_(),jhe=nE.Sync,Ohe=nE.Tar,Ahe=Ib(),Sz=Buffer.alloc(1024),Uw=Symbol("onStat"),Jw=Symbol("ended"),Io=Symbol("queue"),ed=Symbol("current"),$l=Symbol("process"),$w=Symbol("processing"),Dz=Symbol("processJob"),Lo=Symbol("jobs"),G_=Symbol("jobDone"),Xw=Symbol("addFSEntry"),Tz=Symbol("addTarEntry"),V_=Symbol("stat"),eE=Symbol("readdir"),Gw=Symbol("onreaddir"),zw=Symbol("pipe"),kz=Symbol("entry"),z_=Symbol("entryOpt"),tE=Symbol("writeEntryClass"),Rz=Symbol("write"),K_=Symbol("ondrain"),Qw=require("fs"),Pz=require("path"),Nhe=Hw(),Q_=zc(),rE=Nhe(class extends Lhe{constructor(e){super(e),e=e||Object.create(null),this.opt=e,this.file=e.file||"",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=Q_(e.prefix||""),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this[tE]=nE,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),this.portable=!!e.portable,this.zip=null,e.gzip?(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new Fhe.Gzip(e.gzip),this.zip.on("data",t=>super.write(t)),this.zip.on("end",t=>super.end()),this.zip.on("drain",t=>this[K_]()),this.on("resume",t=>this.zip.resume())):this.on("drain",this[K_]),this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,this.mtime=e.mtime||null,this.filter=typeof e.filter=="function"?e.filter:t=>!0,this[Io]=new Ahe,this[Lo]=0,this.jobs=+e.jobs||4,this[$w]=!1,this[Jw]=!1}[Rz](e){return super.write(e)}add(e){return this.write(e),this}end(e){return e&&this.write(e),this[Jw]=!0,this[$l](),this}write(e){if(this[Jw])throw new Error("write after end");return e instanceof Mhe?this[Tz](e):this[Xw](e),this.flowing}[Tz](e){let t=Q_(Pz.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let i=new Kw(e.path,t,!1);i.entry=new Ohe(e,this[z_](i)),i.entry.on("end",r=>this[G_](i)),this[Lo]+=1,this[Io].push(i)}this[$l]()}[Xw](e){let t=Q_(Pz.resolve(this.cwd,e));this[Io].push(new Kw(e,t)),this[$l]()}[V_](e){e.pending=!0,this[Lo]+=1;let t=this.follow?"stat":"lstat";Qw[t](e.absolute,(i,r)=>{e.pending=!1,this[Lo]-=1,i?this.emit("error",i):this[Uw](e,r)})}[Uw](e,t){this.statCache.set(e.absolute,t),e.stat=t,this.filter(e.path,t)||(e.ignore=!0),this[$l]()}[eE](e){e.pending=!0,this[Lo]+=1,Qw.readdir(e.absolute,(t,i)=>{if(e.pending=!1,this[Lo]-=1,t)return this.emit("error",t);this[Gw](e,i)})}[Gw](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[$l]()}[$l](){if(!this[$w]){this[$w]=!0;for(let e=this[Io].head;e!==null&&this[Lo]this.warn(t,i,r),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix}}[kz](e){this[Lo]+=1;try{return new this[tE](e.path,this[z_](e)).on("end",()=>this[G_](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[K_](){this[ed]&&this[ed].entry&&this[ed].entry.resume()}[zw](e){e.piped=!0,e.readdir&&e.readdir.forEach(r=>{let o=e.path,s=o==="./"?"":o.replace(/\/*$/,"/");this[Xw](s+r)});let t=e.entry,i=this.zip;i?t.on("data",r=>{i.write(r)||t.pause()}):t.on("data",r=>{super.write(r)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}}),iE=class extends rE{constructor(e){super(e),this[tE]=jhe}pause(){}resume(){}[V_](e){let t=this.follow?"statSync":"lstatSync";this[Uw](e,Qw[t](e.absolute))}[eE](e,t){this[Gw](e,Qw.readdirSync(e.absolute))}[zw](e){let t=e.entry,i=this.zip;e.readdir&&e.readdir.forEach(r=>{let o=e.path,s=o==="./"?"":o.replace(/\/*$/,"/");this[Xw](s+r)}),i?t.on("data",r=>{i.write(r)}):t.on("data",r=>{super[Rz](r)})}};rE.Sync=iE;_z.exports=rE});var ld=w(Df=>{"use strict";var Hhe=d_(),Bhe=require("events").EventEmitter,An=require("fs"),aE=An.writev;if(!aE){let n=process.binding("fs"),e=n.FSReqWrap||n.FSReqCallback;aE=(t,i,r,o)=>{let s=(l,u)=>o(l,u,i),a=new e;a.oncomplete=s,n.writeBuffers(t,i,r,a)}}var sd=Symbol("_autoClose"),no=Symbol("_close"),Sf=Symbol("_ended"),It=Symbol("_fd"),Ez=Symbol("_finished"),Da=Symbol("_flags"),oE=Symbol("_flush"),lE=Symbol("_handleChunk"),uE=Symbol("_makeBuf"),rx=Symbol("_mode"),ex=Symbol("_needDrain"),rd=Symbol("_onerror"),ad=Symbol("_onopen"),sE=Symbol("_onread"),id=Symbol("_onwrite"),Ta=Symbol("_open"),Cs=Symbol("_path"),Ul=Symbol("_pos"),Fo=Symbol("_queue"),nd=Symbol("_read"),Iz=Symbol("_readSize"),Sa=Symbol("_reading"),tx=Symbol("_remain"),Lz=Symbol("_size"),ix=Symbol("_write"),td=Symbol("_writing"),nx=Symbol("_defaultFlag"),od=Symbol("_errored"),ox=class extends Hhe{constructor(e,t){if(t=t||{},super(t),this.readable=!0,this.writable=!1,typeof e!="string")throw new TypeError("path must be a string");this[od]=!1,this[It]=typeof t.fd=="number"?t.fd:null,this[Cs]=e,this[Iz]=t.readSize||16*1024*1024,this[Sa]=!1,this[Lz]=typeof t.size=="number"?t.size:1/0,this[tx]=this[Lz],this[sd]=typeof t.autoClose=="boolean"?t.autoClose:!0,typeof this[It]=="number"?this[nd]():this[Ta]()}get fd(){return this[It]}get path(){return this[Cs]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Ta](){An.open(this[Cs],"r",(e,t)=>this[ad](e,t))}[ad](e,t){e?this[rd](e):(this[It]=t,this.emit("open",t),this[nd]())}[uE](){return Buffer.allocUnsafe(Math.min(this[Iz],this[tx]))}[nd](){if(!this[Sa]){this[Sa]=!0;let e=this[uE]();if(e.length===0)return process.nextTick(()=>this[sE](null,0,e));An.read(this[It],e,0,e.length,null,(t,i,r)=>this[sE](t,i,r))}}[sE](e,t,i){this[Sa]=!1,e?this[rd](e):this[lE](t,i)&&this[nd]()}[no](){if(this[sd]&&typeof this[It]=="number"){let e=this[It];this[It]=null,An.close(e,t=>t?this.emit("error",t):this.emit("close"))}}[rd](e){this[Sa]=!0,this[no](),this.emit("error",e)}[lE](e,t){let i=!1;return this[tx]-=e,e>0&&(i=super.write(ethis[ad](e,t))}[ad](e,t){this[nx]&&this[Da]==="r+"&&e&&e.code==="ENOENT"?(this[Da]="w",this[Ta]()):e?this[rd](e):(this[It]=t,this.emit("open",t),this[oE]())}end(e,t){return e&&this.write(e,t),this[Sf]=!0,!this[td]&&!this[Fo].length&&typeof this[It]=="number"&&this[id](null,0),this}write(e,t){return typeof e=="string"&&(e=Buffer.from(e,t)),this[Sf]?(this.emit("error",new Error("write() after end()")),!1):this[It]===null||this[td]||this[Fo].length?(this[Fo].push(e),this[ex]=!0,!1):(this[td]=!0,this[ix](e),!0)}[ix](e){An.write(this[It],e,0,e.length,this[Ul],(t,i)=>this[id](t,i))}[id](e,t){e?this[rd](e):(this[Ul]!==null&&(this[Ul]+=t),this[Fo].length?this[oE]():(this[td]=!1,this[Sf]&&!this[Ez]?(this[Ez]=!0,this[no](),this.emit("finish")):this[ex]&&(this[ex]=!1,this.emit("drain"))))}[oE](){if(this[Fo].length===0)this[Sf]&&this[id](null,0);else if(this[Fo].length===1)this[ix](this[Fo].pop());else{let e=this[Fo];this[Fo]=[],aE(this[It],e,this[Ul],(t,i)=>this[id](t,i))}}[no](){if(this[sd]&&typeof this[It]=="number"){let e=this[It];this[It]=null,An.close(e,t=>t?this.emit("error",t):this.emit("close"))}}},dE=class extends sx{[Ta](){let e;if(this[nx]&&this[Da]==="r+")try{e=An.openSync(this[Cs],this[Da],this[rx])}catch(t){if(t.code==="ENOENT")return this[Da]="w",this[Ta]();throw t}else e=An.openSync(this[Cs],this[Da],this[rx]);this[ad](null,e)}[no](){if(this[sd]&&typeof this[It]=="number"){let e=this[It];this[It]=null,An.closeSync(e),this.emit("close")}}[ix](e){let t=!0;try{this[id](null,An.writeSync(this[It],e,0,e.length,this[Ul])),t=!1}finally{if(t)try{this[no]()}catch{}}}};Df.ReadStream=ox;Df.ReadStreamSync=cE;Df.WriteStream=sx;Df.WriteStreamSync=dE});var gx=w((fHe,Bz)=>{"use strict";var qhe=Hw(),Whe=Qc(),Yhe=require("events"),Zhe=Ib(),Jhe=1024*1024,$he=Ow(),Fz=Nw(),Uhe=P_(),{nextTick:Xhe}=require("process"),hE=Buffer.from([31,139]),Cr=Symbol("state"),Xl=Symbol("writeEntry"),Ss=Symbol("readEntry"),gE=Symbol("nextEntry"),Mz=Symbol("processEntry"),Sr=Symbol("extendedHeader"),Tf=Symbol("globalExtendedHeader"),ka=Symbol("meta"),jz=Symbol("emitMeta"),Zt=Symbol("buffer"),Ds=Symbol("queue"),Gl=Symbol("ended"),Oz=Symbol("emittedEnd"),zl=Symbol("emit"),Nn=Symbol("unzip"),ax=Symbol("consumeChunk"),lx=Symbol("consumeChunkSub"),pE=Symbol("consumeBody"),Az=Symbol("consumeMeta"),Nz=Symbol("consumeHeader"),ux=Symbol("consuming"),fE=Symbol("bufferConcat"),mE=Symbol("maybeEnd"),kf=Symbol("writing"),Pa=Symbol("aborted"),cx=Symbol("onDone"),Kl=Symbol("sawValidEntry"),dx=Symbol("sawNullBlock"),hx=Symbol("sawEOF"),Hz=Symbol("closeStream"),Ghe=n=>!0;Bz.exports=qhe(class extends Yhe{constructor(e){e=e||{},super(e),this.file=e.file||"",this[Kl]=null,this.on(cx,t=>{(this[Cr]==="begin"||this[Kl]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(cx,e.ondone):this.on(cx,t=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||Jhe,this.filter=typeof e.filter=="function"?e.filter:Ghe,this.writable=!0,this.readable=!1,this[Ds]=new Zhe,this[Zt]=null,this[Ss]=null,this[Xl]=null,this[Cr]="begin",this[ka]="",this[Sr]=null,this[Tf]=null,this[Gl]=!1,this[Nn]=null,this[Pa]=!1,this[dx]=!1,this[hx]=!1,this.on("end",()=>this[Hz]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onentry=="function"&&this.on("entry",e.onentry)}[Nz](e,t){this[Kl]===null&&(this[Kl]=!1);let i;try{i=new Whe(e,t,this[Sr],this[Tf])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(i.nullBlock)this[dx]?(this[hx]=!0,this[Cr]==="begin"&&(this[Cr]="header"),this[zl]("eof")):(this[dx]=!0,this[zl]("nullBlock"));else if(this[dx]=!1,!i.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:i});else if(!i.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:i});else{let r=i.type;if(/^(Symbolic)?Link$/.test(r)&&!i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:i});else if(!/^(Symbolic)?Link$/.test(r)&&i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:i});else{let o=this[Xl]=new $he(i,this[Sr],this[Tf]);if(!this[Kl])if(o.remain){let s=()=>{o.invalid||(this[Kl]=!0)};o.on("end",s)}else this[Kl]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[zl]("ignoredEntry",o),this[Cr]="ignore",o.resume()):o.size>0&&(this[ka]="",o.on("data",s=>this[ka]+=s),this[Cr]="meta"):(this[Sr]=null,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zl]("ignoredEntry",o),this[Cr]=o.remain?"ignore":"header",o.resume()):(o.remain?this[Cr]="body":(this[Cr]="header",o.end()),this[Ss]?this[Ds].push(o):(this[Ds].push(o),this[gE]())))}}}[Hz](){Xhe(()=>this.emit("close"))}[Mz](e){let t=!0;return e?Array.isArray(e)?this.emit.apply(this,e):(this[Ss]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",i=>this[gE]()),t=!1)):(this[Ss]=null,t=!1),t}[gE](){do;while(this[Mz](this[Ds].shift()));if(!this[Ds].length){let e=this[Ss];!e||e.flowing||e.size===e.remain?this[kf]||this.emit("drain"):e.once("drain",i=>this.emit("drain"))}}[pE](e,t){let i=this[Xl],r=i.blockRemain,o=r>=e.length&&t===0?e:e.slice(t,t+r);return i.write(o),i.blockRemain||(this[Cr]="header",this[Xl]=null,i.end()),o.length}[Az](e,t){let i=this[Xl],r=this[pE](e,t);return this[Xl]||this[jz](i),r}[zl](e,t,i){!this[Ds].length&&!this[Ss]?this.emit(e,t,i):this[Ds].push([e,t,i])}[jz](e){switch(this[zl]("meta",this[ka]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[Sr]=Fz.parse(this[ka],this[Sr],!1);break;case"GlobalExtendedHeader":this[Tf]=Fz.parse(this[ka],this[Tf],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":this[Sr]=this[Sr]||Object.create(null),this[Sr].path=this[ka].replace(/\0.*/,"");break;case"NextFileHasLongLinkpath":this[Sr]=this[Sr]||Object.create(null),this[Sr].linkpath=this[ka].replace(/\0.*/,"");break;default:throw new Error("unknown meta: "+e.type)}}abort(e){this[Pa]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}write(e){if(this[Pa])return;if(this[Nn]===null&&e){if(this[Zt]&&(e=Buffer.concat([this[Zt],e]),this[Zt]=null),e.lengththis[ax](o)),this[Nn].on("error",o=>this.abort(o)),this[Nn].on("end",o=>{this[Gl]=!0,this[ax]()}),this[kf]=!0;let r=this[Nn][i?"end":"write"](e);return this[kf]=!1,r}}this[kf]=!0,this[Nn]?this[Nn].write(e):this[ax](e),this[kf]=!1;let t=this[Ds].length?!1:this[Ss]?this[Ss].flowing:!0;return!t&&!this[Ds].length&&this[Ss].once("drain",i=>this.emit("drain")),t}[fE](e){e&&!this[Pa]&&(this[Zt]=this[Zt]?Buffer.concat([this[Zt],e]):e)}[mE](){if(this[Gl]&&!this[Oz]&&!this[Pa]&&!this[ux]){this[Oz]=!0;let e=this[Xl];if(e&&e.blockRemain){let t=this[Zt]?this[Zt].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[Zt]&&e.write(this[Zt]),e.end()}this[zl](cx)}}[ax](e){if(this[ux])this[fE](e);else if(!e&&!this[Zt])this[mE]();else{if(this[ux]=!0,this[Zt]){this[fE](e);let t=this[Zt];this[Zt]=null,this[lx](t)}else this[lx](e);for(;this[Zt]&&this[Zt].length>=512&&!this[Pa]&&!this[hx];){let t=this[Zt];this[Zt]=null,this[lx](t)}this[ux]=!1}(!this[Zt]||this[Gl])&&this[mE]()}[lx](e){let t=0,i=e.length;for(;t+512<=i&&!this[Pa]&&!this[hx];)switch(this[Cr]){case"begin":case"header":this[Nz](e,t),t+=512;break;case"ignore":case"body":t+=this[pE](e,t);break;case"meta":t+=this[Az](e,t);break;default:throw new Error("invalid state: "+this[Cr])}t{"use strict";var zhe=Jc(),Wz=gx(),ud=require("fs"),Khe=ld(),qz=require("path"),bE=Vc();Zz.exports=(n,e,t)=>{typeof n=="function"?(t=n,e=null,n={}):Array.isArray(n)&&(e=n,n={}),typeof e=="function"&&(t=e,e=null),e?e=Array.from(e):e=[];let i=zhe(n);if(i.sync&&typeof t=="function")throw new TypeError("callback not supported for sync tar functions");if(!i.file&&typeof t=="function")throw new TypeError("callback only supported with file option");return e.length&&Vhe(i,e),i.noResume||Qhe(i),i.file&&i.sync?ege(i):i.file?tge(i,t):Yz(i)};var Qhe=n=>{let e=n.onentry;n.onentry=e?t=>{e(t),t.resume()}:t=>t.resume()},Vhe=(n,e)=>{let t=new Map(e.map(o=>[bE(o),!0])),i=n.filter,r=(o,s)=>{let a=s||qz.parse(o).root||".",l=o===a?!1:t.has(o)?t.get(o):r(qz.dirname(o),a);return t.set(o,l),l};n.filter=i?(o,s)=>i(o,s)&&r(bE(o)):o=>r(bE(o))},ege=n=>{let e=Yz(n),t=n.file,i=!0,r;try{let o=ud.statSync(t),s=n.maxReadSize||16*1024*1024;if(o.size{let t=new Wz(n),i=n.maxReadSize||16*1024*1024,r=n.file,o=new Promise((s,a)=>{t.on("error",a),t.on("end",s),ud.stat(r,(l,u)=>{if(l)a(l);else{let c=new Khe.ReadStream(r,{readSize:i,size:u.size});c.on("error",a),c.pipe(t)}})});return e?o.then(e,e):o},Yz=n=>new Wz(n)});var zz=w((bHe,Gz)=>{"use strict";var ige=Jc(),fx=Vw(),Jz=ld(),$z=px(),Uz=require("path");Gz.exports=(n,e,t)=>{if(typeof e=="function"&&(t=e),Array.isArray(n)&&(e=n,n={}),!e||!Array.isArray(e)||!e.length)throw new TypeError("no files or directories specified");e=Array.from(e);let i=ige(n);if(i.sync&&typeof t=="function")throw new TypeError("callback not supported for sync tar functions");if(!i.file&&typeof t=="function")throw new TypeError("callback only supported with file option");return i.file&&i.sync?nge(i,e):i.file?rge(i,e,t):i.sync?oge(i,e):sge(i,e)};var nge=(n,e)=>{let t=new fx.Sync(n),i=new Jz.WriteStreamSync(n.file,{mode:n.mode||438});t.pipe(i),Xz(t,e)},rge=(n,e,t)=>{let i=new fx(n),r=new Jz.WriteStream(n.file,{mode:n.mode||438});i.pipe(r);let o=new Promise((s,a)=>{r.on("error",a),r.on("close",s),i.on("error",a)});return yE(i,e),t?o.then(t,t):o},Xz=(n,e)=>{e.forEach(t=>{t.charAt(0)==="@"?$z({file:Uz.resolve(n.cwd,t.slice(1)),sync:!0,noResume:!0,onentry:i=>n.add(i)}):n.add(t)}),n.end()},yE=(n,e)=>{for(;e.length;){let t=e.shift();if(t.charAt(0)==="@")return $z({file:Uz.resolve(n.cwd,t.slice(1)),noResume:!0,onentry:i=>n.add(i)}).then(i=>yE(n,e));n.add(t)}n.end()},oge=(n,e)=>{let t=new fx.Sync(n);return Xz(t,e),t},sge=(n,e)=>{let t=new fx(n);return yE(t,e),t}});var vE=w((yHe,nK)=>{"use strict";var age=Jc(),Kz=Vw(),tr=require("fs"),Qz=ld(),Vz=px(),eK=require("path"),tK=Qc();nK.exports=(n,e,t)=>{let i=age(n);if(!i.file)throw new TypeError("file is required");if(i.gzip)throw new TypeError("cannot append to compressed archives");if(!e||!Array.isArray(e)||!e.length)throw new TypeError("no files or directories specified");return e=Array.from(e),i.sync?lge(i,e):cge(i,e,t)};var lge=(n,e)=>{let t=new Kz.Sync(n),i=!0,r,o;try{try{r=tr.openSync(n.file,"r+")}catch(l){if(l.code==="ENOENT")r=tr.openSync(n.file,"w+");else throw l}let s=tr.fstatSync(r),a=Buffer.alloc(512);e:for(o=0;os.size)break;o+=u,n.mtimeCache&&n.mtimeCache.set(l.path,l.mtime)}i=!1,uge(n,t,o,r,e)}finally{if(i)try{tr.closeSync(r)}catch{}}},uge=(n,e,t,i,r)=>{let o=new Qz.WriteStreamSync(n.file,{fd:i,start:t});e.pipe(o),dge(e,r)},cge=(n,e,t)=>{e=Array.from(e);let i=new Kz(n),r=(s,a,l)=>{let u=(f,m)=>{f?tr.close(s,b=>l(f)):l(null,m)},c=0;if(a===0)return u(null,0);let d=0,h=Buffer.alloc(512),g=(f,m)=>{if(f)return u(f);if(d+=m,d<512&&m)return tr.read(s,h,d,h.length-d,c+d,g);if(c===0&&h[0]===31&&h[1]===139)return u(new Error("cannot append to compressed archives"));if(d<512)return u(null,c);let b=new tK(h);if(!b.cksumValid)return u(null,c);let v=512*Math.ceil(b.size/512);if(c+v+512>a||(c+=v+512,c>=a))return u(null,c);n.mtimeCache&&n.mtimeCache.set(b.path,b.mtime),d=0,tr.read(s,h,0,512,c,g)};tr.read(s,h,0,512,c,g)},o=new Promise((s,a)=>{i.on("error",a);let l="r+",u=(c,d)=>{if(c&&c.code==="ENOENT"&&l==="r+")return l="w+",tr.open(n.file,l,u);if(c)return a(c);tr.fstat(d,(h,g)=>{if(h)return tr.close(d,()=>a(h));r(d,g.size,(f,m)=>{if(f)return a(f);let b=new Qz.WriteStream(n.file,{fd:d,start:m});i.pipe(b),b.on("error",a),b.on("close",s),iK(i,e)})})};tr.open(n.file,l,u)});return t?o.then(t,t):o},dge=(n,e)=>{e.forEach(t=>{t.charAt(0)==="@"?Vz({file:eK.resolve(n.cwd,t.slice(1)),sync:!0,noResume:!0,onentry:i=>n.add(i)}):n.add(t)}),n.end()},iK=(n,e)=>{for(;e.length;){let t=e.shift();if(t.charAt(0)==="@")return Vz({file:eK.resolve(n.cwd,t.slice(1)),noResume:!0,onentry:i=>n.add(i)}).then(i=>iK(n,e));n.add(t)}n.end()}});var oK=w((vHe,rK)=>{"use strict";var hge=Jc(),gge=vE();rK.exports=(n,e,t)=>{let i=hge(n);if(!i.file)throw new TypeError("file is required");if(i.gzip)throw new TypeError("cannot append to compressed archives");if(!e||!Array.isArray(e)||!e.length)throw new TypeError("no files or directories specified");return e=Array.from(e),pge(i),gge(i,e,t)};var pge=n=>{let e=n.filter;n.mtimeCache||(n.mtimeCache=new Map),n.filter=e?(t,i)=>e(t,i)&&!(n.mtimeCache.get(t)>i.mtime):(t,i)=>!(n.mtimeCache.get(t)>i.mtime)}});var lK=w((wHe,aK)=>{var{promisify:sK}=require("util"),Ra=require("fs"),fge=n=>{if(!n)n={mode:511,fs:Ra};else if(typeof n=="object")n={mode:511,fs:Ra,...n};else if(typeof n=="number")n={mode:n,fs:Ra};else if(typeof n=="string")n={mode:parseInt(n,8),fs:Ra};else throw new TypeError("invalid options argument");return n.mkdir=n.mkdir||n.fs.mkdir||Ra.mkdir,n.mkdirAsync=sK(n.mkdir),n.stat=n.stat||n.fs.stat||Ra.stat,n.statAsync=sK(n.stat),n.statSync=n.statSync||n.fs.statSync||Ra.statSync,n.mkdirSync=n.mkdirSync||n.fs.mkdirSync||Ra.mkdirSync,n};aK.exports=fge});var cK=w((xHe,uK)=>{var mge=process.env.__TESTING_MKDIRP_PLATFORM__||process.platform,{resolve:bge,parse:yge}=require("path"),vge=n=>{if(/\0/.test(n))throw Object.assign(new TypeError("path must be a string without null bytes"),{path:n,code:"ERR_INVALID_ARG_VALUE"});if(n=bge(n),mge==="win32"){let e=/[*|"<>?:]/,{root:t}=yge(n);if(e.test(n.substr(t.length)))throw Object.assign(new Error("Illegal characters in path."),{path:n,code:"EINVAL"})}return n};uK.exports=vge});var fK=w((CHe,pK)=>{var{dirname:dK}=require("path"),hK=(n,e,t=void 0)=>t===e?Promise.resolve():n.statAsync(e).then(i=>i.isDirectory()?t:void 0,i=>i.code==="ENOENT"?hK(n,dK(e),e):void 0),gK=(n,e,t=void 0)=>{if(t!==e)try{return n.statSync(e).isDirectory()?t:void 0}catch(i){return i.code==="ENOENT"?gK(n,dK(e),e):void 0}};pK.exports={findMade:hK,findMadeSync:gK}});var CE=w((SHe,bK)=>{var{dirname:mK}=require("path"),wE=(n,e,t)=>{e.recursive=!1;let i=mK(n);return i===n?e.mkdirAsync(n,e).catch(r=>{if(r.code!=="EISDIR")throw r}):e.mkdirAsync(n,e).then(()=>t||n,r=>{if(r.code==="ENOENT")return wE(i,e).then(o=>wE(n,e,o));if(r.code!=="EEXIST"&&r.code!=="EROFS")throw r;return e.statAsync(n).then(o=>{if(o.isDirectory())return t;throw r},()=>{throw r})})},xE=(n,e,t)=>{let i=mK(n);if(e.recursive=!1,i===n)try{return e.mkdirSync(n,e)}catch(r){if(r.code!=="EISDIR")throw r;return}try{return e.mkdirSync(n,e),t||n}catch(r){if(r.code==="ENOENT")return xE(n,e,xE(i,e,t));if(r.code!=="EEXIST"&&r.code!=="EROFS")throw r;try{if(!e.statSync(n).isDirectory())throw r}catch{throw r}}};bK.exports={mkdirpManual:wE,mkdirpManualSync:xE}});var wK=w((DHe,vK)=>{var{dirname:yK}=require("path"),{findMade:wge,findMadeSync:xge}=fK(),{mkdirpManual:Cge,mkdirpManualSync:Sge}=CE(),Dge=(n,e)=>(e.recursive=!0,yK(n)===n?e.mkdirAsync(n,e):wge(e,n).then(i=>e.mkdirAsync(n,e).then(()=>i).catch(r=>{if(r.code==="ENOENT")return Cge(n,e);throw r}))),Tge=(n,e)=>{if(e.recursive=!0,yK(n)===n)return e.mkdirSync(n,e);let i=xge(e,n);try{return e.mkdirSync(n,e),i}catch(r){if(r.code==="ENOENT")return Sge(n,e);throw r}};vK.exports={mkdirpNative:Dge,mkdirpNativeSync:Tge}});var DK=w((THe,SK)=>{var xK=require("fs"),kge=process.env.__TESTING_MKDIRP_NODE_VERSION__||process.version,SE=kge.replace(/^v/,"").split("."),CK=+SE[0]>10||+SE[0]==10&&+SE[1]>=12,Pge=CK?n=>n.mkdir===xK.mkdir:()=>!1,Rge=CK?n=>n.mkdirSync===xK.mkdirSync:()=>!1;SK.exports={useNative:Pge,useNativeSync:Rge}});var EK=w((kHe,_K)=>{var cd=lK(),dd=cK(),{mkdirpNative:TK,mkdirpNativeSync:kK}=wK(),{mkdirpManual:PK,mkdirpManualSync:RK}=CE(),{useNative:_ge,useNativeSync:Ege}=DK(),hd=(n,e)=>(n=dd(n),e=cd(e),_ge(e)?TK(n,e):PK(n,e)),Ige=(n,e)=>(n=dd(n),e=cd(e),Ege(e)?kK(n,e):RK(n,e));hd.sync=Ige;hd.native=(n,e)=>TK(dd(n),cd(e));hd.manual=(n,e)=>PK(dd(n),cd(e));hd.nativeSync=(n,e)=>kK(dd(n),cd(e));hd.manualSync=(n,e)=>RK(dd(n),cd(e));_K.exports=hd});var AK=w((PHe,OK)=>{"use strict";var Dr=require("fs"),Ql=require("path"),Lge=Dr.lchown?"lchown":"chown",Fge=Dr.lchownSync?"lchownSync":"chownSync",LK=Dr.lchown&&!process.version.match(/v1[1-9]+\./)&&!process.version.match(/v10\.[6-9]/),IK=(n,e,t)=>{try{return Dr[Fge](n,e,t)}catch(i){if(i.code!=="ENOENT")throw i}},Mge=(n,e,t)=>{try{return Dr.chownSync(n,e,t)}catch(i){if(i.code!=="ENOENT")throw i}},jge=LK?(n,e,t,i)=>r=>{!r||r.code!=="EISDIR"?i(r):Dr.chown(n,e,t,i)}:(n,e,t,i)=>i,DE=LK?(n,e,t)=>{try{return IK(n,e,t)}catch(i){if(i.code!=="EISDIR")throw i;Mge(n,e,t)}}:(n,e,t)=>IK(n,e,t),Oge=process.version,FK=(n,e,t)=>Dr.readdir(n,e,t),Age=(n,e)=>Dr.readdirSync(n,e);/^v4\./.test(Oge)&&(FK=(n,e,t)=>Dr.readdir(n,t));var mx=(n,e,t,i)=>{Dr[Lge](n,e,t,jge(n,e,t,r=>{i(r&&r.code!=="ENOENT"?r:null)}))},MK=(n,e,t,i,r)=>{if(typeof e=="string")return Dr.lstat(Ql.resolve(n,e),(o,s)=>{if(o)return r(o.code!=="ENOENT"?o:null);s.name=e,MK(n,s,t,i,r)});if(e.isDirectory())TE(Ql.resolve(n,e.name),t,i,o=>{if(o)return r(o);let s=Ql.resolve(n,e.name);mx(s,t,i,r)});else{let o=Ql.resolve(n,e.name);mx(o,t,i,r)}},TE=(n,e,t,i)=>{FK(n,{withFileTypes:!0},(r,o)=>{if(r){if(r.code==="ENOENT")return i();if(r.code!=="ENOTDIR"&&r.code!=="ENOTSUP")return i(r)}if(r||!o.length)return mx(n,e,t,i);let s=o.length,a=null,l=u=>{if(!a){if(u)return i(a=u);if(--s===0)return mx(n,e,t,i)}};o.forEach(u=>MK(n,u,e,t,l))})},Nge=(n,e,t,i)=>{if(typeof e=="string")try{let r=Dr.lstatSync(Ql.resolve(n,e));r.name=e,e=r}catch(r){if(r.code==="ENOENT")return;throw r}e.isDirectory()&&jK(Ql.resolve(n,e.name),t,i),DE(Ql.resolve(n,e.name),t,i)},jK=(n,e,t)=>{let i;try{i=Age(n,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;if(r.code==="ENOTDIR"||r.code==="ENOTSUP")return DE(n,e,t);throw r}return i&&i.length&&i.forEach(r=>Nge(n,r,e,t)),DE(n,e,t)};OK.exports=TE;TE.sync=jK});var qK=w((RHe,kE)=>{"use strict";var NK=EK(),Tr=require("fs"),bx=require("path"),HK=AK(),ro=zc(),yx=class extends Error{constructor(e,t){super("Cannot extract through symbolic link"),this.path=t,this.symlink=e}get name(){return"SylinkError"}},vx=class extends Error{constructor(e,t){super(t+": Cannot cd into '"+e+"'"),this.path=e,this.code=t}get name(){return"CwdError"}},wx=(n,e)=>n.get(ro(e)),Pf=(n,e,t)=>n.set(ro(e),t),Hge=(n,e)=>{Tr.stat(n,(t,i)=>{(t||!i.isDirectory())&&(t=new vx(n,t&&t.code||"ENOTDIR")),e(t)})};kE.exports=(n,e,t)=>{n=ro(n);let i=e.umask,r=e.mode|448,o=(r&i)!==0,s=e.uid,a=e.gid,l=typeof s=="number"&&typeof a=="number"&&(s!==e.processUid||a!==e.processGid),u=e.preserve,c=e.unlink,d=e.cache,h=ro(e.cwd),g=(b,v)=>{b?t(b):(Pf(d,n,!0),v&&l?HK(v,s,a,x=>g(x)):o?Tr.chmod(n,r,t):t())};if(d&&wx(d,n)===!0)return g();if(n===h)return Hge(n,g);if(u)return NK(n,{mode:r}).then(b=>g(null,b),g);let m=ro(bx.relative(h,n)).split("/");xx(h,m,r,d,c,h,null,g)};var xx=(n,e,t,i,r,o,s,a)=>{if(!e.length)return a(null,s);let l=e.shift(),u=ro(bx.resolve(n+"/"+l));if(wx(i,u))return xx(u,e,t,i,r,o,s,a);Tr.mkdir(u,t,BK(u,e,t,i,r,o,s,a))},BK=(n,e,t,i,r,o,s,a)=>l=>{l?Tr.lstat(n,(u,c)=>{if(u)u.path=u.path&&ro(u.path),a(u);else if(c.isDirectory())xx(n,e,t,i,r,o,s,a);else if(r)Tr.unlink(n,d=>{if(d)return a(d);Tr.mkdir(n,t,BK(n,e,t,i,r,o,s,a))});else{if(c.isSymbolicLink())return a(new yx(n,n+"/"+e.join("/")));a(l)}}):(s=s||n,xx(n,e,t,i,r,o,s,a))},Bge=n=>{let e=!1,t="ENOTDIR";try{e=Tr.statSync(n).isDirectory()}catch(i){t=i.code}finally{if(!e)throw new vx(n,t)}};kE.exports.sync=(n,e)=>{n=ro(n);let t=e.umask,i=e.mode|448,r=(i&t)!==0,o=e.uid,s=e.gid,a=typeof o=="number"&&typeof s=="number"&&(o!==e.processUid||s!==e.processGid),l=e.preserve,u=e.unlink,c=e.cache,d=ro(e.cwd),h=b=>{Pf(c,n,!0),b&&a&&HK.sync(b,o,s),r&&Tr.chmodSync(n,i)};if(c&&wx(c,n)===!0)return h();if(n===d)return Bge(d),h();if(l)return h(NK.sync(n,i));let f=ro(bx.relative(d,n)).split("/"),m=null;for(let b=f.shift(),v=d;b&&(v+="/"+b);b=f.shift())if(v=ro(bx.resolve(v)),!wx(c,v))try{Tr.mkdirSync(v,i),m=m||v,Pf(c,v,!0)}catch{let C=Tr.lstatSync(v);if(C.isDirectory()){Pf(c,v,!0);continue}else if(u){Tr.unlinkSync(v),Tr.mkdirSync(v,i),m=m||v,Pf(c,v,!0);continue}else if(C.isSymbolicLink())return new yx(v,v+"/"+f.join("/"))}return h(m)}});var RE=w((_He,WK)=>{var PE=Object.create(null),{hasOwnProperty:qge}=Object.prototype;WK.exports=n=>(qge.call(PE,n)||(PE[n]=n.normalize("NFKD")),PE[n])});var $K=w((EHe,JK)=>{var YK=require("assert"),Wge=RE(),Yge=Vc(),{join:ZK}=require("path"),Zge=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Jge=Zge==="win32";JK.exports=()=>{let n=new Map,e=new Map,t=u=>u.split("/").slice(0,-1).reduce((d,h)=>(d.length&&(h=ZK(d[d.length-1],h)),d.push(h||"/"),d),[]),i=new Set,r=u=>{let c=e.get(u);if(!c)throw new Error("function does not have any path reservations");return{paths:c.paths.map(d=>n.get(d)),dirs:[...c.dirs].map(d=>n.get(d))}},o=u=>{let{paths:c,dirs:d}=r(u);return c.every(h=>h[0]===u)&&d.every(h=>h[0]instanceof Set&&h[0].has(u))},s=u=>i.has(u)||!o(u)?!1:(i.add(u),u(()=>a(u)),!0),a=u=>{if(!i.has(u))return!1;let{paths:c,dirs:d}=e.get(u),h=new Set;return c.forEach(g=>{let f=n.get(g);YK.equal(f[0],u),f.length===1?n.delete(g):(f.shift(),typeof f[0]=="function"?h.add(f[0]):f[0].forEach(m=>h.add(m)))}),d.forEach(g=>{let f=n.get(g);YK(f[0]instanceof Set),f[0].size===1&&f.length===1?n.delete(g):f[0].size===1?(f.shift(),h.add(f[0])):f[0].delete(u)}),i.delete(u),h.forEach(g=>s(g)),!0};return{check:o,reserve:(u,c)=>{u=Jge?["win32 parallelization disabled"]:u.map(h=>Wge(Yge(ZK(h))).toLowerCase());let d=new Set(u.map(h=>t(h)).reduce((h,g)=>h.concat(g)));return e.set(c,{dirs:d,paths:u}),u.forEach(h=>{let g=n.get(h);g?g.push(c):n.set(h,[c])}),d.forEach(h=>{let g=n.get(h);g?g[g.length-1]instanceof Set?g[g.length-1].add(c):g.push(new Set([c])):n.set(h,[new Set([c])])}),s(c)}}}});var GK=w((IHe,XK)=>{var $ge=process.env.__FAKE_PLATFORM__||process.platform,Uge=$ge==="win32",Xge=global.__FAKE_TESTING_FS__||require("fs"),{O_CREAT:Gge,O_TRUNC:zge,O_WRONLY:Kge,UV_FS_O_FILEMAP:UK=0}=Xge.constants,Qge=Uge&&!!UK,Vge=512*1024,epe=UK|zge|Gge|Kge;XK.exports=Qge?n=>n"w"});var AE=w((LHe,u3)=>{"use strict";var tpe=require("assert"),ipe=gx(),pt=require("fs"),npe=ld(),Ts=require("path"),s3=qK(),zK=A_(),rpe=$K(),ope=N_(),ir=zc(),spe=Vc(),ape=RE(),KK=Symbol("onEntry"),IE=Symbol("checkFs"),QK=Symbol("checkFs2"),Dx=Symbol("pruneCache"),LE=Symbol("isReusable"),kr=Symbol("makeFs"),FE=Symbol("file"),ME=Symbol("directory"),Tx=Symbol("link"),VK=Symbol("symlink"),e3=Symbol("hardlink"),t3=Symbol("unsupported"),i3=Symbol("checkPath"),_a=Symbol("mkdir"),cn=Symbol("onError"),Cx=Symbol("pending"),n3=Symbol("pend"),gd=Symbol("unpend"),_E=Symbol("ended"),EE=Symbol("maybeClose"),jE=Symbol("skip"),Rf=Symbol("doChown"),_f=Symbol("uid"),Ef=Symbol("gid"),If=Symbol("checkedCwd"),a3=require("crypto"),l3=GK(),lpe=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Lf=lpe==="win32",upe=(n,e)=>{if(!Lf)return pt.unlink(n,e);let t=n+".DELETE."+a3.randomBytes(16).toString("hex");pt.rename(n,t,i=>{if(i)return e(i);pt.unlink(t,e)})},cpe=n=>{if(!Lf)return pt.unlinkSync(n);let e=n+".DELETE."+a3.randomBytes(16).toString("hex");pt.renameSync(n,e),pt.unlinkSync(e)},r3=(n,e,t)=>n===n>>>0?n:e===e>>>0?e:t,o3=n=>ape(spe(ir(n))).toLowerCase(),dpe=(n,e)=>{e=o3(e);for(let t of n.keys()){let i=o3(t);(i===e||i.indexOf(e+"/")===0)&&n.delete(t)}},hpe=n=>{for(let e of n.keys())n.delete(e)},Ff=class extends ipe{constructor(e){if(e||(e={}),e.ondone=t=>{this[_E]=!0,this[EE]()},super(e),this[If]=!1,this.reservations=rpe(),this.transform=typeof e.transform=="function"?e.transform:null,this.writable=!0,this.readable=!1,this[Cx]=0,this[_E]=!1,this.dirCache=e.dirCache||new Map,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=null,this.gid=null,this.setOwner=!1;e.preserveOwner===void 0&&typeof e.uid!="number"?this.preserveOwner=process.getuid&&process.getuid()===0:this.preserveOwner=!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():null,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():null,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||Lf,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=ir(Ts.resolve(e.cwd||process.cwd())),this.strip=+e.strip||0,this.processUmask=e.noChmod?0:process.umask(),this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",t=>this[KK](t))}warn(e,t,i={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(i.recoverable=!1),super.warn(e,t,i)}[EE](){this[_E]&&this[Cx]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[i3](e){if(this.strip){let t=ir(e.path).split("/");if(t.length=this.strip)e.linkpath=i.slice(this.strip).join("/");else return!1}}if(!this.preservePaths){let t=ir(e.path),i=t.split("/");if(i.includes("..")||Lf&&/^[a-z]:\.\.$/i.test(i[0]))return this.warn("TAR_ENTRY_ERROR","path contains '..'",{entry:e,path:t}),!1;let[r,o]=ope(t);r&&(e.path=o,this.warn("TAR_ENTRY_INFO",`stripping ${r} from absolute path`,{entry:e,path:t}))}if(Ts.isAbsolute(e.path)?e.absolute=ir(Ts.resolve(e.path)):e.absolute=ir(Ts.resolve(this.cwd,e.path)),!this.preservePaths&&e.absolute.indexOf(this.cwd+"/")!==0&&e.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:e,path:ir(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!=="Directory"&&e.type!=="GNUDumpDir")return!1;if(this.win32){let{root:t}=Ts.win32.parse(e.absolute);e.absolute=t+zK.encode(e.absolute.slice(t.length));let{root:i}=Ts.win32.parse(e.path);e.path=i+zK.encode(e.path.slice(i.length))}return!0}[KK](e){if(!this[i3](e))return e.resume();switch(tpe.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[IE](e);case"CharacterDevice":case"BlockDevice":case"FIFO":default:return this[t3](e)}}[cn](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[gd](),t.resume())}[_a](e,t,i){s3(ir(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:t,noChmod:this.noChmod},i)}[Rf](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[_f](e){return r3(this.uid,e.uid,this.processUid)}[Ef](e){return r3(this.gid,e.gid,this.processGid)}[FE](e,t){let i=e.mode&4095||this.fmode,r=new npe.WriteStream(e.absolute,{flags:l3(e.size),mode:i,autoClose:!1});r.on("error",l=>{r.fd&&pt.close(r.fd,()=>{}),r.write=()=>!0,this[cn](l,e),t()});let o=1,s=l=>{if(l){r.fd&&pt.close(r.fd,()=>{}),this[cn](l,e),t();return}--o===0&&pt.close(r.fd,u=>{u?this[cn](u,e):this[gd](),t()})};r.on("finish",l=>{let u=e.absolute,c=r.fd;if(e.mtime&&!this.noMtime){o++;let d=e.atime||new Date,h=e.mtime;pt.futimes(c,d,h,g=>g?pt.utimes(u,d,h,f=>s(f&&g)):s())}if(this[Rf](e)){o++;let d=this[_f](e),h=this[Ef](e);pt.fchown(c,d,h,g=>g?pt.chown(u,d,h,f=>s(f&&g)):s())}s()});let a=this.transform&&this.transform(e)||e;a!==e&&(a.on("error",l=>{this[cn](l,e),t()}),e.pipe(a)),a.pipe(r)}[ME](e,t){let i=e.mode&4095||this.dmode;this[_a](e.absolute,i,r=>{if(r){this[cn](r,e),t();return}let o=1,s=a=>{--o===0&&(t(),this[gd](),e.resume())};e.mtime&&!this.noMtime&&(o++,pt.utimes(e.absolute,e.atime||new Date,e.mtime,s)),this[Rf](e)&&(o++,pt.chown(e.absolute,this[_f](e),this[Ef](e),s)),s()})}[t3](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[VK](e,t){this[Tx](e,e.linkpath,"symlink",t)}[e3](e,t){let i=ir(Ts.resolve(this.cwd,e.linkpath));this[Tx](e,i,"link",t)}[n3](){this[Cx]++}[gd](){this[Cx]--,this[EE]()}[jE](e){this[gd](),e.resume()}[LE](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!Lf}[IE](e){this[n3]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,i=>this[QK](e,i))}[Dx](e){e.type==="SymbolicLink"?hpe(this.dirCache):e.type!=="Directory"&&dpe(this.dirCache,e.absolute)}[QK](e,t){this[Dx](e);let i=a=>{this[Dx](e),t(a)},r=()=>{this[_a](this.cwd,this.dmode,a=>{if(a){this[cn](a,e),i();return}this[If]=!0,o()})},o=()=>{if(e.absolute!==this.cwd){let a=ir(Ts.dirname(e.absolute));if(a!==this.cwd)return this[_a](a,this.dmode,l=>{if(l){this[cn](l,e),i();return}s()})}s()},s=()=>{pt.lstat(e.absolute,(a,l)=>{if(l&&(this.keep||this.newer&&l.mtime>e.mtime)){this[jE](e),i();return}if(a||this[LE](e,l))return this[kr](null,e,i);if(l.isDirectory()){if(e.type==="Directory"){let u=!this.noChmod&&e.mode&&(l.mode&4095)!==e.mode,c=d=>this[kr](d,e,i);return u?pt.chmod(e.absolute,e.mode,c):c()}if(e.absolute!==this.cwd)return pt.rmdir(e.absolute,u=>this[kr](u,e,i))}if(e.absolute===this.cwd)return this[kr](null,e,i);upe(e.absolute,u=>this[kr](u,e,i))})};this[If]?o():r()}[kr](e,t,i){if(e){this[cn](e,t),i();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[FE](t,i);case"Link":return this[e3](t,i);case"SymbolicLink":return this[VK](t,i);case"Directory":case"GNUDumpDir":return this[ME](t,i)}}[Tx](e,t,i,r){pt[i](t,e.absolute,o=>{o?this[cn](o,e):(this[gd](),e.resume()),r()})}},Sx=n=>{try{return[null,n()]}catch(e){return[e,null]}},OE=class extends Ff{[kr](e,t){return super[kr](e,t,()=>{})}[IE](e){if(this[Dx](e),!this[If]){let o=this[_a](this.cwd,this.dmode);if(o)return this[cn](o,e);this[If]=!0}if(e.absolute!==this.cwd){let o=ir(Ts.dirname(e.absolute));if(o!==this.cwd){let s=this[_a](o,this.dmode);if(s)return this[cn](s,e)}}let[t,i]=Sx(()=>pt.lstatSync(e.absolute));if(i&&(this.keep||this.newer&&i.mtime>e.mtime))return this[jE](e);if(t||this[LE](e,i))return this[kr](null,e);if(i.isDirectory()){if(e.type==="Directory"){let s=!this.noChmod&&e.mode&&(i.mode&4095)!==e.mode,[a]=s?Sx(()=>{pt.chmodSync(e.absolute,e.mode)}):[];return this[kr](a,e)}let[o]=Sx(()=>pt.rmdirSync(e.absolute));this[kr](o,e)}let[r]=e.absolute===this.cwd?[]:Sx(()=>cpe(e.absolute));this[kr](r,e)}[FE](e,t){let i=e.mode&4095||this.fmode,r=a=>{let l;try{pt.closeSync(o)}catch(u){l=u}(a||l)&&this[cn](a||l,e),t()},o;try{o=pt.openSync(e.absolute,l3(e.size),i)}catch(a){return r(a)}let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>this[cn](a,e)),e.pipe(s)),s.on("data",a=>{try{pt.writeSync(o,a,0,a.length)}catch(l){r(l)}}),s.on("end",a=>{let l=null;if(e.mtime&&!this.noMtime){let u=e.atime||new Date,c=e.mtime;try{pt.futimesSync(o,u,c)}catch(d){try{pt.utimesSync(e.absolute,u,c)}catch{l=d}}}if(this[Rf](e)){let u=this[_f](e),c=this[Ef](e);try{pt.fchownSync(o,u,c)}catch(d){try{pt.chownSync(e.absolute,u,c)}catch{l=l||d}}}r(l)})}[ME](e,t){let i=e.mode&4095||this.dmode,r=this[_a](e.absolute,i);if(r){this[cn](r,e),t();return}if(e.mtime&&!this.noMtime)try{pt.utimesSync(e.absolute,e.atime||new Date,e.mtime)}catch{}if(this[Rf](e))try{pt.chownSync(e.absolute,this[_f](e),this[Ef](e))}catch{}t(),e.resume()}[_a](e,t){try{return s3.sync(ir(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:t})}catch(i){return i}}[Tx](e,t,i,r){try{pt[i+"Sync"](t,e.absolute),r(),e.resume()}catch(o){return this[cn](o,e)}}};Ff.Sync=OE;u3.exports=Ff});var p3=w((FHe,g3)=>{"use strict";var gpe=Jc(),kx=AE(),d3=require("fs"),h3=ld(),c3=require("path"),NE=Vc();g3.exports=(n,e,t)=>{typeof n=="function"?(t=n,e=null,n={}):Array.isArray(n)&&(e=n,n={}),typeof e=="function"&&(t=e,e=null),e?e=Array.from(e):e=[];let i=gpe(n);if(i.sync&&typeof t=="function")throw new TypeError("callback not supported for sync tar functions");if(!i.file&&typeof t=="function")throw new TypeError("callback only supported with file option");return e.length&&ppe(i,e),i.file&&i.sync?fpe(i):i.file?mpe(i,t):i.sync?bpe(i):ype(i)};var ppe=(n,e)=>{let t=new Map(e.map(o=>[NE(o),!0])),i=n.filter,r=(o,s)=>{let a=s||c3.parse(o).root||".",l=o===a?!1:t.has(o)?t.get(o):r(c3.dirname(o),a);return t.set(o,l),l};n.filter=i?(o,s)=>i(o,s)&&r(NE(o)):o=>r(NE(o))},fpe=n=>{let e=new kx.Sync(n),t=n.file,i=d3.statSync(t),r=n.maxReadSize||16*1024*1024;new h3.ReadStreamSync(t,{readSize:r,size:i.size}).pipe(e)},mpe=(n,e)=>{let t=new kx(n),i=n.maxReadSize||16*1024*1024,r=n.file,o=new Promise((s,a)=>{t.on("error",a),t.on("close",s),d3.stat(r,(l,u)=>{if(l)a(l);else{let c=new h3.ReadStream(r,{readSize:i,size:u.size});c.on("error",a),c.pipe(t)}})});return e?o.then(e,e):o},bpe=n=>new kx.Sync(n),ype=n=>new kx(n)});var f3=w(ki=>{"use strict";ki.c=ki.create=zz();ki.r=ki.replace=vE();ki.t=ki.list=px();ki.u=ki.update=oK();ki.x=ki.extract=p3();ki.Pack=Vw();ki.Unpack=AE();ki.Parse=gx();ki.ReadEntry=Ow();ki.WriteEntry=X_();ki.Header=Qc();ki.Pax=Nw();ki.types=E_()});var v3=w((jHe,y3)=>{y3.exports=dn;function dn(n){if(!(this instanceof dn))return new dn(n);this.value=n}dn.prototype.get=function(n){for(var e=this.value,t=0;t{var vpe=v3(),wpe=require("events").EventEmitter;w3.exports=pd;function pd(n){var e=pd.saw(n,{}),t=n.call(e.handlers,e);return t!==void 0&&(e.handlers=t),e.record(),e.chain()}pd.light=function(e){var t=pd.saw(e,{}),i=e.call(t.handlers,t);return i!==void 0&&(t.handlers=i),t.chain()};pd.saw=function(n,e){var t=new wpe;return t.handlers=e,t.actions=[],t.chain=function(){var i=vpe(t.handlers).map(function(r){if(this.isRoot)return r;var o=this.path;typeof r=="function"&&this.update(function(){return t.actions.push({path:o,args:[].slice.call(arguments)}),i})});return process.nextTick(function(){t.emit("begin"),t.next()}),i},t.pop=function(){return t.actions.shift()},t.next=function(){var i=t.pop();if(!i)t.emit("end");else if(!i.trap){var r=t.handlers;i.path.forEach(function(o){r=r[o]}),r.apply(t.handlers,i.args)}},t.nest=function(i){var r=[].slice.call(arguments,1),o=!0;if(typeof i=="boolean"){var o=i;i=r.shift()}var s=pd.saw(n,{}),a=n.call(s.handlers,s);a!==void 0&&(s.handlers=a),typeof t.step<"u"&&s.record(),i.apply(s.chain(),r),o!==!1&&s.on("end",t.next)},t.record=function(){xpe(t)},["trap","down","jump"].forEach(function(i){t[i]=function(){throw new Error("To use the trap, down and jump features, please call record() first to start recording actions.")}}),t};function xpe(n){n.step=0,n.pop=function(){return n.actions[n.step++]},n.trap=function(e,t){var i=Array.isArray(e)?e:[e];n.actions.push({path:i,step:n.step,cb:t,trap:!0})},n.down=function(e){var t=(Array.isArray(e)?e:[e]).join("/"),i=n.actions.slice(n.step).map(function(o){return o.trap&&o.step<=n.step?!1:o.path.join("/")==t}).indexOf(!0);i>=0?n.step+=i:n.step=n.actions.length;var r=n.actions[n.step-1];r&&r.trap?(n.step=r.step,r.cb()):n.next()},n.jump=function(e){n.step=e,n.next()}}});var S3=w((AHe,C3)=>{C3.exports=wn;function wn(n){if(!(this instanceof wn))return new wn(n);this.buffers=n||[],this.length=this.buffers.reduce(function(e,t){return e+t.length},0)}wn.prototype.push=function(){for(var n=0;n=0?n:this.length-n,r=[].slice.call(arguments,2);e===void 0?e=this.length-i:e>this.length-i&&(e=this.length-i);for(var n=0;n0){var u=i-a;if(u+e0){var g=r.slice();g.unshift(d),g.push(h),t.splice.apply(t,[l,1].concat(g)),l+=g.length,r=[]}else t.splice(l,1,d,h),l+=2}else o.push(t[l].slice(u)),t[l]=t[l].slice(0,u),l++}for(r.length>0&&(t.splice.apply(t,[l,0].concat(r)),l+=r.length);o.lengththis.length&&(e=this.length);for(var i=0,r=0;r=e-n?Math.min(u+(e-n)-s,l):l;t[a].copy(o,s,u,c),s+=c-u}return o};wn.prototype.pos=function(n){if(n<0||n>=this.length)throw new Error("oob");for(var e=n,t=0,i=null;;){if(i=this.buffers[t],e=this.buffers[t].length;)if(i=0,t++,t>=this.buffers.length)return-1;var l=this.buffers[t][i];if(l==n[r]){if(r==0&&(o={i:t,j:i,pos:s}),r++,r==n.length)return o.pos}else r!=0&&(t=o.i,i=o.j,s=o.pos,r=0);i++,s++}};wn.prototype.toBuffer=function(){return this.slice()};wn.prototype.toString=function(n,e,t){return this.slice(e,t).toString(n)}});var T3=w((NHe,D3)=>{D3.exports=function(n){function e(i,r){var o=t.store,s=i.split(".");s.slice(0,-1).forEach(function(l){o[l]===void 0&&(o[l]={}),o=o[l]});var a=s[s.length-1];return arguments.length==1?o[a]:o[a]=r}var t={get:function(i){return e(i)},set:function(i,r){return e(i,r)},store:n||{}};return t}});var I3=w((Vl,E3)=>{var Cpe=x3(),k3=require("events").EventEmitter,Spe=S3(),Px=T3(),Dpe=require("stream").Stream;Vl=E3.exports=function(n,e){if(Buffer.isBuffer(n))return Vl.parse(n);var t=Vl.stream();return n&&n.pipe?n.pipe(t):n&&(n.on(e||"data",function(i){t.write(i)}),n.on("end",function(){t.end()})),t};Vl.stream=function(n){if(n)return Vl.apply(null,arguments);var e=null;function t(d,h,g){e={bytes:d,skip:g,cb:function(f){e=null,h(f)}},r()}var i=null;function r(){if(!e){c&&(u=!0);return}if(typeof e=="function")e();else{var d=i+e.bytes;if(a.length>=d){var h;i==null?(h=a.splice(0,d),e.skip||(h=h.slice())):(e.skip||(h=a.slice(i,d)),i=d),e.skip?e.cb():e.cb(h)}}}function o(d){function h(){u||d.next()}var g=_3(function(f,m){return function(b){t(f,function(v){l.set(b,m(v)),h()})}});return g.tap=function(f){d.nest(f,l.store)},g.into=function(f,m){l.get(f)||l.set(f,{});var b=l;l=Px(b.get(f)),d.nest(function(){m.apply(this,arguments),this.tap(function(){l=b})},l.store)},g.flush=function(){l.store={},h()},g.loop=function(f){var m=!1;d.nest(!1,function b(){this.vars=l.store,f.call(this,function(){m=!0,h()},l.store),this.tap(function(){m?d.next():b.call(this)}.bind(this))},l.store)},g.buffer=function(f,m){typeof m=="string"&&(m=l.get(m)),t(m,function(b){l.set(f,b),h()})},g.skip=function(f){typeof f=="string"&&(f=l.get(f)),t(f,function(){h()})},g.scan=function(m,b){if(typeof b=="string")b=new Buffer(b);else if(!Buffer.isBuffer(b))throw new Error("search must be a Buffer or a string");var v=0;e=function(){var x=a.indexOf(b,i+v),C=x-i-v;x!==-1?(e=null,i!=null?(l.set(m,a.slice(i,i+v+C)),i+=v+C+b.length):(l.set(m,a.slice(0,v+C)),a.splice(0,v+C+b.length)),h(),r()):C=Math.max(a.length-b.length-i-v,0),v+=C},r()},g.peek=function(f){i=0,d.nest(function(){f.call(this,l.store),this.tap(function(){i=null})})},g}var s=Cpe.light(o);s.writable=!0;var a=Spe();s.write=function(d){a.push(d),r()};var l=Px(),u=!1,c=!1;return s.end=function(){c=!0},s.pipe=Dpe.prototype.pipe,Object.getOwnPropertyNames(k3.prototype).forEach(function(d){s[d]=k3.prototype[d]}),s};Vl.parse=function(e){var t=_3(function(o,s){return function(a){if(i+o<=e.length){var l=e.slice(i,i+o);i+=o,r.set(a,s(l))}else r.set(a,null);return t}}),i=0,r=Px();return t.vars=r.store,t.tap=function(o){return o.call(t,r.store),t},t.into=function(o,s){r.get(o)||r.set(o,{});var a=r;return r=Px(a.get(o)),s.call(t,r.store),r=a,t},t.loop=function(o){for(var s=!1,a=function(){s=!0};s===!1;)o.call(t,a,r.store);return t},t.buffer=function(o,s){typeof s=="string"&&(s=r.get(s));var a=e.slice(i,Math.min(e.length,i+s));return i+=s,r.set(o,a),t},t.skip=function(o){return typeof o=="string"&&(o=r.get(o)),i+=o,t},t.scan=function(o,s){if(typeof s=="string")s=new Buffer(s);else if(!Buffer.isBuffer(s))throw new Error("search must be a Buffer or a string");r.set(o,null);for(var a=0;a+i<=e.length-s.length+1;a++){for(var l=0;l=e.length},t};function P3(n){for(var e=0,t=0;t{var L3=require("stream").Transform,Ppe=require("util");function eu(n,e){if(!(this instanceof eu))return new eu;L3.call(this);var t=typeof n=="object"?n.pattern:n;this.pattern=Buffer.isBuffer(t)?t:Buffer.from(t),this.requiredLength=this.pattern.length,n.requiredExtraSize&&(this.requiredLength+=n.requiredExtraSize),this.data=new Buffer(""),this.bytesSoFar=0,this.matchFn=e}Ppe.inherits(eu,L3);eu.prototype.checkDataChunk=function(n){var e=this.data.length>=this.requiredLength;if(!!e){var t=this.data.indexOf(this.pattern,n?1:0);if(t>=0&&t+this.requiredLength>this.data.length){if(t>0){var i=this.data.slice(0,t);this.push(i),this.bytesSoFar+=t,this.data=this.data.slice(t)}return}if(t===-1){var r=this.data.length-this.requiredLength+1,i=this.data.slice(0,r);this.push(i),this.bytesSoFar+=r,this.data=this.data.slice(r);return}if(t>0){var i=this.data.slice(0,t);this.data=this.data.slice(t),this.push(i),this.bytesSoFar+=t}var o=this.matchFn?this.matchFn(this.data,this.bytesSoFar):!0;if(o){this.data=new Buffer("");return}return!0}};eu.prototype._transform=function(n,e,t){this.data=Buffer.concat([this.data,n]);for(var i=!0;this.checkDataChunk(!i);)i=!1;t()};eu.prototype._flush=function(n){if(this.data.length>0)for(var e=!0;this.checkDataChunk(!e);)e=!1;this.data.length>0&&(this.push(this.data),this.data=null),n()};F3.exports=eu});var O3=w((BHe,j3)=>{"use strict";var HE=require("stream"),Rpe=require("util").inherits;function Mf(){if(!(this instanceof Mf))return new Mf;HE.PassThrough.call(this),this.path=null,this.type=null,this.isDirectory=!1}Rpe(Mf,HE.PassThrough);Mf.prototype.autodrain=function(){return this.pipe(new HE.Transform({transform:function(n,e,t){t()}}))};j3.exports=Mf});var qE=w((qHe,N3)=>{"use strict";var Ea=I3(),BE=require("stream"),_pe=require("util"),Epe=require("zlib"),Ipe=M3(),A3=O3(),Ne={STREAM_START:0,START:1,LOCAL_FILE_HEADER:2,LOCAL_FILE_HEADER_SUFFIX:3,FILE_DATA:4,FILE_DATA_END:5,DATA_DESCRIPTOR:6,CENTRAL_DIRECTORY_FILE_HEADER:7,CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:8,CDIR64_END:9,CDIR64_END_DATA_SECTOR:10,CDIR64_LOCATOR:11,CENTRAL_DIRECTORY_END:12,CENTRAL_DIRECTORY_END_COMMENT:13,TRAILING_JUNK:14,ERROR:99},jf=4294967296,Lpe=67324752,Fpe=134695760,Mpe=33639248,jpe=101075792,Ope=117853008,Ape=101010256;function Qi(n){if(!(this instanceof Qi))return new Qi(n);BE.Transform.call(this),this.options=n||{},this.data=new Buffer(""),this.state=Ne.STREAM_START,this.skippedBytes=0,this.parsedEntity=null,this.outStreamInfo={}}_pe.inherits(Qi,BE.Transform);Qi.prototype.processDataChunk=function(n){var e;switch(this.state){case Ne.STREAM_START:case Ne.START:e=4;break;case Ne.LOCAL_FILE_HEADER:e=26;break;case Ne.LOCAL_FILE_HEADER_SUFFIX:e=this.parsedEntity.fileNameLength+this.parsedEntity.extraFieldLength;break;case Ne.DATA_DESCRIPTOR:e=12;break;case Ne.CENTRAL_DIRECTORY_FILE_HEADER:e=42;break;case Ne.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:e=this.parsedEntity.fileNameLength+this.parsedEntity.extraFieldLength+this.parsedEntity.fileCommentLength;break;case Ne.CDIR64_END:e=52;break;case Ne.CDIR64_END_DATA_SECTOR:e=this.parsedEntity.centralDirectoryRecordSize-44;break;case Ne.CDIR64_LOCATOR:e=16;break;case Ne.CENTRAL_DIRECTORY_END:e=18;break;case Ne.CENTRAL_DIRECTORY_END_COMMENT:e=this.parsedEntity.commentLength;break;case Ne.FILE_DATA:return 0;case Ne.FILE_DATA_END:return 0;case Ne.TRAILING_JUNK:return this.options.debug&&console.log("found",n.length,"bytes of TRAILING_JUNK"),n.length;default:return n.length}var t=n.length;if(t>>8,(o&255)===80){s=a;break}return this.skippedBytes+=s,this.options.debug&&console.log("Skipped",this.skippedBytes,"bytes"),s}this.state=Ne.ERROR;var l=r?"Not a valid zip file":"Invalid signature in zip file";if(this.options.debug){var u=n.readUInt32LE(0),c;try{c=n.slice(0,4).toString()}catch{}console.log("Unexpected signature in zip file: 0x"+u.toString(16),'"'+c+'", skipped',this.skippedBytes,"bytes")}return this.emit("error",new Error(l)),n.length}return this.skippedBytes=0,e;case Ne.LOCAL_FILE_HEADER:return this.parsedEntity=this._readFile(n),this.state=Ne.LOCAL_FILE_HEADER_SUFFIX,e;case Ne.LOCAL_FILE_HEADER_SUFFIX:var d=new A3,h=(this.parsedEntity.flags&2048)!==0;d.path=this._decodeString(n.slice(0,this.parsedEntity.fileNameLength),h);var f=n.slice(this.parsedEntity.fileNameLength,this.parsedEntity.fileNameLength+this.parsedEntity.extraFieldLength),m=this._readExtraFields(f);if(m&&m.parsed&&(m.parsed.path&&!h&&(d.path=m.parsed.path),Number.isFinite(m.parsed.uncompressedSize)&&this.parsedEntity.uncompressedSize===jf-1&&(this.parsedEntity.uncompressedSize=m.parsed.uncompressedSize),Number.isFinite(m.parsed.compressedSize)&&this.parsedEntity.compressedSize===jf-1&&(this.parsedEntity.compressedSize=m.parsed.compressedSize)),this.parsedEntity.extra=m.parsed||{},this.options.debug){let k=Object.assign({},this.parsedEntity,{path:d.path,flags:"0x"+this.parsedEntity.flags.toString(16),extraFields:m&&m.debug});console.log("decoded LOCAL_FILE_HEADER:",JSON.stringify(k,null,2))}return this._prepareOutStream(this.parsedEntity,d),this.emit("entry",d),this.state=Ne.FILE_DATA,e;case Ne.CENTRAL_DIRECTORY_FILE_HEADER:return this.parsedEntity=this._readCentralDirectoryEntry(n),this.state=Ne.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX,e;case Ne.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:var h=(this.parsedEntity.flags&2048)!==0,g=this._decodeString(n.slice(0,this.parsedEntity.fileNameLength),h),f=n.slice(this.parsedEntity.fileNameLength,this.parsedEntity.fileNameLength+this.parsedEntity.extraFieldLength),m=this._readExtraFields(f);m&&m.parsed&&m.parsed.path&&!h&&(g=m.parsed.path),this.parsedEntity.extra=m.parsed;var b=(this.parsedEntity.versionMadeBy&65280)>>8===3,v,x;if(b){v=this.parsedEntity.externalFileAttributes>>>16;var C=v>>>12;x=(C&10)===10}if(this.options.debug){let k=Object.assign({},this.parsedEntity,{path:g,flags:"0x"+this.parsedEntity.flags.toString(16),unixAttrs:v&&"0"+v.toString(8),isSymlink:x,extraFields:m.debug});console.log("decoded CENTRAL_DIRECTORY_FILE_HEADER:",JSON.stringify(k,null,2))}return this.state=Ne.START,e;case Ne.CDIR64_END:return this.parsedEntity=this._readEndOfCentralDirectory64(n),this.options.debug&&console.log("decoded CDIR64_END_RECORD:",this.parsedEntity),this.state=Ne.CDIR64_END_DATA_SECTOR,e;case Ne.CDIR64_END_DATA_SECTOR:return this.state=Ne.START,e;case Ne.CDIR64_LOCATOR:return this.state=Ne.START,e;case Ne.CENTRAL_DIRECTORY_END:return this.parsedEntity=this._readEndOfCentralDirectory(n),this.options.debug&&console.log("decoded CENTRAL_DIRECTORY_END:",this.parsedEntity),this.state=Ne.CENTRAL_DIRECTORY_END_COMMENT,e;case Ne.CENTRAL_DIRECTORY_END_COMMENT:return this.options.debug&&console.log("decoded CENTRAL_DIRECTORY_END_COMMENT:",n.slice(0,e).toString()),this.state=Ne.TRAILING_JUNK,e;case Ne.ERROR:return n.length;default:return console.log("didn't handle state #",this.state,"discarding"),n.length}};Qi.prototype._prepareOutStream=function(n,e){var t=this,i=n.uncompressedSize===0&&/[\/\\]$/.test(e.path);e.path=e.path.replace(/^([/\\]*[.]+[/\\]+)*[/\\]*/,""),e.type=i?"Directory":"File",e.isDirectory=i;var r=!(n.flags&8);r&&(e.size=n.uncompressedSize);var o=n.versionsNeededToExtract<=45;if(this.outStreamInfo={stream:null,limit:r?n.compressedSize:-1,written:0},r)this.outStreamInfo.stream=new BE.PassThrough;else{var s=new Buffer(4);s.writeUInt32LE(Fpe,0);var a=n.extra.zip64Mode,l=a?20:12,u={pattern:s,requiredExtraSize:l},c=new Ipe(u,function(m,b){var v=t._readDataDescriptor(m,a),x=v.compressedSize===b;if(!a&&!x&&b>=jf)for(var C=b-jf;C>=0&&(x=v.compressedSize===C,!x);)C-=jf;if(!!x){t.state=Ne.FILE_DATA_END;var k=a?24:16;return t.data.length>0?t.data=Buffer.concat([m.slice(k),t.data]):t.data=m.slice(k),!0}});this.outStreamInfo.stream=c}var d=n.flags&1||n.flags&64;if(d||!o){var h=d?"Encrypted files are not supported!":"Zip version "+Math.floor(n.versionsNeededToExtract/10)+"."+n.versionsNeededToExtract%10+" is not supported";e.skip=!0,setImmediate(()=>{e.emit("error",new Error(h))}),this.outStreamInfo.stream.pipe(new A3().autodrain());return}var g=n.compressionMethod>0;if(g){var f=Epe.createInflateRaw();f.on("error",function(m){t.state=Ne.ERROR,t.emit("error",m)}),this.outStreamInfo.stream.pipe(f).pipe(e)}else this.outStreamInfo.stream.pipe(e);this._drainAllEntries&&e.autodrain()};Qi.prototype._readFile=function(n){var e=Ea.parse(n).word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars;return e};Qi.prototype._readExtraFields=function(n){var e={},t={parsed:e};this.options.debug&&(t.debug=[]);for(var i=0;i=x+4&&a&1&&(e.mtime=new Date(n.readUInt32LE(i+x)*1e3),x+=4),r.extraSize>=x+4&&a&2&&(e.atime=new Date(n.readUInt32LE(i+x)*1e3),x+=4),r.extraSize>=x+4&&a&4&&(e.ctime=new Date(n.readUInt32LE(i+x)*1e3));break;case 28789:o="Info-ZIP Unicode Path Extra Field";var l=n.readUInt8(i);if(l===1){var x=1,u=n.readUInt32LE(i+x);x+=4;var c=n.slice(i+x);e.path=c.toString()}break;case 13:case 22613:o=r.extraId===13?"PKWARE Unix":"Info-ZIP UNIX (type 1)";var x=0;if(r.extraSize>=8){var d=new Date(n.readUInt32LE(i+x)*1e3);x+=4;var h=new Date(n.readUInt32LE(i+x)*1e3);if(x+=4,e.atime=d,e.mtime=h,r.extraSize>=12){var g=n.readUInt16LE(i+x);x+=2;var f=n.readUInt16LE(i+x);x+=2,e.uid=g,e.gid=f}}break;case 30805:o="Info-ZIP UNIX (type 2)";var x=0;if(r.extraSize>=4){var g=n.readUInt16LE(i+x);x+=2;var f=n.readUInt16LE(i+x);x+=2,e.uid=g,e.gid=f}break;case 30837:o="Info-ZIP New Unix";var x=0,m=n.readUInt8(i);if(x+=1,m===1){var b=n.readUInt8(i+x);x+=1,b<=6&&(e.uid=n.readUIntLE(i+x,b)),x+=b;var v=n.readUInt8(i+x);x+=1,v<=6&&(e.gid=n.readUIntLE(i+x,v))}break;case 30062:o="ASi Unix";var x=0;if(r.extraSize>=14){var C=n.readUInt32LE(i+x);x+=4;var k=n.readUInt16LE(i+x);x+=2;var T=n.readUInt32LE(i+x);x+=4;var g=n.readUInt16LE(i+x);x+=2;var f=n.readUInt16LE(i+x);if(x+=2,e.mode=k,e.uid=g,e.gid=f,r.extraSize>14){var j=i+x,N=i+r.extraSize-14,X=this._decodeString(n.slice(j,N));e.symlink=X}}break}this.options.debug&&t.debug.push({extraId:"0x"+r.extraId.toString(16),description:o,data:n.slice(i,i+r.extraSize).inspect()}),i+=r.extraSize}return t};Qi.prototype._readDataDescriptor=function(n,e){if(e){var t=Ea.parse(n).word32lu("dataDescriptorSignature").word32lu("crc32").word64lu("compressedSize").word64lu("uncompressedSize").vars;return t}var t=Ea.parse(n).word32lu("dataDescriptorSignature").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").vars;return t};Qi.prototype._readCentralDirectoryEntry=function(n){var e=Ea.parse(n).word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars;return e};Qi.prototype._readEndOfCentralDirectory64=function(n){var e=Ea.parse(n).word64lu("centralDirectoryRecordSize").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskNumberWithCentralDirectoryStart").word64lu("centralDirectoryEntries").word64lu("totalCentralDirectoryEntries").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars;return e};Qi.prototype._readEndOfCentralDirectory=function(n){var e=Ea.parse(n).word16lu("diskNumber").word16lu("diskStart").word16lu("centralDirectoryEntries").word16lu("totalCentralDirectoryEntries").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars;return e};var Npe="\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0 ";Qi.prototype._decodeString=function(n,e){if(e)return n.toString("utf8");if(this.options.decodeString)return this.options.decodeString(n);let t="";for(var i=0;i0&&(this.data=this.data.slice(t),this.data.length!==0););if(this.state===Ne.FILE_DATA){if(this.outStreamInfo.limit>=0){var i=this.outStreamInfo.limit-this.outStreamInfo.written,r;i{if(this.state===Ne.FILE_DATA_END)return this.state=Ne.START,o.end(e);e()})}return}e()};Qi.prototype.drainAll=function(){this._drainAllEntries=!0};Qi.prototype._transform=function(n,e,t){var i=this;i.data.length>0?i.data=Buffer.concat([i.data,n]):i.data=n;var r=i.data.length,o=function(){if(i.data.length>0&&i.data.length0){e._parseOrOutput("buffer",function(){if(e.data.length>0)return setImmediate(function(){e._flush(n)});n()});return}if(e.state===Ne.FILE_DATA)return n(new Error("Stream finished in an invalid state, uncompression failed"));setImmediate(n)};N3.exports=Qi});var B3=w((WHe,H3)=>{var Of=require("stream").Transform,Hpe=require("util"),Bpe=qE();function Ia(n){if(!(this instanceof Ia))return new Ia(n);var e=n||{};Of.call(this,{readableObjectMode:!0}),this.opts=n||{},this.unzipStream=new Bpe(this.opts);var t=this;this.unzipStream.on("entry",function(i){t.push(i)}),this.unzipStream.on("error",function(i){t.emit("error",i)})}Hpe.inherits(Ia,Of);Ia.prototype._transform=function(n,e,t){this.unzipStream.write(n,e,t)};Ia.prototype._flush=function(n){var e=this;this.unzipStream.end(function(){process.nextTick(function(){e.emit("close")}),n()})};Ia.prototype.on=function(n,e){return n==="entry"?Of.prototype.on.call(this,"data",e):Of.prototype.on.call(this,n,e)};Ia.prototype.drainAll=function(){return this.unzipStream.drainAll(),this.pipe(new Of({objectMode:!0,transform:function(n,e,t){t()}}))};H3.exports=Ia});var Z3=w((YHe,Y3)=>{var Af=require("path"),q3=require("fs"),W3=parseInt("0777",8);Y3.exports=fd.mkdirp=fd.mkdirP=fd;function fd(n,e,t,i){typeof e=="function"?(t=e,e={}):(!e||typeof e!="object")&&(e={mode:e});var r=e.mode,o=e.fs||q3;r===void 0&&(r=W3),i||(i=null);var s=t||function(){};n=Af.resolve(n),o.mkdir(n,r,function(a){if(!a)return i=i||n,s(null,i);switch(a.code){case"ENOENT":if(Af.dirname(n)===n)return s(a);fd(Af.dirname(n),e,function(l,u){l?s(l,u):fd(n,e,s,u)});break;default:o.stat(n,function(l,u){l||!u.isDirectory()?s(a,i):s(null,i)});break}})}fd.sync=function n(e,t,i){(!t||typeof t!="object")&&(t={mode:t});var r=t.mode,o=t.fs||q3;r===void 0&&(r=W3),i||(i=null),e=Af.resolve(e);try{o.mkdirSync(e,r),i=i||e}catch(a){switch(a.code){case"ENOENT":i=n(Af.dirname(e),t,i),n(e,t,i);break;default:var s;try{s=o.statSync(e)}catch{throw a}if(!s.isDirectory())throw a;break}}return i}});var X3=w((ZHe,U3)=>{var qpe=require("fs"),J3=require("path"),Wpe=require("util"),Ype=Z3(),$3=require("stream").Transform,Zpe=qE();function La(n){if(!(this instanceof La))return new La(n);$3.call(this),this.opts=n||{},this.unzipStream=new Zpe(this.opts),this.unfinishedEntries=0,this.afterFlushWait=!1,this.createdDirectories={};var e=this;this.unzipStream.on("entry",this._processEntry.bind(this)),this.unzipStream.on("error",function(t){e.emit("error",t)})}Wpe.inherits(La,$3);La.prototype._transform=function(n,e,t){this.unzipStream.write(n,e,t)};La.prototype._flush=function(n){var e=this,t=function(){process.nextTick(function(){e.emit("close")}),n()};this.unzipStream.end(function(){if(e.unfinishedEntries>0)return e.afterFlushWait=!0,e.on("await-finished",t);t()})};La.prototype._processEntry=function(n){var e=this,t=J3.join(this.opts.path,n.path),i=n.isDirectory?t:J3.dirname(t);this.unfinishedEntries++;var r=function(){var o=qpe.createWriteStream(t);o.on("close",function(){e.unfinishedEntries--,e._notifyAwaiter()}),o.on("error",function(s){e.emit("error",s)}),n.pipe(o)};if(this.createdDirectories[i]||i===".")return r();Ype(i,function(o){if(o)return e.emit("error",o);if(e.createdDirectories[i]=!0,n.isDirectory){e.unfinishedEntries--,e._notifyAwaiter();return}r()})};La.prototype._notifyAwaiter=function(){this.afterFlushWait&&this.unfinishedEntries===0&&(this.emit("await-finished"),this.afterFlushWait=!1)};U3.exports=La});var G3=w(WE=>{"use strict";WE.Parse=B3();WE.Extract=X3()});function Jpe(n){let e=n.etag;if(typeof e=="string"&&(e=e.replace(/^W\//,""),!(!e.startsWith('"')||!e.endsWith('"'))))return e.slice(1,-1)}function $pe(n){let i=xG().parse(n).parameters.filename;if(i)return R.extname(i)}function Nf(n,e,t){let i=zR(n),{etagAlgorithm:r}=e,{dest:o,onProgress:s,extract:a}=e;if(!o||!R.isAbsolute(o))throw new Error("Expect absolute file path for dest option.");if(!F.existsSync(o))F.mkdirSync(o,{recursive:!0});else{let h=F.statSync(o);if(h&&!h.isDirectory())throw new Error(`${o} exists, but not directory!`)}let l=GR(i),u=QR(i,e);!u.agent&&e.agent&&(u.agent=e.agent);let c=R.extname(i.pathname),d=!1;return new Promise((h,g)=>{if(t){let b=t.onCancellationRequested(()=>{b.dispose(),m.destroy(new Error("request aborted"))})}let f,m=l.request(u,b=>{if(b.statusCode>=200&&b.statusCode<300||b.statusCode===1223){let v=b.headers,x=v["content-disposition"],C=Jpe(v),k=C&&typeof r=="string";if(!c&&x&&(c=$pe(x)),a===!0)if(c===".zip"||v["content-type"]=="application/zip")a="unzip";else if(c==".tgz")a="untar";else{g(new Error(`Unable to detect extract method for ${i}`));return}let T=Number(v["content-length"]),j=!isNaN(T),N=0;b.on("error",Y=>{g(new Error(`Unable to connect ${i}: ${Y.message}`))});let X=k?Ab.createHash(r):void 0;b.on("data",Y=>{if(N+=Y.length,X&&X.update(Y),j){let K=(N/T*100).toFixed(1);typeof s=="function"?s(K):YE.info(`Download ${i} progress ${K}%`)}}),b.on("end",()=>{clearTimeout(f),f=void 0,YE.info("Download completed:",i)});let se;if(a==="untar"){let Y=f3();se=b.pipe(Y.x({strip:e.strip??1,C:o}))}else if(a==="unzip"){let Y=G3();se=b.pipe(Y.Extract({path:o}))}else o=R.join(o,`${Fl()}${c}`),se=b.pipe(F.createWriteStream(o));se.on("finish",()=>{if(X&&X.digest("hex")!==C){g(new Error(`Etag check failed by ${r}, content not match.`));return}YE.info(`Downloaded ${i} => ${o}`),setTimeout(()=>{h(o)},100)}),se.on("error",g)}else g(new Error(`Invalid response from ${i}: ${b.statusCode}`))});m.on("error",b=>{if(u.agent&&b.code=="ECONNRESET")f=setTimeout(()=>{d=!0,g(b)},XR);else{if(clearTimeout(f),u.agent&&u.agent.proxy){g(new Error(`Request failed using proxy ${u.agent.proxy.host}: ${b.message}`));return}d=!0,g(b)}}),m.on("timeout",()=>{m.destroy(new Error(`request timeout after ${e.timeout}ms`))}),typeof e.timeout=="number"&&e.timeout&&m.setTimeout(e.timeout),m.end()})}var YE,ZE=D(()=>{"use strict";rt();xe();de();ww();YE=Z("model-download")});function Xpe(n=Pt.homedir()){let e,t=R.join(n,".npmrc");if(F.existsSync(t))try{let i=F.readFileSync(t,"utf8"),r;for(let o of i.split(/\r?\n/)){if(o.startsWith("#"))continue;let s=o.match(/^(.*?)=(.*)$/);s&&s[1]==="coc.nvim:registry"&&(r=s[2])}r&&(e=new Rx.URL(r))}catch(i){Q3.debug("Error on parse .npmrc:",i)}return e??new Rx.URL("https://registry.npmjs.org")}function Gpe(n){let e=R.basename(n);return e==="npm"||e==="npm.CMD"}function zpe(n){let e=R.basename(n);return["yarn","yarn.CMD","yarnpkg","yarnpkg.CMD"].includes(e)}function Kpe(n){let e=R.basename(n);return e==="pnpm"||e==="pnpm.CMD"}function z3(n){return!!(F.existsSync(n)&&F.lstatSync(n).isSymbolicLink())}function Qpe(n){return Object.keys(n.dependencies??{}).filter(e=>!Upe.includes(e))}var K3,Rx,Q3,Upe,_x,V3=D(()=>{"use strict";K3=require("events"),Rx=require("url");rt();xe();ZE();ww();st();de();fe();he();Q3=Z("extension-installer"),Upe=["coc.nvim","esbuild","webpack","@types/node"];_x=class extends K3.EventEmitter{constructor(t,i,r){super();this.root=t;this.npm=i;this.def=r;if(/^https?:/.test(r))this.url=r;else{let o=r.match(/(.+)@([^/]+)$/);o?(this.name=o[1],this.version=o[2]):this.name=r}}get info(){return{name:this.name,version:this.version}}async getInfo(){if(this.url)return await this.getInfoFromUri();let t=Xpe();this.log(`Get info from ${t}`);let i=await this.fetch(new Rx.URL(this.name,t),{timeout:1e4,buffer:!0}),r=JSON.parse(i.toString());this.version||(this.version=r["dist-tags"].latest);let o=r.versions[this.version];if(!o)throw new Error(`${this.def} doesn't exists in ${t}.`);let s=o.engines&&o.engines.coc;if(!s)throw new Error(`${this.def} is not a valid coc extension, "engines" field with coc property required.`);return{"dist.tarball":o.dist.tarball,"engines.coc":s,version:o.version,name:r.name}}async getInfoFromUri(){let{url:t}=this;if(!t.startsWith("https://github.com"))throw new Error(`"${t}" is not supported, coc.nvim support github.com only`);t=t.replace(/\/$/,"");let i="master";if(t.includes("@")){let a=t.indexOf("@");i=t.substr(a+1),t=t.substring(0,a)}let r=t.replace("github.com","raw.githubusercontent.com")+`/${i}/package.json`;this.log(`Get info from ${r}`);let o=await this.fetch(r,{timeout:1e4}),s=typeof o=="string"?JSON.parse(o):o;return this.name=s.name,{"dist.tarball":`${t}/archive/${i}.tar.gz`,"engines.coc":s.engines?s.engines.coc:null,name:s.name,version:s.version}}log(t,i=!1){this.emit("message",t,i)}async install(){this.log(`Using npm from: ${this.npm}`);let t=await this.getInfo();Q3.info(`Fetched info of ${this.def}`,t);let{name:i,version:r}=t,o=oe(t["engines.coc"]).replace(/^\^/,">=");if(o&&!sr.satisfies(y.version,o))throw new Error(`${i} ${t.version} requires coc.nvim >= ${o}, please update coc.nvim.`);let s=await this.doInstall(t);return{name:i,updated:s,version:r,url:this.url,folder:R.join(this.root,t.name)}}async update(t){t&&(this.url=t);let i;if(this.name){let l=R.join(this.root,this.name);if(z3(l)){this.log("Skipped update for symbol link");return}i=Xr(R.join(l,"package.json")).version}this.log(`Using npm from: ${this.npm}`);let r=await this.getInfo();if(i&&r.version&&sr.gte(i,r.version)){this.log(`Current version ${i} is up to date.`);return}let o=r["engines.coc"]?r["engines.coc"].replace(/^\^/,">="):"";if(o&&!sr.satisfies(y.version,o))throw new Error(`${r.version} requires coc.nvim ${o}, please update coc.nvim.`);if(!await this.doInstall(r))return;let a=R.join(this.root,r.name,"package.json");return this.log(`Updated to v${r.version}`),R.dirname(a)}getInstallArguments(t,i){let r=["install","--ignore-scripts","--no-lockfile"];return i&&i.startsWith("https://github.com")&&(r=["install"]),Gpe(t)&&(r.push("--omit=dev"),r.push("--legacy-peer-deps"),r.push("--no-global")),zpe(t)&&(r.push("--production"),r.push("--ignore-engines")),Kpe(t)&&(r.push("--production"),r.push("--config.strict-peer-dependencies=false")),r}readLines(t,i){ho.createInterface({input:i}).on("line",o=>{this.log(`${t} ${o}`,!0)})}installDependencies(t,i){return i.length==0?Promise.resolve():new Promise((r,o)=>{let s=this.getInstallArguments(this.npm,this.url);this.log(`Installing dependencies by: ${this.npm} ${s.join(" ")}.`);let a=pn.spawn(this.npm,s,{cwd:t,env:Object.assign(process.env,{NODE_ENV:"production"})});this.readLines("[npm stdout]",a.stdout),this.readLines("[npm stderr]",a.stderr),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8"),a.on("error",o),a.on("exit",l=>{if(l){o(new Error(`${this.npm} install exited with ${l}`));return}r()})})}async doInstall(t){let i=R.join(this.root,t.name);if(z3(i))return!1;let r=t.name.replace(/\//g,"_"),o=R.join(this.root,`${r}-${me()}`),s=t["dist.tarball"];this.log(`Downloading from ${s}`);let a=s.startsWith("https://registry.npmjs.org")?"md5":void 0;try{await this.download(s,{dest:o,etagAlgorithm:a,extract:"untar",onProgress:u=>this.log(`Download progress ${u}%`,!0)}),this.log(`Extension download at ${o}`);let l=Xr(R.join(o,"package.json"));await this.installDependencies(o,Qpe(l))}catch(l){throw F.rmSync(o,{recursive:!0,force:!0}),l}return this.log(`Download extension ${t.name}@${t.version} at ${o}`),F.mkdirSync(R.dirname(i),{recursive:!0}),F.existsSync(i)&&F.rmSync(i,{force:!0,recursive:!0}),F.renameSync(o,i),this.log(`Move extension ${t.name}@${t.version} to ${i}`),!0}async download(t,i){return await Nf(t,i)}async fetch(t,i={}){return await gf(t,i)}}});var Hf,eQ=D(()=>{"use strict";st();de();Be();Hf=class{constructor(e){this.filepath=e;F.existsSync(e)||F.writeFileSync(e,"{}","utf8")}merge(e){if(!F.existsSync(e))return;let t=Xr(e),i=Xr(this.filepath);Object.assign(i,t),Ks(this.filepath,i),F.unlinkSync(e)}fetchContent(e,t){let r=Xr(this.filepath)[e];if(!!r)return r[t]}async update(e,t,i){let{filepath:r}=this,o=Xr(r);o[e]=o[e]||{},i!==void 0?o[e][t]=Li(i):delete o[e][t],Ks(r,o)}createMemento(e){return{get:(t,i)=>{let r=this.fetchContent(e,t);return r===void 0?i:r},update:async(t,i)=>{await this.update(e,t,i)}}}}});var tQ,Vpe,efe,Bf,iQ=D(()=>{"use strict";tQ=require("events");xe();te();de();he();Vpe=pn.spawn,efe=Z("list-commandTask"),Bf=class extends tQ.EventEmitter{constructor(t){super();this.opt=t;this.disposables=[];this.start()}start(){let{cmd:t,args:i,cwd:r,onLine:o}=this.opt,s=Vpe(t,i,{cwd:r||y.cwd,windowsHide:!0});this.disposables.push({dispose:()=>{s.kill()}}),s.on("error",l=>{this.emit("error",l.message)}),s.stderr.on("data",l=>{efe.error(`[${t} Error]`,l.toString("utf8"))});let a=ho.createInterface(s.stdout);a.on("line",l=>{let u=o(l);u&&this.emit("data",u)}),a.on("close",()=>{this.emit("end")})}dispose(){W(this.disposables)}}});var tu,JE,lt,Fa=D(()=>{"use strict";We();he();tu=["","","","","","","","","","","","","","","","","","","","<2-LeftMouse>","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],JE=class{get debounceTime(){return this.get("interactiveDebounceTime",100)}get extendedSearchMode(){return this.get("extendedSearchMode",!0)}get smartcase(){return this.get("smartCase",!1)}get signOffset(){return this.get("signOffset",900)}get(e,t){return y.initialConfiguration.get("list."+e,t)}get previousKey(){return this.fixKey(this.get("previousKeymap",""))}get nextKey(){return this.fixKey(this.get("nextKeymap",""))}fixKey(e){if(tu.includes(e))return e;let t=tu.find(i=>i.toLowerCase()==e.toLowerCase());return t||(P.showErrorMessage(`Configured key "${e}" not supported.`),null)}},lt=new JE});function tfe(n){switch(n){case"latex":return"tex";default:return n}}var hi,Mo=D(()=>{"use strict";ae();Je();te();st();Tt();fe();he();iQ();Fa();hi=class{constructor(){this.defaultAction="open";this.actions=[];this.options=[];this.disposables=[];this.nvim=y.nvim,this.config=lt}get alignColumns(){return lt.get("alignColumns",!1)}get floatPreview(){return lt.get("floatPreview",!1)}get hlGroup(){return lt.get("previewHighlightGroup","Search")}get previewHeight(){return lt.get("maxPreviewHeight",12)}get splitRight(){return lt.get("previewSplitRight",!1)}get toplineStyle(){return lt.get("previewToplineStyle","offset")}get toplineOffset(){return lt.get("previewToplineOffset",3)}parseArguments(e){if(!this.optionMap){this.optionMap=new Map;for(let i of this.options){let r=i.name.split(/,\s*/g).map(s=>s.replace(/\s+.*/g,"")),o=i.key?i.key:r[r.length-1].replace(/^-/,"");for(let s of r)this.optionMap.set(s,{name:o,hasValue:i.hasValue})}}let t={};for(let i=0;i{let r=await this.convertLocation(t.location);await this.previewLocation(r,i)}});let{nvim:e}=this;this.createAction({name:"quickfix",multiple:!0,execute:async t=>{let i=await Promise.all(t.map(o=>this.convertLocation(o.location).then(s=>y.getQuickfixItem(s))));await e.call("setqflist",[i]);let r=await e.getVar("coc_quickfix_open_command");e.command(typeof r=="string"?r:"copen",!0)}});for(let t of["open","tabe","drop","vsplit","split"])this.createAction({name:t,execute:async(i,r)=>{await this.jumpTo(i.location,t=="open"?null:t,r)},tabPersist:t==="open"})}async convertLocation(e){if(typeof e=="string")return Ke.create(e,M.create(0,0,0,0));if(Ke.is(e))return e;let t=O.parse(e.uri);return t.scheme!="file"?Ke.create(e.uri,M.create(0,0,0,0)):await NZ(t.fsPath,e.line,e.text)}async jumpTo(e,t,i){if(t==null&&i&&i.options.position==="tab"&&(t="tabe"),typeof e=="string"){await y.jumpTo(e,null,t);return}let{range:r,uri:o}=await this.convertLocation(e),s=r.start;s.line==0&&s.character==0&&Ge(s,r.end)==0&&(s=null),await y.jumpTo(o,s,t)}createAction(e){let{name:t}=e,i=this.actions.findIndex(r=>r.name==t);i!==-1&&this.actions.splice(i,1),this.actions.push(e)}async previewLocation(e,t){let{uri:i,range:r}=e,o=y.getDocument(e.uri),s=O.parse(i),a=await y.documentsManager.getLines(i),l={bufnr:o?o.bufnr:void 0,winid:t.window.id,range:Gt(r)?null:r,lnum:r.start.line+1,name:s.scheme=="file"?s.fsPath:i,filetype:tfe(o?o.languageId:y.documentsManager.getLanguageId(s.fsPath)),position:t.options.position,maxHeight:this.previewHeight,splitRight:this.splitRight,hlGroup:this.hlGroup,scheme:s.scheme,toplineStyle:this.toplineStyle,toplineOffset:this.toplineOffset,targetRange:e.targetRange};await this.openPreview(a,l)}async preview(e,t){let{bufname:i,filetype:r,range:o,lines:s,lnum:a}=e,l={winid:t.window.id,lnum:o?o.start.line+1:a||1,filetype:r,position:t.options.position,maxHeight:this.previewHeight,splitRight:this.splitRight,hlGroup:this.hlGroup,toplineStyle:this.toplineStyle,toplineOffset:this.toplineOffset};i&&(l.name=i),o&&(l.range=o),await this.openPreview(s,l)}async openPreview(e,t){let{nvim:i}=this;this.floatPreview&&t.position!=="tab"?await i.call("coc#list#float_preview",[e,t]):await i.call("coc#list#preview",[e,t]),i.command("redraw",!0)}doHighlight(){}dispose(){W(this.disposables)}}});function md(n){let e=n.length,t=new Uint16Array(e);for(let i=0,r=e;i=97&&n<=122&&e+32===n||t&&(n<=90&&n+32===e||$E(n)===e))return!0}else{let i=$E(e);if(i===n||t&&$E(n)===i)return!0}return!1}function $E(n){return String.fromCharCode(n).toLowerCase().charCodeAt(0)}function bd(n,e,t=!1){let i=n.length,r=e.length;if(i>r)return!1;let o=0,s=n[0];for(let a=0;a{"use strict";Yt()});var ife,XE,qf,GE,zE=D(()=>{"use strict";de();xe();fe();Yt();ife=Z("list-db"),XE=R.join(Gn,"list_history.dat"),qf=class{constructor(){this.folders=[];this.names=[];this.items=[];this._changed=!1;try{this.load()}catch(e){ife.error("Error on load db",e)}}get currItems(){return this.items}getHistory(e,t){let i=this.names.indexOf(e),r=this.folders.indexOf(t);return i==-1||r==-1?[]:this.items.reduce((o,s)=>(s[1]==i&&s[2]==r&&o.push(s[0]),o),[])}addItem(e,t,i){let{folders:r,names:o}=this;ue(t)>255&&(t=Xt(t,0,255)),r.includes(i)||r.push(i),o.includes(e)||o.push(e);let s=o.indexOf(e),a=r.indexOf(i),l=this.items.findIndex(u=>u[0]==t&&u[1]==s&&u[2]==a);l!=-1&&this.items.splice(l,1),this.items.push([t,s,a]),this._changed=!0}save(){let{folders:e,items:t,names:i}=this;if(!this._changed)return;let r=e.reduce((u,c)=>(u.push(Buffer.from(c,"utf8"),Buffer.alloc(1)),u),[]),o=Buffer.concat(r);r=i.reduce((u,c)=>(u.push(Buffer.from(c,"utf8"),Buffer.alloc(1)),u),[]);let s=Buffer.concat(r),a=Buffer.allocUnsafe(9);a.writeUInt8(2,0),a.writeUInt32BE(o.byteLength,1),a.writeUInt32BE(s.byteLength,5),r=t.reduce((u,c)=>{let d=Buffer.from(c[0],"utf8");return u.push(Buffer.from([d.byteLength]),d,Buffer.from([c[1],c[2]])),u},[]);let l=Buffer.concat([a,o,s,...r]);F.writeFileSync(XE,l),this._changed=!1}load(){if(!F.existsSync(XE))return;let e=F.readFileSync(XE),t=e.readUInt32BE(1),i=e.readUInt32BE(5),r=e.slice(9,9+t),o=0,s=[],a=[];for(let h=0;h{"use strict";de();xe();Re();Ex();zE();fe();nfe=Z("list-history"),iu=class{constructor(e,t,i,r){this.prompt=e;this.name=t;this.db=i;this.cwd=r;this._index=-1;this._filtered=[]}get loaded(){return this.db.getHistory(this.name,this.cwd)}get filtered(){return this._filtered}get index(){return this._index}static migrate(e){try{let t=F.readdirSync(e);if(t=t.filter(r=>r.startsWith("list-")&&r.endsWith("-history.json")&&F.statSync(R.join(e,r)).isFile()),t.length===0)return;let i=new qf;for(let r of t){let o=r.match(/^list-(.*)-history.json$/)[1],s=F.readFileSync(R.join(e,r),"utf8"),a=JSON.parse(s);for(let[l,u]of Object.entries(a)){let c=Buffer.from(l,"base64").toString("utf8");Array.isArray(u)&&u.forEach(d=>{i.addItem(o,d,c)})}}t.forEach(r=>{F.unlinkSync(R.join(e,r))}),i.save()}catch(t){nfe.error("Error on migrate history:",t)}}get curr(){return this._index==-1||this._filtered==null?null:this._filtered[this._index]}filter(){let{input:e}=this.prompt;if(e!==this.curr){if(this.historyInput="",e.length>0){let t=md(e);this._filtered=this.loaded.filter(i=>bd(t,i))}else this._filtered=this.loaded;this._index=-1}}add(){let{db:e,prompt:t,cwd:i}=this,{input:r}=t;!r||r.length<2||r==this.historyInput||e.addItem(this.name,r,i)}previous(){let{_filtered:e,_index:t}=this;re(e)||(t<=0?this._index=e.length-1:this._index=t-1,this.historyInput=this.prompt.input=oe(e[this._index]))}next(){let{_filtered:e,_index:t}=this;re(e)||(t==e.length-1?this._index=0:this._index=t+1,this.historyInput=this.prompt.input=oe(e[this._index]))}}});var Wf,nQ=D(()=>{"use strict";We();Fa();Wf=class{constructor(e,t){this.manager=e;this.nvim=t;this.insertMappings=new Map;this.normalMappings=new Map;this.userInsertMappings=new Map;this.userNormalMappings=new Map;this.actions=new Map;let{prompt:i}=e;this.addAction("do:switch",async()=>{await e.switchMatcher()}),this.addAction("do:selectall",async()=>{var r;await((r=e.session)==null?void 0:r.ui.selectAll())}),this.addAction("do:help",async()=>{var r;await((r=e.session)==null?void 0:r.showHelp())}),this.addAction("do:refresh",async()=>{var r;await((r=e.session)==null?void 0:r.reloadItems())}),this.addAction("do:exit",async()=>{await e.cancel()}),this.addAction("do:stop",()=>{e.stop()}),this.addAction("do:cancel",async()=>{await e.cancel(!1)}),this.addAction("do:toggle",async()=>{var r;await((r=e.session)==null?void 0:r.ui.toggleSelection())}),this.addAction("do:jumpback",()=>{var r;(r=e.session)==null||r.jumpBack()}),this.addAction("do:previous",async()=>{await this.navigate(!0)}),this.addAction("do:next",async()=>{await this.navigate(!1)}),this.addAction("do:defaultaction",async()=>{await e.doAction()}),this.addAction("do:chooseaction",async()=>{await e.chooseAction()}),this.addAction("do:togglemode",()=>{e.toggleMode()}),this.addAction("do:previewtoggle",async()=>{await e.togglePreview()}),this.addAction("do:previewup",()=>{this.scrollPreview("up")}),this.addAction("do:previewdown",()=>{this.scrollPreview("down")}),this.addAction("do:command",async()=>{await e.cancel(!1),await t.eval('feedkeys(":")')}),this.addAction("prompt:previous",()=>{var r;(r=e.session)==null||r.history.previous()}),this.addAction("prompt:next",()=>{var r;(r=e.session)==null||r.history.next()}),this.addAction("prompt:start",()=>{i.moveToStart()}),this.addAction("prompt:end",()=>{i.moveToEnd()}),this.addAction("prompt:left",()=>{i.moveLeft()}),this.addAction("prompt:right",()=>{i.moveRight()}),this.addAction("prompt:deleteforward",()=>{i.onBackspace()}),this.addAction("prompt:deletebackward",()=>{i.removeNext()}),this.addAction("prompt:removetail",()=>{i.removeTail()}),this.addAction("prompt:removeahead",()=>{i.removeAhead()}),this.addAction("prompt:removeword",()=>{i.removeWord()}),this.addAction("prompt:insertregister",()=>{i.insertRegister()}),this.addAction("prompt:paste",async()=>{await i.paste()}),this.addAction("eval",async r=>{await i.eval(r)}),this.addAction("command",async r=>{await e.command(r)}),this.addAction("action",async r=>{await e.doAction(r)}),this.addAction("feedkeys",async r=>{await e.feedkeys(r)}),this.addAction("feedkeys!",async r=>{await e.feedkeys(r,!1)}),this.addAction("normal",async r=>{await e.normal(r,!1)}),this.addAction("normal!",async r=>{await e.normal(r,!0)}),this.addAction("call",async r=>{await e.call(r)}),this.addAction("expr",async r=>{let o=await e.call(r);o&&await e.doAction(o)}),this.addKeyMapping("insert","","do:switch"),this.addKeyMapping("insert","","prompt:next"),this.addKeyMapping("insert","","prompt:previous"),this.addKeyMapping("insert","","prompt:paste"),this.addKeyMapping("insert",["",""],"do:defaultaction"),this.addKeyMapping("insert",["",""," "],"do:chooseaction"),this.addKeyMapping("insert","","do:togglemode"),this.addKeyMapping("insert","","do:stop"),this.addKeyMapping("insert","","do:refresh"),this.addKeyMapping("insert","","prompt:left"),this.addKeyMapping("insert","","prompt:right"),this.addKeyMapping("insert",["",""],"prompt:end"),this.addKeyMapping("insert",["",""],"prompt:start"),this.addKeyMapping("insert",["","",""],"prompt:deleteforward"),this.addKeyMapping("insert","","prompt:removeword"),this.addKeyMapping("insert","","prompt:removeahead"),this.addKeyMapping("insert","","prompt:insertregister"),this.addKeyMapping("normal","t","action:tabe"),this.addKeyMapping("normal","s","action:split"),this.addKeyMapping("normal","d","action:drop"),this.addKeyMapping("normal",["","","\r"],"do:defaultaction"),this.addKeyMapping("normal","","do:selectall"),this.addKeyMapping("normal"," ","do:toggle"),this.addKeyMapping("normal","p","do:previewtoggle"),this.addKeyMapping("normal",[""," ",""],"do:chooseaction"),this.addKeyMapping("normal","","do:stop"),this.addKeyMapping("normal","","do:refresh"),this.addKeyMapping("normal","","do:jumpback"),this.addKeyMapping("normal","","do:previewdown"),this.addKeyMapping("normal","","do:previewup"),this.addKeyMapping("normal",["i","I","o","O","a","A"],"do:togglemode"),this.addKeyMapping("normal","?","do:help"),this.addKeyMapping("normal",":","do:command"),this.createMappings()}createMappings(){let e=lt.get("insertMappings",{});this.userInsertMappings=this.fixUserMappings(e,"list.insertMappings");let t=lt.get("normalMappings",{});this.userNormalMappings=this.fixUserMappings(t,"list.normalMappings")}hasUserMapping(e,t){return(e=="insert"?this.userInsertMappings:this.userNormalMappings).has(t)}isValidAction(e){if(this.actions.has(e))return!0;let[t,i]=e.split(":",2);return!(!i||!this.actions.has(t))}fixUserMappings(e,t){let i=new Map;for(let[r,o]of Object.entries(e)){if(!this.isValidAction(o)){P.showWarningMessage(`Invalid configuration - unable to support action "${o}" in "${t}"`);continue}if(r.length==1)i.set(r,o);else if(r.startsWith("<")&&r.endsWith(">"))if(r.toLowerCase()=="")i.set(" ",o);else if(r.toLowerCase()=="")i.set("",o);else if(tu.includes(r))i.set(r,o);else{let s=!1;for(let a=0;athis.doAction(e);let[t,i]=e.split(":",2);if(!i||!this.actions.has(t))throw new Error(`Invalid action ${e}`);return()=>this.doAction(t,i)}async doAction(e,t){let i=this.actions.get(e);if(!i)throw new Error(`Action ${e} doesn't exist`);await Promise.resolve(i(t))}scrollPreview(e){let{nvim:t}=this;t.pauseNotification(),t.call("coc#list#scroll_preview",[e],!0),t.command("redraw",!0),t.resumeNotification(!1,!0)}}});var Yf,rQ=D(()=>{"use strict";U();Fa();Yf=class{constructor(e){this.nvim=e;this.cusorIndex=0;this._input="";this._mode="insert";this.interactive=!1;this.requestInput=!1;this._onDidChangeInput=new p.Emitter;this.onDidChangeInput=this._onDidChangeInput.event}get input(){return this._input}set input(e){this._input!=e&&(this.cusorIndex=e.length,this._input=e,this.drawPrompt(),this._onDidChangeInput.fire(this._input))}get mode(){return this._mode}set mode(e){e!=this._mode&&(this._mode=e,this.drawPrompt())}set matcher(e){this._matcher=e,this.drawPrompt()}start(e){e&&(this.interactive=e.interactive,this.cusorIndex=e.input.length,this._input=e.input,this._mode=e.mode,this._matcher=e.interactive?"":e.matcher),this.nvim.call("coc#prompt#start_prompt",["list"],!0),this.drawPrompt()}cancel(){let{nvim:e}=this;e.call("coc#prompt#stop_prompt",["list"],!0)}reset(){this._input="",this.cusorIndex=0}drawPrompt(){let e=lt.get("indicator",">"),{cusorIndex:t,interactive:i,input:r,_matcher:o}=this,s=['echo ""'];if(this.mode=="insert")if(i?s.push("echohl MoreMsg | echon 'INTERACTIVE ' | echohl None"):o&&s.push(`echohl MoreMsg | echon '${o.toUpperCase()} ' | echohl None`),s.push(`echohl Special | echon '${e} ' | echohl None`),t==r.length)s.push(`echon '${r.replace(/'/g,"''")}'`),s.push("echohl Cursor | echon ' ' | echohl None");else{let l=r.slice(0,t);l&&s.push(`echon '${l.replace(/'/g,"''")}'`),s.push(`echohl Cursor | echon '${r[t].replace(/'/,"''")}' | echohl None`);let u=r.slice(t+1);s.push(`echon '${u.replace(/'/g,"''")}'`)}else s.push('echohl MoreMsg | echo "" | echohl None');s.push("redraw");let a=s.join("|");this.nvim.command(a,!0)}moveLeft(){this.cusorIndex!=0&&(this.cusorIndex=this.cusorIndex-1,this.drawPrompt())}moveRight(){this.cusorIndex!=this._input.length&&(this.cusorIndex=this.cusorIndex+1,this.drawPrompt())}moveToEnd(){this.cusorIndex!=this._input.length&&(this.cusorIndex=this._input.length,this.drawPrompt())}moveToStart(){this.cusorIndex!=0&&(this.cusorIndex=0,this.drawPrompt())}onBackspace(){let{cusorIndex:e,input:t}=this;if(e==0)return;let i=t.slice(0,e),r=t.slice(e);this.cusorIndex=e-1,this._input=`${i.slice(0,i.length-1)}${r}`,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}removeNext(){let{cusorIndex:e,input:t}=this;if(e==t.length)return;let i=t.slice(0,e),r=t.slice(e+1);this._input=`${i}${r}`,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}removeWord(){let{cusorIndex:e,input:t}=this;if(e==0)return;let i=t.slice(0,e),r=t.slice(e),o=i.replace(/[\w$]+([^\w$]+)?$/,"");this.cusorIndex=e-(i.length-o.length),this._input=`${o}${r}`,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}removeTail(){let{cusorIndex:e,input:t}=this;if(e==t.length)return;let i=t.slice(0,e);this._input=i,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}removeAhead(){let{cusorIndex:e,input:t}=this;if(e==0)return;let i=t.slice(e);this.cusorIndex=0,this._input=i,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}async acceptCharacter(e){if(this.requestInput){if(this.requestInput=!1,/^[0-9a-z"%#*+/:\-.]$/.test(e)){let t=await this.nvim.call("getreg",e);t=t.replace(/\n/g," "),this.addText(t)}}else this.addText(e)}insertRegister(){this.requestInput=!0}async paste(){let e=await this.nvim.eval("@*");e=e.replace(/\n/g,""),e&&this.addText(e)}async eval(e){let t=await this.nvim.call("eval",[e]);t=t.replace(/\n/g,""),this.addText(t)}addText(e){let{cusorIndex:t,input:i}=this;this.cusorIndex=t+e.length;let r=i.slice(0,t),o=i.slice(t);this._input=`${r}${e}${o}`,this.drawPrompt(),this._onDidChangeInput.fire(this._input)}}});var Ix,oQ=D(()=>{"use strict";Ix=class{constructor(){this._busy=!1;this._fns=[];this._resolves=[]}run(e){this._busy?this._fns.push(e):(this._busy=!0,e().finally(()=>{this.next()}))}waitFinish(){return this._busy?new Promise(e=>{this._resolves.push(e)}):Promise.resolve()}next(){let e=this._fns.shift();e?e().finally(()=>{this.next()}):this.finish()}finish(){this._busy=!1;let e;for(;(e=this._resolves.pop())!=null;)e()}cancel(){this._fns=[],this.finish()}}});var rfe,Zf,sQ=D(()=>{"use strict";Pe();te();Re();de();U();oQ();fe();he();Fa();rfe=pe(100,20),Zf=class{constructor(e,t,i){this.nvim=e;this.name=t;this.listOptions=i;this.newTab=!1;this.reversed=!1;this.currIndex=0;this.items=[];this.disposables=[];this.selected=new Set;this.sequence=new Ix;this._onDidChangeLine=new p.Emitter;this._onDidOpen=new p.Emitter;this._onDidClose=new p.Emitter;this._onDidLineChange=new p.Emitter;this._onDoubleClick=new p.Emitter;this.onDidChangeLine=this._onDidChangeLine.event;this.onDidLineChange=this._onDidLineChange.event;this.onDidOpen=this._onDidOpen.event;this.onDidClose=this._onDidClose.event;this.onDidDoubleClick=this._onDoubleClick.event;this.newTab=i.position=="tab",this.reversed=i.reverse===!0,_.on("BufWinLeave",async o=>{o!=this.bufnr||this.window==null||(this.window=null,this._onDidClose.fire(o))},null,this.disposables),_.on("CursorMoved",async(o,s)=>{if(o!=this.bufnr)return;let a=this.lnumToIndex(s[0]);this.onLineChange(a)},null,this.disposables);let r=ft(async o=>{if(o!=this.bufnr)return;let[s,a,l]=await e.eval('[win_getid(),line("w0"),line("w$")]');if(l<300||s!=this.winid)return;let u=l-a+1,c=this.lnumToIndex(a),d=this.lnumToIndex(a+u*2);e.pauseNotification(),this.doHighlight(c,d),e.command("redraw",!0),e.resumeNotification(!1,!0)},rfe);this.disposables.push({dispose:()=>{r.clear()}}),_.on("CursorMoved",r,null,this.disposables)}onDidChangeItems(e){e.append||this.clearSelection(),this.sequence.run(async()=>{let{items:t,reload:i,append:r,finished:o,sorted:s}=e;this.shouldSort&&!s&&(t=r?this.items.concat(t):t,i=r==!0,r=!1,t.sort((a,l)=>a.score!=l.score?l.score-a.score:a.sortText>l.sortText?1:-1)),r?await this.appendItems(t):await this.drawItems(t,o,i)})}lnumToIndex(e){let{reversed:t,length:i}=this;return t?Math.max(0,i-e):e-1}indexToLnum(e){let{reversed:t,length:i}=this;return t?Math.max(Math.min(i,i-e),1):Math.min(e+1,i)}get bufnr(){var e;return(e=this.buffer)==null?void 0:e.id}get winid(){var e;return(e=this.window)==null?void 0:e.id}get limitLines(){return lt.get("limitLines",1/0)}onLineChange(e){this.currIndex!=e&&(this.currIndex=e,this._onDidChangeLine.fire(e))}get index(){return this.currIndex}getItem(e){return this.items[e]}get item(){let{window:e}=this;return e?e.cursor.then(t=>(this.currIndex=this.lnumToIndex(t[0]),this.items[this.currIndex])):Promise.resolve(null)}async echoMessage(e){let{items:t}=this,r=`[${t.indexOf(e)+1}/${t.length}] ${oe(e.label)}`;this.nvim.callTimer("coc#ui#echo_lines",[[r]],!0)}updateItem(e,t){if(!this.buffer||t>=this.length)return;let{nvim:i}=this,r=this.indexToLnum(t);i.pauseNotification(),this.buffer.setOption("modifiable",!0,!0),i.call("setbufline",[this.bufnr,r,e.label],!0),this.doHighlight(t,t+1),this.buffer.setOption("modifiable",!1,!0),i.resumeNotification(!0,!0)}async getItems(){if(this.length==0||!this.window)return[];let e=await this.nvim.call("mode");if(e=="v"||e=="V"){let[r,o]=await this.getSelectedRange(),s=[];for(let a=r;a<=o;a++){let l=this.lnumToIndex(a),u=this.items[l];u&&s.push(u)}return s}let{selectedItems:t}=this;if(t.length)return t;let i=await this.item;return le(i)}async onMouse(e){let{nvim:t,window:i}=this;if(!i)return;let[r,o,s]=await t.eval("[v:mouse_winid,v:mouse_lnum,v:mouse_col]");if(e=="mouseDown"){this.mouseDown={winid:r,lnum:o,col:s,current:r==i.id};return}let a=r==i.id;if(a&&e=="doubleClick"&&(this.setCursor(o),this._onDoubleClick.fire()),a&&e=="mouseDrag"){if(!this.mouseDown)return;await this.selectLines(this.mouseDown.lnum,o)}else if(a&&e=="mouseUp"){if(!this.mouseDown)return;this.mouseDown.lnum==o?(this.setCursor(o),t.command("redraw",!0)):await this.selectLines(this.mouseDown.lnum,o)}else!a&&e=="mouseUp"&&(t.pauseNotification(),t.call("win_gotoid",r,!0),t.call("cursor",[o,s],!0),t.command("redraw",!0),t.resumeNotification(!1,!0))}async resume(){let{items:e,selected:t,nvim:i}=this;if(await this.drawItems(e,!0,!0),!(!t.size||!this.buffer)){i.pauseNotification();for(let r of t)this.buffer.placeSign({lnum:r,id:lt.signOffset+r,name:"CocSelected",group:"coc-list"});i.command("redraw",!0),i.resumeNotification(!1,!0)}}async toggleSelection(){let{nvim:e,reversed:t}=this;await e.call("win_gotoid",[this.winid]);let i=await e.call("line","."),r=await e.call("mode");if(r=="v"||r=="V"){let[o,s]=await this.getSelectedRange();o>s&&([o,s]=[s,o]);for(let l=o;l<=s;l++)this.toggleLine(l);this.setCursor(s),e.command("redraw",!0),await e.resumeNotification();return}e.pauseNotification(),this.toggleLine(i),this.setCursor(t?i-1:i+1),e.command("redraw",!0),await e.resumeNotification()}toggleLine(e){let{selected:t,buffer:i}=this,r=t.has(e),o=lt.signOffset;r?(t.delete(e),i.unplaceSign({id:o+e,group:"coc-list"})):(t.add(e),i.placeSign({lnum:e,id:o+e,name:"CocSelected",group:"coc-list"}))}async selectLines(e,t){let{nvim:i,buffer:r,length:o}=this,s=lt.signOffset;this.clearSelection();let{selected:a}=this;i.pauseNotification(),e>t&&([e,t]=[t,e]);for(let u=e;u<=t&&!(u>o);u++)a.add(u),r.placeSign({lnum:u,id:s+u,name:"CocSelected",group:"coc-list"});this.setCursor(t),i.command("redraw",!0),await i.resumeNotification()}async selectAll(){let{length:e}=this;e>0&&await this.selectLines(1,e)}clearSelection(){let{selected:e,buffer:t}=this;t&&e.size>0&&(t.unplaceSign({group:"coc-list"}),this.selected.clear())}get ready(){return this.window?Promise.resolve():new Promise(e=>{let t=this.onDidLineChange(()=>{t.dispose(),e()})})}getHeight(e,t){let{listOptions:i}=this;if(typeof i.height=="number")return i.height;let r=lt.get("height",10);return t&&!i.interactive&&i.input.length==0&&(r=Math.min(e,r)),Math.max(1,r)}async drawItems(e,t,i=!1){let{nvim:r,name:o,listOptions:s}=this;if(this.items=e.length>this.limitLines?e.slice(0,this.limitLines):e,!this.window){let c=this.getHeight(e.length,t),{position:d,numberSelect:h}=s,[g,f,m]=await r.call("coc#list#create",[d,c,o,h]);this.tabnr=m,this.height=c,this.buffer=r.createBuffer(g);let b=this.window=r.createWindow(f),v=lt.get("statusLineSegments");v&&b.setOption("statusline",v.join(" "),!0),this._onDidOpen.fire(this.bufnr)}let a=[],l=0;this.items.forEach((c,d)=>{a.push(c.label),!i&&l==0&&c.preselect&&(l=d)});let u=i?this.currIndex:l;this.setLines(a,0,u),this._onDidLineChange.fire()}async appendItems(e){if(!this.window||e.length===0)return;let t=this.items.length,i=this.limitLines-t;if(i>0){let r=io.label),r.length,this.currIndex)}}get shouldSort(){let{matcher:e,interactive:t}=this.listOptions;return!(t||e!=="fuzzy")}setLines(e,t,i){let{nvim:r,buffer:o,window:s,reversed:a,newTab:l}=this;if(!(!o||!s)){if(r.pauseNotification(),t||(r.call("coc#compat#clear_matches",[s.id],!0),e.length||(e=["No results, press ? on normal mode to get help."],r.call("coc#compat#matchaddpos",["Comment",[[1]],99,s.id],!0))),o.setOption("modifiable",!0,!0),a){let u=e.reverse();t?r.call("coc#compat#prepend_lines",[o.id,u],!0):o.setLines(u,{start:0,end:-1,strictIndexing:!1},!0)}else o.setLines(e,{start:t?-1:0,end:-1,strictIndexing:!1},!0);if(o.setOption("modifiable",!1,!0),a&&!l){let u=lt.get("height",10);r.call("coc#window#set_height",[s.id,Math.max(Math.min(u,this.length),1)],!0)}if(i>this.items.length-1&&(i=0),i==0)if(t==0)this.doHighlight(0,299);else{let u=this.length-t-1;u<300&&this.doHighlight(u,Math.min(299,this.length-1))}else{let u=l?y.env.lines:this.height;this.doHighlight(Math.max(0,i-u),Math.min(i+u+1,this.length-1))}if(!t){this.currIndex=i;let u=this.indexToLnum(i);s.setCursor([u,0],!0),r.call("coc#list#select",[o.id,u],!0)}a&&r.command("normal! zb",!0),r.command("redraws",!0),r.resumeNotification(!0,!0)}}restoreWindow(){if(this.newTab)return;let{winid:e,height:t}=this;e&&t&&this.nvim.call("coc#window#set_height",[e,t],!0)}get length(){return this.items.length}get selectedItems(){let{selected:e,items:t}=this,i=[];for(let r of e){let o=this.lnumToIndex(r);t[r-1]&&i.push(t[o])}return i}doHighlight(e,t){let{items:i,reversed:r,length:o,buffer:s}=this,a=[],l=u=>{let c=this.indexToLnum(u)-1,{ansiHighlights:d}=i[u];if(d)for(let h of d){let{span:g,hlGroup:f}=h;a.push({hlGroup:f,lnum:c,colStart:g[0],colEnd:g[1]})}};if(r)for(let u=Math.min(t,o-1);u>=e;u--)l(u);else for(let u=e;u<=Math.min(t,o-1);u++)l(u);e=this.indexToLnum(e)-1,t=this.indexToLnum(t)-1,e>t&&([e,t]=[t,e]),!(!s||a.length==0)&&s.updateHighlights("list",a,{start:e,end:t+1,priority:99})}setCursor(e,t=0,i){var s;let{items:r}=this,o=r.length==0?1:r.length;e>o||(i=i??this.lnumToIndex(e),this.onLineChange(i),(s=this.window)==null||s.setCursor([e,t],!0),this.nvim.call("coc#list#select",[this.bufnr,e],!0))}async setIndex(e){if(e<0||e>=this.items.length)return;let{nvim:t}=this,i=this.indexToLnum(e);t.pauseNotification(),this.setCursor(i,0,e),t.command("redraw",!0),await t.resumeNotification(!1)}async moveCursor(e){let{index:t,reversed:i}=this;await this.setIndex(i?t-e:t+e)}async getSelectedRange(){let{nvim:e}=this;await e.call("coc#prompt#stop_prompt",["list"]),await e.eval('feedkeys("\\", "in")');let[,t]=await e.call("getpos","'<"),[,i]=await e.call("getpos","'>");return this.nvim.call("coc#prompt#start_prompt",["list"],!0),[t,i]}cancel(){this.sequence.cancel()}reset(){this.cancel(),this.window&&(this.window=null,this.buffer=null,this.tabnr=void 0)}dispose(){W(this.disposables),this.nvim.call("coc#window#close",[Ie(this.winid,-1)],!0),this.reset(),this.items=[],this._onDidChangeLine.dispose(),this._onDidOpen.dispose(),this._onDidClose.dispose(),this._onDidLineChange.dispose(),this._onDoubleClick.dispose()}}});async function Lx(n,e,t,i){if(n.length===0)return;let r=new QE,o=n.length;function s(l){let u=[];r.start();for(let c=l;c{setImmediate(()=>{l(s(a))})})}var aQ,QE,lQ=D(()=>{"use strict";aQ=15,QE=class{constructor(e=aQ){this.yieldAfter=Math.max(e,aQ),this.startTime=Date.now(),this.counter=0,this.total=0,this.counterInterval=1}start(){this.startTime=Date.now()}shouldYield(){if(++this.counter>=this.counterInterval){let e=Date.now()-this.startTime,t=Math.max(0,this.yieldAfter-e);if(this.total+=this.counter,this.counter=0,e>=this.yieldAfter||t<=1)return this.counterInterval=1,this.total=0,!0;switch(e){case 0:case 1:this.counterInterval=this.total*2;break}}return!1}}});function Fx(n){return n.filterText!=null?eU(n.filterText,n.label):n.label}function uQ(n,e){return e?lfe(n):[n]}function Jf(n){let{label:e,converted:t}=n;if(t)return n;if(e.includes(` +`)&&(e=n.label=e.replace(/\r?\n.*/gm,"")),e.includes(sfe)){let{line:i,highlights:r}=bc(e);n.label=i,Array.isArray(n.ansiHighlights)||(n.ansiHighlights=r)}return n.converted=!0,n}function afe(n,e,t,i){return t?pZ(e,n):i?n.toLowerCase().indexOf(e.toLowerCase()):n.indexOf(e)}function lfe(n){let e=[],t=0,i=0,r="";for(;io.replace(/\\\s/g," ").trim()).filter(o=>o.length>0)}var ofe,sfe,cQ,Ma,$f,dQ=D(()=>{"use strict";xe();te();yc();Re();lQ();MP();Ex();ls();U();fe();he();Fa();ofe=Z("list-worker"),sfe="\x1B",cQ=[32,9],Ma="CocListSearch",$f=class{constructor(e,t,i){this.list=e;this.prompt=t;this.listOptions=i;this._loading=!1;this._finished=!1;this.mutex=new ji;this.totalItems=[];this._onDidChangeItems=new p.Emitter;this._onDidChangeLoading=new p.Emitter;this.onDidChangeItems=this._onDidChangeItems.event;this.onDidChangeLoading=this._onDidChangeLoading.event;this.fuzzyMatch=y.createFuzzyMatch()}set loading(e){this._loading!=e&&(this._loading=e,this._onDidChangeLoading.fire(e))}get isLoading(){return this._loading}async loadItems(e,t=!1){this.cancelFilter(),this.filteredCount=0,this._finished=!1;let{list:i,listOptions:r}=this;this.loading=!0;let{interactive:o}=r;this.tokenSource=new p.CancellationTokenSource;let s=this.tokenSource.token,a=await i.loadItems(e,s);if(!s.isCancellationRequested)if(a=a??[],Array.isArray(a)){this.tokenSource=null,this.totalItems=a,this.loading=!1,this._finished=!0;let l;o?(l=this.convertToHighlightItems(a),this._onDidChangeItems.fire({sorted:!0,items:l,reload:t,finished:!0})):(this.filterTokenSource=new p.CancellationTokenSource,await this.mutex.use(async()=>{await this.filterItems(a,{reload:t},s)}))}else{let l=a,u=this.totalItems=[],c=0,d=e.input;this.filterTokenSource=new p.CancellationTokenSource;let h=async b=>{await this.mutex.use(async()=>{if(this.input!=d&&(d=this.input,c=Ie(this.filteredCount,0)),c>=u.length)return;let x=c>0,C=u.slice(c);if(c=u.length,o){let k=this.convertToHighlightItems(C);this._onDidChangeItems.fire({items:k,append:x,reload:t,sorted:!0,finished:b})}else{let k=this.filterTokenSource;await this.filterItems(C,{append:x,reload:t},k.token)}})},g=setInterval(async()=>{await h()},50);l.on("data",b=>{u.push(b)});let f=async()=>{if(l!=null&&(clearInterval(g),this.tokenSource=null,l=null,this.loading=!1,this._finished=!0,m.dispose(),!s.isCancellationRequested)){if(u.length==0){this._onDidChangeItems.fire({items:[],append:!1,sorted:!0,reload:t,finished:!0});return}await h(!0)}},m=s.onCancellationRequested(()=>{this.mutex.reset(),l==null||l.dispose(),f()});l.on("error",async b=>{l!=null&&(l=null,this.tokenSource=null,this.loading=!1,m.dispose(),clearInterval(g),y.nvim.call("coc#prompt#stop_prompt",["list"],!0),y.nvim.echoError(`Task error: ${b.toString()}`),ofe.error("Task error:",b))}),l.on("end",f)}}async drawItems(){let{totalItems:e}=this;if(e.length===0)return;this.cancelFilter();let t=this.filterTokenSource=new p.CancellationTokenSource,i=t.token;await this.mutex.use(async()=>{if(i.isCancellationRequested)return;let{totalItems:r}=this;this.filteredCount=r.length,await this.filterItems(r,{},t.token)})}cancelFilter(){this.filterTokenSource&&(this.filterTokenSource.cancel(),this.filterTokenSource=null)}stop(){this.cancelFilter(),this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null),this.loading=!1}get length(){return this.totalItems.length}get input(){return this.prompt.input}convertToHighlightItems(e){let t=oe(this.input);t.length>0&&this.fuzzyMatch.setPattern(t);let i=e.map(r=>{if(Jf(r),t.length>0&&r.filterText!==""){let s=Fx(r),a=this.fuzzyMatch.matchHighlights(s,Ma);r.ansiHighlights=Array.isArray(r.ansiHighlights)?r.ansiHighlights.filter(l=>l.hlGroup!==Ma):[],a&&r.ansiHighlights.push(...a.highlights)}return r});return this.fuzzyMatch.free(),i}async filterItemsByInclude(e,t,i,r){let{ignorecase:o}=this.listOptions,s=lt.smartcase,a=uQ(e,lt.extendedSearchMode);o&&(a=a.map(l=>l.toLowerCase())),await Lx(t,l=>{Jf(l);let u=[],c=Fx(l),d=zs(c),h=0;l.ansiHighlights=le(l.ansiHighlights).filter(g=>g.hlGroup!==Ma);for(let g of a){let f=c.slice(h),m=afe(f,g,s,o);if(m===-1)break;let b=m+h+g.length;u.push([d(m+h),d(b)]),h=b}return u.length!==a.length?!1:(l.ansiHighlights.push(...u.map(g=>({span:g,hlGroup:Ma}))),!0)},r,i)}async filterItemsByRegex(e,t,i,r){let{ignorecase:o}=this.listOptions,s=o?"iu":"u",a=uQ(e,lt.extendedSearchMode),l=a.reduce((u,c)=>{try{u.push(new RegExp(c,s))}catch{}return u},[]);await Lx(t,u=>{Jf(u),u.ansiHighlights=le(u.ansiHighlights).filter(f=>f.hlGroup!==Ma);let c=[],d=Fx(u),h=zs(d),g=0;for(let f of l){let m=d.slice(g).match(f);if(m==null)break;let b=m.index+g+m[0].length;c.push([h(m.index+g),h(b)]),g=b}return c.length!==a.length?!1:(u.ansiHighlights.push(...c.map(f=>({span:f,hlGroup:Ma}))),!0)},r,i)}async filterItemsByFuzzyMatch(e,t,i,r){let{extendedSearchMode:o,smartcase:s}=lt,{sort:a}=this.listOptions,l=0;this.fuzzyMatch.setPattern(e,!o);let u=md(e);o&&(u=u.filter(c=>!cQ.includes(c))),await Lx(t,c=>{Jf(c);let d=Fx(c),h=this.fuzzyMatch.matchHighlights(d,Ma);if(!h||s&&!bd(u,d))return!1;let g=Array.isArray(c.ansiHighlights)?c.ansiHighlights.filter(f=>f.hlGroup!=Ma):[];return g.push(...h.highlights),{sortText:typeof c.sortText=="string"?c.sortText:String.fromCharCode(l),score:h.score,ansiHighlights:g}},(c,d)=>{r(c,d,a)},i)}async filterItems(e,t,i){let{input:r}=this;if(r.length===0){let l=e.map(u=>Jf(u));this._onDidChangeItems.fire({items:l,sorted:!0,finished:this._finished,...t});return}let o=!1,s=[],a=(l,u,c)=>{let d=u&&this._finished;if(!(i.isCancellationRequested||!d&&l.length==0))if(c)s.push(...l),u&&this._onDidChangeItems.fire({items:s,append:!1,sorted:!1,reload:t.reload,finished:d});else{let h=t.append===!0||o;o=!0,this._onDidChangeItems.fire({items:l,append:h,sorted:!0,reload:t.reload,finished:d})}};switch(this.listOptions.matcher){case"strict":await this.filterItemsByInclude(r,e,i,a);break;case"regex":await this.filterItemsByRegex(r,e,i,a);break;default:await this.filterItemsByFuzzyMatch(r,e,i,a)}}dispose(){this.stop()}}});var ufe,cfe,Uf,hQ=D(()=>{"use strict";ha();te();de();U();We();he();Fa();zE();KE();sQ();dQ();ufe=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],cfe=pe(50,1),Uf=class{constructor(e,t,i,r,o){this.nvim=e;this.prompt=t;this.list=i;this.listOptions=r;this.listArgs=o;this.loadingFrame="";this.hidden=!1;this.disposables=[];this.args=[];this.ui=new Zf(e,i.name,r),this.history=new iu(t,i.name,GE,y.cwd),this.worker=new $f(i,t,r);let s=ft(async()=>{let[d,h,g]=await e.eval('[coc#list#has_preview(),win_getid(),line(".")]');if(d&&h==this.winid){let f=this.ui.lnumToIndex(g);await this.doPreview(f)}},cfe);this.disposables.push({dispose:()=>{s.clear()}}),this.ui.onDidChangeLine(s,null,this.disposables),this.ui.onDidChangeLine(this.resolveItem,this,this.disposables),this.ui.onDidLineChange(this.resolveItem,this,this.disposables);let a=ft(async()=>{this.updateStatus();let{autoPreview:d}=this.listOptions;if(!d){let[h,g]=await e.eval("[coc#list#has_preview(),mode()]");if(g!="n"||!h)return}await this.doAction("preview")},50);this.disposables.push({dispose:()=>{a.clear()}}),this.ui.onDidLineChange(a,null,this.disposables),this.ui.onDidOpen(async()=>{typeof this.list.doHighlight=="function"&&this.list.doHighlight(),this.listOptions.first&&await this.doAction()},null,this.disposables),this.ui.onDidClose(this.hide,this,this.disposables),this.ui.onDidDoubleClick(this.doAction,this,this.disposables),this.worker.onDidChangeItems(d=>{this.hidden||this.ui.onDidChangeItems(d)},null,this.disposables);let l=0,u,c;this.disposables.push(p.Disposable.create(()=>{clearTimeout(u),clearInterval(c)})),this.worker.onDidChangeLoading(d=>{this.hidden||(u&&clearTimeout(u),d?(l=Date.now(),c&&clearInterval(c),c=setInterval(()=>{let h=Math.floor((Date.now()-l)%1e3/100);this.loadingFrame=ufe[h],this.updateStatus()},100)):u=setTimeout(()=>{this.loadingFrame="",c&&clearInterval(c),c=null,this.updateStatus()},Math.max(0,200-(Date.now()-l))))},null,this.disposables)}async start(e){this.args=e,this.cwd=y.cwd,this.hidden=!1;let{listArgs:t}=this,i=await this.nvim.eval('[win_getid(),bufnr("%"),winheight("%")]');this.listArgs=t,this.history.filter(),this.targetWinid=i[0],this.targetBufnr=i[1],this.savedHeight=i[2],await this.worker.loadItems(this.context)}async reloadItems(){!this.ui.winid||await this.worker.loadItems(this.context,!0)}async call(e){await this.nvim.call("coc#prompt#stop_prompt",["list"]);let t=await this.ui.getItems(),i={name:this.name,args:this.listArgs,input:this.prompt.input,winid:this.targetWinid,bufnr:this.targetBufnr,targets:t},r=await this.nvim.call(e,[i]);return this.prompt.start(),r}async chooseAction(){let{nvim:e,defaultAction:t}=this,{actions:i}=this.list,r=i.map(d=>d.name),o=r.indexOf(t.name);o!=-1&&(r.splice(o,1),r.unshift(t.name));let s=new Set,a=[],l=[],u=y.env.dialog&<.get("menuAction",!1);for(let d of r){let h=0;for(let g of d){if(!s.has(g)){s.add(g),a.push(`${d.slice(0,h)}&${d.slice(h)}`);break}h++}h==d.length&&l.push(d)}l.length&&!u&&(r=r.filter(d=>!l.includes(d)));let c;u?(e.call("coc#prompt#stop_prompt",["list"],!0),c=await P.showMenuPicker(r,{title:"Choose action",shortcuts:!0}),c=c+1,this.prompt.start()):(await e.call("coc#prompt#stop_prompt",["list"]),c=await e.call("confirm",["Choose action:",a.join(` +`)]),await Zi(10),this.prompt.start()),c&&await this.doAction(r[c-1])}async doAction(e){let{list:t}=this,i;if(e!=null){if(i=t.actions.find(o=>o.name==e),!i){P.showErrorMessage(`Action ${e} not found`);return}}else i=this.defaultAction;let r;if(e=="preview"){let o=await this.ui.item;r=o?[o]:[]}else r=await this.ui.getItems();r.length&&await this.doItemAction(r,i)}async doPreview(e){let t=this.ui.getItem(e),i=this.list.actions.find(r=>r.name=="preview");!t||!i||await this.doItemAction([t],i)}async first(){await this.doDefaultAction(0)}async last(){await this.doDefaultAction(this.ui.length-1)}async previous(){await this.doDefaultAction(this.ui.index-1)}async next(){await this.doDefaultAction(this.ui.index+1)}async doDefaultAction(e){let{ui:t}=this,i=t.getItem(e);!i||(await this.ui.setIndex(e),await this.doItemAction([i],this.defaultAction),await t.echoMessage(i))}get name(){return this.list.name}get winid(){return this.ui.winid}get length(){return this.ui.length}get defaultAction(){let{defaultAction:e,actions:t,name:i}=this.list,r=y.getConfiguration(`list.source.${i}`),o;if(r.defaultAction&&(o=t.find(s=>s.name==r.defaultAction)),o||(o=t.find(s=>s.name==e)),o||(o=t[0]),!o)throw new Error(`default action "${e}" not found`);return o}async hide(e=!1,t=y.isVim){if(this.hidden)return;let{nvim:i,timer:r,targetWinid:o,context:s}=this,{winid:a}=this.ui;if(r&&clearTimeout(r),this.worker.stop(),this.history.add(),this.ui.reset(),GE.save(),this.hidden=!0,i.pauseNotification(),i.call("coc#prompt#stop_prompt",["list"],!0),a&&i.call("coc#list#close",[a,s.options.position,o,this.savedHeight],!0),e)return i.resumeNotification(!0,!0);await i.resumeNotification(!1),t&&(await Zi(10),i.call("coc#prompt#stop_prompt",["list"],!0),i.redrawVim())}toggleMode(){let e=this.prompt.mode=="normal"?"insert":"normal";this.prompt.mode=e,this.listOptions.mode=e,this.updateStatus()}stop(){this.worker.stop()}async resolveItem(){let e=this.ui.index,t=this.ui.getItem(e);if(!t||t.resolved)return;let{list:i}=this;if(typeof i.resolveItem=="function"){let r=t.label,o=await Promise.resolve(i.resolveItem(t));if(o&&e==this.ui.index){if(Object.assign(t,o,{resolved:!0}),r==o.label)return;this.ui.updateItem(t,e)}}}async showHelp(){await this.hide();let{list:e,nvim:t}=this;t.pauseNotification(),t.command("tabe +setl\\ previewwindow [LIST HELP]",!0),t.command("setl nobuflisted noswapfile buftype=nofile bufhidden=wipe",!0),await t.resumeNotification();let i=e.options&&e.options.length,r=await t.buffer,o=new zi;if(o.addLine("NAME","Label"),o.addLine(` ${e.name} - ${e.description||""} +`),o.addLine("SYNOPSIS","Label"),o.addLine(` :CocList [LIST OPTIONS] ${e.name}${i?" [ARGUMENTS]":""} +`),e.detail){o.addLine("DESCRIPTION","Label");let a=e.detail.split(` +`).map(l=>" "+l);o.addLine(a.join(` +`)+` +`)}if(i){o.addLine("ARGUMENTS","Label"),o.addLine("");for(let a of e.options)o.addLine(a.name,"Special"),o.addLine(` ${a.description}`),o.addLine("");o.addLine("")}let s=y.getConfiguration(`list.source.${e.name}`);if(Object.keys(s).length){o.addLine("CONFIGURATIONS","Label"),o.addLine("");for(let a of Object.keys(s)){let l=s[a],u=`list.source.${e.name}.${a}`,c=Ie(y.configurations.getDescription(u),a);o.addLine(` "${u}"`,"MoreMsg"),o.addText(` - ${c} current value: `),o.addText(JSON.stringify(l),"Special")}o.addLine("")}o.addLine("ACTIONS","Label"),o.addLine(` ${e.actions.map(a=>a.name).join(", ")}`),o.addLine(""),o.addLine("see ':h coc-list-options' for available list options.","Comment"),t.pauseNotification(),o.render(r,0,-1),t.command("setl nomod",!0),t.command("setl nomodifiable",!0),t.command("normal! gg",!0),t.command("nnoremap q :bd!",!0),await t.resumeNotification()}async switchMatcher(){let{matcher:e,interactive:t}=this.listOptions;if(t)return;let i=["fuzzy","strict","regex"],r=i.indexOf(e)+1;r>=i.length&&(r=0),this.listOptions.matcher=i[r],this.prompt.matcher=i[r],await this.worker.drawItems()}updateStatus(){let{ui:e,list:t,nvim:i}=this;if(!e.bufnr)return;let r=i.createBuffer(e.bufnr),o={mode:this.prompt.mode.toUpperCase(),args:this.args.join(" "),name:t.name,cwd:this.cwd,loading:this.loadingFrame,total:this.worker.length};r.setVar("list_status",o,!0),i.command("redraws",!0)}get context(){let{winid:e}=this.ui;return{options:this.listOptions,args:this.listArgs,input:this.prompt.input,cwd:y.cwd,window:this.window,buffer:this.buffer,listWindow:e?this.nvim.createWindow(e):void 0}}get window(){return this.targetWinid?this.nvim.createWindow(this.targetWinid):void 0}get buffer(){return this.targetBufnr?this.nvim.createBuffer(this.targetBufnr):void 0}onMouseEvent(e){switch(e){case"":return this.ui.onMouse("mouseDown");case"":return this.ui.onMouse("mouseDrag");case"":return this.ui.onMouse("mouseUp");case"<2-LeftMouse>":return this.ui.onMouse("doubleClick")}}async doNumberSelect(e){if(!this.listOptions.numberSelect)return!1;let t=e.charCodeAt(0);if(t>=48&&t<=57){let i=Number(e);if(i==0&&(i=10),this.ui.length>=i)return this.nvim.pauseNotification(),this.ui.setCursor(i),await this.nvim.resumeNotification(),await this.doAction(),!0}return!1}jumpBack(){let{targetWinid:e,nvim:t}=this;e&&(t.pauseNotification(),t.call("coc#prompt#stop_prompt",["list"],!0),this.nvim.call("win_gotoid",[e],!0),t.resumeNotification(!1,!0))}async resume(){this.winid&&await this.hide();let e=await this.nvim.eval('[win_getid(),bufnr("%"),winheight("%")]');this.hidden=!1,this.targetWinid=e[0],this.targetBufnr=e[1],this.savedHeight=e[2],this.prompt.start(),await this.ui.resume(),this.listOptions.autoPreview&&await this.doAction("preview")}async doItemAction(e,t){let{noQuit:i,position:r}=this.listOptions,{nvim:o}=this,s=t.persist===!0||t.name=="preview";r==="tab"&&t.tabPersist&&(s=!0);let a=this.winid&&(s||i);if(a?s||(o.pauseNotification(),o.call("coc#prompt#stop_prompt",["list"],!0),o.call("win_gotoid",[this.context.window.id],!0),await o.resumeNotification()):await this.hide(),t.multiple)await Promise.resolve(t.execute(e,this.context));else if(t.parallel)await Promise.all(e.map(l=>Promise.resolve(t.execute(l,this.context))));else for(let l of e)await Promise.resolve(t.execute(l,this.context));a&&this.ui.restoreWindow(),t.reload&&a?await this.reloadItems():a&&this.nvim.command("redraw",!0)}onInputChange(){this.timer&&clearTimeout(this.timer),this.ui.cancel(),this.history.filter(),this.listOptions.input=this.prompt.input,this.listOptions.interactive?(this.worker.stop(),this.timer=setTimeout(async()=>{await this.worker.loadItems(this.context)},lt.debounceTime)):this.worker.drawItems()}dispose(){this.hide(!0),W(this.disposables),this.worker.dispose(),this.ui.dispose()}}});function Xf(n,e){return n.length>e?n.slice(0,e-1)+".":n+" ".repeat(e-n.length)}function Mx(n,e){if(!n.startsWith("file:"))return n;let t=O.parse(n).fsPath;return dt(e,t)?R.relative(e,t):t}function Pr(n,e){if(e.length===0)return[];let t=[];if(n){let i=Array(Math.min(...e.map(r=>r.label.length))).fill(0);for(let r of e)for(let o=0;o({...r,label:r.label.map((o,s)=>o.padEnd(i[s])).join(" ")}))}else t=e.map(i=>({...i,label:i.label.join(" ")}));return t}function gQ(n,e){if(n==="hidden")return"";if(n==="full")return e;if(n==="short"){let t=e.split(R.sep);return t.length<2?e:[...t.slice(0,t.length-2).filter(r=>r.length>0).map(r=>r[0]),t[t.length-1]].join(R.sep)}else{let t=e.split(R.sep);return oe(t[t.length-1])}}var jo=D(()=>{"use strict";de();Je();st();fe()});function hfe(n,e){let t=n.indexOf(e);return t==-1?-1:n.length-t}var dfe,Gf,pQ=D(()=>{"use strict";Dt();rs();wo();he();Mo();jo();fe();dfe=li.as(ns.ExtensionContribution),Gf=class extends hi{constructor(){super();this.defaultAction="run";this.description="registered commands of coc.nvim";this.name="commands";this.mru=y.createMru("commands"),this.addAction("run",async t=>{await V.fireCommand(t.data.cmd)}),this.addAction("append",async t=>{let{cmd:i}=t.data;await y.nvim.feedKeys(`:CocCommand ${i} `,"n",!1)})}async loadItems(t){let i=[],r=await this.mru.load(),o=new Set;for(let s of dfe.onCommands.concat(V.commandList)){let{id:a,title:l}=s;o.has(a)||(o.add(a),i.push({label:[a,oe(l)],filterText:a,data:{cmd:a,score:hfe(r,a)}}))}return i.sort((s,a)=>a.data.score-s.data.score),Pr(this.alignColumns,i)}doHighlight(){let{nvim:t}=this;t.pauseNotification(),t.command("syntax match CocCommandsTitle /\\t.*$/ contained containedin=CocCommandsLine",!0),t.command("highlight default link CocCommandsTitle Comment",!0),t.resumeNotification(!1,!0)}}});function gfe(n,e){let t=e.uri??O.file(e.filename).toString(),i="",r=[],o=0;n.length>0&&(i=n+" ",r.push({span:[o,o+ue(n)],hlGroup:"Directory"})),o=ue(i);let s=e.lnum??e.range.start.line+1,a=e.col??ue(e.text.slice(0,e.range.start.character))+1,l=`|${e.type?e.type+" ":""}${s} Col ${a}|`;if(i+=l,r.push({span:[o,o+ue(l)],hlGroup:"LineNr"}),e.type){let d=e.type.toLowerCase()==="error"?"Error":"WarningMsg";r.push({span:[o+1,o+ue(e.type)],hlGroup:d})}if(e.range&&e.range.start.line==e.range.end.line){let d=ue(i)+1,h=d+ue(e.text.slice(0,e.range.start.character)),g=d+ue(e.text.slice(0,e.range.end.character));r.push({span:[h,g],hlGroup:"Search"})}i+=" "+e.text;let u=`${n}${e.text.trim()}`,c;if(e.range)c=Ke.create(t,e.range);else{let d=Q.create(e.lnum-1,e.col-1),h=Q.create((e.end_lnum??e.lnum)-1,(e.end_col??e.col)-1);c=Ke.create(t,M.create(d,h))}return c.targetRange=e.targetRange?e.targetRange:M.create(s-1,0,s-1,99),{label:i,location:c,filterText:u,ansiHighlights:r}}var oo,zf=D(()=>{"use strict";ae();Je();Dt();Re();st();de();fe();Mo();oo=class extends hi{constructor(){super();this.defaultAction="open";this.description="show locations saved by g:coc_jump_locations variable";this.name="location";this.createAction({name:"refactor",multiple:!0,execute:async t=>{let i=t.map(r=>r.location);await V.executeCommand("editor.action.showRefactor",i)}}),this.addLocationActions()}async loadItems(t,i){let r=await this.nvim.getVar("coc_jump_locations");r=le(r);let o=t.buffer.id,s=r.every(l=>l.bufnr==o);return r.map(l=>{let u=s?"":l.filename;return u.length>0&&R.isAbsolute(u)&&(u=dt(t.cwd,u)?R.relative(t.cwd,u):u),gfe(u,l)})}}});function pfe(n,e,t,i="full"){let r=dt(e,n.file)?R.relative(e,n.file):n.file,o=gQ(i,r),s=i!=="hidden"?[`${o}:${n.lnum}`]:[],a=t?`[${n.source} ${Ie(n.code,"")}]`:n.source;return[...s,a,n.severity,n.message]}var Kf,fQ=D(()=>{"use strict";Hc();te();st();de();jo();zf();Kf=class extends oo{constructor(t){super();this.defaultAction="open";this.description="diagnostics of current workspace";this.name="diagnostics";ui.onDidRefresh(async()=>{let i=t.getSession("diagnostics");i&&await i.reloadItems()},null,this.disposables)}async loadItems(t){let i=await ui.getDiagnosticList(),{cwd:r}=t,o=this.getConfig(),s=o.get("includeCode",!0),a=o.get("pathFormat","full"),l=i.map(u=>({label:pfe(u,r,s,a),location:u.location}));return Pr(this.alignColumns,l)}doHighlight(){let{nvim:t}=this;t.pauseNotification(),t.command("syntax match CocDiagnosticsFile /\\v^\\s*\\S+/ contained containedin=CocDiagnosticsLine",!0),t.command("syntax match CocDiagnosticsError /\\tError\\s*\\t/ contained containedin=CocDiagnosticsLine",!0),t.command("syntax match CocDiagnosticsWarning /\\tWarning\\s*\\t/ contained containedin=CocDiagnosticsLine",!0),t.command("syntax match CocDiagnosticsInfo /\\tInformation\\s*\\t/ contained containedin=CocDiagnosticsLine",!0),t.command("syntax match CocDiagnosticsHint /\\tHint\\s*\\t/ contained containedin=CocDiagnosticsLine",!0),t.command("highlight default link CocDiagnosticsFile Comment",!0),t.command("highlight default link CocDiagnosticsError CocErrorSign",!0),t.command("highlight default link CocDiagnosticsWarning CocWarningSign",!0),t.command("highlight default link CocDiagnosticsInfo CocInfoSign",!0),t.command("highlight default link CocDiagnosticsHint CocHintSign",!0),t.resumeNotification(!1,!0)}}});function mfe(n,e){return n.data.priority!=e.data.priority?e.data.priority-n.data.priority:e.data.id>n.data.id?1:-1}function bfe(n){let e="+";return n=="disabled"?e="-":n=="activated"?e="*":n=="unknown"&&(e="?"),e}function yfe(n){switch(n){case"unknown":return 2;case"activated":return 1;case"disabled":return-1;default:return 0}}var ffe,Qf,mQ=D(()=>{"use strict";Je();nu();te();de();he();Mo();jo();ffe=pe(50,0),Qf=class extends hi{constructor(t){super();this.manager=t;this.defaultAction="toggle";this.description="manage coc extensions";this.name="extensions";this.addAction("toggle",async i=>{let{id:r,state:o}=i.data;o!="disabled"&&(o=="activated"?await this.manager.deactivate(r):await this.manager.activate(r),await Zi(ffe))},{persist:!0,reload:!0,parallel:!0}),this.addAction("configuration",async i=>{let{root:r}=i.data,o=R.join(r,"package.json");if(F.existsSync(o)){let a=F.readFileSync(o,"utf8").split(/\r?\n/).findIndex(l=>l.includes('"contributes"'));await y.jumpTo(O.file(o),{line:a==-1?0:a,character:0})}}),this.addAction("open",async i=>{let{root:r}=i.data;y.nvim.call("coc#ui#open_url",[r],!0)}),this.addAction("disable",async i=>{let{id:r,state:o}=i.data;o!=="disabled"&&await this.manager.toggleExtension(r)},{persist:!0,reload:!0,parallel:!0}),this.addAction("enable",async i=>{let{id:r,state:o}=i.data;o=="disabled"&&await this.manager.toggleExtension(r)},{persist:!0,reload:!0,parallel:!0}),this.addAction("lock",async i=>{let{id:r}=i.data;this.manager.states.setLocked(r,!0)},{persist:!0,reload:!0}),this.addAction("help",async i=>{let{root:r}=i.data,s=F.readdirSync(r,{encoding:"utf8"}).find(a=>/^readme/i.test(a));s&&await y.jumpTo(O.file(s))}),this.addAction("reload",async i=>{let{id:r}=i.data;await this.manager.reloadExtension(r)},{persist:!0,reload:!0}),this.addMultipleAction("uninstall",async i=>{let r=[];for(let o of i)o.data.isLocal||r.push(o.data.id);await this.manager.uninstallExtensions(r)})}async loadItems(){let t=[],i=await Ht.getExtensionStates();for(let r of i){let o=bfe(r.state),s=F.realpathSync(r.root),a=r.isLocked;t.push({label:[`${o} ${r.id}${a?" \uE0A2":""}`,...r.isLocal?["[RTP]"]:[],r.version,s.replace(Pt.homedir(),"~")],filterText:r.id,data:{id:r.id,root:s,state:r.state,isLocal:r.isLocal,priority:yfe(r.state)}})}return t.sort(mfe),Pr(this.alignColumns,t)}doHighlight(){let{nvim:t}=this;t.pauseNotification(),t.command("syntax match CocExtensionsActivited /\\v^\\*/ contained containedin=CocExtensionsLine",!0),t.command("syntax match CocExtensionsLoaded /\\v^\\+/ contained containedin=CocExtensionsLine",!0),t.command("syntax match CocExtensionsDisabled /\\v^-/ contained containedin=CocExtensionsLine",!0),t.command("syntax match CocExtensionsName /\\v%3c\\S+/ contained containedin=CocExtensionsLine",!0),t.command("syntax match CocExtensionsRoot /\\v\\t[^\\t]*$/ contained containedin=CocExtensionsLine",!0),t.command("syntax match CocExtensionsLocal /\\v\\[RTP\\]/ contained containedin=CocExtensionsLine",!0),t.command("highlight default link CocExtensionsActivited Special",!0),t.command("highlight default link CocExtensionsLoaded Normal",!0),t.command("highlight default link CocExtensionsDisabled Comment",!0),t.command("highlight default link CocExtensionsName String",!0),t.command("highlight default link CocExtensionsLocal MoreMsg",!0),t.command("highlight default link CocExtensionsRoot Comment",!0),t.resumeNotification(!1,!0)}}});var Vf,bQ=D(()=>{"use strict";Je();st();We();he();Mo();Vf=class extends hi{constructor(){super();this.defaultAction="edit";this.description="list of current workspace folders";this.name="folders";this.addAction("edit",async t=>{let i=await this.nvim.call("input",["Folder: ",t.label,"dir"]);if(!hc(i)){P.showWarningMessage(`invalid path: ${i}`);return}y.workspaceFolderControl.renameWorkspaceFolder(t.label,i)}),this.addAction("delete",async t=>{y.workspaceFolderControl.removeWorkspaceFolder(t.label)},{reload:!0,persist:!0}),this.addAction("newfile",async(t,i)=>{let r=await P.requestInput("File name",t.label+"/");!r||(await y.createFile(r,{overwrite:!1,ignoreIfExists:!0}),await this.jumpTo(O.file(r).toString(),null,i))})}async loadItems(){return y.folderPaths.map(t=>({label:t}))}}});var em,yQ=D(()=>{"use strict";ae();Se();he();Mo();jo();em=class extends hi{constructor(){super();this.defaultAction="open";this.description="links of current buffer";this.name="links";this.addAction("open",async t=>{let{target:i}=t.data;await y.openResource(i)}),this.addAction("jump",async t=>{let{location:i}=t.data;await y.jumpTo(i.uri,i.range.start)})}async loadItems(t,i){let r=await t.window.buffer,o=y.getAttachedDocument(r.id),s=[],a=await I.getDocumentLinks(o.textDocument,i);if(a==null)throw new Error("Links provider not found.");let l=[];for(let u of a)u=u.target?u:await I.resolveDocumentLink(u,i),u.target&&s.push({label:Mx(u.target,y.cwd),data:{target:u.target,location:Ke.create(o.uri,u.range)}}),l.push(u);return s}}});function vfe(n,e){let t=n.indexOf(e);return t==-1?-1:n.length-t}var tm,vQ=D(()=>{"use strict";Tg();fe();Mo();jo();tm=class extends hi{constructor(t){super();this.listMap=t;this.name="lists";this.defaultAction="open";this.description="registered lists of coc.nvim";this.mru=new Gr("lists");this.addAction("open",async i=>{let{name:r}=i.data;await this.mru.add(r),setTimeout(()=>{this.nvim.command(`CocList ${r}`,!0)},50)})}async loadItems(t){let i=[],r=await this.mru.load();for(let o of this.listMap.values())o.name!="lists"&&i.push({label:[o.name,oe(o.description)],data:{name:o.name,interactive:o.interactive,score:vfe(r,o.name)}});return i.sort((o,s)=>s.data.score-o.data.score),Pr(this.alignColumns,i)}doHighlight(){let{nvim:t}=this;t.pauseNotification(),t.command("syntax match CocListsDesc /\\t.*$/ contained containedin=CocListsLine",!0),t.command("highlight default link CocListsDesc Comment",!0),t.resumeNotification(!1,!0)}}});function ks(n){switch(n){case De.File:return"File";case De.Module:return"Module";case De.Namespace:return"Namespace";case De.Package:return"Package";case De.Class:return"Class";case De.Method:return"Method";case De.Property:return"Property";case De.Field:return"Field";case De.Constructor:return"Constructor";case De.Enum:return"Enum";case De.Interface:return"Interface";case De.Function:return"Function";case De.Variable:return"Variable";case De.Constant:return"Constant";case De.String:return"String";case De.Number:return"Number";case De.Boolean:return"Boolean";case De.Array:return"Array";case De.Object:return"Object";case De.Key:return"Key";case De.Null:return"Null";case De.EnumMember:return"EnumMember";case De.Struct:return"Struct";case De.Event:return"Event";case De.Operator:return"Operator";case De.TypeParameter:return"TypeParameter";default:return"Unknown"}}var im=D(()=>{"use strict";ae()});function wfe(n,e,t){let i=[],r=(o,s=0)=>{o.sort((a,l)=>Dc(a.selectionRange,l.selectionRange));for(let a of o){let l=ks(a.kind),u=Ke.create(e,a.selectionRange);i.push({label:[`${"| ".repeat(s)}${a.name}`,`[${l}]`,`${a.range.start.line+1}`],filterText:xfe(a,t),location:u,data:{kind:l}}),re(a.children)||r(a.children,s+1)}};return r(n),t&&(i=i.filter(o=>o.data.kind.toLowerCase().indexOf(t)==0)),i}function xfe(n,e){return typeof e=="string"&&e.length>0?n.name:`${n.name}${ks(n.kind)}`}async function Cfe(n,e){if(!go.sync("ctags",{nothrow:!0}))return[];let t=O.parse(n.uri),i=R.extname(t.fsPath),r="",s=`${await e.call("tempname")}.${i}`,a=await e.call("fnameescape",s);await Sg(a,n.getDocumentContent());try{r=await xo(`ctags -f - --excmd=number --language-force=${n.filetype} ${a}`)}catch{}return r.trim().length||(r=await xo(`ctags -f - --excmd=number ${a}`)),r=r.trim(),r?Sfe(r,n):[]}function Sfe(n,e){let t=n.split(/\r?\n/),i=[];for(let r of t){let o=r.split(" ");if(o.length<4)continue;let s=Number(o[2].replace(/;"$/,"")),l=e.getline(s-1).indexOf(o[0]),u=l==-1?0:l,c=M.create(s-1,u,s-1,u+o[0].length);i.push({label:`${o[0]} [${o[3]}] ${s}`,filterText:o[0],location:Ke.create(e.uri,c),data:{line:s}})}return i.sort((r,o)=>r.data.line-o.data.line),i}var nm,wQ=D(()=>{"use strict";ae();Je();Se();Re();im();st();de();Tt();Tl();he();jo();zf();nm=class extends oo{constructor(){super(...arguments);this.description="symbols of current document";this.name="outline";this.options=[{name:"-k, -kind KIND",hasValue:!0,description:"filter symbol by kind"}]}async loadItems(t,i){let r=y.getAttachedDocument(t.buffer.id),s=this.getConfig().get("ctagsFiletypes",[]),a,l=this.parseArguments(t.args),u=l.kind?l.kind.toString().toLowerCase():null;if(s.includes(r.filetype)||(a=await I.getDocumentSymbol(r.textDocument,i)),i.isCancellationRequested)return[];if(!a)return await Cfe(r,this.nvim);if(re(a))return[];let c=wfe(a,r.uri,u);return Pr(this.alignColumns,c)}doHighlight(){let{nvim:t}=this;t.pauseNotification(),t.command("syntax match CocOutlineName /\\v\\s?[^\\t]+\\s/ contained containedin=CocOutlineLine",!0),t.command("syntax match CocOutlineIndentLine /\\v\\|/ contained containedin=CocOutlineLine,CocOutlineName",!0),t.command("syntax match CocOutlineKind /\\[\\w\\+\\]/ contained containedin=CocOutlineLine",!0),t.command("syntax match CocOutlineLine /\\d\\+$/ contained containedin=CocOutlineLine",!0),t.command("highlight default link CocOutlineName Normal",!0),t.command("highlight default link CocOutlineIndentLine Comment",!0),t.command("highlight default link CocOutlineKind Typedef",!0),t.command("highlight default link CocOutlineLine Comment",!0),t.resumeNotification(!1,!0)}}});function He(){return me()}var si=D(()=>{"use strict";rt()});function q(n,e){return n[e]===void 0&&(n[e]={}),n[e]}var ru,so,jx,Ox,ou,Rr,Le,ut=D(()=>{"use strict";U();Xe();he();si();Ii();ru=class extends Rt{constructor(t){super();this.data=t}},so=class{constructor(e){this._client=e}sendRequest(e,t,i,r){return this._client.sendRequest(e,t,i).then(o=>i.isCancellationRequested||o==null?r??null:o,o=>this._client.handleFailedRequest(e,i,o,r??null))}};(e=>{function n(t){return t!=null&&tt(t.fillClientCapabilities)&&tt(t.initialize)&&tt(t.dispose)&&(t.fillInitializeParams===void 0||tt(t.fillInitializeParams))&&t.registrationType===void 0}e.is=n})(jx||(jx={}));(e=>{function n(t){let i=t;return i!=null&&tt(i.fillClientCapabilities)&&tt(i.initialize)&&tt(i.dispose)&&(i.fillInitializeParams===void 0||tt(i.fillInitializeParams))&&tt(i.register)&&tt(i.unregister)&&i.registrationType!==void 0}e.is=n})(Ox||(Ox={}));ou=class extends so{constructor(e){super(e)}getState(){let e=this.getDocumentSelectors(),t=0;for(let r of e){t++;for(let o of y.textDocuments)if(y.match(r,o)>0)return{kind:"document",id:this.registrationType.method,registrations:!0,matches:!0}}let i=t>0;return{kind:"document",id:this.registrationType.method,registrations:i,matches:!1}}},Rr=class extends ou{constructor(t,i,r,o,s,a){super(t);this._event=i,this._type=r,this._middleware=o,this._createParams=s,this._selectorFilter=a,this._selectors=new Map,this._onNotificationSent=new p.Emitter}static textDocumentFilter(t,i){for(let r of t)if(y.match(r,i)>0)return!0;return!1}getDocumentSelectors(){return this._selectors.values()}register(t){!t.registerOptions.documentSelector||(this._listener||(this._listener=this._event(i=>{this.callback(i).catch(r=>{this._client.error(`Sending document notification ${this._type.method} failed.`,r)})})),this._selectors.set(t.id,t.registerOptions.documentSelector))}async callback(t){if(!this.matches(t))return;let i=async o=>{let s=this._createParams(o);await this._client.sendNotification(this._type,s).catch(),this.notificationSent(o,this._type,s)},r=this._client.middleware[this._middleware];return Promise.resolve(r?r(t,o=>i(o)):i(t))}matches(t){return!this._selectorFilter||this._selectorFilter(this._selectors.values(),t)}get onNotificationSent(){return this._onNotificationSent.event}notificationSent(t,i,r){this._onNotificationSent.fire({original:t,type:i,params:r})}unregister(t){this._selectors.delete(t)}dispose(){this._selectors.clear(),this._onNotificationSent.dispose(),this._listener&&(this._listener.dispose(),this._listener=void 0)}getProvider(t){for(let i of this.getDocumentSelectors())if(y.match(i,t)>0)return{send:r=>this.callback(r)}}},Le=class extends ou{constructor(t,i){super(t);this._registrationType=i,this._registrations=new Map}*getDocumentSelectors(){for(let t of this._registrations.values()){let i=t.data.registerOptions.documentSelector;i!==null&&(yield i)}}get registrationType(){return this._registrationType}get registrationLength(){return this._registrations.size}register(t){if(!t.registerOptions.documentSelector)return;let i=this.registerLanguageProvider(t.registerOptions,t.id);this._registrations.set(t.id,{disposable:i[0],data:t,provider:i[1]})}unregister(t){let i=this._registrations.get(t);i!==void 0&&i.disposable.dispose()}dispose(){this._registrations.forEach(t=>{t.disposable.dispose()}),this._registrations.clear()}getRegistration(t,i){if(!i)return[void 0,void 0];if(Pn(i)&&i===!0)return[He(),{documentSelector:t}];if(p.TextDocumentRegistrationOptions.is(i)){let r=p.StaticRegistrationOptions.hasId(i)?i.id:He(),o=i.documentSelector??t;return[r,Object.assign({},{documentSelector:o},i)]}return p.WorkDoneProgressOptions.is(i)?[p.StaticRegistrationOptions.hasId(i)?i.id:He(),Object.assign({},{documentSelector:t},i)]:[void 0,void 0]}getRegistrationOptions(t,i){if(!(!t||!i))return Pn(i)&&i===!0?{documentSelector:t}:Object.assign({},i,{documentSelector:t})}getProvider(t){for(let i of this._registrations.values()){let r=i.data.registerOptions.documentSelector;if(r!==null&&y.match(r,t)>0)return i.provider}}getAllProviders(){let t=[];for(let i of this._registrations.values())t.push(i.provider);return t}}});var ja,VE=D(()=>{"use strict";Je();Ii();ja=class{constructor(e,t){if(typeof e!="string"&&(!e||!O.isUri(e)&&typeof e.uri!="string"))throw oT("base");if(typeof t!="string")throw oT("pattern");typeof e=="string"?this.baseUri=O.file(e):O.isUri(e)?this.baseUri=e:this.baseUri=O.parse(e.uri),this.pattern=t}toJSON(){return{pattern:this.pattern,baseUri:this.baseUri.toJSON()}}}});function Dfe(n){return{uri:n.uri,languageId:n.languageId,version:n.version,text:n.getText()}}function xQ(n){return{textDocument:Dfe(n)}}function CQ(n){let{baseUri:e,pattern:t}=n;return typeof e=="string"?new ja(O.parse(e),t):new ja(e,t)}function SQ(n){return{textDocument:{uri:n.uri}}}function DQ(n){return{textDocument:{uri:n.uri,version:n.version},contentChanges:[{text:n.getText()}]}}function TQ(n){let{textDocument:e,contentChanges:t}=n;return{textDocument:{uri:e.uri,version:e.version},contentChanges:t.slice()}}function e0(n){return{textDocument:Ax(n.document),reason:n.reason}}function Ax(n){return{uri:n.uri,version:n.version}}function kQ(n,e){let t={textDocument:Ax(n)};return e&&(t.text=n.getText()),t}function yd(n){return n.toString()}function PQ(n,e,t){return{textDocument:{uri:n.uri},position:e,context:ci(t,["option"])}}function Bi(n,e){return{textDocument:{uri:n.uri},position:e}}function RQ(n,e,t){return{textDocument:ao(n),position:e,context:t}}function ao(n){return{uri:n.uri}}function _Q(n,e,t){return{textDocument:{uri:n.uri},position:e,context:{includeDeclaration:t.includeDeclaration}}}function EQ(n){return{textDocument:{uri:n.uri}}}function IQ(n){return{textDocument:{uri:n.uri}}}var ii=D(()=>{"use strict";Je();VE();io()});var Nx,LQ=D(()=>{"use strict";Se();U();ut();ii();Nx=class extends Le{constructor(e){super(e,p.CallHierarchyPrepareRequest.type)}fillClientCapabilities(e){let i=q(q(e,"textDocument"),"callHierarchy");i.dynamicRegistration=!0}initialize(e,t){let[i,r]=this.getRegistration(t,e.callHierarchyProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t={prepareCallHierarchy:(i,r,o)=>{let s=this._client,a=(u,c,d)=>{let h=Bi(u,c);return this.sendRequest(p.CallHierarchyPrepareRequest.type,h,d)},l=s.middleware;return l.prepareCallHierarchy?l.prepareCallHierarchy(i,r,o,a):a(i,r,o)},provideCallHierarchyIncomingCalls:(i,r)=>{let o=this._client,s=(l,u)=>this.sendRequest(p.CallHierarchyIncomingCallsRequest.type,{item:l},u),a=o.middleware;return a.provideCallHierarchyIncomingCalls?a.provideCallHierarchyIncomingCalls(i,r,s):s(i,r)},provideCallHierarchyOutgoingCalls:(i,r)=>{let o=this._client,s=(l,u)=>this.sendRequest(p.CallHierarchyOutgoingCallsRequest.type,{item:l},u),a=o.middleware;return a.provideCallHierarchyOutgoingCalls?a.provideCallHierarchyOutgoingCalls(i,r,s):s(i,r)}};return[I.registerCallHierarchyProvider(e.documentSelector,t),t]}}});var Hx,FQ=D(()=>{"use strict";ae();Dt();Se();U();ut();si();Hx=class extends Le{constructor(t){super(t,p.CodeActionRequest.type);this.disposables=[]}fillClientCapabilities(t){let i=q(q(t,"textDocument"),"codeAction");i.dynamicRegistration=!0,i.isPreferredSupport=!0,i.disabledSupport=!0,i.dataSupport=!0,i.honorsChangeAnnotations=!1,i.resolveSupport={properties:["edit"]},i.codeActionLiteralSupport={codeActionKind:{valueSet:[ri.Empty,ri.QuickFix,ri.Refactor,ri.RefactorExtract,ri.RefactorInline,ri.RefactorRewrite,ri.Source,ri.SourceOrganizeImports]}}}initialize(t,i){let r=this.getRegistrationOptions(i,t.codeActionProvider);!r||this.register({id:He(),registerOptions:r})}registerLanguageProvider(t){let i=o=>{let s=this._client,a=(u,c)=>{let d={command:u,arguments:c};return s.sendRequest(p.ExecuteCommandRequest.type,d)},l=s.middleware;this.disposables.push(V.registerCommand(o,(...u)=>l.executeCommand?l.executeCommand(o,u,a):a(o,u),null,!0))},r={provideCodeActions:(o,s,a,l)=>{let u=this._client,c=(h,g,f,m)=>{let b={textDocument:{uri:h.uri},range:g,context:f};return this.sendRequest(p.CodeActionRequest.type,b,m).then(v=>{if(!!v)return v.forEach(x=>{var k;let C=En.is(x)?x.command:(k=x.command)==null?void 0:k.command;C&&!V.has(C)&&i(C)}),v})},d=u.middleware;return d.provideCodeActions?d.provideCodeActions(o,s,a,l,c):c(o,s,a,l)},resolveCodeAction:t.resolveProvider?(o,s)=>{let a=this._client.middleware,l=(u,c)=>this.sendRequest(p.CodeActionResolveRequest.type,u,c,u);return a.resolveCodeAction?a.resolveCodeAction(o,s,l):l(o,s)}:void 0};return[I.registerCodeActionProvider(t.documentSelector,r,this._client.id,t.codeActionKinds),r]}dispose(){this.disposables.forEach(t=>{t.dispose()}),this.disposables=[],super.dispose()}}});var Bx,MQ=D(()=>{"use strict";Se();U();ut();ii();si();Bx=class extends Le{constructor(e){super(e,p.CodeLensRequest.type)}fillClientCapabilities(e){q(q(e,"textDocument"),"codeLens").dynamicRegistration=!0,q(q(e,"workspace"),"codeLens").refreshSupport=!0}initialize(e,t){this._client.onRequest(p.CodeLensRefreshRequest.type,async()=>{for(let o of this.getAllProviders())o.onDidChangeCodeLensEmitter.fire()});let r=this.getRegistrationOptions(t,e.codeLensProvider);!r||this.register({id:He(),registerOptions:r})}registerLanguageProvider(e){let t=new p.Emitter,i={onDidChangeCodeLenses:t.event,provideCodeLenses:(r,o)=>{let s=this._client,a=(u,c)=>this.sendRequest(p.CodeLensRequest.type,IQ(u),c),l=s.middleware;return l.provideCodeLenses?l.provideCodeLenses(r,o,a):a(r,o)},resolveCodeLens:e.resolveProvider?(r,o)=>{let s=this._client,a=(u,c)=>this.sendRequest(p.CodeLensResolveRequest.type,u,c,u),l=s.middleware;return l.resolveCodeLens?l.resolveCodeLens(r,o,a):a(r,o)}:void 0};return[I.registerCodeLensProvider(e.documentSelector,i),{provider:i,onDidChangeCodeLensEmitter:t}]}}});var qx,jQ=D(()=>{"use strict";Se();U();ut();qx=class extends Le{constructor(e){super(e,p.DocumentColorRequest.type)}fillClientCapabilities(e){q(q(e,"textDocument"),"colorProvider").dynamicRegistration=!0}initialize(e,t){let[i,r]=this.getRegistration(t,e.colorProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t={provideColorPresentations:(i,r,o)=>{let s=this._client,a=(u,c,d)=>{let h={color:u,textDocument:{uri:c.document.uri},range:c.range};return this.sendRequest(p.ColorPresentationRequest.type,h,d)},l=s.middleware;return l.provideColorPresentations?l.provideColorPresentations(i,r,o,a):a(i,r,o)},provideDocumentColors:(i,r)=>{let o=this._client,s=(l,u)=>{let c={textDocument:{uri:l.uri}};return this.sendRequest(p.DocumentColorRequest.type,c,u)},a=o.middleware;return a.provideDocumentColors?a.provideDocumentColors(i,r,s):s(i,r)}};return[I.registerDocumentColorProvider(e.documentSelector,t),t]}}});var Tfe,Wx,OQ=D(()=>{"use strict";ae();Se();U();ut();ii();si();Tfe=[ie.Text,ie.Method,ie.Function,ie.Constructor,ie.Field,ie.Variable,ie.Class,ie.Interface,ie.Module,ie.Property,ie.Unit,ie.Value,ie.Enum,ie.Keyword,ie.Snippet,ie.Color,ie.File,ie.Reference,ie.Folder,ie.EnumMember,ie.Constant,ie.Struct,ie.Event,ie.Operator,ie.TypeParameter],Wx=class extends Le{constructor(e){super(e,p.CompletionRequest.type)}fillClientCapabilities(e){let t=this._client.clientOptions.disableSnippetCompletion!==!0,i=q(q(e,"textDocument"),"completion");i.dynamicRegistration=!0,i.contextSupport=!0,i.completionItem={snippetSupport:t,commitCharactersSupport:!0,documentationFormat:this._client.supportedMarkupKind,deprecatedSupport:!0,preselectSupport:!0,insertReplaceSupport:!0,tagSupport:{valueSet:[Ko.Deprecated]},resolveSupport:{properties:["documentation","detail","additionalTextEdits"]},labelDetailsSupport:!0,insertTextModeSupport:{valueSet:[mr.asIs,mr.adjustIndentation]}},i.completionItemKind={valueSet:Tfe},i.insertTextMode=mr.adjustIndentation,i.completionList={itemDefaults:["commitCharacters","editRange","insertTextFormat","insertTextMode"]}}initialize(e,t){let i=this.getRegistrationOptions(t,e.completionProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e,t){let i=e.triggerCharacters||[],r=e.allCommitCharacters||[],o={provideCompletionItems:(l,u,c,d)=>{let h=this._client.middleware,g=(f,m,b,v)=>this.sendRequest(p.CompletionRequest.type,PQ(f,m,b),v,[]);return h.provideCompletionItem?h.provideCompletionItem(l,u,d,c,g):g(l,u,d,c)},resolveCompletionItem:e.resolveProvider?(l,u)=>{let c=this._client.middleware,d=(h,g)=>this.sendRequest(p.CompletionResolveRequest.type,h,g,h);return c.resolveCompletionItem?c.resolveCompletionItem(l,u,d):d(l,u)}:void 0},s=this._client.id+(this.registrationLength==0?"":"-"+t);return[I.registerCompletionItemProvider(s,"LS",e.documentSelector,o,i,e.priority,r),o]}}});var Yx,su,AQ=D(()=>{"use strict";aa();Xe();U();he();ut();si();Yx=class{constructor(e){this._client=e}get method(){return p.ConfigurationRequest.method}fillClientCapabilities(e){q(e,"workspace").configuration=!0}getState(){return{kind:"static"}}initialize(){let e=this._client,{configuredSection:t}=e;e.onRequest(p.ConfigurationRequest.type,(i,r)=>{let o=a=>{let l=[];for(let u of a.items){let c=t?t+(u.section?`.${u.section}`:""):u.section;l.push(this.getConfiguration(u.scopeUri,c))}return l},s=e.middleware.workspace;return s!=null&&s.configuration?s.configuration(i,r,o):o(i,r)})}getConfiguration(e,t){let i=null;if(t){let r=t.lastIndexOf(".");if(r===-1)i=xc(y.getConfiguration(void 0,e).get(t));else{let o=y.getConfiguration(t.substr(0,r),e);i=xc(o.get(t.substr(r+1)))}}else{let r=y.getConfiguration(t,e);i={};for(let o of Object.keys(r))r.has(o)&&(i[o]=xc(r.get(o)))}return i??null}dispose(){}},su=class{constructor(e){this._client=e;this._listeners=new Map}getState(){return{kind:"workspace",id:this.registrationType.method,registrations:this._listeners.size>0}}get registrationType(){return p.DidChangeConfigurationNotification.type}fillClientCapabilities(e){q(q(e,"workspace"),"didChangeConfiguration").dynamicRegistration=!0}initialize(){var t;let e=(t=this._client.clientOptions.synchronize)==null?void 0:t.configurationSection;if(e!==void 0){let i=this.configuredUID=He();this.register({id:i,registerOptions:{section:e}})}}register(e){if(this._client.configuredSection&&e.id!==this.configuredUID)return;let{section:t}=e.registerOptions,i=y.onDidChangeConfiguration(r=>{this.onDidChangeConfiguration(t,r)});this._listeners.set(e.id,i),t!==void 0&&this.onDidChangeConfiguration(t,void 0)}unregister(e){let t=this._listeners.get(e);t&&(this._listeners.delete(e),t.dispose())}dispose(){for(let e of this._listeners.values())e.dispose();this._listeners.clear()}onDidChangeConfiguration(e,t){var l;let{configuredSection:i}=this._client,r;if($e(e)?r=[e]:r=e,r!=null&&t!=null&&!r.map(d=>d.startsWith("languageserver.")?"languageserver":d).some(d=>t.affectsConfiguration(d)))return;let o=u=>{if(u==null)return this._client.sendNotification(p.DidChangeConfigurationNotification.type,{settings:null});let c=this._client.clientOptions.workspaceFolder,d=i?su.getConfiguredSettings(i,c):su.extractSettingsInformation(u,c);return this._client.sendNotification(p.DidChangeConfigurationNotification.type,{settings:d})},s=(l=this._client.middleware.workspace)==null?void 0:l.didChangeConfiguration;(s?Promise.resolve(s(r,o)):o(r)).catch(u=>{this._client.error(`Sending notification ${p.DidChangeConfigurationNotification.type.method} failed`,u)})}static getConfiguredSettings(e,t){let i=9,r=y.getConfiguration(e.slice(0,-i),t);return N$(r.get("settings",{}))}static extractSettingsInformation(e,t){function i(o,s){let a=o;for(let l=0;l=0?l=y.getConfiguration(s.substr(0,a),t).get(s.substr(a+1)):l=y.getConfiguration(s,t);let u=e[o].split(".");i(r,u)[u[u.length-1]]=l}return r}}});var Zx,NQ=D(()=>{"use strict";Se();U();ut();ii();Zx=class extends Le{constructor(e){super(e,p.DeclarationRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"declaration");t.dynamicRegistration=!0,t.linkSupport=!0}initialize(e,t){let[i,r]=this.getRegistration(t,e.declarationProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t={provideDeclaration:(i,r,o)=>{let s=this._client,a=(u,c,d)=>this.sendRequest(p.DeclarationRequest.type,Bi(u,c),d),l=s.middleware;return l.provideDeclaration?l.provideDeclaration(i,r,o,a):a(i,r,o)}};return[I.registerDeclarationProvider(e.documentSelector,t),t]}}});var Jx,HQ=D(()=>{"use strict";Se();U();ut();ii();si();Jx=class extends Le{constructor(e){super(e,p.DefinitionRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"definition");t.dynamicRegistration=!0,t.linkSupport=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.definitionProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e){let t={provideDefinition:(i,r,o)=>{let s=this._client,a=(u,c,d)=>this.sendRequest(p.DefinitionRequest.type,Bi(u,c),d),l=s.middleware;return l.provideDefinition?l.provideDefinition(i,r,o,a):a(i,r,o)}};return[I.registerDefinitionProvider(e.documentSelector,t),t]}}});var BQ,t0,i0,n0,r0,$x,qQ=D(()=>{"use strict";de();rt();Je();Se();Ii();fR();U();We();he();ut();te();BQ=pe(3e3,10),t0=class{constructor(){this.documentPullStates=new Map,this.workspacePullStates=new Map}track(e,t,i){let r=e===1?this.documentPullStates:this.workspacePullStates,[o,s,a]=t instanceof O?[t.toString(),t,i]:[t.uri.toString(),O.parse(t.uri),t.version],l=r.get(o);return l===void 0&&(l={document:s,pulledVersion:a,resultId:void 0},r.set(o,l)),l}update(e,t,i,r){let o=e===1?this.documentPullStates:this.workspacePullStates,[s,a,l,u]=t instanceof O?[t.toString(),t,i,r]:[t.uri,O.parse(t.uri),t.version,i],c=o.get(s);c===void 0?(c={document:a,pulledVersion:l,resultId:u},o.set(s,c)):(c.pulledVersion=l,c.resultId=u)}unTrack(e,t){let i=t instanceof O?t.toString():t.uri;(e===1?this.documentPullStates:this.workspacePullStates).delete(i)}tracks(e,t){let i=t instanceof O?t.toString():t.uri;return(e===1?this.documentPullStates:this.workspacePullStates).has(i)}trackingDocuments(){return Array.from(this.documentPullStates.keys())}getResultId(e,t){var o;let i=t instanceof O?t.toString():t.uri;return(o=(e===1?this.documentPullStates:this.workspacePullStates).get(i))==null?void 0:o.resultId}getAllResultIds(){let e=[];for(let[t,i]of this.workspacePullStates)this.documentPullStates.has(t)&&(i=this.documentPullStates.get(t)),i.resultId!==void 0&&e.push({uri:t,value:i.resultId});return e}},i0=class extends so{constructor(t,i){var r;super(t);this.client=t,this.options=i,this.enableWorkspace=i.workspaceDiagnostics&&((r=this.client.clientOptions.diagnosticPullOptions)==null?void 0:r.workspace)!==!1,this.isDisposed=!1,this.onDidChangeDiagnosticsEmitter=new p.Emitter,this.provider=this.createProvider(),this.diagnostics=I.createDiagnosticCollection(i.identifier?i.identifier:t.id),this.openRequests=new Map,this.documentStates=new t0,this.workspaceErrorCounter=0}knows(t,i){return this.documentStates.tracks(t,i)}trackingDocuments(){return this.documentStates.trackingDocuments()}forget(t,i){this.documentStates.unTrack(t,i)}pull(t,i){this.pullAsync(t).then(()=>{i&&i()},r=>{this.client.error(`Document pull failed for text document ${t.uri}`,r)})}async pullAsync(t){if(this.isDisposed)return;let i=t.uri,r=t.version,o=this.openRequests.get(i),s=this.documentStates.track(1,t);if(o===void 0){let a=new p.CancellationTokenSource;this.openRequests.set(i,{state:"open",document:t,version:r,tokenSource:a});let l,u;try{l=await this.provider.provideDiagnostics(t,s.resultId,a.token)??{kind:p.DocumentDiagnosticReportKind.Full,items:[]}}catch(d){if(d instanceof ru&&d.data&&p.DiagnosticServerCancellationData.is(d.data)&&d.data.retriggerRequest===!1&&(u={state:"drop",document:t}),u===void 0&&d instanceof Rt)u={state:"reschedule",document:t};else throw d}if(u=u??this.openRequests.get(i),u===void 0){this.client.error(`Lost request state in diagnostic pull model. Clearing diagnostics for ${i}`),this.diagnostics.delete(i);return}if(this.openRequests.delete(i),!P.visibleTextEditors.some(d=>d.document.uri===i)){this.documentStates.unTrack(1,t);return}if(u.state==="drop")return;l!==void 0&&(l.kind===p.DocumentDiagnosticReportKind.Full&&this.diagnostics.set(i,l.items),s.pulledVersion=r,s.resultId=l.resultId),u.state==="reschedule"&&this.pull(t)}else o.state==="open"?(o.tokenSource.cancel(),this.openRequests.set(i,{state:"reschedule",document:o.document})):o.state==="drop"&&this.openRequests.set(i,{state:"reschedule",document:o.document})}forgetDocument(t){let i=t.uri,r=this.openRequests.get(i);this.enableWorkspace?r!==void 0?this.openRequests.set(i,{state:"reschedule",document:t}):this.pull(t,()=>{this.forget(1,t)}):(r!==void 0&&(r.state==="open"&&r.tokenSource.cancel(),this.openRequests.delete(i)),this.diagnostics.delete(i.toString()),this.forget(1,t))}pullWorkspace(){!this.enableWorkspace||this.pullWorkspaceAsync().then(()=>{this.workspaceTimeout=(0,p.RAL)().timer.setTimeout(()=>{this.pullWorkspace()},BQ)},t=>{!(t instanceof ru)&&!p.DiagnosticServerCancellationData.is(t.data)&&(this.client.error("Workspace diagnostic pull failed.",t),this.workspaceErrorCounter++),this.workspaceErrorCounter<=5&&(this.workspaceTimeout=(0,p.RAL)().timer.setTimeout(()=>{this.pullWorkspace()},BQ))})}async pullWorkspaceAsync(){if(!this.provider.provideWorkspaceDiagnostics)return;this.workspaceCancellation!==void 0&&(this.workspaceCancellation.cancel(),this.workspaceCancellation=void 0),this.workspaceCancellation=new p.CancellationTokenSource;let t=this.documentStates.getAllResultIds();await this.provider.provideWorkspaceDiagnostics(t,this.workspaceCancellation.token,i=>{if(!(!i||this.isDisposed))for(let r of i.items)r.kind===p.DocumentDiagnosticReportKind.Full&&(this.documentStates.tracks(1,O.parse(r.uri))||this.diagnostics.set(r.uri.toString(),r.items)),this.documentStates.update(2,O.parse(r.uri),r.version??void 0,r.resultId)})}createProvider(){let t={onDidChangeDiagnostics:this.onDidChangeDiagnosticsEmitter.event,provideDiagnostics:(i,r,o)=>{let s=this.client.middleware,a=(l,u,c)=>{let d=l instanceof O?l.toString():l.uri,h={identifier:this.options.identifier,textDocument:{uri:d},previousResultId:u};return this.sendRequest(p.DocumentDiagnosticRequest.type,h,c,{kind:p.DocumentDiagnosticReportKind.Full,items:[]}).then(async g=>g==null||this.isDisposed?{kind:p.DocumentDiagnosticReportKind.Full,items:[]}:(s.handleDiagnostics&&g.kind==p.DocumentDiagnosticReportKind.Full&&s.handleDiagnostics(d,g.items,(f,m)=>{g.items=m}),g))};return s.provideDiagnostics?s.provideDiagnostics(i,r,o,a):a(i,r,o)}};return this.options.workspaceDiagnostics&&(t.provideWorkspaceDiagnostics=(i,r,o)=>{let s=(l,u)=>{let c=me(),d=this.client.onProgress(p.WorkspaceDiagnosticRequest.partialResult,c,g=>{if(g==null){o(null);return}o(g)}),h={identifier:this.options.identifier,previousResultIds:l,partialResultToken:c};return this.sendRequest(p.WorkspaceDiagnosticRequest.type,h,u,{items:[]}).then(async g=>(o(g),{items:[]})).finally(()=>{d.dispose()})},a=this.client.middleware;return a.provideWorkspaceDiagnostics?a.provideWorkspaceDiagnostics(i,r,o,s):s(i,r,o)}),t}dispose(){var t,i;this.isDisposed=!0,(t=this.workspaceCancellation)==null||t.cancel(),(i=this.workspaceTimeout)==null||i.dispose();for(let r of this.openRequests.values())r.state==="open"&&r.tokenSource.cancel();this.openRequests.clear()}},n0=class{constructor(e){this.diagnosticRequestor=e,this.documents=new Dp}add(e){let t=e.uri;this.documents.has(t)||(this.documents.set(t,e,2),this.trigger())}remove(e){var i;let t=e.uri;this.documents.has(t)&&(this.documents.delete(t),this.diagnosticRequestor.pull(e)),this.documents.size===0?this.stop():e.uri===((i=this.endDocument)==null?void 0:i.uri)&&(this.endDocument=this.documents.last)}trigger(){if(this.intervalHandle!==void 0){this.endDocument=this.documents.last;return}this.endDocument=this.documents.last,this.intervalHandle=(0,p.RAL)().timer.setInterval(()=>{let e=this.documents.first;if(e!==void 0){let t=e.uri;this.diagnosticRequestor.pull(e),this.documents.set(t,e,2),e===this.endDocument&&this.stop()}},200)}dispose(){this.stop(),this.documents.clear()}stop(){var e;(e=this.intervalHandle)==null||e.dispose(),this.intervalHandle=void 0,this.endDocument=void 0}},r0=class{constructor(e,t){var h;let i=e.clientOptions.diagnosticPullOptions,r=t.documentSelector,o=[],s=i.ignored??[],a=g=>!(y.match(r,g)<=0||!P.visibleTextEditors.some(m=>m.document.uri===g.uri)||s.length>0&&s.some(m=>ni(O.parse(g.uri).fsPath,m,{dot:!0})));this.diagnosticRequestor=new i0(e,t),this.backgroundScheduler=new n0(this.diagnosticRequestor);let l=g=>{var f;!a(g)||!t.interFileDependencies||((f=this.activeTextDocument)==null?void 0:f.uri)===g.uri||this.backgroundScheduler.add(g)};this.activeTextDocument=(h=P.activeTextEditor)==null?void 0:h.document.textDocument,P.onDidChangeActiveTextEditor(g=>{let f=this.activeTextDocument,m=this.activeTextDocument=g==null?void 0:g.document.textDocument;f!==void 0&&l(f),m!=null&&this.backgroundScheduler.remove(m)},null,o);let u=e.getFeature(p.DidOpenTextDocumentNotification.method);o.push(u.onNotificationSent(g=>{let f=g.original;a(f)&&this.diagnosticRequestor.pull(f,()=>{l(f)})}));let c=(g,f)=>!(i.filter&&i.filter(g,f)||!this.diagnosticRequestor.knows(1,g));if(i.onChange===!0){let g=e.getFeature(p.DidChangeTextDocumentNotification.method);o.push(g.onNotificationSent(async f=>{let m=y.getDocument(f.original.bufnr).textDocument;f.original.contentChanges.length!=0&&c(m,"onType")&&this.diagnosticRequestor.pull(m,()=>{this.backgroundScheduler.trigger()})}))}if(i.onSave===!0){let g=e.getFeature(p.DidSaveTextDocumentNotification.method);o.push(g.onNotificationSent(f=>{let m=f.original;c(m,"onSave")&&this.diagnosticRequestor.pull(f.original,()=>{this.backgroundScheduler.trigger()})}))}let d=e.getFeature(p.DidCloseTextDocumentNotification.method);o.push(d.onNotificationSent(g=>{this.cleanUpDocument(g.original)})),this.diagnosticRequestor.onDidChangeDiagnosticsEmitter.event(()=>{for(let g of y.textDocuments)a(g)&&this.diagnosticRequestor.pull(g)}),P.onDidChangeVisibleTextEditors(g=>{let f=new Set,m=this.diagnosticRequestor.trackingDocuments();g.forEach(b=>{let{uri:v,textDocument:x}=b.document;f.has(v)||(f.add(v),a(x)&&!m.includes(v)&&this.diagnosticRequestor.pull(x,()=>{l(x)}))}),m.forEach(b=>{if(f.has(b))return;let v=y.getDocument(b);v&&v.attached&&this.cleanUpDocument(v.textDocument)})},null,o),t.workspaceDiagnostics===!0&&t.identifier!=="da348dc5-c30a-4515-9d98-31ff3be38d14"&&this.diagnosticRequestor.pullWorkspace(),this.disposable=p.Disposable.create(()=>[...o,this.backgroundScheduler,this.diagnosticRequestor].forEach(g=>g.dispose()))}get onDidChangeDiagnosticsEmitter(){return this.diagnosticRequestor.onDidChangeDiagnosticsEmitter}get diagnostics(){return this.diagnosticRequestor.provider}knows(e,t){return this.diagnosticRequestor.knows(e,t)}cleanUpDocument(e){this.diagnosticRequestor.knows(1,e)&&(this.diagnosticRequestor.forgetDocument(e),this.backgroundScheduler.remove(e))}},$x=class extends Le{constructor(e){super(e,p.DocumentDiagnosticRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"diagnostic");t.dynamicRegistration=!0,t.relatedDocumentSupport=!0,q(q(e,"workspace"),"diagnostics").refreshSupport=!0}initialize(e,t){let i=this._client,[r,o]=this.getRegistration(t,e.diagnosticProvider);!r||!o||(i.onRequest(p.DiagnosticRefreshRequest.type,async()=>{for(let s of this.getAllProviders())s.onDidChangeDiagnosticsEmitter.fire()}),this.register({id:r,registerOptions:o}))}registerLanguageProvider(e){let t=new r0(this._client,e);return[t.disposable,t]}}});var Ux,WQ=D(()=>{"use strict";Se();U();ut();ii();si();Ux=class extends Le{constructor(e){super(e,p.DocumentHighlightRequest.type)}fillClientCapabilities(e){q(q(e,"textDocument"),"documentHighlight").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentHighlightProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e){let t={provideDocumentHighlights:(i,r,o)=>{let s=this._client,a=(u,c,d)=>this.sendRequest(p.DocumentHighlightRequest.type,Bi(u,c),d),l=s.middleware;return l.provideDocumentHighlights?l.provideDocumentHighlights(i,r,o,a):a(i,r,o)}};return[I.registerDocumentHighlightProvider(e.documentSelector,t),t]}}});var Xx,YQ=D(()=>{"use strict";Se();U();ut();si();Xx=class extends Le{constructor(e){super(e,p.DocumentLinkRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"documentLink");t.dynamicRegistration=!0,t.tooltipSupport=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentLinkProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e){let t={provideDocumentLinks:(i,r)=>{let o=this._client,s=(l,u)=>this.sendRequest(p.DocumentLinkRequest.type,{textDocument:{uri:l.uri}},u),a=o.middleware;return a.provideDocumentLinks?a.provideDocumentLinks(i,r,s):s(i,r)},resolveDocumentLink:e.resolveProvider?(i,r)=>{let o=this._client,s=(l,u)=>this.sendRequest(p.DocumentLinkResolveRequest.type,l,u,l),a=o.middleware;return a.resolveDocumentLink?a.resolveDocumentLink(i,r,s):s(i,r)}:void 0};return[I.registerDocumentLinkProvider(e.documentSelector,t),t]}}});var o0,s0,Gx,a0=D(()=>{"use strict";ae();Se();U();ut();ii();si();o0=[De.File,De.Module,De.Namespace,De.Package,De.Class,De.Method,De.Property,De.Field,De.Constructor,De.Enum,De.Interface,De.Function,De.Variable,De.Constant,De.String,De.Number,De.Boolean,De.Array,De.Object,De.Key,De.Null,De.EnumMember,De.Struct,De.Event,De.Operator,De.TypeParameter],s0=[$i.Deprecated],Gx=class extends Le{constructor(e){super(e,p.DocumentSymbolRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"documentSymbol");t.dynamicRegistration=!0,t.symbolKind={valueSet:o0},t.hierarchicalDocumentSymbolSupport=!0,t.tagSupport={valueSet:s0},t.labelSupport=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentSymbolProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e){let t={meta:e.label?{label:e.label}:void 0,provideDocumentSymbols:(i,r)=>{let o=this._client,s=(l,u)=>this.sendRequest(p.DocumentSymbolRequest.type,EQ(l),u),a=o.middleware;return a.provideDocumentSymbols?a.provideDocumentSymbols(i,r,s):s(i,r)}};return[I.registerDocumentSymbolProvider(e.documentSelector,t),t]}}});var zx,ZQ=D(()=>{"use strict";U();ut();Dt();si();zx=class extends so{constructor(t){super(t);this._commands=new Map}getState(){return{kind:"workspace",id:this.registrationType.method,registrations:this._commands.size>0}}get registrationType(){return p.ExecuteCommandRequest.type}fillClientCapabilities(t){q(q(t,"workspace"),"executeCommand").dynamicRegistration=!0}initialize(t){!t.executeCommandProvider||this.register({id:He(),registerOptions:Object.assign({},t.executeCommandProvider)})}register(t){let r=this._client.middleware,o=(s,a)=>{let l={command:s,arguments:a};return this.sendRequest(p.ExecuteCommandRequest.type,l,p.CancellationToken.None)};if(t.registerOptions.commands){let s=[];for(let a of t.registerOptions.commands)s.push(V.registerCommand(a,(...l)=>r.executeCommand?r.executeCommand(a,l,o):o(a,l),null,!0));this._commands.set(t.id,s)}}unregister(t){let i=this._commands.get(t);i&&i.forEach(r=>r.dispose())}dispose(){this._commands.forEach(t=>{t.forEach(i=>i.dispose())}),this._commands.clear()}}});function kfe(n,e){return n[e]}function JQ(n,e,t){n[e]=t}function nC(n){return{files:n.files.map(e=>({uri:e.toString()}))}}function $Q(n){return{files:n.files.map(e=>({oldUri:e.oldUri.toString(),newUri:e.newUri.toString()}))}}var vd,rm,Kx,Qx,Vx,om,eC,tC,iC,UQ=D(()=>{"use strict";de();st();U();he();ut();si();vd=class extends so{constructor(t,i,r,o,s){super(t);this._filters=new Map;this._event=i,this._registrationType=r,this._clientCapability=o,this._serverCapability=s}getState(){return{kind:"workspace",id:this._registrationType.method,registrations:this._filters.size>0}}get registrationType(){return this._registrationType}fillClientCapabilities(t){let i=q(q(t,"workspace"),"fileOperations");JQ(i,"dynamicRegistration",!0),JQ(i,this._clientCapability,!0)}initialize(t){var o;let i=(o=t.workspace)==null?void 0:o.fileOperations,r=i!==void 0?kfe(i,this._serverCapability):void 0;if((r==null?void 0:r.filters)!==void 0)try{this.register({id:He(),registerOptions:{filters:r.filters}})}catch(s){this._client.warn(`Ignoring invalid glob pattern for ${this._serverCapability} registration: ${s}`)}}register(t){this._listener||(this._listener=this._event(this.send,this));let i=t.registerOptions.filters.map(r=>{let o=new ni.Minimatch(r.pattern.glob,vd.asMinimatchOptions(r.pattern.options));if(!o.makeRe())throw new Error(`Invalid pattern ${r.pattern.glob}!`);return{scheme:r.scheme,matcher:o,kind:r.pattern.matches}});this._filters.set(t.id,i)}unregister(t){this._filters.delete(t)}dispose(){this._filters.clear(),this._listener&&(this._listener.dispose(),this._listener=void 0)}async filter(t,i){let r=await Promise.all(t.files.map(async s=>{let a=i(s),l=a.fsPath.replace(/\\/g,"/");for(let u of this._filters.values())for(let c of u)if(!(c.scheme!==void 0&&c.scheme!==a.scheme)){if(c.matcher.match(l)){if(c.kind===void 0)return!0;let d=await Jk(a.fsPath);if(d===void 0)return this._client.error(`Failed to determine file type for ${a.toString()}.`),!0;if(d===1&&c.kind===p.FileOperationPatternKind.file||d===2&&c.kind===p.FileOperationPatternKind.folder)return!0}else if(c.kind===p.FileOperationPatternKind.folder&&await Jk(a.fsPath)===2&&c.matcher.match(`${l}/`))return!0}return!1})),o=t.files.filter((s,a)=>r[a]);return{...t,files:o}}static asMinimatchOptions(t){if(t!==void 0&&t.ignoreCase===!0)return{nocase:!0}}},rm=class extends vd{constructor(t,i,r,o,s,a,l){super(t,i,r,o,s);this._notificationType=r,this._accessUri=a,this._createParams=l}async send(t){let i=await this.filter(t,this._accessUri);if(i.files.length){let r=async s=>{if(!!this._client.isRunning())return this._client.sendNotification(this._notificationType,this._createParams(s))},o=this.doSend(i,r);o&&await o.catch(s=>{this._client.error(`Sending notification ${this.registrationType.method} failed`,s)})}}},Kx=class extends rm{constructor(e){super(e,y.onDidCreateFiles,p.DidCreateFilesNotification.type,"didCreate","didCreate",t=>t,t=>nC(t))}doSend(e,t){let i=this._client.middleware.workspace;return i!=null&&i.didCreateFiles?i.didCreateFiles(e,t):t(e)}},Qx=class extends rm{constructor(e){super(e,y.onDidRenameFiles,p.DidRenameFilesNotification.type,"didRename","didRename",t=>t.oldUri,t=>$Q(t))}doSend(e,t){let i=this._client.middleware.workspace;return i!=null&&i.didRenameFiles?i.didRenameFiles(e,t):t(e)}},Vx=class extends rm{constructor(e){super(e,y.onDidDeleteFiles,p.DidDeleteFilesNotification.type,"didDelete","didDelete",t=>t,t=>nC(t))}doSend(e,t){let i=this._client.middleware.workspace;return i!=null&&i.didDeleteFiles?i.didDeleteFiles(e,t):t(e)}},om=class extends vd{constructor(t,i,r,o,s,a,l){super(t,i,r,o,s);this._requestType=r,this._accessUri=a,this._createParams=l}async send(t){let i=this.waitUntil(t);t.waitUntil(i)}async waitUntil(t){let i=await this.filter(t,this._accessUri);if(i.files.length){let r=o=>this.sendRequest(this._requestType,this._createParams(o),p.CancellationToken.None);return this.doSend(i,r)}else return}},eC=class extends om{constructor(e){super(e,y.onWillCreateFiles,p.WillCreateFilesRequest.type,"willCreate","willCreate",t=>t,t=>nC(t))}doSend(e,t){let i=this._client.middleware.workspace;return i!=null&&i.willCreateFiles?i.willCreateFiles(e,t):t(e)}},tC=class extends om{constructor(e){super(e,y.onWillRenameFiles,p.WillRenameFilesRequest.type,"willRename","willRename",t=>t.oldUri,t=>$Q(t))}doSend(e,t){let i=this._client.middleware.workspace;return i!=null&&i.willRenameFiles?i.willRenameFiles(e,t):t(e)}},iC=class extends om{constructor(e){super(e,y.onWillDeleteFiles,p.WillDeleteFilesRequest.type,"willDelete","willDelete",t=>t,t=>nC(t))}doSend(e,t){let i=this._client.middleware.workspace;return i!=null&&i.willDeleteFiles?i.willDeleteFiles(e,t):t(e)}}});var Pfe,rC,XQ=D(()=>{"use strict";te();Xe();de();U();he();ut();ii();si();Pfe=pe(200,20),rC=class{constructor(e){this._client=e;this._watchers=new Map;this._fileEventsMap=new Map;this.debouncedFileNotify=ft(()=>{this._notifyFileEvent()},Pfe)}async _notifyFileEvent(){let e=this._fileEventsMap;e.size!=0&&(await this._client.forceDocumentSync(),this._client.sendNotification(p.DidChangeWatchedFilesNotification.type,{changes:Array.from(e.values())}).catch(t=>{this._client.error("Notify file events failed.",t)}),e.clear())}notifyFileEvent(e){let t=this;function i(o){t._fileEventsMap.set(o.uri,o),t.debouncedFileNotify()}let r=this._client.middleware.workspace;r!=null&&r.didChangeWatchedFile?r.didChangeWatchedFile(e,i):i(e)}getState(){return{kind:"workspace",id:this.registrationType.method,registrations:this._watchers.size>0}}get registrationType(){return p.DidChangeWatchedFilesNotification.type}fillClientCapabilities(e){q(q(e,"workspace"),"didChangeWatchedFiles").dynamicRegistration=!0,q(q(e,"workspace"),"didChangeWatchedFiles").relativePatternSupport=!0}initialize(e,t){var s;let i=(s=this._client.clientOptions.synchronize)==null?void 0:s.fileEvents;if(!i)return;let r=Array.isArray(i)?i:[i],o=[];for(let a of r)o.push(a),this.hookListeners(a,!a.ignoreCreateEvents,!a.ignoreChangeEvents,!a.ignoreDeleteEvents,o);this._watchers.set(He(),o)}register(e){if(!Array.isArray(e.registerOptions.watchers))return;let t=[];for(let i of e.registerOptions.watchers){let r;if($e(i.globPattern))r=i.globPattern;else if(p.RelativePattern.is(i.globPattern))r=CQ(i.globPattern);else continue;let o=!0,s=!0,a=!0;i.kind!=null&&(o=(i.kind&p.WatchKind.Create)!==0,s=(i.kind&p.WatchKind.Change)!==0,a=(i.kind&p.WatchKind.Delete)!==0);let l=y.createFileSystemWatcher(r,!o,!s,!a);this.hookListeners(l,o,s,a,t),t.push(l)}this._watchers.set(e.id,t)}hookListeners(e,t,i,r,o){t&&e.onDidCreate(s=>this.notifyFileEvent({uri:yd(s),type:p.FileChangeType.Created}),null,o),i&&e.onDidChange(s=>this.notifyFileEvent({uri:yd(s),type:p.FileChangeType.Changed}),null,o),r&&e.onDidDelete(s=>this.notifyFileEvent({uri:yd(s),type:p.FileChangeType.Deleted}),null,o)}unregister(e){let t=this._watchers.get(e);if(t){for(let i of t)i.dispose();this._watchers.delete(e)}}dispose(){this._fileEventsMap.clear(),this.debouncedFileNotify.clear(),this._watchers.forEach(e=>{for(let t of e)t.dispose()}),this._watchers.clear()}}});var oC,GQ=D(()=>{"use strict";Se();U();ut();oC=class extends Le{constructor(e){super(e,p.FoldingRangeRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"foldingRange");t.dynamicRegistration=!0,t.rangeLimit=5e3,t.lineFoldingOnly=!0,t.foldingRangeKind={valueSet:[p.FoldingRangeKind.Comment,p.FoldingRangeKind.Imports,p.FoldingRangeKind.Region]},t.foldingRange={collapsedText:!1}}initialize(e,t){let[i,r]=this.getRegistration(t,e.foldingRangeProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t={provideFoldingRanges:(i,r,o)=>{let s=this._client,a=(u,c,d)=>{let h={textDocument:{uri:u.uri}};return this.sendRequest(p.FoldingRangeRequest.type,h,d)},l=s.middleware;return l.provideFoldingRanges?l.provideFoldingRanges(i,r,o,a):a(i,r,o)}};return[I.registerFoldingRangeProvider(e.documentSelector,t),t]}}});var sC,aC,lC,zQ=D(()=>{"use strict";Se();U();ut();ii();si();sC=class extends Le{constructor(e){super(e,p.DocumentFormattingRequest.type)}fillClientCapabilities(e){q(q(e,"textDocument"),"formatting").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentFormattingProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e){let t={provideDocumentFormattingEdits:(i,r,o)=>{let s=this._client,a=(u,c,d)=>{let h={textDocument:{uri:u.uri},options:c};return this.sendRequest(p.DocumentFormattingRequest.type,h,d)},l=s.middleware;return l.provideDocumentFormattingEdits?l.provideDocumentFormattingEdits(i,r,o,a):a(i,r,o)}};return[I.registerDocumentFormatProvider(e.documentSelector,t,this._client.clientOptions.formatterPriority),t]}},aC=class extends Le{constructor(e){super(e,p.DocumentRangeFormattingRequest.type)}fillClientCapabilities(e){q(q(e,"textDocument"),"rangeFormatting").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentRangeFormattingProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e){let t={provideDocumentRangeFormattingEdits:(i,r,o,s)=>{let a=this._client,l=(c,d,h,g)=>{let f={textDocument:{uri:c.uri},range:d,options:h};return this.sendRequest(p.DocumentRangeFormattingRequest.type,f,g)},u=a.middleware;return u.provideDocumentRangeFormattingEdits?u.provideDocumentRangeFormattingEdits(i,r,o,s,l):l(i,r,o,s)}};return[I.registerDocumentRangeFormatProvider(e.documentSelector,t),t]}},lC=class extends Le{constructor(e){super(e,p.DocumentOnTypeFormattingRequest.type)}fillClientCapabilities(e){q(q(e,"textDocument"),"onTypeFormatting").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.documentOnTypeFormattingProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e){let t={provideOnTypeFormattingEdits:(o,s,a,l,u)=>{let c=this._client,d=(g,f,m,b,v)=>{let x={textDocument:Ax(g),position:f,ch:m,options:b};return this.sendRequest(p.DocumentOnTypeFormattingRequest.type,x,v)},h=c.middleware;return h.provideOnTypeFormattingEdits?h.provideOnTypeFormattingEdits(o,s,a,l,u,d):d(o,s,a,l,u)}},i=e.moreTriggerCharacter||[],r=[e.firstTriggerCharacter,...i];return[I.registerOnTypeFormattingEditProvider(e.documentSelector,t,r),t]}}});var uC,KQ=D(()=>{"use strict";Se();U();ut();ii();si();uC=class extends Le{constructor(e){super(e,p.HoverRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"hover");t.dynamicRegistration=!0,t.contentFormat=this._client.supportedMarkupKind}initialize(e,t){let i=this.getRegistrationOptions(t,e.hoverProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e){let t={provideHover:(i,r,o)=>{let s=this._client,a=(u,c,d)=>this.sendRequest(p.HoverRequest.type,Bi(u,c),d),l=s.middleware;return l.provideHover?l.provideHover(i,r,o,a):a(i,r,o)}};return[I.registerHoverProvider(e.documentSelector,t),t]}}});var cC,QQ=D(()=>{"use strict";Se();U();ut();ii();cC=class extends Le{constructor(e){super(e,p.ImplementationRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"implementation");t.dynamicRegistration=!0,t.linkSupport=!0}initialize(e,t){let[i,r]=this.getRegistration(t,e.implementationProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t={provideImplementation:(i,r,o)=>{let s=this._client,a=(u,c,d)=>this.sendRequest(p.ImplementationRequest.type,Bi(u,c),d),l=s.middleware;return l.provideImplementation?l.provideImplementation(i,r,o,a):a(i,r,o)}};return[I.registerImplementationProvider(e.documentSelector,t),t]}}});var dC,VQ=D(()=>{"use strict";Se();U();ut();ii();dC=class extends Le{constructor(e){super(e,p.InlayHintRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"inlayHint");t.dynamicRegistration=!0,t.resolveSupport={properties:["tooltip","textEdits","label.tooltip","label.location","label.command"]},q(q(e,"workspace"),"inlayHint").refreshSupport=!0}initialize(e,t){this._client.onRequest(p.InlayHintRefreshRequest.type,async()=>{for(let o of this.getAllProviders())o.onDidChangeInlayHints.fire()});let[i,r]=this.getRegistration(t,e.inlayHintProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t=new p.Emitter,i={onDidChangeInlayHints:t.event,provideInlayHints:(o,s,a)=>{let l=this._client,u=(d,h,g)=>{let f={textDocument:ao(d),range:h};return this.sendRequest(p.InlayHintRequest.type,f,g,null)},c=l.middleware;return c.provideInlayHints?c.provideInlayHints(o,s,a,u):u(o,s,a)}};i.resolveInlayHint=e.resolveProvider===!0?(o,s)=>{let a=this._client,l=(c,d)=>this.sendRequest(p.InlayHintResolveRequest.type,c,d),u=a.middleware;return u.resolveInlayHint?u.resolveInlayHint(o,s,l):l(o,s)}:void 0;let r=e.documentSelector;return[I.registerInlayHintsProvider(r,i),{provider:i,onDidChangeInlayHints:t}]}}});var hC,e4=D(()=>{"use strict";Se();U();ut();ii();hC=class extends Le{constructor(e){super(e,p.InlineValueRequest.type)}fillClientCapabilities(e){q(q(e,"textDocument"),"inlineValue").dynamicRegistration=!0,q(q(e,"workspace"),"inlineValue").refreshSupport=!0}initialize(e,t){this._client.onRequest(p.InlineValueRefreshRequest.type,async()=>{for(let o of this.getAllProviders())o.onDidChangeInlineValues.fire()});let[i,r]=this.getRegistration(t,e.inlineValueProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t=new p.Emitter,i={onDidChangeInlineValues:t.event,provideInlineValues:(o,s,a,l)=>{let u=this._client,c=(h,g,f,m)=>{let b={textDocument:ao(h),range:g,context:f};return this.sendRequest(p.InlineValueRequest.type,b,m)},d=u.middleware;return d.provideInlineValues?d.provideInlineValues(o,s,a,l,c):c(o,s,a,l)}},r=e.documentSelector;return[I.registerInlineValuesProvider(r,i),{provider:i,onDidChangeInlineValues:t}]}}});var gC,t4=D(()=>{"use strict";Se();U();ut();ii();gC=class extends Le{constructor(e){super(e,p.LinkedEditingRangeRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"linkedEditingRange");t.dynamicRegistration=!0}initialize(e,t){let[i,r]=this.getRegistration(t,e.linkedEditingRangeProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t={provideLinkedEditingRanges:(i,r,o)=>{let s=this._client,a=(u,c,d)=>{let h=Bi(u,c);return this.sendRequest(p.LinkedEditingRangeRequest.type,h,d)},l=s.middleware;return l.provideLinkedEditingRange?l.provideLinkedEditingRange(i,r,o,a):a(i,r,o)}};return[I.registerLinkedEditingRangeProvider(e.documentSelector,t),t]}}});function Rfe(n){return typeof n!="number"?!1:n>=0&&n<=100}var wd,l0=D(()=>{"use strict";te();U();We();wd=class{constructor(e,t,i){this.client=e;this.token=t;this.disposables=[];this._cancelled=!1;this._percent=0;this._started=!1;this.disposables.push(e.onProgress(p.WorkDoneProgress.type,this.token,r=>{switch(r.kind){case"begin":this.begin(r);break;case"report":this.report(r);break;case"end":this.done(r.message),i&&i(this);break}}))}begin(e){return this._started||this._cancelled?!1:(this._started=!0,P.withProgress({source:`language-client-${this.client.id}`,cancellable:e.cancellable,title:e.title},(t,i)=>(this.progress=t,this.report(e),this._cancelled?Promise.resolve():(this.disposables.push(i.onCancellationRequested(()=>{this.client.sendNotification(p.WorkDoneProgressCancelNotification.type,{token:this.token}),this.cancel()})),new Promise((r,o)=>{this._resolve=r,this._reject=o})))),!0)}report(e){if(!this.progress)return;let t={};e.message&&(t.message=e.message),Rfe(e.percentage)&&(t.increment=e.percentage-this._percent,this._percent=e.percentage),Object.keys(t).length>0&&this.progress.report(t)}cancel(){this._cancelled||(this.cleanUp(),this._reject!==void 0&&(this._reject(),this._resolve=void 0,this._reject=void 0))}done(e){if(this.progress){let t={};e&&(t.message=e),typeof this._percent=="number"&&this._percent>0&&(t.increment=100-this._percent),this.progress.report(t)}this.cleanUp(),this._resolve&&(this._resolve(),this._resolve=void 0,this._reject=void 0)}cleanUp(){this._cancelled=!0,this.progress=void 0,W(this.disposables)}}});var pC,i4=D(()=>{"use strict";U();ut();l0();pC=class{constructor(e){this._client=e;this.activeParts=new Set}get method(){return p.WorkDoneProgressCreateRequest.method}fillClientCapabilities(e){q(e,"window").workDoneProgress=!0}getState(){return{kind:"window",id:p.WorkDoneProgressCreateRequest.method,registrations:this.activeParts.size>0}}initialize(){let e=this._client,t=r=>{this.activeParts.delete(r)},i=r=>{this.activeParts.add(new wd(this._client,r.token,t))};e.onRequest(p.WorkDoneProgressCreateRequest.type,i)}dispose(){for(let e of this.activeParts)e.done();this.activeParts.clear()}}});var fC,n4=D(()=>{"use strict";Se();U();ut();ii();si();fC=class extends Le{constructor(e){super(e,p.ReferencesRequest.type)}fillClientCapabilities(e){q(q(e,"textDocument"),"references").dynamicRegistration=!0}initialize(e,t){let i=this.getRegistrationOptions(t,e.referencesProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e){let t={provideReferences:(i,r,o,s)=>{let a=this._client,l=(c,d,h,g)=>this.sendRequest(p.ReferencesRequest.type,_Q(c,d,h),g),u=a.middleware;return u.provideReferences?u.provideReferences(i,r,o,s,l):l(i,r,o,s)}};return[I.registerReferencesProvider(e.documentSelector,t),t]}}});var mC,r4=D(()=>{"use strict";ae();Se();Xe();U();ut();ii();si();mC=class extends Le{constructor(e){super(e,p.RenameRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"rename");t.dynamicRegistration=!0,t.prepareSupport=!0,t.honorsChangeAnnotations=!0,t.prepareSupportDefaultBehavior=p.PrepareSupportDefaultBehavior.Identifier}initialize(e,t){let i=this.getRegistrationOptions(t,e.renameProvider);!i||(Pn(e.renameProvider)&&(i.prepareProvider=!1),this.register({id:He(),registerOptions:i}))}registerLanguageProvider(e){let t={provideRenameEdits:(i,r,o,s)=>{let a=this._client,l=(c,d,h,g)=>{let f={textDocument:{uri:c.uri},position:d,newName:h};return this.sendRequest(p.RenameRequest.type,f,g)},u=a.middleware;return u.provideRenameEdits?u.provideRenameEdits(i,r,o,s,l):l(i,r,o,s)},prepareRename:e.prepareProvider?(i,r,o)=>{let s=this._client,a=(u,c,d)=>{let h={textDocument:ao(u),position:c};return this.sendRequest(p.PrepareRenameRequest.type,h,d).then(g=>{if(!g)return null;if(M.is(g))return g;if(this.isDefaultBehavior(g))return g.defaultBehavior===!0?null:Promise.reject(new Error("The element can't be renamed."));if(g&&M.is(g.range))return{range:g.range,placeholder:g.placeholder}})},l=s.middleware;return l.prepareRename?l.prepareRename(i,r,o,a):a(i,r,o)}:void 0};return[I.registerRenameProvider(e.documentSelector,t),t]}isDefaultBehavior(e){let t=e;return t&&Pn(t.defaultBehavior)}}});var bC,o4=D(()=>{"use strict";Se();U();ut();bC=class extends Le{constructor(e){super(e,p.SelectionRangeRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"selectionRange");t.dynamicRegistration=!0}initialize(e,t){let[i,r]=this.getRegistration(t,e.selectionRangeProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t={provideSelectionRanges:(i,r,o)=>{let s=this._client,a=(u,c,d)=>{let h={textDocument:{uri:u.uri},positions:c};return this.sendRequest(p.SelectionRangeRequest.type,h,d)},l=s.middleware;return l.provideSelectionRanges?l.provideSelectionRanges(i,r,o,a):a(i,r,o)}};return[I.registerSelectionRangeProvider(e.documentSelector,t),t]}}});var yC,s4=D(()=>{"use strict";ae();Se();Xe();U();ut();ii();yC=class extends Le{constructor(e){super(e,p.SemanticTokensRegistrationType.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"semanticTokens");t.dynamicRegistration=!0,t.tokenTypes=[St.namespace,St.type,St.class,St.enum,St.interface,St.struct,St.typeParameter,St.parameter,St.variable,St.property,St.enumMember,St.event,St.function,St.method,St.macro,St.keyword,St.modifier,St.comment,St.string,St.number,St.regexp,St.decorator,St.operator],t.tokenModifiers=[nn.declaration,nn.definition,nn.readonly,nn.static,nn.deprecated,nn.abstract,nn.async,nn.modification,nn.documentation,nn.defaultLibrary],t.formats=[p.TokenFormat.Relative],t.requests={range:!0,full:{delta:!0}},t.multilineTokenSupport=!1,t.overlappingTokenSupport=!1,t.serverCancelSupport=!0,t.augmentsSyntaxTokens=!0,q(q(e,"workspace"),"semanticTokens").refreshSupport=!0}initialize(e,t){this._client.onRequest(p.SemanticTokensRefreshRequest.type,async()=>{for(let s of this.getAllProviders())s.onDidChangeSemanticTokensEmitter.fire()});let[r,o]=this.getRegistration(t,e.semanticTokensProvider);!r||!o||this.register({id:r,registerOptions:o})}registerLanguageProvider(e){let t=Pn(e.full)?e.full:e.full!==void 0,i=e.full!==void 0&&typeof e.full!="boolean"&&e.full.delta===!0,r=new p.Emitter,o=t?{onDidChangeSemanticTokens:r.event,provideDocumentSemanticTokens:(u,c)=>{let h=this._client.middleware,g=(f,m)=>{let b={textDocument:ao(f)};return this.sendRequest(p.SemanticTokensRequest.type,b,m)};return h.provideDocumentSemanticTokens?h.provideDocumentSemanticTokens(u,c,g):g(u,c)},provideDocumentSemanticTokensEdits:i?(u,c,d)=>{let g=this._client.middleware,f=(m,b,v)=>{let x={textDocument:ao(m),previousResultId:b};return this.sendRequest(p.SemanticTokensDeltaRequest.type,x,v)};return g.provideDocumentSemanticTokensEdits?g.provideDocumentSemanticTokensEdits(u,c,d,f):f(u,c,d)}:void 0}:void 0,a=e.range===!0?{provideDocumentRangeSemanticTokens:(u,c,d)=>{let g=this._client.middleware,f=(m,b,v)=>{let x={textDocument:ao(m),range:b};return this.sendRequest(p.SemanticTokensRangeRequest.type,x,v)};return g.provideDocumentRangeSemanticTokens?g.provideDocumentRangeSemanticTokens(u,c,d,f):f(u,c,d)}}:void 0,l=[];return o!==void 0&&l.push(I.registerDocumentSemanticTokensProvider(e.documentSelector,o,e.legend)),a!==void 0&&l.push(I.registerDocumentRangeSemanticTokensProvider(e.documentSelector,a,e.legend)),[p.Disposable.create(()=>l.forEach(u=>u.dispose())),{range:a,full:o,onDidChangeSemanticTokensEmitter:r}]}}});var vC,a4=D(()=>{"use strict";Se();U();ut();ii();si();vC=class extends Le{constructor(e){super(e,p.SignatureHelpRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"signatureHelp");t.dynamicRegistration=!0,t.contextSupport=!0,t.signatureInformation={documentationFormat:this._client.supportedMarkupKind,activeParameterSupport:!0,parameterInformation:{labelOffsetSupport:!0}}}initialize(e,t){let i=this.getRegistrationOptions(t,e.signatureHelpProvider);!i||this.register({id:He(),registerOptions:i})}registerLanguageProvider(e){let t={provideSignatureHelp:(r,o,s,a)=>{let l=this._client,u=(d,h,g,f)=>this.sendRequest(p.SignatureHelpRequest.type,RQ(d,h,g),f),c=l.middleware;return c.provideSignatureHelp?c.provideSignatureHelp(r,o,a,s,u):u(r,o,a,s)}};return[I.registerSignatureHelpProvider(e.documentSelector,t,e.triggerCharacters),t]}}});var wC,xC,CC,SC,DC,TC,l4=D(()=>{"use strict";U();he();ut();ii();si();wC=class extends Rr{constructor(t,i){super(t,y.onDidOpenTextDocument,p.DidOpenTextDocumentNotification.type,"didOpen",r=>xQ(r),Rr.textDocumentFilter);this._syncedDocuments=i}get registrationType(){return p.DidOpenTextDocumentNotification.type}fillClientCapabilities(t){q(q(t,"textDocument"),"synchronization").dynamicRegistration=!0}initialize(t,i){let r=t.resolvedTextDocumentSync;i&&r&&r.openClose&&this.register({id:He(),registerOptions:{documentSelector:i}})}register(t){super.register(t),t.registerOptions.documentSelector&&y.textDocuments.forEach(i=>{let r=i.uri;this._syncedDocuments.has(r)||this.callback(i)})}notificationSent(t,i,r){super.notificationSent(t,i,r),this._syncedDocuments.set(t.uri.toString(),t)}},xC=class extends Rr{constructor(t,i){super(t,y.onDidCloseTextDocument,p.DidCloseTextDocumentNotification.type,"didClose",r=>SQ(r),Rr.textDocumentFilter);this._syncedDocuments=i}get registrationType(){return p.DidCloseTextDocumentNotification.type}fillClientCapabilities(t){q(q(t,"textDocument"),"synchronization").dynamicRegistration=!0}initialize(t,i){let r=t.resolvedTextDocumentSync;i&&r&&r.openClose&&this.register({id:He(),registerOptions:{documentSelector:i}})}notificationSent(t,i,r){super.notificationSent(t,i,r),this._syncedDocuments.delete(t.uri.toString())}unregister(t){let i=this._selectors.get(t);if(!i)return;super.unregister(t);let r=this._selectors.values();this._syncedDocuments.forEach(o=>{if(y.match(i,o)>0&&!this._selectorFilter(r,o)){let s=this._client.middleware,a=u=>this._client.sendNotification(this._type,this._createParams(u));this._syncedDocuments.delete(o.uri.toString());let l=s.didClose?s.didClose(o,a):a(o);l&&l.catch(u=>{this._client.error(`Sending document notification ${this._type.method} failed`,u)})}})}},CC=class extends ou{constructor(t){super(t);this._changeData=new Map,this._onNotificationSent=new p.Emitter}*getDocumentSelectors(){for(let t of this._changeData.values())yield t.documentSelector}get registrationType(){return p.DidChangeTextDocumentNotification.type}fillClientCapabilities(t){q(q(t,"textDocument"),"synchronization").dynamicRegistration=!0}initialize(t,i){let r=t.resolvedTextDocumentSync;i&&r&&r.change!==void 0&&r.change!==p.TextDocumentSyncKind.None&&this.register({id:He(),registerOptions:Object.assign({},{documentSelector:i},{syncKind:r.change})})}register(t){!t.registerOptions.documentSelector||(this._listener||(this._listener=y.onDidChangeTextDocument(this.callback,this)),this._changeData.set(t.id,{documentSelector:t.registerOptions.documentSelector,syncKind:t.registerOptions.syncKind}))}callback(t){if(t.contentChanges.length===0)return;let i=y.getDocument(t.textDocument.uri),{textDocument:r}=i,o=[];for(let s of this._changeData.values())if(y.match(s.documentSelector,r)>0){let a=this._client.middleware,l,u;s.syncKind===p.TextDocumentSyncKind.Incremental?u=async c=>{let d=TQ(c);await this._client.sendNotification(p.DidChangeTextDocumentNotification.type,d),this.notificationSent(c,p.DidChangeTextDocumentNotification.type,d)}:s.syncKind===p.TextDocumentSyncKind.Full?u=async c=>{let d=DQ(r);await this._client.sendNotification(p.DidChangeTextDocumentNotification.type,d),this.notificationSent(c,p.DidChangeTextDocumentNotification.type,d)}:u=()=>Promise.resolve(void 0),l=a.didChange?a.didChange(t,u):u(t),l&&o.push(l)}return Promise.all(o).then(void 0,s=>{throw this._client.error(`Sending document notification ${p.DidChangeTextDocumentNotification.type.method} failed`,s),s})}get onNotificationSent(){return this._onNotificationSent.event}notificationSent(t,i,r){this._onNotificationSent.fire({original:t,type:i,params:r})}unregister(t){this._changeData.delete(t)}dispose(){this._changeData.clear(),this._listener&&(this._listener.dispose(),this._listener=void 0)}getProvider(t){for(let i of this._changeData.values())if(y.match(i.documentSelector,t)>0)return{send:r=>this.callback(r)}}},SC=class extends Rr{constructor(e){super(e,y.onWillSaveTextDocument,p.WillSaveTextDocumentNotification.type,"willSave",t=>e0(t),(t,i)=>Rr.textDocumentFilter(t,i.document))}get registrationType(){return p.WillSaveTextDocumentNotification.type}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"synchronization");t.willSave=!0}initialize(e,t){let i=e.resolvedTextDocumentSync;t&&i&&i.willSave&&this.register({id:He(),registerOptions:{documentSelector:t}})}},DC=class extends ou{constructor(t){super(t);this._selectors=new Map}getDocumentSelectors(){return this._selectors.values()}get registrationType(){return p.WillSaveTextDocumentWaitUntilRequest.type}fillClientCapabilities(t){let i=q(q(t,"textDocument"),"synchronization");i.willSaveWaitUntil=!0}initialize(t,i){let r=t.resolvedTextDocumentSync;i&&i.length>0&&r&&r.willSaveWaitUntil&&this.register({id:He(),registerOptions:{documentSelector:i}})}register(t){!t.registerOptions.documentSelector||(this._listener||(this._listener=y.onWillSaveTextDocument(this.callback,this)),this._selectors.set(t.id,t.registerOptions.documentSelector))}callback(t){if(Rr.textDocumentFilter(this._selectors.values(),t.document)){let i=this._client.middleware,r=o=>this.sendRequest(p.WillSaveTextDocumentWaitUntilRequest.type,e0(o),p.CancellationToken.None);t.waitUntil(i.willSaveWaitUntil?i.willSaveWaitUntil(t,r):r(t))}}unregister(t){this._selectors.delete(t),this._selectors.size===0&&this._listener&&(this._listener.dispose(),this._listener=void 0)}dispose(){this._selectors.clear(),this._listener&&(this._listener.dispose(),this._listener=void 0)}},TC=class extends Rr{constructor(t){super(t,y.onDidSaveTextDocument,p.DidSaveTextDocumentNotification.type,"didSave",i=>kQ(i,this._includeText),Rr.textDocumentFilter);this._includeText=!1}get registrationType(){return p.DidSaveTextDocumentNotification.type}fillClientCapabilities(t){q(q(t,"textDocument"),"synchronization").didSave=!0}initialize(t,i){let r=t.resolvedTextDocumentSync;if(i&&r&&r.save){let o=typeof r.save=="boolean"?{includeText:!1}:{includeText:!!r.save.includeText};this.register({id:He(),registerOptions:Object.assign({},{documentSelector:i},o)})}}register(t){this._includeText=!!t.registerOptions.includeText,super.register(t)}}});var kC,u4=D(()=>{"use strict";Se();U();ut();ii();kC=class extends Le{constructor(e){super(e,p.TypeDefinitionRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"typeDefinition");t.dynamicRegistration=!0,t.linkSupport=!0}initialize(e,t){let[i,r]=this.getRegistration(t,e.typeDefinitionProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t={provideTypeDefinition:(i,r,o)=>{let s=this._client,a=(u,c,d)=>this.sendRequest(p.TypeDefinitionRequest.type,Bi(u,c),d),l=s.middleware;return l.provideTypeDefinition?l.provideTypeDefinition(i,r,o,a):a(i,r,o)}};return[I.registerTypeDefinitionProvider(e.documentSelector,t),t]}}});var PC,c4=D(()=>{"use strict";Se();U();ut();ii();PC=class extends Le{constructor(e){super(e,p.TypeHierarchyPrepareRequest.type)}fillClientCapabilities(e){let t=q(q(e,"textDocument"),"typeHierarchy");t.dynamicRegistration=!0}initialize(e,t){let[i,r]=this.getRegistration(t,e.typeHierarchyProvider);!i||!r||this.register({id:i,registerOptions:r})}registerLanguageProvider(e){let t=this._client,i=e.documentSelector,r={prepareTypeHierarchy:(o,s,a)=>{let l=(c,d,h)=>{let g=Bi(c,d);return this.sendRequest(p.TypeHierarchyPrepareRequest.type,g,h)},u=t.middleware;return u.prepareTypeHierarchy?u.prepareTypeHierarchy(o,s,a,l):l(o,s,a)},provideTypeHierarchySupertypes:(o,s)=>{let a=(u,c)=>this.sendRequest(p.TypeHierarchySupertypesRequest.type,{item:u},c),l=t.middleware;return l.provideTypeHierarchySupertypes?l.provideTypeHierarchySupertypes(o,s,a):a(o,s)},provideTypeHierarchySubtypes:(o,s)=>{let a=(u,c)=>this.sendRequest(p.TypeHierarchySubtypesRequest.type,{item:u},c),l=t.middleware;return l.provideTypeHierarchySubtypes?l.provideTypeHierarchySubtypes(o,s,a):a(o,s)}};return[I.registerTypeHierarchyProvider(i,r),r]}}});function d4(){let n=process.env.LANG;return n?n.split(".")[0]:"en"}function Ps(n){return $e(n)?n:n.method}function au(){return Kd(new Date)}function h4(n){return n.isLSPMessage&&n.type?`[LSP - ${au()}] `:`[Trace - ${au()}] `}function sm(n,e=!1){if(n instanceof p.ResponseError){let t=n;return` Message: ${t.message} + Code: ${t.code} ${t.data?` +`+t.data.toString():""}`}return n instanceof Error?$e(n.stack)?n.stack:n.message:$e(n)?n:(0,ot.inspect)(n,!1,null,e)}function g4(n){if(typeof n!="string")return sm(n);let e=["Params: ","Result: "];for(let t of e)if(n.startsWith(t))try{let i=JSON.parse(n.slice(t.length));return t+sm(i,!0)}catch{return n}return n}var p4=D(()=>{"use strict";xe();Xe();de();U()});var _C,EC,RC,f4=D(()=>{"use strict";_C=(t=>(t[t.DoNotRestart=1]="DoNotRestart",t[t.Restart=2]="Restart",t))(_C||{}),EC=(t=>(t[t.Continue=1]="Continue",t[t.Shutdown=2]="Shutdown",t))(EC||{}),RC=class{constructor(e,t){this.name=e;this.maxRestartCount=t;this.milliseconds=3*60*1e3;this.restarts=[]}error(e,t,i){return i&&i<=3?1:2}closed(){return this.restarts.push(Date.now()),this.restarts.length{"use strict";xe();IC=Z("language-client"),LC=class{error(e){IC.error(e)}warn(e){IC.warn(e)}info(e){IC.info(e)}log(e){IC.log(e)}},am=class{error(e){}warn(e){}info(e){}log(e){}}});function u0(n,e){if(n!==void 0)return n[e]}function b4(n,e){return n.filter(t=>!e.includes(t))}var FC,y4=D(()=>{"use strict";Je();st();U();he();si();FC=class{constructor(e){this._client=e;this._listeners=new Map}getState(){return{kind:"workspace",id:this.registrationType.method,registrations:this._listeners.size>0}}get registrationType(){return p.DidChangeWorkspaceFoldersNotification.type}getValidWorkspaceFolders(){let{workspaceFolders:e}=y;if(!e||e.length==0)return;let t=this._client.clientOptions.ignoredRootPaths??[],i=e.filter(r=>{let o=O.parse(r.uri).fsPath;return t.every(s=>!ai(s,o))});return i.length?i:void 0}fillInitializeParams(e){let t=this.getValidWorkspaceFolders();this.initializeWithFolders(t),t===void 0?(this._client.warn("No valid workspaceFolder exists"),e.workspaceFolders=null):e.workspaceFolders=t.map(i=>this.asProtocol(i))}initializeWithFolders(e){this._initialFolders=e}fillClientCapabilities(e){e.workspace=e.workspace||{},e.workspace.workspaceFolders=!0}initialize(e){let t=this._client;t.onRequest(p.WorkspaceFoldersRequest.type,o=>{let s=()=>{let l=this.getValidWorkspaceFolders();return l===void 0?null:l.map(c=>this.asProtocol(c))},a=t.middleware.workspace;return a!=null&&a.workspaceFolders?a.workspaceFolders(o,s):s(o)});let i=u0(u0(u0(e,"workspace"),"workspaceFolders"),"changeNotifications"),r;typeof i=="string"?r=i:i&&(r=He()),r&&this.register({id:r,registerOptions:void 0})}doSendEvent(e,t){let i={event:{added:e.map(r=>this.asProtocol(r)),removed:t.map(r=>this.asProtocol(r))}};return this._client.sendNotification(p.DidChangeWorkspaceFoldersNotification.type,i)}sendInitialEvent(e){let t;if(this._initialFolders&&e){let i=b4(this._initialFolders,e),r=b4(e,this._initialFolders);(r.length>0||i.length>0)&&(t=this.doSendEvent(r,i))}else this._initialFolders?t=this.doSendEvent([],this._initialFolders):e&&(t=this.doSendEvent(e,[]));t&&t.catch(i=>{this._client.error(`Sending notification ${p.DidChangeWorkspaceFoldersNotification.type.method} failed`,i)})}register(e){let t=e.id,i=this._client,r=y.onDidChangeWorkspaceFolders(s=>{let a=c=>this.doSendEvent(c.added,c.removed),l=i.middleware.workspace,u=l!=null&&l.didChangeWorkspaceFolders?l.didChangeWorkspaceFolders(s,a):a(s);u&&u.catch(c=>{this._client.error(`Sending notification ${p.DidChangeWorkspaceFoldersNotification.type.method} failed`,c)})});this._listeners.set(t,r);let o=this.getValidWorkspaceFolders();this.sendInitialEvent(o)}unregister(e){}dispose(){for(let e of this._listeners.values())e.dispose();this._listeners.clear()}asProtocol(e){return e==null?null:{uri:e.uri,name:e.name}}}});var c0,MC,v4=D(()=>{"use strict";Se();U();a0();ut();si();c0=class extends so{constructor(t,i){super(t);this._registrationType=i;this._registrations=new Map}getState(){let t=this._registrations.size>0;return{kind:"workspace",id:this._registrationType.method,registrations:t}}get registrationType(){return this._registrationType}register(t){let i=this.registerLanguageProvider(t.registerOptions);this._registrations.set(t.id,{disposable:i[0],provider:i[1]})}unregister(t){let i=this._registrations.get(t);i&&i.disposable.dispose()}dispose(){this._registrations.forEach(t=>{t.disposable.dispose()}),this._registrations.clear()}getProviders(){let t=[];for(let i of this._registrations.values())t.push(i.provider);return t}},MC=class extends c0{constructor(e){super(e,p.WorkspaceSymbolRequest.type)}fillClientCapabilities(e){let t=q(q(e,"workspace"),"symbol");t.dynamicRegistration=!0,t.symbolKind={valueSet:o0},t.tagSupport={valueSet:s0},t.resolveSupport={properties:["location.range"]}}initialize(e){!e.workspaceSymbolProvider||this.register({id:He(),registerOptions:e.workspaceSymbolProvider===!0?{workDoneProgress:!1}:e.workspaceSymbolProvider})}registerLanguageProvider(e){let t={provideWorkspaceSymbols:(i,r)=>{let o=this._client,s=(l,u)=>this.sendRequest(p.WorkspaceSymbolRequest.type,{query:l},u),a=o.middleware;return a.provideWorkspaceSymbols?a.provideWorkspaceSymbols(i,r,s):s(i,r)},resolveWorkspaceSymbol:e.resolveProvider===!0?(i,r)=>{let o=this._client,s=(l,u)=>this.sendRequest(p.WorkspaceSymbolResolveRequest.type,l,u),a=o.middleware;return a.resolveWorkspaceSymbol?a.resolveWorkspaceSymbol(i,r,s):s(i,r)}:void 0};return[I.registerWorkspaceSymbolProvider(t),t]}}});function _fe(n,e,t,i,r){let o=new LC,s=(0,p.createProtocolConnection)(n,e,o,r);return s.onError(l=>{t(l[0],l[1],l[2])}),s.onClose(i),{id:"",hasPendingResponse:()=>s.hasPendingResponse(),listen:()=>s.listen(),sendRequest:(l,...u)=>s.sendRequest(Ps(l),...u),onRequest:(l,u)=>s.onRequest(Ps(l),u),sendNotification:(l,u)=>s.sendNotification(Ps(l),u),onNotification:(l,u)=>s.onNotification(Ps(l),u),onProgress:s.onProgress,sendProgress:s.sendProgress,trace:(l,u,c)=>s.trace(l,u,c),initialize:l=>s.sendRequest(p.InitializeRequest.type,l),shutdown:()=>s.sendRequest(p.ShutdownRequest.type,void 0),exit:()=>s.sendNotification(p.ExitNotification.type),end:()=>s.end(),dispose:()=>s.dispose()}}var d0,w4,x4,OC,AC,h0,xd,jC,lm,Efe,g0=D(()=>{"use strict";ae();Je();Se();xe();te();Re();Ii();st();Xe();de();Tt();U();fe();We();he();LQ();FQ();MQ();jQ();OQ();AQ();NQ();HQ();qQ();WQ();YQ();a0();ZQ();ut();UQ();XQ();GQ();zQ();KQ();QQ();VQ();e4();t4();i4();l0();n4();r4();o4();s4();a4();l4();u4();c4();p4();ii();f4();m4();si();y4();v4();d0=Z("language-client-client"),w4="\x1B[31m",x4="\x1B[39m";OC=(r=>(r[r.Info=1]="Info",r[r.Warn=2]="Warn",r[r.Error=3]="Error",r[r.Never=4]="Never",r))(OC||{}),AC=(i=>(i[i.Stopped=1]="Stopped",i[i.Running=2]="Running",i[i.Starting=3]="Starting",i))(AC||{}),h0=(s=>(s[s.Initial=0]="Initial",s[s.Starting=1]="Starting",s[s.StartFailed=2]="StartFailed",s[s.Running=3]="Running",s[s.Stopping=4]="Stopping",s[s.Stopped=5]="Stopped",s))(h0||{});(e=>{function n(t){return t&&p.MessageReader.is(t.reader)&&p.MessageWriter.is(t.writer)}e.is=n})(xd||(xd={}));jC=class{constructor(e,t,i){this._consoleDebug=!1;this._features=[];this._dynamicFeatures=new Map;this._id=e,this._name=t,i.outputChannel?this._outputChannel=i.outputChannel:this._outputChannel=void 0,this._clientOptions=this.resolveClientOptions(i),this.$state=0,this._connection=void 0,this._initializeResult=void 0,this._listeners=[],this._diagnostics=void 0,this._notificationHandlers=new Map,this._pendingNotificationHandlers=new Map,this._notificationDisposables=new Map,this._requestHandlers=new Map,this._pendingRequestHandlers=new Map,this._requestDisposables=new Map,this._progressHandlers=new Map,this._pendingProgressHandlers=new Map,this._progressDisposables=new Map,this._ignoredRegistrations=new Set,this._onStop=void 0,this._stateChangeEmitter=new p.Emitter,this._trace=p.Trace.Off,this._tracer={log:(r,o)=>{$e(r)?this.logTrace(r,o):this.logObjectTrace(r)}},this._syncedDocuments=new Map,this.registerBuiltinFeatures()}switchConsole(){this._consoleDebug=!this._consoleDebug,this._consoleDebug||this.enableVerboseTrace()}resolveClientOptions(e){var u;let t={isTrusted:!1,supportHtml:!1};e.markdown!=null&&(t.isTrusted=e.markdown.isTrusted===!0,t.supportHtml=e.markdown.supportHtml===!0);let i=e.disableSnippetCompletion,r=e.disableMarkdown;r===void 0&&(r=y.initialConfiguration.get("coc.preferences.enableMarkdown")===!1);let o=y.getConfiguration("pullDiagnostic",e.workspaceFolder),s=e.diagnosticPullOptions??{};s.onChange===void 0&&(s.onChange=o.get("onChange")),s.onSave===void 0&&(s.onSave=o.get("onSave")),s.workspace===void 0&&(s.workspace=o.get("workspace")),s.ignored=o.get("ignored",[]).concat(s.ignored??[]);let a=e.disabledFeatures??[];for(let c of["disableCompletion","disableWorkspaceFolders","disableDiagnostics"])if(typeof e[c]=="boolean"){let d=` +`+Error().stack.split(` +`).slice(2,4).join(` +`);if(d0.warn(`${c} in the client options is deprecated. use disabledFeatures instead.`,d),e[c]===!0){let h=c.slice(7);a.push(h[0].toLowerCase()+h.slice(1))}}let l=e.separateDiagnostics;return e.separateDiagnostics===void 0&&(l=y.getConfiguration("diagnostic",e.workspaceFolder).get("separateRelatedInformationAsDiagnostics")),{disabledFeatures:a,disableMarkdown:r,disableSnippetCompletion:i,separateDiagnostics:l,diagnosticPullOptions:s,rootPatterns:e.rootPatterns??[],requireRootPattern:e.requireRootPattern,disableDynamicRegister:e.disableDynamicRegister,formatterPriority:e.formatterPriority??0,ignoredRootPaths:e.ignoredRootPaths??[],documentSelector:e.documentSelector??[],synchronize:e.synchronize??{},diagnosticCollectionName:e.diagnosticCollectionName,outputChannelName:e.outputChannelName??this._id,revealOutputChannelOn:e.revealOutputChannelOn??4,stdioEncoding:e.stdioEncoding??"utf8",initializationOptions:e.initializationOptions,initializationFailedHandler:e.initializationFailedHandler,progressOnInitialization:e.progressOnInitialization===!0,errorHandler:e.errorHandler??this.createDefaultErrorHandler((u=e.connectionOptions)==null?void 0:u.maxRestartCount),middleware:e.middleware??{},workspaceFolder:e.workspaceFolder,connectionOptions:e.connectionOptions,markdown:t}}get supportedMarkupKind(){return this.clientOptions.disableMarkdown?[fr.PlainText]:[fr.Markdown,fr.PlainText]}get state(){return this.getPublicState()}get $state(){return this._state}set $state(e){let t=this.getPublicState();this._state=e;let i=this.getPublicState();i!==t&&this._stateChangeEmitter.fire({oldState:t,newState:i})}get id(){return this._id}get name(){return this._name}get middleware(){return this._clientOptions.middleware}getPublicState(){return this.$state===3?2:this.$state===1?3:1}get initializeResult(){return this._initializeResult}async sendRequest(e,...t){this.checkState();try{return await(await this.$start()).sendRequest(e,...t)}catch(i){throw this.error(`Sending request ${Ps(e)} failed.`,i),i}}onRequest(e,t){let i=Ps(e);this._requestHandlers.set(i,t);let r=this.activeConnection(),o;return r!==void 0?(this._requestDisposables.set(i,r.onRequest(e,t)),o={dispose:()=>{let s=this._requestDisposables.get(i);s!==void 0&&(s.dispose(),this._requestDisposables.delete(i))}}):(this._pendingRequestHandlers.set(i,t),o={dispose:()=>{this._pendingRequestHandlers.delete(i);let s=this._requestDisposables.get(i);s!==void 0&&(s.dispose(),this._requestDisposables.delete(i))}}),{dispose:()=>{this._requestHandlers.delete(i),o.dispose()}}}async sendNotification(e,t){if(!(this.$state===2||this.$state===4||this.$state===5))try{return await(await this.$start()).sendNotification(e,t)}catch(i){throw this.error(`Sending notification ${Ps(e)} failed.`,i),i}}onNotification(e,t){let i=Ps(e);this._notificationHandlers.set(i,t);let r=this.activeConnection(),o;return r!==void 0?(this._notificationDisposables.set(i,r.onNotification(e,t)),o={dispose:()=>{let s=this._notificationDisposables.get(i);s!==void 0&&(s.dispose(),this._notificationDisposables.delete(i))}}):(this._pendingNotificationHandlers.set(i,t),o={dispose:()=>{this._pendingNotificationHandlers.delete(i);let s=this._notificationDisposables.get(i);s!==void 0&&(s.dispose(),this._notificationDisposables.delete(i))}}),{dispose:()=>{this._notificationHandlers.delete(i),o.dispose()}}}onProgress(e,t,i){this._progressHandlers.set(t,{type:e,handler:i});let r=this.activeConnection(),o,s=this._clientOptions.middleware.handleWorkDoneProgress,a=p.WorkDoneProgress.is(e)&&s!==void 0?l=>{s(t,l,()=>i(l))}:i;return r!==void 0?(this._progressDisposables.set(t,r.onProgress(e,t,a)),o={dispose:()=>{let l=this._progressDisposables.get(t);l!==void 0&&(l.dispose(),this._progressDisposables.delete(t))}}):(this._pendingProgressHandlers.set(t,{type:e,handler:i}),o={dispose:()=>{this._pendingProgressHandlers.delete(t);let l=this._progressDisposables.get(t);l!==void 0&&(l.dispose(),this._progressDisposables.delete(t))}}),{dispose:()=>{this._progressHandlers.delete(t),o.dispose()}}}async sendProgress(e,t,i){this.checkState();try{await(await this.$start()).sendProgress(e,t,i)}catch(r){throw this.error(`Sending progress for token ${t} failed.`,r),r}}get configuredSection(){var t;let e=(t=this._clientOptions.synchronize)==null?void 0:t.configurationSection;return typeof e=="string"&&e.startsWith("languageserver.")?e:void 0}get clientOptions(){return this._clientOptions}get onDidChangeState(){return this._stateChangeEmitter.event}get outputChannel(){if(!this._outputChannel){let{outputChannelName:e}=this._clientOptions;this._outputChannel=P.createOutputChannel(Ie(e,this._name))}return this._outputChannel}get diagnostics(){return this._diagnostics}createDefaultErrorHandler(e){return new RC(this._id,e??4)}set trace(e){this._trace=e;let t=this.activeConnection();t!==void 0&&t.trace(this._trace,this._tracer,{sendNotification:!1,traceFormat:this._traceFormat})}logObjectTrace(e){this.outputChannel.append(h4(e)),this.traceData(e)}traceData(e,t=!1){this.outputChannel.appendLine(sm(e)),this._consoleDebug&&(t?console.error(w4+sm(e)+x4):console.log(g4(e)))}consoleMessage(e,t,i=!1){if(this._consoleDebug){let r=e+" "+t;i?console.error(w4+r+x4):console.log(r)}}info(e,t,i=!0){let r=`[Info - ${au()}]`;this.outputChannel.appendLine(`${r} ${e}`),this.consoleMessage(r,e),t!=null&&this.traceData(t),i&&this._clientOptions.revealOutputChannelOn<=1&&this.showNotificationMessage(p.MessageType.Info,e)}warn(e,t,i=!0){let r=`[Warn - ${au()}]`;this.outputChannel.appendLine(`${r} ${e}`),this.consoleMessage(r,e),t!=null&&this.traceData(t),i&&this._clientOptions.revealOutputChannelOn<=2&&this.showNotificationMessage(p.MessageType.Warning,e)}error(e,t,i=!0){let r=`[Error - ${au()}]`;this.outputChannel.appendLine(`${r} ${e}`),this.consoleMessage(r,e,!0),t!=null&&this.traceData(t,!0),(i==="force"||i&&this._clientOptions.revealOutputChannelOn<=3)&&this.showNotificationMessage(p.MessageType.Error,e)}logTrace(e,t){let i=`[Trace - ${au()}]`;this.outputChannel.appendLine(`${i} ${e}`),this.consoleMessage(i,e),t!=null&&this.traceData(t)}showNotificationMessage(e,t){(e===p.MessageType.Error?P.showErrorMessage.bind(P):e===p.MessageType.Warning?P.showWarningMessage.bind(P):P.showInformationMessage.bind(P))(t)}needsStart(){return this.$state===0||this.$state===4||this.$state===5}needsStop(){return this.$state===1||this.$state===3}activeConnection(){return this.$state===3&&this._connection!==void 0?this._connection:void 0}get hasPendingResponse(){var e;return(e=this._connection)==null?void 0:e.hasPendingResponse()}onReady(){return this._onStart?this._onStart:new Promise(e=>{let t=this.onDidChangeState(i=>{i.newState===2&&(t.dispose(),e())})})}get started(){return this.$state!=0}isRunning(){return this.$state===3}async _start(){if(this._disposed==="disposing"||this._disposed==="disposed")throw new Error("Client got disposed and can't be restarted.");if(this.$state===4)throw new Error("Client is currently stopping. Can only restart a full stopped client");if(this._onStart!==void 0)return this._onStart;this._rootPath=this.resolveRootPath();let[e,t,i]=this.createOnStartPromise();if(this._onStart=e,this._diagnostics===void 0){let r=this._clientOptions,o=r.diagnosticCollectionName?r.diagnosticCollectionName:this._id;r.disabledFeatures.includes("diagnostics")||(this._diagnostics=I.createDiagnosticCollection(o))}for(let[r,o]of this._notificationHandlers)this._pendingNotificationHandlers.has(r)||this._pendingNotificationHandlers.set(r,o);for(let[r,o]of this._requestHandlers)this._pendingRequestHandlers.has(r)||this._pendingRequestHandlers.set(r,o);for(let[r,o]of this._progressHandlers)this._pendingProgressHandlers.has(r)||this._pendingProgressHandlers.set(r,o);this.$state=1;try{let r=await this.createConnection();this.handleConnectionEvents(r),r.listen(),await this.initialize(r),t()}catch(r){this.$state=2,this.error(`${this._name} client: couldn't create connection to server.`,r,"force"),i(r)}return this._onStart}start(){let e=this._start();return e.dispose=()=>{this.needsStop()&&this.stop()},e}async $start(){if(this.$state===2)throw new Error("Previous start failed. Can't restart server.");await this._start();let e=this.activeConnection();if(e===void 0)throw new Error("Starting server failed");return e}handleConnectionEvents(e){e.onNotification(p.LogMessageNotification.type,t=>{switch(t.type){case p.MessageType.Error:this.error(t.message);break;case p.MessageType.Warning:this.warn(t.message);break;case p.MessageType.Info:this.info(t.message);break;default:this.outputChannel.appendLine(t.message)}}),e.onNotification(p.ShowMessageNotification.type,t=>{switch(t.type){case p.MessageType.Error:P.showErrorMessage(t.message);break;case p.MessageType.Warning:P.showWarningMessage(t.message);break;case p.MessageType.Info:P.showInformationMessage(t.message);break;default:P.showInformationMessage(t.message)}}),e.onRequest(p.ShowMessageRequest.type,t=>{let i;switch(t.type){case p.MessageType.Error:i=P.showErrorMessage.bind(P);break;case p.MessageType.Warning:i=P.showWarningMessage.bind(P);break;case p.MessageType.Info:i=P.showInformationMessage.bind(P);break;default:i=P.showInformationMessage.bind(P)}let r=le(t.actions);return i(t.message,...r).then(o=>o??null)}),e.onRequest(p.ShowDocumentRequest.type,async t=>{var o;let i=async s=>{try{if(s.external===!0||/^https?:\/\//.test(s.uri))return await y.openResource(s.uri),{success:!0};{let{selection:a,takeFocus:l}=s;return l===!1?await y.loadFile(s.uri):(await y.jumpTo(s.uri,a==null?void 0:a.start),a&&Ge(a.start,a.end)!=0&&await P.selectRange(a)),{success:!0}}}catch{return{success:!1}}},r=(o=this._clientOptions.middleware.window)==null?void 0:o.showDocument;return r!==void 0?r(t,i):i(t)})}createOnStartPromise(){let e,t;return[new Promise((r,o)=>{e=r,t=o}),e,t]}resolveRootPath(){if(this._clientOptions.workspaceFolder)return O.parse(this._clientOptions.workspaceFolder.uri).fsPath;let{ignoredRootPaths:e,rootPatterns:t,requireRootPattern:i}=this._clientOptions,r;re(t)||(r=y.documentsManager.resolveRoot(t,i));let o=r||y.rootPath;return ai(o,Pt.homedir())||e.some(s=>ai(o,s))?(this.warn(`Ignored rootPath ${o} of client "${this._id}"`),null):o}initialize(e){let{initializationOptions:t,workspaceFolder:i,progressOnInitialization:r}=this._clientOptions;this.refreshTrace(e,!1);let o=this._rootPath,s={processId:process.pid,rootPath:o||null,rootUri:o?yd(O.file(o)):null,capabilities:this.computeClientCapabilities(),initializationOptions:tt(t)?t():t,trace:p.Trace.toString(this._trace),workspaceFolders:i?[i]:null,locale:d4(),clientInfo:{name:"coc.nvim",version:y.version}};if(this.fillInitializeParams(s),r){let a=He();s.workDoneToken=a,e.id=this._id;let l=new wd(e,a);return l.begin({title:`Initializing ${this.id}`,kind:"begin"}),this.doInitialize(e,s).then(u=>(l.done(),u),u=>(l.done(),Promise.reject(u)))}else return this.doInitialize(e,s)}async doInitialize(e,t){try{let i=await e.initialize(t);if(i.capabilities.positionEncoding!==void 0&&i.capabilities.positionEncoding!==p.PositionEncodingKind.UTF16)throw await e.shutdown(),await e.exit(),e.end(),e.dispose(),new Error(`Unsupported position encoding (${i.capabilities.positionEncoding}) received from server ${this.name}`);this._initializeResult=i,this.$state=3;let r;$t(i.capabilities.textDocumentSync)?i.capabilities.textDocumentSync===p.TextDocumentSyncKind.None?r={openClose:!1,change:p.TextDocumentSyncKind.None,save:void 0}:r={openClose:!0,change:i.capabilities.textDocumentSync,save:{includeText:!1}}:i.capabilities.textDocumentSync!==void 0&&i.capabilities.textDocumentSync!==null&&(r=i.capabilities.textDocumentSync),this._capabilities=Object.assign({},i.capabilities,{resolvedTextDocumentSync:r}),e.onNotification(p.PublishDiagnosticsNotification.type,o=>this.handleDiagnostics(o)),e.onRequest(p.RegistrationRequest.type,o=>this.handleRegistrationRequest(o)),e.onRequest("client/registerFeature",o=>this.handleRegistrationRequest(o)),e.onRequest(p.UnregistrationRequest.type,o=>this.handleUnregistrationRequest(o)),e.onRequest("client/unregisterFeature",o=>this.handleUnregistrationRequest(o)),e.onRequest(p.ApplyWorkspaceEditRequest.type,o=>this.handleApplyWorkspaceEdit(o));for(let[o,s]of this._pendingNotificationHandlers)this._notificationDisposables.set(o,e.onNotification(o,s));this._pendingNotificationHandlers.clear();for(let[o,s]of this._pendingRequestHandlers)this._requestDisposables.set(o,e.onRequest(o,s));this._pendingRequestHandlers.clear();for(let[o,s]of this._pendingProgressHandlers)this._progressDisposables.set(o,e.onProgress(s.type,o,s.handler));return this._pendingProgressHandlers.clear(),await e.sendNotification(p.InitializedNotification.type,{}),this.hookConfigurationChanged(e),this.initializeFeatures(e),i}catch(i){let r=o=>{o?this.initialize(e).catch(()=>{}):this.stop().catch(()=>{})};throw this._clientOptions.initializationFailedHandler?r(this._clientOptions.initializationFailedHandler(i)):i instanceof p.ResponseError&&i.data&&i.data.retry?(this._connection&&(this._connection.end(),this._connection.dispose(),this._connection=null),P.showErrorMessage(i.message,{title:"Retry",id:"retry"}).then(o=>{r(o&&o.id==="retry")})):(P.showErrorMessage(oe(i.message)),this.error("Server initialization failed.",i),d0.error(`Server ${this.id} initialization failed.`,i),r(!1)),i}}stop(e=2e3){return this.shutdown("stop",e)}async shutdown(e,t){if(this.$state===5||this.$state===0)return;if(this.$state===4)return this._onStop;let i=this.activeConnection();if(i===void 0||this.$state!==3&&this.$state!==1)throw new Error(`Client is not running and can't be stopped. It's current state is: ${this.$state}`);this._initializeResult=void 0,this.$state=4,this.cleanUp(e);let r,o=new Promise(a=>{r=setTimeout(a,t)}),s=(async a=>(await a.shutdown(),await a.exit(),a))(i);return this._onStop=Promise.race([o,s]).then(a=>{if(r&&clearTimeout(r),a!==void 0)a.end(),a.dispose();else throw this.error("Stopping server timed out",void 0),new Error("Stopping the server timed out")},a=>{throw this.error("Stopping server failed",a),a}).finally(()=>{this.$state=5,e==="stop"&&this.cleanUpChannel(),this._onStart=void 0,this._onStop=void 0,this._connection=void 0,this._ignoredRegistrations.clear()})}dispose(e=2e3){if(!this._disposed)try{return this._disposed="disposing",this.needsStop()?this.stop(e):void 0}finally{this._disposed="disposed"}}cleanUp(e){this._listeners&&(this._listeners.forEach(t=>t.dispose()),this._listeners=[]),this._syncedDocuments&&this._syncedDocuments.clear();for(let t of this._features.values())typeof t.dispose=="function"&&t.dispose();e==="stop"&&this._diagnostics&&(this._diagnostics.dispose(),this._diagnostics=void 0)}cleanUpChannel(){this._outputChannel&&(this._outputChannel.dispose(),this._outputChannel=void 0)}async forceDocumentSync(){let e=Array.from(this._syncedDocuments.values());await Promise.all(e.map(t=>{let i=y.getDocument(t.uri);return i?i.synchronize():null}))}handleDiagnostics(e){let{uri:t,diagnostics:i,version:r}=e;if($t(r)&&!y.hasDocument(t,r))return;let o=this.clientOptions.middleware.handleDiagnostics;o?o(t,i,(s,a)=>this.setDiagnostics(s,a)):this.setDiagnostics(t,i)}async createConnection(){let e=(r,o,s)=>{this.handleConnectionError(r,o,s)},t=()=>{this.handleConnectionClosed()},i=await this.createMessageTransports(Ie(this._clientOptions.stdioEncoding,"utf8"));return this._connection=_fe(i.reader,i.writer,e,t,this._clientOptions.connectionOptions),this._connection}handleConnectionClosed(){if(this.$state===5){d0.debug(`client ${this._id} normal closed`);return}try{this._connection&&this._connection.dispose()}catch{}let e=1;if(this.$state!==4&&this._clientOptions.errorHandler)try{e=this._clientOptions.errorHandler.closed()}catch{}this._connection=void 0,e===1?(this.error("Connection to server got closed. Server will not be restarted.",void 0,"force"),this.cleanUp("stop"),this.$state===1?this.$state=2:this.$state=5,this._onStop=Promise.resolve(),this._onStart=void 0):e===2&&(this.info("Connection to server got closed. Server will restart."),this.cleanUp("restart"),this.$state=0,this._onStop=Promise.resolve(),this._onStart=void 0,this.start().catch(this.error.bind(this,"Restarting server failed")))}checkState(){if(this.$state===2||this.$state===4||this.$state===5)throw new p.ResponseError(p.ErrorCodes.ConnectionInactive,"Client is not running")}handleConnectionError(e,t,i){this._clientOptions.errorHandler.error(e,t,i)===2&&(this.error(`Client ${this._name}: connection to server is erroring. Shutting down server.`,void 0,"force"),this.stop().catch(this.error.bind(this,"Stopping server failed")))}hookConfigurationChanged(e){y.onDidChangeConfiguration(t=>{t.affectsConfiguration(this._id)&&this.refreshTrace(e,!0)},null,this._listeners)}refreshTrace(e,t){let i=y.getConfiguration(this._id,this.clientOptions.workspaceFolder),r=p.Trace.Off,o=p.TraceFormat.Text;if(i){let s=i.get("trace.server","off");typeof s=="string"?r=p.Trace.fromString(s):(r=p.Trace.fromString(i.get("trace.server.verbosity","off")),o=p.TraceFormat.fromString(i.get("trace.server.format","text")))}t&&this._trace==r&&this._traceFormat==o||(this._trace=r,this._traceFormat=o,e.trace(this._trace,this._tracer,{sendNotification:t,traceFormat:this._traceFormat}).catch(this.error.bind(this,"Updating trace failed with error")))}enableVerboseTrace(){this._trace=p.Trace.Verbose,this._traceFormat=p.TraceFormat.Text,this._connection.trace(this._trace,this._tracer,{sendNotification:!0,traceFormat:this._traceFormat}).catch(this.error.bind(this,"Updating trace failed with error"))}registerFeatures(e){for(let t of e)this.registerFeature(t,"")}registerFeature(e,t){let{disabledFeatures:i}=this._clientOptions;if(!(i.length>0&&i.includes(t))&&(this._features.push(e),Ox.is(e))){let r=e.registrationType;this._dynamicFeatures.set(r.method,e)}}getStaticFeature(e){return this._features.find(t=>jx.is(t)&&t.method==e)}getFeature(e){return this._dynamicFeatures.get(e)}registerBuiltinFeatures(){this.registerFeature(new su(this),"configuration"),this.registerFeature(new wC(this,this._syncedDocuments),"document"),this.registerFeature(new CC(this),"document"),this.registerFeature(new xC(this,this._syncedDocuments),"document"),this.registerFeature(new SC(this),"willSave"),this.registerFeature(new DC(this),"willSaveWaitUntil"),this.registerFeature(new TC(this),"didSave"),this.registerFeature(new rC(this),"fileSystemWatcher"),this.registerFeature(new Wx(this),"completion"),this.registerFeature(new uC(this),"hover"),this.registerFeature(new vC(this),"signatureHelp"),this.registerFeature(new fC(this),"references"),this.registerFeature(new Jx(this),"definition"),this.registerFeature(new Ux(this),"documentHighlight"),this.registerFeature(new Gx(this),"documentSymbol"),this.registerFeature(new Hx(this),"codeAction"),this.registerFeature(new Bx(this),"codeLens"),this.registerFeature(new sC(this),"documentFormatting"),this.registerFeature(new aC(this),"documentRangeFormatting"),this.registerFeature(new lC(this),"documentOnTypeFormatting"),this.registerFeature(new mC(this),"rename"),this.registerFeature(new Xx(this),"documentLink"),this.registerFeature(new zx(this),"executeCommand"),this.registerFeature(new Yx(this),"pullConfiguration"),this.registerFeature(new kC(this),"typeDefinition"),this.registerFeature(new cC(this),"implementation"),this.registerFeature(new Zx(this),"declaration"),this.registerFeature(new qx(this),"colorProvider"),this.registerFeature(new oC(this),"foldingRange"),this.registerFeature(new bC(this),"selectionRange"),this.registerFeature(new Nx(this),"callHierarchy"),this.registerFeature(new pC(this),"progress"),this.registerFeature(new gC(this),"linkedEditing"),this.registerFeature(new Kx(this),"fileEvents"),this.registerFeature(new Qx(this),"fileEvents"),this.registerFeature(new Vx(this),"fileEvents"),this.registerFeature(new eC(this),"fileEvents"),this.registerFeature(new tC(this),"fileEvents"),this.registerFeature(new iC(this),"fileEvents"),this.registerFeature(new yC(this),"semanticTokens"),this.registerFeature(new dC(this),"inlayHint"),this.registerFeature(new hC(this),"inlineValue"),this.registerFeature(new $x(this),"pullDiagnostic"),this.registerFeature(new PC(this),"typeHierarchy"),this.registerFeature(new MC(this),"workspaceSymbol"),this.clientOptions.workspaceFolder===void 0&&this.registerFeature(new FC(this),"workspaceFolders")}registerProposedFeatures(){this.registerFeatures(Efe.createAll(this))}fillInitializeParams(e){for(let t of this._features)tt(t.fillInitializeParams)&&t.fillInitializeParams(e)}computeClientCapabilities(){let e={};q(e,"workspace").applyEdit=!0;let t=q(q(e,"workspace"),"workspaceEdit");t.documentChanges=!0,t.resourceOperations=[p.ResourceOperationKind.Create,p.ResourceOperationKind.Rename,p.ResourceOperationKind.Delete],t.failureHandling=p.FailureHandlingKind.Undo,t.normalizesLineEndings=!0,t.changeAnnotationSupport={groupsOnLabel:!1};let i=q(q(e,"textDocument"),"publishDiagnostics");i.relatedInformation=!0,i.versionSupport=!0,i.tagSupport={valueSet:[Ji.Unnecessary,Ji.Deprecated]},i.codeDescriptionSupport=!0,i.dataSupport=!0;let r=q(e,"window"),o=q(r,"showMessage");o.messageActionItem={additionalPropertiesSupport:!0};let s=q(r,"showDocument");s.support=!0;let a=q(e,"general");a.regularExpressions={engine:"ECMAScript",version:"ES2020"},a.markdown={parser:"marked",version:"4.0.10"},a.positionEncodings=["utf-16"],a.staleRequestSupport={cancel:!0,retryOnContentModified:Array.from(jC.RequestsToCancelOnContentModified)};for(let l of this._features)l.fillClientCapabilities(e);return e}initializeFeatures(e){let t=this._clientOptions.documentSelector;for(let i of this._features)tt(i.preInitialize)&&i.preInitialize(this._capabilities,t);for(let i of this._features)i.initialize(this._capabilities,t)}handleRegistrationRequest(e){if(!this.clientOptions.disableDynamicRegister){if(!this.isRunning()){for(let t of e.registrations)this._ignoredRegistrations.add(t.id);return}for(let t of e.registrations){let i=this._dynamicFeatures.get(t.method);if(!i){this.error(`No feature implementation for ${t.method} found. Registration failed.`);return}let r=t.registerOptions??{};r.documentSelector=r.documentSelector??this._clientOptions.documentSelector;let o={id:t.id,registerOptions:r};i.register(o)}}}handleUnregistrationRequest(e){return new Promise(t=>{for(let i of e.unregisterations){if(this._ignoredRegistrations.has(i.id))continue;let r=this._dynamicFeatures.get(i.method);r&&r.unregister(i.id)}t()})}setDiagnostics(e,t){var r;if(!this._diagnostics)return;if(this.clientOptions.separateDiagnostics&&t.length>0){let o=new Map;o.set(e,t);for(let s of t){if((r=s.relatedInformation)!=null&&r.length){let a=`${s.message} Related diagnostics: -`; - for (const info of diagnostic.relatedInformation) { - const basename = import_path17.default.basename(URI.parse(info.location.uri).fsPath); - const ln = info.location.range.start.line; - message = `${message} -${basename}(line ${ln + 1}): ${info.message}`; - const diags = entries.get(info.location.uri) || []; - diags.push(import_vscode_languageserver_protocol49.Diagnostic.create(info.location.range, info.message, import_vscode_languageserver_protocol49.DiagnosticSeverity.Hint, diagnostic.code, diagnostic.source)); - entries.set(info.location.uri, diags); - } - diagnostic.message = message; - } - this._diagnostics.set(Array.from(entries)); - } - } else { - this._diagnostics.set(uri, diagnostics); - } - } - createConnection() { - let errorHandler = (error, message, count) => { - logger47.error("connection error:", error, message); - this.handleConnectionError(error, message, count); - }; - let closeHandler = () => { - this.handleConnectionClosed(); - }; - return this.createMessageTransports(this._clientOptions.stdioEncoding || "utf8").then((transports) => { - return createConnection(transports.reader, transports.writer, errorHandler, closeHandler, this._clientOptions.connectionOptions); - }); - } - handleConnectionClosed() { - if (this.state === 5) { - return; - } - try { - if (this._resolvedConnection) { - this._resolvedConnection.dispose(); - } - } catch (error) { - } - let action = 1; - if (this.state !== 4) { - try { - action = this._clientOptions.errorHandler.closed(); - } catch (error) { - } - } - this._connectionPromise = void 0; - this._resolvedConnection = void 0; - if (action === 1) { - this.error("Connection to server got closed. Server will not be restarted."); - if (this.state === 1) { - this._onReadyCallbacks.reject(new Error(`Connection to server got closed. Server will not be restarted.`)); - this.state = 2; - } else { - this.state = 5; - } - this.cleanUp(false, true); - } else if (action === 2) { - this.info("Connection to server got closed. Server will restart."); - this.cleanUp(false, true); - this.state = 0; - this.start(); - } - } - restart() { - this.cleanUp(true, false); - this.start(); - } - handleConnectionError(error, message, count) { - let action = this._clientOptions.errorHandler.error(error, message, count); - if (action === 2) { - this.error("Connection to server is erroring. Shutting down server."); - this.stop(); - } - } - hookConfigurationChanged(connection) { - workspace_default.onDidChangeConfiguration(() => { - this.refreshTrace(connection, true); - }); - } - refreshTrace(connection, sendNotification = false) { - let config = workspace_default.getConfiguration(this._id); - let trace = import_vscode_languageserver_protocol49.Trace.Off; - let traceFormat = import_vscode_languageserver_protocol49.TraceFormat.Text; - if (config) { - const traceConfig = config.get("trace.server", "off"); - if (typeof traceConfig === "string") { - trace = import_vscode_languageserver_protocol49.Trace.fromString(traceConfig); - } else { - trace = import_vscode_languageserver_protocol49.Trace.fromString(config.get("trace.server.verbosity", "off")); - traceFormat = import_vscode_languageserver_protocol49.TraceFormat.fromString(config.get("trace.server.format", "text")); - } - } - this._trace = trace; - this._traceFormat = traceFormat; - connection.trace(this._trace, this._tracer, { - sendNotification, - traceFormat: this._traceFormat - }); - } - hookFileEvents(_connection) { - let fileEvents = this._clientOptions.synchronize.fileEvents; - if (!fileEvents) - return; - let watchers; - if (Array.isArray(fileEvents)) { - watchers = fileEvents; - } else { - watchers = [fileEvents]; - } - if (!watchers) { - return; - } - this._dynamicFeatures.get(import_vscode_languageserver_protocol49.DidChangeWatchedFilesNotification.type.method).registerRaw(generateUuid(), watchers); - } - registerFeatures(features) { - for (let feature of features) { - this.registerFeature(feature); - } - } - registerFeature(feature) { - this._features.push(feature); - if (DynamicFeature.is(feature)) { - const registrationType = feature.registrationType; - this._dynamicFeatures.set(registrationType.method, feature); - } - } - getFeature(request2) { - return this._dynamicFeatures.get(request2); - } - registerBuiltinFeatures() { - this.registerFeature(new ConfigurationFeature(this)); - this.registerFeature(new DidOpenTextDocumentFeature(this, this._syncedDocuments)); - this.registerFeature(new DidChangeTextDocumentFeature(this)); - this.registerFeature(new WillSaveFeature(this)); - this.registerFeature(new WillSaveWaitUntilFeature(this)); - this.registerFeature(new DidSaveTextDocumentFeature(this)); - this.registerFeature(new DidCloseTextDocumentFeature(this, this._syncedDocuments)); - this.registerFeature(new FileSystemWatcherFeature(this, (event) => this.notifyFileEvent(event))); - if (!this._clientOptions.disableCompletion) { - this.registerFeature(new CompletionItemFeature(this)); - } - this.registerFeature(new HoverFeature(this)); - this.registerFeature(new SignatureHelpFeature(this)); - this.registerFeature(new DefinitionFeature(this)); - this.registerFeature(new ReferencesFeature(this)); - this.registerFeature(new DocumentHighlightFeature(this)); - this.registerFeature(new DocumentSymbolFeature(this)); - this.registerFeature(new WorkspaceSymbolFeature(this)); - this.registerFeature(new CodeActionFeature(this)); - this.registerFeature(new CodeLensFeature(this)); - this.registerFeature(new DocumentFormattingFeature(this)); - this.registerFeature(new DocumentRangeFormattingFeature(this)); - this.registerFeature(new DocumentOnTypeFormattingFeature(this)); - this.registerFeature(new RenameFeature(this)); - this.registerFeature(new DocumentLinkFeature(this)); - this.registerFeature(new ExecuteCommandFeature(this)); - } - fillInitializeParams(params) { - for (let feature of this._features) { - if (func(feature.fillInitializeParams)) { - feature.fillInitializeParams(params); - } - } - } - computeClientCapabilities() { - const result = {}; - ensure(result, "workspace").applyEdit = true; - const workspaceEdit = ensure(ensure(result, "workspace"), "workspaceEdit"); - workspaceEdit.documentChanges = true; - workspaceEdit.resourceOperations = [import_vscode_languageserver_protocol49.ResourceOperationKind.Create, import_vscode_languageserver_protocol49.ResourceOperationKind.Rename, import_vscode_languageserver_protocol49.ResourceOperationKind.Delete]; - workspaceEdit.failureHandling = import_vscode_languageserver_protocol49.FailureHandlingKind.TextOnlyTransactional; - const diagnostics = ensure(ensure(result, "textDocument"), "publishDiagnostics"); - diagnostics.relatedInformation = true; - diagnostics.versionSupport = false; - diagnostics.tagSupport = { valueSet: [import_vscode_languageserver_protocol49.DiagnosticTag.Unnecessary, import_vscode_languageserver_protocol49.DiagnosticTag.Deprecated] }; - const windowCapabilities = ensure(result, "window"); - const showMessage = ensure(windowCapabilities, "showMessage"); - showMessage.messageActionItem = { additionalPropertiesSupport: false }; - const showDocument = ensure(windowCapabilities, "showDocument"); - showDocument.support = false; - const generalCapabilities = ensure(result, "general"); - generalCapabilities.regularExpressions = { engine: "ECMAScript", version: "ES2020" }; - generalCapabilities.markdown = { parser: "marked", version: "1.1.0" }; - for (let feature of this._features) { - feature.fillClientCapabilities(result); - } - return result; - } - initializeFeatures(_connection) { - let documentSelector = this._clientOptions.documentSelector; - for (let feature of this._features) { - feature.initialize(this._capabilities, documentSelector); - } - } - handleRegistrationRequest(params) { - if (this.clientOptions.disableDynamicRegister) - return Promise.resolve(); - return new Promise((resolve3, reject) => { - for (const registration of params.registrations) { - const feature = this._dynamicFeatures.get(registration.method); - if (!feature) { - reject(new Error(`No feature implementation for ${registration.method} found. Registration failed.`)); - return; - } - const options = registration.registerOptions || {}; - options.documentSelector = options.documentSelector || this._clientOptions.documentSelector; - const data = { - id: registration.id, - registerOptions: options - }; - try { - feature.register(data); - } catch (err) { - reject(err); - return; - } - } - resolve3(); - }); - } - handleUnregistrationRequest(params) { - return new Promise((resolve3, reject) => { - for (let unregistration of params.unregisterations) { - const feature = this._dynamicFeatures.get(unregistration.method); - if (!feature) { - reject(new Error(`No feature implementation for ${unregistration.method} found. Unregistration failed.`)); - return; - } - feature.unregister(unregistration.id); - } - resolve3(); - }); - } - handleApplyWorkspaceEdit(params) { - let workspaceEdit = params.edit; - let openTextDocuments = new Map(); - workspace_default.textDocuments.forEach((document2) => openTextDocuments.set(document2.uri.toString(), document2)); - let versionMismatch = false; - if (workspaceEdit.documentChanges) { - for (const change of workspaceEdit.documentChanges) { - if (import_vscode_languageserver_protocol49.TextDocumentEdit.is(change) && change.textDocument.version && change.textDocument.version >= 0) { - let textDocument = openTextDocuments.get(change.textDocument.uri); - if (textDocument && textDocument.version !== change.textDocument.version) { - versionMismatch = true; - break; - } - } - } - } - if (versionMismatch) { - return Promise.resolve({ applied: false }); - } - return workspace_default.applyEdit(params.edit).then((value) => { - return { applied: value }; - }); - } - getLocale() { - const lang = process.env.LANG; - if (!lang) - return "en"; - return lang.split(".")[0]; - } - handleFailedRequest(type, token, error, defaultValue) { - if (error instanceof import_vscode_languageserver_protocol49.ResponseError) { - if (error.code === import_vscode_languageserver_protocol49.LSPErrorCodes.RequestCancelled) { - if (token !== void 0 && token.isCancellationRequested) { - return defaultValue; - } - } else if (error.code === import_vscode_languageserver_protocol49.LSPErrorCodes.ContentModified) { - return defaultValue; - } - } - this.error(`Request ${type.method} failed.`, error); - } - logFailedRequest(type, error) { - if (error instanceof import_vscode_languageserver_protocol49.ResponseError && error.code === import_vscode_languageserver_protocol49.LSPErrorCodes.RequestCancelled) { - return; - } - this.error(`Request ${type.method} failed.`, error); - } - }; - } -}); - -// src/language-client/colorProvider.ts -function ensure2(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -var import_vscode_languageserver_protocol50, ColorProviderFeature; -var init_colorProvider = __esm({ - "src/language-client/colorProvider.ts"() { - import_vscode_languageserver_protocol50 = __toModule(require_main2()); - init_languages(); - init_client(); - "use strict"; - ColorProviderFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol50.DocumentColorRequest.type); - } - fillClientCapabilities(capabilities) { - ensure2(ensure2(capabilities, "textDocument"), "colorProvider").dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - let [id, options] = this.getRegistration(documentSelector, capabilities.colorProvider); - if (!id || !options) { - return; - } - this.register({ id, registerOptions: options }); - } - registerLanguageProvider(options) { - const provider = { - provideColorPresentations: (color, context, token) => { - const client = this._client; - const provideColorPresentations = (color2, context2, token2) => { - const requestParams = { - color: color2, - textDocument: { uri: context2.document.uri }, - range: context2.range - }; - return client.sendRequest(import_vscode_languageserver_protocol50.ColorPresentationRequest.type, requestParams, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol50.ColorPresentationRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideColorPresentations ? middleware.provideColorPresentations(color, context, token, provideColorPresentations) : provideColorPresentations(color, context, token); - }, - provideDocumentColors: (document2, token) => { - const client = this._client; - const provideDocumentColors = (document3, token2) => { - const requestParams = { - textDocument: { uri: document3.uri } - }; - return client.sendRequest(import_vscode_languageserver_protocol50.DocumentColorRequest.type, requestParams, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol50.ColorPresentationRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideDocumentColors ? middleware.provideDocumentColors(document2, token, provideDocumentColors) : provideDocumentColors(document2, token); - } - }; - return [languages_default.registerDocumentColorProvider(options.documentSelector, provider), provider]; - } - }; - } -}); - -// src/language-client/configuration.ts -function toJSONObject(obj) { - if (obj) { - if (Array.isArray(obj)) { - return obj.map(toJSONObject); - } else if (typeof obj === "object") { - const res = Object.create(null); - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - res[key] = toJSONObject(obj[key]); - } - } - return res; - } - } - return obj; -} -var import_vscode_languageserver_protocol51, logger48, ConfigurationFeature2; -var init_configuration3 = __esm({ - "src/language-client/configuration.ts"() { - import_vscode_languageserver_protocol51 = __toModule(require_main2()); - init_workspace(); - logger48 = require_logger2()("languageclient-configuration"); - ConfigurationFeature2 = class { - constructor(_client) { - this._client = _client; - var _a2; - let section2 = (_a2 = this._client.clientOptions.synchronize) == null ? void 0 : _a2.configurationSection; - if (typeof section2 === "string" && section2.startsWith("languageserver.")) { - this.languageserverSection = section2; - } - } - fillClientCapabilities(capabilities) { - capabilities.workspace = capabilities.workspace || {}; - capabilities.workspace.configuration = true; - } - initialize() { - let client = this._client; - client.onRequest(import_vscode_languageserver_protocol51.ConfigurationRequest.type, (params, token) => { - let configuration = (params2) => { - let result = []; - for (let item of params2.items) { - result.push(this.getConfiguration(item.scopeUri, item.section)); - } - return result; - }; - let middleware = client.clientOptions.middleware.workspace; - return middleware && middleware.configuration ? middleware.configuration(params, token, configuration) : configuration(params, token); - }); - } - getConfiguration(resource, section2) { - let result = null; - if (section2) { - if (this.languageserverSection) { - section2 = `${this.languageserverSection}.${section2}`; - } - let index = section2.lastIndexOf("."); - if (index === -1) { - result = toJSONObject(workspace_default.getConfiguration(void 0, resource).get(section2)); - } else { - let config = workspace_default.getConfiguration(section2.substr(0, index), resource); - if (config) { - result = toJSONObject(config.get(section2.substr(index + 1))); - } - } - } else { - let config = workspace_default.getConfiguration(this.languageserverSection, resource); - result = {}; - for (let key of Object.keys(config)) { - if (config.has(key)) { - result[key] = toJSONObject(config.get(key)); - } - } - } - return result; - } - dispose() { - } - }; - } -}); - -// src/language-client/declaration.ts -function ensure3(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -var import_vscode_languageserver_protocol52, DeclarationFeature; -var init_declaration = __esm({ - "src/language-client/declaration.ts"() { - import_vscode_languageserver_protocol52 = __toModule(require_main2()); - init_languages(); - init_client(); - init_converter(); - "use strict"; - DeclarationFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol52.DeclarationRequest.type); - } - fillClientCapabilities(capabilities) { - let declarationSupport = ensure3(ensure3(capabilities, "textDocument"), "declaration"); - declarationSupport.dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - const [id, options] = this.getRegistration(documentSelector, capabilities.declarationProvider); - if (!id || !options) { - return; - } - this.register({ id, registerOptions: options }); - } - registerLanguageProvider(options) { - const provider = { - provideDeclaration: (document2, position, token) => { - const client = this._client; - const provideDeclaration = (document3, position2, token2) => client.sendRequest(import_vscode_languageserver_protocol52.DeclarationRequest.type, asTextDocumentPositionParams(document3, position2), token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol52.DeclarationRequest.type, token2, error, null); - }); - const middleware = client.clientOptions.middleware; - return middleware.provideDeclaration ? middleware.provideDeclaration(document2, position, token, provideDeclaration) : provideDeclaration(document2, position, token); - } - }; - return [languages_default.registerDeclarationProvider(options.documentSelector, provider), provider]; - } - }; - } -}); - -// src/language-client/foldingRange.ts -function ensure4(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -var import_vscode_languageserver_protocol53, FoldingRangeFeature; -var init_foldingRange = __esm({ - "src/language-client/foldingRange.ts"() { - import_vscode_languageserver_protocol53 = __toModule(require_main2()); - init_languages(); - init_client(); - "use strict"; - FoldingRangeFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol53.FoldingRangeRequest.type); - } - fillClientCapabilities(capabilities) { - let capability = ensure4(ensure4(capabilities, "textDocument"), "foldingRange"); - capability.dynamicRegistration = true; - capability.rangeLimit = 5e3; - capability.lineFoldingOnly = true; - } - initialize(capabilities, documentSelector) { - const [id, options] = this.getRegistration(documentSelector, capabilities.foldingRangeProvider); - if (!id || !options) { - return; - } - this.register({ id, registerOptions: options }); - } - registerLanguageProvider(options) { - const provider = { - provideFoldingRanges: (document2, context, token) => { - const client = this._client; - const provideFoldingRanges = (document3, _, token2) => { - const requestParams = { - textDocument: { uri: document3.uri } - }; - return client.sendRequest(import_vscode_languageserver_protocol53.FoldingRangeRequest.type, requestParams, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol53.FoldingRangeRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideFoldingRanges ? middleware.provideFoldingRanges(document2, context, token, provideFoldingRanges) : provideFoldingRanges(document2, context, token); - } - }; - return [languages_default.registerFoldingRangeProvider(options.documentSelector, provider), provider]; - } - }; - } -}); - -// src/language-client/implementation.ts -function ensure5(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -var import_vscode_languageserver_protocol54, ImplementationFeature; -var init_implementation = __esm({ - "src/language-client/implementation.ts"() { - import_vscode_languageserver_protocol54 = __toModule(require_main2()); - init_languages(); - init_client(); - init_converter(); - ImplementationFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol54.ImplementationRequest.type); - } - fillClientCapabilities(capabilities) { - const implementationSupport = ensure5(ensure5(capabilities, "textDocument"), "implementation"); - implementationSupport.dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - const [id, options] = this.getRegistration(documentSelector, capabilities.implementationProvider); - if (!id || !options) { - return; - } - this.register({ id, registerOptions: options }); - } - registerLanguageProvider(options) { - const provider = { - provideImplementation: (document2, position, token) => { - const client = this._client; - const provideImplementation = (document3, position2, token2) => client.sendRequest(import_vscode_languageserver_protocol54.ImplementationRequest.type, asTextDocumentPositionParams(document3, position2), token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol54.ImplementationRequest.type, token2, error, null); - }); - const middleware = client.clientOptions.middleware; - return middleware.provideImplementation ? middleware.provideImplementation(document2, position, token, provideImplementation) : provideImplementation(document2, position, token); - } - }; - return [languages_default.registerImplementationProvider(options.documentSelector, provider), provider]; - } - }; - } -}); - -// src/language-client/progress.ts -function ensure6(target, key) { - if (target[key] === void 0) { - target[key] = Object.create(null); - } - return target[key]; -} -var import_vscode_languageserver_protocol55, ProgressFeature; -var init_progress2 = __esm({ - "src/language-client/progress.ts"() { - import_vscode_languageserver_protocol55 = __toModule(require_main2()); - init_progressPart(); - "use strict"; - ProgressFeature = class { - constructor(_client) { - this._client = _client; - this.activeParts = new Set(); - } - fillClientCapabilities(capabilities) { - ensure6(capabilities, "window").workDoneProgress = true; - } - initialize() { - let client = this._client; - const deleteHandler = (part) => { - this.activeParts.delete(part); - }; - const createHandler = (params) => { - this.activeParts.add(new ProgressPart(this._client, params.token, deleteHandler)); - }; - client.onRequest(import_vscode_languageserver_protocol55.WorkDoneProgressCreateRequest.type, createHandler); - } - dispose() { - for (const part of this.activeParts) { - part.done(); - } - this.activeParts.clear(); - } - }; - } -}); - -// src/language-client/typeDefinition.ts -function ensure7(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -var import_vscode_languageserver_protocol56, TypeDefinitionFeature; -var init_typeDefinition = __esm({ - "src/language-client/typeDefinition.ts"() { - import_vscode_languageserver_protocol56 = __toModule(require_main2()); - init_languages(); - init_client(); - init_converter(); - TypeDefinitionFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol56.TypeDefinitionRequest.type); - } - fillClientCapabilities(capabilities) { - const typeDefinitionSupport = ensure7(ensure7(capabilities, "textDocument"), "typeDefinition"); - typeDefinitionSupport.dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - const [id, options] = this.getRegistration(documentSelector, capabilities.typeDefinitionProvider); - if (!id || !options) { - return; - } - this.register({ id, registerOptions: options }); - } - registerLanguageProvider(options) { - const provider = { - provideTypeDefinition: (document2, position, token) => { - const client = this._client; - const provideTypeDefinition = (document3, position2, token2) => client.sendRequest(import_vscode_languageserver_protocol56.TypeDefinitionRequest.type, asTextDocumentPositionParams(document3, position2), token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol56.TypeDefinitionRequest.type, token2, error, null); - }); - const middleware = client.clientOptions.middleware; - return middleware.provideTypeDefinition ? middleware.provideTypeDefinition(document2, position, token, provideTypeDefinition) : provideTypeDefinition(document2, position, token); - } - }; - return [languages_default.registerTypeDefinitionProvider(options.documentSelector, provider), provider]; - } - }; - } -}); - -// src/language-client/workspaceFolders.ts -function access(target, key) { - if (target === void 0) { - return void 0; - } - return target[key]; -} -function arrayDiff(left, right) { - return left.filter((element) => !right.includes(element)); -} -var import_vscode_languageserver_protocol57, import_os8, logger49, WorkspaceFoldersFeature; -var init_workspaceFolders = __esm({ - "src/language-client/workspaceFolders.ts"() { - import_vscode_languageserver_protocol57 = __toModule(require_main2()); - init_workspace(); - import_os8 = __toModule(require("os")); - init_uuid(); - init_esm2(); - "use strict"; - logger49 = require_logger2()("language-client-workspaceFolder"); - WorkspaceFoldersFeature = class { - constructor(_client) { - this._client = _client; - this._listeners = new Map(); - } - get registrationType() { - return import_vscode_languageserver_protocol57.DidChangeWorkspaceFoldersNotification.type; - } - getValidWorkspaceFolders() { - let { workspaceFolders } = workspace_default; - if (!workspaceFolders || workspaceFolders.length == 0) - return void 0; - let home = import_os8.default.homedir(); - let { ignoredRootPaths } = this._client.clientOptions; - if (!Array.isArray(ignoredRootPaths)) { - ignoredRootPaths = []; - } - let arr = workspaceFolders.filter((o) => { - let fsPath = URI.parse(o.uri).fsPath; - return fsPath != home && !ignoredRootPaths.includes(fsPath); - }); - return arr.length ? arr : void 0; - } - asProtocol(workspaceFolder) { - if (workspaceFolder === void 0) { - return null; - } - return { uri: workspaceFolder.uri, name: workspaceFolder.name }; - } - fillInitializeParams(params) { - const folders = this.getValidWorkspaceFolders(); - this._initialFolders = folders; - if (folders == null) { - params.workspaceFolders = null; - } else { - params.workspaceFolders = folders.map((folder) => this.asProtocol(folder)); - } - } - fillClientCapabilities(capabilities) { - capabilities.workspace = capabilities.workspace || {}; - capabilities.workspace.workspaceFolders = true; - } - initialize(capabilities) { - let client = this._client; - client.onRequest(import_vscode_languageserver_protocol57.WorkspaceFoldersRequest.type, (token) => { - let workspaceFolders = () => { - let folders = this.getValidWorkspaceFolders(); - if (folders === void 0) { - return null; - } - let result = folders.map((folder) => this.asProtocol(folder)); - return result; - }; - const middleware = client.clientOptions.middleware.workspace; - return middleware && middleware.workspaceFolders ? middleware.workspaceFolders(token, workspaceFolders) : workspaceFolders(token); - }); - const value = access(access(access(capabilities, "workspace"), "workspaceFolders"), "changeNotifications"); - let id; - if (typeof value === "string") { - id = value; - } else if (value === true) { - id = generateUuid(); - } - if (id) { - this.register({ - id, - registerOptions: void 0 - }); - } - } - doSendEvent(addedFolders, removedFolders) { - let params = { - event: { - added: addedFolders.map((folder) => this.asProtocol(folder)), - removed: removedFolders.map((folder) => this.asProtocol(folder)) - } - }; - this._client.sendNotification(import_vscode_languageserver_protocol57.DidChangeWorkspaceFoldersNotification.type, params); - } - sendInitialEvent(currentWorkspaceFolders) { - if (this._initialFolders && currentWorkspaceFolders) { - const removed = arrayDiff(this._initialFolders, currentWorkspaceFolders); - const added = arrayDiff(currentWorkspaceFolders, this._initialFolders); - if (added.length > 0 || removed.length > 0) { - this.doSendEvent(added, removed); - } - } else if (this._initialFolders) { - this.doSendEvent([], this._initialFolders); - } else if (currentWorkspaceFolders) { - this.doSendEvent(currentWorkspaceFolders, []); - } - } - register(data) { - let id = data.id; - let client = this._client; - let disposable = workspace_default.onDidChangeWorkspaceFolders((event) => { - let didChangeWorkspaceFolders = (event2) => { - this.doSendEvent(event2.added, event2.removed); - }; - let middleware = client.clientOptions.middleware.workspace; - middleware && middleware.didChangeWorkspaceFolders ? middleware.didChangeWorkspaceFolders(event, didChangeWorkspaceFolders) : didChangeWorkspaceFolders(event); - }); - this._listeners.set(id, disposable); - let workspaceFolders = this.getValidWorkspaceFolders(); - this.sendInitialEvent(workspaceFolders); - } - unregister(id) { - let disposable = this._listeners.get(id); - if (disposable === void 0) { - return; - } - this._listeners.delete(id); - disposable.dispose(); - } - dispose() { - for (let disposable of this._listeners.values()) { - disposable.dispose(); - } - this._listeners.clear(); - } - }; - } -}); - -// src/language-client/selectionRange.ts -function ensure8(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -var import_vscode_languageserver_protocol58, SelectionRangeFeature; -var init_selectionRange = __esm({ - "src/language-client/selectionRange.ts"() { - import_vscode_languageserver_protocol58 = __toModule(require_main2()); - init_languages(); - init_client(); - "use strict"; - SelectionRangeFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol58.SelectionRangeRequest.type); - } - fillClientCapabilities(capabilities) { - let capability = ensure8(ensure8(capabilities, "textDocument"), "selectionRange"); - capability.dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - let [id, options] = this.getRegistration(documentSelector, capabilities.selectionRangeProvider); - if (!id || !options) { - return; - } - this.register({ id, registerOptions: options }); - } - registerLanguageProvider(options) { - const provider = { - provideSelectionRanges: (document2, positions2, token) => { - const client = this._client; - const provideSelectionRanges = (document3, positions3, token2) => { - const requestParams = { - textDocument: { uri: document3.uri }, - positions: positions3 - }; - return client.sendRequest(import_vscode_languageserver_protocol58.SelectionRangeRequest.type, requestParams, token2).then((ranges) => ranges, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol58.SelectionRangeRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideSelectionRanges ? middleware.provideSelectionRanges(document2, positions2, token, provideSelectionRanges) : provideSelectionRanges(document2, positions2, token); - } - }; - return [languages_default.registerSelectionRangeProvider(options.documentSelector, provider), provider]; - } - }; - } -}); - -// src/language-client/callHierarchy.ts -function ensure9(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -var import_vscode_languageserver_protocol59, CallHierarchyFeature; -var init_callHierarchy = __esm({ - "src/language-client/callHierarchy.ts"() { - import_vscode_languageserver_protocol59 = __toModule(require_main2()); - init_languages(); - init_client(); - init_converter(); - "use strict"; - CallHierarchyFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol59.CallHierarchyPrepareRequest.type); - } - fillClientCapabilities(cap) { - const capabilities = cap; - const capability = ensure9(ensure9(capabilities, "textDocument"), "callHierarchy"); - capability.dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - const [id, options] = this.getRegistration(documentSelector, capabilities.callHierarchyProvider); - if (!id || !options) { - return; - } - this.register({ id, registerOptions: options }); - } - registerLanguageProvider(options) { - const provider = { - prepareCallHierarchy: (document2, position, token) => { - const client = this._client; - const prepareCallHierarchy = (document3, position2, token2) => { - const params = asTextDocumentPositionParams(document3, position2); - return client.sendRequest(import_vscode_languageserver_protocol59.CallHierarchyPrepareRequest.type, params, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol59.CallHierarchyPrepareRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.prepareCallHierarchy ? middleware.prepareCallHierarchy(document2, position, token, prepareCallHierarchy) : prepareCallHierarchy(document2, position, token); - }, - provideCallHierarchyIncomingCalls: (item, token) => { - const client = this._client; - const provideCallHierarchyIncomingCalls = (item2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol59.CallHierarchyIncomingCallsRequest.type, { item: item2 }, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol59.CallHierarchyIncomingCallsRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideCallHierarchyIncomingCalls ? middleware.provideCallHierarchyIncomingCalls(item, token, provideCallHierarchyIncomingCalls) : provideCallHierarchyIncomingCalls(item, token); - }, - provideCallHierarchyOutgoingCalls: (item, token) => { - const client = this._client; - const provideCallHierarchyOutgoingCalls = (item2, token2) => { - return client.sendRequest(import_vscode_languageserver_protocol59.CallHierarchyOutgoingCallsRequest.type, { item: item2 }, token2).then((res) => res, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol59.CallHierarchyOutgoingCallsRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideCallHierarchyOutgoingCalls ? middleware.provideCallHierarchyOutgoingCalls(item, token, provideCallHierarchyOutgoingCalls) : provideCallHierarchyOutgoingCalls(item, token); - } - }; - return [languages_default.registerCallHierarchyProvider(options.documentSelector, provider), provider]; - } - }; - } -}); - -// src/language-client/semanticTokens.ts -function ensure10(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -var import_vscode_languageserver_protocol60, logger50, SemanticTokensFeature; -var init_semanticTokens = __esm({ - "src/language-client/semanticTokens.ts"() { - import_vscode_languageserver_protocol60 = __toModule(require_main2()); - init_languages(); - init_converter(); - init_is(); - init_client(); - "use strict"; - logger50 = require_logger2()("languageclient-semanticTokens"); - SemanticTokensFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol60.SemanticTokensRegistrationType.type); - } - fillClientCapabilities(capabilities) { - const capability = ensure10(ensure10(capabilities, "textDocument"), "semanticTokens"); - capability.dynamicRegistration = true; - capability.tokenTypes = [ - import_vscode_languageserver_protocol60.SemanticTokenTypes.namespace, - import_vscode_languageserver_protocol60.SemanticTokenTypes.type, - import_vscode_languageserver_protocol60.SemanticTokenTypes.class, - import_vscode_languageserver_protocol60.SemanticTokenTypes.enum, - import_vscode_languageserver_protocol60.SemanticTokenTypes.interface, - import_vscode_languageserver_protocol60.SemanticTokenTypes.struct, - import_vscode_languageserver_protocol60.SemanticTokenTypes.typeParameter, - import_vscode_languageserver_protocol60.SemanticTokenTypes.parameter, - import_vscode_languageserver_protocol60.SemanticTokenTypes.variable, - import_vscode_languageserver_protocol60.SemanticTokenTypes.property, - import_vscode_languageserver_protocol60.SemanticTokenTypes.enumMember, - import_vscode_languageserver_protocol60.SemanticTokenTypes.event, - import_vscode_languageserver_protocol60.SemanticTokenTypes.function, - import_vscode_languageserver_protocol60.SemanticTokenTypes.method, - import_vscode_languageserver_protocol60.SemanticTokenTypes.macro, - import_vscode_languageserver_protocol60.SemanticTokenTypes.keyword, - import_vscode_languageserver_protocol60.SemanticTokenTypes.modifier, - import_vscode_languageserver_protocol60.SemanticTokenTypes.comment, - import_vscode_languageserver_protocol60.SemanticTokenTypes.string, - import_vscode_languageserver_protocol60.SemanticTokenTypes.number, - import_vscode_languageserver_protocol60.SemanticTokenTypes.regexp, - import_vscode_languageserver_protocol60.SemanticTokenTypes.operator - ]; - capability.tokenModifiers = [ - import_vscode_languageserver_protocol60.SemanticTokenModifiers.declaration, - import_vscode_languageserver_protocol60.SemanticTokenModifiers.definition, - import_vscode_languageserver_protocol60.SemanticTokenModifiers.readonly, - import_vscode_languageserver_protocol60.SemanticTokenModifiers.static, - import_vscode_languageserver_protocol60.SemanticTokenModifiers.deprecated, - import_vscode_languageserver_protocol60.SemanticTokenModifiers.abstract, - import_vscode_languageserver_protocol60.SemanticTokenModifiers.async, - import_vscode_languageserver_protocol60.SemanticTokenModifiers.modification, - import_vscode_languageserver_protocol60.SemanticTokenModifiers.documentation, - import_vscode_languageserver_protocol60.SemanticTokenModifiers.defaultLibrary - ]; - capability.formats = [import_vscode_languageserver_protocol60.TokenFormat.Relative]; - capability.requests = { - range: true, - full: { - delta: true - } - }; - capability.multilineTokenSupport = false; - capability.overlappingTokenSupport = false; - ensure10(ensure10(capabilities, "workspace"), "semanticTokens").refreshSupport = true; - } - initialize(capabilities, documentSelector) { - const client = this._client; - client.onRequest(import_vscode_languageserver_protocol60.SemanticTokensRefreshRequest.type, async () => { - for (const provider of this.getAllProviders()) { - provider.onDidChangeSemanticTokensEmitter.fire(); - } - }); - const [id, options] = this.getRegistration(documentSelector, capabilities.semanticTokensProvider); - if (!id || !options) { - return; - } - this.register({ id, registerOptions: options }); - } - registerLanguageProvider(options) { - const fullProvider = boolean(options.full) ? options.full : options.full !== void 0; - const hasEditProvider = options.full !== void 0 && typeof options.full !== "boolean" && options.full.delta === true; - const eventEmitter = new import_vscode_languageserver_protocol60.Emitter(); - const documentProvider = fullProvider ? { - onDidChangeSemanticTokens: eventEmitter.event, - provideDocumentSemanticTokens: (document2, token) => { - const client = this._client; - const middleware = client.clientOptions.middleware; - const provideDocumentSemanticTokens = (document3, token2) => { - const params = { - textDocument: asTextDocumentIdentifier(document3) - }; - return client.sendRequest(import_vscode_languageserver_protocol60.SemanticTokensRequest.type, params, token2).then((result) => result, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol60.SemanticTokensRequest.type, token2, error, null); - }); - }; - return middleware.provideDocumentSemanticTokens ? middleware.provideDocumentSemanticTokens(document2, token, provideDocumentSemanticTokens) : provideDocumentSemanticTokens(document2, token); - }, - provideDocumentSemanticTokensEdits: hasEditProvider ? (document2, previousResultId, token) => { - const client = this._client; - const middleware = client.clientOptions.middleware; - const provideDocumentSemanticTokensEdits = (document3, previousResultId2, token2) => { - const params = { - textDocument: asTextDocumentIdentifier(document3), - previousResultId: previousResultId2 - }; - return client.sendRequest(import_vscode_languageserver_protocol60.SemanticTokensDeltaRequest.type, params, token2).then((result) => result, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol60.SemanticTokensDeltaRequest.type, token2, error, null); - }); - }; - return middleware.provideDocumentSemanticTokensEdits ? middleware.provideDocumentSemanticTokensEdits(document2, previousResultId, token, provideDocumentSemanticTokensEdits) : provideDocumentSemanticTokensEdits(document2, previousResultId, token); - } : void 0 - } : void 0; - const hasRangeProvider = options.range === true; - const rangeProvider = hasRangeProvider ? { - provideDocumentRangeSemanticTokens: (document2, range, token) => { - const client = this._client; - const middleware = client.clientOptions.middleware; - const provideDocumentRangeSemanticTokens = (document3, range2, token2) => { - const params = { - textDocument: asTextDocumentIdentifier(document3), - range: range2 - }; - return client.sendRequest(import_vscode_languageserver_protocol60.SemanticTokensRangeRequest.type, params, token2).then((result) => result, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol60.SemanticTokensRangeRequest.type, token2, error, null); - }); - }; - return middleware.provideDocumentRangeSemanticTokens ? middleware.provideDocumentRangeSemanticTokens(document2, range, token, provideDocumentRangeSemanticTokens) : provideDocumentRangeSemanticTokens(document2, range, token); - } - } : void 0; - const disposables = []; - if (documentProvider !== void 0) { - disposables.push(languages_default.registerDocumentSemanticTokensProvider(options.documentSelector, documentProvider, options.legend)); - } - if (rangeProvider !== void 0) { - disposables.push(languages_default.registerDocumentRangeSemanticTokensProvider(options.documentSelector, rangeProvider, options.legend)); - } - return [import_vscode_languageserver_protocol60.Disposable.create(() => disposables.forEach((item) => item.dispose())), { range: rangeProvider, full: documentProvider, onDidChangeSemanticTokensEmitter: eventEmitter }]; - } - }; - } -}); - -// src/language-client/linkedEditingRange.ts -function ensure11(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -var import_vscode_languageserver_protocol61, logger51, LinkedEditingFeature; -var init_linkedEditingRange = __esm({ - "src/language-client/linkedEditingRange.ts"() { - import_vscode_languageserver_protocol61 = __toModule(require_main2()); - init_languages(); - init_client(); - init_converter(); - logger51 = require_logger2()("languageclient-linkedEditingRange"); - LinkedEditingFeature = class extends TextDocumentFeature { - constructor(client) { - super(client, import_vscode_languageserver_protocol61.LinkedEditingRangeRequest.type); - } - fillClientCapabilities(capabilities) { - const linkedEditingSupport = ensure11(ensure11(capabilities, "textDocument"), "linkedEditingRange"); - linkedEditingSupport.dynamicRegistration = true; - } - initialize(capabilities, documentSelector) { - let [id, options] = this.getRegistration(documentSelector, capabilities.linkedEditingRangeProvider); - if (!id || !options) { - return; - } - this.register({ id, registerOptions: options }); - } - registerLanguageProvider(options) { - const provider = { - provideLinkedEditingRanges: (document2, position, token) => { - const client = this._client; - const provideLinkedEditing = (document3, position2, token2) => { - const params = asTextDocumentPositionParams(document3, position2); - return client.sendRequest(import_vscode_languageserver_protocol61.LinkedEditingRangeRequest.type, params, token2).then((result) => result, (error) => { - return client.handleFailedRequest(import_vscode_languageserver_protocol61.LinkedEditingRangeRequest.type, token2, error, null); - }); - }; - const middleware = client.clientOptions.middleware; - return middleware.provideLinkedEditingRange ? middleware.provideLinkedEditingRange(document2, position, token, provideLinkedEditing) : provideLinkedEditing(document2, position, token); - } - }; - return [languages_default.registerLinkedEditingRangeProvider(options.documentSelector, provider), provider]; - } - }; - } -}); - -// src/language-client/fileOperations.ts -function ensure12(target, key) { - if (target[key] === void 0) { - target[key] = {}; - } - return target[key]; -} -function access2(target, key) { - return target[key]; -} -function assign(target, key, value) { - target[key] = value; -} -function asCreateDeleteFilesParams(e) { - return { - files: e.files.map((f) => ({ uri: f.toString() })) - }; -} -function asRenameFilesParams(e) { - return { - files: e.files.map((f) => ({ oldUri: f.oldUri.toString(), newUri: f.newUri.toString() })) - }; -} -var minimatch5, import_vscode_languageserver_protocol62, logger52, FileOperationFeature, NotificationFileOperationFeature, DidCreateFilesFeature, DidRenameFilesFeature, DidDeleteFilesFeature, RequestFileOperationFeature, WillCreateFilesFeature, WillRenameFilesFeature, WillDeleteFilesFeature; -var init_fileOperations = __esm({ - "src/language-client/fileOperations.ts"() { - minimatch5 = __toModule(require_minimatch()); - import_vscode_languageserver_protocol62 = __toModule(require_main2()); - init_types(); - init_fs(); - init_workspace(); - init_uuid(); - logger52 = require_logger2()("language-client-fileOperations"); - FileOperationFeature = class { - constructor(client, event, registrationType, clientCapability, serverCapability) { - this._filters = new Map(); - this._client = client; - this._event = event; - this._registrationType = registrationType; - this._clientCapability = clientCapability; - this._serverCapability = serverCapability; - } - get registrationType() { - return this._registrationType; - } - fillClientCapabilities(capabilities) { - const value = ensure12(ensure12(capabilities, "workspace"), "fileOperations"); - assign(value, "dynamicRegistration", true); - assign(value, this._clientCapability, true); - } - initialize(capabilities) { - var _a2; - const options = (_a2 = capabilities.workspace) == null ? void 0 : _a2.fileOperations; - const capability = options !== void 0 ? access2(options, this._serverCapability) : void 0; - if ((capability == null ? void 0 : capability.filters) !== void 0) { - try { - this.register({ - id: generateUuid(), - registerOptions: { filters: capability.filters } - }); - } catch (e) { - this._client.warn(`Ignoring invalid glob pattern for ${this._serverCapability} registration: ${e}`); - } - } - } - register(data) { - if (!this._listener) { - this._listener = this._event(this.send, this); - } - const minimatchFilter = data.registerOptions.filters.map((filter) => { - const matcher = new minimatch5.Minimatch(filter.pattern.glob, FileOperationFeature.asMinimatchOptions(filter.pattern.options)); - if (!matcher.makeRe()) { - throw new Error(`Invalid pattern ${filter.pattern.glob}!`); - } - return { scheme: filter.scheme, matcher, kind: filter.pattern.matches }; - }); - this._filters.set(data.id, minimatchFilter); - } - unregister(id) { - this._filters.delete(id); - if (this._filters.size === 0 && this._listener) { - this._listener.dispose(); - this._listener = void 0; - } - } - dispose() { - this._filters.clear(); - if (this._listener) { - this._listener.dispose(); - this._listener = void 0; - } - } - async filter(event, prop) { - const fileMatches = await Promise.all(event.files.map(async (item) => { - const uri = prop(item); - const path36 = uri.fsPath.replace(/\\/g, "/"); - for (const filters of this._filters.values()) { - for (const filter of filters) { - if (filter.scheme !== void 0 && filter.scheme !== uri.scheme) { - continue; - } - if (filter.matcher.match(path36)) { - if (filter.kind === void 0) { - return true; - } - const fileType = await FileOperationFeature.getFileType(uri); - if (fileType === void 0) { - this._client.error(`Failed to determine file type for ${uri.toString()}.`); - return true; - } - if (fileType === FileType.File && filter.kind === import_vscode_languageserver_protocol62.FileOperationPatternKind.file || fileType === FileType.Directory && filter.kind === import_vscode_languageserver_protocol62.FileOperationPatternKind.folder) { - return true; - } - } else if (filter.kind === import_vscode_languageserver_protocol62.FileOperationPatternKind.folder) { - const fileType = await FileOperationFeature.getFileType(uri); - if (fileType === FileType.Directory && filter.matcher.match(`${path36}/`)) { - return true; - } - } - } - } - return false; - })); - const files = event.files.filter((_, index) => fileMatches[index]); - return __spreadProps(__spreadValues({}, event), { files }); - } - static async getFileType(uri) { - try { - const stat = await statAsync(uri.fsPath); - if (stat.isFile()) { - return FileType.File; - } - if (stat.isDirectory()) { - return FileType.Directory; - } - if (stat.isSymbolicLink()) { - return FileType.SymbolicLink; - } - return FileType.Unknown; - } catch (e) { - return void 0; - } - } - static asMinimatchOptions(options) { - if (options === void 0) { - return void 0; - } - if (options.ignoreCase === true) { - return { nocase: true }; - } - return void 0; - } - }; - NotificationFileOperationFeature = class extends FileOperationFeature { - constructor(client, event, notificationType, clientCapability, serverCapability, accessUri, createParams) { - super(client, event, notificationType, clientCapability, serverCapability); - this._notificationType = notificationType; - this._accessUri = accessUri; - this._createParams = createParams; - } - async send(originalEvent) { - const filteredEvent = await this.filter(originalEvent, this._accessUri); - if (filteredEvent.files.length) { - const next = async (event) => { - this._client.sendNotification(this._notificationType, this._createParams(event)); - }; - this.doSend(filteredEvent, next); - } - } - }; - DidCreateFilesFeature = class extends NotificationFileOperationFeature { - constructor(client) { - super(client, workspace_default.onDidCreateFiles, import_vscode_languageserver_protocol62.DidCreateFilesNotification.type, "didCreate", "didCreate", (i) => i, (e) => asCreateDeleteFilesParams(e)); - } - doSend(event, next) { - var _a2; - const middleware = (_a2 = this._client.clientOptions.middleware) == null ? void 0 : _a2.workspace; - return (middleware == null ? void 0 : middleware.didCreateFiles) ? middleware.didCreateFiles(event, next) : next(event); - } - }; - DidRenameFilesFeature = class extends NotificationFileOperationFeature { - constructor(client) { - super(client, workspace_default.onDidRenameFiles, import_vscode_languageserver_protocol62.DidRenameFilesNotification.type, "didRename", "didRename", (i) => i.oldUri, (e) => asRenameFilesParams(e)); - } - doSend(event, next) { - var _a2; - const middleware = (_a2 = this._client.clientOptions.middleware) == null ? void 0 : _a2.workspace; - return (middleware == null ? void 0 : middleware.didRenameFiles) ? middleware.didRenameFiles(event, next) : next(event); - } - }; - DidDeleteFilesFeature = class extends NotificationFileOperationFeature { - constructor(client) { - super(client, workspace_default.onDidDeleteFiles, import_vscode_languageserver_protocol62.DidDeleteFilesNotification.type, "didDelete", "didDelete", (i) => i, (e) => asCreateDeleteFilesParams(e)); - } - doSend(event, next) { - var _a2; - const middleware = (_a2 = this._client.clientOptions.middleware) == null ? void 0 : _a2.workspace; - return (middleware == null ? void 0 : middleware.didDeleteFiles) ? middleware.didDeleteFiles(event, next) : next(event); - } - }; - RequestFileOperationFeature = class extends FileOperationFeature { - constructor(client, event, requestType, clientCapability, serverCapability, accessUri, createParams) { - super(client, event, requestType, clientCapability, serverCapability); - this._requestType = requestType; - this._accessUri = accessUri; - this._createParams = createParams; - } - async send(originalEvent) { - const waitUntil = this.waitUntil(originalEvent); - originalEvent.waitUntil(waitUntil); - } - async waitUntil(originalEvent) { - const filteredEvent = await this.filter(originalEvent, this._accessUri); - if (filteredEvent.files.length) { - const next = (event) => { - return this._client.sendRequest(this._requestType, this._createParams(event)); - }; - return this.doSend(filteredEvent, next); - } else { - return void 0; - } - } - }; - WillCreateFilesFeature = class extends RequestFileOperationFeature { - constructor(client) { - super(client, workspace_default.onWillCreateFiles, import_vscode_languageserver_protocol62.WillCreateFilesRequest.type, "willCreate", "willCreate", (i) => i, (e) => asCreateDeleteFilesParams(e)); - } - doSend(event, next) { - var _a2; - const middleware = (_a2 = this._client.clientOptions.middleware) == null ? void 0 : _a2.workspace; - return (middleware == null ? void 0 : middleware.willCreateFiles) ? middleware.willCreateFiles(event, next) : next(event); - } - }; - WillRenameFilesFeature = class extends RequestFileOperationFeature { - constructor(client) { - super(client, workspace_default.onWillRenameFiles, import_vscode_languageserver_protocol62.WillRenameFilesRequest.type, "willRename", "willRename", (i) => i.oldUri, (e) => asRenameFilesParams(e)); - } - doSend(event, next) { - var _a2; - const middleware = (_a2 = this._client.clientOptions.middleware) == null ? void 0 : _a2.workspace; - return (middleware == null ? void 0 : middleware.willRenameFiles) ? middleware.willRenameFiles(event, next) : next(event); - } - }; - WillDeleteFilesFeature = class extends RequestFileOperationFeature { - constructor(client) { - super(client, workspace_default.onWillDeleteFiles, import_vscode_languageserver_protocol62.WillDeleteFilesRequest.type, "willDelete", "willDelete", (i) => i, (e) => asCreateDeleteFilesParams(e)); - } - doSend(event, next) { - var _a2; - const middleware = (_a2 = this._client.clientOptions.middleware) == null ? void 0 : _a2.workspace; - return (middleware == null ? void 0 : middleware.willDeleteFiles) ? middleware.willDeleteFiles(event, next) : next(event); - } - }; - } -}); - -// src/language-client/index.ts -var import_child_process4, import_fs17, import_path18, import_node, ChildProcess2, logger53, Executable, TransportKind, Transport, NodeModule, StreamInfo, ChildProcessInfo, LanguageClient, SettingMonitor, ProposedFeatures; -var init_language_client = __esm({ - "src/language-client/index.ts"() { - import_child_process4 = __toModule(require("child_process")); - import_fs17 = __toModule(require("fs")); - import_path18 = __toModule(require("path")); - import_node = __toModule(require_node3()); - init_types(); - init_util(); - init_is(); - init_processes(); - init_workspace(); - init_client(); - init_colorProvider(); - init_configuration3(); - init_declaration(); - init_foldingRange(); - init_implementation(); - init_progress2(); - init_typeDefinition(); - init_workspaceFolders(); - init_selectionRange(); - init_callHierarchy(); - init_semanticTokens(); - init_linkedEditingRange(); - init_fileOperations(); - init_client(); - ChildProcess2 = import_child_process4.default.ChildProcess; - logger53 = require_logger2()("language-client-index"); - (function(Executable3) { - function is(value) { - return string(value.command); - } - Executable3.is = is; - })(Executable || (Executable = {})); - (function(TransportKind2) { - TransportKind2[TransportKind2["stdio"] = 0] = "stdio"; - TransportKind2[TransportKind2["ipc"] = 1] = "ipc"; - TransportKind2[TransportKind2["pipe"] = 2] = "pipe"; - TransportKind2[TransportKind2["socket"] = 3] = "socket"; - })(TransportKind || (TransportKind = {})); - (function(Transport3) { - function isSocket(value) { - let candidate = value; - return candidate && candidate.kind === 3 && number(candidate.port); - } - Transport3.isSocket = isSocket; - })(Transport || (Transport = {})); - (function(NodeModule2) { - function is(value) { - return string(value.module); - } - NodeModule2.is = is; - })(NodeModule || (NodeModule = {})); - (function(StreamInfo2) { - function is(value) { - let candidate = value; - return candidate && candidate.writer !== void 0 && candidate.reader !== void 0; - } - StreamInfo2.is = is; - })(StreamInfo || (StreamInfo = {})); - (function(ChildProcessInfo2) { - function is(value) { - let candidate = value; - return candidate && candidate.process !== void 0 && typeof candidate.detached === "boolean"; - } - ChildProcessInfo2.is = is; - })(ChildProcessInfo || (ChildProcessInfo = {})); - LanguageClient = class extends BaseLanguageClient { - constructor(arg1, arg2, arg3, arg4, arg5) { - let id; - let name2; - let serverOptions; - let clientOptions; - let forceDebug; - if (string(arg2)) { - id = arg1; - name2 = arg2; - serverOptions = arg3; - clientOptions = arg4; - forceDebug = !!arg5; - } else { - id = arg1.toLowerCase(); - name2 = arg1; - serverOptions = arg2; - clientOptions = arg3; - forceDebug = arg4; - } - if (forceDebug === void 0) { - forceDebug = false; - } - super(id, name2, clientOptions); - this._serverOptions = serverOptions; - this._forceDebug = forceDebug; - this.registerProposedFeatures(); - } - stop() { - return super.stop().then(() => { - if (this._serverProcess) { - let toCheck = this._serverProcess; - this._serverProcess = void 0; - if (this._isDetached === void 0 || !this._isDetached) { - this.checkProcessDied(toCheck); - } - this._isDetached = void 0; - } - }); - } - get serviceState() { - let state = this._state; - switch (state) { - case ClientState.Initial: - return ServiceStat.Initial; - case ClientState.Running: - return ServiceStat.Running; - case ClientState.StartFailed: - return ServiceStat.StartFailed; - case ClientState.Starting: - return ServiceStat.Starting; - case ClientState.Stopped: - return ServiceStat.Stopped; - case ClientState.Stopping: - return ServiceStat.Stopping; - default: - logger53.error(`Unknown state: ${state}`); - return ServiceStat.Stopped; - } - } - static stateName(state) { - switch (state) { - case ClientState.Initial: - return "Initial"; - case ClientState.Running: - return "Running"; - case ClientState.StartFailed: - return "StartFailed"; - case ClientState.Starting: - return "Starting"; - case ClientState.Stopped: - return "Stopped"; - case ClientState.Stopping: - return "Stopping"; - default: - return "Unknonw"; - } - } - checkProcessDied(childProcess) { - if (!childProcess || global.hasOwnProperty("__TEST__")) - return; - if (global.hasOwnProperty("__TEST__")) { - process.kill(childProcess.pid, 0); - return; - } - setTimeout(() => { - try { - process.kill(childProcess.pid, 0); - terminate(childProcess); - } catch (error) { - } - }, 2e3); - } - handleConnectionClosed() { - this._serverProcess = void 0; - super.handleConnectionClosed(); - } - createMessageTransports(encoding) { - function getEnvironment(env, fork) { - if (!env && !fork) { - return void 0; - } - let result = Object.create(null); - Object.keys(process.env).forEach((key) => result[key] = process.env[key]); - if (env) { - Object.keys(env).forEach((key) => result[key] = env[key]); - } - return result; - } - const debugStartWith = ["--debug=", "--debug-brk=", "--inspect=", "--inspect-brk="]; - const debugEquals = ["--debug", "--debug-brk", "--inspect", "--inspect-brk"]; - function startedInDebugMode() { - let args = process.execArgv; - if (args) { - return args.some((arg) => { - return debugStartWith.some((value) => arg.startsWith(value)) || debugEquals.some((value) => arg === value); - }); - } - return false; - } - function assertStdio(process2) { - if (process2.stdin === null || process2.stdout === null || process2.stderr === null) { - throw new Error("Process created without stdio streams"); - } - } - let server = this._serverOptions; - if (func(server)) { - return server().then((result) => { - if (MessageTransports.is(result)) { - this._isDetached = !!result.detached; - return result; - } else if (StreamInfo.is(result)) { - this._isDetached = !!result.detached; - return { - reader: new import_node.StreamMessageReader(result.reader), - writer: new import_node.StreamMessageWriter(result.writer) - }; - } else { - let cp3; - if (ChildProcessInfo.is(result)) { - cp3 = result.process; - this._isDetached = result.detached; - } else { - cp3 = result; - this._isDetached = false; - } - cp3.stderr.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - return { - reader: new import_node.StreamMessageReader(cp3.stdout), - writer: new import_node.StreamMessageWriter(cp3.stdin) - }; - } - }); - } - let json; - let runDebug = server; - if (runDebug.run || runDebug.debug) { - if (typeof v8debug === "object" || this._forceDebug || startedInDebugMode()) { - json = runDebug.debug; - } else { - json = runDebug.run; - } - } else { - json = server; - } - return this._getServerWorkingDir(json.options).then((serverWorkingDir) => { - if (NodeModule.is(json) && json.module) { - let node = json; - let transport = node.transport || 0; - if (node.runtime) { - let args = []; - let options = node.options || Object.create(null); - if (options.execArgv) { - options.execArgv.forEach((element) => args.push(element)); - } - args.push(node.module); - if (node.args) { - node.args.forEach((element) => args.push(element)); - } - const execOptions = Object.create(null); - execOptions.cwd = serverWorkingDir; - execOptions.env = getEnvironment(options.env, false); - const runtime = this._getRuntimePath(node.runtime, serverWorkingDir); - let pipeName; - if (transport === 1) { - execOptions.stdio = [null, null, null, "ipc"]; - args.push("--node-ipc"); - } else if (transport === 0) { - args.push("--stdio"); - } else if (transport === 2) { - pipeName = (0, import_node.generateRandomPipeName)(); - args.push(`--pipe=${pipeName}`); - } else if (Transport.isSocket(transport)) { - args.push(`--socket=${transport.port}`); - } - args.push(`--clientProcessId=${process.pid.toString()}`); - if (transport === 1 || transport === 0) { - let serverProcess = import_child_process4.default.spawn(runtime, args, execOptions); - if (!serverProcess || !serverProcess.pid) { - return Promise.reject(`Launching server using runtime ${runtime} failed.`); - } - this._serverProcess = serverProcess; - serverProcess.stderr.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - if (transport === 1) { - serverProcess.stdout.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - return Promise.resolve({ reader: new import_node.IPCMessageReader(serverProcess), writer: new import_node.IPCMessageWriter(serverProcess) }); - } else { - return Promise.resolve({ reader: new import_node.StreamMessageReader(serverProcess.stdout), writer: new import_node.StreamMessageWriter(serverProcess.stdin) }); - } - } else if (transport === 2) { - return (0, import_node.createClientPipeTransport)(pipeName).then((transport2) => { - let process2 = import_child_process4.default.spawn(runtime, args, execOptions); - if (!process2 || !process2.pid) { - return Promise.reject(`Launching server using runtime ${runtime} failed.`); - } - this._serverProcess = process2; - process2.stderr.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - process2.stdout.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - return transport2.onConnected().then((protocol) => { - return { reader: protocol[0], writer: protocol[1] }; - }); - }); - } else if (Transport.isSocket(transport)) { - return (0, import_node.createClientSocketTransport)(transport.port).then((transport2) => { - let process2 = import_child_process4.default.spawn(runtime, args, execOptions); - if (!process2 || !process2.pid) { - return Promise.reject(`Launching server using runtime ${runtime} failed.`); - } - this._serverProcess = process2; - process2.stderr.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - process2.stdout.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - return transport2.onConnected().then((protocol) => { - return { reader: protocol[0], writer: protocol[1] }; - }); - }); - } - } else { - let pipeName; - return new Promise((resolve3, _reject) => { - let args = node.args && node.args.slice() || []; - if (transport === 1) { - args.push("--node-ipc"); - } else if (transport === 0) { - args.push("--stdio"); - } else if (transport === 2) { - pipeName = (0, import_node.generateRandomPipeName)(); - args.push(`--pipe=${pipeName}`); - } else if (Transport.isSocket(transport)) { - args.push(`--socket=${transport.port}`); - } - args.push(`--clientProcessId=${process.pid.toString()}`); - let options = node.options || Object.create(null); - options.env = getEnvironment(options.env, true); - options.execArgv = options.execArgv || []; - options.cwd = serverWorkingDir; - options.silent = true; - if (transport === 1 || transport === 0) { - let sp = import_child_process4.default.fork(node.module, args || [], options); - assertStdio(sp); - this._serverProcess = sp; - sp.stderr.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - if (transport === 1) { - sp.stdout.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - resolve3({ reader: new import_node.IPCMessageReader(this._serverProcess), writer: new import_node.IPCMessageWriter(this._serverProcess) }); - } else { - resolve3({ reader: new import_node.StreamMessageReader(sp.stdout), writer: new import_node.StreamMessageWriter(sp.stdin) }); - } - } else if (transport === 2) { - void (0, import_node.createClientPipeTransport)(pipeName).then((transport2) => { - let sp = import_child_process4.default.fork(node.module, args || [], options); - assertStdio(sp); - this._serverProcess = sp; - sp.stderr.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - sp.stdout.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - void transport2.onConnected().then((protocol) => { - resolve3({ reader: protocol[0], writer: protocol[1] }); - }); - }); - } else if (Transport.isSocket(transport)) { - void (0, import_node.createClientSocketTransport)(transport.port).then((transport2) => { - let sp = import_child_process4.default.fork(node.module, args || [], options); - assertStdio(sp); - this._serverProcess = sp; - sp.stderr.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - sp.stdout.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - void transport2.onConnected().then((protocol) => { - resolve3({ reader: protocol[0], writer: protocol[1] }); - }); - }); - } - }); - } - } else if (Executable.is(json) && json.command) { - let command = json; - let args = command.args || []; - let options = Object.assign({}, command.options); - options.env = options.env ? Object.assign({}, process.env, options.env) : process.env; - options.cwd = options.cwd || serverWorkingDir; - let cmd = workspace_default.expand(json.command); - let serverProcess = import_child_process4.default.spawn(cmd, args, options); - serverProcess.on("error", (e) => { - this.error(e.message); - logger53.error(e); - }); - if (!serverProcess || !serverProcess.pid) { - return Promise.reject(`Launching server "${this.id}" using command ${command.command} failed.`); - } - logger53.info(`Language server "${this.id}" started with ${serverProcess.pid}`); - serverProcess.on("exit", (code) => { - if (code != 0) - this.error(`${command.command} exited with code: ${code}`); - }); - serverProcess.stderr.on("data", (data) => this.outputChannel.append(string(data) ? data : data.toString(encoding))); - this._serverProcess = serverProcess; - this._isDetached = !!options.detached; - return Promise.resolve({ reader: new import_node.StreamMessageReader(serverProcess.stdout), writer: new import_node.StreamMessageWriter(serverProcess.stdin) }); - } - return Promise.reject(`Unsupported server configuration ${JSON.stringify(server, null, 2)}`); - }); - } - _getRuntimePath(runtime, serverWorkingDirectory) { - if (import_path18.default.isAbsolute(runtime)) { - return runtime; - } - const mainRootPath = this._mainGetRootPath(); - if (mainRootPath !== void 0) { - const result = import_path18.default.join(mainRootPath, runtime); - if (import_fs17.default.existsSync(result)) { - return result; - } - } - if (serverWorkingDirectory !== void 0) { - const result = import_path18.default.join(serverWorkingDirectory, runtime); - if (import_fs17.default.existsSync(result)) { - return result; - } - } - return runtime; - } - _mainGetRootPath() { - let folders = workspace_default.workspaceFolders; - if (!folders || folders.length === 0) { - return void 0; - } - let folder = folders[0]; - return folder.uri; - } - registerProposedFeatures() { - this.registerFeatures(ProposedFeatures.createAll(this)); - } - registerBuiltinFeatures() { - super.registerBuiltinFeatures(); - this.registerFeature(new ConfigurationFeature2(this)); - this.registerFeature(new TypeDefinitionFeature(this)); - this.registerFeature(new ImplementationFeature(this)); - this.registerFeature(new DeclarationFeature(this)); - this.registerFeature(new ColorProviderFeature(this)); - this.registerFeature(new FoldingRangeFeature(this)); - this.registerFeature(new SelectionRangeFeature(this)); - this.registerFeature(new ProgressFeature(this)); - this.registerFeature(new CallHierarchyFeature(this)); - if (workspace_default.isNvim || workspace_default.isVim && workspace_default.env.textprop) { - const config = workspace_default.getConfiguration("coc.preferences"); - const enabled = config.get("semanticTokensHighlights", true); - if (enabled) - this.registerFeature(new SemanticTokensFeature(this)); - } - this.registerFeature(new LinkedEditingFeature(this)); - this.registerFeature(new DidCreateFilesFeature(this)); - this.registerFeature(new DidRenameFilesFeature(this)); - this.registerFeature(new DidDeleteFilesFeature(this)); - this.registerFeature(new WillCreateFilesFeature(this)); - this.registerFeature(new WillRenameFilesFeature(this)); - this.registerFeature(new WillDeleteFilesFeature(this)); - if (!this.clientOptions.disableWorkspaceFolders) { - this.registerFeature(new WorkspaceFoldersFeature(this)); - } - } - _getServerWorkingDir(options) { - let cwd = options && options.cwd; - if (cwd && !import_path18.default.isAbsolute(cwd)) - cwd = import_path18.default.join(workspace_default.cwd, cwd); - if (!cwd) - cwd = workspace_default.cwd; - if (cwd) { - return new Promise((s) => { - import_fs17.default.lstat(cwd, (err, stats) => { - s(!err && stats.isDirectory() ? cwd : void 0); - }); - }); - } - return Promise.resolve(void 0); - } - appendOutput(data, encoding) { - let msg = string(data) ? data : data.toString(encoding); - this.outputChannel.append(msg.endsWith("\n") ? msg : msg + "\n"); - } - }; - SettingMonitor = class { - constructor(_client, _setting) { - this._client = _client; - this._setting = _setting; - this._listeners = []; - } - start() { - workspace_default.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration(this._setting)) { - this.onDidChangeConfiguration(); - } - }, null, this._listeners); - this.onDidChangeConfiguration(); - return { - dispose: () => { - disposeAll(this._listeners); - if (this._client.needsStop()) { - this._client.stop(); - } - } - }; - } - onDidChangeConfiguration() { - let index = this._setting.indexOf("."); - let primary = index >= 0 ? this._setting.substr(0, index) : this._setting; - let rest = index >= 0 ? this._setting.substr(index + 1) : void 0; - let enabled = rest ? workspace_default.getConfiguration(primary).get(rest, true) : workspace_default.getConfiguration(primary); - if (enabled && this._client.needsStart()) { - this._client.start(); - } else if (!enabled && this._client.needsStop()) { - this._client.stop(); - } - } - }; - (function(ProposedFeatures2) { - function createAll(_client) { - let result = []; - return result; - } - ProposedFeatures2.createAll = createAll; - })(ProposedFeatures || (ProposedFeatures = {})); - } -}); - -// src/services.ts -function getStateName(state) { - switch (state) { - case ServiceStat.Initial: - return "init"; - case ServiceStat.Running: - return "running"; - case ServiceStat.Starting: - return "starting"; - case ServiceStat.StartFailed: - return "startFailed"; - case ServiceStat.Stopping: - return "stopping"; - case ServiceStat.Stopped: - return "stopped"; - default: - return "unknown"; - } -} -function documentSelectorToLanguageIds(documentSelector) { - let res = documentSelector.map((filter) => { - if (typeof filter == "string") { - return filter; - } - return filter.language; - }); - res = res.filter((s) => typeof s == "string"); - return Array.from(new Set(res)); -} -function getLanguageServerOptions(id, name2, config) { - let { command, module: module2, port, args, filetypes } = config; - args = args || []; - if (!filetypes) { - window_default.showMessage(`Wrong configuration of LS "${name2}", filetypes not found`, "error"); - return null; - } - if (!command && !module2 && !port) { - window_default.showMessage(`Wrong configuration of LS "${name2}", no command or module specified.`, "error"); - return null; - } - let serverOptions; - if (module2) { - module2 = workspace_default.expand(module2); - if (!import_fs18.default.existsSync(module2)) { - window_default.showMessage(`Module file "${module2}" not found for LS "${name2}"`, "error"); - return null; - } - serverOptions = { - module: module2, - runtime: config.runtime || process.execPath, - args, - transport: getTransportKind(config), - options: getForkOptions(config) - }; - } else if (command) { - serverOptions = { - command, - args, - options: getSpawnOptions(config) - }; - } else if (port) { - serverOptions = () => new Promise((resolve3, reject) => { - let client = new import_net2.default.Socket(); - let host = config.host || "127.0.0.1"; - logger54.info(`languageserver "${id}" connecting to ${host}:${port}`); - client.connect(port, host, () => { - resolve3({ - reader: client, - writer: client - }); - }); - client.on("error", (e) => { - reject(new Error(`Connection error for ${id}: ${e.message}`)); - }); - }); - } - let disableWorkspaceFolders = !!config.disableWorkspaceFolders; - let disableSnippetCompletion = !!config.disableSnippetCompletion; - let ignoredRootPaths = config.ignoredRootPaths || []; - let clientOptions = { - ignoredRootPaths: ignoredRootPaths.map((s) => workspace_default.expand(s)), - disableWorkspaceFolders, - disableSnippetCompletion, - disableDynamicRegister: !!config.disableDynamicRegister, - disableCompletion: !!config.disableCompletion, - disableDiagnostics: !!config.disableDiagnostics, - formatterPriority: config.formatterPriority || 0, - documentSelector: getDocumentSelector(config.filetypes, config.additionalSchemes), - revealOutputChannelOn: getRevealOutputChannelOn(config.revealOutputChannelOn), - synchronize: { - configurationSection: `${id}.settings` - }, - diagnosticCollectionName: name2, - outputChannelName: id, - stdioEncoding: config.stdioEncoding || "utf8", - progressOnInitialization: config.progressOnInitialization !== false, - initializationOptions: config.initializationOptions || {} - }; - return [clientOptions, serverOptions]; -} -function getRevealOutputChannelOn(revealOn) { - switch (revealOn) { - case "info": - return RevealOutputChannelOn.Info; - case "warn": - return RevealOutputChannelOn.Warn; - case "error": - return RevealOutputChannelOn.Error; - case "never": - return RevealOutputChannelOn.Never; - default: - return RevealOutputChannelOn.Never; - } -} -function getDocumentSelector(filetypes, additionalSchemes) { - let documentSelector = []; - let schemes = ["file", "untitled"].concat(additionalSchemes || []); - if (!filetypes) - return schemes.map((s) => ({ scheme: s })); - filetypes.forEach((filetype) => { - documentSelector.push(...schemes.map((scheme) => ({ language: filetype, scheme }))); - }); - return documentSelector; -} -function getTransportKind(config) { - let { transport, transportPort } = config; - if (!transport || transport == "ipc") - return TransportKind.ipc; - if (transport == "stdio") - return TransportKind.stdio; - if (transport == "pipe") - return TransportKind.pipe; - return { kind: TransportKind.socket, port: transportPort }; -} -function getForkOptions(config) { - return { - cwd: config.cwd, - execArgv: config.execArgv || [], - env: config.env || void 0 - }; -} -function getSpawnOptions(config) { - return { - cwd: config.cwd, - detached: !!config.detached, - shell: !!config.shell, - env: config.env || void 0 - }; -} -function stateString(state) { - switch (state) { - case State2.Running: - return "running"; - case State2.Starting: - return "starting"; - case State2.Stopped: - return "stopped"; - default: - return "unknown"; - } -} -var import_events18, import_fs18, import_net2, import_vscode_languageserver_protocol63, logger54, ServiceManager, services_default; -var init_services = __esm({ - "src/services.ts"() { - import_events18 = __toModule(require("events")); - import_fs18 = __toModule(require("fs")); - import_net2 = __toModule(require("net")); - import_vscode_languageserver_protocol63 = __toModule(require_main2()); - init_language_client(); - init_types(); - init_util(); - init_workspace(); - init_window(); - logger54 = require_logger2()("services"); - ServiceManager = class extends import_events18.EventEmitter { - constructor() { - super(...arguments); - this.registered = new Map(); - this.disposables = []; - } - init() { - workspace_default.onDidOpenTextDocument((document2) => { - this.start(document2); - }, null, this.disposables); - workspace_default.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("languageserver")) { - this.createCustomServices(); - } - }, null, this.disposables); - this.createCustomServices(); - } - dispose() { - this.removeAllListeners(); - disposeAll(this.disposables); - for (let service of this.registered.values()) { - service.dispose(); - } - } - regist(service) { - let { id } = service; - if (!id) - logger54.error("invalid service configuration. ", service.name); - if (this.registered.get(id)) - return; - this.registered.set(id, service); - logger54.info(`registered service "${id}"`); - if (this.shouldStart(service)) { - service.start(); - } - if (service.state == ServiceStat.Running) { - this.emit("ready", id); - } - service.onServiceReady(() => { - logger54.info(`service ${id} started`); - this.emit("ready", id); - }, null, this.disposables); - return import_vscode_languageserver_protocol63.Disposable.create(() => { - service.stop(); - service.dispose(); - this.registered.delete(id); - }); - } - getService(id) { - let service = this.registered.get(id); - if (!service) - service = this.registered.get(`languageserver.${id}`); - return service; - } - shouldStart(service) { - if (service.state != ServiceStat.Initial) { - return false; - } - let selector = service.selector; - for (let doc of workspace_default.documents) { - if (workspace_default.match(selector, doc.textDocument)) { - return true; - } - } - return false; - } - start(document2) { - let services = this.getServices(document2); - for (let service of services) { - if (service.state == ServiceStat.Initial) { - service.start(); - } - } - } - getServices(document2) { - let res = []; - for (let service of this.registered.values()) { - if (workspace_default.match(service.selector, document2) > 0) { - res.push(service); - } - } - return res; - } - stop(id) { - let service = this.registered.get(id); - if (!service) { - window_default.showMessage(`Service ${id} not found`, "error"); - return; - } - return Promise.resolve(service.stop()); - } - stopAll() { - for (let service of this.registered.values()) { - service.stop(); - } - } - async toggle(id) { - let service = this.registered.get(id); - if (!service) { - window_default.showMessage(`Service ${id} not found`, "error"); - return; - } - let { state } = service; - try { - if (state == ServiceStat.Running) { - await Promise.resolve(service.stop()); - } else if (state == ServiceStat.Initial) { - await service.start(); - } else if (state == ServiceStat.Stopped) { - await service.restart(); - } - } catch (e) { - window_default.showMessage(`Service error: ${e.message}`, "error"); - } - } - getServiceStats() { - let res = []; - for (let [id, service] of this.registered) { - res.push({ - id, - languageIds: documentSelectorToLanguageIds(service.selector), - state: getStateName(service.state) - }); - } - return res; - } - createCustomServices() { - let lspConfig = workspace_default.getConfiguration().get("languageserver", {}); - for (let key of Object.keys(lspConfig)) { - let config = lspConfig[key]; - if (!this.validServerConfig(key, config)) { - continue; - } - this.registLanguageClient(key, config); - } - } - validServerConfig(key, config) { - let errors = []; - if (config.module != null && typeof config.module !== "string") { - errors.push(`"module" field of languageserver ${key} should be string`); - } - if (config.command != null && typeof config.command !== "string") { - errors.push(`"command" field of languageserver ${key} should be string`); - } - if (config.transport != null && typeof config.transport !== "string") { - errors.push(`"transport" field of languageserver ${key} should be string`); - } - if (config.transportPort != null && typeof config.transportPort !== "number") { - errors.push(`"transportPort" field of languageserver ${key} should be string`); - } - if (!Array.isArray(config.filetypes) || !config.filetypes.every((s) => typeof s === "string")) { - errors.push(`"filetypes" field of languageserver ${key} should be array of string`); - } - if (config.additionalSchemes && (!Array.isArray(config.additionalSchemes) || config.additionalSchemes.some((s) => typeof s !== "string"))) { - errors.push(`"additionalSchemes" field of languageserver ${key} should be array of string`); - } - if (errors.length) { - window_default.showMessage(errors.join("\n"), "error"); - return false; - } - return true; - } - waitClient(id) { - let service = this.getService(id); - if (service && service.state == ServiceStat.Running) - return Promise.resolve(); - if (service) - return new Promise((resolve3) => { - service.onServiceReady(() => { - resolve3(); - }); - }); - return new Promise((resolve3) => { - let listener = (clientId) => { - if (clientId == id || clientId == `languageserver.${id}`) { - this.off("ready", listener); - resolve3(); - } - }; - this.on("ready", listener); - }); - } - async registNotification(id, method) { - await this.waitClient(id); - let service = this.getService(id); - if (!service.client) { - window_default.showMessage(`Not a language client: ${id}`, "error"); - return; - } - let client = service.client; - client.onNotification(method, async (result) => { - await workspace_default.nvim.call("coc#do_notify", [id, method, result]); - }); - } - async sendNotification(id, method, params) { - if (!method) - throw new Error(`method required for ontification`); - let service = this.getService(id); - if (!service || !service.client) - throw new Error(`Language server ${id} not found`); - if (service.state == ServiceStat.Starting) { - await service.client.onReady(); - } - if (service.state != ServiceStat.Running) { - throw new Error(`Language server ${id} not running`); - } - await Promise.resolve(service.client.sendNotification(method, params)); - } - async sendRequest(id, method, params, token) { - if (!method) - throw new Error(`method required for sendRequest`); - let service = this.getService(id); - if (!service) - await wait(100); - service = this.getService(id); - if (!service || !service.client) { - throw new Error(`Language server ${id} not found`); - } - if (service.state == ServiceStat.Starting) { - await service.client.onReady(); - } - if (service.state != ServiceStat.Running) { - throw new Error(`Language server ${id} not running`); - } - if (!token) { - let tokenSource = new import_vscode_languageserver_protocol63.CancellationTokenSource(); - token = tokenSource.token; - } - return await Promise.resolve(service.client.sendRequest(method, params, token)); - } - registLanguageClient(name2, config) { - let id = typeof name2 === "string" ? `languageserver.${name2}` : name2.id; - let disposables = []; - let onDidServiceReady = new import_vscode_languageserver_protocol63.Emitter(); - let client = typeof name2 === "string" ? null : name2; - if (this.registered.has(id)) - return; - let created = false; - let service = { - id, - client, - name: typeof name2 === "string" ? name2 : name2.name, - selector: typeof name2 === "string" ? getDocumentSelector(config.filetypes, config.additionalSchemes) : name2.clientOptions.documentSelector, - state: ServiceStat.Initial, - onServiceReady: onDidServiceReady.event, - start: () => { - if (service.state == ServiceStat.Starting || service.state == ServiceStat.Running) { - return; - } - if (client && !client.needsStart()) { - return; - } - if (created && client) { - client.restart(); - return Promise.resolve(); - } - if (!created) { - if (typeof name2 == "string" && !client) { - let config2 = workspace_default.getConfiguration().get("languageserver", {})[name2]; - if (!config2 || config2.enable === false) - return; - let opts = getLanguageServerOptions(id, name2, config2); - if (!opts) - return; - client = new LanguageClient(id, name2, opts[1], opts[0]); - service.selector = opts[0].documentSelector; - service.client = client; - } - client.onDidChangeState((changeEvent) => { - let { oldState, newState } = changeEvent; - if (newState == State2.Starting) { - service.state = ServiceStat.Starting; - } else if (newState == State2.Running) { - service.state = ServiceStat.Running; - } else if (newState == State2.Stopped) { - service.state = ServiceStat.Stopped; - } - let oldStr = stateString(oldState); - let newStr = stateString(newState); - logger54.info(`${client.name} state change: ${oldStr} => ${newStr}`); - }, null, disposables); - created = true; - } - service.state = ServiceStat.Starting; - logger54.debug(`starting service: ${id}`); - let disposable = client.start(); - disposables.push(disposable); - return new Promise((resolve3) => { - client.onReady().then(() => { - onDidServiceReady.fire(void 0); - resolve3(); - }, (e) => { - window_default.showMessage(`Server ${id} failed to start: ${e}`, "error"); - logger54.error(`Server ${id} failed to start:`, e); - service.state = ServiceStat.StartFailed; - resolve3(); - }); - }); - }, - dispose: async () => { - onDidServiceReady.dispose(); - disposeAll(disposables); - }, - stop: async () => { - if (!client || !client.needsStop()) - return; - await Promise.resolve(client.stop()); - }, - restart: async () => { - if (client) { - service.state = ServiceStat.Starting; - client.restart(); - } else { - await service.start(); - } - } - }; - return this.regist(service); - } - }; - services_default = new ServiceManager(); - } -}); - -// src/list/configuration.ts -var import_events19, validKeys, ListConfiguration; -var init_configuration4 = __esm({ - "src/list/configuration.ts"() { - init_workspace(); - init_window(); - import_events19 = __toModule(require("events")); - validKeys = [ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "<2-LeftMouse>", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "" - ]; - ListConfiguration = class extends import_events19.EventEmitter { - constructor() { - super(); - this.configuration = workspace_default.getConfiguration("list"); - this.disposable = workspace_default.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("list")) { - this.configuration = workspace_default.getConfiguration("list"); - this.emit("change"); - } - }); - } - get(key, defaultValue) { - return this.configuration.get(key, defaultValue); - } - get previousKey() { - return this.fixKey(this.configuration.get("previousKeymap", "")); - } - get nextKey() { - return this.fixKey(this.configuration.get("nextKeymap", "")); - } - dispose() { - this.disposable.dispose(); - this.removeAllListeners(); - } - fixKey(key) { - if (validKeys.includes(key)) - return key; - let find = validKeys.find((s) => s.toLowerCase() == key.toLowerCase()); - if (find) - return find; - window_default.showMessage(`Configured key "${key}" not supported.`, "error"); - return null; - } - }; - } -}); - -// src/list/mappings.ts -var import_extensions, logger55, Mappings; -var init_mappings = __esm({ - "src/list/mappings.ts"() { - import_extensions = __toModule(require_extensions()); - init_window(); - init_configuration4(); - logger55 = require_logger2()("list-mappings"); - Mappings = class { - constructor(manager, nvim, config) { - this.manager = manager; - this.nvim = nvim; - this.config = config; - this.insertMappings = new Map(); - this.normalMappings = new Map(); - this.userInsertMappings = new Map(); - this.userNormalMappings = new Map(); - let { prompt } = manager; - this.add("insert", "", () => { - var _a2; - (_a2 = manager.session) == null ? void 0 : _a2.history.next(); - }); - this.add("insert", "", () => { - var _a2; - (_a2 = manager.session) == null ? void 0 : _a2.history.previous(); - }); - this.add("insert", "", async () => { - await prompt.paste(); - }); - this.add("insert", "", () => manager.switchMatcher()); - this.add("insert", ["", ""], async () => { - await manager.doAction(); - }); - this.add("insert", ["", "", " "], () => manager.chooseAction()); - this.add("insert", "", () => { - manager.toggleMode(); - }); - this.add("insert", "", () => { - manager.stop(); - return; - }); - this.add("insert", "", async () => { - var _a2; - await ((_a2 = manager.session) == null ? void 0 : _a2.reloadItems()); - }); - this.add("insert", "", () => { - prompt.moveLeft(); - }); - this.add("insert", "", () => { - prompt.moveRight(); - }); - this.add("insert", ["", ""], () => { - prompt.moveToEnd(); - }); - this.add("insert", ["", ""], () => { - prompt.moveToStart(); - }); - this.add("insert", ["", "", ""], () => { - prompt.onBackspace(); - }); - this.add("insert", "", () => { - prompt.removeWord(); - }); - this.add("insert", "", () => { - prompt.removeAhead(); - }); - this.add("insert", "", () => prompt.insertRegister()); - this.add("insert", "", () => manager.feedkeys("", false)); - this.add("insert", "", () => manager.feedkeys("", false)); - this.add("insert", "", () => manager.feedkeys("", false)); - this.add("insert", "", () => manager.normal("j")); - this.add("insert", "", () => manager.normal("k")); - this.add("insert", [""], this.doScroll.bind(this, "")); - this.add("insert", [""], this.doScroll.bind(this, "")); - this.add("insert", [""], this.doScroll.bind(this, "")); - this.add("insert", [""], this.doScroll.bind(this, "")); - this.add("normal", "t", () => manager.doAction("tabe")); - this.add("normal", "s", () => manager.doAction("split")); - this.add("normal", "d", () => manager.doAction("drop")); - this.add("normal", ["", "", "\r"], () => manager.doAction()); - this.add("normal", "", () => { - var _a2; - return (_a2 = manager.session) == null ? void 0 : _a2.ui.selectAll(); - }); - this.add("normal", " ", () => { - var _a2; - return (_a2 = manager.session) == null ? void 0 : _a2.ui.toggleSelection(); - }); - this.add("normal", "p", () => manager.togglePreview()); - this.add("normal", ["", " ", ""], () => manager.chooseAction()); - this.add("normal", "", () => { - manager.stop(); - }); - this.add("normal", "", () => { - var _a2; - return (_a2 = manager.session) == null ? void 0 : _a2.reloadItems(); - }); - this.add("normal", "", () => { - var _a2; - return (_a2 = manager.session) == null ? void 0 : _a2.jumpBack(); - }); - this.add("normal", "", () => this.scrollPreview("down")); - this.add("normal", "", () => this.scrollPreview("up")); - this.add("normal", ["i", "I", "o", "O", "a", "A"], () => manager.toggleMode()); - this.add("normal", "?", () => { - var _a2; - return (_a2 = manager.session) == null ? void 0 : _a2.showHelp(); - }); - this.add("normal", ":", async () => { - await manager.cancel(false); - await nvim.eval('feedkeys(":")'); - }); - this.add("normal", [""], this.doScroll.bind(this, "")); - this.add("normal", [""], this.doScroll.bind(this, "")); - this.createMappings(); - config.on("change", () => { - this.createMappings(); - }); - } - createMappings() { - let insertMappings = this.config.get("insertMappings", {}); - this.userInsertMappings = this.fixUserMappings(insertMappings); - let normalMappings = this.config.get("normalMappings", {}); - this.userNormalMappings = this.fixUserMappings(normalMappings); - } - fixUserMappings(mappings) { - let res = new Map(); - for (let [key, value] of Object.entries(mappings)) { - if (key.length == 1) { - res.set(key, value); - } else if (key.startsWith("<") && key.endsWith(">")) { - if (key.toLowerCase() == "") { - res.set(" ", value); - } else if (key.toLowerCase() == "") { - res.set("", value); - } else if (validKeys.includes(key)) { - res.set(key, value); - } else { - let find = false; - for (let i = 0; i < validKeys.length; i++) { - if (validKeys[i].toLowerCase() == key.toLowerCase()) { - find = true; - res.set(validKeys[i], value); - break; - } - } - if (!find) - window_default.showMessage(`Invalid list mappings key configuration: "${key}"`, "warning"); - } - } else { - window_default.showMessage(`Invalid list mappings key configuration: "${key}"`, "warning"); - } - } - return res; - } - async doInsertKeymap(key) { - let nextKey = this.config.nextKey; - let previousKey = this.config.previousKey; - let { session } = this.manager; - if (!session) - return; - if (key == nextKey) { - session.ui.index = session.ui.index + 1; - return true; - } - if (key == previousKey) { - session.ui.index = session.ui.index - 1; - return true; - } - let expr = this.userInsertMappings.get(key); - if (expr) { - await this.evalExpression(expr, "insert"); - return true; - } - if (this.insertMappings.has(key)) { - let fn = this.insertMappings.get(key); - await Promise.resolve(fn()); - return true; - } - return false; - } - async doNormalKeymap(key) { - let expr = this.userNormalMappings.get(key); - if (expr) { - await this.evalExpression(expr, "normal"); - return true; - } - if (this.normalMappings.has(key)) { - let fn = this.normalMappings.get(key); - await Promise.resolve(fn()); - return true; - } - return false; - } - add(mode, key, fn) { - let mappings = mode == "insert" ? this.insertMappings : this.normalMappings; - if (Array.isArray(key)) { - for (let k of key) { - mappings.set(k, fn); - } - } else { - mappings.set(key, fn); - } - } - async onError(msg) { - let { nvim } = this; - await nvim.call("coc#prompt#stop_prompt", ["list"]); - window_default.showMessage(msg, "error"); - } - async evalExpression(expr, _mode) { - var _a2, _b, _c, _d, _e, _f, _g; - if (typeof expr != "string" || !expr.includes(":")) { - await this.onError(`Invalid list mapping expression: ${expr}`); - return; - } - let { manager } = this; - let { prompt } = manager; - let [key, action] = expr.split(":", 2); - if (key == "do") { - switch (action.toLowerCase()) { - case "switch": - manager.switchMatcher(); - return; - case "selectall": - await ((_a2 = manager.session) == null ? void 0 : _a2.ui.selectAll()); - return; - case "help": - await ((_b = manager.session) == null ? void 0 : _b.showHelp()); - return; - case "refresh": - await ((_c = manager.session) == null ? void 0 : _c.reloadItems()); - return; - case "exit": - await manager.cancel(); - return; - case "stop": - manager.stop(); - return; - case "cancel": - await manager.cancel(false); - return; - case "toggle": - await ((_d = manager.session) == null ? void 0 : _d.ui.toggleSelection()); - return; - case "jumpback": - (_e = manager.session) == null ? void 0 : _e.jumpBack(); - return; - case "previous": - await manager.normal("k"); - return; - case "next": - await manager.normal("j"); - return; - case "defaultaction": - await manager.doAction(); - return; - case "togglemode": - return manager.toggleMode(); - case "previewtoggle": - return manager.togglePreview(); - case "previewup": - return this.scrollPreview("up"); - case "previewdown": - return this.scrollPreview("down"); - default: - await this.onError(`'${action}' not supported`); - } - } else if (key == "prompt") { - switch (action) { - case "previous": - (_f = manager.session) == null ? void 0 : _f.history.previous(); - return; - case "next": - (_g = manager.session) == null ? void 0 : _g.history.next(); - return; - case "start": - return prompt.moveToStart(); - case "end": - return prompt.moveToEnd(); - case "left": - return prompt.moveLeft(); - case "right": - return prompt.moveRight(); - case "deleteforward": - return prompt.onBackspace(); - case "deletebackward": - return prompt.removeNext(); - case "removetail": - return prompt.removeTail(); - case "removeahead": - return prompt.removeAhead(); - case "insertregister": - prompt.insertRegister(); - return; - case "paste": - await prompt.paste(); - return; - default: - await this.onError(`prompt '${action}' not supported`); - } - } else if (key == "eval") { - await prompt.eval(action); - } else if (key == "command") { - await manager.command(action); - } else if (key == "action") { - await manager.doAction(action); - } else if (key == "feedkeys") { - await manager.feedkeys(action); - } else if (key == "normal") { - await manager.normal(action, false); - } else if (key == "normal!") { - await manager.normal(action, true); - } else if (key == "call") { - await manager.call(action); - } else if (key == "expr") { - let name2 = await manager.call(action); - if (name2) - await manager.doAction(name2); - } else { - await this.onError(`Invalid expression ${expr}`); - } - } - async doScroll(key) { - await this.manager.feedkeys(key); - } - scrollPreview(dir) { - let { nvim } = this; - nvim.pauseNotification(); - nvim.call("coc#list#scroll_preview", [dir], true); - nvim.command("redraw", true); - void nvim.resumeNotification(false, true); - } - }; - } -}); - -// src/list/prompt.ts -var import_vscode_languageserver_protocol64, logger56, Prompt; -var init_prompt = __esm({ - "src/list/prompt.ts"() { - import_vscode_languageserver_protocol64 = __toModule(require_main2()); - logger56 = require_logger2()("list-prompt"); - Prompt = class { - constructor(nvim, config) { - this.nvim = nvim; - this.config = config; - this.cusorIndex = 0; - this._input = ""; - this._mode = "insert"; - this.interactive = false; - this.requestInput = false; - this._onDidChangeInput = new import_vscode_languageserver_protocol64.Emitter(); - this.onDidChangeInput = this._onDidChangeInput.event; - } - get input() { - return this._input; - } - set input(str) { - if (this._input == str) - return; - this.cusorIndex = str.length; - this._input = str; - this.drawPrompt(); - this._onDidChangeInput.fire(this._input); - } - get mode() { - return this._mode; - } - set mode(val) { - if (val == this._mode) - return; - this._mode = val; - this.drawPrompt(); - } - set matcher(val) { - this._matcher = val; - this.drawPrompt(); - } - start(opts) { - if (opts) { - this.interactive = opts.interactive; - this.cusorIndex = opts.input.length; - this._input = opts.input; - this._mode = opts.mode; - this._matcher = opts.interactive ? "" : opts.matcher; - } - this.nvim.call("coc#prompt#start_prompt", ["list"], true); - this.drawPrompt(); - } - cancel() { - let { nvim } = this; - nvim.call("coc#prompt#stop_prompt", ["list"], true); - } - reset() { - this._input = ""; - this.cusorIndex = 0; - } - drawPrompt() { - let indicator = this.config.get("indicator", ">"); - let { cusorIndex, interactive, input, _matcher } = this; - let cmds = ['echo ""']; - if (this.mode == "insert") { - if (interactive) { - cmds.push(`echohl MoreMsg | echon 'INTERACTIVE ' | echohl None`); - } else if (_matcher) { - cmds.push(`echohl MoreMsg | echon '${_matcher.toUpperCase()} ' | echohl None`); - } - cmds.push(`echohl Special | echon '${indicator} ' | echohl None`); - if (cusorIndex == input.length) { - cmds.push(`echon '${input.replace(/'/g, "''")}'`); - cmds.push(`echohl Cursor | echon ' ' | echohl None`); - } else { - let pre = input.slice(0, cusorIndex); - if (pre) - cmds.push(`echon '${pre.replace(/'/g, "''")}'`); - cmds.push(`echohl Cursor | echon '${input[cusorIndex].replace(/'/, "''")}' | echohl None`); - let post = input.slice(cusorIndex + 1); - cmds.push(`echon '${post.replace(/'/g, "''")}'`); - } - } else { - cmds.push(`echohl MoreMsg | echo "" | echohl None`); - } - cmds.push("redraw"); - let cmd = cmds.join("|"); - this.nvim.command(cmd, true); - } - moveLeft() { - if (this.cusorIndex == 0) - return; - this.cusorIndex = this.cusorIndex - 1; - this.drawPrompt(); - } - moveRight() { - if (this.cusorIndex == this._input.length) - return; - this.cusorIndex = this.cusorIndex + 1; - this.drawPrompt(); - } - moveToEnd() { - if (this.cusorIndex == this._input.length) - return; - this.cusorIndex = this._input.length; - this.drawPrompt(); - } - moveToStart() { - if (this.cusorIndex == 0) - return; - this.cusorIndex = 0; - this.drawPrompt(); - } - onBackspace() { - let { cusorIndex, input } = this; - if (cusorIndex == 0) - return; - let pre = input.slice(0, cusorIndex); - let post = input.slice(cusorIndex); - this.cusorIndex = cusorIndex - 1; - this._input = `${pre.slice(0, pre.length - 1)}${post}`; - this.drawPrompt(); - this._onDidChangeInput.fire(this._input); - } - removeNext() { - let { cusorIndex, input } = this; - if (cusorIndex == input.length - 1) - return; - let pre = input.slice(0, cusorIndex); - let post = input.slice(cusorIndex + 1); - this._input = `${pre}${post}`; - this.drawPrompt(); - this._onDidChangeInput.fire(this._input); - } - removeWord() { - let { cusorIndex, input } = this; - if (cusorIndex == 0) - return; - let pre = input.slice(0, cusorIndex); - let post = input.slice(cusorIndex); - let remain = pre.replace(/[\w$]+([^\w$]+)?$/, ""); - this.cusorIndex = cusorIndex - (pre.length - remain.length); - this._input = `${remain}${post}`; - this.drawPrompt(); - this._onDidChangeInput.fire(this._input); - } - removeTail() { - let { cusorIndex, input } = this; - if (cusorIndex == input.length) - return; - let pre = input.slice(0, cusorIndex); - this._input = pre; - this.drawPrompt(); - this._onDidChangeInput.fire(this._input); - } - removeAhead() { - let { cusorIndex, input } = this; - if (cusorIndex == 0) - return; - let post = input.slice(cusorIndex); - this.cusorIndex = 0; - this._input = post; - this.drawPrompt(); - this._onDidChangeInput.fire(this._input); - } - async acceptCharacter(ch) { - if (this.requestInput) { - this.requestInput = false; - if (/^[0-9a-z"%#*+/:\-.]$/.test(ch)) { - let text = await this.nvim.call("getreg", ch); - text = text.replace(/\n/g, " "); - this.addText(text); - } - } else { - this.addText(ch); - } - } - insertRegister() { - this.requestInput = true; - } - async paste() { - let text = await this.nvim.eval("@*"); - text = text.replace(/\n/g, ""); - if (!text) - return; - this.addText(text); - } - async eval(expression) { - let text = await this.nvim.call("eval", [expression]); - text = text.replace(/\n/g, ""); - this.addText(text); - } - addText(text) { - let { cusorIndex, input } = this; - this.cusorIndex = cusorIndex + text.length; - let pre = input.slice(0, cusorIndex); - let post = input.slice(cusorIndex); - this._input = `${pre}${text}${post}`; - this.drawPrompt(); - this._onDidChangeInput.fire(this._input); - } - }; - } -}); - -// src/util/fuzzy.ts -function getCharCodes(str) { - let res = []; - for (let i = 0, l = str.length; i < l; i++) { - res.push(str.charCodeAt(i)); - } - return res; -} -function wordChar(ch) { - return ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90; -} -function caseMatch(input, code) { - if (input == code) - return true; - if (input >= 97 && input <= 122 && code + 32 === input) - return true; - return false; -} -function fuzzyChar(a, b) { - let ca = a.charCodeAt(0); - let cb = b.charCodeAt(0); - if (ca === cb) - return true; - if (ca >= 97 && ca <= 122 && cb + 32 === ca) - return true; - return false; -} -function fuzzyMatch(needle, text) { - let totalCount = needle.length; - if (needle.length > text.length) - return false; - let i = 0; - for (let j = 0; j < text.length; j++) { - if (i === totalCount) - break; - let code = text.charCodeAt(j); - let m = needle[i]; - if (code === m) { - i = i + 1; - continue; - } - if (m >= 97 && m <= 122 && code + 32 === m) { - i = i + 1; - continue; - } - } - return i === totalCount; -} -var init_fuzzy = __esm({ - "src/util/fuzzy.ts"() { - } -}); - -// src/list/history.ts -var logger57, InputHistory; -var init_history = __esm({ - "src/list/history.ts"() { - init_fuzzy(); - init_workspace(); - logger57 = require_logger2()("list-history"); - InputHistory = class { - constructor(prompt, name2) { - this.prompt = prompt; - this.name = name2; - this.index = -1; - this.loaded = []; - this.current = []; - this.db = workspace_default.createDatabase(`list-${name2}-history`); - this.key = Buffer.from(workspace_default.cwd).toString("base64"); - } - filter() { - let { input } = this.prompt; - if (input == this.curr) - return; - this.historyInput = ""; - let codes = getCharCodes(input); - this.current = this.loaded.filter((s) => fuzzyMatch(codes, s)); - this.index = -1; - } - get curr() { - return this.index == -1 ? null : this.current[this.index]; - } - load(input) { - let { db } = this; - input = input || ""; - let arr = db.fetch(this.key); - if (!arr || !Array.isArray(arr)) { - this.loaded = []; - } else { - this.loaded = arr; - } - this.index = -1; - this.current = this.loaded.filter((s) => s.startsWith(input)); - } - add() { - let { loaded, db, prompt } = this; - let { input } = prompt; - if (!input || input.length < 2 || input == this.historyInput) - return; - let idx = loaded.indexOf(input); - if (idx != -1) - loaded.splice(idx, 1); - loaded.push(input); - if (loaded.length > 200) { - loaded = loaded.slice(-200); - } - db.push(this.key, loaded); - } - previous() { - let { current, index } = this; - if (!current || !current.length) - return; - if (index <= 0) { - this.index = current.length - 1; - } else { - this.index = index - 1; - } - this.historyInput = this.prompt.input = current[this.index] || ""; - } - next() { - let { current, index } = this; - if (!current || !current.length) - return; - if (index == current.length - 1) { - this.index = 0; - } else { - this.index = index + 1; - } - this.historyInput = this.prompt.input = current[this.index] || ""; - } - }; - } -}); - -// src/list/ui.ts -var import_debounce5, import_vscode_languageserver_protocol65, logger58, ListUI; -var init_ui = __esm({ - "src/list/ui.ts"() { - import_debounce5 = __toModule(require_debounce()); - import_vscode_languageserver_protocol65 = __toModule(require_main2()); - init_events(); - init_util(); - init_workspace(); - logger58 = require_logger2()("list-ui"); - ListUI = class { - constructor(nvim, name2, listOptions, config) { - this.nvim = nvim; - this.name = name2; - this.listOptions = listOptions; - this.config = config; - this.newTab = false; - this.currIndex = 0; - this.items = []; - this.disposables = []; - this.selected = new Set(); - this._onDidChangeLine = new import_vscode_languageserver_protocol65.Emitter(); - this._onDidOpen = new import_vscode_languageserver_protocol65.Emitter(); - this._onDidClose = new import_vscode_languageserver_protocol65.Emitter(); - this._onDidLineChange = new import_vscode_languageserver_protocol65.Emitter(); - this._onDoubleClick = new import_vscode_languageserver_protocol65.Emitter(); - this.onDidChangeLine = this._onDidChangeLine.event; - this.onDidLineChange = this._onDidLineChange.event; - this.onDidOpen = this._onDidOpen.event; - this.onDidClose = this._onDidClose.event; - this.onDidDoubleClick = this._onDoubleClick.event; - this.signOffset = config.get("signOffset"); - this.matchHighlightGroup = config.get("matchHighlightGroup", "Search"); - this.newTab = listOptions.position == "tab"; - events_default.on("BufWinLeave", async (bufnr) => { - if (bufnr != this.bufnr || this.window == null) - return; - this.window = null; - this._onDidClose.fire(bufnr); - }, null, this.disposables); - events_default.on("CursorMoved", async (bufnr, cursor) => { - if (bufnr != this.bufnr) - return; - this.onLineChange(cursor[0] - 1); - }, null, this.disposables); - let debounced = (0, import_debounce5.default)(async (bufnr) => { - if (bufnr != this.bufnr) - return; - let [winid, start, end] = await nvim.eval('[win_getid(),line("w0"),line("w$")]'); - if (end < 300 || winid != this.winid) - return; - nvim.pauseNotification(); - this.doHighlight(start - 1, end); - nvim.command("redraw", true); - void nvim.resumeNotification(false, true); - }, 100); - this.disposables.push({ - dispose: () => { - debounced.clear(); - } - }); - events_default.on("CursorMoved", debounced, null, this.disposables); - } - get bufnr() { - var _a2; - return (_a2 = this.buffer) == null ? void 0 : _a2.id; - } - get winid() { - var _a2; - return (_a2 = this.window) == null ? void 0 : _a2.id; - } - get limitLines() { - return this.config.get("limitLines", 3e4); - } - onLineChange(index) { - if (this.currIndex == index) - return; - this.currIndex = index; - this._onDidChangeLine.fire(index); - } - set index(n) { - if (n < 0 || n >= this.items.length) - return; - let { nvim } = this; - nvim.pauseNotification(); - this.setCursor(n + 1, 0); - nvim.command("redraw", true); - void nvim.resumeNotification(false, true); - } - get index() { - return this.currIndex; - } - getItem(index) { - return this.items[index]; - } - get item() { - let { window: window2 } = this; - if (!window2) - return Promise.resolve(null); - return window2.cursor.then((cursor) => { - this.currIndex = cursor[0] - 1; - return this.items[this.currIndex]; - }); - } - async echoMessage(item) { - let { items } = this; - let idx = items.indexOf(item); - let msg = `[${idx + 1}/${items.length}] ${item.label || ""}`; - this.nvim.callTimer("coc#util#echo_lines", [[msg]], true); - } - async updateItem(item, index) { - if (!this.bufnr) - return; - let obj = Object.assign({ resolved: true }, item); - if (index < this.length) { - this.items[index] = obj; - let { nvim } = this; - nvim.pauseNotification(); - this.buffer.setOption("modifiable", true, true); - nvim.call("setbufline", [this.bufnr, index + 1, obj.label], true); - this.buffer.setOption("modifiable", false, true); - await nvim.resumeNotification(); - } - } - async getItems() { - if (this.length == 0 || !this.window) - return []; - let mode = await this.nvim.call("mode"); - if (mode == "v" || mode == "V") { - let [start, end] = await this.getSelectedRange(); - let res = []; - for (let i = start; i <= end; i++) { - let item2 = this.items[i - 1]; - if (item2) - res.push(item2); - } - return res; - } - let { selectedItems } = this; - if (selectedItems.length) - return selectedItems; - let item = await this.item; - return item == null ? [] : [item]; - } - async onMouse(event) { - let { nvim, window: window2 } = this; - if (!window2) - return; - let [winid, lnum, col] = await nvim.eval(`[v:mouse_winid,v:mouse_lnum,v:mouse_col]`); - if (event == "mouseDown") { - this.mouseDown = { winid, lnum, col, current: winid == window2.id }; - return; - } - let current = winid == window2.id; - if (current && event == "doubleClick") { - this.setCursor(lnum, 0); - this._onDoubleClick.fire(); - } - if (current && event == "mouseDrag") { - if (!this.mouseDown) - return; - await this.selectLines(this.mouseDown.lnum, lnum); - } else if (current && event == "mouseUp") { - if (!this.mouseDown) - return; - if (this.mouseDown.lnum == lnum) { - this.setCursor(lnum, 0); - nvim.command("redraw", true); - } else { - await this.selectLines(this.mouseDown.lnum, lnum); - } - } else if (!current && event == "mouseUp") { - nvim.pauseNotification(); - nvim.call("win_gotoid", winid, true); - nvim.call("cursor", [lnum, col], true); - nvim.command("redraw", true); - void nvim.resumeNotification(false, true); - } - } - async resume() { - var _a2; - let { items, selected, nvim } = this; - await this.drawItems(items, this.height, true); - if (!selected.size) - return; - nvim.pauseNotification(); - for (let lnum of selected) { - (_a2 = this.buffer) == null ? void 0 : _a2.placeSign({ lnum, id: this.signOffset + lnum, name: "CocSelected", group: "coc-list" }); - } - nvim.command("redraw", true); - void nvim.resumeNotification(false, true); - } - async toggleSelection() { - let { nvim } = this; - await nvim.call("win_gotoid", [this.winid]); - let lnum = await nvim.call("line", "."); - let mode = await nvim.call("mode"); - if (mode == "v" || mode == "V") { - let [start, end] = await this.getSelectedRange(); - let reverse = start > end; - if (reverse) - [start, end] = [end, start]; - for (let i = start; i <= end; i++) { - this.toggleLine(i); - } - this.setCursor(end, 0); - nvim.command("redraw", true); - await nvim.resumeNotification(); - return; - } - nvim.pauseNotification(); - this.toggleLine(lnum); - this.setCursor(lnum + 1, 0); - nvim.command("redraw", true); - await nvim.resumeNotification(); - } - toggleLine(lnum) { - let { selected, buffer, signOffset: signOffset2 } = this; - let exists = selected.has(lnum); - if (!exists) { - selected.add(lnum); - buffer.placeSign({ lnum, id: signOffset2 + lnum, name: "CocSelected", group: "coc-list" }); - } else { - selected.delete(lnum); - buffer.unplaceSign({ id: signOffset2 + lnum, group: "coc-list" }); - } - } - async selectLines(start, end) { - let { nvim, signOffset: signOffset2, buffer, length } = this; - this.clearSelection(); - let { selected } = this; - nvim.pauseNotification(); - let reverse = start > end; - if (reverse) - [start, end] = [end, start]; - for (let i = start; i <= end; i++) { - if (i > length) - break; - selected.add(i); - buffer.placeSign({ lnum: i, id: signOffset2 + i, name: "CocSelected", group: "coc-list" }); - } - this.setCursor(end, 0); - nvim.command("redraw", true); - await nvim.resumeNotification(); - } - async selectAll() { - let { length } = this; - if (length == 0) - return; - await this.selectLines(1, length); - } - clearSelection() { - let { selected, signOffset: signOffset2, buffer } = this; - if (selected.size > 0) { - let signIds = []; - for (let lnum of selected) { - signIds.push(signOffset2 + lnum); - } - buffer == null ? void 0 : buffer.unplaceSign({ group: "coc-list" }); - this.selected.clear(); - } - } - get ready() { - if (this.window) - return Promise.resolve(); - return new Promise((resolve3) => { - let disposable = this.onDidLineChange(() => { - disposable.dispose(); - resolve3(); - }); - }); - } - async drawItems(items, height, reload = false) { - const { nvim, name: name2, listOptions } = this; - this.items = items.length > this.limitLines ? items.slice(0, this.limitLines) : items; - if (!this.window) { - let { position, numberSelect } = listOptions; - let [bufnr, winid] = await nvim.call("coc#list#create", [position, height, name2, numberSelect]); - this.height = height; - this.buffer = nvim.createBuffer(bufnr); - let win = this.window = nvim.createWindow(winid); - let statusSegments = this.config.get("statusLineSegments"); - if (statusSegments) - win.setOption("statusline", statusSegments.join(" "), true); - this._onDidOpen.fire(this.bufnr); - } - const lines = this.items.map((item) => item.label); - let newIndex = reload ? this.currIndex : 0; - this.setLines(lines, false, newIndex); - this._onDidLineChange.fire(this.currIndex + 1); - } - appendItems(items) { - let curr = this.items.length; - if (curr >= this.limitLines) - return; - let max = this.limitLines - curr; - let append = items.slice(0, max); - this.items = this.items.concat(append); - this.setLines(append.map((item) => item.label), curr > 0, this.currIndex); - } - setLines(lines, append = false, index) { - let { nvim, buffer, window: window2 } = this; - if (!buffer || !window2) - return; - nvim.pauseNotification(); - if (!append) { - nvim.call("coc#compat#clear_matches", [window2.id], true); - if (!lines.length) { - lines = ["No results, press ? on normal mode to get help."]; - nvim.call("coc#compat#matchaddpos", ["Comment", [[1]], 99, window2.id], true); - } - } - buffer.setOption("modifiable", true, true); - void buffer.setLines(lines, { start: append ? -1 : 0, end: -1, strictIndexing: false }, true); - buffer.setOption("modifiable", false, true); - if (!append && index == 0) { - this.doHighlight(0, 299); - } else { - let height = this.newTab ? workspace_default.env.lines : this.height; - this.doHighlight(Math.max(0, index - height), Math.min(index + height + 1, this.length - 1)); - } - if (!append) { - this.currIndex = index; - window2.setCursor([index + 1, 0], true); - } - nvim.command("redraws", true); - void nvim.resumeNotification(false, true); - } - restoreWindow() { - if (this.newTab) - return; - let { winid, height } = this; - if (winid && height) { - this.nvim.call("coc#list#restore", [winid, height], true); - } - } - get length() { - return this.items.length; - } - get selectedItems() { - let { selected, items } = this; - let res = []; - for (let i of selected) { - if (items[i - 1]) - res.push(items[i - 1]); - } - return res; - } - doHighlight(start, end) { - let { items } = this; - let groups = []; - for (let i = start; i <= Math.min(end, items.length - 1); i++) { - let { ansiHighlights, highlights } = items[i]; - if (ansiHighlights) { - for (let hi of ansiHighlights) { - let { span, hlGroup } = hi; - groups.push({ hlGroup, priority: 9, pos: [i + 1, span[0] + 1, span[1] - span[0]] }); - } - } - if (highlights && Array.isArray(highlights.spans)) { - let { spans, hlGroup } = highlights; - for (let span of spans) { - groups.push({ hlGroup: hlGroup || this.matchHighlightGroup, priority: 11, pos: [i + 1, span[0] + 1, span[1] - span[0]] }); - } - } - } - this.nvim.call("coc#compat#matchaddgroups", [this.window.id, groups], true); - } - setCursor(lnum, col) { - var _a2; - let { items } = this; - let max = items.length == 0 ? 1 : items.length; - if (lnum > max) - return; - this.onLineChange(lnum - 1); - (_a2 = this.window) == null ? void 0 : _a2.setCursor([lnum, col], true); - } - async getSelectedRange() { - let { nvim } = this; - await nvim.call("coc#prompt#stop_prompt", ["list"]); - await nvim.eval('feedkeys("\\", "in")'); - let [, start] = await nvim.call("getpos", "'<"); - let [, end] = await nvim.call("getpos", "'>"); - this.nvim.call("coc#prompt#start_prompt", ["list"], true); - return [start, end]; - } - reset() { - if (this.window) { - this.window = null; - this.buffer = null; - } - } - dispose() { - disposeAll(this.disposables); - this.nvim.call("coc#window#close", [this.winid || -1], true); - this.window = null; - this.buffer = null; - this.items = []; - this._onDidChangeLine.dispose(); - this._onDidOpen.dispose(); - this._onDidClose.dispose(); - this._onDidLineChange.dispose(); - this._onDoubleClick.dispose(); - } - }; - } -}); - -// src/util/score.ts -function getMatchResult(text, query, filename = "") { - if (!text) - return { score: 0 }; - if (!query) - return { score: 1 }; - let matches = []; - let codes = getCharCodes(query); - let filenameIdx = filename ? text.indexOf(filename) : -1; - let matchBase = filenameIdx != -1 && fuzzyMatch(codes, filename); - let score5 = 0; - let c = query[0]; - let idx = 0; - if (matchBase) { - if (filename.startsWith(c)) { - score5 = score5 + 2; - idx = filenameIdx + 1; - matches.push(filenameIdx); - } else if (filename[0].toLowerCase() == c) { - score5 = score5 + 1.5; - idx = filenameIdx + 1; - matches.push(filenameIdx); - } else { - for (let i = 1; i < filename.length; i++) { - if (fuzzyChar(c, filename[i])) { - score5 = score5 + 1; - idx = filenameIdx + i + 1; - matches.push(filenameIdx + i); - break; - } - } - } - } else if (text.startsWith(c)) { - score5 = score5 + 1; - matches.push(0); - idx = 1; - } else { - for (let i = 1; i < text.length; i++) { - let pre = text[i - 1]; - if (pre == import_path19.sep && text[i] == c) { - score5 = score5 + 1; - matches.push(i); - idx = i + 1; - break; - } - } - if (idx == 0) { - for (let i = 0; i < text.length; i++) { - if (fuzzyChar(c, text[i])) { - score5 = score5 + 0.5; - matches.push(i); - idx = i + 1; - break; - } - } - } - } - if (idx == 0) - return { score: 0 }; - if (codes.length == 1) - return { score: score5, matches }; - return nextResult(codes.slice(1), text, idx, { score: score5, matches }); -} -function nextResult(codes, text, idx, curr) { - let { score: score5, matches } = curr; - let results = []; - let c = codes[0]; - let remain = codes.slice(1); - let result; - function getRemianResult(index) { - if (!result) - return; - if (remain.length == 0) { - results.push(result); - } else if (result) { - let res = nextResult(remain, text, index, result); - if (res) - results.push(res); - } - } - let followed = idx < text.length ? text[idx].charCodeAt(0) : null; - if (!followed) - return null; - if (followed == c) { - result = { score: score5 + 1, matches: matches.concat([idx]) }; - getRemianResult(idx + 1); - } else if (caseMatch(c, followed)) { - result = { score: score5 + 0.5, matches: matches.concat([idx]) }; - getRemianResult(idx + 1); - } - if (idx + 1 < text.length) { - for (let i = idx + 1; i < text.length; i++) { - let ch = text[i].charCodeAt(0); - if (text[i - 1] == import_path19.sep && caseMatch(c, ch)) { - let add = c == ch ? 1 : 0.5; - result = { score: score5 + add, matches: matches.concat([i]) }; - getRemianResult(i + 1); - break; - } - } - for (let i = idx + 1; i < text.length; i++) { - let ch = text[i].charCodeAt(0); - if (caseMatch(c, ch)) { - let add = c == ch ? 0.5 : 0.2; - result = { score: score5 + add, matches: matches.concat([i]) }; - getRemianResult(i + 1); - break; - } - } - } - return results.length ? bestResult(results) : null; -} -function bestResult(results) { - let res = results[0]; - for (let i = 1; i < results.length; i++) { - if (results[i].score > res.score) { - res = results[i]; - } - } - return res; -} -var import_path19; -var init_score = __esm({ - "src/util/score.ts"() { - import_path19 = __toModule(require("path")); - init_fuzzy(); - } -}); - -// src/list/worker.ts -function getFilterLabel(item) { - return item.filterText != null ? patchLine(item.filterText, item.label) : item.label; -} -function parseInput(input) { - let res = []; - let startIdx = 0; - let currIdx = 0; - let prev = ""; - for (; currIdx < input.length; currIdx++) { - let ch = input[currIdx]; - if (ch.charCodeAt(0) === 32) { - if (prev && prev != "\\" && startIdx != currIdx) { - res.push(input.slice(startIdx, currIdx)); - startIdx = currIdx + 1; - } - } else { - } - prev = ch; - } - if (startIdx != input.length) { - res.push(input.slice(startIdx, input.length)); - } - return res.map((s) => s.replace(/\\\s/g, " ").trim()).filter((s) => s.length > 0); -} -var import_vscode_languageserver_protocol66, logger59, controlCode, Worker; -var init_worker = __esm({ - "src/list/worker.ts"() { - import_vscode_languageserver_protocol66 = __toModule(require_main2()); - init_ansiparse(); - init_diff(); - init_fzy(); - init_score(); - init_string(); - init_window(); - init_workspace(); - logger59 = require_logger2()("list-worker"); - controlCode = ""; - Worker = class { - constructor(nvim, list2, prompt, listOptions, config) { - this.nvim = nvim; - this.list = list2; - this.prompt = prompt; - this.listOptions = listOptions; - this.config = config; - this._loading = false; - this.totalItems = []; - this._onDidChangeItems = new import_vscode_languageserver_protocol66.Emitter(); - this._onDidChangeLoading = new import_vscode_languageserver_protocol66.Emitter(); - this.onDidChangeItems = this._onDidChangeItems.event; - this.onDidChangeLoading = this._onDidChangeLoading.event; - } - set loading(loading) { - if (this._loading == loading) - return; - this._loading = loading; - this._onDidChangeLoading.fire(loading); - } - get isLoading() { - return this._loading; - } - async loadItems(context, reload = false) { - let { list: list2, listOptions } = this; - this.loading = true; - let { interactive } = listOptions; - this.tokenSource = new import_vscode_languageserver_protocol66.CancellationTokenSource(); - let token = this.tokenSource.token; - let items = await list2.loadItems(context, token); - if (token.isCancellationRequested) - return; - if (!items || Array.isArray(items)) { - this.tokenSource = null; - items = items || []; - this.totalItems = items.map((item) => { - item.label = this.fixLabel(item.label); - this.parseListItemAnsi(item); - return item; - }); - this.loading = false; - let filtered; - if (!interactive) { - filtered = this.filterItems(items); - } else { - filtered = this.convertToHighlightItems(items); - } - this._onDidChangeItems.fire({ - items: filtered, - reload, - finished: true - }); - } else { - let task = items; - let totalItems = this.totalItems = []; - let count = 0; - let currInput = context.input; - let timer; - let lastTs; - let _onData = (finished) => { - lastTs = Date.now(); - if (count >= totalItems.length) - return; - let inputChanged = this.input != currInput; - if (interactive && inputChanged) - return; - if (count == 0 || inputChanged) { - currInput = this.input; - count = totalItems.length; - let items2; - if (interactive) { - items2 = this.convertToHighlightItems(totalItems); - } else { - items2 = this.filterItems(totalItems); - } - this._onDidChangeItems.fire({ items: items2, reload, append: false, finished }); - } else { - let remain = totalItems.slice(count); - count = totalItems.length; - let items2; - if (!interactive) { - items2 = this.filterItems(remain); - } else { - items2 = this.convertToHighlightItems(remain); - } - this._onDidChangeItems.fire({ items: items2, append: true, finished }); - } - }; - task.on("data", (item) => { - if (timer) - clearTimeout(timer); - if (token.isCancellationRequested) - return; - if (interactive && this.input != currInput) - return; - item.label = this.fixLabel(item.label); - this.parseListItemAnsi(item); - totalItems.push(item); - if (!lastTs && totalItems.length == 500 || Date.now() - lastTs > 200) { - _onData(); - } else { - timer = setTimeout(() => _onData(), 50); - } - }); - let onEnd = () => { - if (task == null) - return; - this.tokenSource = null; - task = null; - this.loading = false; - disposable.dispose(); - if (timer) - clearTimeout(timer); - if (totalItems.length == 0) { - this._onDidChangeItems.fire({ items: [], finished: true }); - } else { - _onData(true); - } - }; - let disposable = token.onCancellationRequested(() => { - if (task) { - task.dispose(); - onEnd(); - } - }); - task.on("error", async (error) => { - if (task == null) - return; - task = null; - this.tokenSource = null; - this.loading = false; - disposable.dispose(); - if (timer) - clearTimeout(timer); - this.nvim.call("coc#prompt#stop_prompt", ["list"], true); - window_default.showMessage(`Task error: ${error.toString()}`, "error"); - logger59.error(error); - }); - task.on("end", onEnd); - } - } - drawItems() { - let { totalItems } = this; - let items; - items = this.filterItems(totalItems); - this._onDidChangeItems.fire({ items, finished: true }); - } - stop() { - if (this.tokenSource) { - this.tokenSource.cancel(); - this.tokenSource = null; - } - this.loading = false; - } - get length() { - return this.totalItems.length; - } - get input() { - return this.prompt.input; - } - convertToHighlightItems(items) { - let { input } = this; - if (!input) - return []; - return items.map((item) => { - let filterLabel = getFilterLabel(item); - let res = getMatchResult(filterLabel, input); - if (!(res == null ? void 0 : res.score)) - return item; - let highlights = this.getHighlights(filterLabel, res.matches); - return Object.assign({}, item, { highlights }); - }); - } - filterItems(items) { - let { input } = this; - let { sort, matcher, ignorecase } = this.listOptions; - let inputs = this.config.extendedSearchMode ? parseInput(input) : [input]; - if (input.length == 0 || inputs.length == 0) - return items; - if (matcher == "strict") { - let filtered2 = []; - for (let item of items) { - let spans = []; - let filterLabel = getFilterLabel(item); - let match = true; - for (let input2 of inputs) { - let idx2 = ignorecase ? filterLabel.toLowerCase().indexOf(input2.toLowerCase()) : filterLabel.indexOf(input2); - if (idx2 == -1) { - match = false; - break; - } - spans.push([byteIndex(filterLabel, idx2), byteIndex(filterLabel, idx2 + byteLength(input2))]); - } - if (match) { - filtered2.push(Object.assign({}, item, { - highlights: { spans } - })); - } - } - return filtered2; - } - if (matcher == "regex") { - let filtered2 = []; - let flags = ignorecase ? "iu" : "u"; - let regexes = inputs.reduce((p, c) => { - try { - let regex = new RegExp(c, flags); - p.push(regex); - } catch (e) { - } - return p; - }, []); - for (let item of items) { - let spans = []; - let filterLabel = getFilterLabel(item); - let match = true; - for (let regex of regexes) { - let ms = filterLabel.match(regex); - if (ms == null) { - match = false; - break; - } - spans.push([byteIndex(filterLabel, ms.index), byteIndex(filterLabel, ms.index + byteLength(ms[0]))]); - } - if (match) { - filtered2.push(Object.assign({}, item, { - highlights: { spans } - })); - } - } - return filtered2; - } - let filtered = []; - let idx = 0; - for (let item of items) { - let filterText = item.filterText || item.label; - let matchScore2 = 0; - let matches = []; - let filterLabel = getFilterLabel(item); - let match = true; - for (let input2 of inputs) { - if (!hasMatch(input2, filterText)) { - match = false; - break; - } - matches.push(...positions(input2, filterLabel)); - if (sort) - matchScore2 += score2(input2, filterText); - } - if (!match) - continue; - let obj = Object.assign({}, item, { - sortText: typeof item.sortText === "string" ? item.sortText : String.fromCharCode(idx), - score: matchScore2, - highlights: this.getHighlights(filterLabel, matches) - }); - filtered.push(obj); - idx = idx + 1; - } - if (sort && filtered.length) { - filtered.sort((a, b) => { - if (a.score != b.score) - return b.score - a.score; - if (a.sortText > b.sortText) - return 1; - return -1; - }); - } - return filtered; - } - getHighlights(text, matches) { - let spans = []; - if (matches && matches.length) { - let start = matches.shift(); - let next = matches.shift(); - let curr = start; - while (next) { - if (next == curr + 1) { - curr = next; - next = matches.shift(); - continue; - } - spans.push([byteIndex(text, start), byteIndex(text, curr) + 1]); - start = next; - curr = start; - next = matches.shift(); - } - spans.push([byteIndex(text, start), byteIndex(text, curr) + 1]); - } - return { spans }; - } - parseListItemAnsi(item) { - let { label } = item; - if (item.ansiHighlights || !label.includes(controlCode)) - return; - let { line, highlights } = parseAnsiHighlights(label); - item.label = line; - item.ansiHighlights = highlights; - } - fixLabel(label) { - let { columns } = workspace_default.env; - label = label.split("\n").join(" "); - return label.slice(0, columns * 2); - } - dispose() { - this.stop(); - } - }; - } -}); - -// src/list/session.ts -var import_debounce6, frames2, logger60, ListSession; -var init_session = __esm({ - "src/list/session.ts"() { - import_debounce6 = __toModule(require_debounce()); - init_mutex(); - init_extensions2(); - init_highligher(); - init_util(); - init_workspace(); - init_window(); - init_history(); - init_ui(); - init_worker(); - frames2 = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"]; - logger60 = require_logger2()("list-session"); - ListSession = class { - constructor(nvim, prompt, list2, listOptions, listArgs = [], config) { - this.nvim = nvim; - this.prompt = prompt; - this.list = list2; - this.listOptions = listOptions; - this.listArgs = listArgs; - this.config = config; - this.loadingFrame = ""; - this.hidden = false; - this.disposables = []; - this.mutex = new Mutex(); - this.args = []; - this.ui = new ListUI(nvim, list2.name, listOptions, config); - this.history = new InputHistory(prompt, list2.name); - this.worker = new Worker(nvim, list2, prompt, listOptions, { - interactiveDebounceTime: config.get("interactiveDebounceTime", 100), - extendedSearchMode: config.get("extendedSearchMode", true) - }); - this.interactiveDebounceTime = config.get("interactiveDebounceTime", 100); - let debouncedChangeLine = (0, import_debounce6.default)(async () => { - let [previewing, currwin, lnum] = await nvim.eval('[coc#list#has_preview(),win_getid(),line(".")]'); - if (previewing && currwin == this.winid) { - await this.doPreview(lnum - 1); - } - }, 50); - this.disposables.push({ - dispose: () => { - debouncedChangeLine.clear(); - } - }); - this.ui.onDidChangeLine(debouncedChangeLine, null, this.disposables); - this.ui.onDidChangeLine(this.resolveItem, this, this.disposables); - this.ui.onDidLineChange(this.resolveItem, this, this.disposables); - let debounced = (0, import_debounce6.default)(async () => { - let { autoPreview } = this.listOptions; - if (!autoPreview) { - let [previewing, mode] = await nvim.eval("[coc#list#has_preview(),mode()]"); - if (!previewing || mode != "n") - return; - } - await this.doAction("preview"); - }, 50); - this.disposables.push({ - dispose: () => { - debounced.clear(); - } - }); - this.ui.onDidLineChange(debounced, null, this.disposables); - this.ui.onDidLineChange(() => { - this.updateStatus(); - }, null, this.disposables); - this.ui.onDidOpen(async () => { - if (typeof this.list.doHighlight == "function") { - this.list.doHighlight(); - } - if (this.listOptions.first) { - await this.doAction(); - } - }, null, this.disposables); - this.ui.onDidClose(async () => { - await this.hide(); - }, null, this.disposables); - this.ui.onDidDoubleClick(async () => { - await this.doAction(); - }, null, this.disposables); - this.worker.onDidChangeItems(async ({ items, reload, append, finished }) => { - let release = await this.mutex.acquire(); - if (!this.hidden) { - try { - if (append) { - this.ui.appendItems(items); - } else { - let height = this.config.get("height", 10); - if (finished && !listOptions.interactive && listOptions.input.length == 0) { - height = Math.min(items.length, height); - } - await this.ui.drawItems(items, Math.max(1, height), reload); - } - } catch (e) { - nvim.echoError(e); - } - } - release(); - }, null, this.disposables); - this.worker.onDidChangeLoading((loading) => { - if (this.hidden) - return; - if (loading) { - this.interval = setInterval(() => { - let idx = Math.floor(new Date().getMilliseconds() / 100); - this.loadingFrame = frames2[idx]; - this.updateStatus(); - }, 100); - } else { - if (this.interval) { - this.loadingFrame = ""; - clearInterval(this.interval); - this.interval = null; - } - this.updateStatus(); - } - }, null, this.disposables); - } - async start(args) { - this.args = args; - this.cwd = workspace_default.cwd; - this.hidden = false; - let { listOptions, listArgs } = this; - let res = await this.nvim.eval('[win_getid(),bufnr("%"),winheight("%")]'); - this.listArgs = listArgs; - this.history.load(listOptions.input || ""); - this.window = this.nvim.createWindow(res[0]); - this.buffer = this.nvim.createBuffer(res[1]); - this.savedHeight = res[2]; - await this.worker.loadItems(this.context); - } - async reloadItems() { - if (!this.window) - return; - let bufnr = await this.nvim.call("winbufnr", [this.window.id]); - if (bufnr == -1) - return; - this.buffer = this.nvim.createBuffer(bufnr); - await this.worker.loadItems(this.context, true); - } - async call(fname) { - var _a2, _b; - await this.nvim.call("coc#prompt#stop_prompt", ["list"]); - let targets = await this.ui.getItems(); - let context = { - name: this.name, - args: this.listArgs, - input: this.prompt.input, - winid: (_a2 = this.window) == null ? void 0 : _a2.id, - bufnr: (_b = this.buffer) == null ? void 0 : _b.id, - targets - }; - let res = await this.nvim.call(fname, [context]); - this.prompt.start(); - return res; - } - async chooseAction() { - let { nvim } = this; - let { actions, defaultAction } = this.list; - let names = actions.map((o) => o.name); - let idx = names.indexOf(defaultAction); - if (idx != -1) { - names.splice(idx, 1); - names.unshift(defaultAction); - } - let shortcuts = new Set(); - let choices = []; - let invalids = []; - for (let name2 of names) { - let i = 0; - for (let ch of name2) { - if (!shortcuts.has(ch)) { - shortcuts.add(ch); - choices.push(`${name2.slice(0, i)}&${name2.slice(i)}`); - break; - } - i++; - } - if (i == name2.length) { - invalids.push(name2); - } - } - if (invalids.length) { - names = names.filter((s) => !invalids.includes(s)); - } - await nvim.call("coc#prompt#stop_prompt", ["list"]); - let n = await nvim.call("confirm", ["Choose action:", choices.join("\n")]); - await wait(10); - this.prompt.start(); - if (n) - await this.doAction(names[n - 1]); - if (invalids.length) { - nvim.echoError(`Can't create shortcut for actions: ${invalids.join(",")} of "${this.name}" list`); - } - } - async doAction(name2) { - let { list: list2 } = this; - name2 = name2 || list2.defaultAction; - let action = list2.actions.find((o) => o.name == name2); - if (!action) { - window_default.showMessage(`Action ${name2} not found`, "error"); - return; - } - let items; - if (name2 == "preview") { - let item = await this.ui.item; - items = item ? [item] : []; - } else { - items = await this.ui.getItems(); - } - if (items.length) - await this.doItemAction(items, action); - } - async doPreview(index) { - let item = this.ui.getItem(index); - let action = this.list.actions.find((o) => o.name == "preview"); - if (!item || !action) - return; - await this.doItemAction([item], action); - } - async first() { - await this.doDefaultAction(0); - } - async last() { - await this.doDefaultAction(this.ui.length - 1); - } - async previous() { - await this.doDefaultAction(this.ui.index - 1); - } - async next() { - await this.doDefaultAction(this.ui.index + 1); - } - async doDefaultAction(index) { - let { ui } = this; - let item = ui.getItem(index); - if (!item) - return; - ui.index = index; - await this.doItemAction([item], this.defaultAction); - await ui.echoMessage(item); - } - get name() { - return this.list.name; - } - get winid() { - return this.ui.winid; - } - get length() { - return this.ui.length; - } - get defaultAction() { - let { defaultAction, actions } = this.list; - let action = actions.find((o) => o.name == defaultAction); - if (!action) - throw new Error(`default action "${defaultAction}" not found`); - return action; - } - async hide() { - if (this.hidden) - return; - let { nvim, interval } = this; - if (interval) - clearInterval(interval); - this.hidden = true; - this.worker.stop(); - this.history.add(); - let { winid } = this.ui; - this.ui.reset(); - if (this.window && winid) { - await nvim.call("coc#list#hide", [this.window.id, this.savedHeight, winid]); - if (workspace_default.isVim) { - nvim.command("redraw", true); - await wait(10); - } - } - nvim.call("coc#prompt#stop_prompt", ["list"], true); - } - toggleMode() { - let mode = this.prompt.mode == "normal" ? "insert" : "normal"; - this.prompt.mode = mode; - this.listOptions.mode = mode; - this.updateStatus(); - } - stop() { - this.worker.stop(); - } - async resolveItem() { - let index = this.ui.index; - let item = this.ui.getItem(index); - if (!item || item.resolved) - return; - let { list: list2 } = this; - if (typeof list2.resolveItem == "function") { - let resolved = await Promise.resolve(list2.resolveItem(item)); - if (resolved && index == this.ui.index) { - await this.ui.updateItem(resolved, index); - } - } - } - async showHelp() { - await this.hide(); - let { list: list2, nvim } = this; - if (!list2) - return; - nvim.pauseNotification(); - nvim.command(`tabe +setl\\ previewwindow [LIST HELP]`, true); - nvim.command("setl nobuflisted noswapfile buftype=nofile bufhidden=wipe", true); - await nvim.resumeNotification(); - let hasOptions = list2.options && list2.options.length; - let buf = await nvim.buffer; - let highligher = new Highlighter(); - highligher.addLine("NAME", "Label"); - highligher.addLine(` ${list2.name} - ${list2.description || ""} -`); - highligher.addLine("SYNOPSIS", "Label"); - highligher.addLine(` :CocList [LIST OPTIONS] ${list2.name}${hasOptions ? " [ARGUMENTS]" : ""} -`); - if (list2.detail) { - highligher.addLine("DESCRIPTION", "Label"); - let lines = list2.detail.split("\n").map((s) => " " + s); - highligher.addLine(lines.join("\n") + "\n"); - } - if (hasOptions) { - highligher.addLine("ARGUMENTS", "Label"); - highligher.addLine(""); - for (let opt of list2.options) { - highligher.addLine(opt.name, "Special"); - highligher.addLine(` ${opt.description}`); - highligher.addLine(""); - } - highligher.addLine(""); - } - let config = workspace_default.getConfiguration(`list.source.${list2.name}`); - if (Object.keys(config).length) { - highligher.addLine("CONFIGURATIONS", "Label"); - highligher.addLine(""); - let props = {}; - extensions_default.all.forEach((extension) => { - let { packageJSON } = extension; - let { contributes } = packageJSON; - if (!contributes) - return; - let { configuration } = contributes; - if (configuration) { - let { properties } = configuration; - if (properties) { - for (let key of Object.keys(properties)) { - props[key] = properties[key]; - } - } - } - }); - for (let key of Object.keys(config)) { - let val = config[key]; - let name2 = `list.source.${list2.name}.${key}`; - let description = props[name2] && props[name2].description ? props[name2].description : key; - highligher.addLine(` "${name2}"`, "MoreMsg"); - highligher.addText(` - ${description}, current value: `); - highligher.addText(JSON.stringify(val), "Special"); - } - highligher.addLine(""); - } - highligher.addLine("ACTIONS", "Label"); - highligher.addLine(` ${list2.actions.map((o) => o.name).join(", ")}`); - highligher.addLine(""); - highligher.addLine(`see ':h coc-list-options' for available list options.`, "Comment"); - nvim.pauseNotification(); - highligher.render(buf, 0, -1); - nvim.command("setl nomod", true); - nvim.command("setl nomodifiable", true); - nvim.command("normal! gg", true); - nvim.command("nnoremap q :bd!", true); - await nvim.resumeNotification(); - } - switchMatcher() { - let { matcher, interactive } = this.listOptions; - if (interactive) - return; - const list2 = ["fuzzy", "strict", "regex"]; - let idx = list2.indexOf(matcher) + 1; - if (idx >= list2.length) - idx = 0; - this.listOptions.matcher = list2[idx]; - this.prompt.matcher = list2[idx]; - this.worker.drawItems(); - } - updateStatus() { - let { ui, list: list2, nvim } = this; - if (!ui.winid) - return; - let buf = nvim.createBuffer(ui.bufnr); - let status = { - mode: this.prompt.mode.toUpperCase(), - args: this.args.join(" "), - name: list2.name, - cwd: this.cwd, - loading: this.loadingFrame, - total: this.worker.length - }; - nvim.pauseNotification(); - buf.setVar("list_status", status, true); - nvim.command("redraws", true); - nvim.resumeNotification(false, true).logError(); - } - get context() { - let { winid } = this.ui; - return { - options: this.listOptions, - args: this.listArgs, - input: this.prompt.input, - cwd: workspace_default.cwd, - window: this.window, - buffer: this.buffer, - listWindow: winid ? this.nvim.createWindow(winid) : void 0 - }; - } - onMouseEvent(key) { - switch (key) { - case "": - return this.ui.onMouse("mouseDown"); - case "": - return this.ui.onMouse("mouseDrag"); - case "": - return this.ui.onMouse("mouseUp"); - case "<2-LeftMouse>": - return this.ui.onMouse("doubleClick"); - } - } - async doNumberSelect(ch) { - if (!this.listOptions.numberSelect) - return false; - let code = ch.charCodeAt(0); - if (code >= 48 && code <= 57) { - let n = Number(ch); - if (n == 0) - n = 10; - if (this.ui.length >= n) { - this.nvim.pauseNotification(); - this.ui.setCursor(n, 0); - await this.nvim.resumeNotification(); - await this.doAction(); - return true; - } - } - return false; - } - jumpBack() { - let { window: window2, nvim } = this; - if (window2) { - nvim.pauseNotification(); - nvim.call("coc#prompt#stop_prompt", ["list"], true); - this.nvim.call("win_gotoid", [window2.id], true); - nvim.resumeNotification(false, true).logError(); - } - } - async resume() { - if (this.winid) - await this.hide(); - let res = await this.nvim.eval('[win_getid(),bufnr("%"),winheight("%")]'); - this.hidden = false; - this.window = this.nvim.createWindow(res[0]); - this.buffer = this.nvim.createBuffer(res[1]); - this.savedHeight = res[2]; - this.prompt.start(); - await this.ui.resume(); - if (this.listOptions.autoPreview) { - await this.doAction("preview"); - } - } - async doItemAction(items, action) { - let { noQuit } = this.listOptions; - let { nvim } = this; - let persistAction = action.persist === true || action.name == "preview"; - let persist = this.winid && (persistAction || noQuit); - try { - if (persist) { - if (!persistAction) { - nvim.pauseNotification(); - nvim.call("coc#prompt#stop_prompt", ["list"], true); - nvim.call("win_gotoid", [this.context.window.id], true); - await nvim.resumeNotification(); - } - } else { - await this.hide(); - } - if (action.multiple) { - await Promise.resolve(action.execute(items, this.context)); - } else if (action.parallel) { - await Promise.all(items.map((item) => Promise.resolve(action.execute(item, this.context)))); - } else { - for (let item of items) { - await Promise.resolve(action.execute(item, this.context)); - } - } - if (persist) { - this.ui.restoreWindow(); - } - if (action.reload && persist) - await this.worker.loadItems(this.context, true); - } catch (e) { - window_default.showMessage(e.message, "error"); - logger60.error(`Error on action "${action.name}"`, e); - } - } - onInputChange() { - if (this.timer) - clearTimeout(this.timer); - let len = this.worker.length; - this.listOptions.input = this.prompt.input; - if (this.listOptions.interactive) { - this.worker.stop(); - this.timer = setTimeout(async () => { - await this.worker.loadItems(this.context); - }, this.interactiveDebounceTime); - } else if (len) { - let wait2 = Math.max(Math.min(Math.floor(len / 200), 300), 50); - this.timer = setTimeout(() => { - this.worker.drawItems(); - }, wait2); - } - } - dispose() { - if (!this.hidden) { - this.hidden = true; - let { winid } = this.ui; - this.ui.reset(); - if (this.window && winid) { - this.nvim.call("coc#list#hide", [this.window.id, this.savedHeight, winid], true); - } - } - if (this.interval) { - clearInterval(this.interval); - } - if (this.timer) { - clearTimeout(this.timer); - } - disposeAll(this.disposables); - this.worker.dispose(); - this.ui.dispose(); - } - }; - } -}); - -// src/list/commandTask.ts -var import_child_process5, import_events21, import_readline3, logger61, CommandTask; -var init_commandTask = __esm({ - "src/list/commandTask.ts"() { - import_child_process5 = __toModule(require("child_process")); - import_events21 = __toModule(require("events")); - import_readline3 = __toModule(require("readline")); - init_util(); - logger61 = require_logger2()("list-commandTask"); - CommandTask = class extends import_events21.EventEmitter { - constructor(opt) { - super(); - this.opt = opt; - this.disposables = []; - this.start(); - } - start() { - let { cmd, args, cwd, onLine } = this.opt; - let proc = (0, import_child_process5.spawn)(cmd, args, { cwd, windowsHide: true }); - this.disposables.push({ - dispose: () => { - proc.kill(); - } - }); - proc.on("error", (e) => { - this.emit("error", e.message); - }); - proc.stderr.on("data", (chunk) => { - logger61.error(`[${cmd} Error]`, chunk.toString("utf8")); - }); - const rl = import_readline3.default.createInterface(proc.stdout); - rl.on("line", (line) => { - let res = onLine(line); - if (res) - this.emit("data", res); - }); - rl.on("close", () => { - this.emit("end"); - }); - } - dispose() { - disposeAll(this.disposables); - } - }; - } -}); - -// src/list/basic.ts -function getFiletype(filetype) { - switch (filetype) { - case "javascriptreact": - return "javascript"; - case "typescriptreact": - return "typescript"; - case "latex": - return "tex"; - default: - if (filetype.indexOf(".") !== -1) - return filetype.split(".")[0]; - return filetype; - } -} -var import_fs19, import_path20, import_readline4, import_vscode_languageserver_protocol67, logger62, BasicList; -var init_basic = __esm({ - "src/list/basic.ts"() { - import_fs19 = __toModule(require("fs")); - import_path20 = __toModule(require("path")); - import_readline4 = __toModule(require("readline")); - import_vscode_languageserver_protocol67 = __toModule(require_main2()); - init_esm2(); - init_util(); - init_fs(); - init_position(); - init_workspace(); - init_commandTask(); - init_configuration4(); - logger62 = require_logger2()("list-basic"); - BasicList = class { - constructor(nvim) { - this.nvim = nvim; - this.defaultAction = "open"; - this.actions = []; - this.options = []; - this.disposables = []; - this.config = new ListConfiguration(); - } - get alignColumns() { - return this.config.get("alignColumns", false); - } - get hlGroup() { - return this.config.get("previewHighlightGroup", "Search"); - } - get previewHeight() { - return this.config.get("maxPreviewHeight", 12); - } - get splitRight() { - return this.config.get("previewSplitRight", false); - } - get toplineStyle() { - return this.config.get("previewToplineStyle", "offset"); - } - get toplineOffset() { - return this.config.get("previewToplineOffset", 3); - } - parseArguments(args) { - if (!this.optionMap) { - this.optionMap = new Map(); - for (let opt of this.options) { - let parts = opt.name.split(/,\s*/g).map((s) => s.replace(/\s+.*/g, "")); - let name2 = opt.key ? opt.key : parts[parts.length - 1].replace(/^-/, ""); - for (let p of parts) { - this.optionMap.set(p, { name: name2, hasValue: opt.hasValue }); - } - } - } - let res = {}; - for (let i = 0; i < args.length; i++) { - let arg = args[i]; - let def = this.optionMap.get(arg); - if (!def) - continue; - let value = true; - if (def.hasValue) { - value = args[i + 1] || ""; - i = i + 1; - } - res[def.name] = value; - } - return res; - } - getConfig() { - return workspace_default.getConfiguration(`list.source.${this.name}`); - } - addAction(name2, fn, options) { - this.createAction(Object.assign({ - name: name2, - execute: fn - }, options || {})); - } - addMultipleAction(name2, fn, options) { - this.createAction(Object.assign({ - name: name2, - multiple: true, - execute: fn - }, options || {})); - } - createCommandTask(opt) { - return new CommandTask(opt); - } - addLocationActions() { - this.createAction({ - name: "preview", - execute: async (item, context) => { - let loc = await this.convertLocation(item.location); - await this.previewLocation(loc, context); - } - }); - let { nvim } = this; - this.createAction({ - name: "quickfix", - multiple: true, - execute: async (items) => { - let quickfixItems = await Promise.all(items.map((item) => this.convertLocation(item.location).then((loc) => workspace_default.getQuickfixItem(loc)))); - await nvim.call("setqflist", [quickfixItems]); - let openCommand = await nvim.getVar("coc_quickfix_open_command"); - nvim.command(typeof openCommand === "string" ? openCommand : "copen", true); - } - }); - for (let name2 of ["open", "tabe", "drop", "vsplit", "split"]) { - this.createAction({ - name: name2, - execute: async (item) => { - await this.jumpTo(item.location, name2 == "open" ? null : name2); - } - }); - } - } - async convertLocation(location) { - if (typeof location == "string") - return import_vscode_languageserver_protocol67.Location.create(location, import_vscode_languageserver_protocol67.Range.create(0, 0, 0, 0)); - if (import_vscode_languageserver_protocol67.Location.is(location)) - return location; - let u = URI.parse(location.uri); - if (u.scheme != "file") - return import_vscode_languageserver_protocol67.Location.create(location.uri, import_vscode_languageserver_protocol67.Range.create(0, 0, 0, 0)); - const rl = import_readline4.default.createInterface({ - input: import_fs19.default.createReadStream(u.fsPath, { encoding: "utf8" }) - }); - let match = location.line; - let n = 0; - let resolved = false; - let line = await new Promise((resolve3) => { - rl.on("line", (line2) => { - if (resolved) - return; - if (line2.includes(match)) { - rl.removeAllListeners(); - rl.close(); - resolved = true; - resolve3(line2); - return; - } - n = n + 1; - }); - rl.on("error", (e) => { - this.nvim.errWriteLine(`Read ${u.fsPath} error: ${e.message}`); - resolve3(null); - }); - }); - if (line != null) { - let character = location.text ? line.indexOf(location.text) : 0; - if (character == 0) - character = line.match(/^\s*/)[0].length; - let end = import_vscode_languageserver_protocol67.Position.create(n, character + (location.text ? location.text.length : 0)); - return import_vscode_languageserver_protocol67.Location.create(location.uri, import_vscode_languageserver_protocol67.Range.create(import_vscode_languageserver_protocol67.Position.create(n, character), end)); - } - return import_vscode_languageserver_protocol67.Location.create(location.uri, import_vscode_languageserver_protocol67.Range.create(0, 0, 0, 0)); - } - async jumpTo(location, command) { - if (typeof location == "string") { - await workspace_default.jumpTo(location, null, command); - return; - } - let { range, uri } = await this.convertLocation(location); - let position = range.start; - if (position.line == 0 && position.character == 0 && comparePosition(position, range.end) == 0) { - position = null; - } - await workspace_default.jumpTo(uri, position, command); - } - createAction(action) { - let { name: name2 } = action; - let idx = this.actions.findIndex((o) => o.name == name2); - if (idx !== -1) - this.actions.splice(idx, 1); - this.actions.push(action); - } - async previewLocation(location, context) { - if (!context.listWindow) - return; - let { nvim } = this; - let { uri, range } = location; - let doc = workspace_default.getDocument(location.uri); - let u = URI.parse(uri); - let lines = []; - if (doc) { - lines = doc.getLines(); - } else if (u.scheme == "file") { - try { - let content = await readFile(u.fsPath, "utf8"); - lines = content.split(/\r?\n/); - } catch (e) { - [`Error on read file ${u.fsPath}`, e.message]; - } - } - let config = { - winid: context.window.id, - range: emptyRange(range) ? null : range, - lnum: range.start.line + 1, - name: u.scheme == "file" ? u.fsPath : uri, - filetype: doc ? doc.filetype : this.getFiletype(u.fsPath), - position: context.options.position, - maxHeight: this.previewHeight, - splitRight: this.splitRight, - hlGroup: this.hlGroup, - scheme: u.scheme, - toplineStyle: this.toplineStyle, - toplineOffset: this.toplineOffset - }; - await nvim.call("coc#list#preview", [lines, config]); - if (workspace_default.isVim) - nvim.command("redraw", true); - } - async preview(options, context) { - let { nvim } = this; - let { bufname, filetype, range, lines, lnum } = options; - let config = { - winid: context.window.id, - lnum: range ? range.start.line + 1 : lnum || 1, - filetype: filetype || "txt", - position: context.options.position, - maxHeight: this.previewHeight, - splitRight: this.splitRight, - hlGroup: this.hlGroup, - toplineStyle: this.toplineStyle, - toplineOffset: this.toplineOffset - }; - if (bufname) - config.name = bufname; - if (range) - config.range = range; - await nvim.call("coc#list#preview", [lines, config]); - if (workspace_default.isVim) - nvim.command("redraw", true); - } - doHighlight() { - } - dispose() { - disposeAll(this.disposables); - } - getFiletype(filepath) { - let extname = import_path20.default.extname(filepath); - if (!extname) - return ""; - for (let doc of workspace_default.documents) { - let fsPath = URI.parse(doc.uri).fsPath; - if (import_path20.default.extname(fsPath) == extname) { - return getFiletype(doc.filetype); - } - } - return ""; - } - }; - } -}); - -// src/list/formatting.ts -function formatListItems(align, list2) { - if (list2.length === 0) { - return []; - } - let processedList = []; - if (align) { - const maxWidths = Array(Math.min(...list2.map((item) => item.label.length))).fill(0); - for (let item of list2) { - for (let i = 0; i < maxWidths.length; i++) { - maxWidths[i] = Math.max(maxWidths[i], item.label[i].length); - } - } - processedList = list2.map((item) => __spreadProps(__spreadValues({}, item), { - label: item.label.map((element, idx) => element.padEnd(maxWidths[idx])).join(" ") - })); - } else { - processedList = list2.map((item) => __spreadProps(__spreadValues({}, item), { label: item.label.join(" ") })); - } - return processedList; -} -function formatPath(format2, pathToFormat) { - var _a2; - if (format2 === "hidden") { - return ""; - } else if (format2 === "full") { - return pathToFormat; - } else if (format2 === "short") { - const segments = pathToFormat.split(import_path21.default.sep); - if (segments.length < 2) { - return pathToFormat; - } - const shortenedInit = segments.slice(0, segments.length - 2).filter((seg) => seg.length > 0).map((seg) => seg[0]); - return [...shortenedInit, segments[segments.length - 1]].join(import_path21.default.sep); - } else { - const segments = pathToFormat.split(import_path21.default.sep); - return (_a2 = segments[segments.length - 1]) != null ? _a2 : ""; - } -} -var import_path21; -var init_formatting = __esm({ - "src/list/formatting.ts"() { - import_path21 = __toModule(require("path")); - } -}); - -// src/list/source/commands.ts -function score3(list2, key) { - let idx = list2.indexOf(key); - return idx == -1 ? -1 : list2.length - idx; -} -var CommandsList; -var init_commands = __esm({ - "src/list/source/commands.ts"() { - init_commands2(); - init_events(); - init_workspace(); - init_basic(); - init_formatting(); - CommandsList = class extends BasicList { - constructor(nvim) { - super(nvim); - this.defaultAction = "run"; - this.description = "registered commands of coc.nvim"; - this.name = "commands"; - this.mru = workspace_default.createMru("commands"); - this.addAction("run", async (item) => { - let { cmd } = item.data; - await events_default.fire("Command", [cmd]); - commands_default.executeCommand(cmd).logError(); - await commands_default.addRecent(cmd); - }); - this.addAction("append", async (item) => { - let { cmd } = item.data; - await nvim.feedKeys(`:CocCommand ${cmd} `, "n", false); - }); - } - async loadItems(_context) { - let items = []; - let mruList = await this.mru.load(); - let { commandList, onCommandList, titles } = commands_default; - let ids = commandList.map((c) => c.id).concat(onCommandList); - for (const id of [...new Set(ids)]) { - items.push({ - label: [id, ...titles.get(id) ? [titles.get(id)] : []], - filterText: id, - data: { cmd: id, score: score3(mruList, id) } - }); - } - items.sort((a, b) => b.data.score - a.data.score); - return formatListItems(this.alignColumns, items); - } - doHighlight() { - let { nvim } = this; - nvim.pauseNotification(); - nvim.command("syntax match CocCommandsTitle /\\t.*$/ contained containedin=CocCommandsLine", true); - nvim.command("highlight default link CocCommandsTitle Comment", true); - void nvim.resumeNotification(false, true); - } - }; - } -}); - -// src/list/source/location.ts -var import_path22, logger63, LocationList; -var init_location = __esm({ - "src/list/source/location.ts"() { - init_main(); - import_path22 = __toModule(require("path")); - init_basic(); - init_workspace(); - init_esm2(); - init_fs(); - init_string(); - logger63 = require_logger2()("list-location"); - LocationList = class extends BasicList { - constructor(nvim) { - super(nvim); - this.defaultAction = "open"; - this.description = "show locations saved by g:coc_jump_locations variable"; - this.name = "location"; - this.addLocationActions(); - } - async loadItems(context, token) { - let locs = await this.nvim.getVar("coc_jump_locations"); - if (token.isCancellationRequested) - return []; - locs = locs || []; - locs.forEach((loc) => { - if (!loc.uri) { - let fullpath = import_path22.default.isAbsolute(loc.filename) ? loc.filename : import_path22.default.join(context.cwd, loc.filename); - loc.uri = URI.file(fullpath).toString(); - } - if (!loc.bufnr && workspace_default.getDocument(loc.uri) != null) { - loc.bufnr = workspace_default.getDocument(loc.uri).bufnr; - } - if (!loc.range) { - let { lnum, col } = loc; - loc.range = Range.create(lnum - 1, col - 1, lnum - 1, col - 1); - } else { - loc.lnum = loc.lnum || loc.range.start.line + 1; - loc.col = loc.col || loc.range.start.character + 1; - } - }); - let bufnr = context.buffer.id; - let ignoreFilepath = locs.every((o) => o.bufnr && bufnr && o.bufnr == bufnr); - let items = locs.map((loc) => { - let filename = ignoreFilepath ? "" : loc.filename; - let filterText = `${filename}${loc.text.trim()}`; - if (import_path22.default.isAbsolute(filename)) { - filename = isParentFolder(context.cwd, filename) ? import_path22.default.relative(context.cwd, filename) : filename; - } - let pre = `${filename} |${loc.type ? loc.type + " " : ""}${loc.lnum} col ${loc.col}| `; - let highlight; - if (loc.range && loc.range.start.line == loc.range.end.line) { - let start = byteLength(pre) + byteLength(loc.text.slice(0, loc.range.start.character)); - let end = byteLength(pre) + byteLength(loc.text.slice(0, loc.range.end.character)); - highlight = { hlGroup: "Search", span: [start, end] }; - } - let label = pre + loc.text; - return { - label, - location: Location.create(loc.uri, loc.range), - filterText, - ansiHighlights: highlight ? [highlight] : void 0 - }; - }); - return items; - } - doHighlight() { - let { nvim } = this; - nvim.pauseNotification(); - nvim.command("syntax match CocLocationName /\\v^[^|]+/ contained containedin=CocLocationLine", true); - nvim.command("syntax match CocLocationPosition /\\v\\|\\w*\\s?\\d+\\scol\\s\\d+\\|/ contained containedin=CocLocationLine", true); - nvim.command("syntax match CocLocationError /Error/ contained containedin=CocLocationPosition", true); - nvim.command("syntax match CocLocationWarning /Warning/ contained containedin=CocLocationPosition", true); - nvim.command("highlight default link CocLocationName Directory", true); - nvim.command("highlight default link CocLocationPosition LineNr", true); - nvim.command("highlight default link CocLocationError Error", true); - nvim.command("highlight default link CocLocationWarning WarningMsg", true); - nvim.resumeNotification().catch((_e) => { - }); - } - }; - } -}); - -// src/list/source/diagnostics.ts -var import_path23, logger64, DiagnosticsList; -var init_diagnostics = __esm({ - "src/list/source/diagnostics.ts"() { - import_path23 = __toModule(require("path")); - init_manager(); - init_location(); - init_fs(); - init_formatting(); - logger64 = require_logger2()("list-symbols"); - DiagnosticsList = class extends LocationList { - constructor() { - super(...arguments); - this.defaultAction = "open"; - this.description = "diagnostics of current workspace"; - this.name = "diagnostics"; - } - async loadItems(context) { - let list2 = manager_default.getDiagnosticList(); - let { cwd } = context; - const config = this.getConfig(); - const shouldIncludeCode = config.get("includeCode", true); - const pathFormat = config.get("pathFormat", "full"); - const unformatted = list2.map((item) => { - const file = isParentFolder(cwd, item.file) ? import_path23.default.relative(cwd, item.file) : item.file; - const formattedPath = formatPath(pathFormat, file); - const formattedPosition = pathFormat !== "hidden" ? [`${formattedPath}:${item.lnum}`] : []; - const code = shouldIncludeCode ? [`[${item.source}${item.code ? "" : "]"}`, item.code ? `${item.code}]` : ""] : []; - return { - label: [...formattedPosition, ...code, item.severity, item.message], - location: item.location - }; - }); - return formatListItems(this.alignColumns, unformatted); - } - doHighlight() { - let { nvim } = this; - nvim.pauseNotification(); - nvim.command("syntax match CocDiagnosticsFile /\\v^\\s*\\S+/ contained containedin=CocDiagnosticsLine", true); - nvim.command("syntax match CocDiagnosticsError /\\tError\\s*\\t/ contained containedin=CocDiagnosticsLine", true); - nvim.command("syntax match CocDiagnosticsWarning /\\tWarning\\s*\\t/ contained containedin=CocDiagnosticsLine", true); - nvim.command("syntax match CocDiagnosticsInfo /\\tInformation\\s*\\t/ contained containedin=CocDiagnosticsLine", true); - nvim.command("syntax match CocDiagnosticsHint /\\tHint\\s*\\t/ contained containedin=CocDiagnosticsLine", true); - nvim.command("highlight default link CocDiagnosticsFile Comment", true); - nvim.command("highlight default link CocDiagnosticsError CocErrorSign", true); - nvim.command("highlight default link CocDiagnosticsWarning CocWarningSign", true); - nvim.command("highlight default link CocDiagnosticsInfo CocInfoSign", true); - nvim.command("highlight default link CocDiagnosticsHint CocHintSign", true); - void nvim.resumeNotification(false, true); - } - }; - } -}); - -// src/list/source/extensions.ts -function getPriority(stat) { - switch (stat) { - case "unknown": - return 2; - case "activated": - return 1; - case "disabled": - return -1; - default: - return 0; - } -} -var import_fs_extra7, import_os9, import_path24, logger65, ExtensionList; -var init_extensions = __esm({ - "src/list/source/extensions.ts"() { - import_fs_extra7 = __toModule(require_lib5()); - import_os9 = __toModule(require("os")); - import_path24 = __toModule(require("path")); - init_esm2(); - init_extensions2(); - init_util(); - init_workspace(); - init_window(); - init_basic(); - init_formatting(); - logger65 = require_logger2()("list-extensions"); - ExtensionList = class extends BasicList { - constructor(nvim) { - super(nvim); - this.defaultAction = "toggle"; - this.description = "manage coc extensions"; - this.name = "extensions"; - this.addAction("toggle", async (item) => { - let { id, state } = item.data; - if (state == "disabled") - return; - if (state == "activated") { - await extensions_default.deactivate(id); - } else { - await extensions_default.activate(id); - } - await wait(100); - }, { persist: true, reload: true, parallel: true }); - this.addAction("configuration", async (item) => { - let { root } = item.data; - let jsonFile = import_path24.default.join(root, "package.json"); - if (import_fs_extra7.default.existsSync(jsonFile)) { - let lines = import_fs_extra7.default.readFileSync(jsonFile, "utf8").split(/\r?\n/); - let idx = lines.findIndex((s) => s.includes('"contributes"')); - await workspace_default.jumpTo(URI.file(jsonFile).toString(), { line: idx == -1 ? 0 : idx, character: 0 }); - } - }); - this.addAction("open", async (item) => { - let { root } = item.data; - if (workspace_default.env.isiTerm) { - nvim.call("coc#util#iterm_open", [root], true); - } else { - nvim.call("coc#util#open_url", [root], true); - } - }); - this.addAction("disable", async (item) => { - let { id, state } = item.data; - if (state !== "disabled") - await extensions_default.toggleExtension(id); - }, { persist: true, reload: true, parallel: true }); - this.addAction("enable", async (item) => { - let { id, state } = item.data; - if (state == "disabled") - await extensions_default.toggleExtension(id); - }, { persist: true, reload: true, parallel: true }); - this.addAction("lock", async (item) => { - let { id } = item.data; - await extensions_default.toggleLock(id); - }, { persist: true, reload: true }); - this.addAction("help", async (item) => { - let { root } = item.data; - let files = await import_fs_extra7.default.readdir(root); - let file = files.find((f) => /^readme/i.test(f)); - if (file) - await workspace_default.callAsync("coc#util#jump", ["edit", import_path24.default.join(root, file)]); - }); - this.addAction("reload", async (item) => { - let { id } = item.data; - await extensions_default.reloadExtension(id); - }, { persist: true, reload: true }); - this.addAction("fix", async (item) => { - let { root, isLocal } = item.data; - let { npm } = extensions_default; - if (isLocal) { - window_default.showMessage(`Can't fix for local extension.`, "warning"); - return; - } - if (!npm) - return; - let folder = import_path24.default.join(root, "node_modules"); - if (import_fs_extra7.default.existsSync(folder)) { - import_fs_extra7.default.removeSync(folder); - } - let terminal = await workspace_default.createTerminal({ - cwd: root - }); - let shown = await terminal.show(false); - if (!shown) - return; - workspace_default.nvim.command(`startinsert`, true); - terminal.sendText(`${npm} install --production --ignore-scripts --no-lockfile`, true); - }); - this.addMultipleAction("uninstall", async (items) => { - let ids = []; - for (let item of items) { - if (item.data.isLocal) - continue; - ids.push(item.data.id); - } - extensions_default.uninstallExtension(ids).catch((e) => { - logger65.error(e); - }); - }); - } - async loadItems(_context) { - let items = []; - let list2 = await extensions_default.getExtensionStates(); - let lockedList = await extensions_default.getLockedList(); - for (let stat of list2) { - let prefix = "+"; - if (stat.state == "disabled") { - prefix = "-"; - } else if (stat.state == "activated") { - prefix = "*"; - } else if (stat.state == "unknown") { - prefix = "?"; - } - let root = await this.nvim.call("resolve", stat.root); - let locked = lockedList.includes(stat.id); - items.push({ - label: [`${prefix} ${stat.id}${locked ? " \uE0A2" : ""}`, ...stat.isLocal ? ["[RTP]"] : [], stat.version, root.replace(import_os9.default.homedir(), "~")], - filterText: stat.id, - data: { - id: stat.id, - root, - state: stat.state, - isLocal: stat.isLocal, - priority: getPriority(stat.state) - } - }); - } - items.sort((a, b) => { - if (a.data.priority != b.data.priority) { - return b.data.priority - a.data.priority; - } - return b.data.id - a.data.id ? 1 : -1; - }); - return formatListItems(this.alignColumns, items); - } - doHighlight() { - let { nvim } = this; - nvim.pauseNotification(); - nvim.command("syntax match CocExtensionsActivited /\\v^\\*/ contained containedin=CocExtensionsLine", true); - nvim.command("syntax match CocExtensionsLoaded /\\v^\\+/ contained containedin=CocExtensionsLine", true); - nvim.command("syntax match CocExtensionsDisabled /\\v^-/ contained containedin=CocExtensionsLine", true); - nvim.command("syntax match CocExtensionsName /\\v%3c\\S+/ contained containedin=CocExtensionsLine", true); - nvim.command("syntax match CocExtensionsRoot /\\v\\t[^\\t]*$/ contained containedin=CocExtensionsLine", true); - nvim.command("syntax match CocExtensionsLocal /\\v\\[RTP\\]/ contained containedin=CocExtensionsLine", true); - nvim.command("highlight default link CocExtensionsActivited Special", true); - nvim.command("highlight default link CocExtensionsLoaded Normal", true); - nvim.command("highlight default link CocExtensionsDisabled Comment", true); - nvim.command("highlight default link CocExtensionsName String", true); - nvim.command("highlight default link CocExtensionsLocal MoreMsg", true); - nvim.command("highlight default link CocExtensionsRoot Comment", true); - nvim.resumeNotification().catch((_e) => { - }); - } - }; - } -}); - -// src/list/source/folders.ts -var import_path25, import_fs_extra8, FoldList; -var init_folders = __esm({ - "src/list/source/folders.ts"() { - import_path25 = __toModule(require("path")); - init_esm2(); - import_fs_extra8 = __toModule(require_lib5()); - init_fs(); - init_workspace(); - init_window(); - init_basic(); - FoldList = class extends BasicList { - constructor(nvim) { - super(nvim); - this.defaultAction = "edit"; - this.description = "list of current workspace folders"; - this.name = "folders"; - this.addAction("edit", async (item) => { - let newPath = await nvim.call("input", ["Folder: ", item.label, "dir"]); - let stat = await statAsync(newPath); - if (!stat || !stat.isDirectory()) { - window_default.showMessage(`invalid path: ${newPath}`, "error"); - return; - } - workspace_default.renameWorkspaceFolder(item.label, newPath); - }); - this.addAction("delete", async (item) => { - workspace_default.removeWorkspaceFolder(item.label); - }, { reload: true, persist: true }); - this.addAction("newfile", async (item) => { - let file = await window_default.requestInput("File name", item.label + "/"); - let dir = import_path25.default.dirname(file); - let stat = await statAsync(dir); - if (!stat || !stat.isDirectory()) { - import_fs_extra8.default.mkdirpSync(dir); - } - await workspace_default.createFile(file, { overwrite: false, ignoreIfExists: true }); - await this.jumpTo(URI.file(file).toString()); - }); - } - async loadItems(_context) { - return workspace_default.folderPaths.map((p) => ({ label: p })); - } - }; - } -}); - -// src/list/source/links.ts -function formatUri(uri) { - if (!uri.startsWith("file:")) - return uri; - let filepath = URI.parse(uri).fsPath; - return isParentFolder(workspace_default.cwd, filepath) ? import_path26.default.relative(workspace_default.cwd, filepath) : filepath; -} -var import_path26, LinksList; -var init_links = __esm({ - "src/list/source/links.ts"() { - init_languages(); - init_workspace(); - import_path26 = __toModule(require("path")); - init_basic(); - init_main(); - init_esm2(); - init_fs(); - LinksList = class extends BasicList { - constructor(nvim) { - super(nvim); - this.defaultAction = "open"; - this.description = "links of current buffer"; - this.name = "links"; - this.addAction("open", async (item) => { - let { target } = item.data; - let uri = URI.parse(target); - if (uri.scheme.startsWith("http")) { - await nvim.call("coc#util#open_url", target); - } else { - await workspace_default.jumpTo(target); - } - }); - this.addAction("jump", async (item) => { - let { location } = item.data; - await workspace_default.jumpTo(location.uri, location.range.start); - }); - } - async loadItems(context, token) { - let buf = await context.window.buffer; - let doc = workspace_default.getDocument(buf.id); - if (!doc) - return null; - let items = []; - let links2 = await languages_default.getDocumentLinks(doc.textDocument, token); - if (links2 == null) { - throw new Error("Links provider not found."); - } - let res = []; - for (let link of links2) { - if (link.target) { - items.push({ - label: formatUri(link.target), - data: { - target: link.target, - location: Location.create(doc.uri, link.range) - } - }); - } else { - link = await languages_default.resolveDocumentLink(link); - if (link.target) { - items.push({ - label: formatUri(link.target), - data: { - target: link.target, - location: Location.create(doc.uri, link.range) - } - }); - } - res.push(link); - } - } - return items; - } - }; - } -}); - -// src/list/source/lists.ts -function score4(list2, key) { - let idx = list2.indexOf(key); - return idx == -1 ? -1 : list2.length - idx; -} -var LinksList2; -var init_lists = __esm({ - "src/list/source/lists.ts"() { - init_basic(); - init_mru(); - init_formatting(); - LinksList2 = class extends BasicList { - constructor(nvim, listMap) { - super(nvim); - this.listMap = listMap; - this.name = "lists"; - this.defaultAction = "open"; - this.description = "registered lists of coc.nvim"; - this.mru = new Mru("lists"); - this.addAction("open", async (item) => { - let { name: name2 } = item.data; - await this.mru.add(name2); - await nvim.command(`CocList ${name2}`); - }); - } - async loadItems(_context) { - let items = []; - let mruList = await this.mru.load(); - for (let list2 of this.listMap.values()) { - if (list2.name == "lists") - continue; - items.push({ - label: [list2.name, ...list2.description ? [list2.description] : []], - data: { - name: list2.name, - interactive: list2.interactive, - score: score4(mruList, list2.name) - } - }); - } - items.sort((a, b) => b.data.score - a.data.score); - return formatListItems(this.alignColumns, items); - } - doHighlight() { - let { nvim } = this; - nvim.pauseNotification(); - nvim.command("syntax match CocListsDesc /\\t.*$/ contained containedin=CocListsLine", true); - nvim.command("highlight default link CocListsDesc Comment", true); - nvim.resumeNotification().catch((_e) => { - }); - } - }; - } -}); - -// src/util/convert.ts -function getSymbolKind(kind) { - switch (kind) { - case import_vscode_languageserver_protocol68.SymbolKind.File: - return "File"; - case import_vscode_languageserver_protocol68.SymbolKind.Module: - return "Module"; - case import_vscode_languageserver_protocol68.SymbolKind.Namespace: - return "Namespace"; - case import_vscode_languageserver_protocol68.SymbolKind.Package: - return "Package"; - case import_vscode_languageserver_protocol68.SymbolKind.Class: - return "Class"; - case import_vscode_languageserver_protocol68.SymbolKind.Method: - return "Method"; - case import_vscode_languageserver_protocol68.SymbolKind.Property: - return "Property"; - case import_vscode_languageserver_protocol68.SymbolKind.Field: - return "Field"; - case import_vscode_languageserver_protocol68.SymbolKind.Constructor: - return "Constructor"; - case import_vscode_languageserver_protocol68.SymbolKind.Enum: - return "Enum"; - case import_vscode_languageserver_protocol68.SymbolKind.Interface: - return "Interface"; - case import_vscode_languageserver_protocol68.SymbolKind.Function: - return "Function"; - case import_vscode_languageserver_protocol68.SymbolKind.Variable: - return "Variable"; - case import_vscode_languageserver_protocol68.SymbolKind.Constant: - return "Constant"; - case import_vscode_languageserver_protocol68.SymbolKind.String: - return "String"; - case import_vscode_languageserver_protocol68.SymbolKind.Number: - return "Number"; - case import_vscode_languageserver_protocol68.SymbolKind.Boolean: - return "Boolean"; - case import_vscode_languageserver_protocol68.SymbolKind.Array: - return "Array"; - case import_vscode_languageserver_protocol68.SymbolKind.Object: - return "Object"; - case import_vscode_languageserver_protocol68.SymbolKind.Key: - return "Key"; - case import_vscode_languageserver_protocol68.SymbolKind.Null: - return "Null"; - case import_vscode_languageserver_protocol68.SymbolKind.EnumMember: - return "EnumMember"; - case import_vscode_languageserver_protocol68.SymbolKind.Struct: - return "Struct"; - case import_vscode_languageserver_protocol68.SymbolKind.Event: - return "Event"; - case import_vscode_languageserver_protocol68.SymbolKind.Operator: - return "Operator"; - case import_vscode_languageserver_protocol68.SymbolKind.TypeParameter: - return "TypeParameter"; - default: - return "Unknown"; - } -} -var import_vscode_languageserver_protocol68; -var init_convert = __esm({ - "src/util/convert.ts"() { - import_vscode_languageserver_protocol68 = __toModule(require_main2()); - } -}); - -// src/list/source/outline.ts -function getFilterText(s, kind) { - return `${s.name}${kind ? ` ${kind}` : ""}`; -} -function sortSymbols(a, b) { - let ra = a.selectionRange; - let rb = b.selectionRange; - if (ra.start.line != rb.start.line) { - return ra.start.line - rb.start.line; - } - return ra.start.character - rb.start.character; -} -var import_path27, import_which3, logger66, Outline; -var init_outline = __esm({ - "src/list/source/outline.ts"() { - import_path27 = __toModule(require("path")); - init_main(); - init_esm2(); - import_which3 = __toModule(require_which()); - init_languages(); - init_util(); - init_fs(); - init_workspace(); - init_location(); - init_convert(); - init_formatting(); - logger66 = require_logger2()("list-symbols"); - Outline = class extends LocationList { - constructor() { - super(...arguments); - this.description = "symbols of current document"; - this.name = "outline"; - this.options = [{ - name: "-k, -kind KIND", - hasValue: true, - description: "filters also by kind" - }]; - } - async loadItems(context, token) { - let buf = await context.window.buffer; - let document2 = workspace_default.getDocument(buf.id); - if (!document2) - return null; - let config = this.getConfig(); - let ctagsFilestypes = config.get("ctagsFilestypes", []); - let symbols; - let args = this.parseArguments(context.args); - if (!ctagsFilestypes.includes(document2.filetype)) { - symbols = await languages_default.getDocumentSymbol(document2.textDocument, token); - } - if (token.isCancellationRequested) - return []; - if (!symbols) - return await this.loadCtagsSymbols(document2); - if (symbols.length == 0) - return []; - let filterKind = args.kind ? args.kind.toLowerCase() : null; - let items = []; - let isSymbols = !symbols[0].hasOwnProperty("location"); - if (isSymbols) { - let addSymbols = function(symbols2, level = 0) { - symbols2.sort(sortSymbols); - for (let s of symbols2) { - let kind = getSymbolKind(s.kind); - let location = Location.create(document2.uri, s.selectionRange); - items.push({ - label: [`${"| ".repeat(level)}${s.name}`, `[${kind}]`, `${s.range.start.line + 1}`], - filterText: getFilterText(s, args.kind == "" ? kind : null), - location, - data: { kind } - }); - if (s.children && s.children.length) { - addSymbols(s.children, level + 1); - } - } - }; - addSymbols(symbols); - if (filterKind) { - items = items.filter((o) => o.data.kind.toLowerCase().indexOf(filterKind) == 0); - } - } else { - symbols.sort((a, b) => { - let sa = a.location.range.start; - let sb = b.location.range.start; - let d = sa.line - sb.line; - return d == 0 ? sa.character - sb.character : d; - }); - for (let s of symbols) { - let kind = getSymbolKind(s.kind); - if (s.name.endsWith(") callback")) - continue; - if (filterKind && !kind.toLowerCase().startsWith(filterKind)) { - continue; - } - if (s.location.uri === void 0) { - s.location.uri = document2.uri; - } - items.push({ - label: [s.name, `[${kind}]`, `${s.location.range.start.line + 1}`], - filterText: getFilterText(s, args.kind == "" ? kind : null), - location: s.location - }); - } - } - return formatListItems(this.alignColumns, items); - } - doHighlight() { - let { nvim } = this; - nvim.pauseNotification(); - nvim.command("syntax match CocOutlineName /\\v\\s?[^\\t]+\\s/ contained containedin=CocOutlineLine", true); - nvim.command("syntax match CocOutlineIndentLine /\\v\\|/ contained containedin=CocOutlineLine,CocOutlineName", true); - nvim.command("syntax match CocOutlineKind /\\[\\w\\+\\]/ contained containedin=CocOutlineLine", true); - nvim.command("syntax match CocOutlineLine /\\d\\+$/ contained containedin=CocOutlineLine", true); - nvim.command("highlight default link CocOutlineName Normal", true); - nvim.command("highlight default link CocOutlineIndentLine Comment", true); - nvim.command("highlight default link CocOutlineKind Typedef", true); - nvim.command("highlight default link CocOutlineLine Comment", true); - nvim.resumeNotification(false, true).logError(); - } - async loadCtagsSymbols(document2) { - if (!import_which3.default.sync("ctags", { nothrow: true })) { - return []; - } - let uri = URI.parse(document2.uri); - let extname = import_path27.default.extname(uri.fsPath); - let content = ""; - let tempname = await this.nvim.call("tempname"); - let filepath = `${tempname}.${extname}`; - let escaped = await this.nvim.call("fnameescape", filepath); - await writeFile(escaped, document2.getDocumentContent()); - try { - content = await runCommand(`ctags -f - --excmd=number --language-force=${document2.filetype} ${escaped}`); - } catch (e) { - } - if (!content.trim().length) { - content = await runCommand(`ctags -f - --excmd=number ${escaped}`); - } - content = content.trim(); - if (!content) - return []; - let lines = content.split(/\r?\n/); - let items = []; - for (let line of lines) { - let parts = line.split(" "); - if (parts.length < 4) - continue; - let lnum = Number(parts[2].replace(/;"$/, "")); - let text = document2.getline(lnum - 1); - if (!text) - continue; - let idx = text.indexOf(parts[0]); - let start = idx == -1 ? 0 : idx; - let range = Range.create(lnum - 1, start, lnum - 1, start + parts[0].length); - items.push({ - label: `${parts[0]} [${parts[3]}] ${lnum}`, - filterText: parts[0], - location: Location.create(document2.uri, range), - data: { line: lnum } - }); - } - items.sort((a, b) => a.data.line - b.data.line); - return items; - } - }; - } -}); - -// src/list/source/services.ts -var ServicesList; -var init_services2 = __esm({ - "src/list/source/services.ts"() { - init_services(); - init_basic(); - init_util(); - init_formatting(); - ServicesList = class extends BasicList { - constructor(nvim) { - super(nvim); - this.defaultAction = "toggle"; - this.description = "registered services of coc.nvim"; - this.name = "services"; - this.addAction("toggle", async (item) => { - let { id } = item.data; - await services_default.toggle(id); - await wait(100); - }, { persist: true, reload: true }); - } - async loadItems(_context) { - let stats = services_default.getServiceStats(); - stats.sort((a, b) => a.id > b.id ? -1 : 1); - return formatListItems(this.alignColumns, stats.map((stat) => { - let prefix = stat.state == "running" ? "*" : " "; - return { - label: [prefix, stat.id, `[${stat.state}]`, stat.languageIds.join(", ")], - data: { id: stat.id } - }; - })); - } - doHighlight() { - let { nvim } = this; - nvim.pauseNotification(); - nvim.command("syntax match CocServicesPrefix /\\v^./ contained containedin=CocServicesLine", true); - nvim.command("syntax match CocServicesName /\\v%3c\\S+/ contained containedin=CocServicesLine", true); - nvim.command("syntax match CocServicesStat /\\v\\t\\[\\w+\\]/ contained containedin=CocServicesLine", true); - nvim.command("syntax match CocServicesLanguages /\\v(\\])@<=.*$/ contained containedin=CocServicesLine", true); - nvim.command("highlight default link CocServicesPrefix Special", true); - nvim.command("highlight default link CocServicesName Type", true); - nvim.command("highlight default link CocServicesStat Statement", true); - nvim.command("highlight default link CocServicesLanguages Comment", true); - nvim.resumeNotification().catch((_e) => { - }); - } - }; - } -}); - -// src/list/source/sources.ts -function fixWidth(str, width) { - if (str.length > width) { - return str.slice(0, width - 1) + "."; - } - return str + " ".repeat(width - str.length); -} -var logger67, SourcesList; -var init_sources = __esm({ - "src/list/source/sources.ts"() { - init_main(); - init_esm2(); - init_sources2(); - init_workspace(); - init_basic(); - logger67 = require_logger2()("list-sources"); - SourcesList = class extends BasicList { - constructor(nvim) { - super(nvim); - this.defaultAction = "toggle"; - this.description = "registered completion sources"; - this.name = "sources"; - this.addAction("toggle", async (item) => { - let { name: name2 } = item.data; - sources_default.toggleSource(name2); - }, { persist: true, reload: true }); - this.addAction("refresh", async (item) => { - let { name: name2 } = item.data; - await sources_default.refresh(name2); - }, { persist: true, reload: true }); - this.addAction("open", async (item) => { - let { location } = item; - if (location) - await this.jumpTo(location); - }); - } - async loadItems(context) { - let stats = sources_default.sourceStats(); - let filetype = await context.buffer.getOption("filetype"); - let map = workspace_default.env.disabledSources; - let disables = map ? map[filetype] || [] : []; - stats.sort((a, b) => { - if (a.type != b.type) - return a.type < b.type ? 1 : -1; - return a.name > b.name ? -1 : 1; - }); - return stats.map((stat) => { - let prefix = stat.disabled ? " " : "*"; - if (disables && disables.includes(stat.name)) { - prefix = "-"; - } - let location; - if (stat.filepath) { - location = Location.create(URI.file(stat.filepath).toString(), Range.create(0, 0, 0, 0)); - } - return { - label: `${prefix} ${fixWidth(stat.name, 22)} ${fixWidth("[" + stat.shortcut + "]", 10)} ${fixWidth(stat.triggerCharacters.join(""), 10)} ${fixWidth(stat.priority.toString(), 3)} ${stat.filetypes.join(",")}`, - location, - data: { name: stat.name } - }; - }); - } - doHighlight() { - let { nvim } = this; - nvim.pauseNotification(); - nvim.command("syntax match CocSourcesPrefix /\\v^./ contained containedin=CocSourcesLine", true); - nvim.command("syntax match CocSourcesName /\\v%3c\\S+/ contained containedin=CocSourcesLine", true); - nvim.command("syntax match CocSourcesType /\\v%25v.*%36v/ contained containedin=CocSourcesLine", true); - nvim.command("syntax match CocSourcesPriority /\\v%46v.*%50v/ contained containedin=CocSourcesLine", true); - nvim.command("syntax match CocSourcesFileTypes /\\v\\S+$/ contained containedin=CocSourcesLine", true); - nvim.command("highlight default link CocSourcesPrefix Special", true); - nvim.command("highlight default link CocSourcesName Type", true); - nvim.command("highlight default link CocSourcesPriority Number", true); - nvim.command("highlight default link CocSourcesFileTypes Comment", true); - nvim.command("highlight default link CocSourcesType Statement", true); - nvim.resumeNotification(false, true); - } - }; - } -}); - -// src/list/source/symbols.ts -var import_path28, import_minimatch5, import_vscode_languageserver_protocol69, logger68, Symbols; -var init_symbols = __esm({ - "src/list/source/symbols.ts"() { - import_path28 = __toModule(require("path")); - import_minimatch5 = __toModule(require_minimatch()); - init_esm2(); - init_languages(); - init_workspace(); - init_location(); - init_convert(); - init_fs(); - init_fzy(); - import_vscode_languageserver_protocol69 = __toModule(require_main2()); - init_formatting(); - logger68 = require_logger2()("list-symbols"); - Symbols = class extends LocationList { - constructor() { - super(...arguments); - this.interactive = true; - this.description = "search workspace symbols"; - this.detail = "Symbols list is provided by server, it works on interactive mode only."; - this.name = "symbols"; - this.options = [{ - name: "-k, -kind KIND", - description: "Filter symbols by kind.", - hasValue: true - }]; - } - async loadItems(context, token) { - let { input } = context; - this.cwd = context.cwd; - let args = this.parseArguments(context.args); - let filterKind = args.kind ? args.kind.toLowerCase() : ""; - if (!context.options.interactive) { - throw new Error("Symbols only works on interactive mode"); - } - let symbols = await languages_default.getWorkspaceSymbols(input, token); - if (!symbols) { - throw new Error("No workspace symbols provider registered"); - } - let config = this.getConfig(); - let excludes = config.get("excludes", []); - let items = []; - for (let s of symbols) { - let kind = getSymbolKind(s.kind); - if (filterKind && kind.toLowerCase() != filterKind) { - continue; - } - let file = URI.parse(s.location.uri).fsPath; - if (isParentFolder(workspace_default.cwd, file)) { - file = import_path28.default.relative(workspace_default.cwd, file); - } - if (excludes.some((p) => (0, import_minimatch5.default)(file, p))) { - continue; - } - items.push({ - label: [s.name, `[${kind}]`, file], - filterText: `${s.name}`, - location: s.location, - data: { original: s, kind: s.kind, file, score: score2(input, s.name) } - }); - } - items.sort((a, b) => { - if (a.data.score != b.data.score) { - return b.data.score - a.data.score; - } - if (a.data.kind != b.data.kind) { - return a.data.kind - b.data.kind; - } - return a.data.file.length - b.data.file.length; - }); - return formatListItems(this.alignColumns, items); - } - async resolveItem(item) { - let s = item.data.original; - if (!s) - return null; - let tokenSource = new import_vscode_languageserver_protocol69.CancellationTokenSource(); - let resolved = await languages_default.resolveWorkspaceSymbol(s, tokenSource.token); - if (!resolved) - return null; - let kind = getSymbolKind(resolved.kind); - let file = URI.parse(resolved.location.uri).fsPath; - if (isParentFolder(this.cwd, file)) { - file = import_path28.default.relative(this.cwd, file); - } - return { - label: `${s.name} [${kind}] ${file}`, - filterText: `${s.name}`, - location: s.location - }; - } - doHighlight() { - let { nvim } = this; - nvim.pauseNotification(); - nvim.command("syntax match CocSymbolsName /\\v^\\s*\\S+/ contained containedin=CocSymbolsLine", true); - nvim.command("syntax match CocSymbolsKind /\\[\\w\\+\\]\\s*\\t/ contained containedin=CocSymbolsLine", true); - nvim.command("syntax match CocSymbolsFile /\\S\\+$/ contained containedin=CocSymbolsLine", true); - nvim.command("highlight default link CocSymbolsName Normal", true); - nvim.command("highlight default link CocSymbolsKind Typedef", true); - nvim.command("highlight default link CocSymbolsFile Comment", true); - nvim.resumeNotification().catch((_e) => { - }); - } - }; - } -}); - -// src/list/manager.ts -var import_debounce7, import_vscode_languageserver_protocol70, logger69, mouseKeys, ListManager, manager_default2; -var init_manager3 = __esm({ - "src/list/manager.ts"() { - import_debounce7 = __toModule(require_debounce()); - import_vscode_languageserver_protocol70 = __toModule(require_main2()); - init_events(); - init_extensions2(); - init_util(); - init_workspace(); - init_window(); - init_configuration4(); - init_mappings(); - init_prompt(); - init_session(); - init_commands(); - init_diagnostics(); - init_extensions(); - init_folders(); - init_links(); - init_lists(); - init_location(); - init_outline(); - init_services2(); - init_sources(); - init_symbols(); - logger69 = require_logger2()("list-manager"); - mouseKeys = ["", "", "", "<2-LeftMouse>"]; - ListManager = class { - constructor() { - this.plugTs = 0; - this.sessionsMap = new Map(); - this.disposables = []; - this.listMap = new Map(); - } - init(nvim) { - this.nvim = nvim; - this.config = new ListConfiguration(); - this.prompt = new Prompt(nvim, this.config); - this.mappings = new Mappings(this, nvim, this.config); - let signText = this.config.get("selectedSignText", "*"); - nvim.command(`sign define CocSelected text=${signText} texthl=CocSelectedText linehl=CocSelectedLine`, true); - events_default.on("InputChar", this.onInputChar, this, this.disposables); - let debounced = (0, import_debounce7.default)(async () => { - let session = await this.getCurrentSession(); - if (session) - this.prompt.drawPrompt(); - }, 100); - events_default.on("FocusGained", debounced, null, this.disposables); - events_default.on("WinEnter", (winid) => { - let session = this.getSessionByWinid(winid); - if (session) - this.prompt.start(session.listOptions); - }, null, this.disposables); - events_default.on("WinLeave", (winid) => { - let session = this.getSessionByWinid(winid); - if (session) - this.prompt.cancel(); - }, null, this.disposables); - this.disposables.push({ - dispose: () => { - debounced.clear(); - } - }); - this.prompt.onDidChangeInput(() => { - let { session } = this; - if (!session) - return; - session.onInputChange(); - session.history.filter(); - }); - this.registerList(new LinksList(nvim)); - this.registerList(new LocationList(nvim)); - this.registerList(new Symbols(nvim)); - this.registerList(new Outline(nvim)); - this.registerList(new CommandsList(nvim)); - this.registerList(new ExtensionList(nvim)); - this.registerList(new DiagnosticsList(nvim)); - this.registerList(new SourcesList(nvim)); - this.registerList(new ServicesList(nvim)); - this.registerList(new LinksList2(nvim, this.listMap)); - this.registerList(new FoldList(nvim)); - } - async start(args) { - let res = this.parseArgs(args); - if (!res) - return; - let { name: name2 } = res.list; - let curr = this.sessionsMap.get(name2); - if (curr) - curr.dispose(); - this.prompt.start(res.options); - let session = new ListSession(this.nvim, this.prompt, res.list, res.options, res.listArgs, this.config); - this.sessionsMap.set(name2, session); - this.lastSession = session; - try { - await session.start(args); - } catch (e) { - this.nvim.call("coc#prompt#stop_prompt", ["list"], true); - let msg = e instanceof Error ? e.message : e.toString(); - window_default.showMessage(`Error on "CocList ${name2}": ${msg}`, "error"); - logger69.error(e); - } - } - getSessionByWinid(winid) { - for (let session of this.sessionsMap.values()) { - if (session && session.winid == winid) { - this.lastSession = session; - return session; - } - } - return null; - } - async getCurrentSession() { - let { id } = await this.nvim.window; - for (let session of this.sessionsMap.values()) { - if (session && session.winid == id) { - this.lastSession = session; - return session; - } - } - return null; - } - async resume(name2) { - var _a2; - if (!name2) { - await ((_a2 = this.session) == null ? void 0 : _a2.resume()); - } else { - let session = this.sessionsMap.get(name2); - if (!session) { - window_default.showMessage(`Can't find exists ${name2} list`); - return; - } - await session.resume(); - } - } - async doAction(name2) { - let lastSession = this.lastSession; - if (!lastSession) - return; - await lastSession.doAction(name2); - } - async first(name2) { - let s = this.getSession(name2); - if (s) - await s.first(); - } - async last(name2) { - let s = this.getSession(name2); - if (s) - await s.last(); - } - async previous(name2) { - let s = this.getSession(name2); - if (s) - await s.previous(); - } - async next(name2) { - let s = this.getSession(name2); - if (s) - await s.next(); - } - getSession(name2) { - if (!name2) - return this.session; - return this.sessionsMap.get(name2); - } - async cancel(close = true) { - this.prompt.cancel(); - if (!close) - return; - if (this.session) - await this.session.hide(); - } - reset() { - this.prompt.cancel(); - this.lastSession = void 0; - for (let session of this.sessionsMap.values()) { - session.dispose(); - } - this.sessionsMap.clear(); - this.nvim.call("coc#prompt#stop_prompt", ["list"], true); - } - switchMatcher() { - var _a2; - (_a2 = this.session) == null ? void 0 : _a2.switchMatcher(); - } - async togglePreview() { - let { nvim } = this; - let winid = await nvim.call("coc#list#get_preview", [0]); - if (winid != -1) { - await nvim.call("coc#window#close", [winid]); - await nvim.command("redraw"); - } else { - await this.doAction("preview"); - } - } - async chooseAction() { - let { lastSession } = this; - if (lastSession) - await lastSession.chooseAction(); - } - parseArgs(args) { - let options = []; - let interactive = false; - let autoPreview = false; - let numberSelect = false; - let noQuit = false; - let first = false; - let name2; - let input = ""; - let matcher = "fuzzy"; - let position = "bottom"; - let listArgs = []; - let listOptions = []; - for (let arg of args) { - if (!name2 && arg.startsWith("-")) { - listOptions.push(arg); - } else if (!name2) { - if (!/^\w+$/.test(arg)) { - window_default.showMessage(`Invalid list option: "${arg}"`, "error"); - return null; - } - name2 = arg; - } else { - listArgs.push(arg); - } - } - name2 = name2 || "lists"; - let config = workspace_default.getConfiguration(`list.source.${name2}`); - if (!listOptions.length && !listArgs.length) - listOptions = config.get("defaultOptions", []); - if (!listArgs.length) - listArgs = config.get("defaultArgs", []); - for (let opt of listOptions) { - if (opt.startsWith("--input")) { - input = opt.slice(8); - } else if (opt == "--number-select" || opt == "-N") { - numberSelect = true; - } else if (opt == "--auto-preview" || opt == "-A") { - autoPreview = true; - } else if (opt == "--regex" || opt == "-R") { - matcher = "regex"; - } else if (opt == "--strict" || opt == "-S") { - matcher = "strict"; - } else if (opt == "--interactive" || opt == "-I") { - interactive = true; - } else if (opt == "--top") { - position = "top"; - } else if (opt == "--tab") { - position = "tab"; - } else if (opt == "--ignore-case" || opt == "--normal" || opt == "--no-sort") { - options.push(opt.slice(2)); - } else if (opt == "--first") { - first = true; - } else if (opt == "--no-quit") { - noQuit = true; - } else { - window_default.showMessage(`Invalid option "${opt}" of list`, "error"); - return null; - } - } - let list2 = this.listMap.get(name2); - if (!list2) { - window_default.showMessage(`List ${name2} not found`, "error"); - return null; - } - if (interactive && !list2.interactive) { - window_default.showMessage(`Interactive mode of "${name2}" list not supported`, "error"); - return null; - } - return { - list: list2, - listArgs, - options: { - numberSelect, - autoPreview, - noQuit, - first, - input, - interactive, - matcher, - position, - ignorecase: options.includes("ignore-case") ? true : false, - mode: !options.includes("normal") ? "insert" : "normal", - sort: !options.includes("no-sort") ? true : false - } - }; - } - async onInputChar(session, ch, charmod) { - if (session != "list") - return; - let { mode } = this.prompt; - let now = Date.now(); - if (ch == "" || this.plugTs && now - this.plugTs < 20) { - this.plugTs = now; - return; - } - if (!ch) - return; - if (ch == "") { - await this.cancel(); - return; - } - if (mode == "insert") { - await this.onInsertInput(ch, charmod); - } else { - await this.onNormalInput(ch, charmod); - } - } - async onInsertInput(ch, charmod) { - let { session } = this; - if (!session) - return; - if (mouseKeys.includes(ch)) { - await this.onMouseEvent(ch); - return; - } - let n = await session.doNumberSelect(ch); - if (n) - return; - let done = await this.mappings.doInsertKeymap(ch); - if (done || charmod) - return; - if (ch.startsWith("<") && ch.endsWith(">")) - return; - for (let s of ch) { - let code = s.codePointAt(0); - if (code == 65533) - return; - if (code < 32 || code >= 127 && code <= 159) - return; - await this.prompt.acceptCharacter(s); - } - } - async onNormalInput(ch, _charmod) { - if (mouseKeys.includes(ch)) { - await this.onMouseEvent(ch); - return; - } - let used = await this.mappings.doNormalKeymap(ch); - if (!used) - await this.feedkeys(ch); - } - onMouseEvent(key) { - if (this.session) - return this.session.onMouseEvent(key); - } - async feedkeys(key, remap = true) { - let { nvim } = this; - key = key.startsWith("<") && key.endsWith(">") ? `\\${key}` : key; - await nvim.call("coc#prompt#stop_prompt", ["list"]); - await nvim.call("eval", [`feedkeys("${key}", "${remap ? "i" : "in"}")`]); - this.prompt.start(); - } - async command(command) { - let { nvim } = this; - await nvim.call("coc#prompt#stop_prompt", ["list"]); - await nvim.command(command); - this.prompt.start(); - } - async normal(command, bang = true) { - let { nvim } = this; - await nvim.call("coc#prompt#stop_prompt", ["list"]); - await nvim.command(`normal${bang ? "!" : ""} ${command}`); - this.prompt.start(); - } - async call(fname) { - if (this.session) - return await this.session.call(fname); - } - get session() { - return this.lastSession; - } - registerList(list2) { - const { name: name2 } = list2; - let exists = this.listMap.get(name2); - if (this.listMap.has(name2)) { - if (exists) { - if (typeof exists.dispose == "function") { - exists.dispose(); - } - this.listMap.delete(name2); - } - window_default.showMessage(`list "${name2}" recreated.`); - } - this.listMap.set(name2, list2); - let config = workspace_default.getConfiguration(`list.source.${name2}`); - let defaultAction = config.get("defaultAction"); - if (defaultAction && list2.actions.find((o) => o.name == defaultAction)) { - list2.defaultAction = defaultAction; - } - extensions_default.addSchemeProperty(`list.source.${name2}.defaultAction`, { - type: "string", - default: null, - description: `Default default action of "${name2}" list.` - }); - extensions_default.addSchemeProperty(`list.source.${name2}.defaultOptions`, { - type: "array", - default: list2.interactive ? ["--interactive"] : [], - description: `Default list options of "${name2}" list, only used when both list option and argument are empty.`, - uniqueItems: true, - items: { - type: "string", - enum: [ - "--top", - "--normal", - "--no-sort", - "--input", - "--tab", - "--strict", - "--regex", - "--ignore-case", - "--number-select", - "--interactive", - "--auto-preview", - "--first", - "--no-quit" - ] - } - }); - extensions_default.addSchemeProperty(`list.source.${name2}.defaultArgs`, { - type: "array", - default: [], - description: `Default argument list of "${name2}" list, only used when list argument is empty.`, - uniqueItems: true, - items: { type: "string" } - }); - return import_vscode_languageserver_protocol70.Disposable.create(() => { - if (typeof list2.dispose == "function") { - list2.dispose(); - } - this.listMap.delete(name2); - }); - } - get names() { - return Array.from(this.listMap.keys()); - } - get descriptions() { - let d = {}; - for (let name2 of this.listMap.keys()) { - let list2 = this.listMap.get(name2); - d[name2] = list2.description; - } - return d; - } - async loadItems(name2) { - let args = [name2]; - let res = this.parseArgs(args); - if (!res) - return; - let { list: list2, options, listArgs } = res; - let source = new import_vscode_languageserver_protocol70.CancellationTokenSource(); - let token = source.token; - let arr = await this.nvim.eval('[win_getid(),bufnr("%")]'); - let items = await list2.loadItems({ - options, - args: listArgs, - input: "", - cwd: workspace_default.cwd, - window: this.nvim.createWindow(arr[0]), - buffer: this.nvim.createBuffer(arr[1]), - listWindow: null - }, token); - return items; - } - toggleMode() { - let lastSession = this.lastSession; - if (lastSession) - lastSession.toggleMode(); - } - get isActivated() { - var _a2; - return ((_a2 = this.session) == null ? void 0 : _a2.winid) != null; - } - stop() { - let lastSession = this.lastSession; - if (lastSession) - lastSession.stop(); - } - dispose() { - for (let session of this.sessionsMap.values()) { - session.dispose(); - } - this.sessionsMap.clear(); - if (this.config) { - this.config.dispose(); - } - this.lastSession = void 0; - disposeAll(this.disposables); - } - }; - manager_default2 = new ListManager(); - } -}); - -// src/snippets/string.ts -var SnippetString; -var init_string2 = __esm({ - "src/snippets/string.ts"() { - SnippetString = class { - constructor(value) { - this._tabstop = 1; - this.value = value || ""; - } - static isSnippetString(thing) { - if (thing instanceof SnippetString) { - return true; - } - if (!thing) { - return false; - } - return typeof thing.value === "string"; - } - static _escape(value) { - return value.replace(/\$|}|\\/g, "\\$&"); - } - appendText(str) { - this.value += SnippetString._escape(str); - return this; - } - appendTabstop(num = this._tabstop++) { - this.value += "$"; - this.value += num; - return this; - } - appendPlaceholder(value, num = this._tabstop++) { - if (typeof value === "function") { - const nested = new SnippetString(); - nested._tabstop = this._tabstop; - value(nested); - this._tabstop = nested._tabstop; - value = nested.value; - } else { - value = SnippetString._escape(value); - } - this.value += "${"; - this.value += num; - this.value += ":"; - this.value += value; - this.value += "}"; - return this; - } - appendChoice(values, num = this._tabstop++) { - const value = values.map((s) => s.replace(/\$|}|\\|,/g, "\\$&")).join(","); - this.value += "${"; - this.value += num; - this.value += "|"; - this.value += value; - this.value += "|}"; - return this; - } - appendVariable(name2, defaultValue) { - if (typeof defaultValue === "function") { - const nested = new SnippetString(); - nested._tabstop = this._tabstop; - defaultValue(nested); - this._tabstop = nested._tabstop; - defaultValue = nested.value; - } else if (typeof defaultValue === "string") { - defaultValue = defaultValue.replace(/\$|}/g, "\\$&"); - } - this.value += "${"; - this.value += name2; - if (defaultValue) { - this.value += ":"; - this.value += defaultValue; - } - this.value += "}"; - return this; - } - }; - } -}); - -// src/tree/index.ts -var init_tree = __esm({ - "src/tree/index.ts"() { - init_TreeItem(); - } -}); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - BasicList: () => BasicList, - Buffer: () => import_neovim.Buffer, - CancellationToken: () => import_vscode_languageserver_protocol71.CancellationToken, - CancellationTokenSource: () => import_vscode_languageserver_protocol71.CancellationTokenSource, - ClientState: () => ClientState, - CloseAction: () => CloseAction, - CodeActionKind: () => import_vscode_languageserver_protocol71.CodeActionKind, - CompletionItemKind: () => import_vscode_languageserver_protocol71.CompletionItemKind, - CompletionTriggerKind: () => import_vscode_languageserver_protocol71.CompletionTriggerKind, - ConfigurationTarget: () => ConfigurationTarget, - Diagnostic: () => import_vscode_languageserver_protocol71.Diagnostic, - DiagnosticSeverity: () => import_vscode_languageserver_protocol71.DiagnosticSeverity, - DiagnosticTag: () => import_vscode_languageserver_protocol71.DiagnosticTag, - Disposable: () => import_vscode_languageserver_protocol71.Disposable, - DocumentHighlightKind: () => import_vscode_languageserver_protocol71.DocumentHighlightKind, - Emitter: () => import_vscode_languageserver_protocol71.Emitter, - ErrorAction: () => ErrorAction, - Event: () => import_vscode_languageserver_protocol71.Event, - FileChangeType: () => import_vscode_languageserver_protocol71.FileChangeType, - FileType: () => FileType, - FloatFactory: () => FloatFactory, - Highligher: () => Highlighter, - InsertTextFormat: () => import_vscode_languageserver_protocol71.InsertTextFormat, - LanguageClient: () => LanguageClient, - Location: () => import_vscode_languageserver_protocol71.Location, - LocationLink: () => import_vscode_languageserver_protocol71.LocationLink, - MarkupKind: () => import_vscode_languageserver_protocol71.MarkupKind, - MessageLevel: () => MessageLevel, - MessageTransports: () => MessageTransports, - Mru: () => Mru, - Mutex: () => Mutex, - Neovim: () => import_neovim.Neovim, - NotificationType: () => import_vscode_languageserver_protocol71.NotificationType, - NotificationType0: () => import_vscode_languageserver_protocol71.NotificationType0, - NullLogger: () => NullLogger, - PatternType: () => PatternType, - Position: () => import_vscode_languageserver_protocol71.Position, - ProgressType: () => import_vscode_languageserver_protocol71.ProgressType, - Range: () => import_vscode_languageserver_protocol71.Range, - RequestType: () => import_vscode_languageserver_protocol71.RequestType, - RequestType0: () => import_vscode_languageserver_protocol71.RequestType0, - RevealOutputChannelOn: () => RevealOutputChannelOn, - ServiceStat: () => ServiceStat, - SettingMonitor: () => SettingMonitor, - SignatureHelpTriggerKind: () => import_vscode_languageserver_protocol71.SignatureHelpTriggerKind, - SnippetString: () => SnippetString, - SourceType: () => SourceType, - State: () => State2, - SymbolKind: () => import_vscode_languageserver_protocol71.SymbolKind, - TextDocumentFeature: () => TextDocumentFeature, - TextEdit: () => import_vscode_languageserver_protocol71.TextEdit, - TransportKind: () => TransportKind, - TreeItem: () => TreeItem, - TreeItemCollapsibleState: () => TreeItemCollapsibleState, - Uri: () => URI, - Watchman: () => Watchman, - Window: () => import_neovim.Window, - ansiparse: () => ansiparse, - commands: () => commands_default, - concurrent: () => concurrent, - diagnosticManager: () => manager_default, - disposeAll: () => disposeAll, - download: () => download, - events: () => events_default, - executable: () => executable, - extensions: () => extensions_default, - fetch: () => fetch, - isRunning: () => isRunning, - languages: () => languages_default, - listManager: () => manager_default2, - runCommand: () => runCommand, - services: () => services_default, - snippetManager: () => manager_default3, - sources: () => sources_default, - wait: () => wait, - watchFile: () => watchFile, - window: () => window_default, - workspace: () => workspace_default -}); -var import_neovim, import_vscode_languageserver_protocol71; -var init_src = __esm({ - "src/index.ts"() { - init_commands2(); - init_events(); - init_languages(); - init_mru(); - init_floatFactory(); - init_fetch(); - init_download(); - init_highligher(); - init_services(); - init_sources2(); - init_workspace(); - init_window(); - init_extensions2(); - init_manager3(); - init_manager4(); - init_string2(); - init_manager(); - init_ansiparse(); - init_watchman(); - init_basic(); - init_mutex(); - init_esm2(); - import_neovim = __toModule(require_lib6()); - import_vscode_languageserver_protocol71 = __toModule(require_main2()); - init_types(); - init_language_client(); - init_util(); - init_tree(); - } -}); - -// src/util/factory.ts -function removedGlobalStub(name2) { - return () => { - throw new Error(`process.${name2}() is not allowed in extension sandbox`); - }; -} -function makeRequireFunction() { - const req = (p) => { - if (p === "coc.nvim") { - return init_src(), src_exports; - } - return this.require(p); - }; - req.resolve = (request2) => Module._resolveFilename(request2, this); - req.main = process.mainModule; - req.extensions = Module._extensions; - req.cache = Module._cache; - return req; -} -function compileInSandbox(sandbox) { - return function(content, filename) { - const require2 = makeRequireFunction.call(this); - const dirname3 = import_path29.default.dirname(filename); - const newContent = content.replace(/^\#\!.*/, ""); - const wrapper = Module.wrap(newContent); - const compiledWrapper = vm.runInContext(wrapper, sandbox, { filename }); - const args = [this.exports, require2, this, filename, dirname3]; - return compiledWrapper.apply(this.exports, args); - }; -} -function createSandbox(filename, logger113) { - const module2 = new Module(filename); - module2.paths = Module._nodeModulePaths(filename); - const sandbox = vm.createContext({ - module: module2, - Buffer, - console: { - debug: (...args) => { - logger113.debug.apply(logger113, args); - }, - log: (...args) => { - logger113.info.apply(logger113, args); - }, - error: (...args) => { - logger113.error.apply(logger113, args); - }, - info: (...args) => { - logger113.info.apply(logger113, args); - }, - warn: (...args) => { - logger113.warn.apply(logger113, args); - } - } - }); - defaults(sandbox, global); - sandbox.Reflect = Reflect; - sandbox.require = function sandboxRequire(p) { - const oldCompile = Module.prototype._compile; - Module.prototype._compile = compileInSandbox(sandbox); - const moduleExports = sandbox.module.require(p); - Module.prototype._compile = oldCompile; - return moduleExports; - }; - sandbox.process = new process.constructor(); - for (let key of Object.keys(process)) { - sandbox.process[key] = process[key]; - } - REMOVED_GLOBALS.forEach((name2) => { - sandbox.process[name2] = removedGlobalStub(name2); - }); - sandbox.process["chdir"] = () => { - }; - sandbox.process.umask = (mask) => { - if (typeof mask !== "undefined") { - throw new Error("Cannot use process.umask() to change mask (read-only)"); - } - return process.umask(); - }; - return sandbox; -} -function createExtension(id, filename, isEmpty2 = false) { - if (isEmpty2 || !import_fs27.default.existsSync(filename)) - return { - activate: () => { - }, - deactivate: null - }; - const sandbox = createSandbox(filename, createLogger(`extension:${id}`)); - delete Module._cache[require.resolve(filename)]; - const defaultImport = sandbox.require(filename); - const activate = defaultImport && defaultImport.activate || defaultImport; - if (typeof activate !== "function") { - return { activate: () => { - }, deactivate: null }; - } - return { - activate, - deactivate: typeof defaultImport.deactivate === "function" ? defaultImport.deactivate : null - }; -} -var import_fs27, import_path29, vm, createLogger, logger70, Module, REMOVED_GLOBALS; -var init_factory = __esm({ - "src/util/factory.ts"() { - import_fs27 = __toModule(require("fs")); - import_path29 = __toModule(require("path")); - vm = __toModule(require("vm")); - init_lodash(); - createLogger = require_logger2(); - logger70 = createLogger("util-factoroy"); - Module = require("module"); - REMOVED_GLOBALS = [ - "reallyExit", - "abort", - "umask", - "setuid", - "setgid", - "setgroups", - "_fatalException", - "exit", - "kill" - ]; - } -}); - -// src/extensions.ts -var import_debounce8, import_fs_extra9, import_isuri2, import_path30, import_semver2, import_vscode_languageserver_protocol72, import_which4, import_extensions7, createLogger2, logger71, ExtensionType, Extensions, extensions_default; -var init_extensions2 = __esm({ - "src/extensions.ts"() { - import_debounce8 = __toModule(require_debounce()); - init_main3(); - import_fs_extra9 = __toModule(require_lib5()); - import_isuri2 = __toModule(require_isuri()); - import_path30 = __toModule(require("path")); - import_semver2 = __toModule(require_semver2()); - import_vscode_languageserver_protocol72 = __toModule(require_main2()); - init_esm2(); - import_which4 = __toModule(require_which()); - init_commands2(); - init_events(); - init_db(); - init_floatFactory(); - init_installBuffer(); - init_installer(); - init_memos(); - init_util(); - init_array(); - import_extensions7 = __toModule(require_extensions()); - init_factory(); - init_fs(); - init_is(); - init_watchman(); - init_workspace(); - init_window(); - createLogger2 = require_logger2(); - logger71 = createLogger2("extensions"); - (function(ExtensionType2) { - ExtensionType2[ExtensionType2["Global"] = 0] = "Global"; - ExtensionType2[ExtensionType2["Local"] = 1] = "Local"; - ExtensionType2[ExtensionType2["SingleFile"] = 2] = "SingleFile"; - ExtensionType2[ExtensionType2["Internal"] = 3] = "Internal"; - })(ExtensionType || (ExtensionType = {})); - Extensions = class { - constructor() { - this.extensions = new Map(); - this.disabled = new Set(); - this._onDidLoadExtension = new import_vscode_languageserver_protocol72.Emitter(); - this._onDidActiveExtension = new import_vscode_languageserver_protocol72.Emitter(); - this._onDidUnloadExtension = new import_vscode_languageserver_protocol72.Emitter(); - this._additionalSchemes = {}; - this.activated = false; - this.disposables = []; - this.ready = true; - this.onDidLoadExtension = this._onDidLoadExtension.event; - this.onDidActiveExtension = this._onDidActiveExtension.event; - this.onDidUnloadExtension = this._onDidUnloadExtension.event; - let folder = global.hasOwnProperty("__TEST__") ? import_path30.default.join(__dirname, "__tests__") : process.env.COC_DATA_HOME; - let root = this.root = import_path30.default.join(folder, "extensions"); - if (!import_fs_extra9.default.existsSync(root)) { - import_fs_extra9.default.mkdirpSync(root); - } - let jsonFile = import_path30.default.join(root, "package.json"); - if (!import_fs_extra9.default.existsSync(jsonFile)) { - import_fs_extra9.default.writeFileSync(jsonFile, '{"dependencies":{}}', "utf8"); - } - let filepath = import_path30.default.join(root, "db.json"); - this.db = new DB(filepath); - } - get outputChannel() { - if (this._outputChannel) - return this._outputChannel; - this._outputChannel = window_default.createOutputChannel("extensions"); - return this._outputChannel; - } - async init() { - let extensionObj = this.db.fetch("extension") || {}; - let keys = Object.keys(extensionObj); - for (let key of keys) { - if (extensionObj[key].disabled == true) { - this.disabled.add(key); - } - } - if (process.env.COC_NO_PLUGINS) - return; - let stats = await this.globalExtensionStats(); - let localStats = await this.localExtensionStats(stats.map((o) => o.id)); - stats = stats.concat(localStats); - this.memos = new Memos(import_path30.default.resolve(this.root, "../memos.json")); - stats.map((stat) => { - let extensionType = stat.isLocal ? 1 : 0; - try { - this.createExtension(stat.root, stat.packageJSON, extensionType); - } catch (e) { - logger71.error(`Error on create ${stat.root}:`, e); - } - }); - await this.loadFileExtensions(); - commands_default.register({ - id: "extensions.forceUpdateAll", - execute: async () => { - let arr = await this.cleanExtensions(); - logger71.info(`Force update extensions: ${arr}`); - await this.installExtensions(arr); - } - }, false, "remove all global extensions and install them"); - workspace_default.onDidRuntimePathChange(async (paths) => { - for (let p of paths) { - if (p && this.checkDirectory(p) === true) { - await this.loadExtension(p); - } - } - }, null, this.disposables); - } - activateExtensions() { - this.activated = true; - for (let item of this.extensions.values()) { - let { id, packageJSON } = item.extension; - this.setupActiveEvents(id, packageJSON).logError(); - } - let floatFactory = new FloatFactory(workspace_default.nvim); - events_default.on("CursorMoved", (0, import_debounce8.debounce)(async (bufnr) => { - if (this.installBuffer && bufnr == this.installBuffer.bufnr) { - let lnum = await workspace_default.nvim.call("line", ["."]); - let msgs = this.installBuffer.getMessages(lnum - 1); - let docs = msgs && msgs.length ? [{ content: msgs.join("\n"), filetype: "txt" }] : []; - await floatFactory.show(docs, { modes: ["n"] }); - } - }, 500)); - if (global.hasOwnProperty("__TEST__")) - return; - this.checkExtensions().logError(); - let config = workspace_default.getConfiguration("coc.preferences"); - let interval = config.get("extensionUpdateCheck", "never"); - let silent = config.get("silentAutoupdate", true); - if (interval != "never") { - let now = new Date(); - let day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - (interval == "daily" ? 0 : 7)); - let ts = this.db.fetch("lastUpdate"); - if (ts && Number(ts) > day.getTime()) - return; - this.outputChannel.appendLine("Start auto update..."); - this.updateExtensions(false, silent).logError(); - } - } - async updateExtensions(sync, silent = false) { - if (!this.npm) - return; - let lockedList = await this.getLockedList(); - let stats = await this.globalExtensionStats(); - stats = stats.filter((o) => ![...lockedList, ...this.disabled].includes(o.id)); - this.db.push("lastUpdate", Date.now()); - if (silent) { - window_default.showMessage("Updating extensions, checkout output:///extensions for details.", "more"); - } - let installBuffer = this.installBuffer = new InstallBuffer(true, sync, silent ? this.outputChannel : void 0); - installBuffer.setExtensions(stats.map((o) => o.id)); - await installBuffer.show(workspace_default.nvim); - let createInstaller = createInstallerFactory(this.npm, this.modulesFolder); - let fn = (stat) => { - let { id } = stat; - installBuffer.startProgress([id]); - let url = stat.exotic ? stat.uri : null; - let installer = createInstaller(id); - installer.on("message", (msg, isProgress) => { - installBuffer.addMessage(id, msg, isProgress); - }); - return installer.update(url).then((directory) => { - installBuffer.finishProgress(id, true); - if (directory) { - this.loadExtension(directory).logError(); - } - }, (err) => { - installBuffer.addMessage(id, err.message); - installBuffer.finishProgress(id, false); - }); - }; - await concurrent(stats, fn, silent ? 1 : 3); - } - async checkExtensions() { - let { globalExtensions } = workspace_default.env; - if (globalExtensions && globalExtensions.length) { - let names = this.filterGlobalExtensions(globalExtensions); - this.installExtensions(names).logError(); - } - } - get installer() { - return createInstallerFactory(this.npm, this.modulesFolder); - } - async installExtensions(list2 = []) { - let { npm } = this; - if (!npm || !list2.length) - return; - list2 = distinct(list2); - let installBuffer = this.installBuffer = new InstallBuffer(); - installBuffer.setExtensions(list2); - await installBuffer.show(workspace_default.nvim); - let createInstaller = createInstallerFactory(this.npm, this.modulesFolder); - let fn = (key) => { - installBuffer.startProgress([key]); - let installer = createInstaller(key); - installer.on("message", (msg, isProgress) => { - installBuffer.addMessage(key, msg, isProgress); - }); - return installer.install().then((name2) => { - installBuffer.finishProgress(key, true); - let directory = import_path30.default.join(this.modulesFolder, name2); - this.loadExtension(directory).logError(); - }, (err) => { - installBuffer.addMessage(key, err.message); - installBuffer.finishProgress(key, false); - logger71.error(`Error on install ${key}`, err); - }); - }; - await concurrent(list2, fn); - } - getMissingExtensions() { - let json = this.loadJson() || { dependencies: {} }; - let ids = []; - for (let key of Object.keys(json.dependencies)) { - let folder = import_path30.default.join(this.modulesFolder, key); - if (!import_fs_extra9.default.existsSync(folder)) { - let val = json.dependencies[key]; - if (val.startsWith("http")) { - ids.push(val); - } else { - ids.push(key); - } - } - } - return ids; - } - get npm() { - let npm = workspace_default.getConfiguration("npm").get("binPath", "npm"); - npm = workspace_default.expand(npm); - for (let exe of [npm, "yarnpkg", "yarn", "npm"]) { - try { - let res = import_which4.default.sync(exe); - return res; - } catch (e) { - continue; - } - } - window_default.showMessage(`Can't find npm or yarn in your $PATH`, "error"); - return null; - } - get all() { - return Array.from(this.extensions.values()).map((o) => o.extension).filter((o) => !this.isDisabled(o.id)); - } - getExtension(id) { - return this.extensions.get(id); - } - getExtensionState(id) { - let disabled = this.isDisabled(id); - if (disabled) - return "disabled"; - let item = this.extensions.get(id); - if (!item) - return "unknown"; - let { extension } = item; - return extension.isActive ? "activated" : "loaded"; - } - async getExtensionStates() { - let localStats = await this.localExtensionStats([]); - let globalStats = await this.globalExtensionStats(); - return localStats.concat(globalStats.filter((o) => localStats.find((s) => s.id == o.id) == null)); - } - async getLockedList() { - let obj = await this.db.fetch("extension"); - obj = obj || {}; - return Object.keys(obj).filter((id) => obj[id].locked === true); - } - async toggleLock(id) { - let key = `extension.${id}.locked`; - let locked = await this.db.fetch(key); - if (locked) { - this.db.delete(key); - } else { - this.db.push(key, true); - } - } - async toggleExtension(id) { - let state = this.getExtensionState(id); - if (state == null) - return; - if (state == "activated") { - await this.deactivate(id); - } - let key = `extension.${id}.disabled`; - this.db.push(key, state == "disabled" ? false : true); - if (state != "disabled") { - this.disabled.add(id); - await this.unloadExtension(id); - } else { - this.disabled.delete(id); - let folder = import_path30.default.join(this.modulesFolder, id); - if (import_fs_extra9.default.existsSync(folder)) { - await this.loadExtension(folder); - } - } - await wait(200); - } - async reloadExtension(id) { - let item = this.extensions.get(id); - if (!item) { - window_default.showMessage(`Extension ${id} not registered`, "error"); - return; - } - if (item.type == 3) { - window_default.showMessage(`Can't reload internal extension "${item.id}"`, "warning"); - return; - } - if (item.type == 2) { - await this.loadExtensionFile(item.filepath); - } else if (item.directory) { - await this.loadExtension(item.directory); - } else { - window_default.showMessage(`Can't reload extension ${item.id}`, "warning"); - } - } - async cleanExtensions() { - let dir = this.modulesFolder; - if (!import_fs_extra9.default.existsSync(dir)) - return []; - let ids = this.globalExtensions; - let res = []; - for (let id of ids) { - let directory = import_path30.default.join(dir, id); - let stat = await import_fs_extra9.default.lstat(directory); - if (!stat || stat && stat.isSymbolicLink()) - continue; - await this.unloadExtension(id); - await import_fs_extra9.default.remove(directory); - res.push(id); - } - return res; - } - async uninstallExtension(ids) { - try { - if (!ids.length) - return; - let [globals2, filtered] = splitArray(ids, (id) => this.globalExtensions.includes(id)); - if (filtered.length) { - window_default.showMessage(`Extensions ${filtered} not global extensions, can't uninstall!`, "warning"); - } - let json = this.loadJson() || { dependencies: {} }; - for (let id of globals2) { - await this.unloadExtension(id); - delete json.dependencies[id]; - let folder = import_path30.default.join(this.modulesFolder, id); - if (import_fs_extra9.default.existsSync(folder)) { - await import_fs_extra9.default.remove(folder); - } - } - const sortedObj = { dependencies: {} }; - Object.keys(json.dependencies).sort().forEach((k) => { - sortedObj.dependencies[k] = json.dependencies[k]; - }); - let jsonFile = import_path30.default.join(this.root, "package.json"); - import_fs_extra9.default.writeFileSync(jsonFile, JSON.stringify(sortedObj, null, 2), { encoding: "utf8" }); - window_default.showMessage(`Removed: ${globals2.join(" ")}`); - } catch (e) { - window_default.showMessage(`Uninstall failed: ${e.message}`, "error"); - } - } - isDisabled(id) { - return this.disabled.has(id); - } - has(id) { - return this.extensions.has(id); - } - isActivated(id) { - let item = this.extensions.get(id); - if (item && item.extension.isActive) { - return true; - } - return false; - } - async loadExtension(folder) { - try { - let parentFolder = import_path30.default.dirname(folder); - let isLocal = import_path30.default.normalize(parentFolder) != import_path30.default.normalize(this.modulesFolder); - let jsonFile = import_path30.default.join(folder, "package.json"); - let packageJSON = JSON.parse(import_fs_extra9.default.readFileSync(jsonFile, "utf8")); - let { name: name2 } = packageJSON; - if (this.isDisabled(name2)) - return false; - await this.unloadExtension(name2); - this.createExtension(folder, Object.freeze(packageJSON), isLocal ? 1 : 0); - return true; - } catch (e) { - window_default.showMessage(`Error on load extension from "${folder}": ${e.message}`, "error"); - logger71.error(`Error on load extension from ${folder}`, e); - return false; - } - } - async loadFileExtensions() { - if (!process.env.COC_VIMCONFIG) - return; - let folder = import_path30.default.join(process.env.COC_VIMCONFIG, "coc-extensions"); - if (!import_fs_extra9.default.existsSync(folder)) - return; - let files = await import_fs_extra9.default.readdir(folder); - files = files.filter((f) => f.endsWith(".js")); - for (let file of files) { - await this.loadExtensionFile(import_path30.default.join(folder, file)); - } - } - loadedExtensions() { - return Array.from(this.extensions.keys()); - } - async watchExtension(id) { - let item = this.extensions.get(id); - if (!item) { - window_default.showMessage(`extension ${id} not found`, "error"); - return; - } - if (id.startsWith("single-")) { - window_default.showMessage(`watching ${item.filepath}`); - this.disposables.push(watchFile(item.filepath, async () => { - await this.loadExtensionFile(item.filepath); - window_default.showMessage(`reloaded ${id}`); - })); - } else { - let watchmanPath = workspace_default.getWatchmanPath(); - if (!watchmanPath) { - window_default.showMessage("watchman not found", "error"); - return; - } - let client = await Watchman.createClient(watchmanPath, item.directory); - if (!client) { - window_default.showMessage(`Can't create watchman client, check output:///watchman`); - return; - } - window_default.showMessage(`watching ${item.directory}`); - this.disposables.push(client); - client.subscribe("**/*.js", async () => { - await this.reloadExtension(id); - window_default.showMessage(`reloaded ${id}`); - }).then((disposable) => { - this.disposables.push(disposable); - }, (e) => { - logger71.error(e); - }); - } - } - async loadExtensionFile(filepath) { - let filename = import_path30.default.basename(filepath); - let basename = import_path30.default.basename(filepath, ".js"); - let name2 = "single-" + basename; - if (this.isDisabled(name2)) - return; - let root = import_path30.default.dirname(filepath); - let packageJSON = { - name: name2, - main: filename, - engines: { coc: "^0.0.79" } - }; - let confpath = import_path30.default.join(root, basename + ".json"); - let stat = await statAsync(confpath); - if (stat && stat.isFile()) { - let content = await readFile(confpath, "utf8"); - let obj = JSON.parse(content); - if (obj) { - let attrs = ["activationEvents", "contributes"]; - for (const attr of attrs) { - if (obj[attr]) { - packageJSON[attr] = obj[attr]; - } - } - } - } - await this.unloadExtension(name2); - this.createExtension(root, packageJSON, 2); - } - async activate(id) { - if (this.isDisabled(id)) { - throw new Error(`Extension ${id} is disabled!`); - } - let item = this.extensions.get(id); - if (!item) { - throw new Error(`Extension ${id} not registered!`); - } - let { extension } = item; - if (extension.isActive) - return true; - await Promise.resolve(extension.activate()); - if (extension.isActive) { - this._onDidActiveExtension.fire(extension); - return true; - } - return false; - } - async deactivate(id) { - let item = this.extensions.get(id); - if (!item) - return false; - await Promise.resolve(item.deactivate()); - return true; - } - async call(id, method, args) { - let item = this.extensions.get(id); - if (!item) - throw new Error(`extension ${id} not registered`); - let { extension } = item; - if (!extension.isActive) { - await this.activate(id); - } - let { exports: exports2 } = extension; - if (!exports2 || !exports2.hasOwnProperty(method)) { - throw new Error(`method ${method} not found on extension ${id}`); - } - return await Promise.resolve(exports2[method].apply(null, args)); - } - getExtensionApi(id) { - let item = this.extensions.get(id); - if (!item) - return null; - let { extension } = item; - return extension.isActive ? extension.exports : null; - } - registerExtension(extension, deactivate) { - let { id, packageJSON } = extension; - this.extensions.set(id, { id, type: 3, extension, deactivate, isLocal: true }); - let { contributes } = packageJSON; - if (contributes) { - let { configuration } = contributes; - if (configuration && configuration.properties) { - let { properties } = configuration; - let props = {}; - for (let key of Object.keys(properties)) { - let val = properties[key].default; - if (val != null) - props[key] = val; - } - workspace_default.configurations.extendsDefaults(props); - } - } - this._onDidLoadExtension.fire(extension); - this.setupActiveEvents(id, packageJSON).logError(); - } - get globalExtensions() { - let json = this.loadJson(); - if (!json || !json.dependencies) - return []; - return Object.keys(json.dependencies); - } - async globalExtensionStats() { - let json = this.loadJson(); - if (!json || !json.dependencies) - return []; - let { modulesFolder } = this; - let res = await Promise.all(Object.keys(json.dependencies).map((key) => new Promise(async (resolve3) => { - try { - let val = json.dependencies[key]; - let root = import_path30.default.join(modulesFolder, key); - let res2 = this.checkDirectory(root); - if (res2 instanceof Error) { - window_default.showMessage(`Unable to load global extension at ${root}: ${res2.message}`, "error"); - logger71.error(`Error on load ${root}`, res2); - return resolve3(null); - } - let content = await readFile(import_path30.default.join(root, "package.json"), "utf8"); - root = await import_fs_extra9.default.realpath(root); - let obj = JSON.parse(content); - let version2 = obj ? obj.version || "" : ""; - let description = obj ? obj.description || "" : ""; - let uri = import_isuri2.default.isValid(val) ? val : ""; - resolve3({ - id: key, - isLocal: false, - version: version2, - description, - exotic: /^https?:/.test(val), - uri: uri.replace(/\.git(#master)?$/, ""), - root, - state: this.getExtensionState(key), - packageJSON: Object.freeze(obj) - }); - } catch (e) { - logger71.error(e); - resolve3(null); - } - }))); - return res.filter((info) => info != null); - } - async localExtensionStats(excludes) { - let runtimepath = await workspace_default.nvim.eval("&runtimepath"); - let paths = runtimepath.split(","); - let res = await Promise.all(paths.map((root) => new Promise(async (resolve3) => { - try { - let res2 = this.checkDirectory(root); - if (res2 !== true) - return resolve3(null); - let jsonFile = import_path30.default.join(root, "package.json"); - let content = await readFile(jsonFile, "utf8"); - let obj = JSON.parse(content); - let exist = this.extensions.get(obj.name); - if (exist && !exist.isLocal) { - logger71.info(`Extension "${obj.name}" in runtimepath already loaded.`); - return resolve3(null); - } - if (excludes.includes(obj.name)) { - logger71.info(`Skipped load vim plugin from "${root}", "${obj.name}" already global extension.`); - return resolve3(null); - } - let version2 = obj ? obj.version || "" : ""; - let description = obj ? obj.description || "" : ""; - resolve3({ - id: obj.name, - isLocal: true, - version: version2, - description, - exotic: false, - root, - state: this.getExtensionState(obj.name), - packageJSON: Object.freeze(obj) - }); - } catch (e) { - logger71.error(e); - resolve3(null); - } - }))); - return res.filter((info) => info != null); - } - loadJson() { - let { root } = this; - let jsonFile = import_path30.default.join(root, "package.json"); - if (!import_fs_extra9.default.existsSync(jsonFile)) - return null; - let errors = []; - let content = import_fs_extra9.default.readFileSync(jsonFile, "utf8"); - let data = parse3(content, errors, { allowTrailingComma: true }); - if (errors && errors.length > 0) { - window_default.showMessage(`Error on parse ${jsonFile}`, "error"); - workspace_default.nvim.call("coc#util#open_file", ["edit", jsonFile], true); - } - return data; - } - get schemes() { - return this._additionalSchemes; - } - addSchemeProperty(key, def) { - this._additionalSchemes[key] = def; - workspace_default.configurations.extendsDefaults({ [key]: def.default }); - } - async setupActiveEvents(id, packageJSON) { - let { activationEvents } = packageJSON; - if (!this.canActivate(id)) - return; - if (!activationEvents || Array.isArray(activationEvents) && activationEvents.includes("*")) { - await this.activate(id).catch((e) => { - window_default.showMessage(`Error on activate extension ${id}: ${e.message}`); - this.outputChannel.appendLine(`Error on activate extension ${id}. -${e.message} - ${e.stack}`); - }); - return; - } - let disposables = []; - let active = () => { - disposeAll(disposables); - return new Promise((resolve3) => { - if (!this.canActivate(id)) { - this.outputChannel.appendLine(`Extension ${id} is disabled or not loaded.`); - return resolve3(); - } - let timer = setTimeout(() => { - this.outputChannel.appendLine(`Extension ${id} activate cost more than 1s`); - resolve3(); - }, 1e3); - this.activate(id).then(() => { - clearTimeout(timer); - resolve3(); - }, (e) => { - clearTimeout(timer); - window_default.showMessage(`Error on activate extension ${id}: ${e.message}`); - this.outputChannel.appendLine(`Error on activate extension ${id}:${e.message} - ${e.stack}`); - resolve3(); - }); - }); - }; - for (let eventName of activationEvents) { - let parts = eventName.split(":"); - let ev = parts[0]; - if (ev == "onLanguage") { - if (workspace_default.filetypes.has(parts[1])) { - await active(); - return; - } - workspace_default.onDidOpenTextDocument((document2) => { - if (document2.languageId == parts[1]) { - void active(); - } - }, null, disposables); - } else if (ev == "onCommand") { - commands_default.onCommandList.push(parts[1]); - events_default.on("Command", async (command) => { - if (command == parts[1]) { - await active(); - await wait(500); - } - }, null, disposables); - } else if (ev == "workspaceContains") { - let check = async () => { - let folders = workspace_default.workspaceFolders.map((o) => URI.parse(o.uri).fsPath); - for (let folder of folders) { - if (inDirectory(folder, parts[1].split(/\s+/))) { - await active(); - return true; - } - } - }; - let res = await check(); - if (res) - return; - workspace_default.onDidChangeWorkspaceFolders(check, null, disposables); - } else if (ev == "onFileSystem") { - for (let doc of workspace_default.documents) { - let u = URI.parse(doc.uri); - if (u.scheme == parts[1]) { - await active(); - return; - } - } - workspace_default.onDidOpenTextDocument((document2) => { - let u = URI.parse(document2.uri); - if (u.scheme == parts[1]) { - void active(); - } - }, null, disposables); - } else { - window_default.showMessage(`Unsupported event ${eventName} of ${id}`, "error"); - } - } - } - createExtension(root, packageJSON, type) { - let id = packageJSON.name; - let isActive = false; - let result; - let filename = import_path30.default.join(root, packageJSON.main || "index.js"); - let ext; - let subscriptions = []; - let exports2; - let extension = { - activate: () => { - if (result) - return result; - let context = { - subscriptions, - extensionPath: root, - globalState: this.memos.createMemento(`${id}|global`), - workspaceState: this.memos.createMemento(`${id}|${workspace_default.rootPath}`), - asAbsolutePath: (relativePath) => import_path30.default.join(root, relativePath), - storagePath: import_path30.default.join(this.root, `${id}-data`), - logger: createLogger2(id) - }; - if (!ext) { - try { - let isEmpty2 = !(packageJSON.engines || {}).hasOwnProperty("coc"); - ext = createExtension(id, filename, isEmpty2); - } catch (e) { - logger71.error(`Error on createExtension ${id} from ${filename}`, e); - return; - } - } - result = new Promise((resolve3, reject) => { - try { - Promise.resolve(ext.activate(context)).then((res) => { - isActive = true; - exports2 = res; - resolve3(res); - }, (e) => { - logger71.error(`Error on active extension ${id}: ${e.message}`, e); - reject(e); - }); - } catch (e) { - logger71.error(`Error on active extension ${id}: ${e.stack}`, e); - reject(e); - } - }); - return result; - } - }; - Object.defineProperties(extension, { - id: { - get: () => id, - enumerable: true - }, - packageJSON: { - get: () => packageJSON, - enumerable: true - }, - extensionPath: { - get: () => root, - enumerable: true - }, - isActive: { - get: () => isActive, - enumerable: true - }, - exports: { - get: () => { - if (!isActive) - throw new Error(`Invalid access to exports, extension "${id}" not activated`); - return exports2; - }, - enumerable: true - } - }); - this.extensions.set(id, { - id, - type, - isLocal: type == 1, - extension, - directory: root, - filepath: filename, - deactivate: () => { - if (!isActive) - return; - result = void 0; - exports2 = void 0; - isActive = false; - disposeAll(subscriptions); - subscriptions.splice(0, subscriptions.length); - subscriptions = []; - if (ext && ext.deactivate) { - try { - return Promise.resolve(ext.deactivate()).catch((e) => { - logger71.error(`Error on ${id} deactivate: `, e); - }); - } catch (e) { - logger71.error(`Error on ${id} deactivate: `, e); - } - } - } - }); - let { contributes } = packageJSON; - if (contributes) { - let { configuration, rootPatterns, commands } = contributes; - if (configuration && configuration.properties) { - let { properties } = configuration; - let props = {}; - for (let key of Object.keys(properties)) { - let val = properties[key].default; - if (val != null) - props[key] = val; - } - workspace_default.configurations.extendsDefaults(props); - } - if (rootPatterns && rootPatterns.length) { - for (let item of rootPatterns) { - workspace_default.addRootPattern(item.filetype, item.patterns); - } - } - if (commands && commands.length) { - for (let cmd of commands) { - commands_default.titles.set(cmd.command, cmd.title); - } - } - } - this._onDidLoadExtension.fire(extension); - if (this.activated) { - this.setupActiveEvents(id, packageJSON).logError(); - } - } - filterGlobalExtensions(names) { - let map = new Map(); - names.forEach((def) => { - let name2 = this.getExtensionName(def); - if (name2) - map.set(name2, def); - }); - let json = this.loadJson(); - let urls = []; - let exists = []; - if (json && json.dependencies) { - for (let key of Object.keys(json.dependencies)) { - let val = json.dependencies[key]; - if (typeof val !== "string") - continue; - if (import_fs_extra9.default.existsSync(import_path30.default.join(this.modulesFolder, key, "package.json"))) { - exists.push(key); - if (/^https?:/.test(val)) { - urls.push(val); - } - } - } - } - for (let name2 of map.keys()) { - if (this.disabled.has(name2) || this.extensions.has(name2)) { - map.delete(name2); - continue; - } - if (/^https?:/.test(name2) && urls.some((url) => url.startsWith(name2)) || exists.includes(name2)) { - map.delete(name2); - } - } - return Array.from(map.values()); - } - getExtensionName(def) { - if (/^https?:/.test(def)) - return def; - if (!def.includes("@")) - return def; - return def.replace(/@[\d.]+$/, ""); - } - get modulesFolder() { - return import_path30.default.join(this.root, global.hasOwnProperty("__TEST__") ? "" : "node_modules"); - } - canActivate(id) { - return !this.disabled.has(id) && this.extensions.has(id); - } - async unloadExtension(id) { - let item = this.extensions.get(id); - if (item) { - await this.deactivate(id); - this.extensions.delete(id); - this._onDidUnloadExtension.fire(id); - } - } - checkDirectory(folder) { - try { - let jsonFile = import_path30.default.join(folder, "package.json"); - if (!import_fs_extra9.default.existsSync(jsonFile)) - throw new Error("package.json not found"); - let packageJSON = JSON.parse(import_fs_extra9.default.readFileSync(jsonFile, "utf8")); - let { name: name2, engines, main } = packageJSON; - if (!name2 || !engines) - throw new Error(`can't find name & engines in package.json`); - if (!engines || !objectLiteral(engines)) { - throw new Error(`invalid engines in ${jsonFile}`); - } - if (main && !import_fs_extra9.default.existsSync(import_path30.default.join(folder, main))) { - throw new Error(`main file ${main} not found, you may need to build the project.`); - } - let keys = Object.keys(engines); - if (!keys.includes("coc") && !keys.includes("vscode")) { - throw new Error(`Engines in package.json doesn't have coc or vscode`); - } - if (keys.includes("coc")) { - let required = engines["coc"].replace(/^\^/, ">="); - if (!import_semver2.default.satisfies(workspace_default.version, required)) { - throw new Error(`Please update coc.nvim, ${packageJSON.name} requires coc.nvim ${engines["coc"]}`); - } - } - return true; - } catch (e) { - return e; - } - } - dispose() { - disposeAll(this.disposables); - } - }; - extensions_default = new Extensions(); - } -}); - -// src/sources/source.ts -var logger72, Source; -var init_source = __esm({ - "src/sources/source.ts"() { - init_types(); - init_string(); - init_workspace(); - logger72 = require_logger2()("sources-source"); - Source = class { - constructor(option) { - this._disabled = false; - this.nvim = workspace_default.nvim; - this.name = option.name; - this.filepath = option.filepath || ""; - this.sourceType = option.sourceType || SourceType.Native; - this.isSnippet = !!option.isSnippet; - this.defaults = option; - } - get priority() { - return this.getConfig("priority", 1); - } - get triggerOnly() { - let triggerOnly = this.defaults["triggerOnly"]; - if (typeof triggerOnly == "boolean") - return triggerOnly; - if (!this.triggerCharacters && !this.triggerPatterns) - return false; - return Array.isArray(this.triggerPatterns) && this.triggerPatterns.length != 0; - } - get triggerCharacters() { - return this.getConfig("triggerCharacters", null); - } - get optionalFns() { - return this.defaults["optionalFns"] || []; - } - get triggerPatterns() { - let patterns = this.getConfig("triggerPatterns", null); - if (!patterns || patterns.length == 0) - return null; - return patterns.map((s) => typeof s === "string" ? new RegExp(s + "$") : s); - } - get shortcut() { - let shortcut = this.getConfig("shortcut", ""); - return shortcut ? shortcut : this.name.slice(0, 3); - } - get enable() { - if (this._disabled) - return false; - return this.getConfig("enable", true); - } - get filetypes() { - return this.getConfig("filetypes", null); - } - get disableSyntaxes() { - return this.getConfig("disableSyntaxes", []); - } - getConfig(key, defaultValue) { - let config = workspace_default.getConfiguration(`coc.source.${this.name}`); - defaultValue = this.defaults.hasOwnProperty(key) ? this.defaults[key] : defaultValue; - return config.get(key, defaultValue); - } - toggle() { - this._disabled = !this._disabled; - } - get firstMatch() { - return this.getConfig("firstMatch", true); - } - get menu() { - let { shortcut } = this; - return shortcut ? `[${shortcut}]` : ""; - } - filterWords(words, opt) { - let { firstMatch } = this; - let res = []; - let { input } = opt; - let cword = opt.word; - if (!input.length) - return []; - let cFirst = input[0]; - for (let word of words) { - if (!word || word.length < 3) - continue; - if (firstMatch && cFirst != word[0]) - continue; - if (!firstMatch && cFirst.toLowerCase() != word[0].toLowerCase()) - continue; - if (word == cword || word == input) - continue; - res.push(word); - } - return res; - } - fixStartcol(opt, valids) { - let { col, input, line, bufnr } = opt; - let start = byteSlice(line, 0, col); - let document2 = workspace_default.getDocument(bufnr); - if (!document2) - return col; - let { chars } = document2; - for (let i = start.length - 1; i >= 0; i--) { - let c = start[i]; - if (!chars.isKeywordChar(c) && !valids.includes(c)) { - break; - } - input = `${c}${input}`; - col = col - 1; - } - opt.col = col; - opt.input = input; - return col; - } - async shouldComplete(opt) { - let { disableSyntaxes } = this; - if (opt.synname && disableSyntaxes && disableSyntaxes.length) { - let synname = (opt.synname || "").toLowerCase(); - if (disableSyntaxes.findIndex((s) => synname.includes(s.toLowerCase())) !== -1) { - return false; - } - } - let fn = this.defaults["shouldComplete"]; - if (typeof fn === "function") - return await Promise.resolve(fn.call(this, opt)); - return true; - } - async refresh() { - let fn = this.defaults["refresh"]; - if (typeof fn === "function") - await Promise.resolve(fn.call(this)); - } - async onCompleteDone(item, opt) { - let fn = this.defaults["onCompleteDone"]; - if (typeof fn === "function") - await Promise.resolve(fn.call(this, item, opt)); - } - async doComplete(opt, token) { - let fn = this.defaults["doComplete"]; - if (typeof fn === "function") - return await Promise.resolve(fn.call(this, opt, token)); - return null; - } - }; - } -}); - -// src/sources/source-language.ts -function getStartColumn(line, items) { - let first = items[0]; - if (!first.textEdit) - return null; - let range = import_vscode_languageserver_protocol73.InsertReplaceEdit.is(first.textEdit) ? first.textEdit.replace : first.textEdit.range; - let { character } = range.start; - for (let i = 1; i < Math.min(10, items.length); i++) { - let o = items[i]; - if (!o.textEdit) - return null; - let r = import_vscode_languageserver_protocol73.InsertReplaceEdit.is(o.textEdit) ? o.textEdit.replace : o.textEdit.range; - if (r.start.character !== character) - return null; - } - return byteIndex(line, character); -} -function getKindString(kind, map, defaultValue = "") { - return map.get(kind) || defaultValue; -} -function getWord(item, opt, invalidInsertCharacters) { - let { label, data, insertTextFormat, insertText, textEdit } = item; - let word; - let newText; - if (data && typeof data.word === "string") - return data.word; - if (textEdit) { - let range = import_vscode_languageserver_protocol73.InsertReplaceEdit.is(textEdit) ? textEdit.replace : textEdit.range; - newText = textEdit.newText; - if (range && range.start.line == range.end.line) { - let { line, col, colnr } = opt; - let character = characterIndex(line, col); - if (range.start.character > character) { - let before = line.slice(character, range.start.character); - newText = before + newText; - } else { - let start = line.slice(range.start.character, character); - if (start.length && newText.startsWith(start)) { - newText = newText.slice(start.length); - } - } - character = characterIndex(line, colnr - 1); - if (range.end.character > character) { - let end = line.slice(character, range.end.character); - if (newText.endsWith(end)) { - newText = newText.slice(0, -end.length); - } - } - } - } else { - newText = insertText; - } - if (insertTextFormat == import_vscode_languageserver_protocol73.InsertTextFormat.Snippet && newText && newText.includes("$")) { - let parser2 = new SnippetParser(); - let text = parser2.text(newText); - word = text ? getValidWord(text, invalidInsertCharacters) : label; - } else { - word = getValidWord(newText, invalidInsertCharacters) || label; - } - return word || ""; -} -function getValidWord(text, invalidChars) { - if (!text) - return ""; - if (!invalidChars.length) - return text; - for (let i = 0; i < text.length; i++) { - let c = text[i]; - if (invalidChars.includes(c)) { - return text.slice(0, i); - } - } - return text; -} -var import_vscode_languageserver_protocol73, logger73, LanguageSource; -var init_source_language = __esm({ - "src/sources/source-language.ts"() { - import_vscode_languageserver_protocol73 = __toModule(require_main2()); - init_commands2(); - init_manager4(); - init_parser2(); - init_position(); - init_string(); - init_window(); - init_workspace(); - logger73 = require_logger2()("source-language"); - LanguageSource = class { - constructor(name2, shortcut, provider, documentSelector, triggerCharacters, allCommitCharacters, priority, completeConfig) { - this.name = name2; - this.shortcut = shortcut; - this.provider = provider; - this.documentSelector = documentSelector; - this.triggerCharacters = triggerCharacters; - this.allCommitCharacters = allCommitCharacters; - this.completeConfig = completeConfig; - this._enabled = true; - this.resolvedIndexes = new Set(); - this.completeItems = []; - this.priority = typeof priority === "number" ? priority : completeConfig.priority; - } - get enable() { - return this._enabled; - } - toggle() { - this._enabled = !this._enabled; - } - shouldCommit(item, character) { - let completeItem = this.completeItems[item.index]; - if (!completeItem) - return false; - let commitCharacters = [...this.allCommitCharacters, ...completeItem.commitCharacters || []]; - return commitCharacters.includes(character); - } - async doComplete(opt, token) { - let { provider, name: name2 } = this; - let { triggerCharacter, bufnr } = opt; - this.filetype = opt.filetype; - this.resolvedIndexes.clear(); - this.completeItems = []; - let triggerKind = this.getTriggerKind(opt); - let position = this.getPosition(opt); - let context = { triggerKind, option: opt }; - if (triggerKind == import_vscode_languageserver_protocol73.CompletionTriggerKind.TriggerCharacter) - context.triggerCharacter = triggerCharacter; - let result; - try { - let doc = workspace_default.getDocument(bufnr); - result = await Promise.resolve(provider.provideCompletionItems(doc.textDocument, position, token, context)); - } catch (e) { - logger73.error(`Complete "${name2}" error:`, e); - return null; - } - if (!result || token.isCancellationRequested) - return null; - let completeItems = Array.isArray(result) ? result : result.items; - if (!completeItems || completeItems.length == 0) - return null; - this.completeItems = completeItems; - let startcol = getStartColumn(opt.line, completeItems); - let option = Object.assign({}, opt); - let prefix; - if (startcol != null) { - if (startcol < option.col) { - prefix = byteSlice(opt.line, startcol, option.col); - } - option.col = startcol; - } - let items = completeItems.map((o, index) => { - let item = this.convertVimCompleteItem(o, this.shortcut, option, prefix); - item.index = index; - return item; - }); - let isIncomplete = typeof result["isIncomplete"] === "boolean" ? result["isIncomplete"] : false; - return { startcol, isIncomplete, items }; - } - async onCompleteResolve(item, token) { - let { index } = item; - let resolving = this.completeItems[index]; - if (!resolving || this.resolvedIndexes.has(index)) - return; - let hasResolve = typeof this.provider.resolveCompletionItem === "function"; - if (hasResolve) { - this.resolvedIndexes.add(index); - try { - let resolved = await Promise.resolve(this.provider.resolveCompletionItem(Object.assign({}, resolving), token)); - if (!resolved || token.isCancellationRequested) { - this.resolvedIndexes.delete(index); - } else if (resolved !== resolving) { - Object.assign(resolving, resolved); - } - } catch (e) { - this.resolvedIndexes.delete(index); - logger73.error(`Error on complete resolve: ${e.message}`, e.stack); - } - } - if (typeof item.documentation === "undefined") { - let { documentation, detail } = resolving; - if (!documentation && !detail) - return; - let docs = []; - if (detail && !item.detailShown && detail != item.word) { - detail = detail.replace(/\n\s*/g, " "); - if (detail.length) { - let isText = /^[\w-\s.,\t\n]+$/.test(detail); - docs.push({ filetype: isText ? "txt" : this.filetype, content: detail }); - } - } - if (documentation) { - if (typeof documentation == "string") { - docs.push({ filetype: "markdown", content: documentation }); - } else if (documentation.value) { - docs.push({ - filetype: documentation.kind == "markdown" ? "markdown" : "txt", - content: documentation.value - }); - } - } - item.documentation = docs; - } - } - async onCompleteDone(vimItem, opt) { - let item = this.completeItems[vimItem.index]; - if (!item) - return; - let line = opt.linenr - 1; - if (item.insertText != null && !item.textEdit) { - item.textEdit = { - range: import_vscode_languageserver_protocol73.Range.create(line, opt.col, line, opt.colnr - 1), - newText: item.insertText - }; - } - if (vimItem.line) - Object.assign(opt, { line: vimItem.line }); - try { - let isSnippet = await this.applyTextEdit(item, vimItem.word, opt); - let { additionalTextEdits } = item; - if (additionalTextEdits && item.textEdit) { - let r = import_vscode_languageserver_protocol73.InsertReplaceEdit.is(item.textEdit) ? item.textEdit.replace : item.textEdit.range; - additionalTextEdits = additionalTextEdits.filter((edit2) => { - let er = import_vscode_languageserver_protocol73.InsertReplaceEdit.is(edit2) ? edit2.replace : edit2.range; - if (rangeOverlap(r, er)) { - logger73.error("Filtered overlap additionalTextEdit:", edit2); - return false; - } - return true; - }); - } - await this.applyAdditionalEdits(additionalTextEdits, opt.bufnr, isSnippet); - if (isSnippet) - await manager_default3.selectCurrentPlaceholder(); - if (item.command && commands_default.has(item.command.command)) { - void commands_default.execute(item.command); - } - } catch (e) { - logger73.error("Error on CompleteDone:", e); - } - } - async applyTextEdit(item, word, option) { - let { nvim } = workspace_default; - let { textEdit } = item; - if (!textEdit) - return false; - let { line, bufnr, linenr } = option; - let doc = workspace_default.getDocument(bufnr); - if (!doc) - return false; - let newText = textEdit.newText; - let range = import_vscode_languageserver_protocol73.InsertReplaceEdit.is(textEdit) ? textEdit.replace : textEdit.range; - let isSnippet = item.insertTextFormat === import_vscode_languageserver_protocol73.InsertTextFormat.Snippet; - let start = line.substr(0, range.start.character); - let end = line.substr(range.end.character); - if (isSnippet && this.completeConfig.snippetsSupport === false) { - isSnippet = false; - newText = word; - } - if (isSnippet) { - let currline = doc.getline(linenr - 1); - let endCharacter = currline.length - end.length; - let r = import_vscode_languageserver_protocol73.Range.create(linenr - 1, range.start.character, linenr - 1, endCharacter); - return await manager_default3.insertSnippet(newText, false, r, item.insertTextMode); - } - let newLines = `${start}${newText}${end}`.split(/\r?\n/); - if (newLines.length == 1) { - await nvim.call("coc#util#setline", [linenr, newLines[0]]); - await window_default.moveTo(import_vscode_languageserver_protocol73.Position.create(linenr - 1, (start + newText).length)); - } else { - let buffer = nvim.createBuffer(bufnr); - await buffer.setLines(newLines, { - start: linenr - 1, - end: linenr, - strictIndexing: false - }); - let line2 = linenr - 1 + newLines.length - 1; - let character = newLines[newLines.length - 1].length - end.length; - await window_default.moveTo({ line: line2, character }); - } - return false; - } - getTriggerKind(opt) { - let { triggerCharacters } = this; - let isTrigger = triggerCharacters.includes(opt.triggerCharacter); - let triggerKind = import_vscode_languageserver_protocol73.CompletionTriggerKind.Invoked; - if (opt.triggerForInComplete) { - triggerKind = import_vscode_languageserver_protocol73.CompletionTriggerKind.TriggerForIncompleteCompletions; - } else if (isTrigger) { - triggerKind = import_vscode_languageserver_protocol73.CompletionTriggerKind.TriggerCharacter; - } - return triggerKind; - } - async applyAdditionalEdits(textEdits, bufnr, snippet) { - if (!textEdits || textEdits.length == 0) - return; - let document2 = workspace_default.getDocument(bufnr); - if (!document2) - return; - await document2.patchChange(true); - let changed = null; - let pos = await window_default.getCursorPosition(); - if (!snippet) - changed = getChangedFromEdits(pos, textEdits); - await document2.applyEdits(textEdits); - if (changed) - await window_default.moveTo(import_vscode_languageserver_protocol73.Position.create(pos.line + changed.line, pos.character + changed.character)); - } - convertVimCompleteItem(item, shortcut, opt, prefix) { - var _a2; - let { echodocSupport, detailMaxLength, invalidInsertCharacters, detailField, labels, defaultKindText } = this.completeConfig; - let hasAdditionalEdit = item.additionalTextEdits && item.additionalTextEdits.length > 0; - let isSnippet = item.insertTextFormat === import_vscode_languageserver_protocol73.InsertTextFormat.Snippet || hasAdditionalEdit; - let label = item.label.trim(); - let obj = { - word: getWord(item, opt, invalidInsertCharacters), - abbr: label, - menu: `[${shortcut}]`, - kind: getKindString(item.kind, labels, defaultKindText), - sortText: item.sortText || null, - sourceScore: item["score"] || null, - filterText: item.filterText || label, - isSnippet, - dup: item.data && item.data.dup == 0 ? 0 : 1 - }; - if (prefix) { - if (!obj.filterText.startsWith(prefix)) { - if (item.textEdit && item.textEdit.newText.startsWith(prefix)) { - obj.filterText = item.textEdit.newText.split(/\r?\n/)[0]; - } - } - if (!item.textEdit && !obj.word.startsWith(prefix)) { - obj.word = `${prefix}${obj.word}`; - } - } - if (item && item.detail && detailField != "preview") { - let detail = item.detail.replace(/\n\s*/g, " "); - if (byteLength(detail) < detailMaxLength) { - if (detailField == "menu") { - obj.menu = `${detail} ${obj.menu}`; - } else if (detailField == "abbr") { - obj.abbr = `${obj.abbr} - ${detail}`; - } - obj.detailShown = 1; - } - } - if (item.documentation) { - obj.info = typeof item.documentation == "string" ? item.documentation : item.documentation.value; - } else { - obj.info = ""; - } - if (obj.word == "") - obj.empty = 1; - if (item.textEdit) - obj.line = opt.line; - if (item.kind == import_vscode_languageserver_protocol73.CompletionItemKind.Folder && !obj.abbr.endsWith("/")) { - obj.abbr = obj.abbr + "/"; - } - if (echodocSupport && item.kind >= 2 && item.kind <= 4) { - let fields = [item.detail || "", obj.abbr, obj.word]; - for (let s of fields) { - if (s.includes("(")) { - obj.signature = s; - break; - } - } - } - if (item.preselect) - obj.preselect = true; - if ((_a2 = item.data) == null ? void 0 : _a2.optional) - obj.abbr = obj.abbr + "?"; - return obj; - } - getPosition(opt) { - let { line, linenr, colnr } = opt; - let part = byteSlice(line, 0, colnr - 1); - return { - line: linenr - 1, - character: part.length - }; - } - }; - } -}); - -// src/sources/source-vim.ts -var logger74, VimSource; -var init_source_vim = __esm({ - "src/sources/source-vim.ts"() { - init_fuzzy(); - init_string(); - init_workspace(); - init_window(); - init_source(); - logger74 = require_logger2()("sources-source-vim"); - VimSource = class extends Source { - async callOptinalFunc(fname, args) { - let exists = this.optionalFns.includes(fname); - if (!exists) - return null; - let name2 = `coc#source#${this.name}#${fname}`; - let res; - try { - res = await this.nvim.call(name2, args); - } catch (e) { - window_default.showMessage(`Vim error from source ${this.name}: ${e.message}`, "error"); - return null; - } - return res; - } - async shouldComplete(opt) { - let shouldRun = await super.shouldComplete(opt); - if (!shouldRun) - return false; - if (!this.optionalFns.includes("should_complete")) - return true; - let res = await this.callOptinalFunc("should_complete", [opt]); - return !!res; - } - async refresh() { - await this.callOptinalFunc("refresh", []); - } - async onCompleteDone(item, _opt) { - if (!this.optionalFns.includes("on_complete")) - return; - await this.callOptinalFunc("on_complete", [item]); - } - onEnter(bufnr) { - if (!this.optionalFns.includes("on_enter")) - return; - let doc = workspace_default.getDocument(bufnr); - if (!doc) - return; - let { filetypes } = this; - if (filetypes && !filetypes.includes(doc.filetype)) - return; - this.callOptinalFunc("on_enter", [{ - bufnr, - uri: doc.uri, - languageId: doc.filetype - }]).logError(); - } - async doComplete(opt, token) { - let { col, input, line, colnr } = opt; - let startcol = await this.callOptinalFunc("get_startcol", [opt]); - if (token.isCancellationRequested) - return; - if (startcol) { - if (startcol < 0) - return null; - startcol = Number(startcol); - if (isNaN(startcol) || startcol < 0) - startcol = col; - if (startcol !== col) { - input = byteSlice(line, startcol, colnr - 1); - opt = Object.assign({}, opt, { - col: startcol, - changed: col - startcol, - input - }); - } - } - let items = await this.nvim.callAsync("coc#util#do_complete", [this.name, opt]); - if (!items || items.length == 0 || token.isCancellationRequested) - return null; - if (this.firstMatch && input.length) { - let ch = input[0]; - items = items.filter((item) => { - let cfirst = item.filterText ? item.filterText[0] : item.word[0]; - return fuzzyChar(ch, cfirst); - }); - } - items = items.map((item) => { - if (typeof item == "string") { - return { word: item, menu: this.menu, isSnippet: this.isSnippet }; - } - let menu = item.menu ? item.menu + " " : ""; - item.menu = `${menu}${this.menu}`; - item.isSnippet = this.isSnippet; - delete item.user_data; - return item; - }); - let res = { items }; - if (startcol) - res.startcol = startcol; - return res; - } - }; - } -}); - -// src/sources/native/around.ts -var around_exports = {}; -__export(around_exports, { - default: () => Around, - regist: () => regist -}); -function regist(sourceMap) { - sourceMap.set("around", new Around()); - return import_vscode_languageserver_protocol74.Disposable.create(() => { - sourceMap.delete("around"); - }); -} -var import_vscode_languageserver_protocol74, logger75, Around; -var init_around = __esm({ - "src/sources/native/around.ts"() { - import_vscode_languageserver_protocol74 = __toModule(require_main2()); - init_source(); - init_workspace(); - logger75 = require_logger2()("sources-around"); - Around = class extends Source { - constructor() { - super({ - name: "around", - filepath: __filename - }); - } - doComplete(opt) { - let { bufnr, input } = opt; - if (input.length === 0) - return null; - let document2 = workspace_default.getDocument(bufnr); - if (!document2) - return null; - let words = document2.words; - let moreWords = document2.getMoreWords(); - words.push(...moreWords); - words = this.filterWords(words, opt); - return Promise.resolve({ - items: words.map((word) => ({ - word, - menu: this.menu - })) - }); - } - }; - } -}); - -// src/sources/native/buffer.ts -var buffer_exports = {}; -__export(buffer_exports, { - default: () => Buffer3, - regist: () => regist2 -}); -function regist2(sourceMap) { - sourceMap.set("buffer", new Buffer3()); - return import_vscode_languageserver_protocol75.Disposable.create(() => { - sourceMap.delete("buffer"); - }); -} -var import_vscode_languageserver_protocol75, logger76, Buffer3; -var init_buffer2 = __esm({ - "src/sources/native/buffer.ts"() { - import_vscode_languageserver_protocol75 = __toModule(require_main2()); - init_source(); - init_workspace(); - logger76 = require_logger2()("sources-buffer"); - Buffer3 = class extends Source { - constructor() { - super({ - name: "buffer", - filepath: __filename - }); - } - get ignoreGitignore() { - return this.getConfig("ignoreGitignore", true); - } - getWords(bufnr) { - let { ignoreGitignore } = this; - let words = []; - workspace_default.documents.forEach((document2) => { - if (document2.bufnr == bufnr) - return; - if (ignoreGitignore && document2.isIgnored) - return; - for (let word of document2.words) { - if (!words.includes(word)) { - words.push(word); - } - } - }); - return words; - } - doComplete(opt) { - let { bufnr, input } = opt; - if (input.length == 0) - return null; - let words = this.getWords(bufnr); - words = this.filterWords(words, opt); - return Promise.resolve({ - items: words.map((word) => ({ - word, - menu: this.menu - })) - }); - } - }; - } -}); - -// src/sources/native/file.ts -var file_exports = {}; -__export(file_exports, { - default: () => File, - regist: () => regist3 -}); -function regist3(sourceMap) { - sourceMap.set("file", new File()); - return import_vscode_languageserver_protocol76.Disposable.create(() => { - sourceMap.delete("file"); - }); -} -var import_fs29, import_minimatch6, import_path31, import_util38, import_vscode_languageserver_protocol76, logger77, pathRe, File; -var init_file = __esm({ - "src/sources/native/file.ts"() { - import_fs29 = __toModule(require("fs")); - import_minimatch6 = __toModule(require_minimatch()); - import_path31 = __toModule(require("path")); - import_util38 = __toModule(require("util")); - import_vscode_languageserver_protocol76 = __toModule(require_main2()); - init_source(); - init_fs(); - init_string(); - init_workspace(); - logger77 = require_logger2()("sources-file"); - pathRe = /(?:\.{0,2}|~|\$HOME|([\w]+)|[a-zA-Z]:|)(\/|\\)(?:[\u4e00-\u9fa5\w.@()-]+(\/|\\))*(?:[\u4e00-\u9fa5\w.@()-])*$/; - File = class extends Source { - constructor() { - super({ - name: "file", - filepath: __filename - }); - } - resolveEnvVariables(str) { - let replaced = str; - replaced = replaced.replace(/%([^%]+)%/g, (_, n) => process.env[n]); - replaced = replaced.replace(/\$([A-Z_]+[A-Z0-9_]*)|\${([A-Z0-9_]*)}/gi, (_, a, b) => process.env[a || b]); - return replaced; - } - getPathOption(opt) { - let { line, colnr } = opt; - let part = byteSlice(line, 0, colnr - 1); - part = this.resolveEnvVariables(part); - if (!part || part.endsWith("//")) - return null; - let ms = part.match(pathRe); - if (ms && ms.length) { - const pathstr = workspace_default.expand(ms[0]); - let input = ms[0].match(/[^/\\]*$/)[0]; - return { pathstr, part: ms[1], startcol: colnr - input.length - 1, input }; - } - return null; - } - async getFileItem(root, filename) { - let f = import_path31.default.join(root, filename); - let stat = await statAsync(f); - if (stat) { - let abbr = stat.isDirectory() ? filename + "/" : filename; - let word = filename; - return { word, abbr }; - } - return null; - } - filterFiles(files) { - let ignoreHidden = this.getConfig("ignoreHidden", true); - let ignorePatterns = this.getConfig("ignorePatterns", []); - return files.filter((f) => { - if (f == null) - return false; - if (ignoreHidden && f.startsWith(".")) - return false; - for (let p of ignorePatterns) { - if ((0, import_minimatch6.default)(f, p, { dot: true })) - return false; - } - return true; - }); - } - async getItemsFromRoot(pathstr, root) { - let res = []; - let part = pathstr.endsWith("/") ? pathstr : import_path31.default.dirname(pathstr); - let dir = import_path31.default.isAbsolute(pathstr) ? part : import_path31.default.join(root, part); - try { - let stat = await statAsync(dir); - if (stat && stat.isDirectory()) { - let files = await import_util38.default.promisify(import_fs29.default.readdir)(dir); - files = this.filterFiles(files); - let items = await Promise.all(files.map((filename) => this.getFileItem(dir, filename))); - res = res.concat(items); - } - res = res.filter((item) => item != null); - return res; - } catch (e) { - logger77.error(`Error on list files:`, e); - return res; - } - } - get trimSameExts() { - return this.getConfig("trimSameExts", []); - } - async doComplete(opt) { - let { col, filepath } = opt; - let option = this.getPathOption(opt); - if (!option) - return null; - let { pathstr, part, startcol, input } = option; - if (startcol < opt.col) - return null; - let startPart = opt.col == startcol ? "" : byteSlice(opt.line, opt.col, startcol); - let dirname3 = import_path31.default.dirname(filepath); - let ext = import_path31.default.extname(import_path31.default.basename(filepath)); - let cwd = await this.nvim.call("getcwd", []); - let root; - if (pathstr.startsWith(".")) { - root = filepath ? import_path31.default.dirname(filepath) : cwd; - } else if (pathstr.startsWith("/")) { - root = pathstr.endsWith("/") ? pathstr : import_path31.default.dirname(pathstr); - } else if (part) { - if (import_fs29.default.existsSync(import_path31.default.join(dirname3, part))) { - root = dirname3; - } else if (import_fs29.default.existsSync(import_path31.default.join(cwd, part))) { - root = cwd; - } - } else { - root = cwd; - } - if (!root) - return null; - let items = await this.getItemsFromRoot(pathstr, root); - let trimExt = this.trimSameExts.includes(ext); - let first = input[0]; - if (first && col == startcol) - items = items.filter((o) => o.word[0] === first); - return { - items: items.map((item) => { - let ex = import_path31.default.extname(item.word); - item.word = trimExt && ex === ext ? item.word.replace(ext, "") : item.word; - return { - word: `${startPart}${item.word}`, - abbr: `${startPart}${item.abbr}`, - menu: this.menu - }; - }) - }; - } - }; - } -}); - -// src/sources/index.ts -var sources_exports = {}; -__export(sources_exports, { - Sources: () => Sources, - default: () => sources_default -}); -var import_fast_diff3, import_fs31, import_path32, import_util39, import_vscode_languageserver_protocol77, logger78, Sources, sources_default; -var init_sources2 = __esm({ - "src/sources/index.ts"() { - import_fast_diff3 = __toModule(require_diff()); - import_fs31 = __toModule(require("fs")); - import_path32 = __toModule(require("path")); - import_util39 = __toModule(require("util")); - import_vscode_languageserver_protocol77 = __toModule(require_main2()); - init_events(); - init_extensions2(); - init_types(); - init_util(); - init_fs(); - init_match(); - init_object(); - init_string(); - init_window(); - init_workspace(); - init_source(); - init_source_language(); - init_source_vim(); - logger78 = require_logger2()("sources"); - Sources = class { - constructor() { - this.sourceMap = new Map(); - this.disposables = []; - this.remoteSourcePaths = []; - } - init() { - this.loadCompleteConfig(); - workspace_default.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("suggest")) { - this.loadCompleteConfig(); - } - }, null, this.disposables); - this.createNativeSources(); - this.createRemoteSources(); - events_default.on("BufEnter", this.onDocumentEnter, this, this.disposables); - workspace_default.watchOption("runtimepath", async (oldValue, newValue) => { - let result = (0, import_fast_diff3.default)(oldValue, newValue); - for (let [changeType, value] of result) { - if (changeType == 1) { - let paths = value.replace(/,$/, "").split(","); - for (let p of paths) { - if (p) - await this.createVimSources(p); - } - } - } - }, this.disposables); - } - loadCompleteConfig() { - let suggest = workspace_default.getConfiguration("suggest"); - let labels = suggest.get("completionItemKindLabels", {}); - let map = new Map([ - [import_vscode_languageserver_protocol77.CompletionItemKind.Text, labels["text"] || "v"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Method, labels["method"] || "f"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Function, labels["function"] || "f"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Constructor, typeof labels["constructor"] == "function" ? "f" : labels["constructor"]], - [import_vscode_languageserver_protocol77.CompletionItemKind.Field, labels["field"] || "m"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Variable, labels["variable"] || "v"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Class, labels["class"] || "C"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Interface, labels["interface"] || "I"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Module, labels["module"] || "M"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Property, labels["property"] || "m"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Unit, labels["unit"] || "U"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Value, labels["value"] || "v"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Enum, labels["enum"] || "E"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Keyword, labels["keyword"] || "k"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Snippet, labels["snippet"] || "S"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Color, labels["color"] || "v"], - [import_vscode_languageserver_protocol77.CompletionItemKind.File, labels["file"] || "F"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Reference, labels["reference"] || "r"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Folder, labels["folder"] || "F"], - [import_vscode_languageserver_protocol77.CompletionItemKind.EnumMember, labels["enumMember"] || "m"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Constant, labels["constant"] || "v"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Struct, labels["struct"] || "S"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Event, labels["event"] || "E"], - [import_vscode_languageserver_protocol77.CompletionItemKind.Operator, labels["operator"] || "O"], - [import_vscode_languageserver_protocol77.CompletionItemKind.TypeParameter, labels["typeParameter"] || "T"] - ]); - let floatEnable = suggest.get("floatEnable", true); - let detailField = suggest.get("detailField", "preview"); - if (detailField == "preview" && (!floatEnable || !workspace_default.floatSupported)) { - detailField = "menu"; - } - this.completeConfig = Object.assign(this.completeConfig || {}, { - labels: map, - floatEnable, - detailField, - defaultKindText: labels["default"] || "", - priority: suggest.get("languageSourcePriority", 99), - echodocSupport: suggest.get("echodocSupport", false), - snippetsSupport: suggest.get("snippetsSupport", true), - detailMaxLength: suggest.get("detailMaxLength", 100), - invalidInsertCharacters: suggest.get("invalidInsertCharacters", ["(", "<", "{", "[", "\r", "\n"]) - }); - } - get nvim() { - return workspace_default.nvim; - } - createNativeSources() { - try { - this.disposables.push((init_around(), around_exports).regist(this.sourceMap)); - this.disposables.push((init_buffer2(), buffer_exports).regist(this.sourceMap)); - this.disposables.push((init_file(), file_exports).regist(this.sourceMap)); - } catch (e) { - console.error("Create source error:" + e.message); - } - } - createLanguageSource(name2, shortcut, selector, provider, triggerCharacters, priority, allCommitCharacters) { - let source = new LanguageSource(name2, shortcut, provider, selector, triggerCharacters || [], allCommitCharacters || [], priority, this.completeConfig); - logger78.debug("created service source", name2); - this.sourceMap.set(name2, source); - return { - dispose: () => { - this.sourceMap.delete(name2); - } - }; - } - async createVimSourceExtension(nvim, filepath) { - let name2 = import_path32.default.basename(filepath, ".vim"); - try { - await nvim.command(`source ${filepath}`); - let fns = await nvim.call("coc#util#remote_fns", name2); - for (let fn of ["init", "complete"]) { - if (!fns.includes(fn)) { - window_default.showMessage(`${fn} not found for source ${name2}`, "error"); - return null; - } - } - let props = await nvim.call(`coc#source#${name2}#init`, []); - let packageJSON = { - name: `coc-source-${name2}`, - engines: { - coc: ">= 0.0.1" - }, - activationEvents: props.filetypes ? props.filetypes.map((f) => `onLanguage:${f}`) : ["*"], - contributes: { - configuration: { - properties: { - [`coc.source.${name2}.enable`]: { - type: "boolean", - default: true - }, - [`coc.source.${name2}.firstMatch`]: { - type: "boolean", - default: !!props.firstMatch - }, - [`coc.source.${name2}.triggerCharacters`]: { - type: "number", - default: props.triggerCharacters || [] - }, - [`coc.source.${name2}.priority`]: { - type: "number", - default: props.priority || 9 - }, - [`coc.source.${name2}.shortcut`]: { - type: "string", - default: props.shortcut || name2.slice(0, 3).toUpperCase(), - description: "Shortcut text shown in complete menu." - }, - [`coc.source.${name2}.disableSyntaxes`]: { - type: "array", - default: [], - items: { - type: "string" - } - }, - [`coc.source.${name2}.filetypes`]: { - type: "array", - default: props.filetypes || null, - description: "Enabled filetypes.", - items: { - type: "string" - } - } - } - } - } - }; - let source = new VimSource({ - name: name2, - filepath, - sourceType: SourceType.Remote, - optionalFns: fns.filter((n) => !["init", "complete"].includes(n)) - }); - let isActive = false; - let extension = { - id: packageJSON.name, - packageJSON, - exports: void 0, - extensionPath: filepath, - activate: () => { - isActive = true; - this.addSource(source); - return Promise.resolve(); - } - }; - Object.defineProperty(extension, "isActive", { - get: () => isActive - }); - extensions_default.registerExtension(extension, () => { - isActive = false; - this.removeSource(source); - }); - } catch (e) { - window_default.showMessage(`Error on create vim source ${name2}: ${e.message}`, "error"); - } - } - createRemoteSources() { - let { runtimepath } = workspace_default.env; - let paths = runtimepath.split(","); - for (let path36 of paths) { - this.createVimSources(path36).logError(); - } - } - async createVimSources(pluginPath) { - if (this.remoteSourcePaths.includes(pluginPath)) - return; - this.remoteSourcePaths.push(pluginPath); - let folder = import_path32.default.join(pluginPath, "autoload/coc/source"); - let stat = await statAsync(folder); - if (stat && stat.isDirectory()) { - let arr = await import_util39.default.promisify(import_fs31.default.readdir)(folder); - arr = arr.filter((s) => s.endsWith(".vim")); - let files = arr.map((s) => import_path32.default.join(folder, s)); - if (files.length == 0) - return; - await Promise.all(files.map((p) => this.createVimSourceExtension(this.nvim, p))); - } - } - get names() { - return Array.from(this.sourceMap.keys()); - } - get sources() { - return Array.from(this.sourceMap.values()); - } - has(name2) { - return this.names.findIndex((o) => o == name2) != -1; - } - getSource(name2) { - if (!name2) - return null; - return this.sourceMap.get(name2) || null; - } - shouldCommit(item, commitCharacter) { - if (!item || !item.source) - return false; - let source = this.getSource(item.source); - if (source && source.sourceType == SourceType.Service && typeof source.shouldCommit === "function") { - return source.shouldCommit(item, commitCharacter); - } - return false; - } - getCompleteSources(opt) { - let { filetype } = opt; - let pre = byteSlice(opt.line, 0, opt.colnr - 1); - let isTriggered = opt.input == "" && !!opt.triggerCharacter; - let uri = getUri(opt.filepath, opt.bufnr, "", workspace_default.env.isCygwin); - if (isTriggered) - return this.getTriggerSources(pre, filetype, uri); - return this.getNormalSources(opt.filetype, uri); - } - getNormalSources(filetype, uri) { - return this.sources.filter((source) => { - let { filetypes, triggerOnly, documentSelector, enable } = source; - if (!enable || triggerOnly || filetypes && !filetypes.includes(filetype)) { - return false; - } - if (documentSelector && score(documentSelector, uri, filetype) == 0) { - return false; - } - if (this.disabledByLanguageId(source, filetype)) { - return false; - } - return true; - }); - } - checkTrigger(source, pre, character) { - let { triggerCharacters, triggerPatterns } = source; - if (!triggerCharacters && !triggerPatterns) - return false; - if (character && triggerCharacters && triggerCharacters.includes(character)) { - return true; - } - if (triggerPatterns && triggerPatterns.findIndex((p) => p.test(pre)) !== -1) { - return true; - } - return false; - } - shouldTrigger(pre, languageId, uri) { - let sources = this.getTriggerSources(pre, languageId, uri); - return sources.length > 0; - } - getTriggerSources(pre, languageId, uri) { - let character = pre.length ? pre[pre.length - 1] : ""; - if (!character) - return []; - return this.sources.filter((source) => { - let { filetypes, enable, documentSelector } = source; - if (!enable || filetypes && !filetypes.includes(languageId)) { - return false; - } - if (documentSelector && score(documentSelector, uri, languageId) == 0) { - return false; - } - if (this.disabledByLanguageId(source, languageId)) - return false; - return this.checkTrigger(source, pre, character); - }); - } - addSource(source) { - let { name: name2 } = source; - if (this.names.includes(name2)) { - logger78.warn(`Recreate source ${name2}`); - } - this.sourceMap.set(name2, source); - return import_vscode_languageserver_protocol77.Disposable.create(() => { - this.sourceMap.delete(name2); - }); - } - removeSource(source) { - let name2 = typeof source == "string" ? source : source.name; - this.sourceMap.delete(name2); - } - async refresh(name2) { - for (let source of this.sources) { - if (!name2 || source.name == name2) { - if (typeof source.refresh === "function") { - await Promise.resolve(source.refresh()); - } - } - } - } - toggleSource(name2) { - if (!name2) - return; - let source = this.getSource(name2); - if (!source) - return; - if (typeof source.toggle === "function") { - source.toggle(); - } - } - sourceStats() { - let res = []; - let items = this.sources; - for (let item of items) { - res.push({ - name: item.name, - priority: item.priority, - triggerCharacters: item.triggerCharacters || [], - shortcut: item.shortcut || "", - filetypes: item.filetypes || [], - filepath: item.filepath || "", - type: item.sourceType == SourceType.Native ? "native" : item.sourceType == SourceType.Remote ? "remote" : "service", - disabled: !item.enable - }); - } - return res; - } - onDocumentEnter(bufnr) { - let { sources } = this; - for (let s of sources) { - if (s.enable && typeof s.onEnter == "function") { - s.onEnter(bufnr); - } - } - } - createSource(config) { - if (!config.name || !config.doComplete) { - throw new Error(`name and doComplete required for createSource`); - } - let source = new Source(Object.assign({ sourceType: SourceType.Service }, config)); - return this.addSource(source); - } - disabledByLanguageId(source, languageId) { - let map = workspace_default.env.disabledSources; - if (isEmpty(map)) - return false; - let list2 = map ? map[languageId] : []; - return Array.isArray(list2) && list2.includes(source.name); - } - dispose() { - disposeAll(this.disposables); - } - }; - sources_default = new Sources(); - } -}); - -// src/completion/match.ts -function nextWordIndex(start = 0, codes) { - for (let i = start; i < codes.length; i++) { - if (isWordIndex(i, codes)) { - return i; - } - } - return -1; -} -function upperCase(code) { - return code >= 65 && code <= 90; -} -function isWordIndex(index, codes) { - if (index == 0) - return true; - let curr = codes[index]; - if (!wordChar(curr)) - return false; - let pre = codes[index - 1]; - if (!wordChar(pre)) - return true; - if (upperCase(curr) && !upperCase(pre)) - return true; - return false; -} -function matchScore(word, input) { - if (input.length == 0 || word.length < input.length) - return 0; - let codes = getCharCodes(word); - let curr = codes[0]; - let score5 = 0; - let first = input[0]; - let idx = 1; - let allowFuzzy = true; - if (caseMatch(first, curr)) { - score5 = first == curr ? 5 : 2.5; - idx = 1; - } else { - let next2 = nextWordIndex(1, codes); - if (next2 != -1) { - if (caseMatch(first, codes[next2])) { - score5 = first == codes[next2] ? 2.5 : 2; - idx = next2 + 1; - } - } - if (score5 == 0) { - for (let i = 1; i < codes.length; i++) { - if (caseMatch(first, codes[i])) { - score5 = first == codes[i] ? 1 : 0.5; - idx = i + 1; - allowFuzzy = false; - } - } - } - } - if (input.length == 1 || score5 == 0) - return score5; - let next = nextScore(codes, idx, input.slice(1), allowFuzzy); - return next == 0 ? 0 : score5 + next; -} -function nextScore(codes, index, inputCodes, allowFuzzy = true) { - if (index >= codes.length) - return 0; - let scores = []; - let input = inputCodes[0]; - let len = codes.length; - let isFinal = inputCodes.length == 1; - if (!wordChar(input)) { - for (let i = index; i < len; i++) { - if (codes[i] == input) { - if (isFinal) - return 1; - let next = nextScore(codes, i + 1, inputCodes.slice(1), allowFuzzy); - return next == 0 ? 0 : 1 + next; - } - } - return 0; - } - let curr = codes[index]; - let match = caseMatch(input, curr); - if (match) { - let score5 = input == curr ? 1 : 0.5; - if (!isFinal) { - let next = nextScore(codes, index + 1, inputCodes.slice(1), allowFuzzy); - score5 = next == 0 ? 0 : score5 + next; - } - scores.push(score5); - } - if (wordChar(input) && !isWordIndex(index, codes)) { - let idx = nextWordIndex(index + 1, codes); - if (idx !== -1) { - let next = codes[idx]; - if (caseMatch(input, next)) { - let score5 = input == next ? 1 : 0.75; - if (!isFinal) { - let next2 = nextScore(codes, idx + 1, inputCodes.slice(1), allowFuzzy); - score5 = next2 == 0 ? 0 : score5 + next2; - } - scores.push(score5); - } - } - } - if (!match && allowFuzzy) { - for (let i = index + 1; i < len; i++) { - let code = codes[i]; - if (caseMatch(input, code)) { - let score5 = input == code ? 0.1 : 0.05; - if (!isFinal) { - let next = nextScore(codes, i + 1, inputCodes.slice(1), false); - score5 = next == 0 ? 0 : score5 + next; - } - scores.push(score5); - } - } - } - if (!scores.length) - return 0; - return Math.max(...scores); -} -var init_match2 = __esm({ - "src/completion/match.ts"() { - init_fuzzy(); - } -}); - -// src/completion/complete.ts -var import_vscode_languageserver_protocol78, logger79, FIRST_TIMEOUT, Complete; -var init_complete = __esm({ - "src/completion/complete.ts"() { - import_vscode_languageserver_protocol78 = __toModule(require_main2()); - init_fuzzy(); - init_string(); - init_match2(); - logger79 = require_logger2()("completion-complete"); - FIRST_TIMEOUT = 500; - Complete = class { - constructor(option, document2, config, sources, nvim) { - this.option = option; - this.document = document2; - this.config = config; - this.sources = sources; - this.nvim = nvim; - this.results = []; - this.completing = new Set(); - this._canceled = false; - this.tokenSources = new Map(); - this._onDidComplete = new import_vscode_languageserver_protocol78.Emitter(); - this.onDidComplete = this._onDidComplete.event; - } - get isCompleting() { - return this.completing.size > 0; - } - get isCanceled() { - return this._canceled; - } - get isEmpty() { - return this.results.length == 0; - } - get startcol() { - return this.option.col || 0; - } - get input() { - return this.option.input; - } - get isIncomplete() { - return this.results.findIndex((o) => o.isIncomplete) !== -1; - } - async completeSource(source) { - let { col } = this.option; - let opt = Object.assign({}, this.option); - let timeout = this.config.timeout; - timeout = Math.max(Math.min(timeout, 15e3), 500); - try { - if (typeof source.shouldComplete === "function") { - let shouldRun = await Promise.resolve(source.shouldComplete(opt)); - if (!shouldRun) - return null; - } - let start = Date.now(); - let oldSource = this.tokenSources.get(source.name); - if (oldSource) - oldSource.cancel(); - let tokenSource = new import_vscode_languageserver_protocol78.CancellationTokenSource(); - this.tokenSources.set(source.name, tokenSource); - await new Promise((resolve3, reject) => { - let { name: name2 } = source; - let timer = setTimeout(() => { - this.nvim.command(`echohl WarningMsg| echom 'source ${source.name} timeout after ${timeout}ms'|echohl None`, true); - tokenSource.cancel(); - }, timeout); - let cancelled = false; - let called = false; - let empty = false; - let ft = setTimeout(() => { - if (called) - return; - empty = true; - resolve3(void 0); - }, FIRST_TIMEOUT); - let onFinished = () => { - if (called) - return; - called = true; - disposable.dispose(); - clearTimeout(ft); - clearTimeout(timer); - this.tokenSources.delete(name2); - }; - let disposable = tokenSource.token.onCancellationRequested(() => { - disposable.dispose(); - this.completing.delete(name2); - cancelled = true; - onFinished(); - logger79.debug(`Source "${name2}" cancelled`); - resolve3(void 0); - }); - this.completing.add(name2); - Promise.resolve(source.doComplete(opt, tokenSource.token)).then((result) => { - this.completing.delete(name2); - if (cancelled) - return; - onFinished(); - let dt = Date.now() - start; - logger79.debug(`Source "${name2}" takes ${dt}ms`); - if (result && result.items && result.items.length) { - result.priority = source.priority; - result.source = name2; - if (empty && result.startcol && result.startcol != col) { - this.results = [result]; - } else { - let { results } = this; - let idx = results.findIndex((o) => o.source == name2); - if (idx != -1) { - results.splice(idx, 1, result); - } else { - results.push(result); - } - } - if (empty) - this._onDidComplete.fire(); - resolve3(void 0); - } else { - let { results } = this; - this.results = results.filter((res) => res.source != name2); - resolve3(void 0); - } - }, (err) => { - this.completing.delete(name2); - onFinished(); - reject(err); - }); - }); - } catch (err) { - this.nvim.command(`echoerr 'Complete ${source.name} error: ${err.message.replace(/'/g, "''")}'`, true); - logger79.error("Complete error:", source.name, err); - } - } - async completeInComplete(resumeInput) { - let { results, document: document2 } = this; - let remains = results.filter((res) => !res.isIncomplete); - remains.forEach((res) => { - res.items.forEach((item) => delete item.user_data); - }); - let arr = results.filter((res) => res.isIncomplete); - let names = arr.map((o) => o.source); - let { input, colnr, linenr } = this.option; - Object.assign(this.option, { - input: resumeInput, - line: document2.getline(linenr - 1), - colnr: colnr + (resumeInput.length - input.length), - triggerCharacter: null, - triggerForInComplete: true - }); - let sources = this.sources.filter((s) => names.includes(s.name)); - await Promise.all(sources.map((s) => this.completeSource(s))); - return this.filterResults(resumeInput, Math.floor(Date.now() / 1e3)); - } - filterResults(input, cid = 0) { - let { results } = this; - results.sort((a, b) => { - if (a.source == "tabnine") - return 1; - if (b.source == "tabnine") - return -1; - return b.priority - a.priority; - }); - let { snippetIndicator, removeDuplicateItems, fixInsertedWord, asciiCharactersOnly } = this.config; - let followPart = !fixInsertedWord || cid == 0 ? "" : this.getFollowPart(); - if (results.length == 0) - return []; - let arr = []; - let codes = getCharCodes(input); - let words = new Set(); - for (let i = 0, l = results.length; i < l; i++) { - let res = results[i]; - let { items, source, priority } = res; - for (let idx = 0; idx < items.length; idx++) { - let item = items[idx]; - if (!item || typeof item.word !== "string") { - continue; - } - let { word } = item; - if (asciiCharactersOnly && !/^[\x00-\x7F]*$/.test(word)) { - continue; - } - if (!item.dup && words.has(word)) - continue; - if (removeDuplicateItems && !item.isSnippet && words.has(word) && item.line == void 0) - continue; - let filterText = item.filterText || item.word; - item.filterText = filterText; - if (filterText.length < input.length) - continue; - let score5 = item.kind && filterText == input ? 64 : matchScore(filterText, codes); - if (input.length && score5 == 0) - continue; - if (followPart.length && !item.isSnippet) { - if (item.word.endsWith(followPart)) { - let { word: word2 } = item; - item.word = item.word.slice(0, -followPart.length); - item.abbr = item.abbr || word2; - } - } - if (!item.user_data) { - let user_data = { cid, source }; - user_data.index = item.index || idx; - if (item.isSnippet) { - let abbr = item.abbr || item.word; - if (!abbr.endsWith(snippetIndicator)) { - item.abbr = `${item.abbr || item.word}${snippetIndicator}`; - } - } - if (item.signature) - user_data.signature = item.signature; - item.user_data = JSON.stringify(user_data); - item.source = source; - } - item.priority = priority; - item.abbr = item.abbr || item.word; - item.score = input.length ? score5 * (item.sourceScore || 1) : 0; - item.localBonus = this.localBonus ? this.localBonus.get(filterText) || 0 : 0; - words.add(word); - if (item.isSnippet && input.length && item.word == input) { - item.preselect = true; - } - arr.push(item); - } - } - arr.sort((a, b) => { - let sa = a.sortText; - let sb = b.sortText; - let wa = a.filterText; - let wb = b.filterText; - if (a.score != b.score) - return b.score - a.score; - if (a.priority != b.priority) - return b.priority - a.priority; - if (sa && sb && sa != sb) - return sa < sb ? -1 : 1; - if (a.localBonus != b.localBonus) { - if (a.localBonus && b.localBonus && wa != wb) { - if (wa.startsWith(wb)) - return 1; - if (wb.startsWith(wa)) - return -1; - } - return b.localBonus - a.localBonus; - } - switch (this.config.defaultSortMethod) { - case "none": - return 0; - case "alphabetical": - return a.filterText.localeCompare(b.filterText); - case "length": - default: - return a.filterText.length - b.filterText.length; - } - }); - return this.limitCompleteItems(arr.slice(0, this.config.maxItemCount)); - } - limitCompleteItems(items) { - let { highPrioritySourceLimit, lowPrioritySourceLimit } = this.config; - if (!highPrioritySourceLimit && !lowPrioritySourceLimit) - return items; - let counts = new Map(); - return items.filter((item) => { - let { priority, source } = item; - let isLow = priority < 90; - let curr = counts.get(source) || 0; - if (lowPrioritySourceLimit && isLow && curr == lowPrioritySourceLimit || highPrioritySourceLimit && !isLow && curr == highPrioritySourceLimit) { - return false; - } - counts.set(source, curr + 1); - return true; - }); - } - hasMatch(input) { - let { results } = this; - if (!results) - return false; - let codes = getCharCodes(input); - for (let i = 0, l = results.length; i < l; i++) { - let items = results[i].items; - let idx = items.findIndex((item) => fuzzyMatch(codes, item.filterText || item.word)); - if (idx !== -1) - return true; - } - return false; - } - async doComplete() { - let opts = this.option; - let { line, colnr, linenr, col } = this.option; - if (this.config.localityBonus) { - let line2 = linenr - 1; - this.localBonus = this.document.getLocalifyBonus(import_vscode_languageserver_protocol78.Position.create(line2, opts.col - 1), import_vscode_languageserver_protocol78.Position.create(line2, colnr)); - } else { - this.localBonus = new Map(); - } - await Promise.all(this.sources.map((s) => this.completeSource(s))); - let { results } = this; - if (results.length == 0) - return []; - let engrossResult = results.find((r) => r.startcol != null && r.startcol != col); - if (engrossResult) { - let { startcol } = engrossResult; - opts.col = startcol; - opts.input = byteSlice(line, startcol, colnr - 1); - this.results = [engrossResult]; - } - logger79.info(`Results from: ${this.results.map((s) => s.source).join(",")}`); - return this.filterResults(opts.input, Math.floor(Date.now() / 1e3)); - } - resolveCompletionItem(item) { - let { results } = this; - if (!results) - return null; - try { - if (item.user_data) { - let { source } = JSON.parse(item.user_data); - let result = results.find((res) => res.source == source); - return result.items.find((o) => o.user_data == item.user_data); - } - for (let result of results) { - let res = result.items.find((o) => o.abbr == item.abbr && o.info == item.info); - if (res) - return res; - } - return null; - } catch (e) { - return null; - } - } - getFollowPart() { - let { colnr, line } = this.option; - let idx = characterIndex(line, colnr - 1); - if (idx == line.length) - return ""; - let part = line.slice(idx - line.length); - return part.match(/^\S?[\w-]*/)[0]; - } - dispose() { - if (this._canceled) - return; - this._onDidComplete.dispose(); - this._canceled = true; - for (let tokenSource of this.tokenSources.values()) { - tokenSource.cancel(); - } - this.tokenSources.clear(); - this.sources = []; - this.results = []; - } - }; - } -}); - -// src/completion/floating.ts -var logger80, Floating; -var init_floating = __esm({ - "src/completion/floating.ts"() { - init_markdown(); - logger80 = require_logger2()("floating"); - Floating = class { - constructor(nvim, isVim7) { - this.nvim = nvim; - this.isVim = isVim7; - this.winid = 0; - this.bufnr = 0; - } - async show(docs, bounding, config, token) { - let { nvim } = this; - docs = docs.filter((o) => o.content.trim().length > 0); - let { lines, codes, highlights } = parseDocuments(docs, { excludeImages: config.excludeImages }); - if (lines.length == 0) { - this.close(); - return; - } - let opts = { - codes, - highlights, - maxWidth: config.maxWidth || 80, - pumbounding: bounding - }; - if (config.border) - opts.border = [1, 1, 1, 1]; - if (config.highlight) - opts.highlight = config.highlight; - if (config.borderhighlight) - opts.borderhighlight = config.borderhighlight; - if (!this.isVim) { - if (typeof config.winblend === "number") - opts.winblend = config.winblend; - opts.focusable = config.focusable === true ? 1 : 0; - if (config.shadow) - opts.shadow = 1; - } - let res = await nvim.call("coc#float#create_pum_float", [this.winid, this.bufnr, lines, opts]); - if (this.isVim) - nvim.command("redraw", true); - if (!res || res.length == 0) - return; - this.winid = res[0]; - this.bufnr = res[1]; - if (token.isCancellationRequested) { - this.close(); - return; - } - } - close() { - let { winid, nvim } = this; - this.winid = 0; - if (!winid) - return; - nvim.call("coc#float#close", [winid], true); - if (this.isVim) - nvim.command("redraw", true); - } - }; - } -}); - -// src/completion/index.ts -var import_vscode_languageserver_protocol79, import_debounce9, logger81, completeItemKeys, Completion, completion_default; -var init_completion = __esm({ - "src/completion/index.ts"() { - import_vscode_languageserver_protocol79 = __toModule(require_main2()); - init_events(); - init_sources2(); - init_util(); - init_is(); - init_workspace(); - init_complete(); - init_floating(); - import_debounce9 = __toModule(require_debounce()); - init_string(); - init_object(); - logger81 = require_logger2()("completion"); - completeItemKeys = ["abbr", "menu", "info", "kind", "icase", "dup", "empty", "user_data"]; - Completion = class { - constructor() { - this.activated = false; - this.disposables = []; - this.complete = null; - this.changedTick = 0; - this.insertCharTs = 0; - this.insertLeaveTs = 0; - } - init() { - this.config = this.getCompleteConfig(); - workspace_default.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("suggest")) { - this.config = this.getCompleteConfig(); - } - }, null, this.disposables); - workspace_default.watchOption("completeopt", async (_, newValue) => { - workspace_default.env.completeOpt = newValue; - if (!this.isActivated) - return; - if (this.config.autoTrigger === "always") { - let content = await this.nvim.call("execute", ["verbose set completeopt"]); - let lines = content.split(/\r?\n/); - console.error(`Some plugin change completeopt during completion: ${lines[lines.length - 1].trim()}!`); - } - }, this.disposables); - this.excludeImages = workspace_default.getConfiguration("coc.preferences").get("excludeImageLinksInMarkdownDocument"); - this.floating = new Floating(workspace_default.nvim, workspace_default.env.isVim); - events_default.on(["InsertCharPre", "MenuPopupChanged", "TextChangedI", "CursorMovedI", "InsertLeave"], () => { - if (this.triggerTimer) { - clearTimeout(this.triggerTimer); - this.triggerTimer = null; - } - }, this, this.disposables); - events_default.on("InsertCharPre", this.onInsertCharPre, this, this.disposables); - events_default.on("InsertLeave", this.onInsertLeave, this, this.disposables); - events_default.on("InsertEnter", this.onInsertEnter, this, this.disposables); - events_default.on("TextChangedP", this.onTextChangedP, this, this.disposables); - events_default.on("TextChangedI", this.onTextChangedI, this, this.disposables); - let fn = (0, import_debounce9.default)(this.onPumChange.bind(this), 20); - this.disposables.push({ - dispose: () => { - fn.clear(); - } - }); - events_default.on("CompleteDone", async (item) => { - this.popupEvent = null; - if (!this.activated) - return; - fn.clear(); - this.cancelResolve(); - this.floating.close(); - await this.onCompleteDone(item); - }, this, this.disposables); - this.cancelResolve(); - events_default.on("MenuPopupChanged", (ev) => { - if (!this.activated || this.isCommandLine) - return; - if (equals(this.popupEvent, ev)) - return; - this.cancelResolve(); - this.popupEvent = ev; - fn(); - }, this, this.disposables); - } - get nvim() { - return workspace_default.nvim; - } - get option() { - if (!this.complete) - return null; - return this.complete.option; - } - get selectedItem() { - if (!this.popupEvent) - return null; - let { completed_item } = this.popupEvent; - return vimCompleteItem(completed_item) ? completed_item : null; - } - get isCommandLine() { - var _a2; - return (_a2 = this.document) == null ? void 0 : _a2.uri.endsWith("%5BCommand%20Line%5D"); - } - get isActivated() { - return this.activated; - } - get document() { - if (!this.option) - return null; - return workspace_default.getDocument(this.option.bufnr); - } - getCompleteConfig() { - let suggest = workspace_default.getConfiguration("suggest"); - function getConfig(key, defaultValue) { - return suggest.get(key, defaultValue); - } - let keepCompleteopt = getConfig("keepCompleteopt", false); - let autoTrigger = getConfig("autoTrigger", "always"); - if (keepCompleteopt && autoTrigger != "none") { - let { completeOpt } = workspace_default; - if (!completeOpt.includes("noinsert") && !completeOpt.includes("noselect")) { - autoTrigger = "none"; - } - } - let floatEnable = workspace_default.floatSupported && getConfig("floatEnable", true); - let acceptSuggestionOnCommitCharacter = workspace_default.env.pumevent && getConfig("acceptSuggestionOnCommitCharacter", false); - return { - autoTrigger, - floatEnable, - keepCompleteopt, - floatConfig: getConfig("floatConfig", {}), - defaultSortMethod: getConfig("defaultSortMethod", "length"), - removeDuplicateItems: getConfig("removeDuplicateItems", false), - disableMenuShortcut: getConfig("disableMenuShortcut", false), - acceptSuggestionOnCommitCharacter, - disableKind: getConfig("disableKind", false), - disableMenu: getConfig("disableMenu", false), - previewIsKeyword: getConfig("previewIsKeyword", "@,48-57,_192-255"), - enablePreview: getConfig("enablePreview", false), - enablePreselect: getConfig("enablePreselect", false), - triggerCompletionWait: getConfig("triggerCompletionWait", 100), - labelMaxLength: getConfig("labelMaxLength", 200), - triggerAfterInsertEnter: getConfig("triggerAfterInsertEnter", false), - noselect: getConfig("noselect", true), - numberSelect: getConfig("numberSelect", false), - maxItemCount: getConfig("maxCompleteItemCount", 50), - timeout: getConfig("timeout", 500), - minTriggerInputLength: getConfig("minTriggerInputLength", 1), - snippetIndicator: getConfig("snippetIndicator", "~"), - fixInsertedWord: getConfig("fixInsertedWord", true), - localityBonus: getConfig("localityBonus", true), - highPrioritySourceLimit: getConfig("highPrioritySourceLimit", null), - lowPrioritySourceLimit: getConfig("lowPrioritySourceLimit", null), - asciiCharactersOnly: getConfig("asciiCharactersOnly", false) - }; - } - async startCompletion(option) { - this.pretext = byteSlice(option.line, 0, option.colnr - 1); - try { - await this._doComplete(option); - } catch (e) { - this.stop(); - logger81.error("Complete error:", e.stack); - } - } - async resumeCompletion(force = false) { - let { document: document2, complete } = this; - if (!document2 || complete.isCanceled || !complete.results || complete.results.length == 0) - return; - let search = this.getResumeInput(); - if (search == this.input && !force) - return; - if (!search || search.endsWith(" ") || !search.startsWith(complete.input)) { - this.stop(); - return; - } - this.input = search; - let items = []; - if (complete.isIncomplete) { - await document2.patchChange(true); - let { changedtick } = document2; - items = await complete.completeInComplete(search); - if (complete.isCanceled || document2.changedtick != changedtick) - return; - } else { - items = complete.filterResults(search); - } - if (!complete.isCompleting && items.length === 0) { - this.stop(); - return; - } - await this.showCompletion(complete.option.col, items); - } - hasSelected() { - if (workspace_default.env.pumevent) - return this.selectedItem != null; - if (!this.config.noselect) - return true; - return false; - } - async showCompletion(col, items) { - let { nvim, document: document2, option } = this; - let { numberSelect, disableKind, labelMaxLength, disableMenuShortcut, disableMenu } = this.config; - let preselect = this.config.enablePreselect ? items.findIndex((o) => o.preselect) : -1; - if (numberSelect && option.input.length && !/^\d/.test(option.input)) { - items = items.map((item, i) => { - let idx = i + 1; - if (i < 9) { - return Object.assign({}, item, { - abbr: item.abbr ? `${idx} ${item.abbr}` : `${idx} ${item.word}` - }); - } - return item; - }); - nvim.call("coc#_map", [], true); - } - this.changedTick = document2.changedtick; - let validKeys2 = completeItemKeys.slice(); - if (disableKind) - validKeys2 = validKeys2.filter((s) => s != "kind"); - if (disableMenu) - validKeys2 = validKeys2.filter((s) => s != "menu"); - let vimItems = items.map((item) => { - let obj = { word: item.word, equal: 1 }; - for (let key of validKeys2) { - if (item.hasOwnProperty(key)) { - if (disableMenuShortcut && key == "menu") { - obj[key] = item[key].replace(/\[.+\]$/, ""); - } else if (key == "abbr" && item[key].length > labelMaxLength) { - obj[key] = item[key].slice(0, labelMaxLength); - } else { - obj[key] = item[key]; - } - } - } - return obj; - }); - nvim.call("coc#_do_complete", [col, vimItems, preselect], true); - } - async _doComplete(option) { - let { source } = option; - let { nvim, config } = this; - let doc = workspace_default.getDocument(option.bufnr); - if (!doc || !doc.attached) - return; - option.filetype = doc.filetype; - this.input = option.input; - let arr = []; - if (source == null) { - arr = sources_default.getCompleteSources(option); - } else { - let s = sources_default.getSource(source); - if (s) - arr.push(s); - } - if (!arr.length) - return; - await doc.patchChange(); - if (doc.changedtick != option.changedtick) - return; - let complete = new Complete(option, doc, config, arr, nvim); - this.start(complete); - let items = await this.complete.doComplete(); - if (complete.isCanceled) - return; - if (items.length == 0 && !complete.isCompleting) { - this.stop(); - return; - } - complete.onDidComplete(async () => { - if (this.selectedItem != null) - return; - let search = this.getResumeInput(); - if (complete.isCanceled || search == null) - return; - let { input } = this.option; - if (search == input) { - let items2 = complete.filterResults(search, Math.floor(Date.now() / 1e3)); - await this.showCompletion(option.col, items2); - } else { - await this.resumeCompletion(); - } - }); - if (items.length) { - let search = this.getResumeInput(); - if (search == option.input) { - await this.showCompletion(option.col, items); - } else { - await this.resumeCompletion(true); - } - } - } - async onTextChangedP(bufnr, info) { - let { option, document: document2 } = this; - let pretext = this.pretext = info.pre; - if (!option || option.bufnr != bufnr || info.changedtick == this.changedTick) - return; - let hasInsert = this.latestInsert != null; - this.lastInsert = null; - if (info.pre.match(/^\s*/)[0] !== option.line.match(/^\s*/)[0]) { - logger81.warn("Complete stopped by indent change."); - this.stop(false); - return; - } - if (!hasInsert || !pretext) - return; - if (sources_default.shouldTrigger(pretext, document2.filetype, document2.uri)) { - await this.triggerCompletion(document2, pretext); - } else { - await this.resumeCompletion(); - } - } - async onTextChangedI(bufnr, info) { - let { nvim, latestInsertChar, option } = this; - let noChange = this.pretext == info.pre; - let pretext = this.pretext = info.pre; - this.lastInsert = null; - let doc = workspace_default.getDocument(bufnr); - if (!doc) - return; - if (!this.activated) { - if (!latestInsertChar) - return; - let triggerSources = sources_default.getTriggerSources(pretext, doc.filetype, doc.uri); - if (triggerSources.length) { - await this.triggerCompletion(doc, this.pretext); - return; - } - this.triggerTimer = setTimeout(async () => { - await this.triggerCompletion(doc, pretext); - }, this.config.triggerCompletionWait); - return; - } - if (!option || bufnr != option.bufnr) - return; - if (option.linenr != info.lnum || option.col >= info.col - 1) { - this.stop(); - return; - } - if (noChange && !latestInsertChar) { - this.stop(false); - return; - } - if (pretext && this.selectedItem && this.config.acceptSuggestionOnCommitCharacter && latestInsertChar) { - let resolvedItem = this.getCompleteItem(this.selectedItem); - let last = pretext[pretext.length - 1]; - if (sources_default.shouldCommit(resolvedItem, last)) { - let { linenr, col, line, colnr } = this.option; - this.stop(); - let { word } = resolvedItem; - let newLine = `${line.slice(0, col)}${word}${latestInsertChar}${line.slice(colnr - 1)}`; - await nvim.call("coc#util#setline", [linenr, newLine]); - let curcol = col + word.length + 2; - await nvim.call("cursor", [linenr, curcol]); - await doc.patchChange(); - return; - } - } - if (sources_default.shouldTrigger(pretext, doc.filetype, doc.uri)) { - await this.triggerCompletion(doc, pretext); - } else { - await this.resumeCompletion(); - } - } - async triggerCompletion(doc, pre) { - if (!doc || !doc.attached) { - logger81.warn("Document not attached, suggest disabled."); - return; - } - let shouldTrigger = this.shouldTrigger(doc, pre); - if (!shouldTrigger) - return; - if (doc.getVar("suggest_disable")) { - logger81.warn(`Suggest disabled by b:coc_suggest_disable`); - return; - } - await doc.patchChange(); - let [disabled, option] = await this.nvim.eval('[get(b:,"coc_suggest_disable",0),coc#util#get_complete_option()]'); - if (disabled == 1) { - logger81.warn(`Suggest disabled by b:coc_suggest_disable`); - return; - } - if (option.blacklist && option.blacklist.includes(option.input)) { - logger81.warn(`Suggest disabled by b:coc_suggest_blacklist`, option.blacklist); - return; - } - if (pre.length) { - option.triggerCharacter = pre.slice(-1); - } - logger81.debug("trigger completion with", option); - await this.startCompletion(option); - } - async onCompleteDone(item) { - let { document: document2, isActivated } = this; - if (!isActivated || !document2 || !vimCompleteItem(item)) - return; - let opt = Object.assign({}, this.option); - let resolvedItem = this.getCompleteItem(item); - this.stop(); - if (!resolvedItem) - return; - let timestamp = this.insertCharTs; - let insertLeaveTs = this.insertLeaveTs; - let source = new import_vscode_languageserver_protocol79.CancellationTokenSource(); - await this.doCompleteResolve(resolvedItem, source.token); - source.dispose(); - await wait(50); - if (this.insertCharTs != timestamp || this.insertLeaveTs != insertLeaveTs) - return; - let [visible, lnum, pre] = await this.nvim.eval(`[pumvisible(),line('.'),strpart(getline('.'), 0, col('.') - 1)]`); - if (visible || lnum != opt.linenr || this.activated || !pre.endsWith(resolvedItem.word)) - return; - await document2.patchChange(true); - await this.doCompleteDone(resolvedItem, opt); - } - async doCompleteResolve(item, token) { - let source = sources_default.getSource(item.source); - if (source && typeof source.onCompleteResolve == "function") { - try { - await Promise.resolve(source.onCompleteResolve(item, token)); - } catch (e) { - logger81.error("Error on complete resolve:", e.stack); - } - } - } - async doCompleteDone(item, opt) { - let data = JSON.parse(item.user_data); - let source = sources_default.getSource(data.source); - if (source && typeof source.onCompleteDone === "function") { - await Promise.resolve(source.onCompleteDone(item, opt)); - } - } - async onInsertLeave() { - this.insertLeaveTs = Date.now(); - this.stop(false); - } - async onInsertEnter(bufnr) { - if (!this.config.triggerAfterInsertEnter || this.config.autoTrigger !== "always") - return; - let doc = workspace_default.getDocument(bufnr); - if (!doc) - return; - let pre = await this.nvim.eval(`strpart(getline('.'), 0, col('.') - 1)`); - if (!pre) - return; - await this.triggerCompletion(doc, pre); - } - async onInsertCharPre(character) { - this.lastInsert = { - character, - timestamp: Date.now() - }; - this.insertCharTs = this.lastInsert.timestamp; - } - get latestInsert() { - let { lastInsert } = this; - if (!lastInsert || Date.now() - lastInsert.timestamp > 500) { - return null; - } - return lastInsert; - } - get latestInsertChar() { - let { latestInsert } = this; - if (!latestInsert) - return ""; - return latestInsert.character; - } - shouldTrigger(doc, pre) { - let autoTrigger = this.config.autoTrigger; - if (autoTrigger == "none") - return false; - if (sources_default.shouldTrigger(pre, doc.filetype, doc.uri)) - return true; - if (autoTrigger !== "always" || this.isActivated) - return false; - let last = pre.slice(-1); - if (last && (doc.isWord(pre.slice(-1)) || last.codePointAt(0) > 255)) { - let minLength = this.config.minTriggerInputLength; - if (minLength == 1) - return true; - let input = this.getInput(doc, pre); - return input.length >= minLength; - } - return false; - } - async onPumChange() { - if (!this.popupEvent) - return; - let { col, row, height, width, scrollbar } = this.popupEvent; - let bounding = { col, row, height, width, scrollbar }; - let resolvedItem = this.getCompleteItem(this.selectedItem); - if (!resolvedItem) { - this.floating.close(); - return; - } - let source = this.resolveTokenSource = new import_vscode_languageserver_protocol79.CancellationTokenSource(); - let { token } = source; - await this.doCompleteResolve(resolvedItem, token); - if (this.resolveTokenSource == source) { - this.resolveTokenSource = null; - } - source.dispose(); - if (token.isCancellationRequested) - return; - let docs = resolvedItem.documentation; - if (!docs && resolvedItem.info) { - let { info } = resolvedItem; - let isText = /^[\w-\s.,\t]+$/.test(info); - docs = [{ filetype: isText ? "txt" : this.document.filetype, content: info }]; - } - if (!docs || docs.length == 0) { - this.floating.close(); - } else { - if (this.config.floatEnable) { - let source2 = new import_vscode_languageserver_protocol79.CancellationTokenSource(); - await this.floating.show(docs, bounding, Object.assign({}, this.config.floatConfig, { - excludeImages: this.excludeImages - }), source2.token); - } - if (!this.isActivated) { - this.floating.close(); - } - } - } - start(complete) { - let { activated } = this; - this.activated = true; - if (activated) { - this.complete.dispose(); - } - this.complete = complete; - if (!this.config.keepCompleteopt) { - this.nvim.command(`noa set completeopt=${this.completeOpt}`, true); - } - } - cancelResolve() { - if (this.resolveTokenSource) { - this.resolveTokenSource.cancel(); - this.resolveTokenSource = null; - } - } - stop(hide = true) { - let { nvim } = this; - if (!this.activated) - return; - this.cancelResolve(); - this.floating.close(); - this.activated = false; - if (this.complete) { - this.complete.dispose(); - this.complete = null; - } - nvim.pauseNotification(); - if (hide) { - nvim.call("coc#_hide", [], true); - } - if (this.config.numberSelect) { - nvim.call("coc#_unmap", [], true); - } - if (!this.config.keepCompleteopt) { - nvim.command(`noa set completeopt=${workspace_default.completeOpt}`, true); - } - nvim.command(`let g:coc#_context = {'start': 0, 'preselect': -1,'candidates': []}`, true); - nvim.resumeNotification(false, true); - } - getInput(document2, pre) { - let input = ""; - for (let i = pre.length - 1; i >= 0; i--) { - let ch = i == 0 ? null : pre[i - 1]; - if (!ch || !document2.isWord(ch)) { - input = pre.slice(i, pre.length); - break; - } - } - return input; - } - getResumeInput() { - let { option, pretext } = this; - if (!option) - return null; - let buf = Buffer.from(pretext, "utf8"); - if (buf.length < option.col) - return null; - let input = buf.slice(option.col).toString("utf8"); - if (option.blacklist && option.blacklist.includes(input)) - return null; - return input; - } - get completeOpt() { - let { noselect, enablePreview } = this.config; - let preview = enablePreview && !workspace_default.env.pumevent ? ",preview" : ""; - if (noselect) - return `noselect,menuone${preview}`; - return `noinsert,menuone${preview}`; - } - getCompleteItem(item) { - if (!this.complete || !vimCompleteItem(item)) - return null; - return this.complete.resolveCompletionItem(item); - } - dispose() { - this.resolveTokenSource = null; - disposeAll(this.disposables); - } - }; - completion_default = new Completion(); - } -}); - -// src/snippets/snippet.ts -var import_vscode_languageserver_protocol80, logger82, CocSnippet; -var init_snippet = __esm({ - "src/snippets/snippet.ts"() { - import_vscode_languageserver_protocol80 = __toModule(require_main2()); - init_main2(); - init_position(); - init_parser2(); - init_string(); - logger82 = require_logger2()("snippets-snipet"); - CocSnippet = class { - constructor(_snippetString, position, _variableResolver) { - this._snippetString = _snippetString; - this.position = position; - this._variableResolver = _variableResolver; - this._parser = new SnippetParser(); - } - async init() { - const snippet = this._parser.parse(this._snippetString, true); - let { _variableResolver } = this; - if (_variableResolver) { - await snippet.resolveVariables(_variableResolver); - } - this.tmSnippet = snippet; - this.update(); - } - adjustPosition(characterCount, lineCount) { - let { line, character } = this.position; - this.position = { - line: line + lineCount, - character: character + characterCount - }; - this.update(); - } - adjustTextEdit(edit2, changedLine) { - let { range, newText } = edit2; - if (comparePosition(this.range.start, range.end) < 0) { - let { start, end } = range; - let overlaped = end.character - this.range.start.character; - if (changedLine && comparePosition(this.range.start, start) > 0 && isSingleLine(range) && start.character - overlaped >= 0 && changedLine.slice(start.character - overlaped, start.character) == changedLine.slice(this.range.start.character, this.range.start.character + overlaped)) { - edit2.range = range = import_vscode_languageserver_protocol80.Range.create(start.line, start.character - overlaped, end.line, end.character - overlaped); - } else { - return false; - } - } - if (!newText.includes("\n") && comparePosition(range.start, range.end) == 0 && comparePosition(this.range.start, range.start) == 0) { - let idx = this._placeholders.findIndex((o) => comparePosition(o.range.start, range.start) == 0); - if (idx !== -1) - return false; - } - let changed = getChangedPosition(this.range.start, edit2); - if (changed.line == 0 && changed.character == 0) - return true; - this.adjustPosition(changed.character, changed.line); - return true; - } - get isPlainText() { - if (this._placeholders.length > 1) - return false; - return this._placeholders.every((o) => o.value == ""); - } - get finalCount() { - return this._placeholders.filter((o) => o.isFinalTabstop).length; - } - toString() { - return this.tmSnippet.toString(); - } - get range() { - let { position } = this; - const content = this.tmSnippet.toString(); - const doc = TextDocument2.create("untitled:/1", "snippet", 0, content); - const pos = doc.positionAt(content.length); - const end = pos.line == 0 ? position.character + pos.character : pos.character; - return import_vscode_languageserver_protocol80.Range.create(position, import_vscode_languageserver_protocol80.Position.create(position.line + pos.line, end)); - } - get firstPlaceholder() { - let index = 0; - for (let p of this._placeholders) { - if (p.index == 0) - continue; - if (index == 0 || p.index < index) { - index = p.index; - } - } - return this.getPlaceholder(index); - } - get lastPlaceholder() { - let index = 0; - for (let p of this._placeholders) { - if (index == 0 || p.index > index) { - index = p.index; - } - } - return this.getPlaceholder(index); - } - getPlaceholderById(id) { - return this._placeholders.find((o) => o.id == id); - } - getPlaceholder(index) { - let placeholders = this._placeholders.filter((o) => o.index == index); - let filtered = placeholders.filter((o) => !o.transform); - return filtered.length ? filtered[0] : placeholders[0]; - } - getPrevPlaceholder(index) { - if (index == 0) - return this.lastPlaceholder; - let prev = this.getPlaceholder(index - 1); - if (!prev) - return this.getPrevPlaceholder(index - 1); - return prev; - } - getNextPlaceholder(index) { - let indexes = this._placeholders.map((o) => o.index); - let max = Math.max.apply(null, indexes); - if (index >= max) - return this.finalPlaceholder; - let next = this.getPlaceholder(index + 1); - if (!next) - return this.getNextPlaceholder(index + 1); - return next; - } - get finalPlaceholder() { - return this._placeholders.find((o) => o.isFinalTabstop); - } - getPlaceholderByRange(range) { - return this._placeholders.find((o) => rangeInRange(range, o.range)); - } - insertSnippet(placeholder, snippet, range) { - let { start } = placeholder.range; - let editStart = import_vscode_languageserver_protocol80.Position.create(range.start.line - start.line, range.start.line == start.line ? range.start.character - start.character : range.start.character); - let editEnd = import_vscode_languageserver_protocol80.Position.create(range.end.line - start.line, range.end.line == start.line ? range.end.character - start.character : range.end.character); - let editRange2 = import_vscode_languageserver_protocol80.Range.create(editStart, editEnd); - let first = this.tmSnippet.insertSnippet(snippet, placeholder.id, editRange2); - this.update(); - return first; - } - updatePlaceholder(placeholder, edit2) { - let { range } = this; - let { value, id, index } = placeholder; - let newText = editRange(placeholder.range, value, edit2); - let delta = 0; - if (!newText.includes("\n")) { - for (let p of this._placeholders) { - if (p.index == index && p.id < id && p.line == placeholder.range.start.line) { - let text = this.tmSnippet.getPlaceholderText(p.id, newText); - delta = delta + byteLength(text) - byteLength(p.value); - } - } - } - if (placeholder.isVariable) { - this.tmSnippet.updateVariable(id, newText); - } else { - this.tmSnippet.updatePlaceholder(id, newText); - } - let endPosition = adjustPosition(range.end, edit2); - let snippetEdit = { - range: import_vscode_languageserver_protocol80.Range.create(range.start, endPosition), - newText: this.tmSnippet.toString() - }; - this.update(); - return { edits: [snippetEdit], delta }; - } - update() { - const snippet = this.tmSnippet; - const { line, character } = this.position; - const document2 = TextDocument2.create("untitled:/1", "snippet", 0, snippet.toString()); - const { placeholders, variables, maxIndexNumber } = snippet; - const variableIndexMap = new Map(); - let variableIndex = maxIndexNumber + 1; - this._placeholders = [...placeholders, ...variables].map((p, idx) => { - const offset = snippet.offset(p); - const position = document2.positionAt(offset); - const start = { - line: line + position.line, - character: position.line == 0 ? character + position.character : position.character - }; - let index; - if (p instanceof Variable) { - let key = p.name; - if (variableIndexMap.has(key)) { - index = variableIndexMap.get(key); - } else { - variableIndexMap.set(key, variableIndex); - index = variableIndex; - variableIndex = variableIndex + 1; - } - } else { - index = p.index; - } - const value = p.toString(); - const lines = value.split(/\r?\n/); - let res = { - range: import_vscode_languageserver_protocol80.Range.create(start, { - line: start.line + lines.length - 1, - character: lines.length == 1 ? start.character + value.length : lines[lines.length - 1].length - }), - transform: p.transform != null, - line: start.line, - id: idx, - index, - value, - isVariable: p instanceof Variable, - isFinalTabstop: p.index === 0 - }; - Object.defineProperty(res, "snippet", { - enumerable: false - }); - if (p instanceof Placeholder && p.choice) { - let { options } = p.choice; - if (options && options.length) { - res.choice = options.map((o) => o.value); - } - } - return res; - }); - } - }; - } -}); - -// src/snippets/variableResolve.ts -var import_path33, logger83, SnippetVariableResolver; -var init_variableResolve = __esm({ - "src/snippets/variableResolve.ts"() { - import_path33 = __toModule(require("path")); - init_window(); - logger83 = require_logger2()("snippets-variable"); - SnippetVariableResolver = class { - constructor() { - this._variableToValue = {}; - const currentDate = new Date(); - Object.assign(this._variableToValue, { - CURRENT_YEAR: currentDate.getFullYear().toString(), - CURRENT_YEAR_SHORT: currentDate.getFullYear().toString().slice(-2), - CURRENT_MONTH: (currentDate.getMonth() + 1).toString(), - CURRENT_DATE: currentDate.getDate().toString(), - CURRENT_HOUR: currentDate.getHours().toString(), - CURRENT_MINUTE: currentDate.getMinutes().toString(), - CURRENT_SECOND: currentDate.getSeconds().toString(), - CURRENT_DAY_NAME: currentDate.toLocaleString("en-US", { weekday: "long" }), - CURRENT_DAY_NAME_SHORT: currentDate.toLocaleString("en-US", { weekday: "short" }), - CURRENT_MONTH_NAME: currentDate.toLocaleString("en-US", { month: "long" }), - CURRENT_MONTH_NAME_SHORT: currentDate.toLocaleString("en-US", { month: "short" }), - TM_FILENAME: null, - TM_FILENAME_BASE: null, - TM_DIRECTORY: null, - TM_FILEPATH: null, - YANK: null, - TM_LINE_INDEX: null, - TM_LINE_NUMBER: null, - TM_CURRENT_LINE: null, - TM_CURRENT_WORD: null, - TM_SELECTED_TEXT: null, - CLIPBOARD: null - }); - } - async resolveValue(name2) { - let { nvim } = window_default; - if (["TM_FILENAME", "TM_FILENAME_BASE", "TM_DIRECTORY", "TM_FILEPATH"].includes(name2)) { - let filepath = await nvim.eval('expand("%:p")'); - if (name2 == "TM_FILENAME") - return import_path33.default.basename(filepath); - if (name2 == "TM_FILENAME_BASE") - return import_path33.default.basename(filepath, import_path33.default.extname(filepath)); - if (name2 == "TM_DIRECTORY") - return import_path33.default.dirname(filepath); - if (name2 == "TM_FILEPATH") - return filepath; - } - if (name2 == "YANK") { - let yank = await nvim.call("getreg", ['""']); - return yank; - } - if (name2 == "TM_LINE_INDEX") { - let lnum = await nvim.call("line", ["."]); - return (lnum - 1).toString(); - } - if (name2 == "TM_LINE_NUMBER") { - let lnum = await nvim.call("line", ["."]); - return lnum.toString(); - } - if (name2 == "TM_CURRENT_LINE") { - let line = await nvim.call("getline", ["."]); - return line; - } - if (name2 == "TM_CURRENT_WORD") { - let word = await nvim.eval(`expand('')`); - return word; - } - if (name2 == "TM_SELECTED_TEXT") { - let text = await nvim.eval(`get(g:,'coc_selected_text', '')`); - return text; - } - if (name2 == "CLIPBOARD") { - return await nvim.eval("@*"); - } - } - async resolve(variable) { - const name2 = variable.name; - let resolved = this._variableToValue[name2]; - if (resolved != null) - return resolved.toString(); - let value = await this.resolveValue(name2); - if (value) - return value; - if (variable.children && variable.children.length) { - return variable.toString(); - } - if (!this._variableToValue.hasOwnProperty(name2)) { - return name2; - } - return ""; - } - }; - } -}); - -// src/util/textedit.ts -function singleLineEdit(edit2) { - let { range, newText } = edit2; - return range.start.line == range.end.line && newText.indexOf("\n") == -1; -} -var init_textedit = __esm({ - "src/util/textedit.ts"() { - } -}); - -// src/snippets/session.ts -function normalizeSnippetString(snippet, indent, opts) { - let lines = snippet.split(/\r?\n/); - let ind = opts.insertSpaces ? " ".repeat(opts.tabSize) : " "; - let tabSize = opts.tabSize || 2; - lines = lines.map((line, idx) => { - let space = line.match(/^\s*/)[0]; - let pre = space; - let isTab = space.startsWith(" "); - if (isTab && opts.insertSpaces) { - pre = ind.repeat(space.length); - } else if (!isTab && !opts.insertSpaces) { - pre = ind.repeat(space.length / tabSize); - } - return (idx == 0 || line.length == 0 ? "" : indent) + pre + line.slice(space.length); - }); - return lines.join("\n"); -} -var import_vscode_languageserver_protocol81, logger84, SnippetSession; -var init_session2 = __esm({ - "src/snippets/session.ts"() { - import_vscode_languageserver_protocol81 = __toModule(require_main2()); - init_completion(); - init_position(); - init_string(); - init_workspace(); - init_window(); - init_events(); - init_snippet(); - init_variableResolve(); - init_textedit(); - logger84 = require_logger2()("snippets-session"); - SnippetSession = class { - constructor(nvim, bufnr) { - this.nvim = nvim; - this.bufnr = bufnr; - this._isActive = false; - this._currId = 0; - this.applying = false; - this.preferComplete = false; - this._snippet = null; - this._onCancelEvent = new import_vscode_languageserver_protocol81.Emitter(); - this.onCancel = this._onCancelEvent.event; - let suggest = workspace_default.getConfiguration("suggest"); - this.preferComplete = suggest.get("preferCompleteThanJumpPlaceholder", false); - } - async start(snippetString, select = true, range, insertTextMode) { - const { document: document2 } = this; - if (!document2 || !document2.attached) - return false; - void events_default.fire("InsertSnippet", []); - if (!range) { - let position2 = await window_default.getCursorPosition(); - range = import_vscode_languageserver_protocol81.Range.create(position2, position2); - } - let position = range.start; - const formatOptions = await workspace_default.getFormatOptions(this.document.uri); - await document2.patchChange(true); - const currentLine = document2.getline(position.line); - const currentIndent = currentLine.match(/^\s*/)[0]; - let inserted = ""; - if (insertTextMode === import_vscode_languageserver_protocol81.InsertTextMode.asIs) { - inserted = snippetString; - } else { - inserted = normalizeSnippetString(snippetString, currentIndent, formatOptions); - } - const resolver = new SnippetVariableResolver(); - const snippet = new CocSnippet(inserted, position, resolver); - await snippet.init(); - const edit2 = import_vscode_languageserver_protocol81.TextEdit.replace(range, snippet.toString()); - if (snippetString.endsWith("\n") && currentLine.slice(position.character).length) { - edit2.newText = edit2.newText + currentIndent; - inserted = inserted + currentIndent; - } - this.applying = true; - await document2.applyEdits([edit2]); - this.applying = false; - if (this._isActive) { - let placeholder = this.findPlaceholder(range); - if (placeholder && !placeholder.isFinalTabstop) { - let index = this.snippet.insertSnippet(placeholder, inserted, range); - let p = this.snippet.getPlaceholder(index); - this._currId = p.id; - if (select) - await this.selectPlaceholder(p); - return true; - } - } - if (snippet.isPlainText) { - this.deactivate(); - let placeholder = snippet.finalPlaceholder; - await window_default.moveTo(placeholder.range.start); - return false; - } - this._snippet = snippet; - this._currId = snippet.firstPlaceholder.id; - if (select) - await this.selectPlaceholder(snippet.firstPlaceholder); - this.activate(); - return true; - } - activate() { - if (this._isActive) - return; - this._isActive = true; - this.nvim.call("coc#snippet#enable", [], true); - } - deactivate() { - if (this._isActive) { - this._isActive = false; - this._snippet = null; - this.nvim.call("coc#snippet#disable", [], true); - logger84.debug("[SnippetManager::cancel]"); - } - this._onCancelEvent.fire(void 0); - this._onCancelEvent.dispose(); - } - get isActive() { - return this._isActive; - } - async nextPlaceholder() { - if (!this.isActive) - return; - await this.document.patchChange(); - let curr = this.placeholder; - let next = this.snippet.getNextPlaceholder(curr.index); - await this.selectPlaceholder(next); - } - async previousPlaceholder() { - if (!this.isActive) - return; - await this.document.patchChange(); - let curr = this.placeholder; - let prev = this.snippet.getPrevPlaceholder(curr.index); - await this.selectPlaceholder(prev); - } - async synchronizeUpdatedPlaceholders(change, changedLine) { - if (!this.isActive || !this.document || this.applying) - return; - let edit2 = { range: change.range, newText: change.text }; - let { snippet } = this; - let adjusted = snippet.adjustTextEdit(edit2, changedLine); - if (adjusted) - return; - let currRange = this.placeholder.range; - if (changedLine != null && singleLineEdit(edit2) && !rangeInRange(edit2.range, currRange) && isSingleLine(currRange) && changedLine.slice(currRange.start.character, currRange.end.character) == this.placeholder.value && events_default.cursor && events_default.cursor.bufnr == this.bufnr && events_default.cursor.lnum == edit2.range.start.line + 1) { - let col = events_default.cursor.col; - let preText = changedLine.slice(0, currRange.start.character); - let postText = changedLine.slice(currRange.end.character); - let newLine = this.document.getline(edit2.range.start.line); - if (newLine.startsWith(preText) && newLine.endsWith(postText)) { - let endCharacter = newLine.length - postText.length; - let cursorIdx = characterIndex(newLine, col - 1); - if (cursorIdx >= preText.length && cursorIdx <= endCharacter) { - let newText = newLine.slice(preText.length, endCharacter); - edit2 = import_vscode_languageserver_protocol81.TextEdit.replace(currRange, newText); - } - } - } - if (comparePosition(edit2.range.start, snippet.range.end) > 0) { - if (!edit2.newText) - return; - logger84.info("Content change after snippet, cancelling snippet session"); - this.deactivate(); - return; - } - let placeholder = this.findPlaceholder(edit2.range); - if (!placeholder) { - logger84.info("Change outside placeholder, cancelling snippet session"); - this.deactivate(); - return; - } - if (placeholder.isFinalTabstop && snippet.finalCount <= 1) { - logger84.info("Change final placeholder, cancelling snippet session"); - this.deactivate(); - return; - } - this._currId = placeholder.id; - let { edits, delta } = snippet.updatePlaceholder(placeholder, edit2); - if (!edits.length) - return; - this.applying = true; - await this.document.applyEdits(edits); - this.applying = false; - if (delta) { - await this.nvim.call("coc#cursor#move_by_col", delta); - } - } - async selectCurrentPlaceholder(triggerAutocmd = true) { - let placeholder = this.snippet.getPlaceholderById(this._currId); - if (placeholder) - await this.selectPlaceholder(placeholder, triggerAutocmd); - } - async selectPlaceholder(placeholder, triggerAutocmd = true) { - let { nvim, document: document2 } = this; - if (!document2 || !placeholder) - return; - let { start, end } = placeholder.range; - const len = end.character - start.character; - const col = byteLength(document2.getline(start.line).slice(0, start.character)) + 1; - this._currId = placeholder.id; - if (placeholder.choice) { - await nvim.call("coc#snippet#show_choices", [start.line + 1, col, len, placeholder.choice]); - if (triggerAutocmd) - nvim.call("coc#util#do_autocmd", ["CocJumpPlaceholder"], true); - } else { - await this.select(placeholder, triggerAutocmd); - } - } - async select(placeholder, triggerAutocmd = true) { - let { range, value, isFinalTabstop } = placeholder; - let { document: document2, nvim } = this; - let { start, end } = range; - let { textDocument } = document2; - let len = textDocument.offsetAt(end) - textDocument.offsetAt(start); - let line = document2.getline(start.line); - let col = line ? byteLength(line.slice(0, start.character)) : 0; - let endLine = document2.getline(end.line); - let endCol = endLine ? byteLength(endLine.slice(0, end.character)) : 0; - nvim.setVar("coc_last_placeholder", { - bufnr: document2.bufnr, - current_text: value, - start: { line: start.line, col, character: start.character }, - end: { line: end.line, col: endCol, character: end.character } - }, true); - let [ve, selection, pumvisible, mode] = await nvim.eval("[&virtualedit, &selection, pumvisible(), mode()]"); - let move_cmd = ""; - if (pumvisible && this.preferComplete) { - let pre = completion_default.hasSelected() ? "" : "\\"; - await nvim.eval(`feedkeys("${pre}\\", 'in')`); - return; - } - if (mode != "n") - move_cmd += "\\"; - if (len == 0) { - if (col == 0 || !mode.startsWith("i") && col < byteLength(line)) { - move_cmd += "i"; - } else { - move_cmd += "a"; - } - } else { - move_cmd += "v"; - endCol = await this.getVirtualCol(end.line + 1, endCol); - if (selection == "inclusive") { - if (end.character == 0) { - move_cmd += `${end.line}G`; - } else { - move_cmd += `${end.line + 1}G${endCol}|`; - } - } else if (selection == "old") { - move_cmd += `${end.line + 1}G${endCol}|`; - } else { - move_cmd += `${end.line + 1}G${endCol + 1}|`; - } - col = await this.getVirtualCol(start.line + 1, col); - move_cmd += `o${start.line + 1}G${col + 1}|o\\`; - } - if (mode == "i" && move_cmd == "\\a") { - move_cmd = ""; - } - nvim.pauseNotification(); - nvim.setOption("virtualedit", "onemore", true); - nvim.call("cursor", [start.line + 1, col + (move_cmd == "a" ? 0 : 1)], true); - if (move_cmd) { - nvim.call("eval", [`feedkeys("${move_cmd}", 'in')`], true); - } - if (mode == "i") { - nvim.call("coc#_cancel", [], true); - } - nvim.setOption("virtualedit", ve, true); - if (isFinalTabstop) { - if (this.snippet.finalCount == 1) { - logger84.info("Jump to final placeholder, cancelling snippet session"); - this.deactivate(); - } else { - nvim.call("coc#snippet#disable", [], true); - } - } - if (workspace_default.env.isVim) - nvim.command("redraw", true); - await nvim.resumeNotification(); - if (triggerAutocmd) - nvim.call("coc#util#do_autocmd", ["CocJumpPlaceholder"], true); - } - async getVirtualCol(line, col) { - let { nvim } = this; - return await nvim.eval(`virtcol([${line}, ${col}])`); - } - async checkPosition() { - if (!this.isActive) - return; - let position = await window_default.getCursorPosition(); - if (this.snippet && positionInRange(position, this.snippet.range) != 0) { - logger84.info("Cursor insert out of range, cancelling snippet session"); - this.deactivate(); - } - } - findPlaceholder(range) { - if (!this.snippet) - return null; - let { placeholder } = this; - if (placeholder && rangeInRange(range, placeholder.range)) - return placeholder; - return this.snippet.getPlaceholderByRange(range) || null; - } - get placeholder() { - if (!this.snippet) - return null; - return this.snippet.getPlaceholderById(this._currId); - } - get snippet() { - return this._snippet; - } - get document() { - return workspace_default.getDocument(this.bufnr); - } - }; - } -}); - -// src/snippets/manager.ts -var logger85, SnippetManager, manager_default3; -var init_manager4 = __esm({ - "src/snippets/manager.ts"() { - init_events(); - init_workspace(); - init_window(); - init_parser2(); - init_session2(); - init_variableResolve(); - init_string2(); - logger85 = require_logger2()("snippets-manager"); - SnippetManager = class { - constructor() { - this.sessionMap = new Map(); - this.disposables = []; - workspace_default.onDidChangeTextDocument(async (e) => { - let session = this.getSession(e.bufnr); - if (session) { - let firstLine = e.originalLines[e.contentChanges[0].range.start.line] || ""; - await session.synchronizeUpdatedPlaceholders(e.contentChanges[0], firstLine); - } - }, null, this.disposables); - workspace_default.onDidCloseTextDocument((textDocument) => { - let doc = workspace_default.getDocument(textDocument.uri); - if (!doc) - return; - let session = this.getSession(doc.bufnr); - if (session) - session.deactivate(); - }, null, this.disposables); - events_default.on("BufEnter", async (bufnr) => { - let session = this.getSession(bufnr); - if (!this.statusItem) - return; - if (session && session.isActive) { - this.statusItem.show(); - } else { - this.statusItem.hide(); - } - }, null, this.disposables); - events_default.on("InsertEnter", async () => { - let { session } = this; - if (!session) - return; - await session.checkPosition(); - }, null, this.disposables); - } - init() { - let config = workspace_default.getConfiguration("coc.preferences"); - this.statusItem = window_default.createStatusBarItem(0); - this.statusItem.text = config.get("snippetStatusText", "SNIP"); - } - async insertSnippet(snippet, select = true, range, insertTextMode) { - let { bufnr } = workspace_default; - let session = this.getSession(bufnr); - if (!session) { - session = new SnippetSession(workspace_default.nvim, bufnr); - this.sessionMap.set(bufnr, session); - session.onCancel(() => { - this.sessionMap.delete(bufnr); - if (workspace_default.bufnr == bufnr) { - this.statusItem.hide(); - } - }); - } - let snippetStr = SnippetString.isSnippetString(snippet) ? snippet.value : snippet; - let isActive = await session.start(snippetStr, select, range, insertTextMode); - if (isActive) - this.statusItem.show(); - return isActive; - } - async selectCurrentPlaceholder(triggerAutocmd = true) { - let { session } = this; - if (session) - return await session.selectCurrentPlaceholder(triggerAutocmd); - } - async nextPlaceholder() { - let { session } = this; - if (session) { - await session.nextPlaceholder(); - } else { - workspace_default.nvim.call("coc#snippet#disable", [], true); - this.statusItem.hide(); - } - return ""; - } - async previousPlaceholder() { - let { session } = this; - if (session) { - await session.previousPlaceholder(); - } else { - workspace_default.nvim.call("coc#snippet#disable", [], true); - this.statusItem.hide(); - } - return ""; - } - cancel() { - let session = this.getSession(workspace_default.bufnr); - if (session) - return session.deactivate(); - workspace_default.nvim.call("coc#snippet#disable", [], true); - if (this.statusItem) - this.statusItem.hide(); - } - get session() { - let session = this.getSession(workspace_default.bufnr); - return session && session.isActive ? session : null; - } - isActived(bufnr) { - let session = this.getSession(bufnr); - return session && session.isActive ? true : false; - } - jumpable() { - let { session } = this; - if (!session) - return false; - let placeholder = session.placeholder; - if (placeholder && !placeholder.isFinalTabstop) { - return true; - } - return false; - } - getSession(bufnr) { - return this.sessionMap.get(bufnr); - } - async resolveSnippet(body) { - let parser2 = new SnippetParser(); - const snippet = parser2.parse(body, true); - const resolver = new SnippetVariableResolver(); - await snippet.resolveVariables(resolver); - return snippet; - } - dispose() { - this.cancel(); - for (let d of this.disposables) { - d.dispose(); - } - } - }; - manager_default3 = new SnippetManager(); - } -}); - -// src/commands.ts -var import_vscode_languageserver_protocol82, logger86, CommandItem, CommandManager, commands_default; -var init_commands2 = __esm({ - "src/commands.ts"() { - import_vscode_languageserver_protocol82 = __toModule(require_main2()); - init_esm2(); - init_manager(); - init_manager4(); - init_util(); - init_workspace(); - init_window(); - logger86 = require_logger2()("commands"); - CommandItem = class { - constructor(id, impl, thisArg, internal = false) { - this.id = id; - this.impl = impl; - this.thisArg = thisArg; - this.internal = internal; - } - execute(...args) { - let { impl, thisArg } = this; - return impl.apply(thisArg, args || []); - } - dispose() { - this.thisArg = null; - this.impl = null; - } - }; - CommandManager = class { - constructor() { - this.commands = new Map(); - this.titles = new Map(); - this.onCommandList = []; - } - init(nvim, plugin) { - this.mru = workspace_default.createMru("commands"); - this.register({ - id: "vscode.open", - execute: async (url) => { - nvim.call("coc#util#open_url", url.toString(), true); - } - }, true); - this.register({ - id: "workbench.action.reloadWindow", - execute: async () => { - await nvim.command("edit"); - } - }, true); - this.register({ - id: "editor.action.insertSnippet", - execute: async (edit2) => { - nvim.call("coc#_cancel", [], true); - return await manager_default3.insertSnippet(edit2.newText, true, edit2.range); - } - }, true); - this.register({ - id: "editor.action.doCodeAction", - execute: async (action) => { - await plugin.cocAction("doCodeAction", action); - } - }, true); - this.register({ - id: "editor.action.triggerSuggest", - execute: async () => { - await wait(60); - nvim.call("coc#start", [], true); - } - }, true); - this.register({ - id: "editor.action.triggerParameterHints", - execute: async () => { - await wait(60); - await plugin.cocAction("showSignatureHelp"); - } - }, true); - this.register({ - id: "editor.action.addRanges", - execute: async (ranges) => { - await plugin.cocAction("addRanges", ranges); - } - }, true); - this.register({ - id: "editor.action.restart", - execute: async () => { - await wait(30); - nvim.command("CocRestart", true); - } - }, true); - this.register({ - id: "editor.action.showReferences", - execute: async (_filepath, _position, references) => { - await workspace_default.showLocations(references); - } - }, true); - this.register({ - id: "editor.action.rename", - execute: async (uri, position) => { - await workspace_default.jumpTo(uri, position); - await plugin.cocAction("rename"); - } - }, true); - this.register({ - id: "editor.action.format", - execute: async () => { - await plugin.cocAction("format"); - } - }, true); - this.register({ - id: "workspace.clearWatchman", - execute: async () => { - let res = await window_default.runTerminalCommand("watchman watch-del-all"); - if (res.success) - window_default.showMessage("Cleared watchman watching directories."); - } - }, false, "run watch-del-all for watchman to free up memory."); - this.register({ - id: "workspace.workspaceFolders", - execute: async () => { - let folders = workspace_default.workspaceFolders; - let lines = folders.map((folder) => URI.parse(folder.uri).fsPath); - await window_default.echoLines(lines); - } - }, false, "show opened workspaceFolders."); - this.register({ - id: "workspace.renameCurrentFile", - execute: async () => { - await workspace_default.renameCurrent(); - } - }, false, "change current filename to a new name and reload it."); - this.register({ - id: "extensions.toggleAutoUpdate", - execute: async () => { - let config = workspace_default.getConfiguration("coc.preferences"); - let interval = config.get("extensionUpdateCheck", "daily"); - if (interval == "never") { - config.update("extensionUpdateCheck", "daily", true); - window_default.showMessage("Extension auto update enabled.", "more"); - } else { - config.update("extensionUpdateCheck", "never", true); - window_default.showMessage("Extension auto update disabled.", "more"); - } - } - }, false, "toggle auto update of extensions."); - this.register({ - id: "workspace.diagnosticRelated", - execute: () => manager_default.jumpRelated() - }, false, "jump to related locations of current diagnostic."); - this.register({ - id: "workspace.showOutput", - execute: async (name2) => { - if (name2) { - window_default.showOutputChannel(name2); - } else { - let names = workspace_default.channelNames; - if (names.length == 0) - return; - if (names.length == 1) { - window_default.showOutputChannel(names[0]); - } else { - let idx = await window_default.showQuickpick(names); - if (idx == -1) - return; - let name3 = names[idx]; - window_default.showOutputChannel(name3); - } - } - } - }, false, "open output buffer to show output from languageservers or extensions."); - this.register({ - id: "document.showIncomingCalls", - execute: async () => { - await plugin.cocAction("showIncomingCalls"); - } - }, false, "show incoming calls in tree view."); - this.register({ - id: "document.showOutgoingCalls", - execute: async () => { - await plugin.cocAction("showOutgoingCalls"); - } - }, false, "show outgoing calls in tree view."); - this.register({ - id: "document.echoFiletype", - execute: async () => { - let bufnr = await nvim.call("bufnr", "%"); - let doc = workspace_default.getDocument(bufnr); - if (!doc) - return; - await window_default.echoLines([doc.filetype]); - } - }, false, "echo the mapped filetype of the current buffer"); - this.register({ - id: "document.renameCurrentWord", - execute: async () => { - let bufnr = await nvim.call("bufnr", "%"); - let doc = workspace_default.getDocument(bufnr); - if (!doc) - return; - let edit2 = await plugin.cocAction("getWordEdit"); - if (!edit2) { - window_default.showMessage("Invalid position", "warning"); - return; - } - let ranges = []; - let { changes, documentChanges } = edit2; - if (changes) { - let edits = changes[doc.uri]; - if (edits) - ranges = edits.map((e) => e.range); - } else if (documentChanges) { - for (let c of documentChanges) { - if (import_vscode_languageserver_protocol82.TextDocumentEdit.is(c) && c.textDocument.uri == doc.uri) { - ranges = c.edits.map((e) => e.range); - } - } - } - if (ranges.length) { - await plugin.cocAction("addRanges", ranges); - } - } - }, false, "rename word under cursor in current buffer by use multiple cursors."); - this.register({ - id: "document.jumpToNextSymbol", - execute: async () => { - let doc = await workspace_default.document; - if (!doc) - return; - let ranges = await plugin.cocAction("symbolRanges"); - if (!ranges) - return; - let { textDocument } = doc; - let offset = await window_default.getOffset(); - ranges.sort((a, b) => { - if (a.start.line != b.start.line) { - return a.start.line - b.start.line; - } - return a.start.character - b.start.character; - }); - for (let i = 0; i <= ranges.length - 1; i++) { - if (textDocument.offsetAt(ranges[i].start) > offset) { - await window_default.moveTo(ranges[i].start); - return; - } - } - await window_default.moveTo(ranges[0].start); - } - }, false, "Jump to next symbol highlight position."); - this.register({ - id: "workspace.openLocation", - execute: async (winid, loc, openCommand) => { - if (winid) - await nvim.call("win_gotoid", [winid]); - await workspace_default.jumpTo(loc.uri, loc.range.start, openCommand); - } - }, true); - this.register({ - id: "document.jumpToPrevSymbol", - execute: async () => { - let doc = await workspace_default.document; - if (!doc) - return; - let ranges = await plugin.cocAction("symbolRanges"); - if (!ranges) - return; - let { textDocument } = doc; - let offset = await window_default.getOffset(); - ranges.sort((a, b) => { - if (a.start.line != b.start.line) { - return a.start.line - b.start.line; - } - return a.start.character - b.start.character; - }); - for (let i = ranges.length - 1; i >= 0; i--) { - if (textDocument.offsetAt(ranges[i].end) < offset) { - await window_default.moveTo(ranges[i].start); - return; - } - } - await window_default.moveTo(ranges[ranges.length - 1].start); - } - }, false, "Jump to previous symbol highlight position."); - } - get commandList() { - let res = []; - for (let item of this.commands.values()) { - if (!item.internal) - res.push(item); - } - return res; - } - dispose() { - for (const registration of this.commands.values()) { - registration.dispose(); - } - this.commands.clear(); - } - execute(command) { - let args = [command.command]; - let arr = command.arguments; - if (arr) - args.push(...arr); - return this.executeCommand.apply(this, args); - } - register(command, internal = false, description) { - for (const id of Array.isArray(command.id) ? command.id : [command.id]) { - this.registerCommand(id, command.execute, command, internal); - if (description) - this.titles.set(id, description); - } - return command; - } - has(id) { - return this.commands.has(id); - } - unregister(id) { - let item = this.commands.get(id); - if (!item) - return; - item.dispose(); - this.commands.delete(id); - } - registerCommand(id, impl, thisArg, internal = false) { - if (id.startsWith("_")) - internal = true; - this.commands.set(id, new CommandItem(id, impl, thisArg, internal)); - return import_vscode_languageserver_protocol82.Disposable.create(() => { - this.commands.delete(id); - }); - } - executeCommand(command, ...rest) { - let cmd = this.commands.get(command); - if (!cmd) - throw new Error(`Command: ${command} not found`); - return Promise.resolve(cmd.execute.apply(cmd, rest)); - } - async addRecent(cmd) { - await this.mru.add(cmd); - await workspace_default.nvim.command(`silent! call repeat#set("\\(coc-command-repeat)", -1)`); - } - async repeatCommand() { - let mruList = await this.mru.load(); - let first = mruList[0]; - if (first) { - await this.executeCommand(first); - await workspace_default.nvim.command(`silent! call repeat#set("\\(coc-command-repeat)", -1)`); - } - } - }; - commands_default = new CommandManager(); - } -}); - -// src/cursors/range.ts -var logger87, TextRange; -var init_range = __esm({ - "src/cursors/range.ts"() { - init_main(); - init_position(); - logger87 = require_logger2()("cursors-range"); - TextRange = class { - constructor(line, start, end, text, preCount) { - this.line = line; - this.start = start; - this.end = end; - this.text = text; - this.preCount = preCount; - this.currStart = start; - this.currEnd = end; - } - add(offset, add) { - let { text, preCount } = this; - let pre = offset == 0 ? "" : text.slice(0, offset); - let post = text.slice(offset); - this.text = `${pre}${add}${post}`; - this.currStart = this.currStart + preCount * add.length; - this.currEnd = this.currEnd + (preCount + 1) * add.length; - } - replace(begin, end, add = "") { - let { text, preCount } = this; - let pre = begin == 0 ? "" : text.slice(0, begin); - let post = text.slice(end); - this.text = pre + add + post; - let l = end - begin - add.length; - this.currStart = this.currStart - preCount * l; - this.currEnd = this.currEnd - (preCount + 1) * l; - } - get range() { - return Range.create(this.line, this.start, this.line, this.end); - } - get currRange() { - return Range.create(this.line, this.currStart, this.line, this.currEnd); - } - applyEdit(edit2) { - let { range, newText } = edit2; - let start = range.start.character; - let end = range.end.character; - let isAdd = start == end; - if (isAdd) { - this.add(start - this.currStart, newText); - } else { - this.replace(start - this.currStart, end - this.currStart, newText); - } - } - adjustFromEdit(edit2) { - let { range, newText } = edit2; - if (comparePosition(range.start, Position.create(this.line, this.currEnd)) > 0) { - return; - } - let newLines = newText.split("\n"); - let changeCount = newLines.length - (range.end.line - range.start.line + 1); - this.line = this.line + changeCount; - if (range.end.line == this.line) { - let remove = range.start.line == range.end.line ? range.end.character - range.start.character : range.end.character; - if (newLines.length > 1 && range.start.line == range.end.line) { - remove = remove + range.start.character; - } - let add = 0; - if (newLines.length > 1) { - add = newLines[newLines.length - 1].length; - } else { - if (range.start.line == range.end.line) { - add = newText.length; - } else { - add = range.start.character + newText.length; - } - } - let delta = add - remove; - for (let key of ["start", "end", "currStart", "currEnd"]) { - this[key] += delta; - } - } - } - sync() { - this.start = this.currStart; - this.end = this.currEnd; - } - get textEdit() { - return { - range: this.range, - newText: this.text - }; - } - }; - } -}); - -// src/cursors/util.ts -function splitRange(doc, range) { - let splited = []; - for (let i = range.start.line; i <= range.end.line; i++) { - let curr = doc.getline(i) || ""; - let sc = i == range.start.line ? range.start.character : 0; - let ec = i == range.end.line ? range.end.character : curr.length; - if (sc == ec) - continue; - splited.push(import_vscode_languageserver_protocol83.Range.create(i, sc, i, ec)); - } - return splited; -} -function getVisualRanges(doc, range) { - let { start, end } = range; - if (start.line > end.line) { - [start, end] = [end, start]; - } - let sc = start.character < end.character ? start.character : end.character; - let ec = start.character < end.character ? end.character : start.character; - let ranges = []; - for (let i = start.line; i <= end.line; i++) { - let line = doc.getline(i); - ranges.push(import_vscode_languageserver_protocol83.Range.create(i, sc, i, Math.min(line.length, ec))); - } - return ranges; -} -function adjustPosition2(position, delta) { - let { line, character } = delta; - return import_vscode_languageserver_protocol83.Position.create(position.line + line, line == 0 ? position.character + character : character); -} -function equalEdit(one, two) { - if (one.newText.length != two.newText.length) - return false; - let { range } = one; - if (range.end.character - range.start.character != two.range.end.character - two.range.start.character) { - return false; - } - return true; -} -var import_vscode_languageserver_protocol83; -var init_util4 = __esm({ - "src/cursors/util.ts"() { - import_vscode_languageserver_protocol83 = __toModule(require_main2()); - } -}); - -// src/cursors/session.ts -var import_fast_diff4, import_vscode_languageserver_protocol84, logger88, CursorSession; -var init_session3 = __esm({ - "src/cursors/session.ts"() { - import_fast_diff4 = __toModule(require_diff()); - import_vscode_languageserver_protocol84 = __toModule(require_main2()); - init_main2(); - init_events(); - init_position(); - init_window(); - init_workspace(); - init_range(); - init_util4(); - logger88 = require_logger2()("cursors-session"); - CursorSession = class { - constructor(nvim, doc, config) { - this.nvim = nvim; - this.doc = doc; - this.config = config; - this._onDidCancel = new import_vscode_languageserver_protocol84.Emitter(); - this.onDidCancel = this._onDidCancel.event; - this.disposables = []; - this.ranges = []; - this.activated = true; - this.changing = false; - this.changed = false; - this.textDocument = this.doc.textDocument; - this.buffer.setVar("coc_cursors_activated", 1, true); - let { cancelKey, nextKey, previousKey } = this.config; - this.disposables.push(workspace_default.registerLocalKeymap("n", cancelKey, () => { - this.cancel(); - }, true)); - this.disposables.push(workspace_default.registerLocalKeymap("n", nextKey, async () => { - if (!this.activated) - return; - let ranges = this.ranges.map((o) => o.currRange); - let curr = await window_default.getCursorPosition(); - for (let r of ranges) { - if (comparePosition(r.start, curr) > 0) { - await window_default.moveTo(r.start); - return; - } - } - if (ranges.length) - await window_default.moveTo(ranges[0].start); - }, true)); - this.disposables.push(workspace_default.registerLocalKeymap("n", previousKey, async () => { - if (!this.activated) - return; - let ranges = this.ranges.map((o) => o.currRange); - ranges.reverse(); - let curr = await window_default.getCursorPosition(); - for (let r of ranges) { - if (comparePosition(r.end, curr) < 0) { - await window_default.moveTo(r.start); - return; - } - } - if (ranges.length) - await window_default.moveTo(ranges[ranges.length - 1].start); - }, true)); - this.doc.onDocumentChange(this.onChange, this, this.disposables); - } - async onChange(e) { - if (!this.activated || this.ranges.length == 0) - return; - if (this.changing) - return; - let change = e.contentChanges[0]; - let { text, range } = change; - let intersect = this.ranges.some((r) => rangeIntersect(range, r.currRange)); - let begin = this.ranges[0].currRange.start; - if (text.endsWith("\n") && comparePosition(begin, range.end) == 0) { - intersect = false; - } - if (!intersect) { - this.ranges.forEach((r) => { - r.adjustFromEdit({ range, newText: text }); - }); - this.doHighlights(); - this.textDocument = this.doc.textDocument; - return; - } - this.changed = true; - let textRange = this.getTextRange(range, text); - if (textRange) { - await this.applySingleEdit(textRange, { range, newText: text }); - } else { - this.applyComposedEdit(e.original, { range, newText: text }); - if (this.activated) { - this.ranges.forEach((r) => { - r.sync(); - }); - this.textDocument = this.doc.textDocument; - } - } - } - doHighlights() { - let { nvim, buffer, ranges } = this; - buffer.clearNamespace("cursors"); - let arr = ranges.map((o) => o.currRange); - buffer.highlightRanges("cursors", "CocCursorRange", arr); - nvim.command("redraw", true); - } - addRanges(ranges) { - let { nvim, doc } = this; - if (this.changed) { - window_default.showMessage(`Can't add ranges after range change.`); - return false; - } - this.ranges = this.ranges.filter((r) => { - let { currRange } = r; - return !ranges.some((range) => rangeOverlap(range, currRange)); - }); - let { textDocument } = doc; - for (let range of ranges) { - let { line } = range.start; - let textRange = new TextRange(line, range.start.character, range.end.character, textDocument.getText(range), 0); - this.ranges.push(textRange); - } - this.ranges.sort((a, b) => comparePosition(a.range.start, b.range.start)); - let preCount = 0; - let currline = -1; - for (let range of this.ranges) { - let { line } = range; - if (line != currline) { - preCount = 0; - } - range.preCount = preCount; - preCount = preCount + 1; - currline = line; - } - nvim.pauseNotification(); - this.doHighlights(); - nvim.resumeNotification(false, true); - return true; - } - cancel() { - if (!this.activated) - return; - let { nvim } = this; - this.activated = false; - let { cancelKey, nextKey, previousKey } = this.config; - nvim.pauseNotification(); - this.buffer.clearNamespace("cursors"); - this.buffer.setVar("coc_cursors_activated", 0, true); - nvim.command("redraw", true); - nvim.resumeNotification(false, true); - this._onDidCancel.fire(); - } - dispose() { - if (!this.doc) - return; - this._onDidCancel.dispose(); - for (let disposable of this.disposables) { - disposable.dispose(); - } - this.ranges = []; - this.doc = null; - this.textDocument = null; - } - get buffer() { - return this.nvim.createBuffer(this.doc.bufnr); - } - getTextRange(range, text) { - let { ranges } = this; - if (text.indexOf("\n") !== -1 || range.start.line != range.end.line) { - return null; - } - ranges.sort((a, b) => { - if (a.line != b.line) - return a.line - b.line; - return a.currRange.start.character - b.currRange.start.character; - }); - for (let i = 0; i < ranges.length; i++) { - let r = ranges[i]; - if (rangeInRange(range, r.currRange)) { - return r; - } - if (r.line != range.start.line) { - continue; - } - if (text.length && range.start.character == r.currRange.end.character) { - let next = ranges[i + 1]; - if (!next) - return r; - return positionInRange(next.currRange.start, range) ? null : r; - } - } - return null; - } - adjustRanges(textRange, range, text) { - let { ranges } = this; - if (range.start.character == range.end.character) { - let isEnd = textRange.currRange.end.character == range.start.character; - if (isEnd) { - ranges.forEach((r) => { - r.add(r.text.length, text); - }); - } else { - let d = range.start.character - textRange.currRange.start.character; - ranges.forEach((r) => { - r.add(Math.min(r.text.length, d), text); - }); - } - } else { - let d = range.end.character - range.start.character; - let isEnd = textRange.currRange.end.character == range.end.character; - if (isEnd) { - if (textRange.currRange.start.character == range.start.character) { - if (text.includes(textRange.text)) { - let idx = text.indexOf(textRange.text); - let pre = idx == 0 ? "" : text.slice(0, idx); - let post = text.slice(idx + textRange.text.length); - if (pre) - ranges.forEach((r) => r.add(0, pre)); - if (post) - ranges.forEach((r) => r.add(r.text.length, post)); - } else if (textRange.text.includes(text)) { - let idx = textRange.text.indexOf(text); - let offset = textRange.text.length - (idx + text.length); - if (idx != 0) - ranges.forEach((r) => r.replace(0, idx)); - if (offset > 0) - ranges.forEach((r) => r.replace(r.text.length - offset, r.text.length)); - } else { - this.cancel(); - } - } else { - ranges.forEach((r) => { - let l = r.text.length; - r.replace(Math.max(0, l - d), l, text); - }); - } - } else { - let start = range.start.character - textRange.currRange.start.character; - ranges.forEach((r) => { - let l = r.text.length; - r.replace(start, Math.min(start + d, l), text); - }); - } - } - } - addRange(range, text) { - if (this.changed) { - window_default.showMessage(`Can't add range after range change.`); - return; - } - let { ranges } = this; - let idx = ranges.findIndex((o) => rangeIntersect(o.range, range)); - if (idx !== -1) { - ranges.splice(idx, 1); - for (let r of ranges) { - if (r.line == range.start.line && r.start > range.start.character) { - r.preCount = r.preCount - 1; - } - } - } else { - let preCount = 0; - let idx2 = 0; - let { line } = range.start; - for (let r of ranges) { - if (r.line > line || r.line == line && r.start > range.end.character) { - break; - } - if (r.line == line) - preCount++; - idx2++; - } - let created = new TextRange(line, range.start.character, range.end.character, text, preCount); - ranges.splice(idx2, 0, created); - for (let r of ranges) { - if (r.line == range.start.line && r.start > range.start.character) { - r.preCount = r.preCount + 1; - } - } - } - if (this.ranges.length == 0) { - this.cancel(); - } else { - this.doHighlights(); - } - } - async applySingleEdit(textRange, edit2) { - let { range, newText } = edit2; - let { doc } = this; - this.adjustRanges(textRange, range, newText); - if (this.ranges.length == 1) { - this.doHighlights(); - return; - } - let edits = this.ranges.map((o) => o.textEdit); - let content = TextDocument2.applyEdits(this.textDocument, edits); - let newLines = content.split("\n"); - let changedLnum = new Set(); - let arr = []; - for (let r of this.ranges) { - if (!changedLnum.has(r.line)) { - changedLnum.add(r.line); - arr.push([r.line, newLines[r.line]]); - } - } - let { nvim } = this; - this.changing = true; - await doc.changeLines(arr); - this.changing = false; - if (this.activated) { - this.ranges.forEach((r) => { - r.sync(); - }); - this.textDocument = this.doc.textDocument; - } - nvim.pauseNotification(); - let { cursor } = events_default; - if (textRange.preCount > 0 && cursor.bufnr == doc.bufnr && textRange.line + 1 == cursor.lnum) { - let changed = textRange.preCount * (newText.length - (range.end.character - range.start.character)); - nvim.call("cursor", [cursor.lnum, cursor.col + changed], true); - } - this.doHighlights(); - nvim.resumeNotification(false, true); - } - applyComposedEdit(original, edit2) { - let { range, newText } = edit2; - let { ranges } = this; - let doc = TextDocument2.create("file:///1", "", 0, original); - let edits = []; - let diffs = (0, import_fast_diff4.default)(original, newText); - let offset = 0; - for (let i = 0; i < diffs.length; i++) { - let diff = diffs[i]; - let pos = adjustPosition2(range.start, doc.positionAt(offset)); - if (diff[0] == import_fast_diff4.default.EQUAL) { - offset = offset + diff[1].length; - } else if (diff[0] == import_fast_diff4.default.DELETE) { - let end = adjustPosition2(range.start, doc.positionAt(offset + diff[1].length)); - if (diffs[i + 1] && diffs[i + 1][0] == import_fast_diff4.default.INSERT) { - edits.push({ range: import_vscode_languageserver_protocol84.Range.create(pos, end), newText: diffs[i + 1][1] }); - i = i + 1; - } else { - edits.push({ range: import_vscode_languageserver_protocol84.Range.create(pos, end), newText: "" }); - } - offset = offset + diff[1].length; - } else if (diff[0] == import_fast_diff4.default.INSERT) { - edits.push({ range: import_vscode_languageserver_protocol84.Range.create(pos, pos), newText: diff[1] }); - } - } - if (edits.some((edit3) => edit3.newText.includes("\n") || edit3.range.start.line != edit3.range.end.line)) { - this.cancel(); - return; - } - if (edits.length == ranges.length) { - let last; - for (let i = 0; i < edits.length; i++) { - let edit3 = edits[i]; - let textRange = this.ranges[i]; - if (!rangeIntersect(textRange.currRange, edit3.range)) { - this.cancel(); - return; - } - if (last && !equalEdit(edit3, last)) { - this.cancel(); - return; - } - textRange.applyEdit(edit3); - last = edit3; - } - } else if (edits.length == ranges.length * 2) { - for (let i = 0; i < edits.length - 1; i = i + 2) { - let edit3 = edits[i]; - let next = edits[i + 1]; - if (edit3.newText.length == 0 && next.newText.length == 0) { - let textRange = this.ranges[i / 2]; - if (comparePosition(textRange.currRange.end, next.range.end) != 0) { - this.cancel(); - return; - } - let start = edit3.range.start.character - textRange.currRange.start.character; - textRange.replace(start, edit3.range.end.character - edit3.range.start.character, ""); - let offset2 = next.range.end.character - next.range.start.character; - let len = textRange.text.length; - textRange.replace(len - offset2, len); - } else if (emptyRange(edit3.range) && emptyRange(next.range)) { - let textRange = this.ranges[i / 2]; - if (comparePosition(textRange.currRange.end, next.range.start) != 0) { - this.cancel(); - return; - } - let start = edit3.range.start.character - textRange.currRange.start.character; - textRange.add(start, edit3.newText); - let len = textRange.text.length; - textRange.add(len, next.newText); - } else { - this.cancel(); - return; - } - } - } else { - this.cancel(); - return; - } - this.doHighlights(); - } - }; - } -}); - -// src/cursors/index.ts -var logger89, Cursors; -var init_cursors = __esm({ - "src/cursors/index.ts"() { - init_main(); - init_events(); - init_position(); - init_window(); - init_workspace(); - init_session3(); - init_util4(); - logger89 = require_logger2()("cursors"); - Cursors = class { - constructor(nvim) { - this.nvim = nvim; - this.sessionsMap = new Map(); - this.disposables = []; - this.loadConfig(); - workspace_default.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("cursors")) { - this.loadConfig(); - } - }, null, this.disposables); - events_default.on("BufUnload", (bufnr) => { - let session = this.getSession(bufnr); - if (!session) - return; - session.dispose(); - this.sessionsMap.delete(bufnr); - }, null, this.disposables); - } - loadConfig() { - let config = workspace_default.getConfiguration("cursors"); - this.config = { - nextKey: config.get("nextKey", ""), - previousKey: config.get("previousKey", ""), - cancelKey: config.get("cancelKey", "") - }; - } - getSession(bufnr) { - return this.sessionsMap.get(bufnr); - } - async isActivated() { - let bufnr = await this.nvim.call("bufnr", ["%"]); - return this.sessionsMap.get(bufnr) != null; - } - async select(bufnr, kind, mode) { - let doc = workspace_default.getDocument(bufnr); - if (!doc || !doc.attached) { - window_default.showMessage(`buffer ${bufnr} not attached.`); - return; - } - let { nvim } = this; - let session = this.createSession(doc); - let pos = await window_default.getCursorPosition(); - let range; - if (kind == "operator") { - await nvim.command(`normal! ${mode == "line" ? `'[` : "`["}`); - let start = await window_default.getCursorPosition(); - await nvim.command(`normal! ${mode == "line" ? `']` : "`]"}`); - let end = await window_default.getCursorPosition(); - await window_default.moveTo(pos); - let relative = comparePosition(start, end); - if (relative == 0) - return; - if (relative >= 0) - [start, end] = [end, start]; - let line = doc.getline(end.line); - if (end.character < line.length) { - end.character = end.character + 1; - } - let ranges = splitRange(doc, Range.create(start, end)); - for (let r of ranges) { - let text = doc.textDocument.getText(r); - session.addRange(r, text); - } - } else if (kind == "word") { - range = doc.getWordRangeAtPosition(pos); - if (!range) { - let line2 = doc.getline(pos.line); - if (pos.character == line2.length) { - range = Range.create(pos.line, Math.max(0, line2.length - 1), pos.line, line2.length); - } else { - range = Range.create(pos.line, pos.character, pos.line, pos.character + 1); - } - } - let line = doc.getline(pos.line); - let text = line.slice(range.start.character, range.end.character); - session.addRange(range, text); - } else if (kind == "position") { - let line = doc.getline(pos.line); - if (pos.character >= line.length) { - range = Range.create(pos.line, line.length - 1, pos.line, line.length); - } else { - range = Range.create(pos.line, pos.character, pos.line, pos.character + 1); - } - session.addRange(range, line.slice(range.start.character, range.end.character)); - } else if (kind == "range") { - await nvim.call("eval", 'feedkeys("\\", "in")'); - let range2 = await workspace_default.getSelectedRange(mode, doc); - if (!range2 || comparePosition(range2.start, range2.end) == 0) - return; - let ranges = mode == "" ? getVisualRanges(doc, range2) : splitRange(doc, range2); - for (let r of ranges) { - let text = doc.textDocument.getText(r); - session.addRange(r, text); - } - } else { - window_default.showMessage(`${kind} not supported`, "error"); - return; - } - if (kind == "word" || kind == "position") { - await nvim.command(`silent! call repeat#set("\\(coc-cursors-${kind})", -1)`); - } - } - createSession(doc) { - let session = this.getSession(doc.bufnr); - if (session) - return session; - session = new CursorSession(this.nvim, doc, this.config); - this.sessionsMap.set(doc.bufnr, session); - session.onDidCancel(() => { - session.dispose(); - this.sessionsMap.delete(doc.bufnr); - }); - return session; - } - async addRanges(ranges) { - let { nvim } = this; - let bufnr = await nvim.call("bufnr", ["%"]); - let doc = workspace_default.getDocument(bufnr); - if (!doc || !doc.attached) { - window_default.showMessage("Document not attached", "error"); - return false; - } - let session = this.createSession(doc); - return session.addRanges(ranges); - } - reset() { - for (let session of this.sessionsMap.values()) { - session.cancel(); - } - this.sessionsMap.clear(); - } - dispose() { - for (let session of this.sessionsMap.values()) { - session.dispose(); - } - this.sessionsMap.clear(); - for (let disposable of this.disposables) { - disposable.dispose(); - } - } - }; - } -}); - -// src/handler/codeActions.ts -var import_vscode_languageserver_protocol85, logger90, CodeActions; -var init_codeActions = __esm({ - "src/handler/codeActions.ts"() { - init_manager(); - import_vscode_languageserver_protocol85 = __toModule(require_main2()); - init_commands2(); - init_workspace(); - init_window(); - init_languages(); - logger90 = require_logger2()("handler-codeActions"); - CodeActions = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - handler.addDisposable(commands_default.registerCommand("editor.action.organizeImport", async (bufnr) => { - await this.organizeImport(bufnr); - })); - commands_default.titles.set("editor.action.organizeImport", "run organize import code action."); - } - async codeActionRange(start, end, only) { - let { doc } = await this.handler.getCurrentState(); - await doc.synchronize(); - let line = doc.getline(end - 1); - let range = import_vscode_languageserver_protocol85.Range.create(start - 1, 0, end - 1, line.length); - let codeActions = await this.getCodeActions(doc, range, only ? [only] : null); - if (!codeActions || codeActions.length == 0) { - window_default.showMessage(`No${only ? " " + only : ""} code action available`, "warning"); - return; - } - let idx = await window_default.showMenuPicker(codeActions.map((o) => o.title), "Choose action"); - let action = codeActions[idx]; - if (action) - await this.applyCodeAction(action); - } - async organizeImport(bufnr) { - let { doc } = await this.handler.getCurrentState(); - if (bufnr && doc.bufnr != bufnr) - return; - await doc.synchronize(); - let actions = await this.getCodeActions(doc, void 0, [import_vscode_languageserver_protocol85.CodeActionKind.SourceOrganizeImports]); - if (actions && actions.length) { - await this.applyCodeAction(actions[0]); - return; - } - throw new Error("Organize import action not found."); - } - async getCodeActions(doc, range, only) { - range = range || import_vscode_languageserver_protocol85.Range.create(0, 0, doc.lineCount, 0); - let diagnostics = manager_default.getDiagnosticsInRange(doc.textDocument, range); - let context = { diagnostics }; - if (only && Array.isArray(only)) - context.only = only; - let codeActions = await this.handler.withRequestToken("code action", (token) => { - return languages_default.getCodeActions(doc.textDocument, range, context, token); - }); - if (!codeActions || codeActions.length == 0) - return []; - codeActions = codeActions.filter((o) => !o.disabled); - codeActions.sort((a, b) => { - if (a.isPreferred && !b.isPreferred) - return -1; - if (b.isPreferred && !a.isPreferred) - return 1; - return 0; - }); - return codeActions; - } - get floatActions() { - if (!workspace_default.floatSupported) - return false; - let config = workspace_default.getConfiguration("coc.preferences"); - return config.get("floatActions", true); - } - async doCodeAction(mode, only) { - let { doc } = await this.handler.getCurrentState(); - let range; - if (mode) - range = await workspace_default.getSelectedRange(mode, doc); - await doc.synchronize(); - let codeActions = await this.getCodeActions(doc, range, Array.isArray(only) ? only : null); - if (typeof only == "string") { - codeActions = codeActions.filter((o) => o.title == only || o.command && o.command.title == only); - } else if (Array.isArray(only)) { - codeActions = codeActions.filter((o) => only.some((k) => o.kind && o.kind.startsWith(k))); - } - if (!codeActions || codeActions.length == 0) { - window_default.showMessage(`No${only ? " " + only : ""} code action available`, "warning"); - return; - } - if (only && codeActions.length == 1) { - await this.applyCodeAction(codeActions[0]); - return; - } - let idx = this.floatActions ? await window_default.showMenuPicker(codeActions.map((o) => o.title), "Choose action") : await window_default.showQuickpick(codeActions.map((o) => o.title)); - let action = codeActions[idx]; - if (action) - await this.applyCodeAction(action); - } - async getCurrentCodeActions(mode, only) { - let { doc } = await this.handler.getCurrentState(); - let range; - if (mode) - range = await workspace_default.getSelectedRange(mode, doc); - return await this.getCodeActions(doc, range, only); - } - async doQuickfix() { - let actions = await this.getCurrentCodeActions("line", [import_vscode_languageserver_protocol85.CodeActionKind.QuickFix]); - if (!actions || actions.length == 0) { - throw new Error("No quickfix action available"); - } - await this.applyCodeAction(actions[0]); - this.nvim.command(`silent! call repeat#set("\\(coc-fix-current)", -1)`, true); - } - async applyCodeAction(action) { - if (action.disabled) { - throw new Error(`Action "${action.title}" is disabled: ${action.disabled.reason}`); - } - action = await this.handler.withRequestToken("resolve codeAction", (token) => { - return languages_default.resolveCodeAction(action, token); - }); - let { edit: edit2, command } = action; - if (edit2) - await workspace_default.applyEdit(edit2); - if (command) - await commands_default.execute(command); - } - }; - } -}); - -// src/handler/codelens/buffer.ts -var import_debounce10, import_vscode_languageserver_protocol86, logger91, CodeLensBuffer; -var init_buffer3 = __esm({ - "src/handler/codelens/buffer.ts"() { - import_debounce10 = __toModule(require_debounce()); - import_vscode_languageserver_protocol86 = __toModule(require_main2()); - init_commands2(); - init_languages(); - init_window(); - init_workspace(); - logger91 = require_logger2()("codelens-buffer"); - CodeLensBuffer = class { - constructor(nvim, bufnr, config) { - this.nvim = nvim; - this.bufnr = bufnr; - this.config = config; - this.fetchCodelenses = (0, import_debounce10.default)(() => { - void this._fetchCodeLenses(); - }, 200); - this.resolveCodeLens = (0, import_debounce10.default)(() => { - void this._resolveCodeLenses(); - }, 200); - this.fetchCodelenses(); - } - currentCodeLens() { - var _a2; - return (_a2 = this.codeLenses) == null ? void 0 : _a2.codeLenses; - } - get enabled() { - return this.textDocument && this.config.enabled && languages_default.hasProvider("codeLens", this.textDocument); - } - async forceFetch() { - this.fetchCodelenses.clear(); - await this._fetchCodeLenses(); - } - get textDocument() { - var _a2; - return (_a2 = workspace_default.getDocument(this.bufnr)) == null ? void 0 : _a2.textDocument; - } - async _fetchCodeLenses() { - var _a2, _b; - if (!this.enabled) - return; - this.cancel(); - let noFetch = !this.isChanged && !((_a2 = this.codeLenses) == null ? void 0 : _a2.hasError); - if (!noFetch) { - let { textDocument } = this; - let version2 = textDocument.version; - let tokenSource = this.tokenSource = new import_vscode_languageserver_protocol86.CancellationTokenSource(); - let token = tokenSource.token; - let codeLenses2 = await languages_default.getCodeLens(textDocument, token); - this.tokenSource = void 0; - if (token.isCancellationRequested) - return; - if (!Array.isArray(codeLenses2) || codeLenses2.length == 0) - return; - let hasError = codeLenses2.some((o) => o == null); - this.codeLenses = { version: version2, codeLenses: codeLenses2.filter((o) => o != null), hasError }; - } - let codeLenses = (_b = this.codeLenses) == null ? void 0 : _b.codeLenses; - if (codeLenses == null ? void 0 : codeLenses.length) { - await this._resolveCodeLenses(); - } - } - async _resolveCodeLenses() { - if (!this.enabled || !this.codeLenses || this.isChanged) - return; - let { codeLenses } = this.codeLenses; - let [bufnr, start, end] = await this.nvim.eval(`[bufnr('%'),line('w0'),line('w$')]`); - if (this.isChanged || bufnr != this.bufnr) - return; - if (this.resolveTokenSource) { - this.resolveTokenSource.cancel(); - } - codeLenses = codeLenses.filter((o) => { - let lnum = o.range.start.line + 1; - return lnum >= start && lnum <= end; - }); - if (codeLenses.length) { - let tokenSource = this.resolveTokenSource = new import_vscode_languageserver_protocol86.CancellationTokenSource(); - let token = tokenSource.token; - await Promise.all(codeLenses.map((codeLens) => languages_default.resolveCodeLens(codeLens, token))); - this.resolveTokenSource = void 0; - if (token.isCancellationRequested || this.isChanged) - return; - } - if (!this.srcId) - this.srcId = await this.nvim.createNamespace("coc-codelens"); - this.nvim.pauseNotification(); - this.clear(start - 1, end); - this.setVirtualText(codeLenses); - await this.nvim.resumeNotification(); - } - get isChanged() { - if (!this.textDocument || !this.codeLenses) - return true; - let { version: version2 } = this.codeLenses; - return this.textDocument.version !== version2; - } - setVirtualText(codeLenses) { - if (codeLenses.length == 0) - return; - let list2 = new Map(); - for (let codeLens of codeLenses) { - let { range, command } = codeLens; - if (!command) - continue; - let { line } = range.start; - if (list2.has(line)) { - list2.get(line).push(codeLens); - } else { - list2.set(line, [codeLens]); - } - } - for (let lnum of list2.keys()) { - let codeLenses2 = list2.get(lnum); - let commands = codeLenses2.map((codeLens) => codeLens.command); - commands = commands.filter((c) => c && c.title); - let chunks = []; - let n_commands = commands.length; - for (let i = 0; i < n_commands; i++) { - let c = commands[i]; - chunks.push([c.title.replace(/(\r\n|\r|\n|\s)+/g, " "), "CocCodeLens"]); - if (i != n_commands - 1) { - chunks.push([this.config.subseparator, "CocCodeLens"]); - } - } - chunks.unshift([`${this.config.separator} `, "CocCodeLens"]); - this.nvim.call("nvim_buf_set_virtual_text", [this.bufnr, this.srcId, lnum, chunks, {}], true); - } - } - clear(start = 0, end = -1) { - if (!this.srcId) - return; - let buf = this.nvim.createBuffer(this.bufnr); - buf.clearNamespace(this.srcId, start, end); - } - cleanUp() { - this.clear(); - this.codeLenses = void 0; - } - getCodelenses() { - var _a2; - return (_a2 = this.codeLenses) == null ? void 0 : _a2.codeLenses; - } - async doAction(line) { - var _a2; - let { codeLenses } = (_a2 = this.codeLenses) != null ? _a2 : {}; - if (!(codeLenses == null ? void 0 : codeLenses.length)) - return; - let commands = []; - for (let codeLens of codeLenses) { - let { range, command } = codeLens; - if (!command || !range) - continue; - if (line == range.start.line) { - commands.push(command); - } - } - if (!commands.length) - return; - if (commands.length == 1) { - await commands_default.execute(commands[0]); - } else { - let res = await window_default.showMenuPicker(commands.map((c) => c.title)); - if (res == -1) - return; - await commands_default.execute(commands[res]); - } - } - cancel() { - this.resolveCodeLens.clear(); - this.fetchCodelenses.clear(); - if (this.tokenSource) { - this.tokenSource.cancel(); - this.tokenSource.dispose(); - this.tokenSource = null; - } - } - onChange() { - this.cancel(); - this.fetchCodelenses(); - } - dispose() { - this.clear(); - this.cancel(); - this.codeLenses = void 0; - } - }; - } -}); - -// src/handler/codelens/index.ts -var logger92, CodeLensManager2; -var init_codelens = __esm({ - "src/handler/codelens/index.ts"() { - init_events(); - init_util(); - init_workspace(); - init_buffer3(); - logger92 = require_logger2()("codelens"); - CodeLensManager2 = class { - constructor(nvim) { - this.nvim = nvim; - this.disposables = []; - this.setConfiguration(); - if (!workspace_default.isNvim) - return; - workspace_default.onDidChangeConfiguration((e) => { - this.setConfiguration(e); - }); - this.buffers = workspace_default.registerBufferSync((doc) => { - if (doc.buftype != "") - return void 0; - return new CodeLensBuffer(nvim, doc.bufnr, this.config); - }); - this.listen(); - } - listen() { - events_default.on("CursorMoved", (bufnr) => { - let buf = this.buffers.getItem(bufnr); - if (buf) - buf.resolveCodeLens(); - }, null, this.disposables); - events_default.on("CursorHold", async (bufnr) => { - let buf = this.buffers.getItem(bufnr); - if (buf) - await buf.forceFetch(); - }, this, this.disposables); - } - async checkProvider() { - for (let buf of this.buffers.items) { - await buf.forceFetch(); - } - } - setConfiguration(e) { - if (e && !e.affectsConfiguration("codeLens")) - return; - let config = workspace_default.getConfiguration("codeLens"); - let enable = this.nvim.hasFunction("nvim_buf_set_virtual_text") && config.get("enable", false); - if (e && enable != this.config.enabled) { - if (enable) { - this.listen(); - } else { - disposeAll(this.disposables); - } - for (let buf of this.buffers.items) { - if (enable) { - buf.fetchCodelenses(); - } else { - buf.cleanUp(); - } - } - } - this.config = Object.assign(this.config || {}, { - enabled: enable, - separator: config.get("separator", "\u2023"), - subseparator: config.get("subseparator", " ") - }); - } - async doAction() { - let [bufnr, line] = await this.nvim.eval(`[bufnr("%"),line(".")-1]`); - let buf = this.buffers.getItem(bufnr); - await (buf == null ? void 0 : buf.doAction(line)); - } - dispose() { - this.buffers.dispose(); - disposeAll(this.disposables); - } - }; - } -}); - -// src/util/color.ts -function pad(str) { - return str.length == 1 ? `0${str}` : str; -} -function toHexString(color) { - let c = toHexColor(color); - return `${pad(c.red.toString(16))}${pad(c.green.toString(16))}${pad(c.blue.toString(16))}`; -} -function toHexColor(color) { - let { red, green, blue: blue2 } = color; - return { - red: Math.round(red * 255), - green: Math.round(green * 255), - blue: Math.round(blue2 * 255) - }; -} -function isDark(color) { - let rgb = [color.red, color.green, color.blue]; - let lum = []; - for (let i = 0; i < rgb.length; i++) { - let chan = rgb[i]; - lum[i] = chan <= 0.03928 ? chan / 12.92 : Math.pow((chan + 0.055) / 1.055, 2.4); - } - let luma = 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; - return luma <= 0.5; -} -var init_color = __esm({ - "src/util/color.ts"() { - } -}); - -// src/handler/colors/colorBuffer.ts -var import_debounce11, import_vscode_languageserver_protocol87, logger93, ColorBuffer; -var init_colorBuffer = __esm({ - "src/handler/colors/colorBuffer.ts"() { - import_debounce11 = __toModule(require_debounce()); - import_vscode_languageserver_protocol87 = __toModule(require_main2()); - init_languages(); - init_array(); - init_object(); - init_position(); - init_color(); - init_workspace(); - logger93 = require_logger2()("colors-buffer"); - ColorBuffer = class { - constructor(nvim, bufnr, enabled, usedColors) { - this.nvim = nvim; - this.bufnr = bufnr; - this.enabled = enabled; - this.usedColors = usedColors; - this._colors = []; - this.highlight = (0, import_debounce11.default)(() => { - void this.doHighlight(); - }, global.hasOwnProperty("__TEST__") ? 10 : 500); - } - onChange() { - this.cancel(); - this.highlight(); - } - get buffer() { - return this.nvim.createBuffer(this.bufnr); - } - get colors() { - return this._colors; - } - hasColor() { - return this._colors.length > 0; - } - setState(enabled) { - this.enabled = enabled; - if (enabled) { - this.highlight(); - } else { - this.clearHighlight(); - } - } - async doHighlight() { - let doc = workspace_default.getDocument(this.bufnr); - if (!doc || !this.enabled) - return; - try { - this.tokenSource = new import_vscode_languageserver_protocol87.CancellationTokenSource(); - let { token } = this.tokenSource; - if (this.version && doc.version == this.version) - return; - let { version: version2 } = doc; - let colors; - colors = await languages_default.provideDocumentColors(doc.textDocument, token); - colors = colors || []; - if (token.isCancellationRequested) - return; - this.version = version2; - await this.addHighlight(colors); - } catch (e) { - logger93.error("Error on highlight:", e); - } - } - async addHighlight(colors) { - colors = colors || []; - if (equals(this._colors, colors)) - return; - let { nvim } = this; - this._colors = colors; - let groups = group(colors, 100); - nvim.pauseNotification(); - this.buffer.clearNamespace("color"); - this.defineColors(colors); - void nvim.resumeNotification(false, true); - for (let colors2 of groups) { - nvim.pauseNotification(); - let colorRanges = this.getColorRanges(colors2); - for (let o of colorRanges) { - this.highlightColor(o.ranges, o.color); - } - void nvim.resumeNotification(false, true); - } - if (workspace_default.isVim) - this.nvim.command("redraw", true); - } - highlightColor(ranges, color) { - let hlGroup = `BG${toHexString(color)}`; - this.buffer.highlightRanges("color", hlGroup, ranges); - } - defineColors(colors) { - for (let color of colors) { - let hex = toHexString(color.color); - if (!this.usedColors.has(hex)) { - this.nvim.command(`hi BG${hex} guibg=#${hex} guifg=#${isDark(color.color) ? "ffffff" : "000000"}`, true); - this.usedColors.add(hex); - } - } - } - getColorRanges(infos) { - let res = []; - for (let info of infos) { - let { color, range } = info; - let idx = res.findIndex((o) => equals(toHexColor(o.color), toHexColor(color))); - if (idx == -1) { - res.push({ - color, - ranges: [range] - }); - } else { - let r = res[idx]; - r.ranges.push(range); - } - } - return res; - } - clearHighlight() { - this.highlight.clear(); - this._colors = []; - this.version = null; - this.buffer.clearNamespace("color"); - } - hasColorAtPosition(position) { - let { colors } = this; - return colors.some((o) => positionInRange(position, o.range) == 0); - } - cancel() { - if (this.tokenSource) { - this.tokenSource.cancel(); - this.tokenSource = null; - } - } - dispose() { - this.highlight.clear(); - this.cancel(); - } - }; - } -}); - -// src/handler/colors/index.ts -var import_vscode_languageserver_protocol88, logger94, Colors; -var init_colors = __esm({ - "src/handler/colors/index.ts"() { - import_vscode_languageserver_protocol88 = __toModule(require_main2()); - init_commands2(); - init_extensions2(); - init_languages(); - init_util(); - init_color(); - init_window(); - init_workspace(); - init_colorBuffer(); - logger94 = require_logger2()("colors-index"); - Colors = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - this._enabled = true; - this.disposables = []; - let config = workspace_default.getConfiguration("coc.preferences"); - this._enabled = config.get("colorSupport", true); - let usedColors = new Set(); - this.highlighters = workspace_default.registerBufferSync((doc) => { - let buf = new ColorBuffer(this.nvim, doc.bufnr, this._enabled, usedColors); - buf.highlight(); - return buf; - }); - extensions_default.onDidActiveExtension(() => { - this.highlightAll(); - }, null, this.disposables); - workspace_default.onDidChangeConfiguration(async (e) => { - if (e.affectsConfiguration("coc.preferences.colorSupport")) { - let config2 = workspace_default.getConfiguration("coc.preferences"); - let enabled = config2.get("colorSupport", true); - this._enabled = enabled; - for (let buf of this.highlighters.items) { - buf.setState(enabled); - } - } - }, null, this.disposables); - this.disposables.push(commands_default.registerCommand("editor.action.pickColor", () => { - return this.pickColor(); - })); - commands_default.titles.set("editor.action.pickColor", "pick color from system color picker when possible."); - this.disposables.push(commands_default.registerCommand("editor.action.colorPresentation", () => { - return this.pickPresentation(); - })); - commands_default.titles.set("editor.action.colorPresentation", "change color presentation."); - } - async pickPresentation() { - let { doc } = await this.handler.getCurrentState(); - this.handler.checkProvier("documentColor", doc.textDocument); - let info = await this.getColorInformation(doc.bufnr); - if (!info) - return window_default.showMessage("Color not found at current position", "warning"); - let document2 = await workspace_default.document; - let tokenSource = new import_vscode_languageserver_protocol88.CancellationTokenSource(); - let presentations = await languages_default.provideColorPresentations(info, document2.textDocument, tokenSource.token); - if (!(presentations == null ? void 0 : presentations.length)) - return; - let res = await window_default.showMenuPicker(presentations.map((o) => o.label), "choose color:"); - if (res == -1) - return; - let presentation = presentations[res]; - let { textEdit, additionalTextEdits, label } = presentation; - if (!textEdit) - textEdit = { range: info.range, newText: label }; - await document2.applyEdits([textEdit]); - if (additionalTextEdits) { - await document2.applyEdits(additionalTextEdits); - } - } - async pickColor() { - let { doc } = await this.handler.getCurrentState(); - this.handler.checkProvier("documentColor", doc.textDocument); - let info = await this.getColorInformation(doc.bufnr); - if (!info) - return window_default.showMessage("Color not found at current position", "warning"); - let { color } = info; - let colorArr = [(color.red * 255).toFixed(0), (color.green * 255).toFixed(0), (color.blue * 255).toFixed(0)]; - let res = await this.nvim.call("coc#util#pick_color", [colorArr]); - if (!res) - return; - let hex = toHexString({ - red: res[0] / 65535, - green: res[1] / 65535, - blue: res[2] / 65535, - alpha: 1 - }); - let document2 = await workspace_default.document; - await document2.applyEdits([{ - range: info.range, - newText: `#${hex}` - }]); - } - get enabled() { - return this._enabled; - } - clearHighlight(bufnr) { - let highlighter = this.highlighters.getItem(bufnr); - if (!highlighter) - return; - highlighter.clearHighlight(); - } - hasColor(bufnr) { - let highlighter = this.highlighters.getItem(bufnr); - if (!highlighter) - return false; - return highlighter.hasColor(); - } - hasColorAtPosition(bufnr, position) { - let highlighter = this.highlighters.getItem(bufnr); - if (!highlighter) - return false; - return highlighter.hasColorAtPosition(position); - } - highlightAll() { - for (let buf of this.highlighters.items) { - buf.highlight(); - } - } - async doHighlight(bufnr) { - let highlighter = this.highlighters.getItem(bufnr); - if (highlighter) - await highlighter.doHighlight(); - } - async getColorInformation(bufnr) { - let highlighter = this.highlighters.getItem(bufnr); - if (!highlighter) - return null; - let position = await window_default.getCursorPosition(); - for (let info of highlighter.colors) { - let { range } = info; - let { start, end } = range; - if (position.line == start.line && position.character >= start.character && position.character <= end.character) { - return info; - } - } - return null; - } - dispose() { - this.highlighters.dispose(); - disposeAll(this.disposables); - } - }; - } -}); - -// src/handler/commands.ts -var logger95, isVim6, Commands; -var init_commands3 = __esm({ - "src/handler/commands.ts"() { - init_commands2(); - init_events(); - init_manager3(); - logger95 = require_logger2()("handler-commands"); - isVim6 = process.env.VIM_NODE_RPC == "1"; - Commands = class { - constructor(nvim, env) { - this.nvim = nvim; - this.env = env; - for (let item of env.vimCommands) { - this.addVimCommand(item); - } - } - addVimCommand(cmd) { - let id = `vim.${cmd.id}`; - commands_default.registerCommand(id, () => { - this.nvim.command(cmd.cmd, true); - if (isVim6) - this.nvim.command("redraw", true); - }); - if (cmd.title) - commands_default.titles.set(id, cmd.title); - } - getCommandList() { - return commands_default.commandList.map((o) => o.id); - } - async repeat() { - await commands_default.repeatCommand(); - } - async runCommand(id, ...args) { - if (id) { - await events_default.fire("Command", [id]); - let res = await commands_default.executeCommand(id, ...args); - if (args.length == 0) { - await commands_default.addRecent(id); - } - return res; - } else { - await manager_default2.start(["commands"]); - } - } - getCommands() { - let list2 = commands_default.commandList; - let res = []; - let { titles } = commands_default; - for (let item of list2) { - res.push({ - id: item.id, - title: titles.get(item.id) || "" - }); - } - return res; - } - }; - } -}); - -// src/handler/fold.ts -var FoldHandler; -var init_fold = __esm({ - "src/handler/fold.ts"() { - init_languages(); - init_workspace(); - FoldHandler = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - } - async fold(kind) { - let { doc, winid } = await this.handler.getCurrentState(); - this.handler.checkProvier("foldingRange", doc.textDocument); - await doc.synchronize(); - let win = this.nvim.createWindow(winid); - let foldlevel = await this.nvim.eval("&foldlevel"); - let ranges = await this.handler.withRequestToken("foldingrange", (token) => { - return languages_default.provideFoldingRanges(doc.textDocument, {}, token); - }, true); - if (!ranges || !ranges.length) - return false; - if (kind) - ranges = ranges.filter((o) => o.kind == kind); - ranges.sort((a, b) => b.startLine - a.startLine); - this.nvim.pauseNotification(); - win.setOption("foldmethod", "manual", true); - this.nvim.command("normal! zE", true); - for (let range of ranges) { - let { startLine, endLine } = range; - let cmd = `${startLine + 1}, ${endLine + 1}fold`; - this.nvim.command(cmd, true); - } - win.setOption("foldenable", true, true); - win.setOption("foldlevel", foldlevel, true); - if (workspace_default.isVim) - this.nvim.command("redraw", true); - await this.nvim.resumeNotification(); - return true; - } - }; - } -}); - -// src/handler/format.ts -var import_vscode_languageserver_protocol89, logger96, pairs, FormatHandler; -var init_format2 = __esm({ - "src/handler/format.ts"() { - import_vscode_languageserver_protocol89 = __toModule(require_main2()); - init_events(); - init_languages(); - init_manager4(); - init_position(); - init_string(); - init_window(); - init_workspace(); - logger96 = require_logger2()("handler-format"); - pairs = new Map([ - ["<", ">"], - [">", "<"], - ["{", "}"], - ["[", "]"], - ["(", ")"] - ]); - FormatHandler = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - this.loadPreferences(); - handler.addDisposable(workspace_default.onDidChangeConfiguration(this.loadPreferences, this)); - handler.addDisposable(workspace_default.onWillSaveTextDocument((event) => { - let { languageId } = event.document; - let filetypes = this.preferences.formatOnSaveFiletypes; - if (filetypes.includes(languageId) || filetypes.includes("*")) { - let willSaveWaitUntil = async () => { - if (!languages_default.hasFormatProvider(event.document)) { - logger96.warn(`Format provider not found for ${event.document.uri}`); - return void 0; - } - let options = await workspace_default.getFormatOptions(event.document.uri); - let tokenSource = new import_vscode_languageserver_protocol89.CancellationTokenSource(); - let timer = setTimeout(() => { - logger96.warn(`Format on save ${event.document.uri} timeout after 0.5s`); - tokenSource.cancel(); - }, 500); - let textEdits = await languages_default.provideDocumentFormattingEdits(event.document, options, tokenSource.token); - clearTimeout(timer); - if (!textEdits && !tokenSource.token.isCancellationRequested) { - logger96.want(`Format on save ${event.document.uri} get undefined result.`); - } - return textEdits; - }; - event.waitUntil(willSaveWaitUntil()); - } - })); - let enterTs; - let enterBufnr; - handler.addDisposable(events_default.on("Enter", async (bufnr) => { - enterTs = Date.now(); - enterBufnr = bufnr; - })); - handler.addDisposable(events_default.on("CursorMovedI", async (bufnr) => { - if (bufnr == enterBufnr && Date.now() - enterTs < 100) { - await this.handleEnter(bufnr); - } - })); - let changedTs; - let lastInsert; - handler.addDisposable(events_default.on("InsertCharPre", async () => { - lastInsert = Date.now(); - })); - handler.addDisposable(events_default.on("TextChangedI", async (bufnr, info) => { - changedTs = Date.now(); - if (!lastInsert || changedTs - lastInsert > 300) - return; - lastInsert = null; - let pre = info.pre[info.pre.length - 1]; - if (pre) - await this.tryFormatOnType(pre, bufnr); - })); - let lastEnterBufnr; - let lastEnterTs; - handler.addDisposable(events_default.on("InsertEnter", (bufnr) => { - lastEnterBufnr = bufnr; - lastEnterTs = Date.now(); - })); - handler.addDisposable(events_default.on("TextChangedI", async (bufnr, info) => { - if (!this.preferences.formatOnType && !/^\s*$/.test(info.pre)) - return; - if (lastEnterBufnr != bufnr || !lastEnterTs || Date.now() - lastEnterTs > 30) - return; - lastEnterBufnr = void 0; - await this.tryFormatOnType("\n", bufnr, true); - })); - } - loadPreferences(e) { - if (!e || e.affectsConfiguration("coc.preferences")) { - let config = workspace_default.getConfiguration("coc.preferences"); - this.preferences = { - formatOnType: config.get("formatOnType", false), - formatOnSaveFiletypes: config.get("formatOnSaveFiletypes", []), - formatOnTypeFiletypes: config.get("formatOnTypeFiletypes", []), - bracketEnterImprove: config.get("bracketEnterImprove", true) - }; - } - } - async tryFormatOnType(ch, bufnr, newLine = false) { - if (!ch || isWord(ch) || !this.preferences.formatOnType) - return; - if (manager_default3.getSession(bufnr) != null) - return; - let doc = workspace_default.getDocument(bufnr); - if (!doc || !doc.attached || doc.isCommandLine) - return; - const filetypes = this.preferences.formatOnTypeFiletypes; - if (filetypes.length && !filetypes.includes(doc.filetype) && !filetypes.includes("*")) { - return; - } - if (!languages_default.hasProvider("formatOnType", doc.textDocument)) { - logger96.warn(`Format on type provider not found for buffer: ${doc.uri}`); - return; - } - if (!languages_default.canFormatOnType(ch, doc.textDocument)) - return; - let position; - let edits = await this.handler.withRequestToken("Format on type", async (token) => { - position = await window_default.getCursorPosition(); - let origLine = doc.getline(position.line - 1); - if (newLine && /^\s*$/.test(origLine)) - return; - let pos = newLine ? { line: position.line - 1, character: origLine.length } : position; - await doc.synchronize(); - return await languages_default.provideDocumentOnTypeEdits(ch, doc.textDocument, pos, token); - }); - if (!edits || !edits.length) - return; - let changed = getChangedFromEdits(position, edits); - await doc.applyEdits(edits); - let to = changed ? import_vscode_languageserver_protocol89.Position.create(position.line + changed.line, position.character + changed.character) : null; - if (to && !newLine) - await window_default.moveTo(to); - } - async formatCurrentBuffer() { - let { doc } = await this.handler.getCurrentState(); - return await this.documentFormat(doc); - } - async formatCurrentRange(mode) { - let { doc } = await this.handler.getCurrentState(); - return await this.documentRangeFormat(doc, mode); - } - async documentFormat(doc) { - await doc.synchronize(); - if (!languages_default.hasFormatProvider(doc.textDocument)) { - throw new Error(`Format provider not found for buffer: ${doc.bufnr}`); - } - let options = await workspace_default.getFormatOptions(doc.uri); - let textEdits = await this.handler.withRequestToken("format", (token) => { - return languages_default.provideDocumentFormattingEdits(doc.textDocument, options, token); - }); - if (textEdits && textEdits.length > 0) { - await doc.applyEdits(textEdits); - return true; - } - return false; - } - async handleEnter(bufnr) { - let { nvim } = this; - let { bracketEnterImprove } = this.preferences; - await this.tryFormatOnType("\n", bufnr); - if (bracketEnterImprove) { - let line = await nvim.call("line", ".") - 1; - let doc = workspace_default.getDocument(bufnr); - if (!doc) - return; - await doc.patchChange(); - let pre = doc.getline(line - 1); - let curr = doc.getline(line); - let prevChar = pre[pre.length - 1]; - if (prevChar && pairs.has(prevChar)) { - let nextChar = curr.trim()[0]; - if (nextChar && pairs.get(prevChar) == nextChar) { - let edits = []; - let opts = await workspace_default.getFormatOptions(doc.uri); - let space = opts.insertSpaces ? " ".repeat(opts.tabSize) : " "; - let currIndent = curr.match(/^\s*/)[0]; - let pos = import_vscode_languageserver_protocol89.Position.create(line - 1, pre.length); - if (doc.filetype == "vim") { - let newText = "\n" + currIndent + space; - edits.push({ range: import_vscode_languageserver_protocol89.Range.create(line, currIndent.length, line, currIndent.length), newText: " \\ " }); - newText = newText + "\\ "; - edits.push({ range: import_vscode_languageserver_protocol89.Range.create(pos, pos), newText }); - await doc.applyEdits(edits); - await window_default.moveTo(import_vscode_languageserver_protocol89.Position.create(line, newText.length - 1)); - } else { - await nvim.eval(`feedkeys("\\O", 'in')`); - } - } - } - } - } - async documentRangeFormat(doc, mode) { - this.handler.checkProvier("formatRange", doc.textDocument); - await doc.synchronize(); - let range; - if (mode) { - range = await workspace_default.getSelectedRange(mode, doc); - if (!range) - return -1; - } else { - let [lnum, count, mode2] = await this.nvim.eval("[v:lnum,v:count,mode()]"); - if (count == 0 || mode2 == "i" || mode2 == "R") - return -1; - range = import_vscode_languageserver_protocol89.Range.create(lnum - 1, 0, lnum - 1 + count, 0); - } - let options = await workspace_default.getFormatOptions(doc.uri); - let textEdits = await this.handler.withRequestToken("Format range", (token) => { - return languages_default.provideDocumentRangeFormattingEdits(doc.textDocument, range, options, token); - }); - if (textEdits && textEdits.length > 0) { - await doc.applyEdits(textEdits); - return 0; - } - return -1; - } - }; - } -}); - -// src/handler/highlights.ts -var import_vscode_languageserver_protocol90, logger97, Highlights; -var init_highlights = __esm({ - "src/handler/highlights.ts"() { - import_vscode_languageserver_protocol90 = __toModule(require_main2()); - init_events(); - init_languages(); - init_util(); - init_workspace(); - logger97 = require_logger2()("documentHighlight"); - Highlights = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - this.disposables = []; - this.highlights = new Map(); - events_default.on(["CursorMoved", "CursorMovedI"], () => { - this.cancel(); - this.clearHighlights(); - }, null, this.disposables); - } - clearHighlights() { - if (this.highlights.size == 0) - return; - for (let winid of this.highlights.keys()) { - let win = this.nvim.createWindow(winid); - win.clearMatchGroup("^CocHighlight"); - } - this.highlights.clear(); - } - async highlight() { - let { nvim } = this; - this.cancel(); - let [bufnr, winid, pos, cursors] = await nvim.eval(`[bufnr("%"),win_getid(),coc#cursor#position(),get(b:,'coc_cursors_activated',0)]`); - let doc = workspace_default.getDocument(bufnr); - if (!doc || !doc.attached || cursors) - return; - if (!languages_default.hasProvider("documentHighlight", doc.textDocument)) - return; - let highlights = await this.getHighlights(doc, import_vscode_languageserver_protocol90.Position.create(pos[0], pos[1])); - if (!highlights) - return; - let groups = {}; - for (let hl of highlights) { - if (!hl.range) - continue; - let hlGroup = hl.kind == import_vscode_languageserver_protocol90.DocumentHighlightKind.Text ? "CocHighlightText" : hl.kind == import_vscode_languageserver_protocol90.DocumentHighlightKind.Read ? "CocHighlightRead" : "CocHighlightWrite"; - groups[hlGroup] = groups[hlGroup] || []; - groups[hlGroup].push(hl.range); - } - let win = nvim.createWindow(winid); - nvim.pauseNotification(); - win.clearMatchGroup("^CocHighlight"); - for (let hlGroup of Object.keys(groups)) { - win.highlightRanges(hlGroup, groups[hlGroup], -1, true); - } - if (workspace_default.isVim) - nvim.command("redraw", true); - nvim.resumeNotification(false, true); - this.highlights.set(winid, highlights); - } - async getSymbolsRanges() { - let { doc, position } = await this.handler.getCurrentState(); - this.handler.checkProvier("documentHighlight", doc.textDocument); - let highlights = await this.getHighlights(doc, position); - if (!highlights) - return null; - return highlights.map((o) => o.range); - } - hasHighlights(winid) { - return this.highlights.get(winid) != null; - } - async getHighlights(doc, position) { - let line = doc.getline(position.line); - let ch = line[position.character]; - if (!ch || !doc.isWord(ch)) - return null; - await doc.synchronize(); - this.tokenSource = new import_vscode_languageserver_protocol90.CancellationTokenSource(); - let source = this.tokenSource; - let highlights = await languages_default.getDocumentHighLight(doc.textDocument, position, source.token); - if (source == this.tokenSource) { - source.dispose(); - this.tokenSource = null; - } - if (source.token.isCancellationRequested) - return null; - return highlights; - } - cancel() { - if (this.tokenSource) { - this.tokenSource.cancel(); - this.tokenSource.dispose(); - this.tokenSource = null; - } - } - dispose() { - this.highlights.clear(); - this.cancel(); - disposeAll(this.disposables); - } - }; - } -}); - -// src/handler/hover.ts -function addDocument(docs, text, filetype, isPreview = false) { - let content = text.trim(); - if (!content.length) - return; - if (isPreview && filetype !== "markdown") { - content = "``` " + filetype + "\n" + content + "\n```"; - } - docs.push({ content, filetype }); -} -function isDocumentation(obj) { - if (!obj) - return false; - return typeof obj.filetype === "string" && typeof obj.content === "string"; -} -async function readLines(uri, start, end) { - let doc = workspace_default.getDocument(uri); - if (doc) - return doc.getLines(start, end + 1); - let fsPath = URI.parse(uri).fsPath; - if (!import_fs33.default.existsSync(fsPath)) - return []; - return await readFileLines(fsPath, start, end); -} -var import_fs33, import_vscode_languageserver_protocol91, logger98, HoverHandler; -var init_hover = __esm({ - "src/handler/hover.ts"() { - import_fs33 = __toModule(require("fs")); - import_vscode_languageserver_protocol91 = __toModule(require_main2()); - init_esm2(); - init_languages(); - init_floatFactory(); - init_util(); - init_fs(); - init_workspace(); - logger98 = require_logger2()("handler-hover"); - HoverHandler = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - this.disposables = []; - this.documentLines = []; - this.hasProvider = false; - this.excludeImages = true; - this.loadConfiguration(); - workspace_default.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables); - this.hoverFactory = new FloatFactory(nvim); - this.disposables.push(this.hoverFactory); - } - registerProvider() { - if (this.hasProvider) - return; - this.hasProvider = true; - let { nvim } = this; - let provider = { - onDidChange: null, - provideTextDocumentContent: async () => { - nvim.pauseNotification(); - nvim.command("setlocal conceallevel=2 nospell nofoldenable wrap", true); - nvim.command("setlocal bufhidden=wipe nobuflisted", true); - nvim.command("setfiletype markdown", true); - nvim.command(`if winnr('j') != winnr('k') | exe "normal! z${Math.min(this.documentLines.length, this.config.previewMaxHeight)}\\ | endif"`, true); - await nvim.resumeNotification(); - return this.documentLines.join("\n"); - } - }; - this.disposables.push(workspace_default.registerTextDocumentContentProvider("coc", provider)); - } - loadConfiguration(e) { - if (!e || e.affectsConfiguration("hover")) { - let config = workspace_default.getConfiguration("hover"); - let target = config.get("target", "float"); - this.config = { - floatConfig: config.get("floatConfig", {}), - autoHide: config.get("autoHide", true), - target: target == "float" && !workspace_default.floatSupported ? "preview" : target, - previewMaxHeight: config.get("previewMaxHeight", 12) - }; - if (this.config.target == "preview") { - this.registerProvider(); - } - let preferences = workspace_default.getConfiguration("coc.preferences"); - this.excludeImages = preferences.get("excludeImageLinksInMarkdownDocument", true); - } - } - async onHover(hoverTarget) { - let { doc, position, winid } = await this.handler.getCurrentState(); - if (hoverTarget == "preview") - this.registerProvider(); - this.handler.checkProvier("hover", doc.textDocument); - await doc.synchronize(); - let hovers = await this.handler.withRequestToken("hover", (token) => { - return languages_default.getHover(doc.textDocument, position, token); - }, true); - if (hovers == null || !hovers.length) - return false; - let hover = hovers.find((o) => import_vscode_languageserver_protocol91.Range.is(o.range)); - if (hover == null ? void 0 : hover.range) { - let win = this.nvim.createWindow(winid); - win.highlightRanges("CocHoverRange", [hover.range], 99, true); - this.timer = setTimeout(() => { - win.clearMatchGroup("CocHoverRange"); - if (workspace_default.isVim) - this.nvim.command("redraw", true); - }, 500); - } - await this.previewHover(hovers, hoverTarget); - return true; - } - async definitionHover(hoverTarget) { - const { doc, position } = await this.handler.getCurrentState(); - if (hoverTarget == "preview") - this.registerProvider(); - this.handler.checkProvier("hover", doc.textDocument); - await doc.synchronize(); - const hovers = await this.handler.withRequestToken("hover", (token) => { - return languages_default.getHover(doc.textDocument, position, token); - }, true); - if (!(hovers == null ? void 0 : hovers.length)) - return false; - const defs = await this.handler.withRequestToken("definitionHover", (token) => { - return languages_default.getDefinitionLinks(doc.textDocument, position, token); - }, false); - if (defs == null ? void 0 : defs.length) { - for (const def of defs) { - if (!def.targetRange) - continue; - const { start, end } = def.targetRange; - const endLine = end.line - start.line >= 100 ? start.line + 100 : end.character == 0 ? end.line - 1 : end.line; - let lines = await readLines(def.targetUri, start.line, endLine); - if (lines.length) { - let indent = lines[0].match(/^\s*/)[0]; - if (indent) - lines = lines.map((l) => l.startsWith(indent) ? l.substring(indent.length) : l); - hovers.push({ content: lines.join("\n"), filetype: doc.filetype }); - } - } - } - await this.previewHover(hovers, hoverTarget); - return true; - } - async previewHover(hovers, target) { - let docs = []; - target = target || this.config.target; - let isPreview = target === "preview"; - for (let hover of hovers) { - if (isDocumentation(hover)) { - docs.push(hover); - continue; - } - let { contents } = hover; - if (Array.isArray(contents)) { - for (let item of contents) { - if (typeof item === "string") { - addDocument(docs, item, "markdown", isPreview); - } else { - addDocument(docs, item.value, item.language, isPreview); - } - } - } else if (import_vscode_languageserver_protocol91.MarkedString.is(contents)) { - if (typeof contents == "string") { - addDocument(docs, contents, "markdown", isPreview); - } else { - addDocument(docs, contents.value, contents.language, isPreview); - } - } else if (import_vscode_languageserver_protocol91.MarkupContent.is(contents)) { - addDocument(docs, contents.value, isMarkdown(contents) ? "markdown" : "txt", isPreview); - } - } - if (target == "float") { - let config = this.hoverFactory.applyFloatConfig({ - modes: ["n"], - autoHide: this.config.autoHide, - excludeImages: this.excludeImages, - maxWidth: 80 - }, this.config.floatConfig); - await this.hoverFactory.show(docs, config); - return; - } - let lines = docs.reduce((p, c) => { - let arr = c.content.split(/\r?\n/); - if (p.length > 0) - p.push(""); - p.push(...arr); - return p; - }, []); - if (target == "echo") { - const msg = lines.join("\n").trim(); - await this.nvim.call("coc#util#echo_hover", [msg]); - } else { - this.documentLines = lines; - await this.nvim.command(`noswapfile pedit coc://document`); - } - } - async getHover() { - let result = []; - let { doc, position } = await this.handler.getCurrentState(); - this.handler.checkProvier("hover", doc.textDocument); - await doc.synchronize(); - let tokenSource = new import_vscode_languageserver_protocol91.CancellationTokenSource(); - let hovers = await languages_default.getHover(doc.textDocument, position, tokenSource.token); - if (Array.isArray(hovers)) { - for (let h of hovers) { - let { contents } = h; - if (Array.isArray(contents)) { - contents.forEach((c) => { - result.push(typeof c === "string" ? c : c.value); - }); - } else if (import_vscode_languageserver_protocol91.MarkupContent.is(contents)) { - result.push(contents.value); - } else { - result.push(typeof contents === "string" ? contents : contents.value); - } - } - } - result = result.filter((s) => s != null && s.length > 0); - return result; - } - dispose() { - if (this.timer) - clearTimeout(this.timer); - disposeAll(this.disposables); - } - }; - } -}); - -// src/handler/links.ts -var import_vscode_languageserver_protocol92, Links; -var init_links2 = __esm({ - "src/handler/links.ts"() { - import_vscode_languageserver_protocol92 = __toModule(require_main2()); - init_languages(); - init_position(); - init_workspace(); - Links = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - } - async getLinks() { - let { doc } = await this.handler.getCurrentState(); - this.handler.checkProvier("documentLink", doc.textDocument); - let links2 = await this.handler.withRequestToken("links", (token) => { - return languages_default.getDocumentLinks(doc.textDocument, token); - }); - return links2 || []; - } - async openLink(link) { - if (!link.target) { - link = await languages_default.resolveDocumentLink(link); - if (!link.target) - throw new Error(`Failed to resolve link target`); - } - await workspace_default.openResource(link.target); - } - async openCurrentLink() { - let [line, character] = await this.nvim.call("coc#cursor#position"); - let links2 = await this.getLinks(); - if (!links2 || links2.length == 0) - return false; - let position = import_vscode_languageserver_protocol92.Position.create(line, character); - for (let link of links2) { - if (positionInRange(position, link.range) == 0) { - await this.openLink(link); - return true; - } - } - return false; - } - }; - } -}); - -// src/handler/locations.ts -var import_vscode_languageserver_protocol93, logger99, LocationsHandler; -var init_locations = __esm({ - "src/handler/locations.ts"() { - import_vscode_languageserver_protocol93 = __toModule(require_main2()); - init_esm2(); - init_languages(); - init_services(); - init_workspace(); - logger99 = require_logger2()("handler-hover"); - LocationsHandler = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - } - async request(method, fn) { - let { doc, position } = await this.handler.getCurrentState(); - this.handler.checkProvier(method, doc.textDocument); - await doc.synchronize(); - return await this.handler.withRequestToken(method, (token) => { - return fn(doc.textDocument, position, token); - }, true); - } - async definitions() { - const { doc, position } = await this.handler.getCurrentState(); - this.handler.checkProvier("definition", doc.textDocument); - await doc.synchronize(); - const tokenSource = new import_vscode_languageserver_protocol93.CancellationTokenSource(); - return languages_default.getDefinition(doc.textDocument, position, tokenSource.token); - } - async declarations() { - const { doc, position } = await this.handler.getCurrentState(); - this.handler.checkProvier("declaration", doc.textDocument); - await doc.synchronize(); - const tokenSource = new import_vscode_languageserver_protocol93.CancellationTokenSource(); - return languages_default.getDeclaration(doc.textDocument, position, tokenSource.token); - } - async typeDefinitions() { - const { doc, position } = await this.handler.getCurrentState(); - this.handler.checkProvier("typeDefinition", doc.textDocument); - await doc.synchronize(); - const tokenSource = new import_vscode_languageserver_protocol93.CancellationTokenSource(); - return languages_default.getTypeDefinition(doc.textDocument, position, tokenSource.token); - } - async implementations() { - const { doc, position } = await this.handler.getCurrentState(); - this.handler.checkProvier("implementation", doc.textDocument); - await doc.synchronize(); - const tokenSource = new import_vscode_languageserver_protocol93.CancellationTokenSource(); - return languages_default.getImplementation(doc.textDocument, position, tokenSource.token); - } - async references() { - const { doc, position } = await this.handler.getCurrentState(); - this.handler.checkProvier("reference", doc.textDocument); - await doc.synchronize(); - const tokenSource = new import_vscode_languageserver_protocol93.CancellationTokenSource(); - return languages_default.getReferences(doc.textDocument, { includeDeclaration: true }, position, tokenSource.token); - } - async gotoDefinition(openCommand) { - let definition = await this.request("definition", (doc, position, token) => { - return languages_default.getDefinition(doc, position, token); - }); - await this.handleLocations(definition, openCommand); - return definition ? definition.length > 0 : false; - } - async gotoDeclaration(openCommand) { - let definition = await this.request("declaration", (doc, position, token) => { - return languages_default.getDeclaration(doc, position, token); - }); - await this.handleLocations(definition, openCommand); - return definition ? Array.isArray(definition) ? definition.length > 0 : true : false; - } - async gotoTypeDefinition(openCommand) { - let definition = await this.request("typeDefinition", (doc, position, token) => { - return languages_default.getTypeDefinition(doc, position, token); - }); - await this.handleLocations(definition, openCommand); - return definition ? definition.length > 0 : false; - } - async gotoImplementation(openCommand) { - let definition = await this.request("implementation", (doc, position, token) => { - return languages_default.getImplementation(doc, position, token); - }); - await this.handleLocations(definition, openCommand); - return definition ? definition.length > 0 : false; - } - async gotoReferences(openCommand, includeDeclaration = true) { - let definition = await this.request("reference", (doc, position, token) => { - return languages_default.getReferences(doc, { includeDeclaration }, position, token); - }); - await this.handleLocations(definition, openCommand); - return definition ? definition.length > 0 : false; - } - async getTagList() { - let { doc, position } = await this.handler.getCurrentState(); - let word = await this.nvim.call("expand", ""); - if (!word) - return null; - if (!languages_default.hasProvider("definition", doc.textDocument)) - return null; - let tokenSource = new import_vscode_languageserver_protocol93.CancellationTokenSource(); - let definitions = await languages_default.getDefinition(doc.textDocument, position, tokenSource.token); - if (!definitions || !definitions.length) - return null; - return definitions.map((location) => { - let parsedURI = URI.parse(location.uri); - const filename = parsedURI.scheme == "file" ? parsedURI.fsPath : parsedURI.toString(); - return { - name: word, - cmd: `keepjumps ${location.range.start.line + 1} | normal ${location.range.start.character + 1}|`, - filename - }; - }); - } - async findLocations(id, method, params, openCommand) { - let { doc, position } = await this.handler.getCurrentState(); - params = params || {}; - Object.assign(params, { - textDocument: { uri: doc.uri }, - position - }); - let res = await services_default.sendRequest(id, method, params); - res = res || []; - let locations = []; - if (Array.isArray(res)) { - locations = res; - } else if (res.hasOwnProperty("location") && res.hasOwnProperty("children")) { - let getLocation2 = (item) => { - locations.push(item.location); - if (item.children && item.children.length) { - for (let loc of item.children) { - getLocation2(loc); - } - } - }; - getLocation2(res); - } - await this.handleLocations(locations, openCommand); - } - async handleLocations(definition, openCommand) { - if (!definition) - return; - let locations = Array.isArray(definition) ? definition : [definition]; - locations = locations.map((o) => import_vscode_languageserver_protocol93.LocationLink.is(o) ? import_vscode_languageserver_protocol93.Location.create(o.targetUri, o.targetRange) : o); - let len = locations.length; - if (len == 0) - return; - if (len == 1 && openCommand !== false) { - let { uri, range } = locations[0]; - await workspace_default.jumpTo(uri, range.start, openCommand); - } else { - await workspace_default.showLocations(locations); - } - } - dispose() { - } - }; - } -}); - -// src/handler/search.ts -function getPathFromArgs(args) { - if (args.length < 2) - return void 0; - let len = args.length; - if (args[len - 1].startsWith("-")) - return void 0; - if (args[len - 2].startsWith("-")) - return void 0; - return args[len - 1]; -} -var import_child_process6, import_events36, import_path34, import_readline5, logger100, defaultArgs, controlCode2, Task2, Search; -var init_search = __esm({ - "src/handler/search.ts"() { - init_mutex(); - import_child_process6 = __toModule(require("child_process")); - import_events36 = __toModule(require("events")); - import_path34 = __toModule(require("path")); - import_readline5 = __toModule(require("readline")); - init_main(); - init_highligher(); - init_ansiparse(); - init_window(); - logger100 = require_logger2()("handler-search"); - defaultArgs = ["--color", "ansi", "--colors", "path:fg:black", "--colors", "line:fg:green", "--colors", "match:fg:red", "--no-messages", "--heading", "-n"]; - controlCode2 = ""; - Task2 = class extends import_events36.EventEmitter { - start(cmd, args, cwd) { - this.process = (0, import_child_process6.spawn)(cmd, args, { cwd }); - this.process.on("error", (e) => { - this.emit("error", e.message); - }); - const rl = import_readline5.default.createInterface(this.process.stdout); - let start; - let fileItem; - let lines = []; - let highlights = []; - let create = true; - rl.on("line", (content) => { - if (content.includes(controlCode2)) { - let items = ansiparse(content); - if (items[0].foreground == "black") { - fileItem = { filepath: import_path34.default.join(cwd, items[0].text), ranges: [] }; - return; - } - let normalLine = items[0].foreground == "green"; - if (normalLine) { - let lnum = parseInt(items[0].text, 10) - 1; - let padlen2 = items[0].text.length + 1; - if (create) { - start = lnum; - create = false; - } - let line = ""; - for (let item of items) { - if (item.foreground == "red") { - let l = lnum - start; - let c = line.length - padlen2; - highlights.push(Range.create(l, c, l, c + item.text.length)); - } - line += item.text; - } - let currline = line.slice(padlen2); - lines.push(currline); - } - } else { - let fileEnd = content.trim().length == 0; - if (fileItem && (fileEnd || content.trim() == "--")) { - let fileRange = { - lines, - highlights, - start, - end: start + lines.length - }; - fileItem.ranges.push(fileRange); - } - if (fileEnd) { - this.emit("item", fileItem); - fileItem = null; - } - lines = []; - highlights = []; - create = true; - } - }); - rl.on("close", () => { - if (fileItem) { - if (lines.length) { - let fileRange = { - lines, - highlights, - start, - end: start + lines.length - }; - fileItem.ranges.push(fileRange); - } - this.emit("item", fileItem); - } - lines = highlights = fileItem = null; - this.emit("end"); - }); - } - dispose() { - if (this.process) { - this.process.kill(); - } - } - }; - Search = class { - constructor(nvim, cmd = "rg") { - this.nvim = nvim; - this.cmd = cmd; - } - run(args, cwd, refactorBuf) { - let { nvim, cmd } = this; - let { afterContext, beforeContext } = refactorBuf.config; - let argList = ["-A", afterContext.toString(), "-B", beforeContext.toString()].concat(defaultArgs, args); - let p = getPathFromArgs(args); - if (p) - argList.pop(); - argList.push("--", p ? import_path34.default.isAbsolute(p) ? p : `./${p.replace(/^\.\//, "")}` : "./"); - this.task = new Task2(); - this.task.start(cmd, argList, cwd); - let mutex = new Mutex(); - let files = 0; - let matches = 0; - let start = Date.now(); - let fileItems = []; - const addFileItems = async () => { - if (fileItems.length == 0) - return; - let items = fileItems.slice(); - fileItems = []; - const release = await mutex.acquire(); - try { - await refactorBuf.addFileItems(items); - } catch (e) { - logger100.error(e); - } - release(); - }; - return new Promise((resolve3, reject) => { - let interval = setInterval(addFileItems, 300); - this.task.on("item", async (fileItem) => { - files++; - matches = matches + fileItem.ranges.reduce((p2, r) => p2 + r.highlights.length, 0); - fileItems.push(fileItem); - }); - this.task.on("error", (message) => { - clearInterval(interval); - window_default.showMessage(`Error on command "${cmd}": ${message}`, "error"); - this.task = null; - reject(new Error(message)); - }); - this.task.on("end", async () => { - clearInterval(interval); - try { - await addFileItems(); - const release = await mutex.acquire(); - release(); - this.task.removeAllListeners(); - this.task = null; - let buf = refactorBuf.buffer; - if (buf) { - nvim.pauseNotification(); - if (files == 0) { - buf.setLines(["No match found"], { start: 1, end: 2, strictIndexing: false }, true); - buf.addHighlight({ line: 1, srcId: -1, colEnd: -1, colStart: 0, hlGroup: "Error" }).logError(); - buf.setOption("modified", false, true); - } else { - let highligher = new Highlighter(); - highligher.addText("Files", "MoreMsg"); - highligher.addText(": "); - highligher.addText(`${files} `, "Number"); - highligher.addText("Matches", "MoreMsg"); - highligher.addText(": "); - highligher.addText(`${matches} `, "Number"); - highligher.addText("Duration", "MoreMsg"); - highligher.addText(": "); - highligher.addText(`${Date.now() - start}ms`, "Number"); - highligher.render(buf, 1, 2); - } - buf.setOption("modified", false, true); - await nvim.resumeNotification(false, true); - } - } catch (e) { - reject(e); - return; - } - resolve3(); - }); - }); - } - abort() { - var _a2; - (_a2 = this.task) == null ? void 0 : _a2.dispose(); - } - }; - } -}); - -// src/handler/refactor/buffer.ts -function adjustRange(range, offset) { - let { start, end } = range; - return import_vscode_languageserver_protocol94.Range.create(start.line - offset, start.character, end.line - offset, end.character); -} -var import_fast_diff5, import_path35, import_vscode_languageserver_protocol94, logger101, SEPARATOR, RefactorBuffer; -var init_buffer4 = __esm({ - "src/handler/refactor/buffer.ts"() { - import_fast_diff5 = __toModule(require_diff()); - import_path35 = __toModule(require("path")); - import_vscode_languageserver_protocol94 = __toModule(require_main2()); - init_main2(); - init_esm2(); - init_commands2(); - init_highligher(); - init_util(); - init_fs(); - init_mutex(); - init_object(); - init_string(); - init_window(); - init_workspace(); - logger101 = require_logger2()("handler-refactorBuffer"); - SEPARATOR = "\u3000"; - RefactorBuffer = class { - constructor(bufnr, srcId, nvim, config, opts) { - this.bufnr = bufnr; - this.srcId = srcId; - this.nvim = nvim; - this.config = config; - this.opts = opts; - this.mutex = new Mutex(); - this._disposed = false; - this.disposables = []; - this._fileItems = []; - this.matchIds = new Set(); - this.changing = false; - this.disposables.push(workspace_default.registerLocalKeymap("n", "", this.splitOpen.bind(this), true)); - workspace_default.onDidChangeTextDocument(this.onDocumentChange, this, this.disposables); - } - get fileItems() { - return this._fileItems; - } - onChange(e) { - if (this.changing) - return; - let doc = this.document; - let { nvim, _fileItems: fileItems } = this; - if (!fileItems.length) - return; - let change = e.contentChanges[0]; - if (!("range" in change)) - return; - let { original } = e; - if (change.range.end.line < 2) - return; - doc.buffer.setOption("modified", true, true); - let { range, text } = change; - let lines = text.split("\n"); - let lineChange = lines.length - (range.end.line - range.start.line) - 1; - if (lineChange == 0) - return; - let lineChanges = []; - if (text.includes("\u3000")) { - let startLine = range.start.line; - let diffs = (0, import_fast_diff5.default)(original, text); - let offset = 0; - let orig = TextDocument2.create("file:///1", "", 0, original); - for (let i = 0; i < diffs.length; i++) { - let diff = diffs[i]; - let pos = orig.positionAt(offset); - if (diff[0] == import_fast_diff5.default.EQUAL) { - offset = offset + diff[1].length; - } else if (diff[0] == import_fast_diff5.default.DELETE) { - let end = orig.positionAt(offset + diff[1].length); - if (diffs[i + 1] && diffs[i + 1][0] == import_fast_diff5.default.INSERT) { - let delta = diffs[i + 1][1].split("\n").length - (end.line - pos.line) - 1; - if (delta != 0) - lineChanges.push({ delta, lnum: pos.line + startLine }); - i = i + 1; - } else { - let delta = -(end.line - pos.line); - if (delta != 0) - lineChanges.push({ delta, lnum: pos.line + startLine }); - } - offset = offset + diff[1].length; - } else if (diff[0] == import_fast_diff5.default.INSERT) { - let delta = diff[1].split("\n").length - 1; - if (delta != 0) - lineChanges.push({ delta, lnum: pos.line + startLine }); - } - } - } else { - lineChanges = [{ delta: lineChange, lnum: range.start.line }]; - } - let changed = false; - for (let item of fileItems) { - for (let range2 of item.ranges) { - let arr = lineChanges.filter((o) => o.lnum < range2.lnum - 1); - if (arr.length) { - let total = arr.reduce((p, c) => p + c.delta, 0); - range2.lnum = range2.lnum + total; - changed = true; - } - } - } - if (!changed) - return; - nvim.pauseNotification(); - this.highlightLineNr(); - nvim.resumeNotification().then((res) => { - if (Array.isArray(res) && res[1] != null) { - logger101.error(`Error on highlightLineNr:`, res[1]); - } - }).logError(); - } - async onDocumentChange(e) { - if (e.bufnr == this.bufnr || this.changing) - return; - let { uri } = e.textDocument; - let { range, text } = e.contentChanges[0]; - let filepath = URI.parse(uri).fsPath; - let fileItem = this._fileItems.find((o) => o.filepath == filepath); - if (!fileItem) - return; - let lineChange = text.split("\n").length - (range.end.line - range.start.line) - 1; - let edits = []; - for (let i = 0; i < fileItem.ranges.length; i++) { - let r = fileItem.ranges[i]; - if (range.start.line >= r.end) { - continue; - } - if (range.end.line < r.start) { - if (lineChange == 0) { - continue; - } else { - r.start = r.start + lineChange; - r.end = r.end + lineChange; - } - } else { - let doc = workspace_default.getDocument(uri); - let newLines = doc.getLines(r.start, r.end); - if (!newLines.length) { - fileItem.ranges.splice(i, 1); - edits.push({ - range: this.getFileRangeRange(r, false), - newText: "" - }); - } else { - r.end = r.start + newLines.length; - edits.push({ - range: this.getFileRangeRange(r, true), - newText: newLines.join("\n") + "\n" - }); - } - } - } - this._fileItems = this._fileItems.filter((o) => o.ranges && o.ranges.length > 0); - if (edits.length) { - this.changing = true; - await this.document.applyEdits(edits); - this.changing = false; - } - this.nvim.pauseNotification(); - this.highlightLineNr(); - this.buffer.setOption("modified", false, true); - await this.nvim.resumeNotification(); - } - async getFileChanges() { - if (this._disposed) - return []; - let changes = []; - let lines = await this.buffer.lines; - lines.push(SEPARATOR); - let arr = []; - let fsPath; - let lnum; - for (let i = 0; i < lines.length; i++) { - let line = lines[i]; - if (line.startsWith(SEPARATOR)) { - if (fsPath) { - changes.push({ - filepath: fsPath, - lines: arr.slice(), - lnum - }); - fsPath = void 0; - arr = []; - } - if (line.length > 1) { - let ms = line.match(/^\u3000(.*)/); - if (ms) { - fsPath = this.getAbsolutePath(ms[1].replace(/\s+$/, "")); - lnum = i + 1; - arr = []; - } - } - } else { - arr.push(line); - } - } - return changes; - } - async splitOpen() { - let { nvim } = this; - let win = nvim.createWindow(this.opts.fromWinid); - let valid = await win.valid; - let lines = await nvim.eval('getline(1,line("."))'); - let len = lines.length; - for (let i = 0; i < len; i++) { - let line = lines[len - i - 1]; - let ms = line.match(/^\u3000(.+)/); - if (ms) { - let filepath = ms[1].trim(); - let r = this.getLinesRange(len - i); - if (!r) - return; - let lnum = r[0] + i - 1; - let bufname = this.getAbsolutePath(filepath); - nvim.pauseNotification(); - if (valid) { - nvim.call("win_gotoid", [this.opts.fromWinid], true); - this.nvim.call("coc#util#jump", ["edit", bufname, [lnum, 1]], true); - } else { - this.nvim.call("coc#util#jump", ["belowright vs", bufname, [lnum, 1]], true); - } - nvim.command("normal! zz", true); - let [, err] = await nvim.resumeNotification(); - if (err) - window_default.showMessage(`Error on open ${filepath}: ${err}`, "error"); - if (!valid) { - this.opts.fromWinid = await nvim.call("win_getid"); - } - break; - } - } - } - async addFileItems(items) { - if (this._disposed) - return; - let { cwd } = this.opts; - let { document: document2 } = this; - const release = await this.mutex.acquire(); - try { - await document2.synchronize(); - for (let item of items) { - let fileItem = this._fileItems.find((o) => o.filepath == item.filepath); - if (fileItem) { - fileItem.ranges.push(...item.ranges); - } else { - this._fileItems.push(item); - } - } - let count = document2.lineCount; - let highligher = new Highlighter(); - let hlRanges = []; - for (let item of items) { - for (let range of item.ranges) { - highligher.addLine(SEPARATOR); - highligher.addLine(SEPARATOR); - range.lnum = count + highligher.length; - highligher.addText(`${isParentFolder(cwd, item.filepath) ? import_path35.default.relative(cwd, item.filepath) : item.filepath}`); - let n = String(range.start + 1).length + String(range.end).length + 4; - if (!this.srcId) - highligher.addText(" ".repeat(n)); - let base = 0 - highligher.length - count; - if (range.highlights) { - hlRanges.push(...range.highlights.map((r) => adjustRange(r, base))); - } - let { lines } = range; - if (!lines) { - lines = await this.getLines(item.filepath, range.start, range.end); - range.lines = lines; - } - highligher.addLines(lines); - } - } - let { nvim, buffer } = this; - this.changing = true; - nvim.pauseNotification(); - highligher.render(buffer, count); - this.highlightLineNr(); - buffer.setOption("modified", false, true); - buffer.setOption("undolevels", 1e3, true); - if (count == 2 && hlRanges.length) { - let pos = hlRanges[0].start; - nvim.call("coc#cursor#move_to", [pos.line, pos.character], true); - } - if (workspace_default.isVim) { - nvim.command("redraw", true); - } - let [, err] = await nvim.resumeNotification(); - if (err) - throw new Error(err[2]); - await document2.patchChange(); - this.changing = false; - await commands_default.executeCommand("editor.action.addRanges", hlRanges); - } catch (e) { - this.changing = false; - logger101.error(`Error on add file item:`, e); - } - release(); - } - async save() { - let { nvim } = this; - let doc = this.document; - let { buffer } = doc; - await doc.patchChange(); - let changes = await this.getFileChanges(); - if (!changes) - return; - changes.sort((a, b) => a.lnum - b.lnum); - let removeList = []; - let deltaMap = new Map(); - for (let i = 0; i < changes.length; i++) { - let change = changes[i]; - let { filepath, lnum } = change; - let curr = deltaMap.get(filepath) || 0; - let item = this._fileItems.find((o) => o.filepath == filepath); - let range = item ? item.ranges.find((o) => o.lnum == lnum) : null; - if (!range || equals(range.lines, change.lines)) { - removeList.push(i); - if (curr && range) { - range.start = range.start + curr; - range.end = range.end + curr; - } - continue; - } - change.start = range.start; - change.end = range.end; - if (curr != 0) - range.start = range.start + curr; - if (change.lines.length != range.lines.length) { - let delta = change.lines.length - range.lines.length; - let total = delta + curr; - deltaMap.set(filepath, total); - range.end = range.end + total; - } else { - range.end = range.end + curr; - } - range.lines = change.lines; - } - if (removeList.length) - changes = changes.filter((_, i) => !removeList.includes(i)); - if (changes.length == 0) { - window_default.showMessage("No change.", "more"); - await buffer.setOption("modified", false); - return false; - } - let changeMap = {}; - for (let change of changes) { - let uri = URI.file(change.filepath).toString(); - let edits = changeMap[uri] || []; - edits.push({ - range: import_vscode_languageserver_protocol94.Range.create(change.start, 0, change.end, 0), - newText: change.lines.join("\n") + "\n" - }); - changeMap[uri] = edits; - } - this.changing = true; - await workspace_default.applyEdit({ changes: changeMap }); - this.changing = false; - nvim.pauseNotification(); - buffer.setOption("modified", false, true); - if (this.config.saveToFile) { - nvim.command("silent noa wa", true); - } - this.highlightLineNr(); - await nvim.resumeNotification(); - return true; - } - getFileRange(lnum) { - for (let item of this._fileItems) { - for (let r of item.ranges) { - if (r.lnum == lnum) { - return r; - } - } - } - } - getLinesRange(lnum) { - for (let item of this._fileItems) { - for (let range of item.ranges) { - if (range.lnum == lnum) { - return [range.start, range.end]; - } - } - } - } - async getLines(fsPath, start, end) { - let uri = URI.file(fsPath).toString(); - let doc = workspace_default.getDocument(uri); - if (doc) - return doc.getLines(start, end); - return await readFileLines(fsPath, start, end - 1); - } - getAbsolutePath(filepath) { - if (import_path35.default.isAbsolute(filepath)) - return filepath; - return import_path35.default.join(this.opts.cwd, filepath); - } - getFileRangeRange(range, lineOnly = true) { - let { document: document2 } = this; - if (!document2) - return null; - let { lnum } = range; - let first = document2.getline(lnum - 1); - if (!first.startsWith("\u3000")) - return null; - let start = lineOnly ? lnum : lnum - 1; - let end = document2.lineCount; - for (let i = lnum; i < document2.lineCount; i++) { - let line = document2.getline(i); - if (line.startsWith("\u3000")) { - end = lineOnly ? i : i + 1; - break; - } - } - return import_vscode_languageserver_protocol94.Range.create(start, 0, end, 0); - } - highlightLineNr() { - let { _fileItems: fileItems, nvim, srcId, bufnr } = this; - let { winid, cwd } = this.opts; - let info = {}; - if (srcId) { - nvim.call("nvim_buf_clear_namespace", [bufnr, srcId, 0, -1], true); - for (let item of fileItems) { - for (let range of item.ranges) { - let text = `${range.start + 1}:${range.end}`; - info[range.lnum] = [range.start + 1, range.end]; - nvim.call("nvim_buf_set_virtual_text", [bufnr, srcId, range.lnum - 1, [[text, "LineNr"]], {}], true); - } - } - } else { - if (this.matchIds.size) { - nvim.call("coc#highlight#clear_matches", [winid, Array.from(this.matchIds)], true); - this.matchIds.clear(); - } - let id = 2e3; - for (let item of fileItems) { - let filename = `${cwd ? import_path35.default.relative(cwd, item.filepath) : item.filepath}`; - let col = byteLength(filename) + 1; - for (let range of item.ranges) { - let text = `:${range.start + 1}:${range.end}`; - for (let i = 0; i < text.length; i++) { - let ch = text[i]; - this.matchIds.add(id); - info[range.lnum] = [range.start + 1, range.end]; - nvim.call("matchaddpos", ["Conceal", [[range.lnum, col + i]], 99, id, { conceal: ch, window: winid }], true); - id++; - } - } - } - } - this.buffer.setVar("line_infos", info, true); - } - get valid() { - return this.buffer.valid; - } - get buffer() { - return this.nvim.createBuffer(this.bufnr); - } - get document() { - if (this._disposed) - return null; - return workspace_default.getDocument(this.bufnr); - } - dispose() { - this._disposed = true; - disposeAll(this.disposables); - } - }; - } -}); - -// src/handler/refactor/index.ts -function adjustRange2(range, offset) { - let { start, end } = range; - return import_vscode_languageserver_protocol95.Range.create(start.line - offset, start.character, end.line - offset, end.character); -} -function emptyWorkspaceEdit(edit2) { - let { changes, documentChanges } = edit2; - if (documentChanges && documentChanges.length) - return false; - if (changes && Object.keys(changes).length) - return false; - return true; -} -var import_vscode_languageserver_protocol95, logger102, name, refactorId, Refactor; -var init_refactor = __esm({ - "src/handler/refactor/index.ts"() { - import_vscode_languageserver_protocol95 = __toModule(require_main2()); - init_esm2(); - init_languages(); - init_util(); - init_fs(); - init_workspace(); - init_search(); - init_buffer4(); - logger102 = require_logger2()("handler-refactor"); - name = "__coc_refactor__"; - refactorId = 0; - Refactor = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - this.buffers = new Map(); - this.disposables = []; - this._onCreate = new import_vscode_languageserver_protocol95.Emitter(); - this.onCreate = this._onCreate.event; - if (workspace_default.isNvim && this.nvim.hasFunction("nvim_buf_set_virtual_text")) { - this.srcId = workspace_default.createNameSpace("coc-refactor"); - } - this.setConfiguration(); - workspace_default.onDidChangeConfiguration(this.setConfiguration, this, this.disposables); - workspace_default.onDidCloseTextDocument((e) => { - let buf = this.buffers.get(e.bufnr); - if (buf) { - buf.dispose(); - this.buffers.delete(e.bufnr); - } - }, null, this.disposables); - workspace_default.onDidChangeTextDocument((e) => { - let buf = this.buffers.get(e.bufnr); - if (buf) - buf.onChange(e); - }, null, this.disposables); - } - setConfiguration(e) { - if (e && !e.affectsConfiguration("refactor")) - return; - let config = workspace_default.getConfiguration("refactor"); - this.config = Object.assign(this.config || {}, { - afterContext: config.get("afterContext", 3), - beforeContext: config.get("beforeContext", 3), - openCommand: config.get("openCommand", "edit"), - saveToFile: config.get("saveToFile", true) - }); - } - async doRefactor() { - let { doc, position } = await this.handler.getCurrentState(); - if (!languages_default.hasProvider("rename", doc.textDocument)) { - throw new Error(`Rename provider not found for current buffer`); - } - await doc.synchronize(); - let edit2 = await this.handler.withRequestToken("refactor", async (token) => { - let res = await languages_default.prepareRename(doc.textDocument, position, token); - if (token.isCancellationRequested) - return null; - if (res === false) - throw new Error(`Provider returns null on prepare, unable to rename at current position`); - let edit3 = await languages_default.provideRenameEdits(doc.textDocument, position, "NewName", token); - if (token.isCancellationRequested) - return null; - if (!edit3) - throw new Error("Provider returns null for rename edits."); - return edit3; - }); - if (edit2) { - await this.fromWorkspaceEdit(edit2, doc.filetype); - } - } - async search(args) { - let buf = await this.createRefactorBuffer(); - if (!buf) - return; - let cwd = await this.nvim.call("getcwd", []); - let search = new Search(this.nvim); - await search.run(args, cwd, buf); - } - async save(bufnr) { - let buf = this.buffers.get(bufnr); - if (buf) - return await buf.save(); - } - getBuffer(bufnr) { - return this.buffers.get(bufnr); - } - async createRefactorBuffer(filetype) { - let { nvim } = this; - let [fromWinid, cwd] = await nvim.eval("[win_getid(),getcwd()]"); - let { openCommand } = this.config; - nvim.pauseNotification(); - nvim.command(`${openCommand} ${name}${refactorId++}`, true); - nvim.command(`setl buftype=acwrite nobuflisted bufhidden=wipe nofen wrap conceallevel=2 concealcursor=n`, true); - nvim.command(`setl undolevels=-1 nolist nospell noswapfile foldmethod=expr foldexpr=coc#util#refactor_foldlevel(v:lnum)`, true); - nvim.command(`setl foldtext=coc#util#refactor_fold_text(v:foldstart)`, true); - nvim.call("setline", [1, ["Save current buffer to make changes", SEPARATOR]], true); - nvim.call("matchadd", ["Comment", "\\%1l"], true); - nvim.call("matchadd", ["Conceal", "^\\%u3000"], true); - nvim.call("matchadd", ["Label", "^\\%u3000\\zs\\S\\+"], true); - nvim.command("setl nomod", true); - if (filetype) - nvim.command(`runtime! syntax/${filetype}.vim`, true); - nvim.call("coc#util#do_autocmd", ["CocRefactorOpen"], true); - let [, err] = await nvim.resumeNotification(); - if (err) - return; - let [bufnr, win] = await nvim.eval('[bufnr("%"),win_getid()]'); - let opts = { fromWinid, winid: win, cwd }; - await workspace_default.document; - let buf = new RefactorBuffer(bufnr, this.srcId, this.nvim, this.config, opts); - this.buffers.set(bufnr, buf); - return buf; - } - async fromLines(lines) { - let buf = await this.createRefactorBuffer(); - if (buf) - await buf.buffer.setLines(lines, { start: 0, end: -1, strictIndexing: false }); - return buf; - } - async fromLocations(locations, filetype) { - if (!locations || locations.length == 0) - return null; - let changes = {}; - let edit2 = { changes }; - for (let location of locations) { - let edits = changes[location.uri] || []; - edits.push({ range: location.range, newText: "" }); - changes[location.uri] = edits; - } - return await this.fromWorkspaceEdit(edit2, filetype); - } - async fromWorkspaceEdit(edit2, filetype) { - if (!edit2 || emptyWorkspaceEdit(edit2)) - return void 0; - let items = []; - let { beforeContext, afterContext } = this.config; - let { changes, documentChanges } = edit2; - if (!changes) { - changes = {}; - for (let change of documentChanges || []) { - if (import_vscode_languageserver_protocol95.TextDocumentEdit.is(change)) { - let { textDocument, edits } = change; - if (textDocument.uri.startsWith("file:")) { - changes[textDocument.uri] = edits; - } - } - } - } - for (let key of Object.keys(changes)) { - let max = await this.getLineCount(key); - let edits = changes[key]; - let ranges = []; - let start = null; - let end = null; - let highlights = []; - edits.sort((a, b) => a.range.start.line - b.range.start.line); - for (let edit3 of edits) { - let { line } = edit3.range.start; - let s = Math.max(0, line - beforeContext); - if (start != null && s < end) { - end = Math.min(max, line + afterContext + 1); - highlights.push(adjustRange2(edit3.range, start)); - } else { - if (start != null) - ranges.push({ start, end, highlights }); - start = s; - end = Math.min(max, line + afterContext + 1); - highlights = [adjustRange2(edit3.range, start)]; - } - } - if (start != null) - ranges.push({ start, end, highlights }); - items.push({ - ranges, - filepath: URI.parse(key).fsPath - }); - } - let buf = await this.createRefactorBuffer(filetype); - await buf.addFileItems(items); - return buf; - } - async getLineCount(uri) { - let doc = workspace_default.getDocument(uri); - if (doc) - return doc.lineCount; - return await getFileLineCount(URI.parse(uri).fsPath); - } - reset() { - if (this.timer) { - clearTimeout(this.timer); - } - for (let buf of this.buffers.values()) { - buf.dispose(); - } - this.buffers.clear(); - } - dispose() { - if (this.timer) { - clearTimeout(this.timer); - } - this._onCreate.dispose(); - for (let buf of this.buffers.values()) { - buf.dispose(); - } - this.buffers.clear(); - disposeAll(this.disposables); - } - }; - } -}); - -// src/handler/rename.ts -var import_vscode_languageserver_protocol96, logger103, Rename; -var init_rename = __esm({ - "src/handler/rename.ts"() { - import_vscode_languageserver_protocol96 = __toModule(require_main2()); - init_languages(); - init_position(); - init_window(); - init_workspace(); - logger103 = require_logger2()("handler-rename"); - Rename = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - } - async getWordEdit() { - let { doc, position } = await this.handler.getCurrentState(); - let range = doc.getWordRangeAtPosition(position); - if (!range || emptyRange(range)) - return null; - let curname = doc.textDocument.getText(range); - if (languages_default.hasProvider("rename", doc.textDocument)) { - await doc.synchronize(); - let requestTokenSource = new import_vscode_languageserver_protocol96.CancellationTokenSource(); - let res = await languages_default.prepareRename(doc.textDocument, position, requestTokenSource.token); - if (res === false) - return null; - let edit2 = await languages_default.provideRenameEdits(doc.textDocument, position, curname, requestTokenSource.token); - if (edit2) - return edit2; - } - window_default.showMessage("Rename provider not found, extract word ranges from current buffer", "more"); - let ranges = doc.getSymbolRanges(curname); - return { - changes: { - [doc.uri]: ranges.map((r) => ({ range: r, newText: curname })) - } - }; - } - async rename(newName) { - let { doc, position } = await this.handler.getCurrentState(); - this.handler.checkProvier("rename", doc.textDocument); - await doc.synchronize(); - let token = new import_vscode_languageserver_protocol96.CancellationTokenSource().token; - let res = await languages_default.prepareRename(doc.textDocument, position, token); - if (res === false) { - window_default.showMessage("Invalid position for rename", "warning"); - return false; - } - let curname; - if (!newName) { - if (import_vscode_languageserver_protocol96.Range.is(res)) { - curname = doc.textDocument.getText(res); - await window_default.moveTo(res.start); - } else if (res && typeof res.placeholder === "string") { - curname = res.placeholder; - } else { - curname = await this.nvim.eval('expand("")'); - } - newName = await window_default.requestInput("New name", curname); - } - if (!newName) - return false; - let edit2 = await languages_default.provideRenameEdits(doc.textDocument, position, newName, token); - if (token.isCancellationRequested || !edit2) - return false; - await workspace_default.applyEdit(edit2); - if (workspace_default.isVim) - this.nvim.command("redraw", true); - return true; - } - }; - } -}); - -// src/handler/selectionRange.ts -var import_vscode_languageserver_protocol97, SelectionRangeHandler; -var init_selectionRange2 = __esm({ - "src/handler/selectionRange.ts"() { - import_vscode_languageserver_protocol97 = __toModule(require_main2()); - init_languages(); - init_object(); - init_position(); - init_window(); - init_workspace(); - SelectionRangeHandler = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - this.selectionRange = null; - } - async getSelectionRanges() { - let { doc, position } = await this.handler.getCurrentState(); - this.handler.checkProvier("selectionRange", doc.textDocument); - await doc.synchronize(); - let selectionRanges = await this.handler.withRequestToken("selection ranges", (token) => { - return languages_default.getSelectionRanges(doc.textDocument, [position], token); - }); - return selectionRanges; - } - async selectRange(visualmode, forward) { - let { nvim } = this; - let { doc } = await this.handler.getCurrentState(); - this.handler.checkProvier("selectionRange", doc.textDocument); - let positions2 = []; - if (!forward && (!this.selectionRange || !visualmode)) - return; - if (visualmode) { - let range = await workspace_default.getSelectedRange(visualmode, doc); - positions2.push(range.start, range.end); - } else { - let position = await window_default.getCursorPosition(); - positions2.push(position); - } - if (!forward) { - let curr = import_vscode_languageserver_protocol97.Range.create(positions2[0], positions2[1]); - let { selectionRange: selectionRange2 } = this; - while (selectionRange2 && selectionRange2.parent) { - if (equals(selectionRange2.parent.range, curr)) { - break; - } - selectionRange2 = selectionRange2.parent; - } - if (selectionRange2 && selectionRange2.parent) { - await workspace_default.selectRange(selectionRange2.range); - } - return; - } - await doc.synchronize(); - let selectionRanges = await this.handler.withRequestToken("selection ranges", (token) => { - return languages_default.getSelectionRanges(doc.textDocument, positions2, token); - }); - if (!selectionRanges || selectionRanges.length == 0) - return; - let mode = await nvim.eval("mode()"); - if (mode != "n") - await nvim.eval(`feedkeys("\\", 'in')`); - let selectionRange; - if (selectionRanges.length == 1) { - selectionRange = selectionRanges[0]; - } else { - let end = positions2[1] || positions2[0]; - let r = import_vscode_languageserver_protocol97.Range.create(positions2[0], end); - selectionRange = selectionRanges[0]; - while (selectionRange) { - if (equals(r, selectionRange.range)) { - selectionRange = selectionRange.parent; - continue; - } - if (positionInRange(positions2[0], selectionRange.range) == 0 && positionInRange(end, selectionRange.range) == 0) { - break; - } - selectionRange = selectionRange.parent; - } - } - if (!selectionRange) - return; - this.selectionRange = selectionRanges[0]; - await workspace_default.selectRange(selectionRange.range); - } - }; - } -}); - -// src/handler/callHierarchy.ts -function isCallHierarchyItem(item) { - if (item && item.name && item.kind && import_vscode_languageserver_protocol98.Range.is(item.range) && item.uri) - return true; - return false; -} -var import_path36, import_vscode_languageserver_protocol98, logger104, _CallHierarchyHandler, CallHierarchyHandler; -var init_callHierarchy2 = __esm({ - "src/handler/callHierarchy.ts"() { - import_path36 = __toModule(require("path")); - import_vscode_languageserver_protocol98 = __toModule(require_main2()); - init_esm2(); - init_commands2(); - init_events(); - init_languages(); - init_tree(); - init_TreeView(); - init_util(); - init_lodash(); - init_workspace(); - logger104 = require_logger2()("Handler-callHierarchy"); - _CallHierarchyHandler = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - this.disposables = []; - this.highlightWinids = new Set(); - this.loadConfiguration(); - workspace_default.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables); - this.disposables.push(commands_default.registerCommand(_CallHierarchyHandler.commandId, async (winid, item, openCommand) => { - var _a2; - let { nvim: nvim2 } = this; - await nvim2.call("win_gotoid", [winid]); - await workspace_default.jumpTo(item.uri, item.selectionRange.start, openCommand); - let win = await nvim2.window; - win.clearMatchGroup(_CallHierarchyHandler.rangesHighlight); - win.highlightRanges(_CallHierarchyHandler.rangesHighlight, [item.selectionRange], 10, true); - if (!((_a2 = item.ranges) == null ? void 0 : _a2.length)) - return; - if (item.sourceUri) { - let doc = workspace_default.getDocument(item.sourceUri); - if (!doc) - return; - let winid2 = await nvim2.call("coc#compat#buf_win_id", [doc.bufnr]); - if (winid2 == -1) - return; - if (winid2 != win.id) { - win = nvim2.createWindow(winid2); - win.clearMatchGroup(_CallHierarchyHandler.rangesHighlight); - } - } - win.highlightRanges(_CallHierarchyHandler.rangesHighlight, item.ranges, 100, true); - this.highlightWinids.add(win.id); - }, null, true)); - events_default.on("BufWinEnter", (_, winid) => { - if (this.highlightWinids.has(winid)) { - this.highlightWinids.delete(winid); - let win = nvim.createWindow(winid); - win.clearMatchGroup(_CallHierarchyHandler.rangesHighlight); - } - }, null, this.disposables); - } - loadConfiguration(e) { - if (!e || e.affectsConfiguration("callHierarchy")) { - let c = workspace_default.getConfiguration("callHierarchy"); - this.config = { - splitCommand: c.get("splitCommand"), - openCommand: c.get("openCommand"), - enableTooltip: c.get("enableTooltip") - }; - } - } - createProvider(doc, winid, position, kind) { - let _onDidChangeTreeData = new import_vscode_languageserver_protocol98.Emitter(); - let source; - let rootItems; - const cancel = () => { - if (source) { - source.cancel(); - source.dispose(); - source = null; - } - }; - const findParent = (curr, element) => { - let children = curr.children; - if (!Array.isArray(children)) - return void 0; - let find = children.find((o) => o == element); - if (find) - return curr; - for (let item of children) { - let res = findParent(item, element); - if (res) - return res; - } - }; - let provider = { - kind, - onDidChangeTreeData: _onDidChangeTreeData.event, - getTreeItem: (element) => { - var _a2; - let item = new TreeItem(element.name, element.children ? TreeItemCollapsibleState.Expanded : TreeItemCollapsibleState.Collapsed); - if (this.config.enableTooltip) { - item.tooltip = import_path36.default.relative(workspace_default.cwd, URI.parse(element.uri).fsPath); - } - item.description = element.detail; - item.deprecated = (_a2 = element.tags) == null ? void 0 : _a2.includes(import_vscode_languageserver_protocol98.SymbolTag.Deprecated); - item.icon = this.handler.getIcon(element.kind); - item.command = { - command: _CallHierarchyHandler.commandId, - title: "open location", - arguments: [winid, element, this.config.openCommand] - }; - return item; - }, - getChildren: async (element) => { - cancel(); - source = new import_vscode_languageserver_protocol98.CancellationTokenSource(); - let { token } = source; - if (!element) { - if (!rootItems) { - rootItems = await this.prepare(doc, position, token); - if (!(rootItems == null ? void 0 : rootItems.length)) - return; - } - for (let o of rootItems) { - let children = await this.getChildren(doc, o, provider.kind, token); - if (token.isCancellationRequested) - break; - if (Array.isArray(children)) - o.children = children; - } - return rootItems; - } - if (element.children) - return element.children; - let items = await this.getChildren(doc, element, provider.kind, token); - source = null; - if (token.isCancellationRequested) - return []; - element.children = items; - return items; - }, - resolveActions: () => { - return [{ - title: "Open in new tab", - handler: async (element) => { - await commands_default.executeCommand(_CallHierarchyHandler.commandId, winid, element, "tabe"); - } - }, { - title: "Show Incoming Calls", - handler: (element) => { - rootItems = [omit(element, ["children", "ranges", "sourceUri"])]; - provider.kind = "incoming"; - _onDidChangeTreeData.fire(void 0); - } - }, { - title: "Show Outgoing Calls", - handler: (element) => { - rootItems = [omit(element, ["children", "ranges", "sourceUri"])]; - provider.kind = "outgoing"; - _onDidChangeTreeData.fire(void 0); - } - }, { - title: "Dismiss", - handler: async (element) => { - let parentElement; - for (let curr of rootItems) { - parentElement = findParent(curr, element); - if (parentElement) - break; - } - if (!parentElement) - return; - let idx = parentElement.children.findIndex((o) => o === element); - parentElement.children.splice(idx, 1); - _onDidChangeTreeData.fire(parentElement); - } - }]; - }, - dispose: () => { - cancel(); - _onDidChangeTreeData.dispose(); - rootItems = void 0; - _onDidChangeTreeData = void 0; - } - }; - return provider; - } - async getChildren(doc, item, kind, token) { - let items = []; - if (kind == "incoming") { - let res = await languages_default.provideIncomingCalls(doc, item, token); - if (res) - items = res.map((o) => Object.assign(o.from, { ranges: o.fromRanges })); - } else { - let res = await languages_default.provideOutgoingCalls(doc, item, token); - if (res) - items = res.map((o) => Object.assign(o.to, { ranges: o.fromRanges, sourceUri: item.uri })); - } - return items; - } - async prepare(doc, position, token) { - this.handler.checkProvier("callHierarchy", doc); - const res = await languages_default.prepareCallHierarchy(doc, position, token); - return isCallHierarchyItem(res) ? [res] : res; - } - async getCallHierarchyItems(item, kind) { - const { doc, position } = await this.handler.getCurrentState(); - const source = new import_vscode_languageserver_protocol98.CancellationTokenSource(); - if (!item) { - await doc.synchronize(); - let res = await this.prepare(doc.textDocument, position, source.token); - item = res ? res[0] : void 0; - if (!res) - return void 0; - } - let method = kind == "incoming" ? "provideIncomingCalls" : "provideOutgoingCalls"; - return await languages_default[method](doc.textDocument, item, source.token); - } - async getIncoming(item) { - return await this.getCallHierarchyItems(item, "incoming"); - } - async getOutgoing(item) { - return await this.getCallHierarchyItems(item, "outgoing"); - } - async showCallHierarchyTree(kind) { - const { doc, position, winid } = await this.handler.getCurrentState(); - await doc.synchronize(); - let provider = this.createProvider(doc.textDocument, winid, position, kind); - let treeView = new BasicTreeView("calls", { treeDataProvider: provider }); - treeView.title = `${kind.toUpperCase()} CALLS`; - provider.onDidChangeTreeData((e) => { - if (!e) - treeView.title = `${provider.kind.toUpperCase()} CALLS`; - }); - treeView.onDidChangeVisibility((e) => { - if (!e.visible) - provider.dispose(); - }); - this.disposables.push(treeView); - await treeView.show(this.config.splitCommand); - } - dispose() { - this.highlightWinids.clear(); - disposeAll(this.disposables); - } - }; - CallHierarchyHandler = _CallHierarchyHandler; - CallHierarchyHandler.commandId = "callHierarchy.reveal"; - CallHierarchyHandler.rangesHighlight = "CocSelectedRange"; - } -}); - -// src/handler/semanticTokensHighlights/buffer.ts -var import_debounce12, import_vscode_languageserver_protocol99, logger105, SEMANTIC_HLGROUP_PREFIX, NAMESPACE, SemanticTokensBuffer; -var init_buffer5 = __esm({ - "src/handler/semanticTokensHighlights/buffer.ts"() { - import_debounce12 = __toModule(require_debounce()); - import_vscode_languageserver_protocol99 = __toModule(require_main2()); - init_languages(); - init_workspace(); - logger105 = require_logger2()("semanticTokens-buffer"); - SEMANTIC_HLGROUP_PREFIX = "CocSem_"; - NAMESPACE = "semanticTokens"; - SemanticTokensBuffer = class { - constructor(nvim, bufnr, config) { - this.nvim = nvim; - this.bufnr = bufnr; - this.config = config; - this.highlight = (0, import_debounce12.default)(() => { - this.doHighlight().catch((e) => { - logger105.error("Error on semanticTokens highlight:", e.stack); - }); - }, global.hasOwnProperty("__TEST__") ? 10 : 2e3); - this.highlight(); - } - onChange() { - this.cancel(); - this.highlight(); - } - async forceHighlight() { - this.cancel(); - this.highlight.clear(); - await this.doHighlight(); - } - get highlights() { - return this._highlights; - } - get enabled() { - if (!this.config.enabled) - return false; - let doc = workspace_default.getDocument(this.bufnr); - if (!doc || !doc.attached) - return false; - return languages_default.hasProvider("semanticTokens", doc.textDocument); - } - get previousVersion() { - if (!this.previousResults) - return void 0; - return this.previousResults.version; - } - get buffer() { - return this.nvim.createBuffer(this.bufnr); - } - checkState() { - if (!this.config.enabled) - throw new Error("SemanticTokens highlights disabled by configuration"); - let doc = workspace_default.getDocument(this.bufnr); - if (!doc || !doc.attached) - throw new Error("Document not attached"); - if (!languages_default.hasProvider("semanticTokens", doc.textDocument)) - throw new Error("SemanticTokens provider not found, your languageserver may not support it"); - } - setState(enabled) { - if (enabled) { - this.highlight(); - } else { - this.highlight.clear(); - this.clearHighlight(); - } - } - async doHighlight() { - if (!this.enabled) - return; - let doc = workspace_default.getDocument(this.bufnr); - const { nvim } = this; - let winid = await nvim.call("bufwinid", [this.bufnr]); - if (winid == -1) - return; - const curr = await this.requestHighlights(doc); - if (!curr) - return; - if (!curr.length) { - this.clearHighlight(); - return; - } - let prev = []; - if (workspace_default.env.updateHighlight) { - prev = await nvim.call("coc#highlight#get_highlights", [this.bufnr, NAMESPACE]); - } - const { highlights, lines } = this.calculateHighlightUpdates(prev, curr); - nvim.pauseNotification(); - if (!workspace_default.env.updateHighlight) { - this.buffer.clearNamespace(NAMESPACE, 0, -1); - } else { - for (const ln of lines) { - this.buffer.clearNamespace(NAMESPACE, ln, ln + 1); - } - } - const groups = {}; - if (highlights.length) { - for (const h of highlights) { - const range = import_vscode_languageserver_protocol99.Range.create(h.lnum, h.colStart, h.lnum, h.colEnd); - groups[h.hlGroup] = groups[h.hlGroup] || []; - groups[h.hlGroup].push(range); - } - } - for (const hlGroup of Object.keys(groups)) { - this.buffer.highlightRanges(NAMESPACE, hlGroup, groups[hlGroup]); - } - nvim.resumeNotification(false, true); - if (workspace_default.isVim) - nvim.command("redraw", true); - } - calculateHighlightUpdates(prev, curr) { - const stringCompare = Intl.Collator("en").compare; - function compare(a, b) { - return a.lnum - b.lnum || a.colStart - b.colStart || a.colEnd - b.colEnd || stringCompare(a.hlGroup, b.hlGroup); - } - prev = prev.slice().sort(compare); - curr = curr.slice().sort(compare); - const prevByLine = new Map(); - for (const hl of prev) { - if (!prevByLine.has(hl.lnum)) - prevByLine.set(hl.lnum, []); - prevByLine.get(hl.lnum).push(hl); - } - const currByLine = new Map(); - for (const hl of curr) { - if (!currByLine.has(hl.lnum)) - currByLine.set(hl.lnum, []); - currByLine.get(hl.lnum).push(hl); - } - const lastLine = Math.max((prev[prev.length - 1] || { lnum: 0 }).lnum, (curr[curr.length - 1] || { lnum: 0 }).lnum); - const lineNumbersToUpdate = new Set(); - for (let i = 0; i <= lastLine; i++) { - const ph = prevByLine.has(i); - const ch = currByLine.has(i); - if (ph !== ch) { - lineNumbersToUpdate.add(i); - continue; - } else if (!ph && !ch) { - continue; - } - const pp = prevByLine.get(i); - const cc = currByLine.get(i); - if (pp.length !== cc.length) { - lineNumbersToUpdate.add(i); - continue; - } - for (let j = 0; j < pp.length; j++) { - if (compare(pp[j], cc[j]) !== 0) { - lineNumbersToUpdate.add(i); - continue; - } - } - } - let highlights = []; - for (const line of lineNumbersToUpdate) { - highlights = highlights.concat(currByLine.get(line) || []); - } - return { highlights, lines: lineNumbersToUpdate }; - } - async requestHighlights(doc, forceFull) { - const legend = languages_default.getLegend(doc.textDocument); - if (!legend) - return void 0; - this.cancel(); - this.tokenSource = new import_vscode_languageserver_protocol99.CancellationTokenSource(); - const { token } = this.tokenSource; - const hasEditProvider = languages_default.hasSemanticTokensEdits(doc.textDocument); - const previousResult = forceFull ? null : this.previousResults; - let result; - let version2 = doc.textDocument.version; - if (hasEditProvider && (previousResult == null ? void 0 : previousResult.resultId)) { - result = await languages_default.provideDocumentSemanticTokensEdits(doc.textDocument, previousResult.resultId, token); - } else { - result = await languages_default.provideDocumentSemanticTokens(doc.textDocument, token); - } - this.tokenSource = null; - if (token.isCancellationRequested || !result) - return void 0; - let tokens = []; - if (import_vscode_languageserver_protocol99.SemanticTokens.is(result)) { - tokens = result.data; - } else { - tokens = previousResult.tokens; - result.edits.forEach((e) => { - if (e.deleteCount > 0) { - tokens.splice(e.start, e.deleteCount, ...e.data); - } else { - tokens.splice(e.start, 0, ...e.data); - } - }); - } - this.previousResults = { resultId: result.resultId, tokens, version: version2 }; - const relatives = []; - for (let i = 0; i < tokens.length; i += 5) { - const deltaLine = tokens[i]; - const deltaStartCharacter = tokens[i + 1]; - const length = tokens[i + 2]; - const tokenType = tokens[i + 3]; - const group2 = SEMANTIC_HLGROUP_PREFIX + legend.tokenTypes[tokenType]; - relatives.push({ - group: group2, - deltaLine, - deltaStartCharacter, - length - }); - } - const res = []; - let currentLine = 0; - let currentCharacter = 0; - for (const { - group: group2, - deltaLine, - deltaStartCharacter, - length - } of relatives) { - const lnum = currentLine + deltaLine; - const colStart = deltaLine === 0 ? currentCharacter + deltaStartCharacter : deltaStartCharacter; - const colEnd = colStart + length; - currentLine = lnum; - currentCharacter = colStart; - res.push({ - hlGroup: group2, - lnum, - colStart, - colEnd - }); - } - this._highlights = res; - return res; - } - clearHighlight() { - this.buffer.clearNamespace(NAMESPACE); - } - cancel() { - if (this.tokenSource) { - this.tokenSource.cancel(); - this.tokenSource = null; - } - } - dispose() { - this.highlight.clear(); - this.previousResults = void 0; - this.cancel(); - } - }; - } -}); - -// src/handler/semanticTokensHighlights/index.ts -var logger106, headGroup, SemanticTokensHighlights; -var init_semanticTokensHighlights = __esm({ - "src/handler/semanticTokensHighlights/index.ts"() { - init_commands2(); - init_events(); - init_languages(); - init_highligher(); - init_util(); - init_window(); - init_workspace(); - init_buffer5(); - logger106 = require_logger2()("semanticTokens"); - headGroup = "Statement"; - SemanticTokensHighlights = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - this.disposables = []; - this.loadConfiguration(); - workspace_default.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables); - commands_default.register({ - id: "semanticTokens.checkCurrent", - execute: async () => { - try { - let item = await this.getCurrentItem(); - item.checkState(); - } catch (e) { - window_default.showMessage(e.message, "error"); - return; - } - window_default.showMessage("Semantic tokens provider found for current buffer", "more"); - } - }, false, "check semantic tokens provider for current buffer"); - commands_default.register({ - id: "semanticTokens.clearCurrent", - execute: async () => { - let buf = await nvim.buffer; - buf.clearNamespace(NAMESPACE, 0, -1); - } - }, false, "clear semantic tokens highlights of current buffer"); - commands_default.register({ - id: "semanticTokens.clearAll", - execute: async () => { - let bufs = await nvim.buffers; - for (let buf of bufs) { - buf.clearNamespace(NAMESPACE, 0, -1); - } - } - }, false, "clear semantic tokens highlights of all buffers"); - this.disposables.push({ - dispose: () => { - commands_default.unregister("semanticTokens.checkCurrentBuffer"); - } - }); - events_default.on("BufEnter", (bufnr) => { - let item = this.highlighters.getItem(bufnr); - if (!item) - return; - let doc = workspace_default.getDocument(bufnr); - if (!doc || doc.textDocument.version == item.previousVersion) - return; - item.forceHighlight().catch((e) => { - logger106.error(`Error on semantic highlighters:`, e); - }); - }, null, this.disposables); - this.highlighters = workspace_default.registerBufferSync((doc) => { - return new SemanticTokensBuffer(this.nvim, doc.bufnr, this.config); - }); - languages_default.onDidSemanticTokensRefresh((selector) => { - for (let item of this.highlighters.items) { - let doc = workspace_default.getDocument(item.bufnr); - if (doc && workspace_default.match(selector, doc.textDocument)) { - item.highlight(); - } - } - }, null, this.disposables); - } - loadConfiguration(e) { - if (!e || e.affectsConfiguration("coc.preferences")) { - let config = workspace_default.getConfiguration("coc.preferences"); - let enabled = config.get("semanticTokensHighlights", true); - if (workspace_default.isVim && !workspace_default.env.textprop) { - enabled = false; - } - if (this.config && enabled != this.config.enabled) { - if (this.highlighters) { - for (let buf of this.highlighters.items) { - buf.setState(enabled); - } - } - } - if (!this.config) { - this.config = { enabled }; - } else { - this.config.enabled = enabled; - } - } - } - async getCurrentItem() { - let buf = await this.nvim.buffer; - let highlighter = this.highlighters.getItem(buf.id); - if (!highlighter) - throw new Error("current buffer not attached"); - return highlighter; - } - async highlightCurrent() { - let highlighter = await this.getCurrentItem(); - highlighter.checkState(); - await highlighter.forceHighlight(); - } - async showHiglightInfo() { - if (!this.config.enabled) - throw new Error("Semantic highlights is disabled by configuration."); - let item = await this.getCurrentItem(); - item.checkState(); - let highlights = item.highlights || []; - let highlighter = new Highlighter(); - let { nvim } = this; - nvim.pauseNotification(); - nvim.command(`vs +setl\\ buftype=nofile __coc_semantic_highlights_${item.bufnr}__`, true); - nvim.command(`setl bufhidden=wipe noswapfile nobuflisted wrap undolevels=-1`, true); - nvim.call("bufnr", ["%"], true); - let res = await nvim.resumeNotification(); - if (res[1]) - throw new Error(`Error on buffer create: ${res[1]}`); - let bufnr = res[0][2]; - highlighter.addLine("Semantic highlights info", headGroup); - highlighter.addLine(""); - highlighter.addLine("The number of semantic tokens: "); - highlighter.addText(String(highlights.length), "Number"); - highlighter.addLine(""); - highlighter.addLine("Semantic highlight groups used by current buffer", headGroup); - highlighter.addLine(""); - const groups = [...new Set(highlights.map(({ hlGroup }) => hlGroup))]; - for (const hlGroup of groups) { - highlighter.addTexts([{ text: "-", hlGroup: "Comment" }, { text: " " }, { text: hlGroup, hlGroup }]); - highlighter.addLine(""); - } - highlighter.addLine("Tokens types that current Language Server supported:", headGroup); - highlighter.addLine(""); - let doc = workspace_default.getDocument(item.bufnr); - const legend = languages_default.getLegend(doc.textDocument); - if (legend == null ? void 0 : legend.tokenTypes.length) { - for (const t of [...new Set(legend.tokenTypes)]) { - highlighter.addTexts([{ text: "-", hlGroup: "Comment" }, { text: " " }, { text: `CocSem_${t}`, hlGroup: `CocSem_${t}` }]); - highlighter.addLine(""); - } - } else { - highlighter.addLine("No token types supported", "Comment"); - } - highlighter.addLine("Tokens modifiers that current Language Server supported:", headGroup); - highlighter.addLine(""); - if (legend == null ? void 0 : legend.tokenModifiers.length) { - for (const t of [...new Set(legend.tokenModifiers)]) { - highlighter.addTexts([{ text: "-", hlGroup: "Comment" }, { text: " " }, { text: `CocSem_${t}`, hlGroup: `CocSem_${t}` }]); - highlighter.addLine(""); - } - } else { - highlighter.addLine("No token modifiers supported", "Comment"); - } - nvim.pauseNotification(); - highlighter.render(nvim.createBuffer(bufnr)); - nvim.resumeNotification(false, true); - } - dispose() { - this.highlighters.dispose(); - disposeAll(this.disposables); - } - }; - } -}); - -// src/handler/signature.ts -var import_vscode_languageserver_protocol100, logger107, Signature; -var init_signature = __esm({ - "src/handler/signature.ts"() { - import_vscode_languageserver_protocol100 = __toModule(require_main2()); - init_events(); - init_languages(); - init_floatFactory(); - init_util(); - init_string(); - init_workspace(); - logger107 = require_logger2()("handler-signature"); - Signature = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - this.disposables = []; - this.signatureFactory = new FloatFactory(nvim); - this.loadConfiguration(); - this.disposables.push(this.signatureFactory); - workspace_default.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables); - events_default.on("CursorMovedI", async (bufnr, cursor) => { - let pos = this.lastPosition; - if (!pos) - return; - if (pos.bufnr == bufnr && pos.lnum == cursor[0] && pos.col <= cursor[1]) - return; - this.signatureFactory.close(); - }, null, this.disposables); - events_default.on(["InsertLeave", "BufEnter"], () => { - var _a2; - (_a2 = this.tokenSource) == null ? void 0 : _a2.cancel(); - }, null, this.disposables); - events_default.on("TextChangedI", () => { - if (this.config.hideOnChange) { - this.signatureFactory.close(); - } - }, null, this.disposables); - events_default.on("TextInsert", async (bufnr, info, character) => { - if (!this.config.trigger) - return; - let doc = this.getTextDocument(bufnr); - if (!doc || !languages_default.shouldTriggerSignatureHelp(doc.textDocument, character)) - return; - await this._triggerSignatureHelp(doc, { line: info.lnum - 1, character: info.pre.length }, false); - }, null, this.disposables); - } - getTextDocument(bufnr) { - let doc = workspace_default.getDocument(bufnr); - if (!doc || doc.isCommandLine || !doc.attached) - return; - return doc; - } - loadConfiguration(e) { - if (!e || e.affectsConfiguration("signature")) { - let config = workspace_default.getConfiguration("signature"); - let target = config.get("target", "float"); - if (target == "float" && !workspace_default.floatSupported) { - target = "echo"; - } - this.config = { - target, - floatConfig: config.get("floatConfig", {}), - trigger: config.get("enable", true), - wait: Math.max(config.get("triggerSignatureWait", 500), 200), - preferAbove: config.get("preferShownAbove", true), - hideOnChange: config.get("hideOnTextChange", false) - }; - } - } - async triggerSignatureHelp() { - let { doc, position, mode } = await this.handler.getCurrentState(); - if (!languages_default.hasProvider("signature", doc.textDocument)) - return false; - let offset = 0; - let character = position.character; - if (mode == "s") { - let placeholder = await this.nvim.getVar("coc_last_placeholder"); - if (placeholder) { - let { start, end, bufnr } = placeholder; - if (bufnr == doc.bufnr && start.line == end.line && start.line == position.line) { - position = import_vscode_languageserver_protocol100.Position.create(start.line, start.character); - offset = character - position.character; - } - } - } - return await this._triggerSignatureHelp(doc, position, true, offset); - } - async _triggerSignatureHelp(doc, position, invoke = true, offset = 0) { - var _a2; - (_a2 = this.tokenSource) == null ? void 0 : _a2.cancel(); - let tokenSource = this.tokenSource = new import_vscode_languageserver_protocol100.CancellationTokenSource(); - let token = tokenSource.token; - token.onCancellationRequested(() => { - tokenSource.dispose(); - this.tokenSource = void 0; - }); - let { target } = this.config; - let timer = this.timer = setTimeout(() => { - tokenSource.cancel(); - }, this.config.wait); - await doc.patchChange(true); - let signatureHelp = await languages_default.getSignatureHelp(doc.textDocument, position, token, { - isRetrigger: this.signatureFactory.checkRetrigger(doc.bufnr), - triggerKind: invoke ? import_vscode_languageserver_protocol100.SignatureHelpTriggerKind.Invoked : import_vscode_languageserver_protocol100.SignatureHelpTriggerKind.TriggerCharacter - }); - clearTimeout(timer); - if (token.isCancellationRequested) - return false; - if (!signatureHelp || signatureHelp.signatures.length == 0) { - this.signatureFactory.close(); - return false; - } - let { activeSignature, signatures } = signatureHelp; - if (activeSignature) { - let [active] = signatures.splice(activeSignature, 1); - if (active) - signatures.unshift(active); - } - if (target == "echo") { - this.echoSignature(signatureHelp); - } else { - await this.showSignatureHelp(doc, position, signatureHelp, offset); - } - return true; - } - async showSignatureHelp(doc, position, signatureHelp, offset) { - let { signatures, activeParameter } = signatureHelp; - let paramDoc = null; - let startOffset = offset; - let docs = signatures.reduce((p, c, idx) => { - var _a2; - let activeIndexes = null; - let nameIndex = c.label.indexOf("("); - if (idx == 0 && activeParameter != null) { - let active = (_a2 = c.parameters) == null ? void 0 : _a2[activeParameter]; - if (active) { - let after = c.label.slice(nameIndex == -1 ? 0 : nameIndex); - paramDoc = active.documentation; - if (typeof active.label === "string") { - let str = after.slice(0); - let ms = str.match(new RegExp("\\b" + active.label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b")); - let index = ms ? ms.index : str.indexOf(active.label); - if (index != -1) { - activeIndexes = [ - index + nameIndex, - index + active.label.length + nameIndex - ]; - } - } else { - activeIndexes = active.label; - } - } - } - if (activeIndexes == null) { - activeIndexes = [nameIndex + 1, nameIndex + 1]; - } - if (offset == startOffset) { - offset = offset + activeIndexes[0] + 1; - } - p.push({ - content: c.label, - filetype: doc.filetype, - active: activeIndexes - }); - if (paramDoc) { - let content2 = typeof paramDoc === "string" ? paramDoc : paramDoc.value; - if (content2.trim().length) { - p.push({ - content: content2, - filetype: isMarkdown(c.documentation) ? "markdown" : "txt" - }); - } - } - if (idx == 0 && c.documentation) { - let { documentation } = c; - let content2 = typeof documentation === "string" ? documentation : documentation.value; - if (content2.trim().length) { - p.push({ - content: content2, - filetype: isMarkdown(c.documentation) ? "markdown" : "txt" - }); - } - } - return p; - }, []); - let content = doc.getline(position.line, false).slice(0, position.character); - this.lastPosition = { bufnr: doc.bufnr, lnum: position.line + 1, col: byteLength(content) + 1 }; - const excludeImages = workspace_default.getConfiguration("coc.preferences").get("excludeImageLinksInMarkdownDocument"); - let config = this.signatureFactory.applyFloatConfig({ - preferTop: this.config.preferAbove, - autoHide: false, - offsetX: offset, - modes: ["i", "ic", "s"], - excludeImages - }, this.config.floatConfig); - await this.signatureFactory.show(docs, config); - } - echoSignature(signatureHelp) { - var _a2; - let { signatures, activeParameter } = signatureHelp; - let columns = workspace_default.env.columns; - signatures = signatures.slice(0, workspace_default.env.cmdheight); - let signatureList = []; - for (let signature of signatures) { - let parts = []; - let { label } = signature; - label = label.replace(/\n/g, " "); - if (label.length >= columns - 16) { - label = label.slice(0, columns - 16) + "..."; - } - let nameIndex = label.indexOf("("); - if (nameIndex == -1) { - parts = [{ text: label, type: "Normal" }]; - } else { - parts.push({ - text: label.slice(0, nameIndex), - type: "Label" - }); - let after = label.slice(nameIndex); - if (signatureList.length == 0 && activeParameter != null) { - let active = (_a2 = signature.parameters) == null ? void 0 : _a2[activeParameter]; - if (active) { - let start; - let end; - if (typeof active.label === "string") { - let str = after.slice(0); - let ms = str.match(new RegExp("\\b" + active.label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b")); - let idx = ms ? ms.index : str.indexOf(active.label); - if (idx == -1) { - parts.push({ text: after, type: "Normal" }); - } else { - start = idx; - end = idx + active.label.length; - } - } else { - [start, end] = active.label; - start = start - nameIndex; - end = end - nameIndex; - } - if (start != null && end != null) { - parts.push({ text: after.slice(0, start), type: "Normal" }); - parts.push({ text: after.slice(start, end), type: "MoreMsg" }); - parts.push({ text: after.slice(end), type: "Normal" }); - } - } - } else { - parts.push({ - text: after, - type: "Normal" - }); - } - } - signatureList.push(parts); - } - this.nvim.callTimer("coc#util#echo_signatures", [signatureList], true); - } - dispose() { - disposeAll(this.disposables); - if (this.timer) { - clearTimeout(this.timer); - } - } - }; - } -}); - -// src/handler/symbols/util.ts -function convertSymbols(symbols) { - let res = []; - let arr = symbols.slice(); - arr.sort(sortDocumentSymbols); - arr.forEach((s) => addDocumentSymbol(res, s, 0)); - return res; -} -function sortDocumentSymbols(a, b) { - let ra = a.selectionRange; - let rb = b.selectionRange; - return comparePosition(ra.start, rb.start); -} -function addDocumentSymbol(res, sym, level) { - let { name: name2, selectionRange, kind, children, range } = sym; - let { start } = selectionRange || range; - res.push({ - col: start.character + 1, - lnum: start.line + 1, - text: name2, - level, - kind: getSymbolKind(kind), - range, - selectionRange - }); - if (children && children.length) { - children.sort(sortDocumentSymbols); - for (let sym2 of children) { - addDocumentSymbol(res, sym2, level + 1); - } - } -} -function isDocumentSymbol(a) { - return a && !a.hasOwnProperty("location"); -} -function isDocumentSymbols(a) { - return isDocumentSymbol(a[0]); -} -var init_util5 = __esm({ - "src/handler/symbols/util.ts"() { - init_convert(); - init_position(); - } -}); - -// src/handler/symbols/buffer.ts -var import_debounce13, import_vscode_languageserver_protocol101, SymbolsBuffer; -var init_buffer6 = __esm({ - "src/handler/symbols/buffer.ts"() { - import_debounce13 = __toModule(require_debounce()); - import_vscode_languageserver_protocol101 = __toModule(require_main2()); - init_languages(); - init_util(); - init_workspace(); - init_util5(); - SymbolsBuffer = class { - constructor(bufnr) { - this.bufnr = bufnr; - this.disposables = []; - this.autoUpdate = false; - this._onDidUpdate = new import_vscode_languageserver_protocol101.Emitter(); - this.onDidUpdate = this._onDidUpdate.event; - this.fetchSymbols = (0, import_debounce13.default)(() => { - this._fetchSymbols().logError(); - }, global.hasOwnProperty("__TEST__") ? 10 : 500); - } - async getSymbols() { - var _a2; - let doc = workspace_default.getDocument(this.bufnr); - if (!doc) - return []; - await doc.patchChange(); - this.autoUpdate = true; - if (doc.version == this.version && ((_a2 = this.symbols) == null ? void 0 : _a2.length)) - return this.symbols; - this.cancel(); - await this._fetchSymbols(); - return this.symbols; - } - onChange() { - this.cancel(); - if (this.autoUpdate) { - this.fetchSymbols(); - } - } - get textDocument() { - var _a2; - return (_a2 = workspace_default.getDocument(this.bufnr)) == null ? void 0 : _a2.textDocument; - } - async _fetchSymbols() { - let { textDocument } = this; - if (!textDocument) - return; - let { version: version2 } = textDocument; - let tokenSource = this.tokenSource = new import_vscode_languageserver_protocol101.CancellationTokenSource(); - let { token } = tokenSource; - let symbols = await languages_default.getDocumentSymbol(textDocument, token); - this.tokenSource = void 0; - if (symbols == null || token.isCancellationRequested) - return; - let res; - if (isDocumentSymbols(symbols)) { - res = symbols; - } else { - res = symbols.map((o) => { - let sym = import_vscode_languageserver_protocol101.DocumentSymbol.create(o.name, "", o.kind, o.location.range, o.location.range); - if (o.deprecated) - sym.tags = [import_vscode_languageserver_protocol101.SymbolTag.Deprecated]; - return sym; - }); - } - this.version = version2; - this.symbols = res; - this._onDidUpdate.fire(res); - } - cancel() { - this.fetchSymbols.clear(); - if (this.tokenSource) { - this.tokenSource.cancel(); - this.tokenSource.dispose(); - this.tokenSource = null; - } - } - dispose() { - this.cancel(); - this.symbols = void 0; - this._onDidUpdate.dispose(); - disposeAll(this.disposables); - } - }; - } -}); - -// src/tree/BasicDataProvider.ts -function isIcon(obj) { - if (!obj) - return false; - return typeof obj.text === "string" && typeof obj.hlGroup === "string"; -} -function sameTreeNode(one, two) { - if (one.label === two.label && one.deprecated === two.deprecated && one.key === two.key) { - return true; - } - return false; -} -function sameTreeNodes(one, two) { - if (one.length !== two.length) - return false; - return one.every((v, idx) => sameTreeNode(v, two[idx])); -} -var import_vscode_languageserver_protocol102, BasicDataProvider; -var init_BasicDataProvider = __esm({ - "src/tree/BasicDataProvider.ts"() { - init_esm_node(); - import_vscode_languageserver_protocol102 = __toModule(require_main2()); - init_commands2(); - init_util(); - init_TreeItem(); - BasicDataProvider = class { - constructor(opts) { - this.opts = opts; - this.disposables = []; - this._onDidChangeTreeData = new import_vscode_languageserver_protocol102.Emitter(); - this.onDidChangeTreeData = this._onDidChangeTreeData.event; - this.invokeCommand = `_invoke_${v4_default()}`; - this.disposables.push(commands_default.registerCommand(this.invokeCommand, async (node) => { - if (typeof opts.handleClick === "function") { - await opts.handleClick(node); - } else { - console.error("Handler not found"); - } - }, null, true)); - if (typeof opts.resolveActions === "function") { - this.resolveActions = opts.resolveActions.bind(this); - } - } - iterate(node, parentNode, level, fn) { - let res = fn(node, parentNode, level); - if (res === false) - return false; - if (Array.isArray(node.children)) { - for (let element of node.children) { - let res2 = this.iterate(element, node, level + 1, fn); - if (res2 === false) - return false; - } - } - return res; - } - updateNodes(old, data, parentNode, fireEvent = true) { - let sameNodes = sameTreeNodes(old, data); - const applyNode = (previous, curr, fireEvent2) => { - var _a2, _b, _c, _d, _e, _f; - let changed = false; - for (let key of Object.keys(curr)) { - if (["children", "key"].includes(key)) - continue; - previous[key] = curr[key]; - } - if (((_a2 = previous.children) == null ? void 0 : _a2.length) && !((_b = curr.children) == null ? void 0 : _b.length)) { - delete previous.children; - changed = true; - } - if (!((_c = previous.children) == null ? void 0 : _c.length) && ((_d = curr.children) == null ? void 0 : _d.length)) { - previous.children = curr.children; - changed = true; - } - if (changed) { - if (fireEvent2) - this._onDidChangeTreeData.fire(previous); - return; - } - if (((_e = previous.children) == null ? void 0 : _e.length) && ((_f = curr.children) == null ? void 0 : _f.length)) { - this.updateNodes(previous.children, curr.children, previous, fireEvent2); - } - }; - if (sameNodes) { - for (let i = 0; i < old.length; i++) { - applyNode(old[i], data[i], fireEvent); - } - } else { - let oldNodes = old.splice(0, old.length); - let used = new Set(); - for (let i = 0; i < data.length; i++) { - let curr = data[i]; - let findIndex; - if (curr.key) { - findIndex = oldNodes.findIndex((o, i2) => !used.has(i2) && o.key == curr.key); - } else { - findIndex = oldNodes.findIndex((o, i2) => !used.has(i2) && o.label == curr.label); - } - if (findIndex === -1) { - old[i] = curr; - } else { - used.add(findIndex); - let previous = oldNodes[findIndex]; - applyNode(previous, curr, false); - old[i] = previous; - } - } - if (fireEvent) { - this._onDidChangeTreeData.fire(parentNode); - } - } - } - update(data, reset) { - if (!this.data) - return; - if (reset) { - this.data = data || []; - this._onDidChangeTreeData.fire(void 0); - } else { - this.updateNodes(this.data, data || [], void 0); - } - return this.data; - } - getTreeItem(node) { - var _a2; - let label = node.label; - let { expandLevel } = this.opts; - let item; - if (!((_a2 = node.children) == null ? void 0 : _a2.length)) { - item = new TreeItem(label); - } else { - if (expandLevel && expandLevel > 0) { - let level = this.getLevel(node); - let state = level && level <= expandLevel ? TreeItemCollapsibleState.Expanded : TreeItemCollapsibleState.Collapsed; - item = new TreeItem(label, state); - } else { - item = new TreeItem(label, TreeItemCollapsibleState.Collapsed); - } - } - item.description = node.description; - if (node.deprecated) - item.deprecated = true; - if (node.tooltip) - item.tooltip = node.tooltip; - if (isIcon(node.icon)) { - item.icon = node.icon; - } else if (typeof this.opts.resolveIcon === "function") { - let res = this.opts.resolveIcon(node); - if (res) - item.icon = res; - } - return item; - } - async getChildren(element) { - if (element) - return element.children || []; - if (this.data) - return this.data; - let data = await Promise.resolve(this.opts.provideData()); - if (!Array.isArray(data)) - throw new Error(`Unable to fetch data`); - this.data = data; - return data; - } - getParent(element) { - if (!this.data) - return void 0; - let find; - for (let item of this.data) { - let res = this.iterate(item, null, 0, (node, parentNode) => { - if (node === element) { - find = parentNode; - return false; - } - }); - if (res === false) - break; - } - return find; - } - getLevel(element) { - if (!this.data) - return void 0; - let level = 0; - for (let item of this.data) { - let res = this.iterate(item, null, 1, (node, _parentNode, l) => { - if (node === element) { - level = l; - return false; - } - }); - if (res === false) - break; - } - return level; - } - async resolveTreeItem(item, element, token) { - if (typeof this.opts.resolveItem === "function") { - let res = await Promise.resolve(this.opts.resolveItem(item, element, token)); - if (res) - Object.assign(item, res); - } - if (!item.command) { - item.command = { - title: `invoke ${element.label}`, - command: this.invokeCommand, - arguments: [element] - }; - } - return item; - } - dispose() { - this.data = []; - this._onDidChangeTreeData.dispose(); - if (typeof this.opts.onDispose === "function") { - this.opts.onDispose(); - } - disposeAll(this.disposables); - } - }; - } -}); - -// src/handler/symbols/outline.ts -var import_debounce14, import_vscode_languageserver_protocol103, logger108, SymbolsOutline; -var init_outline2 = __esm({ - "src/handler/symbols/outline.ts"() { - import_debounce14 = __toModule(require_debounce()); - import_vscode_languageserver_protocol103 = __toModule(require_main2()); - init_events(); - init_languages(); - init_BasicDataProvider(); - init_TreeView(); - init_util(); - init_position(); - init_window(); - init_workspace(); - logger108 = require_logger2()("symbols-outline"); - SymbolsOutline = class { - constructor(nvim, buffers, handler) { - this.nvim = nvim; - this.buffers = buffers; - this.handler = handler; - this.providersMap = new Map(); - this.treeViews = new WeakMap(); - this.originalWins = new WeakMap(); - this.disposables = []; - this.loadConfiguration(); - workspace_default.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables); - events_default.on("BufUnload", async (bufnr) => { - let provider = this.providersMap.get(bufnr); - if (!provider) - return; - this.providersMap.delete(bufnr); - provider.dispose(); - let views = this.treeViews.get(provider); - this.treeViews.delete(provider); - for (let view of views) { - if (!view.visible) - continue; - let winid = this.originalWins.get(view); - if (winid && this.config.checkBufferSwitch) { - let nr = await nvim.call("win_id2win", [winid]); - if (nr) { - let win = nvim.createWindow(view.windowId); - win.setVar("target_bufnr", -1, true); - let timer = setTimeout(() => { - if (view.visible) - view.dispose(); - }, 200); - this.disposables.push({ - dispose: () => { - clearTimeout(timer); - } - }); - continue; - } - } - view.dispose(); - } - }, null, this.disposables); - events_default.on("BufEnter", (0, import_debounce14.default)(() => { - void this._onBufEnter(); - }, global.hasOwnProperty("__TEST__") ? 100 : 300), null, this.disposables); - events_default.on("CursorHold", async (bufnr) => { - if (!this.config.followCursor) - return; - let provider = this.providersMap.get(bufnr); - if (!provider) - return; - let views = this.treeViews.get(provider); - if (!views || !views.length) - return; - let winid = await this.nvim.call("coc#window#find", ["cocViewId", "OUTLINE"]); - if (winid == -1) - return; - let view = views.find((o) => o.windowId == winid); - if (!view) - return; - let pos = await window_default.getCursorPosition(); - let curr; - let checkNode = (node) => { - if (positionInRange(pos, node.range) != 0) - return false; - curr = node; - if (Array.isArray(node.children)) { - for (let n of node.children) { - if (checkNode(n)) - break; - } - } - return true; - }; - let nodes = await Promise.resolve(provider.getChildren()); - for (let n of nodes) { - if (checkNode(n)) - break; - } - if (curr) - await view.reveal(curr); - }, null, this.disposables); - } - async _onBufEnter() { - if (!this.config.checkBufferSwitch) - return; - let [curr, bufnr, winid] = await this.nvim.eval(`[win_getid(),bufnr('%'),coc#window#find('cocViewId', 'OUTLINE')]`); - if (curr == winid || winid == -1) - return; - if (!this.buffers.getItem(bufnr)) - return; - let win = this.nvim.createWindow(winid); - let target = await win.getVar("target_bufnr"); - if (target == bufnr) - return; - await this.show(1); - } - loadConfiguration(e) { - if (!e || e.affectsConfiguration("outline")) { - let c = workspace_default.getConfiguration("outline"); - this.config = { - splitCommand: c.get("splitCommand"), - followCursor: c.get("followCursor"), - keepWindow: c.get("keepWindow"), - expandLevel: c.get("expandLevel"), - checkBufferSwitch: c.get("checkBufferSwitch"), - sortBy: c.get("sortBy"), - showLineNumber: c.get("showLineNumber"), - codeActionKinds: c.get("codeActionKinds") - }; - } - } - convertSymbolToNode(documentSymbol, sortFn) { - var _a2; - return { - label: documentSymbol.name, - tooltip: documentSymbol.detail, - description: this.config.showLineNumber ? `${documentSymbol.selectionRange.start.line + 1}` : void 0, - icon: this.handler.getIcon(documentSymbol.kind), - deprecated: (_a2 = documentSymbol.tags) == null ? void 0 : _a2.includes(import_vscode_languageserver_protocol103.SymbolTag.Deprecated), - kind: documentSymbol.kind, - range: documentSymbol.range, - selectRange: documentSymbol.selectionRange, - children: Array.isArray(documentSymbol.children) ? documentSymbol.children.map((o) => { - return this.convertSymbolToNode(o, sortFn); - }).sort(sortFn) : void 0 - }; - } - setMessage(provider, msg) { - let views = this.treeViews.get(provider); - if (views) { - views.forEach((view) => { - view.message = msg; - }); - } - } - createProvider(buf) { - let { bufnr } = buf; - let { sortBy } = this.config; - let { nvim } = this; - let sortFn = (a, b) => { - if (sortBy === "name") { - return a.label < b.label ? -1 : 1; - } - if (sortBy === "category") { - if (a.kind == b.kind) - return a.label < b.label ? -1 : 1; - return a.kind - b.kind; - } - return comparePosition(a.selectRange.start, b.selectRange.start); - }; - let convertSymbols2 = (symbols) => { - return symbols.map((s) => this.convertSymbolToNode(s, sortFn)).sort(sortFn); - }; - let disposable; - let provider = new BasicDataProvider({ - expandLevel: this.config.expandLevel, - provideData: async () => { - let doc = workspace_default.getDocument(bufnr); - if (!languages_default.hasProvider("documentSymbol", doc.textDocument)) { - throw new Error("Document symbol provider not found"); - } - this.setMessage(provider, "Loading document symbols"); - let arr = await buf.getSymbols(); - if (!arr || arr.length == 0) { - throw new Error("Empty symbols returned from language server. "); - } - disposable = buf.onDidUpdate((symbols) => { - provider.update(convertSymbols2(symbols)); - }); - this.setMessage(provider, void 0); - return convertSymbols2(arr); - }, - handleClick: async (item) => { - let winnr = await nvim.call("bufwinnr", [bufnr]); - if (winnr == -1) - return; - nvim.pauseNotification(); - nvim.command(`${winnr}wincmd w`, true); - let pos = item.selectRange.start; - nvim.call("coc#cursor#move_to", [pos.line, pos.character], true); - nvim.command(`normal! zz`, true); - let buf2 = nvim.createBuffer(bufnr); - buf2.highlightRanges("outline-hover", "CocHoverRange", [item.selectRange]); - nvim.command("redraw", true); - await nvim.resumeNotification(); - setTimeout(() => { - buf2.clearNamespace("outline-hover"); - nvim.command("redraw", true); - }, global.hasOwnProperty("__TEST__") ? 10 : 300); - }, - resolveActions: async (_, element) => { - let winnr = await nvim.call("bufwinnr", [bufnr]); - if (winnr == -1) - return; - let doc = workspace_default.getDocument(bufnr); - let actions = await this.handler.getCodeActions(doc, element.range, this.config.codeActionKinds); - let arr = actions.map((o) => { - return { - title: o.title, - handler: async () => { - let position = element.range.start; - await nvim.command(`${winnr}wincmd w`); - await this.nvim.call("coc#cursor#move_to", [position.line, position.character]); - await this.handler.applyCodeAction(o); - } - }; - }); - return [...arr, { - title: "Visual Select", - handler: async (item) => { - await nvim.command(`${winnr}wincmd w`); - await workspace_default.selectRange(item.range); - } - }]; - }, - onDispose: () => { - this.providersMap.delete(buf.bufnr); - if (disposable) - disposable.dispose(); - } - }); - return provider; - } - async show(keep) { - await workspace_default.document; - let [bufnr, winid] = await this.nvim.eval('[bufnr("%"),win_getid()]'); - let buf = this.buffers.getItem(bufnr); - if (!buf) - throw new Error("Document not attached"); - let provider = this.providersMap.get(bufnr); - if (!provider) { - provider = this.createProvider(buf); - this.providersMap.set(bufnr, provider); - } - let treeView = new BasicTreeView("OUTLINE", { - enableFilter: true, - treeDataProvider: provider - }); - this.originalWins.set(treeView, winid); - let arr = this.treeViews.get(provider) || []; - arr.push(treeView); - this.treeViews.set(provider, arr); - treeView.onDidChangeVisibility(({ visible }) => { - if (visible || !this.treeViews.has(provider)) - return; - let arr2 = this.treeViews.get(provider) || []; - arr2 = arr2.filter((s) => s !== treeView); - this.originalWins.delete(treeView); - if (arr2.length) { - this.treeViews.set(provider, arr2); - return; - } - provider.dispose(); - this.treeViews.delete(provider); - }); - await treeView.show(this.config.splitCommand); - if (treeView.windowId) { - let win = this.nvim.createWindow(treeView.windowId); - win.setVar("target_bufnr", bufnr, true); - } - if (keep == 1 || keep === void 0 && this.config.keepWindow) { - await this.nvim.command("wincmd p"); - } - } - has(bufnr) { - return this.providersMap.has(bufnr); - } - async hide() { - let winid = await this.nvim.call("coc#window#find", ["cocViewId", "OUTLINE"]); - if (winid == -1) - return; - await this.nvim.call("coc#window#close", [winid]); - } - dispose() { - for (let provider of this.providersMap.values()) { - provider.dispose(); - for (let view of this.treeViews.get(provider)) { - view.dispose(); - } - } - this.providersMap.clear(); - disposeAll(this.disposables); - } - }; - } -}); - -// src/handler/symbols/index.ts -var import_vscode_languageserver_protocol104, Symbols2; -var init_symbols2 = __esm({ - "src/handler/symbols/index.ts"() { - import_vscode_languageserver_protocol104 = __toModule(require_main2()); - init_events(); - init_languages(); - init_util(); - init_object(); - init_position(); - init_window(); - init_workspace(); - init_buffer6(); - init_outline2(); - init_util5(); - Symbols2 = class { - constructor(nvim, handler) { - this.nvim = nvim; - this.handler = handler; - this.disposables = []; - this.buffers = workspace_default.registerBufferSync((doc) => { - if (doc.buftype != "") - return void 0; - return new SymbolsBuffer(doc.bufnr); - }); - this.outline = new SymbolsOutline(nvim, this.buffers, handler); - events_default.on("CursorHold", async (bufnr) => { - if (!this.functionUpdate || !this.buffers.getItem(bufnr)) - return; - await this.getCurrentFunctionSymbol(bufnr); - }, null, this.disposables); - events_default.on("InsertEnter", (bufnr) => { - let buf = this.buffers.getItem(bufnr); - if (buf) - buf.cancel(); - }, null, this.disposables); - } - get functionUpdate() { - let config = workspace_default.getConfiguration("coc.preferences"); - return config.get("currentFunctionSymbolAutoUpdate", false); - } - get labels() { - return workspace_default.getConfiguration("suggest").get("completionItemKindLabels", {}); - } - async getWorkspaceSymbols(input) { - this.handler.checkProvier("workspaceSymbols", null); - let tokenSource = new import_vscode_languageserver_protocol104.CancellationTokenSource(); - return await languages_default.getWorkspaceSymbols(input, tokenSource.token); - } - async resolveWorkspaceSymbol(symbolInfo) { - var _a2; - if ((_a2 = symbolInfo.location) == null ? void 0 : _a2.uri) - return symbolInfo; - let tokenSource = new import_vscode_languageserver_protocol104.CancellationTokenSource(); - return await languages_default.resolveWorkspaceSymbol(symbolInfo, tokenSource.token); - } - async getDocumentSymbols(bufnr) { - let buf = this.buffers.getItem(bufnr); - if (!buf) - return; - let res = await buf.getSymbols(); - return res ? convertSymbols(res) : void 0; - } - async getCurrentFunctionSymbol(bufnr) { - if (!bufnr) - bufnr = await this.nvim.call("bufnr", ["%"]); - let doc = workspace_default.getDocument(bufnr); - if (!doc || !doc.attached) - return; - if (!languages_default.hasProvider("documentSymbol", doc.textDocument)) - return; - let position = await window_default.getCursorPosition(); - let symbols = await this.getDocumentSymbols(bufnr); - let buffer = this.nvim.createBuffer(bufnr); - if (!symbols || symbols.length === 0) { - buffer.setVar("coc_current_function", "", true); - this.nvim.call("coc#util#do_autocmd", ["CocStatusChange"], true); - return ""; - } - symbols = symbols.filter((s) => [ - "Class", - "Method", - "Function", - "Struct" - ].includes(s.kind)); - let functionName = ""; - for (let sym of symbols.reverse()) { - if (sym.range && positionInRange(position, sym.range) == 0 && !sym.text.endsWith(") callback")) { - functionName = sym.text; - let label = this.labels[sym.kind.toLowerCase()]; - if (label) - functionName = `${label} ${functionName}`; - break; - } - } - if (this.functionUpdate) { - buffer.setVar("coc_current_function", functionName, true); - this.nvim.call("coc#util#do_autocmd", ["CocStatusChange"], true); - } - return functionName; - } - async selectSymbolRange(inner, visualmode, supportedSymbols) { - let { doc } = await this.handler.getCurrentState(); - this.handler.checkProvier("documentSymbol", doc.textDocument); - let range; - if (visualmode) { - range = await workspace_default.getSelectedRange(visualmode, doc); - } else { - let pos = await window_default.getCursorPosition(); - range = import_vscode_languageserver_protocol104.Range.create(pos, pos); - } - let symbols = await this.getDocumentSymbols(doc.bufnr); - if (!symbols || symbols.length === 0) { - window_default.showMessage("No symbols found", "warning"); - return; - } - symbols = symbols.filter((s) => supportedSymbols.includes(s.kind)); - let selectRange; - for (let sym of symbols.reverse()) { - if (sym.range && !equals(sym.range, range) && rangeInRange(range, sym.range)) { - selectRange = sym.range; - break; - } - } - if (inner && selectRange) { - let { start, end } = selectRange; - let line = doc.getline(start.line + 1); - let endLine = doc.getline(end.line - 1); - selectRange = import_vscode_languageserver_protocol104.Range.create(start.line + 1, line.match(/^\s*/)[0].length, end.line - 1, endLine.length); - } - if (selectRange) { - await workspace_default.selectRange(selectRange); - } else if (["v", "V", ""].includes(visualmode)) { - await this.nvim.command("normal! gv"); - } - } - async showOutline(keep) { - await this.outline.show(keep); - } - async hideOutline() { - await this.outline.hide(); - } - hasOutline(bufnr) { - return this.outline.has(bufnr); - } - dispose() { - this.outline.dispose(); - this.buffers.dispose(); - disposeAll(this.disposables); - } - }; - } -}); - -// src/handler/index.ts -var import_vscode_languageserver_protocol105, logger109, Handler; -var init_handler = __esm({ - "src/handler/index.ts"() { - import_vscode_languageserver_protocol105 = __toModule(require_main2()); - init_events(); - init_languages(); - init_util(); - init_window(); - init_workspace(); - init_codeActions(); - init_codelens(); - init_colors(); - init_commands3(); - init_fold(); - init_format2(); - init_highlights(); - init_hover(); - init_links2(); - init_locations(); - init_refactor(); - init_rename(); - init_selectionRange2(); - init_callHierarchy2(); - init_semanticTokensHighlights(); - init_signature(); - init_symbols2(); - init_convert(); - logger109 = require_logger2()("Handler"); - Handler = class { - constructor(nvim) { - this.nvim = nvim; - this.disposables = []; - this.requestStatusItem = window_default.createStatusBarItem(0, { progress: true }); - events_default.on(["CursorMoved", "CursorMovedI", "InsertEnter", "InsertSnippet", "InsertLeave"], () => { - if (this.requestTokenSource) { - this.requestTokenSource.cancel(); - this.requestTokenSource = null; - } - }, null, this.disposables); - this.labels = workspace_default.getConfiguration("suggest").get("completionItemKindLabels", {}); - this.fold = new FoldHandler(nvim, this); - this.links = new Links(nvim, this); - this.codeLens = new CodeLensManager2(nvim); - this.colors = new Colors(nvim, this); - this.format = new FormatHandler(nvim, this); - this.symbols = new Symbols2(nvim, this); - this.refactor = new Refactor(nvim, this); - this.hover = new HoverHandler(nvim, this); - this.locations = new LocationsHandler(nvim, this); - this.signature = new Signature(nvim, this); - this.rename = new Rename(nvim, this); - this.codeActions = new CodeActions(nvim, this); - this.commands = new Commands(nvim, workspace_default.env); - this.callHierarchy = new CallHierarchyHandler(nvim, this); - this.documentHighlighter = new Highlights(nvim, this); - this.semanticHighlighter = new SemanticTokensHighlights(nvim, this); - this.selectionRange = new SelectionRangeHandler(nvim, this); - this.disposables.push({ - dispose: () => { - this.callHierarchy.dispose(); - this.codeLens.dispose(); - this.refactor.dispose(); - this.signature.dispose(); - this.symbols.dispose(); - this.hover.dispose(); - this.locations.dispose(); - this.colors.dispose(); - this.documentHighlighter.dispose(); - this.semanticHighlighter.dispose(); - } - }); - } - async getCurrentState() { - let { nvim } = this; - let [bufnr, [line, character], winid, mode] = await nvim.eval("[bufnr('%'),coc#cursor#position(),win_getid(),mode()]"); - let doc = workspace_default.getDocument(bufnr); - if (!doc || !doc.attached) - throw new Error(`current buffer ${bufnr} not attached`); - return { - doc, - mode, - position: import_vscode_languageserver_protocol105.Position.create(line, character), - winid - }; - } - addDisposable(disposable) { - this.disposables.push(disposable); - } - checkProvier(id, document2) { - if (!languages_default.hasProvider(id, document2)) { - throw new Error(`${id} provider not found for current buffer, your language server doesn't support it.`); - } - } - async withRequestToken(name2, fn, checkEmpty) { - if (this.requestTokenSource) { - this.requestTokenSource.cancel(); - this.requestTokenSource.dispose(); - } - if (this.requestTimer) { - clearTimeout(this.requestTimer); - } - let statusItem = this.requestStatusItem; - this.requestTokenSource = new import_vscode_languageserver_protocol105.CancellationTokenSource(); - let { token } = this.requestTokenSource; - token.onCancellationRequested(() => { - statusItem.text = `${name2} request canceled`; - statusItem.isProgress = false; - this.requestTimer = setTimeout(() => { - statusItem.hide(); - }, 500); - }); - statusItem.isProgress = true; - statusItem.text = `requesting ${name2}`; - statusItem.show(); - let res; - try { - res = await Promise.resolve(fn(token)); - } catch (e) { - window_default.showMessage(e.message, "error"); - logger109.error(`Error on ${name2}`, e); - } - if (this.requestTokenSource) { - this.requestTokenSource.dispose(); - this.requestTokenSource = void 0; - } - if (token.isCancellationRequested) - return null; - statusItem.hide(); - if (checkEmpty && (!res || Array.isArray(res) && res.length == 0)) { - window_default.showMessage(`${name2} not found`, "warning"); - return null; - } - return res; - } - getIcon(kind) { - let { labels } = this; - let kindText = getSymbolKind(kind); - let defaultIcon = typeof labels["default"] === "string" ? labels["default"] : kindText[0].toLowerCase(); - let text = kindText == "Unknown" ? "" : labels[kindText[0].toLowerCase() + kindText.slice(1)]; - if (!text || typeof text !== "string") - text = defaultIcon; - return { - text, - hlGroup: kindText == "Unknown" ? "CocSymbolDefault" : `CocSymbol${kindText}` - }; - } - async getCodeActions(doc, range, only) { - return await this.codeActions.getCodeActions(doc, range, only); - } - async applyCodeAction(action) { - await this.codeActions.applyCodeAction(action); - } - async hasProvider(id) { - let bufnr = await this.nvim.call("bufnr", "%"); - let doc = workspace_default.getDocument(bufnr); - if (!doc) - return false; - return languages_default.hasProvider(id, doc.textDocument); - } - dispose() { - if (this.requestTimer) { - clearTimeout(this.requestTimer); - } - disposeAll(this.disposables); - } - }; - } -}); - -// src/plugin.ts -var import_events43, import_fs37, import_path37, import_vscode_languageserver_protocol106, logger110, Plugin; -var init_plugin = __esm({ - "src/plugin.ts"() { - import_events43 = __toModule(require("events")); - import_fs37 = __toModule(require("fs")); - import_path37 = __toModule(require("path")); - import_vscode_languageserver_protocol106 = __toModule(require_main2()); - init_esm2(); - init_commands2(); - init_completion(); - init_cursors(); - init_manager(); - init_events(); - init_extensions2(); - init_handler(); - init_manager3(); - init_services(); - init_manager4(); - init_sources2(); - init_types(); - init_window(); - init_workspace(); - logger110 = require_logger2()("plugin"); - Plugin = class extends import_events43.EventEmitter { - constructor(nvim) { - super(); - this.nvim = nvim; - this._ready = false; - this.actions = new Map(); - Object.defineProperty(workspace_default, "nvim", { - get: () => this.nvim - }); - workspace_default.onDidChangeWorkspaceFolders(() => { - nvim.setVar("WorkspaceFolders", workspace_default.folderPaths, true); - }); - this.cursors = new Cursors(nvim); - commands_default.init(nvim, this); - this.addAction("checkJsonExtension", () => { - if (extensions_default.has("coc-json")) - return; - window_default.showMessage(`Run :CocInstall coc-json for json intellisense`, "more"); - }); - this.addAction("rootPatterns", (bufnr) => { - let doc = workspace_default.getDocument(bufnr); - if (!doc) - return null; - return { - buffer: workspace_default.getRootPatterns(doc, PatternType.Buffer), - server: workspace_default.getRootPatterns(doc, PatternType.LanguageServer), - global: workspace_default.getRootPatterns(doc, PatternType.Global) - }; - }); - this.addAction("getConfig", async (key) => { - let document2 = await workspace_default.document; - return workspace_default.getConfiguration(key, document2 ? document2.uri : void 0); - }); - this.addAction("doAutocmd", async (id, ...args) => { - let autocmd = workspace_default.autocmds.get(id); - if (autocmd) { - try { - await Promise.resolve(autocmd.callback.apply(autocmd.thisArg, args)); - } catch (e) { - logger110.error(`Error on autocmd ${autocmd.event}`, e); - window_default.showMessage(`Error on autocmd ${autocmd.event}: ${e.message}`); - } - } - }); - this.addAction("openLog", async () => { - let file = logger110.getLogFile(); - await workspace_default.jumpTo(URI.file(file).toString()); - }); - this.addAction("attach", () => workspace_default.attach()); - this.addAction("detach", () => workspace_default.detach()); - this.addAction("doKeymap", async (key, defaultReturn = "", pressed) => { - let keymap = workspace_default.keymaps.get(key); - if (!keymap) { - logger110.error(`keymap for ${key} not found`); - this.nvim.command(`silent! unmap ${pressed.startsWith("{") && pressed.endsWith("}") ? `<${pressed.slice(1, -1)}>` : pressed}`, true); - return defaultReturn; - } - let [fn, repeat2] = keymap; - let res = await Promise.resolve(fn()); - if (repeat2) - await nvim.command(`silent! call repeat#set("\\(coc-${key})", -1)`); - return res != null ? res : defaultReturn; - }); - this.addAction("registExtensions", async (...folders) => { - for (let folder of folders) { - await extensions_default.loadExtension(folder); - } - }); - this.addAction("snippetCheck", async (checkExpand, checkJump) => { - if (checkExpand && !extensions_default.has("coc-snippets")) { - console.error("coc-snippets required for check expand status!"); - return false; - } - if (checkJump) { - let jumpable = manager_default3.jumpable(); - if (jumpable) - return true; - } - if (checkExpand) { - let api = extensions_default.getExtensionApi("coc-snippets"); - if (api && api.hasOwnProperty("expandable")) { - let expandable = await Promise.resolve(api.expandable()); - if (expandable) - return true; - } - } - return false; - }); - this.addAction("snippetNext", () => manager_default3.nextPlaceholder()); - this.addAction("snippetPrev", () => manager_default3.previousPlaceholder()); - this.addAction("snippetCancel", () => manager_default3.cancel()); - this.addAction("openLocalConfig", () => window_default.openLocalConfig()); - this.addAction("showInfo", async () => { - if (!this.infoChannel) { - this.infoChannel = window_default.createOutputChannel("info"); - } else { - this.infoChannel.clear(); - } - let channel = this.infoChannel; - channel.appendLine("## versions"); - channel.appendLine(""); - let out = await this.nvim.call("execute", ["version"]); - let first = out.trim().split(/\r?\n/, 2)[0].replace(/\(.*\)/, "").trim(); - channel.appendLine("vim version: " + first + `${workspace_default.isVim ? " " + workspace_default.env.version : ""}`); - channel.appendLine("node version: " + process.version); - channel.appendLine("coc.nvim version: " + this.version); - channel.appendLine("coc.nvim directory: " + import_path37.default.dirname(__dirname)); - channel.appendLine("term: " + (process.env.TERM_PROGRAM || process.env.TERM)); - channel.appendLine("platform: " + process.platform); - channel.appendLine(""); - channel.appendLine("## Log of coc.nvim"); - channel.appendLine(""); - let file = logger110.getLogFile(); - if (import_fs37.default.existsSync(file)) { - let content = import_fs37.default.readFileSync(file, { encoding: "utf8" }); - channel.appendLine(content); - } - channel.show(); - }); - this.addAction("findLocations", (id, method, params, openCommand) => { - return this.handler.locations.findLocations(id, method, params, openCommand); - }); - this.addAction("hasProvider", (id) => this.handler.hasProvider(id)); - this.addAction("getTagList", () => this.handler.locations.getTagList()); - this.addAction("hasSelected", () => completion_default.hasSelected()); - this.addAction("listNames", () => manager_default2.names); - this.addAction("listDescriptions", () => manager_default2.descriptions); - this.addAction("listLoadItems", (name2) => manager_default2.loadItems(name2)); - this.addAction("search", (...args) => this.handler.refactor.search(args)); - this.addAction("cursorsSelect", (bufnr, kind, mode) => this.cursors.select(bufnr, kind, mode)); - this.addAction("fillDiagnostics", (bufnr) => manager_default.setLocationlist(bufnr)); - this.addAction("saveRefactor", (bufnr) => this.handler.refactor.save(bufnr)); - this.addAction("commandList", () => this.handler.commands.getCommandList()); - this.addAction("selectSymbolRange", (inner, visualmode, supportedSymbols) => this.handler.symbols.selectSymbolRange(inner, visualmode, supportedSymbols)); - this.addAction("openList", (...args) => manager_default2.start(args)); - this.addAction("listResume", (name2) => manager_default2.resume(name2)); - this.addAction("listCancel", () => manager_default2.cancel(true)); - this.addAction("listPrev", (name2) => manager_default2.previous(name2)); - this.addAction("listNext", (name2) => manager_default2.next(name2)); - this.addAction("listFirst", (name2) => manager_default2.first(name2)); - this.addAction("listLast", (name2) => manager_default2.last(name2)); - this.addAction("sendRequest", (id, method, params) => services_default.sendRequest(id, method, params)); - this.addAction("sendNotification", (id, method, params) => services_default.sendNotification(id, method, params)); - this.addAction("registNotification", (id, method) => services_default.registNotification(id, method)); - this.addAction("updateConfig", (section2, val) => workspace_default.configurations.updateUserConfig({ [section2]: val })); - this.addAction("links", () => this.handler.links.getLinks()); - this.addAction("openLink", () => this.handler.links.openCurrentLink()); - this.addAction("pickColor", () => this.handler.colors.pickColor()); - this.addAction("colorPresentation", () => this.handler.colors.pickPresentation()); - this.addAction("highlight", () => this.handler.documentHighlighter.highlight()); - this.addAction("fold", (kind) => this.handler.fold.fold(kind)); - this.addAction("startCompletion", (option) => completion_default.startCompletion(option)); - this.addAction("stopCompletion", () => completion_default.stop(false)); - this.addAction("sourceStat", () => sources_default.sourceStats()); - this.addAction("refreshSource", (name2) => sources_default.refresh(name2)); - this.addAction("toggleSource", (name2) => sources_default.toggleSource(name2)); - this.addAction("diagnosticRefresh", (bufnr) => manager_default.refresh(bufnr)); - this.addAction("diagnosticInfo", () => manager_default.echoMessage()); - this.addAction("diagnosticToggle", () => manager_default.toggleDiagnostic()); - this.addAction("diagnosticToggleBuffer", async (bufnr) => { - if (!bufnr) - bufnr = await nvim.call("bufnr", ["%"]); - return manager_default.toggleDiagnosticBuffer(bufnr); - }); - this.addAction("diagnosticNext", (severity) => manager_default.jumpNext(severity)); - this.addAction("diagnosticPrevious", (severity) => manager_default.jumpPrevious(severity)); - this.addAction("diagnosticPreview", () => manager_default.preview()); - this.addAction("diagnosticList", () => manager_default.getDiagnosticList()); - this.addAction("jumpDefinition", (openCommand) => this.handler.locations.gotoDefinition(openCommand)); - this.addAction("definitions", () => this.handler.locations.definitions()); - this.addAction("jumpDeclaration", (openCommand) => this.handler.locations.gotoDeclaration(openCommand)); - this.addAction("declarations", () => this.handler.locations.declarations()); - this.addAction("jumpImplementation", (openCommand) => this.handler.locations.gotoImplementation(openCommand)); - this.addAction("implementations", () => this.handler.locations.implementations()); - this.addAction("jumpTypeDefinition", (openCommand) => this.handler.locations.gotoTypeDefinition(openCommand)); - this.addAction("typeDefinitions", () => this.handler.locations.typeDefinitions()); - this.addAction("jumpReferences", (openCommand) => this.handler.locations.gotoReferences(openCommand)); - this.addAction("references", () => this.handler.locations.references()); - this.addAction("jumpUsed", (openCommand) => this.handler.locations.gotoReferences(openCommand, false)); - this.addAction("doHover", (hoverTarget) => this.handler.hover.onHover(hoverTarget)); - this.addAction("definitionHover", (hoverTarget) => this.handler.hover.definitionHover(hoverTarget)); - this.addAction("getHover", () => this.handler.hover.getHover()); - this.addAction("showSignatureHelp", () => this.handler.signature.triggerSignatureHelp()); - this.addAction("documentSymbols", async (bufnr) => { - if (!bufnr) { - let doc = await workspace_default.document; - bufnr = doc.bufnr; - } - return await this.handler.symbols.getDocumentSymbols(bufnr); - }); - this.addAction("ensureDocument", async () => { - let doc = await workspace_default.document; - return doc && doc.attached; - }); - this.addAction("symbolRanges", () => this.handler.documentHighlighter.getSymbolsRanges()); - this.addAction("selectionRanges", () => this.handler.selectionRange.getSelectionRanges()); - this.addAction("rangeSelect", (visualmode, forward) => this.handler.selectionRange.selectRange(visualmode, forward)); - this.addAction("rename", (newName) => this.handler.rename.rename(newName)); - this.addAction("getWorkspaceSymbols", (input) => this.handler.symbols.getWorkspaceSymbols(input)); - this.addAction("resolveWorkspaceSymbol", (symbolInfo) => this.handler.symbols.resolveWorkspaceSymbol(symbolInfo)); - this.addAction("formatSelected", (mode) => this.handler.format.formatCurrentRange(mode)); - this.addAction("format", () => this.handler.format.formatCurrentBuffer()); - this.addAction("commands", () => this.handler.commands.getCommands()); - this.addAction("services", () => services_default.getServiceStats()); - this.addAction("toggleService", (name2) => services_default.toggle(name2)); - this.addAction("codeAction", (mode, only) => this.handler.codeActions.doCodeAction(mode, only)); - this.addAction("organizeImport", () => this.handler.codeActions.organizeImport()); - this.addAction("fixAll", () => this.handler.codeActions.doCodeAction(null, [import_vscode_languageserver_protocol106.CodeActionKind.SourceFixAll])); - let codeActions = []; - this.addAction("doCodeAction", (codeAction) => { - if (codeAction.index == null) { - throw new Error(`index should exists with codeAction`); - } - let action = codeActions[codeAction.index]; - if (!action) - throw new Error(`invalid codeAction index: ${codeAction.index}`); - return this.handler.codeActions.applyCodeAction(action); - }); - this.addAction("codeActions", async (mode, only) => { - codeActions = await this.handler.codeActions.getCurrentCodeActions(mode, only); - return codeActions.map((o, idx) => Object.assign({ index: idx }, o)); - }); - this.addAction("quickfixes", async (mode) => { - codeActions = await this.handler.codeActions.getCurrentCodeActions(mode, [import_vscode_languageserver_protocol106.CodeActionKind.QuickFix]); - return codeActions.map((o, idx) => Object.assign({ index: idx }, o)); - }); - this.addAction("codeLensAction", () => this.handler.codeLens.doAction()); - this.addAction("runCommand", (...args) => this.handler.commands.runCommand(...args)); - this.addAction("doQuickfix", () => this.handler.codeActions.doQuickfix()); - this.addAction("refactor", () => this.handler.refactor.doRefactor()); - this.addAction("repeatCommand", () => this.handler.commands.repeat()); - this.addAction("installExtensions", (...list2) => extensions_default.installExtensions(list2)); - this.addAction("updateExtensions", (sync) => extensions_default.updateExtensions(sync)); - this.addAction("extensionStats", () => extensions_default.getExtensionStates()); - this.addAction("loadedExtensions", () => extensions_default.loadedExtensions()); - this.addAction("watchExtension", (id) => extensions_default.watchExtension(id)); - this.addAction("activeExtension", (name2) => extensions_default.activate(name2)); - this.addAction("deactivateExtension", (name2) => extensions_default.deactivate(name2)); - this.addAction("reloadExtension", (name2) => extensions_default.reloadExtension(name2)); - this.addAction("toggleExtension", (name2) => extensions_default.toggleExtension(name2)); - this.addAction("uninstallExtension", (...args) => extensions_default.uninstallExtension(args)); - this.addAction("getCurrentFunctionSymbol", () => this.handler.symbols.getCurrentFunctionSymbol()); - this.addAction("showOutline", (keep) => this.handler.symbols.showOutline(keep)); - this.addAction("hideOutline", () => this.handler.symbols.hideOutline()); - this.addAction("getWordEdit", () => this.handler.rename.getWordEdit()); - this.addAction("addCommand", (cmd) => this.handler.commands.addVimCommand(cmd)); - this.addAction("addRanges", (ranges) => this.cursors.addRanges(ranges)); - this.addAction("currentWorkspacePath", () => workspace_default.rootPath); - this.addAction("selectCurrentPlaceholder", (triggerAutocmd) => manager_default3.selectCurrentPlaceholder(!!triggerAutocmd)); - this.addAction("codeActionRange", (start, end, only) => this.handler.codeActions.codeActionRange(start, end, only)); - this.addAction("incomingCalls", (item) => this.handler.callHierarchy.getIncoming(item)); - this.addAction("outgoingCalls", (item) => this.handler.callHierarchy.getOutgoing(item)); - this.addAction("showIncomingCalls", () => this.handler.callHierarchy.showCallHierarchyTree("incoming")); - this.addAction("showOutgoingCalls", () => this.handler.callHierarchy.showCallHierarchyTree("outgoing")); - this.addAction("semanticHighlight", () => this.handler.semanticHighlighter.highlightCurrent()); - this.addAction("showSemanticHighlightInfo", () => this.handler.semanticHighlighter.showHiglightInfo()); - } - addAction(key, fn) { - if (this.actions.has(key)) { - throw new Error(`Action ${key} already exists`); - } - this.actions.set(key, fn); - } - async init() { - let { nvim } = this; - let s = Date.now(); - try { - await extensions_default.init(); - await workspace_default.init(); - manager_default3.init(); - completion_default.init(); - manager_default.init(); - manager_default2.init(nvim); - sources_default.init(); - this.handler = new Handler(nvim); - services_default.init(); - extensions_default.activateExtensions(); - workspace_default.setupDynamicAutocmd(true); - nvim.pauseNotification(); - nvim.setVar("WorkspaceFolders", workspace_default.folderPaths, true); - nvim.setVar("coc_service_initialized", 1, true); - nvim.call("coc#util#do_autocmd", ["CocNvimInit"], true); - nvim.resumeNotification(false, true); - this._ready = true; - await events_default.fire("ready", []); - logger110.info(`coc.nvim ${this.version} initialized with node: ${process.version} after ${Date.now() - s}ms`); - this.emit("ready"); - } catch (e) { - nvim.echoError(e); - } - } - get isReady() { - return this._ready; - } - get ready() { - if (this._ready) - return Promise.resolve(); - return new Promise((resolve3) => { - this.once("ready", () => { - resolve3(); - }); - }); - } - get version() { - return workspace_default.version + (true ? "-f021999eb2" : ""); - } - hasAction(method) { - return this.actions.has(method); - } - async cocAction(method, ...args) { - let fn = this.actions.get(method); - if (!fn) - throw new Error(`Action "${method}" not exists`); - let ts = Date.now(); - let res = await Promise.resolve(fn.apply(null, args)); - let dt = Date.now() - ts; - if (dt > 500) - logger110.warn(`Slow action "${method}" cost ${dt}ms`); - return res; - } - getHandler() { - return this.handler; - } - dispose() { - this.removeAllListeners(); - extensions_default.dispose(); - manager_default2.dispose(); - workspace_default.dispose(); - window_default.dispose(); - sources_default.dispose(); - services_default.stopAll(); - services_default.dispose(); - if (this.handler) { - this.handler.dispose(); - } - manager_default3.dispose(); - commands_default.dispose(); - completion_default.dispose(); - manager_default.dispose(); - } - }; - } -}); - -// src/attach.ts -var attach_exports = {}; -__export(attach_exports, { - default: () => attach_default -}); -var import_neovim2, import_log4js, import_semver3, logger111, isTest, ACTIONS_NO_WAIT, attach_default; -var init_attach = __esm({ - "src/attach.ts"() { - import_neovim2 = __toModule(require_lib6()); - import_log4js = __toModule(require_log4js()); - init_events(); - init_plugin(); - import_semver3 = __toModule(require_semver2()); - init_is(); - init_esm2(); - init_package(); - logger111 = require_logger2()("attach"); - isTest = global.hasOwnProperty("__TEST__"); - ACTIONS_NO_WAIT = ["installExtensions", "updateExtensions"]; - attach_default = (opts, requestApi = true) => { - const nvim = (0, import_neovim2.attach)(opts, import_log4js.default.getLogger("node-client"), requestApi); - if (!global.hasOwnProperty("__TEST__")) { - nvim.call("coc#util#path_replace_patterns").then((prefixes) => { - if (objectLiteral(prefixes)) { - const old_uri = URI.file; - URI.file = (path36) => { - path36 = path36.replace(/\\/g, "/"); - Object.keys(prefixes).forEach((k) => path36 = path36.replace(new RegExp("^" + k), prefixes[k])); - return old_uri(path36); - }; - } - }).logError(); - } - nvim.setVar("coc_process_pid", process.pid, true); - const plugin = new Plugin(nvim); - let clientReady = false; - let initialized = false; - nvim.on("notification", async (method, args) => { - switch (method) { - case "VimEnter": { - if (!initialized && clientReady) { - initialized = true; - await plugin.init(); - } - break; - } - case "Log": { - logger111.debug(...args); - break; - } - case "TaskExit": - case "TaskStderr": - case "TaskStdout": - case "GlobalChange": - case "PromptInsert": - case "InputChar": - case "MenuInput": - case "OptionSet": - case "FloatBtnClick": - await events_default.fire(method, args); - break; - case "CocAutocmd": - logger111.trace("Notification autocmd:", ...args); - await events_default.fire(args[0], args.slice(1)); - break; - default: { - let exists = plugin.hasAction(method); - if (!exists) { - if (global.hasOwnProperty("__TEST__")) - return; - console.error(`action "${method}" not exists`); - return; - } - try { - if (!plugin.isReady) { - logger111.warn(`Plugin not ready when received "${method}"`, args); - } else { - logger111.info("receive notification:", method, args); - } - await plugin.ready; - await plugin.cocAction(method, ...args); - } catch (e) { - console.error(`Error on "${method}": ${e.message || e.toString()}`); - logger111.error(`Notification error:`, method, args, e); - } - } - } - }); - nvim.on("request", async (method, args, resp) => { - if (method == "redraw") { - resp.send(); - return; - } - let timer = setTimeout(() => { - logger111.error("Request cost more than 3s", method, args); - }, 3e3); - try { - if (method == "CocAutocmd") { - logger111.trace("Request autocmd:", ...args); - await events_default.fire(args[0], args.slice(1)); - resp.send(void 0); - } else { - if (!plugin.isReady && !ACTIONS_NO_WAIT.includes(method)) { - logger111.warn(`Plugin not ready on request "${method}"`, args); - resp.send("Plugin not ready", true); - return; - } - logger111.info("Request action:", method, args); - let res = await plugin.cocAction(method, ...args); - resp.send(res); - } - clearTimeout(timer); - } catch (e) { - clearTimeout(timer); - resp.send(e.message || e.toString(), true); - logger111.error(`Request error:`, method, args, e); - } - }); - nvim.channelId.then(async (channelId) => { - clientReady = true; - if (isTest) - nvim.command(`let g:coc_node_channel_id = ${channelId}`, true); - let { major, minor, patch } = import_semver3.default.parse(version); - nvim.setClientInfo("coc", { major, minor, patch }, "remote", {}, {}); - let entered = await nvim.getVvar("vim_did_enter"); - if (entered && !initialized) { - initialized = true; - await plugin.init(); - } - }).catch((e) => { - console.error(`Channel create error: ${e.message}`); - }); - return plugin; - }; - } -}); - -// src/main.ts -require_extensions(); -Object.defineProperty(console, "log", { - value() { - logger112.info(...arguments); - } -}); -var logger112 = require_logger2()("server"); -var attach2 = (init_attach(), attach_exports).default; -attach2({ reader: process.stdin, writer: process.stdout }); -process.on("uncaughtException", function(err) { - let msg = "Uncaught exception: " + err.message; - console.error(msg); - logger112.error("uncaughtException", err.stack); -}); -process.on("unhandledRejection", function(reason, p) { - if (reason instanceof Error) { - console.error("UnhandledRejection: " + reason.message + "\n" + reason.stack); - } else { - console.error("UnhandledRejection: " + reason); - } - logger112.error("unhandledRejection ", p, reason); -}); -/*! - * @description Recursive object extending - * @author Viacheslav Lotsmanov - * @license MIT - * - * The MIT License (MIT) - * - * Copyright (c) 2013-2018 Viacheslav Lotsmanov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -/*! - * ISC License - * - * Copyright (c) 2018, Andrea Giammarchi, @WebReflection - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE - * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +`;for(let l of s.relatedInformation){let u=R.basename(O.parse(l.location.uri).fsPath),c=l.location.range.start.line;a=`${a} +${u}(line ${c+1}): ${l.message}`;let d=o.get(l.location.uri)||[];d.push(Hr.create(l.location.range,l.message,it.Hint,s.code,s.source)),o.set(l.location.uri,d)}s.message=a}this._diagnostics.set(Array.from(o))}}else this._diagnostics.set(e,t)}handleApplyWorkspaceEdit(e){let t=e.edit,i=new Map;y.textDocuments.forEach(o=>i.set(o.uri.toString(),o));let r=!1;if(t.documentChanges){for(let o of t.documentChanges)if(Qt.is(o)&&o.textDocument.version&&o.textDocument.version>=0){let s=i.get(o.textDocument.uri);if(s&&s.version!==o.textDocument.version){r=!0;break}}}return r?Promise.resolve({applied:!1}):y.applyEdit(e.edit).then(o=>({applied:o}))}handleFailedRequest(e,t,i,r){if(t&&t.isCancellationRequested)return r;if(i instanceof p.ResponseError){if(i.code===p.ErrorCodes.PendingResponseRejected||i.code===p.ErrorCodes.ConnectionInactive)return r;if(i.code===p.LSPErrorCodes.RequestCancelled||i.code===p.LSPErrorCodes.ServerCancelled)throw i.data!=null?new ru(i.data):new Rt;if(i.code===p.LSPErrorCodes.ContentModified){if(jC.RequestsToCancelOnContentModified.has(e.method))throw new Rt;return r}}throw this.error(`Request ${e.method} failed.`,i),i}logFailedRequest(){}},lm=jC;lm.RequestsToCancelOnContentModified=new Set([p.InlayHintRequest.method,p.SemanticTokensRequest.method,p.SemanticTokensRangeRequest.method,p.SemanticTokensDeltaRequest.method]);Efe={createAll:n=>[]}});function Ffe(n,e){if(R.isAbsolute(n))return n;let t=Mfe();if(t!==void 0){let i=R.join(t,n);if(F.existsSync(i))return i}if(e!==void 0){let i=R.join(e,n);if(F.existsSync(i))return i}return n}function Mfe(){let n=y.workspaceFolders;return!n||n.length===0?void 0:n[0].uri}function jfe(n){let e=n&&n.cwd;return e&&!R.isAbsolute(e)&&(e=R.join(y.cwd,e)),e||(e=y.cwd),new Promise(t=>{F.lstat(e,(i,r)=>{t(!i&&r.isDirectory()?e:void 0)})})}function Ofe(n){return n?n.some(e=>Ife.some(t=>e.startsWith(t))||Lfe.some(t=>e===t)):!1}var NC,Ife,Lfe,C4,p0,qC,HC,f0,m0,b0,Cd,BC,y0=D(()=>{"use strict";xe();te();Xe();de();Tl();U();he();g0();g0();NC=Z("language-client-index"),Ife=["--debug=","--debug-brk=","--inspect=","--inspect-brk="],Lfe=["--debug","--debug-brk","--inspect","--inspect-brk"],C4=pe(2e3,100);(e=>{function n(t){return $e(t.command)}e.is=n})(p0||(p0={}));qC=(r=>(r[r.stdio=0]="stdio",r[r.ipc=1]="ipc",r[r.pipe=2]="pipe",r[r.socket=3]="socket",r))(qC||{});(e=>{function n(t){let i=t;return i&&i.kind===3&&$t(i.port)}e.isSocket=n})(HC||(HC={}));(e=>{function n(t){return $e(t.module)}e.is=n})(f0||(f0={}));(e=>{function n(t){let i=t;return i&&i.writer!==void 0&&i.reader!==void 0}e.is=n})(m0||(m0={}));(e=>{function n(t){let i=t;return i&&i.process!==void 0&&typeof i.detached=="boolean"}e.is=n})(b0||(b0={}));Cd=class extends lm{constructor(t,i,r,o,s){let a,l,u,c,d;$e(i)?(a=t,l=i,u=r,c=o,d=!!s):(a=t.toLowerCase(),l=t,u=i,c=r,d=o);super(a,l,c);this._serverOptions=u,this._forceDebug=!!d,this._isInDebugMode=!!d}stop(t=C4){return super.stop(t).then(()=>{if(this._serverProcess){let i=this._serverProcess;this._serverProcess=void 0,(this._isDetached===void 0||!this._isDetached)&&this.checkProcessDied(i),this._isDetached=void 0}},i=>{if(i.message.includes("timed out")){this._serverProcess.kill("SIGKILL"),this._serverProcess=void 0;return}throw i})}get serviceState(){return this._state}checkProcessDied(t){!t||t.pid===void 0||setTimeout(()=>{try{process.kill(t.pid,0),gv(t)}catch{}},C4)}handleConnectionClosed(){this._serverProcess=void 0,super.handleConnectionClosed()}get isInDebugMode(){return this._isInDebugMode}async restart(){await this.stop(),this.isInDebugMode?(await new Promise(t=>setTimeout(t,1e3)),await this._start()):await this._start()}createMessageTransports(t){function i(u,c){if(!u&&!c)return;let d=Object.create(null);return Object.keys(process.env).forEach(h=>d[h]=process.env[h]),u&&Object.keys(u).forEach(h=>d[h]=u[h]),d}function r(u){if(u.stdin===null||u.stdout===null||u.stderr===null)throw new Error("Process created without stdio streams")}let o=this._serverOptions,s=this.logMessage.bind(this);if(tt(o))return o().then(u=>{if(xd.is(u))return this._isDetached=!!u.detached,u;if(m0.is(u))return this._isDetached=!!u.detached,{reader:new p.StreamMessageReader(u.reader),writer:new p.StreamMessageWriter(u.writer)};{let c;return b0.is(u)?(c=u.process,this._isDetached=u.detached):(c=u,this._isDetached=!1),c.stderr.on("data",s),{reader:new p.StreamMessageReader(c.stdout),writer:new p.StreamMessageWriter(c.stdin)}}});let a,l=o;return l.run||l.debug?typeof v8debug=="object"||this._forceDebug||Ofe(process.execArgv)?a=l.debug:a=l.run:a=o,jfe(a.options).then(u=>{if(f0.is(a)&&a.module){let c=a,d=c.transport||0,h,g=c.runtime?Ffe(c.runtime,u):void 0;return new Promise((f,m)=>{let b=c.args&&c.args.slice()||[];d===1?b.push("--node-ipc"):d===0?b.push("--stdio"):d===2?(h=(0,p.generateRandomPipeName)(),b.push(`--pipe=${h}`)):HC.isSocket(d)&&b.push(`--socket=${d.port}`),b.push(`--clientProcessId=${process.pid}`);let v=c.options||Object.create(null);if(v.env=i(v.env,!0),v.execArgv=v.execArgv||[],v.cwd=u,v.silent=!0,g&&(v.execPath=g),d===1||d===0){let x=pn.fork(c.module,b||[],v);r(x),this._serverProcess=x,NC.info(`Language server "${this.id}" started with ${x.pid}`),x.stderr.on("data",s),d===1?(x.stdout.on("data",s),f({reader:new p.IPCMessageReader(this._serverProcess),writer:new p.IPCMessageWriter(this._serverProcess)})):f({reader:new p.StreamMessageReader(x.stdout),writer:new p.StreamMessageWriter(x.stdin)})}else{if(d===2)return(0,p.createClientPipeTransport)(h).then(x=>{let C=pn.fork(c.module,b||[],v);r(C),NC.info(`Language server "${this.id}" started with ${C.pid}`),this._serverProcess=C,C.stderr.on("data",s),C.stdout.on("data",s),x.onConnected().then(k=>{f({reader:k[0],writer:k[1]})})});if(HC.isSocket(d))return(0,p.createClientSocketTransport)(d.port).then(x=>{let C=pn.fork(c.module,b||[],v);r(C),this._serverProcess=C,NC.info(`Language server "${this.id}" started with ${C.pid}`),C.stderr.on("data",s),C.stdout.on("data",s),x.onConnected().then(k=>{f({reader:k[0],writer:k[1]})})})}})}else if(p0.is(a)&&a.command){let c=a,d=c.args||[],h=Object.assign({},c.options);h.env=h.env?Object.assign({},process.env,h.env):process.env,h.cwd=h.cwd||u;let g=y.expand(a.command),f=pn.spawn(g,d,h);return f.on("error",m=>{this.error(m.message,m)}),!f||!f.pid?Promise.reject(new Error(`Launching server "${this.id}" using command ${c.command} failed.`)):(NC.info(`Language server "${this.id}" started with ${f.pid}`),f.on("exit",m=>{m!=0&&this.error(`${c.command} exited with code: ${m}`)}),f.stderr.on("data",m=>this.outputChannel.append($e(m)?m:m.toString(t))),this._serverProcess=f,this._isDetached=!!h.detached,Promise.resolve({reader:new p.StreamMessageReader(f.stdout),writer:new p.StreamMessageWriter(f.stdin)}))}return Promise.reject(`Unsupported server configuration ${JSON.stringify(o,null,2)}`)})}logMessage(t){let i=this.clientOptions.stdioEncoding;this.outputChannel.append($e(t)?t:t.toString(i))}},BC=class{constructor(e,t){this._client=e;this._setting=t;this._listeners=[]}start(){return y.onDidChangeConfiguration(e=>{e.affectsConfiguration(this._setting)&&this.onDidChangeConfiguration()},null,this._listeners),this.onDidChangeConfiguration(),{dispose:()=>{W(this._listeners),this._client.dispose()}}}onDidChangeConfiguration(){let e=this._setting.indexOf("."),t=e>=0?this._setting.substr(0,e):this._setting,i=e>=0?this._setting.substr(e+1):void 0,r=i?y.getConfiguration(t).get(i,!0):y.getConfiguration(t);r&&this._client.needsStart()?this._client.start().catch(o=>this._client.error("Start failed after configuration change",o,"force")):!r&&this._client.needsStop()&&this._client.stop().catch(o=>this._client.error("Stop failed after configuration change",o,"force"))}}});function Afe(n){let e=n.map(t=>typeof t=="string"?t:t.language);return e=e.filter(t=>typeof t=="string"),Array.from(new Set(e))}function Nfe(n,e,t,i){let{command:r,module:o,port:s,args:a,filetypes:l}=t;if(a=a||[],!l)return P.showErrorMessage(`Wrong configuration of LS "${e}", filetypes not found`),null;if(!r&&!o&&!s)return P.showErrorMessage(`Wrong configuration of LS "${e}", no command or module specified.`),null;let u;if(o){if(o=y.expand(o),!F.existsSync(o))return P.showErrorMessage(`Module file "${o}" not found for LS "${e}"`),null;u={module:o,runtime:t.runtime??process.execPath,args:a,transport:qfe(t),options:Wfe(t)}}else r?u={command:r,args:a,options:Yfe(t)}:u=()=>new Promise((f,m)=>{let b=new FB.Socket,v=t.host??"127.0.0.1";lu.info(`languageserver "${n}" connecting to ${v}:${s}`),b.connect(s,v,()=>{f({reader:b,writer:b})}),b.on("error",x=>{m(new Error(`Connection error for ${n}: ${x.message}`))})});let c=Array.from(t.disabledFeatures||[]);for(let f of["disableWorkspaceFolders","disableCompletion","disableDiagnostics"])if(t[f]===!0){lu.warn(`Language server config "${f}" is deprecated, use "disabledFeatures" instead.`);let m=f.slice(7);c.push(m[0].toLowerCase()+m.slice(1))}let d=!!t.disableSnippetCompletion,h=t.ignoredRootPaths??[];return[{workspaceFolder:i==null?void 0:{name:R.basename(i.fsPath),uri:i.toString()},rootPatterns:t.rootPatterns,requireRootPattern:t.requireRootPattern,ignoredRootPaths:h.map(f=>y.expand(f)),disableSnippetCompletion:d,disableDynamicRegister:!!t.disableDynamicRegister,disabledFeatures:c,formatterPriority:t.formatterPriority,documentSelector:T4(t.filetypes,t.additionalSchemes),revealOutputChannelOn:Bfe(t.revealOutputChannelOn),synchronize:{configurationSection:`${n}.settings`},diagnosticCollectionName:e,outputChannelName:n,stdioEncoding:t.stdioEncoding,progressOnInitialization:t.progressOnInitialization===!0,initializationOptions:t.initializationOptions??{}},u]}function Hfe(n,e){let t=[],i=["module","command","transport"];for(let r of i){let o=e[r];o&&typeof o!="string"&&t.push(`"${r}" field of languageserver ${n} should be string`)}return e.transportPort!=null&&typeof e.transportPort!="number"&&t.push(`"transportPort" field of languageserver ${n} should be number`),(!Array.isArray(e.filetypes)||!e.filetypes.every(r=>typeof r=="string"))&&t.push(`"filetypes" field of languageserver ${n} should be array of string`),e.additionalSchemes&&(!Array.isArray(e.additionalSchemes)||e.additionalSchemes.some(r=>typeof r!="string"))&&t.push(`"additionalSchemes" field of languageserver ${n} should be array of string`),t.length?(lu.error(`Invalid language server configuration for ${n}`,t.join(` +`)),!1):!0}function Bfe(n){switch(n){case"info":return 1;case"warn":return 2;case"error":return 3;case"never":return 4;default:return 4}}function T4(n,e){let t=[],i=["file","untitled"].concat(e||[]);return n?(n.forEach(r=>{t.push(...i.map(o=>({language:r,scheme:o})))}),t):i.map(r=>({scheme:r}))}function qfe(n){let{transport:e,transportPort:t}=n;return!e||e=="ipc"?1:e=="stdio"?0:e=="pipe"?2:{kind:3,port:t}}function Wfe(n){return{cwd:n.cwd,execArgv:n.execArgv??[],env:n.env??void 0}}function Yfe(n){return{cwd:n.cwd,detached:!!n.detached,shell:!!n.shell,env:n.env??void 0}}function S4(n){switch(n){case 2:return 3;case 3:return 1;case 1:return 5;default:return}}function D4(n){switch(n){case 2:return"running";case 3:return"starting";case 1:return"stopped";default:return"unknown"}}function Zfe(n){switch(n){case 0:return"init";case 3:return"running";case 1:return"starting";case 2:return"startFailed";case 4:return"stopping";case 5:return"stopped";default:return"unknown"}}var lu,w0,v0,xn,um=D(()=>{"use strict";Je();Pe();y0();xe();te();de();Be();U();We();he();lu=Z("services"),w0=(s=>(s[s.Initial=0]="Initial",s[s.Starting=1]="Starting",s[s.StartFailed=2]="StartFailed",s[s.Running=3]="Running",s[s.Stopping=4]="Stopping",s[s.Stopped=5]="Stopped",s))(w0||{}),v0=class{constructor(){this.registered=new Map;this.disposables=[];this.pendingNotifications=new Map;this.registLanguageClient=this.registerLanguageClient.bind(this),this.regist=this.register.bind(this)}init(){y.onDidOpenTextDocument(i=>{this.start(i)},null,this.disposables);let e=i=>{for(let r of i)this.registerClientsFromFolder(r)};y.onDidChangeWorkspaceFolders(i=>{e(i.added)},null,this.disposables);let t=y.initialConfiguration.get("languageserver",{});this.registerClientsByConfig(t),e(y.workspaceFolders),y.onDidChangeConfiguration(i=>{if(i.affectsConfiguration("languageserver")){let r=y.getConfiguration("languageserver",null);this.registerClientsByConfig(r)}},null,this.disposables)}registerClientsFromFolder(e){let t=O.parse(e.uri),r=y.getConfiguration(void 0,t).inspect("languageserver").workspaceFolderValue;this.registerClientsByConfig(r,t)}register(e){let{id:t}=e;if(!this.registered.get(t))return this.registered.set(t,e),this.tryStartService(e),e.onServiceReady(()=>{lu.info(`service ${t} started`)},null,this.disposables),p.Disposable.create(()=>{!this.registered.has(t)||(e.dispose(),this.registered.delete(t))})}tryStartService(e){if(_.ready)this.shouldStart(e)&&e.start();else{let t=_.on("ready",()=>{t.dispose(),this.shouldStart(e)&&e.start()})}}getService(e){let t=this.registered.get(e);return t||(t=this.registered.get(`languageserver.${e}`)),t}shouldStart(e){if(e.state!=0)return!1;let t=e.selector;for(let i of y.documents)if(y.match(t,i.textDocument))return!0;return!1}async start(e){let t=[];for(let i of this.registered.values())i.state==0&&y.match(i.selector,e)>0&&t.push(i);await Promise.allSettled(t.map(i=>i.start()))}stop(e){let t=this.registered.get(e);if(t)return Promise.resolve(t.stop())}async toggle(e){let t=this.registered.get(e);if(!t)throw new Error(`Service ${e} not found`);let{state:i}=t;i==3?await Promise.resolve(t.stop()):i==0||i==2?await t.start():i==5&&await t.restart()}getServiceStats(){let e=[];for(let[t,i]of this.registered)e.push({id:t,languageIds:Afe(i.selector),state:Zfe(i.state)});return e}registerClientsByConfig(e,t){for(let i of Object.keys(Ue(e))){let r=e[i];!Hfe(i,r)||this.registerLanguageClient(i,r,t)}}async getLanguageClient(e){let t=this.getService(e);if(t||await Zi(100),t=this.getService(e),!t||!t.client)throw new Error(`Language server ${e} not found`);return t.client}async sendNotification(e,t,i){let r=await this.getLanguageClient(e);await Promise.resolve(r.sendNotification(t,i))}async sendRequest(e,t,i,r){let o=await this.getLanguageClient(e);return r=r??p.CancellationToken.None,await Promise.resolve(o.sendRequest(t,i,r))}registerNotification(e,t){let i=this.getService(e);i&&i.client&&i.client.onNotification(t,async o=>{this.sendNotificationVim(e,t,o)});let r=this.pendingNotifications.get(e)??[];r.push({id:e,method:t}),this.pendingNotifications.set(e,r)}getRegisteredNotifications(e){return e=e.startsWith("languageserver")?e.slice(15):e,this.pendingNotifications.get(e)??[]}sendNotificationVim(e,t,i){y.nvim.call("coc#do_notify",[e,t,i],!0)}registerLanguageClient(e,t,i){let r=typeof e=="string"?`languageserver.${e}`:e.id,o=[],s=new p.Emitter,a=typeof e=="string"?null:e;if(this.registered.has(r))return p.Disposable.create(()=>{});a&&typeof a.dispose=="function"&&o.push(a);let l=!1,u={id:r,client:a,name:typeof e=="string"?e:e.name,selector:typeof e=="string"?T4(t.filetypes,t.additionalSchemes):e.clientOptions.documentSelector,state:a&&a.state===2?3:0,onServiceReady:s.event,start:async()=>{if(!l){if(typeof e=="string"&&!a){let c=y.getConfiguration(void 0,i).get(`languageserver.${e}`,{}),d=Nfe(r,e,c,i);if(!d||c.enable===!1)return;a=new Cd(r,e,d[1],d[0]),u.selector=d[0].documentSelector,u.client=a,o.push(a)}l=!0;for(let c of this.getRegisteredNotifications(r))u.client.onNotification(c.method,async d=>{this.sendNotificationVim(c.id,c.method,d)});a.onDidChangeState(c=>{let{oldState:d,newState:h}=c;u.state=S4(h);let g=D4(d),f=D4(h);lu.info(`LanguageClient ${a.name} state change: ${g} => ${f}`)},null,o)}try{a.needsStart()?(u.state=1,lu.debug(`starting service: ${r}`),await a.start(),s.fire(void 0)):u.state=S4(a.state)}catch(c){P.showErrorMessage(`Server ${r} failed to start: ${c}`),lu.error(`Server ${r} failed to start:`,c),u.state=2}},dispose:async()=>{s.dispose(),W(o)},stop:async()=>{!a||!a.needsStop()||await Promise.resolve(a.stop())},restart:async()=>{a?(u.state=1,await a.restart()):await u.start()}};return this.register(u)}dispose(){W(this.disposables);for(let e of this.registered.values())e.dispose();this.registered.clear()}};xn=new v0});var cm,k4=D(()=>{"use strict";um();te();Mo();jo();cm=class extends hi{constructor(){super();this.defaultAction="toggle";this.description="registered services of coc.nvim";this.name="services";this.addAction("toggle",async t=>{let{id:i}=t.data;await xn.toggle(i),await Zi(50)},{persist:!0,reload:!0})}async loadItems(t){let i=xn.getServiceStats();return Pr(this.alignColumns,i.map(r=>({label:[r.state=="running"?"*":" ",r.id,`[${r.state}]`,r.languageIds.join(", ")],data:{id:r.id}})))}doHighlight(){let{nvim:t}=this;t.pauseNotification(),t.command("syntax match CocServicesPrefix /\\v^./ contained containedin=CocServicesLine",!0),t.command("syntax match CocServicesName /\\v%3c\\S+/ contained containedin=CocServicesLine",!0),t.command("syntax match CocServicesStat /\\v\\t\\[\\w+\\]/ contained containedin=CocServicesLine",!0),t.command("syntax match CocServicesLanguages /\\v(\\])@<=.*$/ contained containedin=CocServicesLine",!0),t.command("highlight default link CocServicesPrefix Special",!0),t.command("highlight default link CocServicesName Type",!0),t.command("highlight default link CocServicesStat Statement",!0),t.command("highlight default link CocServicesLanguages Comment",!0),t.resumeNotification(!1,!0)}}});var dm,P4=D(()=>{"use strict";ae();Je();uu();Mo();jo();dm=class extends hi{constructor(){super();this.defaultAction="toggle";this.description="registered completion sources";this.name="sources";this.addAction("toggle",async t=>{let{name:i}=t.data;Pi.toggleSource(i)},{persist:!0,reload:!0}),this.addAction("refresh",async t=>{let{name:i}=t.data;await Pi.refresh(i)},{persist:!0,reload:!0}),this.addAction("open",async(t,i)=>{let{location:r}=t;r&&await this.jumpTo(r,null,i)})}async loadItems(){return Pi.sourceStats().map(i=>{let r=i.disabled?" ":"*",o;return i.filepath&&(o=Ke.create(O.file(i.filepath).toString(),M.create(0,0,0,0))),{label:`${r} ${Xf(i.name,22)} ${Xf("["+i.shortcut+"]",10)} ${Xf(i.triggerCharacters.join(""),10)} ${Xf(i.priority.toString(),3)} ${i.filetypes.join(",")}`,location:o,data:{name:i.name}}})}doHighlight(){let{nvim:t}=this;t.pauseNotification(),t.command("syntax match CocSourcesPrefix /\\v^./ contained containedin=CocSourcesLine",!0),t.command("syntax match CocSourcesName /\\v%3c\\S+/ contained containedin=CocSourcesLine",!0),t.command("syntax match CocSourcesType /\\v%25v.*%36v/ contained containedin=CocSourcesLine",!0),t.command("syntax match CocSourcesPriority /\\v%46v.*%52v/ contained containedin=CocSourcesLine",!0),t.command("syntax match CocSourcesFileTypes /\\v\\S+$/ contained containedin=CocSourcesLine",!0),t.command("highlight default link CocSourcesPrefix Special",!0),t.command("highlight default link CocSourcesName Type",!0),t.command("highlight default link CocSourcesPriority Number",!0),t.command("highlight default link CocSourcesFileTypes Comment",!0),t.command("highlight default link CocSourcesType Statement",!0),t.resumeNotification(!1,!0)}}});function R4(n){let e=Ke.create(n.uri,M.create(n.range.start,n.range.start));return e.targetRange=n.range,e}function Jfe(n,e){return n.data.score!=e.data.score?e.data.score-n.data.score:n.data.kind!=e.data.kind?n.data.kind-e.data.kind:n.data.file.length-e.data.file.length}var hm,_4=D(()=>{"use strict";ae();Se();Re();im();de();U();fe();he();jo();zf();hm=class extends oo{constructor(){super(...arguments);this.interactive=!0;this.description="search workspace symbols";this.detail="Symbols list is provided by server, it works on interactive mode only.";this.fuzzyMatch=y.createFuzzyMatch();this.name="symbols";this.options=[{name:"-k, -kind KIND",description:"Filter symbols by kind.",hasValue:!0}]}async loadItems(t,i){let{input:r}=t,o=this.parseArguments(t.args),s=o.kind?o.kind.toString().toLowerCase():"";if(!I.hasProvider("workspaceSymbols",{uri:"file:///1",languageId:""}))throw new Error("No workspace symbols provider registered");let a=await I.getWorkspaceSymbols(r,i);if(i.isCancellationRequested)return[];let u=this.getConfig().get("excludes",[]),c=[];this.fuzzyMatch.setPattern(r,!0);for(let d of a){let h=ks(d.kind);if(s&&h.toLowerCase()!=s)continue;let g=Mx(d.location.uri,y.cwd);if(u.some(m=>ni(g,m)))continue;let f=this.createListItem(r,d,h,g);c.push(f)}return this.fuzzyMatch.free(),c.sort(Jfe),c}async resolveItem(t){let i=t.data.original;if(!i)return null;let r=new p.CancellationTokenSource,o=await I.resolveWorkspaceSymbol(i,r.token);return o?(i.location=o.location,t.location=R4(o.location),t):null}createListItem(t,i,r,o){let{name:s}=i,a="",l=[],u=[s,`[${r}]`,o],c=["Normal","Typedef","Comment"];for(let h=0;h0){let h=this.fuzzyMatch.matchHighlights(s,"CocListSearch");h&&(d=h.score,l.push(...h.highlights))}return{label:a,filterText:"",ansiHighlights:l,location:R4(i.location),data:{original:i,input:t,kind:i.kind,file:o,score:d}}}}});function Xfe(n,e,t){let i={};i[`list.source.${n}.defaultAction`]={type:"string",default:null,description:`Default action of "${n}" list.`},i[`list.source.${n}.defaultOptions`]={type:"array",default:e?["--interactive"]:[],description:`Default list options of "${n}" list, only used when both list option and argument are empty.`,uniqueItems:!0,items:{type:"string",enum:["--top","--normal","--no-sort","--input","--height","--tab","--strict","--regex","--ignore-case","--number-select","--reverse","--interactive","--auto-preview","--first","--no-quit"]}},i[`list.source.${n}.defaultArgs`]={type:"array",default:[],description:`Default argument list of "${n}" list, only used when list argument is empty.`,uniqueItems:!0,items:{type:"string"}};let r={scope:1,properties:i};return t&&(r.extensionInfo={id:t}),r}var $fe,E4,Ufe,x0,qi,WC=D(()=>{"use strict";Nv();vo();Pe();nu();xe();te();Yt();rs();de();U();wo();fe();We();he();Fa();KE();nQ();rQ();hQ();pQ();fQ();mQ();bQ();yQ();vQ();zf();wQ();k4();P4();_4();$fe=Z("list-manager"),E4=["","","","<2-LeftMouse>"],Ufe=vi?50:0,x0=class{constructor(){this.plugTs=0;this.sessionsMap=new Map;this.disposables=[];this.listMap=new Map;iu.migrate(Gn)}get nvim(){return y.nvim}init(e){this.prompt=new Yf(e),this.mappings=new Wf(this,e);let t=lt.get("selectedSignText","*");e.command(`sign define CocSelected text=${t} texthl=CocSelectedText linehl=CocSelectedLine`,!0),_.on("InputChar",this.onInputChar,this,this.disposables),_.on("FocusGained",async()=>{await this.getCurrentSession()&&this.prompt.drawPrompt()},null,this.disposables),_.on("WinEnter",r=>{let o=this.getSessionByWinid(r);o&&this.prompt.start(o.listOptions)},null,this.disposables);let i;_.on("WinLeave",r=>{clearTimeout(i),this.getSessionByWinid(r)&&(i=setTimeout(()=>{this.prompt.cancel()},Ufe))},null,this.disposables),y.onDidChangeConfiguration(r=>{r.source!==0&&r.affectsConfiguration("list")&&this.mappings.createMappings()},null,this.disposables),this.prompt.onDidChangeInput(()=>{var r;(r=this.session)==null||r.onInputChange()})}registerLists(){this.registerList(new em,!0),this.registerList(new oo,!0),this.registerList(new hm,!0),this.registerList(new nm,!0),this.registerList(new Gf,!0),this.registerList(new Qf(Ht.manager),!0),this.registerList(new Kf(this),!0),this.registerList(new dm,!0),this.registerList(new cm,!0),this.registerList(new tm(this.listMap),!0),this.registerList(new Vf,!0)}async start(e){let t=this.parseArgs(e);if(!t)return;let{name:i}=t.list,r=this.sessionsMap.get(i);r&&r.dispose(),this.prompt.start(t.options);let o=new Uf(this.nvim,this.prompt,t.list,t.options,t.listArgs);this.sessionsMap.set(i,o),this.lastSession=o;try{await o.start(e)}catch(s){this.nvim.command('echo ""',!0),this.nvim.call("coc#prompt#stop_prompt",["list"],!0),P.showErrorMessage(`Error on "CocList ${i}": ${yr(s)}`),this.nvim.redrawVim(),$fe.error("Error on list start:",s)}}getSessionByWinid(e){for(let t of this.sessionsMap.values())if(t&&t.winid==e)return this.lastSession=t,t;return null}async getCurrentSession(){let{id:e}=await this.nvim.window;for(let t of this.sessionsMap.values())if(t&&t.winid==e)return this.lastSession=t,t;return null}async resume(e){var t;if(!e)await((t=this.session)==null?void 0:t.resume());else{let i=this.sessionsMap.get(e);if(!i){P.showWarningMessage(`Can't find exists ${e} list`);return}await i.resume()}}async doAction(e){let t=this.lastSession;!t||await t.doAction(e)}async first(e){let t=this.getSession(e);t&&await t.first()}async last(e){let t=this.getSession(e);t&&await t.last()}async previous(e){let t=this.getSession(e);t&&await t.previous()}async next(e){let t=this.getSession(e);t&&await t.next()}getSession(e){return e?this.sessionsMap.get(e):this.session}async cancel(e=!0){this.prompt.cancel(),!!e&&this.session&&await this.session.hide()}reset(){this.prompt.cancel(),this.lastSession=void 0;for(let e of this.sessionsMap.values())e.dispose();this.sessionsMap.clear(),this.nvim.call("coc#prompt#stop_prompt",["list"],!0)}async switchMatcher(){var e;await((e=this.session)==null?void 0:e.switchMatcher())}async togglePreview(){let{nvim:e}=this;await e.call("coc#list#get_preview",[0])!=-1?(await e.call("coc#list#close_preview",[]),await e.command("redraw")):await this.doAction("preview")}async chooseAction(){let{lastSession:e}=this;e&&await e.chooseAction()}parseArgs(e){let t=[],i=!1,r=!1,o=!1,s=!1,a=!1,l=!1,u,c="",d="fuzzy",h="bottom",g=[],f=[],m;for(let x of e)if(!u&&x.startsWith("-"))f.push(x);else if(u)g.push(x);else{if(!/^\w+$/.test(x))return P.showErrorMessage(`Invalid list option: "${x}"`),null;u=x}u=u||"lists";let b=y.initialConfiguration.get(`list.source.${u}`);!f.length&&!g.length&&(f=Ie(b==null?void 0:b.defaultOptions,[])),g.length||(g=Ie(b==null?void 0:b.defaultArgs,[]));for(let x of f)if(x.startsWith("--input="))c=x.slice(8);else if(x.startsWith("--height="))m=uZ(x.slice(9));else if(x=="--number-select"||x=="-N")o=!0;else if(x=="--auto-preview"||x=="-A")r=!0;else if(x=="--regex"||x=="-R")d="regex";else if(x=="--strict"||x=="-S")d="strict";else if(x=="--interactive"||x=="-I")i=!0;else if(x=="--top")h="top";else if(x=="--tab")h="tab";else if(x=="--ignore-case"||x=="--normal"||x=="--no-sort")t.push(x.slice(2));else if(x=="--first")a=!0;else if(x=="--reverse")l=!0;else if(x=="--no-quit")s=!0;else return P.showErrorMessage(`Invalid option "${x}" of list`),null;let v=this.listMap.get(u);return v?i&&!v.interactive?(P.showErrorMessage(`Interactive mode of "${u}" list not supported`),null):{list:v,listArgs:g,options:{numberSelect:o,autoPreview:r,height:m,reverse:l,noQuit:s,first:a,input:c,interactive:i,matcher:d,position:h,ignorecase:!!t.includes("ignore-case"),mode:t.includes("normal")?"normal":"insert",sort:!t.includes("no-sort")}}:(P.showErrorMessage(`List ${u} not found`),null)}async onInputChar(e,t,i){if(!t||e!="list")return;let{mode:r}=this.prompt,o=Date.now();if(t==""||this.plugTs&&o-this.plugTs<20){this.plugTs=o;return}if(t==""){await this.cancel();return}r=="insert"?await this.onInsertInput(t,i):await this.onNormalInput(t,i)}async onInsertInput(e,t){let{session:i}=this;if(E4.includes(e)){await this.onMouseEvent(e);return}if(!(!i||await i.doNumberSelect(e)||await this.mappings.doInsertKeymap(e)||t)){if(e.startsWith("<")&&e.endsWith(">")){await this.feedkeys(e,!1);return}for(let s of e){let a=s.codePointAt(0);if(a==65533||a<32||a>=127&&a<=159)return;await this.prompt.acceptCharacter(s)}}}async onNormalInput(e,t){if(E4.includes(e)){await this.onMouseEvent(e);return}await this.mappings.doNormalKeymap(e)||await this.feedkeys(e)}onMouseEvent(e){var t;return(t=this.session)==null?void 0:t.onMouseEvent(e)}async feedkeys(e,t=!0){let{nvim:i}=this;e=e.startsWith("<")&&e.endsWith(">")?`\\${e}`:e,await i.call("coc#prompt#stop_prompt",["list"]),await i.call("eval",[`feedkeys("${e}", "${t?"i":"in"}")`]),this.triggerCursorMoved(),this.prompt.start()}async command(e){let{nvim:t}=this;await t.call("coc#prompt#stop_prompt",["list"]),await t.command(e),this.triggerCursorMoved(),this.prompt.start()}async normal(e,t){let{nvim:i}=this;await i.call("coc#prompt#stop_prompt",["list"]),await i.command(`normal${t?"!":""} ${e}`),this.triggerCursorMoved(),this.prompt.start()}triggerCursorMoved(){this.nvim.isVim&&this.nvim.command("doautocmd CursorMoved",!0)}async call(e){if(this.session)return await this.session.call(e)}get session(){return this.lastSession}registerList(e,t=!1){let{name:i,interactive:r}=e,o;t||(o=pe(xl(Error().stack),void 0));let s=this.deregisterList(i);this.listMap.set(i,e);let a=Xfe(i,r,o);return s||y.configurations.updateConfigurations([a]),p.Disposable.create(()=>{this.deregisterList(i),li.as(Il.Configuration).deregisterConfigurations([a])})}deregisterList(e){let t=this.listMap.get(e);return t?(typeof t.dispose=="function"&&t.dispose(),this.listMap.delete(e),!0):!1}get names(){return Array.from(this.listMap.keys())}get descriptions(){let e={};for(let t of this.listMap.keys()){let i=this.listMap.get(t);e[t]=i.description}return e}async loadItems(e){let t=[e],i=this.parseArgs(t);if(!i||!e)return;let{list:r,options:o,listArgs:s}=i,l=new p.CancellationTokenSource().token,u=await this.nvim.eval('[win_getid(),bufnr("%")]'),c=await r.loadItems({options:o,args:s,input:"",cwd:y.cwd,window:this.nvim.createWindow(u[0]),buffer:this.nvim.createBuffer(u[1]),listWindow:null},l);if(!c||Array.isArray(c))return c;let d=c;return await new Promise((g,f)=>{let m=[];d.on("data",b=>{b.label=Hb(b.label),m.push(b)}),d.on("end",()=>{g(m)}),d.on("error",b=>{f(b)})})}toggleMode(){let e=this.lastSession;e&&e.toggleMode()}get isActivated(){var e;return((e=this.session)==null?void 0:e.winid)!=null}stop(){let e=this.lastSession;e&&e.stop()}dispose(){for(let e of this.sessionsMap.values())e.dispose();this.sessionsMap.clear(),this.lastSession=void 0,W(this.disposables)}},qi=new x0});function C0(n,e){let{range:t,newText:i}=n,r=e.length,o=i.length;if(r===0||o===0)return n;let{start:s,end:a}=t,l=0;for(let h=1;h<=Math.min(o,r)&&i[h-1]===e[h-1];h++)l=h;let u=0,c=Math.min(o-l,r-l);if(c>0)for(let h=1;h<=c&&i[o-h]===e[r-h];h++)u=h;let d=u==0?i.slice(l):i.slice(l,-u);return l>0&&(s=on(s,i.slice(0,l))),u>0&&(a=on(t.start,e.slice(0,-u))),Ye.replace(M.create(s,a),d)}function I4(n,e,t){let i=M.create(n,on(n,t));return Ft(e,i)==0}function L4(n,e,t){if(t.lines.length=0;o--){let s=t.lines[o]??"";if(o===n.line){let a=e.lines[o].slice(0,n.character);if(!s.startsWith(a)){r=!1;break}}else if(s!==e.lines[o]){r=!1;break}}return r}function F4(n,e,t){let i=e.lines.length;if(t.lines.length{let l=s.match(/^\s*/)[0],u=l,c=l.startsWith(" ");return c&&t.insertSpaces?u=r.repeat(l.length):!c&&!t.insertSpaces&&(u=r.repeat(l.length/o)),(a==0||s.length==0?"":e)+u+s.slice(l.length)}),i.join(` +`)}function O4(n){return!!(/^\s/.test(n)||n.indexOf(` +`)!==-1)}function Gfe(n,e){return n.primary!==e.primary?n.primary?-1:1:n.index==0||e.index==0?n.index==0?1:-1:n.index-e.index}var gm,S0=D(()=>{"use strict";Wg();ae();te();Tt();wr();pR();sw();gm=class{constructor(e,t,i,r){this.snippetString=e;this.position=t;this.nvim=i;this.resolver=r}async init(e,t=!1){let i=e?nw(e):void 0,o=new ds(!!e,i).parse(this.snippetString,!0);this.tmSnippet=o,await this.resolve(e),this.synchronize(),t||(this.nvim.call("coc#compat#del_var",["coc_selected_text"],!0),this.nvim.call("coc#compat#del_var",["coc_last_placeholder"],!0))}async resolve(e){let{snippet:t}=this.tmSnippet,{resolver:i,nvim:r}=this;if(i&&await t.resolveVariables(i),e&&e.noPython!==!0){let o=[];t.hasPython&&(o=fX(e)),await t.evalCodeBlocks(r,o)}}getRanges(e){let t=e.marker;if(e.value.length==0)return[];let r=this._placeholders.filter(l=>l.index==e.index).map(l=>l.range),o=this.tmSnippet.enclosingPlaceholders(t),s,a=t.parent;if(t instanceof kt){let l=t.index;s=this.tmSnippet.placeholders.filter(u=>u.index==l&&u.parent==a)}else{let l=t.name;s=this.tmSnippet.variables.filter(u=>u.name==l&&u.parent==a)}return o.forEach(l=>{let u=this._placeholders.filter(c=>c.index==l.index&&c.marker!==l);if(!!u.length)for(let c of s){let d=this.tmSnippet.getTextBefore(c,l);u.forEach(h=>{if(h.transform)r.push(h.range);else{let g=h.range.start;r.push(M.create(on(g,d),on(g,d+c.toString())))}})}}),r.filter(l=>!Gt(l))}getSortedPlaceholders(e){let t=e?[e]:[],i=this._placeholders.filter(r=>r!==e&&!r.transform);return i.sort(Gfe),t.push(...i),t}get hasPython(){return this.tmSnippet.pyBlocks.length>0}resetStartPosition(e){this.position=e,this.synchronize()}get start(){return Object.assign({},this.position)}get range(){return M.create(this.position,on(this.position,this._text))}get text(){return this._text}get finalCount(){return this._placeholders.filter(e=>e.index==0).length}get placeholders(){return this._placeholders.map(e=>e.marker)}get firstPlaceholder(){let e=0;for(let t of this._placeholders)t.index==0||t.transform||(e==0||t.indext.marker===e)}getPlaceholder(e){let t=this._placeholders.filter(r=>r.index==e&&!r.transform),i=t.find(r=>r.primary);return Ie(i,t[0])}getPrevPlaceholder(e){if(e<=1)return;let t=this._placeholders.filter(r=>r.index1;){e=e-1;let r=t.filter(o=>o.index==e);if(r.length){i=Ie(r.find(o=>o.primary),r[0]);break}}return i}getNextPlaceholder(e){let t=this._placeholders.filter(s=>!s.transform),i,r=t.map(s=>s.index),o=Math.max.apply(null,r);for(let s=e+1;s<=o+1;s++){let a=s==o+1?0:s,l=t.filter(u=>u.index==a);if(l.length){i=l.find(u=>u.primary)||l[0];break}}return i}getPlaceholderByRange(e){return this._placeholders.find(t=>ti(e,t.range))}async insertSnippet(e,t,i,r){if(r){let{start:s,end:a}=e.range;this.nvim.setVar("coc_last_placeholder",{current_text:e.value,start:{line:s.line,col:s.character,character:s.character},end:{line:a.line,col:a.character,character:a.character}},!0)}let o=this.tmSnippet.insertSnippet(t,e.marker,i,r);return await this.resolve(r),this.synchronize(),o}getNewText(e,t){let{before:i,after:r}=e;if(!!t.startsWith(i)&&!(t.length{this.tmSnippet=l,this.synchronize()});let u=M.create(o,on(o,a));if(await this.tmSnippet.update(this.nvim,s,i),r.isCancellationRequested)return;this.synchronize();let c=this.getTextBefore(s,a);return{text:this._text,delta:Yv(t,Ye.replace(u,c))}}getTextBefore(e,t){let i=this._placeholders.find(r=>r.marker==e);return i?i.before:t}removeText(e,t){let i=this.tmSnippet.deleteText(e,t);return i&&this.synchronize(),i}synchronize(){let e=this.tmSnippet,{line:t,character:i}=this.position,r=Qr.create("untitled:/1","snippet",0,e.toString()),{placeholders:o,variables:s,maxIndexNumber:a}=e,l=new Map,u=a+1;this._placeholders=[...o,...s].map(c=>{let d=e.offset(c),h=r.positionAt(d),g={line:t+h.line,character:h.line==0?i+h.character:h.character},f;if(c instanceof to){let x=c.name;l.has(x)?f=l.get(x):(l.set(x,u),f=u,u=u+1)}else f=c.index;let m=c.toString(),b=on(h,m);return{index:f,value:m,marker:c,transform:!!c.transform,range:M.create(g,on(g,m)),before:r.getText(M.create(Q.create(0,0),h)),after:r.getText(M.create(b,Q.create(r.lineCount,0))),primary:c instanceof kt&&c.primary===!0}}),this._text=this.tmSnippet.toString()}}});function pm(n){return n<10?"0"+n:n.toString()}function A4(n){let e,t,i,r=n.split(",");for(let o of r){if(e&&t&&i)break;if(!o.includes(":"))continue;let[s,a]=o.split(":");s.includes("s")?e=a:s.includes("e")?t=a:!i&&s==""&&(i=a)}return{start:e,end:t,single:i}}function zfe(n){if(n.endsWith("%s"))return n.slice(0,-2).trim()}var fm,N4=D(()=>{"use strict";rt();Je();de();Be();fm=class{constructor(e,t){this.nvim=e;this.workspaceFolder=t;this._variableToValue={};let i=new Date,r=i.getFullYear().toString();Object.assign(this._variableToValue,{CURRENT_YEAR:r,CURRENT_YEAR_SHORT:r.slice(-2),CURRENT_MONTH:pm(i.getMonth()+1),CURRENT_DATE:pm(i.getDate()),CURRENT_HOUR:pm(i.getHours()),CURRENT_MINUTE:pm(i.getMinutes()),CURRENT_SECOND:pm(i.getSeconds()),CURRENT_DAY_NAME:i.toLocaleString("en-US",{weekday:"long"}),CURRENT_DAY_NAME_SHORT:i.toLocaleString("en-US",{weekday:"short"}),CURRENT_MONTH_NAME:i.toLocaleString("en-US",{month:"long"}),CURRENT_MONTH_NAME_SHORT:i.toLocaleString("en-US",{month:"short"}),TM_FILENAME:null,TM_FILENAME_BASE:null,TM_DIRECTORY:null,TM_FILEPATH:null,YANK:null,TM_LINE_INDEX:null,TM_LINE_NUMBER:null,TM_CURRENT_LINE:null,TM_CURRENT_WORD:null,TM_SELECTED_TEXT:null,VISUAL:null,CLIPBOARD:null,RELATIVE_FILEPATH:null,RANDOM:null,RANDOM_HEX:null,UUID:null,BLOCK_COMMENT_START:null,BLOCK_COMMENT_END:null,LINE_COMMENT:null,WORKSPACE_NAME:null,WORKSPACE_FOLDER:null})}async resolveValue(e){let{nvim:t}=this;if(["TM_FILENAME","TM_FILENAME_BASE","TM_DIRECTORY","TM_FILEPATH"].includes(e)){let i=await t.eval('expand("%:p")');if(e==="TM_FILENAME")return R.basename(i);if(e==="TM_FILENAME_BASE")return R.basename(i,R.extname(i));if(e==="TM_DIRECTORY")return R.dirname(i);if(e==="TM_FILEPATH")return i}if(e==="YANK")return await t.call("getreg",['""']);if(e==="TM_LINE_INDEX")return(await t.call("line",["."])-1).toString();if(e==="TM_LINE_NUMBER")return(await t.call("line",["."])).toString();if(e==="TM_CURRENT_LINE")return await t.call("getline",["."]);if(e==="TM_CURRENT_WORD")return await t.eval("expand('')");if(e==="TM_SELECTED_TEXT"||e=="VISUAL")return await t.eval("get(g:,'coc_selected_text', v:null)");if(e==="CLIPBOARD")return await t.eval("@*");if(e==="RANDOM")return Math.random().toString().slice(-6);if(e==="RANDOM_HEX")return Math.random().toString(16).slice(-6);if(e==="UUID")return me();if(["RELATIVE_FILEPATH","WORKSPACE_NAME","WORKSPACE_FOLDER"].includes(e)){let i=await t.eval('expand("%:p")'),r=this.workspaceFolder.getWorkspaceFolder(O.file(i));if(e==="RELATIVE_FILEPATH")return this.workspaceFolder.getRelativePath(i);if(e==="WORKSPACE_NAME")return r.name;if(e==="WORKSPACE_FOLDER")return O.parse(r.uri).fsPath}if(e==="LINE_COMMENT"){let i=await t.eval("&commentstring"),r=zfe(i);if(r)return r;let o=await t.eval("&comments"),{single:s}=A4(o);return s}if(["BLOCK_COMMENT_START","BLOCK_COMMENT_END"].includes(e)){let i=await t.eval("&comments"),{start:r,end:o}=A4(i);if(e==="BLOCK_COMMENT_START")return r;if(e==="BLOCK_COMMENT_END")return o}}async resolve(e){let t=e.name,i=this._variableToValue[t];if(i!=null)return i.toString();if(Rn(this._variableToValue,t)){let r=await this.resolveValue(t);return!r&&e.children.length?e.toString():r==null?"":r.toString()}return e.children.length?e.toString():t}}});var Rs,D0,mm,H4=D(()=>{"use strict";ae();xe();ls();Be();Tt();U();fe();We();he();sw();S0();N4();Rs=Z("snippets-session"),D0="snippets",mm=class{constructor(e,t,i){this.nvim=e;this.document=t;this.config=i;this.mutex=new ji;this._applying=!1;this._isActive=!1;this._snippet=null;this._onCancelEvent=new p.Emitter;this.onCancel=this._onCancelEvent.event;this.disposable=t.onDocumentChange(async r=>{if(this._applying||!this._isActive)return;let o=r.contentChanges;await this.synchronize({version:r.textDocument.version,change:o[0]})})}async start(e,t,i=!0,r){let{document:o}=this,s=this.getReplacePlaceholder(t),a=[];if(s){let l=this.snippet.range,u=o.textDocument.getText(l),c=M4(s.value,s.range,t);this.current=await this.snippet.insertSnippet(s,e,c,r);let d=C0({range:l,newText:this.snippet.text},u);a.push(d)}else{let l=new fm(this.nvim,y.workspaceFolderControl),u=new gm(e,t.start,this.nvim,l);if(await u.init(r),this._snippet=u,this.current=u.firstPlaceholder.marker,a.push(Ye.replace(t,u.text)),e.replace(/\$0$/,"").endsWith(` +`)){let c=o.getline(t.start.line),d=c.slice(t.end.character);if(d.length){let h=t.end.character,g=d.match(/^\s*/)[0].length,f=M.create(t.end.line,h,t.end.line,h+g);a.push(Ye.replace(f,c.match(/^\s*/)[0]))}}}if(await this.applyEdits(a),this.textDocument=o.textDocument,this.activate(),i&&this.current){let l=this.snippet.getPlaceholderByMarker(this.current);await this.selectPlaceholder(l,!0)}return this._isActive}async applyEdits(e){this._applying=!0,await this.document.applyEdits(e),this._applying=!1}getReplacePlaceholder(e){if(!this.snippet)return;let t=this.findPlaceholder(e);if(!(!t||t.index==0))return t}activate(){this._isActive||(this._isActive=!0,this.nvim.call("coc#snippet#enable",[this.config.preferComplete?1:0],!0))}deactivate(){this.cancel(),this._isActive&&(this.disposable.dispose(),this._isActive=!1,this._snippet=void 0,this.current=null,this.nvim.call("coc#snippet#disable",[],!0),this.config.highlight&&this.nvim.call("coc#highlight#clear_highlight",[this.bufnr,D0,0,-1],!0),this._onCancelEvent.fire(void 0),Rs.debug(`session ${this.bufnr} cancelled`))}get isActive(){return this._isActive}get bufnr(){return this.document.bufnr}async nextPlaceholder(){await this.forceSynchronize();let e=this.placeholder;if(!e)return;let t=this.snippet.getNextPlaceholder(e.index);t&&await this.selectPlaceholder(t)}async previousPlaceholder(){await this.forceSynchronize();let e=this.placeholder;if(!e)return;let t=this.snippet.getPrevPlaceholder(e.index);t&&await this.selectPlaceholder(t)}async selectCurrentPlaceholder(e=!0){if(await this.forceSynchronize(),!this.snippet)return;let t=this.snippet.getPlaceholderByMarker(this.current);t&&await this.selectPlaceholder(t,e)}async selectPlaceholder(e,t=!0){let{nvim:i,document:r}=this;if(!r||!e)return;let{start:o,end:s}=e.range,a=r.getline(o.line),l=nt(a,o.character)+1,u=this.current=e.marker;if(u instanceof kt&&u.choice&&u.choice.options.length)(await Promise.resolve().then(()=>(uu(),T0))).default.setWords(u.choice.options.map(d=>d.value)),await i.call("coc#snippet#show_choices",[o.line+1,l,s,e.value]),t&&i.call("coc#util#do_autocmd",["CocJumpPlaceholder"],!0);else{let c=this.snippet.finalCount;await this.select(e,t),this.highlights(e),e.index==0&&(c==1?(Rs.info("Jump to final placeholder, cancelling snippet session"),this.deactivate()):i.call("coc#snippet#disable",[],!0))}}highlights(e,t=!0){if(!this.config.highlight)return;let i=this.document.buffer;this.nvim.pauseNotification(),i.clearNamespace(D0);let r=this.snippet.getRanges(e);r.length&&i.highlightRanges(D0,"CocSnippetVisual",r),this.nvim.resumeNotification(t,!0)}async select(e,t){let{range:i,value:r}=e,{nvim:o}=this;r.length>0?await o.call("coc#snippet#select",[i.start,i.end,r]):await o.call("coc#snippet#move",[i.start]),t&&o.call("coc#util#do_autocmd",["CocJumpPlaceholder"],!0),o.redrawVim()}async checkPosition(){if(!this.isActive)return;let e=await P.getCursorPosition();this.snippet&&Ft(e,this.snippet.range)!=0&&(Rs.info("Cursor insert out of range, cancelling snippet session"),this.deactivate())}findPlaceholder(e){let{placeholder:t}=this;return t&&ti(e,t.range)?t:this.snippet.getPlaceholderByRange(e)||null}get version(){return this.textDocument?this.textDocument.version:-1}async synchronize(e){await this.mutex.use(()=>(e&&(this.document.version!=e.version||e.version-this.version!==1)&&(e=void 0),this._synchronize(e?e.change:void 0)))}async _synchronize(e){let{document:t,textDocument:i}=this;if(!t.attached||!this._isActive)return;let r=Date.now(),o=t.textDocument;if(o.version==i.version||Me(i.lines,o.lines))return;let{range:s,text:a}=this.snippet;e&&!ti(e.range,s)&&(e=void 0);let l=F4(s.end,i,o);if(!l){Rs.info("Content change after snippet, cancel snippet session"),this.deactivate();return}if(!L4(s.start,i,o)){let v=o.getText(M.create(Q.create(0,0),l));if(v.endsWith(a)){let x=o.positionAt(v.length-a.length);this.snippet.resetStartPosition(x),this.textDocument=o,Rs.info("Content change before snippet, reset snippet position");return}Rs.info("Before and snippet body changed, cancel snippet session"),this.deactivate();return}let c=this.tokenSource=new p.CancellationTokenSource,d=await P.getCursorPosition();if(c.token.isCancellationRequested||t.hasChanged)return;let h,g,f=o.getText(M.create(s.start,l)),m=this.placeholder;if(e){for(let v of this.snippet.getSortedPlaceholders(m))if(ti(e.range,v.range)){h=v,g=this.snippet.getNewText(v,f);break}if(!h&&e.text.length==0&&!Gt(e.range)&&sU(e.range)){let v=e.range.end.character-e.range.start.character,x=o.getText(M.create(s.start,e.range.start)).length;if(this.snippet.removeText(x,v)){this.textDocument=o;return}}}else for(let v of this.snippet.getSortedPlaceholders(m))if(!(Ge(d,v.range.start)<0)&&(g=this.snippet.getNewText(v,f),g!=null&&I4(v.range.start,d,g))){h=v;break}if(!h&&f.endsWith(a)){let v=on(s.start,f.slice(0,-a.length));this.snippet.resetStartPosition(v),this.textDocument=o,Rs.info("Content change before snippet, reset snippet position");return}if(!h){Rs.info("Unable to find changed placeholder, cancel snippet session"),this.deactivate();return}let b=await this.snippet.updatePlaceholder(h,d,g,c.token);if(!(b==null||c.token.isCancellationRequested)){if(t.dirty||!Me(t.textDocument.lines,o.lines)){c.cancel(),c.dispose();return}if(c.dispose(),this.current=h.marker,b.text!==f){let v=C0({range:M.create(this.snippet.start,l),newText:b.text},f);await this.applyEdits([v]);let{delta:x}=b;(x.line!=0||x.character!=0)&&this.nvim.call("coc#cursor#move_to",[d.line+x.line,d.character+x.character],!0),this.highlights(h,!1),this.nvim.redrawVim()}else this.highlights(h);if(Rs.debug("update cost:",Date.now()-r,b.delta),this.textDocument=this.document.textDocument,this.config.nextOnDelete&&m&&m.value.length>0&&h.marker.toString()===""){let v=this.snippet.getNextPlaceholder(h.index);v&&await this.selectPlaceholder(v)}}}async forceSynchronize(){await this.document.patchChange(),(await this.mutex.acquire())(),this.document.version!==this.version&&await this.synchronize()}cancel(){this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource.dispose(),this.tokenSource=null)}get placeholder(){if(!(!this.snippet||!this.current))return this.snippet.getPlaceholderByMarker(this.current)}get snippet(){return this._snippet}static async resolveSnippet(e,t,i){let r=i&&M.is(i.range)?i.range.start:await P.getCursorPosition(),o=i&&typeof i.line=="string"?i.line:await e.line,s;i&&(s=Object.assign({range:M.create(r,r),line:o},i));let a=new fm(e,y.workspaceFolderControl),l=new gm(t,r,e,a);return await l.init(s,!0),l.text}}});var _r,k0=D(()=>{"use strict";_r=class{constructor(e){this._tabstop=1;this.value=e||""}static isSnippetString(e){return e instanceof _r?!0:e?typeof e.value=="string":!1}static _escape(e){return e.replace(/\$|}|\\/g,"\\$&")}appendText(e){return this.value+=_r._escape(e),this}appendTabstop(e=this._tabstop++){return this.value+="$",this.value+=e,this}appendPlaceholder(e,t=this._tabstop++){if(typeof e=="function"){let i=new _r;i._tabstop=this._tabstop,e(i),this._tabstop=i._tabstop,e=i.value}else e=_r._escape(e);return this.value+="${",this.value+=t,this.value+=":",this.value+=e,this.value+="}",this}appendChoice(e,t=this._tabstop++){let i=e.map(r=>r.replace(/\$|}|\\|,/g,"\\$&")).join(",");return this.value+="${",this.value+=t,this.value+="|",this.value+=i,this.value+="|}",this}appendVariable(e,t){if(typeof t=="function"){let i=new _r;i._tabstop=this._tabstop,t(i),this._tabstop=i._tabstop,t=i.value}else typeof t=="string"&&(t=t.replace(/\$|}/g,"\\$&"));return this.value+="${",this.value+=e,t&&(this.value+=":",this.value+=t),this.value+="}",this}}});var P0,pi,cu=D(()=>{"use strict";ae();Dt();Pe();te();Be();Tt();We();he();H4();S0();k0();P0=class{constructor(){this.sessionMap=new Map;this.disposables=[]}init(){_.on("InsertCharPre",(e,t)=>{let i=this.getSession(t);i&&i.cancel()},null,this.disposables),_.on("InsertEnter",async e=>{let t=this.getSession(e);t&&await t.checkPosition()},null,this.disposables),y.onDidCloseTextDocument(e=>{let t=this.getSession(e.bufnr);t&&t.deactivate()},null,this.disposables),P.onDidChangeActiveTextEditor(e=>{if(!this._statusItem)return;this.getSession(e.document.bufnr)?this.statusItem.show():this.statusItem.hide()},null,this.disposables),V.register({id:"editor.action.insertSnippet",execute:async(e,t)=>{let i=t===!0?{}:t;return await this.insertSnippet(e.newText,!0,e.range,mr.adjustIndentation,i||void 0)}},!0)}get nvim(){return y.nvim}get statusItem(){if(this._statusItem)return this._statusItem;let e=this._statusItem=P.createStatusBarItem(0),t=y.initialConfiguration.get("snippet");return e.text=Ie(t.statusText,""),this._statusItem}getSnippetConfig(e){let t=y.getConfiguration("coc.preferences",e),i=y.getConfiguration("snippet",e),r=y.getConfiguration("suggest",e);return{highlight:t.get("snippetHighlight",i.get("highlight",!1)),nextOnDelete:t.get("nextPlaceholderOnDelete",i.get("nextPlaceholderOnDelete",!1)),preferComplete:r.get("preferCompleteThanJumpPlaceholder",!1)}}async insertSnippet(e,t=!0,i,r,o){let{bufnr:s}=y,a=y.getAttachedDocument(s);if(i&&!ti(i,M.create(0,0,a.lineCount+1,0)))throw new Error("Unable to insert snippet, invalid range.");let l;if(!i){let f=await P.getCursorPosition();i=M.create(f,f)}let u=a.getline(i.start.line),c=_r.isSnippetString(e)?e.value:e,d=await this.normalizeInsertText(a.uri,c,u,r);o!=null&&(l=Object.assign({range:Li(i),line:u},o),!Gt(i)&&d.includes("`!p")&&(this.nvim.call("coc#cursor#move_to",[i.start.line,i.start.character],!0),await a.applyEdits([{range:i,newText:""}]),i.end=Q.create(i.start.line,i.start.character)));let h=this.getSession(s);if(h?(await h.forceSynchronize(),h=this.getSession(s)):await a.patchChange(!0),!h){let f=this.getSnippetConfig(a.uri);h=new mm(this.nvim,a,f),h.onCancel(()=>{this.sessionMap.delete(s),this.statusItem.hide()})}let g=await h.start(d,i,t,l);return g?(this.statusItem.show(),this.sessionMap.set(s,h)):(this.statusItem.hide(),this.sessionMap.delete(s)),g}async selectCurrentPlaceholder(e=!0){let{session:t}=this;if(t)return await t.selectCurrentPlaceholder(e)}async nextPlaceholder(){let{session:e}=this;return e?await e.nextPlaceholder():(this.nvim.call("coc#snippet#disable",[],!0),this.statusItem.hide()),""}async previousPlaceholder(){let{session:e}=this;return e?await e.previousPlaceholder():(this.nvim.call("coc#snippet#disable",[],!0),this.statusItem.hide()),""}cancel(){let e=this.getSession(y.bufnr);if(e)return e.deactivate();this.nvim.call("coc#snippet#disable",[],!0),this.statusItem&&this.statusItem.hide()}get session(){return this.getSession(y.bufnr)}getSession(e){return this.sessionMap.get(e)}jumpable(){let{session:e}=this;return e?e.placeholder!=null&&e.placeholder.index!=0:!1}async editsInsideSnippet(e){let t=this.getSession(y.bufnr);if(!t||!t.snippet)return!1;await t.forceSynchronize();let i=t.snippet.range;return!!e.some(r=>Tc(r.range,i))}async resolveSnippet(e,t){if(t){let i=this.getSession(y.bufnr);i!=null&&i.snippet.hasPython&&(t.noPython=!1)}return await mm.resolveSnippet(this.nvim,e,t)}async normalizeInsertText(e,t,i,r){let o="";if(r===mr.asIs||!O4(t))o=t;else{let s=i.match(/^\s*/)[0],a=P.activeTextEditor?P.activeTextEditor.options:await y.getFormatOptions(e);o=j4(t,s,a)}return o}dispose(){this.cancel();for(let e of this.disposables)e.dispose()}},pi=new P0});var bm,B4=D(()=>{"use strict";fe();bm=class{constructor(e=!1){this.addSpace=e;this._label="";this._len=0;this._highlights=[]}append(e,t,i){if(e.length==0)return;let r=this._len>0&&this.addSpace?" ":"",o=this._len+r.length;if(this._label=this._label+r+e,this._len=this._len+ue(e)+r.length,t&&this._highlights.push({hlGroup:t,span:[o,o+ue(e)]}),i)for(let s of i){let a=o+nt(e,s.offset),l=o+nt(e,s.offset+s.length);this._highlights.push({hlGroup:s.hlGroup,span:[a,l]})}}appendBuilder(e){let t=this._len>0&&this.addSpace?" ":"",i=this._len+t.length;this._label=this._label+t+e.label,this._len=this._len+ue(e.label)+t.length,this._highlights.push(...e.highlights.map(r=>({hlGroup:r.hlGroup,span:r.span.map(o=>i+o)})))}get label(){return this._label}get highlights(){return this._highlights}}});function Kfe(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function Qfe(n){return typeof n>"u"||Kfe(n)}var Sd,q4=D(()=>{"use strict";ae();Sd=class{constructor(e){if(this._prevLine=0,this._prevChar=0,this._dataIsSortedAndDeltaEncoded=!0,this._data=[],this._dataLen=0,this._tokenTypeStrToInt=new Map,this._tokenModifierStrToInt=new Map,this._hasLegend=!1,e){this._hasLegend=!0;for(let t=0,i=e.tokenTypes.length;t"u"))return typeof o>"u"&&(o=0),this._pushEncoded(e,t,i,r,o);if(M.is(e)&&typeof t=="string"&&Qfe(i))return this._push(e,t,i);throw new Error("Illegal argument")}_push(e,t,i){if(!this._hasLegend)throw new Error("Legend must be provided in constructor");if(e.start.line!==e.end.line)throw new Error("`range` cannot span multiple lines");if(!this._tokenTypeStrToInt.has(t))throw new Error("`tokenType` is not in the provided legend");let r=e.start.line,o=e.start.character,s=e.end.character-e.start.character,a=this._tokenTypeStrToInt.get(t),l=0;if(i)for(let u of i){if(!this._tokenModifierStrToInt.has(u))throw new Error("`tokenModifier` is not in the provided legend");let c=this._tokenModifierStrToInt.get(u);l|=1<>>0}this._pushEncoded(r,o,s,a,l)}_pushEncoded(e,t,i,r,o){if(this._dataIsSortedAndDeltaEncoded&&(e0&&(s-=this._prevLine,s===0&&(a-=this._prevChar)),this._data[this._dataLen++]=s,this._data[this._dataLen++]=a,this._data[this._dataLen++]=i,this._data[this._dataLen++]=r,this._data[this._dataLen++]=o,this._prevLine=e,this._prevChar=t}static _sortAndDeltaEncode(e){let t=[],i=e.length/5|0;for(let a=0;a{let u=e[5*a],c=e[5*l];if(u===c){let d=e[5*a+1],h=e[5*l+1];return d-h}return u-c});let r=new Array(e.length),o=0,s=0;for(let a=0;a{"use strict";vp()});var R0=w((u3e,Y4)=>{"use strict";ae();Je();Dt();Hc();Pe();nu();Se();Mo();WC();ZE();ww();CP();ha();Tg();VE();um();cu();k0();uu();yc();Ii();ls();U();We();he();y0();B4();q4();W4();te();st();Tl();vo();pa();iw();Y4.exports={get nvim(){return y.nvim},Uri:O,LineBuilder:bm,NullLogger:am,SettingMonitor:BC,LanguageClient:Cd,CancellationTokenSource:p.CancellationTokenSource,ProgressType:p.ProgressType,RequestType:p.RequestType,RequestType0:p.RequestType0,NotificationType:p.NotificationType,NotificationType0:p.NotificationType0,ProtocolRequestType:p.ProtocolRequestType,ProtocolRequestType0:p.ProtocolRequestType0,ProtocolNotificationType:p.ProtocolNotificationType,ProtocolNotificationType0:p.ProtocolNotificationType0,Highligher:zi,Mru:Gr,Emitter:p.Emitter,SnippetString:_r,BasicList:hi,Mutex:ji,TreeItem:Vr,SemanticTokensBuilder:Sd,FloatFactory:Pl,RelativePattern:ja,CancellationError:Rt,WorkspaceChange:mk,ResponseError:p.ResponseError,Trace:p.Trace,DocumentUri:Th,WorkspaceFolder:Vh,InlineValueText:Xh,InlineValueVariableLookup:Gh,InlineValueEvaluatableExpression:zh,InlineValueContext:Kh,InlayHintKind:Br,InlayHintLabelPart:tc,InlayHint:Qh,DiagnosticRelatedInformation:ec,SemanticTokens:$s,SemanticTokenTypes:St,SemanticTokenModifiers:nn,AnnotatedTextEdit:_n,ChangeAnnotation:zo,SymbolTag:$i,Command:En,Color:Vu,CodeDescription:Ih,ColorInformation:Ph,ColorPresentation:Rh,TextDocumentEdit:Qt,TextDocumentIdentifier:Lh,VersionedTextDocumentIdentifier:Fh,TextDocumentItem:Mh,DocumentHighlight:Bh,SelectionRange:Uh,DocumentLink:pl,CodeLens:Jh,FormattingOptions:$h,CodeAction:Zh,CodeActionContext:Yh,DocumentSymbol:Js,WorkspaceSymbol:Wh,CreateFile:Un,RenameFile:Xn,WorkspaceEdit:Ys,InsertReplaceEdit:gl,InsertTextMode:mr,CompletionItem:Oh,CompletionList:Ah,Hover:Vo,ParameterInformation:Nh,SignatureInformation:Hh,SymbolInformation:qh,MarkupContent:Ln,ErrorCodes:p.ErrorCodes,CompletionItemTag:Ko,integer:kh,uinteger:cl,FoldingRangeKind:_h,FoldingRange:Eh,ChangeAnnotationIdentifier:Ti,DeleteFile:In,OptionalVersionedTextDocumentIdentifier:dl,CompletionItemLabelDetails:jh,MarkedString:Qo,ProviderName:jt,DocumentDiagnosticReportKind:p.DocumentDiagnosticReportKind,UniquenessLevel:p.UniquenessLevel,MonikerKind:p.MonikerKind,PatternType:tw,SourceType:Fc,ConfigurationTarget:kg,ServiceStat:w0,FileType:ev,State:AC,ClientState:h0,CloseAction:_C,ErrorAction:EC,TransportKind:qC,MessageTransports:xd,RevealOutputChannelOn:OC,MarkupKind:fr,DiagnosticTag:Ji,DocumentHighlightKind:Zs,SymbolKind:De,SignatureHelpTriggerKind:p.SignatureHelpTriggerKind,FileChangeType:p.FileChangeType,CodeActionKind:ri,Diagnostic:Hr,DiagnosticSeverity:it,CompletionItemKind:ie,InsertTextFormat:hl,Location:Ke,LocationLink:pr,CancellationToken:p.CancellationToken,Position:Q,Range:M,TextEdit:Ye,Disposable:p.Disposable,Event:p.Event,workspace:y,window:P,CodeActionTriggerKind:es,CompletionTriggerKind:p.CompletionTriggerKind,snippetManager:pi,events:_,services:xn,commands:V,sources:Pi,languages:I,diagnosticManager:ui,extensions:Ht,listManager:qi,TreeItemCollapsibleState:Ml,terminate:gv,fetch:gf,download:Nf,ansiparse:Mg,disposeAll:W,concurrent:Vd,watchFile:dc,wait:Zi,runCommand:xo,isRunning:zZ,executable:Dl}});function ime(n){return()=>{throw new Error(`process.${n}() is not allowed in extension sandbox`)}}function nme(n){let e=t=>t==="coc.nvim"?Ue(n):this.require(t);return e.resolve=t=>Oa._resolveFilename(t,this),e.main=eme,e.extensions=Oa._extensions,e.cache=Oa._cache,e}function rme(n,e){return function(t,i){let r=nme.call(this,e),o=R.dirname(i),s=t.startsWith("#!")?t.replace(/^#!.*/,""):t,a=Oa.wrap(s),l=aD.runInContext(a,n,{filename:i}),u=[this.exports,r,this,i,o];return l.apply(this.exports,u)}}function ome(n){if(Rn(n.prototype,"_compile"))return n.prototype;if(Rn(n.prototype.__proto__,"_compile"))return n.prototype.__proto__;throw new Error("_compile not found")}function sme(n,e,t,i=!1){let r=new Oa(n);r.paths=Oa._nodeModulePaths(n);let o=aD.createContext({module:r,Buffer,URL:globalThis.URL,console:{debug:(...a)=>{e.debug.apply(e,a)},log:(...a)=>{e.info.apply(e,a)},error:(...a)=>{e.error.apply(e,a)},info:(...a)=>{e.info.apply(e,a)},warn:(...a)=>{e.warn.apply(e,a)}}},{name:t});UX(o,global),o.Reflect=Reflect;let s=i?void 0:R0();o.require=function(l){let u=_0._compile;_0._compile=rme(o,s);let c=o.module.require(l);return _0._compile=u,c},o.process=new process.constructor;for(let a of Object.keys(process))o.process[a]=process[a];return tme.forEach(a=>{o.process[a]=ime(a)}),o.process.chdir=()=>{},o.process.umask=a=>{if(typeof a<"u")throw new Error("Cannot use process.umask() to change mask (read-only)");return process.umask()},o}function ame(n,e){return n?Vfe:Z(`extension:${e}`)}function Z4(n,e,t){if(t||!F.existsSync(e))return{activate:()=>{},deactivate:null};let i=ame(!global.__isMain&&!0,n),r=sme(e,i,n);delete Oa._cache[require.resolve(e)];let o=r.require(e),s=o&&o.activate||o;return typeof s!="function"?{activate:()=>{}}:typeof o=="function"?{activate:s}:Object.assign({},o)}var Vfe,Oa,eme,tme,_0,J4=D(()=>{"use strict";xe();de();io();Be();Vfe={category:"",log:console.log.bind(console),debug:console.debug.bind(console),error:console.error.bind(console),warn:console.warn.bind(console),info:console.info.bind(console),trace:console.log.bind(console),fatal:console.error.bind(console),mark:console.log.bind(console)},Oa=require("module"),eme=require.main,tme=["reallyExit","abort","umask","setuid","setgid","setgroups","_fatalException","exit","kill"];_0=ome(Oa)});function YC(n,e){let t,i,r;return{start(o){r=o,t=Date.now(),clearTimeout(i),e&&(i=setTimeout(()=>{$4.error(`${n} timeout after ${e}ms`)},e),i.unref())},stop(){clearTimeout(i),$4.trace(`${n}${r?` ${r}`:""} cost:`,Date.now()-t)}}}var $4,E0=D(()=>{"use strict";xe();$4=Z("timing")});function lme(n){return n==="daily"?U4:U4*7}function X4(n,e){let t=[];return Dd(n,e,t)!=null&&t.length==0}function G4(n){return n?n.endsWith(".js")?n:n+".js":"index.js"}async function z4(n,e){let t=R.join(n,"package.json"),i=await Cg(t,"utf8"),r=JSON.parse(i),{engines:o}=r,s=G4(r.main);if(!o||typeof o.coc!="string"&&typeof o.vscode!="string")throw new Error("Invalid engines field");if(Object.keys(o).includes("coc")&&!sr.satisfies(e,o.coc.replace(/^\^/,">=")))throw new Error(`coc.nvim version not match, required ${o.coc}`);if(!o.vscode&&!F.existsSync(R.join(n,s)))throw new Error(`main file ${s} not found, you may need to build the project.`);return r}function Dd(n,e,t){let i=R.join(n,"package.json");if(!F.existsSync(i)){t.push(`package.json not found in ${n}`);return}let r=_s(i),{name:o,engines:s}=r,a=G4(r.main);if(o||t.push("can't find name in package.json"),(!s||!xt(s))&&t.push(`invalid engines in ${i}`),s&&!s.vscode&&!F.existsSync(R.join(n,a))&&t.push(`main file ${a} not found, you may need to build the project.`),s){let l=Object.keys(s);if(!l.includes("coc")&&!l.includes("vscode")&&t.push("Engines in package.json doesn't have coc or vscode"),l.includes("coc")){let u=s.coc.replace(/^\^/,">=");sr.satisfies(e,u)||t.push(`Please update coc.nvim, ${r.name} requires coc.nvim ${s.coc}`)}}return r}function ume(n){return/^https?:/.test(n)||!n.includes("@")?n:n.replace(/@[\d.]+$/,"")}function K4(n){try{F.existsSync(n)||F.mkdirSync(n,{recursive:!0}),F.statSync(n).isDirectory()||(I0.info(`Trying to delete ${n}`),F.unlinkSync(n),F.mkdirSync(n,{recursive:!0}));let t=R.join(n,"package.json");F.existsSync(t)||F.writeFileSync(t,'{"dependencies":{}}',"utf8")}catch(e){return console.error(`Unexpected error when check data home ${n}: ${e}`),!1}return!0}async function Q4(n){return F.existsSync(n)?(await(0,ot.promisify)(F.readdir)(n)).filter(t=>t.endsWith(".js")):[]}function _s(n){try{let e=F.readFileSync(n,"utf8"),t=JSON.parse(e);return Ue(t)}catch(e){return I0.error(`Error on parse json file ${n}`,e),{}}}var I0,U4,ZC,L0=D(()=>{"use strict";xe();Re();st();Xe();de();Be();I0=Z("extension-stat"),U4=24*60*60*1e3,ZC=class{constructor(e){this.folder=e;this.disabled=new Set;this.locked=new Set;this.extensions=new Set;this.localExtensions=new Map;try{this.migrate()}catch(t){I0.error(`Error on update package.json at ${e}`,t)}}migrate(){let e=_s(this.jsonFile),t=R.join(this.folder,"db.json"),i=!1;if(F.existsSync(t)){let o=_s(t),s=o.extension??{};for(let[a,l]of Object.entries(s))l.disabled&&this.disabled.add(a),l.locked&&this.locked.add(a);e.disabled=Array.from(this.disabled),e.locked=Array.from(this.locked),e.lastUpdate-o.lastUpdate,F.unlinkSync(t),i=!0}else this.disabled=new Set(e.disabled??[]),this.locked=new Set(e.locked??[]);i&&Ks(this.jsonFile,e);let r=Object.keys(e.dependencies??{});this.extensions=new Set(r)}*activated(){let{disabled:e}=this;for(let t of Object.keys(this.dependencies))e.has(t)||(yield t)}addLocalExtension(e,t){this.localExtensions.set(e,t)}getFolder(e){return this.extensions.has(e)?R.join(this.folder,"node_modules",e):this.localExtensions.get(e)}getExtensionsStat(){let e={};for(let t of this.extensions)this.disabled.has(t)?e[t]=1:this.locked.has(t)?e[t]=2:e[t]=0;return e}hasExtension(e){return this.extensions.has(e)}addExtension(e,t){let i=_s(this.jsonFile);i.dependencies=i.dependencies??{},i.dependencies[e]=t,this.extensions.add(e),Ks(this.jsonFile,i)}removeExtension(e){let t=_s(this.jsonFile);t.disabled&&(t.disabled=t.disabled.filter(i=>i!==e)),t.locked&&(t.locked=t.locked.filter(i=>i!==e)),t.dependencies=t.dependencies??{},delete t.dependencies[e],this.extensions.delete(e),Ks(this.jsonFile,t)}isDisabled(e){return this.disabled.has(e)}get lockedExtensions(){return Array.from(this.locked)}get disabledExtensions(){return Array.from(this.disabled)}get dependencies(){return _s(this.jsonFile).dependencies??{}}setDisable(e,t){t?this.disabled.add(e):this.disabled.delete(e),this.update("disabled",Array.from(this.disabled))}setLocked(e,t){t?this.locked.add(e):this.locked.delete(e),this.update("locked",Array.from(this.disabled))}setLastUpdate(){this.update("lastUpdate",Date.now())}shouldUpdate(e){if(e==="never")return!1;let t=lme(e),i=_s(this.jsonFile);return i.lastUpdate==null||Date.now()-i.lastUpdate>t}get globalIds(){let e=_s(this.jsonFile);return Object.keys(e.dependencies??{})}filterGlobalExtensions(e){let t=this.disabledExtensions,i=this.dependencies,r=new Map;le(e).forEach(a=>{if(!a||typeof a!="string")return;let l=ume(a);r.set(l,a)});let o=[],s=[];for(let[a,l]of Object.entries(i))F.existsSync(R.join(this.folder,"node_modules",a,"package.json"))&&(s.push(a),typeof l=="string"&&/^https?:/.test(l)&&o.push(l));for(let a of r.keys()){if(t.includes(a)||this.extensions.has(a)){r.delete(a);continue}(/^https?:/.test(a)&&o.some(l=>l.startsWith(a))||s.includes(a))&&r.delete(a)}return Array.from(r.values())}update(e,t){let i=_s(this.jsonFile);i[e]=t,Ks(this.jsonFile,i)}get jsonFile(){return R.join(this.folder,"package.json")}}});function eV(n){let e=[];for(let t of le(n)){let[i]=t.split(":",2);i&&!e.includes(i)&&e.push(i)}return e}function cme(n){let e=[];for(let t of le(n)){let[i,r]=t.split(":",2);i==="onCommand"&&r&&e.push(r)}return e}function dme(n,e){for(let t of e){let i=t.split(":");if(i[0]=="onLanguage"&&(n.languageId==i[1]||n.filetype==i[1]))return!0}return!1}function hme(n,e){for(let t of e){let i=t.split(":");if(i[0]=="onCommand"&&n==i[1])return!0}return!1}function gme(n,e){let t=O.parse(n).scheme;for(let i of e){let r=i.split(":");if(r[0]=="onFileSystem"&&t==r[1])return!0}return!1}function tV(n){return le(n.activationEvents).filter(e=>typeof e=="string"&&e.length>0)}function pme(n){let e=[];for(let t of n){let i=t.split(":");i[0]=="workspaceContains"&&i[1]&&e.push(i[1])}return e}var JC,F0,M0,V4,$C,iV=D(()=>{"use strict";Je();Nv();vo();iR();Pe();xe();eQ();te();Re();Yt();rs();J4();st();Xe();io();de();Be();U();wo();E0();We();he();L0();JC=Z("extensions-manager"),F0=li.as(ns.ExtensionContribution),M0=new Hf(R.resolve(Gn,"memos.json"));M0.merge(R.resolve(Gn,"../memos.json"));V4=li.as(Il.Configuration),$C=class{constructor(e,t){this.states=e;this.folder=t;this.activated=!1;this.disposables=[];this.configurationNodes=[];this.extensions=new Map;this._onDidLoadExtension=new p.Emitter;this._onDidActiveExtension=new p.Emitter;this._onDidUnloadExtension=new p.Emitter;this.singleExtensionsRoot=R.join(Fk,"coc-extensions");this.onDidLoadExtension=this._onDidLoadExtension.event;this.onDidActiveExtension=this._onDidActiveExtension.event;this.onDidUnloadExtension=this._onDidUnloadExtension.event;this.modulesFolder=R.join(this.folder,"node_modules")}activateExtensions(){if(this.activated=!0,process.env.COC_NO_PLUGINS=="1")return;V4.registerConfigurations(this.configurationNodes),this.attachEvents();let e=[];for(let t of this.extensions.keys()){let{extension:i}=this.extensions.get(t),r=i.packageJSON.activationEvents;!r||r.includes("*")?e.push(void i.activate()):this.autoActiavte(t,i)}return Promise.allSettled(e)}async loadFileExtensions(){let e=this.singleExtensionsRoot,t=await Q4(e);await Promise.allSettled(t.map(i=>this.loadExtensionFile(R.join(e,i))))}attachEvents(){y.onDidRuntimePathChange(async e=>{let t=e.filter(r=>r&&X4(r,y.version)),i=P.createOutputChannel("extensions");await Promise.allSettled(t.map(r=>(i.appendLine(`Loading extension from runtimepath: ${r}`),this.loadExtension(r))))},null,this.disposables),y.onDidOpenTextDocument(e=>{let t=y.getDocument(e.bufnr);this.tryActivateExtensions("onLanguage",i=>dme(t,i)),this.tryActivateExtensions("onFileSystem",i=>gme(t.uri,i))},null,this.disposables),_.on("Command",async e=>{let t=!1;this.tryActivateExtensions("onCommand",i=>{let r=hme(e,i);return r&&(t=!0),r}),t&&await Zi(50)},null,this.disposables),y.onDidChangeWorkspaceFolders(e=>{e.added.length>0&&this.tryActivateExtensions("workspaceContains",t=>{let i=pme(t);return y.checkPatterns(i,e.added)})},null,this.disposables)}async cleanExtensions(){let{globalIds:e}=this.states;return await Zk(this.modulesFolder),e.filter(t=>!this.states.isDisabled(t))}tryActivateExtensions(e,t){for(let i of this.extensions.values()){if(i.extension.isActive||!i.events.includes(e))continue;let{extension:o}=i,s=tV(o.packageJSON);Promise.resolve(t(s)).then(a=>{a&&Promise.resolve(o.activate())})}}async checkAutoActivate(e){let t=tV(e);if(t.length===0||t.includes("*"))return!0;let i=[];for(let r of t){let o=r.split(":"),s=o[0];if(s==="onLanguage"){if(y.languageIds.has(o[1])||y.filetypes.has(o[1]))return!0}else if(s==="workspaceContains"&&o[1])i.push(o[1]);else if(s==="onFileSystem"){for(let a of y.documents)if(O.parse(a.uri).scheme==o[1])return!0}}return!!(i.length>0&&await y.checkPatterns(i))}has(e){return this.extensions.has(e)}getExtension(e){return this.extensions.get(e)}get loadedExtensions(){return Array.from(this.extensions.keys())}get all(){return Array.from(this.extensions.values()).map(e=>e.extension)}async activate(e){let t=this.extensions.get(e);if(!t)throw new Error(`Extension ${e} not registered!`);let{extension:i}=t;return i.isActive?!0:(await Promise.resolve(i.activate()),i.isActive===!0)}async deactivate(e){let t=this.extensions.get(e);!t||!t.extension.isActive||await Promise.resolve(t.deactivate())}async loadExtension(e,t=!1){if(Array.isArray(e))return(await Promise.allSettled(e.map(l=>this.loadExtension(l,t)))).forEach(l=>{if(l.status==="rejected")throw new Error(`Error on loadExtension ${l.reason}`)}),!0;let i=[],r=Dd(e,y.version,i);if(i.length>0)throw new Error(i[0]);let{name:o}=r;if(this.states.isDisabled(o))return!1;await this.unloadExtension(o);let s=!this.states.hasExtension(o);return s&&this.states.addLocalExtension(o,e),await this.registerExtension(e,Object.freeze(r),s?1:0,t),!0}async unloadExtension(e){this.extensions.get(e)&&(await this.deactivate(e),this.extensions.delete(e),this._onDidUnloadExtension.fire(e))}async reloadExtension(e){let t=this.extensions.get(e);if(!t||t.type==3)throw new Error(`Extension ${e} not registered`);t.type==2?await this.loadExtensionFile(t.filepath):await this.loadExtension(t.directory)}async call(e,t,i){let r=this.extensions.get(e);if(!r)throw new Error(`extension ${e} not registered`);let{extension:o}=r;o.isActive||await this.activate(e);let{exports:s}=o;if(!s||typeof s[t]!="function")throw new Error(`method ${t} not found on extension ${e}`);return await Promise.resolve(s[t].apply(null,i))}registContribution(e,t,i,r){let{contributes:o,activationEvents:s}=t,{configuration:a,rootPatterns:l,commands:u}=o??{},c,d=HZ(a??{});if(!Sy(d)){let h=tv(d,2);if(xt(a.definitions)){let f=e.replace(/[^\w]/g,""),m=(b,v)=>{if(v=="$ref"){let x=b[v];$e(x)&&x.startsWith("#/definitions/")&&(b[v]=x.slice(0,14)+f+"."+x.slice(14))}};yh(h,m),c={},Object.entries(Li(a.definitions)).forEach(([b,v])=>{xt(v)&&(c[f+"."+b]=v,yh(v,m))})}let g={properties:h,extensionInfo:{id:e,displayName:t.displayName}};if(this.configurationNodes.push(g),this.activated){let f=[],m=this.configurationNodes.findIndex(b=>b.extensionInfo.id===e);m!==-1&&(f.push(this.configurationNodes[m]),this.configurationNodes.splice(m,1)),y.configurations.updateConfigurations([g],f)}}F0.registerExtension(e,{name:e,directory:i,filepath:r,commands:u,definitions:c,rootPatterns:l,onCommands:cme(s)})}getExtensionState(e){if(this.states.isDisabled(e))return"disabled";let i=this.getExtension(e);if(!i)return"unknown";let{extension:r}=i;return r.isActive?"activated":"loaded"}async autoActiavte(e,t){try{await this.checkAutoActivate(t.packageJSON)&&await Promise.resolve(t.activate())}catch(i){JC.error(`Error on activate ${e}`,i)}}async loadExtensionFile(e,t=!1){let i=await Fn(e);if(!i||!i.isFile())return;let r=R.basename(e),o=R.basename(e,".js"),s="single-"+o,a=R.dirname(e),l={name:s,main:r,engines:{coc:">=0.0.82"}},u=R.join(a,o+".json"),c=Xr(u);for(let d of["activationEvents","contributes"])l[d]=c[d];return await this.unloadExtension(s),await this.registerExtension(a,l,2,t),s}registerExtensions(e){for(let t of e)try{let i=t.isLocal?1:0;this.registerExtension(t.root,t.packageJSON,i)}catch(i){JC.error(`Error on regist extension from ${t.root}: `,i)}}async registerExtension(e,t,i,r=!1){let o=t.name;if(this.states.isDisabled(o))return;let s=!1,a,l=R.join(e,t.main||"index.js"),u=i===2?l:e,c,d,h=[],g=YC(`activate ${o}`,5e3),f={activate:()=>a||(a=new Promise(async(m,b)=>{g.start();try{let v=typeof t.engines.coc>"u";d=Z4(o,l,v);let x={subscriptions:h,extensionPath:u,globalState:M0.createMemento(`${o}|global`),workspaceState:M0.createMemento(`${o}|${y.rootPath}`),asAbsolutePath:k=>R.join(e,k),storagePath:R.join(this.folder,`${o}-data`),logger:Z(`extension:${o}`)},C=await Promise.resolve(d.activate(x));s=!0,c=C,this._onDidActiveExtension.fire(f),g.stop(),m(C)}catch(v){JC.error(`Error on active extension ${o}:`,v),b(v)}}),a),id:o,packageJSON:t,extensionPath:u,get isActive(){return s},get module(){return d},get exports(){if(!s)throw new Error(`Invalid access to exports, extension "${o}" not activated`);return c}};Object.freeze(f),this.extensions.set(o,{id:o,type:i,isLocal:i==1,extension:f,directory:e,filepath:l,events:eV(t.activationEvents),deactivate:async()=>{if(!!s&&(s=!1,a=void 0,c=void 0,W(h),d&&typeof d.deactivate=="function"))try{await Promise.resolve(d.deactivate()),d=void 0}catch(m){JC.error(`Error on ${o} deactivate: `,m)}}}),this.registContribution(o,t,e,l),this._onDidLoadExtension.fire(f),this.activated&&!r&&await this.autoActiavte(o,f)}unregistContribution(e){let t=this.configurationNodes.findIndex(i=>i.extensionInfo.id===e);if(F0.unregistExtension(e),t!==-1){let i=this.configurationNodes[t];this.configurationNodes.splice(t,1),V4.deregisterConfigurations([i])}}async registerInternalExtension(e,t){let{id:i,packageJSON:r}=e;this.extensions.set(i,{id:i,directory:__dirname,type:3,events:eV(r.activationEvents),extension:e,deactivate:t,isLocal:!0}),this.registContribution(i,r,__dirname),this._onDidLoadExtension.fire(e),await this.autoActiavte(i,e)}async uninstallExtensions(e){let[t,i]=$y(e,r=>this.states.hasExtension(r));for(let r of t)await this.unloadExtension(r),this.states.removeExtension(r),F0.unregistExtension(r),await Zk(R.join(this.modulesFolder,r));i.length>0&&P.showWarningMessage(`Global extensions ${i.join(", ")} not found`),t.length>0&&P.showInformationMessage(`Removed extensions: ${t.join(" ")}`)}async toggleExtension(e){let t=this.getExtensionState(e);if(t=="activated"&&await this.deactivate(e),t!="disabled")this.states.setDisable(e,!0),this.unregistContribution(e),await this.unloadExtension(e);else if(this.states.setDisable(e,!1),e.startsWith("single-")){let i=R.join(this.singleExtensionsRoot,`${e.replace(/^single-/,"")}.js`);await this.loadExtensionFile(i)}else{let i=this.states.getFolder(e);i?await this.loadExtension(i):P.showWarningMessage(`Extension ${e} not found`)}}async watchExtension(e){let t=this.getExtension(e);if(!t)throw new Error(`extension ${e} not found`);if(e.startsWith("single-"))P.showInformationMessage(`watching ${t.filepath}`),this.disposables.push(dc(t.filepath,async()=>{await this.loadExtensionFile(t.filepath),P.showInformationMessage(`reloaded ${e}`)},!1));else{let i=y.getWatchmanPath();if(!i)throw new Error("watchman not found");let r=await cs.createClient(i,t.directory);this.disposables.push(r),P.showInformationMessage(`watching ${t.directory}`),await r.subscribe("**/*.js",async()=>{await this.reloadExtension(e),P.showInformationMessage(`reloaded ${e}`)})}}async load(e,t){let i;if(hc(e)?(i=Xr(R.join(e,"package.json")).name,await this.loadExtension(e,!0)):i=await this.loadExtensionFile(e,!0),!i)throw new Error(`Unable to load extension at ${e}`);if(this.states.isDisabled(i))throw new Error(`extension ${i} is disabled`);let o=this.getExtension(i);return t&&await o.extension.activate(),{get isActive(){return o.extension.isActive},get name(){return i},get api(){return o.extension.exports},get exports(){let s=o.extension.module??{};return ci(s,["activate"])},unload:()=>this.unloadExtension(i)}}dispose(){W(this.disposables)}}});var fme,UC,mme,XC,nV=D(()=>{"use strict";Pe();oR();te();de();U();fe();We();he();fme=pe(100,1),UC=class{constructor(e,t){this.isUpdate=e;this.channel=t}start(e){this.channel.appendLine(`${this.isUpdate?"Updating":"Installing"} ${e.join(", ")}`)}addMessage(e,t,i){i||this.channel.appendLine(`${e} - ${t}`)}startProgress(e){this.channel.appendLine(`Start ${this.isUpdate?"update":"install"} ${e}`)}finishProgress(e,t){t?this.channel.appendLine(`${e} ${this.isUpdate?"update":"install"} succeed!`):this.channel.appendLine(`${e} ${this.isUpdate?"update":"install"} failed!`)}},mme=pe(500,10),XC=class{constructor(e){this.isUpdate=e;this.statMap=new Map;this.updated=new Set;this.messagesMap=new Map;this.disposables=[];this.names=[];let t=P.createFloatFactory({modes:["n"]});this.disposables.push(t);let i=ft(async(r,o)=>{if(r==this.bufnr){let s=this.getMessages(o[0]-1),a=s.length>0?[{content:s.join(` +`),filetype:"txt"}]:[];await t.show(a)}},mme);this.disposables.push(p.Disposable.create(()=>{i.clear()})),_.on("CursorMoved",i,this.disposables),_.on("BufUnload",r=>{r===this.bufnr&&this.dispose()},null,this.disposables)}async start(e){this.statMap.clear(),this.names=e;for(let t of e)this.statMap.set(t,0);await this.show()}addMessage(e,t){let i=this.messagesMap.get(e)||[];this.messagesMap.set(e,i.concat(t.trim().split(/\r?\n/))),(t.startsWith("Updated to")||t.startsWith("Installed extension"))&&this.updated.add(e)}startProgress(e){this.statMap.set(e,2)}finishProgress(e,t){this.statMap.set(e,t?3:1)}get remains(){let e=0;for(let t of this.names){let i=this.statMap.get(t);[3,1].includes(i)||(e=e+1)}return e}getLinesAndHighlights(e){let t=[],i=[];for(let r of this.names){let o=this.statMap.get(r),s="*",a,l=e+t.length;switch(o){case 2:{let h=new Date,g=Math.floor(h.getMilliseconds()/100);s=rR[g],a=void 0;break}case 1:s="\u2717",a="ErrorMsg";break;case 3:s="\u2713",a=this.updated.has(r)?"MoreMsg":"Comment";break}let u=this.messagesMap.get(r)||[],c=`- ${s} `,d=ue(c);a&&i.push({hlGroup:a,lnum:l,colStart:d,colEnd:d+ue(r)}),t.push(`${c}${r} ${u.length?u[u.length-1]:""}`)}return{lines:t,highlights:i}}getMessages(e){let t=this.names[e-2];return this.messagesMap.get(t)??[]}get stopped(){return this.interval==null}draw(){let{remains:e,bufnr:t}=this,{nvim:i}=y;if(!t)return;let r=i.createBuffer(t),o=e==0?`${this.isUpdate?"Update":"Install"} finished`:`Installing, ${e} remaining...`,{lines:s,highlights:a}=this.getLinesAndHighlights(2);i.pauseNotification(),r.setLines([o,"",...s],{start:0,end:-1,strictIndexing:!1},!0),r.updateHighlights("coc-extensions",a,{priority:99}),e==0&&this.interval&&(clearInterval(this.interval),this.interval=null),i.resumeNotification(!0,!0)}highlight(){let{nvim:e}=y;e.call("matchadd",["CocListFgCyan","^\\-\\s\\zs\\*"],!0),e.call("matchadd",["CocListFgGreen","^\\-\\s\\zs\u2713"],!0),e.call("matchadd",["CocListFgRed","^\\-\\s\\zs\u2717"],!0)}async show(){let e=_.requesting===!0,{nvim:t}=y;t.pauseNotification(),t.command(e?"enew":"vs +enew",!0),t.call("bufnr",["%"],!0),t.command("setl buftype=nofile bufhidden=wipe noswapfile nobuflisted wrap undolevels=-1",!0),e||t.command("nnoremap q :q",!0),this.highlight();let i=await t.resumeNotification();this.bufnr=i[0][1],this.interval=setInterval(()=>{this.draw()},fme)}dispose(){this.bufnr=void 0,this.messagesMap.clear(),this.statMap.clear(),W(this.disposables),clearInterval(this.interval),this.interval=null}}});function bme(n){return Cy(n)?n.replace(/\.git(#master|#main)?$/,""):""}var ym,GC,j0,Ht,nu=D(()=>{"use strict";Dt();vo();xe();te();Re();Yt();Xe();de();Tl();We();he();V3();iV();L0();nV();ym=Z("extensions-index"),GC=R.join(Gn,"extensions"),j0=class{constructor(){this.modulesFolder=R.join(GC,"node_modules");K4(GC),this.states=new ZC(GC),this.manager=new $C(this.states,GC),V.register({id:"extensions.forceUpdateAll",execute:async()=>{let e=await this.manager.cleanExtensions();ym.info(`Force update extensions: ${e}`),await this.installExtensions(e)}},!1,"remove all global extensions and install them"),this.globalPromise=this.globalExtensions(),V.register({id:"extensions.toggleAutoUpdate",execute:async()=>{let e=y.getConfiguration("coc.preferences",null),t=e.get("extensionUpdateCheck","daily"),i=1;t=="never"?(await e.update("extensionUpdateCheck","daily",i),P.showInformationMessage("Extension auto update enabled.")):(await e.update("extensionUpdateCheck","never",i),P.showInformationMessage("Extension auto update disabled."))}},!1,"toggle auto update of extensions.")}async init(e){if(process.env.COC_NO_PLUGINS=="1")return;let t=await this.globalPromise;this.manager.registerExtensions(t);let i=this.runtimeExtensionStats(e);this.manager.registerExtensions(i),this.manager.loadFileExtensions()}async activateExtensions(){if(await this.manager.activateExtensions(),process.env.COC_NO_PLUGINS=="1")return;let e=this.states.filterGlobalExtensions(y.env.globalExtensions);this.installExtensions(e);let t=y.initialConfiguration.get("coc.preferences"),i=t.extensionUpdateCheck,r=t.silentAutoupdate;this.states.shouldUpdate(i)&&(this.outputChannel.appendLine("Start auto update..."),this.updateExtensions(r).catch(o=>{this.outputChannel.appendLine(`Error on updateExtensions ${o}`)}))}get onDidLoadExtension(){return this.manager.onDidLoadExtension}get onDidActiveExtension(){return this.manager.onDidActiveExtension}get onDidUnloadExtension(){return this.manager.onDidUnloadExtension}get outputChannel(){return P.createOutputChannel("extensions")}get all(){return this.manager.all}has(e){return this.manager.has(e)}getExtension(e){return this.manager.getExtension(e)}getExtensionById(e){let t=this.manager.getExtension(e);return t?t.extension:void 0}get schemes(){return{}}addSchemeProperty(e,t){}getExtensionState(e){return this.manager.getExtensionState(e)}isActivated(e){let t=this.manager.getExtension(e);return t!=null&&t.extension.isActive}async call(e,t,i){return await this.manager.call(e,t,i)}get npm(){let e=y.initialConfiguration.get("npm.binPath");e=y.expand(e);for(let t of[e,"yarnpkg","yarn","npm"])if(Dl(t))return go.sync(t);return P.showErrorMessage("Can't find npm or yarn in your $PATH"),null}createInstallerUI(e,t){return t?new UC(e,this.outputChannel):new XC(e)}creteInstaller(e,t){return new _x(this.modulesFolder,e,t)}async installExtensions(e){if(re(e)||!this.npm)return;let{npm:t}=this;e=yi(e);let i=this.createInstallerUI(!1,!1);await Promise.resolve(i.start(e)),await Vd(e,async o=>{try{i.startProgress(o);let s=this.creteInstaller(t,o);s.on("message",(u,c)=>{i.addMessage(o,u,c)});let a=await s.install();i.finishProgress(o,!0),this.states.addExtension(a.name,a.url?a.url:`>=${a.version}`),o.match(/@[\d.]+$/)!=null&&this.states.setLocked(a.name,!0),await this.manager.loadExtension(a.folder)}catch(s){i.addMessage(o,s.message),i.finishProgress(o,!1),P.showErrorMessage(`Error on install ${o}: ${s}`),ym.error(`Error on install ${o}`,s)}})}async updateExtensions(e=!1){let{npm:t}=this;if(!t)return;let i=this.globalExtensionStats();i=i.filter(s=>s.isLocked||s.state==="disabled"?(this.outputChannel.appendLine(`Skipped update for ${s.isLocked?"locked":"disabled"} extension "${s.id}"`),!1):!0),this.states.setLastUpdate(),this.cleanModulesFolder();let r=this.createInstallerUI(!0,e);await Promise.resolve(r.start(i.map(s=>s.id))),await Vd(i,async s=>{let{id:a}=s;try{r.startProgress(a);let l=s.exotic?s.uri:null,u=this.creteInstaller(t,a);u.on("message",(d,h)=>{r.addMessage(a,d,h)});let c=await u.update(l);r.finishProgress(a,!0),c&&await this.manager.loadExtension(c)}catch(l){r.addMessage(a,l.message),r.finishProgress(a,!1),P.showErrorMessage(`Error on update ${a}: ${l}`),ym.error(`Error on update ${a}`,l)}},e?1:3)}async getExtensionStates(){let e=await y.nvim.eval('join(globpath(&runtimepath, "", 0, 1), ",")'),t=this.runtimeExtensionStats(e),i=this.globalExtensionStats();return t.concat(i)}async globalExtensions(){if(process.env.COC_NO_PLUGINS=="1")return[];let e=[];for(let t of this.states.activated()){let i=R.join(this.modulesFolder,t);try{let r=await z4(i,bl);e.push({root:i,isLocal:!1,packageJSON:r})}catch(r){ym.error(`Error on load package.json of ${t}`,r)}}return e}globalExtensionStats(){let e=this.states.dependencies,t=this.states.lockedExtensions,i=[];return Object.entries(e).map(([r,o])=>{let s=R.join(this.modulesFolder,r),a=[],l=Dd(s,bl,a);if(a.length>0){this.outputChannel.appendLine(`Error on load ${r} at ${s}: ${a.join(` +`)}`);return}l.name=r,i.push({id:r,root:s,isLocal:!1,version:l.version,description:l.description??"",isLocked:t.includes(r),exotic:/^https?:/.test(o),uri:bme(o),state:this.getExtensionState(r),packageJSON:l})}),ym.debug("globalExtensionStats:",i.length),i}runtimeExtensionStats(e){let t=this.states.lockedExtensions,i=e.split(","),r=[],o=new Set;return i.map(s=>{let a=[],l=Dd(s,y.version,a);if(a.length>0)return;let{name:u}=l;!u||this.states.hasExtension(u)||o.has(u)||(this.states.addLocalExtension(u,s),o.add(u),r.push({id:l.name,isLocal:!0,isLocked:t.includes(u),version:l.version,description:l.description??"",exotic:!1,root:s,state:this.getExtensionState(l.name),packageJSON:Object.freeze(l)}))}),r}cleanModulesFolder(){let t=this.states.globalIds.map(r=>r.replace(/\/.*$/,""));if(!F.existsSync(this.modulesFolder))return;let i=F.readdirSync(this.modulesFolder);for(let r of i){if(t.includes(r))continue;let o=R.join(this.modulesFolder,r),s=F.lstatSync(o);s.isSymbolicLink()?F.unlinkSync(o):s.isDirectory()&&F.rmSync(o,{recursive:!0,force:!0})}}dispose(){this.manager.dispose()}};Ht=new j0});var zC,rV=D(()=>{"use strict";Je();st();zC=class{constructor(e){this.doc=e;this.lineWords=[];this._gitIgnored=!1;this.parseWords();let t=O.parse(e.uri);t.scheme==="file"&&MZ(t.fsPath).then(i=>{this._gitIgnored=i})}getWords(){let e=[];for(let t of this.lineWords)t.forEach(i=>{e.includes(i)||e.push(i)});return e}parseWords(){let{lineWords:e,doc:t}=this,{chars:i}=t;for(let r of this.doc.textDocument.lines){let o=i.matchLine(r,2);e.push(o)}}get bufnr(){return this.doc.bufnr}get gitIgnored(){return this._gitIgnored}onChange(e){if(e.contentChanges.length==0)return;let{lineWords:t,doc:i}=this,{range:r,text:o}=e.contentChanges[0],{start:s,end:a}=r,l=s.line,c=a.line-l,h=i.textDocument.lines.slice(l,l+o.split(/\n/).length).map(g=>i.chars.matchLine(g,2));t.splice(l,c+1,...h)}*matchWords(e){let{lineWords:t}=this;e>=t.length&&(e=t.length-1);for(let i=0;iml&&(i=za(i)),UE(n,i.charCodeAt(0))}var yme,vme,wme,xme,nr,Td=D(()=>{"use strict";Pe();te();Re();Yt();Ex();de();Xe();fe();he();pa();yme=["_","$","-"],vme=[95,36,45],wme=pe(80,20),xme=50,nr=class{constructor(e){this.noMatchWords=new Set;this.disposables=[];this._disabled=!1;this.name=e.name,this.filepath=e.filepath||"",this.sourceType=e.sourceType||0,this.isSnippet=!!e.isSnippet,this.defaults=e,this.documentSelector=e.documentSelector;let t=`coc.source.${e.name}`;this.config=Ie(y.initialConfiguration.get(t),{}),y.onDidChangeConfiguration(i=>{i.affectsConfiguration(t)&&(this.config=Ie(y.initialConfiguration.get(t),{}))},null,this.disposables),_.on("CompleteDone",()=>{this.noMatchWords.clear()},null,this.disposables)}get nvim(){return y.nvim}get priority(){return this.getConfig("priority",1)}get triggerPatterns(){let e=this.getConfig("triggerPatterns",null);return re(e)?null:e.map(t=>$e(t)?new RegExp(t+"$"):t)}get triggerOnly(){let e=this.defaults.triggerOnly;return Pn(e)?e:Array.isArray(this.triggerPatterns)&&this.triggerPatterns.length>0}get triggerCharacters(){return le(this.getConfig("triggerCharacters",[]))}get firstMatch(){return this.getConfig("firstMatch",!0)}get optionalFns(){return this.defaults.optionalFns||[]}get shortcut(){let e=this.getConfig("shortcut","");return e||this.name.slice(0,3)}get enable(){return this._disabled?!1:this.getConfig("enable",!0)}get filetypes(){return this.getConfig("filetypes",null)}get disableSyntaxes(){return this.getConfig("disableSyntaxes",[])}getConfig(e,t){let i=this.config[e];return tt(i)||i==null?t??null:i}toggle(){this._disabled=!this._disabled}get menu(){return""}async checkComplete(e){let{disableSyntaxes:t}=this;if(!re(t)&&e.synname){let r=e.synname.toLowerCase();if(t.findIndex(o=>r.includes(o.toLowerCase()))!==-1)return!1}let i=this.defaults.shouldComplete;return tt(i)?!!await Promise.resolve(i.call(this,e)):!0}async refresh(){let e=this.defaults.refresh;tt(e)&&await Promise.resolve(e.call(this))}async onCompleteDone(e,t){let i=this.defaults.onCompleteDone;tt(i)&&await Promise.resolve(i.call(this,e,t))}async doComplete(e,t){if(!await this.checkComplete(e)||t.isCancellationRequested)return null;let r=this.defaults.doComplete;return await Promise.resolve(r.call(this,e,t))}async onCompleteResolve(e,t,i){let r=this.defaults.onCompleteResolve;tt(r)&&await Promise.resolve(r.call(this,e,t,i))}async getResults(e,t,i,r,o){let{firstMatch:s,noMatchWords:a}=this,l=Date.now(),u=l,c=t.length,d=t.charCodeAt(0),h=md(t),g=lc(d),f=0;for(let m of e)for(let b of m){if(f++,f%100===0){let v=Date.now();if(v-u>15&&(await ar(),u=v),o.isCancellationRequested||v-l>wme)return!0}if(!(b.length<=1&&b.charCodeAt(0)<255||b===i||r.has(b)||a.has(b))){if(s&&!Cme(d,g,b)){a.add(b);continue}if(c>1&&!bd(h,g&&b[0].charCodeAt(0)>ml?za(b):b)){a.add(b);continue}if(r.add(b),r.size==xme)return!0}}return!1}dispose(){W(this.disposables)}}});function Dme(n){var t,i;let e=((t=n.data)==null?void 0:t.ultisnip)===!0?{}:(i=n.data)==null?void 0:i.ultisnip;return e||void 0}function Tme(n,e,t){let i=n.match(/^\s*/)[0],r=e.match(/^\s*/)[0];if(i===r)return 0;let o=r.length-i.length;return t.start.character+=o,t.end.character+=o,o}var Sme,vm,oV=D(()=>{"use strict";ae();Dt();Rl();xe();cu();te();Re();Ii();Xe();Be();U();fe();he();pa();jl();Sme=Z("source-language"),vm=class{constructor(e,t,i,r,o,s,a){this.name=e;this.shortcut=t;this.provider=i;this.documentSelector=r;this.triggerCharacters=o;this.allCommitCharacters=s;this.priority=a;this.sourceType=2;this._enabled=!0;this.itemDefaults={};this.resolving=new WeakMap}get enable(){return this._enabled}toggle(){this._enabled=!this._enabled}shouldCommit(e,t){return this.allCommitCharacters.includes(t)?!0:le(e.commitCharacters??this.itemDefaults.commitCharacters).includes(t)}async doComplete(e,t){let{triggerCharacter:i,bufnr:r,position:o}=e,s=this.getTriggerKind(e);this.triggerContext={lnum:o.line,character:o.character,line:e.line};let a={triggerKind:s,option:e};s==p.CompletionTriggerKind.TriggerCharacter&&(a.triggerCharacter=i);let l=y.getDocument(r).textDocument;await ar();let u=await Promise.resolve(this.provider.provideCompletionItems(l,o,t,a));if(!u||t.isCancellationRequested)return null;let c=Array.isArray(u)?u:u.items;if(!c||c.length==0)return null;let d=this.itemDefaults=Ue(u.itemDefaults);return{isIncomplete:AW(u)?u.isIncomplete===!0:!1,items:c,itemDefaults:d}}onCompleteResolve(e,t,i){if(!tt(this.provider.resolveCompletionItem))return;let o=this.resolving.get(e);if(o)return o;let s=!1;return o=new Promise(async(a,l)=>{let u=i.onCancellationRequested(()=>{this.resolving.delete(e),l(new Rt)});try{let c=await Promise.resolve(this.provider.resolveCompletionItem(e,i));u.dispose(),i.isCancellationRequested||(c?Object.assign(e,c):(s=!0,this.resolving.delete(e))),a()}catch(c){s=!0,this.resolving.delete(e),l(c)}}),s||this.resolving.set(e,o),o}async onCompleteDone(e,t){let i=y.getDocument(t.bufnr);await i.patchChange(!0);let r=!re(e.additionalTextEdits);r&&await pi.editsInsideSnippet(e.additionalTextEdits)&&pi.cancel();let o=i.version,s=await this.applyTextEdit(i,r,e,t);r&&(await i.applyEdits(e.additionalTextEdits,i.version!=o,!s),s&&await pi.selectCurrentPlaceholder()),e.command&&(V.has(e.command.command)?await V.execute(e.command):Sme.warn(`Command "${e.command.command}" not registered to coc.nvim`))}async applyTextEdit(e,t,i,r){let{linenr:o,col:s}=r,{character:a,line:l}=this.triggerContext,u=await Dv(y.nvim);if(u.line!=o-1)return;let{textEdit:c,insertText:d,label:h}=i,g=yR(i,this.itemDefaults,void 0,r.insertMode);if(!g){let x=a+(r.insertMode=="insert"?0:r.followWord.length);g=M.create(u.line,Ut(l,s),u.line,x)}g.end.character{"use strict";ae();Rl();cu();fe();he();Td();Xe();wm=class extends nr{async callOptionalFunc(e,t){if(!this.optionalFns.includes(e))return null;let r=`coc#source#${this.name}#${e}`;return await this.nvim.call(r,t)}async checkComplete(e){return await super.checkComplete(e)?this.optionalFns.includes("should_complete")?!!await this.callOptionalFunc("should_complete",[e]):!0:!1}async refresh(){await this.callOptionalFunc("refresh",[])}async insertSnippet(e,t){let i=await Dv(this.nvim),{line:r,col:o}=t,s=r.match(/^\s*/)[0],a=i.text.match(/^\s*/)[0],l=M.create(i.line,Ut(r,o)+a.length-s.length,i.line,i.character);await pi.insertSnippet(e,!0,l)}async onCompleteDone(e,t){this.optionalFns.includes("on_complete")?await this.callOptionalFunc("on_complete",[e]):e.isSnippet&&e.insertText&&await this.insertSnippet(e.insertText,t)}onEnter(e){if(!this.optionalFns.includes("on_enter"))return;let t=y.getDocument(e);if(!t)return;let{filetypes:i}=this;i&&!i.includes(t.filetype)||this.callOptionalFunc("on_enter",[{bufnr:e,uri:t.uri,languageId:t.filetype}])}async doComplete(e,t){if(!await this.checkComplete(e))return null;let r=await this.callOptionalFunc("get_startcol",[e]);if(t.isCancellationRequested)return null;let{col:o,input:s,line:a,colnr:l}=e;$t(r)&&r>=0&&r!==o&&(s=Xt(a,r,l-1),e=Object.assign({},e,{col:r,changed:o-r,input:s}));let u=await this.nvim.callAsync("coc#util#do_complete",[this.name,e]);if(!u||u.length==0||t.isCancellationRequested)return null;let c=this.firstMatch&&s.length>0,d=c?s[0].toLowerCase():"",h=[];return u.forEach(g=>{let f=$e(g)?{word:g}:g;if(c){let m=(f.filterText??f.word)[0];if(d&&m.toLowerCase()!==d)return}this.isSnippet&&(f.isSnippet=!0),h.push(f)}),{items:h,startcol:$t(r)?r:void 0}}}});var aV={};Ls(aV,{Around:()=>KC,register:()=>kme});function kme(n,e){let t=new KC(e);n.set("around",t)}var KC,lV=D(()=>{"use strict";te();Td();KC=class extends nr{constructor(t){super({name:"around",filepath:__filename});this.keywords=t}async doComplete(t,i){let{bufnr:r,input:o,word:s,linenr:a,triggerForInComplete:l}=t,u=this.keywords.getItem(r);if(await ar(),l||(this.noMatchWords=new Set),o.length===0||!u||i.isCancellationRequested)return null;let c=u.matchWords(a-1),d=new Set;return{isIncomplete:await this.getResults([c],o,s,d,i),items:Array.from(d).map(g=>({word:g}))}}}});var uV={};Ls(uV,{Buffer:()=>QC,register:()=>Pme});function Pme(n,e){let t=new QC(e);n.set("buffer",t)}var QC,cV=D(()=>{"use strict";te();Td();QC=class extends nr{constructor(t){super({name:"buffer",filepath:__filename});this.keywords=t}get ignoreGitignore(){return this.getConfig("ignoreGitignore",!0)}async doComplete(t,i){let{bufnr:r,input:o,word:s,triggerForInComplete:a}=t;if(await ar(),a||(this.noMatchWords=new Set),o.length===0||i.isCancellationRequested)return null;let l=[];for(let d of this.keywords.items)d.bufnr===r||this.ignoreGitignore&&d.gitIgnored||l.push(d.matchWords(0));let u=new Set;return{isIncomplete:await this.getResults(l,o,s,u,i),items:Array.from(u).map(d=>({word:d}))}}}});var mV={};Ls(mV,{File:()=>VC,filterFiles:()=>gV,getDirectory:()=>pV,getFileItem:()=>hV,getItemsFromRoot:()=>fV,register:()=>_me,resolveEnvVariables:()=>dV});function dV(n,e=process.env){let t=n;return t=t.replace(/%([^%]+)%/g,(i,r)=>e[r]??i),t=t.replace(/\$([A-Z_]+[A-Z0-9_]*)|\${([A-Z0-9_]*)}/gi,(i,r,o)=>e[r||o]??i),t}async function hV(n,e){let t=R.join(n,e),i=await Fn(t);if(i){let r=i.isDirectory(),o=r?e+"/":e;return{word:e,abbr:o,kind:r?ie.Folder:ie.File}}return null}function gV(n,e,t=[]){return n.filter(i=>{if(!i||e&&i.startsWith("."))return!1;for(let r of t)if(ni(i,r,{dot:!0}))return!1;return!0})}function pV(n,e){let t=/[\\/]$/.test(n)?n:R.dirname(n);return R.isAbsolute(n)?t:R.join(e,t)}async function fV(n,e,t,i){let r=[],o=pV(n,e),s=await Fn(o);if(s&&s.isDirectory()){let a=await(0,ot.promisify)(F.readdir)(o);a=gV(a,t,i);let l=await Promise.all(a.map(u=>hV(o,u)));r=r.concat(l)}return r=r.filter(a=>a!=null),r}function _me(n){n.set("file",new VC(Ur))}var Rme,VC,bV=D(()=>{"use strict";ae();st();de();wl();fe();he();Td();Rme=/(?:\.{0,2}|~|\$HOME|([\w]+)|[a-zA-Z]:|)(\/|\\+)(?:[\u4E00-\u9FA5\u00A0-\u024F\w .@()-]+(\/|\\+))*(?:[\u4E00-\u9FA5\u00A0-\u024F\w .@()-])*$/;VC=class extends nr{constructor(t){super({name:"file",filepath:__filename});this.isWindows=t}get triggerCharacters(){let t=this.getConfig("triggerCharacters",[]);return this.isWindows?t:t.filter(i=>i!="\\")}getPathOption(t){let{line:i,colnr:r}=t,o=Xt(i,0,r-1);if(o=dV(o),!o||o.endsWith("//"))return null;let s=o.match(Rme);if(s&&s.length){let a=y.expand(s[0]),l=s[0].match(/[^/\\]*$/)[0];return{pathstr:a,part:s[1],startcol:r-l.length-1,input:l}}return null}shouldTrim(t){return this.getConfig("trimSameExts",[]).includes(t)}async getRoot(t,i,r,o){let s,a=r?R.dirname(r):"";if(t.startsWith("."))s=r?a:o;else if(this.isWindows&&/^\w+:/.test(t))s=/[\\/]$/.test(t)?t:R.win32.dirname(t);else if(!this.isWindows&&t.startsWith("/"))s=t.endsWith("/")?t:R.posix.dirname(t);else if(i){let l=await(0,ot.promisify)(F.exists)(R.join(a,i));l?s=a:(l=await(0,ot.promisify)(F.exists)(R.join(o,i)),l&&(s=o))}else s=o;return s}async doComplete(t,i){let{filepath:r}=t,o=this.getPathOption(t);if(!o||o.startcol{let b=R.extname(m.word);return m.word=f&&b===c?m.word.replace(c,""):m.word,{word:`${u}${m.word}`,abbr:`${u}${m.abbr}`,menu:this.menu}})}}}});var T0={};Ls(T0,{Sources:()=>tS,default:()=>Pi,getSourceType:()=>yV,logError:()=>A0});function A0(n){eS.error("Error on source create",n)}function yV(n){return n===0?"native":n===1?"remote":"service"}var eS,O0,tS,Pi,uu=D(()=>{"use strict";Pe();nu();xe();te();Re();st();Xe();de();U();fe();We();he();rV();Td();oV();sV();pa();jl();eS=Z("sources"),O0=class{constructor(){this.name="$words";this.shortcut="";this.triggerOnly=!0;this.words=[]}doComplete(e){return{items:this.words.map(t=>({word:t,filterText:e.input}))}}},tS=class{constructor(){this.sourceMap=new Map;this.disposables=[];this.remoteSourcePaths=[];this.wordsSource=new O0}init(){this.keywords=y.registerBufferSync(e=>new zC(e)),this.createNativeSources(),this.createRemoteSources(),_.on("BufEnter",this.onDocumentEnter,this,this.disposables),y.onDidRuntimePathChange(e=>{for(let t of e)this.createVimSources(t).catch(A0)},null,this.disposables)}get nvim(){return y.nvim}getKeywordsBuffer(e){return this.keywords.getItem(e)}setWords(e){this.wordsSource.words=e}createNativeSources(){this.sourceMap.set(this.wordsSource.name,this.wordsSource),Promise.all([Promise.resolve().then(()=>(lV(),aV)).then(e=>{e.register(this.sourceMap,this.keywords)}),Promise.resolve().then(()=>(cV(),uV)).then(e=>{e.register(this.sourceMap,this.keywords)}),Promise.resolve().then(()=>(bV(),mV)).then(e=>{e.register(this.sourceMap)})])}createLanguageSource(e,t,i,r,o,s,a){let l=new vm(e,t,r,i,le(o),le(a),s);return eS.trace("created service source",e),this.sourceMap.set(e,l),{dispose:()=>{this.sourceMap.delete(e)}}}async createVimSourceExtension(e){let{nvim:t}=this;try{let i=R.basename(e,".vim");await t.command(`source ${e}`);let r=await t.call("coc#util#remote_fns",i);for(let u of["init","complete"])if(!r.includes(u))throw new Error(`function "coc#source#${i}#${u}" not found`);let o=await t.call(`coc#source#${i}#init`,[]),s={name:`coc-vim-source-${i}`,engines:{coc:">= 0.0.1"},activationEvents:o.filetypes?o.filetypes.map(u=>`onLanguage:${u}`):["*"],contributes:{configuration:{properties:{[`coc.source.${i}.enable`]:{type:"boolean",default:!0},[`coc.source.${i}.firstMatch`]:{type:"boolean",default:!!o.firstMatch},[`coc.source.${i}.triggerCharacters`]:{type:"number",default:o.triggerCharacters??[]},[`coc.source.${i}.priority`]:{type:"number",default:o.priority??9},[`coc.source.${i}.shortcut`]:{type:"string",default:o.shortcut??i.slice(0,3).toUpperCase(),description:"Shortcut text shown in complete menu."},[`coc.source.${i}.disableSyntaxes`]:{type:"array",default:[],items:{type:"string"}},[`coc.source.${i}.filetypes`]:{type:"array",default:o.filetypes||null,description:"Enabled filetypes.",items:{type:"string"}}}}}},a=!1,l={id:s.name,packageJSON:s,exports:void 0,extensionPath:e,activate:()=>{a=!0;let u=new wm({name:i,filepath:e,isSnippet:o.isSnippet,sourceType:1,triggerOnly:!!o.triggerOnly,optionalFns:r.filter(c=>!["init","complete"].includes(c))});return this.addSource(u),Promise.resolve()}};Object.defineProperty(l,"isActive",{get:()=>a}),await Ht.manager.registerInternalExtension(l,()=>{a=!1,this.removeSource(i)})}catch(i){P.showErrorMessage(`Error on create vim source from ${e}: ${i}`)}}createRemoteSources(){let e=y.env.runtimepath.split(",");for(let t of e)this.createVimSources(t).catch(A0)}async createVimSources(e){if(this.remoteSourcePaths.includes(e)||!e)return;this.remoteSourcePaths.push(e);let t=R.join(e,"autoload/coc/source"),i=await Fn(t);if(i&&i.isDirectory()){let o=(await(0,ot.promisify)(F.readdir)(t)).filter(s=>s.endsWith(".vim")).map(s=>R.join(t,s));await Promise.allSettled(o.map(s=>this.createVimSourceExtension(s)))}}get names(){return Array.from(this.sourceMap.keys())}get sources(){return Array.from(this.sourceMap.values())}has(e){return this.names.findIndex(t=>t==e)!=-1}getSource(e){return this.sourceMap.get(e)??null}shouldCommit(e,t,i){return!t||e==null?!1:tt(e.shouldCommit)?e.shouldCommit(t,i):!1}getSources(e){let{source:t}=e;if(t)return le(this.getSource(t));let i=y.getUri(e.bufnr);return this.getNormalSources(e.filetype,i)}getNormalSources(e,t){let i=e.split(".");return this.sources.filter(o=>{let{filetypes:s,triggerOnly:a,documentSelector:l,enable:u}=o;return!(!u||a||s&&!hg(s,i)||l&&i.every(c=>y.match(l,{uri:t,languageId:c})==0))})}checkTrigger(e,t,i){let{triggerCharacters:r,triggerPatterns:o}=e;return!!(!re(r)&&r.includes(i)||!re(o)&&o.findIndex(s=>s.test(t))!==-1)}shouldTrigger(e,t,i){return this.getTriggerSources(e,t,i).length>0}getTriggerSources(e,t,i,r=[]){if(!e)return[];let o=e[e.length-1],s=t.split(".");return this.sources.filter(a=>{let{filetypes:l,enable:u,documentSelector:c,name:d}=a;return r.includes(d)||!u||l&&!hg(l,s)||c&&s.every(h=>y.match(c,{uri:i,languageId:h})==0)?!1:this.checkTrigger(a,e,o)})}addSource(e){let{name:t}=e;return this.names.includes(t)&&eS.warn(`Recreate source ${t}`),this.sourceMap.set(t,e),p.Disposable.create(()=>{this.removeSource(e)})}removeSource(e){let t=typeof e=="string"?e:e.name,i=typeof e=="string"?this.sourceMap.get(e):e;i&&typeof i.dispose=="function"&&i.dispose(),this.sourceMap.delete(t)}async refresh(e){for(let t of this.sources)(!e||t.name==e)&&typeof t.refresh=="function"&&await Promise.resolve(t.refresh())}toggleSource(e){let t=this.getSource(e);t&&typeof t.toggle=="function"&&t.toggle()}sourceStats(){var i;let e=[],t=y.initialConfiguration.get("suggest.languageSourcePriority");for(let r of this.sourceMap.values())r.name!=="$words"&&e.push({name:r.name,priority:uw(r,t),triggerCharacters:le(r.triggerCharacters),shortcut:oe(r.shortcut),filetypes:le(r.filetypes??((i=r.documentSelector)==null?void 0:i.map(o=>$e(o)?o:o.language))),filepath:oe(r.filepath),type:yV(r.sourceType),disabled:!r.enable});return e}onDocumentEnter(e){let{sources:t}=this;for(let i of t)i.enable&&tt(i.onEnter)&&i.onEnter(e)}createSource(e){if(typeof e.name!="string"||typeof e.doComplete!="function")throw eS.error("Bad config for createSource:",e),new TypeError("name and doComplete required for createSource");let t=new nr(Object.assign({sourceType:2},e));return this.addSource(t)}dispose(){W(this.disposables)}};Pi=new tS});var vV,jt,N0,I,Se=D(()=>{"use strict";ae();Hc();JX();GX();zX();KX();QX();VX();e2();i2();n2();o2();s2();a2();l2();u2();SR();d2();h2();g2();p2();f2();m2();b2();y2();v2();w2();C2();S2();te();Xe();U();fe();vV=pe(500,10),jt=(B=>(B.FormatOnType="formatOnType",B.Rename="rename",B.OnTypeEdit="onTypeEdit",B.DocumentLink="documentLink",B.DocumentColor="documentColor",B.FoldingRange="foldingRange",B.Format="format",B.CodeAction="codeAction",B.FormatRange="formatRange",B.Hover="hover",B.Signature="signature",B.WorkspaceSymbols="workspaceSymbols",B.DocumentSymbol="documentSymbol",B.DocumentHighlight="documentHighlight",B.Definition="definition",B.Declaration="declaration",B.TypeDefinition="typeDefinition",B.Reference="reference",B.Implementation="implementation",B.CodeLens="codeLens",B.SelectionRange="selectionRange",B.CallHierarchy="callHierarchy",B.SemanticTokens="semanticTokens",B.SemanticTokensRange="semanticTokensRange",B.LinkedEditing="linkedEditing",B.InlayHint="inlayHint",B.InlineValue="inlineValue",B.TypeHierarchy="typeHierarchy",B))(jt||{}),N0=class{constructor(){this._onDidSemanticTokensRefresh=new p.Emitter;this._onDidInlayHintRefresh=new p.Emitter;this._onDidCodeLensRefresh=new p.Emitter;this._onDidColorsRefresh=new p.Emitter;this._onDidLinksRefresh=new p.Emitter;this.onDidSemanticTokensRefresh=this._onDidSemanticTokensRefresh.event;this.onDidInlayHintRefresh=this._onDidInlayHintRefresh.event;this.onDidCodeLensRefresh=this._onDidCodeLensRefresh.event;this.onDidColorsRefresh=this._onDidColorsRefresh.event;this.onDidLinksRefresh=this._onDidLinksRefresh.event;this.onTypeFormatManager=new Xp;this.documentLinkManager=new Ap;this.documentColorManager=new jp;this.foldingRangeManager=new Hp;this.renameManager=new zp;this.formatManager=new Bp;this.codeActionManager=new Ip;this.workspaceSymbolsManager=new rf;this.formatRangeManager=new qp;this.hoverManager=new Wp;this.signatureManager=new ef;this.documentSymbolManager=new Np;this.documentHighlightManager=new Op;this.definitionManager=new Mp;this.declarationManager=new Fp;this.typeDefinitionManager=new tf;this.typeHierarchyManager=new nf;this.referenceManager=new Gp;this.implementationManager=new Yp;this.codeLensManager=new Lp;this.selectionRangeManager=new Kp;this.callHierarchyManager=new Ep;this.semanticTokensManager=new Qp;this.semanticTokensRangeManager=new Vp;this.linkedEditingManager=new Up;this.inlayHintManager=new Zp;this.inlineValueManager=new $p;this.registerReferenceProvider=this.registerReferencesProvider}hasFormatProvider(e){return!!(this.formatManager.hasProvider(e)||this.formatRangeManager.hasProvider(e))}registerOnTypeFormattingEditProvider(e,t,i){return this.onTypeFormatManager.register(e,t,i)}registerCompletionItemProvider(e,t,i,r,o=[],s,a){i=$e(i)?[{language:i}]:i;let l=(uu(),No(T0)).default;return l.removeSource(e),l.createLanguageSource(e,t,i,r,o,s,a)}registerCodeActionProvider(e,t,i,r){return this.codeActionManager.register(e,t,i,r)}registerHoverProvider(e,t){return this.hoverManager.register(e,t)}registerSelectionRangeProvider(e,t){return this.selectionRangeManager.register(e,t)}registerSignatureHelpProvider(e,t,i){return this.signatureManager.register(e,t,i)}registerDocumentSymbolProvider(e,t,i){return i&&(t.meta=i),this.documentSymbolManager.register(e,t)}registerFoldingRangeProvider(e,t){return this.foldingRangeManager.register(e,t)}registerDocumentHighlightProvider(e,t){return this.documentHighlightManager.register(e,t)}registerDocumentLinkProvider(e,t){this._onDidLinksRefresh.fire(e);let i=this.documentLinkManager.register(e,t);return p.Disposable.create(()=>{i.dispose(),this._onDidLinksRefresh.fire(e)})}registerDocumentColorProvider(e,t){this._onDidColorsRefresh.fire(e);let i=this.documentColorManager.register(e,t);return p.Disposable.create(()=>{i.dispose(),this._onDidColorsRefresh.fire(e)})}registerDefinitionProvider(e,t){return this.definitionManager.register(e,t)}registerDeclarationProvider(e,t){return this.declarationManager.register(e,t)}registerTypeDefinitionProvider(e,t){return this.typeDefinitionManager.register(e,t)}registerTypeHierarchyProvider(e,t){return this.typeHierarchyManager.register(e,t)}registerImplementationProvider(e,t){return this.implementationManager.register(e,t)}registerReferencesProvider(e,t){return this.referenceManager.register(e,t)}registerRenameProvider(e,t){return this.renameManager.register(e,t)}registerWorkspaceSymbolProvider(e){return arguments.length>1&&tt(arguments[1].provideWorkspaceSymbols)&&(e=arguments[1]),this.workspaceSymbolsManager.register(e)}registerDocumentFormatProvider(e,t,i=0){return this.formatManager.register(e,t,i)}registerDocumentRangeFormatProvider(e,t,i=0){return this.formatRangeManager.register(e,t,i)}registerCallHierarchyProvider(e,t){return this.callHierarchyManager.register(e,t)}registerCodeLensProvider(e,t){return this.registerProviderWithEvent(e,t,"onDidChangeCodeLenses",this.codeLensManager,this._onDidCodeLensRefresh)}registerDocumentSemanticTokensProvider(e,t,i){return this.registerProviderWithEvent(e,t,"onDidChangeSemanticTokens",this.semanticTokensManager,this._onDidSemanticTokensRefresh,i)}registerDocumentRangeSemanticTokensProvider(e,t,i){let r=setTimeout(()=>{this._onDidSemanticTokensRefresh.fire(e)},vV),o=this.semanticTokensRangeManager.register(e,t,i);return p.Disposable.create(()=>{clearTimeout(r),o.dispose(),this._onDidSemanticTokensRefresh.fire(e)})}registerInlayHintsProvider(e,t){return this.registerProviderWithEvent(e,t,"onDidChangeInlayHints",this.inlayHintManager,this._onDidInlayHintRefresh)}registerInlineValuesProvider(e,t){return this.inlineValueManager.register(e,t)}registerLinkedEditingRangeProvider(e,t){return this.linkedEditingManager.register(e,t)}shouldTriggerSignatureHelp(e,t){return this.signatureManager.shouldTrigger(e,t)}async getHover(e,t,i){return await this.hoverManager.provideHover(e,t,i)}async getSignatureHelp(e,t,i,r){return await this.signatureManager.provideSignatureHelp(e,t,i,r)}async getDefinition(e,t,i){return await this.definitionManager.provideDefinition(e,t,i)}async getDefinitionLinks(e,t,i){return await this.definitionManager.provideDefinitionLinks(e,t,i)}async getDeclaration(e,t,i){return await this.declarationManager.provideDeclaration(e,t,i)}async getTypeDefinition(e,t,i){return await this.typeDefinitionManager.provideTypeDefinition(e,t,i)}async getImplementation(e,t,i){return await this.implementationManager.provideImplementations(e,t,i)}async getReferences(e,t,i,r){return await this.referenceManager.provideReferences(e,i,t,r)}async getDocumentSymbol(e,t){return await this.documentSymbolManager.provideDocumentSymbols(e,t)}getDocumentSymbolMetadata(e){return this.documentSymbolManager.getMetaData(e)}async getSelectionRanges(e,t,i){return await this.selectionRangeManager.provideSelectionRanges(e,t,i)}async getWorkspaceSymbols(e,t){return await this.workspaceSymbolsManager.provideWorkspaceSymbols(oe(e),t)}async resolveWorkspaceSymbol(e,t){return await this.workspaceSymbolsManager.resolveWorkspaceSymbol(e,t)}async prepareRename(e,t,i){return await this.renameManager.prepareRename(e,t,i)}async provideRenameEdits(e,t,i,r){return await this.renameManager.provideRenameEdits(e,t,i,r)}async provideDocumentFormattingEdits(e,t,i){let r=await this.formatManager.provideDocumentFormattingEdits(e,t,i);if(r==null){if(!this.formatRangeManager.hasProvider(e))return null;let s=e.positionAt(e.getText().length),a=M.create(Q.create(0,0),s);return await this.provideDocumentRangeFormattingEdits(e,a,t,i)}return r}async provideDocumentRangeFormattingEdits(e,t,i,r){return await this.formatRangeManager.provideDocumentRangeFormattingEdits(e,t,i,r)}async getCodeActions(e,t,i,r){return await this.codeActionManager.provideCodeActions(e,t,i,r)}async getDocumentHighLight(e,t,i){return await this.documentHighlightManager.provideDocumentHighlights(e,t,i)}async getDocumentLinks(e,t){return await this.documentLinkManager.provideDocumentLinks(e,t)}async resolveDocumentLink(e,t){return await this.documentLinkManager.resolveDocumentLink(e,t)}async provideDocumentColors(e,t){return await this.documentColorManager.provideDocumentColors(e,t)}async provideFoldingRanges(e,t,i){return await this.foldingRangeManager.provideFoldingRanges(e,t,i)}async provideColorPresentations(e,t,i){return await this.documentColorManager.provideColorPresentations(e,t,i)}async getCodeLens(e,t){return await this.codeLensManager.provideCodeLenses(e,t)}async resolveCodeLens(e,t){return await this.codeLensManager.resolveCodeLens(e,t)}async resolveCodeAction(e,t){return await this.codeActionManager.resolveCodeAction(e,t)}async provideDocumentOnTypeEdits(e,t,i,r){return this.onTypeFormatManager.onCharacterType(e,t,i,r)}canFormatOnType(e,t){return this.onTypeFormatManager.couldTrigger(t,e)!=null}async prepareCallHierarchy(e,t,i){return this.callHierarchyManager.prepareCallHierarchy(e,t,i)}async provideIncomingCalls(e,t,i){return this.callHierarchyManager.provideCallHierarchyIncomingCalls(e,t,i)}async provideOutgoingCalls(e,t,i){return this.callHierarchyManager.provideCallHierarchyOutgoingCalls(e,t,i)}getLegend(e,t){return t?this.semanticTokensRangeManager.getLegend(e):this.semanticTokensManager.getLegend(e)}hasSemanticTokensEdits(e){return this.semanticTokensManager.hasSemanticTokensEdits(e)}async provideDocumentSemanticTokens(e,t){return this.semanticTokensManager.provideDocumentSemanticTokens(e,t)}async provideDocumentSemanticTokensEdits(e,t,i){return this.semanticTokensManager.provideDocumentSemanticTokensEdits(e,t,i)}async provideDocumentRangeSemanticTokens(e,t,i){return this.semanticTokensRangeManager.provideDocumentRangeSemanticTokens(e,t,i)}async provideInlayHints(e,t,i){return this.inlayHintManager.provideInlayHints(e,t,i)}async resolveInlayHint(e,t){return this.inlayHintManager.resolveInlayHint(e,t)}async provideLinkedEdits(e,t,i){return this.linkedEditingManager.provideLinkedEditingRanges(e,t,i)}async provideInlineValues(e,t,i,r){return this.inlineValueManager.provideInlineValues(e,t,i,r)}async prepareTypeHierarchy(e,t,i){return this.typeHierarchyManager.prepareTypeHierarchy(e,t,i)}async provideTypeHierarchySupertypes(e,t){return this.typeHierarchyManager.provideTypeHierarchySupertypes(e,t)}async provideTypeHierarchySubtypes(e,t){return this.typeHierarchyManager.provideTypeHierarchySubtypes(e,t)}createDiagnosticCollection(e){return ui.create(e)}registerProviderWithEvent(e,t,i,r,o,s){let a=[],l=setTimeout(()=>{o.fire(e)},vV);return a.push(p.Disposable.create(()=>{clearTimeout(l)})),tt(t[i])&&a.push(t[i](()=>{clearTimeout(l),o.fire(e)})),a.push(r.register(e,t,s)),p.Disposable.create(()=>{W(a),o.fire(e)})}hasProvider(e,t){switch(e){case"onTypeEdit":case"formatOnType":return this.onTypeFormatManager.hasProvider(t);case"rename":return this.renameManager.hasProvider(t);case"documentLink":return this.documentLinkManager.hasProvider(t);case"documentColor":return this.documentColorManager.hasProvider(t);case"foldingRange":return this.foldingRangeManager.hasProvider(t);case"format":return this.formatManager.hasProvider(t)||this.formatRangeManager.hasProvider(t);case"codeAction":return this.codeActionManager.hasProvider(t);case"workspaceSymbols":return this.workspaceSymbolsManager.hasProvider();case"formatRange":return this.formatRangeManager.hasProvider(t);case"hover":return this.hoverManager.hasProvider(t);case"signature":return this.signatureManager.hasProvider(t);case"documentSymbol":return this.documentSymbolManager.hasProvider(t);case"documentHighlight":return this.documentHighlightManager.hasProvider(t);case"definition":return this.definitionManager.hasProvider(t);case"declaration":return this.declarationManager.hasProvider(t);case"typeDefinition":return this.typeDefinitionManager.hasProvider(t);case"reference":return this.referenceManager.hasProvider(t);case"implementation":return this.implementationManager.hasProvider(t);case"codeLens":return this.codeLensManager.hasProvider(t);case"selectionRange":return this.selectionRangeManager.hasProvider(t);case"callHierarchy":return this.callHierarchyManager.hasProvider(t);case"semanticTokens":return this.semanticTokensManager.hasProvider(t);case"semanticTokensRange":return this.semanticTokensRangeManager.hasProvider(t);case"linkedEditing":return this.linkedEditingManager.hasProvider(t);case"inlayHint":return this.inlayHintManager.hasProvider(t);case"inlineValue":return this.inlineValueManager.hasProvider(t);case"typeHierarchy":return this.typeHierarchyManager.hasProvider(t);default:return!1}}},I=new N0});var du,xm,wV=D(()=>{"use strict";ae();Pe();Se();Re();Be();Xe();Tt();he();te();du=class{static async create(e,t,i){let{position:r}=t,o=[t.linenr,t.colnr];if(!e)return du.None;let s=y.getDocument(t.bufnr),a=await I.getSelectionRanges(s.textDocument,[r],i);if(!a||i.isCancellationRequested)return du.None;let l=[],u=d=>{d&&d.range.end.line-d.range.start.line<2e3&&(l.unshift(d.range),u(d.parent))};u(le(a)[0]);let c=l.length>0?await Promise.race([qb(100,i),y.computeWordRanges(t.bufnr,l[0],i)]):void 0;return xt(c)?(delete c[t.word],new class extends du{distance(d,h){if(!Me([_.cursor.lnum,_.cursor.col],o))return 0;if(h.kind===ie.Keyword||Ue(h.source).name==="snippets")return 2<<20;let g=c[h.word];if(re(g))return 2<<20;let f=aZ(g,M.create(d,d),Dc),m=f>=0?g[f]:g[Math.max(0,~f-1)],b=l.length;for(let v of l){if(!ti(m,v))break;b-=1}return b}}):du.None}},xm=du;xm.None=new class extends du{distance(){return 0}}});function jme(n,e,t,i){let r=t.sortText,o=i.sortText;if(t.score!==i.score)return i.score-t.score;if(t.priority!==i.priority)return i.priority-t.priority;if(t.source===i.source&&r!==o)return r{"use strict";ae();xe();te();Re();pc();Xe();Vs();U();fe();he();pa();jl();wV();hu=Z("completion-complete"),Ime=2<<20,Lme=50,Fme=5e3,Mme=200,Cm=class{constructor(e,t,i,r){this.option=e;this.document=t;this.config=i;this.sources=r;this.results=new Map;this._input="";this._completing=!1;this.names=[];this.cid=0;this.minCharacter=Number.MAX_SAFE_INTEGER;this._onDidRefresh=new p.Emitter;this.tokenSources=new Set;this.tokensInfo=new WeakMap;this.itemsMap=new WeakMap;this.onDidRefresh=this._onDidRefresh.event;this.inputStart=Ut(e.line,e.col),this.timeout=eP(this.config.timeout,Lme,Fme),r.sort((o,s)=>(s.priority??99)-(o.priority??99)),this.names=r.map(o=>o.name),this.asciiMatch=i.asciiMatch&&DX(e.input)}get nvim(){return y.nvim}fireRefresh(e){clearTimeout(this.timer),e?this.timer=setTimeout(()=>{this._onDidRefresh.fire()},e):this._onDidRefresh.fire()}get totalLength(){let e=0;for(let t of this.results.values())e+=t.items.length;return e}resolveItem(e){if(!!e)return{source:e.source,item:this.itemsMap.get(e)}}get isCompleting(){return this._completing}get input(){return this._input}get isEmpty(){return this.results.size===0}get hasInComplete(){for(let e of this.results.values())if(e.isIncomplete)return!0;return!1}getIncompleteSources(){return this.sources.filter(e=>{let t=this.results.get(e.name);return t&&t.isIncomplete===!0})}async doComplete(){let e=this.createTokenSource(!1),t=e.token,i=await Promise.all([this.nvim.call("coc#util#synname",[]),this.nvim.call("coc#util#suggest_variables",[this.option.bufnr]),this.document.patchChange()]);if(t.isCancellationRequested)return;this.option.synname=i[0];let r=i[1];if(r.disable)return hu.warn("suggest cancelled by b:coc_suggest_disable"),!0;if(!re(r.disabled_sources)&&(this.sources=this.sources.filter(o=>!r.disabled_sources.includes(o.name)),this.sources.length===0))return hu.warn("suggest cancelled by b:coc_disabled_sources"),!0;if(!re(r.blacklist)&&r.blacklist.includes(this.option.input))return hu.warn("suggest cancelled by b:coc_suggest_blacklist"),!0;xm.create(this.config.localityBonus,this.option,t).then(o=>{this.wordDistance=o}),await qb(eP(this.config.triggerCompletionWait,0,Mme),e.token),await this.completeSources(this.sources,e,this.cid)}async completeSources(e,t,i){let r=t.token;if(r.isCancellationRequested)return;this._completing=!0;let o=new Set;e.forEach(d=>o.add(d.name));let s,a,l=new Promise(d=>{a=r.onCancellationRequested(()=>{clearTimeout(s),d()}),s=setTimeout(()=>{let h=Array.from(o);a.dispose(),t.cancel(),hu.warn(`Completion timeout after ${this.timeout}ms`,h),this.nvim.setVar("coc_timeout_sources",h,!0),d()},this.timeout)}),u=this.getDefaultRange(),c=e.map(d=>this.completeSource(d,u,r).then(h=>{o.delete(d.name),!(r.isCancellationRequested||i!=0||this.cid>0&&this._completing)&&(o.size===0?this.fireRefresh(0):h&&this.fireRefresh(16))}));await Promise.race([l,Promise.allSettled(c)]),this.tokenSources.delete(t),a.dispose(),clearTimeout(s),i===this.cid&&(this._completing=!1)}async completeSource(e,t,i){let r=Object.assign({},this.option),{asciiMatch:o}=this,s=this.config.insertMode,a=e.name,l=!1;try{if(tt(e.shouldComplete)&&(!await Promise.resolve(e.shouldComplete(r))||i.isCancellationRequested))return;let u=Date.now(),c=this.itemsMap;await new Promise((d,h)=>{Promise.resolve(e.doComplete(r,i)).then(g=>{if(i.isCancellationRequested){d(void 0);return}let f=g?g.items.length:0;if(hu.debug(`Source "${a}" finished with ${f} items ms cost:`,Date.now()-u),f>0){if($t(g.startcol)){let C=r.linenr-1;t=M.create(C,Ut(r.line,g.startcol),C,t.end.character)}let m=uw(e,this.config.languageSourcePriority),b={source:e,insertMode:s,priority:m,asciiMatch:o,itemDefaults:g.itemDefaults,range:t},v=new aw(this.inputStart,b,r),x=g.items.reduce((C,k)=>{let T=v.convertToDurationItem(k);return T?(c.set(T,k),C.push(T),C):(hu.error(`Unexpected completion item from ${a}:`,k),C)},[]);this.minCharacter=Math.min(this.minCharacter,v.minCharacter),this.results.set(a,{items:x,isIncomplete:g.isIncomplete===!0}),l=!0}else this.results.delete(a);d()},g=>{h(g)})})}catch(u){hu.error("Complete error:",e.name,u)}return l}async completeInComplete(e){let{document:t}=this;this.cancelInComplete();let i=this.createTokenSource(!0),r=i.token;await t.patchChange(!0);let{input:o,colnr:s,linenr:a,followWord:l,position:u}=this.option;Object.assign(this.option,{word:e+l,input:e,line:t.getline(a-1),position:{line:u.line,character:u.character+e.length-o.length},colnr:s+(e.length-o.length),triggerCharacter:void 0,triggerForInComplete:!0}),this.cid++;let c=this.getIncompleteSources();if(await this.completeSources(c,i,this.cid),!r.isCancellationRequested)return this.filterItems(e)}filterItems(e){let{results:t,names:i,option:r,inputStart:o}=this;this._input=e;let s=e.length,{maxItemCount:a,defaultSortMethod:l,removeDuplicateItems:u}=this.config,c=[],d=new Set,h=s==0,g=e.toLowerCase(),f=!this.config.filterGraceful||this.totalLength>2e3?Sl:ia,m={boostFullMatch:!0,firstMatchCanBeWeak:!1},b=Q.create(r.linenr-1,o);for(let v of i){let x=t.get(v);if(!x)continue;let C=x.items;for(let k=0;k0){let Y=N.slice(0,T.delta);se=f(Y+e,Y+g,0,N,N.toLowerCase(),0,m)}else se=f(e,g,0,N,N.toLowerCase(),0,m);if(se==null)continue;T.score=se[0],T.positions=se,this.wordDistance&&(T.localBonus=Ime-this.wordDistance.distance(b,T))}d.add(j),c.push(T)}}return c.sort(jme.bind(null,h,l)),this.limitCompleteItems(c.slice(0,a))}async filterResults(e){return clearTimeout(this.timer),e!==this.option.input&&this.hasInComplete?await this.completeInComplete(e):this.filterItems(e)}limitCompleteItems(e){let{highPrioritySourceLimit:t,lowPrioritySourceLimit:i}=this.config;if(!t&&!i)return e;let r=new Map;return e.filter(o=>{let{priority:s,source:a}=o,l=s<90,u=r.get(a)||0;return i&&l&&u==i||t&&!l&&u==t?!1:(r.set(a,u+1),!0)})}getDefaultRange(){let{insertMode:e}=this.config,{linenr:t,followWord:i,position:r}=this.option,o=t-1,s=r.character+(e=="replace"?i.length:0);return M.create(o,this.inputStart,o,s)}createTokenSource(e){let t=new p.CancellationTokenSource;return this.tokenSources.add(t),t.token.onCancellationRequested(()=>{this.tokenSources.delete(t)}),this.tokensInfo.set(t,e),t}cancelInComplete(){let{tokenSources:e,tokensInfo:t}=this;for(let i of Array.from(e))t.get(i)===!0&&i.cancel()}cancel(){let{tokenSources:e,timer:t}=this;clearTimeout(t);for(let i of Array.from(e))i.cancel();e.clear(),this._completing=!1}dispose(){this.cancel(),this.results.clear(),this._onDidRefresh.dispose()}}});var Ome,Ame,Sm,CV=D(()=>{"use strict";xe();xP();te();Ii();Xe();U();he();jl();Ome=Z("completion-floating"),Ame=pe(500,50),Sm=class{constructor(e){this.config=e}async resolveItem(e,t,i,r,o=!1){if(this.cancel(),tt(e.onCompleteResolve))try{await this.requestWithToken(s=>Promise.resolve(e.onCompleteResolve(t,i,s)))}catch(s){if(vy(s))return;Ome.error(`Error on resolve complete item from ${e.name}:`,t,s);return}r&&this.show(PX(t,i.filetype,o))}show(e){let t=this.config.floatConfig;if(e=e.filter(i=>i.content.trim().length>0),e.length===0)this.close();else{let i=y.configurations.markdownPreference,{lines:r,codes:o,highlights:s}=Sv(e,i),a={codes:o,highlights:s,highlight:t.highlight??"CocFloating",maxWidth:t.maxWidth||80,rounded:t.rounded?1:0,focusable:t.focusable===!0?1:0};t.shadow&&(a.shadow=1),t.border&&(a.border=[1,1,1,1]),t.borderhighlight&&(a.borderhighlight=t.borderhighlight),typeof t.winblend=="number"&&(a.winblend=t.winblend);let{nvim:l}=y;l.call("coc#dialog#create_pum_float",[r,a],!0),l.redrawVim()}}close(){y.nvim.call("coc#pum#close_detail",[],!0),y.nvim.redrawVim()}cancel(){this.resolveTokenSource&&(this.resolveTokenSource.cancel(),this.resolveTokenSource=void 0)}requestWithToken(e){let t=this.resolveTokenSource=new p.CancellationTokenSource;return new Promise((i,r)=>{let o=!1,s=u=>{o||(o=!0,l.dispose(),clearTimeout(a),this.resolveTokenSource===t&&(this.resolveTokenSource=void 0),u?r(u):i())},a=setTimeout(()=>{t.cancel()},Ame),l=t.token.onCancellationRequested(()=>{s(new Rt)});e(t.token).then(()=>{s()},u=>{s(u)})})}}});function SV(n,e,t,i,r,o){for(let s of dv(e,t,2,o))n.push({hlGroup:"CocPumSearch",lnum:r,colStart:i+s[0],colEnd:i+s[1]})}function Nme(n,e,t){if(e.length===0)return n;for(let i=t;i{"use strict";Eg();Re();pc();Xe();Vs();fe();he();jl();Dm=class{constructor(e,t){this.config=e;this.mruLoader=t;this._search=""}get nvim(){return y.nvim}get search(){return this._search}reset(){this._search="",this._pumConfig=void 0}get pumConfig(){if(this._pumConfig)return this._pumConfig;let{floatConfig:e,pumFloatConfig:t,reversePumAboveCursor:i}=this.config;t||(t=e);let r={};return $e(t.highlight)&&(r.highlight=t.highlight),$t(t.winblend)&&(r.winblend=t.winblend),t.shadow&&(r.shadow=t.shadow),t.border&&(r.border=[1,1,1,1],r.rounded=t.rounded?1:0,r.borderhighlight=t.borderhighlight??"CocFloating"),r.reverse=i===!0,this._pumConfig=r,r}stringWidth(e,t=!1){return y.getDisplayWidth(e,t)}show(e,t,i){this._search=t;let{noselect:r,enablePreselect:o,invalidInsertCharacters:s,selection:a,virtualText:l,kindMap:u,defaultKindText:c}=this.config,d=s.map(ye=>ye.charCodeAt(0)),h=o?e.findIndex(ye=>ye.preselect):-1,g=-1,f=0,m=0,b=0,v=0,x=h==-1&&!r&&a!=="first",C=[],T=Ut(i.line,i.col);for(let ye=0;yeg&&(g=H,h=ye)}$t(Fe.character)&&Fe.character0&&(e[h].word.startsWith(t)||(h=-1)),!r)h=h==-1?0:h;else{if(h>0){let[ye]=e.splice(h,1);e.unshift(ye);let[Fe]=C.splice(h,1);C.unshift(Fe)}h=-1}let j={input:t,index:h,bufnr:i.bufnr,line:i.linenr,col:i.col,startcol:nt(i.line,T),virtualText:l,words:e.map(ye=>{let Fe=ye.character,$=Math.max(1,i.position.character-Fe+1),H=Nme(ye.word,d,$);return Hme(H,Fe,i.line,T)})},N=this.pumConfig,X=[],se=[],Y=0,K={border:!!N.border,menuWidth:m,abbrWidth:f,kindWidth:b,shortcutWidth:v};this.adjustAbbrWidth(K);let B=t.toLowerCase();for(let ye=0;yeo&&(l=l.slice(0,o-1)+"."),{text:l,highlights:u}}adjustAbbrWidth(e){let{formatItems:t}=this.config,i=rn(y.env.pumwidth,15),r=0;for(let o of t)o=="abbr"?r+=e.abbrWidth+1:o=="menu"&&e.menuWidth?r+=e.menuWidth+1:o=="kind"&&e.kindWidth?r+=e.kindWidth+1:o=="shortcut"&&e.shortcutWidth&&(r+=e.shortcutWidth+1);r{let x=this.fillWidth(b,v);f+=v,g+=ue(x),h+=x};for(let b of u)switch(b){case"abbr":{if(!re(i.positions)){let C=FX(g,i);if(C!=-1)SV(o,i.abbr,i.positions,C,s,l);else{let k=na(e,t,0,i.abbr,i.abbr.toLowerCase(),0);SV(o,i.abbr,k,0,s,l)}}let v=r.text,x=g;m(v,a.abbrWidth+1),r.highlights.forEach(C=>{o.push({hlGroup:C.hlGroup,lnum:s,colStart:x+C.start,colEnd:x+C.end})}),i.deprecated&&o.push({hlGroup:"CocPumDeprecated",lnum:s,colStart:x,colEnd:g-1});break}case"menu":{if(a.menuWidth>0){let v=g;m(oe(i.menu),a.menuWidth+1),i.menu&&o.push({hlGroup:"CocPumMenu",lnum:s,colStart:v,colEnd:v+ue(i.menu)})}break}case"kind":if(a.kindWidth>0){let{kind:v}=i,x=bR(v,c,d),C=g;m(oe(x),a.kindWidth+1),x&&o.push({hlGroup:TX(v),lnum:s,colStart:C,colEnd:C+ue(x)})}break;case"shortcut":if(a.shortcutWidth>0){let v=g,x=i.shortcut;m(x?`[${x}]`:"",a.shortcutWidth+1),x&&o.push({hlGroup:"CocPumShortcut",lnum:s,colStart:v,colEnd:v+ue(x)+2})}break}return[f,h]}fillWidth(e,t){let i=t-this.stringWidth(e);return e+" ".repeat(Math.max(i,0))}}});var H0,Bme,qme,B0,Tm,TV=D(()=>{"use strict";ae();Je();Dt();Pe();xe();te();Re();Xe();de();Vs();Be();fe();We();he();xV();CV();DV();uu();pa();jl();H0=Z("completion"),Bme=pe(200,20),qme=pe(10,0),B0=class{constructor(){this.disposables=[];this.complete=null;this.activeItems=[]}get nvim(){return y.nvim}init(){this.loadConfiguration(),y.onDidChangeConfiguration(this.loadConfiguration,this,this.disposables),P.onDidChangeActiveTextEditor(e=>{this.loadLocalConfig(e.document)},null,this.disposables),this._mru=new lw,this.pum=new Dm(this.staticConfig,this._mru),this.floating=new Sm(this.staticConfig),this._debounced=ft(this.onCursorMovedI.bind(this),qme),_.on("CursorMoved",()=>{this.stop(!0)},null,this.disposables),_.on("CursorMovedI",this._debounced,this,this.disposables),_.on("CursorMovedI",()=>{clearTimeout(this.triggerTimer)},null,this.disposables),_.on("CompleteStop",e=>{this.stop(!1,e)},null,this.disposables),_.on("InsertEnter",this.onInsertEnter,this,this.disposables),_.on("TextChangedI",this.onTextChangedI,this,this.disposables),_.on("TextChangedP",this.onTextChangedP,this,this.disposables),_.on("MenuPopupChanged",async e=>{if(!this.option)return;this.popupEvent=e;let t=this.complete.resolveItem(this.selectedItem);if(!t||!e.move&&this.complete.isCompleting)return;let i=this.selectedItem.detailRendered,r=this.config.enableFloat;await this.floating.resolveItem(t.source,t.item,this.option,r,i)},null,this.disposables),this.nvim.call("coc#ui#check_pum_keymappings",[this.config.autoTrigger],!0),V.registerCommand("editor.action.triggerSuggest",async e=>{await this.startCompletion({source:e})},this,!0)}get mru(){return this._mru}onCursorMovedI(e,t,i){if(i||!this.option||e!==this.option.bufnr)return;let{linenr:r,colnr:o,col:s}=this.option;if(r===t[0]){if(t[1]==o&&t[1]===ue(oe(this.pretext))+1)return;let a=this.document.getline(t[0]-1);if(a.match(/^\s*/)[0]!==this.option.line.match(/^\s*/)[0])return;let l=Ut(a,t[1]-1),u=Ut(a,s);if(u{if(clearTimeout(this.triggerTimer),r.isEmpty){this.stop(!1);return}this.inserted||await this.filterResults()}),await r.doComplete()&&this.stop(!1)}async onTextChangedP(e,t){!t.insertChar&&this.complete&&this.complete.cancel(),this.pretext=t.pre}async onTextChangedI(e,t){let i=y.getDocument(e);if(!i||!i.attached)return;let{option:r}=this;if(r!=null){if(!t.insertChar){let s=Xt(r.line,0,r.col);if(this.selectedItem){let{word:a,startcol:l}=this.popupEvent;if(Xt(r.line,0,l)+a==t.pre){this.pretext=t.pre;return}}else if(s+this.pum.search==t.pre)return}if(t.pre.match(/^\s*/)[0]!==r.line.match(/^\s*/)[0]){await this.triggerCompletion(i,t);return}IX(e,this.pretext,t,r)&&this.stop(!0)}if(t.pre===this.pretext)return;clearTimeout(this.triggerTimer);let o=this.pretext=t.pre;if(!t.insertChar){this.complete&&await this.filterResults();return}if(this.config.acceptSuggestionOnCommitCharacter&&this.selectedItem){let s=o.slice(-1),a=this.selectedItem,l=this.complete.resolveItem(a);if(l&&Pi.shouldCommit(l.source,l.item,s)){H0.debug("commit by commit character.");let u=nt(this.option.line,a.character)+1;this.stop(!0),this.nvim.call("coc#pum#repalce",[u,a.word+t.insertChar],!0);return}}if(!i.chars.isKeywordChar(t.insertChar)){let s=this.getTriggerSources(i,o);if(s.length>0){await this.triggerCompletion(i,t,s);return}}if(!this.complete){await this.triggerCompletion(i,t);return}if(this.complete.isEmpty){this.triggerTimer=setTimeout(async()=>{await this.triggerCompletion(i,t)},Bme);return}await this.filterResults(t)}getTriggerSources(e,t){let i=e.getVar("disabled_sources",[]);return this.config.autoTrigger==="none"?[]:Pi.getTriggerSources(t,e.filetype,e.uri,i)}async triggerCompletion(e,t,i){let{minTriggerInputLength:r,autoTrigger:o}=this.config,{pre:s}=t;if(o==="none"||!i&&!this.shouldTrigger(e,s))return!1;let a=this.getCompleteOption(e,t);return i==null&&a.input.length0){await this.triggerCompletion(a,e,l);return}}if(s.length==0){let l=o.slice(-1);(!t.isCompleting||l.length===0||!a.chars.isKeywordChar(l))&&this.stop(!0);return}this.activeItems=s,this.pum.show(s,o,this.option)}cancel(){this.complete!=null&&(this.complete.dispose(),this.complete=null),this.triggerTimer!=null&&(clearTimeout(this.triggerTimer),this.triggerTimer=null),this.pretext=void 0,this.activeItems=[],this.popupEvent=void 0}dispose(){W(this.disposables)}},Tm=new B0});function q0(n,e){let t=[];for(let i=e.start.line;i<=e.end.line;i++){let r=n.getline(i)||"",o=i==e.start.line?e.start.character:0,s=i==e.end.line?e.end.character:r.length;o!=s&&t.push(M.create(i,o,i,s))}return t}function kV(n,e){let{start:t,end:i}=Wv(e),r=t.character{"use strict";ae();Be();wr()});var gu,Y0=D(()=>{"use strict";ae();Tt();wr();Rm();gu=class{constructor(e,t,i){this.start=Q.create(e,t),this._text=i,this.end=on(this.start,this._text)}get position(){return this.start}get line(){return this.start.line}get text(){return this._text}get range(){return M.create(this.start,this.end)}get textEdit(){return{range:this.range,newText:this.text}}applyChange(e){W0(e)?this.applySurrondChange(e):this.applyTextChange(e)}applySurrondChange(e){let{prepend:t,append:i}=e,r=this._text.length,o=this._text.substring(t[0],r-i[0]);this._text=`${t[1]}${o}${i[1]}`}applyTextChange(e){let{text:t}=this,{offset:i,remove:r,fromEnd:o,insert:s}=e;o&&(i=-i);let a=t.slice(0,o&&i==0?t.length:i),l=t.slice(a.length);r&&(l=l.slice(r)),this._text=`${a}${s||""}${l}`}move(e){if(e!=0){let{line:t,character:i}=this.start;this.start=Q.create(t,i+e)}this.end=on(this.start,this._text)}adjustFromEdit(e){let t=Yv(this.start,e);if(t.line||t.character){let{line:i,character:r}=this.start;this.start=Q.create(i+t.line,r+t.character),this.end=on(this.start,this._text)}return t.character}isBefore(e){let{position:t}=e,{line:i,character:r}=this.start;return t.line==i&&t.character>r}}});function Wme(n,e){return!(n.length!=2||n[0].offset!=0||n[1].offset+(n[1].remove?n[1].remove.length:0)!==e)}var _m,Em,PV=D(()=>{"use strict";Wg();ae();xe();te();de();Tt();U();wr();We();he();Y0();Rm();_m=Z("cursors-session"),Em=class{constructor(e,t,i){this.nvim=e;this.doc=t;this.config=i;this._onDidCancel=new p.Emitter;this._onDidUpdate=new p.Emitter;this.onDidCancel=this._onDidCancel.event;this.onDidUpdate=this._onDidUpdate.event;this.disposables=[];this.ranges=[];this.activated=!0;this.changing=!1;let{bufnr:r}=t;t.buffer.setVar("coc_cursors_activated",1,!0);let{cancelKey:o,nextKey:s,previousKey:a}=this.config;this.disposables.push(y.registerLocalKeymap(r,"n",o,()=>{this.cancel()})),this.disposables.push(y.registerLocalKeymap(r,"n",s,async()=>{let l=this.ranges.map(d=>d.range),u=await P.getCursorPosition();for(let d of l)if(Ge(d.start,u)>0){await P.moveTo(d.start);return}let c=this.config.wrapscan;l.length&&c&&await P.moveTo(l[0].start)})),this.disposables.push(y.registerLocalKeymap(r,"n",a,async()=>{let l=this.ranges.map(d=>d.range),u=await P.getCursorPosition();for(let d=l.length-1;d>=0;d--){let h=l[d];if(Ge(h.end,u)<0){await P.moveTo(h.start);return}}let c=this.config.wrapscan;l.length&&c&&await P.moveTo(l[l.length-1].start)})),this.doc.onDocumentChange(async l=>{await this.onChange(l),this.activated&&!this.changing&&this._onDidUpdate.fire()},this,this.disposables)}addRange(e){let{ranges:t}=this,i=t.findIndex(r=>Ll(r.range,e));i!==-1?t.splice(i,1):(this.createRange(e),t.sort((r,o)=>Ge(r.range.start,o.range.start))),this.ranges.length==0?this.cancel():this.doHighlights()}addRanges(e){this.doc._forceSync(),this.ranges=this.ranges.filter(t=>!e.some(i=>Tc(i,t.range)));for(let t of e)this.createRange(t);return this.ranges.sort((t,i)=>Ge(t.range.start,i.range.start)),this.doHighlights(),!0}createRange(e){let{textDocument:t}=this.doc,{line:i,character:r}=e.start,o=t.getText(e);this.ranges.push(new gu(i,r,o))}async onChange(e){if(!this.activated||this.changing)return;if(e.contentChanges.length===0){this.doHighlights();return}let t=e.contentChanges[0],{text:i,range:r}=t,o=this.ranges.filter(s=>!(!Ll(r,s.range)||qv(r,s.range)&&(i.includes(` +`)||!Gt(r))));if(Gt(r)&&o.length>0&&(o=o.slice(0,1)),o.length==0)_m.debug("no affected ranges"),this.ranges.forEach(s=>{s.adjustFromEdit({range:r,newText:i})}),this.doHighlights();else if(o.length==1&&ti(r,o[0].range)){if(_m.debug("affected single range"),i.includes(` +`)){this.cancel();return}await this.applySingleEdit(o[0],{range:r,newText:i})}else if(!i.length||!this.validChange(r,i)){_m.debug("filter affected ranges.");let s=this.ranges.filter(a=>!o.includes(a));s.length>0?(this.ranges=s,s.forEach(a=>{a.adjustFromEdit({range:r,newText:i})}),this.doHighlights()):this.cancel()}else{_m.debug("Check undo & redo");let s=this.ranges[0],a=this.ranges[this.ranges.length-1],l=e.originalLines.slice(s.line,a.line+1),u=this.doc.textDocument.lines.slice(s.line,a.line+1);this.applyComposedEdit(l,u)}}validChange(e,t){if(ca(Ye.replace(e,t))!=0||!ti(e,this.range))return!1;let i=this.ranges[0],r=this.ranges[this.ranges.length-1];return!(e.start.line!=i.position.line||e.end.line!=r.position.line)}get range(){let e=this.ranges[0],t=this.ranges[this.ranges.length-1];return M.create(e.position,t.range.end)}doHighlights(){let{nvim:e,ranges:t,doc:i}=this,r=i.buffer,o=[];t.forEach(s=>{i.addHighlights(o,"CocCursorRange",s.range,{combine:!1,start_incl:!0,end_incl:!0})}),o.sort((s,a)=>s.lnum!=a.lnum?s.lnum-a.lnum:s.colStart!=a.colStart?s.colStart-a.colStart:0),r.updateHighlights("cursors",o,{priority:4096}),e.redrawVim()}get currentRanges(){return this.ranges.map(e=>e.range)}cancel(){if(!this.activated)return;_m.debug("cursors cancel");let e=this.doc.buffer;this.activated=!1,this.ranges=[],e.clearNamespace("cursors"),e.setVar("coc_cursors_activated",0,!0),this._onDidUpdate.fire(),this._onDidCancel.fire()}dispose(){!this.doc||(this._onDidCancel.dispose(),this._onDidUpdate.dispose(),W(this.disposables),this.ranges=[],this.doc=null)}async applySingleEdit(e,t){let{doc:i,ranges:r}=this;r.filter(u=>u!==e&&u.position.line==e.position.line).forEach(u=>u.adjustFromEdit(t));let s=iS(e,t.range,t.newText),a=km(s);r.forEach(u=>u.applyChange(s));let l=r.filter(u=>u!==e).map(u=>u.textEdit);if(this.changing=!0,await i.applyEdits(l,!0,!0),this.changing=!1,a!=0)for(let u of r){let c=Pm(u,this.ranges,e);u.move(c*a)}this.doHighlights()}applyComposedEdit(e,t){let i=fi(e[0],t[0]),r=this.ranges[0],o=r.position.character,s=r.position.line,a=r.text.length,l=i[0];if(o>0&&(l[0]!=fi.EQUAL||!l[1].startsWith(e[0].slice(0,o))))return this.cancel(),!1;let u=0,c=!1,d=[];for(let v=0;v0&&(C=C.slice(o)),x==fi.EQUAL){if(u+=C.length,u>a)break}else if(x==fi.DELETE){let k=u;if(u+=C.length,u>a){c=!0;break}d.push({offset:k,remove:C})}else{let k=i[v-1];k&&k[0]==fi.DELETE?d[d.length-1].add=C:d.push({offset:u,add:C})}}if(c||!d.length)return this.cancel(),!1;let h=Qr.create("file:///1","",0,e.join(` +`)),g;if(d.length==1)g={offset:d[0].offset,remove:d[0].remove?d[0].remove.length:0,insert:d[0].add??""};else if(Wme(d,a))g={prepend:[d[0].remove?d[0].remove.length:0,d[0].add??""],append:[d[1].remove?d[1].remove.length:0,d[1].add??""]};else{let v=r.text,x="",C="",k=d[0].offset;for(let T of d){if(T.offset>k+x.length){let j=v.slice(k+x.length,T.offset);x+=j,C+=j}T.add&&(C+=T.add),T.remove&&(x+=T.remove)}g={offset:k,remove:x.length,insert:C}}let f=this.ranges.map(v=>{let x=v.position.line-s,{start:C,end:k}=v.range,T=M.create(x,C.character,x,k.character);return v.applyChange(g),Ye.replace(T,v.text)});if(Qr.applyEdits(h,f)!==t.join(` +`))return this.cancel(),!1;let b=km(g);if(b!=0)for(let v of this.ranges){let x=Pm(v,this.ranges);v.move(x*b)}return this.doHighlights(),!0}}});var Im,RV=D(()=>{"use strict";ae();We();he();Dt();PV();Rm();Im=class{constructor(e){this.nvim=e;this.sessionsMap=new Map;this.disposables=[];this.loadConfiguration(),y.onDidChangeConfiguration(this.loadConfiguration,this,this.disposables),y.onDidCloseTextDocument(t=>{let i=this.getSession(t.bufnr);!i||(this.sessionsMap.delete(t.bufnr),i.dispose())},null,this.disposables),this.disposables.push(V.registerCommand("editor.action.addRanges",async t=>{await this.addRanges(t)},null,!0))}loadConfiguration(e){if(!e||e.affectsConfiguration("cursors")){let t=y.initialConfiguration;this.config=t.get("cursors")}}cancel(e){let t=y.getDocument(e);if(!t)return;let i=this.getSession(t.bufnr);i&&i.cancel()}getSession(e){return this.sessionsMap.get(e)}async isActivated(){let e=await this.nvim.call("bufnr",["%"]);return this.sessionsMap.get(e)!=null}async select(e,t,i){let r=y.getAttachedDocument(e),{nvim:o}=this,s=this.createSession(r),a;if(t=="operator"){let l=await o.eval(`[getpos("'["),getpos("']")]`);if(i=="char"){let u=r.getPosition(l[0][1],l[0][2]),c=r.getPosition(l[1][1],l[1][2]+1),d=q0(r,M.create(u,c));s.addRanges(d)}else{let u=[];for(let c=l[0][1]-1;c<=l[1][1]-1;c++){let d=r.getline(c);u.push(M.create(c,0,c,d.length))}s.addRanges(u)}}else if(t=="word"){let l=await P.getCursorPosition();if(a=r.getWordRangeAtPosition(l),!a){let u=r.getline(l.line);l.character==u.length?a=M.create(l.line,Math.max(0,u.length-1),l.line,u.length):a=M.create(l.line,l.character,l.line,l.character+1)}s.addRange(a),await o.command(`silent! call repeat#set("\\(coc-cursors-${t})", -1)`)}else if(t=="position"){let l=await P.getCursorPosition(),u=r.getline(l.line);l.character>=u.length?a=M.create(l.line,u.length-1,l.line,u.length):a=M.create(l.line,l.character,l.line,l.character+1),s.addRange(a),await o.command(`silent! call repeat#set("\\(coc-cursors-${t})", -1)`)}else if(t=="range"){await o.call("eval",'feedkeys("\\", "in")');let l=await P.getSelectedRange(i);if(!l)return;let u=i==""?kV(r,l):q0(r,l);for(let c of u)s.addRange(c)}else throw new Error(`select kind "${t}" not supported`)}createSession(e){let{bufnr:t}=e,i=this.getSession(t);return i||(i=new Em(this.nvim,e,this.config),this.sessionsMap.set(t,i),i.onDidCancel(()=>{i.dispose(),this.sessionsMap.delete(t)}),i)}async addRanges(e){let{nvim:t}=this,i=await t.call("bufnr",["%"]),r=y.getAttachedDocument(i);return this.createSession(r).addRanges(e)}reset(){for(let e of this.sessionsMap.values())e.cancel();this.sessionsMap.clear()}}});function _V(n,e,t){!Array.isArray(e)||t&&t.isCancellationRequested||(e.forEach(i=>i.parent=n),n.children=e)}var Z0,Aa,J0=D(()=>{"use strict";ae();Je();Dt();de();U();he();vp();Z0=class{constructor(e,t,i,r,o,s,a){this.meta=e;this.winid=t;this.config=i;this.commandId=r;this.rootItems=o;this.getIcon=s;this.resolveChildren=a;this._onDidChangeTreeData=new p.Emitter;this.onDidChangeTreeData=this._onDidChangeTreeData.event;this.actions=[];this.addAction("Open in new tab",async l=>{await V.executeCommand(this.commandId,t,l,"tabe")}),this.addAction("Dismiss",async l=>{if(l.parent==null){let u=this.rootItems.filter(c=>c!==l);this.reset(u)}else{let u=l.parent,c=u.children.findIndex(d=>d===l);u.children.splice(c,1),this._onDidChangeTreeData.fire(u)}})}cancel(){this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=void 0)}reset(e){this.rootItems=e,this._onDidChangeTreeData.fire(void 0)}addAction(e,t){this.actions.push({title:e,handler:t})}async getChildren(e){this.cancel(),this.tokenSource=new p.CancellationTokenSource;let{token:t}=this.tokenSource;if(!e){for(let r of this.rootItems){let o=await this.resolveChildren(r,this.meta,t);_V(r,o,t)}return this.rootItems}if(e.children)return e.children;let i=await this.resolveChildren(e,this.meta,t);return this.tokenSource=void 0,_V(e,i,t),i}getTreeItem(e){var i;let t=new Vr(e.name,e.children?2:1);return this.config.enableTooltip&&(t.tooltip=R.relative(y.cwd,O.parse(e.uri).fsPath)),t.description=e.detail,t.deprecated=(i=e.tags)==null?void 0:i.includes($i.Deprecated),t.icon=this.getIcon(e.kind),t.command={command:this.commandId,title:"open location",arguments:[this.winid,e,this.config.openCommand]},t}resolveActions(){return this.actions}dispose(){this.cancel(),y.nvim.createWindow(this.winid).clearMatchGroup(Z0.rangesHighlight)}},Aa=Z0;Aa.rangesHighlight="CocSelectedRange"});function EV(n){return ci(n,["children","parent","ranges","sourceUri"])}function IV(n){return!!(n&&typeof n.name=="string"&&n.kind&&M.is(n.range))}function LV(n){return`${n.toUpperCase()} CALLS`}var Es,pu,FV=D(()=>{"use strict";ae();Dt();Pe();Se();J0();wp();te();Re();io();U();We();he();Es=class{constructor(e,t){this.nvim=e;this.handler=t;this.disposables=[];this.highlightWinids=new Set;this.loadConfiguration(),y.onDidChangeConfiguration(this.loadConfiguration,this,this.disposables),this.disposables.push(V.registerCommand(Es.commandId,async(i,r,o)=>{var l;let{nvim:s}=this;await s.call("win_gotoid",[i]),await y.jumpTo(r.uri,r.selectionRange.start,o);let a=await s.window;if(a.clearMatchGroup(Es.rangesHighlight),a.highlightRanges(Es.rangesHighlight,[r.selectionRange],10,!0),!!((l=r.ranges)!=null&&l.length)){if(r.sourceUri){let u=y.getDocument(r.sourceUri);if(!u)return;let c=await s.call("coc#compat#buf_win_id",[u.bufnr]);if(c==-1)return;c!=a.id&&(a=s.createWindow(c),a.clearMatchGroup(Es.rangesHighlight))}a.highlightRanges(Es.rangesHighlight,r.ranges,100,!0),this.highlightWinids.add(a.id)}},null,!0)),_.on("BufWinEnter",(i,r)=>{this.highlightWinids.has(r)&&(this.highlightWinids.delete(r),e.createWindow(r).clearMatchGroup(Es.rangesHighlight))},null,this.disposables),V.register({id:"document.showIncomingCalls",execute:async()=>{await this.showCallHierarchyTree("incoming")}},!1,"show incoming calls in tree view."),V.register({id:"document.showOutgoingCalls",execute:async()=>{await this.showCallHierarchyTree("outgoing")}},!1,"show outgoing calls in tree view.")}loadConfiguration(e){if(!e||e.affectsConfiguration("callHierarchy")){let t=y.getConfiguration("callHierarchy",null);this.config={splitCommand:t.get("splitCommand"),openCommand:t.get("openCommand"),enableTooltip:t.get("enableTooltip")}}}createProvider(e,t,i,r){let o=new Aa(r,i,this.config,Es.commandId,e,s=>this.handler.getIcon(s),(s,a,l)=>this.getChildren(t,s,a,l));for(let s of["incoming","outgoing"]){let a=s==="incoming"?"Show Incoming Calls":"Show Outgoing Calls";o.addAction(a,l=>{o.meta=s;let u=[EV(l)];o.reset(u)})}return o}async getChildren(e,t,i,r){let o=[],s=EV(t);if(i=="incoming"){let a=await I.provideIncomingCalls(e,s,r);a&&(o=a.map(l=>Object.assign(l.from,{ranges:l.fromRanges})))}else{let a=await I.provideOutgoingCalls(e,s,r);a&&(o=a.map(l=>Object.assign(l.to,{ranges:l.fromRanges,sourceUri:t.uri})))}return o}async prepare(e,t,i){this.handler.checkProvider("callHierarchy",e);let r=await I.prepareCallHierarchy(e,t,i);return IV(r)?[r]:r}async getCallHierarchyItems(e,t){let{doc:i,position:r}=await this.handler.getCurrentState(),o=new p.CancellationTokenSource;if(!e){await i.synchronize();let a=await this.prepare(i.textDocument,r,o.token);if(e=a?a[0]:void 0,!a)throw new Error("Unable to getCallHierarchyItem at current position")}let s=t=="incoming"?"provideIncomingCalls":"provideOutgoingCalls";return await I[s](i.textDocument,e,o.token)}async getIncoming(e){return await this.getCallHierarchyItems(e,"incoming")}async getOutgoing(e){return await this.getCallHierarchyItems(e,"outgoing")}async showCallHierarchyTree(e){let{doc:t,position:i,winid:r}=await this.handler.getCurrentState();if(await t.synchronize(),!I.hasProvider("callHierarchy",t.textDocument)){P.showErrorMessage("CallHierarchy provider not found for current document, it's not supported by your languageserver");return}let o=await I.prepareCallHierarchy(t.textDocument,i,p.CancellationToken.None),s=IV(o)?[o]:o;if(re(s)){P.showWarningMessage("Unable to get CallHierarchyItem at cursor position.");return}let a=this.createProvider(s,t.textDocument,r,e),l=new So("calls",{treeDataProvider:a});l.title=LV(e),a.onDidChangeTreeData(u=>{u||(l.title=LV(a.meta))}),l.onDidChangeVisibility(u=>{u.visible||a.dispose()}),this.disposables.push(l),await l.show(this.config.splitCommand)}dispose(){this.highlightWinids.clear(),W(this.disposables)}},pu=Es;pu.commandId="callHierarchy.reveal",pu.rangesHighlight="CocSelectedRange"});function Yme(n){return n?typeof n=="string"||n[0]===ri.QuickFix||n[0]===ri.SourceFixAll:!1}var Lm,MV=D(()=>{"use strict";ae();Dt();Hc();Se();Vs();We();he();Lm=class{constructor(e,t){this.nvim=e;this.handler=t;t.addDisposable(V.registerCommand("editor.action.organizeImport",async()=>{await this.organizeImport()||P.showWarningMessage("Organize import action not found")})),V.titles.set("editor.action.organizeImport","Run organize import code action, show warning when not exists")}async codeActionRange(e,t,i){let{doc:r}=await this.handler.getCurrentState();await r.synchronize();let o=r.getline(t-1),s=M.create(e-1,0,t-1,o.length),a=await this.getCodeActions(r,s,i?[i]:null);if(a=a.filter(c=>!c.disabled),!a||a.length==0){P.showWarningMessage(`No${i?" "+i:""} code action available`);return}let l=await P.showMenuPicker(a.map(c=>c.title),"Choose action"),u=a[l];u&&await this.applyCodeAction(u)}async organizeImport(){let{doc:e}=await this.handler.getCurrentState();await e.synchronize();let t=await this.getCodeActions(e,void 0,[ri.SourceOrganizeImports]);return t&&t.length?(await this.applyCodeAction(t[0]),!0):!1}async getCodeActions(e,t,i){t=t??M.create(0,0,e.lineCount,0);let o={diagnostics:ui.getDiagnosticsInRange(e.textDocument,t),triggerKind:es.Invoked};i&&Array.isArray(i)&&(o.only=i);let s=await this.handler.withRequestToken("code action",a=>I.getCodeActions(e.textDocument,t,o,a));return!s||s.length==0?[]:(s.sort((a,l)=>a.disabled&&!l.disabled?1:l.disabled&&!a.disabled?-1:a.isPreferred!=l.isPreferred?Vk(l.isPreferred)-Vk(a.isPreferred):0),s)}get floatActions(){return y.floatSupported?y.getConfiguration("coc.preferences",null).get("floatActions",!0):!1}async doCodeAction(e,t,i=!1){let{doc:r}=await this.handler.getCurrentState(),o;e&&(o=await P.getSelectedRange(e)),await r.synchronize();let s=await this.getCodeActions(r,o,Array.isArray(t)?t:null);if(typeof t=="string"?s=s.filter(u=>u.title==t||u.command&&u.command.title==t):Array.isArray(t)&&(s=s.filter(u=>t.some(c=>u.kind&&u.kind.startsWith(c)))),(!this.floatActions||!i)&&(s=s.filter(u=>!u.disabled)),!s||s.length==0){P.showWarningMessage(`No${t?" "+t:""} code action available`);return}if(s.length==1&&!s[0].disabled&&Yme(t)){await this.applyCodeAction(s[0]);return}let a=this.floatActions?await P.showMenuPicker(s.map(u=>({text:u.title,disabled:u.disabled})),"Choose action"):await P.showQuickpick(s.map(u=>u.title)),l=s[a];l&&await this.applyCodeAction(l)}async getCurrentCodeActions(e,t){let{doc:i}=await this.handler.getCurrentState(),r;return e&&(r=await P.getSelectedRange(e)),(await this.getCodeActions(i,r,t)).filter(s=>!s.disabled)}async doQuickfix(){let e=await this.getCurrentCodeActions("currline",[ri.QuickFix]);if(!e||e.length==0){P.showWarningMessage("No quickfix action available");return}await this.applyCodeAction(e[0]),this.nvim.command('silent! call repeat#set("\\(coc-fix-current)", -1)',!0)}async applyCodeAction(e){if(e.disabled)throw new Error(`Action "${e.title}" is disabled: ${e.disabled.reason}`);let t=await this.handler.withRequestToken("resolve codeAction",o=>I.resolveCodeAction(e,o)),{edit:i,command:r}=t;i&&await y.applyEdit(i),r&&await V.execute(r)}}});function kd(n){Zme.error("Error on handler: ",yr(n))}var Zme,$0=D(()=>{"use strict";xe();fe();Zme=Z("handler-util")});function $me(n){return n=="top"?"above":n=="eol"?"after":n==="right_align"?"right":"above"}function Ume(n,e){if(!(e!=null&&e.length))return[];let t=[];for(let i of e){let{range:r,command:o}=i;!mh(o)||n==r.start.line&&t.push(o)}return t}var F7e,Pd,jV,U0,Jme,Fm,OV=D(()=>{"use strict";Dt();Se();xe();te();Re();Xe();de();U();We();he();$0();F7e=Z("codelens-buffer"),jV=pe(200,20),U0="CocCodeLens",Jme="Normal",Fm=class{constructor(e,t){this.nvim=e;this.document=t;this.display=!0;this.resolveCodeLens=ft(()=>{this._resolveCodeLenses().catch(kd)},jV),this.debounceFetch=ft(()=>{this.fetchCodeLenses().catch(kd)},jV),this.hasProvider&&this.debounceFetch()}get config(){return this._config?this._config:(this.loadConfiguration(),this._config)}loadConfiguration(){let e=y.getConfiguration("codeLens",this.document);this._config={enabled:e.get("enable",!1),position:e.get("position","top"),separator:e.get("separator",""),subseparator:e.get("subseparator"," ")}}async toggleDisplay(){this.display?(this.display=!1,this.clear()):(this.display=!0,this.resolveCodeLens.clear(),await this._resolveCodeLenses())}get bufnr(){return this.document.bufnr}onChange(e){e.contentChanges.length===0&&this.codeLenses!=null?(this.resolveCodeLens.clear(),this._resolveCodeLenses().catch(kd)):(this.cancel(),this.debounceFetch())}get currentCodeLens(){var e;return(e=this.codeLenses)==null?void 0:e.codeLenses}get hasProvider(){return I.hasProvider("codeLens",this.document)}async forceFetch(){!this.config.enabled||!this.hasProvider||(await this.document.synchronize(),this.cancel(),await this.fetchCodeLenses())}async fetchCodeLenses(){var t;if(!this.hasProvider||!this.config.enabled)return;if(!(((t=this.codeLenses)==null?void 0:t.version)==this.document.version)){let i=this.codeLenses==null,{textDocument:r}=this.document,o=r.version;this.cancelFetch();let a=(this.tokenSource=new p.CancellationTokenSource).token;Pd||(Pd=await this.nvim.createNamespace("coc-codelens"));let l=await I.getCodeLens(r,a);if(a.isCancellationRequested)return;if(l=Ie(l,[]),l=l.filter(u=>u!=null),re(l)){this.clear();return}this.codeLenses={version:o,codeLenses:l},i&&this.setVirtualText(l)}this.resolveCodeLens.clear(),await this._resolveCodeLenses()}async _resolveCodeLenses(){if(!this.codeLenses||this.isChanged)return;let{codeLenses:e}=this.codeLenses,[t,i,r,o]=await this.nvim.eval("[bufnr('%'),line('w0'),line('w$'),line('$')]");if(!(this.isChanged||t!=this.bufnr)){if(this.cancel(),e=e.filter(s=>{let a=s.range.start.line+1;return a>=i&&a<=r}),e.length){let a=(this.resolveTokenSource=new p.CancellationTokenSource).token;if(await Promise.all(e.map(l=>mh(l.command)?Promise.resolve():(l.command=void 0,I.resolveCodeLens(l,a)))),this.resolveTokenSource=void 0,a.isCancellationRequested||this.isChanged)return}r==o&&(r=-1),this.nvim.pauseNotification(),this.clear(i-1,r),this.setVirtualText(e),this.nvim.resumeNotification(!0,!0)}}get isChanged(){if(!this.codeLenses||this.document.dirty)return!0;let{version:e}=this.codeLenses;return this.document.textDocument.version!==e}setVirtualText(e){let{document:t}=this;if(!Pd||!t||!e.length||!this.display)return;let i=this.config.position==="top",r=new Map;for(let o of e){let{line:s}=o.range.start,a=r.get(s)??[];a.push(o),r.set(s,a)}for(let o of r.keys()){let a=r.get(o).reduce((c,d)=>(d&&d.command&&d.command.title&&c.push(d.command.title.replace(/\s+/g," ")),c),[]),l=[],u=a.length;for(let c=0;c0&&this.config.separator&&l.unshift([`${this.config.separator} `,U0]),i&&l.length==0&&l.push([" ",Jme]),l.length>0&&t.buffer.setVirtualText(Pd,o,l,{text_align:$me(this.config.position),indent:!0})}}clear(e=0,t=-1){if(!Pd)return;this.nvim.createBuffer(this.bufnr).clearNamespace(Pd,e,t)}async doAction(e){var i;let t=Ume(e,(i=this.codeLenses)==null?void 0:i.codeLenses);if(t.length==1)await V.execute(t[0]);else if(t.length>1){let r=await P.showMenuPicker(t.map(o=>o.title));r!=-1&&await V.execute(t[r])}}cancelFetch(){this.debounceFetch.clear(),this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null)}cancelResolve(){this.resolveTokenSource&&(this.resolveTokenSource.cancel(),this.resolveTokenSource=null)}cancel(){this.resolveCodeLens.clear(),this.cancelResolve(),this.cancelFetch()}abandonResult(){this.codeLenses=void 0}dispose(){this.cancel(),this.codeLenses=void 0}}});var Xme,Mm,AV=D(()=>{"use strict";de();Dt();Pe();Se();te();U();We();he();OV();Xme=pe(200,0),Mm=class{constructor(e){this.nvim=e;this.disposables=[];y.onDidChangeConfiguration(i=>{if(i.affectsConfiguration("codeLens"))for(let r of this.buffers.items)r.loadConfiguration()},this,this.disposables),this.buffers=y.registerBufferSync(i=>{if(i.buftype=="")return new Fm(e,i)}),this.disposables.push(this.buffers),_.on("CursorHold",async i=>{let r=this.buffers.getItem(i);r&&r.config.enabled&&!r.currentCodeLens&&await r.forceFetch()},null,this.disposables),_.on("CursorMoved",i=>{let r=this.buffers.getItem(i);r&&r.resolveCodeLens()},null,this.disposables);let t=ft(async i=>{for(let r of this.buffers.items)!y.match(i,r.document)||(r.abandonResult(),await r.forceFetch())},Xme);this.disposables.push(p.Disposable.create(()=>{t.clear()})),I.onDidCodeLensRefresh(t,null,this.disposables),V.register({id:"document.toggleCodeLens",execute:()=>this.toggle(y.bufnr)},!1,"toggle codeLens display of current buffer")}async toggle(e){let t=this.buffers.getItem(e);try{y.getAttachedDocument(e),await t.toggleDisplay()}catch(i){P.showErrorMessage(i.message)}}async checkProvider(){for(let e of this.buffers.items)await e.forceFetch()}async doAction(){let[e,t]=await this.nvim.eval('[bufnr("%"),line(".")-1]'),i=this.buffers.getItem(e);i&&await i.doAction(t)}dispose(){W(this.disposables)}}});function X0(n){return n.length==1?`0${n}`:n}function jm(n){let e=Gme(n);return`${X0(e.red.toString(16))}${X0(e.green.toString(16))}${X0(e.blue.toString(16))}`}function Gme(n){let{red:e,green:t,blue:i}=n;return{red:Math.round(e*255),green:Math.round(t*255),blue:Math.round(i*255)}}function NV(n){let e=[n.red,n.green,n.blue],t=[];for(let r=0;r{"use strict"});function Kme(n){return`BG${jm(n)}`}var HV,zme,Om,BV=D(()=>{"use strict";Se();te();G0();Xe();de();Tt();U();We();he();HV="color",zme=pe(200,10),Om=class{constructor(e,t,i,r){this.nvim=e;this.doc=t;this.config=i;this.usedColors=r;this._colors=[];this.highlight=ft(()=>{this.doHighlight()},zme),this.hasProvider&&this.highlight()}get enable(){return Pn(this._enable)?this._enable:(this._enable=y.getConfiguration("colors",this.doc).get("enable",!1),this._enable)}updateDocumentConfig(){let e=this.enabled;this._enable=y.getConfiguration("colors",this.doc).get("enable",!1),e!=this.enabled&&(e?this.clearHighlight():this.doHighlight())}toggle(){this._enable?(this._enable=!1,this.clearHighlight()):(this._enable=!0,this.doHighlight())}get hasProvider(){return I.hasProvider("documentColor",this.doc)}get enabled(){let{filetypes:e}=this.config,{filetype:t}=this.doc;return!y.env.updateHighlight||!this.hasProvider?!1:Array.isArray(e)&&(e.includes("*")||e.includes(t))?!0:this.enable}onChange(){this.cancel(),this.highlight()}get buffer(){return this.doc.buffer}get colors(){return this._colors}hasColor(){return this._colors.length>0}async doHighlight(){if(!this.enabled)return;let{nvim:e,doc:t}=this;this.tokenSource=new p.CancellationTokenSource;let{token:i}=this.tokenSource,r;if(r=await I.provideDocumentColors(t.textDocument,i),i.isCancellationRequested)return;r=r||[],r.sort((a,l)=>Ge(a.range.start,l.range.start)),this._colors=r;let o=[];r.forEach(a=>{let l=Kme(a.color);t.addHighlights(o,l,a.range,{combine:!1})});let s=await P.diffHighlights(t.bufnr,HV,o);i.isCancellationRequested||!s||(e.pauseNotification(),this.defineColors(r),e.resumeNotification(!1,!0),await P.applyDiffHighlights(t.bufnr,HV,this.config.highlightPriority,s,!0))}defineColors(e){for(let t of e){let i=jm(t.color);this.usedColors.has(i)||(this.nvim.command(`hi BG${i} guibg=#${i} guifg=#${NV(t.color)?"ffffff":"000000"}`,!0),this.usedColors.add(i))}}hasColorAtPosition(e){return this.colors.some(t=>Ft(e,t.range)==0)}clearHighlight(){this.highlight.clear(),this._colors=[],this.buffer.clearNamespace("color")}cancel(){this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null)}dispose(){this._colors=[],this.highlight.clear(),this.cancel()}}});var Am,qV=D(()=>{"use strict";Dt();Pe();Se();te();G0();U();We();he();BV();Am=class{constructor(e,t){this.nvim=e;this.handler=t;this.disposables=[];this.loadConfiguration(),y.onDidChangeConfiguration(this.loadConfiguration,this,this.disposables);let i=new Set;this.highlighters=y.registerBufferSync(r=>new Om(this.nvim,r,this.config,i)),_.on("ColorScheme",()=>{i.clear();for(let r of this.highlighters.items)r.cancel(),r.doHighlight()},null,this.disposables),I.onDidColorsRefresh(r=>{for(let o of this.highlighters.items)y.match(r,o.doc)&&o.highlight()}),V.register({id:"editor.action.pickColor",execute:async()=>{await this.pickColor()}},!1,"pick color from system color picker when possible."),V.register({id:"editor.action.colorPresentation",execute:async()=>{await this.pickPresentation()}},!1,"change color presentation."),V.register({id:"document.toggleColors",execute:async()=>{let r=await e.call("bufnr",["%"]),o=this.highlighters.getItem(r);y.getAttachedDocument(r),o.toggle()}},!1,"toggle colors for current buffer")}loadConfiguration(e){if(!e||e.affectsConfiguration("colors")){let t=y.initialConfiguration.get("colors");if(this.config=Object.assign(this.config??{},{filetypes:t.filetypes,highlightPriority:Ie(t.highlightPriority,1e3)}),e)for(let i of this.highlighters.items)i.updateDocumentConfig()}}async pickPresentation(){let{doc:e}=await this.handler.getCurrentState();this.handler.checkProvider("documentColor",e.textDocument);let t=await this.getColorInformation(e.bufnr);if(!t)return void P.showWarningMessage("Color not found at current position");let i=new p.CancellationTokenSource,r=await I.provideColorPresentations(t,e.textDocument,i.token);if(!(r!=null&&r.length))return void P.showWarningMessage("No color presentations found");let o=await P.showMenuPicker(r.map(c=>c.label),"Choose color:");if(o==-1)return;let s=r[o],{textEdit:a,additionalTextEdits:l,label:u}=s;a||(a={range:t.range,newText:u}),await e.applyEdits([a]),l&&await e.applyEdits(l)}async pickColor(){let{doc:e}=await this.handler.getCurrentState();this.handler.checkProvider("documentColor",e.textDocument);let t=await this.getColorInformation(e.bufnr);if(!t)return void P.showWarningMessage("Color not found at current position");let{color:i}=t,r=[(i.red*255).toFixed(0),(i.green*255).toFixed(0),(i.blue*255).toFixed(0)],o=await this.nvim.call("coc#color#pick_color",[r]);if(!o)return;let s=jm({red:o[0]/65535,green:o[1]/65535,blue:o[2]/65535,alpha:1});await e.applyEdits([{range:t.range,newText:`#${s}`}])}isEnabled(e){let t=this.highlighters.getItem(e);return t!=null&&t.enabled===!0}clearHighlight(e){let t=this.highlighters.getItem(e);t&&t.clearHighlight()}hasColor(e){let t=this.highlighters.getItem(e);return t?t.hasColor():!1}hasColorAtPosition(e,t){let i=this.highlighters.getItem(e);return i?i.hasColorAtPosition(t):!1}highlightAll(){for(let e of this.highlighters.items)e.highlight()}async doHighlight(e){let t=this.highlighters.getItem(e);t&&await t.doHighlight()}async getColorInformation(e){let t=this.highlighters.getItem(e);if(!t)return null;let i=await P.getCursorPosition();for(let r of t.colors){let{range:o}=r,{start:s,end:a}=o;if(i.line==s.line&&i.character>=s.character&&i.character<=a.character)return r}return null}dispose(){this.highlighters.dispose(),W(this.disposables)}}});function Qme(n){return n&&$e(n.id)&&$e(n.cmd)&&n.id.length>0&&n.cmd.length>0}var Nm,WV=D(()=>{"use strict";Dt();WC();he();Xe();Nm=class{constructor(e){this.nvim=e;for(let t of y.env.vimCommands)this.addVimCommand(t)}addVimCommand(e){if(!Qme(e))return;let t=`vim.${e.id}`;V.registerCommand(t,()=>{this.nvim.command(e.cmd,!0),this.nvim.redrawVim()}),e.title&&V.titles.set(t,e.title)}getCommandList(){return V.commandList.map(e=>e.id)}async repeat(){await V.repeatCommand()}async runCommand(e,...t){if(e)return await V.fireCommand(e,...t);await qi.start(["commands"])}}});var Hm,YV=D(()=>{"use strict";Se();Hm=class{constructor(e,t){this.nvim=e;this.handler=t}async fold(e){let{doc:t,winid:i}=await this.handler.getCurrentState();this.handler.checkProvider("foldingRange",t.textDocument),await t.synchronize();let r=this.nvim.createWindow(i),o=await this.nvim.eval("&foldlevel"),s=await this.handler.withRequestToken("foldingrange",a=>I.provideFoldingRanges(t.textDocument,{},a),!0);if(!s||!s.length)return!1;e&&(s=s.filter(a=>a.kind==e)),s.sort((a,l)=>l.startLine-a.startLine),this.nvim.pauseNotification(),r.setOption("foldmethod","manual",!0),this.nvim.command("normal! zE",!0);for(let a of s){let{startLine:l,endLine:u}=a,c=`${l+1}, ${u+1}fold`;this.nvim.command(c,!0)}return r.setOption("foldenable",!0,!0),r.setOption("foldlevel",o,!0),await this.nvim.resumeNotification(!0),!0}}});var z0,Bm,ZV=D(()=>{"use strict";ae();Dt();Pe();Se();xe();cu();Re();te();U();fe();We();he();z0=Z("handler-format"),Bm=class{constructor(e,t){this.nvim=e;this.handler=t;this.setConfiguration(),t.addDisposable(y.onDidChangeConfiguration(this.setConfiguration,this)),t.addDisposable(P.onDidChangeActiveTextEditor(()=>{this.setConfiguration()})),t.addDisposable(y.onWillSaveTextDocument(i=>{if(this.shouldFormatOnSave(i.document)){let r=async()=>{if(!I.hasFormatProvider(i.document)){z0.warn(`Format provider not found for ${i.document.uri}`);return}let o=await y.getFormatOptions(i.document.uri),s=new p.CancellationTokenSource,a,l=new Promise(d=>{a=setTimeout(()=>{z0.warn(`Format on save ${i.document.uri} timeout after 0.5s`),s.cancel(),d(void 0)},500)}),u=I.provideDocumentFormattingEdits(i.document,o,s.token),c=await Promise.race([l,u]);return clearTimeout(a),Array.isArray(c)?c:void 0};i.waitUntil(r())}})),t.addDisposable(_.on("Enter",async i=>{let r=await _.race(["CursorMovedI"],100);r.args&&r.args[0]===i&&await this.handleEnter(i)})),t.addDisposable(_.on("TextInsert",async(i,r,o)=>{_.pumvisible||await this.tryFormatOnType(o,i)})),t.addDisposable(V.registerCommand("editor.action.formatDocument",async i=>{let r=i?y.getDocument(i):(await this.handler.getCurrentState()).doc;await this.documentFormat(r)})),V.titles.set("editor.action.formatDocument","Format Document")}shouldFormatOnSave(e){let{languageId:t,uri:i}=e,r=y.getConfiguration("coc.preferences",{uri:i,languageId:t}),o=r.get("formatOnSaveFiletypes",null),s=r.get("formatOnSave",!1);return Array.isArray(o)?o.includes("*")||o.includes(t):s}setConfiguration(e){var t;if(!e||e.affectsConfiguration("coc.preferences")){let i=(t=P.activeTextEditor)==null?void 0:t.document,r=y.getConfiguration("coc.preferences",i);this.preferences={formatOnType:r.get("formatOnType",!1),formatOnTypeFiletypes:r.get("formatOnTypeFiletypes",null),bracketEnterImprove:r.get("bracketEnterImprove",!0)}}}shouldFormatOnType(e){let t=this.preferences.formatOnTypeFiletypes;return re(e)||t.includes(e)||t.includes("*")}async tryFormatOnType(e,t,i=!1){if(!e||lc(e.charCodeAt(0))||!this.preferences.formatOnType||pi.getSession(t)!=null)return;let r=y.getDocument(t);if(!r||!r.attached||!this.shouldFormatOnType(r.filetype))return;if(!I.hasProvider("formatOnType",r.textDocument)){z0.warn(`Format on type provider not found for buffer: ${r.uri}`);return}if(!I.canFormatOnType(e,r.textDocument))return;let o,s=await this.handler.withRequestToken("Format on type",async a=>{o=await P.getCursorPosition();let l=r.getline(o.line-1);if(!(i&&/^\s*$/.test(l)))return await r.synchronize(),await I.provideDocumentOnTypeEdits(e,r.textDocument,o,a)});re(s)||await r.applyEdits(s,!1,!0)}async formatCurrentBuffer(){let{doc:e}=await this.handler.getCurrentState();return await this.documentFormat(e)}async formatCurrentRange(e){let{doc:t}=await this.handler.getCurrentState();return await this.documentRangeFormat(t,e)}async documentFormat(e){if(await e.synchronize(),!I.hasFormatProvider(e.textDocument))throw new Error(`Format provider not found for buffer: ${e.bufnr}`);let t=await y.getFormatOptions(e.uri),i=await this.handler.withRequestToken("format",r=>I.provideDocumentFormattingEdits(e.textDocument,t,r));return i&&i.length>0?(await e.applyEdits(i,!1,!0),!0):!1}async handleEnter(e){let{nvim:t}=this,{bracketEnterImprove:i}=this.preferences;if(await this.tryFormatOnType(` +`,e),i){let r=await t.call("line",".")-1,o=y.getDocument(e);if(!o)return;await o.patchChange();let s=o.getline(r-1),a=o.getline(r),l=s[s.length-1];if(l&&Qd.has(l)){let u=a.trim()[0];if(u&&Qd.get(l)==u){let c=[],d=await y.getFormatOptions(o.uri),h=d.insertSpaces?" ".repeat(d.tabSize):" ",g=a.match(/^\s*/)[0],f=Q.create(r-1,s.length);if(o.filetype=="vim"){let m=` +`+g+h;c.push({range:M.create(r,g.length,r,g.length),newText:" \\ "}),m=m+"\\ ",c.push({range:M.create(f,f),newText:m}),await o.applyEdits(c),await P.moveTo(Q.create(r,m.length-1))}else await t.eval(`feedkeys("\\O", 'in')`)}}}}async documentRangeFormat(e,t){this.handler.checkProvider("formatRange",e.textDocument),await e.synchronize();let i;if(t){if(i=await P.getSelectedRange(t),!i)return-1}else{let[s,a,l]=await this.nvim.eval("[v:lnum,v:count,mode()]");if(a==0||l=="i"||l=="R")return-1;i=M.create(s-1,0,s-1+a,0)}let r=await y.getFormatOptions(e.uri),o=await this.handler.withRequestToken("Format range",s=>I.provideDocumentRangeFormattingEdits(e.textDocument,i,r,s));return re(o)?-1:(await e.applyEdits(o,!1,!0),0)}}});var qm,JV=D(()=>{"use strict";ae();Dt();Pe();Se();te();Tt();U();We();he();qm=class{constructor(e,t){this.nvim=e;this.handler=t;this.disposables=[];this.highlights=new Map;_.on(["CursorMoved","CursorMovedI"],()=>{this.cancel(),this.clearHighlights()},null,this.disposables),this.loadConfiguration(),y.onDidChangeConfiguration(this.loadConfiguration,this,this.disposables),P.onDidChangeActiveTextEditor(()=>{this.loadConfiguration()},null,this.disposables),V.register({id:"document.jumpToNextSymbol",execute:async()=>{await this.jumpSymbol("next")}},!1,"Jump to next symbol highlight position."),V.register({id:"document.jumpToPrevSymbol",execute:async()=>{await this.jumpSymbol("previous")}},!1,"Jump to previous symbol highlight position.")}loadConfiguration(e){let t=y.getConfiguration("documentHighlight",this.handler.uri);(!e||e.affectsConfiguration("documentHighlight"))&&(this.config=Object.assign(this.config||{},{priority:t.get("priority",-1),timeout:t.get("timeout",300)}))}isEnabled(e,t){let i=y.getDocument(e);return!(!i||!i.attached||t||!I.hasProvider("documentHighlight",i.textDocument))}clearHighlights(){if(this.highlights.size!=0){for(let e of this.highlights.keys())this.nvim.createWindow(e).clearMatchGroup("^CocHighlight");this.highlights.clear()}}async highlight(){let{nvim:e}=this;this.cancel();let[t,i,r,o]=await e.eval(`[bufnr("%"),win_getid(),coc#cursor#position(),get(b:,'coc_cursors_activated',0)]`);if(!this.isEnabled(t,o))return;let s=y.getDocument(t),a=await this.getHighlights(s,Q.create(r[0],r[1]));if(!a)return;let l={};for(let c of a){if(!c.range)continue;let d=c.kind==Zs.Text?"CocHighlightText":c.kind==Zs.Read?"CocHighlightRead":"CocHighlightWrite";l[d]=l[d]||[],l[d].push(c.range)}let u=e.createWindow(i);e.pauseNotification(),u.clearMatchGroup("^CocHighlight");for(let c of Object.keys(l))u.highlightRanges(c,l[c],this.config.priority,!0);e.resumeNotification(!0,!0),this.highlights.set(i,a)}async jumpSymbol(e){let t=await this.getSymbolsRanges();if(!t)return;let i=await P.getCursorPosition();if(e=="next"){for(let r=0;r<=t.length-1;r++)if(Ge(t[r].start,i)>0){await P.moveTo(t[r].start);return}await P.moveTo(t[0].start)}else{for(let r=t.length-1;r>=0;r--)if(Ge(t[r].end,i)<0){await P.moveTo(t[r].start);return}await P.moveTo(t[t.length-1].start)}}async getSymbolsRanges(){let{doc:e,position:t}=await this.handler.getCurrentState();this.handler.checkProvider("documentHighlight",e.textDocument);let i=await this.getHighlights(e,t);return i?i.map(r=>r.range).sort((r,o)=>r.start.line!=o.start.line?r.start.line-o.start.line:r.start.character-o.start.character):null}hasHighlights(e){return this.highlights.get(e)!=null}async getHighlights(e,t){let r=e.getline(t.line)[t.character];if(!r||!e.isWord(r))return null;await e.synchronize(),this.cancel();let o=this.tokenSource=new p.CancellationTokenSource,s=this.timer=setTimeout(()=>{o.token.isCancellationRequested||o.cancel()},this.config.timeout),a=await I.getDocumentHighLight(e.textDocument,t,o.token);return clearTimeout(s),o.token.isCancellationRequested?null:a}cancel(){this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource.dispose(),this.tokenSource=null)}dispose(){this.timer&&clearTimeout(this.timer),this.cancel(),this.highlights.clear(),W(this.disposables)}}});async function ebe(n,e,t){for(let i of e){if(!(i!=null&&i.targetRange))continue;let{start:r,end:o}=i.targetRange,s=o.line-r.line>=100?r.line+100:o.character==0?o.line-1:o.line,a=await ibe(i.targetUri,r.line,s);if(a.length){let l=a[0].match(/^\s*/)[0];l&&(a=a.map(u=>u.startsWith(l)?u.substring(l.length):u)),n.push({content:a.join(` +`),filetype:t})}}}function Wm(n,e,t,i=!1){let r=e.trim();!r.length||(i&&t!=="markdown"&&(r="``` "+t+` +`+r+"\n```"),n.push({content:r,filetype:t}))}function tbe(n){return n?typeof n.filetype=="string"&&typeof n.content=="string":!1}async function ibe(n,e,t){let i=y.getDocument(n);if(i)return i.getLines(e,t+1);let r=O.parse(n).fsPath;return F.existsSync(r)?await Qs(r,e,t):[]}var Vme,Ym,$V=D(()=>{"use strict";ae();Je();Se();te();Re();st();Xe();de();U();fe();We();he();Vme=pe(500,10),Ym=class{constructor(e,t){this.nvim=e;this.handler=t;this.disposables=[];this.documentLines=[];this.hasProvider=!1;this.loadConfiguration(),y.onDidChangeConfiguration(this.loadConfiguration,this,this.disposables),this.hoverFactory=P.createFloatFactory({modes:["n"],autoHide:this.config.autoHide}),this.disposables.push(this.hoverFactory),P.onDidChangeActiveTextEditor(()=>{this.loadConfiguration()},null,this.disposables)}registerProvider(){if(this.hasProvider)return;this.hasProvider=!0;let{nvim:e}=this,t={onDidChange:null,provideTextDocumentContent:async()=>(e.pauseNotification(),e.command("setlocal conceallevel=2 nospell nofoldenable wrap",!0),e.command("setlocal bufhidden=wipe nobuflisted",!0),e.command("setfiletype markdown",!0),e.command(`if winnr('j') != winnr('k') | exe "normal! z${Math.min(this.documentLines.length,this.config.previewMaxHeight)}\\" | endif`,!0),await e.resumeNotification(),this.documentLines.join(` +`))};this.disposables.push(y.registerTextDocumentContentProvider("coc",t))}loadConfiguration(e){if(!e||e.affectsConfiguration("hover")){let t=y.getConfiguration("hover",this.handler.uri);this.config={floatConfig:t.get("floatConfig",{}),autoHide:t.get("autoHide",!0),target:t.get("target","float"),previewMaxHeight:t.get("previewMaxHeight",12)},this.config.target=="preview"&&this.registerProvider()}}async onHover(e){let{doc:t,position:i,winid:r}=await this.handler.getCurrentState();e=="preview"&&this.registerProvider(),this.handler.checkProvider("hover",t.textDocument),await t.synchronize();let o=await this.handler.withRequestToken("hover",a=>I.getHover(t.textDocument,i,a),!0);if(o==null||!o.length)return!1;let s=o.find(a=>M.is(a.range));if(s!=null&&s.range){let a=this.nvim.createWindow(r);a.highlightRanges("CocHoverRange",[s.range],99,!0),this.timer=setTimeout(()=>{a.clearMatchGroup("CocHoverRange"),this.nvim.redrawVim()},500)}return await this.previewHover(o,e),!0}async definitionHover(e){let{doc:t,position:i,winid:r}=await this.handler.getCurrentState();e=="preview"&&this.registerProvider(),this.handler.checkProvider("hover",t.textDocument),await t.synchronize();let o=await this.handler.withRequestToken("hover",l=>I.getHover(t.textDocument,i,l),!0);if(re(o))return!1;let s=await this.handler.withRequestToken("definitionHover",l=>I.getDefinitionLinks(t.textDocument,i,l),!1);await ebe(o,s,t.filetype);let a=o.find(l=>Vo.is(l)&&M.is(l.range));if(a){let l=this.nvim.createWindow(r);l.highlightRanges("CocHoverRange",[a.range],99,!0),this.timer=setTimeout(()=>{l.clearMatchGroup("CocHoverRange"),this.nvim.redrawVim()},Vme)}return await this.previewHover(o,e),!0}async previewHover(e,t){let i=[];t=t??this.config.target;let r=t==="preview";for(let s of e){if(tbe(s)){i.push(s);continue}let{contents:a}=s;if(Array.isArray(a))for(let l of a)typeof l=="string"?Wm(i,l,"markdown",r):Wm(i,l.value,l.language,r);else Qo.is(a)?typeof a=="string"?Wm(i,a,"markdown",r):Wm(i,a.value,a.language,r):Ln.is(a)&&Wm(i,a.value,bh(a)?"markdown":"txt",r)}if(t=="float"){await this.hoverFactory.show(i,this.config.floatConfig);return}let o=i.reduce((s,a)=>{let l=a.content.split(/\r?\n/);return s.length>0&&s.push(""),s.push(...l),s},[]);if(t=="echo"){let s=o.join(` +`).trim();await this.nvim.call("coc#ui#echo_hover",[s])}else this.documentLines=o,await this.nvim.command("noswapfile pedit coc://document")}async getHover(e){let t=[],i,r;if(e){i=e.bufnr?y.getAttachedDocument(e.bufnr):await y.document;let a=i.getline(e.line-1),l=Ut(a,e.col-1);r=Q.create(e.line-1,l)}else{let a=await this.handler.getCurrentState();i=a.doc,r=a.position}this.handler.checkProvider("hover",i.textDocument),await i.synchronize();let o=new p.CancellationTokenSource,s=await I.getHover(i.textDocument,r,o.token);for(let a of s){let{contents:l}=a;Array.isArray(l)?l.forEach(u=>{t.push(typeof u=="string"?u:u.value)}):Ln.is(l)?t.push(l.value):t.push(typeof l=="string"?l:l.value)}return t=t.filter(a=>a!=null&&a.length>0),t}dispose(){this.timer&&clearTimeout(this.timer),W(this.disposables)}}});var Na,K0=D(()=>{"use strict";Na=class{constructor(){this.ranges=[]}get current(){let e=[];return this.ranges.sort((t,i)=>t[0]-i[0]),this.ranges.forEach(t=>{e.push(t[0],t[1])}),e}clear(){this.ranges=[]}add(e,t){e>t&&([e,t]=[t,e]);let{ranges:i}=this;if(i.length==0)i.push([e,t]);else{i.sort((l,u)=>l[0]-u[0]);let r,o,s=[];for(let l=0;lt||(s.push(l),r==null&&(r=Math.min(e,u[0])),o=Math.max(t,u[1]))}let a=s.length?i.filter((l,u)=>!s.includes(u)):i;this.ranges=a,r!=null&&o!=null?this.ranges.push([r,o]):this.ranges.push([e,t])}}has(e,t){return this.ranges.findIndex(r=>r[0]<=e&&r[1]>=t)!==-1}static mergeSpans(e){let t=[];for(let i of e){let r=t.findIndex(o=>!(i[1]o[1]));if(r==-1)t.push(i);else{let o=t[r];t[r]=[Math.min(i[0],o[0]),Math.max(i[1],o[1])]}}return t}}});function Q0(n){switch(n){case Br.Parameter:return"CocInlayHintParameter";case Br.Type:return"CocInlayHintType";default:return"CocInlayHint"}}var fu,nbe,rbe,Zm,UV=D(()=>{"use strict";ae();Pe();Se();K0();SR();te();Ii();Tt();U();fe();he();nbe=pe(100,10),rbe=pe(500,10);Zm=class{constructor(e,t){this.nvim=e;this.doc=t;this.regions=new Na;this.currentHints=[];this._onDidRefresh=new p.Emitter;this.onDidRefresh=this._onDidRefresh.event;this.render=Wb(()=>{this.renderRange()},nbe),this.hasProvider&&this.render()}get config(){return this._config?this._config:(this.loadConfiguration(),this._config)}loadConfiguration(){let e=y.getConfiguration("inlayHint",this.doc),t=this._config&&this._config.enable!=e.enable;if(this._config={enable:e.get("enable"),display:e.get("display",!0),filetypes:e.get("filetypes"),refreshOnInsertMode:e.get("refreshOnInsertMode"),enableParameter:e.get("enableParameter"),typeSeparator:e.get("typeSeparator",""),parameterSeparator:e.get("parameterSeparator",""),subSeparator:e.get("subSeparator"," ")},t){let{enable:i,display:r}=this._config;i?(this.clearCache(),this.clearVirtualText()):r&&this.renderRange()}}onInsertLeave(){this.config.refreshOnInsertMode||this.render()}onInsertEnter(){this.config.refreshOnInsertMode||this.cancel()}get current(){return this.currentHints}get enabled(){return!this.config.display||!this.configEnabled?!1:this.hasProvider}get hasProvider(){return I.hasProvider("inlayHint",this.doc)}get configEnabled(){let{filetypes:e,enable:t}=this.config;return Array.isArray(e)?e.includes("*")||e.includes(this.doc.filetype):t===!0}toggle(){if(!I.hasProvider("inlayHint",this.doc.textDocument))throw new Error("Inlay hint provider not found for current document");if(!this.configEnabled)throw new Error(`Filetype "${this.doc.filetype}" not enabled by inlayHint configuration`);this.config.display?(this.config.display=!1,this.clearCache(),this.clearVirtualText()):(this.config.display=!0,this.renderRange())}clearCache(){this.currentHints=[],this.regions.clear(),this.render.clear()}onTextChange(){this.clearCache(),this.cancel()}onChange(){this.cancel(),this.render()}cancel(){this.render.clear(),this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null)}async requestInlayHints(e,t){try{return await I.provideInlayHints(this.doc.textDocument,e,t)}catch(i){!t.isCancellationRequested&&i instanceof Rt&&this.render(rbe)}}async renderRange(){if(this.cancel(),_.insertMode&&!this.config.refreshOnInsertMode||!this.enabled)return;this.tokenSource=new p.CancellationTokenSource;let e=this.tokenSource.token,t=await this.nvim.call("coc#window#visible_range",[this.doc.bufnr]);if(!Array.isArray(t)||t[1]<=0||e.isCancellationRequested||(fu||(fu=await this.nvim.createNamespace("coc-inlayHint")),e.isCancellationRequested||this.regions.has(t[0],t[1])))return;let i=M.create(t[0]-1,0,t[1],0),r=await this.requestInlayHints(i,e);r==null||e.isCancellationRequested||(this.regions.add(t[0],t[1]),this.config.enableParameter||(r=r.filter(o=>o.kind!==Br.Parameter)),this.currentHints=this.currentHints.filter(o=>Ft(o.position,i)!==0),this.currentHints.push(...r),this.setVirtualText(i,r,y.env.isVim))}setVirtualText(e,t,i){let{nvim:r,doc:o}=this,s=o.buffer,{subSeparator:a,parameterSeparator:l,typeSeparator:u}=this.config,c=new Map;if(!i)for(let d of t){let{line:h}=d.position,g=c.get(h)??[];g.length>0&&g.push([a,a===" "?"Normal":Q0(d.kind)]);let f=d.kind===Br.Parameter?l:u;g.push([f+Jp(d),Q0(d.kind)]),c.set(h,g)}if(r.pauseNotification(),s.clearNamespace(fu,e.start.line,e.end.line+1),i)for(let d of t){let h=[],{position:g}=d,f=this.doc.getline(g.line),m=nt(f,g.character)+1;d.paddingLeft&&h.push([" ","Normal"]),h.push([Jp(d),Q0(d.kind)]),d.paddingRight&&h.push([" ","Normal"]),s.setVirtualText(fu,g.line,h,{col:m})}else for(let[d,h]of c.entries())s.setExtMark(fu,d,0,{virt_text:h,virt_text_pos:"eol",hl_mode:"combine"});r.resumeNotification(!0,!0),this._onDidRefresh.fire()}clearVirtualText(){fu&&this.doc.buffer.clearNamespace(fu)}dispose(){this.cancel()}}});var Jm,XV=D(()=>{"use strict";Dt();Pe();Se();te();U();We();he();UV();Jm=class{constructor(e,t){this.disposables=[];this.buffers=y.registerBufferSync(i=>{if(!!y.env.virtualText)return new Zm(e,i)}),this.disposables.push(this.buffers),y.onDidChangeConfiguration(i=>{for(let r of this.buffers.items)i.affectsConfiguration("inlayHint",r.doc)&&r.loadConfiguration()},null,this.disposables),I.onDidInlayHintRefresh(async i=>{for(let r of this.buffers.items)y.match(i,r.doc.textDocument)&&(r.clearCache(),I.hasProvider("inlayHint",r.doc.textDocument)?r.render():r.clearVirtualText())},null,this.disposables),_.on("InsertLeave",i=>{let r=this.buffers.getItem(i);r&&r.onInsertLeave()},null,this.disposables),_.on("InsertEnter",i=>{let r=this.buffers.getItem(i);r&&r.onInsertEnter()},null,this.disposables),_.on("CursorMoved",i=>{this.refresh(i)},null,this.disposables),_.on("WinScrolled",async i=>{let r=await e.call("winbufnr",[i]);r!=-1&&this.refresh(r)},null,this.disposables),V.register({id:"document.toggleInlayHint",execute:i=>this.toggle(i??y.bufnr)},!1,"toggle codeLens display of current buffer"),t.addDisposable(p.Disposable.create(()=>{W(this.disposables)}))}toggle(e){let t=this.getItem(e);try{y.getAttachedDocument(e),t.toggle()}catch(i){P.showErrorMessage(i.message)}}getItem(e){return this.buffers.getItem(e)}refresh(e){let t=this.buffers.getItem(e);t&&t.render()}}});var obe,$m,GV=D(()=>{"use strict";ae();Y0();Rm();Pe();Se();te();de();Tt();U();fe();We();he();obe=pe(200,10),$m=class{constructor(e,t){this.nvim=e;this.changing=!1;this.checkPosition=ft(this._checkPosition,obe),t.addDisposable(_.on("CursorMoved",(i,r)=>{this.cancel(),this.checkPosition(i,[r[0],r[1]])})),t.addDisposable(_.on("CursorMovedI",(i,r)=>{this.cancel(),this.checkPosition(i,[r[0],r[1]])})),t.addDisposable(P.onDidChangeActiveTextEditor(()=>{this.cancel(),this.cancelEdit()})),t.addDisposable(_.on("InsertCharPre",(i,r)=>{if(r!==this.bufnr)return;let o=y.getDocument(r);this.wordPattern?new RegExp(this.wordPattern).test(i)||this.cancelEdit():!o.isWord(i)&&i!=="-"&&this.cancelEdit()})),t.addDisposable(y.onDidChangeTextDocument(async i=>{await this.onChange(i)}))}cancelEdit(){var e;(e=this.window)==null||e.clearMatchGroup("^CocLinkedEditing"),this.ranges=void 0,this.window=void 0,this.bufnr=void 0}async onChange(e){if(e.bufnr!==this.bufnr||this.changing||!this.ranges)return;if(e.contentChanges.length===0){this.doHighlights();return}let t=e.contentChanges[0],{text:i,range:r}=t,o=this.ranges.filter(s=>!(!Ll(r,s.range)||qv(r,s.range)&&(i.includes(` +`)||!Gt(r))));if(o.length==1&&ti(r,o[0].range)){if(i.includes(` +`)){this.cancelEdit();return}await this.applySingleEdit(o[0],{range:r,newText:i})}else this.cancelEdit()}async applySingleEdit(e,t){let{bufnr:i,ranges:r}=this,o=y.getDocument(i);r.filter(c=>c!==e&&c.position.line==e.position.line).forEach(c=>c.adjustFromEdit(t));let a=iS(e,t.range,t.newText),l=km(a);r.forEach(c=>c.applyChange(a));let u=r.filter(c=>c!==e).map(c=>c.textEdit);if(this.changing=!0,await o.applyEdits(u,!0,!0),this.changing=!1,l!=0)for(let c of r){let d=Pm(c,this.ranges,e);c.move(d*l)}this.doHighlights()}doHighlights(){let{window:e,ranges:t,nvim:i}=this;e&&t&&(i.pauseNotification(),e.clearMatchGroup("^CocLinkedEditing"),e.highlightRanges("CocLinkedEditing",t.map(r=>r.range),99,!0),i.resumeNotification(!0,!0))}_checkPosition(e,t){if(_.pumvisible||!y.isAttached(e))return;let i=y.getDocument(e);if(!y.getConfiguration("coc.preferences",i).get("enableLinkedEditing",!1)||!I.hasProvider("linkedEditing",i.textDocument))return;let s=Ut(i.getline(t[0]-1),t[1]-1),a=Q.create(t[0]-1,s);if(this.ranges){if(this.ranges.some(l=>Ft(a,l.range)==0))return;this.cancelEdit()}this.enable(i,a)}async enable(e,t){let i=e.textDocument,o=(this.tokenSource=new p.CancellationTokenSource).token,s=await this.nvim.window,a=await I.provideLinkedEdits(i,t,o);if(o.isCancellationRequested||!a||a.ranges.length==0)return;let l=a.ranges.map(u=>new gu(u.start.line,u.start.character,i.getText(u)));this.wordPattern=a.wordPattern,this.bufnr=e.bufnr,this.window=s,this.ranges=l,this.doHighlights()}cancel(){this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null)}}});function lbe(n,e){if(n.length!=e.length)return!1;for(let t=0;t{"use strict";KV=Lr(aS());ae();Pe();Se();te();Re();Be();Tt();U();We();he();sbe=pe(200,10),zV="links",abe="CocLink",Um=class{constructor(e,t){this.nvim=e;this.handler=t;this.disposables=[];this.setConfiguration(),y.onDidChangeConfiguration(this.setConfiguration,this,this.disposables),_.on("CursorHold",async()=>{await this.showTooltip()},null,this.disposables),_.on(["CursorMoved","InsertEnter"],()=>{this.cancel()},null,this.disposables),this.buffers=y.registerBufferSync(i=>new eI(i)),this.disposables.push(this.buffers),I.onDidLinksRefresh(i=>{for(let r of this.buffers.items)y.match(i,r.doc)&&r.fetchLinks()},null,this.disposables)}setConfiguration(e){if((!e||e.affectsConfiguration("links"))&&(this.tooltip=y.initialConfiguration.get("links.tooltip",!1),e))for(let t of this.buffers.items)t.updateDocumentConfig()}async showTooltip(){if(!this.tooltip)return;let e=await this.getCurrentLink();if(!e||!e.target)return;let t=e.target;e.tooltip&&(t+=" "+e.tooltip);let i={content:t,filetype:"txt"};V0||(V0=P.createFloatFactory({})),await V0.show([i])}async getLinks(){let{doc:e}=await this.handler.getCurrentState(),t=this.buffers.getItem(e.bufnr);return await t.getLinks(),le(t.links)}async getCurrentLink(){let e=await this.getLinks(),t=await P.getCursorPosition();if(e&&e.length){for(let a of e)if(Ft(t,a.range)==0){if(!a.target){let l=this.tokenSource=this.tokenSource||new p.CancellationTokenSource;if(a=await I.resolveDocumentLink(a,this.tokenSource.token),this.tokenSource=void 0,!a.target||l.token.isCancellationRequested)continue}return a}}let i=await this.nvim.call("getline",["."]),r=/\w+?:\/\/[^)\]'" ]+/g,o,s;for(;(o=r.exec(i))!==null;){let a=o.index;if(a<=t.character&&a+o[0].length>=t.character){s=pl.create(M.create(t.line,a,t.line,a+o[0].length),o[0]);break}}return s}async openCurrentLink(){let e=await this.getCurrentLink();return e?(await this.openLink(e),!0):!1}async openLink(e){if(!e.target)throw new Error("Failed to resolve link target");await y.openResource(e.target)}getBuffer(e){return this.buffers.getItem(e)}cancel(){this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null)}dispose(){W(this.disposables)}},eI=class{constructor(e){this.doc=e;this.links=[];this.fetchLinks=(0,KV.default)(()=>{this.getLinks()},sbe),this.hasProvider&&this.fetchLinks()}get config(){return this._config?this._config:(this.updateDocumentConfig(),this._config)}get hasProvider(){return I.hasProvider("documentLink",this.doc)}updateDocumentConfig(){let e=y.getConfiguration("links",this.doc);this._config={enable:e.get("enable",!0),highlight:e.get("highlight",!1)}}onChange(e){e.contentChanges.length==0?this.highlight():(this.cancel(),this.fetchLinks())}highlight(){if(!this.config.highlight||!this.links)return;let{links:e,doc:t}=this;if(re(e))this.clearHighlight();else{let i=[];e.forEach(r=>{t.addHighlights(i,abe,r.range)}),this.doc.buffer.updateHighlights(zV,i,{priority:2048})}}clearHighlight(){this.buffer.clearNamespace(zV)}get buffer(){return this.doc.buffer}cancel(){this.fetchLinks.clear(),this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null)}async getLinks(){if(!this.hasProvider||!this.config.enable)return;this.cancel();let t=(this.tokenSource=new p.CancellationTokenSource).token,i=await I.getDocumentLinks(this.doc.textDocument,t);this.tokenSource=void 0,!(t.isCancellationRequested||lbe(le(this.links),le(i)))&&(this.links=le(i),this.highlight())}dispose(){this.cancel()}}});var Xm,VV=D(()=>{"use strict";ae();Je();Se();um();Be();U();he();Xm=class{constructor(e,t){this.nvim=e;this.handler=t}async request(e,t){let{doc:i,position:r}=await this.handler.getCurrentState();return this.handler.checkProvider(e,i.textDocument),await i.synchronize(),await this.handler.withRequestToken(e,o=>t(i.textDocument,r,o),!0)}async definitions(){let{doc:e,position:t}=await this.handler.getCurrentState();this.handler.checkProvider("definition",e.textDocument),await e.synchronize();let i=new p.CancellationTokenSource;return I.getDefinition(e.textDocument,t,i.token)}async declarations(){let{doc:e,position:t}=await this.handler.getCurrentState();this.handler.checkProvider("declaration",e.textDocument),await e.synchronize();let i=new p.CancellationTokenSource;return I.getDeclaration(e.textDocument,t,i.token)}async typeDefinitions(){let{doc:e,position:t}=await this.handler.getCurrentState();this.handler.checkProvider("typeDefinition",e.textDocument),await e.synchronize();let i=new p.CancellationTokenSource;return I.getTypeDefinition(e.textDocument,t,i.token)}async implementations(){let{doc:e,position:t}=await this.handler.getCurrentState();this.handler.checkProvider("implementation",e.textDocument),await e.synchronize();let i=new p.CancellationTokenSource;return I.getImplementation(e.textDocument,t,i.token)}async references(e){let{doc:t,position:i}=await this.handler.getCurrentState();this.handler.checkProvider("reference",t.textDocument),await t.synchronize();let r=new p.CancellationTokenSource;return I.getReferences(t.textDocument,{includeDeclaration:!e},i,r.token)}async gotoDefinition(e){let t=await this.request("definition",(i,r,o)=>I.getDefinition(i,r,o));return await this.handleLocations(t,e),t?t.length>0:!1}async gotoDeclaration(e){let t=await this.request("declaration",(i,r,o)=>I.getDeclaration(i,r,o));return await this.handleLocations(t,e),t?t.length>0:!1}async gotoTypeDefinition(e){let t=await this.request("typeDefinition",(i,r,o)=>I.getTypeDefinition(i,r,o));return await this.handleLocations(t,e),t?t.length>0:!1}async gotoImplementation(e){let t=await this.request("implementation",(i,r,o)=>I.getImplementation(i,r,o));return await this.handleLocations(t,e),t?t.length>0:!1}async gotoReferences(e,t=!0){let i=await this.request("reference",(r,o,s)=>I.getReferences(r,{includeDeclaration:t},o,s));return await this.handleLocations(i,e),i?i.length>0:!1}async getTagList(){let{doc:e,position:t}=await this.handler.getCurrentState(),i=await this.nvim.call("expand","");if(!i||!I.hasProvider("definition",e.textDocument))return null;let r=new p.CancellationTokenSource,o=await I.getDefinition(e.textDocument,t,r.token);return!o||!o.length?null:o.map(s=>{let a=O.parse(s.uri),l=a.scheme=="file"?a.fsPath:a.toString();return{name:i,cmd:`silent keepjumps ${s.range.start.line+1} | normal ${s.range.start.character+1}|`,filename:l}})}async findLocations(e,t,i,r=!1){let{doc:o,position:s}=await this.handler.getCurrentState();i=i||{},Object.assign(i,{textDocument:{uri:o.uri},position:s});let a=await xn.sendRequest(e,t,i),l=this.toLocations(a);return await this.handleLocations(l,r),l.length>0}toLocations(e){let t=[];if(e&&Rn(e,"location")&&Rn(e,"children")){let i=r=>{if(!!r){if(Ke.is(r.location))t.push(r.location);else if(pr.is(r.location)){let o=r.location;t.push({uri:o.targetUri,range:o.targetSelectionRange,targetRange:o.targetRange})}if(r.children&&r.children.length)for(let o of r.children)i(o)}};return i(e),t}if(Ke.is(e))t.push(e);else if(pr.is(e))t.push({uri:e.targetUri,range:e.targetSelectionRange,targetRange:e.targetRange});else if(Array.isArray(e))for(let i of e)Ke.is(i)?t.push(i):i&&typeof i.targetUri=="string"&&t.push({uri:i.targetUri,range:i.targetSelectionRange,targetRange:i.targetRange});return t}async handleLocations(e,t){if(!e)return;let i=e.length;if(i!=0)if(i==1&&t!==!1){let{uri:r,range:o}=e[0];await y.jumpTo(r,o.start,t)}else await y.showLocations(e)}}});var Gm,e6=D(()=>{"use strict";Be();Gm=class{constructor(){this.stack=[]}add(e){let t=new Map;for(let i of e)t.set(i.lnum,i);this.stack.push(t)}checkInsert(e){if(!this.stack.length)return;let t=this.stack[this.stack.length-1],i=Array.from(t.keys()).sort((r,o)=>r-o);if(!!Me(i,e))return this.stack.pop(),Array.from(t.values())}}});function cbe(n,e){let{start:t,end:i}=n;return M.create(t.line-e,t.character,i.line-e,i.character)}function dbe(n){let{contentChanges:e,bufnr:t,textDocument:i,original:r,originalLines:o}=n,{range:s,text:a}=e[0],l=[{range:s,text:a}];if(r){let u=r.split(/\r?\n/),c=u[u.length-1];if(c.startsWith(lo)){let g=o[s.start.line].slice(0,s.start.character);if(g==c){r=g+u.slice(0,-1).join(` +`)+` +`;let{start:f,end:m}=s;l[0].range=M.create(f.line,0,m.line,0)}}let d=o[s.start.line-1],h=u.length>1?u[u.length-2]:"";if(c==""&&h.startsWith(lo)&&d==h&&s.start.character==0&&s.end.character==0){r=d+` +`+u.slice(0,-2).join(` +`)+` +`;let{start:g,end:f}=s;l[0].range=M.create(g.line-1,0,f.line-1,0)}}else if(Gt(s)&&s.start.character!=0){let u=a.split(/\r?\n/),c=u[u.length-1],d=o[s.start.line].slice(0,s.start.character);if(c.startsWith(lo)&&d==c){l[0].text=d+u.slice(0,-1).join(` +`)+` +`;let{start:h,end:g}=s;l[0].range=M.create(h.line,0,g.line,0)}}return{contentChanges:l,bufnr:t,textDocument:i,original:r,originalLines:o}}var ube,lo,zm,t6=D(()=>{"use strict";Wg();ae();Je();xe();ha();te();st();io();ls();de();Be();Tt();fe();wr();We();he();e6();ube=Z("handler-refactorBuffer"),lo="\u3000",zm=class{constructor(e,t,i,r,o){this.bufnr=e;this.srcId=t;this.nvim=i;this.config=r;this.opts=o;this._disposed=!1;this._fileItems=[];this.mutex=new ji;this.disposables=[];this.matchIds=new Set;this.changing=!1;this.changes=new Gm,this.disposables.push(y.registerLocalKeymap(e,"n","",this.splitOpen.bind(this),!0)),r.showMenu&&this.disposables.push(y.registerLocalKeymap(e,"n",r.showMenu,this.showMenu.bind(this),!0)),y.onDidChangeTextDocument(this.onDocumentChange,this,this.disposables)}async showMenu(){let e=await P.showMenuPicker(["Tab open","Remove block"]);if(e==-1)return;let t=await this.searchCurrentRange();if(!!t){if(e==0){let r=(await this.nvim.eval("strpart(getline('.'), 0 ,col('.') - 1)")).length,o=this.getAbsolutePath(t.filepath);this.nvim.call("coc#util#jump",["tabe",o,[t.line,r]],!0)}if(e==1){let i=this.getDeleteRange(t);await this.document.applyEdits([Ye.del(i)])}}}get fileItems(){return this._fileItems}getFileItem(e){let t=O.parse(e).fsPath;return this._fileItems.find(i=>ai(i.filepath,t))}getFileRange(e){for(let t of this._fileItems)for(let i of t.ranges)if(i.lnum==e)return Object.assign(ci(i,["highlights"]),{filepath:t.filepath});throw new Error(`File range not found at lnum: ${e}`)}onChange(e){if(this.changing)return;if(e.contentChanges.length===0){this.highlightLineNr(),this.nvim.redrawVim();return}let{nvim:t}=this;e=dbe(e);let i=e.contentChanges[0],{original:r}=e;i.range.end.line>2&&t.call("setbufvar",[e.bufnr,"&modified",1],!0);let{range:o,text:s}=i;if(ca(Ye.replace(o,s))==0)return;let l=[Ye.replace(o,s)],u=[];if(!Gt(o)&&!s.includes("\u3000")){let c=o.start.line,d=[],h=r.split(/\r?\n/);for(let g=0;g1&&f.includes("\u3000")&&d.push(c+g+1)}if(d.length){let g=d.map(f=>this.getFileRange(f));for(let f of this._fileItems)f.ranges=f.ranges.filter(m=>!d.includes(m.lnum));this.changes.add(g)}}else if(Gt(o)&&s.includes("\u3000")){let c=s.split(/\r?\n/),d=[],h=o.start.line;for(let g=0;g1&&f.includes("\u3000")&&d.push(h+g+1)}if(d.length){let g=this.changes.checkInsert(d);g&&(u=g)}}else s.includes("\u3000")&&(l=this.diffChanges(r,s),l.forEach(c=>{c.range=rU(c.range,o.start)}));this.adjustLnums(l),t.pauseNotification(),this.highlightLineNr(),t.resumeNotification(!0,!0),u.length&&u.forEach(c=>{this._fileItems.find(h=>h.filepath==c.filepath).ranges.push(c)})}diffChanges(e,t){let i=[],r=fi(e,t),o=0,s=Qr.create("file:///1","",0,e);for(let a=0;a=c.start+c.lines.length)continue;if(r.end.line!l.includes(c))),this._fileItems=this._fileItems.filter(u=>u.ranges&&u.ranges.length>0),a.length&&(this.adjustLnums(a),this.changing=!0,await this.document.applyEdits(a),this.changing=!1),this.nvim.pauseNotification(),this.highlightLineNr(),this.buffer.setOption("modified",!1,!0),await this.nvim.resumeNotification(!0)}adjustLnums(e){for(let t of this._fileItems)for(let i of t.ranges){let r=i.lnum-1;i.lnum+=AP(Q.create(r,0),e)}}async getFileChanges(){let e=[],t=await this.buffer.lines;t.push(lo);let i=[],r,o;for(let s=0;s1){let l=a.match(/^\u3000(.*)/);l&&(r=this.getAbsolutePath(l[1].replace(/\s+$/,"")),o=s+1,i=[])}}else i.push(a)}return e}async splitOpen(){let{nvim:e}=this,i=await e.createWindow(this.opts.fromWinid).valid,o=(await e.eval("strpart(getline('.'), 0 ,col('.') - 1)")).length,s=await this.searchCurrentRange();if(s){let a=this.getAbsolutePath(s.filepath);e.pauseNotification(),i?(e.call("win_gotoid",[this.opts.fromWinid],!0),this.nvim.call("coc#util#jump",["edit",a,[s.line,o]],!0)):this.nvim.call("coc#util#jump",["belowright vs",a,[s.line,o]],!0),e.command("normal! zz",!0),await e.resumeNotification(!0),i||(this.opts.fromWinid=await e.call("win_getid"))}}async searchCurrentRange(){let{nvim:e}=this,t=await e.eval('getline(1,line("."))'),i=t.length;for(let r=0;rcbe(k,m)));let{lines:b,start:v,end:x,highlights:C}=h;b||(b=await this.getLines(c.filepath,v,x)),d.push({lines:b,lnum:g,start:v,highlights:C}),s.addLines(b)}if(d.length){let h={filepath:c.filepath,ranges:d},g=this._fileItems.find(f=>f.filepath==c.filepath);g?g.ranges.push(...h.ranges):this._fileItems.push(h)}}let{nvim:l,buffer:u}=this;if(this.changing=!0,l.pauseNotification(),s.render(u,o),this.highlightLineNr(),u.setOption("modified",!1,!0),u.setOption("undolevels",1e3,!0),o==2&&a.length){let c=a[0].start;l.call("coc#cursor#move_to",[c.line,c.character],!0)}await l.resumeNotification(!0),await i.patchChange(),this.changing=!1,await P.cursors.addRanges(a)}catch(o){this.changing=!1,ube.error("Error on add file item:",o)}r()}findRange(e,t){let r=this.fileItems.find(o=>ai(this.getAbsolutePath(o.filepath),e)).ranges.find(o=>o.lnum==t);if(!r)throw new Error(`File range not found at lnum: ${t}`);return r}async save(){let{nvim:e}=this,t=this.document,{buffer:i}=t;await t.patchChange();let r=await this.getFileChanges();if(!r)return;r.sort((a,l)=>a.lnum-l.lnum);let o=[];for(let a=0;a0&&a.ranges.forEach(c=>{c.start+=AP(Q.create(c.start,0),u)})}return e.pauseNotification(),i.setOption("modified",!1,!0),this.config.saveToFile&&e.command("silent noa wa",!0),this.highlightLineNr(),await e.resumeNotification(),!0}async getLines(e,t,i){let r=O.file(e).toString(),o=y.getDocument(r);return o?o.getLines(t,i):await Qs(e,t,i-1)}getAbsolutePath(e){return R.isAbsolute(e)?e:R.join(this.opts.cwd,e)}highlightLineNr(){let{fileItems:e,nvim:t,srcId:i,bufnr:r}=this,{winid:o,cwd:s}=this.opts,a={};if(i){t.call("nvim_buf_clear_namespace",[r,i,0,-1],!0);for(let l of e)for(let u of l.ranges){let c=u.start+u.lines.length,d=`${u.start+1}:${c}`;a[u.lnum]=[u.start+1,c],t.call("nvim_buf_set_virtual_text",[r,i,u.lnum-1,[[d,"LineNr"]],{}],!0)}}else{this.matchIds.size&&(t.call("coc#highlight#clear_matches",[o,Array.from(this.matchIds)],!0),this.matchIds.clear());let l=2e3;for(let u of e){let c=`${s?R.relative(s,u.filepath):u.filepath}`,d=ue(c)+1;for(let h of u.ranges){let g=h.start+h.lines.length,f=`:${h.start+1}:${g}`;for(let m=0;m{"use strict";i6=require("child_process"),n6=require("events");ae();xe();ha();yc();ls();de();We();hbe=Z("handler-search"),gbe=["--color","ansi","--colors","path:fg:black","--colors","line:fg:green","--colors","match:fg:red","--no-messages","--heading","-n"],pbe="\x1B",tI=class extends n6.EventEmitter{start(t,i,r){this.process=(0,i6.spawn)(t,i,{cwd:r}),this.process.on("error",d=>{this.emit("error",d.message)});let o=ho.createInterface(this.process.stdout),s,a,l=[],u=[],c=!0;o.on("line",d=>{if(d.includes(pbe)){let h=Mg(d);if(h.length==0)return;if(h[0].foreground=="black"){a={filepath:R.join(r,h[0].text),ranges:[]};return}if(h[0].foreground=="green"){let f=parseInt(h[0].text,10)-1,m=h[0].text.length+1;c&&(s=f,c=!1);let b="";for(let x of h){if(x.foreground=="red"){let C=f-s,k=b.length-m;u.push(M.create(C,k,C,k+x.text.length))}b+=x.text}let v=b.slice(m);l.push(v)}}else{let h=d.trim().length==0;a&&(h||d.trim()=="--")&&a.ranges.push({lines:l,highlights:u,start:s}),h&&(this.emit("item",a),a=null),l=[],u=[],c=!0}}),o.on("close",()=>{a&&(l.length&&a.ranges.push({lines:l,highlights:u,start:s}),this.emit("item",a)),l=u=a=null,this.emit("end")})}dispose(){this.process&&this.process.kill()}},Km=class{constructor(e,t="rg"){this.nvim=e;this.cmd=t}run(e,t,i){let{nvim:r,cmd:o}=this,{afterContext:s,beforeContext:a}=i.config,l=["-A",s.toString(),"-B",a.toString()].concat(gbe,e),u=fbe(e);u&&l.pop(),l.push("--",u?R.isAbsolute(u)?u:`./${u.replace(/^\.\//,"")}`:"./"),this.task=new tI,this.task.start(o,l,t);let c=new ji,d=0,h=0,g=Date.now(),f=[],m=async()=>{if(f.length==0)return;let b=f.slice();f=[];let v=await c.acquire();try{await i.addFileItems(b)}catch(x){hbe.error(x)}v()};return new Promise((b,v)=>{let x=setInterval(m,300);this.task.on("item",async C=>{d++,h=h+C.ranges.reduce((k,T)=>k+T.highlights.length,0),f.push(C)}),this.task.on("error",C=>{clearInterval(x),P.showErrorMessage(`Error on command "${o}": ${C}`),this.task=null,v(new Error(C))}),this.task.on("end",async()=>{clearInterval(x);try{await m(),(await c.acquire())(),this.task.removeAllListeners(),this.task=null;let k=i.buffer;if(k){if(r.pauseNotification(),d==0)k.setLines(["No match found"],{start:1,end:2,strictIndexing:!1},!0),k.addHighlight({line:1,srcId:-1,colEnd:-1,colStart:0,hlGroup:"Error"}),k.setOption("modified",!1,!0);else{let T=new zi;T.addText("Files","MoreMsg"),T.addText(": "),T.addText(`${d} `,"Number"),T.addText("Matches","MoreMsg"),T.addText(": "),T.addText(`${h} `,"Number"),T.addText("Duration","MoreMsg"),T.addText(": "),T.addText(`${Date.now()-g}ms`,"Number"),T.render(k,1,2)}k.setOption("modified",!1,!0),r.resumeNotification(!1,!0)}}catch(C){v(C);return}b()})})}abort(){var e;(e=this.task)==null||e.dispose()}}});function o6(n,e){let{start:t,end:i}=n;return M.create(t.line-e,t.character,i.line-e,i.character)}var mbe,bbe,iI,Qm,s6=D(()=>{"use strict";ae();Je();Pe();Se();te();st();U();wr();he();t6();r6();mbe="__coc_refactor__",bbe=0,Qm=class{constructor(e,t){this.nvim=e;this.handler=t;this.buffers=new Map;this.disposables=[];this._onCreate=new p.Emitter;this.onCreate=this._onCreate.event;this.setConfiguration(),y.onDidChangeConfiguration(this.setConfiguration,this,this.disposables),_.on("BufUnload",i=>{let r=this.buffers.get(i);r&&(r.dispose(),this.buffers.delete(i))},null,this.disposables),y.onDidChangeTextDocument(i=>{let r=this.buffers.get(i.bufnr);r&&r.onChange(i)},null,this.disposables)}has(e){return this.buffers.has(e)}setConfiguration(e){if(e&&!e.affectsConfiguration("refactor"))return;let t=y.getConfiguration("refactor",null);this.config=Object.assign(this.config||{},{afterContext:t.get("afterContext",3),beforeContext:t.get("beforeContext",3),openCommand:t.get("openCommand","edit"),saveToFile:t.get("saveToFile",!0),showMenu:t.get("showMenu","")})}async doRefactor(){let{doc:e,position:t}=await this.handler.getCurrentState();if(!I.hasProvider("rename",e.textDocument))throw new Error("Rename provider not found for current buffer");await e.synchronize();let i=await this.handler.withRequestToken("refactor",async r=>{let o=await I.prepareRename(e.textDocument,t,r);if(r.isCancellationRequested)return null;if(o===!1)throw new Error("Provider returns null on prepare, unable to rename at current position");let s=await I.provideRenameEdits(e.textDocument,t,"NewName",r);if(r.isCancellationRequested)return null;if(!s)throw new Error("Provider returns null for rename edits.");return s});i&&await this.fromWorkspaceEdit(i,e.filetype)}async search(e){let t=await this.createRefactorBuffer(),i=await this.nvim.call("getcwd",[]);await new Km(this.nvim).run(e,i,t)}async save(e){let t=this.buffers.get(e);if(t)return await t.save()}getBuffer(e){return this.buffers.get(e)}async createRefactorBuffer(e,t=!1){let{nvim:i}=this,[r,o]=await i.eval("[win_getid(),getcwd()]"),{openCommand:s}=this.config;!i.isVim&&!iI&&(iI=await this.nvim.createNamespace("coc-refactor")),i.pauseNotification(),i.command(`${s} ${mbe}${bbe++}`,!0),i.command("setl buftype=acwrite nobuflisted bufhidden=wipe nofen wrap conceallevel=2 concealcursor=n",!0),i.command("setl undolevels=-1 nolist nospell noswapfile foldmethod=expr foldexpr=coc#util#refactor_foldlevel(v:lnum)",!0),i.command("setl foldtext=coc#util#refactor_fold_text(v:foldstart)",!0),i.call("setline",[1,["Save current buffer to make changes",lo]],!0),i.call("matchadd",["Comment","\\%1l"],!0),i.call("matchadd",["Conceal","^\\%u3000"],!0),i.call("matchadd",["Label","^\\%u3000\\zs\\S\\+"],!0),i.command("setl nomod",!0),e&&i.command(`runtime! syntax/${e}.vim`,!0),i.call("coc#util#do_autocmd",["CocRefactorOpen"],!0),await i.resumeNotification();let[a,l]=await i.eval('[bufnr("%"),win_getid()]'),u={fromWinid:r,winid:l,cwd:o};await y.document;let c=new zm(a,t?void 0:iI,this.nvim,this.config,u);return this.buffers.set(a,c),c}async fromLines(e){let t=await this.createRefactorBuffer();return await t.buffer.setLines(e,{start:0,end:-1,strictIndexing:!1}),t}async fromLocations(e,t){if(!e||e.length==0)return;let i={},r={changes:i};for(let o of e){let s=i[o.uri]||[];s.push({range:o.range,newText:""}),i[o.uri]=s}return await this.fromWorkspaceEdit(r,t)}async fromWorkspaceEdit(e,t){if(!e||lU(e))return;let i=[],{beforeContext:r,afterContext:o}=this.config,{changes:s,documentChanges:a}=e;if(!s){s={};for(let u of a||[])if(Qt.is(u)){let{textDocument:c,edits:d}=u;s[c.uri]=d}}for(let u of Object.keys(s)){let c=await this.getLineCount(u),d=s[u],h=[],g=null,f=null,m=[];d.sort((b,v)=>b.range.start.line-v.range.start.line);for(let b of d){let{line:v}=b.range.start,x=Math.max(0,v-r);g!=null&&x{"use strict";ae();Se();Tt();U();We();he();Vm=class{constructor(e,t){this.nvim=e;this.handler=t}async getWordEdit(){let{doc:e,position:t}=await this.handler.getCurrentState(),i=e.getWordRangeAtPosition(t);if(!i||Gt(i))return null;let r=e.textDocument.getText(i);if(I.hasProvider("rename",e.textDocument)){await e.synchronize();let s=new p.CancellationTokenSource;if(await I.prepareRename(e.textDocument,t,s.token)!==!1){let l=r.startsWith("a")?"b":"a",u=await I.provideRenameEdits(e.textDocument,t,l,s.token);if(u)return u}}P.showInformationMessage("Rename provider not found, extract word ranges from current buffer");let o=e.getSymbolRanges(r);return{changes:{[e.uri]:o.map(s=>({range:s,newText:r}))}}}async rename(e){let{doc:t,position:i}=await this.handler.getCurrentState();this.handler.checkProvider("rename",t.textDocument),await t.synchronize();let r=new p.CancellationTokenSource().token,o=await I.prepareRename(t.textDocument,i,r);if(o===!1)return P.showWarningMessage("Invalid position for rename"),!1;let s;if(!e){M.is(o)?(s=t.textDocument.getText(o),await P.moveTo(o.start)):o&&typeof o.placeholder=="string"?s=o.placeholder:s=await this.nvim.eval('expand("")');let l=y.getConfiguration("coc.preferences",null);e=await P.requestInput("New name",l.get("renameFillCurrent",!0)?s:void 0)}if(e===""&&P.showWarningMessage("Empty word, rename canceled"),!e)return!1;let a=await I.provideRenameEdits(t.textDocument,i,e,r);return r.isCancellationRequested||!a?!1:(await y.applyEdit(a),this.nvim.redrawVim(),!0)}}});var eb,l6=D(()=>{"use strict";ae();Se();Be();Tt();We();eb=class{constructor(e,t){this.nvim=e;this.handler=t;this.selectionRange=null}async getSelectionRanges(){let{doc:e,position:t}=await this.handler.getCurrentState();return this.handler.checkProvider("selectionRange",e.textDocument),await e.synchronize(),await this.handler.withRequestToken("selection ranges",r=>I.getSelectionRanges(e.textDocument,[t],r))}async selectRange(e,t){let{nvim:i}=this,{doc:r}=await this.handler.getCurrentState();this.handler.checkProvider("selectionRange",r.textDocument);let o=[];if(!t&&(!this.selectionRange||!e))return;if(e){let u=await P.getSelectedRange(e);o.push(u.start,u.end)}else{let u=await P.getCursorPosition();o.push(u)}if(!t){let u=M.create(o[0],o[1]),{selectionRange:c}=this;for(;c&&c.parent&&!Me(c.parent.range,u);)c=c.parent;c&&c.parent&&await P.selectRange(c.range);return}await r.synchronize();let s=await this.handler.withRequestToken("selection ranges",u=>I.getSelectionRanges(r.textDocument,o,u));if(!s||s.length==0)return;await i.eval("mode()")!="n"&&await i.eval(`feedkeys("\\", 'in')`);let l;if(s.length==1)l=s[0];else{let u=o[1]??o[0],c=M.create(o[0],u);for(l=s[0];l;){if(Me(c,l.range)){l=l.parent;continue}if(Ft(o[0],l.range)==0&&Ft(u,l.range)==0)break;l=l.parent}}!l||(this.selectionRange=s[0],await P.selectRange(l.range))}}});function nS(n){if(!n)return"";if(nI.has(n))return nI.get(n);let e=[];for(let i=0;i{"use strict";ae();Se();xe();K0();te();Re();Ii();te();Vs();U();fe();We();he();ybe=Z("semanticTokens-buffer"),vbe=pe(15,5),Rd="CocSem",Oo="semanticTokens",u6=pe(100,20),wbe=pe(500,20),nI=new Map,tb=class{constructor(e,t,i){this.nvim=e;this.doc=t;this.staticConfig=i;this._dirty=!1;this.regions=new Na;this._onDidRefresh=new p.Emitter;this.onDidRefresh=this._onDidRefresh.event;this.highlight=Wb(()=>{this.doHighlight()},u6),this.hasProvider&&this.highlight()}get config(){return this._config?this._config:(this.loadConfiguration(),this._config)}loadConfiguration(){let e=y.getConfiguration("semanticTokens",this.doc),t=this._config!=null&&this._config.enable!=e.enable;this._config={enable:e.get("enable"),highlightPriority:e.get("highlightPriority"),incrementTypes:e.get("incrementTypes"),combinedModifiers:e.get("combinedModifiers")},t&&(this._config.enable?this.highlight():this.clearHighlight())}get configEnabled(){let{enable:e}=this.config,{filetypes:t}=this.staticConfig;return Array.isArray(t)?t.includes("*")||t.includes(this.doc.filetype):e}get bufnr(){return this.doc.bufnr}onChange(){this.highlight()}onTextChange(){this.cancel()}async forceHighlight(){this.clearHighlight(),this.cancel(),await this.doHighlight(!0)}async onShown(){if(this.shouldRangeHighlight)return;let{doc:e}=this;e.dirty||e.version===this._version||await this.doHighlight(!1,!0)}get hasProvider(){return I.hasProvider("semanticTokens",this.doc)||I.hasProvider("semanticTokensRange",this.doc)}get hasLegend(){let{textDocument:e}=this.doc;return I.getLegend(e)!=null||I.getLegend(e,!0)!=null}get rangeProviderOnly(){return!I.hasProvider("semanticTokens",this.doc)&&I.hasProvider("semanticTokensRange",this.doc)}get shouldRangeHighlight(){let{textDocument:e}=this.doc;return I.hasProvider("semanticTokensRange",e)&&this.previousResults==null}get lineCount(){return this.doc.lineCount}get highlights(){if(!!this._highlights)return this._highlights[1]}get buffer(){return this.nvim.createBuffer(this.bufnr)}get enabled(){return!this.configEnabled||!y.env.updateHighlight||!this.hasLegend?!1:this.hasProvider}checkState(){if(!y.env.updateHighlight)throw new Error("Can't perform highlight update, highlight update requires vim >= 8.1.1719 or neovim >= 0.5.0");if(!this.configEnabled)throw new Error(`Semantic tokens highlight not enabled for current filetype: ${this.doc.filetype}`);if(this.staticConfig.highlightGroups.length===0)throw new Error("Unable to find highlight groups starts with CocSem");if(!this.hasProvider||!this.hasLegend)throw new Error(`SemanticTokens provider not found for ${this.doc.uri}`)}async getTokenRanges(e,t,i){let r=0,o=0,s=[],a,l=this.doc.textDocument,u=Date.now();for(let c=0;cvbe){if(await ar(),i.isCancellationRequested)break;u=Date.now()}let d=e[c],h=e[c+1],g=e[c+2],f=t.tokenTypes[e[c+3]],m=t.tokenModifiers.filter((C,k)=>e[c+4]&1<=i))continue;let u={lnum:l,hlGroup:a.hlGroup,colStart:a.range[1],colEnd:a.range[2],combine:a.combine};r.includes(a.tokenType)&&(u.end_incl=!0,u.start_incl=!0),s.push(u)}return s}async doHighlight(e=!1,t=!1){var l;if(this.cancel(),!this.enabled||!t&&!y.editors.isVisible(this.bufnr))return;let r=(this.tokenSource=new p.CancellationTokenSource).token;if(this.shouldRangeHighlight){let c=(this.rangeTokenSource=new p.CancellationTokenSource).token;if(await this.doRangeHighlight(c),c.isCancellationRequested||(this.rangeTokenSource=void 0),c.isCancellationRequested&&this.rangeProviderOnly)return}if(r.isCancellationRequested)return;let{doc:o}=this,s=o.version,a;if(s===((l=this.previousResults)==null?void 0:l.version))if(this._highlights&&this._highlights[0]==s)a=this._highlights[1];else{let u=this.previousResults.tokens,c=I.getLegend(o.textDocument);a=await this.getTokenRanges(u,c,r)}else a=await this.sendRequest(()=>this.requestAllHighlights(r,e),r);if(!(r.isCancellationRequested||!a)){if(this._highlights=[s,a],!this._dirty||a.length<200){let u=this.toHighlightItems(a),c=await P.diffHighlights(this.bufnr,Oo,u,void 0,r);if(r.isCancellationRequested||!c)return;this._dirty=!0,this._version=s;let d=this.config.highlightPriority;await P.applyDiffHighlights(this.bufnr,Oo,d,c)}else this.regions.clear(),await this.highlightRegions(r);r.isCancellationRequested||(this.tokenSource=void 0),this._onDidRefresh.fire()}}async sendRequest(e,t){try{return await e()}catch(i){t.isCancellationRequested||(i instanceof Rt?this.highlight(wbe):ybe.error("Error on request semanticTokens: ",i));return}}async doRangeHighlight(e){let{version:t}=this.doc,i=await this.sendRequest(()=>this.requestRangeHighlights(e),e);if(i==null||e.isCancellationRequested)return;let{highlights:r,start:o,end:s}=i;if(this.rangeProviderOnly||!this.previousResults){(!this._highlights||t!==this._highlights[0])&&(this._highlights=[t,[]]);let u=this._highlights[1],c=u.reduce((d,h)=>d.add(h.range[0]),new Set);r.forEach(d=>{c.has(d.range[0])||u.push(d)})}let a=this.toHighlightItems(r),l=await P.diffHighlights(this.bufnr,Oo,a,[o,s],e);if(l){let u=this.config.highlightPriority;await P.applyDiffHighlights(this.bufnr,Oo,u,l,!0),this._dirty=!0}}async highlightRegions(e,t=!1){let{regions:i,highlights:r,config:o,lineCount:s,bufnr:a}=this;if(!r)return;let l=await this.nvim.call("coc#window#visible_ranges",[a]);if(e.isCancellationRequested||l.length===0)return;let u=y.env.lines;l.forEach(c=>{let d=c[0];c[0]=Math.max(0,Math.floor(d-u*1.5)),c[1]=Math.min(s,Math.ceil(c[1]+u*1.5),d+u*2)});for(let[c,d]of Na.mergeSpans(l)){if(!t&&i.has(c,d))continue;let h=this.toHighlightItems(r,c,d),g=await P.diffHighlights(a,Oo,h,[c,d],e);if(e.isCancellationRequested)break;i.add(c,d);let f=o.highlightPriority;g&&P.applyDiffHighlights(a,Oo,f,g,!0)}}async onCursorMoved(){if(this.cancel(!0),!this.enabled||this.doc.dirty)return;let t=(this.rangeTokenSource=new p.CancellationTokenSource).token;await Zi(u6),!t.isCancellationRequested&&(this.shouldRangeHighlight?await this.doRangeHighlight(t):await this.highlightRegions(t),t.isCancellationRequested||(this.rangeTokenSource=void 0))}async requestRangeHighlights(e){let{nvim:t,doc:i}=this,r=await t.call("coc#window#visible_range",[this.bufnr]);if(!r||e.isCancellationRequested)return null;let o=Math.min(r[0]+y.env.lines*2,r[1]+y.env.lines,i.lineCount),s=M.create(r[0]-1,0,o,0),a=await I.provideDocumentRangeSemanticTokens(i.textDocument,s,e);if(!a||!$s.is(a)||e.isCancellationRequested)return null;let l=I.getLegend(i.textDocument,!0),u=await this.getTokenRanges(a.data,l,e);return u?{highlights:u,start:r[0]-1,end:r[1]}:null}async requestAllHighlights(e,t){let i=this.doc.textDocument,r=I.getLegend(i),o=I.hasSemanticTokensEdits(i),s=t?null:this.previousResults,a=i.version,l;if(o&&(s==null?void 0:s.resultId)?l=await I.provideDocumentSemanticTokensEdits(i,s.resultId,e):l=await I.provideDocumentSemanticTokens(i,e),e.isCancellationRequested||l==null)return;let u=[];return $s.is(l)?u=l.data:s&&Array.isArray(l.edits)&&(u=s.tokens,l.edits.forEach(c=>{u.splice(c.start,rn(c.deleteCount),...le(c.data))})),this.previousResults={resultId:l.resultId,tokens:u,version:a},await this.getTokenRanges(u,r,e)}clearHighlight(){this.previousResults=void 0,this._highlights=void 0,this.regions.clear(),this.buffer.clearNamespace(Oo)}abandonResult(){this.previousResults=void 0}cancel(e=!1){this.rangeTokenSource&&(this.rangeTokenSource.cancel(),this.rangeTokenSource=null),!e&&(this.regions.clear(),this.highlight.clear(),this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource=null))}dispose(){this.cancel(),this.clearHighlight(),this._onDidRefresh.dispose()}}});function d6(){return y.initialConfiguration.get("semanticTokens.filetypes",null)}var rS,_d,ib,h6=D(()=>{"use strict";Dt();Pe();Se();ha();te();Re();fe();We();he();c6();rS="Statement";ib=class{constructor(e){this.nvim=e;this.disposables=[];this.staticConfig={filetypes:d6(),highlightGroups:[]},y.onDidChangeConfiguration(t=>{if(t.affectsConfiguration("semanticTokens")){this.staticConfig.filetypes=d6();for(let i of this.highlighters.items)i.loadConfiguration()}},this,this.disposables),V.register({id:"semanticTokens.checkCurrent",execute:async()=>{await this.showHighlightInfo()}},!1,"show semantic tokens highlight information of current buffer"),V.register({id:"semanticTokens.refreshCurrent",execute:()=>this.highlightCurrent()},!1,"refresh semantic tokens highlight of current buffer."),V.register({id:"semanticTokens.inspect",execute:()=>this.inspectSemanticToken()},!1,"Inspect semantic token information at cursor position."),V.register({id:"semanticTokens.clearCurrent",execute:async()=>{(await e.buffer).clearNamespace(Oo,0,-1)}},!1,"clear semantic tokens highlight of current buffer"),V.register({id:"semanticTokens.clearAll",execute:async()=>{let t=await e.buffers;for(let i of t)i.clearNamespace(Oo,0,-1)}},!1,"clear semantic tokens highlight of all buffers"),this.highlighters=y.registerBufferSync(t=>new tb(this.nvim,t,this.staticConfig)),I.onDidSemanticTokensRefresh(async t=>{re(this.staticConfig.highlightGroups)&&await this.fetchHighlightGroups();let i=P.visibleTextEditors.map(r=>r.document.bufnr);for(let r of this.highlighters.items)!y.match(t,r.doc)||(r.hasProvider?(r.abandonResult(),i.includes(r.bufnr)&&r.highlight()):r.clearHighlight())},null,this.disposables),_.on("BufWinEnter",async t=>{let i=this.highlighters.getItem(t);i&&await i.onShown()},null,this.disposables),_.on("CursorMoved",async t=>{let i=this.highlighters.getItem(t);i&&await i.onCursorMoved()},null,this.disposables)}async inspectSemanticToken(){let e=await this.getCurrentItem();if(!e||!e.enabled){if(e)try{e.checkState()}catch(a){P.showErrorMessage(a.message)}else{let a=await y.document;P.showErrorMessage(`Document not attached, ${a.notAttachReason}`)}this.closeFloat();return}let[t,i,r]=await this.nvim.call("getcurpos",[]),s=le(e.highlights).find(a=>{let l=r-1;return a.range[0]===i-1&&l>=a.range[1]&&lc.hlGroup!=null).map(({hlGroup:c})=>c));for(let c of a)r.addTexts([{text:"-",hlGroup:"Comment"},{text:" "},{text:c,hlGroup:c}]);r.addLine(""),r.addLine("Tokens types that current Language Server supported:",rS),r.addLine("");let l=y.getDocument(i.bufnr),u=I.getLegend(l.textDocument)??I.getLegend(l.textDocument,!0);if(u.tokenTypes.length){for(let c of[...new Set(u.tokenTypes)]){let d=Rd+is(c);r.addTexts([{text:"-",hlGroup:"Comment"},{text:" "},{text:d,hlGroup:d}])}r.addLine("")}else r.addLine("No token types supported","Comment"),r.addLine("");if(r.addLine("Tokens modifiers that current Language Server supported:",rS),r.addLine(""),u.tokenModifiers.length){for(let c of[...new Set(u.tokenModifiers)]){let d=Rd+is(c);r.addTexts([{text:"-",hlGroup:"Comment"},{text:" "},{text:d,hlGroup:d}])}r.addLine("")}else r.addLine("No token modifiers exist","Comment"),r.addLine("")}catch(s){r.addLine(yr(s))}t.pauseNotification(),r.render(t.createBuffer(o[0][2])),t.resumeNotification(!0,!0)}dispose(){this.highlighters.dispose(),W(this.disposables)}}});var xbe,nb,g6=D(()=>{"use strict";Pe();Se();te();Xe();de();U();fe();We();he();xbe=pe(100,10),nb=class{constructor(e,t){this.nvim=e;this.handler=t;this.disposables=[];this.loadConfiguration(),this.signatureFactory=P.createFloatFactory(Object.assign({preferTop:this.config.preferAbove,autoHide:!1,modes:["i","ic","s"]},this.config.floatConfig)),this.disposables.push(this.signatureFactory),y.onDidChangeConfiguration(this.loadConfiguration,this,this.disposables),_.on("CursorMovedI",ft(this.checkCurosr.bind(this),xbe),null,this.disposables),_.on(["InsertLeave","BufEnter"],()=>{var i;(i=this.tokenSource)==null||i.cancel()},null,this.disposables),_.on("TextChangedI",()=>{this.config.hideOnChange&&this.signatureFactory.close()},null,this.disposables),_.on("TextInsert",async(i,r,o)=>{if(!this.config.enableTrigger)return;let s=y.getDocument(i);!s||!s.attached||!I.shouldTriggerSignatureHelp(s.textDocument,o)||await this._triggerSignatureHelp(s,{line:r.lnum-1,character:r.pre.length},!1)},null,this.disposables),P.onDidChangeActiveTextEditor(()=>{this.loadConfiguration()},null,this.disposables)}checkCurosr(e,t){let i=this.lastPosition,r=this.signatureFactory;if(!i||e!==i.bufnr||r.window==null)return;let o=y.getDocument(e);if(!o||t[0]!=i.lnum||t[1]{o.dispose(),this.tokenSource=void 0});let{target:a}=this.config,l=this.timer=setTimeout(()=>{o.cancel()},this.config.wait);await e.patchChange(!0);let u=await I.getSignatureHelp(e.textDocument,t,s,{isRetrigger:this.signatureFactory.checkRetrigger(e.bufnr),triggerKind:i?p.SignatureHelpTriggerKind.Invoked:p.SignatureHelpTriggerKind.TriggerCharacter});if(clearTimeout(l),s.isCancellationRequested)return!1;if(!u||u.signatures.length==0)return this.signatureFactory.close(),!1;let{activeSignature:c,signatures:d}=u;if(c){let[g]=d.splice(c,1);g&&d.unshift(g)}return a=="echo"?this.echoSignature(u):await this.showSignatureHelp(e,t,u,r),!0}async showSignatureHelp(e,t,i,r){let{signatures:o,activeParameter:s}=i;s=typeof s=="number"?s:void 0;let a=null,l=r,u=o.reduce((d,h,g)=>{var v,x;let f=null,m=h.activeParameter??s;m===void 0&&((v=h.parameters)==null?void 0:v.length)>0&&(m=0);let b=h.label.indexOf("(");if(g==0&&typeof m=="number"){let C=(x=h.parameters)==null?void 0:x[m];if(C){let k=h.label.slice(b==-1?0:b);if(a=C.documentation,typeof C.label=="string"){let T=k.slice(0),j=T.match(new RegExp("\\b"+C.label.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b")),N=j?j.index:T.indexOf(C.label);N!=-1&&(f=[N+b,N+C.label.length+b])}else f=C.label}}if(f==null&&(f=[b+1,b+1]),r==l&&(r=r+f[0]+1),d.push({content:h.label,filetype:e.filetype,active:f}),a){let C=typeof a=="string"?a:a.value;C.trim().length&&d.push({content:C,filetype:bh(h.documentation)?"markdown":"txt"})}if(g==0&&h.documentation){let{documentation:C}=h,k=typeof C=="string"?C:C.value;k.trim().length&&d.push({content:k,filetype:bh(h.documentation)?"markdown":"txt"})}return d},[]),c=e.getline(t.line,!1).slice(0,t.character);this.lastPosition={bufnr:e.bufnr,lnum:t.line+1,col:ue(c)+1},await this.signatureFactory.show(u,{offsetX:r})}echoSignature(e){var s;let{signatures:t,activeParameter:i}=e,r=y.env.columns;t=t.slice(0,y.env.cmdheight);let o=[];for(let a of t){let l=[],{label:u}=a;u=u.replace(/\n/g," "),u.length>=r-16&&(u=u.slice(0,r-16)+"...");let c=u.indexOf("(");if(c==-1)l=[{text:u,type:"Normal"}];else{l.push({text:u.slice(0,c),type:"Label"});let d=u.slice(c);if(o.length==0&&i!=null){let h=(s=a.parameters)==null?void 0:s[i];if(h){let g,f;if(typeof h.label=="string"){let m=d.slice(0),b=m.match(new RegExp("\\b"+h.label.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b")),v=b?b.index:m.indexOf(h.label);v==-1?l.push({text:d,type:"Normal"}):(g=v,f=v+h.label.length)}else[g,f]=h.label,g=g-c,f=f-c;g!=null&&f!=null&&(l.push({text:d.slice(0,g),type:"Normal"}),l.push({text:d.slice(g,f),type:"MoreMsg"}),l.push({text:d.slice(f),type:"Normal"}))}}else l.push({text:d,type:"Normal"})}o.push(l)}this.nvim.callTimer("coc#ui#echo_signatures",[o],!0)}dispose(){W(this.disposables),this.timer&&clearTimeout(this.timer)}}});var Dnt,Cbe,rb,p6=D(()=>{"use strict";Se();xe();te();de();U();$0();Dnt=Z("symbols-buffer"),Cbe=pe(500,10),rb=class{constructor(e,t){this.doc=e;this.autoUpdateBufnrs=t;this.disposables=[];this._onDidUpdate=new p.Emitter;this.onDidUpdate=this._onDidUpdate.event;this.fetchSymbols=ft(()=>{this._fetchSymbols().catch(kd)},Cbe)}async getSymbols(){var t;let{doc:e}=this;return await e.patchChange(),this.autoUpdateBufnrs.add(e.bufnr),e.version==this.version&&((t=this.symbols)==null?void 0:t.length)?this.symbols:(this.cancel(),await this._fetchSymbols(),this.symbols)}onChange(e){e.contentChanges.length!==0&&(this.cancel(),this.autoUpdateBufnrs.has(this.doc.bufnr)&&this.fetchSymbols())}async _fetchSymbols(){let{textDocument:e}=this.doc,{version:t}=e,i=this.tokenSource=new p.CancellationTokenSource,{token:r}=i,o=await I.getDocumentSymbol(e,r);this.tokenSource=void 0,!(o==null||r.isCancellationRequested)&&(this.version=t,this.symbols=o,this._onDidUpdate.fire(o))}cancel(){this.fetchSymbols.clear(),this.tokenSource&&(this.tokenSource.cancel(),this.tokenSource.dispose(),this.tokenSource=null)}dispose(){this.cancel(),this.symbols=void 0,this._onDidUpdate.dispose(),W(this.disposables)}}});function Sbe(n){return n?typeof n.text=="string"&&typeof n.hlGroup=="string":!1}function Dbe(n,e){return n.label===e.label&&n.deprecated===e.deprecated&&n.key===e.key}function Tbe(n,e){return n.length!==e.length?!1:n.every((t,i)=>Dbe(t,e[i]))}var ob,f6=D(()=>{"use strict";rt();U();Dt();te();vp();Re();ob=class{constructor(e){this.opts=e;this.disposables=[];this._onDidChangeTreeData=new p.Emitter;this.onDidChangeTreeData=this._onDidChangeTreeData.event;this.invokeCommand=`_invoke_${me()}`,this.disposables.push(V.registerCommand(this.invokeCommand,async t=>{await e.handleClick(t)},null,!0)),typeof e.resolveActions=="function"&&(this.resolveActions=e.resolveActions.bind(this))}iterate(e,t,i,r){let o=r(e,t,i);if(o===!1)return!1;if(Array.isArray(e.children)){for(let s of e.children)if(this.iterate(s,e,i+1,r)===!1)return!1}return o}updateNodes(e,t,i,r=!0){let o=Tbe(e,t),s=(a,l,u)=>{var d,h,g,f;let c=!1;for(let m of Object.keys(l))["children","key"].includes(m)||(a[m]=l[m]);if(((d=a.children)==null?void 0:d.length)&&!((h=l.children)!=null&&h.length)&&(delete a.children,c=!0),!((g=a.children)!=null&&g.length)&&((f=l.children)==null?void 0:f.length)&&(a.children=l.children,c=!0),c){u&&this._onDidChangeTreeData.fire(a);return}le(a.children).length>0&&le(l.children).length>0&&this.updateNodes(a.children,l.children,a,u)};if(o)for(let a=0;a!l.has(g)&&h.key==c.key):d=a.findIndex((h,g)=>!l.has(g)&&h.label==c.label),d===-1)e[u]=c;else{l.add(d);let h=a[d];s(h,c,!1),e[u]=h}}r&&this._onDidChangeTreeData.fire(i)}}update(e,t){if(!!this.data)return t?(this.data=le(e),this._onDidChangeTreeData.fire(void 0)):this.updateNodes(this.data,le(e),void 0),this.data}getTreeItem(e){var o;let t=e.label,{expandLevel:i}=this.opts,r;if(!((o=e.children)!=null&&o.length))r=new Vr(t);else if(i&&i>0){let s=this.getLevel(e),a=s&&s<=i?2:1;r=new Vr(t,a)}else r=new Vr(t,1);if(r.description=e.description,e.deprecated&&(r.deprecated=!0),e.tooltip&&(r.tooltip=e.tooltip),Sbe(e.icon))r.icon=e.icon;else if(typeof this.opts.resolveIcon=="function"){let s=this.opts.resolveIcon(e);s&&(r.icon=s)}return r}async getChildren(e){if(e)return e.children??[];if(this.data)return this.data;let t=await Promise.resolve(this.opts.provideData());if(!Array.isArray(t))throw new Error("Unable to fetch data");return this.data=t,t}getParent(e){if(!this.data)return;let t;for(let i of this.data)if(this.iterate(i,null,0,(o,s)=>{if(o===e)return t=s,!1})===!1)break;return t}getLevel(e){if(!this.data)return 0;let t=0;for(let i of le(this.data))if(this.iterate(i,null,1,(o,s,a)=>{if(o===e)return t=a,!1})===!1)break;return t}async resolveTreeItem(e,t,i){if(typeof this.opts.resolveItem=="function"){let r=await Promise.resolve(this.opts.resolveItem(e,t,i));r&&Object.assign(e,r)}return e.command||(e.command={title:`invoke ${t.label}`,command:this.invokeCommand,arguments:[t]}),e}dispose(){this.data=[],this._onDidChangeTreeData.dispose(),typeof this.opts.onDispose=="function"&&this.opts.onDispose(),W(this.disposables)}}});function Pbe(n,e){let t,i=r=>{for(let o of r)if(Ft(n,o.range)==0){t=o,Array.isArray(o.children)&&i(o.children);break}};return i(e),t}var kbe,sb,m6=D(()=>{"use strict";ae();Pe();Se();f6();wp();te();Tt();We();he();kbe=pe(300,10),sb=class{constructor(e,t,i){this.nvim=e;this.buffers=t;this.handler=i;this.treeViewList=[];this.providersMap=new Map;this.sortByMap=new Map;this.disposables=[];this.loadConfiguration(),y.onDidChangeConfiguration(this.loadConfiguration,this,this.disposables),y.onDidCloseTextDocument(async r=>{let{bufnr:o}=r,s=this.providersMap.get(o);!s||await e.call("bufloaded",[o])||(this.providersMap.delete(o),s.dispose())},null,this.disposables),P.onDidChangeActiveTextEditor(async r=>{if(!this.config.checkBufferSwitch)return;this.treeViewList.find(s=>s.visible&&s.targetTabId==r.tabpageid)&&(await this.showOutline(r.document.bufnr,r.tabpageid),await e.command(`noa call win_gotoid(${r.winid})`))},null,this.disposables),_.on("CursorHold",async(r,o)=>{if(!this.config.followCursor||!this.providersMap.get(r))return;let a=await e.tabpage,l=this.treeViewList.find(u=>u.visible&&u.targetBufnr==r&&u.targetTabId==a.id);!l||await this.revealPosition(r,l,Q.create(o[0]-1,o[1]-1))},null,this.disposables)}async revealPosition(e,t,i){let r=this.providersMap.get(e),o=await Promise.resolve(r.getChildren()),s=Pbe(i,o);s&&await t.reveal(s)}loadConfiguration(e){if(!e||e.affectsConfiguration("outline")){let t=y.getConfiguration("outline",null);this.config={splitCommand:t.get("splitCommand"),switchSortKey:t.get("switchSortKey"),togglePreviewKey:t.get("togglePreviewKey"),followCursor:t.get("followCursor"),keepWindow:t.get("keepWindow"),expandLevel:t.get("expandLevel"),autoWidth:t.get("autoWidth"),checkBufferSwitch:t.get("checkBufferSwitch"),detailAsDescription:t.get("detailAsDescription"),sortBy:t.get("sortBy"),showLineNumber:t.get("showLineNumber"),codeActionKinds:t.get("codeActionKinds"),autoPreview:t.get("autoPreview"),previewMaxWidth:t.get("previewMaxWidth"),previewBorder:t.get("previewBorder"),previewBorderRounded:t.get("previewBorderRounded"),previewHighlightGroup:t.get("previewHighlightGroup"),previewBorderHighlightGroup:t.get("previewBorderHighlightGroup"),previewWinblend:t.get("previewWinblend")}}}convertSymbolToNode(e,t){var s;let i=[],{detailAsDescription:r,showLineNumber:o}=this.config;return r&&e.detail&&i.push(e.detail),o&&i.push(`${e.selectionRange.start.line+1}`),{label:e.name,tooltip:r?void 0:e.detail,description:i.join(" "),icon:this.handler.getIcon(e.kind),deprecated:(s=e.tags)==null?void 0:s.includes($i.Deprecated),kind:e.kind,range:e.range,selectRange:e.selectionRange,children:Array.isArray(e.children)?e.children.map(a=>this.convertSymbolToNode(a,t)).sort(t):void 0}}setMessage(e,t){this.treeViewList.forEach(i=>{i.valid&&i.targetBufnr==e&&(i.message=t)})}convertSymbols(e,t){let i=this.getSortBy(e),r=(o,s)=>i==="name"?o.labelthis.convertSymbolToNode(o,r)).sort(r)}onSymbolsUpdate(e,t){let i=this.providersMap.get(e);i&&i.update(this.convertSymbols(e,t))}createProvider(e){let{nvim:t}=this,i=new ob({expandLevel:this.config.expandLevel,provideData:async()=>{let r=this.buffers.getItem(e);if(!r)throw new Error("Document not attached");let o=y.getDocument(e);if(!I.hasProvider("documentSymbol",o.textDocument))throw new Error("Document symbol provider not found");let s=I.getDocumentSymbolMetadata(o.textDocument);s&&s.label&&this.treeViewList.filter(u=>u.valid&&u.targetBufnr==e).forEach(u=>u.description=s.label),this.setMessage(e,"Loading document symbols");let a=await r.getSymbols();if(!a||a.length==0)throw new Error("Empty symbols returned from language server. ");return this.setMessage(e,void 0),this.convertSymbols(e,a)},handleClick:async r=>{let o=await t.call("bufwinnr",[e]);if(o==-1)return;t.pauseNotification(),t.command(`${o}wincmd w`,!0);let s=r.selectRange.start;t.call("coc#cursor#move_to",[s.line,s.character],!0),t.command("normal! zz",!0);let a=t.createBuffer(e);a.highlightRanges("outline-hover","CocHoverRange",[r.selectRange]),t.command("redraw",!0),await t.resumeNotification(),setTimeout(()=>{a.clearNamespace("outline-hover"),t.command("redraw",!0)},kbe)},resolveActions:async(r,o)=>{let s=await t.call("bufwinnr",[e]);if(s==-1)return;let a=y.getDocument(e);return[...(await this.handler.getCodeActions(a,o.range,this.config.codeActionKinds)).map(c=>({title:c.title,handler:async()=>{let d=o.range.start;await t.command(`${s}wincmd w`),await this.nvim.call("coc#cursor#move_to",[d.line,d.character]),await this.handler.applyCodeAction(c)}})),{title:"Visual Select",handler:async c=>{await t.command(`${s}wincmd w`),await P.selectRange(c.range)}}]},onDispose:()=>{for(let r of this.treeViewList.slice())r.provider===i&&r.dispose()}});return i}getSortBy(e){return this.sortByMap.get(e)??this.config.sortBy}async showOutline(e,t){this.providersMap.has(e)||this.providersMap.set(e,this.createProvider(e));let i=this.treeViewList.find(r=>r.valid&&r.targetBufnr==e&&r.targetTabId==t);if(!i){let{switchSortKey:r,togglePreviewKey:o}=this.config,s=this.config.autoPreview,a;i=new So("OUTLINE",{autoWidth:this.config.autoWidth,bufhidden:"hide",enableFilter:!0,treeDataProvider:this.providersMap.get(e)});let l=this.getSortBy(e),u;i.description=`${l[0].toUpperCase()}${l.slice(1)}`,this.treeViewList.push(i);let c=_.on("BufEnter",d=>{a&&d!==a&&(u=void 0,this.closePreview())});i.onDispose(()=>{let d=this.treeViewList.findIndex(h=>h===i);d!==-1&&this.treeViewList.splice(d,1),c.dispose(),this.closePreview()}),i.onDidCursorMoved(async d=>{s&&u!==d&&(u=d,a=await this.doPreview(e,d))}),i.registerLocalKeymap("n",r,async()=>{let d=["category","name","position"],h=this.getSortBy(e),g=d.map(x=>({text:x,disabled:x===h})),f=await P.showMenuPicker(g,{title:"Choose sort method"});if(f<0)return;let m=d[f];this.sortByMap.set(e,m),this.treeViewList.filter(x=>x.targetBufnr==e).forEach(x=>{x.description=`${m[0].toUpperCase()}${m.slice(1)}`});let v=this.buffers.getItem(e);this.onSymbolsUpdate(e,v.symbols)},!0),i.registerLocalKeymap("n",o,async d=>{s=!s,s?a=await this.doPreview(e,d):(u=void 0,this.closePreview())},!0)}return await i.show(this.config.splitCommand,!1),i}async doPreview(e,t){if(!t){this.closePreview();return}let i={bufnr:e,range:t.range,border:this.config.previewBorder,rounded:this.config.previewBorderRounded,maxWidth:this.config.previewMaxWidth,highlight:this.config.previewHighlightGroup,borderhighlight:this.config.previewBorderHighlightGroup,winblend:this.config.previewWinblend};return await this.nvim.call("coc#ui#outline_preview",[i])}closePreview(){this.nvim.call("coc#ui#outline_close_preview",[],!0)}async show(e){let[t,i]=await this.nvim.eval('[bufnr("%"),win_getid()]'),r=await this.nvim.tabpage,o=y.getDocument(t);if(o&&!o.attached){P.showErrorMessage(`Unable to show outline, ${o.notAttachReason}`);return}let s=await P.getCursorPosition(),a=await this.showOutline(t,r.id);if(e==1||e===void 0&&this.config.keepWindow)await this.nvim.command(`noa call win_gotoid(${i})`);else if(this.config.followCursor){let l=a.onDidRefrash(async()=>{l.dispose(),await this.nvim.eval('bufnr("%")')==t&&a.visible&&await this.revealPosition(t,a,s)})}}has(e){return this.providersMap.has(e)}async hide(){let e=await this.nvim.call("coc#window#find",["cocViewId","OUTLINE"]);e!=-1&&await this.nvim.call("coc#window#close",[e])}dispose(){for(let e of this.treeViewList)e.dispose();this.treeViewList=[];for(let e of this.providersMap.values())e.dispose();this.providersMap.clear(),W(this.disposables)}}});function b6(n){let e=[],t=n.slice();return t.sort(y6),t.forEach(i=>v6(e,i,0)),e}function y6(n,e){let t=n.selectionRange,i=e.selectionRange;return Ge(t.start,i.start)}function v6(n,e,t){let{name:i,selectionRange:r,detail:o,kind:s,children:a,range:l,tags:u}=e,{start:c}=r||l,d={col:c.character+1,lnum:c.line+1,text:i,level:t,kind:ks(s),range:l,selectionRange:r};if(o&&(d.detail=o),u&&u.includes($i.Deprecated)&&(d.deprecated=!0),n.push(d),a&&a.length){a.sort(y6);for(let h of a)v6(n,h,t+1)}}var w6=D(()=>{"use strict";ae();im();Tt()});var ab,x6=D(()=>{"use strict";ae();Pe();Se();te();Be();Tt();U();fe();We();he();p6();m6();w6();ab=class{constructor(e,t){this.nvim=e;this.handler=t;this.disposables=[];this.autoUpdateBufnrs=new Set;this.buffers=y.registerBufferSync(i=>{let{bufnr:r}=i,o=new rb(i,this.autoUpdateBufnrs);return o.onDidUpdate(s=>{!this.outline||this.outline.onSymbolsUpdate(r,s)}),o}),this.outline=new sb(e,this.buffers,t),_.on("CursorHold",async(i,r)=>{if(!this.buffers.getItem(i)||!this.autoUpdate(i))return;let o=y.getDocument(i),s=Ut(o.getline(r[0]-1),r[1]-1),a=Q.create(r[0]-1,s),l=await this.getFunctionSymbol(i,a);e.createBuffer(i).setVar("coc_current_function",l??"",!0),this.nvim.call("coc#util#do_autocmd",["CocStatusChange"],!0)},null,this.disposables),_.on("InsertEnter",i=>{let r=this.buffers.getItem(i);r&&r.cancel()},null,this.disposables)}autoUpdate(e){let t=y.getDocument(e);return y.getConfiguration("coc.preferences",t).get("currentFunctionSymbolAutoUpdate",!1)}get labels(){return y.getConfiguration("suggest").get("completionItemKindLabels",{})}async getWorkspaceSymbols(e){this.handler.checkProvider("workspaceSymbols",null);let t=new p.CancellationTokenSource;return await I.getWorkspaceSymbols(e,t.token)}async resolveWorkspaceSymbol(e){var i;if((i=e.location)!=null&&i.uri)return e;let t=new p.CancellationTokenSource;return await I.resolveWorkspaceSymbol(e,t.token)}async getDocumentSymbols(e){if(!e){e=await this.nvim.call("bufnr",["%"]);let r=y.getDocument(e);if(!r||!r.attached)return}let t=this.buffers.getItem(e);if(!t)return;let i=await t.getSymbols();return i?b6(i):void 0}async getFunctionSymbol(e,t){let i=await this.getDocumentSymbols(e),r=this.nvim.createBuffer(e);if(!i||i.length===0)return r.setVar("coc_current_function","",!0),this.nvim.call("coc#util#do_autocmd",["CocStatusChange"],!0),"";i=i.filter(a=>["Class","Method","Function","Struct"].includes(a.kind));let o="",s=this.labels;for(let a of i.reverse())if(a.range&&Ft(t,a.range)==0&&!a.text.endsWith(") callback")){o=a.text;let l=s[a.kind.toLowerCase()];l&&(o=`${l} ${o}`);break}return o}async getCurrentFunctionSymbol(){let e=await this.nvim.call("bufnr",["%"]),t=y.getDocument(e);if(!t||!t.attached||!I.hasProvider("documentSymbol",t.textDocument))return;let i=await P.getCursorPosition();return await this.getFunctionSymbol(e,i)}async selectSymbolRange(e,t,i){let{doc:r}=await this.handler.getCurrentState();this.handler.checkProvider("documentSymbol",r.textDocument);let o;if(t)o=await P.getSelectedRange(t);else{let l=await P.getCursorPosition();o=M.create(l,l)}let s=await this.getDocumentSymbols(r.bufnr);if(!s||s.length===0){P.showWarningMessage("No symbols found");return}s=s.filter(l=>i.includes(l.kind));let a;for(let l of s.reverse())if(l.range&&!Me(l.range,o)&&ti(o,l.range)){a=l.range;break}if(e&&a){let{start:l,end:u}=a,c=r.getline(l.line+1),d=r.getline(u.line-1);a=M.create(l.line+1,c.match(/^\s*/)[0].length,u.line-1,d.length)}a?await P.selectRange(a):["v","V",""].includes(t)&&await this.nvim.command("normal! gv")}async showOutline(e){await this.outline.show(e)}async hideOutline(){await this.outline.hide()}hasOutline(e){return this.outline.has(e)}dispose(){this.outline.dispose(),this.buffers.dispose(),W(this.disposables)}}});function Rbe(n){return ci(n,["children","parent"])}function C6(n){return n==="supertypes"?"Super types":"Sub types"}var mu,bu,S6=D(()=>{"use strict";Dt();Pe();Se();J0();wp();te();Re();io();We();he();mu=class{constructor(e,t){this.nvim=e;this.handler=t;this.disposables=[];this.highlightWinids=new Set;this.loadConfiguration(),y.onDidChangeConfiguration(this.loadConfiguration,this,this.disposables),_.on("BufWinEnter",(i,r)=>{this.highlightWinids.has(r)&&(this.highlightWinids.delete(r),e.createWindow(r).clearMatchGroup(mu.rangesHighlight))},null,this.disposables),this.disposables.push(V.registerCommand(mu.commandId,async(i,r,o)=>{let{nvim:s}=this;await s.call("win_gotoid",[i]),await y.jumpTo(r.uri,r.range.start,o);let a=await s.window;a.clearMatchGroup(mu.rangesHighlight),a.highlightRanges(mu.rangesHighlight,[r.selectionRange],10,!0),this.highlightWinids.add(a.id)},null,!0))}loadConfiguration(e){if(!e||e.affectsConfiguration("typeHierarchy")){let t=y.getConfiguration("typeHierarchy",null);this.config={splitCommand:t.get("splitCommand"),openCommand:t.get("openCommand"),enableTooltip:t.get("enableTooltip")}}}createProvider(e,t,i){let r=new Aa(i,t,this.config,mu.commandId,e,o=>this.handler.getIcon(o),(o,s,a)=>this.getChildren(o,s,a));return r.addAction("Show Super Types",o=>{r.meta="supertypes";let s=[ci(o,["children","parent"])];r.reset(s)}),r.addAction("Show Sub Types",o=>{r.meta="subtypes";let s=[ci(o,["children","parent"])];r.reset(s)}),r}async getChildren(e,t,i){let r=[],o=Rbe(e);return t=="supertypes"?r=await I.provideTypeHierarchySupertypes(o,i):r=await I.provideTypeHierarchySubtypes(o,i),r}async prepare(e,t){return this.handler.checkProvider("typeHierarchy",e),await this.handler.withRequestToken("typeHierarchy",async i=>await I.prepareTypeHierarchy(e,t,i),!1)}async showTypeHierarchyTree(e){let{doc:t,position:i,winid:r}=await this.handler.getCurrentState();await t.synchronize();let o=await this.prepare(t.textDocument,i);if(re(o)){P.showWarningMessage("Unable to get TypeHierarchyItems at cursor position.");return}let s=this.createProvider(o,r,e),a=new So("types",{treeDataProvider:s});a.title=C6(e),s.onDidChangeTreeData(l=>{l||(a.title=C6(s.meta))}),a.onDidChangeVisibility(l=>{l.visible||s.dispose()}),this.disposables.push(a),await a.show(this.config.splitCommand)}dispose(){this.highlightWinids.clear(),W(this.disposables)}},bu=mu;bu.rangesHighlight="CocSelectedRange",bu.commandId="typeHierarchy.reveal"});var D6,lb,T6=D(()=>{"use strict";rt();D6=require("v8");Je();Dt();iw();nu();Se();xe();ha();cu();te();Yt();Ii();st();Xe();de();fe();We();he();lb=class{constructor(e){this.nvim=e;Object.defineProperty(P,"openLocalConfig",{get:()=>this.openLocalConfig.bind(this)}),V.register({id:"workspace.openLocation",execute:async(t,i,r)=>{t&&await e.call("win_gotoid",[t]),await y.jumpTo(i.uri,i.range.start,r)}},!0),V.register({id:"workspace.undo",execute:async()=>{await y.files.undoWorkspaceEdit()}},!1,"Undo previous this.workspace edit"),V.register({id:"workspace.redo",execute:async()=>{await y.files.redoWorkspaceEdit()}},!1,"Redo previous this.workspace edit"),V.register({id:"workspace.inspectEdit",execute:async()=>{await y.files.inspectEdit()}},!1,"Inspect previous this.workspace edit in new tab"),V.register({id:"workspace.renameCurrentFile",execute:async()=>{await this.renameCurrent()}},!1,"change current filename to a new name and reload it."),V.register({id:"document.checkBuffer",execute:async()=>{await this.bufferCheck()}},!1,"Check providers for current buffer."),V.register({id:"document.echoFiletype",execute:async()=>{let t=await e.call("bufnr","%"),i=y.getAttachedDocument(t);await P.echoLines([i.filetype])}},!1,"echo the mapped filetype of the current buffer"),V.register({id:"workspace.workspaceFolders",execute:async()=>{let i=y.workspaceFolders.map(r=>O.parse(r.uri).fsPath);await P.echoLines(i)}},!1,"show opened workspaceFolders."),V.register({id:"workspace.writeHeapSnapshot",execute:async()=>{let t=R.join(Pt.homedir(),`${me()}-${process.pid}.heapsnapshot`);return(0,D6.writeHeapSnapshot)(t),P.showInformationMessage(`Create heapdump at: ${t}`),t}},!1,"Generates a snapshot of the current V8 heap and writes it to a JSON file."),V.register({id:"workspace.showOutput",execute:async t=>{t||(t=await P.showQuickPick(y.channelNames,{title:"Choose output name"})),P.showOutputChannel(oe(t))}},!1,"open output buffer to show output from languageservers or extensions."),V.register({id:"workspace.clearWatchman",execute:async()=>{let t=await P.runTerminalCommand("watchman watch-del-all");return t.success&&P.showInformationMessage("Cleared watchman watching directories."),t.success}},!1,"run watch-del-all for watchman to free up memory.")}async openLog(){let e=Yb();await y.jumpTo(O.file(e).toString())}async openLocalConfig(){let e=await this.nvim.call("expand",["%:p"]),t=await this.nvim.eval("&filetype");if(!e||!R.isAbsolute(e)){P.showWarningMessage("Current buffer doesn't have valid file path.");return}let i=y.getWorkspaceFolder(O.file(e).toString());if(!i){let s=y.initialConfiguration.get("workspace"),a=Ie(s.rootPatterns,[]),l=Ie(s.ignoredFiletypes,[]),u;l.includes(t)&&(u=`Filetype '${t}' is ignored for workspace folder resolve.`),u||(u=`Can't resolve workspace folder for file '${e}, consider create one of ${a.join(", ")} in your project root.'.`),P.showWarningMessage(u);return}let r=O.parse(i.uri).fsPath,o=R.join(r,".vim");if(!F.existsSync(o)){if(!await P.showPrompt(`Would you like to create folder'${r}/.vim'?`))return;F.mkdirSync(o)}await y.jumpTo(O.file(R.join(o,fg)))}async renameCurrent(){let{nvim:e}=this,t=await e.call("expand",["%:p"]),i=await e.callAsync("coc#util#with_callback",["input",["New path: ",t,"file"]]);i=i?i.trim():null,!(i===t||!i)&&(t.toLowerCase()!=i.toLowerCase()&&F.existsSync(i)&&!await P.showPrompt(`${i} exists, overwrite?`)||await y.renameFile(t,i,{overwrite:!0}))}addWorkspaceFolder(e){if(!$e(e))throw TypeError("folder should be string");if(e=y.expand(e),!hc(e))throw MW(e);y.workspaceFolderControl.addWorkspaceFolder(e,!0)}async bufferCheck(){let e=await y.document;if(!e.attached){await P.showDialog({title:"Buffer check result",content:`Document not attached, ${e.notAttachReason}`,highlight:"WarningMsg"});return}let t=new zi;t.addLine("Provider state","Title"),t.addLine("");for(let i of Object.values(jt)){if(i==="onTypeEdit")continue;let r=I.hasProvider(i,e.textDocument);t.addTexts([{text:"-",hlGroup:"Comment"},{text:" "},r?{text:"\u2713",hlGroup:"CocListFgGreen"}:{text:"\u2717",hlGroup:"CocListFgRed"},{text:" "},{text:i,hlGroup:r?"Normal":"CocFadeOut"}])}await P.showDialog({title:"Buffer check result",content:t.content,highlights:t.highlights})}async doAutocmd(e,t){await y.autocmds.doAutocmd(e,t)}async getConfiguration(e){let t=await y.document;return y.getConfiguration(e,t?t.uri:void 0)}getRootPatterns(e){let t=y.getDocument(e);return t?{buffer:y.workspaceFolderControl.getRootPatterns(t,0),server:y.workspaceFolderControl.getRootPatterns(t,1)||[],global:y.workspaceFolderControl.getRootPatterns(t,2)}:null}async ensureDocument(){let e=await y.document;return e&&e.attached}async doKeymap(e,t=""){return await y.keymaps.doKeymap(e,t)}async snippetCheck(e,t){return!!(t&&pi.jumpable()||e&&await Promise.resolve(Ht.manager.call("coc-snippets","expandable",[])))}async showInfo(){let e=[],t=y.version+"-b11a93ba 2022-12-25 15:19:13 +0800";e.push("## versions"),e.push("");let r=(await this.nvim.call("execute",["version"])).trim().split(/\r?\n/,2)[0].replace(/\(.*\)/,"").trim();e.push("vim version: "+r+`${y.isVim?" "+y.env.version:""}`),e.push("node version: "+process.version),e.push("coc.nvim version: "+t),e.push("coc.nvim directory: "+R.dirname(__dirname)),e.push("term: "+(process.env.TERM_PROGRAM||process.env.TERM)),e.push("platform: "+process.platform),e.push(""),e.push("## Log of coc.nvim"),e.push("");let o=Yb(),s=jb();if(F.existsSync(o)){let l=F.readFileSync(o,{encoding:"utf8"});e.push(...l.split(/\r?\n/).map(u=>s(u)))}await this.nvim.command("vnew +setl\\ buftype=nofile\\ bufhidden=wipe\\ nobuflisted"),await(await this.nvim.buffer).setLines(e,{start:0,end:-1,strictIndexing:!1})}}});var _be,ub,k6=D(()=>{"use strict";ae();Dt();Pe();Se();xe();te();im();Be();U();wr();We();he();FV();MV();AV();qV();WV();YV();ZV();JV();$V();XV();GV();QV();VV();s6();a6();l6();h6();g6();x6();S6();T6();_be=Z("Handler"),ub=class{constructor(e){this.nvim=e;this.disposables=[];_.on(["CursorMoved","CursorMovedI","InsertEnter","InsertSnippet","InsertLeave"],()=>{this.requestTokenSource&&(this.requestTokenSource.cancel(),this.requestTokenSource=null)},null,this.disposables),this.fold=new Hm(e,this),this.links=new Um(e,this),this.codeLens=new Mm(e),this.colors=new Am(e,this),this.format=new Bm(e,this),this.symbols=new ab(e,this),this.refactor=new Qm(e,this),this.hover=new Ym(e,this),this.locations=new Xm(e,this),this.signature=new nb(e,this),this.rename=new Vm(e,this),this.workspace=new lb(e),this.codeActions=new Lm(e,this),this.commands=new Nm(e),this.callHierarchy=new pu(e,this),this.typeHierarchy=new bu(e,this),this.documentHighlighter=new qm(e,this),this.semanticHighlighter=new ib(e),this.selectionRange=new eb(e,this),this.linkedEditingHandler=new $m(e,this),this.inlayHintHandler=new Jm(e,this),this.disposables.push({dispose:()=>{this.callHierarchy.dispose(),this.typeHierarchy.dispose(),this.codeLens.dispose(),this.links.dispose(),this.refactor.dispose(),this.signature.dispose(),this.symbols.dispose(),this.hover.dispose(),this.colors.dispose(),this.documentHighlighter.dispose(),this.semanticHighlighter.dispose()}}),this.registerCommands()}registerCommands(){V.register({id:"document.renameCurrentWord",execute:async()=>{let e=await y.document,t=await this.rename.getWordEdit(),i=uU(e.uri,Ue(t));if(!i)return P.showWarningMessage("Invalid position");await V.executeCommand("editor.action.addRanges",i)}},!1,"rename word under cursor in current buffer by multiple cursors."),V.register({id:["workbench.action.reloadWindow","editor.action.restart"],execute:()=>{this.nvim.command("CocRestart",!0)}},!0),this.register("vscode.open",e=>{this.nvim.call("coc#ui#open_url",e.toString(),!0)}),this.register("editor.action.doCodeAction",async e=>{await this.codeActions.applyCodeAction(e)}),this.register("editor.action.triggerParameterHints",async()=>{await this.signature.triggerSignatureHelp()}),this.register("editor.action.showReferences",async(e,t,i)=>{await y.jumpTo(e,t),await y.showLocations(i)}),this.register("editor.action.rename",async(e,t,i)=>{await y.jumpTo(e,t),await this.rename.rename(i)}),this.register("editor.action.format",async()=>{await this.format.formatCurrentBuffer()}),this.register("editor.action.showRefactor",async e=>{let t=e.filter(i=>Ke.is(i));return await this.refactor.fromLocations(t)})}register(e,t){this.disposables.push(V.registerCommand(e,t,null,!0))}get requestStatusItem(){return this._requestStatusItem?this._requestStatusItem:(this._requestStatusItem=P.createStatusBarItem(0,{progress:!0}),this._requestStatusItem)}get labels(){return y.initialConfiguration.get("suggest.completionItemKindLabels",{})}get uri(){var e;return(e=P.activeTextEditor)==null?void 0:e.document.uri}async getCurrentState(){let{nvim:e}=this,[t,[i,r],o,s]=await e.eval("[bufnr('%'),coc#cursor#position(),win_getid(),mode()]");return{doc:y.getAttachedDocument(t),mode:s,position:Q.create(i,r),winid:o}}addDisposable(e){this.disposables.push(e)}checkProvider(e,t){if(!I.hasProvider(e,t))throw new Error(`${e} provider not found for current buffer, your language server doesn't support it.`)}async withRequestToken(e,t,i){this.requestTokenSource&&(this.requestTokenSource.cancel(),this.requestTokenSource.dispose()),this.requestTimer&&clearTimeout(this.requestTimer);let r=this.requestStatusItem;this.requestTokenSource=new p.CancellationTokenSource;let{token:o}=this.requestTokenSource;o.onCancellationRequested(()=>{r.text=`${e} request canceled`,r.isProgress=!1,this.requestTimer=setTimeout(()=>{r.hide()},500)}),r.isProgress=!0,r.text=`requesting ${e}`,r.show();let s;try{s=await Promise.resolve(t(o))}catch(a){_be.error(`Error on request ${e}`,a),this.nvim.errWriteLine(`Error on ${e}: ${a}`)}return this.requestTokenSource&&(this.requestTokenSource.dispose(),this.requestTokenSource=void 0),o.isCancellationRequested?null:(r.hide(),i&&(!s||Array.isArray(s)&&s.length==0)?(P.showWarningMessage(`${e} not found`),null):s)}getIcon(e){let{labels:t}=this,i=ks(e),r=typeof t.default=="string"?t.default:i[0].toLowerCase(),o=i=="Unknown"?"":t[i[0].toLowerCase()+i.slice(1)];return(!o||typeof o!="string")&&(o=r),{text:o,hlGroup:i=="Unknown"?"CocSymbolDefault":`CocSymbol${i}`}}async getCodeActions(e,t,i){return(await this.codeActions.getCodeActions(e,t,i)).filter(o=>!o.disabled)}async applyCodeAction(e){await this.codeActions.applyCodeAction(e)}async hasProvider(e){let t=await this.nvim.call("bufnr","%"),i=y.getDocument(t);return i?I.hasProvider(e,i.textDocument):!1}dispose(){this.requestTimer&&clearTimeout(this.requestTimer),W(this.disposables)}}});var Ebe,cb,P6=D(()=>{"use strict";ae();Dt();TV();uu();iv();RV();Hc();Pe();nu();k6();WC();xe();um();cu();te();We();he();Ebe=Z("plugin"),cb=class{constructor(e){this.nvim=e;this.ready=!1;this.initialized=!1;this.actions=new Map;this.disposables=[];Object.defineProperty(P,"workspace",{get:()=>y}),Object.defineProperty(y,"nvim",{get:()=>this.nvim}),Object.defineProperty(P,"nvim",{get:()=>this.nvim}),Object.defineProperty(P,"cursors",{get:()=>this.cursors}),Object.defineProperty(V,"nvim",{get:()=>this.nvim}),this.cursors=new Im(e),qi.init(e),this.addAction("checkJsonExtension",()=>{Ht.has("coc-json")||P.showInformationMessage("Run :CocInstall coc-json for json intellisense")}),this.addAction("rootPatterns",t=>this.handler.workspace.getRootPatterns(t)),this.addAction("ensureDocument",()=>this.handler.workspace.ensureDocument()),this.addAction("addWorkspaceFolder",t=>this.handler.workspace.addWorkspaceFolder(t)),this.addAction("getConfig",t=>this.handler.workspace.getConfiguration(t)),this.addAction("doAutocmd",(t,...i)=>this.handler.workspace.doAutocmd(t,i)),this.addAction("openLog",()=>this.handler.workspace.openLog()),this.addAction("attach",()=>y.attach()),this.addAction("detach",()=>y.detach()),this.addAction("doKeymap",(t,i)=>this.handler.workspace.doKeymap(t,i)),this.addAction("registerExtensions",(...t)=>Ht.manager.loadExtension(t),"registExtensions"),this.addAction("snippetCheck",(t,i)=>this.handler.workspace.snippetCheck(t,i)),this.addAction("snippetInsert",(t,i,r,o)=>pi.insertSnippet(i,!0,t,r,o)),this.addAction("snippetNext",()=>pi.nextPlaceholder()),this.addAction("snippetPrev",()=>pi.previousPlaceholder()),this.addAction("snippetCancel",()=>pi.cancel()),this.addAction("openLocalConfig",()=>this.handler.workspace.openLocalConfig()),this.addAction("bufferCheck",()=>this.handler.workspace.bufferCheck()),this.addAction("showInfo",()=>this.handler.workspace.showInfo()),this.addAction("hasProvider",t=>this.handler.hasProvider(t)),this.addAction("cursorsSelect",(t,i,r)=>this.cursors.select(t,i,r)),this.addAction("fillDiagnostics",t=>ui.setLocationlist(t)),this.addAction("commandList",()=>this.handler.commands.getCommandList()),this.addAction("selectSymbolRange",(t,i,r)=>this.handler.symbols.selectSymbolRange(t,i,r)),this.addAction("openList",(...t)=>qi.start(t)),this.addAction("listNames",()=>qi.names),this.addAction("listDescriptions",()=>qi.descriptions),this.addAction("listLoadItems",t=>qi.loadItems(t)),this.addAction("listResume",t=>qi.resume(t)),this.addAction("listCancel",()=>qi.cancel(!0)),this.addAction("listPrev",t=>qi.previous(t)),this.addAction("listNext",t=>qi.next(t)),this.addAction("listFirst",t=>qi.first(t)),this.addAction("listLast",t=>qi.last(t)),this.addAction("sendRequest",(t,i,r)=>xn.sendRequest(t,i,r)),this.addAction("sendNotification",(t,i,r)=>xn.sendNotification(t,i,r)),this.addAction("registerNotification",(t,i)=>xn.registerNotification(t,i),"registNotification"),this.addAction("updateConfig",(t,i)=>y.configurations.updateMemoryConfig({[t]:i})),this.addAction("links",()=>this.handler.links.getLinks()),this.addAction("openLink",()=>this.handler.links.openCurrentLink()),this.addAction("pickColor",()=>this.handler.colors.pickColor()),this.addAction("colorPresentation",()=>this.handler.colors.pickPresentation()),this.addAction("highlight",()=>this.handler.documentHighlighter.highlight()),this.addAction("fold",t=>this.handler.fold.fold(t)),this.addAction("startCompletion",t=>Tm.startCompletion(t)),this.addAction("sourceStat",()=>Pi.sourceStats()),this.addAction("refreshSource",t=>Pi.refresh(t)),this.addAction("toggleSource",t=>Pi.toggleSource(t)),this.addAction("diagnosticRefresh",t=>ui.refresh(t)),this.addAction("diagnosticInfo",()=>ui.echoCurrentMessage()),this.addAction("diagnosticToggle",t=>ui.toggleDiagnostic(t)),this.addAction("diagnosticToggleBuffer",(t,i)=>ui.toggleDiagnosticBuffer(t,i)),this.addAction("diagnosticNext",t=>ui.jumpNext(t)),this.addAction("diagnosticPrevious",t=>ui.jumpPrevious(t)),this.addAction("diagnosticPreview",()=>ui.preview()),this.addAction("diagnosticList",()=>ui.getDiagnosticList()),this.addAction("findLocations",(t,i,r,o)=>this.handler.locations.findLocations(t,i,r,o)),this.addAction("getTagList",()=>this.handler.locations.getTagList()),this.addAction("definitions",()=>this.handler.locations.definitions()),this.addAction("declarations",()=>this.handler.locations.declarations()),this.addAction("implementations",()=>this.handler.locations.implementations()),this.addAction("typeDefinitions",()=>this.handler.locations.typeDefinitions()),this.addAction("references",t=>this.handler.locations.references(t)),this.addAction("jumpUsed",t=>this.handler.locations.gotoReferences(t,!1)),this.addAction("jumpDefinition",t=>this.handler.locations.gotoDefinition(t)),this.addAction("jumpReferences",t=>this.handler.locations.gotoReferences(t)),this.addAction("jumpTypeDefinition",t=>this.handler.locations.gotoTypeDefinition(t)),this.addAction("jumpDeclaration",t=>this.handler.locations.gotoDeclaration(t)),this.addAction("jumpImplementation",t=>this.handler.locations.gotoImplementation(t)),this.addAction("doHover",t=>this.handler.hover.onHover(t)),this.addAction("definitionHover",t=>this.handler.hover.definitionHover(t)),this.addAction("getHover",t=>this.handler.hover.getHover(t)),this.addAction("showSignatureHelp",()=>this.handler.signature.triggerSignatureHelp()),this.addAction("documentSymbols",t=>this.handler.symbols.getDocumentSymbols(t)),this.addAction("symbolRanges",()=>this.handler.documentHighlighter.getSymbolsRanges()),this.addAction("selectionRanges",()=>this.handler.selectionRange.getSelectionRanges()),this.addAction("rangeSelect",(t,i)=>this.handler.selectionRange.selectRange(t,i)),this.addAction("rename",t=>this.handler.rename.rename(t)),this.addAction("getWorkspaceSymbols",t=>this.handler.symbols.getWorkspaceSymbols(t)),this.addAction("resolveWorkspaceSymbol",t=>this.handler.symbols.resolveWorkspaceSymbol(t)),this.addAction("formatSelected",t=>this.handler.format.formatCurrentRange(t)),this.addAction("format",()=>this.handler.format.formatCurrentBuffer()),this.addAction("commands",()=>V.commandList),this.addAction("services",()=>xn.getServiceStats()),this.addAction("toggleService",t=>xn.toggle(t)),this.addAction("codeAction",(t,i,r)=>this.handler.codeActions.doCodeAction(t,i,r)),this.addAction("organizeImport",()=>this.handler.codeActions.organizeImport()),this.addAction("fixAll",()=>this.handler.codeActions.doCodeAction(null,[ri.SourceFixAll])),this.addAction("doCodeAction",t=>this.handler.codeActions.applyCodeAction(t)),this.addAction("codeActions",(t,i)=>this.handler.codeActions.getCurrentCodeActions(t,i)),this.addAction("quickfixes",t=>this.handler.codeActions.getCurrentCodeActions(t,[ri.QuickFix])),this.addAction("codeLensAction",()=>this.handler.codeLens.doAction()),this.addAction("doQuickfix",()=>this.handler.codeActions.doQuickfix()),this.addAction("search",(...t)=>this.handler.refactor.search(t)),this.addAction("saveRefactor",t=>this.handler.refactor.save(t)),this.addAction("refactor",()=>this.handler.refactor.doRefactor()),this.addAction("runCommand",(...t)=>this.handler.commands.runCommand(...t)),this.addAction("repeatCommand",()=>this.handler.commands.repeat()),this.addAction("installExtensions",(...t)=>Ht.installExtensions(t)),this.addAction("updateExtensions",t=>Ht.updateExtensions(t)),this.addAction("extensionStats",()=>Ht.getExtensionStates()),this.addAction("loadedExtensions",()=>Ht.manager.loadedExtensions),this.addAction("watchExtension",t=>Ht.manager.watchExtension(t)),this.addAction("activeExtension",t=>Ht.manager.activate(t)),this.addAction("deactivateExtension",t=>Ht.manager.deactivate(t)),this.addAction("reloadExtension",t=>Ht.manager.reloadExtension(t)),this.addAction("toggleExtension",t=>Ht.manager.toggleExtension(t)),this.addAction("uninstallExtension",(...t)=>Ht.manager.uninstallExtensions(t)),this.addAction("getCurrentFunctionSymbol",()=>this.handler.symbols.getCurrentFunctionSymbol()),this.addAction("showOutline",t=>this.handler.symbols.showOutline(t)),this.addAction("hideOutline",()=>this.handler.symbols.hideOutline()),this.addAction("getWordEdit",()=>this.handler.rename.getWordEdit()),this.addAction("addCommand",t=>this.handler.commands.addVimCommand(t)),this.addAction("addRanges",t=>this.cursors.addRanges(t)),this.addAction("currentWorkspacePath",()=>y.rootPath),this.addAction("selectCurrentPlaceholder",t=>pi.selectCurrentPlaceholder(!!t)),this.addAction("codeActionRange",(t,i,r)=>this.handler.codeActions.codeActionRange(t,i,r)),this.addAction("incomingCalls",t=>this.handler.callHierarchy.getIncoming(t)),this.addAction("outgoingCalls",t=>this.handler.callHierarchy.getOutgoing(t)),this.addAction("showIncomingCalls",()=>this.handler.callHierarchy.showCallHierarchyTree("incoming")),this.addAction("showOutgoingCalls",()=>this.handler.callHierarchy.showCallHierarchyTree("outgoing")),this.addAction("showSuperTypes",()=>this.handler.typeHierarchy.showTypeHierarchyTree("supertypes")),this.addAction("showSubTypes",()=>this.handler.typeHierarchy.showTypeHierarchyTree("subtypes")),this.addAction("inspectSemanticToken",()=>this.handler.semanticHighlighter.inspectSemanticToken()),this.addAction("semanticHighlight",()=>this.handler.semanticHighlighter.highlightCurrent()),this.addAction("showSemanticHighlightInfo",()=>this.handler.semanticHighlighter.showHighlightInfo())}get workspace(){return y}get completion(){return Tm}addAction(e,t,i){if(this.actions.has(e))throw new Error(`Action ${e} already exists`);this.actions.set(e,t),i&&this.actions.set(i,t)}async init(e){if(this.initialized)return;this.initialized=!0;let{nvim:t}=this;await Ht.init(e),await y.init(P),y.registerTextDocumentContentProvider("output",os.getProvider(t)),t.setVar("coc_workspace_initialized",!0,!0),pi.init(),xn.init(),Pi.init(),Tm.init(),ui.init(),this.handler=new ub(t),this.disposables.push(this.handler),qi.registerLists(),await Ht.activateExtensions(),y.configurations.flushConfigurations(),t.pauseNotification(),t.setVar("coc_service_initialized",1,!0),t.call("coc#util#do_autocmd",["CocNvimInit"],!0),t.resumeNotification(!1,!0),Ebe.info(`coc.nvim initialized with node: ${process.version} after`,Date.now()-pe(global.__starttime,Date.now())),this.ready=!0,await _.fire("ready",[])}get isReady(){return this.ready}hasAction(e){return this.actions.has(e)}async cocAction(e,...t){let i=this.actions.get(e);if(!i)throw new Error(`Action "${e}" not exist`);return await Promise.resolve(i.apply(null,t))}getHandler(){return this.handler}dispose(){W(this.disposables),Ht.dispose(),qi.dispose(),y.dispose(),os.dispose(),P.dispose(),Pi.dispose(),xn.dispose(),pi.dispose(),V.dispose(),Tm.dispose(),ui.dispose()}}});var sI={};Ls(sI,{default:()=>Lbe,pathReplace:()=>_6});function _6(n){if(xt(n)){let e=O.file;O.file=t=>(t=t.replace(/\\/g,"/"),Object.keys(n).forEach(i=>t=t.replace(new RegExp("^"+i),n[i])),e(t))}}var R6,Ao,Ibe,rI,oI,Lbe,aI=D(()=>{"use strict";R6=Lr(IW());Je();Pe();xe();P6();Yt();Xe();de();fe();E0();Ao=Z("attach"),Ibe=["installExtensions","updateExtensions"],rI=sr.parse(bl),oI=[];Lbe=(n,e=!1)=>{let t=(0,R6.attach)(n,Z("node-client"),e);t.setVar("coc_process_pid",process.pid,!0),t.setClientInfo("coc",{major:rI.major,minor:rI.minor,patch:rI.patch},"remote",{},{});let i=new cb(t),r=_.on("ready",()=>{r.dispose();for(let[s,a]of oI)i.cocAction(s,...a).catch(l=>{console.error(`Error on notification "${s}": ${l}`),Ao.error(`Error on notification ${s}`,l)});oI=[]});t.on("notification",async(s,a)=>{switch(s){case"VimEnter":{_6(a[0]),await i.init(a[1]);break}case"Log":{Ao.debug("Vim log",...a);break}case"TaskExit":case"TaskStderr":case"TaskStdout":case"GlobalChange":case"PromptInsert":case"InputChar":case"MenuInput":case"OptionSet":case"PromptKeyPress":case"FloatBtnClick":case"CompleteStop":case"PumInsert":Ao.trace("Event: ",s,...a),await _.fire(s,a);break;case"CocAutocmd":Ao.trace("Notification autocmd:",...a),await _.fire(a[0],a.slice(1));break;case"redraw":break;default:try{if(Ao.info("receive notification:",s,a),!i.isReady){oI.push([s,a]);return}await i.cocAction(s,...a)}catch(l){console.error(`Error on notification "${s}": ${yr(l)}`),Ao.error(`Error on notification ${s}`,l)}}});let o=YC("Request",3e3);return t.on("request",async(s,a,l)=>{o.start(s);try{if(_.requesting=!0,s=="CocAutocmd")Ao.trace("Request autocmd:",...a),await _.fire(a[0],a.slice(1)),l.send(void 0);else if(!i.isReady&&!Ibe.includes(s))Ao.warn(`Plugin not ready on request "${s}"`,a),l.send("Plugin not ready",!0);else{Ao.info("Request action:",s,a);let u=await i.cocAction(s,...a);l.send(u)}_.requesting=!1}catch(u){_.requesting=!1,l.send(yr(u),!0),Ao.error("Request error:",s,a,u)}o.stop()}),i}});if(global.__isMain){Object.defineProperty(console,"log",{value(){e&&e.info(...arguments)}});let{createLogger:n}=(xe(),No(dD)),e=n("server");process.on("uncaughtException",function(i){let r="Uncaught exception: "+i.message;console.error(r),e.error("uncaughtException",i.stack)}),process.on("unhandledRejection",function(i,r){if(i instanceof Error)if(typeof i.code=="number"){let o="Unhandled response error "+i.code+" from language server: "+i.message;i.data!=null?console.error(o,i.data):console.error(o)}else console.error("UnhandledRejection: "+i.message+` +`+i.stack);else console.error("UnhandledRejection: "+i);e.error("unhandledRejection ",r,i)});let t=(aI(),No(sI)).default;t({reader:process.stdin,writer:process.stdout})}else{let n=R0(),e=(xe(),No(dD)).logger,t=(aI(),No(sI)).default;module.exports={attach:t,exports:n,logger:e,loadExtension:(i,r)=>n.extensions.manager.load(i,r)}} /*! * bytes * Copyright(c) 2012-2014 TJ Holowaychuk @@ -68544,25 +287,4 @@ process.on("unhandledRejection", function(reason, p) { * MIT Licensed */ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -/** - * event-lite.js - Light-weight EventEmitter (less than 1KB when gzipped) - * - * @copyright Yusuke Kawasaki - * @license MIT - * @constructor - * @see https://github.com/kawanet/event-lite - * @see http://kawanet.github.io/event-lite/EventLite.html - * @example - * var EventLite = require("event-lite"); - * - * function MyClass() {...} // your class - * - * EventLite.mixin(MyClass.prototype); // import event methods - * - * var obj = new MyClass(); - * obj.on("foo", function() {...}); // add event listener - * obj.once("bar", function() {...}); // add one-time event listener - * obj.emit("foo"); // dispatch event - * obj.emit("bar"); // dispatch another event - * obj.off("foo"); // remove event listener - */ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ diff --git a/vim-config/plugins/coc.nvim/data/schema.json b/vim-config/plugins/coc.nvim/data/schema.json index a4ad1bd6..eb93ec1d 100644 --- a/vim-config/plugins/coc.nvim/data/schema.json +++ b/vim-config/plugins/coc.nvim/data/schema.json @@ -1,9 +1,8 @@ { - "$schema": "http://json-schema.org/draft-07/schema#", "description": "Configuration file for coc.nvim", "additionalProperties": false, "definitions": { - "float": { + "floatConfig": { "type": "object", "properties": { "border": { @@ -11,6 +10,11 @@ "default": false, "description": "Set to true to use borders." }, + "rounded": { + "type": "boolean", + "default": false, + "description": "Use rounded borders when border is true." + }, "highlight": { "type": "string", "default": "CocFloating", @@ -59,169 +63,246 @@ } } }, - "languageServerBase": { + "languageserver.enable": { + "type": "boolean", + "description": "Enable the languageserver, restart coc.nvim required after change.", + "default": true + }, + "languageserver.filetypes": { + "type": "array", + "default": [], + "description": "Supported filetypes, add * in array for all filetypes.", + "items": { + "type": "string" + } + }, + "languageserver.cwd": { + "type": "string", + "default": "", + "description": "Working directory of languageserver, absolute path or relative to workspace folder, use workspace root by default" + }, + "languageserver.settings": { + "type": "object", + "default": {}, + "description": "Settings of languageserver" + }, + "languageserver.initializationOptions": { + "type": "object", + "default": {}, + "description": "initializationOptions passed to languageserver" + }, + "languageserver.env": { + "type": "object", + "default": null, + "description": "Environment variables for child process." + }, + "languageserver.stdioEncoding": { + "type": "string", + "default": "utf8", + "description": "Encoding used for stdio of child process." + }, + "languageserver.rootPatterns": { + "type": "array", + "default": [], + "description": "Root patterns used to resolve rootPath from current file, default to workspace root", + "items": { + "type": "string" + } + }, + "languageserver.requireRootPattern": { + "type": "boolean", + "default": false, + "description": "If true, doesn't start server when root pattern not found." + }, + "languageserver.ignoredRootPaths": { + "type": "array", + "default": [], + "description": "Absolute root paths that language server should not use as rootPath, higher priority than rootPatterns.", + "items": { + "type": "string" + } + }, + "languageserver.additionalSchemes": { + "type": "array", + "default": [], + "description": "Additional URI schemes, default schemes including file & untitled.", + "items": { + "type": "string" + } + }, + "languageserver.revealOutputChannelOn": { + "type": "string", + "default": "never", + "description": "Configure message level to show the output channel buffer", + "enum": ["info", "warn", "error", "never"] + }, + "languageserver.progressOnInitialization": { + "type": "boolean", + "default": false, + "description": "Enable progress report on languageserver initialize." + }, + "languageserver.trace.server": { + "type": "string", + "default": "off", + "enum": ["off", "messages", "verbose"], + "description": "Trace level of communication between server and client" + }, + "languageserver.trace.server.verbosity": { + "type": "string", + "default": "off", + "enum": ["off", "messages", "verbose"], + "description": "Trace level of communication between server and client" + }, + "languageserver.trace.server.format": { + "type": "string", + "default": "text", + "enum": ["text", "json"], + "description": "Text format of trace messages." + }, + "languageserver.disableDynamicRegister": { + "type": "boolean", + "default": false, + "description": "Disable dynamic registerCapability feature for this languageserver to avoid duplicate feature registration." + }, + "languageserver.disableSnippetCompletion": { + "type": "boolean", + "default": false, + "description": "Disable completion snippet feature for this languageserver, the languageserver may not respect it." + }, + "languageserver.disabledFeatures": { + "type": "array", + "default": [], + "description": "Disabled features for this languageserver.", + "items": { + "type": "string", + "enum": [ + "completion", + "configuration", + "workspaceFolders", + "diagnostics", + "willSave", + "willSaveUntil", + "didSaveTextDocument", + "fileSystemWatcher", + "hover", + "signatureHelp", + "definition", + "references", + "documentHighlight", + "documentSymbol", + "workspaceSymbol", + "codeAction", + "codeLens", + "formatting", + "documentFormatting", + "documentRangeFormatting", + "documentOnTypeFormatting", + "rename", + "documentLink", + "executeCommand", + "pullConfiguration", + "typeDefinition", + "implementation", + "declaration", + "color", + "foldingRange", + "selectionRange", + "progress", + "callHierarchy", + "linkedEditing", + "inlayHint", + "inlineValue", + "typeHierarchy", + "pullDiagnostic", + "fileEvents", + "semanticTokens" + ] + } + }, + "languageserver.formatterPriority": { + "type": "number", + "default": 0, + "description": "Priority of this languageserver's formatter." + }, + "languageServerSocket": { "type": "object", + "required": ["port", "filetypes"], + "additionalProperties": false, "properties": { - "enable": { - "type": "boolean", - "default": true + "port": { + "type": "integer", + "description": "Port number of socket server" }, - "cwd": { + "host": { "type": "string", - "default": "", - "description": "Working directory of languageserver, absolute path or relative to workspace folder, use workspace root by default" - }, - "disableDynamicRegister": { - "type": "boolean", - "default": false, - "description": "Disable dynamic registerCapability feature for this languageserver to avoid duplicated feature regstration." + "default": "127.0.0.1", + "description": "Host of server" }, - "disableWorkspaceFolders": { - "type": "boolean", - "default": false, - "description": "Disable workspaceFolders feature for this languageserver." + "enable": { + "$ref": "#/definitions/languageserver.enable" }, "disableSnippetCompletion": { - "type": "boolean", - "default": false, - "description": "Disable completion snippet feature for this languageserver, the languageserver may not respect it." + "$ref": "#/definitions/languageserver.disableSnippetCompletion" }, - "disableDiagnostics": { - "type": "boolean", - "default": false, - "description": "Disable handle diagnostics for this languageserver." + "disableDynamicRegister": { + "$ref": "#/definitions/languageserver.disableDynamicRegister" }, - "disableCompletion": { - "type": "boolean", - "default": false, - "description": "Disable completion feature for this languageserver." + "disabledFeatures": { + "$ref": "#/definitions/languageserver.disabledFeatures" }, "formatterPriority": { - "type": "number", - "default": 0, - "description": "Priority of this languageserver's fomatter." - }, - "env": { - "type": "object", - "default": null, - "description": "Environment variables for child process." - }, - "stdioEncoding": { - "type": "string", - "default": "utf8", - "description": "Encoding used for stdio of child process." + "$ref": "#/definitions/languageserver.formatterPriority" }, "rootPatterns": { - "type": "array", - "default": [], - "description": "Root patterns used to resolve rootPath from current file, default to workspace root", - "items": { - "type": "string" - } + "$ref": "#/definitions/languageserver.rootPatterns" }, "requireRootPattern": { - "type": "boolean", - "default": false, - "description": "If true, doesn't start server when root pattern not found." + "$ref": "#/definitions/languageserver.requireRootPattern" }, "ignoredRootPaths": { - "type": "array", - "default": [], - "description": "Absolute root paths that language server should not use as rootPath, higher priority than rootPatterns.", - "items": { - "type": "string" - } + "$ref": "#/definitions/languageserver.ignoredRootPaths" }, "filetypes": { - "type": "array", - "default": [], - "description": "Supported filetypes, add * in array for all filetypes.", - "items": { - "type": "string" - } + "$ref": "#/definitions/languageserver.filetypes" }, "additionalSchemes": { - "type": "array", - "default": [], - "description": "Additional uri schemes, default schemes including file & untitled.", - "items": { - "type": "string" - } + "$ref": "#/definitions/languageserver.additionalSchemes" }, "revealOutputChannelOn": { - "type": "string", - "default": "never", - "description": "Configure message level to show the output channel buffer", - "enum": ["info", "warn", "error", "never"] + "$ref": "#/definitions/languageserver.revealOutputChannelOn" }, "progressOnInitialization": { - "type": "boolean", - "default": true, - "description": "Enable progress report on languageserver initialize." + "$ref": "#/definitions/languageserver.progressOnInitialization" }, "initializationOptions": { - "type": "object", - "default": {}, - "description": "initializationOptions passed to languageserver" + "$ref": "#/definitions/languageserver.initializationOptions" }, "settings": { - "type": "object", - "default": {}, - "description": "Settings of languageserver" + "$ref": "#/definitions/languageserver.settings" + }, + "stdioEncoding": { + "$ref": "#/definitions/languageserver.stdioEncoding" }, "trace.server": { - "type": "string", - "default": "off", - "enum": ["off", "messages", "verbose"], - "description": "Trace level of communication between server and client" - } - } - }, - "languageServerSocket": { - "type": "object", - "allOf": [{ "$ref": "#/definitions/languageServerBase" }], - "required": ["port", "filetypes"], - "additionalProperties": false, - "properties": { - "port": { - "type": "integer", - "description": "Port number of socket server" + "$ref": "#/definitions/languageserver.trace.server" }, - "host": { - "type": "string", - "default": "127.0.0.1", - "description": "Host of server" + "trace.server.verbosity": { + "$ref": "#/definitions/languageserver.trace.server.verbosity" }, - "disableWorkspaceFolders": {}, - "disableSnippetCompletion": {}, - "disableDynamicRegister": {}, - "disableDiagnostics": {}, - "disableCompletion": {}, - "formatterPriority": {}, - "enable": {}, - "rootPatterns": {}, - "requireRootPattern": {}, - "ignoredRootPaths": {}, - "filetypes": {}, - "additionalSchemes": {}, - "revealOutputChannelOn": {}, - "progressOnInitialization": {}, - "initializationOptions": {}, - "settings": {}, - "stdioEncoding": {}, - "trace.server": {} + "trace.server.format": { + "$ref": "#/definitions/languageserver.trace.server.format" + } } }, "languageServerModule": { "type": "object", - "allOf": [{ "$ref": "#/definitions/languageServerBase" }], "required": ["module", "filetypes"], "additionalProperties": false, "properties": { "module": { "type": "string", "default": "", - "description": "Absolute path of javascript file, should works in IPC mode" + "description": "Absolute path of Javascript file, should works in IPC mode" }, "args": { "type": "array", @@ -239,7 +320,7 @@ "execArgv": { "type": "array", "default": [], - "description": "Argv passed to node when using module, normally used for debugging, ex: [\"--nolazy\", \"--inspect-brk=6045\"]", + "description": "ARGV passed to node when using module, normally used for debugging, ex: [\"--nolazy\", \"--inspect-brk=6045\"]", "items": { "type": "string" } @@ -254,32 +335,65 @@ "type": "integer", "description": "Port number used when transport is 'socket'" }, - "cwd": {}, - "env": {}, - "enable": {}, - "disableDynamicRegister": {}, - "disableWorkspaceFolders": {}, - "disableSnippetCompletion": {}, - "disableDiagnostics": {}, - "disableCompletion": {}, - "formatterPriority": {}, - "rootPatterns": {}, - "requireRootPattern": {}, - "ignoredRootPaths": {}, - "filetypes": {}, - "additionalSchemes": {}, - "revealOutputChannelOn": {}, - "progressOnInitialization": {}, - "initializationOptions": {}, - "stdioEncoding": {}, - "settings": {}, - "trace.server": {} + "enable": { + "$ref": "#/definitions/languageserver.enable" + }, + "disableSnippetCompletion": { + "$ref": "#/definitions/languageserver.disableSnippetCompletion" + }, + "disableDynamicRegister": { + "$ref": "#/definitions/languageserver.disableDynamicRegister" + }, + "disabledFeatures": { + "$ref": "#/definitions/languageserver.disabledFeatures" + }, + "formatterPriority": { + "$ref": "#/definitions/languageserver.formatterPriority" + }, + "rootPatterns": { + "$ref": "#/definitions/languageserver.rootPatterns" + }, + "requireRootPattern": { + "$ref": "#/definitions/languageserver.requireRootPattern" + }, + "ignoredRootPaths": { + "$ref": "#/definitions/languageserver.ignoredRootPaths" + }, + "filetypes": { + "$ref": "#/definitions/languageserver.filetypes" + }, + "additionalSchemes": { + "$ref": "#/definitions/languageserver.additionalSchemes" + }, + "revealOutputChannelOn": { + "$ref": "#/definitions/languageserver.revealOutputChannelOn" + }, + "progressOnInitialization": { + "$ref": "#/definitions/languageserver.progressOnInitialization" + }, + "initializationOptions": { + "$ref": "#/definitions/languageserver.initializationOptions" + }, + "settings": { + "$ref": "#/definitions/languageserver.settings" + }, + "stdioEncoding": { + "$ref": "#/definitions/languageserver.stdioEncoding" + }, + "trace.server": { + "$ref": "#/definitions/languageserver.trace.server" + }, + "trace.server.verbosity": { + "$ref": "#/definitions/languageserver.trace.server.verbosity" + }, + "trace.server.format": { + "$ref": "#/definitions/languageserver.trace.server.format" + } } }, "languageServerCommand": { "type": "object", "required": ["command", "filetypes"], - "allOf": [{ "$ref": "#/definitions/languageServerBase" }], "additionalProperties": false, "properties": { "command": { @@ -305,541 +419,785 @@ "default": false, "description": "Use shell for process" }, - "cwd": {}, - "env": {}, - "enable": {}, - "disableDynamicRegister": {}, - "disableWorkspaceFolders": {}, - "disableSnippetCompletion": {}, - "disableDiagnostics": {}, - "disableCompletion": {}, - "formatterPriority": {}, - "rootPatterns": {}, - "requireRootPattern": {}, - "ignoredRootPaths": {}, - "filetypes": {}, - "additionalSchemes": {}, - "revealOutputChannelOn": {}, - "progressOnInitialization": {}, - "initializationOptions": {}, - "stdioEncoding": {}, - "settings": {}, - "trace.server": {} + "enable": { + "$ref": "#/definitions/languageserver.enable" + }, + "disableSnippetCompletion": { + "$ref": "#/definitions/languageserver.disableSnippetCompletion" + }, + "disableDynamicRegister": { + "$ref": "#/definitions/languageserver.disableDynamicRegister" + }, + "disabledFeatures": { + "$ref": "#/definitions/languageserver.disabledFeatures" + }, + "formatterPriority": { + "$ref": "#/definitions/languageserver.formatterPriority" + }, + "rootPatterns": { + "$ref": "#/definitions/languageserver.rootPatterns" + }, + "requireRootPattern": { + "$ref": "#/definitions/languageserver.requireRootPattern" + }, + "ignoredRootPaths": { + "$ref": "#/definitions/languageserver.ignoredRootPaths" + }, + "filetypes": { + "$ref": "#/definitions/languageserver.filetypes" + }, + "additionalSchemes": { + "$ref": "#/definitions/languageserver.additionalSchemes" + }, + "revealOutputChannelOn": { + "$ref": "#/definitions/languageserver.revealOutputChannelOn" + }, + "progressOnInitialization": { + "$ref": "#/definitions/languageserver.progressOnInitialization" + }, + "initializationOptions": { + "$ref": "#/definitions/languageserver.initializationOptions" + }, + "settings": { + "$ref": "#/definitions/languageserver.settings" + }, + "stdioEncoding": { + "$ref": "#/definitions/languageserver.stdioEncoding" + }, + "trace.server": { + "$ref": "#/definitions/languageserver.trace.server" + }, + "trace.server.verbosity": { + "$ref": "#/definitions/languageserver.trace.server.verbosity" + }, + "trace.server.format": { + "$ref": "#/definitions/languageserver.trace.server.format" + } } } }, "properties": { - "http.proxy": { - "type": "string", - "default": "", - "pattern": "^https?://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$", - "description": "The proxy setting to use. If not set, will be inherited from the `http_proxy` and `https_proxy` environment variables." - }, - "http.proxyStrictSSL": { + "callHierarchy.enableTooltip": { "type": "boolean", - "description": "Controls whether the proxy server certificate should be verified against the list of supplied CAs", - "default": true - }, - "http.proxyAuthorization": { - "type": ["null", "string"], - "description": "The value to send as the `Proxy-Authorization` header for every network request.", - "default": null + "scope": "application", + "default": true, + "description": "Enable tooltip to show relative filepath of call hierarchy." }, - "http.proxyCA": { + "callHierarchy.openCommand": { "type": "string", - "description": "CA (file) to use as Certificate Authority", - "default": null + "scope": "application", + "default": "edit", + "description": "Open command for callHierarchy tree view." }, - "npm.binPath": { + "callHierarchy.splitCommand": { "type": "string", - "default": "npm", - "description": "Command or absolute path to npm or yarn." + "scope": "application", + "default": "botright 30vs", + "description": "Window split command used by callHierarchy tree view." }, - "suggest.enablePreselect": { - "type": "boolean", - "description": "Enable preselect feature of LSP, only works on neovim", - "default": false + "coc.preferences.rootPatterns": { + "type": ["array", "null"], + "default": null, + "scope": "application", + "description": "Root patterns to resolve workspaceFolder from parent folders of opened files, resolved from up to down.", + "deprecationMessage": "Use 'workspace.rootPatterns' instead.", + "items": { + "type": "string" + } }, - "suggest.enablePreview": { + "coc.preferences.bracketEnterImprove": { "type": "boolean", - "description": "Add preview option to completeopt, default: false.", - "default": false + "scope": "language-overridable", + "description": "Improve enter inside bracket `<> {} [] ()` by add new empty line below and place cursor to it. Works with `coc#on_enter()`", + "default": true }, - "suggest.floatEnable": { + "coc.preferences.currentFunctionSymbolAutoUpdate": { "type": "boolean", - "description": "Enable floating window for documentation when possible.", - "default": true + "scope": "language-overridable", + "description": "Automatically update the value of b:coc_current_function on CursorHold event", + "default": false }, - "suggest.floatConfig": { - "type": "object", - "description": "Configure style of documentation window for complete item.", - "allOf": [{ "$ref": "#/definitions/float" }], - "additionalProperties": false, - "properties": { - "border": {}, - "highlight": {}, - "borderhighlight": {}, - "maxWidth": {}, - "winblend": {}, - "focusable": {}, - "shadow": {} - } + "coc.preferences.enableLinkedEditing": { + "type": "boolean", + "scope": "language-overridable", + "default": false, + "description": "Enable linked editing support." }, - "suggest.labelMaxLength": { - "type": "number", - "description": "Max length of abbr that shown as label of complete item.", - "default": 200 + "coc.preferences.enableMarkdown": { + "type": "boolean", + "scope": "application", + "description": "Tell the language server that markdown text format is supported, note that markdown text may not rendered as expected.", + "default": true }, - "suggest.detailMaxLength": { - "type": "number", - "description": "Max length of detail that should be shown in popup menu.", - "default": 100 + "coc.preferences.enableMessageDialog": { + "type": "boolean", + "scope": "application", + "default": false, + "description": "Enable messages shown in notification dialog." }, - "suggest.detailField": { - "type": "string", - "default": "preview", - "description": "Where to show the detail text of CompleteItem from LS.", - "enum": ["abbr", "menu", "preview"] + "coc.preferences.excludeImageLinksInMarkdownDocument": { + "type": "boolean", + "description": "Exclude image links from markdown text in float window.", + "scope": "application", + "default": true }, - "suggest.autoTrigger": { - "type": "string", - "default": "always", - "description": "How should completion be triggered", - "enum": ["always", "trigger", "none"] + "coc.preferences.enableGFMBreaksInMarkdownDocument": { + "type": "boolean", + "description": "Exclude GFM breaks in markdown document.", + "scope": "application", + "default": true }, - "suggest.languageSourcePriority": { - "type": "number", - "default": 99, - "description": "Priority of language sources." + "coc.preferences.extensionUpdateCheck": { + "type": "string", + "scope": "application", + "default": "never", + "description": "Interval for check extension update, could be daily, weekly, never", + "enum": ["daily", "weekly", "never"] }, - "suggest.numberSelect": { + "coc.preferences.floatActions": { "type": "boolean", - "description": "Input number to select complete item, works on neovim >= 0.4.0 only.", - "default": false + "scope": "application", + "description": "Set to false to disable float/popup support for actions menu.", + "default": true }, - "suggest.disableKind": { + "coc.preferences.formatOnSave": { "type": "boolean", - "description": "Remove kind field from vim complete item.", + "description": "Set to true to enable formatting on save.", + "scope": "language-overridable", "default": false }, - "suggest.disableMenu": { - "type": "boolean", - "description": "Remove menu field from vim complete item.", - "default": false + "coc.preferences.formatOnSaveFiletypes": { + "type": ["null", "array"], + "scope": "resource", + "default": null, + "description": "Filetypes that should run format on save.", + "deprecationMessage": "Use coc.preferences.formatOnSave as language override configuration instead, see :h coc-configuration-scope", + "items": { + "type": "string" + } }, - "suggest.disableMenuShortcut": { + "coc.preferences.formatOnType": { "type": "boolean", - "description": "Disable shortcut of completion source in menu.", + "description": "Set to true to enable formatting on typing.", + "scope": "language-overridable", "default": false }, - "suggest.snippetIndicator": { + "coc.preferences.formatOnTypeFiletypes": { + "type": ["null", "array"], + "default": null, + "scope": "resource", + "description": "Filetypes that should run format on typing, only works when `coc.preferences.formatOnType` is `true`", + "deprecationMessage": "Use coc.preferences.formatOnType as language override configuration instead, see :h coc-configuration-scope", + "items": { + "type": "string" + } + }, + "coc.preferences.jumpCommand": { + "anyOf": [ + { + "type": "string", + "enum": [ + "edit", + "split", + "vsplit", + "tabe", + "drop", + "tab drop", + "pedit" + ] + }, + { "type": "string", "minimum": 1 } + ], + "scope": "application", + "description": "Command used for location jump, like goto definition, goto references etc. Can be also a custom command that gives file as an argument.", + "default": "edit" + }, + "coc.preferences.maxFileSize": { "type": "string", - "default": "~", - "description": "The character used in abbr of complete item to indicate the item could be expand as snippet." + "scope": "application", + "default": "10MB", + "description": "Maximum file size in bytes that coc.nvim should handle, default '10MB'" }, - "suggest.maxCompleteItemCount": { - "type": "number", - "default": 50, - "description": "Maximum number of complete items shown in vim" + "coc.preferences.messageLevel": { + "type": "string", + "scope": "application", + "description": "Message level for filter echoed messages, could be 'more', 'warning' and 'error'", + "default": "more", + "enum": ["more", "warning", "error"] }, - "suggest.preferCompleteThanJumpPlaceholder": { + "coc.preferences.promptInput": { "type": "boolean", - "description": "Confirm completion instead of jump to next placeholder when completion is activated.", - "default": false + "description": "Use prompt buffer in float window for user input.", + "scope": "application", + "default": true }, - "suggest.fixInsertedWord": { + "coc.preferences.renameFillCurrent": { "type": "boolean", - "description": "Make inserted word replace word characters after cursor position.", - "default": true + "scope": "application", + "default": true, + "description": "Disable to stop Refactor-Rename float/popup window from populating with old name in the New Name field." }, - "suggest.localityBonus": { + "coc.preferences.silentAutoupdate": { "type": "boolean", - "description": "Boost suggestions that appear closer to the cursor position.", + "description": "Not open split window with update status when performing auto update.", + "scope": "application", "default": true }, - "suggest.triggerAfterInsertEnter": { + "coc.preferences.useQuickfixForLocations": { "type": "boolean", - "description": "Trigger completion after InsertEnter, auto trigger should be 'always' to enable this option", + "scope": "application", + "description": "Use vim's quickfix list for jump locations,\n need restart on change.", "default": false }, - "suggest.timeout": { - "type": "integer", - "default": 5000, - "minimum": 500, - "maximum": 15000, - "description": "Timeout for completion, in miliseconds." + "coc.preferences.watchmanPath": { + "type": "string", + "scope": "application", + "description": "executable path for https://facebook.github.io/watchman/, detected from $PATH by default", + "default": null }, - "suggest.minTriggerInputLength": { + "coc.preferences.willSaveHandlerTimeout": { "type": "integer", - "default": 1, - "description": "Mininal input length for trigger completion, default 1" + "scope": "application", + "default": 500, + "minimum": 200, + "maximum": 5000, + "description": "Will save handler timeout" }, - "suggest.triggerCompletionWait": { + "coc.source.around.disableSyntaxes": { + "type": "array", + "default": [], + "scope": "application", + "items": { + "type": "string" + } + }, + "coc.source.around.enable": { + "type": "boolean", + "scope": "application", + "default": true + }, + "coc.source.around.priority": { "type": "integer", - "default": 100, - "minimum": 30, - "maximum": 500, - "description": "Wait time between text change and completion start, cancel completion when text changed during wait." + "scope": "application", + "default": 1 + }, + "coc.source.around.shortcut": { + "type": "string", + "scope": "application", + "default": "A" }, - "suggest.echodocSupport": { + "coc.source.buffer.disableSyntaxes": { + "type": "array", + "default": [], + "scope": "application", + "items": { + "type": "string" + } + }, + "coc.source.buffer.enable": { "type": "boolean", - "default": false, - "description": "When enabled, add function signature to user_data.signature to support echodoc.vim" + "scope": "application", + "default": true }, - "suggest.acceptSuggestionOnCommitCharacter": { + "coc.source.buffer.ignoreGitignore": { "type": "boolean", - "default": false, - "description": "Controls whether suggestions should be accepted on commit characters. For example, in JavaScript, the semi-colon (`;`) can be a commit character that accepts a suggestion and types that character. Requires CompleteChanged event to work." + "default": true, + "scope": "application", + "description": "Ignore git ignored files for buffer words" }, - "suggest.noselect": { + "coc.source.buffer.priority": { + "type": "integer", + "scope": "application", + "default": 1 + }, + "coc.source.buffer.shortcut": { + "type": "string", + "scope": "application", + "default": "B" + }, + "coc.source.file.disableSyntaxes": { + "type": "array", + "default": [], + "scope": "application", + "items": { + "type": "string" + } + }, + "coc.source.file.enable": { "type": "boolean", - "description": "Not make vim select first item on completion start", + "scope": "application", "default": true }, - "suggest.keepCompleteopt": { + "coc.source.file.ignoreHidden": { "type": "boolean", - "description": "When enabled, completeopt is not overridden, auto completion will be disabled if completeopt doesn't have noinsert and noselect.", - "default": false + "scope": "application", + "default": true, + "description": "Ignore completion for hidden files" }, - "suggest.lowPrioritySourceLimit": { - "type": "integer", - "minimum": 1, - "maximum": 100, - "description": "Max items count for source priority lower than 90." + "coc.source.file.ignorePatterns": { + "type": "array", + "scope": "application", + "default": [], + "description": "Ignore patterns of matcher", + "items": { + "type": "string" + } }, - "suggest.highPrioritySourceLimit": { + "coc.source.file.priority": { "type": "integer", - "minimum": 1, - "maximum": 100, - "description": "Max items count for source priority bigger than or equal to 90." + "scope": "application", + "default": 10 }, - "suggest.removeDuplicateItems": { + "coc.source.file.shortcut": { + "type": "string", + "scope": "application", + "default": "F" + }, + "coc.source.file.triggerCharacters": { + "type": "array", + "default": ["/", "\\"], + "scope": "application", + "items": { + "type": "string" + } + }, + "coc.source.file.trimSameExts": { + "type": "array", + "scope": "application", + "default": [".ts", ".js"], + "description": "Trim same extension on file completion", + "items": { + "type": "string" + } + }, + "codeLens.enable": { "type": "boolean", - "description": "Remove completion items with duplicated word for all sources, snippet items are excluded.", + "scope": "language-overridable", + "description": "Enable codeLens feature, require neovim with set virtual text feature.", "default": false }, - "suggest.defaultSortMethod": { + "codeLens.position": { "type": "string", - "description": "Default sorting behavior for suggested completion items.", - "default": "length", - "enum": ["length", "alphabetical", "none"] + "scope": "resource", + "enum": ["top", "eol", "right_align"], + "description": "Position of codeLens, requires nvim >= 0.6.0", + "default": "top" }, - "suggest.snippetsSupport": { - "type": "boolean", - "description": "Set to false to disable snippets support of completion.", - "default": true + "codeLens.separator": { + "type": "string", + "scope": "resource", + "description": "Separator text for codeLens in virtual text", + "default": "" }, - "suggest.completionItemKindLabels": { - "type": "object", - "default": {}, - "description": "Set custom labels to completion items' kinds.", - "properties": { - "text": { "type": "string" }, - "method": { "type": "string" }, - "function": { "type": "string" }, - "constructor": { "type": "string" }, - "field": { "type": "string" }, - "variable": { "type": "string" }, - "class": { "type": "string" }, - "interface": { "type": "string" }, - "module": { "type": "string" }, - "property": { "type": "string" }, - "unit": { "type": "string" }, - "value": { "type": "string" }, - "enum": { "type": "string" }, - "keyword": { "type": "string" }, - "snippet": { "type": "string" }, - "color": { "type": "string" }, - "file": { "type": "string" }, - "reference": { "type": "string" }, - "folder": { "type": "string" }, - "enumMember": { "type": "string" }, - "constant": { "type": "string" }, - "struct": { "type": "string" }, - "event": { "type": "string" }, - "operator": { "type": "string" }, - "typeParameter": { "type": "string" }, - "default": { "type": "string" } - }, - "additionalProperties": false + "codeLens.subseparator": { + "type": "string", + "scope": "resource", + "description": "Subseparator between codeLenses in virtual text", + "default": " | " }, - "suggest.invalidInsertCharacters": { - "type": "array", + "colors.enable": { + "type": "boolean", + "scope": "language-overridable", + "description": "Enable colors highlight feature, for termainal vim, 'termguicolors' option should be enabled and the termainal support gui colors.", + "default": false + }, + "colors.filetypes": { + "type": ["array", "null"], + "default": null, + "scope": "resource", + "deprecationMessage": "Use colors.enable as language override configuration instead, see :h coc-configuration-scope", + "description": "Filetypes that should be enabled for colors highlight feature, use \"*\" for all filetypes.", "items": { "type": "string" - }, - "description": "Invalid character for strip valid word when inserting text of complete item.", - "default": [" ", "(", "<", "{", "[", "\r", "\n"] + } }, - "suggest.asciiCharactersOnly": { + "colors.highlightPriority": { + "type": "number", + "scope": "application", + "description": "Priority for colors highlights, works on vim8 and neovim >= 0.6.0", + "default": 1000, + "maximum": 4096 + }, + "cursors.cancelKey": { + "type": "string", + "scope": "application", + "default": "", + "description": "Key used for cancel cursors session." + }, + "cursors.nextKey": { + "type": "string", + "scope": "application", + "default": "", + "description": "Key used for jump to next cursors position." + }, + "cursors.previousKey": { + "type": "string", + "scope": "application", + "default": "", + "description": "Key used for jump to previous cursors position." + }, + "cursors.wrapscan": { "type": "boolean", - "description": "Suggest ASCII characters only", + "scope": "application", + "default": true, + "description": "Searches wrap around the first or last cursors range." + }, + "diagnostic.autoRefresh": { + "type": "boolean", + "scope": "language-overridable", + "description": "Enable automatically refresh diagnostics, use diagnosticRefresh action when it's disabled.", + "default": true + }, + "diagnostic.checkCurrentLine": { + "type": "boolean", + "scope": "language-overridable", + "description": "When enabled, show all diagnostics of current line if there are none at the current position.", + "default": false + }, + "diagnostic.displayByAle": { + "type": "boolean", + "scope": "language-overridable", + "description": "Use Ale for display diagnostics in vim, will disable coc for display diagnostics, restart required on change.", "default": false }, "diagnostic.enable": { "type": "boolean", + "scope": "language-overridable", "description": "Set to false to disable diagnostic display", "default": true }, - "diagnostic.highlighLimit": { + "diagnostic.enableHighlightLineNumber": { + "type": "boolean", + "scope": "application", + "default": true, + "description": "Enable highlighting line numbers for diagnostics, only works with neovim." + }, + "diagnostic.enableMessage": { + "type": "string", + "scope": "application", + "default": "always", + "description": "When to enable show messages of diagnostics.", + "enum": ["always", "jump", "never"] + }, + "diagnostic.enableSign": { + "type": "boolean", + "scope": "language-overridable", + "default": true, + "description": "Enable signs for diagnostics." + }, + "diagnostic.errorSign": { + "type": "string", + "scope": "application", + "description": "Text of error sign", + "default": ">>" + }, + "diagnostic.filetypeMap": { + "type": "object", + "scope": "application", + "description": "A map between buffer filetype and the filetype assigned to diagnostics. To syntax highlight diagnostics with their parent buffer type use `\"default\": \"bufferType\"`", + "default": {} + }, + "diagnostic.floatConfig": { + "type": "object", + "scope": "application", + "description": "Configure float window style of diagnostic message.", + "allOf": [{ "$ref": "#/definitions/floatConfig" }], + "additionalProperties": false, + "properties": { + "border": {}, + "rounded": {}, + "highlight": {}, + "borderhighlight": {}, + "title": {}, + "close": {}, + "maxHeight": {}, + "maxWidth": {}, + "winblend": {}, + "focusable": {}, + "shadow": {} + } + }, + "diagnostic.format": { + "type": "string", + "scope": "language-overridable", + "description": "Define the diagnostic format that shown in float window or echoed, available parts: source, code, severity, message", + "default": "%message (%source%code)" + }, + "diagnostic.highlightLimit": { "type": "number", - "description": "Limit count for highlighted diagnostics, too many diagnostic highlights could make vim stop responsing", + "scope": "language-overridable", + "description": "Limit count for highlighted diagnostics, too many diagnostic highlights could make vim stop responding", "default": 1000 }, - "diagnostic.autoRefresh": { - "type": "boolean", - "description": "Enable automatically refresh diagnostics, use diagnosticRefresh action when it's disabled.", - "default": true + "diagnostic.highlightPriority": { + "type": "number", + "scope": "language-overridable", + "description": "Priority for diagnostic highlights, works on vim8 and neovim >= 0.6.0", + "default": 4096, + "maximum": 4096, + "minimum": 110 + }, + "diagnostic.hintSign": { + "type": "string", + "scope": "application", + "description": "Text of hint sign", + "default": ">>" + }, + "diagnostic.infoSign": { + "type": "string", + "scope": "application", + "description": "Text of info sign", + "default": ">>" }, "diagnostic.level": { "type": "string", + "scope": "resource", "description": "Used for filter diagnostics by diagnostic severity.", "default": "hint", "enum": ["hint", "information", "warning", "error"] }, + "diagnostic.locationlistLevel": { + "type": ["string", "null"], + "scope": "language-overridable", + "description": "Filter diagnostics in locationlist.", + "default": null, + "enum": ["hint", "information", "warning", "error"] + }, "diagnostic.locationlistUpdate": { "type": "boolean", + "scope": "language-overridable", "description": "Update locationlist on diagnostics change, only works with locationlist opened by :CocDiagnostics command and first window of associated buffer.", "default": true }, - "diagnostic.checkCurrentLine": { - "type": "boolean", - "description": "When enabled, show all diagnostics of current line if there are none at the current position.", - "default": false + "diagnostic.messageDelay": { + "type": "number", + "scope": "application", + "description": "How long to wait (in milliseconds) before displaying the diagnostic message with echo or float", + "default": 200 + }, + "diagnostic.messageLevel": { + "type": ["string", "null"], + "scope": "language-overridable", + "description": "Filter diagnostic message in float window/popup.", + "default": null, + "enum": ["hint", "information", "warning", "error"] }, "diagnostic.messageTarget": { "type": "string", + "scope": "language-overridable", "description": "Diagnostic message target.", "default": "float", "enum": ["echo", "float"] }, - "diagnostic.messageDelay": { - "type": "number", - "description": "How long to wait (in milliseconds) before displaying the diagnostic message with echo or float", - "default": 200 - }, "diagnostic.refreshOnInsertMode": { "type": "boolean", + "scope": "language-overridable", "description": "Enable diagnostic refresh on insert mode, default false.", "default": false }, - "diagnostic.displayByAle": { + "diagnostic.separateRelatedInformationAsDiagnostics": { + "type": "boolean", + "default": false, + "scope": "application", + "description": "Separate related information as diagnostics." + }, + "diagnostic.showDeprecated": { + "type": "boolean", + "default": true, + "scope": "language-overridable", + "description": "Show diagnostics with deprecated tag." + }, + "diagnostic.showUnused": { "type": "boolean", - "description": "Use Ale for display diagnostics in vim, will disable coc for display diagnostics, restart required on change.", - "default": false + "default": true, + "scope": "language-overridable", + "description": "Show diagnostics with unused tag, affects highlight, sign, virtual text, message" + }, + "diagnostic.signLevel": { + "type": ["string", "null"], + "scope": "language-overridable", + "description": "Filter diagnostics displayed in signcolumn.", + "default": null, + "enum": ["hint", "information", "warning", "error"] + }, + "diagnostic.signPriority": { + "type": "number", + "scope": "resource", + "description": "Priority of diagnostic signs, default to 10", + "default": 10 }, "diagnostic.virtualText": { "type": "boolean", - "description": "Use NeoVim virtual text to display diagnostics", + "scope": "language-overridable", + "description": "Use virtual text to display diagnostics, requires neovim >= 0.5.0 or vim >= 9.0.0067.", "default": false }, + "diagnostic.virtualTextAlign": { + "type": "string", + "scope": "language-overridable", + "description": "Position of virtual text, default 'after'. Vim9 only", + "default": "after", + "enum": ["after", "right", "below"] + }, "diagnostic.virtualTextCurrentLineOnly": { "type": "boolean", + "scope": "language-overridable", "description": "Only show virtualText diagnostic on current cursor line", "default": true }, - "diagnostic.virtualTextPrefix": { + "diagnostic.virtualTextFormat": { "type": "string", - "description": "The prefix added virtual text diagnostics", - "default": " " + "scope": "language-overridable", + "description": "Define the virtual text diagnostic format, available parts: source, code, severity, message", + "default": "%message" }, - "diagnostic.virtualTextLines": { - "type": "number", - "description": "The number of non empty lines from a diagnostic to display", - "default": 3 + "diagnostic.virtualTextLevel": { + "type": ["string", "null"], + "scope": "language-overridable", + "description": "Filter diagnostic message in virtual text by level", + "default": null, + "enum": ["hint", "information", "warning", "error"] + }, + "diagnostic.virtualTextLimitInOneLine": { + "type": "integer", + "scope": "language-overridable", + "minimum": 1, + "description": "The maximum number of diagnostic messages to disaply in one line", + "default": 999 }, "diagnostic.virtualTextLineSeparator": { "type": "string", + "scope": "language-overridable", "description": "The text that will mark a line end from the diagnostic message", "default": " \\ " }, - "diagnostic.enableSign": { - "type": "boolean", - "default": true, - "description": "Enable signs for diagnostics." - }, - "diagnostic.enableHighlightLineNumber": { - "type": "boolean", - "default": true, - "description": "Enable highlighting line numbers for diagnostics, only works with neovim and diagnostic.enableSign is true." - }, - "diagnostic.enableMessage": { - "type": "string", - "default": "always", - "description": "When to enable show messages of diagnostics.", - "enum": ["always", "jump", "never"] - }, - "diagnostic.highlightOffset": { - "type": "number", - "description": "Offset number of buffer.addHighlight, neovim only.", - "default": 1000 - }, - "diagnostic.signPriority": { + "diagnostic.virtualTextLines": { "type": "number", - "description": "Priority of diagnostic signs, default to 10", - "default": 10 + "scope": "language-overridable", + "description": "The number of non empty lines from a diagnostic to display", + "default": 3 }, - "diagnostic.errorSign": { + "diagnostic.virtualTextPrefix": { "type": "string", - "description": "Text of error sign", - "default": ">>" + "scope": "language-overridable", + "description": "The prefix added virtual text diagnostics", + "default": " " + }, + "diagnostic.virtualTextWinCol": { + "type": ["number", "null"], + "scope": "language-overridable", + "description": "Window column number to align virtual text, neovim only.", + "default": null }, "diagnostic.warningSign": { "type": "string", + "scope": "application", "description": "Text of warning sign", "default": "โš " }, - "diagnostic.infoSign": { + "dialog.confirmKey": { "type": "string", - "description": "Text of info sign", - "default": ">>" + "default": "", + "scope": "application", + "description": "Confirm key for confirm selection used by menu and picker, you can always use to cancel." }, - "diagnostic.hintSign": { - "type": "string", - "description": "Text of hint sign", - "default": ">>" + "dialog.floatBorderHighlight": { + "type": ["string", "null"], + "default": null, + "scope": "application", + "description": "Highlight group for border of dialog window/popup, default to 'CocFloating'" }, - "diagnostic.floatConfig": { - "type": "object", - "description": "Configure float window style of diagnostic message.", - "allOf": [{ "$ref": "#/definitions/float" }], - "additionalProperties": false, - "properties": { - "border": {}, - "highlight": {}, - "borderhighlight": {}, - "title": {}, - "close": {}, - "maxHeight": {}, - "maxWidth": {}, - "winblend": {}, - "focusable": {}, - "shadow": {} - } + "dialog.floatHighlight": { + "type": ["string", "null"], + "default": null, + "scope": "application", + "description": "Highlight group for dialog window/popup, default to 'CocFloating'" }, - "diagnostic.filetypeMap": { - "type": "object", - "description": "A map between buffer filetype and the filetype assigned to diagnostics. To syntax highlight diagnostics withs their parent buffer type use `\"default\": \"bufferType\"`", - "default": {} + "dialog.maxHeight": { + "type": "number", + "default": 30, + "scope": "application", + "description": "Maximum height of dialog window." }, - "diagnostic.format": { - "type": "string", - "description": "Define the diagnostic format that shown in float window or echoed, available parts: source, code, severity, message", - "default": "[%source%code] [%severity] %message" + "dialog.maxWidth": { + "type": "number", + "default": 80, + "scope": "application", + "description": "Maximum width of dialog window." }, - "diagnostic.separateRelatedInformationAsDiagnostics": { + "dialog.pickerButtonShortcut": { "type": "boolean", - "default": false, - "description": "Separate related information as diagnostics." + "default": true, + "scope": "application", + "description": "Show shortcut in buttons of picker dialog window/popup, used when dialog.pickerButtons is true." }, - "diagnostic.showUnused": { + "dialog.pickerButtons": { "type": "boolean", "default": true, - "description": "Show diagnostics with unused tag." + "scope": "application", + "description": "Show buttons for picker dialog window/popup." }, - "diagnostic.showDeprecated": { + "dialog.rounded": { "type": "boolean", "default": true, - "description": "Show diagnostics with deprecated tag." + "scope": "application", + "description": "use rounded border for dialog window." }, - "signature.enable": { - "type": "boolean", - "description": "Enable signature help when trigger character typed, require restart service on change.", - "default": true + "dialog.shortcutHighlight": { + "type": "string", + "default": "MoreMsg", + "scope": "application", + "description": "Highlight group for shortcut character in menu dialog, default to 'MoreMsg'" }, - "signature.triggerSignatureWait": { + "documentHighlight.priority": { + "type": "number", + "default": -1, + "scope": "resource", + "description": "Match priority used by document highlight, see ':h matchadd'" + }, + "documentHighlight.timeout": { "type": "integer", - "default": 500, + "default": 300, "minimum": 200, - "maximum": 1000, - "description": "Timeout for trigger signature help, in miliseconds." - }, - "signature.target": { - "type": "string", - "description": "Target of signature help, use float when possible by default.", - "default": "float", - "enum": ["float", "echo"] + "maximum": 5000, + "scope": "resource", + "description": "Timeout for document highlight, in milliseconds." }, - "signature.floatConfig": { + "floatFactory.floatConfig": { "type": "object", - "description": "Configure float window style of signature documents.", - "allOf": [{ "$ref": "#/definitions/float" }], + "scope": "application", + "description": "Configure default style float window/popup created by float factory (created around cursor and automatically closed)", + "allOf": [{ "$ref": "#/definitions/floatConfig" }], "additionalProperties": false, "properties": { "border": {}, + "rounded": {}, "highlight": {}, "borderhighlight": {}, "title": {}, "close": {}, - "maxHeight": {}, "maxWidth": {}, + "maxHeight": {}, "winblend": {}, "focusable": {}, "shadow": {} } }, - "signature.preferShownAbove": { - "type": "boolean", - "description": "Show signature help float window above cursor when possible, require restart service on change.", - "default": true - }, - "signature.hideOnTextChange": { - "type": "boolean", - "description": "Hide signature float window when text changed on insert mode.", - "default": false - }, - "codeLens.enable": { - "type": "boolean", - "description": "Enable codeLens feature, require neovim with set virtual text feature.", - "default": false - }, - "codeLens.separator": { - "type": "string", - "description": "Separator text for codeLens in virtual text", - "default": "โ€ฃ" - }, - "codeLens.subseparator": { - "type": "string", - "description": "Subseparator between codeLenses in virtual text", - "default": " " - }, - "refactor.openCommand": { - "type": "string", - "description": "Open command for refactor window.", - "default": "vsplit" - }, - "refactor.saveToFile": { + "hover.autoHide": { "type": "boolean", - "description": "Save to file when write refactor buffer with ':noa wa' command, set to false if you want save buffer by yourself.", - "default": true - }, - "refactor.beforeContext": { - "type": "number", - "default": 3, - "description": "Print num lines of leading context before each match." - }, - "refactor.afterContext": { - "type": "number", - "default": 3, - "description": "Print num lines of trailing context after each match." - }, - "hover.target": { - "type": "string", - "description": "Target to show hover information, default is floating window when possible.", - "enum": ["preview", "echo", "float"] - }, - "hover.previewMaxHeight": { - "type": "number", - "default": 12, - "description": "Max height of preview window for hover." + "scope": "application", + "default": true, + "description": "Automatically hide hover float window on CursorMove or InsertEnter." }, "hover.floatConfig": { "type": "object", + "scope": "application", "description": "Configure float window style of hover documents.", - "allOf": [{ "$ref": "#/definitions/float" }], + "allOf": [{ "$ref": "#/definitions/floatConfig" }], "additionalProperties": false, "properties": { "border": {}, + "rounded": {}, "highlight": {}, "borderhighlight": {}, "title": {}, @@ -851,617 +1209,1082 @@ "shadow": {} } }, - "hover.autoHide": { - "type": "boolean", - "default": true, - "description": "Automatically hide hover float window on CursorMove or InsertEnter." - }, - "dialog.maxHeight": { - "type": "number", - "default": 20, - "description": "Maximum height of dialog window." - }, - "dialog.maxWidth": { + "hover.previewMaxHeight": { "type": "number", - "default": 80, - "description": "Maximum width of dialog window." + "scope": "resource", + "default": 12, + "description": "Max height of preview window for hover." }, - "dialog.confirmKey": { + "hover.target": { "type": "string", - "default": "", - "description": "Confirm key for confirm selection used by menu and picker, you can always use to cancel." - }, - "dialog.pickerButtons": { - "type": "boolean", - "default": true, - "description": "Show buttons for picker dialog window/popup." - }, - "dialog.pickerButtonShortcut": { - "type": "boolean", - "default": true, - "description": "Show shortcut in buttons of picker dialog window/popup, used when dialog.pickerButtons is true." - }, - "dialog.floatHighlight": { - "type": ["string", "null"], - "default": null, - "description": "Highlight group for dialog window/popup, default to 'CocFloating'" - }, - "dialog.floatBorderHighlight": { - "type": ["string", "null"], - "default": null, - "description": "Highlight group for border of dialog window/popup, default to 'CocFloating'" - }, - "notification.marginTop": { - "type": "number", - "default": 1, - "description": "Margin top for notification dialog." - }, - "notification.marginRight": { - "type": "number", - "default": 1, - "description": "Margin right for notification dialog." + "default": "float", + "scope": "resource", + "description": "Target to show hover information, default is floating window when possible.", + "enum": ["preview", "echo", "float"] }, - "notification.maxWidth": { - "type": "number", - "default": 60, - "description": "Maximum content width of notification dialog." + "http.proxy": { + "type": "string", + "default": "", + "pattern": "^https?://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$", + "description": "The proxy setting to use. If not set, will be inherited from the `http_proxy` and `https_proxy` environment variables.", + "scope": "application" }, - "notification.maxHeight": { - "type": "number", - "default": 10, - "description": "Maximum content height of notification dialog." + "http.proxyAuthorization": { + "type": ["null", "string"], + "description": "The value to send as the `Proxy-Authorization` header for every network request.", + "default": null, + "scope": "application" }, - "notification.highlightGroup": { + "http.proxyCA": { "type": "string", - "default": "CocFloating", - "description": "Highlight group of notification dialog." + "description": "CA (file) to use as Certificate Authority", + "default": null, + "scope": "application" }, - "notification.minProgressWidth": { - "type": "number", - "default": 30, - "description": "Minimum width of progress notification." + "http.proxyStrictSSL": { + "type": "boolean", + "description": "Controls whether the proxy server certificate should be verified against the list of supplied CAs", + "default": true, + "scope": "application" }, - "workspace.ignoredFiletypes": { - "type": "array", - "default": ["markdown", "log", "txt", "help"], - "description": "Filetypes that should be ignored for resolve workspace folder.", - "items": { - "type": "string" - } + "inlayHint.enable": { + "type": "boolean", + "default": true, + "scope": "language-overridable", + "description": "Enable inlay hint support" }, - "workspace.bottomUpFiletypes": { - "type": "array", - "default": [], - "description": "Filetypes that should have workspace folder should resolved from base directory of file.", + "inlayHint.enableParameter": { + "type": "boolean", + "scope": "language-overridable", + "default": true, + "description": "Enable inlay hints for parameters." + }, + "inlayHint.display": { + "type": "boolean", + "scope": "language-overridable", + "default": true, + "description": "Display inlay hints." + }, + "inlayHint.filetypes": { + "type": ["array", "null"], + "scope": "application", + "description": "Filetypes that enable inlayHint, all filetypes are enabled by default", + "deprecationMessage": "Use inlayHint.enable with language scope instead, see :h coc-configuration-scope", + "default": null, "items": { "type": "string" } }, - "workspace.workspaceFolderCheckCwd": { + "inlayHint.parameterSeparator": { + "type": "string", + "scope": "language-overridable", + "default": "", + "description": "Separator for parameter inlay hint, neovim only." + }, + "inlayHint.refreshOnInsertMode": { "type": "boolean", - "default": true, - "description": "Whether the cwd directory should be checked first when resolving workspace folder." + "default": false, + "scope": "language-overridable", + "description": "Refresh inlayHints on insert mode." }, - "list.indicator": { + "inlayHint.subSeparator": { "type": "string", - "default": ">", - "description": "The character used as first character in prompt line" + "scope": "language-overridable", + "default": " ", + "description": "Separator for chained inlay hints, neovim only." + }, + "inlayHint.typeSeparator": { + "type": "string", + "scope": "language-overridable", + "default": "", + "description": "Separator for type inlay hint, neovim only." + }, + "links.enable": { + "type": "boolean", + "scope": "language-overridable", + "description": "Enable document links", + "default": true + }, + "links.tooltip": { + "type": "boolean", + "scope": "application", + "description": "Show tooltip of link under cursor on CursorHold.", + "default": false + }, + "links.highlight": { + "type": "boolean", + "scope": "application", + "description": "Use CocLink highlight group to highlight links", + "default": false + }, + "list.floatPreview": { + "type": "boolean", + "default": false, + "scope": "application", + "description": "Enable preview with float window/popup, default: `false`" }, "list.alignColumns": { "type": "boolean", "default": false, + "scope": "application", "description": "Whether to align lists in columns, default: `false`" }, - "list.interactiveDebounceTime": { - "type": "number", - "default": 100, - "description": "Debouce time for input change on interactive mode." + "list.extendedSearchMode": { + "type": "boolean", + "scope": "application", + "default": true, + "description": "Enable extended search mode which allows multiple search patterns delimited by spaces." }, "list.height": { "type": "number", + "scope": "application", "default": 10, "description": "Height of split list window." }, - "list.statusLineSegments": { - "type": ["array", "null"], - "default": [ - "%#CocListMode#-- %{get(b:list_status, \"mode\", \"\")} --%*", - "%{get(b:list_status, \"loading\", \"\")}", - "%{get(b:list_status, \"args\", \"\")}", - "(%L/%{get(b:list_status, \"total\", \"\")})", - "%=", - "%#CocListPath# %{get(b:list_status, \"cwd\", \"\")} %l/%L%*" - ], - "items": { - "types": "string" - }, - "description": "An array of statusline segments that will be used to draw the status line for list windows." - }, - "list.signOffset": { - "type": "number", - "default": 900, - "description": "Sign offset of list, should be different from other plugins." - }, - "list.selectedSignText": { + "list.indicator": { "type": "string", - "default": "*", - "description": "Sign text for selected lines." + "default": ">", + "scope": "application", + "description": "The character used as first character in prompt line." }, - "list.extendedSearchMode": { - "type": "boolean", - "default": true, - "description": "Enable extended search mode which allows multiple search patterns delimited by spaces." + "list.insertMappings": { + "type": "object", + "scope": "application", + "default": {}, + "description": "Custom keymappings on insert mode." }, - "list.limitLines": { + "list.interactiveDebounceTime": { "type": "number", - "default": 30000, + "default": 100, + "scope": "application", + "description": "Debounce time for input change on interactive mode." + }, + "list.limitLines": { + "type": ["number", "null"], + "scope": "application", + "default": null, "description": "Limit lines for list buffer." }, "list.maxPreviewHeight": { "type": "number", + "scope": "application", "default": 12, "description": "Max height for preview window of list." }, - "list.previewSplitRight": { + "list.menuAction": { "type": "boolean", "default": false, - "description": "Use vsplit for preview window." + "scope": "application", + "description": "Use menu picker instead of confirm() for choose action." }, - "list.matchHighlightGroup": { + "list.nextKeymap": { "type": "string", - "default": "Search", - "description": "Highlight group used for matched texts in list window." + "scope": "application", + "default": "", + "description": "Key used for select next line on insert mode." + }, + "list.normalMappings": { + "type": "object", + "scope": "application", + "default": {}, + "description": "Custom keymappings on normal mode." }, "list.previewHighlightGroup": { "type": "string", + "scope": "application", "default": "Search", "description": "Highlight group used for highlight the range in preview window." }, - "list.previewToplineStyle": { - "type": "string", - "default": "offset", - "description": "Topline style for list previews", - "enum": ["offset", "middle"] + "list.previewSplitRight": { + "type": "boolean", + "scope": "application", + "default": false, + "description": "Use vsplit for preview window." }, "list.previewToplineOffset": { "type": "number", + "scope": "application", "default": 3, "description": "Topline offset for list previews" }, - "list.nextKeymap": { + "list.previewToplineStyle": { "type": "string", - "default": "", - "description": "Key used for select next line on insert mode." + "scope": "application", + "default": "offset", + "description": "Topline style for list previews", + "enum": ["offset", "middle"] }, "list.previousKeymap": { "type": "string", + "scope": "application", "default": "", "description": "Key used for select previous line on insert mode." }, - "list.normalMappings": { - "type": "object", - "default": {}, - "description": "Custom keymappings on normal mode." + "list.selectedSignText": { + "type": "string", + "scope": "application", + "default": "*", + "description": "Sign text for selected lines." }, - "list.insertMappings": { - "type": "object", - "default": {}, - "description": "Custom keymappings on insert mode." + "list.signOffset": { + "type": "number", + "scope": "application", + "default": 900, + "description": "Sign offset of list, should be different from other plugins." + }, + "list.smartCase": { + "type": "boolean", + "default": false, + "scope": "application", + "description": "Use smartcase match for fuzzy match and strict match, --ignore-case will be ignored, may not affect interactive list." }, "list.source.diagnostics.includeCode": { "type": "boolean", + "scope": "application", "description": "Whether to show the diagnostic code in the list.", "default": true }, "list.source.diagnostics.pathFormat": { "type": "string", + "scope": "application", "description": "Decide how the filepath is shown in the list.", "enum": ["full", "short", "filename", "hidden"], "default": "full" }, + "list.source.outline.ctagsFiletypes": { + "type": "array", + "scope": "application", + "default": [], + "description": "Filetypes that should use ctags for outline instead of language server.", + "items": { + "type": "string" + } + }, "list.source.symbols.excludes": { "type": "array", + "scope": "application", "default": [], - "description": "Patterns of minimatch for filepath to execlude from symbols list.", + "description": "Patterns of minimatch for filepath to exclude from symbols list.", "items": { "type": "string" } }, - "list.source.outline.ctagsFilestypes": { + "list.statusLineSegments": { + "type": ["array", "null"], + "scope": "application", + "default": [ + "%#CocListMode#-- %{coc#list#status(\"mode\")} --%*", + "%{coc#list#status(\"loading\")}", + "%{coc#list#status(\"args\")}", + "(%L/%{coc#list#status(\"total\")})", + "%=", + "%#CocListPath# %{coc#list#status(\"cwd\")} %l/%L%*" + ], + "items": { + "types": "string" + }, + "description": "An array of statusline segments that will be used to draw the status line for list windows." + }, + "notification.statusLineProgress": { + "type": "boolean", + "default": true, + "scope": "application", + "description": "Show progress notification in status line, instead of float window/popup." + }, + "notification.border": { + "type": "boolean", + "default": true, + "scope": "application", + "description": "Enable rounded border for notification windows." + }, + "notification.disabledProgressSources": { "type": "array", "default": [], - "description": "Filetypes that should use ctags for outline instead of language server.", + "scope": "application", + "description": "Sources that should be disabled for message progress, use * to disable all message only progresses", "items": { "type": "string" } }, - "cursors.cancelKey": { - "type": "string", - "default": "", - "description": "Key used for cancel cursors session." + "notification.focusable": { + "type": "boolean", + "default": true, + "scope": "application", + "description": "Enable focus by user actions (wincmds, mouse events), neovim only." }, - "cursors.nextKey": { + "notification.highlightGroup": { "type": "string", - "default": "", - "description": "Key used for jump to next cursors position. " + "default": "Normal", + "scope": "application", + "description": "Highlight group of notification dialog." }, - "cursors.previousKey": { - "type": "string", - "default": "", - "description": "Key used for jump to previous cursors position." + "notification.marginRight": { + "type": "integer", + "default": 10, + "scope": "application", + "description": "Margin right to the right of editor window." }, - "tree.closedIcon": { - "type": "string", - "default": "+", - "description": "Closed icon of tree view." + "notification.maxHeight": { + "type": "integer", + "default": 10, + "scope": "application", + "description": "Maximum content height of notification dialog." }, - "tree.openedIcon": { - "type": "string", - "default": "-", - "description": "Opend icon of tree view." + "notification.maxWidth": { + "type": "integer", + "default": 60, + "scope": "application", + "description": "Maximum content width of notification dialog." }, - "tree.key.toggleSelection": { - "type": "string", - "default": "", - "description": "Trigger key to select/unselect item" + "notification.minProgressWidth": { + "type": "integer", + "default": 30, + "scope": "application", + "description": "Minimal with of progress notification." }, - "tree.key.toggle": { - "type": "string", - "default": "t", - "description": "Trigger key to toggle expand state of tree node, does nothing with leaf node." + "notification.timeout": { + "type": "integer", + "default": 10000, + "scope": "application", + "description": "Timeout for auto close notifications, in milliseconds." }, - "tree.key.actions": { + "notification.winblend": { + "type": "integer", + "default": 30, + "minimum": 0, + "maximum": 100, + "scope": "application", + "description": "Winblend option of notification window, neovim only." + }, + "npm.binPath": { "type": "string", - "default": "", - "description": "Trigger key to invoke actions." + "scope": "application", + "default": "npm", + "description": "Command or absolute path to npm or yarn." + }, + "outline.autoPreview": { + "type": "boolean", + "scope": "application", + "default": false, + "description": "Enable auto preview on cursor move." + }, + "outline.autoWidth": { + "type": "boolean", + "scope": "application", + "default": true, + "description": "Automatically increase window width to avoid wrapped lines." + }, + "outline.checkBufferSwitch": { + "type": "boolean", + "scope": "application", + "default": true, + "description": "Recreate outline view after user changed to another buffer on current tab." + }, + "outline.codeActionKinds": { + "type": "array", + "scope": "application", + "default": ["", "quickfix", "refactor"], + "description": "Filter code actions in actions menu by kinds.", + "items": { + "type": "string", + "enum": ["", "quickfix", "refactor", "source"] + } + }, + "outline.detailAsDescription": { + "type": "boolean", + "scope": "application", + "default": true, + "description": "Show detail as description aside with label, when false detail will be shown in tooltip on cursor hold." + }, + "outline.expandLevel": { + "type": "number", + "scope": "application", + "default": 1, + "description": "Expand level of tree nodes." + }, + "outline.followCursor": { + "type": "boolean", + "scope": "application", + "default": true, + "description": "Reveal item in outline tree on cursor hold." + }, + "outline.keepWindow": { + "type": "boolean", + "scope": "application", + "default": false, + "description": "Jump back to original window after outline is shown." }, - "tree.key.collapseAll": { - "type": "string", - "default": "M", - "description": "Trigger key to collapse all tree node." + "outline.previewBorder": { + "type": "boolean", + "scope": "application", + "default": true, + "description": "Use border for preview window." }, - "tree.key.invoke": { + "outline.previewBorderHighlightGroup": { "type": "string", - "default": "", - "description": "Trigger key to invoke default command of current node or selection." + "scope": "application", + "default": "Normal", + "description": "Border highlight group of preview window." }, - "tree.key.close": { - "type": "string", - "default": "", - "description": "Trigger key to dispose the tree and close tree window." + "outline.previewBorderRounded": { + "type": "boolean", + "scope": "application", + "default": false, + "description": "Use rounded border for preview window." }, - "tree.key.activeFilter": { + "outline.previewHighlightGroup": { "type": "string", - "default": "f", - "description": "Trigger key active filter." + "scope": "application", + "default": "Normal", + "description": "Highlight group of preview window." }, - "tree.key.selectNext": { - "type": "string", - "default": "", - "description": "Trigger key to select next item during filter." + "outline.previewMaxWidth": { + "type": "number", + "scope": "application", + "default": 80, + "description": "Max width of preview window." }, - "tree.key.selectPrevious": { - "type": "string", - "default": "", - "description": "Trigger key to select previous item during filter." + "outline.previewWinblend": { + "type": "integer", + "scope": "application", + "default": 0, + "minimum": 0, + "maximum": 100, + "description": "Enables pseudo-transparency by set 'winblend' option of window, neovim only." }, "outline.showLineNumber": { "type": "boolean", + "scope": "application", "default": true, "description": "Show line number of symbols." }, + "outline.sortBy": { + "type": "string", + "scope": "application", + "default": "category", + "description": "Sort method for symbols.", + "enum": ["position", "name", "category"] + }, "outline.splitCommand": { "type": "string", + "scope": "application", "default": "botright 30vs", "description": "Window split command used by outline." }, - "outline.followCursor": { + "outline.switchSortKey": { + "type": "string", + "scope": "application", + "default": "", + "description": "The key used to switch sort method for symbols provider of current tree view." + }, + "outline.togglePreviewKey": { + "type": "string", + "scope": "application", + "default": "p", + "description": "The key used to toggle auto preview feature." + }, + "pullDiagnostic.ignored": { + "type": "array", + "default": [], + "scope": "application", + "description": "Minimatch patterns to match full filepath that should be ignored for pullDiagnostic.", + "items": { + "type": "string" + } + }, + "pullDiagnostic.onChange": { "type": "boolean", "default": true, - "description": "Reveal item in outline tree on cursor hold." + "scope": "language-overridable", + "description": "Whether to pull for diagnostics on document change." }, - "outline.keepWindow": { + "pullDiagnostic.onSave": { "type": "boolean", "default": false, - "description": "Jump back to original window after outline is shown." + "scope": "language-overridable", + "description": "Whether to pull for diagnostics on document save." }, - "outline.sortBy": { - "type": "string", - "default": "category", - "description": "Sort method for symbols.", - "enum": ["position", "name", "category"] + "pullDiagnostic.workspace": { + "type": "boolean", + "default": true, + "scope": "application", + "description": "Whether to pull for workspace diagnostics when possible." }, - "outline.expandLevel": { + "refactor.afterContext": { "type": "number", - "default": 1, - "description": "Expand level of tree nodes." + "scope": "application", + "default": 3, + "description": "Print num lines of trailing context after each match." }, - "outline.checkBufferSwitch": { + "refactor.beforeContext": { + "type": "number", + "scope": "application", + "default": 3, + "description": "Print num lines of leading context before each match." + }, + "refactor.openCommand": { + "type": "string", + "scope": "application", + "description": "Open command for refactor window.", + "default": "vsplit" + }, + "refactor.saveToFile": { "type": "boolean", - "default": true, - "description": "Recreate outline view after user changed to another buffer on current tab." + "scope": "application", + "description": "Save changed buffer to file when write refactor buffer with ':noa wa' command.", + "default": true }, - "outline.codeActionKinds": { + "refactor.showMenu": { + "type": "string", + "scope": "application", + "default": "", + "description": "Refactor buffer local mapping to bring up menu for this chunk." + }, + "semanticTokens.combinedModifiers": { "type": "array", - "default": ["", "quickfix", "refactor"], - "description": "Filter code actions in actions menu by kinds.", + "scope": "language-overridable", + "description": "Semantic token modifiers that should have highlight combined with syntax highlights.", + "default": ["deprecated"], "items": { - "type": "string", - "enum": ["", "quickfix", "refactor", "source"] + "type": "string" } }, - "callHierarchy.openCommand": { - "type": "string", - "default": "edit", - "description": "Open command for callHierarchy tree view." + "semanticTokens.enable": { + "type": "boolean", + "default": false, + "scope": "language-overridable", + "description": "Enable semantic tokens support" }, - "callHierarchy.splitCommand": { - "type": "string", - "default": "botright 30vs", - "description": "Window split command used by callHierarchy tree view." + "semanticTokens.filetypes": { + "type": ["array", "null"], + "scope": "resource", + "description": "Filetypes that enable semantic tokens highlighting or [\"*\"] for any filetype", + "deprecationMessage": "Use semanticTokens.enable configuration with language scope instead, see :h coc-configuration-scope", + "default": null, + "items": { + "type": "string" + } }, - "callHierarchy.enableTooltip": { - "type": "boolean", - "default": true, - "description": "Enable tooltip to show relative filepath of call hierarchy." + "semanticTokens.highlightPriority": { + "type": "number", + "scope": "language-overridable", + "description": "Priority for semantic tokens highlight.", + "default": 2048, + "maximum": 4096 }, - "coc.preferences.enableMessageDialog": { + "semanticTokens.incrementTypes": { + "type": "array", + "scope": "language-overridable", + "description": "Semantic token types that should increase highlight when insert at the start and end position of token.", + "default": ["variable", "string", "parameter"], + "items": { + "type": "string" + } + }, + "signature.enable": { "type": "boolean", - "default": false, - "description": "Enable messages shown in notification dialog." + "scope": "language-overridable", + "description": "Enable show signature help when trigger character typed.", + "default": true }, - "coc.preferences.maxFileSize": { - "type": "string", - "default": "10MB", - "description": "Maximum file size in bytes that coc.nvim should handle, default '10MB'" + "signature.floatConfig": { + "type": "object", + "scope": "application", + "description": "Configure float window style of signature documents.", + "allOf": [{ "$ref": "#/definitions/floatConfig" }], + "additionalProperties": false, + "properties": { + "border": {}, + "rounded": {}, + "highlight": {}, + "borderhighlight": {}, + "title": {}, + "close": {}, + "maxHeight": {}, + "maxWidth": {}, + "winblend": {}, + "focusable": {}, + "shadow": {} + } + }, + "signature.hideOnTextChange": { + "type": "boolean", + "scope": "language-overridable", + "description": "Hide signature float window when text changed on insert mode.", + "default": false }, - "coc.preferences.promptWorkspaceEdit": { + "signature.preferShownAbove": { "type": "boolean", - "description": "Prompt confirm from user when apply workspace edit for unloaded files.", + "scope": "application", + "description": "Show signature help float window above cursor when possible, require restart service on change.", "default": true }, - "coc.preferences.listOfWorkspaceEdit": { + "signature.target": { "type": "string", - "default": "quickfix", - "description": "List should contains changed locations after workspace edit, default to vim's quickfix", - "enum": ["quickfix", "location", "none"] + "scope": "language-overridable", + "description": "Target of signature help, use float when possible by default.", + "default": "float", + "enum": ["float", "echo"] }, - "coc.preferences.useQuickfixForLocations": { + "signature.triggerSignatureWait": { + "type": "integer", + "scope": "language-overridable", + "default": 500, + "minimum": 200, + "maximum": 1000, + "description": "Timeout for trigger signature help, in milliseconds." + }, + "snippet.highlight": { "type": "boolean", - "description": "Use vim's quickfix list for jump locations,\n need restart on change.", + "scope": "resource", + "description": "Use highlight group 'CocSnippetVisual' to highlight placeholders with same index of current one.", "default": false }, - "coc.preferences.extensionUpdateCheck": { - "type": "string", - "default": "never", - "description": "Interval for check extension update, could be daily, weekly, never", - "enum": ["daily", "weekly", "never"] + "snippet.nextPlaceholderOnDelete": { + "type": "boolean", + "scope": "resource", + "description": "Automatically jump to the next placeholder when the current one is completely deleted.", + "default": false }, - "coc.preferences.snippetStatusText": { + "snippet.statusText": { "type": "string", + "scope": "application", "default": "SNIP", "description": "Text shown in statusline to indicate snippet session is activated." }, - "coc.preferences.colorSupport": { + "suggest.acceptSuggestionOnCommitCharacter": { + "type": "boolean", + "default": false, + "scope": "language-overridable", + "description": "Controls whether suggestions should be accepted on commit characters. For example, in JavaScript, the semi-colon (`;`) can be a commit character that accepts a suggestion and types that character." + }, + "suggest.asciiCharactersOnly": { + "type": "boolean", + "description": "Trigger suggest with ASCII characters only", + "scope": "language-overridable", + "default": false + }, + "suggest.asciiMatch": { + "type": "boolean", + "description": "Convert unicode characters to ascii for match", + "scope": "language-overridable", + "default": true + }, + "suggest.autoTrigger": { + "type": "string", + "scope": "language-overridable", + "default": "always", + "description": "How should completion be triggered", + "enum": ["always", "trigger", "none"] + }, + "suggest.completionItemKindLabels": { + "type": "object", + "default": {}, + "scope": "application", + "description": "Set custom labels to completion items' kinds.", + "properties": { + "text": { "type": "string" }, + "method": { "type": "string" }, + "function": { "type": "string" }, + "constructor": { "type": "string" }, + "field": { "type": "string" }, + "variable": { "type": "string" }, + "class": { "type": "string" }, + "interface": { "type": "string" }, + "module": { "type": "string" }, + "property": { "type": "string" }, + "unit": { "type": "string" }, + "value": { "type": "string" }, + "enum": { "type": "string" }, + "keyword": { "type": "string" }, + "snippet": { "type": "string" }, + "color": { "type": "string" }, + "file": { "type": "string" }, + "reference": { "type": "string" }, + "folder": { "type": "string" }, + "enumMember": { "type": "string" }, + "constant": { "type": "string" }, + "struct": { "type": "string" }, + "event": { "type": "string" }, + "operator": { "type": "string" }, + "typeParameter": { "type": "string" }, + "default": { "type": "string" } + }, + "additionalProperties": false + }, + "suggest.defaultSortMethod": { + "type": "string", + "description": "Default sorting behavior for suggested completion items.", + "default": "length", + "scope": "language-overridable", + "enum": ["length", "alphabetical", "none"] + }, + "suggest.detailField": { + "type": "string", + "scope": "application", + "default": "preview", + "description": "Where to show the detail text of CompleteItem from LS.", + "enum": ["abbr", "preview"] + }, + "suggest.detailMaxLength": { + "type": "number", + "scope": "application", + "description": "Max length of detail that should be shown in popup menu.", + "deprecationMessage": "Use suggest.labelMaxLength instead.", + "default": 100 + }, + "suggest.enableFloat": { + "type": "boolean", + "scope": "language-overridable", + "description": "Enable float window with documentation aside with popupmenu.", + "default": true + }, + "suggest.enablePreselect": { "type": "boolean", - "description": "Enable color highlight if language server support it.", + "scope": "application", + "description": "Enable preselect feature of LSP, works when suggest.noselect is false.", "default": true }, - "coc.preferences.semanticTokensHighlights": { + "suggest.filterGraceful": { "type": "boolean", - "description": "Enable semanticTokens highlight if language server support it.", + "description": "Controls whether filtering and sorting suggestions accounts for small typos.", + "scope": "language-overridable", "default": true }, - "coc.preferences.currentFunctionSymbolAutoUpdate": { - "type": "boolean", - "description": "Automatically update the value of b:coc_current_function on CursorHold event", - "default": false + "suggest.floatConfig": { + "type": "object", + "scope": "application", + "description": "Configure style of popup menu and documentation window of completion.", + "allOf": [{ "$ref": "#/definitions/floatConfig" }], + "additionalProperties": false, + "properties": { + "border": {}, + "rounded": {}, + "highlight": {}, + "borderhighlight": {}, + "maxWidth": {}, + "winblend": {}, + "shadow": {} + } + }, + "suggest.formatItems": { + "type": "array", + "scope": "application", + "items": { + "enum": ["abbr", "menu", "kind", "shortcut"] + }, + "contains": { + "enum": ["abbr"] + }, + "uniqueItems": true, + "description": "Items shown in popup menu in order.", + "default": ["abbr", "menu", "kind", "shortcut"] + }, + "suggest.highPrioritySourceLimit": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "scope": "language-overridable", + "description": "Max items count for source priority bigger than or equal to 90." + }, + "suggest.insertMode": { + "type": "string", + "scope": "language-overridable", + "default": "replace", + "description": "Controls whether words are overwritten when accepting completions.", + "enum": ["insert", "replace"] }, - "coc.preferences.formatOnSaveFiletypes": { + "suggest.ignoreRegexps": { "type": "array", - "default": [], - "description": "Filetypes that should run format on save.", + "scope": "language-overridable", "items": { "type": "string" - } - }, - "coc.preferences.enableFloatHighlight": { - "type": "boolean", - "description": "Enable highlight for floating window.", - "default": true + }, + "description": "Regexps to ignore when trigger suggest", + "default": [] }, - "coc.preferences.rootPatterns": { + "suggest.invalidInsertCharacters": { "type": "array", - "default": [".git", ".hg", ".projections.json"], - "description": "Root patterns to resolve workspaceFolder from parent folders of opened files, resolved from up to down.", "items": { "type": "string" - } - }, - "coc.preferences.watchmanPath": { - "type": "string", - "description": "executable path for https://facebook.github.io/watchman/, detected from $PATH by default", - "default": null + }, + "scope": "application", + "description": "Invalid character for strip valid word when inserting text of complete item.", + "default": ["\r", "\n"] }, - "coc.preferences.jumpCommand": { - "anyOf": [ - { - "type": "string", - "enum": [ - "edit", - "split", - "vsplit", - "tabe", - "drop", - "tab drop", - "pedit" - ] - }, - { "type": "string", "minimum": 1 } - ], - "description": "Command used for location jump, like goto definition, goto references etc. Can be also a custom command that gives file as an argument.", - "default": "edit" + "suggest.labelMaxLength": { + "type": "number", + "scope": "application", + "description": "Max length of abbr that shown as label of complete item.", + "default": 200 }, - "coc.preferences.messageLevel": { - "type": "string", - "description": "Message level for filter echoed messages, could be 'more', 'warning' and 'error'", - "default": "more", - "enum": ["more", "warning", "error"] + "suggest.languageSourcePriority": { + "type": "number", + "default": 99, + "scope": "language-overridable", + "description": "Priority of language sources." }, - "coc.preferences.bracketEnterImprove": { + "suggest.localityBonus": { "type": "boolean", - "description": "Improve enter inside bracket `<> {} [] ()` by add new empty line below and place cursor to it. Works with `coc#on_enter()`", + "description": "Controls whether sorting favors words that appear close to the cursor.", + "scope": "language-overridable", "default": true }, - "coc.preferences.formatOnType": { + "suggest.lowPrioritySourceLimit": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "scope": "language-overridable", + "description": "Max items count for source priority lower than 90." + }, + "suggest.maxCompleteItemCount": { + "type": "number", + "default": 256, + "scope": "language-overridable", + "description": "Maximum number of complete items shown in vim" + }, + "suggest.minTriggerInputLength": { + "type": "integer", + "default": 1, + "scope": "language-overridable", + "description": "Minimal input length for trigger completion, default 1" + }, + "suggest.noselect": { "type": "boolean", - "description": "Set to true to enable formatting on typing", + "scope": "application", + "description": "Not make vim select first item on popupmenu shown", "default": false }, - "coc.preferences.formatOnTypeFiletypes": { - "type": "array", - "default": [], - "description": "Filetypes that should run format on typing. Only take effect when `coc.preferences.formatOnType` set `true`", - "items": { - "type": "string" + "suggest.preferCompleteThanJumpPlaceholder": { + "type": "boolean", + "description": "Confirm completion instead of jump to next placeholder when completion is activated.", + "scope": "resource", + "default": false + }, + "suggest.pumFloatConfig": { + "type": ["object", "null"], + "scope": "application", + "description": "Configure style of popup menu, suggest.floatConfig is used when not specified.", + "allOf": [{ "$ref": "#/definitions/floatConfig" }], + "additionalProperties": false, + "default": null, + "properties": { + "border": {}, + "rounded": {}, + "highlight": {}, + "borderhighlight": {}, + "winblend": {}, + "shadow": {} } }, - "coc.preferences.floatActions": { + "suggest.removeDuplicateItems": { "type": "boolean", - "description": "Set to false to disable float/popup support for actions menu, won't work on vim without float or popup window support.", - "default": true + "description": "Remove completion items with duplicated word for all sources, snippet items are excluded.", + "scope": "language-overridable", + "default": false }, - "coc.preferences.promptInput": { + "suggest.reversePumAboveCursor": { "type": "boolean", - "description": "Use prompt buffer in float window for user input.", - "default": true + "scope": "application", + "description": "Reverse order of complete items when pum shown above cursor.", + "default": false }, - "coc.preferences.enableMarkdown": { - "type": "boolean", - "description": "Tell the language server that markdown text format is supported, note that markdown text may not rendered as expected.", - "default": true + "suggest.selection": { + "type": "string", + "scope": "application", + "default": "first", + "description": "Controls how suggestions are pre-selected when showing the suggest list.", + "enum": ["first", "recentlyUsed", "recentlyUsedByPrefix"] }, - "coc.preferences.excludeImageLinksInMarkdownDocument": { - "type": "boolean", - "description": "Exclude image links from markdown text in float window.", - "default": true + "suggest.snippetIndicator": { + "type": "string", + "default": "~", + "scope": "application", + "description": "The character used in abbr of complete item to indicate the item could be expand as snippet." }, - "coc.preferences.silentAutoupdate": { + "suggest.snippetsSupport": { "type": "boolean", - "description": "Not open split window with update status when performing auto update.", + "scope": "language-overridable", + "description": "Set to false to disable snippets support of completion.", "default": true }, - "coc.preferences.willSaveHandlerTimeout": { + "suggest.timeout": { "type": "integer", - "default": 500, - "minimum": 200, - "maximum": 5000, - "description": "Will save handler timeout" + "default": 5000, + "minimum": 500, + "maximum": 15000, + "scope": "language-overridable", + "description": "Timeout for completion, in milliseconds." }, - "coc.source.around.enable": { + "suggest.triggerAfterInsertEnter": { "type": "boolean", - "default": true + "description": "Trigger completion after InsertEnter, auto trigger should be 'always' to enable this option", + "scope": "language-overridable", + "default": false + }, + "suggest.triggerCompletionWait": { + "type": "integer", + "default": 0, + "minimum": 0, + "maximum": 50, + "scope": "language-overridable", + "description": "Wait time between text change and completion start, cancel completion when text changed during wait." }, - "coc.source.around.firstMatch": { + "suggest.virtualText": { "type": "boolean", - "description": "Filter complete items by first letter strict match.", - "default": true + "scope": "application", + "description": "Show virtual text for insert word of selected item, requires neovim >= 0.5.0 or vim >= 9.0.0067", + "default": false }, - "coc.source.around.shortcut": { + "tree.closedIcon": { "type": "string", - "default": "A" + "scope": "application", + "default": "+", + "description": "Closed icon of tree view." }, - "coc.source.around.priority": { - "type": "integer", - "default": 1 + "tree.key.actions": { + "type": "string", + "scope": "application", + "default": "", + "description": "Trigger key to invoke actions." }, - "coc.source.around.disableSyntaxes": { - "type": "array", - "default": [], - "items": { - "type": "string" - } + "tree.key.activeFilter": { + "type": "string", + "scope": "application", + "default": "f", + "description": "Trigger key active filter." }, - "coc.source.buffer.enable": { - "type": "boolean", - "default": true + "tree.key.close": { + "type": "string", + "scope": "application", + "default": "", + "description": "Trigger key to dispose the tree and close tree window." }, - "coc.source.buffer.shortcut": { + "tree.key.collapseAll": { "type": "string", - "default": "B" + "scope": "application", + "default": "M", + "description": "Trigger key to collapse all tree node." }, - "coc.source.buffer.priority": { - "type": "integer", - "default": 1 + "tree.key.invoke": { + "type": "string", + "scope": "application", + "default": "", + "description": "Trigger key to invoke default command of current node or selection." }, - "coc.source.buffer.firstMatch": { - "type": "boolean", - "description": "Filter complete items by first letter strict match.", - "default": true + "tree.key.selectNext": { + "type": "string", + "scope": "application", + "default": "", + "description": "Trigger key to select next item during filter." }, - "coc.source.buffer.ignoreGitignore": { + "tree.key.selectPrevious": { + "type": "string", + "scope": "application", + "default": "", + "description": "Trigger key to select previous item during filter." + }, + "tree.key.toggle": { + "type": "string", + "scope": "application", + "default": "t", + "description": "Trigger key to toggle expand state of tree node, does nothing with leaf node." + }, + "tree.key.toggleSelection": { + "type": "string", + "scope": "application", + "default": "", + "description": "Trigger key to select/unselect item" + }, + "tree.openedIcon": { + "type": "string", + "scope": "application", + "default": "-", + "description": "Opened icon of tree view." + }, + "typeHierarchy.enableTooltip": { "type": "boolean", + "scope": "application", "default": true, - "description": "Ignore git ignored files for buffer words" + "description": "Enable tooltip to show relative filepath of type hierarchy." }, - "coc.source.buffer.disableSyntaxes": { + "typeHierarchy.openCommand": { + "type": "string", + "scope": "application", + "default": "edit", + "description": "Open command for type hierarchy tree view." + }, + "typeHierarchy.splitCommand": { + "type": "string", + "scope": "application", + "default": "botright 30vs", + "description": "Window split command used by type hierarchy tree view." + }, + "workspace.rootPatterns": { "type": "array", - "default": [], + "default": [".git", ".hg", ".projections.json"], + "scope": "application", + "description": "Root patterns to resolve workspaceFolder from parent folders of opened files, resolved from up to down.", "items": { "type": "string" } }, - "coc.source.file.enable": { - "type": "boolean", - "default": true - }, - "coc.source.file.shortcut": { - "type": "string", - "default": "F" - }, - "coc.source.file.priority": { - "type": "integer", - "default": 10 - }, - "coc.source.file.disableSyntaxes": { + "workspace.bottomUpFiletypes": { "type": "array", "default": [], + "scope": "application", + "description": "Filetypes that should have workspace folder should resolved from base directory of file, or [\"*\"] for any filetype.", "items": { "type": "string" } }, - "coc.source.file.triggerCharacters": { + "workspace.ignoredFiletypes": { "type": "array", - "default": ["/", "\\"], + "default": [], + "scope": "application", + "description": "Filetypes that should be ignored for workspace folder resolve.", "items": { "type": "string" } }, - "coc.source.file.trimSameExts": { + "workspace.ignoredFolders": { "type": "array", - "default": [".ts", ".js"], - "description": "Trim same extension on file completion", + "default": ["$HOME"], + "scope": "application", + "description": "List of folders that should not be resolved as workspace folder, environment variables and minimatch patterns can be used.", "items": { "type": "string" } }, - "coc.source.file.ignoreHidden": { + "workspace.openOutputCommand": { + "type": "string", + "default": "vs", + "scope": "resource", + "description": "Command used to open output channel." + }, + "workspace.openResourceCommand": { + "type": "string", + "default": "tab drop", + "scope": "application", + "description": "Command to open files that not loaded, load files as hidden buffers when empty." + }, + "workspace.workspaceFolderCheckCwd": { "type": "boolean", "default": true, - "description": "Ignore completion for hidden files" + "scope": "application", + "description": "Whether the current working directory should be used first when checking patterns match for workspace folder." }, - "coc.source.file.ignorePatterns": { - "type": "array", - "default": [], - "description": "Ignore patterns of matcher", - "items": { - "type": "string" - } + "workspace.workspaceFolderFallbackCwd": { + "type": "boolean", + "default": true, + "scope": "application", + "description": "Use current working directory as workspace folder when no root patterns resolved." }, "languageserver": { "type": "object", "default": {}, - "description": "Dictionary of languageservers, key is used as id of languageserver.", + "scope": "resource", + "description": "Dictionary of languageservers, key is used as id of languageserver, restart coc.nvim required after change.", "patternProperties": { "^[_a-zA-Z]+$": { "oneOf": [ diff --git a/vim-config/plugins/coc.nvim/doc/coc-api.txt b/vim-config/plugins/coc.nvim/doc/coc-api.txt new file mode 100644 index 00000000..a8e0706c --- /dev/null +++ b/vim-config/plugins/coc.nvim/doc/coc-api.txt @@ -0,0 +1,414 @@ +*coc-api.txt* NodeJS client for Vim & Neovim. + +CONTENTS + +Vim sources |coc-api-vim-source| +Extension introduction |coc-api-intro| +Extension package json |coc-api-json| +Single file extensions |coc-api-single| +Create custom Extensions |coc-api-extension| +Debug extensions |coc-api-debug| + +============================================================================== + +This is the guide for extend coc.nvim by create vim completion sources and +coc.nvim extensions. + +------------------------------------------------------------------------------ +VIM SOURCES *coc-api-vim-source* + +During initialization, coc.nvim searches vim's |runtimepath| for file pattern +`autoload/coc/source/${name}.vim`, matched files would be loaded as vim +completion sources. + +Note: LSP completion features like `TextEdit`, `additionalTextEdits`, +`command` are not supported by vim sources, use the NodeJS API +`languages.registerCompletionItemProvider` for LSP completion. + +For example, create a file `autoload/coc/source/email.vim` inside your plugin +folder. With code: +> + " vim source for emails + function! coc#source#email#init() abort + return { + \ 'priority': 9, + \ 'shortcut': 'Email', + \ 'triggerCharacters': ['@'] + \} + endfunction + + function! coc#source#email#complete(option, cb) abort + let items = ['foo@gmail.com', 'bar@yahoo.com'] + call a:cb(items) + endfunction +< +`init` and `complete` are required functions for vim sources, error message +will be shown when not exists. + +Source option:~ + + The source option object is returned by `coc#source#{name}#init` + function, available properties: + + โ€ข shortcut: The shortcut characters shown in popup menu, first three + characters from the source name would be used when not exists. + โ€ข priority: The priority of source, default to `9`. + โ€ข filetypes: Array of filetype names this source should be triggered + by. Available for all filetypes when not exists. + โ€ข firstMatch: When is truthy value, only the completion item that has the + first letter matching the user input will be shown. + โ€ข triggerCharacters: Trigger characters for this source, default to `[]`. + โ€ข triggerOnly: The source should only be triggered by trigger characters, + when trigger characters is false or empty, the source would only be + triggered by api |coc#start()|. + โ€ข isSnippet: All complete items returned by `complete` are snippets, + which would have snippet indicator text added to the label in popup + menu. The "isSnippet" property of completion item override this + option. + + All options are optional. + +Source configurations:~ + + Vim sources register |coc-configuration| for allow the user to customize the + source behavior. + + โ€ข `coc.source.${name}.enable` Enable the source, default to `true`. + โ€ข `coc.source.${name}.disableSyntaxes` Disabled syntax names when trigger + completion. + โ€ข `coc.source.${name}.firstMatch` Default to "firstMatch" of source option. + โ€ข `coc.source.${name}.priority` Default to "priority" of source option. + โ€ข `coc.source.${name}.shortcut` Default to "shortcut" of source option. + โ€ข `coc.source.${name}.filetypes` Default to "filetypes" of source option. + +Complete function:~ + + The complete function is called with complete option as the first argument + and a callback function as the second argument, the callback function should + be called with list of complete item or `v:null` synchronously or + asynchronously. + + Note: synchronously compute complete items blocks vim's operation. + Note: Error during completion is not thrown, use |:CocOpenLog| to check the + error log. + + Complete option have following properties: + + โ€ข bufnr: Current buffer number. + โ€ข line: Content line when trigger completion. + โ€ข col: Start col of completion, start col of the keywords before cursor by + default, 0 based. + โ€ข input: Input text between start col and curosr col. + โ€ข filetype: Filetype of current buffer. + โ€ข filepath: Fullpath of current buffer. + โ€ข changedtick: b:changedtick value when trigger completion. + โ€ข triggerCharacter: The character which trigger the completion, could be + empty string. + โ€ข colnr: Cursor col when trigger completion, 1 based. + โ€ข linenr: Line number of curosr, 1 based. + + Complete items extends vim's |complete-items| with the following properties: + + โ€ข deprecated: The complete item would be rendered with strike through + highlight when truthy. + โ€ข labelDetails: Additional details for a completion item label, which have + optional `detail` and/or `description` text. + โ€ข sortText: A string that should be used when comparing this item with other + items, word is used when not exists. + โ€ข filterText: A string that should be used when filtering a set of + complete items, word is used when not exists. + โ€ข insertText: The text to insert, could be snippet text, word is used when + not exists. + โ€ข isSnippet: The text to insert is snippet when is truthy value, when + truthy and `on_complete` not provided by vim source, the `insertText` is + expanded as textmate snippet when confirm completion. + โ€ข documentation: Array of `Documentation`, which provide `filetype` and + `content` text to be displayed in preview window. + + Only the "word" property is mandatory for complete items. + +Optional functions:~ + + The vim source could provide some optional functions which would be invoked + by coc.nvim: + + โ€ข `coc#source#{name}#get_startcol(option)` Used to alter the start col of + completion, the returned col must <= current curosr col. + โ€ข `coc#source#{name}#on_complete(item)` Called with selected complete item + when user confirm the completion by |coc#pum#confirm()| or + |coc#_select_confirm()|. Normally used for apply nesessary edits to the + buffer. + โ€ข `coc#source#{name}#on_enter(option)` Called on |BufEnter| with option + contains: + โ€ข bufnr: The buffer number. + โ€ข uri: The uri text of buffer. + โ€ข languageId: The mapped filetype of buffer, see |coc-document-filetype|. + โ€ข `coc#source#{name}#refresh()` Called when the user trigger refresh action + for the source. + +------------------------------------------------------------------------------ +EXTENSION INTRODUCTION *coc-api-intro* + +Every extension of coc.nvim has a JavaScript entry file, that file is loaded +by NodeJS API `vm.runInContext` with an identical global context (like iframe +in browser). + +The JavaScript entry file should be a CommonJS module with `activate` method +exported, and `require('coc.nvim')` can be used to access modules exported by +coc.nvim, for example: +> + const {window} = require('coc.nvim') + exports.activate = async context => { + window.showInformationMessage('extension activated') + } +< +When `exports.deactivate` is exported from the JavaScript entry file as a +function, it would be called on extension deactivate. + +Limitation of extension context:~ + +Some methods/properties provided by NodeJS can't be used inside extension +context, including: + + โ€ข `process.reallyExit()` + โ€ข `process.abort()` + โ€ข `process.setuid()` + โ€ข `process.setgid()` + โ€ข `process.setgroups()` + โ€ข `process._fatalException()` + โ€ข `process.exit()` + โ€ข `process.kill()` + โ€ข `process.umask()` Could only be used to get umask value. + โ€ข `process.chdir()` Could be called, but no effect at all. + +Some globals may can't be accessed directly, for example `TextDecoder`, +`TextEncoder`, use `globalThis` like `globalThis.TextDecoder` to access them. + + *coc-api-console* + +Stdin and stdout of the NodeJS process is used for communication between vim +and NodeJS process, use the methods related to `process.stdin` and +`process.stdout` may cause unexpected behavior. However, some methods of +`console` are provided for debugging purpose. + +Messages from `console` of extension would be redirected to the log file +|:CocOpenLog|. Available methods: + + โ€ข `debug(...args: any[])` Write debug message to the log file. + โ€ข `log(...args: any[])` Write info message to the log file. + โ€ข `info(...args: any[])` Write info message to the log file. + โ€ข `error(...args: any[])` Write error message to the log file. + โ€ข `warn(...args: any[])` Write warning message to the log file. + +Check the full NodeJS API interfaces at: +https://github.com/neoclide/coc.nvim/blob/master/typings/index.d.ts + +------------------------------------------------------------------------------ +EXTENSION PACKAGE JSON *coc-api-json* + +The package.json file inside extension root defines the meta data of the +extension. For example: +> + { + "name": "coc-my-extension", + "version": "1.0.0", + "main": "lib/index.js", + "engines": { + "coc": "^0.0.82" + }, + "activationEvents": [ + "*", + ], + "contributes": { + "rootPatterns": [{ + "filetype": "myfiletype", + "patterns": [ + "project_root.json" + ] + }], + "commands": [{ + "title": "My command", + "category": "myextension", + "id": "myextension.myCommand" + }], + "configuration": { + "type": "object", + "properties": { + "myextension.enable": { + "type": "boolean", + "default": true, + "scope": "resource", + "description": "Enable running of my extension." + } + } + } + } + } +< +Required properties of package.json: + + โ€ข name: The unique name of extension, to publish the extension, the name + should not be taken by exists packages at https://www.npmjs.com/ + โ€ข version: The semver version of extension. + โ€ข engines: Should have `coc` property with minimal required coc.nvim version. + +The `main` property contains the relative filepath of the javascript entry +file, `index.js` would be used when not exists. + +The `activationEvents` property tell coc.nvim when to activate the extension, +when the property not exists or `*` is included, the extension would be +activated during coc.nvim initialize. Other possible events: + + โ€ข onLanguage: Activate the extension when document of specific languageId + exists, ex: `"onLanguage:vim"` activate the extension when there's buffer with + languageId as vim loaded. + โ€ข onFileSystem: Activate the extension when document with custom schema + loaded, ex: `"onFileSystem:fugitive"` activate the extension when there's + buffer with schema `fugitive` loaded. + โ€ข onCommand: activate the extension when specific command invoked by user, + ex: `"onCommand:tsserver.reloadProjects"` + โ€ข workspaceContains: activate the extension when the glob pattern match one + of the file in current workspace folder, ex: + `"workspaceContains:**/package.json"` + +Optional `contributes` property contains the meta data that contributed to +coc.nvim, inclduing: + + โ€ข rootPatterns: The patterns to resolve |coc-workspace-folders| for + associated filetype. + โ€ข commands: List of commands with `id` and `title` that can be invoked by + |:CocCommand|. + โ€ข configuration: Contains `properties` object or a list of configurations + that each one provide `properties` objects which define the configuration + properties contributed by this extension. + +The `contributes` property could also contains other properties that used by +other extensions, for example: the `jsonValidation` property could be used by +coc-json. + +It's recommended to install `coc-json` for json intellisense support. + +------------------------------------------------------------------------------ +SINGLE FILE EXTENSIONS *coc-api-single* + +The easiest way to access the NodeJS API is make use of single file +extensions. + +All Javascript files that ends with `.js` inside the folder "coc-extensions" +under |g:coc_config_home| are considered as coc extensions. + +The javascript files would be loaded during coc.nvim initialize by default. + +To contribute extension meta data, create file `${name}.json` aside with +`${name}.js`, the json file works the same as package.json of extension +|coc-api-json|, except that only `activationEvents` and `contributes` +properties are used. + +Single file extensions can't be managed by extensions list. + +------------------------------------------------------------------------------ +CREATE CUSTOM EXTENSIONS *coc-api-extension* + +To make an extension installable by |:CocInstall|, the easiest way is make use +of https://github.com/fannheyward/create-coc-extension. Simply run command +> + npm init coc-extension [extension-name] +< +or +> + yarn create coc-extension [extension-name] +< +in terminal and you will be prompted for create a javascript/typescript +extension step by step. + +To manually create an extension, follow these step: + + โ€ข Create an empty folder and goto that folder. + โ€ข Create the package.json file |coc-api-json|. + โ€ข Create a javascript file with name `index.js` and write code. + โ€ข Add the created folder to your vim's runtimepath by + add `set runtimepath^=/path/to/folder` in your vimrc. + +Recommended steps: + + โ€ข Install types of NodeJS and coc.nvim by terminal command + `yarn install @types/node@14.14 coc.nvim` in extension folder. + โ€ข Bundle the javascript files when using multiple node dependencies by + esbuild to save the time of installation. A typical build script looks + like: +> + async function start() { + await require('esbuild').build({ + entryPoints: ['src/index.ts'], + bundle: true, + minify: process.env.NODE_ENV === 'production', + sourcemap: process.env.NODE_ENV === 'development', + mainFields: ['module', 'main'], + external: ['coc.nvim'], + platform: 'node', + target: 'node14.14', + outfile: 'lib/index.js' + }) + } + + start().catch(e => { + console.error(e) + }) +< +------------------------------------------------------------------------------ +DEBUG EXTENSIONS *coc-api-debug* + +Uncaught errors:~ + +When an uncaught error raised on the NodeJS process, the error message would +be send to vim through stderr, and echoed by vim (unless +|g:coc_disable_uncaught_error| is enabeld). + +The error messages are not stored by vim's message history, use +|:CocPrintErrors| to show previous errors. + +When error happens on the vim side, the promise would be rejected when sending +request to vim, for notifications, vim would send `nvim_error_event` to the +NodeJS process, and the node-client would create error log for it. + +Use the log file:~ + +โ€ข Configure `NVIM_COC_LOG_LEVEL` to `trace` in vimrc: + `let $NVIM_COC_LOG_LEVEL='trace'` +โ€ข Configure `NVIM_COC_LOG_FILE` to a fixed in vimrc: + `let $NVIM_COC_LOG_FILE=/tmp/coc.log`, otherwise it would be different for + each vim instance. +โ€ข Use |coc-api-console| to add console statements in javascript/typescript +code and compile the extension when needed. +โ€ข Tail the log file by `tail` command and make the issue happen. + +Add source map support:~ + +When the javascript code is bundled by esbuild, it would be useful to have +correct source map support for the error stack. + +โ€ข Install global source-map-support by `npm install -g source-map-support` +โ€ข Find out the npm root by `npm root -g` +โ€ข Load source-map-support with coc.nvim by append arguments to node in vimrc: + `let g:coc_node_args = ['-r', '/path/to/npm/root/source-map-support/register']` + Repalce the part `/path/to/npm/root` with result from `npm root -g` terminal + command. + +Note: the source-map-support module slows down the coc.nvim initialization. + +Debug javascript code in chrome:~ + +โ€ข Add `let g:coc_node_args = ['--nolazy', '--inspect-brk=5858']` +โ€ข Open vim and you will get the error message indicate that the debugger is + listening. +โ€ข Open Chrome browser with url chrome://inspect/#devices, configure + the `Target discovery settings` and you will get the remote target to + inspect. +โ€ข Click the inspect link to open the devtools. +โ€ข Click the sources label to debug javascript code. + +Other debugger clients can be used as well, see: +https://nodejs.org/en/docs/guides/debugging-getting-started/ + +============================================================================== +vim:tw=78:sta:noet:ts=8:sts=0:ft=help:fen: diff --git a/vim-config/plugins/coc.nvim/doc/coc-config.txt b/vim-config/plugins/coc.nvim/doc/coc-config.txt new file mode 100644 index 00000000..6c8ef737 --- /dev/null +++ b/vim-config/plugins/coc.nvim/doc/coc-config.txt @@ -0,0 +1,1771 @@ +*coc-config.txt* NodeJS client for Vim & Neovim. + +CONTENTS + +Call hierarchy |coc-config-callHierarchy| +CodeLens |coc-config-codeLens| +Colors |coc-config-colors| +Completion |coc-config-suggest| +Cursors |coc-config-cursors| +Diagnostics |coc-config-diagnostic| +Dialog |coc-config-dialog| +Document highlight |coc-config-documentHighlight| +Float factory |coc-config-floatFactory| +Hover |coc-config-hover| +Http |coc-config-http| +Inlay hint |coc-config-inlayHint| +Links |coc-config-links| +List |coc-config-list| +Notification |coc-config-notification| +Npm |coc-config-npm| +Outline |coc-config-outline| +Pull diagnostics |coc-config-pullDiagnostic| +Refactor |coc-config-refactor| +Semantic tokens |coc-config-semanticTokens| +Signature |coc-config-signature| +Tree |coc-config-tree| +Type hierarchy |coc-config-typeHierarchy| +Workspace |coc-config-workspace| +Preferences |coc-config-preferences| +Float |coc-config-float| +Language server |coc-config-languageserver| + +============================================================================== +BUILTIN CONFIGURATIONS *coc-config* + +Builtin configurations of coc.nvim, it's recommended to use `coc-json` +extension for completion and validation support. + +------------------------------------------------------------------------------ +CallHierarchy~ + *coc-config-callHierarchy* +"callHierarchy.enableTooltip" *coc-config-callHierarchy-enableTooltip* + + Enable tooltip to show relative filepath of call hierarchy item. + + Scope: `application`, default: `true` + +"callHierarchy.openCommand" *coc-config-callHierarchy-openCommand* + + Open command for call hierarchy tree view. + + Scope: `application`, default: `"edit"` + +"callHierarchy.splitCommand" *coc-config-callHierarchy-splitCommand* + + Window split command used by call hierarchy tree view. + + Scope: `application`, default: `"botright 30vs"` + +------------------------------------------------------------------------------ +CodeLens~ + *coc-config-codeLens* +"codeLens.enable" *coc-config-codeLens-enable* + + Enable codeLens feature, require neovim with set virtual text feature. + + Scope: `language-overridable`, default: `false` + +"codeLens.position" *coc-config-codeLens-position* + + Position of codeLens, requires nvim >= 0.6.0. + + Scope: `resource`, default: `"top"` + +"codeLens.separator" *coc-config-codeLens-separator* + + Separator text for codeLens in virtual text. + + Scope: `resource`, default: `""` + +"codeLens.subseparator" *coc-config-codeLens-subseparator* + + Subseparator between codeLenses in virtual text. + + Scope: `resource`, default: `" | "` + +------------------------------------------------------------------------------ +Colors~ + *coc-config-colors* +"colors.enable" *coc-config-colors-enable* + + Enable colors highlight feature, for termainal vim, 'termguicolors' + option should be enabled and the termainal support gui colors. + + Scope: `language-overridable`, default: `false` + +"colors.highlightPriority" *coc-config-colors-highlightPriority* + + Priority for colors highlights, works on vim8 and neovim >= 0.6.0. + + Scope: `application`, default: `1000` + +------------------------------------------------------------------------------ +Cursors~ + *coc-config-cursors* +"cursors.cancelKey" *coc-config-cursors-cancelKey* + + Key used for cancel cursors session. + + Scope: `application`, default: `""` + +"cursors.nextKey" *coc-config-cursors-nextKey* + + Key used for jump to next cursors position. + + Scope: `application`, default: `""` + +"cursors.previousKey" *coc-config-cursors-previousKey* + + Key used for jump to previous cursors position. + + Scope: `application`, default: `""` + +"cursors.wrapscan" *coc-config-cursors-wrapscan* + + Searches wrap around the first or last cursors range. + + Scope: `application`, default: `true` + +------------------------------------------------------------------------------ +Diagnostic~ + *coc-config-diagnostic* +"diagnostic.autoRefresh" *coc-config-diagnostic-autoRefresh* + + Enable automatically refresh diagnostics, use diagnosticRefresh action + when it's disabled. + + Scope: `language-overridable`, default: `true` + +"diagnostic.checkCurrentLine" *coc-config-diagnostic-checkCurrentLine* + + When enabled, show all diagnostics of current line if there are none at + the current position. + + Scope: `language-overridable`, default: `false` + +"diagnostic.displayByAle" *coc-config-diagnostic-displayByAle* + + Use Ale for display diagnostics in vim, will disable coc for display + diagnostics, restart required on change. + + Scope: `language-overridable`, default: `false` + +"diagnostic.enable" *coc-config-diagnostic-enable* + + Set to false to disable diagnostic display. + + Scope: `language-overridable`, default: `true` + +"diagnostic.enableHighlightLineNumber" *coc-config-diagnostic-enableHighlightLineNumber* + + Enable highlighting line numbers for diagnostics, only works with neovim. + + Scope: `application`, default: `true` + +"diagnostic.enableMessage" *coc-config-diagnostic-enableMessage* + + When to enable show messages of diagnostics. + + Scope: `application`, default: `"always"` + +"diagnostic.enableSign" *coc-config-diagnostic-enableSign* + + Enable signs for diagnostics. + + Scope: `language-overridable`, default: `true` + +"diagnostic.errorSign" *coc-config-diagnostic-errorSign* + + Text of error sign. + + Scope: `application`, default: `">>"` + +"diagnostic.filetypeMap" *coc-config-diagnostic-filetypeMap* + + A map between buffer filetype and the filetype assigned to diagnostics. + To syntax highlight diagnostics with their parent buffer type use `" + default": "bufferType"`. + + Scope: `application`, default: `{}` + +"diagnostic.floatConfig" *coc-config-diagnostic-floatConfig* + + Configuration of floating window/popup for diagnostic messages, see + |coc-config-float|. + + Scope: `application`, default: `null` + +"diagnostic.format" *coc-config-diagnostic-format* + + Define the diagnostic format that shown in float window or echoed, + available parts: source, code, severity, message. + + Scope: `language-overridable`, default: `"%message (%source%code)"` + +"diagnostic.highlightLimit" *coc-config-diagnostic-highlightLimit* + + Limit count for highlighted diagnostics, too many diagnostic highlights + could make vim stop responding. + + Scope: `language-overridable`, default: `1000` + +"diagnostic.highlightPriority" *coc-config-diagnostic-highlightPriority* + + Priority for diagnostic highlights, works on vim8 and neovim >= 0.6.0. + + Scope: `language-overridable`, default: `4096` + +"diagnostic.hintSign" *coc-config-diagnostic-hintSign* + + Text of hint sign. + + Scope: `application`, default: `">>"` + +"diagnostic.infoSign" *coc-config-diagnostic-infoSign* + + Text of info sign. + + Scope: `application`, default: `">>"` + +"diagnostic.level" *coc-config-diagnostic-level* + + Used for filter diagnostics by diagnostic severity. + + Scope: `resource`, default: `"hint"` + +"diagnostic.locationlistLevel" *coc-config-diagnostic-locationlistLevel* + + Filter diagnostics in locationlist. + + Scope: `language-overridable`, default: `null` + +"diagnostic.locationlistUpdate" *coc-config-diagnostic-locationlistUpdate* + + Update locationlist on diagnostics change, only works with locationlist + opened by :CocDiagnostics command and first window of associated buffer. + + Scope: `language-overridable`, default: `true` + +"diagnostic.messageDelay" *coc-config-diagnostic-messageDelay* + + How long to wait (in milliseconds) before displaying the diagnostic + message with echo or float + + Scope: `application`, default: `200` + +"diagnostic.messageLevel" *coc-config-diagnostic-messageLevel* + + Filter diagnostic message in float window/popup. + + Scope: `language-overridable`, default: `null` + +"diagnostic.messageTarget" *coc-config-diagnostic-messageTarget* + + Diagnostic message target. + + Scope: `language-overridable`, default: `"float"` + +"diagnostic.refreshOnInsertMode" *coc-config-diagnostic-refreshOnInsertMode* + + Enable diagnostic refresh on insert mode, default false. + + Scope: `language-overridable`, default: `false` + +"diagnostic.separateRelatedInformationAsDiagnostics" *coc-config-diagnostic-separateRelatedInformationAsDiagnostics* + + Separate related information as diagnostics. + + Scope: `application`, default: `false` + +"diagnostic.showDeprecated" *coc-config-diagnostic-showDeprecated* + + Show diagnostics with deprecated tag. + + Scope: `language-overridable`, default: `true` + +"diagnostic.showUnused" *coc-config-diagnostic-showUnused* + + Show diagnostics with unused tag, affects highlight, sign, virtual + text , message. + + Scope: `language-overridable`, default: `true` + +"diagnostic.signLevel" *coc-config-diagnostic-signLevel* + + Filter diagnostics displayed in signcolumn. + + Scope: `language-overridable`, default: `null` + +"diagnostic.signPriority" *coc-config-diagnostic-signPriority* + + Priority of diagnostic signs. + + Scope: `resource`, default: `10` + +"diagnostic.virtualText" *coc-config-diagnostic-virtualText* + + Use virtual text to display diagnostics, requires neovim >= 0.5.0 or + vim >= 9.0.0067. + + Scope: `language-overridable`, default: `false` + +"diagnostic.virtualTextAlign" *coc-config-diagnostic-virtualTextAlign* + + Position of virtual text. Vim9 only. + + Scope: `language-overridable`, default: `"after"` + +"diagnostic.virtualTextCurrentLineOnly" *coc-config-diagnostic-virtualTextCurrentLineOnly* + + Only show virtualText diagnostic on current cursor line. + + Scope: `language-overridable`, default: `true` + +"diagnostic.virtualTextFormat" *coc-config-diagnostic-virtualTextFormat* + + Define the virtual text diagnostic format, available parts: source, code + , severity, message. + + Scope: `language-overridable`, default: `"%message"` + +"diagnostic.virtualTextLevel" *coc-config-diagnostic-virtualTextLevel* + + Filter diagnostic message in virtual text by level. + + Scope: `language-overridable`, default: `null` + +"diagnostic.virtualTextLimitInOneLine" *coc-config-diagnostic-virtualTextLimitInOneLine* + + The maximum number of diagnostic messages to disaply in one line. + + Scope: `language-overridable`, default: `999` + +"diagnostic.virtualTextLineSeparator" *coc-config-diagnostic-virtualTextLineSeparator* + + The text that will mark a line end from the diagnostic message. + + Scope: `language-overridable`, default: `" \ "` + +"diagnostic.virtualTextLines" *coc-config-diagnostic-virtualTextLines* + + The number of non empty lines from a diagnostic to display. + + Scope: `language-overridable`, default: `3` + +"diagnostic.virtualTextPrefix" *coc-config-diagnostic-virtualTextPrefix* + + The prefix added virtual text diagnostics. + + Scope: `language-overridable`, default: `" "` + +"diagnostic.virtualTextWinCol" *coc-config-diagnostic-virtualTextWinCol* + + Window column number to align virtual text, neovim only. + + Scope: `language-overridable`, default: `null` + +"diagnostic.warningSign" *coc-config-diagnostic-warningSign* + + Text of warning sign. + + Scope: `application`, default: `"โš "` + +------------------------------------------------------------------------------ +Dialog~ + *coc-config-dialog* +"dialog.confirmKey" *coc-config-dialog-confirmKey* + + Confirm key for confirm selection used by menu and picker, you can + always use to cancel. + + Scope: `application`, default: `""` + +"dialog.floatBorderHighlight" *coc-config-dialog-floatBorderHighlight* + + Highlight group for border of dialog window/popup, use 'CocFloating' + when not specified. + + Scope: `application`, default: `null` + +"dialog.floatHighlight" *coc-config-dialog-floatHighlight* + + Highlight group for dialog window/popup, use 'CocFloating' when not + specified. + + Scope: `application`, default: `null` + +"dialog.maxHeight" *coc-config-dialog-maxHeight* + + Maximum height of dialog window, for quickpick, it's content window's + height. + + Scope: `application`, default: `30` + +"dialog.maxWidth" *coc-config-dialog-maxWidth* + + Maximum width of dialog window. + + Scope: `application`, default: `80` + +"dialog.pickerButtonShortcut" *coc-config-dialog-pickerButtonShortcut* + + Show shortcut in buttons of picker dialog window/popup, used when dialog + .pickerButtons is true. + + Scope: `application`, default: `true` + +"dialog.pickerButtons" *coc-config-dialog-pickerButtons* + + Show buttons for picker dialog window/popup. + + Scope: `application`, default: `true` + +"dialog.rounded" *coc-config-dialog-rounded* + + use rounded border for dialog window. + + Scope: `application`, default: `true` + +"dialog.shortcutHighlight" *coc-config-dialog-shortcutHighlight* + + Highlight group for shortcut character in menu dialog. + + Scope: `application`, default: `"MoreMsg"` + +------------------------------------------------------------------------------ +DocumentHighlight~ + *coc-config-documentHighlight* +"documentHighlight.priority" *coc-config-documentHighlight-priority* + + Match priority used by document highlight, see ':h matchadd'. + + Scope: `resource`, default: `-1` + +"documentHighlight.timeout" *coc-config-documentHighlight-timeout* + + Timeout for document highlight, in milliseconds. + + Scope: `resource`, default: `300` + +------------------------------------------------------------------------------ +FloatFactory~ + *coc-config-floatFactory* +"floatFactory.floatConfig" *coc-config-floatFactory-floatConfig* + + Configure default float window/popup style created by float factory + (created around cursor and automatically closed), properties of + |coc-config-float| are used. + + Scope: `application`, default: `null` + +------------------------------------------------------------------------------ +Hover~ + *coc-config-hover* +"hover.autoHide" *coc-config-hover-autoHide* + + Automatically hide hover float window on CursorMove or InsertEnter. + + Scope: `application`, default: `true` + +"hover.floatConfig" *coc-config-hover-floatConfig* + + Configuration of floating window/popup for hover documents, see + |coc-config-float|. + + Scope: `application`, default: `null` + +"hover.previewMaxHeight" *coc-config-hover-previewMaxHeight* + + Max height of preview window for hover. + + Scope: `resource`, default: `12` + +"hover.target" *coc-config-hover-target* + + Target to show hover information, could be `float`, `echo` or + `preview`. + + Scope: `resource`, default: `float` + +------------------------------------------------------------------------------ +Http proxy~ + *coc-config-http* +"http.proxy" *coc-config-http-proxy* + + The proxy setting to use. If not set, will be inherited from the ` + http_proxy` and `https_proxy` environment variables. + + Scope: `application`, default: `""` + +"http.proxyAuthorization" *coc-config-http-proxyAuthorization* + + The value to send as the `Proxy-Authorization` header for every network + request. + + Scope: `application`, default: `null` + +"http.proxyCA" *coc-config-http-proxyCA* + + CA (file) to use as Certificate Authority> + + Scope: `application`, default: `null` + +"http.proxyStrictSSL" *coc-config-http-proxyStrictSSL* + + Controls whether the proxy server certificate should be verified + against the list of supplied CAs. + + Scope: `application`, default: `true` + +------------------------------------------------------------------------------ +InlayHint~ + *coc-config-inlayHint* +"inlayHint.enable" *coc-config-inlayHint-enable* + + Enable inlay hint support. + + Scope: `language-overridable`, default: `true` + +"inlayHint.enableParameter" *coc-config-inlayHint-enableParameter* + + Enable inlay hints for parameters. + + Scope: `language-overridable`, default: `true` + +"inlayHint.display" *coc-config-inlayHint-display* + + Display inlay hints. Toggle with :CocCommand document.toggleInlayHint + + Scope: `language-overridable`, default: `true` + +"inlayHint.parameterSeparator" *coc-config-inlayHint-parameterSeparator* + + Separator for parameter inlay hint, neovim only. + + Scope: `language-overridable`, default: `""` + +"inlayHint.refreshOnInsertMode" *coc-config-inlayHint-refreshOnInsertMode* + + Refresh inlayHints on insert mode. + + Scope: `language-overridable`, default: `false` + +"inlayHint.subSeparator" *coc-config-inlayHint-subSeparator* + + Separator for chained inlay hints, neovim only. + + Scope: `language-overridable`, default: `" "` + +"inlayHint.typeSeparator" *coc-config-inlayHint-typeSeparator* + + Separator for type inlay hint, neovim only. + + Scope: `language-overridable`, default: `""` + +------------------------------------------------------------------------------ +Links~ + *coc-config-links* +"links.enable" *coc-config-links-enable* + + Enable document links. + + Scope: `language-overridable`, default: `true` + +"links.highlight" *coc-config-links-highlight* + + Use CocLink highlight group to highlight links. + + Scope: `application`, default: `false` + +"links.tooltip" *coc-config-links-tooltip* + + Show tooltip of link under cursor on CursorHold. + + Scope: `application`, default: `false` + +------------------------------------------------------------------------------ +List~ + *coc-config-list* +"list.alignColumns" *coc-config-list-alignColumns* + + Whether to align lists in columns. + + Scope: `application`, default: `false` + +"list.extendedSearchMode" *coc-config-list-extendedSearchMode* + + Enable extended search mode which allows multiple search patterns + delimited by spaces. + + Scope: `application`, default: `true` + +"list.floatPreview" *coc-config-list-floatPreview* + + Enable preview with float window/popup, default: `false`. + + Scope: `application`, default: `false` + +"list.height" *coc-config-list-height* + + Height of split list window. + + Scope: `application`, default: `10` + +"list.indicator" *coc-config-list-indicator* + + The character used as first character in prompt line. + + Scope: `application`, default: `">"` + +"list.insertMappings" *coc-config-list-insertMappings* + + Custom keymappings on insert mode. + + Scope: `application`, default: `{}` + +"list.interactiveDebounceTime" *coc-config-list-interactiveDebounceTime* + + Debounce time for input change on interactive mode. + + Scope: `application`, default: `100` + +"list.limitLines" *coc-config-list-limitLines* + + Limit lines for list buffer. + + Scope: `application`, default: `null` + +"list.maxPreviewHeight" *coc-config-list-maxPreviewHeight* + + Max height for preview window of list. + + Scope: `application`, default: `12` + +"list.menuAction" *coc-config-list-menuAction* + + Use menu picker instead of confirm() for choose action. + + Scope: `application`, default: `false` + +"list.nextKeymap" *coc-config-list-nextKeymap* + + Key used for select next line on insert mode. + + Scope: `application`, default: `""` + +"list.normalMappings" *coc-config-list-normalMappings* + + Custom keymappings on normal mode. + + Scope: `application`, default: `{}` + +"list.previewHighlightGroup" *coc-config-list-previewHighlightGroup* + + Highlight group used for highlight the range in preview window. + + Scope: `application`, default: `"Search"` + +"list.previewSplitRight" *coc-config-list-previewSplitRight* + + Use vsplit for preview window. + + Scope: `application`, default: `false` + +"list.previewToplineOffset" *coc-config-list-previewToplineOffset* + + Topline offset for list previews + + Scope: `application`, default: `3` + +"list.previewToplineStyle" *coc-config-list-previewToplineStyle* + + Topline style for list previews, could be "offset" or "middle". + + Scope: `application`, default: `"offset"` + +"list.previousKeymap" *coc-config-list-previousKeymap* + + Key used for select previous line on insert mode. + + Scope: `application`, default: `""` + +"list.selectedSignText" *coc-config-list-selectedSignText* + + Sign text for selected lines. + + Scope: `application`, default: `"*"` + +"list.signOffset" *coc-config-list-signOffset* + + Sign offset of list, should be different from other plugins. + + Scope: `application`, default: `900` + +"list.smartCase" *coc-config-list-smartCase* + + Use smartcase match for fuzzy match and strict match, --ignore-case + will be ignored, may not affect interactive list. + + Scope: `application`, default: `false` + +"list.source.diagnostics.includeCode" *coc-config-list-source-diagnostics-includeCode* + + Whether to show the diagnostic code in the list. + + Scope: `application`, default: `true` + +"list.source.diagnostics.pathFormat" *coc-config-list-source-diagnostics-pathFormat* + + Decide how the filepath is shown in the list. + + Scope: `application`, default: `"full"` + +"list.source.outline.ctagsFiletypes" *coc-config-list-source-outline-ctagsFiletypes* + + Filetypes that should use ctags for outline instead of language server. + + Scope: `application`, default: `[]` + +"list.source.symbols.excludes" *coc-config-list-source-symbols-excludes* + + Patterns of minimatch for filepath to exclude from symbols list. + + Scope: `application`, default: `[]` + +"list.statusLineSegments" *coc-config-list-statusLineSegments* + + An array of statusline segments that will be used to draw the status + line for list windows. + + Scope: `application`. + +------------------------------------------------------------------------------ +Notification~ + *coc-config-notification* +"notification.border" *coc-config-notification-border* + + Enable rounded border for notification windows. + + Scope: `application`, default: `true` + +"notification.disabledProgressSources" *coc-config-notification-disabledProgressSources* + + Sources that should be disabled for message progress, use * to disable + all progresses. + + Scope: `application`, default: `[]` + +"notification.focusable" *coc-config-notification-focusable* + + Enable focus by user actions (wincmds, mouse events), neovim only. + + Scope: `application`, default: `true` + +"notification.highlightGroup" *coc-config-notification-highlightGroup* + + Highlight group of notification dialog. + + Scope: `application`, default: `"Normal"` + +"notification.marginRight" *coc-config-notification-marginRight* + + Margin right to the right of editor window. + + Scope: `application`, default: `10` + +"notification.maxHeight" *coc-config-notification-maxHeight* + + Maximum content height of notification dialog. + + Scope: `application`, default: `10` + +"notification.maxWidth" *coc-config-notification-maxWidth* + + Maximum content width of notification dialog. + + Scope: `application`, default: `60` + +"notification.minProgressWidth" *coc-config-notification-minProgressWidth* + + Minimal with of progress notification. + + Scope: `application`, default: `30` + +"notification.statusLineProgress" *coc-config-notification-statusLineProgress* + + Show progress notification in status line, instead of use float + window/popup. + +"notification.timeout" *coc-config-notification-timeout* + + Timeout for auto close notifications, in milliseconds. + + Scope: `application`, default: `10000` + +"notification.winblend" *coc-config-notification-winblend* + + Winblend option of notification window, neovim only. + + Scope: `application`, default: `30` + +------------------------------------------------------------------------------ +Npm~ + *coc-config-npm* +"npm.binPath" *coc-config-npm-binPath* + + Command or absolute path to npm or yarn for global extension + install/uninstall. + + Scope: `application`, default: `"npm"` + +------------------------------------------------------------------------------ +Outline~ + *coc-config-outline* +"outline.autoPreview" *coc-config-outline-autoPreview* + + Enable auto preview on cursor move. + + Scope: `application`, default: `false` + +"outline.autoWidth" *coc-config-outline-autoWidth* + + Automatically increase window width to avoid wrapped lines. + + Scope: `application`, default: `true` + +"outline.checkBufferSwitch" *coc-config-outline-checkBufferSwitch* + + Recreate outline view after user changed to another buffer on current + tab. + + Scope: `application`, default: `true` + +"outline.codeActionKinds" *coc-config-outline-codeActionKinds* + + Filter code actions in actions menu by kinds. + + Scope: `application`, default: `["","quickfix","refactor"]` + +"outline.detailAsDescription" *coc-config-outline-detailAsDescription* + + Show detail as description aside with label, when false detail will be + shown in tooltip on cursor hold. + + Scope: `application`, default: `true` + +"outline.expandLevel" *coc-config-outline-expandLevel* + + Expand level of tree nodes. + + Scope: `application`, default: `1` + +"outline.followCursor" *coc-config-outline-followCursor* + + Reveal item in outline tree on cursor hold. + + Scope: `application`, default: `true` + +"outline.keepWindow" *coc-config-outline-keepWindow* + + Jump back to original window after outline is shown. + + Scope: `application`, default: `false` + +"outline.previewBorder" *coc-config-outline-previewBorder* + + Use border for preview window. + + Scope: `application`, default: `true` + +"outline.previewBorderHighlightGroup" *coc-config-outline-previewBorderHighlightGroup* + + Border highlight group of preview window. + + Scope: `application`, default: `"Normal"` + +"outline.previewBorderRounded" *coc-config-outline-previewBorderRounded* + + Use rounded border for preview window. + + Scope: `application`, default: `false` + +"outline.previewHighlightGroup" *coc-config-outline-previewHighlightGroup* + + Highlight group of preview window. + + Scope: `application`, default: `"Normal"` + +"outline.previewMaxWidth" *coc-config-outline-previewMaxWidth* + + Max width of preview window. + + Scope: `application`, default: `80` + +"outline.previewWinblend" *coc-config-outline-previewWinblend* + + Enables pseudo-transparency by set 'winblend' option of window, neovim + only. + + Scope: `application`, default: `0` + +"outline.showLineNumber" *coc-config-outline-showLineNumber* + + Show line number of symbols. + + Scope: `application`, default: `true` + +"outline.sortBy" *coc-config-outline-sortBy* + + Default sort method for symbols outline. + + Scope: `application`, default: `"category"` + +"outline.splitCommand" *coc-config-outline-splitCommand* + + Window split command used by outline. + + Scope: `application`, default: `"botright 30vs"` + +"outline.switchSortKey" *coc-config-outline-switchSortKey* + + The key used to switch sort method for symbols provider of current + tree view. + + Scope: `application`, default: `""` + +"outline.togglePreviewKey" *coc-config-outline-togglePreviewKey* + + The key used to toggle auto preview feature. + + Scope: `application`, default: `"p"` + +------------------------------------------------------------------------------ +PullDiagnostic~ + *coc-config-pullDiagnostic* +"pullDiagnostic.ignored" *coc-config-pullDiagnostic-ignored* + + Minimatch patterns to match full filepath that should be ignored for + pullDiagnostic. + + Scope: `application`, default: `[]` + +"pullDiagnostic.onChange" *coc-config-pullDiagnostic-onChange* + + Whether to pull for diagnostics on document change. + + Scope: `language-overridable`, default: `true` + +"pullDiagnostic.onSave" *coc-config-pullDiagnostic-onSave* + + Whether to pull for diagnostics on document save. + + Scope: `language-overridable`, default: `false` + +"pullDiagnostic.workspace" *coc-config-pullDiagnostic-workspace* + + Whether to pull for workspace diagnostics when possible. + + Scope: `application`, default: `true` + +------------------------------------------------------------------------------ +Refactor~ + *coc-config-refactor* +"refactor.afterContext" *coc-config-refactor-afterContext* + + Print num lines of trailing context after each match. + + Scope: `application`, default: `3` + +"refactor.beforeContext" *coc-config-refactor-beforeContext* + + Print num lines of leading context before each match. + + Scope: `application`, default: `3` + +"refactor.openCommand" *coc-config-refactor-openCommand* + + Open command for refactor window. + + Scope: `application`, default: `"vsplit"` + +"refactor.saveToFile" *coc-config-refactor-saveToFile* + + Save changed buffer to file when write refactor buffer with ':noa wa' + command. + + Scope: `application`, default: `true` + +"refactor.showMenu" *coc-config-refactor-showMenu* + + Refactor buffer local mapping to bring up menu for this chunk. + + Scope: `application`, default: `""` + +------------------------------------------------------------------------------ +SemanticTokens~ + *coc-config-semanticTokens* +"semanticTokens.combinedModifiers" *coc-config-semanticTokens-combinedModifiers* + + Semantic token modifiers that should have highlight combined with + syntax highlights. + + Scope: `language-overridable`, default: `["deprecated"]` + +"semanticTokens.enable" *coc-config-semanticTokens-enable* + + Enable semantic tokens support. + + Scope: `language-overridable`, default: `false` + +"semanticTokens.highlightPriority" *coc-config-semanticTokens-highlightPriority* + + Priority for semantic tokens highlight. + + Scope: `language-overridable`, default: `2048` + +"semanticTokens.incrementTypes" *coc-config-semanticTokens-incrementTypes* + + Semantic token types that should increase highlight when insert at the + start and end position of token. + + Scope: `language-overridable`, default: `["variable","string","parameter"]` + +------------------------------------------------------------------------------ +Signature~ + *coc-config-signature* +"signature.enable" *coc-config-signature-enable* + + Enable show signature help when trigger character typed. + + Scope: `language-overridable`, default: `true` + +"signature.floatConfig" *coc-config-signature-floatConfig* + + Configuration of floating window/popup for signature documents, see + |coc-config-float|. + + Scope: `application`, default: `null` + +"signature.hideOnTextChange" *coc-config-signature-hideOnTextChange* + + Hide signature float window when text changed on insert mode. + + Scope: `language-overridable`, default: `false` + +"signature.preferShownAbove" *coc-config-signature-preferShownAbove* + + Show signature help float window above cursor when possible, require + restart coc.nvim on change. + + Scope: `application`, default: `true` + +"signature.target" *coc-config-signature-target* + + Target of signature help, use float when possible by default. + + Scope: `language-overridable`, default: `"float"` + +"signature.triggerSignatureWait" *coc-config-signature-triggerSignatureWait* + + Timeout for trigger signature help, in milliseconds. + + Scope: `language-overridable`, default: `500` + +------------------------------------------------------------------------------ +Snippet~ + *coc-config-snippet* +"snippet.highlight" *coc-config-snippet-highlight* + + Use highlight group 'CocSnippetVisual' to highlight placeholders with + same index of current one. + + Scope: `resource`, default: `false` + +"snippet.nextPlaceholderOnDelete" *coc-config-snippet-nextPlaceholderOnDelete* + + Automatically jump to the next placeholder when the current one is + completely deleted. + + Scope: `resource`, default: `false` + +"snippet.statusText" *coc-config-snippet-statusText* + + Text shown in statusline to indicate snippet session is activated. + + Scope: `application`, default: `"SNIP"` + +------------------------------------------------------------------------------ +Suggest~ + *coc-config-suggest* +"suggest.acceptSuggestionOnCommitCharacter" *coc-config-suggest-acceptSuggestionOnCommitCharacter* + + Controls whether suggestions should be accepted on commit characters. + For example, in JavaScript, the semi-colon (`;`) can be a commit + character that accepts a suggestion and types that character. + + Scope: `language-overridable`, default: `false` + +"suggest.asciiCharactersOnly" *coc-config-suggest-asciiCharactersOnly* + + Trigger suggest with ASCII characters only. + + Scope: `language-overridable`, default: `false` + +"suggest.asciiMatch" *coc-config-suggest-asciiMatch* + + Convert unicode characters to ascii for match. + + Scope: `language-overridable`, default: `true` + +"suggest.autoTrigger" *coc-config-suggest-autoTrigger* + + How should completion be triggered, could be `"always"`, `"trigger"` + or `"none"`. + + Scope: `language-overridable`, default: `"always"` + +"suggest.completionItemKindLabels" *coc-config-suggest-completionItemKindLabels* + + Set custom labels to completion items' kinds. + Default value: > + { + "text": "v", + "method": "f", + "function": "f", + "constructor": "f", + "field": "m", + "variable": "v", + "class": "C", + "interface": "I", + "module": "M", + "property": "m", + "unit": "U", + "value": "v", + "enum": "E", + "keyword": "k", + "snippet": "S", + "color": "v", + "file": "F", + "reference": "r", + "folder": "F", + "enumMember": "m", + "constant": "v", + "struct": "S", + "event": "E", + "operator": "O", + "typeParameter": "T", + "default": "" + } +< + Scope: `application` + +"suggest.defaultSortMethod" *coc-config-suggest-defaultSortMethod* + + Default sorting behavior when trigger is empty, could be `"length"`, + `"alphabetical"` or `"none"`. + + Scope: `language-overridable`, default: `"length"` + +"suggest.detailField" *coc-config-suggest-detailField* + + Where to show the detail text of CompleteItem from language server. + + Scope: `application`, default: `"preview"` + +"suggest.enableFloat" *coc-config-suggest-enableFloat* + + Enable float window with documentation aside with popupmenu. + + Scope: `language-overridable`, default: `true"` + +"suggest.enablePreselect" *coc-config-suggest-enablePreselect* + + Enable preselect feature, works when |coc-config-suggest-noselect| is + false. + + Scope: `application`, default: `true` + +"suggest.floatConfig" *coc-config-suggest-floatConfig* + + Configure style of popup menu and documentation window for completion, + see |coc-config-float|. + + Note: some properties not work, including: "title", "focusable", + "close" and "maxHeight" (use 'pumheight' option for maximum height of + popup menu). + + Note: "maxWidth" not works for popup menu, use + |coc-config-suggest-labelMaxLength| instead. + +"suggest.formatItems" *coc-config-suggest-formatItems* + + Items shown in popup menu in order. + + Scope: `application`, default: `["abbr","menu","kind","shortcut"]` + +"suggest.highPrioritySourceLimit" *coc-config-suggest-highPrioritySourceLimit* + + Max items count for source priority bigger than or equal to 90. + + Scope: `language-overridable`, default: `null` + +"suggest.insertMode" *coc-config-suggest-insertMode* + + Controls whether words are overwritten when accepting completions. + + Scope: `language-overridable`, default: `โ€œreplace"` + +"suggest.ignoreRegexps" *coc-config-suggest-ignoreRegexps* + + Regexps to ignore when trigger suggest. + + Scope: `language-overridable`, default: `[]` + +"suggest.invalidInsertCharacters" *coc-config-suggest-invalidInsertCharacters* + + Invalid character for strip valid word when inserting text of complete + item. + + Scope: `application`, default: `["\r","\n"]` + +"suggest.labelMaxLength" *coc-config-suggest-labelMaxLength* + + Max length of abbr that shown as label of complete item. + + Scope: `application`, default: `200` + +"suggest.languageSourcePriority" *coc-config-suggest-languageSourcePriority* + + Priority of language sources. + + Scope: `language-overridable`, default: `99` + +"suggest.localityBonus" *coc-config-suggest-localityBonus* + + Boost suggestions that appear closer to the cursor position. + + Scope: `language-overridable`, default: `true` + +"suggest.lowPrioritySourceLimit" *coc-config-suggest-lowPrioritySourceLimit* + + Max items count for source priority lower than 90. + + Scope: `language-overridable`, default: `null` + +"suggest.maxCompleteItemCount" *coc-config-suggest-maxCompleteItemCount* + + Maximum number of complete items shown in vim. + + Scope: `language-overridable`, default: `256` + +"suggest.minTriggerInputLength" *coc-config-suggest-minTriggerInputLength* + + Minimal input length for trigger completion. + + Scope: `language-overridable`, default: `1` + +"suggest.noselect" *coc-config-suggest-noselect* + + Not make vim select first item on popupmenu shown. + + Scope: `application`, default: `false` + +"suggest.preferCompleteThanJumpPlaceholder" *coc-config-suggest-preferCompleteThanJumpPlaceholder* + + Confirm completion instead of jump to next placeholder when completion + is activated. + + Scope: `resource`, default: `false` + +"suggest.pumFloatConfig" *coc-config-suggest-pumFloatConfig* + + Configure style of popup menu, |coc-config-suggest-floatConfig| is + used when not specified, see |coc-config-float|. + + Available properties: "border", "rounded", "highlight", + "borderhighlight", "winblend" and "shadow". + + Note: 'winblend' option is used for custom popup menu when not + configured, use 'pumwidth' for minimal width of popup menu and + 'pumheight' for maximum height of popup menu. + + Scope: `application`, default: `null` + +"suggest.removeDuplicateItems" *coc-config-suggest-removeDuplicateItems* + + Remove completion items with duplicated word for all sources, snippet + items are excluded. + + Scope: `language-overridable`, default: `false` + +"suggest.reversePumAboveCursor" *coc-config-suggest-reversePumAboveCursor* + + Reverse order of complete items when pum shown above cursor. + + Scope: `application`, default: `false` + +"suggest.selection" *coc-config-suggest-selection* + + Controls how suggestions are pre-selected when showing the suggest list. + + Scope: `application`, default: `"first"` + +"suggest.snippetIndicator" *coc-config-suggest-snippetIndicator* + + The character used in abbr of complete item to indicate the item could + be expand as snippet. + + Scope: `application`, default: `"~"` + +"suggest.snippetsSupport" *coc-config-suggest-snippetsSupport* + + Set to false to disable snippets support of completion. + + Scope: `language-overridable`, default: `true` + +"suggest.timeout" *coc-config-suggest-timeout* + + Timeout for completion, in milliseconds. + + Scope: `language-overridable`, default: `5000` + +"suggest.triggerAfterInsertEnter" *coc-config-suggest-triggerAfterInsertEnter* + + Trigger completion after InsertEnter, |coc-config-suggest-autoTrigger| + should be 'always' to enable this option + + Scope: `language-overridable`, default: `false` + +"suggest.triggerCompletionWait" *coc-config-suggest-triggerCompletionWait* + + Wait time between text change and completion start, cancel completion + when text changed during wait. + + Scope: `language-overridable`, default: `0` + +"suggest.virtualText" *coc-config-suggest-virtualText* + + Show virtual text for insert word of selected item, requires + neovim >= 0.5.0 or vim >= 9.0.0067. + + Scope: `application`, default: `false` + +------------------------------------------------------------------------------ +Tree~ + *coc-config-tree* +"tree.closedIcon" *coc-config-tree-closedIcon* + + Closed icon of tree view. + + Scope: `application`, default: `"+"` + +"tree.key.actions" *coc-config-tree-key-actions* + + Trigger key to invoke actions. + + Scope: `application`, default: `""` + +"tree.key.activeFilter" *coc-config-tree-key-activeFilter* + + Trigger key active filter. + + Scope: `application`, default: `"f"` + +"tree.key.close" *coc-config-tree-key-close* + + Trigger key to dispose the tree and close tree window. + + Scope: `application`, default: `""` + +"tree.key.collapseAll" *coc-config-tree-key-collapseAll* + + Trigger key to collapse all tree node. + + Scope: `application`, default: `"M"` + +"tree.key.invoke" *coc-config-tree-key-invoke* + + Trigger key to invoke default command of current node or selection. + + Scope: `application`, default: `""` + +"tree.key.selectNext" *coc-config-tree-key-selectNext* + + Trigger key to select next item during filter. + + Scope: `application`, default: `""` + +"tree.key.selectPrevious" *coc-config-tree-key-selectPrevious* + + Trigger key to select previous item during filter. + + Scope: `application`, default: `""` + +"tree.key.toggle" *coc-config-tree-key-toggle* + + Trigger key to toggle expand state of tree node, does nothing with leaf + node. + + Scope: `application`, default: `"t"` + +"tree.key.toggleSelection" *coc-config-tree-key-toggleSelection* + + Trigger key to select/unselect item. + + Scope: `application`, default: `""` + +"tree.openedIcon" *coc-config-tree-openedIcon* + + Opened icon of tree view. + + Scope: `application`, default: `"-"` + +------------------------------------------------------------------------------ +TypeHierarchy~ + *coc-config-typeHierarchy* +"typeHierarchy.enableTooltip" *coc-config-typeHierarchy-enableTooltip* + + Enable tooltip to show relative filepath of type hierarchy item. + + Scope: `application`, default: `true` + +"typeHierarchy.openCommand" *coc-config-typeHierarchy-openCommand* + + Open command for type hierarchy tree view. + + Scope: `application`, default: `"edit"` + +"typeHierarchy.splitCommand" *coc-config-typeHierarchy-splitCommand* + + Window split command used by type hierarchy tree view. + + Scope: `application`, default: `"botright 30vs"` + +------------------------------------------------------------------------------ +Workspace~ + *coc-config-workspace* +"workspace.rootPatterns" *coc-config-workspace-rootPatterns* + + Root patterns to resolve workspaceFolder from parent folders of opened + files, resolved from up to down. + + Scope: `application`, default: `[".git",".hg",".projections.json"]` + +"workspace.bottomUpFiletypes" *coc-config-workspace-bottomUpFiletypes* + + Filetypes that should have workspace folder should resolved from base + directory of file, or ["*"] for any filetype. + + Scope: `application`, default: `[]` + +"workspace.ignoredFiletypes" *coc-config-workspace-ignoredFiletypes* + + Filetypes that should be ignored for workspace folder resolve. + + Scope: `resource`, default: `[]` + +"workspace.ignoredFolders" *coc-config-workspace-ignoredFolders* + + List of folders that should not be resolved as workspace folder, + environment variables and minimatch patterns can be used. + + Scope: `application`, default: `["$HOME"]` + +"workspace.openOutputCommand" *coc-config-workspace-openOutputCommand* + + Command used to open output channel. + + Scope: `resource`, default: `"vs"` + +"workspace.openResourceCommand" *coc-config-workspace-openResourceCommand* + + Command to open files that not loaded, load files as hidden buffers + when empty. + + Scope: `application`, default: `"tab drop"` + +"workspace.workspaceFolderCheckCwd" *coc-config-workspace-workspaceFolderCheckCwd* + + Whether the current working directory should be used first when + checking patterns match for workspace folder. + + Scope: `application`, default: `true` + +"workspace.workspaceFolderFallbackCwd" *coc-config-workspace-workspaceFolderFallbackCwd* + + Use current working directory as workspace folder when no root + patterns resolved. + + Scope: `application`, default: `true` + +------------------------------------------------------------------------------ +Preferences~ + *coc-config-preferences* +"coc.preferences.bracketEnterImprove" *coc-preferences-bracketEnterImprove* + + Improve enter inside bracket `<> {} [] ()` by add new empty line below + and place cursor to it. Works with `coc#on_enter()` + + Scope: `language-overridable`, default: `true` + +"coc.preferences.currentFunctionSymbolAutoUpdate" *coc-preferences-currentFunctionSymbolAutoUpdate* + + Automatically update the value of b:coc_current_function on CursorHold + event + + Scope: `language-overridable`, default: `false` + +"coc.preferences.enableLinkedEditing" *coc-preferences-enableLinkedEditing* + + Enable linked editing support. + + Scope: `language-overridable`, default: `false` + +"coc.preferences.enableMarkdown" *coc-preferences-enableMarkdown* + + Tell the language server that markdown text format is supported, note + that markdown text may not rendered as expected. + + Scope: `application`, default: `true` + +"coc.preferences.enableMessageDialog" *coc-preferences-enableMessageDialog* + + Enable messages shown in notification dialog. + + Scope: `application`, default: `false` + +"coc.preferences.excludeImageLinksInMarkdownDocument" *coc-preferences-excludeImageLinksInMarkdownDocument* + + Exclude image links from markdown text in float window. + + Scope: `application`, default: `true` + +"coc.preferences.enableGFMBreaksInMarkdownDocument" *coc-preferences-enableGFMBreaksInmakrdownDocument* + + Exclude GFM breaks in markdown document. + + Scope: `application`, default: `true` + +"coc.preferences.extensionUpdateCheck" *coc-preferences-extensionUpdateCheck* + + Interval for check extension update, could be "daily", "weekly" or + "never" + + Scope: `application`, default: `"never"` + +"coc.preferences.floatActions" *coc-preferences-floatActions* + + Set to false to disable float/popup support for actions menu. + + Scope: `application`, default: `true` + +"coc.preferences.formatOnSave" *coc-preferences-formatOnSave* + + Set to true to enable formatting on save. + + Scope: `language-overridable`, default: `false` + +"coc.preferences.formatOnType" *coc-preferences-formatOnType* + + Set to true to enable formatting on typing + + Scope: `language-overridable`, default: `false` + +"coc.preferences.jumpCommand" *coc-preferences-jumpCommand* + + Command used for location jump, like goto definition, goto references + etc. Can be also a custom command that gives file as an argument. + + Scope: `application`, default: `"edit"` + +"coc.preferences.maxFileSize" *coc-preferences-maxFileSize* + + Maximum file size in bytes that coc.nvim should handle, default + '10MB'. + + Scope: `application`, default: `"10MB"` + +"coc.preferences.messageLevel" *coc-preferences-messageLevel* + + Message level for filter echoed messages, could be 'more', 'warning' + and 'error' + + Scope: `application`, default: `"more"` + +"coc.preferences.promptInput" *coc-preferences-promptInput* + + Use prompt buffer in float window for user input. + + Scope: `application`, default: `true` + +"coc.preferences.renameFillCurrent" *coc-preferences-renameFillCurrent* + + Disable to stop Refactor-Rename float/popup window from populating + with old name in the New Name field. + + Scope: `application`, default: `true` + +"coc.preferences.silentAutoupdate" *coc-preferences-silentAutoupdate* + + Not open split window with update status when performing auto update. + + Scope: `application`, default: `true` + +"coc.preferences.useQuickfixForLocations" *coc-preferences-useQuickfixForLocations* + + Use vim's quickfix list for jump locations, need restart on change. + + Scope: `application`, default: `false` + +"coc.preferences.watchmanPath" *coc-preferences-watchmanPath* + + executable path for https://facebook.github.io/watchman/, detected + from $PATH by default + + Scope: `application`, default: `null` + +"coc.preferences.willSaveHandlerTimeout" *coc-preferences-willSaveHandlerTimeout* + + Will save handler timeout. + + Scope: `application`, default: `500` + +------------------------------------------------------------------------------ +Float configuration~ + *coc-config-float* + +Used by `suggest.floatConfig`, `diagnostic.floatConfig`, +`signature.floatConfig` and `hover.floatConfig`, following properties are +supported: + + - "border": Change to `true` to enable border. + - "rounded": Use rounded borders when border is `true`. + - "highlight": Background highlight group of float window, default: + `"CocFloating"`. + - "title": Title text used by float window, default: `""`. + - "borderhighlight": Border highlight group of float window, default: + `"CocFloating"`. + - "close": Set to `true` to draw close icon. + - "maxWidth": Maximum width of float window, contains border. + - "maxHeight": Maximum height of float window, contains border. + - "winblend": Set 'winblend' option of window, neovim only, default: + `0`. + - "focusable": Set to false to make window not focusable, neovim only. + - "shadow": Set to true to enable shadow, neovim only. + +------------------------------------------------------------------------------ +Languageserver~ + *coc-config-languageserver* + + Dictionary of Language Servers, key is the ID of corresponding server, + and value is configuration of languageserver. Default: `{}` + + Properties of languageserver configuration: + + - "enable": Change to `false` to disable that languageserver. + + - "filetypes": Supported filetypes, add * in array for all filetypes. + Note: it's required for start the languageserver, please make sure + your filetype is expected by `:CocCommand document.echoFiletype` command + + - "additionalSchemes": Additional URI schemes, default schemes + including file & untitled. + Note: you have to setup vim provide content for custom URI as well. + + - "cwd": Working directory used to start languageserver, vim's cwd is + used by default. + + - "env": Environment variables for child process. + + - "settings": Settings for languageserver, received on server + initialization. + + - "trace.server": Trace level of communication between server and + client that showed with output channel, open output channel by + command `:CocCommand workspace.showOutput` + + - "stdioEncoding": Encoding used for stdio of child process. + + - "initializationOptions": Initialization options passed to + languageserver (it's deprecated) + + - "rootPatterns": Root patterns used to resolve rootPath from current + file. + + - "requireRootPattern": If true, doesn't start server when root + pattern not found. + + - "ignoredRootPaths": Absolute root paths that language server should + not use as rootPath, higher priority than rootPatterns. + + - "disableDynamicRegister": Disable dynamic registerCapability feature + for this languageserver to avoid duplicated feature registration. + + - "disableSnippetCompletion": Disable snippet completion feature for + this languageserver. + + - "disabledFeatures": Disable features for this languageserver, + valid keys: +> + ["completion", "configuration", "workspaceFolders", "diagnostics", + "willSave", "willSaveUntil", "didSaveTextDocument", + "fileSystemWatcher", "hover", "signatureHelp", "definition", + "references", "documentHighlight", "documentSymbol", + "workspaceSymbol", "codeAction", "codeLens", "formatting", + "documentFormatting", "documentRangeFormatting", + "documentOnTypeFormatting", "rename", "documentLink", + "executeCommand", "pullConfiguration", "typeDefinition", + "implementation", "declaration", "color", "foldingRange", + "selectionRange", "progress", "callHierarchy", "linkedEditing", + "fileEvents", "semanticTokens"] +< + - "formatterPriority": Priority of this languageserver's formatter. + + - "revealOutputChannelOn": Configure message level to show the output + channel buffer. + + - "progressOnInitialization": Enable progress report on languageserver + initialize. + +Language server start with command:~ + + Additional fields can be used for a command languageserver: + + - "command": Executable program name in $PATH or absolute path of + executable used for start languageserver. + + - "args": Command line arguments of command. + + - "detached": Detach language server when is true. + + - "shell": Use shell for server process, default: `false` + +Language server start with module:~ + + Additional fields can be used for a languageserver started by node + module: + + - "module": Absolute filepath of Javascript file. + + - "args": Extra arguments used on fork Javascript module. + + - "runtime": Absolute path of node runtime, node runtime of coc.nvim + is used by default. + + - "execArgv": ARGV passed to node on fork, normally used for + debugging, example: `["--nolazy", "--inspect-brk=6045"]` + + - "transport": Transport kind used by server, could be 'ipc', 'stdio', + 'socket' and 'pipe'. 'ipc' is used by default (recommended). + + - "transportPort": Port number used when transport is 'socket'. + +Language server use initialized socket server:~ + + - "port": Port number of socket server. + + - "host": Host of socket server, default to `127.0.0.1`. + +============================================================================== +vim:tw=78:nosta:noet:ts=8:sts=0:ft=help:noet:fen: diff --git a/vim-config/plugins/coc.nvim/doc/coc.txt b/vim-config/plugins/coc.nvim/doc/coc.txt index 004dab15..81c28365 100644 --- a/vim-config/plugins/coc.nvim/doc/coc.txt +++ b/vim-config/plugins/coc.nvim/doc/coc.txt @@ -1,23 +1,51 @@ *coc-nvim.txt* NodeJS client for Vim & Neovim. -Version: 0.0.80 +Version: 0.0.82 Author: Qiming Zhao -License: MIT license CONTENTS *coc-contents* Introduction |coc-introduction| Requirements |coc-requirements| Installation |coc-installation| +Extensions |coc-extensions| Configuration |coc-configuration| -Completion |coc-completion| +Floating windows |coc-floating| +LSP features |coc-lsp| + Document |coc-document| + Hover |coc-hover| + Completion |coc-completion| + Diagnostics |coc-diagnostics| + Pull diagnostics |coc-pullDiagnostics| + Locations |coc-locations| + Rename |coc-rename| + Signature help |coc-signature| + Inlay hint |coc-inlayHint| + Format |coc-format| + Code action |coc-code-actions| + Document highlights |coc-document-highlights| + Document colors |coc-document-colors| + Document links |coc-document-links| + Snippets |coc-snippets| + Workspace |coc-workspace| + Cursors |coc-cursors| + Outline |coc-outline| + Call hierarchy |coc-callHierarchy| + Type hierarchy |coc-typeHierarchy| + Semantic highlights |coc-semantic-highlights| + Fold |coc-fold| + Selection range |coc-selection-range| + Code Lens |coc-code-lens| + Linked editing |coc-linked-editing| Interface |coc-interface| Key mappings |coc-key-mappings| - Variables |coc-variables| - Functions |coc-functions| - Commands |coc-commands| - Autocmds |coc-autocmds| - Highlights |coc-highlights| + Variables |coc-variables| + Buffer variables |coc-buffer-variables| + Global variables |coc-global-variables| + Functions |coc-functions| + Commands |coc-commands| + Autocmds |coc-autocmds| + Highlights |coc-highlights| Tree |coc-tree| Tree mappings |coc-tree-mappings| Tree filter |coc-tree-filter| @@ -27,62 +55,59 @@ List |coc-list| List configuration |coc-list-configuration| List mappings |coc-list-mappings| list sources |coc-list-sources| - Location |coc-list-location| - Extensions |coc-list-extensions| - Diagnostics |coc-list-diagnostics| - Outline |coc-list-outline| - Symbols |coc-list-symbols| - Services |coc-list-services| - Commands |coc-list-commands| - Links |coc-list-links| - Sources |coc-list-completion-sources| - Lists |coc-list-lists| Dialog |coc-dialog| - Dialog basic |coc-dialog-basic| - Dialog confirm |coc-dialog-confirm| - Dialog input |coc-dialog-input| - Dialog menu |coc-dialog-menu| - Dialog picker |coc-dialog-picker| -Statusline support |coc-status| - Manual |coc-status-manual| - Airline |coc-status-airline| - Lightline |coc-status-lightline| + Dialog basic |coc-dialog-basic| + Dialog confirm |coc-dialog-confirm| + Dialog input |coc-dialog-input| + Dialog menu |coc-dialog-menu| + Dialog picker |coc-dialog-picker| +Notification |coc-notification| +Statusline integration |coc-status| + Manual |coc-status-manual| + Airline |coc-status-airline| + Lightline |coc-status-lightline| +Create plugins |coc-plugins| FAQ |coc-faq| -Changelog |coc-changelog| +Change log |coc-changelog| ============================================================================== INTRODUCTION *coc-introduction* Coc.nvim enhances your (Neo)Vim to match the user experience provided by -VSCode through a rich plugin (or extension) ecosystem and support for Language -Server Protocol. +VSCode through a rich extension ecosystem and implemented the client features +specified by Language Server Protocol (3.17 for now), see |coc-lsp|. -Some of its key features include:~ +Some features (like completion) automatically works by default, all of them +can be disabled by |coc-configuration|. -- APIs compatible with both Vim8 and Neovim. -- Loading VSCode-like extensions. -- Configuring coc.nvim and its extensions with a JSON configuration file. -- Configuring Language Servers implemented according to Language Server - Protocol (LSP). +Some key features:~ + + โ€ข Typescript APIs compatible with both Vim8 and Neovim. + โ€ข Loading VSCode-like extensions |coc-api-extension|. + โ€ข Configuring coc.nvim and its extensions with JSON configuration + |coc-configuration|. + โ€ข Configuring Language Servers that using Language Server Protocol (LSP) + |coc-config-languageserver|. It is designed for best possible integration with other Vim plugins. -Note: This plugin doesn't come with support for any specific language. You -will need to install a coc extension or set up the language server yourself. +Note: coc.nvim doesn't come with support for any specific language. You +will need to install coc.nvim extensions |coc-extensions| or set up the +language server by use |coc-config-languageserver|. -Note: This plugin doesn't change any of your existing key-mappings. You will -need to create key-mappings by yourself, see README for examples. +Note: multiple language servers for same document is allowed, but you should +avoid configure same language server that already used by coc.nvim extension. -Note: Automatic completion plugins can't play nicely together, you can disable -automatic completion of coc.nvim through `"suggest.autoTrigger": "none"` (or -`"suggest.autoTrigger": "trigger"`) in your settings file. +Note: automatic completion plugins can't play nicely together, you can disable +automatic completion of coc.nvim by use `"suggest.autoTrigger": "none"` (or +`"suggest.autoTrigger": "trigger"`) in your |coc-configuration|. ============================================================================== REQUIREMENTS *coc-requirements* -Neovim >= 0.3.2 or Vim >= 8.0.1453. +Neovim >= 0.4.0 or Vim >= 8.1.1719. -NodeJS https://nodejs.org/ >= 12.12.0. +NodeJS https://nodejs.org/ >= 14.14.0. Yarn https://yarnpkg.com/ required to build coc.nvim from typescript source code. @@ -99,1143 +124,1269 @@ And run: > :PlugInstall -For other plugin managers, make sure to use code from the release branch. +For other plugin managers, make sure to use the release branch (unless you +need to build from typescript source code). -You can also use Vim's native package management: > +To use Vim's native |packages| on Linux or MaxOS, use script like: > #!/bin/sh # for vim8 mkdir -p ~/.vim/pack/coc/start cd ~/.vim/pack/coc/start curl --fail -L https://github.com/neoclide/coc.nvim/archive/release.tar.gz|tar xzfv - + vim -c 'helptags ~/.vim/pack/coc/start/doc|q' # for neovim mkdir -p ~/.local/share/nvim/site/pack/coc/start cd ~/.local/share/nvim/site/pack/coc/start curl --fail -L https://github.com/neoclide/coc.nvim/archive/release.tar.gz|tar xzfv - + nvim -c 'helptags ~/.local/share/nvim/site/pack/coc/start|q' -============================================================================== -CONFIGURATION *coc-configuration* - -The configuration of coc.nvim is stored in `coc-settings.json` file. You can -open it through |:CocConfig|. This will open (or create) a global settings -files in folder returned by |coc#util#get_config_home()| - -To create a local configuration project for a specific workspace, use -|:CocLocalConfig|: this will create `.vim/coc-settings.json` in the current -workspace folder. - -The global configuration file can be created in another directory by setting -`g:coc_config_home` in your `.vimrc` or `init.vim`: > - - let g:coc_config_home = '/path/you/prefer' - -When creating a local configuration file, it's possible to use -|b:coc_root_patterns| for resolve the root directory from the filepath of -opend buffer. - -Since the configuration files are all in JSON format, it's suggested to enable -JSON completion and validation by install the `coc-json` extension: > - - :CocInstall coc-json -< -Check https://github.com/neoclide/coc.nvim/wiki/Using-the-configuration-file -for more details. - -Built-in configurations:~ - - *coc-config-http* -*http.proxy* - - HTTP proxy URI, used for extensions that send request, default: `""` - -"http.proxyStrictSSL":~ - - Controls whether the proxy server certificate should be verified - against the list of supplied CAs, default: `true` - -"http.proxyAuthorization":~ - - The value to send as the `Proxy-Authorization` header for every - network request. - -"http.proxyCA":~ - - CA (file) to use as Certificate Authority. - - *coc-config-suggest* -"suggest.enablePreselect":~ - - Enable preselect feature on Neovim, default: `false` - -"suggest.labelMaxLength":~ - - Maximum length of label shown in 'pum', default: `200` - -"suggest.enablePreview":~ - - Add preview option to 'completeopt', default: `false` - -"suggest.floatEnable":~ - - Enable floating window for documentation when possible, default: `true` - -"suggest.floatConfig":~ - - Configuration of floating window/popup, see |coc-config-float|. - Excludes properties: "title", "close" and "maxHeight". - -"suggest.detailMaxLength":~ - - Max length of detail that will be shown in popup menu, default: `100` - -"suggest.detailField":~ - - Where to add the detail in complete item when it's less than max - length, default: `"preview"` when floating documentation is enabled. - - Valid options: ["abbr", "menu", "preview"] - -"suggest.autoTrigger":~ - - How should completion be triggered, default: `"always"` - - Valid options: ["always", "trigger", "none"] - - - `always`: trigger suggest on word characters and trigger - characters. - - `trigger`: trigger suggest on trigger characters only. - - `none`: no auto trigger at all. - -"suggest.languageSourcePriority":~ - - Priority of language sources, default: `99` - -"suggest.numberSelect":~ - - Input number to select complete item, it could be wrong when - using '' and '' to select complete item, default: `false` - -"suggest.disableKind":~ - - Remove kind field from Vim complete item, default: `false` - -"suggest.disableMenu":~ - - Remove menu field from Vim complete item, default: `false` - -"suggest.snippetIndicator":~ - - The character used in completion item abbreviation to indicate it - expands as code snippet, default: `"~"` - -"suggest.maxCompleteItemCount":~ - - Maximum number of complete items shown in Vim, default: `50` - -"suggest.preferCompleteThanJumpPlaceholder":~ - - Confirm completion instead of jump to next placeholder when completion - activates, default: `false` - -"suggest.snippetsSupport":~ - - Enable snippets expands expand on confirm completion. When set to - `false` coc.nvim would set language client option: - `CompletionClientCapabilities.completionItem.snippetSupport` to - `false` as well. - - Note: the language server may still send completion items with - snippets when falsy. - -"suggest.fixInsertedWord":~ - - Inserted word replaces the next one, default: `true` - -"suggest.localityBonus":~ - - Boost suggestions that appear closer to the cursor position, - default: `true` - -"suggest.triggerAfterInsertEnter":~ - - Trigger completion after |InsertEnter|. Requires "suggest.autoTrigger" - to be set, default: `false` - -"suggest.timeout":~ - - Timeout for completion (unit: milliseconds), default: `5000` - -"suggest.minTriggerInputLength":~ - - Number of characters in the current word after which the completion - triggers, default: `1` - -"suggest.triggerCompletionWait":~ - - Delay between typing the trigger character and completion start which - initiates server synchronization, default: `100` - -"suggest.echodocSupport":~ - - Add function signature to `user_data.signature` to support `echodoc.vim`, - default: `false` - -"suggest.acceptSuggestionOnCommitCharacter":~ - - The server provides a set of commit characters: these characters can - trigger completion item acceptance. This also inserts commit character - after the completion item text. Requires `CompleteChanged` event to work, - default: `false` +when using source code of coc.nvim, you'll have to install +https://yarnpkg.com/ and run `yarn install` in project root of coc.nvim. -"suggest.noselect":~ - - Prevent Vim from selecting the first item on completion start, - default: `true` - -"suggest.keepCompleteopt":~ - - When enabled, 'completeopt' is not overridden. Autocompletion will be - disabled if 'completeopt' doesn't have 'noinsert' and 'noselect', - default: `false` - -"suggest.lowPrioritySourceLimit":~ - - Max items count for source priority lower than `90`. - -"suggest.highPrioritySourceLimit":~ - - Max items count for source priority bigger than or equal to `90`. - -"suggest.disableMenuShortcut":~ +============================================================================== +EXTENSIONS *coc-extensions* - Disable shortcut of completion source in menu, default: `false` +To provide LSP features of different filetypes, the user have to config +|coc-config-languageserver| or install coc extensions. -"suggest.removeDuplicateItems":~ +Extensions are more powerful since they could contribute json schemes, +commands, and use middleware methods of languageserver to provide better +results. It's also possible to provide features that beyond LSP. + *coc-extensions-folder* +Extensions are loaded from `"extensions"` folder inside +|coc#util#get_data_home()| and folders in 'runtimepath' when detected. - Remove completion items with duplicated word for all sources, snippet - items are excluded, default: `false` +Use `let $COC_NO_PLUGINS = '1'` in vimrc to disable the load of extensions. -"suggest.defaultSortMethod":~ +See |coc-api-extension| for the guide to create coc.nvim extension. - Default sorting behavior for suggested completion items, default: - `length` +Install extensions from git (not recommended):~ -"suggest.invalidInsertCharacters":~ + โ€ข Download the source code. + โ€ข In project root, install dependencies and compile the code by `yarn install` + (needed by most coc extensions). + โ€ข Add the project root to vim's runtimepath by `set runtimepath^=/path/to/project` - Invalid character for strip valid word when inserting text of complete - item, default: ` ,(,<,{,[,\r,\n` +Plugin manager like [vim-plug] can be used as well. -"suggest.asciiCharactersOnly":~ +Note: use coc.nvim extensions from source code requires install dependencies, +which may take huge disk usage. - Suggest ASCII characters only, default: `false` + *coc-extensions-npm* +Install global extensions from npm (recommended):~ -"suggest.completionItemKindLabels":~ +Use |:CocInstall| to install coc extensions from vim's command line. - Set custom labels to completion item kinds, default: `{}`. +To make coc.nvim install extensions on startup, use |g:coc_global_extensions|. - Example configuration: with https://nerdfonts.com: > +To use package manager other than npm (like `yarn` or `pnpm`), use +|coc-config-npm-binPath|. - "suggest.completionItemKindLabels": { - "keyword": "\uf1de", - "variable": "\ue79b", - "value": "\uf89f", - "operator": "\u03a8", - "constructor": "\uf0ad", - "function": "\u0192", - "reference": "\ufa46", - "constant": "\uf8fe", - "method": "\uf09a", - "struct": "\ufb44", - "class": "\uf0e8", - "interface": "\uf417", - "text": "\ue612", - "enum": "\uf435", - "enumMember": "\uf02b", - "module": "\uf40d", - "color": "\ue22b", - "property": "\ue624", - "field": "\uf9be", - "unit": "\uf475", - "event": "\ufacd", - "file": "\uf723", - "folder": "\uf114", - "snippet": "\ue60b", - "typeParameter": "\uf728", - "default": "\uf29c" - } +To customize npm registry for coc.nvim add `coc.nvim:registry` in your +`~/.npmrc`, like: +> + coc.nvim:registry=https://registry.mycompany.org/ < - *coc-config-diagnostic* -"diagnostic.enable":~ - - Display diagnostics, default: `true` - -"diagnostic.highlighLimit":~ - - Limit count for highlighted diagnostics, too many diagnostic - highlights could make vim stop responsing. - - default: `1000` - -"diagnostic.autoRefresh":~ - - Enable automatically refresh diagnostics, use - |CocAction('diagnosticRefresh')| action to refresh diagnostics when it's - disabled. - -"diagnostic.enableSign":~ - - Enable signs for diagnostics, default: `true` - -"diagnostic.enableMessage":~ - - When to enable show messages of diagnostics. - - Valid options: ["always","jump","never"], always means including - cursor hold and after jump to another diagnostic. - - default: `"always"` - -"diagnostic.enableHighlightLineNumber":~ - - Enable highlighting line numbers for diagnostics, only works with - neovim and `diagnostic.enableSign` is true. - - default: `true` - -"diagnostic.locationlistUpdate"~ - - Update locationlist on diagnostics change, only works with - locationlist opened by :CocDiagnostics command and first window of - associated buffer. - - default: `true` - -"diagnostic.level":~ - - Filter diagnostics by severity, default: `"hint"` - - Valid options: ["hint", "information", "warning", "error"] - -"diagnostic.messageDelay":~ - - How long to wait (in milliseconds) before displaying the diagnostic - message with echo or float. - - Default: `200` - -"diagnostic.checkCurrentLine":~ - - Show all diagnostics of the current line if none of them are at the - current position, default: `false` +To customize extension folder, configure |g:coc_data_home|. -"diagnostic.messageTarget":~ +Uninstall global extensions:~ - Diagnostic message target, default: `"float"` +Use |:CocUninstall|. - Valid options: ["echo", "float"] +Update global extensions:~ -"diagnostic.refreshOnInsertMode":~ +Use |:CocUpdate| or |:CocUpdateSync|. - Refresh diagnostics when in insert mode, default: `false` +To update extensions automatically, config |coc-preferences-extensionUpdateCheck|. -"diagnostic.displayByAle":~ +Manage extensions list:~ - Use ALE for displaying diagnostics. This will disable coc.nvim for - displaying diagnostics. Restart to make changes take the effect, - default: `false` +Use |coc-list-extensions| or |CocAction('extensionStats')| to get list of extensions. -"diagnostic.virtualText":~ - - Use Neovim virtual text to display diagnostics, default: `false` - -"diagnostic.virtualTextCurrentLineOnly":~ - - Only show virtualText diagnostic on current cursor line, default: - `true` +============================================================================== +CONFIGURATION *coc-configuration* -"diagnostic.virtualTextPrefix":~ +The configuration of coc.nvim is stored in file named "coc-settings.json". - The prefix added for virtual text diagnostics, default: `" "` +Configuration properties are contributed by coc.nvim itself and coc.nvim +extensions. See |coc-config| for builtin configurations. -"diagnostic.virtualTextLines":~ +The configuration files are all in JSON format (with comment supported), it's +recommended to enable JSON completion and validation by install the `coc-json` +extension: +> + :CocInstall coc-json +< +To fix the highlight of comment, use: +> + autocmd FileType json syntax match Comment +\/\/.\+$+ +< +in your vimrc. - The number of non-empty lines from a diagnostic to display, default: `3` +Global configuration file:~ -"diagnostic.virtualTextLineSeparator":~ +Command |:CocConfig| will open (create when necessary) a user settings +file in the folder returned by |coc#util#get_config_home()|. - The text that will mark a line end from the diagnostic message, - default: `" \\ "` +The user configuration value could be overwritten by API |coc#config()| or +|g:coc_user_config|. -"diagnostic.highlightOffset":~ +The global configuration file can be created in another directory by setting +|g:coc_config_home| in your vimrc like: > - Offset number of buffer.addHighlight, Neovim only, default: `1000` + let g:coc_config_home = '/path/to/folder' -"diagnostic.signPriority":~ +Folder configuration file:~ - Priority of diagnostic sign, default to `10`, check |sign-priority|. +To create a local configuration file for a specific workspace folder, use +|:CocLocalConfig| to create and open `.vim/coc-settings.json` in current +workspace folder. -"diagnostic.errorSign":~ +Folder configuration would overwrite user configuration. - Sign of error diagnostics shown in the 'signcolumn', default: `">>"` +Note: the configuration file won't work when the parent folder is not resolved +as workspace folder, it's best practice to start vim inside workspace folder, +see |coc-workspace-folders|. -"diagnostic.warningSign":~ + *coc-configuration-expand* +Variables expands:~ - Sign of warning diagnostics shown in the 'signcolumn', default: `"โš "` +Variables would be expanded in string values of configuration, supported +variables: -"diagnostic.infoSign":~ + โ€ข `${userHome}` the path of the user's home folder + โ€ข `${cwd}` current working directory of vim. - Sign of info diagnostics shown in the 'signcolumn', default: `">>"` +You can also reference environment variables through the `${env:name}` syntax +(for example, `${env:USERNAME}`), no expand happens when env not exists. -"diagnostic.hintSign":~ +Configurations that requires file paths (ex: +|coc-config-workspace-ignoredFolders|) support expand `~` at the beginning of +the filepath to user's home and some additional variables: - Sign of hint diagnostics shown in the 'signcolumn', default: `">>"` + โ€ข `${workspaceFolder}` the current opened file's workspace folder. + โ€ข `${workspaceFolderBasename}` the name of the workspace folder opened in + coc.nvim without any slashes (/). + โ€ข `${file}` the current opened file. + โ€ข `${fileDirname}` the current opened file's dirname. + โ€ข `${fileExtname}` the current opened file's extension. + โ€ข `${fileBasename}` the current opened file's basename + โ€ข `${fileBasenameNoExtension}` the current opened file's basename with no file extension. -"diagnostic.floatConfig"~ + *coc-configuration-scope* +Configuration scope:~ - Configuration of floating window/popup, see |coc-config-float|. +A configuration could be one of three different configuration scopes: -"diagnostic.filetypeMap":~ + โ€ข `"application"` the configuration could only be used in user configuration + file. - A map between buffer filetype and the filetype assigned to diagnostics. - To syntax highlight diagnostics withs their parent buffer type use - `"default": "bufferType"`, default: `{}` + โ€ข `"resource"` the configuration could be used in user and workspace folder + configuration file. -"diagnostic.format":~ + โ€ข `"language-overridable"` the configuration could be used in user and + workspace folder configuration file, and can be use used in language scoped + configuration section like `[typescript][json]`. For example: > - Define the diagnostic format. - Available parts: source, code, severity, message + // disable inlay hint for some languages + "[rust][lua][c]": { + "inlayHint.enable": false + } +< +============================================================================== +FLOATING WINDOWS *coc-floating* - Default: `[%source%code] [%severity] %message` +Floating windows/popups are created by |api-floatwin| on neovim or |popupwin| +on vim. + *coc-floating-scroll* +Scroll floating windows:~ -"diagnostic.separateRelatedInformationAsDiagnostics":~ +See |coc#float#has_scroll()| for example. - Separate related information as diagnostics, default: `false` +Note: use |coc#pum#scroll()| for scroll popup menu. -"signature.enable":~ + *coc-floating-close* +Close floating windows:~ - Enable signature help when trigger character typed. Requires service - restart on change, default: `true` +To close all floating windows/popups use |coc#float#close_all()| or +|popup_clear()| on vim. Or you can use o on neovim which close all +split windows as well. Or use |popup_clear()| on vim. -"signature.floatConfig":~ +To close single floating window/popup, use |coc#float#close()|. - Configuration of floating window/popup for signature documents, see - |coc-config-float|. + *coc-floating-focus* +Focus floating windows:~ -"signature.triggerSignatureWait":~ +On neovim, use w (or |(coc-float-jump)|) could focus a floating +window just created (if it's focusable). It's not allowed to focus popups on +vim, unless it's using a terminal buffer. - Timeout for signature request trigger (milliseconds), default: `500`. - Change to higher value for slow Language Servers. + *coc-floating-config* +Configure floating windows:~ -"signature.target":~ +To set custom window options on floating window create, use autocmd +|CocOpenFloat| or |CocOpenFloatPrompt|. - Target of signature help, use `"float"` when possible by default. +Related variables: - Valid options: ["float", "echo"] + โ€ข |g:coc_last_float_win| + โ€ข |g:coc_borderchars| + โ€ข |g:coc_border_joinchars| + โ€ข |g:coc_markdown_disabled_languages| -"signature.preferShownAbove":~ +Related highlight groups: - Show signature help's floating window above cursor when possible. - Requires restart on change, default: `true` + โ€ข |CocFloating| For floating window background. + โ€ข |CocFloatDividingLine| For dividing lines. + โ€ข |CocFloatActive| For active parts. + โ€ข |CocMenuSel| For selected line. -"signature.hideOnTextChange":~ +To customize floating windows used by popup menu, use: - Hide signature help's floating window when text changed. Requires - restart on change, default: `false` + โ€ข |coc-config-suggest-floatConfig| + โ€ข |coc-config-suggest-pumFloatConfig| - *coc-config-refactor* -"refactor.saveToFile":~ +For floating windows created around cursor, like diagnostics, hover and +signature use |coc-config-floatFactory-floatConfig| for common float +configurations. For further customization, use: - Save chagnes to file when write refactor buffer with |:write| command, - set to false if you want save buffer by yourself. + โ€ข |coc-config-diagnostic-floatConfig| + โ€ข |coc-config-signature-floatConfig| + โ€ข |coc-config-hover-floatConfig| -"refactor.openCommand":~ +For customize dialog windows, use |coc-config-dialog|. +For customize notification windows, use |coc-config-notification|. - Open command for refactor window, default: `vsplit` +Configure |coc-preferences-enableMessageDialog| to show messages as +notifications (except for the messages of unexpected errors which are always +echoed). -"refactor.beforeContext":~ +============================================================================== +LSP FEATURES *coc-lsp* - Print num lines of leading context before each match, default: `3` +Most features of LSP 3.17 are supported, checkout the specification at +https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/ -"refactor.afterContext":~ +Features not supported: - Print num lines of trailing context after each match, default: `3` + โ€ข Telemetry. + โ€ข Inline values for debugger. + โ€ข Notebook document. - *coc-config-hover* -"hover.target":~ +LSP features only works with attached documents, see |coc-document-attached|. - Target to show hover information, default is floating window when - possible. +To check exists providers of current buffer, use command +`:CocCommand document.checkBuffer` or API |CocHasProvider()|. - Valid options: ["preview", "echo", "float"] +For historic reason, some features automatically works by default, but some +are not. -"hover.previewMaxHeight":~ +Features automatically work by default:~ - Max height of preview window for hover, default: `12` + โ€ข Trigger completion |coc-completion|. + โ€ข Diagnostics refresh |coc-diagnostics|. + โ€ข Pull diagnostics |coc-pullDiagnostics|. + โ€ข Trigger signature help |coc-signature|. + โ€ข Inlay hints |coc-inlayHint| -"hover.floatConfig":~ +Most features could be toggled by |coc-configuration| and some vim variables. - Configuration of floating window/popup for hover documents, see - |coc-config-float|. +Features require enabled by configuration:~ -"hover.autoHide":~ + โ€ข Semantic highlights |coc-semantic-highlights|. + โ€ข Document color highlights |coc-document-colors|. + โ€ข Code lens, |coc-code-lens| + โ€ข Linked editing, |coc-linked-editing|. + โ€ข Format on type, enabled by |coc-preferences-formatOnType| + โ€ข Format on save, enabled by |coc-preferences-formatOnSave|. - Automatically hide hover float window on CursorMove or InsertEnter, - default `true`. +Features requested by user:~ - *coc-config-dialog* -"dialog.maxWidth": ~ + โ€ข Locations related (including definitions, references etc.) |coc-locations| + โ€ข Invoke code action |coc-code-actions|. + โ€ข Show call hierarchy tree |coc-callHierarchy|. + โ€ข Show type hierarchy tree |coc-typeHierarchy| + โ€ข Format, range format and on type format |coc-format|. + โ€ข Highlight same symbol ranges |coc-document-highlights|. + โ€ข Outline of document symbols |coc-outline| and |coc-list-symbols|. + โ€ข Show hover information |coc-hover|. + โ€ข Rename symbol under cursor |coc-rename|. + โ€ข Open link under cursor |coc-document-links|. + โ€ข Selection range |coc-selection-range| + โ€ข Create folding ranges |coc-fold|. - Maximum width of dialog window. +For convenient, some actions have associated |coc-key-mappings| provided. +Prefer |CocAction()| for more options. -"dialog.maxHeight": ~ +Features triggered by languageserver:~ - Maximum height of dialog window. + โ€ข Show message notification (use |coc-notification|). + โ€ข Show message request (use |coc-dialog-menu|). + โ€ข Log message notification (use `:CocCommand workspace.showOutput` to show + output). + โ€ข Show document request (opened by vim or your browser for url). + โ€ข Work done progress (use |coc-notification|). -"dialog.confirmKey":~ +To make coc.nvim provide LSP features for your languages, checkout +https://github.com/neoclide/coc.nvim/wiki/Language-servers - Confirm key for confirm selection used by menu and picker, you can - always use to cancel, default to ``. +To debug issues with languageserver, checkout +https://github.com/neoclide/coc.nvim/wiki/Debug-language-server -"dialog.pickerButtons":~ +------------------------------------------------------------------------------ +DOCUMENT *coc-document* - Show buttons for picker dialog window/popup, default `true`. +An associated document is created on buffer create, and disposed on buffer +unload. -"dialog.pickerButtonShortcut":~ +Attached document:~ + *coc-document-attached* - Show shortcut in buttons of picker dialog window/popup, used when - dialog.pickerButtons is true, default `true`. +An attached document means coc.nvim synchronize the lines of vim's buffer with +associated document automatically. -"dialog.floatHighlight":~ +Only attached documents are synchronized with language servers and therefore +LSP features could be provided for the attached buffer. - Highlight group for dialog window/popup, default to 'CocFloating'. +The buffer may not be attached by following reasons: -"dialog.floatBorderHighlight":~ + โ€ข The 'buftype' is neither nor 'acwrite', (could be bypassed by + |b:coc_force_attach|). + โ€ข Buffer variable |b:coc_enabled| is `0`. + โ€ข Byte length of buffer exceed |coc-preferences-maxFileSize|. + โ€ข Buffer is used for command line window. - Highlight group for border of dialog window/popup, default to - 'CocFloating'. +Use |CocAction('ensureDocument')| or `:CocCommand document.checkBuffer` to +check attached state of current buffer. - *coc-config-notification* -"notification.marginTop": ~ +Filetype map:~ + *coc-document-filetype* - Margin top for notification dialog, default to `1`. +Some filetypes are mapped to others to match the languageId used by VSCode, +including: -"notification.marginRight": ~ + โ€ข javascript.jsx -> javascriptreact + โ€ข typescript.jsx -> typescriptreact + โ€ข typescript.tsx -> typescriptreact + โ€ข tex -> latex - Margin right for notification dialog, default to `1`. +Use |g:coc_filetype_map| to create additional filetype maps. -"notification.maxWidth": ~ +Use `:CocCommand document.echoFiletype` to echo mapped filetype of current +document. - Maximum content width of notification dialog, default to `60`. +Note make sure use mapped filetypes for configurations that expect filetypes. -"notification.maxHeight": ~ +------------------------------------------------------------------------------ +HOVER *coc-hover* - Maximum content height of notification dialog, default to `10`. +Hover feature provide information at a given text document position, normally +include type information and documentation of current symbol. -"notification.highlightGroup": ~ +Hover functions:~ - Highlight group of notification dialog, default to `CocFloating`. + โ€ข |CocAction('doHover')| Show hover information at cursor position. + โ€ข |CocAction('definitionHover')||| Show hover information with definition + context at cursor position. + โ€ข |CocAction('getHover')| Get hover documentations at cursor position. -"notification.minProgressWidth": ~ + *coc-hover-example* +Hover key-mapping example:~ +> + nnoremap K :call ShowDocumentation() + " Show hover when provider exists, fallback to vim's builtin behavior. + function! ShowDocumentation() + if CocAction('hasProvider', 'hover') + call CocActionAsync('definitionHover') + else + call feedkeys('K', 'in') + endif + endfunction +< +------------------------------------------------------------------------------ +COMPLETION *coc-completion* - Minimum width of progress notification, default to `30`. +Vim's builtin completion is no longer used. The default completion +now works like in VSCode: - *coc-config-codelens* -"codeLens.enable":~ + โ€ข Completion is automatically triggered by default. + โ€ข Selection is enabled by default, use |coc-config-suggest-noselect| to + disable default selection. + โ€ข When selection is enabled and no preselect item exists, the first complete + item will be selected (depends on |coc-config-suggest-selection|). + โ€ข Snippet expand and additional edits only work after confirm completion. + โ€ข 'completeopt' is not used and APIs of builtin popupmenu not work. - Enable `codeLens` feature. Requires Neovim with virtual text feature, - default: `false`. + *coc-completion-default* +Default Key-mappings:~ -"codeLens.separator":~ +To make the new completion work like the builtin completion, without any +additional configuration, the following key-mappings are used when +the {lhs} is not mapped: - Separator text for `codeLens` in virtual text, default: `"โ€ฃ"`. +Use , , and to navigate completion list: > -"codeLens.subseparator":~ + inoremap coc#pum#visible() ? coc#pum#next(1) : "\" + inoremap coc#pum#visible() ? coc#pum#prev(1) : "\" + inoremap coc#pum#visible() ? coc#pum#next(0) : "\" + inoremap coc#pum#visible() ? coc#pum#prev(0) : "\" +< +Use and to scroll: > - Subseparator text for multiple `codeLens`es in virtual text, default: `" "` + inoremap coc#pum#visible() ? coc#pum#scroll(1) : "\" + inoremap coc#pum#visible() ? coc#pum#scroll(0) : "\" +< +Use and to cancel and confirm completion: > + + inoremap coc#pum#visible() ? coc#pum#cancel() : "\" + inoremap coc#pum#visible() ? coc#pum#confirm() : "\" + +Note: and are not remapped by coc.nvim. + + *coc-completion-variables* +Related variables:~ + + โ€ข Disable completion for buffer: |b:coc_suggest_disable| + โ€ข Disable specific sources for buffer: |b:coc_disabled_sources| + โ€ข Disable words for completion: |b:coc_suggest_blacklist| + โ€ข Add additional keyword characters: |b:coc_additional_keywords| + + *coc-completion-functions* +Related functions:~ + + โ€ข Trigger completion with options: |coc#start()|. + โ€ข Trigger completion refresh: |coc#refresh()|. + โ€ข Select and confirm completion: |coc#_select_confirm()|. + โ€ข Check if the custom popupmenu is visible: |coc#pum#visible()|. + โ€ข Select the next completion item: |coc#pum#next()|. + โ€ข Select the previous completion item: |coc#pum#prev()|. + โ€ข Cancel completion and reset trigger text: |coc#pum#cancel()|. + โ€ข Confirm completion: |coc#pum#confirm()|. + โ€ข Close the popupmenu only: |coc#pum#stop()|. + โ€ข Get information about the popupmenu: |coc#pum#info()|. + โ€ข Select specific completion item: |coc#pum#select()|. + โ€ข Insert word of selected item and finish completion: |coc#pum#insert()|. + โ€ข Insert one more character from current complete item: |coc#pum#one_more()|. + โ€ข Scroll popupmenu: |coc#pum#scroll()|. + + *coc-completion-customize* +Customize completion:~ + +Use |coc-config-suggest| to change the completion behavior. + +Use 'pumwidth' for configure the minimal width of the popupmenu and 'pumheight' +for its maximum height. + +Related Highlight groups: + |CocPum| for highlight groups of customized pum. + |CocSymbol| for kind icons. + |CocMenuSel| for background highlight of selected item. + +Note: background, border and winblend are configured by +|coc-config-suggest-floatConfig|. + +Example user key-mappings:~ + *coc-completion-example* + +Note: use command `:verbose imap` to check current insert +key-mappings when your key-mappings not work. + +Use and to navigate completion list: > + + function! CheckBackspace() abort + let col = col('.') - 1 + return !col || getline('.')[col - 1] =~ '\s' + endfunction + + " Insert when previous text is space, refresh completion if not. + inoremap + \ coc#pum#visible() ? coc#pum#next(1): + \ CheckBackspace() ? "\" : + \ coc#refresh() + inoremap coc#pum#visible() ? coc#pum#prev(1) : "\" + +Use to trigger completion: > + + if has('nvim') + inoremap coc#refresh() + else + inoremap coc#refresh() + endif +< +Use to confirm completion, use: > -"workspace.ignoredFiletypes":~ + inoremap coc#pum#visible() ? coc#_select_confirm() : "\" +< +To make to confirm selection of selected complete item or notify coc.nvim +to format on enter, use: > - Filetypes to ignore for workspace folder resolution, - default: `["markdown","log","txt","help"]` + inoremap coc#pum#visible() ? coc#_select_confirm() + \: "\u\\=coc#on_enter()\" - Note: This is the filetype after mapping by `g:coc_filetype_map`. +Map for trigger completion, completion confirm, snippet expand and jump +like VSCode: > -"workspace.bottomUpFiletypes":~ + inoremap + \ coc#pum#visible() ? coc#_select_confirm() : + \ coc#expandableOrJumpable() ? + \ "\=coc#rpc#request('doKeymap', ['snippets-expand-jump',''])\" : + \ CheckBackspace() ? "\" : + \ coc#refresh() - Filetypes that should have workspace folder should resolved from - base directory of file. + function! CheckBackspace() abort + let col = col('.') - 1 + return !col || getline('.')[col - 1] =~# '\s' + endfunction -"workspace.workspaceFolderCheckCwd":~ + let g:coc_snippet_next = '' +< +Note: the `coc-snippets` extension is required for this to work. - Whether the cwd directory should be checked first when resolving - workspace folder of current buffer. +------------------------------------------------------------------------------ +DIAGNOSTICS SUPPORT *coc-diagnostics* - *coc-config-list* -"list.indicator":~ +Diagnostics of coc.nvim are automatically refreshed to UI by default, checkout +|coc-config-diagnostic| for available configurations. - The character used as first character in prompt line, default: `">"` +Note most language servers only send diagnostics for opened buffers for +performance reason, some lint tools could provide diagnostics for all files in +workspace. -"list.alignColumns":~ +Note pull diagnostics feature is added in LSP 3.17, which is not available +yet. - Whether to align lists in columns, default: `false` + *coc-diagnostics-refresh* +Changes on diagnostics refresh~ -"list.height":~ + โ€ข Add highlights for diagnostic ranges and virtual text (when enabled on + neovim or vim >= 9.0.0067), see |coc-highlights-diagnostics|. + โ€ข Add diagnostic signs to 'signcolumn', use `set signcolumn=yes` to avoid + unnecessary UI refresh. + โ€ข Update variable |b:coc_diagnostic_info|. + โ€ข Refresh related |location-list| which was opened by |:CocDiagnostics|. - Height of split list window, default: `10` +Diagnostics are not refreshed when buffer is hidden, and refresh on insert +mode is disabled by default. -"list.signOffset":~ +Diagnostics highlights:~ - Sign offset of list, should be different from other plugins, default: - `900` +See |coc-highlights-diagnostics|. -"list.selectedSignText":~ + *coc-diagnostics-toggle* +Enable and disable diagnostics~ - Sign text for selected lines, default: `"*"` +Use |coc-config-diagnostic-enable| to toggle diagnostics feature. -"list.limitLines":~ +Use |CocAction('diagnosticToggle')| for enable/disable diagnostics feature. - Limit lines shown in the list buffer, default: `30000` +Use |CocAction('diagnosticToggleBuffer')| for enable/disable diagnostics of +current buffer. -"list.maxPreviewHeight":~ +Show diagnostic messages~ - Max height for preview window of list, default: `12` +Diagnostic messages would be automatically shown/hide when the diagnostics +under cursor position changed (use float window/popup when possible) by +default. -"list.matchHighlightGroup":~ +To manually refresh diagnostics messages, use |(coc-diagnostic-info)| +and |CocAction('diagnosticPreview')|. - Highlight group used for matched texts in list window. - default: `"Search"` + *coc-diagnostics-jump* +Jump between diagnostics~ -"list.previewHighlightGroup":~ +Use key-mappings: - Highlight group used for highlighting the range in preview window, - default: `"Search"` + |(coc-diagnostic-next)| jump to diagnostic after cursor position. + |(coc-diagnostic-prev)| jump to diagnostic before cursor position. + |(coc-diagnostic-next-error)| jump to next error. + |(coc-diagnostic-prev-error)| jump to previous error. -"list.previewToplineStyle":~ +Check all diagnostics~ - Topline style for list previews - default: `"offset"` - Valid options: ["offset","middle"] +Use |coc-list-diagnostics| to open |coc-list| with all available diagnostics. -"list.previewToplineOffset":~ +Use API |CocAction('diagnosticList')| to get list of all diagnostics. - Topline offset for list previews - default: `3` +------------------------------------------------------------------------------ +PULL DIAGNOSTICS SUPPORT *coc-pullDiagnostics* -"list.nextKeymap":~ +Diagnostics are pulled for visible documents when supported by languageserver. +Pull for workspace diagnostics is also enabled by default. - Key for selecting next line in the insert mode, default: `""` +Document diagnostics are pulled on change by default, and can be +configured to be pulled on save. -"list.previousKeymap":~ +Checkout |coc-config-pullDiagnostic| for related configurations. - Key for selecting previous line in the insert mode, default: `""` +------------------------------------------------------------------------------ +LOCATIONS SUPPORT *coc-locations* -"list.extendedSearchMode": ~ +There're different kinds of locations, including "definitions", "declarations", +"implementations", "typeDefinitions" and "references". - Enable extended search mode which allows multiple search patterns - delimited by spaces, default: `true` +Key-mappings for invoke locations request~ -"list.normalMappings":~ + โ€ข |(coc-definition)| + โ€ข |(coc-declaration)| + โ€ข |(coc-implementation)| + โ€ข |(coc-type-definition)| + โ€ข |(coc-references)| + โ€ข |(coc-references-used)| - Custom key mappings in the normal mode, default: `{}` +Error will be shown when the buffer not attached |coc-document-attached|. +Message will be shown when no result found. -"list.insertMappings":~ +Location jump behavior~ - Custom key mappings in the insert mode, default: `{}` +When there's only one location returned, the location is opened by command +specified by |coc-preferences-jumpCommand| ("edit" by default), context mark +is added by |m'|, so you can jump back previous location by . -"list.interactiveDebounceTime":~ +When multiple locations returned, |coc-list-location| is opened for preview +and other further actions. - Debouce time for input change on interactive mode, default: `100` +To use |coc-list-location| for single location as well, use +|coc-locations-api| (instead key-mappings provided by coc.nvim). -"list.previewSplitRight":~ +To change default options of |coc-list-location| or use other plugin for +list of locations, see |g:coc_enable_locationlist|. - Use vsplit for preview window, default: `false` +To use vim's quickfix for locations, use configuration +|coc-preferences-useQuickfixForLocations|. -"list.source.symbols.excludes":~ +To use vim's tag list for definitions, use |CocTagFunc()|. - Patterns of minimatch for filepath to execlude from symbols list, - default: `[]` + *coc-locations-api* +Related APIs~ -"list.source.outline.ctagsFilestypes":~ + โ€ข |CocAction('jumpDefinition')| Jump to definition locations. + โ€ข |CocAction('jumpDeclaration')| Jump to declaration locations. + โ€ข |CocAction('jumpImplementation')| Jump to implementation locations. + โ€ข |CocAction('jumpTypeDefinition')| Jump to type definition locations. + โ€ข |CocAction('jumpReferences')|| Jump to references. + โ€ข |CocAction('jumpUsed')| Jump to references without declarations. + โ€ข |CocAction('definitions')| Get definition list. + โ€ข |CocAction('declarations')| Get declaration list. + โ€ข |CocAction('implementations')| Get implementation list. + โ€ข |CocAction('typeDefinitions')| Get type definition list. + โ€ข |CocAction('references')| Get reference list. - Filetypes that should use `ctags` for outline instead of language server, - default: `[]` +Send custom locations request to languageserver: + โ€ข |CocLocations()| + โ€ข |CocLocationsAsync()| -"list.source.diagnostics.pathFormat":~ +------------------------------------------------------------------------------ +RENAME *coc-rename* - Decide how the filepath is shown in the list. +Rename provides workspace-wide rename of a symbol. Workspace edit +|coc-workspace-edit| is requested and applied to related buffers when +confirmed. - Valid options: ["full", "short", "filename", "hidden"]. +Check if current buffer has rename provider with +`:echo CocAction('hasProvider', 'rename')` - default: `"full"` +Rename key-mappings:~ -"list.source.diagnostics.includeCode":~ + โ€ข |(coc-rename)| - Whether to show the diagnostic code in the list. +Rename functions:~ - default: `true` + โ€ข |CocAction('rename')| Rename the symbol under the cursor. + โ€ข |CocAction('refactor')| Open refactor buffer for all references (including + definitions), recommended for function signature refactor. - *coc-config-preferences* -"coc.preferences.enableMessageDialog"~ +Rename local variable:~ - Enable messages shown in notification dialog, default: `false` +Use command `:CocCommand document.renameCurrentWord` which uses |coc-cursors| +to edit multiple locations at the same time and defaults to word extraction +when rename provider doesn't exist. -"coc.preferences.maxFileSize":~ +Rename configuration:~ - Maximum file size in bytes that coc.nvim should handle, default: `'10MB'` +Use |coc-preferences-renameFillCurrent| to enable/disable populating prompt +window with current variable name. -"coc.preferences.promptWorkspaceEdit":~ +------------------------------------------------------------------------------ +SIGNATURE HELP *coc-signature* - Prompt confirm from user for workspace edit. - default: `true` +Signature help for functions is shown automatically when user +types trigger characters defined by the provider, which will use floating +window/popup to show relevant documentation. -"coc.preferences.useQuickfixForLocations":~ +Use |CocAction('showSignatureHelp')| to trigger signature help manually. - Use Vim's quickfix list for jump locations. Requires restart on change, - default: `false` +Note error will not be thrown when provider does not exist or nothing is returned +by languageserver, use `echo CocAction('hasProvider', 'signature')` to check +if a signature help provider exists. -"coc.preferences.extensionUpdateCheck":~ +Use |coc-config-signature| to change default signature help behavior. - Interval for checking extension updates, default: `"daily"` +|CocFloatActive| is used to highlight activated parameter part. - Valid options: ["daily","weekly","never"] +------------------------------------------------------------------------------ +INLAY HINT *coc-inlayHint* -"coc.preferences.snippetStatusText":~ +Inlay hint is enabled for all filetypes by default. Inlay hint uses virtual +text which requires neovim >= 0.5.0 or vim >= 9.0.0067. - Text shown in 'statusline' to indicate snippet session is activate. - Check |coc-status| for statusline integration. +Note: you may need configure extension or languageserver to make inlay hint +works. - Default: `"SNIP"` +To temporarily toggle inlay hint of current buffer, use command +`:CocCommand document.toggleInlayHint` -"coc.preferences.colorSupport":~ +Change highlight group:~ - Enable color highlight if Language Server support it, default: `true` + โ€ข |CocInlayHint| + โ€ข |CocInlayHintType| + โ€ข |CocInlayHintParameter| -"coc.preferences.currentFunctionSymbolAutoUpdate":~ +Configure inlay hint support:~ - Automatically update the value of `b:coc_current_function` on `CursorHold` - event, default: `false` +|coc-config-inlayHint| -"coc.preferences.formatOnSaveFiletypes":~ +------------------------------------------------------------------------------ +FORMAT *coc-format* - Filetypes for which formatting triggers after saving, default: `[]` +Some tools may reload buffer from disk file during format, coc.nvim only +apply `TextEdit[]` to the document. - Note: This is the filetype after mapping by `g:coc_filetype_map`. +Don't be confused with vim's indent feature, configure/fix the 'indentexpr' of +your buffer if the indent is wrong after character insert. (use +|coc-format-ontype| might helps with the indent) -"coc.preferences.enableFloatHighlight":~ + *coc-format-options* +Format options:~ - Enable highlight for floating window, default: `true` +Buffer options that affect document format: 'eol', 'shiftwidth' and +'expandtab'. -"coc.preferences.rootPatterns":~ + โ€ข |b:coc_trim_trailing_whitespace| Trim trailing whitespace on a line. + โ€ข |b:coc_trim_final_newlines| Trim all newlines after the final newline at + the end of the file. - Root patterns to resolve `workspaceFolder` from parent folders of opened - files, resolved from up to down, default: - `[".git",".hg",".projections.json"]` +Those options are converted to `DocumentFormattingOptions` and transferred to +languageservers before format. Note: the languageservers may only support +some of those options. -"coc.preferences.watchmanPath":~ + *coc-format-document* +Format full document:~ - Executable path for https://facebook.github.io/watchman/, detected - from $PATH by default, default: `null` +Use |CocAction('format')|, you can create a command like: > -"coc.preferences.jumpCommand":~ + command! -nargs=0 Format :call CocActionAsync('format') +< +to format current buffer. - Command used for location jump performed for goto definition, goto - references etc, default: `"edit"` + *coc-format-ontype* +Format on type:~ - Valid options: ["edit", "split", "vsplit", "tabe", "drop", "tab drop"] +Format on type could be enabled by |coc-preferences-formatOnType|. -"coc.preferences.messageLevel":~ +Use `:CocCommand document.checkBuffer` to check if `formatOnType` provider +exists for current buffer. - Message level for filter echoed messages default: `"more"` +To format on , create key-mapping of that uses |coc#on_enter()|. - Valid options: ["more", "warning", "error"] +If you don't like the behavior on type bracket characters, configure +|coc-preferences-bracketEnterImprove||. -"coc.preferences.formatOnType":~ + *coc-format-selected* +Format selected code:~ - Set to true to enable format on type, default: `false` +Use 'formatexpr' for specific filetypes: > -"coc.preferences.bracketEnterImprove":~ + autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected') - Improve handling of pressing enter inside brackets (`<> {} [] ()`) by - create a new empty line in the middle, the indent is calculated by vim, - checkout |indentexpr| for details. +So that |gq| could works for format range of lines. +> +Setup visual mode and operator key-mappings: > - Works with |coc#on_enter()|, default: `true` + xmap f (coc-format-selected) + nmap f (coc-format-selected) +< + *coc-format-onsave* +Format on save:~ -"coc.preferences.formatOnTypeFiletypes":~ +To enable format on save, use configuration |coc-preferences-formatOnSave|. - Filetypes that should run format on typing, default: `[]` +Or create |BufWritePre| autocmd like: > - Note: takes effect when `coc.preferences.formatOnType` set `true`. - Note: This is the filetype after mapping by `g:coc_filetype_map`. + autocmd BufWritePre * call CocAction('format') +< +Note the operation have to synchronized, avoid use |CocActionAsync()|. +Note to skip the autocmd, use `:noa w` to save the buffer. -"coc.preferences.listOfWorkspaceEdit":~ +The operation on save will block your vim, to not block too long time, the +operation will be canceled after 0.5s, configured by +|coc-preferences-willSaveHandlerTimeout| - List should contains changed locations after workspace edit, default - to vim's quickfix, default: `quickfix` +------------------------------------------------------------------------------ +CODE ACTION *coc-code-actions* +Code actions are used for ask languageserver to provide specific kind code +changes. -"coc.preferences.floatActions":~ +Possible code action kinds: - Set to false to disable float/popup support for actions menu. - Default: `true` + โ€ข `quickfix` used for fix diagnostic(s). + โ€ข `refactor` used for code refactor. + โ€ข `source` code actions apply to the entire file. + โ€ข `organizeImport` organize import statements of current document. -"coc.preferences.promptInput":~ +Key-mappings for code actions:~ - Use prompt buffer in float window for user input. - Default: `true` + โ€ข |(coc-fix-current)| Invoke quickfix action at current line if any. + โ€ข |(coc-codeaction-cursor)| Choose code actions at cursor position. + โ€ข |(coc-codeaction-line)| Choose code actions at current line. + โ€ข |(coc-codeaction)| Choose code actions of current file. + โ€ข |(coc-codeaction-source)| Choose source code action of current file. + โ€ข |(coc-codeaction-selected)| Choose code actions from selected range. + โ€ข |(coc-codeaction-refactor)| Choose refactor code action at cursor + position. + โ€ข |(coc-codeaction-refactor-selected)| Choose refactor code action with + selected code. -"coc.preferences.enableMarkdown":~ +Except for |(coc-fix-current)| which invoke code action directly, +|coc-dialog-menu| would be shown for pick specific code action. - Tell the language server that markdown text format is supported, - note that you may have additional escaped characters for markdown - text. +To invoke organize import action, use command like: +> + command! -nargs=0 OR :call CocAction('organizeImport') -"coc.preferences.silentAutoupdate"~ +See |CocAction('organizeImport')| for details. - Not open split window with update status when performing auto update. +Related APIs~ -"coc.preferences.willSaveHandlerTimeout"~ + โ€ข |CocAction('codeActions')| + โ€ข |CocAction('organizeImport')| + โ€ข |CocAction('fixAll')| + โ€ข |CocAction('quickfixes')| + โ€ข |CocAction('doCodeAction')| + โ€ข |CocAction('doQuickfix')| + โ€ข |CocAction('codeActionRange')| - Will save handler timeout, default: `500` +------------------------------------------------------------------------------ +DOCUMENT HIGHLIGHTS *coc-document-highlights* - *coc-config-cursors* +Document highlights is used for highlight same symbols of current document +under cursor. -"cursors.cancelKey":~ +To enable highlight on CursorHold, create an autocmd like this: > - Key used for cancel cursors session, default: `` + autocmd CursorHold * call CocActionAsync('highlight') +< +Checkout |coc-highlights-document| for related highlight groups. -"cursors.nextKey":~ +Note error will not be thrown when provider not exists or nothing returned +from languageserver with |CocAction('highlight')| - Key used for jump to next cursors position. , default: `` +Install `coc-highlight` extension if you want to highlight same words under +cursor without languageserver support. -"cursors.previousKey":~ +To jump between previous/next symbol position, use +`:CocCommand document.jumpToPrevSymbol` and +`:CocCommand document.jumpToNextSymbol` - Key used for jump to previous cursors position, default: `` +------------------------------------------------------------------------------ +DOCUMENT COLORS *coc-document-colors* - *coc-config-tree* -"tree.closedIcon": ~ - - Closed icon of tree view, use '๏„…' to make it looks better when you - have patched font, default: '+'. +Document colors added color highlights to vim buffers. To enable document +color highlights, use |coc-config-colors-enable|. -"tree.openedIcon": ~ - - Opened icon of tree view, use '๏„‡' to make it looks better when you - have patched font, default: '-' +The feature requires vim >= 8.1.1719 or neovim >= 0.5.0. -"tree.key.toggleSelection":~ +Note: the highlights define gui colors only, make use you have 'termguicolors' +enabled (and your terminal support gui colors) if you're using vim in +terminal. - Trigger key to select/unselect item, default: +To pick a color from system color picker, use |CocAction('pickColor')| or +choose `editor.action.pickColor` from |:CocCommand|. -"tree.key.toggle":~ +Note: pick color may not work on your system. - Trigger key to toggle expand state of tree node, default: 't' +To change color presentation, use |CocAction('colorPresentation')| or choose +`editor.action.colorPresentation` from |:CocCommand|. -"tree.key.actions":~ +To highlights colors without languageservers, install +https://github.com/neoclide/coc-highlight - Trigger key to invoke actions, default: +============================================================================== +DOCUMENT LINKS *coc-document-links* -"tree.key.collapseAll":~ +Check if current buffer have documentLink provider by +`:echo CocAction('hasProvider', 'documentLink')` - Trigger key to collapse all tree node, default: 'M' +Highlight and tooltip of the links could be configured by |coc-config-links|. -"tree.key.invoke":~ +Use |coc-list-links| to manage list of links in current document. - Trigger key to invoke default command of current node or selection, - default: +Document link key-mappings:~ -"tree.key.close":~ +|(coc-openlink)| - Trigger key to dispose the tree and close tree window, default: +Document link functions:~ -"tree.key.activeFilter":~ + โ€ข |CocAction('openLink')| Open link under cursor. + โ€ข |CocAction('links')| Get link list of current buffer. - Trigger key active filter, only works when tree view support filter, - default: 'f' +------------------------------------------------------------------------------ +SNIPPETS SUPPORT *coc-snippets* -"tree.key.selectNext":~ +Snippets engine of coc.nvim support both VSCode snippets and ultisnips +snippets format. - Trigger key to select next item during filter, default +The completion item with snippet format has label ends with +|coc-config-suggest-snippetIndicator| (`~` by default). -"tree.key.selectPrevious":~ +Select the complete item and confirm the completion by |coc#pum#confirm()| or +|coc#_select_confirm()| to expand the snippet of current selected complete +ttem. - Trigger key to select previous item during filter, default +Jump snippet placeholders:~ - *coc-config-outline* -"outline.splitCommand":~ +|g:coc_snippet_next| and |g:coc_snippet_prev| are used to jump placeholders on +both select mode and insert mode, which defaults to and . Buffer +key-mappings are created on snippet activate, and removed on snippet +deactivate. - Window split command used by outline, default 'botright 30vs' +Deactivate snippet session:~ -"outline.followCursor":~ +A snippet session would be deactivated under the following conditions: - Reveal item in outline tree on cursor hold, default `true` + โ€ข |InsertEnter| triggered outside snippet. + โ€ข Jump to final placeholder. + โ€ข Content change detected after snippet. + โ€ข Content changed in a snippet outside placeholder (except for deletion of + plain text). -"outline.keepWindow":~ +To load and expand custom snippets, install `coc-snippets` extension is +recommended. - Jump back to original window after outline is shown, default `false` +Related configurations:~ -"outline.sortBy":~ + โ€ข |g:coc_snippet_prev| + โ€ข |g:coc_snippet_next| + โ€ข |g:coc_selectmode_mapping| + โ€ข |coc-config-suggest-snippetIndicator| + โ€ข |coc-config-suggest-preferCompleteThanJumpPlaceholder| + โ€ข |coc-config-snippet-highlight| + โ€ข |coc-config-snippet-statusText| + โ€ข |coc-config-snippet-nextPlaceholderOnDelete| - Sort method for symbols, default: 'category' - Could be 'position', 'name' or 'category'. +Related functions:~ -"outline.expandLevel":~ + โ€ข |coc#snippet#next()| + โ€ข |coc#snippet#prev()| + โ€ข |coc#expandable()| + โ€ข |coc#jumpable()| + โ€ข |coc#expandableOrJumpable()| - Default expand level of tree nodes, default `1` +Related variables, highlights and autocmds:~ -"outline.checkBufferSwitch":~ + โ€ข |b:coc_snippet_active| Check if snippet session is activated. + โ€ข |CocSnippetVisual| For highlight of current placeholders. + โ€ข |CocJumpPlaceholder| AutocmdS triggered after placeholder jump. - Recreate outline view after changed to another buffer on current tab. - Default `true` +------------------------------------------------------------------------------ +WORKSPACE SUPPORT *coc-workspace* -"outline.showLineNumber": ~ + *coc-workspace-folders* +Workspace folders~ - Show line number of document symbols. - Default `true` +Unlike VSCode which prompt you to open folders, workspace folders of coc.nvim +are resolved from filepath after document attached. -"outline.codeActionKinds":~ +A list of file/folder names is used for resolve workspace folder, the patterns +could comes from: - Filter code actions in actions menu by kinds. - Default: ["", "quickfix", "refactor", "source"] + โ€ข |b:coc_root_patterns| + โ€ข "rootPatterns" field of languageserver in |coc-config-languageserver|. + โ€ข "rootPatterns" contributions from coc.nvim extensions. + โ€ข |coc-config-workspace-rootPatterns| - *coc-config-callHierarchy* +Workspace folder is resolved from cwd of vim first (by default) and then from +top directory to the parent directory of current filepath, when workspace +folder not resolved, current working directory is used if it's parent folder +of current buffer. Configurations are provided to change the default behavior: -"callHierarchy.openCommand":~ + โ€ข |coc-config-workspace-ignoredFiletypes| + โ€ข |coc-config-workspace-ignoredFolders| + โ€ข |coc-config-workspace-bottomUpFiletypes| + โ€ข |coc-config-workspace-workspaceFolderCheckCwd| + โ€ข |coc-config-workspace-workspaceFolderFallbackCwd| - Open command for callHierarchy tree view, default to "edit". - -"callHierarchy.splitCommand":~ +Note for performance reason, user's home directory would never considered as +workspace folder, which also means the languageserver that requires workspace +folder may not work when you start vim from home directory. - Window split command used by callHierarchy tree view. +To preserve workspace folders across vim session, |g:WorkspaceFolders| is +provided. -"callHierarchy.enableTooltip":~ +Use `:CocCommand workspace.workspaceFolders` to echo current workspaceFolders. - Enable tooltip to show relative filepath of call hierarchy. +To manage current workspace folders, use |coc-list-folders| - *coc-config-npm* -"npm.binPath":~ +To get related root patterns of current buffer, use |coc#util#root_patterns()| - Command or full path of npm or yarn executable for install/update - extensions, default: `npm` + *coc-workspace-edits* +Workspace edit~ - *coc-config-float* +Workspace edit is used to apply changes for multiple buffers(and/or files), the +edit could contains document edits and file operations (including file create, +file/directory delete and file/directory rename). -Used by `suggest.floatConfig`, `diagnostic.floatConfig`, -`signature.floatConfig` and `hover.floatConfig`, following properties are -supported: +When the edit failed to apply, coc.nvim will revert the changes (including +document edits and file operations) that previous made. - - "border": Change to `true` to enable border. - - "highlight": Background highlight group of float window. - - "title": Title used by float window. - - "borderhighlight": Border highlight group of float window. - - "close": Set to true to draw close icon. - - "maxWidth": Maximum width of float window, contains border. - - "maxHeight": Maximum height of float window, contains border. - - "winblend": Set 'winblend' option of window, neovim only. - - "focusable": Set to false to make window not focusable, neovim only. - - "shadow": Set to true to enable shadow, neovim only. +Files not loaded would be loaded by `tab drop` command, configured by +|coc-config-workspace-openResourceCommand|. - *coc-config-languageserver* -"languageserver":~ +To undo and redo workspace edit just applied, use command +`:CocCommand workspace.undo` and `:CocCommand workspace.redo` - Dictionary of Language Servers, key is the ID of corresponding server, - and value is configuration of languageserver. Default: `{}` +To inspect previous workspace edit, use command +`:CocCommand workspace.inspectEdit`, in opened buffer, use for jump to +change position under cursor. - Properties of languageserver configuration: +------------------------------------------------------------------------------ +CURSORS SUPPORT *coc-cursors* - - "enable": Change to `false` to disable that languageserver. +Multiple cursors supported is added to allow edit multiple locations at once. - - "filetypes": Supported filetypes, add * in array for all filetypes. - Note: it's required for start the languageserver, please make sure - your filetype is expected by `:CocCommand document.echoFiletype` command +Cursors session could be started by following ways: - - "additionalSchemes": Additional uri schemes, default schemes - including file & untitled. - Note: you have to setup vim provide content for custom uri as well. + โ€ข Use command `:CocCommand document.renameCurrentWord` to rename variable + under cursor. + โ€ข Use |(coc-refactor)| to open refactor buffer. + โ€ข Use |:CocSearch| to open searched locations. + โ€ข Use cursors related key-mappings to add text range, including + |(coc-cursors-operator)|, |(coc-cursors-word)|, + |(coc-cursors-position)| and |(coc-cursors-range)| + โ€ข Ranges added by command `editor.action.addRanges` from coc extensions. - - "cwd": Working directory used to start languageserver, vim's cwd is - used by default. +Default key-mappings when cursors activated: - - "env": Environment variables for child process. + โ€ข cancel cursors session. + โ€ข jump to next cursors range. + โ€ข jump to previous cursors range. - - "settings": Settings for languageserver, received on server - initialization. +Use |coc-config-cursors| to change cursors related key-mappings. +Use highlight group |CocCursorRange| to change default range highlight. +Use |b:coc_cursors_activated| to check if cursors session is activated. - - "trace.server": Trace level of communication between server and - client that showed with output channel. +-------------------------------------------------------------------------------- +SYMBOLS OUTLINE *coc-outline* - - "stdioEncoding": Encoding used for stdio of child process. +Outline is a split window with current document symbols rendered as +|coc-tree|. - - "initializationOptions": Initialization options passed to - languageserver (it's deprecated) +To show and hide outline of current window, use |CocAction('showOutline')| and +|CocAction('hideOutline')|. - - "rootPatterns": Root patterns used to resolve rootPath from current - file. +Outline view has Window variable `cocViewId` set to `OUTLINE`. - - "requireRootPattern": If true, doesn't start server when root - pattern not found. +Following outline features are supported: - - "ignoredRootPaths": Absolute root paths that language server should - not use as rootPath, higher priority than rootPatterns. + โ€ข Start fuzzy filter by |coc-config-tree-key-activeFilter|. + โ€ข Automatic update after document change. + โ€ข Automatic reload when buffer in current window changed. + โ€ข Automatic follow cursor position by default. + โ€ข Different filter modes that can be changed on the fly + |coc-config-outline-switchSortKey|. + โ€ข Enable auto preview by |coc-config-outline-togglePreviewKey|. - - "disableDynamicRegister": Disable dynamic registerCapability feature - for this languageserver to avoid duplicated feature regstration. +Outline would try to reload document symbols after 500ms when provider not +registered, which avoid the necessary to check provider existence. - - "disableWorkspaceFolders": Disable workspaceFolders feature for this - languageserver. +Checkout |coc-config-tree| and |coc-config-outline| for available +configurations. - - "disableSnippetCompletion": Disable snippet completion feature for - this languageserver. +Checkout |CocTree| and |CocSymbol| for customize highlights. - - "disableDiagnostics": Disable handle diagnostics for this - languageserver. +Use configuration `"suggest.completionItemKindLabels"` for custom icons. - - "disableCompletion": Disable completion feature for this - languageserver. +To show outline for each tab automatically, use |autocmd|: +> + autocmd VimEnter,Tabnew * + \ if empty(&buftype) | call CocActionAsync('showOutline', 1) | endif +< +To close outline when it's the last window automatically, use +|autocmd| like: +> + autocmd BufEnter * call CheckOutline() + function! CheckOutline() abort + if &filetype ==# 'coctree' && winnr('$') == 1 + if tabpagenr('$') != 1 + close + else + bdelete + endif + endif + endfunction +< +Create a key-mapping to toggle outline, like: +> + nnoremap o :call ToggleOutline() + function! ToggleOutline() abort + let winid = coc#window#find('cocViewId', 'OUTLINE') + if winid == -1 + call CocActionAsync('showOutline', 1) + else + call coc#window#close(winid) + endif + endfunction +< +-------------------------------------------------------------------------------- +CALL HIERARCHY *coc-callHierarchy* - - "formatterPriority": Priority of this languageserver's fomatter. +A call hierarchy is a split |coc-tree| window with locations for incoming or +outgoing calls of function under cursor position. - - "revealOutputChannelOn": Configure message level to show the output - channel buffer. +Call hierarchy window is opened by |CocAction('showIncomingCalls')| and +|CocAction('showOutgoingCalls')|. - - "progressOnInitialization": Enable progress report on languageserver - initialize. +Call hierarchy is configured by |CocSymbol|, |coc-config-callHierarchy| and +|coc-config-tree|. -Language server start with command:~ +Related ranges are highlighted with |CocSelectedRange| highlight group in +opened buffer. - Additional fields can be used for command language server: +|coc-dialog-menu| could be invoked by |coc-config-tree-key-actions| (default +to ). Available actions: - - "command": Executable program name in $PATH or absolute path of - executable used for start languageserver. + โ€ข Dismiss. + โ€ข Open in new tab. + โ€ข Show Incoming Calls. + โ€ข Show Outgoing Calls. - - "args": Command line arguments of command. +Use in call hierarchy tree to open location in original window. - - "detached": Detach language server when is true. +-------------------------------------------------------------------------------- +TYPE HIERARCHY *coc-typeHierarchy* - - "shell": Use shell for server process, default: `false` +A type hierarchy is a split |coc-tree| window with locations for super types +or sub types from types at current position. -Language server start with module:~ +Type hierarchy window is opened by |CocAction('showSuperTypes')| and +|CocAction('showSubTypes')|. - Additional fields can be used forlanguage server started by node - module: +Type hierarchy is configured by |CocSymbol|, |coc-config-typeHierarchy| and +|coc-config-tree|. - - "module": Absolute filepath of javascript file. +Actions are the same as |coc-callHierarchy|. - - "args": Extra arguments used on fork javascript module. +-------------------------------------------------------------------------------- +SEMANTIC HIGHLIGHTS *coc-semantic-highlights* - - "runtime": Absolute path of node runtime, node runtime of coc.nvim - is used by default. +Semantic tokens are used to add additional color information to a buffer that +depends on language specific symbol information. - - "execArgv": Argv passed to node on fork, normally used for - debugging, example: `["--nolazy", "--inspect-brk=6045"]` +The feature requires vim >= 8.1.1719 or neovim >= 0.5.0. - - "transport": Transport kind used by server, could be 'ipc', 'stdio', - 'socket' and 'pipe'. 'ipc' is used by default (recommended). +Use |coc-config-semanticTokens-enable| to enable semantic tokens highlights. - - "transportPort": Port number used when transport is 'socket'. +Use `:CocCommand semanticTokens.checkCurrent` to check semantic highlight +information with current buffer. -Language server use initialized socket server:~ +To create custom highlights for symbol under cursor, follow these steps: - - "port": Port number of socket server. + โ€ข Inspect semantic token by +> + :CocCommand semanticTokens.inspect +< + to check token type and token modifiers with current symbol. - - "host": Host of socket server, default to `127.0.0.1`. + โ€ข Create new highlight group by |highlight|, for example: +> + :hi link CocSemDeclarationVariable MoreMsg +< + โ€ข Refresh semantic highlight of current buffer by: +> + :CocCommand semanticTokens.refreshCurrent +< +See |CocSem| to customize semantic token highlight groups. -============================================================================== -COMPLETION *coc-completion* +See |coc-config-semanticTokens| for related configurations. -Default behavior of coc.nvim's completion: +-------------------------------------------------------------------------------- +FOLD *coc-fold* -- Completion is automatically triggered. -- 'completeopt' is temporarily changed to `noinsert,menuone`. -- Snippet complete item would only be expanded after confirm completion. +Check if current buffer have fold provider by +`:echo CocAction('hasProvider', 'foldingRange')` -Use configurations |coc-config-suggest| to change behavior of completion. +Use |CocAction('fold')| to create folds by request the languageserver and +create manual folds on current window. -Tips:~ +-------------------------------------------------------------------------------- +SELECTION RANGE *coc-selection-range* -- 'completeopt' used by coc.nvim default to `noselect,menuone`. +Select range forward or backward at cursor position. -- Your 'completeopt' option would be changed and restored during completion, - so you can still use `menu,preview` for Vim's built in completion. +Check if current buffer have selection range provider by +`:echo CocAction('hasProvider', 'selectionRange')` -- Snippet expand and additional edit feature of LSP requires confirm - completion to work. +Selection range key-mappings:~ -- Floating window is available on Neovim >= 0.4.0. + โ€ข |(coc-range-select)| Select range forward. + โ€ข |(coc-range-select-backward)| Select range backward. ------------------------------------------------------------------------------- +Selection range function:~ -Example key-mappings:~ + โ€ข |CocAction('rangeSelect')| Visual select previous or next selection range -Map to trigger completion and navigate to the next item: > +-------------------------------------------------------------------------------- +CODE LENS *coc-code-lens* - function! s:check_back_space() abort - let col = col('.') - 1 - return !col || getline('.')[col - 1] =~ '\s' - endfunction +Code lens feature shows additional information above or after specific lines. +Works best on nvim >= 0.6.0 and vim >= 9.0.0438, on older vim, some +configurations may not work or not work at all. - inoremap - \ pumvisible() ? "\" : - \ check_back_space() ? "\" : - \ coc#refresh() +Check if current buffer have code lens provider by +`:echo CocAction('hasProvider', 'codeLens')` +To temporarily toggle codeLens of current buffer, use command +`:CocCommand document.toggleCodeLens` -Map to trigger completion: > +Code lens are not shown by default, use |coc-config-codeLens-enable| to enable, +you may also need enable code lens by configure extension or configured +languageserver. - inoremap coc#refresh() -< - to confirm completion, use: > +Code lens are automatically requested on buffer create/change, checkout +|coc-config-codeLens| for available configurations. - inoremap pumvisible() ? "\" : "\" -< -To make auto-select the first completion item and notify coc.nvim to -format on enter, use: > +-------------------------------------------------------------------------------- +LINKED EDITING *coc-linked-editing* - inoremap pumvisible() ? coc#_select_confirm() - \: "\u\\=coc#on_enter()\" +Linked editing feature enables editing multiple linked ranges at the same time, +for example: html tags. The linked editing ranges would be highlighted with +|CocLinkedEditing| when activated. -Map for trigger completion, completion confirm, snippet expand and jump -like VSCode. > - - inoremap - \ pumvisible() ? coc#_select_confirm() : - \ coc#expandableOrJumpable() ? - \ "\=coc#rpc#request('doKeymap', ['snippets-expand-jump',''])\" : - \ check_back_space() ? "\" : - \ coc#refresh() - - function! s:check_back_space() abort - let col = col('.') - 1 - return !col || getline('.')[col - 1] =~# '\s' - endfunction +Check if current buffer have linked editing provider by +`:echo CocAction('hasProvider', 'linkedEditing')` - let g:coc_snippet_next = '' -< -Note: the `coc-snippets` extension is required for this to work. +Linked editing feature is disabled by default, use +|coc-preferences-enableLinkedEditing| to enable. ============================================================================== INTERFACE *coc-interface* ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- Key mappings *coc-key-mappings* -Unlike some vim plugins, coc.nvim doesn't create user global key-mappings by -default. However, there're some cases that local key-mappings are enabled for -current buffer. - - Snippet jump key-mappings when snippet is activated: - |g:coc_snippet_prev| and |g:coc_snippet_next|. - - Cursor jump and cancel key-mappings when cursors is activated - |coc-config-cursors|. +There're some cases that local key-mappings are enabled for current buffer. - Dialog key-mappings for confirm and cancel dialog window - |coc-config-dialog|. - - Key-mappings for |CocList| buffer: |coc-list-mappings|. + โ€ข Snippet jump key-mappings when snippet is activated: |g:coc_snippet_prev| + and |g:coc_snippet_next|. + โ€ข Cursor jump and cancel key-mappings when cursors is activated + |coc-config-cursors|. + โ€ข Dialog key-mappings for confirm and cancel dialog window + |coc-config-dialog|. + โ€ข Key-mappings for |CocList| buffer: |coc-list-mappings|. Note: Use |:verbose| command to check key-mappings that taking effect. @@ -1246,36 +1397,38 @@ Note: key-mappings are provided for convenient, use |CocActionAsync()| or Normal mode key-mappings:~ -*(coc-diagnostic-info)* Show diagnostic message of current position by +*(coc-diagnostic-info)* Show diagnostic message of current position by invoke |CocAction('diagnosticInfo')| -*(coc-diagnostic-next)* Jump to next diagnostic position. +*(coc-diagnostic-next)* Jump to next diagnostic position after current +cursor position. -*(coc-diagnostic-prev)* Jump to previous diagnostic position. +*(coc-diagnostic-prev)* Jump to previous diagnostic position before +current cursor position. -*(coc-diagnostic-next-error)* Jump to next diagnostic error position. +*(coc-diagnostic-next-error)* Jump to next diagnostic error position. -*(coc-diagnostic-prev-error)* Jump to previous diagnostic error position. +*(coc-diagnostic-prev-error)* Jump to previous diagnostic error position. -*(coc-definition)* Jump to definition(s) of current symbol by invoke +*(coc-definition)* Jump to definition(s) of current symbol by invoke |CocAction('jumpDefinition')| -*(coc-declaration)* Jump to declaration(s) of current symbol by invoke +*(coc-declaration)* Jump to declaration(s) of current symbol by invoke |CocAction('jumpDeclaration')| -*(coc-implementation)* Jump to implementation(s) of current symbol by +*(coc-implementation)* Jump to implementation(s) of current symbol by invoke |CocAction('jumpImplementation')| -*(coc-type-definition)* Jump to type definition(s) of current symbol by +*(coc-type-definition)* Jump to type definition(s) of current symbol by invoke |CocAction('jumpTypeDefinition')| -*(coc-references)* Jump to references of current symbol by invoke +*(coc-references)* Jump to references of current symbol by invoke |CocAction('jumpReferences')| -*(coc-references-used)* Jump to references of current symbol exclude +*(coc-references-used)* Jump to references of current symbol exclude declarations. -*(coc-format-selected)* +*(coc-format-selected)* Format selected range, works on both |visual-mode| and |normal-mode|, when used in normal mode, the selection works on the motion object. @@ -1288,54 +1441,56 @@ declarations. makes `p` format the visually selected range, and you can use `pap` to format a paragraph. -*(coc-format)* - - Format the whole buffer by invoke |CocAction('format')|, normally you - would like to use a command like: > - - command! -nargs=0 Format :call CocAction('format') -< - to format current buffer. - -*(coc-rename)* Rename symbol under cursor to a new word by invoke +*(coc-format)* Format the whole buffer by invoke |CocAction('format')| +*(coc-rename)* Rename symbol under cursor to a new word by invoke |CocAction('rename')| -*(coc-refactor)* Open refactor window for refactor of current symbol by +*(coc-refactor)* Open refactor window for refactor of current symbol by invoke |CocAction('refactor')| -*(coc-command-repeat)* Repeat latest |CocCommand|. +*(coc-command-repeat)* Repeat latest |CocCommand|. + +*(coc-codeaction)* Get and run code action(s) for current file, use +|coc-codeaction-cursor| for same behavior as VSCode. -*(coc-codeaction)* Get and run code action(s) for current file, use -|coc-codeaction-cursor| for same beharior as VSCode. +*(coc-codeaction-source)* Get and run source code action(s) for current +file. The same as 'Source action...' in context menu of VSCode. -*(coc-codeaction-line)* Get and run code action(s) for current line. +*(coc-codeaction-line)* Get and run code action(s) for current line. -*(coc-codeaction-cursor)* Get and run code action(s) using empty range +*(coc-codeaction-cursor)* Get and run code action(s) using empty range at current cursor. -*(Coc-codeaction-selected)* Get and run code action(s) with the selected -region. Works on both |visual-mode| and |normal-mode|. +*(coc-codeaction-selected)* Get and run code action(s) with the selected +code. Works on both |visual-mode| and |normal-mode|. + +*(coc-codeaction-refactor)* Get and run refactor code action(s) at +current cursor, the same as refactor context menu in VSCode, disabled actions +are not excluded. -*(coc-openlink)* Open link under cursor. +*(coc-codeaction-refactor-selected)* Get and run refactor code action(s) +with selected code. Works on both |visual-mode| and |normal-mode|. -*(coc-codelens-action)* Do command from codeLens of current line. +*(coc-openlink)* Open link under cursor by use |CocAction('openlink')|. -*(coc-fix-current)* Try first quickfix action for diagnostics of current +*(coc-codelens-action)* Do command from codeLens of current line. + +*(coc-fix-current)* Try first quickfix action for diagnostics of current line. -*(coc-float-hide)* Hide all float windows/popups created by coc.nvim. +*(coc-float-hide)* Hide all float windows/popups created by coc.nvim. -*(coc-float-jump)* Jump to first float window (neovim only), use +*(coc-float-jump)* Jump to first float window (neovim only), use |CTRL-W_p| for jump to previous window. -*(coc-range-select)* +*(coc-range-select)* Select next selection range. Works on both |visual-mode| and |normal-mode|. Note: requires selection ranges feature of language server. -*(coc-funcobj-i)* +*(coc-funcobj-i)* Select inside function. Recommend mapping: Works on both |visual-mode| and |normal-mode|. @@ -1347,7 +1502,7 @@ line. server. *(coc-funcobj-a)* - + Select around function. Works on both |visual-mode| and |normal-mode|. Recommended mapping: > @@ -1368,7 +1523,7 @@ line. Note: Requires 'textDocument.documentSymbol' support from the language server. -*(coc-classobj-a)* +*(coc-classobj-a)* Select around class/struct/interface. Works on both |visual-mode| and |normal-mode|. Recommended mapping: @@ -1380,7 +1535,7 @@ line. server. -*(coc-cursors-operator)* Add text to cursors session by motion object. +*(coc-cursors-operator)* Add text to cursors session by motion object. *(coc-cursors-word)* Add current word to cursors session. @@ -1389,22 +1544,24 @@ session. Visual mode key-mappings:~ -*(coc-range-select-backward)* +*(coc-range-select-backward)* Select previous selection range. Note: requires selection ranges feature of language server, like: coc-tsserver, coc-python -*(coc-cursors-range)* Add selection to cursors session. +*(coc-cursors-range)* Add selection to cursors session. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- VARIABLES *coc-variables* ------------------------------------------------------------------------------- - User defined variables:~ +-------------------------------------------------------------------------------- + +Buffer variables *coc-buffer-variables* + b:coc_enabled *b:coc_enabled* Set to `0` on buffer create if you don't want coc.nvim receive content @@ -1413,13 +1570,18 @@ b:coc_enabled *b:coc_enabled* " Disable file with size > 1MB autocmd BufAdd * if getfsize(expand('')) > 1024*1024 | \ let b:coc_enabled=0 | - \ ndif + \ endif < +b:coc_force_attach *b:coc_force_attach* + + When is `1`, attach the buffer without check the 'buftype' option. + Should be set on buffer create. + b:coc_root_patterns *b:coc_root_patterns* Root patterns used for resolving workspaceFolder for the current file, will be used instead of - `"coc.preferences.rootPatterns"` setting. Example: > + `"workspace.rootPatterns"` setting. Example: > autocmd FileType python let b:coc_root_patterns = \ ['.git', '.env'] @@ -1432,6 +1594,12 @@ b:coc_suggest_disable *b:coc_suggest_disable* " Disable completion for python autocmd FileType python let b:coc_suggest_disable = 1 +b:coc_disabled_sources *b:coc_disabled_sources* + + Disabled completion sources of current buffer. Example: +> + let b:coc_disabled_sources = ['around', 'buffer', 'file'] +< b:coc_diagnostic_disable *b:coc_diagnostic_disable* Disable diagnostic support of current buffer. @@ -1441,41 +1609,54 @@ b:coc_suggest_blacklist *b:coc_suggest_blacklist* List of input words for which completion should not be triggered. Example: > - " Disable completion for 'end' in lua files + " Disable completion for 'end' in Lua files autocmd FileType lua let b:coc_suggest_blacklist = ["end"] b:coc_additional_keywords *b:coc_additional_keywords* Addition keyword characters for generate keywords. Example: > - " Add keyword characters for css + " Add keyword characters for CSS autocmd FileType css let b:coc_additional_keywords = ["-"] +b:coc_trim_trailing_whitespace *b:coc_trim_trailing_whitespace* + + Trim trailing whitespace on a line, default `0`. + Use by "FormattingOptions" send to the server. + +b:coc_trim_final_newlines *b:coc_trim_final_newlines* + + Trim all newlines after the final newline at the end of the file. + Use by "FormattingOptions" send to the server. + + Other buffer options that affect document format: 'eol', 'shiftwidth' + and 'expandtab'. + + Note: language server may not respect format options. + +-------------------------------------------------------------------------------- + +Global variables *coc-global-variables* + g:coc_disable_startup_warning *g:coc_disable_startup_warning* Disable possible warning on startup for old vim/node version. Default: 0 -g:coc_disable_uncaught_error *g:coc_disable_uncaught_error* +g:coc_disable_uncaught_error *g:coc_disable_uncaught_error* Disable uncaught error messages from node process of coc.nvim. Default: 0 -g:coc_text_prop_offset *g:coc_text_prop_offset* +g:coc_text_prop_offset *g:coc_text_prop_offset* Start |textprop| id offset of highlight namespaces on vim, change to - other value to avoid conflict. + other value to avoid conflict with other vim plugin. Default: 1000 -g:coc_channel_timeout *g:coc_channel_timeout* - - Channel timeout in seconds for request to node client. - - Default: 30 - g:coc_disable_transparent_cursor *g:coc_disable_transparent_cursor* Disable transparent cursor when CocList is activated. @@ -1491,19 +1672,14 @@ g:coc_start_at_startup *g:coc_start_at_startup* Default: 1 -g:coc_user_config *g:coc_user_config* - - User configuration object, define this variable when you can't use - |coc#config()| - g:coc_global_extensions *g:coc_global_extensions* Global extension names to install when they aren't installed. > let g:coc_global_extensions = ['coc-json', 'coc-git'] < - Note: coc.nvim would try to install extensions that not installed in - this list after initialization. + Note: coc.nvim will try to install extensions that are not installed + in this list after initialization. g:coc_uri_prefix_replace_patterns *g:coc_uri_prefix_replace_patterns* @@ -1523,8 +1699,8 @@ g:coc_enable_locationlist *g:coc_enable_locationlist* If you want use vim's quickfix list instead, add `"coc.preferences.useQuickfixForLocations": true` in your - configuration file, this configuration would be ignored and no autocmd - triggered. + configuration file, this configuration would be ignored and no + |CocLocationsChange| triggered. Default: 1 @@ -1558,14 +1734,12 @@ g:coc_filetype_map *g:coc_filetype_map* < Default: {} - Note: coc will always map filetype `javascript.jsx` to - `javascriptreact` and `typescript.tsx` to - `typescriptreact`. You can find the mapped filetype - of the current buffer by running `:CocCommand document.echoFiletype`. + See |coc-document-filetype| for details. g:coc_selectmode_mapping *g:coc_selectmode_mapping* - Add key mappings for making snippet select mode easier. > + Add key mappings for making snippet select mode easier. The same as + |Ultisnip| does. > snoremap c snoremap c @@ -1586,26 +1760,14 @@ g:coc_node_path *g:coc_node_path* g:coc_node_args *g:coc_node_args* - Arguments passed to node when starting coc service from source code. + Arguments passed to node when starting coc.nvim service. - Useful for starting coc in debug mode, example: > + Useful for start coc.nvim in debug mode, example: > > let g:coc_node_args = ['--nolazy', '--inspect-brk=6045'] < Default: [] -g:coc_jump_locations *g:coc_jump_locations* - - This variable would be set to jump locations when the - |CocLocationsChange| autocmd is fired. - - Each location item contains: - - 'filename': full file path. - 'lnum': line number (1 based). - 'col': column number(1 based). - 'text': line content of location. - g:coc_status_error_sign *g:coc_status_error_sign* Error character used for statusline, default: `E` @@ -1623,10 +1785,10 @@ g:coc_quickfix_open_command *g:coc_quickfix_open_command* < Default: |copen| -g:WorkspaceFolders *g:WorkspaceFolders* +g:coc_open_url_command *g:coc_open_url_command* - Current workspace folders, used for restoring from a session file, add - `set sessionoptions+=globals` to vimrc for restoring globals. + Command used for open remote url, when not exists, coc.nvim will try + to use "open", "xdg-open" on Mac and Linux, "cmd /c start" on windows. g:node_client_debug *g:node_client_debug* @@ -1639,28 +1801,66 @@ g:node_client_debug *g:node_client_debug* < Default: `0` +g:coc_user_config *g:coc_user_config* + + User configuration which will be passed to coc.nvim process during + initialization, no effect when changed after coc.nvim started. Prefer + |coc#config| unless coc.nvim is lazy loaded. Example: > + + let g:coc_user_config = {} + let g:coc_user_config['suggest.timeout'] = 500 + let g:coc_user_config['suggest.noselect'] = v:true +< + Note: those configuration would overwrite the configuration from the + user's settings file, unless you have to use some dynamic variables, + using the settings file is recommended. + g:coc_config_home *g:coc_config_home* Configure the directory which will be used to look for - `coc-settings.json`, default: + user's `coc-settings.json`, default: Windows: `~/AppData/Local/nvim` Other: `~/.config/nvim` g:coc_data_home *g:coc_data_home* - Configure the directory which will be used to for coc data - files(extensions, mru and so on), default: + Configure the directory which will be used to for data + files(extensions, MRU and so on), default: Windows: `~/AppData/Local/coc` Other: `~/.config/coc` -g:coc_sources_disable_map *g:coc_sources_disable_map* +g:coc_terminal_height *g:coc_terminal_height* - Configure disabled sources for different filetypes. - Use `:CocList sources` for loaded complete sources. Example: -> - let g:coc_sources_disable_map = { \ 'python': ['omni', 'tag'] \ } + Height of terminal window, default `8`. + +g:coc_markdown_disabled_languages *g:coc_markdown_disabled_languages* + + Filetype list that should be disabled for highlight in markdown block, + useful to disable filetypes that could be slow with syntax + highlighting, example: > + + let g:coc_markdown_disabled_languages = ['html'] + +g:coc_highlight_maximum_count *g:coc_highlight_maximum_count* + + When highlight items exceed maximum count, highlight items will be + grouped and added by using |timer_start| for better user experience. + + Default `100` + +g:coc_default_semantic_highlight_groups *g:coc_default_semantic_highlight_groups* + + Create default semantic highlight groups for |coc-semantic-highlights| + + Default: `1` + +g:coc_max_treeview_width *g:coc_max_treeview_width* + + Maximum width of tree view when adjusted by auto width. + + Default: `40` g:coc_borderchars *g:coc_borderchars* @@ -1682,17 +1882,41 @@ g:coc_prompt_win_width *g:coc_prompt_win_width* Width of input prompt window, default `32`. -g:coc_markdown_disabled_languages *g:coc_markdown_disabled_languages* + *g:coc_notify* +g:coc_notify_error_icon *g:coc_notify_error_icon* - Filetype list that should be disabled for highlight in markdown block, - Example: > + Error icon for notification, default to: ๏— - let g:coc_markdown_disabled_languages = ['html'] +g:coc_notify_warning_icon *g:coc_notify_warning_icon* ------------------------------------------------------------------------------- + Warning icon for notification, default to: โš  + +g:coc_notify_info_icon *g:coc_notify_info_icon* + + Info icon for notification, default to: ๏ช + +-------------------------------------------------------------------------------- + +Some variables are provided by coc.nvim. + + +g:WorkspaceFolders *g:WorkspaceFolders* + + Current workspace folders, used for restoring from a session file, add + `set sessionoptions+=globals` to vimrc for restoring globals on + session load. + +g:coc_jump_locations *g:coc_jump_locations* -Some variables are provided by coc.nvim so you can use them in your -statusline. See |coc-status| for detail. + This variable would be set to jump locations when the + |CocLocationsChange| autocmd is fired. + + Each location item contains: + + 'filename': full file path. + 'lnum': line number (1 based). + 'col': column number(1 based). + 'text': line content of location. g:coc_process_pid *g:coc_process_pid* @@ -1704,13 +1928,14 @@ g:coc_process_pid *g:coc_process_pid* < in your vimrc. -g:coc_service_initialized *g:coc_service_initialized* +g:coc_service_initialized *g:coc_service_initialized* Is `1` when coc.nvim initialized, used with autocmd |CocNvimInit|. g:coc_status *g:coc_status* - Status string contributed by extensions, used for status line. + Status string contributed by coc.nvim and extensions, used for status + line. g:coc_last_float_win *g:coc_last_float_win* @@ -1722,6 +1947,11 @@ g:coc_last_hover_message *g:coc_last_hover_message* Note: not used when floating or preview window used for `doHover`. +b:coc_snippet_active *b:coc_snippet_active* + + Is `1` when snippet session is activated, use |coc#jumpable| to check + if it's possible to jump placeholder. + b:coc_diagnostic_info *b:coc_diagnostic_info* Diagnostic information of current buffer, the format would look like: @@ -1742,13 +1972,10 @@ b:coc_cursors_activated *b:coc_cursors_activated* Use expression `get(b:, 'coc_cursors_activated',0)` to check if cursors session is activated for current buffer. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- FUNCTIONS *coc-functions* -Coc functions are normally used by user defined command/keymap or other -plugins. - -Note: some functions only work after the coc service has been initialized. +Some functions only work after the coc.nvim has been initialized. To run a function on startup, use an autocmd like: > @@ -1761,19 +1988,35 @@ coc#start([{option}]) *coc#start()* - `source` specific completion source name. - Example: > + Example: > + + inoremap =coc#start({'source': 'word'}) +< + Use `:CocList sources` to get available sources. + +coc#refresh() *coc#refresh()* + + Start or refresh completion at current cursor position, bind this to + 'imap' to trigger completion, example: > + + if has('nvim') + inoremap coc#refresh() + else + inoremap coc#refresh() + endif + +coc#_select_confirm() *coc#_select_confirm()* - inoremap =coc#start({'source': 'word'}) -< - Use `CocList sources` to get available sources. + Select first completion item if no completion item is selected, then + confirm the completion like |coc#pum#confirm()|. Return coc#config({section}, {value}) *coc#config()* - Change user configuration by Vim script, no changes would be made to - user configuration file. Example: > + Change user configuration, overwrite configurations from + user config file and default values. Example: > call coc#config('coc.preferences', { - \ 'timeout': 1000, + \ 'willSaveHandlerTimeout': 1000, \}) call coc#config('languageserver', { \ 'ccls': { @@ -1785,12 +2028,10 @@ coc#config({section}, {value}) *coc#config()* < Note: this function can be called multiple times. - - Note: this function can be called before the service has been - initialized. - + Note: this function can be called before coc.nvim started. Note: this function can work alongside the user configuration file, but it's not recommended to use both. + Note: use |g:coc_user_config| when you have coc.nvim lazy loaded. coc#add_extension({name}, ...) *coc#add_extension()* @@ -1814,13 +2055,6 @@ coc#add_command({id}, {command}, [{title}]) *coc#add_command()* call coc#add_command('mundoToggle', 'MundoToggle', \ 'toggle mundo window') < -coc#refresh() *coc#refresh()* - - Start or refresh completion at current cursor position, bind this to - 'imap' to trigger completion, example: > - - inoremap coc#refresh() -< coc#expandable() *coc#expandable()* Check if a snippet is expandable at the current position. @@ -1837,14 +2071,16 @@ coc#expandableOrJumpable() *coc#expandableOrJumpable()* coc#on_enter() *coc#on_enter()* - Notify coc.nvim that `` has been pressed. + Notify coc.nvim that has been pressed. Used for the format on type and improvement of brackets, example: > - inoremap pumvisible() ? coc#_select_confirm() - \: "\u\\=coc#on_enter()\" + " Confirm the completion when popupmenu is visible, insert and + " notify coc.nvim otherwise. + inoremap coc#pum#visible() ? coc#pum#confirm() + \: "\u\\=coc#on_enter()\" < - Note๏ผšto enable formatOnType, add ` "coc.preferences.formatOnType": true` + Note๏ผšto enable format on type, add ` "coc.preferences.formatOnType": true` in your settings file. coc#status() *coc#status()* @@ -1854,18 +2090,9 @@ coc#status() *coc#status()* extension contributed statuses from `g:coc_status`. For statusline integration, see |coc-status| -coc#_select_confirm() *coc#_select_confirm()* - - Select first completion item if no completion item is selected, then - confirm the completion. - - Note: for this function to work as expected, either |CompleteChanged| - autocmd should exists or only and should be used to select - a completion item. - -coc#util#api_version() *coc#util#api_version()* +coc#util#api_version() *coc#util#api_version()* - Get coc.nvim's vim api version number, start from `1`. + Get coc.nvim's vim API version number, start from `1`. coc#util#job_command() *coc#util#job_command()* @@ -1877,16 +2104,15 @@ coc#util#get_config_home() *coc#util#get_config_home()* coc#util#get_data_home() *coc#util#get_data_home()* - Get `coc` data directory. + Get data home directory, return |g:coc_data_home| when defined, else + use $XDG_CONFIG_HOME/coc when $XDG_CONFIG_HOME exists, else fallback + to `~/AppData/Local/coc` on windows and `~/.config/coc` on other + systems. coc#util#extension_root() *coc#util#extension_root()* Return extensions root of coc.nvim. -coc#util#rebuild() *coc#util#rebuild()* - - Run `npm rebuild` for all coc extensions. - coc#util#root_patterns() *coc#util#root_patterns()* Get root patterns used for current document. @@ -1902,6 +2128,133 @@ coc#util#get_config({key}) *coc#util#get_config()* :echo coc#util#get_config('coc.preferences') +coc#snippet#next() *coc#snippet#next()* + + Jump to next placeholder, does nothing when |coc#jumpable| is 0. + +coc#snippet#prev() *coc#snippet#prev()* + + Jump to previous placeholder, does nothing when |coc#jumpable| is 0. + + *coc#pum* +coc#pum#visible() *coc#pum#visible()* + + Check if customized popupmenu is visible like |pumvisible()| does. + Return 1 when popup menu is visible. + +coc#pum#next({insert}) *coc#pum#next()* + + Select next item of customized popupmenu, insert word when {insert} is + 1. + + Note: this function should only be used in key-mappings. + +coc#pum#prev({insert}) *coc#pum#prev()* + + Select previous item of customized popupmenu, insert word when {insert} + is truth value. + + Note: this function should only be used in key-mappings. + +coc#pum#stop() *coc#pum#stop()* + + Close the customized popupmenu, works like of vim. + + Note: this function should only be used in key-mappings. + +coc#pum#cancel() *coc#pum#cancel()* + + Cancel the customized popupmenu and revert trigger input, like + of vim. When no completion item selected, close the popup menu only. + + Note: this function should only be used in key-mappings. + +coc#pum#insert() *coc#pum#insert()* + + Insert word of current selected item and finish completion. Unlike + |coc#pum#confirm()|, no text edit would be applied and snippet would + not be expanded. + + Note: this function should only be used in key-mappings. + +coc#pum#confirm() *coc#pum#confirm()* + + Confirm completion of current selected item and close the customized + popup menu, like of vim. + + Note: this function should only be used in key-mappings. + +coc#pum#info() *coc#pum#info()* + + Return information of the customized popupmenu, should only be used + when |coc#pum#visible()| is 1. + + Result contains: + index Current select item index, 0 based. + scrollbar Non-zero if a scrollbar is displayed. + row Screen row count, 0 based. + col Screen column count, 0 based. + width Width of pum, including padding and border. + height Height of pum, including padding and border. + size Count of displayed complete items. + inserted Is |v:true| when there is item inserted. + reversed Is |v:true| when pum shown above cursor and + enable |suggest.reversePumAboveCursor| + +coc#pum#select({index}, {insert}, {confirm}) *coc#pum#select()* + + Selects an item in the completion popupmenu. + Return empty string. + + Parameters:~ + {index} Index (zero-based) of the item to select. + {insert} Whether the selection should be inserted + in the buffer. + {confirm} Confirm the completion and dismiss the + popupmenu, implies `insert`. + +coc#pum#one_more() *coc#pum#one_more()* + + Insert one more character from current complete item (first complete + item when no complete item selected), works like of + |popupmenu-keys|. Note that the word of complete item should starts + with current input. + + Nothing happens when failed. + + Note: this function should only be used in key-mappings. + +coc#pum#scroll({forward}) *coc#pum#scroll()* + + Scroll the popupmenu forward or backward by page. + Timer is used to make it works as {rhs} of key-mappings. + Return . + + Parameters:~ + {forward} Scroll forward when none zero. + + *coc#notify* +coc#notify#close_all() *coc#notify#close_all()* + + Close all notification windows. + +coc#notify#do_action([{winid}]) *coc#notify#do_action()* + + Invoke action for all notification windows, or particular window with + winid. + +coc#notify#copy() *coc#notify#copy()* + + Copy all content from notifications to system clipboard. + +coc#notify#show_sources() *coc#notify#show_sources()* + + Show source name (extension name) in notification windows. + +coc#notify#keep() *coc#notify#keep()* + + Stop auto hide timer of notification windows. + coc#float#has_float([{all}]) *coc#float#has_float()* Check if float window/popup exists, check coc.nvim's float @@ -1912,6 +2265,8 @@ coc#float#close_all([{all}]) *coc#float#close_all()* Close all float windows/popups created by coc.nvim, set {all} to `1` for all float window/popups. + Return `""`. + coc#float#close({winid}) *coc#float#close()* Close float window/popup with {winid}. @@ -1932,11 +2287,11 @@ coc#float#has_scroll() *coc#float#has_scroll()* vnoremap coc#float#has_scroll() ? coc#float#scroll(0) : "\" endif < -coc#float#scroll({forward}, [{amount}]) *coc#float#scroll()* +coc#float#scroll({forward}, [{amount}]) *coc#float#scroll()* Scroll all scrollable float windows/popups, scroll backward when {forward} is not `1`. {amount} could be number or full page when - omitted. + omitted. Popup menu is excluded. Note: this function requires nvim >= 0.4.0 or vim >= 8.2.750 to work. @@ -1964,14 +2319,14 @@ CocNotify({id}, {method}, [{params}]) *CocNotify()* > call CocNotify('ccls', '$ccls/reload') < - *CocRegistNotification()* + *CocRegisterNotification()* -CocRegistNotification({id}, {method}, {callback}) +CocRegisterNotification({id}, {method}, {callback}) - Regist notification callback for specified client {id} and {method}, + Register notification callback for specified client {id} and {method}, example: > - autocmd User CocNvimInit call CocRegistNotification('ccls', + autocmd User CocNvimInit call CocRegisterNotification('ccls', \ '$ccls/publishSemanticHighlight', function('s:Handler')) < {callback} is called with single param as notification result. @@ -1984,7 +2339,7 @@ CocRegistNotification({id}, {method}, {callback}) CocLocations({id}, {method}, [{params}, {openCommand}]) Send location request to language client of {id} with - {method} and optional {params}. eg: > + {method} and optional {params}. e.g.: > call CocLocations('ccls', '$ccls/call', {'callee': v:true}) @@ -2008,23 +2363,26 @@ CocAction({action}, [...{args}]) *CocAction()* Checkout |coc-actions| for available actions. - Note: it's recommended to use |CocActionAsync()| unless you need - result from |CocAction()|. + Note: it's recommended to use |CocActionAsync()| unless you have to + block your vim. *CocActionAsync()* CocActionAsync({action}, [...{args}, [{callback}]]) - Call CocAction by send notification to server of coc.nvim. + Call CocAction by send notification to NodeJS process of coc.nvim. - Optional callback is called with `error` as the first argument and - `response` as the second argument. + When callback function exists as the last argument, the callback + function is called with `error` string as the first argument and + `resutl` as the second argument. When no callback exists, error + message would be echoed. Checkout |coc-actions| for available actions. CocHasProvider({feature}) *CocHasProvider()* - Check if provider exists for specified feature. Supported features: + Check if provider exists for specified feature of current buffer. + Supported features: `rename` `onTypeEdit` `documentLink` `documentColor` `foldingRange` `format` `codeAction` `workspaceSymbols` `formatRange` `hover` @@ -2042,26 +2400,24 @@ CocTagFunc({pattern}, {flags}, {info}) *CocTagFunc()* > :echo exists('&tagfunc') < ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- *coc-actions* Available Actions ~ -Acceptable {action} names for |CocAction()| and |CocActionAsync|. +Acceptable {action} names for |CocAction()| and |CocActionAsync()|. -"ensureDocument" *CocAction('ensureDocument')* +"addWorkspaceFolder" {folder} *CocAction('addWorkspaceFolder')* - Ensure current document is attached to coc.nvim, should be used when - you need invoke action of current document just after document - created. + Add {folder} to workspace folders, {folder} should be exists directory + on file system. - Return `v:false` when the document can't be attached, the document - won't be attached for one of these reasons: +"ensureDocument" *CocAction('ensureDocument')* - 1. The 'buftype' option is neither nor acwrite. - 2. Buffer variable `b:coc_enabled` is set to `0`. - 3. Size of buffer bigger than `coc.preferences.maxFileSize` - configuration. - 4. The buffer is used for command line window. + Ensure current document is attached to coc.nvim + |coc-document-attached|, should be used when you need invoke action of + current document on buffer create. + + Return |v:false| when document can't be attached. "diagnosticList" *CocAction('diagnosticList')* @@ -2071,19 +2427,30 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. Show diagnostic message at the current position, do not truncate. -"diagnosticToggle" *CocAction('diagnosticToggle')* +"diagnosticToggle" [{enable}] *CocAction('diagnosticToggle')* Enable/disable diagnostics on the fly, not work when `displayByAle` is - enabled. + enabled. You can toggle by specifying {enable}. {enable} can be 0 or 1 + +"diagnosticToggleBuffer" [{bufnr}] [{enable}] *CocAction('diagnosticToggleBuffer')* + + Toggle diagnostics for specific buffer, current buffer is used when + {bufnr} not provided. 0 for current buffer + You can toggle by specifying {enable}. {enable} can be 0 or 1 + + Note: this will only affect diagnostics shown in the UI, list of all + diagnostics won't change. "diagnosticPreview" *CocAction('diagnosticPreview')* Show diagnostics under current cursor in preview window. -"diagnosticRefresh" [{bufnr}] *CocAction('diagnosticRefresh')* +"diagnosticRefresh" [{bufnr}] *CocAction('diagnosticRefresh')* Force refresh diagnostics for special buffer with {bufnr} or all buffers - when {bufnr} not exists, returns `v:null` before diagnostics are shown. + when {bufnr} doesn't exist, returns `v:null` before diagnostics are shown. + + NOTE: Will refresh in any mode. Useful when `diagnostic.autoRefresh` is `false`. @@ -2099,9 +2466,37 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. enable/disable {source}. +"definitions" *CocAction('definitions')* + + Get definition locations of symbol under cursor. + Return LSP `Location[]` + +"declarations" *CocAction('declarations')* + + Get declaration location(s) of symbol under cursor. + Return LSP `Location | Location[] | LocationLink[]` + +"implementations" *CocAction('implementations')* + + Get implementation locations of symbol under cursor. + Return LSP `Location[]` + +"typeDefinitions" *CocAction('typeDefinitions')* + + Get type definition locations of symbol under cursor. + Return LSP `Location[]` + +"references" [{excludeDeclaration}] *CocAction('references')* + + Get references location list of symbol under cursor. + + {excludeDeclaration}: exclude declaration locations when not zero. + + Return LSP `Location[]` + "jumpDefinition" [{openCommand}] *CocAction('jumpDefinition')* - jump to definition position of the current symbol. + jump to definition locations of the current symbol. Return `v:false` when location not found. |coc-list-location| is used when more than one position is available, @@ -2115,7 +2510,7 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. "jumpDeclaration" [{openCommand}] *CocAction('jumpDeclaration')* - jump to declaration position of the current symbol. + jump to declaration locations of the current symbol. Return `v:false` when location not found. same behavior as "jumpDefinition". @@ -2124,29 +2519,44 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. "jumpImplementation" [{openCommand}] *CocAction('jumpImplementation')* - Jump to implementation position of the current symbol. + Jump to implementation locations of the current symbol. Return `v:false` when location not found. same behavior as "jumpDefinition" "jumpTypeDefinition" [{openCommand}] *CocAction('jumpTypeDefinition')* - Jump to type definition position of the current symbol. + Jump to type definition locations of the current symbol. Return `v:false` when location not found. same behavior as "jumpDefinition" "jumpReferences" [{openCommand}] *CocAction('jumpReferences')* - Jump to references position of the current symbol. + Jump to references locations of the current symbol, use + |CocAction('jumpUsed')| to exclude declaration locations. + Return `v:false` when location not found. same behavior as "jumpDefinition" -"getHover" *CocAction('getHover')* +"jumpUsed" [{openCommand}] *CocAction('jumpUsed')* + + Jump references locations without declarations. + + same behavior as "jumpDefinition" + +"getHover" [{hoverLocation}] *CocAction('getHover')* + + Get documentation text array on {hoverLocation} or current position, + returns array of string. - Get documentation text array on current position, returns array of - string. + {hoverLocation} could contains: + โ€ข bufnr: optional buffer number. + โ€ข line: 1 based line number. + โ€ข col: 1 based col number + + Throw error when buffer with bufnr is not attached. "doHover" [{hoverTarget}] *CocAction('doHover')* @@ -2156,7 +2566,7 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. {hoverTarget}: optional specification for where to show hover info, defaults to `coc.preferences.hoverTarget` in `coc-settings.json`. Valid options: ["preview", "echo", "float"] - + "definitionHover" [{hoverTarget}] *CocAction('definitionHover')* Same as |CocAction('doHover')|, but includes definition contents from @@ -2170,7 +2580,7 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. autocmd User CocJumpPlaceholder call \ CocActionAsync('showSignatureHelp') < -"getCurrentFunctionSymbol" *CocAction('getCurrentFunctionSymbol')* +"getCurrentFunctionSymbol" *CocAction('getCurrentFunctionSymbol')* Return the function string that current cursor in. @@ -2180,8 +2590,15 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. "rename" *CocAction('rename')* - Rename the symbol under the cursor position, user will be prompted for - a new name. + Rename the symbol under the cursor position, |coc-dialog-input| would + be shown for prompt a new name. + + Show error message when the provider not found or prepare rename + failed. + + The buffers are not saved after apply workspace edits, use |:wa| to + save all buffers. It's possible to undo/redo and inspect the changes, + see |coc-workspace-edits|. Note: coc.nvim supports rename for disk files, but your language server may not. @@ -2192,6 +2609,9 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. Check |coc-config-cursors| and |coc-config-refactor| for related configuration. + Use to open buffer at current position in split window. + Use to show action menu which have tab open and remove actions. + "format" *CocAction('format')* Format current buffer using the language server. @@ -2204,6 +2624,18 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. When {mode} is omitted, it should be called using |formatexpr|. +"snippetInsert" {range} {snippet} [{mode}] *CocAction('snippetInsert')* + + Insert {snippet} text as specific {range} of current buffer. + + {range} should be valid LSP range like: +> + // all 0 based utf16 unit code index. + {"start": {"line": 0, "character": 1}, "end": {"line": 0, "character": 3}} +< + {snippet} is the textmate format snippet text used by VSCode. + + {mode} could be 1 or 2, use 1 to disable format of snippet. "selectionRanges" *CocAction('selectionRanges')* @@ -2217,24 +2649,31 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. Start or stop a service. -"codeAction" [{mode}] [{only}] *CocAction('codeAction')* +"codeAction" [{mode}] [{only}] [{include_disabled}] *CocAction('codeAction')* Prompt for a code action and do it. - {mode} could be `line` or `cursor` or result of |visualmode()|, + {mode} could be `currline` or `cursor` or result of |visualmode()|, current buffer range is used when it's empty string. {only} can be title of a codeAction or list of CodeActionKind. + {include_disabled} include disabled actions when is truth value. + "codeActionRange" {start} {end} [{kind}] *CocAction('codeActionRange')* Run code action for range. - {start} start line number of range. - {end} end line number of range. - {kind} code action kind, see |CocAction('codeActions')| for available - action kind. + {start} Start line number of range. + {end} End line number of range. + {kind} Code action kind, see |CocAction('codeActions')| for available + action kind. + + Can be used to create commands like: > + command! -nargs=* -range CocAction :call CocActionAsync('codeActionRange', , , ) + command! -nargs=* -range CocFix :call CocActionAsync('codeActionRange', , , 'quickfix') +< "codeLensAction" *CocAction('codeLensAction')* Invoke the command for codeLens of current line (or the line that @@ -2256,32 +2695,39 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. command! -nargs=0 OrganizeImport \ :call CocActionAsync('runCommand', 'tsserver.organizeImports') - +< "fold" {{kind}} *CocAction('fold')* - Fold the current buffer, optionally use {kind} for filtering folds, - {kind} could be either 'comment', 'imports' or 'region' + Fold the current buffer, optionally use {kind} for specific + FoldingRangeKind. + {kind} could be 'comment', 'imports' or 'region'. Return `v:false` when failed. + You can create a custom command like: > + + command! -nargs=? Fold :call CocAction('fold', ) +< "highlight" *CocAction('highlight')* Highlight the symbols under the cursor. - Overwrite the highlight groups |CocHighlightText|, |CocHighlightRead| - and |CocHighlightWrite| for customizing the colors. - - To enable highlight on CursorHold, create an autocmd like this: > - autocmd CursorHold * silent call CocActionAsync('highlight') -< -"openLink" [{command}] *CocAction('openlink')* +"openLink" [{command}] *CocAction('openLink')* Open a link under the cursor with {command}. {command} default to `edit`. File and URL links are supported, return `v:false` when failed. - Note: it needs language server support documentLink feature to work. + URI under cursor would be searched when no link returned from the + "documentLink" provider. + + Configure |g:coc_open_url_command| for custom command to open remote + url. + +"links" *CocAction('links')* + + Return document link list of current buffer. "extensionStats" *CocAction('extensionStats')* @@ -2312,24 +2758,20 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. "pickColor" *CocAction('pickColor')* - Change the color at the current cursor position. - - Requires language server support for the document color request. + Change the color at the current cursor position, requires + `documentColor` provider |CocHasProvider|. Note: only works on mac or when you have python support on Vim and - have the gtk module installed. + have the GTK module installed. "colorPresentation" *CocAction('colorPresentation')* - Change the color presentation at the current color position. - - Requires a language server that supports color representation - requests. + Change the color presentation at the current color position, requires + `documentColor` provider |CocHasProvider|. "codeActions" [{mode}] [{only}] *CocAction('codeActions')* - Get and invoke codeActions on current document, quickpick menu would - be shown when there're many codeActions. + Get codeActions list of current document. {mode} can be result of |visualmode()| for visual selected range. When it's falsy value, current file is used as range. @@ -2345,12 +2787,12 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. action - 'source.fixAll': Base kind for auto-fix source actions - {only} can also be string, which means filter by tilte of codeAction. + {only} can also be string, which means filter by title of codeAction. "organizeImport" *CocAction('organizeImport')* - Run organize import codeAction for current buffer. - Show warning when codeAction not found. + Run organize import code action for current buffer. + Return `false` when the code action not exists. "fixAll" *CocAction('fixAll')* @@ -2379,32 +2821,23 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. Ranges must be provided as array of range type: https://git.io/fjiEG -"getWordEdit" *CocAction('getWordEdit')* +"getWordEdit" *CocAction('getWordEdit')* Get workspaceEdit of current word, language server used when possible, extract word from current buffer as fallback. -"getWorkspaceSymbols" {input} *CocAction(getWorkspaceSymbols)* +"getWorkspaceSymbols" {input} *CocAction('getWorkspaceSymbols')* Get workspace symbols from {input}. -"resolveWorkspaceSymbol" {symbol} *CocAction('resolveWorkspaceSymbol')* +"resolveWorkspaceSymbol" {symbol} *CocAction('resolveWorkspaceSymbol')* Resolve location for workspace {symbol}. -"diagnosticToggleBuffer" [{bufnr}] *CocAction('diagnosticToggleBuffer')* - - Toggle diagnostics for specific buffer, current buffer is used when - {bufnr} not provided. - - Note: this will only affect diagnostics shown in the UI, list of all - diagnostics won't change. +"showOutline" [{keep}] *CocAction('showOutline')* -"showOutline" [{keep}] *CocAction('showOutline')* - - Show outline tree view for current buffer. Old outline window on current - tab would be replaced. - Outline view has Window variable `cocViewId` set to `OUTLINE`. + Show |coc-outline| for current buffer. Does nothing when outline + window already shown for current buffer. {keep} override `"outline.keepWindow"` configuration when specified. Could be 0 or 1. @@ -2412,68 +2845,65 @@ Acceptable {action} names for |CocAction()| and |CocActionAsync|. Returns after window is shown (document symbol request is still in progress). - Note: like VSCode, outline would try to reload document symbols after - 500ms when provider not registered, which avoid the necessary to check - provider existence. - - Note: error is shown when current buffer is not attatched, checkout - |CocAction('ensureDocument')|, for possible reasons. - - Checkout |coc-config-tree| and |coc-config-outline| for available - configurations. - - Checkout |CocTree| and |CocSymbol| for customize highlights. - - Use configuration `"suggest.completionItemKindLabels"` for custom icons. - - To show outline for each tab automatically, use |autocmd|: -> - autocmd VimEnter,Tabnew * - \ if empty(&buftype) | call CocActionAsync('showOutline', 1) | endif -< -"hideOutline" *CocAction('hideOutline')* +"hideOutline" *CocAction('hideOutline')* - Close outline window on current tab. Throws vim error when it can't + Close |coc-outline| on current tab. Throws vim error when it can't be closed by vim. -"incomingCalls" [{CallHierarchyItem}] *CocAction('incomingCalls')* +"incomingCalls" [{CallHierarchyItem}] *CocAction('incomingCalls')* Retrieve incoming calls from {CallHierarchyItem} or current position when not provided. -"outgoingCalls" [{CallHierarchyItem}] *CocAction('outgoingCalls')* +"outgoingCalls" [{CallHierarchyItem}] *CocAction('outgoingCalls')* Retrieve outgoing calls from {CallHierarchyItem} or current position when not provided. -"showIncomingCalls" *CocAction('showIncomingCalls')* +"showIncomingCalls" *CocAction('showIncomingCalls')* - Show incoming calls of current function with |coc-tree|, - Configured by |CocSymbol|, |coc-config-callHierarchy| and - |coc-config-tree|. + Show incoming calls of current function with |coc-tree|, see + |coc-callHierarchy| - Related ranges are highlighted with |CocSelectedRange| highlight - group. +"showOutgoingCalls" *CocAction('showOutgoingCalls')* + + Show outgoing calls of current function with |coc-tree|. - |coc-dialog-menu| could be invoked by key configured by - `"tree.key.actions". Available actions: +"showSuperTypes" *CocAction('showSuperTypes')* - - Dismiss. - - Open in new tab. - - Show Incoming Calls. - - Show Outgoing Calls. + Show super types of types under cursor with |coc-tree|, see + |coc-typeHierarchy|. A warning is shown when no types found under + cursor. +"showSubTypes" *CocAction('showSubTypes')* -"showOutgoingCalls" *CocAction('showOutgoingCalls')* + Show sub types of types under cursor with |coc-tree|, see + |coc-typeHierarchy|. A warning is shown when no types found under + cursor. - Show outgoing calls of current function with |coc-tree|. +"semanticHighlight" *CocAction('semanticHighlight')* ------------------------------------------------------------------------------- + Request semantic tokens highlight for current buffer. + +"inspectSemanticToken" *CocAction('inspectSemanticToken')* + + Inspect semantic token information at cursor position. + +"rangeSelect" {visualmode} {forward} *CocAction('rangeSelect')* + + Visual select previous or next selection range, requires + `selectionRange` provider. + + {visualmode} should be result of {visualmode} or "" for current cursor + position. + {forward} select backward when it's falsy value. + +-------------------------------------------------------------------------------- COMMANDS *coc-commands* :CocStart *:CocStart* - Start the coc.nvim server, do nothing if it's already started. + Start the coc.nvim server, do nothing if the server already started. :CocRestart *:CocRestart* @@ -2481,10 +2911,18 @@ COMMANDS *coc-commands* Use this command when you want coc to start all over again. +:CocPrintErrors *:CocPrintErrors* + + Show errors from stderr of NodeJS process in a split window. + :CocDisable *:CocDisable* - Disable handling vim events. + Disable handling vim events, useful for debug performance issues. + To disable dynamic autocmds registered by extensions, use: +> + :autocmd! coc_dynamic_autocmd +< :CocEnable *:CocEnable* Enable handling vim events. @@ -2496,8 +2934,7 @@ COMMANDS *coc-commands* :CocLocalConfig *:CocLocalConfig* - Edit or create `.vim/coc-settings.json` of the current working - directory. + Edit or create `.vim/coc-settings.json` in current workspace folder. :CocInstall [{option}] {name} ... *:CocInstall* @@ -2514,12 +2951,15 @@ COMMANDS *coc-commands* :CocInstall coc-omni@1.0.0 " Install snippet extension from github :CocInstall https://github.com/dsznajder/vscode-es7-javascript-react-snippets -> +< :CocUninstall {name} *:CocUninstall* Uninstall an extension, use to complete the extension name. + Note: the data create by extension is not cleaned up, you may have to + manually remove them. + :CocUpdate *:CocUpdate* Update all coc extensions to the latest version. @@ -2528,29 +2968,11 @@ COMMANDS *coc-commands* Block version of update coc extensions. -:CocRebuild *:CocRebuild* - - Run `npm rebuild` for coc extensions. - - May be required when environment nodejs get upgraded. - -:CocCommand {name} [{args}] ... *:CocCommand* +:CocCommand {name} [{args}] ... *:CocCommand* Run a command contributed by extensions, use `` for name completion. -:{range}CocAction [{only}] *:CocAction* - - Get codeActions of current document in actions list, - with optional {range}. - - {only} can be `quickfix`, `refactor`, `source.fixAll` as - CodeActionKind. - -:{range}CocFix *:CocFix* - - Same as `:CocAction quickfix` for quickfix actions. - :CocOpenLog *:CocOpenLog* Open log file of coc.nvim. @@ -2569,7 +2991,7 @@ COMMANDS *coc-commands* let $NVIM_COC_LOG_LEVEL='debug' < - to the beginning of your `.vimrc` + to your `.vimrc` :CocInfo *:CocInfo* @@ -2578,7 +3000,10 @@ COMMANDS *coc-commands* :CocDiagnostics [height] *:CocDiagnostics* - Open vim's |location-list| with diagnostics of current buffer. + Open vim's |location-list| with diagnostics of current buffer. The + location list is automatically updated by default. When multiple + location list are opened for one buffer, only first one would be + automatically updated. :CocSearch *:CocSearch* @@ -2612,7 +3037,7 @@ COMMANDS *coc-commands* Note: By default, vcs ignore files including `.gitignore` and `.ignore` are respected - Excape arguments:~ + Escape arguments:~ || is used to convert command line arguments to arguments of rg, which means you have to escape space for single argument. For @@ -2633,16 +3058,16 @@ COMMANDS *coc-commands* related files. You can make any kind of changes, including add lines and remove lines. -:CocWatch [extension] *:CocWatch* +:CocWatch [extension] *:CocWatch* Watch loaded [extension] for reload on file change, use for complete extension id. -:CocOutline *:CocOutline* +:CocOutline *:CocOutline* Invoke |CocAction('showOutline')| by notification. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- AUTOCMD *coc-autocmds* *CocLocationsChange* @@ -2671,7 +3096,7 @@ AUTOCMD *coc-autocmds* :autocmd User CocStatusChange {command} Triggered after `g:coc_status` changed, can be used for refresh - stautsline. + statusline. *CocDiagnosticChange* @@ -2702,7 +3127,7 @@ AUTOCMD *coc-autocmds* :autocmd User CocOpenFloatPrompt {command} Triggered when a floating prompt window is opened (triggered after - CocOpenFloat). + |CocOpenFloat|). *CocTerminalOpen* :autocmd User CocTerminalOpen {command} @@ -2710,16 +3135,18 @@ AUTOCMD *coc-autocmds* Triggered when the terminal is shown, can be used for adjusting the window height. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- HIGHLIGHTS *coc-highlights* -To customize a highlight, simply use |:highlight| command in your vimrc, like: +The best place to override highlight groups is a file named +after/colors/ .vim in your 'runtimepath' (e.g., +~/.config/nvim/after/colors/solarized.vim). Example declaration: > " make error texts have a red color highlight CocErrorHighlight ctermfg=Red guifg=#ff0000 < -Type |:highlight| command with group name to check current highlight. +Use |:highlight| with group name to check current highlight. Note: don't use `:hi default` for overwriting the highlights. @@ -2738,6 +3165,7 @@ Markdown related~ *CocMarkdownLink* for markdown link text in floating window/popup. Diagnostics related~ + *coc-highlights-diagnostics* *CocFadeOut* for faded out text, such as for highlighting unnecessary code. *CocErrorSign* for error signs. @@ -2758,10 +3186,17 @@ Diagnostics related~ default. *CocErrorLine* line highlight of sign which contains error. *CocWarningLine* line highlight of sign which contains warning. -*CocInfoLine* line highlight of sign which information. +*CocInfoLine* line highlight of sign which information. *CocHintLine* line highlight of sign which contains hint. +Highlight with higher priority would overwrite highlight with lower priority. +The priority order: + + |CocUnusedHighlight| > |CocDeprecatedHighlight| > |CocErrorHighlight| + > |CocWarningHighlight| > |CocInfoHighlight| > |CocHintHighlight| + Document highlight related~ + *coc-highlights-document* Highlights used for highlighting same symbols in the buffer at the current cursor position. @@ -2771,36 +3206,83 @@ cursor position. *CocHighlightWrite* for `Write` kind of document symbol. Float window/popup related~ + *coc-highlights-float* *CocFloating* default highlight group of floating windows/popups. -Default link to |NormalFloat| on neovim and|`Pmenu| on vim. -*CocErrorFloat* for errors in floating windows/popups. -*CocWarningFloat* for warnings in floating windows/popups. -*CocInfoFloat* for infos in floating windows/popups. -*CocHintFloat* for hints in floating windows/popups. +Default links to |NormalFloat| on neovim and |Pmenu| on vim. +*CocFloatThumb* thumb highlight of scrollbar. +*CocFloatSbar* Scrollbar highlight of floating window/popups. +*CocFloatDividingLine* for dividing lines, links to |NonText| by default. +*CocFloatActive* for activated text, links to |CocSearch| by default. +*CocErrorFloat* for error text in floating windows/popups. +*CocHintFloat* for hint text in floating windows/popups. + +Inlay hint related~ + *coc-highlights-inlayHint* + +*CocInlayHint* for highlight inlay hint virtual text block, default uses +foreground from |CocHintSign| and background from |SignColumn| +*CocInlayHintParameter* for parameter kind of inlay hint. +*CocInlayHintType* for type kind of inlay hint. + +Notification window/popup related~ + +CocNotification *CocNotification* + +*CocNotificationProgress* for progress line in progress notification. +*CocNotificationButton* for action buttons in notification window. +*CocNotificationError* for highlight border of error notification. +*CocNotificationWarning* for highlight border of warning notification. +*CocNotificationInfo* for highlight border of info notification. List related~ + *CocList* -*CocSelectedText* for sign text of selected lines. -*CocSelectedLine* for line highlight of selected lines. -*CocListMode* for mode in statusline of CocList. -*CocListPath* for current cwd in statusline of CocList. +*CocSearch* for matched characters. +*CocListLine* for current cursor line. +*CocListSearch* for matched characters. +*CocListMode* for mode text in the statusline. +*CocListPath* for cwd text in the statusline. +*CocSelectedText* for sign text of selected lines (multiple selection only). +*CocSelectedLine* for line highlight of selected lines (multiple selection only). Tree view related~ -CocTree* *CocTree* +CocTree *CocTree* *CocTreeTitle* for title in tree view. *CocTreeDescription* for description beside label. *CocTreeOpenClose* for open and close icon in tree view. *CocTreeSelected* for highlight lines contains selected node. -Symbol icons~ - -CocSymbol* *CocSymbol* +Popup menu related~ + *CocPum* +*CocPumSearch* for matched input characters, linked to |CocSearch| by default. +*CocPumDetail* for highlight label details that follows label (including +possible detail and description). +*CocPumMenu* for menu of complete item. +*CocPumShortcut* for shortcut text of source. +*CocPumDeprecated* for deprecated label. +*CocPumVirtualText* for virtual text which enabled by +|coc-config-suggest-virtualText| -Highlight groups for symbol icons, including: +Symbol icons~ +CocSymbol *CocSymbol* + +Highlight groups for symbol icons, including `CompletionItemKind` and +`SymbolKind` of LSP. The highlight groups link to related |nvim-treesitter| +highlight groups when possible and fallback to builtin highlight groups. + +*CocSymbolDefault* linked to |hl-MoreMsg| by default. +*CocSymbolText* +*CocSymbolUnit* +*CocSymbolValue* +*CocSymbolKeyword* +*CocSymbolSnippet* +*CocSymbolColor* +*CocSymbolReference* +*CocSymbolFolder* *CocSymbolFile* *CocSymbolModule* *CocSymbolNamespace* @@ -2827,53 +3309,55 @@ Highlight groups for symbol icons, including: *CocSymbolEvent* *CocSymbolOperator* *CocSymbolTypeParameter* -*CocSymbolDefault* -Note: Use configuration `suggest.completionItemKindLabels` for customized icon +Note: Use configuration |coc-config-suggest-completionItemKindLabels| for customized icon characters. +Semantic token highlight groups~ + *CocSem* + +Semantic highlight groups are starts with `CocSem` which link to related +|nvim-treesitter| highlight groups when possible and fallback to builtin +highlight groups, use variable |g:coc_default_semantic_highlight_groups| to +disable creation of these highlight groups. + +Only semantic tokens types and `deprecated` modifier have default +highlight groups. + +You need create highlight groups for highlight other modifiers and/or specific +modifier with type, for example: +> + " Add highlights for defaultLibrary modifier + hi link CocSemDefaultLibrary TSOtherDefaultLibrary + hi link CocSemDefaultLibraryClass TSTypeDefaultLibrary + hi link CocSemDefaultLibraryInterface TSTypeDefaultLibrary + hi link CocSemDefaultLibraryEnum TSTypeDefaultLibrary + hi link CocSemDefaultLibraryType TSTypeDefaultLibrary + hi link CocSemDefaultLibraryNamespace TSTypeDefaultLibrary + + " Add highlights for declaration modifier + hi link CocSemDeclaration TSOtherDeclaration + hi link CocSemDeclarationClass TSTypeDeclaration + hi link CocSemDeclarationInterface TSTypeDeclaration + hi link CocSemDeclarationEnum TSTypeDeclaration + hi link CocSemDeclarationType TSTypeDeclaration + hi link CocSemDeclarationNamespace TSTypeDeclaration +< +The modifier highlight groups have higher priority. + Others~ +*CocDisabled* highlight for disabled items, eg: menu item. *CocCodeLens* for virtual text of codeLens. -*CocCursorRange* for ranges of activated cursors. +*CocCursorRange* for highlight of activated cursors ranges. +*CocLinkedEditing* for highlight of activated linked editing ranges. *CocHoverRange* for range of current hovered symbol. -*CocMenuSel* for current menu item in menu dialog, works on neovim only since -vim doesn't support change highlight group of cursorline inside popup. +*CocMenuSel* for current menu item in menu dialog (should only provide +background color). *CocSelectedRange* for highlight ranges of outgoing calls. - -Semantic highlights~ - -CocSem_* *CocSem* - - Used for words whose semantics are provided by the language server, which - typically analyzes source code more deeply than vim's builtin syntax parser. - - Basic defaults are provided for the "standard" token kinds, but any kind - supported by the server can be highlighted by creating the highlight group. - - Default (enabled by setting `g:coc_default_semantic_highlight_groups = 1`): - `hi default link CocSem_namespace Identifier` - `hi default link CocSem_type Type` - `hi default link CocSem_class Structure` - `hi default link CocSem_enum Type` - `hi default link CocSem_interface Type` - `hi default link CocSem_struct Structure` - `hi default link CocSem_typeParameter Type` - `hi default link CocSem_parameter Identifier` - `hi default link CocSem_variable Identifier` - `hi default link CocSem_property Identifier` - `hi default link CocSem_enumMember Constant` - `hi default link CocSem_event Identifier` - `hi default link CocSem_function Function` - `hi default link CocSem_method Function` - `hi default link CocSem_macro Macro` - `hi default link CocSem_keyword Keyword` - `hi default link CocSem_modifier StorageClass` - `hi default link CocSem_comment Comment` - `hi default link CocSem_string String` - `hi default link CocSem_number Number` - `hi default link CocSem_regexp Normal` - `hi default link CocSem_operator Operator` +*CocSnippetVisual* for highlight snippet placeholders. +*CocLink* for highlight document links. +*CocInputBoxVirtualText* for highlight placeholder of input box. ============================================================================== TREE SUPPORT *coc-tree* @@ -2881,16 +3365,16 @@ TREE SUPPORT *coc-tree* Tree view is used for render outline and call hierarchy, following features are supported: -- Data update while keep tree node open/close state. -- Auto refresh on load error. -- Click open/close icon to toggle collapse state. -- Click node to invoke default command. -- Show tooltip in float window on |CursorHold| when possible. -- Key-mappings support |coc-tree-mappings| -- Optional multiple selection. -- Optional node reveal support. -- Optional fuzzy filter support. -- Provide api `window.createTreeView` for extensions. + โ€ข Data update while keep tree node open/close state. + โ€ข Auto refresh on load error. + โ€ข Click open/close icon to toggle collapse state. + โ€ข Click node to invoke default command. + โ€ข Show tooltip in float window on |CursorHold| when possible. + โ€ข Key-mappings support |coc-tree-mappings| + โ€ข Optional multiple selection. + โ€ข Optional node reveal support. + โ€ข Optional fuzzy filter support. + โ€ข Provide API `window.createTreeView` for extensions. Check |coc-config-tree| for related configurations. @@ -2899,7 +3383,7 @@ options. Use variable |w:cocViewId| to detect the kind of tree. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- TREE KEY MAPPINGS *coc-tree-mappings* @@ -2916,7 +3400,7 @@ t - Trigger key to toggle expand state of tree node, configured by `tree.key.toggle`. M - Collapse all tree node, configured by `"tree.key.collapseAll"`. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- TREE FILTER *coc-tree-filter* @@ -2929,6 +3413,7 @@ When filter mode is activated, type normal character to insert filter input and following special keys are supported: - Delete last filter character when possible. + - Delete last filter character when possible. - Clean up filter text. - Navigate to previous filter text (stored on command invoke). - Navigate to next filter text (stored on command invoke). @@ -2945,22 +3430,22 @@ Built-in list support to make working with lists of items easier. The following features are supported: -- Insert & normal mode. -- Default key-mappings for insert & normal mode. -- Customize key-mappings for insert & normal mode. -- Commands for reopening & doing actions with a previous list. -- Different match modes. -- Interactive mode. -- Auto preview on cursor move. -- Number select support. -- Built-in actions for locations. -- Parse ANSI code. -- Mouse support. -- Select actions using . -- Multiple selections using in normal mode. -- Select lines by visual selection. - ------------------------------------------------------------------------------- + โ€ข Insert & normal mode. + โ€ข Default key-mappings for insert & normal mode. + โ€ข Customize key-mappings for insert & normal mode. + โ€ข Commands for reopening & doing actions with a previous list. + โ€ข Different match modes. + โ€ข Interactive mode. + โ€ข Auto preview on cursor move. + โ€ข Number select support. + โ€ข Built-in actions for locations. + โ€ข Parse ANSI code. + โ€ข Mouse support. + โ€ข Select actions using . + โ€ข Multiple selections using in normal mode. + โ€ข Select lines by visual selection. + +-------------------------------------------------------------------------------- LIST COMMAND *coc-list-command* @@ -2972,7 +3457,7 @@ LIST COMMAND *coc-list-command* < For current jump locations. - See |coc-list-options| for available list options, + For {options}, see |coc-list-options|. Also check |coc-config-list| for list configuration. @@ -2980,7 +3465,7 @@ LIST COMMAND *coc-list-command* Press `?` on normal mode to get supported {args} of current list. - When {source} is empty, lists source is used. + When {source} is empty, the lists source with list of sources is used. :CocListResume [{name}] *:CocListResume* @@ -3013,79 +3498,88 @@ LIST COMMAND *coc-list-command* *coc-list-options* Options of CocList command~ ---top +----top Show list as top window. ---tab +----tab Open list in new tabpage. ---normal +----normal Start list in normal mode, recommended for short list. ---no-sort +----no-sort Disable sort made by fuzzy score or most recently used, use it when it's already sorted. ---input={input} +----input={input} Specify the input on session start. ---strict --S +----height={number} + + Specify the height of list window, override configuration + |coc-config-list-height|. No effect when list opened in new tab by + `--tab`. + +----strict + โ€ขS Use strict matching instead of fuzzy matching. ---regex --R +----regex + โ€ขR Use regex matching instead of fuzzy matching. ---ignore-case +----ignore-case Ignore case when using strict matching or regex matching. ---number-select --N +----number-select + โ€ขN Type a line number to select an item and invoke the default action on insert mode. Type `0` to select the 10th line. - ---interactive --I +----interactive + โ€ขI Use interactive mode, list items would be reloaded on input change, filter and sort would be done by list implementation. + Note: only works when the list support interactive mode. + Note: filtering and sorting would be done by underlying task, which means options including `--strict`, `--no-sort`, `--regex`, `--ignore-case` would not work at all. - Note: it requires list implementation have support for interactive - mode. - ---auto-preview --A +----auto-preview + โ€ขA Start a preview for the current item on the visible list. ---no-quit +----no-quit - Not quit list session after do action. + Not quit list session after invoke action. Note: you may need to refresh the list for current state. ---first +----first Invoke default action for first list item on list open. Nothing happens when the list is empty. ------------------------------------------------------------------------------- +----reverse + + Reverse the order of list items shown in the window, the bottom line + would shown the first item. + +-------------------------------------------------------------------------------- LIST CONFIGURATION *coc-list-configuration* Use `coc-settings.json` for configuration of lists. -The general configuration of list starts with 'list.'. +Configuration of list starts with 'list.'. -Checkout |coc-config-list| or type `list.` in your settings file to get completion +See |coc-config-list| or type `list.` in your settings file to get completion list (requires coc-json installed). For configuration of a specified list, use section that starts with: @@ -3102,7 +3596,8 @@ in your coc-settings.json Change default options:~ -Use `list.source.{name}.defaultOptions` setting like: > +To change |coc-list-options| for source with {name}, use +`list.source.{name}.defaultOptions` configuration like: > // make symbols list use normal mode and interactive by default "list.source.symbols.defaultOptions": ["--interactive", "--number-select"], @@ -3125,7 +3620,7 @@ empty. Note: Type `?` on normal mode to get supported arguments of current list. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- LIST MAPPINGS *coc-list-mappings* @@ -3168,10 +3663,10 @@ Default mappings on normal mode: - Select action. - Scroll preview window down. - Scroll preview window up. - - Toggle select of current item. + - Toggle selection of current item. i,I,o,O,a,A - Change to insert mode. p - Preview action. -: - Cancel list session without closing window. +: - Cancel the prompt and enter command mode. ? - Show help of current list. t - Do 'tabe' action. d - Do 'drop' action. @@ -3218,7 +3713,8 @@ The mapping expression should be `command:arguments`, available commands: 'togglemode' - toggle between insert and normal mode. 'previous' - move cursor to previous item. 'next' - move cursor to next item. - 'defaultaction' - do default action for selected items or current item. + 'defaultaction' - do default action for selected item(s). + 'chooseaction' - choose action for selected item(s). 'jumpback' - stop prompt and jump back to original window. 'previewtoggle' - toggle preview window, requires preview action exists. 'previewup' - scroll preview window up. @@ -3235,17 +3731,19 @@ The mapping expression should be `command:arguments`, available commands: 'deletebackward' - remove next character. 'removetail' - remove characters afterwards. 'removeahead' - remove character ahead. + 'removeword' - remove word before cursor. 'insertregister' - insert content from Vim register. 'paste' - append text from system clipboard to prompt. -'eval' - append text to prompt from result of VimL expression. -'action' - execute action of list, use to find available actions. -'feedkeys' - feedkeys to list window, use `\\` in JSON to escape special - characters. -'normal' - execute normal command in list window. -'normal!' - execute normal command without remap. -'command' - execute command. -'call' - call Vim function with |coc-list-context| as only argument. -'expr' - same as 'call' but expect the function return action name. +'eval' - append text to prompt from result of VimL expression. +'action' - execute action of list, use to find available actions. +'feedkeys' - feedkeys to list window, use `\\` in JSON to escape special + characters. +'feedkeys!' - feedkeys without remap. +'normal' - execute normal command in list window. +'normal!' - execute normal command without remap. +'command' - execute command. +'call' - call Vim function with |coc-list-context| as only argument. +'expr' - same as 'call' but expect the function return action name. *coc-list-context* @@ -3267,11 +3765,11 @@ Target contains the following properties: 'location' - optional location of item, check out https://bit.ly/2Rtb6Bo 'data' - optional additional properties. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- LIST SOURCES *coc-list-sources* ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- location *coc-list-location* @@ -3290,7 +3788,14 @@ location *coc-list-location* extensions *coc-list-extensions* - Manage coc extensions. + Manage coc.nvim extensions. + First column in the list window represent the state of extension: + + - "*" means the extension is activated. + - "+" means the extension package json is loaded, but not activated by + load the javascript file. + - "-" means the extension is disabled by 'disable' action. + - "?" means the extension is not recognized by coc.nvim. Actions: @@ -3311,6 +3816,15 @@ diagnostics *coc-list-diagnostics* - Same as |coc-list-location| +folders *coc-list-folders* + + Manage current workspace folders of coc.nvim. + + Actions: + + - 'edit' change the directory of workspace folder. + - 'delete' remove selected workspace folder. + outline *coc-list-outline* Symbols in the current document. @@ -3385,20 +3899,20 @@ Note dialog feature requires neovim >= 0.4.0 or vim >= 8.2.0750 to work. See |coc-config-dialog| for available configurations. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- *coc-dialog-basic* -A basic dialog is create by javascript api `window.showDialog` , which is just +A basic dialog is create by Javascript API `window.showDialog` , which is just some texts with optional buttons. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- *coc-dialog-confirm* A confirm dialog is used for user to confirm an action, normally created by `window.showPrompt()` Confirm dialog uses filter feature on vim8 and -|getchar()| on neoivm. +|getchar()| on Neovim. The difference is you can operate vim on vim8, but not on neovim. @@ -3408,36 +3922,62 @@ Supported key-mappings: , n, N - reject the action, return 0 for callback. y,Y - accept the action, return 1 for callback. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- *coc-dialog-input* -A input dialog request user input with optional default value, normally +An input dialog request user input with optional default value, normally created by `window.requestInput`, when `"coc.preferences.promptInput"` is -false, vim's commandline input prompt is used instead. +false, vim's command line input prompt is used instead. + +On neovim, it uses float window, on vim8, it opens terminal in popup. Supported key-mappings: - - move cursor to first col. - - move cursor to last col. - - cancel input, an empty string is received by callback. - - confirm current input. + - move cursor to first col. + - move cursor to last col. + - cancel input, null is received by callback. + - accept current input selection of current item. -And other insert mode key-mappings that your neovim provided. +QuickPick related (available when created by |coc-dialog-quickpick|). ------------------------------------------------------------------------------- + - scroll forward quickpick list. + - scroll backward quickpick list. + - move to next item in quickpick list. + - move to previous item in quickpick list. + - toggle selection of current item in quickpick list when +canSelectMany is supported. + +Note on neovim, other insert mode key-mappings could work. + +Note not possible to configure key-mappings on vim8, to customize key-mappings +on neovim, use |CocOpenFloatPrompt| with current buffer. + +-------------------------------------------------------------------------------- + + *coc-dialog-quickpick* + +A quickpick is a input dialog in the middle with a float window/popup contains +filtered list items. + +Fuzzy filter is used by default. + +See |coc-config-dialog| for available configurations. + +See |coc-dialog-input| for available key-mappings. + +-------------------------------------------------------------------------------- *coc-dialog-menu* -A menu dialog is shown aside current cursor position for pick a single item -from list of items, |coc-codeaction| uses menu dialog by default when it's -supported, extensions could use `window.showMenuPicker` to create menu -dialog. +A menu dialog is used for pick a single item from list of items, extensions +could use `window.showMenuPicker` to create menu dialog. Supported key-mappings: - cancel selection. - - confirm selection of current item. + - confirm selection of current item, use +|dialog.confirmKey| to override. 1-9 - select item with 1 based index. g - move to first item. G - move to last item. @@ -3446,18 +3986,19 @@ k - move to previous item. - scroll forward. - scroll backward. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- *coc-dialog-picker* -A picker dialog is used for multiple selection. On neovim, it's possible to -toggle selection by mouse click inside the bracket. Extensions could use -`window.showPickerDialog` to create picker dialog. +A picker dialog is used for single/multiple selection. On neovim, it's +possible to toggle selection by mouse click inside the bracket. Extensions +could use `window.showPickerDialog` to create picker dialog. Supported key-mappings: - cancel selection. - - confirm selection of selected items. + - confirm selection of current item, use +|dialog.confirmKey| to override. - toggle selection of current item. g - move to first item. G - move to last item. @@ -3466,9 +4007,46 @@ k - move to previous item. - scroll forward. - scroll backward. -Note when close button is clicked, the selection is canceled with undefined +When close button is clicked, the selection is canceled with undefined result (same as ). +It's recommended to use |coc-dialog-quickpick| for filter support. + +============================================================================== + +NOTIFICATION SUPPORT *coc-notification* + +Notification windows are created at the bottom right of the screen. + +Notifications are created by Javascript APIs: `window.showErrorMessage()`, +`window.showWarningMessage()`, `window.showInformationMessage()`, +`window.showNotification()` and `window.withProgress()`. + +Possible kind of notifications: 'error', 'warning', 'info' and 'progress'. + +Message notifications (not progress) requires +|coc-preferences-enableMessageDialog| to be `true`. + +Message notifications without actions would be automatically closed after +milliseconds specified by |coc-config-notification-timeout|. + +Use |coc-config-notification-disabledProgressSources| to disable progress +notifications for specific sources. + +Customize notifications:~ + + โ€ข Customize icons: |g:coc_notify| + โ€ข Customize highlights: |CocNotification| + โ€ข Customize configurations: |coc-config-notification| + +Related functions:~ + + โ€ข |coc#notify#close_all()| + โ€ข |coc#notify#do_action()| + โ€ข |coc#notify#copy()| + โ€ข |coc#notify#show_sources()| + โ€ข |coc#notify#keep()| + ============================================================================== STATUSLINE SUPPORT *coc-status* @@ -3479,8 +4057,12 @@ shown in statusline. The easiest way is add `%{coc#status()}` to your 'statusline' option. Example: > set statusline^=%{coc#status()} -> ------------------------------------------------------------------------------- +< +You may need to use |CocStatusChange| for automatically refresh statusline: > + + autocmd User CocStatusChange redrawstatus +< +-------------------------------------------------------------------------------- *coc-status-manual* @@ -3501,34 +4083,14 @@ Create function: < Add `%{StatusDiagnostic()}` to your 'statusline' option. ------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- *coc-status-airline* With vim-airline: https://github.com/vim-airline/vim-airline -Error and warning display should work in vim-airline out of box. +See |airline-coc| -Disable vim-airline integration: -> - let g:airline#extensions#coc#enabled = 0 -< -Change error symbol: -> - let airline#extensions#coc#error_symbol = 'Error:' -< -Change warning symbol: -> - let airline#extensions#coc#warning_symbol = 'Warning:' -< -Change error format: -> - let airline#extensions#coc#stl_format_err = '%E{[%e(#%fe)]}' -< -Change warning format: -> - let airline#extensions#coc#stl_format_warn = '%W{[%w(#%fw)]}' -< ------------------------------------------------------------------------------ *coc-status-lightline* @@ -3551,35 +4113,26 @@ Use configuration like: > autocmd User CocStatusChange,CocDiagnosticChange call lightline#update() < ============================================================================== -CUSTOM SOURCE *coc-custom-source* +CREATE PLUGINS *coc-plugins* -Creating a custom source in VimL is supported. +There're different ways to extend coc.nvim: -Check out https://github.com/neoclide/coc.nvim/wiki/Create-custom-source + โ€ข Create vim completion sources |coc-api-vim-source|. + โ€ข Create extensions |coc-api-extension|. + โ€ข Create single file extensions |coc-api-single-file|. + โ€ข Debug coc.nvim extension |coc-api-debug|. ============================================================================== FAQ *coc-faq* ------------------------------------------------------------------------------ -Q: I got the error message with xxx provider not found. - -A: It means you don't have coc extension or languageserver that provide - this feature, you have to install extension for it or configure - languageserver. - Note some languageserver may not have that feature supported, please - checkout it's documentation. +Check out https://github.com/neoclide/coc.nvim/wiki/F.A.Q -Q: Syntax highlight on float/popup doesn't looks right. - -A: On neovim, coc.nvim uses background neovim instance which load syntax - plugins only for generate highlights, it may not what you would expect. - -Q: I don't have float/popup window shown up. - -A: For vim8, make sure `echo has('textprop') && has('patch-8.1.1719')` - echo 1. For neovim, you need neovim >= 0.4.0. +============================================================================== +CHANGELOG *coc-changelog* +See history.md under project root. ============================================================================== -vim:tw=78:nosta:noet:ts=8:sts=0:ft=help:noet:fen:fdm=marker: +vim:tw=78:nosta:noet:ts=8:sts=0:ft=help:noet:fen: diff --git a/vim-config/plugins/coc.nvim/doc/tags b/vim-config/plugins/coc.nvim/doc/tags index faba9333..36971144 100644 --- a/vim-config/plugins/coc.nvim/doc/tags +++ b/vim-config/plugins/coc.nvim/doc/tags @@ -1,11 +1,9 @@ -:CocAction coc.txt /*:CocAction* :CocCommand coc.txt /*:CocCommand* :CocConfig coc.txt /*:CocConfig* :CocDiagnostics coc.txt /*:CocDiagnostics* :CocDisable coc.txt /*:CocDisable* :CocEnable coc.txt /*:CocEnable* :CocFirst coc.txt /*:CocFirst* -:CocFix coc.txt /*:CocFix* :CocInfo coc.txt /*:CocInfo* :CocInstall coc.txt /*:CocInstall* :CocLast coc.txt /*:CocLast* @@ -17,7 +15,7 @@ :CocOpenLog coc.txt /*:CocOpenLog* :CocOutline coc.txt /*:CocOutline* :CocPrev coc.txt /*:CocPrev* -:CocRebuild coc.txt /*:CocRebuild* +:CocPrintErrors coc.txt /*:CocPrintErrors* :CocRestart coc.txt /*:CocRestart* :CocSearch coc.txt /*:CocSearch* :CocStart coc.txt /*:CocStart* @@ -25,43 +23,47 @@ :CocUpdate coc.txt /*:CocUpdate* :CocUpdateSync coc.txt /*:CocUpdateSync* :CocWatch coc.txt /*:CocWatch* +(coc-classobj-a) coc.txt /*(coc-classobj-a)* (coc-classobj-i) coc.txt /*(coc-classobj-i)* +(coc-codeaction) coc.txt /*(coc-codeaction)* +(coc-codeaction-cursor) coc.txt /*(coc-codeaction-cursor)* +(coc-codeaction-line) coc.txt /*(coc-codeaction-line)* +(coc-codeaction-refactor) coc.txt /*(coc-codeaction-refactor)* +(coc-codeaction-refactor-selected) coc.txt /*(coc-codeaction-refactor-selected)* +(coc-codeaction-selected) coc.txt /*(coc-codeaction-selected)* +(coc-codeaction-source) coc.txt /*(coc-codeaction-source)* +(coc-codelens-action) coc.txt /*(coc-codelens-action)* +(coc-command-repeat) coc.txt /*(coc-command-repeat)* +(coc-cursors-operator) coc.txt /*(coc-cursors-operator)* (coc-cursors-position) coc.txt /*(coc-cursors-position)* +(coc-cursors-range) coc.txt /*(coc-cursors-range)* (coc-cursors-word) coc.txt /*(coc-cursors-word)* +(coc-declaration) coc.txt /*(coc-declaration)* +(coc-definition) coc.txt /*(coc-definition)* +(coc-diagnostic-info) coc.txt /*(coc-diagnostic-info)* +(coc-diagnostic-next) coc.txt /*(coc-diagnostic-next)* +(coc-diagnostic-next-error) coc.txt /*(coc-diagnostic-next-error)* +(coc-diagnostic-prev) coc.txt /*(coc-diagnostic-prev)* +(coc-diagnostic-prev-error) coc.txt /*(coc-diagnostic-prev-error)* +(coc-fix-current) coc.txt /*(coc-fix-current)* +(coc-float-hide) coc.txt /*(coc-float-hide)* +(coc-float-jump) coc.txt /*(coc-float-jump)* +(coc-format) coc.txt /*(coc-format)* +(coc-format-selected) coc.txt /*(coc-format-selected)* (coc-funcobj-a) coc.txt /*(coc-funcobj-a)* -(Coc-codeaction-selected) coc.txt /*(Coc-codeaction-selected)* -(coc-classobj-a) coc.txt /*(coc-classobj-a)* -(coc-codeaction) coc.txt /*(coc-codeaction)* -(coc-codeaction-cursor) coc.txt /*(coc-codeaction-cursor)* -(coc-codeaction-line) coc.txt /*(coc-codeaction-line)* -(coc-codelens-action) coc.txt /*(coc-codelens-action)* -(coc-command-repeat) coc.txt /*(coc-command-repeat)* -(coc-cursors-operator) coc.txt /*(coc-cursors-operator)* -(coc-cursors-range) coc.txt /*(coc-cursors-range)* -(coc-declaration) coc.txt /*(coc-declaration)* -(coc-definition) coc.txt /*(coc-definition)* -(coc-diagnostic-info) coc.txt /*(coc-diagnostic-info)* -(coc-diagnostic-next) coc.txt /*(coc-diagnostic-next)* -(coc-diagnostic-next-error) coc.txt /*(coc-diagnostic-next-error)* -(coc-diagnostic-prev) coc.txt /*(coc-diagnostic-prev)* -(coc-diagnostic-prev-error) coc.txt /*(coc-diagnostic-prev-error)* -(coc-fix-current) coc.txt /*(coc-fix-current)* -(coc-float-hide) coc.txt /*(coc-float-hide)* -(coc-float-jump) coc.txt /*(coc-float-jump)* -(coc-format) coc.txt /*(coc-format)* -(coc-format-selected) coc.txt /*(coc-format-selected)* -(coc-funcobj-i) coc.txt /*(coc-funcobj-i)* -(coc-implementation) coc.txt /*(coc-implementation)* -(coc-openlink) coc.txt /*(coc-openlink)* -(coc-range-select) coc.txt /*(coc-range-select)* -(coc-range-select-backward) coc.txt /*(coc-range-select-backward)* -(coc-refactor) coc.txt /*(coc-refactor)* -(coc-references) coc.txt /*(coc-references)* -(coc-references-used) coc.txt /*(coc-references-used)* -(coc-rename) coc.txt /*(coc-rename)* -(coc-type-definition) coc.txt /*(coc-type-definition)* +(coc-funcobj-i) coc.txt /*(coc-funcobj-i)* +(coc-implementation) coc.txt /*(coc-implementation)* +(coc-openlink) coc.txt /*(coc-openlink)* +(coc-range-select) coc.txt /*(coc-range-select)* +(coc-range-select-backward) coc.txt /*(coc-range-select-backward)* +(coc-refactor) coc.txt /*(coc-refactor)* +(coc-references) coc.txt /*(coc-references)* +(coc-references-used) coc.txt /*(coc-references-used)* +(coc-rename) coc.txt /*(coc-rename)* +(coc-type-definition) coc.txt /*(coc-type-definition)* CocAction('activeExtension') coc.txt /*CocAction('activeExtension')* CocAction('addRanges') coc.txt /*CocAction('addRanges')* +CocAction('addWorkspaceFolder') coc.txt /*CocAction('addWorkspaceFolder')* CocAction('codeAction') coc.txt /*CocAction('codeAction')* CocAction('codeActionRange') coc.txt /*CocAction('codeActionRange')* CocAction('codeActions') coc.txt /*CocAction('codeActions')* @@ -69,7 +71,9 @@ CocAction('codeLensAction') coc.txt /*CocAction('codeLensAction')* CocAction('colorPresentation') coc.txt /*CocAction('colorPresentation')* CocAction('commands') coc.txt /*CocAction('commands')* CocAction('deactivateExtension') coc.txt /*CocAction('deactivateExtension')* +CocAction('declarations') coc.txt /*CocAction('declarations')* CocAction('definitionHover') coc.txt /*CocAction('definitionHover')* +CocAction('definitions') coc.txt /*CocAction('definitions')* CocAction('diagnosticInfo') coc.txt /*CocAction('diagnosticInfo')* CocAction('diagnosticList') coc.txt /*CocAction('diagnosticList')* CocAction('diagnosticPreview') coc.txt /*CocAction('diagnosticPreview')* @@ -89,50 +93,66 @@ CocAction('formatSelected') coc.txt /*CocAction('formatSelected')* CocAction('getCurrentFunctionSymbol') coc.txt /*CocAction('getCurrentFunctionSymbol')* CocAction('getHover') coc.txt /*CocAction('getHover')* CocAction('getWordEdit') coc.txt /*CocAction('getWordEdit')* +CocAction('getWorkspaceSymbols') coc.txt /*CocAction('getWorkspaceSymbols')* CocAction('hideOutline') coc.txt /*CocAction('hideOutline')* CocAction('highlight') coc.txt /*CocAction('highlight')* +CocAction('implementations') coc.txt /*CocAction('implementations')* CocAction('incomingCalls') coc.txt /*CocAction('incomingCalls')* +CocAction('inspectSemanticToken') coc.txt /*CocAction('inspectSemanticToken')* CocAction('jumpDeclaration') coc.txt /*CocAction('jumpDeclaration')* CocAction('jumpDefinition') coc.txt /*CocAction('jumpDefinition')* CocAction('jumpImplementation') coc.txt /*CocAction('jumpImplementation')* CocAction('jumpReferences') coc.txt /*CocAction('jumpReferences')* CocAction('jumpTypeDefinition') coc.txt /*CocAction('jumpTypeDefinition')* -CocAction('openlink') coc.txt /*CocAction('openlink')* +CocAction('jumpUsed') coc.txt /*CocAction('jumpUsed')* +CocAction('links') coc.txt /*CocAction('links')* +CocAction('openLink') coc.txt /*CocAction('openLink')* CocAction('organizeImport') coc.txt /*CocAction('organizeImport')* CocAction('outgoingCalls') coc.txt /*CocAction('outgoingCalls')* CocAction('pickColor') coc.txt /*CocAction('pickColor')* CocAction('quickfixes') coc.txt /*CocAction('quickfixes')* +CocAction('rangeSelect') coc.txt /*CocAction('rangeSelect')* CocAction('refactor') coc.txt /*CocAction('refactor')* +CocAction('references') coc.txt /*CocAction('references')* CocAction('refreshSource') coc.txt /*CocAction('refreshSource')* CocAction('reloadExtension') coc.txt /*CocAction('reloadExtension')* CocAction('rename') coc.txt /*CocAction('rename')* CocAction('resolveWorkspaceSymbol') coc.txt /*CocAction('resolveWorkspaceSymbol')* CocAction('runCommand') coc.txt /*CocAction('runCommand')* CocAction('selectionRanges') coc.txt /*CocAction('selectionRanges')* +CocAction('semanticHighlight') coc.txt /*CocAction('semanticHighlight')* CocAction('services') coc.txt /*CocAction('services')* CocAction('showIncomingCalls') coc.txt /*CocAction('showIncomingCalls')* CocAction('showOutgoingCalls') coc.txt /*CocAction('showOutgoingCalls')* CocAction('showOutline') coc.txt /*CocAction('showOutline')* CocAction('showSignatureHelp') coc.txt /*CocAction('showSignatureHelp')* +CocAction('showSubTypes') coc.txt /*CocAction('showSubTypes')* +CocAction('showSuperTypes') coc.txt /*CocAction('showSuperTypes')* +CocAction('snippetInsert') coc.txt /*CocAction('snippetInsert')* CocAction('sourceStat') coc.txt /*CocAction('sourceStat')* CocAction('toggleExtension') coc.txt /*CocAction('toggleExtension')* CocAction('toggleService') coc.txt /*CocAction('toggleService')* CocAction('toggleSource') coc.txt /*CocAction('toggleSource')* +CocAction('typeDefinitions') coc.txt /*CocAction('typeDefinitions')* CocAction('uninstallExtension') coc.txt /*CocAction('uninstallExtension')* CocAction() coc.txt /*CocAction()* -CocAction(getWorkspaceSymbols) coc.txt /*CocAction(getWorkspaceSymbols)* CocActionAsync() coc.txt /*CocActionAsync()* CocBold coc.txt /*CocBold* CocCodeLens coc.txt /*CocCodeLens* CocCursorRange coc.txt /*CocCursorRange* CocDeprecatedHighlight coc.txt /*CocDeprecatedHighlight* CocDiagnosticChange coc.txt /*CocDiagnosticChange* +CocDisabled coc.txt /*CocDisabled* CocErrorFloat coc.txt /*CocErrorFloat* CocErrorHighlight coc.txt /*CocErrorHighlight* CocErrorLine coc.txt /*CocErrorLine* CocErrorSign coc.txt /*CocErrorSign* CocErrorVirtualText coc.txt /*CocErrorVirtualText* CocFadeOut coc.txt /*CocFadeOut* +CocFloatActive coc.txt /*CocFloatActive* +CocFloatDividingLine coc.txt /*CocFloatDividingLine* +CocFloatSbar coc.txt /*CocFloatSbar* +CocFloatThumb coc.txt /*CocFloatThumb* CocFloating coc.txt /*CocFloating* CocHasProvider() coc.txt /*CocHasProvider()* CocHighlightRead coc.txt /*CocHighlightRead* @@ -144,15 +164,23 @@ CocHintLine coc.txt /*CocHintLine* CocHintSign coc.txt /*CocHintSign* CocHintVirtualText coc.txt /*CocHintVirtualText* CocHoverRange coc.txt /*CocHoverRange* -CocInfoFloat coc.txt /*CocInfoFloat* CocInfoHighlight coc.txt /*CocInfoHighlight* CocInfoLine coc.txt /*CocInfoLine* CocInfoSign coc.txt /*CocInfoSign* CocInfoVirtualText coc.txt /*CocInfoVirtualText* +CocInlayHint coc.txt /*CocInlayHint* +CocInlayHintParameter coc.txt /*CocInlayHintParameter* +CocInlayHintType coc.txt /*CocInlayHintType* +CocInputBoxVirtualText coc.txt /*CocInputBoxVirtualText* CocItalic coc.txt /*CocItalic* CocJumpPlaceholder coc.txt /*CocJumpPlaceholder* +CocLink coc.txt /*CocLink* +CocLinkedEditing coc.txt /*CocLinkedEditing* +CocList coc.txt /*CocList* +CocListLine coc.txt /*CocListLine* CocListMode coc.txt /*CocListMode* CocListPath coc.txt /*CocListPath* +CocListSearch coc.txt /*CocListSearch* CocLocations() coc.txt /*CocLocations()* CocLocationsAsync() coc.txt /*CocLocationsAsync()* CocLocationsChange coc.txt /*CocLocationsChange* @@ -160,23 +188,39 @@ CocMarkdownCode coc.txt /*CocMarkdownCode* CocMarkdownHeader coc.txt /*CocMarkdownHeader* CocMarkdownLink coc.txt /*CocMarkdownLink* CocMenuSel coc.txt /*CocMenuSel* +CocNotification coc.txt /*CocNotification* +CocNotificationButton coc.txt /*CocNotificationButton* +CocNotificationError coc.txt /*CocNotificationError* +CocNotificationInfo coc.txt /*CocNotificationInfo* +CocNotificationProgress coc.txt /*CocNotificationProgress* +CocNotificationWarning coc.txt /*CocNotificationWarning* CocNotify() coc.txt /*CocNotify()* CocNvimInit coc.txt /*CocNvimInit* CocOpenFloat coc.txt /*CocOpenFloat* CocOpenFloatPrompt coc.txt /*CocOpenFloatPrompt* -CocRegistNotification() coc.txt /*CocRegistNotification()* +CocPum coc.txt /*CocPum* +CocPumDeprecated coc.txt /*CocPumDeprecated* +CocPumDetail coc.txt /*CocPumDetail* +CocPumMenu coc.txt /*CocPumMenu* +CocPumSearch coc.txt /*CocPumSearch* +CocPumShortcut coc.txt /*CocPumShortcut* +CocPumVirtualText coc.txt /*CocPumVirtualText* +CocRegisterNotification() coc.txt /*CocRegisterNotification()* CocRequest() coc.txt /*CocRequest()* CocRequestAsync() coc.txt /*CocRequestAsync()* +CocSearch coc.txt /*CocSearch* CocSelectedLine coc.txt /*CocSelectedLine* CocSelectedRange coc.txt /*CocSelectedRange* CocSelectedText coc.txt /*CocSelectedText* CocSem coc.txt /*CocSem* +CocSnippetVisual coc.txt /*CocSnippetVisual* CocStatusChange coc.txt /*CocStatusChange* CocStrikeThrough coc.txt /*CocStrikeThrough* CocSymbol coc.txt /*CocSymbol* CocSymbolArray coc.txt /*CocSymbolArray* CocSymbolBoolean coc.txt /*CocSymbolBoolean* CocSymbolClass coc.txt /*CocSymbolClass* +CocSymbolColor coc.txt /*CocSymbolColor* CocSymbolConstant coc.txt /*CocSymbolConstant* CocSymbolConstructor coc.txt /*CocSymbolConstructor* CocSymbolDefault coc.txt /*CocSymbolDefault* @@ -185,9 +229,11 @@ CocSymbolEnumMember coc.txt /*CocSymbolEnumMember* CocSymbolEvent coc.txt /*CocSymbolEvent* CocSymbolField coc.txt /*CocSymbolField* CocSymbolFile coc.txt /*CocSymbolFile* +CocSymbolFolder coc.txt /*CocSymbolFolder* CocSymbolFunction coc.txt /*CocSymbolFunction* CocSymbolInterface coc.txt /*CocSymbolInterface* CocSymbolKey coc.txt /*CocSymbolKey* +CocSymbolKeyword coc.txt /*CocSymbolKeyword* CocSymbolMethod coc.txt /*CocSymbolMethod* CocSymbolModule coc.txt /*CocSymbolModule* CocSymbolNamespace coc.txt /*CocSymbolNamespace* @@ -197,9 +243,14 @@ CocSymbolObject coc.txt /*CocSymbolObject* CocSymbolOperator coc.txt /*CocSymbolOperator* CocSymbolPackage coc.txt /*CocSymbolPackage* CocSymbolProperty coc.txt /*CocSymbolProperty* +CocSymbolReference coc.txt /*CocSymbolReference* +CocSymbolSnippet coc.txt /*CocSymbolSnippet* CocSymbolString coc.txt /*CocSymbolString* CocSymbolStruct coc.txt /*CocSymbolStruct* +CocSymbolText coc.txt /*CocSymbolText* CocSymbolTypeParameter coc.txt /*CocSymbolTypeParameter* +CocSymbolUnit coc.txt /*CocSymbolUnit* +CocSymbolValue coc.txt /*CocSymbolValue* CocSymbolVariable coc.txt /*CocSymbolVariable* CocTagFunc() coc.txt /*CocTagFunc()* CocTerminalOpen coc.txt /*CocTerminalOpen* @@ -210,7 +261,6 @@ CocTreeSelected coc.txt /*CocTreeSelected* CocTreeTitle coc.txt /*CocTreeTitle* CocUnderline coc.txt /*CocUnderline* CocUnusedHighlight coc.txt /*CocUnusedHighlight* -CocWarningFloat coc.txt /*CocWarningFloat* CocWarningHighlight coc.txt /*CocWarningHighlight* CocWarningLine coc.txt /*CocWarningLine* CocWarningSign coc.txt /*CocWarningSign* @@ -220,10 +270,15 @@ b:coc_current_function coc.txt /*b:coc_current_function* b:coc_cursors_activated coc.txt /*b:coc_cursors_activated* b:coc_diagnostic_disable coc.txt /*b:coc_diagnostic_disable* b:coc_diagnostic_info coc.txt /*b:coc_diagnostic_info* +b:coc_disabled_sources coc.txt /*b:coc_disabled_sources* b:coc_enabled coc.txt /*b:coc_enabled* +b:coc_force_attach coc.txt /*b:coc_force_attach* b:coc_root_patterns coc.txt /*b:coc_root_patterns* +b:coc_snippet_active coc.txt /*b:coc_snippet_active* b:coc_suggest_blacklist coc.txt /*b:coc_suggest_blacklist* b:coc_suggest_disable coc.txt /*b:coc_suggest_disable* +b:coc_trim_final_newlines coc.txt /*b:coc_trim_final_newlines* +b:coc_trim_trailing_whitespace coc.txt /*b:coc_trim_trailing_whitespace* coc#_select_confirm() coc.txt /*coc#_select_confirm()* coc#add_command() coc.txt /*coc#add_command()* coc#add_extension() coc.txt /*coc#add_extension()* @@ -236,8 +291,28 @@ coc#float#has_float() coc.txt /*coc#float#has_float()* coc#float#has_scroll() coc.txt /*coc#float#has_scroll()* coc#float#scroll() coc.txt /*coc#float#scroll()* coc#jumpable() coc.txt /*coc#jumpable()* +coc#notify coc.txt /*coc#notify* +coc#notify#close_all() coc.txt /*coc#notify#close_all()* +coc#notify#copy() coc.txt /*coc#notify#copy()* +coc#notify#do_action() coc.txt /*coc#notify#do_action()* +coc#notify#keep() coc.txt /*coc#notify#keep()* +coc#notify#show_sources() coc.txt /*coc#notify#show_sources()* coc#on_enter() coc.txt /*coc#on_enter()* +coc#pum coc.txt /*coc#pum* +coc#pum#cancel() coc.txt /*coc#pum#cancel()* +coc#pum#confirm() coc.txt /*coc#pum#confirm()* +coc#pum#info() coc.txt /*coc#pum#info()* +coc#pum#insert() coc.txt /*coc#pum#insert()* +coc#pum#next() coc.txt /*coc#pum#next()* +coc#pum#one_more() coc.txt /*coc#pum#one_more()* +coc#pum#prev() coc.txt /*coc#pum#prev()* +coc#pum#scroll() coc.txt /*coc#pum#scroll()* +coc#pum#select() coc.txt /*coc#pum#select()* +coc#pum#stop() coc.txt /*coc#pum#stop()* +coc#pum#visible() coc.txt /*coc#pum#visible()* coc#refresh() coc.txt /*coc#refresh()* +coc#snippet#next() coc.txt /*coc#snippet#next()* +coc#snippet#prev() coc.txt /*coc#snippet#prev()* coc#start() coc.txt /*coc#start()* coc#status() coc.txt /*coc#status()* coc#util#api_version() coc.txt /*coc#util#api_version()* @@ -246,45 +321,326 @@ coc#util#get_config() coc.txt /*coc#util#get_config()* coc#util#get_config_home() coc.txt /*coc#util#get_config_home()* coc#util#get_data_home() coc.txt /*coc#util#get_data_home()* coc#util#job_command() coc.txt /*coc#util#job_command()* -coc#util#rebuild() coc.txt /*coc#util#rebuild()* coc#util#root_patterns() coc.txt /*coc#util#root_patterns()* coc-actions coc.txt /*coc-actions* +coc-api-console coc-api.txt /*coc-api-console* +coc-api-debug coc-api.txt /*coc-api-debug* +coc-api-extension coc-api.txt /*coc-api-extension* +coc-api-intro coc-api.txt /*coc-api-intro* +coc-api-json coc-api.txt /*coc-api-json* +coc-api-single coc-api.txt /*coc-api-single* +coc-api-vim-source coc-api.txt /*coc-api-vim-source* +coc-api.txt coc-api.txt /*coc-api.txt* coc-autocmds coc.txt /*coc-autocmds* +coc-buffer-variables coc.txt /*coc-buffer-variables* +coc-callHierarchy coc.txt /*coc-callHierarchy* +coc-changelog coc.txt /*coc-changelog* +coc-code-actions coc.txt /*coc-code-actions* +coc-code-lens coc.txt /*coc-code-lens* coc-commands coc.txt /*coc-commands* coc-completion coc.txt /*coc-completion* -coc-config-callHierarchy coc.txt /*coc-config-callHierarchy* -coc-config-codelens coc.txt /*coc-config-codelens* -coc-config-cursors coc.txt /*coc-config-cursors* -coc-config-diagnostic coc.txt /*coc-config-diagnostic* -coc-config-dialog coc.txt /*coc-config-dialog* -coc-config-float coc.txt /*coc-config-float* -coc-config-hover coc.txt /*coc-config-hover* -coc-config-http coc.txt /*coc-config-http* -coc-config-languageserver coc.txt /*coc-config-languageserver* -coc-config-list coc.txt /*coc-config-list* -coc-config-notification coc.txt /*coc-config-notification* -coc-config-npm coc.txt /*coc-config-npm* -coc-config-outline coc.txt /*coc-config-outline* -coc-config-preferences coc.txt /*coc-config-preferences* -coc-config-refactor coc.txt /*coc-config-refactor* -coc-config-suggest coc.txt /*coc-config-suggest* -coc-config-tree coc.txt /*coc-config-tree* +coc-completion-customize coc.txt /*coc-completion-customize* +coc-completion-default coc.txt /*coc-completion-default* +coc-completion-example coc.txt /*coc-completion-example* +coc-completion-functions coc.txt /*coc-completion-functions* +coc-completion-variables coc.txt /*coc-completion-variables* +coc-config coc-config.txt /*coc-config* +coc-config-callHierarchy coc-config.txt /*coc-config-callHierarchy* +coc-config-callHierarchy-enableTooltip coc-config.txt /*coc-config-callHierarchy-enableTooltip* +coc-config-callHierarchy-openCommand coc-config.txt /*coc-config-callHierarchy-openCommand* +coc-config-callHierarchy-splitCommand coc-config.txt /*coc-config-callHierarchy-splitCommand* +coc-config-codeLens coc-config.txt /*coc-config-codeLens* +coc-config-codeLens-enable coc-config.txt /*coc-config-codeLens-enable* +coc-config-codeLens-position coc-config.txt /*coc-config-codeLens-position* +coc-config-codeLens-separator coc-config.txt /*coc-config-codeLens-separator* +coc-config-codeLens-subseparator coc-config.txt /*coc-config-codeLens-subseparator* +coc-config-colors coc-config.txt /*coc-config-colors* +coc-config-colors-enable coc-config.txt /*coc-config-colors-enable* +coc-config-colors-highlightPriority coc-config.txt /*coc-config-colors-highlightPriority* +coc-config-cursors coc-config.txt /*coc-config-cursors* +coc-config-cursors-cancelKey coc-config.txt /*coc-config-cursors-cancelKey* +coc-config-cursors-nextKey coc-config.txt /*coc-config-cursors-nextKey* +coc-config-cursors-previousKey coc-config.txt /*coc-config-cursors-previousKey* +coc-config-cursors-wrapscan coc-config.txt /*coc-config-cursors-wrapscan* +coc-config-diagnostic coc-config.txt /*coc-config-diagnostic* +coc-config-diagnostic-autoRefresh coc-config.txt /*coc-config-diagnostic-autoRefresh* +coc-config-diagnostic-checkCurrentLine coc-config.txt /*coc-config-diagnostic-checkCurrentLine* +coc-config-diagnostic-displayByAle coc-config.txt /*coc-config-diagnostic-displayByAle* +coc-config-diagnostic-enable coc-config.txt /*coc-config-diagnostic-enable* +coc-config-diagnostic-enableHighlightLineNumber coc-config.txt /*coc-config-diagnostic-enableHighlightLineNumber* +coc-config-diagnostic-enableMessage coc-config.txt /*coc-config-diagnostic-enableMessage* +coc-config-diagnostic-enableSign coc-config.txt /*coc-config-diagnostic-enableSign* +coc-config-diagnostic-errorSign coc-config.txt /*coc-config-diagnostic-errorSign* +coc-config-diagnostic-filetypeMap coc-config.txt /*coc-config-diagnostic-filetypeMap* +coc-config-diagnostic-floatConfig coc-config.txt /*coc-config-diagnostic-floatConfig* +coc-config-diagnostic-format coc-config.txt /*coc-config-diagnostic-format* +coc-config-diagnostic-highlightLimit coc-config.txt /*coc-config-diagnostic-highlightLimit* +coc-config-diagnostic-highlightPriority coc-config.txt /*coc-config-diagnostic-highlightPriority* +coc-config-diagnostic-hintSign coc-config.txt /*coc-config-diagnostic-hintSign* +coc-config-diagnostic-infoSign coc-config.txt /*coc-config-diagnostic-infoSign* +coc-config-diagnostic-level coc-config.txt /*coc-config-diagnostic-level* +coc-config-diagnostic-locationlistLevel coc-config.txt /*coc-config-diagnostic-locationlistLevel* +coc-config-diagnostic-locationlistUpdate coc-config.txt /*coc-config-diagnostic-locationlistUpdate* +coc-config-diagnostic-messageDelay coc-config.txt /*coc-config-diagnostic-messageDelay* +coc-config-diagnostic-messageLevel coc-config.txt /*coc-config-diagnostic-messageLevel* +coc-config-diagnostic-messageTarget coc-config.txt /*coc-config-diagnostic-messageTarget* +coc-config-diagnostic-refreshOnInsertMode coc-config.txt /*coc-config-diagnostic-refreshOnInsertMode* +coc-config-diagnostic-separateRelatedInformationAsDiagnostics coc-config.txt /*coc-config-diagnostic-separateRelatedInformationAsDiagnostics* +coc-config-diagnostic-showDeprecated coc-config.txt /*coc-config-diagnostic-showDeprecated* +coc-config-diagnostic-showUnused coc-config.txt /*coc-config-diagnostic-showUnused* +coc-config-diagnostic-signLevel coc-config.txt /*coc-config-diagnostic-signLevel* +coc-config-diagnostic-signPriority coc-config.txt /*coc-config-diagnostic-signPriority* +coc-config-diagnostic-virtualText coc-config.txt /*coc-config-diagnostic-virtualText* +coc-config-diagnostic-virtualTextAlign coc-config.txt /*coc-config-diagnostic-virtualTextAlign* +coc-config-diagnostic-virtualTextCurrentLineOnly coc-config.txt /*coc-config-diagnostic-virtualTextCurrentLineOnly* +coc-config-diagnostic-virtualTextFormat coc-config.txt /*coc-config-diagnostic-virtualTextFormat* +coc-config-diagnostic-virtualTextLevel coc-config.txt /*coc-config-diagnostic-virtualTextLevel* +coc-config-diagnostic-virtualTextLimitInOneLine coc-config.txt /*coc-config-diagnostic-virtualTextLimitInOneLine* +coc-config-diagnostic-virtualTextLineSeparator coc-config.txt /*coc-config-diagnostic-virtualTextLineSeparator* +coc-config-diagnostic-virtualTextLines coc-config.txt /*coc-config-diagnostic-virtualTextLines* +coc-config-diagnostic-virtualTextPrefix coc-config.txt /*coc-config-diagnostic-virtualTextPrefix* +coc-config-diagnostic-virtualTextWinCol coc-config.txt /*coc-config-diagnostic-virtualTextWinCol* +coc-config-diagnostic-warningSign coc-config.txt /*coc-config-diagnostic-warningSign* +coc-config-dialog coc-config.txt /*coc-config-dialog* +coc-config-dialog-confirmKey coc-config.txt /*coc-config-dialog-confirmKey* +coc-config-dialog-floatBorderHighlight coc-config.txt /*coc-config-dialog-floatBorderHighlight* +coc-config-dialog-floatHighlight coc-config.txt /*coc-config-dialog-floatHighlight* +coc-config-dialog-maxHeight coc-config.txt /*coc-config-dialog-maxHeight* +coc-config-dialog-maxWidth coc-config.txt /*coc-config-dialog-maxWidth* +coc-config-dialog-pickerButtonShortcut coc-config.txt /*coc-config-dialog-pickerButtonShortcut* +coc-config-dialog-pickerButtons coc-config.txt /*coc-config-dialog-pickerButtons* +coc-config-dialog-rounded coc-config.txt /*coc-config-dialog-rounded* +coc-config-dialog-shortcutHighlight coc-config.txt /*coc-config-dialog-shortcutHighlight* +coc-config-documentHighlight coc-config.txt /*coc-config-documentHighlight* +coc-config-documentHighlight-priority coc-config.txt /*coc-config-documentHighlight-priority* +coc-config-documentHighlight-timeout coc-config.txt /*coc-config-documentHighlight-timeout* +coc-config-float coc-config.txt /*coc-config-float* +coc-config-floatFactory coc-config.txt /*coc-config-floatFactory* +coc-config-floatFactory-floatConfig coc-config.txt /*coc-config-floatFactory-floatConfig* +coc-config-hover coc-config.txt /*coc-config-hover* +coc-config-hover-autoHide coc-config.txt /*coc-config-hover-autoHide* +coc-config-hover-floatConfig coc-config.txt /*coc-config-hover-floatConfig* +coc-config-hover-previewMaxHeight coc-config.txt /*coc-config-hover-previewMaxHeight* +coc-config-hover-target coc-config.txt /*coc-config-hover-target* +coc-config-http coc-config.txt /*coc-config-http* +coc-config-http-proxy coc-config.txt /*coc-config-http-proxy* +coc-config-http-proxyAuthorization coc-config.txt /*coc-config-http-proxyAuthorization* +coc-config-http-proxyCA coc-config.txt /*coc-config-http-proxyCA* +coc-config-http-proxyStrictSSL coc-config.txt /*coc-config-http-proxyStrictSSL* +coc-config-inlayHint coc-config.txt /*coc-config-inlayHint* +coc-config-inlayHint-display coc-config.txt /*coc-config-inlayHint-display* +coc-config-inlayHint-enable coc-config.txt /*coc-config-inlayHint-enable* +coc-config-inlayHint-enableParameter coc-config.txt /*coc-config-inlayHint-enableParameter* +coc-config-inlayHint-parameterSeparator coc-config.txt /*coc-config-inlayHint-parameterSeparator* +coc-config-inlayHint-refreshOnInsertMode coc-config.txt /*coc-config-inlayHint-refreshOnInsertMode* +coc-config-inlayHint-subSeparator coc-config.txt /*coc-config-inlayHint-subSeparator* +coc-config-inlayHint-typeSeparator coc-config.txt /*coc-config-inlayHint-typeSeparator* +coc-config-languageserver coc-config.txt /*coc-config-languageserver* +coc-config-links coc-config.txt /*coc-config-links* +coc-config-links-enable coc-config.txt /*coc-config-links-enable* +coc-config-links-highlight coc-config.txt /*coc-config-links-highlight* +coc-config-links-tooltip coc-config.txt /*coc-config-links-tooltip* +coc-config-list coc-config.txt /*coc-config-list* +coc-config-list-alignColumns coc-config.txt /*coc-config-list-alignColumns* +coc-config-list-extendedSearchMode coc-config.txt /*coc-config-list-extendedSearchMode* +coc-config-list-floatPreview coc-config.txt /*coc-config-list-floatPreview* +coc-config-list-height coc-config.txt /*coc-config-list-height* +coc-config-list-indicator coc-config.txt /*coc-config-list-indicator* +coc-config-list-insertMappings coc-config.txt /*coc-config-list-insertMappings* +coc-config-list-interactiveDebounceTime coc-config.txt /*coc-config-list-interactiveDebounceTime* +coc-config-list-limitLines coc-config.txt /*coc-config-list-limitLines* +coc-config-list-maxPreviewHeight coc-config.txt /*coc-config-list-maxPreviewHeight* +coc-config-list-menuAction coc-config.txt /*coc-config-list-menuAction* +coc-config-list-nextKeymap coc-config.txt /*coc-config-list-nextKeymap* +coc-config-list-normalMappings coc-config.txt /*coc-config-list-normalMappings* +coc-config-list-previewHighlightGroup coc-config.txt /*coc-config-list-previewHighlightGroup* +coc-config-list-previewSplitRight coc-config.txt /*coc-config-list-previewSplitRight* +coc-config-list-previewToplineOffset coc-config.txt /*coc-config-list-previewToplineOffset* +coc-config-list-previewToplineStyle coc-config.txt /*coc-config-list-previewToplineStyle* +coc-config-list-previousKeymap coc-config.txt /*coc-config-list-previousKeymap* +coc-config-list-selectedSignText coc-config.txt /*coc-config-list-selectedSignText* +coc-config-list-signOffset coc-config.txt /*coc-config-list-signOffset* +coc-config-list-smartCase coc-config.txt /*coc-config-list-smartCase* +coc-config-list-source-diagnostics-includeCode coc-config.txt /*coc-config-list-source-diagnostics-includeCode* +coc-config-list-source-diagnostics-pathFormat coc-config.txt /*coc-config-list-source-diagnostics-pathFormat* +coc-config-list-source-outline-ctagsFiletypes coc-config.txt /*coc-config-list-source-outline-ctagsFiletypes* +coc-config-list-source-symbols-excludes coc-config.txt /*coc-config-list-source-symbols-excludes* +coc-config-list-statusLineSegments coc-config.txt /*coc-config-list-statusLineSegments* +coc-config-notification coc-config.txt /*coc-config-notification* +coc-config-notification-border coc-config.txt /*coc-config-notification-border* +coc-config-notification-disabledProgressSources coc-config.txt /*coc-config-notification-disabledProgressSources* +coc-config-notification-focusable coc-config.txt /*coc-config-notification-focusable* +coc-config-notification-highlightGroup coc-config.txt /*coc-config-notification-highlightGroup* +coc-config-notification-marginRight coc-config.txt /*coc-config-notification-marginRight* +coc-config-notification-maxHeight coc-config.txt /*coc-config-notification-maxHeight* +coc-config-notification-maxWidth coc-config.txt /*coc-config-notification-maxWidth* +coc-config-notification-minProgressWidth coc-config.txt /*coc-config-notification-minProgressWidth* +coc-config-notification-statusLineProgress coc-config.txt /*coc-config-notification-statusLineProgress* +coc-config-notification-timeout coc-config.txt /*coc-config-notification-timeout* +coc-config-notification-winblend coc-config.txt /*coc-config-notification-winblend* +coc-config-npm coc-config.txt /*coc-config-npm* +coc-config-npm-binPath coc-config.txt /*coc-config-npm-binPath* +coc-config-outline coc-config.txt /*coc-config-outline* +coc-config-outline-autoPreview coc-config.txt /*coc-config-outline-autoPreview* +coc-config-outline-autoWidth coc-config.txt /*coc-config-outline-autoWidth* +coc-config-outline-checkBufferSwitch coc-config.txt /*coc-config-outline-checkBufferSwitch* +coc-config-outline-codeActionKinds coc-config.txt /*coc-config-outline-codeActionKinds* +coc-config-outline-detailAsDescription coc-config.txt /*coc-config-outline-detailAsDescription* +coc-config-outline-expandLevel coc-config.txt /*coc-config-outline-expandLevel* +coc-config-outline-followCursor coc-config.txt /*coc-config-outline-followCursor* +coc-config-outline-keepWindow coc-config.txt /*coc-config-outline-keepWindow* +coc-config-outline-previewBorder coc-config.txt /*coc-config-outline-previewBorder* +coc-config-outline-previewBorderHighlightGroup coc-config.txt /*coc-config-outline-previewBorderHighlightGroup* +coc-config-outline-previewBorderRounded coc-config.txt /*coc-config-outline-previewBorderRounded* +coc-config-outline-previewHighlightGroup coc-config.txt /*coc-config-outline-previewHighlightGroup* +coc-config-outline-previewMaxWidth coc-config.txt /*coc-config-outline-previewMaxWidth* +coc-config-outline-previewWinblend coc-config.txt /*coc-config-outline-previewWinblend* +coc-config-outline-showLineNumber coc-config.txt /*coc-config-outline-showLineNumber* +coc-config-outline-sortBy coc-config.txt /*coc-config-outline-sortBy* +coc-config-outline-splitCommand coc-config.txt /*coc-config-outline-splitCommand* +coc-config-outline-switchSortKey coc-config.txt /*coc-config-outline-switchSortKey* +coc-config-outline-togglePreviewKey coc-config.txt /*coc-config-outline-togglePreviewKey* +coc-config-preferences coc-config.txt /*coc-config-preferences* +coc-config-pullDiagnostic coc-config.txt /*coc-config-pullDiagnostic* +coc-config-pullDiagnostic-ignored coc-config.txt /*coc-config-pullDiagnostic-ignored* +coc-config-pullDiagnostic-onChange coc-config.txt /*coc-config-pullDiagnostic-onChange* +coc-config-pullDiagnostic-onSave coc-config.txt /*coc-config-pullDiagnostic-onSave* +coc-config-pullDiagnostic-workspace coc-config.txt /*coc-config-pullDiagnostic-workspace* +coc-config-refactor coc-config.txt /*coc-config-refactor* +coc-config-refactor-afterContext coc-config.txt /*coc-config-refactor-afterContext* +coc-config-refactor-beforeContext coc-config.txt /*coc-config-refactor-beforeContext* +coc-config-refactor-openCommand coc-config.txt /*coc-config-refactor-openCommand* +coc-config-refactor-saveToFile coc-config.txt /*coc-config-refactor-saveToFile* +coc-config-refactor-showMenu coc-config.txt /*coc-config-refactor-showMenu* +coc-config-semanticTokens coc-config.txt /*coc-config-semanticTokens* +coc-config-semanticTokens-combinedModifiers coc-config.txt /*coc-config-semanticTokens-combinedModifiers* +coc-config-semanticTokens-enable coc-config.txt /*coc-config-semanticTokens-enable* +coc-config-semanticTokens-highlightPriority coc-config.txt /*coc-config-semanticTokens-highlightPriority* +coc-config-semanticTokens-incrementTypes coc-config.txt /*coc-config-semanticTokens-incrementTypes* +coc-config-signature coc-config.txt /*coc-config-signature* +coc-config-signature-enable coc-config.txt /*coc-config-signature-enable* +coc-config-signature-floatConfig coc-config.txt /*coc-config-signature-floatConfig* +coc-config-signature-hideOnTextChange coc-config.txt /*coc-config-signature-hideOnTextChange* +coc-config-signature-preferShownAbove coc-config.txt /*coc-config-signature-preferShownAbove* +coc-config-signature-target coc-config.txt /*coc-config-signature-target* +coc-config-signature-triggerSignatureWait coc-config.txt /*coc-config-signature-triggerSignatureWait* +coc-config-snippet coc-config.txt /*coc-config-snippet* +coc-config-snippet-highlight coc-config.txt /*coc-config-snippet-highlight* +coc-config-snippet-nextPlaceholderOnDelete coc-config.txt /*coc-config-snippet-nextPlaceholderOnDelete* +coc-config-snippet-statusText coc-config.txt /*coc-config-snippet-statusText* +coc-config-suggest coc-config.txt /*coc-config-suggest* +coc-config-suggest-acceptSuggestionOnCommitCharacter coc-config.txt /*coc-config-suggest-acceptSuggestionOnCommitCharacter* +coc-config-suggest-asciiCharactersOnly coc-config.txt /*coc-config-suggest-asciiCharactersOnly* +coc-config-suggest-asciiMatch coc-config.txt /*coc-config-suggest-asciiMatch* +coc-config-suggest-autoTrigger coc-config.txt /*coc-config-suggest-autoTrigger* +coc-config-suggest-completionItemKindLabels coc-config.txt /*coc-config-suggest-completionItemKindLabels* +coc-config-suggest-defaultSortMethod coc-config.txt /*coc-config-suggest-defaultSortMethod* +coc-config-suggest-detailField coc-config.txt /*coc-config-suggest-detailField* +coc-config-suggest-enableFloat coc-config.txt /*coc-config-suggest-enableFloat* +coc-config-suggest-enablePreselect coc-config.txt /*coc-config-suggest-enablePreselect* +coc-config-suggest-floatConfig coc-config.txt /*coc-config-suggest-floatConfig* +coc-config-suggest-formatItems coc-config.txt /*coc-config-suggest-formatItems* +coc-config-suggest-highPrioritySourceLimit coc-config.txt /*coc-config-suggest-highPrioritySourceLimit* +coc-config-suggest-ignoreRegexps coc-config.txt /*coc-config-suggest-ignoreRegexps* +coc-config-suggest-insertMode coc-config.txt /*coc-config-suggest-insertMode* +coc-config-suggest-invalidInsertCharacters coc-config.txt /*coc-config-suggest-invalidInsertCharacters* +coc-config-suggest-labelMaxLength coc-config.txt /*coc-config-suggest-labelMaxLength* +coc-config-suggest-languageSourcePriority coc-config.txt /*coc-config-suggest-languageSourcePriority* +coc-config-suggest-localityBonus coc-config.txt /*coc-config-suggest-localityBonus* +coc-config-suggest-lowPrioritySourceLimit coc-config.txt /*coc-config-suggest-lowPrioritySourceLimit* +coc-config-suggest-maxCompleteItemCount coc-config.txt /*coc-config-suggest-maxCompleteItemCount* +coc-config-suggest-minTriggerInputLength coc-config.txt /*coc-config-suggest-minTriggerInputLength* +coc-config-suggest-noselect coc-config.txt /*coc-config-suggest-noselect* +coc-config-suggest-preferCompleteThanJumpPlaceholder coc-config.txt /*coc-config-suggest-preferCompleteThanJumpPlaceholder* +coc-config-suggest-pumFloatConfig coc-config.txt /*coc-config-suggest-pumFloatConfig* +coc-config-suggest-removeDuplicateItems coc-config.txt /*coc-config-suggest-removeDuplicateItems* +coc-config-suggest-reversePumAboveCursor coc-config.txt /*coc-config-suggest-reversePumAboveCursor* +coc-config-suggest-selection coc-config.txt /*coc-config-suggest-selection* +coc-config-suggest-snippetIndicator coc-config.txt /*coc-config-suggest-snippetIndicator* +coc-config-suggest-snippetsSupport coc-config.txt /*coc-config-suggest-snippetsSupport* +coc-config-suggest-timeout coc-config.txt /*coc-config-suggest-timeout* +coc-config-suggest-triggerAfterInsertEnter coc-config.txt /*coc-config-suggest-triggerAfterInsertEnter* +coc-config-suggest-triggerCompletionWait coc-config.txt /*coc-config-suggest-triggerCompletionWait* +coc-config-suggest-virtualText coc-config.txt /*coc-config-suggest-virtualText* +coc-config-tree coc-config.txt /*coc-config-tree* +coc-config-tree-closedIcon coc-config.txt /*coc-config-tree-closedIcon* +coc-config-tree-key-actions coc-config.txt /*coc-config-tree-key-actions* +coc-config-tree-key-activeFilter coc-config.txt /*coc-config-tree-key-activeFilter* +coc-config-tree-key-close coc-config.txt /*coc-config-tree-key-close* +coc-config-tree-key-collapseAll coc-config.txt /*coc-config-tree-key-collapseAll* +coc-config-tree-key-invoke coc-config.txt /*coc-config-tree-key-invoke* +coc-config-tree-key-selectNext coc-config.txt /*coc-config-tree-key-selectNext* +coc-config-tree-key-selectPrevious coc-config.txt /*coc-config-tree-key-selectPrevious* +coc-config-tree-key-toggle coc-config.txt /*coc-config-tree-key-toggle* +coc-config-tree-key-toggleSelection coc-config.txt /*coc-config-tree-key-toggleSelection* +coc-config-tree-openedIcon coc-config.txt /*coc-config-tree-openedIcon* +coc-config-typeHierarchy coc-config.txt /*coc-config-typeHierarchy* +coc-config-typeHierarchy-enableTooltip coc-config.txt /*coc-config-typeHierarchy-enableTooltip* +coc-config-typeHierarchy-openCommand coc-config.txt /*coc-config-typeHierarchy-openCommand* +coc-config-typeHierarchy-splitCommand coc-config.txt /*coc-config-typeHierarchy-splitCommand* +coc-config-workspace coc-config.txt /*coc-config-workspace* +coc-config-workspace-bottomUpFiletypes coc-config.txt /*coc-config-workspace-bottomUpFiletypes* +coc-config-workspace-ignoredFiletypes coc-config.txt /*coc-config-workspace-ignoredFiletypes* +coc-config-workspace-ignoredFolders coc-config.txt /*coc-config-workspace-ignoredFolders* +coc-config-workspace-openOutputCommand coc-config.txt /*coc-config-workspace-openOutputCommand* +coc-config-workspace-openResourceCommand coc-config.txt /*coc-config-workspace-openResourceCommand* +coc-config-workspace-rootPatterns coc-config.txt /*coc-config-workspace-rootPatterns* +coc-config-workspace-workspaceFolderCheckCwd coc-config.txt /*coc-config-workspace-workspaceFolderCheckCwd* +coc-config-workspace-workspaceFolderFallbackCwd coc-config.txt /*coc-config-workspace-workspaceFolderFallbackCwd* +coc-config.txt coc-config.txt /*coc-config.txt* coc-configuration coc.txt /*coc-configuration* +coc-configuration-expand coc.txt /*coc-configuration-expand* +coc-configuration-scope coc.txt /*coc-configuration-scope* coc-contents coc.txt /*coc-contents* -coc-custom-source coc.txt /*coc-custom-source* +coc-cursors coc.txt /*coc-cursors* +coc-diagnostics coc.txt /*coc-diagnostics* +coc-diagnostics-jump coc.txt /*coc-diagnostics-jump* +coc-diagnostics-refresh coc.txt /*coc-diagnostics-refresh* +coc-diagnostics-toggle coc.txt /*coc-diagnostics-toggle* coc-dialog coc.txt /*coc-dialog* coc-dialog-basic coc.txt /*coc-dialog-basic* coc-dialog-confirm coc.txt /*coc-dialog-confirm* coc-dialog-input coc.txt /*coc-dialog-input* coc-dialog-menu coc.txt /*coc-dialog-menu* coc-dialog-picker coc.txt /*coc-dialog-picker* +coc-dialog-quickpick coc.txt /*coc-dialog-quickpick* +coc-document coc.txt /*coc-document* +coc-document-attached coc.txt /*coc-document-attached* +coc-document-colors coc.txt /*coc-document-colors* +coc-document-filetype coc.txt /*coc-document-filetype* +coc-document-highlights coc.txt /*coc-document-highlights* +coc-document-links coc.txt /*coc-document-links* +coc-extensions coc.txt /*coc-extensions* +coc-extensions-folder coc.txt /*coc-extensions-folder* +coc-extensions-npm coc.txt /*coc-extensions-npm* coc-faq coc.txt /*coc-faq* +coc-floating coc.txt /*coc-floating* +coc-floating-close coc.txt /*coc-floating-close* +coc-floating-config coc.txt /*coc-floating-config* +coc-floating-focus coc.txt /*coc-floating-focus* +coc-floating-scroll coc.txt /*coc-floating-scroll* +coc-fold coc.txt /*coc-fold* +coc-format coc.txt /*coc-format* +coc-format-document coc.txt /*coc-format-document* +coc-format-onsave coc.txt /*coc-format-onsave* +coc-format-ontype coc.txt /*coc-format-ontype* +coc-format-options coc.txt /*coc-format-options* +coc-format-selected coc.txt /*coc-format-selected* coc-functions coc.txt /*coc-functions* +coc-global-variables coc.txt /*coc-global-variables* coc-highlights coc.txt /*coc-highlights* +coc-highlights-diagnostics coc.txt /*coc-highlights-diagnostics* +coc-highlights-document coc.txt /*coc-highlights-document* +coc-highlights-float coc.txt /*coc-highlights-float* +coc-highlights-inlayHint coc.txt /*coc-highlights-inlayHint* +coc-hover coc.txt /*coc-hover* +coc-hover-example coc.txt /*coc-hover-example* +coc-inlayHint coc.txt /*coc-inlayHint* coc-installation coc.txt /*coc-installation* coc-interface coc.txt /*coc-interface* coc-introduction coc.txt /*coc-introduction* coc-key-mappings coc.txt /*coc-key-mappings* +coc-linked-editing coc.txt /*coc-linked-editing* coc-list coc.txt /*coc-list* coc-list-command coc.txt /*coc-list-command* coc-list-commands coc.txt /*coc-list-commands* @@ -293,6 +649,7 @@ coc-list-configuration coc.txt /*coc-list-configuration* coc-list-context coc.txt /*coc-list-context* coc-list-diagnostics coc.txt /*coc-list-diagnostics* coc-list-extensions coc.txt /*coc-list-extensions* +coc-list-folders coc.txt /*coc-list-folders* coc-list-links coc.txt /*coc-list-links* coc-list-lists coc.txt /*coc-list-lists* coc-list-location coc.txt /*coc-list-location* @@ -304,8 +661,40 @@ coc-list-services coc.txt /*coc-list-services* coc-list-sources coc.txt /*coc-list-sources* coc-list-symbols coc.txt /*coc-list-symbols* coc-list-target coc.txt /*coc-list-target* +coc-locations coc.txt /*coc-locations* +coc-locations-api coc.txt /*coc-locations-api* +coc-lsp coc.txt /*coc-lsp* +coc-notification coc.txt /*coc-notification* coc-nvim.txt coc.txt /*coc-nvim.txt* +coc-outline coc.txt /*coc-outline* +coc-plugins coc.txt /*coc-plugins* +coc-preferences-bracketEnterImprove coc-config.txt /*coc-preferences-bracketEnterImprove* +coc-preferences-currentFunctionSymbolAutoUpdate coc-config.txt /*coc-preferences-currentFunctionSymbolAutoUpdate* +coc-preferences-enableGFMBreaksInmakrdownDocument coc-config.txt /*coc-preferences-enableGFMBreaksInmakrdownDocument* +coc-preferences-enableLinkedEditing coc-config.txt /*coc-preferences-enableLinkedEditing* +coc-preferences-enableMarkdown coc-config.txt /*coc-preferences-enableMarkdown* +coc-preferences-enableMessageDialog coc-config.txt /*coc-preferences-enableMessageDialog* +coc-preferences-excludeImageLinksInMarkdownDocument coc-config.txt /*coc-preferences-excludeImageLinksInMarkdownDocument* +coc-preferences-extensionUpdateCheck coc-config.txt /*coc-preferences-extensionUpdateCheck* +coc-preferences-floatActions coc-config.txt /*coc-preferences-floatActions* +coc-preferences-formatOnSave coc-config.txt /*coc-preferences-formatOnSave* +coc-preferences-formatOnType coc-config.txt /*coc-preferences-formatOnType* +coc-preferences-jumpCommand coc-config.txt /*coc-preferences-jumpCommand* +coc-preferences-maxFileSize coc-config.txt /*coc-preferences-maxFileSize* +coc-preferences-messageLevel coc-config.txt /*coc-preferences-messageLevel* +coc-preferences-promptInput coc-config.txt /*coc-preferences-promptInput* +coc-preferences-renameFillCurrent coc-config.txt /*coc-preferences-renameFillCurrent* +coc-preferences-silentAutoupdate coc-config.txt /*coc-preferences-silentAutoupdate* +coc-preferences-useQuickfixForLocations coc-config.txt /*coc-preferences-useQuickfixForLocations* +coc-preferences-watchmanPath coc-config.txt /*coc-preferences-watchmanPath* +coc-preferences-willSaveHandlerTimeout coc-config.txt /*coc-preferences-willSaveHandlerTimeout* +coc-pullDiagnostics coc.txt /*coc-pullDiagnostics* +coc-rename coc.txt /*coc-rename* coc-requirements coc.txt /*coc-requirements* +coc-selection-range coc.txt /*coc-selection-range* +coc-semantic-highlights coc.txt /*coc-semantic-highlights* +coc-signature coc.txt /*coc-signature* +coc-snippets coc.txt /*coc-snippets* coc-status coc.txt /*coc-status* coc-status-airline coc.txt /*coc-status-airline* coc-status-lightline coc.txt /*coc-status-lightline* @@ -313,25 +702,36 @@ coc-status-manual coc.txt /*coc-status-manual* coc-tree coc.txt /*coc-tree* coc-tree-filter coc.txt /*coc-tree-filter* coc-tree-mappings coc.txt /*coc-tree-mappings* +coc-typeHierarchy coc.txt /*coc-typeHierarchy* coc-variables coc.txt /*coc-variables* +coc-workspace coc.txt /*coc-workspace* +coc-workspace-edits coc.txt /*coc-workspace-edits* +coc-workspace-folders coc.txt /*coc-workspace-folders* g:WorkspaceFolders coc.txt /*g:WorkspaceFolders* g:coc_border_joinchars coc.txt /*g:coc_border_joinchars* g:coc_borderchars coc.txt /*g:coc_borderchars* -g:coc_channel_timeout coc.txt /*g:coc_channel_timeout* g:coc_config_home coc.txt /*g:coc_config_home* g:coc_data_home coc.txt /*g:coc_data_home* +g:coc_default_semantic_highlight_groups coc.txt /*g:coc_default_semantic_highlight_groups* g:coc_disable_startup_warning coc.txt /*g:coc_disable_startup_warning* g:coc_disable_transparent_cursor coc.txt /*g:coc_disable_transparent_cursor* g:coc_disable_uncaught_error coc.txt /*g:coc_disable_uncaught_error* g:coc_enable_locationlist coc.txt /*g:coc_enable_locationlist* g:coc_filetype_map coc.txt /*g:coc_filetype_map* g:coc_global_extensions coc.txt /*g:coc_global_extensions* +g:coc_highlight_maximum_count coc.txt /*g:coc_highlight_maximum_count* g:coc_jump_locations coc.txt /*g:coc_jump_locations* g:coc_last_float_win coc.txt /*g:coc_last_float_win* g:coc_last_hover_message coc.txt /*g:coc_last_hover_message* g:coc_markdown_disabled_languages coc.txt /*g:coc_markdown_disabled_languages* +g:coc_max_treeview_width coc.txt /*g:coc_max_treeview_width* g:coc_node_args coc.txt /*g:coc_node_args* g:coc_node_path coc.txt /*g:coc_node_path* +g:coc_notify coc.txt /*g:coc_notify* +g:coc_notify_error_icon coc.txt /*g:coc_notify_error_icon* +g:coc_notify_info_icon coc.txt /*g:coc_notify_info_icon* +g:coc_notify_warning_icon coc.txt /*g:coc_notify_warning_icon* +g:coc_open_url_command coc.txt /*g:coc_open_url_command* g:coc_process_pid coc.txt /*g:coc_process_pid* g:coc_prompt_win_width coc.txt /*g:coc_prompt_win_width* g:coc_quickfix_open_command coc.txt /*g:coc_quickfix_open_command* @@ -339,13 +739,12 @@ g:coc_selectmode_mapping coc.txt /*g:coc_selectmode_mapping* g:coc_service_initialized coc.txt /*g:coc_service_initialized* g:coc_snippet_next coc.txt /*g:coc_snippet_next* g:coc_snippet_prev coc.txt /*g:coc_snippet_prev* -g:coc_sources_disable_map coc.txt /*g:coc_sources_disable_map* g:coc_start_at_startup coc.txt /*g:coc_start_at_startup* g:coc_status coc.txt /*g:coc_status* g:coc_status_error_sign coc.txt /*g:coc_status_error_sign* g:coc_status_warning_sign coc.txt /*g:coc_status_warning_sign* +g:coc_terminal_height coc.txt /*g:coc_terminal_height* g:coc_text_prop_offset coc.txt /*g:coc_text_prop_offset* g:coc_uri_prefix_replace_patterns coc.txt /*g:coc_uri_prefix_replace_patterns* g:coc_user_config coc.txt /*g:coc_user_config* g:node_client_debug coc.txt /*g:node_client_debug* -http.proxy coc.txt /*http.proxy* diff --git a/vim-config/plugins/coc.nvim/esbuild.js b/vim-config/plugins/coc.nvim/esbuild.js deleted file mode 100755 index 9ab20185..00000000 --- a/vim-config/plugins/coc.nvim/esbuild.js +++ /dev/null @@ -1,75 +0,0 @@ -const cp = require('child_process') -const fs = require('fs') -const path = require('path') -let revision = '' -try { - let res = cp.execSync('git rev-parse HEAD', {encoding: 'utf8'}) - revision = res.trim().slice(0, 10) -} catch (e) { - // ignore -} - -let envPlugin = { - name: 'env', - setup(build) { - build.onResolve({filter: /\/appenders/}, args => { - let fullpath = path.join(args.resolveDir, args.path) - return { - path: path.relative(__dirname, fullpath).replace(/\\/g, '/'), - namespace: 'env-ns' - } - }) - build.onLoad({filter: /^node_modules\/log4js\/lib\/appenders$/, namespace: 'env-ns'}, args => { - let content = fs.readFileSync(path.join(args.path, 'index.js'), 'utf8') - return { - contents: content.replace(/require\.main/g, '""'), - resolveDir: args.path - } - }) - } -} - -async function start(watch) { - await require('esbuild').build({ - entryPoints: ['src/main.ts'], - bundle: true, - watch, - minify: process.env.NODE_ENV === 'production', - sourcemap: process.env.NODE_ENV === 'development', - define: {REVISION: '"' + revision + '"', ESBUILD: 'true'}, - mainFields: ['module', 'main'], - platform: 'node', - target: 'node12.12', - outfile: 'build/index.js', - banner: { - js: `(function () { - var v = process.version - var parts = v.slice(1).split('.') - var major = parseInt(parts[0], 10) - var minor = parseInt(parts[1], 10) - if (major < 12 || (major == 12 && minor < 12)) { - throw new Error('coc.nvim requires node >= v12.12.0, current version: ' + v) - } -})(); ` - }, - plugins: [envPlugin] - }) -} - -let watch = false -if (process.argv.length > 2 && process.argv[2] === '--watch') { - console.log('watching...') - watch = { - onRebuild(error) { - if (error) { - console.error('watch build failed:', error) - } else { - console.log('watch build succeeded') - } - }, - } -} - -start(watch).catch(e => { - console.error(e) -}) diff --git a/vim-config/plugins/coc.nvim/history.md b/vim-config/plugins/coc.nvim/history.md index b426703c..4f2a22e3 100644 --- a/vim-config/plugins/coc.nvim/history.md +++ b/vim-config/plugins/coc.nvim/history.md @@ -1,3 +1,653 @@ +# 2022-12-25 + +- Create symbol tree from SymbolInformation list. + +# 2022-12-23 + +- Support `URI` as param for API `workspace.jumpTo()`. + +# 2022-12-22 + +- Support popup window for window related APIs. + +# 2022-12-21 + +- When create `CocSem` highlight group, replace invalid character of token types + and token modifiers with underline. + +# 2022-12-20 + +- Export `Buffer.setKeymap` and `Buffer.deleteKeymap` with vim and neovim support. +- Make `workspace.registerLocalKeymap` accept bufnr argument. + +# 2022-12-12 + +- Allow configuration of `window` scoped used by folder configuration file, like + VSCode. +- Add location support for `getHover` action. +- Use unique id for each tab on vim. +- Chinese word segmentation for keywords. + +# 2022-12-05 + +- Add `switchConsole` method to `LanguageClient` + +# 2022-12-03 + +- Add configuration `suggest.insertMode`. + +# 2022-12-02 + +- Expand variables for string configuration value. + +# 2022-11-30 + +- File fragment support for `workspace.jumpTo()`. +- Support `g:coc_open_url_command`. +- Support `contributes.configuration` from extension as array. + +# 2022-11-29 + +- Add documentations for develop of coc.nvim extensions. +- Remove unused variable `g:coc_channel_timeout`. + +# 2022-11-28 + +- Placeholder and update value support for `InputBox` and `QuickPick`. +- `triggerOnly` option property for vim completion source. +- Export `getExtensionById` from `extensions` module. + +# 2022-11-26 + +- Use CTRL-R expression instead of timer for pum related functions: + + - `coc#pum#insert()` + - `coc#pum#one_more()` + - `coc#pum#next()` + - `coc#pum#prev()` + - `coc#pum#stop()` + - `coc#pum#cancel()` + - `coc#pum#confirm()` + +# 2022-11-25 + +- Avoid view change on list create. +- Add configurations `links.enable` and `links.highlight`. +- Use cursorline for list on neovim (to have correct highlight). +- Fix highlight not work on neovim 0.5.0 by use `luaeval`. + +# 2022-11-22 + +- Add command `document.toggleCodeLens`. + +# 2022-11-21 + +- Add `CocAction('addWorkspaceFolder')`. + +# 2022-11-20 + +- Support code lens feature on vim9. +- `codeLens.subseparator` default changed to `|`, like VSCode. +- Add configuration `coc.preferences.enableGFMBreaksInMarkdownDocument`, default to `true` +- Add key-mappings `(coc-codeaction-selected)` and `(coc-codeaction-refactor-selected)`. + +# 2022-11-19 + +- Create highlights after VimEnter. +- Action 'organizeImport' return false instead of throw error when import code + action not found. + +# 2022-11-18 + +- Throw error when rpc request error, instead of echo message. + +# 2022-11-13 + +- Plugin emit ready after extensions activated. + +# 2022-11-12 + +- Not cancel completion when request for in complete sources. + +# 2022-11-11 + +- Support filter and display completion items with different start positions. +- Remove configuration `suggest.fixInsertedWord`, insert word would always + be fixed. +- Configuration `suggest.invalidInsertCharacters` default to line break + characters. + +# 2022-11-10 + +- Not reset 'Search' highlight on float window as it could be used. +- Note remap `` on float preview window. +- Add new action `feedkeys!` to list. +- Add new configuration `list.floatPreview`. + +# 2022-11-07 + +- Add API `CocAction('snippetInsert')` for snippet insert from vim plugin. +- Snippet support for vim source, snippet item should have `isSnippet` to be + `true` and `insertText` to be snippet text, when `on_complete` function exists, + the snippet expand should be handled completion source. + +# 2022-11-06 + +- `window.createQuickPick()` API that show QuickPick by default, call `show()` +- Fix change value property for QuickPick not works. + +# 2022-10-30 + +- Add configuration `colors.enable`, mark `colors.filetypes` deprecated. +- Add command `document.toggleColors` for toggle colors of current buffer. +- Changed filter of completion to use code from VSCode. +- Add configuration `suggest.filterGraceful` + +# 2022-10-39 + +- Add configuration `suggest.enableFloat` back. + +# 2022-10-27 + +- Use `workspace.rootPatterns` replace `coc.preferences.rootPatterns`, old + configuration still works when exists. +- Store configurations with configuration registry. + +# 2022-10-25 + +- Add `--height` support to `CocList`. + +# 2022-10-24 + +- Use builtin static words source for snippet choices. +- Remove configuration `"snippet.choicesMenuPicker"` +- Remove unused internal functions `coc#complete_indent()` and + `coc#_do_complete()` + +# 2022-10-21 + +- Consider utf-16 code unit instead of unicode code point. +- Add `coc#string#character_index()` `coc#string#byte_index()` and + `coc#string#character_length()`. + +# 2022-10-20 + +- Add `coc#pum#one_more()` + +# 2022-10-19 + +- Trigger for trigger sources when no filter results available. + +# 2022-10-18 + +- Change `suggest.maxCompleteItemCount` default to 256. + +# 2022-10-17 + +- Set `g:coc_service_initialized` to `0` before service restart. +- Show warning when diagnostic jump failed. +- Use strwidth.wasm module for string display width. +- Add API `workspace.getDisplayWidth`. + +# 2022-10-15 + +- Add configuration `inlayHint.display`. + +# 2022-10-07 + +- Use `CocFloatActive` for highlight active parameters. + +# 2022-09-28 + +- Limit popupmenu width when exceed screen to &pumwidth, instead of change + completion column. +- Make escape of `${name}` for ultisnip snippets the same behavior as + Ultisnip.vim. + +# 2022-09-27 + +- Use fuzzy.wasm for native fuzzy match. +- Add `binarySearch` and `isFalsyOrEmpty` functions for array. +- `suggest.localityBonus` works like VSCode, using selection ranges. +- Add and export `workspace.computeWordRanges`. +- Rework keywords parse for better performance (parse changed lines only and use + yield to reduce iteration). + +# 2022-09-12 + +- All configurations are now scoped #4185 +- No `onDidChangeConfiguration` event fired when workspace folder changed. +- Deprecated configuration `suggest.detailMaxLength`, use `suggest.labelMaxLength` instead. +- Deprecated configuration `inlayHint.filetypes`, use `inlayHint.enable` with scoped languages instead. +- Deprecated configuration `semanticTokens.filetypes`, use `semanticTokens.enable` with scoped languages instead. +- Use `workspaceFolderValue` instead of `workspaceValue` for `ConfigurationInspect` returned by `WorkspaceConfiguration.inspect()`. + +# 2022-09-04 + +- Add configuration "snippet.choicesMenuPicker". + +# 2022-09-03 + +- Send "WinClosed" event to node client. +- Add `onDidFilterStateChange` and `onDidCursorMoved` to `TreeView`. +- Support `autoPreview` for outline. + +# 2022-09-02 + +- Support `diagnostic.virtualTextFormat`. +- Add command `workspace.writeHeapSnapshot`. + +# 2022-09-01 + +- Add configuration "suggest.asciiMatch" +- Support `b:coc_force_attach`. + +# 2022-08-31 + +- Add configuration "suggest.reversePumAboveCursor". +- Use `DiagnosticSign*` highlight groups when possible. +- Use `DiagnosticUnderline*` highlight groups when possible. + +# 2022-08-30 + +- Export `LineBuilder` class. + +# 2022-08-29 + +- Fix semanticTokens highlights unexpected cleared +- Fix range of `doQuickfix` action. +- Check reverse of `CocFloating`, use `border` and `Normal` highlight when reversed. +- Make `CocInlayHint` use background of `SignColumn`. +- Add command `document.toggleInlayHint`. + +# 2022-08-28 + +- Make `CocMenuSel` use background of `PmenuSel`. +- Snippet related configuration changed (old configuration still works until next release) + - "coc.preferences.snippetStatusText" -> "snippet.statusText" + - "coc.preferences.snippetHighlight" -> "snippet.highlight" + - "coc.preferences.nextPlaceholderOnDelete" -> "snippet.nextPlaceholderOnDelete" +- Add configuration `"list.smartCase"` +- Add configurations for inlay hint + - "inlayHint.refreshOnInsertMode" + - "inlayHint.enableParameter" + - "inlayHint.typeSeparator" + - "inlayHint.parameterSeparator" + - "inlayHint.subSeparator" + +# 2022-08-27 + +- Avoid use `EasyMotion#is_active`, use autocmd to disable linting. +- Show message when call hierarchy provider not found or bad position. + +# 2022-08-26 + +- Remove `completeOpt` from `workspace.env`. +- Add configuration `"diagnostic.virtualTextAlign"`. +- Add warning when required features not compiled with vim. +- Not echo error for semanticTokens request (log only). +- Merge results form providers when possible. + +# 2022-08-24 + +- Virtual text of suggest on vim9. +- Virtual text of diagnostics on vim9. +- Add configuration `inlayHint.filetypes`. +- Inlay hint support on vim9. + +# 2022-08-23 + +- Retry semanticTokens request on server cancel (LSP 3.17). +- `RelativePattern` support for `workspace.createFileSystemWatcher()`. +- `relativePatternSupport` for `DidChangeWatchedFiles` (LSP 3.17). +- Not echo error on `doComplete()`. + +# 2022-08-21 + +- Added `window.createFloatFactory()`, deprecated `FloatFactory` class. +- Support `labelDetails` field of `CompleteItem`(LSP 3.17). +- Added `triggerKind` to `CodeActionContext`, export `CodeActionTriggerKind`. + +# 2022-08-20 + +- Support pull diagnostics `:h coc-pullDiagnostics`. +- Break change: avoid extension overwrite builtin configuration defaults. +- Change default value of configuration "diagnostic.format". +- 'line' changes to 'currline' for `CocAction('codeAction')`. +- Check NodeJS version on syntax error. + +# 2022-08-10 + +- Change "notification.highlightGroup" default to "Normal". + +# 2022-08-07 + +- Add configuration 'suggest.pumFloatConfig'. + +# 2022-08-04 + +- Make diagnostic float window with the same background as CocFloating. + +# 2022-08-03 + +- Add highlight group 'CocFloatingDividingLine'. + +# 2022-08-01 + +- Use custom popup menu, #3862. +- Use "first" instead of "none" for configuration `suggest.selection`. +- Make "first" default for `suggest.selection`, like VSCode. +- Add default blue color for hlgroup `CocMenuSel`. + +# 2022-06-14 + +- Add highlight groups `CocListLine` and `CocListSearch`. + +# 2022-06-11 + +- Add configuration "notification.disabledProgressSources" +- Add "rounded" property to "floatConfig" + +# 2022-06-04 + +- Add configuration `workspace.openOutputCommand`. +- Log channel message of vim when `g:node_client_debug` enabled. + +# 2022-05-30 + +- Disable `progressOnInitialization` for language client by default. + +# 2022-05-28 + +- Support `repeat#set` for commands that make changes only. + +# 2022-05-24 + +- Add transition and annotation support for `workspace.applyEdits()`. +- Add command `workspace.undo` and `workspace.redo`. +- Remove configuration `coc.preferences.promptWorkspaceEdit`. +- Remove command `CocAction` and `CocFix`. + +# 2022-05-22 + +- Check for previous position when not able to find completion match. +- Add `content` support to `window.showMenuPicker()` + +# 2022-05-17 + +- Add `QuickPick` module. +- Add API `window.showQuickPick()` and `window.createQuickPick()`. + +# 2022-05-16 + +- Add properties `title`, `loading` & `borderhighlight` to `InputBox` + +# 2022-05-14 + +- Add `InputOption` support to `window.requestInput` +- Add API `window.createInputBox()`. + +# 2022-05-13 + +- Notification support like VSCode https://github.com/neoclide/coc.nvim/discussions/3813 +- Add configuration `notification.minProgressWidth` +- Add configuration `notification.preferMenuPicker` +- Support `source` in notification windows. + +# 2022-05-07 + +- Show sort method as description in outline view. +- Add configuration `outline.switchSortKey`, default to ``. +- Add configuration `outline.detailAsDescription`, default to `true`. +- Add variable `g:coc_max_treeview_width`. +- Add `position: 'center'` support to `window.showMenuPicker()` + +# 2022-05-06 + +- Use menu for `window.showQuickpick()`. +- Add configuration `outline.autoWidth`, default to `true`. + +# 2022-05-05 + +- Add key bindings to dialog (created by `window.showDialog()`) on neovim. + +# 2022-05-04 + +- Add `languages.registerInlayHintsProvider()` for inlay hint support. + +# 2022-04-25 + +- Add `LinkedEditing` support + +# 2022-04-23 + +- Add `WinScrolled` event to events. + +# 2022-04-20 + +- Select recent item when input is empty and selection is `recentUsedByPrefix`. +- Add `coc#snippet#prev()` and `coc#snippet#next()`. +- Add command `document.checkBuffer`. +- Add `region` param to `window.diffHighlights()`. + +# 2022-04-06 + +- `workspace.onDidOpenTextDocument` fire `contentChanges` as empty array when + document changed with same lines. + +# 2022-04-04 + +- Avoid `CompleteDone` cancel next completion. +- Avoid indent change on `` and `` during completion. +- Support `joinUndo` and `move` with `document.applyEdits()`. + +# 2022-04-02 + +- Change `suggest.triggerCompletionWait` default to `0`. +- Not trigger completion on `TextChangedP`. +- Remove configuration `suggest.echodocSupport`. +- Fix complettion triggered after ``. + +# 2022-03-31 + +- Check buffer rename on write. + +# 2022-03-30 + +- Improve words parse performance. +- Remove configurations `coc.source.around.firstMatch` and `coc.source.buffer.firstMatch`. +- Fix `coc.source.buffer.ignoreGitignore` not works + +# 2022-03-30 + +- Check document reload on detach. + +# 2022-03-29 + +- Add menu actions to refactor buffer. + +# 2022-03-12 + +- Avoid use `` for cancel completion. + +# 2022-03-05 + +- Make `WinClosed` event fires on `CursorHold` to support vim8. +- Add events `TabNew` and `TabClose`. +- Make outline reuse TreeView buffer. + +# 2022-03-02 + +- Add ultisnip option to `snippetManager.insertSnippet()` and + `snippetManager.resolveSnippet()`. +- Support ultisnip regex option: `/a` (ascii option). +- Support transform replacement of ultisnip, including: + - Variable placeholders, `$0`, `$1` etc. + - Escape sequence `\u` `\l` `\U` `\L` `\E` `\n` `\t` + - Conditional replacement: `(?no:text:other text)` + +# 2022-02-28 + +- Change `workspace.ignoredFiletypes` default value to `[]` + +# 2022-02-24 + +- Add `window.activeTextEditor`, `window.visibleTextEditors`. +- Add events `window.onDidChangeActiveTextEditor` `window.onDidChangeVisibleTextEditors`. +- Add class `RelativePattern`. +- Add `workspace.findFiles()`. + +# 2022-02-23 + +- Add `workspace.openTextDocument()` +- Add `Workspace.getRelativePath()`. +- Add `window.terminals` `window.onDidOpenTerminal` `window.onDidCloseTerminal` + and `window.createTerminal`. +- Add `exitStatus` property to `Terminal`. +- Support `strictEnv` in `TerminalOptions` on neovim. +- Deprecated warning for `workspace.createTerminal()`, + `workspace.onDidOpenTerminal` and `workspace.onDidCloseTerminal` + +# 2022-02-18 + +- Clear all highlights created by coc.nvim before restart. +- Support strike through for ansiparse. +- Support `highlights` for `Documentation` in float window. + +# 2022-02-17 + +- Change workspace configuration throw error when workspace folder can't be + resolved. +- Remove configuration `diagnostic.highlightOffset`. + +# 2022-02-15 + +- Add `events.race`. +- Change default `suggest.triggerCompletionWait` to 50. +- Support trigger completion after indent fix. + +# 2022-02-14 + +- Add `pumvisible` property to events. + +# 2022-02-10 + +- Add shortcut support for `window.showMenuPicker()`. +- Add configuration `dialog.shortcutHighlight` for shortcut highlight. +- Add configuration `list.menuAction` for choose action by menu picker. + +# 2022-02-09 + +- Add error log to `nvim_error_event`. +- Add `nvim.lua()` which replace `nvim.executeLua()` to typings.d.ts. + +# 2022-02-08 + +- Support `MenuItem` with disabled property for `window.showMenuPicker` +- Support show disabled code actions in menu picker. + +# 2022-02-07 + +- Change `:CocLocalConfig` to open configuration file of current workspace + folder. + +# 2022-02-05 + +- Support `version` from `textDocument/publishDiagnostics` notification's parameter. +- Support `codeDescription` of diagnostics by add href to float window. +- Support `showDocument` request from language server. +- Support `label` from DocumentSymbolOptions in outline tree. +- Support extra url use regexp under cursor with `openLink` action. +- Support `activeParameter` from signature information. +- Add `trimTrailingWhitespace`, `insertFinalNewline` and `trimFinalNewlines` to FormattingOptions. +- Add configuration `links.tooltip`, default to `false`. + +# 2022-02-04 + +- Add `--reverse` option to list. +- Add `` key-mapping to cancel list in preview window (neovim only). + +# 2022-02-02 + +- Remove `disableWorkspaceFolders` `disableDiagnostics` and `disableCompletion` + from language client option. +- Add configuration `documentHighlight.timeout`. +- Add `tabPersist` option to `ListAction`. +- Add `refactor` to `LocationList` + +# 2022-01-30 + +- Add configuration `diagnostics.virtualTextLevel`. +- Remove configuration `suggest.numberSelect` + +# 2022-01-26 + +- Use `nvim_buf_set_text` when possible to keep extmarks. + +# 2022-01-25 + +- Not trigger completion when filtered is succeed. +- Move methods `workspace.getSelectedRange` `workspace.selectRange` to `window` + module, show deprecated warning when using old methods. + +# 2022-01-23 + +- Support semantic tokens highlights from range provider. + +# 2022-01-22 + +- Not set `gravity` with api `nvim_buf_set_extmark` because highlight bug, wait neovim fix. +- Support watch later created workspace folders for file events. + +# 2022-01-21 + +- Changed semantic token highlight prefix from `CocSem_` to `CocSem`. +- Changed semantic token highlight disabled by default, use configuration + `semanticTokens.filetypes` +- Add configuration `semanticTokens.filetypes`. +- Add configuration `semanticTokens.highlightPriority`. +- Add configuration `semanticTokens.incrementTypes`. +- Add configuration `semanticTokens.combinedModifiers`. +- Add command `semanticTokens.refreshCurrent`. +- Add command `semanticTokens.inspect`. +- Add action `inspectSemanticToken`. +- Rework command `semanticTokens.checkCurrent` to show highlight information. +- Support semantic tokens highlight group composed with type and modifier. + +# 2022-01-21 + +- Add configuration `workspace.ignoredFolders`. +- Add configuration `workspace.workspaceFolderFallbackCwd`. + +# 2022-01-20 + +- Remove deprecated method `workspace.resolveRootFolder`. + +# 2022-01-17 + +- Extend `buffer.updateHighlights` to support `priority`, `combine`, `start_incl` and `end_incl`. +- Add configuration `diagnostic.highlightPriority`. +- Add configuration `colors.filetypes` and `colors.highlightPriority`. + +# 2022-01-16 + +- Add configuration `codeLens.position`. + +# 2022-01-14 + +- Add configuration `suggest.selection`. + +# 2022-01-13 + +- `codeLens.separator` now defaults to `""` and will be placed above lines on neovim >= 0.6.0 . +- Add configurations 'diagnostic.locationlistLevel', 'diagnostic.signLevel', 'diagnostic.messageLevel'. + +# 2022-01-12 + +- Add document.lineAt(), export TextLine class. +- Upgrade node-client, support nvim.exec(). +- Add documentHighlight.priority configuration. + # 2019-08-18 0.0.74 - feat(cursors): support multiple cursors. @@ -30,7 +680,7 @@ - feat(plugin): add highligher module - feat(refactor): add `(coc-refactor)` for refactor window - feat(extension): use mv module for folder rename -- feat(extension): support install taged extension +- feat(extension): support install tagged extension - feat(extension): support custom extension root `g:coc_extension_root` - feat(handler): close signature float window on ')' - feat(list): support `g:coc_quickfix_open_command` @@ -102,7 +752,7 @@ - Add `disableDiagnostics` & `disableCompletion` to languageclient configuration. - Add `signature.triggerSignatureWait` configuration. - Add vim-repeat support for run command and quickfix. -- Add prefered `codeAction` support. +- Add preferred `codeAction` support. - Add `prompt.paste` action to list. - Add title as argument support for `codeAction` action. - Add `suggest.floatEnable` configuration. @@ -153,16 +803,16 @@ - **Break change** logic for resolve workspace folder changed. - Add `Task` module. - Add `getCurrentFunctionSymbol` action. -- Add `list.source.outline.ctagsFilestypes` setting. +- Add `list.source.outline.ctagsFiletypes` setting. - Add `suggest.disableMenu` and `suggest.disableMenu` settings. - Add `equal` support for complete items. - Add support for do action with visual select lines of list. - Add expand tilder support for language server command. - Add switch matcher support to list. -- Add select all support to lsit. +- Add select all support to list. - Add quickfix action to list. - Add `selectionRanges` of LSP. -- Add load extentions for &rtp support. +- Add load extensions for &rtp support. - Add `coc#on_enter()` for formatOnType and add new lines on enter. - Improve completion by support trigger completion when pumvisible. - Remove document check on `BufWritePre`. @@ -172,7 +822,7 @@ - **Break change** not using vim-node-rpc from npm modules any more. - **Break change** rename `_` to `CocRefresh`. - Fix wrong format options send to server. -- Fix throw eror when extention root not created. +- Fix throw error when extension root not created. - Fix MarkedString not considered as markdown. - Fix echo message on vim exit. - Fix error throw on file watch. @@ -183,11 +833,11 @@ - Add `workspace.resolveRootFolder`. - Add `diagnostic.joinMessageLines` setting. - Add `suggest.completionItemKindLabels` setting. -- Add `memento` support for extention. +- Add `memento` support for extension. - Add `workspace.getSelectedRange`. - Add `Terminal` module. - Add command `workbench.action.reloadWindow`. -- Fix extention not activated by command. +- Fix extension not activated by command. - Fix broken undo with floating window. - Fix document create possible wrong uri & filetype. - Improve highlight with floating window. @@ -218,7 +868,7 @@ - Fix critical performance issue on diff text. - Improve color of `CocHighlightText`. - Improve sort of complete items. -- Improve extention list with version and open action. +- Improve extension list with version and open action. # 2019-03-16 @@ -238,14 +888,14 @@ - **Break change** change buffers instead of disk file for `workspace.applyEdits`. - **Break change** add config errors to diagnostic list instead of jump locations. -- **Break change** hack for popup menu flicker is remvoed, use `suggest.reloadPumOnInsertChar` to enable it. +- **Break change** hack for popup menu flicker is removed, use `suggest.reloadPumOnInsertChar` to enable it. - **Break change** use `nvim_select_popupmenu_item` for number select completion. - Add floating window for completion items. - Add floating window support for diagnostics. - Add floating window support for hover documentation. - Add `coc#on_enter()` for notify enter pressed. - Add setting `coc.preferences.useQuickfixForLocations`. -- Add support of `g:coc_watch_extensions` for automatic reload extentions. +- Add support of `g:coc_watch_extensions` for automatic reload extensions. - Add command: `editor.action.doCodeAction`. - Fix service on restarted on windows after rebuild. - Fix config of airline. @@ -270,7 +920,7 @@ - **Break change** default of `suggest.detailMaxLength` changed to 100. - **Break change** option of `workspace.registerKeymap` changed. -- Add settings: `suggest.defailField`. +- Add settings: `suggest.detailField`. - Add check for autocmd in health check. - Add trigger patterns support for complete sources. - Add support of `coc-snippets-expand-jump` @@ -283,7 +933,7 @@ - **Break change** no longer automatic trigger for CursorHoldI #452. - **Break change** add preview option of `completeopt` according to `suggest.enablePreview`. - Add statusItem for CocUpdate. -- Add `-sycn` option for `:CocInstall` +- Add `-sync` option for `:CocInstall` - Add support for floating preview window. - Add more module export. - Fix check of vim-node-rpc throw error. @@ -340,15 +990,15 @@ not found. - Add support for configure sign in statusline. - Add help action for list. -- Fix parse error on extentions update. +- Fix parse error on extensions update. - Fix wrong uri on windows. - Fix cancel list without close ui. - Improve startup time by remove jobwait. # 2019-02-02 -- **Break change:** extentions now update automatically, prompt is removed. -- Add check for extention compatibility. +- **Break change:** extensions now update automatically, prompt is removed. +- Add check for extension compatibility. - Add transform support for placeholder. - Add check for node version. - Add error check for list. @@ -356,7 +1006,7 @@ - Fix preview window not shown. - Fix highlight not cleared on vim. - Fix highlight commands of list block vim on start. -- Improve extention load. +- Improve extension load. - Improve list experience. # 2019-01-28 @@ -371,7 +1021,7 @@ # 2019-01-24 -- **Break change:** python code for denite support moved to seperated repo. +- **Break change:** python code for denite support moved to separated repo. - **Break change:** Quickfix list no longer used. - Add list support. - Add configuration: `coc.preferences.diagnostic.virtualText`. @@ -416,7 +1066,7 @@ - **Break change:** created keymaps use rpcrequest instead of rpcnotify. - **Break change:** snippets provider is removed, use `coc-snippets` for - extention snippets. + extension snippets. - Add command: `coc.action.insertSnippet` - Fix position of snippets. - Fix modifier of registered keymaps. @@ -434,7 +1084,7 @@ # 2018-12-27 - **Break change:** no more message on service ready. -- **Break change:** vim source now registered as extention. +- **Break change:** vim source now registered as extension. - **Break change:** complete item sort have reworked. - **Break change:** request send to coc would throw when service not ready. - Add support for check current state on diagnostic update. @@ -464,7 +1114,7 @@ - Add command `workspace.clearWatchman`. - Add `quickfixs`, `doCodeAction` and `doQuickfix` actions. - Add `g:vim_node_rpc_args` for debug purpose. -- Add `coc#add_extension()` for specify extentions to install. +- Add `coc#add_extension()` for specify extensions to install. - Fix clients not restarted on CocRestart. - Fix `execArgv` and `runtime` not work for node language server. - Fix detail of complete item not echoed sometimes. @@ -475,7 +1125,7 @@ # 2018-12-17 -- **Break change** `vim-node-rpc` now upgrade in bacground. +- **Break change** `vim-node-rpc` now upgrade in background. - Add `ignoredRootPaths` to `languageserver` option. - Add detect of vim running state. - Add `client.vim` for create clients. @@ -489,7 +1139,7 @@ - **Break change** `fixInsertedWord` fix inserted word which ends with word after. - **Break change** `onCompleteSelect` is removed. -- Add `workspace.registerKeymap` for regist keymap. +- Add `workspace.registerKeymap` for register keymap. - Add match score for sort complete items. - Fix possible connection lost. - Fix priority of diagnostic signs. @@ -516,7 +1166,7 @@ `never`. - Fix can't install on windows vim. - Fix `displayByAle` not clearing diagnostics. -- Add check for `vim-node-rpc` udpate on vim. +- Add check for `vim-node-rpc` update on vim. - Add `Resolver` module. - Improve apply `WorkspaceEdit`, support `0` as document version and merge edits for same document. @@ -528,7 +1178,7 @@ - Add setting: `coc.preferences.hoverTarget`, support use echo. - Add setting `coc.preferences.diagnostic.displayByAle` for use ale to display errors. - Add setting `coc.preferences.extensionUpdateCheck` for control update check of - extentions. + extensions. - Add `coc#config` for set configuration in vim. - Fix rootPath not resolved on initialize. - Fix possible wrong `tabSize` by use `shiftwidth` option. @@ -552,7 +1202,7 @@ - Add echo message when provider not found for some actions. - Add support for `formatexpr` - Add support for locality bonus like VSCode. -- Add support of `applyAdditionaLEdits` on item selected by `` +- Add support of `applyAdditionalLEdits` on item selected by `` - Add `coc.preferences.useQuickfixForLocations` - Add `coc.preferences.messageLevel` - Add support for trigger command which not registered by server. @@ -569,13 +1219,13 @@ # 2018-11-24 -- **Break change** sources exluding `around`, `buffer` or `file` are extracted +- **Break change** sources excluding `around`, `buffer` or `file` are extracted as extensions. -- **Break change** custom source not exists any more. +- **Break change** custom source doesn't exist any more. - Add `coc.preferences.preferCompleteThanJumpPlaceholder` to make jump placeholder behavior as confirm completion when possible. - Add `CocDiagnosticChange` autocmd for force statusline update. -- Add `onDidUnloadExtension` event on extention unload. +- Add `onDidUnloadExtension` event on extension unload. - Fix `getDiagnosticsInRange`, consider all interactive ranges. - Fix completion throw when `data` on complete item is `string`. - Fix `commitCharacters` not works. @@ -839,7 +1489,7 @@ # 2018-09-07 -- **Break change**: all extension all seperated from core, checkout +- **Break change**: all extension all separated from core, checkout [Using coc extension](https://github.com/neoclide/coc.nvim/wiki/Using-coc-extensions) - Fix `textDocumentSync` option not work when received as object. - Fix wrong diagnostic info when using multiple lint servers. @@ -959,7 +1609,7 @@ - Add support filetype change of buffer. - Add basic test for completion. - Improve loading speed, use child process to initialize vim sources. -- Improve install.sh, install node when not exists. +- Improve install.sh, install node when it doesn't exist. - Improve interface of workspace. - Fix loading of configuration content. diff --git a/vim-config/plugins/coc.nvim/jest.js b/vim-config/plugins/coc.nvim/jest.js deleted file mode 100644 index 97e40400..00000000 --- a/vim-config/plugins/coc.nvim/jest.js +++ /dev/null @@ -1,17 +0,0 @@ -const path = require('path') -const os = require('os') -const fs = require('fs') - -process.on('uncaughtException', function (err) { - let msg = 'Uncaught exception: ' + err.stack - console.error(msg) -}) - -module.exports = async () => { - let dataHome = path.join(os.tmpdir(), `coc-test/${process.pid}`) - fs.mkdirSync(dataHome, {recursive: true}) - process.env.NODE_ENV = 'test' - process.env.COC_DATA_HOME = dataHome - process.env.COC_VIMCONFIG = path.join(__dirname, 'src/__tests__') - process.env.TMPDIR = '/tmp/coc-test' -} diff --git a/vim-config/plugins/coc.nvim/lua/coc/highlight.lua b/vim-config/plugins/coc.nvim/lua/coc/highlight.lua new file mode 100644 index 00000000..cbdd7d4d --- /dev/null +++ b/vim-config/plugins/coc.nvim/lua/coc/highlight.lua @@ -0,0 +1,85 @@ +local api = vim.api + +local M = {} + +-- Get single line extmarks +function M.getHighlights(bufnr, key, s, e) + if not api.nvim_buf_is_loaded(bufnr) then + return nil + end + s = s or 0 + e = e or -1 + local max = e == -1 and api.nvim_buf_line_count(bufnr) or e + 1 + local ns = api.nvim_create_namespace('coc-' .. key) + local markers = api.nvim_buf_get_extmarks(bufnr, ns, {s, 0}, {e, -1}, {details = true}) + local res = {} + for _, mark in ipairs(markers) do + local id = mark[1] + local line = mark[2] + local startCol = mark[3] + local details = mark[4] + local endCol = details.end_col + if line < max then + local delta = details.end_row - line + if delta <= 1 and (delta == 0 or endCol == 0) then + if startCol == endCol then + api.nvim_buf_del_extmark(bufnr, ns, id) + else + if delta == 1 then + local text = api.nvim_buf_get_lines(bufnr, line, line + 1, false)[1] or '' + endCol = #text + end + table.insert(res, {details.hl_group, line, startCol, endCol, id}) + end + end + end + end + return res +end + +local function addHighlights(bufnr, ns, highlights, priority) + for _, items in ipairs(highlights) do + local hlGroup = items[1] + local line = items[2] + local startCol = items[3] + local endCol = items[4] + local hlMode = items[5] and 'combine' or 'replace' + -- Error: col value outside range + pcall(api.nvim_buf_set_extmark, bufnr, ns, line, startCol, { + end_col = endCol, + hl_group = hlGroup, + hl_mode = hlMode, + right_gravity = true, + priority = type(priority) == 'number' and math.min(priority, 4096) or 4096 + }) + end +end + +local function addHighlightTimer(bufnr, ns, highlights, priority, maxCount) + local hls = {} + local next = {} + for i, v in ipairs(highlights) do + if i < maxCount then + table.insert(hls, v) + else + table.insert(next, v) + end + end + addHighlights(bufnr, ns, hls, priority) + if #next > 0 then + vim.defer_fn(function() + addHighlightTimer(bufnr, ns, next, priority, maxCount) + end, 30) + end +end + +function M.set(bufnr, ns, highlights, priority) + local maxCount = vim.g.coc_highlight_maximum_count + if #highlights > maxCount then + addHighlightTimer(bufnr, ns, highlights, priority, maxCount) + else + addHighlights(bufnr, ns, highlights, priority) + end +end + +return M diff --git a/vim-config/plugins/coc.nvim/package.json b/vim-config/plugins/coc.nvim/package.json index 04a4872d..3285f308 100644 --- a/vim-config/plugins/coc.nvim/package.json +++ b/vim-config/plugins/coc.nvim/package.json @@ -1,121 +1,17 @@ { - "name": "coc.nvim-master", - "version": "0.0.80", + "name": "coc.nvim-release", + "version": "0.0.82", "description": "LSP based intellisense engine for neovim & vim8.", - "main": "./lib/index.js", "engines": { "node": ">=12.12.0" }, - "scripts": { - "clean": "rimraf lib build", - "lint": "eslint . --ext .ts --quiet", - "lint:typecheck": "tsc -p tsconfig.json", - "build": "node esbuild.js", - "test": "./node_modules/.bin/jest --forceExit", - "test-build": "./node_modules/.bin/jest --coverage --forceExit", - "prepare": "node esbuild.js" - }, "repository": { "type": "git", "url": "git+https://github.com/neoclide/coc.nvim.git" }, - "keywords": [ - "complete", - "neovim" - ], "author": "Qiming Zhao ", - "license": "MIT", "bugs": { "url": "https://github.com/neoclide/coc.nvim/issues" }, - "homepage": "https://github.com/neoclide/coc.nvim#readme", - "jest": { - "globals": { - "__TEST__": true - }, - "projects": [ - "" - ], - "watchman": false, - "clearMocks": true, - "globalSetup": "./jest.js", - "testEnvironment": "node", - "coveragePathIgnorePatterns": [ - "/src/__tests__/*" - ], - "coverageReporters": [ - "text", - "lcov" - ], - "moduleFileExtensions": [ - "ts", - "tsx", - "json", - "js" - ], - "transform": { - "^.+\\.tsx?$": "ts-jest" - }, - "testRegex": "src/__tests__/.*\\.(test|spec)\\.ts$", - "coverageDirectory": "./coverage/" - }, - "devDependencies": { - "@types/cli-table": "^0.3.0", - "@types/debounce": "^3.0.0", - "@types/fb-watchman": "^2.0.0", - "@types/fs-extra": "^9.0.6", - "@types/jest": "^27.0.1", - "@types/marked": "^2.0.4", - "@types/minimatch": "^3.0.3", - "@types/mkdirp": "^1.0.1", - "@types/node": "12.12.12", - "@types/semver": "^7.3.4", - "@types/tar": "^4.0.5", - "@types/uuid": "^8.3.0", - "@types/which": "^1.3.2", - "@typescript-eslint/eslint-plugin": "^4.11.1", - "@typescript-eslint/parser": "^4.11.1", - "bser": "^2.1.1", - "esbuild": "^0.12.7", - "eslint": "^7.15.0", - "eslint-plugin-jest": "^24.1.3", - "eslint-plugin-jsdoc": "^30.7.13", - "jest": "27.0.6", - "ts-jest": "^27.0.5", - "typescript": "^4.3.5", - "vscode-languageserver": "7.0.0" - }, - "dependencies": { - "@chemzqm/neovim": "^5.4.0", - "bytes": "^3.1.0", - "tslib": "^2.0.3", - "ansi-styles": "^5.0.0", - "cli-table": "^0.3.4", - "debounce": "^1.2.0", - "fast-diff": "^1.2.0", - "fb-watchman": "^2.0.1", - "fs-extra": "^9.0.1", - "follow-redirects": "^1.13.0", - "http-proxy-agent": "^4.0.1", - "https-proxy-agent": "^5.0.0", - "isuri": "^2.0.3", - "jsonc-parser": "^3.0.0", - "log4js": "^6.3.0", - "marked": "^2.1.3", - "minimatch": "^3.0.4", - "rc": "^1.2.8", - "semver": "^7.3.2", - "strip-ansi": "^6.0.0", - "tar": "^6.1.9", - "unzip-stream": "^0.3.1", - "content-disposition": "^0.5.3", - "decompress-response": "^6.0.0", - "uuid": "^7.0.3", - "which": "^2.0.2", - "vscode-uri": "^2.1.2", - "vscode-jsonrpc": "^6.0.0", - "vscode-languageserver-protocol": "^3.16.0", - "vscode-languageserver-textdocument": "^1.0.1", - "vscode-languageserver-types": "^3.16.0" - } + "homepage": "https://github.com/neoclide/coc.nvim#readme" } diff --git a/vim-config/plugins/coc.nvim/plugin/coc.vim b/vim-config/plugins/coc.nvim/plugin/coc.vim index 66f995d1..2c225929 100644 --- a/vim-config/plugins/coc.nvim/plugin/coc.vim +++ b/vim-config/plugins/coc.nvim/plugin/coc.vim @@ -7,25 +7,33 @@ function! s:checkVersion() abort let l:unsupported = 0 if get(g:, 'coc_disable_startup_warning', 0) != 1 if has('nvim') - let l:unsupported = !has('nvim-0.3.2') + let l:unsupported = !has('nvim-0.4.0') else - let l:unsupported = !has('patch-8.0.1453') + let l:unsupported = !has('patch-8.1.1719') endif if l:unsupported == 1 echohl Error - echom "coc.nvim requires at least Vim 8.0.1453 or Neovim 0.3.2, but you're using an older version." + echom "coc.nvim requires at least Vim 8.1.1719 or Neovim 0.4.0, but you're using an older version." echom "Please upgrade your (neo)vim." echom "You can add this to your vimrc to avoid this message:" echom " let g:coc_disable_startup_warning = 1" echom "Note that some features may error out or behave incorrectly." - echom "Please do not report bugs unless you're using at least Vim 8.0.1453 or Neovim 0.3.2." + echom "Please do not report bugs unless you're using at least Vim 8.1.1719 or Neovim 0.4.0." echohl None sleep 2 else - if !has('nvim-0.4.0') && !has('patch-8.1.1719') + if !has('nvim-0.5.0') && !has('patch-8.2.0750') echohl WarningMsg - echom "coc.nvim works best on vim >= 8.1.1719 and neovim >= 0.4.0, consider upgrade your vim." + echom "coc.nvim works best on vim >= 8.2.0750 and neovim >= 0.5.0, consider upgrade your vim." + echom "You can add this to your vimrc to avoid this message:" + echom " let g:coc_disable_startup_warning = 1" + echom "Note that some features may behave incorrectly." + echohl None + sleep 2 + elseif !has('nvim') && (!has('job') || !has('popupwin') || !has('textprop')) + echohl WarningMsg + echom "coc.nvim requires job, popupwin and textprop features of vim, consider recompile your vim." echom "You can add this to your vimrc to avoid this message:" echom " let g:coc_disable_startup_warning = 1" echom "Note that some features may behave incorrectly." @@ -40,10 +48,9 @@ call s:checkVersion() let g:did_coc_loaded = 1 let g:coc_service_initialized = 0 -let s:is_win = has('win32') || has('win64') let s:root = expand(':h:h') let s:is_vim = !has('nvim') -let s:is_gvim = get(v:, 'progname', '') ==# 'gvim' +let s:is_gvim = s:is_vim && has("gui_running") if get(g:, 'coc_start_at_startup', 1) && !s:is_gvim call coc#rpc#start_server() @@ -57,13 +64,30 @@ function! CocTagFunc(pattern, flags, info) abort return coc#rpc#request('getTagList', []) endfunction +" Used by popup prompt on vim function! CocPopupCallback(bufnr, arglist) abort if len(a:arglist) == 2 if a:arglist[0] == 'confirm' - call coc#rpc#notify('PromptInsert', [a:arglist[1]]) + call coc#rpc#notify('PromptInsert', [a:arglist[1], a:bufnr]) elseif a:arglist[0] == 'exit' execute 'silent! bd! '.a:bufnr "call coc#rpc#notify('PromptUpdate', [a:arglist[1]]) + elseif a:arglist[0] == 'change' + let text = a:arglist[1] + let current = getbufvar(a:bufnr, 'current', '') + if text !=# current + call setbufvar(a:bufnr, 'current', text) + let cursor = term_getcursor(a:bufnr) + let info = { + \ 'lnum': cursor[0], + \ 'col': cursor[1], + \ 'line': text, + \ 'changedtick': 0 + \ } + call coc#rpc#notify('CocAutocmd', ['TextChangedI', a:bufnr, info]) + endif + elseif a:arglist[0] == 'send' + call coc#rpc#notify('PromptKeyPress', [a:bufnr, a:arglist[1]]) endif endif endfunction @@ -91,18 +115,23 @@ function! CocNotify(...) abort return coc#rpc#request('sendNotification', a:000) endfunction +function! CocRegisterNotification(id, method, cb) abort + call coc#on_notify(a:id, a:method, a:cb) +endfunction + +" Deprecated, use CocRegisterNotification instead function! CocRegistNotification(id, method, cb) abort call coc#on_notify(a:id, a:method, a:cb) endfunction function! CocLocations(id, method, ...) abort let args = [a:id, a:method] + copy(a:000) - call coc#rpc#request('findLocations', args) + return coc#rpc#request('findLocations', args) endfunction function! CocLocationsAsync(id, method, ...) abort let args = [a:id, a:method] + copy(a:000) - call coc#rpc#notify('findLocations', args) + return s:AsyncRequest('findLocations', args) endfunction function! CocRequestAsync(...) @@ -157,7 +186,7 @@ function! s:OpenConfig() let home = coc#util#get_config_home() if !isdirectory(home) echohl MoreMsg - echom 'Config directory "'.home.'" not exists, create? (y/n)' + echom 'Config directory "'.home.'" does not exist, create? (y/n)' echohl None let confirm = nr2char(getchar()) redraw! @@ -167,7 +196,7 @@ function! s:OpenConfig() call mkdir(home, 'p') end endif - execute 'edit '.home.'/coc-settings.json' + execute 'edit '.fnameescape(home.'/coc-settings.json') call coc#rpc#notify('checkJsonExtension', []) endfunction @@ -213,9 +242,13 @@ function! s:AddAnsiGroups() abort endtry endfunction -function! s:CursorRangeFromSelected(type, ...) abort - " add range by operator - call coc#rpc#request('cursorsSelect', [bufnr('%'), 'operator', a:type]) +function! s:CreateHighlight(group, fg, bg) abort + let cmd = coc#highlight#compose(a:fg, a:bg) + if !empty(trim(cmd)) + exe 'hi default '.a:group.' '.cmd + else + exe 'hi default link '.a:group.' '.a:fg + endif endfunction function! s:OpenDiagnostics(...) abort @@ -232,9 +265,7 @@ function! s:Disable() abort if get(g:, 'coc_enabled', 0) == 0 return endif - augroup coc_nvim - autocmd! - augroup end + autocmd! coc_nvim call coc#rpc#request('detach', []) echohl MoreMsg echom '[coc.nvim] Event disabled' @@ -243,39 +274,104 @@ function! s:Disable() abort endfunction function! s:Autocmd(...) abort - if !g:coc_service_initialized + if !get(g:, 'coc_workspace_initialized', 0) return endif call coc#rpc#notify('CocAutocmd', a:000) endfunction +function! s:HandleCharInsert(char, bufnr) abort + if get(g:, 'coc_feeding_keys', 0) + return + endif + if get(g:, 'coc_disable_space_report', 0) + let g:coc_disable_space_report = 0 + if a:char ==# ' ' + return + endif + endif + call s:Autocmd('InsertCharPre', a:char, a:bufnr) +endfunction + +function! s:HandleTextChangedI(bufnr) abort + if get(g:, 'coc_feeding_keys', 0) + unlet g:coc_feeding_keys + endif + call s:Autocmd('TextChangedI', a:bufnr, coc#util#change_info()) +endfunction + +function! s:HandleInsertLeave(bufnr) abort + call coc#pum#close() + call s:Autocmd('InsertLeave', a:bufnr) +endfunction + +function! s:HandleWinScrolled(winid) abort + if getwinvar(a:winid, 'float', 0) + call coc#float#nvim_scrollbar(a:winid) + endif + call s:Autocmd('WinScrolled', a:winid) +endfunction + +function! s:HandleWinClosed(winid) abort + call coc#float#on_close(a:winid) + call coc#notify#on_close(a:winid) + call s:Autocmd('WinClosed', a:winid) +endfunction + function! s:SyncAutocmd(...) - if !g:coc_service_initialized + if !get(g:, 'coc_workspace_initialized', 0) return endif call coc#rpc#request('CocAutocmd', a:000) endfunction +function! s:VimLeavePre() abort + let g:coc_vim_leaving = 1 + call s:Autocmd('VimLeavePre') + if s:is_vim && exists('$COC_NVIM_REMOTE_ADDRESS') + " Helps to avoid connection error. + call coc#rpc#close_connection() + return + endif + if get(g:, 'coc_node_env', '') ==# 'test' + return + endif + if s:is_vim + call timer_start(1, { -> coc#client#kill('coc')}) + endif +endfunction + +function! s:VimEnter() abort + if coc#rpc#started() + if !exists('$COC_NVIM_REMOTE_ADDRESS') + call coc#rpc#notify('VimEnter', [coc#util#path_replace_patterns(), join(globpath(&runtimepath, "", 0, 1), ",")]) + endif + elseif get(g:, 'coc_start_at_startup', 1) + call coc#rpc#start_server() + endif + call s:Highlight() +endfunction + function! s:Enable(initialize) if get(g:, 'coc_enabled', 0) == 1 return endif + let g:coc_enabled = 1 + sign define CocCurrentLine linehl=CocMenuSel + sign define CocListCurrent linehl=CocListLine + sign define CocTreeSelected linehl=CocTreeSelected + if s:is_vim + call coc#api#tabpage_ids() + endif augroup coc_nvim autocmd! - if exists('##MenuPopupChanged') && exists('*nvim_open_win') - autocmd MenuPopupChanged * call s:Autocmd('MenuPopupChanged', get(v:, 'event', {}), win_screenpos(winnr())[0] + winline() - 2) - endif - if exists('##CompleteChanged') - autocmd CompleteChanged * call s:Autocmd('MenuPopupChanged', get(v:, 'event', {}), win_screenpos(winnr())[0] + winline() - 2) - endif - - if coc#rpc#started() - autocmd VimEnter * call coc#rpc#notify('VimEnter', []) - elseif get(g:, 'coc_start_at_startup', 1) - autocmd VimEnter * call coc#rpc#start_server() + if !v:vim_did_enter + autocmd VimEnter * call s:VimEnter() + else + call s:Highlight() endif if s:is_vim if exists('##DirChanged') @@ -284,51 +380,57 @@ function! s:Enable(initialize) if exists('##TerminalOpen') autocmd TerminalOpen * call s:Autocmd('TermOpen', +expand('')) endif + autocmd CursorMoved list:///* call coc#list#select(bufnr('%'), line('.')) + autocmd TabNew * call coc#api#tabpage_ids() else autocmd DirChanged * call s:Autocmd('DirChanged', get(v:event, 'cwd', '')) autocmd TermOpen * call s:Autocmd('TermOpen', +expand('')) - autocmd TermClose * call s:Autocmd('TermClose', +expand('')) - autocmd CursorMoved * call coc#float#nvim_refresh_scrollbar(win_getid()) autocmd WinEnter * call coc#float#nvim_win_enter(win_getid()) - if exists('##WinClosed') - autocmd WinClosed * call coc#float#close_related(+expand('')) - autocmd WinClosed * call s:Autocmd('WinClosed', +expand('')) - endif endif - if has('nvim-0.4.0') || has('patch-8.1.1719') - autocmd CursorHold * call coc#float#check_related() + if exists('##CompleteChanged') + autocmd CompleteChanged * call timer_start(1, { -> coc#pum#close()}) + endif + autocmd CursorHold * call coc#float#check_related() + if exists('##WinClosed') + autocmd WinClosed * call s:HandleWinClosed(+expand('')) + elseif exists('##TabEnter') + autocmd TabEnter * call coc#notify#reflow() endif + if exists('##WinScrolled') + autocmd WinScrolled * call s:HandleWinScrolled(+expand('')) + endif + autocmd TabNew * call s:Autocmd('TabNew', coc#util#tabnr_id(tabpagenr())) + autocmd TabClosed * call s:Autocmd('TabClosed', coc#util#tabpages()) autocmd WinLeave * call s:Autocmd('WinLeave', win_getid()) autocmd WinEnter * call s:Autocmd('WinEnter', win_getid()) autocmd BufWinLeave * call s:Autocmd('BufWinLeave', +expand(''), bufwinid(+expand(''))) autocmd BufWinEnter * call s:Autocmd('BufWinEnter', +expand(''), win_getid()) autocmd FileType * call s:Autocmd('FileType', expand(''), +expand('')) - autocmd CompleteDone * call s:Autocmd('CompleteDone', get(v:, 'completed_item', {})) - autocmd InsertCharPre * call s:Autocmd('InsertCharPre', v:char, bufnr('%')) + autocmd InsertCharPre * call s:HandleCharInsert(v:char, bufnr('%')) if exists('##TextChangedP') - autocmd TextChangedP * call s:Autocmd('TextChangedP', +expand(''), {'lnum': line('.'), 'col': col('.'), 'pre': strpart(getline('.'), 0, col('.') - 1), 'changedtick': b:changedtick}) + autocmd TextChangedP * call s:Autocmd('TextChangedP', +expand(''), coc#util#change_info()) endif - autocmd TextChangedI * call s:Autocmd('TextChangedI', +expand(''), {'lnum': line('.'), 'col': col('.'), 'pre': strpart(getline('.'), 0, col('.') - 1), 'changedtick': b:changedtick}) - autocmd InsertLeave * call s:Autocmd('InsertLeave', +expand('')) + autocmd TextChangedI * call s:HandleTextChangedI(+expand('')) + autocmd InsertLeave * call s:HandleInsertLeave(+expand('')) autocmd InsertEnter * call s:Autocmd('InsertEnter', +expand('')) autocmd BufHidden * call s:Autocmd('BufHidden', +expand('')) autocmd BufEnter * call s:Autocmd('BufEnter', +expand('')) autocmd TextChanged * call s:Autocmd('TextChanged', +expand(''), getbufvar(+expand(''), 'changedtick')) - autocmd BufWritePost * call s:Autocmd('BufWritePost', +expand('')) + autocmd BufWritePost * call s:Autocmd('BufWritePost', +expand(''), getbufvar(+expand(''), 'changedtick')) autocmd CursorMoved * call s:Autocmd('CursorMoved', +expand(''), [line('.'), col('.')]) autocmd CursorMovedI * call s:Autocmd('CursorMovedI', +expand(''), [line('.'), col('.')]) - autocmd CursorHold * call s:Autocmd('CursorHold', +expand('')) - autocmd CursorHoldI * call s:Autocmd('CursorHoldI', +expand('')) + autocmd CursorHold * call s:Autocmd('CursorHold', +expand(''), [line('.'), col('.')]) + autocmd CursorHoldI * call s:Autocmd('CursorHoldI', +expand(''), [line('.'), col('.')]) autocmd BufNewFile,BufReadPost * call s:Autocmd('BufCreate', +expand('')) autocmd BufUnload * call s:Autocmd('BufUnload', +expand('')) - autocmd BufWritePre * call s:SyncAutocmd('BufWritePre', +expand('')) + autocmd BufWritePre * call s:SyncAutocmd('BufWritePre', +expand(''), bufname(+expand('')), getbufvar(+expand(''), 'changedtick')) autocmd FocusGained * if mode() !~# '^c' | call s:Autocmd('FocusGained') | endif autocmd FocusLost * call s:Autocmd('FocusLost') autocmd VimResized * call s:Autocmd('VimResized', &columns, &lines) - autocmd VimLeavePre * let g:coc_vim_leaving = 1 + autocmd VimLeavePre * call s:VimLeavePre() autocmd BufReadCmd,FileReadCmd,SourceCmd list://* call coc#list#setup(expand('')) autocmd BufWriteCmd __coc_refactor__* :call coc#rpc#notify('saveRefactor', [+expand('')]) - autocmd ColorScheme * call s:Hi() + autocmd ColorScheme * call s:Highlight() | call s:Autocmd('ColorScheme') augroup end if a:initialize == 0 call coc#rpc#request('attach', []) @@ -338,135 +440,197 @@ function! s:Enable(initialize) endif endfunction -function! s:Hi() abort - hi default CocErrorSign ctermfg=Red guifg=#ff0000 guibg=NONE - hi default CocWarningSign ctermfg=Brown guifg=#ff922b guibg=NONE - hi default CocInfoSign ctermfg=Yellow guifg=#fab005 guibg=NONE - hi default CocHintSign ctermfg=Blue guifg=#15aabf guibg=NONE +function! s:Highlight() abort hi default CocSelectedText ctermfg=Red guifg=#fb4934 guibg=NONE hi default CocCodeLens ctermfg=Gray guifg=#999999 guibg=NONE - hi default CocUnderline cterm=underline gui=underline + hi default CocUnderline term=underline cterm=underline gui=underline guisp=#ebdbb2 hi default CocBold term=bold cterm=bold gui=bold hi default CocItalic term=italic cterm=italic gui=italic - if s:is_vim || has('nvim-0.4.0') - hi default CocStrikeThrough cterm=strikethrough gui=strikethrough + hi default CocStrikeThrough term=strikethrough cterm=strikethrough gui=strikethrough + hi default CocMarkdownLink ctermfg=Blue guifg=#15aabf guibg=NONE + hi default CocDisabled guifg=#999999 ctermfg=gray + hi default CocSearch ctermfg=Blue guifg=#15aabf guibg=NONE + hi default CocLink term=underline cterm=underline gui=underline guisp=#15aabf + if coc#highlight#get_contrast('Normal', has('nvim') ? 'NormalFloat' : 'Pmenu') > 2.0 + exe 'hi default CocFloating '.coc#highlight#create_bg_command('Normal', &background ==# 'dark' ? -30 : 30) + exe 'hi default CocMenuSel '.coc#highlight#create_bg_command('CocFloating', &background ==# 'dark' ? -20 : 20) + exe 'hi default CocFloatThumb '.coc#highlight#create_bg_command('CocFloating', &background ==# 'dark' ? -40 : 40) + hi default link CocFloatSbar CocFloating else - hi default CocStrikeThrough guifg=#989898 ctermfg=gray + exe 'hi default link CocFloating '.(has('nvim') ? 'NormalFloat' : 'Pmenu') + if coc#highlight#get_contrast('CocFloating', 'PmenuSel') > 2.0 + exe 'hi default CocMenuSel '.coc#highlight#create_bg_command('CocFloating', &background ==# 'dark' ? -30 : 30) + else + exe 'hi default CocMenuSel '.coc#highlight#get_hl_command(synIDtrans(hlID('PmenuSel')), 'bg', '237', '#13354A') + endif + hi default link CocFloatThumb PmenuThumb + hi default link CocFloatSbar PmenuSbar endif - hi default CocMarkdownLink ctermfg=Blue guifg=#15aabf guibg=NONE - hi default link CocFadeOut Conceal - hi default link CocMarkdownCode markdownCode - hi default link CocMarkdownHeader markdownH1 - hi default link CocMenuSel PmenuSel - hi default link CocErrorFloat CocErrorSign - hi default link CocWarningFloat CocWarningSign - hi default link CocInfoFloat CocInfoSign - hi default link CocHintFloat CocHintSign - hi default link CocErrorHighlight CocUnderline - hi default link CocWarningHighlight CocUnderline - hi default link CocInfoHighlight CocUnderline - hi default link CocHintHighlight CocUnderline + if coc#highlight#get_contrast('Normal', 'CursorLine') < 1.3 + " Avoid color too close + exe 'hi default CocListLine '.coc#highlight#create_bg_command('Normal', &background ==# 'dark' ? -20 : 20) + else + hi default link CocListLine CursorLine + endif + hi default link CocFloatActive CocSearch + hi default link CocFadeOut Conceal + hi default link CocMarkdownCode markdownCode + hi default link CocMarkdownHeader markdownH1 hi default link CocDeprecatedHighlight CocStrikeThrough hi default link CocUnusedHighlight CocFadeOut - hi default link CocListMode ModeMsg - hi default link CocListPath Comment - hi default link CocHighlightText CursorColumn - hi default link CocHoverRange Search - hi default link CocCursorRange Search - hi default link CocHighlightRead CocHighlightText - hi default link CocHighlightWrite CocHighlightText + hi default link CocListSearch CocSearch + hi default link CocListMode ModeMsg + hi default link CocListPath Comment + hi default link CocHighlightText CursorColumn + hi default link CocHoverRange Search + hi default link CocCursorRange Search + hi default link CocLinkedEditing CocCursorRange + hi default link CocHighlightRead CocHighlightText + hi default link CocHighlightWrite CocHighlightText + " Notification + hi default CocNotificationProgress ctermfg=Blue guifg=#15aabf guibg=NONE + hi default link CocNotificationButton CocUnderline + hi default link CocNotificationError CocErrorFloat + hi default link CocNotificationWarning CocWarningFloat + hi default link CocNotificationInfo CocInfoFloat + " Snippet + hi default link CocSnippetVisual Visual " Tree view highlights - hi default link CocTreeTitle Title + hi default link CocTreeTitle Title hi default link CocTreeDescription Comment - hi default link CocTreeOpenClose CocBold - hi default link CocTreeSelected CursorLine - hi default link CocSelectedRange CocHighlightText + hi default link CocTreeOpenClose CocBold + hi default link CocTreeSelected CursorLine + hi default link CocSelectedRange CocHighlightText " Symbol highlights - hi default link CocSymbolDefault MoreMsg - hi default link CocSymbolFile Statement - hi default link CocSymbolModule Statement - hi default link CocSymbolNamespace Statement - hi default link CocSymbolPackage Statement - hi default link CocSymbolClass Statement - hi default link CocSymbolMethod Function - hi default link CocSymbolProperty Keyword - hi default link CocSymbolField CocSymbolDefault - hi default link CocSymbolConstructor Function - hi default link CocSymbolEnum CocSymbolDefault - hi default link CocSymbolInterface CocSymbolDefault - hi default link CocSymbolFunction Function - hi default link CocSymbolVariable CocSymbolDefault - hi default link CocSymbolConstant Constant - hi default link CocSymbolString String - hi default link CocSymbolNumber Number - hi default link CocSymbolBoolean Boolean - hi default link CocSymbolArray CocSymbolDefault - hi default link CocSymbolObject CocSymbolDefault - hi default link CocSymbolKey Keyword - hi default link CocSymbolNull Type - hi default link CocSymbolEnumMember CocSymbolDefault - hi default link CocSymbolStruct Keyword - hi default link CocSymbolEvent Keyword - hi default link CocSymbolOperator Operator - hi default link CocSymbolTypeParameter Operator - - if has('nvim') - hi default link CocFloating NormalFloat - else - hi default link CocFloating Pmenu - endif - if !exists('*sign_getdefined') || empty(sign_getdefined('CocCurrentLine')) - sign define CocCurrentLine linehl=CocMenuSel - endif - if !exists('*sign_getdefined') || empty(sign_getdefined('CocTreeSelected')) - sign define CocTreeSelected linehl=CocTreeSelected - endif + hi default link CocSymbolDefault MoreMsg + "Pum + hi default link CocPumSearch CocSearch + hi default link CocPumDetail Comment + hi default link CocPumMenu CocFloating + hi default link CocPumShortcut Comment + hi default link CocPumDeprecated CocStrikeThrough + hi default CocVirtualText ctermfg=12 guifg=#504945 + hi default link CocPumVirtualText CocVirtualText + hi default link CocInputBoxVirtualText CocVirtualText + hi default link CocFloatDividingLine CocVirtualText + if has('nvim-0.5.0') hi default CocCursorTransparent gui=strikethrough blend=100 endif - if has('nvim') - let names = ['Error', 'Warning', 'Info', 'Hint'] - for name in names - if !hlexists('Coc'.name.'VirtualText') - exe 'hi default link Coc'.name.'VirtualText Coc'.name.'Sign' - endif - endfor - endif - call s:AddAnsiGroups() + let sign_colors = { + \ 'Error': ['Red', '#ff0000'], + \ 'Warn': ['Brown', '#ff922b'], + \ 'Info': ['Yellow', '#fab005'], + \ 'Hint': ['Blue', '#15aabf'] + \ } + for name in ['Error', 'Warning', 'Info', 'Hint'] + let suffix = name ==# 'Warning' ? 'Warn' : name + if hlexists('DiagnosticUnderline'.suffix) + exe 'hi default link Coc'.name.'Highlight DiagnosticUnderline'.suffix + else + exe 'hi default link Coc'.name.'Highlight CocUnderline' + endif + if hlexists('DiagnosticSign'.suffix) + exe 'hi default link Coc'.name.'Sign DiagnosticSign'.suffix + else + exe 'hi default Coc'.name.'Sign ctermfg='.sign_colors[suffix][0].' guifg='.sign_colors[suffix][1] + endif + if hlexists('DiagnosticVirtualText'.suffix) + exe 'hi default link Coc'.name.'VirtualText DiagnosticVirtualText'.suffix + else + call s:CreateHighlight('Coc'.name.'VirtualText', 'Coc'.name.'Sign', 'Normal') + endif + if hlexists('Diagnostic'.suffix) + exe 'hi default link Coc'.name.'Float Diagnostic'.suffix + else + call s:CreateHighlight('Coc'.name.'Float', 'Coc'.name.'Sign', 'CocFloating') + endif + endfor - if get(g:, 'coc_default_semantic_highlight_groups', 0) == 1 - hi default link CocSem_namespace Identifier - hi default link CocSem_type Type - hi default link CocSem_class Structure - hi default link CocSem_enum Type - hi default link CocSem_interface Type - hi default link CocSem_struct Structure - hi default link CocSem_typeParameter Type - hi default link CocSem_parameter Identifier - hi default link CocSem_variable Identifier - hi default link CocSem_property Identifier - hi default link CocSem_enumMember Constant - hi default link CocSem_event Identifier - hi default link CocSem_function Function - hi default link CocSem_method Function - hi default link CocSem_macro Macro - hi default link CocSem_keyword Keyword - hi default link CocSem_modifier StorageClass - hi default link CocSem_comment Comment - hi default link CocSem_string String - hi default link CocSem_number Number - hi default link CocSem_regexp Normal - hi default link CocSem_operator Operator - endif -endfunction + call s:CreateHighlight('CocInlayHint', 'CocHintSign', 'SignColumn') + for name in ['Parameter', 'Type'] + exe 'hi default link CocInlayHint'.name.' CocInlayHint' + endfor -function! s:FormatFromSelected(type) - call CocActionAsync('formatSelected', a:type) -endfunction + call s:AddAnsiGroups() -function! s:CodeActionFromSelected(type) - call CocActionAsync('codeAction', a:type) + if get(g:, 'coc_default_semantic_highlight_groups', 1) + let hlMap = { + \ 'Namespace': ['@namespace', 'Include'], + \ 'Type': ['@type', 'Type'], + \ 'Class': ['@constructor', 'Special'], + \ 'Enum': ['@type', 'Type'], + \ 'Interface': ['@type', 'Type'], + \ 'Struct': ['@structure', 'Identifier'], + \ 'TypeParameter': ['@parameter', 'Identifier'], + \ 'Parameter': ['@parameter', 'Identifier'], + \ 'Variable': ['@variable', 'Identifier'], + \ 'Property': ['@property', 'Identifier'], + \ 'EnumMember': ['@property', 'Constant'], + \ 'Event': ['@keyword', 'Keyword'], + \ 'Function': ['@function', 'Function'], + \ 'Method': ['@method', 'Function'], + \ 'Macro': ['@constant.macro', 'Define'], + \ 'Keyword': ['@keyword', 'Keyword'], + \ 'Modifier': ['@storageclass', 'StorageClass'], + \ 'Comment': ['@comment', 'Comment'], + \ 'String': ['@string', 'String'], + \ 'Number': ['@number', 'Number'], + \ 'Boolean': ['@boolean', 'Boolean'], + \ 'Regexp': ['@string.regex', 'String'], + \ 'Operator': ['@operator', 'Operator'], + \ 'Decorator': ['@symbol', 'Identifier'], + \ 'Deprecated': ['@text.strike', 'CocDeprecatedHighlight'] + \ } + for [key, value] in items(hlMap) + let ts = get(value, 0, '') + let fallback = get(value, 1, '') + execute 'hi default link CocSem'.key.' '.(coc#highlight#valid(ts) ? ts : fallback) + endfor + endif + let symbolMap = { + \ 'Keyword': ['@keyword', 'Keyword'], + \ 'Namespace': ['@namespace', 'Include'], + \ 'Class': ['@constructor', 'Special'], + \ 'Method': ['@method', 'Function'], + \ 'Property': ['@property', 'Identifier'], + \ 'Text': ['@text', 'CocSymbolDefault'], + \ 'Unit': ['@unit', 'CocSymbolDefault'], + \ 'Value': ['@value', 'CocSymbolDefault'], + \ 'Snippet': ['@snippet', 'CocSymbolDefault'], + \ 'Color': ['@color', 'Float'], + \ 'Reference': ['@text.reference', 'Constant'], + \ 'Folder': ['@folder', 'CocSymbolDefault'], + \ 'File': ['@file', 'Statement'], + \ 'Module': ['@module', 'Statement'], + \ 'Package': ['@package', 'Statement'], + \ 'Field': ['@field', 'Identifier'], + \ 'Constructor': ['@constructor', 'Special'], + \ 'Enum': ['@type', 'CocSymbolDefault'], + \ 'Interface': ['@type', 'CocSymbolDefault'], + \ 'Function': ['@function', 'Function'], + \ 'Variable': ['@variable.builtin', 'Special'], + \ 'Constant': ['@constant', 'Constant'], + \ 'String': ['@string', 'String'], + \ 'Number': ['@number', 'Number'], + \ 'Boolean': ['@boolean', 'Boolean'], + \ 'Array': ['@array', 'CocSymbolDefault'], + \ 'Object': ['@object', 'CocSymbolDefault'], + \ 'Key': ['@key', 'Identifier'], + \ 'Null': ['@null', 'Type'], + \ 'EnumMember': ['@property', 'Identifier'], + \ 'Struct': ['@structure', 'Keyword'], + \ 'Event': ['@constant', 'Constant'], + \ 'Operator': ['@operator', 'Operator'], + \ 'TypeParameter': ['@parameter', 'Identifier'], + \ } + for [key, value] in items(symbolMap) + let hlGroup = coc#highlight#valid(value[0]) ? value[0] : get(value, 1, 'CocSymbolDefault') + if hlexists(hlGroup) + execute 'hi default CocSymbol'.key.' '.coc#highlight#get_hl_command(synIDtrans(hlID(hlGroup)), 'fg', '223', '#ebdbb2') + endif + endfor endfunction function! s:ShowInfo() @@ -481,8 +645,8 @@ function! s:ShowInfo() else let output = trim(system(node . ' --version')) let ms = matchlist(output, 'v\(\d\+\).\(\d\+\).\(\d\+\)') - if empty(ms) || str2nr(ms[1]) < 12 || (str2nr(ms[1]) == 12 && str2nr(ms[2]) < 12) - call add(lines, 'Error: Node version '.output.' < 12.12.0, please upgrade node.js') + if empty(ms) || str2nr(ms[1]) < 14 || (str2nr(ms[1]) == 14 && str2nr(ms[2]) < 14) + call add(lines, 'Error: Node version '.output.' < 14.14.0, please upgrade node.js') endif endif " check bundle @@ -504,6 +668,23 @@ function! s:ShowInfo() endif endfunction +function! s:CursorRangeFromSelected(type, ...) abort + " add range by operator + call coc#rpc#request('cursorsSelect', [bufnr('%'), 'operator', a:type]) +endfunction + +function! s:FormatFromSelected(type) + call CocActionAsync('formatSelected', a:type) +endfunction + +function! s:CodeActionFromSelected(type) + call CocActionAsync('codeAction', a:type) +endfunction + +function! s:CodeActionRefactorFromSelected(type) + call CocActionAsync('codeAction', a:type, ['refactor'] ,v:true) +endfunction + command! -nargs=0 CocOutline :call coc#rpc#notify('showOutline', []) command! -nargs=? CocDiagnostics :call s:OpenDiagnostics() command! -nargs=0 CocInfo :call s:ShowInfo() @@ -514,7 +695,7 @@ command! -nargs=0 CocConfig :call s:OpenConfig() command! -nargs=0 CocLocalConfig :call coc#rpc#notify('openLocalConfig', []) command! -nargs=0 CocRestart :call coc#rpc#restart() command! -nargs=0 CocStart :call coc#rpc#start_server() -command! -nargs=0 CocRebuild :call coc#util#rebuild() +command! -nargs=0 CocPrintErrors :call coc#rpc#show_errors() command! -nargs=1 -complete=custom,s:LoadedExtensions CocWatch :call coc#rpc#notify('watchExtension', []) command! -nargs=+ -complete=custom,s:SearchOptions CocSearch :call coc#rpc#notify('search', []) command! -nargs=+ -complete=custom,s:ExtensionList CocUninstall :call CocActionAsync('uninstallExtension', ) @@ -526,25 +707,58 @@ command! -nargs=? -complete=custom,coc#list#names CocPrev :call coc#rpc# command! -nargs=? -complete=custom,coc#list#names CocNext :call coc#rpc#notify('listNext', []) command! -nargs=? -complete=custom,coc#list#names CocFirst :call coc#rpc#notify('listFirst', []) command! -nargs=? -complete=custom,coc#list#names CocLast :call coc#rpc#notify('listLast', []) -command! -nargs=* -range CocAction :call coc#rpc#notify('codeActionRange', [, , ]) -command! -nargs=* -range CocFix :call coc#rpc#notify('codeActionRange', [, , 'quickfix']) command! -nargs=0 CocUpdate :call coc#util#update_extensions(1) command! -nargs=0 -bar CocUpdateSync :call coc#util#update_extensions() command! -nargs=* -bar -complete=custom,s:InstallOptions CocInstall :call coc#util#install_extension([]) call s:Enable(1) -call s:Hi() +augroup coc_dynamic_autocmd +augroup END +augroup coc_dynamic_content +augroup END +augroup coc_dynamic_option +augroup END + +" Default key-mappings for completion +if empty(mapcheck('', 'i')) + inoremap coc#pum#visible() ? coc#pum#next(1) : "\" +endif +if empty(mapcheck('', 'i')) + inoremap coc#pum#visible() ? coc#pum#prev(1) : "\" +endif +if empty(mapcheck('', 'i')) + inoremap coc#pum#visible() ? coc#pum#next(0) : "\" +endif +if empty(mapcheck('', 'i')) + inoremap coc#pum#visible() ? coc#pum#prev(0) : "\" +endif +if empty(mapcheck('', 'i')) + inoremap coc#pum#visible() ? coc#pum#cancel() : "\" +endif +if empty(mapcheck('', 'i')) + inoremap coc#pum#visible() ? coc#pum#confirm() : "\" +endif +if empty(mapcheck('', 'i')) + inoremap coc#pum#visible() ? coc#pum#scroll(1) : "\" +endif +if empty(mapcheck('', 'i')) + inoremap coc#pum#visible() ? coc#pum#scroll(0) : "\" +endif vnoremap (coc-range-select) :call CocActionAsync('rangeSelect', visualmode(), v:true) vnoremap (coc-range-select-backward) :call CocActionAsync('rangeSelect', visualmode(), v:false) -nnoremap (coc-range-select) :call CocActionAsync('rangeSelect', '', v:true) -nnoremap (coc-codelens-action) :call CocActionAsync('codeLensAction') -vnoremap (coc-format-selected) :call CocActionAsync('formatSelected', visualmode()) -vnoremap (coc-codeaction-selected) :call CocActionAsync('codeAction', visualmode()) -nnoremap (coc-codeaction-selected) :set operatorfunc=CodeActionFromSelectedg@ -nnoremap (coc-codeaction) :call CocActionAsync('codeAction', '') -nnoremap (coc-codeaction-line) :call CocActionAsync('codeAction', 'line') -nnoremap (coc-codeaction-cursor) :call CocActionAsync('codeAction', 'cursor') +nnoremap (coc-range-select) :call CocActionAsync('rangeSelect', '', v:true) +nnoremap (coc-codelens-action) :call CocActionAsync('codeLensAction') +vnoremap (coc-format-selected) :call CocActionAsync('formatSelected', visualmode()) +vnoremap (coc-codeaction-selected) :call CocActionAsync('codeAction', visualmode()) +vnoremap (coc-codeaction-refactor-selected) :call CocActionAsync('codeAction', visualmode(), ['refactor'], v:true) +nnoremap (coc-codeaction-selected) :set operatorfunc=CodeActionFromSelectedg@ +nnoremap (coc-codeaction-refactor-selected) :set operatorfunc=CodeActionRefactorFromSelectedg@ +nnoremap (coc-codeaction) :call CocActionAsync('codeAction', '') +nnoremap (coc-codeaction-line) :call CocActionAsync('codeAction', 'currline') +nnoremap (coc-codeaction-cursor) :call CocActionAsync('codeAction', 'cursor') +nnoremap (coc-codeaction-refactor) :call CocActionAsync('codeAction', 'cursor', ['refactor'], v:true) +nnoremap (coc-codeaction-source) :call CocActionAsync('codeAction', '', ['source'], v:true) nnoremap (coc-rename) :call CocActionAsync('rename') nnoremap (coc-format-selected) :set operatorfunc=FormatFromSelectedg@ nnoremap (coc-format) :call CocActionAsync('format') @@ -565,7 +779,6 @@ nnoremap (coc-float-hide) :call coc#float#c nnoremap (coc-float-jump) :call coc#float#jump() nnoremap (coc-command-repeat) :call CocAction('repeatCommand') nnoremap (coc-refactor) :call CocActionAsync('refactor') -inoremap CocRefresh =coc#_complete() nnoremap (coc-cursors-operator) :set operatorfunc=CursorRangeFromSelectedg@ vnoremap (coc-cursors-range) :call CocAction('cursorsSelect', bufnr('%'), 'range', visualmode()) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/autoload/coc/source/email.vim b/vim-config/plugins/coc.nvim/src/__tests__/autoload/coc/source/email.vim deleted file mode 100644 index de932ee7..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/autoload/coc/source/email.vim +++ /dev/null @@ -1,17 +0,0 @@ -" vim source for emails -function! coc#source#email#init() abort - return { - \ 'priority': 9, - \ 'shortcut': 'Email', - \ 'triggerCharacters': ['@'] - \} -endfunction - -function! coc#source#email#should_complete(opt) abort - return 1 -endfunction - -function! coc#source#email#complete(opt, cb) abort - let items = ['foo@gmail.com', 'bar@yahoo.com'] - call a:cb(items) -endfunction diff --git a/vim-config/plugins/coc.nvim/src/__tests__/client/changedFiles.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/client/changedFiles.test.ts deleted file mode 100644 index f2c78fd6..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/client/changedFiles.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -/* eslint-disable */ -import helper from '../helper' -// import * as assert from 'assert' -import fs from 'fs' -import * as lsclient from '../../language-client' -import * as path from 'path' -import { URI } from 'vscode-uri' -// import which from 'which' - -beforeAll(async () => { - await helper.setup() -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('Client integration', () => { - - it('should send file change notification', (done) => { - if (global.hasOwnProperty('__TEST__')) return done() - let serverModule = path.join(__dirname, './server/testFileWatcher.js') - let serverOptions: lsclient.ServerOptions = { - module: serverModule, - transport: lsclient.TransportKind.ipc - } - let clientOptions: lsclient.LanguageClientOptions = { - documentSelector: ['css'], - synchronize: {}, initializationOptions: {}, - middleware: { - } - } - let client = new lsclient.LanguageClient('css', 'Test Language Server', serverOptions, clientOptions) - let disposable = client.start() - - client.onReady().then(_ => { - setTimeout(async () => { - let file = path.join(__dirname, 'test.js') - fs.writeFileSync(file, '', 'utf8') - await helper.wait(300) - let res = await client.sendRequest('custom/received') - expect(res).toEqual({ - changes: [{ - uri: URI.file(file).toString(), - type: 1 - }] - }) - fs.unlinkSync(file) - disposable.dispose() - done() - }, 200) - }, e => { - disposable.dispose() - done(e) - }) - }) - -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/client/connection.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/client/connection.test.ts deleted file mode 100644 index de88dd8b..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/client/connection.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { Duplex } from 'stream' -import { ProgressType } from 'vscode-jsonrpc' -import { createProtocolConnection, DocumentSymbolParams, DocumentSymbolRequest, InitializeParams, InitializeRequest, InitializeResult, ProtocolConnection, StreamMessageReader, StreamMessageWriter } from 'vscode-languageserver-protocol/node' -import { SymbolInformation, SymbolKind } from 'vscode-languageserver-types' -import { NullLogger } from '../../language-client/client' - -class TestStream extends Duplex { - public _write(chunk: string, _encoding: string, done: () => void): void { - this.emit('data', chunk) - done() - } - - public _read(_size: number): void { - } -} - -let serverConnection: ProtocolConnection -let clientConnection: ProtocolConnection -let progressType: ProgressType = new ProgressType() - -beforeEach(() => { - const up = new TestStream() - const down = new TestStream() - const logger = new NullLogger() - serverConnection = createProtocolConnection(new StreamMessageReader(up), new StreamMessageWriter(down), logger) - clientConnection = createProtocolConnection(new StreamMessageReader(down), new StreamMessageWriter(up), logger) - serverConnection.listen() - clientConnection.listen() -}) - -afterEach(() => { - serverConnection.dispose() - clientConnection.dispose() -}) - -describe('Connection Tests', () => { - it('should ensure proper param passing', async () => { - let paramsCorrect = false - serverConnection.onRequest(InitializeRequest.type, params => { - paramsCorrect = !Array.isArray(params) - let result: InitializeResult = { - capabilities: { - } - } - return result - }) - - const init: InitializeParams = { - rootUri: 'file:///home/dirkb', - processId: 1, - capabilities: {}, - workspaceFolders: null, - } - await clientConnection.sendRequest(InitializeRequest.type, init) - expect(paramsCorrect).toBe(true) - }) - - it('should provid token', async () => { - serverConnection.onRequest(DocumentSymbolRequest.type, params => { - expect(params.partialResultToken).toBe('3b1db4c9-e011-489e-a9d1-0653e64707c2') - return [] - }) - - const params: DocumentSymbolParams = { - textDocument: { uri: 'file:///abc.txt' }, - partialResultToken: '3b1db4c9-e011-489e-a9d1-0653e64707c2' - } - await clientConnection.sendRequest(DocumentSymbolRequest.type, params) - }) - - it('should report result', async () => { - let result: SymbolInformation = { - name: 'abc', - kind: SymbolKind.Class, - location: { - uri: 'file:///abc.txt', - range: { start: { line: 0, character: 1 }, end: { line: 2, character: 3 } } - } - } - serverConnection.onRequest(DocumentSymbolRequest.type, params => { - expect(params.partialResultToken).toBe('3b1db4c9-e011-489e-a9d1-0653e64707c2') - serverConnection.sendProgress(progressType, params.partialResultToken, [result]) - return [] - }) - - const params: DocumentSymbolParams = { - textDocument: { uri: 'file:///abc.txt' }, - partialResultToken: '3b1db4c9-e011-489e-a9d1-0653e64707c2' - } - let progressOK = false - clientConnection.onProgress(progressType, '3b1db4c9-e011-489e-a9d1-0653e64707c2', values => { - progressOK = (values !== undefined && values.length === 1) - }) - await clientConnection.sendRequest(DocumentSymbolRequest.type, params) - expect(progressOK).toBeTruthy() - }) - - it('should provide workDoneToken', async () => { - serverConnection.onRequest(DocumentSymbolRequest.type, params => { - expect(params.workDoneToken).toBe('3b1db4c9-e011-489e-a9d1-0653e64707c2') - return [] - }) - - const params: DocumentSymbolParams = { - textDocument: { uri: 'file:///abc.txt' }, - workDoneToken: '3b1db4c9-e011-489e-a9d1-0653e64707c2' - } - await clientConnection.sendRequest(DocumentSymbolRequest.type, params) - }) - - it('should report work done progress', async () => { - serverConnection.onRequest(DocumentSymbolRequest.type, params => { - expect(params.workDoneToken).toBe('3b1db4c9-e011-489e-a9d1-0653e64707c2') - serverConnection.sendProgress(progressType, params.workDoneToken, { - kind: 'begin', - title: 'progress' - }) - serverConnection.sendProgress(progressType, params.workDoneToken, { - kind: 'report', - message: 'message' - }) - serverConnection.sendProgress(progressType, params.workDoneToken, { - kind: 'end', - message: 'message' - }) - return [] - }) - - const params: DocumentSymbolParams = { - textDocument: { uri: 'file:///abc.txt' }, - workDoneToken: '3b1db4c9-e011-489e-a9d1-0653e64707c2' - } - let result = '' - clientConnection.onProgress(progressType, '3b1db4c9-e011-489e-a9d1-0653e64707c2', value => { - result += value.kind - }) - await clientConnection.sendRequest(DocumentSymbolRequest.type, params) - expect(result).toBe('beginreportend') - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/client/converter.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/client/converter.test.ts deleted file mode 100644 index 564b8381..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/client/converter.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { CompletionTriggerKind, Position, TextDocumentItem, TextDocumentSaveReason } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { URI } from 'vscode-uri' -import * as cv from '../../language-client/utils/converter' - -describe('converter', () => { - - function createDocument(): TextDocument { - return TextDocument.create('file:///1', 'css', 1, '') - } - - it('should asLanguageIds', () => { - let selector = ['css', { language: 'javascript' }] - expect(cv.asLanguageIds(selector)).toEqual(['css', 'javascript']) - }) - - it('should convertToTextDocumentItem', () => { - let doc = createDocument() - expect(cv.convertToTextDocumentItem(doc).uri).toBe(doc.uri) - expect(TextDocumentItem.is(cv.convertToTextDocumentItem(doc))).toBe(true) - }) - - it('should asCloseTextDocumentParams', () => { - let doc = createDocument() - expect(cv.asCloseTextDocumentParams(doc).textDocument.uri).toBe(doc.uri) - }) - - it('should asChangeTextDocumentParams', () => { - let doc = createDocument() - expect(cv.asChangeTextDocumentParams(doc).textDocument.uri).toBe(doc.uri) - }) - - it('should asWillSaveTextDocumentParams', () => { - let res = cv.asWillSaveTextDocumentParams({ document: createDocument(), reason: TextDocumentSaveReason.Manual, waitUntil: () => { } }) - expect(res.textDocument).toBeDefined() - expect(res.reason).toBeDefined() - }) - - it('should asVersionedTextDocumentIdentifier', () => { - let res = cv.asVersionedTextDocumentIdentifier(createDocument()) - expect(res.uri).toBeDefined() - expect(res.version).toBeDefined() - }) - - it('should asSaveTextDocumentParams', () => { - let res = cv.asSaveTextDocumentParams(createDocument(), true) - expect(res.textDocument.uri).toBeDefined() - expect(res.text).toBeDefined() - }) - - it('should asUri', () => { - let uri = URI.file('/tmp/a') - expect(cv.asUri(uri)).toBe(uri.toString()) - }) - - it('should asCompletionParams', () => { - let params = cv.asCompletionParams(createDocument(), Position.create(0, 0), { triggerKind: CompletionTriggerKind.Invoked }) - expect(params.textDocument).toBeDefined() - expect(params.position).toBeDefined() - expect(params.context).toBeDefined() - }) - - it('should asTextDocumentPositionParams', () => { - let params = cv.asTextDocumentPositionParams(createDocument(), Position.create(0, 0)) - expect(params.textDocument).toBeDefined() - expect(params.position).toBeDefined() - }) - - it('should asTextDocumentIdentifier', () => { - let doc = cv.asTextDocumentIdentifier(createDocument()) - expect(doc.uri).toBeDefined() - }) - - it('should asReferenceParams', () => { - let params = cv.asReferenceParams(createDocument(), Position.create(0, 0), { includeDeclaration: false }) - expect(params.textDocument.uri).toBeDefined() - expect(params.position).toBeDefined() - }) - - it('should asDocumentSymbolParams', () => { - let doc = cv.asDocumentSymbolParams(createDocument()) - expect(doc.textDocument.uri).toBeDefined() - }) - - it('should asCodeLensParams', () => { - let doc = cv.asCodeLensParams(createDocument()) - expect(doc.textDocument.uri).toBeDefined() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/client/delayer.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/client/delayer.test.ts deleted file mode 100644 index 3f196976..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/client/delayer.test.ts +++ /dev/null @@ -1,154 +0,0 @@ -/* eslint-disable */ -import assert from 'assert' -import { Delayer } from '../../language-client/utils/async' - -test('Delayer', () => { - let count = 0 - let factory = () => { - return Promise.resolve(++count) - } - - let delayer = new Delayer(0) - let promises: Thenable[] = [] - - assert(!delayer.isTriggered()) - - promises.push(delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()) })) - assert(delayer.isTriggered()) - - promises.push(delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()) })) - assert(delayer.isTriggered()) - - promises.push(delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()) })) - assert(delayer.isTriggered()) - - return Promise.all(promises).then(() => { - assert(!delayer.isTriggered()) - }).finally(() => { - delayer.dispose() - }) -}) - -/* -test('Delayer - simple cancel', async () => { - let count = 0 - let factory = () => { - return Promise.resolve(++count) - } - - let delayer = new Delayer(10) - - assert(!delayer.isTriggered()) - - const p = delayer.trigger(factory).then(() => { - assert(false) - }, () => { - assert(true, 'yes, it was cancelled') - }) - assert(delayer.isTriggered()) - delayer.cancel() - assert(!delayer.isTriggered()) - await p -}) - -test('Delayer - cancel should cancel all calls to trigger', function() { - let count = 0 - let factory = () => { - return Promise.resolve(++count) - } - - let delayer = new Delayer(0) - let promises: Thenable[] = [] - - assert(!delayer.isTriggered()) - - promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled') })) - assert(delayer.isTriggered()) - - promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled') })) - assert(delayer.isTriggered()) - - promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled') })) - assert(delayer.isTriggered()) - - delayer.cancel() - - return Promise.all(promises).then(() => { - assert(!delayer.isTriggered()) - }) -}) - -test('Delayer - trigger, cancel, then trigger again', function() { - let count = 0 - let factory = () => { - return Promise.resolve(++count) - } - - let delayer = new Delayer(0) - let promises: Thenable[] = [] - - assert(!delayer.isTriggered()) - - const p = delayer.trigger(factory).then((result) => { - assert.equal(result, 1) - assert(!delayer.isTriggered()) - - promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled') })) - assert(delayer.isTriggered()) - - promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled') })) - assert(delayer.isTriggered()) - - delayer.cancel() - - const p = Promise.all(promises).then(() => { - promises = [] - - assert(!delayer.isTriggered()) - - promises.push(delayer.trigger(factory).then(() => { assert.equal(result, 1); assert(!delayer.isTriggered()) })) - assert(delayer.isTriggered()) - - promises.push(delayer.trigger(factory).then(() => { assert.equal(result, 1); assert(!delayer.isTriggered()) })) - assert(delayer.isTriggered()) - - const p = Promise.all(promises).then(() => { - assert(!delayer.isTriggered()) - }) - - assert(delayer.isTriggered()) - - return p - }) - - return p - }) - - assert(delayer.isTriggered()) - - return p -}) -*/ - -test('Delayer - last task should be the one getting called', function() { - let factoryFactory = (n: number) => () => { - return Promise.resolve(n) - } - - let delayer = new Delayer(0) - let promises: Thenable[] = [] - - assert(!delayer.isTriggered()) - - promises.push(delayer.trigger(factoryFactory(1)).then((n) => { assert.equal(n, 3) })) - promises.push(delayer.trigger(factoryFactory(2)).then((n) => { assert.equal(n, 3) })) - promises.push(delayer.trigger(factoryFactory(3)).then((n) => { assert.equal(n, 3) })) - - const p = Promise.all(promises).then(() => { - assert(!delayer.isTriggered()) - }) - - assert(delayer.isTriggered()) - - return p -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/client/features.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/client/features.test.ts deleted file mode 100644 index 8dc95dfb..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/client/features.test.ts +++ /dev/null @@ -1,1054 +0,0 @@ -import * as assert from 'assert' -import path from 'path' -import { URI } from 'vscode-uri' -import { LanguageClient, ServerOptions, TransportKind, Middleware, LanguageClientOptions } from '../../language-client/index' -import { CancellationTokenSource, Color, DocumentSelector, Position, Range, DefinitionRequest, Location, HoverRequest, Hover, CompletionRequest, CompletionTriggerKind, CompletionItem, SignatureHelpRequest, SignatureHelpTriggerKind, SignatureInformation, ParameterInformation, ReferencesRequest, DocumentHighlightRequest, DocumentHighlight, DocumentHighlightKind, CodeActionRequest, CodeAction, WorkDoneProgressBegin, WorkDoneProgressReport, WorkDoneProgressEnd, ProgressToken, DocumentFormattingRequest, TextEdit, DocumentRangeFormattingRequest, DocumentOnTypeFormattingRequest, RenameRequest, WorkspaceEdit, DocumentLinkRequest, DocumentLink, DocumentColorRequest, ColorInformation, ColorPresentation, DeclarationRequest, FoldingRangeRequest, FoldingRange, ImplementationRequest, SelectionRangeRequest, SelectionRange, TypeDefinitionRequest, ProtocolRequestType, CallHierarchyPrepareRequest, CallHierarchyItem, CallHierarchyIncomingCall, CallHierarchyOutgoingCall, SemanticTokensRegistrationType, LinkedEditingRangeRequest, WillCreateFilesRequest, DidCreateFilesNotification, WillRenameFilesRequest, DidRenameFilesNotification, WillDeleteFilesRequest, DidDeleteFilesNotification, TextDocumentEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import helper from '../helper' -import workspace from '../../workspace' - -describe('Client integration', () => { - let client!: LanguageClient - let middleware: Middleware - let uri!: string - let document!: TextDocument - let tokenSource!: CancellationTokenSource - const position: Position = Position.create(1, 1) - const range: Range = Range.create(1, 1, 1, 2) - - function rangeEqual(range: Range, sl: number, sc: number, el: number, ec: number): void { - assert.strictEqual(range.start.line, sl) - assert.strictEqual(range.start.character, sc) - assert.strictEqual(range.end.line, el) - assert.strictEqual(range.end.character, ec) - } - - function colorEqual(color: Color, red: number, green: number, blue: number, alpha: number): void { - assert.strictEqual(color.red, red) - assert.strictEqual(color.green, green) - assert.strictEqual(color.blue, blue) - assert.strictEqual(color.alpha, alpha) - } - - function uriEqual(actual: string, expected: string): void { - assert.strictEqual(actual, expected) - } - - function isArray(value: Array | undefined | null, clazz: any, length = 1): asserts value is Array { - assert.ok(Array.isArray(value), `value is array`) - assert.strictEqual(value!.length, length, 'value has given length') - if (clazz && typeof clazz.is === 'function') { - for (let item of value) { - assert.ok(clazz.is(item)) - } - } - } - - function isDefined(value: T | undefined | null): asserts value is Exclude { - if (value === undefined || value === null) { - throw new Error(`Value is null or undefined`) - } - } - - beforeAll(async () => { - await helper.setup() - workspace.registerTextDocumentContentProvider('lsptests', { - provideTextDocumentContent: (_uri: URI) => { - return [ - 'REM @ECHO OFF', - 'cd c:\\source', - 'REM This is the location of the files that you want to sort', - 'FOR %%f IN (*.doc *.txt) DO XCOPY c:\\source\\"%%f" c:\\text /m /y', - 'REM This moves any files with a .doc or', - 'REM .txt extension from c:\\source to c:\\text', - 'REM %%f is a variable', - 'FOR %%f IN (*.jpg *.png *.bmp) DO XCOPY C:\\source\\"%%f" c:\\images /m /y', - 'REM This moves any files with a .jpg, .png,', - 'REM or .bmp extension from c:\\source to c:\\images;;', - ].join('\n') - } - }) - - uri = URI.parse('lsptests://localhost/test.bat').toString() - let doc = await workspace.loadFile(uri.toString()) - document = doc.textDocument - tokenSource = new CancellationTokenSource() - const serverModule = path.join(__dirname, './server/testServer.js') - const serverOptions: ServerOptions = { - run: { module: serverModule, transport: TransportKind.ipc }, - debug: { module: serverModule, transport: TransportKind.ipc, options: { execArgv: ['--nolazy', '--inspect=6014'] } } - } - const documentSelector: DocumentSelector = [{ scheme: 'lsptests' }] - - middleware = {} - const clientOptions: LanguageClientOptions = { - documentSelector, synchronize: {}, initializationOptions: {}, middleware - } - - client = new LanguageClient('test svr', 'Test Language Server', serverOptions, clientOptions) - client.start() - await client.onReady() - }) - - afterAll(async () => { - await client.stop() - await helper.shutdown() - }) - - test('InitializeResult', () => { - let expected = { - capabilities: { - textDocumentSync: 1, - definitionProvider: true, - hoverProvider: true, - completionProvider: { resolveProvider: true, triggerCharacters: ['"', ':'] }, - signatureHelpProvider: { - triggerCharacters: [':'], - retriggerCharacters: [':'] - }, - referencesProvider: true, - documentHighlightProvider: true, - codeActionProvider: { - resolveProvider: true - }, - documentFormattingProvider: true, - documentRangeFormattingProvider: true, - documentOnTypeFormattingProvider: { - firstTriggerCharacter: ':' - }, - renameProvider: { - prepareProvider: true - }, - documentLinkProvider: { - resolveProvider: true - }, - colorProvider: true, - declarationProvider: true, - foldingRangeProvider: true, - implementationProvider: true, - selectionRangeProvider: true, - typeDefinitionProvider: true, - callHierarchyProvider: true, - semanticTokensProvider: { - legend: { - tokenTypes: [], - tokenModifiers: [] - }, - range: true, - full: { - delta: true - } - }, - workspace: { - fileOperations: { - didCreate: { filters: [{ scheme: 'file', pattern: { glob: '**/created-static/**{/,/*.txt}' } }] }, - didRename: { - filters: [ - { scheme: 'file', pattern: { glob: '**/renamed-static/**/', matches: 'folder' } }, - { scheme: 'file', pattern: { glob: '**/renamed-static/**/*.txt', matches: 'file' } } - ] - }, - didDelete: { filters: [{ scheme: 'file', pattern: { glob: '**/deleted-static/**{/,/*.txt}' } }] }, - willCreate: { filters: [{ scheme: 'file', pattern: { glob: '**/created-static/**{/,/*.txt}' } }] }, - willRename: { - filters: [ - { scheme: 'file', pattern: { glob: '**/renamed-static/**/', matches: 'folder' } }, - { scheme: 'file', pattern: { glob: '**/renamed-static/**/*.txt', matches: 'file' } } - ] - }, - willDelete: { filters: [ {scheme: 'file', pattern: { glob: '**/deleted-static/**{/,/*.txt}' } }] }, - }, - }, - linkedEditingRangeProvider: true - }, - customResults: { - hello: 'world' - } - } - assert.deepEqual(client.initializeResult, expected) - }) - - test('Goto Definition', async () => { - const provider = client.getFeature(DefinitionRequest.method).getProvider(document) - isDefined(provider) - const result = (await provider.provideDefinition(document, position, tokenSource.token)) as Location - assert.strictEqual(Location.is(result), true) - uriEqual(result.uri, uri) - rangeEqual(result.range, 0, 0, 0, 1) - let middlewareCalled = false - middleware.provideDefinition = (document, position, token, next) => { - middlewareCalled = true - return next(document, position, token) - } - await provider.provideDefinition(document, position, tokenSource.token) - middleware.provideDefinition = undefined - assert.strictEqual(middlewareCalled, true) - }) - - test('Hover', async () => { - const provider = client.getFeature(HoverRequest.method).getProvider(document) - isDefined(provider) - const result = await provider.provideHover(document, position, tokenSource.token) - assert.ok(Hover.is(result)) - assert.strictEqual((result.contents as any).kind, 'plaintext') - assert.strictEqual((result.contents as any).value, 'foo') - let middlewareCalled = false - middleware.provideHover = (document, position, token, next) => { - middlewareCalled = true - return next(document, position, token) - } - await provider.provideHover(document, position, tokenSource.token) - middleware.provideHover = undefined - assert.strictEqual(middlewareCalled, true) - }) - - test('Completion', async () => { - const provider = client.getFeature(CompletionRequest.method).getProvider(document) - isDefined(provider) - const result = (await provider.provideCompletionItems(document, position, tokenSource.token, { triggerKind: CompletionTriggerKind.Invoked, triggerCharacter: ':' })) as CompletionItem[] - - isArray(result, CompletionItem) - const item = result[0] - assert.strictEqual(item.label, 'item') - assert.strictEqual(item.insertText, 'text') - assert.strictEqual(item.detail, undefined) - isDefined(provider.resolveCompletionItem) - - const resolved = await provider.resolveCompletionItem(item, tokenSource.token) - isDefined(resolved) - assert.strictEqual(resolved.detail, 'detail') - - let middlewareCalled = 0 - middleware.provideCompletionItem = (document, position, context, token, next) => { - middlewareCalled++ - return next(document, position, context, token) - } - middleware.resolveCompletionItem = (item, token, next) => { - middlewareCalled++ - return next(item, token) - } - await provider.provideCompletionItems(document, position, tokenSource.token, { triggerKind: CompletionTriggerKind.Invoked, triggerCharacter: ':' }) - await provider.resolveCompletionItem(item, tokenSource.token) - middleware.provideCompletionItem = undefined - middleware.resolveCompletionItem = undefined - assert.strictEqual(middlewareCalled, 2) - }) - - test('SignatureHelpRequest', async () => { - const provider = client.getFeature(SignatureHelpRequest.method).getProvider(document) - isDefined(provider) - const result = await provider.provideSignatureHelp(document, position, tokenSource.token, - { - isRetrigger: false, - triggerKind: SignatureHelpTriggerKind.Invoked, - triggerCharacter: ':' - } - ) - - assert.strictEqual(result.activeSignature, 1) - assert.strictEqual(result.activeParameter, 1) - isArray(result.signatures, SignatureInformation) - - const signature = result.signatures[0] - assert.strictEqual(signature.label, 'label') - assert.strictEqual(signature.documentation, 'doc') - isArray(signature.parameters, ParameterInformation) - - const parameter = signature.parameters[0] - assert.strictEqual(parameter.label, 'label') - assert.strictEqual(parameter.documentation, 'doc') - - let middlewareCalled = false - middleware.provideSignatureHelp = (d, p, c, t, n) => { - middlewareCalled = true - return n(d, p, c, t) - } - await provider.provideSignatureHelp(document, position, tokenSource.token, - { - isRetrigger: false, - triggerKind: SignatureHelpTriggerKind.Invoked, - triggerCharacter: ':' - } - ) - middleware.provideSignatureHelp = undefined - assert.ok(middlewareCalled) - }) - - test('References', async () => { - const provider = client.getFeature(ReferencesRequest.method).getProvider(document) - isDefined(provider) - const result = await provider.provideReferences(document, position, { - includeDeclaration: true - }, tokenSource.token) - - isArray(result, Location, 2) - for (let i = 0; i < result.length; i++) { - const location = result[i] - rangeEqual(location.range, i, i, i, i) - assert.strictEqual(location.uri.toString(), document.uri.toString()) - } - - let middlewareCalled = false - middleware.provideReferences = (d, p, c, t, n) => { - middlewareCalled = true - return n(d, p, c, t) - } - await provider.provideReferences(document, position, { - includeDeclaration: true - }, tokenSource.token) - middleware.provideReferences = undefined - assert.ok(middlewareCalled) - }) - - test('Document Highlight', async () => { - const provider = client.getFeature(DocumentHighlightRequest.method).getProvider(document) - isDefined(provider) - const result = await provider.provideDocumentHighlights(document, position, tokenSource.token) - - isArray(result, DocumentHighlight, 1) - - const highlight = result[0] - assert.strictEqual(highlight.kind, DocumentHighlightKind.Read) - rangeEqual(highlight.range, 2, 2, 2, 2) - - let middlewareCalled = false - middleware.provideDocumentHighlights = (d, p, t, n) => { - middlewareCalled = true - return n(d, p, t) - } - await provider.provideDocumentHighlights(document, position, tokenSource.token) - middleware.provideDocumentHighlights = undefined - assert.ok(middlewareCalled) - }) - - test('Code Actions', async () => { - const provider = client.getFeature(CodeActionRequest.method).getProvider(document) - isDefined(provider) - const result = (await provider.provideCodeActions(document, range, { - diagnostics: [] - }, tokenSource.token)) as CodeAction[] - - isArray(result, CodeAction) - const action = result[0] - assert.strictEqual(action.title, 'title') - assert.strictEqual(action.command?.title, 'title') - assert.strictEqual(action.command?.command, 'id') - - const resolved = (await provider.resolveCodeAction(result[0], tokenSource.token)) - assert.strictEqual(resolved?.title, 'resolved') - - let middlewareCalled = false - middleware.provideCodeActions = (d, r, c, t, n) => { - middlewareCalled = true - return n(d, r, c, t) - } - - await provider.provideCodeActions(document, range, { diagnostics: [] }, tokenSource.token) - middleware.provideCodeActions = undefined - assert.ok(middlewareCalled) - - middlewareCalled = false - middleware.resolveCodeAction = (c, t, n) => { - middlewareCalled = true - return n(c, t) - } - - await provider.resolveCodeAction!(result[0], tokenSource.token) - middleware.resolveCodeAction = undefined - assert.ok(middlewareCalled) - }) - - test('Progress', async () => { - const progressToken = 'TEST-PROGRESS-TOKEN' - const middlewareEvents: Array = [] - let currentProgressResolver: (value: unknown) => void | undefined - - // Set up middleware that calls the current resolve function when it gets its 'end' progress event. - middleware.handleWorkDoneProgress = (token: ProgressToken, params, next) => { - if (token === progressToken) { - middlewareEvents.push(params) - if (params.kind === 'end') { - setImmediate(currentProgressResolver) - } - } - return next(token, params) - } - - // Trigger multiple sample progress events. - for (let i = 0; i < 2; i++) { - await new Promise((resolve, reject) => { - currentProgressResolver = resolve - client.sendRequest( - new ProtocolRequestType('testing/sendSampleProgress'), - {}, - tokenSource.token, - ).catch(reject) - }) - } - - middleware.handleWorkDoneProgress = undefined - - // Ensure all events were handled. - assert.deepStrictEqual( - middlewareEvents.map(p => p.kind), - ['begin', 'report', 'end', 'begin', 'report', 'end'], - ) - }) - - test('Document Formatting', async () => { - const provider = client.getFeature(DocumentFormattingRequest.method).getProvider(document) - isDefined(provider) - const result = await provider.provideDocumentFormattingEdits(document, { tabSize: 4, insertSpaces: false }, tokenSource.token) - - isArray(result, TextEdit) - const edit = result[0] - assert.strictEqual(edit.newText, 'insert') - rangeEqual(edit.range, 0, 0, 0, 0) - - let middlewareCalled = true - middleware.provideDocumentFormattingEdits = (d, c, t, n) => { - middlewareCalled = true - return n(d, c, t) - } - await provider.provideDocumentFormattingEdits(document, { tabSize: 4, insertSpaces: false }, tokenSource.token) - middleware.provideDocumentFormattingEdits = undefined - assert.ok(middlewareCalled) - }) - - test('Document Range Formatting', async () => { - const provider = client.getFeature(DocumentRangeFormattingRequest.method).getProvider(document) - isDefined(provider) - const result = await provider.provideDocumentRangeFormattingEdits(document, range, { tabSize: 4, insertSpaces: false }, tokenSource.token) - - isArray(result, TextEdit) - const edit = result[0] - assert.strictEqual(edit.newText, '') - rangeEqual(edit.range, 1, 1, 1, 2) - - let middlewareCalled = true - middleware.provideDocumentRangeFormattingEdits = (d, r, c, t, n) => { - middlewareCalled = true - return n(d, r, c, t) - } - await provider.provideDocumentRangeFormattingEdits(document, range, { tabSize: 4, insertSpaces: false }, tokenSource.token) - middleware.provideDocumentFormattingEdits = undefined - assert.ok(middlewareCalled) - }) - - test('Document on Type Formatting', async () => { - const provider = client.getFeature(DocumentOnTypeFormattingRequest.method).getProvider(document) - isDefined(provider) - const result = await provider.provideOnTypeFormattingEdits(document, position, 'a', { tabSize: 4, insertSpaces: false }, tokenSource.token) - - isArray(result, TextEdit) - const edit = result[0] - assert.strictEqual(edit.newText, 'replace') - rangeEqual(edit.range, 2, 2, 2, 3) - - let middlewareCalled = true - middleware.provideOnTypeFormattingEdits = (d, p, s, c, t, n) => { - middlewareCalled = true - return n(d, p, s, c, t) - } - await provider.provideOnTypeFormattingEdits(document, position, 'a', { tabSize: 4, insertSpaces: false }, tokenSource.token) - middleware.provideDocumentFormattingEdits = undefined - assert.ok(middlewareCalled) - }) - - test('Rename', async () => { - const provider = client.getFeature(RenameRequest.method).getProvider(document) - isDefined(provider) - isDefined(provider.prepareRename) - const prepareResult = await provider.prepareRename(document, position, tokenSource.token) as Range - - rangeEqual(prepareResult, 1, 1, 1, 2) - const renameResult = await provider.provideRenameEdits(document, position, 'newName', tokenSource.token) - assert.ok(WorkspaceEdit.is(renameResult)) - let middlewareCalled = 0 - middleware.prepareRename = (d, p, t, n) => { - middlewareCalled++ - return n(d, p, t) - } - await provider.prepareRename(document, position, tokenSource.token) - middleware.prepareRename = undefined - middleware.provideRenameEdits = (d, p, w, t, n) => { - middlewareCalled++ - return n(d, p, w, t) - } - await provider.provideRenameEdits(document, position, 'newName', tokenSource.token) - middleware.provideRenameEdits = undefined - assert.strictEqual(middlewareCalled, 2) - }) - - test('Document Link', async () => { - const provider = client.getFeature(DocumentLinkRequest.method).getProvider(document) - isDefined(provider) - const result = await provider.provideDocumentLinks(document, tokenSource.token) - - isArray(result, DocumentLink) - const documentLink = result[0] - rangeEqual(documentLink.range, 1, 1, 1, 2) - - let middlewareCalled = 0 - middleware.provideDocumentLinks = (d, t, n) => { - middlewareCalled++ - return n(d, t) - } - await provider.provideDocumentLinks(document, tokenSource.token) - middleware.provideDocumentLinks = undefined - - isDefined(provider.resolveDocumentLink) - const resolved = await provider.resolveDocumentLink(documentLink, tokenSource.token) - isDefined(resolved.target) - assert.strictEqual(resolved.target.toString(), URI.file('/target.txt').toString()) - - middleware.resolveDocumentLink = (i, t, n) => { - middlewareCalled++ - return n(i, t) - } - await provider.resolveDocumentLink(documentLink, tokenSource.token) - middleware.resolveDocumentLink = undefined - assert.strictEqual(middlewareCalled, 2) - }) - - test('Document Color', async () => { - const provider = client.getFeature(DocumentColorRequest.method).getProvider(document) - isDefined(provider) - const colors = await provider.provideDocumentColors(document, tokenSource.token) - - isArray(colors, ColorInformation) - const color = colors[0] - - rangeEqual(color.range, 1, 1, 1, 2) - colorEqual(color.color, 1, 1, 1, 1) - - let middlewareCalled = 0 - middleware.provideDocumentColors = (d, t, n) => { - middlewareCalled++ - return n(d, t) - } - await provider.provideDocumentColors(document, tokenSource.token) - middleware.provideDocumentColors = undefined - - const presentations = await provider.provideColorPresentations(color.color, { document, range }, tokenSource.token) - - isArray(presentations, ColorPresentation) - const presentation = presentations[0] - assert.strictEqual(presentation.label, 'label') - - middleware.provideColorPresentations = (c, x, t, n) => { - middlewareCalled++ - return n(c, x, t) - } - await provider.provideColorPresentations(color.color, { document, range }, tokenSource.token) - middleware.provideColorPresentations = undefined - assert.strictEqual(middlewareCalled, 2) - }) - - test('Goto Declaration', async () => { - const provider = client.getFeature(DeclarationRequest.method).getProvider(document) - isDefined(provider) - const result = (await provider.provideDeclaration(document, position, tokenSource.token)) as Location - - uriEqual(result.uri, uri) - rangeEqual(result.range, 1, 1, 1, 2) - - let middlewareCalled = false - middleware.provideDeclaration = (document, position, token, next) => { - middlewareCalled = true - return next(document, position, token) - } - await provider.provideDeclaration(document, position, tokenSource.token) - middleware.provideDeclaration = undefined - assert.strictEqual(middlewareCalled, true) - }) - - test('Folding Ranges', async () => { - const provider = client.getFeature(FoldingRangeRequest.method).getProvider(document) - isDefined(provider) - const result = (await provider.provideFoldingRanges(document, {}, tokenSource.token)) - - isArray(result, FoldingRange, 1) - const range = result[0] - assert.strictEqual(range.startLine, 1) - assert.strictEqual(range.endLine, 2) - let middlewareCalled = true - middleware.provideFoldingRanges = (d, c, t, n) => { - middlewareCalled = true - return n(d, c, t) - } - await provider.provideFoldingRanges(document, {}, tokenSource.token) - middleware.provideFoldingRanges = undefined - assert.ok(middlewareCalled) - }) - - test('Goto Implementation', async () => { - const provider = client.getFeature(ImplementationRequest.method).getProvider(document) - isDefined(provider) - const result = (await provider.provideImplementation(document, position, tokenSource.token)) as Location - - uriEqual(result.uri, uri) - rangeEqual(result.range, 2, 2, 3, 3) - - let middlewareCalled = false - middleware.provideImplementation = (document, position, token, next) => { - middlewareCalled = true - return next(document, position, token) - } - await provider.provideImplementation(document, position, tokenSource.token) - middleware.provideImplementation = undefined - assert.strictEqual(middlewareCalled, true) - }) - - test('Selection Range', async () => { - const provider = client.getFeature(SelectionRangeRequest.method).getProvider(document) - isDefined(provider) - const result = (await provider.provideSelectionRanges(document, [position], tokenSource.token)) - - isArray(result, SelectionRange, 1) - const range = result[0] - rangeEqual(range.range, 1, 2, 3, 4) - let middlewareCalled = false - middleware.provideSelectionRanges = (d, p, t, n) => { - middlewareCalled = true - return n(d, p, t) - } - await provider.provideSelectionRanges(document, [position], tokenSource.token) - middleware.provideSelectionRanges = undefined - assert.strictEqual(middlewareCalled, true) - }) - - test('Type Definition', async () => { - const provider = client.getFeature(TypeDefinitionRequest.method).getProvider(document) - isDefined(provider) - const result = (await provider.provideTypeDefinition(document, position, tokenSource.token)) as Location - - uriEqual(result.uri, uri) - rangeEqual(result.range, 2, 2, 3, 3) - - let middlewareCalled = false - middleware.provideTypeDefinition = (document, position, token, next) => { - middlewareCalled = true - return next(document, position, token) - } - await provider.provideTypeDefinition(document, position, tokenSource.token) - middleware.provideTypeDefinition = undefined - assert.strictEqual(middlewareCalled, true) - }) - - test('Call Hierarchy', async () => { - const provider = client.getFeature(CallHierarchyPrepareRequest.method).getProvider(document) - isDefined(provider) - const result = (await provider.prepareCallHierarchy(document, position, tokenSource.token)) as CallHierarchyItem[] - expect(result.length).toBe(1) - - let middlewareCalled = false - middleware.prepareCallHierarchy = (d, p, t, n) => { - middlewareCalled = true - return n(d, p, t) - } - await provider.prepareCallHierarchy(document, position, tokenSource.token) - middleware.prepareCallHierarchy = undefined - assert.strictEqual(middlewareCalled, true) - - const item = result[0] - const incoming = (await provider.provideCallHierarchyIncomingCalls(item, tokenSource.token)) as CallHierarchyIncomingCall[] - expect(incoming.length).toBe(1) - assert.deepEqual(incoming[0].from, item) - middlewareCalled = false - middleware.provideCallHierarchyIncomingCalls = (i, t, n) => { - middlewareCalled = true - return n(i, t) - } - await provider.provideCallHierarchyIncomingCalls(item, tokenSource.token) - middleware.provideCallHierarchyIncomingCalls = undefined - assert.strictEqual(middlewareCalled, true) - - const outgoing = (await provider.provideCallHierarchyOutgoingCalls(item, tokenSource.token)) as CallHierarchyOutgoingCall[] - expect(outgoing.length).toBe(1) - assert.deepEqual(outgoing[0].to, item) - middlewareCalled = false - middleware.provideCallHierarchyOutgoingCalls = (i, t, n) => { - middlewareCalled = true - return n(i, t) - } - await provider.provideCallHierarchyOutgoingCalls(item, tokenSource.token) - middleware.provideCallHierarchyOutgoingCalls = undefined - assert.strictEqual(middlewareCalled, true) - }) - - const referenceFileUri = URI.parse('/dummy-edit') - function ensureReferenceEdit(edits: WorkspaceEdit, type: string, expectedLines: string[]) { - // // Ensure the edits are as expected. - assert.strictEqual(edits.documentChanges?.length, 1) - const edit = edits.documentChanges[0] as TextDocumentEdit - assert.strictEqual(edit.edits.length, 1) - assert.strictEqual(edit.textDocument.uri, referenceFileUri.path) - assert.strictEqual(edit.edits[0].newText.trim(), `${type}:\n${expectedLines.join('\n')}`.trim()) - } - async function ensureNotificationReceived(type: string, params: any) { - const result = await client.sendRequest( - new ProtocolRequestType('testing/lastFileOperationRequest'), - {}, - tokenSource.token, - ) - assert.strictEqual(result.type, type) - assert.deepEqual(result.params, params) - assert.deepEqual(result, { - type, - params - }) - } - - const createFiles = [ - '/my/file.txt', - '/my/file.js', - '/my/folder/', - // Static registration for tests is [operation]-static and *.txt - '/my/created-static/file.txt', - '/my/created-static/file.js', - '/my/created-static/folder/', - // Dynamic registration for tests is [operation]-dynamic and *.js - '/my/created-dynamic/file.txt', - '/my/created-dynamic/file.js', - '/my/created-dynamic/folder/', - ].map(p => URI.file(p)) - - const renameFiles = [ - ['/my/file.txt', '/my-new/file.txt'], - ['/my/file.js', '/my-new/file.js'], - ['/my/folder/', '/my-new/folder/'], - // Static registration for tests is [operation]-static and *.txt - ['/my/renamed-static/file.txt', '/my-new/renamed-static/file.txt'], - ['/my/renamed-static/file.js', '/my-new/renamed-static/file.js'], - ['/my/renamed-static/folder/', '/my-new/renamed-static/folder/'], - // Dynamic registration for tests is [operation]-dynamic and *.js - ['/my/renamed-dynamic/file.txt', '/my-new/renamed-dynamic/file.txt'], - ['/my/renamed-dynamic/file.js', '/my-new/renamed-dynamic/file.js'], - ['/my/renamed-dynamic/folder/', '/my-new/renamed-dynamic/folder/'], - ].map(([o, n]) => ({ oldUri: URI.file(o), newUri: URI.file(n) })) - - const deleteFiles = [ - '/my/file.txt', - '/my/file.js', - '/my/folder/', - // Static registration for tests is [operation]-static and *.txt - '/my/deleted-static/file.txt', - '/my/deleted-static/file.js', - '/my/deleted-static/folder/', - // Dynamic registration for tests is [operation]-dynamic and *.js - '/my/deleted-dynamic/file.txt', - '/my/deleted-dynamic/file.js', - '/my/deleted-dynamic/folder/', - ].map(p => URI.file(p)) - - test('File Operations - Will Create Files', async () => { - const feature = client.getFeature(WillCreateFilesRequest.method) - isDefined(feature) - - const sendCreateRequest = () => new Promise(async (resolve, reject) => { - void feature.send({ files: createFiles, waitUntil: resolve }) - // If feature.send didn't call waitUntil synchronously then something went wrong. - reject(new Error('Feature unexpectedly did not call waitUntil synchronously')) - }) - - // Send the event and ensure the server responds with an edit referencing the - // correct files. - let edits = await sendCreateRequest() - ensureReferenceEdit( - edits, - 'WILL CREATE', - [ - 'file:///my/created-static/file.txt', - 'file:///my/created-static/folder/', - 'file:///my/created-dynamic/file.js', - 'file:///my/created-dynamic/folder/', - ], - ) - - // Add middleware that strips out any folders. - middleware.workspace = middleware.workspace || {} - middleware.workspace.willCreateFiles = (event, next) => next({ - ...event, - files: event.files.filter(f => !f.path.endsWith('/')), - }) - - // Ensure we get the same results minus the folders that the middleware removed. - edits = await sendCreateRequest() - ensureReferenceEdit( - edits, - 'WILL CREATE', - [ - 'file:///my/created-static/file.txt', - 'file:///my/created-dynamic/file.js', - ], - ) - - middleware.workspace.willCreateFiles = undefined - }) - - test('File Operations - Did Create Files', async () => { - const feature = client.getFeature(DidCreateFilesNotification.method) - isDefined(feature) - - // Send the event and ensure the server reports the notification was sent. - await feature.send({ files: createFiles }) - await ensureNotificationReceived( - 'create', - { - files: [ - { uri: 'file:///my/created-static/file.txt' }, - { uri: 'file:///my/created-static/folder/' }, - { uri: 'file:///my/created-dynamic/file.js' }, - { uri: 'file:///my/created-dynamic/folder/' }, - ], - }, - ) - - // Add middleware that strips out any folders. - middleware.workspace = middleware.workspace || {} - middleware.workspace.didCreateFiles = (event, next) => next({ - files: event.files.filter(f => !f.path.endsWith('/')), - }) - - // Ensure we get the same results minus the folders that the middleware removed. - await feature.send({ files: createFiles }) - await ensureNotificationReceived( - 'create', - { - files: [ - { uri: 'file:///my/created-static/file.txt' }, - { uri: 'file:///my/created-dynamic/file.js' }, - ], - }, - ) - - middleware.workspace.didCreateFiles = undefined - }) - - test('File Operations - Will Rename Files', async () => { - const feature = client.getFeature(WillRenameFilesRequest.method) - isDefined(feature) - - const sendRenameRequest = () => new Promise(async (resolve, reject) => { - void feature.send({ files: renameFiles, waitUntil: resolve }) - // If feature.send didn't call waitUntil synchronously then something went wrong. - reject(new Error('Feature unexpectedly did not call waitUntil synchronously')) - }) - - // Send the event and ensure the server responds with an edit referencing the - // correct files. - let edits = await sendRenameRequest() - ensureReferenceEdit( - edits, - 'WILL RENAME', - [ - 'file:///my/renamed-static/file.txt -> file:///my-new/renamed-static/file.txt', - 'file:///my/renamed-static/folder/ -> file:///my-new/renamed-static/folder/', - 'file:///my/renamed-dynamic/file.js -> file:///my-new/renamed-dynamic/file.js', - 'file:///my/renamed-dynamic/folder/ -> file:///my-new/renamed-dynamic/folder/', - ], - ) - - // Add middleware that strips out any folders. - middleware.workspace = middleware.workspace || {} - middleware.workspace.willRenameFiles = (event, next) => next({ - ...event, - files: event.files.filter(f => !f.oldUri.path.endsWith('/')), - }) - - // Ensure we get the same results minus the folders that the middleware removed. - edits = await sendRenameRequest() - ensureReferenceEdit( - edits, - 'WILL RENAME', - [ - 'file:///my/renamed-static/file.txt -> file:///my-new/renamed-static/file.txt', - 'file:///my/renamed-dynamic/file.js -> file:///my-new/renamed-dynamic/file.js', - ], - ) - - middleware.workspace.willRenameFiles = undefined - }) - - test('File Operations - Did Rename Files', async () => { - const feature = client.getFeature(DidRenameFilesNotification.method) - isDefined(feature) - - // Send the event and ensure the server reports the notification was sent. - await feature.send({ files: renameFiles }) - await ensureNotificationReceived( - 'rename', - { - files: [ - { oldUri: 'file:///my/renamed-static/file.txt', newUri: 'file:///my-new/renamed-static/file.txt' }, - { oldUri: 'file:///my/renamed-static/folder/', newUri: 'file:///my-new/renamed-static/folder/' }, - { oldUri: 'file:///my/renamed-dynamic/file.js', newUri: 'file:///my-new/renamed-dynamic/file.js' }, - { oldUri: 'file:///my/renamed-dynamic/folder/', newUri: 'file:///my-new/renamed-dynamic/folder/' }, - ], - }, - ) - - // Add middleware that strips out any folders. - middleware.workspace = middleware.workspace || {} - middleware.workspace.didRenameFiles = (event, next) => next({ - files: event.files.filter(f => !f.oldUri.path.endsWith('/')), - }) - - // Ensure we get the same results minus the folders that the middleware removed. - await feature.send({ files: renameFiles }) - await ensureNotificationReceived( - 'rename', - { - files: [ - { oldUri: 'file:///my/renamed-static/file.txt', newUri: 'file:///my-new/renamed-static/file.txt' }, - { oldUri: 'file:///my/renamed-dynamic/file.js', newUri: 'file:///my-new/renamed-dynamic/file.js' }, - ], - }, - ) - - middleware.workspace.didRenameFiles = undefined - }) - - test('File Operations - Will Delete Files', async () => { - const feature = client.getFeature(WillDeleteFilesRequest.method) - isDefined(feature) - - const sendDeleteRequest = () => new Promise(async (resolve, reject) => { - void feature.send({ files: deleteFiles, waitUntil: resolve }) - // If feature.send didn't call waitUntil synchronously then something went wrong. - reject(new Error('Feature unexpectedly did not call waitUntil synchronously')) - }) - - // Send the event and ensure the server responds with an edit referencing the - // correct files. - let edits = await sendDeleteRequest() - ensureReferenceEdit( - edits, - 'WILL DELETE', - [ - 'file:///my/deleted-static/file.txt', - 'file:///my/deleted-static/folder/', - 'file:///my/deleted-dynamic/file.js', - 'file:///my/deleted-dynamic/folder/', - ], - ) - - // Add middleware that strips out any folders. - middleware.workspace = middleware.workspace || {} - middleware.workspace.willDeleteFiles = (event, next) => next({ - ...event, - files: event.files.filter(f => !f.path.endsWith('/')), - }) - - // Ensure we get the same results minus the folders that the middleware removed. - edits = await sendDeleteRequest() - ensureReferenceEdit( - edits, - 'WILL DELETE', - [ - 'file:///my/deleted-static/file.txt', - 'file:///my/deleted-dynamic/file.js', - ], - ) - - middleware.workspace.willDeleteFiles = undefined - }) - - test('File Operations - Did Delete Files', async () => { - const feature = client.getFeature(DidDeleteFilesNotification.method) - isDefined(feature) - - // Send the event and ensure the server reports the notification was sent. - await feature.send({ files: deleteFiles }) - await ensureNotificationReceived( - 'delete', - { - files: [ - { uri: 'file:///my/deleted-static/file.txt' }, - { uri: 'file:///my/deleted-static/folder/' }, - { uri: 'file:///my/deleted-dynamic/file.js' }, - { uri: 'file:///my/deleted-dynamic/folder/' }, - ], - }, - ) - - // Add middleware that strips out any folders. - middleware.workspace = middleware.workspace || {} - middleware.workspace.didDeleteFiles = (event, next) => next({ - files: event.files.filter(f => !f.path.endsWith('/')), - }) - - // Ensure we get the same results minus the folders that the middleware removed. - await feature.send({ files: deleteFiles }) - await ensureNotificationReceived( - 'delete', - { - files: [ - { uri: 'file:///my/deleted-static/file.txt' }, - { uri: 'file:///my/deleted-dynamic/file.js' }, - ], - }, - ) - - middleware.workspace.didDeleteFiles = undefined - }) - - test('Semantic Tokens', async () => { - const provider = client.getFeature(SemanticTokensRegistrationType.method).getProvider(document) - const rangeProvider = provider?.range - isDefined(rangeProvider) - const rangeResult = await rangeProvider.provideDocumentRangeSemanticTokens(document, range, tokenSource.token) - assert.ok(rangeResult !== undefined) - - let middlewareCalled = false - middleware.provideDocumentRangeSemanticTokens = (d, r, t, n) => { - middlewareCalled = true - return n(d, r, t) - } - await rangeProvider.provideDocumentRangeSemanticTokens(document, range, tokenSource.token) - middleware.provideDocumentRangeSemanticTokens = undefined - assert.strictEqual(middlewareCalled, true) - - const fullProvider = provider?.full - isDefined(fullProvider) - const fullResult = await fullProvider.provideDocumentSemanticTokens(document, tokenSource.token) - assert.ok(fullResult !== undefined) - - middlewareCalled = false - middleware.provideDocumentSemanticTokens = (d, t, n) => { - middlewareCalled = true - return n(d, t) - } - await fullProvider.provideDocumentSemanticTokens(document, tokenSource.token) - middleware.provideDocumentSemanticTokens = undefined - assert.strictEqual(middlewareCalled, true) - - middlewareCalled = false - middleware.provideDocumentSemanticTokensEdits = (d, i, t, n) => { - middlewareCalled = true - return n(d, i, t) - } - await fullProvider.provideDocumentSemanticTokensEdits!(document, '2', tokenSource.token) - middleware.provideDocumentSemanticTokensEdits = undefined - assert.strictEqual(middlewareCalled, true) - }) - - test('Linked Editing Ranges', async () => { - const provider = client.getFeature(LinkedEditingRangeRequest.method).getProvider(document) - isDefined(provider) - const result = await provider.provideLinkedEditingRanges(document, position, tokenSource.token) - - isArray(result.ranges, Range, 1) - rangeEqual(result.ranges[0], 1, 1, 1, 1) - - let middlewareCalled = false - middleware.provideLinkedEditingRange = (document, position, token, next) => { - middlewareCalled = true - return next(document, position, token) - } - await provider.provideLinkedEditingRanges(document, position, tokenSource.token) - middleware.provideTypeDefinition = undefined - assert.strictEqual(middlewareCalled, true) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/client/integration.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/client/integration.test.ts deleted file mode 100644 index 168ff552..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/client/integration.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -/* eslint-disable */ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -'use strict' - -import helper from '../helper' -import * as assert from 'assert' -import * as lsclient from '../../language-client' -import path from 'path' - -beforeAll(async () => { - await helper.setup() -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -async function testLanguageServer(serverOptions: lsclient.ServerOptions): Promise { - let clientOptions: lsclient.LanguageClientOptions = { - documentSelector: ['css'], - synchronize: {}, - initializationOptions: {} - } - let client = new lsclient.LanguageClient('css', 'Test Language Server', serverOptions, clientOptions) - client.start() - await client.onReady() - expect(client.initializeResult).toBeDefined() -} - -describe('Client integration', () => { - - it('should initialize use IPC channel', (done) => { - let serverModule = path.join(__dirname, './server/testInitializeResult.js') - let serverOptions: lsclient.ServerOptions = { - run: { module: serverModule, transport: lsclient.TransportKind.ipc }, - debug: { module: serverModule, transport: lsclient.TransportKind.ipc, options: { execArgv: ['--nolazy', '--inspect=6014'] } } - } - let clientOptions: lsclient.LanguageClientOptions = { - documentSelector: ['css'], - synchronize: {}, initializationOptions: {}, - middleware: { - handleDiagnostics: (uri, diagnostics, next) => { - assert.equal(uri, "uri:/test.ts") - assert.ok(Array.isArray(diagnostics)) - assert.equal(diagnostics.length, 0) - next(uri, diagnostics) - disposable.dispose() - done() - } - } - } - let client = new lsclient.LanguageClient('css', 'Test Language Server', serverOptions, clientOptions) - let disposable = client.start() - - assert.equal(client.initializeResult, undefined) - - client.onReady().then(_ => { - try { - let expected = { - capabilities: { - textDocumentSync: 1, - completionProvider: { resolveProvider: true, triggerCharacters: ['"', ':'] }, - hoverProvider: true, - renameProvider: { - prepareProvider: true - } - }, - customResults: { - "hello": "world" - } - } - assert.deepEqual(client.initializeResult, expected) - } catch (e) { - disposable.dispose() - done(e) - } - }, e => { - disposable.dispose() - done(e) - }) - }) - - it('should initialize use stdio', async () => { - let serverModule = path.join(__dirname, './server/testInitializeResult.js') - let serverOptions: lsclient.ServerOptions = { - module: serverModule, - transport: lsclient.TransportKind.stdio - } - await testLanguageServer(serverOptions) - }) - - it('should initialize use pipe', async () => { - let serverModule = path.join(__dirname, './server/testInitializeResult.js') - let serverOptions: lsclient.ServerOptions = { - module: serverModule, - transport: lsclient.TransportKind.pipe - } - await testLanguageServer(serverOptions) - }) - - it('should initialize use socket', async () => { - let serverModule = path.join(__dirname, './server/testInitializeResult.js') - let serverOptions: lsclient.ServerOptions = { - module: serverModule, - transport: { - kind: lsclient.TransportKind.socket, - port: 8088 - } - } - await testLanguageServer(serverOptions) - }) - - it('should initialize as command', async () => { - let serverModule = path.join(__dirname, './server/testInitializeResult.js') - let serverOptions: lsclient.ServerOptions = { - command: 'node', - args: [serverModule, '--stdio'] - } - await testLanguageServer(serverOptions) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/client/server/testFileWatcher.js b/vim-config/plugins/coc.nvim/src/__tests__/client/server/testFileWatcher.js deleted file mode 100644 index 6ac96e6f..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/client/server/testFileWatcher.js +++ /dev/null @@ -1,35 +0,0 @@ -const languageserver = require('vscode-languageserver') -let connection = languageserver.createConnection() -let documents = new languageserver.TextDocuments() -documents.listen(connection) - -connection.onInitialize(() => { - let capabilities = { - textDocumentSync: documents.syncKind - } - return { capabilities } -}) - -connection.onInitialized(() => { - connection.sendRequest('client/registerCapability', { - registrations: [{ - id: 'didChangeWatchedFiles', - method: 'workspace/didChangeWatchedFiles', - registerOptions: { - watchers: [{ globPattern: "**" }] - } - }] - }) -}) - -let received - -connection.onNotification('workspace/didChangeWatchedFiles', params => { - received = params -}) - -connection.onRequest('custom/received', async () => { - return received -}) - -connection.listen() diff --git a/vim-config/plugins/coc.nvim/src/__tests__/client/server/testInitializeResult.js b/vim-config/plugins/coc.nvim/src/__tests__/client/server/testInitializeResult.js deleted file mode 100644 index 705561a6..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/client/server/testInitializeResult.js +++ /dev/null @@ -1,40 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -'use strict' -Object.defineProperty(exports, "__esModule", {value: true}) -const tslib_1 = require("tslib") -const assert = tslib_1.__importStar(require("assert")) -const vscode_languageserver_1 = require("vscode-languageserver") -let connection = vscode_languageserver_1.createConnection() - -let documents = new vscode_languageserver_1.TextDocuments() -documents.listen(connection) -connection.onInitialize((params) => { - assert.equal(params.capabilities.workspace.applyEdit, true) - assert.equal(params.capabilities.workspace.workspaceEdit.documentChanges, true) - assert.deepEqual(params.capabilities.workspace.workspaceEdit.resourceOperations, [vscode_languageserver_1.ResourceOperationKind.Create, vscode_languageserver_1.ResourceOperationKind.Rename, vscode_languageserver_1.ResourceOperationKind.Delete]) - assert.equal(params.capabilities.workspace.workspaceEdit.failureHandling, vscode_languageserver_1.FailureHandlingKind.TextOnlyTransactional) - assert.equal(params.capabilities.textDocument.completion.completionItem.deprecatedSupport, true) - assert.equal(params.capabilities.textDocument.completion.completionItem.preselectSupport, true) - assert.equal(params.capabilities.textDocument.signatureHelp.signatureInformation.parameterInformation.labelOffsetSupport, true) - assert.equal(params.capabilities.textDocument.rename.prepareSupport, true) - let valueSet = params.capabilities.textDocument.completion.completionItemKind.valueSet - assert.equal(valueSet[0], 1) - assert.equal(valueSet[valueSet.length - 1], vscode_languageserver_1.CompletionItemKind.TypeParameter) - let capabilities = { - textDocumentSync: documents.syncKind, - completionProvider: {resolveProvider: true, triggerCharacters: ['"', ':']}, - hoverProvider: true, - renameProvider: { - prepareProvider: true - } - } - return {capabilities, customResults: {"hello": "world"}} -}) -connection.onInitialized(() => { - connection.sendDiagnostics({uri: "uri:/test.ts", diagnostics: []}) -}) -// Listen on the connection -connection.listen() diff --git a/vim-config/plugins/coc.nvim/src/__tests__/client/server/testServer.js b/vim-config/plugins/coc.nvim/src/__tests__/client/server/testServer.js deleted file mode 100644 index 07e2edd8..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/client/server/testServer.js +++ /dev/null @@ -1,414 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -const assert = require('assert') -const {URI} = require('vscode-uri') -const { - createConnection, CompletionItemKind, ResourceOperationKind, FailureHandlingKind, - DiagnosticTag, CompletionItemTag, TextDocumentSyncKind, MarkupKind, SignatureInformation, ParameterInformation, - Location, Range, DocumentHighlight, DocumentHighlightKind, CodeAction, Command, TextEdit, Position, DocumentLink, - ColorInformation, Color, ColorPresentation, FoldingRange, SelectionRange, SymbolKind, ProtocolRequestType, WorkDoneProgress, - WorkDoneProgressCreateRequest} = require('vscode-languageserver') - -const { - DidCreateFilesNotification, - DidRenameFilesNotification, - DidDeleteFilesNotification, - WillCreateFilesRequest, WillRenameFilesRequest, WillDeleteFilesRequest -} = require('vscode-languageserver-protocol') - -let connection = createConnection() - -console.log = connection.console.log.bind(connection.console) -console.error = connection.console.error.bind(connection.console) - -connection.onInitialize(params => { - assert.equal((params.capabilities.workspace).applyEdit, true) - assert.equal(params.capabilities.workspace.workspaceEdit.documentChanges, true) - assert.equal(params.capabilities.workspace.workspaceEdit.failureHandling, FailureHandlingKind.TextOnlyTransactional) - assert.equal(params.capabilities.textDocument.completion.completionItem.deprecatedSupport, true) - assert.equal(params.capabilities.textDocument.completion.completionItem.preselectSupport, true) - assert.equal(params.capabilities.textDocument.completion.completionItem.tagSupport.valueSet.length, 1) - assert.equal(params.capabilities.textDocument.completion.completionItem.tagSupport.valueSet[0], CompletionItemTag.Deprecated) - assert.equal(params.capabilities.textDocument.signatureHelp.signatureInformation.parameterInformation.labelOffsetSupport, true) - // assert.equal(params.capabilities.textDocument.definition.linkSupport, true) - // assert.equal(params.capabilities.textDocument.declaration.linkSupport, true) - // assert.equal(params.capabilities.textDocument.implementation.linkSupport, true) - // assert.equal(params.capabilities.textDocument.typeDefinition.linkSupport, true) - assert.equal(params.capabilities.textDocument.rename.prepareSupport, true) - assert.equal(params.capabilities.textDocument.publishDiagnostics.relatedInformation, true) - assert.equal(params.capabilities.textDocument.publishDiagnostics.tagSupport.valueSet.length, 2) - assert.equal(params.capabilities.textDocument.publishDiagnostics.tagSupport.valueSet[0], DiagnosticTag.Unnecessary) - assert.equal(params.capabilities.textDocument.publishDiagnostics.tagSupport.valueSet[1], DiagnosticTag.Deprecated) - assert.equal(params.capabilities.textDocument.documentLink.tooltipSupport, true) - let valueSet = params.capabilities.textDocument.completion.completionItemKind.valueSet - assert.equal(valueSet[0], 1) - assert.equal(valueSet[valueSet.length - 1], CompletionItemKind.TypeParameter) - assert.deepEqual(params.capabilities.workspace.workspaceEdit.resourceOperations, [ResourceOperationKind.Create, ResourceOperationKind.Rename, ResourceOperationKind.Delete]) - assert.equal(params.capabilities.workspace.fileOperations.willCreate, true) - - let capabilities = { - textDocumentSync: TextDocumentSyncKind.Full, - definitionProvider: true, - hoverProvider: true, - completionProvider: {resolveProvider: true, triggerCharacters: ['"', ':']}, - signatureHelpProvider: { - triggerCharacters: [':'], - retriggerCharacters: [':'] - }, - referencesProvider: true, - documentHighlightProvider: true, - codeActionProvider: { - resolveProvider: true - }, - documentFormattingProvider: true, - documentRangeFormattingProvider: true, - documentOnTypeFormattingProvider: { - firstTriggerCharacter: ':' - }, - renameProvider: { - prepareProvider: true - }, - documentLinkProvider: { - resolveProvider: true - }, - colorProvider: true, - declarationProvider: true, - foldingRangeProvider: true, - implementationProvider: true, - selectionRangeProvider: true, - typeDefinitionProvider: true, - callHierarchyProvider: true, - semanticTokensProvider: { - legend: { - tokenTypes: [], - tokenModifiers: [] - }, - range: true, - full: { - delta: true - } - }, - workspace: { - fileOperations: { - // Static reg is folders + .txt files with operation kind in the path - didCreate: { - filters: [{ scheme: 'file', pattern: { glob: '**/created-static/**{/,/*.txt}' }}] - }, - didRename: { - filters: [ - { scheme: 'file', pattern: { glob: '**/renamed-static/**/', matches: 'folder' } }, - { scheme: 'file', pattern: { glob: '**/renamed-static/**/*.txt', matches: 'file' } } - ] - }, - didDelete: { - filters: [{ scheme: 'file', pattern: { glob: '**/deleted-static/**{/,/*.txt}' } }] - }, - willCreate: { - filters: [{ scheme: 'file', pattern: { glob: '**/created-static/**{/,/*.txt}' } }] - }, - willRename: { - filters: [ - { scheme: 'file', pattern: { glob: '**/renamed-static/**/', matches: 'folder' } }, - { scheme: 'file', pattern: { glob: '**/renamed-static/**/*.txt', matches: 'file' } } - ] - }, - willDelete: { - filters: [{ scheme: 'file', pattern: { glob: '**/deleted-static/**{/,/*.txt}' } }] - }, - }, - }, - linkedEditingRangeProvider: true - } - return {capabilities, customResults: {hello: 'world'}} -}) - -connection.onInitialized(() => { - // Dynamic reg is folders + .js files with operation kind in the path - connection.client.register(DidCreateFilesNotification.type, { - filters: [{ scheme: 'file', pattern: { glob: '**/created-dynamic/**{/,/*.js}' } }] - }); - connection.client.register(DidRenameFilesNotification.type, { - filters: [ - { scheme: 'file', pattern: { glob: '**/renamed-dynamic/**/', matches: 'folder' } }, - { scheme: 'file', pattern: { glob: '**/renamed-dynamic/**/*.js', matches: 'file' } } - ] - }); - connection.client.register(DidDeleteFilesNotification.type, { - filters: [{ scheme: 'file', pattern: { glob: '**/deleted-dynamic/**{/,/*.js}' } }] - }); - connection.client.register(WillCreateFilesRequest.type, { - filters: [{ scheme: 'file', pattern: { glob: '**/created-dynamic/**{/,/*.js}' } }] - }); - connection.client.register(WillRenameFilesRequest.type, { - filters: [ - { scheme: 'file', pattern: { glob: '**/renamed-dynamic/**/', matches: 'folder' } }, - { scheme: 'file', pattern: { glob: '**/renamed-dynamic/**/*.js', matches: 'file' } } - ] - }); - connection.client.register(WillDeleteFilesRequest.type, { - filters: [{ scheme: 'file', pattern: { glob: '**/deleted-dynamic/**{/,/*.js}' } }] - }); -}) - -connection.onDeclaration((params) => { - assert.equal(params.position.line, 1) - assert.equal(params.position.character, 1) - return {uri: params.textDocument.uri, range: {start: {line: 1, character: 1}, end: {line: 1, character: 2}}} -}) - -connection.onDefinition((params) => { - assert.equal(params.position.line, 1) - assert.equal(params.position.character, 1) - return {uri: params.textDocument.uri, range: {start: {line: 0, character: 0}, end: {line: 0, character: 1}}} -}) - -connection.onHover((_params) => { - return { - contents: { - kind: MarkupKind.PlainText, - value: 'foo' - } - } -}) - -connection.onCompletion((_params) => { - return [ - {label: 'item', insertText: 'text'} - ] -}) - -connection.onCompletionResolve((item) => { - item.detail = 'detail' - return item -}) - -connection.onSignatureHelp((_params) => { - const result = { - signatures: [ - SignatureInformation.create('label', 'doc', ParameterInformation.create('label', 'doc')) - ], - activeSignature: 1, - activeParameter: 1 - } - return result -}) - -connection.onReferences((params) => { - return [ - Location.create(params.textDocument.uri, Range.create(0, 0, 0, 0)), - Location.create(params.textDocument.uri, Range.create(1, 1, 1, 1)) - ] -}) - -connection.onDocumentHighlight((_params) => { - return [ - DocumentHighlight.create(Range.create(2, 2, 2, 2), DocumentHighlightKind.Read) - ] -}) - -connection.onCodeAction((_params) => { - return [ - CodeAction.create('title', Command.create('title', 'id')) - ] -}) - -connection.onCodeActionResolve((codeAction) => { - codeAction.title = 'resolved' - return codeAction -}) - -connection.onDocumentFormatting((_params) => { - return [ - TextEdit.insert(Position.create(0, 0), 'insert') - ] -}) - -connection.onDocumentRangeFormatting((_params) => { - return [ - TextEdit.del(Range.create(1, 1, 1, 2)) - ] -}) - -connection.onDocumentOnTypeFormatting((_params) => { - return [ - TextEdit.replace(Range.create(2, 2, 2, 3), 'replace') - ] -}) - -connection.onPrepareRename((_params) => { - return Range.create(1, 1, 1, 2) -}) - -connection.onRenameRequest((_params) => { - return {documentChanges: []} -}) - -connection.onDocumentLinks((_params) => { - return [ - DocumentLink.create(Range.create(1, 1, 1, 2)) - ] -}) - -connection.onDocumentLinkResolve((link) => { - link.target = URI.file('/target.txt').toString() - return link -}) - -connection.onDocumentColor((_params) => { - return [ - ColorInformation.create(Range.create(1, 1, 1, 2), Color.create(1, 1, 1, 1)) - ] -}) - -connection.onColorPresentation((_params) => { - return [ - ColorPresentation.create('label') - ] -}) - -connection.onFoldingRanges((_params) => { - return [ - FoldingRange.create(1, 2) - ] -}) - -connection.onImplementation((params) => { - assert.equal(params.position.line, 1) - assert.equal(params.position.character, 1) - return {uri: params.textDocument.uri, range: {start: {line: 2, character: 2}, end: {line: 3, character: 3}}} -}) - -connection.onSelectionRanges((_params) => { - return [ - SelectionRange.create(Range.create(1, 2, 3, 4)) - ] -}) - -let lastFileOperationRequest -connection.workspace.onDidCreateFiles((params) => {lastFileOperationRequest = {type: 'create', params}}) -connection.workspace.onDidRenameFiles((params) => {lastFileOperationRequest = {type: 'rename', params}}) -connection.workspace.onDidDeleteFiles((params) => {lastFileOperationRequest = {type: 'delete', params}}) - -connection.onRequest( - new ProtocolRequestType('testing/lastFileOperationRequest'), - () => { - return lastFileOperationRequest - }, -) - -connection.workspace.onWillCreateFiles((params) => { - const createdFilenames = params.files.map((f) => `${f.uri}`).join('\n') - return { - documentChanges: [{ - textDocument: {uri: '/dummy-edit', version: null}, - edits: [ - TextEdit.insert(Position.create(0, 0), `WILL CREATE:\n${createdFilenames}`), - ] - }], - } -}) - -connection.workspace.onWillRenameFiles((params) => { - const renamedFilenames = params.files.map((f) => `${f.oldUri} -> ${f.newUri}`).join('\n') - return { - documentChanges: [{ - textDocument: {uri: '/dummy-edit', version: null}, - edits: [ - TextEdit.insert(Position.create(0, 0), `WILL RENAME:\n${renamedFilenames}`), - ] - }], - } -}) - -connection.workspace.onWillDeleteFiles((params) => { - const deletedFilenames = params.files.map((f) => `${f.uri}`).join('\n') - return { - documentChanges: [{ - textDocument: {uri: '/dummy-edit', version: null}, - edits: [ - TextEdit.insert(Position.create(0, 0), `WILL DELETE:\n${deletedFilenames}`), - ] - }], - } -}) - -connection.onTypeDefinition((params) => { - assert.equal(params.position.line, 1) - assert.equal(params.position.character, 1) - return {uri: params.textDocument.uri, range: {start: {line: 2, character: 2}, end: {line: 3, character: 3}}} -}) - -connection.languages.callHierarchy.onPrepare((params) => { - return [ - { - kind: SymbolKind.Function, - name: 'name', - range: Range.create(1, 1, 1, 1), - selectionRange: Range.create(2, 2, 2, 2), - uri: params.textDocument.uri - } - ] -}) - -connection.languages.callHierarchy.onIncomingCalls((params) => { - return [ - { - from: params.item, - fromRanges: [Range.create(1, 1, 1, 1)] - } - ] -}) - -connection.languages.callHierarchy.onOutgoingCalls((params) => { - return [ - { - to: params.item, - fromRanges: [Range.create(1, 1, 1, 1)] - } - ] -}) - -connection.languages.semanticTokens.onRange(() => { - return { - resultId: '1', - data: [] - } -}) - -connection.languages.semanticTokens.on(() => { - return { - resultId: '2', - data: [] - } -}) - -connection.languages.semanticTokens.onDelta(() => { - return { - resultId: '3', - data: [] - } -}) - -connection.languages.onLinkedEditingRange(() => { - return { - ranges: [Range.create(1, 1, 1, 1)], - wordPattern: '\\w' - } -}) - -connection.onRequest( - new ProtocolRequestType('testing/sendSampleProgress'), - async (_, __) => { - const progressToken = 'TEST-PROGRESS-TOKEN' - await connection.sendRequest(WorkDoneProgressCreateRequest.type, {token: progressToken}) - connection.sendProgress(WorkDoneProgress.type, progressToken, {kind: 'begin', title: 'Test Progress'}) - connection.sendProgress(WorkDoneProgress.type, progressToken, {kind: 'report', percentage: 50, message: 'Halfway!'}) - connection.sendProgress(WorkDoneProgress.type, progressToken, {kind: 'end', message: 'Completed!'}) - }, -) - -// Listen on the connection -connection.listen() diff --git a/vim-config/plugins/coc.nvim/src/__tests__/coc-settings.json b/vim-config/plugins/coc.nvim/src/__tests__/coc-settings.json deleted file mode 100644 index 365a52e8..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/coc-settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "suggest.timeout": 5000, - "suggest.triggerCompletionWait": 10, - "tslint.enable": false -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/completion/basic.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/completion/basic.test.ts deleted file mode 100644 index 6ee1aa8c..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/completion/basic.test.ts +++ /dev/null @@ -1,446 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { ISource, SourceType, CompleteResult, CompleteOption } from '../../types' -import helper from '../helper' -import sources from '../../sources' -import { CancellationToken } from 'vscode-jsonrpc' - -let nvim: Neovim -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('completion', () => { - - it('should not show word of word source on empty input', async () => { - await nvim.setLine('foo bar') - await helper.wait(200) - await nvim.input('of') - let res = await helper.visible('foo', 'around') - expect(res).toBe(true) - await nvim.input('') - await helper.wait(200) - res = await helper.notVisible('foo') - expect(res).toBe(true) - }) - - it('should trigger on first letter insert', async () => { - await helper.edit() - await nvim.setLine('foo bar') - await helper.wait(30) - await nvim.input('of') - let res = await helper.visible('foo', 'around') - expect(res).toBe(true) - }) - - it('should trigger on force refresh', async () => { - await helper.edit() - await nvim.setLine('foo f') - await helper.wait(100) - await nvim.input('A') - await helper.wait(10) - await nvim.call('coc#start') - let res = await helper.visible('foo', 'around') - expect(res).toBe(true) - }) - - it('should filter and sort on increment search', async () => { - await helper.edit() - await nvim.setLine('forceDocumentSync format fallback') - await helper.wait(30) - await nvim.input('of') - await helper.waitPopup() - let items = await helper.getItems() - let l = items.length - await nvim.input('oa') - await helper.wait(100) - items = await helper.getItems() - expect(items.findIndex(o => o.word == 'fallback')).toBe(-1) - expect(items.length).toBeLessThan(l) - }) - - it('should filter on character remove by backspace', async () => { - await helper.edit() - await nvim.setLine('forceDocumentSync format fallback') - await helper.wait(30) - await nvim.input('ofa') - - await helper.waitPopup() - let items = await helper.getItems() - let words = items.map(o => o.word) - expect(words).toContain('fallback') - expect(words).toContain('format') - await nvim.input('') - await helper.wait(100) - items = await helper.getItems() - words = items.map(o => o.word) - expect(words).toEqual([]) - }) - - it('should not trigger on insert enter', async () => { - await helper.edit() - await nvim.setLine('foo bar') - await helper.wait(30) - await nvim.input('o') - let visible = await nvim.call('pumvisible') - expect(visible).toBe(0) - }) - - it('should filter on fast input', async () => { - await helper.edit() - await nvim.setLine('foo bar') - await helper.wait(60) - await nvim.input('oba') - await helper.waitPopup() - let items = await helper.getItems() - let item = items.find(o => o.word == 'foo') - expect(item).toBeFalsy() - expect(items[0].word).toBe('bar') - }) - - it('should fix start column', async () => { - await helper.edit() - let source: ISource = { - name: 'test', - priority: 10, - enable: true, - firstMatch: false, - sourceType: SourceType.Native, - triggerCharacters: [], - doComplete: async (): Promise => { - let result: CompleteResult = { - startcol: 0, - items: [{ word: 'foo.bar' }] - } - return Promise.resolve(result) - } - } - let disposable = sources.addSource(source) - await nvim.setLine('foo.') - await nvim.input('Ab') - await helper.waitPopup() - let val = await nvim.getVar('coc#_context') as any - expect(val.start).toBe(0) - disposable.dispose() - }) - - it('should stop completion when type none trigger character', async () => { - await helper.edit() - let source: ISource = { - name: 'test', - priority: 10, - enable: true, - firstMatch: false, - sourceType: SourceType.Native, - triggerCharacters: [], - doComplete: async (): Promise => { - let result: CompleteResult = { - items: [{ word: 'if(' }] - } - return Promise.resolve(result) - } - } - let disposable = sources.addSource(source) - await nvim.setLine('') - await nvim.input('iif') - await helper.waitPopup() - await nvim.input('(') - await helper.wait(300) - let res = await helper.pumvisible() - expect(res).toBe(true) - disposable.dispose() - }) - - it('should trigger on triggerCharacters', async () => { - await helper.edit() - let source: ISource = { - name: 'trigger', - priority: 10, - enable: true, - sourceType: SourceType.Native, - triggerCharacters: ['.'], - doComplete: async (): Promise => Promise.resolve({ - items: [{ word: 'foo' }] - }) - } - sources.addSource(source) - await nvim.input('i') - await helper.wait(30) - await nvim.input('.') - await helper.waitPopup() - sources.removeSource(source) - let res = await helper.visible('foo', 'trigger') - expect(res).toBe(true) - }) - - it('should should complete items without input', async () => { - await helper.edit() - let source: ISource = { - enable: true, - name: 'trigger', - priority: 10, - sourceType: SourceType.Native, - doComplete: async (): Promise => Promise.resolve({ - items: [{ word: 'foo' }, { word: 'bar' }] - }) - } - let disposable = sources.addSource(source) - await nvim.command('inoremap coc#refresh()') - await nvim.input('i') - await helper.wait(30) - await nvim.input('') - await helper.waitPopup() - let items = await helper.getItems() - expect(items.length).toBeGreaterThan(1) - disposable.dispose() - await helper.wait(300) - }) - - it('should show float window', async () => { - await helper.edit() - let source: ISource = { - name: 'float', - priority: 10, - enable: true, - sourceType: SourceType.Native, - doComplete: (): Promise => Promise.resolve({ - items: [{ word: 'foo', info: 'bar' }] - }) - } - sources.addSource(source) - await nvim.input('i') - await helper.wait(30) - await nvim.input('f') - await helper.waitPopup() - await nvim.eval('feedkeys("\\","in")') - await helper.wait(800) - let hasFloat = await nvim.call('coc#float#has_float') - expect(hasFloat).toBe(1) - sources.removeSource(source) - let res = await helper.visible('foo', 'float') - expect(res).toBe(true) - }) - - it('should trigger on triggerPatterns', async () => { - await helper.edit() - let source: ISource = { - name: 'pattern', - priority: 10, - enable: true, - sourceType: SourceType.Native, - triggerPatterns: [/\w+\.$/], - doComplete: async (): Promise => Promise.resolve({ - items: [{ word: 'foo' }] - }) - } - sources.addSource(source) - await nvim.input('i') - await helper.wait(10) - await nvim.input('.') - await helper.wait(30) - let pumvisible = await nvim.call('pumvisible') - expect(pumvisible).toBe(0) - await nvim.input('a') - await helper.wait(30) - await nvim.input('.') - await helper.waitPopup() - sources.removeSource(source) - let res = await helper.visible('foo', 'pattern') - expect(res).toBe(true) - }) - - it('should not trigger triggerOnly source', async () => { - await helper.edit() - await nvim.setLine('foo bar') - let source: ISource = { - name: 'pattern', - triggerOnly: true, - priority: 10, - enable: true, - sourceType: SourceType.Native, - triggerPatterns: [/^From:\s*/], - doComplete: async (): Promise => Promise.resolve({ - items: [{ word: 'foo' }] - }) - } - let disposable = sources.addSource(source) - await nvim.input('o') - await helper.wait(10) - await nvim.input('f') - await helper.wait(10) - let res = await helper.visible('foo', 'around') - expect(res).toBe(true) - let items = await helper.items() - expect(items.length).toBe(1) - disposable.dispose() - }) - - it('should not trigger when cursor moved', async () => { - await helper.edit() - let source: ISource = { - name: 'trigger', - priority: 10, - enable: true, - sourceType: SourceType.Native, - triggerCharacters: ['.'], - doComplete: async (): Promise => Promise.resolve({ - items: [{ word: 'foo' }] - }) - } - sources.addSource(source) - await nvim.setLine('.a') - await nvim.input('A') - await nvim.eval('feedkeys("\\")') - await helper.wait(10) - await nvim.eval('feedkeys("\\")') - await helper.wait(200) - let visible = await nvim.call('pumvisible') - expect(visible).toBe(0) - sources.removeSource(source) - }) - - it('should trigger when completion is not completed', async () => { - await helper.edit() - let token: CancellationToken - let source: ISource = { - name: 'completion', - priority: 10, - enable: true, - sourceType: SourceType.Native, - triggerCharacters: ['.'], - doComplete: async (opt, cancellationToken): Promise => { - if (opt.triggerCharacter != '.') { - token = cancellationToken - return new Promise((resolve, reject) => { - let timer = setTimeout(() => { - resolve({ items: [{ word: 'foo' }] }) - }, 200) - if (cancellationToken.isCancellationRequested) { - clearTimeout(timer) - reject(new Error('Cancelled')) - } - }) - } - return Promise.resolve({ - items: [{ word: 'bar' }] - }) - } - } - let disposable = sources.addSource(source) - await nvim.input('if') - await helper.wait(100) - await nvim.input('.') - await helper.visible('bar', 'completion') - expect(token.isCancellationRequested).toBe(true) - disposable.dispose() - }) - - it('should limit results for low priority source', async () => { - helper.updateConfiguration('suggest.lowPrioritySourceLimit', 2) - await nvim.setLine('filename filepath find filter findIndex') - await helper.wait(200) - await nvim.input('of') - await helper.waitPopup() - let items = await helper.getItems() - items = items.filter(o => o.menu == '[A]') - expect(items.length).toBe(2) - }) - - it('should limit result for high priority source', async () => { - helper.updateConfiguration('suggest.highPrioritySourceLimit', 2) - await helper.edit() - let source: ISource = { - name: 'high', - priority: 90, - enable: true, - sourceType: SourceType.Native, - triggerCharacters: ['.'], - doComplete: async (): Promise => Promise.resolve({ - items: ['filename', 'filepath', 'filter', 'file'].map(key => ({ word: key })) - }) - } - let disposable = sources.addSource(source) - await nvim.input('i') - await helper.wait(30) - await nvim.input('.') - await helper.waitPopup() - let items = await helper.getItems() - expect(items.length).toBeGreaterThan(1) - disposable.dispose() - }) - - it('should truncate label of complete items', async () => { - helper.updateConfiguration('suggest.labelMaxLength', 10) - await helper.edit() - let source: ISource = { - name: 'high', - priority: 90, - enable: true, - sourceType: SourceType.Native, - triggerCharacters: ['.'], - doComplete: async (): Promise => Promise.resolve({ - items: ['a', 'b', 'c', 'd'].map(key => ({ word: key.repeat(20) })) - }) - } - let disposable = sources.addSource(source) - await nvim.input('i') - await helper.wait(30) - await nvim.input('.') - await helper.waitPopup() - let items = await helper.getItems() - for (let item of items) { - expect(item.abbr.length).toBeLessThanOrEqual(10) - } - disposable.dispose() - }) - - it('should delete previous items if complete item is null', async () => { - await helper.edit() - let source1: ISource = { - name: 'source1', - priority: 90, - enable: true, - sourceType: SourceType.Native, - triggerCharacters: ['.'], - doComplete: async (): Promise => Promise.resolve({ - items: [ {word: 'foo', dup: 1} ] - }) - } - let source2: ISource = { - name: 'source2', - priority: 90, - enable: true, - sourceType: SourceType.Native, - triggerCharacters: ['.'], - doComplete: async (opt: CompleteOption): Promise => { - let result: CompleteResult = opt.input == 'foo' ? null : { - items: [{ word: 'foo', dup: 1 }], isIncomplete: true - } - return Promise.resolve(result) - } - } - let disposable1 = sources.addSource(source1) - let disposable2 = sources.addSource(source2) - await nvim.input('i') - await helper.wait(30) - await nvim.input('.f') - await helper.waitPopup() - let items = await helper.getItems() - expect(items.length).toEqual(2) - await nvim.input('oo') - await helper.waitPopup() - items = await helper.getItems() - expect(items.length).toEqual(1) - expect(items[0].word).toBe('foo') - disposable1.dispose() - disposable2.dispose() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/completion/float.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/completion/float.test.ts deleted file mode 100644 index 049bdcae..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/completion/float.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import sources from '../../sources' -import { CompleteResult, ISource, SourceType } from '../../types' -import helper from '../helper' - -let nvim: Neovim -let source: ISource -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - source = { - name: 'float', - priority: 10, - enable: true, - sourceType: SourceType.Native, - doComplete: (): Promise => Promise.resolve({ - items: [{ - word: 'foo', - info: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' - }, { - word: 'foot', - info: 'foot' - }, { - word: 'football', - }] - }) - } - sources.addSource(source) -}) - -afterAll(async () => { - sources.removeSource(source) - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('completion float', () => { - - it('should not show float window when disabled', async () => { - helper.updateConfiguration('suggest.floatEnable', false) - await helper.edit() - await nvim.input('if') - await helper.visible('foo', 'float') - helper.updateConfiguration('suggest.floatEnable', true) - let hasFloat = await nvim.call('coc#float#has_float') - expect(hasFloat).toBe(0) - }) - - it('should cancel float window', async () => { - await helper.edit() - await nvim.input('if') - await helper.visible('foo', 'float') - let items = await helper.getItems() - expect(items[0].word).toBe('foo') - expect(items[0].info.length > 0).toBeTruthy() - await nvim.input('') - await helper.wait(500) - await nvim.input('') - await helper.wait(100) - let hasFloat = await nvim.call('coc#float#has_float') - expect(hasFloat).toBe(0) - }) - - it('should adjust float window position', async () => { - await helper.edit() - await nvim.setLine(' '.repeat(70)) - await nvim.input('Af') - await helper.visible('foo', 'float') - await nvim.input('') - await helper.wait(300) - let floatWin = await helper.getFloat() - let config = await floatWin.getConfig() - expect(config.col + config.width).toBeLessThan(180) - }) - - it('should redraw float window on item change', async () => { - await helper.edit() - await nvim.setLine(' '.repeat(70)) - await nvim.input('Af') - await helper.visible('foo', 'float') - await nvim.input('') - await helper.wait(50) - await nvim.input('') - await helper.wait(300) - let floatWin = await helper.getFloat() - let buf = await floatWin.buffer - let lines = await buf.lines - expect(lines.length).toBeGreaterThan(0) - expect(lines[0]).toMatch('foot') - }) - - it('should hide float window when item info is empty', async () => { - await helper.edit() - await nvim.setLine(' '.repeat(70)) - await nvim.input('Af') - await helper.visible('foo', 'float') - await nvim.input('') - await helper.wait(10) - await nvim.input('') - await helper.wait(10) - await nvim.input('') - await helper.wait(100) - let hasFloat = await nvim.call('coc#float#has_float') - expect(hasFloat).toBe(0) - }) - - it('should hide float window after completion', async () => { - await helper.edit() - await nvim.setLine(' '.repeat(70)) - await nvim.input('Af') - await helper.visible('foo', 'float') - await nvim.input('') - await helper.wait(100) - await nvim.input('') - await helper.wait(30) - let hasFloat = await nvim.call('coc#float#has_float') - expect(hasFloat).toBe(0) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/completion/match.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/completion/match.test.ts deleted file mode 100644 index 91c7083d..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/completion/match.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { matchScore } from '../../completion/match' -import { getCharCodes } from '../../util/fuzzy' - -function score(word: string, input: string): number { - return matchScore(word, getCharCodes(input)) -} - -describe('matchScore', () => { - - it('should match score for last letter', () => { - expect(score('#!3', '3')).toBe(1) - }) - - it('should match first letter', () => { - expect(score('abc', 'a')).toBe(5) - expect(score('Abc', 'a')).toBe(2.5) - expect(score('__abc', 'a')).toBe(2.5) - expect(score('$Abc', 'a')).toBe(2) - expect(score('$Abc', 'A')).toBe(2.5) - expect(score('$Abc', '$A')).toBe(6) - expect(score('$Abc', '$a')).toBe(5.5) - expect(score('foo_bar', 'b')).toBe(2.5) - expect(score('foo_Bar', 'b')).toBe(2) - expect(score('_foo_Bar', 'b')).toBe(0.5) - expect(score('_foo_Bar', 'f')).toBe(2.5) - expect(score('bar', 'a')).toBe(1) - expect(score('fooBar', 'B')).toBe(2.5) - expect(score('fooBar', 'b')).toBe(2) - }) - - it('should match follow letters', () => { - expect(score('abc', 'ab')).toBe(6) - expect(score('adB', 'ab')).toBe(5.75) - expect(score('adb', 'ab')).toBe(5.1) - expect(score('adCB', 'ab')).toBe(5.05) - expect(score('a_b_c', 'ab')).toBe(6) - expect(score('FooBar', 'fb')).toBe(3.25) - expect(score('FBar', 'fb')).toBe(3) - expect(score('FooBar', 'FB')).toBe(6) - expect(score('FBar', 'FB')).toBe(6) - expect(score('a__b', 'a__b')).toBe(8) - expect(score('aBc', 'ab')).toBe(5.5) - expect(score('a_B_c', 'ab')).toBe(5.75) - expect(score('abc', 'abc')).toBe(7) - expect(score('abc', 'aC')).toBe(0) - expect(score('abc', 'ac')).toBe(5.1) - expect(score('abC', 'ac')).toBe(5.75) - expect(score('abC', 'aC')).toBe(6) - }) - - it('should only allow search once', () => { - expect(score('foobar', 'fbr')).toBe(0) - expect(score('foobaRow', 'fbr')).toBe(5.85) - expect(score('foobaRow', 'fbR')).toBe(6.1) - expect(score('foobar', 'fa')).toBe(5.1) - }) - - it('should have higher score for strict match', () => { - expect(score('language-client-protocol', 'lct')).toBe(6.1) - expect(score('language-client-types', 'lct')).toBe(7) - }) - - it('should find highest score', () => { - expect(score('ArrayRotateTail', 'art')).toBe(4) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/completion/sources.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/completion/sources.test.ts deleted file mode 100644 index 478e24dc..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/completion/sources.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import helper from '../helper' -import { ISource, SourceType, CompleteResult } from '../../types' -import sources from '../../sources' - -let nvim: Neovim -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('native sources', () => { - - it('should works for around source', async () => { - await helper.createDocument() - await nvim.setLine('foo ') - await helper.wait(100) - let { mode } = await nvim.mode - expect(mode).toBe('n') - await nvim.input('Af') - let res = await helper.visible('foo', 'around') - expect(res).toBe(true) - await nvim.input('') - }) - - it('should works for buffer source', async () => { - await nvim.command('set hidden') - await helper.createDocument() - await helper.createDocument() - await nvim.setLine('other') - await nvim.command('bp') - await helper.wait(300) - let { mode } = await nvim.mode - expect(mode).toBe('n') - await nvim.input('io') - let res = await helper.visible('other', 'buffer') - expect(res).toBe(true) - }) - - it('should works for file source', async () => { - await helper.edit() - await nvim.input('i/') - await helper.waitPopup() - let items = await helper.getItems() - expect(items.length).toBeGreaterThan(0) - let res = await helper.visible(items[0].word, 'file') - expect(res).toBe(true) - await nvim.input('') - await nvim.input('o./') - await helper.waitPopup() - items = await helper.getItems() - let item = items.find(o => o.word == 'vimrc') - expect(item).toBeTruthy() - }) - - it('should works for file source with other source use same triggerCharacter', async () => { - await helper.edit() - let source: ISource = { - name: 'test', - priority: 50, - enable: true, - firstMatch: false, - sourceType: SourceType.Native, - triggerCharacters: ['.', '/'], - doComplete: async (): Promise => { - let result: CompleteResult = { - items: [{ word: 'foo' }] - } - return Promise.resolve(result) - } - } - let disposable = sources.addSource(source) - await nvim.input('i.') - await helper.waitPopup() - let items = await helper.getItems() - expect(items.length).toBe(1) - await nvim.input('/') - await helper.waitPopup() - items = await helper.getItems() - expect(items.length).toBeGreaterThan(1) - expect(items[0].word).toBe('foo') - disposable.dispose() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/completion/util.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/completion/util.test.ts deleted file mode 100644 index 477f7cdf..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/completion/util.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { CompletionItemKind, TextEdit, Position } from 'vscode-languageserver-types' -import { getStartColumn, getKindString } from '../../sources/source-language' - -describe('getKindString()', () => { - it('should get kind text', async () => { - let map = new Map() - map.set(CompletionItemKind.Enum, 'E') - let res = getKindString(CompletionItemKind.Enum, map, '') - expect(res).toBe('E') - }) - - it('should get default value', async () => { - let map = new Map() - let res = getKindString(CompletionItemKind.Enum, map, 'D') - expect(res).toBe('D') - }) -}) - -describe('getStartColumn()', () => { - it('should get start col', async () => { - expect(getStartColumn('', [{ label: 'foo' }])).toBe(null) - expect(getStartColumn('', [ - { label: 'foo', textEdit: TextEdit.insert(Position.create(0, 0), 'a') }, - { label: 'bar' }])).toBe(null) - expect(getStartColumn('foo', [ - { label: 'foo', textEdit: TextEdit.insert(Position.create(0, 0), 'a') }, - { label: 'bar', textEdit: TextEdit.insert(Position.create(0, 1), 'b') }])).toBe(null) - expect(getStartColumn('foo', [ - { label: 'foo', textEdit: TextEdit.insert(Position.create(0, 2), 'a') }, - { label: 'bar', textEdit: TextEdit.insert(Position.create(0, 2), 'b') }])).toBe(2) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/extensions/global/index.js b/vim-config/plugins/coc.nvim/src/__tests__/extensions/global/index.js deleted file mode 100644 index e48cb515..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/extensions/global/index.js +++ /dev/null @@ -1,7 +0,0 @@ -exports.activate = async context => { - return { - getContext: () => { - return context - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/extensions/global/package.json b/vim-config/plugins/coc.nvim/src/__tests__/extensions/global/package.json deleted file mode 100644 index 784d43bd..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/extensions/global/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "global", - "version": "1.0.0", - "engines": { - "coc": "^0.0.46" - } -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/extensions/package.json b/vim-config/plugins/coc.nvim/src/__tests__/extensions/package.json deleted file mode 100644 index cc903b48..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/extensions/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "dependencies": { - "global": ">=1.0.0", - "test": ">=1.0.0" - } -} \ No newline at end of file diff --git a/vim-config/plugins/coc.nvim/src/__tests__/extensions/root.js b/vim-config/plugins/coc.nvim/src/__tests__/extensions/root.js deleted file mode 100644 index 0e76809f..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/extensions/root.js +++ /dev/null @@ -1,7 +0,0 @@ -exports.activate = context => { - return { - root: () => { - return context.extensionPath - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/extensions/test/index.js b/vim-config/plugins/coc.nvim/src/__tests__/extensions/test/index.js deleted file mode 100644 index f8d2f71a..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/extensions/test/index.js +++ /dev/null @@ -1,13 +0,0 @@ -exports.activate = async context => { - return { - asAbsolutePath: p => { - return context.asAbsolutePath(p) - }, - getContext: () => { - return context - }, - echo: x => { - return x - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/extensions/test/package.json b/vim-config/plugins/coc.nvim/src/__tests__/extensions/test/package.json deleted file mode 100644 index 4993d0aa..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/extensions/test/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "test", - "version": "1.0.0", - "engines": { - "coc": "^0.0.46" - }, - "contributes": { - "rootPatterns": [ - { - "filetype": "javascript", - "patterns": [ - "package.json", - "jsconfig.json" - ] - } - ], - "commands": [ - { - "title": "Test", - "command": "test.run" - } - ], - "configuration": { - "properties": { - "test.enable": { - "type": "boolean", - "default": true, - "description": "Enable test" - } - } - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/extensions/vim/local/index.js b/vim-config/plugins/coc.nvim/src/__tests__/extensions/vim/local/index.js deleted file mode 100644 index e48cb515..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/extensions/vim/local/index.js +++ /dev/null @@ -1,7 +0,0 @@ -exports.activate = async context => { - return { - getContext: () => { - return context - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/extensions/vim/local/package.json b/vim-config/plugins/coc.nvim/src/__tests__/extensions/vim/local/package.json deleted file mode 100644 index 95a64e73..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/extensions/vim/local/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "local", - "version": "1.0.0", - "engines": { - "coc": "^0.0.46" - } -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/callHierarchy.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/callHierarchy.test.ts deleted file mode 100644 index f0048e11..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/callHierarchy.test.ts +++ /dev/null @@ -1,398 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, CallHierarchyItem, SymbolKind, Range, SymbolTag } from 'vscode-languageserver-protocol' -import CallHierarchyHandler from '../../handler/callHierarchy' -import languages from '../../languages' -import workspace from '../../workspace' -import { disposeAll } from '../../util' -import { URI } from 'vscode-uri' -import helper, { createTmpFile } from '../helper' - -let nvim: Neovim -let callHierarchy: CallHierarchyHandler -let disposables: Disposable[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - callHierarchy = helper.plugin.getHandler().callHierarchy -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(async () => { - await helper.createDocument() -}) - -afterEach(async () => { - disposeAll(disposables) - await helper.reset() -}) - -function createCallItem(name: string, kind: SymbolKind, uri: string, range: Range): CallHierarchyItem { - return { - name, - kind, - uri, - range, - selectionRange: range - } -} - -describe('CallHierarchy', () => { - it('should throw for when provider not exists', async () => { - let err - try { - await callHierarchy.getIncoming() - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should get undefined when prepare failed', async () => { - disposables.push(languages.registerCallHierarchyProvider([{ language: '*' }], { - prepareCallHierarchy() { - return undefined - }, - provideCallHierarchyIncomingCalls() { - return [] - }, - provideCallHierarchyOutgoingCalls() { - return [] - } - })) - let res = await callHierarchy.getOutgoing() - expect(res).toBeUndefined() - }) - - it('should get incoming & outgoing callHierarchy items', async () => { - disposables.push(languages.registerCallHierarchyProvider([{ language: '*' }], { - prepareCallHierarchy() { - return createCallItem('foo', SymbolKind.Class, 'test:///foo', Range.create(0, 0, 0, 5)) - }, - provideCallHierarchyIncomingCalls() { - return [{ - from: createCallItem('bar', SymbolKind.Class, 'test:///bar', Range.create(1, 0, 1, 5)), - fromRanges: [Range.create(0, 0, 0, 5)] - }] - }, - provideCallHierarchyOutgoingCalls() { - return [{ - to: createCallItem('bar', SymbolKind.Class, 'test:///bar', Range.create(1, 0, 1, 5)), - fromRanges: [Range.create(1, 0, 1, 5)] - }] - } - })) - let res = await callHierarchy.getIncoming() - expect(res.length).toBe(1) - expect(res[0].from.name).toBe('bar') - let outgoing = await callHierarchy.getOutgoing() - expect(outgoing.length).toBe(1) - res = await callHierarchy.getIncoming(outgoing[0].to) - expect(res.length).toBe(1) - }) - - it('should show message when provider not exists', async () => { - await callHierarchy.showCallHierarchyTree('incoming') - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines[0]).toMatch('callHierarchy provider not found') - await nvim.command('wincmd p') - }) - - it('should no results when no result returned.', async () => { - disposables.push(languages.registerCallHierarchyProvider([{ language: '*' }], { - prepareCallHierarchy() { - return [] - }, - provideCallHierarchyIncomingCalls() { - return [] - }, - provideCallHierarchyOutgoingCalls() { - return [] - } - })) - await callHierarchy.showCallHierarchyTree('incoming') - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines[0]).toBe('No results') - await nvim.command('wincmd p') - }) - - it('should render description and support default action', async () => { - let doc = await workspace.document - let bufnr = doc.bufnr - await doc.buffer.setLines(['foo'], { start: 0, end: -1, strictIndexing: false }) - let fsPath = await createTmpFile('foo\nbar\ncontent\n') - let uri = URI.file(fsPath).toString() - disposables.push(languages.registerCallHierarchyProvider([{ language: '*' }], { - prepareCallHierarchy() { - return createCallItem('foo', SymbolKind.Class, doc.uri, Range.create(0, 0, 0, 3)) - }, - provideCallHierarchyIncomingCalls() { - let item = createCallItem('bar', SymbolKind.Class, uri, Range.create(1, 0, 1, 3)) - item.detail = 'Detail' - item.tags = [SymbolTag.Deprecated] - return [{ - from: item, - fromRanges: [Range.create(2, 0, 2, 5)] - }] - }, - provideCallHierarchyOutgoingCalls() { - return [] - } - })) - await callHierarchy.showCallHierarchyTree('incoming') - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual([ - 'INCOMING CALLS', - '- c foo', - ' + c bar Detail' - ]) - await nvim.command('exe 3') - await nvim.input('t') - await helper.wait(50) - let line = await nvim.line - expect(line).toEqual(' - c bar Detail') - await nvim.input('') - await helper.wait(50) - doc = await workspace.document - expect(doc.uri).toBe(uri) - let res = await nvim.call('coc#cursor#position') - expect(res).toEqual([1, 0]) - let matches = await nvim.call('getmatches') as any[] - expect(matches.length).toBe(2) - await nvim.command(`b ${bufnr}`) - await helper.wait(50) - matches = await nvim.call('getmatches') - expect(matches.length).toBe(0) - await nvim.command(`wincmd o`) - await helper.wait(50) - }) - - it('should invoke open in new tab action', async () => { - let doc = await workspace.document - await doc.buffer.setLines(['foo', 'bar'], { start: 0, end: -1, strictIndexing: false }) - let fsPath = await createTmpFile('foo\nbar\ncontent\n') - let uri = URI.file(fsPath).toString() - disposables.push(languages.registerCallHierarchyProvider([{ language: '*' }], { - prepareCallHierarchy() { - return createCallItem('foo', SymbolKind.Class, doc.uri, Range.create(0, 0, 0, 3)) - }, - provideCallHierarchyIncomingCalls() { - return [] - }, - provideCallHierarchyOutgoingCalls() { - let item = createCallItem('bar', SymbolKind.Class, uri, Range.create(0, 0, 0, 1)) - item.detail = 'Detail' - return [{ - to: item, - fromRanges: [Range.create(1, 0, 1, 3)] - }] - } - })) - let win = await nvim.window - let tab = await nvim.call('tabpagenr') - await callHierarchy.showCallHierarchyTree('outgoing') - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual([ - 'OUTGOING CALLS', - '- c foo', - ' + c bar Detail' - ]) - await nvim.command('exe 3') - await nvim.input('') - await helper.wait(50) - await nvim.input('') - await helper.wait(200) - let newTab = await nvim.call('tabpagenr') - expect(newTab != tab).toBe(true) - doc = await workspace.document - expect(doc.uri).toBe(uri) - let res = await nvim.call('getmatches', [win.id]) - expect(res.length).toBe(1) - }) - - it('should invoke show incoming calls action', async () => { - let doc = await workspace.document - await doc.buffer.setLines(['foo', 'bar'], { start: 0, end: -1, strictIndexing: false }) - let fsPath = await createTmpFile('foo\nbar\ncontent\n') - let uri = URI.file(fsPath).toString() - disposables.push(languages.registerCallHierarchyProvider([{ language: '*' }], { - prepareCallHierarchy() { - return createCallItem('foo', SymbolKind.Class, doc.uri, Range.create(0, 0, 0, 3)) - }, - provideCallHierarchyIncomingCalls() { - return [{ - from: createCallItem('test', SymbolKind.Class, 'test:///bar', Range.create(1, 0, 1, 5)), - fromRanges: [Range.create(0, 0, 0, 5)] - }] - }, - provideCallHierarchyOutgoingCalls() { - let item = createCallItem('bar', SymbolKind.Class, uri, Range.create(0, 0, 0, 1)) - item.detail = 'Detail' - return [{ - to: item, - fromRanges: [Range.create(1, 0, 1, 3)] - }] - } - })) - await callHierarchy.showCallHierarchyTree('outgoing') - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual([ - 'OUTGOING CALLS', - '- c foo', - ' + c bar Detail' - ]) - await nvim.command('exe 3') - await nvim.input('') - await helper.wait(50) - await nvim.input('2') - await helper.wait(200) - lines = await buf.lines - expect(lines).toEqual([ - 'INCOMING CALLS', - '- c bar Detail', - ' + c test' - ]) - await nvim.command('bd!') - }) - - it('should invoke show outgoing calls action', async () => { - let doc = await workspace.document - await doc.buffer.setLines(['foo', 'bar'], { start: 0, end: -1, strictIndexing: false }) - let fsPath = await createTmpFile('foo\nbar\ncontent\n') - let uri = URI.file(fsPath).toString() - disposables.push(languages.registerCallHierarchyProvider([{ language: '*' }], { - prepareCallHierarchy() { - return createCallItem('foo', SymbolKind.Class, doc.uri, Range.create(0, 0, 0, 3)) - }, - provideCallHierarchyIncomingCalls() { - return [{ - from: createCallItem('test', SymbolKind.Class, 'test:///bar', Range.create(1, 0, 1, 5)), - fromRanges: [Range.create(0, 0, 0, 5)] - }] - }, - provideCallHierarchyOutgoingCalls() { - let item = createCallItem('bar', SymbolKind.Class, uri, Range.create(0, 0, 0, 1)) - item.detail = 'Detail' - return [{ - to: item, - fromRanges: [Range.create(1, 0, 1, 3)] - }] - } - })) - await callHierarchy.showCallHierarchyTree('incoming') - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual([ - 'INCOMING CALLS', - '- c foo', - ' + c test' - ]) - await nvim.command('exe 3') - await nvim.input('') - await helper.wait(50) - await nvim.input('3') - await helper.wait(200) - lines = await buf.lines - expect(lines).toEqual([ - 'OUTGOING CALLS', - '- c test', - ' + c bar Detail' - ]) - await nvim.command('bd!') - }) - - it('should invoke dismiss action #1', async () => { - let doc = await workspace.document - await doc.buffer.setLines(['foo', 'bar'], { start: 0, end: -1, strictIndexing: false }) - let fsPath = await createTmpFile('foo\nbar\ncontent\n') - let uri = URI.file(fsPath).toString() - disposables.push(languages.registerCallHierarchyProvider([{ language: '*' }], { - prepareCallHierarchy() { - return createCallItem('foo', SymbolKind.Class, doc.uri, Range.create(0, 0, 0, 3)) - }, - provideCallHierarchyIncomingCalls() { - return [] - }, - provideCallHierarchyOutgoingCalls() { - let item = createCallItem('bar', SymbolKind.Class, uri, Range.create(0, 0, 0, 1)) - item.detail = 'Detail' - return [{ - to: item, - fromRanges: [Range.create(1, 0, 1, 3)] - }] - } - })) - await callHierarchy.showCallHierarchyTree('outgoing') - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual([ - 'OUTGOING CALLS', - '- c foo', - ' + c bar Detail' - ]) - await nvim.command('exe 3') - await nvim.input('') - await helper.wait(50) - await nvim.input('4') - await helper.wait(200) - lines = await buf.lines - expect(lines).toEqual([ - 'OUTGOING CALLS', - '- c foo' - ]) - await nvim.command('wincmd c') - }) - - it('should invoke dismiss action #2', async () => { - let doc = await workspace.document - await doc.buffer.setLines(['foo', 'bar'], { start: 0, end: -1, strictIndexing: false }) - let fsPath = await createTmpFile('foo\nbar\ncontent\n') - let uri = URI.file(fsPath).toString() - disposables.push(languages.registerCallHierarchyProvider([{ language: '*' }], { - prepareCallHierarchy() { - return createCallItem('foo', SymbolKind.Class, doc.uri, Range.create(0, 0, 0, 3)) - }, - provideCallHierarchyIncomingCalls() { - return [] - }, - provideCallHierarchyOutgoingCalls() { - let item = createCallItem('bar', SymbolKind.Class, uri, Range.create(0, 0, 0, 1)) - item.detail = 'Detail' - return [{ - to: item, - fromRanges: [Range.create(1, 0, 1, 3)] - }] - } - })) - await callHierarchy.showCallHierarchyTree('outgoing') - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual([ - 'OUTGOING CALLS', - '- c foo', - ' + c bar Detail' - ]) - await nvim.command('exe 3') - await nvim.input('t') - await helper.wait(50) - await nvim.command('exe 4') - await nvim.input('') - await helper.wait(50) - await nvim.input('4') - await helper.wait(200) - lines = await buf.lines - expect(lines).toEqual([ - 'OUTGOING CALLS', - '- c foo', - ' - c bar Detail' - ]) - await nvim.command('wincmd c') - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/codeActions.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/codeActions.test.ts deleted file mode 100644 index d0b70c76..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/codeActions.test.ts +++ /dev/null @@ -1,386 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationToken, CodeAction, Command, CodeActionContext, CodeActionKind, TextEdit, Disposable, Range, Position } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import commands from '../../commands' -import ActionsHandler from '../../handler/codeActions' -import languages from '../../languages' -import { ProviderResult } from '../../provider' -import { disposeAll } from '../../util' -import { rangeInRange } from '../../util/position' -import helper from '../helper' - -let nvim: Neovim -let disposables: Disposable[] = [] -let codeActions: ActionsHandler -let currActions: CodeAction[] -let resolvedAction: CodeAction -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - codeActions = helper.plugin.getHandler().codeActions -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(async () => { - disposables.push(languages.registerCodeActionProvider([{ language: '*' }], { - provideCodeActions: ( - _document: TextDocument, - _range: Range, - _context: CodeActionContext, - _token: CancellationToken - ) => currActions, - resolveCodeAction: ( - _action: CodeAction, - _token: CancellationToken - ): ProviderResult => resolvedAction - }, undefined)) -}) - -afterEach(async () => { - disposeAll(disposables) - await helper.reset() -}) - -describe('handler codeActions', () => { - describe('organizeImport', () => { - it('should throw error when organize import action not found', async () => { - currActions = [] - await helper.createDocument() - let err - try { - await codeActions.organizeImport() - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should perform organize import action', async () => { - let doc = await helper.createDocument() - await doc.buffer.setLines(['foo', 'bar'], { start: 0, end: -1, strictIndexing: false }) - let edits: TextEdit[] = [] - edits.push(TextEdit.replace(Range.create(0, 0, 0, 3), 'bar')) - edits.push(TextEdit.replace(Range.create(1, 0, 1, 3), 'foo')) - let edit = { changes: { [doc.uri]: edits } } - let action = CodeAction.create('organize import', edit, CodeActionKind.SourceOrganizeImports) - currActions = [action, CodeAction.create('another action')] - await codeActions.organizeImport() - let lines = await doc.buffer.lines - expect(lines).toEqual(['bar', 'foo']) - }) - - it('should register editor.action.organizeImport command', async () => { - let doc = await helper.createDocument() - await doc.buffer.setLines(['foo', 'bar'], { start: 0, end: -1, strictIndexing: false }) - let edits: TextEdit[] = [] - edits.push(TextEdit.replace(Range.create(0, 0, 0, 3), 'bar')) - edits.push(TextEdit.replace(Range.create(1, 0, 1, 3), 'foo')) - let edit = { changes: { [doc.uri]: edits } } - let action = CodeAction.create('organize import', edit, CodeActionKind.SourceOrganizeImports) - currActions = [action, CodeAction.create('another action')] - await commands.executeCommand('editor.action.organizeImport') - let lines = await doc.buffer.lines - expect(lines).toEqual(['bar', 'foo']) - }) - }) - - describe('codeActionRange', () => { - it('should show warning when no action available', async () => { - await helper.createDocument() - currActions = [] - await codeActions.codeActionRange(1, 2, CodeActionKind.QuickFix) - let line = await helper.getCmdline() - expect(line).toMatch(/No quickfix code action/) - }) - - it('should apply choosen action', async () => { - let doc = await helper.createDocument() - let edits: TextEdit[] = [] - edits.push(TextEdit.insert(Position.create(0, 0), 'bar')) - let edit = { changes: { [doc.uri]: edits } } - let action = CodeAction.create('code fix', edit, CodeActionKind.QuickFix) - currActions = [action] - let p = codeActions.codeActionRange(1, 2, CodeActionKind.QuickFix) - await helper.wait(50) - await nvim.input('') - await p - let buf = nvim.createBuffer(doc.bufnr) - let lines = await buf.lines - expect(lines[0]).toBe('bar') - }) - }) - - describe('getCodeActions', () => { - it('should get empty actions', async () => { - currActions = [] - let doc = await helper.createDocument() - let res = await codeActions.getCodeActions(doc) - expect(res.length).toBe(0) - }) - - it('should filter disabled actions', async () => { - currActions = [] - let action = CodeAction.create('foo', CodeActionKind.QuickFix) - action.disabled = { reason: 'disabled' } - currActions.push(action) - action = CodeAction.create('foo', CodeActionKind.QuickFix) - action.disabled = { reason: 'disabled' } - currActions.push(action) - let doc = await helper.createDocument() - let res = await codeActions.getCodeActions(doc) - expect(res.length).toBe(0) - }) - - it('should get all actions', async () => { - let doc = await helper.createDocument() - await doc.buffer.setLines(['', '', ''], { start: 0, end: -1, strictIndexing: false }) - let action = CodeAction.create('curr action', CodeActionKind.Empty) - currActions = [action] - let range: Range - disposables.push(languages.registerCodeActionProvider([{ language: '*' }], { - provideCodeActions: ( - _document: TextDocument, - r: Range, - _context: CodeActionContext, _token: CancellationToken - ) => { - range = r - return [CodeAction.create('a'), CodeAction.create('b'), CodeAction.create('c')] - }, - }, undefined)) - let res = await codeActions.getCodeActions(doc) - expect(range).toEqual(Range.create(0, 0, 3, 0)) - expect(res.length).toBe(4) - }) - - it('should filter actions by range', async () => { - let doc = await helper.createDocument() - await doc.buffer.setLines(['', '', ''], { start: 0, end: -1, strictIndexing: false }) - currActions = [] - let range: Range - disposables.push(languages.registerCodeActionProvider([{ language: '*' }], { - provideCodeActions: ( - _document: TextDocument, - r: Range, - _context: CodeActionContext, _token: CancellationToken - ) => { - range = r - if (rangeInRange(r, Range.create(0, 0, 1, 0))) return [CodeAction.create('a')] - return [CodeAction.create('a'), CodeAction.create('b'), CodeAction.create('c')] - }, - }, undefined)) - let res = await codeActions.getCodeActions(doc, Range.create(0, 0, 0, 0)) - expect(range).toEqual(Range.create(0, 0, 0, 0)) - expect(res.length).toBe(1) - }) - - it('should filter actions by kind prefix', async () => { - let doc = await helper.createDocument() - let action = CodeAction.create('my action', CodeActionKind.SourceFixAll) - currActions = [action] - let res = await codeActions.getCodeActions(doc, undefined, [CodeActionKind.Source]) - expect(res.length).toBe(1) - expect(res[0].kind).toBe(CodeActionKind.SourceFixAll) - }) - }) - - describe('getCurrentCodeActions', () => { - let range: Range - beforeEach(() => { - disposables.push(languages.registerCodeActionProvider([{ language: '*' }], { - provideCodeActions: ( - _document: TextDocument, - r: Range, - _context: CodeActionContext, _token: CancellationToken - ) => { - range = r - return [CodeAction.create('a'), CodeAction.create('b'), CodeAction.create('c')] - }, - }, undefined)) - }) - - it('should get codeActions by line', async () => { - currActions = [] - await helper.createDocument() - let res = await codeActions.getCurrentCodeActions('line') - expect(range).toEqual(Range.create(0, 0, 1, 0)) - expect(res.length).toBe(3) - }) - - it('should get codeActions by cursor', async () => { - currActions = [] - await helper.createDocument() - let res = await codeActions.getCurrentCodeActions('cursor') - expect(range).toEqual(Range.create(0, 0, 0, 0)) - expect(res.length).toBe(3) - }) - - it('should get codeActions by visual mode', async () => { - currActions = [] - await helper.createDocument() - await nvim.setLine('foo') - await nvim.command('normal! 0v$') - await nvim.input('') - let res = await codeActions.getCurrentCodeActions('v') - expect(range).toEqual(Range.create(0, 0, 0, 4)) - expect(res.length).toBe(3) - }) - }) - - describe('doCodeAction', () => { - it('should not throw when no action exists', async () => { - currActions = [] - await helper.createDocument() - let err - try { - await codeActions.doCodeAction(undefined) - } catch (e) { - err = e - } - expect(err).toBeUndefined() - }) - - it('should apply single code action when only is title', async () => { - let doc = await helper.createDocument() - let edits: TextEdit[] = [] - edits.push(TextEdit.insert(Position.create(0, 0), 'bar')) - let edit = { changes: { [doc.uri]: edits } } - let action = CodeAction.create('code fix', edit, CodeActionKind.QuickFix) - currActions = [action] - await codeActions.doCodeAction(undefined, 'code fix') - let lines = await doc.buffer.lines - expect(lines).toEqual(['bar']) - }) - - it('should apply single code action when only is codeAction array', async () => { - let doc = await helper.createDocument() - let edits: TextEdit[] = [] - edits.push(TextEdit.insert(Position.create(0, 0), 'bar')) - let edit = { changes: { [doc.uri]: edits } } - let action = CodeAction.create('code fix', edit, CodeActionKind.QuickFix) - currActions = [action] - await codeActions.doCodeAction(undefined, [CodeActionKind.QuickFix]) - let lines = await doc.buffer.lines - expect(lines).toEqual(['bar']) - }) - - it('should action dialog to choose action', async () => { - let doc = await helper.createDocument() - let edits: TextEdit[] = [] - edits.push(TextEdit.insert(Position.create(0, 0), 'bar')) - let edit = { changes: { [doc.uri]: edits } } - let action = CodeAction.create('code fix', edit, CodeActionKind.QuickFix) - currActions = [action, CodeAction.create('foo')] - let promise = codeActions.doCodeAction(null) - await helper.wait(50) - let ids = await nvim.call('coc#float#get_float_win_list') as number[] - expect(ids.length).toBeGreaterThan(0) - await nvim.input('') - await promise - let lines = await doc.buffer.lines - expect(lines).toEqual(['bar']) - }) - - it('should choose code actions by range', async () => { - let range: Range - disposables.push(languages.registerCodeActionProvider([{ language: '*' }], { - provideCodeActions: ( - _document: TextDocument, - r: Range, - _context: CodeActionContext, _token: CancellationToken - ) => { - range = r - return [CodeAction.create('my title'), CodeAction.create('b'), CodeAction.create('c')] - }, - }, undefined)) - await helper.createDocument() - await nvim.setLine('abc') - await nvim.command('normal! 0v$') - await nvim.input('') - await codeActions.doCodeAction('v', 'my title') - expect(range).toEqual({ start: { line: 0, character: 0 }, end: { line: 0, character: 4 } }) - }) - }) - - describe('doQuickfix', () => { - it('should throw when quickfix action not exists', async () => { - let err - currActions = [] - await helper.createDocument() - try { - await codeActions.doQuickfix() - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should do preferred quickfix action', async () => { - let doc = await helper.createDocument() - let edits: TextEdit[] = [] - edits.push(TextEdit.insert(Position.create(0, 0), 'bar')) - let edit = { changes: { [doc.uri]: edits } } - let action = CodeAction.create('code fix', edit, CodeActionKind.QuickFix) - action.isPreferred = true - currActions = [CodeAction.create('foo', CodeActionKind.QuickFix), action, CodeAction.create('bar')] - await codeActions.doQuickfix() - let lines = await doc.buffer.lines - expect(lines).toEqual(['bar']) - }) - }) - - describe('applyCodeAction', () => { - it('should resolve codeAction', async () => { - let doc = await helper.createDocument() - let edits: TextEdit[] = [] - edits.push(TextEdit.insert(Position.create(0, 0), 'bar')) - let edit = { changes: { [doc.uri]: edits } } - let action = CodeAction.create('code fix', CodeActionKind.QuickFix) - action.isPreferred = true - currActions = [action] - resolvedAction = Object.assign({ edit }, action) - let arr = await codeActions.getCurrentCodeActions('line', [CodeActionKind.QuickFix]) - await codeActions.applyCodeAction(arr[0]) - let lines = await doc.buffer.lines - expect(lines).toEqual(['bar']) - }) - - it('should throw for disabled action', async () => { - let action = CodeAction.create('my action', CodeActionKind.Empty) - action.disabled = { reason: 'disabled' } - let err - try { - await codeActions.applyCodeAction(action) - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should invoke registered command after apply edit', async () => { - let called - disposables.push(commands.registerCommand('test.execute', async (s: string) => { - called = s - await nvim.command(s) - })) - let doc = await helper.createDocument() - let edits: TextEdit[] = [] - edits.push(TextEdit.insert(Position.create(0, 0), 'bar')) - let edit = { changes: { [doc.uri]: edits } } - let action = CodeAction.create('code fix', CodeActionKind.QuickFix) - action.isPreferred = true - currActions = [action] - resolvedAction = Object.assign({ - edit, - command: Command.create('run vim command', 'test.execute', 'normal! $') - }, action) - let arr = await codeActions.getCurrentCodeActions('line', [CodeActionKind.QuickFix]) - await codeActions.applyCodeAction(arr[0]) - let lines = await doc.buffer.lines - expect(lines).toEqual(['bar']) - expect(called).toBe('normal! $') - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/codelens.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/codelens.test.ts deleted file mode 100644 index 899ca01c..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/codelens.test.ts +++ /dev/null @@ -1,269 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, Range, Command, TextEdit, Position } from 'vscode-languageserver-protocol' -import { disposeAll } from '../../util' -import languages from '../../languages' -import commands from '../../commands' -import CodeLens from '../../handler/codelens/index' -import helper, { createTmpFile } from '../helper' -import events from '../../events' - -let nvim: Neovim -let codeLens: CodeLens -let disposables: Disposable[] = [] -let srcId: number - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - srcId = await nvim.createNamespace('coc-codelens') - codeLens = helper.plugin.getHandler().codeLens - helper.updateConfiguration('codeLens.enable', true) -}) - -afterAll(async () => { - helper.updateConfiguration('codeLens.enable', false) - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -describe('codeLenes featrue', () => { - - it('should do codeLenes request and resolve codeLenes', async () => { - disposables.push(languages.registerCodeLensProvider([{ language: 'javascript' }], { - provideCodeLenses: () => { - return [{ - range: Range.create(0, 0, 0, 1) - }, { - range: Range.create(1, 0, 1, 1) - }] - }, - resolveCodeLens: codeLens => { - codeLens.command = Command.create('save', '__save') - return codeLens - } - })) - let doc = await helper.createDocument('example.js') - await nvim.call('setline', [1, ['a', 'b', 'c']]) - await codeLens.checkProvider() - let buf = codeLens.buffers.getItem(doc.bufnr) - let codelens = buf.getCodelenses() - expect(codelens).toBeDefined() - expect(codelens[0].command).toBeDefined() - expect(codelens[1].command).toBeDefined() - let markers = await helper.getMarkers(doc.bufnr, srcId) - expect(markers.length).toBe(2) - }) - - it('should refresh codeLens on CursorHold', async () => { - disposables.push(languages.registerCodeLensProvider([{ language: 'javascript' }], { - provideCodeLenses: document => { - let n = document.lineCount - let arr: any[] = [] - for (let i = 0; i <= n - 2; i++) { - arr.push({ - range: Range.create(i, 0, i, 1), - command: Command.create('save', '__save', i) - }) - } - return arr - } - })) - let doc = await helper.createDocument('example.js') - await helper.wait(100) - let markers = await helper.getMarkers(doc.bufnr, srcId) - await nvim.call('setline', [1, ['a', 'b', 'c']]) - await doc.synchronize() - await events.fire('CursorHold', [doc.bufnr]) - await helper.wait(200) - markers = await helper.getMarkers(doc.bufnr, srcId) - expect(markers.length).toBe(3) - }) - - it('should cancel codeLenes request on document change', async () => { - let cancelled = false - disposables.push(languages.registerCodeLensProvider([{ language: 'javascript' }], { - provideCodeLenses: (_, token) => { - return new Promise(resolve => { - token.onCancellationRequested(() => { - cancelled = true - clearTimeout(timer) - resolve(null) - }) - let timer = setTimeout(() => { - resolve([{ - range: Range.create(0, 0, 0, 1) - }, { - range: Range.create(1, 0, 1, 1) - }]) - }, 2000) - }) - }, - resolveCodeLens: codeLens => { - codeLens.command = Command.create('save', '__save') - return codeLens - } - })) - let doc = await helper.createDocument('codelens.js') - await doc.applyEdits([TextEdit.insert(Position.create(0, 0), 'a\nb\nc')]) - let p = codeLens.checkProvider() - await doc.applyEdits([TextEdit.replace(Range.create(0, 0, 0, 1), 'foo')]) - await p - expect(cancelled).toBe(true) - let buf = codeLens.buffers.getItem(doc.bufnr) - let codelens = buf.getCodelenses() - expect(codelens).toBeUndefined() - }) - - it('should resolve on CursorMoved', async () => { - disposables.push(languages.registerCodeLensProvider([{ language: 'javascript' }], { - provideCodeLenses: () => { - return [{ - range: Range.create(90, 0, 90, 1) - }, { - range: Range.create(91, 0, 91, 1) - }] - }, - resolveCodeLens: async codeLens => { - await helper.wait(50) - codeLens.command = Command.create('save', '__save') - return codeLens - } - })) - let doc = await helper.createDocument('example.js') - let arr = new Array(100) - arr.fill('') - await nvim.call('setline', [1, arr]) - await doc.synchronize() - await codeLens.checkProvider() - await nvim.command('normal! gg') - await helper.wait(300) - await nvim.command('normal! G') - await helper.wait(300) - let buf = codeLens.buffers.getItem(doc.bufnr) - let codelens = buf.getCodelenses() - expect(codelens).toBeDefined() - expect(codelens[0].command).toBeDefined() - expect(codelens[1].command).toBeDefined() - }) - - it('should invoke codeLenes action', async () => { - let fn = jest.fn() - disposables.push(commands.registerCommand('__save', (...args) => { - fn(...args) - })) - disposables.push(languages.registerCodeLensProvider([{ language: 'javascript' }], { - provideCodeLenses: () => { - return [{ - range: Range.create(0, 0, 0, 1) - }] - }, - resolveCodeLens: codeLens => { - codeLens.command = Command.create('save', '__save', 1, 2, 3) - return codeLens - } - })) - await helper.createDocument('example.js') - await nvim.call('setline', [1, ['a', 'b', 'c']]) - await codeLens.checkProvider() - await helper.doAction('codeLensAction') - expect(fn).toBeCalledWith(1, 2, 3) - }) - - it('should use picker fo multiple codeLenses', async () => { - let fn = jest.fn() - disposables.push(commands.registerCommand('__save', (...args) => { - fn(...args) - })) - disposables.push(commands.registerCommand('__delete', (...args) => { - fn(...args) - })) - disposables.push(languages.registerCodeLensProvider([{ language: 'javascript' }], { - provideCodeLenses: () => { - return [{ - range: Range.create(0, 0, 0, 1), - command: Command.create('save', '__save', 1, 2, 3) - }, { - range: Range.create(0, 1, 0, 2), - command: Command.create('save', '__delete', 4, 5, 6) - }] - } - })) - let doc = await helper.createDocument('example.js') - await nvim.call('setline', [1, ['a', 'b', 'c']]) - await doc.synchronize() - await codeLens.checkProvider() - let p = helper.doAction('codeLensAction') - await helper.wait(30) - await nvim.input('') - await p - expect(fn).toBeCalledWith(1, 2, 3) - }) - - it('should refresh for failed codeLens request', async () => { - let called = 0 - let fn = jest.fn() - disposables.push(commands.registerCommand('__save', (...args) => { - fn(...args) - })) - disposables.push(commands.registerCommand('__foo', (...args) => { - fn(...args) - })) - disposables.push(languages.registerCodeLensProvider([{ language: '*' }], { - provideCodeLenses: () => { - called++ - if (called == 1) { - return null - } - return [{ - range: Range.create(0, 0, 0, 1), - command: Command.create('foo', '__foo') - }] - } - })) - disposables.push(languages.registerCodeLensProvider([{ language: '*' }], { - provideCodeLenses: () => { - return [{ - range: Range.create(0, 0, 0, 1), - command: Command.create('save', '__save') - }] - } - })) - let doc = await helper.createDocument('example.js') - await nvim.call('setline', [1, ['a', 'b', 'c']]) - await codeLens.checkProvider() - let markers = await helper.getMarkers(doc.buffer.id, srcId) - expect(markers.length).toBeGreaterThan(0) - let codeLensBuffer = codeLens.buffers.getItem(doc.buffer.id) - await codeLensBuffer.forceFetch() - let curr = codeLensBuffer.currentCodeLens() - expect(curr.length).toBeGreaterThan(1) - expect(called).toBe(2) - }) - - it('should refresh on configuration change', async () => { - disposables.push(languages.registerCodeLensProvider([{ language: '*' }], { - provideCodeLenses: () => { - return [{ - range: Range.create(0, 0, 0, 1), - command: Command.create('save', '__save') - }] - } - })) - let filepath = await createTmpFile('abc') - let buffer = await helper.edit(filepath) - await codeLens.checkProvider() - helper.updateConfiguration('codeLens.enable', false) - await helper.wait(10) - let markers = await helper.getMarkers(buffer.id, srcId) - expect(markers.length).toBe(0) - helper.updateConfiguration('codeLens.enable', true) - await helper.wait(300) - markers = await helper.getMarkers(buffer.id, srcId) - expect(markers.length).toBeGreaterThan(0) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/colors.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/colors.test.ts deleted file mode 100644 index 48accb36..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/colors.test.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationToken, Color, ColorInformation, ColorPresentation, Disposable, Position, Range } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import commands from '../../commands' -import { toHexString } from '../../util/color' -import Colors from '../../handler/colors/index' -import languages from '../../languages' -import { ProviderResult } from '../../provider' -import { disposeAll } from '../../util' -import helper from '../helper' - -let nvim: Neovim -let state = 'normal' -let colors: Colors -let disposables: Disposable[] = [] -let colorPresentations: ColorPresentation[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - colors = helper.plugin.getHandler().colors - disposables.push(languages.registerDocumentColorProvider([{ language: '*' }], { - provideColorPresentations: ( - _color: Color, - _context: { document: TextDocument; range: Range }, - _token: CancellationToken - ): ColorPresentation[] => colorPresentations, - provideDocumentColors: ( - document: TextDocument, - _token: CancellationToken - ): ProviderResult => { - if (state == 'empty') return [] - if (state == 'error') return Promise.reject(new Error('no color')) - let matches = Array.from((document.getText() as any).matchAll(/#\w{6}/g)) as any - return matches.map(o => { - let start = document.positionAt(o.index) - let end = document.positionAt(o.index + o[0].length) - return { - range: Range.create(start, end), - color: getColor(255, 255, 255) - } - }) - } - })) -}) - -afterAll(async () => { - disposeAll(disposables) - await helper.shutdown() -}) - -afterEach(async () => { - colorPresentations = [] - await helper.reset() -}) - -function getColor(r: number, g: number, b: number): Color { - return { red: r / 255, green: g / 255, blue: b / 255, alpha: 1 } -} - -describe('Colors', () => { - describe('utils', () => { - it('should get hex string', () => { - let color = getColor(255, 255, 255) - let hex = toHexString(color) - expect(hex).toBe('ffffff') - }) - }) - - describe('configuration', () => { - it('should toggle enable state on configuration change', async () => { - await helper.createDocument() - helper.updateConfiguration('coc.preferences.colorSupport', false) - expect(colors.enabled).toBe(false) - helper.updateConfiguration('coc.preferences.colorSupport', true) - expect(colors.enabled).toBe(true) - }) - }) - - describe('commands', () => { - it('should register editor.action.pickColor command', async () => { - await helper.mockFunction('coc#util#pick_color', [0, 0, 0]) - let doc = await helper.createDocument() - await nvim.setLine('#ffffff') - doc.forceSync() - await colors.doHighlight(doc.bufnr) - await commands.executeCommand('editor.action.pickColor') - let line = await nvim.getLine() - expect(line).toBe('#000000') - }) - - it('should register editor.action.colorPresentation command', async () => { - colorPresentations = [ColorPresentation.create('red'), ColorPresentation.create('#ff0000')] - let doc = await helper.createDocument() - await nvim.setLine('#ffffff') - doc.forceSync() - await colors.doHighlight(doc.bufnr) - let p = commands.executeCommand('editor.action.colorPresentation') - await helper.wait(100) - await nvim.input('1') - await p - let line = await nvim.getLine() - expect(line).toBe('red') - }) - }) - - describe('doHighlight', () => { - it('should clearHighlight on empty result', async () => { - let doc = await helper.createDocument() - await nvim.setLine('#ffffff') - state = 'empty' - await colors.doHighlight(doc.bufnr) - let res = colors.hasColor(doc.bufnr) - expect(res).toBe(false) - state = 'normal' - }) - - it('should not highlight on error result', async () => { - let doc = await helper.createDocument() - await nvim.setLine('#ffffff') - state = 'error' - await colors.doHighlight(doc.bufnr) - let res = colors.hasColor(doc.bufnr) - expect(res).toBe(false) - state = 'normal' - }) - - it('should highlight after document changed', async () => { - let doc = await helper.createDocument() - doc.forceSync() - await colors.doHighlight(doc.bufnr) - expect(colors.hasColor(doc.bufnr)).toBe(false) - expect(colors.hasColorAtPosition(doc.bufnr, Position.create(0, 1))).toBe(false) - await nvim.setLine('#ffffff #ff0000') - doc.forceSync() - await helper.wait(300) - expect(colors.hasColorAtPosition(doc.bufnr, Position.create(0, 1))).toBe(true) - expect(colors.hasColor(doc.bufnr)).toBe(true) - }) - - it('should clearHighlight on clearHighlight', async () => { - let doc = await helper.createDocument() - await nvim.setLine('#ffffff #ff0000') - doc.forceSync() - await colors.doHighlight(doc.bufnr) - expect(colors.hasColor(doc.bufnr)).toBe(true) - colors.clearHighlight(doc.bufnr) - expect(colors.hasColor(doc.bufnr)).toBe(false) - }) - - it('should highlight colors', async () => { - let doc = await helper.createDocument() - await nvim.setLine('#ffffff') - await colors.doHighlight(doc.bufnr) - let exists = await nvim.call('hlexists', 'BGffffff') - expect(exists).toBe(1) - }) - }) - - describe('hasColor()', () => { - it('should return false when bufnr not exists', async () => { - let res = colors.hasColor(99) - colors.clearHighlight(99) - expect(res).toBe(false) - }) - }) - - describe('getColorInformation()', () => { - it('should return null when highlighter not exists', async () => { - let res = await colors.getColorInformation(99) - expect(res).toBe(null) - }) - - it('should return null when color not found', async () => { - let doc = await helper.createDocument() - await nvim.setLine('#ffffff foo ') - doc.forceSync() - await colors.doHighlight(doc.bufnr) - await nvim.call('cursor', [1, 12]) - let res = await colors.getColorInformation(doc.bufnr) - expect(res).toBe(null) - }) - }) - - describe('hasColorAtPosition()', () => { - it('should return false when bufnr not exists', async () => { - let res = colors.hasColorAtPosition(99, Position.create(0, 0)) - expect(res).toBe(false) - }) - }) - - describe('pickPresentation()', () => { - it('should show warning when color not exists', async () => { - await helper.createDocument() - await colors.pickPresentation() - let msg = await helper.getCmdline() - expect(msg).toMatch('Color not found') - }) - - it('should not throw when presentations not exists', async () => { - colorPresentations = [] - let doc = await helper.createDocument() - await nvim.setLine('#ffffff') - doc.forceSync() - await colors.doHighlight(99) - await colors.doHighlight(doc.bufnr) - await helper.doAction('colorPresentation') - }) - - it('should pick presentations', async () => { - colorPresentations = [ColorPresentation.create('red'), ColorPresentation.create('#ff0000')] - let doc = await helper.createDocument() - await nvim.setLine('#ffffff') - doc.forceSync() - await colors.doHighlight(doc.bufnr) - let p = helper.doAction('colorPresentation') - await helper.wait(100) - await nvim.input('1') - await p - let line = await nvim.getLine() - expect(line).toBe('red') - }) - }) - - describe('pickColor()', () => { - it('should show warning when color not exists', async () => { - await helper.createDocument() - await colors.pickColor() - let msg = await helper.getCmdline() - expect(msg).toMatch('not found') - }) - - it('should pickColor', async () => { - await helper.mockFunction('coc#util#pick_color', [0, 0, 0]) - let doc = await helper.createDocument() - await nvim.setLine('#ffffff') - doc.forceSync() - await colors.doHighlight(doc.bufnr) - await helper.doAction('pickColor') - let line = await nvim.getLine() - expect(line).toBe('#000000') - }) - - it('should not throw when pick color return 0', async () => { - await helper.mockFunction('coc#util#pick_color', 0) - let doc = await helper.createDocument() - await nvim.setLine('#ffffff') - doc.forceSync() - await colors.doHighlight(doc.bufnr) - await helper.doAction('pickColor') - let line = await nvim.getLine() - expect(line).toBe('#ffffff') - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/commands.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/commands.test.ts deleted file mode 100644 index f9026edf..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/commands.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import CommandsHandler from '../../handler/commands' -import commandManager from '../../commands' -import { disposeAll } from '../../util' -import helper from '../helper' - -let nvim: Neovim -let commands: CommandsHandler -let disposables: Disposable[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - commands = (helper.plugin as any).handler.commands -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(async () => { - await helper.createDocument() -}) - -afterEach(async () => { - disposeAll(disposables) - await helper.reset() -}) - -describe('Commands', () => { - describe('addVimCommand', () => { - it('should register global vim commands', async () => { - await commandManager.executeCommand('vim.config') - await helper.wait(50) - let bufname = await nvim.call('bufname', ['%']) - expect(bufname).toMatch('coc-settings.json') - let list = commands.getCommandList() - expect(list.includes('vim.config')).toBe(true) - }) - - it('should add vim command with title', async () => { - commands.addVimCommand({ id: 'list', cmd: 'CocList', title: 'list of coc.nvim' }) - let res = commandManager.titles.get('vim.list') - expect(res).toBe('list of coc.nvim') - commandManager.unregister('vim.list') - }) - }) - - describe('getCommands', () => { - it('should get command items', async () => { - let res = commands.getCommands() - let idx = res.findIndex(o => o.id == 'workspace.showOutput') - expect(idx != -1).toBe(true) - }) - }) - - describe('repeat', () => { - it('should repeat command', async () => { - // let buf = await nvim.buffer - await nvim.call('setline', [1, ['a', 'b', 'c']]) - await nvim.call('cursor', [1, 1]) - commands.addVimCommand({ id: 'remove', cmd: 'normal! dd' }) - await commands.runCommand('vim.remove') - await helper.wait(50) - let res = await nvim.call('getline', [1, '$']) - expect(res).toEqual(['b', 'c']) - await commands.repeat() - await helper.wait(50) - res = await nvim.call('getline', [1, '$']) - expect(res).toEqual(['c']) - }) - }) - - describe('runCommand', () => { - it('should open command list without id', async () => { - await commands.runCommand() - await helper.wait(100) - let bufname = await nvim.call('bufname', ['%']) - expect(bufname).toBe('list:///commands') - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/fold.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/fold.test.ts deleted file mode 100644 index 8ddc23df..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/fold.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, FoldingRange } from 'vscode-languageserver-protocol' -import FoldHandler from '../../handler/fold' -import languages from '../../languages' -import { disposeAll } from '../../util' -import helper from '../helper' - -let nvim: Neovim -let folds: FoldHandler -let disposables: Disposable[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - folds = (helper.plugin as any).handler.fold -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(async () => { - await helper.createDocument() -}) - -afterEach(async () => { - disposeAll(disposables) - await helper.reset() -}) - -describe('Folds', () => { - - it('should return false when no fold ranges found', async () => { - disposables.push(languages.registerFoldingRangeProvider([{ language: '*' }], { - provideFoldingRanges(_doc) { - return [] - } - })) - let res = await folds.fold() - expect(res).toBe(false) - }) - - it('should fold all fold ranges', async () => { - disposables.push(languages.registerFoldingRangeProvider([{ language: '*' }], { - provideFoldingRanges(_doc) { - return [FoldingRange.create(1, 3), FoldingRange.create(4, 6, 0, 0, 'comment')] - } - })) - await nvim.call('setline', [1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']]) - let res = await folds.fold() - expect(res).toBe(true) - let closed = await nvim.call('foldclosed', [2]) - expect(closed).toBe(2) - closed = await nvim.call('foldclosed', [5]) - expect(closed).toBe(5) - }) - - it('should fold comment ranges', async () => { - disposables.push(languages.registerFoldingRangeProvider([{ language: '*' }], { - provideFoldingRanges(_doc) { - return [FoldingRange.create(1, 3), FoldingRange.create(4, 6, 0, 0, 'comment')] - } - })) - await nvim.call('setline', [1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']]) - let res = await folds.fold('comment') - expect(res).toBe(true) - let closed = await nvim.call('foldclosed', [2]) - expect(closed).toBe(-1) - closed = await nvim.call('foldclosed', [5]) - expect(closed).toBe(5) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/format.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/format.test.ts deleted file mode 100644 index 111265b9..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/format.test.ts +++ /dev/null @@ -1,253 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, Position, Range, TextEdit } from 'vscode-languageserver-protocol' -import languages from '../../languages' -import { disposeAll } from '../../util' -import window from '../../window' -import workspace from '../../workspace' -import Format from '../../handler/format' -import helper, { createTmpFile } from '../helper' - -let nvim: Neovim -let disposables: Disposable[] = [] -let format: Format - -beforeAll(async () => { - let { configurations } = workspace - configurations.updateUserConfig({ 'coc.preferences.formatOnType': true }) - await helper.setup() - nvim = helper.nvim - format = helper.plugin.getHandler().format -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - helper.updateConfiguration('coc.preferences.formatOnSaveFiletypes', []) - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -describe('format handler', () => { - describe('documentFormat', () => { - it('should throw when provider not found', async () => { - let doc = await helper.createDocument() - let err - try { - await format.documentFormat(doc) - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should return false when get empty edits ', async () => { - disposables.push(languages.registerDocumentFormatProvider(['*'], { - provideDocumentFormattingEdits: () => { - return [] - } - })) - let doc = await helper.createDocument() - let res = await format.documentFormat(doc) - expect(res).toBe(false) - }) - }) - - describe('formatOnSave', () => { - it('should not throw when provider not found', async () => { - helper.updateConfiguration('coc.preferences.formatOnSaveFiletypes', ['javascript']) - let filepath = await createTmpFile('') - await helper.edit(filepath) - await nvim.command('setf javascript') - await nvim.setLine('foo') - await nvim.command('silent w') - await helper.wait(100) - }) - - it('should invoke format on save', async () => { - helper.updateConfiguration('coc.preferences.formatOnSaveFiletypes', ['text']) - disposables.push(languages.registerDocumentFormatProvider(['text'], { - provideDocumentFormattingEdits: document => { - let lines = document.getText().replace(/\n$/, '').split(/\n/) - let edits: TextEdit[] = [] - for (let i = 0; i < lines.length; i++) { - let text = lines[i] - if (!text.startsWith(' ')) { - edits.push(TextEdit.insert(Position.create(i, 0), ' ')) - } - } - return edits - } - })) - let filepath = await createTmpFile('a\nb\nc\n') - let buf = await helper.edit(filepath) - await nvim.command('setf text') - await nvim.command('w') - let lines = await buf.lines - expect(lines).toEqual([' a', ' b', ' c']) - }) - - it('should cancel when timeout', async () => { - helper.updateConfiguration('coc.preferences.formatOnSaveFiletypes', ['*']) - disposables.push(languages.registerDocumentFormatProvider(['*'], { - provideDocumentFormattingEdits: () => { - return new Promise(resolve => { - setTimeout(() => { - resolve(undefined) - }, 2000) - }) - } - })) - let filepath = await createTmpFile('a\nb\nc\n') - await helper.edit(filepath) - let n = Date.now() - await nvim.command('w') - expect(Date.now() - n).toBeLessThan(1000) - }) - }) - - describe('rangeFormat', () => { - it('should invoke range format', async () => { - disposables.push(languages.registerDocumentRangeFormatProvider(['text'], { - provideDocumentRangeFormattingEdits: (_document, range) => { - let lines: number[] = [] - for (let i = range.start.line; i <= range.end.line; i++) { - lines.push(i) - } - return lines.map(i => { - return TextEdit.insert(Position.create(i, 0), ' ') - }) - } - })) - let doc = await helper.createDocument() - await nvim.call('setline', [1, ['a', 'b', 'c']]) - await nvim.command('setf text') - await nvim.command('normal! ggvG') - await nvim.input('') - await helper.doAction('formatSelected', 'v') - let buf = nvim.createBuffer(doc.bufnr) - let lines = await buf.lines - expect(lines).toEqual([' a', ' b', ' c']) - }) - - it('should format range by formatexpr option', async () => { - let range: Range - disposables.push(languages.registerDocumentRangeFormatProvider(['text'], { - provideDocumentRangeFormattingEdits: (_document, r) => { - range = r - return [] - } - })) - await helper.createDocument() - await nvim.call('setline', [1, ['a', 'b', 'c']]) - await nvim.command('setf text') - await nvim.command(`setl formatexpr=CocAction('formatSelected')`) - await nvim.command('normal! ggvGgq') - expect(range).toEqual({ - start: { line: 0, character: 0 }, end: { line: 3, character: 0 } - }) - }) - }) - - describe('formatOnType', () => { - it('should invoke format', async () => { - disposables.push(languages.registerDocumentFormatProvider(['text'], { - provideDocumentFormattingEdits: () => { - return [TextEdit.insert(Position.create(0, 0), ' ')] - } - })) - await helper.createDocument() - await nvim.setLine('foo') - await nvim.command('setf text') - await helper.doAction('format') - let line = await nvim.line - expect(line).toEqual(' foo') - }) - - it('should does format on type', async () => { - disposables.push(languages.registerOnTypeFormattingEditProvider(['text'], { - provideOnTypeFormattingEdits: () => { - return [TextEdit.insert(Position.create(0, 0), ' ')] - } - }, ['|'])) - await helper.edit() - await nvim.command('setf text') - await nvim.input('i|') - await helper.wait(200) - let line = await nvim.line - expect(line).toBe(' |') - let cursor = await window.getCursorPosition() - expect(cursor).toEqual({ line: 0, character: 3 }) - }) - - it('should format on new line inserted', async () => { - disposables.push(languages.registerOnTypeFormattingEditProvider(['text'], { - provideOnTypeFormattingEdits: (doc, position) => { - let text = doc.getText() - if (text.startsWith(' ')) return [] - return [TextEdit.insert(Position.create(position.line, 0), ' ')] - } - }, ['\n'])) - let buf = await helper.edit() - await nvim.command('setf text') - await nvim.setLine('foo') - await nvim.input('o') - await helper.wait(100) - let lines = await buf.lines - expect(lines).toEqual([' foo', '']) - }) - - it('should adjust cursor after format on type', async () => { - disposables.push(languages.registerOnTypeFormattingEditProvider(['text'], { - provideOnTypeFormattingEdits: () => { - return [ - TextEdit.insert(Position.create(0, 0), ' '), - TextEdit.insert(Position.create(0, 2), 'end') - ] - } - }, ['|'])) - await helper.edit() - await nvim.command('setf text') - await nvim.setLine('"') - await nvim.input('i|') - await helper.wait(100) - let line = await nvim.line - expect(line).toBe(' |"end') - let cursor = await window.getCursorPosition() - expect(cursor).toEqual({ line: 0, character: 3 }) - }) - }) - - describe('bracketEnterImprove', () => { - afterEach(() => { - nvim.command('iunmap ', true) - }) - - it('should format vim file on enter', async () => { - let buf = await helper.edit('foo.vim') - await nvim.command(`inoremap pumvisible() ? coc#_select_confirm() : "\\u\\\\=coc#on_enter()\\"`) - await nvim.setLine('let foo={}') - await nvim.command(`normal! gg$`) - await nvim.input('i') - await nvim.eval(`feedkeys("\\", 'im')`) - await helper.wait(100) - let lines = await buf.lines - expect(lines).toEqual(['let foo={', ' \\ ', ' \\ }']) - }) - - it('should add new line between bracket', async () => { - let buf = await helper.edit() - await nvim.command(`inoremap pumvisible() ? coc#_select_confirm() : "\\u\\\\=coc#on_enter()\\"`) - await nvim.setLine(' {}') - await nvim.command(`normal! gg$`) - await nvim.input('i') - await nvim.eval(`feedkeys("\\", 'im')`) - await helper.wait(100) - let lines = await buf.lines - expect(lines).toEqual([' {', ' ', ' }']) - }) - }) -}) - diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/highlights.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/highlights.test.ts deleted file mode 100644 index cbcd1890..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/highlights.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, DocumentHighlightKind, Position, Range } from 'vscode-languageserver-protocol' -import Highlights from '../../handler/highlights' -import languages from '../../languages' -import workspace from '../../workspace' -import { disposeAll } from '../../util' -import helper from '../helper' - -let nvim: Neovim -let disposables: Disposable[] = [] -let highlights: Highlights - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - highlights = helper.plugin.getHandler().documentHighlighter -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -function registProvider(): void { - disposables.push(languages.registerDocumentHighlightProvider([{ language: '*' }], { - provideDocumentHighlights: async document => { - let word = await nvim.eval('expand("")') - // let word = document.get - let matches = Array.from((document.getText() as any).matchAll(/\w+/g)) as any[] - let filtered = matches.filter(o => o[0] == word) - return filtered.map((o, i) => { - let start = document.positionAt(o.index) - let end = document.positionAt(o.index + o[0].length) - return { - range: Range.create(start, end), - kind: i % 2 == 0 ? DocumentHighlightKind.Read : DocumentHighlightKind.Write - } - }) - } - })) -} - -describe('document highlights', () => { - - it('should return null when highlights provide not exists', async () => { - let doc = await helper.createDocument() - let res = await highlights.getHighlights(doc, Position.create(0, 0)) - expect(res).toBeNull() - }) - - it('should cancel request on CursorMoved', async () => { - let fn = jest.fn() - languages.registerDocumentHighlightProvider([{ language: '*' }], { - provideDocumentHighlights: (_document, _position, token) => { - return new Promise(resolve => { - token.onCancellationRequested(() => { - clearTimeout(timer) - fn() - resolve([]) - }) - let timer = setTimeout(() => { - resolve([{ range: Range.create(0, 0, 0, 3) }]) - }, 3000) - }) - } - }) - await helper.edit() - await nvim.setLine('foo') - let p = highlights.highlight() - await helper.wait(50) - await nvim.call('cursor', [1, 2]) - await p - expect(fn).toBeCalled() - }) - - it('should add highlights to symbols', async () => { - registProvider() - await helper.createDocument() - await nvim.setLine('foo bar foo') - await helper.doAction('highlight') - let winid = await nvim.call('win_getid') as number - expect(highlights.hasHighlights(winid)).toBe(true) - }) - - it('should return highlight ranges', async () => { - registProvider() - await helper.createDocument() - await nvim.setLine('foo bar foo') - let res = await helper.doAction('symbolRanges') - expect(res.length).toBe(2) - }) - - it('should return null when cursor not in word range', async () => { - disposables.push(languages.registerDocumentHighlightProvider([{ language: '*' }], { - provideDocumentHighlights: () => { - return [{ range: Range.create(0, 0, 0, 3) }] - } - })) - let doc = await helper.createDocument() - await nvim.setLine(' oo') - await nvim.call('cursor', [1, 2]) - let res = await highlights.getHighlights(doc, Position.create(0, 0)) - expect(res).toBeNull() - }) - - it('should not throw when document is command line', async () => { - await nvim.call('feedkeys', ['q:', 'in']) - let doc = await workspace.document - expect(doc.isCommandLine).toBe(true) - let err - try { - await highlights.highlight() - } catch (e) { - err = e - } - await nvim.input('') - expect(err).toBeUndefined() - }) - - it('should not throw when provider not found', async () => { - disposeAll(disposables) - await helper.createDocument() - await nvim.setLine(' oo') - await nvim.call('cursor', [1, 2]) - let err - try { - await highlights.highlight() - } catch (e) { - err = e - } - expect(err).toBeUndefined() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/hover.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/hover.test.ts deleted file mode 100644 index 545d2a20..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/hover.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, MarkedString, Hover, Range, TextEdit, Position } from 'vscode-languageserver-protocol' -import HoverHandler from '../../handler/hover' -import { URI } from 'vscode-uri' -import languages from '../../languages' -import { disposeAll } from '../../util' -import helper, { createTmpFile } from '../helper' - -let nvim: Neovim -let hover: HoverHandler -let disposables: Disposable[] = [] -let hoverResult: Hover -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - hover = helper.plugin.getHandler().hover -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(async () => { - await helper.createDocument() - disposables.push(languages.registerHoverProvider([{ language: '*' }], { - provideHover: (_doc, _pos, _token) => { - return hoverResult - } - })) -}) - -afterEach(async () => { - disposeAll(disposables) - await helper.reset() -}) - -async function getDocumentText(): Promise { - let lines = await nvim.call('getbufline', ['coc://document', 1, '$']) as string[] - return lines.join('\n') -} - -describe('Hover', () => { - describe('onHover', () => { - it('should return false when hover not found', async () => { - hoverResult = null - let res = await hover.onHover('preview') - expect(res).toBe(false) - }) - - it('should show MarkupContent hover', async () => { - hoverResult = { contents: { kind: 'plaintext', value: 'my hover' } } - await hover.onHover('preview') - let res = await getDocumentText() - expect(res).toMatch('my hover') - }) - - it('should show MarkedString hover', async () => { - hoverResult = { contents: 'string hover' } - disposables.push(languages.registerHoverProvider([{ language: '*' }], { - provideHover: (_doc, _pos, _token) => { - return { contents: { language: 'typescript', value: 'language hover' } } - } - })) - await hover.onHover('preview') - let res = await getDocumentText() - expect(res).toMatch('string hover') - expect(res).toMatch('language hover') - }) - - it('should show MarkedString hover array', async () => { - hoverResult = { contents: ['foo', { language: 'typescript', value: 'bar' }] } - await hover.onHover('preview') - let res = await getDocumentText() - expect(res).toMatch('foo') - expect(res).toMatch('bar') - }) - - it('should highlight hover range', async () => { - await nvim.setLine('var') - await nvim.command('normal! 0') - hoverResult = { contents: ['foo'], range: Range.create(0, 0, 0, 3) } - await hover.onHover('preview') - let res = await nvim.call('getmatches') as any[] - expect(res.length).toBe(1) - expect(res[0].group).toBe('CocHoverRange') - await helper.wait(600) - res = await nvim.call('getmatches') - expect(res.length).toBe(0) - }) - }) - - describe('previewHover', () => { - it('should echo hover message', async () => { - hoverResult = { contents: ['foo'] } - let res = await hover.onHover('echo') - expect(res).toBe(true) - let msg = await helper.getCmdline() - expect(msg).toMatch('foo') - }) - - it('should show hover in float window', async () => { - hoverResult = { contents: { kind: 'markdown', value: '```typescript\nconst foo:number\n```' } } - await hover.onHover('float') - let win = await helper.getFloat() - expect(win).toBeDefined() - let lines = await nvim.eval(`getbufline(winbufnr(${win.id}),1,'$')`) - expect(lines).toEqual(['const foo:number']) - }) - }) - - describe('getHover', () => { - it('should get hover from MarkedString array', async () => { - hoverResult = { contents: ['foo', { language: 'typescript', value: 'bar' }] } - disposables.push(languages.registerHoverProvider([{ language: '*' }], { - provideHover: (_doc, _pos, _token) => { - return { contents: { language: 'typescript', value: 'MarkupContent hover' } } - } - })) - disposables.push(languages.registerHoverProvider([{ language: '*' }], { - provideHover: (_doc, _pos, _token) => { - return { contents: MarkedString.fromPlainText('MarkedString hover') } - } - })) - let res = await hover.getHover() - expect(res.includes('foo')).toBe(true) - expect(res.includes('bar')).toBe(true) - expect(res.includes('MarkupContent hover')).toBe(true) - expect(res.includes('MarkedString hover')).toBe(true) - }) - - it('should filter empty hover message', async () => { - hoverResult = { contents: [''] } - let res = await hover.getHover() - expect(res.length).toBe(0) - }) - }) - - describe('definitionHover', () => { - it('should load definition from buffer', async () => { - hoverResult = { contents: 'string hover' } - let doc = await helper.createDocument() - await nvim.call('cursor', [1, 1]) - await doc.applyEdits([TextEdit.insert(Position.create(0, 0), 'foo\nbar')]) - disposables.push(languages.registerDefinitionProvider([{ language: '*' }], { - provideDefinition() { - return [{ - targetUri: doc.uri, - targetRange: Range.create(0, 0, 1, 3), - targetSelectionRange: Range.create(0, 0, 0, 3), - }] - } - })) - await hover.definitionHover('preview') - let res = await getDocumentText() - expect(res).toBe('string hover\n\nfoo\nbar') - }) - - it('should load definition link from file', async () => { - let fsPath = await createTmpFile('foo\nbar\n') - hoverResult = { contents: 'string hover' } - let doc = await helper.createDocument() - await nvim.call('cursor', [1, 1]) - await doc.applyEdits([TextEdit.insert(Position.create(0, 0), 'foo\nbar')]) - disposables.push(languages.registerDefinitionProvider([{ language: '*' }], { - provideDefinition() { - return [{ - targetUri: URI.file(fsPath).toString(), - targetRange: Range.create(0, 0, 1, 3), - targetSelectionRange: Range.create(0, 0, 0, 3), - }] - } - })) - await hover.definitionHover('preview') - let res = await getDocumentText() - expect(res).toBe('string hover\n\nfoo\nbar') - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/index.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/index.test.ts deleted file mode 100644 index a66ddc46..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/index.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import Handler from '../../handler/index' -import { disposeAll } from '../../util' -import helper from '../helper' - -let nvim: Neovim -let handler: Handler -let disposables: Disposable[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - handler = (helper.plugin as any).handler -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(async () => { - await helper.createDocument() -}) - -afterEach(async () => { - disposeAll(disposables) - await helper.reset() -}) - -describe('Handler', () => { - describe('hasProvider', () => { - it('should check provider for document', async () => { - let res = await handler.hasProvider('definition') - expect(res).toBe(false) - }) - }) - - describe('checkProvier', () => { - it('should throw error when provider not found', async () => { - let doc = await helper.createDocument() - let err - try { - handler.checkProvier('definition', doc.textDocument) - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - }) - - describe('withRequestToken', () => { - it('should cancel previous request when called again', async () => { - let cancelled = false - let p = handler.withRequestToken('test', token => { - return new Promise(s => { - token.onCancellationRequested(() => { - cancelled = true - clearTimeout(timer) - s(undefined) - }) - let timer = setTimeout(() => { - s(undefined) - }, 3000) - }) - }, false) - setTimeout(async () => { - await handler.withRequestToken('test', () => { - return Promise.resolve(undefined) - }, false) - }, 50) - await p - expect(cancelled).toBe(true) - }) - - it('should cancel request on insert start', async () => { - let cancelled = false - let p = handler.withRequestToken('test', token => { - return new Promise(s => { - token.onCancellationRequested(() => { - cancelled = true - clearTimeout(timer) - s(undefined) - }) - let timer = setTimeout(() => { - s(undefined) - }, 3000) - }) - }, false) - await nvim.input('i') - await p - expect(cancelled).toBe(true) - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/links.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/links.test.ts deleted file mode 100644 index 5fe97761..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/links.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, DocumentLink, Range } from 'vscode-languageserver-protocol' -import LinksHandler from '../../handler/links' -import languages from '../../languages' -import { disposeAll } from '../../util' -import helper from '../helper' - -let nvim: Neovim -let links: LinksHandler -let disposables: Disposable[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - links = (helper.plugin as any).handler.links -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(async () => { - await helper.createDocument() -}) - -afterEach(async () => { - disposeAll(disposables) - await helper.reset() -}) - -describe('Links', () => { - it('should get document links', async () => { - disposables.push(languages.registerDocumentLinkProvider([{ language: '*' }], { - provideDocumentLinks: (_doc, _token) => { - return [ - DocumentLink.create(Range.create(0, 0, 0, 5), 'test:///foo'), - DocumentLink.create(Range.create(1, 0, 1, 5), 'test:///bar') - ] - } - })) - let res = await links.getLinks() - expect(res.length).toBe(2) - }) - - it('should throw error when link target not resolved', async () => { - disposables.push(languages.registerDocumentLinkProvider([{ language: '*' }], { - provideDocumentLinks(_doc, _token) { - return [ - DocumentLink.create(Range.create(0, 0, 0, 5)) - ] - }, - resolveDocumentLink(link) { - return link - } - })) - let res = await links.getLinks() - let err - try { - await links.openLink(res[0]) - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should open link at current position', async () => { - await nvim.setLine('foo') - await nvim.command('normal! 0') - disposables.push(languages.registerDocumentLinkProvider([{ language: '*' }], { - provideDocumentLinks(_doc, _token) { - return [ - DocumentLink.create(Range.create(0, 0, 0, 5)), - ] - }, - resolveDocumentLink(link) { - link.target = 'test:///foo' - return link - } - })) - await links.openCurrentLink() - let bufname = await nvim.call('bufname', '%') - expect(bufname).toBe('test:///foo') - await nvim.call('setline', [1, ['a', 'b', 'c']]) - await nvim.call('cursor', [3, 1]) - let res = await links.openCurrentLink() - expect(res).toBe(false) - }) - - it('should return false when current links not found', async () => { - await nvim.setLine('foo') - await nvim.command('normal! 0') - disposables.push(languages.registerDocumentLinkProvider([{ language: '*' }], { - provideDocumentLinks(_doc, _token) { - return [] - } - })) - let res = await links.openCurrentLink() - expect(res).toBe(false) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/locations.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/locations.test.ts deleted file mode 100644 index b45ddcbb..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/locations.test.ts +++ /dev/null @@ -1,308 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, LocationLink, Location, Range } from 'vscode-languageserver-protocol' -import LocationHandler from '../../handler/locations' -import languages from '../../languages' -import services from '../../services' -import workspace from '../../workspace' -import { disposeAll } from '../../util' -import helper from '../helper' -import { URI } from 'vscode-uri' - -let nvim: Neovim -let locations: LocationHandler -let disposables: Disposable[] = [] -let currLocations: Location[] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - Object.assign(workspace.env, { - locationlist: false - }) - locations = helper.plugin.getHandler().locations -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(async () => { - await helper.createDocument() -}) - -afterEach(async () => { - disposeAll(disposables) - await helper.reset() -}) - -function createLocation(name: string, sl: number, sc: number, el: number, ec: number): Location { - return Location.create(`test://${name}`, Range.create(sl, sc, el, ec)) -} - -describe('locations', () => { - describe('reference', () => { - beforeEach(() => { - disposables.push(languages.registerReferencesProvider([{ language: '*' }], { - provideReferences: () => { - return currLocations - } - })) - }) - - it('should get references', async () => { - currLocations = [createLocation('foo', 0, 0, 0, 0), createLocation('bar', 0, 0, 0, 0)] - let res = await locations.references() - expect(res.length).toBe(2) - }) - - it('should jump to references', async () => { - currLocations = [createLocation('foo', 0, 0, 0, 0)] - let res = await locations.gotoReferences('edit', true) - expect(res).toBe(true) - let name = await nvim.call('bufname', ['%']) - expect(name).toBe('test://foo') - }) - - it('should return false when references not found', async () => { - currLocations = [] - let res = await locations.gotoReferences('edit', true) - expect(res).toBe(false) - }) - }) - - describe('definition', () => { - beforeEach(() => { - disposables.push(languages.registerDefinitionProvider([{ language: '*' }], { - provideDefinition: () => { - return currLocations - } - })) - }) - - it('should get definitions', async () => { - currLocations = [createLocation('foo', 0, 0, 0, 0), createLocation('bar', 0, 0, 0, 0)] - let res = await locations.definitions() - expect(res.length).toBe(2) - }) - - it('should jump to definitions', async () => { - currLocations = [createLocation('foo', 0, 0, 0, 0)] - let res = await locations.gotoDefinition('edit') - expect(res).toBe(true) - let name = await nvim.call('bufname', ['%']) - expect(name).toBe('test://foo') - }) - - it('should return false when definitions not found', async () => { - currLocations = [] - let res = await locations.gotoDefinition('edit') - expect(res).toBe(false) - }) - }) - - describe('declaration', () => { - beforeEach(() => { - disposables.push(languages.registerDeclarationProvider([{ language: '*' }], { - provideDeclaration: () => { - return currLocations - } - })) - }) - - it('should get declarations', async () => { - currLocations = [createLocation('foo', 0, 0, 0, 0), createLocation('bar', 0, 0, 0, 0)] - let res = await locations.declarations() as Location[] - expect(res.length).toBe(2) - }) - - it('should jump to declaration', async () => { - currLocations = [createLocation('foo', 0, 0, 0, 0)] - let res = await locations.gotoDeclaration('edit') - expect(res).toBe(true) - let name = await nvim.call('bufname', ['%']) - expect(name).toBe('test://foo') - }) - - it('should return false when declaration not found', async () => { - currLocations = [] - let res = await locations.gotoDeclaration('edit') - expect(res).toBe(false) - }) - }) - - describe('typeDefinition', () => { - beforeEach(() => { - disposables.push(languages.registerTypeDefinitionProvider([{ language: '*' }], { - provideTypeDefinition: () => { - return currLocations - } - })) - }) - - it('should get type definition', async () => { - currLocations = [createLocation('foo', 0, 0, 0, 0), createLocation('bar', 0, 0, 0, 0)] - let res = await locations.typeDefinitions() as Location[] - expect(res.length).toBe(2) - }) - - it('should jump to type definition', async () => { - currLocations = [createLocation('foo', 0, 0, 0, 0)] - let res = await locations.gotoTypeDefinition('edit') - expect(res).toBe(true) - let name = await nvim.call('bufname', ['%']) - expect(name).toBe('test://foo') - }) - - it('should return false when type definition not found', async () => { - currLocations = [] - let res = await locations.gotoTypeDefinition('edit') - expect(res).toBe(false) - }) - }) - - describe('implementation', () => { - beforeEach(() => { - disposables.push(languages.registerImplementationProvider([{ language: '*' }], { - provideImplementation: () => { - return currLocations - } - })) - }) - - it('should get implementations', async () => { - currLocations = [createLocation('foo', 0, 0, 0, 0), createLocation('bar', 0, 0, 0, 0)] - let res = await locations.implementations() as Location[] - expect(res.length).toBe(2) - }) - - it('should jump to implementation', async () => { - currLocations = [createLocation('foo', 0, 0, 0, 0)] - let res = await locations.gotoImplementation('edit') - expect(res).toBe(true) - let name = await nvim.call('bufname', ['%']) - expect(name).toBe('test://foo') - }) - - it('should return false when implementation not found', async () => { - currLocations = [] - let res = await locations.gotoImplementation('edit') - expect(res).toBe(false) - }) - }) - - describe('getTagList', () => { - it('should return null when cword not exists', async () => { - let res = await locations.getTagList() - expect(res).toBe(null) - }) - - it('should return null when provider not exists', async () => { - await nvim.setLine('foo') - await nvim.command('normal! ^') - let res = await locations.getTagList() - expect(res).toBe(null) - }) - - it('should return null when result is empty', async () => { - disposables.push(languages.registerDefinitionProvider([{ language: '*' }], { - provideDefinition: () => { - return [] - } - })) - await nvim.setLine('foo') - await nvim.command('normal! ^') - let res = await locations.getTagList() - expect(res).toBe(null) - }) - - it('should return tag definitions', async () => { - disposables.push(languages.registerDefinitionProvider([{ language: '*' }], { - provideDefinition: () => { - return [createLocation('bar', 2, 0, 2, 5), Location.create(URI.file('/foo').toString(), Range.create(1, 0, 1, 5))] - } - })) - await nvim.setLine('foo') - await nvim.command('normal! ^') - let res = await locations.getTagList() - expect(res).toEqual([ - { - name: 'foo', - cmd: 'keepjumps 3 | normal 1|', - filename: 'test://bar' - }, - { name: 'foo', cmd: 'keepjumps 2 | normal 1|', filename: '/foo' } - ]) - }) - }) - - describe('findLocations', () => { - // hook result - let fn - let result: any - beforeAll(() => { - fn = services.sendRequest - services.sendRequest = () => { - return Promise.resolve(result) - } - }) - - afterAll(() => { - services.sendRequest = fn - }) - - it('should handle locations from language client', async () => { - result = [createLocation('bar', 2, 0, 2, 5)] - await locations.findLocations('foo', 'mylocation', {}, false) - let res = await nvim.getVar('coc_jump_locations') - expect(res).toEqual([{ - uri: 'test://bar', - lnum: 3, - end_lnum: 3, - col: 1, - end_col: 6, - filename: 'test://bar', - text: '', - range: Range.create(2, 0, 2, 5) - }]) - }) - - it('should handle nested locations', async () => { - let location: any = { - location: createLocation('file', 0, 0, 0, 0), - children: [{ - location: createLocation('foo', 3, 0, 3, 5), - children: [] - }, { - location: createLocation('bar', 4, 0, 4, 5), - children: [] - }] - } - result = location - await locations.findLocations('foo', 'mylocation', {}, false) - let res = await nvim.getVar('coc_jump_locations') as any[] - expect(res.length).toBe(3) - }) - }) - - describe('handleLocations', () => { - it('should not throw when location is undefined', async () => { - await locations.handleLocations(null) - }) - - it('should not throw when locations is empty array', async () => { - await locations.handleLocations([]) - }) - - it('should handle single location', async () => { - await locations.handleLocations(createLocation('single', 0, 0, 0, 0)) - let bufname = await nvim.call('bufname', ['%']) - expect(bufname).toBe('test://single') - }) - - it('should handle location link', async () => { - let link = LocationLink.create('test://link', Range.create(0, 0, 0, 3), Range.create(1, 0, 1, 3)) - await locations.handleLocations([link]) - let bufname = await nvim.call('bufname', ['%']) - expect(bufname).toBe('test://link') - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/outline.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/outline.test.ts deleted file mode 100644 index c8e29dea..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/outline.test.ts +++ /dev/null @@ -1,426 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import { CancellationToken, CodeAction, CodeActionContext, CodeActionKind, Disposable, Range, SymbolTag, TextEdit } from 'vscode-languageserver-protocol' -import events from '../../events' -import Symbols from '../../handler/symbols/index' -import languages from '../../languages' -import { ProviderResult } from '../../provider' -import { disposeAll } from '../../util' -import workspace from '../../workspace' -import helper from '../helper' -import Parser from './parser' - -let nvim: Neovim -let symbols: Symbols -let disposables: Disposable[] = [] - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - symbols = helper.plugin.getHandler().symbols -}) - -beforeEach(() => { - disposables.push(languages.registerDocumentSymbolProvider([{ language: 'javascript' }], { - provideDocumentSymbols: document => { - let parser = new Parser(document.getText()) - let res = parser.parse() - if (res.length) { - res[0].tags = [SymbolTag.Deprecated] - } - return Promise.resolve(res) - } - })) -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -async function getOutlineBuffer(): Promise { - let winid = await nvim.call('coc#window#find', ['cocViewId', 'OUTLINE']) - if (winid == -1) return undefined - let bufnr = await nvim.call('winbufnr', [winid]) - if (bufnr == -1) return undefined - return nvim.createBuffer(bufnr) -} - -describe('symbols outline', () => { - - let defaultCode = `class myClass { - fun1() { } - fun2() {} -}` - - async function createBuffer(code = defaultCode): Promise { - await helper.edit() - let buf = await nvim.buffer - await nvim.command('setf javascript') - await buf.setLines(code.split('\n'), { start: 0, end: -1, strictIndexing: false }) - let doc = await workspace.document - doc.forceSync() - return buf - } - - describe('configuration', () => { - afterEach(() => { - let { configurations } = workspace - configurations.updateUserConfig({ - 'outline.splitCommand': 'botright 30vs', - 'outline.followCursor': true, - 'outline.keepWindow': false, - 'outline.sortBy': 'category', - 'outline.expandLevel': 1, - 'outline.checkBufferSwitch': true - }) - }) - - it('should follow cursor', async () => { - await createBuffer() - let curr = await nvim.call('bufnr', ['%']) - await symbols.showOutline(0) - let bufnr = await nvim.call('bufnr', ['%']) - await nvim.command('wincmd p') - await nvim.command('exe 3') - await events.fire('CursorHold', [curr]) - await helper.wait(50) - let buf = nvim.createBuffer(bufnr) - let lines = await buf.getLines() - expect(lines).toEqual([ - 'OUTLINE', '- c myClass 1', ' m fun1 2', ' m fun2 3' - ]) - let signs = await buf.getSigns({ group: 'CocTree' }) - expect(signs.length).toBe(1) - expect(signs[0]).toEqual({ - lnum: 2, - id: 3001, - name: 'CocTreeSelected', - priority: 10, - group: 'CocTree' - }) - }) - - it('should not follow cursor', async () => { - workspace.configurations.updateUserConfig({ - 'outline.followCursor': false, - }) - await createBuffer() - let curr = await nvim.call('bufnr', ['%']) - await symbols.showOutline(0) - let bufnr = await nvim.call('bufnr', ['%']) - await nvim.command('wincmd p') - await nvim.command('exe 3') - await events.fire('CursorHold', [curr]) - await helper.wait(50) - let buf = nvim.createBuffer(bufnr) - let signs = await buf.getSigns({ group: 'CocTree' }) - expect(signs.length).toBe(0) - }) - - it('should keep current window', async () => { - workspace.configurations.updateUserConfig({ - 'outline.keepWindow': true, - }) - await createBuffer() - let curr = await nvim.call('bufnr', ['%']) - await symbols.showOutline() - let bufnr = await nvim.call('bufnr', ['%']) - expect(curr).toBe(bufnr) - }) - - it('should check on buffer switch', async () => { - workspace.configurations.updateUserConfig({ - 'outline.checkBufferSwitch': true, - }) - await createBuffer() - await symbols.showOutline(1) - await helper.edit('unnamed') - await helper.wait(300) - let buf = await getOutlineBuffer() - let lines = await buf.lines - expect(lines).toEqual(['Document symbol provider not found']) - }) - - it('should not check on buffer switch', async () => { - workspace.configurations.updateUserConfig({ - 'outline.checkBufferSwitch': false - }) - await helper.wait(30) - await createBuffer() - await symbols.showOutline(1) - await helper.edit('unnamed') - await helper.wait(100) - let buf = await getOutlineBuffer() - let lines = await buf.lines - expect(lines).toEqual([ - 'OUTLINE', '- c myClass 1', ' m fun1 2', ' m fun2 3' - ]) - }) - - it('should not check on buffer reload', async () => { - workspace.configurations.updateUserConfig({ - 'outline.checkBufferSwitch': false - }) - await symbols.showOutline(1) - await helper.wait(50) - await createBuffer() - await helper.wait(50) - let buf = await getOutlineBuffer() - expect(buf).toBeUndefined() - }) - - it('should sort by position', async () => { - let code = `class myClass { - fun2() { } - fun1() {} -}` - workspace.configurations.updateUserConfig({ - 'outline.sortBy': 'position', - }) - await createBuffer(code) - await symbols.showOutline(1) - let buf = await getOutlineBuffer() - let lines = await buf.lines - expect(lines).toEqual([ - 'OUTLINE', '- c myClass 1', ' m fun2 2', ' m fun1 3' - ]) - }) - - it('should sort by name', async () => { - let code = `class myClass { - fun2() {} - fun1() {} -}` - workspace.configurations.updateUserConfig({ - 'outline.sortBy': 'name', - }) - await createBuffer(code) - await symbols.showOutline(1) - let buf = await getOutlineBuffer() - let lines = await buf.lines - expect(lines).toEqual([ - 'OUTLINE', '- c myClass 1', ' m fun1 3', ' m fun2 2' - ]) - }) - }) - - describe('events', () => { - - it('should dispose on buffer unload', async () => { - await createBuffer() - let curr = await nvim.call('bufnr', ['%']) - await symbols.showOutline(0) - await nvim.command('tabe') - await nvim.command(`bd! ${curr}`) - await helper.wait(30) - let buf = await getOutlineBuffer() - expect(buf).toBeUndefined() - }) - - it('should check current window on BufEnter', async () => { - await createBuffer() - await symbols.showOutline(0) - let winid = await nvim.call('win_getid', []) - await nvim.command('enew') - await helper.wait(200) - let win = await nvim.window - expect(win.id).toBe(winid) - }) - - it('should recreated when original window exists', async () => { - await symbols.showOutline(1) - await helper.wait(50) - await createBuffer() - await helper.wait(50) - let buf = await getOutlineBuffer() - expect(buf).toBeDefined() - }) - - it('should keep old outline when new buffer not attached', async () => { - await createBuffer() - await symbols.showOutline(1) - await nvim.command(`vnew +setl\\ buftype=nofile`) - await helper.wait(50) - let buf = await getOutlineBuffer() - expect(buf).toBeDefined() - let lines = await buf.lines - expect(lines).toEqual([ - 'OUTLINE', '- c myClass 1', ' m fun1 2', ' m fun2 3' - ]) - }) - - it('should not reload when switch to original buffer', async () => { - await createBuffer() - await symbols.showOutline(0) - let buf = await getOutlineBuffer() - let name = await buf.name - await nvim.command('wincmd p') - await helper.wait(50) - buf = await getOutlineBuffer() - let curr = await buf.name - expect(curr).toBe(name) - }) - - it('should dispose provider on outline hide', async () => { - await createBuffer() - let bufnr = await nvim.call('bufnr', ['%']) - await symbols.showOutline(0) - await nvim.command('q') - await helper.wait(30) - let exists = symbols.hasOutline(bufnr) - expect(exists).toBe(false) - }) - }) - - describe('show()', () => { - it('should throw when document not attached', async () => { - await nvim.command(`edit +setl\\ buftype=nofile t`) - await helper.wait(50) - let err - try { - await symbols.showOutline(1) - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should not throw when provider not exists', async () => { - await symbols.showOutline(1) - let buf = await getOutlineBuffer() - expect(buf).toBeDefined() - }) - - it('should not throw when symbols is empty', async () => { - await createBuffer('') - await symbols.showOutline(1) - let buf = await getOutlineBuffer() - expect(buf).toBeDefined() - }) - - it('should jump to selected symbol', async () => { - await createBuffer() - let bufnr = await nvim.call('bufnr', ['%']) - await symbols.showOutline(0) - await helper.wait(50) - await nvim.command('exe 3') - await nvim.input('') - await helper.wait(50) - let curr = await nvim.call('bufnr', ['%']) - expect(curr).toBe(bufnr) - let cursor = await nvim.call('coc#cursor#position') - expect(cursor).toEqual([1, 2]) - }) - - it('should update symbols', async () => { - await createBuffer() - let doc = await workspace.document - let bufnr = await nvim.call('bufnr', ['%']) - await symbols.showOutline(1) - await helper.wait(10) - let buf = nvim.createBuffer(bufnr) - let code = 'class foo{}' - await buf.setLines(code.split('\n'), { - start: 0, - end: -1, - strictIndexing: false - }) - await doc.synchronize() - await helper.wait(200) - buf = await getOutlineBuffer() - let lines = await buf.lines - expect(lines).toEqual([ - 'No results', - '', - 'OUTLINE' - ]) - }) - }) - - describe('actions', () => { - it('should invoke visual select', async () => { - await createBuffer() - let bufnr = await nvim.call('bufnr', ['%']) - await symbols.showOutline(0) - await helper.wait(50) - await nvim.command('exe 3') - await nvim.input('') - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - let m = await nvim.mode - expect(m.mode).toBe('v') - let buf = await nvim.buffer - expect(buf.id).toBe(bufnr) - }) - - it('should invoke selected code action', async () => { - const codeAction = CodeAction.create('my action', CodeActionKind.Refactor) - let uri: string - disposables.push(languages.registerCodeActionProvider([{ language: '*' }], { - provideCodeActions: ( - _document, - _range: Range, - _context: CodeActionContext, - _token: CancellationToken - ) => [codeAction], - resolveCodeAction: (action): ProviderResult => { - action.edit = { - changes: { - [uri]: [TextEdit.del(Range.create(0, 0, 0, 5))] - } - } - return action - } - }, undefined)) - await createBuffer() - let bufnr = await nvim.call('bufnr', ['%']) - let doc = workspace.getDocument(bufnr) - uri = doc.uri - await symbols.showOutline(0) - await helper.wait(50) - await nvim.command('exe 3') - await nvim.input('') - await helper.wait(50) - await nvim.input('') - await helper.wait(200) - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines[0]).toBe(' myClass {') - }) - }) - - describe('hide()', () => { - it('should hide outline', async () => { - await createBuffer('') - await symbols.showOutline(0) - await symbols.hideOutline() - let buf = await getOutlineBuffer() - expect(buf).toBeUndefined() - }) - - it('should not throw when outline not exists', async () => { - await symbols.hideOutline() - let buf = await getOutlineBuffer() - expect(buf).toBeUndefined() - }) - }) - - describe('dispose', () => { - it('should dispose provider and views', async () => { - await createBuffer('') - let bufnr = await nvim.call('bufnr', ['%']) - await symbols.showOutline(1) - symbols.dispose() - await helper.wait(50) - expect(symbols.hasOutline(bufnr)).toBe(false) - let buf = await getOutlineBuffer() - expect(buf).toBeUndefined() - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/parser.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/parser.ts deleted file mode 100644 index a4a29fae..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/parser.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DocumentSymbol, SymbolKind, Range } from 'vscode-languageserver-protocol' - -/** - * A syntax parser that parse `class` and `method` only. - */ -export default class Parser { - private _curr = 0 - private _symbols: DocumentSymbol[] = [] - private currSymbol: DocumentSymbol | undefined - private len: number - private textDocument: TextDocument - constructor(private _content: string) { - this.len = _content.length - this.textDocument = TextDocument.create('test:///a', 'txt', 1, _content) - } - - public parse(): DocumentSymbol[] { - while (this._curr <= this.len - 1) { - this.parseToken() - } - return this._symbols - } - - /** - * Parse a symbol, reset currSymbol & _curr - */ - private parseToken(): void { - this.skipSpaces() - if (this.currSymbol) { - let endOffset = this.textDocument.offsetAt(this.currSymbol.range.end) - if (this._curr > endOffset) { - this.currSymbol = undefined - } - } - let remain = this.getLineRemian() - let ms = remain.match(/^(class)\s(\w+)\s\{\s*/) - if (ms) { - // find class - let start = this._curr + 6 - let end = start + ms[2].length - let selectionRange = Range.create(this.textDocument.positionAt(start), this.textDocument.positionAt(end)) - let endPosition = this.findMatchedIndex(this._curr + ms[0].length) - let range = Range.create(this.textDocument.positionAt(this._curr), this.textDocument.positionAt(endPosition)) - let symbolInfo: DocumentSymbol = { - range, - selectionRange, - kind: SymbolKind.Class, - name: ms[2], - children: [] - } - if (this.currSymbol && this.currSymbol.children) { - this.currSymbol.children.push(symbolInfo) - } else { - this._symbols.push(symbolInfo) - } - this.currSymbol = symbolInfo - } else if (this.currSymbol && this.currSymbol.kind == SymbolKind.Class) { - let ms = remain.match(/(\w+)\(.*\)\s*\{/) - if (ms) { - // find method - let start = this._curr - let end = start + ms[1].length - let selectionRange = Range.create(this.textDocument.positionAt(start), this.textDocument.positionAt(end)) - let endPosition = this.findMatchedIndex(this._curr + ms[0].length) - let range = Range.create(this.textDocument.positionAt(this._curr), this.textDocument.positionAt(endPosition)) - let symbolInfo: DocumentSymbol = { - range, - selectionRange, - kind: SymbolKind.Method, - name: ms[1] - } - if (this.currSymbol && this.currSymbol.children) { - this.currSymbol.children.push(symbolInfo) - } else { - this._symbols.push(symbolInfo) - } - } - } - this._curr = this._curr + remain.length + 1 - } - - private findMatchedIndex(start: number): number { - let level = 0 - for (let i = start; i < this.len; i++) { - let ch = this._content[i] - if (ch == '{') { - level = level + 1 - } - if (ch == '}') { - if (level == 0) return i - level = level - 1 - } - } - throw new Error(`Can't find matched }`) - } - - private getLineRemian(): string { - let chars = '' - for (let i = this._curr; i < this.len; i++) { - let ch = this._content[i] - if (ch == '\n') break - chars = chars + ch - } - return chars - } - - private skipSpaces(): void { - for (let i = this._curr; i < this.len; i++) { - let ch = this._content[i] - if (!ch || /\S/.test(ch)) { - this._curr = i - break - } - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/refactor.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/refactor.test.ts deleted file mode 100644 index 63046445..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/refactor.test.ts +++ /dev/null @@ -1,347 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import fs from 'fs' -import { URI } from 'vscode-uri' -import Refactor, { FileItem } from '../../handler/refactor/index' -import helper, { createTmpFile } from '../helper' -import languages from '../../languages' -import { WorkspaceEdit, Range } from 'vscode-languageserver-types' -import { Disposable } from '@chemzqm/neovim/lib/api/Buffer' - -let nvim: Neovim -let refactor: Refactor - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - refactor = helper.plugin.getHandler().refactor -}) - -beforeEach(async () => { -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - refactor.reset() - await helper.reset() -}) - -describe('refactor', () => { - describe('create', () => { - it('should create from workspaceEdit', async () => { - let changes = { - [URI.file(__filename).toString()]: [{ - range: Range.create(0, 0, 0, 6), - newText: '' - }, { - range: Range.create(1, 0, 1, 6), - newText: '' - }] - } - let edit: WorkspaceEdit = { changes } - let buf = await refactor.fromWorkspaceEdit(edit) - let shown = await buf.valid - expect(shown).toBe(true) - let items = buf.fileItems - expect(items.length).toBe(1) - }) - - it('should create from locations', async () => { - let uri = URI.file(__filename).toString() - let locations = [{ - uri, - range: Range.create(0, 0, 0, 6), - }, { - uri, - range: Range.create(1, 0, 1, 6), - }] - let buf = await refactor.fromLocations(locations) - let shown = await buf.valid - expect(shown).toBe(true) - let items = buf.fileItems - expect(items.length).toBe(1) - }) - }) - - describe('onChange', () => { - it('should ignore when change after range', async () => { - let doc = await helper.createDocument() - await doc.buffer.append(['foo', 'bar']) - await refactor.fromLocations([{ uri: doc.uri, range: Range.create(0, 0, 0, 3) }]) - let lines = await nvim.call('getline', [1, '$']) - await doc.buffer.append(['def']) - doc.forceSync() - await helper.wait(100) - let newLines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(newLines) - }) - - it('should adjust when change before range', async () => { - let doc = await helper.createDocument() - await doc.buffer.append(['', '', '', '', 'foo', 'bar']) - await helper.wait(50) - doc.forceSync() - let buf = await refactor.fromLocations([{ uri: doc.uri, range: Range.create(4, 0, 4, 3) }]) - await doc.buffer.setLines(['def'], { start: 0, end: 0, strictIndexing: false }) - doc.forceSync() - await helper.wait(100) - let fileRange = buf.getFileRange(4) - expect(fileRange.start).toBe(2) - expect(fileRange.end).toBe(8) - }) - - it('should removed when lines empty', async () => { - let doc = await helper.createDocument() - await doc.buffer.append(['', '', '', '', 'foo', 'bar']) - await helper.wait(50) - doc.forceSync() - let buf = await refactor.fromLocations([{ uri: doc.uri, range: Range.create(4, 0, 4, 3) }]) - await doc.buffer.setLines([], { start: 0, end: -1, strictIndexing: false }) - doc.forceSync() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines.length).toBe(3) - let items = buf.fileItems - expect(items.length).toBe(0) - }) - - it('should change when liens changed', async () => { - let doc = await helper.createDocument() - await doc.buffer.append(['', '', '', '', 'foo', 'bar']) - await helper.wait(50) - doc.forceSync() - await refactor.fromLocations([{ uri: doc.uri, range: Range.create(4, 0, 4, 3) }]) - await doc.buffer.setLines(['def'], { start: 5, end: 6, strictIndexing: false }) - doc.forceSync() - await helper.wait(30) - let lines = await nvim.call('getline', [1, '$']) - expect(lines[lines.length - 2]).toBe('def') - }) - }) - - describe('refactor#getFileChanges', () => { - it('should get changes #1', async () => { - await helper.createDocument() - let lines = ` -Save current buffer to make changes -\u3000 -\u3000 -\u3000/a.ts - }) - } ` - let buf = await refactor.fromLines(lines.split('\n')) - let changes = await buf.getFileChanges() - expect(changes).toEqual([{ lnum: 5, filepath: '/a.ts', lines: [' })', ' } '] }]) - }) - - it('should get changes #2', async () => { - let lines = ` -\u3000/a.ts - }) - } ` - let buf = await refactor.fromLines(lines.split('\n')) - let changes = await buf.getFileChanges() - expect(changes).toEqual([{ lnum: 2, filepath: '/a.ts', lines: [' })', ' } '] }]) - }) - - it('should get changes #3', async () => { - let lines = ` -\u3000/a.ts - }) - } -\u3000` - let buf = await refactor.fromLines(lines.split('\n')) - let changes = await buf.getFileChanges() - expect(changes).toEqual([{ lnum: 2, filepath: '/a.ts', lines: [' })', ' }'] }]) - }) - - it('should get changes #4', async () => { - let lines = ` -\u3000/a.ts -foo -\u3000/b.ts -bar -\u3000` - let buf = await refactor.fromLines(lines.split('\n')) - let changes = await buf.getFileChanges() - expect(changes).toEqual([ - { filepath: '/a.ts', lnum: 2, lines: ['foo'] }, - { filepath: '/b.ts', lnum: 4, lines: ['bar'] } - ]) - }) - }) - - describe('Refactor#createRefactorBuffer', () => { - it('should create refactor buffer', async () => { - await helper.createDocument() - let winid = await nvim.call('win_getid') - let buf = await refactor.createRefactorBuffer() - let curr = await nvim.call('win_getid') - expect(curr).toBeGreaterThan(winid) - let valid = await buf.valid - expect(valid).toBe(true) - }) - - it('should jump to position by ', async () => { - await helper.createDocument() - let buf = await refactor.createRefactorBuffer() - let fileItem: FileItem = { - filepath: __filename, - ranges: [{ start: 10, end: 11 }, { start: 15, end: 20 }] - } - await buf.addFileItems([fileItem]) - await nvim.call('cursor', [5, 1]) - await buf.splitOpen() - let line = await nvim.eval('line(".")') - let bufname = await nvim.eval('bufname("%")') - expect(bufname).toMatch('refactor.test.ts') - expect(line).toBe(11) - }) - }) - - describe('Refactor#saveRefactor', () => { - it('should adjust line ranges after change', async () => { - let filename = await createTmpFile('foo\n\nbar\n') - let fileItem: FileItem = { - filepath: filename, - ranges: [{ start: 0, end: 1 }, { start: 2, end: 3 }] - } - let buf = await refactor.createRefactorBuffer() - await buf.addFileItems([fileItem]) - nvim.pauseNotification() - nvim.call('setline', [5, ['xyz']], true) - nvim.command('undojoin', true) - nvim.call('append', [5, ['de']], true) - nvim.command('undojoin', true) - nvim.call('append', [8, ['bar']], true) - await nvim.resumeNotification() - await helper.wait(100) - let res = await refactor.save(buf.buffer.id) - expect(res).toBe(true) - let content = fs.readFileSync(filename, 'utf8') - expect(content).toBe('xyz\nde\n\nbar\nbar\n') - }) - - it('should not save when no change made', async () => { - let buf = await refactor.createRefactorBuffer() - let fileItem: FileItem = { - filepath: __filename, - ranges: [{ start: 10, end: 11 }, { start: 15, end: 20 }] - } - await buf.addFileItems([fileItem]) - let res = await buf.save() - expect(res).toBe(false) - }) - - it('should sync buffer change to file', async () => { - let doc = await helper.createDocument() - await doc.buffer.replace(['foo', 'bar', 'line'], 0) - await helper.wait(30) - let filename = URI.parse(doc.uri).fsPath - let fileItem: FileItem = { - filepath: filename, - ranges: [{ start: 0, end: 2 }] - } - let buf = await refactor.createRefactorBuffer() - await buf.addFileItems([fileItem]) - await nvim.call('setline', [5, 'changed']) - let res = await buf.save() - expect(res).toBe(true) - expect(fs.existsSync(filename)).toBe(true) - let content = fs.readFileSync(filename, 'utf8') - let lines = content.split('\n') - expect(lines).toEqual(['changed', 'bar', 'line', '']) - fs.unlinkSync(filename) - }) - }) - - describe('doRefactor', () => { - let disposable: Disposable - - afterEach(() => { - if (disposable) disposable.dispose() - disposable = null - }) - - it('should throw when rename provider not found', async () => { - await helper.createDocument() - let err - try { - await refactor.doRefactor() - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should show message when prepare failed', async () => { - await helper.createDocument() - disposable = languages.registerRenameProvider(['*'], { - prepareRename: () => { - return undefined - }, - provideRenameEdits: () => { - return null - } - }) - await refactor.doRefactor() - let res = await helper.getCmdline() - expect(res).toMatch(/unable to rename/) - }) - - it('should show message when returned edits is null', async () => { - await helper.createDocument() - disposable = languages.registerRenameProvider(['*'], { - provideRenameEdits: () => { - return null - } - }) - await refactor.doRefactor() - let res = await helper.getCmdline() - expect(res).toMatch(/returns null/) - }) - - it('should open refactor window when edits is valid', async () => { - let filepath = __filename - disposable = languages.registerRenameProvider(['*'], { - provideRenameEdits: () => { - let changes = { - [URI.file(filepath).toString()]: [{ - range: Range.create(0, 0, 0, 6), - newText: '' - }, { - range: Range.create(1, 0, 1, 6), - newText: '' - }] - } - let edit: WorkspaceEdit = { changes } - return edit - } - }) - await helper.createDocument(filepath) - let winid = await nvim.call('win_getid') - await refactor.doRefactor() - let currWin = await nvim.call('win_getid') - expect(currWin - winid).toBeGreaterThan(0) - let bufnr = await nvim.call('bufnr', ['%']) - let b = refactor.getBuffer(bufnr) - expect(b).toBeDefined() - }) - }) - - describe('search', () => { - it('should open refactor buffer from search result', async () => { - let escaped = await nvim.call('fnameescape', [__dirname]) - await nvim.command(`cd ${escaped}`) - await helper.createDocument() - await refactor.search(['registerRenameProvider']) - let buf = await nvim.buffer - let name = await buf.name - expect(name).toMatch(/__coc_refactor__/) - let lines = await buf.lines - expect(lines[0]).toMatch(/Save current buffer/) - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/rename.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/rename.test.ts deleted file mode 100644 index 6560ca8f..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/rename.test.ts +++ /dev/null @@ -1,263 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, Position, Range, TextEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import Rename from '../../handler/rename' -import languages from '../../languages' -import { disposeAll } from '../../util' -import helper from '../helper' - -let nvim: Neovim -let disposables: Disposable[] = [] -let rename: Rename - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - rename = helper.plugin.getHandler().rename -}) - -function getWordRangeAtPosition(doc: TextDocument, position: Position): Range | null { - let lines = doc.getText().split(/\r?\n/) - let line = lines[position.line] - if (line.length == 0 || position.character >= line.length) return null - if (!/\w/.test(line[position.character])) return null - let start = position.character - let end = position.character + 1 - if (!/\w/.test(line[start])) { - return Range.create(position, { line: position.line, character: position.character + 1 }) - } - while (start >= 0) { - let ch = line[start - 1] - if (!ch || !/\w/.test(ch)) break - start = start - 1 - } - while (end <= line.length) { - let ch = line[end] - if (!ch || !/\w/.test(ch)) break - end = end + 1 - } - return Range.create(position.line, start, position.line, end) -} - -function getSymbolRanges(textDocument: TextDocument, word: string): Range[] { - let res: Range[] = [] - let str = '' - let content = textDocument.getText() - for (let i = 0, l = content.length; i < l; i++) { - let ch = content[i] - if ('-' == ch && str.length == 0) { - continue - } - let isKeyword = /\w/.test(ch) - if (isKeyword) { - str = str + ch - } - if (str.length > 0 && !isKeyword && str == word) { - res.push(Range.create(textDocument.positionAt(i - str.length), textDocument.positionAt(i))) - } - if (!isKeyword) { - str = '' - } - } - return res -} - -beforeEach(() => { - disposables.push(languages.registerRenameProvider([{ language: 'javascript' }], { - provideRenameEdits: (doc, position: Position, newName: string) => { - let range = getWordRangeAtPosition(doc, position) - if (range) { - let word = doc.getText(range) - if (word) { - let ranges = getSymbolRanges(doc, word) - return { - changes: { - [doc.uri]: ranges.map(o => TextEdit.replace(o, newName)) - } - } - } - } - return undefined - }, - prepareRename: (doc, position) => { - let range = getWordRangeAtPosition(doc, position) - return range ? { range, placeholder: doc.getText(range) } : null - } - })) -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -describe('rename handler', () => { - describe('getWordEdit', () => { - it('should not throw when provider not found', async () => { - await helper.edit() - let res = await rename.getWordEdit() - expect(res).toBe(null) - }) - - it('should return null when prepare failed', async () => { - let doc = await helper.createDocument('t.js') - await nvim.setLine('ไฝ ') - await doc.synchronize() - let res = await rename.getWordEdit() - expect(res).toBe(null) - }) - - it('should return workspace edit', async () => { - let doc = await helper.createDocument('t.js') - await nvim.setLine('foo foo') - await doc.synchronize() - let res = await rename.getWordEdit() - expect(res).toBeDefined() - expect(res.changes[doc.uri].length).toBe(2) - }) - - it('should extract words from buffer', async () => { - let doc = await helper.createDocument('t') - await nvim.setLine('ไฝ  ไฝ  ไฝ ') - await doc.synchronize() - let res = await rename.getWordEdit() - expect(res).toBeDefined() - expect(res.changes[doc.uri].length).toBe(3) - }) - }) - - describe('rename', () => { - it('should throw when provider not found', async () => { - await helper.edit() - let err - try { - await rename.rename('foo') - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should return false for invalid position', async () => { - await helper.createDocument('t.js') - let res = await rename.rename('foo') - expect(res).toBe(false) - }) - - it('should use newName from placeholder', async () => { - await helper.createDocument('t.js') - await nvim.setLine('foo foo foo') - let p = rename.rename() - await helper.wait(50) - await nvim.input('') - await helper.wait(10) - await nvim.input('bar') - await nvim.input('') - let res = await p - expect(res).toBe(true) - }) - - it('should return false for empty name', async () => { - await helper.createDocument('t.js') - await nvim.setLine('foo foo foo') - let p = rename.rename() - await helper.wait(50) - await nvim.input('') - await helper.wait(20) - await nvim.input('') - let res = await p - expect(res).toBe(false) - }) - - it('should use newName from range', async () => { - disposables.push(languages.registerRenameProvider([{ language: '*' }], { - provideRenameEdits: (doc, position: Position, newName: string) => { - let range = getWordRangeAtPosition(doc, position) - if (range) { - let word = doc.getText(range) - if (word) { - let ranges = getSymbolRanges(doc, word) - return { - changes: { - [doc.uri]: ranges.map(o => TextEdit.replace(o, newName)) - } - } - } - } - return undefined - }, - prepareRename: (doc, position) => { - let range = getWordRangeAtPosition(doc, position) - return range ? range : null - } - })) - await helper.createDocument() - await nvim.setLine('foo foo foo') - let p = rename.rename() - await helper.wait(50) - await nvim.input('') - await helper.wait(10) - await nvim.input('bar') - await nvim.input('') - let res = await p - expect(res).toBe(true) - let line = await nvim.getLine() - expect(line).toBe('bar bar bar') - }) - - it('should use newName from cword', async () => { - disposables.push(languages.registerRenameProvider([{ language: '*' }], { - provideRenameEdits: (doc, position: Position, newName: string) => { - let range = getWordRangeAtPosition(doc, position) - if (range) { - let word = doc.getText(range) - if (word) { - let ranges = getSymbolRanges(doc, word) - return { - changes: { - [doc.uri]: ranges.map(o => TextEdit.replace(o, newName)) - } - } - } - } - return undefined - } - })) - await helper.createDocument() - await nvim.setLine('foo foo foo') - let p = rename.rename() - await helper.wait(50) - await nvim.input('') - await helper.wait(10) - await nvim.input('bar') - await nvim.input('') - let res = await p - expect(res).toBe(true) - let line = await nvim.getLine() - expect(line).toBe('bar bar bar') - }) - - it('should return false when result is empty', async () => { - disposables.push(languages.registerRenameProvider([{ language: '*' }], { - provideRenameEdits: () => { - return null - } - })) - await helper.createDocument() - await nvim.setLine('foo foo foo') - let p = rename.rename() - await helper.wait(50) - await nvim.input('') - await helper.wait(10) - await nvim.input('bar') - await nvim.input('') - let res = await p - expect(res).toBe(false) - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/search.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/search.test.ts deleted file mode 100644 index bf8ab667..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/search.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import Refactor from '../../handler/refactor' -import Search, { getPathFromArgs } from '../../handler/search' -import helper from '../helper' -import path from 'path' - -let nvim: Neovim -let refactor: Refactor -// use fake rg command -let cmd = path.resolve(__dirname, '../rg') -let cwd = process.cwd() - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - refactor = helper.plugin.getHandler().refactor -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - refactor.reset() - await helper.reset() -}) - -describe('getPathFromArgs', () => { - it('should get undefined path', async () => { - let res = getPathFromArgs(['a']) - expect(res).toBeUndefined() - res = getPathFromArgs(['a', 'b', '-c']) - expect(res).toBeUndefined() - res = getPathFromArgs(['a', '-b', 'c']) - expect(res).toBeUndefined() - }) -}) - -describe('search', () => { - - it('should open refactor window', async () => { - let search = new Search(nvim, cmd) - let buf = await refactor.createRefactorBuffer() - await search.run([], cwd, buf) - await helper.wait(50) - let fileItems = buf.fileItems - expect(fileItems.length).toBe(2) - expect(fileItems[0].ranges.length).toBe(2) - }) - - it('should abort task', async () => { - let search = new Search(nvim, cmd) - let buf = await refactor.createRefactorBuffer() - let p = search.run(['--sleep', '1000'], cwd, buf) - search.abort() - await p - let fileItems = buf.fileItems - expect(fileItems.length).toBe(0) - }) - - it('should work with CocAction search', async () => { - await helper.doAction('search', ['CocAction']) - let bufnr = await nvim.call('bufnr', ['%']) - let buf = refactor.getBuffer(bufnr) - expect(buf).toBeDefined() - }) - - it('should fail on invalid command', async () => { - let search = new Search(nvim, 'rrg') - let buf = await refactor.createRefactorBuffer() - let err - try { - await search.run([], cwd, buf) - } catch (e) { - err = e - } - expect(err).toBeDefined() - let msg = await helper.getCmdline() - expect(msg).toMatch(/Error on command "rrg"/) - }) - - it('should show empty result when no result found', async () => { - await helper.doAction('search', ['should found ' + ' no result']) - let bufnr = await nvim.call('bufnr', ['%']) - let buf = refactor.getBuffer(bufnr) - expect(buf).toBeDefined() - let buffer = await nvim.buffer - let lines = await buffer.lines - expect(lines[1]).toMatch(/No match found/) - }) - - it('should use corrent search folder for rg', async () => { - let search = new Search(nvim, 'rg') - await helper.createDocument() - let buf = await refactor.createRefactorBuffer() - await search.run(['-w', 'createRefactorBuffer', 'src/__tests__'], cwd, buf) - let buffer = await nvim.buffer - let lines = await buffer.lines - expect(lines[1].startsWith('Files: ')).toBe(true) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/selectionRange.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/selectionRange.test.ts deleted file mode 100644 index ec43b39d..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/selectionRange.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, Position, Range, TextEdit } from 'vscode-languageserver-protocol' -import SelectionRange from '../../handler/selectionRange' -import languages from '../../languages' -import workspace from '../../workspace' -import { disposeAll } from '../../util' -import helper from '../helper' - -let nvim: Neovim -let disposables: Disposable[] = [] -let selection: SelectionRange - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - selection = helper.plugin.getHandler().selectionRange -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -describe('selectionRange', () => { - describe('getSelectionRanges()', () => { - it('should throw error when selectionRange provider not exists', async () => { - let doc = await helper.createDocument() - await doc.synchronize() - let err - try { - await selection.getSelectionRanges() - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should return ranges', async () => { - await helper.createDocument() - disposables.push(languages.registerSelectionRangeProvider([{ language: '*' }], { - provideSelectionRanges: _doc => { - return [{ - range: Range.create(0, 0, 0, 1) - }] - } - })) - let res = await selection.getSelectionRanges() - expect(res).toBeDefined() - expect(Array.isArray(res)).toBe(true) - }) - }) - - describe('selectRange()', () => { - async function getSelectedRange(): Promise { - let m = await nvim.mode - expect(m.mode).toBe('v') - let bufnr = await nvim.call('bufnr', ['%']) - await nvim.input('') - let doc = workspace.getDocument(bufnr) - let res = await workspace.getSelectedRange('v', doc) - return res - } - - it('should select ranges forward', async () => { - let doc = await helper.createDocument() - let called = 0 - await doc.applyEdits([TextEdit.insert(Position.create(0, 0), 'foo\nbar\ntest\n')]) - await nvim.call('cursor', [1, 1]) - disposables.push(languages.registerSelectionRangeProvider([{ language: '*' }], { - provideSelectionRanges: _doc => { - called += 1 - let arr = [{ - range: Range.create(0, 0, 0, 1) - }, { - range: Range.create(0, 0, 0, 3) - }, { - range: Range.create(0, 0, 1, 3) - }] - return arr - } - })) - await doc.synchronize() - await selection.selectRange('', false) - await selection.selectRange('', true) - expect(called).toBe(1) - let res = await getSelectedRange() - expect(res).toEqual(Range.create(0, 0, 0, 1)) - await selection.selectRange('v', true) - expect(called).toBe(2) - res = await getSelectedRange() - expect(res).toEqual(Range.create(0, 0, 0, 3)) - await selection.selectRange('v', true) - expect(called).toBe(3) - res = await getSelectedRange() - expect(res).toEqual(Range.create(0, 0, 1, 3)) - await selection.selectRange('v', true) - expect(called).toBe(4) - let m = await nvim.mode - expect(m.mode).toBe('n') - }) - - it('should select ranges backward', async () => { - let doc = await helper.createDocument() - await doc.applyEdits([TextEdit.insert(Position.create(0, 0), 'foo\nbar\ntest\n')]) - await nvim.call('cursor', [1, 1]) - disposables.push(languages.registerSelectionRangeProvider([{ language: '*' }], { - provideSelectionRanges: _doc => { - let arr = [{ - range: Range.create(0, 0, 0, 1) - }, { - range: Range.create(0, 0, 0, 3) - }, { - range: Range.create(0, 0, 1, 3) - }] - return arr - } - })) - await doc.synchronize() - await selection.selectRange('', true) - let mode = await nvim.call('mode') - expect(mode).toBe('v') - await nvim.input('') - await workspace.selectRange(Range.create(0, 0, 1, 3)) - await nvim.input('') - await selection.selectRange('v', false) - let r = await getSelectedRange() - expect(r).toEqual(Range.create(0, 0, 0, 3)) - await nvim.input('') - await selection.selectRange('v', false) - r = await getSelectedRange() - expect(r).toEqual(Range.create(0, 0, 0, 1)) - await nvim.input('') - await selection.selectRange('v', false) - mode = await nvim.call('mode') - expect(mode).toBe('n') - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/semanticTokens.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/semanticTokens.test.ts deleted file mode 100644 index 4d4a20e1..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/semanticTokens.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import { Disposable, SemanticTokensLegend } from 'vscode-languageserver-protocol' -import languages from '../../languages' -import SemanticTokensHighlights from '../../handler/semanticTokensHighlights/index' -import { disposeAll } from '../../util' -import workspace from '../../workspace' -import helper from '../helper' - -let nvim: Neovim -let disposables: Disposable[] = [] -let highlighter: SemanticTokensHighlights -let legend: SemanticTokensLegend = { - tokenTypes: [ - "comment", - "keyword", - "string", - "number", - "regexp", - "operator", - "namespace", - "type", - "struct", - "class", - "interface", - "enum", - "enumMember", - "typeParameter", - "function", - "method", - "property", - "macro", - "variable", - "parameter", - "angle", - "arithmetic", - "attribute", - "bitwise", - "boolean", - "brace", - "bracket", - "builtinType", - "character", - "colon", - "comma", - "comparison", - "constParameter", - "dot", - "escapeSequence", - "formatSpecifier", - "generic", - "label", - "lifetime", - "logical", - "operator", - "parenthesis", - "punctuation", - "selfKeyword", - "semicolon", - "typeAlias", - "union", - "unresolvedReference" - ], - tokenModifiers: [ - "documentation", - "declaration", - "definition", - "static", - "abstract", - "deprecated", - "readonly", - "constant", - "controlFlow", - "injected", - "mutable", - "consuming", - "async", - "library", - "public", - "unsafe", - "attribute", - "trait", - "callable", - "intraDocLink" - ] -} - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - highlighter = helper.plugin.getHandler().semanticHighlighter -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(async () => { - async function createBuffer(code: string): Promise { - let buf = await nvim.buffer - await nvim.command('setf rust') - await buf.setLines(code.split('\n'), { start: 0, end: -1, strictIndexing: false }) - let doc = await workspace.document - doc.forceSync() - return buf - } - - disposables.push(languages.registerDocumentSemanticTokensProvider([{ language: 'rust' }], { - provideDocumentSemanticTokens: () => { - return { - resultId: '1', - data: [ - 0, 0, 2, 1, 0, - 0, 3, 4, 14, 2, - 0, 4, 1, 41, 0, - 0, 1, 1, 41, 0, - 0, 2, 1, 25, 0, - 1, 4, 8, 17, 0, - 0, 8, 1, 41, 0, - 0, 1, 3, 2, 0, - 0, 3, 1, 41, 0, - 0, 1, 1, 44, 0, - 1, 0, 1, 25, 0, - ] - } - } - }, legend)) - await createBuffer(`fn main() { - println!("H"); -}`) -}) - -afterEach(async () => { - workspace.configurations.updateUserConfig({ - 'coc.preferences.semanticTokensHighlights': true - }) - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -describe('semanticTokens', () => { - describe('triggerSemanticTokens', () => { - it('should be disabled', async () => { - await helper.createDocument() - workspace.configurations.updateUserConfig({ - 'coc.preferences.semanticTokensHighlights': false - }) - const curr = await highlighter.getCurrentItem() - let err - try { - curr.checkState() - } catch (e) { - err = e - } - expect(err).toBeDefined() - expect(err.message).toMatch('disabled by configuration') - }) - - it('should get legend by API', async () => { - const doc = await workspace.document - const l = languages.getLegend(doc.textDocument) - expect(l).toEqual(legend) - }) - - it('should get semanticTokens by API', async () => { - // const doc = await workspace.document - // const highlights = await highlighter.getHighlights(doc.bufnr) - // expect(highlights.length).toBe(11) - // expect(highlights[0].hlGroup).toBe('CocSem_keyword') - }) - - it('should doHighlight', async () => { - const doc = await workspace.document - await nvim.call('CocAction', 'semanticHighlight') - const highlights = await nvim.call("coc#highlight#get_highlights", [doc.bufnr, 'semanticTokens']) - expect(highlights.length).toBe(11) - expect(highlights[0].hlGroup).toBe('CocSem_keyword') - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/signature.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/signature.test.ts deleted file mode 100644 index 18b9bbad..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/signature.test.ts +++ /dev/null @@ -1,376 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, Position, ParameterInformation, SignatureInformation } from 'vscode-languageserver-protocol' -import languages from '../../languages' -import { disposeAll } from '../../util' -import Signature from '../../handler/signature' -import workspace from '../../workspace' -import helper from '../helper' - -let nvim: Neovim -let signature: Signature -let disposables: Disposable[] = [] - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - signature = helper.plugin.getHandler().signature -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -describe('signatureHelp', () => { - - describe('triggerSignatureHelp', () => { - it('should show signature by api', async () => { - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - return { - signatures: [SignatureInformation.create('foo()', 'my signature')], - activeParameter: null, - activeSignature: null - } - } - }, [])) - await helper.createDocument() - await nvim.input('foo') - await signature.triggerSignatureHelp() - let win = await helper.getFloat() - expect(win).toBeDefined() - let lines = await helper.getWinLines(win.id) - expect(lines[2]).toMatch('my signature') - }) - - it('should trigger by space', async () => { - let called = false - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - called = true - return { - signatures: [SignatureInformation.create('foo()', 'my signature')], - activeParameter: null, - activeSignature: null - } - } - }, [' '])) - await helper.createDocument() - await nvim.input('i') - await helper.wait(30) - await nvim.input(' ') - await helper.wait(50) - expect(called).toBe(true) - }) - - it('should show signature help with param label as string', async () => { - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - return { - signatures: [ - SignatureInformation.create('foo()', 'my signature'), - SignatureInformation.create('foo(a, b)', 'my signature', ParameterInformation.create('a', 'description')), - ], - activeParameter: 0, - activeSignature: 1 - } - } - }, [])) - await helper.createDocument() - await nvim.input('foo') - await signature.triggerSignatureHelp() - let win = await helper.getFloat() - expect(win).toBeDefined() - let lines = await helper.getWinLines(win.id) - expect(lines.join('\n')).toMatch(/description/) - }) - - it('should consider coc_last_placeholder on select mode', async () => { - let pos: Position - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, position) => { - pos = position - return { - signatures: [ - SignatureInformation.create('foo(a, b)', 'my signature', ParameterInformation.create('a', 'description')), - ], - activeParameter: 1, - activeSignature: null - } - } - }, [])) - let doc = await helper.createDocument() - let line = await nvim.call('line', ['.']) - await nvim.setLine(' fn(abc, def)') - await nvim.command('normal! 0fave') - await nvim.input('') - let placeholder = { - bufnr: doc.bufnr, - start: Position.create(line - 1, 5), - end: Position.create(line - 1, 8) - } - await nvim.setVar('coc_last_placeholder', placeholder) - let m = await nvim.mode - expect(m.mode).toBe('s') - await signature.triggerSignatureHelp() - let win = await helper.getFloat() - expect(win).toBeDefined() - expect(pos).toEqual(Position.create(0, 5)) - }) - }) - - describe('events', () => { - it('should trigger signature help', async () => { - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - return { - signatures: [SignatureInformation.create('foo(x, y)', 'my signature')], - activeParameter: 0, - activeSignature: 0 - } - } - }, ['(', ','])) - await helper.createDocument() - await nvim.input('foo') - await nvim.input('(') - await helper.wait(100) - let win = await helper.getFloat() - expect(win).toBeDefined() - let lines = await helper.getWinLines(win.id) - expect(lines[2]).toMatch('my signature') - }) - - it('should cancel trigger on InsertLeave', async () => { - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: async (_doc, _position, token) => { - await helper.wait(1000) - if (token.isCancellationRequested) return undefined - return { - signatures: [SignatureInformation.create('foo()', 'my signature')], - activeParameter: null, - activeSignature: null - } - } - }, ['(', ','])) - await helper.createDocument() - await nvim.input('foo') - let p = signature.triggerSignatureHelp() - await helper.wait(10) - await nvim.command('stopinsert') - await nvim.call('feedkeys', [String.fromCharCode(27), 'in']) - let res = await p - expect(res).toBe(false) - }) - - it('should not close signature on type', async () => { - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - return { - signatures: [SignatureInformation.create('foo()', 'my signature')], - activeParameter: null, - activeSignature: null - } - } - }, ['(', ','])) - await helper.createDocument() - await nvim.input('foo(') - await helper.wait(100) - await nvim.input('bar') - await helper.wait(100) - let win = await helper.getFloat() - expect(win).toBeDefined() - let lines = await helper.getWinLines(win.id) - expect(lines[2]).toMatch('my signature') - }) - - it('should close signature float when empty signatures returned', async () => { - let empty = false - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - if (empty) return undefined - return { - signatures: [SignatureInformation.create('foo()', 'my signature')], - activeParameter: null, - activeSignature: null - } - } - }, ['(', ','])) - await helper.createDocument() - await nvim.input('foo(') - await helper.wait(100) - let win = await helper.getFloat() - expect(win).toBeDefined() - empty = true - await signature.triggerSignatureHelp() - await helper.wait(50) - let res = await nvim.call('coc#float#valid', [win.id]) - expect(res).toBe(0) - }) - }) - - describe('float window', () => { - it('should align signature window to top', async () => { - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - return { - signatures: [SignatureInformation.create('foo()', 'my signature')], - activeParameter: null, - activeSignature: null - } - } - }, ['(', ','])) - await helper.createDocument() - let buf = await nvim.buffer - await buf.setLines(['', '', '', '', ''], { start: 0, end: -1, strictIndexing: true }) - await nvim.call('cursor', [5, 1]) - await nvim.input('foo(') - await helper.wait(100) - let win = await helper.getFloat() - expect(win).toBeDefined() - let lines = await helper.getWinLines(win.id) - expect(lines[2]).toMatch('my signature') - let res = await nvim.call('coc#float#cursor_relative', [win.id]) as any - expect(res.row).toBeLessThan(0) - }) - - it('should show parameter docs', async () => { - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - return { - signatures: [SignatureInformation.create('foo(a, b)', 'my signature', - ParameterInformation.create('a', 'foo'), - ParameterInformation.create([7, 8], 'bar'))], - activeParameter: 1, - activeSignature: null - } - } - }, ['(', ','])) - await helper.createDocument() - let buf = await nvim.buffer - await buf.setLines(['', '', '', '', ''], { start: 0, end: -1, strictIndexing: true }) - await nvim.call('cursor', [5, 1]) - await nvim.input('foo(a,') - await helper.wait(100) - let win = await helper.getFloat() - expect(win).toBeDefined() - let lines = await helper.getWinLines(win.id) - expect(lines.join('\n')).toMatch('bar') - }) - }) - - describe('configurations', () => { - let { configurations } = workspace - afterEach(() => { - configurations.updateUserConfig({ - 'signature.target': 'float', - 'signature.hideOnTextChange': false, - 'signature.enable': true, - 'signature.triggerSignatureWait': 500 - }) - }) - - it('should cancel signature on timeout', async () => { - configurations.updateUserConfig({ 'signature.triggerSignatureWait': 50 }) - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position, token) => { - return new Promise(resolve => { - token.onCancellationRequested(() => { - clearTimeout(timer) - resolve(undefined) - }) - let timer = setTimeout(() => { - resolve({ - signatures: [SignatureInformation.create('foo()', 'my signature')], - activeParameter: null, - activeSignature: null - }) - }, 200) - }) - } - }, ['(', ','])) - await helper.createDocument() - await signature.triggerSignatureHelp() - let win = await helper.getFloat() - expect(win).toBeUndefined() - configurations.updateUserConfig({ 'signature.triggerSignatureWait': 100 }) - }) - - it('should hide signature window on text change', async () => { - configurations.updateUserConfig({ 'signature.hideOnTextChange': true }) - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - return { - signatures: [SignatureInformation.create('foo()', 'my signature')], - activeParameter: null, - activeSignature: null - } - } - }, ['(', ','])) - await helper.createDocument() - await nvim.input('ifoo(') - let winid = await helper.waitFloat() - await nvim.input('x') - await helper.wait(100) - let res = await nvim.call('coc#float#valid', [winid]) - expect(res).toBe(0) - configurations.updateUserConfig({ 'signature.hideOnTextChange': false }) - }) - - it('should disable signature help trigger', async () => { - configurations.updateUserConfig({ 'signature.enable': false }) - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - return { - signatures: [SignatureInformation.create('foo()', 'my signature')], - activeParameter: null, - activeSignature: null - } - } - }, ['(', ','])) - await helper.createDocument() - await nvim.input('foo') - await nvim.input('(') - await helper.wait(100) - let win = await helper.getFloat() - expect(win).toBeUndefined() - }) - - it('should echo simple signature help', async () => { - let idx = 0 - let activeSignature = null - configurations.updateUserConfig({ 'signature.target': 'echo' }) - disposables.push(languages.registerSignatureHelpProvider([{ scheme: 'file' }], { - provideSignatureHelp: (_doc, _position) => { - return { - signatures: [SignatureInformation.create('foo(a, b)', 'my signature', - ParameterInformation.create('a', 'foo'), - ParameterInformation.create([7, 8], 'bar')), - SignatureInformation.create('a'.repeat(workspace.env.columns + 10)) - ], - activeParameter: idx, - activeSignature - } - } - }, [])) - await helper.createDocument() - await nvim.input('foo(') - await signature.triggerSignatureHelp() - let line = await helper.getCmdline() - expect(line).toMatch('(a, b)') - await nvim.input('a,') - idx = 1 - await signature.triggerSignatureHelp() - line = await helper.getCmdline() - expect(line).toMatch('foo(a, b)') - activeSignature = 1 - await signature.triggerSignatureHelp() - line = await helper.getCmdline() - expect(line).toMatch('aaaaaa') - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/handler/symbols.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/handler/symbols.test.ts deleted file mode 100644 index 4adc00f4..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/handler/symbols.test.ts +++ /dev/null @@ -1,284 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import { Disposable, SymbolInformation, SymbolKind, Range } from 'vscode-languageserver-protocol' -import Symbols from '../../handler/symbols/index' -import languages from '../../languages' -import workspace from '../../workspace' -import events from '../../events' -import { disposeAll } from '../../util' -import helper from '../helper' -import Parser from './parser' - -let nvim: Neovim -let symbols: Symbols -let disposables: Disposable[] = [] - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - symbols = helper.plugin.getHandler().symbols -}) - -beforeEach(() => { - disposables.push(languages.registerDocumentSymbolProvider([{ language: 'javascript' }], { - provideDocumentSymbols: document => { - let parser = new Parser(document.getText()) - let res = parser.parse() - return Promise.resolve(res) - } - })) -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -describe('Parser', () => { - it('should parse content', async () => { - let code = `class myClass { - fun1() { } - }` - let parser = new Parser(code) - let res = parser.parse() - expect(res.length).toBeGreaterThan(0) - }) -}) - -describe('symbols handler', () => { - - async function createBuffer(code: string): Promise { - let buf = await nvim.buffer - await nvim.command('setf javascript') - await buf.setLines(code.split('\n'), { start: 0, end: -1, strictIndexing: false }) - let doc = await workspace.document - doc.forceSync() - return buf - } - - describe('configuration', () => { - afterEach(() => { - helper.updateConfiguration('coc.preferences.currentFunctionSymbolAutoUpdate', false) - helper.updateConfiguration('coc.preferences.currentFunctionSymbolAutoUpdate', false) - }) - - it('should get configuration', async () => { - let functionUpdate = symbols.functionUpdate - expect(functionUpdate).toBe(false) - helper.updateConfiguration('coc.preferences.currentFunctionSymbolAutoUpdate', true) - functionUpdate = symbols.functionUpdate - expect(functionUpdate).toBe(true) - }) - - it('should update symbols automatically', async () => { - helper.updateConfiguration('coc.preferences.currentFunctionSymbolAutoUpdate', true) - let code = `class myClass { - fun1() { - } - }` - let buf = await createBuffer(code) - await nvim.call('cursor', [2, 8]) - await events.fire('CursorHold', [buf.id]) - let val = await buf.getVar('coc_current_function') - expect(val).toBe('fun1') - await nvim.call('cursor', [1, 8]) - await events.fire('CursorHold', [buf.id]) - val = await buf.getVar('coc_current_function') - expect(val).toBe('myClass') - }) - }) - - describe('documentSymbols', () => { - it('should get symbols of current buffer', async () => { - let code = `class myClass { - fun1() { } - }` - await createBuffer(code) - let res = await helper.plugin.cocAction('documentSymbols') - expect(res.length).toBe(2) - }) - - it('should get current function symbols', async () => { - let code = `class myClass { - fun1() { - } - fun2() { - } - } - ` - await createBuffer(code) - await nvim.call('cursor', [3, 0]) - let res = await helper.doAction('getCurrentFunctionSymbol') - expect(res).toBe('fun1') - await nvim.command('normal! G') - res = await helper.doAction('getCurrentFunctionSymbol') - expect(res).toBe('') - }) - - it('should reset coc_current_function when symbols not exists', async () => { - let code = `class myClass { - fun1() { - } - }` - await createBuffer(code) - await nvim.call('cursor', [3, 0]) - let res = await helper.doAction('getCurrentFunctionSymbol') - expect(res).toBe('fun1') - await nvim.command('normal! ggdG') - res = await symbols.getCurrentFunctionSymbol() - expect(res).toBe('') - }) - - it('should support SymbolInformation', async () => { - disposables.push(languages.registerDocumentSymbolProvider(['*'], { - provideDocumentSymbols: () => { - return [ - SymbolInformation.create('root', SymbolKind.Function, Range.create(0, 0, 0, 10)), - SymbolInformation.create('child', SymbolKind.Function, Range.create(0, 0, 0, 10), '', 'root') - ] - } - })) - let doc = await helper.createDocument() - let res = await symbols.getDocumentSymbols(doc.bufnr) - expect(res.length).toBe(2) - expect(res[0].text).toBe('root') - expect(res[1].text).toBe('child') - }) - }) - - describe('selectSymbolRange', () => { - it('should show warning when no symbols exists', async () => { - disposables.push(languages.registerDocumentSymbolProvider(['*'], { - provideDocumentSymbols: () => { - return [] - } - })) - await helper.createDocument() - await nvim.call('cursor', [3, 0]) - await symbols.selectSymbolRange(false, '', ['Function']) - let msg = await helper.getCmdline() - expect(msg).toMatch(/No symbols found/) - }) - - it('should select symbol range at cursor position', async () => { - let code = `class myClass { - fun1() { - } - }` - let buf = await createBuffer(code) - await nvim.call('cursor', [3, 0]) - await helper.doAction('selectSymbolRange', false, '', ['Function', 'Method']) - let mode = await nvim.mode - expect(mode.mode).toBe('v') - let doc = workspace.getDocument(buf.id) - await nvim.input('') - let res = await workspace.getSelectedRange('v', doc) - expect(res).toEqual({ start: { line: 1, character: 6 }, end: { line: 2, character: 6 } }) - }) - - it('should select inner range', async () => { - let code = `class myClass { - fun1() { - let foo; - } -}` - let buf = await createBuffer(code) - await nvim.call('cursor', [3, 3]) - await symbols.selectSymbolRange(true, '', ['Method']) - let mode = await nvim.mode - expect(mode.mode).toBe('v') - let doc = workspace.getDocument(buf.id) - await nvim.input('') - let res = await workspace.getSelectedRange('v', doc) - expect(res).toEqual({ - start: { line: 2, character: 8 }, end: { line: 2, character: 16 } - }) - }) - - it('should reset visualmode when selection not found', async () => { - let code = `class myClass {}` - await createBuffer(code) - await nvim.call('cursor', [1, 1]) - await nvim.command('normal! gg0v$') - let mode = await nvim.mode - expect(mode.mode).toBe('v') - await nvim.input('') - await symbols.selectSymbolRange(true, 'v', ['Method']) - mode = await nvim.mode - expect(mode.mode).toBe('v') - }) - - it('should select symbol range from select range', async () => { - let code = `class myClass { - fun1() { - } - }` - let buf = await createBuffer(code) - await nvim.call('cursor', [2, 8]) - await nvim.command('normal! viw') - await nvim.input('') - await helper.doAction('selectSymbolRange', false, 'v', ['Class']) - let mode = await nvim.mode - expect(mode.mode).toBe('v') - let doc = workspace.getDocument(buf.id) - await nvim.input('') - let res = await workspace.getSelectedRange('v', doc) - expect(res).toEqual({ start: { line: 0, character: 0 }, end: { line: 3, character: 4 } }) - }) - }) - - describe('cancel', () => { - it('should cancel symbols request on insert', async () => { - let cancelled = false - disposables.push(languages.registerDocumentSymbolProvider([{ language: 'text' }], { - provideDocumentSymbols: (_doc, token) => { - return new Promise(s => { - token.onCancellationRequested(() => { - if (timer) clearTimeout(timer) - cancelled = true - s(undefined) - }) - let timer = setTimeout(() => { - s(undefined) - }, 3000) - }) - } - })) - let doc = await helper.createDocument('t.txt') - let p = symbols.getDocumentSymbols(doc.bufnr) - setTimeout(async () => { - await nvim.input('i') - }, 500) - await p - expect(cancelled).toBe(true) - }) - }) - - describe('workspaceSymbols', () => { - it('should get workspace symbols', async () => { - disposables.push(languages.registerWorkspaceSymbolProvider({ - provideWorkspaceSymbols: (_query, _token) => { - return [SymbolInformation.create('far', SymbolKind.Class, Range.create(0, 0, 0, 0))] - }, - resolveWorkspaceSymbol: sym => { - let res = Object.assign({}, sym) - res.location.uri = 'test:///foo' - return res - } - })) - disposables.push(languages.registerWorkspaceSymbolProvider({ - provideWorkspaceSymbols: (_query, _token) => { - return [SymbolInformation.create('bar', SymbolKind.Function, Range.create(0, 0, 0, 0))] - } - })) - let res = await symbols.getWorkspaceSymbols('a') - expect(res.length).toBe(2) - let resolved = await symbols.resolveWorkspaceSymbol(res[0]) - expect(resolved?.location?.uri).toBe('test:///foo') - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/helper.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/helper.test.ts deleted file mode 100644 index 2c1e10ed..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/helper.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import Plugin from '../plugin' -import helper from './helper' - -let nvim: Neovim -let plugin: Plugin -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - plugin = helper.plugin -}) - -describe('Helper', () => { - it('should setup', () => { - expect(nvim).toBeTruthy() - expect(plugin.isReady).toBeTruthy() - }) -}) - -afterAll(async () => { - await helper.shutdown() -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/helper.ts b/vim-config/plugins/coc.nvim/src/__tests__/helper.ts deleted file mode 100644 index 795f45b0..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/helper.ts +++ /dev/null @@ -1,248 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unsafe-return */ -/* eslint-disable @typescript-eslint/no-unsafe-call */ -import { Buffer, Neovim, Window } from '@chemzqm/neovim' -import * as cp from 'child_process' -import { EventEmitter } from 'events' -import fs from 'fs' -import os from 'os' -import path from 'path' -import util from 'util' -import attach from '../attach' -import Document from '../model/document' -import Plugin from '../plugin' -import workspace from '../workspace' -import { v4 as uuid } from 'uuid' -import { VimCompleteItem } from '../types' - -export interface CursorPosition { - bufnum: number - lnum: number - col: number -} - -process.on('uncaughtException', err => { - let msg = 'Uncaught exception: ' + err.stack - console.error(msg) -}) -export class Helper extends EventEmitter { - public nvim: Neovim - public proc: cp.ChildProcess - public plugin: Plugin - - constructor() { - super() - this.setMaxListeners(99) - } - - public setup(): Promise { - const vimrc = path.resolve(__dirname, 'vimrc') - let proc = this.proc = cp.spawn('nvim', ['-u', vimrc, '-i', 'NONE', '--embed'], { - cwd: __dirname - }) - let plugin = this.plugin = attach({ proc }) - this.nvim = plugin.nvim - this.nvim.uiAttach(160, 80, {}).catch(_e => { - // noop - }) - proc.on('exit', () => { - this.proc = null - }) - this.nvim.on('notification', (method, args) => { - if (method == 'redraw') { - for (let arg of args) { - let event = arg[0] - this.emit(event, arg.slice(1)) - } - } - }) - return new Promise(resolve => { - plugin.once('ready', resolve) - }) - } - - public async shutdown(): Promise { - this.plugin.dispose() - await this.nvim.quit() - if (this.proc) { - this.proc.kill('SIGKILL') - } - await this.wait(60) - } - - public async waitPopup(): Promise { - for (let i = 0; i < 40; i++) { - await this.wait(50) - let visible = await this.nvim.call('pumvisible') - if (visible) return - } - throw new Error('timeout after 2s') - } - - public async waitFloat(): Promise { - for (let i = 0; i < 40; i++) { - await this.wait(50) - let winid = await this.nvim.call('coc#float#get_float_win') - if (winid) return winid - } - throw new Error('timeout after 2s') - } - - public async selectCompleteItem(idx: number): Promise { - await this.nvim.call('nvim_select_popupmenu_item', [idx, true, true, {}]) - } - - public async doAction(method: string, ...args: any[]): Promise { - return await this.plugin.cocAction(method, ...args) - } - - public async reset(): Promise { - let mode = await this.nvim.mode - if (mode.mode != 'n' || mode.blocking) { - await this.nvim.command('stopinsert') - await this.nvim.call('feedkeys', [String.fromCharCode(27), 'in']) - } - await this.nvim.command('silent! %bwipeout!') - await this.wait(80) - } - - public async pumvisible(): Promise { - let res = await this.nvim.call('pumvisible', []) as number - return res == 1 - } - - public wait(ms = 30): Promise { - return new Promise(resolve => { - setTimeout(() => { - resolve() - }, ms) - }) - } - - public async visible(word: string, source?: string): Promise { - await this.waitPopup() - let context = await this.nvim.getVar('coc#_context') as any - let items = context.candidates - if (!items) return false - let item = items.find(o => o.word == word) - if (!item || !item.user_data) return false - try { - let o = JSON.parse(item.user_data) - if (source && o.source !== source) { - return false - } - } catch (e) { - return false - } - return true - } - - public async notVisible(word: string): Promise { - let items = await this.getItems() - return items.findIndex(o => o.word == word) == -1 - } - - public async getItems(): Promise { - let visible = await this.pumvisible() - if (!visible) return [] - let context = await this.nvim.getVar('coc#_context') as any - let items = context.candidates - return items || [] - } - - public async edit(file?: string): Promise { - if (!file || !path.isAbsolute(file)) { - file = path.join(__dirname, file ? file : `${uuid()}`) - } - let escaped = await this.nvim.call('fnameescape', file) as string - await this.nvim.command(`edit ${escaped}`) - await this.wait(60) - let bufnr = await this.nvim.call('bufnr', ['%']) as number - return this.nvim.createBuffer(bufnr) - } - - public async createDocument(name?: string): Promise { - let buf = await this.edit(name) - let doc = workspace.getDocument(buf.id) - if (!doc) return await workspace.document - return doc - } - - public async getMarkers(bufnr: number, ns: number): Promise<[number, number, number][]> { - return await this.nvim.call('nvim_buf_get_extmarks', [bufnr, ns, 0, -1, {}]) as [number, number, number][] - } - - public async getCmdline(): Promise { - let str = '' - for (let i = 1, l = 70; i < l; i++) { - let ch = await this.nvim.call('screenchar', [79, i]) - if (ch == -1) break - str += String.fromCharCode(ch) - } - return str.trim() - } - - public updateConfiguration(key: string, value: any): () => void { - let { configurations } = workspace as any - let curr = workspace.getConfiguration(key) - configurations.updateUserConfig({ [key]: value }) - return () => { - configurations.updateUserConfig({ [key]: curr }) - } - } - - public async mockFunction(name: string, result: string | number | any): Promise { - let content = ` - function! ${name}(...) - return ${typeof result == 'number' ? result : JSON.stringify(result)} - endfunction - ` - let file = await createTmpFile(content) - await this.nvim.command(`source ${file}`) - } - - public async items(): Promise { - let context = await this.nvim.getVar('coc#_context') - return context['candidates'] || [] - } - - public async screenLine(line: number): Promise { - let res = '' - for (let i = 1; i <= 80; i++) { - let ch = await this.nvim.call('screenchar', [line, i]) - res = res + String.fromCharCode(ch) - } - return res - } - - public async getWinLines(winid: number): Promise { - return await this.nvim.eval(`getbufline(winbufnr(${winid}), 1, '$')`) as string[] - } - - public async getFloat(): Promise { - let wins = await this.nvim.windows - let floatWin: Window - for (let win of wins) { - let f = await win.getVar('float') - if (f) floatWin = win - } - return floatWin - } - - public async getFloats(): Promise { - let ids = await this.nvim.call('coc#float#get_float_win_list', []) - if (!ids) return [] - return ids.map(id => this.nvim.createWindow(id)) - } -} - -export async function createTmpFile(content: string): Promise { - let tmpFolder = path.join(os.tmpdir(), `coc-${process.pid}`) - if (!fs.existsSync(tmpFolder)) { - fs.mkdirSync(tmpFolder) - } - let filename = path.join(tmpFolder, uuid()) - await util.promisify(fs.writeFile)(filename, content, 'utf8') - return filename -} - -export default new Helper() diff --git a/vim-config/plugins/coc.nvim/src/__tests__/list/basicList.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/list/basicList.test.ts deleted file mode 100644 index 5f05063e..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/list/basicList.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { URI } from 'vscode-uri' -import { Disposable, Range, Location } from 'vscode-languageserver-protocol' -import BasicList, { getFiletype, PreviewOptions } from '../../list/basic' -import manager from '../../list/manager' -import { ListItem } from '../../types' -import { disposeAll } from '../../util' -import helper from '../helper' - -let nvim: Neovim -let disposables: Disposable[] = [] -let previewOptions: PreviewOptions - -let list: SimpleList -class SimpleList extends BasicList { - public name = 'simple' - public defaultAction: 'preview' - constructor(nvim: Neovim) { - super(nvim) - this.addAction('preview', async (_item, context) => { - await this.preview(previewOptions, context) - }) - } - public loadItems(): Promise { - return Promise.resolve(['a', 'b', 'c'].map((s, idx) => { - return { label: s, location: Location.create('test:///a', Range.create(idx, 0, idx + 1, 0)) } as ListItem - })) - } -} - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(() => { - list = new SimpleList(nvim) - disposables.push(manager.registerList(list)) -}) - -afterEach(async () => { - disposeAll(disposables) - manager.reset() - await helper.reset() -}) - -describe('getFiletype()', () => { - it('should get filetype', async () => { - expect(getFiletype('javascriptreact')).toBe('javascript') - expect(getFiletype('typescriptreact')).toBe('typescript') - expect(getFiletype('latex')).toBe('tex') - expect(getFiletype('foo.bar')).toBe('foo') - expect(getFiletype('foo')).toBe('foo') - }) -}) - -describe('BasicList', () => { - async function doPreview(opts: PreviewOptions): Promise { - previewOptions = opts - await manager.start(['--normal', 'simple']) - await manager.session.ui.ready - await manager.doAction('preview') - let res = await nvim.call('coc#list#has_preview') as number - expect(res).toBeGreaterThan(0) - let winid = await nvim.call('win_getid', [res]) - return winid - } - - describe('preview()', () => { - it('should preview lines', async () => { - await doPreview({ filetype: '', lines: ['foo', 'bar'] }) - }) - - it('should preview with bufname', async () => { - await doPreview({ - bufname: 't.js', - filetype: 'typescript', - lines: ['foo', 'bar'] - }) - }) - - it('should preview with range highlight', async () => { - let winid = await doPreview({ - bufname: 't.js', - filetype: 'typescript', - lines: ['foo', 'bar'], - range: Range.create(0, 0, 0, 3) - }) - let res = await nvim.call('getmatches', [winid]) - expect(res.length).toBeGreaterThan(0) - }) - - }) - - describe('createAction()', () => { - it('should overwrite action', async () => { - let idx: number - list.createAction({ - name: 'foo', - execute: () => { idx = 0 } - }) - list.createAction({ - name: 'foo', - execute: () => { idx = 1 } - }) - await manager.start(['--normal', 'simple']) - await manager.session.ui.ready - await manager.doAction('foo') - expect(idx).toBe(1) - }) - }) - - describe('jumpTo()', () => { - it('should jump to uri', async () => { - let uri = URI.file(__filename).toString() - await list.jumpTo(uri, 'edit') - let bufname = await nvim.call('bufname', ['%']) - expect(bufname).toMatch('basicList.test.ts') - }) - - it('should jump to location', async () => { - let uri = URI.file(__filename).toString() - let loc = Location.create(uri, Range.create(0, 0, 1, 0)) - await list.jumpTo(loc, 'edit') - let bufname = await nvim.call('bufname', ['%']) - expect(bufname).toMatch('basicList.test.ts') - }) - - it('should jump to location with empty range', async () => { - let uri = URI.file(__filename).toString() - let loc = Location.create(uri, Range.create(0, 0, 0, 0)) - await list.jumpTo(loc, 'edit') - let bufname = await nvim.call('bufname', ['%']) - expect(bufname).toMatch('basicList.test.ts') - }) - }) - - describe('convertLocation()', () => { - it('should convert uri', async () => { - let uri = URI.file(__filename).toString() - let res = await list.convertLocation(uri) - expect(res.uri).toBe(uri) - }) - - it('should convert location with line', async () => { - let uri = URI.file(__filename).toString() - let res = await list.convertLocation({ uri, line: 'convertLocation()', text: 'convertLocation' }) - expect(res.uri).toBe(uri) - res = await list.convertLocation({ uri, line: 'convertLocation()' }) - expect(res.uri).toBe(uri) - }) - - it('should convert location with custom schema', async () => { - let uri = 'test:///foo' - let res = await list.convertLocation({ uri, line: 'convertLocation()'}) - expect(res.uri).toBe(uri) - }) - }) - - describe('quickfix action', () => { - it('should invoke quickfix action', async () => { - list.addLocationActions() - await manager.start(['--normal', 'simple', '-arg']) - await manager.session.ui.ready - await manager.session.ui.selectAll() - await manager.doAction('quickfix') - let res = await nvim.call('getqflist') - expect(res.length).toBeGreaterThan(1) - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/list/commandTask.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/list/commandTask.test.ts deleted file mode 100644 index 37f2e00c..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/list/commandTask.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import path from 'path' -import { ListContext, ListTask } from '../../types' -import manager from '../../list/manager' -import helper, { createTmpFile } from '../helper' -import BasicList from '../../list/basic' -import { Disposable } from 'vscode-languageserver-protocol' -import { disposeAll } from '../../util' - -class DataList extends BasicList { - public name = 'data' - public async loadItems(_context: ListContext): Promise { - let fsPath = await createTmpFile(`console.log('foo');console.log('');console.log('bar');`) - return this.createCommandTask({ - cmd: 'node', - args: [fsPath], - cwd: path.dirname(fsPath), - onLine: line => { - if (!line) return undefined - return { - label: line - } - } - }) - } -} - -class SleepList extends BasicList { - public name = 'sleep' - public loadItems(_context: ListContext): Promise { - return Promise.resolve(this.createCommandTask({ - cmd: 'sleep', - args: ['10'], - cwd: __dirname, - onLine: line => { - return { - label: line - } - } - })) - } -} - -class StderrList extends BasicList { - public name = 'stderr' - public async loadItems(_context: ListContext): Promise { - let fsPath = await createTmpFile(`console.error('stderr');console.log('stdout')`) - return Promise.resolve(this.createCommandTask({ - cmd: 'node', - args: [fsPath], - cwd: path.dirname(fsPath), - onLine: line => { - return { - label: line - } - } - })) - } -} - -class ErrorTask extends BasicList { - public name = 'error' - public async loadItems(_context: ListContext): Promise { - return Promise.resolve(this.createCommandTask({ - cmd: 'NOT_EXISTS', - args: [], - cwd: __dirname, - onLine: line => { - return { - label: line - } - } - })) - } -} - -let nvim: Neovim -let disposables: Disposable[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - disposeAll(disposables) - manager.reset() - await helper.reset() -}) - -describe('Command task', () => { - it('should not show stderr', async () => { - disposables.push(manager.registerList(new StderrList(nvim))) - await manager.start(['stderr']) - await manager.session.ui.ready - let lines = await nvim.call('getline', [1, '$']) as string[] - expect(lines).toEqual(['stdout']) - }) - - it('should not show error', async () => { - disposables.push(manager.registerList(new ErrorTask(nvim))) - await manager.start(['error']) - await helper.wait(100) - let res = await helper.getCmdline() - expect(res).toMatch('NOT_EXISTS ENOENT') - }) - - it('should create command task', async () => { - let list = new DataList(nvim) - disposables.push(manager.registerList(list)) - await manager.start(['data']) - await helper.wait(500) - let lines = await nvim.call('getline', [1, '$']) as string[] - expect(lines).toEqual(['foo', 'bar']) - }) - - it('should stop command task', async () => { - let list = new SleepList(nvim) - disposables.push(manager.registerList(list)) - await manager.start(['sleep']) - manager.session.stop() - }) - - it('should show error for bad key', async () => { - let list = new DataList(nvim) - list.config.fixKey('') - await helper.wait(500) - let msg = await helper.getCmdline() - expect(msg).toMatch('not supported') - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/list/formatting.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/list/formatting.test.ts deleted file mode 100644 index b9a78433..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/list/formatting.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { formatPath, UnformattedListItem, formatListItems } from '../../list/formatting' - -describe('formatPath()', () => { - it('should format path', async () => { - expect(formatPath('hidden', 'path')).toBe('') - expect(formatPath('full', __filename)).toMatch('formatting.test.ts') - expect(formatPath('short', __filename)).toMatch('formatting.test.ts') - expect(formatPath('filename', __filename)).toMatch('formatting.test.ts') - }) -}) - -describe('formatListItems', () => { - it('should format list items', async () => { - expect(formatListItems(false, [])).toEqual([]) - let items: UnformattedListItem[] = [{ - label: ['a', 'b', 'c'] - }] - expect(formatListItems(false, items)).toEqual([{ - label: 'a\tb\tc' - }]) - items = [{ - label: ['a', 'b', 'c'] - }, { - label: ['foo', 'bar', 'go'] - }] - expect(formatListItems(true, items)).toEqual([{ - label: 'a \tb \tc ' - }, { - label: 'foo\tbar\tgo' - }]) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/list/location.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/list/location.test.ts deleted file mode 100644 index ef9a6eac..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/list/location.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import manager from '../../list/manager' -import { Range } from 'vscode-languageserver-protocol' -import events from '../../events' -import helper from '../helper' - -let nvim: Neovim -const locations: any[] = [{ - filename: __filename, - range: Range.create(0, 0, 0, 6), - text: 'foo' -}, { - filename: __filename, - range: Range.create(2, 0, 2, 6), - text: 'Bar' -}, { - filename: __filename, - range: Range.create(3, 0, 4, 6), - text: 'multiple' -}] - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - await nvim.setVar('coc_jump_locations', locations) -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - manager.reset() - await helper.reset() - await helper.wait(100) -}) - -describe('list commands', () => { - it('should highlight ranges', async () => { - await manager.start(['--normal', '--auto-preview', 'location']) - await manager.session.ui.ready - await helper.wait(200) - manager.prompt.cancel() - await nvim.command('wincmd k') - let name = await nvim.eval('bufname("%")') - expect(name).toMatch('location.test.ts') - let res = await nvim.call('getmatches') - expect(res.length).toBe(1) - }) - - it('should change highlight on cursor move', async () => { - await manager.start(['--normal', '--auto-preview', 'location']) - await manager.session.ui.ready - await helper.wait(200) - await nvim.command('exe 2') - let bufnr = await nvim.eval('bufnr("%")') - await events.fire('CursorMoved', [bufnr, [2, 1]]) - await helper.wait(300) - await nvim.command('wincmd k') - let res = await nvim.call('getmatches') - expect(res.length).toBe(1) - expect(res[0]['pos1']).toEqual([3, 1, 6]) - }) - - it('should highlight multiple line range', async () => { - await manager.start(['--normal', '--auto-preview', 'location']) - await manager.session.ui.ready - await helper.wait(200) - await nvim.command('exe 3') - let bufnr = await nvim.eval('bufnr("%")') - await events.fire('CursorMoved', [bufnr, [2, 1]]) - await helper.wait(300) - await nvim.command('wincmd k') - let res = await nvim.call('getmatches') - expect(res.length).toBe(1) - expect(res[0]['pos1']).toBeDefined() - expect(res[0]['pos2']).toBeDefined() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/list/manager.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/list/manager.test.ts deleted file mode 100644 index b6b7a863..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/list/manager.test.ts +++ /dev/null @@ -1,509 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import path from 'path' -import manager from '../../list/manager' -import events from '../../events' -import { QuickfixItem, IList, ListItem } from '../../types' -import helper from '../helper' - -let nvim: Neovim -const locations: ReadonlyArray = [{ - filename: __filename, - col: 2, - lnum: 1, - text: 'foo' -}, { - filename: __filename, - col: 1, - lnum: 2, - text: 'Bar' -}, { - filename: __filename, - col: 1, - lnum: 3, - text: 'option' -}] - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - await nvim.setVar('coc_jump_locations', locations) -}) - -afterEach(async () => { - manager.reset() - await helper.reset() -}) - -afterAll(async () => { - await helper.shutdown() -}) - -describe('list', () => { - describe('events', () => { - it('should cancel and enable prompt', async () => { - let winid = await nvim.call('win_getid') - await manager.start(['location']) - await manager.session.ui.ready - await nvim.call('win_gotoid', [winid]) - await helper.wait(50) - let res = await nvim.call('coc#prompt#activated') - expect(res).toBe(0) - await nvim.command('wincmd p') - await helper.wait(50) - res = await nvim.call('coc#prompt#activated') - expect(res).toBe(1) - }) - }) - - describe('list commands', () => { - it('should be activated', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await helper.wait(50) - expect(manager.isActivated).toBe(true) - let line = await nvim.getLine() - expect(line).toMatch(/manager.test.ts/) - }) - - it('should get list names', () => { - let names = manager.names - expect(names.length > 0).toBe(true) - }) - - it('should resume list', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await helper.wait(30) - await nvim.eval('feedkeys("j", "in")') - await helper.wait(30) - let line = await nvim.call('line', '.') - expect(line).toBe(2) - await manager.cancel() - await helper.wait(30) - await manager.resume() - await helper.wait(30) - line = await nvim.call('line', '.') - expect(line).toBe(2) - }) - - it('should not quit list with --no-quit', async () => { - await manager.start(['--normal', '--no-quit', 'location']) - await manager.session.ui.ready - let winnr = await nvim.eval('win_getid()') as number - await manager.doAction() - await helper.wait(100) - let wins = await nvim.windows - let ids = wins.map(o => o.id) - expect(ids).toContain(winnr) - }) - - it('should do default action for first item', async () => { - await manager.start(['--normal', '--first', 'location']) - await helper.wait(300) - let name = await nvim.eval('bufname("%")') as string - let filename = path.basename(__filename) - expect(name.includes(filename)).toBe(true) - let pos = await nvim.eval('getcurpos()') - expect(pos[1]).toBe(1) - expect(pos[2]).toBe(2) - }) - - it('should goto next & previous', async () => { - await manager.start(['location']) - await manager.session?.ui.ready - await helper.wait(60) - await manager.doAction() - await manager.cancel() - let bufname = await nvim.eval('expand("%:p")') - expect(bufname).toMatch('manager.test.ts') - await manager.next() - let line = await nvim.call('line', '.') - expect(line).toBe(2) - await helper.wait(60) - await manager.previous() - line = await nvim.call('line', '.') - expect(line).toBe(1) - }) - - it('should parse arguments', async () => { - await manager.start(['--input=test', '--normal', '--no-sort', '--ignore-case', '--top', '--number-select', '--auto-preview', '--strict', 'location']) - await helper.wait(30) - let opts = manager.session?.listOptions - expect(opts).toEqual({ - numberSelect: true, - autoPreview: true, - first: false, - input: 'test', - interactive: false, - matcher: 'strict', - ignorecase: true, - position: 'top', - mode: 'normal', - noQuit: false, - sort: false - }) - }) - }) - - describe('list options', () => { - it('should respect input option', async () => { - await manager.start(['--input=foo', 'location']) - await manager.session.ui.ready - await helper.wait(30) - let line = await helper.getCmdline() - expect(line).toMatch('foo') - expect(manager.isActivated).toBe(true) - }) - - it('should respect regex filter', async () => { - await manager.start(['--input=f.o', '--regex', 'location']) - await helper.wait(200) - let item = await manager.session?.ui.item - expect(item.label).toMatch('foo') - }) - - it('should respect normal option', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - let line = await helper.getCmdline() - expect(line).toBe('') - }) - - it('should respect nosort option', async () => { - await manager.start(['--ignore-case', '--no-sort', 'location']) - await manager.session.ui.ready - expect(manager.isActivated).toBe(true) - await nvim.input('oo') - await helper.wait(100) - let line = await nvim.call('getline', ['.']) - expect(line).toMatch('foo') - }) - - it('should respect ignorecase option', async () => { - await manager.start(['--ignore-case', '--strict', 'location']) - await manager.session.ui.ready - expect(manager.isActivated).toBe(true) - await nvim.input('bar') - await helper.wait(100) - let n = manager.session?.ui.length - expect(n).toBe(1) - let line = await nvim.line - expect(line).toMatch('Bar') - }) - - it('should respect top option', async () => { - await manager.start(['--top', 'location']) - await manager.session.ui.ready - let nr = await nvim.call('winnr') - expect(nr).toBe(1) - }) - - it('should respect number select option', async () => { - await manager.start(['--number-select', 'location']) - await manager.session.ui.ready - await helper.wait(100) - await nvim.eval('feedkeys("2", "in")') - await helper.wait(100) - let lnum = locations[1].lnum - let curr = await nvim.call('line', '.') - expect(lnum).toBe(curr) - }) - - it('should respect auto preview option', async () => { - await manager.start(['--auto-preview', 'location']) - await helper.wait(300) - let previewWinnr = await nvim.call('coc#list#has_preview') - expect(previewWinnr).toBe(2) - let bufnr = await nvim.call('winbufnr', previewWinnr) - let buf = nvim.createBuffer(bufnr) - let name = await buf.name - expect(name).toMatch('manager.test.ts') - await nvim.eval('feedkeys("j", "in")') - await helper.wait(100) - let winnr = await nvim.call('coc#list#has_preview') - expect(winnr).toBe(previewWinnr) - }) - - it('should respect tab option', async () => { - await manager.start(['--tab', '--auto-preview', 'location']) - await manager.session.ui.ready - await helper.wait(200) - await nvim.command('wincmd l') - let previewwindow = await nvim.eval('w:previewwindow') - expect(previewwindow).toBe(1) - }) - }) - - describe('list configuration', () => { - it('should change indicator', async () => { - helper.updateConfiguration('list.indicator', '>>') - await manager.start(['location']) - await helper.wait(200) - let line = await helper.getCmdline() - expect(line).toMatch('>>') - }) - - it('should split right for preview window', async () => { - helper.updateConfiguration('list.previewSplitRight', true) - let win = await nvim.window - await manager.start(['location']) - await helper.wait(100) - await manager.doAction('preview') - await helper.wait(100) - manager.prompt.cancel() - await helper.wait(10) - await nvim.call('win_gotoid', [win.id]) - await nvim.command('wincmd l') - let curr = await nvim.window - let isPreview = await curr.getVar('previewwindow') - expect(isPreview).toBe(1) - helper.updateConfiguration('list.previewSplitRight', false) - }) - - it('should toggle selection mode', async () => { - await manager.start(['--normal', 'location']) - await manager.session?.ui.ready - await nvim.input('V') - await helper.wait(30) - await nvim.input('1') - await helper.wait(30) - await nvim.input('j') - await helper.wait(100) - await manager.session?.ui.toggleSelection() - let items = await manager.session?.ui.getItems() - expect(items.length).toBe(2) - }) - - it('should change next/previous keymap', async () => { - helper.updateConfiguration('list.nextKeymap', '') - helper.updateConfiguration('list.previousKeymap', '') - await manager.start(['location']) - await manager.session.ui.ready - await helper.wait(100) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - let line = await nvim.line - expect(line).toMatch('Bar') - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - line = await nvim.line - expect(line).toMatch('foo') - }) - - it('should respect mouse events', async () => { - async function setMouseEvent(line: number): Promise { - let winid = manager.session?.ui.winid - await nvim.command(`let v:mouse_winid = ${winid}`) - await nvim.command(`let v:mouse_lnum = ${line}`) - await nvim.command(`let v:mouse_col = 1`) - } - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await helper.wait(100) - await setMouseEvent(1) - await manager.onNormalInput('') - await setMouseEvent(2) - await manager.onNormalInput('') - await setMouseEvent(3) - await manager.onNormalInput('') - await helper.wait(100) - let items = await manager.session?.ui.getItems() - expect(items.length).toBe(3) - }) - - it('should toggle preview', async () => { - await manager.start(['--normal', '--auto-preview', 'location']) - await manager.session.ui.ready - await helper.wait(100) - await manager.togglePreview() - await helper.wait(100) - await manager.togglePreview() - await helper.wait(100) - let has = await nvim.call('coc#list#has_preview') - expect(has).toBeGreaterThan(0) - }) - - it('should show help of current list', async () => { - await manager.start(['--normal', '--auto-preview', 'location']) - await helper.wait(200) - await manager.session?.showHelp() - let bufname = await nvim.call('bufname', '%') - expect(bufname).toBe('[LIST HELP]') - }) - - it('should resolve list item', async () => { - let list: IList = { - name: 'test', - actions: [{ - name: 'open', execute: _item => { - // noop - } - }], - defaultAction: 'open', - loadItems: () => Promise.resolve([{ label: 'foo' }, { label: 'bar' }]), - resolveItem: item => { - item.label = item.label.slice(0, 1) - return Promise.resolve(item) - } - } - let disposable = manager.registerList(list) - await manager.start(['--normal', 'test']) - await manager.session.ui.ready - await helper.wait(50) - let line = await nvim.line - expect(line).toBe('f') - disposable.dispose() - }) - }) - - describe('descriptions', () => { - it('should get descriptions', async () => { - let res = manager.descriptions - expect(res).toBeDefined() - expect(res.location).toBeDefined() - }) - }) - - describe('loadItems()', () => { - it('should load items for list', async () => { - let res = await manager.loadItems('location') - expect(res.length).toBeGreaterThan(0) - ; (manager as any).lastSession = undefined - manager.toggleMode() - manager.stop() - }) - }) - - describe('onInsertInput()', () => { - it('should handle insert input', async () => { - await manager.onInsertInput('k') - await manager.onInsertInput('') - await manager.start(['--number-select', 'location']) - await manager.session.ui.ready - await manager.onInsertInput('1') - await helper.wait(300) - let bufname = await nvim.call('expand', ['%:p']) - expect(bufname).toMatch('manager.test.ts') - }) - - it('should ignore invalid input', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await manager.onInsertInput('') - await manager.onInsertInput(String.fromCharCode(65533)) - await manager.onInsertInput(String.fromCharCode(30)) - expect(manager.isActivated).toBe(true) - }) - - it('should ignore insert', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\x", "in")') - await helper.wait(50) - expect(manager.isActivated).toBe(true) - }) - }) - - describe('parseArgs()', () => { - it('should show error for bad option', async () => { - manager.parseArgs(['$x', 'location']) - let msg = await helper.getCmdline() - expect(msg).toMatch('Invalid list option') - }) - - it('should show error for option not exists', async () => { - manager.parseArgs(['-xyz', 'location']) - let msg = await helper.getCmdline() - expect(msg).toMatch('Invalid option') - }) - - it('should show error for interactive with list not support interactive', async () => { - manager.parseArgs(['--interactive', 'location']) - let msg = await helper.getCmdline() - expect(msg).toMatch('not supported') - }) - }) - - describe('resume()', () => { - it('should resume by name', async () => { - await events.fire('FocusGained', []) - await manager.start(['location']) - await manager.session.ui.ready - await helper.wait(50) - await manager.session.hide() - await helper.wait(100) - await manager.resume('location') - expect(manager.isActivated).toBe(true) - }) - }) - - describe('start()', () => { - it('should show error when loadItems throws', async () => { - let list: IList = { - name: 'test', - actions: [{ - name: 'open', - execute: (_item: ListItem) => { - } - }], - defaultAction: 'open', - loadItems: () => { - throw new Error('test error') - } - } - manager.registerList(list) - await manager.start(['test']) - await helper.wait(50) - let msg = await helper.getCmdline() - expect(msg).toMatch('test error') - }) - }) - - describe('first(), last()', () => { - it('should get session by name', async () => { - let last: string - let list: IList = { - name: 'test', - actions: [{ - name: 'open', - execute: (item: ListItem) => { - last = item.label - } - }], - defaultAction: 'open', - loadItems: () => Promise.resolve([{ label: 'foo' }, { label: 'bar' }]) - } - manager.registerList(list) - await manager.start(['test']) - await manager.session.ui.ready - await manager.first('a') - await manager.last('a') - await manager.first('test') - expect(last).toBe('foo') - await manager.last('test') - expect(last).toBe('bar') - }) - }) - - describe('registerList()', () => { - it('should recreat list', async () => { - let list: IList = { - name: 'test', - actions: [{ - name: 'open', execute: _item => { - // noop - } - }], - defaultAction: 'open', - loadItems: () => Promise.resolve([{ label: 'foo' }, { label: 'bar' }]) - } - manager.registerList(list) - helper.updateConfiguration('list.source.test.defaultAction', 'open') - let disposable = manager.registerList(list) - disposable.dispose() - await helper.wait(30) - let msg = await helper.getCmdline() - expect(msg).toMatch('recreated') - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/list/mappings.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/list/mappings.test.ts deleted file mode 100644 index 3cce87c3..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/list/mappings.test.ts +++ /dev/null @@ -1,903 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationToken } from 'vscode-jsonrpc' -import BasicList from '../../list/basic' -import manager from '../../list/manager' -import window from '../../window' -import { ListContext, IList, ListItem, QuickfixItem } from '../../types' -import helper from '../helper' - -class TestList extends BasicList { - public name = 'test' - public timeout = 3000 - public text = 'test' - public detail = 'detail' - public loadItems(_context: ListContext, token: CancellationToken): Promise { - return new Promise(resolve => { - let timer = setTimeout(() => { - resolve([{ label: this.text }]) - }, this.timeout) - token.onCancellationRequested(() => { - if (timer) { - clearTimeout(timer) - resolve([]) - } - }) - }) - } -} - -let nvim: Neovim -const locations: ReadonlyArray = [{ - filename: __filename, - col: 2, - lnum: 1, - text: 'foo' -}, { - filename: __filename, - col: 1, - lnum: 2, - text: 'Bar' -}, { - filename: __filename, - col: 1, - lnum: 3, - text: 'option' -}] - -const lineList: IList = { - name: 'lines', - actions: [{ - name: 'open', - execute: async item => { - await window.moveTo({ - line: (item as ListItem).data.line, - character: 0 - }) - // noop - } - }], - defaultAction: 'open', - async loadItems(_context, _token): Promise { - let lines = [] - for (let i = 0; i < 100; i++) { - lines.push(i.toString()) - } - return lines.map((line, idx) => ({ - label: line, - data: { line: idx } - })) - } -} - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - await nvim.setVar('coc_jump_locations', locations) -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - manager.reset() - await helper.reset() -}) - -describe('list normal mappings', () => { - it('should tabopen by t', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("t", "in")') - await helper.wait(100) - let nr = await nvim.call('tabpagenr') - expect(nr).toBe(2) - }) - - it('should open by ', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - let bufname = await nvim.call('expand', ['%:p']) - expect(bufname).toMatch('mappings.test.ts') - }) - - it('should stop by ', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(50) - let loading = manager.session?.worker.isLoading - expect(loading).toBe(false) - }) - - it('should jump back by ', async () => { - let doc = await helper.createDocument() - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(50) - let bufnr = await nvim.call('bufnr', ['%']) - expect(bufnr).toBe(doc.bufnr) - }) - - it('should scroll preview window by , ', async () => { - await helper.createDocument() - await manager.start(['--auto-preview', '--normal', 'location']) - await manager.session.ui.ready - await helper.wait(100) - let winnr = await nvim.call('coc#list#has_preview') as number - expect(winnr).toBeGreaterThan(0) - let winid = await nvim.call('win_getid', [winnr]) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(50) - let res = await nvim.call('getwininfo', [winid]) - expect(res[0].topline).toBeGreaterThan(1) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(50) - res = await nvim.call('getwininfo', [winid]) - expect(res[0].topline).toBeLessThan(7) - }) - - it('should insert command by :', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys(":", "in")') - await helper.wait(50) - await nvim.eval('feedkeys("let g:x = 1\\", "in")') - await helper.wait(50) - let res = await nvim.getVar('x') - expect(res).toBe(1) - }) - - it('should select action by ', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - await nvim.input('t') - await helper.wait(300) - let nr = await nvim.call('tabpagenr') - expect(nr).toBe(2) - }) - - it('should preview by p', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await helper.wait(50) - await nvim.eval('feedkeys("p", "in")') - await helper.wait(200) - let winnr = await nvim.call('coc#list#has_preview') - expect(winnr).toBe(2) - }) - - it('should stop task by ', async () => { - let disposable = manager.registerList(new TestList(nvim)) - let p = manager.start(['--normal', 'test']) - await helper.wait(200) - await nvim.input('') - await helper.wait(200) - await p - let len = manager.session?.ui.length - expect(len).toBe(0) - disposable.dispose() - }) - - it('should cancel list by ', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(200) - expect(manager.isActivated).toBe(false) - }) - - it('should reload list by ', async () => { - let list = new TestList(nvim) - list.timeout = 0 - let disposable = manager.registerList(list) - await manager.start(['--normal', 'test']) - await manager.session.ui.ready - list.text = 'new' - await nvim.input('') - await helper.wait(30) - let line = await nvim.line - expect(line).toMatch('new') - disposable.dispose() - }) - - it('should select all items by ', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.input('') - await helper.wait(30) - let selected = manager.session?.ui.selectedItems - expect(selected.length).toBe(locations.length) - }) - - it('should toggle selection ', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - let selected = manager.session?.ui.selectedItems - expect(selected.length).toBe(1) - await nvim.eval('feedkeys("k", "in")') - await helper.wait(100) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - selected = manager.session?.ui.selectedItems - expect(selected.length).toBe(0) - }) - - it('should change to insert mode by i, o, a', async () => { - let keys = ['i', 'I', 'o', 'O', 'a', 'A'] - for (let key of keys) { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await helper.wait(50) - await nvim.eval(`feedkeys("${key}", "in")`) - await helper.wait(100) - let mode = manager.prompt.mode - expect(mode).toBe('insert') - } - }) - - it('should show help by ?', async () => { - await manager.start(['--normal', 'location']) - await helper.wait(30) - await nvim.eval('feedkeys("?", "in")') - await helper.wait(30) - await nvim.input('') - await helper.wait(100) - let bufname = await nvim.call('bufname', '%') - expect(bufname).toBe('[LIST HELP]') - }) - - it('should drop by d', async () => { - await manager.start(['--normal', 'location']) - await helper.wait(30) - await nvim.eval('feedkeys("d", "in")') - await helper.wait(100) - let nr = await nvim.call('tabpagenr') - expect(nr).toBe(1) - }) - - it('should split by s', async () => { - await manager.start(['--normal', 'location']) - await helper.wait(30) - await nvim.eval('feedkeys("s", "in")') - await helper.wait(100) - let nr = await nvim.call('winnr') - expect(nr).toBe(1) - }) -}) - -describe('list insert mappings', () => { - it('should open by ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - let bufname = await nvim.call('expand', ['%:p']) - expect(bufname).toMatch('mappings.test.ts') - }) - - it('should paste input by ', async () => { - await nvim.call('setreg', ['*', 'foo']) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - let input = manager.prompt.input - expect(input).toBe('foo') - }) - - it('should insert register content by ', async () => { - await nvim.call('setreg', ['*', 'foo']) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - await nvim.eval('feedkeys("*", "in")') - await helper.wait(100) - let input = manager.prompt.input - expect(input).toBe('foo') - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - await nvim.eval('feedkeys("<", "in")') - await helper.wait(100) - input = manager.prompt.input - expect(input).toBe('foo') - manager.prompt.reset() - }) - - it('should cancel by ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - expect(manager.isActivated).toBe(false) - }) - - it('should select action by ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await helper.wait(100) - nvim.call('eval', 'feedkeys("\\", "in")', true) - await helper.wait(100) - await nvim.input('t') - await helper.wait(500) - let pages = await nvim.tabpages - expect(pages.length).toBe(2) - }) - - it('should select action for visual selected items', async () => { - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await helper.wait(100) - await nvim.input('V') - await helper.wait(30) - await nvim.input('2') - await helper.wait(30) - await nvim.input('j') - await helper.wait(30) - await manager.doAction('tabe') - let nr = await nvim.call('tabpagenr') - expect(nr).toBeGreaterThan(3) - }) - - it('should stop loading by ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - expect(manager.isActivated).toBe(true) - }) - - it('should reload by ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - expect(manager.isActivated).toBe(true) - }) - - it('should change to normal mode by ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - expect(manager.isActivated).toBe(true) - let line = await helper.getCmdline() - expect(line).toBe('') - }) - - it('should select line by and ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(50) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(50) - expect(manager.isActivated).toBe(true) - let line = await nvim.line - expect(line).toMatch('foo') - }) - - it('should move cursor by and ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("f", "in")') - await helper.wait(10) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(10) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(10) - await nvim.eval('feedkeys("a", "in")') - await helper.wait(10) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(10) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(10) - await nvim.eval('feedkeys("c", "in")') - await helper.wait(10) - let input = manager.prompt.input - expect(input).toBe('afc') - }) - - it('should move cursor by and ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - await nvim.eval('feedkeys("\\a", "in")') - await helper.wait(30) - let input = manager.prompt.input - expect(input).toBe('a') - }) - - it('should move cursor by ', async () => { - let disposable = manager.registerList(lineList) - await manager.start(['lines']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - let line = await nvim.eval('line(".")') - expect(line).toBeGreaterThan(1) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - disposable.dispose() - }) - - it('should scroll window by and ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await helper.wait(30) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - }) - - it('should change input by ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("f", "in")') - await helper.wait(30) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - let input = manager.prompt.input - expect(input).toBe('') - }) - - it('should change input by ', async () => { - let revert = helper.updateConfiguration('list.insertMappings', { - '': 'prompt:removetail', - }) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("foo", "in")') - await helper.wait(30) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - let input = manager.prompt.input - revert() - expect(input).toBe('') - }) - - it('should change input by ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("f", "in")') - await helper.wait(30) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - let input = manager.prompt.input - expect(input).toBe('') - }) - - it('should change input by ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - await nvim.eval('feedkeys("f", "in")') - await helper.wait(30) - await nvim.eval('feedkeys("a", "in")') - await helper.wait(30) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - let input = manager.prompt.input - expect(input).toBe('') - }) - - it('should change input by ', async () => { - await manager.start(['--input=a', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - let input = manager.prompt.input - expect(input).toBe('') - }) - - it('should change input by and ', async () => { - async function session(input: string): Promise { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("${input}", "in")`) - await helper.wait(100) - await manager.cancel() - } - await session('foo') - await session('bar') - await manager.start(['location']) - await manager.session.ui.ready - await helper.wait(50) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - let input = manager.prompt.input - expect(input.length).toBeGreaterThan(0) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - input = manager.prompt.input - expect(input.length).toBeGreaterThan(0) - }) - - it('should change matcher by ', async () => { - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(10) - let matcher = manager.session?.listOptions.matcher - expect(matcher).toBe('strict') - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(10) - matcher = manager.session?.listOptions.matcher - expect(matcher).toBe('regex') - await nvim.eval('feedkeys("f", "in")') - await helper.wait(30) - let len = manager.session?.ui.length - expect(len).toBeGreaterThan(0) - }) -}) - -describe('evalExpression', () => { - it('should throw for bad expression', async () => { - let revert = helper.updateConfiguration('list.normalMappings', { - t: 'expr', - }) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("t", "in")') - await helper.wait(30) - revert() - let msg = await helper.getCmdline() - expect(msg).toMatch('Invalid list mapping expression') - }) - - it('should show help', async () => { - helper.updateConfiguration('list.normalMappings', { - t: 'do:help', - }) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("t", "in")') - await helper.wait(50) - let bufname = await nvim.call('bufname', ['%']) - expect(bufname).toMatch('[LIST HELP]') - }) - - it('should exit list', async () => { - helper.updateConfiguration('list.normalMappings', { - t: 'do:exit', - }) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("t", "in")') - await helper.wait(50) - expect(manager.isActivated).toBe(false) - }) - - it('should cancel prompt', async () => { - helper.updateConfiguration('list.normalMappings', { - t: 'do:cancel', - }) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("t", "in")') - await helper.wait(50) - let res = await nvim.call('coc#prompt#activated') - expect(res).toBe(0) - }) - - it('should jump back', async () => { - let doc = await helper.createDocument() - helper.updateConfiguration('list.normalMappings', { - t: 'do:jumpback', - }) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("t", "in")') - await helper.wait(50) - let bufnr = await nvim.call('bufnr', ['%']) - expect(bufnr).toBe(doc.bufnr) - }) - - it('should invoke normal command', async () => { - let revert = helper.updateConfiguration('list.normalMappings', { - x: 'normal!:G' - }) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("x", "in")`) - await helper.wait(50) - revert() - let lnum = await nvim.call('line', ['.']) - expect(lnum).toBeGreaterThan(1) - }) - - it('should toggle, scroll preview', async () => { - let revert = helper.updateConfiguration('list.normalMappings', { - '': 'do:toggle', - a: 'do:toggle', - b: 'do:previewtoggle', - c: 'do:previewup', - d: 'do:previewdown', - e: 'prompt:insertregister', - f: 'do:stop', - g: 'do:togglemode', - }) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys(" ", "in")`) - await helper.wait(50) - for (let key of ['a', 'b', 'c', 'd', 'e', 'f', 'g']) { - await nvim.eval(`feedkeys("${key}", "in")`) - await helper.wait(50) - } - revert() - expect(manager.isActivated).toBe(true) - }) - - it('should show error when action not exists', async () => { - helper.updateConfiguration('list.normalMappings', { - t: 'do:invalid', - }) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("t", "in")') - await helper.wait(50) - let cmd = await helper.getCmdline() - expect(cmd).toMatch('not supported') - }) - - it('should show error when prompt action not exists', async () => { - helper.updateConfiguration('list.normalMappings', { - t: 'prompt:invalid', - }) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("t", "in")') - await helper.wait(50) - let cmd = await helper.getCmdline() - expect(cmd).toMatch('not supported') - }) - - it('should show error for invalid expression ', async () => { - helper.updateConfiguration('list.normalMappings', { - t: 'x:y', - }) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("t", "in")') - await helper.wait(50) - let cmd = await helper.getCmdline() - expect(cmd).toMatch('Invalid expression') - }) -}) - -describe('User mappings', () => { - it('should show warning for invalid key', async () => { - let revert = helper.updateConfiguration('list.insertMappings', { - xy: 'action:tabe', - }) - await helper.wait(30) - let msg = await helper.getCmdline() - revert() - await nvim.command('echo ""') - expect(msg).toMatch('Invalid list mappings key') - revert = helper.updateConfiguration('list.insertMappings', { - '': 'action:tabe', - }) - await helper.wait(30) - msg = await helper.getCmdline() - revert() - expect(msg).toMatch('Invalid list mappings key') - }) - - it('should execute action keymap', async () => { - await helper.wait(200) - let revert = helper.updateConfiguration('list.insertMappings', { - '': 'action:tabe', - }) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("\\", "in")`) - await helper.wait(200) - let nr = await nvim.call('tabpagenr') - expect(nr).toBe(2) - revert() - }) - - it('should execute expr keymap', async () => { - await helper.mockFunction('TabOpen', 'tabe') - helper.updateConfiguration('list.insertMappings', { - '': 'expr:TabOpen', - }) - helper.updateConfiguration('list.normalMappings', { - t: 'expr:TabOpen', - }) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("\\", "in")`) - await helper.wait(100) - let nr = await nvim.call('tabpagenr') - expect(nr).toBe(2) - await manager.start(['--normal', 'location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("t", "in")`) - await helper.wait(100) - nr = await nvim.call('tabpagenr') - expect(nr).toBe(3) - }) - - it('should execute do mappings', async () => { - helper.updateConfiguration('list.previousKeymap', '') - helper.updateConfiguration('list.nextKeymap', '') - helper.updateConfiguration('list.insertMappings', { - '': 'do:refresh', - '': 'do:selectall', - '': 'do:switch', - '': 'do:cancel', - '': 'do:toggle', - '': 'do:next', - '': 'do:previous', - '': 'do:defaultaction', - '': 'do:help', - '': 'do:exit', - '': 'do:toggleMode' - }) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - expect(manager.isActivated).toBe(true) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - expect(manager.session?.ui.selectedItems.length).toBe(locations.length) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - expect(manager.session?.listOptions.matcher).toBe('strict') - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - let item = await manager.session?.ui.item - expect(item.label).toMatch(locations[1].text) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - item = await manager.session?.ui.item - expect(item.label).toMatch(locations[0].text) - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(30) - expect(manager.isActivated).toBe(false) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(50) - let res = await nvim.call('coc#prompt#activated') - expect(res).toBe(0) - await manager.session.hide() - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("?", "in")') - await helper.wait(30) - await nvim.input('') - await manager.cancel() - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - expect(manager.isActivated).toBe(false) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(100) - expect(manager.isActivated).toBe(true) - await nvim.call('coc#prompt#stop_prompt', ['list']) - }, 20000) - - it('should execute prompt mappings', async () => { - helper.updateConfiguration('list.insertMappings', { - '': 'prompt:previous', - '': 'prompt:next', - '': 'prompt:start', - '': 'prompt:end', - '': 'prompt:left', - '': 'prompt:right', - '': 'prompt:deleteforward', - '': 'prompt:deletebackward', - '': 'prompt:removetail', - '': 'prompt:removeahead', - }) - await manager.start(['location']) - await manager.session.ui.ready - for (let key of ['', '', '', '', '', '', '', '', '', '']) { - await nvim.input(key) - await helper.wait(30) - } - expect(manager.isActivated).toBe(true) - }) - - it('should execute feedkeys keymap', async () => { - helper.updateConfiguration('list.insertMappings', { - '': 'feedkeys:\\', - }) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("\\", "in")`) - await helper.wait(30) - let line = await nvim.call('line', '.') - expect(line).toBe(locations.length) - }) - - it('should execute normal keymap', async () => { - helper.updateConfiguration('list.insertMappings', { - '': 'normal:G', - }) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("\\", "in")`) - await helper.wait(30) - let line = await nvim.call('line', '.') - expect(line).toBe(locations.length) - }) - - it('should execute command keymap', async () => { - helper.updateConfiguration('list.insertMappings', { - '': 'command:wincmd p', - }) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("\\", "in")`) - await helper.wait(30) - expect(manager.isActivated).toBe(true) - let winnr = await nvim.call('winnr') - expect(winnr).toBe(1) - }) - - it('should execute call keymap', async () => { - await helper.mockFunction('Test', 1) - helper.updateConfiguration('list.insertMappings', { - '': 'call:Test', - }) - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("\\", "in")`) - await helper.wait(30) - expect(manager.isActivated).toBe(true) - }) - - it('should insert clipboard register to prompt', async () => { - helper.updateConfiguration('list.insertMappings', { - '': 'prompt:paste', - }) - await nvim.command('let @* = "foobar"') - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("\\", "in")`) - await helper.wait(100) - let { input } = manager.prompt - expect(input).toMatch('foobar') - await nvim.command('let @* = ""') - await nvim.eval(`feedkeys("\\", "in")`) - await helper.wait(100) - expect(manager.prompt.input).toMatch('foobar') - }) - - it('should insert text from default register to prompt', async () => { - helper.updateConfiguration('list.insertMappings', { - '': 'eval:@@', - }) - await nvim.command('let @@ = "bar"') - await manager.start(['location']) - await manager.session.ui.ready - await nvim.eval(`feedkeys("\\", "in")`) - await helper.wait(200) - let { input } = manager.prompt - expect(input).toMatch('bar') - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/list/session.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/list/session.test.ts deleted file mode 100644 index 5d4c3ef1..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/list/session.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import BasicList from '../../list/basic' -import manager from '../../list/manager' -import ListSession from '../../list/session' -import { ListItem } from '../../types' -import { disposeAll } from '../../util' -import helper from '../helper' - -let labels: string[] = [] -let lastItem: string -let lastItems: ListItem[] - -class SimpleList extends BasicList { - public name = 'simple' - public detail = 'detail' - public options = [{ - name: 'foo', - description: 'foo' - }] - constructor(nvim: Neovim) { - super(nvim) - this.addAction('open', item => { - lastItem = item.label - }) - this.addMultipleAction('multiple', items => { - lastItems = items - }) - this.addAction('parallel', async () => { - await helper.wait(100) - }, { parallel: true }) - this.addAction('reload', item => { - lastItem = item.label - }, { persist: true, reload: true }) - } - public loadItems(): Promise { - return Promise.resolve(labels.map(s => { - return { label: s } as ListItem - })) - } -} - -let nvim: Neovim -let disposables: Disposable[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - disposeAll(disposables) - manager.reset() - await helper.reset() -}) - -describe('list session', () => { - describe('doDefaultAction()', () => { - it('should throw error when default action not exists', async () => { - labels = ['a', 'b', 'c'] - let list = new SimpleList(nvim) - list.defaultAction = 'foo' - disposables.push(manager.registerList(list)) - await manager.start(['--normal', 'simple']) - let ui = manager.session.ui - await ui.ready - let err - try { - await manager.session.first() - } catch (e) { - err = e - } - expect(err).toBeDefined() - err = null - try { - await manager.session.last() - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - }) - - describe('doItemAction()', () => { - it('should invoke multiple action', async () => { - labels = ['a', 'b', 'c'] - let list = new SimpleList(nvim) - disposables.push(manager.registerList(list)) - await manager.start(['--normal', 'simple']) - let ui = manager.session.ui - await ui.ready - await ui.selectAll() - await manager.doAction('multiple') - expect(lastItems.length).toBe(3) - lastItems = undefined - }) - - it('should invoke parallel action', async () => { - labels = ['a', 'b', 'c'] - let list = new SimpleList(nvim) - disposables.push(manager.registerList(list)) - await manager.start(['--normal', 'simple']) - let ui = manager.session.ui - await ui.ready - await ui.selectAll() - let d = Date.now() - await manager.doAction('parallel') - expect(Date.now() - d).toBeLessThan(300) - }) - - it('should invoke reload action', async () => { - labels = ['a', 'b', 'c'] - let list = new SimpleList(nvim) - disposables.push(manager.registerList(list)) - await manager.start(['--normal', 'simple']) - let ui = manager.session.ui - await ui.ready - labels = ['d', 'e'] - await manager.doAction('reload') - await helper.wait(50) - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual(['d', 'e']) - }) - }) - - describe('resume()', () => { - it('should do preview on resume', async () => { - labels = ['a', 'b', 'c'] - let lastItem - let list = new SimpleList(nvim) - list.actions.push({ - name: 'preview', - execute: item => { - lastItem = item - } - }) - disposables.push(manager.registerList(list)) - await manager.start(['--normal', '--auto-preview', 'simple']) - let ui = manager.session.ui - await ui.ready - await ui.selectLines(1, 2) - await helper.wait(50) - await nvim.call('coc#window#close', [ui.winid]) - await helper.wait(100) - await manager.session.resume() - await helper.wait(100) - expect(lastItem).toBeDefined() - }) - }) - - describe('jumpBack()', () => { - it('should jump back', async () => { - let win = await nvim.window - labels = ['a', 'b', 'c'] - let list = new SimpleList(nvim) - disposables.push(manager.registerList(list)) - await manager.start(['--normal', 'simple']) - let ui = manager.session.ui - await ui.ready - manager.session.jumpBack() - await helper.wait(50) - let winid = await nvim.call('win_getid') - expect(winid).toBe(win.id) - }) - }) - - describe('doNumberSelect()', () => { - async function create(len: number): Promise { - labels = [] - for (let i = 0; i < len; i++) { - let code = 'a'.charCodeAt(0) + i - labels.push(String.fromCharCode(code)) - } - let list = new SimpleList(nvim) - disposables.push(manager.registerList(list)) - await manager.start(['--normal', '--number-select', 'simple']) - let ui = manager.session.ui - await ui.ready - return manager.session - } - - it('should return false for invalid number', async () => { - let session = await create(5) - let res = await session.doNumberSelect('a') - expect(res).toBe(false) - res = await session.doNumberSelect('8') - expect(res).toBe(false) - }) - - it('should consider 0 as 10', async () => { - let session = await create(15) - let res = await session.doNumberSelect('0') - expect(res).toBe(true) - expect(lastItem).toBe('j') - }) - }) -}) - -describe('showHelp()', () => { - it('should show description and options in help', async () => { - labels = ['a', 'b', 'c'] - let list = new SimpleList(nvim) - disposables.push(manager.registerList(list)) - await manager.start(['--normal', 'simple']) - let ui = manager.session.ui - await ui.ready - await manager.session.showHelp() - let lines = await nvim.call('getline', [1, '$']) - expect(lines.indexOf('DESCRIPTION')).toBeGreaterThan(0) - expect(lines.indexOf('ARGUMENTS')).toBeGreaterThan(0) - }) -}) - -describe('chooseAction()', () => { - it('should filter actions not have shortcuts', async () => { - labels = ['a', 'b', 'c'] - let list = new SimpleList(nvim) - list.actions.push({ - name: 'a', - execute: () => { - } - }) - list.actions.push({ - name: 'b', - execute: () => { - } - }) - list.actions.push({ - name: 'ab', - execute: () => { - } - }) - disposables.push(manager.registerList(list)) - await manager.start(['--normal', 'simple']) - let ui = manager.session.ui - await ui.ready - let p = manager.session.chooseAction() - await helper.wait(100) - await nvim.input('a') - await p - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/list/sources.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/list/sources.test.ts deleted file mode 100644 index 5ba84333..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/list/sources.test.ts +++ /dev/null @@ -1,203 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { ListContext, ListItem, ListArgument } from '../../types' -import manager from '../../list/manager' -import languages from '../../languages' -import helper from '../helper' -import workspace from '../../workspace' -import { CancellationToken } from 'vscode-jsonrpc' -import { Location, Range } from 'vscode-languageserver-types' -import BasicList from '../../list/basic' - -let listItems: ListItem[] = [] -class OptionList extends BasicList { - public name = 'option' - public options: ListArgument[] = [{ - name: '-w, -word', - description: 'word' - }, { - name: '-i, -input INPUT', - hasValue: true, - description: 'input' - }] - constructor(nvim) { - super(nvim) - this.addLocationActions() - } - public loadItems(_context: ListContext, _token: CancellationToken): Promise { - return Promise.resolve(listItems) - } -} -jest.setTimeout(3000) - -let nvim: Neovim -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - manager.dispose() - await helper.shutdown() -}) - -afterEach(async () => { - manager.reset() - await helper.reset() - await helper.wait(100) -}) - -describe('BasicList', () => { - describe('parse arguments', () => { - it('should parse args #1', () => { - let list = new OptionList(nvim) - let res = list.parseArguments(['-w']) - expect(res).toEqual({ word: true }) - }) - - it('should parse args #2', () => { - let list = new OptionList(nvim) - let res = list.parseArguments(['-word']) - expect(res).toEqual({ word: true }) - }) - - it('should parse args #3', () => { - let list = new OptionList(nvim) - let res = list.parseArguments(['-input', 'foo']) - expect(res).toEqual({ input: 'foo' }) - }) - }) - - describe('preview()', () => { - it('should preview sketch buffer', async () => { - await nvim.command('new') - await nvim.setLine('foo') - let buffer = await nvim.buffer - await helper.wait(30) - let doc = workspace.getDocument(buffer.id) - expect(doc.uri).toMatch('untitled') - let list = new OptionList(nvim) - listItems.push({ - label: 'foo', - location: Location.create(doc.uri, Range.create(0, 0, 0, 0)) - }) - let disposable = manager.registerList(list) - await manager.start(['option']) - await helper.wait(100) - await manager.doAction('preview') - await helper.wait(100) - await nvim.command('wincmd p') - let win = await nvim.window - let isPreview = await win.getVar('previewwindow') - expect(isPreview).toBe(1) - let line = await nvim.line - expect(line).toBe('foo') - disposable.dispose() - }) - }) -}) - -describe('list sources', () => { - - describe('commands', () => { - it('should load commands source', async () => { - await manager.start(['commands']) - await helper.wait(100) - expect(manager.isActivated).toBe(true) - }) - - it('should do run action', async () => { - await manager.start(['commands']) - await helper.wait(100) - await manager.doAction() - }) - }) - - describe('diagnostics', () => { - it('should load diagnostics source', async () => { - await manager.start(['diagnostics']) - await manager.session?.ui.ready - await helper.wait(100) - expect(manager.isActivated).toBe(true) - }) - }) - - describe('extensions', () => { - it('should load extensions source', async () => { - await manager.start(['extensions']) - await manager.session?.ui.ready - await helper.wait(100) - expect(manager.isActivated).toBe(true) - }) - }) - - describe('folders', () => { - it('should load folders source', async () => { - await manager.start(['folders']) - await manager.session?.ui.ready - await helper.wait(100) - expect(manager.isActivated).toBe(true) - }) - }) - - describe('lists', () => { - it('should load lists source', async () => { - await manager.start(['lists']) - await manager.session?.ui.ready - await helper.wait(100) - expect(manager.isActivated).toBe(true) - }) - }) - - describe('outline', () => { - it('should load outline source', async () => { - await manager.start(['outline']) - await manager.session?.ui.ready - await helper.wait(100) - expect(manager.isActivated).toBe(true) - }) - }) - - describe('services', () => { - it('should load services source', async () => { - await manager.start(['services']) - await manager.session?.ui.ready - await helper.wait(100) - expect(manager.isActivated).toBe(true) - }) - }) - - describe('sources', () => { - it('should load sources source', async () => { - await manager.start(['sources']) - await manager.session?.ui.ready - await helper.wait(100) - expect(manager.isActivated).toBe(true) - }) - }) - - describe('symbols', () => { - it('should load symbols source', async () => { - let disposable = languages.registerWorkspaceSymbolProvider({ - provideWorkspaceSymbols: () => [] - }) - await manager.start(['symbols']) - await manager.session?.ui.ready - await helper.wait(100) - expect(manager.isActivated).toBe(true) - disposable.dispose() - }) - }) - - describe('links', () => { - it('should load links source', async () => { - let disposable = languages.registerDocumentLinkProvider([{ scheme: 'file' }, { scheme: 'untitled' }], { - provideDocumentLinks: () => [] - }) - await manager.start(['links']) - await manager.session?.ui.ready - await helper.wait(100) - expect(manager.isActivated).toBe(true) - disposable.dispose() - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/list/ui.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/list/ui.test.ts deleted file mode 100644 index 345f028f..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/list/ui.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import BasicList from '../../list/basic' -import events from '../../events' -import manager from '../../list/manager' -import { ListItem } from '../../types' -import { disposeAll } from '../../util' -import helper from '../helper' - -let labels: string[] = [] -let lastItem: string - -class SimpleList extends BasicList { - public name = 'simple' - constructor(nvim: Neovim) { - super(nvim) - this.addAction('open', item => { - lastItem = item.label - }) - } - public loadItems(): Promise { - return Promise.resolve(labels.map(s => { - return { label: s, ansiHighlights: [{ span: [0, 1], hlGroup: 'Search' }] } as ListItem - })) - } -} - -let nvim: Neovim -let disposables: Disposable[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - disposeAll(disposables) - manager.reset() - await helper.reset() -}) - -describe('list ui', () => { - describe('selectLines()', () => { - it('should select lines', async () => { - labels = ['foo', 'bar'] - disposables.push(manager.registerList(new SimpleList(nvim))) - await manager.start(['simple']) - let ui = manager.session.ui - await ui.ready - await ui.selectLines(3, 1) - let buf = await nvim.buffer - let res = await buf.getSigns({ group: 'coc-list' }) - expect(res.length).toBe(2) - }) - }) - - describe('resume()', () => { - it('should resume with selected lines', async () => { - labels = ['foo', 'bar'] - disposables.push(manager.registerList(new SimpleList(nvim))) - await manager.start(['simple']) - let ui = manager.session.ui - await ui.ready - await ui.selectLines(1, 2) - await nvim.call('coc#window#close', [ui.winid]) - await helper.wait(100) - await manager.session.resume() - await helper.wait(100) - let buf = await nvim.buffer - let res = await buf.getSigns({ group: 'coc-list' }) - expect(res.length).toBe(2) - }) - }) - - describe('events', () => { - async function mockMouse(winid: number, lnum: number): Promise { - await nvim.command(`let v:mouse_winid = ${winid}`) - await nvim.command(`let v:mouse_lnum = ${lnum}`) - await nvim.command('let v:mouse_col = 1') - } - - it('should fire action on double click', async () => { - labels = ['foo', 'bar'] - disposables.push(manager.registerList(new SimpleList(nvim))) - await manager.start(['simple']) - let ui = manager.session.ui - await ui.ready - await mockMouse(ui.winid, 1) - await manager.session.onMouseEvent('<2-LeftMouse>') - await helper.wait(100) - expect(lastItem).toBe('foo') - }) - - it('should select clicked line', async () => { - labels = ['foo', 'bar'] - disposables.push(manager.registerList(new SimpleList(nvim))) - await manager.start(['simple']) - let ui = manager.session.ui - await ui.ready - await mockMouse(ui.winid, 2) - await ui.onMouse('mouseDown') - await helper.wait(50) - await mockMouse(ui.winid, 2) - await ui.onMouse('mouseUp') - await helper.wait(50) - let item = await ui.item - expect(item.label).toBe('bar') - }) - - it('should jump to original window on click', async () => { - labels = ['foo', 'bar'] - let win = await nvim.window - disposables.push(manager.registerList(new SimpleList(nvim))) - await manager.start(['simple']) - let ui = manager.session.ui - await ui.ready - await mockMouse(win.id, 1) - await ui.onMouse('mouseUp') - await helper.wait(50) - let curr = await nvim.window - expect(curr.id).toBe(win.id) - }) - - it('should highlights items on CursorMoved', async () => { - labels = (new Array(400)).fill('a') - disposables.push(manager.registerList(new SimpleList(nvim))) - await manager.start(['simple', '--normal']) - let ui = manager.session.ui - await ui.ready - await nvim.call('cursor', [350, 1]) - await events.fire('CursorMoved', [ui.bufnr, [350, 1]]) - await helper.wait(300) - let res = await nvim.call('getmatches') - expect(res.length).toBeGreaterThan(300) - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/list/worker.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/list/worker.test.ts deleted file mode 100644 index bbcf9a75..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/list/worker.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import manager from '../../list/manager' -import { parseInput } from '../../list/worker' -import helper from '../helper' -import { ListContext, ListTask, ListItem } from '../../types' -import { CancellationToken, Disposable } from 'vscode-languageserver-protocol' -import { EventEmitter } from 'events' -import colors from 'colors/safe' -import BasicList from '../../list/basic' -import { disposeAll } from '../../util' - -let items: ListItem[] = [] - -class DataList extends BasicList { - public name = 'data' - public loadItems(): Promise { - return Promise.resolve(items) - } -} - -class IntervalTaskList extends BasicList { - public name = 'task' - public timeout = 3000 - public loadItems(_context: ListContext, token: CancellationToken): Promise { - let emitter: any = new EventEmitter() - let i = 0 - let interval = setInterval(() => { - emitter.emit('data', { label: i.toFixed() }) - i++ - }, 50) - emitter.dispose = () => { - clearInterval(interval) - emitter.emit('end') - } - token.onCancellationRequested(() => { - emitter.dispose() - }) - return emitter - } -} - -class DelayTask extends BasicList { - public name = 'delay' - public interactive = true - public loadItems(_context: ListContext, token: CancellationToken): Promise { - let emitter: any = new EventEmitter() - let disposed = false - setTimeout(() => { - if (disposed) return - emitter.emit('data', { label: 'ahead' }) - }, 100) - setTimeout(() => { - if (disposed) return - emitter.emit('data', { label: 'abort' }) - }, 200) - emitter.dispose = () => { - disposed = true - emitter.emit('end') - } - token.onCancellationRequested(() => { - emitter.dispose() - }) - return emitter - } -} - -class InteractiveList extends BasicList { - public name = 'test' - public interactive = true - public loadItems(context: ListContext, _token: CancellationToken): Promise { - return Promise.resolve([{ - label: colors.magenta(context.input || '') - }]) - } -} - -class ErrorList extends BasicList { - public name = 'error' - public interactive = true - public loadItems(_context: ListContext, _token: CancellationToken): Promise { - return Promise.reject(new Error('test error')) - } -} - -class ErrorTaskList extends BasicList { - public name = 'task' - public loadItems(_context: ListContext, _token: CancellationToken): Promise { - let emitter: any = new EventEmitter() - let timeout = setTimeout(() => { - emitter.emit('error', new Error('task error')) - }, 100) - emitter.dispose = () => { - clearTimeout(timeout) - } - return emitter - } -} - -let nvim: Neovim -let disposables: Disposable[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - disposeAll(disposables) - manager.reset() - await helper.reset() -}) - -describe('parseInput', () => { - it('should parse input with space', async () => { - let res = parseInput('a b') - expect(res).toEqual(['a', 'b']) - }) - - it('should parse input with escaped space', async () => { - let res = parseInput('a\\ b') - expect(res).toEqual(['a b']) - }) -}) - -describe('list worker', () => { - - it('should work with long running task', async () => { - disposables.push(manager.registerList(new IntervalTaskList(nvim))) - await manager.start(['task']) - await helper.wait(300) - let len = manager.session?.length - expect(len > 2).toBe(true) - await manager.cancel() - }) - - it('should sort by sortText', async () => { - items = [{ - label: 'abc', - sortText: 'b' - }, { - label: 'ade', - sortText: 'a' - }] - disposables.push(manager.registerList(new DataList(nvim))) - await manager.start(['data']) - await helper.wait(100) - await nvim.input('a') - await helper.wait(100) - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual(['ade', 'abc']) - await manager.cancel() - }) - - it('should cancel task by use CancellationToken', async () => { - disposables.push(manager.registerList(new IntervalTaskList(nvim))) - await manager.start(['task']) - expect(manager.session?.worker.isLoading).toBe(true) - await helper.wait(100) - manager.session?.stop() - expect(manager.session?.worker.isLoading).toBe(false) - }) - - it('should render slow interactive list', async () => { - disposables.push(manager.registerList(new DelayTask(nvim))) - await manager.start(['delay']) - await nvim.input('a') - await helper.wait(600) - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual(['ahead', 'abort']) - }) - - it('should work with interactive list', async () => { - disposables.push(manager.registerList(new InteractiveList(nvim))) - await manager.start(['-I', 'test']) - await manager.session?.ui.ready - expect(manager.isActivated).toBe(true) - await nvim.eval('feedkeys("f", "in")') - await helper.wait(100) - await nvim.eval('feedkeys("a", "in")') - await helper.wait(100) - await nvim.eval('feedkeys("x", "in")') - await helper.wait(300) - let item = await manager.session?.ui.item - expect(item.label).toBe('fax') - }) - - it('should not activate on load error', async () => { - disposables.push(manager.registerList(new ErrorList(nvim))) - await manager.start(['test']) - expect(manager.isActivated).toBe(false) - }) - - it('should deactivate on task error', async () => { - disposables.push(manager.registerList(new ErrorTaskList(nvim))) - await manager.start(['task']) - await helper.wait(500) - expect(manager.isActivated).toBe(false) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/markdown/index.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/markdown/index.test.ts deleted file mode 100644 index 52653e28..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/markdown/index.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { getHighlightItems, parseMarkdown, parseDocuments } from '../../markdown/index' - -describe('getHighlightItems', () => { - it('should get highlights in single line', async () => { - let res = getHighlightItems('this line has highlights', 0, [10, 15]) - expect(res).toEqual([{ - colStart: 10, - colEnd: 15, - lnum: 0, - hlGroup: 'CocUnderline' - }]) - }) - - it('should get highlights when active end extended', async () => { - let res = getHighlightItems('this line', 0, [5, 30]) - expect(res).toEqual([{ - colStart: 5, - colEnd: 9, - lnum: 0, - hlGroup: 'CocUnderline' - }]) - }) - - it('should get highlights across line', async () => { - let res = getHighlightItems('this line\nhas highlights', 0, [5, 15]) - expect(res).toEqual([{ - colStart: 5, colEnd: 9, lnum: 0, hlGroup: 'CocUnderline' - }, { - colStart: 0, colEnd: 5, lnum: 1, hlGroup: 'CocUnderline' - }]) - }) -}) - -describe('parseMarkdown', () => { - it('should parse code blocks', async () => { - let content = ` -\`\`\`js -var global = globalThis -\`\`\` -\`\`\`ts -let str:string -\`\`\` -` - let res = parseMarkdown(content, {}) - expect(res.lines).toEqual([ - 'var global = globalThis', - '', - 'let str:string' - ]) - expect(res.codes).toEqual([ - { filetype: 'javascript', startLine: 0, endLine: 1 }, - { filetype: 'typescript', startLine: 2, endLine: 3 } - ]) - }) - - it('should parse html code block', async () => { - let content = ` -example: -\`\`\`html -
    code
    -\`\`\` - ` - let res = parseMarkdown(content, {}) - expect(res.lines).toEqual(['example:', '', '
    code
    ']) - expect(res.codes).toEqual([{ filetype: 'html', startLine: 2, endLine: 3 }]) - }) - - it('should compose empty lines', async () => { - let content = 'foo\n\n\nbar\n\n\n' - let res = parseMarkdown(content, {}) - expect(res.lines).toEqual(['foo', '', 'bar']) - }) - - it('should parse ansi highlights', async () => { - let content = '__foo__\n[link](link)' - let res = parseMarkdown(content, {}) - expect(res.lines).toEqual(['foo', 'link']) - expect(res.highlights).toEqual([ - { hlGroup: 'CocBold', lnum: 0, colStart: 0, colEnd: 3 }, - { hlGroup: 'CocUnderline', lnum: 1, colStart: 0, colEnd: 4 } - ]) - }) - - it('should exclude images by option', async () => { - let content = 'head\n![img](img)\ncontent ![img](img) ![img](img)' - let res = parseMarkdown(content, { excludeImages: true }) - expect(res.lines).toEqual(['head', '', 'content']) - }) -}) - -describe('parseDocuments', () => { - it('should parse documents with diagnostic filetypes', async () => { - let docs = [{ - filetype: 'Error', - content: 'Error text' - }, { - filetype: 'Warning', - content: 'Warning text' - }] - let res = parseDocuments(docs) - expect(res.lines).toEqual([ - 'Error text', - 'โ”€', - 'Warning text' - ]) - expect(res.codes).toEqual([ - { hlGroup: 'CocErrorFloat', startLine: 0, endLine: 1 }, - { hlGroup: 'CocWarningFloat', startLine: 2, endLine: 3 } - ]) - }) - - it('should parse markdown document with filetype document', async () => { - let docs = [{ - filetype: 'typescript', - content: 'const workspace' - }, { - filetype: 'markdown', - content: '**header**' - }] - let res = parseDocuments(docs) - expect(res.lines).toEqual([ - 'const workspace', - 'โ”€', - 'header' - ]) - expect(res.highlights).toEqual([{ - hlGroup: 'CocBold', - lnum: 2, - colStart: 0, - colEnd: 6 - }]) - expect(res.codes).toEqual([ - { filetype: 'typescript', startLine: 0, endLine: 1 } - ]) - }) - - it('should parse documents with active highlights', async () => { - let docs = [{ - filetype: 'javascript', - content: 'func(foo, bar)', - active: [5, 8] - }, { - filetype: 'javascript', - content: 'func()', - active: [15, 20] - }] - let res = parseDocuments(docs as any) - expect(res.highlights).toEqual([{ colStart: 5, colEnd: 8, lnum: 0, hlGroup: 'CocUnderline' } - ]) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/markdown/renderer.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/markdown/renderer.test.ts deleted file mode 100644 index 95dbbffd..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/markdown/renderer.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import marked from 'marked' -import Renderer from '../../markdown/renderer' -import * as styles from '../../markdown/styles' -import { parseAnsiHighlights, AnsiResult } from '../../util/ansiparse' - -marked.setOptions({ - renderer: new Renderer() -}) - -function parse(text: string): AnsiResult { - let m = marked(text) - let res = parseAnsiHighlights(m.split(/\n/)[0], true) - return res -} - -describe('styles', () => { - it('should add styles', async () => { - let keys = ['gray', 'magenta', 'bold', 'underline', 'italic', 'strikethrough', 'yellow', 'green', 'blue'] - for (let key of keys) { - let res = styles[key]('text') - expect(res).toContain('text') - } - }) -}) - -describe('Renderer of marked', () => { - it('should create bold highlights', async () => { - let res = parse('**note**.') - expect(res.highlights[0]).toEqual({ - span: [0, 4], - hlGroup: 'CocBold' - }) - }) - - it('should create italic highlights', async () => { - let res = parse('_note_.') - expect(res.highlights[0]).toEqual({ - span: [0, 4], - hlGroup: 'CocItalic' - }) - }) - - it('should create underline highlights for link', async () => { - let res = parse('[baidu](https://baidu.com)') - expect(res.highlights[0]).toEqual({ - span: [0, 5], - hlGroup: 'CocMarkdownLink' - }) - res = parse('https://baidu.com') - expect(res.highlights[0]).toEqual({ - span: [0, 17], - hlGroup: 'CocUnderline' - }) - }) - - it('should parse link', async () => { - // let res = parse('https://doc.rust-lang.org/nightly/core/iter/traits/iterator/Iterator.t.html#map.v') - // console.log(JSON.stringify(res, null, 2)) - let link = 'https://doc.rust-lang.org/nightly/core/iter/traits/iterator/Iterator.t.html#map.v' - let parsed = marked(link) - let res = parseAnsiHighlights(parsed.split(/\n/)[0], true) - expect(res.line).toEqual(link) - expect(res.highlights.length).toBeGreaterThan(0) - expect(res.highlights[0].hlGroup).toBe('CocUnderline') - }) - - it('should create highlight for code span', async () => { - let res = parse('`let foo = "bar"`') - expect(res.highlights[0]).toEqual({ - span: [0, 15], - hlGroup: 'CocMarkdownCode' - }) - }) - - it('should create header highlights', async () => { - let res = parse('# header') - expect(res.highlights[0]).toEqual({ - span: [0, 8], - hlGroup: 'CocMarkdownHeader' - }) - res = parse('## header') - expect(res.highlights[0]).toEqual({ - span: [0, 9], - hlGroup: 'CocMarkdownHeader' - }) - res = parse('### header') - expect(res.highlights[0]).toEqual({ - span: [0, 10], - hlGroup: 'CocMarkdownHeader' - }) - }) - - it('should indent blockquote', async () => { - let res = parse('> header') - expect(res.line).toBe(' header') - }) - - it('should preserve code block', async () => { - let text = '``` js\nconsole.log("foo")\n```' - let m = marked(text) - expect(m.split('\n')).toEqual([ - '``` js', - 'console.log("foo")', - '```', - '' - ]) - }) - - it('should renderer table', async () => { - let text = ` -| Syntax | Description | -| ----------- | ----------- | -| Header | Title | -| Paragraph | Text | -` - let res = marked(text) - expect(res).toContain('Syntax') - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/memos.json b/vim-config/plugins/coc.nvim/src/__tests__/memos.json deleted file mode 100644 index 9e26dfee..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/memos.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/array.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/array.test.ts deleted file mode 100644 index ad3f0c32..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/array.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import * as assert from 'assert' -import * as arrays from '../../util/array' - -describe('Arrays', () => { - - test('distinct', () => { - function compare(a: string): string { - return a - } - - assert.deepStrictEqual(arrays.distinct(['32', '4', '5'], compare), ['32', '4', '5']) - assert.deepStrictEqual(arrays.distinct(['32', '4', '5', '4'], compare), ['32', '4', '5']) - assert.deepStrictEqual(arrays.distinct(['32', 'constructor', '5', '1'], compare), ['32', 'constructor', '5', '1']) - assert.deepStrictEqual(arrays.distinct(['32', 'constructor', 'proto', 'proto', 'constructor'], compare), ['32', 'constructor', 'proto']) - assert.deepStrictEqual(arrays.distinct(['32', '4', '5', '32', '4', '5', '32', '4', '5', '5'], compare), ['32', '4', '5']) - }) - - test('tail', () => { - assert.strictEqual(arrays.tail([1, 2, 3]), 3) - }) - - test('lastIndex', () => { - let res = arrays.lastIndex([1, 2, 3], x => x < 3) - assert.strictEqual(res, 1) - }) - - test('flatMap', () => { - let objs: { [key: string]: number[] }[] = [{ x: [1, 2] }, { y: [3, 4] }, { z: [5, 6] }] - function values(item: { [key: string]: number[] }): number[] { - return Object.keys(item).reduce((p, c) => p.concat(item[c]), []) - } - let res = arrays.flatMap(objs, values) - assert.deepStrictEqual(res, [1, 2, 3, 4, 5, 6]) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/attach.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/attach.test.ts deleted file mode 100644 index 55f0d544..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/attach.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import events from '../../events' -import helper from '../helper' - -function wait(ms: number): Promise { - return new Promise(resolve => { - setTimeout(() => { - resolve() - }, ms) - }) -} -let nvim: Neovim -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('attach', () => { - - it('should listen CocInstalled', async () => { - nvim.emit('notification', 'VimEnter') - await helper.wait(100) - }) - - it('should not throw on event handler error', async () => { - events.on('CursorHold', async () => { - throw new Error('error') - }) - let fn = jest.fn() - nvim.emit('request', 'CocAutocmd', ['CursorHold'], { - send: fn - }) - await wait(100) - expect(fn).toBeCalled() - }) - - it('should not throw when plugin method not found', async () => { - let fn = jest.fn() - nvim.emit('request', 'NotExists', [], { - send: fn - }) - await wait(100) - expect(fn).toBeCalled() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/chars.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/chars.test.ts deleted file mode 100644 index df716001..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/chars.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { Chars } from '../../model/chars' - -describe('chars keyword option', () => { - it('should match @', () => { - let chars = new Chars('@') - expect(chars.isKeywordChar('a')).toBe(true) - expect(chars.isKeywordChar('z')).toBe(true) - expect(chars.isKeywordChar('A')).toBe(true) - expect(chars.isKeywordChar('Z')).toBe(true) - }) - - it('should match letter range', () => { - let chars = new Chars('a-z') - expect(chars.isKeywordChar('a')).toBe(true) - expect(chars.isKeywordChar('A')).toBe(false) - }) - - it('should match code range', () => { - let chars = new Chars('48-57') - expect(chars.isKeywordChar('a')).toBe(false) - expect(chars.isKeywordChar('0')).toBe(true) - expect(chars.isKeywordChar('9')).toBe(true) - }) - - it('should match @-@', () => { - let chars = new Chars('@-@') - expect(chars.isKeywordChar('@')).toBe(true) - }) - - it('should match single code', () => { - let chars = new Chars('58') - expect(chars.isKeywordChar(':')).toBe(true) - }) - - it('should match single character', () => { - let chars = new Chars('_') - expect(chars.isKeywordChar('_')).toBe(true) - }) -}) - -describe('chars addKeyword', () => { - it('should add keyword', () => { - let chars = new Chars('_') - chars.addKeyword(':') - expect(chars.isKeywordChar(':')).toBe(true) - }) -}) - -describe('chars change keyword', () => { - it('should change keyword', () => { - let chars = new Chars('_') - chars.setKeywordOption(':') - expect(chars.isKeywordChar(':')).toBe(true) - expect(chars.isKeywordChar('_')).toBe(false) - }) -}) - -describe('chars match keywords', () => { - it('should match keywords', () => { - let chars = new Chars('@') - let res = chars.matchKeywords('foo bar') - expect(res).toEqual(['foo', 'bar']) - }) - - it('should consider unicode character as word', () => { - let chars = new Chars('@') - let res = chars.matchKeywords('blackะบะพั„ะต') - expect(res).toEqual(['blackะบะพั„ะต']) - }) -}) - -describe('chars isKeyword', () => { - it('should check isKeyword', () => { - let chars = new Chars('@') - expect(chars.isKeyword('foo')).toBe(true) - expect(chars.isKeyword('f@')).toBe(false) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/client.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/client.test.ts deleted file mode 100644 index 887f4f88..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/client.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import helper from '../helper' - -let nvim: Neovim - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('node client pauseNotification', () => { - it('should work with notify & request', async () => { - nvim.pauseNotification() - nvim.call('setline', [1, 'foo'], true) - nvim.call('append', [1, ['bar']], true) - await nvim.resumeNotification(false, true) - await helper.wait(500) - let buffer = await nvim.buffer - let lines = await buffer.lines - expect(lines).toEqual(['foo', 'bar']) - nvim.pauseNotification() - nvim.call('eval', ['&buftype'], true) - nvim.call('bufnr', ['%'], true) - let res = await nvim.resumeNotification() - expect(res).toEqual([['', buffer.id], null]) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/completion.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/completion.test.ts deleted file mode 100644 index 5c307795..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/completion.test.ts +++ /dev/null @@ -1,756 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-jsonrpc' -import { CompletionItem, InsertTextFormat, Position, Range, TextEdit, CompletionList } from 'vscode-languageserver-types' -import completion from '../../completion' -import languages from '../../languages' -import { CompletionItemProvider } from '../../provider' -import snippetManager from '../../snippets/manager' -import sources from '../../sources' -import { CompleteOption, CompleteResult, ISource, SourceType } from '../../types' -import { disposeAll } from '../../util' -import workspace from '../../workspace' -import helper from '../helper' - -let nvim: Neovim -let disposables: Disposable[] = [] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -beforeEach(async () => { - disposables = [] - await helper.createDocument() - await nvim.call('feedkeys', [String.fromCharCode(27), 'in']) -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - disposeAll(disposables) - await helper.reset() -}) - -describe('completion events', () => { - - it('should load preferences', () => { - let minTriggerInputLength = completion.config.minTriggerInputLength - expect(minTriggerInputLength).toBe(1) - }) - - it('should reload preferences onChange', () => { - let { configurations } = workspace - configurations.updateUserConfig({ 'suggest.maxCompleteItemCount': 30 }) - let snippetIndicator = completion.config.maxItemCount - expect(snippetIndicator).toBe(30) - }) -}) - -describe('completion start', () => { - - it('should deactivate on doComplete error', async () => { - let fn = (completion as any)._doComplete - ; (completion as any)._doComplete = async () => { - throw new Error('fake') - } - let option: CompleteOption = await nvim.call('coc#util#get_complete_option') - await completion.startCompletion(option) - ; (completion as any)._doComplete = fn - expect(completion.isActivated).toBe(false) - }) - - it('should start completion', async () => { - await nvim.setLine('foo football') - await nvim.input('a') - await nvim.call('cursor', [1, 2]) - let option: CompleteOption = await nvim.call('coc#util#get_complete_option') - await completion.startCompletion(option) - expect(completion.isActivated).toBe(true) - }) - - it('should show slow source', async () => { - let source: ISource = { - priority: 0, - enable: true, - name: 'slow', - sourceType: SourceType.Service, - triggerCharacters: ['.'], - doComplete: (_opt: CompleteOption): Promise => new Promise(resolve => { - setTimeout(() => { - resolve({ items: [{ word: 'foo' }, { word: 'bar' }] }) - }, 600) - }) - } - disposables.push(sources.addSource(source)) - await helper.edit() - await nvim.input('i.') - await helper.waitPopup() - expect(completion.isActivated).toBe(true) - let items = await helper.items() - expect(items.length).toBe(2) - }) -}) - -describe('completion resumeCompletion', () => { - - it('should stop if no filtered items', async () => { - await nvim.setLine('foo ') - await helper.wait(50) - await nvim.input('Af') - await helper.waitPopup() - expect(completion.isActivated).toBe(true) - await nvim.input('d') - await helper.wait(60) - expect(completion.isActivated).toBe(false) - }) - - it('should deactivate without filtered items', async () => { - await nvim.setLine('foo fbi ') - await nvim.input('Af') - await helper.waitPopup() - await nvim.input('c') - await helper.wait(100) - let items = await helper.items() - expect(items.length).toBe(0) - expect(completion.isActivated).toBe(false) - }) - - it('should deactivate when insert space', async () => { - let source: ISource = { - priority: 0, - enable: true, - name: 'empty', - sourceType: SourceType.Service, - triggerCharacters: ['.'], - doComplete: (_opt: CompleteOption): Promise => new Promise(resolve => { - resolve({ items: [{ word: 'foo bar' }] }) - }) - } - sources.addSource(source) - await helper.edit() - await nvim.input('i.') - await helper.waitPopup() - expect(completion.isActivated).toBe(true) - sources.removeSource(source) - let items = await helper.items() - expect(items[0].word).toBe('foo bar') - await nvim.input(' ') - await helper.wait(60) - expect(completion.isActivated).toBe(false) - }) - - it('should use resume input to filter', async () => { - let source: ISource = { - priority: 0, - enable: true, - name: 'source', - sourceType: SourceType.Service, - triggerCharacters: ['.'], - doComplete: (): Promise => new Promise(resolve => { - setTimeout(() => { - resolve({ items: [{ word: 'foo' }, { word: 'bar' }] }) - }, 60) - }) - } - sources.addSource(source) - await helper.edit() - await nvim.input('i.') - await helper.wait(20) - await nvim.input('f') - await helper.waitPopup() - expect(completion.isActivated).toBe(true) - let items = await helper.items() - expect(items.length).toBe(1) - expect(items[0].word).toBe('foo') - sources.removeSource(source) - }) - - it('should filter slow source', async () => { - let source: ISource = { - priority: 0, - enable: true, - name: 'slow', - sourceType: SourceType.Service, - triggerCharacters: ['.'], - doComplete: (): Promise => new Promise(resolve => { - setTimeout(() => { - resolve({ items: [{ word: 'foo' }, { word: 'bar' }] }) - }, 600) - }) - } - disposables.push(sources.addSource(source)) - await helper.edit() - await nvim.input('i.') - await helper.wait(60) - await nvim.input('f') - await helper.waitPopup() - await nvim.input('o') - await helper.wait(100) - expect(completion.isActivated).toBe(true) - let items = await helper.items() - expect(items.length).toBe(1) - expect(items[0].word).toBe('foo') - }) - - it('should complete inComplete source', async () => { - let source: ISource = { - priority: 0, - enable: true, - name: 'inComplete', - sourceType: SourceType.Service, - triggerCharacters: ['.'], - doComplete: async (opt: CompleteOption): Promise => { - await helper.wait(30) - if (opt.input.length <= 1) { - return { isIncomplete: true, items: [{ word: 'foo' }, { word: opt.input }] } - } - return { isIncomplete: false, items: [{ word: 'foo' }, { word: opt.input }] } - } - } - disposables.push(sources.addSource(source)) - await helper.edit() - await nvim.input('i.') - await helper.waitPopup() - expect(completion.isActivated).toBe(true) - await nvim.input('a') - await helper.wait(30) - await nvim.input('b') - await helper.wait(100) - }) - - it('should not complete inComplete source when isIncomplete is false', async () => { - await helper.createDocument() - let lastOption: CompleteOption - let source: ISource = { - priority: 0, - enable: true, - name: 'inComplete', - sourceType: SourceType.Service, - triggerCharacters: ['.'], - doComplete: async (opt: CompleteOption): Promise => { - lastOption = opt - await helper.wait(30) - if (opt.input.length <= 1) { - return { isIncomplete: true, items: [{ word: 'foobar' }] } - } - return { isIncomplete: false, items: [{ word: 'foobar' }] } - } - } - disposables.push(sources.addSource(source)) - await helper.edit() - await nvim.input('i.') - await helper.waitPopup() - expect(completion.isActivated).toBe(true) - await nvim.input('fo') - await helper.wait(100) - await nvim.input('b') - await helper.wait(200) - expect(completion.isActivated).toBe(true) - }) -}) - -describe('completion InsertEnter', () => { - it('should trigger completion if triggerAfterInsertEnter is true', async () => { - await helper.createDocument() - await nvim.setLine('foo fo') - let config = workspace.getConfiguration('suggest') - config.update('triggerAfterInsertEnter', true) - await helper.wait(100) - let triggerAfterInsertEnter = completion.config.triggerAfterInsertEnter - expect(triggerAfterInsertEnter).toBe(true) - await nvim.input('A') - await helper.waitPopup() - expect(completion.isActivated).toBe(true) - config.update('triggerAfterInsertEnter', undefined) - }) - - it('should not trigger when input length too small', async () => { - let config = workspace.getConfiguration('suggest') - config.update('triggerAfterInsertEnter', true) - await helper.wait(100) - let triggerAfterInsertEnter = completion.config.triggerAfterInsertEnter - expect(triggerAfterInsertEnter).toBe(true) - await nvim.setLine('foo ') - await nvim.input('A') - await helper.wait(100) - expect(completion.isActivated).toBe(false) - config.update('triggerAfterInsertEnter', undefined) - }) -}) - -describe('completion TextChangedP', () => { - it('should stop when input length below option input length', async () => { - await helper.edit() - await nvim.setLine('foo fbi ') - await nvim.input('Af') - await helper.waitPopup() - await nvim.input('') - await helper.wait(100) - expect(completion.isActivated).toBe(false) - }) - - it('should fix cursor position with plain text on additionalTextEdits', async () => { - let provider: CompletionItemProvider = { - provideCompletionItems: async (): Promise => [{ - label: 'foo', - filterText: 'foo', - additionalTextEdits: [TextEdit.insert(Position.create(0, 0), 'a\nbar')] - }] - } - disposables.push(languages.registerCompletionItemProvider('edits', 'edit', null, provider)) - await nvim.input('if') - await helper.waitPopup() - await helper.selectCompleteItem(0) - await helper.wait(200) - let line = await nvim.line - expect(line).toBe('barfoo') - let [, lnum, col] = await nvim.call('getcurpos') - expect(lnum).toBe(2) - expect(col).toBe(7) - }) - - it('should filter in complete request', async () => { - let provider: CompletionItemProvider = { - provideCompletionItems: async (doc, pos, token, context): Promise => { - let option = (context as any).option - if (context.triggerCharacter == '.') { - return { - isIncomplete: true, - items: [ - { - label: 'foo' - }, { - label: 'bar' - } - ] - } - } - if (option.input == 'f') { - await helper.wait(100) - if (token.isCancellationRequested) return - return { - isIncomplete: true, - items: [ - { - label: 'foo' - } - ] - } - } - if (option.input == 'fo') { - await helper.wait(100) - if (token.isCancellationRequested) return - return { - isIncomplete: false, - items: [ - { - label: 'foo' - } - ] - } - } - } - } - disposables.push(languages.registerCompletionItemProvider('edits', 'edit', null, provider, ['.'])) - await nvim.input('i.') - await helper.waitPopup() - await nvim.input('f') - await helper.wait(60) - await nvim.input('o') - await helper.wait(300) - let res = await helper.getItems() - expect(res.length).toBe(1) - }) - - it('should provide word when textEdit after startcol', async () => { - // some LS would send textEdit after first character, - // need fix the word from newText - let provider: CompletionItemProvider = { - provideCompletionItems: async (_, position): Promise => { - if (position.line != 0) return null - return [{ - label: 'bar', - filterText: 'ar', - textEdit: { - range: Range.create(0, 1, 0, 1), - newText: 'ar' - } - }] - } - } - disposables.push(languages.registerCompletionItemProvider('edits', 'edit', null, provider)) - await nvim.input('ib') - await helper.waitPopup() - let context = await nvim.getVar('coc#_context') as any - expect(context.start).toBe(1) - expect(context.candidates[0].word).toBe('ar') - }) - - it('should adjust completion position by textEdit start position', async () => { - let provider: CompletionItemProvider = { - provideCompletionItems: async (_document, _position, _token, context): Promise => { - if (!context.triggerCharacter) return - return [{ - label: 'foo', - textEdit: { - range: Range.create(0, 0, 0, 1), - newText: '?foo' - } - }] - } - } - disposables.push(languages.registerCompletionItemProvider('fix', 'f', null, provider, ['?'])) - await nvim.input('i?') - await helper.waitPopup() - await nvim.eval('feedkeys("\\", "in")') - await helper.wait(200) - let line = await nvim.line - expect(line).toBe('?foo') - }) - - it('should fix cursor position with snippet on additionalTextEdits', async () => { - await helper.createDocument() - let provider: CompletionItemProvider = { - provideCompletionItems: async (): Promise => [{ - label: 'if', - insertTextFormat: InsertTextFormat.Snippet, - textEdit: { range: Range.create(0, 0, 0, 2), newText: 'if($1)' }, - additionalTextEdits: [TextEdit.insert(Position.create(0, 0), 'bar ')], - preselect: true - }] - } - disposables.push(languages.registerCompletionItemProvider('edits', 'edit', null, provider)) - await nvim.input('ii') - await helper.waitPopup() - let res = await helper.getItems() - let idx = res.findIndex(o => o.menu == '[edit]') - await helper.selectCompleteItem(idx) - await helper.wait(800) - let line = await nvim.line - expect(line).toBe('bar if()') - let [, lnum, col] = await nvim.call('getcurpos') - expect(lnum).toBe(1) - expect(col).toBe(8) - }) - - it('should fix cursor position with plain text snippet on additionalTextEdits', async () => { - let provider: CompletionItemProvider = { - provideCompletionItems: async (): Promise => [{ - label: 'if', - insertTextFormat: InsertTextFormat.Snippet, - textEdit: { range: Range.create(0, 0, 0, 2), newText: 'do$0' }, - additionalTextEdits: [TextEdit.insert(Position.create(0, 0), 'bar ')], - preselect: true - }] - } - disposables.push(languages.registerCompletionItemProvider('edits', 'edit', null, provider)) - await nvim.input('iif') - await helper.waitPopup() - await helper.selectCompleteItem(0) - await helper.wait(200) - let line = await nvim.line - let [, lnum, col] = await nvim.call('getcurpos') - expect(line).toBe('bar do') - expect(lnum).toBe(1) - expect(col).toBe(7) - }) - - it('should fix cursor position with nested snippet on additionalTextEdits', async () => { - await helper.createDocument() - let res = await snippetManager.insertSnippet('func($1)$0') - expect(res).toBe(true) - let provider: CompletionItemProvider = { - provideCompletionItems: async (): Promise => [{ - label: 'if', - insertTextFormat: InsertTextFormat.Snippet, - insertText: 'do$0', - additionalTextEdits: [TextEdit.insert(Position.create(0, 0), 'bar ')], - preselect: true - }] - } - disposables.push(languages.registerCompletionItemProvider('edits', 'edit', null, provider)) - await nvim.input('if') - await helper.waitPopup() - await helper.selectCompleteItem(0) - await helper.wait(200) - let line = await nvim.line - let [, lnum, col] = await nvim.call('getcurpos') - expect(line).toBe('bar func(do)') - expect(lnum).toBe(1) - expect(col).toBe(12) - }) - - it('should fix cursor position and keep placeholder with snippet on additionalTextEdits', async () => { - let doc = await helper.createDocument() - let text = 'foo0bar1' - await nvim.setLine(text) - let provider: CompletionItemProvider = { - provideCompletionItems: async (): Promise => [{ - label: 'var', - insertTextFormat: InsertTextFormat.Snippet, - textEdit: { range: Range.create(0, text.length + 1, 0, text.length + 1), newText: '${1:foo} = foo0bar1' }, - additionalTextEdits: [TextEdit.del(Range.create(0, 0, 0, text.length + 1))], - preselect: true - }] - } - disposables.push(languages.registerCompletionItemProvider('edits', 'edit', null, provider, ['.'])) - await nvim.input('A.') - await helper.waitPopup() - let res = await helper.getItems() - let idx = res.findIndex(o => o.menu == '[edit]') - await helper.selectCompleteItem(idx) - await helper.wait(800) - let line = await nvim.line - expect(line).toBe('foo = foo0bar1') - expect(snippetManager.isActived(doc.bufnr)).toBe(true) - let [, lnum, col] = await nvim.call('getcurpos') - expect(lnum).toBe(1) - expect(col).toBe(3) - }) - - it('should fix input for snippet item', async () => { - let provider: CompletionItemProvider = { - provideCompletionItems: async (): Promise => [{ - label: 'foo', - filterText: 'foo', - insertText: '${1:foo}($2)', - insertTextFormat: InsertTextFormat.Snippet, - }] - } - disposables.push(languages.registerCompletionItemProvider('snippets-test', 'st', null, provider)) - await nvim.input('if') - await helper.waitPopup() - await nvim.input('') - await helper.wait(100) - let line = await nvim.line - expect(line).toBe('foo') - }) - - it('should filter on none keyword input', async () => { - let source: ISource = { - priority: 99, - enable: true, - name: 'temp', - sourceType: SourceType.Service, - doComplete: (_opt: CompleteOption): Promise => Promise.resolve({ items: [{ word: 'foo#abc' }] }), - } - disposables.push(sources.addSource(source)) - await nvim.input('if') - await helper.waitPopup() - await nvim.input('#') - await helper.wait(100) - let items = await helper.getItems() - expect(items[0].word).toBe('foo#abc') - }) - - it('should use source-provided score', async () => { - let source: ISource = { - priority: 0, - enable: true, - name: 'source', - sourceType: SourceType.Service, - doComplete: (_opt: CompleteOption): Promise => Promise.resolve({ - items: [ - { word: 'candidate_a', sourceScore: 0.1 }, - { word: 'candidate_b', sourceScore: 10 }, - { word: 'candidate_c' }, - ] - }), - } - disposables.push(sources.addSource(source)) - await nvim.input('ocand') - await helper.waitPopup() - let items = await helper.getItems() - expect(items[0].word).toBe('candidate_b') - expect(items[1].word).toBe('candidate_c') - expect(items[2].word).toBe('candidate_a') - }) - - it('should do resolve for complete item', async () => { - let source: ISource = { - priority: 0, - enable: true, - name: 'resolve', - sourceType: SourceType.Service, - triggerCharacters: ['.'], - doComplete: (_opt: CompleteOption): Promise => Promise.resolve({ items: [{ word: 'foo' }] }), - onCompleteResolve: item => { - item.info = 'detail' - } - } - sources.addSource(source) - await nvim.input('i.') - await helper.waitPopup() - await helper.wait(100) - await nvim.input('') - await helper.wait(100) - // let items = completion.completeItems - // expect(items[0].info).toBe('detail') - sources.removeSource(source) - }) -}) - -describe('completion done', () => { - it('should fix word on CompleteDone', async () => { - await nvim.setLine('fball football') - await nvim.input('i') - await nvim.call('cursor', [1, 2]) - let option: CompleteOption = await nvim.call('coc#util#get_complete_option') - await completion.startCompletion(option) - let items = await helper.items() - expect(items.length).toBe(1) - await nvim.input('') - await helper.wait(30) - await nvim.call('coc#_select') - await helper.wait(100) - let line = await nvim.line - expect(line).toBe('football football') - }) -}) - -describe('completion option', () => { - it('should hide kind and menu when configured', async () => { - helper.updateConfiguration('suggest.disableKind', true) - helper.updateConfiguration('suggest.disableMenu', true) - await nvim.setLine('fball football') - await nvim.input('of') - await helper.waitPopup() - let items = await helper.getItems() - expect(items[0].kind).toBeUndefined() - expect(items[0].menu).toBeUndefined() - helper.updateConfiguration('suggest.disableKind', false) - helper.updateConfiguration('suggest.disableMenu', false) - }) -}) - -describe('completion trigger', () => { - it('should trigger completion on type trigger character', async () => { - let source: ISource = { - priority: 1, - enable: true, - name: 'trigger', - sourceType: SourceType.Service, - triggerCharacters: ['.'], - doComplete: (opt: CompleteOption): Promise => { - if (opt.triggerCharacter == '.') { - return Promise.resolve({ items: [{ word: 'bar' }] }) - } - return Promise.resolve({ items: [{ word: 'foo#bar' }] }) - } - } - sources.addSource(source) - await nvim.input('i') - await helper.wait(30) - await nvim.input('.') - await helper.waitPopup() - let items = await helper.items() - expect(items.length).toBeGreaterThan(0) - sources.removeSource(source) - }) - - it('should not trigger if autoTrigger is none', async () => { - let config = workspace.getConfiguration('suggest') - config.update('autoTrigger', 'none') - let autoTrigger = completion.config.autoTrigger - expect(autoTrigger).toBe('none') - await nvim.setLine('foo fo') - await nvim.input('A') - await helper.wait(100) - expect(completion.isActivated).toBe(false) - config.update('autoTrigger', 'always') - }) - - it('should trigger complete on trigger patterns match', async () => { - let source: ISource = { - priority: 99, - enable: true, - name: 'temp', - triggerPatterns: [/EM/], - sourceType: SourceType.Service, - doComplete: (opt: CompleteOption): Promise => { - if (!opt.input.startsWith('EM')) return null - return Promise.resolve({ - items: [ - { word: 'foo', filterText: 'EMfoo' }, - { word: 'bar', filterText: 'EMbar' } - ] - }) - }, - } - disposables.push(sources.addSource(source)) - await nvim.input('i') - await nvim.input('EM') - await helper.waitPopup() - let items = await helper.getItems() - expect(items.length).toBe(2) - }) - - it('should trigger complete when pumvisible and triggerPatterns match', async () => { - await nvim.setLine('EnumMember') - let source: ISource = { - priority: 99, - enable: true, - name: 'temp', - triggerPatterns: [/EM/], - sourceType: SourceType.Service, - doComplete: (opt: CompleteOption): Promise => { - if (!opt.input.startsWith('EM')) return null - return Promise.resolve({ - items: [ - { word: 'a', filterText: 'EMa' }, - { word: 'b', filterText: 'EMb' } - ] - }) - }, - } - disposables.push(sources.addSource(source)) - await nvim.input('o') - await helper.wait(10) - await nvim.input('E') - await helper.wait(30) - await nvim.input('M') - await helper.waitPopup() - let items = await helper.getItems() - expect(items.length).toBeGreaterThan(2) - }) -}) - -describe('completion TextChangedI', () => { - it('should respect commitCharacter on TextChangedI', async () => { - let source: ISource = { - priority: 0, - enable: true, - name: 'slow', - sourceType: SourceType.Service, - triggerCharacters: ['.'], - doComplete: (opt: CompleteOption): Promise => { - if (opt.triggerCharacter == '.') { - return Promise.resolve({ items: [{ word: 'bar' }] }) - } - return Promise.resolve({ items: [{ word: 'foo' }] }) - }, - shouldCommit: (_item, character) => character == '.' - } - sources.addSource(source) - await nvim.input('if') - await helper.pumvisible() - await helper.wait(100) - await nvim.input('.') - await helper.wait(100) - sources.removeSource(source) - }) - - it('should cancel completion with same pretext', async () => { - await nvim.setLine('foo') - await nvim.input('of') - await helper.pumvisible() - await helper.wait(30) - await nvim.call('coc#_cancel', []) - let line = await nvim.line - let visible = await nvim.call('pumvisible') - expect(line).toBe('f') - expect(visible).toBe(0) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/configurations.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/configurations.test.ts deleted file mode 100644 index d6cfb646..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/configurations.test.ts +++ /dev/null @@ -1,247 +0,0 @@ -import fs from 'fs' -import os from 'os' -import { ParseError } from 'jsonc-parser' -import path from 'path' -import Configurations from '../../configuration' -import { convertErrors, getChangedKeys, getConfigurationValue, getKeys, parseConfiguration } from '../../configuration/util' -import { IConfigurationModel } from '../../types' -import { URI } from 'vscode-uri' -import { v1 as uuidv1 } from 'uuid' -import { CONFIG_FILE_NAME } from '../../util' - -const config = fs.readFileSync(path.join(__dirname, './settings.json'), 'utf8') -const workspaceConfigFile = path.resolve(__dirname, `../sample/.vim/${CONFIG_FILE_NAME}`) - -function getConfigurationModel(): IConfigurationModel { - let [, contents] = parseConfiguration(config) - return { contents } -} - -function createConfigurations(): Configurations { - let userConfigFile = path.join(__dirname, './settings.json') - return new Configurations(userConfigFile) -} - -describe('Configurations', () => { - it('should convert errors', () => { - let errors: ParseError[] = [] - for (let i = 0; i < 17; i++) { - errors.push({ - error: i, - offset: 0, - length: 10 - }) - } - let res = convertErrors('file:///1', 'abc', errors) - expect(res.length).toBe(17) - }) - - it('should get all keys', () => { - let res = getKeys({ - foo: { - bar: 1, - from: { - to: 2 - } - }, - bar: [1, 2] - }) - expect(res).toEqual(['foo', 'foo.bar', 'foo.from', 'foo.from.to', 'bar']) - }) - - it('should get configuration value', () => { - let root = { - foo: { - bar: 1, - from: { - to: 2 - } - }, - bar: [1, 2] - } - let res = getConfigurationValue(root, 'foo.from.to', 1) - expect(res).toBe(2) - res = getConfigurationValue(root, 'foo.from', 1) - expect(res).toEqual({ to: 2 }) - }) - - it('should add folder as workspace configuration', () => { - let configurations = createConfigurations() - configurations.onDidChange(e => { - let affects = e.affectsConfiguration('coc') - expect(affects).toBe(true) - }) - configurations.addFolderFile(workspaceConfigFile) - let o = configurations.configuration.workspace.contents - expect(o.coc.preferences.rootPath).toBe('./src') - configurations.dispose() - }) - - it('should get changed keys #1', () => { - let res = getChangedKeys({ y: 2 }, { x: 1 }) - expect(res).toEqual(['x', 'y']) - }) - - it('should get changed keys #2', () => { - let res = getChangedKeys({ x: 1, c: { d: 4 } }, { x: 1, b: { x: 5 } }) - expect(res).toEqual(['b', 'b.x', 'c', 'c.d']) - }) - - it('should load default configurations', () => { - let conf = new Configurations() - expect(conf.defaults.contents.coc).toBeDefined() - let c = conf.getConfiguration('languageserver') - expect(c).toEqual({}) - conf.dispose() - }) - - it('should parse configurations', () => { - let { contents } = getConfigurationModel() - expect(contents.foo.bar).toBe(1) - expect(contents.bar.foo).toBe(2) - expect(contents.schema).toEqual({ 'https://example.com': '*.yaml' }) - }) - - it('should update user config #1', () => { - let conf = new Configurations() - let fn = jest.fn() - conf.onDidChange(e => { - expect(e.affectsConfiguration('x')).toBe(true) - fn() - }) - conf.updateUserConfig({ x: 1 }) - let config = conf.configuration.user - expect(config.contents).toEqual({ x: 1 }) - expect(fn).toBeCalled() - }) - - it('should update user config #2', () => { - let conf = new Configurations() - conf.updateUserConfig({ x: 1 }) - conf.updateUserConfig({ x: undefined }) - let config = conf.configuration.user - expect(config.contents).toEqual({}) - }) - - it('should update workspace config', () => { - let conf = new Configurations() - conf.updateUserConfig({ foo: { bar: 1 } }) - let curr = conf.getConfiguration('foo') - curr.update('bar', 2, false) - curr = conf.getConfiguration('foo') - let n = curr.get('bar') - expect(n).toBe(2) - }) - - it('should handle errors', () => { - let tmpFile = path.join(os.tmpdir(), uuidv1()) - fs.writeFileSync(tmpFile, '{"x":', 'utf8') - let conf = new Configurations(tmpFile) - let errors = conf.errorItems - expect(errors.length > 1).toBe(true) - conf.dispose() - }) - - it('should change to new folder configuration', () => { - let conf = new Configurations() - conf.addFolderFile(workspaceConfigFile) - let configFile = path.join(__dirname, './settings.json') - conf.addFolderFile(configFile) - let file = path.resolve(__dirname, '../sample/tmp.js') - let fn = jest.fn() - conf.onDidChange(fn) - conf.setFolderConfiguration(URI.file(file).toString()) - let { contents } = conf.workspace - expect(contents.foo).toBeUndefined() - expect(fn).toBeCalled() - conf.dispose() - }) - - it('should get nested property', () => { - let config = createConfigurations() - let conf = config.getConfiguration('servers.c') - let res = conf.get('trace.server', '') - expect(res).toBe('verbose') - config.dispose() - }) - - it('should get user and workspace configuration', () => { - let userConfigFile = path.join(__dirname, './settings.json') - let configurations = new Configurations(userConfigFile) - let data = configurations.configuration.toData() - expect(data.user).toBeDefined() - expect(data.workspace).toBeDefined() - expect(data.defaults).toBeDefined() - let value = configurations.configuration.getValue() - expect(value.foo).toBeDefined() - expect(value.foo.bar).toBe(1) - configurations.dispose() - }) - - it('should override with new value', () => { - let configurations = createConfigurations() - configurations.configuration.defaults.setValue('foo', 1) - let { contents } = configurations.defaults - expect(contents.foo).toBe(1) - configurations.dispose() - }) - - it('should extends defaults', () => { - let configurations = createConfigurations() - configurations.extendsDefaults({ 'a.b': 1 }) - configurations.extendsDefaults({ 'a.b': 2 }) - let o = configurations.defaults.contents - expect(o.a.b).toBe(2) - configurations.dispose() - }) - - it('should update configuration', async () => { - let configurations = createConfigurations() - configurations.addFolderFile(workspaceConfigFile) - let fn = jest.fn() - configurations.onDidChange(e => { - expect(e.affectsConfiguration('foo')).toBe(true) - expect(e.affectsConfiguration('foo.bar')).toBe(true) - expect(e.affectsConfiguration('foo.bar', 'file://tmp/foo.js')).toBe(false) - fn() - }) - let config = configurations.getConfiguration('foo') - let o = config.get('bar') - expect(o).toBe(1) - config.update('bar', 6) - config = configurations.getConfiguration('foo') - expect(config.get('bar')).toBe(6) - expect(fn).toBeCalledTimes(1) - configurations.dispose() - }) - - it('should remove configuration', async () => { - let configurations = createConfigurations() - configurations.addFolderFile(workspaceConfigFile) - let fn = jest.fn() - configurations.onDidChange(e => { - expect(e.affectsConfiguration('foo')).toBe(true) - expect(e.affectsConfiguration('foo.bar')).toBe(true) - fn() - }) - let config = configurations.getConfiguration('foo') - let o = config.get('bar') - expect(o).toBe(1) - config.update('bar', null, true) - config = configurations.getConfiguration('foo') - expect(config.get('bar')).toBeUndefined() - expect(fn).toBeCalledTimes(1) - configurations.dispose() - }) -}) - -describe('parse configuration', () => { - it('should only split top level dot keys', () => { - let o = { 'x.y': 'foo' } - let [, contents] = parseConfiguration(JSON.stringify(o)) - expect(contents).toEqual({ x: { y: 'foo' } }) - let schema = { 'my.schema': { 'foo.bar': 1 } } - let [, obj] = parseConfiguration(JSON.stringify(schema)) - expect(obj).toEqual({ my: { schema: { 'foo.bar': 1 } } }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/cursors.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/cursors.test.ts deleted file mode 100644 index ef37424b..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/cursors.test.ts +++ /dev/null @@ -1,421 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Range } from 'vscode-languageserver-types' -import Cursors from '../../cursors' -import Document from '../../model/document' -import helper from '../helper' - -let nvim: Neovim -let cursors: Cursors -let ns: number - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - ns = await nvim.createNamespace('coc-cursors') - cursors = new Cursors(nvim) -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - nvim.pauseNotification() - cursors.reset() - await nvim.resumeNotification() - await helper.reset() -}) - -async function rangeCount(): Promise { - let buf = await nvim.buffer - let markers = await helper.getMarkers(buf.id, ns) - return markers.length -} - -describe('cursors#select', () => { - - it('should select by position', async () => { - let doc = await helper.createDocument() - await nvim.call('setline', [1, ['a', 'b']]) - await nvim.call('cursor', [1, 1]) - await helper.wait(100) - doc.forceSync() - await helper.wait(100) - await cursors.select(doc.bufnr, 'position', 'n') - await helper.wait(30) - let n = await rangeCount() - expect(n).toBe(1) - await nvim.setOption('virtualedit', 'onemore') - await nvim.call('cursor', [2, 2]) - await cursors.select(doc.bufnr, 'position', 'n') - n = await rangeCount() - expect(n).toBe(2) - await cursors.select(doc.bufnr, 'position', 'n') - n = await rangeCount() - expect(n).toBe(1) - }) - - it('should select by word', async () => { - let doc = await helper.createDocument() - await nvim.call('setline', [1, ['foo', 'bar']]) - await nvim.call('cursor', [1, 1]) - await helper.wait(30) - doc.forceSync() - await cursors.select(doc.bufnr, 'word', 'n') - let n = await rangeCount() - expect(n).toBe(1) - await nvim.call('cursor', [2, 2]) - await cursors.select(doc.bufnr, 'word', 'n') - n = await rangeCount() - expect(n).toBe(2) - await cursors.select(doc.bufnr, 'word', 'n') - n = await rangeCount() - expect(n).toBe(1) - }) - - it('should select last character', async () => { - let doc = await helper.createDocument() - await nvim.setOption('virtualedit', 'onemore') - await nvim.call('setline', [1, ['}', '{']]) - await nvim.call('cursor', [1, 2]) - await helper.wait(30) - doc.forceSync() - await cursors.select(doc.bufnr, 'word', 'n') - let n = await rangeCount() - expect(n).toBe(1) - await nvim.call('cursor', [2, 1]) - await helper.wait(30) - doc.forceSync() - await cursors.select(doc.bufnr, 'word', 'n') - n = await rangeCount() - expect(n).toBe(2) - }) - - it('should select by visual range', async () => { - let doc = await helper.createDocument() - await nvim.call('setline', [1, ['"foo"', '"bar"']]) - await nvim.call('cursor', [1, 1]) - await nvim.command('normal! vE') - await helper.wait(30) - doc.forceSync() - await cursors.select(doc.bufnr, 'range', 'v') - let n = await rangeCount() - expect(n).toBe(1) - await nvim.call('cursor', [2, 1]) - await nvim.command('normal! vE') - await cursors.select(doc.bufnr, 'range', 'v') - n = await rangeCount() - expect(n).toBe(2) - await cursors.select(doc.bufnr, 'range', 'v') - n = await rangeCount() - expect(n).toBe(1) - }) - - it('should select by operator', async () => { - await nvim.command('nmap x (coc-cursors-operator)') - await helper.createDocument() - await nvim.call('setline', [1, ['"short"', '"long"']]) - await nvim.call('cursor', [1, 2]) - await nvim.input('xa"') - await helper.wait(30) - await nvim.call('cursor', [2, 2]) - await nvim.input('xa"') - await helper.wait(30) - await nvim.command('nunmap x') - }) -}) - -describe('cursors#addRanges', () => { - it('should add ranges', async () => { - let doc = await helper.createDocument() - await nvim.call('setline', [1, ['foo foo foo', 'bar bar']]) - await helper.wait(30) - doc.forceSync() - let ranges = [ - Range.create(0, 0, 0, 3), - Range.create(0, 4, 0, 7), - Range.create(0, 8, 0, 11), - Range.create(1, 0, 1, 3), - Range.create(1, 4, 1, 7) - ] - await cursors.addRanges(ranges) - let n = await rangeCount() - expect(n).toBe(5) - }) -}) - -describe('cursors#onchange', () => { - - async function setup(): Promise { - let doc = await helper.createDocument() - await nvim.call('setline', [1, ['foo foo foo', 'bar bar']]) - await helper.wait(30) - doc.forceSync() - let ranges = [ - Range.create(0, 0, 0, 3), - Range.create(0, 4, 0, 7), - Range.create(0, 8, 0, 11), - Range.create(1, 0, 1, 3), - Range.create(1, 4, 1, 7) - ] - await cursors.addRanges(ranges) - await nvim.call('cursor', [1, 1]) - return doc - } - - it('should ignore change after last range', async () => { - let doc = await setup() - await doc.buffer.append(['append']) - doc.forceSync() - await helper.wait(50) - let n = await rangeCount() - expect(n).toBe(5) - }) - - it('should adjust ranges on change before first line', async () => { - let doc = await setup() - await doc.buffer.setLines(['prepend'], { start: 0, end: 0, strictIndexing: false }) - doc.forceSync() - await helper.wait(200) - let n = await rangeCount() - expect(n).toBe(5) - await nvim.call('cursor', [2, 1]) - await nvim.input('ia') - await helper.wait(100) - doc.forceSync() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['prepend', 'afoo afoo afoo', 'abar abar']) - }) - - it('should work when change made to unrelated line', async () => { - let doc = await setup() - await doc.buffer.setLines(['prepend'], { start: 0, end: 0, strictIndexing: false }) - doc.forceSync() - await helper.wait(200) - let n = await rangeCount() - expect(n).toBe(5) - await nvim.call('cursor', [1, 1]) - await nvim.input('ia') - await helper.wait(200) - doc.forceSync() - await helper.wait(100) - await nvim.call('cursor', [2, 1]) - await nvim.input('a') - await helper.wait(100) - await doc.synchronize() - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['aprepend', 'afoo afoo afoo', 'abar abar']) - }) - - it('should add text before', async () => { - let doc = await setup() - await nvim.input('iabc') - await helper.wait(30) - await doc.synchronize() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['abcfoo abcfoo abcfoo', 'abcbar abcbar']) - }) - - it('should add text after', async () => { - let doc = await setup() - await nvim.call('cursor', [1, 4]) - await nvim.input('iabc') - await helper.wait(30) - await doc.synchronize() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['fooabc fooabc fooabc', 'barabc barabc']) - }) - - it('should add text around', async () => { - let doc = await setup() - await nvim.setLine('"foo" foo foo') - await helper.wait(30) - doc.forceSync() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['"foo" "foo" "foo"', '"bar" "bar"']) - }) - - it('should remove text before', async () => { - let doc = await setup() - await nvim.command('normal! x') - doc.forceSync() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['oo oo oo', 'ar ar']) - }) - - it('should remove text middle', async () => { - let doc = await setup() - await nvim.call('cursor', [2, 2]) - await nvim.command('normal! x') - doc.forceSync() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['fo fo fo', 'br br']) - }) - - it('should remove text after', async () => { - let doc = await setup() - await nvim.call('cursor', [1, 3]) - await nvim.command('normal! x') - doc.forceSync() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['fo fo fo', 'ba ba']) - }) - - it('should remove text around', async () => { - let doc = await helper.createDocument() - await nvim.call('setline', [1, ['"foo" "bar"']]) - await helper.wait(30) - doc.forceSync() - let ranges = [ - Range.create(0, 0, 0, 5), - Range.create(0, 6, 0, 11) - ] - await cursors.addRanges(ranges) - await nvim.call('cursor', [1, 2]) - await nvim.setLine('foo "bar"') - doc.forceSync() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['foo bar']) - }) - - it('should replace text before', async () => { - let doc = await setup() - await nvim.call('cursor', [1, 1]) - await nvim.command('normal! ra') - doc.forceSync() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['aoo aoo aoo', 'aar aar']) - }) - - it('should replace text after', async () => { - let doc = await setup() - await nvim.call('cursor', [1, 3]) - await nvim.command('normal! ra') - doc.forceSync() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['foa foa foa', 'baa baa']) - }) - - it('should replace text middle', async () => { - let doc = await setup() - await nvim.call('cursor', [1, 2]) - await nvim.input('sab') - await helper.wait(30) - doc.forceSync() - await helper.wait(100) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['fabo fabo fabo', 'babr babr']) - }) - - it('should adjust undo & redo on add & remove', async () => { - let doc = await setup() - await nvim.call('cursor', [1, 4]) - await nvim.input('iabc') - await helper.wait(30) - doc.forceSync() - let n = await rangeCount() - expect(n).toBe(5) - await helper.wait(30) - await nvim.command('undo') - await helper.wait(30) - doc.forceSync() - n = await rangeCount() - expect(n).toBe(5) - await helper.wait(30) - await nvim.command('redo') - await helper.wait(30) - doc.forceSync() - expect(await rangeCount()).toBe(5) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['fooabc fooabc fooabc', 'barabc barabc']) - }) - - it('should adjust undo & redo on change around', async () => { - let doc = await setup() - await nvim.setLine('"foo" foo foo') - await helper.wait(30) - doc.forceSync() - expect(await rangeCount()).toBe(5) - await helper.wait(30) - await nvim.command('undo') - await helper.wait(30) - doc.forceSync() - expect(await rangeCount()).toBe(5) - await helper.wait(30) - await nvim.command('redo') - await helper.wait(30) - doc.forceSync() - expect(await rangeCount()).toBe(5) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['"foo" "foo" "foo"', '"bar" "bar"']) - }) -}) - -describe('cursors#keymaps', () => { - async function setup(): Promise { - let doc = await helper.createDocument() - await nvim.call('setline', [1, ['a', 'b', 'c']]) - await helper.wait(30) - doc.forceSync() - await nvim.call('cursor', [1, 1]) - await cursors.select(doc.bufnr, 'position', 'n') - await helper.wait(30) - await nvim.call('cursor', [2, 1]) - await cursors.select(doc.bufnr, 'position', 'n') - await helper.wait(30) - await nvim.call('cursor', [3, 1]) - await cursors.select(doc.bufnr, 'position', 'n') - } - - async function hasKeymap(key): Promise { - let buf = await nvim.buffer - let keymaps = await buf.getKeymap('n') as any - return keymaps.find(o => o.lhs == key) != null - } - - it('should setup cancel keymap', async () => { - await setup() - let count = await rangeCount() - expect(count).toBe(3) - await nvim.input('') - await helper.wait(100) - count = await rangeCount() - expect(count).toBe(0) - let has = await hasKeymap('') - expect(has).toBe(false) - }) - - it('should setup next key', async () => { - await setup() - await nvim.input('') - await helper.wait(50) - let cursor = await nvim.call('coc#cursor#position') - expect(cursor).toEqual([0, 0]) - await nvim.input('') - await helper.wait(50) - cursor = await nvim.call('coc#cursor#position') - expect(cursor).toEqual([1, 0]) - }) - - it('should setup previous key', async () => { - await setup() - await nvim.input('') - await helper.wait(50) - let cursor = await nvim.call('coc#cursor#position') - expect(cursor).toEqual([1, 0]) - await nvim.input('') - await helper.wait(50) - cursor = await nvim.call('coc#cursor#position') - expect(cursor).toEqual([0, 0]) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/db.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/db.test.ts deleted file mode 100644 index a948293d..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/db.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import DB from '../../model/db' -import path from 'path' - -let db: DB -beforeAll(async () => { - db = new DB(path.join(__dirname, 'db.json')) -}) - -afterAll(async () => { - db.destroy() -}) - -afterEach(async () => { - db.clear() -}) - -describe('DB', () => { - - test('db.exists()', async () => { - let exists = db.exists('a.b') - expect(exists).toBe(false) - db.push('a.b', { foo: 1 }) - exists = db.exists('a.b.foo') - expect(exists).toBe(true) - }) - - test('db.fetch()', async () => { - let res = await db.fetch('x') - expect(res).toBeUndefined() - db.push('x', 1) - res = await db.fetch('x') - expect(res).toBe(1) - db.push('x', { foo: 1 }) - res = await db.fetch('x') - expect(res).toEqual({ foo: 1 }) - }) - - test('db.delete()', async () => { - db.push('foo.bar', 1) - db.delete('foo.bar') - let exists = db.exists('foo.bar') - expect(exists).toBe(false) - }) - - test('db.push()', async () => { - db.push('foo.x', 1) - db.push('foo.y', '2') - db.push('foo.z', true) - db.push('foo.n', null) - db.push('foo.o', { x: 1 }) - let res = db.fetch('foo') - expect(res).toEqual({ - x: 1, - y: '2', - z: true, - n: null, - o: { x: 1 } - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/decorator.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/decorator.test.ts deleted file mode 100644 index 85e58948..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/decorator.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import * as decorator from '../../util/decorator' - -class CallTest { - public count = 0 - - @decorator.memorize - public async memorized(): Promise { return ++this.count } -} - -describe('memorize', () => { - test('overlapping', async () => { - const c = new CallTest() - - const first = c.memorized() - const second = c.memorized() - expect(await first).toBe(1) - expect(await second).toBe(2) - }) - test('nonoverlapping', async () => { - const c = new CallTest() - - const first = c.memorized() - expect(await first).toBe(1) - const second = c.memorized() - expect(await second).toBe(1) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/diagnosticBuffer.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/diagnosticBuffer.test.ts deleted file mode 100644 index 9f6bdfbd..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/diagnosticBuffer.test.ts +++ /dev/null @@ -1,250 +0,0 @@ -import helper from '../helper' -import { Neovim } from '@chemzqm/neovim' -import { DiagnosticBuffer } from '../../diagnostic/buffer' -import { Range, DiagnosticSeverity, Diagnostic, DiagnosticTag, Position } from 'vscode-languageserver-types' -import workspace from '../../workspace' - -let nvim: Neovim -const config: any = { - autoRefresh: true, - checkCurrentLine: false, - locationlistUpdate: true, - enableSign: true, - enableHighlightLineNumber: true, - enableMessage: 'always', - messageTarget: 'echo', - messageDelay: 250, - refreshOnInsertMode: false, - virtualTextSrcId: 99, - virtualText: false, - virtualTextCurrentLineOnly: true, - virtualTextPrefix: " ", - virtualTextLines: 3, - virtualTextLineSeparator: " \\ ", - displayByAle: false, - level: DiagnosticSeverity.Hint, - signPriority: 11, - errorSign: '>>', - warningSign: '>>', - infoSign: '>>', - hintSign: '>>', - filetypeMap: { - default: '' - }, -} - -async function createDiagnosticBuffer(): Promise { - let doc = await helper.createDocument() - return new DiagnosticBuffer(nvim, doc.bufnr, doc.uri, config, () => { - // noop - }) -} - -function createDiagnostic(msg: string, range?: Range, severity?: DiagnosticSeverity, tags?: DiagnosticTag[]): Diagnostic & { collection: string } { - range = range ? range : Range.create(0, 0, 0, 1) - return Object.assign(Diagnostic.create(range, msg, severity || DiagnosticSeverity.Error, 999, 'test'), { collection: 'test', tags }) -} - -let ns: number -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - ns = await nvim.createNamespace('coc-diagnostic') -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('diagnostic buffer', () => { - describe('refresh()', () => { - it('should add signs', async () => { - let diagnostics = [createDiagnostic('foo'), createDiagnostic('bar')] - let buf = await createDiagnosticBuffer() - buf.addSigns('a', diagnostics) - await helper.wait(30) - let res = await nvim.call('sign_getplaced', [buf.bufnr, { group: 'CocDiagnostica' }]) - let signs = res[0].signs - expect(signs).toBeDefined() - expect(signs[0].name).toBe('CocError') - }) - - it('should set diagnostic info', async () => { - let r = Range.create(0, 1, 0, 2) - let diagnostics = [ - createDiagnostic('foo', r, DiagnosticSeverity.Error), - createDiagnostic('bar', r, DiagnosticSeverity.Warning), - createDiagnostic('foo', r, DiagnosticSeverity.Hint), - createDiagnostic('bar', r, DiagnosticSeverity.Information) - ] - let buf = await createDiagnosticBuffer() - await buf.refresh({ '': diagnostics }) - let buffer = await nvim.buffer - let res = await buffer.getVar('coc_diagnostic_info') - expect(res).toEqual({ - lnums: [1, 1, 1, 1], - information: 1, - hint: 1, - warning: 1, - error: 1 - }) - }) - - it('should add highlight', async () => { - let buf = await createDiagnosticBuffer() - let doc = workspace.getDocument(buf.bufnr) - await nvim.setLine('abc') - await doc.patchChange(true) - nvim.pauseNotification() - buf.updateHighlights('', [ - createDiagnostic('foo', Range.create(0, 0, 0, 1), DiagnosticSeverity.Error), - createDiagnostic('bar', Range.create(0, 0, 0, 1), DiagnosticSeverity.Warning) - ]) - await nvim.resumeNotification() - let res = await nvim.call('nvim_buf_get_extmarks', [buf.bufnr, ns, 0, -1, { details: true }]) as any - expect(res).toEqual([ - [ - 1, - 0, - 0, - { - hl_group: 'CocWarningHighlight', - priority: 4096, - end_col: 1, - end_row: 0 - } - ], - [ - 2, - 0, - 0, - { - hl_group: 'CocErrorHighlight', - priority: 4096, - end_col: 1, - end_row: 0 - } - ] - ]) - nvim.pauseNotification() - buf.updateHighlights('', []) - await nvim.resumeNotification() - res = await nvim.call('nvim_buf_get_extmarks', [buf.bufnr, ns, 0, -1, { details: true }]) as any[] - expect(res.length).toBe(0) - }) - - it('should add deprecated highlight', async () => { - let diagnostic = createDiagnostic('foo', Range.create(0, 0, 0, 1), DiagnosticSeverity.Information, [DiagnosticTag.Deprecated]) - let buf = await createDiagnosticBuffer() - let doc = workspace.getDocument(buf.bufnr) - await nvim.setLine('foo') - await doc.patchChange(true) - nvim.pauseNotification() - buf.updateHighlights('', [diagnostic]) - await nvim.resumeNotification() - let res = await nvim.call('nvim_buf_get_extmarks', [buf.bufnr, ns, 0, -1, {}]) as [number, number, number][] - expect(res.length).toBe(1) - }) - }) - - describe('showVirtualText()', () => { - beforeEach(async () => { - config.virtualText = true - config.virtualTextSrcId = await nvim.createNamespace('diagnostics-virtualText') - }) - afterEach(() => { - config.virtualText = false - config.virtualTextCurrentLineOnly = true - }) - - it('should show virtual text on current line', async () => { - let diagnostic = createDiagnostic('foo') - let buf = await createDiagnosticBuffer() - let diagnostics = [diagnostic] - await buf.refresh({ '': diagnostics }) - let ns = config.virtualTextSrcId - let res = await nvim.call('nvim_buf_get_extmarks', [buf.bufnr, ns, 0, -1, { details: true }]) as any - expect(res.length).toBe(1) - let texts = res[0][3].virt_text - expect(texts[0]).toEqual([' foo', 'CocErrorVirtualText']) - }) - - it('should virtual text on all lines', async () => { - config.virtualTextCurrentLineOnly = false - let buf = await createDiagnosticBuffer() - let diagnostics = [ - createDiagnostic('foo', Range.create(0, 0, 0, 1)), - createDiagnostic('bar', Range.create(1, 0, 1, 1)), - ] - await buf.refresh({ '': diagnostics }) - let ns = config.virtualTextSrcId - let res = await nvim.call('nvim_buf_get_extmarks', [buf.bufnr, ns, 0, -1, { details: true }]) as any - expect(res.length).toBe(2) - }) - }) - - describe('updateLocationList()', () => { - beforeEach(async () => { - config.locationlistUpdate = true - }) - afterEach(() => { - config.locationlistUpdate = false - }) - - it('should update location list', async () => { - let buf = await createDiagnosticBuffer() - await nvim.call('setloclist', [0, [], 'r', { title: 'Diagnostics of coc', items: [] }]) - await buf.refresh({ - a: [createDiagnostic('foo')] - }) - let res = await nvim.eval(`getloclist(bufwinid(${buf.bufnr}))`) as any[] - expect(res.length).toBe(1) - expect(res[0].text).toBe('[test 999] foo [E]') - }) - }) - - describe('clear()', () => { - let config = workspace.getConfiguration('diagnostic') - beforeEach(() => { - config.update('virtualText', true) - }) - afterEach(() => { - config.update('virtualText', false) - }) - - it('should clear all diagnostics', async () => { - let diagnostic = createDiagnostic('foo') - let buf = await createDiagnosticBuffer() - let diagnostics = [diagnostic] - await buf.refresh({ '': diagnostics }) - buf.clear() - await helper.wait(50) - let buffer = await nvim.buffer - let res = await buffer.getVar("coc_diagnostic_info") - expect(res == null).toBe(true) - }) - }) - - describe('getDiagnostics()', () => { - it('should get sorted diagnostics', async () => { - let buf = await createDiagnosticBuffer() - let diagnostics = [ - createDiagnostic('three', Range.create(0, 1, 0, 2), DiagnosticSeverity.Error), - createDiagnostic('one', Range.create(0, 0, 0, 2), DiagnosticSeverity.Warning), - createDiagnostic('two', Range.create(0, 0, 0, 2), DiagnosticSeverity.Error), - ] - diagnostics[0].tags = [DiagnosticTag.Unnecessary] - await buf.refresh({ - x: diagnostics, - y: [createDiagnostic('four', Range.create(0, 0, 0, 2), DiagnosticSeverity.Error)] - }) - let res = buf.getDiagnosticsAt(Position.create(0, 1), false) - let arr = res.map(o => o.message) - expect(arr).toEqual(['four', 'two', 'three', 'one']) - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/diagnosticCollection.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/diagnosticCollection.test.ts deleted file mode 100644 index 1321b5bb..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/diagnosticCollection.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import DiagnosticCollection from '../../diagnostic/collection' -import { Diagnostic, Range } from 'vscode-languageserver-types' - -function createDiagnostic(msg: string, range?: Range): Diagnostic { - range = range ? range : Range.create(0, 0, 0, 1) - return Diagnostic.create(range, msg) -} - -describe('diagnostic collection', () => { - - it('should create collection', () => { - let collection = new DiagnosticCollection('test') - expect(collection.name).toBe('test') - }) - - it('should set diagnostic with uri', () => { - let collection = new DiagnosticCollection('test') - let diagnostic = createDiagnostic('error') - let uri = 'file:///1' - collection.set(uri, [diagnostic]) - expect(collection.get(uri).length).toBe(1) - collection.set(uri, []) - expect(collection.get(uri).length).toBe(0) - }) - - it('should clear diagnostics with null as diagnostics', () => { - let collection = new DiagnosticCollection('test') - let diagnostic = createDiagnostic('error') - let uri = 'file:///1' - collection.set(uri, [diagnostic]) - expect(collection.get(uri).length).toBe(1) - collection.set(uri, null) - expect(collection.get(uri).length).toBe(0) - }) - - it('should clear diagnostics with undefined as diagnostics in entries', () => { - let collection = new DiagnosticCollection('test') - let diagnostic = createDiagnostic('error') - let entries: [string, Diagnostic[] | null][] = [ - ['file:1', [diagnostic]], - ['file:1', undefined] - ] - let uri = 'file:///1' - collection.set(entries) - expect(collection.get(uri).length).toBe(0) - }) - - it('should set diagnostics with entries', () => { - let collection = new DiagnosticCollection('test') - let diagnostic = createDiagnostic('error') - let uri = 'file:///1' - let other = 'file:///2' - let entries: [string, Diagnostic[]][] = [ - [uri, [diagnostic]], - [other, [diagnostic]], - [uri, [createDiagnostic('other')]] - ] - collection.set(entries) - expect(collection.get(uri).length).toBe(2) - expect(collection.get(other).length).toBe(1) - }) - - it('should delete diagnostics for uri', () => { - let collection = new DiagnosticCollection('test') - let diagnostic = createDiagnostic('error') - let uri = 'file:///1' - collection.set(uri, [diagnostic]) - collection.delete(uri) - expect(collection.get(uri).length).toBe(0) - }) - - it('should clear all diagnostics', () => { - let collection = new DiagnosticCollection('test') - let diagnostic = createDiagnostic('error') - let uri = 'file:///1' - collection.set(uri, [diagnostic]) - collection.clear() - expect(collection.get(uri).length).toBe(0) - }) - - it('should call for every uri with diagnostics', () => { - let collection = new DiagnosticCollection('test') - let diagnostic = createDiagnostic('error') - let uri = 'file:///1' - let other = 'file:///2' - let entries: [string, Diagnostic[]][] = [ - [uri, [diagnostic]], - [other, [diagnostic]], - [uri, [createDiagnostic('other')]] - ] - collection.set(entries) - let arr: string[] = [] - collection.forEach(uri => { - arr.push(uri) - }) - expect(arr).toEqual([uri, other]) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/diagnosticManager.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/diagnosticManager.test.ts deleted file mode 100644 index 14e5fe82..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/diagnosticManager.test.ts +++ /dev/null @@ -1,556 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import path from 'path' -import { severityLevel, getNameFromSeverity } from '../../diagnostic/util' -import { Range, DiagnosticSeverity, Diagnostic, Location, DiagnosticTag } from 'vscode-languageserver-types' -import { URI } from 'vscode-uri' -import Document from '../../model/document' -import workspace from '../../workspace' -import window from '../../window' -import manager from '../../diagnostic/manager' -import helper, { createTmpFile } from '../helper' - -let nvim: Neovim -function createDiagnostic(msg: string, range?: Range, severity?: DiagnosticSeverity): Diagnostic { - range = range ? range : Range.create(0, 0, 0, 1) - return Diagnostic.create(range, msg, severity || DiagnosticSeverity.Error) -} - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - manager.reset() - await helper.reset() -}) - -async function createDocument(name?: string): Promise { - let doc = await helper.createDocument(name) - let collection = manager.create('test') - let diagnostics: Diagnostic[] = [] - await doc.buffer.setLines(['foo bar foo bar', 'foo bar', 'foo', 'bar'], { - start: 0, - end: -1, - strictIndexing: false - }) - diagnostics.push(createDiagnostic('error', Range.create(0, 2, 0, 4), DiagnosticSeverity.Error)) - diagnostics.push(createDiagnostic('warning', Range.create(0, 5, 0, 6), DiagnosticSeverity.Warning)) - diagnostics.push(createDiagnostic('information', Range.create(1, 0, 1, 1), DiagnosticSeverity.Information)) - diagnostics.push(createDiagnostic('hint', Range.create(1, 2, 1, 3), DiagnosticSeverity.Hint)) - diagnostics.push(createDiagnostic('error', Range.create(2, 0, 2, 2), DiagnosticSeverity.Error)) - collection.set(doc.uri, diagnostics) - doc.forceSync() - return doc -} - -describe('diagnostic manager', () => { - describe('refresh()', () => { - it('should refresh on buffer create', async () => { - let uri = URI.file(path.join(path.dirname(__dirname), 'doc')).toString() - let fn = jest.fn() - let disposable = manager.onDidRefresh(() => { - fn() - }) - let collection = manager.create('tmp') - let diagnostic = createDiagnostic('My Error') - collection.set(uri, [diagnostic]) - let doc = await helper.createDocument('doc') - let val = await doc.buffer.getVar('coc_diagnostic_info') as any - expect(fn).toBeCalled() - expect(val).toBeDefined() - expect(val.error).toBe(1) - collection.dispose() - disposable.dispose() - }) - - it('should delay refresh on InsertLeave', async () => { - let doc = await helper.createDocument() - await nvim.input('i') - let collection = manager.create('test') - let diagnostics: Diagnostic[] = [] - await doc.buffer.setLines(['foo bar foo bar', 'foo bar', 'foo', 'bar'], { - start: 0, - end: -1, - strictIndexing: false - }) - diagnostics.push(createDiagnostic('error', Range.create(0, 2, 0, 4), DiagnosticSeverity.Error)) - collection.set(doc.uri, diagnostics) - await helper.wait(10) - await nvim.input('') - await helper.wait(100) - let val = await doc.buffer.getVar('coc_diagnostic_info') as any - expect(val).toBe(null) - await helper.wait(600) - val = await doc.buffer.getVar('coc_diagnostic_info') as any - expect(val).toBeDefined() - }) - }) - - describe('toggleDiagnostic()', () => { - it('should toggle diagnostics', async () => { - let doc = await createDocument() - await helper.wait(50) - manager.toggleDiagnostic() - await helper.wait(50) - let val = await doc.buffer.getVar('coc_diagnostic_info') as any - expect(val).toBe(null) - manager.toggleDiagnostic() - await helper.wait(50) - val = await doc.buffer.getVar('coc_diagnostic_info') as any - expect(val).toBeDefined() - expect(val.error).toBe(2) - }) - }) - - describe('getDiagnosticList()', () => { - it('should get all diagnostics', async () => { - await createDocument() - let list = manager.getDiagnosticList() - expect(list).toBeDefined() - expect(list.length).toBeGreaterThanOrEqual(5) - expect(list[0].severity).toBe('Error') - expect(list[1].severity).toBe('Error') - expect(list[2].severity).toBe('Warning') - expect(list[3].severity).toBe('Information') - expect(list[4].severity).toBe('Hint') - }) - - it('should filter diagnostics by configuration', async () => { - let config = workspace.getConfiguration('diagnostic') - config.update('level', 'warning') - config.update('showUnused', false) - config.update('showDeprecated', false) - let doc = await createDocument() - let diagnostics = manager.getDiagnostics(doc.uri)['test'] - diagnostics[0].tags = [DiagnosticTag.Unnecessary] - diagnostics[2].tags = [DiagnosticTag.Deprecated] - let collection = manager.getCollectionByName('test') - collection.set(doc.uri, diagnostics) - let list = manager.getDiagnosticList() - expect(list.length).toBe(1) - expect(list[0].severity).toBe('Warning') - let res = manager.getDiagnostics(doc.uri)['test'] - expect(res.length).toBe(1) - helper.updateConfiguration('diagnostic.level', 'hint') - helper.updateConfiguration('diagnostic.showUnused', true) - helper.updateConfiguration('diagnostic.showDeprecated', true) - let ranges = manager.getSortedRanges(doc.uri) - expect(ranges.length).toBe(3) - }) - }) - - describe('preview()', () => { - it('should not throw with empty diagnostics', async () => { - await helper.createDocument() - await manager.preview() - let tabpage = await nvim.tabpage - let wins = await tabpage.windows - expect(wins.length).toBe(1) - }) - - it('should open preview window', async () => { - await createDocument() - await nvim.call('cursor', [1, 3]) - await manager.preview() - let res = await nvim.call('coc#window#find', ['&previewwindow', 1]) - expect(res).toBeDefined() - await nvim.call('win_gotoid', [res]) - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines[0]).toEqual('[test] [E]') - }) - }) - - describe('setLocationlist()', () => { - it('should set location list', async () => { - let doc = await createDocument() - await manager.setLocationlist(doc.bufnr) - await nvim.command('lopen') - let buftype = await nvim.eval('&buftype') as string - expect(buftype).toBe('quickfix') - }) - }) - - describe('setConfigurationErrors()', () => { - it('should set configuration errors', async () => { - let doc = await helper.createDocument() - let errors = [{ - location: Location.create(doc.uri, Range.create(0, 0, 1, 0)), - message: 'foo', - }, { - location: Location.create(doc.uri, Range.create(1, 0, 2, 0)), - message: 'bar', - }] - manager.setConfigurationErrors(errors) - await helper.wait(50) - let res = manager.getDiagnostics(doc.uri, 'config')['config'] - expect(res.length).toBe(2) - manager.setConfigurationErrors() - await helper.wait(50) - res = manager.getDiagnostics(doc.uri, 'config')['config'] - expect(res.length).toBe(0) - }) - }) - - describe('create()', () => { - it('should create diagnostic collection', async () => { - let doc = await helper.createDocument() - let collection = manager.create('test') - collection.set(doc.uri, [createDiagnostic('foo')]) - await helper.wait(50) - let info = await doc.buffer.getVar('coc_diagnostic_info') - expect(info).toBeDefined() - await nvim.command('bd!') - await helper.wait(50) - }) - }) - - describe('getSortedRanges()', () => { - it('should get sorted ranges of document', async () => { - let doc = await helper.createDocument() - await nvim.call('setline', [1, ['a', 'b', 'c']]) - let collection = manager.create('test') - let diagnostics: Diagnostic[] = [] - diagnostics.push(createDiagnostic('x', Range.create(0, 0, 0, 1))) - diagnostics.push(createDiagnostic('y', Range.create(0, 1, 0, 2))) - diagnostics.push(createDiagnostic('z', Range.create(1, 0, 1, 2))) - collection.set(doc.uri, diagnostics) - let ranges = manager.getSortedRanges(doc.uri) - expect(ranges[0]).toEqual(Range.create(0, 0, 0, 1)) - expect(ranges[1]).toEqual(Range.create(0, 1, 0, 2)) - expect(ranges[2]).toEqual(Range.create(1, 0, 1, 2)) - ranges = manager.getSortedRanges(doc.uri, 'error') - expect(ranges.length).toBe(3) - expect(manager.getSortedRanges(doc.uri, 'warning').length).toBe(0) - }) - }) - - describe('getDiagnosticsInRange', () => { - it('should get diagnostics in range', async () => { - let doc = await helper.createDocument() - let collection = manager.create('test') - let diagnostics: Diagnostic[] = [] - await doc.buffer.setLines(['foo bar foo bar', 'foo bar'], { - start: 0, - end: -1, - strictIndexing: false - }) - await helper.wait(300) - diagnostics.push(createDiagnostic('a', Range.create(0, 0, 0, 1))) - diagnostics.push(createDiagnostic('b', Range.create(0, 2, 0, 3))) - diagnostics.push(createDiagnostic('c', Range.create(1, 0, 1, 2))) - collection.set(doc.uri, diagnostics) - let res = manager.getDiagnosticsInRange(doc.textDocument, Range.create(0, 0, 0, 3)) - expect(res.length).toBe(2) - }) - }) - - describe('getCurrentDiagnostics', () => { - it('should get diagnostics under corsor', async () => { - let config = workspace.getConfiguration('diagnostic') - await createDocument() - let diagnostics = await manager.getCurrentDiagnostics() - expect(diagnostics.length).toBe(0) - await nvim.call('cursor', [1, 4]) - diagnostics = await manager.getCurrentDiagnostics() - expect(diagnostics.length).toBe(1) - config.update('checkCurrentLine', true) - await nvim.call('cursor', [1, 2]) - diagnostics = await manager.getCurrentDiagnostics() - expect(diagnostics.length).toBe(2) - config.update('checkCurrentLine', false) - }) - - it('should get empty diagnostic at end of line', async () => { - let doc = await helper.createDocument() - await nvim.setLine('foo') - doc.forceSync() - await nvim.command('normal! $') - let diagnostic = Diagnostic.create(Range.create(0, 3, 1, 0), 'error', DiagnosticSeverity.Error) - let collection = manager.create('empty') - collection.set(doc.uri, [diagnostic]) - await manager.refreshBuffer(doc.bufnr, true) - let diagnostics = await manager.getCurrentDiagnostics() - expect(diagnostics.length).toBeGreaterThanOrEqual(1) - expect(diagnostics[0].message).toBe('error') - collection.dispose() - }) - - it('should get diagnostic next to end of line', async () => { - let doc = await helper.createDocument() - await nvim.setLine('foo') - doc.forceSync() - await nvim.command('normal! $') - let diagnostic = Diagnostic.create(Range.create(0, 3, 0, 4), 'error', DiagnosticSeverity.Error) - let collection = manager.create('empty') - collection.set(doc.uri, [diagnostic]) - await manager.refreshBuffer(doc.bufnr, true) - let diagnostics = await manager.getCurrentDiagnostics() - expect(diagnostics.length).toBeGreaterThanOrEqual(1) - expect(diagnostics[0].message).toBe('error') - collection.dispose() - }) - - it('should get diagnostic with empty range at end of line', async () => { - let doc = await helper.createDocument() - await nvim.setLine('foo') - doc.forceSync() - await nvim.command('normal! $') - let diagnostic = Diagnostic.create(Range.create(0, 3, 1, 0), 'error', DiagnosticSeverity.Error) - let collection = manager.create('empty') - collection.set(doc.uri, [diagnostic]) - await manager.refreshBuffer(doc.bufnr, true) - let diagnostics = await manager.getCurrentDiagnostics() - expect(diagnostics.length).toBeGreaterThanOrEqual(1) - expect(diagnostics[0].message).toBe('error') - collection.dispose() - }) - - it('should get diagnostic pass end of the buffer lines', async () => { - let doc = await helper.createDocument() - await nvim.setLine('foo') - doc.forceSync() - await nvim.command('normal! ^') - let diagnostic = Diagnostic.create(Range.create(1, 0, 1, 0), 'error', DiagnosticSeverity.Error) - let collection = manager.create('empty') - collection.set(doc.uri, [diagnostic]) - await manager.refreshBuffer(doc.bufnr, true) - let diagnostics = await manager.getCurrentDiagnostics() - expect(diagnostics.length).toBeGreaterThanOrEqual(1) - expect(diagnostics[0].message).toBe('error') - collection.dispose() - }) - - }) - - describe('jumpRelated', () => { - it('should jump to related position', async () => { - let doc = await helper.createDocument() - let range = Range.create(0, 0, 0, 10) - let location = Location.create(URI.file(__filename).toString(), range) - let diagnostic = Diagnostic.create(range, 'msg', DiagnosticSeverity.Error, 1000, 'test', - [{ location, message: 'test' }]) - let collection = manager.create('positions') - collection.set(doc.uri, [diagnostic]) - await manager.refreshBuffer(doc.uri, true) - await nvim.call('cursor', [1, 1]) - await manager.jumpRelated() - await helper.wait(100) - let bufname = await nvim.call('bufname', '%') - expect(bufname).toMatch('diagnosticManager') - }) - - it('should open location list', async () => { - let doc = await helper.createDocument() - let range = Range.create(0, 0, 0, 10) - let diagnostic = Diagnostic.create(range, 'msg', DiagnosticSeverity.Error, 1000, 'test', - [{ - location: Location.create(URI.file(__filename).toString(), Range.create(1, 0, 1, 10)), - message: 'foo' - }, { - location: Location.create(URI.file(__filename).toString(), Range.create(2, 0, 2, 10)), - message: 'bar' - }]) - let collection = manager.create('positions') - collection.set(doc.uri, [diagnostic]) - await manager.refreshBuffer(doc.uri, true) - await nvim.call('cursor', [1, 1]) - await manager.jumpRelated() - await helper.wait(100) - let bufname = await nvim.call('bufname', '%') - expect(bufname).toBe('list:///location') - }) - }) - - describe('jumpPrevious & jumpNext', () => { - it('should jump to previous', async () => { - let doc = await createDocument() - await nvim.command('normal! G$') - let ranges = manager.getSortedRanges(doc.uri) - ranges.reverse() - for (let i = 0; i < ranges.length; i++) { - await manager.jumpPrevious() - let pos = await window.getCursorPosition() - expect(pos).toEqual(ranges[i].start) - } - await manager.jumpPrevious() - }) - - it('should jump to next', async () => { - let doc = await createDocument() - await nvim.call('cursor', [0, 0]) - let ranges = manager.getSortedRanges(doc.uri) - for (let i = 0; i < ranges.length; i++) { - await manager.jumpNext() - let pos = await window.getCursorPosition() - expect(pos).toEqual(ranges[i].start) - } - await manager.jumpNext() - }) - }) - - describe('diagnostic configuration', () => { - it('should use filetype map from config', async () => { - let config = workspace.getConfiguration('diagnostic') - config.update('filetypeMap', { default: 'bufferType' }) - let doc = await createDocument('foo.js') - let collection = manager.getCollectionByName('test') - let diagnostics = [createDiagnostic('99', Range.create(0, 0, 0, 2), DiagnosticSeverity.Error)] - collection.set(doc.uri, diagnostics) - await nvim.call('cursor', [1, 1]) - await nvim.command('doautocmd CursorHold') - let winid = await helper.waitFloat() - await nvim.call('win_gotoid', [winid]) - await nvim.command('normal! $') - let res = await nvim.eval('synIDattr(synID(line("."),col("."),1),"name")') - expect(res).toMatch(/javascript/i) - config.update('filetypeMap', {}) - }) - - it('should show floating window on cursor hold', async () => { - let config = workspace.getConfiguration('diagnostic') - config.update('messageTarget', 'float') - await createDocument() - await nvim.call('cursor', [1, 3]) - await nvim.command('doautocmd CursorHold') - let winid = await helper.waitFloat() - let bufnr = await nvim.call('nvim_win_get_buf', winid) as number - let buf = nvim.createBuffer(bufnr) - let lines = await buf.lines - expect(lines.join('\n')).toMatch('error') - }) - - it('should echo messages on cursor hold', async () => { - let config = workspace.getConfiguration('diagnostic') - config.update('messageTarget', 'echo') - await createDocument() - await nvim.call('cursor', [1, 3]) - await helper.wait(600) - let line = await helper.getCmdline() - expect(line).toMatch('error') - config.update('messageTarget', 'float') - }) - - it('should show diagnostics of current line', async () => { - let config = workspace.getConfiguration('diagnostic') - config.update('checkCurrentLine', true) - await createDocument() - await nvim.call('cursor', [1, 1]) - let winid = await helper.waitFloat() - let bufnr = await nvim.call('nvim_win_get_buf', winid) as number - let buf = nvim.createBuffer(bufnr) - let lines = await buf.lines - expect(lines.length).toBe(3) - config.update('checkCurrentLine', false) - }) - - it('should filter diagnostics by level', async () => { - helper.updateConfiguration('diagnostic.level', 'warning') - let doc = await createDocument() - let diagnosticsMap = manager.getDiagnostics(doc.uri) - for (let diagnostics of Object.values(diagnosticsMap)) { - for (let diagnostic of diagnostics) { - expect(diagnostic.severity != DiagnosticSeverity.Hint).toBe(true) - expect(diagnostic.severity != DiagnosticSeverity.Information).toBe(true) - } - } - helper.updateConfiguration('diagnostic.level', 'hint') - }) - - it('should send ale diagnostic items', async () => { - let config = workspace.getConfiguration('diagnostic') - config.update('displayByAle', true) - let content = ` - function! MockAleResults(bufnr, collection, items) - let g:collection = a:collection - let g:items = a:items - endfunction - ` - let file = await createTmpFile(content) - await nvim.command(`source ${file}`) - await createDocument() - await helper.wait(50) - let items = await nvim.getVar('items') as any[] - expect(Array.isArray(items)).toBe(true) - expect(items.length).toBeGreaterThan(0) - await nvim.command('bd!') - await helper.wait(50) - items = await nvim.getVar('items') as any[] - expect(items).toEqual([]) - config.update('displayByAle', false) - }) - }) - - describe('severityLevel & getNameFromSeverity', () => { - it('should get severity level', () => { - expect(severityLevel('hint')).toBe(DiagnosticSeverity.Hint) - expect(severityLevel('error')).toBe(DiagnosticSeverity.Error) - expect(severityLevel('warning')).toBe(DiagnosticSeverity.Warning) - expect(severityLevel('information')).toBe(DiagnosticSeverity.Information) - expect(severityLevel('')).toBe(DiagnosticSeverity.Hint) - }) - - it('should get severity name', () => { - expect(getNameFromSeverity(null as any)).toBe('CocError') - }) - }) - - describe('toggleDiagnosticBuffer', () => { - it('should toggle diagnostics for buffer', async () => { - let doc = await createDocument() - // required to wait refresh finish - await helper.wait(50) - await manager.toggleDiagnosticBuffer(doc.bufnr) - await helper.wait(50) - let buf = nvim.createBuffer(doc.bufnr) - let res = await buf.getVar('coc_diagnostic_info') as any - expect(res == null).toBe(true) - await manager.toggleDiagnosticBuffer(doc.bufnr) - await helper.wait(50) - res = await buf.getVar('coc_diagnostic_info') as any - expect(res.error).toBe(2) - }) - }) - - describe('refresh', () => { - let config = workspace.getConfiguration('diagnostic') - beforeEach(() => { - config.update('autoRefresh', false) - }) - afterEach(() => { - config.update('autoRefresh', true) - }) - - it('should refresh by bufnr', async () => { - let doc = await createDocument() - let buf = nvim.createBuffer(doc.bufnr) - let res = await buf.getVar('coc_diagnostic_info') as any - // should not refresh - expect(res == null).toBe(true) - manager.refresh(doc.bufnr) - await helper.wait(100) - res = await buf.getVar('coc_diagnostic_info') as any - expect(res?.error).toBe(2) - }) - - it('should refresh all buffers', async () => { - let one = await helper.createDocument('one') - let two = await helper.createDocument('two') - let collection = manager.create('tmp') - collection.set([[one.uri, [createDiagnostic('Error one')]], [two.uri, [createDiagnostic('Error two')]]]) - manager.refresh() - await helper.wait(50) - for (let bufnr of [one.bufnr, two.bufnr]) { - let buf = nvim.createBuffer(bufnr) - let res = await buf.getVar('coc_diagnostic_info') as any - expect(res?.error).toBe(1) - } - collection.dispose() - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/dialog.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/dialog.test.ts deleted file mode 100644 index eb9954e9..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/dialog.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import Dialog, { DialogButton } from '../../model/dialog' -import helper from '../helper' - -let nvim: Neovim - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('Dialog module', () => { - it('should show dialog', async () => { - let dialog = new Dialog(nvim, { content: 'ไฝ ๅฅฝ' }) - await dialog.show({}) - let winid = await dialog.winid - let win = nvim.createWindow(winid) - let width = await win.width - expect(width).toBe(4) - await nvim.call('coc#float#close', [winid]) - }) - - it('should invoke callback with index -1', async () => { - let callback = jest.fn() - let dialog = new Dialog(nvim, { content: 'ไฝ ๅฅฝ', callback }) - await dialog.show({}) - let winid = await dialog.winid - await nvim.call('coc#float#close', [winid]) - await helper.wait(50) - expect(callback).toHaveBeenCalledWith(-1) - }) - - it('should invoke callback on click', async () => { - let callback = jest.fn() - let buttons: DialogButton[] = [{ - index: 0, - text: 'yes' - }, { - index: 1, - text: 'no' - }] - let dialog = new Dialog(nvim, { content: 'ไฝ ๅฅฝ', buttons, callback }) - await dialog.show({}) - let winid = await dialog.winid - let btnwin = await nvim.call('coc#float#get_related', [winid, 'buttons']) - await nvim.call('win_gotoid', [btnwin]) - await nvim.call('cursor', [2, 1]) - await nvim.call('coc#float#nvim_float_click', []) - await helper.wait(50) - expect(callback).toHaveBeenCalledWith(0) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/diff.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/diff.test.ts deleted file mode 100644 index 51ea5a39..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/diff.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { TextEdit } from 'vscode-languageserver-types' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { diffLines, getChange, patchLine, ChangedLines } from '../../util/diff' - -describe('diff lines', () => { - function diff(oldStr: string, newStr: string): ChangedLines { - let oldLines = oldStr.split('\n') - return diffLines(oldLines, newStr.split('\n'), oldLines.length - 2) - } - - it('should diff changed lines', () => { - let res = diff('a\n', 'b\n') - expect(res).toEqual({ start: 0, end: 1, replacement: ['b'] }) - }) - - it('should diff added lines', () => { - let res = diff('a\n', 'a\nb\n') - expect(res).toEqual({ - start: 1, - end: 1, - replacement: ['b'] - }) - }) - - it('should diff remove lines', () => { - let res = diff('a\n\n', 'a\n') - expect(res).toEqual({ - start: 1, - end: 2, - replacement: [] - }) - }) - - it('should diff remove multiple lines', () => { - let res = diff('a\n\n\n', 'a\n') - expect(res).toEqual({ - start: 1, - end: 3, - replacement: [] - }) - }) - - it('should diff removed line', () => { - let res = diff('a\n\n\nb', 'a\n\nb') - expect(res).toEqual({ - start: 2, - end: 3, - replacement: [] - }) - }) - - it('should reduce changed lines', async () => { - let res = diffLines(['a', 'b', 'c'], ['a', 'b', 'c', 'd'], 0) - expect(res).toEqual({ - start: 3, - end: 3, - replacement: ['d'] - }) - }) -}) - -describe('patch line', () => { - it('should patch line', () => { - let res = patchLine('foo', 'bar foo bar') - expect(res.length).toBe(7) - expect(res).toBe(' foo') - }) -}) - -describe('should get text edits', () => { - - function applyEdits(oldStr: string, newStr: string): void { - let doc = TextDocument.create('untitled://1', 'markdown', 0, oldStr) - let change = getChange(doc.getText(), newStr) - let start = doc.positionAt(change.start) - let end = doc.positionAt(change.end) - let edit: TextEdit = { - range: { start, end }, - newText: change.newText - } - let res = TextDocument.applyEdits(doc, [edit]) - expect(res).toBe(newStr) - } - - it('should get diff for comments ', async () => { - let oldStr = '/*\n *\n * \n' - let newStr = '/*\n *\n *\n * \n' - let doc = TextDocument.create('untitled://1', 'markdown', 0, oldStr) - let change = getChange(doc.getText(), newStr, 1) - let start = doc.positionAt(change.start) - let end = doc.positionAt(change.end) - let edit: TextEdit = { - range: { start, end }, - newText: change.newText - } - let res = TextDocument.applyEdits(doc, [edit]) - expect(res).toBe(newStr) - }) - - it('should return null for same content', () => { - let change = getChange('', '') - expect(change).toBeNull() - change = getChange('abc', 'abc') - expect(change).toBeNull() - }) - - it('should get diff for added', () => { - applyEdits('1\n2', '1\n2\n3\n4') - }) - - it('should get diff for added #0', () => { - applyEdits('\n\n', '\n\n\n') - }) - - it('should get diff for added #1', () => { - applyEdits('1\n2\n3', '5\n1\n2\n3') - }) - - it('should get diff for added #2', () => { - applyEdits('1\n2\n3', '1\n2\n4\n3') - }) - - it('should get diff for added #3', () => { - applyEdits('1\n2\n3', '4\n1\n2\n3\n5') - }) - - it('should get diff for added #4', () => { - applyEdits(' ', ' ') - }) - - it('should get diff for replace', () => { - applyEdits('1\n2\n3\n4\n5', '1\n5\n3\n6\n7') - }) - - it('should get diff for replace #1', () => { - applyEdits('1\n2\n3\n4\n5', '1\n5\n3\n6\n7') - }) - - it('should get diff for remove #0', () => { - applyEdits('1\n2\n3\n4', '1\n4') - }) - - it('should get diff for remove #1', () => { - applyEdits('1\n2\n3\n4', '1') - }) - - it('should get diff for remove #2', () => { - applyEdits(' ', ' ') - }) - - it('should prefer cursor position for change', async () => { - let res = getChange(' int n', ' n', 0) - expect(res).toEqual({ start: 1, end: 5, newText: '' }) - res = getChange(' int n', ' n') - expect(res).toEqual({ start: 0, end: 4, newText: '' }) - }) - - it('should prefer next line for change', async () => { - let res = getChange('a\nb', 'a\nc\nb') - expect(res).toEqual({ start: 2, end: 2, newText: 'c\n' }) - applyEdits('a\nb', 'a\nc\nb') - }) - - it('should prefer previous line for change', async () => { - let res = getChange('\n\na', '\na') - expect(res).toEqual({ start: 0, end: 1, newText: '' }) - }) - - it('should consider cursor', () => { - let res = getChange('\n\n\n', '\n\n\n\n', 1) - expect(res).toEqual({ start: 2, end: 2, newText: '\n' }) - }) - - it('should get minimal diff', () => { - let res = getChange('foo\nbar', 'fab\nbar', 2) - expect(res).toEqual({ start: 1, end: 3, newText: 'ab' }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/document.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/document.test.ts deleted file mode 100644 index 11535de4..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/document.test.ts +++ /dev/null @@ -1,413 +0,0 @@ -import fs from 'fs' -import path from 'path' -import { Neovim } from '@chemzqm/neovim' -import { Position, Range, TextEdit } from 'vscode-languageserver-protocol' -import workspace from '../../workspace' -import helper from '../helper' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { Disposable } from '@chemzqm/neovim/lib/api/Buffer' -import { disposeAll } from '../../util' -import Document from '../../model/document' -import { URI } from 'vscode-uri' - -let nvim: Neovim -jest.setTimeout(5000) - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('properties', () => { - it('should parse iskeyword', async () => { - let doc = await helper.createDocument() - await nvim.setLine('foo bar') - doc.forceSync() - let words = doc.words - expect(words).toEqual(['foo', 'bar']) - }) - - it('should applyEdits', async () => { - let doc = await helper.createDocument() - let edits: TextEdit[] = [] - edits.push({ - range: Range.create(0, 0, 0, 0), - newText: 'a\n' - }) - edits.push({ - range: Range.create(0, 0, 0, 0), - newText: 'b\n' - }) - await doc.applyEdits(edits) - let content = doc.getDocumentContent() - expect(content).toBe('a\nb\n\n') - }) - - it('should applyEdits with changed lines', async () => { - let doc = await helper.createDocument() - await nvim.setLine('a') - await doc.patchChange() - let edits: TextEdit[] = [] - edits.push({ - range: Range.create(0, 1, 0, 1), - newText: `\n\nd` - }) - await doc.applyEdits(edits) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['a', '', 'd']) - }) - - it('should parse iskeyword of character range', async () => { - await nvim.setOption('iskeyword', 'a-z,A-Z,48-57,_') - let doc = await helper.createDocument() - let opt = await nvim.getOption('iskeyword') - expect(opt).toBe('a-z,A-Z,48-57,_') - await nvim.setLine('foo bar') - doc.forceSync() - await helper.wait(100) - let words = doc.words - expect(words).toEqual(['foo', 'bar']) - }) - - it('should get word range', async () => { - await helper.createDocument() - await nvim.setLine('foo bar') - await helper.wait(30) - let doc = await workspace.document - let range = doc.getWordRangeAtPosition({ line: 0, character: 0 }) - expect(range).toEqual(Range.create(0, 0, 0, 3)) - range = doc.getWordRangeAtPosition({ line: 0, character: 3 }) - expect(range).toBeNull() - range = doc.getWordRangeAtPosition({ line: 0, character: 4 }) - expect(range).toEqual(Range.create(0, 4, 0, 7)) - range = doc.getWordRangeAtPosition({ line: 0, character: 7 }) - expect(range).toBeNull() - }) - - it('should get symbol ranges', async () => { - let doc = await helper.createDocument() - await nvim.setLine('foo bar foo') - let ranges = doc.getSymbolRanges('foo') - expect(ranges.length).toBe(2) - }) - - it('should get localify bonus', async () => { - let doc = await helper.createDocument() - let { buffer } = doc - await buffer.setLines(['context content clearTimeout', '', 'product confirm'], - { start: 0, end: -1, strictIndexing: false }) - await helper.wait(100) - let pos: Position = { line: 1, character: 0 } - let res = doc.getLocalifyBonus(pos, pos) - expect(res.has('confirm')).toBe(true) - expect(res.has('clearTimeout')).toBe(true) - }) - - it('should get current line', async () => { - let doc = await helper.createDocument() - let { buffer } = doc - await buffer.setLines(['first line', 'second line'], - { start: 0, end: -1, strictIndexing: false }) - await helper.wait(30) - let line = doc.getline(1, true) - expect(line).toBe('second line') - }) - - it('should get cached line', async () => { - let doc = await helper.createDocument() - let { buffer } = doc - await buffer.setLines(['first line', 'second line'], - { start: 0, end: -1, strictIndexing: false }) - await helper.wait(30) - doc.forceSync() - let line = doc.getline(0, false) - expect(line).toBe('first line') - }) - - it('should get variable form buffer', async () => { - await nvim.command('autocmd BufNewFile,BufRead * let b:coc_enabled = 1') - let doc = await helper.createDocument() - let val = doc.getVar('enabled') - expect(val).toBe(1) - }) - - it('should attach change events', async () => { - let doc = await helper.createDocument() - await nvim.setLine('abc') - await helper.wait(50) - let content = doc.getDocumentContent() - expect(content.indexOf('abc')).toBe(0) - }) - - it('should not attach change events when b:coc_enabled is false', async () => { - await nvim.command('autocmd BufNewFile,BufRead *.dis let b:coc_enabled = 0') - let doc = await helper.createDocument('a.dis') - let val = doc.getVar('enabled', 0) - expect(val).toBe(0) - await nvim.setLine('abc') - await helper.wait(50) - let content = doc.getDocumentContent() - expect(content.indexOf('abc')).toBe(-1) - }) - - it('should get lineCount, previewwindow, winid', async () => { - let doc = await helper.createDocument() - let { lineCount, winid, previewwindow } = doc - expect(lineCount).toBe(1) - expect(winid != -1).toBe(true) - expect(previewwindow).toBe(false) - }) - - it('should set filetype', async () => { - let doc = await helper.createDocument() - doc.setFiletype('javascript.jsx') - expect(doc.filetype).toBe('javascriptreact') - doc.setFiletype('typescript.jsx') - expect(doc.filetype).toBe('typescriptreact') - doc.setFiletype('typescript.tsx') - expect(doc.filetype).toBe('typescriptreact') - doc.setFiletype('tex') - expect(doc.filetype).toBe('latex') - doc.setFiletype('foo') - expect(doc.filetype).toBe('foo') - }) -}) - -describe('synchronize', () => { - it('should synchronize on lines change', async () => { - let document = await helper.createDocument() - let doc = TextDocument.create('untitled:1', 'txt', 1, document.getDocumentContent()) - let disposables = [] - document.onDocumentChange(e => { - TextDocument.update(doc, e.contentChanges, 2) - }, null, disposables) - // document.on - await nvim.setLine('abc') - document.forceSync() - expect(doc.getText()).toBe('abc\n') - disposeAll(disposables) - }) - - it('should synchronize changes after applyEdits', async () => { - let document = await helper.createDocument() - let doc = TextDocument.create('untitled:1', 'txt', 1, document.getDocumentContent()) - let disposables = [] - document.onDocumentChange(e => { - TextDocument.update(doc, e.contentChanges, e.textDocument.version) - }, null, disposables) - await nvim.setLine('abc') - await document.patchChange() - await document.applyEdits([TextEdit.insert({ line: 0, character: 0 }, 'd')]) - expect(doc.getText()).toBe('dabc\n') - disposeAll(disposables) - }) -}) - -describe('recreate', () => { - async function assertDocument(fn: (doc: Document) => Promise): Promise { - let disposables: Disposable[] = [] - let fsPath = path.join(__dirname, 'document.txt') - fs.writeFileSync(fsPath, '{\nfoo\n}\n', 'utf8') - await helper.edit(fsPath) - let document = await workspace.document - document.forceSync() - let doc = TextDocument.create(document.uri, 'txt', document.version, document.getDocumentContent()) - let uri = doc.uri - workspace.onDidOpenTextDocument(e => { - if (e.uri == uri) { - doc = TextDocument.create(e.uri, 'txt', e.version, e.getText()) - } - }, null, disposables) - workspace.onDidCloseTextDocument(e => { - if (e.uri == doc.uri) doc = null - }, null, disposables) - workspace.onDidChangeTextDocument(e => { - TextDocument.update(doc, e.contentChanges, e.textDocument.version) - }, null, disposables) - await fn(document) - document = await workspace.document - document.forceSync() - let text = document.getDocumentContent() - expect(doc).toBeDefined() - expect(doc.getText()).toBe(text) - disposeAll(disposables) - fs.unlinkSync(fsPath) - } - - it('should synchronize after make changes', async () => { - await assertDocument(async () => { - await nvim.call('setline', [1, 'a']) - await nvim.call('setline', [2, 'b']) - }) - }) - - it('should synchronize after edit', async () => { - await assertDocument(async doc => { - let fsPath = URI.parse(doc.uri).fsPath - fs.writeFileSync(fsPath, '{\n}\n', 'utf8') - await nvim.command('edit') - await helper.wait(50) - await nvim.call('deletebufline', [doc.bufnr, 1]) - doc = await workspace.document - let content = doc.getDocumentContent() - expect(content).toBe('}\n') - }) - }) - - it('should synchronize after force edit', async () => { - await assertDocument(async doc => { - let fsPath = URI.parse(doc.uri).fsPath - fs.writeFileSync(fsPath, '{\n}\n', 'utf8') - await nvim.command('edit') - await helper.wait(50) - await nvim.call('deletebufline', [doc.bufnr, 1]) - doc = await workspace.document - let content = doc.getDocumentContent() - expect(content).toBe('}\n') - }) - }) -}) - -describe('getEndOffset', () => { - it('should getEndOffset #1', async () => { - let doc = await helper.createDocument() - await doc.buffer.setLines(['', ''], { start: 0, end: -1, strictIndexing: false }) - await helper.wait(30) - let end = doc.getEndOffset(1, 1, false) - expect(end).toBe(2) - end = doc.getEndOffset(2, 1, false) - expect(end).toBe(1) - }) - - it('should getEndOffset #2', async () => { - let doc = await helper.createDocument() - await doc.buffer.setLines(['a', ''], { start: 0, end: -1, strictIndexing: false }) - await helper.wait(30) - let end = doc.getEndOffset(1, 1, false) - expect(end).toBe(2) - }) - - it('should getEndOffset #3', async () => { - let doc = await helper.createDocument() - await doc.buffer.setLines(['a'], { start: 0, end: -1, strictIndexing: false }) - await helper.wait(30) - let end = doc.getEndOffset(1, 2, false) - expect(end).toBe(1) - }) - - it('should getEndOffset #4', async () => { - let doc = await helper.createDocument() - await doc.buffer.setLines(['ไฝ ๅฅฝ', ''], { start: 0, end: -1, strictIndexing: false }) - await helper.wait(30) - let end = doc.getEndOffset(1, 1, false) - expect(end).toBe(3) - end = doc.getEndOffset(1, 1, true) - expect(end).toBe(4) - }) -}) - -describe('applyEdits', () => { - it('should synchronize content added', async () => { - let doc = await helper.createDocument() - let buffer = doc.buffer - await doc.buffer.setLines(['foo f'], { start: 0, end: -1, strictIndexing: false }) - await doc.synchronize() - await nvim.command('normal! gg^2l') - await nvim.input('a') - await buffer.detach() - await nvim.input('r') - await doc.applyEdits([{ - range: Range.create(0, 0, 0, 5), - newText: 'foo foo' - }]) - await helper.wait(100) - let line = await nvim.line - expect(line).toBe('foor foo') - }) - - it('should synchronize content delete', async () => { - let doc = await helper.createDocument() - let buffer = doc.buffer - await doc.buffer.setLines(['foo f'], { start: 0, end: -1, strictIndexing: false }) - await doc.synchronize() - await nvim.command('normal! gg^2l') - await nvim.input('a') - await buffer.detach() - await nvim.input('') - await doc.applyEdits([{ - range: Range.create(0, 0, 0, 5), - newText: 'foo foo' - }]) - await helper.wait(100) - let line = await nvim.line - expect(line).toBe('fo foo') - }) -}) - -describe('highlights', () => { - it('should add highlights to document', async () => { - await helper.createDocument() - let buf = await nvim.buffer - await buf.setLines(['ไฝ ๅฅฝ', 'world'], { start: 0, end: -1, strictIndexing: false }) - let ranges = [ - Range.create(0, 0, 0, 2), - Range.create(1, 0, 1, 3) - ] - let ns = await nvim.createNamespace('coc-highlight') - nvim.pauseNotification() - buf.highlightRanges('highlight', 'Search', ranges) - await nvim.resumeNotification() - let markers = await helper.getMarkers(buf.id, ns) - expect(markers.length).toBe(2) - nvim.pauseNotification() - buf.clearNamespace('highlight') - await nvim.resumeNotification() - markers = await helper.getMarkers(buf.id, ns) - expect(markers.length).toBe(0) - }) - - it('should add/clear highlights of current window', async () => { - await helper.createDocument() - let buf = await nvim.buffer - await buf.setLines(['ไฝ ๅฅฝ', 'world'], { start: 0, end: -1, strictIndexing: false }) - let win = await nvim.window - let ranges = [ - Range.create(0, 0, 0, 2), - Range.create(1, 0, 1, 3) - ] - let res = await win.highlightRanges('Search', ranges) - expect(res.length).toBe(2) - let matches = await nvim.call('getmatches', [win.id]) - expect(matches.length).toBe(2) - nvim.pauseNotification() - win.clearMatchGroup('Search') - await nvim.resumeNotification() - matches = await nvim.call('getmatches', [win.id]) - expect(matches.length).toBe(0) - }) - - it('should clear matches by ids', async () => { - await helper.createDocument() - let buf = await nvim.buffer - await buf.setLines(['ไฝ ๅฅฝ', 'world'], { start: 0, end: -1, strictIndexing: false }) - let win = await nvim.window - let ranges = [ - Range.create(0, 0, 0, 2), - Range.create(1, 0, 1, 3) - ] - let ids = await win.highlightRanges('Search', ranges) - nvim.pauseNotification() - win.clearMatches(ids) - await nvim.resumeNotification() - let matches = await nvim.call('getmatches', [win.id]) - expect(matches.length).toBe(0) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/events.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/events.test.ts deleted file mode 100644 index 653f6e2a..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/events.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import events from '../../events' -import { disposeAll } from '../../util' -let disposables: Disposable[] = [] -import helper from '../helper' - -let nvim: Neovim - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - disposeAll(disposables) -}) - -describe('register handler', () => { - it('should register single handler', async () => { - let fn = jest.fn() - let obj = {} - let disposable = events.on('BufEnter', fn, obj) - disposables.push(disposable) - await events.fire('BufEnter', ['a', 'b']) - expect(fn).toBeCalledWith('a', 'b') - }) - - it('should register multiple events', async () => { - let fn = jest.fn() - let disposable = events.on(['TaskExit', 'TaskStderr'], fn) - disposables.push(disposable) - await events.fire('TaskExit', []) - await events.fire('TaskStderr', []) - expect(fn).toBeCalledTimes(2) - }) - - it('should resolve after timeout', async () => { - let fn = (): Promise => new Promise(resolve => { - setTimeout(() => { - resolve() - }, 100) - }) - let disposable = events.on('FocusGained', fn, {}) - disposables.push(disposable) - let ts = Date.now() - await events.fire('FocusGained', []) - expect(Date.now() - ts >= 100).toBe(true) - }) - - it('should emit TextInsert after TextChangedI', async () => { - let arr: string[] = [] - events.on('TextInsert', () => { - arr.push('insert') - }, null, disposables) - events.on('TextChangedI', () => { - arr.push('change') - }, null, disposables) - await nvim.input('ia') - await helper.wait(300) - expect(arr).toEqual(['change', 'insert']) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/extensions.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/extensions.test.ts deleted file mode 100644 index 2fd8260c..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/extensions.test.ts +++ /dev/null @@ -1,221 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import fs from 'fs' -import path from 'path' -import events from '../../events' -import extensions, { API, Extension } from '../../extensions' -import helper from '../helper' -import { v1 as uuidv1 } from 'uuid' - -let nvim: Neovim -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -jest.setTimeout(30000) - -describe('extensions', () => { - - it('should load global extensions', async () => { - let stat = extensions.getExtensionState('test') - expect(stat).toBe('activated') - }) - - it('should filter global extensions', async () => { - let res = extensions.filterGlobalExtensions(['test', 'foo']) - expect(res).toEqual(['foo']) - }) - - it('should load local extensions from &rtp', async () => { - let folder = path.resolve(__dirname, '../extensions/vim/local') - await nvim.command(`set runtimepath^=${folder}`) - await helper.wait(300) - let stat = extensions.getExtensionState('local') - expect(stat).toBe('activated') - }) - - it('should install/uninstall npm extension', async () => { - await extensions.installExtensions(['coc-omni']) - let folder = path.join(__dirname, '../extensions/coc-omni') - let exists = fs.existsSync(folder) - expect(exists).toBe(true) - await helper.wait(200) - await extensions.uninstallExtension(['coc-omni']) - exists = fs.existsSync(folder) - expect(exists).toBe(false) - }) - - it('should install/uninstall extension by url', async () => { - await extensions.installExtensions(['https://github.com/hollowtree/vscode-vue-snippets']) - let folder = path.join(__dirname, '../extensions/vue-snippets') - let exists = fs.existsSync(folder) - expect(exists).toBe(true) - await extensions.uninstallExtension(['vue-snippets']) - exists = fs.existsSync(folder) - expect(exists).toBe(false) - }) - - it('should install/uninstall extension by url with branch', async () => { - await extensions.installExtensions(['https://github.com/sdras/vue-vscode-snippets@main']) - let folder = path.join(__dirname, '../extensions/vue-vscode-snippets') - let exists = fs.existsSync(folder) - expect(exists).toBe(true) - await extensions.uninstallExtension(['vue-vscode-snippets']) - exists = fs.existsSync(folder) - expect(exists).toBe(false) - }) - - it('should parse extension info', () => { - const installer = extensions.installer - const scoped = installer('@yaegassy/coc-intelephense').info - expect(scoped.name).toBe('@yaegassy/coc-intelephense') - - const scopedVer = installer('@yaegassy/coc-intelephense@0.2.1').info - expect(scopedVer.name).toBe('@yaegassy/coc-intelephense') - expect(scopedVer.version).toBe('0.2.1') - }) - - it('should get all extensions', () => { - let list = extensions.all - expect(Array.isArray(list)).toBe(true) - }) - - it('should get extensions stat', async () => { - let stats = await extensions.getExtensionStates() - expect(stats.length).toBeGreaterThan(0) - }) - - it('should toggle extension', async () => { - await extensions.toggleExtension('test') - let stat = extensions.getExtensionState('test') - expect(stat).toBe('disabled') - await extensions.toggleExtension('test') - stat = extensions.getExtensionState('test') - expect(stat).toBe('activated') - }) - - it('should reload extension', async () => { - await extensions.reloadExtension('test') - await helper.wait(100) - let stat = extensions.getExtensionState('test') - expect(stat).toBe('activated') - }) - - it('should has extension', () => { - let res = extensions.has('test') - expect(res).toBe(true) - }) - - it('should be activated', async () => { - let res = extensions.has('test') - expect(res).toBe(true) - }) - - it('should activate & deactivate extension', async () => { - await extensions.deactivate('test') - let stat = extensions.getExtensionState('test') - expect(stat).toBe('loaded') - await extensions.activate('test') - stat = extensions.getExtensionState('test') - expect(stat).toBe('activated') - }) - - it('should call extension API', async () => { - let res = await extensions.call('test', 'echo', ['5']) - expect(res).toBe('5') - let p: string = await extensions.call('test', 'asAbsolutePath', ['..']) - expect(p.endsWith('extensions')).toBe(true) - }) - - it('should get extension API', () => { - let res = extensions.getExtensionApi('test') as any - expect(typeof res.echo).toBe('function') - }) - - it('should load single file extension', async () => { - let filepath = path.join(__dirname, '../extensions/root.js') - await extensions.loadExtensionFile(filepath) - expect(extensions.has('single-root')).toBe(true) - }) -}) - -describe('extensions active events', () => { - - function createExtension(event: string): Extension { - let id = uuidv1() - let isActive = false - let packageJSON = { - name: id, - activationEvents: [event] - } - let ext = { - id, - packageJSON, - exports: void 0, - extensionPath: '', - activate: async () => { - isActive = true - } - } as any - Object.defineProperty(ext, 'isActive', { - get: () => isActive - }) - extensions.registerExtension(ext, () => { - isActive = false - }) - return ext - } - - it('should activate on language', async () => { - let ext = createExtension('onLanguage:javascript') - expect(ext.isActive).toBe(false) - await nvim.command('edit /tmp/a.js') - await helper.wait(300) - expect(ext.isActive).toBe(true) - ext = createExtension('onLanguage:javascript') - expect(ext.isActive).toBe(true) - }) - - it('should activate on command', async () => { - let ext = createExtension('onCommand:test.echo') - await events.fire('Command', ['test.echo']) - await helper.wait(30) - expect(ext.isActive).toBe(true) - }) - - it('should activate on workspace contains', async () => { - let ext = createExtension('workspaceContains:package.json') - let root = path.resolve(__dirname, '../../..') - await nvim.command(`edit ${path.join(root, 'file.js')}`) - await helper.wait(100) - expect(ext.isActive).toBe(true) - }) - - it('should activate on file system', async () => { - let ext = createExtension('onFileSystem:zip') - await nvim.command('edit zip:///a') - await helper.wait(30) - expect(ext.isActive).toBe(true) - ext = createExtension('onFileSystem:zip') - expect(ext.isActive).toBe(true) - }) -}) - -describe('extension properties', () => { - it('should get extensionPath', () => { - let ext = extensions.getExtension('test') - let p = ext.extension.extensionPath - expect(p.endsWith('test')).toBe(true) - }) - - it('should deactivate', async () => { - let ext = extensions.getExtension('test') - await ext.deactivate() - expect(ext.extension.isActive).toBe(false) - await extensions.activate('test') - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/fetch.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/fetch.test.ts deleted file mode 100644 index 7a66a9f9..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/fetch.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import fs from 'fs-extra' -import os from 'os' -import path from 'path' -import { parse } from 'url' -import download from '../../model/download' -import fetch, { getAgent } from '../../model/fetch' -import helper from '../helper' - -beforeAll(async () => { - await helper.setup() -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - helper.updateConfiguration('http.proxy', '') - await helper.reset() -}) - -describe('fetch', () => { - - it('should fetch json', async () => { - let res = await fetch('https://nodejs.org/dist/index.json') - expect(Array.isArray(res)).toBe(true) - }, 10000) - - it('should fetch buffer', async () => { - let res = await fetch('https://www.npmjs.com/', { buffer: true }) - expect(Buffer.isBuffer(res)).toBe(true) - }) - - it('should throw on request error', async () => { - let err - try { - await fetch('http://not_exists_org') - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should report valid proxy', async () => { - let agent = getAgent(parse('http://google.com'), { proxyUrl: 'domain.com:1234' }) - expect(agent).toBe(null) - - agent = getAgent(parse('http://google.com'), { proxyUrl: 'https://domain.com:1234' }) - let proxy = (agent as any).proxy - expect(proxy.host).toBe('domain.com') - expect(proxy.port).toBe(1234) - - agent = getAgent(parse('http://google.com'), { proxyUrl: 'http://user:pass@domain.com:1234' }) - proxy = (agent as any).proxy - expect(proxy.host).toBe('domain.com') - expect(proxy.port).toBe(1234) - expect(proxy.auth).toBe('user:pass') - }) -}) - -describe('download', () => { - it('should download binary file', async () => { - let url = 'https://registry.npmjs.org/coc-pairs/-/coc-pairs-1.2.13.tgz' - let tmpFolder = await fs.mkdtemp(path.join(os.tmpdir(), 'coc-test')) - let res = await download(url, { dest: tmpFolder }) - expect(fs.existsSync(res)).toBe(true) - await fs.remove(tmpFolder) - }, 10000) - - it('should download tgz', async () => { - let url = 'https://registry.npmjs.org/coc-pairs/-/coc-pairs-1.2.13.tgz' - let tmpFolder = await fs.mkdtemp(path.join(os.tmpdir(), 'coc-test')) - await download(url, { dest: tmpFolder, extract: 'untar' }) - let file = path.join(tmpFolder, 'package.json') - expect(fs.existsSync(file)).toBe(true) - await fs.remove(tmpFolder) - }, 10000) - - it('should extract zip file', async () => { - let url = 'https://codeload.github.com/chemzqm/vimrc/zip/master' - let tmpFolder = await fs.mkdtemp(path.join(os.tmpdir(), 'coc-test')) - await download(url, { dest: tmpFolder, extract: 'unzip' }) - let folder = path.join(tmpFolder, 'vimrc-master') - expect(fs.existsSync(folder)).toBe(true) - await fs.remove(tmpFolder) - }, 30000) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/floatFactory.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/floatFactory.test.ts deleted file mode 100644 index c978c135..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/floatFactory.test.ts +++ /dev/null @@ -1,276 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import FloatFactory from '../../model/floatFactory' -import snippetManager from '../../snippets/manager' -import { Documentation } from '../../markdown/index' -import helper from '../helper' - -let nvim: Neovim -let floatFactory: FloatFactory -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - floatFactory = new FloatFactory(nvim) -}) - -afterAll(async () => { - await helper.shutdown() - floatFactory.dispose() -}) - -afterEach(async () => { - floatFactory.close() - await helper.reset() -}) - -describe('FloatFactory', () => { - describe('show()', () => { - it('should show window', async () => { - expect(floatFactory.window).toBe(null) - expect(floatFactory.buffer).toBe(null) - expect(floatFactory.bufnr).toBe(0) - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'f'.repeat(81) - }] - await floatFactory.show(docs) - expect(floatFactory.window).toBeDefined() - expect(floatFactory.buffer).toBeDefined() - let hasFloat = await nvim.call('coc#float#has_float') - expect(hasFloat).toBe(1) - await floatFactory.show([{ filetype: 'txt', content: '' }]) - expect(floatFactory.window).toBe(null) - }) - - it('should create window', async () => { - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'f'.repeat(81) - }] - await floatFactory.create(docs) - expect(floatFactory.window).toBeDefined() - }) - - it('should catch error on create', async () => { - let fn = floatFactory.unbind - floatFactory.unbind = () => { - throw new Error('bad') - } - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'f'.repeat(81) - }] - await floatFactory.show(docs) - floatFactory.unbind = fn - let msg = await helper.getCmdline() - expect(msg).toMatch('bad') - }) - - it('should show only one window', async () => { - await helper.edit() - await nvim.setLine('foo') - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'foo' - }] - await Promise.all([ - floatFactory.show(docs), - floatFactory.show(docs) - ]) - let count = 0 - let wins = await nvim.windows - for (let win of wins) { - let isFloat = await win.getVar('float') - if (isFloat) count++ - } - expect(count).toBe(1) - }) - - it('should close window when close called after create', async () => { - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'f' - }] - let p = floatFactory.show(docs) - await helper.wait(1) - floatFactory.close() - await p - let activated = await floatFactory.activated() - expect(activated).toBe(false) - }) - - it('should not create on visual mode', async () => { - await helper.createDocument() - await nvim.call('cursor', [1, 1]) - await nvim.setLine('foo') - await nvim.command('normal! v$') - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'f' - }] - await floatFactory.show(docs) - expect(floatFactory.window).toBe(null) - }) - }) - - describe('checkRetrigger', () => { - it('should check retrigger', async () => { - expect(floatFactory.checkRetrigger(99)).toBe(false) - let bufnr = await nvim.call('bufnr', ['%']) - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'f' - }] - await floatFactory.show(docs) - expect(floatFactory.checkRetrigger(99)).toBe(false) - expect(floatFactory.checkRetrigger(bufnr)).toBe(true) - }) - }) - - describe('options', () => { - it('should config maxHeight and maxWidth', async () => { - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'f'.repeat(80) + '\nbar', - }] - await floatFactory.show(docs, { - maxWidth: 20, - maxHeight: 1 - }) - let win = floatFactory.window - expect(win).toBeDefined() - let width = await win.width - let height = await win.height - expect(width).toBe(19) - expect(height).toBe(1) - }) - - it('should set border, title, highlight, borderhighlight, cursorline', async () => { - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'foo\nbar' - }] - await floatFactory.show(docs, { - border: [1, 1, 1, 1], - title: 'title', - highlight: 'Pmenu', - borderhighlight: 'MoreMsg', - cursorline: true - }) - let activated = await floatFactory.activated() - expect(activated).toBe(true) - }) - - it('should respect prefer top', async () => { - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'foo\nbar' - }] - await nvim.call('append', [1, ['', '', '']]) - await nvim.command('exe 4') - await floatFactory.show(docs, { preferTop: true }) - let win = await helper.getFloat() - expect(win).toBeDefined() - let pos = await nvim.call('nvim_win_get_position', [win.id]) - expect(pos).toEqual([1, 0]) - }) - }) - - describe('events', () => { - it('should hide on BufEnter', async () => { - await helper.edit() - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'foo' - }] - await floatFactory.show(docs) - await nvim.command(`edit foo`) - await helper.wait(50) - let hasFloat = await nvim.call('coc#float#has_float') - expect(hasFloat).toBe(0) - }) - - it('should hide on CursorMoved', async () => { - await helper.createDocument() - await nvim.setLine('foo') - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'foo' - }] - await floatFactory.show(docs) - let hasFloat = await nvim.call('coc#float#has_float') - expect(hasFloat).toBe(1) - await helper.wait(30) - await nvim.input('$') - await helper.wait(200) - hasFloat = await nvim.call('coc#float#has_float') - expect(hasFloat).toBe(0) - }) - - it('should not hide when cursor position not changed', async () => { - await helper.edit() - await nvim.setLine('foo') - let cursor = await nvim.eval("[line('.'), col('.')]") - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'foo' - }] - await floatFactory.show(docs) - await nvim.call('cursor', [1, 2]) - await helper.wait(10) - await nvim.call('cursor', cursor) - await helper.wait(200) - let hasFloat = await nvim.call('coc#float#has_float') - expect(hasFloat).toBe(1) - }) - - it('should preserve float when autohide disable and not overlap with pum', async () => { - await helper.createDocument() - let buf = await nvim.buffer - await buf.setLines(['foo', '', '', '', 'f'], { start: 0, end: -1, strictIndexing: false }) - await nvim.call('cursor', [5, 2]) - await nvim.input('A') - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'foo' - }] - await floatFactory.show(docs, { - preferTop: true, - autoHide: false - }) - let activated = await floatFactory.activated() - expect(activated).toBe(true) - await nvim.input('') - await helper.wait(100) - let pumvisible = await helper.pumvisible() - expect(pumvisible).toBe(true) - activated = await floatFactory.activated() - expect(activated).toBe(true) - }) - }) - - it('should allow select mode', async () => { - await helper.createDocument() - await snippetManager.insertSnippet('${1:foo}') - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'foo' - }] - await floatFactory.show(docs) - let { mode } = await nvim.mode - expect(mode).toBe('s') - }) - - it('should get active state of window', async () => { - let docs: Documentation[] = [{ - filetype: 'markdown', - content: 'f'.repeat(81) - }] - await floatFactory.show(docs) - let res = await floatFactory.activated() - expect(res).toBe(true) - await nvim.call('coc#float#close_all') - res = await floatFactory.activated() - expect(res).toBe(false) - }) - -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/memos.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/memos.test.ts deleted file mode 100644 index 76af1232..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/memos.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import Memos from '../../model/memos' -import os from 'os' -import path from 'path' -import fs from 'fs' - -let filepath = path.join(os.tmpdir(), 'test') -let memos: Memos -beforeEach(() => { - memos = new Memos(filepath) -}) - -afterEach(() => { - if (fs.existsSync(filepath)) { - fs.unlinkSync(filepath) - } -}) - -describe('Memos', () => { - it('should udpate and get', async () => { - let memo = memos.createMemento('x') - await memo.update('foo.bar', 'memo') - let res = memo.get('foo.bar') - expect(res).toBe('memo') - }) - - it('should get value for key not exists', async () => { - let memo = memos.createMemento('y') - let res = memo.get('xyz') - expect(res).toBeUndefined() - }) - - it('should use defaultValue when not exists', async () => { - let memo = memos.createMemento('y') - let res = memo.get('f.o.o', 'default') - expect(res).toBe('default') - }) - - it('should update multiple values', async () => { - let memo = memos.createMemento('x') - await memo.update('foo', 'x') - await memo.update('bar', 'y') - expect(memo.get('foo')).toBe('x') - expect(memo.get('bar')).toBe('y') - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/menu.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/menu.test.ts deleted file mode 100644 index 015a3bce..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/menu.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import helper from '../helper' -import Menu from '../../model/menu' - -let nvim: Neovim -let menu: Menu - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - menu.dispose() - await helper.reset() -}) - -describe('Menu', () => { - it('should cancel by ', async () => { - menu = new Menu(nvim, { items: ['foo', 'bar'] }) - let p = new Promise(resolve => { - menu.onDidClose(v => { - resolve(v) - }) - }) - await menu.show() - await helper.wait(30) - await nvim.input('') - let res = await p - expect(res).toBe(-1) - }) - - it('should select by CR', async () => { - menu = new Menu(nvim, { items: ['foo', 'bar'] }) - let p = new Promise(resolve => { - menu.onDidClose(v => { - resolve(v) - }) - }) - await menu.show() - await helper.wait(30) - await nvim.input('j') - await helper.wait(30) - await nvim.input('') - let res = await p - expect(res).toBe(1) - }) - - it('should ignore invalid index', async () => { - menu = new Menu(nvim, { items: ['foo', 'bar'] }) - await menu.show() - await helper.wait(30) - await nvim.input('0') - await helper.wait(30) - let exists = await nvim.call('coc#float#has_float', []) - expect(exists).toBe(1) - }) - - it('should select by index number', async () => { - menu = new Menu(nvim, { items: ['foo', 'bar'] }) - let p = new Promise(resolve => { - menu.onDidClose(v => { - resolve(v) - }) - }) - await menu.show() - await helper.wait(30) - await nvim.input('1') - let res = await p - expect(res).toBe(0) - }) - - it('should navigate by j, k, g & G', async () => { - menu = new Menu(nvim, { items: ['one', 'two', 'three'] }) - await menu.show() - await helper.wait(50) - let id = await nvim.call('coc#float#get_float_win') - expect(id).toBeGreaterThan(0) - let win = nvim.createWindow(id) - await nvim.input('j') - await helper.wait(50) - let cursor = await win.cursor - expect(cursor[0]).toBe(2) - await nvim.input('k') - await helper.wait(50) - cursor = await win.cursor - expect(cursor[0]).toBe(1) - await nvim.input('G') - await helper.wait(50) - cursor = await win.cursor - expect(cursor[0]).toBe(3) - await nvim.input('g') - await helper.wait(50) - cursor = await win.cursor - expect(cursor[0]).toBe(1) - }) - - it('should select by numbers', async () => { - let selected: number - menu = new Menu(nvim, { items: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] }) - await menu.show() - let promise = new Promise(resolve => { - menu.onDidClose(n => { - selected = n - resolve(undefined) - }) - }) - await helper.wait(50) - await nvim.input('1') - await helper.wait(50) - await nvim.input('0') - await promise - expect(selected).toBe(9) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/mru.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/mru.test.ts deleted file mode 100644 index 4447c79b..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/mru.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import Mru from '../../model/mru' -import os from 'os' -import fs from 'fs' -import path from 'path' -const root = fs.mkdtempSync(path.join(os.tmpdir(), 'coc-mru-')) - -describe('Mru', () => { - - it('should load items', async () => { - let mru = new Mru('test', root) - await mru.clean() - let res = await mru.load() - expect(res.length).toBe(0) - }) - - it('should add items', async () => { - let mru = new Mru('test', root) - await mru.add('a') - await mru.add('b') - let res = await mru.load() - expect(res.length).toBe(2) - await mru.clean() - }) - - it('should remove item', async () => { - let mru = new Mru('test', root) - await mru.add('a') - await mru.remove('a') - let res = await mru.load() - expect(res.length).toBe(0) - await mru.clean() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/outputChannel.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/outputChannel.test.ts deleted file mode 100644 index f41ae1c0..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/outputChannel.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import OutputChannel from '../../model/outputChannel' -import { wait } from '../../util' -import helper from '../helper' - -let nvim: Neovim -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterEach(async () => { - await helper.reset() -}) - -afterAll(async () => { - await helper.shutdown() -}) - -describe('OutputChannel', () => { - test('outputChannel.show(true)', async () => { - await nvim.setLine('foo') - let c = new OutputChannel('0', nvim) - let bufnr = (await nvim.buffer).id - c.show(true) - await wait(100) - let nr = (await nvim.buffer).id - expect(bufnr).toBe(nr) - }) - - test('outputChannel.show(false)', async () => { - let c = new OutputChannel('1', nvim) - let bufnr = (await nvim.buffer).id - c.show() - await wait(100) - let nr = (await nvim.buffer).id - expect(bufnr).toBeLessThan(nr) - }) - - test('outputChannel.appendLine()', async () => { - let c = new OutputChannel('2', nvim) - c.show() - await wait(100) - let buf = await nvim.buffer - c.appendLine('foo') - await wait(500) - let lines = await buf.lines - expect(lines).toContain('foo') - }) - - test('outputChannel.append()', async () => { - let c = new OutputChannel('3', nvim) - c.show(false) - await wait(60) - c.append('foo') - c.append('bar') - await wait(500) - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines.join('\n')).toMatch('foo') - }) - - test('outputChannel.clear()', async () => { - let c = new OutputChannel('4', nvim) - c.show(false) - await wait(30) - let buf = await nvim.buffer - c.appendLine('foo') - c.appendLine('bar') - await wait(30) - c.clear() - await wait(30) - let lines = await buf.lines - let content = lines.join('') - expect(content).toBe('') - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/picker.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/picker.test.ts deleted file mode 100644 index 469f75df..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/picker.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { CancellationTokenSource } from 'vscode-languageserver-protocol' -import { Neovim } from '@chemzqm/neovim' -import Picker, { QuickPickItem } from '../../model/picker' -import helper from '../helper' - -let nvim: Neovim -let picker: Picker - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - if (picker) picker.dispose() - picker = undefined - await helper.reset() -}) - -const items: QuickPickItem[] = [{ label: 'foo' }, { label: 'bar' }] - -describe('Picker create', () => { - it('should show dialog with buttons', async () => { - picker = new Picker(nvim, { title: 'title', items }) - let winid = await picker.show({ pickerButtons: true }) - expect(winid).toBeDefined() - let id = await nvim.call('coc#float#get_related', [winid, 'buttons']) - expect(id).toBeGreaterThan(0) - let res = await nvim.call('sign_getplaced', [picker.buffer.id, { lnum: 1 }]) - expect(res[0].signs).toBeDefined() - expect(res[0].signs[0].name).toBe('CocCurrentLine') - }) - - it('should cancel dialog when cancellation token requested', async () => { - let tokenSource = new CancellationTokenSource() - picker = new Picker(nvim, { title: 'title', items }, tokenSource.token) - let winid = await picker.show({ pickerButtons: true }) - expect(winid).toBeDefined() - tokenSource.cancel() - await helper.wait(50) - let res = await nvim.call('coc#float#valid', [winid]) - expect(res).toBe(0) - }) -}) - -describe('Picker key mappings', () => { - it('should toggle selection mouse click bracket', async () => { - picker = new Picker(nvim, { title: 'title', items }) - let winid = await picker.show() - await nvim.setVar('mouse_position', [winid, 1, 1]) - await nvim.input('') - await helper.wait(50) - let buf = picker.buffer - let lines = await buf.getLines({ start: 0, end: 1, strictIndexing: false }) - expect(lines[0]).toMatch(/^\[x\]/) - }) - - it('should change current line on mouse click label', async () => { - picker = new Picker(nvim, { title: 'title', items }) - let winid = await picker.show() - await nvim.setVar('mouse_position', [winid, 2, 4]) - await nvim.input('') - await helper.wait(50) - let buf = picker.buffer - let res = await nvim.call('sign_getplaced', [buf.id, { lnum: 2 }]) - expect(res[0].signs).toBeDefined() - expect(res[0].signs[0].name).toBe('CocCurrentLine') - }) - - it('should cancel by ', async () => { - await helper.createDocument() - picker = new Picker(nvim, { title: 'title', items }) - let winid = await picker.show({ pickerButtons: true }) - expect(winid).toBeDefined() - let fn = jest.fn() - picker.onDidClose(fn) - await nvim.eval(`feedkeys("\\", 'in')`) - await helper.wait(200) - expect(fn).toBeCalledTimes(1) - }) - - it('should confirm by ', async () => { - await helper.createDocument() - picker = new Picker(nvim, { title: 'title', items }) - let winid = await picker.show({ pickerButtons: true }) - expect(winid).toBeDefined() - let fn = jest.fn() - picker.onDidClose(fn) - await nvim.input('') - await helper.wait(100) - await nvim.input('') - await nvim.command('redraw') - await helper.wait(100) - expect(fn).toBeCalledWith([0]) - }) - - it('should move cursor by j, k, g & G', async () => { - await helper.createDocument() - picker = new Picker(nvim, { title: 'title', items }) - let winid = await picker.show({ pickerButtons: true }) - expect(winid).toBeDefined() - await nvim.input('j') - await helper.wait(100) - let res = await nvim.call('sign_getplaced', [picker.buffer.id]) - expect(res[0].signs[0].lnum).toBe(2) - await nvim.input('k') - await helper.wait(100) - res = await nvim.call('sign_getplaced', [picker.buffer.id]) - expect(res[0].signs[0].lnum).toBe(1) - await nvim.input('G') - await helper.wait(100) - res = await nvim.call('sign_getplaced', [picker.buffer.id]) - expect(res[0].signs[0].lnum).toBe(2) - await nvim.input('g') - await helper.wait(100) - res = await nvim.call('sign_getplaced', [picker.buffer.id]) - expect(res[0].signs[0].lnum).toBe(1) - }) - - it('should toggle selection by ', async () => { - await helper.createDocument() - picker = new Picker(nvim, { title: 'title', items }) - let winid = await picker.show({ pickerButtons: true }) - expect(winid).toBeDefined() - let fn = jest.fn() - picker.onDidClose(fn) - await nvim.input('') - await helper.wait(100) - await nvim.command('redraw') - let lines = await nvim.call('getbufline', [picker.buffer.id, 1]) - expect(lines[0]).toMatch('[x]') - }) - - it('should scroll forward & backward', async () => { - await helper.createDocument() - let items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'].map(s => { - return { label: s } - }) - picker = new Picker(nvim, { title: 'title', items }) - let winid = await picker.show({ maxHeight: 3 }) - expect(winid).toBeDefined() - await nvim.input('') - await helper.wait(100) - let info = await nvim.call('getwininfo', [winid]) - expect(info[0]).toBeDefined() - expect(info[0].topline).toBeGreaterThan(1) - await nvim.input('') - await helper.wait(100) - info = await nvim.call('getwininfo', [winid]) - expect(info[0]).toBeDefined() - expect(info[0].topline).toBe(1) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/plugin.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/plugin.test.ts deleted file mode 100644 index 30fec85e..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/plugin.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import helper from '../helper' -import path from 'path' -import workspace from '../../workspace' -import { Neovim } from '@chemzqm/neovim' - -let nvim: Neovim - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('help tags', () => { - it('should generate help tags', async () => { - let root = workspace.pluginRoot - let dir = await nvim.call('fnameescape', path.join(root, 'doc')) - let res = await nvim.call('execute', `helptags ${dir}`) as string - expect(res.length).toBe(0) - }) - - it('should return jumpable', async () => { - let jumpable = await helper.plugin.cocAction('snippetCheck', false, true) - expect(jumpable).toBe(false) - }) - - it('should show CocInfo', async () => { - await nvim.call('CocActionAsync', ['showInfo']) - await helper.wait(300) - let line = await nvim.line - expect(line).toMatch('versions') - }) - - it('should ensure current document created', async () => { - await nvim.command('tabe tmp.js') - let res = await helper.plugin.cocAction('ensureDocument') - expect(res).toBe(true) - let bufnr = await nvim.call('bufnr', ['%']) - let doc = workspace.getDocument(bufnr) - expect(doc).toBeDefined() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/position.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/position.test.ts deleted file mode 100644 index 38d041e4..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/position.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { rangeInRange, positionInRange, comparePosition, isSingleLine, getChangedPosition, rangeOverlap } from '../../util/position' -import { Position, Range, TextEdit } from 'vscode-languageserver-types' - -function addPosition(position: Position, line: number, character: number): Position { - return Position.create(position.line + line, position.character + character) -} - -describe('Position', () => { - test('rangeInRange', () => { - let pos = Position.create(0, 0) - let r = Range.create(pos, pos) - expect(rangeInRange(r, r)).toBe(true) - expect(rangeInRange(r, Range.create(addPosition(pos, 1, 0), pos))).toBe(false) - }) - - test('rangeOverlap', () => { - let r = Range.create(0, 0, 0, 0) - expect(rangeOverlap(r, Range.create(0, 0, 0, 0))).toBe(false) - expect(rangeOverlap(Range.create(0, 0, 0, 10), Range.create(0, 1, 0, 2))).toBe(true) - expect(rangeOverlap(Range.create(0, 0, 0, 1), Range.create(0, 1, 0, 2))).toBe(false) - expect(rangeOverlap(Range.create(0, 1, 0, 2), Range.create(0, 0, 0, 1))).toBe(false) - expect(rangeOverlap(Range.create(0, 0, 0, 1), Range.create(0, 2, 0, 3))).toBe(false) - }) - - test('positionInRange', () => { - let pos = Position.create(0, 0) - let r = Range.create(pos, pos) - expect(positionInRange(pos, r)).toBe(0) - }) - - test('comparePosition', () => { - let pos = Position.create(0, 0) - expect(comparePosition(pos, pos)).toBe(0) - }) - - test('isSingleLine', () => { - let pos = Position.create(0, 0) - let r = Range.create(pos, pos) - expect(isSingleLine(r)).toBe(true) - }) - - test('getChangedPosition #1', () => { - let pos = Position.create(0, 0) - let edit = TextEdit.insert(pos, 'abc') - let res = getChangedPosition(pos, edit) - expect(res).toEqual({ line: 0, character: 3 }) - }) - - test('getChangedPosition #2', () => { - let pos = Position.create(0, 0) - let edit = TextEdit.insert(pos, 'a\nb\nc') - let res = getChangedPosition(pos, edit) - expect(res).toEqual({ line: 2, character: 1 }) - }) - - test('getChangedPosition #3', () => { - let pos = Position.create(0, 1) - let r = Range.create(addPosition(pos, 0, -1), pos) - let edit = TextEdit.replace(r, 'a\nb\n') - let res = getChangedPosition(pos, edit) - expect(res).toEqual({ line: 2, character: -1 }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/score.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/score.test.ts deleted file mode 100644 index e49c8b28..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/score.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { getMatchResult } from '../../util/score' - -describe('match result', () => { - - it('should respect filename #1', () => { - let res = getMatchResult('/coc.nvim/coc.txt', 'coc', 'coc.txt') - expect(res).toEqual({ score: 4, matches: [10, 11, 12] }) - }) - - it('should respect filename #2', () => { - let res = getMatchResult('/coc.nvim/Coc.txt', 'coc', 'Coc.txt') - expect(res).toEqual({ score: 3.5, matches: [10, 11, 12] }) - }) - - it('should respect filename #3', () => { - let res = getMatchResult('/coc.nvim/cdoxc.txt', 'coc', 'cdoxc.txt') - expect(res).toEqual({ score: 3, matches: [10, 12, 14] }) - }) - - it('should respect path start', () => { - let res = getMatchResult('/foob/baxr/xyz', 'fbx') - expect(res).toEqual({ score: 3, matches: [1, 6, 11] }) - }) - - it('should find fuzzy result', () => { - let res = getMatchResult('foobarzyx', 'fbx') - expect(res).toEqual({ score: 2, matches: [0, 3, 8] }) - }) - - it('should find fuzzy result #1', () => { - let res = getMatchResult('LICENSES/preferred/MIT', 'lsit') - expect(res).toEqual({ score: 1.4, matches: [0, 5, 20, 21] }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/settings.json b/vim-config/plugins/coc.nvim/src/__tests__/modules/settings.json deleted file mode 100644 index 55bb35f8..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/settings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "foo.bar": 1, - "bar.foo": 2, - "schema": { - "https://example.com": "*.yaml" - }, - "servers": { - "c": { - "trace.server": "verbose" - } - } -} \ No newline at end of file diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/sources.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/sources.test.ts deleted file mode 100644 index ccb6dfe6..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/sources.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import path from 'path' -import events from '../../events' -import workspace from '../../workspace' -import sources from '../../sources' -import { ISource, SourceType } from '../../types' -import helper from '../helper' - -let nvim: Neovim -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('sources', () => { - - it('should do document enter', async () => { - let fn = jest.fn() - let source: ISource = { - name: 'enter', - enable: true, - priority: 0, - sourceType: SourceType.Service, - triggerCharacters: [], - doComplete: () => Promise.resolve({ items: [] }), - onEnter: fn - } - sources.addSource(source) - let buffer = await nvim.buffer - await events.fire('BufEnter', [buffer.id]) - expect(fn).toBeCalled() - sources.removeSource(source) - }) - - it('should return source states', () => { - let stats = sources.sourceStats() - expect(stats.length > 1).toBe(true) - }) - - it('should toggle source state', () => { - sources.toggleSource('around') - let s = sources.getSource('around') - expect(s.enable).toBe(false) - sources.toggleSource('around') - }) - - it('should disable source by coc_sources_disable_map', async () => { - await nvim.command('let g:coc_sources_disable_map = {"python": ["around", "buffer"]}') - let res = sources.getNormalSources('python', 'file:///t.py') - await nvim.command('let g:coc_sources_disable_map = {}') - expect(res.find(o => o.name == 'around')).toBeUndefined() - expect(res.find(o => o.name == 'buffer')).toBeUndefined() - }) -}) - -describe('sources#has', () => { - - it('should has source', () => { - expect(sources.has('around')).toBe(true) - }) - - it('should not has source', () => { - expect(sources.has('NotExists')).toBe(false) - }) -}) - -describe('sources#refresh', () => { - it('should refresh if possible', async () => { - let fn = jest.fn() - let source: ISource = { - name: 'refresh', - enable: true, - priority: 0, - sourceType: SourceType.Service, - triggerCharacters: [], - doComplete: () => Promise.resolve({ items: [] }), - refresh: fn - } - sources.addSource(source) - await sources.refresh('refresh') - expect(fn).toBeCalled() - sources.removeSource(source) - }) - - it('should work if refresh not defined', async () => { - let source: ISource = { - name: 'refresh', - enable: true, - priority: 0, - sourceType: SourceType.Service, - triggerCharacters: [], - doComplete: () => Promise.resolve({ items: [] }) - } - sources.addSource(source) - await sources.refresh('refresh') - sources.removeSource(source) - }) -}) - -describe('sources#createSource', () => { - it('should create source', async () => { - let disposable = sources.createSource({ - name: 'custom', - doComplete: () => Promise.resolve({ - items: [{ - word: 'custom' - }] - }) - }) - await helper.createDocument() - await nvim.input('i') - await helper.wait(30) - await nvim.input('c') - let visible = await helper.visible('custom', 'custom') - expect(visible).toBe(true) - disposable.dispose() - }) - - it('should create vim source', async () => { - let folder = path.resolve(__dirname, '..') - await nvim.command(`set runtimepath+=${folder}`) - await helper.wait(100) - let exists = sources.has('email') - expect(exists).toBe(true) - await helper.createDocument() - await nvim.input('i') - await helper.wait(10) - await nvim.input('@') - await helper.visible('foo@gmail.com') - }) -}) - -describe('sources#getTriggerSources()', () => { - it('should filter by filetypes', async () => { - let source: ISource = { - name: 'test', - enable: true, - priority: 0, - filetypes: ['javascript'], - sourceType: SourceType.Service, - triggerCharacters: ['#'], - doComplete: () => Promise.resolve({ items: [] }) - } - let disposable = sources.addSource(source) - let res = sources.getTriggerSources('#', 'javascript', 'file:///tmp.js') - expect(res.find(o => o.name == 'test')).toBeDefined() - disposable.dispose() - }) - - it('should filter by documentSelector', async () => { - let source: ISource = { - name: 'test', - enable: true, - priority: 0, - documentSelector: [{ language: 'javascript' }], - sourceType: SourceType.Service, - triggerCharacters: ['#'], - doComplete: () => Promise.resolve({ items: [] }) - } - let disposable = sources.addSource(source) - let res = sources.getTriggerSources('#', 'javascript', 'file:///tmp.js') - expect(res.find(o => o.name == 'test')).toBeDefined() - disposable.dispose() - }) - - it('should filter by disabledSources', async () => { - workspace.env.disabledSources = { - javascript: ['test'] - } - let source: ISource = { - name: 'test', - enable: true, - priority: 0, - documentSelector: [{ language: 'javascript' }], - sourceType: SourceType.Service, - triggerCharacters: ['#'], - doComplete: () => Promise.resolve({ items: [] }) - } - let disposable = sources.addSource(source) - let res = sources.getTriggerSources('#', 'javascript', 'file:///tmp.js') - expect(res.find(o => o.name == 'test')).toBeUndefined() - disposable.dispose() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/task.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/task.test.ts deleted file mode 100644 index bd90ebed..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/task.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import helper, { createTmpFile } from '../helper' -import workspace from '../../workspace' - -let nvim: Neovim -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -describe('task test', () => { - it('should start task', async () => { - let task = workspace.createTask('sleep') - let started = await task.start({ cmd: 'sleep', args: ['50'] }) - expect(started).toBe(true) - task.dispose() - }) - - it('should stop task', async () => { - let task = workspace.createTask('sleep') - await task.start({ cmd: 'sleep', args: ['50'] }) - await helper.wait(10) - await task.stop() - let running = await task.running - expect(running).toBe(false) - task.dispose() - }) - - it('should emit exit event', async () => { - let fn = jest.fn() - let task = workspace.createTask('sleep') - task.onExit(fn) - await task.start({ cmd: 'sleep', args: ['50'] }) - await helper.wait(10) - await task.stop() - task.dispose() - expect(fn).toBeCalled() - }) - - it('should emit stdout event', async () => { - let file = await createTmpFile('echo foo') - let fn = jest.fn() - let task = workspace.createTask('echo') - let called = false - task.onStdout(lines => { - if (!called) expect(lines).toEqual(['foo']) - called = true - fn() - }) - await task.start({ cmd: '/bin/sh', args: [file] }) - await helper.wait(300) - task.dispose() - expect(fn).toBeCalled() - }) - - it('should change environment variables', async () => { - let file = await createTmpFile('echo $NODE_ENV\necho $COC_NVIM_TEST\nsleep 1') - let task = workspace.createTask('ENV') - let lines: string[] = [] - task.onStdout(arr => { - lines.push(...arr) - }) - await task.start({ - cmd: '/bin/sh', - args: [file], - env: { - NODE_ENV: 'production', - COC_NVIM_TEST: 'yes' - } - }) - await helper.wait(300) - expect(lines).toEqual(['production', 'yes']) - let res = await nvim.call('getenv', 'COC_NVIM_TEST') - expect(res).toBeNull() - task.dispose() - }) - - it('should receive stdout lines as expected', async () => { - let file = await createTmpFile('echo 3\necho ""\necho 4') - let task = workspace.createTask('ENV') - let lines: string[] = [] - task.onStdout(arr => { - lines.push(...arr) - }) - await task.start({ - cmd: '/bin/sh', - args: [file] - }) - await helper.wait(300) - expect(lines).toEqual(['3', '', '4']) - task.dispose() - }) - - it('should emit stderr event', async () => { - let file = await createTmpFile('console.error("start\\n\\nend");') - let fn = jest.fn() - let task = workspace.createTask('error') - let lines: string[] = [] - task.onStderr(arr => { - lines.push(...arr) - fn() - }) - await task.start({ cmd: 'node', args: [file] }) - await helper.wait(300) - expect(lines).toEqual(['start', '', 'end']) - task.dispose() - expect(fn).toBeCalled() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/terminal.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/terminal.test.ts deleted file mode 100644 index 9597c8b9..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/terminal.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import helper from '../helper' -import TerminalModel from '../../model/terminal' - -let nvim: Neovim -let terminal: TerminalModel -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - terminal = new TerminalModel('sh', [], nvim) - await terminal.start(__dirname, { COC_TERMINAL: `option '-term'` }) -}) - -afterAll(async () => { - terminal.dispose() - await helper.shutdown() -}) - -describe('terminal properties', () => { - it('should get name', () => { - let name = terminal.name - expect(name).toBe('sh') - }) - - it('should have correct cwd and env', async () => { - let bufnr = terminal.bufnr - terminal.sendText('echo $PWD') - await helper.wait(300) - let lines = await nvim.call('getbufline', [bufnr, 1, '$']) as string[] - expect(lines[0].trim().length).toBeGreaterThan(0) - terminal.sendText('echo $COC_TERMINAL') - await helper.wait(300) - lines = await nvim.call('getbufline', [bufnr, 1, '$']) as string[] - expect(lines.includes(`option '-term'`)).toBe(true) - }) - - it('should get pid', async () => { - let pid = await terminal.processId - expect(typeof pid).toBe('number') - }) - - it('should hide terminal window', async () => { - await terminal.hide() - let winnr = await nvim.call('bufwinnr', terminal.bufnr) - expect(winnr).toBe(-1) - }) - - it('should show terminal window', async () => { - await terminal.show() - let winnr = await nvim.call('bufwinnr', terminal.bufnr) - expect(winnr != -1).toBe(true) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/textdocument.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/textdocument.test.ts deleted file mode 100644 index 1d0a5e42..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/textdocument.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { Position, Range } from 'vscode-languageserver-protocol' -import { LinesTextDocument } from '../../model/textdocument' - -function createTextDocument(lines: string[]): LinesTextDocument { - return new LinesTextDocument('file://a', 'txt', 1, lines, true) -} - -describe('LinesTextDocument', () => { - it('should get line count and content', async () => { - let doc = createTextDocument(['a', 'b']) - expect(doc.lineCount).toBe(3) - let content = doc.getText() - expect(content).toBe('a\nb\n') - }) - - it('should get position', async () => { - let doc = createTextDocument(['foo', 'bar']) - let pos = doc.positionAt(4) - expect(pos).toEqual({ line: 1, character: 0 }) - }) - - it('should get content by range', async () => { - let doc = createTextDocument(['foo', 'bar']) - let content = doc.getText(Range.create(0, 0, 0, 3)) - expect(content).toBe('foo') - }) - - it('should get offset', async () => { - let doc = createTextDocument(['foo', 'bar']) - let offset = doc.offsetAt(Position.create(0, 4)) - expect(offset).toBe(4) - offset = doc.offsetAt(Position.create(2, 1)) - expect(offset).toBe(8) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/util.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/util.test.ts deleted file mode 100644 index 24416f90..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/util.test.ts +++ /dev/null @@ -1,295 +0,0 @@ -import path from 'path' -import { URI } from 'vscode-uri' -import { Range } from 'vscode-languageserver-protocol' -import os from 'os' -import fs from 'fs' -import { wait, watchFile } from '../../util' -import { isGitIgnored, findUp, resolveRoot, statAsync, parentDirs, isParentFolder } from '../../util/fs' -import { fuzzyChar, fuzzyMatch, getCharCodes } from '../../util/fuzzy' -import { score, positions, groupPositions } from '../../util/fzy' -import { score as matchScore } from '../../util/match' -import { mixin } from '../../util/object' -import { Mutex } from '../../util/mutex' -import { indexOf, rangeParts } from '../../util/string' -import helper, { createTmpFile } from '../helper' -import { ansiparse } from '../../util/ansiparse' -import { concurrent } from '../../util' -import { spawn } from 'child_process' -import { terminate } from '../../util/processes' - -describe('rangeParts', () => { - it('should get parts', async () => { - let res = rangeParts('foo bar', Range.create(0, 0, 0, 4)) - expect(res).toEqual(['', 'bar']) - res = rangeParts('foo\nbar', Range.create(0, 1, 1, 1)) - expect(res).toEqual(['f', 'ar']) - res = rangeParts('x\nfoo\nbar\ny', Range.create(0, 1, 2, 3)) - expect(res).toEqual(['x', '\ny']) - }) -}) - -describe('watchFile', () => { - it('should watch file', async () => { - let filepath = await createTmpFile('my file') - let fn = jest.fn() - let disposable = watchFile(filepath, () => { - fn() - }) - await wait(30) - fs.writeFileSync(filepath, 'new file', 'utf8') - await wait(200) - expect(fn).toBeCalled() - disposable.dispose() - }) -}) - -describe('score test', () => { - it('should match schema', () => { - let uri = URI.file('/foo').toString() - let s = matchScore([{ language: '*', scheme: 'file' }], uri, 'typescript') - expect(s).toBe(5) - }) - - it('fzy#score', async () => { - let a = score("amuser", "app/models/user.rb") - let b = score("amuser", "app/models/customer.rb") - expect(a).toBeGreaterThan(b) - }) - - it('fzy#positions', async () => { - let arr = positions("amuser", "app/models/user.rb") - expect(arr).toEqual([0, 4, 11, 12, 13, 14]) - }) - - it('fzy#groupPositions', async () => { - let arr = groupPositions([1, 2, 3, 6, 7, 10]) - expect(arr).toEqual([[1, 4], [6, 8], [10, 11]]) - }) -}) - -describe('parentDirs', () => { - it('get parentDirs', () => { - let dirs = parentDirs('/a/b/c') - expect(dirs).toEqual(['/', '/a', '/a/b']) - }) -}) - -describe('isParentFolder', () => { - it('check parent folder', () => { - expect(isParentFolder('/a', '/a/b')).toBe(true) - expect(isParentFolder('/a/b', '/a/b/')).toBe(false) - expect(isParentFolder('/a/b', '/a/b')).toBe(false) - expect(isParentFolder('/a/b', '/a/b', true)).toBe(true) - }) -}) - -describe('string test', () => { - it('should find index', () => { - expect(indexOf('a,b,c', ',', 2)).toBe(3) - expect(indexOf('a,b,c', ',', 1)).toBe(1) - }) -}) - -describe('concurrent', () => { - it('should run concurrent', async () => { - let res: number[] = [] - let fn = (n: number): Promise => { - return new Promise(resolve => { - setTimeout(() => { - res.push(n) - resolve() - }, n * 100) - }) - } - let arr = [5, 4, 3, 6, 8] - let ts = Date.now() - await concurrent(arr, fn, 3) - let dt = Date.now() - ts - expect(dt).toBeLessThanOrEqual(1300) - expect(dt).toBeGreaterThanOrEqual(1200) - expect(res).toEqual([3, 4, 5, 6, 8]) - }) -}) - -describe('fuzzy match test', () => { - it('should be fuzzy match', () => { - let needle = 'aBc' - let codes = getCharCodes(needle) - expect(fuzzyMatch(codes, 'abc')).toBeFalsy - expect(fuzzyMatch(codes, 'ab')).toBeFalsy - expect(fuzzyMatch(codes, 'addbdd')).toBeFalsy - expect(fuzzyMatch(codes, 'abbbBc')).toBeTruthy - expect(fuzzyMatch(codes, 'daBc')).toBeTruthy - expect(fuzzyMatch(codes, 'ABCz')).toBeTruthy - }) - - it('should be fuzzy for character', () => { - expect(fuzzyChar('a', 'a')).toBeTruthy - expect(fuzzyChar('a', 'A')).toBeTruthy - expect(fuzzyChar('z', 'z')).toBeTruthy - expect(fuzzyChar('z', 'Z')).toBeTruthy - expect(fuzzyChar('A', 'a')).toBeFalsy - expect(fuzzyChar('A', 'A')).toBeTruthy - expect(fuzzyChar('Z', 'z')).toBeFalsy - expect(fuzzyChar('Z', 'Z')).toBeTruthy - }) -}) - -describe('fs test', () => { - it('fs statAsync', async () => { - let res = await statAsync(__filename) - expect(res).toBeDefined - expect(res.isFile()).toBe(true) - }) - - it('fs statAsync #1', async () => { - let res = await statAsync(path.join(__dirname, 'file_not_exist')) - expect(res).toBeNull - }) - - it('should be not ignored', async () => { - let res = await isGitIgnored(__filename) - expect(res).toBeFalsy - }) - - it('should be ignored', async () => { - let res = await isGitIgnored(path.resolve(__dirname, '../lib/index.js.map')) - expect(res).toBeTruthy - }) -}) - -describe('object test', () => { - it('mixin should recursive', () => { - let res = mixin({ a: { b: 1 } }, { a: { c: 2 }, d: 3 }) - expect(res.a.b).toBe(1) - expect(res.a.c).toBe(2) - expect(res.d).toBe(3) - }) -}) - -describe('resolveRoot', () => { - it('resolve root consider root path', () => { - let res = resolveRoot(__dirname, ['.git']) - expect(res).toMatch('coc.nvim') - }) - - it('should resolve from parent folders', () => { - let root = path.resolve(__dirname, '../extensions/snippet-sample') - let res = resolveRoot(root, ['package.json']) - expect(res.endsWith('coc.nvim')).toBe(true) - }) - - it('should resolve from parent folders with bottom-up method', () => { - let root = path.resolve(__dirname, '../extensions/snippet-sample') - let res = resolveRoot(root, ['package.json'], null, true) - expect(res.endsWith('extensions')).toBe(true) - }) - - it('should resolve to cwd', () => { - let root = path.resolve(__dirname, '../extensions/test/') - let res = resolveRoot(root, ['package.json'], root, false, true) - expect(res).toBe(root) - }) - - it('should resolve to root', () => { - let root = path.resolve(__dirname, '../extensions/test/') - let res = resolveRoot(root, ['package.json'], root, false, false) - expect(res).toBe(path.resolve(__dirname, '../../../')) - }) - - it('should not resolve to home', () => { - let res = resolveRoot(__dirname, ['.config']) - expect(res != os.homedir()).toBeTruthy() - }) -}) - -describe('findUp', () => { - it('findUp by filename', () => { - let filepath = findUp('package.json', __dirname) - expect(filepath).toMatch('coc.nvim') - filepath = findUp('not_exists', __dirname) - expect(filepath).toBeNull() - }) - - it('findUp by filenames', async () => { - let filepath = findUp(['src'], __dirname) - expect(filepath).toMatch('coc.nvim') - }) -}) - -describe('ansiparse', () => { - it('ansiparse #1', () => { - let str = '\u001b[33mText\u001b[mnormal' - let res = ansiparse(str) - expect(res).toEqual([{ - foreground: 'yellow', text: 'Text' - }, { - text: 'normal' - }]) - }) - - it('ansiparse #2', () => { - let str = '\u001b[33m\u001b[mText' - let res = ansiparse(str) - expect(res).toEqual([ - { foreground: 'yellow', text: '' }, - { text: 'Text' }]) - }) - - it('ansiparse #3', () => { - let str = 'this.\u001b[0m\u001b[31m\u001b[1mhistory\u001b[0m.add()' - let res = ansiparse(str) - expect(res[1]).toEqual({ - foreground: 'red', - bold: true, text: 'history' - }) - }) -}) - -describe('Mutex', () => { - it('mutex run in serial', async () => { - let lastTs: number - let fn = () => new Promise(resolve => { - if (lastTs) { - let dt = Date.now() - lastTs - expect(dt).toBeGreaterThanOrEqual(298) - } - lastTs = Date.now() - setTimeout(() => { - resolve() - }, 300) - }) - let mutex = new Mutex() - await Promise.all([ - mutex.use(fn), - mutex.use(fn), - mutex.use(fn) - ]) - }) - - it('mutex run after job finish', async () => { - let count = 0 - let fn = () => new Promise(resolve => { - count = count + 1 - setTimeout(() => { - resolve() - }, 100) - }) - let mutex = new Mutex() - await mutex.use(fn) - await helper.wait(10) - await mutex.use(fn) - expect(count).toBe(2) - }) -}) - -describe('terminate', () => { - it('should terminate process', async () => { - let cwd = process.cwd() - let child = spawn('sleep', ['10'], { cwd, detached: true }) - let res = terminate(child, cwd) - await helper.wait(60) - expect(res).toBe(true) - expect(child.connected).toBe(false) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/watchman.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/watchman.test.ts deleted file mode 100644 index d08a0122..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/watchman.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -// import watchman from 'fb-watchman' -import { Neovim } from '@chemzqm/neovim' -import net from 'net' -import fs from 'fs' -import bser from 'bser' -import Watchman, { FileChangeItem } from '../../watchman' -import helper from '../helper' -import BufferChannel from '../../model/outputChannel' - -let server: net.Server -let client: net.Socket -const sockPath = '/tmp/watchman-fake' -process.env.WATCHMAN_SOCK = sockPath - -let nvim: Neovim -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -function wait(ms: number): Promise { - return new Promise(resolve => { - setTimeout(() => { - resolve(undefined) - }, ms) - }) -} - -function sendResponse(data: any): void { - client.write(bser.dumpToBuffer(data)) -} - -function createFileChange(file: string, exists = true): FileChangeItem { - return { - size: 1, - name: file, - exists, - new: false, - type: 'f', - mtime_ms: Date.now() - } -} - -function sendSubscription(uid: string, root: string, files: FileChangeItem[]): void { - client.write(bser.dumpToBuffer({ - subscription: uid, - root, - files - })) -} - -beforeAll(done => { - // create a mock sever for watchman - server = net.createServer(c => { - client = c - c.on('data', data => { - let obj = bser.loadFromBuffer(data) - if (obj[0] == 'watch-project') { - sendResponse({ watch: obj[1] }) - } else if (obj[0] == 'unsubscribe') { - sendResponse({ path: obj[1] }) - } else if (obj[0] == 'clock') { - sendResponse({ clock: 'clock' }) - } else if (obj[0] == 'version') { - let { optional, required } = obj[1] - let res = {} - for (let key of Object.keys(optional)) { - res[key] = true - } - for (let key of Object.keys(required)) { - res[key] = true - } - sendResponse({ capabilities: res }) - } else if (obj[0] == 'subscribe') { - sendResponse({ subscribe: obj[2] }) - } else { - sendResponse({}) - } - }) - }) - server.on('error', err => { - throw err - }) - server.listen(sockPath, () => { - done() - }) -}) - -afterAll(() => { - client.unref() - server.close() - if (fs.existsSync(sockPath)) { - fs.unlinkSync(sockPath) - } -}) - -describe('watchman', () => { - it('should checkCapability', async () => { - let client = new Watchman(null) - let res = await client.checkCapability() - expect(res).toBe(true) - client.dispose() - }) - - it('should watchProject', async () => { - let client = new Watchman(null) - let res = await client.watchProject(__dirname) - expect(res).toBe(true) - client.dispose() - }) - - it('should subscribe', async () => { - let client = new Watchman(null, new BufferChannel('watchman', nvim)) - let cwd = process.cwd() - await client.watchProject(cwd) - let fn = jest.fn() - let disposable = await client.subscribe(`${cwd}/*`, fn) - let changes: FileChangeItem[] = [createFileChange(`${cwd}/a`)] - sendSubscription((global as any).subscribe, cwd, changes) - await wait(100) - expect(fn).toBeCalled() - let call = fn.mock.calls[0][0] - disposable.dispose() - expect(call.root).toBe(cwd) - client.dispose() - }) - - it('should unsubscribe', async () => { - let client = new Watchman(null) - await client.watchProject(process.cwd()) - let fn = jest.fn() - let disposable = await client.subscribe(`${process.cwd()}/*`, fn) - disposable.dispose() - client.dispose() - }) -}) - -describe('Watchman#createClient', () => { - it('should create client', async () => { - let client = await Watchman.createClient(null, process.cwd()) - expect(client).toBeDefined() - client.dispose() - }) - - it('should resue client for same root', async () => { - let client = await Watchman.createClient(null, process.cwd()) - expect(client).toBeDefined() - let other = await Watchman.createClient(null, process.cwd()) - expect(client).toBe(other) - client.dispose() - }) - - it('should not create client for root', async () => { - let client = await Watchman.createClient(null, '/') - expect(client).toBeNull() - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/window.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/window.test.ts deleted file mode 100644 index 727b2b1a..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/window.test.ts +++ /dev/null @@ -1,365 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, Emitter, Range } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import { TreeItem, TreeItemCollapsibleState } from '../../tree' -import { disposeAll } from '../../util' -import window from '../../window' -import workspace from '../../workspace' -import events from '../../events' -import helper from '../helper' - -let nvim: Neovim -let disposables: Disposable[] = [] - -interface FileNode { - filepath: string - isFolder?: boolean -} - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim - let config = workspace.getConfiguration('coc.preferences') - config.update('enableMessageDialog', true) -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -describe('window functions', () => { - it('should get offset', async () => { - let doc = await helper.createDocument() - await doc.applyEdits([{ range: Range.create(0, 0, 0, 0), newText: 'foo\nbar' }]) - let buf = await nvim.buffer - await buf.setLines(['foo', 'bar'], { start: 0, end: -1 }) - await helper.wait(100) - await nvim.call('cursor', [2, 2]) - let n = await window.getOffset() - expect(n).toBe(5) - }) - - it('should echo lines', async () => { - await window.echoLines(['a', 'b']) - let ch = await nvim.call('screenchar', [79, 1]) - let s = String.fromCharCode(ch) - expect(s).toBe('a') - }) - - it('should echo multiple lines with truncate', async () => { - await window.echoLines(['a', 'b', 'd', 'e'], true) - let ch = await nvim.call('screenchar', [79, 1]) - let s = String.fromCharCode(ch) - expect(s).toBe('a') - }) - - it('should run terminal command', async () => { - let res = await window.runTerminalCommand('ls', __dirname) - expect(res.success).toBe(true) - }) - - it('should open temimal buffer', async () => { - let bufnr = await window.openTerminal('ls', { autoclose: false, keepfocus: false }) - let curr = await nvim.eval('bufnr("%")') - expect(curr).toBe(bufnr) - let buftype = await nvim.eval('&buftype') - expect(buftype).toBe('terminal') - }) - - it('should show mesages', async () => { - await helper.edit() - window.showMessage('error', 'error') - await helper.wait(100) - let str = await helper.getCmdline() - expect(str).toMatch('error') - window.showMessage('warning', 'warning') - await helper.wait(100) - str = await helper.getCmdline() - expect(str).toMatch('warning') - window.showMessage('moremsg') - await helper.wait(100) - str = await helper.getCmdline() - expect(str).toMatch('moremsg') - }) - - it('should create outputChannel', () => { - let channel = window.createOutputChannel('channel') - expect(channel.name).toBe('channel') - }) - - it('should create TreeView instance', async () => { - let emitter = new Emitter() - let removed = false - let treeView = window.createTreeView('files', { - treeDataProvider: { - onDidChangeTreeData: emitter.event, - getChildren: root => { - if (root) return undefined - if (removed) return [{ filepath: '/foo/a', isFolder: true }] - return [{ filepath: '/foo/a', isFolder: true }, { filepath: '/foo/b.js' }] - }, - getTreeItem: (node: FileNode) => { - let { filepath, isFolder } = node - return new TreeItem(URI.file(filepath), isFolder ? TreeItemCollapsibleState.Collapsed : TreeItemCollapsibleState.None) - }, - } - }) - disposables.push(emitter) - disposables.push(treeView) - await treeView.show() - await helper.wait(50) - await nvim.command('exe 2') - await nvim.input('t') - await helper.wait(50) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['files', '- a', ' b.js']) - removed = true - emitter.fire(undefined) - await helper.wait(50) - lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['files', '- a']) - }) - - it('should show outputChannel', async () => { - window.createOutputChannel('channel') - window.showOutputChannel('channel') - await helper.wait(50) - let buf = await nvim.buffer - let name = await buf.name - expect(name).toMatch('channel') - }) - - it('should not show none exists channel', async () => { - let buf = await nvim.buffer - let bufnr = buf.id - window.showOutputChannel('NONE') - await helper.wait(10) - buf = await nvim.buffer - expect(buf.id).toBe(bufnr) - }) - - it('should get cursor position', async () => { - await helper.createDocument() - await nvim.setLine(' ') - await nvim.call('cursor', [1, 3]) - let pos = await window.getCursorPosition() - expect(pos).toEqual({ - line: 0, - character: 2 - }) - }) - - it('should moveTo position in insert mode', async () => { - await helper.edit() - await nvim.setLine('foo') - await nvim.input('i') - await window.moveTo({ line: 0, character: 3 }) - let col = await nvim.call('col', '.') - expect(col).toBe(4) - let virtualedit = await nvim.getOption('virtualedit') - expect(virtualedit).toBe('') - }) - - it('should choose quickpick', async () => { - let p = window.showQuickpick(['a', 'b']) - await helper.wait(100) - await nvim.input('1') - await nvim.input('') - let res = await p - expect(res).toBe(0) - }) - - it('should cancel quickpick', async () => { - let p = window.showQuickpick(['a', 'b']) - await helper.wait(100) - await nvim.input('') - let res = await p - expect(res).toBe(-1) - }) - - it('should show prompt', async () => { - let p = window.showPrompt('prompt') - await helper.wait(100) - await nvim.input('y') - let res = await p - expect(res).toBe(true) - }) - - it('should show dialog', async () => { - let dialog = await window.showDialog({ content: 'foo' }) - let winid = await dialog.winid - expect(winid).toBeDefined() - expect(winid).toBeGreaterThan(1000) - }) - - it('should show menu', async () => { - let p = window.showMenuPicker(['a', 'b', 'c'], 'choose item') - await helper.wait(100) - let exists = await nvim.call('coc#float#has_float', []) - expect(exists).toBe(1) - await nvim.input('2') - let res = await p - expect(res).toBe(1) - }) - - it('should request input', async () => { - let winid = await nvim.call('win_getid') - let p = window.requestInput('Name') - await helper.wait(100) - await nvim.input('bar') - let res = await p - let curr = await nvim.call('win_getid') - expect(curr).toBe(winid) - expect(res).toBe('bar') - }) - - it('should return null when input empty', async () => { - let p = window.requestInput('Name') - await helper.wait(30) - await nvim.input('') - let res = await p - expect(res).toBeNull() - }) - - it('should return select items for picker', async () => { - let curr = await nvim.call('win_getid') - let p = window.showPickerDialog(['foo', 'bar'], 'select') - await helper.wait(100) - await nvim.input(' ') - await helper.wait(30) - await nvim.input('') - let res = await p - let winid = await nvim.call('win_getid') - expect(winid).toBe(curr) - expect(res).toEqual(['foo']) - }) - - async function ensureNotification(idx: number): Promise { - let ids = await nvim.call('coc#float#get_float_win_list') - expect(ids.length).toBe(1) - let win = nvim.createWindow(ids[0]) - let kind = await win.getVar('kind') - expect(kind).toBe('notification') - let bufnr = await nvim.call('winbufnr', [win.id]) - await events.fire('FloatBtnClick', [bufnr, idx]) - } - - it('should show information message', async () => { - let p = window.showInformationMessage('information message', 'first', 'second') - await helper.wait(50) - await ensureNotification(0) - let res = await p - expect(res).toBe('first') - }) - - it('should show warning message', async () => { - let p = window.showWarningMessage('warning message', 'first', 'second') - await helper.wait(50) - await ensureNotification(1) - let res = await p - expect(res).toBe('second') - }) - - it('should show error message', async () => { - let p = window.showErrorMessage('error message', 'first', 'second') - await helper.wait(50) - await ensureNotification(0) - let res = await p - expect(res).toBe('first') - }) -}) - -describe('window notifications', () => { - it('should show notification with options', async () => { - let res = await window.showNotification({ - content: 'my notification', - close: true, - title: 'title', - timeout: 500 - }) - expect(res).toBe(true) - let ids = await nvim.call('coc#float#get_float_win_list') - expect(ids.length).toBe(1) - let win = nvim.createWindow(ids[0]) - let kind = await win.getVar('kind') - expect(kind).toBe('notification') - let winid = await nvim.call('coc#float#get_related', [win.id, 'border']) - let bufnr = await nvim.call('winbufnr', [winid]) - let buf = nvim.createBuffer(bufnr) - let lines = await buf.lines - expect(lines[0].includes('title')).toBe(true) - await helper.wait(600) - let valid = await nvim.call('coc#float#valid', [win.id]) - expect(valid).toBeFalsy() - }) - - it('should show progress notification', async () => { - let called = 0 - let res = await window.withProgress({ title: 'Downloading', cancellable: true }, (progress, token) => { - let n = 0 - return new Promise(resolve => { - let interval = setInterval(() => { - progress.report({ message: 'progress', increment: 1 }) - n = n + 10 - called = called + 1 - if (n == 100) { - clearInterval(interval) - resolve('done') - } - }, 100) - token.onCancellationRequested(() => { - clearInterval(interval) - resolve(undefined) - }) - }) - }) - expect(called).toBe(10) - expect(res).toBe('done') - }) - - it('should cancel progress notification on window close', async () => { - let called = 0 - let p = window.withProgress({ title: 'Downloading', cancellable: true }, (progress, token) => { - let n = 0 - return new Promise(resolve => { - let interval = setInterval(() => { - progress.report({ message: 'progress', increment: 1 }) - n = n + 10 - called = called + 1 - if (n == 100) { - clearInterval(interval) - resolve('done') - } - }, 100) - token.onCancellationRequested(() => { - clearInterval(interval) - resolve(undefined) - }) - }) - }) - await helper.wait(300) - await nvim.call('coc#float#close_all', []) - let res = await p - expect(called).toBeLessThan(10) - expect(res).toBe(undefined) - }) - - it('should cancel progress when window not shown', async () => { - let called = 0 - let p = window.withProgress({ title: 'Process' }, () => { - called = called + 1 - return Promise.resolve() - }) - await p - await helper.wait(120) - let floats = await helper.getFloats() - expect(called).toBe(1) - expect(floats.length).toBe(0) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/modules/workspace.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/modules/workspace.test.ts deleted file mode 100644 index fb670b4d..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/modules/workspace.test.ts +++ /dev/null @@ -1,1043 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import fs from 'fs' -import os from 'os' -import path from 'path' -import { v4 as uuid } from 'uuid' -import { Disposable, Emitter } from 'vscode-languageserver-protocol' -import { CreateFile, DeleteFile, Location, Position, Range, RenameFile, TextDocumentEdit, TextEdit, VersionedTextDocumentIdentifier, WorkspaceEdit } from 'vscode-languageserver-types' -import { URI } from 'vscode-uri' -import events from '../../events' -import { TextDocumentContentProvider } from '../../provider' -import { ConfigurationTarget } from '../../types' -import { disposeAll } from '../../util' -import { readFile } from '../../util/fs' -import window from '../../window' -import workspace from '../../workspace' -import helper, { createTmpFile } from '../helper' - -let nvim: Neovim -let disposables: Disposable[] = [] - -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() - disposeAll(disposables) - disposables = [] -}) - -describe('workspace properties', () => { - - it('should have initialized', () => { - let { nvim, rootPath, cwd, documents, initialized, textDocuments } = workspace - expect(nvim).toBeTruthy() - expect(initialized).toBe(true) - expect(documents.length).toBe(1) - expect(textDocuments.length).toBe(1) - expect(rootPath).toBe(process.cwd()) - expect(cwd).toBe(process.cwd()) - }) - - it('should add workspaceFolder', async () => { - await helper.edit() - let { workspaceFolders, workspaceFolder } = workspace - expect(workspaceFolders.length).toBe(1) - expect(workspaceFolders[0].name).toBe('coc.nvim') - expect(workspaceFolder.name).toBe('coc.nvim') - }) - - it('should check isVim and isNvim', async () => { - let { isVim, isNvim } = workspace - expect(isVim).toBe(false) - expect(isNvim).toBe(true) - }) - - it('should return plugin root', () => { - let { pluginRoot } = workspace - expect(typeof pluginRoot).toBe('string') - }) - - it('should ready', async () => { - (workspace as any)._initialized = false - let p = workspace.ready - ; (workspace as any)._initialized = true - ; (workspace as any)._onDidWorkspaceInitialized.fire(void 0) - await p - }) - - it('should get filetyps', async () => { - await helper.edit('f.js') - let filetypes = workspace.filetypes - expect(filetypes.has('javascript')).toBe(true) - }) -}) - -describe('workspace applyEdits', () => { - it('should apply TextEdit of documentChanges', async () => { - let doc = await helper.createDocument() - let versioned = VersionedTextDocumentIdentifier.create(doc.uri, doc.version) - let edit = TextEdit.insert(Position.create(0, 0), 'bar') - let change = TextDocumentEdit.create(versioned, [edit]) - let workspaceEdit: WorkspaceEdit = { - documentChanges: [change] - } - let res = await workspace.applyEdit(workspaceEdit) - expect(res).toBe(true) - let line = await nvim.getLine() - expect(line).toBe('bar') - }) - - it('should not apply TextEdit if version miss match', async () => { - let doc = await helper.createDocument() - let versioned = VersionedTextDocumentIdentifier.create(doc.uri, 10) - let edit = TextEdit.insert(Position.create(0, 0), 'bar') - let change = TextDocumentEdit.create(versioned, [edit]) - let workspaceEdit: WorkspaceEdit = { - documentChanges: [change] - } - let res = await workspace.applyEdit(workspaceEdit) - expect(res).toBe(false) - }) - - it('should apply edits with changes to buffer', async () => { - let doc = await helper.createDocument() - let changes = { - [doc.uri]: [TextEdit.insert(Position.create(0, 0), 'bar')] - } - let workspaceEdit: WorkspaceEdit = { changes } - let res = await workspace.applyEdit(workspaceEdit) - expect(res).toBe(true) - let line = await nvim.getLine() - expect(line).toBe('bar') - }) - - it('should apply edits with changes to file not in buffer list', async () => { - let filepath = await createTmpFile('bar') - let uri = URI.file(filepath).toString() - let changes = { - [uri]: [TextEdit.insert(Position.create(0, 0), 'foo')] - } - let res = await workspace.applyEdit({ changes }) - expect(res).toBe(true) - let doc = workspace.getDocument(uri) - let content = doc.getDocumentContent() - expect(content).toMatch(/^foobar/) - await nvim.command('silent! %bwipeout!') - }) - - it('should apply edits when file not exists', async () => { - let filepath = path.join(__dirname, 'not_exists') - let uri = URI.file(filepath).toString() - let changes = { - [uri]: [TextEdit.insert(Position.create(0, 0), 'foo')] - } - let res = await workspace.applyEdit({ changes }) - expect(res).toBe(true) - }) - - it('should adjust cursor position after applyEdits', async () => { - let doc = await helper.createDocument() - let pos = await window.getCursorPosition() - expect(pos).toEqual({ line: 0, character: 0 }) - let edit = TextEdit.insert(Position.create(0, 0), 'foo\n') - let versioned = VersionedTextDocumentIdentifier.create(doc.uri, null) - let documentChanges = [TextDocumentEdit.create(versioned, [edit])] - let res = await workspace.applyEdit({ documentChanges }) - expect(res).toBe(true) - pos = await window.getCursorPosition() - expect(pos).toEqual({ line: 1, character: 0 }) - }) - - it('should support null version of documentChanges', async () => { - let file = path.join(__dirname, 'foo') - await workspace.createFile(file, { ignoreIfExists: true, overwrite: true }) - let uri = URI.file(file).toString() - let versioned = VersionedTextDocumentIdentifier.create(uri, null) - let edit = TextEdit.insert(Position.create(0, 0), 'bar') - let change = TextDocumentEdit.create(versioned, [edit]) - let workspaceEdit: WorkspaceEdit = { - documentChanges: [change] - } - let res = await workspace.applyEdit(workspaceEdit) - expect(res).toBe(true) - await nvim.command('wa') - let content = await readFile(file, 'utf8') - expect(content).toMatch(/^bar/) - await workspace.deleteFile(file, { ignoreIfNotExists: true }) - }) - - it('should support CreateFile edit', async () => { - let file = path.join(__dirname, 'foo') - let uri = URI.file(file).toString() - let workspaceEdit: WorkspaceEdit = { - documentChanges: [CreateFile.create(uri, { overwrite: true })] - } - let res = await workspace.applyEdit(workspaceEdit) - expect(res).toBe(true) - await workspace.deleteFile(file, { ignoreIfNotExists: true }) - }) - - it('should support DeleteFile edit', async () => { - let file = path.join(__dirname, 'foo') - await workspace.createFile(file, { ignoreIfExists: true, overwrite: true }) - let uri = URI.file(file).toString() - let workspaceEdit: WorkspaceEdit = { - documentChanges: [DeleteFile.create(uri)] - } - let res = await workspace.applyEdit(workspaceEdit) - expect(res).toBe(true) - }) - - it('should check uri for CreateFile edit', async () => { - let workspaceEdit: WorkspaceEdit = { - documentChanges: [CreateFile.create('term://.', { overwrite: true })] - } - let res = await workspace.applyEdit(workspaceEdit) - expect(res).toBe(false) - }) - - it('should support RenameFile edit', async () => { - let file = path.join(__dirname, 'foo') - await workspace.createFile(file, { ignoreIfExists: true, overwrite: true }) - let newFile = path.join(__dirname, 'bar') - let uri = URI.file(file).toString() - let workspaceEdit: WorkspaceEdit = { - documentChanges: [RenameFile.create(uri, URI.file(newFile).toString())] - } - let res = await workspace.applyEdit(workspaceEdit) - expect(res).toBe(true) - await workspace.deleteFile(newFile, { ignoreIfNotExists: true }) - }) - - it('should support changes with edit and rename', async () => { - let file = await createTmpFile('test') - let doc = await helper.createDocument(file) - let newFile = path.join(os.tmpdir(), `coc-${process.pid}/new-${uuid()}`) - let newUri = URI.file(newFile).toString() - let edit: WorkspaceEdit = { - documentChanges: [ - { - textDocument: { - version: null, - uri: doc.uri, - }, - edits: [ - { - range: { - start: { - line: 0, - character: 0 - }, - end: { - line: 0, - character: 4 - } - }, - newText: 'bar' - } - ] - }, - { - oldUri: doc.uri, - newUri, - kind: 'rename' - } - ] - } - let res = await workspace.applyEdit(edit) - expect(res).toBe(true) - let curr = await workspace.document - expect(curr.uri).toBe(newUri) - expect(curr.getline(0)).toBe('bar') - let line = await nvim.line - expect(line).toBe('bar') - }) - - it('should support edit new file with CreateFile', async () => { - let file = path.join(os.tmpdir(), 'foo') - let uri = URI.file(file).toString() - let workspaceEdit: WorkspaceEdit = { - documentChanges: [ - CreateFile.create(uri, { overwrite: true }), - TextDocumentEdit.create({ uri, version: 0 }, [ - TextEdit.insert(Position.create(0, 0), 'foo bar') - ]) - ] - } - let res = await workspace.applyEdit(workspaceEdit) - expect(res).toBe(true) - let doc = workspace.getDocument(uri) - expect(doc).toBeDefined() - let line = doc.getline(0) - expect(line).toBe('foo bar') - await workspace.deleteFile(file, { ignoreIfNotExists: true }) - }) -}) - -describe('workspace methods', () => { - it('should selected range', async () => { - let buf = await helper.edit() - await nvim.setLine('foobar') - await nvim.command('normal! viw') - await nvim.eval(`feedkeys("\\", 'in')`) - let doc = workspace.getDocument(buf.id) - let range = await workspace.getSelectedRange('v', doc) - expect(range).toEqual({ start: { line: 0, character: 0 }, end: { line: 0, character: 6 } }) - }) - - it('should get the document', async () => { - let buf = await helper.edit() - let doc = workspace.getDocument(buf.id) - expect(doc.buffer.equals(buf)).toBeTruthy() - doc = workspace.getDocument(doc.uri) - expect(doc.buffer.equals(buf)).toBeTruthy() - }) - - it('should get format options', async () => { - let opts = await workspace.getFormatOptions() - expect(opts.insertSpaces).toBe(true) - expect(opts.tabSize).toBe(2) - }) - - it('should get format options of current buffer', async () => { - let buf = await helper.edit() - await buf.setOption('shiftwidth', 8) - await buf.setOption('expandtab', false) - let doc = workspace.getDocument(buf.id) - let opts = await workspace.getFormatOptions(doc.uri) - expect(opts.insertSpaces).toBe(false) - expect(opts.tabSize).toBe(8) - }) - - it('should get format options when uri not exists', async () => { - let uri = URI.file('/tmp/foo').toString() - let opts = await workspace.getFormatOptions(uri) - expect(opts.insertSpaces).toBe(true) - expect(opts.tabSize).toBe(2) - }) - - it('should get config files', async () => { - let file = workspace.getConfigFile(ConfigurationTarget.Global) - expect(file).toBeFalsy() - file = workspace.getConfigFile(ConfigurationTarget.User) - expect(file).toBeTruthy() - }) - - it('should create file watcher', async () => { - let watcher = workspace.createFileSystemWatcher('**/*.ts') - expect(watcher).toBeTruthy() - }) - - it('should get quickfix item from Location', async () => { - let filepath = await createTmpFile('quickfix') - let uri = URI.file(filepath).toString() - let p = Position.create(0, 0) - let loc = Location.create(uri, Range.create(p, p)) - let item = await workspace.getQuickfixItem(loc) - expect(item.filename).toBe(filepath) - expect(item.text).toBe('quickfix') - }) - - it('should get line of document', async () => { - let doc = await helper.createDocument() - await nvim.setLine('abc') - let line = await workspace.getLine(doc.uri, 0) - expect(line).toBe('abc') - }) - - it('should get line of file', async () => { - let filepath = await createTmpFile('quickfix') - let uri = URI.file(filepath).toString() - let line = await workspace.getLine(uri, 0) - expect(line).toBe('quickfix') - }) - - it('should read content from buffer', async () => { - let doc = await helper.createDocument() - await doc.applyEdits([{ range: Range.create(0, 0, 0, 0), newText: 'foo' }]) - let line = await workspace.readFile(doc.uri) - expect(line).toBe('foo\n') - }) - - it('should read content from file', async () => { - let filepath = await createTmpFile('content') - let content = await workspace.readFile(URI.file(filepath).toString()) - expect(content).toBe(content) - }) - - it('should get current document', async () => { - let buf = await helper.edit('foo') - let doc = await workspace.document - expect(doc.bufnr).toBe(buf.id) - buf = await helper.edit('tmp') - doc = await workspace.document - expect(doc.bufnr).toBe(buf.id) - }) - - it('should expand filepath', async () => { - let home = os.homedir() - let res = workspace.expand('~/$NODE_ENV/') - expect(res.startsWith(home)).toBeTruthy() - expect(res).toContain(process.env.NODE_ENV) - - res = workspace.expand('$HOME/$NODE_ENV/') - expect(res.startsWith(home)).toBeTruthy() - expect(res).toContain(process.env.NODE_ENV) - }) - - it('should expand variables', async () => { - expect(workspace.expand('${workspace}/foo')).toBe(`${workspace.root}/foo`) - expect(workspace.expand('${env:NODE_ENV}')).toBe(process.env.NODE_ENV) - expect(workspace.expand('${cwd}')).toBe(workspace.cwd) - let folder = path.dirname(workspace.root) - expect(workspace.expand('${workspaceFolderBasename}')).toBe(folder) - await helper.edit('bar.ts') - expect(workspace.expand('${file}')).toContain('bar') - expect(workspace.expand('${fileDirname}')).toBe(path.dirname(__dirname)) - expect(workspace.expand('${fileExtname}')).toBe('.ts') - expect(workspace.expand('${fileBasename}')).toBe('bar.ts') - expect(workspace.expand('${fileBasenameNoExtension}')).toBe('bar') - }) - - it('should run command', async () => { - let res = await workspace.runCommand('ls', __dirname, 1) - expect(res).toMatch('workspace') - }) - - it('should resolve module path if exists', async () => { - let res = await workspace.resolveModule('typescript') - expect(res).toBeTruthy() - }) - - it('should not resolve module if not exists', async () => { - let res = await workspace.resolveModule('foo') - expect(res).toBeFalsy() - }) - - it('should return match score for document', async () => { - let doc = await helper.createDocument('tmp.xml') - expect(workspace.match(['xml'], doc.textDocument)).toBe(10) - expect(workspace.match(['wxml'], doc.textDocument)).toBe(0) - expect(workspace.match([{ language: 'xml' }], doc.textDocument)).toBe(10) - expect(workspace.match([{ language: 'wxml' }], doc.textDocument)).toBe(0) - expect(workspace.match([{ pattern: '**/*.xml' }], doc.textDocument)).toBe(5) - expect(workspace.match([{ pattern: '**/*.html' }], doc.textDocument)).toBe(0) - expect(workspace.match([{ scheme: 'file' }], doc.textDocument)).toBe(5) - expect(workspace.match([{ scheme: 'term' }], doc.textDocument)).toBe(0) - expect(workspace.match([{ language: 'xml' }, { scheme: 'file' }], doc.textDocument)).toBe(10) - }) - - it('should create terminal', async () => { - let terminal = await workspace.createTerminal({ name: 'test' }) - let pid = await terminal.processId - expect(typeof pid == 'number').toBe(true) - terminal.dispose() - }) - - it('should rename buffer', async () => { - await helper.createDocument('a') - let p = workspace.renameCurrent() - await helper.wait(30) - await nvim.input('b') - await p - let name = await nvim.eval('bufname("%")') as string - expect(name.endsWith('b')).toBe(true) - }) - - it('should rename file', async () => { - let cwd = await nvim.call('getcwd') - let file = path.join(cwd, 'a') - fs.writeFileSync(file, 'foo', 'utf8') - await helper.createDocument('a') - let p = workspace.renameCurrent() - await helper.wait(30) - await nvim.input('b') - await p - let name = await nvim.eval('bufname("%")') as string - expect(name.endsWith('b')).toBe(true) - expect(fs.existsSync(path.join(cwd, 'b'))).toBe(true) - fs.unlinkSync(path.join(cwd, 'b')) - }) -}) - -describe('workspace utility', () => { - - it('should support float', async () => { - let floatSupported = workspace.floatSupported - expect(floatSupported).toBe(true) - }) - - it('should loadFile', async () => { - let doc = await helper.createDocument() - let newFile = URI.file(path.join(__dirname, 'abc')).toString() - let document = await workspace.loadFile(newFile) - let bufnr = await nvim.call('bufnr', '%') - expect(document.uri.endsWith('abc')).toBe(true) - expect(bufnr).toBe(doc.bufnr) - }) - - it('should loadFiles', async () => { - let files = ['a', 'b', 'c'].map(key => URI.file(path.join(__dirname, key)).toString()) - await workspace.loadFiles(files) - for (let file of files) { - let uri = URI.file(file).toString() - let doc = workspace.getDocument(uri) - expect(doc).toBeDefined() - } - }) - - it('should not create file if document exists', async () => { - let doc = await helper.createDocument() - let filepath = URI.parse(doc.uri).fsPath - await workspace.createFile(filepath, { ignoreIfExists: false }) - let exists = fs.existsSync(filepath) - expect(exists).toBe(false) - }) - - it('should create file if parent folder not exists', async () => { - const folder = path.join(__dirname, 'foo') - const filepath = path.join(folder, 'bar') - await workspace.createFile(filepath) - const exists = fs.existsSync(filepath) - expect(exists).toBe(true) - fs.unlinkSync(filepath) - fs.rmdirSync(folder) - }) - - it('should not create file if file exists with ignoreIfExists', async () => { - let file = await createTmpFile('foo') - await workspace.createFile(file, { ignoreIfExists: true }) - let content = fs.readFileSync(file, 'utf8') - expect(content).toBe('foo') - }) - - it('should create file if not exists', async () => { - await helper.edit() - let filepath = path.join(__dirname, 'foo') - await workspace.createFile(filepath, { ignoreIfExists: true }) - let exists = fs.existsSync(filepath) - expect(exists).toBe(true) - fs.unlinkSync(filepath) - }) - - it('should create folder if not exists', async () => { - let filepath = path.join(__dirname, 'bar/') - await workspace.createFile(filepath) - expect(fs.existsSync(filepath)).toBe(true) - fs.rmdirSync(filepath) - }) - - it('should not throw on folder create if overwrite is true', async () => { - let filepath = path.join(__dirname, 'bar/') - await workspace.createFile(filepath) - await workspace.createFile(filepath, { overwrite: true }) - expect(fs.existsSync(filepath)).toBe(true) - fs.rmdirSync(filepath) - }) - - it('should rename if file not exists', async () => { - let filepath = path.join(__dirname, 'foo') - let newPath = path.join(__dirname, 'bar') - await workspace.createFile(filepath) - await workspace.renameFile(filepath, newPath) - expect(fs.existsSync(newPath)).toBe(true) - expect(fs.existsSync(filepath)).toBe(false) - fs.unlinkSync(newPath) - }) - - it('should rename current buffer with another buffer', async () => { - let file = await createTmpFile('test') - let doc = await helper.createDocument(file) - await nvim.setLine('bar') - await helper.wait(50) - let newFile = path.join(os.tmpdir(), `coc-${process.pid}/new-${uuid()}`) - await workspace.renameFile(file, newFile) - let bufnr = await nvim.call('bufnr', ['%']) - expect(bufnr).toBeGreaterThan(doc.bufnr) - let line = await nvim.line - expect(line).toBe('bar') - let exists = fs.existsSync(newFile) - expect(exists).toBe(true) - }) - - it('should overwrite if file exists', async () => { - let filepath = path.join(os.tmpdir(), uuid()) - let newPath = path.join(os.tmpdir(), uuid()) - await workspace.createFile(filepath) - await workspace.createFile(newPath) - await workspace.renameFile(filepath, newPath, { overwrite: true }) - expect(fs.existsSync(newPath)).toBe(true) - expect(fs.existsSync(filepath)).toBe(false) - fs.unlinkSync(newPath) - }) - - it('should delete file if exists', async () => { - let filepath = path.join(__dirname, 'foo') - await workspace.createFile(filepath) - expect(fs.existsSync(filepath)).toBe(true) - await workspace.deleteFile(filepath) - expect(fs.existsSync(filepath)).toBe(false) - }) - - it('should delete folder if exists', async () => { - let filepath = path.join(__dirname, 'foo/') - await workspace.createFile(filepath) - expect(fs.existsSync(filepath)).toBe(true) - await workspace.deleteFile(filepath, { recursive: true }) - expect(fs.existsSync(filepath)).toBe(false) - }) - - it('should open resource', async () => { - let uri = URI.file(path.join(os.tmpdir(), 'bar')).toString() - await workspace.openResource(uri) - let buf = await nvim.buffer - let name = await buf.name - expect(name).toMatch('bar') - }) - - it('should open none file uri', async () => { - let uri = 'jdi://abc' - await workspace.openResource(uri) - let buf = await nvim.buffer - let name = await buf.name - expect(name).toBe('jdi://abc') - }) - - it('should open opened buffer', async () => { - let buf = await helper.edit() - let doc = workspace.getDocument(buf.id) - await workspace.openResource(doc.uri) - await helper.wait(30) - let bufnr = await nvim.call('bufnr', '%') - expect(bufnr).toBe(buf.id) - }) - - it('should open url', async () => { - await helper.mockFunction('coc#util#open_url', 0) - let buf = await helper.edit() - let uri = 'http://example.com' - await workspace.openResource(uri) - await helper.wait(30) - let bufnr = await nvim.call('bufnr', '%') - expect(bufnr).toBe(buf.id) - }) - - it('should create database', async () => { - let db = workspace.createDatabase('test') - let res = db.exists('xyz') - expect(res).toBe(false) - db.destroy() - }) - - it('should get current state', async () => { - let buf = await helper.edit() - await buf.setLines(['foo', 'bar'], { start: 0, end: -1, strictIndexing: false }) - await nvim.call('cursor', [2, 2]) - let doc = workspace.getDocument(buf.id) - let state = await workspace.getCurrentState() - expect(doc.uri).toBe(state.document.uri) - expect(state.position).toEqual({ line: 1, character: 1 }) - }) - - it('should jumpTo position', async () => { - let uri = URI.file('/tmp/foo').toString() - await workspace.jumpTo(uri, { line: 1, character: 1 }) - await nvim.command('setl buftype=nofile') - let buf = await nvim.buffer - let name = await buf.name - expect(name).toMatch('/foo') - await buf.setLines(['foo', 'bar'], { start: 0, end: -1, strictIndexing: false }) - await workspace.jumpTo(uri, { line: 1, character: 1 }) - let pos = await nvim.call('getcurpos') - expect(pos.slice(1, 3)).toEqual([2, 2]) - }) - - it('should jumpTo uri without normalize', async () => { - let uri = 'zipfile:///tmp/clojure-1.9.0.jar::clojure/core.clj' - await workspace.jumpTo(uri) - let buf = await nvim.buffer - let name = await buf.name - expect(name).toBe(uri) - }) - - it('should jump without position', async () => { - let uri = URI.file('/tmp/foo').toString() - await workspace.jumpTo(uri) - let buf = await nvim.buffer - let name = await buf.name - expect(name).toMatch('/foo') - }) - - it('should jumpTo custom uri scheme', async () => { - let uri = 'jdt://foo' - await workspace.jumpTo(uri, { line: 1, character: 1 }) - let buf = await nvim.buffer - let name = await buf.name - expect(name).toBe(uri) - }) - - it('should findUp to tsconfig.json from current file', async () => { - await helper.edit(path.join(__dirname, 'edit')) - let filepath = await workspace.findUp('tsconfig.json') - expect(filepath).toMatch('tsconfig.json') - }) - - it('should findUp from current file ', async () => { - await helper.edit('foo') - let filepath = await workspace.findUp('tsconfig.json') - expect(filepath).toMatch('tsconfig.json') - }) - - it('should not findUp from file in other directory', async () => { - await nvim.command(`edit ${path.join(os.tmpdir(), 'foo')}`) - let filepath = await workspace.findUp('tsconfig.json') - expect(filepath).toBeNull() - }) - - it('should resolveRootPath', async () => { - let file = path.join(__dirname, 'foo') - let uri = URI.file(file) - let res = await workspace.resolveRootFolder(uri, ['.git']) - expect(res).toMatch('coc.nvim') - }) - - it('should register autocmd', async () => { - let event: any - let eventCount = 0 - let disposables = [] - disposables.push(workspace.registerAutocmd({ - event: 'TextYankPost', - arglist: ['v:event'], - callback: ev => { - eventCount += 1 - event = ev - } - })) - disposables.push(workspace.registerAutocmd({ - event: ['InsertEnter', 'CursorMoved'], - callback: () => { - eventCount += 1 - } - })) - await nvim.setLine('foo') - await helper.wait(30) - await nvim.command('normal! yy') - await helper.wait(30) - await nvim.command('normal! Abar') - await helper.wait(30) - expect(event.regtype).toBe('V') - expect(event.operator).toBe('y') - expect(event.regcontents).toEqual(['foo']) - expect(eventCount).toBeGreaterThan(2) - disposables.forEach(d => d.dispose()) - }) - - it('should regist keymap', async () => { - let fn = jest.fn() - await nvim.command('nmap go (coc-echo)') - let disposable = workspace.registerKeymap(['n', 'v'], 'echo', fn, { sync: true }) - await helper.wait(30) - let { mode } = await nvim.mode - expect(mode).toBe('n') - await nvim.call('feedkeys', ['go', 'i']) - await helper.wait(10) - expect(fn).toBeCalledTimes(1) - disposable.dispose() - await nvim.call('feedkeys', ['go', 'i']) - await helper.wait(10) - expect(fn).toBeCalledTimes(1) - }) - - it('should regist expr keymap', async () => { - let called = false - let fn = () => { - called = true - return '""' - } - await nvim.input('i') - let { mode } = await nvim.mode - expect(mode).toBe('i') - let disposable = workspace.registerExprKeymap('i', '"', fn) - await helper.wait(30) - await nvim.call('feedkeys', ['"', 't']) - await helper.wait(30) - expect(called).toBe(true) - let line = await nvim.line - expect(line).toBe('""') - disposable.dispose() - }) - - it('should regist buffer expr keymap', async () => { - let fn = () => '""' - await nvim.input('i') - let disposable = workspace.registerExprKeymap('i', '"', fn, true) - await helper.wait(30) - await nvim.call('feedkeys', ['"', 't']) - await helper.wait(30) - let line = await nvim.line - expect(line).toBe('""') - disposable.dispose() - }) - - it('should watch options', async () => { - let fn = jest.fn() - workspace.watchOption('showmode', fn, disposables) - await helper.wait(30) - await nvim.command('set showmode') - await helper.wait(30) - expect(fn).toBeCalled() - await nvim.command('noa set noshowmode') - }) - - it('should watch global', async () => { - let fn = jest.fn() - workspace.watchGlobal('x', fn, disposables) - await nvim.command('let g:x = 1') - await helper.wait(30) - }) -}) - -describe('workspace events', () => { - - it('should listen to fileType change', async () => { - let buf = await helper.edit() - await nvim.command('setf xml') - await helper.wait(40) - let doc = workspace.getDocument(buf.id) - expect(doc.filetype).toBe('xml') - }) - - it('should listen optionSet', async () => { - let opt = workspace.completeOpt - expect(opt).toMatch('menuone') - await nvim.command('set completeopt=menu,preview') - await helper.wait(50) - opt = workspace.completeOpt - expect(opt).toBe('menu,preview') - }) - - it('should fire onDidOpenTextDocument', async () => { - let fn = jest.fn() - workspace.onDidOpenTextDocument(fn, null, disposables) - await helper.edit() - await helper.wait(30) - expect(fn).toHaveBeenCalledTimes(1) - }) - - it('should fire onDidChangeTextDocument', async () => { - let fn = jest.fn() - await helper.edit() - workspace.onDidChangeTextDocument(fn, null, disposables) - await nvim.setLine('foo') - let doc = await workspace.document - doc.forceSync() - await helper.wait(20) - expect(fn).toHaveBeenCalledTimes(1) - }) - - it('should fire onDidChangeConfiguration', async () => { - await helper.createDocument() - let fn = jest.fn() - let disposable = workspace.onDidChangeConfiguration(e => { - disposable.dispose() - expect(e.affectsConfiguration('tsserver')).toBe(true) - expect(e.affectsConfiguration('tslint')).toBe(false) - fn() - }) - let config = workspace.getConfiguration('tsserver') - config.update('enable', false) - await helper.wait(100) - expect(fn).toHaveBeenCalledTimes(1) - config.update('enable', undefined) - }) - - it('should get empty configuration for none exists section', () => { - let config = workspace.getConfiguration('notexists') - let keys = Object.keys(config) - expect(keys.length).toBe(0) - }) - - it('should fire onWillSaveUntil', async () => { - let doc = await helper.createDocument() - let filepath = URI.parse(doc.uri).fsPath - let fn = jest.fn() - let disposable = workspace.onWillSaveTextDocument(event => { - let promise = new Promise(resolve => { - fn() - let edit: TextEdit = { - newText: 'foo', - range: Range.create(0, 0, 0, 0) - } - resolve([edit]) - }) - event.waitUntil(promise) - }) - await helper.wait(100) - await nvim.setLine('bar') - await helper.wait(30) - await events.fire('BufWritePre', [doc.bufnr]) - await helper.wait(30) - let content = doc.getDocumentContent() - expect(content.startsWith('foobar')).toBe(true) - disposable.dispose() - expect(fn).toBeCalledTimes(1) - if (fs.existsSync(filepath)) { - fs.unlinkSync(filepath) - } - }) - - it('should not work for async waitUntil', async () => { - let doc = await helper.createDocument() - let filepath = URI.parse(doc.uri).fsPath - let disposable = workspace.onWillSaveTextDocument(event => { - setTimeout(() => { - let edit: TextEdit = { - newText: 'foo', - range: Range.create(0, 0, 0, 0) - } - event.waitUntil(Promise.resolve([edit])) - }, 30) - }) - await nvim.setLine('bar') - await helper.wait(30) - await nvim.command('wa') - let content = doc.getDocumentContent() - expect(content).toMatch('bar') - disposable.dispose() - if (fs.existsSync(filepath)) { - fs.unlinkSync(filepath) - } - }) - - it('should only use first returned textEdits', async () => { - let doc = await helper.createDocument() - let filepath = URI.parse(doc.uri).fsPath - let disposables: Disposable[] = [] - workspace.onWillSaveTextDocument(event => { - event.waitUntil(Promise.resolve(undefined)) - }, null, disposables) - workspace.onWillSaveTextDocument(event => { - let promise = new Promise(resolve => { - setTimeout(() => { - let edit: TextEdit = { - newText: 'foo', - range: Range.create(0, 0, 0, 0) - } - resolve([edit]) - }, 10) - }) - event.waitUntil(promise) - }, null, disposables) - workspace.onWillSaveTextDocument(event => { - let promise = new Promise(resolve => { - setTimeout(() => { - let edit: TextEdit = { - newText: 'bar', - range: Range.create(0, 0, 0, 0) - } - resolve([edit]) - }, 30) - }) - event.waitUntil(promise) - }, null, disposables) - await nvim.setLine('bar') - await helper.wait(30) - await nvim.command('wa') - let content = doc.getDocumentContent() - expect(content).toMatch('foo') - disposeAll(disposables) - if (fs.existsSync(filepath)) { - fs.unlinkSync(filepath) - } - }) - - it('should attach & detach', async () => { - let buf = await helper.edit() - await nvim.command('CocDisable') - await helper.wait(100) - let doc = workspace.getDocument(buf.id) - expect(doc).toBeUndefined() - await nvim.command('CocEnable') - await helper.wait(100) - doc = workspace.getDocument(buf.id) - expect(doc.bufnr).toBe(buf.id) - }) - - it('should create document with same bufnr', async () => { - await nvim.command('tabe') - let buf = await helper.edit() - await helper.wait(100) - let doc = workspace.getDocument(buf.id) - expect(doc).toBeDefined() - }) -}) - -describe('workspace textDocument content provider', () => { - - it('should regist document content provider', async () => { - let provider: TextDocumentContentProvider = { - provideTextDocumentContent: (_uri, _token): string => 'sample text' - } - workspace.registerTextDocumentContentProvider('test', provider) - await helper.wait(100) - await nvim.command('edit test://1') - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual(['sample text']) - }) - - it('should react onChagne event of document content provider', async () => { - let text = 'foo' - let emitter = new Emitter() - let event = emitter.event - let provider: TextDocumentContentProvider = { - onDidChange: event, - provideTextDocumentContent: (_uri, _token): string => text - } - workspace.registerTextDocumentContentProvider('jdk', provider) - await helper.wait(80) - await nvim.command('edit jdk://1') - await helper.wait(100) - text = 'bar' - emitter.fire(URI.parse('jdk://1')) - await helper.wait(200) - let buf = await nvim.buffer - let lines = await buf.lines - expect(lines).toEqual(['bar']) - }) -}) - -describe('workspace registerBufferSync', () => { - it('should regist', async () => { - await helper.createDocument() - let created = 0 - let deleted = 0 - let changed = 0 - let disposable = workspace.registerBufferSync(() => { - created = created + 1 - return { - dispose: () => { - deleted += 1 - }, - onChange: () => { - changed += 1 - } - } - }) - disposables.push(disposable) - let doc = await helper.createDocument() - expect(created).toBe(2) - await doc.applyEdits([TextEdit.insert(Position.create(0, 0), 'foo')]) - expect(changed).toBe(1) - await nvim.command('bd!') - await helper.wait(50) - expect(deleted).toBe(1) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/rg b/vim-config/plugins/coc.nvim/src/__tests__/rg deleted file mode 100755 index 056d698a..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/rg +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env node -// black:30 red:31 green:32 - -let content = `\x1b[30mmodules/cursors.test.ts\x1b[m -\x1b[32m218\x1b[m- let doc = await setup() -\x1b[32m219\x1b[m- await nvim.call('cursor', [1, 4]) -\x1b[32m220\x1b[m: await nvim.input('\x1b[31mabc\x1b[m') -\x1b[32m221\x1b[m- await helper.wait(30) -\x1b[32m222\x1b[m- doc.forceSync() -\x1b[32m223\x1b[m- await helper.wait(100) -\x1b[32m224\x1b[m- let lines = await nvim.call('getline', [1, '$']) -\x1b[32m225\x1b[m: expect(lines).toEqual(['\x1b[31mabc\x1b[m fooabc fooabc', 'barabc barabc']) -\x1b[32m226\x1b[m- }) -\x1b[32m227\x1b[m- --- -\x1b[32m32\x1b[m- expect(rangeCount()).toBe(5) -\x1b[32m33\x1b[m- let lines = await nvim.call('getline', [1, '$']) -\x1b[32m34\x1b[m: expect(lines).toEqual(['\x1b[31mabc\x1b[m fooabc fooabc', 'barabc barabc']) -\x1b[32m35\x1b[m- }) -\x1b[32m36\x1b[m- - -\x1b[30mmodules/position.test.ts\x1b[m -\x1b[32m42\x1b[m- test('getChangedPosition #1', () => { -\x1b[32m43\x1b[m- let pos = Position.create(0, 0) -\x1b[32m44\x1b[m: let edit = TextEdit.insert(pos, '\x1b[31mabc\x1b[m') -\x1b[32m45\x1b[m- let res = getChangedPosition(pos, edit) -\x1b[32m46\x1b[m- expect(res).toEqual({ line: 0, character: 3 }) -` - -let idx = process.argv.findIndex(s => s == '--sleep') -if (idx !== -1) { - let ms = process.argv[idx + 1] - setTimeout(() => { - process.stdout.write(content) - }, ms) -} else { - process.stdout.write(content) -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/sample/.vim/coc-settings.json b/vim-config/plugins/coc.nvim/src/__tests__/sample/.vim/coc-settings.json deleted file mode 100644 index 745333b2..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/sample/.vim/coc-settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "coc.preferences.rootPath": "./src" -} diff --git a/vim-config/plugins/coc.nvim/src/__tests__/snippets/manager.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/snippets/manager.test.ts deleted file mode 100644 index a90db5a9..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/snippets/manager.test.ts +++ /dev/null @@ -1,306 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import path from 'path' -import { Range } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import Document from '../../model/document' -import snippetManager from '../../snippets/manager' -import { SnippetString } from '../../snippets/string' -import workspace from '../../workspace' -import helper from '../helper' - -let nvim: Neovim -let doc: Document -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -beforeEach(async () => { - doc = await helper.createDocument() -}) - -describe('snippet provider', () => { - describe('insertSnippet()', () => { - it('should not active when insert plain snippet', async () => { - await snippetManager.insertSnippet('foo') - let line = await nvim.line - expect(line).toBe('foo') - expect(snippetManager.session).toBe(null) - expect(snippetManager.getSession(doc.bufnr)).toBeUndefined() - expect(snippetManager.isActived(doc.bufnr)).toBe(false) - }) - - it('should resolve variables', async () => { - await snippetManager.insertSnippet('${foo:abcdef} ${bar}') - let line = await nvim.line - expect(line).toBe('abcdef bar') - }) - - it('should start new session if session exists', async () => { - await nvim.setLine('bar') - await snippetManager.insertSnippet('${1:foo} ') - await helper.wait(100) - await nvim.input('') - await nvim.command('stopinsert') - await nvim.input('A') - await helper.wait(100) - let active = await snippetManager.insertSnippet('${2:bar}') - expect(active).toBe(true) - let line = await nvim.getLine() - expect(line).toBe('foo barbar') - }) - - it('should start nest session', async () => { - await snippetManager.insertSnippet('${1:foo} ${2:bar}') - await nvim.input('') - await helper.wait(100) - let active = await snippetManager.insertSnippet('${1:x} $1') - expect(active).toBe(true) - }) - - it('should not consider plaintext as placeholder', async () => { - await snippetManager.insertSnippet('${1} ${2:bar}') - await nvim.input('$foo;') - await helper.wait(100) - await snippetManager.insertSnippet('${1:x}', false, Range.create(0, 5, 0, 6)) - await helper.wait(100) - let line = await nvim.line - expect(line).toBe('$foo;xbar') - }) - - it('should insert nest plain snippet', async () => { - await snippetManager.insertSnippet('${1:foo} ${2:bar}') - await nvim.input('') - await helper.wait(100) - let active = await snippetManager.insertSnippet('bar') - expect(active).toBe(true) - let cursor = await nvim.call('coc#cursor#position') - expect(cursor).toEqual([0, 3]) - }) - - it('should work with nest snippet', async () => { - let buf = await helper.edit() - let snip = '
    \n$0\n' - await snippetManager.insertSnippet(snip) - await helper.wait(30) - await nvim.input('abcde') - await helper.wait(100) - let lines = await buf.lines - expect(lines).toEqual(['', '', '']) - }) - - it('should insert snippetString', async () => { - let snippetString = new SnippetString() - .appendTabstop(1) - .appendText(' ') - .appendPlaceholder('bar', 2) - await snippetManager.insertSnippet(snippetString) - await nvim.input('$foo;') - await helper.wait(100) - snippetString = new SnippetString() - .appendVariable('foo', 'x') - await snippetManager.insertSnippet(snippetString, false, Range.create(0, 5, 0, 6)) - await helper.wait(100) - let line = await nvim.line - expect(line).toBe('$foo;xbar') - }) - }) - - describe('nextPlaceholder()', () => { - it('should goto next placeholder', async () => { - await snippetManager.insertSnippet('${1:a} ${2:b}') - await snippetManager.nextPlaceholder() - await helper.wait(30) - let col = await nvim.call('col', '.') - expect(col).toBe(3) - }) - - it('should remove keymap on nextPlaceholder when session not exits', async () => { - await nvim.call('coc#snippet#enable') - await snippetManager.nextPlaceholder() - await helper.wait(60) - let val = await doc.buffer.getVar('coc_snippet_active') - expect(val).toBe(0) - }) - }) - - describe('previousPlaceholder()', () => { - it('should goto previous placeholder', async () => { - await snippetManager.insertSnippet('${1:a} ${2:b}') - await snippetManager.nextPlaceholder() - await snippetManager.previousPlaceholder() - let col = await nvim.call('col', '.') - expect(col).toBe(1) - }) - - it('should remove keymap on previousPlaceholder when session not exits', async () => { - await nvim.call('coc#snippet#enable') - await snippetManager.previousPlaceholder() - await helper.wait(60) - let val = await doc.buffer.getVar('coc_snippet_active') - expect(val).toBe(0) - }) - }) - - describe('Events', () => { - it('should check position on InsertEnter', async () => { - await nvim.input('ibar') - await snippetManager.insertSnippet('${1:foo} $1 ') - await helper.wait(60) - await nvim.input('A') - await helper.wait(60) - expect(snippetManager.session).toBeNull() - }) - - }) - - describe('cancel()', () => { - it('should cancel snippet session', async () => { - let buffer = doc.buffer - await nvim.call('coc#snippet#enable') - snippetManager.cancel() - await helper.wait(60) - let val = await buffer.getVar('coc_snippet_active') - expect(val).toBe(0) - let active = await snippetManager.insertSnippet('${1:foo}') - expect(active).toBe(true) - snippetManager.cancel() - expect(snippetManager.session).toBeNull() - }) - }) - - describe('configuration', () => { - it('should respect preferCompleteThanJumpPlaceholder', async () => { - let config = workspace.getConfiguration('suggest') - config.update('preferCompleteThanJumpPlaceholder', true) - await nvim.setLine('foo') - await nvim.input('o') - await snippetManager.insertSnippet('${1:foo} ${2:bar}') - await helper.wait(10) - await nvim.input('f') - await helper.waitPopup() - await nvim.input('') - await helper.wait(200) - let line = await nvim.getLine() - expect(line).toBe('foo bar') - config.update('preferCompleteThanJumpPlaceholder', false) - }) - }) - - describe('jumpable()', () => { - it('should check jumpable', async () => { - await nvim.input('i') - await snippetManager.insertSnippet('${1:foo} ${2:bar}') - let jumpable = snippetManager.jumpable() - expect(jumpable).toBe(true) - await snippetManager.nextPlaceholder() - await helper.wait(30) - await snippetManager.nextPlaceholder() - await helper.wait(30) - jumpable = snippetManager.jumpable() - expect(jumpable).toBe(false) - }) - }) - - describe('synchronize text', () => { - it('should update placeholder on placeholder update', async () => { - await snippetManager.insertSnippet('$1\n${1/,/,\\n/g}') - await nvim.input('a,b') - await helper.wait(50) - doc.forceSync() - await helper.wait(200) - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(['a,b', 'a,', 'b']) - }) - - it('should adjust cursor position on update', async () => { - await nvim.input('i') - await snippetManager.insertSnippet('${1/..*/ -> /}$1') - let line = await nvim.line - expect(line).toBe('') - await helper.wait(60) - await nvim.input('x') - await helper.wait(400) - line = await nvim.line - expect(line).toBe(' -> x') - let col = await nvim.call('col', '.') - expect(col).toBe(6) - }) - - it('should synchronize text on change final placeholder', async () => { - await nvim.command('startinsert') - let res = await snippetManager.insertSnippet('$0empty$0') - expect(res).toBe(true) - await nvim.input('abc') - await nvim.input('') - await helper.wait(50) - await doc.patchChange() - let line = await nvim.line - expect(line).toBe('abcemptyabc') - }) - - it('should fix edit to current placeholder', async () => { - await nvim.command('startinsert') - let res = await snippetManager.insertSnippet('()$1$0', true) - expect(res).toBe(true) - await nvim.input('(') - await nvim.input(')') - await nvim.input('') - await helper.wait(50) - await doc.patchChange() - await helper.wait(200) - expect(snippetManager.session).toBeDefined() - }) - }) - - describe('resolveSnippet', () => { - it('should resolve snippet', async () => { - let fsPath = URI.parse(doc.uri).fsPath - let res = await snippetManager.resolveSnippet(`$TM_FILENAME`) - expect(res.toString()).toBe(path.basename(fsPath)) - res = await snippetManager.resolveSnippet(`$TM_FILENAME_BASE`) - expect(res.toString()).toBe(path.basename(fsPath, path.extname(fsPath))) - res = await snippetManager.resolveSnippet(`$TM_DIRECTORY`) - expect(res.toString()).toBe(path.dirname(fsPath)) - res = await snippetManager.resolveSnippet(`$TM_FILEPATH`) - expect(res.toString()).toBe(fsPath) - await nvim.call('setreg', ['""', 'foo']) - res = await snippetManager.resolveSnippet(`$YANK`) - expect(res.toString()).toBe('foo') - res = await snippetManager.resolveSnippet(`$TM_LINE_INDEX`) - expect(res.toString()).toBe('0') - res = await snippetManager.resolveSnippet(`$TM_LINE_NUMBER`) - expect(res.toString()).toBe('1') - await nvim.setLine('foo') - res = await snippetManager.resolveSnippet(`$TM_CURRENT_LINE`) - expect(res.toString()).toBe('foo') - res = await snippetManager.resolveSnippet(`$TM_CURRENT_WORD`) - expect(res.toString()).toBe('foo') - await nvim.call('setreg', ['*', 'foo']) - res = await snippetManager.resolveSnippet(`$CLIPBOARD`) - expect(res.toString()).toBe('foo') - let d = new Date() - res = await snippetManager.resolveSnippet(`$CURRENT_YEAR`) - expect(res.toString()).toBe(d.getFullYear().toString()) - res = await snippetManager.resolveSnippet(`$NOT_EXISTS`) - expect(res.toString()).toBe('NOT_EXISTS') - }) - }) - - describe('dispose()', () => { - it('should dispose', async () => { - let active = await snippetManager.insertSnippet('${1:foo}') - expect(active).toBe(true) - snippetManager.dispose() - expect(snippetManager.session).toBe(null) - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/snippets/parser.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/snippets/parser.test.ts deleted file mode 100644 index 307a17f9..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/snippets/parser.test.ts +++ /dev/null @@ -1,780 +0,0 @@ -/* eslint-disable */ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -import * as assert from 'assert' -import { Scanner, TokenType, SnippetParser, Text, Placeholder, Variable, Marker, TextmateSnippet, Choice, FormatString, Transform } from '../../snippets/parser' -import { Range } from 'vscode-languageserver-types' - -describe('SnippetParser', () => { - - test('Scanner', () => { - - const scanner = new Scanner() - assert.equal(scanner.next().type, TokenType.EOF) - - scanner.text('abc') - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.EOF) - - scanner.text('{{abc}}') - assert.equal(scanner.next().type, TokenType.CurlyOpen) - assert.equal(scanner.next().type, TokenType.CurlyOpen) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.CurlyClose) - assert.equal(scanner.next().type, TokenType.CurlyClose) - assert.equal(scanner.next().type, TokenType.EOF) - - scanner.text('abc() ') - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.Format) - assert.equal(scanner.next().type, TokenType.EOF) - - scanner.text('abc 123') - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.Format) - assert.equal(scanner.next().type, TokenType.Int) - assert.equal(scanner.next().type, TokenType.EOF) - - scanner.text('$foo') - assert.equal(scanner.next().type, TokenType.Dollar) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.EOF) - - scanner.text('$foo_bar') - assert.equal(scanner.next().type, TokenType.Dollar) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.EOF) - - scanner.text('$foo-bar') - assert.equal(scanner.next().type, TokenType.Dollar) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.Dash) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.EOF) - - scanner.text('${foo}') - assert.equal(scanner.next().type, TokenType.Dollar) - assert.equal(scanner.next().type, TokenType.CurlyOpen) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.CurlyClose) - assert.equal(scanner.next().type, TokenType.EOF) - - scanner.text('${1223:foo}') - assert.equal(scanner.next().type, TokenType.Dollar) - assert.equal(scanner.next().type, TokenType.CurlyOpen) - assert.equal(scanner.next().type, TokenType.Int) - assert.equal(scanner.next().type, TokenType.Colon) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.CurlyClose) - assert.equal(scanner.next().type, TokenType.EOF) - - scanner.text('\\${}') - assert.equal(scanner.next().type, TokenType.Backslash) - assert.equal(scanner.next().type, TokenType.Dollar) - assert.equal(scanner.next().type, TokenType.CurlyOpen) - assert.equal(scanner.next().type, TokenType.CurlyClose) - - scanner.text('${foo/regex/format/option}') - assert.equal(scanner.next().type, TokenType.Dollar) - assert.equal(scanner.next().type, TokenType.CurlyOpen) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.Forwardslash) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.Forwardslash) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.Forwardslash) - assert.equal(scanner.next().type, TokenType.VariableName) - assert.equal(scanner.next().type, TokenType.CurlyClose) - assert.equal(scanner.next().type, TokenType.EOF) - }) - - function assertText(value: string, expected: string) { - const p = new SnippetParser() - const actual = p.text(value) - assert.equal(actual, expected) - } - - function assertMarker(input: TextmateSnippet | Marker[] | string, ...ctors: Function[]) { - let marker: Marker[] - if (input instanceof TextmateSnippet) { - marker = input.children - } else if (typeof input === 'string') { - const p = new SnippetParser() - marker = p.parse(input).children - } else { - marker = input - } - while (marker.length > 0) { - let m = marker.pop() - let ctor = ctors.pop() - assert.ok(m instanceof ctor) - } - assert.equal(marker.length, ctors.length) - assert.equal(marker.length, 0) - } - - function assertTextAndMarker(value: string, escaped: string, ...ctors: Function[]) { - assertText(value, escaped) - assertMarker(value, ...ctors) - } - - function assertEscaped(value: string, expected: string) { - const actual = SnippetParser.escape(value) - assert.equal(actual, expected) - } - - test('Parser, escaped', function() { - assertEscaped('foo$0', 'foo\\$0') - assertEscaped('foo\\$0', 'foo\\\\\\$0') - assertEscaped('f$1oo$0', 'f\\$1oo\\$0') - assertEscaped('${1:foo}$0', '\\${1:foo\\}\\$0') - assertEscaped('$', '\\$') - }) - - test('Parser, text', () => { - assertText('$', '$') - assertText('\\\\$', '\\$') - assertText('{', '{') - assertText('\\}', '}') - assertText('\\abc', '\\abc') - assertText('foo${f:\\}}bar', 'foo}bar') - assertText('\\{', '\\{') - assertText('I need \\\\\\$', 'I need \\$') - assertText('\\', '\\') - assertText('\\{{', '\\{{') - assertText('{{', '{{') - assertText('{{dd', '{{dd') - assertText('}}', '}}') - assertText('ff}}', 'ff}}') - - assertText('farboo', 'farboo') - assertText('far{{}}boo', 'far{{}}boo') - assertText('far{{123}}boo', 'far{{123}}boo') - assertText('far\\{{123}}boo', 'far\\{{123}}boo') - assertText('far{{id:bern}}boo', 'far{{id:bern}}boo') - assertText('far{{id:bern {{basel}}}}boo', 'far{{id:bern {{basel}}}}boo') - assertText('far{{id:bern {{id:basel}}}}boo', 'far{{id:bern {{id:basel}}}}boo') - assertText('far{{id:bern {{id2:basel}}}}boo', 'far{{id:bern {{id2:basel}}}}boo') - }) - - - test('Parser, TM text', () => { - assertTextAndMarker('foo${1:bar}}', 'foobar}', Text, Placeholder, Text) - assertTextAndMarker('foo${1:bar}${2:foo}}', 'foobarfoo}', Text, Placeholder, Placeholder, Text) - - assertTextAndMarker('foo${1:bar\\}${2:foo}}', 'foobar}foo', Text, Placeholder) - - let [, placeholder] = new SnippetParser().parse('foo${1:bar\\}${2:foo}}').children - let { children } = (placeholder) - - assert.equal((placeholder).index, '1') - assert.ok(children[0] instanceof Text) - assert.equal(children[0].toString(), 'bar}') - assert.ok(children[1] instanceof Placeholder) - assert.equal(children[1].toString(), 'foo') - }) - - test('Parser, placeholder', () => { - assertTextAndMarker('farboo', 'farboo', Text) - assertTextAndMarker('far{{}}boo', 'far{{}}boo', Text) - assertTextAndMarker('far{{123}}boo', 'far{{123}}boo', Text) - assertTextAndMarker('far\\{{123}}boo', 'far\\{{123}}boo', Text) - }) - - test('Parser, literal code', () => { - assertTextAndMarker('far`123`boo', 'far`123`boo', Text) - assertTextAndMarker('far\\`123\\`boo', 'far\\`123\\`boo', Text) - }) - - test('Parser, variables/tabstop', () => { - assertTextAndMarker('$far-boo', '-boo', Variable, Text) - assertTextAndMarker('\\$far-boo', '$far-boo', Text) - assertTextAndMarker('far$farboo', 'far', Text, Variable) - assertTextAndMarker('far${farboo}', 'far', Text, Variable) - assertTextAndMarker('$123', '', Placeholder) - assertTextAndMarker('$farboo', '', Variable) - assertTextAndMarker('$far12boo', '', Variable) - assertTextAndMarker('000_${far}_000', '000__000', Text, Variable, Text) - assertTextAndMarker('FFF_${TM_SELECTED_TEXT}_FFF$0', 'FFF__FFF', Text, Variable, Text, Placeholder) - }) - - test('Parser, variables/placeholder with defaults', () => { - assertTextAndMarker('${name:value}', 'value', Variable) - assertTextAndMarker('${1:value}', 'value', Placeholder) - assertTextAndMarker('${1:bar${2:foo}bar}', 'barfoobar', Placeholder) - - assertTextAndMarker('${name:value', '${name:value', Text) - assertTextAndMarker('${1:bar${2:foobar}', '${1:barfoobar', Text, Placeholder) - }) - - test('Parser, variable transforms', function() { - assertTextAndMarker('${foo///}', '', Variable) - assertTextAndMarker('${foo/regex/format/gmi}', '', Variable) - assertTextAndMarker('${foo/([A-Z][a-z])/format/}', '', Variable) - - // invalid regex - assertTextAndMarker('${foo/([A-Z][a-z])/format/GMI}', '${foo/([A-Z][a-z])/format/GMI}', Text) - assertTextAndMarker('${foo/([A-Z][a-z])/format/funky}', '${foo/([A-Z][a-z])/format/funky}', Text) - assertTextAndMarker('${foo/([A-Z][a-z]/format/}', '${foo/([A-Z][a-z]/format/}', Text) - - // tricky regex - assertTextAndMarker('${foo/m\\/atch/$1/i}', '', Variable) - assertMarker('${foo/regex\/format/options}', Text) - - // incomplete - assertTextAndMarker('${foo///', '${foo///', Text) - assertTextAndMarker('${foo/regex/format/options', '${foo/regex/format/options', Text) - - // format string - assertMarker('${foo/.*/${0:fooo}/i}', Variable) - assertMarker('${foo/.*/${1}/i}', Variable) - assertMarker('${foo/.*/$1/i}', Variable) - assertMarker('${foo/.*/This-$1-encloses/i}', Variable) - assertMarker('${foo/.*/complex${1:else}/i}', Variable) - assertMarker('${foo/.*/complex${1:-else}/i}', Variable) - assertMarker('${foo/.*/complex${1:+if}/i}', Variable) - assertMarker('${foo/.*/complex${1:?if:else}/i}', Variable) - assertMarker('${foo/.*/complex${1:/upcase}/i}', Variable) - - }) - - test('Parser, placeholder with transform', () => { - const p = new SnippetParser() - const snippet = p.parse('${1:type}${1/(.+)/ /}') - let s = snippet.toString() - assert.equal(s.length, 5) - }) - - test('Parser, placeholder transforms', function() { - assertTextAndMarker('${1///}', '', Placeholder) - assertTextAndMarker('${1/regex/format/gmi}', '', Placeholder) - assertTextAndMarker('${1/([A-Z][a-z])/format/}', '', Placeholder) - assertTextAndMarker('${1///}', '', Placeholder) - - // tricky regex - assertTextAndMarker('${1/m\\/atch/$1/i}', '', Placeholder) - assertMarker('${1/regex\/format/options}', Text) - - // incomplete - assertTextAndMarker('${1///', '${1///', Text) - assertTextAndMarker('${1/regex/format/options', '${1/regex/format/options', Text) - }) - - test('No way to escape forward slash in snippet regex #36715', function() { - assertMarker('${TM_DIRECTORY/src\\//$1/}', Variable) - }) - - test('No way to escape forward slash in snippet format section #37562', function() { - assertMarker('${TM_SELECTED_TEXT/a/\\/$1/g}', Variable) - assertMarker('${TM_SELECTED_TEXT/a/in\\/$1ner/g}', Variable) - assertMarker('${TM_SELECTED_TEXT/a/end\\//g}', Variable) - }) - - test('Parser, placeholder with choice', () => { - - assertTextAndMarker('${1|one,two,three|}', 'one', Placeholder) - assertTextAndMarker('${1|one|}', 'one', Placeholder) - assertTextAndMarker('${1|one1,two2|}', 'one1', Placeholder) - assertTextAndMarker('${1|one1\\,two2|}', 'one1,two2', Placeholder) - assertTextAndMarker('${1|one1\\|two2|}', 'one1|two2', Placeholder) - assertTextAndMarker('${1|one1\\atwo2|}', 'one1\\atwo2', Placeholder) - assertTextAndMarker('${1|one,two,three,|}', '${1|one,two,three,|}', Text) - assertTextAndMarker('${1|one,', '${1|one,', Text) - - const p = new SnippetParser() - const snippet = p.parse('${1|one,two,three|}') - assertMarker(snippet, Placeholder) - const expected = [Placeholder, Text, Text, Text] - snippet.walk(marker => { - assert.equal(marker, expected.shift()) - return true - }) - }) - - test('Snippet choices: unable to escape comma and pipe, #31521', function() { - assertTextAndMarker('console.log(${1|not\\, not, five, 5, 1 23|});', 'console.log(not, not);', Text, Placeholder, Text) - }) - - test('Marker, toTextmateString()', function() { - - function assertTextsnippetString(input: string, expected: string): void { - const snippet = new SnippetParser().parse(input) - const actual = snippet.toTextmateString() - assert.equal(actual, expected) - } - - assertTextsnippetString('$1', '$1') - assertTextsnippetString('\\$1', '\\$1') - assertTextsnippetString('console.log(${1|not\\, not, five, 5, 1 23|});', 'console.log(${1|not\\, not, five, 5, 1 23|});') - assertTextsnippetString('console.log(${1|not\\, not, \\| five, 5, 1 23|});', 'console.log(${1|not\\, not, \\| five, 5, 1 23|});') - assertTextsnippetString('this is text', 'this is text') - assertTextsnippetString('this ${1:is ${2:nested with $var}}', 'this ${1:is ${2:nested with ${var}}}') - assertTextsnippetString('this ${1:is ${2:nested with $var}}}', 'this ${1:is ${2:nested with ${var}}}\\}') - }) - - test('Marker, toTextmateString() <-> identity', function() { - - function assertIdent(input: string): void { - // full loop: (1) parse input, (2) generate textmate string, (3) parse, (4) ensure both trees are equal - const snippet = new SnippetParser().parse(input) - const input2 = snippet.toTextmateString() - const snippet2 = new SnippetParser().parse(input2) - - function checkCheckChildren(marker1: Marker, marker2: Marker) { - assert.ok(marker1 instanceof Object.getPrototypeOf(marker2).constructor) - assert.ok(marker2 instanceof Object.getPrototypeOf(marker1).constructor) - - assert.equal(marker1.children.length, marker2.children.length) - assert.equal(marker1.toString(), marker2.toString()) - - for (let i = 0; i < marker1.children.length; i++) { - checkCheckChildren(marker1.children[i], marker2.children[i]) - } - } - - checkCheckChildren(snippet, snippet2) - } - - assertIdent('$1') - assertIdent('\\$1') - assertIdent('console.log(${1|not\\, not, five, 5, 1 23|});') - assertIdent('console.log(${1|not\\, not, \\| five, 5, 1 23|});') - assertIdent('this is text') - assertIdent('this ${1:is ${2:nested with $var}}') - assertIdent('this ${1:is ${2:nested with $var}}}') - assertIdent('this ${1:is ${2:nested with $var}} and repeating $1') - }) - - test('Parser, choise marker', () => { - const { placeholders } = new SnippetParser().parse('${1|one,two,three|}') - - assert.equal(placeholders.length, 1) - assert.ok(placeholders[0].choice instanceof Choice) - assert.ok(placeholders[0].children[0] instanceof Choice) - assert.equal((placeholders[0].children[0]).options.length, 3) - - assertText('${1|one,two,three|}', 'one') - assertText('\\${1|one,two,three|}', '${1|one,two,three|}') - assertText('${1\\|one,two,three|}', '${1\\|one,two,three|}') - assertText('${1||}', '${1||}') - }) - - test('Backslash character escape in choice tabstop doesn\'t work #58494', function() { - - const { placeholders } = new SnippetParser().parse('${1|\\,,},$,\\|,\\\\|}') - assert.equal(placeholders.length, 1) - assert.ok(placeholders[0].choice instanceof Choice) - }) - - test('Parser, only textmate', () => { - const p = new SnippetParser() - assertMarker(p.parse('far{{}}boo'), Text) - assertMarker(p.parse('far{{123}}boo'), Text) - assertMarker(p.parse('far\\{{123}}boo'), Text) - - assertMarker(p.parse('far$0boo'), Text, Placeholder, Text) - assertMarker(p.parse('far${123}boo'), Text, Placeholder, Text) - assertMarker(p.parse('far\\${123}boo'), Text) - }) - - test('Parser, real world', () => { - let marker = new SnippetParser().parse('console.warn(${1: $TM_SELECTED_TEXT })').children - - assert.equal(marker[0].toString(), 'console.warn(') - assert.ok(marker[1] instanceof Placeholder) - assert.equal(marker[2].toString(), ')') - - const placeholder = marker[1] - assert.equal(placeholder, false) - assert.equal(placeholder.index, '1') - assert.equal(placeholder.children.length, 3) - assert.ok(placeholder.children[0] instanceof Text) - assert.ok(placeholder.children[1] instanceof Variable) - assert.ok(placeholder.children[2] instanceof Text) - assert.equal(placeholder.children[0].toString(), ' ') - assert.equal(placeholder.children[1].toString(), '') - assert.equal(placeholder.children[2].toString(), ' ') - - const nestedVariable = placeholder.children[1] - assert.equal(nestedVariable.name, 'TM_SELECTED_TEXT') - assert.equal(nestedVariable.children.length, 0) - - marker = new SnippetParser().parse('$TM_SELECTED_TEXT').children - assert.equal(marker.length, 1) - assert.ok(marker[0] instanceof Variable) - }) - - test('Parser, transform example', () => { - let { children } = new SnippetParser().parse('${1:name} : ${2:type}${3/\\s:=(.*)/${1:+ :=}${1}/};\n$0') - - //${1:name} - assert.ok(children[0] instanceof Placeholder) - assert.equal(children[0].children.length, 1) - assert.equal(children[0].children[0].toString(), 'name') - assert.equal((children[0]).transform, undefined) - - // : - assert.ok(children[1] instanceof Text) - assert.equal(children[1].toString(), ' : ') - - //${2:type} - assert.ok(children[2] instanceof Placeholder) - assert.equal(children[2].children.length, 1) - assert.equal(children[2].children[0].toString(), 'type') - - //${3/\\s:=(.*)/${1:+ :=}${1}/} - assert.ok(children[3] instanceof Placeholder) - assert.equal(children[3].children.length, 0) - assert.notEqual((children[3]).transform, undefined) - let transform = (children[3]).transform - assert.equal(transform.regexp, '/\\s:=(.*)/') - assert.equal(transform.children.length, 2) - assert.ok(transform.children[0] instanceof FormatString) - assert.equal((transform.children[0]).index, 1) - assert.equal((transform.children[0]).ifValue, ' :=') - assert.ok(transform.children[1] instanceof FormatString) - assert.equal((transform.children[1]).index, 1) - assert.ok(children[4] instanceof Text) - assert.equal(children[4].toString(), ';\n') - - }) - - test('Parser, default placeholder values', () => { - - assertMarker('errorContext: `${1:err}`, error: $1', Text, Placeholder, Text, Placeholder) - - const [, p1, , p2] = new SnippetParser().parse('errorContext: `${1:err}`, error:$1').children - - assert.equal((p1).index, '1') - assert.equal((p1).children.length, '1') - assert.equal(((p1).children[0]), 'err') - - assert.equal((p2).index, '1') - assert.equal((p2).children.length, '1') - assert.equal(((p2).children[0]), 'err') - }) - - test('Parser, default placeholder values and one transform', () => { - - assertMarker('errorContext: `${1:err}`, error: ${1/err/ok/}', Text, Placeholder, Text, Placeholder) - - const [, p3, , p4] = new SnippetParser().parse('errorContext: `${1:err}`, error:${1/err/ok/}').children - - assert.equal((p3).index, '1') - assert.equal((p3).children.length, '1') - assert.equal(((p3).children[0]), 'err') - assert.equal((p3).transform, undefined) - - assert.equal((p4).index, '1') - assert.equal((p4).children.length, '1') - assert.equal(((p4).children[0]), 'ok') - assert.notEqual((p4).transform, undefined) - }) - - test('Repeated snippet placeholder should always inherit, #31040', function() { - assertText('${1:foo}-abc-$1', 'foo-abc-foo') - assertText('${1:foo}-abc-${1}', 'foo-abc-foo') - assertText('${1:foo}-abc-${1:bar}', 'foo-abc-foo') - assertText('${1}-abc-${1:foo}', 'foo-abc-foo') - }) - - test('backspace esapce in TM only, #16212', () => { - const actual = new SnippetParser().text('Foo \\\\${abc}bar') - assert.equal(actual, 'Foo \\bar') - }) - - test('colon as variable/placeholder value, #16717', () => { - let actual = new SnippetParser().text('${TM_SELECTED_TEXT:foo:bar}') - assert.equal(actual, 'foo:bar') - - actual = new SnippetParser().text('${1:foo:bar}') - assert.equal(actual, 'foo:bar') - }) - - test('incomplete placeholder', () => { - assertTextAndMarker('${1:}', '', Placeholder) - }) - - test('marker#len', () => { - - function assertLen(template: string, ...lengths: number[]): void { - const snippet = new SnippetParser().parse(template, true) - snippet.walk(m => { - const expected = lengths.shift() - assert.equal(m.len(), expected) - return true - }) - assert.equal(lengths.length, 0) - } - - assertLen('text$0', 4, 0) - assertLen('$1text$0', 0, 4, 0) - assertLen('te$1xt$0', 2, 0, 2, 0) - assertLen('errorContext: `${1:err}`, error: $0', 15, 0, 3, 10, 0) - assertLen('errorContext: `${1:err}`, error: $1$0', 15, 0, 3, 10, 0, 3, 0) - assertLen('$TM_SELECTED_TEXT$0', 0, 0) - assertLen('${TM_SELECTED_TEXT:def}$0', 0, 3, 0) - }) - - test('parser, parent node', function() { - let snippet = new SnippetParser().parse('This ${1:is ${2:nested}}$0', true) - - assert.equal(snippet.placeholders.length, 3) - let [first, second] = snippet.placeholders - assert.equal(first.index, '1') - assert.equal(second.index, '2') - assert.ok(second.parent === first) - assert.ok(first.parent === snippet) - - snippet = new SnippetParser().parse('${VAR:default${1:value}}$0', true) - assert.equal(snippet.placeholders.length, 2) - ;[first] = snippet.placeholders - assert.equal(first.index, '1') - - assert.ok(snippet.children[0] instanceof Variable) - assert.ok(first.parent === snippet.children[0]) - }) - - test('TextmateSnippet#enclosingPlaceholders', () => { - let snippet = new SnippetParser().parse('This ${1:is ${2:nested}}$0', true) - let [first, second] = snippet.placeholders - - assert.deepEqual(snippet.enclosingPlaceholders(first), []) - assert.deepEqual(snippet.enclosingPlaceholders(second), [first]) - }) - - test('TextmateSnippet#offset', () => { - let snippet = new SnippetParser().parse('te$1xt', true) - assert.equal(snippet.offset(snippet.children[0]), 0) - assert.equal(snippet.offset(snippet.children[1]), 2) - assert.equal(snippet.offset(snippet.children[2]), 2) - - snippet = new SnippetParser().parse('${TM_SELECTED_TEXT:def}', true) - assert.equal(snippet.offset(snippet.children[0]), 0) - assert.equal(snippet.offset((snippet.children[0]).children[0]), 0) - - // forgein marker - assert.equal(snippet.offset(new Text('foo')), -1) - }) - - test('TextmateSnippet#placeholder', () => { - let snippet = new SnippetParser().parse('te$1xt$0', true) - let placeholders = snippet.placeholders - assert.equal(placeholders.length, 2) - - snippet = new SnippetParser().parse('te$1xt$1$0', true) - placeholders = snippet.placeholders - assert.equal(placeholders.length, 3) - - - snippet = new SnippetParser().parse('te$1xt$2$0', true) - placeholders = snippet.placeholders - assert.equal(placeholders.length, 3) - - snippet = new SnippetParser().parse('${1:bar${2:foo}bar}$0', true) - placeholders = snippet.placeholders - assert.equal(placeholders.length, 3) - }) - - test('TextmateSnippet#replace 1/2', function() { - let snippet = new SnippetParser().parse('aaa${1:bbb${2:ccc}}$0', true) - - assert.equal(snippet.placeholders.length, 3) - const [, second] = snippet.placeholders - assert.equal(second.index, '2') - - const enclosing = snippet.enclosingPlaceholders(second) - assert.equal(enclosing.length, 1) - assert.equal(enclosing[0].index, '1') - - let nested = new SnippetParser().parse('ddd$1eee$0', true) - snippet.replace(second, nested.children) - - assert.equal(snippet.toString(), 'aaabbbdddeee') - assert.equal(snippet.placeholders.length, 4) - assert.equal(snippet.placeholders[0].index, '1') - assert.equal(snippet.placeholders[1].index, '1') - assert.equal(snippet.placeholders[2].index, '0') - assert.equal(snippet.placeholders[3].index, '0') - - const newEnclosing = snippet.enclosingPlaceholders(snippet.placeholders[1]) - assert.ok(newEnclosing[0] === snippet.placeholders[0]) - assert.equal(newEnclosing.length, 1) - assert.equal(newEnclosing[0].index, '1') - }) - - test('TextmateSnippet#replace 2/2', function() { - let snippet = new SnippetParser().parse('aaa${1:bbb${2:ccc}}$0', true) - - assert.equal(snippet.placeholders.length, 3) - const [, second] = snippet.placeholders - assert.equal(second.index, '2') - - let nested = new SnippetParser().parse('dddeee$0', true) - snippet.replace(second, nested.children) - - assert.equal(snippet.toString(), 'aaabbbdddeee') - assert.equal(snippet.placeholders.length, 3) - }) - - test('TextmateSnippet#insertSnippet', function() { - let snippet = new SnippetParser().parse('${1:aaa} ${1:aaa} bbb ${2:ccc}}$0', true) - snippet.insertSnippet('|${1:dd} ${2:ff}|', 1, Range.create(0, 0, 0, 0)) - const [one, two, three] = snippet.placeholders - assert.equal(one.index, 1) - assert.equal(one.toString(), 'aaa') - assert.equal(two.index, 2) - assert.equal(two.toString(), 'dd') - assert.equal(three.index, 3) - assert.equal(three.toString(), 'ff') - }) - - test('TextmateSnippet#updatePlaceholder', function() { - let snippet = new SnippetParser().parse('aaa${1:bbb} ${1:bbb}', true) - snippet.updatePlaceholder(0, 'ccc') - let p = snippet.placeholders[0] - assert.equal(p.toString(), 'ccc') - }) - - test('Snippet order for placeholders, #28185', function() { - - const _10 = new Placeholder(10) - const _2 = new Placeholder(2) - - assert.equal(Placeholder.compareByIndex(_10, _2), 1) - }) - - test('Maximum call stack size exceeded, #28983', function() { - new SnippetParser().parse('${1:${foo:${1}}}') - }) - - test('Snippet can freeze the editor, #30407', function() { - - const seen = new Set() - - seen.clear() - new SnippetParser().parse('class ${1:${TM_FILENAME/(?:\\A|_)([A-Za-z0-9]+)(?:\\.rb)?/(?2::\\u$1)/g}} < ${2:Application}Controller\n $3\nend').walk(marker => { - assert.ok(!seen.has(marker)) - seen.add(marker) - return true - }) - - seen.clear() - new SnippetParser().parse('${1:${FOO:abc$1def}}').walk(marker => { - assert.ok(!seen.has(marker)) - seen.add(marker) - return true - }) - }) - - test('Snippets: make parser ignore `${0|choice|}`, #31599', function() { - assertTextAndMarker('${0|foo,bar|}', '${0|foo,bar|}', Text) - assertTextAndMarker('${1|foo,bar|}', 'foo', Placeholder) - }) - - - test('Transform -> FormatString#resolve', function() { - - // shorthand functions - assert.equal(new FormatString(1, 'upcase').resolve('foo'), 'FOO') - assert.equal(new FormatString(1, 'downcase').resolve('FOO'), 'foo') - assert.equal(new FormatString(1, 'capitalize').resolve('bar'), 'Bar') - assert.equal(new FormatString(1, 'capitalize').resolve('bar no repeat'), 'Bar no repeat') - assert.equal(new FormatString(1, 'pascalcase').resolve('bar-foo'), 'BarFoo') - assert.equal(new FormatString(1, 'notKnown').resolve('input'), 'input') - - // if - assert.equal(new FormatString(1, undefined, 'foo', undefined).resolve(undefined), '') - assert.equal(new FormatString(1, undefined, 'foo', undefined).resolve(''), '') - assert.equal(new FormatString(1, undefined, 'foo', undefined).resolve('bar'), 'foo') - - // else - assert.equal(new FormatString(1, undefined, undefined, 'foo').resolve(undefined), 'foo') - assert.equal(new FormatString(1, undefined, undefined, 'foo').resolve(''), 'foo') - assert.equal(new FormatString(1, undefined, undefined, 'foo').resolve('bar'), 'bar') - - // if-else - assert.equal(new FormatString(1, undefined, 'bar', 'foo').resolve(undefined), 'foo') - assert.equal(new FormatString(1, undefined, 'bar', 'foo').resolve(''), 'foo') - assert.equal(new FormatString(1, undefined, 'bar', 'foo').resolve('baz'), 'bar') - }) - - test('Snippet variable transformation doesn\'t work if regex is complicated and snippet body contains \'$$\' #55627', function() { - const snippet = new SnippetParser().parse('const fileName = "${TM_FILENAME/(.*)\\..+$/$1/}"') - assert.equal(snippet.toTextmateString(), 'const fileName = "${TM_FILENAME/(.*)\\..+$/${1}/}"') - }) - - test('[BUG] HTML attribute suggestions: Snippet session does not have end-position set, #33147', function() { - - const { placeholders } = new SnippetParser().parse('src="$1"', true) - const [first, second] = placeholders - - assert.equal(placeholders.length, 2) - assert.equal(first.index, 1) - assert.equal(second.index, 0) - - }) - - test('Snippet optional transforms are not applied correctly when reusing the same variable, #37702', function() { - - const transform = new Transform() - transform.appendChild(new FormatString(1, 'upcase')) - transform.appendChild(new FormatString(2, 'upcase')) - transform.regexp = /^(.)|-(.)/g - - assert.equal(transform.resolve('my-file-name'), 'MyFileName') - - const clone = transform.clone() - assert.equal(clone.resolve('my-file-name'), 'MyFileName') - }) - - test('problem with snippets regex #40570', function() { - - const snippet = new SnippetParser().parse('${TM_DIRECTORY/.*src[\\/](.*)/$1/}') - assertMarker(snippet, Variable) - }) - - test('Variable transformation doesn\'t work if undefined variables are used in the same snippet #51769', function() { - let transform = new Transform() - transform.appendChild(new Text('bar')) - transform.regexp = new RegExp('foo', 'gi') - assert.equal(transform.toTextmateString(), '/foo/bar/ig') - }) - - test('Snippet parser freeze #53144', function() { - let snippet = new SnippetParser().parse('${1/(void$)|(.+)/${1:?-\treturn nil;}/}') - assertMarker(snippet, Placeholder) - }) - - test('snippets variable not resolved in JSON proposal #52931', function() { - assertTextAndMarker('FOO${1:/bin/bash}', 'FOO/bin/bash', Text, Placeholder) - }) - - test('Mirroring sequence of nested placeholders not selected properly on backjumping #58736', function() { - let snippet = new SnippetParser().parse('${3:nest1 ${1:nest2 ${2:nest3}}} $3') - assert.equal(snippet.children.length, 3) - assert.ok(snippet.children[0] instanceof Placeholder) - assert.ok(snippet.children[1] instanceof Text) - assert.ok(snippet.children[2] instanceof Placeholder) - - function assertParent(marker: Marker) { - marker.children.forEach(assertParent) - if (!(marker instanceof Placeholder)) { - return - } - let found = false - let m: Marker = marker - while (m && !found) { - if (m.parent === snippet) { - found = true - } - m = m.parent - } - assert.ok(found) - } - let [, , clone] = snippet.children - assertParent(clone) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/snippets/session.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/snippets/session.test.ts deleted file mode 100644 index d787dc23..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/snippets/session.test.ts +++ /dev/null @@ -1,537 +0,0 @@ -import { Range } from 'vscode-languageserver-protocol' -import { Neovim } from '@chemzqm/neovim' -import workspace from '../../workspace' -import window from '../../window' -import { SnippetSession } from '../../snippets/session' -import helper from '../helper' - -let nvim: Neovim -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -afterEach(async () => { - await helper.reset() -}) - -describe('SnippetSession#start', () => { - - it('should start with plain snippet', async () => { - let buf = await helper.edit() - await helper.wait(30) - await nvim.input('i') - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('bar$0') - expect(res).toBe(false) - let pos = await window.getCursorPosition() - expect(pos).toEqual({ line: 0, character: 3 }) - }) - - it('should start with range replaced', async () => { - let buf = await helper.edit() - await helper.wait(30) - await nvim.setLine('foo') - await nvim.input('i') - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('bar$0', true, Range.create(0, 0, 0, 3)) - expect(res).toBe(false) - let line = await nvim.line - expect(line).toBe('bar') - }) - - it('should insert placeholder with default value', async () => { - let buf = await helper.edit() - await helper.wait(30) - await nvim.input('i') - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('a${TM_SELECTED_TEXT:return}b') - expect(res).toBe(false) - let line = await nvim.line - expect(line).toBe('areturnb') - }) - - it('should fix indent of next line when necessary', async () => { - let buf = await helper.edit() - await nvim.setLine(' ab') - await nvim.input('i') - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('x\n') - expect(res).toBe(false) - let lines = await buf.lines - expect(lines).toEqual([' ax', ' b']) - }) - - it('should start with final position for plain snippet', async () => { - let buf = await helper.edit() - await nvim.command('startinsert') - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('bar$0') - expect(res).toBe(false) - let pos = await window.getCursorPosition() - expect(pos).toEqual({ line: 0, character: 3 }) - }) - - it('should insert indent for snippet endsWith line break', async () => { - let buf = await helper.edit() - await nvim.setLine(' bar') - await helper.wait(10) - await nvim.command('startinsert') - await nvim.call('cursor', [1, 3]) - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('foo\n') - expect(res).toBe(false) - let lines = await buf.lines - expect(lines).toEqual([' foo', ' bar']) - }) - - it('should insert resolved variable', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${TM_LINE_NUMBER}') - expect(res).toBe(false) - let line = await nvim.line - expect(line).toBe('1') - }) - - it('should use default value of unresolved variable', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${TM_SELECTION:abc}') - expect(res).toBe(false) - let line = await nvim.line - expect(line).toBe('abc') - }) - - it('should start with snippet insert', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start(' ${1:aa} bb $1') - expect(res).toBe(true) - let line = await nvim.getLine() - expect(line).toBe(' aa bb aa') - let { mode } = await nvim.mode - expect(mode).toBe('s') - let pos = await window.getCursorPosition() - expect(pos).toEqual({ line: 0, character: 2 }) - }) - - it('should start without select placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start(' ${1:aa} ', false) - expect(res).toBe(true) - let line = await nvim.getLine() - expect(line).toBe(' aa ') - let { mode } = await nvim.mode - expect(mode).toBe('n') - await session.selectCurrentPlaceholder() - await helper.wait(100) - let m = await nvim.mode - expect(m.mode).toBe('s') - }) - - it('should start with variable selected', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${foo:bar}', false) - expect(res).toBe(true) - let line = await nvim.getLine() - expect(line).toBe('bar') - await session.selectCurrentPlaceholder() - await helper.wait(100) - let m = await nvim.mode - expect(m.mode).toBe('s') - }) - - it('should start with nest snippet', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${1:a} ${2:b}', false) - let line = await nvim.getLine() - expect(line).toBe('a b') - expect(res).toBe(true) - let { placeholder } = session - expect(placeholder.index).toBe(1) - res = await session.start('${1:foo} ${2:bar}') - expect(res).toBe(true) - placeholder = session.placeholder - let { snippet } = session - expect(placeholder.index).toBe(2) - line = await nvim.getLine() - expect(line).toBe('foo bara b') - expect(snippet.toString()).toBe('foo bara b') - }) - - it('should jump to nested snippet placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start('${1} ${2:b}', false) - await session.start('${1:foo} ${2:bar}') - await session.nextPlaceholder() - await session.nextPlaceholder() - await session.nextPlaceholder() - let pos = await window.getCursorPosition() - expect(pos).toEqual({ line: 0, character: 8 }) - }) - - it('should jump to variable placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start('${foo} ${bar}', false) - await session.selectCurrentPlaceholder() - await helper.wait(100) - await session.nextPlaceholder() - let pos = await window.getCursorPosition() - expect(pos).toEqual({ line: 0, character: 6 }) - }) - - it('should jump to variable placeholder after number placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start('${foo} ${1:bar}', false) - await session.selectCurrentPlaceholder() - await session.nextPlaceholder() - let pos = await window.getCursorPosition() - expect(pos).toEqual({ line: 0, character: 2 }) - }) - - it('should jump to variable placeholder with same name only once', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start('${foo} ${foo} ${2:bar}', false) - await session.selectCurrentPlaceholder() - await session.nextPlaceholder() - await session.nextPlaceholder() - let pos = await window.getCursorPosition() - expect(pos).toEqual({ line: 0, character: 11 }) - }) - - it('should start nest snippet without select', async () => { - let buf = await helper.edit() - await nvim.command('startinsert') - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${1:a} ${2:b}') - await helper.wait(30) - await nvim.input('') - res = await session.start('${1:foo} ${2:bar}', false) - await helper.wait(30) - expect(res).toBe(true) - let line = await nvim.line - expect(line).toBe('foo bar b') - }) - - it('should select none transform placeholder', async () => { - let buf = await helper.edit() - await nvim.command('startinsert') - let session = new SnippetSession(nvim, buf.id) - await session.start('${1/..*/ -> /}xy$1') - await helper.wait(30) - let col = await nvim.call('col', '.') - expect(col).toBe(3) - }) - - it('should indent multiple lines variable text', async () => { - let text = 'abc\n def' - await nvim.setVar('coc_selected_text', text) - let buf = await helper.edit() - await nvim.input('i') - let session = new SnippetSession(nvim, buf.id) - await session.start('fun\n ${0:${TM_SELECTED_TEXT:return}}\nend') - await helper.wait(30) - let lines = await buf.lines - expect(lines.length).toBe(4) - expect(lines).toEqual([ - 'fun', ' abc', ' def', 'end' - ]) - }) -}) - -describe('SnippetSession#deactivate', () => { - - it('should deactivate on invalid change', async () => { - let doc = await helper.createDocument() - await nvim.input('i') - let session = new SnippetSession(nvim, doc.bufnr) - let res = await session.start('${1:a}bc') - expect(res).toBe(true) - let edit = { - range: Range.create(0, 0, 0, 2), - newText: '' - } - await doc.applyEdits([edit]) - await session.synchronizeUpdatedPlaceholders({ range: edit.range, text: edit.newText }) - expect(session.isActive).toBe(false) - }) - - it('should deactivate on cursor outside', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('a${1:a}b') - expect(res).toBe(true) - await buf.append(['foo', 'bar']) - await nvim.call('cursor', [2, 1]) - await session.checkPosition() - expect(session.isActive).toBe(false) - }) - - it('should cancel keymap on jump final placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await nvim.input('i') - await session.start('$0x${1:a}b$0') - let line = await nvim.line - expect(line).toBe('xab') - let map = await nvim.call('maparg', ['', 'i']) as string - expect(map).toMatch('snippetNext') - await session.nextPlaceholder() - map = await nvim.call('maparg', ['', 'i']) as string - expect(map).toBe('') - }) -}) - -describe('SnippetSession#nextPlaceholder', () => { - - it('should goto next placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${1:a} ${2:b} c') - expect(res).toBe(true) - await session.nextPlaceholder() - let { placeholder } = session - expect(placeholder.index).toBe(2) - }) - - it('should jump to none transform placeholder', async () => { - let buf = await helper.edit() - await helper.wait(60) - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${1} ${2/^_(.*)/$2/}bar$2') - expect(res).toBe(true) - let line = await nvim.line - expect(line).toBe(' bar') - await session.nextPlaceholder() - await helper.wait(60) - let col = await nvim.call('col', '.') - expect(col).toBe(5) - }) -}) - -describe('SnippetSession#previousPlaceholder', () => { - - it('should goto previous placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${1:foo} ${2:bar}') - expect(res).toBe(true) - await session.nextPlaceholder() - await helper.wait(60) - expect(session.placeholder.index).toBe(2) - await session.previousPlaceholder() - await helper.wait(60) - expect(session.placeholder.index).toBe(1) - }) -}) - -describe('SnippetSession#synchronizeUpdatedPlaceholders', () => { - - it('should adjust with line changed before start position', async () => { - let buf = await helper.edit() - await nvim.setLine('abd') - await nvim.input('o') - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${1:foo}') - await helper.wait(30) - expect(res).toBe(true) - await session.synchronizeUpdatedPlaceholders({ - range: Range.create(0, 0, 0, 3), - text: 'def' - }) - expect(session.isActive).toBe(true) - }) - - it('should adjust for variable placeholders', async () => { - let buf = await helper.edit() - await nvim.input('i') - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${foo} ${foo}') - expect(res).toBe(true) - await session.selectCurrentPlaceholder() - await helper.wait(100) - await nvim.input('bar') - await helper.wait(100) - await session.synchronizeUpdatedPlaceholders({ - range: Range.create(0, 0, 0, 3), - text: 'bar' - }) - let line = await nvim.getLine() - expect(line).toBe('bar bar') - }) - - it('should adjust with previous line change', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${1:foo}') - await nvim.input('Obar') - await helper.wait(30) - expect(res).toBe(true) - await session.synchronizeUpdatedPlaceholders({ - range: Range.create(0, 0, 0, 0), - text: 'bar\n' - }) - expect(session.isActive).toBe(true) - let { start } = session.snippet.range - expect(start).toEqual({ line: 1, character: 0 }) - }) - - it('should adjust with previous character change', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('foo ${1:foo}') - await nvim.input('Ibar') - await helper.wait(30) - expect(res).toBe(true) - await session.synchronizeUpdatedPlaceholders({ - range: Range.create(0, 0, 0, 0), - text: 'bar' - }) - expect(session.isActive).toBe(true) - let { start } = session.snippet.range - expect(start).toEqual({ line: 0, character: 3 }) - }) - - it('should deactivate when content add after snippet', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${1:foo} $0 ') - await nvim.input('Abar') - await helper.wait(100) - expect(res).toBe(true) - await session.synchronizeUpdatedPlaceholders({ - range: Range.create(0, 5, 0, 5), - text: 'bar' - }) - expect(session.isActive).toBe(false) - }) - - it('should not deactivate when content remove after snippet', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - let res = await session.start('${1:foo}') - expect(res).toBe(true) - await nvim.input('Abar') - await helper.wait(30) - await session.synchronizeUpdatedPlaceholders({ - range: Range.create(0, 5, 0, 6), - text: '' - }) - await helper.wait(30) - expect(session.isActive).toBe(true) - }) - - it('should deactivate when change outside placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start('a${1:b}c') - let doc = await workspace.document - await doc.applyEdits([{ - range: Range.create(0, 0, 0, 1), - newText: '' - }]) - await session.synchronizeUpdatedPlaceholders({ - range: Range.create(0, 0, 0, 1), - text: '' - }) - expect(session.isActive).toBe(false) - }) - - it('should deactivate when jump to single final placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start(' $0 ${1:a}') - await session.nextPlaceholder() - expect(session.isActive).toBe(false) - }) -}) - -describe('SnippetSession#checkPosition', () => { - - it('should cancel snippet if position out of range', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await nvim.setLine('bar') - await session.start('${1:foo}') - await nvim.call('cursor', [1, 5]) - await session.checkPosition() - expect(session.isActive).toBe(false) - }) - - it('should not cancel snippet if position in range', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start('${1:foo}') - await nvim.call('cursor', [1, 3]) - await session.checkPosition() - expect(session.isActive).toBe(true) - }) -}) - -describe('SnippetSession#findPlaceholder', () => { - - it('should find current placeholder if possible', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start('${1:abc}${2:def}') - let placeholder = session.findPlaceholder(Range.create(0, 3, 0, 3)) - expect(placeholder.index).toBe(1) - }) - - it('should return null if placeholder not found', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start('${1:abc}xyz${2:def}') - let placeholder = session.findPlaceholder(Range.create(0, 4, 0, 4)) - expect(placeholder).toBeNull() - }) -}) - -describe('SnippetSession#selectPlaceholder', () => { - - it('should select range placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start('${1:abc}') - let mode = await nvim.mode - expect(mode.mode).toBe('s') - await nvim.input('') - let line = await nvim.line - expect(line).toBe('') - }) - - it('should select empty placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await session.start('a ${1} ${2}') - let mode = await nvim.mode - expect(mode.mode).toBe('i') - let col = await nvim.call('col', '.') - expect(col).toBe(3) - }) - - it('should select choice placeholder', async () => { - let buf = await helper.edit() - let session = new SnippetSession(nvim, buf.id) - await nvim.input('i') - await session.start('${1|one,two,three|}') - await helper.wait(60) - let line = await nvim.line - expect(line).toBe('one') - let val = await nvim.eval('g:coc#_context') as any - expect(val.start).toBe(0) - expect(val.candidates).toEqual(['one', 'two', 'three']) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/snippets/string.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/snippets/string.test.ts deleted file mode 100644 index cfbadda9..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/snippets/string.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { SnippetString } from '../../snippets/string' - -describe('SnippetString', () => { - describe('Append', () => { - it('should append plain snippets', () => { - let snippetString = new SnippetString('foo') - expect(snippetString.value).toBe('foo') - - snippetString = new SnippetString().appendText('foo') - expect(snippetString.value).toBe('foo') - }) - - it('should append tabstop', () => { - let snippetString = new SnippetString() - .appendTabstop() - .appendText(' ') - .appendTabstop() - .appendText(' ') - .appendTabstop(4) - .appendText(' ') - .appendTabstop(3) - - expect(snippetString.value).toBe('$1 $2 $4 $3') - }) - - it('should append placeholder', () => { - let snippetString = new SnippetString() - .appendPlaceholder('abcdef') - .appendText(' ') - .appendPlaceholder('foo') - .appendText(' ') - .appendPlaceholder('bar', 4) - .appendText(' ') - .appendPlaceholder('a', 3) - .appendText(' ') - .appendPlaceholder(s => { - s.appendText('plain') - }, 5) - - expect(snippetString.value).toBe('${1:abcdef} ${2:foo} ${4:bar} ${3:a} ${5:plain}') - }) - - it('should append choice', () => { - let snippetString = new SnippetString() - .appendChoice(['foo', 'bar']) - .appendText(' ') - .appendChoice(['foo3', 'bar3'], 3) - .appendText(' ') - .appendChoice(['foo2', 'bar2'], 2) - - expect(snippetString.value).toBe('${1|foo,bar|} ${3|foo3,bar3|} ${2|foo2,bar2|}') - }) - - it('should append variables', () => { - let snippetString = new SnippetString() - .appendVariable('foo', 'abcdef') - .appendText(' ') - .appendVariable('bar') - - expect(snippetString.value).toBe('${foo:abcdef} ${bar}') - - snippetString = new SnippetString() - .appendVariable('foo', s => s.appendText('abcdef')) - .appendText(' ') - .appendVariable('bar') - - expect(snippetString.value).toBe('${foo:abcdef} ${bar}') - }) - }) - - describe('isSnippetString()', () => { - let snippetString = new SnippetString() - expect(SnippetString.isSnippetString(snippetString)).toBe(true) - - let snippetStr = '' - expect(SnippetString.isSnippetString(snippetStr)).toBe(false) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/tree/basicProvider.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/tree/basicProvider.test.ts deleted file mode 100644 index 92dc104b..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/tree/basicProvider.test.ts +++ /dev/null @@ -1,541 +0,0 @@ -import { CancellationTokenSource, Disposable } from 'vscode-languageserver-protocol' -import { TreeItemCollapsibleState } from '../../tree' -import commandsManager from '../../commands' -import BasicDataProvider, { TreeNode } from '../../tree/BasicDataProvider' -import { disposeAll } from '../../util' - -let disposables: Disposable[] = [] - -type NodeDef = [string, NodeDef[]?] - -interface CustomNode extends TreeNode { - kind?: string - x?: number - y?: number -} - -afterEach(async () => { - disposeAll(disposables) - disposables = [] -}) - -function createNode(label: string, children?: TreeNode[], key?: string, tooltip?: string): CustomNode { - let res: TreeNode = { label } - if (children) res.children = children - if (tooltip) res.tooltip = tooltip - if (key) res.key = key - return res -} - -let defaultDef: NodeDef[] = [ - ['a', [['c'], ['d']]], - ['b', [['e'], ['f']]], - ['g'] -] - -function createLabels(data: ReadonlyArray): string[] { - let res: string[] = [] - const addLabels = (n: TreeNode, level: number) => { - res.push(' '.repeat(level) + n.label) - if (n.children) { - for (let node of n.children) { - addLabels(node, level + 1) - } - } - } - for (let item of data || []) { - addLabels(item, 0) - } - return res -} - -function findNode(label: string, nodes: ReadonlyArray): TreeNode | undefined { - for (let n of nodes) { - if (n.label == label) { - return n - } - let children = n.children - if (Array.isArray(children)) { - let find = findNode(label, children) - if (find) return find - } - } -} - -function createNodes(defs: NodeDef[]): TreeNode[] { - return defs.map(o => { - let children - if (Array.isArray(o[1])) { - children = createNodes(o[1]) - } - return createNode(o[0], children) - }) -} - -describe('BasicDataProvider', () => { - describe('getChildren()', () => { - it('should get children from root', async () => { - let nodes = createNodes(defaultDef) - let provider = new BasicDataProvider({ - provideData: () => { - return nodes - } - }) - disposables.push(provider) - let res = await provider.getChildren() - expect(res.length).toBe(3) - expect(res.map(o => o.label)).toEqual(['a', 'b', 'g']) - }) - - it('should get children from child node', async () => { - let provider = new BasicDataProvider({ - provideData: () => { - return createNodes(defaultDef) - } - }) - disposables.push(provider) - let res = await provider.getChildren() - let nodes = await provider.getChildren(res[0]) - expect(nodes.length).toBe(2) - expect(nodes.map(o => o.label)).toEqual(['c', 'd']) - }) - - it('should throw when provideData throws', async () => { - let provider = new BasicDataProvider({ - provideData: () => { - throw new Error('my error') - } - }) - disposables.push(provider) - let err - try { - await provider.getChildren() - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - }) - - describe('getTreeItem()', () => { - it('should get tree item from node', async () => { - let provider = new BasicDataProvider({ - provideData: () => { - return createNodes(defaultDef) - } - }) - disposables.push(provider) - let res = await provider.getChildren() - let item = provider.getTreeItem(res[0]) - expect(item).toBeDefined() - expect(item.collapsibleState).toBe(TreeItemCollapsibleState.Collapsed) - item = provider.getTreeItem(res[2]) - expect(item.collapsibleState).toBe(TreeItemCollapsibleState.None) - }) - - it('should respect expandLevel option', async () => { - let provider = new BasicDataProvider({ - expandLevel: 1, - provideData: () => { - return createNodes(defaultDef) - } - }) - disposables.push(provider) - let res = await provider.getChildren() - let item = provider.getTreeItem(res[0]) - expect(item).toBeDefined() - expect(item.collapsibleState).toBe(TreeItemCollapsibleState.Expanded) - }) - - it('should include highlights', async () => { - let provider = new BasicDataProvider({ - provideData: () => { - return [createNode('a', [], undefined, 'tip')] - } - }) - disposables.push(provider) - let res = await provider.getChildren() - let item = provider.getTreeItem(res[0]) - expect(item).toBeDefined() - expect(item.tooltip).toBe('tip') - }) - - it('should use icon from node', async () => { - let node = createNode('a', [], undefined, 'tip') - node.icon = { - text: 'i', - hlGroup: 'Function' - } - let provider = new BasicDataProvider({ - provideData: () => { - return [node] - } - }) - disposables.push(provider) - let res = await provider.getChildren() - let item = provider.getTreeItem(res[0]) - expect(item).toBeDefined() - expect(item.icon).toBeDefined() - expect(item.icon).toEqual({ - text: 'i', - hlGroup: 'Function' - }) - }) - - it('should resolve icon', async () => { - let provider = new BasicDataProvider({ - provideData: () => { - let node = createNode('a', [], undefined, 'tip') - node.kind = 'function' - return [node] - }, - resolveIcon: item => { - if (item.kind === 'function') { - return { - text: 'f', - hlGroup: 'Function' - } - } - } - }) - disposables.push(provider) - let res = await provider.getChildren() - let item = provider.getTreeItem(res[0]) - expect(item).toBeDefined() - expect(item.icon).toEqual({ - text: 'f', - hlGroup: 'Function' - }) - }) - }) - - describe('getParent()', () => { - it('should get undefined when data not exists', async () => { - let node = createNode('a') - let provider = new BasicDataProvider({ - provideData: () => { - return [node] - } - }) - disposables.push(provider) - let res = provider.getParent(node) - expect(res).toBeUndefined() - }) - - it('should get parent node', async () => { - let node = createNode('g') - let provider = new BasicDataProvider({ - provideData: () => { - return [ - createNode('a', [createNode('c', [node]), createNode('d')]), - createNode('b', [createNode('e'), createNode('f')]), - createNode('g') - ] - } - }) - disposables.push(provider) - await provider.getChildren() - let res = provider.getParent(node) - expect(res).toBeDefined() - expect(res.label).toBe('c') - // console.log(provider.labels.join('\n')) - }) - }) - - describe('resolveTreeItem()', () => { - it('should resolve tooltip and command', async () => { - let node = createNode('a') - let provider = new BasicDataProvider({ - provideData: () => { - return [node] - }, - resolveItem: item => { - item.tooltip = 'tip' - item.command = { - command: 'test command', - title: 'test' - } - return item - } - }) - disposables.push(provider) - await provider.getChildren() - let source = new CancellationTokenSource() - let item = provider.getTreeItem(node) - let resolved = await provider.resolveTreeItem(item, node, source.token) - expect(resolved.tooltip).toBe('tip') - expect(resolved.command.command).toBe('test command') - }) - - it('should register command invoke click', async () => { - let node = createNode('a') - let called: TreeNode - let provider = new BasicDataProvider({ - provideData: () => { - return [node] - }, - handleClick: item => { - called = item - } - }) - disposables.push(provider) - await provider.getChildren() - let source = new CancellationTokenSource() - let item = provider.getTreeItem(node) - let resolved = await provider.resolveTreeItem(item, node, source.token) - expect(resolved.command).toBeDefined() - expect(resolved.command.command).toMatch('invoke') - await commandsManager.execute(resolved.command) - expect(called).toBeDefined() - expect(called).toBe(node) - }) - }) - - describe('update()', () => { - it('should add children with event', async () => { - let defs: NodeDef[] = [ - ['a', [['b']]], - ['b', [['f']]] - ] - let nodes = createNodes(defs) - let b = nodes[0].children[0] - let provider = new BasicDataProvider({ - provideData: () => { - return nodes - } - }) - disposables.push(provider) - await provider.getChildren() - let called = false - provider.onDidChangeTreeData(node => { - expect(node).toBe(b) - called = true - }) - let newDefs: NodeDef[] = [ - ['a', [['b', [['c'], ['d']]]]], - ['b', [['f']]] - ] - let curr = provider.update(createNodes(newDefs)) - let labels = createLabels(curr) - expect(labels).toEqual([ - 'a', ' b', ' c', ' d', 'b', ' f' - ]) - expect(called).toBe(true) - expect(b.children).toBeDefined() - expect(b.children.length).toBe(2) - }) - - it('should remove children with event', async () => { - let defs: NodeDef[] = [ - ['a', [['b', [['c'], ['d']]]]], - ['e', [['f']]] - ] - let nodes = createNodes(defs) - let b = nodes[0].children[0] - let provider = new BasicDataProvider({ - provideData: () => { - return nodes - } - }) - disposables.push(provider) - await provider.getChildren() - let called = false - provider.onDidChangeTreeData(node => { - expect(node).toBe(b) - called = true - }) - let newDefs: NodeDef[] = [ - ['a', [['b']]], - ['e', [['f']]] - ] - let curr = provider.update(createNodes(newDefs)) - let labels = createLabels(curr) - expect(labels).toEqual([ - 'a', ' b', 'e', ' f' - ]) - expect(called).toBe(true) - expect(b.children).toBeUndefined() - }) - - it('should not fire event for children when parent have changed', async () => { - let defs: NodeDef[] = [ - ['a', [['b', [['c'], ['d']]]]] - ] - let nodes = createNodes(defs) - let provider = new BasicDataProvider({ - provideData: () => { - return nodes - } - }) - disposables.push(provider) - await provider.getChildren() - let called = 0 - provider.onDidChangeTreeData(node => { - expect(node).toBeUndefined() - called += 1 - }) - let newDefs: NodeDef[] = [ - ['a', [['b', [['c'], ['d'], ['g']]]]], - ['e', [['f']]] - ] - let curr = provider.update(createNodes(newDefs)) - expect(called).toBe(1) - let labels = createLabels(curr) - expect(labels).toEqual([ - 'a', ' b', ' c', ' d', ' g', 'e', ' f' - ]) - }) - - it('should fire events for independent node change', async () => { - let defs: NodeDef[] = [ - ['a', [['b', [['c']]]]], - ['e', [['f']]] - ] - let nodes = createNodes(defs) - let provider = new BasicDataProvider({ - provideData: () => { - return nodes - } - }) - disposables.push(provider) - await provider.getChildren() - let called = [] - provider.onDidChangeTreeData(node => { - called.push(node) - }) - let newDefs: NodeDef[] = [ - ['a', [['b', [['c'], ['d']]]]], - ['e', [['f', [['g']]]]] - ] - let curr = provider.update(createNodes(newDefs)) - expect(called.length).toBe(2) - expect(called[0].label).toBe('b') - expect(called[1].label).toBe('f') - let labels = createLabels(curr) - expect(labels).toEqual([ - 'a', ' b', ' c', ' d', 'e', ' f', ' g' - ]) - }) - - it('should apply new properties', async () => { - let defs: NodeDef[] = [ - ['a', [['b']]], - ['e', [['f']]] - ] - let nodes = createNodes(defs) - let provider = new BasicDataProvider({ - provideData: () => { - return nodes - } - }) - disposables.push(provider) - await provider.getChildren() - let newNodes = createNodes([ - ['a', [['b', [['c']]]]], - ['e', [['f', [['g']]]]] - ]) - let b = newNodes[0].children[0] - Object.assign(b, { x: 1, y: 2 }) - let curr = provider.update(newNodes) - let node = curr[0].children[0] - expect(node).toBeDefined() - expect(node.x).toBe(1) - expect(node.y).toBe(2) - }) - - it('should keep references and have new data sequence', async () => { - let defs: NodeDef[] = [ - ['a', [['b'], ['c']]], - ['e', [['f']]], - ['g'] - ] - let nodes = createNodes(defs) - let keeps = [ - findNode('a', nodes), - findNode('b', nodes), - findNode('c', nodes), - findNode('e', nodes), - findNode('f', nodes), - ] - let provider = new BasicDataProvider({ - provideData: () => { - return nodes - } - }) - disposables.push(provider) - await provider.getChildren() - let newNodes = createNodes([ - ['a', [['c', [['d'], ['h']]], ['b']]], - ['e', [['f', [['j']]], ['i']]] - ]) - let curr = provider.update(newNodes) - expect(curr).toBe(nodes) - expect(keeps[0]).toBe(findNode('a', curr)) - expect(keeps[1]).toBe(findNode('b', curr)) - expect(keeps[2]).toBe(findNode('c', curr)) - expect(keeps[3]).toBe(findNode('e', curr)) - expect(keeps[4]).toBe(findNode('f', curr)) - let labels = createLabels(curr) - expect(labels).toEqual([ - 'a', ' c', ' d', ' h', ' b', 'e', ' f', ' j', ' i' - ]) - }) - - it('should use key for nodes', async () => { - let nodes = [ - createNode('a', [], 'x'), - createNode('a', [], 'y'), - createNode('a', [], 'z'), - ] - let provider = new BasicDataProvider({ - provideData: () => { - return nodes - } - }) - disposables.push(provider) - await provider.getChildren() - let newNodes = [ - createNode('a', [], 'x'), - createNode('a', [], 'z'), - ] - let curr = provider.update(newNodes) - expect(curr.length).toBe(2) - expect(curr[0].key).toBe('x') - expect(curr[1].key).toBe('z') - }) - - it('should reset data', async () => { - let nodes = [ - createNode('a', [], 'x'), - ] - let provider = new BasicDataProvider({ - provideData: () => { - return nodes - } - }) - disposables.push(provider) - await provider.getChildren() - let newNodes = [ - createNode('a', [], 'x'), - ] - let curr = provider.update(newNodes, true) - expect(curr === nodes).toBe(false) - }) - }) - - describe('dispose', () => { - it('should invoke onDispose from opts', async () => { - let called = false - let provider = new BasicDataProvider({ - provideData: () => { - return [] - }, - onDispose: () => { - called = true - } - }) - provider.dispose() - expect(called).toBe(true) - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/tree/treeView.test.ts b/vim-config/plugins/coc.nvim/src/__tests__/tree/treeView.test.ts deleted file mode 100644 index 6b0aa605..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/tree/treeView.test.ts +++ /dev/null @@ -1,1146 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import TreeView from '../../tree/TreeView' -import { TreeItem } from '../../tree/TreeItem' -import BasicDataProvider, { ProviderOptions, TreeNode } from '../../tree/BasicDataProvider' -import { disposeAll } from '../../util' -import events from '../../events' -import workspace from '../../workspace' -import helper from '../helper' -import { TreeViewOptions } from '../../tree' - -type NodeDef = [string, NodeDef[]?] - -let nvim: Neovim -let disposables: Disposable[] = [] -let treeView: TreeView -let provider: BasicDataProvider -let nodes: TreeNode[] -beforeAll(async () => { - await helper.setup() - nvim = helper.nvim -}) - -afterAll(async () => { - await helper.shutdown() -}) - -beforeEach(async () => { - await helper.createDocument() -}) - -afterEach(async () => { - if (provider) provider.dispose() - if (treeView) treeView.dispose() - disposeAll(disposables) - await helper.reset() -}) - -function createNode(label: string, children?: TreeNode[], key?: string, tooltip?: string): TreeNode { - let res: TreeNode = { label } - if (children) res.children = children - if (tooltip) res.tooltip = tooltip - if (key) res.key = key - return res -} - -function createNodes(defs: NodeDef[]): TreeNode[] { - return defs.map(o => { - let children - if (Array.isArray(o[1])) { - children = createNodes(o[1]) - } - return createNode(o[0], children) - }) -} - -function createTreeView(defs: NodeDef[], opts: Partial> = {}, providerOpts: Partial> = {}) { - nodes = createNodes(defs) - provider = new BasicDataProvider(Object.assign(providerOpts, { - provideData: () => { - return nodes - } - })) - treeView = new TreeView('test', Object.assign(opts, { - treeDataProvider: provider - })) -} - -function updateData(defs: NodeDef[], reset = false) { - nodes = createNodes(defs) - provider.update(nodes, reset) -} - -function makeUpdateUIThrowError() { - (treeView as any).updateUI = () => { - throw new Error('Error on updateUI') - } -} - -let defaultDef: NodeDef[] = [ - ['a', [['c'], ['d']]], - ['b', [['e'], ['f']]], - ['g'] -] - -async function checkLines(arr: string[]): Promise { - let lines = await nvim.call('getline', [1, '$']) - expect(lines).toEqual(arr) -} - -describe('TreeView', () => { - describe('TreeItem()', () => { - it('should create TreeItem from resourceUri', async () => { - let item = new TreeItem(URI.file('/foo/bar.ts')) - expect(item.resourceUri).toBeDefined() - expect(item.label).toBe('bar.ts') - expect(item.label).toBeDefined() - }) - }) - - describe('show()', () => { - it('should show with title', async () => { - createTreeView(defaultDef) - expect(treeView).toBeDefined() - await treeView.show() - let visible = treeView.visible - expect(visible).toBe(true) - await helper.wait(50) - await checkLines(['test', '+ a', '+ b', ' g']) - }) - - it('should not show when visible', async () => { - createTreeView(defaultDef) - await treeView.show() - let windowId = treeView.windowId - await treeView.show() - expect(treeView.windowId).toBe(windowId) - }) - - it('should reuse window', async () => { - createTreeView(defaultDef) - await treeView.show() - let windowId = treeView.windowId - await helper.wait(50) - provider.dispose() - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - expect(treeView.windowId).toBe(windowId) - }) - - it('should render item icon', async () => { - createTreeView(defaultDef) - nodes[0].icon = { text: 'i', hlGroup: 'Title' } - nodes[1].icon = { text: 'i', hlGroup: 'Title' } - nodes[2].icon = { text: 'i', hlGroup: 'Title' } - await treeView.show() - await helper.wait(50) - await checkLines(['test', '+ i a', '+ i b', ' i g']) - }) - }) - - describe('configuration', () => { - afterAll(() => { - let { configurations } = workspace - configurations.updateUserConfig({ - 'tree.openedIcon': '-', - 'tree.closedIcon': '+', - }) - }) - - it('should change open close icon', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - let { configurations } = workspace - configurations.updateUserConfig({ - 'tree.openedIcon': '๏„‡', - 'tree.closedIcon': '๏„…', - }) - await helper.wait(50) - await checkLines(['test', '๏„… a', '๏„… b', ' g']) - }) - }) - - describe('public properties', () => { - it('should change title', async () => { - createTreeView(defaultDef) - treeView.title = 'foo' - await treeView.show() - await helper.wait(50) - await checkLines(['foo', '+ a', '+ b', ' g']) - treeView.title = 'bar' - await helper.wait(50) - await checkLines(['bar', '+ a', '+ b', ' g']) - treeView.title = undefined - await helper.wait(50) - await checkLines(['+ a', '+ b', ' g']) - makeUpdateUIThrowError() - treeView.title = 'xyz' - await helper.wait(50) - await checkLines(['+ a', '+ b', ' g']) - }) - - it('should change description', async () => { - createTreeView(defaultDef) - treeView.description = 'desc' - await treeView.show() - await helper.wait(50) - await checkLines(['test desc', '+ a', '+ b', ' g']) - treeView.description = 'foo bar' - await helper.wait(50) - await checkLines(['test foo bar', '+ a', '+ b', ' g']) - treeView.description = '' - await helper.wait(50) - await checkLines(['test', '+ a', '+ b', ' g']) - makeUpdateUIThrowError() - treeView.description = 'desc' - await helper.wait(50) - await checkLines(['test', '+ a', '+ b', ' g']) - }) - - it('should change message', async () => { - createTreeView(defaultDef) - treeView.message = 'hello' - await treeView.show() - await helper.wait(50) - await checkLines(['hello', '', 'test', '+ a', '+ b', ' g']) - treeView.message = 'foo' - await helper.wait(50) - await checkLines(['foo', '', 'test', '+ a', '+ b', ' g']) - treeView.message = undefined - await helper.wait(50) - await checkLines(['test', '+ a', '+ b', ' g']) - makeUpdateUIThrowError() - treeView.message = 'bar' - await helper.wait(50) - await checkLines(['test', '+ a', '+ b', ' g']) - }) - }) - - describe('options', () => { - it('should disable winfixwidth', async () => { - createTreeView(defaultDef, { winfixwidth: false }) - await treeView.show() - let res = await nvim.eval('&winfixwidth') - expect(res).toBe(0) - }) - - it('should disable leaf indent', async () => { - createTreeView(defaultDef, { disableLeafIndent: true }) - await treeView.show() - await helper.wait(50) - await checkLines(['test', '+ a', '+ b', 'g']) - }) - - it('should support many selection', async () => { - createTreeView(defaultDef, { canSelectMany: true }) - await treeView.show() - await helper.wait(50) - let selection: TreeNode[] - treeView.onDidChangeSelection(e => { - selection = e.selection - }) - await nvim.command('exe 1') - await nvim.input('') - await helper.wait(10) - await nvim.command('exe 2') - await nvim.input('') - await helper.wait(50) - expect(selection.length).toBe(1) - await nvim.command('exe 3') - await nvim.input('') - await helper.wait(50) - expect(selection.length).toBe(2) - await nvim.input('') - await helper.wait(50) - expect(selection.length).toBe(1) - let buf = await nvim.buffer - let res = await nvim.call('sign_getplaced', [buf.id, { group: 'CocTree' }]) - let signs = res[0].signs - expect(treeView.selection.length).toBe(1) - expect(signs.length).toBe(1) - expect(signs[0]).toEqual({ - lnum: 2, - id: 3001, - name: 'CocTreeSelected', - priority: 10, - group: 'CocTree' - }) - }) - }) - - describe('key-mappings', () => { - it('should jump back by ', async () => { - let winid = await nvim.call('win_getid') - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - let win = await nvim.window - expect(win.id).toBe(winid) - }) - - it('should toggle selection by ', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - let selection: TreeNode[] - treeView.onDidChangeSelection(e => { - selection = e.selection - }) - await nvim.command('exe 1') - await nvim.input('') - await helper.wait(10) - await nvim.command('exe 2') - await nvim.input('') - await helper.wait(50) - expect(selection.length).toBe(1) - await nvim.command('exe 3') - await nvim.input('') - await helper.wait(50) - let buf = await nvim.buffer - let res = await nvim.call('sign_getplaced', [buf.id, { group: 'CocTree' }]) - let signs = res[0].signs - expect(treeView.selection.length).toBe(1) - expect(signs.length).toBe(1) - expect(signs[0]).toEqual({ - lnum: 3, - id: 3002, - name: 'CocTreeSelected', - priority: 10, - group: 'CocTree' - }) - await nvim.input('') - await helper.wait(50) - res = await nvim.call('sign_getplaced', [buf.id, { group: 'CocTree' }]) - signs = res[0].signs - expect(signs.length).toBe(0) - }) - - it('should reset signs after expand & collapse', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - await nvim.command('exe 2') - await nvim.input('t') - await helper.wait(50) - await checkLines([ - 'test', - '- a', - ' c', - ' d', - '+ b', - ' g', - ]) - await nvim.command('exe 3') - await nvim.input('') - await helper.wait(50) - let buf = await nvim.buffer - let res = await nvim.call('sign_getplaced', [buf.id, { group: 'CocTree' }]) - expect(res[0].signs.length).toBe(1) - await nvim.command('exe 2') - await nvim.input('t') - await helper.wait(50) - res = await nvim.call('sign_getplaced', [buf.id, { group: 'CocTree' }]) - expect(res[0].signs.length).toBe(0) - await nvim.input('t') - await helper.wait(100) - res = await nvim.call('sign_getplaced', [buf.id, { group: 'CocTree' }]) - expect(res[0].signs.length).toBe(1) - }) - - it('should close tree view by ', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - expect(treeView.visible).toBe(true) - await nvim.input('') - await helper.wait(50) - expect(treeView.visible).toBe(false) - }) - - it('should invoke command by ', async () => { - let node: TreeNode - createTreeView(defaultDef, {}, { - handleClick: n => { - node = n - } - }) - await treeView.show() - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - expect(node).toBeUndefined() - await nvim.command('exe 2') - await nvim.input('') - await helper.wait(50) - expect(node.label).toBe('a') - }) - - it('should not throw when resolve command cancelled', async () => { - let node: TreeNode - let cancelled = false - createTreeView(defaultDef, {}, { - handleClick: n => { - node = n - }, - resolveItem: (item, _node, token) => { - return new Promise(resolve => { - let timer = setTimeout(() => { - item.command = { - title: 'not exists', - command: 'test' - } - resolve(item) - }, 5000) - token.onCancellationRequested(() => { - cancelled = true - clearTimeout(timer) - resolve(item) - }) - }) - } - }) - await treeView.show() - await helper.wait(50) - await nvim.command('exe 2') - await nvim.input('') - await helper.wait(50) - await nvim.command('exe 1') - await helper.wait(50) - expect(cancelled).toBe(true) - expect(node).toBeUndefined() - }) - - it('should toggle expand by t', async () => { - createTreeView(defaultDef) - let c = nodes[0].children[0] - c.children = [createNode('h')] - await treeView.show() - await helper.wait(50) - await nvim.command('exe 1') - await nvim.input('t') - await helper.wait(50) - await nvim.command('exe 3') - await nvim.input('t') - await helper.wait(50) - await nvim.command('exe 2') - await nvim.input('t') - await helper.wait(50) - await checkLines([ - 'test', '- a', ' + c', ' d', '- b', ' e', ' f', ' g' - ]) - await nvim.command('exe 2') - await nvim.input('t') - await helper.wait(50) - await checkLines([ - 'test', '+ a', '- b', ' e', ' f', ' g' - ]) - }) - - it('should should collapse parent node by t', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - await nvim.command('exe 2') - await nvim.input('t') - await helper.wait(50) - await checkLines([ - 'test', - '- a', - ' c', - ' d', - '+ b', - ' g', - ]) - await nvim.command('exe 3') - await nvim.input('t') - await helper.wait(50) - await checkLines([ - 'test', - '+ a', - '+ b', - ' g', - ]) - }) - - it('should collapse all nodes by M', async () => { - createTreeView(defaultDef) - let c = nodes[0].children[0] - c.children = [createNode('h')] - await treeView.show() - await helper.wait(50) - await nvim.command('exe 2') - await nvim.input('t') - await helper.wait(50) - await nvim.command('exe 3') - await nvim.input('t') - await helper.wait(50) - await nvim.command('exe 6') - await nvim.input('t') - await helper.wait(50) - await checkLines([ - 'test', - '- a', - ' - c', - ' h', - ' d', - '- b', - ' e', - ' f', - ' g', - ]) - await nvim.input('M') - await helper.wait(50) - await checkLines([ - 'test', - '+ a', - '+ b', - ' g', - ]) - let res = await treeView.checkLines() - expect(res).toBe(true) - }) - - it('should toggle expand on open/close icon click ', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - await nvim.call('cursor', [1, 1]) - await nvim.input('') - await helper.wait(50) - await nvim.call('cursor', [2, 1]) - await nvim.input('') - await helper.wait(50) - await checkLines([ - 'test', - '- a', - ' c', - ' d', - '+ b', - ' g', - ]) - await nvim.input('') - await helper.wait(50) - await checkLines([ - 'test', - '+ a', - '+ b', - ' g', - ]) - let res = await treeView.checkLines() - expect(res).toBe(true) - }) - - it('should invoke command on node click', async () => { - let node: TreeNode - createTreeView(defaultDef, {}, { - handleClick: n => { - node = n - } - }) - await treeView.show() - await helper.wait(50) - await nvim.call('cursor', [2, 3]) - await nvim.input('') - await helper.wait(50) - expect(node).toBeDefined() - expect(node.label).toBe('a') - }) - }) - - describe('invokeActions', () => { - it('should show warning when resolveActions not exists', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - await nvim.call('cursor', [2, 3]) - await nvim.input('') - await helper.wait(50) - let cmdline = await helper.getCmdline() - expect(cmdline).toMatch('No actions') - }) - - it('should show warning when resolveActions is empty', async () => { - createTreeView(defaultDef, {}, { - resolveActions: () => { - return [] - } - }) - await treeView.show() - await helper.wait(50) - await nvim.call('cursor', [2, 3]) - await nvim.input('') - await helper.wait(50) - let cmdline = await helper.getCmdline() - expect(cmdline).toMatch('No actions') - }) - - it('should invoke selected action', async () => { - let args: any[] - let called = false - createTreeView(defaultDef, {}, { - resolveActions: (item, element) => { - args = [item, element] - return [{ - title: 'one', - handler: () => { - called = true - } - }] - } - }) - await treeView.show() - await helper.wait(50) - await nvim.call('cursor', [2, 3]) - await nvim.input('') - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - expect(called).toBe(true) - expect(args[0].label).toBe('a') - expect(args[1].label).toBe('a') - }) - }) - - describe('events', () => { - it('should emit visibility change on buffer unload', async () => { - createTreeView(defaultDef) - let visible - treeView.onDidChangeVisibility(e => { - visible = e.visible - }) - await treeView.show() - await helper.wait(50) - let buf = await nvim.buffer - nvim.command(`bd! ${buf.id}`, true) - await helper.wait(50) - expect(visible).toBe(false) - }) - - it('should show tooltip on CursorHold', async () => { - createTreeView(defaultDef, {}, { - resolveItem: (item, node) => { - if (node.label == 'a') { - item.tooltip = 'first' - } - if (node.label == 'b') { - item.tooltip = { kind: 'markdown', value: '#title' } - } - return item - } - }) - await treeView.show() - await helper.wait(50) - await nvim.command('exe 2') - let bufnr = await nvim.eval(`bufnr('%')`) as number - await events.fire('CursorHold', [bufnr]) - let win = await helper.getFloat() - expect(win).toBeDefined() - let buf = await win.buffer - let lines = await buf.lines - expect(lines).toEqual(['first']) - await helper.wait(50) - await nvim.command('exe 3') - await events.fire('CursorHold', [bufnr]) - lines = await buf.lines - expect(lines).toEqual(['#title']) - }) - }) - - describe('data change', () => { - it('should ignore hidden node change', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - let tick = await nvim.eval('b:changedtick') - updateData([ - ['a', [['c', [['h']]], ['d']]], - ['b', [['e'], ['f']]], - ['g'] - ]) - await helper.wait(50) - let curr = await nvim.eval('b:changedtick') - expect(curr).toBe(tick) - }) - - it('should render all nodes on root change', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - updateData([ - ['g'], - ['h'], - ['b', [['e'], ['f']]], - ['a', [['c'], ['d']]] - ]) - await helper.wait(50) - await checkLines([ - 'test', - ' g', - ' h', - '+ b', - '+ a', - ]) - let res = await treeView.checkLines() - expect(res).toBe(true) - }) - - it('should keep node open state', async () => { - createTreeView(defaultDef) - let c = nodes[0].children[0] - c.children = [createNode('h')] - await treeView.show() - await helper.wait(50) - await nvim.command('exe 2') - await nvim.input('t') - await helper.wait(50) - await nvim.command('exe 3') - await nvim.input('t') - await helper.wait(50) - await nvim.command('exe 6') - await nvim.input('t') - await helper.wait(50) - updateData([ - ['h'], - ['g', [['i']]], - ['b', [['f']]], - ['a', [['c'], ['j']]] - ]) - await helper.wait(50) - await checkLines([ - 'test', - ' h', - '+ g', - '- b', - ' f', - '- a', - ' c', - ' j', - ]) - let res = await treeView.checkLines() - expect(res).toBe(true) - }) - - it('should render changed nodes', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - await nvim.command('exe 2') - await nvim.input('t') - await helper.wait(50) - updateData([ - ['a', [['h', [['i']]], ['d']]], - ['b', [['e'], ['f']]], - ['g'], - ]) - await helper.wait(50) - await checkLines([ - 'test', - '- a', - ' + h', - ' d', - '+ b', - ' g', - ]) - let res = await treeView.checkLines() - expect(res).toBe(true) - }) - - it('should error message on error', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - await nvim.command('exe 2') - await nvim.input('t') - await helper.wait(50) - let msg = 'Unable to fetch children' - provider.getChildren = () => { - throw new Error(msg) - } - updateData([['a']]) - await helper.wait(50) - let line = await nvim.call('getline', [1]) - expect(line).toMatch(msg) - let res = await treeView.checkLines() - expect(res).toBe(true) - }) - - it('should show error message on refresh error', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - makeUpdateUIThrowError() - updateData([ - ['a', [['h'], ['d']]], - ['b', [['e'], ['f']]], - ['g'], - ]) - await helper.wait(50) - let line = await helper.getCmdline() - expect(line).toMatch('Error on updateUI') - }) - - it('should render deprecated node with deprecated highlight', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - let defs: NodeDef[] = [ - ['a'], - ['b'] - ] - let nodes = createNodes(defs) - nodes[0].deprecated = true - provider.update(nodes) - await helper.wait(50) - await checkLines([ - 'test', - ' a', - ' b', - ]) - let ns = await nvim.call('coc#highlight#create_namespace', ['tree']) - let bufnr = await nvim.call('bufnr', ['%']) - let markers = await nvim.call('nvim_buf_get_extmarks', [bufnr, ns, [1, 0], [1, -1], { details: true }]) as any[] - expect(markers.length > 0).toBe(true) - expect(markers[0][3]['hl_group']).toBe('CocDeprecatedHighlight') - }) - }) - - describe('focusItem()', () => { - it('should not throw when node not rendered', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - let c = nodes[0].children[0] - treeView.focusItem(c) - }) - - it('should focus rendered node', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - treeView.focusItem(nodes[1]) - await helper.wait(50) - let line = await nvim.call('getline', ['.']) - expect(line).toBe('+ b') - }) - }) - - describe('reveal()', () => { - it('should throw error when getParent not exists', async () => { - createTreeView(defaultDef) - provider.getParent = undefined - await treeView.show() - await helper.wait(50) - let err - try { - await treeView.reveal(nodes[0].children[0]) - } catch (e) { - err = e - } - expect(err).toBeDefined() - }) - - it('should select item', async () => { - createTreeView(defaultDef) - let c = nodes[0].children[0] - let h = createNode('h') - c.children = [h] - await treeView.show() - await helper.wait(50) - await treeView.reveal(h) - await checkLines([ - 'test', - '- a', - ' - c', - ' h', - ' d', - '+ b', - ' g', - ]) - let selection = treeView.selection - expect(selection.length).toBe(1) - expect(selection[0].label).toBe('h') - let line = await nvim.call('getline', ['.']) - expect(line).toMatch('h') - }) - - it('should not select item', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - await treeView.reveal(nodes[1], { select: false }) - let lnum = await nvim.call('line', ['.']) - expect(lnum).toBe(1) - }) - - it('should focus item', async () => { - createTreeView(defaultDef) - await treeView.show() - await helper.wait(50) - await treeView.reveal(nodes[1], { focus: true }) - let line = await nvim.call('getline', ['.']) - expect(line).toMatch('b') - }) - - it('should expand item whih single level', async () => { - createTreeView(defaultDef) - let c = nodes[0].children[0] - c.children = [createNode('h')] - await treeView.show() - await helper.wait(50) - await treeView.reveal(nodes[0], { expand: true }) - await checkLines([ - 'test', - '- a', - ' + c', - ' d', - '+ b', - ' g', - ]) - }) - - it('should expand item whih 2 level', async () => { - createTreeView(defaultDef) - let c = nodes[0].children[0] - c.children = [createNode('h')] - await treeView.show() - await helper.wait(50) - await treeView.reveal(nodes[0], { expand: 2 }) - await checkLines([ - 'test', - '- a', - ' - c', - ' h', - ' d', - '+ b', - ' g', - ]) - }) - }) - - describe('filter', () => { - async function createFilterTreeView(opts: Partial> = {}): Promise { - createTreeView(defaultDef, { enableFilter: true }, opts) - await treeView.show() - await helper.wait(50) - await nvim.input('f') - await helper.wait(50) - } - - it('should start filter by input', async () => { - await createFilterTreeView() - await checkLines([ - 'test', ' ', ' a', ' c', ' d', ' b', ' e', ' f', ' g' - ]) - await nvim.input('a') - await helper.wait(50) - await checkLines([ - 'test', - 'a ', - ' a', - ]) - }) - - it('should not throw error on filter', async () => { - await createFilterTreeView() - ; (treeView as any).getRenderedLine = () => { - throw new Error('Error on updateUI') - } - await nvim.input('a') - await helper.wait(100) - }) - - it('should add & remove Cursor highlight on window change', async () => { - let winid = await nvim.call('win_getid') - let ns = await nvim.call('coc#highlight#create_namespace', ['tree']) - await createFilterTreeView() - let bufnr = await nvim.call('bufnr', ['%']) - let markers = await nvim.call('nvim_buf_get_extmarks', [bufnr, ns, [1, 0], [1, -1], {}]) as [number, number, number][] - expect(markers[0]).toBeDefined() - await nvim.call('win_gotoid', [winid]) - await helper.wait(50) - markers = await nvim.call('nvim_buf_get_extmarks', [bufnr, ns, [1, 0], [1, -1], {}]) as [number, number, number][] - expect(markers.length).toBe(0) - await nvim.command('wincmd p') - await helper.wait(50) - markers = await nvim.call('nvim_buf_get_extmarks', [bufnr, ns, [1, 0], [1, -1], {}]) as [number, number, number][] - expect(markers.length).toBe(1) - }) - - it('should filter new nodes on data change', async () => { - await createFilterTreeView() - await nvim.input('a') - await helper.wait(50) - updateData([ - ['ab'], - ['e'], - ['fa'] - ]) - await helper.wait(50) - await checkLines([ - 'test', - 'a ', - ' ab', - ' fa', - ]) - }) - - it('should change selected item by and ', async () => { - await createFilterTreeView() - await nvim.input('a') - await helper.wait(50) - updateData([ - ['ab'], - ['fa'] - ]) - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - let curr = treeView.selection[0] - expect(curr.label).toBe('fa') - await nvim.input('') - await helper.wait(50) - curr = treeView.selection[0] - expect(curr.label).toBe('ab') - await nvim.input('') - await helper.wait(50) - curr = treeView.selection[0] - expect(curr.label).toBe('fa') - await nvim.input('') - await helper.wait(50) - curr = treeView.selection[0] - expect(curr.label).toBe('ab') - }) - - it('should not throw with empty nodes', async () => { - await createFilterTreeView() - await nvim.input('ab') - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - await checkLines(['test', 'ab ']) - let curr = treeView.selection[0] - expect(curr).toBeUndefined() - }) - - it('should invoke command by ', async () => { - let node - await createFilterTreeView({ - handleClick: n => { - node = n - } - }) - await nvim.input('') - await helper.wait(50) - expect(node).toBeDefined() - let curr = treeView.selection[0] - expect(curr).toBeDefined() - }) - - it('should keep state when press with empty selection ', async () => { - await createFilterTreeView() - await nvim.input('ab') - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - await checkLines(['test', 'ab ']) - }) - - it('should delete last filter character by ', async () => { - await createFilterTreeView() - await nvim.input('a') - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - await checkLines([ - 'test', ' ', ' a', ' c', ' d', ' b', ' e', ' f', ' g' - ]) - }) - - it('should clean filter character by ', async () => { - await createFilterTreeView() - await nvim.input('ab') - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - await checkLines([ - 'test', ' ', ' a', ' c', ' d', ' b', ' e', ' f', ' g' - ]) - }) - - it('should cancel filter by and ', async () => { - await createFilterTreeView() - await nvim.input('') - await helper.wait(50) - await checkLines([ - 'test', - '+ a', - '+ b', - ' g', - ]) - await nvim.input('f') - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - await checkLines([ - 'test', - '+ a', - '+ b', - ' g', - ]) - }) - - it('should navigate input history by and ', async () => { - await createFilterTreeView() - await nvim.input('a') - await helper.wait(20) - await nvim.input('') - await helper.wait(50) - await nvim.input('f') - await helper.wait(50) - await nvim.input('b') - await helper.wait(20) - await nvim.input('') - await helper.wait(50) - await nvim.input('f') - await helper.wait(50) - await nvim.input('') - await helper.wait(50) - await checkLines([ - 'test', - 'a ', - ' a', - ]) - await nvim.input('') - await helper.wait(50) - await checkLines([ - 'test', - 'b ', - ' b', - ]) - await nvim.input('') - await helper.wait(50) - await checkLines([ - 'test', - 'a ', - ' a', - ]) - await nvim.input('') - await helper.wait(50) - await checkLines([ - 'test', - 'b ', - ' b', - ]) - }) - }) -}) diff --git a/vim-config/plugins/coc.nvim/src/__tests__/vimrc b/vim-config/plugins/coc.nvim/src/__tests__/vimrc deleted file mode 100644 index 60d51897..00000000 --- a/vim-config/plugins/coc.nvim/src/__tests__/vimrc +++ /dev/null @@ -1,26 +0,0 @@ -set nocompatible - -set hidden -set noswapfile -set nobackup -set completeopt=menuone,noinsert,noselect -set tabstop=2 -set cmdheight=2 -set shiftwidth=2 -set updatetime=300 -set expandtab -set noshowmode -set shortmess=at - -let s:dir = expand(':h') -let s:root = expand(':h:h:h') -let g:coc_node_env = 'test' - -let g:coc_vim_commands = [{ - \ "id": "config", - \ "cmd": "edit coc-settings.json" - \ }] - -autocmd BufNewFile,BufRead *.ts set filetype=typescript - -execute 'set runtimepath+='.s:root diff --git a/vim-config/plugins/coc.nvim/src/attach.ts b/vim-config/plugins/coc.nvim/src/attach.ts deleted file mode 100644 index 7650d0cd..00000000 --- a/vim-config/plugins/coc.nvim/src/attach.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { attach, Attach, NeovimClient } from '@chemzqm/neovim' -import log4js from 'log4js' -import events from './events' -import Plugin from './plugin' -import semver from 'semver' -import { objectLiteral } from './util/is' -import { URI } from 'vscode-uri' -import { version as VERSION } from '../package.json' - -const logger = require('./util/logger')('attach') -const isTest = global.hasOwnProperty('__TEST__') -/** - * Request actions that not need plugin ready - */ -const ACTIONS_NO_WAIT = ['installExtensions', 'updateExtensions'] - -export default (opts: Attach, requestApi = true): Plugin => { - const nvim: NeovimClient = attach(opts, log4js.getLogger('node-client'), requestApi) - if (!global.hasOwnProperty('__TEST__')) { - nvim.call('coc#util#path_replace_patterns').then(prefixes => { - if (objectLiteral(prefixes)) { - const old_uri = URI.file - URI.file = (path): URI => { - path = path.replace(/\\/g, '/') - Object.keys(prefixes).forEach(k => path = path.replace(new RegExp('^' + k), prefixes[k])) - return old_uri(path) - } - } - }).logError() - } - nvim.setVar('coc_process_pid', process.pid, true) - const plugin = new Plugin(nvim) - let clientReady = false - let initialized = false - nvim.on('notification', async (method, args) => { - switch (method) { - case 'VimEnter': { - if (!initialized && clientReady) { - initialized = true - await plugin.init() - } - break - } - case 'Log': { - logger.debug(...args) - break - } - case 'TaskExit': - case 'TaskStderr': - case 'TaskStdout': - case 'GlobalChange': - case 'PromptInsert': - case 'InputChar': - case 'MenuInput': - case 'OptionSet': - case 'FloatBtnClick': - await events.fire(method, args) - break - case 'CocAutocmd': - logger.trace('Notification autocmd:', ...args) - await events.fire(args[0], args.slice(1)) - break - default: { - let exists = plugin.hasAction(method) - if (!exists) { - if (global.hasOwnProperty('__TEST__')) return - console.error(`action "${method}" not exists`) - return - } - try { - if (!plugin.isReady) { - logger.warn(`Plugin not ready when received "${method}"`, args) - } else { - logger.info('receive notification:', method, args) - } - await plugin.ready - await plugin.cocAction(method, ...args) - } catch (e) { - console.error(`Error on "${method}": ${e.message || e.toString()}`) - logger.error(`Notification error:`, method, args, e) - } - } - } - }) - - nvim.on('request', async (method: string, args, resp) => { - if (method == 'redraw') { - // ignore redraw from neovim - resp.send() - return - } - let timer = setTimeout(() => { - logger.error('Request cost more than 3s', method, args) - }, 3000) - try { - if (method == 'CocAutocmd') { - logger.trace('Request autocmd:', ...args) - await events.fire(args[0], args.slice(1)) - resp.send(undefined) - } else { - if (!plugin.isReady && !ACTIONS_NO_WAIT.includes(method)) { - logger.warn(`Plugin not ready on request "${method}"`, args) - resp.send('Plugin not ready', true) - return - } - logger.info('Request action:', method, args) - let res = await plugin.cocAction(method, ...args) - resp.send(res) - } - clearTimeout(timer) - } catch (e) { - clearTimeout(timer) - resp.send(e.message || e.toString(), true) - logger.error(`Request error:`, method, args, e) - } - }) - - nvim.channelId.then(async channelId => { - clientReady = true - // Used for test client on vim side - if (isTest) nvim.command(`let g:coc_node_channel_id = ${channelId}`, true) - let { major, minor, patch } = semver.parse(VERSION) - nvim.setClientInfo('coc', { major, minor, patch }, 'remote', {}, {}) - let entered = await nvim.getVvar('vim_did_enter') - if (entered && !initialized) { - initialized = true - await plugin.init() - } - }).catch(e => { - console.error(`Channel create error: ${e.message}`) - }) - return plugin -} diff --git a/vim-config/plugins/coc.nvim/src/channels.ts b/vim-config/plugins/coc.nvim/src/channels.ts deleted file mode 100644 index 6d5b6864..00000000 --- a/vim-config/plugins/coc.nvim/src/channels.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { URI } from 'vscode-uri' -import BufferChannel from './model/outputChannel' -import { Disposable } from 'vscode-languageserver-protocol' -import { TextDocumentContentProvider } from './provider' -import events from './events' -import { OutputChannel } from './types' -const logger = require('./util/logger')('channels') - -export class Channels { - private outputChannels: Map = new Map() - private bufnrs: Map = new Map() - private disposable: Disposable - constructor() { - this.disposable = events.on('BufUnload', bufnr => { - let name = this.bufnrs.get(bufnr) - if (name) { - let channel = this.outputChannels.get(name) - if (channel) channel.created = false - } - }) - } - - /** - * Get text document provider - */ - public getProvider(nvim: Neovim): TextDocumentContentProvider { - let provider: TextDocumentContentProvider = { - onDidChange: null, - provideTextDocumentContent: async (uri: URI) => { - let channel = this.get(uri.path.slice(1)) - if (!channel) return '' - nvim.pauseNotification() - nvim.call('bufnr', ['%'], true) - nvim.command('setlocal nospell nofoldenable nowrap noswapfile', true) - nvim.command('setlocal buftype=nofile bufhidden=hide', true) - nvim.command('setfiletype log', true) - let res = await nvim.resumeNotification() - if (!res[1]) { - this.bufnrs.set(res[0][0], channel.name) - channel.created = true - } - return channel.content - } - } - return provider - } - - public get names(): string[] { - return Array.from(this.outputChannels.keys()) - } - - public get(channelName: string): BufferChannel | null { - return this.outputChannels.get(channelName) - } - - public create(name: string, nvim: Neovim): OutputChannel | null { - if (this.outputChannels.has(name)) return this.outputChannels.get(name) - if (!/^[\w\s-.]+$/.test(name)) throw new Error(`Invalid channel name "${name}", only word characters and white space allowed.`) - let channel = new BufferChannel(name, nvim, () => { - this.outputChannels.delete(name) - }) - this.outputChannels.set(name, channel) - return channel - } - - public show(name: string, preserveFocus?: boolean): void { - let channel = this.outputChannels.get(name) - if (!channel) return - channel.show(preserveFocus) - } - - public dispose(): void { - this.disposable.dispose() - for (let channel of this.outputChannels.values()) { - channel.dispose() - } - this.outputChannels.clear() - } -} - -export default new Channels() diff --git a/vim-config/plugins/coc.nvim/src/commands.ts b/vim-config/plugins/coc.nvim/src/commands.ts deleted file mode 100644 index 704a94bc..00000000 --- a/vim-config/plugins/coc.nvim/src/commands.ts +++ /dev/null @@ -1,379 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import * as language from 'vscode-languageserver-protocol' -import { CodeAction, Disposable, Location, Position, Range, TextDocumentEdit, TextEdit, WorkspaceEdit } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import diagnosticManager from './diagnostic/manager' -import Mru from './model/mru' -import Plugin from './plugin' -import snipetsManager from './snippets/manager' -import { wait } from './util' -import workspace from './workspace' -import window from './window' -const logger = require('./util/logger')('commands') - -// command center -export interface Command { - readonly id: string | string[] - execute(...args: any[]): void | Promise -} - -class CommandItem implements Disposable, Command { - constructor( - public id: string, - private impl: (...args: any[]) => void, - private thisArg: any, - public internal = false - ) { - } - - public execute(...args: any[]): void | Promise { - let { impl, thisArg } = this - return impl.apply(thisArg, args || []) - } - - public dispose(): void { - this.thisArg = null - this.impl = null - } -} - -export class CommandManager implements Disposable { - private readonly commands = new Map() - public titles = new Map() - public onCommandList: string[] = [] - private mru: Mru - - public init(nvim: Neovim, plugin: Plugin): void { - this.mru = workspace.createMru('commands') - this.register({ - id: 'vscode.open', - execute: async (url: string | URI) => { - nvim.call('coc#util#open_url', url.toString(), true) - } - }, true) - this.register({ - id: 'workbench.action.reloadWindow', - execute: async () => { - await nvim.command('edit') - } - }, true) - this.register({ - id: 'editor.action.insertSnippet', - execute: async (edit: TextEdit) => { - nvim.call('coc#_cancel', [], true) - return await snipetsManager.insertSnippet(edit.newText, true, edit.range) - } - }, true) - this.register({ - id: 'editor.action.doCodeAction', - execute: async (action: CodeAction) => { - await plugin.cocAction('doCodeAction', action) - } - }, true) - this.register({ - id: 'editor.action.triggerSuggest', - execute: async () => { - await wait(60) - nvim.call('coc#start', [], true) - } - }, true) - this.register({ - id: 'editor.action.triggerParameterHints', - execute: async () => { - await wait(60) - await plugin.cocAction('showSignatureHelp') - } - }, true) - this.register({ - id: 'editor.action.addRanges', - execute: async (ranges: Range[]) => { - await plugin.cocAction('addRanges', ranges) - } - }, true) - this.register({ - id: 'editor.action.restart', - execute: async () => { - await wait(30) - nvim.command('CocRestart', true) - } - }, true) - this.register({ - id: 'editor.action.showReferences', - execute: async (_filepath: string, _position: Position, references: Location[]) => { - await workspace.showLocations(references) - } - }, true) - this.register({ - id: 'editor.action.rename', - execute: async (uri: string, position: Position) => { - await workspace.jumpTo(uri, position) - await plugin.cocAction('rename') - } - }, true) - this.register({ - id: 'editor.action.format', - execute: async () => { - await plugin.cocAction('format') - } - }, true) - this.register({ - id: 'workspace.clearWatchman', - execute: async () => { - let res = await window.runTerminalCommand('watchman watch-del-all') - if (res.success) window.showMessage('Cleared watchman watching directories.') - } - }, false, 'run watch-del-all for watchman to free up memory.') - this.register({ - id: 'workspace.workspaceFolders', - execute: async () => { - let folders = workspace.workspaceFolders - let lines = folders.map(folder => URI.parse(folder.uri).fsPath) - await window.echoLines(lines) - } - }, false, 'show opened workspaceFolders.') - this.register({ - id: 'workspace.renameCurrentFile', - execute: async () => { - await workspace.renameCurrent() - } - }, false, 'change current filename to a new name and reload it.') - this.register({ - id: 'extensions.toggleAutoUpdate', - execute: async () => { - let config = workspace.getConfiguration('coc.preferences') - let interval = config.get('extensionUpdateCheck', 'daily') - if (interval == 'never') { - config.update('extensionUpdateCheck', 'daily', true) - window.showMessage('Extension auto update enabled.', 'more') - } else { - config.update('extensionUpdateCheck', 'never', true) - window.showMessage('Extension auto update disabled.', 'more') - } - } - }, false, 'toggle auto update of extensions.') - this.register({ - id: 'workspace.diagnosticRelated', - execute: () => diagnosticManager.jumpRelated() - }, false, 'jump to related locations of current diagnostic.') - this.register({ - id: 'workspace.showOutput', - execute: async (name?: string) => { - if (name) { - window.showOutputChannel(name) - } else { - let names = workspace.channelNames - if (names.length == 0) return - if (names.length == 1) { - window.showOutputChannel(names[0]) - } else { - let idx = await window.showQuickpick(names) - if (idx == -1) return - let name = names[idx] - window.showOutputChannel(name) - } - } - } - }, false, 'open output buffer to show output from languageservers or extensions.') - this.register({ - id: 'document.showIncomingCalls', - execute: async () => { - await plugin.cocAction('showIncomingCalls') - } - }, false, 'show incoming calls in tree view.') - this.register({ - id: 'document.showOutgoingCalls', - execute: async () => { - await plugin.cocAction('showOutgoingCalls') - } - }, false, 'show outgoing calls in tree view.') - this.register({ - id: 'document.echoFiletype', - execute: async () => { - let bufnr = await nvim.call('bufnr', '%') - let doc = workspace.getDocument(bufnr) - if (!doc) return - await window.echoLines([doc.filetype]) - } - }, false, 'echo the mapped filetype of the current buffer') - this.register({ - id: 'document.renameCurrentWord', - execute: async () => { - let bufnr = await nvim.call('bufnr', '%') - let doc = workspace.getDocument(bufnr) - if (!doc) return - let edit = await plugin.cocAction('getWordEdit') as WorkspaceEdit - if (!edit) { - window.showMessage('Invalid position', 'warning') - return - } - let ranges: Range[] = [] - let { changes, documentChanges } = edit - if (changes) { - let edits = changes[doc.uri] - if (edits) ranges = edits.map(e => e.range) - } else if (documentChanges) { - for (let c of documentChanges) { - if (TextDocumentEdit.is(c) && c.textDocument.uri == doc.uri) { - ranges = c.edits.map(e => e.range) - } - } - } - if (ranges.length) { - await plugin.cocAction('addRanges', ranges) - } - } - }, false, 'rename word under cursor in current buffer by use multiple cursors.') - this.register({ - id: 'document.jumpToNextSymbol', - execute: async () => { - let doc = await workspace.document - if (!doc) return - let ranges = await plugin.cocAction('symbolRanges') as Range[] - if (!ranges) return - let { textDocument } = doc - let offset = await window.getOffset() - ranges.sort((a, b) => { - if (a.start.line != b.start.line) { - return a.start.line - b.start.line - } - return a.start.character - b.start.character - }) - for (let i = 0; i <= ranges.length - 1; i++) { - if (textDocument.offsetAt(ranges[i].start) > offset) { - await window.moveTo(ranges[i].start) - return - } - } - await window.moveTo(ranges[0].start) - } - }, false, 'Jump to next symbol highlight position.') - this.register({ - id: 'workspace.openLocation', - execute: async (winid: number, loc: Location, openCommand?: string) => { - if (winid) await nvim.call('win_gotoid', [winid]) - await workspace.jumpTo(loc.uri, loc.range.start, openCommand) - } - }, true) - this.register({ - id: 'document.jumpToPrevSymbol', - execute: async () => { - let doc = await workspace.document - if (!doc) return - let ranges = await plugin.cocAction('symbolRanges') as Range[] - if (!ranges) return - let { textDocument } = doc - let offset = await window.getOffset() - ranges.sort((a, b) => { - if (a.start.line != b.start.line) { - return a.start.line - b.start.line - } - return a.start.character - b.start.character - }) - for (let i = ranges.length - 1; i >= 0; i--) { - if (textDocument.offsetAt(ranges[i].end) < offset) { - await window.moveTo(ranges[i].start) - return - } - } - await window.moveTo(ranges[ranges.length - 1].start) - } - }, false, 'Jump to previous symbol highlight position.') - } - - public get commandList(): CommandItem[] { - let res: CommandItem[] = [] - for (let item of this.commands.values()) { - if (!item.internal) res.push(item) - } - return res - } - - public dispose(): void { - for (const registration of this.commands.values()) { - registration.dispose() - } - this.commands.clear() - } - - public execute(command: language.Command): Promise { - let args = [command.command] - let arr = command.arguments - if (arr) args.push(...arr) - return this.executeCommand.apply(this, args) - } - - public register(command: T, internal = false, description?: string): T { - for (const id of Array.isArray(command.id) ? command.id : [command.id]) { - this.registerCommand(id, command.execute, command, internal) - if (description) this.titles.set(id, description) - } - return command - } - - public has(id: string): boolean { - return this.commands.has(id) - } - - public unregister(id: string): void { - let item = this.commands.get(id) - if (!item) return - item.dispose() - this.commands.delete(id) - } - - /** - * Registers a command that can be invoked via a keyboard shortcut, - * a menu item, an action, or directly. - * - * Registering a command with an existing command identifier twice - * will cause an error. - * - * @param command A unique identifier for the command. - * @param impl A command handler function. - * @param thisArg The `this` context used when invoking the handler function. - * @return Disposable which unregisters this command on disposal. - */ - public registerCommand(id: string, impl: (...args: any[]) => void, thisArg?: any, internal = false): Disposable { - if (id.startsWith("_")) internal = true - this.commands.set(id, new CommandItem(id, impl, thisArg, internal)) - return Disposable.create(() => { - this.commands.delete(id) - }) - } - - /** - * Executes the command denoted by the given command identifier. - * - * * *Note 1:* When executing an editor command not all types are allowed to - * be passed as arguments. Allowed are the primitive types `string`, `boolean`, - * `number`, `undefined`, and `null`, as well as [`Position`](#Position), [`Range`](#Range), [`URI`](#URI) and [`Location`](#Location). - * * *Note 2:* There are no restrictions when executing commands that have been contributed - * by extensions. - * - * @param command Identifier of the command to execute. - * @param rest Parameters passed to the command function. - * @return A promise that resolves to the returned value of the given command. `undefined` when - * the command handler function doesn't return anything. - */ - public executeCommand(command: string, ...rest: any[]): Promise { - let cmd = this.commands.get(command) - if (!cmd) throw new Error(`Command: ${command} not found`) - return Promise.resolve(cmd.execute.apply(cmd, rest)) - } - - public async addRecent(cmd: string): Promise { - await this.mru.add(cmd) - await workspace.nvim.command(`silent! call repeat#set("\\(coc-command-repeat)", -1)`) - } - - public async repeatCommand(): Promise { - let mruList = await this.mru.load() - let first = mruList[0] - if (first) { - await this.executeCommand(first) - await workspace.nvim.command(`silent! call repeat#set("\\(coc-command-repeat)", -1)`) - } - } -} - -export default new CommandManager() diff --git a/vim-config/plugins/coc.nvim/src/completion/complete.ts b/vim-config/plugins/coc.nvim/src/completion/complete.ts deleted file mode 100644 index 5684165c..00000000 --- a/vim-config/plugins/coc.nvim/src/completion/complete.ts +++ /dev/null @@ -1,376 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationTokenSource, Emitter, Event, Position } from 'vscode-languageserver-protocol' -import Document from '../model/document' -import { CompleteOption, FloatConfig, VimCompleteItem, CompleteResult, ExtendedCompleteItem, ISource } from '../types' -import { fuzzyMatch, getCharCodes } from '../util/fuzzy' -import { byteSlice, characterIndex } from '../util/string' -import { matchScore } from './match' -const logger = require('../util/logger')('completion-complete') - -export interface CompleteConfig { - disableKind: boolean - disableMenu: boolean - disableMenuShortcut: boolean - enablePreview: boolean - enablePreselect: boolean - labelMaxLength: number - floatEnable: boolean - autoTrigger: string - previewIsKeyword: string - triggerCompletionWait: number - minTriggerInputLength: number - triggerAfterInsertEnter: boolean - acceptSuggestionOnCommitCharacter: boolean - noselect: boolean - keepCompleteopt: boolean - numberSelect: boolean - maxItemCount: number - timeout: number - snippetIndicator: string - fixInsertedWord: boolean - localityBonus: boolean - highPrioritySourceLimit: number - lowPrioritySourceLimit: number - removeDuplicateItems: boolean - defaultSortMethod: string - asciiCharactersOnly: boolean - floatConfig: FloatConfig -} - -export type Callback = () => void - -// first time completion -const FIRST_TIMEOUT = 500 - -export default class Complete { - // identify this complete - public results: CompleteResult[] = [] - private completing: Set = new Set() - private _canceled = false - private localBonus: Map - private tokenSources: Map = new Map() - private readonly _onDidComplete = new Emitter() - public readonly onDidComplete: Event = this._onDidComplete.event - constructor(public option: CompleteOption, - private document: Document, - private config: CompleteConfig, - private sources: ISource[], - private nvim: Neovim) { - } - - public get isCompleting(): boolean { - return this.completing.size > 0 - } - - public get isCanceled(): boolean { - return this._canceled - } - - public get isEmpty(): boolean { - return this.results.length == 0 - } - - public get startcol(): number { - return this.option.col || 0 - } - - public get input(): string { - return this.option.input - } - - public get isIncomplete(): boolean { - return this.results.findIndex(o => o.isIncomplete) !== -1 - } - - private async completeSource(source: ISource): Promise { - let { col } = this.option - // new option for each source - let opt = Object.assign({}, this.option) - let timeout = this.config.timeout - timeout = Math.max(Math.min(timeout, 15000), 500) - try { - if (typeof source.shouldComplete === 'function') { - let shouldRun = await Promise.resolve(source.shouldComplete(opt)) - if (!shouldRun) return null - } - let start = Date.now() - let oldSource = this.tokenSources.get(source.name) - if (oldSource) oldSource.cancel() - let tokenSource = new CancellationTokenSource() - this.tokenSources.set(source.name, tokenSource) - await new Promise((resolve, reject) => { - let { name } = source - let timer = setTimeout(() => { - this.nvim.command(`echohl WarningMsg| echom 'source ${source.name} timeout after ${timeout}ms'|echohl None`, true) - tokenSource.cancel() - }, timeout) - let cancelled = false - let called = false - let empty = false - let ft = setTimeout(() => { - if (called) return - empty = true - resolve(undefined) - }, FIRST_TIMEOUT) - let onFinished = () => { - if (called) return - called = true - disposable.dispose() - clearTimeout(ft) - clearTimeout(timer) - this.tokenSources.delete(name) - } - let disposable = tokenSource.token.onCancellationRequested(() => { - disposable.dispose() - this.completing.delete(name) - cancelled = true - onFinished() - logger.debug(`Source "${name}" cancelled`) - resolve(undefined) - }) - this.completing.add(name) - Promise.resolve(source.doComplete(opt, tokenSource.token)).then(result => { - this.completing.delete(name) - if (cancelled) return - onFinished() - let dt = Date.now() - start - logger.debug(`Source "${name}" takes ${dt}ms`) - if (result && result.items && result.items.length) { - result.priority = source.priority - result.source = name - // lazy completed items - if (empty && result.startcol && result.startcol != col) { - this.results = [result] - } else { - let { results } = this - let idx = results.findIndex(o => o.source == name) - if (idx != -1) { - results.splice(idx, 1, result) - } else { - results.push(result) - } - } - if (empty) this._onDidComplete.fire() - resolve(undefined) - } else { - let { results } = this - this.results = results.filter(res => res.source != name) - resolve(undefined) - } - }, err => { - this.completing.delete(name) - onFinished() - reject(err) - }) - }) - } catch (err) { - this.nvim.command(`echoerr 'Complete ${source.name} error: ${err.message.replace(/'/g, "''")}'`, true) - logger.error('Complete error:', source.name, err) - } - } - - public async completeInComplete(resumeInput: string): Promise { - let { results, document } = this - let remains = results.filter(res => !res.isIncomplete) - remains.forEach(res => { - res.items.forEach(item => delete item.user_data) - }) - let arr = results.filter(res => res.isIncomplete) - let names = arr.map(o => o.source) - let { input, colnr, linenr } = this.option - Object.assign(this.option, { - input: resumeInput, - line: document.getline(linenr - 1), - colnr: colnr + (resumeInput.length - input.length), - triggerCharacter: null, - triggerForInComplete: true - }) - let sources = this.sources.filter(s => names.includes(s.name)) - await Promise.all(sources.map(s => this.completeSource(s))) - return this.filterResults(resumeInput, Math.floor(Date.now() / 1000)) - } - - public filterResults(input: string, cid = 0): ExtendedCompleteItem[] { - let { results } = this - results.sort((a, b) => { - if (a.source == 'tabnine') return 1 - if (b.source == 'tabnine') return -1 - return b.priority - a.priority - }) - let { snippetIndicator, removeDuplicateItems, fixInsertedWord, asciiCharactersOnly } = this.config - let followPart = (!fixInsertedWord || cid == 0) ? '' : this.getFollowPart() - if (results.length == 0) return [] - let arr: ExtendedCompleteItem[] = [] - let codes = getCharCodes(input) - let words: Set = new Set() - for (let i = 0, l = results.length; i < l; i++) { - let res = results[i] - let { items, source, priority } = res - for (let idx = 0; idx < items.length; idx++) { - let item = items[idx] - if (!item || typeof item.word !== 'string') { - continue - } - let { word } = item - // eslint-disable-next-line no-control-regex - if (asciiCharactersOnly && !/^[\x00-\x7F]*$/.test(word)) { - continue - } - if (!item.dup && words.has(word)) continue - if (removeDuplicateItems && !item.isSnippet && words.has(word) && item.line == undefined) continue - let filterText = item.filterText || item.word - item.filterText = filterText - if (filterText.length < input.length) continue - let score = item.kind && filterText == input ? 64 : matchScore(filterText, codes) - if (input.length && score == 0) continue - if (followPart.length && !item.isSnippet) { - if (item.word.endsWith(followPart)) { - let { word } = item - item.word = item.word.slice(0, - followPart.length) - item.abbr = item.abbr || word - } - } - if (!item.user_data) { - let user_data: any = { cid, source } - user_data.index = item.index || idx - if (item.isSnippet) { - let abbr = item.abbr || item.word - if (!abbr.endsWith(snippetIndicator)) { - item.abbr = `${item.abbr || item.word}${snippetIndicator}` - } - } - if (item.signature) user_data.signature = item.signature - item.user_data = JSON.stringify(user_data) - item.source = source - } - item.priority = priority - item.abbr = item.abbr || item.word - item.score = input.length ? score * (item.sourceScore || 1) : 0 - item.localBonus = this.localBonus ? this.localBonus.get(filterText) || 0 : 0 - words.add(word) - if (item.isSnippet && input.length && item.word == input) { - item.preselect = true - } - arr.push(item) - } - } - arr.sort((a, b) => { - let sa = a.sortText - let sb = b.sortText - let wa = a.filterText - let wb = b.filterText - if (a.score != b.score) return b.score - a.score - if (a.priority != b.priority) return b.priority - a.priority - if (sa && sb && sa != sb) return sa < sb ? -1 : 1 - if (a.localBonus != b.localBonus) { - if (a.localBonus && b.localBonus && wa != wb) { - if (wa.startsWith(wb)) return 1 - if (wb.startsWith(wa)) return -1 - } - return b.localBonus - a.localBonus - } - // Default sort method - switch (this.config.defaultSortMethod) { - case 'none': - return 0 - case 'alphabetical': - return a.filterText.localeCompare(b.filterText) - case 'length': - default: // Fallback on length - return a.filterText.length - b.filterText.length - } - }) - return this.limitCompleteItems(arr.slice(0, this.config.maxItemCount)) - } - - private limitCompleteItems(items: ExtendedCompleteItem[]): ExtendedCompleteItem[] { - let { highPrioritySourceLimit, lowPrioritySourceLimit } = this.config - if (!highPrioritySourceLimit && !lowPrioritySourceLimit) return items - let counts: Map = new Map() - return items.filter(item => { - let { priority, source } = item - let isLow = priority < 90 - let curr = counts.get(source) || 0 - if ((lowPrioritySourceLimit && isLow && curr == lowPrioritySourceLimit) - || (highPrioritySourceLimit && !isLow && curr == highPrioritySourceLimit)) { - return false - } - counts.set(source, curr + 1) - return true - }) - } - - public hasMatch(input: string): boolean { - let { results } = this - if (!results) return false - let codes = getCharCodes(input) - for (let i = 0, l = results.length; i < l; i++) { - let items = results[i].items - let idx = items.findIndex(item => fuzzyMatch(codes, item.filterText || item.word)) - if (idx !== -1) return true - } - return false - } - - public async doComplete(): Promise { - let opts = this.option - let { line, colnr, linenr, col } = this.option - if (this.config.localityBonus) { - let line = linenr - 1 - this.localBonus = this.document.getLocalifyBonus(Position.create(line, opts.col - 1), Position.create(line, colnr)) - } else { - this.localBonus = new Map() - } - await Promise.all(this.sources.map(s => this.completeSource(s))) - let { results } = this - if (results.length == 0) return [] - let engrossResult = results.find(r => r.startcol != null && r.startcol != col) - if (engrossResult) { - let { startcol } = engrossResult - opts.col = startcol - opts.input = byteSlice(line, startcol, colnr - 1) - this.results = [engrossResult] - } - logger.info(`Results from: ${this.results.map(s => s.source).join(',')}`) - return this.filterResults(opts.input, Math.floor(Date.now() / 1000)) - } - - public resolveCompletionItem(item: VimCompleteItem): ExtendedCompleteItem | null { - let { results } = this - if (!results) return null - try { - if (item.user_data) { - let { source } = JSON.parse(item.user_data) - let result = results.find(res => res.source == source) - return result.items.find(o => o.user_data == item.user_data) - } - for (let result of results) { - let res = result.items.find(o => o.abbr == item.abbr && o.info == item.info) - if (res) return res - } - return null - } catch (e) { - return null - } - } - - private getFollowPart(): string { - let { colnr, line } = this.option - let idx = characterIndex(line, colnr - 1) - if (idx == line.length) return '' - let part = line.slice(idx - line.length) - return part.match(/^\S?[\w-]*/)[0] - } - - public dispose(): void { - if (this._canceled) return - this._onDidComplete.dispose() - this._canceled = true - for (let tokenSource of this.tokenSources.values()) { - tokenSource.cancel() - } - this.tokenSources.clear() - this.sources = [] - this.results = [] - } -} diff --git a/vim-config/plugins/coc.nvim/src/completion/floating.ts b/vim-config/plugins/coc.nvim/src/completion/floating.ts deleted file mode 100644 index a7a3fa38..00000000 --- a/vim-config/plugins/coc.nvim/src/completion/floating.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationToken } from 'vscode-jsonrpc' -import { FloatConfig } from '../types' -import { parseDocuments, Documentation } from '../markdown' -const logger = require('../util/logger')('floating') - -export interface PumBounding { - readonly height: number - readonly width: number - readonly row: number - readonly col: number - readonly scrollbar: boolean -} - -export interface FloatingConfig extends FloatConfig { - excludeImages: boolean -} - -export default class Floating { - private winid = 0 - private bufnr = 0 - - constructor( - private nvim: Neovim, - private isVim: boolean) { - } - - public async show(docs: Documentation[], bounding: PumBounding, config: FloatingConfig, token: CancellationToken): Promise { - let { nvim } = this - docs = docs.filter(o => o.content.trim().length > 0) - let { lines, codes, highlights } = parseDocuments(docs, { excludeImages: config.excludeImages }) - if (lines.length == 0) { - this.close() - return - } - let opts: any = { - codes, - highlights, - maxWidth: config.maxWidth || 80, - pumbounding: bounding, - } - if (config.border) opts.border = [1, 1, 1, 1] - if (config.highlight) opts.highlight = config.highlight - if (config.borderhighlight) opts.borderhighlight = config.borderhighlight - if (!this.isVim) { - if (typeof config.winblend === 'number') opts.winblend = config.winblend - opts.focusable = config.focusable === true ? 1 : 0 - if (config.shadow) opts.shadow = 1 - } - let res = await nvim.call('coc#float#create_pum_float', [this.winid, this.bufnr, lines, opts]) - // can't use redrawVim which lost the cursor. - if (this.isVim) nvim.command('redraw', true) - if (!res || res.length == 0) return - this.winid = res[0] - this.bufnr = res[1] - if (token.isCancellationRequested) { - this.close() - return - } - } - - public close(): void { - let { winid, nvim } = this - this.winid = 0 - if (!winid) return - nvim.call('coc#float#close', [winid], true) - if (this.isVim) nvim.command('redraw', true) - } -} diff --git a/vim-config/plugins/coc.nvim/src/completion/index.ts b/vim-config/plugins/coc.nvim/src/completion/index.ts deleted file mode 100644 index dbe871dd..00000000 --- a/vim-config/plugins/coc.nvim/src/completion/index.ts +++ /dev/null @@ -1,623 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationToken, CancellationTokenSource, Disposable } from 'vscode-languageserver-protocol' -import events, { PopupChangeEvent, InsertChange } from '../events' -import Document from '../model/document' -import sources from '../sources' -import { CompleteOption, ISource, VimCompleteItem, ExtendedCompleteItem, FloatConfig } from '../types' -import { disposeAll, wait } from '../util' -import * as Is from '../util/is' -import workspace from '../workspace' -import Complete, { CompleteConfig } from './complete' -import Floating, { PumBounding } from './floating' -import debounce from 'debounce' -import { byteSlice } from '../util/string' -import { equals } from '../util/object' -const logger = require('../util/logger')('completion') -const completeItemKeys = ['abbr', 'menu', 'info', 'kind', 'icase', 'dup', 'empty', 'user_data'] - -export interface LastInsert { - character: string - timestamp: number -} - -export class Completion implements Disposable { - public config: CompleteConfig - private popupEvent: PopupChangeEvent - private triggerTimer: NodeJS.Timer - private floating: Floating - // current input string - private activated = false - private input: string - private lastInsert?: LastInsert - private disposables: Disposable[] = [] - private complete: Complete | null = null - private resolveTokenSource: CancellationTokenSource - private pretext: string - private changedTick = 0 - private insertCharTs = 0 - private insertLeaveTs = 0 - private excludeImages: boolean - - public init(): void { - this.config = this.getCompleteConfig() - workspace.onDidChangeConfiguration(e => { - if (e.affectsConfiguration('suggest')) { - this.config = this.getCompleteConfig() - } - }, null, this.disposables) - workspace.watchOption('completeopt', async (_, newValue) => { - workspace.env.completeOpt = newValue - if (!this.isActivated) return - if (this.config.autoTrigger === 'always') { - let content = await this.nvim.call('execute', ['verbose set completeopt']) as string - let lines = content.split(/\r?\n/) - console.error(`Some plugin change completeopt during completion: ${lines[lines.length - 1].trim()}!`) - } - }, this.disposables) - this.excludeImages = workspace.getConfiguration('coc.preferences').get('excludeImageLinksInMarkdownDocument') - this.floating = new Floating(workspace.nvim, workspace.env.isVim) - events.on(['InsertCharPre', 'MenuPopupChanged', 'TextChangedI', 'CursorMovedI', 'InsertLeave'], () => { - if (this.triggerTimer) { - clearTimeout(this.triggerTimer) - this.triggerTimer = null - } - }, this, this.disposables) - events.on('InsertCharPre', this.onInsertCharPre, this, this.disposables) - events.on('InsertLeave', this.onInsertLeave, this, this.disposables) - events.on('InsertEnter', this.onInsertEnter, this, this.disposables) - events.on('TextChangedP', this.onTextChangedP, this, this.disposables) - events.on('TextChangedI', this.onTextChangedI, this, this.disposables) - let fn = debounce(this.onPumChange.bind(this), 20) - this.disposables.push({ - dispose: () => { - fn.clear() - } - }) - events.on('CompleteDone', async item => { - this.popupEvent = null - if (!this.activated) return - fn.clear() - this.cancelResolve() - this.floating.close() - await this.onCompleteDone(item) - }, this, this.disposables) - this.cancelResolve() - events.on('MenuPopupChanged', ev => { - if (!this.activated || this.isCommandLine) return - if (equals(this.popupEvent, ev)) return - this.cancelResolve() - this.popupEvent = ev - fn() - }, this, this.disposables) - } - - private get nvim(): Neovim { - return workspace.nvim - } - - public get option(): CompleteOption { - if (!this.complete) return null - return this.complete.option - } - - private get selectedItem(): VimCompleteItem | null { - if (!this.popupEvent) return null - let { completed_item } = this.popupEvent - return Is.vimCompleteItem(completed_item) ? completed_item : null - } - - private get isCommandLine(): boolean { - return this.document?.uri.endsWith('%5BCommand%20Line%5D') - } - - public get isActivated(): boolean { - return this.activated - } - - private get document(): Document | null { - if (!this.option) return null - return workspace.getDocument(this.option.bufnr) - } - - private getCompleteConfig(): CompleteConfig { - let suggest = workspace.getConfiguration('suggest') - function getConfig(key, defaultValue: T): T { - return suggest.get(key, defaultValue) - } - let keepCompleteopt = getConfig('keepCompleteopt', false) - let autoTrigger = getConfig('autoTrigger', 'always') - if (keepCompleteopt && autoTrigger != 'none') { - let { completeOpt } = workspace - if (!completeOpt.includes('noinsert') && !completeOpt.includes('noselect')) { - autoTrigger = 'none' - } - } - let floatEnable = workspace.floatSupported && getConfig('floatEnable', true) - let acceptSuggestionOnCommitCharacter = workspace.env.pumevent && getConfig('acceptSuggestionOnCommitCharacter', false) - return { - autoTrigger, - floatEnable, - keepCompleteopt, - floatConfig: getConfig('floatConfig', {}), - defaultSortMethod: getConfig('defaultSortMethod', 'length'), - removeDuplicateItems: getConfig('removeDuplicateItems', false), - disableMenuShortcut: getConfig('disableMenuShortcut', false), - acceptSuggestionOnCommitCharacter, - disableKind: getConfig('disableKind', false), - disableMenu: getConfig('disableMenu', false), - previewIsKeyword: getConfig('previewIsKeyword', '@,48-57,_192-255'), - enablePreview: getConfig('enablePreview', false), - enablePreselect: getConfig('enablePreselect', false), - triggerCompletionWait: getConfig('triggerCompletionWait', 100), - labelMaxLength: getConfig('labelMaxLength', 200), - triggerAfterInsertEnter: getConfig('triggerAfterInsertEnter', false), - noselect: getConfig('noselect', true), - numberSelect: getConfig('numberSelect', false), - maxItemCount: getConfig('maxCompleteItemCount', 50), - timeout: getConfig('timeout', 500), - minTriggerInputLength: getConfig('minTriggerInputLength', 1), - snippetIndicator: getConfig('snippetIndicator', '~'), - fixInsertedWord: getConfig('fixInsertedWord', true), - localityBonus: getConfig('localityBonus', true), - highPrioritySourceLimit: getConfig('highPrioritySourceLimit', null), - lowPrioritySourceLimit: getConfig('lowPrioritySourceLimit', null), - asciiCharactersOnly: getConfig('asciiCharactersOnly', false) - } - } - - public async startCompletion(option: CompleteOption): Promise { - this.pretext = byteSlice(option.line, 0, option.colnr - 1) - try { - await this._doComplete(option) - } catch (e) { - this.stop() - logger.error('Complete error:', e.stack) - } - } - - private async resumeCompletion(force = false): Promise { - let { document, complete } = this - if (!document - || complete.isCanceled - || !complete.results - || complete.results.length == 0) return - let search = this.getResumeInput() - if (search == this.input && !force) return - if (!search || search.endsWith(' ') || !search.startsWith(complete.input)) { - this.stop() - return - } - this.input = search - let items: VimCompleteItem[] = [] - if (complete.isIncomplete) { - await document.patchChange(true) - let { changedtick } = document - items = await complete.completeInComplete(search) - if (complete.isCanceled || document.changedtick != changedtick) return - } else { - items = complete.filterResults(search) - } - if (!complete.isCompleting && items.length === 0) { - this.stop() - return - } - await this.showCompletion(complete.option.col, items) - } - - public hasSelected(): boolean { - if (workspace.env.pumevent) return this.selectedItem != null - if (!this.config.noselect) return true - return false - } - - private async showCompletion(col: number, items: ExtendedCompleteItem[]): Promise { - let { nvim, document, option } = this - let { numberSelect, disableKind, labelMaxLength, disableMenuShortcut, disableMenu } = this.config - let preselect = this.config.enablePreselect ? items.findIndex(o => o.preselect) : -1 - if (numberSelect && option.input.length && !/^\d/.test(option.input)) { - items = items.map((item, i) => { - let idx = i + 1 - if (i < 9) { - return Object.assign({}, item, { - abbr: item.abbr ? `${idx} ${item.abbr}` : `${idx} ${item.word}` - }) - } - return item - }) - nvim.call('coc#_map', [], true) - } - this.changedTick = document.changedtick - let validKeys = completeItemKeys.slice() - if (disableKind) validKeys = validKeys.filter(s => s != 'kind') - if (disableMenu) validKeys = validKeys.filter(s => s != 'menu') - let vimItems = items.map(item => { - let obj = { word: item.word, equal: 1 } - for (let key of validKeys) { - if (item.hasOwnProperty(key)) { - if (disableMenuShortcut && key == 'menu') { - obj[key] = item[key].replace(/\[.+\]$/, '') - } else if (key == 'abbr' && item[key].length > labelMaxLength) { - obj[key] = item[key].slice(0, labelMaxLength) - } else { - obj[key] = item[key] - } - } - } - return obj - }) - nvim.call('coc#_do_complete', [col, vimItems, preselect], true) - } - - private async _doComplete(option: CompleteOption): Promise { - let { source } = option - let { nvim, config } = this - let doc = workspace.getDocument(option.bufnr) - if (!doc || !doc.attached) return - // use fixed filetype - option.filetype = doc.filetype - // current input - this.input = option.input - let arr: ISource[] = [] - if (source == null) { - arr = sources.getCompleteSources(option) - } else { - let s = sources.getSource(source) - if (s) arr.push(s) - } - if (!arr.length) return - await doc.patchChange() - // document get changed, not complete - if (doc.changedtick != option.changedtick) return - let complete = new Complete(option, doc, config, arr, nvim) - this.start(complete) - let items = await this.complete.doComplete() - if (complete.isCanceled) return - if (items.length == 0 && !complete.isCompleting) { - this.stop() - return - } - complete.onDidComplete(async () => { - if (this.selectedItem != null) return - let search = this.getResumeInput() - if (complete.isCanceled || search == null) return - let { input } = this.option - if (search == input) { - let items = complete.filterResults(search, Math.floor(Date.now() / 1000)) - await this.showCompletion(option.col, items) - } else { - await this.resumeCompletion() - } - }) - if (items.length) { - let search = this.getResumeInput() - if (search == option.input) { - await this.showCompletion(option.col, items) - } else { - await this.resumeCompletion(true) - } - } - } - - private async onTextChangedP(bufnr: number, info: InsertChange): Promise { - let { option, document } = this - let pretext = this.pretext = info.pre - // avoid trigger filter on pumvisible - if (!option || option.bufnr != bufnr || info.changedtick == this.changedTick) return - let hasInsert = this.latestInsert != null - this.lastInsert = null - if (info.pre.match(/^\s*/)[0] !== option.line.match(/^\s*/)[0]) { - // Can't handle indent change - logger.warn('Complete stopped by indent change.') - this.stop(false) - return - } - // not handle when not triggered by character insert - if (!hasInsert || !pretext) return - if (sources.shouldTrigger(pretext, document.filetype, document.uri)) { - await this.triggerCompletion(document, pretext) - } else { - await this.resumeCompletion() - } - } - - private async onTextChangedI(bufnr: number, info: InsertChange): Promise { - let { nvim, latestInsertChar, option } = this - let noChange = this.pretext == info.pre - let pretext = this.pretext = info.pre - this.lastInsert = null - let doc = workspace.getDocument(bufnr) - if (!doc) return - // try trigger on character type - if (!this.activated) { - if (!latestInsertChar) return - let triggerSources = sources.getTriggerSources(pretext, doc.filetype, doc.uri) - if (triggerSources.length) { - await this.triggerCompletion(doc, this.pretext) - return - } - this.triggerTimer = setTimeout(async () => { - await this.triggerCompletion(doc, pretext) - }, this.config.triggerCompletionWait) - return - } - // Ignore change with other buffer - if (!option || bufnr != option.bufnr) return - if (option.linenr != info.lnum || option.col >= info.col - 1) { - this.stop() - return - } - // Completion is canceled by - if (noChange && !latestInsertChar) { - this.stop(false) - return - } - // Check commit character - if (pretext - && this.selectedItem - && this.config.acceptSuggestionOnCommitCharacter - && latestInsertChar) { - let resolvedItem = this.getCompleteItem(this.selectedItem) - let last = pretext[pretext.length - 1] - if (sources.shouldCommit(resolvedItem, last)) { - let { linenr, col, line, colnr } = this.option - this.stop() - let { word } = resolvedItem - let newLine = `${line.slice(0, col)}${word}${latestInsertChar}${line.slice(colnr - 1)}` - await nvim.call('coc#util#setline', [linenr, newLine]) - let curcol = col + word.length + 2 - await nvim.call('cursor', [linenr, curcol]) - await doc.patchChange() - return - } - } - // prefer trigger completion - if (sources.shouldTrigger(pretext, doc.filetype, doc.uri)) { - await this.triggerCompletion(doc, pretext) - } else { - await this.resumeCompletion() - } - } - - private async triggerCompletion(doc: Document, pre: string): Promise { - if (!doc || !doc.attached) { - logger.warn('Document not attached, suggest disabled.') - return - } - // check trigger - let shouldTrigger = this.shouldTrigger(doc, pre) - if (!shouldTrigger) return - if (doc.getVar('suggest_disable')) { - logger.warn(`Suggest disabled by b:coc_suggest_disable`) - return - } - await doc.patchChange() - let [disabled, option] = await this.nvim.eval('[get(b:,"coc_suggest_disable",0),coc#util#get_complete_option()]') as [number, CompleteOption] - if (disabled == 1) { - logger.warn(`Suggest disabled by b:coc_suggest_disable`) - return - } - if (option.blacklist && option.blacklist.includes(option.input)) { - logger.warn(`Suggest disabled by b:coc_suggest_blacklist`, option.blacklist) - return - } - if (pre.length) { - option.triggerCharacter = pre.slice(-1) - } - logger.debug('trigger completion with', option) - await this.startCompletion(option) - } - - private async onCompleteDone(item: VimCompleteItem): Promise { - let { document, isActivated } = this - if (!isActivated || !document || !Is.vimCompleteItem(item)) return - let opt = Object.assign({}, this.option) - let resolvedItem = this.getCompleteItem(item) - this.stop() - if (!resolvedItem) return - let timestamp = this.insertCharTs - let insertLeaveTs = this.insertLeaveTs - let source = new CancellationTokenSource() - await this.doCompleteResolve(resolvedItem, source.token) - source.dispose() - // Wait possible TextChangedI - await wait(50) - if (this.insertCharTs != timestamp || this.insertLeaveTs != insertLeaveTs) return - let [visible, lnum, pre] = await this.nvim.eval(`[pumvisible(),line('.'),strpart(getline('.'), 0, col('.') - 1)]`) as [number, number, string] - if (visible || lnum != opt.linenr || this.activated || !pre.endsWith(resolvedItem.word)) return - await document.patchChange(true) - await this.doCompleteDone(resolvedItem, opt) - } - - private async doCompleteResolve(item: ExtendedCompleteItem, token: CancellationToken): Promise { - let source = sources.getSource(item.source) - if (source && typeof source.onCompleteResolve == 'function') { - try { - await Promise.resolve(source.onCompleteResolve(item, token)) - } catch (e) { - logger.error('Error on complete resolve:', e.stack) - } - } - } - - public async doCompleteDone(item: ExtendedCompleteItem, opt: CompleteOption): Promise { - let data = JSON.parse(item.user_data) - let source = sources.getSource(data.source) - if (source && typeof source.onCompleteDone === 'function') { - await Promise.resolve(source.onCompleteDone(item, opt)) - } - } - - private async onInsertLeave(): Promise { - this.insertLeaveTs = Date.now() - this.stop(false) - } - - private async onInsertEnter(bufnr: number): Promise { - if (!this.config.triggerAfterInsertEnter || this.config.autoTrigger !== 'always') return - let doc = workspace.getDocument(bufnr) - if (!doc) return - let pre = await this.nvim.eval(`strpart(getline('.'), 0, col('.') - 1)`) as string - if (!pre) return - await this.triggerCompletion(doc, pre) - } - - private async onInsertCharPre(character: string): Promise { - this.lastInsert = { - character, - timestamp: Date.now(), - } - this.insertCharTs = this.lastInsert.timestamp - } - - private get latestInsert(): LastInsert | null { - let { lastInsert } = this - if (!lastInsert || Date.now() - lastInsert.timestamp > 500) { - return null - } - return lastInsert - } - - private get latestInsertChar(): string { - let { latestInsert } = this - if (!latestInsert) return '' - return latestInsert.character - } - - public shouldTrigger(doc: Document, pre: string): boolean { - let autoTrigger = this.config.autoTrigger - if (autoTrigger == 'none') return false - if (sources.shouldTrigger(pre, doc.filetype, doc.uri)) return true - if (autoTrigger !== 'always' || this.isActivated) return false - let last = pre.slice(-1) - if (last && (doc.isWord(pre.slice(-1)) || last.codePointAt(0) > 255)) { - let minLength = this.config.minTriggerInputLength - if (minLength == 1) return true - let input = this.getInput(doc, pre) - return input.length >= minLength - } - return false - } - - private async onPumChange(): Promise { - if (!this.popupEvent) return - let { col, row, height, width, scrollbar } = this.popupEvent - let bounding: PumBounding = { col, row, height, width, scrollbar } - let resolvedItem = this.getCompleteItem(this.selectedItem) - if (!resolvedItem) { - this.floating.close() - return - } - let source = this.resolveTokenSource = new CancellationTokenSource() - let { token } = source - await this.doCompleteResolve(resolvedItem, token) - if (this.resolveTokenSource == source) { - this.resolveTokenSource = null - } - source.dispose() - if (token.isCancellationRequested) return - let docs = resolvedItem.documentation - if (!docs && resolvedItem.info) { - let { info } = resolvedItem - let isText = /^[\w-\s.,\t]+$/.test(info) - docs = [{ filetype: isText ? 'txt' : this.document.filetype, content: info }] - } - if (!docs || docs.length == 0) { - this.floating.close() - } else { - if (this.config.floatEnable) { - let source = new CancellationTokenSource() - await this.floating.show(docs, bounding, Object.assign({}, this.config.floatConfig, { - excludeImages: this.excludeImages - }), source.token) - } - if (!this.isActivated) { - this.floating.close() - } - } - } - - public start(complete: Complete): void { - let { activated } = this - this.activated = true - if (activated) { - this.complete.dispose() - } - this.complete = complete - if (!this.config.keepCompleteopt) { - this.nvim.command(`noa set completeopt=${this.completeOpt}`, true) - } - } - - private cancelResolve(): void { - if (this.resolveTokenSource) { - this.resolveTokenSource.cancel() - this.resolveTokenSource = null - } - } - - public stop(hide = true): void { - let { nvim } = this - if (!this.activated) return - this.cancelResolve() - this.floating.close() - this.activated = false - if (this.complete) { - this.complete.dispose() - this.complete = null - } - nvim.pauseNotification() - if (hide) { - nvim.call('coc#_hide', [], true) - } - if (this.config.numberSelect) { - nvim.call('coc#_unmap', [], true) - } - if (!this.config.keepCompleteopt) { - nvim.command(`noa set completeopt=${workspace.completeOpt}`, true) - } - nvim.command(`let g:coc#_context = {'start': 0, 'preselect': -1,'candidates': []}`, true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } - - private getInput(document: Document, pre: string): string { - let input = '' - for (let i = pre.length - 1; i >= 0; i--) { - let ch = i == 0 ? null : pre[i - 1] - if (!ch || !document.isWord(ch)) { - input = pre.slice(i, pre.length) - break - } - } - return input - } - - public getResumeInput(): string { - let { option, pretext } = this - if (!option) return null - let buf = Buffer.from(pretext, 'utf8') - if (buf.length < option.col) return null - let input = buf.slice(option.col).toString('utf8') - if (option.blacklist && option.blacklist.includes(input)) return null - return input - } - - private get completeOpt(): string { - let { noselect, enablePreview } = this.config - let preview = enablePreview && !workspace.env.pumevent ? ',preview' : '' - if (noselect) return `noselect,menuone${preview}` - return `noinsert,menuone${preview}` - } - - private getCompleteItem(item: VimCompleteItem | {} | null): ExtendedCompleteItem | null { - if (!this.complete || !Is.vimCompleteItem(item)) return null - return this.complete.resolveCompletionItem(item) - } - - public dispose(): void { - this.resolveTokenSource = null - disposeAll(this.disposables) - } -} - -export default new Completion() diff --git a/vim-config/plugins/coc.nvim/src/completion/match.ts b/vim-config/plugins/coc.nvim/src/completion/match.ts deleted file mode 100644 index b82d6087..00000000 --- a/vim-config/plugins/coc.nvim/src/completion/match.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { getCharCodes, caseMatch, wordChar } from '../util/fuzzy' - -function nextWordIndex(start = 0, codes: number[]): number { - for (let i = start; i < codes.length; i++) { - if (isWordIndex(i, codes)) { - return i - } - } - return -1 -} - -function upperCase(code: number): boolean { - return code >= 65 && code <= 90 -} - -function isWordIndex(index: number, codes: number[]): boolean { - if (index == 0) return true - let curr = codes[index] - if (!wordChar(curr)) return false - let pre = codes[index - 1] - if (!wordChar(pre)) return true - if (upperCase(curr) && !upperCase(pre)) return true - return false -} - -/** - * Rules: - * - First strict 5, first case match 2.5 - * - First word character strict 2.5, first word character case 2 - * - First fuzzy match strict 1, first fuzzy case 0.5 - * - Follow strict 1, follow case 0.5 - * - Follow word start 1, follow word case 0.75 - * - First fuzzy strict 0.1, first fuzzy case 0.05 - * - * @public - * @param {string} word - * @param {number[]} input - * @returns {number} - */ -export function matchScore(word: string, input: number[]): number { - if (input.length == 0 || word.length < input.length) return 0 - let codes = getCharCodes(word) - let curr = codes[0] - let score = 0 - let first = input[0] - let idx = 1 - let allowFuzzy = true - if (caseMatch(first, curr)) { - score = first == curr ? 5 : 2.5 - idx = 1 - } else { - // first word 2.5/2 - let next = nextWordIndex(1, codes) - if (next != -1) { - if (caseMatch(first, codes[next])) { - score = first == codes[next] ? 2.5 : 2 - idx = next + 1 - } - } - if (score == 0) { - // first fuzzy 1/0.5 - for (let i = 1; i < codes.length; i++) { - if (caseMatch(first, codes[i])) { - score = first == codes[i] ? 1 : 0.5 - idx = i + 1 - allowFuzzy = false - } - } - } - } - if (input.length == 1 || score == 0) return score - let next = nextScore(codes, idx, input.slice(1), allowFuzzy) - return next == 0 ? 0 : score + next -} - -function nextScore(codes: number[], index: number, inputCodes: number[], allowFuzzy = true): number { - if (index >= codes.length) return 0 - let scores: number[] = [] - let input = inputCodes[0] - let len = codes.length - let isFinal = inputCodes.length == 1 - if (!wordChar(input)) { - for (let i = index; i < len; i++) { - if (codes[i] == input) { - if (isFinal) return 1 - let next = nextScore(codes, i + 1, inputCodes.slice(1), allowFuzzy) - return next == 0 ? 0 : 1 + next - } - } - return 0 - } - let curr = codes[index] - let match = caseMatch(input, curr) - if (match) { - let score = input == curr ? 1 : 0.5 - if (!isFinal) { - let next = nextScore(codes, index + 1, inputCodes.slice(1), allowFuzzy) - score = next == 0 ? 0 : score + next - } - scores.push(score) - } - // should not find if current is word index - if (wordChar(input) && !isWordIndex(index, codes)) { - let idx = nextWordIndex(index + 1, codes) - if (idx !== -1) { - let next = codes[idx] - if (caseMatch(input, next)) { - let score = input == next ? 1 : 0.75 - if (!isFinal) { - let next = nextScore(codes, idx + 1, inputCodes.slice(1), allowFuzzy) - score = next == 0 ? 0 : score + next - } - scores.push(score) - } - } - } - // find fuzzy - if (!match && allowFuzzy) { - for (let i = index + 1; i < len; i++) { - let code = codes[i] - if (caseMatch(input, code)) { - let score = input == code ? 0.1 : 0.05 - if (!isFinal) { - let next = nextScore(codes, i + 1, inputCodes.slice(1), false) - score = next == 0 ? 0 : score + next - } - scores.push(score) - } - } - } - if (!scores.length) return 0 - return Math.max(...scores) -} diff --git a/vim-config/plugins/coc.nvim/src/configuration/configuration.ts b/vim-config/plugins/coc.nvim/src/configuration/configuration.ts deleted file mode 100644 index dcd13aff..00000000 --- a/vim-config/plugins/coc.nvim/src/configuration/configuration.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { ConfigurationModel } from './model' -import { IConfigurationData } from '../types' - -export class Configuration { - private _consolidateConfiguration: ConfigurationModel - - constructor( - private _defaultConfiguration: ConfigurationModel, - private _userConfiguration: ConfigurationModel, - private _workspaceConfiguration: ConfigurationModel, - private _memoryConfiguration: ConfigurationModel = new ConfigurationModel(), - ) { - } - - private getConsolidateConfiguration(): ConfigurationModel { - if (!this._consolidateConfiguration) { - this._consolidateConfiguration = this._defaultConfiguration.merge(this._userConfiguration, this._workspaceConfiguration, this._memoryConfiguration) - this._consolidateConfiguration = this._consolidateConfiguration.freeze() - } - return this._consolidateConfiguration - } - - public getValue(section?: string): any { - let configuration = this.getConsolidateConfiguration() - return configuration.getValue(section) - } - - public inspect(key: string): { - default: C - user: C - workspace: C - memory?: C - value: C - } { - const consolidateConfigurationModel = this.getConsolidateConfiguration() - const { _workspaceConfiguration, _memoryConfiguration } = this - return { - default: this._defaultConfiguration.freeze().getValue(key), - user: this._userConfiguration.freeze().getValue(key), - workspace: _workspaceConfiguration.freeze().getValue(key), - memory: _memoryConfiguration.freeze().getValue(key), - value: consolidateConfigurationModel.getValue(key) - } - } - - public get defaults(): ConfigurationModel { - return this._defaultConfiguration - } - - public get user(): ConfigurationModel { - return this._userConfiguration - } - - public get workspace(): ConfigurationModel { - return this._workspaceConfiguration - } - - public toData(): IConfigurationData { - return { - defaults: { - contents: this._defaultConfiguration.contents - }, - user: { - contents: this._userConfiguration.contents - }, - workspace: { - contents: this._workspaceConfiguration.contents - } - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/configuration/index.ts b/vim-config/plugins/coc.nvim/src/configuration/index.ts deleted file mode 100644 index f0c151c4..00000000 --- a/vim-config/plugins/coc.nvim/src/configuration/index.ts +++ /dev/null @@ -1,338 +0,0 @@ -import os from 'os' -import fs from 'fs' -import path from 'path' -import { Emitter, Event, Disposable } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import { ConfigurationChangeEvent, ConfigurationInspect, ConfigurationShape, ConfigurationTarget, ErrorItem, IConfigurationData, IConfigurationModel, WorkspaceConfiguration } from '../types' -import { deepClone, deepFreeze, mixin } from '../util/object' -import { watchFile, disposeAll, CONFIG_FILE_NAME } from '../util' -import { Configuration } from './configuration' -import { ConfigurationModel } from './model' -import { addToValueTree, loadDefaultConfigurations, parseContentFromFile, getChangedKeys } from './util' -import { objectLiteral } from '../util/is' -import { isParentFolder, findUp } from '../util/fs' -const logger = require('../util/logger')('configurations') - -function lookUp(tree: any, key: string): any { - if (key) { - if (tree && tree.hasOwnProperty(key)) return tree[key] - const parts = key.split('.') - let node = tree - for (let i = 0; node && i < parts.length; i++) { - node = node[parts[i]] - } - return node - } - return tree -} - -export default class Configurations { - private _configuration: Configuration - private _errorItems: ErrorItem[] = [] - private _folderConfigurations: Map = new Map() - private _onError = new Emitter() - private _onChange = new Emitter() - private disposables: Disposable[] = [] - private workspaceConfigFile: string - - public readonly onError: Event = this._onError.event - public readonly onDidChange: Event = this._onChange.event - - constructor( - private userConfigFile?: string | null, - private readonly _proxy?: ConfigurationShape - ) { - let user = this.parseContentFromFile(userConfigFile) - let data: IConfigurationData = { - defaults: loadDefaultConfigurations(), - user, - workspace: { contents: {} } - } - this._configuration = Configurations.parse(data) - this.watchFile(userConfigFile, ConfigurationTarget.User) - let folderConfigFile = path.join(process.cwd(), `.vim/${CONFIG_FILE_NAME}`) - if (folderConfigFile != userConfigFile && fs.existsSync(folderConfigFile)) { - this.addFolderFile(folderConfigFile) - } - } - - private parseContentFromFile(filepath: string): IConfigurationModel { - if (!filepath) return { contents: {} } - let uri = URI.file(filepath).toString() - this._errorItems = this._errorItems.filter(o => o.location.uri != uri) - let res = parseContentFromFile(filepath, errors => { - this._errorItems.push(...errors) - }) - this._onError.fire(this._errorItems) - return res - } - - public get errorItems(): ErrorItem[] { - return this._errorItems - } - - public get foldConfigurations(): Map { - return this._folderConfigurations - } - - // used for extensions, no change event fired - public extendsDefaults(props: { [key: string]: any }): void { - let { defaults } = this._configuration - let { contents } = defaults - contents = deepClone(contents) - Object.keys(props).forEach(key => { - addToValueTree(contents, key, props[key], msg => { - logger.error(msg) - }) - }) - let data: IConfigurationData = { - defaults: { contents }, - user: this._configuration.user, - workspace: this._configuration.workspace - } - this._configuration = Configurations.parse(data) - } - - // change user configuration, without change file - public updateUserConfig(props: { [key: string]: any }): void { - if (!props || Object.keys(props).length == 0) return - let { user } = this._configuration - let model = user.clone() - Object.keys(props).forEach(key => { - let val = props[key] - if (val === undefined) { - model.removeValue(key) - } else if (objectLiteral(val)) { - for (let k of Object.keys(val)) { - model.setValue(`${key}.${k}`, val[k]) - } - } else { - model.setValue(key, val) - } - }) - this.changeConfiguration(ConfigurationTarget.User, model) - } - - public get defaults(): ConfigurationModel { - return this._configuration.defaults - } - - public get user(): ConfigurationModel { - return this._configuration.user - } - - public get workspace(): ConfigurationModel { - return this._configuration.workspace - } - - public addFolderFile(filepath: string): void { - let { _folderConfigurations } = this - if (_folderConfigurations.has(filepath)) return - if (path.resolve(filepath, '../..') == os.homedir()) return - let model = this.parseContentFromFile(filepath) - this.watchFile(filepath, ConfigurationTarget.Workspace) - this.changeConfiguration(ConfigurationTarget.Workspace, model, filepath) - } - - private watchFile(filepath: string, target: ConfigurationTarget): void { - if (!fs.existsSync(filepath) || global.hasOwnProperty('__TEST__')) return - let disposable = watchFile(filepath, () => { - let model = this.parseContentFromFile(filepath) - this.changeConfiguration(target, model, filepath) - }) - this.disposables.push(disposable) - } - - // create new configuration and fire change event - public changeConfiguration(target: ConfigurationTarget, model: IConfigurationModel, configFile?: string): void { - let { defaults, user, workspace } = this._configuration - let { workspaceConfigFile } = this - let data: IConfigurationData = { - defaults: target == ConfigurationTarget.Global ? model : defaults, - user: target == ConfigurationTarget.User ? model : user, - workspace: target == ConfigurationTarget.Workspace ? model : workspace, - } - let configuration = Configurations.parse(data) - let changed = getChangedKeys(this._configuration.getValue(), configuration.getValue()) - if (target == ConfigurationTarget.Workspace && configFile) { - this._folderConfigurations.set(configFile, new ConfigurationModel(model.contents)) - this.workspaceConfigFile = configFile - } - if (changed.length == 0) return - this._configuration = configuration - this._onChange.fire({ - affectsConfiguration: (section, resource) => { - if (!resource || target != ConfigurationTarget.Workspace) return changed.includes(section) - let u = URI.parse(resource) - if (u.scheme !== 'file') return changed.includes(section) - let filepath = u.fsPath - let preRoot = workspaceConfigFile ? path.resolve(workspaceConfigFile, '../..') : '' - if (configFile && !isParentFolder(preRoot, filepath, true) && !isParentFolder(path.resolve(configFile, '../..'), filepath)) { - return false - } - return changed.includes(section) - } - }) - } - - public setFolderConfiguration(uri: string): void { - let u = URI.parse(uri) - if (u.scheme != 'file') return - let filepath = u.fsPath - for (let [configFile, model] of this.foldConfigurations) { - let root = path.resolve(configFile, '../..') - if (isParentFolder(root, filepath, true) && this.workspaceConfigFile != configFile) { - this.changeConfiguration(ConfigurationTarget.Workspace, model, configFile) - break - } - } - } - - public hasFolderConfiguration(filepath: string): boolean { - let { folders } = this - return folders.findIndex(f => isParentFolder(f, filepath, true)) !== -1 - } - - public getConfigFile(target: ConfigurationTarget): string { - if (target == ConfigurationTarget.Global) return null - if (target == ConfigurationTarget.User) return this.userConfigFile - return this.workspaceConfigFile - } - - private get folders(): string[] { - let res: string[] = [] - let { _folderConfigurations } = this - for (let folder of _folderConfigurations.keys()) { - res.push(path.resolve(folder, '../..')) - } - return res - } - - public get configuration(): Configuration { - return this._configuration - } - - /** - * getConfiguration - * - * @public - * @param {string} section - * @returns {WorkspaceConfiguration} - */ - public getConfiguration(section?: string, resource?: string): WorkspaceConfiguration { - let configuration: Configuration - if (resource) { - let { defaults, user } = this._configuration - configuration = new Configuration(defaults, user, this.getFolderConfiguration(resource)) - } else { - configuration = this._configuration - } - const config = Object.freeze(lookUp(configuration.getValue(null), section)) - - const result: WorkspaceConfiguration = { - has(key: string): boolean { - return typeof lookUp(config, key) !== 'undefined' - }, - get: (key: string, defaultValue?: T) => { - let result: T = lookUp(config, key) - if (result == null) return defaultValue - return result - }, - update: (key: string, value: any, isUser = false) => { - let s = section ? `${section}.${key}` : key - let target = isUser ? ConfigurationTarget.User : ConfigurationTarget.Workspace - let model = target == ConfigurationTarget.User ? this.user.clone() : this.workspace.clone() - if (value == undefined) { - model.removeValue(s) - } else { - model.setValue(s, value) - } - if (target == ConfigurationTarget.Workspace && !this.workspaceConfigFile && this._proxy) { - let file = this.workspaceConfigFile = this._proxy.workspaceConfigFile - if (!fs.existsSync(file)) { - let folder = path.dirname(file) - if (!fs.existsSync(folder)) fs.mkdirSync(folder) - fs.writeFileSync(file, '{}', { encoding: 'utf8' }) - } - } - this.changeConfiguration(target, model, target == ConfigurationTarget.Workspace ? this.workspaceConfigFile : this.userConfigFile) - if (this._proxy && !global.hasOwnProperty('__TEST__')) { - if (value == undefined) { - this._proxy.$removeConfigurationOption(target, s) - } else { - this._proxy.$updateConfigurationOption(target, s, value) - } - } - }, - inspect: (key: string): ConfigurationInspect => { - key = section ? `${section}.${key}` : key - const config = this._configuration.inspect(key) - if (config) { - return { - key, - defaultValue: config.default, - globalValue: config.user, - workspaceValue: config.workspace, - } - } - return undefined - } - } - Object.defineProperty(result, 'has', { - enumerable: false - }) - Object.defineProperty(result, 'get', { - enumerable: false - }) - Object.defineProperty(result, 'update', { - enumerable: false - }) - Object.defineProperty(result, 'inspect', { - enumerable: false - }) - - if (typeof config === 'object') { - mixin(result, config, false) - } - return deepFreeze(result) - } - - private getFolderConfiguration(uri: string): ConfigurationModel { - let u = URI.parse(uri) - if (u.scheme != 'file') return new ConfigurationModel() - let filepath = u.fsPath - for (let [configFile, model] of this.foldConfigurations) { - let root = path.resolve(configFile, '../..') - if (isParentFolder(root, filepath, true)) return model - } - return new ConfigurationModel() - } - - public checkFolderConfiguration(uri: string): void { - let u = URI.parse(uri) - if (u.scheme != 'file') return - let rootPath = path.dirname(u.fsPath) - if (!this.hasFolderConfiguration(rootPath)) { - let folder = findUp('.vim', rootPath) - if (folder && folder != os.homedir()) { - let file = path.join(folder, CONFIG_FILE_NAME) - if (fs.existsSync(file)) { - this.addFolderFile(file) - } - } - } else { - this.setFolderConfiguration(uri) - } - } - - private static parse(data: IConfigurationData): Configuration { - const defaultConfiguration = new ConfigurationModel(data.defaults.contents) - const userConfiguration = new ConfigurationModel(data.user.contents) - const workspaceConfiguration = new ConfigurationModel(data.workspace.contents) - return new Configuration(defaultConfiguration, userConfiguration, workspaceConfiguration, new ConfigurationModel()) - } - - public dispose(): void { - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/configuration/model.ts b/vim-config/plugins/coc.nvim/src/configuration/model.ts deleted file mode 100644 index da5f17e6..00000000 --- a/vim-config/plugins/coc.nvim/src/configuration/model.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { IConfigurationModel } from '../types' -import { objectLiteral } from '../util/is' -import { deepClone } from '../util/object' -import { addToValueTree, getConfigurationValue, removeFromValueTree } from './util' - -export class ConfigurationModel implements IConfigurationModel { - - constructor(private _contents: any = {}) { } - - public get contents(): any { - return this._contents - } - - public clone(): ConfigurationModel { - return new ConfigurationModel(deepClone(this._contents)) - } - - public getValue(section: string): V { - let res = section - ? getConfigurationValue(this.contents, section) - : this.contents - return res - } - - public merge(...others: ConfigurationModel[]): ConfigurationModel { - const contents = deepClone(this.contents) - - for (const other of others) { - this.mergeContents(contents, other.contents) - } - return new ConfigurationModel(contents) - } - - public freeze(): ConfigurationModel { - if (!Object.isFrozen(this._contents)) { - Object.freeze(this._contents) - } - return this - } - - private mergeContents(source: any, target: any): void { - for (const key of Object.keys(target)) { - if (key in source) { - if (objectLiteral(source[key]) && objectLiteral(target[key])) { - this.mergeContents(source[key], target[key]) - continue - } - } - source[key] = deepClone(target[key]) - } - } - - // Update methods - - public setValue(key: string, value: any): void { - addToValueTree(this.contents, key, value, message => { - console.error(message) - }) - } - - public removeValue(key: string): void { - removeFromValueTree(this.contents, key) - } -} diff --git a/vim-config/plugins/coc.nvim/src/configuration/shape.ts b/vim-config/plugins/coc.nvim/src/configuration/shape.ts deleted file mode 100644 index e8a408ce..00000000 --- a/vim-config/plugins/coc.nvim/src/configuration/shape.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import fs from 'fs' -import { applyEdits, modify } from 'jsonc-parser' -import path from 'path' -import { FormattingOptions } from 'vscode-languageserver-types' -import { URI } from 'vscode-uri' -import { ConfigurationShape, ConfigurationTarget, IWorkspace } from '../types' -import { CONFIG_FILE_NAME } from '../util' -const logger = require('../util/logger')('configuration-shape') - -export default class ConfigurationProxy implements ConfigurationShape { - - constructor(private workspace: IWorkspace) { - } - - private get nvim(): Neovim { - return this.workspace.nvim - } - - private async modifyConfiguration(target: ConfigurationTarget, key: string, value?: any): Promise { - let { nvim, workspace } = this - let file = workspace.getConfigFile(target) - if (!file) return - let formattingOptions: FormattingOptions = { tabSize: 2, insertSpaces: true } - let content = fs.readFileSync(file, 'utf8') - value = value == null ? undefined : value - let edits = modify(content, [key], value, { formattingOptions }) - content = applyEdits(content, edits) - fs.writeFileSync(file, content, 'utf8') - let doc = workspace.getDocument(URI.file(file).toString()) - if (doc) nvim.command('checktime', true) - return - } - - public get workspaceConfigFile(): string { - let folder = path.join(this.workspace.root, '.vim') - return path.join(folder, CONFIG_FILE_NAME) - } - - public $updateConfigurationOption(target: ConfigurationTarget, key: string, value: any): void { - this.modifyConfiguration(target, key, value).logError() - } - - public $removeConfigurationOption(target: ConfigurationTarget, key: string): void { - this.modifyConfiguration(target, key).logError() - } -} diff --git a/vim-config/plugins/coc.nvim/src/configuration/util.ts b/vim-config/plugins/coc.nvim/src/configuration/util.ts deleted file mode 100644 index 463b1dd6..00000000 --- a/vim-config/plugins/coc.nvim/src/configuration/util.ts +++ /dev/null @@ -1,271 +0,0 @@ -import { Location, Range } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { parse, ParseError } from 'jsonc-parser' -import { IConfigurationModel, ErrorItem } from '../types' -import { emptyObject, objectLiteral } from '../util/is' -import { equals } from '../util/object' -import fs from 'fs' -import { URI } from 'vscode-uri' -import path, { dirname, resolve } from 'path' -const logger = require('../util/logger')('configuration-util') -declare const ESBUILD - -const pluginRoot = typeof ESBUILD === 'undefined' ? resolve(__dirname, '../..') : dirname(__dirname) - -export type ShowError = (errors: ErrorItem[]) => void - -export function parseContentFromFile(filepath: string | null, onError?: ShowError): IConfigurationModel { - if (!filepath || !fs.existsSync(filepath)) return { contents: {} } - let content: string - let uri = URI.file(filepath).toString() - try { - content = fs.readFileSync(filepath, 'utf8') - } catch (_e) { - content = '' - } - let [errors, contents] = parseConfiguration(content) - if (errors && errors.length) { - onError(convertErrors(uri, content, errors)) - } - return { contents } -} - -export function parseConfiguration(content: string): [ParseError[], any] { - if (content.length == 0) return [[], {}] - let errors: ParseError[] = [] - let data = parse(content, errors, { allowTrailingComma: true }) - function addProperty(current: object, key: string, remains: string[], value: any): void { - if (remains.length == 0) { - current[key] = convert(value) - } else { - if (!current[key]) current[key] = {} - let o = current[key] - let first = remains.shift() - addProperty(o, first, remains, value) - } - } - - function convert(obj: any, split = false): any { - if (!objectLiteral(obj)) return obj - if (emptyObject(obj)) return {} - let dest = {} - for (let key of Object.keys(obj)) { - if (split && key.includes('.')) { - let parts = key.split('.') - let first = parts.shift() - addProperty(dest, first, parts, obj[key]) - } else { - dest[key] = convert(obj[key]) - } - } - return dest - } - return [errors, convert(data, true)] -} - -export function convertErrors(uri: string, content: string, errors: ParseError[]): ErrorItem[] { - let items: ErrorItem[] = [] - let document = TextDocument.create(uri, 'json', 0, content) - for (let err of errors) { - let msg = 'parse error' - switch (err.error) { - case 2: - msg = 'invalid number' - break - case 8: - msg = 'close brace expected' - break - case 5: - msg = 'colon expected' - break - case 6: - msg = 'comma expected' - break - case 9: - msg = 'end of file expected' - break - case 16: - msg = 'invaliad character' - break - case 10: - msg = 'invalid commment token' - break - case 15: - msg = 'invalid escape character' - break - case 1: - msg = 'invalid symbol' - break - case 14: - msg = 'invalid unicode' - break - case 3: - msg = 'property name expected' - break - case 13: - msg = 'unexpected end of number' - break - case 12: - msg = 'unexpected end of string' - break - case 11: - msg = 'unexpected end of comment' - break - case 4: - msg = 'value expected' - break - default: - msg = 'Unknwn error' - break - } - let range: Range = { - start: document.positionAt(err.offset), - end: document.positionAt(err.offset + err.length), - } - let loc = Location.create(uri, range) - items.push({ location: loc, message: msg }) - } - return items -} - -export function addToValueTree( - settingsTreeRoot: any, - key: string, - value: any, - conflictReporter: (message: string) => void -): void { - const segments = key.split('.') - const last = segments.pop() - - let curr = settingsTreeRoot - for (let i = 0; i < segments.length; i++) { - let s = segments[i] - let obj = curr[s] - switch (typeof obj) { - case 'function': { - obj = curr[s] = {} - break - } - case 'undefined': { - obj = curr[s] = {} - break - } - case 'object': - break - default: - conflictReporter( - `Ignoring ${key} as ${segments - .slice(0, i + 1) - .join('.')} is ${JSON.stringify(obj)}` - ) - return - } - curr = obj - } - - if (typeof curr === 'object') { - curr[last] = value // workaround https://github.com/Microsoft/vscode/issues/13606 - } else { - conflictReporter( - `Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}` - ) - } -} - -export function removeFromValueTree(valueTree: any, key: string): void { - const segments = key.split('.') - doRemoveFromValueTree(valueTree, segments) -} - -function doRemoveFromValueTree(valueTree: any, segments: string[]): void { - const first = segments.shift() - if (segments.length === 0) { - // Reached last segment - delete valueTree[first] - return - } - - if (Object.keys(valueTree).includes(first)) { - const value = valueTree[first] - if (typeof value === 'object' && !Array.isArray(value)) { - doRemoveFromValueTree(value, segments) - if (Object.keys(value).length === 0) { - delete valueTree[first] - } - } - } -} - -export function getConfigurationValue( - config: any, - settingPath: string, - defaultValue?: T -): T { - function accessSetting(config: any, path: string[]): any { - let current = config - for (let i = 0; i < path.length; i++) { - if (typeof current !== 'object' || current === null) { - return undefined - } - current = current[path[i]] - } - return current as T - } - - const path = settingPath.split('.') - const result = accessSetting(config, path) - - return typeof result === 'undefined' ? defaultValue : result -} - -export function loadDefaultConfigurations(): IConfigurationModel { - let file = path.join(pluginRoot, 'data/schema.json') - if (!fs.existsSync(file)) { - console.error('schema.json not found, reinstall coc.nvim to fix this!') - return { contents: {} } - } - let content = fs.readFileSync(file, 'utf8') - let { properties } = JSON.parse(content) - let config = {} - Object.keys(properties).forEach(key => { - let value = properties[key].default - if (value !== undefined) { - addToValueTree(config, key, value, message => { - logger.error(message) - }) - } - }) - return { contents: config } -} - -export function getKeys(obj: { [key: string]: any }, curr?: string): string[] { - let keys: string[] = [] - for (let key of Object.keys(obj)) { - let val = obj[key] - let newKey = curr ? `${curr}.${key}` : key - keys.push(newKey) - if (objectLiteral(val)) { - keys.push(...getKeys(val, newKey)) - } - } - return keys -} - -export function getChangedKeys(from: { [key: string]: any }, to: { [key: string]: any }): string[] { - let keys: string[] = [] - let fromKeys = getKeys(from) - let toKeys = getKeys(to) - const added = toKeys.filter(key => !fromKeys.includes(key)) - const removed = fromKeys.filter(key => !toKeys.includes(key)) - keys.push(...added) - keys.push(...removed) - for (const key of fromKeys) { - if (!toKeys.includes(key)) continue - const value1 = getConfigurationValue(from, key) - const value2 = getConfigurationValue(to, key) - if (!equals(value1, value2)) { - keys.push(key) - } - } - return keys -} diff --git a/vim-config/plugins/coc.nvim/src/cursors/index.ts b/vim-config/plugins/coc.nvim/src/cursors/index.ts deleted file mode 100644 index adbffbaa..00000000 --- a/vim-config/plugins/coc.nvim/src/cursors/index.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-jsonrpc' -import { Range } from 'vscode-languageserver-types' -import events from '../events' -import Document from '../model/document' -import { comparePosition } from '../util/position' -import window from '../window' -import workspace from '../workspace' -import CursorSession from './session' -import { getVisualRanges, splitRange } from './util' -const logger = require('../util/logger')('cursors') - -interface Config { - cancelKey: string - previousKey: string - nextKey: string -} - -export default class Cursors { - private sessionsMap: Map = new Map() - private disposables: Disposable[] = [] - private config: Config - constructor(private nvim: Neovim) { - this.loadConfig() - workspace.onDidChangeConfiguration(e => { - if (e.affectsConfiguration('cursors')) { - this.loadConfig() - } - }, null, this.disposables) - events.on('BufUnload', bufnr => { - let session = this.getSession(bufnr) - if (!session) return - session.dispose() - this.sessionsMap.delete(bufnr) - }, null, this.disposables) - } - - private loadConfig(): void { - let config = workspace.getConfiguration('cursors') - this.config = { - nextKey: config.get('nextKey', ''), - previousKey: config.get('previousKey', ''), - cancelKey: config.get('cancelKey', '') - } - } - - public getSession(bufnr: number): CursorSession | undefined { - return this.sessionsMap.get(bufnr) - } - - public async isActivated(): Promise { - let bufnr = await this.nvim.call('bufnr', ['%']) as number - return this.sessionsMap.get(bufnr) != null - } - - public async select(bufnr: number, kind: string, mode: string): Promise { - let doc = workspace.getDocument(bufnr) - if (!doc || !doc.attached) { - window.showMessage(`buffer ${bufnr} not attached.`) - return - } - let { nvim } = this - let session = this.createSession(doc) - let pos = await window.getCursorPosition() - let range: Range - if (kind == 'operator') { - await nvim.command(`normal! ${mode == 'line' ? `'[` : '`['}`) - let start = await window.getCursorPosition() - await nvim.command(`normal! ${mode == 'line' ? `']` : '`]'}`) - let end = await window.getCursorPosition() - await window.moveTo(pos) - let relative = comparePosition(start, end) - // do nothing for empty range - if (relative == 0) return - if (relative >= 0) [start, end] = [end, start] - // include end character - let line = doc.getline(end.line) - if (end.character < line.length) { - end.character = end.character + 1 - } - let ranges = splitRange(doc, Range.create(start, end)) - for (let r of ranges) { - let text = doc.textDocument.getText(r) - session.addRange(r, text) - } - } else if (kind == 'word') { - range = doc.getWordRangeAtPosition(pos) - if (!range) { - let line = doc.getline(pos.line) - if (pos.character == line.length) { - range = Range.create(pos.line, Math.max(0, line.length - 1), pos.line, line.length) - } else { - range = Range.create(pos.line, pos.character, pos.line, pos.character + 1) - } - } - let line = doc.getline(pos.line) - let text = line.slice(range.start.character, range.end.character) - session.addRange(range, text) - } else if (kind == 'position') { - // make sure range contains character for highlight - let line = doc.getline(pos.line) - if (pos.character >= line.length) { - range = Range.create(pos.line, line.length - 1, pos.line, line.length) - } else { - range = Range.create(pos.line, pos.character, pos.line, pos.character + 1) - } - session.addRange(range, line.slice(range.start.character, range.end.character)) - } else if (kind == 'range') { - await nvim.call('eval', 'feedkeys("\\", "in")') - let range = await workspace.getSelectedRange(mode, doc) - if (!range || comparePosition(range.start, range.end) == 0) return - let ranges = mode == '\x16' ? getVisualRanges(doc, range) : splitRange(doc, range) - for (let r of ranges) { - let text = doc.textDocument.getText(r) - session.addRange(r, text) - } - } else { - window.showMessage(`${kind} not supported`, 'error') - return - } - if (kind == 'word' || kind == 'position') { - await nvim.command(`silent! call repeat#set("\\(coc-cursors-${kind})", -1)`) - } - } - - private createSession(doc: Document): CursorSession { - let session = this.getSession(doc.bufnr) - if (session) return session - session = new CursorSession(this.nvim, doc, this.config) - this.sessionsMap.set(doc.bufnr, session) - session.onDidCancel(() => { - session.dispose() - this.sessionsMap.delete(doc.bufnr) - }) - return session - } - - // Add ranges to current document - public async addRanges(ranges: Range[]): Promise { - let { nvim } = this - let bufnr = await nvim.call('bufnr', ['%']) as number - let doc = workspace.getDocument(bufnr) - if (!doc || !doc.attached) { - window.showMessage('Document not attached', 'error') - return false - } - let session = this.createSession(doc) - return session.addRanges(ranges) - } - - public reset(): void { - for (let session of this.sessionsMap.values()) { - session.cancel() - } - this.sessionsMap.clear() - } - - public dispose(): void { - for (let session of this.sessionsMap.values()) { - session.dispose() - } - this.sessionsMap.clear() - for (let disposable of this.disposables) { - disposable.dispose() - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/cursors/range.ts b/vim-config/plugins/coc.nvim/src/cursors/range.ts deleted file mode 100644 index 8e732007..00000000 --- a/vim-config/plugins/coc.nvim/src/cursors/range.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { Position, Range, TextEdit } from 'vscode-languageserver-types' -import { comparePosition } from '../util/position' -const logger = require('../util/logger')('cursors-range') - -// edit range -export default class TextRange { - private currStart: number - private currEnd: number - - constructor(public line: number, - public start: number, - public end: number, - public text: string, - // range count at this line before, shuld be updated on range add - public preCount: number) { - this.currStart = start - this.currEnd = end - } - - public add(offset: number, add: string): void { - let { text, preCount } = this - let pre = offset == 0 ? '' : text.slice(0, offset) - let post = text.slice(offset) - this.text = `${pre}${add}${post}` - this.currStart = this.currStart + preCount * add.length - this.currEnd = this.currEnd + (preCount + 1) * add.length - } - - public replace(begin: number, end: number, add = ''): void { - let { text, preCount } = this - let pre = begin == 0 ? '' : text.slice(0, begin) - let post = text.slice(end) - this.text = pre + add + post - let l = end - begin - add.length - this.currStart = this.currStart - preCount * l - this.currEnd = this.currEnd - (preCount + 1) * l - } - - public get range(): Range { - return Range.create(this.line, this.start, this.line, this.end) - } - - public get currRange(): Range { - return Range.create(this.line, this.currStart, this.line, this.currEnd) - } - - public applyEdit(edit: TextEdit): void { - let { range, newText } = edit - let start = range.start.character - let end = range.end.character - let isAdd = start == end - if (isAdd) { - this.add(start - this.currStart, newText) - } else { - this.replace(start - this.currStart, end - this.currStart, newText) - } - } - - /** - * Adjust from textEdit that not overlap - */ - public adjustFromEdit(edit: TextEdit): void { - let { range, newText } = edit - // no change if edit after current range - if (comparePosition(range.start, Position.create(this.line, this.currEnd)) > 0) { - return - } - let newLines = newText.split('\n') - let changeCount = newLines.length - (range.end.line - range.start.line + 1) - this.line = this.line + changeCount - if (range.end.line == this.line) { - let remove = range.start.line == range.end.line ? range.end.character - range.start.character : range.end.character - if (newLines.length > 1 && range.start.line == range.end.line) { - remove = remove + range.start.character - } - let add = 0 - if (newLines.length > 1) { - add = newLines[newLines.length - 1].length - } else { - if (range.start.line == range.end.line) { - add = newText.length - } else { - add = range.start.character + newText.length - } - } - let delta = add - remove - for (let key of ['start', 'end', 'currStart', 'currEnd']) { - this[key] += delta - } - } - } - - public sync(): void { - this.start = this.currStart - this.end = this.currEnd - } - - public get textEdit(): TextEdit { - return { - range: this.range, - newText: this.text - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/cursors/session.ts b/vim-config/plugins/coc.nvim/src/cursors/session.ts deleted file mode 100644 index 00ca3e3f..00000000 --- a/vim-config/plugins/coc.nvim/src/cursors/session.ts +++ /dev/null @@ -1,444 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import fastDiff from 'fast-diff' -import { Disposable, Emitter, Event, Range, TextEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import events from '../events' -import Document from '../model/document' -import { DidChangeTextDocumentParams } from '../types' -import { comparePosition, emptyRange, positionInRange, rangeInRange, rangeIntersect, rangeOverlap } from '../util/position' -import window from '../window' -import workspace from '../workspace' -import TextRange from './range' -import { adjustPosition, equalEdit } from './util' -const logger = require('../util/logger')('cursors-session') - -export interface Config { - cancelKey: string - previousKey: string - nextKey: string -} - -/** - * Cursor session for single buffer - */ -export default class CursorSession { - private readonly _onDidCancel = new Emitter() - public readonly onDidCancel: Event = this._onDidCancel.event - private disposables: Disposable[] = [] - private ranges: TextRange[] = [] - private activated = true - private changing = false - private changed = false - private textDocument: TextDocument - constructor( - private nvim: Neovim, - private doc: Document, - private config: Config) { - this.textDocument = this.doc.textDocument - this.buffer.setVar('coc_cursors_activated', 1, true) - let { cancelKey, nextKey, previousKey } = this.config - this.disposables.push(workspace.registerLocalKeymap('n', cancelKey, () => { - this.cancel() - }, true)) - this.disposables.push(workspace.registerLocalKeymap('n', nextKey, async () => { - if (!this.activated) return - let ranges = this.ranges.map(o => o.currRange) - let curr = await window.getCursorPosition() - for (let r of ranges) { - if (comparePosition(r.start, curr) > 0) { - await window.moveTo(r.start) - return - } - } - if (ranges.length) await window.moveTo(ranges[0].start) - }, true)) - this.disposables.push(workspace.registerLocalKeymap('n', previousKey, async () => { - if (!this.activated) return - let ranges = this.ranges.map(o => o.currRange) - ranges.reverse() - let curr = await window.getCursorPosition() - for (let r of ranges) { - if (comparePosition(r.end, curr) < 0) { - await window.moveTo(r.start) - return - } - } - if (ranges.length) await window.moveTo(ranges[ranges.length - 1].start) - }, true)) - this.doc.onDocumentChange(this.onChange, this, this.disposables) - } - - private async onChange(e: DidChangeTextDocumentParams): Promise { - if (!this.activated || this.ranges.length == 0) return - if (this.changing) return - let change = e.contentChanges[0] - let { text, range } = change - let intersect = this.ranges.some(r => rangeIntersect(range, r.currRange)) - let begin = this.ranges[0].currRange.start - if (text.endsWith('\n') && comparePosition(begin, range.end) == 0) { - // prepend lines - intersect = false - } - if (!intersect) { - this.ranges.forEach(r => { - r.adjustFromEdit({ range, newText: text }) - }) - this.doHighlights() - this.textDocument = this.doc.textDocument - return - } - this.changed = true - // get range from edit - let textRange = this.getTextRange(range, text) - if (textRange) { - await this.applySingleEdit(textRange, { range, newText: text }) - } else { - this.applyComposedEdit(e.original, { range, newText: text }) - if (this.activated) { - this.ranges.forEach(r => { - r.sync() - }) - this.textDocument = this.doc.textDocument - } - } - } - - private doHighlights(): void { - let { nvim, buffer, ranges } = this - buffer.clearNamespace('cursors') - let arr = ranges.map(o => o.currRange) - buffer.highlightRanges('cursors', 'CocCursorRange', arr) - nvim.command('redraw', true) - } - - public addRanges(ranges: Range[]): boolean { - let { nvim, doc } = this - if (this.changed) { - window.showMessage(`Can't add ranges after range change.`) - return false - } - // filter overlap ranges - this.ranges = this.ranges.filter(r => { - let { currRange } = r - return !ranges.some(range => rangeOverlap(range, currRange)) - }) - let { textDocument } = doc - for (let range of ranges) { - let { line } = range.start - let textRange = new TextRange(line, range.start.character, range.end.character, textDocument.getText(range), 0) - this.ranges.push(textRange) - } - this.ranges.sort((a, b) => comparePosition(a.range.start, b.range.start)) - // fix preCount - let preCount = 0 - let currline = -1 - for (let range of this.ranges) { - let { line } = range - if (line != currline) { - preCount = 0 - } - range.preCount = preCount - preCount = preCount + 1 - currline = line - } - nvim.pauseNotification() - this.doHighlights() - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - return true - } - - /** - * Cancel session and highlights - */ - public cancel(): void { - if (!this.activated) return - let { nvim } = this - this.activated = false - let { cancelKey, nextKey, previousKey } = this.config - nvim.pauseNotification() - this.buffer.clearNamespace('cursors') - this.buffer.setVar('coc_cursors_activated', 0, true) - nvim.command('redraw', true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - this._onDidCancel.fire() - } - - /** - * Called on buffer unload or cancel - */ - public dispose(): void { - if (!this.doc) return - this._onDidCancel.dispose() - for (let disposable of this.disposables) { - disposable.dispose() - } - this.ranges = [] - this.doc = null - this.textDocument = null - } - - private get buffer(): Buffer { - return this.nvim.createBuffer(this.doc.bufnr) - } - - /** - * Find changed range from edit - */ - private getTextRange(range: Range, text: string): TextRange | null { - let { ranges } = this - if (text.indexOf('\n') !== -1 || range.start.line != range.end.line) { - return null - } - ranges.sort((a, b) => { - if (a.line != b.line) return a.line - b.line - return a.currRange.start.character - b.currRange.start.character - }) - for (let i = 0; i < ranges.length; i++) { - let r = ranges[i] - if (rangeInRange(range, r.currRange)) { - return r - } - if (r.line != range.start.line) { - continue - } - if (text.length && range.start.character == r.currRange.end.character) { - // end add - let next = ranges[i + 1] - if (!next) return r - return positionInRange(next.currRange.start, range) ? null : r - } - } - return null - } - - /** - * Adjust change for current ranges - */ - private adjustRanges(textRange: TextRange, range: Range, text: string): void { - let { ranges } = this - if (range.start.character == range.end.character) { - // add - let isEnd = textRange.currRange.end.character == range.start.character - if (isEnd) { - ranges.forEach(r => { - r.add(r.text.length, text) - }) - } else { - let d = range.start.character - textRange.currRange.start.character - ranges.forEach(r => { - r.add(Math.min(r.text.length, d), text) - }) - } - } else { - // replace - let d = range.end.character - range.start.character - let isEnd = textRange.currRange.end.character == range.end.character - if (isEnd) { - if (textRange.currRange.start.character == range.start.character) { - // changed both start and end - if (text.includes(textRange.text)) { - let idx = text.indexOf(textRange.text) - let pre = idx == 0 ? '' : text.slice(0, idx) - let post = text.slice(idx + textRange.text.length) - if (pre) ranges.forEach(r => r.add(0, pre)) - if (post) ranges.forEach(r => r.add(r.text.length, post)) - } else if (textRange.text.includes(text)) { - // delete - let idx = textRange.text.indexOf(text) - let offset = textRange.text.length - (idx + text.length) - if (idx != 0) ranges.forEach(r => r.replace(0, idx)) - if (offset > 0) ranges.forEach(r => r.replace(r.text.length - offset, r.text.length)) - } else { - this.cancel() - } - } else { - ranges.forEach(r => { - let l = r.text.length - r.replace(Math.max(0, l - d), l, text) - }) - } - } else { - let start = range.start.character - textRange.currRange.start.character - ranges.forEach(r => { - let l = r.text.length - r.replace(start, Math.min(start + d, l), text) - }) - } - } - } - - public addRange(range: Range, text: string): void { - if (this.changed) { - window.showMessage(`Can't add range after range change.`) - return - } - let { ranges } = this - let idx = ranges.findIndex(o => rangeIntersect(o.range, range)) - // remove range when intersect - if (idx !== -1) { - ranges.splice(idx, 1) - // adjust preCount after - for (let r of ranges) { - if (r.line == range.start.line && r.start > range.start.character) { - r.preCount = r.preCount - 1 - } - } - } else { - let preCount = 0 - let idx = 0 - let { line } = range.start - // idx & preCount - for (let r of ranges) { - if (r.line > line || (r.line == line && r.start > range.end.character)) { - break - } - if (r.line == line) preCount++ - idx++ - } - let created = new TextRange(line, range.start.character, range.end.character, text, preCount) - ranges.splice(idx, 0, created) - // adjust preCount after - for (let r of ranges) { - if (r.line == range.start.line && r.start > range.start.character) { - r.preCount = r.preCount + 1 - } - } - } - if (this.ranges.length == 0) { - this.cancel() - } else { - this.doHighlights() - } - } - - private async applySingleEdit(textRange: TextRange, edit: TextEdit): Promise { - // single range change, calculate & apply changes for all ranges - let { range, newText } = edit - let { doc } = this - this.adjustRanges(textRange, range, newText) - if (this.ranges.length == 1) { - this.doHighlights() - return - } - let edits = this.ranges.map(o => o.textEdit) - let content = TextDocument.applyEdits(this.textDocument, edits) - let newLines = content.split('\n') - let changedLnum: Set = new Set() - let arr: [number, string][] = [] - for (let r of this.ranges) { - if (!changedLnum.has(r.line)) { - changedLnum.add(r.line) - arr.push([r.line, newLines[r.line]]) - } - } - let { nvim } = this - this.changing = true - await doc.changeLines(arr) - this.changing = false - if (this.activated) { - this.ranges.forEach(r => { - r.sync() - }) - this.textDocument = this.doc.textDocument - } - // apply changes - nvim.pauseNotification() - let { cursor } = events - if (textRange.preCount > 0 && cursor.bufnr == doc.bufnr && textRange.line + 1 == cursor.lnum) { - let changed = textRange.preCount * (newText.length - (range.end.character - range.start.character)) - nvim.call('cursor', [cursor.lnum, cursor.col + changed], true) - } - this.doHighlights() - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } - - private applyComposedEdit(original: string, edit: TextEdit): void { - // check complex edit - let { range, newText } = edit - let { ranges } = this - let doc = TextDocument.create('file:///1', '', 0, original) - let edits: TextEdit[] = [] - let diffs = fastDiff(original, newText) - let offset = 0 - for (let i = 0; i < diffs.length; i++) { - let diff = diffs[i] - let pos = adjustPosition(range.start, doc.positionAt(offset)) - if (diff[0] == fastDiff.EQUAL) { - offset = offset + diff[1].length - } else if (diff[0] == fastDiff.DELETE) { - let end = adjustPosition(range.start, doc.positionAt(offset + diff[1].length)) - if (diffs[i + 1] && diffs[i + 1][0] == fastDiff.INSERT) { - // change - edits.push({ range: Range.create(pos, end), newText: diffs[i + 1][1] }) - i = i + 1 - } else { - // delete - edits.push({ range: Range.create(pos, end), newText: '' }) - } - offset = offset + diff[1].length - } else if (diff[0] == fastDiff.INSERT) { - edits.push({ range: Range.create(pos, pos), newText: diff[1] }) - } - } - if (edits.some(edit => edit.newText.includes('\n') || edit.range.start.line != edit.range.end.line)) { - this.cancel() - return - } - if (edits.length == ranges.length) { - let last: TextEdit - for (let i = 0; i < edits.length; i++) { - let edit = edits[i] - let textRange = this.ranges[i] - if (!rangeIntersect(textRange.currRange, edit.range)) { - this.cancel() - return - } - if (last && !equalEdit(edit, last)) { - this.cancel() - return - } - textRange.applyEdit(edit) - last = edit - } - } else if (edits.length == ranges.length * 2) { - for (let i = 0; i < edits.length - 1; i = i + 2) { - let edit = edits[i] - let next = edits[i + 1] - if (edit.newText.length == 0 && next.newText.length == 0) { - // remove begin & end - let textRange = this.ranges[i / 2] - if (comparePosition(textRange.currRange.end, next.range.end) != 0) { - this.cancel() - return - } - let start = edit.range.start.character - textRange.currRange.start.character - textRange.replace(start, edit.range.end.character - edit.range.start.character, '') - let offset = next.range.end.character - next.range.start.character - let len = textRange.text.length - textRange.replace(len - offset, len) - } else if (emptyRange(edit.range) && emptyRange(next.range)) { - // add begin & end - let textRange = this.ranges[i / 2] - if (comparePosition(textRange.currRange.end, next.range.start) != 0) { - this.cancel() - return - } - let start = edit.range.start.character - textRange.currRange.start.character - textRange.add(start, edit.newText) - let len = textRange.text.length - textRange.add(len, next.newText) - } else { - this.cancel() - return - } - } - } else { - this.cancel() - return - } - this.doHighlights() - } -} diff --git a/vim-config/plugins/coc.nvim/src/cursors/util.ts b/vim-config/plugins/coc.nvim/src/cursors/util.ts deleted file mode 100644 index 0ad3839b..00000000 --- a/vim-config/plugins/coc.nvim/src/cursors/util.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Range, Position, TextEdit } from 'vscode-languageserver-protocol' -import Document from '../model/document' - -/** - * Split to single line ranges - */ -export function splitRange(doc: Document, range: Range): Range[] { - let splited: Range[] = [] - for (let i = range.start.line; i <= range.end.line; i++) { - let curr = doc.getline(i) || '' - let sc = i == range.start.line ? range.start.character : 0 - let ec = i == range.end.line ? range.end.character : curr.length - if (sc == ec) continue - splited.push(Range.create(i, sc, i, ec)) - } - return splited -} - -/** - * Get ranges of visual block - */ -export function getVisualRanges(doc: Document, range: Range): Range[] { - let { start, end } = range - if (start.line > end.line) { - [start, end] = [end, start] - } - let sc = start.character < end.character ? start.character : end.character - let ec = start.character < end.character ? end.character : start.character - let ranges: Range[] = [] - for (let i = start.line; i <= end.line; i++) { - let line = doc.getline(i) - ranges.push(Range.create(i, sc, i, Math.min(line.length, ec))) - } - return ranges -} - -export function adjustPosition(position: Position, delta: Position): Position { - let { line, character } = delta - return Position.create(position.line + line, line == 0 ? position.character + character : character) -} - -export function equalEdit(one: TextEdit, two: TextEdit): boolean { - if (one.newText.length != two.newText.length) return false - let { range } = one - if (range.end.character - range.start.character != two.range.end.character - two.range.start.character) { - return false - } - return true -} diff --git a/vim-config/plugins/coc.nvim/src/diagnostic/buffer.ts b/vim-config/plugins/coc.nvim/src/diagnostic/buffer.ts deleted file mode 100644 index 8290d0bc..00000000 --- a/vim-config/plugins/coc.nvim/src/diagnostic/buffer.ts +++ /dev/null @@ -1,392 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import { Mutex } from '../util/mutex' -import { Diagnostic, DiagnosticSeverity, DiagnosticTag, Position } from 'vscode-languageserver-protocol' -import { BufferSyncItem, FloatConfig, HighlightItem, LocationListItem } from '../types' -import { equals } from '../util/object' -import { comparePosition, lineInRange, positionInRange } from '../util/position' -import workspace from '../workspace' -import events from '../events' -import { getLocationListItem, getNameFromSeverity, getSeverityType } from './util' -const isVim = process.env.VIM_NODE_RPC == '1' -const logger = require('../util/logger')('diagnostic-buffer') -const signGroup = 'CocDiagnostic' -const highlightNamespace = 'diagnostic' -// higher priority first -const hlGroups = ['CocErrorHighlight', 'CocWarningHighlight', 'CocInfoHighlight', 'CocHintHighlight', 'CocDeprecatedHighlight', 'CocUnusedHighlight'] - -export enum DiagnosticHighlight { - Error = 'CocErrorHighlight', - Warning = 'CocWarningHighlight', - Information = 'CocInfoHighlight', - Hint = 'CocHintHighlight', - Deprecated = 'CocDeprecatedHighlight', - Unused = 'CocUnusedHighlight' -} - -export interface DiagnosticConfig { - highlighLimit: number - autoRefresh: boolean - enableSign: boolean - locationlistUpdate: boolean - enableHighlightLineNumber: boolean - checkCurrentLine: boolean - enableMessage: string - displayByAle: boolean - signPriority: number - errorSign: string - warningSign: string - infoSign: string - hintSign: string - level: number - messageTarget: string - messageDelay: number - refreshOnInsertMode: boolean - virtualText: boolean - virtualTextCurrentLineOnly: boolean - virtualTextSrcId: number - virtualTextPrefix: string - virtualTextLines: number - virtualTextLineSeparator: string - filetypeMap: object - showUnused?: boolean - showDeprecated?: boolean - format?: string - floatConfig: FloatConfig -} - -interface DiagnosticInfo { - /** - * current bufnr - */ - bufnr: number - lnum: number - winid: number - locationlist: string -} - -/** - * Manage diagnostics of buffer, including: - * - * - highlights - * - variable - * - signs - * - location list - * - virtual text - */ -export class DiagnosticBuffer implements BufferSyncItem { - private diagnosticsMap: Map> = new Map() - private mutex = new Mutex() - private _disposed = false - constructor( - private readonly nvim: Neovim, - public readonly bufnr: number, - public readonly uri: string, - private config: DiagnosticConfig, - private onRefresh: (diagnostics: ReadonlyArray) => void - ) { - } - - private get displayByAle(): boolean { - return this.config.displayByAle - } - - private clearHighlight(collection: string): void { - this.buffer.clearNamespace(highlightNamespace + collection) - } - - private clearSigns(collection: string): void { - this.buffer.unplaceSign({ group: signGroup + collection }) - } - - private get diagnostics(): Diagnostic[] { - let res: Diagnostic[] = [] - for (let diags of this.diagnosticsMap.values()) { - res.push(...diags) - } - return res - } - - private get buffer(): Buffer { - return this.nvim.createBuffer(this.bufnr) - } - - private refreshAle(collection: string, diagnostics: ReadonlyArray): void { - let aleItems = diagnostics.map(o => { - let range = o.range - return { - text: o.message, - code: o.code, - lnum: range.start.line + 1, - col: range.start.character + 1, - end_lnum: range.end.line + 1, - end_col: range.end.character, - type: getSeverityType(o.severity) - } - }) - let method = global.hasOwnProperty('__TEST__') ? 'MockAleResults' : 'ale#other_source#ShowResults' - this.nvim.call(method, [this.bufnr, 'coc' + collection, aleItems], true) - } - - /** - * Refresh buffer with new diagnostics. - * - * @param {Object} diagnosticsMap - * @param {boolean} force Force highlights update. - */ - public async refresh(diagnosticsMap: { [collection: string]: Diagnostic[] }, force?: boolean): Promise { - let release = await this.mutex.acquire() - try { - await this._refresh(diagnosticsMap, force === true) - release() - } catch (e) { - release() - this.nvim.echoError(e) - } - } - - /** - * Refresh UI with new diagnostics. - */ - private async _refresh(diagnosticsMap: { [collection: string]: Diagnostic[] }, force: boolean): Promise { - let { refreshOnInsertMode } = this.config - let { nvim } = this - let checkInsert = !this.displayByAle && !refreshOnInsertMode - if (events.insertMode && checkInsert) return - let info = await nvim.call('coc#util#diagnostic_info', [this.bufnr, checkInsert]) as DiagnosticInfo | undefined - if (!info || this._disposed) return - if (this.displayByAle) { - nvim.pauseNotification() - for (let [collection, diagnostics] of Object.entries(diagnosticsMap)) { - // no need to save diagnostics - this.diagnosticsMap.set(collection, []) - this.refreshAle(collection, diagnostics) - } - await nvim.resumeNotification() - } else { - let changed = false - let redraw = false - nvim.pauseNotification() - for (let [collection, diagnostics] of Object.entries(diagnosticsMap)) { - let prev = this.diagnosticsMap.get(collection) || [] - this.diagnosticsMap.set(collection, diagnostics) - if (!equals(prev, diagnostics)) { - changed = true - redraw = true - this.addSigns(collection, diagnostics) - this.updateHighlights(collection, diagnostics) - } else if (prev.length && force) { - redraw = true - this.updateHighlights(collection, diagnostics) - } - } - if (changed) { - this.showVirtualText(info.lnum, info.bufnr) - this.updateLocationList(info.winid, info.locationlist) - this.setDiagnosticInfo() - } - if (isVim && redraw) this.nvim.command('redraw', true) - await this.nvim.resumeNotification() - } - this.onRefresh(this.diagnostics) - } - - public updateLocationList(winid: number, title: string): void { - if (!this.config.locationlistUpdate || winid == -1 || title !== 'Diagnostics of coc') return - let items: LocationListItem[] = [] - let { diagnostics } = this - diagnostics.sort(sortDiagnostics) - for (let diagnostic of diagnostics) { - let item = getLocationListItem(this.bufnr, diagnostic) - items.push(item) - } - this.nvim.call('setloclist', [winid, [], 'r', { title: 'Diagnostics of coc', items }], true) - } - - public addSigns(collection: string, diagnostics: ReadonlyArray): void { - if (!this.config.enableSign) return - let group = signGroup + collection - this.buffer.unplaceSign({ group }) - let signsMap: Map = new Map() - for (let diagnostic of diagnostics) { - let { range, severity } = diagnostic - let line = range.start.line - let exists = signsMap.get(line) || [] - if (exists.includes(severity)) { - continue - } - exists.push(severity) - signsMap.set(line, exists) - let priority = this.config.signPriority + 4 - severity - let name = getNameFromSeverity(severity) - this.buffer.placeSign({ name, lnum: line + 1, group, priority }) - } - } - - public setDiagnosticInfo(): void { - let lnums = [0, 0, 0, 0] - let info = { error: 0, warning: 0, information: 0, hint: 0, lnums } - for (let diagnostics of this.diagnosticsMap.values()) { - for (let diagnostic of diagnostics) { - let lnum = diagnostic.range.start.line + 1 - switch (diagnostic.severity) { - case DiagnosticSeverity.Warning: - info.warning = info.warning + 1 - lnums[1] = lnums[1] ? Math.min(lnums[1], lnum) : lnum - break - case DiagnosticSeverity.Information: - info.information = info.information + 1 - lnums[2] = lnums[2] ? Math.min(lnums[2], lnum) : lnum - break - case DiagnosticSeverity.Hint: - info.hint = info.hint + 1 - lnums[3] = lnums[3] ? Math.min(lnums[3], lnum) : lnum - break - default: - lnums[0] = lnums[0] ? Math.min(lnums[0], lnum) : lnum - info.error = info.error + 1 - } - } - } - let buf = this.nvim.createBuffer(this.bufnr) - buf.setVar('coc_diagnostic_info', info, true) - this.nvim.call('coc#util#do_autocmd', ['CocDiagnosticChange'], true) - } - - public showVirtualText(lnum: number, bufnr?: number): void { - if (!this.config.virtualText) return - let { virtualTextSrcId, virtualTextPrefix, virtualTextCurrentLineOnly } = this.config - let { diagnostics, buffer } = this - if (virtualTextCurrentLineOnly) { - if (bufnr && this.bufnr != bufnr) return - diagnostics = diagnostics.filter(d => { - let { start, end } = d.range - return start.line <= lnum - 1 && end.line >= lnum - 1 - }) - } - diagnostics.sort(sortDiagnostics) - buffer.clearNamespace(virtualTextSrcId) - for (let i = diagnostics.length - 1; i >= 0; i--) { - let diagnostic = diagnostics[i] - let { line } = diagnostic.range.start - let highlight = getNameFromSeverity(diagnostic.severity) + 'VirtualText' - let msg = diagnostic.message.split(/\n/) - .map((l: string) => l.trim()) - .filter((l: string) => l.length > 0) - .slice(0, this.config.virtualTextLines) - .join(this.config.virtualTextLineSeparator) - void buffer.setVirtualText(virtualTextSrcId, line, [[virtualTextPrefix + msg, highlight]], {}) - } - } - - public updateHighlights(collection: string, diagnostics: Diagnostic[]): void { - if (!diagnostics.length) { - this.clearHighlight(collection) - } else { - let items = this.getHighlightItems(diagnostics) - this.buffer.updateHighlights(highlightNamespace + collection, items) - } - } - - private getHighlightItems(diagnostics: ReadonlyArray): HighlightItem[] { - let doc = workspace.getDocument(this.bufnr) - if (!doc) return [] - let res: HighlightItem[] = [] - for (let diagnostic of diagnostics.slice(0, this.config.highlighLimit)) { - let hlGroup = getHighlightGroup(diagnostic) - doc.addHighlights(res, hlGroup, diagnostic.range) - } - // needed for iteration performance and since diagnostic highlight may cross lines. - res.sort((a, b) => { - if (a.lnum != b.lnum) return a.lnum - b.lnum - if (a.colStart != b.colStart) return a.colStart - b.colStart - return hlGroups.indexOf(b.hlGroup) - hlGroups.indexOf(a.hlGroup) - }) - return res - } - - /** - * Clear all diagnostics from UI. - */ - public clear(): void { - let { nvim } = this - let collections = Array.from(this.diagnosticsMap.keys()) - this.diagnosticsMap.clear() - if (this.displayByAle) { - for (let collection of collections) { - let method = global.hasOwnProperty('__TEST__') ? 'MockAleResults' : 'ale#other_source#ShowResults' - this.nvim.call(method, [this.bufnr, collection, []], true) - } - } else { - nvim.pauseNotification() - for (let collection of collections) { - this.clearHighlight(collection) - this.clearSigns(collection) - } - if (this.config.virtualText) { - this.buffer.clearNamespace(this.config.virtualTextSrcId) - } - this.buffer.deleteVar('coc_diagnostic_info') - void nvim.resumeNotification(false, true) - } - } - - /** - * Get diagnostics at cursor position. - */ - public getDiagnosticsAt(pos: Position, checkCurrentLine: boolean): Diagnostic[] { - let diagnostics: Diagnostic[] = [] - for (let diags of this.diagnosticsMap.values()) { - if (checkCurrentLine) { - diagnostics.push(...diags.filter(o => lineInRange(pos.line, o.range))) - } else { - diagnostics.push(...diags.filter(o => positionInRange(pos, o.range) == 0)) - } - } - diagnostics.sort(sortDiagnostics) - return diagnostics - } - - public async isEnabled(): Promise { - if (this._disposed) return false - let buf = this.nvim.createBuffer(this.bufnr) - let res = await buf.getVar('coc_diagnostic_disable') - return res != 1 - } - - public dispose(): void { - this._disposed = true - this.clear() - } -} - -/** - * Sort by severity and position - */ -function sortDiagnostics(a: Diagnostic, b: Diagnostic): number { - if ((a.severity || 1) != (b.severity || 1)) { - return (a.severity || 1) - (b.severity || 1) - } - let d = comparePosition(a.range.start, b.range.start) - if (d != 0) return d - return a.source > b.source ? 1 : -1 -} - -function getHighlightGroup(diagnostic: Diagnostic): DiagnosticHighlight { - let tags = diagnostic.tags || [] - if (tags.includes(DiagnosticTag.Deprecated)) { - return DiagnosticHighlight.Deprecated - } - if (tags.includes(DiagnosticTag.Unnecessary)) { - return DiagnosticHighlight.Unused - } - switch (diagnostic.severity) { - case DiagnosticSeverity.Warning: - return DiagnosticHighlight.Warning - case DiagnosticSeverity.Information: - return DiagnosticHighlight.Information - case DiagnosticSeverity.Hint: - return DiagnosticHighlight.Hint - default: - return DiagnosticHighlight.Error - } -} diff --git a/vim-config/plugins/coc.nvim/src/diagnostic/collection.ts b/vim-config/plugins/coc.nvim/src/diagnostic/collection.ts deleted file mode 100644 index d0e75c23..00000000 --- a/vim-config/plugins/coc.nvim/src/diagnostic/collection.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { Diagnostic, Emitter, Event, Range } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import workspace from '../workspace' -const logger = require('../util/logger')('diagnostic-collection') - -export default class DiagnosticCollection { - private diagnosticsMap: Map = new Map() - private _onDidDiagnosticsChange = new Emitter() - public readonly onDidDiagnosticsChange: Event = this._onDidDiagnosticsChange.event - - constructor( - public readonly name: string, - private onDispose?: () => void) { - } - - public set(uri: string, diagnostics: Diagnostic[] | undefined): void - public set(entries: [string, Diagnostic[] | undefined][]): void - public set(entries: [string, Diagnostic[] | undefined][] | string, diagnostics?: Diagnostic[]): void { - let diagnosticsPerFile: Map = new Map() - if (!Array.isArray(entries)) { - let doc = workspace.getDocument(entries) - let uri = doc ? doc.uri : entries - diagnosticsPerFile.set(uri, diagnostics || []) - } else { - for (let item of entries) { - let [uri, diagnostics] = item - let doc = workspace.getDocument(uri) - uri = doc ? doc.uri : uri - if (diagnostics == null) { - // clear previous diagnostics if entry contains null - diagnostics = [] - } else { - diagnostics = (diagnosticsPerFile.get(uri) || []).concat(diagnostics) - } - diagnosticsPerFile.set(uri, diagnostics) - } - } - for (let item of diagnosticsPerFile) { - let [uri, diagnostics] = item - uri = URI.parse(uri).toString() - diagnostics.forEach(o => { - // should be message for the file, but we need range - o.range = o.range || Range.create(0, 0, 0, 0) - o.message = o.message || '' - o.source = o.source || this.name - }) - this.diagnosticsMap.set(uri, diagnostics) - this._onDidDiagnosticsChange.fire(uri) - } - } - - public delete(uri: string): void { - this.diagnosticsMap.delete(uri) - this._onDidDiagnosticsChange.fire(uri) - } - - public clear(): void { - let uris = this.diagnosticsMap.keys() - this.diagnosticsMap.clear() - for (let uri of uris) { - this._onDidDiagnosticsChange.fire(uri) - } - } - - public forEach(callback: (uri: string, diagnostics: Diagnostic[], collection: DiagnosticCollection) => any, thisArg?: any): void { - for (let uri of this.diagnosticsMap.keys()) { - let diagnostics = this.diagnosticsMap.get(uri) - callback.call(thisArg, uri, diagnostics, this) - } - } - - public get(uri: string): Diagnostic[] { - let arr = this.diagnosticsMap.get(uri) - return arr == null ? [] : arr - } - - public has(uri: string): boolean { - return this.diagnosticsMap.has(uri) - } - - public dispose(): void { - this.clear() - if (this.onDispose) this.onDispose() - this._onDidDiagnosticsChange.dispose() - } -} diff --git a/vim-config/plugins/coc.nvim/src/diagnostic/manager.ts b/vim-config/plugins/coc.nvim/src/diagnostic/manager.ts deleted file mode 100644 index de4e34a0..00000000 --- a/vim-config/plugins/coc.nvim/src/diagnostic/manager.ts +++ /dev/null @@ -1,635 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import debounce from 'debounce' -import { Diagnostic, DiagnosticSeverity, DiagnosticTag, Disposable, Emitter, Event, Location, Position, Range } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { URI } from 'vscode-uri' -import events from '../events' -import BufferSync from '../model/bufferSync' -import FloatFactory from '../model/floatFactory' -import { ConfigurationChangeEvent, ErrorItem, LocationListItem } from '../types' -import { disposeAll } from '../util' -import { comparePosition, rangeIntersect } from '../util/position' -import window from '../window' -import workspace from '../workspace' -import { DiagnosticBuffer, DiagnosticConfig } from './buffer' -import DiagnosticCollection from './collection' -import { getLocationListItem, getSeverityName, severityLevel } from './util' -const logger = require('../util/logger')('diagnostic-manager') - -export interface DiagnosticEventParams { - bufnr: number - uri: string - diagnostics: ReadonlyArray -} - -export interface DiagnosticItem { - file: string - lnum: number - end_lnum: number - col: number - end_col: number - source: string - code: string | number - message: string - severity: string - level: number - location: Location -} - -export class DiagnosticManager implements Disposable { - public config: DiagnosticConfig - private enabled = true - private readonly _onDidRefresh = new Emitter() - public readonly onDidRefresh: Event = this._onDidRefresh.event - private buffers: BufferSync - private floatFactory: FloatFactory - private collections: DiagnosticCollection[] = [] - private disposables: Disposable[] = [] - private timer: NodeJS.Timer - - public init(): void { - this.setConfiguration() - workspace.onDidChangeConfiguration(e => { - this.setConfiguration(e) - }, null, this.disposables) - - this.floatFactory = new FloatFactory(this.nvim) - this.buffers = workspace.registerBufferSync(doc => { - if (doc.buftype !== '') return undefined - let buf = new DiagnosticBuffer( - this.nvim, doc.bufnr, doc.uri, this.config, - diagnostics => { - this._onDidRefresh.fire({ diagnostics, uri: buf.uri, bufnr: buf.bufnr }) - if (['never', 'jump'].includes(this.config.enableMessage)) return - if (events.insertMode) return - this.echoMessage(true).logError() - }) - let collections = this.getCollections(doc.uri) - if (this.enabled && collections.length) { - let diagnostics = this.getDiagnostics(doc.uri) - void buf.refresh(diagnostics) - } - return buf - }) - - workspace.onDidCloseTextDocument(e => { - for (let collection of this.collections) { - collection.delete(e.uri) - } - }, null, this.disposables) - - events.on('CursorMoved', bufnr => { - if (this.config.enableMessage != 'always') return - if (!this.buffers.getItem(bufnr)) return - if (this.timer) clearTimeout(this.timer) - this.timer = setTimeout(async () => { - await this.echoMessage(true) - }, this.config.messageDelay) - }, null, this.disposables) - - let fn = debounce((bufnr, cursor) => { - if (!this.config.virtualTextCurrentLineOnly) return - let buf = this.buffers.getItem(bufnr) - if (buf) buf.showVirtualText(cursor[0]) - }, 100) - events.on('CursorMoved', fn, null, this.disposables) - this.disposables.push(Disposable.create(() => { - fn.clear() - })) - let timer: NodeJS.Timer - events.on('InsertLeave', async bufnr => { - if (this.config.refreshOnInsertMode || !this.autoRefresh) return - let doc = workspace.getDocument(bufnr) - if (!doc?.attached) return - doc._forceSync() - timer = setTimeout(() => { - if (events.insertMode) return - for (let buf of this.buffers.items) { - void buf.refresh(this.getDiagnostics(buf.uri), false) - } - }, Math.max(0, 500 - Date.now() + events.lastChangeTs)) - }, null, this.disposables) - let clear = () => { - if (timer) clearTimeout(timer) - } - this.disposables.push({ dispose: clear }) - events.on('InsertEnter', clear, null, this.disposables) - events.on('BufEnter', async () => { - if (this.timer) clearTimeout(this.timer) - }, null, this.disposables) - let errorItems = workspace.configurations.errorItems - this.setConfigurationErrors(errorItems) - workspace.configurations.onError(items => { - this.setConfigurationErrors(items) - }, null, this.disposables) - } - - private defineSigns(): void { - let { nvim } = this - let { enableHighlightLineNumber, enableSign } = this.config - if (!enableSign) return - nvim.pauseNotification() - for (let kind of ['Error', 'Warning', 'Info', 'Hint']) { - let signText = this.config[kind.toLowerCase() + 'Sign'] - let cmd = `sign define Coc${kind} linehl=Coc${kind}Line` - if (signText) cmd += ` texthl=Coc${kind}Sign text=${signText}` - if (enableHighlightLineNumber) cmd += ` numhl=Coc${kind}Sign` - nvim.command(cmd, true) - } - void nvim.resumeNotification(false, true) - } - - /** - * Fill location list with diagnostics - */ - public async setLocationlist(bufnr: number): Promise { - let buf = this.buffers.getItem(bufnr) - let diagnosticsMap = buf ? this.getDiagnostics(buf.uri) : {} - let items: LocationListItem[] = [] - for (let diagnostics of Object.values(diagnosticsMap)) { - for (let diagnostic of diagnostics) { - let item = getLocationListItem(bufnr, diagnostic) - items.push(item) - } - } - let curr = await this.nvim.call('getloclist', [0, { title: 1 }]) as any - let action = curr.title && curr.title.indexOf('Diagnostics of coc') != -1 ? 'r' : ' ' - await this.nvim.call('setloclist', [0, [], action, { title: 'Diagnostics of coc', items }]) - } - - public setConfigurationErrors(errorItems?: ErrorItem[]): void { - let collection = this.create('config') - if (errorItems?.length) { - let entries: Map = new Map() - for (let item of errorItems) { - let { uri } = item.location - let diagnostics: Diagnostic[] = entries.get(uri) || [] - diagnostics.push(Diagnostic.create(item.location.range, item.message, DiagnosticSeverity.Error)) - entries.set(uri, diagnostics) - } - collection.set(Array.from(entries)) - } else { - collection.clear() - } - } - - /** - * Create collection by name - */ - public create(name: string): DiagnosticCollection { - let collection = this.getCollectionByName(name) - if (collection) return collection - collection = new DiagnosticCollection(name, () => { - let idx = this.collections.findIndex(o => o == collection) - if (idx !== -1) this.collections.splice(idx, 1) - }) - this.collections.push(collection) - collection.onDidDiagnosticsChange(uri => { - let buf = this.buffers.getItem(uri) - if (!this.autoRefresh || !buf) return - if (events.insertMode && !this.config.refreshOnInsertMode) return - void buf.refresh(this.getDiagnostics(uri, name), true) - }) - return collection - } - - /** - * Get diagnostics ranges from document - */ - public getSortedRanges(uri: string, severity?: string): Range[] { - let collections = this.getCollections(uri) - let res: Range[] = [] - let level = severity ? severityLevel(severity) : 0 - for (let collection of collections) { - let diagnostics = collection.get(uri) - if (level) { - diagnostics = diagnostics.filter(o => o.severity == level) - } else { - let minLevel = this.config.level - if (minLevel && minLevel < DiagnosticSeverity.Hint) { - diagnostics = diagnostics.filter(o => { - if (o.severity && o.severity > minLevel) { - return false - } - return true - }) - } - } - let ranges = diagnostics.map(o => o.range) - res.push(...ranges) - } - res.sort((a, b) => { - if (a.start.line != b.start.line) { - return a.start.line - b.start.line - } - return a.start.character - b.start.character - }) - return res - } - - /** - * Get readonly diagnostics for a buffer - */ - public getDiagnostics(uri: string, collection?: string): { [collection: string]: Diagnostic[] } { - let res: { [collection: string]: Diagnostic[] } = {} - let collections = collection ? [this.getCollectionByName(collection)] : this.getCollections(uri) - let { level, showUnused, showDeprecated } = this.config - for (let collection of collections) { - if (!collection) continue - let items = collection.get(uri) || [] - if (items.length) { - items = items.filter(d => { - if (level && d.severity && d.severity > level) { - return false - } - if (!showUnused && d.tags?.includes(DiagnosticTag.Unnecessary)) { - return false - } - if (!showDeprecated && d.tags?.includes(DiagnosticTag.Deprecated)) { - return false - } - return true - }) - items.sort((a, b) => { - return comparePosition(a.range.start, b.range.start) - }) - } - res[collection.name] = items - } - return res - } - - public getDiagnosticsInRange(document: TextDocument, range: Range): Diagnostic[] { - let collections = this.getCollections(document.uri) - let res: Diagnostic[] = [] - for (let collection of collections) { - let items = collection.get(document.uri) - if (!items) continue - for (let item of items) { - if (rangeIntersect(item.range, range)) { - res.push(item) - } - } - } - return res - } - - /** - * Show diagnostics under curosr in preview window - */ - public async preview(): Promise { - let diagnostics = await this.getCurrentDiagnostics() - if (diagnostics.length == 0) { - this.nvim.command('pclose', true) - return - } - let lines: string[] = [] - for (let diagnostic of diagnostics) { - let { source, code, severity, message } = diagnostic - let s = getSeverityName(severity)[0] - lines.push(`[${source}${code ? ' ' + code : ''}] [${s}]`) - lines.push(...message.split(/\r?\n/)) - lines.push('') - } - this.nvim.call('coc#util#preview_info', [lines, 'txt'], true) - } - - /** - * Jump to previous diagnostic position - */ - public async jumpPrevious(severity?: string): Promise { - let buffer = await this.nvim.buffer - let document = workspace.getDocument(buffer.id) - if (!document) return - let curpos = await window.getCursorPosition() - let ranges = this.getSortedRanges(document.uri, severity) - let pos: Position - for (let i = ranges.length - 1; i >= 0; i--) { - let end = ranges[i].end - if (comparePosition(end, curpos) < 0) { - pos = ranges[i].start - break - } else if (i == 0) { - let wrapscan = await this.nvim.getOption('wrapscan') - if (wrapscan) pos = ranges[ranges.length - 1].start - } - } - if (pos) { - await window.moveTo(pos) - if (this.config.enableMessage == 'never') return - await this.echoMessage(false) - } - } - - /** - * Jump to next diagnostic position - */ - public async jumpNext(severity?: string): Promise { - let buffer = await this.nvim.buffer - let document = workspace.getDocument(buffer.id) - let curpos = await window.getCursorPosition() - let ranges = this.getSortedRanges(document.uri, severity) - let pos: Position - for (let i = 0; i <= ranges.length - 1; i++) { - let start = ranges[i].start - if (comparePosition(start, curpos) > 0) { - pos = ranges[i].start - break - } else if (i == ranges.length - 1) { - let wrapscan = await this.nvim.getOption('wrapscan') - if (wrapscan) pos = ranges[0].start - } - } - if (pos) { - await window.moveTo(pos) - if (this.config.enableMessage == 'never') return - await this.echoMessage(false) - } - } - - /** - * All diagnostics of current workspace - */ - public getDiagnosticList(): DiagnosticItem[] { - let res: DiagnosticItem[] = [] - const { level, showUnused, showDeprecated } = this.config - for (let collection of this.collections) { - collection.forEach((uri, diagnostics) => { - let file = URI.parse(uri).fsPath - for (let diagnostic of diagnostics) { - if (diagnostic.severity && diagnostic.severity > level) { - continue - } - if (!showUnused && diagnostic.tags?.includes(DiagnosticTag.Unnecessary)) { - continue - } - if (!showDeprecated && diagnostic.tags?.includes(DiagnosticTag.Deprecated)) { - continue - } - let { start, end } = diagnostic.range - let o: DiagnosticItem = { - file, - lnum: start.line + 1, - end_lnum: end.line + 1, - col: start.character + 1, - end_col: end.character + 1, - code: diagnostic.code, - source: diagnostic.source || collection.name, - message: diagnostic.message, - severity: getSeverityName(diagnostic.severity), - level: diagnostic.severity || 0, - location: Location.create(uri, diagnostic.range) - } - res.push(o) - } - }) - } - res.sort((a, b) => { - if (a.level !== b.level) { - return a.level - b.level - } - if (a.file !== b.file) { - return a.file > b.file ? 1 : -1 - } else { - if (a.lnum != b.lnum) { - return a.lnum - b.lnum - } - return a.col - b.col - } - }) - return res - } - - private getDiagnosticsAt(bufnr: number, cursor: [number, number], atEnd = false, lastline = false): Diagnostic[] { - let buffer = this.buffers.getItem(bufnr) - if (!buffer) return [] - let pos = Position.create(cursor[0], cursor[1]) - let res = buffer.getDiagnosticsAt(pos, this.config.checkCurrentLine) - if (this.config.checkCurrentLine || res.length) return res - // check next character when cursor at end of line. - if (atEnd) { - pos = Position.create(cursor[0], cursor[1] + 1) - res = buffer.getDiagnosticsAt(pos, false) - if (res.length) return res - } - // check next line when cursor at the beginning of last line. - if (lastline && cursor[1] == 0) { - pos = Position.create(cursor[0] + 1, 0) - res = buffer.getDiagnosticsAt(pos, false) - } - return res - } - - public async getCurrentDiagnostics(): Promise { - let [bufnr, cursor, eol, lastline] = await this.nvim.eval(`[bufnr("%"),coc#cursor#position(),col('.')==col('$')-1,line('.')==line('$')]`) as [number, [number, number], number, number] - return this.getDiagnosticsAt(bufnr, cursor, eol == 1, lastline == 1) - } - - /** - * Echo diagnostic message under cursor. - */ - public async echoMessage(truncate = false): Promise { - const config = this.config - if (!this.enabled || config.displayByAle) return - if (this.timer) clearTimeout(this.timer) - let useFloat = config.messageTarget == 'float' - // echo - let [filetype, mode] = await this.nvim.eval(`[&filetype,mode()]`) as [string, string] - if (mode != 'n') return - let diagnostics = await this.getCurrentDiagnostics() - if (diagnostics.length == 0) { - if (useFloat) this.floatFactory.close() - return - } - if (truncate && workspace.insertMode) return - let docs = [] - let ft = '' - if (Object.keys(config.filetypeMap).length > 0) { - const defaultFiletype = config.filetypeMap['default'] || '' - ft = config.filetypeMap[filetype] || (defaultFiletype == 'bufferType' ? filetype : defaultFiletype) - } - diagnostics.forEach(diagnostic => { - let { source, code, severity, message } = diagnostic - let s = getSeverityName(severity)[0] - const codeStr = code ? ' ' + code : '' - const str = config.format.replace('%source', source).replace('%code', codeStr).replace('%severity', s).replace('%message', message) - let filetype = 'Error' - if (ft === '') { - switch (severity) { - case DiagnosticSeverity.Hint: - filetype = 'Hint' - break - case DiagnosticSeverity.Warning: - filetype = 'Warning' - break - case DiagnosticSeverity.Information: - filetype = 'Info' - break - } - } else { - filetype = ft - } - docs.push({ filetype, content: str }) - }) - if (useFloat) { - let config = this.floatFactory.applyFloatConfig({ modes: ['n'], maxWidth: 80 }, this.config.floatConfig) - await this.floatFactory.show(docs, config) - } else { - let lines = docs.map(d => d.content).join('\n').split(/\r?\n/) - if (lines.length) { - await this.nvim.command('echo ""') - await window.echoLines(lines, truncate) - } - } - } - - public async jumpRelated(): Promise { - let diagnostics = await this.getCurrentDiagnostics() - if (!diagnostics) return - let diagnostic = diagnostics.find(o => o.relatedInformation != null) - if (!diagnostic) return - let locations = diagnostic.relatedInformation.map(o => o.location) - if (locations.length == 1) { - await workspace.jumpTo(locations[0].uri, locations[0].range.start) - } else if (locations.length > 1) { - await workspace.showLocations(locations) - } - } - - public reset(): void { - if (this.timer) { - clearTimeout(this.timer) - } - this.buffers.reset() - for (let collection of this.collections) { - collection.dispose() - } - this.collections = [] - } - - public dispose(): void { - this.buffers.dispose() - if (this.timer) { - clearTimeout(this.timer) - } - for (let collection of this.collections) { - collection.dispose() - } - this.floatFactory?.close() - this.collections = [] - disposeAll(this.disposables) - } - - private get nvim(): Neovim { - return workspace.nvim - } - - private setConfiguration(event?: ConfigurationChangeEvent): void { - if (event && !event.affectsConfiguration('diagnostic')) return - let config = workspace.getConfiguration('diagnostic') - let messageTarget = config.get('messageTarget', 'float') - if (messageTarget == 'float' && !workspace.env.floating && !workspace.env.textprop) { - messageTarget = 'echo' - } - let enableHighlightLineNumber = config.get('enableHighlightLineNumber', true) - if (!workspace.isNvim) enableHighlightLineNumber = false - this.config = { - floatConfig: config.get('floatConfig', {}), - messageTarget, - enableHighlightLineNumber, - highlighLimit: config.get('highlighLimit', 1000), - autoRefresh: config.get('autoRefresh', true), - virtualTextSrcId: workspace.createNameSpace('diagnostic-virtualText'), - checkCurrentLine: config.get('checkCurrentLine', false), - enableSign: workspace.env.sign && config.get('enableSign', true), - locationlistUpdate: config.get('locationlistUpdate', true), - enableMessage: config.get('enableMessage', 'always'), - messageDelay: config.get('messageDelay', 200), - virtualText: config.get('virtualText', false) && this.nvim.hasFunction('nvim_buf_set_virtual_text'), - virtualTextCurrentLineOnly: config.get('virtualTextCurrentLineOnly', true), - virtualTextPrefix: config.get('virtualTextPrefix', " "), - virtualTextLineSeparator: config.get('virtualTextLineSeparator', " \\ "), - virtualTextLines: config.get('virtualTextLines', 3), - displayByAle: config.get('displayByAle', false), - level: severityLevel(config.get('level', 'hint')), - signPriority: config.get('signPriority', 10), - errorSign: config.get('errorSign', '>>'), - warningSign: config.get('warningSign', '>>'), - infoSign: config.get('infoSign', '>>'), - hintSign: config.get('hintSign', '>>'), - refreshOnInsertMode: config.get('refreshOnInsertMode', false), - filetypeMap: config.get('filetypeMap', {}), - showUnused: config.get('showUnused', true), - showDeprecated: config.get('showDeprecated', true), - format: config.get('format', '[%source%code] [%severity] %message'), - } - this.enabled = config.get('enable', true) - this.defineSigns() - } - - public getCollectionByName(name: string): DiagnosticCollection { - return this.collections.find(o => o.name == name) - } - - private getCollections(uri: string): DiagnosticCollection[] { - return this.collections.filter(c => c.has(uri)) - } - - public toggleDiagnostic(): void { - let { enabled } = this - this.enabled = !enabled - for (let buf of this.buffers.items) { - if (this.enabled) { - void this.refreshBuffer(buf.uri, true) - } else { - buf.clear() - } - } - } - - public async toggleDiagnosticBuffer(bufnr: number): Promise { - if (!this.enabled) return - let buf = this.buffers.getItem(bufnr) - if (buf) { - let isEnabled = await buf.isEnabled() - await this.nvim.call('setbufvar', [bufnr, 'coc_diagnostic_disable', isEnabled ? 1 : 0]) - if (isEnabled) { - buf.clear() - } else { - void this.refreshBuffer(bufnr, true) - } - } - } - - private get autoRefresh(): boolean { - return this.enabled && this.config.autoRefresh - } - - /** - * Refresh diagnostics by uri or bufnr - */ - public async refreshBuffer(uri: string | number, force = false): Promise { - let buf = this.buffers.getItem(uri) - if (!buf) return false - await buf.refresh(this.getDiagnostics(buf.uri), force) - return true - } - - /** - * Force diagnostics refresh. - */ - public refresh(bufnr?: number): void { - if (!bufnr) { - for (let item of this.buffers.items) { - void this.refreshBuffer(item.uri, true) - } - } else { - let item = this.buffers.getItem(bufnr) - if (item) { - void this.refreshBuffer(item.uri, true) - } - } - } -} - -export default new DiagnosticManager() diff --git a/vim-config/plugins/coc.nvim/src/diagnostic/util.ts b/vim-config/plugins/coc.nvim/src/diagnostic/util.ts deleted file mode 100644 index 83d7335c..00000000 --- a/vim-config/plugins/coc.nvim/src/diagnostic/util.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { DiagnosticSeverity, Diagnostic } from 'vscode-languageserver-protocol' -import { LocationListItem } from '../types' - -export function getSeverityName(severity: DiagnosticSeverity): string { - switch (severity) { - case DiagnosticSeverity.Warning: - return 'Warning' - case DiagnosticSeverity.Information: - return 'Information' - case DiagnosticSeverity.Hint: - return 'Hint' - default: - return 'Error' - } -} - -export function getSeverityType(severity: DiagnosticSeverity): string { - switch (severity) { - case DiagnosticSeverity.Warning: - return 'W' - case DiagnosticSeverity.Information: - return 'I' - case DiagnosticSeverity.Hint: - return 'I' - default: - return 'E' - } -} - -export function severityLevel(level: string): number { - switch (level) { - case 'hint': - return DiagnosticSeverity.Hint - case 'information': - return DiagnosticSeverity.Information - case 'warning': - return DiagnosticSeverity.Warning - case 'error': - return DiagnosticSeverity.Error - default: - return DiagnosticSeverity.Hint - } -} - -export function getNameFromSeverity(severity: DiagnosticSeverity): string { - switch (severity) { - case DiagnosticSeverity.Error: - return 'CocError' - case DiagnosticSeverity.Warning: - return 'CocWarning' - case DiagnosticSeverity.Information: - return 'CocInfo' - case DiagnosticSeverity.Hint: - return 'CocHint' - default: - return 'CocError' - } -} - -export function getLocationListItem(bufnr: number, diagnostic: Diagnostic): LocationListItem { - let { start, end } = diagnostic.range - let owner = diagnostic.source || 'coc.nvim' - let msg = diagnostic.message.split('\n')[0] - let type = getSeverityName(diagnostic.severity).slice(0, 1).toUpperCase() - return { - bufnr, - lnum: start.line + 1, - end_lnum: end.line + 1, - col: start.character + 1, - end_col: end.character + 1, - text: `[${owner}${diagnostic.code ? ' ' + diagnostic.code : ''}] ${msg} [${type}]`, - type - } -} diff --git a/vim-config/plugins/coc.nvim/src/events.ts b/vim-config/plugins/coc.nvim/src/events.ts deleted file mode 100644 index 7dbbb7f9..00000000 --- a/vim-config/plugins/coc.nvim/src/events.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { Disposable } from 'vscode-languageserver-protocol' -import { disposeAll } from './util' -import { VimCompleteItem } from './types' -import { equals } from './util/object' -const logger = require('./util/logger')('events') - -export type Result = void | Promise - -export interface PopupChangeEvent { - completed_item: VimCompleteItem | {} - height: number - width: number - row: number - col: number - size: number - scrollbar: boolean -} - -export interface InsertChange { - lnum: number - col: number - pre: string - changedtick: number -} - -export type BufEvents = 'BufHidden' | 'BufEnter' | 'BufWritePost' - | 'CursorHold' | 'InsertLeave' | 'TermOpen' | 'TermClose' | 'InsertEnter' - | 'BufCreate' | 'BufUnload' | 'BufWritePre' | 'CursorHoldI' | 'Enter' - -export type EmptyEvents = 'FocusGained' | 'FocusLost' | 'InsertSnippet' | 'ready' - -export type InsertChangeEvents = 'TextChangedP' | 'TextChangedI' - -export type TaskEvents = 'TaskExit' | 'TaskStderr' | 'TaskStdout' - -export type WindowEvents = 'WinLeave' | 'WinEnter' | 'WinClosed' - -export type AllEvents = BufEvents | EmptyEvents | MoveEvents | TaskEvents | WindowEvents - | InsertChangeEvents | 'CompleteDone' | 'TextChanged' | 'MenuPopupChanged' - | 'InsertCharPre' | 'FileType' | 'BufWinEnter' | 'BufWinLeave' | 'VimResized' - | 'DirChanged' | 'OptionSet' | 'Command' | 'BufReadCmd' | 'GlobalChange' | 'InputChar' - | 'WinLeave' | 'MenuInput' | 'PromptInsert' | 'FloatBtnClick' | 'InsertSnippet' | 'TextInsert' - -export type MoveEvents = 'CursorMoved' | 'CursorMovedI' - -export type OptionValue = string | number | boolean - -export interface CursorPosition { - bufnr: number - lnum: number - col: number - insert: boolean -} - -export interface LatestInsert { - bufnr: number - character: string - timestamp: number -} - -class Events { - - private handlers: Map = new Map() - private _cursor: CursorPosition - private _latestInsert: LatestInsert - private _lastChange = 0 - private _insertMode = false - private _pumAlignTop = false - - public get cursor(): CursorPosition { - return this._cursor - } - - public get pumAlignTop(): boolean { - return this._pumAlignTop - } - - public get insertMode(): boolean { - return this._insertMode - } - - public get lastChangeTs(): number { - return this._lastChange - } - - public async fire(event: string, args: any[]): Promise { - let cbs = this.handlers.get(event) - if (event == 'InsertEnter') { - this._insertMode = true - } else if (event == 'InsertLeave') { - this._insertMode = false - } else if (!this._insertMode && (event == 'CursorHoldI' || event == 'CursorMovedI')) { - this._insertMode = true - void this.fire('InsertEnter', [args[0]]) - } else if (this._insertMode && (event == 'CursorHold' || event == 'CursorMoved')) { - this._insertMode = false - this.fire('InsertLeave', [args[0]]).logError() - } - if (event == 'MenuPopupChanged') { - this._pumAlignTop = args[1] > args[0].row - } - if (event == 'InsertCharPre') { - this._latestInsert = { bufnr: args[1], character: args[0], timestamp: Date.now() } - } - if (event == 'TextChanged') { - this._lastChange = Date.now() - } - if (event == 'TextChangedI' || event == 'TextChangedP') { - this._lastChange = Date.now() - if (this._latestInsert) { - let insert = this._latestInsert - this._latestInsert = undefined - if (insert.bufnr == args[0] && Date.now() - insert.timestamp < 200 && args[1].pre.length) { - let character = args[1].pre.slice(-1) - // make it fires after TextChangedI & TextChangedP - process.nextTick(() => { - void this.fire('TextInsert', [...args, character]) - }) - } - } - } - if (event == 'CursorMoved' || event == 'CursorMovedI') { - let cursor = { - bufnr: args[0], - lnum: args[1][0], - col: args[1][1], - insert: event == 'CursorMovedI' - } - // Avoid CursorMoved event when it's not moved at all - if (this._cursor && equals(this._cursor, cursor)) return - this._cursor = cursor - } - if (cbs) { - try { - await Promise.all(cbs.map(fn => fn(args))) - } catch (e) { - if (e.message && e.message.indexOf('transport disconnected') == -1) return - logger.error(`Error on event: ${event}`, e.stack) - } - } - } - - public on(event: EmptyEvents | AllEvents[], handler: () => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: BufEvents, handler: (bufnr: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: MoveEvents, handler: (bufnr: number, cursor: [number, number]) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: InsertChangeEvents, handler: (bufnr: number, info: InsertChange) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: WindowEvents, handler: (winid: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'TextInsert', handler: (bufnr: number, info: InsertChange, character: string) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'FloatBtnClick', handler: (bufnr: number, index: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'TextChanged', handler: (bufnr: number, changedtick: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'TaskExit', handler: (id: string, code: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'TaskStderr' | 'TaskStdout', handler: (id: string, lines: string[]) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'BufReadCmd', handler: (scheme: string, fullpath: string) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'VimResized', handler: (columns: number, lines: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'Command', handler: (name: string) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'MenuPopupChanged', handler: (event: PopupChangeEvent, cursorline: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'CompleteDone', handler: (item: VimCompleteItem) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'InsertCharPre', handler: (character: string, bufnr: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'FileType', handler: (filetype: string, bufnr: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'BufWinEnter' | 'BufWinLeave', handler: (bufnr: number, winid: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'DirChanged', handler: (cwd: string) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'OptionSet' | 'GlobalChange', handler: (option: string, oldVal: OptionValue, newVal: OptionValue) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'InputChar', handler: (session: string, character: string, mode: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: 'PromptInsert', handler: (value: string, bufnr: number) => Result, thisArg?: any, disposables?: Disposable[]): Disposable - public on(event: AllEvents[] | AllEvents, handler: (...args: any[]) => Result, thisArg?: any, disposables?: Disposable[]): Disposable { - if (Array.isArray(event)) { - let arr = disposables || [] - for (let ev of event) { - this.on(ev as any, handler, thisArg, arr) - } - return Disposable.create(() => { - disposeAll(arr) - }) - } else { - let arr = this.handlers.get(event) || [] - let stack = Error().stack - let wrappedhandler = args => new Promise((resolve, reject) => { - let timer - try { - Promise.resolve(handler.apply(thisArg || null, args)).then(() => { - if (timer) clearTimeout(timer) - resolve(undefined) - }, e => { - if (timer) clearTimeout(timer) - reject(e) - }) - timer = setTimeout(() => { - logger.warn(`Handler of ${event} blocked more than 2s:`, stack) - }, 2000) - } catch (e) { - reject(e) - } - }) - arr.push(wrappedhandler) - this.handlers.set(event, arr) - let disposable = Disposable.create(() => { - let idx = arr.indexOf(wrappedhandler) - if (idx !== -1) { - arr.splice(idx, 1) - } - }) - if (disposables) { - disposables.push(disposable) - } - return disposable - } - } -} -export default new Events() diff --git a/vim-config/plugins/coc.nvim/src/extensions.ts b/vim-config/plugins/coc.nvim/src/extensions.ts deleted file mode 100644 index 1be986d2..00000000 --- a/vim-config/plugins/coc.nvim/src/extensions.ts +++ /dev/null @@ -1,1061 +0,0 @@ -import { debounce } from 'debounce' -import { parse, ParseError } from 'jsonc-parser' -import fs from 'fs-extra' -import isuri from 'isuri' -import path from 'path' -import semver from 'semver' -import { Disposable, Emitter, Event } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import which from 'which' -import commandManager from './commands' -import events from './events' -import DB from './model/db' -import FloatFactory from './model/floatFactory' -import InstallBuffer from './model/installBuffer' -import { createInstallerFactory } from './model/installer' -import Memos from './model/memos' -import { disposeAll, wait, concurrent, watchFile } from './util' -import { distinct, splitArray } from './util/array' -import './util/extensions' -import { createExtension, ExtensionExport } from './util/factory' -import { inDirectory, readFile, statAsync } from './util/fs' -import { objectLiteral } from './util/is' -import Watchman from './watchman' -import workspace from './workspace' -import window from './window' -import { OutputChannel } from './types' - -const createLogger = require('./util/logger') -const logger = createLogger('extensions') - -export type API = { [index: string]: any } | void | null | undefined - -export type ExtensionState = 'disabled' | 'loaded' | 'activated' | 'unknown' - -export enum ExtensionType { - Global, - Local, - SingleFile, - Internal -} - -export interface PropertyScheme { - type: string - default: any - description: string - enum?: string[] - items?: any - [key: string]: any -} - -export interface Extension { - readonly id: string - readonly extensionPath: string - readonly isActive: boolean - readonly packageJSON: any - readonly exports: T - activate(): Promise -} - -export interface ExtensionItem { - id: Readonly - type: Readonly - extension: Extension - deactivate: () => void | Promise - filepath?: string - directory?: string - isLocal: Readonly -} - -export interface ExtensionJson { - name: string - main?: string - engines: { - [key: string]: string - } - version?: string - [key: string]: any -} - -export interface ExtensionInfo { - id: string - version: string - description: string - root: string - exotic: boolean - uri?: string - state: ExtensionState - isLocal: boolean - packageJSON: Readonly -} - -// global local file native -export class Extensions { - private extensions: Map = new Map() - private disabled: Set = new Set() - private db: DB - private memos: Memos - private root: string - private _onDidLoadExtension = new Emitter>() - private _onDidActiveExtension = new Emitter>() - private _onDidUnloadExtension = new Emitter() - private _additionalSchemes: { [key: string]: PropertyScheme } = {} - private activated = false - private installBuffer: InstallBuffer - private disposables: Disposable[] = [] - private _outputChannel: OutputChannel | undefined - public ready = true - public readonly onDidLoadExtension: Event> = this._onDidLoadExtension.event - public readonly onDidActiveExtension: Event> = this._onDidActiveExtension.event - public readonly onDidUnloadExtension: Event = this._onDidUnloadExtension.event - - constructor() { - let folder = global.hasOwnProperty('__TEST__') ? path.join(__dirname, '__tests__') : process.env.COC_DATA_HOME - let root = this.root = path.join(folder, 'extensions') - if (!fs.existsSync(root)) { - fs.mkdirpSync(root) - } - let jsonFile = path.join(root, 'package.json') - if (!fs.existsSync(jsonFile)) { - fs.writeFileSync(jsonFile, '{"dependencies":{}}', 'utf8') - } - let filepath = path.join(root, 'db.json') - this.db = new DB(filepath) - } - - private get outputChannel(): OutputChannel { - if (this._outputChannel) return this._outputChannel - this._outputChannel = window.createOutputChannel('extensions') - return this._outputChannel - } - - public async init(): Promise { - let extensionObj = this.db.fetch('extension') || {} - let keys = Object.keys(extensionObj) - for (let key of keys) { - if (extensionObj[key].disabled == true) { - this.disabled.add(key) - } - } - if (process.env.COC_NO_PLUGINS) return - let stats = await this.globalExtensionStats() - let localStats = await this.localExtensionStats(stats.map(o => o.id)) - stats = stats.concat(localStats) - this.memos = new Memos(path.resolve(this.root, '../memos.json')) - stats.map(stat => { - let extensionType = stat.isLocal ? ExtensionType.Local : ExtensionType.Global - try { - this.createExtension(stat.root, stat.packageJSON, extensionType) - } catch (e) { - logger.error(`Error on create ${stat.root}:`, e) - } - }) - await this.loadFileExtensions() - commandManager.register({ - id: 'extensions.forceUpdateAll', - execute: async () => { - let arr = await this.cleanExtensions() - logger.info(`Force update extensions: ${arr}`) - await this.installExtensions(arr) - } - }, false, 'remove all global extensions and install them') - workspace.onDidRuntimePathChange(async paths => { - for (let p of paths) { - if (p && this.checkDirectory(p) === true) { - await this.loadExtension(p) - } - } - }, null, this.disposables) - } - - public activateExtensions(): void { - this.activated = true - for (let item of this.extensions.values()) { - let { id, packageJSON } = item.extension - this.setupActiveEvents(id, packageJSON).logError() - } - // make sure workspace.env exists - let floatFactory = new FloatFactory(workspace.nvim) - events.on('CursorMoved', debounce(async bufnr => { - if (this.installBuffer && bufnr == this.installBuffer.bufnr) { - let lnum = await workspace.nvim.call('line', ['.']) - let msgs = this.installBuffer.getMessages(lnum - 1) - let docs = msgs && msgs.length ? [{ content: msgs.join('\n'), filetype: 'txt' }] : [] - await floatFactory.show(docs, { modes: ['n'] }) - } - }, 500)) - if (global.hasOwnProperty('__TEST__')) return - // check extensions need watch & install - this.checkExtensions().logError() - let config = workspace.getConfiguration('coc.preferences') - let interval = config.get('extensionUpdateCheck', 'never') - let silent = config.get('silentAutoupdate', true) - if (interval != 'never') { - let now = new Date() - let day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - (interval == 'daily' ? 0 : 7)) - let ts = this.db.fetch('lastUpdate') - if (ts && Number(ts) > day.getTime()) return - this.outputChannel.appendLine('Start auto update...') - this.updateExtensions(false, silent).logError() - } - } - - public async updateExtensions(sync?: boolean, silent = false): Promise { - if (!this.npm) return - let lockedList = await this.getLockedList() - let stats = await this.globalExtensionStats() - stats = stats.filter(o => ![...lockedList, ...this.disabled].includes(o.id)) - this.db.push('lastUpdate', Date.now()) - if (silent) { - window.showMessage('Updating extensions, checkout output:///extensions for details.', 'more') - } - let installBuffer = this.installBuffer = new InstallBuffer(true, sync, silent ? this.outputChannel : undefined) - installBuffer.setExtensions(stats.map(o => o.id)) - await installBuffer.show(workspace.nvim) - let createInstaller = createInstallerFactory(this.npm, this.modulesFolder) - let fn = (stat: ExtensionInfo): Promise => { - let { id } = stat - installBuffer.startProgress([id]) - let url = stat.exotic ? stat.uri : null - // msg => installBuffer.addMessage(id, msg) - let installer = createInstaller(id) - installer.on('message', (msg, isProgress) => { - installBuffer.addMessage(id, msg, isProgress) - }) - return installer.update(url).then(directory => { - installBuffer.finishProgress(id, true) - if (directory) { - this.loadExtension(directory).logError() - } - }, err => { - installBuffer.addMessage(id, err.message) - installBuffer.finishProgress(id, false) - }) - } - await concurrent(stats, fn, silent ? 1 : 3) - } - - private async checkExtensions(): Promise { - let { globalExtensions } = workspace.env - if (globalExtensions && globalExtensions.length) { - let names = this.filterGlobalExtensions(globalExtensions) - this.installExtensions(names).logError() - } - } - - public get installer() { - return createInstallerFactory(this.npm, this.modulesFolder) - } - - /** - * Install extensions, can be called without initialize. - */ - public async installExtensions(list: string[] = []): Promise { - let { npm } = this - if (!npm || !list.length) return - list = distinct(list) - let installBuffer = this.installBuffer = new InstallBuffer() - installBuffer.setExtensions(list) - await installBuffer.show(workspace.nvim) - let createInstaller = createInstallerFactory(this.npm, this.modulesFolder) - let fn = (key: string): Promise => { - installBuffer.startProgress([key]) - let installer = createInstaller(key) - installer.on('message', (msg, isProgress) => { - installBuffer.addMessage(key, msg, isProgress) - }) - return installer.install().then(name => { - installBuffer.finishProgress(key, true) - let directory = path.join(this.modulesFolder, name) - this.loadExtension(directory).logError() - }, err => { - installBuffer.addMessage(key, err.message) - installBuffer.finishProgress(key, false) - logger.error(`Error on install ${key}`, err) - }) - } - await concurrent(list, fn) - } - - /** - * Get list of extensions in package.json that not installed - */ - public getMissingExtensions(): string[] { - let json = this.loadJson() || { dependencies: {} } - let ids: string[] = [] - for (let key of Object.keys(json.dependencies)) { - let folder = path.join(this.modulesFolder, key) - if (!fs.existsSync(folder)) { - let val = json.dependencies[key] - if (val.startsWith('http')) { - ids.push(val) - } else { - ids.push(key) - } - } - } - return ids - } - - public get npm(): string { - let npm = workspace.getConfiguration('npm').get('binPath', 'npm') - npm = workspace.expand(npm) - for (let exe of [npm, 'yarnpkg', 'yarn', 'npm']) { - try { - let res = which.sync(exe) - return res - } catch (e) { - continue - } - } - window.showMessage(`Can't find npm or yarn in your $PATH`, 'error') - return null - } - - /** - * Get all loaded extensions. - */ - public get all(): Extension[] { - return Array.from(this.extensions.values()).map(o => o.extension).filter(o => !this.isDisabled(o.id)) - } - - public getExtension(id: string): ExtensionItem { - return this.extensions.get(id) - } - - public getExtensionState(id: string): ExtensionState { - let disabled = this.isDisabled(id) - if (disabled) return 'disabled' - let item = this.extensions.get(id) - if (!item) return 'unknown' - let { extension } = item - return extension.isActive ? 'activated' : 'loaded' - } - - public async getExtensionStates(): Promise { - let localStats = await this.localExtensionStats([]) - let globalStats = await this.globalExtensionStats() - return localStats.concat(globalStats.filter(o => localStats.find(s => s.id == o.id) == null)) - } - - public async getLockedList(): Promise { - let obj = await this.db.fetch('extension') - obj = obj || {} - return Object.keys(obj).filter(id => obj[id].locked === true) - } - - public async toggleLock(id: string): Promise { - let key = `extension.${id}.locked` - let locked = await this.db.fetch(key) - if (locked) { - this.db.delete(key) - } else { - this.db.push(key, true) - } - } - - public async toggleExtension(id: string): Promise { - let state = this.getExtensionState(id) - if (state == null) return - if (state == 'activated') { - await this.deactivate(id) - } - let key = `extension.${id}.disabled` - this.db.push(key, state == 'disabled' ? false : true) - if (state != 'disabled') { - this.disabled.add(id) - await this.unloadExtension(id) - } else { - this.disabled.delete(id) - let folder = path.join(this.modulesFolder, id) - if (fs.existsSync(folder)) { - await this.loadExtension(folder) - } - } - await wait(200) - } - - public async reloadExtension(id: string): Promise { - let item = this.extensions.get(id) - if (!item) { - window.showMessage(`Extension ${id} not registered`, 'error') - return - } - if (item.type == ExtensionType.Internal) { - window.showMessage(`Can't reload internal extension "${item.id}"`, 'warning') - return - } - if (item.type == ExtensionType.SingleFile) { - await this.loadExtensionFile(item.filepath) - } else if (item.directory) { - await this.loadExtension(item.directory) - } else { - window.showMessage(`Can't reload extension ${item.id}`, 'warning') - } - } - - /** - * Unload & remove all global extensions, return removed extensions. - */ - public async cleanExtensions(): Promise { - let dir = this.modulesFolder - if (!fs.existsSync(dir)) return [] - let ids = this.globalExtensions - let res: string[] = [] - for (let id of ids) { - let directory = path.join(dir, id) - let stat = await fs.lstat(directory) - if (!stat || (stat && stat.isSymbolicLink())) continue - await this.unloadExtension(id) - await fs.remove(directory) - res.push(id) - } - return res - } - - public async uninstallExtension(ids: string[]): Promise { - try { - if (!ids.length) return - let [globals, filtered] = splitArray(ids, id => this.globalExtensions.includes(id)) - if (filtered.length) { - window.showMessage(`Extensions ${filtered} not global extensions, can't uninstall!`, 'warning') - } - let json = this.loadJson() || { dependencies: {} } - for (let id of globals) { - await this.unloadExtension(id) - delete json.dependencies[id] - // remove directory - let folder = path.join(this.modulesFolder, id) - if (fs.existsSync(folder)) { - await fs.remove(folder) - } - } - // update package.json - const sortedObj = { dependencies: {} } - Object.keys(json.dependencies).sort().forEach(k => { - sortedObj.dependencies[k] = json.dependencies[k] - }) - let jsonFile = path.join(this.root, 'package.json') - fs.writeFileSync(jsonFile, JSON.stringify(sortedObj, null, 2), { encoding: 'utf8' }) - window.showMessage(`Removed: ${globals.join(' ')}`) - } catch (e) { - window.showMessage(`Uninstall failed: ${e.message}`, 'error') - } - } - - public isDisabled(id: string): boolean { - return this.disabled.has(id) - } - - public has(id: string): boolean { - return this.extensions.has(id) - } - - public isActivated(id: string): boolean { - let item = this.extensions.get(id) - if (item && item.extension.isActive) { - return true - } - return false - } - - /** - * Load extension from folder, folder should contains coc extension. - */ - public async loadExtension(folder: string): Promise { - try { - let parentFolder = path.dirname(folder) - let isLocal = path.normalize(parentFolder) != path.normalize(this.modulesFolder) - let jsonFile = path.join(folder, 'package.json') - let packageJSON = JSON.parse(fs.readFileSync(jsonFile, 'utf8')) - let { name } = packageJSON - if (this.isDisabled(name)) return false - // unload if loaded - await this.unloadExtension(name) - this.createExtension(folder, Object.freeze(packageJSON), isLocal ? ExtensionType.Local : ExtensionType.Global) - return true - } catch (e) { - window.showMessage(`Error on load extension from "${folder}": ${e.message}`, 'error') - logger.error(`Error on load extension from ${folder}`, e) - return false - } - } - - private async loadFileExtensions(): Promise { - if (!process.env.COC_VIMCONFIG) return - let folder = path.join(process.env.COC_VIMCONFIG, 'coc-extensions') - if (!fs.existsSync(folder)) return - let files = await fs.readdir(folder) - files = files.filter(f => f.endsWith('.js')) - for (let file of files) { - await this.loadExtensionFile(path.join(folder, file)) - } - } - - public loadedExtensions(): string[] { - return Array.from(this.extensions.keys()) - } - - public async watchExtension(id: string): Promise { - let item = this.extensions.get(id) - if (!item) { - window.showMessage(`extension ${id} not found`, 'error') - return - } - if (id.startsWith('single-')) { - window.showMessage(`watching ${item.filepath}`) - this.disposables.push(watchFile(item.filepath, async () => { - await this.loadExtensionFile(item.filepath) - window.showMessage(`reloaded ${id}`) - })) - } else { - let watchmanPath = workspace.getWatchmanPath() - if (!watchmanPath) { - window.showMessage('watchman not found', 'error') - return - } - let client = await Watchman.createClient(watchmanPath, item.directory) - if (!client) { - window.showMessage(`Can't create watchman client, check output:///watchman`) - return - } - window.showMessage(`watching ${item.directory}`) - this.disposables.push(client) - client.subscribe('**/*.js', async () => { - await this.reloadExtension(id) - window.showMessage(`reloaded ${id}`) - }).then(disposable => { - this.disposables.push(disposable) - }, e => { - logger.error(e) - }) - } - } - - /** - * Load single javascript file as extension. - */ - public async loadExtensionFile(filepath: string): Promise { - let filename = path.basename(filepath) - let basename = path.basename(filepath, '.js') - let name = 'single-' + basename - if (this.isDisabled(name)) return - let root = path.dirname(filepath) - let packageJSON = { - name, main: filename, engines: { coc: '^0.0.79' } - } - let confpath = path.join(root, basename + '.json') - let stat = await statAsync(confpath) - if (stat && stat.isFile()) { - let content = await readFile(confpath, 'utf8') - let obj = JSON.parse(content) - if (obj) { - let attrs = ['activationEvents', 'contributes'] - for (const attr of attrs) { - if (obj[attr]) { - packageJSON[attr] = obj[attr] - } - } - } - } - await this.unloadExtension(name) - this.createExtension(root, packageJSON, ExtensionType.SingleFile) - } - - /** - * Activate extension, throw error if disabled or not exists - * Returns true if extension successfully activated. - */ - public async activate(id): Promise { - if (this.isDisabled(id)) { - throw new Error(`Extension ${id} is disabled!`) - } - let item = this.extensions.get(id) - if (!item) { - throw new Error(`Extension ${id} not registered!`) - } - let { extension } = item - if (extension.isActive) return true - await Promise.resolve(extension.activate()) - if (extension.isActive) { - this._onDidActiveExtension.fire(extension) - return true - } - return false - } - - public async deactivate(id): Promise { - let item = this.extensions.get(id) - if (!item) return false - await Promise.resolve(item.deactivate()) - return true - } - - public async call(id: string, method: string, args: any[]): Promise { - let item = this.extensions.get(id) - if (!item) throw new Error(`extension ${id} not registered`) - let { extension } = item - if (!extension.isActive) { - await this.activate(id) - } - let { exports } = extension - if (!exports || !exports.hasOwnProperty(method)) { - throw new Error(`method ${method} not found on extension ${id}`) - } - return await Promise.resolve(exports[method].apply(null, args)) - } - - public getExtensionApi(id: string): API | null { - let item = this.extensions.get(id) - if (!item) return null - let { extension } = item - return extension.isActive ? extension.exports : null - } - - public registerExtension(extension: Extension, deactivate?: () => void): void { - let { id, packageJSON } = extension - this.extensions.set(id, { id, type: ExtensionType.Internal, extension, deactivate, isLocal: true }) - let { contributes } = packageJSON - if (contributes) { - let { configuration } = contributes - if (configuration && configuration.properties) { - let { properties } = configuration - let props = {} - for (let key of Object.keys(properties)) { - let val = properties[key].default - if (val != null) props[key] = val - } - workspace.configurations.extendsDefaults(props) - } - } - this._onDidLoadExtension.fire(extension) - this.setupActiveEvents(id, packageJSON).logError() - } - - public get globalExtensions(): string[] { - let json = this.loadJson() - if (!json || !json.dependencies) return [] - return Object.keys(json.dependencies) - } - - private async globalExtensionStats(): Promise { - let json = this.loadJson() - if (!json || !json.dependencies) return [] - let { modulesFolder } = this - let res: ExtensionInfo[] = await Promise.all(Object.keys(json.dependencies).map(key => new Promise(async resolve => { - try { - let val = json.dependencies[key] - let root = path.join(modulesFolder, key) - let res = this.checkDirectory(root) - if (res instanceof Error) { - window.showMessage(`Unable to load global extension at ${root}: ${res.message}`, 'error') - logger.error(`Error on load ${root}`, res) - return resolve(null) - } - let content = await readFile(path.join(root, 'package.json'), 'utf8') - root = await fs.realpath(root) - let obj = JSON.parse(content) - let version = obj ? obj.version || '' : '' - let description = obj ? obj.description || '' : '' - let uri = isuri.isValid(val) ? val : '' - resolve({ - id: key, - isLocal: false, - version, - description, - exotic: /^https?:/.test(val), - uri: uri.replace(/\.git(#master)?$/, ''), - root, - state: this.getExtensionState(key), - packageJSON: Object.freeze(obj) - }) - } catch (e) { - logger.error(e) - resolve(null) - } - }))) - return res.filter(info => info != null) - } - - private async localExtensionStats(excludes: string[]): Promise { - let runtimepath = await workspace.nvim.eval('&runtimepath') as string - let paths = runtimepath.split(',') - let res: ExtensionInfo[] = await Promise.all(paths.map(root => new Promise(async resolve => { - try { - let res = this.checkDirectory(root) - if (res !== true) return resolve(null) - let jsonFile = path.join(root, 'package.json') - let content = await readFile(jsonFile, 'utf8') - let obj = JSON.parse(content) - let exist = this.extensions.get(obj.name) - if (exist && !exist.isLocal) { - logger.info(`Extension "${obj.name}" in runtimepath already loaded.`) - return resolve(null) - } - if (excludes.includes(obj.name)) { - logger.info(`Skipped load vim plugin from "${root}", "${obj.name}" already global extension.`) - return resolve(null) - } - let version = obj ? obj.version || '' : '' - let description = obj ? obj.description || '' : '' - resolve({ - id: obj.name, - isLocal: true, - version, - description, - exotic: false, - root, - state: this.getExtensionState(obj.name), - packageJSON: Object.freeze(obj) - }) - } catch (e) { - logger.error(e) - resolve(null) - } - }))) - return res.filter(info => info != null) - } - - private loadJson(): any { - let { root } = this - let jsonFile = path.join(root, 'package.json') - if (!fs.existsSync(jsonFile)) return null - let errors: ParseError[] = [] - let content = fs.readFileSync(jsonFile, 'utf8') - let data = parse(content, errors, { allowTrailingComma: true }) - if (errors && errors.length > 0) { - window.showMessage(`Error on parse ${jsonFile}`, 'error') - workspace.nvim.call('coc#util#open_file', ['edit', jsonFile], true) - } - return data - } - - public get schemes(): { [key: string]: PropertyScheme } { - return this._additionalSchemes - } - - public addSchemeProperty(key: string, def: PropertyScheme): void { - this._additionalSchemes[key] = def - workspace.configurations.extendsDefaults({ [key]: def.default }) - } - - private async setupActiveEvents(id: string, packageJSON: any): Promise { - let { activationEvents } = packageJSON - if (!this.canActivate(id)) return - if (!activationEvents || Array.isArray(activationEvents) && activationEvents.includes('*')) { - await this.activate(id).catch(e => { - window.showMessage(`Error on activate extension ${id}: ${e.message}`) - this.outputChannel.appendLine(`Error on activate extension ${id}.\n${e.message}\n ${e.stack}`) - }) - return - } - let disposables: Disposable[] = [] - let active = (): Promise => { - disposeAll(disposables) - return new Promise(resolve => { - if (!this.canActivate(id)) { - this.outputChannel.appendLine(`Extension ${id} is disabled or not loaded.`) - return resolve() - } - let timer = setTimeout(() => { - this.outputChannel.appendLine(`Extension ${id} activate cost more than 1s`) - resolve() - }, 1000) - this.activate(id).then(() => { - clearTimeout(timer) - resolve() - }, e => { - clearTimeout(timer) - window.showMessage(`Error on activate extension ${id}: ${e.message}`) - this.outputChannel.appendLine(`Error on activate extension ${id}:${e.message}\n ${e.stack}`) - resolve() - }) - }) - } - - for (let eventName of activationEvents as string[]) { - let parts = eventName.split(':') - let ev = parts[0] - if (ev == 'onLanguage') { - if (workspace.filetypes.has(parts[1])) { - await active() - return - } - workspace.onDidOpenTextDocument(document => { - if (document.languageId == parts[1]) { - void active() - } - }, null, disposables) - } else if (ev == 'onCommand') { - commandManager.onCommandList.push(parts[1]) - events.on('Command', async command => { - if (command == parts[1]) { - await active() - await wait(500) - } - }, null, disposables) - } else if (ev == 'workspaceContains') { - let check = async () => { - let folders = workspace.workspaceFolders.map(o => URI.parse(o.uri).fsPath) - for (let folder of folders) { - if (inDirectory(folder, parts[1].split(/\s+/))) { - await active() - return true - } - } - } - let res = await check() - if (res) return - workspace.onDidChangeWorkspaceFolders(check, null, disposables) - } else if (ev == 'onFileSystem') { - for (let doc of workspace.documents) { - let u = URI.parse(doc.uri) - if (u.scheme == parts[1]) { - await active() - return - } - } - workspace.onDidOpenTextDocument(document => { - let u = URI.parse(document.uri) - if (u.scheme == parts[1]) { - void active() - } - }, null, disposables) - } else { - window.showMessage(`Unsupported event ${eventName} of ${id}`, 'error') - } - } - } - - private createExtension(root: string, packageJSON: any, type: ExtensionType): void { - let id = packageJSON.name - let isActive = false - let result: Promise | undefined - let filename = path.join(root, packageJSON.main || 'index.js') - let ext: ExtensionExport - let subscriptions: Disposable[] = [] - let exports: any - let extension: any = { - activate: (): Promise => { - if (result) return result - let context = { - subscriptions, - extensionPath: root, - globalState: this.memos.createMemento(`${id}|global`), - workspaceState: this.memos.createMemento(`${id}|${workspace.rootPath}`), - asAbsolutePath: relativePath => path.join(root, relativePath), - storagePath: path.join(this.root, `${id}-data`), - logger: createLogger(id) - } - if (!ext) { - try { - let isEmpty = !(packageJSON.engines || {}).hasOwnProperty('coc') - ext = createExtension(id, filename, isEmpty) - } catch (e) { - logger.error(`Error on createExtension ${id} from ${filename}`, e) - return - } - } - result = new Promise((resolve, reject) => { - try { - Promise.resolve(ext.activate(context)).then(res => { - isActive = true - exports = res - resolve(res) - }, e => { - logger.error(`Error on active extension ${id}: ${e.message}`, e) - reject(e) - }) - } catch (e) { - logger.error(`Error on active extension ${id}: ${e.stack}`, e) - reject(e) - } - }) - return result - } - } - Object.defineProperties(extension, { - id: { - get: () => id, - enumerable: true - }, - packageJSON: { - get: () => packageJSON, - enumerable: true - }, - extensionPath: { - get: () => root, - enumerable: true - }, - isActive: { - get: () => isActive, - enumerable: true - }, - exports: { - get: () => { - if (!isActive) throw new Error(`Invalid access to exports, extension "${id}" not activated`) - return exports - }, - enumerable: true - } - }) - - this.extensions.set(id, { - id, - type, - isLocal: type == ExtensionType.Local, - extension, - directory: root, - filepath: filename, - deactivate: () => { - if (!isActive) return - result = undefined - exports = undefined - isActive = false - disposeAll(subscriptions) - subscriptions.splice(0, subscriptions.length) - subscriptions = [] - if (ext && ext.deactivate) { - try { - return Promise.resolve(ext.deactivate()).catch(e => { - logger.error(`Error on ${id} deactivate: `, e) - }) - } catch (e) { - logger.error(`Error on ${id} deactivate: `, e) - } - } - } - }) - let { contributes } = packageJSON - if (contributes) { - let { configuration, rootPatterns, commands } = contributes - if (configuration && configuration.properties) { - let { properties } = configuration - let props = {} - for (let key of Object.keys(properties)) { - let val = properties[key].default - if (val != null) props[key] = val - } - workspace.configurations.extendsDefaults(props) - } - if (rootPatterns && rootPatterns.length) { - for (let item of rootPatterns) { - workspace.addRootPattern(item.filetype, item.patterns) - } - } - if (commands && commands.length) { - for (let cmd of commands) { - commandManager.titles.set(cmd.command, cmd.title) - } - } - } - this._onDidLoadExtension.fire(extension) - if (this.activated) { - this.setupActiveEvents(id, packageJSON).logError() - } - } - - /** - * Filter out global extensions that needs install - */ - public filterGlobalExtensions(names: string[]): string[] { - let map: Map = new Map() - names.forEach(def => { - let name = this.getExtensionName(def) - if (name) map.set(name, def) - }) - let json = this.loadJson() - let urls: string[] = [] - let exists: string[] = [] - if (json && json.dependencies) { - for (let key of Object.keys(json.dependencies)) { - let val = json.dependencies[key] - if (typeof val !== 'string') continue - if (fs.existsSync(path.join(this.modulesFolder, key, 'package.json'))) { - exists.push(key) - if (/^https?:/.test(val)) { - urls.push(val) - } - } - } - } - for (let name of map.keys()) { - if (this.disabled.has(name) || this.extensions.has(name)) { - map.delete(name) - continue - } - if ((/^https?:/.test(name) && urls.some(url => url.startsWith(name))) - || exists.includes(name)) { - map.delete(name) - } - } - return Array.from(map.values()) - } - - /** - * Name of extension - */ - private getExtensionName(def: string): string { - if (/^https?:/.test(def)) return def - if (!def.includes('@')) return def - return def.replace(/@[\d.]+$/, '') - } - - private get modulesFolder(): string { - return path.join(this.root, global.hasOwnProperty('__TEST__') ? '' : 'node_modules') - } - - private canActivate(id: string): boolean { - return !this.disabled.has(id) && this.extensions.has(id) - } - - /** - * Deactive & unregist extension - */ - private async unloadExtension(id: string): Promise { - let item = this.extensions.get(id) - if (item) { - await this.deactivate(id) - this.extensions.delete(id) - this._onDidUnloadExtension.fire(id) - } - } - - /** - * Check if folder contains extension, return Error - */ - private checkDirectory(folder: string): boolean | Error { - try { - let jsonFile = path.join(folder, 'package.json') - if (!fs.existsSync(jsonFile)) throw new Error('package.json not found') - let packageJSON = JSON.parse(fs.readFileSync(jsonFile, 'utf8')) - let { name, engines, main } = packageJSON - if (!name || !engines) throw new Error(`can't find name & engines in package.json`) - if (!engines || !objectLiteral(engines)) { - throw new Error(`invalid engines in ${jsonFile}`) - } - if (main && !fs.existsSync(path.join(folder, main))) { - throw new Error(`main file ${main} not found, you may need to build the project.`) - } - let keys = Object.keys(engines) - if (!keys.includes('coc') && !keys.includes('vscode')) { - throw new Error(`Engines in package.json doesn't have coc or vscode`) - } - if (keys.includes('coc')) { - let required = engines['coc'].replace(/^\^/, '>=') - if (!semver.satisfies(workspace.version, required)) { - throw new Error(`Please update coc.nvim, ${packageJSON.name} requires coc.nvim ${engines['coc']}`) - } - } - return true - } catch (e) { - return e - } - } - - public dispose(): void { - disposeAll(this.disposables) - } -} - -export default new Extensions() diff --git a/vim-config/plugins/coc.nvim/src/handler/callHierarchy.ts b/vim-config/plugins/coc.nvim/src/handler/callHierarchy.ts deleted file mode 100644 index 80c4ba4c..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/callHierarchy.ts +++ /dev/null @@ -1,257 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import path from 'path' -import { CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, CancellationToken, CancellationTokenSource, Disposable, Emitter, Position, Range, SymbolTag } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { URI } from 'vscode-uri' -import commands from '../commands' -import events from '../events' -import languages from '../languages' -import { TreeDataProvider, TreeItem, TreeItemCollapsibleState } from '../tree/index' -import BasicTreeView from '../tree/TreeView' -import { ConfigurationChangeEvent, HandlerDelegate } from '../types' -import { disposeAll } from '../util' -import { omit } from '../util/lodash' -import workspace from '../workspace' -const logger = require('../util/logger')('Handler-callHierarchy') - -interface CallHierarchyDataItem extends CallHierarchyItem { - ranges?: Range[] - sourceUri?: string - children?: CallHierarchyItem[] -} - -interface CallHierarchyConfig { - splitCommand: string - openCommand: string - enableTooltip: boolean -} - -interface CallHierarchyProvider extends TreeDataProvider { - kind: 'incoming' | 'outgoing' - dispose: () => void -} - -function isCallHierarchyItem(item: any): item is CallHierarchyItem { - if (item && item.name && item.kind && Range.is(item.range) && item.uri) return true - return false -} - -export default class CallHierarchyHandler { - private config: CallHierarchyConfig - private disposables: Disposable[] = [] - public static commandId = 'callHierarchy.reveal' - public static rangesHighlight = 'CocSelectedRange' - private highlightWinids: Set = new Set() - constructor(private nvim: Neovim, private handler: HandlerDelegate) { - this.loadConfiguration() - workspace.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables) - this.disposables.push(commands.registerCommand(CallHierarchyHandler.commandId, async (winid: number, item: CallHierarchyDataItem, openCommand?: string) => { - let { nvim } = this - await nvim.call('win_gotoid', [winid]) - await workspace.jumpTo(item.uri, item.selectionRange.start, openCommand) - let win = await nvim.window - win.clearMatchGroup(CallHierarchyHandler.rangesHighlight) - win.highlightRanges(CallHierarchyHandler.rangesHighlight, [item.selectionRange], 10, true) - if (!item.ranges?.length) return - if (item.sourceUri) { - let doc = workspace.getDocument(item.sourceUri) - if (!doc) return - let winid = await nvim.call('coc#compat#buf_win_id', [doc.bufnr]) - if (winid == -1) return - if (winid != win.id) { - win = nvim.createWindow(winid) - win.clearMatchGroup(CallHierarchyHandler.rangesHighlight) - } - } - win.highlightRanges(CallHierarchyHandler.rangesHighlight, item.ranges, 100, true) - this.highlightWinids.add(win.id) - }, null, true)) - events.on('BufWinEnter', (_, winid) => { - if (this.highlightWinids.has(winid)) { - this.highlightWinids.delete(winid) - let win = nvim.createWindow(winid) - win.clearMatchGroup(CallHierarchyHandler.rangesHighlight) - } - }, null, this.disposables) - } - - private loadConfiguration(e?: ConfigurationChangeEvent): void { - if (!e || e.affectsConfiguration('callHierarchy')) { - let c = workspace.getConfiguration('callHierarchy') - this.config = { - splitCommand: c.get('splitCommand'), - openCommand: c.get('openCommand'), - enableTooltip: c.get('enableTooltip') - } - } - } - - private createProvider(doc: TextDocument, winid: number, position: Position, kind: 'incoming' | 'outgoing'): CallHierarchyProvider { - let _onDidChangeTreeData = new Emitter() - let source: CancellationTokenSource | undefined - let rootItems: CallHierarchyDataItem[] | undefined - const cancel = () => { - if (source) { - source.cancel() - source.dispose() - source = null - } - } - const findParent = (curr: CallHierarchyDataItem, element: CallHierarchyDataItem): CallHierarchyDataItem | undefined => { - let children = curr.children - if (!Array.isArray(children)) return undefined - let find = children.find(o => o == element) - if (find) return curr - for (let item of children) { - let res = findParent(item, element) - if (res) return res - } - } - let provider: CallHierarchyProvider = { - kind, - onDidChangeTreeData: _onDidChangeTreeData.event, - getTreeItem: element => { - let item = new TreeItem(element.name, element.children ? TreeItemCollapsibleState.Expanded : TreeItemCollapsibleState.Collapsed) - if (this.config.enableTooltip) { - item.tooltip = path.relative(workspace.cwd, URI.parse(element.uri).fsPath) - } - item.description = element.detail - item.deprecated = element.tags?.includes(SymbolTag.Deprecated) - item.icon = this.handler.getIcon(element.kind) - item.command = { - command: CallHierarchyHandler.commandId, - title: 'open location', - arguments: [winid, element, this.config.openCommand] - } - return item - }, - getChildren: async element => { - cancel() - source = new CancellationTokenSource() - let { token } = source - if (!element) { - if (!rootItems) { - rootItems = await this.prepare(doc, position, token) as CallHierarchyDataItem[] - if (!rootItems?.length) return - } - for (let o of rootItems) { - let children = await this.getChildren(doc, o, provider.kind, token) - if (token.isCancellationRequested) break - if (Array.isArray(children)) o.children = children - } - return rootItems - } - if (element.children) return element.children - let items = await this.getChildren(doc, element, provider.kind, token) - source = null - if (token.isCancellationRequested) return [] - element.children = items - return items - }, - resolveActions: () => { - return [{ - title: 'Open in new tab', - handler: async element => { - await commands.executeCommand(CallHierarchyHandler.commandId, winid, element, 'tabe') - } - }, { - title: 'Show Incoming Calls', - handler: element => { - rootItems = [omit(element, ['children', 'ranges', 'sourceUri'])] - provider.kind = 'incoming' - _onDidChangeTreeData.fire(undefined) - } - }, { - title: 'Show Outgoing Calls', - handler: element => { - rootItems = [omit(element, ['children', 'ranges', 'sourceUri'])] - provider.kind = 'outgoing' - _onDidChangeTreeData.fire(undefined) - } - }, { - title: 'Dismiss', - handler: async element => { - let parentElement: CallHierarchyDataItem | undefined - for (let curr of rootItems) { - parentElement = findParent(curr, element) - if (parentElement) break - } - if (!parentElement) return - let idx = parentElement.children.findIndex(o => o === element) - parentElement.children.splice(idx, 1) - _onDidChangeTreeData.fire(parentElement) - } - }] - }, - dispose: () => { - cancel() - _onDidChangeTreeData.dispose() - rootItems = undefined - _onDidChangeTreeData = undefined - } - } - return provider - } - - private async getChildren(doc: TextDocument, item: CallHierarchyItem, kind: 'incoming' | 'outgoing', token: CancellationToken): Promise { - let items: CallHierarchyDataItem[] = [] - if (kind == 'incoming') { - let res = await languages.provideIncomingCalls(doc, item, token) - if (res) items = res.map(o => Object.assign(o.from, { ranges: o.fromRanges })) - } else { - let res = await languages.provideOutgoingCalls(doc, item, token) - if (res) items = res.map(o => Object.assign(o.to, { ranges: o.fromRanges, sourceUri: item.uri })) - } - return items - } - - private async prepare(doc: TextDocument, position: Position, token: CancellationToken): Promise { - this.handler.checkProvier('callHierarchy', doc) - const res = await languages.prepareCallHierarchy(doc, position, token) - return isCallHierarchyItem(res) ? [res] : res - } - - private async getCallHierarchyItems(item: CallHierarchyItem | undefined, kind: 'outgoing'): Promise - private async getCallHierarchyItems(item: CallHierarchyItem | undefined, kind: 'incoming'): Promise - private async getCallHierarchyItems(item: CallHierarchyItem | undefined, kind: 'incoming' | 'outgoing'): Promise { - const { doc, position } = await this.handler.getCurrentState() - const source = new CancellationTokenSource() - if (!item) { - await doc.synchronize() - let res = await this.prepare(doc.textDocument, position, source.token) - item = res ? res[0] : undefined - if (!res) return undefined - } - let method = kind == 'incoming' ? 'provideIncomingCalls' : 'provideOutgoingCalls' - return await languages[method](doc.textDocument, item, source.token) - } - - public async getIncoming(item?: CallHierarchyItem): Promise { - return await this.getCallHierarchyItems(item, 'incoming') - } - - public async getOutgoing(item?: CallHierarchyItem): Promise { - return await this.getCallHierarchyItems(item, 'outgoing') - } - - public async showCallHierarchyTree(kind: 'incoming' | 'outgoing'): Promise { - const { doc, position, winid } = await this.handler.getCurrentState() - await doc.synchronize() - let provider = this.createProvider(doc.textDocument, winid, position, kind) - let treeView = new BasicTreeView('calls', { treeDataProvider: provider }) - treeView.title = `${kind.toUpperCase()} CALLS` - provider.onDidChangeTreeData(e => { - if (!e) treeView.title = `${provider.kind.toUpperCase()} CALLS` - }) - treeView.onDidChangeVisibility(e => { - if (!e.visible) provider.dispose() - }) - this.disposables.push(treeView) - await treeView.show(this.config.splitCommand) - } - - public dispose(): void { - this.highlightWinids.clear() - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/codeActions.ts b/vim-config/plugins/coc.nvim/src/handler/codeActions.ts deleted file mode 100644 index 9fd54cff..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/codeActions.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { NeovimClient as Neovim } from '@chemzqm/neovim' -import diagnosticManager from '../diagnostic/manager' -import { CodeAction, CodeActionContext, Range, CodeActionKind } from 'vscode-languageserver-protocol' -import commandManager from '../commands' -import workspace from '../workspace' -import Document from '../model/document' -import window from '../window' -import { HandlerDelegate } from '../types' -import languages from '../languages' -const logger = require('../util/logger')('handler-codeActions') - -/** - * Handle codeActions related methods. - */ -export default class CodeActions { - constructor( - private nvim: Neovim, - private handler: HandlerDelegate - ) { - handler.addDisposable(commandManager.registerCommand('editor.action.organizeImport', async (bufnr?: number) => { - await this.organizeImport(bufnr) - })) - commandManager.titles.set('editor.action.organizeImport', 'run organize import code action.') - } - - public async codeActionRange(start: number, end: number, only?: string): Promise { - let { doc } = await this.handler.getCurrentState() - await doc.synchronize() - let line = doc.getline(end - 1) - let range = Range.create(start - 1, 0, end - 1, line.length) - let codeActions = await this.getCodeActions(doc, range, only ? [only] : null) - if (!codeActions || codeActions.length == 0) { - window.showMessage(`No${only ? ' ' + only : ''} code action available`, 'warning') - return - } - let idx = await window.showMenuPicker(codeActions.map(o => o.title), 'Choose action') - let action = codeActions[idx] - if (action) await this.applyCodeAction(action) - } - - public async organizeImport(bufnr?: number): Promise { - let { doc } = await this.handler.getCurrentState() - if (bufnr && doc.bufnr != bufnr) return - await doc.synchronize() - let actions = await this.getCodeActions(doc, undefined, [CodeActionKind.SourceOrganizeImports]) - if (actions && actions.length) { - await this.applyCodeAction(actions[0]) - return - } - throw new Error('Organize import action not found.') - } - - public async getCodeActions(doc: Document, range?: Range, only?: CodeActionKind[]): Promise { - range = range || Range.create(0, 0, doc.lineCount, 0) - let diagnostics = diagnosticManager.getDiagnosticsInRange(doc.textDocument, range) - let context: CodeActionContext = { diagnostics } - if (only && Array.isArray(only)) context.only = only - let codeActions = await this.handler.withRequestToken('code action', token => { - return languages.getCodeActions(doc.textDocument, range, context, token) - }) - if (!codeActions || codeActions.length == 0) return [] - // TODO support fadeout disabled actions in menu - codeActions = codeActions.filter(o => !o.disabled) - codeActions.sort((a, b) => { - if (a.isPreferred && !b.isPreferred) return -1 - if (b.isPreferred && !a.isPreferred) return 1 - return 0 - }) - return codeActions - } - - private get floatActions(): boolean { - if (!workspace.floatSupported) return false - let config = workspace.getConfiguration('coc.preferences') - return config.get('floatActions', true) - } - - public async doCodeAction(mode: string | null, only?: CodeActionKind[] | string): Promise { - let { doc } = await this.handler.getCurrentState() - let range: Range - if (mode) range = await workspace.getSelectedRange(mode, doc) - await doc.synchronize() - let codeActions = await this.getCodeActions(doc, range, Array.isArray(only) ? only : null) - if (typeof only == 'string') { - codeActions = codeActions.filter(o => o.title == only || (o.command && o.command.title == only)) - } else if (Array.isArray(only)) { - codeActions = codeActions.filter(o => only.some(k => o.kind && o.kind.startsWith(k))) - } - if (!codeActions || codeActions.length == 0) { - window.showMessage(`No${only ? ' ' + only : ''} code action available`, 'warning') - return - } - if (only && codeActions.length == 1) { - await this.applyCodeAction(codeActions[0]) - return - } - let idx = this.floatActions - ? await window.showMenuPicker( - codeActions.map(o => o.title), - "Choose action" - ) - : await window.showQuickpick(codeActions.map(o => o.title)) - let action = codeActions[idx] - if (action) await this.applyCodeAction(action) - } - - /** - * Get current codeActions - */ - public async getCurrentCodeActions(mode?: string, only?: CodeActionKind[]): Promise { - let { doc } = await this.handler.getCurrentState() - let range: Range - if (mode) range = await workspace.getSelectedRange(mode, doc) - return await this.getCodeActions(doc, range, only) - } - - /** - * Invoke preferred quickfix at current position - */ - public async doQuickfix(): Promise { - let actions = await this.getCurrentCodeActions('line', [CodeActionKind.QuickFix]) - if (!actions || actions.length == 0) { - throw new Error('No quickfix action available') - } - await this.applyCodeAction(actions[0]) - this.nvim.command(`silent! call repeat#set("\\(coc-fix-current)", -1)`, true) - } - - public async applyCodeAction(action: CodeAction): Promise { - if (action.disabled) { - throw new Error(`Action "${action.title}" is disabled: ${action.disabled.reason}`) - } - action = await this.handler.withRequestToken('resolve codeAction', token => { - return languages.resolveCodeAction(action, token) - }) - let { edit, command } = action - if (edit) await workspace.applyEdit(edit) - if (command) await commandManager.execute(command) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/codelens/buffer.ts b/vim-config/plugins/coc.nvim/src/handler/codelens/buffer.ts deleted file mode 100644 index 9caa16e1..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/codelens/buffer.ts +++ /dev/null @@ -1,213 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import debounce from 'debounce' -import { CancellationTokenSource, CodeLens, Command } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import commandManager from '../../commands' -import languages from '../../languages' -import { BufferSyncItem } from '../../types' -import window from '../../window' -import workspace from '../../workspace' -const logger = require('../../util/logger')('codelens-buffer') - -export interface CodeLensInfo { - codeLenses: CodeLens[] - version: number - hasError: boolean -} - -export interface CodeLensConfig { - enabled: boolean - separator: string - subseparator: string -} - -/** - * CodeLens buffer - */ -export default class CodeLensBuffer implements BufferSyncItem { - private codeLenses: CodeLensInfo - private tokenSource: CancellationTokenSource - private resolveTokenSource: CancellationTokenSource - private srcId: number - public fetchCodelenses: (() => void) & { clear(): void } - public resolveCodeLens: (() => void) & { clear(): void } - constructor( - private nvim: Neovim, - public readonly bufnr: number, - private config: CodeLensConfig - ) { - this.fetchCodelenses = debounce(() => { - void this._fetchCodeLenses() - }, 200) - this.resolveCodeLens = debounce(() => { - void this._resolveCodeLenses() - }, 200) - this.fetchCodelenses() - } - - public currentCodeLens(): CodeLens[] { - return this.codeLenses?.codeLenses - } - - private get enabled(): boolean { - return this.textDocument && this.config.enabled && languages.hasProvider('codeLens', this.textDocument) - } - - public async forceFetch(): Promise { - this.fetchCodelenses.clear() - await this._fetchCodeLenses() - } - - private get textDocument(): TextDocument | undefined { - return workspace.getDocument(this.bufnr)?.textDocument - } - - private async _fetchCodeLenses(): Promise { - if (!this.enabled) return - this.cancel() - let noFetch = !this.isChanged && !this.codeLenses?.hasError - if (!noFetch) { - let { textDocument } = this - let version = textDocument.version - let tokenSource = this.tokenSource = new CancellationTokenSource() - let token = tokenSource.token - let codeLenses = await languages.getCodeLens(textDocument, token) - this.tokenSource = undefined - if (token.isCancellationRequested) return - if (!Array.isArray(codeLenses) || codeLenses.length == 0) return - let hasError = codeLenses.some(o => o == null) - this.codeLenses = { version, codeLenses: codeLenses.filter(o => o != null), hasError } - } - let codeLenses = this.codeLenses?.codeLenses - if (codeLenses?.length) { - await this._resolveCodeLenses() - } - } - - /** - * Resolve visible codeLens - */ - private async _resolveCodeLenses(): Promise { - if (!this.enabled || !this.codeLenses || this.isChanged) return - let { codeLenses } = this.codeLenses - let [bufnr, start, end] = await this.nvim.eval(`[bufnr('%'),line('w0'),line('w$')]`) as [number, number, number] - // only resolve current buffer - if (this.isChanged || bufnr != this.bufnr) return - if (this.resolveTokenSource) { - this.resolveTokenSource.cancel() - } - codeLenses = codeLenses.filter(o => { - let lnum = o.range.start.line + 1 - return lnum >= start && lnum <= end - }) - if (codeLenses.length) { - let tokenSource = this.resolveTokenSource = new CancellationTokenSource() - let token = tokenSource.token - await Promise.all(codeLenses.map(codeLens => languages.resolveCodeLens(codeLens, token))) - this.resolveTokenSource = undefined - if (token.isCancellationRequested || this.isChanged) return - } - if (!this.srcId) this.srcId = await this.nvim.createNamespace('coc-codelens') - this.nvim.pauseNotification() - this.clear(start - 1, end) - this.setVirtualText(codeLenses) - await this.nvim.resumeNotification() - } - - private get isChanged(): boolean { - if (!this.textDocument || !this.codeLenses) return true - let { version } = this.codeLenses - return this.textDocument.version !== version - } - - /** - * Attach resolved codeLens - */ - private setVirtualText(codeLenses: CodeLens[]): void { - if (codeLenses.length == 0) return - let list: Map = new Map() - for (let codeLens of codeLenses) { - let { range, command } = codeLens - if (!command) continue - let { line } = range.start - if (list.has(line)) { - list.get(line).push(codeLens) - } else { - list.set(line, [codeLens]) - } - } - for (let lnum of list.keys()) { - let codeLenses = list.get(lnum) - let commands = codeLenses.map(codeLens => codeLens.command) - commands = commands.filter(c => c && c.title) - let chunks = [] - let n_commands = commands.length - for (let i = 0; i < n_commands; i++) { - let c = commands[i] - chunks.push([c.title.replace(/(\r\n|\r|\n|\s)+/g, " "), 'CocCodeLens'] as [string, string]) - if (i != n_commands - 1) { - chunks.push([this.config.subseparator, 'CocCodeLens'] as [string, string]) - } - } - chunks.unshift([`${this.config.separator} `, 'CocCodeLens']) - this.nvim.call('nvim_buf_set_virtual_text', [this.bufnr, this.srcId, lnum, chunks, {}], true) - } - } - - public clear(start = 0, end = -1): void { - if (!this.srcId) return - let buf = this.nvim.createBuffer(this.bufnr) - buf.clearNamespace(this.srcId, start, end) - } - - public cleanUp(): void { - this.clear() - this.codeLenses = undefined - } - - public getCodelenses(): CodeLens[] | undefined { - return this.codeLenses?.codeLenses - } - - public async doAction(line: number): Promise { - let { codeLenses } = this.codeLenses ?? {} - if (!codeLenses?.length) return - let commands: Command[] = [] - for (let codeLens of codeLenses) { - let { range, command } = codeLens - if (!command || !range) continue - if (line == range.start.line) { - commands.push(command) - } - } - if (!commands.length) return - if (commands.length == 1) { - await commandManager.execute(commands[0]) - } else { - let res = await window.showMenuPicker(commands.map(c => c.title)) - if (res == -1) return - await commandManager.execute(commands[res]) - } - } - - private cancel(): void { - this.resolveCodeLens.clear() - this.fetchCodelenses.clear() - if (this.tokenSource) { - this.tokenSource.cancel() - this.tokenSource.dispose() - this.tokenSource = null - } - } - - public onChange(): void { - this.cancel() - this.fetchCodelenses() - } - - public dispose(): void { - this.clear() - this.cancel() - this.codeLenses = undefined - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/codelens/index.ts b/vim-config/plugins/coc.nvim/src/handler/codelens/index.ts deleted file mode 100644 index 0cd6f5c5..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/codelens/index.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { NeovimClient as Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import events from '../../events' -import BufferSync from '../../model/bufferSync' -import { ConfigurationChangeEvent } from '../../types' -import { disposeAll } from '../../util' -import workspace from '../../workspace' -import CodeLensBuffer, { CodeLensConfig } from './buffer' -const logger = require('../../util/logger')('codelens') - -/** - * Show codeLens of document, works on neovim only. - */ -export default class CodeLensManager { - private config: CodeLensConfig - private disposables: Disposable[] = [] - public buffers: BufferSync - constructor(private nvim: Neovim) { - this.setConfiguration() - // need neovim to work - if (!workspace.isNvim) return - workspace.onDidChangeConfiguration(e => { - this.setConfiguration(e) - }) - this.buffers = workspace.registerBufferSync(doc => { - if (doc.buftype != '') return undefined - return new CodeLensBuffer(nvim, doc.bufnr, this.config) - }) - this.listen() - } - - private listen(): void { - events.on('CursorMoved', bufnr => { - let buf = this.buffers.getItem(bufnr) - if (buf) buf.resolveCodeLens() - }, null, this.disposables) - // Refresh on CursorHold - events.on('CursorHold', async bufnr => { - let buf = this.buffers.getItem(bufnr) - if (buf) await buf.forceFetch() - }, this, this.disposables) - } - - /** - * Check provider for buf that not fetched - */ - public async checkProvider(): Promise { - for (let buf of this.buffers.items) { - await buf.forceFetch() - } - } - - private setConfiguration(e?: ConfigurationChangeEvent): void { - if (e && !e.affectsConfiguration('codeLens')) return - let config = workspace.getConfiguration('codeLens') - let enable: boolean = this.nvim.hasFunction('nvim_buf_set_virtual_text') && config.get('enable', false) - if (e && enable != this.config.enabled) { - if (enable) { - this.listen() - } else { - disposeAll(this.disposables) - } - for (let buf of this.buffers.items) { - if (enable) { - buf.fetchCodelenses() - } else { - buf.cleanUp() - } - } - } - this.config = Object.assign(this.config || {}, { - enabled: enable, - separator: config.get('separator', 'โ€ฃ'), - subseparator: config.get('subseparator', ' ') - }) - } - - public async doAction(): Promise { - let [bufnr, line] = await this.nvim.eval(`[bufnr("%"),line(".")-1]`) as [number, number] - let buf = this.buffers.getItem(bufnr) - await buf?.doAction(line) - } - - public dispose(): void { - this.buffers.dispose() - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/colors/colorBuffer.ts b/vim-config/plugins/coc.nvim/src/handler/colors/colorBuffer.ts deleted file mode 100644 index b6880103..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/colors/colorBuffer.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import debounce from 'debounce' -import { CancellationToken, CancellationTokenSource, Color, ColorInformation, Position, Range } from 'vscode-languageserver-protocol' -import languages from '../../languages' -import { SyncItem } from '../../model/bufferSync' -import { group } from '../../util/array' -import { equals } from '../../util/object' -import { positionInRange } from '../../util/position' -import { isDark, toHexColor, toHexString } from '../../util/color' -import workspace from '../../workspace' -const logger = require('../../util/logger')('colors-buffer') - -export interface ColorRanges { - color: Color - ranges: Range[] -} - -export default class ColorBuffer implements SyncItem { - private _colors: ColorInformation[] = [] - private tokenSource: CancellationTokenSource - private version: number - public highlight: Function & { clear(): void } - // last highlight version - constructor( - private nvim: Neovim, - private bufnr: number, - private enabled: boolean, - private usedColors: Set) { - this.highlight = debounce(() => { - void this.doHighlight() - }, global.hasOwnProperty('__TEST__') ? 10 : 500) - } - - public onChange(): void { - this.cancel() - this.highlight() - } - - public get buffer(): Buffer { - return this.nvim.createBuffer(this.bufnr) - } - - public get colors(): ColorInformation[] { - return this._colors - } - - public hasColor(): boolean { - return this._colors.length > 0 - } - - public setState(enabled: boolean): void { - this.enabled = enabled - if (enabled) { - this.highlight() - } else { - this.clearHighlight() - } - } - - public async doHighlight(): Promise { - let doc = workspace.getDocument(this.bufnr) - if (!doc || !this.enabled) return - try { - this.tokenSource = new CancellationTokenSource() - let { token } = this.tokenSource - if (this.version && doc.version == this.version) return - let { version } = doc - let colors: ColorInformation[] - colors = await languages.provideDocumentColors(doc.textDocument, token) - colors = colors || [] - if (token.isCancellationRequested) return - this.version = version - await this.addHighlight(colors) - } catch (e) { - logger.error('Error on highlight:', e) - } - } - - private async addHighlight(colors: ColorInformation[]): Promise { - colors = colors || [] - if (equals(this._colors, colors)) return - let { nvim } = this - this._colors = colors - // improve performance - let groups = group(colors, 100) - nvim.pauseNotification() - this.buffer.clearNamespace('color') - this.defineColors(colors) - void nvim.resumeNotification(false, true) - for (let colors of groups) { - nvim.pauseNotification() - let colorRanges = this.getColorRanges(colors) - for (let o of colorRanges) { - this.highlightColor(o.ranges, o.color) - } - void nvim.resumeNotification(false, true) - } - if (workspace.isVim) this.nvim.command('redraw', true) - } - - private highlightColor(ranges: Range[], color: Color): void { - let hlGroup = `BG${toHexString(color)}` - this.buffer.highlightRanges('color', hlGroup, ranges) - } - - private defineColors(colors: ColorInformation[]): void { - for (let color of colors) { - let hex = toHexString(color.color) - if (!this.usedColors.has(hex)) { - this.nvim.command(`hi BG${hex} guibg=#${hex} guifg=#${isDark(color.color) ? 'ffffff' : '000000'}`, true) - this.usedColors.add(hex) - } - } - } - - private getColorRanges(infos: ColorInformation[]): ColorRanges[] { - let res: ColorRanges[] = [] - for (let info of infos) { - let { color, range } = info - let idx = res.findIndex(o => equals(toHexColor(o.color), toHexColor(color))) - if (idx == -1) { - res.push({ - color, - ranges: [range] - }) - } else { - let r = res[idx] - r.ranges.push(range) - } - } - return res - } - - public clearHighlight(): void { - this.highlight.clear() - this._colors = [] - this.version = null - this.buffer.clearNamespace('color') - } - - public hasColorAtPosition(position: Position): boolean { - let { colors } = this - return colors.some(o => positionInRange(position, o.range) == 0) - } - - public cancel(): void { - if (this.tokenSource) { - this.tokenSource.cancel() - this.tokenSource = null - } - } - - public dispose(): void { - this.highlight.clear() - this.cancel() - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/colors/index.ts b/vim-config/plugins/coc.nvim/src/handler/colors/index.ts deleted file mode 100644 index 997e77db..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/colors/index.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationTokenSource, ColorInformation, Disposable, Position } from 'vscode-languageserver-protocol' -import commandManager from '../../commands' -import extensions from '../../extensions' -import languages from '../../languages' -import BufferSync from '../../model/bufferSync' -import { HandlerDelegate } from '../../types' -import { disposeAll } from '../../util' -import { toHexString } from '../../util/color' -import window from '../../window' -import workspace from '../../workspace' -import ColorBuffer from './colorBuffer' -const logger = require('../../util/logger')('colors-index') - -export default class Colors { - private _enabled = true - private disposables: Disposable[] = [] - private highlighters: BufferSync - - constructor(private nvim: Neovim, private handler: HandlerDelegate) { - let config = workspace.getConfiguration('coc.preferences') - this._enabled = config.get('colorSupport', true) - let usedColors: Set = new Set() - this.highlighters = workspace.registerBufferSync(doc => { - let buf = new ColorBuffer(this.nvim, doc.bufnr, this._enabled, usedColors) - buf.highlight() - return buf - }) - extensions.onDidActiveExtension(() => { - this.highlightAll() - }, null, this.disposables) - workspace.onDidChangeConfiguration(async e => { - if (e.affectsConfiguration('coc.preferences.colorSupport')) { - let config = workspace.getConfiguration('coc.preferences') - let enabled = config.get('colorSupport', true) - this._enabled = enabled - for (let buf of this.highlighters.items) { - buf.setState(enabled) - } - } - }, null, this.disposables) - this.disposables.push(commandManager.registerCommand('editor.action.pickColor', () => { - return this.pickColor() - })) - commandManager.titles.set('editor.action.pickColor', 'pick color from system color picker when possible.') - this.disposables.push(commandManager.registerCommand('editor.action.colorPresentation', () => { - return this.pickPresentation() - })) - commandManager.titles.set('editor.action.colorPresentation', 'change color presentation.') - } - - public async pickPresentation(): Promise { - let { doc } = await this.handler.getCurrentState() - this.handler.checkProvier('documentColor', doc.textDocument) - let info = await this.getColorInformation(doc.bufnr) - if (!info) return window.showMessage('Color not found at current position', 'warning') - let document = await workspace.document - let tokenSource = new CancellationTokenSource() - let presentations = await languages.provideColorPresentations(info, document.textDocument, tokenSource.token) - if (!presentations?.length) return - let res = await window.showMenuPicker(presentations.map(o => o.label), 'choose color:') - if (res == -1) return - let presentation = presentations[res] - let { textEdit, additionalTextEdits, label } = presentation - if (!textEdit) textEdit = { range: info.range, newText: label } - await document.applyEdits([textEdit]) - if (additionalTextEdits) { - await document.applyEdits(additionalTextEdits) - } - } - - public async pickColor(): Promise { - let { doc } = await this.handler.getCurrentState() - this.handler.checkProvier('documentColor', doc.textDocument) - let info = await this.getColorInformation(doc.bufnr) - if (!info) return window.showMessage('Color not found at current position', 'warning') - let { color } = info - let colorArr = [(color.red * 255).toFixed(0), (color.green * 255).toFixed(0), (color.blue * 255).toFixed(0)] - let res = await this.nvim.call('coc#util#pick_color', [colorArr]) - if (!res) return - let hex = toHexString({ - red: (res[0] / 65535), - green: (res[1] / 65535), - blue: (res[2] / 65535), - alpha: 1 - }) - let document = await workspace.document - await document.applyEdits([{ - range: info.range, - newText: `#${hex}` - }]) - } - - public get enabled(): boolean { - return this._enabled - } - - public clearHighlight(bufnr: number): void { - let highlighter = this.highlighters.getItem(bufnr) - if (!highlighter) return - highlighter.clearHighlight() - } - - public hasColor(bufnr: number): boolean { - let highlighter = this.highlighters.getItem(bufnr) - if (!highlighter) return false - return highlighter.hasColor() - } - - public hasColorAtPosition(bufnr: number, position: Position): boolean { - let highlighter = this.highlighters.getItem(bufnr) - if (!highlighter) return false - return highlighter.hasColorAtPosition(position) - } - - public highlightAll(): void { - for (let buf of this.highlighters.items) { - buf.highlight() - } - } - - public async doHighlight(bufnr: number): Promise { - let highlighter = this.highlighters.getItem(bufnr) - if (highlighter) await highlighter.doHighlight() - } - - public async getColorInformation(bufnr: number): Promise { - let highlighter = this.highlighters.getItem(bufnr) - if (!highlighter) return null - let position = await window.getCursorPosition() - for (let info of highlighter.colors) { - let { range } = info - let { start, end } = range - if (position.line == start.line - && position.character >= start.character - && position.character <= end.character) { - return info - } - } - return null - } - - public dispose(): void { - this.highlighters.dispose() - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/commands.ts b/vim-config/plugins/coc.nvim/src/handler/commands.ts deleted file mode 100644 index 467957a1..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/commands.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import commandManager from '../commands' -import events from '../events' -import { Env } from '../types' -import listManager from '../list/manager' -const logger = require('../util/logger')('handler-commands') -const isVim = process.env.VIM_NODE_RPC == '1' - -interface CommandItem { - id: string - title: string -} - -export default class Commands { - constructor(private nvim: Neovim, private env: Readonly) { - for (let item of env.vimCommands) { - this.addVimCommand(item) - } - } - - public addVimCommand(cmd: { id: string; cmd: string; title?: string }): void { - let id = `vim.${cmd.id}` - commandManager.registerCommand(id, () => { - this.nvim.command(cmd.cmd, true) - if (isVim) this.nvim.command('redraw', true) - }) - if (cmd.title) commandManager.titles.set(id, cmd.title) - } - - public getCommandList(): string[] { - return commandManager.commandList.map(o => o.id) - } - - public async repeat(): Promise { - await commandManager.repeatCommand() - } - - public async runCommand(id?: string, ...args: any[]): Promise { - if (id) { - // needed to load onCommand extensions - await events.fire('Command', [id]) - let res = await commandManager.executeCommand(id, ...args) - if (args.length == 0) { - await commandManager.addRecent(id) - } - return res - } else { - await listManager.start(['commands']) - } - } - - public getCommands(): CommandItem[] { - let list = commandManager.commandList - let res: CommandItem[] = [] - let { titles } = commandManager - for (let item of list) { - res.push({ - id: item.id, - title: titles.get(item.id) || '' - }) - } - return res - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/fold.ts b/vim-config/plugins/coc.nvim/src/handler/fold.ts deleted file mode 100644 index 3b955a6c..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/fold.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationTokenSource, Range, WorkspaceEdit } from 'vscode-languageserver-protocol' -import languages from '../languages' -import { HandlerDelegate } from '../types' -import workspace from '../workspace' - -export default class FoldHandler { - constructor(private nvim: Neovim, private handler: HandlerDelegate) { - } - - public async fold(kind?: string | 'comment' | 'region'): Promise { - let { doc, winid } = await this.handler.getCurrentState() - this.handler.checkProvier('foldingRange', doc.textDocument) - await doc.synchronize() - let win = this.nvim.createWindow(winid) - let foldlevel = await this.nvim.eval('&foldlevel') as number - let ranges = await this.handler.withRequestToken('foldingrange', token => { - return languages.provideFoldingRanges(doc.textDocument, {}, token) - }, true) - if (!ranges || !ranges.length) return false - if (kind) ranges = ranges.filter(o => o.kind == kind) - ranges.sort((a, b) => b.startLine - a.startLine) - this.nvim.pauseNotification() - win.setOption('foldmethod', 'manual', true) - this.nvim.command('normal! zE', true) - for (let range of ranges) { - let { startLine, endLine } = range - let cmd = `${startLine + 1}, ${endLine + 1}fold` - this.nvim.command(cmd, true) - } - win.setOption('foldenable', true, true) - win.setOption('foldlevel', foldlevel, true) - if (workspace.isVim) this.nvim.command('redraw', true) - await this.nvim.resumeNotification() - return true - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/format.ts b/vim-config/plugins/coc.nvim/src/handler/format.ts deleted file mode 100644 index bad33af2..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/format.ts +++ /dev/null @@ -1,228 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationTokenSource, Position, Range, TextEdit } from 'vscode-languageserver-protocol' -import events from '../events' -import languages from '../languages' -import Document from '../model/document' -import snippetManager from '../snippets/manager' -import { ConfigurationChangeEvent, HandlerDelegate } from '../types' -import { getChangedFromEdits } from '../util/position' -import { isWord } from '../util/string' -import window from '../window' -import workspace from '../workspace' -const logger = require('../util/logger')('handler-format') - -const pairs: Map = new Map([ - ['<', '>'], - ['>', '<'], - ['{', '}'], - ['[', ']'], - ['(', ')'], -]) - -interface FormatPreferences { - formatOnType: boolean - formatOnTypeFiletypes: string[] - formatOnSaveFiletypes: string[] - bracketEnterImprove: boolean -} - -export default class FormatHandler { - private preferences: FormatPreferences - constructor( - private nvim: Neovim, - private handler: HandlerDelegate - ) { - this.loadPreferences() - handler.addDisposable(workspace.onDidChangeConfiguration(this.loadPreferences, this)) - handler.addDisposable(workspace.onWillSaveTextDocument(event => { - let { languageId } = event.document - let filetypes = this.preferences.formatOnSaveFiletypes - if (filetypes.includes(languageId) || filetypes.includes('*')) { - let willSaveWaitUntil = async (): Promise => { - if (!languages.hasFormatProvider(event.document)) { - logger.warn(`Format provider not found for ${event.document.uri}`) - return undefined - } - let options = await workspace.getFormatOptions(event.document.uri) - let tokenSource = new CancellationTokenSource() - let timer = setTimeout(() => { - logger.warn(`Format on save ${event.document.uri} timeout after 0.5s`) - tokenSource.cancel() - }, 500) - let textEdits = await languages.provideDocumentFormattingEdits(event.document, options, tokenSource.token) - clearTimeout(timer) - if (!textEdits && !tokenSource.token.isCancellationRequested) { - logger.want(`Format on save ${event.document.uri} get undefined result.`) - } - return textEdits - } - event.waitUntil(willSaveWaitUntil()) - } - })) - let enterTs: number - let enterBufnr: number - handler.addDisposable(events.on('Enter', async bufnr => { - enterTs = Date.now() - enterBufnr = bufnr - })) - handler.addDisposable(events.on('CursorMovedI', async bufnr => { - if (bufnr == enterBufnr && Date.now() - enterTs < 100) { - await this.handleEnter(bufnr) - } - })) - let changedTs: number - let lastInsert: number - handler.addDisposable(events.on('InsertCharPre', async () => { - lastInsert = Date.now() - })) - handler.addDisposable(events.on('TextChangedI', async (bufnr, info) => { - changedTs = Date.now() - if (!lastInsert || changedTs - lastInsert > 300) return - lastInsert = null - let pre = info.pre[info.pre.length - 1] - if (pre) await this.tryFormatOnType(pre, bufnr) - })) - let lastEnterBufnr: number - let lastEnterTs: number - handler.addDisposable(events.on('InsertEnter', bufnr => { - lastEnterBufnr = bufnr - lastEnterTs = Date.now() - })) - handler.addDisposable(events.on('TextChangedI', async (bufnr, info) => { - if (!this.preferences.formatOnType && !/^\s*$/.test(info.pre)) return - if (lastEnterBufnr != bufnr || !lastEnterTs || Date.now() - lastEnterTs > 30) return - lastEnterBufnr = undefined - await this.tryFormatOnType('\n', bufnr, true) - })) - } - - private loadPreferences(e?: ConfigurationChangeEvent): void { - if (!e || e.affectsConfiguration('coc.preferences')) { - let config = workspace.getConfiguration('coc.preferences') - this.preferences = { - formatOnType: config.get('formatOnType', false), - formatOnSaveFiletypes: config.get('formatOnSaveFiletypes', []), - formatOnTypeFiletypes: config.get('formatOnTypeFiletypes', []), - bracketEnterImprove: config.get('bracketEnterImprove', true), - } - } - } - - private async tryFormatOnType(ch: string, bufnr: number, newLine = false): Promise { - if (!ch || isWord(ch) || !this.preferences.formatOnType) return - if (snippetManager.getSession(bufnr) != null) return - let doc = workspace.getDocument(bufnr) - if (!doc || !doc.attached || doc.isCommandLine) return - const filetypes = this.preferences.formatOnTypeFiletypes - if (filetypes.length && !filetypes.includes(doc.filetype) && !filetypes.includes('*')) { - // Only check formatOnTypeFiletypes when set, avoid breaking change - return - } - if (!languages.hasProvider('formatOnType', doc.textDocument)) { - logger.warn(`Format on type provider not found for buffer: ${doc.uri}`) - return - } - if (!languages.canFormatOnType(ch, doc.textDocument)) return - let position: Position - let edits = await this.handler.withRequestToken('Format on type', async token => { - position = await window.getCursorPosition() - let origLine = doc.getline(position.line - 1) - // not format for empty line. - if (newLine && /^\s*$/.test(origLine)) return - let pos: Position = newLine ? { line: position.line - 1, character: origLine.length } : position - await doc.synchronize() - return await languages.provideDocumentOnTypeEdits(ch, doc.textDocument, pos, token) - }) - if (!edits || !edits.length) return - let changed = getChangedFromEdits(position, edits) - await doc.applyEdits(edits) - let to = changed ? Position.create(position.line + changed.line, position.character + changed.character) : null - if (to && !newLine) await window.moveTo(to) - } - - public async formatCurrentBuffer(): Promise { - let { doc } = await this.handler.getCurrentState() - return await this.documentFormat(doc) - } - - public async formatCurrentRange(mode: string): Promise { - let { doc } = await this.handler.getCurrentState() - return await this.documentRangeFormat(doc, mode) - } - - public async documentFormat(doc: Document): Promise { - await doc.synchronize() - if (!languages.hasFormatProvider(doc.textDocument)) { - throw new Error(`Format provider not found for buffer: ${doc.bufnr}`) - } - let options = await workspace.getFormatOptions(doc.uri) - let textEdits = await this.handler.withRequestToken('format', token => { - return languages.provideDocumentFormattingEdits(doc.textDocument, options, token) - }) - if (textEdits && textEdits.length > 0) { - await doc.applyEdits(textEdits) - return true - } - return false - } - - private async handleEnter(bufnr: number): Promise { - let { nvim } = this - let { bracketEnterImprove } = this.preferences - await this.tryFormatOnType('\n', bufnr) - if (bracketEnterImprove) { - let line = (await nvim.call('line', '.') as number) - 1 - let doc = workspace.getDocument(bufnr) - if (!doc) return - await doc.patchChange() - let pre = doc.getline(line - 1) - let curr = doc.getline(line) - let prevChar = pre[pre.length - 1] - if (prevChar && pairs.has(prevChar)) { - let nextChar = curr.trim()[0] - if (nextChar && pairs.get(prevChar) == nextChar) { - let edits: TextEdit[] = [] - let opts = await workspace.getFormatOptions(doc.uri) - let space = opts.insertSpaces ? ' '.repeat(opts.tabSize) : '\t' - let currIndent = curr.match(/^\s*/)[0] - let pos: Position = Position.create(line - 1, pre.length) - // make sure indent of current line - if (doc.filetype == 'vim') { - let newText = '\n' + currIndent + space - edits.push({ range: Range.create(line, currIndent.length, line, currIndent.length), newText: ' \\ ' }) - newText = newText + '\\ ' - edits.push({ range: Range.create(pos, pos), newText }) - await doc.applyEdits(edits) - await window.moveTo(Position.create(line, newText.length - 1)) - } else { - await nvim.eval(`feedkeys("\\O", 'in')`) - } - } - } - } - } - - public async documentRangeFormat(doc: Document, mode?: string): Promise { - this.handler.checkProvier('formatRange', doc.textDocument) - await doc.synchronize() - let range: Range - if (mode) { - range = await workspace.getSelectedRange(mode, doc) - if (!range) return -1 - } else { - let [lnum, count, mode] = await this.nvim.eval("[v:lnum,v:count,mode()]") as [number, number, string] - // we can't handle - if (count == 0 || mode == 'i' || mode == 'R') return -1 - range = Range.create(lnum - 1, 0, lnum - 1 + count, 0) - } - let options = await workspace.getFormatOptions(doc.uri) - let textEdits = await this.handler.withRequestToken('Format range', token => { - return languages.provideDocumentRangeFormattingEdits(doc.textDocument, range, options, token) - }) - if (textEdits && textEdits.length > 0) { - await doc.applyEdits(textEdits) - return 0 - } - return -1 - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/highlights.ts b/vim-config/plugins/coc.nvim/src/handler/highlights.ts deleted file mode 100644 index 10b7c6c5..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/highlights.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationTokenSource, Disposable, DocumentHighlight, DocumentHighlightKind, Position, Range } from 'vscode-languageserver-protocol' -import events from '../events' -import languages from '../languages' -import Document from '../model/document' -import { HandlerDelegate } from '../types' -import { disposeAll } from '../util' -import workspace from '../workspace' -const logger = require('../util/logger')('documentHighlight') - -/** - * Highlight same symbols. - * Highlights are added to window by matchaddpos. - */ -export default class Highlights { - private disposables: Disposable[] = [] - private tokenSource: CancellationTokenSource - private highlights: Map = new Map() - constructor(private nvim: Neovim, private handler: HandlerDelegate) { - events.on(['CursorMoved', 'CursorMovedI'], () => { - this.cancel() - this.clearHighlights() - }, null, this.disposables) - } - - public clearHighlights(): void { - if (this.highlights.size == 0) return - for (let winid of this.highlights.keys()) { - let win = this.nvim.createWindow(winid) - win.clearMatchGroup('^CocHighlight') - } - this.highlights.clear() - } - - public async highlight(): Promise { - let { nvim } = this - this.cancel() - let [bufnr, winid, pos, cursors] = await nvim.eval(`[bufnr("%"),win_getid(),coc#cursor#position(),get(b:,'coc_cursors_activated',0)]`) as [number, number, [number, number], number] - let doc = workspace.getDocument(bufnr) - if (!doc || !doc.attached || cursors) return - if (!languages.hasProvider('documentHighlight', doc.textDocument)) return - let highlights = await this.getHighlights(doc, Position.create(pos[0], pos[1])) - if (!highlights) return - let groups: { [index: string]: Range[] } = {} - for (let hl of highlights) { - if (!hl.range) continue - let hlGroup = hl.kind == DocumentHighlightKind.Text - ? 'CocHighlightText' - : hl.kind == DocumentHighlightKind.Read ? 'CocHighlightRead' : 'CocHighlightWrite' - groups[hlGroup] = groups[hlGroup] || [] - groups[hlGroup].push(hl.range) - } - let win = nvim.createWindow(winid) - nvim.pauseNotification() - win.clearMatchGroup('^CocHighlight') - for (let hlGroup of Object.keys(groups)) { - win.highlightRanges(hlGroup, groups[hlGroup], -1, true) - } - if (workspace.isVim) nvim.command('redraw', true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - this.highlights.set(winid, highlights) - } - - public async getSymbolsRanges(): Promise { - let { doc, position } = await this.handler.getCurrentState() - this.handler.checkProvier('documentHighlight', doc.textDocument) - let highlights = await this.getHighlights(doc, position) - if (!highlights) return null - return highlights.map(o => o.range) - } - - public hasHighlights(winid: number): boolean { - return this.highlights.get(winid) != null - } - - public async getHighlights(doc: Document, position: Position): Promise { - let line = doc.getline(position.line) - let ch = line[position.character] - if (!ch || !doc.isWord(ch)) return null - await doc.synchronize() - this.tokenSource = new CancellationTokenSource() - let source = this.tokenSource - let highlights = await languages.getDocumentHighLight(doc.textDocument, position, source.token) - if (source == this.tokenSource) { - source.dispose() - this.tokenSource = null - } - if (source.token.isCancellationRequested) return null - return highlights - } - - private cancel(): void { - if (this.tokenSource) { - this.tokenSource.cancel() - this.tokenSource.dispose() - this.tokenSource = null - } - } - - public dispose(): void { - this.highlights.clear() - this.cancel() - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/hover.ts b/vim-config/plugins/coc.nvim/src/handler/hover.ts deleted file mode 100644 index 167cfc68..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/hover.ts +++ /dev/null @@ -1,235 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import fs from 'fs' -import { CancellationTokenSource, Disposable, Hover, MarkedString, MarkupContent, Range } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import languages from '../languages' -import { Documentation } from '../markdown' -import FloatFactory, { FloatWinConfig } from '../model/floatFactory' -import { TextDocumentContentProvider } from '../provider' -import { ConfigurationChangeEvent, FloatConfig, HandlerDelegate } from '../types' -import { disposeAll, isMarkdown } from '../util' -import { readFileLines } from '../util/fs' -import workspace from '../workspace' -const logger = require('../util/logger')('handler-hover') - -export type HoverTarget = 'float' | 'preview' | 'echo' - -interface HoverConfig { - target: HoverTarget - floatConfig: FloatConfig - previewMaxHeight: number - autoHide: boolean -} - -export default class HoverHandler { - private hoverFactory: FloatFactory - private disposables: Disposable[] = [] - private documentLines: string[] = [] - private config: HoverConfig - private timer: NodeJS.Timeout - private hasProvider = false - private excludeImages = true - constructor(private nvim: Neovim, private handler: HandlerDelegate) { - this.loadConfiguration() - workspace.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables) - this.hoverFactory = new FloatFactory(nvim) - this.disposables.push(this.hoverFactory) - } - - private registerProvider(): void { - if (this.hasProvider) return - this.hasProvider = true - let { nvim } = this - let provider: TextDocumentContentProvider = { - onDidChange: null, - provideTextDocumentContent: async () => { - nvim.pauseNotification() - nvim.command('setlocal conceallevel=2 nospell nofoldenable wrap', true) - nvim.command('setlocal bufhidden=wipe nobuflisted', true) - nvim.command('setfiletype markdown', true) - nvim.command(`if winnr('j') != winnr('k') | exe "normal! z${Math.min(this.documentLines.length, this.config.previewMaxHeight)}\\ | endif"`, true) - await nvim.resumeNotification() - return this.documentLines.join('\n') - } - } - this.disposables.push(workspace.registerTextDocumentContentProvider('coc', provider)) - } - - private loadConfiguration(e?: ConfigurationChangeEvent): void { - if (!e || e.affectsConfiguration('hover')) { - let config = workspace.getConfiguration('hover') - let target = config.get('target', 'float') - this.config = { - floatConfig: config.get('floatConfig', {}), - autoHide: config.get('autoHide', true), - target: target == 'float' && !workspace.floatSupported ? 'preview' : target, - previewMaxHeight: config.get('previewMaxHeight', 12) - } - if (this.config.target == 'preview') { - this.registerProvider() - } - let preferences = workspace.getConfiguration('coc.preferences') - this.excludeImages = preferences.get('excludeImageLinksInMarkdownDocument', true) - } - } - - public async onHover(hoverTarget?: HoverTarget): Promise { - let { doc, position, winid } = await this.handler.getCurrentState() - if (hoverTarget == 'preview') this.registerProvider() - this.handler.checkProvier('hover', doc.textDocument) - await doc.synchronize() - let hovers = await this.handler.withRequestToken('hover', token => { - return languages.getHover(doc.textDocument, position, token) - }, true) - if (hovers == null || !hovers.length) return false - let hover = hovers.find(o => Range.is(o.range)) - if (hover?.range) { - let win = this.nvim.createWindow(winid) - win.highlightRanges('CocHoverRange', [hover.range], 99, true) - this.timer = setTimeout(() => { - win.clearMatchGroup('CocHoverRange') - if (workspace.isVim) this.nvim.command('redraw', true) - }, 500) - } - await this.previewHover(hovers, hoverTarget) - return true - } - - public async definitionHover(hoverTarget: HoverTarget): Promise { - const { doc, position } = await this.handler.getCurrentState() - if (hoverTarget == 'preview') this.registerProvider() - this.handler.checkProvier('hover', doc.textDocument) - await doc.synchronize() - const hovers: (Hover | Documentation)[] = await this.handler.withRequestToken('hover', token => { - return languages.getHover(doc.textDocument, position, token) - }, true) - if (!hovers?.length) return false - const defs = await this.handler.withRequestToken('definitionHover', token => { - return languages.getDefinitionLinks(doc.textDocument, position, token) - }, false) - if (defs?.length) { - for (const def of defs) { - if (!def.targetRange) continue - const { start, end } = def.targetRange - const endLine = end.line - start.line >= 100 ? start.line + 100 : (end.character == 0 ? end.line - 1 : end.line) - let lines = await readLines(def.targetUri, start.line, endLine) - if (lines.length) { - let indent = lines[0].match(/^\s*/)[0] - if (indent) lines = lines.map(l => l.startsWith(indent) ? l.substring(indent.length) : l) - hovers.push({ content: lines.join('\n'), filetype: doc.filetype }) - } - } - } - await this.previewHover(hovers, hoverTarget) - return true - } - - private async previewHover(hovers: (Hover | Documentation)[], target?: string): Promise { - let docs: Documentation[] = [] - target = target || this.config.target - let isPreview = target === 'preview' - for (let hover of hovers) { - if (isDocumentation(hover)) { - docs.push(hover) - continue - } - let { contents } = hover - if (Array.isArray(contents)) { - for (let item of contents) { - if (typeof item === 'string') { - addDocument(docs, item, 'markdown', isPreview) - } else { - addDocument(docs, item.value, item.language, isPreview) - } - } - } else if (MarkedString.is(contents)) { - if (typeof contents == 'string') { - addDocument(docs, contents, 'markdown', isPreview) - } else { - addDocument(docs, contents.value, contents.language, isPreview) - } - } else if (MarkupContent.is(contents)) { - addDocument(docs, contents.value, isMarkdown(contents) ? 'markdown' : 'txt', isPreview) - } - } - if (target == 'float') { - let config = this.hoverFactory.applyFloatConfig({ - modes: ['n'], - autoHide: this.config.autoHide, - excludeImages: this.excludeImages, - maxWidth: 80, - }, this.config.floatConfig) - await this.hoverFactory.show(docs, config) - return - } - let lines = docs.reduce((p, c) => { - let arr = c.content.split(/\r?\n/) - if (p.length > 0) p.push('') - p.push(...arr) - return p - }, []) - if (target == 'echo') { - const msg = lines.join('\n').trim() - await this.nvim.call('coc#util#echo_hover', [msg]) - } else { - this.documentLines = lines - await this.nvim.command(`noswapfile pedit coc://document`) - } - } - - /** - * Get hover text array - */ - public async getHover(): Promise { - let result: string[] = [] - let { doc, position } = await this.handler.getCurrentState() - this.handler.checkProvier('hover', doc.textDocument) - await doc.synchronize() - let tokenSource = new CancellationTokenSource() - let hovers = await languages.getHover(doc.textDocument, position, tokenSource.token) - if (Array.isArray(hovers)) { - for (let h of hovers) { - let { contents } = h - if (Array.isArray(contents)) { - contents.forEach(c => { - result.push(typeof c === 'string' ? c : c.value) - }) - } else if (MarkupContent.is(contents)) { - result.push(contents.value) - } else { - result.push(typeof contents === 'string' ? contents : contents.value) - } - } - } - result = result.filter(s => s != null && s.length > 0) - return result - } - - public dispose(): void { - if (this.timer) clearTimeout(this.timer) - disposeAll(this.disposables) - } -} - -function addDocument(docs: Documentation[], text: string, filetype: string, isPreview = false): void { - let content = text.trim() - if (!content.length) - return - if (isPreview && filetype !== 'markdown') { - content = '``` ' + filetype + '\n' + content + '\n```' - } - docs.push({ content, filetype }) -} - -function isDocumentation(obj: any): obj is Documentation { - if (!obj) return false - return typeof obj.filetype === 'string' && typeof obj.content === 'string' -} - -async function readLines(uri: string, start: number, end: number): Promise { - let doc = workspace.getDocument(uri) - if (doc) return doc.getLines(start, end + 1) - let fsPath = URI.parse(uri).fsPath - if (!fs.existsSync(fsPath)) return [] - return await readFileLines(fsPath, start, end) -} diff --git a/vim-config/plugins/coc.nvim/src/handler/index.ts b/vim-config/plugins/coc.nvim/src/handler/index.ts deleted file mode 100644 index 59265892..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/index.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { NeovimClient as Neovim } from '@chemzqm/neovim' -import { CancellationToken, CancellationTokenSource, CodeAction, CodeActionKind, Disposable, Position, Range, SymbolKind } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import events from '../events' -import languages from '../languages' -import Document from '../model/document' -import { StatusBarItem } from '../model/status' -import { ProviderName } from '../types' -import { disposeAll } from '../util' -import window from '../window' -import workspace from '../workspace' -import CodeActions from './codeActions' -import CodeLens from './codelens/index' -import Colors from './colors/index' -import Commands from './commands' -import Fold from './fold' -import Format from './format' -import Highlights from './highlights' -import HoverHandler from './hover' -import Links from './links' -import Locations from './locations' -import Refactor from './refactor/index' -import Rename from './rename' -import SelectionRange from './selectionRange' -import CallHierarchy from './callHierarchy' -import SemanticTokensHighlights from './semanticTokensHighlights/index' -import Signature from './signature' -import Symbols from './symbols/index' -import { HandlerDelegate } from '../types' -import { getSymbolKind } from '../util/convert' -const logger = require('../util/logger')('Handler') - -export interface CurrentState { - doc: Document - winid: number - position: Position - // :h mode() - mode: string -} - -export default class Handler implements HandlerDelegate { - public readonly documentHighlighter: Highlights - public readonly colors: Colors - public readonly signature: Signature - public readonly locations: Locations - public readonly symbols: Symbols - public readonly refactor: Refactor - public readonly codeActions: CodeActions - public readonly format: Format - public readonly hover: HoverHandler - public readonly codeLens: CodeLens - public readonly commands: Commands - public readonly links: Links - public readonly rename: Rename - public readonly fold: Fold - public readonly selectionRange: SelectionRange - public readonly callHierarchy: CallHierarchy - public readonly semanticHighlighter: SemanticTokensHighlights - private labels: { [key: string]: string } - private requestStatusItem: StatusBarItem - private requestTokenSource: CancellationTokenSource | undefined - private requestTimer: NodeJS.Timer - private disposables: Disposable[] = [] - - constructor(private nvim: Neovim) { - this.requestStatusItem = window.createStatusBarItem(0, { progress: true }) - events.on(['CursorMoved', 'CursorMovedI', 'InsertEnter', 'InsertSnippet', 'InsertLeave'], () => { - if (this.requestTokenSource) { - this.requestTokenSource.cancel() - this.requestTokenSource = null - } - }, null, this.disposables) - this.labels = workspace.getConfiguration('suggest').get('completionItemKindLabels', {}) - this.fold = new Fold(nvim, this) - this.links = new Links(nvim, this) - this.codeLens = new CodeLens(nvim) - this.colors = new Colors(nvim, this) - this.format = new Format(nvim, this) - this.symbols = new Symbols(nvim, this) - this.refactor = new Refactor(nvim, this) - this.hover = new HoverHandler(nvim, this) - this.locations = new Locations(nvim, this) - this.signature = new Signature(nvim, this) - this.rename = new Rename(nvim, this) - this.codeActions = new CodeActions(nvim, this) - this.commands = new Commands(nvim, workspace.env) - this.callHierarchy = new CallHierarchy(nvim, this) - this.documentHighlighter = new Highlights(nvim, this) - this.semanticHighlighter = new SemanticTokensHighlights(nvim, this) - this.selectionRange = new SelectionRange(nvim, this) - this.disposables.push({ - dispose: () => { - this.callHierarchy.dispose() - this.codeLens.dispose() - this.refactor.dispose() - this.signature.dispose() - this.symbols.dispose() - this.hover.dispose() - this.locations.dispose() - this.colors.dispose() - this.documentHighlighter.dispose() - this.semanticHighlighter.dispose() - } - }) - } - - public async getCurrentState(): Promise { - let { nvim } = this - let [bufnr, [line, character], winid, mode] = await nvim.eval("[bufnr('%'),coc#cursor#position(),win_getid(),mode()]") as [number, [number, number], number, string] - let doc = workspace.getDocument(bufnr) - if (!doc || !doc.attached) throw new Error(`current buffer ${bufnr} not attached`) - return { - doc, - mode, - position: Position.create(line, character), - winid - } - } - - public addDisposable(disposable: Disposable): void { - this.disposables.push(disposable) - } - - /** - * Throw error when provider not exists. - */ - public checkProvier(id: ProviderName, document: TextDocument): void { - if (!languages.hasProvider(id, document)) { - throw new Error(`${id} provider not found for current buffer, your language server doesn't support it.`) - } - } - - public async withRequestToken(name: string, fn: (token: CancellationToken) => Thenable, checkEmpty?: boolean): Promise { - if (this.requestTokenSource) { - this.requestTokenSource.cancel() - this.requestTokenSource.dispose() - } - if (this.requestTimer) { - clearTimeout(this.requestTimer) - } - let statusItem = this.requestStatusItem - this.requestTokenSource = new CancellationTokenSource() - let { token } = this.requestTokenSource - token.onCancellationRequested(() => { - statusItem.text = `${name} request canceled` - statusItem.isProgress = false - this.requestTimer = setTimeout(() => { - statusItem.hide() - }, 500) - }) - statusItem.isProgress = true - statusItem.text = `requesting ${name}` - statusItem.show() - let res: T - try { - res = await Promise.resolve(fn(token)) - } catch (e) { - window.showMessage(e.message, 'error') - logger.error(`Error on ${name}`, e) - } - if (this.requestTokenSource) { - this.requestTokenSource.dispose() - this.requestTokenSource = undefined - } - if (token.isCancellationRequested) return null - statusItem.hide() - if (checkEmpty && (!res || (Array.isArray(res) && res.length == 0))) { - window.showMessage(`${name} not found`, 'warning') - return null - } - return res - } - - public getIcon(kind: SymbolKind): { text: string, hlGroup: string } { - let { labels } = this - let kindText = getSymbolKind(kind) - let defaultIcon = typeof labels['default'] === 'string' ? labels['default'] : kindText[0].toLowerCase() - let text = kindText == 'Unknown' ? '' : labels[kindText[0].toLowerCase() + kindText.slice(1)] - if (!text || typeof text !== 'string') text = defaultIcon - return { - text, - hlGroup: kindText == 'Unknown' ? 'CocSymbolDefault' : `CocSymbol${kindText}` - } - } - - public async getCodeActions(doc: Document, range?: Range, only?: CodeActionKind[]): Promise { - return await this.codeActions.getCodeActions(doc, range, only) - } - - public async applyCodeAction(action: CodeAction): Promise { - await this.codeActions.applyCodeAction(action) - } - - public async hasProvider(id: string): Promise { - let bufnr = await this.nvim.call('bufnr', '%') - let doc = workspace.getDocument(bufnr) - if (!doc) return false - return languages.hasProvider(id as ProviderName, doc.textDocument) - } - - public dispose(): void { - if (this.requestTimer) { - clearTimeout(this.requestTimer) - } - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/links.ts b/vim-config/plugins/coc.nvim/src/handler/links.ts deleted file mode 100644 index 7f02b94d..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/links.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { DocumentLink, Position } from 'vscode-languageserver-protocol' -import languages from '../languages' -import { HandlerDelegate } from '../types' -import { positionInRange } from '../util/position' -import workspace from '../workspace' - -export default class Links { - constructor(private nvim: Neovim, private handler: HandlerDelegate) { - } - - public async getLinks(): Promise { - let { doc } = await this.handler.getCurrentState() - this.handler.checkProvier('documentLink', doc.textDocument) - let links = await this.handler.withRequestToken('links', token => { - return languages.getDocumentLinks(doc.textDocument, token) - }) - return links || [] - } - - public async openLink(link: DocumentLink): Promise { - if (!link.target) { - link = await languages.resolveDocumentLink(link) - if (!link.target) throw new Error(`Failed to resolve link target`) - } - await workspace.openResource(link.target) - } - - public async openCurrentLink(): Promise { - let [line, character] = await this.nvim.call('coc#cursor#position') as [number, number] - let links = await this.getLinks() - if (!links || links.length == 0) return false - let position = Position.create(line, character) - for (let link of links) { - if (positionInRange(position, link.range) == 0) { - await this.openLink(link) - return true - } - } - return false - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/locations.ts b/vim-config/plugins/coc.nvim/src/handler/locations.ts deleted file mode 100644 index 29208b34..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/locations.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationToken, CancellationTokenSource, Definition, Location, LocationLink, Position, TextDocument } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import languages from '../languages' -import services from '../services' -import { HandlerDelegate, ProviderName } from '../types' -import workspace from '../workspace' -const logger = require('../util/logger')('handler-hover') - -export interface TagDefinition { - name: string - cmd: string - filename: string -} - -export type RequestFunc = (doc: TextDocument, position: Position, token: CancellationToken) => Thenable - -export default class LocationsHandler { - constructor(private nvim: Neovim, private handler: HandlerDelegate) { - } - - private async request(method: ProviderName, fn: RequestFunc): Promise { - let { doc, position } = await this.handler.getCurrentState() - this.handler.checkProvier(method, doc.textDocument) - await doc.synchronize() - return await this.handler.withRequestToken(method, token => { - return fn(doc.textDocument, position, token) - }, true) - } - - public async definitions(): Promise { - const { doc, position } = await this.handler.getCurrentState() - this.handler.checkProvier('definition', doc.textDocument) - await doc.synchronize() - const tokenSource = new CancellationTokenSource() - return languages.getDefinition(doc.textDocument, position, tokenSource.token) - } - - public async declarations(): Promise { - const { doc, position } = await this.handler.getCurrentState() - this.handler.checkProvier('declaration', doc.textDocument) - await doc.synchronize() - const tokenSource = new CancellationTokenSource() - return languages.getDeclaration(doc.textDocument, position, tokenSource.token) - } - - public async typeDefinitions(): Promise { - const { doc, position } = await this.handler.getCurrentState() - this.handler.checkProvier('typeDefinition', doc.textDocument) - await doc.synchronize() - const tokenSource = new CancellationTokenSource() - return languages.getTypeDefinition(doc.textDocument, position, tokenSource.token) - } - - public async implementations(): Promise { - const { doc, position } = await this.handler.getCurrentState() - this.handler.checkProvier('implementation', doc.textDocument) - await doc.synchronize() - const tokenSource = new CancellationTokenSource() - return languages.getImplementation(doc.textDocument, position, tokenSource.token) - } - - public async references(): Promise { - const { doc, position } = await this.handler.getCurrentState() - this.handler.checkProvier('reference', doc.textDocument) - await doc.synchronize() - const tokenSource = new CancellationTokenSource() - return languages.getReferences(doc.textDocument, { includeDeclaration: true }, position, tokenSource.token) - } - - public async gotoDefinition(openCommand?: string): Promise { - let definition = await this.request('definition', (doc, position, token) => { - return languages.getDefinition(doc, position, token) - }) - await this.handleLocations(definition, openCommand) - return definition ? definition.length > 0 : false - } - - public async gotoDeclaration(openCommand?: string): Promise { - let definition = await this.request('declaration', (doc, position, token) => { - return languages.getDeclaration(doc, position, token) - }) - await this.handleLocations(definition, openCommand) - return definition ? (Array.isArray(definition) ? definition.length > 0 : true) : false - } - - public async gotoTypeDefinition(openCommand?: string): Promise { - let definition = await this.request('typeDefinition', (doc, position, token) => { - return languages.getTypeDefinition(doc, position, token) - }) - await this.handleLocations(definition, openCommand) - return definition ? definition.length > 0 : false - } - - public async gotoImplementation(openCommand?: string): Promise { - let definition = await this.request('implementation', (doc, position, token) => { - return languages.getImplementation(doc, position, token) - }) - await this.handleLocations(definition, openCommand) - return definition ? definition.length > 0 : false - } - - public async gotoReferences(openCommand?: string, includeDeclaration = true): Promise { - let definition = await this.request('reference', (doc, position, token) => { - return languages.getReferences(doc, { includeDeclaration }, position, token) - }) - await this.handleLocations(definition, openCommand) - return definition ? definition.length > 0 : false - } - - public async getTagList(): Promise { - let { doc, position } = await this.handler.getCurrentState() - let word = await this.nvim.call('expand', '') - if (!word) return null - if (!languages.hasProvider('definition', doc.textDocument)) return null - let tokenSource = new CancellationTokenSource() - let definitions = await languages.getDefinition(doc.textDocument, position, tokenSource.token) - if (!definitions || !definitions.length) return null - return definitions.map(location => { - let parsedURI = URI.parse(location.uri) - const filename = parsedURI.scheme == 'file' ? parsedURI.fsPath : parsedURI.toString() - return { - name: word, - cmd: `keepjumps ${location.range.start.line + 1} | normal ${location.range.start.character + 1}|`, - filename, - } - }) - } - - /** - * Send custom request for locations to services. - */ - public async findLocations(id: string, method: string, params: any, openCommand?: string | false): Promise { - let { doc, position } = await this.handler.getCurrentState() - params = params || {} - Object.assign(params, { - textDocument: { uri: doc.uri }, - position - }) - let res: any = await services.sendRequest(id, method, params) - res = res || [] - let locations: Location[] = [] - if (Array.isArray(res)) { - locations = res as Location[] - } else if (res.hasOwnProperty('location') && res.hasOwnProperty('children')) { - let getLocation = (item: any): void => { - locations.push(item.location as Location) - if (item.children && item.children.length) { - for (let loc of item.children) { - getLocation(loc) - } - } - } - getLocation(res) - } - await this.handleLocations(locations, openCommand) - } - - public async handleLocations(definition: Definition | LocationLink[], openCommand?: string | false): Promise { - if (!definition) return - let locations: Location[] = Array.isArray(definition) ? definition as Location[] : [definition] - locations = locations.map(o => LocationLink.is(o) ? Location.create(o.targetUri, o.targetRange) : o) - let len = locations.length - if (len == 0) return - if (len == 1 && openCommand !== false) { - let { uri, range } = locations[0] - await workspace.jumpTo(uri, range.start, openCommand) - } else { - await workspace.showLocations(locations) - } - } - - public dispose(): void { - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/refactor/buffer.ts b/vim-config/plugins/coc.nvim/src/handler/refactor/buffer.ts deleted file mode 100644 index 64ba241b..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/refactor/buffer.ts +++ /dev/null @@ -1,545 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import fastDiff from 'fast-diff' -import path from 'path' -import { Disposable, Range, TextEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { URI } from 'vscode-uri' -import commands from '../../commands' -import Document from '../../model/document' -import Highlighter from '../../model/highligher' -import { BufferSyncItem, DidChangeTextDocumentParams } from '../../types' -import { disposeAll } from '../../util' -import { isParentFolder, readFileLines } from '../../util/fs' -import { Mutex } from '../../util/mutex' -import { equals } from '../../util/object' -import { byteLength } from '../../util/string' -import window from '../../window' -import workspace from '../../workspace' -const logger = require('../../util/logger')('handler-refactorBuffer') - -export const SEPARATOR = '\u3000' - -export interface LineChange { - // zero indexed - lnum: number - delta: number -} - -export interface FileChange { - // line number of filepath - lnum: number - // start line 0 indexed - start?: number - // end line 0 indexed, excluded - end?: number - filepath: string - lines: string[] -} - -export interface FileRange { - // start lnum in refactor buffer, 1 indexed - lnum?: number - // start line 0 indexed - start: number - // end line 0 indexed, excluded - end: number - // range relatived to new range - highlights?: Range[] - lines?: string[] -} - -export interface FileItem { - filepath: string - ranges: FileRange[] -} - -export interface RefactorConfig { - openCommand: string - beforeContext: number - afterContext: number - saveToFile: boolean -} - -export interface RefactorBufferOpts { - cwd: string - winid: number - fromWinid: number -} - -export default class RefactorBuffer implements BufferSyncItem { - private mutex = new Mutex() - private _disposed = false - private disposables: Disposable[] = [] - private _fileItems: FileItem[] = [] - private matchIds: Set = new Set() - private changing = false - constructor( - private bufnr: number, - private srcId: number, - private nvim: Neovim, - public readonly config: RefactorConfig, - private opts: RefactorBufferOpts - ) { - this.disposables.push(workspace.registerLocalKeymap('n', '', this.splitOpen.bind(this), true)) - workspace.onDidChangeTextDocument(this.onDocumentChange, this, this.disposables) - } - - public get fileItems(): FileItem[] { - return this._fileItems - } - - public onChange(e: DidChangeTextDocumentParams): void { - if (this.changing) return - let doc = this.document - let { nvim, _fileItems: fileItems } = this - if (!fileItems.length) return - let change = e.contentChanges[0] - if (!('range' in change)) return - let { original } = e - if (change.range.end.line < 2) return - doc.buffer.setOption('modified', true, true) - let { range, text } = change - let lines = text.split('\n') - let lineChange = lines.length - (range.end.line - range.start.line) - 1 - if (lineChange == 0) return - let lineChanges: LineChange[] = [] - if (text.includes('\u3000')) { - let startLine = range.start.line - let diffs = fastDiff(original, text) - let offset = 0 - let orig = TextDocument.create('file:///1', '', 0, original) - for (let i = 0; i < diffs.length; i++) { - let diff = diffs[i] - let pos = orig.positionAt(offset) - if (diff[0] == fastDiff.EQUAL) { - offset = offset + diff[1].length - } else if (diff[0] == fastDiff.DELETE) { - let end = orig.positionAt(offset + diff[1].length) - if (diffs[i + 1] && diffs[i + 1][0] == fastDiff.INSERT) { - let delta = diffs[i + 1][1].split('\n').length - (end.line - pos.line) - 1 - if (delta != 0) lineChanges.push({ delta, lnum: pos.line + startLine }) - i = i + 1 - } else { - let delta = - (end.line - pos.line) - if (delta != 0) lineChanges.push({ delta, lnum: pos.line + startLine }) - } - offset = offset + diff[1].length - } else if (diff[0] == fastDiff.INSERT) { - let delta = diff[1].split('\n').length - 1 - if (delta != 0) lineChanges.push({ delta, lnum: pos.line + startLine }) - } - } - } else { - lineChanges = [{ delta: lineChange, lnum: range.start.line }] - } - let changed = false - // adjust LineNr highlights - for (let item of fileItems) { - for (let range of item.ranges) { - let arr = lineChanges.filter(o => o.lnum < range.lnum - 1) - if (arr.length) { - let total = arr.reduce((p, c) => p + c.delta, 0) - range.lnum = range.lnum + total - changed = true - } - } - } - if (!changed) return - nvim.pauseNotification() - this.highlightLineNr() - nvim.resumeNotification().then(res => { - if (Array.isArray(res) && res[1] != null) { - logger.error(`Error on highlightLineNr:`, res[1]) - } - }).logError() - } - - /** - * Handle changes of other buffers. - */ - private async onDocumentChange(e: DidChangeTextDocumentParams): Promise { - if (e.bufnr == this.bufnr || this.changing) return - let { uri } = e.textDocument - let { range, text } = e.contentChanges[0] - let filepath = URI.parse(uri).fsPath - let fileItem = this._fileItems.find(o => o.filepath == filepath) - // not affected - if (!fileItem) return - let lineChange = text.split('\n').length - (range.end.line - range.start.line) - 1 - let edits: TextEdit[] = [] - // 4 cases: ignore, change lineNr, reload, remove - for (let i = 0; i < fileItem.ranges.length; i++) { - let r = fileItem.ranges[i] - if (range.start.line >= r.end) { - continue - } - if (range.end.line < r.start) { - if (lineChange == 0) { - continue - } else { - r.start = r.start + lineChange - r.end = r.end + lineChange - } - } else { - let doc = workspace.getDocument(uri) - let newLines = doc.getLines(r.start, r.end) - if (!newLines.length) { - // remove this range - fileItem.ranges.splice(i, 1) - edits.push({ - range: this.getFileRangeRange(r, false), - newText: '' - }) - } else { - r.end = r.start + newLines.length - // reload lines, reset end - edits.push({ - range: this.getFileRangeRange(r, true), - newText: newLines.join('\n') + '\n' - }) - } - } - } - // clean fileItem with empty ranges - this._fileItems = this._fileItems.filter(o => o.ranges && o.ranges.length > 0) - if (edits.length) { - this.changing = true - await this.document.applyEdits(edits) - this.changing = false - } - this.nvim.pauseNotification() - this.highlightLineNr() - this.buffer.setOption('modified', false, true) - await this.nvim.resumeNotification() - } - - /** - * Current changed file ranges - */ - public async getFileChanges(): Promise { - if (this._disposed) return [] - let changes: FileChange[] = [] - let lines = await this.buffer.lines - lines.push(SEPARATOR) - // current lines - let arr: string[] = [] - let fsPath: string - let lnum: number - for (let i = 0; i < lines.length; i++) { - let line = lines[i] - if (line.startsWith(SEPARATOR)) { - if (fsPath) { - changes.push({ - filepath: fsPath, - lines: arr.slice(), - lnum - }) - fsPath = undefined - arr = [] - } - if (line.length > 1) { - let ms = line.match(/^\u3000(.*)/) - if (ms) { - fsPath = this.getAbsolutePath(ms[1].replace(/\s+$/, '')) - lnum = i + 1 - arr = [] - } - } - } else { - arr.push(line) - } - } - return changes - } - - /** - * Open line under cursor in split window - */ - public async splitOpen(): Promise { - let { nvim } = this - let win = nvim.createWindow(this.opts.fromWinid) - let valid = await win.valid - let lines = await nvim.eval('getline(1,line("."))') as string[] - let len = lines.length - for (let i = 0; i < len; i++) { - let line = lines[len - i - 1] - let ms = line.match(/^\u3000(.+)/) - if (ms) { - let filepath = ms[1].trim() - let r = this.getLinesRange(len - i) - if (!r) return - let lnum = r[0] + i - 1 - let bufname = this.getAbsolutePath(filepath) - nvim.pauseNotification() - if (valid) { - nvim.call('win_gotoid', [this.opts.fromWinid], true) - this.nvim.call('coc#util#jump', ['edit', bufname, [lnum, 1]], true) - } else { - this.nvim.call('coc#util#jump', ['belowright vs', bufname, [lnum, 1]], true) - } - nvim.command('normal! zz', true) - let [, err] = await nvim.resumeNotification() - if (err) window.showMessage(`Error on open ${filepath}: ${err}`, 'error') - if (!valid) { - this.opts.fromWinid = await nvim.call('win_getid') - } - break - } - } - } - - /** - * Add FileItem to refactor buffer. - */ - public async addFileItems(items: FileItem[]): Promise { - if (this._disposed) return - let { cwd } = this.opts - let { document } = this - const release = await this.mutex.acquire() - try { - await document.synchronize() - for (let item of items) { - let fileItem = this._fileItems.find(o => o.filepath == item.filepath) - if (fileItem) { - fileItem.ranges.push(...item.ranges) - } else { - this._fileItems.push(item) - } - } - let count = document.lineCount - let highligher = new Highlighter() - let hlRanges: Range[] = [] - for (let item of items) { - for (let range of item.ranges) { - highligher.addLine(SEPARATOR) - highligher.addLine(SEPARATOR) - range.lnum = count + highligher.length - highligher.addText(`${isParentFolder(cwd, item.filepath) ? path.relative(cwd, item.filepath) : item.filepath}`) - // white spaces for conceal texts - let n = String(range.start + 1).length + String(range.end).length + 4 - if (!this.srcId) highligher.addText(' '.repeat(n)) - let base = 0 - highligher.length - count - if (range.highlights) { - hlRanges.push(...range.highlights.map(r => adjustRange(r, base))) - } - let { lines } = range - if (!lines) { - lines = await this.getLines(item.filepath, range.start, range.end) - range.lines = lines - } - highligher.addLines(lines) - } - } - let { nvim, buffer } = this - this.changing = true - nvim.pauseNotification() - highligher.render(buffer, count) - this.highlightLineNr() - buffer.setOption('modified', false, true) - buffer.setOption('undolevels', 1000, true) - if (count == 2 && hlRanges.length) { - let pos = hlRanges[0].start - nvim.call('coc#cursor#move_to', [pos.line, pos.character], true) - } - if (workspace.isVim) { - nvim.command('redraw', true) - } - let [, err] = await nvim.resumeNotification() - if (err) throw new Error(err[2]) - await document.patchChange() - this.changing = false - await commands.executeCommand('editor.action.addRanges', hlRanges) - } catch (e) { - this.changing = false - logger.error(`Error on add file item:`, e) - } - release() - } - - /** - * Save changes to buffers/files, return false when no change made. - */ - public async save(): Promise { - let { nvim } = this - let doc = this.document - let { buffer } = doc - await doc.patchChange() - let changes = await this.getFileChanges() - if (!changes) return - changes.sort((a, b) => a.lnum - b.lnum) - // filter changes that not change - let removeList: number[] = [] - let deltaMap: Map = new Map() - for (let i = 0; i < changes.length; i++) { - let change = changes[i] - let { filepath, lnum } = change - let curr = deltaMap.get(filepath) || 0 - let item = this._fileItems.find(o => o.filepath == filepath) - let range = item ? item.ranges.find(o => o.lnum == lnum) : null - if (!range || equals(range.lines, change.lines)) { - removeList.push(i) - if (curr && range) { - range.start = range.start + curr - range.end = range.end + curr - } - continue - } - change.start = range.start - change.end = range.end - if (curr != 0) range.start = range.start + curr - if (change.lines.length != range.lines.length) { - let delta = change.lines.length - range.lines.length - let total = delta + curr - deltaMap.set(filepath, total) - range.end = range.end + total - } else { - range.end = range.end + curr - } - range.lines = change.lines - } - if (removeList.length) changes = changes.filter((_, i) => !removeList.includes(i)) - if (changes.length == 0) { - window.showMessage('No change.', 'more') - await buffer.setOption('modified', false) - return false - } - let changeMap: { [uri: string]: TextEdit[] } = {} - for (let change of changes) { - let uri = URI.file(change.filepath).toString() - let edits = changeMap[uri] || [] - edits.push({ - range: Range.create(change.start, 0, change.end, 0), - newText: change.lines.join('\n') + '\n' - }) - changeMap[uri] = edits - } - this.changing = true - await workspace.applyEdit({ changes: changeMap }) - this.changing = false - nvim.pauseNotification() - buffer.setOption('modified', false, true) - if (this.config.saveToFile) { - nvim.command('silent noa wa', true) - } - this.highlightLineNr() - await nvim.resumeNotification() - return true - } - - public getFileRange(lnum: number): FileRange { - for (let item of this._fileItems) { - for (let r of item.ranges) { - if (r.lnum == lnum) { - return r - } - } - } - } - - private getLinesRange(lnum: number): [number, number] | null { - for (let item of this._fileItems) { - for (let range of item.ranges) { - if (range.lnum == lnum) { - return [range.start, range.end] - } - } - } - } - - private async getLines(fsPath: string, start: number, end: number): Promise { - let uri = URI.file(fsPath).toString() - let doc = workspace.getDocument(uri) - if (doc) return doc.getLines(start, end) - return await readFileLines(fsPath, start, end - 1) - } - - private getAbsolutePath(filepath: string): string { - if (path.isAbsolute(filepath)) return filepath - return path.join(this.opts.cwd, filepath) - } - - /** - * Edit range of FileRange - */ - private getFileRangeRange(range: FileRange, lineOnly = true): Range { - let { document } = this - if (!document) return null - let { lnum } = range - let first = document.getline(lnum - 1) - if (!first.startsWith('\u3000')) return null - let start = lineOnly ? lnum : lnum - 1 - let end = document.lineCount - for (let i = lnum; i < document.lineCount; i++) { - let line = document.getline(i) - if (line.startsWith('\u3000')) { - end = lineOnly ? i : i + 1 - break - } - } - return Range.create(start, 0, end, 0) - } - - /** - * Use conceal to add lineNr - */ - private highlightLineNr(): void { - let { _fileItems: fileItems, nvim, srcId, bufnr } = this - let { winid, cwd } = this.opts - let info = {} - if (srcId) { - nvim.call('nvim_buf_clear_namespace', [bufnr, srcId, 0, -1], true) - for (let item of fileItems) { - for (let range of item.ranges) { - let text = `${range.start + 1}:${range.end}` - info[range.lnum] = [range.start + 1, range.end] - nvim.call('nvim_buf_set_virtual_text', [bufnr, srcId, range.lnum - 1, [[text, 'LineNr']], {}], true) - } - } - } else { - if (this.matchIds.size) { - nvim.call('coc#highlight#clear_matches', [winid, Array.from(this.matchIds)], true) - this.matchIds.clear() - } - let id = 2000 - for (let item of fileItems) { - let filename = `${cwd ? path.relative(cwd, item.filepath) : item.filepath}` - let col = byteLength(filename) + 1 - for (let range of item.ranges) { - let text = `:${range.start + 1}:${range.end}` - for (let i = 0; i < text.length; i++) { - let ch = text[i] - this.matchIds.add(id) - info[range.lnum] = [range.start + 1, range.end] - nvim.call('matchaddpos', ['Conceal', [[range.lnum, col + i]], 99, id, { conceal: ch, window: winid }], true) - id++ - } - } - } - } - this.buffer.setVar('line_infos', info, true) - } - - public get valid(): Promise { - return this.buffer.valid - } - - public get buffer(): Buffer { - return this.nvim.createBuffer(this.bufnr) - } - - public get document(): Document | null { - if (this._disposed) return null - return workspace.getDocument(this.bufnr) - } - - public dispose(): void { - this._disposed = true - disposeAll(this.disposables) - } -} - -function adjustRange(range: Range, offset: number): Range { - let { start, end } = range - return Range.create(start.line - offset, start.character, end.line - offset, end.character) -} - diff --git a/vim-config/plugins/coc.nvim/src/handler/refactor/index.ts b/vim-config/plugins/coc.nvim/src/handler/refactor/index.ts deleted file mode 100644 index d96e0503..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/refactor/index.ts +++ /dev/null @@ -1,247 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable, Emitter, Event, Location, Range, TextDocumentEdit, TextEdit, WorkspaceEdit } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import languages from '../../languages' -import { ConfigurationChangeEvent, HandlerDelegate } from '../../types' -import { disposeAll } from '../../util' -import { getFileLineCount } from '../../util/fs' -import window from '../../window' -import workspace from '../../workspace' -import Search from '../search' -import RefactorBuffer, { FileItem, FileRange, RefactorConfig, SEPARATOR } from './buffer' -const logger = require('../../util/logger')('handler-refactor') - -const name = '__coc_refactor__' -let refactorId = 0 - -export { FileItem } - -export default class Refactor { - private srcId: number - private timer: NodeJS.Timer - private buffers: Map = new Map() - public config: RefactorConfig - private disposables: Disposable[] = [] - private readonly _onCreate = new Emitter() - public readonly onCreate: Event = this._onCreate.event - constructor( - private nvim: Neovim, - private handler: HandlerDelegate - ) { - if (workspace.isNvim && this.nvim.hasFunction('nvim_buf_set_virtual_text')) { - this.srcId = workspace.createNameSpace('coc-refactor') - } - this.setConfiguration() - workspace.onDidChangeConfiguration(this.setConfiguration, this, this.disposables) - workspace.onDidCloseTextDocument(e => { - let buf = this.buffers.get(e.bufnr) - if (buf) { - buf.dispose() - this.buffers.delete(e.bufnr) - } - }, null, this.disposables) - workspace.onDidChangeTextDocument(e => { - let buf = this.buffers.get(e.bufnr) - if (buf) buf.onChange(e) - }, null, this.disposables) - } - - private setConfiguration(e?: ConfigurationChangeEvent): void { - if (e && !e.affectsConfiguration('refactor')) return - let config = workspace.getConfiguration('refactor') - this.config = Object.assign(this.config || {}, { - afterContext: config.get('afterContext', 3), - beforeContext: config.get('beforeContext', 3), - openCommand: config.get('openCommand', 'edit'), - saveToFile: config.get('saveToFile', true) - }) - } - - /** - * Refactor of current symbol - */ - public async doRefactor(): Promise { - let { doc, position } = await this.handler.getCurrentState() - if (!languages.hasProvider('rename', doc.textDocument)) { - throw new Error(`Rename provider not found for current buffer`) - } - await doc.synchronize() - let edit = await this.handler.withRequestToken('refactor', async token => { - let res = await languages.prepareRename(doc.textDocument, position, token) - if (token.isCancellationRequested) return null - if (res === false) throw new Error(`Provider returns null on prepare, unable to rename at current position`) - let edit = await languages.provideRenameEdits(doc.textDocument, position, 'NewName', token) - if (token.isCancellationRequested) return null - if (!edit) throw new Error('Provider returns null for rename edits.') - return edit - }) - if (edit) { - await this.fromWorkspaceEdit(edit, doc.filetype) - } - } - - /** - * Search by rg - */ - public async search(args: string[]): Promise { - let buf = await this.createRefactorBuffer() - if (!buf) return - let cwd = await this.nvim.call('getcwd', []) - let search = new Search(this.nvim) - await search.run(args, cwd, buf) - } - - public async save(bufnr: number): Promise { - let buf = this.buffers.get(bufnr) - if (buf) return await buf.save() - } - - public getBuffer(bufnr: number): RefactorBuffer { - return this.buffers.get(bufnr) - } - - /** - * Create initialized refactor buffer - */ - public async createRefactorBuffer(filetype?: string): Promise { - let { nvim } = this - let [fromWinid, cwd] = await nvim.eval('[win_getid(),getcwd()]') as [number, string] - let { openCommand } = this.config - nvim.pauseNotification() - nvim.command(`${openCommand} ${name}${refactorId++}`, true) - nvim.command(`setl buftype=acwrite nobuflisted bufhidden=wipe nofen wrap conceallevel=2 concealcursor=n`, true) - nvim.command(`setl undolevels=-1 nolist nospell noswapfile foldmethod=expr foldexpr=coc#util#refactor_foldlevel(v:lnum)`, true) - nvim.command(`setl foldtext=coc#util#refactor_fold_text(v:foldstart)`, true) - nvim.call('setline', [1, ['Save current buffer to make changes', SEPARATOR]], true) - nvim.call('matchadd', ['Comment', '\\%1l'], true) - nvim.call('matchadd', ['Conceal', '^\\%u3000'], true) - nvim.call('matchadd', ['Label', '^\\%u3000\\zs\\S\\+'], true) - nvim.command('setl nomod', true) - if (filetype) nvim.command(`runtime! syntax/${filetype}.vim`, true) - nvim.call('coc#util#do_autocmd', ['CocRefactorOpen'], true) - let [, err] = await nvim.resumeNotification() - if (err) return - let [bufnr, win] = await nvim.eval('[bufnr("%"),win_getid()]') as [number, number] - let opts = { fromWinid, winid: win, cwd } - await workspace.document - let buf = new RefactorBuffer(bufnr, this.srcId, this.nvim, this.config, opts) - this.buffers.set(bufnr, buf) - return buf - } - - /** - * Create refactor buffer from lines - */ - public async fromLines(lines: string[]): Promise { - let buf = await this.createRefactorBuffer() - if (buf) await buf.buffer.setLines(lines, { start: 0, end: -1, strictIndexing: false }) - return buf - } - - /** - * Create refactor buffer from locations - */ - public async fromLocations(locations: Location[], filetype?: string): Promise { - if (!locations || locations.length == 0) return null - let changes: { [uri: string]: TextEdit[] } = {} - let edit: WorkspaceEdit = { changes } - for (let location of locations) { - let edits: TextEdit[] = changes[location.uri] || [] - edits.push({ range: location.range, newText: '' }) - changes[location.uri] = edits - } - return await this.fromWorkspaceEdit(edit, filetype) - } - - /** - * Start refactor from workspaceEdit - */ - public async fromWorkspaceEdit(edit: WorkspaceEdit, filetype?: string): Promise { - if (!edit || emptyWorkspaceEdit(edit)) return undefined - let items: FileItem[] = [] - let { beforeContext, afterContext } = this.config - let { changes, documentChanges } = edit - if (!changes) { - changes = {} - for (let change of documentChanges || []) { - if (TextDocumentEdit.is(change)) { - let { textDocument, edits } = change - if (textDocument.uri.startsWith('file:')) { - changes[textDocument.uri] = edits - } - } - } - } - for (let key of Object.keys(changes)) { - let max = await this.getLineCount(key) - let edits = changes[key] - let ranges: FileRange[] = [] - // start end highlights - let start = null - let end = null - let highlights: Range[] = [] - edits.sort((a, b) => a.range.start.line - b.range.start.line) - for (let edit of edits) { - let { line } = edit.range.start - let s = Math.max(0, line - beforeContext) - if (start != null && s < end) { - end = Math.min(max, line + afterContext + 1) - highlights.push(adjustRange(edit.range, start)) - } else { - if (start != null) ranges.push({ start, end, highlights }) - start = s - end = Math.min(max, line + afterContext + 1) - highlights = [adjustRange(edit.range, start)] - } - } - if (start != null) ranges.push({ start, end, highlights }) - items.push({ - ranges, - filepath: URI.parse(key).fsPath - }) - } - let buf = await this.createRefactorBuffer(filetype) - await buf.addFileItems(items) - return buf - } - - private async getLineCount(uri: string): Promise { - let doc = workspace.getDocument(uri) - if (doc) return doc.lineCount - return await getFileLineCount(URI.parse(uri).fsPath) - } - - public reset(): void { - if (this.timer) { - clearTimeout(this.timer) - } - for (let buf of this.buffers.values()) { - buf.dispose() - } - this.buffers.clear() - } - - public dispose(): void { - if (this.timer) { - clearTimeout(this.timer) - } - this._onCreate.dispose() - for (let buf of this.buffers.values()) { - buf.dispose() - } - this.buffers.clear() - disposeAll(this.disposables) - } -} - -function adjustRange(range: Range, offset: number): Range { - let { start, end } = range - return Range.create(start.line - offset, start.character, end.line - offset, end.character) -} - -function emptyWorkspaceEdit(edit: WorkspaceEdit): boolean { - let { changes, documentChanges } = edit - if (documentChanges && documentChanges.length) return false - if (changes && Object.keys(changes).length) return false - return true -} diff --git a/vim-config/plugins/coc.nvim/src/handler/rename.ts b/vim-config/plugins/coc.nvim/src/handler/rename.ts deleted file mode 100644 index 3279f0ae..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/rename.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationTokenSource, Range, WorkspaceEdit } from 'vscode-languageserver-protocol' -import languages from '../languages' -import { HandlerDelegate } from '../types' -import { emptyRange } from '../util/position' -import window from '../window' -import workspace from '../workspace' -const logger = require('../util/logger')('handler-rename') - -export default class Rename { - constructor( - private nvim: Neovim, - private handler: HandlerDelegate) { - } - - public async getWordEdit(): Promise { - let { doc, position } = await this.handler.getCurrentState() - let range = doc.getWordRangeAtPosition(position) - if (!range || emptyRange(range)) return null - let curname = doc.textDocument.getText(range) - if (languages.hasProvider('rename', doc.textDocument)) { - await doc.synchronize() - let requestTokenSource = new CancellationTokenSource() - let res = await languages.prepareRename(doc.textDocument, position, requestTokenSource.token) - if (res === false) return null - let edit = await languages.provideRenameEdits(doc.textDocument, position, curname, requestTokenSource.token) - if (edit) return edit - } - window.showMessage('Rename provider not found, extract word ranges from current buffer', 'more') - let ranges = doc.getSymbolRanges(curname) - return { - changes: { - [doc.uri]: ranges.map(r => ({ range: r, newText: curname })) - } - } - } - - public async rename(newName?: string): Promise { - let { doc, position } = await this.handler.getCurrentState() - this.handler.checkProvier('rename', doc.textDocument) - await doc.synchronize() - let token = (new CancellationTokenSource()).token - let res = await languages.prepareRename(doc.textDocument, position, token) - if (res === false) { - window.showMessage('Invalid position for rename', 'warning') - return false - } - let curname: string - if (!newName) { - if (Range.is(res)) { - curname = doc.textDocument.getText(res) - await window.moveTo(res.start) - } else if (res && typeof res.placeholder === 'string') { - curname = res.placeholder - } else { - curname = await this.nvim.eval('expand("")') as string - } - newName = await window.requestInput('New name', curname) - } - if (!newName) return false - let edit = await languages.provideRenameEdits(doc.textDocument, position, newName, token) - if (token.isCancellationRequested || !edit) return false - await workspace.applyEdit(edit) - if (workspace.isVim) this.nvim.command('redraw', true) - return true - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/search.ts b/vim-config/plugins/coc.nvim/src/handler/search.ts deleted file mode 100644 index cf95850d..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/search.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Mutex } from '../util/mutex' -import { ChildProcess, spawn } from 'child_process' -import { EventEmitter } from 'events' -import path from 'path' -import readline from 'readline' -import { Range } from 'vscode-languageserver-types' -import Highlighter from '../model/highligher' -import { ansiparse } from '../util/ansiparse' -import window from '../window' -import RefactorBuffer, { FileItem, FileRange } from './refactor/buffer' -const logger = require('../util/logger')('handler-search') - -const defaultArgs = ['--color', 'ansi', '--colors', 'path:fg:black', '--colors', 'line:fg:green', '--colors', 'match:fg:red', '--no-messages', '--heading', '-n'] -const controlCode = '\x1b' - -// emit FileItem -class Task extends EventEmitter { - private process: ChildProcess - public start(cmd: string, args: string[], cwd: string): void { - this.process = spawn(cmd, args, { cwd }) - this.process.on('error', e => { - this.emit('error', e.message) - }) - const rl = readline.createInterface(this.process.stdout) - let start: number - let fileItem: FileItem - let lines: string[] = [] - let highlights: Range[] = [] - let create = true - rl.on('line', content => { - if (content.includes(controlCode)) { - let items = ansiparse(content) - if (items[0].foreground == 'black') { - fileItem = { filepath: path.join(cwd, items[0].text), ranges: [] } - return - } - let normalLine = items[0].foreground == 'green' - if (normalLine) { - let lnum = parseInt(items[0].text, 10) - 1 - let padlen = items[0].text.length + 1 - if (create) { - start = lnum - create = false - } - let line = '' - for (let item of items) { - if (item.foreground == 'red') { - let l = lnum - start - let c = line.length - padlen - highlights.push(Range.create(l, c, l, c + item.text.length)) - } - line += item.text - } - let currline = line.slice(padlen) - lines.push(currline) - } - } else { - let fileEnd = content.trim().length == 0 - if (fileItem && (fileEnd || content.trim() == '--')) { - let fileRange: FileRange = { - lines, - highlights, - start, - end: start + lines.length - } - fileItem.ranges.push(fileRange) - } - if (fileEnd) { - this.emit('item', fileItem) - fileItem = null - } - lines = [] - highlights = [] - create = true - } - }) - rl.on('close', () => { - if (fileItem) { - if (lines.length) { - let fileRange: FileRange = { - lines, - highlights, - start, - end: start + lines.length - } - fileItem.ranges.push(fileRange) - } - this.emit('item', fileItem) - } - lines = highlights = fileItem = null - this.emit('end') - }) - } - - public dispose(): void { - if (this.process) { - this.process.kill() - } - } -} - -export default class Search { - private task: Task - constructor(private nvim: Neovim, private cmd = 'rg') { - } - - public run(args: string[], cwd: string, refactorBuf: RefactorBuffer): Promise { - let { nvim, cmd } = this - let { afterContext, beforeContext } = refactorBuf.config - let argList = ['-A', afterContext.toString(), '-B', beforeContext.toString()].concat(defaultArgs, args) - let p = getPathFromArgs(args) - if (p) argList.pop() - argList.push('--', p ? path.isAbsolute(p) ? p : `./${p.replace(/^\.\//, '')}` : './') - this.task = new Task() - this.task.start(cmd, argList, cwd) - let mutex: Mutex = new Mutex() - let files = 0 - let matches = 0 - let start = Date.now() - // remaining items - let fileItems: FileItem[] = [] - const addFileItems = async () => { - if (fileItems.length == 0) return - let items = fileItems.slice() - fileItems = [] - const release = await mutex.acquire() - try { - await refactorBuf.addFileItems(items) - } catch (e) { - logger.error(e) - } - release() - } - return new Promise((resolve, reject) => { - let interval = setInterval(addFileItems, 300) - this.task.on('item', async (fileItem: FileItem) => { - files++ - matches = matches + fileItem.ranges.reduce((p, r) => p + r.highlights.length, 0) - fileItems.push(fileItem) - }) - this.task.on('error', message => { - clearInterval(interval) - window.showMessage(`Error on command "${cmd}": ${message}`, 'error') - this.task = null - reject(new Error(message)) - }) - this.task.on('end', async () => { - clearInterval(interval) - try { - await addFileItems() - const release = await mutex.acquire() - release() - this.task.removeAllListeners() - this.task = null - let buf = refactorBuf.buffer - if (buf) { - nvim.pauseNotification() - if (files == 0) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - buf.setLines(['No match found'], { start: 1, end: 2, strictIndexing: false }, true) - buf.addHighlight({ line: 1, srcId: -1, colEnd: -1, colStart: 0, hlGroup: 'Error' }).logError() - buf.setOption('modified', false, true) - } else { - let highligher = new Highlighter() - highligher.addText('Files', 'MoreMsg') - highligher.addText(': ') - highligher.addText(`${files} `, 'Number') - highligher.addText('Matches', 'MoreMsg') - highligher.addText(': ') - highligher.addText(`${matches} `, 'Number') - highligher.addText('Duration', 'MoreMsg') - highligher.addText(': ') - highligher.addText(`${Date.now() - start}ms`, 'Number') - highligher.render(buf, 1, 2) - } - buf.setOption('modified', false, true) - await nvim.resumeNotification(false, true) - } - } catch (e) { - reject(e) - return - } - resolve() - }) - }) - } - - public abort(): void { - this.task?.dispose() - } -} - -// rg requires `-- [path]` at the end -export function getPathFromArgs(args: string[]): string | undefined { - if (args.length < 2) return undefined - let len = args.length - if (args[len - 1].startsWith('-')) return undefined - if (args[len - 2].startsWith('-')) return undefined - return args[len - 1] -} diff --git a/vim-config/plugins/coc.nvim/src/handler/selectionRange.ts b/vim-config/plugins/coc.nvim/src/handler/selectionRange.ts deleted file mode 100644 index 3b014aeb..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/selectionRange.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Position, Range, SelectionRange } from 'vscode-languageserver-protocol' -import languages from '../languages' -import { HandlerDelegate } from '../types' -import { equals } from '../util/object' -import { positionInRange } from '../util/position' -import window from '../window' -import workspace from '../workspace' - -export default class SelectionRangeHandler { - private selectionRange: SelectionRange = null - constructor(private nvim: Neovim, private handler: HandlerDelegate) { - } - - public async getSelectionRanges(): Promise { - let { doc, position } = await this.handler.getCurrentState() - this.handler.checkProvier('selectionRange', doc.textDocument) - await doc.synchronize() - let selectionRanges: SelectionRange[] = await this.handler.withRequestToken('selection ranges', token => { - return languages.getSelectionRanges(doc.textDocument, [position], token) - }) - return selectionRanges - } - - public async selectRange(visualmode: string, forward: boolean): Promise { - let { nvim } = this - let { doc } = await this.handler.getCurrentState() - this.handler.checkProvier('selectionRange', doc.textDocument) - let positions: Position[] = [] - if (!forward && (!this.selectionRange || !visualmode)) return - if (visualmode) { - let range = await workspace.getSelectedRange(visualmode, doc) - positions.push(range.start, range.end) - } else { - let position = await window.getCursorPosition() - positions.push(position) - } - if (!forward) { - let curr = Range.create(positions[0], positions[1]) - let { selectionRange } = this - while (selectionRange && selectionRange.parent) { - if (equals(selectionRange.parent.range, curr)) { - break - } - selectionRange = selectionRange.parent - } - if (selectionRange && selectionRange.parent) { - await workspace.selectRange(selectionRange.range) - } - return - } - await doc.synchronize() - let selectionRanges: SelectionRange[] = await this.handler.withRequestToken('selection ranges', token => { - return languages.getSelectionRanges(doc.textDocument, positions, token) - }) - if (!selectionRanges || selectionRanges.length == 0) return - let mode = await nvim.eval('mode()') - if (mode != 'n') await nvim.eval(`feedkeys("\\", 'in')`) - let selectionRange: SelectionRange - if (selectionRanges.length == 1) { - selectionRange = selectionRanges[0] - } else { - let end = positions[1] || positions[0] - let r = Range.create(positions[0], end) - selectionRange = selectionRanges[0] - while (selectionRange) { - if (equals(r, selectionRange.range)) { - selectionRange = selectionRange.parent - continue - } - if ( - positionInRange(positions[0], selectionRange.range) == 0 && - positionInRange(end, selectionRange.range) == 0) { - break - } - selectionRange = selectionRange.parent - } - } - if (!selectionRange) return - this.selectionRange = selectionRanges[0] - await workspace.selectRange(selectionRange.range) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/semanticTokensHighlights/buffer.ts b/vim-config/plugins/coc.nvim/src/handler/semanticTokensHighlights/buffer.ts deleted file mode 100644 index e0da0c29..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/semanticTokensHighlights/buffer.ts +++ /dev/null @@ -1,301 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import debounce from 'debounce' -import { CancellationTokenSource, Range, SemanticTokens, SemanticTokensDelta, uinteger } from 'vscode-languageserver-protocol' -import languages from '../../languages' -import { SyncItem } from '../../model/bufferSync' -import Document from '../../model/document' -import { HighlightItem } from '../../types' -import workspace from '../../workspace' -const logger = require('../../util/logger')('semanticTokens-buffer') - -const SEMANTIC_HLGROUP_PREFIX = 'CocSem_' -/** - * Relative highlight - */ -interface RelativeHighlight { - group: string - deltaLine: number - deltaStartCharacter: number - length: number -} - -export interface SemanticTokensConfig { - enabled: boolean -} - -interface SemanticTokensPreviousResult { - readonly version: number - readonly resultId: string | undefined, - readonly tokens?: uinteger[], -} - -export const NAMESPACE = 'semanticTokens' - -export default class SemanticTokensBuffer implements SyncItem { - private tokenSource: CancellationTokenSource - private _highlights: HighlightItem[] - private previousResults: SemanticTokensPreviousResult - public highlight: Function & { clear(): void } - constructor( - private nvim: Neovim, - public readonly bufnr: number, - private readonly config: SemanticTokensConfig) { - this.highlight = debounce(() => { - this.doHighlight().catch(e => { - logger.error('Error on semanticTokens highlight:', e.stack) - }) - }, global.hasOwnProperty('__TEST__') ? 10 : 2000) - this.highlight() - } - - public onChange(): void { - this.cancel() - this.highlight() - } - - public async forceHighlight(): Promise { - this.cancel() - this.highlight.clear() - await this.doHighlight() - } - - /** - * Get current highlight items - */ - public get highlights(): ReadonlyArray { - return this._highlights - } - - public get enabled(): boolean { - if (!this.config.enabled) return false - let doc = workspace.getDocument(this.bufnr) - if (!doc || !doc.attached) return false - return languages.hasProvider('semanticTokens', doc.textDocument) - } - - public get previousVersion(): number | undefined { - if (!this.previousResults) return undefined - return this.previousResults.version - } - - private get buffer(): Buffer { - return this.nvim.createBuffer(this.bufnr) - } - - public checkState(): void { - if (!this.config.enabled) throw new Error('SemanticTokens highlights disabled by configuration') - let doc = workspace.getDocument(this.bufnr) - if (!doc || !doc.attached) throw new Error('Document not attached') - if (!languages.hasProvider('semanticTokens', doc.textDocument)) throw new Error('SemanticTokens provider not found, your languageserver may not support it') - } - - public setState(enabled: boolean): void { - if (enabled) { - this.highlight() - } else { - this.highlight.clear() - this.clearHighlight() - } - } - - private async doHighlight(): Promise { - if (!this.enabled) return - let doc = workspace.getDocument(this.bufnr) - const { nvim } = this - let winid = await nvim.call('bufwinid', [this.bufnr]) - // not visible on current tab - if (winid == -1) return - const curr = await this.requestHighlights(doc) - // request cancelled or can't work - if (!curr) return - if (!curr.length) { - this.clearHighlight() - return - } - let prev: HighlightItem[] = [] - if (workspace.env.updateHighlight) { - prev = (await nvim.call('coc#highlight#get_highlights', [this.bufnr, NAMESPACE])) as HighlightItem[] - } - const { highlights, lines } = this.calculateHighlightUpdates(prev, curr) - nvim.pauseNotification() - if (!workspace.env.updateHighlight) { - this.buffer.clearNamespace(NAMESPACE, 0, -1) - } else { - for (const ln of lines) { - this.buffer.clearNamespace(NAMESPACE, ln, ln + 1) - } - } - const groups: { [index: string]: Range[] } = {} - if (highlights.length) { - for (const h of highlights) { - const range = Range.create(h.lnum, h.colStart, h.lnum, h.colEnd) - groups[h.hlGroup] = groups[h.hlGroup] || [] - groups[h.hlGroup].push(range) - } - } - for (const hlGroup of Object.keys(groups)) { - this.buffer.highlightRanges(NAMESPACE, hlGroup, groups[hlGroup]) - } - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - if (workspace.isVim) nvim.command('redraw', true) - } - - private calculateHighlightUpdates(prev: HighlightItem[], curr: HighlightItem[]): { highlights: HighlightItem[], lines: Set } { - const stringCompare = Intl.Collator("en").compare - function compare(a: HighlightItem, b: HighlightItem): number { - return ( - a.lnum - b.lnum || - a.colStart - b.colStart || - a.colEnd - b.colEnd || - stringCompare(a.hlGroup, b.hlGroup) - ) - } - - prev = prev.slice().sort(compare) - curr = curr.slice().sort(compare) - - const prevByLine: Map = new Map() - for (const hl of prev) { - if (!prevByLine.has(hl.lnum)) prevByLine.set(hl.lnum, []) - prevByLine.get(hl.lnum).push(hl) - } - - const currByLine: Map = new Map() - for (const hl of curr) { - if (!currByLine.has(hl.lnum)) currByLine.set(hl.lnum, []) - currByLine.get(hl.lnum).push(hl) - } - - const lastLine = Math.max( - (prev[prev.length - 1] || { lnum: 0 }).lnum, - (curr[curr.length - 1] || { lnum: 0 }).lnum - ) - const lineNumbersToUpdate: Set = new Set() - for (let i = 0; i <= lastLine; i++) { - const ph = prevByLine.has(i) - const ch = currByLine.has(i) - if (ph !== ch) { - lineNumbersToUpdate.add(i) - continue - } else if (!ph && !ch) { - continue - } - - const pp = prevByLine.get(i) - const cc = currByLine.get(i) - - if (pp.length !== cc.length) { - lineNumbersToUpdate.add(i) - continue - } - - for (let j = 0; j < pp.length; j++) { - if (compare(pp[j], cc[j]) !== 0) { - lineNumbersToUpdate.add(i) - continue - } - } - } - - let highlights: HighlightItem[] = [] - for (const line of lineNumbersToUpdate) { - highlights = highlights.concat(currByLine.get(line) || []) - } - return { highlights, lines: lineNumbersToUpdate } - } - - /** - * Request highlights from provider, return undefined when can't request or request cancelled - * TODO use range provider as well - */ - private async requestHighlights(doc: Document, forceFull?: boolean): Promise { - const legend = languages.getLegend(doc.textDocument) - if (!legend) return undefined - this.cancel() - this.tokenSource = new CancellationTokenSource() - const { token } = this.tokenSource - const hasEditProvider = languages.hasSemanticTokensEdits(doc.textDocument) - const previousResult = forceFull ? null : this.previousResults - let result: SemanticTokens | SemanticTokensDelta - let version = doc.textDocument.version - if (hasEditProvider && previousResult?.resultId) { - result = await languages.provideDocumentSemanticTokensEdits(doc.textDocument, previousResult.resultId, token) - } else { - result = await languages.provideDocumentSemanticTokens(doc.textDocument, token) - } - this.tokenSource = null - if (token.isCancellationRequested || !result) return undefined - - let tokens: uinteger[] = [] - if (SemanticTokens.is(result)) { - tokens = result.data - } else { - tokens = previousResult.tokens - result.edits.forEach(e => { - if (e.deleteCount > 0) { - tokens.splice(e.start, e.deleteCount, ...e.data) - } else { - tokens.splice(e.start, 0, ...e.data) - } - }) - } - this.previousResults = { resultId: result.resultId, tokens, version } - const relatives: RelativeHighlight[] = [] - for (let i = 0; i < tokens.length; i += 5) { - const deltaLine = tokens[i] - const deltaStartCharacter = tokens[i + 1] - const length = tokens[i + 2] - const tokenType = tokens[i + 3] - // const tokenModifiers = legend.tokenModifiers.filter((_, m) => tokens[i + 4] & (1 << m)) - const group = SEMANTIC_HLGROUP_PREFIX + legend.tokenTypes[tokenType] - relatives.push({ - group, - deltaLine, - deltaStartCharacter, - length - }) - } - - const res: HighlightItem[] = [] - let currentLine = 0 - let currentCharacter = 0 - for (const { - group, - deltaLine, - deltaStartCharacter, - length - } of relatives) { - const lnum = currentLine + deltaLine - const colStart = deltaLine === 0 ? currentCharacter + deltaStartCharacter : deltaStartCharacter - const colEnd = colStart + length - currentLine = lnum - currentCharacter = colStart - res.push({ - hlGroup: group, - lnum, - colStart, - colEnd - }) - } - this._highlights = res - return res - } - - public clearHighlight(): void { - this.buffer.clearNamespace(NAMESPACE) - } - - public cancel(): void { - if (this.tokenSource) { - this.tokenSource.cancel() - this.tokenSource = null - } - } - - public dispose(): void { - this.highlight.clear() - this.previousResults = undefined - this.cancel() - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/semanticTokensHighlights/index.ts b/vim-config/plugins/coc.nvim/src/handler/semanticTokensHighlights/index.ts deleted file mode 100644 index f20d642a..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/semanticTokensHighlights/index.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import commands from '../../commands' -import events from '../../events' -import languages from '../../languages' -import BufferSync from '../../model/bufferSync' -import Highlighter from '../../model/highligher' -import { ConfigurationChangeEvent, HandlerDelegate } from '../../types' -import { disposeAll } from '../../util' -import window from '../../window' -import workspace from '../../workspace' -import SemanticTokensBuffer, { NAMESPACE, SemanticTokensConfig } from './buffer' -const logger = require('../../util/logger')('semanticTokens') -const headGroup = 'Statement' - -export default class SemanticTokensHighlights { - // shared with buffers - private config: SemanticTokensConfig - private disposables: Disposable[] = [] - private highlighters: BufferSync - - constructor(private nvim: Neovim, private handler: HandlerDelegate) { - this.loadConfiguration() - workspace.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables) - commands.register({ - id: 'semanticTokens.checkCurrent', - execute: async () => { - try { - let item = await this.getCurrentItem() - item.checkState() - } catch (e) { - window.showMessage(e.message, 'error') - return - } - window.showMessage('Semantic tokens provider found for current buffer', 'more') - } - }, false, 'check semantic tokens provider for current buffer') - commands.register({ - id: 'semanticTokens.clearCurrent', - execute: async () => { - let buf = await nvim.buffer - buf.clearNamespace(NAMESPACE, 0, -1) - } - }, false, 'clear semantic tokens highlights of current buffer') - commands.register({ - id: 'semanticTokens.clearAll', - execute: async () => { - let bufs = await nvim.buffers - for (let buf of bufs) { - buf.clearNamespace(NAMESPACE, 0, -1) - } - } - }, false, 'clear semantic tokens highlights of all buffers') - this.disposables.push({ - dispose: () => { - commands.unregister('semanticTokens.checkCurrentBuffer') - } - }) - // may need update highlights for buffer that becomes visible - events.on('BufEnter', bufnr => { - let item = this.highlighters.getItem(bufnr) - if (!item) return - let doc = workspace.getDocument(bufnr) - if (!doc || doc.textDocument.version == item.previousVersion) return - item.forceHighlight().catch(e => { - logger.error(`Error on semantic highlighters:`, e) - }) - }, null, this.disposables) - this.highlighters = workspace.registerBufferSync(doc => { - return new SemanticTokensBuffer(this.nvim, doc.bufnr, this.config) - }) - languages.onDidSemanticTokensRefresh(selector => { - for (let item of this.highlighters.items) { - let doc = workspace.getDocument(item.bufnr) - if (doc && workspace.match(selector, doc.textDocument)) { - item.highlight() - } - } - }, null, this.disposables) - } - - private loadConfiguration(e?: ConfigurationChangeEvent): void { - if (!e || e.affectsConfiguration('coc.preferences')) { - // let con = this.config || {} - let config = workspace.getConfiguration('coc.preferences') - let enabled = config.get('semanticTokensHighlights', true) - if (workspace.isVim && !workspace.env.textprop) { - enabled = false - } - if (this.config && enabled != this.config.enabled) { - if (this.highlighters) { - for (let buf of this.highlighters.items) { - buf.setState(enabled) - } - } - } - if (!this.config) { - this.config = { enabled } - } else { - this.config.enabled = enabled - } - } - } - - public async getCurrentItem(): Promise { - let buf = await this.nvim.buffer - let highlighter = this.highlighters.getItem(buf.id) - if (!highlighter) throw new Error('current buffer not attached') - return highlighter - } - - /** - * Force highlight of current buffer - */ - public async highlightCurrent(): Promise { - let highlighter = await this.getCurrentItem() - highlighter.checkState() - await highlighter.forceHighlight() - } - - /** - * Show semantic highlight info in temporarily buffer - */ - public async showHiglightInfo(): Promise { - if (!this.config.enabled) throw new Error('Semantic highlights is disabled by configuration.') - let item = await this.getCurrentItem() - item.checkState() - let highlights = item.highlights || [] - let highlighter = new Highlighter() - let { nvim } = this - nvim.pauseNotification() - nvim.command(`vs +setl\\ buftype=nofile __coc_semantic_highlights_${item.bufnr}__`, true) - nvim.command(`setl bufhidden=wipe noswapfile nobuflisted wrap undolevels=-1`, true) - nvim.call('bufnr', ['%'], true) - let res = await nvim.resumeNotification() - if (res[1]) throw new Error(`Error on buffer create: ${res[1]}`) - let bufnr = res[0][2] as number - highlighter.addLine('Semantic highlights info', headGroup) - highlighter.addLine('') - highlighter.addLine('The number of semantic tokens: ') - highlighter.addText(String(highlights.length), 'Number') - highlighter.addLine('') - highlighter.addLine('Semantic highlight groups used by current buffer', headGroup) - highlighter.addLine('') - const groups = [...new Set(highlights.map(({ hlGroup }) => hlGroup))] - for (const hlGroup of groups) { - highlighter.addTexts([{ text: '-', hlGroup: 'Comment' }, { text: ' ' }, { text: hlGroup, hlGroup }]) - highlighter.addLine('') - } - highlighter.addLine('Tokens types that current Language Server supported:', headGroup) - highlighter.addLine('') - let doc = workspace.getDocument(item.bufnr) - const legend = languages.getLegend(doc.textDocument) - if (legend?.tokenTypes.length) { - for (const t of [...new Set(legend.tokenTypes)]) { - highlighter.addTexts([{ text: '-', hlGroup: 'Comment' }, { text: ' ' }, { text: `CocSem_${t}`, hlGroup: `CocSem_${t}` }]) - highlighter.addLine('') - } - } else { - highlighter.addLine('No token types supported', 'Comment') - } - highlighter.addLine('Tokens modifiers that current Language Server supported:', headGroup) - highlighter.addLine('') - if (legend?.tokenModifiers.length) { - for (const t of [...new Set(legend.tokenModifiers)]) { - highlighter.addTexts([{ text: '-', hlGroup: 'Comment' }, { text: ' ' }, { text: `CocSem_${t}`, hlGroup: `CocSem_${t}` }]) - highlighter.addLine('') - } - } else { - highlighter.addLine('No token modifiers supported', 'Comment') - } - nvim.pauseNotification() - highlighter.render(nvim.createBuffer(bufnr)) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } - - public dispose(): void { - this.highlighters.dispose() - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/signature.ts b/vim-config/plugins/coc.nvim/src/handler/signature.ts deleted file mode 100644 index b1dfc795..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/signature.ts +++ /dev/null @@ -1,284 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationTokenSource, Disposable, MarkupContent, Position, SignatureHelp, SignatureHelpTriggerKind } from 'vscode-languageserver-protocol' -import events from '../events' -import languages from '../languages' -import Document from '../model/document' -import FloatFactory from '../model/floatFactory' -import { ConfigurationChangeEvent, FloatConfig, HandlerDelegate } from '../types' -import { disposeAll, isMarkdown } from '../util' -import { byteLength } from '../util/string' -import workspace from '../workspace' -const logger = require('../util/logger')('handler-signature') - -interface SignatureConfig { - wait: number - trigger: boolean - target: string - preferAbove: boolean - hideOnChange: boolean - floatConfig: FloatConfig -} - -interface SignaturePosition { - bufnr: number - lnum: number - col: number -} - -interface SignaturePart { - text: string - type: 'Label' | 'MoreMsg' | 'Normal' -} - -export default class Signature { - private timer: NodeJS.Timer - private config: SignatureConfig - private signatureFactory: FloatFactory - private lastPosition: SignaturePosition | undefined - private disposables: Disposable[] = [] - private tokenSource: CancellationTokenSource | undefined - constructor(private nvim: Neovim, private handler: HandlerDelegate) { - this.signatureFactory = new FloatFactory(nvim) - this.loadConfiguration() - this.disposables.push(this.signatureFactory) - workspace.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables) - events.on('CursorMovedI', async (bufnr, cursor) => { - let pos = this.lastPosition - if (!pos) return - // avoid close signature for valid position. - if (pos.bufnr == bufnr && pos.lnum == cursor[0] && pos.col <= cursor[1]) return - this.signatureFactory.close() - }, null, this.disposables) - events.on(['InsertLeave', 'BufEnter'], () => { - this.tokenSource?.cancel() - }, null, this.disposables) - events.on('TextChangedI', () => { - if (this.config.hideOnChange) { - this.signatureFactory.close() - } - }, null, this.disposables) - events.on('TextInsert', async (bufnr, info, character) => { - if (!this.config.trigger) return - let doc = this.getTextDocument(bufnr) - if (!doc || !languages.shouldTriggerSignatureHelp(doc.textDocument, character)) return - await this._triggerSignatureHelp(doc, { line: info.lnum - 1, character: info.pre.length }, false) - }, null, this.disposables) - } - - private getTextDocument(bufnr: number): Document | undefined { - let doc = workspace.getDocument(bufnr) - if (!doc || doc.isCommandLine || !doc.attached) return - return doc - } - - private loadConfiguration(e?: ConfigurationChangeEvent): void { - if (!e || e.affectsConfiguration('signature')) { - let config = workspace.getConfiguration('signature') - let target = config.get('target', 'float') - if (target == 'float' && !workspace.floatSupported) { - target = 'echo' - } - this.config = { - target, - floatConfig: config.get('floatConfig', {}), - trigger: config.get('enable', true), - wait: Math.max(config.get('triggerSignatureWait', 500), 200), - preferAbove: config.get('preferShownAbove', true), - hideOnChange: config.get('hideOnTextChange', false), - } - } - } - - public async triggerSignatureHelp(): Promise { - let { doc, position, mode } = await this.handler.getCurrentState() - if (!languages.hasProvider('signature', doc.textDocument)) return false - let offset = 0 - let character = position.character - if (mode == 's') { - let placeholder = await this.nvim.getVar('coc_last_placeholder') as any - if (placeholder) { - let { start, end, bufnr } = placeholder - if (bufnr == doc.bufnr && start.line == end.line && start.line == position.line) { - position = Position.create(start.line, start.character) - offset = character - position.character - } - } - } - return await this._triggerSignatureHelp(doc, position, true, offset) - } - - private async _triggerSignatureHelp(doc: Document, position: Position, invoke = true, offset = 0): Promise { - this.tokenSource?.cancel() - let tokenSource = this.tokenSource = new CancellationTokenSource() - let token = tokenSource.token - token.onCancellationRequested(() => { - tokenSource.dispose() - this.tokenSource = undefined - }) - let { target } = this.config - let timer = this.timer = setTimeout(() => { - tokenSource.cancel() - }, this.config.wait) - await doc.patchChange(true) - let signatureHelp = await languages.getSignatureHelp(doc.textDocument, position, token, { - isRetrigger: this.signatureFactory.checkRetrigger(doc.bufnr), - triggerKind: invoke ? SignatureHelpTriggerKind.Invoked : SignatureHelpTriggerKind.TriggerCharacter - }) - clearTimeout(timer) - if (token.isCancellationRequested) return false - if (!signatureHelp || signatureHelp.signatures.length == 0) { - this.signatureFactory.close() - return false - } - let { activeSignature, signatures } = signatureHelp - if (activeSignature) { - // make active first - let [active] = signatures.splice(activeSignature, 1) - if (active) signatures.unshift(active) - } - if (target == 'echo') { - this.echoSignature(signatureHelp) - } else { - await this.showSignatureHelp(doc, position, signatureHelp, offset) - } - return true - } - - private async showSignatureHelp(doc: Document, position: Position, signatureHelp: SignatureHelp, offset: number): Promise { - let { signatures, activeParameter } = signatureHelp - let paramDoc: string | MarkupContent = null - let startOffset = offset - let docs = signatures.reduce((p, c, idx) => { - let activeIndexes: [number, number] = null - let nameIndex = c.label.indexOf('(') - if (idx == 0 && activeParameter != null) { - let active = c.parameters?.[activeParameter] - if (active) { - let after = c.label.slice(nameIndex == -1 ? 0 : nameIndex) - paramDoc = active.documentation - if (typeof active.label === 'string') { - let str = after.slice(0) - let ms = str.match(new RegExp('\\b' + active.label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b')) - let index = ms ? ms.index : str.indexOf(active.label) - if (index != -1) { - activeIndexes = [ - index + nameIndex, - index + active.label.length + nameIndex - ] - } - } else { - activeIndexes = active.label - } - } - } - if (activeIndexes == null) { - activeIndexes = [nameIndex + 1, nameIndex + 1] - } - if (offset == startOffset) { - offset = offset + activeIndexes[0] + 1 - } - p.push({ - content: c.label, - filetype: doc.filetype, - active: activeIndexes - }) - if (paramDoc) { - let content = typeof paramDoc === 'string' ? paramDoc : paramDoc.value - if (content.trim().length) { - p.push({ - content, - filetype: isMarkdown(c.documentation) ? 'markdown' : 'txt' - }) - } - } - if (idx == 0 && c.documentation) { - let { documentation } = c - let content = typeof documentation === 'string' ? documentation : documentation.value - if (content.trim().length) { - p.push({ - content, - filetype: isMarkdown(c.documentation) ? 'markdown' : 'txt' - }) - } - } - return p - }, []) - let content = doc.getline(position.line, false).slice(0, position.character) - this.lastPosition = { bufnr: doc.bufnr, lnum: position.line + 1, col: byteLength(content) + 1 } - const excludeImages = workspace.getConfiguration('coc.preferences').get('excludeImageLinksInMarkdownDocument') - let config = this.signatureFactory.applyFloatConfig({ - preferTop: this.config.preferAbove, - autoHide: false, - offsetX: offset, - modes: ['i', 'ic', 's'], - excludeImages - }, this.config.floatConfig) - await this.signatureFactory.show(docs, config) - } - - private echoSignature(signatureHelp: SignatureHelp): void { - let { signatures, activeParameter } = signatureHelp - let columns = workspace.env.columns - signatures = signatures.slice(0, workspace.env.cmdheight) - let signatureList: SignaturePart[][] = [] - for (let signature of signatures) { - let parts: SignaturePart[] = [] - let { label } = signature - label = label.replace(/\n/g, ' ') - if (label.length >= columns - 16) { - label = label.slice(0, columns - 16) + '...' - } - let nameIndex = label.indexOf('(') - if (nameIndex == -1) { - parts = [{ text: label, type: 'Normal' }] - } else { - parts.push({ - text: label.slice(0, nameIndex), - type: 'Label' - }) - let after = label.slice(nameIndex) - if (signatureList.length == 0 && activeParameter != null) { - let active = signature.parameters?.[activeParameter] - if (active) { - let start: number - let end: number - if (typeof active.label === 'string') { - let str = after.slice(0) - let ms = str.match(new RegExp('\\b' + active.label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b')) - let idx = ms ? ms.index : str.indexOf(active.label) - if (idx == -1) { - parts.push({ text: after, type: 'Normal' }) - } else { - start = idx - end = idx + active.label.length - } - } else { - [start, end] = active.label - start = start - nameIndex - end = end - nameIndex - } - if (start != null && end != null) { - parts.push({ text: after.slice(0, start), type: 'Normal' }) - parts.push({ text: after.slice(start, end), type: 'MoreMsg' }) - parts.push({ text: after.slice(end), type: 'Normal' }) - } - } - } else { - parts.push({ - text: after, - type: 'Normal' - }) - } - } - signatureList.push(parts) - } - this.nvim.callTimer('coc#util#echo_signatures', [signatureList], true) - } - - public dispose(): void { - disposeAll(this.disposables) - if (this.timer) { - clearTimeout(this.timer) - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/symbols/buffer.ts b/vim-config/plugins/coc.nvim/src/handler/symbols/buffer.ts deleted file mode 100644 index 6f66474c..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/symbols/buffer.ts +++ /dev/null @@ -1,89 +0,0 @@ -import debounce from 'debounce' -import { CancellationTokenSource, Disposable, DocumentSymbol, Emitter, Event, SymbolTag, TextDocument } from 'vscode-languageserver-protocol' -import languages from '../../languages' -import { SyncItem } from '../../model/bufferSync' -import { disposeAll } from '../../util' -import workspace from '../../workspace' -import { isDocumentSymbols } from './util' - -export default class SymbolsBuffer implements SyncItem { - private disposables: Disposable[] = [] - public fetchSymbols: (() => void) & { clear(): void } - private autoUpdate = false - private version: number - private symbols: DocumentSymbol[] - private tokenSource: CancellationTokenSource - private readonly _onDidUpdate = new Emitter() - public readonly onDidUpdate: Event = this._onDidUpdate.event - constructor(public readonly bufnr: number) { - this.fetchSymbols = debounce(() => { - this._fetchSymbols().logError() - }, global.hasOwnProperty('__TEST__') ? 10 : 500) - } - - /** - * Enable autoUpdate when invoked. - */ - public async getSymbols(): Promise { - let doc = workspace.getDocument(this.bufnr) - if (!doc) return [] - await doc.patchChange() - this.autoUpdate = true - // refresh for empty symbols since some languages server could be buggy first time. - if (doc.version == this.version && this.symbols?.length) return this.symbols - this.cancel() - await this._fetchSymbols() - return this.symbols - } - - public onChange(): void { - this.cancel() - if (this.autoUpdate) { - this.fetchSymbols() - } - } - - private get textDocument(): TextDocument | undefined { - return workspace.getDocument(this.bufnr)?.textDocument - } - - private async _fetchSymbols(): Promise { - let { textDocument } = this - if (!textDocument) return - let { version } = textDocument - let tokenSource = this.tokenSource = new CancellationTokenSource() - let { token } = tokenSource - let symbols = await languages.getDocumentSymbol(textDocument, token) - this.tokenSource = undefined - if (symbols == null || token.isCancellationRequested) return - let res: DocumentSymbol[] - if (isDocumentSymbols(symbols)) { - res = symbols - } else { - res = symbols.map(o => { - let sym = DocumentSymbol.create(o.name, '', o.kind, o.location.range, o.location.range) - if (o.deprecated) sym.tags = [SymbolTag.Deprecated] - return sym - }) - } - this.version = version - this.symbols = res - this._onDidUpdate.fire(res) - } - - public cancel(): void { - this.fetchSymbols.clear() - if (this.tokenSource) { - this.tokenSource.cancel() - this.tokenSource.dispose() - this.tokenSource = null - } - } - - public dispose(): void { - this.cancel() - this.symbols = undefined - this._onDidUpdate.dispose() - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/symbols/index.ts b/vim-config/plugins/coc.nvim/src/handler/symbols/index.ts deleted file mode 100644 index d4fba17c..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/symbols/index.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationTokenSource, Disposable, Range, SymbolInformation } from 'vscode-languageserver-protocol' -import events from '../../events' -import languages from '../../languages' -import BufferSync from '../../model/bufferSync' -import { HandlerDelegate } from '../../types' -import { disposeAll } from '../../util/index' -import { equals } from '../../util/object' -import { positionInRange, rangeInRange } from '../../util/position' -import window from '../../window' -import workspace from '../../workspace' -import SymbolsBuffer from './buffer' -import Outline from './outline' -import { convertSymbols, SymbolInfo } from './util' - -export default class Symbols { - private buffers: BufferSync - private disposables: Disposable[] = [] - private outline: Outline - - constructor( - private nvim: Neovim, - private handler: HandlerDelegate - ) { - this.buffers = workspace.registerBufferSync(doc => { - if (doc.buftype != '') return undefined - return new SymbolsBuffer(doc.bufnr) - }) - this.outline = new Outline(nvim, this.buffers, handler) - events.on('CursorHold', async (bufnr: number) => { - if (!this.functionUpdate || !this.buffers.getItem(bufnr)) return - await this.getCurrentFunctionSymbol(bufnr) - }, null, this.disposables) - events.on('InsertEnter', (bufnr: number) => { - let buf = this.buffers.getItem(bufnr) - if (buf) buf.cancel() - }, null, this.disposables) - } - - public get functionUpdate(): boolean { - let config = workspace.getConfiguration('coc.preferences') - return config.get('currentFunctionSymbolAutoUpdate', false) - } - - public get labels(): { [key: string]: string } { - return workspace.getConfiguration('suggest').get('completionItemKindLabels', {}) - } - - public async getWorkspaceSymbols(input: string): Promise { - this.handler.checkProvier('workspaceSymbols', null) - let tokenSource = new CancellationTokenSource() - return await languages.getWorkspaceSymbols(input, tokenSource.token) - } - - public async resolveWorkspaceSymbol(symbolInfo: SymbolInformation): Promise { - if (symbolInfo.location?.uri) return symbolInfo - let tokenSource = new CancellationTokenSource() - return await languages.resolveWorkspaceSymbol(symbolInfo, tokenSource.token) - } - - public async getDocumentSymbols(bufnr: number): Promise { - let buf = this.buffers.getItem(bufnr) - if (!buf) return - let res = await buf.getSymbols() - return res ? convertSymbols(res) : undefined - } - - public async getCurrentFunctionSymbol(bufnr?: number): Promise { - if (!bufnr) bufnr = await this.nvim.call('bufnr', ['%']) - let doc = workspace.getDocument(bufnr) - if (!doc || !doc.attached) return - if (!languages.hasProvider('documentSymbol', doc.textDocument)) return - let position = await window.getCursorPosition() - let symbols = await this.getDocumentSymbols(bufnr) - let buffer = this.nvim.createBuffer(bufnr) - if (!symbols || symbols.length === 0) { - buffer.setVar('coc_current_function', '', true) - this.nvim.call('coc#util#do_autocmd', ['CocStatusChange'], true) - return '' - } - symbols = symbols.filter(s => [ - 'Class', - 'Method', - 'Function', - 'Struct', - ].includes(s.kind)) - let functionName = '' - for (let sym of symbols.reverse()) { - if (sym.range - && positionInRange(position, sym.range) == 0 - && !sym.text.endsWith(') callback')) { - functionName = sym.text - let label = this.labels[sym.kind.toLowerCase()] - if (label) functionName = `${label} ${functionName}` - break - } - } - if (this.functionUpdate) { - buffer.setVar('coc_current_function', functionName, true) - this.nvim.call('coc#util#do_autocmd', ['CocStatusChange'], true) - } - return functionName - } - - /* - * supportedSymbols must be string values of symbolKind - */ - public async selectSymbolRange(inner: boolean, visualmode: string, supportedSymbols: string[]): Promise { - let { doc } = await this.handler.getCurrentState() - this.handler.checkProvier('documentSymbol', doc.textDocument) - let range: Range - if (visualmode) { - range = await workspace.getSelectedRange(visualmode, doc) - } else { - let pos = await window.getCursorPosition() - range = Range.create(pos, pos) - } - let symbols = await this.getDocumentSymbols(doc.bufnr) - if (!symbols || symbols.length === 0) { - window.showMessage('No symbols found', 'warning') - return - } - symbols = symbols.filter(s => supportedSymbols.includes(s.kind)) - let selectRange: Range - for (let sym of symbols.reverse()) { - if (sym.range && !equals(sym.range, range) && rangeInRange(range, sym.range)) { - selectRange = sym.range - break - } - } - if (inner && selectRange) { - let { start, end } = selectRange - let line = doc.getline(start.line + 1) - let endLine = doc.getline(end.line - 1) - selectRange = Range.create(start.line + 1, line.match(/^\s*/)[0].length, end.line - 1, endLine.length) - } - if (selectRange) { - await workspace.selectRange(selectRange) - } else if (['v', 'V', '\x16'].includes(visualmode)) { - await this.nvim.command('normal! gv') - } - } - - public async showOutline(keep?: number): Promise { - await this.outline.show(keep) - } - - public async hideOutline(): Promise { - await this.outline.hide() - } - - public hasOutline(bufnr: number): boolean { - return this.outline.has(bufnr) - } - - public dispose(): void { - this.outline.dispose() - this.buffers.dispose() - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/symbols/outline.ts b/vim-config/plugins/coc.nvim/src/handler/symbols/outline.ts deleted file mode 100644 index 3f8b8aee..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/symbols/outline.ts +++ /dev/null @@ -1,319 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import debounce from 'debounce' -import { CodeActionKind, Disposable, DocumentSymbol, Range, SymbolKind, SymbolTag } from 'vscode-languageserver-protocol' -import events from '../../events' -import languages from '../../languages' -import BufferSync from '../../model/bufferSync' -import BasicDataProvider, { TreeNode } from '../../tree/BasicDataProvider' -import BasicTreeView from '../../tree/TreeView' -import { ConfigurationChangeEvent, HandlerDelegate } from '../../types' -import { disposeAll } from '../../util' -import { comparePosition, positionInRange } from '../../util/position' -import window from '../../window' -import workspace from '../../workspace' -import SymbolsBuffer from './buffer' -const logger = require('../../util/logger')('symbols-outline') - -// Support expand level. -interface OutlineNode extends TreeNode { - kind: SymbolKind - range: Range - selectRange: Range -} - -interface OutlineConfig { - splitCommand: string - followCursor: boolean - keepWindow: boolean - expandLevel: number - checkBufferSwitch: boolean - showLineNumber: boolean - codeActionKinds: CodeActionKind[] - sortBy: 'position' | 'name' | 'category' -} - -/** - * Manage TreeViews and Providers of outline. - */ -export default class SymbolsOutline { - private providersMap: Map> = new Map() - private treeViews: WeakMap, BasicTreeView[]> = new WeakMap() - private originalWins: WeakMap, number> = new WeakMap() - private config: OutlineConfig - private disposables: Disposable[] = [] - constructor( - private nvim: Neovim, - private buffers: BufferSync, - private handler: HandlerDelegate - ) { - this.loadConfiguration() - workspace.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables) - events.on('BufUnload', async bufnr => { - let provider = this.providersMap.get(bufnr) - if (!provider) return - this.providersMap.delete(bufnr) - provider.dispose() - let views = this.treeViews.get(provider) - this.treeViews.delete(provider) - for (let view of views) { - if (!view.visible) continue - let winid = this.originalWins.get(view) - if (winid && this.config.checkBufferSwitch) { - // check if original window exists - let nr = await nvim.call('win_id2win', [winid]) - if (nr) { - let win = nvim.createWindow(view.windowId) - // buffer could be recreated. - win.setVar('target_bufnr', -1, true) - let timer = setTimeout(() => { - if (view.visible) view.dispose() - }, 200) - this.disposables.push({ - dispose: () => { - clearTimeout(timer) - } - }) - continue - } - } - view.dispose() - } - }, null, this.disposables) - events.on('BufEnter', debounce(() => { - void this._onBufEnter() - }, global.hasOwnProperty('__TEST__') ? 100 : 300), null, this.disposables) - events.on('CursorHold', async bufnr => { - if (!this.config.followCursor) return - let provider = this.providersMap.get(bufnr) - if (!provider) return - let views = this.treeViews.get(provider) - if (!views || !views.length) return - let winid = await this.nvim.call('coc#window#find', ['cocViewId', 'OUTLINE']) - if (winid == -1) return - let view = views.find(o => o.windowId == winid) - if (!view) return - let pos = await window.getCursorPosition() - let curr: OutlineNode - let checkNode = (node: OutlineNode): boolean => { - if (positionInRange(pos, node.range) != 0) return false - curr = node - if (Array.isArray(node.children)) { - for (let n of node.children) { - if (checkNode(n)) break - } - } - return true - } - let nodes = await Promise.resolve(provider.getChildren()) - for (let n of nodes) { - if (checkNode(n)) break - } - if (curr) await view.reveal(curr) - }, null, this.disposables) - } - - private async _onBufEnter(): Promise { - if (!this.config.checkBufferSwitch) return - let [curr, bufnr, winid] = await this.nvim.eval(`[win_getid(),bufnr('%'),coc#window#find('cocViewId', 'OUTLINE')]`) as [number, number, number] - if (curr == winid || winid == -1) return - if (!this.buffers.getItem(bufnr)) return - let win = this.nvim.createWindow(winid) - let target = await win.getVar('target_bufnr') - if (target == bufnr) return - await this.show(1) - } - - private loadConfiguration(e?: ConfigurationChangeEvent): void { - if (!e || e.affectsConfiguration('outline')) { - let c = workspace.getConfiguration('outline') - this.config = { - splitCommand: c.get('splitCommand'), - followCursor: c.get('followCursor'), - keepWindow: c.get('keepWindow'), - expandLevel: c.get('expandLevel'), - checkBufferSwitch: c.get('checkBufferSwitch'), - sortBy: c.get<'position' | 'name' | 'category'>('sortBy'), - showLineNumber: c.get('showLineNumber'), - codeActionKinds: c.get('codeActionKinds') - } - } - } - - private convertSymbolToNode(documentSymbol: DocumentSymbol, sortFn: (a: OutlineNode, b: OutlineNode) => number): OutlineNode { - return { - label: documentSymbol.name, - tooltip: documentSymbol.detail, - description: this.config.showLineNumber ? `${documentSymbol.selectionRange.start.line + 1}` : undefined, - icon: this.handler.getIcon(documentSymbol.kind), - deprecated: documentSymbol.tags?.includes(SymbolTag.Deprecated), - kind: documentSymbol.kind, - range: documentSymbol.range, - selectRange: documentSymbol.selectionRange, - children: Array.isArray(documentSymbol.children) ? documentSymbol.children.map(o => { - return this.convertSymbolToNode(o, sortFn) - }).sort(sortFn) : undefined - } - } - - private setMessage(provider: BasicDataProvider, msg: string | undefined): void { - let views = this.treeViews.get(provider) - if (views) { - views.forEach(view => { - view.message = msg - }) - } - } - - private createProvider(buf: SymbolsBuffer): BasicDataProvider { - let { bufnr } = buf - let { sortBy } = this.config - let { nvim } = this - let sortFn = (a: OutlineNode, b: OutlineNode): number => { - if (sortBy === 'name') { - return a.label < b.label ? -1 : 1 - } - if (sortBy === 'category') { - if (a.kind == b.kind) return a.label < b.label ? -1 : 1 - return a.kind - b.kind - } - return comparePosition(a.selectRange.start, b.selectRange.start) - } - let convertSymbols = (symbols: DocumentSymbol[]): OutlineNode[] => { - return symbols.map(s => this.convertSymbolToNode(s, sortFn)).sort(sortFn) - } - let disposable: Disposable - let provider = new BasicDataProvider({ - expandLevel: this.config.expandLevel, - provideData: async () => { - let doc = workspace.getDocument(bufnr) - if (!languages.hasProvider('documentSymbol', doc.textDocument)) { - throw new Error('Document symbol provider not found') - } - this.setMessage(provider, 'Loading document symbols') - let arr = await buf.getSymbols() - if (!arr || arr.length == 0) { - // server may return empty symbols on buffer initialize, throw error to force reload. - throw new Error('Empty symbols returned from language server. ') - } - disposable = buf.onDidUpdate(symbols => { - provider.update(convertSymbols(symbols)) - }) - this.setMessage(provider, undefined) - return convertSymbols(arr) - }, - handleClick: async item => { - let winnr = await nvim.call('bufwinnr', [bufnr]) - if (winnr == -1) return - nvim.pauseNotification() - nvim.command(`${winnr}wincmd w`, true) - let pos = item.selectRange.start - nvim.call('coc#cursor#move_to', [pos.line, pos.character], true) - nvim.command(`normal! zz`, true) - let buf = nvim.createBuffer(bufnr) - buf.highlightRanges('outline-hover', 'CocHoverRange', [item.selectRange]) - nvim.command('redraw', true) - await nvim.resumeNotification() - setTimeout(() => { - buf.clearNamespace('outline-hover') - nvim.command('redraw', true) - }, global.hasOwnProperty('__TEST__') ? 10 : 300) - }, - resolveActions: async (_, element) => { - let winnr = await nvim.call('bufwinnr', [bufnr]) - if (winnr == -1) return - let doc = workspace.getDocument(bufnr) - let actions = await this.handler.getCodeActions(doc, element.range, this.config.codeActionKinds) - let arr = actions.map(o => { - return { - title: o.title, - handler: async () => { - let position = element.range.start - await nvim.command(`${winnr}wincmd w`) - await this.nvim.call('coc#cursor#move_to', [position.line, position.character]) - await this.handler.applyCodeAction(o) - } - } - }) - return [...arr, { - title: 'Visual Select', - handler: async item => { - await nvim.command(`${winnr}wincmd w`) - await workspace.selectRange(item.range) - } - }] - }, - onDispose: () => { - this.providersMap.delete(buf.bufnr) - if (disposable) disposable.dispose() - } - }) - return provider - } - - /** - * Create outline view. - */ - public async show(keep?: number): Promise { - await workspace.document - let [bufnr, winid] = await this.nvim.eval('[bufnr("%"),win_getid()]') as [number, number] - let buf = this.buffers.getItem(bufnr) - if (!buf) throw new Error('Document not attached') - let provider = this.providersMap.get(bufnr) - if (!provider) { - provider = this.createProvider(buf) - this.providersMap.set(bufnr, provider) - } - let treeView = new BasicTreeView('OUTLINE', { - enableFilter: true, - treeDataProvider: provider, - }) - this.originalWins.set(treeView, winid) - let arr = this.treeViews.get(provider) || [] - arr.push(treeView) - this.treeViews.set(provider, arr) - treeView.onDidChangeVisibility(({ visible }) => { - if (visible || !this.treeViews.has(provider)) return - let arr = this.treeViews.get(provider) || [] - arr = arr.filter(s => s !== treeView) - this.originalWins.delete(treeView) - if (arr.length) { - this.treeViews.set(provider, arr) - return - } - provider.dispose() - this.treeViews.delete(provider) - }) - await treeView.show(this.config.splitCommand) - if (treeView.windowId) { - let win = this.nvim.createWindow(treeView.windowId) - win.setVar('target_bufnr', bufnr, true) - } - if (keep == 1 || (keep === undefined && this.config.keepWindow)) { - await this.nvim.command('wincmd p') - } - } - - public has(bufnr: number): boolean { - return this.providersMap.has(bufnr) - } - - /** - * Hide outline of current tab. - */ - public async hide(): Promise { - let winid = await this.nvim.call('coc#window#find', ['cocViewId', 'OUTLINE']) as number - if (winid == -1) return - await this.nvim.call('coc#window#close', [winid]) - } - - public dispose(): void { - for (let provider of this.providersMap.values()) { - provider.dispose() - for (let view of this.treeViews.get(provider)) { - view.dispose() - } - } - this.providersMap.clear() - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/handler/symbols/util.ts b/vim-config/plugins/coc.nvim/src/handler/symbols/util.ts deleted file mode 100644 index d5f03bec..00000000 --- a/vim-config/plugins/coc.nvim/src/handler/symbols/util.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { DocumentSymbol, Range, SymbolInformation } from 'vscode-languageserver-protocol' -import { getSymbolKind } from '../../util/convert' -import { comparePosition } from '../../util/position' - -export interface SymbolInfo { - filepath?: string - lnum: number - col: number - text: string - kind: string - level?: number - containerName?: string - range: Range - selectionRange?: Range -} - -export function convertSymbols(symbols: DocumentSymbol[]): SymbolInfo[] { - let res: SymbolInfo[] = [] - let arr = symbols.slice() - arr.sort(sortDocumentSymbols) - arr.forEach(s => addDocumentSymbol(res, s, 0)) - return res -} - -export function sortDocumentSymbols(a: DocumentSymbol, b: DocumentSymbol): number { - let ra = a.selectionRange - let rb = b.selectionRange - return comparePosition(ra.start, rb.start) -} - -export function addDocumentSymbol(res: SymbolInfo[], sym: DocumentSymbol, level: number): void { - let { name, selectionRange, kind, children, range } = sym - let { start } = selectionRange || range - res.push({ - col: start.character + 1, - lnum: start.line + 1, - text: name, - level, - kind: getSymbolKind(kind), - range, - selectionRange - }) - if (children && children.length) { - children.sort(sortDocumentSymbols) - for (let sym of children) { - addDocumentSymbol(res, sym, level + 1) - } - } -} - -function isDocumentSymbol(a: DocumentSymbol | SymbolInformation): a is DocumentSymbol { - return a && !a.hasOwnProperty('location') -} - -export function isDocumentSymbols(a: DocumentSymbol[] | SymbolInformation[]): a is DocumentSymbol[] { - return isDocumentSymbol(a[0]) -} diff --git a/vim-config/plugins/coc.nvim/src/index.ts b/vim-config/plugins/coc.nvim/src/index.ts deleted file mode 100644 index 96525e19..00000000 --- a/vim-config/plugins/coc.nvim/src/index.ts +++ /dev/null @@ -1,72 +0,0 @@ -import commands from './commands' -import events from './events' -import languages from './languages' -import Mru from './model/mru' -import FloatFactory from './model/floatFactory' -import fetch from './model/fetch' -import download from './model/download' -import Highligher from './model/highligher' -import services from './services' -import sources from './sources/index' -import workspace from './workspace' -import window from './window' -import extensions from './extensions' -import listManager from './list/manager' -import snippetManager from './snippets/manager' -import { SnippetString } from './snippets/string' -import diagnosticManager from './diagnostic/manager' -import { ansiparse } from './util/ansiparse' -import Watchman from './watchman' -import BasicList from './list/basic' -import { Mutex } from './util/mutex' -import { URI } from 'vscode-uri' -import { Neovim, Buffer, Window } from '@chemzqm/neovim' -import { - CodeActionKind, - Disposable, - Position, - Range, - TextEdit, - RequestType, - RequestType0, - NotificationType, - NotificationType0, - Event, - CancellationToken, - CancellationTokenSource, - Emitter, - Diagnostic, - DiagnosticSeverity, - CompletionItemKind, - InsertTextFormat, - Location, - LocationLink, - MarkupKind, - FileChangeType, - SignatureHelpTriggerKind, - SymbolKind, - DocumentHighlightKind, - CompletionTriggerKind, - DiagnosticTag, - ProgressType, -} from 'vscode-languageserver-protocol' - -export { PatternType, SourceType, MessageLevel, ConfigurationTarget, ServiceStat, FileType } from './types' -export { - State, - NullLogger, - ClientState, - CloseAction, - ErrorAction, - TransportKind, - SettingMonitor, - LanguageClient, - MessageTransports, - TextDocumentFeature, - RevealOutputChannelOn, -} from './language-client' - -export { Neovim, MarkupKind, DiagnosticTag, DocumentHighlightKind, SymbolKind, SignatureHelpTriggerKind, FileChangeType, CodeActionKind, Diagnostic, DiagnosticSeverity, CompletionItemKind, InsertTextFormat, Location, LocationLink, CancellationTokenSource, CancellationToken, ProgressType, Position, Range, TextEdit, RequestType, RequestType0, NotificationType, NotificationType0, Buffer, Window, Highligher, Mru, Watchman, URI as Uri, Disposable, Event, Emitter, FloatFactory, fetch, download, ansiparse } -export { workspace, window, CompletionTriggerKind, snippetManager, SnippetString, events, services, commands, sources, languages, diagnosticManager, extensions, listManager, BasicList, Mutex } -export { disposeAll, concurrent, watchFile, wait, runCommand, isRunning, executable } from './util' -export { TreeItem, TreeItemCollapsibleState } from './tree/index' diff --git a/vim-config/plugins/coc.nvim/src/language-client/LICENSE.txt b/vim-config/plugins/coc.nvim/src/language-client/LICENSE.txt deleted file mode 100644 index 9afc63d4..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/LICENSE.txt +++ /dev/null @@ -1,23 +0,0 @@ -MIT License - -Copyright (c) 2015 - present Microsoft Corporation - -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vim-config/plugins/coc.nvim/src/language-client/callHierarchy.ts b/vim-config/plugins/coc.nvim/src/language-client/callHierarchy.ts deleted file mode 100644 index 92199de8..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/callHierarchy.ts +++ /dev/null @@ -1,122 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -'use strict' - -import { - CallHierarchyClientCapabilities, CallHierarchyIncomingCall, CallHierarchyIncomingCallsRequest, CallHierarchyItem, CallHierarchyOptions, CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsRequest, CallHierarchyPrepareRequest, CallHierarchyRegistrationOptions, CancellationToken, ClientCapabilities, Disposable, DocumentSelector, Position, ServerCapabilities -} from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import languages from '../languages' -import { CallHierarchyProvider, ProviderResult } from '../provider' -import { BaseLanguageClient, TextDocumentFeature } from './client' -import { asTextDocumentPositionParams } from './utils/converter' - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = {} as any - } - return target[key] -} - -export interface PrepareCallHierarchySignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult -} - -export interface CallHierarchyIncomingCallsSignature { - (this: void, item: CallHierarchyItem, token: CancellationToken): ProviderResult -} - -export interface CallHierarchyOutgoingCallsSignature { - (this: void, item: CallHierarchyItem, token: CancellationToken): ProviderResult -} - -/** - * Call hierarchy middleware - * - * @since 3.16.0 - */ -export interface CallHierarchyMiddleware { - prepareCallHierarchy?: (this: void, document: TextDocument, positions: Position, token: CancellationToken, next: PrepareCallHierarchySignature) => ProviderResult - provideCallHierarchyIncomingCalls?: (this: void, item: CallHierarchyItem, token: CancellationToken, next: CallHierarchyIncomingCallsSignature) => ProviderResult - provideCallHierarchyOutgoingCalls?: (this: void, item: CallHierarchyItem, token: CancellationToken, next: CallHierarchyOutgoingCallsSignature) => ProviderResult -} - -export class CallHierarchyFeature extends TextDocumentFeature { - constructor(client: BaseLanguageClient) { - super(client, CallHierarchyPrepareRequest.type) - } - - public fillClientCapabilities(cap: ClientCapabilities): void { - const capabilities: ClientCapabilities & CallHierarchyClientCapabilities = cap as ClientCapabilities & CallHierarchyClientCapabilities - const capability = ensure(ensure(capabilities, 'textDocument')!, 'callHierarchy')! - capability.dynamicRegistration = true - } - - public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { - const [id, options] = this.getRegistration(documentSelector, capabilities.callHierarchyProvider) - if (!id || !options) { - return - } - this.register({ id, registerOptions: options }) - } - - protected registerLanguageProvider(options: CallHierarchyRegistrationOptions): [Disposable, CallHierarchyProvider] { - const provider: CallHierarchyProvider = { - prepareCallHierarchy: (document: TextDocument, position: Position, token: CancellationToken) => { - const client = this._client - const prepareCallHierarchy: PrepareCallHierarchySignature = (document, position, token) => { - const params = asTextDocumentPositionParams(document, position) - return client.sendRequest(CallHierarchyPrepareRequest.type, params, token).then( - res => res, - error => { - return client.handleFailedRequest(CallHierarchyPrepareRequest.type, token, error, null) - } - ) - } - - const middleware = client.clientOptions.middleware - return middleware.prepareCallHierarchy - ? middleware.prepareCallHierarchy(document, position, token, prepareCallHierarchy) - : prepareCallHierarchy(document, position, token) - }, - - provideCallHierarchyIncomingCalls: (item: CallHierarchyItem, token: CancellationToken) => { - const client = this._client - const provideCallHierarchyIncomingCalls: CallHierarchyIncomingCallsSignature = (item, token) => { - return client.sendRequest(CallHierarchyIncomingCallsRequest.type, { item }, token).then( - res => res, - error => { - return client.handleFailedRequest(CallHierarchyIncomingCallsRequest.type, token, error, null) - } - ) - } - - const middleware = client.clientOptions.middleware - return middleware.provideCallHierarchyIncomingCalls - ? middleware.provideCallHierarchyIncomingCalls(item, token, provideCallHierarchyIncomingCalls) - : provideCallHierarchyIncomingCalls(item, token) - }, - - provideCallHierarchyOutgoingCalls: (item: CallHierarchyItem, token: CancellationToken) => { - const client = this._client - const provideCallHierarchyOutgoingCalls: CallHierarchyOutgoingCallsSignature = (item, token) => { - return client.sendRequest(CallHierarchyOutgoingCallsRequest.type, { item }, token).then( - res => res, - error => { - return client.handleFailedRequest(CallHierarchyOutgoingCallsRequest.type, token, error, null) - } - ) - } - - const middleware = client.clientOptions.middleware - return middleware.provideCallHierarchyOutgoingCalls - ? middleware.provideCallHierarchyOutgoingCalls(item, token, provideCallHierarchyOutgoingCalls) - : provideCallHierarchyOutgoingCalls(item, token) - } - } - - return [languages.registerCallHierarchyProvider(options.documentSelector, provider), provider] - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/client.ts b/vim-config/plugins/coc.nvim/src/language-client/client.ts deleted file mode 100644 index 1b7d0d21..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/client.ts +++ /dev/null @@ -1,4352 +0,0 @@ -/* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -/* eslint-disable */ -import path from 'path' -import { ApplyWorkspaceEditParams, CompletionItemTag, ApplyWorkspaceEditRequest, ApplyWorkspaceEditResponse, CancellationToken, ClientCapabilities, CodeAction, CodeActionContext, CodeActionKind, CodeActionOptions, CodeActionParams, CodeActionRegistrationOptions, CodeActionRequest, CodeLens, CodeLensOptions, CodeLensRegistrationOptions, CodeLensRequest, CodeLensResolveRequest, Command, CompletionContext, CompletionItem, CompletionItemKind, CompletionList, CompletionOptions, CompletionRegistrationOptions, CompletionRequest, CompletionResolveRequest, createProtocolConnection, DeclarationRequest, Definition, DefinitionOptions, DefinitionRegistrationOptions, DefinitionRequest, Diagnostic, DiagnosticSeverity, DiagnosticTag, DidChangeConfigurationNotification, DidChangeConfigurationParams, DidChangeConfigurationRegistrationOptions, DidChangeTextDocumentNotification, DidChangeTextDocumentParams, DidChangeWatchedFilesNotification, DidChangeWatchedFilesParams, DidChangeWatchedFilesRegistrationOptions, DidCloseTextDocumentNotification, DidCloseTextDocumentParams, DidOpenTextDocumentNotification, DidOpenTextDocumentParams, DidSaveTextDocumentNotification, DidSaveTextDocumentParams, Disposable, DocumentColorRequest, DocumentFormattingOptions, DocumentFormattingParams, DocumentFormattingRequest, DocumentHighlight, DocumentHighlightOptions, DocumentHighlightRegistrationOptions, DocumentHighlightRequest, DocumentLink, DocumentLinkOptions, DocumentLinkRegistrationOptions, DocumentLinkRequest, DocumentLinkResolveRequest, DocumentOnTypeFormattingOptions, DocumentOnTypeFormattingParams, DocumentOnTypeFormattingRegistrationOptions, DocumentOnTypeFormattingRequest, DocumentRangeFormattingOptions, DocumentRangeFormattingParams, DocumentRangeFormattingRegistrationOptions, DocumentRangeFormattingRequest, DocumentSelector, DocumentSymbol, DocumentSymbolOptions, DocumentSymbolRegistrationOptions, DocumentSymbolRequest, Emitter, Event, ExecuteCommandParams, ExecuteCommandRegistrationOptions, ExecuteCommandRequest, ExitNotification, FailureHandlingKind, FileChangeType, FileEvent, FoldingRangeRequest, FormattingOptions, GenericNotificationHandler, GenericRequestHandler, Hover, HoverOptions, HoverRegistrationOptions, HoverRequest, ImplementationRequest, InitializedNotification, InitializeError, InitializeParams, InitializeRequest, InitializeResult, Location, Logger, LogMessageNotification, LogMessageParams, MarkupKind, Message, MessageReader, MessageType, MessageWriter, NotificationHandler, NotificationHandler0, NotificationType, NotificationType0, Position, PrepareRenameRequest, ProgressToken, ProgressType, PublishDiagnosticsNotification, PublishDiagnosticsParams, Range, ReferenceOptions, ReferenceRegistrationOptions, ReferencesRequest, RegistrationParams, RegistrationRequest, RenameOptions, RenameParams, RenameRegistrationOptions, RenameRequest, RequestHandler, RequestHandler0, RequestType, RequestType0, ResourceOperationKind, ResponseError, SelectionRangeRequest, ServerCapabilities, ShowMessageNotification, ShowMessageParams, ShowMessageRequest, ShutdownRequest, SignatureHelp, SignatureHelpOptions, SignatureHelpRegistrationOptions, SignatureHelpRequest, StaticRegistrationOptions, SymbolInformation, SymbolKind, SymbolTag, TelemetryEventNotification, TextDocumentChangeRegistrationOptions, TextDocumentEdit, TextDocumentPositionParams, TextDocumentRegistrationOptions, TextDocumentSaveRegistrationOptions, TextDocumentSyncKind, TextDocumentSyncOptions, TextEdit, Trace, TraceFormat, TraceOptions, Tracer, TypeDefinitionRequest, UnregistrationParams, UnregistrationRequest, WatchKind, WillSaveTextDocumentNotification, WillSaveTextDocumentParams, WillSaveTextDocumentWaitUntilRequest, WorkDoneProgressOptions, WorkspaceEdit, WorkspaceFolder, WorkspaceSymbolRegistrationOptions, WorkspaceSymbolRequest, SignatureHelpContext, WorkDoneProgressBegin, WorkDoneProgressEnd, WorkDoneProgressReport, WorkDoneProgress, DefinitionLink, ProtocolRequestType0, ProtocolRequestType, MessageSignature, ProtocolNotificationType0, ProtocolNotificationType, RegistrationType, LSPErrorCodes, SaveOptions, CancellationStrategy, CallHierarchyPrepareRequest, SemanticTokensRegistrationType, CodeActionResolveRequest, CodeLensRefreshRequest, ShowDocumentParams, ShowDocumentRequest, ShowDocumentResult, InsertTextMode, LinkedEditingRangeRequest, DidCreateFilesNotification, FileOperationRegistrationOptions, DidRenameFilesNotification, DidDeleteFilesNotification, WillCreateFilesRequest, WillRenameFilesRequest, WillDeleteFilesRequest } from 'vscode-languageserver-protocol' -import { TextDocument } from "vscode-languageserver-textdocument" -import { URI } from 'vscode-uri' -import commands from '../commands' -import languages from '../languages' -import FileWatcher from '../model/fileSystemWatcher' -import { CallHierarchyProvider, CodeActionProvider, CodeLensProvider, CompletionItemProvider, DeclarationProvider, DefinitionProvider, DocumentColorProvider, DocumentFormattingEditProvider, DocumentHighlightProvider, DocumentLinkProvider, DocumentRangeFormattingEditProvider, DocumentSymbolProvider, FoldingRangeProvider, HoverProvider, ImplementationProvider, LinkedEditingRangeProvider, OnTypeFormattingEditProvider, ProviderResult, ReferenceProvider, RenameProvider, SelectionRangeProvider, SignatureHelpProvider, TypeDefinitionProvider, WorkspaceSymbolProvider } from '../provider' -import { FileCreateEvent, FileDeleteEvent, FileRenameEvent, FileWillCreateEvent, FileWillDeleteEvent, FileWillRenameEvent, OutputChannel, TextDocumentWillSaveEvent, Thenable } from '../types' -import { resolveRoot } from '../util/fs' -import * as Is from '../util/is' -import { omit } from '../util/lodash' -import DiagnosticCollection from '../diagnostic/collection' -import window, { MessageItem } from '../window' -import workspace from '../workspace' -import sources from '../sources' -import { CallHierarchyMiddleware } from './callHierarchy' -import { ColorProviderMiddleware } from './colorProvider' -import { ConfigurationWorkspaceMiddleware } from './configuration' -import { DeclarationMiddleware } from './declaration' -import { FoldingRangeProviderMiddleware } from './foldingRange' -import { ImplementationMiddleware } from './implementation' -import { ProgressPart } from './progressPart' -import { SelectionRangeProviderMiddleware } from './selectionRange' -import { SemanticTokensMiddleware, SemanticTokensProviders } from './semanticTokens' -import { TypeDefinitionMiddleware } from './typeDefinition' -import { FileOperationsMiddleware } from './fileOperations' -import { Delayer } from './utils/async' -import os from 'os' -import * as cv from './utils/converter' -import * as UUID from './utils/uuid' -import { WorkspaceFolderWorkspaceMiddleware } from './workspaceFolders' -import { LinkedEditingRangeMiddleware } from './linkedEditingRange' - -const logger = require('../util/logger')('language-client-client') - -interface IConnection { - listen(): void - - sendRequest(type: ProtocolRequestType0, token?: CancellationToken): Promise - sendRequest(type: ProtocolRequestType, params: P, token?: CancellationToken): Promise - sendRequest(type: RequestType0, token?: CancellationToken): Promise - sendRequest(type: RequestType, params: P, token?: CancellationToken): Promise - sendRequest(method: string, token?: CancellationToken): Promise - sendRequest(method: string, param: any, token?: CancellationToken): Promise - sendRequest(type: string | MessageSignature, ...params: any[]): Promise - - onRequest(type: ProtocolRequestType0, handler: RequestHandler0): Disposable - onRequest(type: ProtocolRequestType, handler: RequestHandler): Disposable - onRequest(type: RequestType0, handler: RequestHandler0): Disposable - onRequest(type: RequestType, handler: RequestHandler): Disposable - onRequest(method: string, handler: GenericRequestHandler): Disposable - onRequest(method: string | MessageSignature, handler: GenericRequestHandler): Disposable - - sendNotification(type: ProtocolNotificationType0): void - sendNotification(type: ProtocolNotificationType, params?: P): void - sendNotification(type: NotificationType0): void - sendNotification

    (type: NotificationType

    , params?: P): void - sendNotification(method: string): void - sendNotification(method: string, params: any): void - sendNotification(method: string | MessageSignature, params?: any): void - - onNotification(type: ProtocolNotificationType0, handler: NotificationHandler0): Disposable - onNotification(type: ProtocolNotificationType, handler: NotificationHandler

    ): Disposable - onNotification(type: NotificationType0, handler: NotificationHandler0): Disposable - onNotification

    (type: NotificationType

    , handler: NotificationHandler

    ): Disposable - onNotification(method: string, handler: GenericNotificationHandler): Disposable - onNotification(method: string | MessageSignature, handler: GenericNotificationHandler): Disposable - - onProgress

    (type: ProgressType

    , token: string | number, handler: NotificationHandler

    ): Disposable - sendProgress

    (type: ProgressType

    , token: string | number, value: P): void - - trace(value: Trace, tracer: Tracer, sendNotification?: boolean): void - trace(value: Trace, tracer: Tracer, traceOptions?: TraceOptions): void - - initialize(params: InitializeParams): Promise - shutdown(): Promise - exit(): void - - onLogMessage(handle: NotificationHandler): void - onShowMessage(handler: NotificationHandler): void - onTelemetry(handler: NotificationHandler): void - - didChangeConfiguration(params: DidChangeConfigurationParams): void - didChangeWatchedFiles(params: DidChangeWatchedFilesParams): void - - didOpenTextDocument(params: DidOpenTextDocumentParams): void - didChangeTextDocument(params: DidChangeTextDocumentParams): void - didCloseTextDocument(params: DidCloseTextDocumentParams): void - didSaveTextDocument(params: DidSaveTextDocumentParams): void - onDiagnostics(handler: NotificationHandler): void - - dispose(): void -} - -class ConsoleLogger implements Logger { - public error(message: string): void { - logger.error(message) - } - public warn(message: string): void { - logger.warn(message) - } - public info(message: string): void { - logger.info(message) - } - public log(message: string): void { - logger.log(message) - } -} - -export class NullLogger implements Logger { - error(_message: string): void { - } - warn(_message: string): void { - } - info(_message: string): void { - } - log(_message: string): void { - } -} - -interface ConnectionErrorHandler { - (error: Error, message: Message | undefined, count: number | undefined): void -} - -interface ConnectionCloseHandler { - (): void -} - -interface ConnectionOptions { - cancellationStrategy: CancellationStrategy - maxRestartCount?: number -} - -function createConnection( - inputStream: NodeJS.ReadableStream, - outputStream: NodeJS.WritableStream, - errorHandler: ConnectionErrorHandler, - closeHandler: ConnectionCloseHandler, - options?: ConnectionOptions -): IConnection -function createConnection( - reader: MessageReader, - writer: MessageWriter, - errorHandler: ConnectionErrorHandler, - closeHandler: ConnectionCloseHandler, - options?: ConnectionOptions -): IConnection -function createConnection( - input: any, - output: any, - errorHandler: ConnectionErrorHandler, - closeHandler: ConnectionCloseHandler, - options?: ConnectionOptions -): IConnection { - let logger = new ConsoleLogger() - let connection = createProtocolConnection(input, output, logger, options) - connection.onError(data => { - errorHandler(data[0], data[1], data[2]) - }) - connection.onClose(closeHandler) - let result: IConnection = { - listen: (): void => connection.listen(), - - sendRequest: (type: string | MessageSignature, ...params: any[]): Promise => connection.sendRequest(Is.string(type) ? type : type.method, ...params), - onRequest: (type: string | MessageSignature, handler: GenericRequestHandler): Disposable => connection.onRequest(Is.string(type) ? type : type.method, handler), - - sendNotification: (type: string | MessageSignature, params?: any): void => connection.sendNotification(Is.string(type) ? type : type.method, params), - onNotification: (type: string | MessageSignature, handler: GenericNotificationHandler): Disposable => connection.onNotification(Is.string(type) ? type : type.method, handler), - - onProgress: connection.onProgress, - sendProgress: connection.sendProgress, - - trace: ( - value: Trace, - tracer: Tracer, - sendNotificationOrTraceOptions?: boolean | TraceOptions - ): void => { - const defaultTraceOptions: TraceOptions = { - sendNotification: false, - traceFormat: TraceFormat.Text - } - - if (sendNotificationOrTraceOptions === undefined) { - connection.trace(value, tracer, defaultTraceOptions) - } else if (Is.boolean(sendNotificationOrTraceOptions)) { - connection.trace(value, tracer, sendNotificationOrTraceOptions) - } else { - connection.trace(value, tracer, sendNotificationOrTraceOptions) - } - }, - - initialize: (params: InitializeParams) => - connection.sendRequest(InitializeRequest.type, params), - shutdown: () => connection.sendRequest(ShutdownRequest.type, undefined), - exit: () => connection.sendNotification(ExitNotification.type), - - onLogMessage: (handler: NotificationHandler) => - connection.onNotification(LogMessageNotification.type, handler), - onShowMessage: (handler: NotificationHandler) => - connection.onNotification(ShowMessageNotification.type, handler), - onTelemetry: (handler: NotificationHandler) => - connection.onNotification(TelemetryEventNotification.type, handler), - - didChangeConfiguration: (params: DidChangeConfigurationParams) => - connection.sendNotification( - DidChangeConfigurationNotification.type, - params - ), - didChangeWatchedFiles: (params: DidChangeWatchedFilesParams) => - connection.sendNotification( - DidChangeWatchedFilesNotification.type, - params - ), - - didOpenTextDocument: (params: DidOpenTextDocumentParams) => - connection.sendNotification(DidOpenTextDocumentNotification.type, params), - didChangeTextDocument: (params: DidChangeTextDocumentParams) => - connection.sendNotification( - DidChangeTextDocumentNotification.type, - params - ), - didCloseTextDocument: (params: DidCloseTextDocumentParams) => - connection.sendNotification( - DidCloseTextDocumentNotification.type, - params - ), - didSaveTextDocument: (params: DidSaveTextDocumentParams) => - connection.sendNotification(DidSaveTextDocumentNotification.type, params), - - onDiagnostics: (handler: NotificationHandler) => - connection.onNotification(PublishDiagnosticsNotification.type, handler), - - dispose: () => connection.dispose() - } - - return result -} - -/** - * An action to be performed when the connection is producing errors. - */ -export enum ErrorAction { - /** - * Continue running the server. - */ - Continue = 1, - /** - * Shutdown the server. - */ - Shutdown = 2 -} - -/** - * An action to be performed when the connection to a server got closed. - */ -export enum CloseAction { - /** - * Don't restart the server. The connection stays closed. - */ - DoNotRestart = 1, - /** - * Restart the server. - */ - Restart = 2 -} - -/** - * A plugable error handler that is invoked when the connection is either - * producing errors or got closed. - */ -export interface ErrorHandler { - /** - * An error has occurred while writing or reading from the connection. - * - * @param error - the error received - * @param message - the message to be delivered to the server if know. - * @param count - a count indicating how often an error is received. Will - * be reset if a message got successfully send or received. - */ - error(error: Error, message: Message | undefined, count: number | undefined): ErrorAction - - /** - * The connection to the server got closed. - */ - closed(): CloseAction -} - -class DefaultErrorHandler implements ErrorHandler { - private readonly restarts: number[] - - constructor(private name: string, private maxRestartCount: number) { - this.restarts = [] - } - - public error(_error: Error, _message: Message, count: number): ErrorAction { - if (count && count <= 3) { - return ErrorAction.Continue - } - return ErrorAction.Shutdown - } - public closed(): CloseAction { - this.restarts.push(Date.now()) - if (this.restarts.length < this.maxRestartCount) { - return CloseAction.Restart - } else { - let diff = this.restarts[this.restarts.length - 1] - this.restarts[0] - if (diff <= 3 * 60 * 1000) { - window.showMessage(`The "${this.name}" server crashed ${this.maxRestartCount} times in the last 3 minutes. The server will not be restarted.`, 'error') - return CloseAction.DoNotRestart - } else { - this.restarts.shift() - return CloseAction.Restart - } - } - } -} - -export interface InitializationFailedHandler { - (error: ResponseError | Error | any): boolean -} - -export interface SynchronizeOptions { - configurationSection?: string | string[] - fileEvents?: FileWatcher | FileWatcher[] -} - -export enum RevealOutputChannelOn { - Info = 1, - Warn = 2, - Error = 3, - Never = 4 -} - -export interface HandleWorkDoneProgressSignature { - (this: void, token: ProgressToken, params: WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd): void -} - -export interface HandleDiagnosticsSignature { - (this: void, uri: string, diagnostics: Diagnostic[]): void -} - -export interface ProvideCompletionItemsSignature { - ( - this: void, - document: TextDocument, - position: Position, - context: CompletionContext, - token: CancellationToken, - ): ProviderResult -} - -export interface ResolveCompletionItemSignature { - (this: void, item: CompletionItem, token: CancellationToken): ProviderResult -} - -export interface ProvideHoverSignature { - ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult -} - -export interface ProvideSignatureHelpSignature { - ( - this: void, - document: TextDocument, - position: Position, - context: SignatureHelpContext, - token: CancellationToken - ): ProviderResult -} - -export interface ProvideDefinitionSignature { - ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult -} - -export interface ProvideReferencesSignature { - ( - this: void, - document: TextDocument, - position: Position, - options: { includeDeclaration: boolean }, - token: CancellationToken - ): ProviderResult -} - -export interface ProvideDocumentHighlightsSignature { - ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult -} - -export interface ProvideDocumentSymbolsSignature { - (this: void, document: TextDocument, token: CancellationToken): ProviderResult -} - -export interface ProvideWorkspaceSymbolsSignature { - (this: void, query: string, token: CancellationToken): ProviderResult -} - -export interface ProvideCodeActionsSignature { - ( - this: void, - document: TextDocument, - range: Range, - context: CodeActionContext, - token: CancellationToken - ): ProviderResult<(Command | CodeAction)[]> -} - -export interface ResolveCodeActionSignature { - (this: void, item: CodeAction, token: CancellationToken): ProviderResult -} - -export interface ProvideCodeLensesSignature { - (this: void, document: TextDocument, token: CancellationToken): ProviderResult -} - -export interface ResolveCodeLensSignature { - (this: void, codeLens: CodeLens, token: CancellationToken): ProviderResult -} - -export interface ProvideDocumentFormattingEditsSignature { - ( - this: void, - document: TextDocument, - options: FormattingOptions, - token: CancellationToken - ): ProviderResult -} - -export interface ProvideDocumentRangeFormattingEditsSignature { - ( - this: void, - document: TextDocument, - range: Range, - options: FormattingOptions, - token: CancellationToken - ): ProviderResult -} - -export interface ProvideOnTypeFormattingEditsSignature { - ( - this: void, - document: TextDocument, - position: Position, - ch: string, - options: FormattingOptions, - token: CancellationToken - ): ProviderResult -} - -export interface PrepareRenameSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult -} - -export interface ProvideRenameEditsSignature { - ( - this: void, - document: TextDocument, - position: Position, - newName: string, - token: CancellationToken - ): ProviderResult -} - -export interface ProvideDocumentLinksSignature { - (this: void, document: TextDocument, token: CancellationToken): ProviderResult -} - -export interface ResolveDocumentLinkSignature { - (this: void, link: DocumentLink, token: CancellationToken): ProviderResult -} - -export interface ExecuteCommandSignature { - (this: void, command: string, args: any[]): ProviderResult -} - -export interface NextSignature { - (this: void, data: P, next: (data: P) => R): R -} - -export interface DidChangeConfigurationSignature { - (this: void, sections: string[] | undefined): void -} - -export interface DidChangeWatchedFileSignature { - (this: void, event: FileEvent): void -} - -export interface _WorkspaceMiddleware { - didChangeConfiguration?: ( - this: void, - sections: string[] | undefined, - next: DidChangeConfigurationSignature - ) => void - didChangeWatchedFile?: (this: void, event: FileEvent, next: DidChangeWatchedFileSignature) => void -} - -export type WorkspaceMiddleware = _WorkspaceMiddleware & ConfigurationWorkspaceMiddleware & WorkspaceFolderWorkspaceMiddleware & FileOperationsMiddleware - -export interface _WindowMiddleware { - showDocument?: (this: void, params: ShowDocumentParams, next: ShowDocumentRequest.HandlerSignature) => Promise -} - -export type WindowMiddleware = _WindowMiddleware - -/** - * The Middleware lets extensions intercept the request and notifications send and received - * from the server - */ -export interface _Middleware { - didOpen?: NextSignature - didChange?: NextSignature - willSave?: NextSignature - willSaveWaitUntil?: NextSignature< - TextDocumentWillSaveEvent, - Thenable - > - didSave?: NextSignature - didClose?: NextSignature - - handleDiagnostics?: ( - this: void, - uri: string, - diagnostics: Diagnostic[], - next: HandleDiagnosticsSignature - ) => void - provideCompletionItem?: ( - this: void, - document: TextDocument, - position: Position, - context: CompletionContext, - token: CancellationToken, - next: ProvideCompletionItemsSignature - ) => ProviderResult - resolveCompletionItem?: ( - this: void, - item: CompletionItem, - token: CancellationToken, - next: ResolveCompletionItemSignature - ) => ProviderResult - provideHover?: ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken, - next: ProvideHoverSignature - ) => ProviderResult - provideSignatureHelp?: ( - this: void, - document: TextDocument, - position: Position, - context: SignatureHelpContext, - token: CancellationToken, - next: ProvideSignatureHelpSignature - ) => ProviderResult - provideDefinition?: ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken, - next: ProvideDefinitionSignature - ) => ProviderResult - provideReferences?: ( - this: void, - document: TextDocument, - position: Position, - options: { includeDeclaration: boolean }, - token: CancellationToken, - next: ProvideReferencesSignature - ) => ProviderResult - provideDocumentHighlights?: ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken, - next: ProvideDocumentHighlightsSignature - ) => ProviderResult - provideDocumentSymbols?: ( - this: void, - document: TextDocument, - token: CancellationToken, - next: ProvideDocumentSymbolsSignature - ) => ProviderResult - provideWorkspaceSymbols?: ( - this: void, - query: string, - token: CancellationToken, - next: ProvideWorkspaceSymbolsSignature - ) => ProviderResult - provideCodeActions?: ( - this: void, - document: TextDocument, - range: Range, - context: CodeActionContext, - token: CancellationToken, - next: ProvideCodeActionsSignature - ) => ProviderResult<(Command | CodeAction)[]> - handleWorkDoneProgress?: ( - this: void, - token: ProgressToken, - params: WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd, next: HandleWorkDoneProgressSignature - ) => void - resolveCodeAction?: ( - this: void, - item: CodeAction, - token: CancellationToken, - next: ResolveCodeActionSignature - ) => ProviderResult - provideCodeLenses?: ( - this: void, - document: TextDocument, - token: CancellationToken, - next: ProvideCodeLensesSignature - ) => ProviderResult - resolveCodeLens?: ( - this: void, - codeLens: CodeLens, - token: CancellationToken, - next: ResolveCodeLensSignature - ) => ProviderResult - provideDocumentFormattingEdits?: ( - this: void, - document: TextDocument, - options: FormattingOptions, - token: CancellationToken, - next: ProvideDocumentFormattingEditsSignature - ) => ProviderResult - provideDocumentRangeFormattingEdits?: ( - this: void, - document: TextDocument, - range: Range, - options: FormattingOptions, - token: CancellationToken, - next: ProvideDocumentRangeFormattingEditsSignature - ) => ProviderResult - provideOnTypeFormattingEdits?: ( - this: void, - document: TextDocument, - position: Position, - ch: string, - options: FormattingOptions, - token: CancellationToken, - next: ProvideOnTypeFormattingEditsSignature - ) => ProviderResult - prepareRename?: ( - this: void, document: TextDocument, - position: Position, - token: CancellationToken, - next: PrepareRenameSignature - ) => ProviderResult - provideRenameEdits?: ( - this: void, - document: TextDocument, - position: Position, - newName: string, - token: CancellationToken, - next: ProvideRenameEditsSignature - ) => ProviderResult - provideDocumentLinks?: ( - this: void, - document: TextDocument, - token: CancellationToken, - next: ProvideDocumentLinksSignature - ) => ProviderResult - resolveDocumentLink?: ( - this: void, - link: DocumentLink, - token: CancellationToken, - next: ResolveDocumentLinkSignature - ) => ProviderResult - executeCommand?: ( - this: void, - command: string, - args: any[], - next: ExecuteCommandSignature - ) => ProviderResult - workspace?: WorkspaceMiddleware - window?: WindowMiddleware -} - -export type Middleware = _Middleware & - TypeDefinitionMiddleware & - ImplementationMiddleware & - ColorProviderMiddleware & - DeclarationMiddleware & - FoldingRangeProviderMiddleware & - CallHierarchyMiddleware & - SemanticTokensMiddleware & - LinkedEditingRangeMiddleware & - SelectionRangeProviderMiddleware - -export interface LanguageClientOptions { - ignoredRootPaths?: string[] - documentSelector?: DocumentSelector | string[] - synchronize?: SynchronizeOptions - diagnosticCollectionName?: string - disableDynamicRegister?: boolean - disableWorkspaceFolders?: boolean - disableSnippetCompletion?: boolean - disableDiagnostics?: boolean - disableCompletion?: boolean - formatterPriority?: number - outputChannelName?: string - outputChannel?: OutputChannel - revealOutputChannelOn?: RevealOutputChannelOn - /** - * The encoding use to read stdout and stderr. Defaults - * to 'utf8' if omitted. - */ - stdioEncoding?: string - initializationOptions?: any | (() => any) - initializationFailedHandler?: InitializationFailedHandler - progressOnInitialization?: boolean - errorHandler?: ErrorHandler - middleware?: Middleware - workspaceFolder?: WorkspaceFolder - connectionOptions?: ConnectionOptions - markdown?: { - isTrusted?: boolean - } -} - -interface ResolvedClientOptions { - ignoredRootPaths?: string[] - disableWorkspaceFolders: boolean - disableSnippetCompletion: boolean - disableDynamicRegister: boolean - disableDiagnostics: boolean - disableCompletion: boolean - formatterPriority: number - documentSelector?: DocumentSelector - synchronize: SynchronizeOptions - diagnosticCollectionName?: string - outputChannelName: string - revealOutputChannelOn: RevealOutputChannelOn - stdioEncoding: string - initializationOptions?: any | (() => any) - initializationFailedHandler?: InitializationFailedHandler - progressOnInitialization: boolean - errorHandler: ErrorHandler - middleware: Middleware - workspaceFolder?: WorkspaceFolder - connectionOptions?: ConnectionOptions - markdown: { - isTrusted: boolean - } -} - -export enum State { - Stopped = 1, - Running = 2, - Starting = 3, -} - -export interface StateChangeEvent { - oldState: State - newState: State -} - -export enum ClientState { - Initial, - Starting, - StartFailed, - Running, - Stopping, - Stopped -} - -const SupportedSymbolKinds: SymbolKind[] = [ - SymbolKind.File, - SymbolKind.Module, - SymbolKind.Namespace, - SymbolKind.Package, - SymbolKind.Class, - SymbolKind.Method, - SymbolKind.Property, - SymbolKind.Field, - SymbolKind.Constructor, - SymbolKind.Enum, - SymbolKind.Interface, - SymbolKind.Function, - SymbolKind.Variable, - SymbolKind.Constant, - SymbolKind.String, - SymbolKind.Number, - SymbolKind.Boolean, - SymbolKind.Array, - SymbolKind.Object, - SymbolKind.Key, - SymbolKind.Null, - SymbolKind.EnumMember, - SymbolKind.Struct, - SymbolKind.Event, - SymbolKind.Operator, - SymbolKind.TypeParameter -] - -const SupportedCompletionItemKinds: CompletionItemKind[] = [ - CompletionItemKind.Text, - CompletionItemKind.Method, - CompletionItemKind.Function, - CompletionItemKind.Constructor, - CompletionItemKind.Field, - CompletionItemKind.Variable, - CompletionItemKind.Class, - CompletionItemKind.Interface, - CompletionItemKind.Module, - CompletionItemKind.Property, - CompletionItemKind.Unit, - CompletionItemKind.Value, - CompletionItemKind.Enum, - CompletionItemKind.Keyword, - CompletionItemKind.Snippet, - CompletionItemKind.Color, - CompletionItemKind.File, - CompletionItemKind.Reference, - CompletionItemKind.Folder, - CompletionItemKind.EnumMember, - CompletionItemKind.Constant, - CompletionItemKind.Struct, - CompletionItemKind.Event, - CompletionItemKind.Operator, - CompletionItemKind.TypeParameter -] - -const SupportedSymbolTags: SymbolTag[] = [ - SymbolTag.Deprecated -] - -function ensure(target: T, key: K): T[K] { - if (target[key] === undefined) { - target[key] = {} as any - } - return target[key] -} - -interface ResolvedTextDocumentSyncCapabilities { - resolvedTextDocumentSync?: TextDocumentSyncOptions -} - -export interface RegistrationData { - id: string - registerOptions: T -} - -/** - * A static feature. A static feature can't be dynamically activate via the - * server. It is wired during the initialize sequence. - */ -export interface StaticFeature { - /** - * Called to fill the initialize params. - * - * @params the initialize params. - */ - fillInitializeParams?: (params: InitializeParams) => void - - /** - * Called to fill in the client capabilities this feature implements. - * - * @param capabilities The client capabilities to fill. - */ - fillClientCapabilities(capabilities: ClientCapabilities): void - - /** - * Initialize the feature. This method is called on a feature instance - * when the client has successfully received the initialize request from - * the server and before the client sends the initialized notification - * to the server. - * - * @param capabilities the server capabilities - * @param documentSelector the document selector pass to the client's constuctor. - * May be `undefined` if the client was created without a selector. - */ - initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector | undefined - ): void - - /** - * Called when the client is stopped to dispose this feature. Usually a feature - * unregisters listeners registered hooked up with the VS Code extension host. - */ - dispose(): void -} - -export interface DynamicFeature { - - /** - * Called to fill the initialize params. - * - * @params the initialize params. - */ - fillInitializeParams?: (params: InitializeParams) => void - - /** - * Called to fill in the client capabilities this feature implements. - * - * @param capabilities The client capabilities to fill. - */ - fillClientCapabilities(capabilities: ClientCapabilities): void - - /** - * Initialize the feature. This method is called on a feature instance - * when the client has successfully received the initialize request from - * the server and before the client sends the initialized notification - * to the server. - * - * @param capabilities the server capabilities. - * @param documentSelector the document selector pass to the client's constructor. - * May be `undefined` if the client was created without a selector. - */ - initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector | undefined - ): void - - /** - * The signature (e.g. method) for which this features support dynamic activation / registration. - */ - registrationType: RegistrationType - - /** - * Is called when the server send a register request for the given message. - * - * @param data additional registration data as defined in the protocol. - */ - register(data: RegistrationData): void - - /** - * Is called when the server wants to unregister a feature. - * - * @param id the id used when registering the feature. - */ - unregister(id: string): void - - /** - * Called when the client is stopped to dispose this feature. Usually a feature - * unregisters listeners registered hooked up with the VS Code extension host. - */ - dispose(): void -} - -export interface NotificationFeature { - /** - * Triggers the corresponding RPC method. - */ - getProvider(document: TextDocument): { send: T } | undefined -} - -namespace DynamicFeature { - export function is(value: any): value is DynamicFeature { - let candidate: DynamicFeature = value - return ( - candidate && - Is.func(candidate.register) && - Is.func(candidate.unregister) && - Is.func(candidate.dispose) && - candidate.registrationType !== undefined - ) - } -} - -interface CreateParamsSignature { - (data: E): P -} - -abstract class DocumentNotifications - implements DynamicFeature, NotificationFeature<(data: E) => void> { - private _listener: Disposable | undefined - protected _selectors: Map = new Map() - - public static textDocumentFilter( - selectors: IterableIterator, - textDocument: TextDocument - ): boolean { - for (const selector of selectors) { - if (workspace.match(selector, textDocument) > 0) { - return true - } - } - return false - } - - constructor( - protected _client: BaseLanguageClient, - private _event: Event, - protected _type: ProtocolNotificationType, - protected _middleware: NextSignature | undefined, - protected _createParams: CreateParamsSignature, - protected _selectorFilter?: ( - selectors: IterableIterator, - data: E - ) => boolean - ) {} - - public abstract registrationType: RegistrationType - - public abstract fillClientCapabilities(capabilities: ClientCapabilities): void - - public abstract initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector | undefined - ): void - - public register( - data: RegistrationData - ): void { - if (!data.registerOptions.documentSelector) { - return - } - if (!this._listener) { - this._listener = this._event(this.callback, this) - } - this._selectors.set(data.id, data.registerOptions.documentSelector) - } - - private callback(data: E): void { - if ( - !this._selectorFilter || - this._selectorFilter(this._selectors.values(), data) - ) { - if (this._middleware) { - this._middleware(data, data => - this._client.sendNotification(this._type, this._createParams(data)) - ) - } else { - this._client.sendNotification(this._type, this._createParams(data)) - } - this.notificationSent(data) - } - } - - protected notificationSent(_data: E): void {} - - public unregister(id: string): void { - this._selectors.delete(id) - if (this._selectors.size === 0 && this._listener) { - this._listener.dispose() - this._listener = undefined - } - } - - public dispose(): void { - this._selectors.clear() - if (this._listener) { - this._listener.dispose() - this._listener = undefined - } - } - - public getProvider(document: TextDocument): { send: (data: E) => void } | undefined { - for (const selector of this._selectors.values()) { - if (workspace.match(selector, document)) { - return { - send: (data: E) => { - this.callback(data) - } - } - } - } - return undefined - } -} - -class DidOpenTextDocumentFeature extends DocumentNotifications { - constructor(client: BaseLanguageClient, private _syncedDocuments: Map) { - super( - client, - workspace.onDidOpenTextDocument, - DidOpenTextDocumentNotification.type, - client.clientOptions.middleware!.didOpen, - (textDocument) => { - return { textDocument: cv.convertToTextDocumentItem(textDocument) } - }, - DocumentNotifications.textDocumentFilter - ) - } - - public get registrationType(): RegistrationType { - return DidOpenTextDocumentNotification.type - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!.dynamicRegistration = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync - if ( - documentSelector && - textDocumentSyncOptions && - textDocumentSyncOptions.openClose - ) { - this.register({ - id: UUID.generateUuid(), - registerOptions: { documentSelector: documentSelector } - }) - } - } - - public register( - data: RegistrationData - ): void { - super.register(data) - if (!data.registerOptions.documentSelector) { - return - } - let documentSelector = data.registerOptions.documentSelector - workspace.textDocuments.forEach(textDocument => { - let uri: string = textDocument.uri.toString() - if (this._syncedDocuments.has(uri)) { - return - } - if (workspace.match(documentSelector, textDocument) > 0) { - let middleware = this._client.clientOptions.middleware! - let didOpen = (textDocument: TextDocument) => { - this._client.sendNotification( - this._type, - this._createParams(textDocument) - ) - } - if (middleware.didOpen) { - middleware.didOpen(textDocument, didOpen) - } else { - didOpen(textDocument) - } - this._syncedDocuments.set(uri, textDocument) - } - }) - } - - protected notificationSent(textDocument: TextDocument): void { - super.notificationSent(textDocument) - this._syncedDocuments.set(textDocument.uri.toString(), textDocument) - } -} - -class DidCloseTextDocumentFeature extends DocumentNotifications< - DidCloseTextDocumentParams, - TextDocument - > { - constructor( - client: BaseLanguageClient, - private _syncedDocuments: Map - ) { - super( - client, - workspace.onDidCloseTextDocument, - DidCloseTextDocumentNotification.type, - client.clientOptions.middleware!.didClose, - (textDocument) => cv.asCloseTextDocumentParams(textDocument), - DocumentNotifications.textDocumentFilter - ) - } - - public get registrationType(): RegistrationType { - return DidCloseTextDocumentNotification.type - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure( - ensure(capabilities, 'textDocument')!, - 'synchronization' - )!.dynamicRegistration = true - } - - public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { - let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync - if ( - documentSelector && - textDocumentSyncOptions && - textDocumentSyncOptions.openClose - ) { - this.register({ - id: UUID.generateUuid(), - registerOptions: { documentSelector: documentSelector } - }) - } - } - - protected notificationSent(textDocument: TextDocument): void { - super.notificationSent(textDocument) - this._syncedDocuments.delete(textDocument.uri.toString()) - } - - public unregister(id: string): void { - let selector = this._selectors.get(id)! - // The super call removed the selector from the map - // of selectors. - super.unregister(id) - let selectors = this._selectors.values() - this._syncedDocuments.forEach(textDocument => { - if ( - workspace.match(selector, textDocument) > 0 && - !this._selectorFilter!(selectors, textDocument) - ) { - let middleware = this._client.clientOptions.middleware! - let didClose = (textDocument: TextDocument) => { - this._client.sendNotification( - this._type, - this._createParams(textDocument) - ) - } - this._syncedDocuments.delete(textDocument.uri.toString()) - if (middleware.didClose) { - middleware.didClose(textDocument, didClose) - } else { - didClose(textDocument) - } - } - }) - } -} - -interface DidChangeTextDocumentData { - documentSelector: DocumentSelector - syncKind: 0 | 1 | 2 -} - -class DidChangeTextDocumentFeature - implements DynamicFeature, NotificationFeature<(event: DidChangeTextDocumentParams) => void> { - private _listener: Disposable | undefined - private _changeData: Map = new Map() - - constructor(private _client: BaseLanguageClient) {} - - public get registrationType(): RegistrationType { - return DidChangeTextDocumentNotification.type - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!.dynamicRegistration = true - } - - public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { - let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync - if ( - documentSelector && - textDocumentSyncOptions && - textDocumentSyncOptions.change !== undefined && - textDocumentSyncOptions.change !== TextDocumentSyncKind.None - ) { - this.register({ - id: UUID.generateUuid(), - registerOptions: Object.assign( - {}, - { documentSelector: documentSelector }, - { syncKind: textDocumentSyncOptions.change } - ) - }) - } - } - - public register( - data: RegistrationData - ): void { - if (!data.registerOptions.documentSelector) { - return - } - if (!this._listener) { - this._listener = workspace.onDidChangeTextDocument(this.callback, this) - } - this._changeData.set(data.id, { - documentSelector: data.registerOptions.documentSelector, - syncKind: data.registerOptions.syncKind - }) - } - - private callback(event: DidChangeTextDocumentParams): void { - // Text document changes are send for dirty changes as well. We don't - // have dirty / undirty events in the LSP so we ignore content changes - // with length zero. - if (event.contentChanges.length === 0) { - return - } - let doc = workspace.getDocument(event.textDocument.uri) - if (!doc) return - let { textDocument } = doc - for (const changeData of this._changeData.values()) { - if (workspace.match(changeData.documentSelector, textDocument) > 0) { - let middleware = this._client.clientOptions.middleware! - if (changeData.syncKind === TextDocumentSyncKind.Incremental) { - if (middleware.didChange) { - middleware.didChange(event, () => - this._client.sendNotification( - DidChangeTextDocumentNotification.type, - omit(event, ['bufnr', 'original']) - ) - ) - } else { - this._client.sendNotification( - DidChangeTextDocumentNotification.type, - omit(event, ['bufnr', 'original']) - ) - } - } else if (changeData.syncKind === TextDocumentSyncKind.Full) { - let didChange: (event: DidChangeTextDocumentParams) => void = event => { - let { textDocument } = workspace.getDocument(event.textDocument.uri) - this._client.sendNotification( - DidChangeTextDocumentNotification.type, - cv.asChangeTextDocumentParams(textDocument) - ) - } - if (middleware.didChange) { - middleware.didChange(event, didChange) - } else { - didChange(event) - } - } - } - } - } - - public unregister(id: string): void { - this._changeData.delete(id) - if (this._changeData.size === 0 && this._listener) { - this._listener.dispose() - this._listener = undefined - } - } - - public dispose(): void { - this._changeData.clear() - if (this._listener) { - this._listener.dispose() - this._listener = undefined - } - } - - public getProvider(document: TextDocument): { send: (event: DidChangeTextDocumentParams) => void } | undefined { - for (const changeData of this._changeData.values()) { - if (workspace.match(changeData.documentSelector, document)) { - return { - send: (event: DidChangeTextDocumentParams): void => { - this.callback(event) - } - } - } - } - return undefined - } -} - -class WillSaveFeature extends DocumentNotifications { - constructor(client: BaseLanguageClient) { - super( - client, - workspace.onWillSaveTextDocument, - WillSaveTextDocumentNotification.type, - client.clientOptions.middleware!.willSave, - willSaveEvent => cv.asWillSaveTextDocumentParams(willSaveEvent), - (selectors, willSaveEvent) => DocumentNotifications.textDocumentFilter(selectors, willSaveEvent.document) - ) - } - - public get registrationType(): RegistrationType { - return WillSaveTextDocumentNotification.type - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - let value = ensure(ensure(capabilities, 'textDocument')!, 'synchronization')! - value.willSave = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync - if ( - documentSelector && - textDocumentSyncOptions && - textDocumentSyncOptions.willSave - ) { - this.register({ - id: UUID.generateUuid(), - registerOptions: { documentSelector: documentSelector } - }) - } - } -} - -class WillSaveWaitUntilFeature implements DynamicFeature { - private _listener: Disposable | undefined - private _selectors: Map = new Map() - - constructor(private _client: BaseLanguageClient) {} - - public get registrationType(): RegistrationType { - return WillSaveTextDocumentWaitUntilRequest.type - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - let value = ensure(ensure(capabilities, 'textDocument')!, 'synchronization')! - value.willSaveWaitUntil = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync - if ( - documentSelector && - textDocumentSyncOptions && - textDocumentSyncOptions.willSaveWaitUntil - ) { - this.register({ - id: UUID.generateUuid(), - registerOptions: { documentSelector: documentSelector } - }) - } - } - - public register( - data: RegistrationData - ): void { - if (!data.registerOptions.documentSelector) { - return - } - if (!this._listener) { - this._listener = workspace.onWillSaveTextDocument(this.callback, this) - } - this._selectors.set(data.id, data.registerOptions.documentSelector) - } - - private callback(event: TextDocumentWillSaveEvent): void { - if (DocumentNotifications.textDocumentFilter( - this._selectors.values(), - event.document)) { - let middleware = this._client.clientOptions.middleware! - let willSaveWaitUntil = (event: TextDocumentWillSaveEvent): Thenable => { - return this._client - .sendRequest( - WillSaveTextDocumentWaitUntilRequest.type, - cv.asWillSaveTextDocumentParams(event) - ) - .then(edits => { - return edits ? edits : [] - }, e => { - window.showMessage(`Error on willSaveWaitUntil: ${e}`, 'error') - logger.error(e) - return [] - }) - } - event.waitUntil( - middleware.willSaveWaitUntil - ? middleware.willSaveWaitUntil(event, willSaveWaitUntil) - : willSaveWaitUntil(event) - ) - } - } - - public unregister(id: string): void { - this._selectors.delete(id) - if (this._selectors.size === 0 && this._listener) { - this._listener.dispose() - this._listener = undefined - } - } - - public dispose(): void { - this._selectors.clear() - if (this._listener) { - this._listener.dispose() - this._listener = undefined - } - } -} - -class DidSaveTextDocumentFeature extends DocumentNotifications< - DidSaveTextDocumentParams, - TextDocument - > { - private _includeText: boolean - - constructor(client: BaseLanguageClient) { - super( - client, - workspace.onDidSaveTextDocument, - DidSaveTextDocumentNotification.type, - client.clientOptions.middleware!.didSave, - textDocument => - cv.asSaveTextDocumentParams( - textDocument, - this._includeText - ), - DocumentNotifications.textDocumentFilter - ) - this._includeText = false - } - - public get registrationType(): RegistrationType { - return DidSaveTextDocumentNotification.type - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure( - ensure(capabilities, 'textDocument')!, - 'synchronization' - )!.didSave = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync - if ( - documentSelector && - textDocumentSyncOptions && - textDocumentSyncOptions.save - ) { - const saveOptions: SaveOptions = typeof textDocumentSyncOptions.save === 'boolean' - ? { includeText: false } - : { includeText: !!textDocumentSyncOptions.save.includeText } - this.register({ - id: UUID.generateUuid(), - registerOptions: Object.assign( - {}, - { documentSelector: documentSelector }, - saveOptions - ) - }) - } - } - - public register( - data: RegistrationData - ): void { - this._includeText = !!data.registerOptions.includeText - super.register(data) - } -} - -class FileSystemWatcherFeature - implements DynamicFeature { - private _watchers: Map = new Map() - - constructor( - _client: BaseLanguageClient, - private _notifyFileEvent: (event: FileEvent) => void - ) {} - - public get registrationType(): RegistrationType { - return DidChangeWatchedFilesNotification.type - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure( - ensure(capabilities, 'workspace')!, - 'didChangeWatchedFiles' - )!.dynamicRegistration = true - } - - public initialize( - _capabilities: ServerCapabilities, - _documentSelector: DocumentSelector - ): void {} - - public register( - data: RegistrationData - ): void { - if (!Array.isArray(data.registerOptions.watchers)) { - return - } - let disposables: Disposable[] = [] - for (let watcher of data.registerOptions.watchers) { - if (!Is.string(watcher.globPattern)) { - continue - } - let watchCreate: boolean = true, - watchChange: boolean = true, - watchDelete: boolean = true - if (watcher.kind != null) { - watchCreate = (watcher.kind & WatchKind.Create) !== 0 - watchChange = (watcher.kind & WatchKind.Change) != 0 - watchDelete = (watcher.kind & WatchKind.Delete) != 0 - } - let fileSystemWatcher = workspace.createFileSystemWatcher( - watcher.globPattern, - !watchCreate, - !watchChange, - !watchDelete - ) - this.hookListeners( - fileSystemWatcher, - watchCreate, - watchChange, - watchDelete, - disposables - ) - disposables.push(fileSystemWatcher) - } - this._watchers.set(data.id, disposables) - } - - public registerRaw(id: string, fileSystemWatchers: FileWatcher[]) { - let disposables: Disposable[] = [] - for (let fileSystemWatcher of fileSystemWatchers) { - disposables.push(fileSystemWatcher) - this.hookListeners(fileSystemWatcher, true, true, true, disposables) - } - this._watchers.set(id, disposables) - } - - private hookListeners( - fileSystemWatcher: FileWatcher, - watchCreate: boolean, - watchChange: boolean, - watchDelete: boolean, - listeners: Disposable[] - ): void { - if (watchCreate) { - fileSystemWatcher.onDidCreate( - resource => - this._notifyFileEvent({ - uri: cv.asUri(resource), - type: FileChangeType.Created - }), - null, - listeners - ) - } - if (watchChange) { - fileSystemWatcher.onDidChange( - resource => - this._notifyFileEvent({ - uri: cv.asUri(resource), - type: FileChangeType.Changed - }), - null, - listeners - ) - } - if (watchDelete) { - fileSystemWatcher.onDidDelete( - resource => - this._notifyFileEvent({ - uri: cv.asUri(resource), - type: FileChangeType.Deleted - }), - null, - listeners - ) - } - } - - public unregister(id: string): void { - let disposables = this._watchers.get(id) - if (disposables) { - for (let disposable of disposables) { - disposable.dispose() - } - } - } - - public dispose(): void { - this._watchers.forEach(disposables => { - for (let disposable of disposables) { - disposable.dispose() - } - }) - this._watchers.clear() - } -} - -interface TextDocumentFeatureRegistration { - disposable: Disposable - data: RegistrationData - provider: PR -} - -export interface TextDocumentProviderFeature { - /** - * Triggers the corresponding RPC method. - */ - getProvider(textDocument: TextDocument): T | undefined -} - -export abstract class TextDocumentFeature< - PO, RO extends TextDocumentRegistrationOptions & PO, PR - > implements DynamicFeature { - private _registrations: Map> = new Map() - - constructor( - protected _client: BaseLanguageClient, - private _registrationType: RegistrationType - ) {} - - public get registrationType(): RegistrationType { - return this._registrationType - } - - public abstract fillClientCapabilities(capabilities: ClientCapabilities): void - - public abstract initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void - - public register(data: RegistrationData): void { - if (!data.registerOptions.documentSelector) { - return - } - let registration = this.registerLanguageProvider(data.registerOptions) - this._registrations.set(data.id, { disposable: registration[0], data, provider: registration[1] }) - } - - protected abstract registerLanguageProvider(options: RO): [Disposable, PR] - - public unregister(id: string): void { - let registration = this._registrations.get(id) - if (registration) { - registration.disposable.dispose() - } - } - - public dispose(): void { - this._registrations.forEach(value => { - value.disposable.dispose() - }) - this._registrations.clear() - } - - protected getRegistration(documentSelector: DocumentSelector | undefined, capability: undefined | PO | (RO & StaticRegistrationOptions)): [string | undefined, (RO & { documentSelector: DocumentSelector }) | undefined] { - if (!capability) { - return [undefined, undefined] - } else if (TextDocumentRegistrationOptions.is(capability)) { - const id = StaticRegistrationOptions.hasId(capability) ? capability.id : UUID.generateUuid() - const selector = capability.documentSelector || documentSelector - if (selector) { - return [id, Object.assign({}, capability, { documentSelector: selector })] - } - } else if (Is.boolean(capability) && capability === true || WorkDoneProgressOptions.is(capability)) { - if (!documentSelector) { - return [undefined, undefined] - } - let options: RO & { documentSelector: DocumentSelector } = (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector })) as any - return [UUID.generateUuid(), options] - } - return [undefined, undefined] - } - - protected getRegistrationOptions(documentSelector: DocumentSelector | undefined, capability: undefined | PO): (RO & { documentSelector: DocumentSelector }) | undefined { - if (!documentSelector || !capability) { - return undefined - } - return (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector })) as RO & { documentSelector: DocumentSelector } - } - - public getProvider(textDocument: TextDocument): PR | undefined { - for (const registration of this._registrations.values()) { - let selector = registration.data.registerOptions.documentSelector - if (selector !== null && workspace.match(selector, textDocument) > 0) { - return registration.provider - } - } - return undefined - } - - protected getAllProviders(): Iterable { - const result: PR[] = [] - for (const item of this._registrations.values()) { - result.push(item.provider) - } - return result - } -} - -export interface WorkspaceProviderFeature { - getProviders(): PR[] | undefined -} - -interface WorkspaceFeatureRegistration { - disposable: Disposable - provider: PR -} - -abstract class WorkspaceFeature implements DynamicFeature { - protected _registrations: Map> = new Map() - - constructor( - protected _client: BaseLanguageClient, - private _registrationType: RegistrationType - ) {} - - public get registrationType(): RegistrationType { - return this._registrationType - } - - public abstract fillClientCapabilities(capabilities: ClientCapabilities): void - - public abstract initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector | undefined - ): void - - public register(data: RegistrationData): void { - const registration = this.registerLanguageProvider(data.registerOptions) - this._registrations.set(data.id, { disposable: registration[0], provider: registration[1] }) - } - - protected abstract registerLanguageProvider(options: RO): [Disposable, PR] - - public unregister(id: string): void { - const registration = this._registrations.get(id) - if (registration) registration.disposable.dispose() - } - - public dispose(): void { - this._registrations.forEach(value => { - value.disposable.dispose() - }) - this._registrations.clear() - } - - public getProviders(): PR[] { - const result: PR[] = [] - for (const registration of this._registrations.values()) { - result.push(registration.provider) - } - return result - } -} - -export interface ProvideResolveFeature { - provide: T1 - resolve: T2 -} - -class CompletionItemFeature extends TextDocumentFeature { - private index: number - constructor(client: BaseLanguageClient) { - super(client, CompletionRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - let snippetSupport = this._client.clientOptions.disableSnippetCompletion !== true - let completion = ensure(ensure(capabilities, 'textDocument')!, 'completion')! - completion.dynamicRegistration = true - completion.contextSupport = true - completion.completionItem = { - snippetSupport, - commitCharactersSupport: true, - documentationFormat: this._client.supporedMarkupKind, - deprecatedSupport: true, - preselectSupport: true, - insertReplaceSupport: true, - tagSupport: { valueSet: [CompletionItemTag.Deprecated] }, - resolveSupport: { properties: ['documentation', 'detail', 'additionalTextEdits'] }, - insertTextModeSupport: { valueSet: [InsertTextMode.asIs, InsertTextMode.adjustIndentation] } - } - completion.completionItemKind = { valueSet: SupportedCompletionItemKinds } - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - this.index = 0 - const options = this.getRegistrationOptions(documentSelector, capabilities.completionProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider(options: CompletionRegistrationOptions): [Disposable, CompletionItemProvider] { - let triggerCharacters = options.triggerCharacters || [] - let allCommitCharacters = options.allCommitCharacters || [] - let priority = (options as any).priority as number - const provider: CompletionItemProvider = { - provideCompletionItems: (document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext): ProviderResult => { - const client = this._client - const middleware = this._client.clientOptions.middleware! - const provideCompletionItems: ProvideCompletionItemsSignature = (document, position, context, token) => { - return client.sendRequest( - CompletionRequest.type, - cv.asCompletionParams(document, position, context), - token - ).then(result => result, error => { - return client.handleFailedRequest(CompletionRequest.type, token, error, null) - }) - } - - return middleware.provideCompletionItem - ? middleware.provideCompletionItem(document, position, context, token, provideCompletionItems) - : provideCompletionItems(document, position, context, token) - }, - resolveCompletionItem: options.resolveProvider - ? (item: CompletionItem, token: CancellationToken): ProviderResult => { - const client = this._client - const middleware = this._client.clientOptions.middleware! - const resolveCompletionItem: ResolveCompletionItemSignature = (item, token) => { - return client.sendRequest( - CompletionResolveRequest.type, - item, - token - ).then(res => res, error => { - return client.handleFailedRequest(CompletionResolveRequest.type, token, error, item) - }) - } - - return middleware.resolveCompletionItem - ? middleware.resolveCompletionItem(item, token, resolveCompletionItem) - : resolveCompletionItem(item, token) - } - : undefined - } - // index is needed since one language server could create many sources. - let name = this._client.id + (this.index ? '-' + this.index : '') - sources.removeSource(name) - const disposable = languages.registerCompletionItemProvider( - name, - 'LS', - options.documentSelector || this._client.clientOptions.documentSelector, - provider, - triggerCharacters, - priority, - allCommitCharacters) - this.index = this.index + 1 - return [disposable, provider] - } -} - -class HoverFeature extends TextDocumentFeature< - boolean | HoverOptions, HoverRegistrationOptions, HoverProvider - > { - constructor(client: BaseLanguageClient) { - super(client, HoverRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - const hoverCapability = ensure( - ensure(capabilities, 'textDocument')!, - 'hover' - )! - hoverCapability.dynamicRegistration = true - hoverCapability.contentFormat = this._client.supporedMarkupKind - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.hoverProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: HoverRegistrationOptions - ): [Disposable, HoverProvider] { - const provider: HoverProvider = { - provideHover: (document, position, token) => { - const client = this._client - const provideHover: ProvideHoverSignature = (document, position, token) => { - return client.sendRequest( - HoverRequest.type, - cv.asTextDocumentPositionParams(document, position), - token - ).then(res => res, error => { - return client.handleFailedRequest(HoverRequest.type, token, error, null) - }) - } - - const middleware = client.clientOptions.middleware! - return middleware.provideHover - ? middleware.provideHover(document, position, token, provideHover) - : provideHover(document, position, token) - } - } - - return [languages.registerHoverProvider(options.documentSelector!, provider), provider] - } -} - -class SignatureHelpFeature extends TextDocumentFeature< - SignatureHelpOptions, SignatureHelpRegistrationOptions, SignatureHelpProvider - > { - constructor(client: BaseLanguageClient) { - super(client, SignatureHelpRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - let config = ensure(ensure(capabilities, 'textDocument')!, 'signatureHelp')! - config.dynamicRegistration = true - config.contextSupport = true - config.signatureInformation = { - documentationFormat: this._client.supporedMarkupKind, - activeParameterSupport: true, - parameterInformation: { - labelOffsetSupport: true - } - } as any - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.signatureHelpProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: SignatureHelpRegistrationOptions - ): [Disposable, SignatureHelpProvider] { - const provider: SignatureHelpProvider = { - provideSignatureHelp: (document, position, token, context) => { - const client = this._client - const providerSignatureHelp: ProvideSignatureHelpSignature = (document, position, context, token) => { - return client.sendRequest( - SignatureHelpRequest.type, - cv.asSignatureHelpParams(document, position, context), - token - ).then(res => res, error => { - return client.handleFailedRequest(SignatureHelpRequest.type, token, error, null) - } - ) - } - - const middleware = client.clientOptions.middleware! - return middleware.provideSignatureHelp - ? middleware.provideSignatureHelp(document, position, context, token, providerSignatureHelp) - : providerSignatureHelp(document, position, context, token) - } - } - - const triggerCharacters = options.triggerCharacters || [] - const disposable = languages.registerSignatureHelpProvider(options.documentSelector!, provider, triggerCharacters) - return [disposable, provider] - } -} - -class DefinitionFeature extends TextDocumentFeature< - boolean | DefinitionOptions, DefinitionRegistrationOptions, DefinitionProvider - > { - constructor(client: BaseLanguageClient) { - super(client, DefinitionRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - let definitionSupport = ensure(ensure(capabilities, 'textDocument')!, 'definition')! - definitionSupport.dynamicRegistration = true - // definitionSupport.linkSupport = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.definitionProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: DefinitionRegistrationOptions - ): [Disposable, DefinitionProvider] { - const provider: DefinitionProvider = { - provideDefinition: (document, position, token) => { - const client = this._client - const provideDefinition: ProvideDefinitionSignature = (document, position, token) => { - return client.sendRequest( - DefinitionRequest.type, - cv.asTextDocumentPositionParams(document, position), - token - ).then(res => res, error => { - return client.handleFailedRequest(DefinitionRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideDefinition - ? middleware.provideDefinition(document, position, token, provideDefinition) - : provideDefinition(document, position, token) - } - } - - return [languages.registerDefinitionProvider(options.documentSelector!, provider), provider] - } -} - -class ReferencesFeature extends TextDocumentFeature< - boolean | ReferenceOptions, ReferenceRegistrationOptions, ReferenceProvider - > { - constructor(client: BaseLanguageClient) { - super(client, ReferencesRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure( - ensure(capabilities, 'textDocument')!, - 'references' - )!.dynamicRegistration = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.referencesProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: TextDocumentRegistrationOptions - ): [Disposable, ReferenceProvider] { - const provider: ReferenceProvider = { - provideReferences: (document, position, options, token) => { - const client = this._client - const _providerReferences: ProvideReferencesSignature = (document, position, options, token) => { - return client.sendRequest( - ReferencesRequest.type, - cv.asReferenceParams(document, position, options), - token - ).then(res => res, error => { - return client.handleFailedRequest(ReferencesRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideReferences - ? middleware.provideReferences(document, position, options, token, _providerReferences) - : _providerReferences(document, position, options, token) - } - } - return [languages.registerReferencesProvider(options.documentSelector!, provider), provider] - } -} - -class DocumentHighlightFeature extends TextDocumentFeature< - boolean | DocumentHighlightOptions, DocumentHighlightRegistrationOptions, DocumentHighlightProvider - > { - constructor(client: BaseLanguageClient) { - super(client, DocumentHighlightRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure( - ensure(capabilities, 'textDocument')!, - 'documentHighlight' - )!.dynamicRegistration = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentHighlightProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: TextDocumentRegistrationOptions - ): [Disposable, DocumentHighlightProvider] { - const provider: DocumentHighlightProvider = { - provideDocumentHighlights: (document, position, token) => { - const client = this._client - const _provideDocumentHighlights: ProvideDocumentHighlightsSignature = (document, position, token) => { - return client.sendRequest( - DocumentHighlightRequest.type, - cv.asTextDocumentPositionParams(document, position), - token - ).then(res => res, error => { - return client.handleFailedRequest(DocumentHighlightRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideDocumentHighlights - ? middleware.provideDocumentHighlights(document, position, token, _provideDocumentHighlights) - : _provideDocumentHighlights(document, position, token) - } - } - return [languages.registerDocumentHighlightProvider(options.documentSelector!, provider), provider] - } -} - -class DocumentSymbolFeature extends TextDocumentFeature< - boolean | DocumentSymbolOptions, DocumentSymbolRegistrationOptions, DocumentSymbolProvider - > { - constructor(client: BaseLanguageClient) { - super(client, DocumentSymbolRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - let symbolCapabilities = ensure(ensure(capabilities, 'textDocument')!, 'documentSymbol')! as any - symbolCapabilities.dynamicRegistration = true - symbolCapabilities.symbolKind = { - valueSet: SupportedSymbolKinds - } - symbolCapabilities.hierarchicalDocumentSymbolSupport = true - symbolCapabilities.tagSupport = { - valueSet: SupportedSymbolTags - } - // TODO: capabilities - // symbolCapabilities.labelSupport = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentSymbolProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: DocumentSymbolRegistrationOptions - ): [Disposable, DocumentSymbolProvider] { - const provider: DocumentSymbolProvider = { - provideDocumentSymbols: (document, token) => { - const client = this._client - const _provideDocumentSymbols: ProvideDocumentSymbolsSignature = (document, token) => { - return client.sendRequest( - DocumentSymbolRequest.type, - cv.asDocumentSymbolParams(document), - token - ).then( - (data) => { - if (data === null) { - return undefined - } - if (data.length === 0) { - return [] - } else { - let element = data[0] - if (DocumentSymbol.is(element)) { - return data as DocumentSymbol[] - } else { - return data as SymbolInformation[] - } - } - }, - (error) => { - return client.handleFailedRequest(DocumentSymbolRequest.type, token, error, null) - } - ) - } - const middleware = client.clientOptions.middleware! - return middleware.provideDocumentSymbols - ? middleware.provideDocumentSymbols(document, token, _provideDocumentSymbols) - : _provideDocumentSymbols(document, token) - } - } - const metadata = options.label ? { label: options.label } : undefined - return [languages.registerDocumentSymbolProvider(options.documentSelector!, provider, metadata), provider] - } -} - -class WorkspaceSymbolFeature extends WorkspaceFeature { - constructor(client: BaseLanguageClient) { - super(client, WorkspaceSymbolRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - let symbolCapabilities = ensure( - ensure(capabilities, 'workspace')!, - 'symbol' - )! as any - symbolCapabilities.dynamicRegistration = true - symbolCapabilities.symbolKind = { - valueSet: SupportedSymbolKinds - } - symbolCapabilities.tagSupport = { - valueSet: SupportedSymbolTags - } - } - - public initialize( - capabilities: ServerCapabilities, - ): void { - if (!capabilities.workspaceSymbolProvider) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: capabilities.workspaceSymbolProvider === true ? { workDoneProgress: false } : capabilities.workspaceSymbolProvider - }) - } - - protected registerLanguageProvider(_options: WorkspaceSymbolRegistrationOptions): [Disposable, WorkspaceSymbolProvider] { - const provider: WorkspaceSymbolProvider = { - provideWorkspaceSymbols: (query, token) => { - const client = this._client - const provideWorkspaceSymbols: ProvideWorkspaceSymbolsSignature = (query, token) => { - return client.sendRequest(WorkspaceSymbolRequest.type, { query }, token).then( - res => res, - error => { - return client.handleFailedRequest(WorkspaceSymbolRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideWorkspaceSymbols - ? middleware.provideWorkspaceSymbols(query, token, provideWorkspaceSymbols) - : provideWorkspaceSymbols(query, token) - } - } - return [languages.registerWorkspaceSymbolProvider(provider), provider] - } -} - -class CodeActionFeature extends TextDocumentFeature { - private disposables: Disposable[] = [] - constructor(client: BaseLanguageClient) { - super(client, CodeActionRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - const cap = ensure(ensure(capabilities, 'textDocument')!, 'codeAction')! - cap.dynamicRegistration = true - cap.isPreferredSupport = true - cap.disabledSupport = true - cap.dataSupport = true - cap.honorsChangeAnnotations = false - cap.resolveSupport = { - properties: ['edit'] - } - cap.codeActionLiteralSupport = { - codeActionKind: { - valueSet: [ - CodeActionKind.Empty, - CodeActionKind.QuickFix, - CodeActionKind.Refactor, - CodeActionKind.RefactorExtract, - CodeActionKind.RefactorInline, - CodeActionKind.RefactorRewrite, - CodeActionKind.Source, - CodeActionKind.SourceOrganizeImports - ] - } - } - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.codeActionProvider) - if (!options) { - return - } - - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: CodeActionRegistrationOptions - ): [Disposable, CodeActionProvider] { - const registCommand = (id: string) => { - if (commands.has(id)) return - const client = this._client - const executeCommand: ExecuteCommandSignature = (command: string, args: any[]): any => { - const params: ExecuteCommandParams = { - command, - arguments: args - } - return client.sendRequest(ExecuteCommandRequest.type, params).then(undefined, (error) => { - client.handleFailedRequest(ExecuteCommandRequest.type, undefined, error, undefined) - throw error - }) - } - const middleware = client.clientOptions.middleware! - this.disposables.push(commands.registerCommand(id, (...args: any[]) => { - return middleware.executeCommand - ? middleware.executeCommand(id, args, executeCommand) - : executeCommand(id, args) - }, null, true)) - } - const provider: CodeActionProvider = { - provideCodeActions: (document, range, context, token) => { - const client = this._client - const _provideCodeActions: ProvideCodeActionsSignature = (document, range, context, token) => { - const params: CodeActionParams = { - textDocument: { - uri: document.uri - }, - range, - context, - } - return client.sendRequest(CodeActionRequest.type, params, token).then( - (values) => { - if (values === null) { - return undefined - } - // some server may not registered commands to client. - values.forEach(val => { - let cmd = Command.is(val) ? val.command : val.command?.command - if (cmd && !commands.has(cmd)) registCommand(cmd) - }) - return values - }, - (error) => { - return client.handleFailedRequest(CodeActionRequest.type, token, error, null) - } - ) - } - const middleware = client.clientOptions.middleware! - return middleware.provideCodeActions - ? middleware.provideCodeActions(document, range, context, token, _provideCodeActions) - : _provideCodeActions(document, range, context, token) - }, - resolveCodeAction: options.resolveProvider - ? (item: CodeAction, token: CancellationToken) => { - const client = this._client - const middleware = this._client.clientOptions.middleware! - const resolveCodeAction: ResolveCodeActionSignature = (item, token) => { - return client.sendRequest(CodeActionResolveRequest.type, item, token).then( - (values) => values, - (error) => { - return client.handleFailedRequest(CodeActionResolveRequest.type, token, error, item) - } - ) - } - return middleware.resolveCodeAction - ? middleware.resolveCodeAction(item, token, resolveCodeAction) - : resolveCodeAction(item, token) - } - : undefined - } - return [languages.registerCodeActionProvider(options.documentSelector, provider, this._client.id, options.codeActionKinds), provider] - } - - public dispose(): void { - this.disposables.forEach(o => { - o.dispose() - }) - this.disposables = [] - super.dispose() - } -} - -interface CodeLensProviderData { - provider?: CodeLensProvider - onDidChangeCodeLensEmitter?: Emitter -} - -class CodeLensFeature extends TextDocumentFeature { - constructor(client: BaseLanguageClient) { - super(client, CodeLensRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure( - ensure(capabilities, 'textDocument')!, - 'codeLens' - )!.dynamicRegistration = true - ensure(ensure(capabilities, 'workspace')!, - 'codeLens' - )!.refreshSupport = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const client = this._client - client.onRequest(CodeLensRefreshRequest.type, async () => { - for (const provider of this.getAllProviders()) { - provider.onDidChangeCodeLensEmitter.fire() - } - }) - const options = this.getRegistrationOptions(documentSelector, capabilities.codeLensProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: CodeLensRegistrationOptions - ): [Disposable, CodeLensProviderData] { - const emitter: Emitter = new Emitter() - const provider: CodeLensProvider = { - onDidChangeCodeLenses: emitter.event, - provideCodeLenses: (document, token) => { - const client = this._client - const provideCodeLenses: ProvideCodeLensesSignature = (document, token) => { - return client.sendRequest( - CodeLensRequest.type, - cv.asCodeLensParams(document), - token - ).then(res => res, error => { - return client.handleFailedRequest(CodeLensRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideCodeLenses - ? middleware.provideCodeLenses(document, token, provideCodeLenses) - : provideCodeLenses(document, token) - }, - resolveCodeLens: (options.resolveProvider) - ? (codeLens: CodeLens, token: CancellationToken): ProviderResult => { - const client = this._client - const resolveCodeLens: ResolveCodeLensSignature = (codeLens, token) => { - return client.sendRequest( - CodeLensResolveRequest.type, - codeLens, - token - ).then(res => res, error => { - return client.handleFailedRequest(CodeLensResolveRequest.type, token, error, codeLens) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.resolveCodeLens - ? middleware.resolveCodeLens(codeLens, token, resolveCodeLens) - : resolveCodeLens(codeLens, token) - } - : undefined - } - - return [languages.registerCodeLensProvider(options.documentSelector, provider), { provider, onDidChangeCodeLensEmitter: emitter }] - } -} - -class DocumentFormattingFeature extends TextDocumentFeature< - boolean | DocumentFormattingOptions, DocumentHighlightRegistrationOptions, DocumentFormattingEditProvider - > { - - constructor(client: BaseLanguageClient) { - super(client, DocumentFormattingRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure( - ensure(capabilities, 'textDocument')!, - 'formatting' - )!.dynamicRegistration = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentFormattingProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: TextDocumentRegistrationOptions - ): [Disposable, DocumentFormattingEditProvider] { - const provider: DocumentFormattingEditProvider = { - provideDocumentFormattingEdits: (document, options, token) => { - const client = this._client - const provideDocumentFormattingEdits: ProvideDocumentFormattingEditsSignature = (document, options, token) => { - const params: DocumentFormattingParams = { - textDocument: { uri: document.uri }, - options - } - return client.sendRequest(DocumentFormattingRequest.type, params, token).then(res => res, (error) => { - return client.handleFailedRequest(DocumentFormattingRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideDocumentFormattingEdits - ? middleware.provideDocumentFormattingEdits(document, options, token, provideDocumentFormattingEdits) - : provideDocumentFormattingEdits(document, options, token) - } - } - - return [ - languages.registerDocumentFormatProvider(options.documentSelector!, provider, this._client.clientOptions.formatterPriority), - provider - ] - } -} - -class DocumentRangeFormattingFeature extends TextDocumentFeature< - boolean | DocumentRangeFormattingOptions, DocumentRangeFormattingRegistrationOptions, DocumentRangeFormattingEditProvider - > { - constructor(client: BaseLanguageClient) { - super(client, DocumentRangeFormattingRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure( - ensure(capabilities, 'textDocument')!, - 'rangeFormatting' - )!.dynamicRegistration = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentRangeFormattingProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: TextDocumentRegistrationOptions - ): [Disposable, DocumentRangeFormattingEditProvider] { - const provider: DocumentRangeFormattingEditProvider = { - provideDocumentRangeFormattingEdits: (document, range, options, token) => { - const client = this._client - const provideDocumentRangeFormattingEdits: ProvideDocumentRangeFormattingEditsSignature = (document, range, options, token) => { - const params: DocumentRangeFormattingParams = { - textDocument: { uri: document.uri }, - range, - options, - } - return client.sendRequest(DocumentRangeFormattingRequest.type, params, token).then(res => res, error => { - return client.handleFailedRequest(DocumentRangeFormattingRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideDocumentRangeFormattingEdits - ? middleware.provideDocumentRangeFormattingEdits(document, range, options, token, provideDocumentRangeFormattingEdits) - : provideDocumentRangeFormattingEdits(document, range, options, token) - } - } - - return [languages.registerDocumentRangeFormatProvider(options.documentSelector, provider), provider] - } -} - -class DocumentOnTypeFormattingFeature extends TextDocumentFeature< - DocumentOnTypeFormattingOptions, DocumentOnTypeFormattingRegistrationOptions, OnTypeFormattingEditProvider - > { - - constructor(client: BaseLanguageClient) { - super(client, DocumentOnTypeFormattingRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure(ensure(capabilities, 'textDocument')!, 'onTypeFormatting')!.dynamicRegistration = true - } - - public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentOnTypeFormattingProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider(options: DocumentOnTypeFormattingRegistrationOptions): [Disposable, OnTypeFormattingEditProvider] { - const provider: OnTypeFormattingEditProvider = { - provideOnTypeFormattingEdits: (document, position, ch, options, token) => { - const client = this._client - const provideOnTypeFormattingEdits: ProvideOnTypeFormattingEditsSignature = (document, position, ch, options, token) => { - const params: DocumentOnTypeFormattingParams = { - textDocument: cv.asVersionedTextDocumentIdentifier(document), - position, - ch, - options - } - return client.sendRequest(DocumentOnTypeFormattingRequest.type, params, token).then(res => res, (error) => { - return client.handleFailedRequest(DocumentOnTypeFormattingRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideOnTypeFormattingEdits - ? middleware.provideOnTypeFormattingEdits(document, position, ch, options, token, provideOnTypeFormattingEdits) - : provideOnTypeFormattingEdits(document, position, ch, options, token) - } - } - - const moreTriggerCharacter = options.moreTriggerCharacter || [] - const characters = [options.firstTriggerCharacter, ...moreTriggerCharacter] - return [languages.registerOnTypeFormattingEditProvider(options.documentSelector!, provider, characters), provider] - } -} - -interface DefaultBehavior { - defaultBehavior: boolean -} - -class RenameFeature extends TextDocumentFeature { - constructor(client: BaseLanguageClient) { - super(client, RenameRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - let rename = ensure(ensure(capabilities, 'textDocument')!, 'rename')! - rename.dynamicRegistration = true - rename.prepareSupport = true - // TODO: capabilities - // rename.honorsChangeAnnotations = true - // rename.prepareSupportDefaultBehavior = PrepareSupportDefaultBehavior.Identifier - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.renameProvider) - if (!options) { - return - } - if (Is.boolean(capabilities.renameProvider)) { - options.prepareProvider = false - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider(options: RenameRegistrationOptions): [Disposable, RenameProvider] { - const provider: RenameProvider = { - provideRenameEdits: (document, position, newName, token) => { - const client = this._client - const provideRenameEdits: ProvideRenameEditsSignature = (document, position, newName, token) => { - const params: RenameParams = { - textDocument: { uri: document.uri }, - position, - newName: newName - } - return client.sendRequest(RenameRequest.type, params, token).then(res => res, (error: ResponseError) => { - return client.handleFailedRequest(RenameRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideRenameEdits - ? middleware.provideRenameEdits(document, position, newName, token, provideRenameEdits) - : provideRenameEdits(document, position, newName, token) - }, - prepareRename: options.prepareProvider - ? (document, position, token) => { - const client = this._client - const prepareRename: PrepareRenameSignature = (document, position, token) => { - const params: TextDocumentPositionParams = { - textDocument: cv.asTextDocumentIdentifier(document), - position - } - return client.sendRequest(PrepareRenameRequest.type, params, token).then( - (result) => { - if (Range.is(result)) { - return result - } else if (this.isDefaultBehavior(result)) { - return result.defaultBehavior === true ? null : Promise.reject(new Error(`The element can't be renamed.`)) - } else if (result && Range.is(result.range)) { - return { - range: result.range, - placeholder: result.placeholder - } - } - // To cancel the rename vscode API expects a rejected promise. - return Promise.reject(new Error(`The element can't be renamed.`)) - }, - (error: ResponseError) => { - return client.handleFailedRequest(PrepareRenameRequest.type, token, error, undefined) - } - ) - } - const middleware = client.clientOptions.middleware! - return middleware.prepareRename - ? middleware.prepareRename(document, position, token, prepareRename) - : prepareRename(document, position, token) - } - : undefined - } - - return [languages.registerRenameProvider(options.documentSelector, provider), provider] - } - - private isDefaultBehavior(value: any): value is DefaultBehavior { - const candidate: DefaultBehavior = value - return candidate && Is.boolean(candidate.defaultBehavior) - } -} - -class DocumentLinkFeature extends TextDocumentFeature { - constructor(client: BaseLanguageClient) { - super(client, DocumentLinkRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - const documentLinkCapabilities = ensure(ensure(capabilities, 'textDocument')!, 'documentLink')! - documentLinkCapabilities.dynamicRegistration = true - // TODO support tooltip - documentLinkCapabilities.tooltipSupport = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const options = this.getRegistrationOptions(documentSelector, capabilities.documentLinkProvider) - if (!options) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: options - }) - } - - protected registerLanguageProvider( - options: DocumentLinkRegistrationOptions - ): [Disposable, DocumentLinkProvider] { - const provider: DocumentLinkProvider = { - provideDocumentLinks: (document: TextDocument, token: CancellationToken): ProviderResult => { - const client = this._client - const provideDocumentLinks: ProvideDocumentLinksSignature = (document, token) => { - return client.sendRequest( - DocumentLinkRequest.type, - { - textDocument: { uri: document.uri } - }, - token - ).then(res => res, (error: ResponseError) => { - return client.handleFailedRequest(DocumentLinkRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideDocumentLinks - ? middleware.provideDocumentLinks(document, token, provideDocumentLinks) - : provideDocumentLinks(document, token) - }, - resolveDocumentLink: options.resolveProvider - ? (link, token) => { - const client = this._client - let resolveDocumentLink: ResolveDocumentLinkSignature = (link, token) => { - return client.sendRequest(DocumentLinkResolveRequest.type, link, token).then(res => res, (error: ResponseError) => { - return client.handleFailedRequest(DocumentLinkResolveRequest.type, token, error, link) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.resolveDocumentLink - ? middleware.resolveDocumentLink(link, token, resolveDocumentLink) - : resolveDocumentLink(link, token) - } - : undefined - } - - return [languages.registerDocumentLinkProvider(options.documentSelector, provider), provider] - } -} - -class ConfigurationFeature implements DynamicFeature { - private _listeners: Map = new Map() - - constructor(private _client: BaseLanguageClient) {} - - public get registrationType(): RegistrationType { - return DidChangeConfigurationNotification.type - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure(ensure(capabilities, 'workspace')!, 'didChangeConfiguration')!.dynamicRegistration = true - } - - public initialize(): void { - let section = this._client.clientOptions.synchronize?.configurationSection - if (section !== undefined) { - this.register({ - id: UUID.generateUuid(), - registerOptions: { - section: section - } - }) - } - } - - public register( - data: RegistrationData - ): void { - let { section } = data.registerOptions - let disposable = workspace.onDidChangeConfiguration((event) => { - if (typeof section == 'string' && !event.affectsConfiguration(section)) { - return - } - if (Array.isArray(section) && !section.some(v => event.affectsConfiguration(v))) { - return - } - if (section != undefined) { - this.onDidChangeConfiguration(data.registerOptions.section) - } - }) - this._listeners.set(data.id, disposable) - if (Is.string(section) && section.endsWith('.settings')) { - let settings = this.getConfiguredSettings(section as string) - if (!settings || Is.emptyObject(settings)) return - } - if (section != undefined) { - // Avoid server bug - this.onDidChangeConfiguration(data.registerOptions.section) - } - } - - public unregister(id: string): void { - let disposable = this._listeners.get(id) - if (disposable) { - this._listeners.delete(id) - disposable.dispose() - } - } - - public dispose(): void { - for (let disposable of this._listeners.values()) { - disposable.dispose() - } - this._listeners.clear() - } - - private onDidChangeConfiguration(configurationSection: string | string[]): void { - let isConfigured = typeof configurationSection === 'string' && configurationSection.startsWith('languageserver.') - let sections: string[] | undefined - if (Is.string(configurationSection)) { - sections = [configurationSection] - } else { - sections = configurationSection - } - let didChangeConfiguration = (sections: string[] | undefined): void => { - if (sections === undefined) { - this._client.sendNotification(DidChangeConfigurationNotification.type, { settings: null }) - return - } - this._client.sendNotification(DidChangeConfigurationNotification.type, { - settings: isConfigured ? this.getConfiguredSettings(sections[0]) : this.extractSettingsInformation(sections) - }) - } - let middleware = this.getMiddleware() - middleware - ? middleware(sections, didChangeConfiguration) - : didChangeConfiguration(sections) - } - - // for configured languageserver - private getConfiguredSettings(key: string): any { - let len = '.settings'.length - let config = workspace.getConfiguration(key.slice(0, - len)) - return config.get('settings', {}) - } - - private extractSettingsInformation(keys: string[]): any { - function ensurePath(config: any, path: string[]): any { - let current = config - for (let i = 0; i < path.length - 1; i++) { - let obj = current[path[i]] - if (!obj) { - obj = Object.create(null) - current[path[i]] = obj - } - current = obj - } - return current - } - let result = Object.create(null) - for (let i = 0; i < keys.length; i++) { - let key = keys[i] - let index: number = key.indexOf('.') - let config: any = null - if (index >= 0) { - config = workspace.getConfiguration(key.substr(0, index)).get(key.substr(index + 1)) - } else { - config = workspace.getConfiguration(key) - } - if (config) { - let path = keys[i].split('.') - ensurePath(result, path)[path[path.length - 1]] = config - } - } - return result - } - - private getMiddleware() { - let middleware = this._client.clientOptions.middleware! - if (middleware.workspace && middleware.workspace.didChangeConfiguration) { - return middleware.workspace.didChangeConfiguration - } else { - return undefined - } - } -} - -class ExecuteCommandFeature - implements DynamicFeature { - private _commands: Map = new Map() - constructor(private _client: BaseLanguageClient) {} - - public get registrationType(): RegistrationType { - return ExecuteCommandRequest.type - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure( - ensure(capabilities, 'workspace')!, - 'executeCommand' - )!.dynamicRegistration = true - } - - public initialize(capabilities: ServerCapabilities): void { - if (!capabilities.executeCommandProvider) { - return - } - this.register({ - id: UUID.generateUuid(), - registerOptions: Object.assign({}, capabilities.executeCommandProvider) - }) - } - - public register( - data: RegistrationData - ): void { - const client = this._client - const middleware = client.clientOptions.middleware! - const executeCommand: ExecuteCommandSignature = (command: string, args: any[]): any => { - const params: ExecuteCommandParams = { - command, - arguments: args - } - return client.sendRequest(ExecuteCommandRequest.type, params).then(undefined, (error) => { - client.handleFailedRequest(ExecuteCommandRequest.type, undefined, error, undefined) - throw error - }) - } - if (data.registerOptions.commands) { - let disposables: Disposable[] = [] - for (const command of data.registerOptions.commands) { - disposables.push(commands.registerCommand(command, (...args: any[]) => { - return middleware.executeCommand - ? middleware.executeCommand(command, args, executeCommand) - : executeCommand(command, args) - }, null, true)) - } - this._commands.set(data.id, disposables) - } - } - - public unregister(id: string): void { - let disposables = this._commands.get(id) - if (disposables) { - disposables.forEach(disposable => disposable.dispose()) - } - } - - public dispose(): void { - this._commands.forEach(value => { - value.forEach(disposable => disposable.dispose()) - }) - this._commands.clear() - } -} - -export interface MessageTransports { - reader: MessageReader - writer: MessageWriter - detached?: boolean -} - -export namespace MessageTransports { - export function is(value: any): value is MessageTransports { - let candidate: MessageTransports = value - return ( - candidate && - MessageReader.is(value.reader) && - MessageWriter.is(value.writer) - ) - } -} - -class OnReady { - private _used: boolean - constructor(private _resolve: () => void, private _reject: (error: any) => void) { - this._used = false - } - - public get isUsed(): boolean { - return this._used - } - - public resolve(): void { - this._used = true - this._resolve() - } - - public reject(error: any): void { - this._used = true - this._reject(error) - } -} - -export abstract class BaseLanguageClient { - private _id: string - private _name: string - private _markdownSupport: boolean - private _clientOptions: ResolvedClientOptions - - protected _state: ClientState - private _onReady: Promise - private _onReadyCallbacks: OnReady - private _onStop: Promise | undefined - private _connectionPromise: Promise | undefined - private _resolvedConnection: IConnection | undefined - private _initializeResult: InitializeResult | undefined - private _outputChannel: OutputChannel | undefined - private _capabilities: ServerCapabilities & ResolvedTextDocumentSyncCapabilities - - private _listeners: Disposable[] | undefined - private _providers: Disposable[] | undefined - private _diagnostics: DiagnosticCollection | undefined - private _syncedDocuments: Map - - private _fileEvents: FileEvent[] - private _fileEventDelayer: Delayer - private _stateChangeEmitter: Emitter - - private _traceFormat: TraceFormat - private _trace: Trace - private _tracer: Tracer - - public constructor( - id: string, - name: string, - clientOptions: LanguageClientOptions - ) { - this._id = id - this._name = name - if (clientOptions.outputChannel) { - this._outputChannel = clientOptions.outputChannel - } else { - this._outputChannel = undefined - } - let disableSnippetCompletion = false - let suggest = workspace.getConfiguration('suggest') - if (suggest.get('snippetsSupport', true) === false || clientOptions.disableSnippetCompletion) { - disableSnippetCompletion = true - } - - const markdown = { isTrusted: false } - if (clientOptions.markdown !== undefined && clientOptions.markdown.isTrusted === true) { - markdown.isTrusted = true - } - - this._clientOptions = { - disableWorkspaceFolders: clientOptions.disableWorkspaceFolders, - disableSnippetCompletion, - disableDynamicRegister: clientOptions.disableDynamicRegister, - disableDiagnostics: clientOptions.disableDiagnostics, - disableCompletion: clientOptions.disableCompletion, - formatterPriority: clientOptions.formatterPriority, - ignoredRootPaths: clientOptions.ignoredRootPaths, - documentSelector: clientOptions.documentSelector || [], - synchronize: clientOptions.synchronize || {}, - diagnosticCollectionName: clientOptions.diagnosticCollectionName, - outputChannelName: clientOptions.outputChannelName || this._id, - revealOutputChannelOn: - clientOptions.revealOutputChannelOn || RevealOutputChannelOn.Never, - stdioEncoding: clientOptions.stdioEncoding || 'utf8', - initializationOptions: clientOptions.initializationOptions, - initializationFailedHandler: clientOptions.initializationFailedHandler, - progressOnInitialization: !!clientOptions.progressOnInitialization, - errorHandler: clientOptions.errorHandler || this.createDefaultErrorHandler(clientOptions.connectionOptions?.maxRestartCount), - middleware: clientOptions.middleware || {}, - workspaceFolder: clientOptions.workspaceFolder, - connectionOptions: clientOptions.connectionOptions, - markdown - } - this.state = ClientState.Initial - this._connectionPromise = undefined - this._resolvedConnection = undefined - this._initializeResult = undefined - this._listeners = undefined - this._providers = undefined - this._diagnostics = undefined - - this._fileEvents = [] - this._fileEventDelayer = new Delayer(250) - this._onReady = new Promise((resolve, reject) => { - this._onReadyCallbacks = new OnReady(resolve, reject) - }) - this._onStop = undefined - this._stateChangeEmitter = new Emitter() - this._trace = Trace.Off - this._tracer = { - log: (messageOrDataObject: string | any, data?: string) => { - if (Is.string(messageOrDataObject)) { - this.logTrace(messageOrDataObject, data) - } else { - this.logObjectTrace(messageOrDataObject) - } - } - } - this._syncedDocuments = new Map() - let preferences = workspace.getConfiguration('coc.preferences') - this._markdownSupport = preferences.get('enableMarkdown', true) - this.registerBuiltinFeatures() - } - - public get supporedMarkupKind(): MarkupKind[] { - if (this._markdownSupport) return [MarkupKind.Markdown, MarkupKind.PlainText] - return [MarkupKind.PlainText] - } - - private get state(): ClientState { - return this._state - } - - public get id(): string { - return this._id - } - - public get name(): string { - return this._name - } - - private set state(value: ClientState) { - let oldState = this.getPublicState() - this._state = value - let newState = this.getPublicState() - if (newState !== oldState) { - this._stateChangeEmitter.fire({ oldState, newState }) - } - } - - public getPublicState(): State { - if (this.state === ClientState.Running) { - return State.Running - } else if (this.state === ClientState.Starting) { - return State.Starting - } else { - return State.Stopped - } - } - - public get initializeResult(): InitializeResult | undefined { - return this._initializeResult - } - - public sendRequest(type: ProtocolRequestType0, token?: CancellationToken): Promise - public sendRequest(type: ProtocolRequestType, params: P, token?: CancellationToken): Promise - public sendRequest(type: RequestType0, token?: CancellationToken): Promise - public sendRequest(type: RequestType, params: P, token?: CancellationToken): Promise - public sendRequest(method: string, token?: CancellationToken): Promise - public sendRequest(method: string, param: any, token?: CancellationToken): Promise - public sendRequest(type: string | MessageSignature, ...params: any[]): Promise { - if (!this.isConnectionActive()) { - throw new Error('Language client is not ready yet') - } - try { - return this._resolvedConnection!.sendRequest(type, ...params) - } catch (error) { - this.error( - `Sending request ${Is.string(type) ? type : type.method} failed.`, - error - ) - throw error - } - } - - public onRequest(type: ProtocolRequestType0, handler: RequestHandler0): Disposable - public onRequest(type: ProtocolRequestType, handler: RequestHandler): Disposable - public onRequest(type: RequestType0, handler: RequestHandler0): Disposable - public onRequest(type: RequestType, handler: RequestHandler): Disposable - public onRequest(method: string, handler: GenericRequestHandler): Disposable - public onRequest(type: string | MessageSignature, handler: GenericRequestHandler): Disposable { - if (!this.isConnectionActive()) { - throw new Error('Language client is not ready yet') - } - try { - return this._resolvedConnection!.onRequest(type, handler) - } catch (error) { - this.error( - `Registering request handler ${Is.string(type) ? type : type.method - } failed.`, - error - ) - throw error - } - } - - public sendNotification(type: ProtocolNotificationType0): void - public sendNotification(type: ProtocolNotificationType, params?: P): void - public sendNotification(type: NotificationType0): void - public sendNotification

    (type: NotificationType

    , params?: P): void - public sendNotification(method: string): void - public sendNotification(method: string, params: any): void - public sendNotification

    (type: string | MessageSignature, params?: P): void { - if (!this.isConnectionActive()) { - throw new Error('Language client is not ready yet') - } - try { - this._resolvedConnection!.sendNotification(type, params) - } catch (error) { - this.error( - `Sending notification ${Is.string(type) ? type : type.method} failed.`, - error - ) - throw error - } - } - - public onNotification(type: ProtocolNotificationType0, handler: NotificationHandler0): Disposable - public onNotification(type: ProtocolNotificationType, handler: NotificationHandler

    ): Disposable - public onNotification(type: NotificationType0, handler: NotificationHandler0): Disposable - public onNotification

    (type: NotificationType

    , handler: NotificationHandler

    ): Disposable - public onNotification(method: string, handler: GenericNotificationHandler): Disposable - public onNotification(type: string | MessageSignature, handler: GenericNotificationHandler): Disposable { - if (!this.isConnectionActive()) { - throw new Error('Language client is not ready yet') - } - try { - return this._resolvedConnection!.onNotification(type, handler) - } catch (error) { - this.error( - `Registering notification handler ${Is.string(type) ? type : type.method - } failed.`, - error - ) - throw error - } - } - - public onProgress

    (type: ProgressType, token: string | number, handler: NotificationHandler

    ): Disposable { - if (!this.isConnectionActive()) { - throw new Error('Language client is not ready yet') - } - try { - if (type == WorkDoneProgress.type) { - const handleWorkDoneProgress = this._clientOptions.middleware!.handleWorkDoneProgress - if (handleWorkDoneProgress !== undefined) { - return this._resolvedConnection!.onProgress(type, token, (params) => { - handleWorkDoneProgress(token, params as any, () => handler(params as unknown as P)) - }) - } - } - return this._resolvedConnection!.onProgress(type, token, handler) - } catch (error) { - this.error(`Registering progress handler for token ${token} failed.`, error) - throw error - } - } - - public sendProgress

    (type: ProgressType

    , token: string | number, value: P): void { - if (!this.isConnectionActive()) { - throw new Error('Language client is not ready yet') - } - try { - this._resolvedConnection!.sendProgress(type, token, value) - } catch (error) { - this.error(`Sending progress for token ${token} failed.`, error) - throw error - } - } - - public get clientOptions(): LanguageClientOptions { - return this._clientOptions - } - - public get onDidChangeState(): Event { - return this._stateChangeEmitter.event - } - - public get outputChannel(): OutputChannel { - if (!this._outputChannel) { - let { outputChannelName } = this._clientOptions - this._outputChannel = window.createOutputChannel(outputChannelName ? outputChannelName : this._name) - } - return this._outputChannel - } - - public get diagnostics(): DiagnosticCollection | undefined { - return this._diagnostics - } - - public createDefaultErrorHandler(maxRestartCount?: number): ErrorHandler { - return new DefaultErrorHandler(this._id, maxRestartCount ?? 4) - } - - public set trace(value: Trace) { - this._trace = value - this.onReady().then( - () => { - this.resolveConnection().then(connection => { - connection.trace(this._trace, this._tracer, { - sendNotification: false, - traceFormat: this._traceFormat - }) - }) - }, - () => {} - ) - } - - private logObjectTrace(data: any): void { - if (data.isLSPMessage && data.type) { - this.outputChannel.append(`[LSP - ${(new Date().toLocaleTimeString())}] `) - } else { - this.outputChannel.append(`[Trace - ${(new Date().toLocaleTimeString())}] `) - } - if (data) { - this.outputChannel.appendLine(`${JSON.stringify(data)}`) - } - } - - private data2String(data: any): string { - if (data instanceof ResponseError) { - const responseError = data as ResponseError - return ` Message: ${responseError.message}\n Code: ${responseError.code - } ${responseError.data ? '\n' + responseError.data.toString() : ''}` - } - if (data instanceof Error) { - if (Is.string(data.stack)) { - return data.stack - } - return (data as Error).message - } - if (Is.string(data)) { - return data - } - return data.toString() - } - - private _appendOutput(type: string, message: string, data?: any): void { - let level = RevealOutputChannelOn.Error - switch (type) { - case 'Info': - level = RevealOutputChannelOn.Info - break - case 'Warn': - level = RevealOutputChannelOn.Warn - break - } - this.outputChannel.appendLine(`[${type} - ${(new Date().toLocaleTimeString())}] ${message}`) - let dataString: string - if (data) { - dataString = this.data2String(data) - this.outputChannel.appendLine(dataString) - } - if (this._clientOptions.revealOutputChannelOn <= level) { - this.outputChannel.show(true) - } - } - - public info(message: string, data?: any): void { - this._appendOutput('Info', message, data) - } - - public warn(message: string, data?: any): void { - this._appendOutput('Warn', message, data) - } - - public error(message: string, data?: any): void { - this._appendOutput('Error', message, data) - } - - private logTrace(message: string, data?: any): void { - this.outputChannel.appendLine(`[Trace - ${(new Date().toLocaleTimeString())}] ${message}`) - if (data) { - this.outputChannel.appendLine(this.data2String(data)) - } - } - - public needsStart(): boolean { - return ( - this.state === ClientState.Initial || - this.state === ClientState.Stopping || - this.state === ClientState.Stopped - ) - } - - public needsStop(): boolean { - return ( - this.state === ClientState.Starting || this.state === ClientState.Running - ) - } - - public onReady(): Promise { - return this._onReady - } - - public get started(): boolean { - return this.state != ClientState.Initial - } - - private isConnectionActive(): boolean { - return this.state === ClientState.Running && !!this._resolvedConnection - } - - public start(): Disposable { - if (this._onReadyCallbacks.isUsed) { - this._onReady = new Promise((resolve, reject) => { - this._onReadyCallbacks = new OnReady(resolve, reject) - }) - } - this._listeners = [] - this._providers = [] - // If we restart then the diagnostics collection is reused. - if (!this._diagnostics) { - let opts = this._clientOptions - let name = opts.diagnosticCollectionName ? opts.diagnosticCollectionName : this._id - this._diagnostics = languages.createDiagnosticCollection(name) - } - - this.state = ClientState.Starting - this.resolveConnection() - .then(connection => { - connection.onLogMessage(message => { - let kind: string - switch (message.type) { - case MessageType.Error: - kind = 'error' - this.error(message.message) - break - case MessageType.Warning: - kind = 'warning' - this.warn(message.message) - break - case MessageType.Info: - kind = 'info' - this.info(message.message) - break - default: - kind = 'log' - this.outputChannel.appendLine(message.message) - } - if (global.hasOwnProperty('__TEST__')) { - console.log(`[${kind}] ${message.message}`) - return - } - }) - connection.onShowMessage(message => { - switch (message.type) { - case MessageType.Error: - window.showErrorMessage(message.message) - break - case MessageType.Warning: - window.showWarningMessage(message.message) - break - case MessageType.Info: - window.showInformationMessage(message.message) - break - default: - window.showInformationMessage(message.message) - } - }) - connection.onRequest(ShowMessageRequest.type, params => { - let messageFunc: (message: string, ...items: T[]) => Thenable - switch (params.type) { - case MessageType.Error: - messageFunc = window.showErrorMessage.bind(window) - break - case MessageType.Warning: - messageFunc = window.showWarningMessage.bind(window) - break - case MessageType.Info: - messageFunc = window.showInformationMessage.bind(window) - break - default: - messageFunc = window.showInformationMessage.bind(window) - } - let actions = params.actions || [] - return messageFunc(params.message, ...actions) - }) - connection.onRequest(ShowDocumentRequest.type, async (params): Promise => { - const showDocument = async (params: ShowDocumentParams): Promise => { - try { - if (params.external === true) { - await workspace.openResource(params.uri) - return { success: true } - } else { - if (params.selection) { - params.selection.start - } - await workspace.jumpTo(params.uri, params.selection?.start) - return { success: true } - } - } catch (error) { - return { success: true } - } - } - const middleware = this._clientOptions.middleware.window?.showDocument - if (middleware !== undefined) { - return middleware(params, showDocument) - } else { - return showDocument(params) - } - }) - connection.onTelemetry(_data => { - // ignored - }) - connection.listen() - // Error is handled in the intialize call. - return this.initialize(connection) - }).then(undefined, error => { - this.state = ClientState.StartFailed - this._onReadyCallbacks.reject(error) - this.error('Starting client failed ', error) - }) - return Disposable.create(() => { - if (this.needsStop()) { - this.stop() - } - }) - } - - private resolveConnection(): Promise { - if (!this._connectionPromise) { - this._connectionPromise = this.createConnection() - } - return this._connectionPromise - } - - private resolveRootPath(): string | null | false { - if (this._clientOptions.workspaceFolder) { - return URI.parse(this._clientOptions.workspaceFolder.uri).fsPath - } - let { ignoredRootPaths } = this._clientOptions - let config = workspace.getConfiguration(this.id) - let rootPatterns = config.get('rootPatterns', []) - let required = config.get('requireRootPattern', false) - let resolved: string - if (rootPatterns && rootPatterns.length) { - let doc = workspace.getDocument(workspace.bufnr) - if (doc && doc.schema == 'file') { - let dir = path.dirname(URI.parse(doc.uri).fsPath) - resolved = resolveRoot(dir, rootPatterns, workspace.cwd) - } - } - if (required && !resolved) return false - let rootPath = resolved || workspace.rootPath || workspace.cwd - if (rootPath === os.homedir() || (ignoredRootPaths && ignoredRootPaths.includes(rootPath))) { - this.warn(`Ignored rootPath ${rootPath} of client "${this._id}"`) - return null - } - return rootPath - } - - private initialize(connection: IConnection): Promise { - this.refreshTrace(connection, false) - let { initializationOptions, progressOnInitialization } = this._clientOptions - let rootPath = this.resolveRootPath() - if (rootPath === false) { - console.warn(`required root pattern not found, server not started.`) - return - } - let initParams: any = { - processId: process.pid, - rootPath: rootPath ? rootPath : null, - rootUri: rootPath ? cv.asUri(URI.file(rootPath)) : null, - capabilities: this.computeClientCapabilities(), - initializationOptions: Is.func(initializationOptions) ? initializationOptions() : initializationOptions, - trace: Trace.toString(this._trace), - workspaceFolders: null, - locale: this.getLocale(), - clientInfo: { - name: 'coc.nvim', - version: workspace.version - } - } - this.fillInitializeParams(initParams) - if (progressOnInitialization) { - const token: ProgressToken = UUID.generateUuid() - initParams.workDoneToken = token - const part = new ProgressPart(connection, token) - part.begin({ title: `initializing ${this.id}`, kind: 'begin' }) - return this.doInitialize(connection, initParams).then((result) => { - part.done() - return result - }, (error) => { - part.cancel() - throw error - }) - } else { - return this.doInitialize(connection, initParams) - } - } - - private doInitialize(connection: IConnection, initParams: InitializeParams): Promise { - return connection.initialize(initParams).then(result => { - this._resolvedConnection = connection - this._initializeResult = result - this.state = ClientState.Running - - let textDocumentSyncOptions: TextDocumentSyncOptions | undefined = undefined - if (Is.number(result.capabilities.textDocumentSync)) { - if (result.capabilities.textDocumentSync === TextDocumentSyncKind.None) { - textDocumentSyncOptions = { - openClose: false, - change: TextDocumentSyncKind.None, - save: undefined - } - } else { - textDocumentSyncOptions = { - openClose: true, - change: result.capabilities.textDocumentSync, - save: { - includeText: false - } - } - } - } else if (result.capabilities.textDocumentSync != null && result.capabilities.textDocumentSync !== undefined) { - textDocumentSyncOptions = result.capabilities.textDocumentSync as TextDocumentSyncOptions - } - this._capabilities = Object.assign({}, result.capabilities, { - resolvedTextDocumentSync: textDocumentSyncOptions - }) - if (!this._clientOptions.disableDiagnostics) { - connection.onDiagnostics(params => this.handleDiagnostics(params)) - } - connection.onRequest(RegistrationRequest.type, params => - this.handleRegistrationRequest(params) - ) - // See https://github.com/Microsoft/vscode-languageserver-node/issues/199 - connection.onRequest('client/registerFeature', params => - this.handleRegistrationRequest(params) - ) - connection.onRequest(UnregistrationRequest.type, params => - this.handleUnregistrationRequest(params) - ) - // See https://github.com/Microsoft/vscode-languageserver-node/issues/199 - connection.onRequest('client/unregisterFeature', params => - this.handleUnregistrationRequest(params) - ) - connection.onRequest(ApplyWorkspaceEditRequest.type, params => - this.handleApplyWorkspaceEdit(params) - ) - - connection.sendNotification(InitializedNotification.type, {}) - - this.hookFileEvents(connection) - this.hookConfigurationChanged(connection) - this.initializeFeatures(connection) - this._onReadyCallbacks.resolve() - return result - }).then(undefined, error => { - if (this._clientOptions.initializationFailedHandler) { - if (this._clientOptions.initializationFailedHandler(error)) { - this.initialize(connection) - } else { - this.stop() - this._onReadyCallbacks.reject(error) - } - } else if ( - error instanceof ResponseError && - error.data && - error.data.retry - ) { - window.showPrompt(error.message + ' Retry?').then(confirmed => { - if (confirmed) { - this.initialize(connection) - } else { - this.stop() - this._onReadyCallbacks.reject(error) - } - }) - } else { - if (error && error.message) { - window.showMessage(error.message, 'error') - } - this.error('Server initialization failed.', error) - this.stop() - this._onReadyCallbacks.reject(error) - } - throw error - }) - } - - public stop(): Promise { - this._initializeResult = undefined - if (!this._connectionPromise) { - this.state = ClientState.Stopped - return Promise.resolve() - } - if (this.state === ClientState.Stopping && this._onStop) { - return this._onStop - } - this.state = ClientState.Stopping - this.cleanUp() - // unkook listeners - return (this._onStop = this.resolveConnection().then(connection => { - return connection.shutdown().then(() => { - connection.exit() - connection.dispose() - this.state = ClientState.Stopped - this.cleanUpChannel() - this._onStop = undefined - this._connectionPromise = undefined - this._resolvedConnection = undefined - }) - }).catch(e => { - logger.error('Error on stop languageserver:', e) - this.state = ClientState.Stopped - this.cleanUpChannel() - this._onStop = undefined - this._connectionPromise = undefined - this._resolvedConnection = undefined - })) - } - - private cleanUp(channel: boolean = true, diagnostics: boolean = true): void { - if (this._listeners) { - this._listeners.forEach(listener => listener.dispose()) - this._listeners = undefined - } - if (this._providers) { - this._providers.forEach(provider => provider.dispose()) - this._providers = undefined - } - for (let feature of this._features.values()) { - if (typeof feature.dispose === 'function') { - feature.dispose() - } else { - logger.error(`Feature can't be disposed`, feature) - } - } - if (this._syncedDocuments) { - this._syncedDocuments.clear() - } - if (channel) { - this.cleanUpChannel() - } - if (this._diagnostics) { - if (diagnostics) { - this._diagnostics.dispose() - this._diagnostics = undefined - } else { - this._diagnostics.clear() - } - } - } - - private cleanUpChannel(): void { - if (this._outputChannel) { - this._outputChannel.dispose() - this._outputChannel = undefined - } - } - - private notifyFileEvent(event: FileEvent): void { - const client = this - function didChangeWatchedFile(this: void, event: FileEvent) { - client._fileEvents.push(event) - client._fileEventDelayer.trigger(() => { - client.onReady().then(() => { - client.resolveConnection().then(connection => { - if (client.isConnectionActive()) { - connection.didChangeWatchedFiles({ changes: client._fileEvents }) - } - client._fileEvents = [] - }) - }, (error) => { - client.error(`Notify file events failed.`, error) - }) - }) - } - const workSpaceMiddleware = this.clientOptions.middleware?.workspace - workSpaceMiddleware?.didChangeWatchedFile ? workSpaceMiddleware.didChangeWatchedFile(event, didChangeWatchedFile) : didChangeWatchedFile(event) - } - - private handleDiagnostics(params: PublishDiagnosticsParams) { - if (!this._diagnostics) { - return - } - let { uri, diagnostics } = params - let middleware = this.clientOptions.middleware!.handleDiagnostics - if (middleware) { - middleware(uri, diagnostics, (uri, diagnostics) => - this.setDiagnostics(uri, diagnostics) - ) - } else { - this.setDiagnostics(uri, diagnostics) - } - } - - private setDiagnostics(uri: string, diagnostics: Diagnostic[] | undefined) { - if (!this._diagnostics) { - return - } - - const separate = workspace.getConfiguration('diagnostic').get('separateRelatedInformationAsDiagnostics') as boolean - if (separate && diagnostics.length > 0) { - const entries: Map = new Map() - entries.set(uri, diagnostics) - - for (const diagnostic of diagnostics) { - if (diagnostic.relatedInformation?.length) { - let message = `${diagnostic.message}\n\nRelated diagnostics:\n` - for (const info of diagnostic.relatedInformation) { - const basename = path.basename(URI.parse(info.location.uri).fsPath) - const ln = info.location.range.start.line - message = `${message}\n${basename}(line ${ln + 1}): ${info.message}` - - const diags: Diagnostic[] = entries.get(info.location.uri) || [] - diags.push(Diagnostic.create(info.location.range, info.message, DiagnosticSeverity.Hint, diagnostic.code, diagnostic.source)) - entries.set(info.location.uri, diags) - } - diagnostic.message = message - } - this._diagnostics.set(Array.from(entries)) - } - } else { - this._diagnostics.set(uri, diagnostics) - } - } - - protected abstract createMessageTransports( - encoding: string - ): Promise - - private createConnection(): Promise { - let errorHandler = (error: Error, message: Message | undefined, count: number | undefined) => { - logger.error('connection error:', error, message) - this.handleConnectionError(error, message, count) - } - - let closeHandler = () => { - this.handleConnectionClosed() - } - - return this.createMessageTransports( - this._clientOptions.stdioEncoding || 'utf8' - ).then(transports => { - return createConnection( - transports.reader, - transports.writer, - errorHandler, - closeHandler, - this._clientOptions.connectionOptions - ) - }) - } - - protected handleConnectionClosed() { - // Check whether this is a normal shutdown in progress or the client stopped normally. - if (this.state === ClientState.Stopped) { - return - } - try { - if (this._resolvedConnection) { - this._resolvedConnection.dispose() - } - } catch (error) { - // Disposing a connection could fail if error cases. - } - let action = CloseAction.DoNotRestart - if (this.state !== ClientState.Stopping) { - try { - action = this._clientOptions.errorHandler!.closed() - } catch (error) { - // Ignore errors coming from the error handler. - } - } - this._connectionPromise = undefined - this._resolvedConnection = undefined - if (action === CloseAction.DoNotRestart) { - this.error( - 'Connection to server got closed. Server will not be restarted.' - ) - if (this.state === ClientState.Starting) { - this._onReadyCallbacks.reject(new Error(`Connection to server got closed. Server will not be restarted.`)) - this.state = ClientState.StartFailed - } else { - this.state = ClientState.Stopped - } - this.cleanUp(false, true) - } else if (action === CloseAction.Restart) { - this.info('Connection to server got closed. Server will restart.') - this.cleanUp(false, true) - this.state = ClientState.Initial - this.start() - } - } - - public restart(): void { - this.cleanUp(true, false) - this.start() - } - - private handleConnectionError(error: Error, message: Message, count: number) { - let action = this._clientOptions.errorHandler!.error(error, message, count) - if (action === ErrorAction.Shutdown) { - this.error('Connection to server is erroring. Shutting down server.') - this.stop() - } - } - - private hookConfigurationChanged(connection: IConnection): void { - workspace.onDidChangeConfiguration(() => { - this.refreshTrace(connection, true) - }) - } - - private refreshTrace( - connection: IConnection, - sendNotification: boolean = false - ): void { - let config = workspace.getConfiguration(this._id) - let trace: Trace = Trace.Off - let traceFormat: TraceFormat = TraceFormat.Text - if (config) { - const traceConfig = config.get('trace.server', 'off') - - if (typeof traceConfig === 'string') { - trace = Trace.fromString(traceConfig) - } else { - trace = Trace.fromString(config.get('trace.server.verbosity', 'off')) - traceFormat = TraceFormat.fromString(config.get('trace.server.format', 'text')) - } - } - this._trace = trace - this._traceFormat = traceFormat - connection.trace(this._trace, this._tracer, { - sendNotification, - traceFormat: this._traceFormat - }) - } - - private hookFileEvents(_connection: IConnection): void { - let fileEvents = this._clientOptions.synchronize.fileEvents - if (!fileEvents) return - let watchers: FileWatcher[] - if (Array.isArray(fileEvents)) { - watchers = fileEvents - } else { - watchers = [fileEvents] - } - if (!watchers) { - return - } - (this._dynamicFeatures.get( - DidChangeWatchedFilesNotification.type.method - )! as FileSystemWatcherFeature).registerRaw(UUID.generateUuid(), watchers) - } - - private readonly _features: (StaticFeature | DynamicFeature)[] = [] - private readonly _dynamicFeatures: Map> = new Map< - string, - DynamicFeature - >() - - public registerFeatures( - features: (StaticFeature | DynamicFeature)[] - ): void { - for (let feature of features) { - this.registerFeature(feature) - } - } - - public registerFeature(feature: StaticFeature | DynamicFeature): void { - this._features.push(feature) - if (DynamicFeature.is(feature)) { - const registrationType = feature.registrationType - this._dynamicFeatures.set(registrationType.method, feature) - } - } - - public getFeature(request: typeof DidOpenTextDocumentNotification.method): DynamicFeature & NotificationFeature<(textDocument: TextDocument) => void> - public getFeature(request: typeof DidChangeTextDocumentNotification.method): DynamicFeature & NotificationFeature<(textDocument: TextDocument) => void> - public getFeature(request: typeof WillSaveTextDocumentNotification.method): DynamicFeature & NotificationFeature<(textDocument: TextDocument) => void> - public getFeature(request: typeof WillSaveTextDocumentWaitUntilRequest.method): DynamicFeature & NotificationFeature<(textDocument: TextDocument) => ProviderResult> - public getFeature(request: typeof DidSaveTextDocumentNotification.method): DynamicFeature & NotificationFeature<(textDocument: TextDocument) => void> - public getFeature(request: typeof DidCloseTextDocumentNotification.method): DynamicFeature & NotificationFeature<(textDocument: TextDocument) => void> - public getFeature(request: typeof DidCreateFilesNotification.method): DynamicFeature & { send: (event: FileCreateEvent) => Promise } - public getFeature(request: typeof DidRenameFilesNotification.method): DynamicFeature & { send: (event: FileRenameEvent) => Promise } - public getFeature(request: typeof DidDeleteFilesNotification.method): DynamicFeature & { send: (event: FileDeleteEvent) => Promise } - public getFeature(request: typeof WillCreateFilesRequest.method): DynamicFeature & { send: (event: FileWillCreateEvent) => Promise } - public getFeature(request: typeof WillRenameFilesRequest.method): DynamicFeature & { send: (event: FileWillRenameEvent) => Promise } - public getFeature(request: typeof WillDeleteFilesRequest.method): DynamicFeature & { send: (event: FileWillDeleteEvent) => Promise } - public getFeature(request: typeof CompletionRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof HoverRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof SignatureHelpRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof DefinitionRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof ReferencesRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof DocumentHighlightRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof CodeActionRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof DocumentFormattingRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof DocumentRangeFormattingRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof DocumentOnTypeFormattingRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof RenameRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof DocumentSymbolRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof DocumentLinkRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof DocumentColorRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof DeclarationRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof FoldingRangeRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof ImplementationRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof SelectionRangeRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof TypeDefinitionRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof CallHierarchyPrepareRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof SemanticTokensRegistrationType.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof LinkedEditingRangeRequest.method): DynamicFeature & TextDocumentProviderFeature - public getFeature(request: typeof WorkspaceSymbolRequest.method): DynamicFeature & WorkspaceProviderFeature - public getFeature(request: string): DynamicFeature | undefined { - return this._dynamicFeatures.get(request) - } - - protected registerBuiltinFeatures() { - this.registerFeature(new ConfigurationFeature(this)) - this.registerFeature(new DidOpenTextDocumentFeature(this, this._syncedDocuments)) - this.registerFeature(new DidChangeTextDocumentFeature(this)) - this.registerFeature(new WillSaveFeature(this)) - this.registerFeature(new WillSaveWaitUntilFeature(this)) - this.registerFeature(new DidSaveTextDocumentFeature(this)) - this.registerFeature(new DidCloseTextDocumentFeature(this, this._syncedDocuments)) - this.registerFeature(new FileSystemWatcherFeature(this, event => this.notifyFileEvent(event))) - if (!this._clientOptions.disableCompletion) { - this.registerFeature(new CompletionItemFeature(this)) - } - this.registerFeature(new HoverFeature(this)) - this.registerFeature(new SignatureHelpFeature(this)) - this.registerFeature(new DefinitionFeature(this)) - this.registerFeature(new ReferencesFeature(this)) - this.registerFeature(new DocumentHighlightFeature(this)) - this.registerFeature(new DocumentSymbolFeature(this)) - this.registerFeature(new WorkspaceSymbolFeature(this)) - this.registerFeature(new CodeActionFeature(this)) - this.registerFeature(new CodeLensFeature(this)) - this.registerFeature(new DocumentFormattingFeature(this)) - this.registerFeature(new DocumentRangeFormattingFeature(this)) - this.registerFeature(new DocumentOnTypeFormattingFeature(this)) - this.registerFeature(new RenameFeature(this)) - this.registerFeature(new DocumentLinkFeature(this)) - this.registerFeature(new ExecuteCommandFeature(this)) - } - - private fillInitializeParams(params: InitializeParams): void { - for (let feature of this._features) { - if (Is.func(feature.fillInitializeParams)) { - feature.fillInitializeParams(params) - } - } - } - - private computeClientCapabilities(): ClientCapabilities { - const result: ClientCapabilities = {} - ensure(result, 'workspace')!.applyEdit = true - const workspaceEdit = ensure(ensure(result, 'workspace')!, 'workspaceEdit')! - workspaceEdit.documentChanges = true - workspaceEdit.resourceOperations = [ResourceOperationKind.Create, ResourceOperationKind.Rename, ResourceOperationKind.Delete] - workspaceEdit.failureHandling = FailureHandlingKind.TextOnlyTransactional - // TODO: capabilities - // workspaceEdit.normalizesLineEndings = true - // workspaceEdit.changeAnnotationSupport = { - // groupsOnLabel: true - // } - const diagnostics = ensure(ensure(result, 'textDocument')!, 'publishDiagnostics')! - diagnostics.relatedInformation = true - diagnostics.versionSupport = false - diagnostics.tagSupport = { valueSet: [DiagnosticTag.Unnecessary, DiagnosticTag.Deprecated] } - // TODO: capabilities - // diagnostics.dataSupport = true - // diagnostics.codeDescriptionSupport = true - - // TODO: capabilities, disabled by default - const windowCapabilities = ensure(result, 'window')! - const showMessage = ensure(windowCapabilities, 'showMessage')! - showMessage.messageActionItem = { additionalPropertiesSupport: false } - const showDocument = ensure(windowCapabilities, 'showDocument')! - showDocument.support = false - - const generalCapabilities = ensure(result, 'general')! - generalCapabilities.regularExpressions = { engine: 'ECMAScript', version: 'ES2020' } - generalCapabilities.markdown = { parser: 'marked', version: '1.1.0' } - - for (let feature of this._features) { - feature.fillClientCapabilities(result) - } - return result - } - - private initializeFeatures(_connection: IConnection): void { - let documentSelector = this._clientOptions.documentSelector - for (let feature of this._features) { - feature.initialize(this._capabilities, documentSelector) - } - } - - private handleRegistrationRequest( - params: RegistrationParams - ): Promise { - if (this.clientOptions.disableDynamicRegister) return Promise.resolve() - return new Promise((resolve, reject) => { - for (const registration of params.registrations) { - const feature = this._dynamicFeatures.get(registration.method) - if (!feature) { - reject( - new Error( - `No feature implementation for ${registration.method} found. Registration failed.` - ) - ) - return - } - const options = registration.registerOptions || {} - options.documentSelector = options.documentSelector || this._clientOptions.documentSelector - const data: RegistrationData = { - id: registration.id, - registerOptions: options - } - try { - feature.register(data) - } catch (err) { - reject(err) - return - } - } - resolve() - }) - } - - private handleUnregistrationRequest( - params: UnregistrationParams - ): Promise { - return new Promise((resolve, reject) => { - for (let unregistration of params.unregisterations) { - const feature = this._dynamicFeatures.get(unregistration.method) - if (!feature) { - reject( - new Error( - `No feature implementation for ${unregistration.method} found. Unregistration failed.` - ) - ) - return - } - feature.unregister(unregistration.id) - } - resolve() - }) - } - - private handleApplyWorkspaceEdit( - params: ApplyWorkspaceEditParams - ): Promise { - // This is some sort of workaround since the version check should be done by VS Code in the Workspace.applyEdit. - // However doing it here adds some safety since the server can lag more behind then an extension. - let workspaceEdit: WorkspaceEdit = params.edit - let openTextDocuments: Map = new Map() - workspace.textDocuments.forEach((document) => openTextDocuments.set(document.uri.toString(), document)) - let versionMismatch = false - if (workspaceEdit.documentChanges) { - for (const change of workspaceEdit.documentChanges) { - if (TextDocumentEdit.is(change) && change.textDocument.version && change.textDocument.version >= 0) { - let textDocument = openTextDocuments.get(change.textDocument.uri) - if (textDocument && textDocument.version !== change.textDocument.version) { - versionMismatch = true - break - } - } - } - } - if (versionMismatch) { - return Promise.resolve({ applied: false }) - } - return workspace.applyEdit(params.edit).then(value => { - return { applied: value } - }) - } - - private getLocale(): string { - const lang = process.env.LANG - if (!lang) return 'en' - - return lang.split('.')[0] - } - - public handleFailedRequest(type: MessageSignature, token: CancellationToken | undefined, error: any, defaultValue: T): T { - // If we get a request cancel or a content modified don't log anything. - if (error instanceof ResponseError) { - if (error.code === LSPErrorCodes.RequestCancelled) { - if (token !== undefined && token.isCancellationRequested) { - return defaultValue - } - // do not throw error - } else if (error.code === LSPErrorCodes.ContentModified) { - return defaultValue - } - } - this.error(`Request ${type.method} failed.`, error) - } - - public logFailedRequest(type: any, error: any): void { - // If we get a request cancel don't log anything. - if (error instanceof ResponseError && error.code === LSPErrorCodes.RequestCancelled) { - // TODO: handle LSPErrorCodes.ContentModified - return - } - this.error(`Request ${type.method} failed.`, error) - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/colorProvider.ts b/vim-config/plugins/coc.nvim/src/language-client/colorProvider.ts deleted file mode 100644 index fcfd1a5a..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/colorProvider.ts +++ /dev/null @@ -1,116 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -'use strict' - -import { CancellationToken, ClientCapabilities, Color, ColorInformation, ColorPresentation, ColorPresentationRequest, Disposable, DocumentColorOptions, DocumentColorRegistrationOptions, DocumentColorRequest, DocumentSelector, Range, ServerCapabilities } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import languages from '../languages' -import { DocumentColorProvider, ProviderResult } from '../provider' -import { BaseLanguageClient, TextDocumentFeature } from './client' - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = {} as any - } - return target[key] -} - -export type ProvideDocumentColorsSignature = (document: TextDocument, token: CancellationToken) => ProviderResult - -export type ProvideColorPresentationSignature = ( - color: Color, - context: { document: TextDocument; range: Range }, - token: CancellationToken -) => ProviderResult - -export interface ColorProviderMiddleware { - provideDocumentColors?: ( - this: void, - document: TextDocument, - token: CancellationToken, - next: ProvideDocumentColorsSignature - ) => ProviderResult - provideColorPresentations?: ( - this: void, - color: Color, - context: { document: TextDocument; range: Range }, - token: CancellationToken, - next: ProvideColorPresentationSignature - ) => ProviderResult -} - -export class ColorProviderFeature extends TextDocumentFeature< - boolean | DocumentColorOptions, DocumentColorRegistrationOptions, DocumentColorProvider - > { - constructor(client: BaseLanguageClient) { - super(client, DocumentColorRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure( - ensure(capabilities, 'textDocument')!, - 'colorProvider' - )!.dynamicRegistration = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - let [id, options] = this.getRegistration(documentSelector, capabilities.colorProvider) - if (!id || !options) { - return - } - - this.register({ id, registerOptions: options }) - } - - protected registerLanguageProvider( - options: DocumentColorRegistrationOptions - ): [Disposable, DocumentColorProvider] { - const provider: DocumentColorProvider = { - provideColorPresentations: (color, context, token) => { - const client = this._client - const provideColorPresentations: ProvideColorPresentationSignature = (color, context, token) => { - const requestParams = { - color, - textDocument: { uri: context.document.uri }, - range: context.range - } - return client.sendRequest(ColorPresentationRequest.type, requestParams, token).then( - res => res, - (error: any) => { - return client.handleFailedRequest(ColorPresentationRequest.type, token, error, null) - } - ) - } - const middleware = client.clientOptions.middleware - return middleware.provideColorPresentations - ? middleware.provideColorPresentations(color, context, token, provideColorPresentations) - : provideColorPresentations(color, context, token) - }, - provideDocumentColors: (document, token) => { - const client = this._client - const provideDocumentColors: ProvideDocumentColorsSignature = (document, token) => { - const requestParams = { - textDocument: { uri: document.uri } - } - return client.sendRequest(DocumentColorRequest.type, requestParams, token).then( - res => res, - (error: any) => { - return client.handleFailedRequest(ColorPresentationRequest.type, token, error, null) - } - ) - } - const middleware = client.clientOptions.middleware - return middleware.provideDocumentColors - ? middleware.provideDocumentColors(document, token, provideDocumentColors) - : provideDocumentColors(document, token) - } - } - - return [languages.registerDocumentColorProvider(options.documentSelector, provider), provider] - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/configuration.ts b/vim-config/plugins/coc.nvim/src/language-client/configuration.ts deleted file mode 100644 index c2c9f646..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/configuration.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -import { ClientCapabilities, ConfigurationRequest } from 'vscode-languageserver-protocol' -import workspace from '../workspace' -import { BaseLanguageClient, StaticFeature } from './client' -const logger = require('../util/logger')('languageclient-configuration') - -export interface ConfigurationWorkspaceMiddleware { - configuration?: ConfigurationRequest.MiddlewareSignature -} - -export class ConfigurationFeature implements StaticFeature { - private languageserverSection: string | undefined - constructor(private _client: BaseLanguageClient) { - let section = this._client.clientOptions.synchronize?.configurationSection - if (typeof section === 'string' && section.startsWith('languageserver.')) { - this.languageserverSection = section - } - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - capabilities.workspace = capabilities.workspace || {} - capabilities.workspace.configuration = true - } - - public initialize(): void { - let client = this._client - client.onRequest(ConfigurationRequest.type, (params, token) => { - let configuration: ConfigurationRequest.HandlerSignature = params => { - let result: any[] = [] - for (let item of params.items) { - result.push(this.getConfiguration(item.scopeUri, item.section)) - } - return result - } - let middleware = client.clientOptions.middleware.workspace - return middleware && middleware.configuration - ? middleware.configuration(params, token, configuration) - : configuration(params, token) - }) - } - - private getConfiguration( - resource: string | undefined, - section: string | undefined - ): any { - let result: any = null - if (section) { - if (this.languageserverSection) { - section = `${this.languageserverSection}.${section}` - } - let index = section.lastIndexOf('.') - if (index === -1) { - result = toJSONObject(workspace.getConfiguration(undefined, resource).get(section)) - } else { - let config = workspace.getConfiguration(section.substr(0, index), resource) - if (config) { - result = toJSONObject(config.get(section.substr(index + 1))) - } - } - } else { - let config = workspace.getConfiguration(this.languageserverSection, resource) - result = {} - for (let key of Object.keys(config)) { - if (config.has(key)) { - result[key] = toJSONObject(config.get(key)) - } - } - } - return result - } - - public dispose(): void { - } -} - -export function toJSONObject(obj: any): any { - if (obj) { - if (Array.isArray(obj)) { - return obj.map(toJSONObject) - } else if (typeof obj === 'object') { - const res = Object.create(null) - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - res[key] = toJSONObject(obj[key]) - } - } - return res - } - } - return obj -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/declaration.ts b/vim-config/plugins/coc.nvim/src/language-client/declaration.ts deleted file mode 100644 index 2e1a195e..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/declaration.ts +++ /dev/null @@ -1,67 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -'use strict' - -import { CancellationToken, ClientCapabilities, Declaration, DeclarationLink, DeclarationOptions, DeclarationRegistrationOptions, DeclarationRequest, Disposable, DocumentSelector, Position, ServerCapabilities } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import languages from '../languages' -import { DeclarationProvider, ProviderResult } from '../provider' -import { BaseLanguageClient, TextDocumentFeature } from './client' -import { asTextDocumentPositionParams } from './utils/converter' - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = {} as any - } - return target[key] -} - -export interface ProvideDeclarationSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult -} - -export interface DeclarationMiddleware { - provideDeclaration?: (this: void, document: TextDocument, position: Position, token: CancellationToken, next: ProvideDeclarationSignature) => ProviderResult -} - -export class DeclarationFeature extends TextDocumentFeature { - - constructor(client: BaseLanguageClient) { - super(client, DeclarationRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - let declarationSupport = ensure(ensure(capabilities, 'textDocument')!, 'declaration')! - declarationSupport.dynamicRegistration = true - // declarationSupport.linkSupport = true - } - - public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { - const [id, options] = this.getRegistration(documentSelector, capabilities.declarationProvider) - if (!id || !options) { - return - } - this.register({ id, registerOptions: options }) - } - - protected registerLanguageProvider(options: DeclarationRegistrationOptions): [Disposable, DeclarationProvider] { - const provider: DeclarationProvider = { - provideDeclaration: (document: TextDocument, position: Position, token: CancellationToken) => { - const client = this._client - const provideDeclaration: ProvideDeclarationSignature = (document, position, token) => client.sendRequest(DeclarationRequest.type, asTextDocumentPositionParams(document, position), token).then( - res => res, error => { - return client.handleFailedRequest(DeclarationRequest.type, token, error, null) - } - ) - const middleware = client.clientOptions.middleware - return middleware.provideDeclaration - ? middleware.provideDeclaration(document, position, token, provideDeclaration) - : provideDeclaration(document, position, token) - } - } - - return [languages.registerDeclarationProvider(options.documentSelector, provider), provider] - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/fileOperations.ts b/vim-config/plugins/coc.nvim/src/language-client/fileOperations.ts deleted file mode 100644 index 3d3397c1..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/fileOperations.ts +++ /dev/null @@ -1,436 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import * as minimatch from 'minimatch' -import { ClientCapabilities, CreateFilesParams, DeleteFilesParams, DidCreateFilesNotification, DidDeleteFilesNotification, DidRenameFilesNotification, Disposable, Event, FileOperationClientCapabilities, FileOperationOptions, FileOperationPatternKind, FileOperationPatternOptions, FileOperationRegistrationOptions, ProtocolNotificationType, ProtocolRequestType, RegistrationType, RenameFilesParams, ServerCapabilities, WillCreateFilesRequest, WillDeleteFilesRequest, WillRenameFilesRequest, WorkspaceEdit } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import { FileCreateEvent, FileDeleteEvent, FileRenameEvent, FileType, FileWillCreateEvent, FileWillDeleteEvent, FileWillRenameEvent } from '../types' -import { statAsync } from '../util/fs' -import workspace from '../workspace' -import { BaseLanguageClient, DynamicFeature, NextSignature, RegistrationData } from './client' -import * as UUID from './utils/uuid' -const logger = require('../util/logger')('language-client-fileOperations') - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = {} as any - } - return target[key] -} - -function access(target: T, key: K): T[K] { - return target[key] -} - -function assign(target: T, key: K, value: T[K]): void { - target[key] = value -} - -function asCreateDeleteFilesParams(e: FileCreateEvent | FileDeleteEvent): CreateFilesParams | DeleteFilesParams { - return { - files: e.files.map(f => ({uri: f.toString()})) - } -} - -function asRenameFilesParams(e: FileRenameEvent | FileWillRenameEvent): RenameFilesParams { - return { - files: e.files.map(f => ({oldUri: f.oldUri.toString(), newUri: f.newUri.toString()})) - } -} - -/** - * File operation middleware - * - * @since 3.16.0 - */ -export interface FileOperationsMiddleware { - didCreateFiles?: NextSignature; - willCreateFiles?: NextSignature>; - didRenameFiles?: NextSignature; - willRenameFiles?: NextSignature>; - didDeleteFiles?: NextSignature; - willDeleteFiles?: NextSignature>; -} - -interface EventWithFiles { - readonly files: ReadonlyArray; -} - -abstract class FileOperationFeature> - implements DynamicFeature { - protected _client: BaseLanguageClient - private _event: Event - private _registrationType: RegistrationType - private _clientCapability: keyof FileOperationClientCapabilities - private _serverCapability: keyof FileOperationOptions - private _listener: Disposable | undefined - private _filters = new Map< - string, - Array<{ - scheme?: string; - matcher: minimatch.IMinimatch; - kind?: FileOperationPatternKind; - }> - >() - - constructor( - client: BaseLanguageClient, - event: Event, - registrationType: RegistrationType, - clientCapability: keyof FileOperationClientCapabilities, - serverCapability: keyof FileOperationOptions - ) { - this._client = client - this._event = event - this._registrationType = registrationType - this._clientCapability = clientCapability - this._serverCapability = serverCapability - } - - public get registrationType(): RegistrationType { - return this._registrationType - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - const value = ensure(ensure(capabilities, 'workspace')!, 'fileOperations')! - // this happens n times but it is the same value so we tolerate this. - assign(value, 'dynamicRegistration', true) - assign(value, this._clientCapability, true) - } - - public initialize(capabilities: ServerCapabilities): void { - const options = capabilities.workspace?.fileOperations - const capability = options !== undefined ? access(options, this._serverCapability) : undefined - if (capability?.filters !== undefined) { - try { - this.register({ - id: UUID.generateUuid(), - registerOptions: { filters: capability.filters }, - }) - } catch (e) { - this._client.warn( - `Ignoring invalid glob pattern for ${this._serverCapability} registration: ${e}` - ) - } - } - } - - public register(data: RegistrationData): void { - if (!this._listener) { - this._listener = this._event(this.send, this) - } - const minimatchFilter = data.registerOptions.filters.map(filter => { - const matcher = new minimatch.Minimatch( - filter.pattern.glob, - FileOperationFeature.asMinimatchOptions(filter.pattern.options) - ) - if (!matcher.makeRe()) { - throw new Error(`Invalid pattern ${filter.pattern.glob}!`) - } - return { scheme: filter.scheme, matcher, kind: filter.pattern.matches } - }) - this._filters.set(data.id, minimatchFilter) - } - - public abstract send(data: E): Promise - - public unregister(id: string): void { - this._filters.delete(id) - if (this._filters.size === 0 && this._listener) { - this._listener.dispose() - this._listener = undefined - } - } - - public dispose(): void { - this._filters.clear() - if (this._listener) { - this._listener.dispose() - this._listener = undefined - } - } - - protected async filter(event: E, prop: (i: I) => URI): Promise { - // (Asynchronously) map each file onto a boolean of whether it matches - // any of the globs. - const fileMatches = await Promise.all( - event.files.map(async item => { - const uri = prop(item) - // Use fsPath to make this consistent with file system watchers but help - // minimatch to use '/' instead of `\\` if present. - const path = uri.fsPath.replace(/\\/g, '/') - for (const filters of this._filters.values()) { - for (const filter of filters) { - if (filter.scheme !== undefined && filter.scheme !== uri.scheme) { - continue - } - if (filter.matcher.match(path)) { - // The pattern matches. If kind is undefined then everything is ok - if (filter.kind === undefined) { - return true - } - const fileType = await FileOperationFeature.getFileType(uri) - // If we can't determine the file type than we treat it as a match. - // Dropping it would be another alternative. - if (fileType === undefined) { - this._client.error( - `Failed to determine file type for ${uri.toString()}.` - ) - return true - } - if ( - (fileType === FileType.File && filter.kind === FileOperationPatternKind.file) || - (fileType === FileType.Directory && filter.kind === FileOperationPatternKind.folder) - ) { - return true - } - } else if (filter.kind === FileOperationPatternKind.folder) { - const fileType = await FileOperationFeature.getFileType(uri) - if (fileType === FileType.Directory && filter.matcher.match(`${path}/`)) { - return true - } - } - } - } - return false - }) - ) - - // Filter the files to those that matched. - const files = event.files.filter((_, index) => fileMatches[index]) - - return { ...event, files } - } - - private static async getFileType(uri: URI): Promise { - try { - const stat = await statAsync(uri.fsPath) - if (stat.isFile()) { - return FileType.File - } - if (stat.isDirectory()) { - return FileType.Directory - } - if (stat.isSymbolicLink()) { - return FileType.SymbolicLink - } - return FileType.Unknown - } catch (e) { - return undefined - } - } - - private static asMinimatchOptions(options: FileOperationPatternOptions | undefined): minimatch.IOptions | undefined { - if (options === undefined) { - return undefined - } - if (options.ignoreCase === true) { - return { nocase: true } - } - return undefined - } -} - -abstract class NotificationFileOperationFeature; }, P> extends FileOperationFeature { - - private _notificationType: ProtocolNotificationType - private _accessUri: (i: I) => URI - private _createParams: (e: E) => P - - constructor( - client: BaseLanguageClient, - event: Event, - notificationType: ProtocolNotificationType, - clientCapability: keyof FileOperationClientCapabilities, - serverCapability: keyof FileOperationOptions, - accessUri: (i: I) => URI, - createParams: (e: E) => P - ) { - super(client, event, notificationType, clientCapability, serverCapability) - this._notificationType = notificationType - this._accessUri = accessUri - this._createParams = createParams - } - - public async send(originalEvent: E): Promise { - // Create a copy of the event that has the files filtered to match what the - // server wants. - const filteredEvent = await this.filter(originalEvent, this._accessUri) - if (filteredEvent.files.length) { - const next = async (event: E): Promise => { - this._client.sendNotification( - this._notificationType, - this._createParams(event) - ) - } - this.doSend(filteredEvent, next) - } - } - - protected abstract doSend(event: E, next: (event: E) => void): void -} - -export class DidCreateFilesFeature extends NotificationFileOperationFeature { - constructor(client: BaseLanguageClient) { - super( - client, - workspace.onDidCreateFiles, - DidCreateFilesNotification.type, - 'didCreate', - 'didCreate', - (i: URI) => i, - e => asCreateDeleteFilesParams(e), - ) - } - - protected doSend(event: FileCreateEvent, next: (event: FileCreateEvent) => void): void { - const middleware = this._client.clientOptions.middleware?.workspace - return middleware?.didCreateFiles ? middleware.didCreateFiles(event, next) : next(event) - } -} - -export class DidRenameFilesFeature extends NotificationFileOperationFeature<{ oldUri: URI; newUri: URI }, FileRenameEvent, RenameFilesParams> { - constructor(client: BaseLanguageClient) { - super( - client, - workspace.onDidRenameFiles, - DidRenameFilesNotification.type, - 'didRename', - 'didRename', - (i: { oldUri: URI; newUri: URI }) => i.oldUri, - e => asRenameFilesParams(e) - ) - } - - protected doSend(event: FileRenameEvent, next: (event: FileRenameEvent) => void): void { - const middleware = this._client.clientOptions.middleware?.workspace - return middleware?.didRenameFiles ? middleware.didRenameFiles(event, next) : next(event) - } -} - -export class DidDeleteFilesFeature extends NotificationFileOperationFeature { - constructor(client: BaseLanguageClient) { - super( - client, - workspace.onDidDeleteFiles, - DidDeleteFilesNotification.type, - 'didDelete', - 'didDelete', - (i: URI) => i, - e => asCreateDeleteFilesParams(e) - ) - } - - protected doSend(event: FileCreateEvent, next: (event: FileCreateEvent) => void): void { - const middleware = this._client.clientOptions.middleware?.workspace - return middleware?.didDeleteFiles ? middleware.didDeleteFiles(event, next) : next(event) - } -} - -interface RequestEvent { - readonly files: ReadonlyArray; - waitUntil(thenable: Thenable): void; -} - -abstract class RequestFileOperationFeature, P> extends FileOperationFeature { - private _requestType: ProtocolRequestType - private _accessUri: (i: I) => URI - private _createParams: (e: EventWithFiles) => P - - constructor( - client: BaseLanguageClient, - event: Event, - requestType: ProtocolRequestType, - clientCapability: keyof FileOperationClientCapabilities, - serverCapability: keyof FileOperationOptions, - accessUri: (i: I) => URI, - createParams: (e: EventWithFiles) => P - ) { - super(client, event, requestType, clientCapability, serverCapability) - this._requestType = requestType - this._accessUri = accessUri - this._createParams = createParams - } - - public async send(originalEvent: E & RequestEvent): Promise { - const waitUntil = this.waitUntil(originalEvent) - originalEvent.waitUntil(waitUntil) - } - - private async waitUntil(originalEvent: E): Promise { - // Create a copy of the event that has the files filtered to match what the - // server wants. - const filteredEvent = await this.filter(originalEvent, this._accessUri) - - if (filteredEvent.files.length) { - const next = (event: EventWithFiles): Promise => { - return this._client.sendRequest(this._requestType, this._createParams(event)) - } - return this.doSend(filteredEvent, next) - } else { - return undefined - } - } - - protected abstract doSend(event: E, next: (event: EventWithFiles) => Thenable | Thenable): Thenable | Thenable -} - -export class WillCreateFilesFeature extends RequestFileOperationFeature { - constructor(client: BaseLanguageClient) { - super( - client, - workspace.onWillCreateFiles, - WillCreateFilesRequest.type, - 'willCreate', - 'willCreate', - (i: URI) => i, - e => asCreateDeleteFilesParams(e) - ) - } - - protected doSend(event: FileWillCreateEvent, next: (event: FileCreateEvent) => Thenable | Thenable): Thenable | Thenable { - const middleware = this._client.clientOptions.middleware?.workspace - return middleware?.willCreateFiles ? middleware.willCreateFiles(event, next) : next(event) - } -} - -export class WillRenameFilesFeature extends RequestFileOperationFeature<{ oldUri: URI; newUri: URI }, FileWillRenameEvent, RenameFilesParams> { - constructor(client: BaseLanguageClient) { - super( - client, - workspace.onWillRenameFiles, - WillRenameFilesRequest.type, - 'willRename', - 'willRename', - (i: { oldUri: URI; newUri: URI }) => i.oldUri, - e => asRenameFilesParams(e) - ) - } - - protected doSend(event: FileWillRenameEvent, next: (event: FileRenameEvent) => Thenable | Thenable): Thenable | Thenable { - const middleware = this._client.clientOptions.middleware?.workspace - return middleware?.willRenameFiles ? middleware.willRenameFiles(event, next) : next(event) - } -} - -export class WillDeleteFilesFeature extends RequestFileOperationFeature { - constructor(client: BaseLanguageClient) { - super( - client, - workspace.onWillDeleteFiles, - WillDeleteFilesRequest.type, - 'willDelete', - 'willDelete', - (i: URI) => i, - e => asCreateDeleteFilesParams(e) - ) - } - - protected doSend(event: FileWillDeleteEvent, next: (event: FileDeleteEvent) => Thenable | Thenable): Thenable | Thenable { - const middleware = this._client.clientOptions.middleware?.workspace - return middleware?.willDeleteFiles ? middleware.willDeleteFiles(event, next) : next(event) - } -} - diff --git a/vim-config/plugins/coc.nvim/src/language-client/foldingRange.ts b/vim-config/plugins/coc.nvim/src/language-client/foldingRange.ts deleted file mode 100644 index 07ce1b4d..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/foldingRange.ts +++ /dev/null @@ -1,90 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -'use strict' - -import { CancellationToken, ClientCapabilities, Disposable, DocumentSelector, FoldingRange, FoldingRangeOptions, FoldingRangeParams, FoldingRangeRegistrationOptions, FoldingRangeRequest, ServerCapabilities } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import languages from '../languages' -import { FoldingContext, FoldingRangeProvider, ProviderResult } from '../provider' -import { BaseLanguageClient, TextDocumentFeature } from './client' - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = {} as any - } - return target[key] -} - -export type ProvideFoldingRangeSignature = ( - this: void, - document: TextDocument, - context: FoldingContext, - token: CancellationToken -) => ProviderResult - -export interface FoldingRangeProviderMiddleware { - provideFoldingRanges?: ( - this: void, - document: TextDocument, - context: FoldingContext, - token: CancellationToken, - next: ProvideFoldingRangeSignature - ) => ProviderResult -} - -export class FoldingRangeFeature extends TextDocumentFeature< - boolean | FoldingRangeOptions, FoldingRangeRegistrationOptions, FoldingRangeProvider - > { - constructor(client: BaseLanguageClient) { - super(client, FoldingRangeRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - let capability = ensure( - ensure(capabilities, 'textDocument')!, - 'foldingRange' - )! - capability.dynamicRegistration = true - capability.rangeLimit = 5000 - capability.lineFoldingOnly = true - } - - public initialize( - capabilities: ServerCapabilities, - documentSelector: DocumentSelector - ): void { - const [id, options] = this.getRegistration(documentSelector, capabilities.foldingRangeProvider) - if (!id || !options) { - return - } - this.register({ id, registerOptions: options }) - } - - protected registerLanguageProvider( - options: FoldingRangeRegistrationOptions - ): [Disposable, FoldingRangeProvider] { - const provider: FoldingRangeProvider = { - provideFoldingRanges: (document, context, token) => { - const client = this._client - const provideFoldingRanges: ProvideFoldingRangeSignature = (document, _, token) => { - const requestParams: FoldingRangeParams = { - textDocument: { uri: document.uri } - } - return client.sendRequest(FoldingRangeRequest.type, requestParams, token).then( - res => res, (error: any) => { - return client.handleFailedRequest(FoldingRangeRequest.type, token, error, null) - } - ) - } - const middleware = client.clientOptions.middleware - return middleware.provideFoldingRanges - ? middleware.provideFoldingRanges(document, context, token, provideFoldingRanges) - : provideFoldingRanges(document, context, token) - } - } - - return [languages.registerFoldingRangeProvider(options.documentSelector, provider), provider] - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/implementation.ts b/vim-config/plugins/coc.nvim/src/language-client/implementation.ts deleted file mode 100644 index 1874beec..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/implementation.ts +++ /dev/null @@ -1,65 +0,0 @@ -/* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -import { CancellationToken, ClientCapabilities, Definition, DefinitionLink, Disposable, DocumentSelector, ImplementationOptions, ImplementationRegistrationOptions, ImplementationRequest, Position, ServerCapabilities } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import languages from '../languages' -import { ImplementationProvider, ProviderResult } from '../provider' -import { BaseLanguageClient, TextDocumentFeature } from './client' -import * as cv from './utils/converter' - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = {} as any - } - return target[key] -} - -export interface ProvideImplementationSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult -} - -export interface ImplementationMiddleware { - provideImplementation?: (this: void, document: TextDocument, position: Position, token: CancellationToken, next: ProvideImplementationSignature) => ProviderResult -} - -export class ImplementationFeature extends TextDocumentFeature { - - constructor(client: BaseLanguageClient) { - super(client, ImplementationRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - const implementationSupport = ensure(ensure(capabilities, 'textDocument')!, 'implementation')! - implementationSupport.dynamicRegistration = true - // implementationSupport.linkSupport = true - } - - public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { - const [id, options] = this.getRegistration(documentSelector, capabilities.implementationProvider) - if (!id || !options) { - return - } - this.register({ id, registerOptions: options }) - } - - protected registerLanguageProvider(options: ImplementationRegistrationOptions): [Disposable, ImplementationProvider] { - const provider: ImplementationProvider = { - provideImplementation: (document, position, token) => { - const client = this._client - const provideImplementation: ProvideImplementationSignature = (document, position, token) => client.sendRequest(ImplementationRequest.type, cv.asTextDocumentPositionParams(document, position), token).then( - res => res, error => { - return client.handleFailedRequest(ImplementationRequest.type, token, error, null) - } - ) - const middleware = client.clientOptions.middleware - return middleware.provideImplementation - ? middleware.provideImplementation(document, position, token, provideImplementation) - : provideImplementation(document, position, token) - } - } - - return [languages.registerImplementationProvider(options.documentSelector, provider), provider] - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/index.ts b/vim-config/plugins/coc.nvim/src/language-client/index.ts deleted file mode 100644 index e7fdfc85..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/index.ts +++ /dev/null @@ -1,637 +0,0 @@ -/* eslint-disable no-redeclare */ -import cp from 'child_process' -import fs from 'fs' -import path from 'path' -import { createClientPipeTransport, createClientSocketTransport, Disposable, generateRandomPipeName, IPCMessageReader, IPCMessageWriter, StreamMessageReader, StreamMessageWriter } from 'vscode-languageserver-protocol/node' -import { ServiceStat } from '../types' -import { disposeAll } from '../util' -import * as Is from '../util/is' -import { terminate } from '../util/processes' -import workspace from '../workspace' -import { BaseLanguageClient, ClientState, DynamicFeature, LanguageClientOptions, MessageTransports, StaticFeature } from './client' -import { ColorProviderFeature } from './colorProvider' -import { ConfigurationFeature as PullConfigurationFeature } from './configuration' -import { DeclarationFeature } from './declaration' -import { FoldingRangeFeature } from './foldingRange' -import { ImplementationFeature } from './implementation' -import { ProgressFeature } from './progress' -import { TypeDefinitionFeature } from './typeDefinition' -import { WorkspaceFoldersFeature } from './workspaceFolders' -import { SelectionRangeFeature } from './selectionRange' -import ChildProcess = cp.ChildProcess -import { CallHierarchyFeature } from './callHierarchy' -import { SemanticTokensFeature } from './semanticTokens' -import { LinkedEditingFeature } from './linkedEditingRange' -import { DidCreateFilesFeature, DidDeleteFilesFeature, DidRenameFilesFeature, WillCreateFilesFeature, WillDeleteFilesFeature, WillRenameFilesFeature } from './fileOperations' - -const logger = require('../util/logger')('language-client-index') - -export * from './client' - -declare let v8debug: any - -export interface ExecutableOptions { - cwd?: string - env?: any - detached?: boolean - shell?: boolean -} - -export interface Executable { - command: string - args?: string[] - options?: ExecutableOptions -} - -namespace Executable { - export function is(value: any): value is Executable { - return Is.string(value.command) - } -} - -export interface ForkOptions { - cwd?: string - env?: any - execPath?: string - encoding?: string - execArgv?: string[] -} - -export enum TransportKind { - stdio, - ipc, - pipe, - socket -} - -export interface SocketTransport { - kind: TransportKind.socket - port: number -} - -namespace Transport { - export function isSocket(value: Transport): value is SocketTransport { - let candidate = value as SocketTransport - return ( - candidate && - candidate.kind === TransportKind.socket && - Is.number(candidate.port) - ) - } -} - -/** - * To avoid any timing, pipe name or port number issues the pipe (TransportKind.pipe) - * and the sockets (TransportKind.socket and SocketTransport) are owned by the - * VS Code processes. The server process simply connects to the pipe / socket. - * In node term the VS Code process calls `createServer`, then starts the server - * process, waits until the server process has connected to the pipe / socket - * and then signals that the connection has been established and messages can - * be send back and forth. If the language server is implemented in a different - * programm language the server simply needs to create a connection to the - * passed pipe name or port number. - */ -export type Transport = TransportKind | SocketTransport - -export interface NodeModule { - module: string - transport?: Transport - args?: string[] - runtime?: string - options?: ForkOptions -} - -namespace NodeModule { - export function is(value: any): value is NodeModule { - return Is.string(value.module) - } -} - -export interface StreamInfo { - writer: NodeJS.WritableStream - reader: NodeJS.ReadableStream - detached?: boolean -} - -namespace StreamInfo { - export function is(value: any): value is StreamInfo { - let candidate = value as StreamInfo - return ( - candidate && candidate.writer !== void 0 && candidate.reader !== void 0 - ) - } -} - -export interface ChildProcessInfo { - process: ChildProcess - detached: boolean -} - -namespace ChildProcessInfo { - export function is(value: any): value is ChildProcessInfo { - let candidate = value as ChildProcessInfo - return ( - candidate && - candidate.process !== void 0 && - typeof candidate.detached === 'boolean' - ) - } -} - -export type ServerOptions = - | Executable - | { run: Executable; debug: Executable } - | { run: NodeModule; debug: NodeModule } - | NodeModule - | (() => Promise) - -export class LanguageClient extends BaseLanguageClient { - private _forceDebug: boolean - private _serverProcess: ChildProcess | undefined - private _isDetached: boolean | undefined - private _serverOptions: ServerOptions - - public constructor( - name: string, - serverOptions: ServerOptions, - clientOptions: LanguageClientOptions, - forceDebug?: boolean - ) - public constructor( - id: string, - name: string, - serverOptions: ServerOptions, - clientOptions: LanguageClientOptions, - forceDebug?: boolean - ) - public constructor( - arg1: string, - arg2: string | ServerOptions, - arg3: LanguageClientOptions | ServerOptions, - arg4?: boolean | LanguageClientOptions, - arg5?: boolean - ) { - let id: string - let name: string - let serverOptions: ServerOptions - let clientOptions: LanguageClientOptions - let forceDebug: boolean - if (Is.string(arg2)) { - id = arg1 - name = arg2 - serverOptions = arg3 as ServerOptions - clientOptions = arg4 as LanguageClientOptions - forceDebug = !!arg5 - } else { - // first signature - id = arg1.toLowerCase() - name = arg1 - serverOptions = arg2 - clientOptions = arg3 as LanguageClientOptions - forceDebug = arg4 as boolean - } - if (forceDebug === void 0) { - forceDebug = false - } - super(id, name, clientOptions) - this._serverOptions = serverOptions - this._forceDebug = forceDebug - this.registerProposedFeatures() - } - - public stop(): Promise { - return super.stop().then(() => { - if (this._serverProcess) { - let toCheck = this._serverProcess - this._serverProcess = undefined - if (this._isDetached === void 0 || !this._isDetached) { - this.checkProcessDied(toCheck) - } - this._isDetached = undefined - } - }) - } - - public get serviceState(): ServiceStat { - let state = this._state - switch (state) { - case ClientState.Initial: - return ServiceStat.Initial - case ClientState.Running: - return ServiceStat.Running - case ClientState.StartFailed: - return ServiceStat.StartFailed - case ClientState.Starting: - return ServiceStat.Starting - case ClientState.Stopped: - return ServiceStat.Stopped - case ClientState.Stopping: - return ServiceStat.Stopping - default: - logger.error(`Unknown state: ${state}`) - return ServiceStat.Stopped - } - } - - public static stateName(state: ClientState): string { - switch (state) { - case ClientState.Initial: - return 'Initial' - case ClientState.Running: - return 'Running' - case ClientState.StartFailed: - return 'StartFailed' - case ClientState.Starting: - return 'Starting' - case ClientState.Stopped: - return 'Stopped' - case ClientState.Stopping: - return 'Stopping' - default: - return 'Unknonw' - } - } - - private checkProcessDied(childProcess: ChildProcess | undefined): void { - if (!childProcess || global.hasOwnProperty('__TEST__')) return - if (global.hasOwnProperty('__TEST__')) { - process.kill(childProcess.pid, 0) - return - } - setTimeout(() => { - // Test if the process is still alive. Throws an exception if not - try { - process.kill(childProcess.pid, 0) - terminate(childProcess) - } catch (error) { - // All is fine. - } - }, 2000) - } - - protected handleConnectionClosed(): void { - this._serverProcess = undefined - super.handleConnectionClosed() - } - - protected createMessageTransports(encoding: string): Promise { - - function getEnvironment(env: any, fork: boolean): any { - if (!env && !fork) { - return undefined - } - let result: any = Object.create(null) - Object.keys(process.env).forEach(key => result[key] = process.env[key]) - if (env) { - Object.keys(env).forEach(key => result[key] = env[key]) - } - return result - } - - const debugStartWith: string[] = ['--debug=', '--debug-brk=', '--inspect=', '--inspect-brk='] - const debugEquals: string[] = ['--debug', '--debug-brk', '--inspect', '--inspect-brk'] - function startedInDebugMode(): boolean { - let args: string[] = (process as any).execArgv - if (args) { - return args.some(arg => { - return debugStartWith.some(value => arg.startsWith(value)) || - debugEquals.some(value => arg === value) - }) - } - return false - } - - function assertStdio(process: cp.ChildProcess): asserts process is cp.ChildProcessWithoutNullStreams { - if (process.stdin === null || process.stdout === null || process.stderr === null) { - throw new Error('Process created without stdio streams') - } - } - - let server = this._serverOptions - // We got a function. - if (Is.func(server)) { - return server().then(result => { - if (MessageTransports.is(result)) { - this._isDetached = !!result.detached - return result - } else if (StreamInfo.is(result)) { - this._isDetached = !!result.detached - return { - reader: new StreamMessageReader(result.reader), - writer: new StreamMessageWriter(result.writer) - } - } else { - let cp: ChildProcess - if (ChildProcessInfo.is(result)) { - cp = result.process - this._isDetached = result.detached - } else { - cp = result - this._isDetached = false - } - cp.stderr!.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - return { - reader: new StreamMessageReader(cp.stdout!), - writer: new StreamMessageWriter(cp.stdin!) - } - } - }) - } - let json: NodeModule | Executable - let runDebug = server as { run: any; debug: any } - if (runDebug.run || runDebug.debug) { - if (typeof v8debug === 'object' || this._forceDebug || startedInDebugMode()) { - json = runDebug.debug - } else { - json = runDebug.run - } - } else { - json = server as NodeModule | Executable - } - return this._getServerWorkingDir(json.options).then(serverWorkingDir => { - if (NodeModule.is(json) && json.module) { - let node = json - let transport = node.transport || TransportKind.stdio - if (node.runtime) { - let args: string[] = [] - let options: ForkOptions = node.options || Object.create(null) - if (options.execArgv) { - options.execArgv.forEach(element => args.push(element)) - } - args.push(node.module) - if (node.args) { - node.args.forEach(element => args.push(element)) - } - const execOptions: cp.SpawnOptionsWithoutStdio = Object.create(null) - execOptions.cwd = serverWorkingDir - execOptions.env = getEnvironment(options.env, false) - const runtime = this._getRuntimePath(node.runtime, serverWorkingDir) - let pipeName: string | undefined - if (transport === TransportKind.ipc) { - // exec options not correctly typed in lib - execOptions.stdio = [null, null, null, 'ipc'] as any - args.push('--node-ipc') - } else if (transport === TransportKind.stdio) { - args.push('--stdio') - } else if (transport === TransportKind.pipe) { - pipeName = generateRandomPipeName() - args.push(`--pipe=${pipeName}`) - } else if (Transport.isSocket(transport)) { - args.push(`--socket=${transport.port}`) - } - args.push(`--clientProcessId=${process.pid.toString()}`) - if (transport === TransportKind.ipc || transport === TransportKind.stdio) { - let serverProcess = cp.spawn(runtime, args, execOptions) - if (!serverProcess || !serverProcess.pid) { - return Promise.reject(`Launching server using runtime ${runtime} failed.`) - } - this._serverProcess = serverProcess - serverProcess.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - if (transport === TransportKind.ipc) { - serverProcess.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - return Promise.resolve({ reader: new IPCMessageReader(serverProcess), writer: new IPCMessageWriter(serverProcess) }) - } else { - return Promise.resolve({ reader: new StreamMessageReader(serverProcess.stdout), writer: new StreamMessageWriter(serverProcess.stdin) }) - } - } else if (transport === TransportKind.pipe) { - return createClientPipeTransport(pipeName!).then(transport => { - let process = cp.spawn(runtime, args, execOptions) - if (!process || !process.pid) { - return Promise.reject(`Launching server using runtime ${runtime} failed.`) - } - this._serverProcess = process - process.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - process.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - return transport.onConnected().then(protocol => { - return { reader: protocol[0], writer: protocol[1] } - }) - }) - } else if (Transport.isSocket(transport)) { - return createClientSocketTransport(transport.port).then(transport => { - let process = cp.spawn(runtime, args, execOptions) - if (!process || !process.pid) { - return Promise.reject(`Launching server using runtime ${runtime} failed.`) - } - this._serverProcess = process - process.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - process.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - return transport.onConnected().then(protocol => { - return { reader: protocol[0], writer: protocol[1] } - }) - }) - } - } else { - let pipeName: string | undefined - return new Promise((resolve, _reject) => { - let args = node.args && node.args.slice() || [] - if (transport === TransportKind.ipc) { - args.push('--node-ipc') - } else if (transport === TransportKind.stdio) { - args.push('--stdio') - } else if (transport === TransportKind.pipe) { - pipeName = generateRandomPipeName() - args.push(`--pipe=${pipeName}`) - } else if (Transport.isSocket(transport)) { - args.push(`--socket=${transport.port}`) - } - args.push(`--clientProcessId=${process.pid.toString()}`) - let options: cp.ForkOptions = node.options || Object.create(null) - options.env = getEnvironment(options.env, true) - options.execArgv = options.execArgv || [] - options.cwd = serverWorkingDir - options.silent = true - if (transport === TransportKind.ipc || transport === TransportKind.stdio) { - let sp = cp.fork(node.module, args || [], options) - assertStdio(sp) - this._serverProcess = sp - sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - if (transport === TransportKind.ipc) { - sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - resolve({ reader: new IPCMessageReader(this._serverProcess), writer: new IPCMessageWriter(this._serverProcess) }) - } else { - resolve({ reader: new StreamMessageReader(sp.stdout), writer: new StreamMessageWriter(sp.stdin) }) - } - } else if (transport === TransportKind.pipe) { - void createClientPipeTransport(pipeName!).then(transport => { - let sp = cp.fork(node.module, args || [], options) - assertStdio(sp) - this._serverProcess = sp - sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - void transport.onConnected().then(protocol => { - resolve({ reader: protocol[0], writer: protocol[1] }) - }) - }) - } else if (Transport.isSocket(transport)) { - void createClientSocketTransport(transport.port).then(transport => { - let sp = cp.fork(node.module, args || [], options) - assertStdio(sp) - this._serverProcess = sp - sp.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - sp.stdout.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - void transport.onConnected().then(protocol => { - resolve({ reader: protocol[0], writer: protocol[1] }) - }) - }) - } - }) - } - } else if (Executable.is(json) && json.command) { - let command: Executable = json - let args = command.args || [] - let options = Object.assign({}, command.options) - options.env = options.env ? Object.assign({}, process.env, options.env) : process.env - options.cwd = options.cwd || serverWorkingDir - let cmd = workspace.expand(json.command) - let serverProcess = cp.spawn(cmd, args, options) - serverProcess.on('error', e => { - this.error(e.message) - logger.error(e) - }) - if (!serverProcess || !serverProcess.pid) { - return Promise.reject(`Launching server "${this.id}" using command ${command.command} failed.`) - } - logger.info(`Language server "${this.id}" started with ${serverProcess.pid}`) - serverProcess.on('exit', code => { - if (code != 0) this.error(`${command.command} exited with code: ${code}`) - }) - serverProcess.stderr.on('data', data => this.outputChannel.append(Is.string(data) ? data : data.toString(encoding))) - this._serverProcess = serverProcess - this._isDetached = !!options.detached - return Promise.resolve({ reader: new StreamMessageReader(serverProcess.stdout), writer: new StreamMessageWriter(serverProcess.stdin) }) - } - return Promise.reject(`Unsupported server configuration ${JSON.stringify(server, null, 2)}`) - }) - - } - - private _getRuntimePath(runtime: string, serverWorkingDirectory: string | undefined): string { - if (path.isAbsolute(runtime)) { - return runtime - } - const mainRootPath = this._mainGetRootPath() - if (mainRootPath !== undefined) { - const result = path.join(mainRootPath, runtime) - if (fs.existsSync(result)) { - return result - } - } - if (serverWorkingDirectory !== undefined) { - const result = path.join(serverWorkingDirectory, runtime) - if (fs.existsSync(result)) { - return result - } - } - return runtime - } - - private _mainGetRootPath(): string | undefined { - let folders = workspace.workspaceFolders - if (!folders || folders.length === 0) { - return undefined - } - let folder = folders[0] - return folder.uri - } - - public registerProposedFeatures(): void { - this.registerFeatures(ProposedFeatures.createAll(this)) - } - - protected registerBuiltinFeatures(): void { - super.registerBuiltinFeatures() - this.registerFeature(new PullConfigurationFeature(this)) - this.registerFeature(new TypeDefinitionFeature(this)) - this.registerFeature(new ImplementationFeature(this)) - this.registerFeature(new DeclarationFeature(this)) - this.registerFeature(new ColorProviderFeature(this)) - this.registerFeature(new FoldingRangeFeature(this)) - this.registerFeature(new SelectionRangeFeature(this)) - this.registerFeature(new ProgressFeature(this)) - this.registerFeature(new CallHierarchyFeature(this)) - if (workspace.isNvim || (workspace.isVim && workspace.env.textprop)) { - const config = workspace.getConfiguration('coc.preferences') - const enabled = config.get('semanticTokensHighlights', true) - if (enabled) this.registerFeature(new SemanticTokensFeature(this)) - } - this.registerFeature(new LinkedEditingFeature(this)) - this.registerFeature(new DidCreateFilesFeature(this)) - this.registerFeature(new DidRenameFilesFeature(this)) - this.registerFeature(new DidDeleteFilesFeature(this)) - this.registerFeature(new WillCreateFilesFeature(this)) - this.registerFeature(new WillRenameFilesFeature(this)) - this.registerFeature(new WillDeleteFilesFeature(this)) - if (!this.clientOptions.disableWorkspaceFolders) { - this.registerFeature(new WorkspaceFoldersFeature(this)) - } - } - - private _getServerWorkingDir(options?: { cwd?: string }): Promise { - let cwd = options && options.cwd - if (cwd && !path.isAbsolute(cwd)) cwd = path.join(workspace.cwd, cwd) - if (!cwd) cwd = workspace.cwd - if (cwd) { - // make sure the folder exists otherwise creating the process will fail - return new Promise(s => { - fs.lstat(cwd, (err, stats) => { - s(!err && stats.isDirectory() ? cwd : undefined) - }) - }) - } - return Promise.resolve(undefined) - } - - private appendOutput(data: any, encoding: string): void { - let msg: string = Is.string(data) ? data : data.toString(encoding) - this.outputChannel.append(msg.endsWith('\n') ? msg : msg + '\n') - } -} - -export class SettingMonitor { - private _listeners: Disposable[] - - constructor(private _client: LanguageClient, private _setting: string) { - this._listeners = [] - } - - public start(): Disposable { - workspace.onDidChangeConfiguration(e => { - if (e.affectsConfiguration(this._setting)) { - this.onDidChangeConfiguration() - } - }, null, this._listeners) - this.onDidChangeConfiguration() - return { - dispose: () => { - disposeAll(this._listeners) - if (this._client.needsStop()) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - this._client.stop() - } - } - } - } - - private onDidChangeConfiguration(): void { - let index = this._setting.indexOf('.') - let primary = index >= 0 ? this._setting.substr(0, index) : this._setting - let rest = index >= 0 ? this._setting.substr(index + 1) : undefined - let enabled = rest - ? workspace.getConfiguration(primary).get(rest, true) - : workspace.getConfiguration(primary) - if (enabled && this._client.needsStart()) { - this._client.start() - } else if (!enabled && this._client.needsStop()) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - this._client.stop() - } - } -} - -// Exporting proposed protocol. -export namespace ProposedFeatures { - export function createAll(_client: BaseLanguageClient): (StaticFeature | DynamicFeature)[] { - let result: (StaticFeature | DynamicFeature)[] = [] - return result - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/linkedEditingRange.ts b/vim-config/plugins/coc.nvim/src/language-client/linkedEditingRange.ts deleted file mode 100644 index 4a4346b5..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/linkedEditingRange.ts +++ /dev/null @@ -1,71 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. -* ------------------------------------------------------------------------------------------ */ - -import { CancellationToken, ClientCapabilities, Disposable, DocumentSelector, LinkedEditingRangeOptions, LinkedEditingRangeRegistrationOptions, LinkedEditingRangeRequest, LinkedEditingRanges, Position, ServerCapabilities } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import languages from '../languages' -import { LinkedEditingRangeProvider, ProviderResult } from '../provider' -import { BaseLanguageClient, TextDocumentFeature } from './client' -import * as cv from './utils/converter' -const logger = require('../util/logger')('languageclient-linkedEditingRange') - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = {} as any - } - return target[key] -} - -export interface ProvideLinkedEditingRangeSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult -} - -/** - * Linked editing middleware - * - * @since 3.16.0 - */ -export interface LinkedEditingRangeMiddleware { - provideLinkedEditingRange?: (this: void, document: TextDocument, position: Position, token: CancellationToken, next: ProvideLinkedEditingRangeSignature) => ProviderResult -} - -export class LinkedEditingFeature extends TextDocumentFeature { - - constructor(client: BaseLanguageClient) { - super(client, LinkedEditingRangeRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - const linkedEditingSupport = ensure(ensure(capabilities, 'textDocument')!, 'linkedEditingRange')! - linkedEditingSupport.dynamicRegistration = true - } - - public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { - let [id, options] = this.getRegistration(documentSelector, capabilities.linkedEditingRangeProvider) - if (!id || !options) { - return - } - this.register({ id, registerOptions: options }) - } - - protected registerLanguageProvider(options: LinkedEditingRangeRegistrationOptions): [Disposable, LinkedEditingRangeProvider] { - const provider: LinkedEditingRangeProvider = { - provideLinkedEditingRanges: (document, position, token) => { - const client = this._client - const provideLinkedEditing: ProvideLinkedEditingRangeSignature = (document, position, token) => { - const params = cv.asTextDocumentPositionParams(document, position) - return client.sendRequest(LinkedEditingRangeRequest.type, params, token).then(result => result, error => { - return client.handleFailedRequest(LinkedEditingRangeRequest.type, token, error, null) - }) - } - const middleware = client.clientOptions.middleware! - return middleware.provideLinkedEditingRange - ? middleware.provideLinkedEditingRange(document, position, token, provideLinkedEditing) - : provideLinkedEditing(document, position, token) - } - } - return [languages.registerLinkedEditingRangeProvider(options.documentSelector!, provider), provider] - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/progress.ts b/vim-config/plugins/coc.nvim/src/language-client/progress.ts deleted file mode 100644 index db74e53b..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/progress.ts +++ /dev/null @@ -1,45 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -'use strict' - -import { ClientCapabilities, WorkDoneProgressCreateParams, WorkDoneProgressCreateRequest } from 'vscode-languageserver-protocol' -import { BaseLanguageClient, StaticFeature } from './client' -import { ProgressPart } from './progressPart' -// const logger = require('../util/logger')('language-client-progress') - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = Object.create(null) - } - return target[key] -} - -export class ProgressFeature implements StaticFeature { - private activeParts: Set = new Set() - constructor(private _client: BaseLanguageClient) { - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - ensure(capabilities, 'window')!.workDoneProgress = true - } - - public initialize(): void { - let client = this._client - const deleteHandler = (part: ProgressPart) => { - this.activeParts.delete(part) - } - const createHandler = (params: WorkDoneProgressCreateParams) => { - this.activeParts.add(new ProgressPart(this._client, params.token, deleteHandler)) - } - client.onRequest(WorkDoneProgressCreateRequest.type, createHandler) - } - - public dispose(): void { - for (const part of this.activeParts) { - part.done() - } - this.activeParts.clear() - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/progressPart.ts b/vim-config/plugins/coc.nvim/src/language-client/progressPart.ts deleted file mode 100644 index 6d6be04c..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/progressPart.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -'use strict' - -import { Disposable, NotificationHandler, ProgressToken, ProgressType, ProtocolNotificationType, WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressReport } from 'vscode-languageserver-protocol' -import { StatusBarItem } from '../model/status' -import { disposeAll } from '../util' -import window from '../window' -const logger = require('../util/logger')('language-client-progressPart') - -export interface ProgressContext { - onProgress

    (type: ProgressType

    , token: string | number, handler: NotificationHandler

    ): Disposable - sendNotification(type: ProtocolNotificationType, params?: P): void -} - -export class ProgressPart { - private disposables: Disposable[] = [] - private statusBarItem: StatusBarItem | undefined - private _cancelled = false - private title: string - - public constructor(private client: ProgressContext, private token: ProgressToken, done?: (part: ProgressPart) => void) { - this.statusBarItem = window.createStatusBarItem(99, { progress: true }) - this.disposables.push(client.onProgress(WorkDoneProgress.type, this.token, value => { - switch (value.kind) { - case 'begin': - this.begin(value) - break - case 'report': - this.report(value) - break - case 'end': - this.done(value.message) - done && done(this) - break - } - })) - } - - public begin(params: WorkDoneProgressBegin): void { - if (typeof this.title === 'string') return - // TODO support params.cancellable - this.title = params.title - this.report(params) - } - - private report(params: WorkDoneProgressReport | WorkDoneProgressBegin): void { - let statusBarItem = this.statusBarItem - let parts: string[] = [] - if (this.title) parts.push(this.title) - if (typeof params.percentage == 'number') parts.push(params.percentage.toFixed(0) + '%') - if (params.message) parts.push(params.message) - statusBarItem.text = parts.join(' ') - statusBarItem.show() - } - - public cancel(): void { - if (this._cancelled) return - this._cancelled = true - disposeAll(this.disposables) - } - - public done(message?: string): void { - if (this._cancelled) return - const statusBarItem = this.statusBarItem - statusBarItem.text = `${this.title} ${message || 'finished'}` - setTimeout(() => { - statusBarItem.dispose() - }, 300) - this.cancel() - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/selectionRange.ts b/vim-config/plugins/coc.nvim/src/language-client/selectionRange.ts deleted file mode 100644 index 65e9143d..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/selectionRange.ts +++ /dev/null @@ -1,70 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -'use strict' - -import { CancellationToken, ClientCapabilities, Disposable, DocumentSelector, Position, SelectionRange, SelectionRangeClientCapabilities, SelectionRangeOptions, SelectionRangeParams, SelectionRangeRegistrationOptions, SelectionRangeRequest, ServerCapabilities } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import languages from '../languages' -import { ProviderResult, SelectionRangeProvider } from '../provider' -import { BaseLanguageClient, TextDocumentFeature } from './client' - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = {} as any - } - return target[key] -} - -export interface ProvideSelectionRangeSignature { - (this: void, document: TextDocument, positions: Position[], token: CancellationToken): ProviderResult -} - -export interface SelectionRangeProviderMiddleware { - provideSelectionRanges?: (this: void, document: TextDocument, positions: Position[], token: CancellationToken, next: ProvideSelectionRangeSignature) => ProviderResult -} - -export class SelectionRangeFeature extends TextDocumentFeature { - constructor(client: BaseLanguageClient) { - super(client, SelectionRangeRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities & SelectionRangeClientCapabilities): void { - let capability = ensure(ensure(capabilities, 'textDocument')!, 'selectionRange')! - capability.dynamicRegistration = true - } - - public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { - let [id, options] = this.getRegistration(documentSelector, capabilities.selectionRangeProvider) - if (!id || !options) { - return - } - this.register({ id, registerOptions: options }) - } - - protected registerLanguageProvider(options: SelectionRangeRegistrationOptions): [Disposable, SelectionRangeProvider] { - const provider: SelectionRangeProvider = { - provideSelectionRanges: (document, positions, token) => { - const client = this._client - const provideSelectionRanges: ProvideSelectionRangeSignature = (document, positions, token) => { - const requestParams: SelectionRangeParams = { - textDocument: { uri: document.uri }, - positions - } - return client.sendRequest(SelectionRangeRequest.type, requestParams, token).then( - ranges => ranges, - (error: any) => { - return client.handleFailedRequest(SelectionRangeRequest.type, token, error, null) - } - ) - } - const middleware = client.clientOptions.middleware - return middleware.provideSelectionRanges - ? middleware.provideSelectionRanges(document, positions, token, provideSelectionRanges) - : provideSelectionRanges(document, positions, token) - } - } - return [languages.registerSelectionRangeProvider(options.documentSelector, provider), provider] - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/semanticTokens.ts b/vim-config/plugins/coc.nvim/src/language-client/semanticTokens.ts deleted file mode 100644 index 23923f1f..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/semanticTokens.ts +++ /dev/null @@ -1,202 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -'use strict' - -import { - CancellationToken, SemanticTokensClientCapabilities, ClientCapabilities, Disposable, DocumentSelector, Emitter, Range, SemanticTokenModifiers, SemanticTokens, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensDeltaRequest, SemanticTokensOptions, SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeRequest, SemanticTokensRefreshRequest, SemanticTokensRegistrationOptions, SemanticTokensRegistrationType, SemanticTokensRequest, SemanticTokenTypes, ServerCapabilities, TokenFormat -} from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import languages from '../languages' -import { DocumentRangeSemanticTokensProvider, DocumentSemanticTokensProvider, ProviderResult } from '../provider' -import * as cv from './utils/converter' -import * as Is from '../util/is' -import { BaseLanguageClient, Middleware, TextDocumentFeature } from './client' -const logger = require('../util/logger')('languageclient-semanticTokens') - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = {} as any - } - return target[key] -} - -export interface DocumentSemanticsTokensSignature { - (this: void, document: TextDocument, token: CancellationToken): ProviderResult -} - -export interface DocumentSemanticsTokensEditsSignature { - (this: void, document: TextDocument, previousResultId: string, token: CancellationToken): ProviderResult -} - -export interface DocumentRangeSemanticTokensSignature { - (this: void, document: TextDocument, range: Range, token: CancellationToken): ProviderResult -} - -/** - * The semantic token middleware - * - * @since 3.16.0 - */ -export interface SemanticTokensMiddleware { - provideDocumentSemanticTokens?: (this: void, document: TextDocument, token: CancellationToken, next: DocumentSemanticsTokensSignature) => ProviderResult - provideDocumentSemanticTokensEdits?: (this: void, document: TextDocument, previousResultId: string, token: CancellationToken, next: DocumentSemanticsTokensEditsSignature) => ProviderResult - provideDocumentRangeSemanticTokens?: (this: void, document: TextDocument, range: Range, token: CancellationToken, next: DocumentRangeSemanticTokensSignature) => ProviderResult -} - -export interface SemanticTokensProviders { - range?: DocumentRangeSemanticTokensProvider - full?: DocumentSemanticTokensProvider - onDidChangeSemanticTokensEmitter: Emitter -} - -export class SemanticTokensFeature extends TextDocumentFeature { - - constructor(client: BaseLanguageClient) { - super(client, SemanticTokensRegistrationType.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - const capability = ensure(ensure(capabilities, 'textDocument')!, 'semanticTokens')! - capability.dynamicRegistration = true - capability.tokenTypes = [ - SemanticTokenTypes.namespace, - SemanticTokenTypes.type, - SemanticTokenTypes.class, - SemanticTokenTypes.enum, - SemanticTokenTypes.interface, - SemanticTokenTypes.struct, - SemanticTokenTypes.typeParameter, - SemanticTokenTypes.parameter, - SemanticTokenTypes.variable, - SemanticTokenTypes.property, - SemanticTokenTypes.enumMember, - SemanticTokenTypes.event, - SemanticTokenTypes.function, - SemanticTokenTypes.method, - SemanticTokenTypes.macro, - SemanticTokenTypes.keyword, - SemanticTokenTypes.modifier, - SemanticTokenTypes.comment, - SemanticTokenTypes.string, - SemanticTokenTypes.number, - SemanticTokenTypes.regexp, - SemanticTokenTypes.operator - ] - capability.tokenModifiers = [ - SemanticTokenModifiers.declaration, - SemanticTokenModifiers.definition, - SemanticTokenModifiers.readonly, - SemanticTokenModifiers.static, - SemanticTokenModifiers.deprecated, - SemanticTokenModifiers.abstract, - SemanticTokenModifiers.async, - SemanticTokenModifiers.modification, - SemanticTokenModifiers.documentation, - SemanticTokenModifiers.defaultLibrary - ] - capability.formats = [TokenFormat.Relative] - capability.requests = { - range: true, - full: { - delta: true - } - } - capability.multilineTokenSupport = false - capability.overlappingTokenSupport = false - ensure(ensure(capabilities, 'workspace')!, 'semanticTokens')!.refreshSupport = true - } - - public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { - const client = this._client - client.onRequest(SemanticTokensRefreshRequest.type, async () => { - for (const provider of this.getAllProviders()) { - provider.onDidChangeSemanticTokensEmitter.fire() - } - }) - const [id, options] = this.getRegistration(documentSelector, capabilities.semanticTokensProvider) - if (!id || !options) { - return - } - this.register({ id, registerOptions: options }) - } - - protected registerLanguageProvider(options: SemanticTokensRegistrationOptions): [Disposable, SemanticTokensProviders] { - const fullProvider = Is.boolean(options.full) ? options.full : options.full !== undefined - const hasEditProvider = options.full !== undefined && typeof options.full !== 'boolean' && options.full.delta === true - const eventEmitter: Emitter = new Emitter() - const documentProvider: DocumentSemanticTokensProvider | undefined = fullProvider - ? { - onDidChangeSemanticTokens: eventEmitter.event, - provideDocumentSemanticTokens: (document, token) => { - const client = this._client - const middleware = client.clientOptions.middleware! as Middleware & SemanticTokensMiddleware - const provideDocumentSemanticTokens: DocumentSemanticsTokensSignature = (document, token) => { - const params: SemanticTokensParams = { - textDocument: cv.asTextDocumentIdentifier(document) - } - return client.sendRequest(SemanticTokensRequest.type, params, token).then(result => result, (error: any) => { - return client.handleFailedRequest(SemanticTokensRequest.type, token, error, null) - }) - } - return middleware.provideDocumentSemanticTokens - ? middleware.provideDocumentSemanticTokens(document, token, provideDocumentSemanticTokens) - : provideDocumentSemanticTokens(document, token) - }, - provideDocumentSemanticTokensEdits: hasEditProvider - ? (document, previousResultId, token) => { - const client = this._client - const middleware = client.clientOptions.middleware! as Middleware & SemanticTokensMiddleware - const provideDocumentSemanticTokensEdits: DocumentSemanticsTokensEditsSignature = (document, previousResultId, token) => { - const params: SemanticTokensDeltaParams = { - textDocument: cv.asTextDocumentIdentifier(document), - previousResultId - } - return client.sendRequest(SemanticTokensDeltaRequest.type, params, token).then(result => result, (error: any) => { - return client.handleFailedRequest(SemanticTokensDeltaRequest.type, token, error, null) - }) - } - return middleware.provideDocumentSemanticTokensEdits - ? middleware.provideDocumentSemanticTokensEdits(document, previousResultId, token, provideDocumentSemanticTokensEdits) - : provideDocumentSemanticTokensEdits(document, previousResultId, token) - } - : undefined - } - : undefined - - const hasRangeProvider: boolean = options.range === true - const rangeProvider: DocumentRangeSemanticTokensProvider | undefined = hasRangeProvider - ? { - provideDocumentRangeSemanticTokens: (document: TextDocument, range: Range, token: CancellationToken) => { - const client = this._client - const middleware = client.clientOptions.middleware! as Middleware & SemanticTokensMiddleware - const provideDocumentRangeSemanticTokens: DocumentRangeSemanticTokensSignature = (document, range, token) => { - const params: SemanticTokensRangeParams = { - textDocument: cv.asTextDocumentIdentifier(document), - range - } - return client.sendRequest(SemanticTokensRangeRequest.type, params, token).then( - result => result, - (error: any) => { - return client.handleFailedRequest(SemanticTokensRangeRequest.type, token, error, null) - }) - } - return middleware.provideDocumentRangeSemanticTokens - ? middleware.provideDocumentRangeSemanticTokens(document, range, token, provideDocumentRangeSemanticTokens) - : provideDocumentRangeSemanticTokens(document, range, token) - } - } - : undefined - - const disposables: Disposable[] = [] - if (documentProvider !== undefined) { - disposables.push(languages.registerDocumentSemanticTokensProvider(options.documentSelector!, documentProvider, options.legend)) - } - if (rangeProvider !== undefined) { - disposables.push(languages.registerDocumentRangeSemanticTokensProvider(options.documentSelector!, rangeProvider, options.legend)) - } - - return [Disposable.create(() => disposables.forEach(item => item.dispose())), { range: rangeProvider, full: documentProvider, onDidChangeSemanticTokensEmitter: eventEmitter }] - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/typeDefinition.ts b/vim-config/plugins/coc.nvim/src/language-client/typeDefinition.ts deleted file mode 100644 index 75f3acf7..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/typeDefinition.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -import { CancellationToken, ClientCapabilities, Definition, DefinitionLink, Disposable, DocumentSelector, Position, ServerCapabilities, TypeDefinitionOptions, TypeDefinitionRegistrationOptions, TypeDefinitionRequest } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import languages from '../languages' -import { ProviderResult, TypeDefinitionProvider } from '../provider' -import { BaseLanguageClient, TextDocumentFeature } from './client' -import * as cv from './utils/converter' - -function ensure(target: T, key: K): T[K] { - if (target[key] === void 0) { - target[key] = {} as any - } - return target[key] -} - -export interface ProvideTypeDefinitionSignature { - ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult -} - -export interface TypeDefinitionMiddleware { - provideTypeDefinition?: ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken, - next: ProvideTypeDefinitionSignature - ) => ProviderResult -} - -export class TypeDefinitionFeature extends TextDocumentFeature { - constructor(client: BaseLanguageClient) { - super(client, TypeDefinitionRequest.type) - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - const typeDefinitionSupport = ensure(ensure(capabilities, 'textDocument')!, 'typeDefinition')! - typeDefinitionSupport.dynamicRegistration = true - // typeDefinitionSupport.linkSupport = true - } - - public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { - const [id, options] = this.getRegistration(documentSelector, capabilities.typeDefinitionProvider) - if (!id || !options) { - return - } - this.register({ id, registerOptions: options }) - } - - protected registerLanguageProvider(options: TypeDefinitionRegistrationOptions): [Disposable, TypeDefinitionProvider] { - const provider: TypeDefinitionProvider = { - provideTypeDefinition: (document, position, token) => { - const client = this._client - const provideTypeDefinition: ProvideTypeDefinitionSignature = (document, position, token) => client.sendRequest(TypeDefinitionRequest.type, cv.asTextDocumentPositionParams(document, position), token).then( - res => res, error => { - return client.handleFailedRequest(TypeDefinitionRequest.type, token, error, null) - } - ) - const middleware = client.clientOptions.middleware - return middleware.provideTypeDefinition - ? middleware.provideTypeDefinition(document, position, token, provideTypeDefinition) - : provideTypeDefinition(document, position, token) - } - } - return [languages.registerTypeDefinitionProvider(options.documentSelector, provider), provider] - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/utils/async.ts b/vim-config/plugins/coc.nvim/src/language-client/utils/async.ts deleted file mode 100644 index 1e772bcb..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/utils/async.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { RAL } from 'vscode-languageserver-protocol' - -export interface ITask { - (): T -} - -export class Delayer { - - public defaultDelay: number - private timeout: RAL.TimeoutHandle | undefined - private completionPromise: Promise | undefined - private onSuccess: ((value: T | Promise | undefined) => void) | undefined - private task: ITask | undefined - - constructor(defaultDelay: number) { - this.defaultDelay = defaultDelay - this.timeout = undefined - this.completionPromise = undefined - this.onSuccess = undefined - this.task = undefined - } - - public trigger(task: ITask, delay: number = this.defaultDelay): Promise { - this.task = task - if (delay >= 0) { - this.cancelTimeout() - } - - if (!this.completionPromise) { - this.completionPromise = new Promise(resolve => { - this.onSuccess = resolve - }).then(() => { - this.completionPromise = undefined - this.onSuccess = undefined - let result = this.task!() - this.task = undefined - return result - }) - } - - if (delay >= 0 || this.timeout === void 0) { - this.timeout = RAL().timer.setTimeout(() => { - this.timeout = undefined - this.onSuccess!(undefined) - }, delay >= 0 ? delay : this.defaultDelay) - } - - return this.completionPromise - } - - public forceDelivery(): T | undefined { - if (!this.completionPromise) { - return undefined - } - this.cancelTimeout() - let result: T = this.task!() - this.completionPromise = undefined - this.onSuccess = undefined - this.task = undefined - return result - } - - public isTriggered(): boolean { - return this.timeout !== void 0 - } - - public cancel(): void { - this.cancelTimeout() - this.completionPromise = undefined - } - - public dispose(): void { - this.cancelTimeout() - } - - private cancelTimeout(): void { - if (this.timeout !== void 0) { - RAL().timer.clearTimeout(this.timeout) - this.timeout = undefined - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/utils/converter.ts b/vim-config/plugins/coc.nvim/src/language-client/utils/converter.ts deleted file mode 100644 index b05248a5..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/utils/converter.ts +++ /dev/null @@ -1,135 +0,0 @@ -/* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -import { CodeLensParams, CompletionContext, CompletionParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidSaveTextDocumentParams, DocumentSelector, DocumentSymbolParams, Position, ReferenceParams, SignatureHelpContext, SignatureHelpParams, TextDocumentIdentifier, TextDocumentItem, TextDocumentPositionParams, VersionedTextDocumentIdentifier, WillSaveTextDocumentParams } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { URI } from 'vscode-uri' -import { TextDocumentWillSaveEvent } from '../../types' -import { omit } from '../../util/lodash' - -export function asLanguageIds(documentSelector: DocumentSelector): string[] { - let res = documentSelector.map(filter => { - if (typeof filter == 'string') { - return filter - } - return filter.language - }) - res = res.filter(s => s != null) - return res.length == 0 ? null : res -} - -export function convertToTextDocumentItem(document: TextDocument): TextDocumentItem { - return { - uri: document.uri, - languageId: document.languageId, - version: document.version, - text: document.getText() - } -} - -export function asCloseTextDocumentParams(document: TextDocument): DidCloseTextDocumentParams { - return { - textDocument: { - uri: document.uri - } - } -} - -export function asChangeTextDocumentParams(document: TextDocument): DidChangeTextDocumentParams { - let result: DidChangeTextDocumentParams = { - textDocument: { - uri: document.uri, - version: document.version - }, - contentChanges: [{ text: document.getText() }] - } - return result -} - -export function asWillSaveTextDocumentParams(event: TextDocumentWillSaveEvent): WillSaveTextDocumentParams { - return { - textDocument: asVersionedTextDocumentIdentifier(event.document), - reason: event.reason - } -} - -export function asVersionedTextDocumentIdentifier(textDocument: TextDocument): VersionedTextDocumentIdentifier { - return { - uri: textDocument.uri, - version: textDocument.version - } -} - -export function asSaveTextDocumentParams(document: TextDocument, includeText: boolean): DidSaveTextDocumentParams { - let result: DidSaveTextDocumentParams = { - textDocument: asVersionedTextDocumentIdentifier(document) - } - if (includeText) { - result.text = document.getText() - } - return result -} - -export function asUri(resource: URI): string { - return resource.toString() -} - -export function asCompletionParams(textDocument: TextDocument, position: Position, context: CompletionContext): CompletionParams { - return { - textDocument: { - uri: textDocument.uri, - }, - position, - context: omit(context, ['option']), - } -} - -export function asTextDocumentPositionParams(textDocument: TextDocument, position: Position): TextDocumentPositionParams { - return { - textDocument: { - uri: textDocument.uri, - }, - position - } -} - -export function asSignatureHelpParams(textDocument: TextDocument, position: Position, context: SignatureHelpContext): SignatureHelpParams { - return { - textDocument: asTextDocumentIdentifier(textDocument), - position, - context - } -} - -export function asTextDocumentIdentifier(textDocument: TextDocument): TextDocumentIdentifier { - return { - uri: textDocument.uri - } -} - -export function asReferenceParams(textDocument: TextDocument, position: Position, options: { includeDeclaration: boolean }): ReferenceParams { - return { - textDocument: { - uri: textDocument.uri, - }, - position, - context: { includeDeclaration: options.includeDeclaration } - } -} - -export function asDocumentSymbolParams(textDocument: TextDocument): DocumentSymbolParams { - return { - textDocument: { - uri: textDocument.uri - } - } -} - -export function asCodeLensParams(textDocument: TextDocument): CodeLensParams { - return { - textDocument: { - uri: textDocument.uri - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/utils/uuid.ts b/vim-config/plugins/coc.nvim/src/language-client/utils/uuid.ts deleted file mode 100644 index 0adb8eee..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/utils/uuid.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { v4 as uuidv4 } from 'uuid' - -export function generateUuid(): string { - return uuidv4() -} diff --git a/vim-config/plugins/coc.nvim/src/language-client/workspaceFolders.ts b/vim-config/plugins/coc.nvim/src/language-client/workspaceFolders.ts deleted file mode 100644 index 30cd6409..00000000 --- a/vim-config/plugins/coc.nvim/src/language-client/workspaceFolders.ts +++ /dev/null @@ -1,170 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -'use strict' - -import { CancellationToken, ClientCapabilities, DidChangeWorkspaceFoldersNotification, DidChangeWorkspaceFoldersParams, Disposable, InitializeParams, RegistrationType, ServerCapabilities, WorkspaceFolder, WorkspaceFoldersChangeEvent, WorkspaceFoldersRequest } from 'vscode-languageserver-protocol' -import workspace from '../workspace' -import os from 'os' -import { BaseLanguageClient, DynamicFeature, NextSignature, RegistrationData } from './client' -import * as UUID from './utils/uuid' -import { URI } from 'vscode-uri' -const logger = require('../util/logger')('language-client-workspaceFolder') - -function access(target: T | undefined, key: K): T[K] | undefined { - if (target === void 0) { - return undefined - } - return target[key] -} - -function arrayDiff(left: ReadonlyArray, right: ReadonlyArray): T[] { - return left.filter(element => !right.includes(element)) -} - -export interface WorkspaceFolderWorkspaceMiddleware { - workspaceFolders?: WorkspaceFoldersRequest.MiddlewareSignature - didChangeWorkspaceFolders?: NextSignature -} - -export class WorkspaceFoldersFeature implements DynamicFeature { - - private _listeners: Map = new Map() - private _initialFolders: ReadonlyArray | undefined - - constructor(private _client: BaseLanguageClient) { - } - - public get registrationType(): RegistrationType { - return DidChangeWorkspaceFoldersNotification.type - } - - private getValidWorkspaceFolders(): WorkspaceFolder[] | undefined { - let { workspaceFolders } = workspace - if (!workspaceFolders || workspaceFolders.length == 0) return undefined - let home = os.homedir() - let { ignoredRootPaths } = this._client.clientOptions - if (!Array.isArray(ignoredRootPaths)) { - ignoredRootPaths = [] - } - let arr = workspaceFolders.filter(o => { - let fsPath = URI.parse(o.uri).fsPath - return fsPath != home && !ignoredRootPaths.includes(fsPath) - }) - return arr.length ? arr : undefined - } - - private asProtocol(workspaceFolder: WorkspaceFolder): WorkspaceFolder - private asProtocol(workspaceFolder: undefined): null - private asProtocol(workspaceFolder: WorkspaceFolder | undefined): WorkspaceFolder | null { - if (workspaceFolder === void 0) { - return null - } - return { uri: workspaceFolder.uri, name: workspaceFolder.name } - } - - public fillInitializeParams(params: InitializeParams): void { - const folders = this.getValidWorkspaceFolders() - this._initialFolders = folders - if (folders == null) { - params.workspaceFolders = null - } else { - params.workspaceFolders = folders.map(folder => this.asProtocol(folder)) - } - // params.workspaceFolders = workspace.workspaceFolders - } - - public fillClientCapabilities(capabilities: ClientCapabilities): void { - capabilities.workspace = capabilities.workspace || {} - capabilities.workspace.workspaceFolders = true - } - - public initialize(capabilities: ServerCapabilities): void { - let client = this._client - client.onRequest(WorkspaceFoldersRequest.type, (token: CancellationToken) => { - let workspaceFolders: WorkspaceFoldersRequest.HandlerSignature = () => { - let folders = this.getValidWorkspaceFolders() - if (folders === void 0) { - return null - } - let result: WorkspaceFolder[] = folders.map(folder => this.asProtocol(folder)) - return result - } - const middleware = client.clientOptions.middleware.workspace - return middleware && middleware.workspaceFolders - ? middleware.workspaceFolders(token, workspaceFolders) - : workspaceFolders(token) - }) - const value = access(access(access(capabilities, 'workspace'), 'workspaceFolders'), 'changeNotifications') - let id: string | undefined - if (typeof value === 'string') { - id = value - } else if (value === true) { - id = UUID.generateUuid() - } - if (id) { - this.register({ - id, - registerOptions: undefined - }) - } - } - - private doSendEvent(addedFolders: ReadonlyArray, removedFolders: ReadonlyArray): void { - let params: DidChangeWorkspaceFoldersParams = { - event: { - added: addedFolders.map(folder => this.asProtocol(folder)), - removed: removedFolders.map(folder => this.asProtocol(folder)) - } - } - this._client.sendNotification(DidChangeWorkspaceFoldersNotification.type, params) - } - - protected sendInitialEvent(currentWorkspaceFolders: ReadonlyArray | undefined): void { - if (this._initialFolders && currentWorkspaceFolders) { - const removed: WorkspaceFolder[] = arrayDiff(this._initialFolders, currentWorkspaceFolders) - const added: WorkspaceFolder[] = arrayDiff(currentWorkspaceFolders, this._initialFolders) - if (added.length > 0 || removed.length > 0) { - this.doSendEvent(added, removed) - } - } else if (this._initialFolders) { - this.doSendEvent([], this._initialFolders) - } else if (currentWorkspaceFolders) { - this.doSendEvent(currentWorkspaceFolders, []) - } - } - - public register(data: RegistrationData): void { - let id = data.id - let client = this._client - let disposable = workspace.onDidChangeWorkspaceFolders(event => { - let didChangeWorkspaceFolders = (event: WorkspaceFoldersChangeEvent) => { - this.doSendEvent(event.added, event.removed) - } - let middleware = client.clientOptions.middleware.workspace - middleware && middleware.didChangeWorkspaceFolders - ? middleware.didChangeWorkspaceFolders(event, didChangeWorkspaceFolders) - : didChangeWorkspaceFolders(event) - }) - this._listeners.set(id, disposable) - let workspaceFolders = this.getValidWorkspaceFolders() - this.sendInitialEvent(workspaceFolders) - } - - public unregister(id: string): void { - let disposable = this._listeners.get(id) - if (disposable === void 0) { - return - } - this._listeners.delete(id) - disposable.dispose() - } - - public dispose(): void { - for (let disposable of this._listeners.values()) { - disposable.dispose() - } - this._listeners.clear() - } -} diff --git a/vim-config/plugins/coc.nvim/src/languages.ts b/vim-config/plugins/coc.nvim/src/languages.ts deleted file mode 100644 index 2c23c637..00000000 --- a/vim-config/plugins/coc.nvim/src/languages.ts +++ /dev/null @@ -1,450 +0,0 @@ -import { CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, CancellationToken, CancellationTokenSource, CodeAction, CodeActionContext, CodeActionKind, CodeLens, ColorInformation, ColorPresentation, DefinitionLink, Disposable, DocumentHighlight, DocumentLink, DocumentSelector, DocumentSymbol, Emitter, Event, FoldingRange, FormattingOptions, Hover, LinkedEditingRanges, Location, LocationLink, Position, Range, SelectionRange, SemanticTokens, SemanticTokensDelta, SemanticTokensLegend, SignatureHelp, SignatureHelpContext, SymbolInformation, TextEdit, WorkspaceEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import DiagnosticCollection from './diagnostic/collection' -import diagnosticManager from './diagnostic/manager' -import { CallHierarchyProvider, CodeActionProvider, CodeLensProvider, CompletionItemProvider, DeclarationProvider, DefinitionProvider, DocumentColorProvider, DocumentFormattingEditProvider, DocumentHighlightProvider, DocumentLinkProvider, DocumentRangeFormattingEditProvider, DocumentRangeSemanticTokensProvider, DocumentSemanticTokensProvider, DocumentSymbolProvider, FoldingContext, FoldingRangeProvider, HoverProvider, ImplementationProvider, LinkedEditingRangeProvider, OnTypeFormattingEditProvider, ReferenceContext, ReferenceProvider, RenameProvider, SelectionRangeProvider, SignatureHelpProvider, TypeDefinitionProvider, WorkspaceSymbolProvider } from './provider' -import CallHierarchyManager from './provider/callHierarchyManager' -import CodeActionManager from './provider/codeActionManager' -import CodeLensManager from './provider/codeLensManager' -import DeclarationManager from './provider/declarationManager' -import DefinitionManager from './provider/definitionManager' -import DocumentColorManager from './provider/documentColorManager' -import DocumentHighlightManager from './provider/documentHighlightManager' -import DocumentLinkManager from './provider/documentLinkManager' -import DocumentSymbolManager from './provider/documentSymbolManager' -import FoldingRangeManager from './provider/foldingRangeManager' -import FormatManager from './provider/formatManager' -import FormatRangeManager from './provider/formatRangeManager' -import HoverManager from './provider/hoverManager' -import ImplementationManager from './provider/implementationManager' -import LinkedEditingRangeManager from './provider/linkedEditingRangeManager' -import OnTypeFormatManager from './provider/onTypeFormatManager' -import ReferenceManager from './provider/referenceManager' -import RenameManager from './provider/renameManager' -import SelectionRangeManager from './provider/selectionRangeManager' -import SemanticTokensManager from './provider/semanticTokensManager' -import SemanticTokensRangeManager from './provider/semanticTokensRangeManager' -import SignatureManager from './provider/signatureManager' -import TypeDefinitionManager from './provider/typeDefinitionManager' -import WorkspaceSymbolManager from './provider/workspaceSymbolsManager' -const logger = require('./util/logger')('languages') - -export interface DocumentSymbolProviderMetadata { - /** - * A human-readable string that is shown when multiple outlines trees show for one document. - */ - label?: string -} - -class Languages { - private _onDidSemanticTokensRefresh = new Emitter() - public readonly onDidSemanticTokensRefresh: Event = this._onDidSemanticTokensRefresh.event - private onTypeFormatManager = new OnTypeFormatManager() - private documentLinkManager = new DocumentLinkManager() - private documentColorManager = new DocumentColorManager() - private foldingRangeManager = new FoldingRangeManager() - private renameManager = new RenameManager() - private formatManager = new FormatManager() - private codeActionManager = new CodeActionManager() - private workspaceSymbolsManager = new WorkspaceSymbolManager() - private formatRangeManager = new FormatRangeManager() - private hoverManager = new HoverManager() - private signatureManager = new SignatureManager() - private documentSymbolManager = new DocumentSymbolManager() - private documentHighlightManager = new DocumentHighlightManager() - private definitionManager = new DefinitionManager() - private declarationManager = new DeclarationManager() - private typeDefinitionManager = new TypeDefinitionManager() - private referenceManager = new ReferenceManager() - private implementationManager = new ImplementationManager() - private codeLensManager = new CodeLensManager() - private selectionRangeManager = new SelectionRangeManager() - private callHierarchyManager = new CallHierarchyManager() - private semanticTokensManager = new SemanticTokensManager() - private semanticTokensRangeManager = new SemanticTokensRangeManager() - private linkedEditingManager = new LinkedEditingRangeManager() - private cancelTokenSource: CancellationTokenSource = new CancellationTokenSource() - - public hasFormatProvider(doc: TextDocument): boolean { - if (this.formatManager.hasProvider(doc)) { - return true - } - if (this.formatRangeManager.hasProvider(doc)) { - return true - } - return false - } - - public registerOnTypeFormattingEditProvider( - selector: DocumentSelector, - provider: OnTypeFormattingEditProvider, - triggerCharacters: string[] - ): Disposable { - return this.onTypeFormatManager.register(selector, provider, triggerCharacters) - } - - public registerCompletionItemProvider( - name: string, - shortcut: string, - selector: DocumentSelector | null, - provider: CompletionItemProvider, - triggerCharacters: string[] = [], - priority?: number, - allCommitCharacters?: string[] - ): Disposable { - selector = typeof selector == 'string' ? [{ language: selector }] : selector - let sources = require('./sources/index').default - return sources.createLanguageSource(name, shortcut, selector, provider, triggerCharacters, priority, allCommitCharacters) - } - - public registerCodeActionProvider(selector: DocumentSelector, provider: CodeActionProvider, clientId: string | undefined, codeActionKinds?: CodeActionKind[]): Disposable { - return this.codeActionManager.register(selector, provider, clientId, codeActionKinds) - } - - public registerHoverProvider(selector: DocumentSelector, provider: HoverProvider): Disposable { - return this.hoverManager.register(selector, provider) - } - - public registerSelectionRangeProvider(selector: DocumentSelector, provider: SelectionRangeProvider): Disposable { - return this.selectionRangeManager.register(selector, provider) - } - - public registerSignatureHelpProvider( - selector: DocumentSelector, - provider: SignatureHelpProvider, - triggerCharacters?: string[]): Disposable { - return this.signatureManager.register(selector, provider, triggerCharacters) - } - - public registerDocumentSymbolProvider(selector: DocumentSelector, provider: DocumentSymbolProvider, metadata?: DocumentSymbolProviderMetadata): Disposable { - return this.documentSymbolManager.register(selector, provider, metadata?.label) - } - - public registerFoldingRangeProvider(selector: DocumentSelector, provider: FoldingRangeProvider): Disposable { - return this.foldingRangeManager.register(selector, provider) - } - - public registerDocumentHighlightProvider(selector: DocumentSelector, provider: DocumentHighlightProvider): Disposable { - return this.documentHighlightManager.register(selector, provider) - } - - public registerCodeLensProvider(selector: DocumentSelector, provider: CodeLensProvider): Disposable { - return this.codeLensManager.register(selector, provider) - } - - public registerDocumentLinkProvider(selector: DocumentSelector, provider: DocumentLinkProvider): Disposable { - return this.documentLinkManager.register(selector, provider) - } - - public registerDocumentColorProvider(selector: DocumentSelector, provider: DocumentColorProvider): Disposable { - return this.documentColorManager.register(selector, provider) - } - - public registerDefinitionProvider(selector: DocumentSelector, provider: DefinitionProvider): Disposable { - return this.definitionManager.register(selector, provider) - } - - public registerDeclarationProvider(selector: DocumentSelector, provider: DeclarationProvider): Disposable { - return this.declarationManager.register(selector, provider) - } - - public registerTypeDefinitionProvider(selector: DocumentSelector, provider: TypeDefinitionProvider): Disposable { - return this.typeDefinitionManager.register(selector, provider) - } - - public registerImplementationProvider(selector: DocumentSelector, provider: ImplementationProvider): Disposable { - return this.implementationManager.register(selector, provider) - } - - public registerReferencesProvider(selector: DocumentSelector, provider: ReferenceProvider): Disposable { - return this.referenceManager.register(selector, provider) - } - - public registerRenameProvider(selector: DocumentSelector, provider: RenameProvider): Disposable { - return this.renameManager.register(selector, provider) - } - - public registerWorkspaceSymbolProvider(provider: WorkspaceSymbolProvider): Disposable { - if (arguments.length > 1 && typeof arguments[1].provideWorkspaceSymbols === 'function') { - provider = arguments[1] - } - return this.workspaceSymbolsManager.register(provider) - } - - public registerDocumentFormatProvider(selector: DocumentSelector, provider: DocumentFormattingEditProvider, priority = 0): Disposable { - return this.formatManager.register(selector, provider, priority) - } - - public registerDocumentRangeFormatProvider(selector: DocumentSelector, provider: DocumentRangeFormattingEditProvider, priority = 0): Disposable { - return this.formatRangeManager.register(selector, provider, priority) - } - - public registerCallHierarchyProvider(selector: DocumentSelector, provider: CallHierarchyProvider): Disposable { - return this.callHierarchyManager.register(selector, provider) - } - - public registerDocumentSemanticTokensProvider(selector: DocumentSelector, provider: DocumentSemanticTokensProvider, legend: SemanticTokensLegend): Disposable { - this._onDidSemanticTokensRefresh.fire(selector) - return this.semanticTokensManager.register(selector, provider, legend, () => { - this._onDidSemanticTokensRefresh.fire(selector) - }) - } - - public registerDocumentRangeSemanticTokensProvider(selector: DocumentSelector, provider: DocumentRangeSemanticTokensProvider, legend: SemanticTokensLegend): Disposable { - this._onDidSemanticTokensRefresh.fire(selector) - return this.semanticTokensRangeManager.register(selector, provider, legend) - } - - public registerLinkedEditingRangeProvider(selector: DocumentSelector, provider: LinkedEditingRangeProvider): Disposable { - return this.linkedEditingManager.register(selector, provider) - } - - public shouldTriggerSignatureHelp(document: TextDocument, triggerCharacter: string): boolean { - return this.signatureManager.shouldTrigger(document, triggerCharacter) - } - - public async getHover(document: TextDocument, position: Position, token: CancellationToken): Promise { - return await this.hoverManager.provideHover(document, position, token) - } - - public async getSignatureHelp(document: TextDocument, position: Position, token: CancellationToken, context: SignatureHelpContext): Promise { - return await this.signatureManager.provideSignatureHelp(document, position, token, context) - } - - public async getDefinition(document: TextDocument, position: Position, token: CancellationToken): Promise { - if (!this.definitionManager.hasProvider(document)) return null - return await this.definitionManager.provideDefinition(document, position, token) - } - - public async getDefinitionLinks(document: TextDocument, position: Position, token: CancellationToken): Promise { - if (!this.definitionManager.hasProvider(document)) return null - return await this.definitionManager.provideDefinitionLinks(document, position, token) - } - - public async getDeclaration(document: TextDocument, position: Position, token: CancellationToken): Promise { - if (!this.declarationManager.hasProvider(document)) return null - return await this.declarationManager.provideDeclaration(document, position, token) - } - - public async getTypeDefinition(document: TextDocument, position: Position, token: CancellationToken): Promise { - if (!this.typeDefinitionManager.hasProvider(document)) return null - return await this.typeDefinitionManager.provideTypeDefinition(document, position, token) - } - - public async getImplementation(document: TextDocument, position: Position, token: CancellationToken): Promise { - if (!this.implementationManager.hasProvider(document)) return null - return await this.implementationManager.provideReferences(document, position, token) - } - - public async getReferences(document: TextDocument, context: ReferenceContext, position: Position, token: CancellationToken): Promise { - if (!this.referenceManager.hasProvider(document)) return null - return await this.referenceManager.provideReferences(document, position, context, token) - } - - public async getDocumentSymbol(document: TextDocument, token: CancellationToken): Promise { - return await this.documentSymbolManager.provideDocumentSymbols(document, token) - } - - public async getSelectionRanges(document: TextDocument, positions: Position[], token): Promise { - return await this.selectionRangeManager.provideSelectionRanges(document, positions, token) - } - - public async getWorkspaceSymbols(query: string, token: CancellationToken): Promise { - query = query || '' - return await this.workspaceSymbolsManager.provideWorkspaceSymbols(query, token) - } - - public async resolveWorkspaceSymbol(symbol: SymbolInformation, token: CancellationToken): Promise { - return await this.workspaceSymbolsManager.resolveWorkspaceSymbol(symbol, token) - } - - public async prepareRename(document: TextDocument, position: Position, token: CancellationToken): Promise { - return await this.renameManager.prepareRename(document, position, token) - } - - public async provideRenameEdits(document: TextDocument, position: Position, newName: string, token: CancellationToken): Promise { - return await this.renameManager.provideRenameEdits(document, position, newName, token) - } - - public async provideDocumentFormattingEdits(document: TextDocument, options: FormattingOptions, token: CancellationToken): Promise { - if (!this.formatManager.hasProvider(document)) { - let hasRangeFormater = this.formatRangeManager.hasProvider(document) - if (!hasRangeFormater) return null - let end = document.positionAt(document.getText().length) - let range = Range.create(Position.create(0, 0), end) - return await this.provideDocumentRangeFormattingEdits(document, range, options, token) - } - return await this.formatManager.provideDocumentFormattingEdits(document, options, token) - } - - public async provideDocumentRangeFormattingEdits(document: TextDocument, range: Range, options: FormattingOptions, token: CancellationToken): Promise { - if (!this.formatRangeManager.hasProvider(document)) return null - return await this.formatRangeManager.provideDocumentRangeFormattingEdits(document, range, options, token) - } - - public async getCodeActions(document: TextDocument, range: Range, context: CodeActionContext, token: CancellationToken): Promise { - return await this.codeActionManager.provideCodeActions(document, range, context, token) - } - - public async getDocumentHighLight(document: TextDocument, position: Position, token: CancellationToken): Promise { - return await this.documentHighlightManager.provideDocumentHighlights(document, position, token) - } - - public async getDocumentLinks(document: TextDocument, token: CancellationToken): Promise { - if (!this.documentLinkManager.hasProvider(document)) { - return null - } - return (await this.documentLinkManager.provideDocumentLinks(document, token)) || [] - } - - public async resolveDocumentLink(link: DocumentLink): Promise { - return await this.documentLinkManager.resolveDocumentLink(link, this.token) - } - - public async provideDocumentColors(document: TextDocument, token: CancellationToken): Promise { - return await this.documentColorManager.provideDocumentColors(document, token) - } - - public async provideFoldingRanges(document: TextDocument, context: FoldingContext, token: CancellationToken): Promise { - if (!this.foldingRangeManager.hasProvider(document)) { - return null - } - return await this.foldingRangeManager.provideFoldingRanges(document, context, token) - } - - public async provideColorPresentations(color: ColorInformation, document: TextDocument, token: CancellationToken): Promise { - return await this.documentColorManager.provideColorPresentations(color, document, token) - } - - public async getCodeLens(document: TextDocument, token: CancellationToken): Promise<(CodeLens | null)[]> { - return await this.codeLensManager.provideCodeLenses(document, token) - } - - public async resolveCodeLens(codeLens: CodeLens, token: CancellationToken): Promise { - if (codeLens.command != null) return codeLens - return await this.codeLensManager.resolveCodeLens(codeLens, token) - } - - public async resolveCodeAction(codeAction: CodeAction, token: CancellationToken): Promise { - return await this.codeActionManager.resolveCodeAction(codeAction, token) - } - - public async provideDocumentOnTypeEdits( - character: string, - document: TextDocument, - position: Position, - token: CancellationToken - ): Promise { - return this.onTypeFormatManager.onCharacterType(character, document, position, token) - } - - public canFormatOnType(character: string, document: TextDocument): boolean { - return this.onTypeFormatManager.getProvider(document, character) != null - } - - public async prepareCallHierarchy(document: TextDocument, position: Position, token: CancellationToken): Promise { - return this.callHierarchyManager.prepareCallHierarchy(document, position, token) - } - - public async provideIncomingCalls(document: TextDocument, item: CallHierarchyItem, token: CancellationToken): Promise { - return this.callHierarchyManager.provideCallHierarchyIncomingCalls(document, item, token) - } - - public async provideOutgoingCalls(document: TextDocument, item: CallHierarchyItem, token: CancellationToken): Promise { - return this.callHierarchyManager.provideCallHierarchyOutgoingCalls(document, item, token) - } - - public getLegend(document: TextDocument, range?: boolean): SemanticTokensLegend | undefined { - if (range) return this.semanticTokensRangeManager.getLegend(document) - return this.semanticTokensManager.getLegend(document) - } - - public hasSemanticTokensEdits(document: TextDocument): boolean { - return this.semanticTokensManager.hasSemanticTokensEdits(document) - } - - public async provideDocumentSemanticTokens(document: TextDocument, token: CancellationToken): Promise { - return this.semanticTokensManager.provideDocumentSemanticTokens(document, token) - } - - public async provideDocumentSemanticTokensEdits(document: TextDocument, previousResultId: string, token: CancellationToken): Promise { - return this.semanticTokensManager.provideDocumentSemanticTokensEdits(document, previousResultId, token) - } - - public async provideDocumentRangeSemanticTokens(document: TextDocument, range: Range, token: CancellationToken): Promise { - return this.semanticTokensRangeManager.provideDocumentRangeSemanticTokens(document, range, token) - } - - public hasLinkedEditing(document: TextDocument): boolean { - return this.linkedEditingManager.hasProvider(document) - } - - public async provideLinkedEdits(document: TextDocument, position: Position, token: CancellationToken): Promise { - return this.linkedEditingManager.provideLinkedEditingRanges(document, position, token) - } - - public hasProvider(id: string, document: TextDocument): boolean { - switch (id) { - case 'formatOnType': - return this.onTypeFormatManager.hasProvider(document) - case 'rename': - return this.renameManager.hasProvider(document) - case 'onTypeEdit': - return this.onTypeFormatManager.hasProvider(document) - case 'documentLink': - return this.documentLinkManager.hasProvider(document) - case 'documentColor': - return this.documentColorManager.hasProvider(document) - case 'foldingRange': - return this.foldingRangeManager.hasProvider(document) - case 'format': - return this.formatManager.hasProvider(document) || this.formatRangeManager.hasProvider(document) - case 'codeAction': - return this.codeActionManager.hasProvider(document) - case 'workspaceSymbols': - return this.workspaceSymbolsManager.hasProvider() - case 'formatRange': - return this.formatRangeManager.hasProvider(document) - case 'hover': - return this.hoverManager.hasProvider(document) - case 'signature': - return this.signatureManager.hasProvider(document) - case 'documentSymbol': - return this.documentSymbolManager.hasProvider(document) - case 'documentHighlight': - return this.documentHighlightManager.hasProvider(document) - case 'definition': - return this.definitionManager.hasProvider(document) - case 'declaration': - return this.declarationManager.hasProvider(document) - case 'typeDefinition': - return this.typeDefinitionManager.hasProvider(document) - case 'reference': - return this.referenceManager.hasProvider(document) - case 'implementation': - return this.implementationManager.hasProvider(document) - case 'codeLens': - return this.codeLensManager.hasProvider(document) - case 'selectionRange': - return this.selectionRangeManager.hasProvider(document) - case 'callHierarchy': - return this.callHierarchyManager.hasProvider(document) - case 'semanticTokens': - return this.semanticTokensManager.hasProvider(document) - case 'linkedEditing': - return this.linkedEditingManager.hasProvider(document) - default: - throw new Error(`Invalid provider name: ${id}`) - } - } - public createDiagnosticCollection(owner: string): DiagnosticCollection { - return diagnosticManager.create(owner) - } - - private get token(): CancellationToken { - this.cancelTokenSource = new CancellationTokenSource() - return this.cancelTokenSource.token - } -} - -export default new Languages() diff --git a/vim-config/plugins/coc.nvim/src/list/basic.ts b/vim-config/plugins/coc.nvim/src/list/basic.ts deleted file mode 100644 index 19c83d7e..00000000 --- a/vim-config/plugins/coc.nvim/src/list/basic.ts +++ /dev/null @@ -1,323 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import fs from 'fs' -import path from 'path' -import readline from 'readline' -import { CancellationToken, Disposable, Location, Position, Range } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import { ProviderResult } from '../provider' -import { IList, ListAction, ListArgument, ListContext, ListItem, ListTask, LocationWithLine, WorkspaceConfiguration } from '../types' -import { disposeAll } from '../util' -import { readFile } from '../util/fs' -import { comparePosition, emptyRange } from '../util/position' -import workspace from '../workspace' -import CommandTask, { CommandTaskOption } from './commandTask' -import ListConfiguration from './configuration' -const logger = require('../util/logger')('list-basic') - -interface ActionOptions { - persist?: boolean - reload?: boolean - parallel?: boolean -} - -interface ArgumentItem { - hasValue: boolean - name: string -} - -interface PreviewConfig { - winid: number - position: string - hlGroup: string - maxHeight: number - name?: string - splitRight: boolean - lnum: number - filetype?: string - range?: Range - scheme?: string - toplineStyle: string - toplineOffset: number -} - -export interface PreviewOptions { - bufname?: string - filetype: string - lines: string[] - lnum?: number - range?: Range - sketch?: boolean -} - -export default abstract class BasicList implements IList, Disposable { - public name: string - public defaultAction = 'open' - public readonly actions: ListAction[] = [] - public options: ListArgument[] = [] - protected disposables: Disposable[] = [] - private optionMap: Map - public config: ListConfiguration - - constructor(protected nvim: Neovim) { - this.config = new ListConfiguration() - } - - public get alignColumns(): boolean { - return this.config.get('alignColumns', false) - } - - protected get hlGroup(): string { - return this.config.get('previewHighlightGroup', 'Search') - } - - protected get previewHeight(): number { - return this.config.get('maxPreviewHeight', 12) - } - - protected get splitRight(): boolean { - return this.config.get('previewSplitRight', false) - } - - protected get toplineStyle(): string { - return this.config.get('previewToplineStyle', 'offset') - } - - protected get toplineOffset(): number { - return this.config.get('previewToplineOffset', 3) - } - - public parseArguments(args: string[]): { [key: string]: string | boolean } { - if (!this.optionMap) { - this.optionMap = new Map() - for (let opt of this.options) { - let parts = opt.name.split(/,\s*/g).map(s => s.replace(/\s+.*/g, '')) - let name = opt.key ? opt.key : parts[parts.length - 1].replace(/^-/, '') - for (let p of parts) { - this.optionMap.set(p, { name, hasValue: opt.hasValue }) - } - } - } - let res: { [key: string]: string | boolean } = {} - for (let i = 0; i < args.length; i++) { - let arg = args[i] - let def = this.optionMap.get(arg) - if (!def) continue - let value: string | boolean = true - if (def.hasValue) { - value = args[i + 1] || '' - i = i + 1 - } - res[def.name] = value - } - return res - } - - /** - * Get configuration of current list - */ - protected getConfig(): WorkspaceConfiguration { - return workspace.getConfiguration(`list.source.${this.name}`) - } - - protected addAction(name: string, fn: (item: ListItem, context: ListContext) => ProviderResult, options?: ActionOptions): void { - this.createAction(Object.assign({ - name, - execute: fn - }, options || {})) - } - - protected addMultipleAction(name: string, fn: (item: ListItem[], context: ListContext) => ProviderResult, options?: ActionOptions): void { - this.createAction(Object.assign({ - name, - multiple: true, - execute: fn - }, options || {})) - } - - protected createCommandTask(opt: CommandTaskOption): CommandTask { - return new CommandTask(opt) - } - - public addLocationActions(): void { - this.createAction({ - name: 'preview', - execute: async (item: ListItem, context: ListContext) => { - let loc = await this.convertLocation(item.location) - await this.previewLocation(loc, context) - } - }) - let { nvim } = this - this.createAction({ - name: 'quickfix', - multiple: true, - execute: async (items: ListItem[]) => { - let quickfixItems = await Promise.all(items.map(item => this.convertLocation(item.location).then(loc => workspace.getQuickfixItem(loc)))) - await nvim.call('setqflist', [quickfixItems]) - let openCommand = await nvim.getVar('coc_quickfix_open_command') as string - nvim.command(typeof openCommand === 'string' ? openCommand : 'copen', true) - } - }) - for (let name of ['open', 'tabe', 'drop', 'vsplit', 'split']) { - this.createAction({ - name, - execute: async (item: ListItem) => { - await this.jumpTo(item.location, name == 'open' ? null : name) - } - }) - } - } - - public async convertLocation(location: Location | LocationWithLine | string): Promise { - if (typeof location == 'string') return Location.create(location, Range.create(0, 0, 0, 0)) - if (Location.is(location)) return location - let u = URI.parse(location.uri) - if (u.scheme != 'file') return Location.create(location.uri, Range.create(0, 0, 0, 0)) - const rl = readline.createInterface({ - input: fs.createReadStream(u.fsPath, { encoding: 'utf8' }), - }) - let match = location.line - let n = 0 - let resolved = false - let line = await new Promise(resolve => { - rl.on('line', line => { - if (resolved) return - if (line.includes(match)) { - rl.removeAllListeners() - rl.close() - resolved = true - resolve(line) - return - } - n = n + 1 - }) - rl.on('error', e => { - this.nvim.errWriteLine(`Read ${u.fsPath} error: ${e.message}`) - resolve(null) - }) - }) - if (line != null) { - let character = location.text ? line.indexOf(location.text) : 0 - if (character == 0) character = line.match(/^\s*/)[0].length - let end = Position.create(n, character + (location.text ? location.text.length : 0)) - return Location.create(location.uri, Range.create(Position.create(n, character), end)) - } - return Location.create(location.uri, Range.create(0, 0, 0, 0)) - } - - public async jumpTo(location: Location | LocationWithLine | string, command?: string): Promise { - if (typeof location == 'string') { - await workspace.jumpTo(location, null, command) - return - } - let { range, uri } = await this.convertLocation(location) - let position = range.start - if (position.line == 0 && position.character == 0 && comparePosition(position, range.end) == 0) { - // allow plugin that remember position. - position = null - } - await workspace.jumpTo(uri, position, command) - } - - public createAction(action: ListAction): void { - let { name } = action - let idx = this.actions.findIndex(o => o.name == name) - // allow override - if (idx !== -1) this.actions.splice(idx, 1) - this.actions.push(action) - } - - protected async previewLocation(location: Location, context: ListContext): Promise { - if (!context.listWindow) return - let { nvim } = this - let { uri, range } = location - let doc = workspace.getDocument(location.uri) - let u = URI.parse(uri) - let lines: string[] = [] - if (doc) { - lines = doc.getLines() - } else if (u.scheme == 'file') { - try { - let content = await readFile(u.fsPath, 'utf8') - lines = content.split(/\r?\n/) - } catch (e) { - [`Error on read file ${u.fsPath}`, e.message] - } - } - let config: PreviewConfig = { - winid: context.window.id, - range: emptyRange(range) ? null : range, - lnum: range.start.line + 1, - name: u.scheme == 'file' ? u.fsPath : uri, - filetype: doc ? doc.filetype : this.getFiletype(u.fsPath), - position: context.options.position, - maxHeight: this.previewHeight, - splitRight: this.splitRight, - hlGroup: this.hlGroup, - scheme: u.scheme, - toplineStyle: this.toplineStyle, - toplineOffset: this.toplineOffset, - } - await nvim.call('coc#list#preview', [lines, config]) - if (workspace.isVim) nvim.command('redraw', true) - } - - public async preview(options: PreviewOptions, context: ListContext): Promise { - let { nvim } = this - let { bufname, filetype, range, lines, lnum } = options - let config: PreviewConfig = { - winid: context.window.id, - lnum: range ? range.start.line + 1 : lnum || 1, - filetype: filetype || 'txt', - position: context.options.position, - maxHeight: this.previewHeight, - splitRight: this.splitRight, - hlGroup: this.hlGroup, - toplineStyle: this.toplineStyle, - toplineOffset: this.toplineOffset, - } - if (bufname) config.name = bufname - if (range) config.range = range - await nvim.call('coc#list#preview', [lines, config]) - if (workspace.isVim) nvim.command('redraw', true) - } - - public abstract loadItems(context: ListContext, token?: CancellationToken): Promise - - public doHighlight(): void { - // noop - } - - public dispose(): void { - disposeAll(this.disposables) - } - - /** - * Get filetype by check same extension name buffer. - */ - private getFiletype(filepath: string): string { - let extname = path.extname(filepath) - if (!extname) return '' - for (let doc of workspace.documents) { - let fsPath = URI.parse(doc.uri).fsPath - if (path.extname(fsPath) == extname) { - return getFiletype(doc.filetype) - } - } - return '' - } -} - -export function getFiletype(filetype: string): string { - switch (filetype) { - case 'javascriptreact': - return 'javascript' - case 'typescriptreact': - return 'typescript' - case 'latex': - // LaTeX (LSP language ID 'latex') has Vim filetype 'tex' - return 'tex' - default: - if (filetype.indexOf('.') !== -1) return filetype.split('.')[0] - return filetype - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/commandTask.ts b/vim-config/plugins/coc.nvim/src/list/commandTask.ts deleted file mode 100644 index e67dc19c..00000000 --- a/vim-config/plugins/coc.nvim/src/list/commandTask.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { spawn } from 'child_process' -import { EventEmitter } from 'events' -import readline from 'readline' -import { Disposable } from 'vscode-languageserver-protocol' -import { ListItem, ListTask } from '../types' -import { disposeAll } from '../util' -const logger = require('../util/logger')('list-commandTask') - -export interface CommandTaskOption { - /** - * Command to run. - */ - cmd: string - /** - * Arguments of command. - */ - args: string[] - cwd: string - /** - * Runs for each line, return undefined for invalid item. - */ - onLine: (line: string) => ListItem | undefined -} - -export default class CommandTask extends EventEmitter implements ListTask { - private disposables: Disposable[] = [] - constructor(private opt: CommandTaskOption) { - super() - this.start() - } - - private start(): void { - let { cmd, args, cwd, onLine } = this.opt - let proc = spawn(cmd, args, { cwd, windowsHide: true }) - this.disposables.push({ - dispose: () => { - proc.kill() - } - }) - proc.on('error', e => { - this.emit('error', e.message) - }) - proc.stderr.on('data', chunk => { - logger.error(`[${cmd} Error]`, chunk.toString('utf8')) - }) - const rl = readline.createInterface(proc.stdout) - rl.on('line', line => { - let res = onLine(line) - if (res) this.emit('data', res) - }) - rl.on('close', () => { - this.emit('end') - }) - } - - public dispose(): void { - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/configuration.ts b/vim-config/plugins/coc.nvim/src/list/configuration.ts deleted file mode 100644 index 933ad9e3..00000000 --- a/vim-config/plugins/coc.nvim/src/list/configuration.ts +++ /dev/null @@ -1,120 +0,0 @@ -import workspace from '../workspace' -import window from '../window' -import { WorkspaceConfiguration } from '../types' -import { EventEmitter } from 'events' -import { Disposable } from 'vscode-languageserver-protocol' - -export const validKeys = [ - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '<2-LeftMouse>', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', -] - -export default class ListConfiguration extends EventEmitter { - private configuration: WorkspaceConfiguration - private disposable: Disposable - constructor() { - super() - this.configuration = workspace.getConfiguration('list') - this.disposable = workspace.onDidChangeConfiguration(e => { - if (e.affectsConfiguration('list')) { - this.configuration = workspace.getConfiguration('list') - this.emit('change') - } - }) - } - - public get(key: string, defaultValue?: T): T { - return this.configuration.get(key, defaultValue) - } - - public get previousKey(): string { - return this.fixKey(this.configuration.get('previousKeymap', '')) - } - - public get nextKey(): string { - return this.fixKey(this.configuration.get('nextKeymap', '')) - } - - public dispose(): void { - this.disposable.dispose() - this.removeAllListeners() - } - - public fixKey(key: string): string { - if (validKeys.includes(key)) return key - let find = validKeys.find(s => s.toLowerCase() == key.toLowerCase()) - if (find) return find - window.showMessage(`Configured key "${key}" not supported.`, 'error') - return null - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/formatting.ts b/vim-config/plugins/coc.nvim/src/list/formatting.ts deleted file mode 100644 index fa8a4c62..00000000 --- a/vim-config/plugins/coc.nvim/src/list/formatting.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { ListItem } from '../types' -import path from 'path' - -export type PathFormatting = "full" | "short" | "filename" | "hidden" - -export interface UnformattedListItem extends Omit { - label: string[] -} - -export function formatListItems(align: boolean, list: UnformattedListItem[]): ListItem[] { - if (list.length === 0) { - return [] - } - - let processedList: ListItem[] = [] - if (align) { - const maxWidths = Array(Math.min(...list.map(item => item.label.length))).fill(0) - for (let item of list) { - for (let i = 0; i < maxWidths.length; i++) { - maxWidths[i] = Math.max(maxWidths[i], item.label[i].length) - } - } - processedList = list - .map(item => ({ - ...item, - label: item.label - .map((element, idx) => element.padEnd(maxWidths[idx])) - .join("\t") - })) - } else { - processedList = list.map(item => ({ ...item, label: item.label.join("\t") })) - } - return processedList -} - -export function formatPath(format: PathFormatting, pathToFormat: string): string { - if (format === "hidden") { - return "" - } else if (format === "full") { - return pathToFormat - } else if (format === "short") { - const segments = pathToFormat.split(path.sep) - if (segments.length < 2) { - return pathToFormat - } - const shortenedInit = segments - .slice(0, segments.length - 2) - .filter(seg => seg.length > 0) - .map(seg => seg[0]) - return [...shortenedInit, segments[segments.length - 1]].join(path.sep) - } else { - const segments = pathToFormat.split(path.sep) - return segments[segments.length - 1] ?? "" - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/history.ts b/vim-config/plugins/coc.nvim/src/list/history.ts deleted file mode 100644 index 4a71721e..00000000 --- a/vim-config/plugins/coc.nvim/src/list/history.ts +++ /dev/null @@ -1,83 +0,0 @@ -import DB from '../model/db' -import { fuzzyMatch, getCharCodes } from '../util/fuzzy' -import workspace from '../workspace' -import Prompt from './prompt' -const logger = require('../util/logger')('list-history') - -export default class InputHistory { - private db: DB - private index = -1 - private loaded: string[] = [] - private current: string[] = [] - private historyInput: string - private key: string - - constructor( - private prompt: Prompt, - private name: string - ) { - this.db = workspace.createDatabase(`list-${name}-history`) - this.key = Buffer.from(workspace.cwd).toString('base64') - } - - public filter(): void { - let { input } = this.prompt - if (input == this.curr) return - this.historyInput = '' - let codes = getCharCodes(input) - this.current = this.loaded.filter(s => fuzzyMatch(codes, s)) - this.index = -1 - } - - public get curr(): string | null { - return this.index == -1 ? null : this.current[this.index] - } - - public load(input: string): void { - let { db } = this - input = input || '' - let arr = db.fetch(this.key) - if (!arr || !Array.isArray(arr)) { - this.loaded = [] - } else { - this.loaded = arr - } - this.index = -1 - this.current = this.loaded.filter(s => s.startsWith(input)) - } - - public add(): void { - let { loaded, db, prompt } = this - let { input } = prompt - if (!input || input.length < 2 || input == this.historyInput) return - let idx = loaded.indexOf(input) - if (idx != -1) loaded.splice(idx, 1) - loaded.push(input) - if (loaded.length > 200) { - loaded = loaded.slice(-200) - } - db.push(this.key, loaded) - } - - public previous(): void { - let { current, index } = this - if (!current || !current.length) return - if (index <= 0) { - this.index = current.length - 1 - } else { - this.index = index - 1 - } - this.historyInput = this.prompt.input = current[this.index] || '' - } - - public next(): void { - let { current, index } = this - if (!current || !current.length) return - if (index == current.length - 1) { - this.index = 0 - } else { - this.index = index + 1 - } - this.historyInput = this.prompt.input = current[this.index] || '' - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/manager.ts b/vim-config/plugins/coc.nvim/src/list/manager.ts deleted file mode 100644 index 9ac20ecc..00000000 --- a/vim-config/plugins/coc.nvim/src/list/manager.ts +++ /dev/null @@ -1,496 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import debounce from 'debounce' -import { CancellationTokenSource, Disposable } from 'vscode-languageserver-protocol' -import events from '../events' -import extensions from '../extensions' -import { IList, ListOptions, Matcher } from '../types' -import { disposeAll } from '../util' -import workspace from '../workspace' -import window from '../window' -import ListConfiguration from './configuration' -import Mappings from './mappings' -import Prompt from './prompt' -import ListSession from './session' -import CommandsList from './source/commands' -import DiagnosticsList from './source/diagnostics' -import ExtensionList from './source/extensions' -import FolderList from './source/folders' -import LinksList from './source/links' -import ListsList from './source/lists' -import LocationList from './source/location' -import OutlineList from './source/outline' -import ServicesList from './source/services' -import SourcesList from './source/sources' -import SymbolsList from './source/symbols' -const logger = require('../util/logger')('list-manager') - -const mouseKeys = ['', '', '', '<2-LeftMouse>'] - -export class ListManager implements Disposable { - public prompt: Prompt - public config: ListConfiguration - private nvim: Neovim - private plugTs = 0 - private mappings: Mappings - private sessionsMap: Map = new Map() - private lastSession: ListSession | undefined - private disposables: Disposable[] = [] - private listMap: Map = new Map() - - public init(nvim: Neovim): void { - this.nvim = nvim - this.config = new ListConfiguration() - this.prompt = new Prompt(nvim, this.config) - this.mappings = new Mappings(this, nvim, this.config) - let signText = this.config.get('selectedSignText', '*') - nvim.command(`sign define CocSelected text=${signText} texthl=CocSelectedText linehl=CocSelectedLine`, true) - events.on('InputChar', this.onInputChar, this, this.disposables) - let debounced = debounce(async () => { - let session = await this.getCurrentSession() - if (session) this.prompt.drawPrompt() - }, 100) - events.on('FocusGained', debounced, null, this.disposables) - events.on('WinEnter', winid => { - let session = this.getSessionByWinid(winid) - if (session) this.prompt.start(session.listOptions) - }, null, this.disposables) - events.on('WinLeave', winid => { - let session = this.getSessionByWinid(winid) - if (session) this.prompt.cancel() - }, null, this.disposables) - this.disposables.push({ - dispose: () => { - debounced.clear() - } - }) - // filter history on input - this.prompt.onDidChangeInput(() => { - let { session } = this - if (!session) return - session.onInputChange() - session.history.filter() - }) - this.registerList(new LinksList(nvim)) - this.registerList(new LocationList(nvim)) - this.registerList(new SymbolsList(nvim)) - this.registerList(new OutlineList(nvim)) - this.registerList(new CommandsList(nvim)) - this.registerList(new ExtensionList(nvim)) - this.registerList(new DiagnosticsList(nvim)) - this.registerList(new SourcesList(nvim)) - this.registerList(new ServicesList(nvim)) - this.registerList(new ListsList(nvim, this.listMap)) - this.registerList(new FolderList(nvim)) - } - - public async start(args: string[]): Promise { - let res = this.parseArgs(args) - if (!res) return - let { name } = res.list - let curr = this.sessionsMap.get(name) - if (curr) curr.dispose() - this.prompt.start(res.options) - let session = new ListSession(this.nvim, this.prompt, res.list, res.options, res.listArgs, this.config) - this.sessionsMap.set(name, session) - this.lastSession = session - try { - await session.start(args) - } catch (e) { - this.nvim.call('coc#prompt#stop_prompt', ['list'], true) - let msg = e instanceof Error ? e.message : e.toString() - window.showMessage(`Error on "CocList ${name}": ${msg}`, 'error') - logger.error(e) - } - } - - private getSessionByWinid(winid: number): ListSession | null { - for (let session of this.sessionsMap.values()) { - if (session && session.winid == winid) { - this.lastSession = session - return session - } - } - return null - } - - private async getCurrentSession(): Promise { - let { id } = await this.nvim.window - for (let session of this.sessionsMap.values()) { - if (session && session.winid == id) { - this.lastSession = session - return session - } - } - return null - } - - public async resume(name?: string): Promise { - if (!name) { - await this.session?.resume() - } else { - let session = this.sessionsMap.get(name) - if (!session) { - window.showMessage(`Can't find exists ${name} list`) - return - } - await session.resume() - } - } - - public async doAction(name?: string): Promise { - let lastSession = this.lastSession - if (!lastSession) return - await lastSession.doAction(name) - } - - public async first(name?: string): Promise { - let s = this.getSession(name) - if (s) await s.first() - } - - public async last(name?: string): Promise { - let s = this.getSession(name) - if (s) await s.last() - } - - public async previous(name?: string): Promise { - let s = this.getSession(name) - if (s) await s.previous() - } - - public async next(name?: string): Promise { - let s = this.getSession(name) - if (s) await s.next() - } - - private getSession(name?: string): ListSession { - if (!name) return this.session - return this.sessionsMap.get(name) - } - - public async cancel(close = true): Promise { - this.prompt.cancel() - if (!close) return - if (this.session) await this.session.hide() - } - - /** - * Clear all list sessions - */ - public reset(): void { - this.prompt.cancel() - this.lastSession = undefined - for (let session of this.sessionsMap.values()) { - session.dispose() - } - this.sessionsMap.clear() - this.nvim.call('coc#prompt#stop_prompt', ['list'], true) - } - - public switchMatcher(): void { - this.session?.switchMatcher() - } - - public async togglePreview(): Promise { - let { nvim } = this - let winid = await nvim.call('coc#list#get_preview', [0]) - if (winid != -1) { - await nvim.call('coc#window#close', [winid]) - await nvim.command('redraw') - } else { - await this.doAction('preview') - } - } - - public async chooseAction(): Promise { - let { lastSession } = this - if (lastSession) await lastSession.chooseAction() - } - - public parseArgs(args: string[]): { list: IList; options: ListOptions; listArgs: string[] } | null { - let options: string[] = [] - let interactive = false - let autoPreview = false - let numberSelect = false - let noQuit = false - let first = false - let name: string - let input = '' - let matcher: Matcher = 'fuzzy' - let position = 'bottom' - let listArgs: string[] = [] - let listOptions: string[] = [] - for (let arg of args) { - if (!name && arg.startsWith('-')) { - listOptions.push(arg) - } else if (!name) { - if (!/^\w+$/.test(arg)) { - window.showMessage(`Invalid list option: "${arg}"`, 'error') - return null - } - name = arg - } else { - listArgs.push(arg) - } - } - name = name || 'lists' - let config = workspace.getConfiguration(`list.source.${name}`) - if (!listOptions.length && !listArgs.length) listOptions = config.get('defaultOptions', []) - if (!listArgs.length) listArgs = config.get('defaultArgs', []) - for (let opt of listOptions) { - if (opt.startsWith('--input')) { - input = opt.slice(8) - } else if (opt == '--number-select' || opt == '-N') { - numberSelect = true - } else if (opt == '--auto-preview' || opt == '-A') { - autoPreview = true - } else if (opt == '--regex' || opt == '-R') { - matcher = 'regex' - } else if (opt == '--strict' || opt == '-S') { - matcher = 'strict' - } else if (opt == '--interactive' || opt == '-I') { - interactive = true - } else if (opt == '--top') { - position = 'top' - } else if (opt == '--tab') { - position = 'tab' - } else if (opt == '--ignore-case' || opt == '--normal' || opt == '--no-sort') { - options.push(opt.slice(2)) - } else if (opt == '--first') { - first = true - } else if (opt == '--no-quit') { - noQuit = true - } else { - window.showMessage(`Invalid option "${opt}" of list`, 'error') - return null - } - } - let list = this.listMap.get(name) - if (!list) { - window.showMessage(`List ${name} not found`, 'error') - return null - } - if (interactive && !list.interactive) { - window.showMessage(`Interactive mode of "${name}" list not supported`, 'error') - return null - } - return { - list, - listArgs, - options: { - numberSelect, - autoPreview, - noQuit, - first, - input, - interactive, - matcher, - position, - ignorecase: options.includes('ignore-case') ? true : false, - mode: !options.includes('normal') ? 'insert' : 'normal', - sort: !options.includes('no-sort') ? true : false - }, - } - } - - private async onInputChar(session: string, ch: string, charmod: number): Promise { - if (session != 'list') return - let { mode } = this.prompt - let now = Date.now() - if (ch == '' || (this.plugTs && now - this.plugTs < 20)) { - this.plugTs = now - return - } - if (!ch) return - if (ch == '') { - await this.cancel() - return - } - if (mode == 'insert') { - await this.onInsertInput(ch, charmod) - } else { - await this.onNormalInput(ch, charmod) - } - } - - public async onInsertInput(ch: string, charmod?: number): Promise { - let { session } = this - if (!session) return - if (mouseKeys.includes(ch)) { - await this.onMouseEvent(ch) - return - } - let n = await session.doNumberSelect(ch) - if (n) return - let done = await this.mappings.doInsertKeymap(ch) - if (done || charmod) return - if (ch.startsWith('<') && ch.endsWith('>')) return - for (let s of ch) { - let code = s.codePointAt(0) - if (code == 65533) return - // exclude control character - if (code < 32 || code >= 127 && code <= 159) return - await this.prompt.acceptCharacter(s) - } - } - - public async onNormalInput(ch: string, _charmod?: number): Promise { - if (mouseKeys.includes(ch)) { - await this.onMouseEvent(ch) - return - } - let used = await this.mappings.doNormalKeymap(ch) - if (!used) await this.feedkeys(ch) - } - - private onMouseEvent(key): Promise { - if (this.session) return this.session.onMouseEvent(key) - } - - public async feedkeys(key: string, remap = true): Promise { - let { nvim } = this - key = key.startsWith('<') && key.endsWith('>') ? `\\${key}` : key - await nvim.call('coc#prompt#stop_prompt', ['list']) - await nvim.call('eval', [`feedkeys("${key}", "${remap ? 'i' : 'in'}")`]) - this.prompt.start() - } - - public async command(command: string): Promise { - let { nvim } = this - await nvim.call('coc#prompt#stop_prompt', ['list']) - await nvim.command(command) - this.prompt.start() - } - - public async normal(command: string, bang = true): Promise { - let { nvim } = this - await nvim.call('coc#prompt#stop_prompt', ['list']) - await nvim.command(`normal${bang ? '!' : ''} ${command}`) - this.prompt.start() - } - - public async call(fname: string): Promise { - if (this.session) return await this.session.call(fname) - } - - public get session(): ListSession | undefined { - return this.lastSession - } - - public registerList(list: IList): Disposable { - const { name } = list - let exists = this.listMap.get(name) - if (this.listMap.has(name)) { - if (exists) { - if (typeof exists.dispose == 'function') { - exists.dispose() - } - this.listMap.delete(name) - } - window.showMessage(`list "${name}" recreated.`) - } - this.listMap.set(name, list) - let config = workspace.getConfiguration(`list.source.${name}`) - let defaultAction = config.get('defaultAction') - if (defaultAction && list.actions.find(o => o.name == defaultAction)) { - list.defaultAction = defaultAction - } - extensions.addSchemeProperty(`list.source.${name}.defaultAction`, { - type: 'string', - default: null, - description: `Default default action of "${name}" list.` - }) - extensions.addSchemeProperty(`list.source.${name}.defaultOptions`, { - type: 'array', - default: list.interactive ? ['--interactive'] : [], - description: `Default list options of "${name}" list, only used when both list option and argument are empty.`, - uniqueItems: true, - items: { - type: 'string', - enum: ['--top', '--normal', '--no-sort', '--input', '--tab', - '--strict', '--regex', '--ignore-case', '--number-select', - '--interactive', '--auto-preview', '--first', '--no-quit'] - } - }) - extensions.addSchemeProperty(`list.source.${name}.defaultArgs`, { - type: 'array', - default: [], - description: `Default argument list of "${name}" list, only used when list argument is empty.`, - uniqueItems: true, - items: { type: 'string' } - }) - return Disposable.create(() => { - if (typeof list.dispose == 'function') { - list.dispose() - } - this.listMap.delete(name) - }) - } - - public get names(): string[] { - return Array.from(this.listMap.keys()) - } - - public get descriptions(): { [name: string]: string } { - let d = {} - for (let name of this.listMap.keys()) { - let list = this.listMap.get(name) - d[name] = list.description - } - return d - } - - /** - * Get items of {name} list, not work with interactive list and list return task. - * - * @param {string} name - * @returns {Promise} - */ - public async loadItems(name: string): Promise { - let args = [name] - let res = this.parseArgs(args) - if (!res) return - let { list, options, listArgs } = res - let source = new CancellationTokenSource() - let token = source.token - let arr = await this.nvim.eval('[win_getid(),bufnr("%")]') - let items = await list.loadItems({ - options, - args: listArgs, - input: '', - cwd: workspace.cwd, - window: this.nvim.createWindow(arr[0]), - buffer: this.nvim.createBuffer(arr[1]), - listWindow: null - }, token) - return items - } - - public toggleMode(): void { - let lastSession = this.lastSession - if (lastSession) lastSession.toggleMode() - } - - public get isActivated(): boolean { - return this.session?.winid != null - } - - public stop(): void { - let lastSession = this.lastSession - if (lastSession) lastSession.stop() - } - - public dispose(): void { - for (let session of this.sessionsMap.values()) { - session.dispose() - } - this.sessionsMap.clear() - if (this.config) { - this.config.dispose() - } - this.lastSession = undefined - disposeAll(this.disposables) - } -} - -export default new ListManager() diff --git a/vim-config/plugins/coc.nvim/src/list/mappings.ts b/vim-config/plugins/coc.nvim/src/list/mappings.ts deleted file mode 100644 index 2b816ef2..00000000 --- a/vim-config/plugins/coc.nvim/src/list/mappings.ts +++ /dev/null @@ -1,321 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { ListMode } from '../types' -import '../util/extensions' -import window from '../window' -import ListConfiguration, { validKeys } from './configuration' -import { ListManager } from './manager' -const logger = require('../util/logger')('list-mappings') - -export default class Mappings { - private insertMappings: Map void | Promise> = new Map() - private normalMappings: Map void | Promise> = new Map() - private userInsertMappings: Map = new Map() - private userNormalMappings: Map = new Map() - - constructor(private manager: ListManager, - private nvim: Neovim, - private config: ListConfiguration) { - let { prompt } = manager - - this.add('insert', '', () => { - manager.session?.history.next() - }) - this.add('insert', '', () => { - manager.session?.history.previous() - }) - this.add('insert', '', async () => { - await prompt.paste() - }) - this.add('insert', '', () => manager.switchMatcher()) - this.add('insert', ['', ''], async () => { - await manager.doAction() - }) - this.add('insert', ['', '', '\t'], () => manager.chooseAction()) - this.add('insert', '', () => { - manager.toggleMode() - }) - this.add('insert', '', () => { - manager.stop() - return - }) - this.add('insert', '', async () => { - await manager.session?.reloadItems() - }) - this.add('insert', '', () => { - prompt.moveLeft() - }) - this.add('insert', '', () => { - prompt.moveRight() - }) - this.add('insert', ['', ''], () => { - prompt.moveToEnd() - }) - this.add('insert', ['', ''], () => { - prompt.moveToStart() - }) - this.add('insert', ['', '', ''], () => { - prompt.onBackspace() - }) - this.add('insert', '', () => { - prompt.removeWord() - }) - this.add('insert', '', () => { - prompt.removeAhead() - }) - this.add('insert', '', () => prompt.insertRegister()) - this.add('insert', '', () => manager.feedkeys('', false)) - this.add('insert', '', () => manager.feedkeys('', false)) - this.add('insert', '', () => manager.feedkeys('', false)) - this.add('insert', '', () => manager.normal('j')) - this.add('insert', '', () => manager.normal('k')) - this.add('insert', [''], this.doScroll.bind(this, '')) - this.add('insert', [''], this.doScroll.bind(this, '')) - this.add('insert', [''], this.doScroll.bind(this, '')) - this.add('insert', [''], this.doScroll.bind(this, '')) - this.add('normal', 't', () => manager.doAction('tabe')) - this.add('normal', 's', () => manager.doAction('split')) - this.add('normal', 'd', () => manager.doAction('drop')) - this.add('normal', ['', '', '\r'], () => manager.doAction()) - this.add('normal', '', () => manager.session?.ui.selectAll()) - this.add('normal', ' ', () => manager.session?.ui.toggleSelection()) - this.add('normal', 'p', () => manager.togglePreview()) - this.add('normal', ['', '\t', ''], () => manager.chooseAction()) - this.add('normal', '', () => { - manager.stop() - }) - this.add('normal', '', () => manager.session?.reloadItems()) - this.add('normal', '', () => manager.session?.jumpBack()) - this.add('normal', '', () => this.scrollPreview('down')) - this.add('normal', '', () => this.scrollPreview('up')) - this.add('normal', ['i', 'I', 'o', 'O', 'a', 'A'], () => manager.toggleMode()) - this.add('normal', '?', () => manager.session?.showHelp()) - this.add('normal', ':', async () => { - await manager.cancel(false) - await nvim.eval('feedkeys(":")') - }) - this.add('normal', [''], this.doScroll.bind(this, '')) - this.add('normal', [''], this.doScroll.bind(this, '')) - this.createMappings() - config.on('change', () => { - this.createMappings() - }) - } - - private createMappings(): void { - let insertMappings = this.config.get('insertMappings', {}) - this.userInsertMappings = this.fixUserMappings(insertMappings) - let normalMappings = this.config.get('normalMappings', {}) - this.userNormalMappings = this.fixUserMappings(normalMappings) - } - - private fixUserMappings(mappings: { [key: string]: string }): Map { - let res: Map = new Map() - for (let [key, value] of Object.entries(mappings)) { - if (key.length == 1) { - res.set(key, value) - } else if (key.startsWith('<') && key.endsWith('>')) { - if (key.toLowerCase() == '') { - res.set(' ', value) - } else if (key.toLowerCase() == '') { - res.set('', value) - } else if (validKeys.includes(key)) { - res.set(key, value) - } else { - let find = false - for (let i = 0; i < validKeys.length; i++) { - if (validKeys[i].toLowerCase() == key.toLowerCase()) { - find = true - res.set(validKeys[i], value) - break - } - } - if (!find) window.showMessage(`Invalid list mappings key configuration: "${key}"`, 'warning') - } - } else { - window.showMessage(`Invalid list mappings key configuration: "${key}"`, 'warning') - } - } - return res - } - - public async doInsertKeymap(key: string): Promise { - let nextKey = this.config.nextKey - let previousKey = this.config.previousKey - let { session } = this.manager - if (!session) return - if (key == nextKey) { - session.ui.index = session.ui.index + 1 - return true - } - if (key == previousKey) { - session.ui.index = session.ui.index - 1 - return true - } - let expr = this.userInsertMappings.get(key) - if (expr) { - await this.evalExpression(expr, 'insert') - return true - } - if (this.insertMappings.has(key)) { - let fn = this.insertMappings.get(key) - await Promise.resolve(fn()) - return true - } - return false - } - - public async doNormalKeymap(key: string): Promise { - let expr = this.userNormalMappings.get(key) - if (expr) { - await this.evalExpression(expr, 'normal') - return true - } - if (this.normalMappings.has(key)) { - let fn = this.normalMappings.get(key) - await Promise.resolve(fn()) - return true - } - return false - } - - private add(mode: ListMode, key: string | string[], fn: () => void | Promise): void { - let mappings = mode == 'insert' ? this.insertMappings : this.normalMappings - if (Array.isArray(key)) { - for (let k of key) { - mappings.set(k, fn) - } - } else { - mappings.set(key, fn) - } - } - - private async onError(msg: string): Promise { - let { nvim } = this - await nvim.call('coc#prompt#stop_prompt', ['list']) - window.showMessage(msg, 'error') - } - - private async evalExpression(expr: string, _mode: string): Promise { - if (typeof expr != 'string' || !expr.includes(':')) { - await this.onError(`Invalid list mapping expression: ${expr}`) - return - } - let { manager } = this - let { prompt } = manager - let [key, action] = expr.split(':', 2) - if (key == 'do') { - switch (action.toLowerCase()) { - case 'switch': - manager.switchMatcher() - return - case 'selectall': - await manager.session?.ui.selectAll() - return - case 'help': - await manager.session?.showHelp() - return - case 'refresh': - await manager.session?.reloadItems() - return - case 'exit': - await manager.cancel() - return - case 'stop': - manager.stop() - return - case 'cancel': - await manager.cancel(false) - return - case 'toggle': - await manager.session?.ui.toggleSelection() - return - case 'jumpback': - manager.session?.jumpBack() - return - case 'previous': - await manager.normal('k') - return - case 'next': - await manager.normal('j') - return - case 'defaultaction': - await manager.doAction() - return - case 'togglemode': - return manager.toggleMode() - case 'previewtoggle': - return manager.togglePreview() - case 'previewup': - return this.scrollPreview('up') - case 'previewdown': - return this.scrollPreview('down') - default: - await this.onError(`'${action}' not supported`) - } - } else if (key == 'prompt') { - switch (action) { - case 'previous': - manager.session?.history.previous() - return - case 'next': - manager.session?.history.next() - return - case 'start': - return prompt.moveToStart() - case 'end': - return prompt.moveToEnd() - case 'left': - return prompt.moveLeft() - case 'right': - return prompt.moveRight() - case 'deleteforward': - return prompt.onBackspace() - case 'deletebackward': - return prompt.removeNext() - case 'removetail': - return prompt.removeTail() - case 'removeahead': - return prompt.removeAhead() - case 'insertregister': - prompt.insertRegister() - return - case 'paste': - await prompt.paste() - return - default: - await this.onError(`prompt '${action}' not supported`) - } - } else if (key == 'eval') { - await prompt.eval(action) - } else if (key == 'command') { - await manager.command(action) - } else if (key == 'action') { - await manager.doAction(action) - } else if (key == 'feedkeys') { - await manager.feedkeys(action) - } else if (key == 'normal') { - await manager.normal(action, false) - } else if (key == 'normal!') { - await manager.normal(action, true) - } else if (key == 'call') { - await manager.call(action) - } else if (key == 'expr') { - let name = await manager.call(action) - if (name) await manager.doAction(name) - } else { - await this.onError(`Invalid expression ${expr}`) - } - } - - private async doScroll(key: string): Promise { - await this.manager.feedkeys(key) - } - - private scrollPreview(dir: 'up' | 'down'): void { - let { nvim } = this - nvim.pauseNotification() - nvim.call('coc#list#scroll_preview', [dir], true) - nvim.command('redraw', true) - void nvim.resumeNotification(false, true) - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/prompt.ts b/vim-config/plugins/coc.nvim/src/list/prompt.ts deleted file mode 100644 index ca31cd62..00000000 --- a/vim-config/plugins/coc.nvim/src/list/prompt.ts +++ /dev/null @@ -1,214 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Emitter, Event } from 'vscode-languageserver-protocol' -import { ListMode, ListOptions, Matcher } from '../types' -import ListConfiguration from './configuration' -const logger = require('../util/logger')('list-prompt') - -export default class Prompt { - private cusorIndex = 0 - private _input = '' - private _matcher: Matcher | '' - private _mode: ListMode = 'insert' - private interactive = false - private requestInput = false - - private _onDidChangeInput = new Emitter() - public readonly onDidChangeInput: Event = this._onDidChangeInput.event - - constructor(private nvim: Neovim, private config: ListConfiguration) { - } - - public get input(): string { - return this._input - } - - public set input(str: string) { - if (this._input == str) return - this.cusorIndex = str.length - this._input = str - this.drawPrompt() - this._onDidChangeInput.fire(this._input) - } - - public get mode(): ListMode { - return this._mode - } - - public set mode(val: ListMode) { - if (val == this._mode) return - this._mode = val - this.drawPrompt() - } - - public set matcher(val: Matcher) { - this._matcher = val - this.drawPrompt() - } - - public start(opts?: ListOptions): void { - if (opts) { - this.interactive = opts.interactive - this.cusorIndex = opts.input.length - this._input = opts.input - this._mode = opts.mode - this._matcher = opts.interactive ? '' : opts.matcher - } - this.nvim.call('coc#prompt#start_prompt', ['list'], true) - this.drawPrompt() - } - - public cancel(): void { - let { nvim } = this - nvim.call('coc#prompt#stop_prompt', ['list'], true) - } - - public reset(): void { - this._input = '' - this.cusorIndex = 0 - } - - public drawPrompt(): void { - let indicator = this.config.get('indicator', '>') - let { cusorIndex, interactive, input, _matcher } = this - let cmds = ['echo ""'] - if (this.mode == 'insert') { - if (interactive) { - cmds.push(`echohl MoreMsg | echon 'INTERACTIVE ' | echohl None`) - } else if (_matcher) { - cmds.push(`echohl MoreMsg | echon '${_matcher.toUpperCase()} ' | echohl None`) - } - cmds.push(`echohl Special | echon '${indicator} ' | echohl None`) - if (cusorIndex == input.length) { - cmds.push(`echon '${input.replace(/'/g, "''")}'`) - cmds.push(`echohl Cursor | echon ' ' | echohl None`) - } else { - let pre = input.slice(0, cusorIndex) - if (pre) cmds.push(`echon '${pre.replace(/'/g, "''")}'`) - cmds.push(`echohl Cursor | echon '${input[cusorIndex].replace(/'/, "''")}' | echohl None`) - let post = input.slice(cusorIndex + 1) - cmds.push(`echon '${post.replace(/'/g, "''")}'`) - } - } else { - cmds.push(`echohl MoreMsg | echo "" | echohl None`) - } - cmds.push('redraw') - let cmd = cmds.join('|') - this.nvim.command(cmd, true) - } - - public moveLeft(): void { - if (this.cusorIndex == 0) return - this.cusorIndex = this.cusorIndex - 1 - this.drawPrompt() - } - - public moveRight(): void { - if (this.cusorIndex == this._input.length) return - this.cusorIndex = this.cusorIndex + 1 - this.drawPrompt() - } - - public moveToEnd(): void { - if (this.cusorIndex == this._input.length) return - this.cusorIndex = this._input.length - this.drawPrompt() - } - - public moveToStart(): void { - if (this.cusorIndex == 0) return - this.cusorIndex = 0 - this.drawPrompt() - } - - public onBackspace(): void { - let { cusorIndex, input } = this - if (cusorIndex == 0) return - let pre = input.slice(0, cusorIndex) - let post = input.slice(cusorIndex) - this.cusorIndex = cusorIndex - 1 - this._input = `${pre.slice(0, pre.length - 1)}${post}` - this.drawPrompt() - this._onDidChangeInput.fire(this._input) - } - - public removeNext(): void { - let { cusorIndex, input } = this - if (cusorIndex == input.length - 1) return - let pre = input.slice(0, cusorIndex) - let post = input.slice(cusorIndex + 1) - this._input = `${pre}${post}` - this.drawPrompt() - this._onDidChangeInput.fire(this._input) - } - - public removeWord(): void { - let { cusorIndex, input } = this - if (cusorIndex == 0) return - let pre = input.slice(0, cusorIndex) - let post = input.slice(cusorIndex) - let remain = pre.replace(/[\w$]+([^\w$]+)?$/, '') - this.cusorIndex = cusorIndex - (pre.length - remain.length) - this._input = `${remain}${post}` - this.drawPrompt() - this._onDidChangeInput.fire(this._input) - } - - public removeTail(): void { - let { cusorIndex, input } = this - if (cusorIndex == input.length) return - let pre = input.slice(0, cusorIndex) - this._input = pre - this.drawPrompt() - this._onDidChangeInput.fire(this._input) - } - - public removeAhead(): void { - let { cusorIndex, input } = this - if (cusorIndex == 0) return - let post = input.slice(cusorIndex) - this.cusorIndex = 0 - this._input = post - this.drawPrompt() - this._onDidChangeInput.fire(this._input) - } - - public async acceptCharacter(ch: string): Promise { - if (this.requestInput) { - this.requestInput = false - if (/^[0-9a-z"%#*+/:\-.]$/.test(ch)) { - let text = await this.nvim.call('getreg', ch) as string - text = text.replace(/\n/g, ' ') - this.addText(text) - } - } else { - this.addText(ch) - } - } - - public insertRegister(): void { - this.requestInput = true - } - - public async paste(): Promise { - let text = await this.nvim.eval('@*') as string - text = text.replace(/\n/g, '') - if (!text) return - this.addText(text) - } - - public async eval(expression: string): Promise { - let text = await this.nvim.call('eval', [expression]) as string - text = text.replace(/\n/g, '') - this.addText(text) - } - - private addText(text: string): void { - let { cusorIndex, input } = this - this.cusorIndex = cusorIndex + text.length - let pre = input.slice(0, cusorIndex) - let post = input.slice(cusorIndex) - this._input = `${pre}${text}${post}` - this.drawPrompt() - this._onDidChangeInput.fire(this._input) - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/session.ts b/vim-config/plugins/coc.nvim/src/list/session.ts deleted file mode 100644 index bcdd43d4..00000000 --- a/vim-config/plugins/coc.nvim/src/list/session.ts +++ /dev/null @@ -1,578 +0,0 @@ -import { Buffer, Neovim, Window } from '@chemzqm/neovim' -import debounce from 'debounce' -import { Disposable } from 'vscode-languageserver-protocol' -import { Mutex } from '../util/mutex' -import extensions from '../extensions' -import Highlighter from '../model/highligher' -import { IList, ListAction, ListContext, ListItem, ListMode, ListOptions, Matcher } from '../types' -import { disposeAll, wait } from '../util' -import workspace from '../workspace' -import window from '../window' -import ListConfiguration from './configuration' -import InputHistory from './history' -import Prompt from './prompt' -import UI from './ui' -import Worker from './worker' -const frames = ['โ ‹', 'โ ™', 'โ น', 'โ ธ', 'โ ผ', 'โ ด', 'โ ฆ', 'โ ง', 'โ ‡', 'โ '] -const logger = require('../util/logger')('list-session') - -/** - * Activated list session with UI and worker - */ -export default class ListSession { - public readonly history: InputHistory - public readonly ui: UI - public readonly worker: Worker - private cwd: string - private interval: NodeJS.Timer - private loadingFrame = '' - private timer: NodeJS.Timer - private hidden = false - private disposables: Disposable[] = [] - private savedHeight: number - private window: Window - private buffer: Buffer - private interactiveDebounceTime: number - private mutex: Mutex = new Mutex() - /** - * Original list arguments. - */ - private args: string[] = [] - constructor( - private nvim: Neovim, - private prompt: Prompt, - private list: IList, - public readonly listOptions: ListOptions, - private listArgs: string[] = [], - private config: ListConfiguration - ) { - this.ui = new UI(nvim, list.name, listOptions, config) - this.history = new InputHistory(prompt, list.name) - this.worker = new Worker(nvim, list, prompt, listOptions, { - interactiveDebounceTime: config.get('interactiveDebounceTime', 100), - extendedSearchMode: config.get('extendedSearchMode', true) - }) - this.interactiveDebounceTime = config.get('interactiveDebounceTime', 100) - let debouncedChangeLine = debounce(async () => { - let [previewing, currwin, lnum] = await nvim.eval('[coc#list#has_preview(),win_getid(),line(".")]') as [number, number, number] - if (previewing && currwin == this.winid) { - await this.doPreview(lnum - 1) - } - }, 50) - this.disposables.push({ - dispose: () => { - debouncedChangeLine.clear() - } - }) - this.ui.onDidChangeLine(debouncedChangeLine, null, this.disposables) - this.ui.onDidChangeLine(this.resolveItem, this, this.disposables) - this.ui.onDidLineChange(this.resolveItem, this, this.disposables) - let debounced = debounce(async () => { - let { autoPreview } = this.listOptions - if (!autoPreview) { - let [previewing, mode] = await nvim.eval('[coc#list#has_preview(),mode()]') as [number, string] - if (!previewing || mode != 'n') return - } - await this.doAction('preview') - }, 50) - this.disposables.push({ - dispose: () => { - debounced.clear() - } - }) - this.ui.onDidLineChange(debounced, null, this.disposables) - this.ui.onDidLineChange(() => { - this.updateStatus() - }, null, this.disposables) - this.ui.onDidOpen(async () => { - if (typeof this.list.doHighlight == 'function') { - this.list.doHighlight() - } - if (this.listOptions.first) { - await this.doAction() - } - }, null, this.disposables) - this.ui.onDidClose(async () => { - await this.hide() - }, null, this.disposables) - this.ui.onDidDoubleClick(async () => { - await this.doAction() - }, null, this.disposables) - this.worker.onDidChangeItems(async ({ items, reload, append, finished }) => { - let release = await this.mutex.acquire() - if (!this.hidden) { - try { - if (append) { - this.ui.appendItems(items) - } else { - let height = this.config.get('height', 10) - if (finished && !listOptions.interactive && listOptions.input.length == 0) { - height = Math.min(items.length, height) - } - await this.ui.drawItems(items, Math.max(1, height), reload) - } - } catch (e) { - nvim.echoError(e) - } - } - release() - }, null, this.disposables) - this.worker.onDidChangeLoading(loading => { - if (this.hidden) return - if (loading) { - this.interval = setInterval(() => { - let idx = Math.floor((new Date()).getMilliseconds() / 100) - this.loadingFrame = frames[idx] - this.updateStatus() - }, 100) - } else { - if (this.interval) { - this.loadingFrame = '' - clearInterval(this.interval) - this.interval = null - } - this.updateStatus() - } - }, null, this.disposables) - } - - public async start(args: string[]): Promise { - this.args = args - this.cwd = workspace.cwd - this.hidden = false - let { listOptions, listArgs } = this - let res = await this.nvim.eval('[win_getid(),bufnr("%"),winheight("%")]') - this.listArgs = listArgs - this.history.load(listOptions.input || '') - this.window = this.nvim.createWindow(res[0]) - this.buffer = this.nvim.createBuffer(res[1]) - this.savedHeight = res[2] - await this.worker.loadItems(this.context) - } - - public async reloadItems(): Promise { - if (!this.window) return - let bufnr = await this.nvim.call('winbufnr', [this.window.id]) - // can't reload since window not exists - if (bufnr == -1) return - this.buffer = this.nvim.createBuffer(bufnr) - await this.worker.loadItems(this.context, true) - } - - public async call(fname: string): Promise { - await this.nvim.call('coc#prompt#stop_prompt', ['list']) - let targets = await this.ui.getItems() - let context = { - name: this.name, - args: this.listArgs, - input: this.prompt.input, - winid: this.window?.id, - bufnr: this.buffer?.id, - targets - } - let res = await this.nvim.call(fname, [context]) - this.prompt.start() - return res - } - - public async chooseAction(): Promise { - let { nvim } = this - let { actions, defaultAction } = this.list - let names: string[] = actions.map(o => o.name) - let idx = names.indexOf(defaultAction) - if (idx != -1) { - names.splice(idx, 1) - names.unshift(defaultAction) - } - let shortcuts: Set = new Set() - let choices: string[] = [] - let invalids: string[] = [] - for (let name of names) { - let i = 0 - for (let ch of name) { - if (!shortcuts.has(ch)) { - shortcuts.add(ch) - choices.push(`${name.slice(0, i)}&${name.slice(i)}`) - break - } - i++ - } - if (i == name.length) { - invalids.push(name) - } - } - if (invalids.length) { - names = names.filter(s => !invalids.includes(s)) - } - await nvim.call('coc#prompt#stop_prompt', ['list']) - let n = await nvim.call('confirm', ['Choose action:', choices.join('\n')]) as number - await wait(10) - this.prompt.start() - if (n) await this.doAction(names[n - 1]) - if (invalids.length) { - nvim.echoError(`Can't create shortcut for actions: ${invalids.join(',')} of "${this.name}" list`) - } - } - - public async doAction(name?: string): Promise { - let { list } = this - name = name || list.defaultAction - let action = list.actions.find(o => o.name == name) - if (!action) { - window.showMessage(`Action ${name} not found`, 'error') - return - } - let items: ListItem[] - if (name == 'preview') { - let item = await this.ui.item - items = item ? [item] : [] - } else { - items = await this.ui.getItems() - } - if (items.length) await this.doItemAction(items, action) - } - - private async doPreview(index: number): Promise { - let item = this.ui.getItem(index) - let action = this.list.actions.find(o => o.name == 'preview') - if (!item || !action) return - await this.doItemAction([item], action) - } - - public async first(): Promise { - await this.doDefaultAction(0) - } - - public async last(): Promise { - await this.doDefaultAction(this.ui.length - 1) - } - - public async previous(): Promise { - await this.doDefaultAction(this.ui.index - 1) - } - - public async next(): Promise { - await this.doDefaultAction(this.ui.index + 1) - } - - private async doDefaultAction(index: number): Promise { - let { ui } = this - let item = ui.getItem(index) - if (!item) return - ui.index = index - await this.doItemAction([item], this.defaultAction) - await ui.echoMessage(item) - } - - /** - * list name - */ - public get name(): string { - return this.list.name - } - - /** - * Window id used by list. - * - * @returns {number | undefined} - */ - public get winid(): number | undefined { - return this.ui.winid - } - - public get length(): number { - return this.ui.length - } - - private get defaultAction(): ListAction { - let { defaultAction, actions } = this.list - let action = actions.find(o => o.name == defaultAction) - if (!action) throw new Error(`default action "${defaultAction}" not found`) - return action - } - - public async hide(): Promise { - if (this.hidden) return - let { nvim, interval } = this - if (interval) clearInterval(interval) - this.hidden = true - this.worker.stop() - this.history.add() - let { winid } = this.ui - this.ui.reset() - if (this.window && winid) { - await nvim.call('coc#list#hide', [this.window.id, this.savedHeight, winid]) - if (workspace.isVim) { - nvim.command('redraw', true) - // Needed for tabe action, don't know why. - await wait(10) - } - } - nvim.call('coc#prompt#stop_prompt', ['list'], true) - } - - public toggleMode(): void { - let mode: ListMode = this.prompt.mode == 'normal' ? 'insert' : 'normal' - this.prompt.mode = mode - this.listOptions.mode = mode - this.updateStatus() - } - - public stop(): void { - this.worker.stop() - } - - private async resolveItem(): Promise { - let index = this.ui.index - let item = this.ui.getItem(index) - if (!item || item.resolved) return - let { list } = this - if (typeof list.resolveItem == 'function') { - let resolved = await Promise.resolve(list.resolveItem(item)) - if (resolved && index == this.ui.index) { - await this.ui.updateItem(resolved, index) - } - } - } - - public async showHelp(): Promise { - await this.hide() - let { list, nvim } = this - if (!list) return - nvim.pauseNotification() - nvim.command(`tabe +setl\\ previewwindow [LIST HELP]`, true) - nvim.command('setl nobuflisted noswapfile buftype=nofile bufhidden=wipe', true) - await nvim.resumeNotification() - let hasOptions = list.options && list.options.length - let buf = await nvim.buffer - let highligher = new Highlighter() - highligher.addLine('NAME', 'Label') - highligher.addLine(` ${list.name} - ${list.description || ''}\n`) - highligher.addLine('SYNOPSIS', 'Label') - highligher.addLine(` :CocList [LIST OPTIONS] ${list.name}${hasOptions ? ' [ARGUMENTS]' : ''}\n`) - if (list.detail) { - highligher.addLine('DESCRIPTION', 'Label') - let lines = list.detail.split('\n').map(s => ' ' + s) - highligher.addLine(lines.join('\n') + '\n') - } - if (hasOptions) { - highligher.addLine('ARGUMENTS', 'Label') - highligher.addLine('') - for (let opt of list.options) { - highligher.addLine(opt.name, 'Special') - highligher.addLine(` ${opt.description}`) - highligher.addLine('') - } - highligher.addLine('') - } - let config = workspace.getConfiguration(`list.source.${list.name}`) - if (Object.keys(config).length) { - highligher.addLine('CONFIGURATIONS', 'Label') - highligher.addLine('') - let props = {} - extensions.all.forEach(extension => { - let { packageJSON } = extension - let { contributes } = packageJSON - if (!contributes) return - let { configuration } = contributes - if (configuration) { - let { properties } = configuration - if (properties) { - for (let key of Object.keys(properties)) { - props[key] = properties[key] - } - } - } - }) - for (let key of Object.keys(config)) { - let val = config[key] - let name = `list.source.${list.name}.${key}` - let description = props[name] && props[name].description ? props[name].description : key - highligher.addLine(` "${name}"`, 'MoreMsg') - highligher.addText(` - ${description}, current value: `) - highligher.addText(JSON.stringify(val), 'Special') - } - highligher.addLine('') - } - highligher.addLine('ACTIONS', 'Label') - highligher.addLine(` ${list.actions.map(o => o.name).join(', ')}`) - highligher.addLine('') - highligher.addLine(`see ':h coc-list-options' for available list options.`, 'Comment') - nvim.pauseNotification() - highligher.render(buf, 0, -1) - nvim.command('setl nomod', true) - nvim.command('setl nomodifiable', true) - nvim.command('normal! gg', true) - nvim.command('nnoremap q :bd!', true) - await nvim.resumeNotification() - } - - public switchMatcher(): void { - let { matcher, interactive } = this.listOptions - if (interactive) return - const list: Matcher[] = ['fuzzy', 'strict', 'regex'] - let idx = list.indexOf(matcher) + 1 - if (idx >= list.length) idx = 0 - this.listOptions.matcher = list[idx] - this.prompt.matcher = list[idx] - this.worker.drawItems() - } - - public updateStatus(): void { - let { ui, list, nvim } = this - if (!ui.winid) return - let buf = nvim.createBuffer(ui.bufnr) - let status = { - mode: this.prompt.mode.toUpperCase(), - args: this.args.join(' '), - name: list.name, - cwd: this.cwd, - loading: this.loadingFrame, - total: this.worker.length - } - nvim.pauseNotification() - buf.setVar('list_status', status, true) - nvim.command('redraws', true) - nvim.resumeNotification(false, true).logError() - } - - public get context(): ListContext { - let { winid } = this.ui - return { - options: this.listOptions, - args: this.listArgs, - input: this.prompt.input, - cwd: workspace.cwd, - window: this.window, - buffer: this.buffer, - listWindow: winid ? this.nvim.createWindow(winid) : undefined - } - } - - public onMouseEvent(key): Promise { - switch (key) { - case '': - return this.ui.onMouse('mouseDown') - case '': - return this.ui.onMouse('mouseDrag') - case '': - return this.ui.onMouse('mouseUp') - case '<2-LeftMouse>': - return this.ui.onMouse('doubleClick') - } - } - - public async doNumberSelect(ch: string): Promise { - if (!this.listOptions.numberSelect) return false - let code = ch.charCodeAt(0) - if (code >= 48 && code <= 57) { - let n = Number(ch) - if (n == 0) n = 10 - if (this.ui.length >= n) { - this.nvim.pauseNotification() - this.ui.setCursor(n, 0) - await this.nvim.resumeNotification() - await this.doAction() - return true - } - } - return false - } - - public jumpBack(): void { - let { window, nvim } = this - if (window) { - nvim.pauseNotification() - nvim.call('coc#prompt#stop_prompt', ['list'], true) - this.nvim.call('win_gotoid', [window.id], true) - nvim.resumeNotification(false, true).logError() - } - } - - public async resume(): Promise { - if (this.winid) await this.hide() - let res = await this.nvim.eval('[win_getid(),bufnr("%"),winheight("%")]') - this.hidden = false - this.window = this.nvim.createWindow(res[0]) - this.buffer = this.nvim.createBuffer(res[1]) - this.savedHeight = res[2] - this.prompt.start() - await this.ui.resume() - if (this.listOptions.autoPreview) { - await this.doAction('preview') - } - } - - private async doItemAction(items: ListItem[], action: ListAction): Promise { - let { noQuit } = this.listOptions - let { nvim } = this - let persistAction = action.persist === true || action.name == 'preview' - let persist = this.winid && (persistAction || noQuit) - try { - if (persist) { - if (!persistAction) { - nvim.pauseNotification() - nvim.call('coc#prompt#stop_prompt', ['list'], true) - nvim.call('win_gotoid', [this.context.window.id], true) - await nvim.resumeNotification() - } - } else { - await this.hide() - } - if (action.multiple) { - await Promise.resolve(action.execute(items, this.context)) - } else if (action.parallel) { - await Promise.all(items.map(item => Promise.resolve(action.execute(item, this.context)))) - } else { - for (let item of items) { - await Promise.resolve(action.execute(item, this.context)) - } - } - if (persist) { - this.ui.restoreWindow() - } - if (action.reload && persist) await this.worker.loadItems(this.context, true) - } catch (e) { - window.showMessage(e.message, 'error') - logger.error(`Error on action "${action.name}"`, e) - } - } - - public onInputChange(): void { - if (this.timer) clearTimeout(this.timer) - let len = this.worker.length - this.listOptions.input = this.prompt.input - // reload or filter items - if (this.listOptions.interactive) { - this.worker.stop() - this.timer = setTimeout(async () => { - await this.worker.loadItems(this.context) - }, this.interactiveDebounceTime) - } else if (len) { - let wait = Math.max(Math.min(Math.floor(len / 200), 300), 50) - this.timer = setTimeout(() => { - this.worker.drawItems() - }, wait) - } - } - - public dispose(): void { - if (!this.hidden) { - this.hidden = true - let { winid } = this.ui - this.ui.reset() - if (this.window && winid) { - this.nvim.call('coc#list#hide', [this.window.id, this.savedHeight, winid], true) - } - } - if (this.interval) { - clearInterval(this.interval) - } - if (this.timer) { - clearTimeout(this.timer) - } - disposeAll(this.disposables) - this.worker.dispose() - this.ui.dispose() - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/source/commands.ts b/vim-config/plugins/coc.nvim/src/list/source/commands.ts deleted file mode 100644 index 17247e2b..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/commands.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import commandManager from '../../commands' -import events from '../../events' -import Mru from '../../model/mru' -import { ListContext, ListItem } from '../../types' -import workspace from '../../workspace' -import BasicList from '../basic' -import { formatListItems, UnformattedListItem } from '../formatting' - -export default class CommandsList extends BasicList { - public defaultAction = 'run' - public description = 'registered commands of coc.nvim' - public readonly name = 'commands' - private mru: Mru - - constructor(nvim: Neovim) { - super(nvim) - this.mru = workspace.createMru('commands') - this.addAction('run', async item => { - let { cmd } = item.data - await events.fire('Command', [cmd]) - commandManager.executeCommand(cmd).logError() - await commandManager.addRecent(cmd) - }) - this.addAction('append', async item => { - let { cmd } = item.data - await nvim.feedKeys(`:CocCommand ${cmd} `, 'n', false) - }) - } - - public async loadItems(_context: ListContext): Promise { - let items: UnformattedListItem[] = [] - let mruList = await this.mru.load() - let { commandList, onCommandList, titles } = commandManager - let ids = commandList.map(c => c.id).concat(onCommandList) - for (const id of [...new Set(ids)]) { - items.push({ - label: [id, ...(titles.get(id) ? [titles.get(id)] : [])], - filterText: id, - data: { cmd: id, score: score(mruList, id) } - }) - } - items.sort((a, b) => b.data.score - a.data.score) - return formatListItems(this.alignColumns, items) - } - - public doHighlight(): void { - let { nvim } = this - nvim.pauseNotification() - nvim.command('syntax match CocCommandsTitle /\\t.*$/ contained containedin=CocCommandsLine', true) - nvim.command('highlight default link CocCommandsTitle Comment', true) - void nvim.resumeNotification(false, true) - } -} - -function score(list: string[], key: string): number { - let idx = list.indexOf(key) - return idx == -1 ? -1 : list.length - idx -} diff --git a/vim-config/plugins/coc.nvim/src/list/source/diagnostics.ts b/vim-config/plugins/coc.nvim/src/list/source/diagnostics.ts deleted file mode 100644 index ef66ba29..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/diagnostics.ts +++ /dev/null @@ -1,49 +0,0 @@ -import path from 'path' -import diagnosticManager from '../../diagnostic/manager' -import { ListContext, ListItem } from '../../types' -import LocationList from './location' -import { isParentFolder } from '../../util/fs' -import { formatListItems, formatPath, PathFormatting, UnformattedListItem } from '../formatting' -const logger = require('../../util/logger')('list-symbols') - -export default class DiagnosticsList extends LocationList { - public readonly defaultAction = 'open' - public readonly description = 'diagnostics of current workspace' - public name = 'diagnostics' - - public async loadItems(context: ListContext): Promise { - let list = diagnosticManager.getDiagnosticList() - let { cwd } = context - const config = this.getConfig() - const shouldIncludeCode = config.get('includeCode', true) - const pathFormat = config.get('pathFormat', "full") - const unformatted: UnformattedListItem[] = list.map(item => { - const file = isParentFolder(cwd, item.file) ? path.relative(cwd, item.file) : item.file - const formattedPath = formatPath(pathFormat, file) - const formattedPosition = pathFormat !== "hidden" ? [`${formattedPath}:${item.lnum}`] : [] - const code = shouldIncludeCode ? [`[${item.source}${item.code ? '' : ']'}`, item.code ? `${item.code}]` : ''] : [] - return { - label: [...formattedPosition, ...code, item.severity, item.message], - location: item.location, - } - }) - return formatListItems(this.alignColumns, unformatted) - } - - public doHighlight(): void { - let { nvim } = this - nvim.pauseNotification() - nvim.command('syntax match CocDiagnosticsFile /\\v^\\s*\\S+/ contained containedin=CocDiagnosticsLine', true) - nvim.command('syntax match CocDiagnosticsError /\\tError\\s*\\t/ contained containedin=CocDiagnosticsLine', true) - nvim.command('syntax match CocDiagnosticsWarning /\\tWarning\\s*\\t/ contained containedin=CocDiagnosticsLine', true) - nvim.command('syntax match CocDiagnosticsInfo /\\tInformation\\s*\\t/ contained containedin=CocDiagnosticsLine', true) - nvim.command('syntax match CocDiagnosticsHint /\\tHint\\s*\\t/ contained containedin=CocDiagnosticsLine', true) - nvim.command('highlight default link CocDiagnosticsFile Comment', true) - nvim.command('highlight default link CocDiagnosticsError CocErrorSign', true) - nvim.command('highlight default link CocDiagnosticsWarning CocWarningSign', true) - nvim.command('highlight default link CocDiagnosticsInfo CocInfoSign', true) - nvim.command('highlight default link CocDiagnosticsHint CocHintSign', true) - void nvim.resumeNotification(false, true) - } -} - diff --git a/vim-config/plugins/coc.nvim/src/list/source/extensions.ts b/vim-config/plugins/coc.nvim/src/list/source/extensions.ts deleted file mode 100644 index 94843c47..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/extensions.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import fs from 'fs-extra' -import os from 'os' -import path from 'path' -import { URI } from 'vscode-uri' -import extensions from '../../extensions' -import { ListContext, ListItem } from '../../types' -import { wait } from '../../util' -import workspace from '../../workspace' -import window from '../../window' -import BasicList from '../basic' -import { formatListItems, UnformattedListItem } from '../formatting' -const logger = require('../../util/logger')('list-extensions') - -export default class ExtensionList extends BasicList { - public defaultAction = 'toggle' - public description = 'manage coc extensions' - public name = 'extensions' - - constructor(nvim: Neovim) { - super(nvim) - this.addAction('toggle', async item => { - let { id, state } = item.data - if (state == 'disabled') return - if (state == 'activated') { - await extensions.deactivate(id) - } else { - await extensions.activate(id) - } - await wait(100) - }, { persist: true, reload: true, parallel: true }) - - this.addAction('configuration', async item => { - let { root } = item.data - let jsonFile = path.join(root, 'package.json') - if (fs.existsSync(jsonFile)) { - let lines = fs.readFileSync(jsonFile, 'utf8').split(/\r?\n/) - let idx = lines.findIndex(s => s.includes('"contributes"')) - await workspace.jumpTo(URI.file(jsonFile).toString(), { line: idx == -1 ? 0 : idx, character: 0 }) - } - }) - - this.addAction('open', async item => { - let { root } = item.data - if (workspace.env.isiTerm) { - nvim.call('coc#util#iterm_open', [root], true) - } else { - nvim.call('coc#util#open_url', [root], true) - } - }) - - this.addAction('disable', async item => { - let { id, state } = item.data - if (state !== 'disabled') await extensions.toggleExtension(id) - }, { persist: true, reload: true, parallel: true }) - - this.addAction('enable', async item => { - let { id, state } = item.data - if (state == 'disabled') await extensions.toggleExtension(id) - }, { persist: true, reload: true, parallel: true }) - - this.addAction('lock', async item => { - let { id } = item.data - await extensions.toggleLock(id) - }, { persist: true, reload: true }) - - this.addAction('help', async item => { - let { root } = item.data - let files = await fs.readdir(root) - let file = files.find(f => /^readme/i.test(f)) - if (file) await workspace.callAsync('coc#util#jump', ['edit', path.join(root, file)]) - }) - - this.addAction('reload', async item => { - let { id } = item.data - await extensions.reloadExtension(id) - }, { persist: true, reload: true }) - - this.addAction('fix', async item => { - let { root, isLocal } = item.data - let { npm } = extensions - if (isLocal) { - window.showMessage(`Can't fix for local extension.`, 'warning') - return - } - if (!npm) return - let folder = path.join(root, 'node_modules') - if (fs.existsSync(folder)) { - fs.removeSync(folder) - } - let terminal = await workspace.createTerminal({ - cwd: root - }) - let shown = await terminal.show(false) - if (!shown) return - workspace.nvim.command(`startinsert`, true) - terminal.sendText(`${npm} install --production --ignore-scripts --no-lockfile`, true) - }) - - this.addMultipleAction('uninstall', async items => { - let ids = [] - for (let item of items) { - if (item.data.isLocal) continue - ids.push(item.data.id) - } - extensions.uninstallExtension(ids).catch(e => { - logger.error(e) - }) - }) - } - - public async loadItems(_context: ListContext): Promise { - let items: UnformattedListItem[] = [] - let list = await extensions.getExtensionStates() - let lockedList = await extensions.getLockedList() - for (let stat of list) { - let prefix = '+' - if (stat.state == 'disabled') { - prefix = '-' - } else if (stat.state == 'activated') { - prefix = '*' - } else if (stat.state == 'unknown') { - prefix = '?' - } - let root = await this.nvim.call('resolve', stat.root) - let locked = lockedList.includes(stat.id) - items.push({ - label: [`${prefix} ${stat.id}${locked ? ' ๎‚ข' : ''}`, ...(stat.isLocal ? ['[RTP]'] : []), stat.version, root.replace(os.homedir(), '~')], - filterText: stat.id, - data: { - id: stat.id, - root, - state: stat.state, - isLocal: stat.isLocal, - priority: getPriority(stat.state) - } - }) - } - items.sort((a, b) => { - if (a.data.priority != b.data.priority) { - return b.data.priority - a.data.priority - } - return b.data.id - a.data.id ? 1 : -1 - }) - return formatListItems(this.alignColumns, items) - } - - public doHighlight(): void { - let { nvim } = this - nvim.pauseNotification() - nvim.command('syntax match CocExtensionsActivited /\\v^\\*/ contained containedin=CocExtensionsLine', true) - nvim.command('syntax match CocExtensionsLoaded /\\v^\\+/ contained containedin=CocExtensionsLine', true) - nvim.command('syntax match CocExtensionsDisabled /\\v^-/ contained containedin=CocExtensionsLine', true) - nvim.command('syntax match CocExtensionsName /\\v%3c\\S+/ contained containedin=CocExtensionsLine', true) - nvim.command('syntax match CocExtensionsRoot /\\v\\t[^\\t]*$/ contained containedin=CocExtensionsLine', true) - nvim.command('syntax match CocExtensionsLocal /\\v\\[RTP\\]/ contained containedin=CocExtensionsLine', true) - nvim.command('highlight default link CocExtensionsActivited Special', true) - nvim.command('highlight default link CocExtensionsLoaded Normal', true) - nvim.command('highlight default link CocExtensionsDisabled Comment', true) - nvim.command('highlight default link CocExtensionsName String', true) - nvim.command('highlight default link CocExtensionsLocal MoreMsg', true) - nvim.command('highlight default link CocExtensionsRoot Comment', true) - nvim.resumeNotification().catch(_e => { - // noop - }) - } -} - -function getPriority(stat: string): number { - switch (stat) { - case 'unknown': - return 2 - case 'activated': - return 1 - case 'disabled': - return -1 - default: - return 0 - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/source/folders.ts b/vim-config/plugins/coc.nvim/src/list/source/folders.ts deleted file mode 100644 index b2ea073f..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/folders.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import path from 'path' -import { URI } from 'vscode-uri' -import fs from 'fs-extra' -import { ListContext, ListItem } from '../../types' -import { statAsync } from '../../util/fs' -import workspace from '../../workspace' -import window from '../../window' -import BasicList from '../basic' - -export default class FoldList extends BasicList { - public defaultAction = 'edit' - public description = 'list of current workspace folders' - public name = 'folders' - - constructor(nvim: Neovim) { - super(nvim) - - this.addAction('edit', async item => { - let newPath = await nvim.call('input', ['Folder: ', item.label, 'dir']) - let stat = await statAsync(newPath) - if (!stat || !stat.isDirectory()) { - window.showMessage(`invalid path: ${newPath}`, 'error') - return - } - workspace.renameWorkspaceFolder(item.label, newPath) - }) - - this.addAction('delete', async item => { - workspace.removeWorkspaceFolder(item.label) - }, { reload: true, persist: true }) - - this.addAction('newfile', async item => { - let file = await window.requestInput('File name', item.label + '/') - let dir = path.dirname(file) - let stat = await statAsync(dir) - if (!stat || !stat.isDirectory()) { - fs.mkdirpSync(dir) - } - await workspace.createFile(file, { overwrite: false, ignoreIfExists: true }) - await this.jumpTo(URI.file(file).toString()) - }) - } - - public async loadItems(_context: ListContext): Promise { - return workspace.folderPaths.map(p => ({ label: p })) - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/source/links.ts b/vim-config/plugins/coc.nvim/src/list/source/links.ts deleted file mode 100644 index 02eee7c8..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/links.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import languages from '../../languages' -import workspace from '../../workspace' -import path from 'path' -import { ListContext, ListItem } from '../../types' -import BasicList from '../basic' -import { DocumentLink, Location } from 'vscode-languageserver-types' -import { URI } from 'vscode-uri' -import { isParentFolder } from '../../util/fs' -import { CancellationToken } from 'vscode-languageserver-protocol' - -export default class LinksList extends BasicList { - public defaultAction = 'open' - public description = 'links of current buffer' - public name = 'links' - - constructor(nvim: Neovim) { - super(nvim) - - this.addAction('open', async item => { - let { target } = item.data - let uri = URI.parse(target) - if (uri.scheme.startsWith('http')) { - await nvim.call('coc#util#open_url', target) - } else { - await workspace.jumpTo(target) - } - }) - - this.addAction('jump', async item => { - let { location } = item.data - await workspace.jumpTo(location.uri, location.range.start) - }) - } - - public async loadItems(context: ListContext, token: CancellationToken): Promise { - let buf = await context.window.buffer - let doc = workspace.getDocument(buf.id) - if (!doc) return null - let items: ListItem[] = [] - let links = await languages.getDocumentLinks(doc.textDocument, token) - if (links == null) { - throw new Error('Links provider not found.') - } - let res: DocumentLink[] = [] - for (let link of links) { - if (link.target) { - items.push({ - label: formatUri(link.target), - data: { - target: link.target, - location: Location.create(doc.uri, link.range) - } - }) - } else { - link = await languages.resolveDocumentLink(link) - if (link.target) { - items.push({ - label: formatUri(link.target), - data: { - target: link.target, - location: Location.create(doc.uri, link.range) - } - }) - } - res.push(link) - } - } - return items - } -} - -function formatUri(uri: string): string { - if (!uri.startsWith('file:')) return uri - let filepath = URI.parse(uri).fsPath - return isParentFolder(workspace.cwd, filepath) ? path.relative(workspace.cwd, filepath) : filepath -} diff --git a/vim-config/plugins/coc.nvim/src/list/source/lists.ts b/vim-config/plugins/coc.nvim/src/list/source/lists.ts deleted file mode 100644 index ad15fd48..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/lists.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { IList, ListContext, ListItem } from '../../types' -import BasicList from '../basic' -import Mru from '../../model/mru' -import { formatListItems, UnformattedListItem } from '../formatting' - -export default class LinksList extends BasicList { - public readonly name = 'lists' - public readonly defaultAction = 'open' - public readonly description = 'registered lists of coc.nvim' - private mru: Mru = new Mru('lists') - - constructor(nvim: Neovim, private readonly listMap: Map) { - super(nvim) - - this.addAction('open', async item => { - let { name } = item.data - await this.mru.add(name) - await nvim.command(`CocList ${name}`) - }) - } - - public async loadItems(_context: ListContext): Promise { - let items: UnformattedListItem[] = [] - let mruList = await this.mru.load() - for (let list of this.listMap.values()) { - if (list.name == 'lists') continue - items.push({ - label: [list.name, ...(list.description ? [list.description] : [])], - data: { - name: list.name, - interactive: list.interactive, - score: score(mruList, list.name) - } - }) - } - items.sort((a, b) => b.data.score - a.data.score) - return formatListItems(this.alignColumns, items) - } - - public doHighlight(): void { - let { nvim } = this - nvim.pauseNotification() - nvim.command('syntax match CocListsDesc /\\t.*$/ contained containedin=CocListsLine', true) - nvim.command('highlight default link CocListsDesc Comment', true) - nvim.resumeNotification().catch(_e => { - // noop - }) - } -} - -function score(list: string[], key: string): number { - let idx = list.indexOf(key) - return idx == -1 ? -1 : list.length - idx -} diff --git a/vim-config/plugins/coc.nvim/src/list/source/location.ts b/vim-config/plugins/coc.nvim/src/list/source/location.ts deleted file mode 100644 index 15f52e8a..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/location.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Location, Range } from 'vscode-languageserver-types' -import path from 'path' -import { ListContext, ListItem, QuickfixItem, AnsiHighlight } from '../../types' -import BasicList from '../basic' -import workspace from '../../workspace' -import { URI } from 'vscode-uri' -import { isParentFolder } from '../../util/fs' -import { CancellationToken } from 'vscode-languageserver-protocol' -import { byteLength } from '../../util/string' -const logger = require('../../util/logger')('list-location') - -export default class LocationList extends BasicList { - public defaultAction = 'open' - public description = 'show locations saved by g:coc_jump_locations variable' - public name = 'location' - - constructor(nvim: Neovim) { - super(nvim) - this.addLocationActions() - } - - public async loadItems(context: ListContext, token: CancellationToken): Promise { - // filename, lnum, col, text, type - let locs = await this.nvim.getVar('coc_jump_locations') as QuickfixItem[] - if (token.isCancellationRequested) return [] - locs = locs || [] - locs.forEach(loc => { - if (!loc.uri) { - let fullpath = path.isAbsolute(loc.filename) ? loc.filename : path.join(context.cwd, loc.filename) - loc.uri = URI.file(fullpath).toString() - } - if (!loc.bufnr && workspace.getDocument(loc.uri) != null) { - loc.bufnr = workspace.getDocument(loc.uri).bufnr - } - if (!loc.range) { - let { lnum, col } = loc - loc.range = Range.create(lnum - 1, col - 1, lnum - 1, col - 1) - } else { - loc.lnum = loc.lnum || loc.range.start.line + 1 - loc.col = loc.col || loc.range.start.character + 1 - } - }) - let bufnr = context.buffer.id - let ignoreFilepath = locs.every(o => o.bufnr && bufnr && o.bufnr == bufnr) - let items: ListItem[] = locs.map(loc => { - let filename = ignoreFilepath ? '' : loc.filename - let filterText = `${filename}${loc.text.trim()}` - if (path.isAbsolute(filename)) { - filename = isParentFolder(context.cwd, filename) ? path.relative(context.cwd, filename) : filename - } - let pre = `${filename} |${loc.type ? loc.type + ' ' : ''}${loc.lnum} col ${loc.col}| ` - let highlight: AnsiHighlight - if (loc.range && loc.range.start.line == loc.range.end.line) { - let start = byteLength(pre) + byteLength(loc.text.slice(0, loc.range.start.character)) - let end = byteLength(pre) + byteLength(loc.text.slice(0, loc.range.end.character)) - highlight = { hlGroup: 'Search', span: [start, end] } - } - let label = pre + loc.text - return { - label, - location: Location.create(loc.uri, loc.range), - filterText, - ansiHighlights: highlight ? [highlight] : undefined - } as ListItem - }) - return items - } - - public doHighlight(): void { - let { nvim } = this - nvim.pauseNotification() - nvim.command('syntax match CocLocationName /\\v^[^|]+/ contained containedin=CocLocationLine', true) - nvim.command('syntax match CocLocationPosition /\\v\\|\\w*\\s?\\d+\\scol\\s\\d+\\|/ contained containedin=CocLocationLine', true) - nvim.command('syntax match CocLocationError /Error/ contained containedin=CocLocationPosition', true) - nvim.command('syntax match CocLocationWarning /Warning/ contained containedin=CocLocationPosition', true) - nvim.command('highlight default link CocLocationName Directory', true) - nvim.command('highlight default link CocLocationPosition LineNr', true) - nvim.command('highlight default link CocLocationError Error', true) - nvim.command('highlight default link CocLocationWarning WarningMsg', true) - nvim.resumeNotification().catch(_e => { - // noop - }) - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/source/outline.ts b/vim-config/plugins/coc.nvim/src/list/source/outline.ts deleted file mode 100644 index 0e028088..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/outline.ts +++ /dev/null @@ -1,160 +0,0 @@ -import path from 'path' -import { DocumentSymbol, Location, Range, SymbolInformation } from 'vscode-languageserver-types' -import { URI } from 'vscode-uri' -import which from 'which' -import languages from '../../languages' -import Document from '../../model/document' -import { ListContext, ListItem, ListArgument } from '../../types' -import { runCommand } from '../../util' -import { writeFile } from '../../util/fs' -import workspace from '../../workspace' -import LocationList from './location' -import { getSymbolKind } from '../../util/convert' -import { CancellationToken } from 'vscode-languageserver-protocol' -import { formatListItems, UnformattedListItem } from '../formatting' -const logger = require('../../util/logger')('list-symbols') - -function getFilterText(s: DocumentSymbol | SymbolInformation, kind: string | null): string { - return `${s.name}${kind ? ` ${kind}` : ''}` -} - -export default class Outline extends LocationList { - public readonly description = 'symbols of current document' - public name = 'outline' - public options: ListArgument[] = [{ - name: '-k, -kind KIND', - hasValue: true, - description: 'filters also by kind', - }] - - public async loadItems(context: ListContext, token: CancellationToken): Promise { - let buf = await context.window.buffer - let document = workspace.getDocument(buf.id) - if (!document) return null - let config = this.getConfig() - let ctagsFilestypes = config.get('ctagsFilestypes', []) - let symbols: DocumentSymbol[] | SymbolInformation[] | null - let args = this.parseArguments(context.args) - if (!ctagsFilestypes.includes(document.filetype)) { - symbols = await languages.getDocumentSymbol(document.textDocument, token) - } - if (token.isCancellationRequested) return [] - if (!symbols) return await this.loadCtagsSymbols(document) - if (symbols.length == 0) return [] - let filterKind = args.kind ? (args.kind as string).toLowerCase() : null - let items: UnformattedListItem[] = [] - let isSymbols = !symbols[0].hasOwnProperty('location') - if (isSymbols) { - // eslint-disable-next-line no-inner-declarations - function addSymbols(symbols: DocumentSymbol[], level = 0): void { - symbols.sort(sortSymbols) - for (let s of symbols) { - let kind = getSymbolKind(s.kind) - let location = Location.create(document.uri, s.selectionRange) - items.push({ - label: [`${'| '.repeat(level)}${s.name}`, `[${kind}]`, `${s.range.start.line + 1}`], - filterText: getFilterText(s, args.kind == '' ? kind : null), - location, - data: { kind } - }) - if (s.children && s.children.length) { - addSymbols(s.children, level + 1) - } - } - } - addSymbols(symbols as DocumentSymbol[]) - if (filterKind) { - items = items.filter(o => o.data.kind.toLowerCase().indexOf(filterKind) == 0) - } - } else { - (symbols as SymbolInformation[]).sort((a, b) => { - let sa = a.location.range.start - let sb = b.location.range.start - let d = sa.line - sb.line - return d == 0 ? sa.character - sb.character : d - }) - for (let s of symbols as SymbolInformation[]) { - let kind = getSymbolKind(s.kind) - if (s.name.endsWith(') callback')) continue - if (filterKind && !kind.toLowerCase().startsWith(filterKind)) { - continue - } - if (s.location.uri === undefined) { - s.location.uri = document.uri - } - items.push({ - label: [s.name, `[${kind}]`, `${s.location.range.start.line + 1}`], - filterText: getFilterText(s, args.kind == '' ? kind : null), - location: s.location - }) - } - } - return formatListItems(this.alignColumns, items) - } - - public doHighlight(): void { - let { nvim } = this - nvim.pauseNotification() - nvim.command('syntax match CocOutlineName /\\v\\s?[^\\t]+\\s/ contained containedin=CocOutlineLine', true) - nvim.command('syntax match CocOutlineIndentLine /\\v\\|/ contained containedin=CocOutlineLine,CocOutlineName', true) - nvim.command('syntax match CocOutlineKind /\\[\\w\\+\\]/ contained containedin=CocOutlineLine', true) - nvim.command('syntax match CocOutlineLine /\\d\\+$/ contained containedin=CocOutlineLine', true) - nvim.command('highlight default link CocOutlineName Normal', true) - nvim.command('highlight default link CocOutlineIndentLine Comment', true) - nvim.command('highlight default link CocOutlineKind Typedef', true) - nvim.command('highlight default link CocOutlineLine Comment', true) - nvim.resumeNotification(false, true).logError() - } - - public async loadCtagsSymbols(document: Document): Promise { - if (!which.sync('ctags', { nothrow: true })) { - return [] - } - let uri = URI.parse(document.uri) - let extname = path.extname(uri.fsPath) - let content = '' - let tempname = await this.nvim.call('tempname') - let filepath = `${tempname}.${extname}` - let escaped = await this.nvim.call('fnameescape', filepath) - await writeFile(escaped, document.getDocumentContent()) - try { - content = await runCommand(`ctags -f - --excmd=number --language-force=${document.filetype} ${escaped}`) - } catch (e) { - // noop - } - if (!content.trim().length) { - content = await runCommand(`ctags -f - --excmd=number ${escaped}`) - } - content = content.trim() - if (!content) return [] - let lines = content.split(/\r?\n/) - let items: ListItem[] = [] - for (let line of lines) { - let parts = line.split('\t') - if (parts.length < 4) continue - let lnum = Number(parts[2].replace(/;"$/, '')) - let text = document.getline(lnum - 1) - if (!text) continue - let idx = text.indexOf(parts[0]) - let start = idx == -1 ? 0 : idx - let range: Range = Range.create(lnum - 1, start, lnum - 1, start + parts[0].length) - items.push({ - label: `${parts[0]} [${parts[3]}] ${lnum}`, - filterText: parts[0], - location: Location.create(document.uri, range), - data: { line: lnum } - }) - } - items.sort((a, b) => a.data.line - b.data.line) - return items - } -} - -function sortSymbols(a: DocumentSymbol, b: DocumentSymbol): number { - let ra = a.selectionRange - let rb = b.selectionRange - if (ra.start.line != rb.start.line) { - return ra.start.line - rb.start.line - } - return ra.start.character - rb.start.character -} diff --git a/vim-config/plugins/coc.nvim/src/list/source/services.ts b/vim-config/plugins/coc.nvim/src/list/source/services.ts deleted file mode 100644 index 49f8f0a5..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/services.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import services from '../../services' -import { ListContext, ListItem } from '../../types' -import BasicList from '../basic' -import { wait } from '../../util' -import { formatListItems } from '../formatting' - -export default class ServicesList extends BasicList { - public defaultAction = 'toggle' - public description = 'registered services of coc.nvim' - public name = 'services' - - constructor(nvim: Neovim) { - super(nvim) - - this.addAction('toggle', async item => { - let { id } = item.data - await services.toggle(id) - await wait(100) - }, { persist: true, reload: true }) - } - - public async loadItems(_context: ListContext): Promise { - let stats = services.getServiceStats() - stats.sort((a, b) => a.id > b.id ? -1 : 1) - return formatListItems(this.alignColumns, stats.map(stat => { - let prefix = stat.state == 'running' ? '*' : ' ' - return { - label: [prefix, stat.id, `[${stat.state}]`, stat.languageIds.join(', ')], - data: { id: stat.id } - } - })) - } - - public doHighlight(): void { - let { nvim } = this - nvim.pauseNotification() - nvim.command('syntax match CocServicesPrefix /\\v^./ contained containedin=CocServicesLine', true) - nvim.command('syntax match CocServicesName /\\v%3c\\S+/ contained containedin=CocServicesLine', true) - nvim.command('syntax match CocServicesStat /\\v\\t\\[\\w+\\]/ contained containedin=CocServicesLine', true) - nvim.command('syntax match CocServicesLanguages /\\v(\\])@<=.*$/ contained containedin=CocServicesLine', true) - nvim.command('highlight default link CocServicesPrefix Special', true) - nvim.command('highlight default link CocServicesName Type', true) - nvim.command('highlight default link CocServicesStat Statement', true) - nvim.command('highlight default link CocServicesLanguages Comment', true) - nvim.resumeNotification().catch(_e => { - // noop - }) - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/source/sources.ts b/vim-config/plugins/coc.nvim/src/list/source/sources.ts deleted file mode 100644 index 1448c3c5..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/sources.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Location, Range } from 'vscode-languageserver-types' -import { URI } from 'vscode-uri' -import sources from '../../sources' -import workspace from '../../workspace' -import { ListContext, ListItem } from '../../types' -import BasicList from '../basic' -const logger = require('../../util/logger')('list-sources') - -export default class SourcesList extends BasicList { - public readonly defaultAction = 'toggle' - public readonly description = 'registered completion sources' - public readonly name = 'sources' - - constructor(nvim: Neovim) { - super(nvim) - - this.addAction('toggle', async item => { - let { name } = item.data - sources.toggleSource(name) - }, { persist: true, reload: true }) - - this.addAction('refresh', async item => { - let { name } = item.data - await sources.refresh(name) - }, { persist: true, reload: true }) - - this.addAction('open', async item => { - let { location } = item - if (location) await this.jumpTo(location) - }) - } - - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public async loadItems(context: ListContext): Promise { - let stats = sources.sourceStats() - let filetype = await context.buffer.getOption('filetype') as string - let map = workspace.env.disabledSources - let disables = map ? map[filetype] || [] : [] - stats.sort((a, b) => { - if (a.type != b.type) return a.type < b.type ? 1 : -1 - return a.name > b.name ? -1 : 1 - }) - return stats.map(stat => { - let prefix = stat.disabled ? ' ' : '*' - if (disables && disables.includes(stat.name)) { - prefix = '-' - } - let location: Location - if (stat.filepath) { - location = Location.create(URI.file(stat.filepath).toString(), Range.create(0, 0, 0, 0)) - } - return { - label: `${prefix} ${fixWidth(stat.name, 22)} ${fixWidth('[' + stat.shortcut + ']', 10)} ${fixWidth(stat.triggerCharacters.join(''), 10)} ${fixWidth(stat.priority.toString(), 3)} ${stat.filetypes.join(',')}`, - location, - data: { name: stat.name } - } - }) - } - - public doHighlight(): void { - let { nvim } = this - nvim.pauseNotification() - nvim.command('syntax match CocSourcesPrefix /\\v^./ contained containedin=CocSourcesLine', true) - nvim.command('syntax match CocSourcesName /\\v%3c\\S+/ contained containedin=CocSourcesLine', true) - nvim.command('syntax match CocSourcesType /\\v%25v.*%36v/ contained containedin=CocSourcesLine', true) - nvim.command('syntax match CocSourcesPriority /\\v%46v.*%50v/ contained containedin=CocSourcesLine', true) - nvim.command('syntax match CocSourcesFileTypes /\\v\\S+$/ contained containedin=CocSourcesLine', true) - nvim.command('highlight default link CocSourcesPrefix Special', true) - nvim.command('highlight default link CocSourcesName Type', true) - nvim.command('highlight default link CocSourcesPriority Number', true) - nvim.command('highlight default link CocSourcesFileTypes Comment', true) - nvim.command('highlight default link CocSourcesType Statement', true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } -} - -function fixWidth(str: string, width: number): string { - if (str.length > width) { - return str.slice(0, width - 1) + '.' - } - return str + ' '.repeat(width - str.length) -} diff --git a/vim-config/plugins/coc.nvim/src/list/source/symbols.ts b/vim-config/plugins/coc.nvim/src/list/source/symbols.ts deleted file mode 100644 index 6ab2a59c..00000000 --- a/vim-config/plugins/coc.nvim/src/list/source/symbols.ts +++ /dev/null @@ -1,105 +0,0 @@ -import path from 'path' -import minimatch from 'minimatch' -import { SymbolInformation, SymbolKind } from 'vscode-languageserver-types' -import { URI } from 'vscode-uri' -import languages from '../../languages' -import { ListContext, ListItem } from '../../types' -import workspace from '../../workspace' -import LocationList from './location' -import { getSymbolKind } from '../../util/convert' -import { isParentFolder } from '../../util/fs' -import { score } from '../../util/fzy' -import { CancellationToken, CancellationTokenSource } from 'vscode-languageserver-protocol' -import { formatListItems, UnformattedListItem } from '../formatting' -const logger = require('../../util/logger')('list-symbols') - -export default class Symbols extends LocationList { - public readonly interactive = true - public readonly description = 'search workspace symbols' - public readonly detail = 'Symbols list is provided by server, it works on interactive mode only.' - private cwd: string - public name = 'symbols' - public options = [{ - name: '-k, -kind KIND', - description: 'Filter symbols by kind.', - hasValue: true - }] - - public async loadItems(context: ListContext, token: CancellationToken): Promise { - let { input } = context - this.cwd = context.cwd - let args = this.parseArguments(context.args) - let filterKind = args.kind ? (args.kind as string).toLowerCase() : '' - if (!context.options.interactive) { - throw new Error('Symbols only works on interactive mode') - } - let symbols = await languages.getWorkspaceSymbols(input, token) - if (!symbols) { - throw new Error('No workspace symbols provider registered') - } - let config = this.getConfig() - let excludes = config.get('excludes', []) - let items: UnformattedListItem[] = [] - for (let s of symbols) { - let kind = getSymbolKind(s.kind) - if (filterKind && kind.toLowerCase() != filterKind) { - continue - } - let file = URI.parse(s.location.uri).fsPath - if (isParentFolder(workspace.cwd, file)) { - file = path.relative(workspace.cwd, file) - } - if (excludes.some(p => minimatch(file, p))) { - continue - } - items.push({ - label: [s.name, `[${kind}]`, file], - filterText: `${s.name}`, - location: s.location, - data: { original: s, kind: s.kind, file, score: score(input, s.name) } - }) - } - items.sort((a, b) => { - if (a.data.score != b.data.score) { - return b.data.score - a.data.score - } - if (a.data.kind != b.data.kind) { - return a.data.kind - b.data.kind - } - return a.data.file.length - b.data.file.length - }) - return formatListItems(this.alignColumns, items) - } - - public async resolveItem(item: ListItem): Promise { - let s = item.data.original - if (!s) return null - let tokenSource = new CancellationTokenSource() - let resolved = await languages.resolveWorkspaceSymbol(s, tokenSource.token) - if (!resolved) return null - let kind = getSymbolKind(resolved.kind) - let file = URI.parse(resolved.location.uri).fsPath - if (isParentFolder(this.cwd, file)) { - file = path.relative(this.cwd, file) - } - return { - label: `${s.name} [${kind}]\t${file}`, - filterText: `${s.name}`, - location: s.location - } - } - - public doHighlight(): void { - let { nvim } = this - nvim.pauseNotification() - nvim.command('syntax match CocSymbolsName /\\v^\\s*\\S+/ contained containedin=CocSymbolsLine', true) - nvim.command('syntax match CocSymbolsKind /\\[\\w\\+\\]\\s*\\t/ contained containedin=CocSymbolsLine', true) - nvim.command('syntax match CocSymbolsFile /\\S\\+$/ contained containedin=CocSymbolsLine', true) - nvim.command('highlight default link CocSymbolsName Normal', true) - nvim.command('highlight default link CocSymbolsKind Typedef', true) - nvim.command('highlight default link CocSymbolsFile Comment', true) - nvim.resumeNotification().catch(_e => { - // noop - }) - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/ui.ts b/vim-config/plugins/coc.nvim/src/list/ui.ts deleted file mode 100644 index c6b17b28..00000000 --- a/vim-config/plugins/coc.nvim/src/list/ui.ts +++ /dev/null @@ -1,429 +0,0 @@ -import { Buffer, Neovim, Window } from '@chemzqm/neovim' -import debounce from 'debounce' -import { Disposable, Emitter, Event } from 'vscode-languageserver-protocol' -import events from '../events' -import { ListItem, ListItemWithHighlights, ListOptions } from '../types' -import { disposeAll } from '../util' -import workspace from '../workspace' -import ListConfiguration from './configuration' -const logger = require('../util/logger')('list-ui') - -export type MouseEvent = 'mouseDown' | 'mouseDrag' | 'mouseUp' | 'doubleClick' - -export interface MousePosition { - winid: number - lnum: number - col: number - current: boolean -} - -export interface HighlightGroup { - hlGroup: string - priority: number - pos: [number, number, number] -} - -export default class ListUI { - private window: Window - private height: number - private newTab = false - private buffer: Buffer - private currIndex = 0 - private items: ListItemWithHighlights[] = [] - private disposables: Disposable[] = [] - private signOffset: number - private matchHighlightGroup: string - private selected: Set = new Set() - private mouseDown: MousePosition - private _onDidChangeLine = new Emitter() - private _onDidOpen = new Emitter() - private _onDidClose = new Emitter() - private _onDidLineChange = new Emitter() - private _onDoubleClick = new Emitter() - public readonly onDidChangeLine: Event = this._onDidChangeLine.event - public readonly onDidLineChange: Event = this._onDidLineChange.event - public readonly onDidOpen: Event = this._onDidOpen.event - public readonly onDidClose: Event = this._onDidClose.event - public readonly onDidDoubleClick: Event = this._onDoubleClick.event - - constructor( - private nvim: Neovim, - private name: string, - private listOptions: ListOptions, - private config: ListConfiguration - ) { - this.signOffset = config.get('signOffset') - this.matchHighlightGroup = config.get('matchHighlightGroup', 'Search') - this.newTab = listOptions.position == 'tab' - events.on('BufWinLeave', async bufnr => { - if (bufnr != this.bufnr || this.window == null) return - this.window = null - this._onDidClose.fire(bufnr) - }, null, this.disposables) - events.on('CursorMoved', async (bufnr, cursor) => { - if (bufnr != this.bufnr) return - this.onLineChange(cursor[0] - 1) - }, null, this.disposables) - let debounced = debounce(async bufnr => { - if (bufnr != this.bufnr) return - let [winid, start, end] = await nvim.eval('[win_getid(),line("w0"),line("w$")]') as number[] - if (end < 300 || winid != this.winid) return - // increment highlights - nvim.pauseNotification() - this.doHighlight(start - 1, end) - nvim.command('redraw', true) - void nvim.resumeNotification(false, true) - }, 100) - this.disposables.push({ - dispose: () => { - debounced.clear() - } - }) - events.on('CursorMoved', debounced, null, this.disposables) - } - - public get bufnr(): number | undefined { - return this.buffer?.id - } - - public get winid(): number | undefined { - return this.window?.id - } - private get limitLines(): number { - return this.config.get('limitLines', 30000) - } - - private onLineChange(index: number): void { - if (this.currIndex == index) return - this.currIndex = index - this._onDidChangeLine.fire(index) - } - - public set index(n: number) { - if (n < 0 || n >= this.items.length) return - let { nvim } = this - nvim.pauseNotification() - this.setCursor(n + 1, 0) - nvim.command('redraw', true) - void nvim.resumeNotification(false, true) - } - - public get index(): number { - return this.currIndex - } - - public getItem(index: number): ListItem { - return this.items[index] - } - - public get item(): Promise { - let { window } = this - if (!window) return Promise.resolve(null) - return window.cursor.then(cursor => { - this.currIndex = cursor[0] - 1 - return this.items[this.currIndex] - }) - } - - public async echoMessage(item: ListItem): Promise { - let { items } = this - let idx = items.indexOf(item) - let msg = `[${idx + 1}/${items.length}] ${item.label || ''}` - this.nvim.callTimer('coc#util#echo_lines', [[msg]], true) - } - - public async updateItem(item: ListItem, index: number): Promise { - if (!this.bufnr) return - let obj: ListItem = Object.assign({ resolved: true }, item) - if (index < this.length) { - this.items[index] = obj - let { nvim } = this - nvim.pauseNotification() - this.buffer.setOption('modifiable', true, true) - nvim.call('setbufline', [this.bufnr, index + 1, obj.label], true) - this.buffer.setOption('modifiable', false, true) - await nvim.resumeNotification() - } - } - - public async getItems(): Promise { - if (this.length == 0 || !this.window) return [] - let mode = await this.nvim.call('mode') - if (mode == 'v' || mode == 'V') { - let [start, end] = await this.getSelectedRange() - let res: ListItem[] = [] - for (let i = start; i <= end; i++) { - let item = this.items[i - 1] - if (item) res.push(item) - } - return res - } - let { selectedItems } = this - if (selectedItems.length) return selectedItems - let item = await this.item - return item == null ? [] : [item] - } - - public async onMouse(event: MouseEvent): Promise { - let { nvim, window } = this - if (!window) return - let [winid, lnum, col] = await nvim.eval(`[v:mouse_winid,v:mouse_lnum,v:mouse_col]`) as [number, number, number] - if (event == 'mouseDown') { - this.mouseDown = { winid, lnum, col, current: winid == window.id } - return - } - let current = winid == window.id - if (current && event == 'doubleClick') { - this.setCursor(lnum, 0) - this._onDoubleClick.fire() - } - if (current && event == 'mouseDrag') { - if (!this.mouseDown) return - await this.selectLines(this.mouseDown.lnum, lnum) - } else if (current && event == 'mouseUp') { - if (!this.mouseDown) return - if (this.mouseDown.lnum == lnum) { - this.setCursor(lnum, 0) - nvim.command('redraw', true) - } else { - await this.selectLines(this.mouseDown.lnum, lnum) - } - } else if (!current && event == 'mouseUp') { - nvim.pauseNotification() - nvim.call('win_gotoid', winid, true) - nvim.call('cursor', [lnum, col], true) - nvim.command('redraw', true) - void nvim.resumeNotification(false, true) - } - } - - public async resume(): Promise { - let { items, selected, nvim } = this - await this.drawItems(items, this.height, true) - if (!selected.size) return - nvim.pauseNotification() - for (let lnum of selected) { - this.buffer?.placeSign({ lnum, id: this.signOffset + lnum, name: 'CocSelected', group: 'coc-list' }) - } - nvim.command('redraw', true) - void nvim.resumeNotification(false, true) - } - - public async toggleSelection(): Promise { - let { nvim } = this - await nvim.call('win_gotoid', [this.winid]) - let lnum = await nvim.call('line', '.') - let mode = await nvim.call('mode') - if (mode == 'v' || mode == 'V') { - let [start, end] = await this.getSelectedRange() - let reverse = start > end - if (reverse) [start, end] = [end, start] - for (let i = start; i <= end; i++) { - this.toggleLine(i) - } - this.setCursor(end, 0) - nvim.command('redraw', true) - await nvim.resumeNotification() - return - } - nvim.pauseNotification() - this.toggleLine(lnum) - this.setCursor(lnum + 1, 0) - nvim.command('redraw', true) - await nvim.resumeNotification() - } - - private toggleLine(lnum: number): void { - let { selected, buffer, signOffset } = this - let exists = selected.has(lnum) - if (!exists) { - selected.add(lnum) - buffer.placeSign({ lnum, id: signOffset + lnum, name: 'CocSelected', group: 'coc-list' }) - } else { - selected.delete(lnum) - buffer.unplaceSign({ id: signOffset + lnum, group: 'coc-list' }) - } - } - - public async selectLines(start: number, end: number): Promise { - let { nvim, signOffset, buffer, length } = this - this.clearSelection() - let { selected } = this - nvim.pauseNotification() - let reverse = start > end - if (reverse) [start, end] = [end, start] - for (let i = start; i <= end; i++) { - if (i > length) break - selected.add(i) - buffer.placeSign({ lnum: i, id: signOffset + i, name: 'CocSelected', group: 'coc-list' }) - } - this.setCursor(end, 0) - nvim.command('redraw', true) - await nvim.resumeNotification() - } - - public async selectAll(): Promise { - let { length } = this - if (length == 0) return - await this.selectLines(1, length) - } - - public clearSelection(): void { - let { selected, signOffset, buffer } = this - if (selected.size > 0) { - let signIds: number[] = [] - for (let lnum of selected) { - signIds.push(signOffset + lnum) - } - buffer?.unplaceSign({ group: 'coc-list' }) - this.selected.clear() - } - } - - public get ready(): Promise { - if (this.window) return Promise.resolve() - return new Promise(resolve => { - let disposable = this.onDidLineChange(() => { - disposable.dispose() - resolve() - }) - }) - } - - public async drawItems(items: ListItem[], height: number, reload = false): Promise { - const { nvim, name, listOptions } = this - this.items = items.length > this.limitLines ? items.slice(0, this.limitLines) : items - if (!this.window) { - let { position, numberSelect } = listOptions - let [bufnr, winid] = await nvim.call('coc#list#create', [position, height, name, numberSelect]) - this.height = height - this.buffer = nvim.createBuffer(bufnr) - let win = this.window = nvim.createWindow(winid) - let statusSegments = this.config.get('statusLineSegments') - if (statusSegments) win.setOption('statusline', statusSegments.join(" "), true) - this._onDidOpen.fire(this.bufnr) - } - const lines = this.items.map(item => item.label) - let newIndex = reload ? this.currIndex : 0 - this.setLines(lines, false, newIndex) - this._onDidLineChange.fire(this.currIndex + 1) - } - - public appendItems(items: ListItem[]): void { - let curr = this.items.length - if (curr >= this.limitLines) return - let max = this.limitLines - curr - let append = items.slice(0, max) - this.items = this.items.concat(append) - this.setLines(append.map(item => item.label), curr > 0, this.currIndex) - } - - private setLines(lines: string[], append = false, index: number): void { - let { nvim, buffer, window } = this - if (!buffer || !window) return - nvim.pauseNotification() - if (!append) { - nvim.call('coc#compat#clear_matches', [window.id], true) - if (!lines.length) { - lines = ['No results, press ? on normal mode to get help.'] - nvim.call('coc#compat#matchaddpos', ['Comment', [[1]], 99, window.id], true) - } - } - buffer.setOption('modifiable', true, true) - void buffer.setLines(lines, { start: append ? -1 : 0, end: -1, strictIndexing: false }, true) - buffer.setOption('modifiable', false, true) - if (!append && index == 0) { - this.doHighlight(0, 299) - } else { - let height = this.newTab ? workspace.env.lines : this.height - this.doHighlight(Math.max(0, index - height), Math.min(index + height + 1, this.length - 1)) - } - if (!append) { - this.currIndex = index - window.setCursor([index + 1, 0], true) - } - nvim.command('redraws', true) - void nvim.resumeNotification(false, true) - } - - public restoreWindow(): void { - if (this.newTab) return - let { winid, height } = this - if (winid && height) { - this.nvim.call('coc#list#restore', [winid, height], true) - } - } - - public get length(): number { - return this.items.length - } - - public get selectedItems(): ListItem[] { - let { selected, items } = this - let res: ListItem[] = [] - for (let i of selected) { - if (items[i - 1]) res.push(items[i - 1]) - } - return res - } - - private doHighlight(start: number, end: number): void { - let { items } = this - let groups: HighlightGroup[] = [] - for (let i = start; i <= Math.min(end, items.length - 1); i++) { - let { ansiHighlights, highlights } = items[i] - if (ansiHighlights) { - for (let hi of ansiHighlights) { - let { span, hlGroup } = hi - groups.push({ hlGroup, priority: 9, pos: [i + 1, span[0] + 1, span[1] - span[0]] }) - } - } - if (highlights && Array.isArray(highlights.spans)) { - let { spans, hlGroup } = highlights - for (let span of spans) { - groups.push({ hlGroup: hlGroup || this.matchHighlightGroup, priority: 11, pos: [i + 1, span[0] + 1, span[1] - span[0]] }) - } - } - } - this.nvim.call('coc#compat#matchaddgroups', [this.window.id, groups], true) - } - - public setCursor(lnum: number, col: number): void { - let { items } = this - let max = items.length == 0 ? 1 : items.length - if (lnum > max) return - // change index since CursorMoved event not fired (seems bug of neovim)! - this.onLineChange(lnum - 1) - this.window?.setCursor([lnum, col], true) - } - - private async getSelectedRange(): Promise<[number, number]> { - let { nvim } = this - await nvim.call('coc#prompt#stop_prompt', ['list']) - await nvim.eval('feedkeys("\\", "in")') - let [, start] = await nvim.call('getpos', "'<") - let [, end] = await nvim.call('getpos', "'>") - this.nvim.call('coc#prompt#start_prompt', ['list'], true) - return [start, end] - } - - public reset(): void { - if (this.window) { - this.window = null - this.buffer = null - } - } - - public dispose(): void { - disposeAll(this.disposables) - this.nvim.call('coc#window#close', [this.winid || -1], true) - this.window = null - this.buffer = null - this.items = [] - this._onDidChangeLine.dispose() - this._onDidOpen.dispose() - this._onDidClose.dispose() - this._onDidLineChange.dispose() - this._onDoubleClick.dispose() - } -} diff --git a/vim-config/plugins/coc.nvim/src/list/worker.ts b/vim-config/plugins/coc.nvim/src/list/worker.ts deleted file mode 100644 index c378944f..00000000 --- a/vim-config/plugins/coc.nvim/src/list/worker.ts +++ /dev/null @@ -1,367 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationTokenSource, Emitter, Event } from 'vscode-languageserver-protocol' -import { IList, ListContext, ListHighlights, ListItem, ListItemsEvent, ListItemWithHighlights, ListOptions, ListTask } from '../types' -import { parseAnsiHighlights } from '../util/ansiparse' -import { patchLine } from '../util/diff' -import { hasMatch, positions, score } from '../util/fzy' -import { getMatchResult } from '../util/score' -import { byteIndex, byteLength } from '../util/string' -import window from '../window' -import workspace from '../workspace' -import Prompt from './prompt' -const logger = require('../util/logger')('list-worker') -const controlCode = '\x1b' - -export interface ExtendedItem extends ListItem { - score: number -} - -export interface WorkerConfiguration { - interactiveDebounceTime: number - extendedSearchMode: boolean -} - -// perform loading task -export default class Worker { - private _loading = false - private totalItems: ListItem[] = [] - private tokenSource: CancellationTokenSource - private _onDidChangeItems = new Emitter() - private _onDidChangeLoading = new Emitter() - public readonly onDidChangeItems: Event = this._onDidChangeItems.event - public readonly onDidChangeLoading: Event = this._onDidChangeLoading.event - - constructor( - private nvim: Neovim, - private list: IList, - private prompt: Prompt, - private listOptions: ListOptions, - private config: WorkerConfiguration - ) { - } - - private set loading(loading: boolean) { - if (this._loading == loading) return - this._loading = loading - this._onDidChangeLoading.fire(loading) - } - - public get isLoading(): boolean { - return this._loading - } - - public async loadItems(context: ListContext, reload = false): Promise { - let { list, listOptions } = this - this.loading = true - let { interactive } = listOptions - this.tokenSource = new CancellationTokenSource() - let token = this.tokenSource.token - let items = await list.loadItems(context, token) - if (token.isCancellationRequested) return - if (!items || Array.isArray(items)) { - this.tokenSource = null - items = (items || []) as ListItem[] - this.totalItems = items.map(item => { - item.label = this.fixLabel(item.label) - this.parseListItemAnsi(item) - return item - }) - this.loading = false - let filtered: ListItemWithHighlights[] - if (!interactive) { - filtered = this.filterItems(items) - } else { - filtered = this.convertToHighlightItems(items) - } - this._onDidChangeItems.fire({ - items: filtered, - reload, - finished: true - }) - } else { - let task = items as ListTask - let totalItems = this.totalItems = [] - let count = 0 - let currInput = context.input - let timer: NodeJS.Timer - let lastTs: number - let _onData = (finished?: boolean) => { - lastTs = Date.now() - if (count >= totalItems.length) return - let inputChanged = this.input != currInput - if (interactive && inputChanged) return - if (count == 0 || inputChanged) { - currInput = this.input - count = totalItems.length - let items: ListItem[] - if (interactive) { - items = this.convertToHighlightItems(totalItems) - } else { - items = this.filterItems(totalItems) - } - this._onDidChangeItems.fire({ items, reload, append: false, finished }) - } else { - let remain = totalItems.slice(count) - count = totalItems.length - let items: ListItem[] - if (!interactive) { - items = this.filterItems(remain) - } else { - items = this.convertToHighlightItems(remain) - } - this._onDidChangeItems.fire({ items, append: true, finished }) - } - } - task.on('data', item => { - if (timer) clearTimeout(timer) - if (token.isCancellationRequested) return - if (interactive && this.input != currInput) return - item.label = this.fixLabel(item.label) - this.parseListItemAnsi(item) - totalItems.push(item) - if ((!lastTs && totalItems.length == 500) - || Date.now() - lastTs > 200) { - _onData() - } else { - timer = setTimeout(() => _onData(), 50) - } - }) - let onEnd = () => { - if (task == null) return - this.tokenSource = null - task = null - this.loading = false - disposable.dispose() - if (timer) clearTimeout(timer) - if (totalItems.length == 0) { - this._onDidChangeItems.fire({ items: [], finished: true }) - } else { - _onData(true) - } - } - let disposable = token.onCancellationRequested(() => { - if (task) { - task.dispose() - onEnd() - } - }) - task.on('error', async (error: Error | string) => { - if (task == null) return - task = null - this.tokenSource = null - this.loading = false - disposable.dispose() - if (timer) clearTimeout(timer) - this.nvim.call('coc#prompt#stop_prompt', ['list'], true) - window.showMessage(`Task error: ${error.toString()}`, 'error') - logger.error(error) - }) - task.on('end', onEnd) - } - } - - /* - * Draw all items with filter if necessary - */ - public drawItems(): void { - let { totalItems } = this - let items: ListItemWithHighlights[] - items = this.filterItems(totalItems) - this._onDidChangeItems.fire({ items, finished: true }) - } - - public stop(): void { - if (this.tokenSource) { - this.tokenSource.cancel() - this.tokenSource = null - } - this.loading = false - } - - public get length(): number { - return this.totalItems.length - } - - private get input(): string { - return this.prompt.input - } - - /** - * Add highlights for interactive list - */ - private convertToHighlightItems(items: ListItem[]): ListItemWithHighlights[] { - let { input } = this - if (!input) return [] - return items.map(item => { - let filterLabel = getFilterLabel(item) - let res = getMatchResult(filterLabel, input) - if (!res?.score) return item - let highlights = this.getHighlights(filterLabel, res.matches) - return Object.assign({}, item, { highlights }) - }) - } - - private filterItems(items: ListItem[]): ListItemWithHighlights[] { - let { input } = this - let { sort, matcher, ignorecase } = this.listOptions - let inputs = this.config.extendedSearchMode ? parseInput(input) : [input] - if (input.length == 0 || inputs.length == 0) return items - if (matcher == 'strict') { - let filtered: ListItemWithHighlights[] = [] - for (let item of items) { - let spans: [number, number][] = [] - let filterLabel = getFilterLabel(item) - let match = true - for (let input of inputs) { - let idx = ignorecase ? filterLabel.toLowerCase().indexOf(input.toLowerCase()) : filterLabel.indexOf(input) - if (idx == -1) { - match = false - break - } - spans.push([byteIndex(filterLabel, idx), byteIndex(filterLabel, idx + byteLength(input))]) - } - if (match) { - filtered.push(Object.assign({}, item, { - highlights: { spans } - })) - } - } - return filtered - } - if (matcher == 'regex') { - let filtered: ListItemWithHighlights[] = [] - let flags = ignorecase ? 'iu' : 'u' - let regexes = inputs.reduce((p, c) => { - try { - let regex = new RegExp(c, flags) - p.push(regex) - } catch (e) {} - return p - }, []) - for (let item of items) { - let spans: [number, number][] = [] - let filterLabel = getFilterLabel(item) - let match = true - for (let regex of regexes) { - let ms = filterLabel.match(regex) - if (ms == null) { - match = false - break - } - spans.push([byteIndex(filterLabel, ms.index), byteIndex(filterLabel, ms.index + byteLength(ms[0]))]) - } - if (match) { - filtered.push(Object.assign({}, item, { - highlights: { spans } - })) - } - } - return filtered - } - let filtered: ExtendedItem[] = [] - let idx = 0 - for (let item of items) { - let filterText = item.filterText || item.label - let matchScore = 0 - let matches: number[] = [] - let filterLabel = getFilterLabel(item) - let match = true - for (let input of inputs) { - if (!hasMatch(input, filterText)) { - match = false - break - } - matches.push(...positions(input, filterLabel)) - if (sort) matchScore += score(input, filterText) - } - if (!match) continue - let obj = Object.assign({}, item, { - sortText: typeof item.sortText === 'string' ? item.sortText : String.fromCharCode(idx), - score: matchScore, - highlights: this.getHighlights(filterLabel, matches) - }) - filtered.push(obj) - idx = idx + 1 - } - if (sort && filtered.length) { - filtered.sort((a, b) => { - if (a.score != b.score) return b.score - a.score - if (a.sortText > b.sortText) return 1 - return -1 - }) - } - return filtered - } - - private getHighlights(text: string, matches?: number[]): ListHighlights { - let spans: [number, number][] = [] - if (matches && matches.length) { - let start = matches.shift() - let next = matches.shift() - let curr = start - while (next) { - if (next == curr + 1) { - curr = next - next = matches.shift() - continue - } - spans.push([byteIndex(text, start), byteIndex(text, curr) + 1]) - start = next - curr = start - next = matches.shift() - } - spans.push([byteIndex(text, start), byteIndex(text, curr) + 1]) - } - return { spans } - } - - // set correct label, add ansi highlights - private parseListItemAnsi(item: ListItem): void { - let { label } = item - if (item.ansiHighlights || !label.includes(controlCode)) return - let { line, highlights } = parseAnsiHighlights(label) - item.label = line - item.ansiHighlights = highlights - } - - private fixLabel(label: string): string { - let { columns } = workspace.env - label = label.split('\n').join(' ') - return label.slice(0, columns * 2) - } - - public dispose(): void { - this.stop() - } -} - -function getFilterLabel(item: ListItem): string { - return item.filterText != null ? patchLine(item.filterText, item.label) : item.label -} - -/** - * `a\ b` => [`a b`] - * `a b` => ['a', 'b'] - */ -export function parseInput(input): string[] { - let res = [] - let startIdx = 0 - let currIdx = 0 - let prev = '' - for (; currIdx < input.length; currIdx++) { - let ch = input[currIdx] - if (ch.charCodeAt(0) === 32) { - // find space - if (prev && prev != '\\' && startIdx != currIdx) { - res.push(input.slice(startIdx, currIdx)) - startIdx = currIdx + 1 - } - } else { - } - prev = ch - } - if (startIdx != input.length) { - res.push(input.slice(startIdx, input.length)) - } - return res.map(s => s.replace(/\\\s/g, ' ').trim()).filter(s => s.length > 0) -} diff --git a/vim-config/plugins/coc.nvim/src/main.ts b/vim-config/plugins/coc.nvim/src/main.ts deleted file mode 100755 index e934cac0..00000000 --- a/vim-config/plugins/coc.nvim/src/main.ts +++ /dev/null @@ -1,26 +0,0 @@ -require('./util/extensions') - -Object.defineProperty(console, 'log', { - value() { - logger.info(...arguments) - } -}) -const logger = require('./util/logger')('server') -const attach = require('./attach').default - -attach({ reader: process.stdin, writer: process.stdout }) - -process.on('uncaughtException', function(err) { - let msg = 'Uncaught exception: ' + err.message - console.error(msg) - logger.error('uncaughtException', err.stack) -}) - -process.on('unhandledRejection', function(reason, p) { - if (reason instanceof Error) { - console.error('UnhandledRejection: ' + reason.message + '\n' + reason.stack) - } else { - console.error('UnhandledRejection: ' + reason) - } - logger.error('unhandledRejection ', p, reason) -}) diff --git a/vim-config/plugins/coc.nvim/src/markdown/index.ts b/vim-config/plugins/coc.nvim/src/markdown/index.ts deleted file mode 100644 index f16602a9..00000000 --- a/vim-config/plugins/coc.nvim/src/markdown/index.ts +++ /dev/null @@ -1,199 +0,0 @@ -import marked from 'marked' -import Renderer from './renderer' -import { parseAnsiHighlights } from '../util/ansiparse' -import { byteLength } from '../util/string' -import stripAnsi from 'strip-ansi' -import { HighlightItem } from '../types' -export const diagnosticFiletypes = ['Error', 'Warning', 'Info', 'Hint'] -const logger = require('../util/logger')('markdown-index') - -export interface Documentation { - filetype: string - content: string - active?: [number, number] -} - -export interface MarkdownParseOptions { - excludeImages?: boolean -} - -export interface CodeBlock { - /** - * Must have filetype or hlgroup - */ - filetype?: string - hlGroup?: string - startLine: number // 0 based - endLine: number -} - -export interface DocumentInfo { - lines: string[] - highlights: HighlightItem[] - codes: CodeBlock[] -} - -export function parseDocuments(docs: Documentation[], opts: MarkdownParseOptions = {}): DocumentInfo { - let lines: string[] = [] - let highlights: HighlightItem[] = [] - let codes: CodeBlock[] = [] - let idx = 0 - for (let doc of docs) { - let currline = lines.length - let { content, filetype } = doc - if (filetype == 'markdown') { - let info = parseMarkdown(content, opts) - codes.push(...info.codes.map(o => { - o.startLine = o.startLine + currline - o.endLine = o.endLine + currline - return o - })) - highlights.push(...info.highlights.map(o => { - o.lnum = o.lnum + currline - return o - })) - lines.push(...info.lines) - } else { - let parts = content.trim().split(/\r?\n/) - if (diagnosticFiletypes.includes(doc.filetype)) { - codes.push({ hlGroup: `Coc${filetype}Float`, startLine: currline, endLine: currline + parts.length }) - } else { - codes.push({ filetype: doc.filetype, startLine: currline, endLine: currline + parts.length }) - } - lines.push(...parts) - } - if (doc.active) { - let arr = getHighlightItems(content, currline, doc.active) - if (arr.length) highlights.push(...arr) - } - if (idx != docs.length - 1) { - lines.push('โ”€') // separate line - } - idx = idx + 1 - } - return { lines, highlights, codes } -} - -/** - * Get 'CocUnderline' highlights from offset range - */ -export function getHighlightItems(content: string, currline: number, active: [number, number]): HighlightItem[] { - let res: HighlightItem[] = [] - let [start, end] = active - let lines = content.split(/\r?\n/) - let used = 0 - let inRange = false - for (let i = 0; i < lines.length; i++) { - let line = lines[i] - if (!inRange) { - if (used + line.length > start) { - inRange = true - let colStart = byteLength(line.slice(0, start - used)) - if (used + line.length > end) { - let colEnd = byteLength(line.slice(0, end - used)) - inRange = false - res.push({ colStart, colEnd, lnum: i + currline, hlGroup: 'CocUnderline' }) - break - } else { - let colEnd = byteLength(line) - res.push({ colStart, colEnd, lnum: i + currline, hlGroup: 'CocUnderline' }) - } - } - } else { - if (used + line.length > end) { - let colEnd = byteLength(line.slice(0, end - used)) - res.push({ colStart: 0, colEnd, lnum: i + currline, hlGroup: 'CocUnderline' }) - inRange = false - break - } else { - let colEnd = byteLength(line) - res.push({ colStart: 0, colEnd, lnum: i + currline, hlGroup: 'CocUnderline' }) - } - } - used = used + line.length + 1 - } - return res -} - -/** - * Parse markdown for lines, highlights & codes - */ -export function parseMarkdown(content: string, opts: MarkdownParseOptions): DocumentInfo { - marked.setOptions({ - renderer: new Renderer(), - gfm: true - }) - let lines: string[] = [] - let highlights: HighlightItem[] = [] - let codes: CodeBlock[] = [] - let currline = 0 - let inCodeBlock = false - let filetype: string - let startLnum = 0 - let parsed = marked(content) - let links = Renderer.getLinks() - if (links.length) { - parsed = parsed + '\n\n' + links.join('\n') - } - parsed = parsed.replace(/\s*$/, '') - let parsedLines = parsed.split(/\n/) - for (let i = 0; i < parsedLines.length; i++) { - let line = parsedLines[i] - if (!line.length) { - let pre = lines[lines.length - 1] - if (pre && pre.length) { - lines.push(line) - currline++ - } - continue - } - if (opts.excludeImages && line.indexOf('![') !== -1) { - line = line.replace(/\s*!\[.*?\]\(.*?\)/g, '') - if (!stripAnsi(line).trim().length) continue - } - if (/\s*```\s*([A-Za-z0-9_,]+)?$/.test(line)) { - if (!inCodeBlock) { - let pre = parsedLines[i - 1] - if (pre && /^\s*```\s*/.test(pre)) { - lines.push('') - currline++ - } - inCodeBlock = true - filetype = line.replace(/^\s*```\s*/, '') - if (filetype == 'js') filetype = 'javascript' - if (filetype == 'ts') filetype = 'typescript' - if (filetype == 'bash') filetype = 'sh' - startLnum = currline - } else { - inCodeBlock = false - codes.push({ - filetype, - startLine: startLnum, - endLine: currline - }) - } - continue - } - if (inCodeBlock) { - // no parse - lines.push(line) - currline++ - continue - } - let res = parseAnsiHighlights(line, true) - if (res.highlights) { - for (let hi of res.highlights) { - let { hlGroup, span } = hi - highlights.push({ - hlGroup, - lnum: currline, - colStart: span[0], - colEnd: span[1] - }) - } - } - lines.push(res.line) - currline++ - } - return { lines, highlights, codes } -} diff --git a/vim-config/plugins/coc.nvim/src/markdown/renderer.ts b/vim-config/plugins/coc.nvim/src/markdown/renderer.ts deleted file mode 100644 index 0018c0f3..00000000 --- a/vim-config/plugins/coc.nvim/src/markdown/renderer.ts +++ /dev/null @@ -1,381 +0,0 @@ -/** - * Renderer for convert markdown to terminal string - */ -import Table from 'cli-table' -import * as styles from './styles' -const logger = require('../util/logger')('markdown-renderer') -let TABLE_CELL_SPLIT = '^*||*^' -let TABLE_ROW_WRAP = '*|*|*|*' -let TABLE_ROW_WRAP_REGEXP = new RegExp(escapeRegExp(TABLE_ROW_WRAP), 'g') -let COLON_REPLACER = '*#COLON|*' -let COLON_REPLACER_REGEXP = new RegExp(escapeRegExp(COLON_REPLACER), 'g') - -let TAB_ALLOWED_CHARACTERS = ['\t'] - -// HARD_RETURN holds a character sequence used to indicate text has a -// hard (no-reflowing) line break. Previously \r and \r\n were turned -// into \n in marked's lexer- preprocessing step. So \r is safe to use -// to indicate a hard (non-reflowed) return. -let HARD_RETURN = '\r' - -let defaultOptions = { - code: identity, - blockquote: identity, - html: styles.gray, - heading: styles.magenta, - firstHeading: styles.magenta, - hr: identity, - listitem: identity, - list, - table: identity, - paragraph: identity, - strong: styles.bold, - em: styles.italic, - codespan: styles.yellow, - del: styles.strikethrough, - link: styles.underline, - href: styles.underline, - text: identity, - unescape: true, - emoji: false, - width: 80, - showSectionPrefix: true, - tab: 2, - tableOptions: {} -} - -function fixHardReturn(text, reflow) { - return reflow ? text.replace(HARD_RETURN, /\n/g) : text -} - -function sanitizeTab(tab, fallbackTab) { - if (typeof tab === 'number') { - return new Array(tab + 1).join(' ') - } else if (typeof tab === 'string' && isAllowedTabString(tab)) { - return tab - } else { - return new Array(fallbackTab + 1).join(' ') - } -} - -function isAllowedTabString(str) { - return TAB_ALLOWED_CHARACTERS.some(function(char) { - return str.match('^(' + char + ')+$') - }) -} - -function indentLines(indent, text) { - return text.replace(/(^|\n)(.+)/g, '$1' + indent + '$2') -} - -function indentify(indent, text) { - if (!text) return text - return indent + text.split('\n').join('\n' + indent) -} - -let BULLET_POINT_REGEX = '\\*' -let NUMBERED_POINT_REGEX = '\\d+\\.' -let POINT_REGEX = - '(?:' + [BULLET_POINT_REGEX, NUMBERED_POINT_REGEX].join('|') + ')' - -// Prevents nested lists from joining their parent list's last line -function fixNestedLists(body, indent) { - let regex = new RegExp( - '' + - '(\\S(?: | )?)' + // Last char of current point, plus one or two spaces - // to allow trailing spaces - '((?:' + - indent + - ')+)' + // Indentation of sub point - '(' + - POINT_REGEX + - '(?:.*)+)$', - 'gm' - ) // Body of subpoint - return body.replace(regex, '$1\n' + indent + '$2$3') -} - -let isPointedLine = function(line, indent) { - return line.match('^(?:' + indent + ')*' + POINT_REGEX) -} - -function toSpaces(str) { - return ' '.repeat(str.length) -} - -let BULLET_POINT = '* ' -function bulletPointLine(indent, line) { - return isPointedLine(line, indent) ? line : toSpaces(BULLET_POINT) + line -} - -function bulletPointLines(lines, indent) { - let transform = bulletPointLine.bind(null, indent) - return lines - .split('\n') - .filter(identity) - .map(transform) - .join('\n') -} - -let numberedPoint = function(n) { - return n + '. ' -} -function numberedLine(indent, line, num) { - return isPointedLine(line, indent) - ? { - num: num + 1, - line: line.replace(BULLET_POINT, numberedPoint(num + 1)) - } - : { - num, - line: toSpaces(numberedPoint(num)) + line - } -} - -function numberedLines(lines, indent) { - let transform = numberedLine.bind(null, indent) - let num = 0 - return lines - .split('\n') - .filter(identity) - .map(line => { - const numbered = transform(line, num) - num = numbered.num - - return numbered.line - }) - .join('\n') -} - -function list(body, ordered, indent) { - body = body.trim() - body = ordered ? numberedLines(body, indent) : bulletPointLines(body, indent) - return body -} - -function section(text) { - return text + '\n\n' -} - -function undoColon(str) { - return str.replace(COLON_REPLACER_REGEXP, ':') -} - -function generateTableRow(text, escape = null) { - if (!text) return [] - escape = escape || identity - let lines = escape(text).split('\n') - - let data = [] - lines.forEach(function(line) { - if (!line) return - let parsed = line - .replace(TABLE_ROW_WRAP_REGEXP, '') - .split(TABLE_CELL_SPLIT) - - data.push(parsed.splice(0, parsed.length - 1)) - }) - return data -} - -function escapeRegExp(str) { - // eslint-disable-next-line no-useless-escape - return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&') -} - -function unescapeEntities(html) { - return html - .replace(/&/g, '&') - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/"/g, '"') - .replace(/'/g, "'") -} - -function identity(str) { - return str -} - -const links: Map = new Map() - -class Renderer { - private o: any - private tab: any - private tableSettings: any - // private emoji: any - private unescape: any - private transform: any - constructor(public options: any = {}, public highlightOptions: any = {}) { - this.o = Object.assign({}, defaultOptions, options) - this.tab = sanitizeTab(this.o.tab, defaultOptions.tab) - this.tableSettings = this.o.tableOptions - // this.emoji = identity - this.unescape = this.o.unescape ? unescapeEntities : identity - this.highlightOptions = highlightOptions || {} - this.transform = this.compose(undoColon, this.unescape) - } - - // Compute length of str not including ANSI escape codes. - // See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - public textLength(str: string): number { - // eslint-disable-next-line no-control-regex - return str.replace(/\u001b\[(?:\d{1,3})(?:;\d{1,3})*m/g, '').length - } - - public text(t: string): string { - return this.o.text(t) - } - - public code(code: string, lang: string, _escaped: boolean): string { - return '``` ' + lang + '\n' + code + '\n```\n' - } - - public blockquote(quote: string): string { - return section(this.o.blockquote(indentify(this.tab, quote.trim()))) - } - - public html(html: string): string { - return this.o.html(html) - } - - public heading(text: string, level: number, _raw: any): string { - text = this.transform(text) - let prefix = this.o.showSectionPrefix - ? new Array(level + 1).join('#') + ' ' - : '' - text = prefix + text - return section( - level === 1 ? this.o.firstHeading(text) : this.o.heading(text) - ) - } - - public hr(): string { - // NOTE: the 'โ”€' character is conveniently translated into a window-wide - // horizontal rule by coc.nvim/autoload/coc/float.vim. Using this character - // causes the horizontal rule to appear like a proper hr separator. In case - // the user isn't benefiting from a floating window, we provide three - // characters so that the hr doesn't deviate too significantly from - // Markdown's normal '-'. - return `โ”€โ”€โ”€\n` - } - - public list(body, ordered): string { - body = this.o.list(body, ordered, this.tab) - return section(fixNestedLists(indentLines(this.tab, body), this.tab)) - } - - public listitem(text: string): string { - let transform = this.compose(this.o.listitem, this.transform) - let isNested = text.indexOf('\n') !== -1 - if (isNested) text = text.trim() - // Use BULLET_POINT as a marker for ordered or unordered list item - return '\n' + BULLET_POINT + transform(text) - } - - public checkbox(checked): string { - return '[' + (checked ? 'X' : ' ') + '] ' - } - - public paragraph(text: string): string { - let transform = this.compose(this.o.paragraph, this.transform) - text = transform(text) - return section(text) - } - - public table(header, body): string { - let table = new Table( - Object.assign( - {}, - { - head: generateTableRow(header)[0] - }, - this.tableSettings - ) - ) - generateTableRow(body, this.transform).forEach(function(row) { - table.push(row) - }) - return section(this.o.table(table.toString())) - } - - public tablerow(content: string): string { - return TABLE_ROW_WRAP + content + TABLE_ROW_WRAP + '\n' - } - - public tablecell(content, _flags): string { - return content + TABLE_CELL_SPLIT - } - - public strong(text: string): string { - return this.o.strong(text) - } - - public em(text: string): string { - text = fixHardReturn(text, this.o.reflowText) - return this.o.em(text) - } - - public codespan(text: string): string { - text = fixHardReturn(text, this.o.reflowText) - return this.o.codespan(text.replace(/:/g, COLON_REPLACER)) - } - - public br(): string { - return '\n' - } - - public del(text: string): string { - return this.o.del(text) - } - - public link(href, title, text): string { - let prot: string - if (this.options.sanitize) { - try { - prot = decodeURIComponent(unescape(href)) - .replace(/[^\w:]/g, '') - .toLowerCase() - } catch (e) { - return '' - } - if (prot.startsWith('javascript:')) { - return '' - } - } - if (text && href && text != href) { - links.set(text, href) - } - if (text && text != href) return styles.blue(text) - let out = this.o.href(href) - return this.o.link(out) - } - - public image(href, title, text): string { - if (typeof this.o.image === 'function') { - return this.o.image(href, title, text) - } - let out = '![' + text - if (title) out += ' โ€“ ' + title - return out + '](' + href + ')\n' - } - - public compose(...funcs: Function[]): any { - return (...args: any[]) => { - for (let i = funcs.length; i-- > 0;) { - args = [funcs[i].apply(this, args)] - } - return args[0] - } - } - - public static getLinks(): string[] { - let res = [] - for (let [text, href] of links.entries()) { - res.push(`${styles.blue(text)}: ${href}`) - } - links.clear() - return res - } -} - -export default Renderer diff --git a/vim-config/plugins/coc.nvim/src/markdown/styles.ts b/vim-config/plugins/coc.nvim/src/markdown/styles.ts deleted file mode 100644 index 2b047d17..00000000 --- a/vim-config/plugins/coc.nvim/src/markdown/styles.ts +++ /dev/null @@ -1,37 +0,0 @@ -import style from 'ansi-styles' - -export function gray(str: string): string { - return `${style.gray.open}${str}${style.gray.close}` -} - -export function magenta(str: string): string { - return `${style.magenta.open}${str}${style.magenta.close}` -} - -export function bold(str: string): string { - return `${style.bold.open}${str}${style.bold.close}` -} - -export function underline(str: string): string { - return `${style.underline.open}${str}${style.underline.close}` -} - -export function strikethrough(str: string): string { - return `${style.strikethrough.open}${str}${style.strikethrough.close}` -} - -export function italic(str: string): string { - return `${style.italic.open}${str}${style.italic.close}` -} - -export function yellow(str: string): string { - return `${style.yellow.open}${str}${style.yellow.close}` -} - -export function green(str: string): string { - return `${style.green.open}${str}${style.green.close}` -} - -export function blue(str: string): string { - return `${style.blue.open}${str}${style.blue.close}` -} diff --git a/vim-config/plugins/coc.nvim/src/model/bufferSync.ts b/vim-config/plugins/coc.nvim/src/model/bufferSync.ts deleted file mode 100644 index 8e2182b3..00000000 --- a/vim-config/plugins/coc.nvim/src/model/bufferSync.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { Disposable } from 'vscode-languageserver-protocol' -import { DidChangeTextDocumentParams, IWorkspace } from '../types' -import { disposeAll } from '../util' -import Document from './document' - -export interface SyncItem extends Disposable { - onChange?(e: DidChangeTextDocumentParams): void -} - -/** - * Buffer sync support, document is always attached and not command line buffer. - */ -export default class BufferSync { - private disposables: Disposable[] = [] - private itemsMap: Map = new Map() - constructor(private _create: (doc: Document) => T | undefined, private workspace: IWorkspace) { - let { disposables } = this - for (let doc of workspace.documents) { - this.create(doc) - } - workspace.onDidOpenTextDocument(e => { - let doc = workspace.getDocument(e.bufnr) - if (doc) this.create(doc) - }, null, disposables) - workspace.onDidChangeTextDocument(e => { - this.onChange(e) - }, null, disposables) - workspace.onDidCloseTextDocument(e => { - this.delete(e.bufnr) - }, null, disposables) - } - - public get items(): Iterable { - return Array.from(this.itemsMap.values()).map(x => x.item) - } - - public getItem(bufnr: number | string): T | undefined { - if (typeof bufnr === 'number') { - return this.itemsMap.get(bufnr)?.item - } - let o = Array.from(this.itemsMap.values()).find(v => { - return v.uri == bufnr - }) - return o ? o.item : undefined - } - - private create(doc: Document): void { - if (!doc || doc.isCommandLine || !doc.attached) return - let o = this.itemsMap.get(doc.bufnr) - if (o) o.item.dispose() - let item = this._create(doc) - if (item) this.itemsMap.set(doc.bufnr, { uri: doc.uri, item }) - } - - private onChange(e: DidChangeTextDocumentParams): void { - let o = this.itemsMap.get(e.bufnr) - if (o && typeof o.item.onChange == 'function') { - o.item.onChange(e) - } - } - - private delete(bufnr: number): void { - let o = this.itemsMap.get(bufnr) - if (o) { - this.itemsMap.delete(bufnr) - o.item.dispose() - } - } - - public reset(): void { - for (let o of this.itemsMap.values()) { - o.item.dispose() - } - this.itemsMap.clear() - } - - public dispose(): void { - disposeAll(this.disposables) - for (let o of this.itemsMap.values()) { - o.item.dispose() - } - this.itemsMap.clear() - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/chars.ts b/vim-config/plugins/coc.nvim/src/model/chars.ts deleted file mode 100644 index fe173f64..00000000 --- a/vim-config/plugins/coc.nvim/src/model/chars.ts +++ /dev/null @@ -1,118 +0,0 @@ -const logger = require('../util/logger')('model-chars') - -export class Range { - public start: number - public end: number - constructor(start: number, end?: number) { - this.start = start - this.end = end ? end : start - } - - public static fromKeywordOption(keywordOption: string): Range[] { - let parts = keywordOption.split(',') - let ranges: Range[] = [] - for (let part of parts) { - if (part == '@') { - // isalpha() of c - ranges.push(new Range(65, 90)) - ranges.push(new Range(97, 122)) - } else if (part == '@-@') { - ranges.push(new Range(64)) - } else if (/^([A-Za-z])-([A-Za-z])$/.test(part)) { - let ms = part.match(/^([A-Za-z])-([A-Za-z])$/) - ranges.push(new Range(ms[1].charCodeAt(0), ms[2].charCodeAt(0))) - } else if (/^\d+-\d+$/.test(part)) { - let ms = part.match(/^(\d+)-(\d+)$/) - ranges.push(new Range(Number(ms[1]), Number(ms[2]))) - } else if (/^\d+$/.test(part)) { - ranges.push(new Range(Number(part))) - } else { - let c = part.charCodeAt(0) - if (!ranges.some(o => o.contains(c))) { - ranges.push(new Range(c)) - } - } - } - return ranges - } - - public contains(c: number): boolean { - return c >= this.start && c <= this.end - } -} - -export class Chars { - public ranges: Range[] = [] - constructor(keywordOption?: string) { - if (keywordOption) this.ranges = Range.fromKeywordOption(keywordOption) - } - - public addKeyword(ch: string): void { - let c = ch.charCodeAt(0) - let { ranges } = this - if (!ranges.some(o => o.contains(c))) { - ranges.push(new Range(c)) - } - } - - public clone(): Chars { - let chars = new Chars() - chars.ranges = this.ranges.slice() - return chars - } - - public setKeywordOption(keywordOption: string): void { - this.ranges = Range.fromKeywordOption(keywordOption) - } - - public matchKeywords(content: string, min = 3): string[] { - let length = content.length - if (length == 0) return [] - let res: Set = new Set() - let str = '' - let len = 0 - for (let i = 0; i < length; i++) { - let ch = content[i] - let code = ch.codePointAt(0) - if (len == 0 && code == 45) continue - let isKeyword = this.isKeywordCode(code) - if (isKeyword) { - if (len == 48) continue - str = str + ch - len = len + 1 - } else { - if (len >= min && len < 48) res.add(str) - str = '' - len = 0 - } - } - if (len != 0) res.add(str) - return Array.from(res) - } - - public isKeywordCode(code: number): boolean { - if (code > 255) return true - if (code < 33) return false - return this.ranges.some(r => r.contains(code)) - } - - public isKeywordChar(ch: string): boolean { - let { ranges } = this - let c = ch.charCodeAt(0) - if (c > 255) return true - if (c < 33) return false - return ranges.some(r => r.contains(c)) - } - - public isKeyword(word: string): boolean { - let { ranges } = this - for (let i = 0, l = word.length; i < l; i++) { - let ch = word.charCodeAt(i) - // for speed - if (ch > 255) return false - if (ranges.some(r => r.contains(ch))) continue - return false - } - return true - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/db.ts b/vim-config/plugins/coc.nvim/src/model/db.ts deleted file mode 100644 index 00a1488a..00000000 --- a/vim-config/plugins/coc.nvim/src/model/db.ts +++ /dev/null @@ -1,133 +0,0 @@ -import fs from 'fs-extra' -import path from 'path' - -export default class DB { - constructor(public readonly filepath: string) { - } - - /** - * Get data by key. - * - * @param {string} key unique key allows dot notation. - * @returns {any} - */ - public fetch(key: string): any { - let obj = this.load() - if (!key) return obj - let parts = key.split('.') - for (let part of parts) { - if (typeof obj[part] == 'undefined') { - return undefined - } - obj = obj[part] - } - return obj - } - - /** - * Check if key exists - * - * @param {string} key unique key allows dot notation. - */ - public exists(key: string): boolean { - let obj = this.load() - let parts = key.split('.') - for (let part of parts) { - if (typeof obj[part] == 'undefined') { - return false - } - obj = obj[part] - } - return true - } - - /** - * Delete data by key - * - * @param {string} key unique key allows dot notation. - */ - public delete(key: string): void { - let obj = this.load() - let origin = obj - let parts = key.split('.') - let len = parts.length - for (let i = 0; i < len; i++) { - if (typeof obj[parts[i]] == 'undefined') { - break - } - if (i == len - 1) { - delete obj[parts[i]] - fs.writeFileSync(this.filepath, JSON.stringify(origin, null, 2), 'utf8') - break - } - obj = obj[parts[i]] - } - } - - /** - * Save data with key - * - * @param {string} key unique string that allows dot notation. - * @param {number|null|boolean|string|{[index} data saved data. - */ - public push(key: string, data: number | null | boolean | string | { [index: string]: any }): void { - let origin = this.load() || {} - let obj = origin - let parts = key.split('.') - let len = parts.length - if (obj == null) { - let dir = path.dirname(this.filepath) - fs.mkdirpSync(dir) - obj = origin - } - for (let i = 0; i < len; i++) { - let key = parts[i] - if (i == len - 1) { - obj[key] = data - fs.writeFileSync(this.filepath, JSON.stringify(origin, null, 2)) - break - } - if (typeof obj[key] == 'undefined') { - obj[key] = {} - obj = obj[key] - } else { - obj = obj[key] - } - } - } - - private load(): any { - let dir = path.dirname(this.filepath) - let stat = fs.statSync(dir) - if (!stat || !stat.isDirectory()) { - fs.mkdirpSync(dir) - fs.writeFileSync(this.filepath, '{}', 'utf8') - return {} - } - try { - let content = fs.readFileSync(this.filepath, 'utf8') - return JSON.parse(content.trim()) - } catch (e) { - fs.writeFileSync(this.filepath, '{}', 'utf8') - return {} - } - } - - /** - * Empty db file. - */ - public clear(): void { - let stat = fs.statSync(this.filepath) - if (!stat || !stat.isFile()) return - fs.writeFileSync(this.filepath, '{}', 'utf8') - } - - /** - * Remove db file. - */ - public destroy(): void { - if (fs.existsSync(this.filepath)) { - fs.unlinkSync(this.filepath) - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/dialog.ts b/vim-config/plugins/coc.nvim/src/model/dialog.ts deleted file mode 100644 index 71baa53f..00000000 --- a/vim-config/plugins/coc.nvim/src/model/dialog.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import events from '../events' -import { disposeAll } from '../util' -const logger = require('../util/logger')('model-dialog') - -export interface DialogButton { - /** - * Use by callback, should >= 0 - */ - index: number - text: string - /** - * Not shown when true - */ - disabled?: boolean -} - -export interface DialogPreferences { - maxWidth?: number - maxHeight?: number - floatHighlight?: string - floatBorderHighlight?: string - pickerButtons?: boolean - pickerButtonShortcut?: boolean - confirmKey?: string -} - -export interface DialogConfig { - content: string - /** - * Optional title text. - */ - title?: string - /** - * show close button, default to true when not specified. - */ - close?: boolean - /** - * highlight group for dialog window, default to `"dialog.floatHighlight"` or 'CocFlating' - */ - highlight?: string - /** - * highlight groups for border, default to `"dialog.borderhighlight"` or 'CocFlating' - */ - borderhighlight?: string - /** - * Buttons as bottom of dialog. - */ - buttons?: DialogButton[] - /** - * index is -1 for window close without button click - */ - callback?: (index: number) => void -} - -export default class Dialog { - private disposables: Disposable[] = [] - private bufnr: number - constructor(private nvim: Neovim, private config: DialogConfig) { - events.on('BufWinLeave', bufnr => { - if (bufnr == this.bufnr) { - this.dispose() - if (config.callback) config.callback(-1) - } - }, null, this.disposables) - events.on('FloatBtnClick', (bufnr, idx) => { - if (bufnr == this.bufnr) { - this.dispose() - let btns = config?.buttons.filter(o => o.disabled != true) - if (config.callback) config.callback(btns[idx].index) - } - }, null, this.disposables) - } - - private get lines(): string[] { - return [...this.config.content.split(/\r?\n/)] - } - - public async show(preferences: DialogPreferences): Promise { - let { nvim } = this - let { title, close, buttons } = this.config - let borderhighlight = this.config.borderhighlight || preferences.floatBorderHighlight - let highlight = this.config.highlight || preferences.floatHighlight - let opts: any = { maxwidth: preferences.maxWidth || 80, } - if (title) opts.title = title - if (close || typeof close === 'undefined') opts.close = 1 - if (preferences.maxHeight) opts.maxHeight = preferences.maxHeight - if (preferences.maxWidth) opts.maxWidth = preferences.maxWidth - if (highlight) opts.highlight = highlight - if (borderhighlight) opts.borderhighlight = [borderhighlight] - if (buttons) opts.buttons = buttons.filter(o => !o.disabled).map(o => o.text) - let res = await nvim.call('coc#float#create_dialog', [this.lines, opts]) - if (!res[1]) return - this.bufnr = res[1] - nvim.command('redraw', true) - } - - public get winid(): Promise { - if (!this.bufnr) return Promise.resolve(null) - return this.nvim.call('bufwinid', [this.bufnr]) - } - - public dispose(): void { - this.bufnr = undefined - disposeAll(this.disposables) - this.disposables = [] - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/document.ts b/vim-config/plugins/coc.nvim/src/model/document.ts deleted file mode 100644 index 4db78905..00000000 --- a/vim-config/plugins/coc.nvim/src/model/document.ts +++ /dev/null @@ -1,723 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import debounce from 'debounce' -import { CancellationToken, Disposable, Emitter, Event, Position, Range, TextEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { URI } from 'vscode-uri' -import events from '../events' -import { DidChangeTextDocumentParams, HighlightItem } from '../types' -import { diffLines, getChange } from '../util/diff' -import { disposeAll, getUri, wait, waitNextTick } from '../util/index' -import { equals } from '../util/object' -import { emptyRange } from '../util/position' -import { byteIndex, byteLength, byteSlice } from '../util/string' -import { Chars } from './chars' -import { LinesTextDocument } from './textdocument' -const logger = require('../util/logger')('model-document') - -export type LastChangeType = 'insert' | 'change' | 'delete' - -export interface Env { - readonly filetypeMap: { [index: string]: string } - readonly isVim: boolean - readonly isCygwin: boolean -} - -export interface ChangeInfo { - lnum: number - line: string - changedtick: number -} - -export interface BufferOption { - eol: number - size: number - winid: number - previewwindow: boolean - variables: { [key: string]: any } - bufname: string - fullpath: string - buftype: string - filetype: string - iskeyword: string - changedtick: number - lines: string[] -} - -// getText, positionAt, offsetAt -export default class Document { - public buftype: string - public isIgnored = false - public chars: Chars - public fireContentChanges: Function & { clear(): void } - public fetchContent: Function & { clear(): void } - private size = 0 - private nvim: Neovim - private eol = true - private variables: { [key: string]: any } - // real current lines - private lines: ReadonlyArray = [] - private _attached = false - private _previewwindow = false - private _winid = -1 - private _filetype: string - private _uri: string - private _changedtick: number - private _words: string[] = [] - private _onDocumentChange = new Emitter() - private _onDocumentDetach = new Emitter() - private disposables: Disposable[] = [] - private _textDocument: LinesTextDocument - public readonly onDocumentChange: Event = this._onDocumentChange.event - public readonly onDocumentDetach: Event = this._onDocumentDetach.event - constructor(public readonly buffer: Buffer, private env: Env, private maxFileSize: number | null) { - this.fireContentChanges = debounce(() => { - this._fireContentChanges() - }, 300) - this.fetchContent = debounce(() => { - void this._fetchContent() - }, 100) - } - - /** - * Synchronize content - */ - public get content(): string { - return this.syncLines.join('\n') + (this.eol ? '\n' : '') - } - - public get attached(): boolean { - return this._attached - } - - /** - * Buffer number - */ - public get bufnr(): number { - return this.buffer.id - } - - public get filetype(): string { - return this._filetype - } - - public get uri(): string { - return this._uri - } - /** - * Check if current document should be attached for changes. - * - * Currently only attach for empty and `acwrite` buftype. - */ - public get shouldAttach(): boolean { - let { buftype, maxFileSize } = this - if (!this.getVar('enabled', true)) return false - if (this.uri.endsWith('%5BCommand%20Line%5D')) return true - // too big - if (this.size == -2) return false - if (maxFileSize && this.size > maxFileSize) return false - return buftype == '' || buftype == 'acwrite' - } - - public get isCommandLine(): boolean { - return this.uri && this.uri.endsWith('%5BCommand%20Line%5D') - } - - public get enabled(): boolean { - return this.getVar('enabled', true) - } - - /** - * All words, extracted by `iskeyword` option. - */ - public get words(): string[] { - return this._words - } - - /** - * Map filetype for languageserver. - */ - public convertFiletype(filetype: string): string { - switch (filetype) { - case 'javascript.jsx': - return 'javascriptreact' - case 'typescript.jsx': - case 'typescript.tsx': - return 'typescriptreact' - case 'tex': - // Vim filetype 'tex' means LaTeX, which has LSP language ID 'latex' - return 'latex' - default: { - let map = this.env.filetypeMap - return map[filetype] || filetype - } - } - } - - /** - * Get current buffer changedtick. - */ - public get changedtick(): number { - return this._changedtick - } - - /** - * Scheme of document. - */ - public get schema(): string { - return URI.parse(this.uri).scheme - } - - /** - * Line count of current buffer. - */ - public get lineCount(): number { - return this.lines.length - } - - /** - * Window ID when buffer create, could be -1 when no window associated. - * - * @deprecated could be wrong. - */ - public get winid(): number { - return this._winid - } - - /** - * Returns if current document is opended with previewwindow - * - * @deprecated - */ - public get previewwindow(): boolean { - return this._previewwindow - } - - /** - * Initialize document model. - * - * @internal - */ - public async init(nvim: Neovim, token: CancellationToken): Promise { - this.nvim = nvim - let opts: BufferOption = await nvim.call('coc#util#get_bufoptions', [this.bufnr, this.maxFileSize]) - if (opts == null) return false - let buftype = this.buftype = opts.buftype - this._previewwindow = opts.previewwindow - this._winid = opts.winid - this.size = typeof opts.size == 'number' ? opts.size : 0 - this.variables = opts.variables || {} - this._changedtick = opts.changedtick - this.eol = opts.eol == 1 - this._uri = getUri(opts.fullpath, this.bufnr, buftype, this.env.isCygwin) - if (token.isCancellationRequested) return false - if (this.shouldAttach) { - this.lines = opts.lines - let res = await this.attach() - if (!res) return false - this._attached = true - } - this._filetype = this.convertFiletype(opts.filetype) - this.setIskeyword(opts.iskeyword) - this.createTextDocument(1, this.lines) - if (token.isCancellationRequested) { - this.detach() - return false - } - return true - } - - private async attach(): Promise { - let attached = await this.buffer.attach(true) - if (!attached) return false - let lines = this.lines - this.buffer.listen('lines', (buf: Buffer, tick: number, firstline: number, lastline: number, linedata: string[]) => { - if (buf.id !== this.bufnr || !this._attached || tick == null) return - if (tick > this._changedtick) { - this._changedtick = tick - lines = [...lines.slice(0, firstline), ...linedata, ...lines.slice(lastline)] - this.lines = lines - this.fireContentChanges() - } - }, this.disposables) - this.buffer.listen('detach', async buf => { - lines = [] - this._onDocumentDetach.fire(buf.id) - }, this.disposables) - return true - } - - /** - * Check if document changed after last synchronize - */ - public get dirty(): boolean { - if (this.lines === this.syncLines) return false - return !equals(this.lines, this.syncLines) - } - - private _fireContentChanges(): void { - let { cursor } = events - if (!this.dirty) return - let textDocument = this._textDocument - let endOffset = null - // consider cursor position. - if (cursor && cursor.bufnr == this.bufnr) { - endOffset = this.getEndOffset(cursor.lnum, cursor.col, cursor.insert) - } - let content = this.getDocumentContent() - let change = getChange(textDocument.getText(), content, endOffset) - if (change == null) return - let start = textDocument.positionAt(change.start) - let end = textDocument.positionAt(change.end) - let original = textDocument.getText(Range.create(start, end)) - this.createTextDocument(this.version + 1, this.lines) - let changes = [{ - range: { start, end }, - rangeLength: change.end - change.start, - text: change.newText - }] - this._onDocumentChange.fire({ - bufnr: this.bufnr, - original, - originalLines: textDocument.lines, - textDocument: { version: this.version, uri: this.uri }, - contentChanges: changes - }) - this._words = this.chars.matchKeywords(content) - } - - public async applyEdits(edits: TextEdit[]): Promise { - if (!Array.isArray(arguments[0]) && Array.isArray(arguments[1])) { - edits = arguments[1] - } - if (edits.length == 0) return - let textDocument = TextDocument.create(this.uri, this.filetype, 1, this.getDocumentContent()) - // apply edits to current textDocument - let applied = TextDocument.applyEdits(textDocument, edits) - let content: string - if (this.eol) { - if (applied.endsWith('\r\n')) { - content = applied.slice(0, -2) - } else { - content = applied.endsWith('\n') ? applied.slice(0, -1) : applied - } - } else { - content = applied - } - let lines = this.lines - let newLines = content.split(/\r?\n/) - // could be equal sometimes - if (!equals(lines, newLines)) { - let lnums = edits.map(o => o.range.start.line) - let d = diffLines(lines, newLines, Math.min.apply(null, lnums)) - let original = lines.slice(d.start, d.end) - this.nvim.call('coc#util#set_lines', [this.bufnr, this._changedtick, original, d.replacement, d.start, d.end], true) - if (this.env.isVim) this.nvim.command('redraw', true) - await waitNextTick(() => { - // can't wait vim sync buffer - this.lines = newLines - this._forceSync() - }) - } - } - - public async changeLines(lines: [number, string][]): Promise { - let filtered: [number, string][] = [] - let newLines = this.lines.slice() - for (let [lnum, text] of lines) { - if (newLines[lnum] != text) { - filtered.push([lnum, text]) - newLines[lnum] = text - } - } - if (!filtered.length) return - this.nvim.call('coc#util#change_lines', [this.bufnr, filtered], true) - if (this.env.isVim) this.nvim.command('redraw', true) - this.lines = newLines - this._forceSync() - } - - public _forceSync(): void { - this.fireContentChanges.clear() - this._fireContentChanges() - } - - public forceSync(): void { - // may cause bugs, prevent extensions use it. - if (global.hasOwnProperty('__TEST__')) { - this._forceSync() - } - } - - /** - * Get offset from lnum & col - */ - public getOffset(lnum: number, col: number): number { - return this.textDocument.offsetAt({ - line: lnum - 1, - character: col - }) - } - - /** - * Check string is word. - */ - public isWord(word: string): boolean { - return this.chars.isKeyword(word) - } - - /** - * Generate more words by split word with `-` - */ - public getMoreWords(): string[] { - let res = [] - let { words, chars } = this - if (!chars.isKeywordChar('-')) return res - for (let word of words) { - word = word.replace(/^-+/, '') - if (word.includes('-')) { - let parts = word.split('-') - for (let part of parts) { - if ( - part.length > 2 && - !res.includes(part) && - !words.includes(part) - ) { - res.push(part) - } - } - } - } - return res - } - - /** - * Current word for replacement - */ - public getWordRangeAtPosition(position: Position, extraChars?: string, current = true): Range | null { - let chars = this.chars.clone() - if (extraChars && extraChars.length) { - for (let ch of extraChars) { - chars.addKeyword(ch) - } - } - let line = this.getline(position.line, current) - if (line.length == 0 || position.character >= line.length) return null - if (!chars.isKeywordChar(line[position.character])) return null - let start = position.character - let end = position.character + 1 - if (!chars.isKeywordChar(line[start])) { - return Range.create(position, { line: position.line, character: position.character + 1 }) - } - while (start >= 0) { - let ch = line[start - 1] - if (!ch || !chars.isKeyword(ch)) break - start = start - 1 - } - while (end <= line.length) { - let ch = line[end] - if (!ch || !chars.isKeywordChar(ch)) break - end = end + 1 - } - return Range.create(position.line, start, position.line, end) - } - - /** - * Synchronized textDocument. - */ - public get textDocument(): TextDocument { - return this._textDocument - } - - private get syncLines(): ReadonlyArray { - return this._textDocument.lines - } - - public get version(): number { - return this._textDocument.version - } - - private createTextDocument(version: number, lines: ReadonlyArray): void { - let { uri, filetype, eol } = this - this._textDocument = new LinesTextDocument(uri, filetype, version, lines, eol) - } - - /** - * Used by vim for fetch new lines. - */ - private async _fetchContent(sync?: boolean): Promise { - if (!this.env.isVim || !this._attached) return - let { nvim, bufnr, changedtick } = this - let o = await nvim.call('coc#util#get_buf_lines', [bufnr, changedtick]) - if (o) { - this._changedtick = o.changedtick - this.lines = o.lines - if (sync) { - this._forceSync() - } else { - this.fireContentChanges() - } - } - } - - /** - * Get and synchronize change - */ - public async patchChange(currentLine?: boolean): Promise { - if (!this._attached) return - if (this.env.isVim) { - if (currentLine) { - let change = await this.nvim.call('coc#util#get_changeinfo', []) as ChangeInfo - if (change.changedtick < this._changedtick) return - let { lnum, line, changedtick } = change - let newLines = this.lines.slice() - this._changedtick = changedtick - if (newLines[lnum - 1] == line) return - newLines[lnum - 1] = line - this.lines = newLines - this._forceSync() - } else { - this.fetchContent.clear() - await this._fetchContent(true) - } - } else { - // changedtick from buffer events could be not latest. #3003 - this._changedtick = await this.buffer.getVar('changedtick') as number - // we have latest lines aftet TextChange on neovim - this._forceSync() - } - } - - /** - * Get ranges of word in textDocument. - */ - public getSymbolRanges(word: string): Range[] { - let { version, filetype, uri } = this - let textDocument = new LinesTextDocument(uri, filetype, version, this.lines, this.eol) - let res: Range[] = [] - let content = textDocument.getText() - let str = '' - for (let i = 0, l = content.length; i < l; i++) { - let ch = content[i] - if ('-' == ch && str.length == 0) { - continue - } - let isKeyword = this.chars.isKeywordChar(ch) - if (isKeyword) { - str = str + ch - } - if (str.length > 0 && !isKeyword && str == word) { - res.push(Range.create(textDocument.positionAt(i - str.length), textDocument.positionAt(i))) - } - if (!isKeyword) { - str = '' - } - } - return res - } - - /** - * Adjust col with new valid character before position. - */ - public fixStartcol(position: Position, valids: string[]): number { - let line = this.getline(position.line) - if (!line) return null - let { character } = position - let start = line.slice(0, character) - let col = byteLength(start) - let { chars } = this - for (let i = start.length - 1; i >= 0; i--) { - let c = start[i] - if (c == ' ') break - if (!chars.isKeywordChar(c) && !valids.includes(c)) { - break - } - col = col - byteLength(c) - } - return col - } - - /** - * Add vim highlight items from highlight group and range. - * Synchronized lines are used for calculate cols. - */ - public addHighlights(items: HighlightItem[], hlGroup: string, range: Range): void { - let { start, end } = range - if (emptyRange(range)) return - for (let line = start.line; line <= end.line; line++) { - const text = this.getline(line, false) - let colStart = line == start.line ? byteIndex(text, start.character) : 0 - let colEnd = line == end.line ? byteIndex(text, end.character) : global.Buffer.byteLength(text) - if (colStart >= colEnd) continue - items.push({ hlGroup, lnum: line, colStart, colEnd }) - } - } - - /** - * Real current line - */ - public getline(line: number, current = true): string { - if (current) return this.lines[line] || '' - return this.syncLines[line] || '' - } - - /** - * Get lines, zero indexed, end exclude. - */ - public getLines(start?: number, end?: number): string[] { - return this.lines.slice(start, end) - } - - /** - * Get current content text. - */ - public getDocumentContent(): string { - let content = this.lines.join('\n') - return this.eol ? content + '\n' : content - } - - /** - * Get variable value by key, defined by `b:coc_{key}` - */ - public getVar(key: string, defaultValue?: T): T { - let val = this.variables[`coc_${key}`] - return val === undefined ? defaultValue : val - } - - /** - * Get position from lnum & col - */ - public getPosition(lnum: number, col: number): Position { - let line = this.getline(lnum - 1) - if (!line || col == 0) return { line: lnum - 1, character: 0 } - let pre = byteSlice(line, 0, col - 1) - return { line: lnum - 1, character: pre.length } - } - - /** - * Get end offset from cursor position. - * For normal mode, use offset - 1 when possible - */ - public getEndOffset(lnum: number, col: number, insert: boolean): number { - let total = 0 - let len = this.lines.length - for (let i = lnum - 1; i < len; i++) { - let line = this.lines[i] - let l = line.length - if (i == lnum - 1 && l != 0) { - // current - let buf = global.Buffer.from(line, 'utf8') - let isEnd = buf.byteLength <= col - 1 - if (!isEnd) { - total = total + buf.slice(col - 1, buf.length).toString('utf8').length - if (!insert) total = total - 1 - } - } else { - total = total + l - } - if (!this.eol && i == len - 1) break - total = total + 1 - } - return total - } - - /** - * Recreate document with new filetype. - */ - public setFiletype(filetype: string): void { - this._filetype = this.convertFiletype(filetype) - let lines = this._textDocument.lines - this._textDocument = new LinesTextDocument(this.uri, this.filetype, 1, lines, this.eol) - } - - /** - * Change iskeyword option of document - */ - public setIskeyword(iskeyword: string): void { - let chars = this.chars = new Chars(iskeyword) - let additional = this.getVar('additional_keywords', []) - if (additional && Array.isArray(additional)) { - for (let ch of additional) { - chars.addKeyword(ch) - } - } - let lines = this.lines.length > 30000 ? this.lines.slice(0, 30000) : this.lines - // TODO not parse words - this._words = this.chars.matchKeywords(lines.join('\n')) - } - - /** - * Detach document. - * - * @internal - */ - public detach(): void { - this._attached = false - disposeAll(this.disposables) - this.disposables = [] - this.fetchContent.clear() - this.fireContentChanges.clear() - this._onDocumentChange.dispose() - this._onDocumentDetach.dispose() - } - - /** - * Synchronize latest document content - */ - public async synchronize(): Promise { - let { changedtick } = this - await this.patchChange() - if (changedtick != this.changedtick) { - await wait(50) - } - } - - /** - * Get localify bonus map. - * - * @internal - */ - public getLocalifyBonus(sp: Position, ep: Position): Map { - let res: Map = new Map() - let { chars } = this - let startLine = Math.max(0, sp.line - 100) - let endLine = Math.min(this.lineCount, sp.line + 100) - let content = this.lines.slice(startLine, endLine).join('\n') - sp = Position.create(sp.line - startLine, sp.character) - ep = Position.create(ep.line - startLine, ep.character) - let doc = TextDocument.create(this.uri, this.filetype, 1, content) - let headCount = doc.offsetAt(sp) - let len = content.length - let tailCount = len - doc.offsetAt(ep) - let start = 0 - let preKeyword = false - for (let i = 0; i < headCount; i++) { - let iskeyword = chars.isKeyword(content[i]) - if (!preKeyword && iskeyword) { - start = i - } else if (preKeyword && (!iskeyword || i == headCount - 1)) { - if (i - start > 1) { - let str = content.slice(start, i) - res.set(str, i / headCount) - } - } - preKeyword = iskeyword - } - start = len - tailCount - preKeyword = false - for (let i = start; i < content.length; i++) { - let iskeyword = chars.isKeyword(content[i]) - if (!preKeyword && iskeyword) { - start = i - } else if (preKeyword && (!iskeyword || i == len - 1)) { - if (i - start > 1) { - let end = i == len - 1 ? i + 1 : i - let str = content.slice(start, end) - let score = res.get(str) || 0 - res.set(str, Math.max(score, (len - i + (end - start)) / tailCount)) - } - } - preKeyword = iskeyword - } - return res - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/download.ts b/vim-config/plugins/coc.nvim/src/model/download.ts deleted file mode 100644 index dba5a04d..00000000 --- a/vim-config/plugins/coc.nvim/src/model/download.ts +++ /dev/null @@ -1,127 +0,0 @@ -import contentDisposition from 'content-disposition' -import { http, https } from 'follow-redirects' -import fs, { Stats } from 'fs-extra' -import { IncomingMessage } from 'http' -import path from 'path' -import tar from 'tar' -import unzip from 'unzip-stream' -import { v1 as uuidv1 } from 'uuid' -import { CancellationToken } from 'vscode-languageserver-protocol' -import { resolveRequestOptions, FetchOptions } from './fetch' -const logger = require('../util/logger')('model-download') - -export interface DownloadOptions extends Omit { - /** - * Folder that contains downloaded file or extracted files by untar or unzip - */ - dest: string - /** - * Remove the specified number of leading path elements for *untar* only, default to `1`. - */ - strip?: number - /** - * If true, use untar for `.tar.gz` filename - */ - extract?: boolean | 'untar' | 'unzip' - onProgress?: (percent: string) => void -} - -/** - * Download file from url, with optional untar/unzip support. - * - * @param {string} url - * @param {DownloadOptions} options contains dest folder and optional onProgress callback - */ -export default function download(url: string, options: DownloadOptions, token?: CancellationToken): Promise { - let { dest, onProgress, extract } = options - if (!dest || !path.isAbsolute(dest)) { - throw new Error(`Expect absolute file path for dest option.`) - } - let stat: Stats - try { - stat = fs.statSync(dest) - } catch (_e) { - fs.mkdirpSync(dest) - } - if (stat && !stat.isDirectory()) { - throw new Error(`${dest} exists, but not directory!`) - } - let mod = url.startsWith('https') ? https : http - let opts = resolveRequestOptions(url, options) - let extname = path.extname(url) - return new Promise((resolve, reject) => { - if (token) { - let disposable = token.onCancellationRequested(() => { - disposable.dispose() - req.destroy(new Error('request aborted')) - }) - } - const req = mod.request(opts, (res: IncomingMessage) => { - if ((res.statusCode >= 200 && res.statusCode < 300) || res.statusCode === 1223) { - let headers = res.headers || {} - let dispositionHeader = headers['content-disposition'] - if (!extname && dispositionHeader) { - let disposition = contentDisposition.parse(dispositionHeader) - if (disposition.parameters?.filename) { - extname = path.extname(disposition.parameters.filename) - } - } - if (extract === true) { - if (extname === '.zip' || headers['content-type'] == 'application/zip') { - extract = 'unzip' - } else if (extname == '.tgz') { - extract = 'untar' - } else { - reject(new Error(`Unable to extract for ${url}`)) - return - } - } - let total = Number(headers['content-length']) - let cur = 0 - if (!isNaN(total)) { - res.on('data', chunk => { - cur += chunk.length - let percent = (cur / total * 100).toFixed(1) - if (onProgress) { - onProgress(percent) - } else { - logger.info(`Download ${url} progress ${percent}%`) - } - }) - } - res.on('error', err => { - reject(new Error(`Unable to connect ${url}: ${err.message}`)) - }) - res.on('end', () => { - logger.info('Download completed:', url) - }) - let stream: any - if (extract === 'untar') { - stream = res.pipe(tar.x({ strip: options.strip ?? 1, C: dest })) - } else if (extract === 'unzip') { - stream = res.pipe(unzip.Extract({ path: dest })) - } else { - dest = path.join(dest, `${uuidv1()}${extname}`) - stream = res.pipe(fs.createWriteStream(dest)) - } - stream.on('finish', () => { - logger.info(`Downloaded ${url} => ${dest}`) - setTimeout(() => { - resolve(dest) - }, 100) - }) - stream.on('error', reject) - } else { - reject(new Error(`Invalid response from ${url}: ${res.statusCode}`)) - } - }) - req.on('error', reject) - req.on('timeout', () => { - req.destroy(new Error(`request timeout after ${options.timeout}ms`)) - }) - if (options.timeout) { - req.setTimeout(options.timeout) - } - req.end() - }) -} diff --git a/vim-config/plugins/coc.nvim/src/model/fetch.ts b/vim-config/plugins/coc.nvim/src/model/fetch.ts deleted file mode 100644 index b817cbb2..00000000 --- a/vim-config/plugins/coc.nvim/src/model/fetch.ts +++ /dev/null @@ -1,257 +0,0 @@ -import { http, https } from 'follow-redirects' -import { Readable } from 'stream' -import { parse, UrlWithStringQuery } from 'url' -import fs from 'fs' -import { objectLiteral } from '../util/is' -import workspace from '../workspace' -import { stringify } from 'querystring' -import createHttpProxyAgent, { HttpProxyAgent } from 'http-proxy-agent' -import createHttpsProxyAgent, { HttpsProxyAgent } from 'https-proxy-agent' -import { CancellationToken } from 'vscode-languageserver-protocol' -import decompressResponse from 'decompress-response' -const logger = require('../util/logger')('model-fetch') - -export type ResponseResult = string | Buffer | { [name: string]: any } - -export interface ProxyOptions { - proxyUrl: string - strictSSL?: boolean - proxyAuthorization?: string | null - proxyCA?: string | null -} - -export interface FetchOptions { - /** - * Default to 'GET' - */ - method?: string - /** - * Default no timeout - */ - timeout?: number - /** - * Always return buffer instead of parsed response. - */ - buffer?: boolean - /** - * - 'string' for text response content - * - 'object' for json response content - * - 'buffer' for response not text or json - */ - data?: string | { [key: string]: any } | Buffer - /** - * Plain object added as query of url - */ - query?: { [key: string]: unknown } - headers?: any - /** - * User for http basic auth, should use with password - */ - user?: string - /** - * Password for http basic auth, should use with user - */ - password?: string -} - -function getSystemProxyURI(endpoint: UrlWithStringQuery): string { - let env: string | null - if (endpoint.protocol === 'http:') { - env = process.env.HTTP_PROXY || process.env.http_proxy || null - } else if (endpoint.protocol === 'https:') { - env = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null - } - let noProxy = process.env.NO_PROXY || process.env.no_proxy - if (noProxy === '*') { - env = null - } else if (noProxy) { - // canonicalize the hostname, so that 'oogle.com' won't match 'google.com' - const hostname = endpoint.hostname.replace(/^\.*/, '.').toLowerCase() - const port = endpoint.port || endpoint.protocol.startsWith('https') ? '443' : '80' - const noProxyList = noProxy.split(',') - for (let i = 0, len = noProxyList.length; i < len; i++) { - let noProxyItem = noProxyList[i].trim().toLowerCase() - // no_proxy can be granular at the port level, which complicates things a bit. - if (noProxyItem.includes(':')) { - let noProxyItemParts = noProxyItem.split(':', 2) - let noProxyHost = noProxyItemParts[0].replace(/^\.*/, '.') - let noProxyPort = noProxyItemParts[1] - if (port === noProxyPort && hostname.endsWith(noProxyHost)) { - env = null - break - } - } else { - noProxyItem = noProxyItem.replace(/^\.*/, '.') - if (hostname.endsWith(noProxyItem)) { - env = null - break - } - } - } - } - return env -} - -export function getAgent(endpoint: UrlWithStringQuery, options: ProxyOptions): HttpsProxyAgent | HttpProxyAgent { - let proxy = options.proxyUrl || getSystemProxyURI(endpoint) - if (proxy) { - const proxyEndpoint = parse(proxy) - if (!/^https?:$/.test(proxyEndpoint.protocol)) { - return null - } - let opts = { - host: proxyEndpoint.hostname, - port: proxyEndpoint.port ? Number(proxyEndpoint.port) : (proxyEndpoint.protocol === 'https' ? '443' : '80'), - auth: proxyEndpoint.auth, - rejectUnauthorized: typeof options.strictSSL === 'boolean' ? options.strictSSL : true - } - logger.info(`Using proxy ${proxy} from ${options.proxyUrl ? 'configuration' : 'system environment'} for ${endpoint.hostname}:`) - return endpoint.protocol === 'http:' ? createHttpProxyAgent(opts) : createHttpsProxyAgent(opts) - } - return null -} - -export function resolveRequestOptions(url: string, options: FetchOptions = {}): any { - let config = workspace.getConfiguration('http') - let { data } = options - let dataType = getDataType(data) - let proxyOptions: ProxyOptions = { - proxyUrl: config.get('proxy', ''), - strictSSL: config.get('proxyStrictSSL', true), - proxyAuthorization: config.get('proxyAuthorization', null), - proxyCA: config.get('proxyCA', null) - } - if (options.query && !url.includes('?')) { - url = `${url}?${stringify(options.query)}` - } - let headers = Object.assign(options.headers || {}, { 'Proxy-Authorization': proxyOptions.proxyAuthorization }) - let endpoint = parse(url) - let agent = getAgent(endpoint, proxyOptions) - let opts: any = { - method: options.method || 'GET', - hostname: endpoint.hostname, - port: endpoint.port ? parseInt(endpoint.port, 10) : (endpoint.protocol === 'https:' ? 443 : 80), - path: endpoint.path, - agent, - rejectUnauthorized: proxyOptions.strictSSL, - maxRedirects: 3, - headers: Object.assign({ - 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)', - 'Accept-Encoding': 'gzip, deflate' - }, headers) - } - if (proxyOptions.proxyCA) { - opts.ca = fs.readFileSync(proxyOptions.proxyCA) - } - if (dataType == 'object') { - opts.headers['Content-Type'] = 'application/json' - } else if (dataType == 'string') { - opts.headers['Content-Type'] = 'text/plain' - } - if (options.user && options.password) { - opts.auth = options.user + ':' + options.password - } - if (options.timeout) { - opts.timeout = options.timeout - } - if (options.buffer) opts.buffer = true - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return opts -} - -function request(url: string, data: any, opts: any, token?: CancellationToken): Promise { - let mod = url.startsWith('https:') ? https : http - return new Promise((resolve, reject) => { - if (token) { - let disposable = token.onCancellationRequested(() => { - disposable.dispose() - req.destroy(new Error('request aborted')) - }) - } - const req = mod.request(opts, res => { - let readable: Readable = res - if ((res.statusCode >= 200 && res.statusCode < 300) || res.statusCode === 1223) { - let headers = res.headers || {} - let chunks: Buffer[] = [] - let contentType: string = headers['content-type'] || '' - readable = decompressResponse(res) - readable.on('data', chunk => { - chunks.push(chunk) - }) - readable.on('end', () => { - let buf = Buffer.concat(chunks) - if (!opts.buffer && (contentType.startsWith('application/json') || contentType.startsWith('text/'))) { - let ms = contentType.match(/charset=(\S+)/) - let encoding = ms ? ms[1] : 'utf8' - let rawData = buf.toString(encoding as BufferEncoding) - if (!contentType.includes('application/json')) { - resolve(rawData) - } else { - try { - const parsedData = JSON.parse(rawData) - resolve(parsedData) - } catch (e) { - reject(new Error(`Parse response error: ${e}`)) - } - } - } else { - resolve(buf) - } - }) - readable.on('error', err => { - reject(new Error(`Unable to connect ${url}: ${err.message}`)) - }) - } else { - reject(new Error(`Bad response from ${url}: ${res.statusCode}`)) - } - }) - req.on('error', reject) - req.on('timeout', () => { - req.destroy(new Error(`Request timeout after ${opts.timeout}ms`)) - }) - if (data) { - if (typeof data === 'string' || Buffer.isBuffer(data)) { - req.write(data) - } else { - req.write(JSON.stringify(data)) - } - } - if (opts.timeout) { - req.setTimeout(opts.timeout) - } - req.end() - }) -} - -function getDataType(data: any): string { - if (data === null) return 'null' - if (data === undefined) return 'undefined' - if (typeof data == 'string') return 'string' - if (Buffer.isBuffer(data)) return 'buffer' - if (Array.isArray(data) || objectLiteral(data)) return 'object' - return 'unknown' -} - -/** - * Send request to server for response, supports: - * - * - Send json data and parse json response. - * - Throw error for failed response statusCode. - * - Timeout support (no timeout by default). - * - Send buffer (as data) and receive data (as response). - * - Proxy support from user configuration & environment. - * - Redirect support, limited to 3. - * - Support of gzip & deflate response content. - */ -export default function fetch(url: string, options: FetchOptions = {}, token?: CancellationToken): Promise { - let opts = resolveRequestOptions(url, options) - return request(url, options.data, opts, token).catch(err => { - logger.error(`Fetch error for ${url}:`, opts, err) - if (opts.agent && opts.agent.proxy) { - let { proxy } = opts.agent - throw new Error(`Request failed using proxy ${proxy.host}: ${err.message}`) - } else { - throw err - } - }) -} diff --git a/vim-config/plugins/coc.nvim/src/model/fileSystemWatcher.ts b/vim-config/plugins/coc.nvim/src/model/fileSystemWatcher.ts deleted file mode 100644 index 78363132..00000000 --- a/vim-config/plugins/coc.nvim/src/model/fileSystemWatcher.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { Disposable, Emitter, Event } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import Watchman, { FileChange } from '../watchman' -import minimatch from 'minimatch' -import path from 'path' -import { disposeAll } from '../util' -import { splitArray } from '../util/array' -const logger = require('../util/logger')('filesystem-watcher') - -export interface RenameEvent { - oldUri: URI - newUri: URI -} - -export default class FileSystemWatcher implements Disposable { - - private _onDidCreate = new Emitter() - private _onDidChange = new Emitter() - private _onDidDelete = new Emitter() - private _onDidRename = new Emitter() - - public readonly onDidCreate: Event = this._onDidCreate.event - public readonly onDidChange: Event = this._onDidChange.event - public readonly onDidDelete: Event = this._onDidDelete.event - public readonly onDidRename: Event = this._onDidRename.event - private disposables: Disposable[] = [] - - constructor( - clientPromise: Promise | null, - private globPattern: string, - public ignoreCreateEvents: boolean, - public ignoreChangeEvents: boolean, - public ignoreDeleteEvents: boolean - ) { - if (!clientPromise) return - clientPromise.then(client => { - if (client) return this.listen(client) - }).catch(error => { - logger.error('watchman initialize failed') - logger.error(error.stack) - }) - } - - private async listen(client: Watchman): Promise { - let { globPattern, - ignoreCreateEvents, - ignoreChangeEvents, - ignoreDeleteEvents } = this - let disposable = await client.subscribe(globPattern, (change: FileChange) => { - let { root, files } = change - files = files.filter(f => f.type == 'f' && minimatch(f.name, globPattern, { dot: true })) - for (let file of files) { - let uri = URI.file(path.join(root, file.name)) - if (!file.exists) { - if (!ignoreDeleteEvents) this._onDidDelete.fire(uri) - } else { - if (file.new === true) { - if (!ignoreCreateEvents) this._onDidCreate.fire(uri) - } else { - if (!ignoreChangeEvents) this._onDidChange.fire(uri) - } - } - } - // file rename - if (files.length == 2 && !files[0].exists && files[1].exists) { - let oldFile = files[0] - let newFile = files[1] - if (oldFile.size == newFile.size) { - this._onDidRename.fire({ - oldUri: URI.file(path.join(root, oldFile.name)), - newUri: URI.file(path.join(root, newFile.name)) - }) - } - } - // detect folder rename - if (files.length >= 2) { - let [oldFiles, newFiles] = splitArray(files, o => o.exists === false) - if (oldFiles.length == newFiles.length) { - for (let oldFile of oldFiles) { - let newFile = newFiles.find(o => o.size == oldFile.size && o.mtime_ms == oldFile.mtime_ms) - if (newFile) { - this._onDidRename.fire({ - oldUri: URI.file(path.join(root, oldFile.name)), - newUri: URI.file(path.join(root, newFile.name)) - }) - } - } - } - } - }) - this.disposables.push(disposable) - return disposable - } - - public dispose(): void { - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/floatFactory.ts b/vim-config/plugins/coc.nvim/src/model/floatFactory.ts deleted file mode 100644 index bd866ffa..00000000 --- a/vim-config/plugins/coc.nvim/src/model/floatFactory.ts +++ /dev/null @@ -1,237 +0,0 @@ -import { Buffer, Neovim, Window } from '@chemzqm/neovim' -import debounce from 'debounce' -import { Disposable } from 'vscode-languageserver-protocol' -import events, { BufEvents } from '../events' -import { Documentation, parseDocuments } from '../markdown' -import { disposeAll } from '../util' -import { Mutex } from '../util/mutex' -import { equals } from '../util/object' -import { FloatConfig } from '../types' -const isVim = process.env.VIM_NODE_RPC == '1' -const logger = require('../util/logger')('model-float') - -export interface WindowConfig { - width: number - height: number - col: number - row: number - relative: 'cursor' | 'win' | 'editor' - style?: string - cursorline?: number - title?: string - border?: number[] - autohide?: number - close?: number -} - -export interface FloatWinConfig { - maxHeight?: number - maxWidth?: number - preferTop?: boolean - autoHide?: boolean - offsetX?: number - title?: string - border?: number[] - cursorline?: boolean - close?: boolean - highlight?: string - borderhighlight?: string - modes?: string[] - shadow?: boolean - winblend?: number - focusable?: boolean - excludeImages?: boolean -} - -/** - * Float window/popup factory for create float/popup around current cursor. - */ -export default class FloatFactory implements Disposable { - private winid = 0 - private _bufnr = 0 - private closeTs: number - private targetBufnr: number - private mutex: Mutex = new Mutex() - private disposables: Disposable[] = [] - private cursor: [number, number] - private onCursorMoved: ((bufnr: number, cursor: [number, number]) => void) & { clear(): void } - constructor(private nvim: Neovim) { - this.onCursorMoved = debounce(this._onCursorMoved.bind(this), 100) - } - - private bindEvents(autoHide: boolean, alignTop: boolean): void { - let eventNames: BufEvents[] = ['InsertLeave', 'InsertEnter', 'BufEnter'] - for (let ev of eventNames) { - events.on(ev, bufnr => { - if (bufnr == this._bufnr) return - this.close() - }, null, this.disposables) - } - events.on('MenuPopupChanged', () => { - // avoid intersect with pum - if (events.pumAlignTop == alignTop) { - this.close() - } - }, null, this.disposables) - this.disposables.push(Disposable.create(() => { - this.onCursorMoved.clear() - })) - events.on('CursorMoved', this.onCursorMoved.bind(this, autoHide), this, this.disposables) - events.on('CursorMovedI', this.onCursorMoved.bind(this, autoHide), this, this.disposables) - } - - public unbind(): void { - if (this.disposables.length) { - disposeAll(this.disposables) - this.disposables = [] - } - } - - public _onCursorMoved(autoHide: boolean, bufnr: number, cursor: [number, number]): void { - if (bufnr == this._bufnr) return - if (bufnr == this.targetBufnr && equals(cursor, this.cursor)) { - // cursor not moved - return - } - if (autoHide || bufnr != this.targetBufnr || !events.insertMode) { - this.close() - return - } - } - - /** - * Create float window/popup at cursor position. - * - * @deprecated use show method instead - */ - public async create(docs: Documentation[], _allowSelection = false, offsetX = 0): Promise { - await this.show(docs, { - offsetX - }) - } - - public applyFloatConfig(conf: FloatWinConfig, opts: FloatConfig): FloatWinConfig { - for (let key of Object.keys(opts)) { - if (key == 'border') { - if (opts.border) conf.border = [1, 1, 1, 1] - continue - } - conf[key] = opts[key] - } - return conf - } - - /** - * Show documentations in float window/popup around cursor. - * Window and buffer are reused when possible. - * Window is closed automatically on change buffer, InsertEnter, CursorMoved and CursorMovedI. - * - * @param docs List of documentations. - * @param config Configuration for floating window/popup. - */ - public async show(docs: Documentation[], config: FloatWinConfig = {}): Promise { - if (docs.length == 0 || docs.every(doc => doc.content.length == 0)) { - this.close() - return - } - let curr = Date.now() - let release = await this.mutex.acquire() - try { - await this.createPopup(docs, config, curr) - release() - } catch (e) { - this.nvim.echoError(e) - release() - } - } - - private async createPopup(docs: Documentation[], opts: FloatWinConfig, timestamp: number): Promise { - docs = docs.filter(o => o.content.trim().length > 0) - let { lines, codes, highlights } = parseDocuments(docs) - let config: any = { - pumAlignTop: events.pumAlignTop, - preferTop: typeof opts.preferTop === 'boolean' ? opts.preferTop : false, - offsetX: opts.offsetX || 0, - title: opts.title || '', - close: opts.close ? 1 : 0, - codes, - highlights, - modes: opts.modes || ['n', 'i', 'ic', 's'] - } - if (!isVim) { - if (typeof opts.winblend === 'number') config.winblend = opts.winblend - if (opts.focusable != null) config.focusable = opts.focusable ? 1 : 0 - if (opts.shadow) config.shadow = 1 - } - if (opts.maxHeight) config.maxHeight = opts.maxHeight - if (opts.maxWidth) config.maxWidth = opts.maxWidth - if (opts.border && !opts.border.every(o => o == 0)) { - config.border = opts.border - } - if (opts.title && !config.border) config.border = [1, 1, 1, 1] - if (opts.highlight) config.highlight = opts.highlight - if (opts.borderhighlight) config.borderhighlight = [opts.borderhighlight] - if (opts.cursorline) config.cursorline = 1 - let autoHide = opts.autoHide == false ? false : true - if (autoHide) config.autohide = 1 - this.unbind() - let arr = await this.nvim.call('coc#float#create_cursor_float', [this.winid, this._bufnr, lines, config]) - this.nvim.redrawVim() - if (!arr || arr.length == 0 || this.closeTs > timestamp) { - let winid = arr && arr.length > 0 ? arr[2] : this.winid - if (winid) { - this.winid = 0 - this.nvim.call('coc#float#close', [winid], true) - this.nvim.redrawVim() - } - return - } - let [targetBufnr, cursor, winid, bufnr, alignTop] = arr as [number, [number, number], number, number, number] - this.winid = winid - this._bufnr = bufnr - this.targetBufnr = targetBufnr - this.cursor = cursor - this.bindEvents(autoHide, alignTop == 1) - } - - /** - * Close float window - */ - public close(): void { - let { winid, nvim } = this - this.closeTs = Date.now() - this.unbind() - if (winid) { - this.winid = 0 - nvim.call('coc#float#close', [winid], true) - nvim.redrawVim() - } - } - - public checkRetrigger(bufnr: number): boolean { - if (this.winid && this.targetBufnr == bufnr) return true - return false - } - - public get bufnr(): number { - return this._bufnr - } - - public get buffer(): Buffer | null { - return this.bufnr ? this.nvim.createBuffer(this.bufnr) : null - } - - public get window(): Window | null { - return this.winid ? this.nvim.createWindow(this.winid) : null - } - - public async activated(): Promise { - if (!this.winid) return false - return await this.nvim.call('coc#float#valid', [this.winid]) != 0 - } - - public dispose(): void { - this.cursor = undefined - this.close() - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/highligher.ts b/vim-config/plugins/coc.nvim/src/model/highligher.ts deleted file mode 100644 index 72067641..00000000 --- a/vim-config/plugins/coc.nvim/src/model/highligher.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { Buffer } from '@chemzqm/neovim' -import { parseAnsiHighlights } from '../util/ansiparse' -import { byteLength } from '../util/string' -import { HighlightItem } from '../types' - -export interface TextItem { - text: string - hlGroup?: string -} - -/** - * Build highlights, with lines and highlights - */ -export default class Highlighter { - private lines: string[] = [] - private highlights: HighlightItem[] = [] - - public addLine(line: string, hlGroup?: string): void { - if (line.includes('\n')) { - for (let content of line.split(/\r?\n/)) { - this.addLine(content, hlGroup) - } - return - } - if (hlGroup) { - this.highlights.push({ - lnum: this.lines.length, - colStart: line.match(/^\s*/)[0].length, - colEnd: byteLength(line), - hlGroup - }) - } // '\x1b' - if (line.includes('\x1b')) { - let res = parseAnsiHighlights(line) - for (let hl of res.highlights) { - let { span, hlGroup } = hl - if (span[0] != span[1]) { - this.highlights.push({ - lnum: this.lines.length, - colStart: span[0], - colEnd: span[1], - hlGroup - }) - } - } - this.lines.push(res.line) - } else { - this.lines.push(line) - } - } - - public addLines(lines): void { - this.lines.push(...lines) - } - - /** - * Add texts to new Lines - */ - public addTexts(items: TextItem[]): void { - this.addLines('') - for (let item of items) { - this.addText(item.text, item.hlGroup) - } - } - - public addText(text: string, hlGroup?: string): void { - let { lines } = this - let pre = lines[lines.length - 1] || '' - if (hlGroup) { - let colStart = byteLength(pre) - this.highlights.push({ - lnum: lines.length ? lines.length - 1 : 0, - colStart, - colEnd: colStart + byteLength(text), - hlGroup - }) - } - if (lines.length) { - lines[lines.length - 1] = `${pre}${text}` - } else { - lines.push(text) - } - } - - public get length(): number { - return this.lines.length - } - - public getline(line: number): string { - return this.lines[line] || '' - } - - // default to replace - public render(buffer: Buffer, start = 0, end = -1): void { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - buffer.setLines(this.lines, { start, end, strictIndexing: false }, true) - for (let item of this.highlights) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - buffer.addHighlight({ - hlGroup: item.hlGroup, - colStart: item.colStart, - colEnd: item.colEnd == null ? -1 : item.colEnd, - line: start + item.lnum, - srcId: -1 - }) - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/installBuffer.ts b/vim-config/plugins/coc.nvim/src/model/installBuffer.ts deleted file mode 100644 index 37c75b75..00000000 --- a/vim-config/plugins/coc.nvim/src/model/installBuffer.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import { EventEmitter } from 'events' -import { Disposable } from 'vscode-languageserver-protocol' -import { OutputChannel } from '../types' -import { frames } from './status' -const logger = require('../util/logger')('model-installBuffer') - -export enum State { - Waiting, - Faild, - Progressing, - Success, -} - -export default class InstallBuffer extends EventEmitter implements Disposable { - private statMap: Map = new Map() - private messagesMap: Map = new Map() - private names: string[] = [] - // eslint-disable-next-line no-undef - private interval: NodeJS.Timer - public bufnr: number - - constructor( - private isUpdate = false, - private isSync = false, - private channel: OutputChannel | undefined = undefined) { - super() - } - - public setExtensions(names: string[]): void { - this.statMap.clear() - this.names = names - for (let name of names) { - this.statMap.set(name, State.Waiting) - } - } - - public addMessage(name: string, msg: string, isProgress = false): void { - if (isProgress && this.channel) return - let lines = this.messagesMap.get(name) || [] - this.messagesMap.set(name, lines.concat(msg.trim().split(/\r?\n/))) - if (this.channel) this.channel.appendLine(`[${name}] ${msg}`) - } - - public startProgress(names: string[]): void { - for (let name of names) { - this.statMap.set(name, State.Progressing) - } - } - - public finishProgress(name: string, succeed = true): void { - if (this.channel) { - if (succeed) { - this.channel.appendLine(`[${name}] install succeed!`) - } else { - this.channel.appendLine(`[${name}] install failed!`) - } - } - this.statMap.set(name, succeed ? State.Success : State.Faild) - } - - public get remains(): number { - let count = 0 - for (let name of this.names) { - let stat = this.statMap.get(name) - if (![State.Success, State.Faild].includes(stat)) { - count = count + 1 - } - } - return count - } - - private getLines(): string[] { - let lines: string[] = [] - for (let name of this.names) { - let state = this.statMap.get(name) - let processText = '*' - switch (state) { - case State.Progressing: { - let d = new Date() - let idx = Math.floor(d.getMilliseconds() / 100) - processText = frames[idx] - break - } - case State.Faild: - processText = 'โœ—' - break - case State.Success: - processText = 'โœ“' - break - } - let msgs = this.messagesMap.get(name) || [] - lines.push(`- ${processText} ${name} ${msgs.length ? msgs[msgs.length - 1] : ''}`) - } - return lines - } - - public getMessages(line: number): string[] { - if (line <= 1) return [] - let name = this.names[line - 2] - if (!name) return [] - return this.messagesMap.get(name) - } - - // draw frame - private draw(nvim: Neovim, buffer: Buffer): void { - let { remains } = this - let first = remains == 0 ? `${this.isUpdate ? 'Update' : 'Install'} finished` : `Installing, ${remains} remains...` - let lines = [first, '', ...this.getLines()] - // eslint-disable-next-line @typescript-eslint/no-floating-promises - buffer.setLines(lines, { start: 0, end: -1, strictIndexing: false }, true) - if (remains == 0 && this.interval) { - clearInterval(this.interval) - this.interval = null - } - if (process.env.VIM_NODE_RPC) { - nvim.command('redraw', true) - } - } - - public highlight(nvim: Neovim): void { - nvim.call('matchadd', ['CocListFgCyan', '^\\-\\s\\zs\\*'], true) - nvim.call('matchadd', ['CocListFgGreen', '^\\-\\s\\zsโœ“'], true) - nvim.call('matchadd', ['CocListFgRed', '^\\-\\s\\zsโœ—'], true) - nvim.call('matchadd', ['CocListFgYellow', '^-.\\{3\\}\\zs\\S\\+'], true) - } - - public async show(nvim: Neovim): Promise { - let { isSync } = this - if (this.channel) return - nvim.pauseNotification() - nvim.command(isSync ? 'enew' : 'vs +enew', true) - nvim.call('bufnr', ['%'], true) - nvim.command('setl buftype=nofile bufhidden=wipe noswapfile nobuflisted wrap undolevels=-1', true) - if (!isSync) { - nvim.command('nnoremap q :q', true) - } - this.highlight(nvim) - let res = await nvim.resumeNotification() - let bufnr = res && res[1] == null ? res[0][1] : null - if (!bufnr) return - this.bufnr = bufnr - let buffer = nvim.createBuffer(bufnr) - this.interval = setInterval(() => { - this.draw(nvim, buffer) - }, 100) - } - - public dispose(): void { - if (this.interval) { - clearInterval(this.interval) - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/installer.ts b/vim-config/plugins/coc.nvim/src/model/installer.ts deleted file mode 100644 index 1cc214f2..00000000 --- a/vim-config/plugins/coc.nvim/src/model/installer.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { EventEmitter } from 'events' -import { spawn } from 'child_process' -import { parse, ParseError } from 'jsonc-parser' -import readline from 'readline' -import fs from 'fs-extra' -import os from 'os' -import path from 'path' -import rc from 'rc' -import semver from 'semver' -import workspace from '../workspace' -import download from './download' -import fetch from './fetch' -import { statAsync } from '../util/fs' -const logger = require('../util/logger')('model-installer') - -export interface Info { - 'dist.tarball'?: string - 'engines.coc'?: string - version?: string - name?: string -} - -function registryUrl(scope = 'coc.nvim'): string { - const result = rc('npm', { registry: 'https://registry.npmjs.org/' }) - const registry = result[`${scope}:registry`] || result.config_registry || result.registry as string - return registry.endsWith('/') ? registry : registry + '/' -} - -export class Installer extends EventEmitter { - private name: string - private url: string - private version: string - constructor( - private root: string, - private npm: string, - // could be url or name@version or name - private def: string - ) { - super() - if (!fs.existsSync(root)) fs.mkdirpSync(root) - if (/^https?:/.test(def)) { - this.url = def - } else { - if (def.startsWith('@')) { - // @author/package - const idx = def.indexOf('@', 1) - if (idx > 1) { - // @author/package@1.0.0 - this.name = def.substring(0, idx) - this.version = def.substring(idx + 1) - } else { - this.name = def - } - } else { - if (def.includes('@')) { - // name@1.0.0 - let [name, version] = def.split('@', 2) - this.name = name - this.version = version - } else { - this.name = def - } - } - } - } - - public get info() { - return { name: this.name, version: this.version } - } - - public async install(): Promise { - this.log(`Using npm from: ${this.npm}`) - let info = await this.getInfo() - logger.info(`Fetched info of ${this.def}`, info) - let { name } = info - let required = info['engines.coc'] ? info['engines.coc'].replace(/^\^/, '>=') : '' - if (required && !semver.satisfies(workspace.version, required)) { - throw new Error(`${name} ${info.version} requires coc.nvim >= ${required}, please update coc.nvim.`) - } - await this.doInstall(info) - return name - } - - public async update(url?: string): Promise { - this.url = url - let folder = path.join(this.root, this.name) - let stat = await fs.lstat(folder) - if (stat.isSymbolicLink()) { - this.log(`Skipped update for symbol link`) - return - } - let version: string - if (fs.existsSync(path.join(folder, 'package.json'))) { - let content = await fs.readFile(path.join(folder, 'package.json'), 'utf8') - version = JSON.parse(content).version - } - this.log(`Using npm from: ${this.npm}`) - let info = await this.getInfo() - if (version && info.version && semver.gte(version, info.version)) { - this.log(`Current version ${version} is up to date.`) - return - } - let required = info['engines.coc'] ? info['engines.coc'].replace(/^\^/, '>=') : '' - if (required && !semver.satisfies(workspace.version, required)) { - throw new Error(`${info.version} requires coc.nvim ${required}, please update coc.nvim.`) - } - await this.doInstall(info) - let jsonFile = path.join(this.root, info.name, 'package.json') - if (fs.existsSync(jsonFile)) { - this.log(`Updated to v${info.version}`) - return path.dirname(jsonFile) - } else { - throw new Error(`Package.json not found: ${jsonFile}`) - } - } - - private async doInstall(info: Info): Promise { - let folder = path.join(this.root, info.name) - if (fs.existsSync(folder)) { - let stat = fs.statSync(folder) - if (!stat.isDirectory()) { - this.log(`${folder} is not directory skipped install`) - return - } - } - let tmpFolder = await fs.mkdtemp(path.join(os.tmpdir(), `${info.name.replace('/', '-')}-`)) - let url = info['dist.tarball'] - this.log(`Downloading from ${url}`) - await download(url, { dest: tmpFolder, onProgress: p => this.log(`Download progress ${p}%`, true), extract: 'untar' }) - this.log(`Extension download at ${tmpFolder}`) - let content = await fs.readFile(path.join(tmpFolder, 'package.json'), 'utf8') - let { dependencies } = JSON.parse(content) - if (dependencies && Object.keys(dependencies).length) { - let p = new Promise((resolve, reject) => { - let args = ['install', '--ignore-scripts', '--no-lockfile', '--production', '--no-global'] - if (url.startsWith('https://github.com')) { - args = ['install'] - } - if ((this.npm.endsWith('npm') || this.npm.endsWith('npm.CMD')) && !this.npm.endsWith('pnpm')) { - args.push('--legacy-peer-deps') - } - if (this.npm.endsWith('yarn')) { - args.push('--ignore-engines') - } - this.log(`Installing dependencies by: ${this.npm} ${args.join(' ')}.`) - const child = spawn(this.npm, args, { - cwd: tmpFolder, - }) - const rl = readline.createInterface({ - input: child.stdout - }) - rl.on('line', line => { - this.log(`[npm] ${line}`, true) - }) - child.stderr.setEncoding('utf8') - child.stdout.setEncoding('utf8') - child.on('error', reject) - let err = '' - child.stderr.on('data', data => { - err += data - }) - child.on('exit', code => { - if (code) { - if (err) this.log(err) - reject(new Error(`${this.npm} install exited with ${code}`)) - return - } - resolve() - }) - }) - await p - } - let jsonFile = path.resolve(this.root, global.hasOwnProperty('__TEST__') ? '' : '..', 'package.json') - let errors: ParseError[] = [] - let obj = parse(fs.readFileSync(jsonFile, 'utf8'), errors, { allowTrailingComma: true }) - if (errors && errors.length > 0) { - throw new Error(`Error on load ${jsonFile}`) - } - obj.dependencies = obj.dependencies || {} - if (this.url) { - obj.dependencies[info.name] = this.url - } else { - obj.dependencies[info.name] = '>=' + info.version - } - const sortedObj = { dependencies: {} } - Object.keys(obj.dependencies).sort().forEach(k => { - sortedObj.dependencies[k] = obj.dependencies[k] - }) - let stat = await statAsync(folder) - if (stat) { - if (stat.isDirectory()) { - fs.removeSync(folder) - } else { - fs.unlinkSync(folder) - } - } - await fs.move(tmpFolder, folder, { overwrite: true }) - await fs.writeFile(jsonFile, JSON.stringify(sortedObj, null, 2), { encoding: 'utf8' }) - this.log(`Update package.json at ${jsonFile}`) - this.log(`Installed extension ${this.name}@${info.version} at ${folder}`) - } - - private async getInfo(): Promise { - if (this.url) return await this.getInfoFromUri() - let registry = registryUrl() - this.log(`Get info from ${registry}`) - let buffer = await fetch(registry + this.name, { timeout: 10000, buffer: true }) - let res = JSON.parse(buffer.toString()) - if (!this.version) this.version = res['dist-tags']['latest'] - let obj = res['versions'][this.version] - if (!obj) throw new Error(`${this.def} doesn't exists in ${registry}.`) - let requiredVersion = obj['engines'] && obj['engines']['coc'] - if (!requiredVersion) { - throw new Error(`${this.def} is not valid coc extension, "engines" field with coc property required.`) - } - return { - 'dist.tarball': obj['dist']['tarball'], - 'engines.coc': requiredVersion, - version: obj['version'], - name: res.name - } as Info - } - - private async getInfoFromUri(): Promise { - let { url } = this - if (!url.includes('github.com')) { - throw new Error(`"${url}" is not supported, coc.nvim support github.com only`) - } - url = url.replace(/\/$/, '') - let branch = 'master' - if (url.includes('@')) { - // https://github.com/sdras/vue-vscode-snippets@main - let idx = url.indexOf('@') - branch = url.substr(idx + 1) - url = url.substring(0, idx) - } - let fileUrl = url.replace('github.com', 'raw.githubusercontent.com') + `/${branch}/package.json` - this.log(`Get info from ${fileUrl}`) - let content = await fetch(fileUrl, { timeout: 10000 }) - let obj = typeof content == 'string' ? JSON.parse(content) : content - this.name = obj.name - return { - 'dist.tarball': `${url}/archive/${branch}.tar.gz`, - 'engines.coc': obj['engines'] ? obj['engines']['coc'] : null, - name: obj.name, - version: obj.version - } - } - - private log(msg: string, isProgress = false): void { - logger.info(msg) - this.emit('message', msg, isProgress) - } -} - -export function createInstallerFactory(npm: string, root: string): (def: string) => Installer { - return (def): Installer => new Installer(root, npm, def) -} diff --git a/vim-config/plugins/coc.nvim/src/model/memos.ts b/vim-config/plugins/coc.nvim/src/model/memos.ts deleted file mode 100644 index 6f72a135..00000000 --- a/vim-config/plugins/coc.nvim/src/model/memos.ts +++ /dev/null @@ -1,64 +0,0 @@ -import fs from 'fs' -import { readFile, statAsync } from '../util/fs' -import { deepClone } from '../util/object' -const logger = require('../util/logger')('model-memos') - -/** - * A memento represents a storage utility. It can store and retrieve - * values. - */ -export interface Memento { - get(key: string): T | undefined - get(key: string, defaultValue: T): T - update(key: string, value: any): Promise -} - -export default class Memos { - constructor(private filepath: string) { - if (!fs.existsSync(filepath)) { - fs.writeFileSync(filepath, '{}', 'utf8') - } - } - - private fetchContent(id: string, key: string): any { - try { - let content = fs.readFileSync(this.filepath, 'utf8') - let res = JSON.parse(content) - let obj = res[id] - if (!obj) return undefined - return obj[key] - } catch (e) { - return undefined - } - } - - private async update(id: string, key: string, value: any): Promise { - let { filepath } = this - try { - let content = fs.readFileSync(filepath, 'utf8') - let current = content ? JSON.parse(content) : {} - current[id] = current[id] || {} - if (value !== undefined) { - current[id][key] = deepClone(value) - } else { - delete current[id][key] - } - content = JSON.stringify(current, null, 2) - fs.writeFileSync(filepath, content, 'utf8') - } catch (e) { - logger.error(`Error on update memos:`, e) - } - } - - public createMemento(id: string): Memento { - return { - get: (key: string, defaultValue?: T): T | undefined => { - let res = this.fetchContent(id, key) - return res === undefined ? defaultValue : res - }, - update: async (key: string, value: any): Promise => { - await this.update(id, key, value) - } - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/menu.ts b/vim-config/plugins/coc.nvim/src/model/menu.ts deleted file mode 100644 index b9a53706..00000000 --- a/vim-config/plugins/coc.nvim/src/model/menu.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import { CancellationToken, Disposable, Emitter, Event } from 'vscode-languageserver-protocol' -import events from '../events' -import { disposeAll } from '../util' -import { DialogPreferences } from './dialog' -import Popup from './popup' -const logger = require('../util/logger')('model-menu') - -export interface MenuConfig { - items: string[] - title?: string -} - -/** - * Select single item from menu at cursor position. - */ -export default class Menu { - private bufnr: number - private win: Popup - private currIndex = 0 - private total: number - private disposables: Disposable[] = [] - private keyMappings: Map void> = new Map() - private readonly _onDidClose = new Emitter() - public readonly onDidClose: Event = this._onDidClose.event - constructor(private nvim: Neovim, private config: MenuConfig, token?: CancellationToken) { - this.total = config.items.length - if (token) { - token.onCancellationRequested(() => { - this.win?.close() - }) - } - this.disposables.push(this._onDidClose) - this.addKeymappings() - } - - private attachEvents(): void { - events.on('InputChar', this.onInputChar.bind(this), null, this.disposables) - events.on('BufWinLeave', bufnr => { - if (bufnr == this.bufnr) { - this._onDidClose.fire(-1) - this.bufnr = undefined - this.win = undefined - this.dispose() - } - }, null, this.disposables) - } - - private addKeymappings(): void { - let { nvim } = this - this.addKeys(['', ''], () => { - this._onDidClose.fire(-1) - this.dispose() - }) - this.addKeys(['\r', ''], () => { - this._onDidClose.fire(this.currIndex) - this.dispose() - }) - let setCursorIndex = idx => { - if (!this.win) return - nvim.pauseNotification() - this.setCursor(idx) - this.win?.refreshScrollbar() - nvim.command('redraw', true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } - this.addKeys('', async () => { - await this.win?.scrollForward() - }) - this.addKeys('', async () => { - await this.win?.scrollBackward() - }) - this.addKeys(['j', '', '', ''], () => { - // next - let idx = this.currIndex == this.total - 1 ? 0 : this.currIndex + 1 - setCursorIndex(idx) - }) - this.addKeys(['k', '', '', ''], () => { - // previous - let idx = this.currIndex == 0 ? this.total - 1 : this.currIndex - 1 - setCursorIndex(idx) - }) - this.addKeys(['g'], () => { - setCursorIndex(0) - }) - this.addKeys(['G'], () => { - setCursorIndex(this.total - 1) - }) - let timer: NodeJS.Timeout - let firstNumber: number - this.addKeys(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], character => { - if (timer) clearTimeout(timer) - let n = parseInt(character, 10) - if (isNaN(n) || n > this.total) return - if (firstNumber == null && n == 0) return - if (firstNumber) { - let count = firstNumber * 10 + n - firstNumber = undefined - this._onDidClose.fire(count - 1) - this.dispose() - return - } - if (this.total < 10 || n * 10 > this.total) { - this._onDidClose.fire(n - 1) - this.dispose() - return - } - timer = setTimeout(async () => { - this._onDidClose.fire(n - 1) - this.dispose() - }, 200) - firstNumber = n - }) - } - - public async show(preferences: DialogPreferences = {}): Promise { - let { nvim } = this - let { title, items } = this.config - let opts: any = {} - if (title) opts.title = title - if (preferences.maxHeight) opts.maxHeight = preferences.maxHeight - if (preferences.maxWidth) opts.maxWidth = preferences.maxWidth - if (preferences.floatHighlight) opts.highlight = preferences.floatHighlight - if (preferences.floatBorderHighlight) opts.borderhighlight = [preferences.floatBorderHighlight] - let lines = items.map((v, i) => { - if (i < 99) return `${i + 1}. ${v}` - return v - }) - if (preferences.confirmKey && preferences.confirmKey != '') { - this.addKeys(preferences.confirmKey, () => { - this._onDidClose.fire(this.currIndex) - this.dispose() - }) - } - let res = await nvim.call('coc#float#create_menu', [lines, opts]) as [number, number] - this.win = new Popup(nvim, res[0], res[1]) - this.bufnr = res[1] - this.attachEvents() - nvim.call('coc#prompt#start_prompt', ['menu'], true) - return res[0] - } - - public get buffer(): Buffer { - return this.bufnr ? this.nvim.createBuffer(this.bufnr) : undefined - } - - public dispose(): void { - disposeAll(this.disposables) - this.disposables = [] - this.nvim.call('coc#prompt#stop_prompt', ['menu'], true) - this.win?.close() - this.win = undefined - } - - private async onInputChar(session: string, character: string): Promise { - if (session != 'menu' || !this.win) return - let fn = this.keyMappings.get(character) - if (fn) { - await Promise.resolve(fn(character)) - } else { - logger.warn(`Ignored key press: ${character}`) - } - } - - private setCursor(index: number): void { - if (!this.win) return - this.currIndex = index - this.win.setCursor(index) - } - - private addKeys(keys: string | string[], fn: (character: string) => void): void { - if (Array.isArray(keys)) { - for (let key of keys) { - this.keyMappings.set(key, fn) - } - } else { - this.keyMappings.set(keys, fn) - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/mru.ts b/vim-config/plugins/coc.nvim/src/model/mru.ts deleted file mode 100644 index b405bd54..00000000 --- a/vim-config/plugins/coc.nvim/src/model/mru.ts +++ /dev/null @@ -1,69 +0,0 @@ -import path from 'path' -import fs from 'fs-extra' - -/** - * Mru - manage string items as lines in mru file. - */ -export default class Mru { - private file: string - - /** - * @param {string} name unique name - * @param {string} base? optional directory name, default to config root of coc.nvim - */ - constructor(private name: string, base?: string) { - this.file = path.join(base || process.env.COC_DATA_HOME, name) - } - - /** - * Load iems from mru file - */ - public async load(): Promise { - let dir = path.dirname(this.file) - try { - fs.mkdirpSync(dir) - if (!fs.existsSync(this.file)) { - fs.writeFileSync(this.file, '', 'utf8') - } - let content = await fs.readFile(this.file, 'utf8') - content = content.trim() - return content.length ? content.trim().split('\n') : [] - } catch (e) { - return [] - } - } - - /** - * Add item to mru file. - */ - public async add(item: string): Promise { - let items = await this.load() - let idx = items.indexOf(item) - if (idx !== -1) items.splice(idx, 1) - items.unshift(item) - fs.writeFileSync(this.file, items.join('\n'), 'utf8') - } - - /** - * Remove item from mru file. - */ - public async remove(item: string): Promise { - let items = await this.load() - let idx = items.indexOf(item) - if (idx !== -1) { - items.splice(idx, 1) - fs.writeFileSync(this.file, items.join('\n'), 'utf8') - } - } - - /** - * Remove the data file. - */ - public async clean(): Promise { - try { - await fs.unlink(this.file) - } catch (e) { - // noop - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/notification.ts b/vim-config/plugins/coc.nvim/src/model/notification.ts deleted file mode 100644 index 32331198..00000000 --- a/vim-config/plugins/coc.nvim/src/model/notification.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import events from '../events' -import { disposeAll } from '../util' -import { DialogButton } from './dialog' -const isVim = process.env.VIM_NODE_RPC == '1' -const logger = require('../util/logger')('model-notification') - -export interface NotificationPreferences { - top: number - right: number - maxWidth: number - maxHeight: number - highlight: string - minProgressWidth: number -} - -export interface NotificationConfig { - content: string - /** - * Optional title text. - */ - title?: string - /** - * Timeout in miliseconds to dismiss notification. - */ - timeout?: number - /** - * show close button, default to true when not specified. - */ - close?: boolean - /** - * highlight groups for border, default to `"dialog.borderhighlight"` or 'CocFlating' - */ - borderhighlight?: string - /** - * Buttons as bottom of dialog. - */ - buttons?: DialogButton[] - /** - * index is -1 for window close without button click - */ - callback?: (index: number) => void -} - -export default class Notification { - protected disposables: Disposable[] = [] - protected bufnr: number - protected _winid: number - protected _disposed = false - constructor(protected nvim: Neovim, protected config: NotificationConfig, attachEvents = true) { - if (attachEvents) { - events.on('BufWinLeave', bufnr => { - if (bufnr == this.bufnr) { - this.dispose() - if (config.callback) config.callback(-1) - } - }, null, this.disposables) - events.on('FloatBtnClick', (bufnr, idx) => { - if (bufnr == this.bufnr) { - this.dispose() - let btns = config?.buttons.filter(o => o.disabled != true) - if (config.callback) config.callback(btns[idx].index) - } - }, null, this.disposables) - } - } - - protected get lines(): string[] { - return this.config.content.split(/\r?\n/) - } - - public async show(preferences: Partial): Promise { - let { nvim } = this - let { title, close, timeout, buttons, borderhighlight } = this.config - let opts: any = Object.assign({}, preferences) - opts.close = close ? 1 : 0 - if (title) opts.title = title - if (borderhighlight) opts.borderhighlight = borderhighlight - if (buttons) opts.buttons = buttons.filter(o => !o.disabled).map(o => o.text) - if (timeout) opts.timeout = timeout - let res = await nvim.call('coc#float#create_notification', [this.lines, opts]) as [number, number] - if (!res) return false - if (this._disposed) { - this.nvim.call('coc#float#close', [res[0]], true) - if (isVim) this.nvim.command('redraw', true) - } else { - this._winid = res[0] - this.bufnr = res[1] - } - return this._winid != undefined - } - - public get winid(): number | undefined { - return this._winid - } - - public dispose(): void { - if (this._disposed) return - this._disposed = true - let { winid } = this - if (winid) { - this.nvim.call('coc#float#close', [winid], true) - if (isVim) this.nvim.command('redraw', true) - } - this.bufnr = undefined - this._winid = undefined - disposeAll(this.disposables) - this.disposables = [] - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/outputChannel.ts b/vim-config/plugins/coc.nvim/src/model/outputChannel.ts deleted file mode 100644 index 6ec409c7..00000000 --- a/vim-config/plugins/coc.nvim/src/model/outputChannel.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { Disposable } from 'vscode-languageserver-protocol' -import { OutputChannel } from '../types' -import { disposeAll } from '../util' -const logger = require('../util/logger')('outpubChannel') - -export default class BufferChannel implements OutputChannel { - private lines: string[] = [''] - private disposables: Disposable[] = [] - private _disposed = false - public created = false - constructor(public name: string, private nvim: Neovim, private onDispose?: () => void) { - } - - public get content(): string { - return this.lines.join('\n') - } - - private _append(value: string): void { - let { nvim } = this - let idx = this.lines.length - 1 - let newlines = value.split(/\r?\n/) - let lastline = this.lines[idx] + newlines[0] - this.lines[idx] = lastline - let append = newlines.slice(1) - this.lines = this.lines.concat(append) - if (!this.created) return - nvim.pauseNotification() - nvim.call('setbufline', [this.bufname, '$', lastline], true) - if (append.length) { - nvim.call('appendbufline', [this.bufname, '$', append], true) - } - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } - - public append(value: string): void { - if (!this.validate()) return - this._append(value) - } - - public appendLine(value: string): void { - if (!this.validate()) return - this._append(value + '\n') - } - - public clear(keep?: number): void { - if (!this.validate()) return - let { nvim } = this - this.lines = keep ? this.lines.slice(-keep) : [] - if (!this.created) return - nvim.pauseNotification() - nvim.call('deletebufline', [this.bufname, 1, '$'], true) - if (this.lines.length) { - nvim.call('appendbufline', [this.bufname, '$', this.lines], true) - } - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } - - public hide(): void { - this.created = false - this.nvim.command(`exe 'silent! bd! '.fnameescape('${this.bufname}')`, true) - } - - private get bufname(): string { - return `output:///${this.name}` - } - - public show(preserveFocus?: boolean): void { - let { nvim } = this - nvim.pauseNotification() - nvim.command(`exe 'vsplit '.fnameescape('${this.bufname}')`, true) - if (preserveFocus) { - nvim.command('wincmd p', true) - } - nvim.command('redraw', true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - this.created = true - } - - private validate(): boolean { - return !this._disposed - } - - public dispose(): void { - if (this.onDispose) this.onDispose() - this._disposed = true - this.hide() - this.lines = [] - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/picker.ts b/vim-config/plugins/coc.nvim/src/model/picker.ts deleted file mode 100644 index 875b8b2d..00000000 --- a/vim-config/plugins/coc.nvim/src/model/picker.ts +++ /dev/null @@ -1,284 +0,0 @@ -import { Buffer, Neovim } from '@chemzqm/neovim' -import { CancellationToken, Disposable, Emitter, Event } from 'vscode-languageserver-protocol' -import events from '../events' -import { disposeAll } from '../util' -import { byteLength } from '../util/string' -import { DialogPreferences } from './dialog' -import Popup from './popup' -const logger = require('../util/logger')('model-dialog') -const isVim = process.env.VIM_NODE_RPC == '1' - -interface PickerConfig { - title: string - items: QuickPickItem[] -} - -/** - * Represents an item that can be selected from - * a list of items. - */ -export interface QuickPickItem { - - /** - * A human-readable string which is rendered prominent - */ - label: string - - /** - * A human-readable string which is rendered less prominent in the same line - */ - description?: string - - /** - * Optional flag indicating if this item is picked initially. - */ - picked?: boolean -} - -/** - * Pick multiple items from dialog - */ -export default class Picker { - private bufnr: number - private win: Popup | undefined - private picked: Set = new Set() - private currIndex = 0 - private total: number - private disposables: Disposable[] = [] - private keyMappings: Map void> = new Map() - private readonly _onDidClose = new Emitter() - public readonly onDidClose: Event = this._onDidClose.event - constructor(private nvim: Neovim, private config: PickerConfig, token?: CancellationToken) { - for (let i = 0; i < config.items.length; i++) { - let item = config.items[i] - if (item.picked) this.picked.add(i) - } - this.total = config.items.length - if (token) { - token.onCancellationRequested(() => { - this.win?.close() - }) - } - this.disposables.push(this._onDidClose) - this.addKeymappings() - } - - private attachEvents(): void { - events.on('InputChar', this.onInputChar.bind(this), null, this.disposables) - events.on('BufWinLeave', bufnr => { - if (bufnr == this.bufnr) { - this._onDidClose.fire(undefined) - this.bufnr = undefined - this.win = undefined - this.dispose() - } - }, null, this.disposables) - events.on('FloatBtnClick', (bufnr, idx) => { - if (bufnr == this.bufnr) { - if (idx == 0) { - let selected = Array.from(this.picked) - this._onDidClose.fire(selected.length ? selected : undefined) - } else { - this._onDidClose.fire(undefined) - } - this.dispose() - } - }, null, this.disposables) - } - - private addKeymappings(): void { - let { nvim } = this - const toggleSelect = idx => { - if (this.picked.has(idx)) { - this.picked.delete(idx) - } else { - this.picked.add(idx) - } - } - this.addKeys('', async () => { - // not work on vim - if (isVim || !this.win) return - let [winid, lnum, col] = await nvim.eval('[v:mouse_winid,v:mouse_lnum,v:mouse_col]') as [number, number, number] - // can't simulate vvar. - if (global.hasOwnProperty('__TEST__')) { - let res = await nvim.getVar('mouse_position') - winid = res[0] - lnum = res[1] - col = res[2] - } - nvim.pauseNotification() - if (winid == this.win.winid) { - if (col <= 3) { - toggleSelect(lnum - 1) - this.changeLine(lnum - 1) - } else { - this.setCursor(lnum - 1) - } - } - nvim.call('win_gotoid', [winid], true) - nvim.call('cursor', [lnum, col], true) - nvim.call('coc#float#nvim_float_click', [], true) - nvim.command('redraw', true) - await nvim.resumeNotification() - }) - this.addKeys(['', ''], () => { - this._onDidClose.fire(undefined) - this.dispose() - }) - this.addKeys('', () => { - if (this.picked.size == 0) { - this._onDidClose.fire(undefined) - } else { - let selected = Array.from(this.picked) - this._onDidClose.fire(selected) - } - this.dispose() - }) - let setCursorIndex = idx => { - nvim.pauseNotification() - this.setCursor(idx) - this.win.refreshScrollbar() - nvim.command('redraw', true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } - this.addKeys(['j', '', '', ''], () => { - // next - let idx = this.currIndex == this.total - 1 ? 0 : this.currIndex + 1 - setCursorIndex(idx) - }) - this.addKeys(['k', '', '', ''], () => { - // previous - let idx = this.currIndex == 0 ? this.total - 1 : this.currIndex - 1 - setCursorIndex(idx) - }) - this.addKeys(['g'], () => { - setCursorIndex(0) - }) - this.addKeys(['G'], () => { - setCursorIndex(this.total - 1) - }) - this.addKeys(' ', async () => { - let idx = this.currIndex - toggleSelect(idx) - nvim.pauseNotification() - this.changeLine(idx) - if (this.currIndex != this.total - 1) { - this.setCursor(this.currIndex + 1) - } - nvim.command('redraw', true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - await nvim.resumeNotification() - }) - this.addKeys('', async () => { - await this.win?.scrollForward() - }) - this.addKeys('', async () => { - await this.win?.scrollBackward() - }) - } - - public async show(preferences: DialogPreferences = {}): Promise { - let { nvim } = this - let { title, items } = this.config - let opts: any = { close: 1, cursorline: 1 } - if (preferences.maxHeight) opts.maxHeight = preferences.maxHeight - if (preferences.maxWidth) opts.maxWidth = preferences.maxWidth - if (title) opts.title = title - opts.close = 1 - opts.cursorline = 1 - if (preferences.floatHighlight) { - opts.highlight = preferences.floatHighlight - } - if (preferences.floatBorderHighlight) { - opts.borderhighlight = [preferences.floatBorderHighlight] - } - if (preferences.pickerButtons) { - let shortcut = preferences.pickerButtonShortcut - opts.buttons = ['Submit' + (shortcut ? ' ' : ''), 'Cancel' + (shortcut ? ' ' : '')] - } - if (preferences.confirmKey && preferences.confirmKey != '') { - this.addKeys(preferences.confirmKey, () => { - this._onDidClose.fire(undefined) - this.dispose() - }) - } - let lines = [] - let positions: [number, number][] = [] - for (let i = 0; i < items.length; i++) { - let item = items[i] - let line = `[${item.picked ? 'x' : ' '}] ${item.label}` - positions.push([i, byteLength(line)]) - if (item.description) line = line + ` ${item.description}` - lines.push(line) - } - let res = await nvim.call('coc#float#create_dialog', [lines, opts]) as [number, number] - this.win = new Popup(nvim, res[0], res[1]) - this.bufnr = res[1] - this.attachEvents() - let buf = nvim.createBuffer(this.bufnr) - nvim.pauseNotification() - for (let pos of positions) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - buf.addHighlight({ hlGroup: 'Comment', line: pos[0], srcId: 1, colStart: pos[1], colEnd: -1 }) - } - nvim.command('redraw', true) - await nvim.resumeNotification() - nvim.call('coc#prompt#start_prompt', ['picker'], true) - return res[0] - } - - public get buffer(): Buffer { - return this.bufnr ? this.nvim.createBuffer(this.bufnr) : undefined - } - - public dispose(): void { - this.picked.clear() - this.keyMappings.clear() - disposeAll(this.disposables) - this.nvim.call('coc#prompt#stop_prompt', ['picker'], true) - this.win?.close() - this.win = undefined - } - - private async onInputChar(session: string, character: string): Promise { - if (session != 'picker' || !this.win) return - let fn = this.keyMappings.get(character) - if (fn) { - await Promise.resolve(fn(character)) - } else { - logger.warn(`Ignored key press: ${character}`) - } - } - - private changeLine(index: number): void { - let { nvim } = this - let item = this.config.items[index] - if (!item) return - let line = `[${this.picked.has(index) ? 'x' : ' '}] ${item.label}` - let col = byteLength(line) - if (item.description) line = line + ` ${item.description}` - nvim.call('setbufline', [this.bufnr, index + 1, line], true) - if (!isVim) { - let buf = nvim.createBuffer(this.bufnr) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - buf.addHighlight({ hlGroup: 'Comment', line: index, srcId: 1, colStart: col, colEnd: -1 }) - } - } - - private setCursor(index: number): void { - if (!this.win) return - this.currIndex = index - this.win.setCursor(index) - } - - private addKeys(keys: string | string[], fn: (character: string) => void): void { - if (Array.isArray(keys)) { - for (let key of keys) { - this.keyMappings.set(key, fn) - } - } else { - this.keyMappings.set(keys, fn) - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/popup.ts b/vim-config/plugins/coc.nvim/src/model/popup.ts deleted file mode 100644 index 2437c566..00000000 --- a/vim-config/plugins/coc.nvim/src/model/popup.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -const isVim = process.env.VIM_NODE_RPC == '1' - -/** - * More methods for float window/popup - */ -export default class Popup { - constructor( - private nvim: Neovim, - public readonly winid, - public readonly bufnr) { - } - - public get valid(): Promise { - return this.nvim.call('coc#float#valid', [this.winid]).then(res => { - return !!res - }) - } - - public close(): void { - this.nvim.call('coc#float#close', [this.winid], true) - } - - public refreshScrollbar(): void { - if (!isVim) this.nvim.call('coc#float#nvim_scrollbar', [this.winid], true) - } - - public execute(cmd: string): void { - this.nvim.call('coc#compat#execute', [this.winid, cmd], true) - } - - /** - * Simple scroll method, not consider wrapped lines. - */ - public async scrollForward(): Promise { - let { nvim, bufnr, winid } = this - let buf = nvim.createBuffer(bufnr) - let total = await buf.length - let botline: number - if (!isVim) { - let infos = await nvim.call('getwininfo', [winid]) - if (!infos || !infos.length) return - botline = infos[0].botline - } else { - botline = await nvim.eval(`get(popup_getpos(${winid}), 'lastline', 0)`) as number - } - if (botline >= total || botline == 0) return - nvim.pauseNotification() - this.setCursor(botline - 1) - this.execute(`silent! noa setl scrolloff=0`) - this.execute(`normal! ${botline}Gzt`) - this.refreshScrollbar() - nvim.command('redraw', true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } - - /** - * Simple scroll method, not consider wrapped lines. - */ - public async scrollBackward(): Promise { - let { nvim, winid } = this - let topline: number - if (!isVim) { - let infos = await nvim.call('getwininfo', [winid]) - if (!infos || !infos.length) return - topline = infos[0].topline - } else { - topline = await nvim.eval(`get(popup_getpos(${winid}), 'firstline', 0)`) as number - } - if (topline == 1) return - nvim.pauseNotification() - this.setCursor(topline - 1) - this.execute(`normal! ${topline}Gzb`) - this.refreshScrollbar() - nvim.command('redraw', true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } - - /** - * Move cursor and highlight. - */ - public setCursor(index: number): void { - let { nvim, bufnr, winid } = this - if (isVim) { - nvim.call('win_execute', [winid, `exe ${index + 1}`], true) - } else { - let win = nvim.createWindow(winid) - win.notify('nvim_win_set_cursor', [[index + 1, 0]]) - nvim.command(`sign unplace 6 buffer=${bufnr}`, true) - nvim.command(`sign place 6 line=${index + 1} name=CocCurrentLine buffer=${bufnr}`, true) - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/progress.ts b/vim-config/plugins/coc.nvim/src/model/progress.ts deleted file mode 100644 index a29245a3..00000000 --- a/vim-config/plugins/coc.nvim/src/model/progress.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import Notification, { NotificationPreferences } from './notification' -import { CancellationToken, CancellationTokenSource } from 'vscode-languageserver-protocol' -import events from '../events' - -export interface ProgressOptions { - title?: string - cancellable?: boolean - task: (progress: Progress<{ message?: string; increment?: number }>, token: CancellationToken) => Thenable -} - -/** - * Defines a generalized way of reporting progress updates. - */ -export interface Progress { - - /** - * Report a progress update. - * - * @param value A progress item, like a message and/or an - * report on how much work finished - */ - report(value: T): void -} - -export default class ProgressNotification extends Notification { - private tokenSource: CancellationTokenSource - constructor(nvim: Neovim, private option: ProgressOptions) { - super(nvim, { - content: '\n', - close: option.cancellable == true, - title: option.title - }, false) - events.on('BufWinLeave', bufnr => { - if (bufnr == this.bufnr) { - if (this.tokenSource) { - this.tokenSource.cancel() - } - this.dispose() - } - }, null, this.disposables) - } - - public async show(preferences: Partial): Promise { - let { task } = this.option - let tokenSource = this.tokenSource = new CancellationTokenSource() - this.disposables.push(tokenSource) - let total = 0 - let res = await new Promise((resolve, reject) => { - tokenSource.token.onCancellationRequested(() => { - resolve(undefined) - }) - super.show(Object.assign({ minWidth: preferences.minProgressWidth || 30, progress: 1 }, preferences)).then(shown => { - if (!shown) reject(new Error('Failed to create float window')) - }).catch(reject) - task({ - report: p => { - if (!this.bufnr) return - let text = '' - if (p.message) text += p.message.replace(/\r?\n/g, ' ') - if (p.increment) { - total += p.increment - text = text + (text.length ? ` ${total}%` : `${total}%`) - } - this.nvim.call('setbufline', [this.bufnr, 2, text], true) - } - }, tokenSource.token).then(res => { - if (this._disposed) return - setTimeout(() => { - this.dispose() - }, 100) - resolve(res) - }, err => { - if (this._disposed) return - this.dispose() - if (err instanceof Error) { - reject(err) - } else { - resolve(undefined) - } - }) - }) - return res - } - - public dispose(): void { - super.dispose() - this.tokenSource = undefined - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/resolver.ts b/vim-config/plugins/coc.nvim/src/model/resolver.ts deleted file mode 100644 index 8b09007e..00000000 --- a/vim-config/plugins/coc.nvim/src/model/resolver.ts +++ /dev/null @@ -1,42 +0,0 @@ -import path from 'path' -import fs from 'fs' -import { executable, runCommand } from '../util' -import { statAsync } from '../util/fs' -import { memorize } from '../util/decorator' -import stripAnsi from 'strip-ansi' -const logger = require('../util/logger')('model-resolver') - -export default class Resolver { - - @memorize - private get nodeFolder(): Promise { - if (!executable('npm')) return Promise.resolve('') - return runCommand('npm --loglevel silent root -g', {}, 3000).then(root => { - return stripAnsi(root).trim() - }) - } - - @memorize - private get yarnFolder(): Promise { - if (!executable('yarnpkg')) return Promise.resolve('') - return runCommand('yarnpkg global dir', {}, 3000).then(root => { - let folder = path.join(stripAnsi(root).trim(), 'node_modules') - let exists = fs.existsSync(folder) - return exists ? folder : '' - }) - } - - public async resolveModule(mod: string): Promise { - let nodeFolder = await this.nodeFolder - let yarnFolder = await this.yarnFolder - if (yarnFolder) { - let s = await statAsync(path.join(yarnFolder, mod, 'package.json')) - if (s && s.isFile()) return path.join(yarnFolder, mod) - } - if (nodeFolder) { - let s = await statAsync(path.join(nodeFolder, mod, 'package.json')) - if (s && s.isFile()) return path.join(nodeFolder, mod) - } - return null - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/status.ts b/vim-config/plugins/coc.nvim/src/model/status.ts deleted file mode 100644 index 86533416..00000000 --- a/vim-config/plugins/coc.nvim/src/model/status.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { Disposable } from 'vscode-languageserver-protocol' -import { NeovimClient as Neovim } from '@chemzqm/neovim' -import { v1 as uuidv1 } from 'uuid' -const logger = require('../util/logger')('model-status') - -export const frames = ['โ ‹', 'โ ™', 'โ น', 'โ ธ', 'โ ผ', 'โ ด', 'โ ฆ', 'โ ง', 'โ ‡', 'โ '] - -export interface StatusBarItem { - /** - * The priority of this item. Higher value means the item should - * be shown more to the left. - */ - readonly priority: number - isProgress: boolean - text: string - show(): void - hide(): void - dispose(): void -} - -export default class StatusLine implements Disposable { - private items: Map = new Map() - private shownIds: Set = new Set() - private _text = '' - private interval: NodeJS.Timer - constructor(private nvim: Neovim) { - this.interval = setInterval(() => { - this.setStatusText().logError() - }, 100) - } - - public dispose(): void { - clearInterval(this.interval) - } - - public createStatusBarItem(priority = 0, isProgress = false): StatusBarItem { - let uid = uuidv1() - - let item: StatusBarItem = { - text: '', - priority, - isProgress, - show: () => { - this.shownIds.add(uid) - }, - hide: () => { - this.shownIds.delete(uid) - }, - dispose: () => { - this.shownIds.delete(uid) - this.items.delete(uid) - } - } - this.items.set(uid, item) - return item - } - - private getText(): string { - if (this.shownIds.size == 0) return '' - let d = new Date() - let idx = Math.floor(d.getMilliseconds() / 100) - let text = '' - let items: StatusBarItem[] = [] - for (let [id, item] of this.items) { - if (this.shownIds.has(id)) { - items.push(item) - } - } - items.sort((a, b) => a.priority - b.priority) - for (let item of items) { - if (!item.isProgress) { - text = `${text} ${item.text}` - } else { - text = `${text} ${frames[idx]} ${item.text}` - } - } - return text - } - - private async setStatusText(): Promise { - let text = this.getText() - let { nvim } = this - if (text != this._text) { - this._text = text - nvim.pauseNotification() - this.nvim.setVar('coc_status', text, true) - this.nvim.call('coc#util#do_autocmd', ['CocStatusChange'], true) - await nvim.resumeNotification(false, true) - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/task.ts b/vim-config/plugins/coc.nvim/src/model/task.ts deleted file mode 100644 index 15439187..00000000 --- a/vim-config/plugins/coc.nvim/src/model/task.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import events from '../events' -import { Disposable, Emitter, Event } from 'vscode-languageserver-protocol' -import { disposeAll } from '../util' - -export interface TaskOptions { - cmd: string - args?: string[] - cwd?: string - pty?: boolean - env?: { [key: string]: string } - detach?: boolean -} - -/** - * Controls long running task started by vim. - * Useful to keep the task running after CocRestart. - * - * @public - */ -export default class Task implements Disposable { - private disposables: Disposable[] = [] - private readonly _onExit = new Emitter() - private readonly _onStderr = new Emitter() - private readonly _onStdout = new Emitter() - public readonly onExit: Event = this._onExit.event - public readonly onStdout: Event = this._onStdout.event - public readonly onStderr: Event = this._onStderr.event - - /** - * @param {Neovim} nvim - * @param {string} id unique id - */ - constructor(private nvim: Neovim, private id: string) { - events.on('TaskExit', (id, code) => { - if (id == this.id) { - this._onExit.fire(code) - } - }, null, this.disposables) - events.on('TaskStderr', (id, lines) => { - if (id == this.id) { - this._onStderr.fire(lines) - } - }, null, this.disposables) - let stdout: string[] = [] - let timer: NodeJS.Timeout - events.on('TaskStdout', (id, lines) => { - if (id == this.id) { - if (timer) clearTimeout(timer) - stdout.push(...lines) - timer = setTimeout(() => { - this._onStdout.fire(stdout) - stdout = [] - }, 100) - } - }, null, this.disposables) - } - - /** - * Start task, task will be restarted when already running. - * - * @param {TaskOptions} opts - * @returns {Promise} - */ - public async start(opts: TaskOptions): Promise { - let { nvim } = this - return await nvim.call('coc#task#start', [this.id, opts]) - } - - /** - * Stop task by SIGTERM or SIGKILL - */ - public async stop(): Promise { - let { nvim } = this - await nvim.call('coc#task#stop', [this.id]) - } - - /** - * Check if the task is running. - */ - public get running(): Promise { - let { nvim } = this - return nvim.call('coc#task#running', [this.id]) - } - - /** - * Stop task and dispose all events. - */ - public dispose(): void { - let { nvim } = this - nvim.call('coc#task#stop', [this.id], true) - this._onStdout.dispose() - this._onStderr.dispose() - this._onExit.dispose() - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/terminal.ts b/vim-config/plugins/coc.nvim/src/model/terminal.ts deleted file mode 100644 index 7184a210..00000000 --- a/vim-config/plugins/coc.nvim/src/model/terminal.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -const logger = require('../util/logger')('model-terminal') - -export interface TerminalOptions { - /** - * A human-readable string which will be used to represent the terminal in the UI. - */ - name?: string - - /** - * A path to a custom shell executable to be used in the terminal. - */ - shellPath?: string - - /** - * Args for the custom shell executable, this does not work on Windows (see #8429) - */ - shellArgs?: string[] - - /** - * A path or URI for the current working directory to be used for the terminal. - */ - cwd?: string - - /** - * Object with environment variables that will be added to the VS Code process. - */ - env?: { [key: string]: string | null } - - /** - * Whether the terminal process environment should be exactly as provided in - * `TerminalOptions.env`. When this is false (default), the environment will be based on the - * window's environment and also apply configured platform settings like - * `terminal.integrated.windows.env` on top. When this is true, the complete environment - * must be provided as nothing will be inherited from the process or any configuration. - */ - strictEnv?: boolean -} - -export default class TerminalModel { - public bufnr: number - private pid = 0 - - constructor(private cmd: string, - private args: string[], - private nvim: Neovim, - private _name?: string) { - } - - public async start(cwd?: string, env?: { [key: string]: string | null }): Promise { - let { nvim } = this - let cmd = [this.cmd, ...this.args] - let [bufnr, pid] = await nvim.call('coc#terminal#start', [cmd, cwd, env || {}]) - this.bufnr = bufnr - this.pid = pid - } - - public get name(): string { - return this._name || this.cmd - } - - public get processId(): Promise { - return Promise.resolve(this.pid) - } - - public sendText(text: string, addNewLine = true): void { - if (!this.bufnr) return - this.nvim.call('coc#terminal#send', [this.bufnr, text, addNewLine], true) - } - - public async show(preserveFocus?: boolean): Promise { - let { bufnr, nvim } = this - if (!bufnr) return - let [loaded, winid, curr] = await nvim.eval(`[bufloaded(${bufnr}),bufwinid(${bufnr}),win_getid()]`) as [number, number, number] - if (!loaded) return false - if (curr == winid) return true - nvim.pauseNotification() - if (winid == -1) { - nvim.command(`below ${bufnr}sb`, true) - nvim.command('resize 8', true) - nvim.call('coc#util#do_autocmd', ['CocTerminalOpen'], true) - } else { - nvim.call('win_gotoid', [winid], true) - } - nvim.command('normal! G', true) - if (preserveFocus) { - nvim.command('wincmd p', true) - } - await nvim.resumeNotification() - return true - } - - public async hide(): Promise { - let { bufnr, nvim } = this - if (!bufnr) return - let winnr = await nvim.call('bufwinnr', bufnr) - if (winnr == -1) return - await nvim.command(`${winnr}close!`) - } - - public dispose(): void { - let { bufnr, nvim } = this - if (!bufnr) return - nvim.call('coc#terminal#close', [bufnr], true) - } -} diff --git a/vim-config/plugins/coc.nvim/src/model/textdocument.ts b/vim-config/plugins/coc.nvim/src/model/textdocument.ts deleted file mode 100644 index 7cc84283..00000000 --- a/vim-config/plugins/coc.nvim/src/model/textdocument.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { Position, Range } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' - -function computeLineOffsets(text: string, isAtLineStart: boolean, textOffset = 0): number[] { - const result: number[] = isAtLineStart ? [textOffset] : [] - for (let i = 0; i < text.length; i++) { - let ch = text.charCodeAt(i) - if (ch === 13 || ch === 10) { - if (ch === 13 && i + 1 < text.length && text.charCodeAt(i + 1) === 10) { - i++ - } - result.push(textOffset + i + 1) - } - } - return result -} - -/** - * Text document that created with readonly lines. - * - * Created for save memory since we could reuse readonly lines. - */ -export class LinesTextDocument implements TextDocument { - private _lineOffsets: number[] | undefined - constructor( - public readonly uri: string, - public readonly languageId: string, - public readonly version: number, - public readonly lines: ReadonlyArray, - private eol: boolean - ) { - - } - - private get _content(): string { - return this.lines.join('\n') + (this.eol ? '\n' : '') - } - - public get lineCount(): number { - return this.lines.length + (this.eol ? 1 : 0) - } - - public getText(range?: Range): string { - if (range) { - const start = this.offsetAt(range.start) - const end = this.offsetAt(range.end) - return this._content.substring(start, end) - } - return this._content - } - - public positionAt(offset: number): Position { - offset = Math.max(Math.min(offset, this._content.length), 0) - let lineOffsets = this.getLineOffsets() - let low = 0 - let high = lineOffsets.length - if (high === 0) { - return { line: 0, character: offset } - } - while (low < high) { - let mid = Math.floor((low + high) / 2) - if (lineOffsets[mid] > offset) { - high = mid - } else { - low = mid + 1 - } - } - // low is the least x for which the line offset is larger than the current offset - // or array.length if no line offset is larger than the current offset - let line = low - 1 - return { line, character: offset - lineOffsets[line] } - } - - public offsetAt(position: Position) { - let lineOffsets = this.getLineOffsets() - if (position.line >= lineOffsets.length) { - return this._content.length - } else if (position.line < 0) { - return 0 - } - let lineOffset = lineOffsets[position.line] - let nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length - return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset) - } - - private getLineOffsets(): number[] { - if (this._lineOffsets === undefined) { - this._lineOffsets = computeLineOffsets(this._content, true) - } - return this._lineOffsets - } -} diff --git a/vim-config/plugins/coc.nvim/src/plugin.ts b/vim-config/plugins/coc.nvim/src/plugin.ts deleted file mode 100644 index b8b4e739..00000000 --- a/vim-config/plugins/coc.nvim/src/plugin.ts +++ /dev/null @@ -1,370 +0,0 @@ -import { NeovimClient as Neovim } from '@chemzqm/neovim' -import { EventEmitter } from 'events' -import fs from 'fs' -import path from 'path' -import { CallHierarchyItem, CodeAction, CodeActionKind } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import commandManager from './commands' -import completion from './completion' -import Cursors from './cursors' -import diagnosticManager from './diagnostic/manager' -import events from './events' -import extensions from './extensions' -import Handler from './handler' -import listManager from './list/manager' -import services from './services' -import snippetManager from './snippets/manager' -import sources from './sources' -import { OutputChannel, PatternType } from './types' -import window from './window' -import workspace from './workspace' -const logger = require('./util/logger')('plugin') - -declare const REVISION - -export default class Plugin extends EventEmitter { - private _ready = false - private handler: Handler | undefined - private infoChannel: OutputChannel - private cursors: Cursors - private actions: Map = new Map() - - constructor(public nvim: Neovim) { - super() - Object.defineProperty(workspace, 'nvim', { - get: () => this.nvim - }) - workspace.onDidChangeWorkspaceFolders(() => { - nvim.setVar('WorkspaceFolders', workspace.folderPaths, true) - }) - this.cursors = new Cursors(nvim) - commandManager.init(nvim, this) - this.addAction('checkJsonExtension', () => { - if (extensions.has('coc-json')) return - window.showMessage(`Run :CocInstall coc-json for json intellisense`, 'more') - }) - this.addAction('rootPatterns', bufnr => { - let doc = workspace.getDocument(bufnr) - if (!doc) return null - return { - buffer: workspace.getRootPatterns(doc, PatternType.Buffer), - server: workspace.getRootPatterns(doc, PatternType.LanguageServer), - global: workspace.getRootPatterns(doc, PatternType.Global) - } - }) - this.addAction('getConfig', async key => { - let document = await workspace.document - return workspace.getConfiguration(key, document ? document.uri : undefined) - }) - this.addAction('doAutocmd', async (id: number, ...args: []) => { - let autocmd = (workspace as any).autocmds.get(id) as any - if (autocmd) { - try { - await Promise.resolve(autocmd.callback.apply(autocmd.thisArg, args)) - } catch (e) { - logger.error(`Error on autocmd ${autocmd.event}`, e) - window.showMessage(`Error on autocmd ${autocmd.event}: ${e.message}`) - } - } - }) - this.addAction('openLog', async () => { - let file = logger.getLogFile() - await workspace.jumpTo(URI.file(file).toString()) - }) - this.addAction('attach', () => workspace.attach()) - this.addAction('detach', () => workspace.detach()) - this.addAction('doKeymap', async (key: string, defaultReturn = '', pressed?: string) => { - let keymap = workspace.keymaps.get(key) - if (!keymap) { - logger.error(`keymap for ${key} not found`) - this.nvim.command(`silent! unmap ${pressed.startsWith('{') && pressed.endsWith('}') ? `<${pressed.slice(1, -1)}>` : pressed}`, true) - return defaultReturn - } - let [fn, repeat] = keymap - let res = await Promise.resolve(fn()) - if (repeat) await nvim.command(`silent! call repeat#set("\\(coc-${key})", -1)`) - return res ?? defaultReturn - }) - this.addAction('registExtensions', async (...folders: string[]) => { - for (let folder of folders) { - await extensions.loadExtension(folder) - } - }) - this.addAction('snippetCheck', async (checkExpand: boolean, checkJump: boolean) => { - if (checkExpand && !extensions.has('coc-snippets')) { - console.error('coc-snippets required for check expand status!') - return false - } - if (checkJump) { - let jumpable = snippetManager.jumpable() - if (jumpable) return true - } - if (checkExpand) { - let api = extensions.getExtensionApi('coc-snippets') as any - if (api && api.hasOwnProperty('expandable')) { - let expandable = await Promise.resolve(api.expandable()) - if (expandable) return true - } - } - return false - }) - this.addAction('snippetNext', () => snippetManager.nextPlaceholder()) - this.addAction('snippetPrev', () => snippetManager.previousPlaceholder()) - this.addAction('snippetCancel', () => snippetManager.cancel()) - this.addAction('openLocalConfig', () => window.openLocalConfig()) - this.addAction('showInfo', async () => { - if (!this.infoChannel) { - this.infoChannel = window.createOutputChannel('info') - } else { - this.infoChannel.clear() - } - let channel = this.infoChannel - channel.appendLine('## versions') - channel.appendLine('') - let out = await this.nvim.call('execute', ['version']) as string - let first = out.trim().split(/\r?\n/, 2)[0].replace(/\(.*\)/, '').trim() - channel.appendLine('vim version: ' + first + `${workspace.isVim ? ' ' + workspace.env.version : ''}`) - channel.appendLine('node version: ' + process.version) - channel.appendLine('coc.nvim version: ' + this.version) - channel.appendLine('coc.nvim directory: ' + path.dirname(__dirname)) - channel.appendLine('term: ' + (process.env.TERM_PROGRAM || process.env.TERM)) - channel.appendLine('platform: ' + process.platform) - channel.appendLine('') - channel.appendLine('## Log of coc.nvim') - channel.appendLine('') - let file = logger.getLogFile() - if (fs.existsSync(file)) { - let content = fs.readFileSync(file, { encoding: 'utf8' }) - channel.appendLine(content) - } - channel.show() - }) - this.addAction('findLocations', (id: string, method: string, params: any, openCommand?: string | false) => { - return this.handler.locations.findLocations(id, method, params, openCommand) - }) - this.addAction('hasProvider', id => this.handler.hasProvider(id)) - this.addAction('getTagList', () => this.handler.locations.getTagList()) - this.addAction('hasSelected', () => completion.hasSelected()) - this.addAction('listNames', () => listManager.names) - this.addAction('listDescriptions', () => listManager.descriptions) - this.addAction('listLoadItems', name => listManager.loadItems(name)) - this.addAction('search', (...args: string[]) => this.handler.refactor.search(args)) - this.addAction('cursorsSelect', (bufnr: number, kind: string, mode: string) => this.cursors.select(bufnr, kind, mode)) - this.addAction('fillDiagnostics', (bufnr: number) => diagnosticManager.setLocationlist(bufnr)) - this.addAction('saveRefactor', bufnr => this.handler.refactor.save(bufnr)) - this.addAction('commandList', () => this.handler.commands.getCommandList()) - this.addAction('selectSymbolRange', (inner: boolean, visualmode: string, supportedSymbols: string[]) => this.handler.symbols.selectSymbolRange(inner, visualmode, supportedSymbols)) - this.addAction('openList', (...args: string[]) => listManager.start(args)) - this.addAction('listResume', (name?: string) => listManager.resume(name)) - this.addAction('listCancel', () => listManager.cancel(true)) - this.addAction('listPrev', (name?: string) => listManager.previous(name)) - this.addAction('listNext', (name?: string) => listManager.next(name)) - this.addAction('listFirst', (name?: string) => listManager.first(name)) - this.addAction('listLast', (name?: string) => listManager.last(name)) - this.addAction('sendRequest', (id: string, method: string, params?: any) => services.sendRequest(id, method, params)) - this.addAction('sendNotification', (id: string, method: string, params?: any) => services.sendNotification(id, method, params)) - this.addAction('registNotification', (id: string, method: string) => services.registNotification(id, method)) - this.addAction('updateConfig', (section: string, val: any) => workspace.configurations.updateUserConfig({ [section]: val })) - this.addAction('links', () => this.handler.links.getLinks()) - this.addAction('openLink', () => this.handler.links.openCurrentLink()) - this.addAction('pickColor', () => this.handler.colors.pickColor()) - this.addAction('colorPresentation', () => this.handler.colors.pickPresentation()) - this.addAction('highlight', () => this.handler.documentHighlighter.highlight()) - this.addAction('fold', (kind?: string) => this.handler.fold.fold(kind)) - this.addAction('startCompletion', option => completion.startCompletion(option)) - this.addAction('stopCompletion', () => completion.stop(false)) - this.addAction('sourceStat', () => sources.sourceStats()) - this.addAction('refreshSource', name => sources.refresh(name)) - this.addAction('toggleSource', name => sources.toggleSource(name)) - this.addAction('diagnosticRefresh', bufnr => diagnosticManager.refresh(bufnr)) - this.addAction('diagnosticInfo', () => diagnosticManager.echoMessage()) - this.addAction('diagnosticToggle', () => diagnosticManager.toggleDiagnostic()) - this.addAction('diagnosticToggleBuffer', async (bufnr?: number) => { - if (!bufnr) bufnr = await nvim.call('bufnr', ['%']) - return diagnosticManager.toggleDiagnosticBuffer(bufnr) - }) - this.addAction('diagnosticNext', severity => diagnosticManager.jumpNext(severity)) - this.addAction('diagnosticPrevious', severity => diagnosticManager.jumpPrevious(severity)) - this.addAction('diagnosticPreview', () => diagnosticManager.preview()) - this.addAction('diagnosticList', () => diagnosticManager.getDiagnosticList()) - this.addAction('jumpDefinition', openCommand => this.handler.locations.gotoDefinition(openCommand)) - this.addAction('definitions', () => this.handler.locations.definitions()) - this.addAction('jumpDeclaration', openCommand => this.handler.locations.gotoDeclaration(openCommand)) - this.addAction('declarations', () => this.handler.locations.declarations()) - this.addAction('jumpImplementation', openCommand => this.handler.locations.gotoImplementation(openCommand)) - this.addAction('implementations', () => this.handler.locations.implementations()) - this.addAction('jumpTypeDefinition', openCommand => this.handler.locations.gotoTypeDefinition(openCommand)) - this.addAction('typeDefinitions', () => this.handler.locations.typeDefinitions()) - this.addAction('jumpReferences', openCommand => this.handler.locations.gotoReferences(openCommand)) - this.addAction('references', () => this.handler.locations.references()) - this.addAction('jumpUsed', openCommand => this.handler.locations.gotoReferences(openCommand, false)) - this.addAction('doHover', hoverTarget => this.handler.hover.onHover(hoverTarget)) - this.addAction('definitionHover', hoverTarget => this.handler.hover.definitionHover(hoverTarget)) - this.addAction('getHover', () => this.handler.hover.getHover()) - this.addAction('showSignatureHelp', () => this.handler.signature.triggerSignatureHelp()) - this.addAction('documentSymbols', async (bufnr?: number) => { - if (!bufnr) { - let doc = await workspace.document - bufnr = doc.bufnr - } - return await this.handler.symbols.getDocumentSymbols(bufnr) - }) - this.addAction('ensureDocument', async () => { - let doc = await workspace.document - return doc && doc.attached - }) - this.addAction('symbolRanges', () => this.handler.documentHighlighter.getSymbolsRanges()) - this.addAction('selectionRanges', () => this.handler.selectionRange.getSelectionRanges()) - this.addAction('rangeSelect', (visualmode, forward) => this.handler.selectionRange.selectRange(visualmode, forward)) - this.addAction('rename', newName => this.handler.rename.rename(newName)) - this.addAction('getWorkspaceSymbols', input => this.handler.symbols.getWorkspaceSymbols(input)) - this.addAction('resolveWorkspaceSymbol', symbolInfo => this.handler.symbols.resolveWorkspaceSymbol(symbolInfo)) - this.addAction('formatSelected', mode => this.handler.format.formatCurrentRange(mode)) - this.addAction('format', () => this.handler.format.formatCurrentBuffer()) - this.addAction('commands', () => this.handler.commands.getCommands()) - this.addAction('services', () => services.getServiceStats()) - this.addAction('toggleService', name => services.toggle(name)) - this.addAction('codeAction', (mode, only) => this.handler.codeActions.doCodeAction(mode, only)) - this.addAction('organizeImport', () => this.handler.codeActions.organizeImport()) - this.addAction('fixAll', () => this.handler.codeActions.doCodeAction(null, [CodeActionKind.SourceFixAll])) - // save actions send to vim, for provider resolve - let codeActions: CodeAction[] = [] - this.addAction('doCodeAction', codeAction => { - if (codeAction.index == null) { - throw new Error(`index should exists with codeAction`) - } - let action = codeActions[codeAction.index] - if (!action) throw new Error(`invalid codeAction index: ${codeAction.index}`) - return this.handler.codeActions.applyCodeAction(action) - }) - this.addAction('codeActions', async (mode, only) => { - codeActions = await this.handler.codeActions.getCurrentCodeActions(mode, only) - // save index for retreive - return codeActions.map((o, idx) => Object.assign({ index: idx }, o)) - }) - this.addAction('quickfixes', async mode => { - codeActions = await this.handler.codeActions.getCurrentCodeActions(mode, [CodeActionKind.QuickFix]) - return codeActions.map((o, idx) => Object.assign({ index: idx }, o)) - }) - this.addAction('codeLensAction', () => this.handler.codeLens.doAction()) - this.addAction('runCommand', (...args: any[]) => this.handler.commands.runCommand(...args)) - this.addAction('doQuickfix', () => this.handler.codeActions.doQuickfix()) - this.addAction('refactor', () => this.handler.refactor.doRefactor()) - this.addAction('repeatCommand', () => this.handler.commands.repeat()) - this.addAction('installExtensions', (...list: string[]) => extensions.installExtensions(list)) - this.addAction('updateExtensions', sync => extensions.updateExtensions(sync)) - this.addAction('extensionStats', () => extensions.getExtensionStates()) - this.addAction('loadedExtensions', () => extensions.loadedExtensions()) - this.addAction('watchExtension', (id: string) => extensions.watchExtension(id)) - this.addAction('activeExtension', name => extensions.activate(name)) - this.addAction('deactivateExtension', name => extensions.deactivate(name)) - this.addAction('reloadExtension', name => extensions.reloadExtension(name)) - this.addAction('toggleExtension', name => extensions.toggleExtension(name)) - this.addAction('uninstallExtension', (...args: string[]) => extensions.uninstallExtension(args)) - this.addAction('getCurrentFunctionSymbol', () => this.handler.symbols.getCurrentFunctionSymbol()) - this.addAction('showOutline', (keep?: number) => this.handler.symbols.showOutline(keep)) - this.addAction('hideOutline', () => this.handler.symbols.hideOutline()) - this.addAction('getWordEdit', () => this.handler.rename.getWordEdit()) - this.addAction('addCommand', cmd => this.handler.commands.addVimCommand(cmd)) - this.addAction('addRanges', ranges => this.cursors.addRanges(ranges)) - this.addAction('currentWorkspacePath', () => workspace.rootPath) - this.addAction('selectCurrentPlaceholder', triggerAutocmd => snippetManager.selectCurrentPlaceholder(!!triggerAutocmd)) - this.addAction('codeActionRange', (start, end, only) => this.handler.codeActions.codeActionRange(start, end, only)) - this.addAction('incomingCalls', (item?: CallHierarchyItem) => this.handler.callHierarchy.getIncoming(item)) - this.addAction('outgoingCalls', (item?: CallHierarchyItem) => this.handler.callHierarchy.getOutgoing(item)) - this.addAction('showIncomingCalls', () => this.handler.callHierarchy.showCallHierarchyTree('incoming')) - this.addAction('showOutgoingCalls', () => this.handler.callHierarchy.showCallHierarchyTree('outgoing')) - this.addAction('semanticHighlight', () => this.handler.semanticHighlighter.highlightCurrent()) - this.addAction('showSemanticHighlightInfo', () => this.handler.semanticHighlighter.showHiglightInfo()) - } - - private addAction(key: string, fn: Function): void { - if (this.actions.has(key)) { - throw new Error(`Action ${key} already exists`) - } - this.actions.set(key, fn) - } - - public async init(): Promise { - let { nvim } = this - let s = Date.now() - try { - await extensions.init() - await workspace.init() - snippetManager.init() - completion.init() - diagnosticManager.init() - listManager.init(nvim) - sources.init() - this.handler = new Handler(nvim) - services.init() - extensions.activateExtensions() - workspace.setupDynamicAutocmd(true) - nvim.pauseNotification() - nvim.setVar('WorkspaceFolders', workspace.folderPaths, true) - nvim.setVar('coc_service_initialized', 1, true) - nvim.call('coc#util#do_autocmd', ['CocNvimInit'], true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - this._ready = true - await events.fire('ready', []) - logger.info(`coc.nvim ${this.version} initialized with node: ${process.version} after ${Date.now() - s}ms`) - this.emit('ready') - } catch (e) { - nvim.echoError(e) - } - } - - public get isReady(): boolean { - return this._ready - } - - public get ready(): Promise { - if (this._ready) return Promise.resolve() - return new Promise(resolve => { - this.once('ready', () => { - resolve() - }) - }) - } - - private get version(): string { - return workspace.version + (typeof REVISION === 'string' ? '-' + REVISION : '') - } - - public hasAction(method: string): boolean { - return this.actions.has(method) - } - - public async cocAction(method: string, ...args: any[]): Promise { - let fn = this.actions.get(method) - if (!fn) throw new Error(`Action "${method}" not exists`) - let ts = Date.now() - let res = await Promise.resolve(fn.apply(null, args)) - let dt = Date.now() - ts - if (dt > 500) logger.warn(`Slow action "${method}" cost ${dt}ms`) - return res - } - - public getHandler(): Handler { - return this.handler - } - - public dispose(): void { - this.removeAllListeners() - extensions.dispose() - listManager.dispose() - workspace.dispose() - window.dispose() - sources.dispose() - services.stopAll() - services.dispose() - if (this.handler) { - this.handler.dispose() - } - snippetManager.dispose() - commandManager.dispose() - completion.dispose() - diagnosticManager.dispose() - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/callHierarchyManager.ts b/vim-config/plugins/coc.nvim/src/provider/callHierarchyManager.ts deleted file mode 100644 index bff1fbec..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/callHierarchyManager.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, CancellationToken, Disposable, DocumentSelector, Position } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { CallHierarchyProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class CallHierarchyManager extends Manager { - - public register(selector: DocumentSelector, provider: CallHierarchyProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async prepareCallHierarchy(document: TextDocument, position: Position, token: CancellationToken): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - if (provider.prepareCallHierarchy === null) return null - return await Promise.resolve(provider.prepareCallHierarchy(document, position, token)) - } - - public async provideCallHierarchyOutgoingCalls(document: TextDocument, item: CallHierarchyItem, token: CancellationToken): Promise { - let providerItem = this.getProvider(document) - if (!providerItem) return null - let { provider } = providerItem - if (provider.provideCallHierarchyOutgoingCalls === null) return null - return await Promise.resolve(provider.provideCallHierarchyOutgoingCalls(item, token)) - } - - public async provideCallHierarchyIncomingCalls(document: TextDocument, item: CallHierarchyItem, token: CancellationToken): Promise { - let providerItem = this.getProvider(document) - if (!providerItem) return null - let { provider } = providerItem - if (provider.provideCallHierarchyIncomingCalls(item, token) === null) return null - - return await Promise.resolve(provider.provideCallHierarchyIncomingCalls(item, token)) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/codeActionManager.ts b/vim-config/plugins/coc.nvim/src/provider/codeActionManager.ts deleted file mode 100644 index a8889dc6..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/codeActionManager.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { CancellationToken, CodeAction, CodeActionContext, CodeActionKind, Command, Disposable, DocumentSelector, Range } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { CodeActionProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' -const logger = require('../util/logger')('codeActionManager') - -export default class CodeActionManager extends Manager { - // action to provider uuid - private providerMap: WeakMap = new WeakMap() - - public register(selector: DocumentSelector, provider: CodeActionProvider, clientId: string | undefined, codeActionKinds?: CodeActionKind[]): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider, - kinds: codeActionKinds, - clientId - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideCodeActions( - document: TextDocument, - range: Range, - context: CodeActionContext, - token: CancellationToken - ): Promise { - let providers = this.getProviders(document) - if (!providers.length) return null - if (context.only) { - let { only } = context - providers = providers.filter(p => { - if (p.kinds && !p.kinds.some(kind => only.includes(kind))) { - return false - } - return true - }) - } - let res: CodeAction[] = [] - await Promise.all(providers.map(item => { - let { provider, id } = item - return Promise.resolve(provider.provideCodeActions(document, range, context, token)).then(actions => { - if (!actions || actions.length == 0) return - for (let action of actions) { - if (Command.is(action)) { - let codeAction: CodeAction = { - title: action.title, - command: action - } - res.push(codeAction) - this.providerMap.set(codeAction, id) - } else { - if (context.only) { - if (!action.kind) continue - let found = false - for (let only of context.only) { - if (action.kind.startsWith(only)) { - found = true - break - } - } - if (!found) continue - } - let idx = res.findIndex(o => o.title == action.title) - if (idx == -1) { - this.providerMap.set(action, id) - res.push(action) - } - } - } - }) - })) - return res - } - - public async resolveCodeAction(codeAction: CodeAction, token: CancellationToken): Promise { - // no need to resolve - if (codeAction.edit != null) return codeAction - let id = this.providerMap.get(codeAction) - if (!id) throw new Error(`provider id not found from codeAction`) - let provider = this.getProviderById(id) - if (!provider || typeof provider.resolveCodeAction !== 'function') { - return codeAction - } - let resolved = await Promise.resolve(provider.resolveCodeAction(codeAction, token)) - // save the map to support resolveClientId - if (resolved) this.providerMap.set(resolved, id) - return resolved || codeAction - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/codeLensManager.ts b/vim-config/plugins/coc.nvim/src/provider/codeLensManager.ts deleted file mode 100644 index fd48d96d..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/codeLensManager.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { CancellationToken, CodeLens, Disposable, DocumentSelector } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { CodeLensProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' -import { omit } from '../util/lodash' -// const logger = require('../util/logger')('codeActionManager') - -export default class CodeLensManager extends Manager { - - public register(selector: DocumentSelector, provider: CodeLensProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideCodeLenses( - document: TextDocument, - token: CancellationToken - ): Promise { - let providers = this.getProviders(document) - if (!providers.length) return null - let arr = await Promise.all(providers.map(item => { - let { provider, id } = item - return Promise.resolve(provider.provideCodeLenses(document, token)).then(res => { - if (Array.isArray(res)) { - for (let item of res) { - (item as any).source = id - } - } - return res - }) - })) - return [].concat(...arr) - } - - public async resolveCodeLens( - codeLens: CodeLens, - token: CancellationToken - ): Promise { - // no need to resolve - if (codeLens.command) return codeLens - let { source } = codeLens as any - let provider = this.getProviderById(source) - if (!provider || typeof provider.resolveCodeLens != 'function') { - return codeLens - } - let res = await Promise.resolve(provider.resolveCodeLens(omit(codeLens, ['source']), token)) - Object.assign(codeLens, res) - return codeLens - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/declarationManager.ts b/vim-config/plugins/coc.nvim/src/provider/declarationManager.ts deleted file mode 100644 index 4cafb37d..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/declarationManager.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, Location, Position, LocationLink } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DeclarationProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' -const logger = require('../util/logger')('definitionManager') - -export default class DeclarationManager extends Manager { - - public register(selector: DocumentSelector, provider: DeclarationProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideDeclaration( - document: TextDocument, - position: Position, - token: CancellationToken - ): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - return await Promise.resolve(provider.provideDeclaration(document, position, token)) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/definitionManager.ts b/vim-config/plugins/coc.nvim/src/provider/definitionManager.ts deleted file mode 100644 index 79c7937e..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/definitionManager.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { CancellationToken, Definition, DefinitionLink, Disposable, DocumentSelector, Location, LocationLink, Position } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DefinitionProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' -import { equals } from '../util/object' -const logger = require('../util/logger')('definitionManager') - -export default class DefinitionManager extends Manager { - - public register(selector: DocumentSelector, provider: DefinitionProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - private async getDefinitions( - document: TextDocument, - position: Position, - token: CancellationToken - ): Promise<(Definition | DefinitionLink[])[]> { - const providers = this.getProviders(document) - if (!providers.length) return [] - const arr = await Promise.all(providers.map(item => { - const { provider } = item - return Promise.resolve(provider.provideDefinition(document, position, token)) - })) - return arr - } - - public async provideDefinition( - document: TextDocument, - position: Position, - token: CancellationToken - ): Promise { - const arr = await this.getDefinitions(document, position, token) - return this.toLocations(arr) - } - - public async provideDefinitionLinks( - document: TextDocument, - position: Position, - token: CancellationToken - ): Promise { - const arr = await this.getDefinitions(document, position, token) - const defs: DefinitionLink[] = [] - for (const def of arr) { - if (!Array.isArray(def)) continue - for (const val of def) { - if (LocationLink.is(val)) { - let idx = defs.findIndex(o => o.targetUri == val.targetUri && equals(o.targetRange, val.targetRange)) - if (idx == -1) defs.push(val) - } - } - } - return defs - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/documentColorManager.ts b/vim-config/plugins/coc.nvim/src/provider/documentColorManager.ts deleted file mode 100644 index 0ca50f0a..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/documentColorManager.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { CancellationToken, ColorInformation, ColorPresentation, Disposable, DocumentSelector } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DocumentColorProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class DocumentColorManager extends Manager { - - public register(selector: DocumentSelector, provider: DocumentColorProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideDocumentColors(document: TextDocument, token: CancellationToken): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - let res: ColorInformation[] = await Promise.resolve(provider.provideDocumentColors(document, token)) - return res - } - - public async provideColorPresentations(colorInformation: ColorInformation, document: TextDocument, token: CancellationToken): Promise { - let { range, color } = colorInformation - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - let res = await Promise.resolve(provider.provideColorPresentations(color, { document, range }, token)) - return res - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/documentHighlightManager.ts b/vim-config/plugins/coc.nvim/src/provider/documentHighlightManager.ts deleted file mode 100644 index 38f6fdb9..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/documentHighlightManager.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { CancellationToken, Disposable, DocumentHighlight, DocumentSelector, Position } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DocumentHighlightProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class DocumentHighlightManager extends Manager { - - public register(selector: DocumentSelector, provider: DocumentHighlightProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideDocumentHighlights( - document: TextDocument, - position: Position, - token: CancellationToken - ): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - return await Promise.resolve(provider.provideDocumentHighlights(document, position, token)) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/documentLinkManager.ts b/vim-config/plugins/coc.nvim/src/provider/documentLinkManager.ts deleted file mode 100644 index 866fbd15..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/documentLinkManager.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { CancellationToken, Disposable, DocumentLink, DocumentSelector } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DocumentLinkProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class DocumentLinkManager extends Manager { - - public register(selector: DocumentSelector, provider: DocumentLinkProvider): Disposable { - let item = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - private async _provideDocumentLinks(item: ProviderItem, document: TextDocument, token: CancellationToken): Promise { - let { provider, id } = item - let items = await Promise.resolve(provider.provideDocumentLinks(document, token)) - if (!items || !items.length) return [] - items.forEach(item => { - item.data = item.data || {} - item.data.source = id - }) - return items - } - - public async provideDocumentLinks(document: TextDocument, token: CancellationToken): Promise { - let items = this.getProviders(document) - if (items.length == 0) return [] - const arr = await Promise.all(items.map(item => this._provideDocumentLinks(item, document, token))) - return [].concat(...arr) - } - - public async resolveDocumentLink(link: DocumentLink, token: CancellationToken): Promise { - let { data } = link - if (!data || !data.source) return null - for (let item of this.providers) { - if (item.id == data.source) { - let { provider } = item - link = await Promise.resolve(provider.resolveDocumentLink(link, token)) - return link - } - } - return null - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/documentSymbolManager.ts b/vim-config/plugins/coc.nvim/src/provider/documentSymbolManager.ts deleted file mode 100644 index 002dae11..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/documentSymbolManager.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, DocumentSymbol, SymbolInformation } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DocumentSymbolProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class DocumentSymbolManager extends Manager { - - public register(selector: DocumentSelector, provider: DocumentSymbolProvider, displayName?: string): Disposable { - let item: ProviderItem = { - id: uuid(), - displayName, - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideDocumentSymbols( - document: TextDocument, - token: CancellationToken - ): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - return (await Promise.resolve(provider.provideDocumentSymbols(document, token))) || [] - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/foldingRangeManager.ts b/vim-config/plugins/coc.nvim/src/provider/foldingRangeManager.ts deleted file mode 100644 index a8b379f7..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/foldingRangeManager.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, FoldingRange } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { FoldingContext, FoldingRangeProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class FoldingRangeManager extends Manager { - - public register(selector: DocumentSelector, provider: FoldingRangeProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideFoldingRanges(document: TextDocument, context: FoldingContext, token: CancellationToken): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - return (await Promise.resolve(provider.provideFoldingRanges(document, context, token)) || []) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/formatManager.ts b/vim-config/plugins/coc.nvim/src/provider/formatManager.ts deleted file mode 100644 index c20a671f..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/formatManager.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, FormattingOptions, TextEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DocumentFormattingEditProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class FormatManager extends Manager { - - public register(selector: DocumentSelector, - provider: DocumentFormattingEditProvider, - priority = 0): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - priority, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public handles(doc: TextDocument): boolean { - return this.getProvider(doc) != null - } - - public async provideDocumentFormattingEdits( - document: TextDocument, - options: FormattingOptions, - token: CancellationToken - ): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - return await Promise.resolve(provider.provideDocumentFormattingEdits(document, options, token)) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/formatRangeManager.ts b/vim-config/plugins/coc.nvim/src/provider/formatRangeManager.ts deleted file mode 100644 index d3c288ca..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/formatRangeManager.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, FormattingOptions, Range, TextEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DocumentRangeFormattingEditProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class FormatRangeManager extends Manager { - - public register(selector: DocumentSelector, - provider: DocumentRangeFormattingEditProvider, - priority = 0): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider, - priority - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideDocumentRangeFormattingEdits( - document: TextDocument, - range: Range, - options: FormattingOptions, - token: CancellationToken - ): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - return await Promise.resolve(provider.provideDocumentRangeFormattingEdits(document, range, options, token)) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/hoverManager.ts b/vim-config/plugins/coc.nvim/src/provider/hoverManager.ts deleted file mode 100644 index b68773df..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/hoverManager.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, Hover, Position } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { HoverProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class HoverManager extends Manager { - - public register(selector: DocumentSelector, provider: HoverProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideHover( - document: TextDocument, - position: Position, - token: CancellationToken - ): Promise { - let items = this.getProviders(document) - if (items.length === 0) return null - let res = [] - for (let i = 0, len = items.length; i < len; i += 1) { - const item = items[i] - let hover = await Promise.resolve(item.provider.provideHover(document, position, token)) - if (hover && hover.contents != '') res.push(hover) - } - return res - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/implementationManager.ts b/vim-config/plugins/coc.nvim/src/provider/implementationManager.ts deleted file mode 100644 index dbac8fb7..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/implementationManager.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, Location, Position } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { ImplementationProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class ImplementationManager extends Manager { - - public register(selector: DocumentSelector, provider: ImplementationProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideReferences( - document: TextDocument, - position: Position, - token: CancellationToken - ): Promise { - let providers = this.getProviders(document) - if (!providers.length) return null - let arr = await Promise.all(providers.map(item => { - let { provider } = item - return Promise.resolve(provider.provideImplementation(document, position, token)) - })) - return this.toLocations(arr) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/index.ts b/vim-config/plugins/coc.nvim/src/provider/index.ts deleted file mode 100644 index 6e22d215..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/index.ts +++ /dev/null @@ -1,815 +0,0 @@ -import { CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, CancellationToken, CodeAction, CodeActionContext, CodeActionKind, CodeLens, Color, ColorInformation, ColorPresentation, Command, CompletionContext, CompletionItem, CompletionList, Definition, DefinitionLink, DocumentHighlight, DocumentLink, DocumentSymbol, Event, FoldingRange, FormattingOptions, Hover, LinkedEditingRanges, Location, Position, Range, SelectionRange, SemanticTokens, SemanticTokensDelta, SignatureHelp, SignatureHelpContext, SymbolInformation, TextEdit, WorkspaceEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { URI } from 'vscode-uri' - -/** - * A provider result represents the values a provider, like the [`HoverProvider`](#HoverProvider), - * may return. For once this is the actual result type `T`, like `Hover`, or a thenable that resolves - * to that type `T`. In addition, `null` and `undefined` can be returned - either directly or from a - * thenable. - * - * The snippets below are all valid implementations of the [`HoverProvider`](#HoverProvider): - * - * ```ts - * let a: HoverProvider = { - * provideHover(doc, pos, token): ProviderResult { - * return new Hover('Hello World') - * } - * } - * - * let b: HoverProvider = { - * provideHover(doc, pos, token): ProviderResult { - * return new Promise(resolve => { - * resolve(new Hover('Hello World')) - * }) - * } - * } - * - * let c: HoverProvider = { - * provideHover(doc, pos, token): ProviderResult { - * return; // undefined - * } - * } - * ``` - */ -export type ProviderResult = - | T - | undefined - | null - | Thenable - -/** - * The completion item provider interface defines the contract between extensions and - * [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense). - * - * Providers can delay the computation of the [`detail`](#CompletionItem.detail) - * and [`documentation`](#CompletionItem.documentation) properties by implementing the - * [`resolveCompletionItem`](#CompletionItemProvider.resolveCompletionItem)-function. However, properties that - * are needed for the initial sorting and filtering, like `sortText`, `filterText`, `insertText`, and `range`, must - * not be changed during resolve. - * - * Providers are asked for completions either explicitly by a user gesture or -depending on the configuration- - * implicitly when typing words or trigger characters. - */ -export interface CompletionItemProvider { - /** - * Provide completion items for the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @param context How the completion was triggered. - * - * @return An array of completions, a [completion list](#CompletionList), or a thenable that resolves to either. - * The lack of a result can be signaled by returning `undefined`, `null`, or an empty array. - */ - provideCompletionItems( - document: TextDocument, - position: Position, - token: CancellationToken, - context?: CompletionContext - ): ProviderResult - - /** - * Given a completion item fill in more data, like [doc-comment](#CompletionItem.documentation) - * or [details](#CompletionItem.detail). - * - * The editor will only resolve a completion item once. - * - * @param item A completion item currently active in the UI. - * @param token A cancellation token. - * @return The resolved completion item or a thenable that resolves to of such. It is OK to return the given - * `item`. When no result is returned, the given `item` will be used. - */ - resolveCompletionItem?( - item: CompletionItem, - token: CancellationToken - ): ProviderResult -} - -/** - * The hover provider interface defines the contract between extensions and - * the [hover](https://code.visualstudio.com/docs/editor/intellisense)-feature. - */ -export interface HoverProvider { - /** - * Provide a hover for the given position and document. Multiple hovers at the same - * position will be merged by the editor. A hover can have a range which defaults - * to the word range at the position when omitted. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return A hover or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideHover( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult -} - -/** - * The definition provider interface defines the contract between extensions and - * the [go to definition](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-definition) - * and peek definition features. - */ -export interface DefinitionProvider { - /** - * Provide the definition of the symbol at the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return A definition or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideDefinition( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult -} - -/** - * The definition provider interface defines the contract between extensions and - * the [go to definition](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-definition) - * and peek definition features. - */ -export interface DeclarationProvider { - /** - * Provide the declaration of the symbol at the given position and document. - */ - provideDeclaration(document: TextDocument, position: Position, token: CancellationToken): ProviderResult -} - -/** - * The signature help provider interface defines the contract between extensions and - * the [parameter hints](https://code.visualstudio.com/docs/editor/intellisense)-feature. - */ -export interface SignatureHelpProvider { - /** - * Provide help for the signature at the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return Signature help or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideSignatureHelp( - document: TextDocument, - position: Position, - token: CancellationToken, - context: SignatureHelpContext - ): ProviderResult -} - -/** - * The type definition provider defines the contract between extensions and - * the go to type definition feature. - */ -export interface TypeDefinitionProvider { - /** - * Provide the type definition of the symbol at the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return A definition or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideTypeDefinition( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult -} - -/** - * Value-object that contains additional information when - * requesting references. - */ -export interface ReferenceContext { - /** - * Include the declaration of the current symbol. - */ - includeDeclaration: boolean -} - -/** - * The reference provider interface defines the contract between extensions and - * the [find references](https://code.visualstudio.com/docs/editor/editingevolved#_peek)-feature. - */ -export interface ReferenceProvider { - /** - * Provide a set of project-wide references for the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param context - * @param token A cancellation token. - * @return An array of locations or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideReferences( - document: TextDocument, - position: Position, - context: ReferenceContext, - token: CancellationToken - ): ProviderResult -} - -/** - * Folding context (for future use) - */ -export interface FoldingContext {} - -/** - * The folding range provider interface defines the contract between extensions and - * [Folding](https://code.visualstudio.com/docs/editor/codebasics#_folding) in the editor. - */ -export interface FoldingRangeProvider { - /** - * Returns a list of folding ranges or null and undefined if the provider - * does not want to participate or was cancelled. - * - * @param document The document in which the command was invoked. - * @param context Additional context information (for future use) - * @param token A cancellation token. - */ - provideFoldingRanges( - document: TextDocument, - context: FoldingContext, - token: CancellationToken - ): ProviderResult -} - -/** - * The document symbol provider interface defines the contract between extensions and - * the [go to symbol](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-symbol)-feature. - */ -export interface DocumentSymbolProvider { - - displayName?: string - - /** - * Provide symbol information for the given document. - * - * @param document The document in which the command was invoked. - * @param token A cancellation token. - * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentSymbols( - document: TextDocument, - token: CancellationToken - ): ProviderResult -} - -/** - * The implemenetation provider interface defines the contract between extensions and - * the go to implementation feature. - */ -export interface ImplementationProvider { - /** - * Provide the implementations of the symbol at the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return A definition or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideImplementation( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult -} - -/** - * The workspace symbol provider interface defines the contract between extensions and - * the [symbol search](https://code.visualstudio.com/docs/editor/editingevolved#_open-symbol-by-name)-feature. - */ -export interface WorkspaceSymbolProvider { - /** - * Project-wide search for a symbol matching the given query string. It is up to the provider - * how to search given the query string, like substring, indexOf etc. To improve performance implementors can - * skip the [location](#SymbolInformation.location) of symbols and implement `resolveWorkspaceSymbol` to do that - * later. - * - * The `query`-parameter should be interpreted in a *relaxed way* as the editor will apply its own highlighting - * and scoring on the results. A good rule of thumb is to match case-insensitive and to simply check that the - * characters of *query* appear in their order in a candidate symbol. Don't use prefix, substring, or similar - * strict matching. - * - * @param query A non-empty query string. - * @param token A cancellation token. - * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideWorkspaceSymbols( - query: string, - token: CancellationToken - ): ProviderResult - - /** - * Given a symbol fill in its [location](#SymbolInformation.location). This method is called whenever a symbol - * is selected in the UI. Providers can implement this method and return incomplete symbols from - * [`provideWorkspaceSymbols`](#WorkspaceSymbolProvider.provideWorkspaceSymbols) which often helps to improve - * performance. - * - * @param symbol The symbol that is to be resolved. Guaranteed to be an instance of an object returned from an - * earlier call to `provideWorkspaceSymbols`. - * @param token A cancellation token. - * @return The resolved symbol or a thenable that resolves to that. When no result is returned, - * the given `symbol` is used. - */ - resolveWorkspaceSymbol?( - symbol: SymbolInformation, - token: CancellationToken - ): ProviderResult -} - -/** - * The rename provider interface defines the contract between extensions and - * the [rename](https://code.visualstudio.com/docs/editor/editingevolved#_rename-symbol)-feature. - */ -export interface RenameProvider { - /** - * Provide an edit that describes changes that have to be made to one - * or many resources to rename a symbol to a different name. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param newName The new name of the symbol. If the given name is not valid, the provider must return a rejected promise. - * @param token A cancellation token. - * @return A workspace edit or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideRenameEdits( - document: TextDocument, - position: Position, - newName: string, - token: CancellationToken - ): ProviderResult - - /** - * Optional function for resolving and validating a position *before* running rename. The result can - * be a range or a range and a placeholder text. The placeholder text should be the identifier of the symbol - * which is being renamed - when omitted the text in the returned range is used. - * - * @param document The document in which rename will be invoked. - * @param position The position at which rename will be invoked. - * @param token A cancellation token. - * @return The range or range and placeholder text of the identifier that is to be renamed. The lack of a result can signaled by returning `undefined` or `null`. - */ - prepareRename?( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult -} - -/** - * The document formatting provider interface defines the contract between extensions and - * the formatting-feature. - */ -export interface DocumentFormattingEditProvider { - /** - * Provide formatting edits for a whole document. - * - * @param document The document in which the command was invoked. - * @param options Options controlling formatting. - * @param token A cancellation token. - * @return A set of text edits or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentFormattingEdits( - document: TextDocument, - options: FormattingOptions, - token: CancellationToken - ): ProviderResult -} - -/** - * The document formatting provider interface defines the contract between extensions and - * the formatting-feature. - */ -export interface DocumentRangeFormattingEditProvider { - /** - * Provide formatting edits for a range in a document. - * - * The given range is a hint and providers can decide to format a smaller - * or larger range. Often this is done by adjusting the start and end - * of the range to full syntax nodes. - * - * @param document The document in which the command was invoked. - * @param range The range which should be formatted. - * @param options Options controlling formatting. - * @param token A cancellation token. - * @return A set of text edits or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentRangeFormattingEdits( - document: TextDocument, - range: Range, - options: FormattingOptions, - token: CancellationToken - ): ProviderResult -} - -/** - * The code action interface defines the contract between extensions and - * the [light bulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature. - * - * A code action can be any command that is [known](#commands.getCommands) to the system. - */ -export interface CodeActionProvider { - /** - * Provide commands for the given document and range. - * - * @param document The document in which the command was invoked. - * @param range The selector or range for which the command was invoked. This will always be a selection if - * there is a currently active editor. - * @param context Context carrying additional information. - * @param token A cancellation token. - * @return An array of commands, quick fixes, or refactorings or a thenable of such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideCodeActions( - document: TextDocument, - range: Range, - context: CodeActionContext, - token: CancellationToken - ): ProviderResult<(Command | CodeAction)[]> - - /** - * Given a code action fill in its [`edit`](#CodeAction.edit)-property. Changes to - * all other properties, like title, are ignored. A code action that has an edit - * will not be resolved. - * - * @param codeAction A code action. - * @param token A cancellation token. - * @return The resolved code action or a thenable that resolves to such. It is OK to return the given - * `item`. When no result is returned, the given `item` will be used. - */ - resolveCodeAction?(codeAction: T, token: CancellationToken): ProviderResult -} - -/** - * Metadata about the type of code actions that a [CodeActionProvider](#CodeActionProvider) providers - */ -export interface CodeActionProviderMetadata { - /** - * [CodeActionKinds](#CodeActionKind) that this provider may return. - * - * The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the provider - * may list our every specific kind they provide, such as `CodeActionKind.Refactor.Extract.append('function`)` - */ - readonly providedCodeActionKinds?: ReadonlyArray -} - -/** - * The document highlight provider interface defines the contract between extensions and - * the word-highlight-feature. - */ -export interface DocumentHighlightProvider { - - /** - * Provide a set of document highlights, like all occurrences of a variable or - * all exit-points of a function. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentHighlights( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult -} - -/** - * The document link provider defines the contract between extensions and feature of showing - * links in the editor. - */ -export interface DocumentLinkProvider { - - /** - * Provide links for the given document. Note that the editor ships with a default provider that detects - * `http(s)` and `file` links. - * - * @param document The document in which the command was invoked. - * @param token A cancellation token. - * @return An array of [document links](#DocumentLink) or a thenable that resolves to such. The lack of a result - * can be signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentLinks(document: TextDocument, token: CancellationToken): ProviderResult - - /** - * Given a link fill in its [target](#DocumentLink.target). This method is called when an incomplete - * link is selected in the UI. Providers can implement this method and return incomple links - * (without target) from the [`provideDocumentLinks`](#DocumentLinkProvider.provideDocumentLinks) method which - * often helps to improve performance. - * - * @param link The link that is to be resolved. - * @param token A cancellation token. - */ - resolveDocumentLink?(link: DocumentLink, token: CancellationToken): ProviderResult -} - -/** - * A code lens provider adds [commands](#Command) to source text. The commands will be shown - * as dedicated horizontal lines in between the source text. - */ -export interface CodeLensProvider { - - /** - * An optional event to signal that the code lenses from this provider have changed. - */ - onDidChangeCodeLenses?: Event - - /** - * Compute a list of [lenses](#CodeLens). This call should return as fast as possible and if - * computing the commands is expensive implementors should only return code lens objects with the - * range set and implement [resolve](#CodeLensProvider.resolveCodeLens). - * - * @param document The document in which the command was invoked. - * @param token A cancellation token. - * @return An array of code lenses or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideCodeLenses(document: TextDocument, token: CancellationToken): ProviderResult - - /** - * This function will be called for each visible code lens, usually when scrolling and after - * calls to [compute](#CodeLensProvider.provideCodeLenses)-lenses. - * - * @param codeLens code lens that must be resolved. - * @param token A cancellation token. - * @return The given, resolved code lens or thenable that resolves to such. - */ - resolveCodeLens?(codeLens: CodeLens, token: CancellationToken): ProviderResult -} - -/** - * The document formatting provider interface defines the contract between extensions and - * the formatting-feature. - */ -export interface OnTypeFormattingEditProvider { - - /** - * Provide formatting edits after a character has been typed. - * - * The given position and character should hint to the provider - * what range the position to expand to, like find the matching `{` - * when `}` has been entered. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param ch The character that has been typed. - * @param options Options controlling formatting. - * @param token A cancellation token. - * @return A set of text edits or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideOnTypeFormattingEdits(document: TextDocument, position: Position, ch: string, options: FormattingOptions, token: CancellationToken): ProviderResult -} - -/** - * The document color provider defines the contract between extensions and feature of - * picking and modifying colors in the editor. - */ -export interface DocumentColorProvider { - - /** - * Provide colors for the given document. - * - * @param document The document in which the command was invoked. - * @param token A cancellation token. - * @return An array of [color information](#ColorInformation) or a thenable that resolves to such. The lack of a result - * can be signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentColors(document: TextDocument, token: CancellationToken): ProviderResult - - /** - * Provide [representations](#ColorPresentation) for a color. - * - * @param color The color to show and insert. - * @param context A context object with additional information - * @param token A cancellation token. - * @return An array of color presentations or a thenable that resolves to such. The lack of a result - * can be signaled by returning `undefined`, `null`, or an empty array. - */ - provideColorPresentations(color: Color, context: { document: TextDocument; range: Range }, token: CancellationToken): ProviderResult -} - -export interface TextDocumentContentProvider { - - /** - * An event to signal a resource has changed. - */ - onDidChange?: Event - - /** - * Provide textual content for a given uri. - * - * The editor will use the returned string-content to create a readonly - * [document](#TextDocument). Resources allocated should be released when - * the corresponding document has been [closed](#workspace.onDidCloseTextDocument). - * - * @param uri An uri which scheme matches the scheme this provider was [registered](#workspace.registerTextDocumentContentProvider) for. - * @param token A cancellation token. - * @return A string or a thenable that resolves to such. - */ - provideTextDocumentContent(uri: URI, token: CancellationToken): ProviderResult -} - -export interface SelectionRangeProvider { - /** - * Provide selection ranges starting at a given position. The first range must [contain](#Range.contains) - * position and subsequent ranges must contain the previous range. - */ - provideSelectionRanges(document: TextDocument, positions: Position[], token: CancellationToken): ProviderResult -} - -/** - * The call hierarchy provider interface describes the contract between extensions - * and the call hierarchy feature which allows to browse calls and caller of function, - * methods, constructor etc. - */ -export interface CallHierarchyProvider { - - /** - * Bootstraps call hierarchy by returning the item that is denoted by the given document - * and position. This item will be used as entry into the call graph. Providers should - * return `undefined` or `null` when there is no item at the given location. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @returns A call hierarchy item or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - prepareCallHierarchy(document: TextDocument, position: Position, token: CancellationToken): ProviderResult - - /** - * Provide all incoming calls for an item, e.g all callers for a method. In graph terms this describes directed - * and annotated edges inside the call graph, e.g the given item is the starting node and the result is the nodes - * that can be reached. - * - * @param item The hierarchy item for which incoming calls should be computed. - * @param token A cancellation token. - * @returns A set of incoming calls or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideCallHierarchyIncomingCalls(item: CallHierarchyItem, token: CancellationToken): ProviderResult - - /** - * Provide all outgoing calls for an item, e.g call calls to functions, methods, or constructors from the given item. In - * graph terms this describes directed and annotated edges inside the call graph, e.g the given item is the starting - * node and the result is the nodes that can be reached. - * - * @param item The hierarchy item for which outgoing calls should be computed. - * @param token A cancellation token. - * @returns A set of outgoing calls or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideCallHierarchyOutgoingCalls(item: CallHierarchyItem, token: CancellationToken): ProviderResult -} - -/** - * The document semantic tokens provider interface defines the contract between extensions and - * semantic tokens. - */ -export interface DocumentSemanticTokensProvider { - /** - * An optional event to signal that the semantic tokens from this provider have changed. - */ - onDidChangeSemanticTokens?: Event - - /** - * Tokens in a file are represented as an array of integers. The position of each token is expressed relative to - * the token before it, because most tokens remain stable relative to each other when edits are made in a file. - * - * --- - * In short, each token takes 5 integers to represent, so a specific token `i` in the file consists of the following array indices: - * - * - at index `5*i` - `deltaLine`: token line number, relative to the previous token - * - at index `5*i+1` - `deltaStart`: token start character, relative to the previous token (relative to 0 or the previous token's start if they are on the same line) - * - at index `5*i+2` - `length`: the length of the token. A token cannot be multiline. - * - at index `5*i+3` - `tokenType`: will be looked up in `SemanticTokensLegend.tokenTypes`. We currently ask that `tokenType` < 65536. - * - at index `5*i+4` - `tokenModifiers`: each set bit will be looked up in `SemanticTokensLegend.tokenModifiers` - * - * --- - * ### How to encode tokens - * - * Here is an example for encoding a file with 3 tokens in a uint32 array: - * ``` - * { line: 2, startChar: 5, length: 3, tokenType: "property", tokenModifiers: ["private", "static"] }, - * { line: 2, startChar: 10, length: 4, tokenType: "type", tokenModifiers: [] }, - * { line: 5, startChar: 2, length: 7, tokenType: "class", tokenModifiers: [] } - * ``` - * - * 1. First of all, a legend must be devised. This legend must be provided up-front and capture all possible token types. - * For this example, we will choose the following legend which must be passed in when registering the provider: - * ``` - * tokenTypes: ['property', 'type', 'class'], - * tokenModifiers: ['private', 'static'] - * ``` - * - * 2. The first transformation step is to encode `tokenType` and `tokenModifiers` as integers using the legend. Token types are looked - * up by index, so a `tokenType` value of `1` means `tokenTypes[1]`. Multiple token modifiers can be set by using bit flags, - * so a `tokenModifier` value of `3` is first viewed as binary `0b00000011`, which means `[tokenModifiers[0], tokenModifiers[1]]` because - * bits 0 and 1 are set. Using this legend, the tokens now are: - * ``` - * { line: 2, startChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 }, - * { line: 2, startChar: 10, length: 4, tokenType: 1, tokenModifiers: 0 }, - * { line: 5, startChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 } - * ``` - * - * 3. The next step is to represent each token relative to the previous token in the file. In this case, the second token - * is on the same line as the first token, so the `startChar` of the second token is made relative to the `startChar` - * of the first token, so it will be `10 - 5`. The third token is on a different line than the second token, so the - * `startChar` of the third token will not be altered: - * ``` - * { deltaLine: 2, deltaStartChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 }, - * { deltaLine: 0, deltaStartChar: 5, length: 4, tokenType: 1, tokenModifiers: 0 }, - * { deltaLine: 3, deltaStartChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 } - * ``` - * - * 4. Finally, the last step is to inline each of the 5 fields for a token in a single array, which is a memory friendly representation: - * ``` - * // 1st token, 2nd token, 3rd token - * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] - * ``` - * - * @see [SemanticTokensBuilder](#SemanticTokensBuilder) for a helper to encode tokens as integers. - * *NOTE*: When doing edits, it is possible that multiple edits occur until VS Code decides to invoke the semantic tokens provider. - * *NOTE*: If the provider cannot temporarily compute semantic tokens, it can indicate this by throwing an error with the message 'Busy'. - */ - provideDocumentSemanticTokens(document: TextDocument, token: CancellationToken): ProviderResult - - /** - * Instead of always returning all the tokens in a file, it is possible for a `DocumentSemanticTokensProvider` to implement - * this method (`provideDocumentSemanticTokensEdits`) and then return incremental updates to the previously provided semantic tokens. - * - * --- - * ### How tokens change when the document changes - * - * Suppose that `provideDocumentSemanticTokens` has previously returned the following semantic tokens: - * ``` - * // 1st token, 2nd token, 3rd token - * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] - * ``` - * - * Also suppose that after some edits, the new semantic tokens in a file are: - * ``` - * // 1st token, 2nd token, 3rd token - * [ 3,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] - * ``` - * It is possible to express these new tokens in terms of an edit applied to the previous tokens: - * ``` - * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] // old tokens - * [ 3,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] // new tokens - * - * edit: { start: 0, deleteCount: 1, data: [3] } // replace integer at offset 0 with 3 - * ``` - * - * *NOTE*: If the provider cannot compute `SemanticTokensEdits`, it can "give up" and return all the tokens in the document again. - * *NOTE*: All edits in `SemanticTokensEdits` contain indices in the old integers array, so they all refer to the previous result state. - */ - provideDocumentSemanticTokensEdits?(document: TextDocument, previousResultId: string, token: CancellationToken): ProviderResult -} - -/** - * The document range semantic tokens provider interface defines the contract between extensions and - * semantic tokens. - */ -export interface DocumentRangeSemanticTokensProvider { - /** - * @see [provideDocumentSemanticTokens](#DocumentSemanticTokensProvider.provideDocumentSemanticTokens). - */ - provideDocumentRangeSemanticTokens(document: TextDocument, range: Range, token: CancellationToken): ProviderResult -} - -export interface LinkedEditingRangeProvider { - /** - * For a given position in a document, returns the range of the symbol at the position and all ranges - * that have the same content. A change to one of the ranges can be applied to all other ranges if the new content - * is valid. An optional word pattern can be returned with the result to describe valid contents. - * If no result-specific word pattern is provided, the word pattern from the language configuration is used. - * - * @param document The document in which the provider was invoked. - * @param position The position at which the provider was invoked. - * @param token A cancellation token. - * @return A list of ranges that can be edited together - */ - provideLinkedEditingRanges(document: TextDocument, position: Position, token: CancellationToken): ProviderResult -} diff --git a/vim-config/plugins/coc.nvim/src/provider/linkedEditingRangeManager.ts b/vim-config/plugins/coc.nvim/src/provider/linkedEditingRangeManager.ts deleted file mode 100644 index a2908c9a..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/linkedEditingRangeManager.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { v4 as uuid } from 'uuid' -import { CancellationToken, Disposable, DocumentSelector, LinkedEditingRanges, Position } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { LinkedEditingRangeProvider } from './index' -import Manager, { ProviderItem } from './manager' -const logger = require('../util/logger')('linkedEditingManager') - -export default class LinkedEditingRangeManager extends Manager { - public register(selector: DocumentSelector, provider: LinkedEditingRangeProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideLinkedEditingRanges(document: TextDocument, position: Position, token: CancellationToken): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - if (!provider.provideLinkedEditingRanges) return null - - return await Promise.resolve(provider.provideLinkedEditingRanges(document, position, token)) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/manager.ts b/vim-config/plugins/coc.nvim/src/provider/manager.ts deleted file mode 100644 index 412f4e51..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/manager.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { Definition, DocumentSelector, Location, LocationLink } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import workspace from '../workspace' -import { equals } from '../util/object' -const logger = require('../util/logger')('provider-manager') - -export interface ProviderItem { - id: string - selector: DocumentSelector - provider: T - [key: string]: any -} - -export default class Manager { - protected providers: Set> = new Set() - - public hasProvider(document: TextDocument): boolean { - return this.getProvider(document) != null - } - - protected getProvider(document: TextDocument): ProviderItem { - let currScore = 0 - let providerItem: ProviderItem - for (let item of this.providers) { - let { selector, priority } = item - let score = workspace.match(selector, document) - if (score == 0) continue - if (typeof priority == 'number') { - score = priority - } - if (score < currScore) continue - currScore = score - providerItem = item - } - return providerItem - } - - protected getProviderById(id: string): T { - let item = Array.from(this.providers).find(o => o.id == id) - return item ? item.provider : null - } - - protected getProviders(document: TextDocument): ProviderItem[] { - let items = Array.from(this.providers) - items = items.filter(item => workspace.match(item.selector, document) > 0) - return items.sort((a, b) => workspace.match(b.selector, document) - workspace.match(a.selector, document)) - } - - protected toLocations(arr: (Definition | LocationLink[] | null)[]): Location[] { - let res: Location[] = [] - for (let def of arr) { - if (!def) continue - if (Location.is(def)) { - addLocation(res, def) - } else if (Array.isArray(def)) { - for (let d of def) { - if (Location.is(d)) { - addLocation(res, d) - } else if (LocationLink.is(d)) { - let { targetUri, targetSelectionRange, targetRange } = d - addLocation(res, Location.create(targetUri, targetSelectionRange || targetRange)) - } - } - } else { - logger.error(`Bad definition`, def) - } - } - return res - } -} - -/** - * Add unique location - */ -function addLocation(arr: Location[], location: Location): void { - let { range, uri } = location - if (arr.find(o => o.uri == uri && equals(o.range, range)) != null) return - arr.push(location) -} diff --git a/vim-config/plugins/coc.nvim/src/provider/onTypeFormatManager.ts b/vim-config/plugins/coc.nvim/src/provider/onTypeFormatManager.ts deleted file mode 100644 index a6f0a83e..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/onTypeFormatManager.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, Position, TextEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import workspace from '../workspace' -import { OnTypeFormattingEditProvider } from './index' -const logger = require('../util/logger')('onTypeFormatManager') - -export interface ProviderItem { - triggerCharacters: string[] - selector: DocumentSelector - provider: OnTypeFormattingEditProvider -} - -export default class OnTypeFormatManager { - private providers: Set = new Set() - - public register(selector: DocumentSelector, provider: OnTypeFormattingEditProvider, triggerCharacters: string[]): Disposable { - let item: ProviderItem = { - triggerCharacters, - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public hasProvider(document: TextDocument): boolean { - for (let o of this.providers) { - let { selector } = o - if (workspace.match(selector, document) > 0) { - return true - } - } - return false - } - - public getProvider(document: TextDocument, triggerCharacter: string): OnTypeFormattingEditProvider | null { - for (let o of this.providers) { - let { triggerCharacters, selector } = o - if (workspace.match(selector, document) > 0 && triggerCharacters.includes(triggerCharacter)) { - return o.provider - } - } - return null - } - - public async onCharacterType(character: string, document: TextDocument, position: Position, token: CancellationToken): Promise { - let provider = this.getProvider(document, character) - if (!provider) return - let formatOpts = await workspace.getFormatOptions(document.uri) - return await Promise.resolve(provider.provideOnTypeFormattingEdits(document, position, character, formatOpts, token)) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/referenceManager.ts b/vim-config/plugins/coc.nvim/src/provider/referenceManager.ts deleted file mode 100644 index e07a7647..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/referenceManager.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, Location, Position, ReferenceContext } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { ReferenceProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class ReferenceManager extends Manager { - - public register(selector: DocumentSelector, provider: ReferenceProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideReferences( - document: TextDocument, - position: Position, - context: ReferenceContext, - token: CancellationToken - ): Promise { - let providers = this.getProviders(document) - if (!providers.length) return null - let arr = await Promise.all(providers.map(item => { - let { provider } = item - return Promise.resolve(provider.provideReferences(document, position, context, token)) - })) - return this.toLocations(arr) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/renameManager.ts b/vim-config/plugins/coc.nvim/src/provider/renameManager.ts deleted file mode 100644 index 43cd5557..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/renameManager.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, Position, Range, WorkspaceEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { RenameProvider } from './index' -import Manager from './manager' -import { v4 as uuid } from 'uuid' - -export default class RenameManager extends Manager { - - public register(selector: DocumentSelector, provider: RenameProvider): Disposable { - let item = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideRenameEdits( - document: TextDocument, - position: Position, - newName: string, - token: CancellationToken - ): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - return await Promise.resolve(provider.provideRenameEdits(document, position, newName, token)) - } - - public async prepareRename( - document: TextDocument, - position: Position, - token: CancellationToken - ): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - if (provider.prepareRename == null) return null - let res = await Promise.resolve(provider.prepareRename(document, position, token)) - // can not rename - if (res == null) return false - return res - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/selectionRangeManager.ts b/vim-config/plugins/coc.nvim/src/provider/selectionRangeManager.ts deleted file mode 100644 index 7d9df328..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/selectionRangeManager.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { SelectionRange, CancellationToken, Disposable, DocumentSelector, Position } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { SelectionRangeProvider } from './index' -import Manager from './manager' -import { v4 as uuid } from 'uuid' - -export default class SelectionRangeManager extends Manager { - - public register(selector: DocumentSelector, provider: SelectionRangeProvider): Disposable { - let item = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideSelectionRanges( - document: TextDocument, - positions: Position[], - token: CancellationToken - ): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - let ranges: SelectionRange[] = await Promise.resolve(provider.provideSelectionRanges(document, positions, token)) - if (!ranges || ranges.length == 0) return [] - for (let i = 0; i < ranges.length - 1; i++) { - let r = ranges[i] - if (!r.parent) r.parent = ranges[i + 1] - } - return ranges - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/semanticTokensManager.ts b/vim-config/plugins/coc.nvim/src/provider/semanticTokensManager.ts deleted file mode 100644 index e1fba09f..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/semanticTokensManager.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { v4 as uuid } from 'uuid' -import { CancellationToken, Disposable, DocumentSelector, SemanticTokens, SemanticTokensDelta, SemanticTokensLegend } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DocumentSemanticTokensProvider } from './index' -import Manager, { ProviderItem } from './manager' -const logger = require('../util/logger')('semanticTokensManager') - -export default class SemanticTokensManager extends Manager { - private resolvedProvider: Map = new Map() - - public register(selector: DocumentSelector, provider: DocumentSemanticTokensProvider, legend: SemanticTokensLegend, onChange: () => void): Disposable { - let id = uuid() - let item: ProviderItem = { - id, - selector, - legend, - provider - } - this.providers.add(item) - let disposable: Disposable | undefined - if (typeof provider.onDidChangeSemanticTokens === 'function') { - disposable = provider.onDidChangeSemanticTokens(() => { - onChange() - }) - } - return Disposable.create(() => { - disposable?.dispose() - for (let [uri, providerId] of this.resolvedProvider.entries()) { - if (providerId == id) { - this.resolvedProvider.delete(uri) - } - } - this.providers.delete(item) - }) - } - - public getLegend(document: TextDocument): SemanticTokensLegend { - const item = this.getProvider(document) - if (!item) return - // save matched provider - this.resolvedProvider.set(document.uri, item.id) - return item.legend - } - - protected resolveProvider(document: TextDocument): DocumentSemanticTokensProvider { - let id = this.resolvedProvider.get(document.uri) - if (id) return this.getProviderById(id) - return this.getProvider(document)?.provider - } - - public hasSemanticTokensEdits(document: TextDocument): boolean { - let provider = this.resolveProvider(document) - if (!provider) return false - return (typeof provider.provideDocumentSemanticTokensEdits === 'function') - } - - public async provideDocumentSemanticTokens(document: TextDocument, token: CancellationToken): Promise { - let provider = this.resolveProvider(document) - if (!provider || typeof provider.provideDocumentSemanticTokens !== 'function') return null - return await Promise.resolve(provider.provideDocumentSemanticTokens(document, token)) - } - - public async provideDocumentSemanticTokensEdits(document: TextDocument, previousResultId: string, token: CancellationToken): Promise { - let provider = this.resolveProvider(document) - if (!provider || typeof provider.provideDocumentSemanticTokensEdits !== 'function') return null - return await Promise.resolve(provider.provideDocumentSemanticTokensEdits(document, previousResultId, token)) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/semanticTokensRangeManager.ts b/vim-config/plugins/coc.nvim/src/provider/semanticTokensRangeManager.ts deleted file mode 100644 index 4f24766b..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/semanticTokensRangeManager.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { v4 as uuid } from 'uuid' -import { CancellationToken, Disposable, DocumentSelector, Range, SemanticTokens, SemanticTokensLegend } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { DocumentRangeSemanticTokensProvider } from './index' -import Manager, { ProviderItem } from './manager' -const logger = require('../util/logger')('semanticTokensRangeManager') - -export default class SemanticTokensRangeManager extends Manager { - public register(selector: DocumentSelector, provider: DocumentRangeSemanticTokensProvider, legend: SemanticTokensLegend): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - legend, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public getLegend(document: TextDocument): SemanticTokensLegend { - const item = this.getProvider(document) - if (!item) return - return item.legend - } - - public async provideDocumentRangeSemanticTokens(document: TextDocument, range: Range, token: CancellationToken): Promise { - let item = this.getProvider(document) - if (!item) return null - let { provider } = item - if (provider.provideDocumentRangeSemanticTokens === null) return null - - return await Promise.resolve(provider.provideDocumentRangeSemanticTokens(document, range, token)) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/signatureManager.ts b/vim-config/plugins/coc.nvim/src/provider/signatureManager.ts deleted file mode 100644 index 21d6a0f7..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/signatureManager.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, Position, SignatureHelp, SignatureHelpContext } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { SignatureHelpProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class SignatureManager extends Manager { - - public register(selector: DocumentSelector, provider: SignatureHelpProvider, triggerCharacters?: string[]): Disposable { - let characters = triggerCharacters.reduce((p, c) => p.concat(c.length == 1 ? [c] : c.split(/\s*/g)), [] as string[]) - let item: ProviderItem = { - id: uuid(), - selector, - provider, - triggerCharacters: characters - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public shouldTrigger(document: TextDocument, triggerCharacter: string): boolean { - let item = this.getProvider(document) - if (!item) return false - let { triggerCharacters } = item - return triggerCharacters && triggerCharacters.indexOf(triggerCharacter) != -1 - } - - public async provideSignatureHelp( - document: TextDocument, - position: Position, - token: CancellationToken, - context: SignatureHelpContext - ): Promise { - let item = this.getProvider(document) - if (!item) return null - let res = await Promise.resolve(item.provider.provideSignatureHelp(document, position, token, context)) - if (res && res.signatures && res.signatures.length) return res - return null - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/typeDefinitionManager.ts b/vim-config/plugins/coc.nvim/src/provider/typeDefinitionManager.ts deleted file mode 100644 index d392f011..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/typeDefinitionManager.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { CancellationToken, Disposable, DocumentSelector, Location, Position } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { TypeDefinitionProvider } from './index' -import Manager, { ProviderItem } from './manager' -import { v4 as uuid } from 'uuid' - -export default class TypeDefinitionManager extends Manager { - - public register(selector: DocumentSelector, provider: TypeDefinitionProvider): Disposable { - let item: ProviderItem = { - id: uuid(), - selector, - provider - } - this.providers.add(item) - return Disposable.create(() => { - this.providers.delete(item) - }) - } - - public async provideTypeDefinition( - document: TextDocument, - position: Position, - token: CancellationToken - ): Promise { - let providers = this.getProviders(document) - if (!providers.length) return null - let arr = await Promise.all(providers.map(item => { - let { provider } = item - return Promise.resolve(provider.provideTypeDefinition(document, position, token)) - })) - return this.toLocations(arr) - } -} diff --git a/vim-config/plugins/coc.nvim/src/provider/workspaceSymbolsManager.ts b/vim-config/plugins/coc.nvim/src/provider/workspaceSymbolsManager.ts deleted file mode 100644 index fb9eeeb4..00000000 --- a/vim-config/plugins/coc.nvim/src/provider/workspaceSymbolsManager.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { v4 as uuid } from 'uuid' -import { CancellationToken, Disposable, SymbolInformation } from 'vscode-languageserver-protocol' -import { WorkspaceSymbolProvider } from './index' - -export default class WorkspaceSymbolManager { - private providers: Map = new Map() - - public register(provider: WorkspaceSymbolProvider): Disposable { - let id = uuid() - this.providers.set(id, provider) - return Disposable.create(() => { - this.providers.delete(id) - }) - } - - public async provideWorkspaceSymbols( - query: string, - token: CancellationToken - ): Promise { - let entries = Array.from(this.providers.entries()) - if (!entries.length) return [] - let res: SymbolInformation[] = [] - await Promise.all(entries.map(o => { - let [id, p] = o - return Promise.resolve(p.provideWorkspaceSymbols(query, token)).then(list => { - if (list) res.push(...list.map(item => Object.assign({ source: id }, item))) - }) - })) - return res - } - - public async resolveWorkspaceSymbol( - symbolInfo: SymbolInformation, - token: CancellationToken - ): Promise { - let provider = this.providers.get((symbolInfo as any).source) - if (!provider) return - if (typeof provider.resolveWorkspaceSymbol != 'function') { - return Promise.resolve(symbolInfo) - } - return await Promise.resolve(provider.resolveWorkspaceSymbol(symbolInfo, token)) - } - - public hasProvider(): boolean { - return this.providers.size > 0 - } -} diff --git a/vim-config/plugins/coc.nvim/src/semanticTokensBuilder.ts b/vim-config/plugins/coc.nvim/src/semanticTokensBuilder.ts deleted file mode 100644 index e21bb3de..00000000 --- a/vim-config/plugins/coc.nvim/src/semanticTokensBuilder.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { Range, SemanticTokens, SemanticTokensLegend } from "vscode-languageserver-protocol" - -function isStringArray(value: any): value is string[] { - return Array.isArray(value) && (value as any[]).every(elem => typeof elem === 'string') -} - -function isStrArrayOrUndefined(arg: any): arg is string[] | undefined { - return ((typeof arg === 'undefined') || isStringArray(arg)) -} - -/** - * A semantic tokens builder can help with creating a `SemanticTokens` instance - * which contains delta encoded semantic tokens. - */ -export class SemanticTokensBuilder { - private _prevLine: number - private _prevChar: number - private _dataIsSortedAndDeltaEncoded: boolean - private _data: number[] - private _dataLen: number - private _tokenTypeStrToInt: Map - private _tokenModifierStrToInt: Map - private _hasLegend: boolean - - constructor(legend?: SemanticTokensLegend) { - this._prevLine = 0 - this._prevChar = 0 - this._dataIsSortedAndDeltaEncoded = true - this._data = [] - this._dataLen = 0 - this._tokenTypeStrToInt = new Map() - this._tokenModifierStrToInt = new Map() - this._hasLegend = false - if (legend) { - this._hasLegend = true - for (let i = 0, len = legend.tokenTypes.length; i < len; i++) { - this._tokenTypeStrToInt.set(legend.tokenTypes[i], i) - } - for (let i = 0, len = legend.tokenModifiers.length; i < len; i++) { - this._tokenModifierStrToInt.set(legend.tokenModifiers[i], i) - } - } - } - - /** - * Add another token. - * - * @param line The token start line number (absolute value). - * @param char The token start character (absolute value). - * @param length The token length in characters. - * @param tokenType The encoded token type. - * @param tokenModifiers The encoded token modifiers. - */ - public push(line: number, char: number, length: number, tokenType: number, tokenModifiers?: number): void - /** - * Add another token. Use only when providing a legend. - * - * @param range The range of the token. Must be single-line. - * @param tokenType The token type. - * @param tokenModifiers The token modifiers. - */ - public push(range: Range, tokenType: string, tokenModifiers?: string[]): void - public push(arg0: any, arg1: any, arg2: any, arg3?: any, arg4?: any): void { - if (typeof arg0 === 'number' && typeof arg1 === 'number' && typeof arg2 === 'number' && typeof arg3 === 'number' && (typeof arg4 === 'number' || typeof arg4 === 'undefined')) { - if (typeof arg4 === 'undefined') { - arg4 = 0 - } - // 1st overload - return this._pushEncoded(arg0, arg1, arg2, arg3, arg4) - } - if (Range.is(arg0) && typeof arg1 === 'string' && isStrArrayOrUndefined(arg2)) { - // 2nd overload - return this._push(arg0, arg1, arg2) - } - throw new Error('Illegal argument') - } - - private _push(range: Range, tokenType: string, tokenModifiers?: string[]): void { - if (!this._hasLegend) { - throw new Error('Legend must be provided in constructor') - } - if (range.start.line !== range.end.line) { - throw new Error('`range` cannot span multiple lines') - } - if (!this._tokenTypeStrToInt.has(tokenType)) { - throw new Error('`tokenType` is not in the provided legend') - } - const line = range.start.line - const char = range.start.character - const length = range.end.character - range.start.character - const nTokenType = this._tokenTypeStrToInt.get(tokenType)! - let nTokenModifiers = 0 - if (tokenModifiers) { - for (const tokenModifier of tokenModifiers) { - if (!this._tokenModifierStrToInt.has(tokenModifier)) { - throw new Error('`tokenModifier` is not in the provided legend') - } - const nTokenModifier = this._tokenModifierStrToInt.get(tokenModifier)! - nTokenModifiers |= (1 << nTokenModifier) >>> 0 - } - } - this._pushEncoded(line, char, length, nTokenType, nTokenModifiers) - } - - private _pushEncoded(line: number, char: number, length: number, tokenType: number, tokenModifiers: number): void { - if (this._dataIsSortedAndDeltaEncoded && (line < this._prevLine || (line === this._prevLine && char < this._prevChar))) { - // push calls were ordered and are no longer ordered - this._dataIsSortedAndDeltaEncoded = false - - // Remove delta encoding from data - const tokenCount = (this._data.length / 5) | 0 - let prevLine = 0 - let prevChar = 0 - for (let i = 0; i < tokenCount; i++) { - let line = this._data[5 * i] - let char = this._data[5 * i + 1] - - if (line === 0) { - // on the same line as previous token - line = prevLine - char += prevChar - } else { - // on a different line than previous token - line += prevLine - } - - this._data[5 * i] = line - this._data[5 * i + 1] = char - - prevLine = line - prevChar = char - } - } - - let pushLine = line - let pushChar = char - if (this._dataIsSortedAndDeltaEncoded && this._dataLen > 0) { - pushLine -= this._prevLine - if (pushLine === 0) { - pushChar -= this._prevChar - } - } - - this._data[this._dataLen++] = pushLine - this._data[this._dataLen++] = pushChar - this._data[this._dataLen++] = length - this._data[this._dataLen++] = tokenType - this._data[this._dataLen++] = tokenModifiers - - this._prevLine = line - this._prevChar = char - } - - private static _sortAndDeltaEncode(data: number[]): number[] { - let pos: number[] = [] - const tokenCount = (data.length / 5) | 0 - for (let i = 0; i < tokenCount; i++) { - pos[i] = i - } - pos.sort((a, b) => { - const aLine = data[5 * a] - const bLine = data[5 * b] - if (aLine === bLine) { - const aChar = data[5 * a + 1] - const bChar = data[5 * b + 1] - return aChar - bChar - } - return aLine - bLine - }) - const result = new Array(data.length) - let prevLine = 0 - let prevChar = 0 - for (let i = 0; i < tokenCount; i++) { - const srcOffset = 5 * pos[i] - const line = data[srcOffset + 0] - const char = data[srcOffset + 1] - const length = data[srcOffset + 2] - const tokenType = data[srcOffset + 3] - const tokenModifiers = data[srcOffset + 4] - - const pushLine = line - prevLine - const pushChar = (pushLine === 0 ? char - prevChar : char) - - const dstOffset = 5 * i - result[dstOffset + 0] = pushLine - result[dstOffset + 1] = pushChar - result[dstOffset + 2] = length - result[dstOffset + 3] = tokenType - result[dstOffset + 4] = tokenModifiers - - prevLine = line - prevChar = char - } - - return result - } - - /** - * Finish and create a `SemanticTokens` instance. - */ - public build(resultId?: string): SemanticTokens { - if (!this._dataIsSortedAndDeltaEncoded) { - return { data: SemanticTokensBuilder._sortAndDeltaEncode(this._data), resultId } - } - return { data: this._data, resultId } - } -} diff --git a/vim-config/plugins/coc.nvim/src/services.ts b/vim-config/plugins/coc.nvim/src/services.ts deleted file mode 100644 index 142968de..00000000 --- a/vim-config/plugins/coc.nvim/src/services.ts +++ /dev/null @@ -1,565 +0,0 @@ -import { SpawnOptions } from 'child_process' -import { EventEmitter } from 'events' -import fs from 'fs' -import net from 'net' -import { CancellationToken, Event, CancellationTokenSource, Disposable, DocumentSelector, Emitter } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { Executable, ForkOptions, LanguageClient, LanguageClientOptions, RevealOutputChannelOn, ServerOptions, State, Transport, TransportKind } from './language-client' -import { ServiceStat } from './types' -import { disposeAll, wait } from './util' -import workspace from './workspace' -import window from './window' -const logger = require('./util/logger')('services') - -interface ServiceInfo { - id: string - state: string - languageIds: string[] -} - -export interface LanguageServerConfig { - module?: string - command?: string - transport?: string - transportPort?: number - disableWorkspaceFolders?: boolean - disableSnippetCompletion?: boolean - disableDynamicRegister?: boolean - disableCompletion?: boolean - disableDiagnostics?: boolean - formatterPriority?: number - filetypes: string[] - additionalSchemes?: string[] - enable?: boolean - args?: string[] - cwd?: string - env?: any - // socket port - port?: number - host?: string - detached?: boolean - shell?: boolean - execArgv?: string[] - rootPatterns?: string[] - ignoredRootPaths?: string[] - initializationOptions?: any - progressOnInitialization?: boolean - revealOutputChannelOn?: string - configSection?: string - stdioEncoding?: string - runtime?: string -} - -export function getStateName(state: ServiceStat): string { - switch (state) { - case ServiceStat.Initial: - return 'init' - case ServiceStat.Running: - return 'running' - case ServiceStat.Starting: - return 'starting' - case ServiceStat.StartFailed: - return 'startFailed' - case ServiceStat.Stopping: - return 'stopping' - case ServiceStat.Stopped: - return 'stopped' - default: - return 'unknown' - } -} - -export interface IServiceProvider { - // unique service id - id: string - name: string - client?: LanguageClient - selector: DocumentSelector - // current state - state: ServiceStat - start(): Promise - dispose(): void - stop(): Promise | void - restart(): Promise | void - onServiceReady: Event -} - -export class ServiceManager extends EventEmitter implements Disposable { - private readonly registered: Map = new Map() - private disposables: Disposable[] = [] - - public init(): void { - workspace.onDidOpenTextDocument(document => { - this.start(document) - }, null, this.disposables) - workspace.onDidChangeConfiguration(e => { - if (e.affectsConfiguration('languageserver')) { - this.createCustomServices() - } - }, null, this.disposables) - this.createCustomServices() - } - - public dispose(): void { - this.removeAllListeners() - disposeAll(this.disposables) - for (let service of this.registered.values()) { - service.dispose() - } - } - - public regist(service: IServiceProvider): Disposable { - let { id } = service - if (!id) logger.error('invalid service configuration. ', service.name) - if (this.registered.get(id)) return - this.registered.set(id, service) - logger.info(`registered service "${id}"`) - if (this.shouldStart(service)) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - service.start() - } - if (service.state == ServiceStat.Running) { - this.emit('ready', id) - } - service.onServiceReady(() => { - logger.info(`service ${id} started`) - this.emit('ready', id) - }, null, this.disposables) - return Disposable.create(() => { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - service.stop() - service.dispose() - this.registered.delete(id) - }) - } - - public getService(id: string): IServiceProvider { - let service = this.registered.get(id) - if (!service) service = this.registered.get(`languageserver.${id}`) - return service - } - - private shouldStart(service: IServiceProvider): boolean { - if (service.state != ServiceStat.Initial) { - return false - } - let selector = service.selector - for (let doc of workspace.documents) { - if (workspace.match(selector, doc.textDocument)) { - return true - } - } - return false - } - - private start(document: TextDocument): void { - let services = this.getServices(document) - for (let service of services) { - if (service.state == ServiceStat.Initial) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - service.start() - } - } - } - - public getServices(document: TextDocument): IServiceProvider[] { - let res: IServiceProvider[] = [] - for (let service of this.registered.values()) { - if (workspace.match(service.selector, document) > 0) { - res.push(service) - } - } - return res - } - - public stop(id: string): Promise { - let service = this.registered.get(id) - if (!service) { - window.showMessage(`Service ${id} not found`, 'error') - return - } - return Promise.resolve(service.stop()) - } - - public stopAll(): void { - for (let service of this.registered.values()) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - service.stop() - } - } - - public async toggle(id: string): Promise { - let service = this.registered.get(id) - if (!service) { - window.showMessage(`Service ${id} not found`, 'error') - return - } - let { state } = service - try { - if (state == ServiceStat.Running) { - await Promise.resolve(service.stop()) - } else if (state == ServiceStat.Initial) { - await service.start() - } else if (state == ServiceStat.Stopped) { - await service.restart() - } - } catch (e) { - window.showMessage(`Service error: ${e.message}`, 'error') - } - } - - public getServiceStats(): ServiceInfo[] { - let res: ServiceInfo[] = [] - for (let [id, service] of this.registered) { - res.push({ - id, - languageIds: documentSelectorToLanguageIds(service.selector), - state: getStateName(service.state) - }) - } - return res - } - - private createCustomServices(): void { - let lspConfig = workspace.getConfiguration().get<{ key: LanguageServerConfig }>('languageserver', {} as any) - for (let key of Object.keys(lspConfig)) { - let config: LanguageServerConfig = lspConfig[key] - if (!this.validServerConfig(key, config)) { - continue - } - this.registLanguageClient(key, config) - } - } - - private validServerConfig(key: string, config: LanguageServerConfig): boolean { - let errors: string[] = [] - if (config.module != null && typeof config.module !== 'string') { - errors.push(`"module" field of languageserver ${key} should be string`) - } - if (config.command != null && typeof config.command !== 'string') { - errors.push(`"command" field of languageserver ${key} should be string`) - } - if (config.transport != null && typeof config.transport !== 'string') { - errors.push(`"transport" field of languageserver ${key} should be string`) - } - if (config.transportPort != null && typeof config.transportPort !== 'number') { - errors.push(`"transportPort" field of languageserver ${key} should be string`) - } - if (!Array.isArray(config.filetypes) || !config.filetypes.every(s => typeof s === 'string')) { - errors.push(`"filetypes" field of languageserver ${key} should be array of string`) - } - if (config.additionalSchemes && (!Array.isArray(config.additionalSchemes) || config.additionalSchemes.some(s => typeof s !== 'string'))) { - errors.push(`"additionalSchemes" field of languageserver ${key} should be array of string`) - } - if (errors.length) { - window.showMessage(errors.join('\n'), 'error') - return false - } - return true - } - - private waitClient(id: string): Promise { - let service = this.getService(id) - if (service && service.state == ServiceStat.Running) return Promise.resolve() - if (service) return new Promise(resolve => { - service.onServiceReady(() => { - resolve() - }) - }) - return new Promise(resolve => { - let listener = clientId => { - if (clientId == id || clientId == `languageserver.${id}`) { - this.off('ready', listener) - resolve() - } - } - this.on('ready', listener) - }) - } - - public async registNotification(id: string, method: string): Promise { - await this.waitClient(id) - let service = this.getService(id) - if (!service.client) { - window.showMessage(`Not a language client: ${id}`, 'error') - return - } - let client = service.client - client.onNotification(method, async result => { - await workspace.nvim.call('coc#do_notify', [id, method, result]) - }) - } - - public async sendNotification(id: string, method: string, params?: any): Promise { - if (!method) throw new Error(`method required for ontification`) - let service = this.getService(id) - // wait for extension activate - if (!service || !service.client) throw new Error(`Language server ${id} not found`) - if (service.state == ServiceStat.Starting) { - await service.client.onReady() - } - if (service.state != ServiceStat.Running) { - throw new Error(`Language server ${id} not running`) - } - await Promise.resolve(service.client.sendNotification(method, params)) - } - - public async sendRequest(id: string, method: string, params?: any, token?: CancellationToken): Promise { - if (!method) throw new Error(`method required for sendRequest`) - let service = this.getService(id) - // wait for extension activate - if (!service) await wait(100) - service = this.getService(id) - if (!service || !service.client) { - throw new Error(`Language server ${id} not found`) - } - if (service.state == ServiceStat.Starting) { - await service.client.onReady() - } - if (service.state != ServiceStat.Running) { - throw new Error(`Language server ${id} not running`) - } - if (!token) { - let tokenSource = new CancellationTokenSource() - token = tokenSource.token - } - return await Promise.resolve(service.client.sendRequest(method, params, token)) - } - - public registLanguageClient(client: LanguageClient): Disposable - public registLanguageClient(name: string, config: LanguageServerConfig): Disposable - public registLanguageClient(name: string | LanguageClient, config?: LanguageServerConfig): Disposable { - let id = typeof name === 'string' ? `languageserver.${name}` : name.id - let disposables: Disposable[] = [] - let onDidServiceReady = new Emitter() - let client: LanguageClient | null = typeof name === 'string' ? null : name - if (this.registered.has(id)) return - let created = false - let service: IServiceProvider = { - id, - client, - name: typeof name === 'string' ? name : name.name, - selector: typeof name === 'string' ? getDocumentSelector(config.filetypes, config.additionalSchemes) : name.clientOptions.documentSelector, - state: ServiceStat.Initial, - onServiceReady: onDidServiceReady.event, - start: (): Promise => { - if (service.state == ServiceStat.Starting || service.state == ServiceStat.Running) { - return - } - if (client && !client.needsStart()) { - return - } - if (created && client) { - client.restart() - return Promise.resolve() - } - if (!created) { - if (typeof name == 'string' && !client) { - let config: LanguageServerConfig = workspace.getConfiguration().get<{ key: LanguageServerConfig }>('languageserver', {} as any)[name] - if (!config || config.enable === false) return - let opts = getLanguageServerOptions(id, name, config) - if (!opts) return - client = new LanguageClient(id, name, opts[1], opts[0]) - service.selector = opts[0].documentSelector - service.client = client - } - client.onDidChangeState(changeEvent => { - let { oldState, newState } = changeEvent - if (newState == State.Starting) { - service.state = ServiceStat.Starting - } else if (newState == State.Running) { - service.state = ServiceStat.Running - } else if (newState == State.Stopped) { - service.state = ServiceStat.Stopped - } - let oldStr = stateString(oldState) - let newStr = stateString(newState) - logger.info(`${client.name} state change: ${oldStr} => ${newStr}`) - }, null, disposables) - created = true - } - service.state = ServiceStat.Starting - logger.debug(`starting service: ${id}`) - let disposable = client.start() - disposables.push(disposable) - return new Promise(resolve => { - client.onReady().then(() => { - onDidServiceReady.fire(void 0) - resolve() - }, e => { - window.showMessage(`Server ${id} failed to start: ${e}`, 'error') - logger.error(`Server ${id} failed to start:`, e) - service.state = ServiceStat.StartFailed - resolve() - }) - }) - }, - dispose: async () => { - onDidServiceReady.dispose() - disposeAll(disposables) - }, - stop: async (): Promise => { - if (!client || !client.needsStop()) return - await Promise.resolve(client.stop()) - }, - restart: async (): Promise => { - if (client) { - service.state = ServiceStat.Starting - client.restart() - } else { - await service.start() - } - }, - } - return this.regist(service) - } -} - -export function documentSelectorToLanguageIds(documentSelector: DocumentSelector): string[] { - let res = documentSelector.map(filter => { - if (typeof filter == 'string') { - return filter - } - return filter.language - }) - res = res.filter(s => typeof s == 'string') - return Array.from(new Set(res)) -} - -// convert config to options -export function getLanguageServerOptions(id: string, name: string, config: LanguageServerConfig): [LanguageClientOptions, ServerOptions] { - let { command, module, port, args, filetypes } = config - args = args || [] - if (!filetypes) { - window.showMessage(`Wrong configuration of LS "${name}", filetypes not found`, 'error') - return null - } - if (!command && !module && !port) { - window.showMessage(`Wrong configuration of LS "${name}", no command or module specified.`, 'error') - return null - } - let serverOptions: ServerOptions - if (module) { - module = workspace.expand(module) - if (!fs.existsSync(module)) { - window.showMessage(`Module file "${module}" not found for LS "${name}"`, 'error') - return null - } - serverOptions = { - module, - runtime: config.runtime || process.execPath, - args, - transport: getTransportKind(config), - options: getForkOptions(config) - } - } else if (command) { - serverOptions = { - command, - args, - options: getSpawnOptions(config) - } as Executable - } else if (port) { - serverOptions = () => new Promise((resolve, reject) => { - let client = new net.Socket() - let host = config.host || '127.0.0.1' - logger.info(`languageserver "${id}" connecting to ${host}:${port}`) - client.connect(port, host, () => { - resolve({ - reader: client, - writer: client - }) - }) - client.on('error', e => { - reject(new Error(`Connection error for ${id}: ${e.message}`)) - }) - }) - } - let disableWorkspaceFolders = !!config.disableWorkspaceFolders - let disableSnippetCompletion = !!config.disableSnippetCompletion - let ignoredRootPaths = config.ignoredRootPaths || [] - let clientOptions: LanguageClientOptions = { - ignoredRootPaths: ignoredRootPaths.map(s => workspace.expand(s)), - disableWorkspaceFolders, - disableSnippetCompletion, - disableDynamicRegister: !!config.disableDynamicRegister, - disableCompletion: !!config.disableCompletion, - disableDiagnostics: !!config.disableDiagnostics, - formatterPriority: config.formatterPriority || 0, - documentSelector: getDocumentSelector(config.filetypes, config.additionalSchemes), - revealOutputChannelOn: getRevealOutputChannelOn(config.revealOutputChannelOn), - synchronize: { - configurationSection: `${id}.settings` - }, - diagnosticCollectionName: name, - outputChannelName: id, - stdioEncoding: config.stdioEncoding || 'utf8', - progressOnInitialization: config.progressOnInitialization !== false, - initializationOptions: config.initializationOptions || {} - } - return [clientOptions, serverOptions] -} - -export function getRevealOutputChannelOn(revealOn: string | undefined): RevealOutputChannelOn { - switch (revealOn) { - case 'info': - return RevealOutputChannelOn.Info - case 'warn': - return RevealOutputChannelOn.Warn - case 'error': - return RevealOutputChannelOn.Error - case 'never': - return RevealOutputChannelOn.Never - default: - return RevealOutputChannelOn.Never - } -} - -export function getDocumentSelector(filetypes: string[] | undefined, additionalSchemes?: string[]): DocumentSelector { - let documentSelector: DocumentSelector = [] - let schemes = ['file', 'untitled'].concat(additionalSchemes || []) - if (!filetypes) return schemes.map(s => ({ scheme: s })) - filetypes.forEach(filetype => { - documentSelector.push(...schemes.map(scheme => ({ language: filetype, scheme }))) - }) - return documentSelector -} - -export function getTransportKind(config: LanguageServerConfig): Transport { - let { transport, transportPort } = config - if (!transport || transport == 'ipc') return TransportKind.ipc - if (transport == 'stdio') return TransportKind.stdio - if (transport == 'pipe') return TransportKind.pipe - return { kind: TransportKind.socket, port: transportPort } -} - -function getForkOptions(config: LanguageServerConfig): ForkOptions { - return { - cwd: config.cwd, - execArgv: config.execArgv || [], - env: config.env || undefined - } -} - -function getSpawnOptions(config: LanguageServerConfig): SpawnOptions { - return { - cwd: config.cwd, - detached: !!config.detached, - shell: !!config.shell, - env: config.env || undefined - } -} - -function stateString(state: State): string { - switch (state) { - case State.Running: - return 'running' - case State.Starting: - return 'starting' - case State.Stopped: - return 'stopped' - default: - return 'unknown' - } -} - -export default new ServiceManager() diff --git a/vim-config/plugins/coc.nvim/src/snippets/manager.ts b/vim-config/plugins/coc.nvim/src/snippets/manager.ts deleted file mode 100644 index a7a1817a..00000000 --- a/vim-config/plugins/coc.nvim/src/snippets/manager.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { Disposable, InsertTextMode, Range } from 'vscode-languageserver-protocol' -import events from '../events' -import { StatusBarItem } from '../model/status' -import workspace from '../workspace' -import window from '../window' -import * as Snippets from "./parser" -import { SnippetSession } from './session' -import { SnippetVariableResolver } from './variableResolve' -import { SnippetString } from './string' -const logger = require('../util/logger')('snippets-manager') - -export class SnippetManager { - private sessionMap: Map = new Map() - private disposables: Disposable[] = [] - private statusItem: StatusBarItem - - constructor() { - workspace.onDidChangeTextDocument(async e => { - let session = this.getSession(e.bufnr) - if (session) { - let firstLine = e.originalLines[e.contentChanges[0].range.start.line] || '' - await session.synchronizeUpdatedPlaceholders(e.contentChanges[0], firstLine) - } - }, null, this.disposables) - - workspace.onDidCloseTextDocument(textDocument => { - let doc = workspace.getDocument(textDocument.uri) - if (!doc) return - let session = this.getSession(doc.bufnr) - if (session) session.deactivate() - }, null, this.disposables) - - events.on('BufEnter', async bufnr => { - let session = this.getSession(bufnr) - if (!this.statusItem) return - if (session && session.isActive) { - this.statusItem.show() - } else { - this.statusItem.hide() - } - }, null, this.disposables) - - events.on('InsertEnter', async () => { - let { session } = this - if (!session) return - await session.checkPosition() - }, null, this.disposables) - } - - public init(): void { - let config = workspace.getConfiguration('coc.preferences') - this.statusItem = window.createStatusBarItem(0) - this.statusItem.text = config.get('snippetStatusText', 'SNIP') - } - - /** - * Insert snippet at current cursor position - */ - public async insertSnippet(snippet: string | SnippetString, select = true, range?: Range, insertTextMode?: InsertTextMode): Promise { - let { bufnr } = workspace - let session = this.getSession(bufnr) - if (!session) { - session = new SnippetSession(workspace.nvim, bufnr) - this.sessionMap.set(bufnr, session) - session.onCancel(() => { - this.sessionMap.delete(bufnr) - if (workspace.bufnr == bufnr) { - this.statusItem.hide() - } - }) - } - let snippetStr = SnippetString.isSnippetString(snippet) ? snippet.value : snippet - let isActive = await session.start(snippetStr, select, range, insertTextMode) - if (isActive) this.statusItem.show() - return isActive - } - - public async selectCurrentPlaceholder(triggerAutocmd = true): Promise { - let { session } = this - if (session) return await session.selectCurrentPlaceholder(triggerAutocmd) - } - - public async nextPlaceholder(): Promise { - let { session } = this - if (session) { - await session.nextPlaceholder() - } else { - workspace.nvim.call('coc#snippet#disable', [], true) - this.statusItem.hide() - } - return '' - } - - public async previousPlaceholder(): Promise { - let { session } = this - if (session) { - await session.previousPlaceholder() - } else { - workspace.nvim.call('coc#snippet#disable', [], true) - this.statusItem.hide() - } - return '' - } - - public cancel(): void { - let session = this.getSession(workspace.bufnr) - if (session) return session.deactivate() - workspace.nvim.call('coc#snippet#disable', [], true) - if (this.statusItem) this.statusItem.hide() - } - - public get session(): SnippetSession { - let session = this.getSession(workspace.bufnr) - return session && session.isActive ? session : null - } - - public isActived(bufnr: number): boolean { - let session = this.getSession(bufnr) - return session && session.isActive ? true : false - } - - public jumpable(): boolean { - let { session } = this - if (!session) return false - let placeholder = session.placeholder - if (placeholder && !placeholder.isFinalTabstop) { - return true - } - return false - } - - public getSession(bufnr: number): SnippetSession { - return this.sessionMap.get(bufnr) - } - - public async resolveSnippet(body: string): Promise { - let parser = new Snippets.SnippetParser() - const snippet = parser.parse(body, true) - const resolver = new SnippetVariableResolver() - await snippet.resolveVariables(resolver) - return snippet - } - - public dispose(): void { - this.cancel() - for (let d of this.disposables) { - d.dispose() - } - } -} - -export default new SnippetManager() diff --git a/vim-config/plugins/coc.nvim/src/snippets/parser.ts b/vim-config/plugins/coc.nvim/src/snippets/parser.ts deleted file mode 100644 index 7dc05631..00000000 --- a/vim-config/plugins/coc.nvim/src/snippets/parser.ts +++ /dev/null @@ -1,1203 +0,0 @@ -/* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { CharCode } from '../util/charCode' -import { rangeParts } from '../util/string' -import { Range } from 'vscode-languageserver-protocol' -const logger = require('../util/logger')('snippets-parser') - -export const enum TokenType { - Dollar, - Colon, - Comma, - CurlyOpen, - CurlyClose, - Backslash, - Forwardslash, - Pipe, - Int, - VariableName, - Format, - Plus, - Dash, - QuestionMark, - EOF -} - -export interface Token { - type: TokenType - pos: number - len: number -} - -export class Scanner { - - private static _table: { [ch: number]: TokenType } = { - [CharCode.DollarSign]: TokenType.Dollar, - [CharCode.Colon]: TokenType.Colon, - [CharCode.Comma]: TokenType.Comma, - [CharCode.OpenCurlyBrace]: TokenType.CurlyOpen, - [CharCode.CloseCurlyBrace]: TokenType.CurlyClose, - [CharCode.Backslash]: TokenType.Backslash, - [CharCode.Slash]: TokenType.Forwardslash, - [CharCode.Pipe]: TokenType.Pipe, - [CharCode.Plus]: TokenType.Plus, - [CharCode.Dash]: TokenType.Dash, - [CharCode.QuestionMark]: TokenType.QuestionMark, - } - - public static isDigitCharacter(ch: number): boolean { - return ch >= CharCode.Digit0 && ch <= CharCode.Digit9 - } - - public static isVariableCharacter(ch: number): boolean { - return ch === CharCode.Underline - || (ch >= CharCode.a && ch <= CharCode.z) - || (ch >= CharCode.A && ch <= CharCode.Z) - } - - public value: string - public pos: number - - constructor() { - this.text('') - } - - public text(value: string): void { - this.value = value - this.pos = 0 - } - - public tokenText(token: Token): string { - return this.value.substr(token.pos, token.len) - } - - public next(): Token { - - if (this.pos >= this.value.length) { - return { type: TokenType.EOF, pos: this.pos, len: 0 } - } - - let pos = this.pos - let len = 0 - let ch = this.value.charCodeAt(pos) - let type: TokenType - - // static types - type = Scanner._table[ch] - if (typeof type === 'number') { - this.pos += 1 - return { type, pos, len: 1 } - } - - // number - if (Scanner.isDigitCharacter(ch)) { - type = TokenType.Int - do { - len += 1 - ch = this.value.charCodeAt(pos + len) - } while (Scanner.isDigitCharacter(ch)) - - this.pos += len - return { type, pos, len } - } - - // variable name - if (Scanner.isVariableCharacter(ch)) { - type = TokenType.VariableName - do { - ch = this.value.charCodeAt(pos + (++len)) - } while (Scanner.isVariableCharacter(ch) || Scanner.isDigitCharacter(ch)) - - this.pos += len - return { type, pos, len } - } - - // format - type = TokenType.Format - do { - len += 1 - ch = this.value.charCodeAt(pos + len) - } while ( - !isNaN(ch) - && typeof Scanner._table[ch] === 'undefined' // not static token - && !Scanner.isDigitCharacter(ch) // not number - && !Scanner.isVariableCharacter(ch) // not variable - ) - - this.pos += len - return { type, pos, len } - } -} - -export abstract class Marker { - - public readonly _markerBrand: any - - public parent: Marker - protected _children: Marker[] = [] - - public appendChild(child: Marker): this { - if (child instanceof Text && this._children[this._children.length - 1] instanceof Text) { - // this and previous child are text -> merge them - (this._children[this._children.length - 1] as Text).value += child.value - } else { - // normal adoption of child - child.parent = this - this._children.push(child) - } - return this - } - - public setOnlyChild(child: Marker): void { - child.parent = this - this._children = [child] - } - - public replace(child: Marker, others: Marker[]): void { - const { parent } = child - const idx = parent.children.indexOf(child) - const newChildren = parent.children.slice(0) - newChildren.splice(idx, 1, ...others) - parent._children = newChildren - ; (function _fixParent(children: Marker[], parent: Marker): void { - for (const child of children) { - child.parent = parent - _fixParent(child.children, child) - } - })(others, parent) - } - - public get children(): Marker[] { - return this._children - } - - public get snippet(): TextmateSnippet | undefined { - // eslint-disable-next-line @typescript-eslint/no-this-alias - let candidate: Marker = this - // eslint-disable-next-line no-constant-condition - while (true) { - if (!candidate) { - return undefined - } - if (candidate instanceof TextmateSnippet) { - return candidate - } - candidate = candidate.parent - } - } - - public toString(): string { - return this.children.reduce((prev, cur) => prev + cur.toString(), '') - } - - public abstract toTextmateString(): string - - public len(): number { - return 0 - } - - public get next(): Marker | null { - let { parent } = this - let { children } = parent - let idx = children.indexOf(this) - return children[idx + 1] - } - - public abstract clone(): Marker -} - -export class Text extends Marker { - - public static escape(value: string): string { - return value.replace(/\$|}|\\/g, '\\$&') - } - - constructor(public value: string) { - super() - } - public toString(): string { - return this.value - } - - public toTextmateString(): string { - return Text.escape(this.value) - } - public len(): number { - return this.value.length - } - public clone(): Text { - return new Text(this.value) - } -} - -export abstract class TransformableMarker extends Marker { - public transform: Transform -} - -export class Placeholder extends TransformableMarker { - public static compareByIndex(a: Placeholder, b: Placeholder): number { - if (a.index === b.index) { - return 0 - } else if (a.isFinalTabstop) { - return 1 - } else if (b.isFinalTabstop) { - return -1 - } else if (a.index < b.index) { - return -1 - } else if (a.index > b.index) { - return 1 - } else { - return 0 - } - } - - constructor(public index: number) { - super() - } - - public get isFinalTabstop(): boolean { - return this.index === 0 - } - - public get choice(): Choice | undefined { - return this._children.length === 1 && this._children[0] instanceof Choice - ? this._children[0] as Choice - : undefined - } - - public toTextmateString(): string { - let transformString = '' - if (this.transform) { - transformString = this.transform.toTextmateString() - } - if (this.children.length === 0 && !this.transform) { - return `$${this.index}` - } else if (this.children.length === 0) { - return `\${${this.index}${transformString}}` - } else if (this.choice) { - return `\${${this.index}|${this.choice.toTextmateString()}|${transformString}}` - } else { - return `\${${this.index}:${this.children.map(child => child.toTextmateString()).join('')}${transformString}}` - } - } - - public clone(): Placeholder { - let ret = new Placeholder(this.index) - if (this.transform) { - ret.transform = this.transform.clone() - } - ret._children = this.children.map(child => child.clone()) - return ret - } -} - -export class Choice extends Marker { - - public readonly options: Text[] = [] - - public appendChild(marker: Marker): this { - if (marker instanceof Text) { - marker.parent = this - this.options.push(marker) - } - return this - } - - public toString(): string { - return this.options[0].value - } - - public toTextmateString(): string { - return this.options - .map(option => option.value.replace(/\||,/g, '\\$&')) - .join(',') - } - - public len(): number { - return this.options[0].len() - } - - public clone(): Choice { - let ret = new Choice() - for (let opt of this.options) { - ret.appendChild(opt as any) - } - return ret - } -} - -export class Transform extends Marker { - - public regexp: RegExp - - public resolve(value: string): string { - let didMatch = false - let ret = value.replace(this.regexp, (...args) => { - didMatch = true - return this._replace(args.slice(0, -2)) - }) - // when the regex didn't match and when the transform has - // else branches, then run those - if (!didMatch && this._children.some(child => child instanceof FormatString && Boolean(child.elseValue))) { - ret = this._replace([]) - } - return ret - } - - private _replace(groups: string[]): string { - let ret = '' - for (const marker of this._children) { - if (marker instanceof FormatString) { - let value = groups[marker.index] || '' - value = marker.resolve(value) - ret += value - } else { - ret += marker.toString() - } - } - return ret - } - - public toString(): string { - return '' - } - - public toTextmateString(): string { - return `/${this.regexp.source}/${this.children.map(c => c.toTextmateString())}/${(this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : '')}` - } - - public clone(): Transform { - let ret = new Transform() - ret.regexp = new RegExp(this.regexp.source, '' + (this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : '')) - ret._children = this.children.map(child => child.clone()) - return ret - } - -} - -export class FormatString extends Marker { - - constructor( - public readonly index: number, - public readonly shorthandName?: string, - public readonly ifValue?: string, - public readonly elseValue?: string, - ) { - super() - } - - public resolve(value: string): string { - if (this.shorthandName === 'upcase') { - return !value ? '' : value.toLocaleUpperCase() - } else if (this.shorthandName === 'downcase') { - return !value ? '' : value.toLocaleLowerCase() - } else if (this.shorthandName === 'capitalize') { - return !value ? '' : (value[0].toLocaleUpperCase() + value.substr(1)) - } else if (this.shorthandName === 'pascalcase') { - return !value ? '' : this._toPascalCase(value) - } else if (Boolean(value) && typeof this.ifValue === 'string') { - return this.ifValue - } else if (!value && typeof this.elseValue === 'string') { - return this.elseValue - } else { - return value || '' - } - } - - private _toPascalCase(value: string): string { - const match = value.match(/[a-z]+/gi) - if (!match) { - return value - } - return match.map(word => word.charAt(0).toUpperCase() - + word.substr(1).toLowerCase()) - .join('') - } - - public toTextmateString(): string { - let value = '${' - value += this.index - if (this.shorthandName) { - value += `:/${this.shorthandName}` - - } else if (this.ifValue && this.elseValue) { - value += `:?${this.ifValue}:${this.elseValue}` - } else if (this.ifValue) { - value += `:+${this.ifValue}` - } else if (this.elseValue) { - value += `:-${this.elseValue}` - } - value += '}' - return value - } - - public clone(): FormatString { - let ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue) - return ret - } -} - -export class Variable extends TransformableMarker { - - constructor(public name: string) { - super() - } - - public async resolve(resolver: VariableResolver): Promise { - let value = await resolver.resolve(this) - if (value && value.includes('\n')) { - // get indent from previous texts - let indent = '' - this.snippet.walk(m => { - if (m == this) { - return false - } - if (m instanceof Text) { - let lines = m.toString().split(/\r?\n/) - indent = lines[lines.length - 1].match(/^\s*/)[0] - } - return true - }) - let lines = value.split('\n') - let indents = lines.filter(s => s.length > 0).map(s => s.match(/^\s*/)[0]) - let minIndent = indents.length == 0 ? '' : - indents.reduce((p, c) => p.length < c.length ? p : c) - let newLines = lines.map((s, i) => i == 0 || s.length == 0 || !s.startsWith(minIndent) ? s : - indent + s.slice(minIndent.length)) - value = newLines.join('\n') - } - if (this.transform) { - value = this.transform.resolve(value || '') - } - if (value !== undefined) { - this._children = [new Text(value) as any] - return true - } - return false - } - - public toTextmateString(): string { - let transformString = '' - if (this.transform) { - transformString = this.transform.toTextmateString() - } - if (this.children.length === 0) { - return `\${${this.name}${transformString}}` - } else { - return `\${${this.name}:${this.children.map(child => child.toTextmateString()).join('')}${transformString}}` - } - } - - public clone(): Variable { - const ret = new Variable(this.name) - if (this.transform) { - ret.transform = this.transform.clone() - } - ret._children = this.children.map(child => child.clone()) - return ret - } -} - -export interface VariableResolver { - resolve(variable: Variable): Promise -} - -function walk(marker: Marker[], visitor: (marker: Marker) => boolean): void { - const stack = [...marker] - while (stack.length > 0) { - const marker = stack.shift() - const recurse = visitor(marker) - if (!recurse) { - break - } - stack.unshift(...marker.children) - } -} - -export class TextmateSnippet extends Marker { - - private _placeholders?: { all: Placeholder[]; last?: Placeholder } - private _variables?: Variable[] - - public get placeholderInfo(): { all: Placeholder[]; last?: Placeholder } { - if (!this._placeholders) { - this._variables = [] - // fill in placeholders - let all: Placeholder[] = [] - let last: Placeholder | undefined - this.walk(candidate => { - if (candidate instanceof Placeholder) { - all.push(candidate) - last = !last || last.index < candidate.index ? candidate : last - } else if (candidate instanceof Variable) { - let first = candidate.name.charCodeAt(0) - // not jumpover for uppercase variable. - if (first < 65 || first > 90) { - this._variables.push(candidate) - } - } - return true - }) - this._placeholders = { all, last } - } - return this._placeholders - } - - public get variables(): Variable[] { - return this._variables - } - - public get placeholders(): Placeholder[] { - const { all } = this.placeholderInfo - return all - } - - public get maxIndexNumber(): number { - let { placeholders } = this - return placeholders.reduce((curr, p) => Math.max(curr, p.index), 0) - } - - public get minIndexNumber(): number { - let { placeholders } = this - let nums = placeholders.map(p => p.index) - nums.sort((a, b) => a - b) - if (nums.length > 1 && nums[0] == 0) return nums[1] - return nums[0] || 0 - } - - public insertSnippet(snippet: string, id: number, range: Range): number { - let placeholder = this.placeholders[id] - if (!placeholder) return - let { index } = placeholder - let [before, after] = rangeParts(placeholder.toString(), range) - let nested = new SnippetParser().parse(snippet, true) - let maxIndexAdded = nested.maxIndexNumber + 1 - let indexes: number[] = [] - for (let p of nested.placeholders) { - if (p.isFinalTabstop) { - p.index = maxIndexAdded + index - } else { - p.index = p.index + index - } - indexes.push(p.index) - } - this.walk(m => { - if (m instanceof Placeholder && m.index > index) { - m.index = m.index + maxIndexAdded - } - return true - }) - let children = nested.children - if (before) children.unshift(new Text(before)) - if (after) children.push(new Text(after)) - this.replace(placeholder, children) - return Math.min.apply(null, indexes) - } - - public updatePlaceholder(id: number, val: string): void { - const placeholder = this.placeholders[id] - for (let p of this.placeholders) { - if (p.index == placeholder.index) { - let child = p.children[0] - let newText = p.transform ? p.transform.resolve(val) : val - if (child) { - p.setOnlyChild(new Text(newText)) - } else { - p.appendChild(new Text(newText)) - } - } - } - this._placeholders = undefined - } - - public updateVariable(id: number, val: string): void { - const find = this.variables[id - this.maxIndexNumber - 1] - if (find) { - let variables = this.variables.filter(o => o.name == find.name) - for (let variable of variables) { - let newText = variable.transform ? variable.transform.resolve(val) : val - variable.setOnlyChild(new Text(newText)) - } - } - } - - /** - * newText after update with value - */ - public getPlaceholderText(id: number, value: string): string { - const placeholder = this.placeholders[id] - if (!placeholder) return value - return placeholder.transform ? placeholder.transform.resolve(value) : value - } - - public offset(marker: Marker): number { - let pos = 0 - let found = false - this.walk(candidate => { - if (candidate === marker) { - found = true - return false - } - pos += candidate.len() - return true - }) - - if (!found) { - return -1 - } - return pos - } - - public fullLen(marker: Marker): number { - let ret = 0 - walk([marker], marker => { - ret += marker.len() - return true - }) - return ret - } - - public enclosingPlaceholders(placeholder: Placeholder): Placeholder[] { - let ret: Placeholder[] = [] - let { parent } = placeholder - while (parent) { - if (parent instanceof Placeholder) { - ret.push(parent) - } - parent = parent.parent - } - return ret - } - - public async resolveVariables(resolver: VariableResolver): Promise { - let items: Variable[] = [] - this.walk(candidate => { - if (candidate instanceof Variable) { - items.push(candidate) - } - return true - }) - await Promise.all(items.map(o => o.resolve(resolver))) - } - - public appendChild(child: Marker): this { - this._placeholders = undefined - return super.appendChild(child) - } - - public replace(child: Marker, others: Marker[]): void { - this._placeholders = undefined - return super.replace(child, others) - } - - public toTextmateString(): string { - return this.children.reduce((prev, cur) => prev + cur.toTextmateString(), '') - } - - public clone(): TextmateSnippet { - let ret = new TextmateSnippet() - this._children = this.children.map(child => child.clone()) - return ret - } - - public walk(visitor: (marker: Marker) => boolean): void { - walk(this.children, visitor) - } -} - -export class SnippetParser { - - public static escape(value: string): string { - return value.replace(/\$|}|\\/g, '\\$&') - } - - private _scanner = new Scanner() - private _token: Token - - public text(value: string): string { - return this.parse(value).toString() - } - - public parse(value: string, insertFinalTabstop?: boolean): TextmateSnippet { - - this._scanner.text(value) - this._token = this._scanner.next() - - const snippet = new TextmateSnippet() - while (this._parse(snippet)) { - // nothing - } - - // fill in values for placeholders. the first placeholder of an index - // that has a value defines the value for all placeholders with that index - const placeholderDefaultValues = new Map() - const incompletePlaceholders: Placeholder[] = [] - snippet.walk(marker => { - if (marker instanceof Placeholder) { - if (marker.isFinalTabstop) { - placeholderDefaultValues.set(0, undefined) - } else if (!placeholderDefaultValues.has(marker.index) && marker.children.length > 0) { - placeholderDefaultValues.set(marker.index, marker.children) - } else { - incompletePlaceholders.push(marker) - } - } - return true - }) - for (const placeholder of incompletePlaceholders) { - if (placeholderDefaultValues.has(placeholder.index)) { - const clone = new Placeholder(placeholder.index) - clone.transform = placeholder.transform - for (const child of placeholderDefaultValues.get(placeholder.index)) { - let marker = child.clone() - if (clone.transform) { - if (marker instanceof Text) { - marker = new Text(clone.transform.resolve(marker.value)) - } else { - for (let child of marker.children) { - if (child instanceof Text) { - marker.replace(child, [new Text(clone.transform.resolve(child.value))]) - break - } - } - } - } - clone.appendChild(marker) - } - snippet.replace(placeholder, [clone]) - } - } - - if (!placeholderDefaultValues.has(0) && insertFinalTabstop) { - // the snippet uses placeholders but has no - // final tabstop defined -> insert at the end - snippet.appendChild(new Placeholder(0)) - } - - return snippet - } - - private _accept(type?: TokenType): boolean - private _accept(type: TokenType | undefined, value: true): string - private _accept(type: TokenType, value?: boolean): boolean | string { - if (type === undefined || this._token.type === type) { - let ret = !value ? true : this._scanner.tokenText(this._token) - this._token = this._scanner.next() - return ret - } - return false - } - - private _backTo(token: Token): false { - this._scanner.pos = token.pos + token.len - this._token = token - return false - } - - private _until(type: TokenType): false | string { - if (this._token.type === TokenType.EOF) { - return false - } - let start = this._token - while (this._token.type !== type) { - this._token = this._scanner.next() - if (this._token.type === TokenType.EOF) { - return false - } - } - let value = this._scanner.value.substring(start.pos, this._token.pos) - this._token = this._scanner.next() - return value - } - - private _parse(marker: Marker): boolean { - return this._parseEscaped(marker) - || this._parseTabstopOrVariableName(marker) - || this._parseComplexPlaceholder(marker) - || this._parseComplexVariable(marker) - || this._parseAnything(marker) - } - - // \$, \\, \} -> just text - private _parseEscaped(marker: Marker): boolean { - let value: string - // eslint-disable-next-line no-cond-assign - if (value = this._accept(TokenType.Backslash, true)) { - // saw a backslash, append escaped token or that backslash - value = this._accept(TokenType.Dollar, true) - || this._accept(TokenType.CurlyClose, true) - || this._accept(TokenType.Backslash, true) - || value - - marker.appendChild(new Text(value)) - return true - } - return false - } - - // $foo -> variable, $1 -> tabstop - private _parseTabstopOrVariableName(parent: Marker): boolean { - let value: string - const token = this._token - const match = this._accept(TokenType.Dollar) - && (value = this._accept(TokenType.VariableName, true) || this._accept(TokenType.Int, true)) - - if (!match) { - return this._backTo(token) - } - - parent.appendChild(/^\d+$/.test(value) - ? new Placeholder(Number(value)) - : new Variable(value) - ) - return true - } - - // ${1:}, ${1} -> placeholder - private _parseComplexPlaceholder(parent: Marker): boolean { - let index: string - const token = this._token - const match = this._accept(TokenType.Dollar) - && this._accept(TokenType.CurlyOpen) - && (index = this._accept(TokenType.Int, true)) - - if (!match) { - return this._backTo(token) - } - - const placeholder = new Placeholder(Number(index)) - - if (this._accept(TokenType.Colon)) { - // ${1:} - // eslint-disable-next-line no-constant-condition - while (true) { - - // ...} -> done - if (this._accept(TokenType.CurlyClose)) { - parent.appendChild(placeholder) - return true - } - - if (this._parse(placeholder)) { - continue - } - - // fallback - parent.appendChild(new Text('${' + index + ':')) - placeholder.children.forEach(parent.appendChild, parent) - return true - } - } else if (placeholder.index > 0 && this._accept(TokenType.Pipe)) { - // ${1|one,two,three|} - const choice = new Choice() - - // eslint-disable-next-line no-constant-condition - while (true) { - if (this._parseChoiceElement(choice)) { - - if (this._accept(TokenType.Comma)) { - // opt, -> more - continue - } - - if (this._accept(TokenType.Pipe)) { - placeholder.appendChild(choice) - if (this._accept(TokenType.CurlyClose)) { - // ..|} -> done - parent.appendChild(placeholder) - return true - } - } - } - - this._backTo(token) - return false - } - - } else if (this._accept(TokenType.Forwardslash)) { - // ${1///} - if (this._parseTransform(placeholder)) { - parent.appendChild(placeholder) - return true - } - - this._backTo(token) - return false - - } else if (this._accept(TokenType.CurlyClose)) { - // ${1} - parent.appendChild(placeholder) - return true - - } else { - // ${1 <- missing curly or colon - return this._backTo(token) - } - } - - private _parseChoiceElement(parent: Choice): boolean { - const token = this._token - const values: string[] = [] - - // eslint-disable-next-line no-constant-condition - while (true) { - if (this._token.type === TokenType.Comma || this._token.type === TokenType.Pipe) { - break - } - let value: string - // eslint-disable-next-line no-cond-assign - if (value = this._accept(TokenType.Backslash, true)) { - // \, \|, or \\ - value = this._accept(TokenType.Comma, true) - || this._accept(TokenType.Pipe, true) - || this._accept(TokenType.Backslash, true) - || value - } else { - value = this._accept(undefined, true) - } - if (!value) { - // EOF - this._backTo(token) - return false - } - values.push(value) - } - - if (values.length === 0) { - this._backTo(token) - return false - } - - parent.appendChild(new Text(values.join(''))) - return true - } - - // ${foo:}, ${foo} -> variable - private _parseComplexVariable(parent: Marker): boolean { - let name: string - const token = this._token - const match = this._accept(TokenType.Dollar) - && this._accept(TokenType.CurlyOpen) - && (name = this._accept(TokenType.VariableName, true)) - - if (!match) { - return this._backTo(token) - } - - const variable = new Variable(name) - if (this._accept(TokenType.Colon)) { - // ${foo:} - // eslint-disable-next-line no-constant-condition - while (true) { - - // ...} -> done - if (this._accept(TokenType.CurlyClose)) { - parent.appendChild(variable) - return true - } - - if (this._parse(variable)) { - continue - } - - // fallback - parent.appendChild(new Text('${' + name + ':')) - variable.children.forEach(parent.appendChild, parent) - return true - } - - } else if (this._accept(TokenType.Forwardslash)) { - // ${foo///} - if (this._parseTransform(variable)) { - parent.appendChild(variable) - return true - } - - this._backTo(token) - return false - - } else if (this._accept(TokenType.CurlyClose)) { - // ${foo} - parent.appendChild(variable) - return true - - } else { - // ${foo <- missing curly or colon - return this._backTo(token) - } - } - - private _parseTransform(parent: TransformableMarker): boolean { - // ...//} - - let transform = new Transform() - let regexValue = '' - let regexOptions = '' - - // (1) /regex - // eslint-disable-next-line no-constant-condition - while (true) { - if (this._accept(TokenType.Forwardslash)) { - break - } - - let escaped: string - // eslint-disable-next-line no-cond-assign - if (escaped = this._accept(TokenType.Backslash, true)) { - escaped = this._accept(TokenType.Forwardslash, true) || escaped - regexValue += escaped - continue - } - - if (this._token.type !== TokenType.EOF) { - regexValue += this._accept(undefined, true) - continue - } - return false - } - - // (2) /format - // eslint-disable-next-line no-constant-condition - while (true) { - if (this._accept(TokenType.Forwardslash)) { - break - } - - let escaped: string - // eslint-disable-next-line no-cond-assign - if (escaped = this._accept(TokenType.Backslash, true)) { - escaped = this._accept(TokenType.Forwardslash, true) || escaped - transform.appendChild(new Text(escaped)) - continue - } - if (this._parseFormatString(transform) || this._parseAnything(transform)) { - let text = transform.children[0] as Text - if (text && text.value && text.value.includes('\\n')) { - text.value = text.value.replace(/\\n/g, '\n') - } - continue - } - return false - } - - // (3) /option - // eslint-disable-next-line no-constant-condition - while (true) { - if (this._accept(TokenType.CurlyClose)) { - break - } - if (this._token.type !== TokenType.EOF) { - regexOptions += this._accept(undefined, true) - continue - } - return false - } - - try { - transform.regexp = new RegExp(regexValue, regexOptions) - } catch (e) { - // invalid regexp - return false - } - - parent.transform = transform - return true - } - - private _parseFormatString(parent: Transform): boolean { - - const token = this._token - if (!this._accept(TokenType.Dollar)) { - return false - } - - let complex = false - if (this._accept(TokenType.CurlyOpen)) { - complex = true - } - - let index = this._accept(TokenType.Int, true) - - if (!index) { - this._backTo(token) - return false - - } else if (!complex) { - // $1 - parent.appendChild(new FormatString(Number(index))) - return true - - } else if (this._accept(TokenType.CurlyClose)) { - // ${1} - parent.appendChild(new FormatString(Number(index))) - return true - - } else if (!this._accept(TokenType.Colon)) { - this._backTo(token) - return false - } - - if (this._accept(TokenType.Forwardslash)) { - // ${1:/upcase} - let shorthand = this._accept(TokenType.VariableName, true) - if (!shorthand || !this._accept(TokenType.CurlyClose)) { - this._backTo(token) - return false - } else { - parent.appendChild(new FormatString(Number(index), shorthand)) - return true - } - - } else if (this._accept(TokenType.Plus)) { - // ${1:+} - let ifValue = this._until(TokenType.CurlyClose) - if (ifValue) { - parent.appendChild(new FormatString(Number(index), undefined, ifValue, undefined)) - return true - } - - } else if (this._accept(TokenType.Dash)) { - // ${2:-} - let elseValue = this._until(TokenType.CurlyClose) - if (elseValue) { - parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue)) - return true - } - - } else if (this._accept(TokenType.QuestionMark)) { - // ${2:?:} - let ifValue = this._until(TokenType.Colon) - if (ifValue) { - let elseValue = this._until(TokenType.CurlyClose) - if (elseValue) { - parent.appendChild(new FormatString(Number(index), undefined, ifValue, elseValue)) - return true - } - } - - } else { - // ${1:} - let elseValue = this._until(TokenType.CurlyClose) - if (elseValue) { - parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue)) - return true - } - } - - this._backTo(token) - return false - } - - private _parseAnything(marker: Marker): boolean { - if (this._token.type !== TokenType.EOF) { - let text = this._scanner.tokenText(this._token) - marker.appendChild(new Text(text)) - this._accept(undefined) - return true - } - return false - } -} diff --git a/vim-config/plugins/coc.nvim/src/snippets/session.ts b/vim-config/plugins/coc.nvim/src/snippets/session.ts deleted file mode 100644 index 0cc9f27b..00000000 --- a/vim-config/plugins/coc.nvim/src/snippets/session.ts +++ /dev/null @@ -1,331 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { FormattingOptions } from 'jsonc-parser' -import { Emitter, Event, InsertTextMode, Range, TextDocumentContentChangeEvent, TextEdit } from 'vscode-languageserver-protocol' -import completion from '../completion' -import Document from '../model/document' -import { comparePosition, isSingleLine, positionInRange, rangeInRange } from '../util/position' -import { byteLength, characterIndex } from '../util/string' -import workspace from '../workspace' -import window from '../window' -import events from '../events' -import { CocSnippet, CocSnippetPlaceholder } from "./snippet" -import { SnippetVariableResolver } from "./variableResolve" -import { singleLineEdit } from '../util/textedit' -const logger = require('../util/logger')('snippets-session') - -export class SnippetSession { - private _isActive = false - private _currId = 0 - // Get state of line where we inserted - private applying = false - private preferComplete = false - private _snippet: CocSnippet = null - private _onCancelEvent = new Emitter() - public readonly onCancel: Event = this._onCancelEvent.event - - constructor(private nvim: Neovim, public readonly bufnr: number) { - let suggest = workspace.getConfiguration('suggest') - this.preferComplete = suggest.get('preferCompleteThanJumpPlaceholder', false) - } - - public async start(snippetString: string, select = true, range?: Range, insertTextMode?: InsertTextMode): Promise { - const { document } = this - if (!document || !document.attached) return false - void events.fire('InsertSnippet', []) - if (!range) { - let position = await window.getCursorPosition() - range = Range.create(position, position) - } - let position = range.start - const formatOptions = await workspace.getFormatOptions(this.document.uri) - await document.patchChange(true) - const currentLine = document.getline(position.line) - const currentIndent = currentLine.match(/^\s*/)[0] - let inserted = '' - if (insertTextMode === InsertTextMode.asIs) { - inserted = snippetString - } else { - inserted = normalizeSnippetString(snippetString, currentIndent, formatOptions) - } - const resolver = new SnippetVariableResolver() - const snippet = new CocSnippet(inserted, position, resolver) - await snippet.init() - const edit = TextEdit.replace(range, snippet.toString()) - if (snippetString.endsWith('\n') - && currentLine.slice(position.character).length) { - // make next line same indent - edit.newText = edit.newText + currentIndent - inserted = inserted + currentIndent - } - this.applying = true - await document.applyEdits([edit]) - this.applying = false - if (this._isActive) { - // find valid placeholder - let placeholder = this.findPlaceholder(range) - // insert to placeholder - if (placeholder && !placeholder.isFinalTabstop) { - // don't repeat snippet insert - let index = this.snippet.insertSnippet(placeholder, inserted, range) - let p = this.snippet.getPlaceholder(index) - this._currId = p.id - if (select) await this.selectPlaceholder(p) - return true - } - } - if (snippet.isPlainText) { - this.deactivate() - let placeholder = snippet.finalPlaceholder - await window.moveTo(placeholder.range.start) - return false - } - // new snippet - this._snippet = snippet - this._currId = snippet.firstPlaceholder.id - if (select) await this.selectPlaceholder(snippet.firstPlaceholder) - this.activate() - return true - } - - private activate(): void { - if (this._isActive) return - this._isActive = true - this.nvim.call('coc#snippet#enable', [], true) - } - - public deactivate(): void { - if (this._isActive) { - this._isActive = false - this._snippet = null - this.nvim.call('coc#snippet#disable', [], true) - logger.debug("[SnippetManager::cancel]") - } - this._onCancelEvent.fire(void 0) - this._onCancelEvent.dispose() - } - - public get isActive(): boolean { - return this._isActive - } - - public async nextPlaceholder(): Promise { - if (!this.isActive) return - await this.document.patchChange() - let curr = this.placeholder - let next = this.snippet.getNextPlaceholder(curr.index) - await this.selectPlaceholder(next) - } - - public async previousPlaceholder(): Promise { - if (!this.isActive) return - await this.document.patchChange() - let curr = this.placeholder - let prev = this.snippet.getPrevPlaceholder(curr.index) - await this.selectPlaceholder(prev) - } - - public async synchronizeUpdatedPlaceholders(change: TextDocumentContentChangeEvent, changedLine?: string): Promise { - if (!this.isActive || !this.document || this.applying) return - let edit: TextEdit = { range: (change as any).range, newText: change.text } - let { snippet } = this - // change outside range - let adjusted = snippet.adjustTextEdit(edit, changedLine) - if (adjusted) return - let currRange = this.placeholder.range - if (changedLine != null - && singleLineEdit(edit) - && !rangeInRange(edit.range, currRange) - && isSingleLine(currRange) - && changedLine.slice(currRange.start.character, currRange.end.character) == this.placeholder.value - && events.cursor - && events.cursor.bufnr == this.bufnr - && events.cursor.lnum == edit.range.start.line + 1) { - let col = events.cursor.col - // split changedLine with currRange - let preText = changedLine.slice(0, currRange.start.character) - let postText = changedLine.slice(currRange.end.character) - let newLine = this.document.getline(edit.range.start.line) - if (newLine.startsWith(preText) && newLine.endsWith(postText)) { - let endCharacter = newLine.length - postText.length - let cursorIdx = characterIndex(newLine, col - 1) - // make sure cursor in range - if (cursorIdx >= preText.length && cursorIdx <= endCharacter) { - let newText = newLine.slice(preText.length, endCharacter) - edit = TextEdit.replace(currRange, newText) - } - } - } - if (comparePosition(edit.range.start, snippet.range.end) > 0) { - if (!edit.newText) return - logger.info('Content change after snippet, cancelling snippet session') - this.deactivate() - return - } - let placeholder = this.findPlaceholder(edit.range) - if (!placeholder) { - logger.info('Change outside placeholder, cancelling snippet session') - this.deactivate() - return - } - if (placeholder.isFinalTabstop && snippet.finalCount <= 1) { - logger.info('Change final placeholder, cancelling snippet session') - this.deactivate() - return - } - this._currId = placeholder.id - let { edits, delta } = snippet.updatePlaceholder(placeholder, edit) - if (!edits.length) return - this.applying = true - await this.document.applyEdits(edits) - this.applying = false - if (delta) { - await this.nvim.call('coc#cursor#move_by_col', delta) - } - } - - public async selectCurrentPlaceholder(triggerAutocmd = true): Promise { - let placeholder = this.snippet.getPlaceholderById(this._currId) - if (placeholder) await this.selectPlaceholder(placeholder, triggerAutocmd) - } - - public async selectPlaceholder(placeholder: CocSnippetPlaceholder, triggerAutocmd = true): Promise { - let { nvim, document } = this - if (!document || !placeholder) return - let { start, end } = placeholder.range - const len = end.character - start.character - const col = byteLength(document.getline(start.line).slice(0, start.character)) + 1 - this._currId = placeholder.id - if (placeholder.choice) { - await nvim.call('coc#snippet#show_choices', [start.line + 1, col, len, placeholder.choice]) - if (triggerAutocmd) nvim.call('coc#util#do_autocmd', ['CocJumpPlaceholder'], true) - } else { - await this.select(placeholder, triggerAutocmd) - } - } - - private async select(placeholder: CocSnippetPlaceholder, triggerAutocmd = true): Promise { - let { range, value, isFinalTabstop } = placeholder - let { document, nvim } = this - let { start, end } = range - let { textDocument } = document - let len = textDocument.offsetAt(end) - textDocument.offsetAt(start) - let line = document.getline(start.line) - let col = line ? byteLength(line.slice(0, start.character)) : 0 - let endLine = document.getline(end.line) - let endCol = endLine ? byteLength(endLine.slice(0, end.character)) : 0 - nvim.setVar('coc_last_placeholder', { - bufnr: document.bufnr, - current_text: value, - start: { line: start.line, col, character: start.character }, - end: { line: end.line, col: endCol, character: end.character } - }, true) - let [ve, selection, pumvisible, mode] = await nvim.eval('[&virtualedit, &selection, pumvisible(), mode()]') as [string, string, number, string] - let move_cmd = '' - if (pumvisible && this.preferComplete) { - let pre = completion.hasSelected() ? '' : '\\' - await nvim.eval(`feedkeys("${pre}\\", 'in')`) - return - } - // create move cmd - if (mode != 'n') move_cmd += "\\" - if (len == 0) { - if (col == 0 || (!mode.startsWith('i') && col < byteLength(line))) { - move_cmd += 'i' - } else { - move_cmd += 'a' - } - } else { - move_cmd += 'v' - endCol = await this.getVirtualCol(end.line + 1, endCol) - if (selection == 'inclusive') { - if (end.character == 0) { - move_cmd += `${end.line}G` - } else { - move_cmd += `${end.line + 1}G${endCol}|` - } - } else if (selection == 'old') { - move_cmd += `${end.line + 1}G${endCol}|` - } else { - move_cmd += `${end.line + 1}G${endCol + 1}|` - } - col = await this.getVirtualCol(start.line + 1, col) - move_cmd += `o${start.line + 1}G${col + 1}|o\\` - } - if (mode == 'i' && move_cmd == "\\a") { - move_cmd = '' - } - nvim.pauseNotification() - nvim.setOption('virtualedit', 'onemore', true) - nvim.call('cursor', [start.line + 1, col + (move_cmd == 'a' ? 0 : 1)], true) - if (move_cmd) { - nvim.call('eval', [`feedkeys("${move_cmd}", 'in')`], true) - } - if (mode == 'i') { - nvim.call('coc#_cancel', [], true) - } - nvim.setOption('virtualedit', ve, true) - if (isFinalTabstop) { - if (this.snippet.finalCount == 1) { - logger.info('Jump to final placeholder, cancelling snippet session') - this.deactivate() - } else { - nvim.call('coc#snippet#disable', [], true) - } - } - if (workspace.env.isVim) nvim.command('redraw', true) - await nvim.resumeNotification() - if (triggerAutocmd) nvim.call('coc#util#do_autocmd', ['CocJumpPlaceholder'], true) - } - - private async getVirtualCol(line: number, col: number): Promise { - let { nvim } = this - return await nvim.eval(`virtcol([${line}, ${col}])`) as number - } - - public async checkPosition(): Promise { - if (!this.isActive) return - let position = await window.getCursorPosition() - if (this.snippet && positionInRange(position, this.snippet.range) != 0) { - logger.info('Cursor insert out of range, cancelling snippet session') - this.deactivate() - } - } - - public findPlaceholder(range: Range): CocSnippetPlaceholder | null { - if (!this.snippet) return null - let { placeholder } = this - if (placeholder && rangeInRange(range, placeholder.range)) return placeholder - return this.snippet.getPlaceholderByRange(range) || null - } - - public get placeholder(): CocSnippetPlaceholder { - if (!this.snippet) return null - return this.snippet.getPlaceholderById(this._currId) - } - - public get snippet(): CocSnippet { - return this._snippet - } - - private get document(): Document { - return workspace.getDocument(this.bufnr) - } -} - -export function normalizeSnippetString(snippet: string, indent: string, opts: FormattingOptions): string { - let lines = snippet.split(/\r?\n/) - let ind = opts.insertSpaces ? ' '.repeat(opts.tabSize) : '\t' - let tabSize = opts.tabSize || 2 - lines = lines.map((line, idx) => { - let space = line.match(/^\s*/)[0] - let pre = space - let isTab = space.startsWith('\t') - if (isTab && opts.insertSpaces) { - pre = ind.repeat(space.length) - } else if (!isTab && !opts.insertSpaces) { - pre = ind.repeat(space.length / tabSize) - } - return (idx == 0 || line.length == 0 ? '' : indent) + pre + line.slice(space.length) - }) - return lines.join('\n') -} diff --git a/vim-config/plugins/coc.nvim/src/snippets/snippet.ts b/vim-config/plugins/coc.nvim/src/snippets/snippet.ts deleted file mode 100644 index e38824b6..00000000 --- a/vim-config/plugins/coc.nvim/src/snippets/snippet.ts +++ /dev/null @@ -1,264 +0,0 @@ -import { Position, Range, TextEdit } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { adjustPosition, comparePosition, editRange, getChangedPosition, rangeInRange, isSingleLine } from '../util/position' -import * as Snippets from "./parser" -import { VariableResolver } from './parser' -import { byteLength } from '../util/string' -const logger = require('../util/logger')('snippets-snipet') - -export interface CocSnippetPlaceholder { - index: number - id: number // unique index - line: number - // range in current buffer - range: Range - value: string - isFinalTabstop: boolean - transform: boolean - isVariable: boolean - choice?: string[] -} - -export class CocSnippet { - private _parser: Snippets.SnippetParser = new Snippets.SnippetParser() - private _placeholders: CocSnippetPlaceholder[] - private tmSnippet: Snippets.TextmateSnippet - - constructor(private _snippetString: string, - private position: Position, - private _variableResolver?: VariableResolver) { - } - - public async init(): Promise { - const snippet = this._parser.parse(this._snippetString, true) - let { _variableResolver } = this - if (_variableResolver) { - await snippet.resolveVariables(_variableResolver) - } - this.tmSnippet = snippet - this.update() - } - - public adjustPosition(characterCount: number, lineCount: number): void { - let { line, character } = this.position - this.position = { - line: line + lineCount, - character: character + characterCount - } - this.update() - } - - // adjust for edit before snippet - public adjustTextEdit(edit: TextEdit, changedLine?: string): boolean { - let { range, newText } = edit - if (comparePosition(this.range.start, range.end) < 0) { - let { start, end } = range - let overlaped = end.character - this.range.start.character - // shift single line range to left as far as possible - if (changedLine && comparePosition(this.range.start, start) > 0 - && isSingleLine(range) - && start.character - overlaped >= 0 - && changedLine.slice(start.character - overlaped, start.character) == - changedLine.slice(this.range.start.character, this.range.start.character + overlaped)) { - edit.range = range = Range.create(start.line, start.character - overlaped, end.line, end.character - overlaped) - } else { - return false - } - } - - // check change of placeholder at beginning - if (!newText.includes('\n') - && comparePosition(range.start, range.end) == 0 - && comparePosition(this.range.start, range.start) == 0) { - let idx = this._placeholders.findIndex(o => comparePosition(o.range.start, range.start) == 0) - if (idx !== -1) return false - } - let changed = getChangedPosition(this.range.start, edit) - if (changed.line == 0 && changed.character == 0) return true - this.adjustPosition(changed.character, changed.line) - return true - } - - public get isPlainText(): boolean { - if (this._placeholders.length > 1) return false - return this._placeholders.every(o => o.value == '') - } - - public get finalCount(): number { - return this._placeholders.filter(o => o.isFinalTabstop).length - } - - public toString(): string { - return this.tmSnippet.toString() - } - - public get range(): Range { - let { position } = this - const content = this.tmSnippet.toString() - const doc = TextDocument.create('untitled:/1', 'snippet', 0, content) - const pos = doc.positionAt(content.length) - const end = pos.line == 0 ? position.character + pos.character : pos.character - return Range.create(position, Position.create(position.line + pos.line, end)) - } - - public get firstPlaceholder(): CocSnippetPlaceholder | null { - let index = 0 - for (let p of this._placeholders) { - if (p.index == 0) continue - if (index == 0 || p.index < index) { - index = p.index - } - } - return this.getPlaceholder(index) - } - - public get lastPlaceholder(): CocSnippetPlaceholder { - let index = 0 - for (let p of this._placeholders) { - if (index == 0 || p.index > index) { - index = p.index - } - } - return this.getPlaceholder(index) - } - - public getPlaceholderById(id: number): CocSnippetPlaceholder { - return this._placeholders.find(o => o.id == id) - } - - public getPlaceholder(index: number): CocSnippetPlaceholder { - let placeholders = this._placeholders.filter(o => o.index == index) - let filtered = placeholders.filter(o => !o.transform) - return filtered.length ? filtered[0] : placeholders[0] - } - - public getPrevPlaceholder(index: number): CocSnippetPlaceholder { - if (index == 0) return this.lastPlaceholder - let prev = this.getPlaceholder(index - 1) - if (!prev) return this.getPrevPlaceholder(index - 1) - return prev - } - - public getNextPlaceholder(index: number): CocSnippetPlaceholder { - let indexes = this._placeholders.map(o => o.index) - let max = Math.max.apply(null, indexes) - if (index >= max) return this.finalPlaceholder - let next = this.getPlaceholder(index + 1) - if (!next) return this.getNextPlaceholder(index + 1) - return next - } - - public get finalPlaceholder(): CocSnippetPlaceholder { - return this._placeholders.find(o => o.isFinalTabstop) - } - - public getPlaceholderByRange(range: Range): CocSnippetPlaceholder { - return this._placeholders.find(o => rangeInRange(range, o.range)) - } - - public insertSnippet(placeholder: CocSnippetPlaceholder, snippet: string, range: Range): number { - let { start } = placeholder.range - // let offset = position.character - start.character - let editStart = Position.create( - range.start.line - start.line, - range.start.line == start.line ? range.start.character - start.character : range.start.character - ) - let editEnd = Position.create( - range.end.line - start.line, - range.end.line == start.line ? range.end.character - start.character : range.end.character - ) - let editRange = Range.create(editStart, editEnd) - let first = this.tmSnippet.insertSnippet(snippet, placeholder.id, editRange) - this.update() - return first - } - - // update internal positions, no change of buffer - // return TextEdit list when needed - public updatePlaceholder(placeholder: CocSnippetPlaceholder, edit: TextEdit): { edits: TextEdit[]; delta: number } { - // let { start, end } = edit.range - let { range } = this - let { value, id, index } = placeholder - let newText = editRange(placeholder.range, value, edit) - let delta = 0 - if (!newText.includes('\n')) { - for (let p of this._placeholders) { - if (p.index == index && - p.id < id && - p.line == placeholder.range.start.line) { - let text = this.tmSnippet.getPlaceholderText(p.id, newText) - delta = delta + byteLength(text) - byteLength(p.value) - } - } - } - if (placeholder.isVariable) { - this.tmSnippet.updateVariable(id, newText) - } else { - this.tmSnippet.updatePlaceholder(id, newText) - } - let endPosition = adjustPosition(range.end, edit) - let snippetEdit: TextEdit = { - range: Range.create(range.start, endPosition), - newText: this.tmSnippet.toString() - } - this.update() - return { edits: [snippetEdit], delta } - } - - private update(): void { - const snippet = this.tmSnippet - const { line, character } = this.position - const document = TextDocument.create('untitled:/1', 'snippet', 0, snippet.toString()) - const { placeholders, variables, maxIndexNumber } = snippet - const variableIndexMap: Map = new Map() - let variableIndex = maxIndexNumber + 1 - - this._placeholders = [...placeholders, ...variables].map((p, idx) => { - const offset = snippet.offset(p) - const position = document.positionAt(offset) - const start: Position = { - line: line + position.line, - character: position.line == 0 ? character + position.character : position.character - } - let index: number - if (p instanceof Snippets.Variable) { - let key = p.name - if (variableIndexMap.has(key)) { - index = variableIndexMap.get(key) - } else { - variableIndexMap.set(key, variableIndex) - index = variableIndex - variableIndex = variableIndex + 1 - } - // variableIndex = variableIndex + 1 - } else { - index = p.index - } - const value = p.toString() - const lines = value.split(/\r?\n/) - let res: CocSnippetPlaceholder = { - range: Range.create(start, { - line: start.line + lines.length - 1, - character: lines.length == 1 ? start.character + value.length : lines[lines.length - 1].length - }), - transform: p.transform != null, - line: start.line, - id: idx, - index, - value, - isVariable: p instanceof Snippets.Variable, - isFinalTabstop: (p as Snippets.Placeholder).index === 0 - } - Object.defineProperty(res, 'snippet', { - enumerable: false - }) - if (p instanceof Snippets.Placeholder && p.choice) { - let { options } = p.choice - if (options && options.length) { - res.choice = options.map(o => o.value) - } - } - return res - }) - } -} diff --git a/vim-config/plugins/coc.nvim/src/snippets/string.ts b/vim-config/plugins/coc.nvim/src/snippets/string.ts deleted file mode 100644 index f1f26207..00000000 --- a/vim-config/plugins/coc.nvim/src/snippets/string.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -export class SnippetString { - public static isSnippetString(thing: any): thing is SnippetString { - if (thing instanceof SnippetString) { - return true - } - if (!thing) { - return false - } - return typeof thing.value === 'string' - } - - private static _escape(value: string): string { - return value.replace(/\$|}|\\/g, '\\$&') - } - - private _tabstop = 1 - - public value: string - - constructor(value?: string) { - this.value = value || '' - } - - public appendText(str: string): SnippetString { - this.value += SnippetString._escape(str) - return this - } - - public appendTabstop(num: number = this._tabstop++): SnippetString { - this.value += '$' - this.value += num - return this - } - - public appendPlaceholder( - value: string | ((snippet: SnippetString) => any), - num: number = this._tabstop++ - ): SnippetString { - if (typeof value === 'function') { - const nested = new SnippetString() - nested._tabstop = this._tabstop - value(nested) - this._tabstop = nested._tabstop - value = nested.value - } else { - value = SnippetString._escape(value) - } - - this.value += '${' - this.value += num - this.value += ':' - this.value += value - this.value += '}' - - return this - } - - public appendChoice( - values: string[], - num: number = this._tabstop++ - ): SnippetString { - const value = values.map(s => s.replace(/\$|}|\\|,/g, '\\$&')).join(',') - - this.value += '${' - this.value += num - this.value += '|' - this.value += value - this.value += '|}' - - return this - } - - public appendVariable( - name: string, - defaultValue?: string | ((snippet: SnippetString) => any) - ): SnippetString { - if (typeof defaultValue === 'function') { - const nested = new SnippetString() - nested._tabstop = this._tabstop - defaultValue(nested) - this._tabstop = nested._tabstop - defaultValue = nested.value - } else if (typeof defaultValue === 'string') { - defaultValue = defaultValue.replace(/\$|}/g, '\\$&') - } - - this.value += '${' - this.value += name - if (defaultValue) { - this.value += ':' - this.value += defaultValue - } - this.value += '}' - - return this - } -} diff --git a/vim-config/plugins/coc.nvim/src/snippets/variableResolve.ts b/vim-config/plugins/coc.nvim/src/snippets/variableResolve.ts deleted file mode 100644 index f04cb671..00000000 --- a/vim-config/plugins/coc.nvim/src/snippets/variableResolve.ts +++ /dev/null @@ -1,94 +0,0 @@ -import path from 'path' -import window from '../window' -import { Variable, VariableResolver } from "./parser" -const logger = require('../util/logger')('snippets-variable') - -export class SnippetVariableResolver implements VariableResolver { - private _variableToValue: { [key: string]: string } = {} - - constructor() { - const currentDate = new Date() - Object.assign(this._variableToValue, { - CURRENT_YEAR: currentDate.getFullYear().toString(), - CURRENT_YEAR_SHORT: currentDate - .getFullYear() - .toString() - .slice(-2), - CURRENT_MONTH: (currentDate.getMonth() + 1).toString(), - CURRENT_DATE: currentDate.getDate().toString(), - CURRENT_HOUR: currentDate.getHours().toString(), - CURRENT_MINUTE: currentDate.getMinutes().toString(), - CURRENT_SECOND: currentDate.getSeconds().toString(), - CURRENT_DAY_NAME: currentDate.toLocaleString("en-US", { weekday: "long" }), - CURRENT_DAY_NAME_SHORT: currentDate.toLocaleString("en-US", { weekday: "short" }), - CURRENT_MONTH_NAME: currentDate.toLocaleString("en-US", { month: "long" }), - CURRENT_MONTH_NAME_SHORT: currentDate.toLocaleString("en-US", { month: "short" }), - TM_FILENAME: null, - TM_FILENAME_BASE: null, - TM_DIRECTORY: null, - TM_FILEPATH: null, - YANK: null, - TM_LINE_INDEX: null, - TM_LINE_NUMBER: null, - TM_CURRENT_LINE: null, - TM_CURRENT_WORD: null, - TM_SELECTED_TEXT: null, - CLIPBOARD: null - }) - } - - private async resolveValue(name: string): Promise { - let { nvim } = window - if (['TM_FILENAME', 'TM_FILENAME_BASE', 'TM_DIRECTORY', 'TM_FILEPATH'].includes(name)) { - let filepath = await nvim.eval('expand("%:p")') as string - if (name == 'TM_FILENAME') return path.basename(filepath) - if (name == 'TM_FILENAME_BASE') return path.basename(filepath, path.extname(filepath)) - if (name == 'TM_DIRECTORY') return path.dirname(filepath) - if (name == 'TM_FILEPATH') return filepath - } - if (name == 'YANK') { - let yank = await nvim.call('getreg', ['""']) as string - return yank - } - if (name == 'TM_LINE_INDEX') { - let lnum = await nvim.call('line', ['.']) as number - return (lnum - 1).toString() - } - if (name == 'TM_LINE_NUMBER') { - let lnum = await nvim.call('line', ['.']) as number - return lnum.toString() - } - if (name == 'TM_CURRENT_LINE') { - let line = await nvim.call('getline', ['.']) as string - return line - } - if (name == 'TM_CURRENT_WORD') { - let word = await nvim.eval(`expand('')`) as string - return word - } - if (name == 'TM_SELECTED_TEXT') { - let text = await nvim.eval(`get(g:,'coc_selected_text', '')`) as string - return text - } - if (name == 'CLIPBOARD') { - return await nvim.eval('@*') as string - } - } - - public async resolve(variable: Variable): Promise { - const name = variable.name - let resolved = this._variableToValue[name] - if (resolved != null) return resolved.toString() - // resolve value from vim - let value = await this.resolveValue(name) - if (value) return value - // use default value when resolved is undefined - if (variable.children && variable.children.length) { - return variable.toString() - } - if (!this._variableToValue.hasOwnProperty(name)) { - return name - } - return '' - } -} diff --git a/vim-config/plugins/coc.nvim/src/sources/index.ts b/vim-config/plugins/coc.nvim/src/sources/index.ts deleted file mode 100644 index afb8ac7b..00000000 --- a/vim-config/plugins/coc.nvim/src/sources/index.ts +++ /dev/null @@ -1,428 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import fastDiff from 'fast-diff' -import fs from 'fs' -import path from 'path' -import util from 'util' -import { CompletionItemKind, Disposable, DocumentSelector } from 'vscode-languageserver-protocol' -import events from '../events' -import extensions from '../extensions' -import { CompletionItemProvider } from '../provider' -import { CompleteOption, ExtendedCompleteItem, ISource, SourceConfig, SourceStat, SourceType } from '../types' -import { disposeAll, getUri } from '../util' -import { statAsync } from '../util/fs' -import { score } from '../util/match' -import { isEmpty } from '../util/object' -import { byteSlice } from '../util/string' -import window from '../window' -import workspace from '../workspace' -import Source from './source' -import LanguageSource, { CompleteConfig } from './source-language' -import VimSource from './source-vim' -const logger = require('../util/logger')('sources') - -export class Sources { - private sourceMap: Map = new Map() - private disposables: Disposable[] = [] - private remoteSourcePaths: string[] = [] - private completeConfig: CompleteConfig - - public init(): void { - this.loadCompleteConfig() - workspace.onDidChangeConfiguration(e => { - if (e.affectsConfiguration('suggest')) { - this.loadCompleteConfig() - } - }, null, this.disposables) - this.createNativeSources() - this.createRemoteSources() - events.on('BufEnter', this.onDocumentEnter, this, this.disposables) - workspace.watchOption('runtimepath', async (oldValue, newValue) => { - let result = fastDiff(oldValue, newValue) - for (let [changeType, value] of result) { - if (changeType == 1) { - let paths = value.replace(/,$/, '').split(',') - for (let p of paths) { - if (p) await this.createVimSources(p) - } - } - } - }, this.disposables) - } - - private loadCompleteConfig(): void { - let suggest = workspace.getConfiguration('suggest') - let labels = suggest.get<{ [key: string]: string }>('completionItemKindLabels', {}) - let map = new Map([ - [CompletionItemKind.Text, labels['text'] || 'v'], - [CompletionItemKind.Method, labels['method'] || 'f'], - [CompletionItemKind.Function, labels['function'] || 'f'], - [CompletionItemKind.Constructor, typeof labels['constructor'] == 'function' ? 'f' : labels['con' + 'structor']], - [CompletionItemKind.Field, labels['field'] || 'm'], - [CompletionItemKind.Variable, labels['variable'] || 'v'], - [CompletionItemKind.Class, labels['class'] || 'C'], - [CompletionItemKind.Interface, labels['interface'] || 'I'], - [CompletionItemKind.Module, labels['module'] || 'M'], - [CompletionItemKind.Property, labels['property'] || 'm'], - [CompletionItemKind.Unit, labels['unit'] || 'U'], - [CompletionItemKind.Value, labels['value'] || 'v'], - [CompletionItemKind.Enum, labels['enum'] || 'E'], - [CompletionItemKind.Keyword, labels['keyword'] || 'k'], - [CompletionItemKind.Snippet, labels['snippet'] || 'S'], - [CompletionItemKind.Color, labels['color'] || 'v'], - [CompletionItemKind.File, labels['file'] || 'F'], - [CompletionItemKind.Reference, labels['reference'] || 'r'], - [CompletionItemKind.Folder, labels['folder'] || 'F'], - [CompletionItemKind.EnumMember, labels['enumMember'] || 'm'], - [CompletionItemKind.Constant, labels['constant'] || 'v'], - [CompletionItemKind.Struct, labels['struct'] || 'S'], - [CompletionItemKind.Event, labels['event'] || 'E'], - [CompletionItemKind.Operator, labels['operator'] || 'O'], - [CompletionItemKind.TypeParameter, labels['typeParameter'] || 'T'], - ]) - let floatEnable = suggest.get('floatEnable', true) - let detailField = suggest.get('detailField', 'preview') - if (detailField == 'preview' && (!floatEnable || !workspace.floatSupported)) { - detailField = 'menu' - } - this.completeConfig = Object.assign(this.completeConfig || {}, { - labels: map, - floatEnable, - detailField, - defaultKindText: labels['default'] || '', - priority: suggest.get('languageSourcePriority', 99), - echodocSupport: suggest.get('echodocSupport', false), - snippetsSupport: suggest.get('snippetsSupport', true), - detailMaxLength: suggest.get('detailMaxLength', 100), - invalidInsertCharacters: suggest.get('invalidInsertCharacters', ['(', '<', '{', '[', '\r', '\n']), - }) - } - - private get nvim(): Neovim { - return workspace.nvim - } - - private createNativeSources(): void { - try { - this.disposables.push((require('./native/around')).regist(this.sourceMap)) - this.disposables.push((require('./native/buffer')).regist(this.sourceMap)) - this.disposables.push((require('./native/file')).regist(this.sourceMap)) - } catch (e) { - console.error('Create source error:' + e.message) - } - } - - public createLanguageSource( - name: string, - shortcut: string, - selector: DocumentSelector | null, - provider: CompletionItemProvider, - triggerCharacters: string[], - priority?: number | undefined, - allCommitCharacters?: string[] - ): Disposable { - let source = new LanguageSource( - name, - shortcut, - provider, - selector, - triggerCharacters || [], - allCommitCharacters || [], - priority, - this.completeConfig) - logger.debug('created service source', name) - this.sourceMap.set(name, source) - return { - dispose: () => { - this.sourceMap.delete(name) - } - } - } - - private async createVimSourceExtension(nvim: Neovim, filepath: string): Promise { - let name = path.basename(filepath, '.vim') - try { - await nvim.command(`source ${filepath}`) - let fns = await nvim.call('coc#util#remote_fns', name) as string[] - for (let fn of ['init', 'complete']) { - if (!fns.includes(fn)) { - window.showMessage(`${fn} not found for source ${name}`, 'error') - return null - } - } - let props = await nvim.call(`coc#source#${name}#init`, []) - let packageJSON = { - name: `coc-source-${name}`, - engines: { - coc: ">= 0.0.1" - }, - activationEvents: props.filetypes ? props.filetypes.map(f => `onLanguage:${f}`) : ['*'], - contributes: { - configuration: { - properties: { - [`coc.source.${name}.enable`]: { - type: 'boolean', - default: true - }, - [`coc.source.${name}.firstMatch`]: { - type: 'boolean', - default: !!props.firstMatch - }, - [`coc.source.${name}.triggerCharacters`]: { - type: 'number', - default: props.triggerCharacters || [] - }, - [`coc.source.${name}.priority`]: { - type: 'number', - default: props.priority || 9 - }, - [`coc.source.${name}.shortcut`]: { - type: 'string', - default: props.shortcut || name.slice(0, 3).toUpperCase(), - description: 'Shortcut text shown in complete menu.' - }, - [`coc.source.${name}.disableSyntaxes`]: { - type: 'array', - default: [], - items: { - type: 'string' - } - }, - [`coc.source.${name}.filetypes`]: { - type: 'array', - default: props.filetypes || null, - description: 'Enabled filetypes.', - items: { - type: 'string' - } - } - } - } - } - } - let source = new VimSource({ - name, - filepath, - sourceType: SourceType.Remote, - optionalFns: fns.filter(n => !['init', 'complete'].includes(n)) - }) - let isActive = false - let extension: any = { - id: packageJSON.name, - packageJSON, - exports: void 0, - extensionPath: filepath, - activate: () => { - isActive = true - this.addSource(source) - return Promise.resolve() - } - } - Object.defineProperty(extension, 'isActive', { - get: () => isActive - }) - extensions.registerExtension(extension, () => { - isActive = false - this.removeSource(source) - }) - } catch (e) { - window.showMessage(`Error on create vim source ${name}: ${e.message}`, 'error') - } - } - - private createRemoteSources(): void { - let { runtimepath } = workspace.env - let paths = runtimepath.split(',') - for (let path of paths) { - this.createVimSources(path).logError() - } - } - - private async createVimSources(pluginPath: string): Promise { - if (this.remoteSourcePaths.includes(pluginPath)) return - this.remoteSourcePaths.push(pluginPath) - let folder = path.join(pluginPath, 'autoload/coc/source') - let stat = await statAsync(folder) - if (stat && stat.isDirectory()) { - let arr = await util.promisify(fs.readdir)(folder) - arr = arr.filter(s => s.endsWith('.vim')) - let files = arr.map(s => path.join(folder, s)) - if (files.length == 0) return - await Promise.all(files.map(p => this.createVimSourceExtension(this.nvim, p))) - } - } - - public get names(): string[] { - return Array.from(this.sourceMap.keys()) - } - - public get sources(): ISource[] { - return Array.from(this.sourceMap.values()) - } - - public has(name): boolean { - return this.names.findIndex(o => o == name) != -1 - } - - public getSource(name: string): ISource | null { - if (!name) return null - return this.sourceMap.get(name) || null - } - - public shouldCommit(item: ExtendedCompleteItem, commitCharacter: string): boolean { - if (!item || !item.source) return false - let source = this.getSource(item.source) - if (source && source.sourceType == SourceType.Service && typeof source.shouldCommit === 'function') { - return source.shouldCommit(item, commitCharacter) - } - return false - } - - public getCompleteSources(opt: CompleteOption): ISource[] { - let { filetype } = opt - let pre = byteSlice(opt.line, 0, opt.colnr - 1) - let isTriggered = opt.input == '' && !!opt.triggerCharacter - let uri = getUri(opt.filepath, opt.bufnr, '', workspace.env.isCygwin) - if (isTriggered) return this.getTriggerSources(pre, filetype, uri) - return this.getNormalSources(opt.filetype, uri) - } - - /** - * Get sources should be used without trigger. - * - * @param {string} filetype - * @returns {ISource[]} - */ - public getNormalSources(filetype: string, uri: string): ISource[] { - return this.sources.filter(source => { - let { filetypes, triggerOnly, documentSelector, enable } = source - if (!enable || triggerOnly || (filetypes && !filetypes.includes(filetype))) { - return false - } - if (documentSelector && score(documentSelector, uri, filetype) == 0) { - return false - } - if (this.disabledByLanguageId(source, filetype)) { - return false - } - return true - }) - } - - private checkTrigger(source: ISource, pre: string, character: string): boolean { - let { triggerCharacters, triggerPatterns } = source - if (!triggerCharacters && !triggerPatterns) return false - if (character && triggerCharacters && triggerCharacters.includes(character)) { - return true - } - if (triggerPatterns && triggerPatterns.findIndex(p => p.test(pre)) !== -1) { - return true - } - return false - } - - public shouldTrigger(pre: string, languageId: string, uri: string): boolean { - let sources = this.getTriggerSources(pre, languageId, uri) - return sources.length > 0 - } - - public getTriggerSources(pre: string, languageId: string, uri: string): ISource[] { - let character = pre.length ? pre[pre.length - 1] : '' - if (!character) return [] - return this.sources.filter(source => { - let { filetypes, enable, documentSelector } = source - if (!enable || (filetypes && !filetypes.includes(languageId))) { - return false - } - if (documentSelector && score(documentSelector, uri, languageId) == 0) { - return false - } - if (this.disabledByLanguageId(source, languageId)) return false - return this.checkTrigger(source, pre, character) - }) - } - - public addSource(source: ISource): Disposable { - let { name } = source - if (this.names.includes(name)) { - logger.warn(`Recreate source ${name}`) - } - this.sourceMap.set(name, source) - return Disposable.create(() => { - this.sourceMap.delete(name) - }) - } - - public removeSource(source: ISource | string): void { - let name = typeof source == 'string' ? source : source.name - this.sourceMap.delete(name) - } - - public async refresh(name?: string): Promise { - for (let source of this.sources) { - if (!name || source.name == name) { - if (typeof source.refresh === 'function') { - await Promise.resolve(source.refresh()) - } - } - } - } - - public toggleSource(name: string): void { - if (!name) return - let source = this.getSource(name) - if (!source) return - if (typeof source.toggle === 'function') { - source.toggle() - } - } - - public sourceStats(): SourceStat[] { - let res: SourceStat[] = [] - let items = this.sources - for (let item of items) { - res.push({ - name: item.name, - priority: item.priority, - triggerCharacters: item.triggerCharacters || [], - shortcut: item.shortcut || '', - filetypes: item.filetypes || [], - filepath: item.filepath || '', - type: item.sourceType == SourceType.Native - ? 'native' : item.sourceType == SourceType.Remote - ? 'remote' : 'service', - disabled: !item.enable - }) - } - return res - } - - private onDocumentEnter(bufnr: number): void { - let { sources } = this - for (let s of sources) { - if (s.enable && typeof s.onEnter == 'function') { - s.onEnter(bufnr) - } - } - } - - public createSource(config: SourceConfig): Disposable { - if (!config.name || !config.doComplete) { - throw new Error(`name and doComplete required for createSource`) - } - let source = new Source(Object.assign({ sourceType: SourceType.Service } as any, config)) - return this.addSource(source) - } - - private disabledByLanguageId(source: ISource, languageId: string): boolean { - let map = workspace.env.disabledSources - if (isEmpty(map)) return false - let list = map ? map[languageId] : [] - return Array.isArray(list) && list.includes(source.name) - } - - public dispose(): void { - disposeAll(this.disposables) - } -} - -export default new Sources() diff --git a/vim-config/plugins/coc.nvim/src/sources/native/around.ts b/vim-config/plugins/coc.nvim/src/sources/native/around.ts deleted file mode 100644 index dcf6a8f8..00000000 --- a/vim-config/plugins/coc.nvim/src/sources/native/around.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { Disposable } from 'vscode-languageserver-protocol' -import Source from '../source' -import { CompleteOption, CompleteResult, ISource } from '../../types' -import workspace from '../../workspace' -const logger = require('../../util/logger')('sources-around') - -export default class Around extends Source { - constructor() { - super({ - name: 'around', - filepath: __filename - }) - } - - public doComplete(opt: CompleteOption): Promise { - let { bufnr, input } = opt - if (input.length === 0) return null - let document = workspace.getDocument(bufnr) - if (!document) return null - let words = document.words - let moreWords = document.getMoreWords() - words.push(...moreWords) - words = this.filterWords(words, opt) - return Promise.resolve({ - items: words.map(word => ({ - word, - menu: this.menu - })) - }) - } -} - -export function regist(sourceMap: Map): Disposable { - sourceMap.set('around', new Around()) - return Disposable.create(() => { - sourceMap.delete('around') - }) -} diff --git a/vim-config/plugins/coc.nvim/src/sources/native/buffer.ts b/vim-config/plugins/coc.nvim/src/sources/native/buffer.ts deleted file mode 100644 index ede62a48..00000000 --- a/vim-config/plugins/coc.nvim/src/sources/native/buffer.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { Disposable } from 'vscode-languageserver-protocol' -import Source from '../source' -import { CompleteOption, CompleteResult, ISource } from '../../types' -import workspace from '../../workspace' -const logger = require('../../util/logger')('sources-buffer') - -export default class Buffer extends Source { - constructor() { - super({ - name: 'buffer', - filepath: __filename - }) - } - - public get ignoreGitignore(): boolean { - return this.getConfig('ignoreGitignore', true) - } - - private getWords(bufnr: number): string[] { - let { ignoreGitignore } = this - let words: string[] = [] - workspace.documents.forEach(document => { - if (document.bufnr == bufnr) return - if (ignoreGitignore && document.isIgnored) return - for (let word of document.words) { - if (!words.includes(word)) { - words.push(word) - } - } - }) - return words - } - - public doComplete(opt: CompleteOption): Promise { - let { bufnr, input } = opt - if (input.length == 0) return null - let words = this.getWords(bufnr) - words = this.filterWords(words, opt) - return Promise.resolve({ - items: words.map(word => ({ - word, - menu: this.menu - })) - }) - } -} - -export function regist(sourceMap: Map): Disposable { - sourceMap.set('buffer', new Buffer()) - return Disposable.create(() => { - sourceMap.delete('buffer') - }) -} diff --git a/vim-config/plugins/coc.nvim/src/sources/native/file.ts b/vim-config/plugins/coc.nvim/src/sources/native/file.ts deleted file mode 100644 index 70226a99..00000000 --- a/vim-config/plugins/coc.nvim/src/sources/native/file.ts +++ /dev/null @@ -1,151 +0,0 @@ -import fs from 'fs' -import minimatch from 'minimatch' -import path from 'path' -import util from 'util' -import { Disposable } from 'vscode-languageserver-protocol' -import Source from '../source' -import { CompleteOption, CompleteResult, ISource, VimCompleteItem } from '../../types' -import { statAsync } from '../../util/fs' -import { byteSlice } from '../../util/string' -import workspace from '../../workspace' -const logger = require('../../util/logger')('sources-file') -const pathRe = /(?:\.{0,2}|~|\$HOME|([\w]+)|[a-zA-Z]:|)(\/|\\)(?:[\u4e00-\u9fa5\w.@()-]+(\/|\\))*(?:[\u4e00-\u9fa5\w.@()-])*$/ - -interface PathOption { - pathstr: string - part: string - startcol: number - input: string -} - -export default class File extends Source { - constructor() { - super({ - name: 'file', - filepath: __filename - }) - } - - private resolveEnvVariables(str: string): string { - let replaced = str - // windows - replaced = replaced.replace(/%([^%]+)%/g, (_, n) => process.env[n]) - // linux and mac - replaced = replaced.replace( - /\$([A-Z_]+[A-Z0-9_]*)|\${([A-Z0-9_]*)}/gi, - (_, a, b) => process.env[a || b] - ) - return replaced - } - - private getPathOption(opt: CompleteOption): PathOption | null { - let { line, colnr } = opt - let part = byteSlice(line, 0, colnr - 1) - part = this.resolveEnvVariables(part) - if (!part || part.endsWith('//')) return null - let ms = part.match(pathRe) - if (ms && ms.length) { - const pathstr = workspace.expand(ms[0]) - let input = ms[0].match(/[^/\\]*$/)[0] - return { pathstr, part: ms[1], startcol: colnr - input.length - 1, input } - } - return null - } - - private async getFileItem(root: string, filename: string): Promise { - let f = path.join(root, filename) - let stat = await statAsync(f) - if (stat) { - let abbr = stat.isDirectory() ? filename + '/' : filename - let word = filename - return { word, abbr } - } - return null - } - - public filterFiles(files: string[]): string[] { - let ignoreHidden = this.getConfig('ignoreHidden', true) - let ignorePatterns = this.getConfig('ignorePatterns', []) - return files.filter(f => { - if (f == null) return false - if (ignoreHidden && f.startsWith(".")) return false - for (let p of ignorePatterns) { - if (minimatch(f, p, { dot: true })) return false - } - return true - }) - } - - public async getItemsFromRoot(pathstr: string, root: string): Promise { - let res = [] - let part = pathstr.endsWith("/") ? pathstr : path.dirname(pathstr) - let dir = path.isAbsolute(pathstr) ? part : path.join(root, part) - try { - let stat = await statAsync(dir) - if (stat && stat.isDirectory()) { - let files = await util.promisify(fs.readdir)(dir) - files = this.filterFiles(files) - let items = await Promise.all(files.map(filename => this.getFileItem(dir, filename))) - res = res.concat(items) - } - res = res.filter(item => item != null) - return res - } catch (e) { - logger.error(`Error on list files:`, e) - return res - } - } - - public get trimSameExts(): string[] { - return this.getConfig('trimSameExts', []) - } - - public async doComplete(opt: CompleteOption): Promise { - let { col, filepath } = opt - let option = this.getPathOption(opt) - if (!option) return null - let { pathstr, part, startcol, input } = option - if (startcol < opt.col) return null - let startPart = opt.col == startcol ? '' : byteSlice(opt.line, opt.col, startcol) - let dirname = path.dirname(filepath) - let ext = path.extname(path.basename(filepath)) - let cwd = await this.nvim.call('getcwd', []) - let root - if (pathstr.startsWith(".")) { - root = filepath ? path.dirname(filepath) : cwd - } else if (pathstr.startsWith("/")) { - root = pathstr.endsWith("/") ? pathstr : path.dirname(pathstr) - } else if (part) { - if (fs.existsSync(path.join(dirname, part))) { - root = dirname - } else if (fs.existsSync(path.join(cwd, part))) { - root = cwd - } - } else { - root = cwd - } - if (!root) return null - let items = await this.getItemsFromRoot(pathstr, root) - let trimExt = this.trimSameExts.includes(ext) - let first = input[0] - if (first && col == startcol) items = items.filter(o => o.word[0] === first) - return { - items: items.map(item => { - let ex = path.extname(item.word) - item.word = trimExt && ex === ext ? item.word.replace(ext, '') : item.word - return { - word: `${startPart}${item.word}`, - abbr: `${startPart}${item.abbr}`, - menu: this.menu - } - }) - } - } -} - -export function regist(sourceMap: Map): Disposable { - sourceMap.set('file', new File()) - return Disposable.create(() => { - sourceMap.delete('file') - }) -} diff --git a/vim-config/plugins/coc.nvim/src/sources/source-language.ts b/vim-config/plugins/coc.nvim/src/sources/source-language.ts deleted file mode 100644 index 1a28f25b..00000000 --- a/vim-config/plugins/coc.nvim/src/sources/source-language.ts +++ /dev/null @@ -1,394 +0,0 @@ -import { CancellationToken, CompletionItem, CompletionItemKind, CompletionList, CompletionTriggerKind, DocumentSelector, InsertReplaceEdit, InsertTextFormat, Position, Range, TextEdit } from 'vscode-languageserver-protocol' -import commands from '../commands' -import { CompletionItemProvider } from '../provider' -import snippetManager from '../snippets/manager' -import { SnippetParser } from '../snippets/parser' -import { CompleteOption, CompleteResult, ExtendedCompleteItem, ISource, SourceType } from '../types' -import { getChangedFromEdits, rangeOverlap } from '../util/position' -import { byteIndex, byteLength, byteSlice, characterIndex } from '../util/string' -import window from '../window' -import workspace from '../workspace' -const logger = require('../util/logger')('source-language') - -export interface CompleteConfig { - labels: Map - snippetsSupport: boolean - defaultKindText: string - priority: number - echodocSupport: boolean - detailMaxLength: number - detailField: string - invalidInsertCharacters: string[] - floatEnable: boolean -} - -export default class LanguageSource implements ISource { - public priority: number - public sourceType: SourceType.Service - private _enabled = true - private filetype: string - private resolvedIndexes: Set = new Set() - private completeItems: CompletionItem[] = [] - constructor( - public readonly name: string, - public readonly shortcut: string, - private provider: CompletionItemProvider, - public readonly documentSelector: DocumentSelector, - public readonly triggerCharacters: string[], - public readonly allCommitCharacters: string[], - priority: number | undefined, - private readonly completeConfig: CompleteConfig, - ) { - this.priority = typeof priority === 'number' ? priority : completeConfig.priority - } - - public get enable(): boolean { - return this._enabled - } - - public toggle(): void { - this._enabled = !this._enabled - } - - public shouldCommit?(item: ExtendedCompleteItem, character: string): boolean { - let completeItem = this.completeItems[item.index] - if (!completeItem) return false - let commitCharacters = [...this.allCommitCharacters, ...(completeItem.commitCharacters || [])] - return commitCharacters.includes(character) - } - - public async doComplete(opt: CompleteOption, token: CancellationToken): Promise { - let { provider, name } = this - let { triggerCharacter, bufnr } = opt - this.filetype = opt.filetype - this.resolvedIndexes.clear() - this.completeItems = [] - let triggerKind: CompletionTriggerKind = this.getTriggerKind(opt) - let position = this.getPosition(opt) - let context: any = { triggerKind, option: opt } - if (triggerKind == CompletionTriggerKind.TriggerCharacter) context.triggerCharacter = triggerCharacter - let result: CompletionItem[] | CompletionList | undefined - try { - let doc = workspace.getDocument(bufnr) - result = await Promise.resolve(provider.provideCompletionItems(doc.textDocument, position, token, context)) - } catch (e) { - // don't disturb user - logger.error(`Complete "${name}" error:`, e) - return null - } - if (!result || token.isCancellationRequested) return null - let completeItems = Array.isArray(result) ? result : result.items - if (!completeItems || completeItems.length == 0) return null - this.completeItems = completeItems - let startcol = getStartColumn(opt.line, completeItems) - let option: CompleteOption = Object.assign({}, opt) - let prefix: string - if (startcol != null) { - if (startcol < option.col) { - prefix = byteSlice(opt.line, startcol, option.col) - } - option.col = startcol - } - let items: ExtendedCompleteItem[] = completeItems.map((o, index) => { - let item = this.convertVimCompleteItem(o, this.shortcut, option, prefix) - item.index = index - return item - }) - let isIncomplete = typeof result['isIncomplete'] === 'boolean' ? result['isIncomplete'] : false - return { startcol, isIncomplete, items } - } - - public async onCompleteResolve(item: ExtendedCompleteItem, token: CancellationToken): Promise { - let { index } = item - let resolving = this.completeItems[index] - if (!resolving || this.resolvedIndexes.has(index)) return - let hasResolve = typeof this.provider.resolveCompletionItem === 'function' - if (hasResolve) { - this.resolvedIndexes.add(index) - try { - let resolved = await Promise.resolve(this.provider.resolveCompletionItem(Object.assign({}, resolving), token)) - if (!resolved || token.isCancellationRequested) { - this.resolvedIndexes.delete(index) - } else if (resolved !== resolving) { - Object.assign(resolving, resolved) - } - } catch (e) { - this.resolvedIndexes.delete(index) - logger.error(`Error on complete resolve: ${e.message}`, e.stack) - } - } - if (typeof item.documentation === 'undefined') { - let { documentation, detail } = resolving - if (!documentation && !detail) return - let docs = [] - if (detail && !item.detailShown && detail != item.word) { - detail = detail.replace(/\n\s*/g, ' ') - if (detail.length) { - let isText = /^[\w-\s.,\t\n]+$/.test(detail) - docs.push({ filetype: isText ? 'txt' : this.filetype, content: detail }) - } - } - if (documentation) { - if (typeof documentation == 'string') { - docs.push({ filetype: 'markdown', content: documentation }) - } else if (documentation.value) { - docs.push({ - filetype: documentation.kind == 'markdown' ? 'markdown' : 'txt', - content: documentation.value - }) - } - } - item.documentation = docs - } - } - - public async onCompleteDone(vimItem: ExtendedCompleteItem, opt: CompleteOption): Promise { - let item = this.completeItems[vimItem.index] - if (!item) return - let line = opt.linenr - 1 - if (item.insertText != null && !item.textEdit) { - item.textEdit = { - range: Range.create(line, opt.col, line, opt.colnr - 1), - newText: item.insertText - } - } - if (vimItem.line) Object.assign(opt, { line: vimItem.line }) - try { - let isSnippet = await this.applyTextEdit(item, vimItem.word, opt) - let { additionalTextEdits } = item - if (additionalTextEdits && item.textEdit) { - let r = InsertReplaceEdit.is(item.textEdit) ? item.textEdit.replace : item.textEdit.range - additionalTextEdits = additionalTextEdits.filter(edit => { - let er = InsertReplaceEdit.is(edit) ? edit.replace : edit.range - if (rangeOverlap(r, er)) { - logger.error('Filtered overlap additionalTextEdit:', edit) - return false - } - return true - }) - } - await this.applyAdditionalEdits(additionalTextEdits, opt.bufnr, isSnippet) - if (isSnippet) await snippetManager.selectCurrentPlaceholder() - if (item.command && commands.has(item.command.command)) { - void commands.execute(item.command) - } - } catch (e) { - logger.error('Error on CompleteDone:', e) - } - } - - private async applyTextEdit(item: CompletionItem, word: string, option: CompleteOption): Promise { - let { nvim } = workspace - let { textEdit } = item - if (!textEdit) return false - let { line, bufnr, linenr } = option - let doc = workspace.getDocument(bufnr) - if (!doc) return false - let newText = textEdit.newText - let range = InsertReplaceEdit.is(textEdit) ? textEdit.replace : textEdit.range - let isSnippet = item.insertTextFormat === InsertTextFormat.Snippet - // replace inserted word - let start = line.substr(0, range.start.character) - let end = line.substr(range.end.character) - if (isSnippet && this.completeConfig.snippetsSupport === false) { - // could be wrong, but maybe best we can do. - isSnippet = false - newText = word - } - if (isSnippet) { - let currline = doc.getline(linenr - 1) - let endCharacter = currline.length - end.length - let r = Range.create(linenr - 1, range.start.character, linenr - 1, endCharacter) - // can't select, since additionalTextEdits would break selection - return await snippetManager.insertSnippet(newText, false, r, item.insertTextMode) - } - let newLines = `${start}${newText}${end}`.split(/\r?\n/) - if (newLines.length == 1) { - await nvim.call('coc#util#setline', [linenr, newLines[0]]) - await window.moveTo(Position.create(linenr - 1, (start + newText).length)) - } else { - let buffer = nvim.createBuffer(bufnr) - await buffer.setLines(newLines, { - start: linenr - 1, - end: linenr, - strictIndexing: false - }) - let line = linenr - 1 + newLines.length - 1 - let character = newLines[newLines.length - 1].length - end.length - await window.moveTo({ line, character }) - } - return false - } - - private getTriggerKind(opt: CompleteOption): CompletionTriggerKind { - let { triggerCharacters } = this - let isTrigger = triggerCharacters.includes(opt.triggerCharacter) - let triggerKind: CompletionTriggerKind = CompletionTriggerKind.Invoked - if (opt.triggerForInComplete) { - triggerKind = CompletionTriggerKind.TriggerForIncompleteCompletions - } else if (isTrigger) { - triggerKind = CompletionTriggerKind.TriggerCharacter - } - return triggerKind - } - - private async applyAdditionalEdits(textEdits: TextEdit[], bufnr: number, snippet: boolean): Promise { - if (!textEdits || textEdits.length == 0) return - let document = workspace.getDocument(bufnr) - if (!document) return - await document.patchChange(true) - // move cursor after edit - let changed = null - let pos = await window.getCursorPosition() - if (!snippet) changed = getChangedFromEdits(pos, textEdits) - await document.applyEdits(textEdits) - if (changed) await window.moveTo(Position.create(pos.line + changed.line, pos.character + changed.character)) - } - - private convertVimCompleteItem(item: CompletionItem, shortcut: string, opt: CompleteOption, prefix: string): ExtendedCompleteItem { - let { echodocSupport, detailMaxLength, invalidInsertCharacters, detailField, labels, defaultKindText } = this.completeConfig - let hasAdditionalEdit = item.additionalTextEdits && item.additionalTextEdits.length > 0 - let isSnippet = item.insertTextFormat === InsertTextFormat.Snippet || hasAdditionalEdit - let label = item.label.trim() - let obj: ExtendedCompleteItem = { - word: getWord(item, opt, invalidInsertCharacters), - abbr: label, - menu: `[${shortcut}]`, - kind: getKindString(item.kind, labels, defaultKindText), - sortText: item.sortText || null, - sourceScore: item['score'] || null, - filterText: item.filterText || label, - isSnippet, - dup: item.data && item.data.dup == 0 ? 0 : 1 - } - if (prefix) { - if (!obj.filterText.startsWith(prefix)) { - if (item.textEdit && item.textEdit.newText.startsWith(prefix)) { - obj.filterText = item.textEdit.newText.split(/\r?\n/)[0] - } - } - if (!item.textEdit && !obj.word.startsWith(prefix)) { - // fix remains completeItem that should not change startcol - obj.word = `${prefix}${obj.word}` - } - } - if (item && item.detail && detailField != 'preview') { - let detail = item.detail.replace(/\n\s*/g, ' ') - if (byteLength(detail) < detailMaxLength) { - if (detailField == 'menu') { - obj.menu = `${detail} ${obj.menu}` - } else if (detailField == 'abbr') { - obj.abbr = `${obj.abbr} - ${detail}` - } - obj.detailShown = 1 - } - } - if (item.documentation) { - obj.info = typeof item.documentation == 'string' ? item.documentation : item.documentation.value - } else { - obj.info = '' - } - if (obj.word == '') obj.empty = 1 - if (item.textEdit) obj.line = opt.line - if (item.kind == CompletionItemKind.Folder && !obj.abbr.endsWith('/')) { - obj.abbr = obj.abbr + '/' - } - if (echodocSupport && item.kind >= 2 && item.kind <= 4) { - let fields = [item.detail || '', obj.abbr, obj.word] - for (let s of fields) { - if (s.includes('(')) { - obj.signature = s - break - } - } - } - if (item.preselect) obj.preselect = true - if (item.data?.optional) obj.abbr = obj.abbr + '?' - return obj - } - - private getPosition(opt: CompleteOption): Position { - let { line, linenr, colnr } = opt - let part = byteSlice(line, 0, colnr - 1) - return { - line: linenr - 1, - character: part.length - } - } -} - -/* - * Check new startcol by check start characters. - */ -export function getStartColumn(line: string, items: CompletionItem[]): number | null { - let first = items[0] - if (!first.textEdit) return null - let range = InsertReplaceEdit.is(first.textEdit) ? first.textEdit.replace : first.textEdit.range - let { character } = range.start - for (let i = 1; i < Math.min(10, items.length); i++) { - let o = items[i] - if (!o.textEdit) return null - let r = InsertReplaceEdit.is(o.textEdit) ? o.textEdit.replace : o.textEdit.range - if (r.start.character !== character) return null - } - return byteIndex(line, character) -} - -export function getKindString(kind: CompletionItemKind, map: Map, defaultValue = ''): string { - return map.get(kind) || defaultValue -} - -export function getWord(item: CompletionItem, opt: CompleteOption, invalidInsertCharacters: string[]): string { - let { label, data, insertTextFormat, insertText, textEdit } = item - let word: string - let newText: string - if (data && typeof data.word === 'string') return data.word - if (textEdit) { - let range = InsertReplaceEdit.is(textEdit) ? textEdit.replace : textEdit.range - newText = textEdit.newText - if (range && range.start.line == range.end.line) { - let { line, col, colnr } = opt - let character = characterIndex(line, col) - if (range.start.character > character) { - let before = line.slice(character, range.start.character) - newText = before + newText - } else { - let start = line.slice(range.start.character, character) - if (start.length && newText.startsWith(start)) { - newText = newText.slice(start.length) - } - } - character = characterIndex(line, colnr - 1) - if (range.end.character > character) { - let end = line.slice(character, range.end.character) - if (newText.endsWith(end)) { - newText = newText.slice(0, - end.length) - } - } - } - } else { - newText = insertText - } - if (insertTextFormat == InsertTextFormat.Snippet - && newText - && newText.includes('$')) { - let parser = new SnippetParser() - let text = parser.text(newText) - word = text ? getValidWord(text, invalidInsertCharacters) : label - } else { - word = getValidWord(newText, invalidInsertCharacters) || label - } - return word || '' -} - -export function getValidWord(text: string, invalidChars: string[]): string { - if (!text) return '' - if (!invalidChars.length) return text - for (let i = 0; i < text.length; i++) { - let c = text[i] - if (invalidChars.includes(c)) { - return text.slice(0, i) - } - } - return text -} diff --git a/vim-config/plugins/coc.nvim/src/sources/source-vim.ts b/vim-config/plugins/coc.nvim/src/sources/source-vim.ts deleted file mode 100644 index c0a02a18..00000000 --- a/vim-config/plugins/coc.nvim/src/sources/source-vim.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { CancellationToken } from 'vscode-languageserver-protocol' -import { CompleteOption, CompleteResult, ExtendedCompleteItem } from '../types' -import { fuzzyChar } from '../util/fuzzy' -import { byteSlice } from '../util/string' -import workspace from '../workspace' -import window from '../window' -import Source from './source' -const logger = require('../util/logger')('sources-source-vim') - -export default class VimSource extends Source { - - private async callOptinalFunc(fname: string, args: any[]): Promise { - let exists = this.optionalFns.includes(fname) - if (!exists) return null - let name = `coc#source#${this.name}#${fname}` - let res - try { - res = await this.nvim.call(name, args) - } catch (e) { - window.showMessage(`Vim error from source ${this.name}: ${e.message}`, 'error') - return null - } - return res - } - - public async shouldComplete(opt: CompleteOption): Promise { - let shouldRun = await super.shouldComplete(opt) - if (!shouldRun) return false - if (!this.optionalFns.includes('should_complete')) return true - let res = await this.callOptinalFunc('should_complete', [opt]) - return !!res - } - - public async refresh(): Promise { - await this.callOptinalFunc('refresh', []) - } - - public async onCompleteDone(item: ExtendedCompleteItem, _opt: CompleteOption): Promise { - if (!this.optionalFns.includes('on_complete')) return - await this.callOptinalFunc('on_complete', [item]) - } - - public onEnter(bufnr: number): void { - if (!this.optionalFns.includes('on_enter')) return - let doc = workspace.getDocument(bufnr) - if (!doc) return - let { filetypes } = this - if (filetypes && !filetypes.includes(doc.filetype)) return - this.callOptinalFunc('on_enter', [{ - bufnr, - uri: doc.uri, - languageId: doc.filetype - }]).logError() - } - - public async doComplete(opt: CompleteOption, token: CancellationToken): Promise { - let { col, input, line, colnr } = opt - let startcol: number | null = await this.callOptinalFunc('get_startcol', [opt]) - if (token.isCancellationRequested) return - if (startcol) { - if (startcol < 0) return null - startcol = Number(startcol) - // invalid startcol - if (isNaN(startcol) || startcol < 0) startcol = col - if (startcol !== col) { - input = byteSlice(line, startcol, colnr - 1) - opt = Object.assign({}, opt, { - col: startcol, - changed: col - startcol, - input - }) - } - } - let items: ExtendedCompleteItem[] = await this.nvim.callAsync('coc#util#do_complete', [this.name, opt]) - if (!items || items.length == 0 || token.isCancellationRequested) return null - if (this.firstMatch && input.length) { - let ch = input[0] - items = items.filter(item => { - let cfirst = item.filterText ? item.filterText[0] : item.word[0] - return fuzzyChar(ch, cfirst) - }) - } - items = items.map(item => { - if (typeof item == 'string') { - return { word: item, menu: this.menu, isSnippet: this.isSnippet } - } - let menu = item.menu ? item.menu + ' ' : '' - item.menu = `${menu}${this.menu}` - item.isSnippet = this.isSnippet - delete item.user_data - return item - }) - let res: CompleteResult = { items } - if (startcol) res.startcol = startcol - return res - } -} diff --git a/vim-config/plugins/coc.nvim/src/sources/source.ts b/vim-config/plugins/coc.nvim/src/sources/source.ts deleted file mode 100644 index 4999984e..00000000 --- a/vim-config/plugins/coc.nvim/src/sources/source.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationToken } from 'vscode-languageserver-protocol' -import { CompleteOption, CompleteResult, ISource, SourceConfig, SourceType, VimCompleteItem } from '../types' -import { byteSlice } from '../util/string' -import workspace from '../workspace' -const logger = require('../util/logger')('sources-source') - -export default class Source implements ISource { - public readonly name: string - public readonly filepath: string - public readonly sourceType: SourceType - public readonly isSnippet: boolean - protected readonly nvim: Neovim - private _disabled = false - private defaults: any - constructor(option: SourceConfig) { - this.nvim = workspace.nvim - // readonly properties - this.name = option.name - this.filepath = option.filepath || '' - this.sourceType = option.sourceType || SourceType.Native - this.isSnippet = !!option.isSnippet - this.defaults = option - } - - /** - * Priority of source, higher priority makes items lower index. - */ - public get priority(): number { - return this.getConfig('priority', 1) - } - - /** - * When triggerOnly is true, not trigger completion on keyword character insert. - */ - public get triggerOnly(): boolean { - let triggerOnly = this.defaults['triggerOnly'] - if (typeof triggerOnly == 'boolean') return triggerOnly - if (!this.triggerCharacters && !this.triggerPatterns) return false - return Array.isArray(this.triggerPatterns) && this.triggerPatterns.length != 0 - } - - public get triggerCharacters(): string[] { - return this.getConfig('triggerCharacters', null) - } - - // exists opitonnal function names for remote source - public get optionalFns(): string[] { - return this.defaults['optionalFns'] || [] - } - - public get triggerPatterns(): RegExp[] | null { - let patterns = this.getConfig('triggerPatterns', null) - if (!patterns || patterns.length == 0) return null - return patterns.map(s => (typeof s === 'string') ? new RegExp(s + '$') : s) - } - - public get shortcut(): string { - let shortcut = this.getConfig('shortcut', '') - return shortcut ? shortcut : this.name.slice(0, 3) - } - - public get enable(): boolean { - if (this._disabled) return false - return this.getConfig('enable', true) - } - - public get filetypes(): string[] | null { - return this.getConfig('filetypes', null) - } - - public get disableSyntaxes(): string[] { - return this.getConfig('disableSyntaxes', []) - } - - public getConfig(key: string, defaultValue?: T): T | null { - let config = workspace.getConfiguration(`coc.source.${this.name}`) - defaultValue = this.defaults.hasOwnProperty(key) ? this.defaults[key] : defaultValue - return config.get(key, defaultValue) - } - - public toggle(): void { - this._disabled = !this._disabled - } - - public get firstMatch(): boolean { - return this.getConfig('firstMatch', true) - } - - public get menu(): string { - let { shortcut } = this - return shortcut ? `[${shortcut}]` : '' - } - - /** - * Filter words that too short or doesn't match input - */ - protected filterWords(words: string[], opt: CompleteOption): string[] { - let { firstMatch } = this - let res = [] - let { input } = opt - let cword = opt.word - if (!input.length) return [] - let cFirst = input[0] - for (let word of words) { - if (!word || word.length < 3) continue - if (firstMatch && cFirst != word[0]) continue - if (!firstMatch && cFirst.toLowerCase() != word[0].toLowerCase()) continue - if (word == cword || word == input) continue - res.push(word) - } - return res - } - - /** - * fix start column for new valid characters - * - * @protected - * @param {CompleteOption} opt - * @param {string[]} valids - valid charscters - * @returns {number} - */ - protected fixStartcol(opt: CompleteOption, valids: string[]): number { - let { col, input, line, bufnr } = opt - let start = byteSlice(line, 0, col) - let document = workspace.getDocument(bufnr) - if (!document) return col - let { chars } = document - for (let i = start.length - 1; i >= 0; i--) { - let c = start[i] - if (!chars.isKeywordChar(c) && !valids.includes(c)) { - break - } - input = `${c}${input}` - col = col - 1 - } - opt.col = col - opt.input = input - return col - } - - public async shouldComplete(opt: CompleteOption): Promise { - let { disableSyntaxes } = this - if (opt.synname && disableSyntaxes && disableSyntaxes.length) { - let synname = (opt.synname || '').toLowerCase() - if (disableSyntaxes.findIndex(s => synname.includes(s.toLowerCase())) !== -1) { - return false - } - } - let fn = this.defaults['shouldComplete'] - if (typeof fn === 'function') return await Promise.resolve(fn.call(this, opt)) - return true - } - - public async refresh(): Promise { - let fn = this.defaults['refresh'] - if (typeof fn === 'function') await Promise.resolve(fn.call(this)) - } - - public async onCompleteDone(item: VimCompleteItem, opt: CompleteOption): Promise { - let fn = this.defaults['onCompleteDone'] - if (typeof fn === 'function') await Promise.resolve(fn.call(this, item, opt)) - } - - public async doComplete(opt: CompleteOption, token: CancellationToken): Promise { - let fn = this.defaults['doComplete'] - if (typeof fn === 'function') return await Promise.resolve(fn.call(this, opt, token)) - return null - } -} diff --git a/vim-config/plugins/coc.nvim/src/tree/BasicDataProvider.ts b/vim-config/plugins/coc.nvim/src/tree/BasicDataProvider.ts deleted file mode 100644 index 6b24dbd6..00000000 --- a/vim-config/plugins/coc.nvim/src/tree/BasicDataProvider.ts +++ /dev/null @@ -1,261 +0,0 @@ -import { v4 as uuid } from 'uuid' -import { CancellationToken, MarkupContent, Disposable, Emitter, Event } from 'vscode-languageserver-protocol' -import commandsManager from '../commands' -import { ProviderResult } from '../provider' -import { disposeAll } from '../util' -import { TreeDataProvider, TreeItemAction } from './index' -import { TreeItem, TreeItemCollapsibleState, TreeItemIcon, TreeItemLabel } from './TreeItem' - -export interface TreeNode { - label: string - key?: string - tooltip?: string | MarkupContent - description?: string - deprecated?: boolean - icon?: TreeItemIcon - children?: this[] -} - -export interface ProviderOptions { - provideData: () => ProviderResult - expandLevel?: number - onDispose?: () => void - handleClick?: (item: T) => ProviderResult - resolveIcon?: (item: T) => TreeItemIcon | undefined - resolveItem?: (item: TreeItem, element: T, token: CancellationToken) => ProviderResult - resolveActions?(item: TreeItem, element: T): ProviderResult[]> -} - -function isIcon(obj: any): obj is TreeItemIcon { - if (!obj) return false - return typeof obj.text === 'string' && typeof obj.hlGroup === 'string' -} - -/** - * Check lable and key, children not checked. - */ -function sameTreeNode(one: T, two: T): boolean { - if (one.label === two.label - && one.deprecated === two.deprecated - && one.key === two.key) { - return true - } - return false -} - -/** - * Check changes of nodes array, children not checked. - */ -function sameTreeNodes(one: T[], two: T[]): boolean { - if (one.length !== two.length) return false - return one.every((v, idx) => sameTreeNode(v, two[idx])) -} - -/** - * Tree data provider for resolved tree with children. - * Use update() to update data. - */ -export default class BasicDataProvider implements TreeDataProvider { - private disposables: Disposable[] = [] - private invokeCommand: string - private data: T[] | undefined - // only fired for change of exists TreeNode - private _onDidChangeTreeData = new Emitter() - public onDidChangeTreeData: Event = this._onDidChangeTreeData.event - public resolveActions: (item: TreeItem, element: T) => ProviderResult[]> - // data is shared with TreeView - constructor(private opts: ProviderOptions) { - this.invokeCommand = `_invoke_${uuid()}` - this.disposables.push(commandsManager.registerCommand(this.invokeCommand, async (node: T) => { - if (typeof opts.handleClick === 'function') { - await opts.handleClick(node) - } else { - console.error('Handler not found') - } - }, null, true)) - if (typeof opts.resolveActions === 'function') { - this.resolveActions = opts.resolveActions.bind(this) - } - } - - private iterate(node: T, parentNode: T | undefined, level: number, fn: (node: T, parentNode: T | undefined, level: number) => void | boolean): void | boolean { - let res = fn(node, parentNode, level) - if (res === false) return false - if (Array.isArray(node.children)) { - for (let element of node.children) { - let res = this.iterate(element, node, level + 1, fn) - if (res === false) return false - } - } - return res - } - - /** - * Change old array to new nodes in place, keep old reference when possible. - */ - private updateNodes(old: T[], data: T[], parentNode: T | undefined, fireEvent = true): void { - let sameNodes = sameTreeNodes(old, data) - const applyNode = (previous: T, curr: T, fireEvent: boolean): void => { - let changed = false - for (let key of Object.keys(curr)) { - if (['children', 'key'].includes(key)) continue - previous[key] = curr[key] - } - if (previous.children?.length && !curr.children?.length) { - // removed children - delete previous.children - changed = true - } - if (!previous.children?.length && curr.children?.length) { - // new children - previous.children = curr.children - changed = true - } - if (changed) { - if (fireEvent) this._onDidChangeTreeData.fire(previous) - return - } - if (previous.children?.length && curr.children?.length) { - this.updateNodes(previous.children, curr.children, previous, fireEvent) - } - } - if (sameNodes) { - for (let i = 0; i < old.length; i++) { - applyNode(old[i], data[i], fireEvent) - } - } else { - let oldNodes = old.splice(0, old.length) - let used: Set = new Set() - for (let i = 0; i < data.length; i++) { - let curr = data[i] - let findIndex: number - if (curr.key) { - findIndex = oldNodes.findIndex((o, i) => !used.has(i) && o.key == curr.key) - } else { - findIndex = oldNodes.findIndex((o, i) => !used.has(i) && o.label == curr.label) - } - if (findIndex === -1) { - old[i] = curr - } else { - used.add(findIndex) - let previous = oldNodes[findIndex] - applyNode(previous, curr, false) - old[i] = previous - } - } - if (fireEvent) { - this._onDidChangeTreeData.fire(parentNode) - } - } - } - - /** - * Update with new data, fires change event when necessary. - */ - public update(data: T[], reset?: boolean): ReadonlyArray { - if (!this.data) return - if (reset) { - this.data = data || [] - this._onDidChangeTreeData.fire(undefined) - } else { - this.updateNodes(this.data, data || [], undefined) - } - return this.data - } - - public getTreeItem(node: T): TreeItem { - let label: string | TreeItemLabel = node.label - let { expandLevel } = this.opts - let item: TreeItem - if (!node.children?.length) { - item = new TreeItem(label) - } else { - if (expandLevel && expandLevel > 0) { - let level = this.getLevel(node) - let state = level && level <= expandLevel ? TreeItemCollapsibleState.Expanded : TreeItemCollapsibleState.Collapsed - item = new TreeItem(label, state) - } else { - item = new TreeItem(label, TreeItemCollapsibleState.Collapsed) - } - } - item.description = node.description - if (node.deprecated) item.deprecated = true - if (node.tooltip) item.tooltip = node.tooltip - if (isIcon(node.icon)) { - item.icon = node.icon - } else if (typeof this.opts.resolveIcon === 'function') { - let res = this.opts.resolveIcon(node) - if (res) item.icon = res - } - return item - } - - public async getChildren(element?: T): Promise { - if (element) return element.children || [] - if (this.data) return this.data - let data = await Promise.resolve(this.opts.provideData()) - if (!Array.isArray(data)) throw new Error(`Unable to fetch data`) - this.data = data - return data - } - - /** - * Use reference check - */ - public getParent(element: T): T | undefined { - if (!this.data) return undefined - let find: T - for (let item of this.data) { - let res = this.iterate(item, null, 0, (node, parentNode) => { - if (node === element) { - find = parentNode - return false - } - }) - if (res === false) break - } - return find - } - - private getLevel(element: T): number { - if (!this.data) return undefined - let level = 0 - for (let item of this.data) { - let res = this.iterate(item, null, 1, (node, _parentNode, l) => { - if (node === element) { - level = l - return false - } - }) - if (res === false) break - } - return level - } - - /** - * Resolve command and tooltip - */ - public async resolveTreeItem(item: TreeItem, element: T, token: CancellationToken): Promise { - if (typeof this.opts.resolveItem === 'function') { - let res = await Promise.resolve(this.opts.resolveItem(item, element, token)) - if (res) Object.assign(item, res) - } - if (!item.command) { - item.command = { - title: `invoke ${element.label}`, - command: this.invokeCommand, - arguments: [element] - } - } - return item - } - - public dispose(): void { - this.data = [] - this._onDidChangeTreeData.dispose() - if (typeof this.opts.onDispose === 'function') { - this.opts.onDispose() - } - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/tree/TreeItem.ts b/vim-config/plugins/coc.nvim/src/tree/TreeItem.ts deleted file mode 100644 index 2ae4fb91..00000000 --- a/vim-config/plugins/coc.nvim/src/tree/TreeItem.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { Command, MarkupContent } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import path from 'path' - -export interface TreeItemLabel { - label: string - highlights?: [number, number][] -} - -// eslint-disable-next-line no-redeclare -export namespace TreeItemLabel { - export function is(obj: any): obj is TreeItemLabel { - return typeof obj.label == 'string' - } -} - -export interface TreeItemIcon { - text: string - hlGroup: string -} - -/** - * Collapsible state of the tree item - */ -export enum TreeItemCollapsibleState { - /** - * Determines an item can be neither collapsed nor expanded. Implies it has no children. - */ - None = 0, - /** - * Determines an item is collapsed - */ - Collapsed = 1, - /** - * Determines an item is expanded - */ - Expanded = 2 -} - -export class TreeItem { - public label: string | TreeItemLabel - public id?: string - public description?: string - public icon?: TreeItemIcon - public resourceUri?: URI - public command?: Command - public tooltip?: string | MarkupContent - public deprecated?: boolean - - constructor(label: string | TreeItemLabel, collapsibleState?: TreeItemCollapsibleState) - // eslint-disable-next-line @typescript-eslint/unified-signatures - constructor(resourceUri: URI, collapsibleState?: TreeItemCollapsibleState) - constructor(label: string | TreeItemLabel | URI, public collapsibleState: TreeItemCollapsibleState = TreeItemCollapsibleState.None) { - if (URI.isUri(label)) { - this.resourceUri = label - this.label = path.basename(label.path) - this.id = label.toString() - } else { - this.label = label - } - } -} diff --git a/vim-config/plugins/coc.nvim/src/tree/TreeView.ts b/vim-config/plugins/coc.nvim/src/tree/TreeView.ts deleted file mode 100644 index aa034376..00000000 --- a/vim-config/plugins/coc.nvim/src/tree/TreeView.ts +++ /dev/null @@ -1,979 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import { CancellationTokenSource, Disposable, Emitter, Event, MarkupContent, MarkupKind, Range } from 'vscode-languageserver-protocol' -import commandManager from '../commands' -import events from '../events' -import FloatFactory from '../model/floatFactory' -import { ConfigurationChangeEvent, Documentation, HighlightItem } from '../types' -import { disposeAll } from '../util' -import { Mutex } from '../util/mutex' -import { equals } from '../util/object' -import { byteLength, byteSlice } from '../util/string' -import { hasMatch, positions, score, groupPositions } from '../util/fzy' -import workspace from '../workspace' -import window from '../window' -import Filter, { sessionKey } from './filter' -import { TreeDataProvider, TreeView, TreeViewExpansionEvent, TreeViewOptions, TreeViewSelectionChangeEvent, TreeViewVisibilityChangeEvent } from './index' -import { TreeItem, TreeItemCollapsibleState, TreeItemLabel } from './TreeItem' -const logger = require('../util/logger')('BasicTreeView') -const highlightNamespace = 'tree' -const signOffset = 3000 -let globalId = 1 - -interface TreeViewConfig { - openedIcon: string - closedIcon: string -} - -interface RenderedItem { - line: string - level: number - node: T -} - -interface ExtendedItem extends RenderedItem { - index: number - score: number - highlights: HighlightItem[] -} - -interface LineState { - /** - * Line count used by message - */ - messageCount: number - /** - * Line count used by title - */ - titleCount: number -} - -interface Keys { - invoke: string - toggle: string - actions: string - collapseAll: string - toggleSelection: string - close: string - activeFilter: string - selectNext: string - selectPrevious: string -} - -interface TreeItemData { - item: TreeItem - resolved: boolean -} - -/** - * Basic TreeView implementation - */ -export default class BasicTreeView implements TreeView { - // Resolved TreeItems - private bufnr: number | undefined - private winid: number | undefined - private config: TreeViewConfig - private keys: Keys - private originalWin: number - private _creating: boolean - private _selection: T[] = [] - private _onDidExpandElement = new Emitter>() - private _onDidCollapseElement = new Emitter>() - private _onDidChangeSelection = new Emitter>() - private _onDidChangeVisibility = new Emitter() - public onDidExpandElement: Event> = this._onDidExpandElement.event - public onDidCollapseElement: Event> = this._onDidCollapseElement.event - public onDidChangeSelection: Event> = this._onDidChangeSelection.event - public onDidChangeVisibility: Event = this._onDidChangeVisibility.event - public message: string | undefined - public title: string - public description: string | undefined - private retryTimers = 0 - private renderedItems: RenderedItem[] = [] - private provider: TreeDataProvider - private nodesMap: Map = new Map() - private mutex: Mutex = new Mutex() - private timer: NodeJS.Timer - private disposables: Disposable[] = [] - private tooltipFactory: FloatFactory - private resolveTokenSource: CancellationTokenSource | undefined - private lineState: LineState = { titleCount: 0, messageCount: 0 } - private filter: Filter | undefined - private filterText: string | undefined - private itemsToFilter: T[] | undefined - private readonly canSelectMany: boolean - private readonly leafIndent: boolean - private readonly winfixwidth: boolean - constructor(private viewId: string, opts: TreeViewOptions) { - this.loadConfiguration() - workspace.onDidChangeConfiguration(this.loadConfiguration, this, this.disposables) - if (opts.enableFilter) { - this.filter = new Filter(this.nvim, [this.keys.selectNext, this.keys.selectPrevious, this.keys.invoke]) - } - this.tooltipFactory = new FloatFactory(workspace.nvim) - this.canSelectMany = !!opts.canSelectMany - this.provider = opts.treeDataProvider - this.leafIndent = opts.disableLeafIndent !== true - this.winfixwidth = opts.winfixwidth !== false - let message: string | undefined - Object.defineProperty(this, 'message', { - set: (msg: string | undefined) => { - message = msg ? msg.replace(/\r?\n/g, ' ') : undefined - this.updateHeadLines() - }, - get: () => { - return message - } - }) - let title = viewId.replace(/\r?\n/g, ' ') - Object.defineProperty(this, 'title', { - set: (newTitle: string) => { - title = newTitle ? newTitle.replace(/\r?\n/g, ' ') : undefined - this.updateHeadLines() - }, - get: () => { - return title - } - }) - let description: string | undefined - Object.defineProperty(this, 'description', { - set: (desc: string | undefined) => { - description = desc ? desc.replace(/\r?\n/g, ' ') : undefined - this.updateHeadLines() - }, - get: () => { - return description - } - }) - let filterText: string | undefined - Object.defineProperty(this, 'filterText', { - set: (text: string | undefined) => { - let { titleCount, messageCount } = this.lineState - let start = titleCount + messageCount - if (text != null) { - let highlights: HighlightItem[] = [{ - lnum: start, - colStart: byteLength(text), - colEnd: byteLength(text) + 1, - hlGroup: 'Cursor' - }] - this.renderedItems = [] - this.updateUI([text + ' '], highlights, start, -1, true) - void this.doFilter(text) - } else if (filterText != null) { - this.updateUI([], [], start, start + 1) - } - filterText = text - }, - get: () => { - return filterText - } - }) - if (this.provider.onDidChangeTreeData) { - this.provider.onDidChangeTreeData(this.onDataChange, this, this.disposables) - } - events.on('BufUnload', bufnr => { - if (bufnr != this.bufnr) return - this.winid = undefined - this.bufnr = undefined - this._onDidChangeVisibility.fire({ visible: false }) - this.dispose() - }, null, this.disposables) - events.on('CursorHold', async bufnr => { - if (bufnr != this.bufnr) return - await this.onHover() - }, null, this.disposables) - events.on(['CursorMoved', 'BufEnter'], () => { - this.cancelResolve() - }, null, this.disposables) - events.on('WinEnter', winid => { - if (winid != this.windowId || !this.filter?.activated) return - let buf = this.nvim.createBuffer(this.bufnr) - let line = this.startLnum - 1 - let len = this.filterText ? this.filterText.length : 0 - let range = Range.create(line, len, line, len + 1) - buf.highlightRanges(highlightNamespace, 'Cursor', [range]) - this.nvim.call('coc#prompt#start_prompt', [sessionKey], true) - this.redraw() - }, null, this.disposables) - events.on('WinLeave', winid => { - if (winid != this.windowId || !this.filter?.activated) return - let buf = this.nvim.createBuffer(this.bufnr) - this.nvim.call('coc#prompt#stop_prompt', [sessionKey], true) - buf.clearNamespace(highlightNamespace, this.startLnum - 1, this.startLnum) - }, null, this.disposables) - this.disposables.push(this._onDidChangeVisibility, this._onDidChangeSelection, this._onDidCollapseElement, this._onDidExpandElement) - if (this.filter) { - this.filter.onDidExit(node => { - this.nodesMap.clear() - this.filterText = undefined - this.itemsToFilter = undefined - if (node && typeof this.provider.getParent === 'function') { - this.renderedItems = [] - void this.reveal(node, { focus: true }) - } else { - this.clearSelection() - void this.render() - } - }) - this.filter.onDidUpdate(text => { - this.filterText = text - }) - this.filter.onDidKeyPress(async character => { - let items = this.renderedItems - if (!items?.length) return - let curr = this.selection[0] - if (character == '' || character == this.keys.selectPrevious) { - let idx = items.findIndex(o => o.node == curr) - let index = idx == -1 || idx == 0 ? items.length - 1 : idx - 1 - let node = items[index]?.node - if (node) this.selectItem(node, true) - } - if (character == '' || character == this.keys.selectNext) { - let idx = items.findIndex(o => o.node == curr) - let index = idx == -1 || idx == items.length - 1 ? 0 : idx + 1 - let node = items[index]?.node - if (node) this.selectItem(node, true) - } - if (character == '' || character == this.keys.invoke) { - if (!curr) return - await this.invokeCommand(curr) - this.filter.deactivate(curr) - } - }) - } - } - - public get windowId(): number | undefined { - return this.winid - } - - private get startLnum(): number { - let filterCount = this.filterText == null ? 0 : 1 - return this.lineState.messageCount + this.lineState.titleCount + filterCount - } - - private get nvim(): Neovim { - return workspace.nvim - } - - private loadConfiguration(e?: ConfigurationChangeEvent): void { - if (!e || e.affectsConfiguration('tree')) { - let config = workspace.getConfiguration('tree') - this.config = { - openedIcon: config.get('openedIcon', ' '), - closedIcon: config.get('closedIcon', ' ') - } - this.keys = { - close: config.get('key.close'), - invoke: config.get('key.invoke'), - toggle: config.get('key.toggle'), - actions: config.get('key.actions'), - collapseAll: config.get('key.collapseAll'), - toggleSelection: config.get('key.toggleSelection'), - activeFilter: config.get('key.activeFilter'), - selectNext: config.get('key.selectNext'), - selectPrevious: config.get('key.selectPrevious') - } - if (e) { - void this.render() - } - } - } - - private async doFilter(text: string): Promise { - let items: ExtendedItem[] = [] - let index = 0 - let release = await this.mutex.acquire() - try { - if (!this.itemsToFilter) { - let itemsToFilter: T[] = [] - const addNodes = async (nodes: T[]): Promise => { - for (let n of nodes) { - itemsToFilter.push(n) - let arr = await Promise.resolve(this.provider.getChildren(n)) - if (arr?.length) await addNodes(arr) - } - } - let nodes = await Promise.resolve(this.provider.getChildren()) - await addNodes(nodes) - this.itemsToFilter = itemsToFilter - } - for (let n of this.itemsToFilter) { - let item = await this.getTreeItem(n) - let label = TreeItemLabel.is(item.label) ? item.label.label : item.label - if (!text || hasMatch(text, label)) { - let idxs = text ? positions(text, label) : [] - item.collapsibleState = TreeItemCollapsibleState.None - item.label = { label, highlights: text ? groupPositions(idxs) : [] } - let { line, highlights } = this.getRenderedLine(item, index, 0) - items.push({ - level: 0, - node: n, - line, - index, - score: text ? score(text, label) : 0, - highlights - }) - index += 1 - } - } - items.sort((a, b) => { - if (a.score != b.score) return b.score - a.score - return a.index - b.index - }) - let lnum = this.startLnum - let highlights: HighlightItem[] = [] - let renderedItems = this.renderedItems = items.map((o, idx) => { - highlights.push(...o.highlights.map(h => { - h.lnum = lnum + idx - return h - })) - delete o.index - delete o.score - delete o.highlights - return o - }) - this.updateUI(renderedItems.map(o => o.line), highlights, lnum, -1, true) - if (renderedItems.length) { - this.selectItem(renderedItems[0].node, true) - } else { - this.clearSelection() - } - this.redraw() - release() - } catch (e) { - release() - logger.error(`Error on tree filter: ${e.message}`, e) - } - } - - private async onHover(): Promise { - let { nvim } = this - let lnum = await nvim.call('line', ['.']) - let element = this.getElementByLnum(lnum - 1) - if (!element) return - let obj = this.nodesMap.get(element) - if (!obj) return - let item = obj.item - if (!obj.resolved) { - item = await this.resolveItem(element, item) - if (!item) return - } - if (!item.tooltip || !this.bufnr) return - let isMarkdown = MarkupContent.is(item.tooltip) && item.tooltip.kind == MarkupKind.Markdown - let doc: Documentation = { - filetype: isMarkdown ? 'markdown' : 'txt', - content: MarkupContent.is(item.tooltip) ? item.tooltip.value : item.tooltip - } - await this.tooltipFactory.show([doc], { modes: ['n'] }) - } - - private async onClick(element: T): Promise { - let { nvim } = this - let [line, col] = await nvim.eval(`[getline('.'),col('.')]`) as [string, number] - let pre = byteSlice(line, 0, col - 1) - let character = line[pre.length] - if (!character) return - let { openedIcon, closedIcon } = this.config - if (/^\s*$/.test(pre) && [openedIcon, closedIcon].includes(character)) { - await this.toggleExpand(element) - } else { - await this.invokeCommand(element) - } - } - - private async invokeCommand(element: T): Promise { - let obj = this.nodesMap.get(element) - if (!obj) return - this.selectItem(element) - let item = obj.item - if (!item.command) { - item = await this.resolveItem(element, item) - if (!item) return - } - if (!item.command) throw new Error(`Failed to resolve command from TreeItem.`) - await commandManager.execute(item.command) - } - - private async invokeActions(element: T): Promise { - this.selectItem(element) - if (typeof this.provider.resolveActions !== 'function') { - await window.showWarningMessage('No actions') - return - } - let obj = this.nodesMap.get(element) - let actions = await Promise.resolve(this.provider.resolveActions(obj.item, element)) - if (!actions || actions.length == 0) { - await window.showWarningMessage('No actions available') - return - } - let keys = actions.map(o => o.title) - let res = await window.showMenuPicker(keys, 'Choose action') - if (res == -1) return - await Promise.resolve(actions[res].handler(element)) - } - - private async onDataChange(node: T | undefined): Promise { - if (this.filter?.activated) { - this.itemsToFilter = undefined - await this.doFilter(this.filterText) - return - } - this.clearSelection() - if (!node) { - await this.render() - return - } - let release = await this.mutex.acquire() - try { - let items = this.renderedItems - let idx = items.findIndex(o => o.node === node) - if (idx != -1 && this.bufnr) { - let obj = items[idx] - let level = obj.level - let removeCount = 0 - for (let i = idx; i < items.length; i++) { - let o = items[i] - if (i == idx || o && o.level > level) { - removeCount += 1 - } - } - let appendItems: RenderedItem[] = [] - let highlights: HighlightItem[] = [] - let start = idx + this.startLnum - await this.appendTreeNode(node, level, start, appendItems, highlights) - items.splice(idx, removeCount, ...appendItems) - this.updateUI(appendItems.map(o => o.line), highlights, start, start + removeCount) - } - release() - } catch (e) { - let errMsg = `Error on tree refresh: ${e.message}` - logger.error(errMsg, e) - this.nvim.errWriteLine('[coc.nvim] ' + errMsg) - release() - } - } - - private async resolveItem(element: T, item: TreeItem): Promise { - if (typeof this.provider.resolveTreeItem === 'function') { - let tokenSource = this.resolveTokenSource = new CancellationTokenSource() - let token = tokenSource.token - item = await Promise.resolve(this.provider.resolveTreeItem(item, element, token)) - tokenSource.dispose() - this.resolveTokenSource = undefined - if (token.isCancellationRequested) return undefined - } - this.nodesMap.set(element, { item, resolved: true }) - return item - } - - public get visible(): boolean { - return this.winid != null - } - - public get selection(): T[] { - return this._selection.slice() - } - - public async checkLines(): Promise { - if (!this.bufnr) return - let buf = this.nvim.createBuffer(this.bufnr) - let curr = await buf.lines - let { titleCount, messageCount } = this.lineState - curr = curr.slice(titleCount + messageCount) - let lines = this.renderedItems.map(o => o.line) - return equals(curr, lines) - } - - /** - * Expand/collapse TreeItem. - */ - private async toggleExpand(element: T): Promise { - let o = this.nodesMap.get(element) - if (!o) return - let treeItem = o.item - let lnum = this.getItemLnum(element) - let nodeIdx = lnum - this.startLnum - let obj = this.renderedItems[nodeIdx] - if (!obj || treeItem.collapsibleState == TreeItemCollapsibleState.None) { - if (typeof this.provider.getParent === 'function') { - let node = await Promise.resolve(this.provider.getParent(element)) - if (node) { - await this.toggleExpand(node) - this.focusItem(node) - } - } - return - } - // remove lines - let removeCount = 0 - if (treeItem.collapsibleState == TreeItemCollapsibleState.Expanded) { - let level = obj.level - for (let i = nodeIdx + 1; i < this.renderedItems.length; i++) { - let o = this.renderedItems[i] - if (!o || o.level <= level) break - removeCount += 1 - } - treeItem.collapsibleState = TreeItemCollapsibleState.Collapsed - } else if (treeItem.collapsibleState == TreeItemCollapsibleState.Collapsed) { - treeItem.collapsibleState = TreeItemCollapsibleState.Expanded - } - let newItems: RenderedItem[] = [] - let newHighlights: HighlightItem[] = [] - await this.appendTreeNode(obj.node, obj.level, lnum, newItems, newHighlights) - this.renderedItems.splice(nodeIdx, removeCount + 1, ...newItems) - this.updateUI(newItems.map(o => o.line), newHighlights, lnum, lnum + removeCount + 1) - this.refreshSigns() - if (treeItem.collapsibleState == TreeItemCollapsibleState.Collapsed) { - this._onDidCollapseElement.fire({ element }) - } else { - this._onDidExpandElement.fire({ element }) - } - } - - private toggleSelection(element: T): void { - let idx = this._selection.findIndex(o => o === element) - if (idx !== -1) { - this.unselectItem(idx) - } else { - this.selectItem(element) - } - } - - private clearSelection(): void { - if (!this.bufnr) return - this._selection = [] - let buf = this.nvim.createBuffer(this.bufnr) - buf.unplaceSign({ group: 'CocTree' }) - this._onDidChangeSelection.fire({ selection: [] }) - } - - private selectItem(item: T, forceSingle?: boolean, noRedraw?: boolean): void { - let { nvim } = this - if (!this.bufnr || !workspace.env.sign) return - let row = this.getItemLnum(item) - if (row == null) return - let buf = nvim.createBuffer(this.bufnr) - let exists = this._selection.includes(item) - if (!this.canSelectMany || forceSingle) { - this._selection = [item] - } else if (!exists) { - this._selection.push(item) - } - nvim.pauseNotification() - if (!this.canSelectMany || forceSingle) { - buf.unplaceSign({ group: 'CocTree' }) - } - nvim.call('coc#compat#execute', [this.winid, `exe ${row + 1}`], true) - buf.placeSign({ id: signOffset + row, lnum: row + 1, name: 'CocTreeSelected', group: 'CocTree' }) - if (!noRedraw) this.redraw() - void nvim.resumeNotification(false, true) - if (!exists) this._onDidChangeSelection.fire({ selection: this._selection }) - } - - private unselectItem(idx: number): void { - let item = this._selection[idx] - let row = this.getItemLnum(item) - if (row == null || !this.bufnr || !workspace.env.sign) return - this._selection.splice(idx, 1) - let buf = this.nvim.createBuffer(this.bufnr) - buf.unplaceSign({ group: 'CocTree', id: signOffset + row }) - this._onDidChangeSelection.fire({ selection: this._selection }) - } - - public focusItem(element: T): void { - if (!this.winid) return - let lnum = this.getItemLnum(element) - if (lnum == null) return - this.nvim.call('coc#compat#execute', [this.winid, `exe ${lnum + 1}`], true) - } - - private getElementByLnum(lnum: number): T | undefined { - let item = this.renderedItems[lnum - this.startLnum] - return item ? item.node : undefined - } - - private getItemLnum(item: T): number | undefined { - let idx = this.renderedItems.findIndex(o => o.node === item) - if (idx == -1) return undefined - return this.startLnum + idx - } - - private async getTreeItem(element: T): Promise { - let exists: TreeItem - let resolved = false - let obj = this.nodesMap.get(element) - if (obj != null) { - exists = obj.item - resolved = obj.resolved - } - let item = await Promise.resolve(this.provider.getTreeItem(element)) - if (item.id && !exists) { - for (let obj of this.nodesMap.values()) { - if (obj.item.id === item.id) { - resolved = obj.resolved - exists = obj.item - break - } - } - } - if (exists - && exists.collapsibleState != TreeItemCollapsibleState.None - && item.collapsibleState != TreeItemCollapsibleState.None) { - item.collapsibleState = exists.collapsibleState - } - this.nodesMap.set(element, { item, resolved }) - return item - } - - private getRenderedLine(treeItem: TreeItem, lnum: number, level: number): { line: string, highlights: HighlightItem[] } { - let { openedIcon, closedIcon } = this.config - const highlights: HighlightItem[] = [] - const { label, deprecated, description } = treeItem - let prefix = ' '.repeat(level) - const addHighlight = (text: string, hlGroup: string) => { - let colStart = byteLength(prefix) - highlights.push({ - lnum, - hlGroup, - colStart, - colEnd: colStart + byteLength(text), - }) - } - switch (treeItem.collapsibleState) { - case TreeItemCollapsibleState.Expanded: { - addHighlight(openedIcon, 'CocTreeOpenClose') - prefix += openedIcon + ' ' - break - } - case TreeItemCollapsibleState.Collapsed: { - addHighlight(closedIcon, 'CocTreeOpenClose') - prefix += closedIcon + ' ' - break - } - default: - prefix += this.leafIndent ? ' ' : '' - } - if (treeItem.icon) { - let { text, hlGroup } = treeItem.icon - addHighlight(text, hlGroup) - prefix += text + ' ' - } - if (TreeItemLabel.is(label) && Array.isArray(label.highlights)) { - let colStart = byteLength(prefix) - for (let o of label.highlights) { - highlights.push({ - lnum, - hlGroup: 'Search', - colStart: colStart + o[0], - colEnd: colStart + o[1] - }) - } - } - let labelText = typeof label === 'string' ? label : label.label - if (deprecated) { - addHighlight(labelText, 'CocDeprecatedHighlight') - } - prefix += labelText - if (description && description.indexOf('\n') == -1) { - prefix += ' ' - addHighlight(description, 'CocTreeDescription') - prefix += description - } - return { line: prefix, highlights } - } - - private async appendTreeNode(element: T, level: number, lnum: number, items: RenderedItem[], highlights: HighlightItem[]): Promise { - let takes = 1 - let treeItem = await this.getTreeItem(element) - let res = this.getRenderedLine(treeItem, lnum, level) - highlights.push(...res.highlights) - items.push({ level, line: res.line, node: element }) - if (treeItem.collapsibleState == TreeItemCollapsibleState.Expanded) { - let l = level + 1 - let children = await Promise.resolve(this.provider.getChildren(element)) || [] - for (let el of children) { - let n = await this.appendTreeNode(el, l, lnum + takes, items, highlights) - takes = takes + n - } - } - return takes - } - - private updateUI(lines: string[], highlights: HighlightItem[], start = 0, end = -1, noRedraw = false): void { - if (!this.bufnr) return - let { nvim } = this - let buf = nvim.createBuffer(this.bufnr) - nvim.pauseNotification() - buf.setOption('modifiable', true, true) - void buf.setLines(lines, { start, end, strictIndexing: false }, true) - if (highlights.length) { - let highlightEnd = end == -1 ? -1 : start + lines.length - nvim.call('coc#highlight#update_highlights', [this.bufnr, highlightNamespace, highlights, start, highlightEnd], true) - } - buf.setOption('modifiable', false, true) - if (!noRedraw) this.redraw() - void nvim.resumeNotification(false, true) - } - - public async reveal(element: T, options: { select?: boolean; focus?: boolean; expand?: number | boolean } = {}): Promise { - if (this.filter?.activated) return - let isShown = this.getItemLnum(element) != null - let { select, focus, expand } = options - let curr = element - if (typeof this.provider.getParent !== 'function') { - throw new Error('missing getParent function from provider for reveal.') - } - if (!isShown) { - while (curr) { - let parentNode = await Promise.resolve(this.provider.getParent(curr)) - if (parentNode) { - let item = await this.getTreeItem(parentNode) - item.collapsibleState = TreeItemCollapsibleState.Expanded - curr = parentNode - } else { - break - } - } - } - if (expand) { - let item = await this.getTreeItem(element) - if (item.collapsibleState == TreeItemCollapsibleState.None) return - item.collapsibleState = TreeItemCollapsibleState.Expanded - if (typeof expand === 'number' && expand > 1) { - let curr = Math.min(expand, 2) - let nodes = await Promise.resolve(this.provider.getChildren(element)) - while (nodes?.length > 0) { - let arr: T[] = [] - for (let n of nodes) { - let item = await this.getTreeItem(n) - if (item.collapsibleState == TreeItemCollapsibleState.None) continue - item.collapsibleState = TreeItemCollapsibleState.Expanded - if (curr > 1) { - let res = await Promise.resolve(this.provider.getChildren(n)) - arr.push(...res) - } - } - nodes = arr - curr = curr - 1 - } - } - } - if (!isShown || expand) { - await this.render() - } - if (select !== false) this.selectItem(element) - if (focus) this.focusItem(element) - } - - private updateHeadLines(initialize = false): void { - let { titleCount, messageCount } = this.lineState - let end = initialize ? -1 : titleCount + messageCount - let lines: string[] = [] - let highlights: HighlightItem[] = [] - try { - if (this.message) { - highlights.push({ hlGroup: 'MoreMsg', colStart: 0, colEnd: byteLength(this.message), lnum: 0 }) - lines.push(this.message) - lines.push('') - } - if (this.title) { - highlights.push({ hlGroup: 'CocTreeTitle', colStart: 0, colEnd: byteLength(this.title), lnum: lines.length }) - if (this.description) { - let colStart = byteLength(this.title) + 1 - highlights.push({ hlGroup: 'Comment', colStart, colEnd: colStart + byteLength(this.description), lnum: lines.length }) - } - lines.push(this.title + (this.description ? ' ' + this.description : '')) - } - this.lineState.messageCount = this.message ? 2 : 0 - this.lineState.titleCount = this.title ? 1 : 0 - this.updateUI(lines, highlights, 0, end) - if (!initialize) { - this.refreshSigns() - } - } catch (e) { - this.nvim.errWriteLine('[coc.nvim] Error on update head lines:' + e.message) - logger.error('Error on update head lines:', e) - } - } - - /** - * Update signs after collapse/expand or head change - */ - private refreshSigns(): void { - let { selection, nvim, bufnr } = this - if (!selection.length || !bufnr || !workspace.env.sign) return - let buf = nvim.createBuffer(bufnr) - nvim.pauseNotification() - buf.unplaceSign({ group: 'CocTree' }) - for (let n of selection) { - let row = this.getItemLnum(n) - if (row == null) continue - buf.placeSign({ id: signOffset + row, lnum: row + 1, name: 'CocTreeSelected', group: 'CocTree' }) - } - void nvim.resumeNotification(false, true) - } - - // Render all tree items - private async render(): Promise { - if (!this.bufnr) return - let release = await this.mutex.acquire() - try { - let lines: string[] = [] - let highlights: HighlightItem[] = [] - let { startLnum } = this - let nodes = await Promise.resolve(this.provider.getChildren()) - let level = 0 - let lnum = startLnum - let renderedItems: RenderedItem[] = [] - if (!nodes?.length) { - this.message = 'No results' - } else { - for (let node of nodes) { - let n = await this.appendTreeNode(node, level, lnum, renderedItems, highlights) - lnum += n - } - } - lines.push(...renderedItems.map(o => o.line)) - this.renderedItems = renderedItems - let delta = this.startLnum - startLnum - if (delta) highlights.forEach(o => o.lnum = o.lnum + delta) - this.updateUI(lines, highlights, this.startLnum, -1) - this.retryTimers = 0 - release() - } catch (e) { - this.renderedItems = [] - this.nodesMap.clear() - this.lineState = { titleCount: 0, messageCount: 1 } - release() - let errMsg = `${e.message}`.replace(/\r?\n/g, ' ') - this.updateUI([errMsg], [{ hlGroup: 'WarningMsg', colStart: 0, colEnd: byteLength(errMsg), lnum: 0 }]) - if (this.retryTimers == 5) return - this.timer = setTimeout(() => { - this.retryTimers = this.retryTimers + 1 - void this.render() - }, 500) - } - } - - public async show(splitCommand = 'belowright 30vs'): Promise { - if (this.bufnr || this._creating) return - this._creating = true - let { nvim } = this - this.originalWin = await nvim.call('win_getid') - let winid = await nvim.call('coc#window#find', ['cocViewId', this.viewId]) - let id = globalId - globalId = globalId + 1 - nvim.pauseNotification() - if (winid != -1) { - nvim.call('win_gotoid', [winid], true) - nvim.command(`silent edit +setl\\ buftype=nofile CocTree${id}`, true) - } else { - nvim.command(`silent keepalt ${splitCommand} +setl\\ buftype=nofile CocTree${id}`, true) - } - nvim.command('setl bufhidden=wipe nolist nonumber norelativenumber foldcolumn=0', true) - nvim.command(`setl signcolumn=${this.canSelectMany ? 'yes' : 'no'}${this.winfixwidth ? ' winfixwidth' : ''}`, true) - nvim.command('setl nocursorline nobuflisted wrap undolevels=-1 filetype=coctree nomodifiable noswapfile', true) - nvim.command(`let w:cocViewId = "${this.viewId.replace(/"/g, '\\"')}"`, true) - nvim.call('bufnr', ['%'], true) - nvim.call('win_getid', [], true) - let res = await nvim.resumeNotification() - if (res[1]) throw new Error(`Error on buffer create:` + JSON.stringify(res[1])) - this._onDidChangeVisibility.fire({ visible: true }) - this.registerKeymaps() - let arr = res[0] - this.bufnr = arr[arr.length - 2] - this.winid = arr[arr.length - 1] - this._creating = false - this.updateHeadLines(true) - void this.render() - } - - private registerKeymaps(): void { - let { toggleSelection, actions, close, invoke, toggle, collapseAll, activeFilter } = this.keys - let { nvim } = this - const regist = (mode: 'n' | 'v' | 's' | 'x', key: string, fn: (element: T | undefined) => Promise, notify = false) => { - this.disposables.push(workspace.registerLocalKeymap(mode, key, async () => { - let lnum = await nvim.call('line', ['.']) - let element = this.getElementByLnum(lnum - 1) - if (element && !this.nodesMap.has(element)) return - await Promise.resolve(fn(element)) - }, notify)) - } - this.disposables.push(workspace.registerLocalKeymap('n', '', () => { - nvim.call('win_gotoid', [this.originalWin], true) - }, true)) - regist('n', '', async element => { - if (element) await this.onClick(element) - }) - this.filter && activeFilter && regist('n', activeFilter, async () => { - this.nvim.command(`exe ${this.startLnum}`, true) - this.filter.active() - this.filterText = '' - }, true) - toggleSelection && regist('n', toggleSelection, async element => { - if (element) this.toggleSelection(element) - }) - invoke && regist('n', invoke, async element => { - if (element) await this.invokeCommand(element) - }, true) - actions && regist('n', actions, async element => { - if (element) await this.invokeActions(element) - }, true) - toggle && regist('n', toggle, async element => { - if (element) await this.toggleExpand(element) - }, true) - collapseAll && regist('n', collapseAll, async () => { - for (let obj of this.nodesMap.values()) { - let item = obj.item - if (item.collapsibleState == TreeItemCollapsibleState.Expanded) { - item.collapsibleState = TreeItemCollapsibleState.Collapsed - } - } - await this.render() - }) - close && regist('n', close, async () => { - this.hide() - }, true) - } - - private hide(): void { - if (!this.bufnr) return - this.nvim.command(`bd! ${this.bufnr}`, true) - this.redraw() - this._onDidChangeVisibility.fire({ visible: false }) - this.bufnr = undefined - this.winid = undefined - } - - private redraw(): void { - if (workspace.isVim || this.filter?.activated) { - this.nvim.command('redraw', true) - } - } - - private cancelResolve(): void { - if (this.resolveTokenSource) { - this.resolveTokenSource.cancel() - this.resolveTokenSource = undefined - } - } - - public dispose(): void { - if (!this.provider) return - if (this.timer) { - clearTimeout(this.timer) - this.timer = undefined - } - this.filter?.dispose() - this._selection = [] - this.hide() - this.itemsToFilter = [] - this.cancelResolve() - this.tooltipFactory.dispose() - this.renderedItems = [] - this.nodesMap.clear() - this.provider = undefined - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/tree/filter.ts b/vim-config/plugins/coc.nvim/src/tree/filter.ts deleted file mode 100644 index 708501e4..00000000 --- a/vim-config/plugins/coc.nvim/src/tree/filter.ts +++ /dev/null @@ -1,95 +0,0 @@ -import events from '../events' -import { Neovim } from '@chemzqm/neovim' -import { Disposable, Emitter, Event } from 'vscode-languageserver-protocol' -import { disposeAll } from '../util' -export const sessionKey = 'filter' - -export default class Filter { - private _activated = false - private text: string - private history: string[] = [] - private disposables: Disposable[] = [] - private readonly _onDidUpdate = new Emitter() - private readonly _onDidExit = new Emitter() - private readonly _onDidKeyPress = new Emitter() - public readonly onDidKeyPress: Event = this._onDidKeyPress.event - public readonly onDidUpdate: Event = this._onDidUpdate.event - public readonly onDidExit: Event = this._onDidExit.event - constructor(private nvim: Neovim, keys: string[]) { - this.text = '' - events.on('InputChar', (session, character) => { - if (session !== sessionKey || !this._activated) return - if (!keys.includes(character)) { - if (character.length == 1) { - this.text = this.text + character - this._onDidUpdate.fire(this.text) - return - } - if (character == '') { - this.text = this.text.slice(0, -1) - this._onDidUpdate.fire(this.text) - return - } - if (character == '') { - this.text = '' - this._onDidUpdate.fire(this.text) - return - } - if (character == '') { - let idx = this.history.indexOf(this.text) - let text = this.history[idx + 1] || this.history[0] - if (text) { - this.text = text - this._onDidUpdate.fire(this.text) - } - return - } - if (character == '') { - let idx = this.history.indexOf(this.text) - let text = this.history[idx - 1] || this.history[this.history.length - 1] - if (text) { - this.text = text - this._onDidUpdate.fire(this.text) - } - } - if (character == '' || character == '') { - this.deactivate() - return - } - } - this._onDidKeyPress.fire(character) - }, null, this.disposables) - } - - public active(): void { - if (this._activated) return - this._activated = true - this.text = '' - this.nvim.call('coc#prompt#start_prompt', [sessionKey], true) - } - - public deactivate(node?: T): void { - if (!this._activated) return - this.nvim.call('coc#prompt#stop_prompt', [sessionKey], true) - this._activated = false - let { text } = this - this.text = '' - this._onDidExit.fire(node) - if (text && !this.history.includes(text)) { - this.history.push(text) - } - } - - public get activated(): boolean { - return this._activated - } - - public dispose(): void { - this.deactivate() - this.history = [] - this._onDidKeyPress.dispose() - this._onDidUpdate.dispose() - this._onDidExit.dispose() - disposeAll(this.disposables) - } -} diff --git a/vim-config/plugins/coc.nvim/src/tree/index.ts b/vim-config/plugins/coc.nvim/src/tree/index.ts deleted file mode 100644 index b1c70846..00000000 --- a/vim-config/plugins/coc.nvim/src/tree/index.ts +++ /dev/null @@ -1,221 +0,0 @@ -import { Disposable, Event, CancellationToken } from 'vscode-languageserver-protocol' -import { ProviderResult } from '../provider' -import { TreeItem, TreeItemIcon, TreeItemCollapsibleState } from './TreeItem' - -export { TreeItem, TreeItemIcon, TreeItemCollapsibleState } - -export interface TreeItemAction { - /** - * Label text in menu. - */ - title: string - handler: (item: T) => ProviderResult -} - -/** - * Options for creating a {@link TreeView} - */ -export interface TreeViewOptions { - /** - * Fixed width for window, default to true - */ - winfixwidth?: boolean - /** - * Enable filter feature, default to false - */ - enableFilter?: boolean - /** - * Disable indent of leaves without children, default to false - */ - disableLeafIndent?: boolean - /** - * A data provider that provides tree data. - */ - treeDataProvider: TreeDataProvider - /** - * Whether the tree supports multi-select. When the tree supports multi-select and a command is executed from the tree, - * the first argument to the command is the tree item that the command was executed on and the second argument is an - * array containing all selected tree items. - */ - canSelectMany?: boolean -} - -/** - * The event that is fired when an element in the {@link TreeView} is expanded or collapsed - */ -export interface TreeViewExpansionEvent { - /** - * Element that is expanded or collapsed. - */ - readonly element: T -} - -/** - * The event that is fired when there is a change in {@link TreeView.selection tree view's selection} - */ -export interface TreeViewSelectionChangeEvent { - readonly selection: T[] -} - -/** - * The event that is fired when there is a change in {@link TreeView.visible tree view's visibility} - */ -export interface TreeViewVisibilityChangeEvent { - readonly visible: boolean -} - -/** - * Represents a Tree view - */ -export interface TreeView extends Disposable { - - /** - * Event that is fired when an element is expanded - */ - readonly onDidExpandElement: Event> - - /** - * Event that is fired when an element is collapsed - */ - readonly onDidCollapseElement: Event> - - /** - * Currently selected elements. - */ - readonly selection: T[] - - /** - * Event that is fired when the {@link TreeView.selection selection} has changed - */ - readonly onDidChangeSelection: Event> - - /** - * `true` if the {@link TreeView tree view} is visible otherwise `false`. - * - * **NOTE:** is `true` when TreeView visible on other tab. - */ - readonly visible: boolean - - /** - * Window id used by TreeView. - */ - readonly windowId: number | undefined - - /** - * Event that is fired when {@link TreeView.visible visibility} has changed - */ - readonly onDidChangeVisibility: Event - - /** - * An optional human-readable message that will be rendered in the view. - * Setting the message to null, undefined, or empty string will remove the message from the view. - */ - message?: string - - /** - * The tree view title is initially taken from viewId of TreeView - * Changes to the title property will be properly reflected in the UI in the title of the view. - */ - title?: string - - /** - * An optional human-readable description which is rendered less prominently in the title of the view. - * Setting the title description to null, undefined, or empty string will remove the description from the view. - */ - description?: string - - /** - * Reveals the given element in the tree view. - * If the tree view is not visible then the tree view is shown and element is revealed. - * - * By default revealed element is selected. - * In order to not to select, set the option `select` to `false`. - * In order to focus, set the option `focus` to `true`. - * In order to expand the revealed element, set the option `expand` to `true`. To expand recursively set `expand` to the number of levels to expand. - * **NOTE:** You can expand only to 3 levels maximum. - * - * **NOTE:** The {@link TreeDataProvider} that the `TreeView` {@link window.createTreeView is registered with} with must implement {@link TreeDataProvider.getParent getParent} method to access this API. - */ - reveal(element: T, options?: { select?: boolean, focus?: boolean, expand?: boolean | number }): Thenable - - /** - * Create tree view in new window, does nothing when it's visible. - * - * **NOTE:** - * **NOTE:** TreeView with same viewId in current tab would be disposed. - * - * @param splitCommand The command to open TreeView window, default to 'belowright 30vs' - */ - show(splitCommand?: string): Promise -} - -/** - * A data provider that provides tree data - */ -export interface TreeDataProvider { - /** - * An optional event to signal that an element or root has changed. - * This will trigger the view to update the changed element/root and its children recursively (if shown). - * To signal that root has changed, do not pass any argument or pass `undefined` or `null`. - */ - onDidChangeTreeData?: Event - - /** - * Get {@link TreeItem} representation of the `element` - * - * @param element The element for which {@link TreeItem} representation is asked for. - * @return {@link TreeItem} representation of the element - */ - getTreeItem(element: T): TreeItem | Thenable - - /** - * Get the children of `element` or root if no element is passed. - * - * @param element The element from which the provider gets children. Can be `undefined`. - * @return Children of `element` or root if no element is passed. - */ - getChildren(element?: T): ProviderResult - - /** - * Optional method to return the parent of `element`. - * Return `null` or `undefined` if `element` is a child of root. - * - * **NOTE:** This method should be implemented in order to access {@link TreeView.reveal reveal} API. - * - * @param element The element for which the parent has to be returned. - * @return Parent of `element`. - */ - getParent?(element: T): ProviderResult - - /** - * Called on hover to resolve the {@link TreeItem.tooltip TreeItem} property if it is undefined. - * Called on tree item click/open to resolve the {@link TreeItem.command TreeItem} property if it is undefined. - * Only properties that were undefined can be resolved in `resolveTreeItem`. - * Functionality may be expanded later to include being called to resolve other missing - * properties on selection and/or on open. - * - * Will only ever be called once per TreeItem. - * - * onDidChangeTreeData should not be triggered from within resolveTreeItem. - * - * *Note* that this function is called when tree items are already showing in the UI. - * Because of that, no property that changes the presentation (label, description, etc.) - * can be changed. - * - * @param item Undefined properties of `item` should be set then `item` should be returned. - * @param element The object associated with the TreeItem. - * @param token A cancellation token. - * @return The resolved tree item or a thenable that resolves to such. It is OK to return the given - * `item`. When no result is returned, the given `item` will be used. - */ - resolveTreeItem?(item: TreeItem, element: T, token: CancellationToken): ProviderResult - - /** - * Called with current element to resolve actions. - * Called when user press 'actions' key. - * - * @param item Resolved item. - * @param element The object under cursor. - */ - resolveActions?(item: TreeItem, element: T): ProviderResult[]> -} diff --git a/vim-config/plugins/coc.nvim/src/types.ts b/vim-config/plugins/coc.nvim/src/types.ts deleted file mode 100644 index 2c1f217d..00000000 --- a/vim-config/plugins/coc.nvim/src/types.ts +++ /dev/null @@ -1,870 +0,0 @@ -// vim: set sw=2 ts=2 sts=2 et foldmarker={{,}} foldmethod=marker foldlevel=0 nofen: -import { Buffer, Neovim, Window } from '@chemzqm/neovim' -import { CancellationToken, CodeAction, CodeActionKind, CreateFile, CreateFileOptions, DeleteFile, DeleteFileOptions, Disposable, DocumentSelector, Event, FormattingOptions, Location, Position, Range, RenameFile, RenameFileOptions, SymbolKind, TextDocumentEdit, TextDocumentSaveReason, TextEdit, WorkspaceEdit, WorkspaceFolder } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { URI } from 'vscode-uri' -import Configurations from './configuration' -import Document from './model/document' -import FileSystemWatcher from './model/fileSystemWatcher' -import { ProviderResult, TextDocumentContentProvider } from './provider' - -export interface Thenable { - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Thenable - // eslint-disable-next-line @typescript-eslint/unified-signatures - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => void): Thenable -} - -export type ProviderName = 'rename' | 'onTypeEdit' | 'documentLink' | 'documentColor' - | 'foldingRange' | 'format' | 'codeAction' | 'workspaceSymbols' | 'formatRange' | 'formatOnType' - | 'hover' | 'signature' | 'documentSymbol' | 'documentHighlight' | 'definition' - | 'declaration' | 'typeDefinition' | 'reference' | 'implementation' - | 'codeLens' | 'selectionRange' | 'callHierarchy' | 'semanticTokens' | 'linkedEditing' - -export interface CurrentState { - doc: Document - winid: number - position: Position - // :h mode() - mode: string -} - -export interface HandlerDelegate { - checkProvier: (id: ProviderName, document: TextDocument) => void - withRequestToken: (name: string, fn: (token: CancellationToken) => Thenable, checkEmpty?: boolean) => Promise - getCurrentState: () => Promise - addDisposable: (disposable: Disposable) => void - getIcon(kind: SymbolKind): { text: string, hlGroup: string } - getCodeActions(doc: Document, range?: Range, only?: CodeActionKind[]): Promise - applyCodeAction(action: CodeAction): Promise -} - -export interface FloatConfig { - border?: boolean - highlight?: string - title?: string - borderhighlight?: string - close?: boolean - maxHeight?: number - maxWidth?: number - winblend?: number - focusable?: boolean - shadow?: boolean -} - -/** - * Represent a highlight that not cross lines - * all zero based. - */ -export interface HighlightItem { - lnum: number - hlGroup: string - /** - * 0 based start column. - */ - colStart: number - /** - * 0 based end column. - */ - colEnd: number -} - -export interface BufferSyncItem { - /** - * Called on buffer unload. - */ - dispose: () => void - /** - * Called on buffer change. - */ - onChange?(e: DidChangeTextDocumentParams): void -} - -export interface Env { - completeOpt: string - runtimepath: string - disabledSources: { [filetype: string]: string[] } - readonly guicursor: string - readonly mode: string - readonly apiversion: number - readonly floating: boolean - readonly sign: boolean - readonly extensionRoot: string - readonly globalExtensions: string[] - readonly workspaceFolders: string[] - readonly config: any - readonly pid: number - readonly columns: number - readonly lines: number - readonly pumevent: boolean - readonly cmdheight: number - readonly filetypeMap: { [index: string]: string } - readonly isVim: boolean - readonly isCygwin: boolean - readonly isMacvim: boolean - readonly isiTerm: boolean - readonly version: string - readonly locationlist: boolean - readonly progpath: string - readonly dialog: boolean - readonly textprop: boolean - readonly updateHighlight: boolean - readonly vimCommands: CommandConfig[] -} - -export interface CommandConfig { - id: string - cmd: string - title?: string -} - -export interface EditerState { - document: TextDocument - position: Position -} - -/** - * An output channel is a container for readonly textual information. - * - * To get an instance of an `OutputChannel` use - * [createOutputChannel](#window.createOutputChannel). - */ -export interface OutputChannel { - - /** - * The human-readable name of this output channel. - */ - readonly name: string - - readonly content: string - /** - * Append the given value to the channel. - * - * @param value A string, falsy values will not be printed. - */ - append(value: string): void - - /** - * Append the given value and a line feed character - * to the channel. - * - * @param value A string, falsy values will be printed. - */ - appendLine(value: string): void - - /** - * Removes output from the channel. Latest `keep` lines will be remained. - */ - clear(keep?: number): void - - /** - * Reveal this channel in the UI. - * - * @param preserveFocus When `true` the channel will not take focus. - */ - show(preserveFocus?: boolean): void - - /** - * Hide this channel from the UI. - */ - hide(): void - - /** - * Dispose and free associated resources. - */ - dispose(): void -} - -export interface IWorkspace { - readonly nvim: Neovim - readonly cwd: string - readonly root: string - readonly isVim: boolean - readonly isNvim: boolean - readonly filetypes: Set - readonly pluginRoot: string - readonly initialized: boolean - readonly completeOpt: string - readonly channelNames: string[] - readonly documents: Document[] - readonly configurations: Configurations - textDocuments: TextDocument[] - workspaceFolder: WorkspaceFolder - onDidOpenTextDocument: Event - onDidCloseTextDocument: Event - onDidChangeTextDocument: Event - onWillSaveTextDocument: Event - onDidSaveTextDocument: Event - onDidChangeConfiguration: Event - onDidWorkspaceInitialized: Event - findUp(filename: string | string[]): Promise - getDocument(uri: number | string): Document - getFormatOptions(uri?: string): Promise - getConfigFile(target: ConfigurationTarget): string - applyEdit(edit: WorkspaceEdit): Promise - createFileSystemWatcher(globPattern: string, ignoreCreate?: boolean, ignoreChange?: boolean, ignoreDelete?: boolean): FileSystemWatcher - getConfiguration(section?: string, _resource?: string): WorkspaceConfiguration - registerTextDocumentContentProvider(scheme: string, provider: TextDocumentContentProvider): Disposable - getQuickfixItem(loc: Location, text?: string, type?: string): Promise - getLine(uri: string, line: number): Promise - readFile(uri: string): Promise - getCurrentState(): Promise - jumpTo(uri: string, position: Position): Promise - createFile(filepath: string, opts?: CreateFileOptions): Promise - renameFile(oldPath: string, newPath: string, opts?: RenameFileOptions): Promise - deleteFile(filepath: string, opts?: DeleteFileOptions): Promise - openResource(uri: string): Promise - resolveModule(name: string): Promise - match(selector: DocumentSelector, document: TextDocument): number - runCommand(cmd: string, cwd?: string, timeout?: number): Promise - dispose(): void -} - -// vim {{ -export interface LocationListItem { - bufnr: number - lnum: number - end_lnum: number - col: number - end_col: number - text: string - type: string -} - -export interface QuickfixItem { - uri?: string - module?: string - range?: Range - text?: string - type?: string - filename?: string - bufnr?: number - lnum?: number - end_lnum?: number - col?: number - end_col?: number - valid?: boolean - nr?: number -} -// }} - -// Enums{{ -export enum PatternType { - Buffer, - LanguageServer, - Global, -} - -export enum SourceType { - Native, - Remote, - Service, -} - -export enum MessageLevel { - More, - Warning, - Error -} - -export enum ConfigurationTarget { - Global, - User, - Workspace -} - -export enum ServiceStat { - Initial, - Starting, - StartFailed, - Running, - Stopping, - Stopped, -} - -export enum FileType { - /** - * The file type is unknown. - */ - Unknown = 0, - /** - * A regular file. - */ - File = 1, - /** - * A directory. - */ - Directory = 2, - /** - * A symbolic link to a file. - */ - SymbolicLink = 64 -} -// }} - -// TextDocument {{ -/** - * An event that is fired when a [document](#TextDocument) will be saved. - * - * To make modifications to the document before it is being saved, call the - * [`waitUntil`](#TextDocumentWillSaveEvent.waitUntil)-function with a thenable - * that resolves to an array of [text edits](#TextEdit). - */ -export interface TextDocumentWillSaveEvent { - - /** - * The document that will be saved. - */ - document: TextDocument - - /** - * The reason why save was triggered. - */ - reason: TextDocumentSaveReason - - /** - * Allows to pause the event loop and to apply [pre-save-edits](#TextEdit). - * Edits of subsequent calls to this function will be applied in order. The - * edits will be *ignored* if concurrent modifications of the document happened. - * - * *Note:* This function can only be called during event dispatch and not - * in an asynchronous manner: - * - * @param thenable A thenable that resolves to [pre-save-edits](#TextEdit). - */ - waitUntil(thenable: Thenable): void -} - -export type DocumentChange = TextDocumentEdit | CreateFile | RenameFile | DeleteFile - -/** - * An event describing a change to a text document. - */ -export interface TextDocumentContentChange { - /** - * The range of the document that changed. - */ - range: Range - /** - * The new text for the provided range. - */ - text: string -} - -export interface DidChangeTextDocumentParams { - /** - * The document that did change. The version number points - * to the version after all provided content changes have - * been applied. - */ - textDocument: { - version: number - uri: string - } - /** - * The actual content changes. The content changes describe single state changes - * to the document. So if there are two content changes c1 (at array index 0) and - * c2 (at array index 1) for a document in state S then c1 moves the document from - * S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed - * on the state S'. - */ - contentChanges: TextDocumentContentChange[] - /** - * Buffer number of document. - */ - bufnr: number - /** - * Original content before change - */ - original: string - /** - * Changed lines - */ - originalLines: ReadonlyArray -} -// }} - -// Completion {{ -export interface Documentation { - filetype: string - content: string - active?: [number, number] -} - -export interface VimCompleteItem { - word: string - abbr?: string - menu?: string - info?: string - kind?: string - icase?: number - equal?: number - dup?: number - empty?: number - user_data?: string -} - -export interface ExtendedCompleteItem extends VimCompleteItem { - score?: number - sortText?: string - sourceScore?: number - filterText?: string - isSnippet?: boolean - source?: string - matchScore?: number - priority?: number - preselect?: boolean - signature?: string - localBonus?: number - index?: number - // used for preview - documentation?: Documentation[] - detailShown?: number - // saved line for apply TextEdit - line?: string -} - -export interface CompleteResult { - items: ExtendedCompleteItem[] - isIncomplete?: boolean - startcol?: number - source?: string - priority?: number -} - -// option on complete & should_complete -export interface CompleteOption { - readonly bufnr: number - readonly line: string - col: number - input: string - filetype: string - readonly filepath: string - readonly word: string - triggerCharacter: string - // cursor position - colnr: number - readonly linenr: number - readonly synname: string - readonly source?: string - readonly blacklist: string[] - readonly changedtick: number - triggerForInComplete?: boolean -} - -export interface SourceStat { - name: string - priority: number - triggerCharacters: string[] - type: string - shortcut: string - filepath: string - disabled: boolean - filetypes: string[] -} - -export type SourceConfig = Omit, 'shortcut' | 'priority' | 'triggerOnly' | 'triggerCharacters' | 'triggerPatterns' | 'enable' | 'filetypes' | 'disableSyntaxes'> - -export interface ISource { - name: string - enable?: boolean - shortcut?: string - priority?: number - sourceType?: SourceType - optionalFns?: string[] - triggerCharacters?: string[] - triggerOnly?: boolean - triggerPatterns?: RegExp[] - disableSyntaxes?: string[] - isSnippet?: boolean - filetypes?: string[] - documentSelector?: DocumentSelector - filepath?: string - firstMatch?: boolean - refresh?(): Promise - toggle?(): void - onEnter?(bufnr: number): void - shouldComplete?(opt: CompleteOption): Promise - doComplete(opt: CompleteOption, token: CancellationToken): ProviderResult - onCompleteResolve?(item: ExtendedCompleteItem, token: CancellationToken): ProviderResult | void - onCompleteDone?(item: ExtendedCompleteItem, opt: CompleteOption): ProviderResult - shouldCommit?(item: ExtendedCompleteItem, character: string): boolean -} -// }} - -// Configuration {{ -/** - * An event describing the change in Configuration - */ -export interface ConfigurationChangeEvent { - - /** - * Returns `true` if the given section for the given resource (if provided) is affected. - * - * @param section Configuration name, supports _dotted_ names. - * @param resource A resource URI. - * @return `true` if the given section for the given resource (if provided) is affected. - */ - affectsConfiguration(section: string, resource?: string): boolean -} - -export interface WorkspaceConfiguration { - /** - * Return a value from this configuration. - * - * @param section Configuration name, supports _dotted_ names. - * @return The value `section` denotes or `undefined`. - */ - get(section: string): T | undefined - - /** - * Return a value from this configuration. - * - * @param section Configuration name, supports _dotted_ names. - * @param defaultValue A value should be returned when no value could be found, is `undefined`. - * @return The value `section` denotes or the default. - */ - get(section: string, defaultValue: T): T - - /** - * Check if this configuration has a certain value. - * - * @param section Configuration name, supports _dotted_ names. - * @return `true` if the section doesn't resolve to `undefined`. - */ - has(section: string): boolean - - /** - * Retrieve all information about a configuration setting. A configuration value - * often consists of a *default* value, a global or installation-wide value, - * a workspace-specific value - * - * *Note:* The configuration name must denote a leaf in the configuration tree - * (`editor.fontSize` vs `editor`) otherwise no result is returned. - * - * @param section Configuration name, supports _dotted_ names. - * @return Information about a configuration setting or `undefined`. - */ - inspect(section: string): ConfigurationInspect | undefined - /** - * Update a configuration value. The updated configuration values are persisted. - * - * - * @param section Configuration name, supports _dotted_ names. - * @param value The new value. - * @param isUser if true, always update user configuration - */ - update(section: string, value: any, isUser?: boolean): void - - /** - * Readable dictionary that backs this configuration. - */ - readonly [key: string]: any -} - -export interface ErrorItem { - location: Location - message: string -} - -export interface ConfigurationInspect { - key: string - defaultValue?: T - globalValue?: T - workspaceValue?: T -} - -export interface ConfigurationShape { - workspaceConfigFile: string - $updateConfigurationOption(target: ConfigurationTarget, key: string, value: any): void - $removeConfigurationOption(target: ConfigurationTarget, key: string): void -} - -export interface IConfigurationModel { - contents: any -} - -export interface IConfigurationData { - defaults: IConfigurationModel - user: IConfigurationModel - workspace: IConfigurationModel -} -// }} - -// File operation {{ -/** - * An event that is fired when files are going to be renamed. - * - * To make modifications to the workspace before the files are renamed, - * call the [`waitUntil](#FileWillCreateEvent.waitUntil)-function with a - * thenable that resolves to a [workspace edit](#WorkspaceEdit). - */ -export interface FileWillRenameEvent { - - /** - * The files that are going to be renamed. - */ - readonly files: ReadonlyArray<{ oldUri: URI, newUri: URI }> - - /** - * Allows to pause the event and to apply a [workspace edit](#WorkspaceEdit). - * - * *Note:* This function can only be called during event dispatch and not - * in an asynchronous manner: - * - * ```ts - * workspace.onWillCreateFiles(event => { - * // async, will *throw* an error - * setTimeout(() => event.waitUntil(promise)); - * - * // sync, OK - * event.waitUntil(promise); - * }) - * ``` - * - * @param thenable A thenable that delays saving. - */ - waitUntil(thenable: Thenable): void -} - -/** - * An event that is fired after files are renamed. - */ -export interface FileRenameEvent { - - /** - * The files that got renamed. - */ - readonly files: ReadonlyArray<{ oldUri: URI, newUri: URI }> -} - -/** - * An event that is fired when files are going to be created. - * - * To make modifications to the workspace before the files are created, - * call the [`waitUntil](#FileWillCreateEvent.waitUntil)-function with a - * thenable that resolves to a [workspace edit](#WorkspaceEdit). - */ -export interface FileWillCreateEvent { - - /** - * The files that are going to be created. - */ - readonly files: ReadonlyArray - - /** - * Allows to pause the event and to apply a [workspace edit](#WorkspaceEdit). - * - * *Note:* This function can only be called during event dispatch and not - * in an asynchronous manner: - * - * ```ts - * workspace.onWillCreateFiles(event => { - * // async, will *throw* an error - * setTimeout(() => event.waitUntil(promise)); - * - * // sync, OK - * event.waitUntil(promise); - * }) - * ``` - * - * @param thenable A thenable that delays saving. - */ - waitUntil(thenable: Thenable): void -} - -/** - * An event that is fired after files are created. - */ -export interface FileCreateEvent { - - /** - * The files that got created. - */ - readonly files: ReadonlyArray -} - -/** - * An event that is fired when files are going to be deleted. - * - * To make modifications to the workspace before the files are deleted, - * call the [`waitUntil](#FileWillCreateEvent.waitUntil)-function with a - * thenable that resolves to a [workspace edit](#WorkspaceEdit). - */ -export interface FileWillDeleteEvent { - - /** - * The files that are going to be deleted. - */ - readonly files: ReadonlyArray - - /** - * Allows to pause the event and to apply a [workspace edit](#WorkspaceEdit). - * - * *Note:* This function can only be called during event dispatch and not - * in an asynchronous manner: - * - * ```ts - * workspace.onWillCreateFiles(event => { - * // async, will *throw* an error - * setTimeout(() => event.waitUntil(promise)); - * - * // sync, OK - * event.waitUntil(promise); - * }) - * ``` - * - * @param thenable A thenable that delays saving. - */ - waitUntil(thenable: Thenable): void -} - -/** - * An event that is fired after files are deleted. - */ -export interface FileDeleteEvent { - - /** - * The files that got deleted. - */ - readonly files: ReadonlyArray -} -// }} - -// List {{ -export interface LocationWithLine { - uri: string - line: string - text?: string -} - -export interface ListItem { - label: string - filterText?: string - /** - * A string that should be used when comparing this item - * with other items, only used for fuzzy filter. - */ - sortText?: string - location?: Location | LocationWithLine | string - data?: any - ansiHighlights?: AnsiHighlight[] - resolved?: boolean -} - -export interface ListHighlights { - // column indexes - spans: [number, number][] - hlGroup?: string -} - -export interface ListItemWithHighlights extends ListItem { - highlights?: ListHighlights -} - -export interface AnsiHighlight { - span: [number, number] - hlGroup: string -} - -export interface ListItemsEvent { - items: ListItem[] - finished: boolean - append?: boolean - reload?: boolean -} - -export type ListMode = 'normal' | 'insert' - -export type Matcher = 'strict' | 'fuzzy' | 'regex' - -export interface ListOptions { - position: string - input: string - ignorecase: boolean - interactive: boolean - sort: boolean - mode: ListMode - matcher: Matcher - autoPreview: boolean - numberSelect: boolean - noQuit: boolean - first: boolean -} - -export interface ListContext { - args: string[] - input: string - cwd: string - options: ListOptions - window: Window - buffer: Buffer - listWindow: Window -} - -export interface ListAction { - name: string - persist?: boolean - reload?: boolean - parallel?: boolean - multiple?: boolean - execute: (item: ListItem | ListItem[], context: ListContext) => ProviderResult -} - -export interface ListTask { - on(event: 'data', callback: (item: ListItem) => void): void - on(event: 'end', callback: () => void): void - on(event: 'error', callback: (msg: string | Error) => void): void - dispose(): void -} - -export interface ListArgument { - key?: string - hasValue?: boolean - name: string - description: string -} - -export interface IList { - /** - * Unique name of list. - */ - name: string - /** - * Action list. - */ - actions: ListAction[] - /** - * Default action name. - */ - defaultAction: string - /** - * Load list items. - */ - loadItems(context: ListContext, token: CancellationToken): Promise - /** - * Resolve list item. - */ - resolveItem?(item: ListItem): Promise - /** - * Should be true when interactive is supported. - */ - interactive?: boolean - /** - * Description of list. - */ - description?: string - /** - * Detail description, shown in help. - */ - detail?: string - /** - * Options supported by list. - */ - options?: ListArgument[] - /** - * Highlight buffer by vim's syntax commands. - */ - doHighlight?(): void - dispose?(): void -} -// }} diff --git a/vim-config/plugins/coc.nvim/src/util/ansiparse.ts b/vim-config/plugins/coc.nvim/src/util/ansiparse.ts deleted file mode 100644 index 61fb37dd..00000000 --- a/vim-config/plugins/coc.nvim/src/util/ansiparse.ts +++ /dev/null @@ -1,243 +0,0 @@ -import { byteLength, upperFirst } from './string' - -export interface AnsiItem { - foreground?: string - background?: string - bold?: boolean - italic?: boolean - underline?: boolean - text: string -} - -const foregroundColors = { - 30: 'black', - 31: 'red', - 32: 'green', - 33: 'yellow', - 34: 'blue', - 35: 'magenta', - 36: 'cyan', - 37: 'white', - 90: 'grey' -} - -const backgroundColors = { - 40: 'black', - 41: 'red', - 42: 'green', - 43: 'yellow', - 44: 'blue', - 45: 'magenta', - 46: 'cyan', - 47: 'white' -} - -const styles = { - 1: 'bold', - 3: 'italic', - 4: 'underline' -} - -export interface AnsiHighlight { - span: [number, number] - hlGroup: string -} - -export interface AnsiResult { - line: string - highlights: AnsiHighlight[] -} - -export function parseAnsiHighlights(line: string, markdown = false): AnsiResult { - let items = ansiparse(line) - let highlights: AnsiHighlight[] = [] - let newLabel = '' - for (let item of items) { - if (!item.text) continue - let { foreground, background, bold, italic, underline } = item - let len = byteLength(newLabel) - if (foreground || background || bold || italic || underline) { - let span: [number, number] = [len, len + byteLength(item.text)] - let hlGroup = '' - if (foreground && background) { - hlGroup = `CocList${upperFirst(foreground)}${upperFirst(background)}` - } else if (foreground) { - if (markdown) { - if (foreground == 'yellow') { - hlGroup = 'CocMarkdownCode' - } else if (foreground == 'blue') { - hlGroup = 'CocMarkdownLink' - } else if (foreground == 'magenta') { - hlGroup = 'CocMarkdownHeader' - } else { - hlGroup = `CocListFg${upperFirst(foreground)}` - } - } else { - hlGroup = `CocListFg${upperFirst(foreground)}` - } - } else if (background) { - hlGroup = `CocListBg${upperFirst(background)}` - } else if (bold) { - hlGroup = 'CocBold' - } else if (italic) { - hlGroup = 'CocItalic' - } else if (underline) { - hlGroup = 'CocUnderline' - } - highlights.push({ span, hlGroup }) - } - newLabel = newLabel + item.text - } - return { line: newLabel, highlights } -} - -export function ansiparse(str: string): AnsiItem[] { - // - // I'm terrible at writing parsers. - // - let matchingControl = null - let matchingData = null - let matchingText = '' - let ansiState = [] - let result = [] - let state: Partial = {} - let eraseChar - - // - // General workflow for this thing is: - // \033\[33mText - // | | | - // | | matchingText - // | matchingData - // matchingControl - // - // \033\[K or \033\[m - // - // In further steps we hope it's all going to be fine. It usually is. - // - - // - // Erases a char from the output - // - eraseChar = () => { - let index - let text - if (matchingText.length) { - matchingText = matchingText.substr(0, matchingText.length - 1) - } - else if (result.length) { - index = result.length - 1 - text = result[index].text - if (text.length === 1) { - // - // A result bit was fully deleted, pop it out to simplify the final output - // - result.pop() - } - else { - result[index].text = text.substr(0, text.length - 1) - } - } - } - - for (let i = 0; i < str.length; i++) { - if (matchingControl != null) { - if (matchingControl == '\x1b' && str[i] == '[') { - // - // We've matched full control code. Lets start matching formating data. - // - - // - // "emit" matched text with correct state - // - if (matchingText) { - state.text = matchingText - result.push(state) - state = {} - matchingText = '' - } - if (matchingText == '' && (str[i + 1] == 'm' || str[i + 1] == 'K')) { - if (state.foreground || state.background) { - state.text = '' - result.push(state) - } - state = {} - } - - matchingControl = null - matchingData = '' - } else { - // - // We failed to match anything - most likely a bad control code. We - // go back to matching regular strings. - // - matchingText += matchingControl + str[i] - matchingControl = null - } - continue - } else if (matchingData != null) { - if (str[i] == ';') { - // - // `;` separates many formatting codes, for example: `\033[33;43m` - // means that both `33` and `43` should be applied. - // - // TODO: this can be simplified by modifying state here. - // - ansiState.push(matchingData) - matchingData = '' - } else if (str[i] == 'm' || str[i] == 'K') { - // - // `m` finished whole formatting code. We can proceed to matching - // formatted text. - // - ansiState.push(matchingData) - matchingData = null - matchingText = '' - - // - // Convert matched formatting data into user-friendly state object. - // - // TODO: DRY. - // - ansiState.forEach(ansiCode => { - if (foregroundColors[ansiCode]) { - state.foreground = foregroundColors[ansiCode] - } else if (backgroundColors[ansiCode]) { - state.background = backgroundColors[ansiCode] - } else if (ansiCode == 39) { - delete state.foreground - } else if (ansiCode == 49) { - delete state.background - } else if (styles[ansiCode]) { - state[styles[ansiCode]] = true - } else if (ansiCode == 22) { - state.bold = false - } else if (ansiCode == 23) { - state.italic = false - } else if (ansiCode == 24) { - state.underline = false - } - }) - ansiState = [] - } - else { - matchingData += str[i] - } - continue - } - - if (str[i] == '\x1b') { - matchingControl = str[i] - } else if (str[i] == '\u0008') { - eraseChar() - } else { - matchingText += str[i] - } - } - - if (matchingText) { - state.text = matchingText + (matchingControl ? matchingControl : '') - result.push(state) - } - return result -} diff --git a/vim-config/plugins/coc.nvim/src/util/array.ts b/vim-config/plugins/coc.nvim/src/util/array.ts deleted file mode 100644 index d123c055..00000000 --- a/vim-config/plugins/coc.nvim/src/util/array.ts +++ /dev/null @@ -1,70 +0,0 @@ - -export function intersect(array: T[], other: T[]): boolean { - for (let item of other) { - if (array.includes(item)) { - return true - } - } - return false -} - -export function splitArray(array: T[], fn: (item: T) => boolean): [T[], T[]] { - let res: [T[], T[]] = [[], []] - for (let item of array) { - if (fn(item)) { - res[0].push(item) - } else { - res[1].push(item) - } - } - return res -} - -export function tail(array: T[], n = 0): T { - return array[array.length - (1 + n)] -} - -export function group(array: T[], size: number): T[][] { - let len = array.length - let res: T[][] = [] - for (let i = 0; i < Math.ceil(len / size); i++) { - res.push(array.slice(i * size, (i + 1) * size)) - } - return res -} - -/** - * Removes duplicates from the given array. The optional keyFn allows to specify - * how elements are checked for equalness by returning a unique string for each. - */ -export function distinct(array: T[], keyFn?: (t: T) => string): T[] { - if (!keyFn) { - return array.filter((element, position) => array.indexOf(element) === position) - } - - const seen: { [key: string]: boolean } = Object.create(null) - return array.filter(elem => { - const key = keyFn(elem) - if (seen[key]) { - return false - } - - seen[key] = true - - return true - }) -} - -export function lastIndex(array: T[], fn: (t: T) => boolean): number { - let i = array.length - 1 - while (i >= 0) { - if (fn(array[i])) { - break - } - i-- - } - return i -} - -export const flatMap = (xs: T[], f: (item: T) => U[]): U[] => - xs.reduce((x: U[], y: T) => [...x, ...f(y)], []) diff --git a/vim-config/plugins/coc.nvim/src/util/callSequence.ts b/vim-config/plugins/coc.nvim/src/util/callSequence.ts deleted file mode 100644 index 2b7a396f..00000000 --- a/vim-config/plugins/coc.nvim/src/util/callSequence.ts +++ /dev/null @@ -1,43 +0,0 @@ - -export default class CallSequence { - private funcs: Set = new Set() - private _canceled = false - private _resolved = false - private promise: Promise - - public addFunction(fn: Function): void { - this.funcs.add(fn) - } - - public start(): Promise { - this.promise = new Promise(async (resolve, reject) => { - for (let fn of this.funcs) { - if (this._canceled) return resolve(true) - try { - let cancel = await Promise.resolve(fn()) - if (cancel === true) { - this._canceled = true - return resolve(true) - } - } catch (e) { - reject(e) - return - } - } - this._resolved = true - resolve(false) - }) - return this.promise - } - - public ready(): Promise { - return this.promise - } - - public cancel(): Promise { - if (this._resolved) return Promise.resolve(void 0) - if (this._canceled) return this.promise - this._canceled = true - return this.promise - } -} diff --git a/vim-config/plugins/coc.nvim/src/util/charCode.ts b/vim-config/plugins/coc.nvim/src/util/charCode.ts deleted file mode 100644 index 34f5a1bb..00000000 --- a/vim-config/plugins/coc.nvim/src/util/charCode.ts +++ /dev/null @@ -1,424 +0,0 @@ -/* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -// Names from https://blog.codinghorror.com/ascii-pronunciation-rules-for-programmers/ - -/** - * An inlined enum containing useful character codes (to be used with String.charCodeAt). - * Please leave the const keyword such that it gets inlined when compiled to JavaScript! - */ -export const enum CharCode { - Null = 0, - /** - * The `\b` character. - */ - Backspace = 8, - /** - * The `\t` character. - */ - Tab = 9, - /** - * The `\n` character. - */ - LineFeed = 10, - /** - * The `\r` character. - */ - CarriageReturn = 13, - Space = 32, - /** - * The `!` character. - */ - ExclamationMark = 33, - /** - * The `"` character. - */ - DoubleQuote = 34, - /** - * The `#` character. - */ - Hash = 35, - /** - * The `$` character. - */ - DollarSign = 36, - /** - * The `%` character. - */ - PercentSign = 37, - /** - * The `&` character. - */ - Ampersand = 38, - /** - * The `'` character. - */ - SingleQuote = 39, - /** - * The `(` character. - */ - OpenParen = 40, - /** - * The `)` character. - */ - CloseParen = 41, - /** - * The `*` character. - */ - Asterisk = 42, - /** - * The `+` character. - */ - Plus = 43, - /** - * The `,` character. - */ - Comma = 44, - /** - * The `-` character. - */ - Dash = 45, - /** - * The `.` character. - */ - Period = 46, - /** - * The `/` character. - */ - Slash = 47, - - Digit0 = 48, - Digit1 = 49, - Digit2 = 50, - Digit3 = 51, - Digit4 = 52, - Digit5 = 53, - Digit6 = 54, - Digit7 = 55, - Digit8 = 56, - Digit9 = 57, - - /** - * The `:` character. - */ - Colon = 58, - /** - * The `;` character. - */ - Semicolon = 59, - /** - * The `<` character. - */ - LessThan = 60, - /** - * The `=` character. - */ - Equals = 61, - /** - * The `>` character. - */ - GreaterThan = 62, - /** - * The `?` character. - */ - QuestionMark = 63, - /** - * The `@` character. - */ - AtSign = 64, - - A = 65, - B = 66, - C = 67, - D = 68, - E = 69, - F = 70, - G = 71, - H = 72, - I = 73, - J = 74, - K = 75, - L = 76, - M = 77, - N = 78, - O = 79, - P = 80, - Q = 81, - R = 82, - S = 83, - T = 84, - U = 85, - V = 86, - W = 87, - X = 88, - Y = 89, - Z = 90, - - /** - * The `[` character. - */ - OpenSquareBracket = 91, - /** - * The `\` character. - */ - Backslash = 92, - /** - * The `]` character. - */ - CloseSquareBracket = 93, - /** - * The `^` character. - */ - Caret = 94, - /** - * The `_` character. - */ - Underline = 95, - /** - * The ``(`)`` character. - */ - BackTick = 96, - - a = 97, - b = 98, - c = 99, - d = 100, - e = 101, - f = 102, - g = 103, - h = 104, - i = 105, - j = 106, - k = 107, - l = 108, - m = 109, - n = 110, - o = 111, - p = 112, - q = 113, - r = 114, - s = 115, - t = 116, - u = 117, - v = 118, - w = 119, - x = 120, - y = 121, - z = 122, - - /** - * The `{` character. - */ - OpenCurlyBrace = 123, - /** - * The `|` character. - */ - Pipe = 124, - /** - * The `}` character. - */ - CloseCurlyBrace = 125, - /** - * The `~` character. - */ - Tilde = 126, - - U_Combining_Grave_Accent = 0x0300, // U+0300 Combining Grave Accent - U_Combining_Acute_Accent = 0x0301, // U+0301 Combining Acute Accent - U_Combining_Circumflex_Accent = 0x0302, // U+0302 Combining Circumflex Accent - U_Combining_Tilde = 0x0303, // U+0303 Combining Tilde - U_Combining_Macron = 0x0304, // U+0304 Combining Macron - U_Combining_Overline = 0x0305, // U+0305 Combining Overline - U_Combining_Breve = 0x0306, // U+0306 Combining Breve - U_Combining_Dot_Above = 0x0307, // U+0307 Combining Dot Above - U_Combining_Diaeresis = 0x0308, // U+0308 Combining Diaeresis - U_Combining_Hook_Above = 0x0309, // U+0309 Combining Hook Above - U_Combining_Ring_Above = 0x030A, // U+030A Combining Ring Above - U_Combining_Double_Acute_Accent = 0x030B, // U+030B Combining Double Acute Accent - U_Combining_Caron = 0x030C, // U+030C Combining Caron - U_Combining_Vertical_Line_Above = 0x030D, // U+030D Combining Vertical Line Above - U_Combining_Double_Vertical_Line_Above = 0x030E, // U+030E Combining Double Vertical Line Above - U_Combining_Double_Grave_Accent = 0x030F, // U+030F Combining Double Grave Accent - U_Combining_Candrabindu = 0x0310, // U+0310 Combining Candrabindu - U_Combining_Inverted_Breve = 0x0311, // U+0311 Combining Inverted Breve - U_Combining_Turned_Comma_Above = 0x0312, // U+0312 Combining Turned Comma Above - U_Combining_Comma_Above = 0x0313, // U+0313 Combining Comma Above - U_Combining_Reversed_Comma_Above = 0x0314, // U+0314 Combining Reversed Comma Above - U_Combining_Comma_Above_Right = 0x0315, // U+0315 Combining Comma Above Right - U_Combining_Grave_Accent_Below = 0x0316, // U+0316 Combining Grave Accent Below - U_Combining_Acute_Accent_Below = 0x0317, // U+0317 Combining Acute Accent Below - U_Combining_Left_Tack_Below = 0x0318, // U+0318 Combining Left Tack Below - U_Combining_Right_Tack_Below = 0x0319, // U+0319 Combining Right Tack Below - U_Combining_Left_Angle_Above = 0x031A, // U+031A Combining Left Angle Above - U_Combining_Horn = 0x031B, // U+031B Combining Horn - U_Combining_Left_Half_Ring_Below = 0x031C, // U+031C Combining Left Half Ring Below - U_Combining_Up_Tack_Below = 0x031D, // U+031D Combining Up Tack Below - U_Combining_Down_Tack_Below = 0x031E, // U+031E Combining Down Tack Below - U_Combining_Plus_Sign_Below = 0x031F, // U+031F Combining Plus Sign Below - U_Combining_Minus_Sign_Below = 0x0320, // U+0320 Combining Minus Sign Below - U_Combining_Palatalized_Hook_Below = 0x0321, // U+0321 Combining Palatalized Hook Below - U_Combining_Retroflex_Hook_Below = 0x0322, // U+0322 Combining Retroflex Hook Below - U_Combining_Dot_Below = 0x0323, // U+0323 Combining Dot Below - U_Combining_Diaeresis_Below = 0x0324, // U+0324 Combining Diaeresis Below - U_Combining_Ring_Below = 0x0325, // U+0325 Combining Ring Below - U_Combining_Comma_Below = 0x0326, // U+0326 Combining Comma Below - U_Combining_Cedilla = 0x0327, // U+0327 Combining Cedilla - U_Combining_Ogonek = 0x0328, // U+0328 Combining Ogonek - U_Combining_Vertical_Line_Below = 0x0329, // U+0329 Combining Vertical Line Below - U_Combining_Bridge_Below = 0x032A, // U+032A Combining Bridge Below - U_Combining_Inverted_Double_Arch_Below = 0x032B, // U+032B Combining Inverted Double Arch Below - U_Combining_Caron_Below = 0x032C, // U+032C Combining Caron Below - U_Combining_Circumflex_Accent_Below = 0x032D, // U+032D Combining Circumflex Accent Below - U_Combining_Breve_Below = 0x032E, // U+032E Combining Breve Below - U_Combining_Inverted_Breve_Below = 0x032F, // U+032F Combining Inverted Breve Below - U_Combining_Tilde_Below = 0x0330, // U+0330 Combining Tilde Below - U_Combining_Macron_Below = 0x0331, // U+0331 Combining Macron Below - U_Combining_Low_Line = 0x0332, // U+0332 Combining Low Line - U_Combining_Double_Low_Line = 0x0333, // U+0333 Combining Double Low Line - U_Combining_Tilde_Overlay = 0x0334, // U+0334 Combining Tilde Overlay - U_Combining_Short_Stroke_Overlay = 0x0335, // U+0335 Combining Short Stroke Overlay - U_Combining_Long_Stroke_Overlay = 0x0336, // U+0336 Combining Long Stroke Overlay - U_Combining_Short_Solidus_Overlay = 0x0337, // U+0337 Combining Short Solidus Overlay - U_Combining_Long_Solidus_Overlay = 0x0338, // U+0338 Combining Long Solidus Overlay - U_Combining_Right_Half_Ring_Below = 0x0339, // U+0339 Combining Right Half Ring Below - U_Combining_Inverted_Bridge_Below = 0x033A, // U+033A Combining Inverted Bridge Below - U_Combining_Square_Below = 0x033B, // U+033B Combining Square Below - U_Combining_Seagull_Below = 0x033C, // U+033C Combining Seagull Below - U_Combining_X_Above = 0x033D, // U+033D Combining X Above - U_Combining_Vertical_Tilde = 0x033E, // U+033E Combining Vertical Tilde - U_Combining_Double_Overline = 0x033F, // U+033F Combining Double Overline - U_Combining_Grave_Tone_Mark = 0x0340, // U+0340 Combining Grave Tone Mark - U_Combining_Acute_Tone_Mark = 0x0341, // U+0341 Combining Acute Tone Mark - U_Combining_Greek_Perispomeni = 0x0342, // U+0342 Combining Greek Perispomeni - U_Combining_Greek_Koronis = 0x0343, // U+0343 Combining Greek Koronis - U_Combining_Greek_Dialytika_Tonos = 0x0344, // U+0344 Combining Greek Dialytika Tonos - U_Combining_Greek_Ypogegrammeni = 0x0345, // U+0345 Combining Greek Ypogegrammeni - U_Combining_Bridge_Above = 0x0346, // U+0346 Combining Bridge Above - U_Combining_Equals_Sign_Below = 0x0347, // U+0347 Combining Equals Sign Below - U_Combining_Double_Vertical_Line_Below = 0x0348, // U+0348 Combining Double Vertical Line Below - U_Combining_Left_Angle_Below = 0x0349, // U+0349 Combining Left Angle Below - U_Combining_Not_Tilde_Above = 0x034A, // U+034A Combining Not Tilde Above - U_Combining_Homothetic_Above = 0x034B, // U+034B Combining Homothetic Above - U_Combining_Almost_Equal_To_Above = 0x034C, // U+034C Combining Almost Equal To Above - U_Combining_Left_Right_Arrow_Below = 0x034D, // U+034D Combining Left Right Arrow Below - U_Combining_Upwards_Arrow_Below = 0x034E, // U+034E Combining Upwards Arrow Below - U_Combining_Grapheme_Joiner = 0x034F, // U+034F Combining Grapheme Joiner - U_Combining_Right_Arrowhead_Above = 0x0350, // U+0350 Combining Right Arrowhead Above - U_Combining_Left_Half_Ring_Above = 0x0351, // U+0351 Combining Left Half Ring Above - U_Combining_Fermata = 0x0352, // U+0352 Combining Fermata - U_Combining_X_Below = 0x0353, // U+0353 Combining X Below - U_Combining_Left_Arrowhead_Below = 0x0354, // U+0354 Combining Left Arrowhead Below - U_Combining_Right_Arrowhead_Below = 0x0355, // U+0355 Combining Right Arrowhead Below - U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356, // U+0356 Combining Right Arrowhead And Up Arrowhead Below - U_Combining_Right_Half_Ring_Above = 0x0357, // U+0357 Combining Right Half Ring Above - U_Combining_Dot_Above_Right = 0x0358, // U+0358 Combining Dot Above Right - U_Combining_Asterisk_Below = 0x0359, // U+0359 Combining Asterisk Below - U_Combining_Double_Ring_Below = 0x035A, // U+035A Combining Double Ring Below - U_Combining_Zigzag_Above = 0x035B, // U+035B Combining Zigzag Above - U_Combining_Double_Breve_Below = 0x035C, // U+035C Combining Double Breve Below - U_Combining_Double_Breve = 0x035D, // U+035D Combining Double Breve - U_Combining_Double_Macron = 0x035E, // U+035E Combining Double Macron - U_Combining_Double_Macron_Below = 0x035F, // U+035F Combining Double Macron Below - U_Combining_Double_Tilde = 0x0360, // U+0360 Combining Double Tilde - U_Combining_Double_Inverted_Breve = 0x0361, // U+0361 Combining Double Inverted Breve - U_Combining_Double_Rightwards_Arrow_Below = 0x0362, // U+0362 Combining Double Rightwards Arrow Below - U_Combining_Latin_Small_Letter_A = 0x0363, // U+0363 Combining Latin Small Letter A - U_Combining_Latin_Small_Letter_E = 0x0364, // U+0364 Combining Latin Small Letter E - U_Combining_Latin_Small_Letter_I = 0x0365, // U+0365 Combining Latin Small Letter I - U_Combining_Latin_Small_Letter_O = 0x0366, // U+0366 Combining Latin Small Letter O - U_Combining_Latin_Small_Letter_U = 0x0367, // U+0367 Combining Latin Small Letter U - U_Combining_Latin_Small_Letter_C = 0x0368, // U+0368 Combining Latin Small Letter C - U_Combining_Latin_Small_Letter_D = 0x0369, // U+0369 Combining Latin Small Letter D - U_Combining_Latin_Small_Letter_H = 0x036A, // U+036A Combining Latin Small Letter H - U_Combining_Latin_Small_Letter_M = 0x036B, // U+036B Combining Latin Small Letter M - U_Combining_Latin_Small_Letter_R = 0x036C, // U+036C Combining Latin Small Letter R - U_Combining_Latin_Small_Letter_T = 0x036D, // U+036D Combining Latin Small Letter T - U_Combining_Latin_Small_Letter_V = 0x036E, // U+036E Combining Latin Small Letter V - U_Combining_Latin_Small_Letter_X = 0x036F, // U+036F Combining Latin Small Letter X - - /** - * Unicode Character 'LINE SEPARATOR' (U+2028) - * http://www.fileformat.info/info/unicode/char/2028/index.htm - */ - LINE_SEPARATOR_2028 = 8232, - - // http://www.fileformat.info/info/unicode/category/Sk/list.htm - U_CIRCUMFLEX = 0x005E, // U+005E CIRCUMFLEX - U_GRAVE_ACCENT = 0x0060, // U+0060 GRAVE ACCENT - U_DIAERESIS = 0x00A8, // U+00A8 DIAERESIS - U_MACRON = 0x00AF, // U+00AF MACRON - U_ACUTE_ACCENT = 0x00B4, // U+00B4 ACUTE ACCENT - U_CEDILLA = 0x00B8, // U+00B8 CEDILLA - U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02C2, // U+02C2 MODIFIER LETTER LEFT ARROWHEAD - U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02C3, // U+02C3 MODIFIER LETTER RIGHT ARROWHEAD - U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02C4, // U+02C4 MODIFIER LETTER UP ARROWHEAD - U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02C5, // U+02C5 MODIFIER LETTER DOWN ARROWHEAD - U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02D2, // U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING - U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02D3, // U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING - U_MODIFIER_LETTER_UP_TACK = 0x02D4, // U+02D4 MODIFIER LETTER UP TACK - U_MODIFIER_LETTER_DOWN_TACK = 0x02D5, // U+02D5 MODIFIER LETTER DOWN TACK - U_MODIFIER_LETTER_PLUS_SIGN = 0x02D6, // U+02D6 MODIFIER LETTER PLUS SIGN - U_MODIFIER_LETTER_MINUS_SIGN = 0x02D7, // U+02D7 MODIFIER LETTER MINUS SIGN - U_BREVE = 0x02D8, // U+02D8 BREVE - U_DOT_ABOVE = 0x02D9, // U+02D9 DOT ABOVE - U_RING_ABOVE = 0x02DA, // U+02DA RING ABOVE - U_OGONEK = 0x02DB, // U+02DB OGONEK - U_SMALL_TILDE = 0x02DC, // U+02DC SMALL TILDE - U_DOUBLE_ACUTE_ACCENT = 0x02DD, // U+02DD DOUBLE ACUTE ACCENT - U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02DE, // U+02DE MODIFIER LETTER RHOTIC HOOK - U_MODIFIER_LETTER_CROSS_ACCENT = 0x02DF, // U+02DF MODIFIER LETTER CROSS ACCENT - U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02E5, // U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR - U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02E6, // U+02E6 MODIFIER LETTER HIGH TONE BAR - U_MODIFIER_LETTER_MID_TONE_BAR = 0x02E7, // U+02E7 MODIFIER LETTER MID TONE BAR - U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02E8, // U+02E8 MODIFIER LETTER LOW TONE BAR - U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02E9, // U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR - U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02EA, // U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK - U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02EB, // U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK - U_MODIFIER_LETTER_UNASPIRATED = 0x02ED, // U+02ED MODIFIER LETTER UNASPIRATED - U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02EF, // U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD - U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02F0, // U+02F0 MODIFIER LETTER LOW UP ARROWHEAD - U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02F1, // U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD - U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02F2, // U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD - U_MODIFIER_LETTER_LOW_RING = 0x02F3, // U+02F3 MODIFIER LETTER LOW RING - U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02F4, // U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT - U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 0x02F5, // U+02F5 MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT - U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 0x02F6, // U+02F6 MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT - U_MODIFIER_LETTER_LOW_TILDE = 0x02F7, // U+02F7 MODIFIER LETTER LOW TILDE - U_MODIFIER_LETTER_RAISED_COLON = 0x02F8, // U+02F8 MODIFIER LETTER RAISED COLON - U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02F9, // U+02F9 MODIFIER LETTER BEGIN HIGH TONE - U_MODIFIER_LETTER_END_HIGH_TONE = 0x02FA, // U+02FA MODIFIER LETTER END HIGH TONE - U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02FB, // U+02FB MODIFIER LETTER BEGIN LOW TONE - U_MODIFIER_LETTER_END_LOW_TONE = 0x02FC, // U+02FC MODIFIER LETTER END LOW TONE - U_MODIFIER_LETTER_SHELF = 0x02FD, // U+02FD MODIFIER LETTER SHELF - U_MODIFIER_LETTER_OPEN_SHELF = 0x02FE, // U+02FE MODIFIER LETTER OPEN SHELF - U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02FF, // U+02FF MODIFIER LETTER LOW LEFT ARROW - U_GREEK_LOWER_NUMERAL_SIGN = 0x0375, // U+0375 GREEK LOWER NUMERAL SIGN - U_GREEK_TONOS = 0x0384, // U+0384 GREEK TONOS - U_GREEK_DIALYTIKA_TONOS = 0x0385, // U+0385 GREEK DIALYTIKA TONOS - U_GREEK_KORONIS = 0x1FBD, // U+1FBD GREEK KORONIS - U_GREEK_PSILI = 0x1FBF, // U+1FBF GREEK PSILI - U_GREEK_PERISPOMENI = 0x1FC0, // U+1FC0 GREEK PERISPOMENI - U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1FC1, // U+1FC1 GREEK DIALYTIKA AND PERISPOMENI - U_GREEK_PSILI_AND_VARIA = 0x1FCD, // U+1FCD GREEK PSILI AND VARIA - U_GREEK_PSILI_AND_OXIA = 0x1FCE, // U+1FCE GREEK PSILI AND OXIA - U_GREEK_PSILI_AND_PERISPOMENI = 0x1FCF, // U+1FCF GREEK PSILI AND PERISPOMENI - U_GREEK_DASIA_AND_VARIA = 0x1FDD, // U+1FDD GREEK DASIA AND VARIA - U_GREEK_DASIA_AND_OXIA = 0x1FDE, // U+1FDE GREEK DASIA AND OXIA - U_GREEK_DASIA_AND_PERISPOMENI = 0x1FDF, // U+1FDF GREEK DASIA AND PERISPOMENI - U_GREEK_DIALYTIKA_AND_VARIA = 0x1FED, // U+1FED GREEK DIALYTIKA AND VARIA - U_GREEK_DIALYTIKA_AND_OXIA = 0x1FEE, // U+1FEE GREEK DIALYTIKA AND OXIA - U_GREEK_VARIA = 0x1FEF, // U+1FEF GREEK VARIA - U_GREEK_OXIA = 0x1FFD, // U+1FFD GREEK OXIA - U_GREEK_DASIA = 0x1FFE, // U+1FFE GREEK DASIA - - U_OVERLINE = 0x203E, // Unicode Character 'OVERLINE' - - /** - * UTF-8 BOM - * Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF) - * http://www.fileformat.info/info/unicode/char/feff/index.htm - */ - UTF8_BOM = 65279 -} diff --git a/vim-config/plugins/coc.nvim/src/util/color.ts b/vim-config/plugins/coc.nvim/src/util/color.ts deleted file mode 100644 index 00a92551..00000000 --- a/vim-config/plugins/coc.nvim/src/util/color.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { Color } from 'vscode-languageserver-protocol' - -function pad(str: string): string { - return str.length == 1 ? `0${str}` : str -} - -export function toHexString(color: Color): string { - let c = toHexColor(color) - return `${pad(c.red.toString(16))}${pad(c.green.toString(16))}${pad(c.blue.toString(16))}` -} - -export function toHexColor(color: Color): { red: number; green: number; blue: number } { - let { red, green, blue } = color - return { - red: Math.round(red * 255), - green: Math.round(green * 255), - blue: Math.round(blue * 255) - } -} - -export function isDark(color: Color): boolean { - // http://www.w3.org/TR/WCAG20/#relativeluminancedef - let rgb = [color.red, color.green, color.blue] - let lum = [] - for (let i = 0; i < rgb.length; i++) { - let chan = rgb[i] - lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4) - } - let luma = 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2] - return luma <= 0.5 -} - diff --git a/vim-config/plugins/coc.nvim/src/util/convert.ts b/vim-config/plugins/coc.nvim/src/util/convert.ts deleted file mode 100644 index 48c7c2b2..00000000 --- a/vim-config/plugins/coc.nvim/src/util/convert.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { SymbolKind } from 'vscode-languageserver-protocol' - -export function getSymbolKind(kind: SymbolKind): string { - switch (kind) { - case SymbolKind.File: - return 'File' - case SymbolKind.Module: - return 'Module' - case SymbolKind.Namespace: - return 'Namespace' - case SymbolKind.Package: - return 'Package' - case SymbolKind.Class: - return 'Class' - case SymbolKind.Method: - return 'Method' - case SymbolKind.Property: - return 'Property' - case SymbolKind.Field: - return 'Field' - case SymbolKind.Constructor: - return 'Constructor' - case SymbolKind.Enum: - return 'Enum' - case SymbolKind.Interface: - return 'Interface' - case SymbolKind.Function: - return 'Function' - case SymbolKind.Variable: - return 'Variable' - case SymbolKind.Constant: - return 'Constant' - case SymbolKind.String: - return 'String' - case SymbolKind.Number: - return 'Number' - case SymbolKind.Boolean: - return 'Boolean' - case SymbolKind.Array: - return 'Array' - case SymbolKind.Object: - return 'Object' - case SymbolKind.Key: - return 'Key' - case SymbolKind.Null: - return 'Null' - case SymbolKind.EnumMember: - return 'EnumMember' - case SymbolKind.Struct: - return 'Struct' - case SymbolKind.Event: - return 'Event' - case SymbolKind.Operator: - return 'Operator' - case SymbolKind.TypeParameter: - return 'TypeParameter' - default: - return 'Unknown' - } -} diff --git a/vim-config/plugins/coc.nvim/src/util/decorator.ts b/vim-config/plugins/coc.nvim/src/util/decorator.ts deleted file mode 100644 index d1bbde6b..00000000 --- a/vim-config/plugins/coc.nvim/src/util/decorator.ts +++ /dev/null @@ -1,19 +0,0 @@ -const logger = require('./logger')('util-decorator') - -export function memorize Promise>(_target: any, key: string, descriptor: any): void { - let fn = descriptor.value - if (typeof fn !== 'function') return - let memoKey = '$' + key - - descriptor.value = function(...args): Promise { - if (this.hasOwnProperty(memoKey)) return Promise.resolve(this[memoKey]) - return new Promise((resolve, reject): void => { - Promise.resolve(fn.apply(this, args)).then(res => { - this[memoKey] = res - resolve(res) - }, e => { - reject(e) - }) - }) - } -} diff --git a/vim-config/plugins/coc.nvim/src/util/diff.ts b/vim-config/plugins/coc.nvim/src/util/diff.ts deleted file mode 100644 index 83b42d71..00000000 --- a/vim-config/plugins/coc.nvim/src/util/diff.ts +++ /dev/null @@ -1,140 +0,0 @@ -import fastDiff from 'fast-diff' -import { byteLength } from './string' -const logger = require('./logger')('util-diff') - -export interface ChangedLines { - start: number - end: number - replacement: string[] -} - -interface Change { - start: number - end: number - newText: string -} - -export function diffLines(oldLines: ReadonlyArray, newLines: ReadonlyArray, startLine: number): ChangedLines { - let endOffset = 0 - let startOffset = 0 - let parts = oldLines.slice(startLine + 1) - for (let i = 0; i < Math.min(parts.length, newLines.length); i++) { - if (parts[parts.length - 1 - i] == newLines[newLines.length - 1 - i]) { - endOffset = endOffset + 1 - } else { - break - } - } - for (let i = 0; i <= Math.min(startLine, newLines.length - 1 - endOffset); i++) { - if (oldLines[i] == newLines[i]) { - startOffset = startOffset + 1 - } else { - break - } - } - let replacement = newLines.slice(startOffset, newLines.length - endOffset) - let end = oldLines.length - endOffset - if (end > startOffset && replacement.length) { - let offset = 0 - for (let i = 0; i < Math.min(replacement.length, end - startOffset); i++) { - if (replacement[i] == oldLines[startOffset + i]) { - offset = offset + 1 - } else { - break - } - } - if (offset) { - return { - start: startOffset + offset, - end, - replacement: replacement.slice(offset) - } - } - } - return { - start: startOffset, - end, - replacement - } -} - -export function getChange(oldStr: string, newStr: string, cursorEnd?: number): Change { - let ol = oldStr.length - let nl = newStr.length - let max = Math.min(ol, nl) - let newText = '' - let startOffset = 0 - let endOffset = -1 - let shouldLimit = false - // find first endOffset, could <= this. one - for (let i = 0; i <= max; i++) { - if (cursorEnd != null && i == cursorEnd) { - endOffset = i - shouldLimit = true - break - } - if (oldStr[ol - i - 1] != newStr[nl - i - 1]) { - endOffset = i - break - } - } - if (endOffset == -1) return null - // find start offset - let remain = max - endOffset - if (remain == 0) { - startOffset = 0 - } else { - for (let i = 0; i <= remain; i++) { - if (oldStr[i] != newStr[i] || i == remain) { - startOffset = i - break - } - } - } - // limit to minimal change - remain = remain - startOffset - if (shouldLimit && remain > 0) { - let end = endOffset - for (let i = 0; i < remain; i++) { - let oc = oldStr[ol - end - 1 - i] - let nc = newStr[nl - end - 1 - i] - if (oc == nc) { - endOffset = endOffset + 1 - } else { - break - } - } - } - let end = ol - endOffset - if (ol == nl && startOffset == end) return null - newText = newStr.slice(startOffset, nl - endOffset) - // optimize for add new line(s) - if (startOffset == end) { - let pre = startOffset == 0 ? '' : newStr[startOffset - 1] - if (pre && pre != '\n' - && oldStr[startOffset] == '\n' - && newText.startsWith('\n')) { - return { start: startOffset + 1, end: end + 1, newText: newText.slice(1) + '\n' } - } - } - return { start: startOffset, end, newText } -} - -export function patchLine(from: string, to: string, fill = ' '): string { - if (from == to) return to - let idx = to.indexOf(from) - if (idx !== -1) return fill.repeat(idx) + from - let result = fastDiff(from, to) - let str = '' - for (let item of result) { - if (item[0] == fastDiff.DELETE) { - // not allowed - return to - } else if (item[0] == fastDiff.INSERT) { - str = str + fill.repeat(byteLength(item[1])) - } else { - str = str + item[1] - } - } - return str -} diff --git a/vim-config/plugins/coc.nvim/src/util/extensions.ts b/vim-config/plugins/coc.nvim/src/util/extensions.ts deleted file mode 100644 index aaf59ead..00000000 --- a/vim-config/plugins/coc.nvim/src/util/extensions.ts +++ /dev/null @@ -1,15 +0,0 @@ -declare interface Promise { - /** - * Catches task error and ignores them. - */ - logError(): void -} - -/** - * Explicitly tells that promise should be run asynchonously. - */ -Promise.prototype.logError = function (this: Promise): void { - this.catch(e => { - require('./logger')('extensions').error(e) - }) -} diff --git a/vim-config/plugins/coc.nvim/src/util/factory.ts b/vim-config/plugins/coc.nvim/src/util/factory.ts deleted file mode 100644 index 79890865..00000000 --- a/vim-config/plugins/coc.nvim/src/util/factory.ts +++ /dev/null @@ -1,171 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unsafe-return */ -import fs from 'fs' -import { Logger } from 'log4js' -import path from 'path' -import * as vm from 'vm' -import { defaults } from './lodash' -const createLogger = require('./logger') -const logger = createLogger('util-factoroy') - -export interface ExtensionExport { - activate: (context: unknown) => any - deactivate: () => any | null -} - -export interface IModule { - new(name: string): any - _resolveFilename: (file: string, context: any) => string - _extensions: {} - _cache: { [file: string]: any } - _compile: () => void - wrap: (content: string) => string - require: (file: string) => NodeModule - _nodeModulePaths: (filename: string) => string[] -} - -const Module: IModule = require('module') -const REMOVED_GLOBALS = [ - 'reallyExit', - 'abort', - 'umask', - 'setuid', - 'setgid', - 'setgroups', - '_fatalException', - 'exit', - 'kill', -] - -function removedGlobalStub(name: string): Function { - return () => { - throw new Error(`process.${name}() is not allowed in extension sandbox`) - } -} - -// @see node/lib/internal/module.js -function makeRequireFunction(this: any): any { - const req: any = (p: string) => { - if (p === 'coc.nvim') { - return require('../index') - } - return this.require(p) - } - req.resolve = (request: string) => Module._resolveFilename(request, this) - req.main = process.mainModule - // Enable support to add extra extension types - req.extensions = Module._extensions - req.cache = Module._cache - return req -} - -// @see node/lib/module.js -function compileInSandbox(sandbox: ISandbox): Function { - // eslint-disable-next-line - return function(this: any, content: string, filename: string): any { - const require = makeRequireFunction.call(this) - const dirname = path.dirname(filename) - // remove shebang - // eslint-disable-next-line - const newContent = content.replace(/^\#\!.*/, '') - const wrapper = Module.wrap(newContent) - const compiledWrapper = vm.runInContext(wrapper, sandbox, { filename }) - const args = [this.exports, require, this, filename, dirname] - return compiledWrapper.apply(this.exports, args) - } -} - -export interface ISandbox { - process: NodeJS.Process - module: NodeModule - require: (p: string) => any - console: { [key in keyof Console]?: Function } - Buffer: any - Reflect: any - // eslint-disable-next-line id-blacklist - String: any - Promise: any -} - -function createSandbox(filename: string, logger: Logger): ISandbox { - const module = new Module(filename) - module.paths = Module._nodeModulePaths(filename) - - const sandbox = vm.createContext({ - module, - Buffer, - console: { - debug: (...args: any[]) => { - logger.debug.apply(logger, args) - }, - log: (...args: any[]) => { - logger.info.apply(logger, args) - }, - error: (...args: any[]) => { - logger.error.apply(logger, args) - }, - info: (...args: any[]) => { - logger.info.apply(logger, args) - }, - warn: (...args: any[]) => { - logger.warn.apply(logger, args) - } - } - }) as ISandbox - - defaults(sandbox, global) - sandbox.Reflect = Reflect - - sandbox.require = function sandboxRequire(p): any { - const oldCompile = Module.prototype._compile - Module.prototype._compile = compileInSandbox(sandbox) - const moduleExports = sandbox.module.require(p) - Module.prototype._compile = oldCompile - return moduleExports - } - - // patch `require` in sandbox to run loaded module in sandbox context - // if you need any of these, it might be worth discussing spawning separate processes - sandbox.process = new (process as any).constructor() - for (let key of Object.keys(process)) { - sandbox.process[key] = process[key] - } - - REMOVED_GLOBALS.forEach(name => { - sandbox.process[name] = removedGlobalStub(name) - }) - sandbox.process['chdir'] = () => {} - - // read-only umask - sandbox.process.umask = (mask?: number) => { - if (typeof mask !== 'undefined') { - throw new Error('Cannot use process.umask() to change mask (read-only)') - } - return process.umask() - } - - return sandbox -} - -// inspiration drawn from Module -export function createExtension(id: string, filename: string, isEmpty = false): ExtensionExport { - if (isEmpty || !fs.existsSync(filename)) return { - activate: () => {}, - deactivate: null - } - const sandbox = createSandbox(filename, createLogger(`extension:${id}`)) - - delete Module._cache[require.resolve(filename)] - - // attempt to import plugin - // Require plugin to export activate & deactivate - const defaultImport = sandbox.require(filename) - const activate = (defaultImport && defaultImport.activate) || defaultImport - - if (typeof activate !== 'function') { - return { activate: () => {}, deactivate: null } - } - return { - activate, - deactivate: typeof defaultImport.deactivate === 'function' ? defaultImport.deactivate : null - } -} diff --git a/vim-config/plugins/coc.nvim/src/util/fs.ts b/vim-config/plugins/coc.nvim/src/util/fs.ts deleted file mode 100644 index af5f44d8..00000000 --- a/vim-config/plugins/coc.nvim/src/util/fs.ts +++ /dev/null @@ -1,251 +0,0 @@ -import { exec } from 'child_process' -import fs from 'fs-extra' -import net from 'net' -import os from 'os' -import path from 'path' -import readline from 'readline' -import util from 'util' -import minimatch from 'minimatch' -const logger = require('./logger')('util-fs') - -export type OnReadLine = (line: string) => void - -export async function statAsync(filepath: string): Promise { - let stat = null - try { - stat = await fs.stat(filepath) - } catch (e) { } - return stat -} - -export async function isDirectory(filepath: string): Promise { - let stat = await statAsync(filepath) - return stat && stat.isDirectory() -} - -export async function unlinkAsync(filepath: string): Promise { - try { - await fs.unlink(filepath) - } catch (e) { } -} - -export function renameAsync(oldPath: string, newPath: string): Promise { - return new Promise((resolve, reject) => { - fs.rename(oldPath, newPath, err => { - if (err) return reject(err) - resolve() - }) - }) -} - -export async function isGitIgnored(fullpath: string): Promise { - if (!fullpath) return false - let stat = await statAsync(fullpath) - if (!stat || !stat.isFile()) return false - let root = null - try { - let { stdout } = await util.promisify(exec)('git rev-parse --show-toplevel', { cwd: path.dirname(fullpath) }) - root = stdout.trim() - } catch (e) { } - if (!root) return false - let file = path.relative(root, fullpath) - try { - let { stdout } = await util.promisify(exec)(`git check-ignore ${file}`, { cwd: root }) - return stdout.trim() == file - } catch (e) { } - return false -} - -export function resolveRoot(folder: string, subs: string[], cwd?: string, bottomup = false, checkCwd = true): string | null { - let home = os.homedir() - let dir = fixDriver(folder) - if (isParentFolder(dir, home, true)) return null - if (checkCwd && cwd && isParentFolder(cwd, dir, true) && inDirectory(cwd, subs)) return cwd - let parts = dir.split(path.sep) - if (bottomup) { - while (parts.length > 0) { - let dir = parts.join(path.sep) - if (dir == home) { - break - } - if (dir != home && inDirectory(dir, subs)) { - return dir - } - parts.pop() - } - return null - } else { - let curr: string[] = [parts.shift()] - for (let part of parts) { - curr.push(part) - let dir = curr.join(path.sep) - if (dir != home && inDirectory(dir, subs)) { - return dir - } - } - return null - } -} - -export function inDirectory(dir: string, subs: string[]): boolean { - try { - let files = fs.readdirSync(dir) - for (let pattern of subs) { - // note, only '*' expanded - let is_wildcard = (pattern.includes('*')) - let res = is_wildcard ? - (minimatch.match(files, pattern, { nobrace: true, noext: true, nocomment: true, nonegate: true, dot: true }).length !== 0) : - (files.includes(pattern)) - if (res) return true - } - } catch (e) { - // could be failed without permission - } - return false -} - -export function findUp(name: string | string[], cwd: string): string { - let root = path.parse(cwd).root - let subs = Array.isArray(name) ? name : [name] - while (cwd && cwd !== root) { - let find = inDirectory(cwd, subs) - if (find) { - for (let sub of subs) { - let filepath = path.join(cwd, sub) - if (fs.existsSync(filepath)) { - return filepath - } - } - } - cwd = path.dirname(cwd) - } - return null -} - -export function readFile(fullpath: string, encoding: string): Promise { - return new Promise((resolve, reject) => { - fs.readFile(fullpath, encoding, (err, content) => { - if (err) reject(err) - resolve(content) - }) - }) -} - -export function getFileLineCount(filepath: string): Promise { - let i - let count = 0 - return new Promise((resolve, reject) => { - fs.createReadStream(filepath) - .on('error', e => reject(e)) - .on('data', chunk => { - for (i = 0; i < chunk.length; ++i) if (chunk[i] == 10) count++ - }) - .on('end', () => resolve(count)) - }) -} - -export function readFileLines(fullpath: string, start: number, end: number): Promise { - if (!fs.existsSync(fullpath)) { - return Promise.reject(new Error(`file does not exist: ${fullpath}`)) - } - let res: string[] = [] - const rl = readline.createInterface({ - input: fs.createReadStream(fullpath, { encoding: 'utf8' }), - crlfDelay: Infinity, - terminal: false - } as any) - let n = 0 - return new Promise((resolve, reject) => { - rl.on('line', line => { - if (n == 0 && line.startsWith('\uFEFF')) { - // handle BOM - line = line.slice(1) - } - if (n >= start && n <= end) { - res.push(line) - } - if (n == end) { - rl.close() - } - n = n + 1 - }) - rl.on('close', () => { - resolve(res) - }) - rl.on('error', reject) - }) -} - -export function readFileLine(fullpath: string, count: number): Promise { - if (!fs.existsSync(fullpath)) { - return Promise.reject(new Error(`file does not exist: ${fullpath}`)) - } - const rl = readline.createInterface({ - input: fs.createReadStream(fullpath, { encoding: 'utf8' }), - crlfDelay: Infinity, - terminal: false - } as any) - let n = 0 - return new Promise((resolve, reject) => { - rl.on('line', line => { - if (n == count) { - if (n == 0 && line.startsWith('\uFEFF')) { - // handle BOM - line = line.slice(1) - } - rl.close() - resolve(line) - return - } - n = n + 1 - }) - rl.on('error', reject) - }) -} - -export async function writeFile(fullpath: string, content: string): Promise { - await fs.writeFile(fullpath, content, { encoding: 'utf8' }) -} - -export function validSocket(path: string): Promise { - let clientSocket = new net.Socket() - return new Promise(resolve => { - clientSocket.on('error', () => { - resolve(false) - }) - clientSocket.connect({ path }, () => { - clientSocket.unref() - resolve(true) - }) - }) -} - -export function isFile(uri: string): boolean { - return uri.startsWith('file:') -} - -export function parentDirs(pth: string): string[] { - let { root, dir } = path.parse(pth) - if (dir === root) return [root] - const dirs = [root] - const parts = dir.slice(root.length).split(path.sep) - for (let i = 1; i <= parts.length; i++) { - dirs.push(path.join(root, parts.slice(0, i).join(path.sep))) - } - return dirs -} - -export function isParentFolder(folder: string, filepath: string, checkEqual = false): boolean { - let pdir = fixDriver(path.resolve(path.normalize(folder))) - let dir = fixDriver(path.resolve(path.normalize(filepath))) - if (pdir == '//') pdir = '/' - if (pdir == dir) return checkEqual ? true : false - if (pdir.endsWith(path.sep)) return dir.startsWith(pdir) - return dir.startsWith(pdir) && dir[pdir.length] == path.sep -} - -// use uppercase for windows driver -export function fixDriver(filepath: string): string { - if (os.platform() != 'win32' || filepath[1] != ':') return filepath - return filepath[0].toUpperCase() + filepath.slice(1) -} diff --git a/vim-config/plugins/coc.nvim/src/util/fuzzy.ts b/vim-config/plugins/coc.nvim/src/util/fuzzy.ts deleted file mode 100644 index 03421285..00000000 --- a/vim-config/plugins/coc.nvim/src/util/fuzzy.ts +++ /dev/null @@ -1,48 +0,0 @@ - -export function getCharCodes(str: string): number[] { - let res = [] - for (let i = 0, l = str.length; i < l; i++) { - res.push(str.charCodeAt(i)) - } - return res -} - -export function wordChar(ch: number): boolean { - return (ch >= 97 && ch <= 122) || (ch >= 65 && ch <= 90) -} - -export function caseMatch(input: number, code: number): boolean { - if (input == code) return true - if (input >= 97 && input <= 122 && code + 32 === input) return true - return false -} - -export function fuzzyChar(a: string, b: string): boolean { - let ca = a.charCodeAt(0) - let cb = b.charCodeAt(0) - if (ca === cb) return true - if (ca >= 97 && ca <= 122 && cb + 32 === ca) return true - return false -} - -// upper case must match, lower case ignore case -export function fuzzyMatch(needle: number[], text: string): boolean { - let totalCount = needle.length - if (needle.length > text.length) return false - let i = 0 - for (let j = 0; j < text.length; j++) { - if (i === totalCount) break - let code = text.charCodeAt(j) - let m = needle[i] - if (code === m) { - i = i + 1 - continue - } - // upper case match lower case - if ((m >= 97 && m <= 122) && code + 32 === m) { - i = i + 1 - continue - } - } - return i === totalCount -} diff --git a/vim-config/plugins/coc.nvim/src/util/fzy.ts b/vim-config/plugins/coc.nvim/src/util/fzy.ts deleted file mode 100644 index cc71f60e..00000000 --- a/vim-config/plugins/coc.nvim/src/util/fzy.ts +++ /dev/null @@ -1,201 +0,0 @@ -let SCORE_MIN = -Infinity -let SCORE_MAX = Infinity - -let SCORE_GAP_LEADING = -0.005 -let SCORE_GAP_TRAILING = -0.005 -let SCORE_GAP_INNER = -0.01 -let SCORE_MATCH_CONSECUTIVE = 1 -let SCORE_MATCH_SLASH = 0.9 -let SCORE_MATCH_WORD = 0.8 -let SCORE_MATCH_CAPITAL = 0.7 -let SCORE_MATCH_DOT = 0.6 - -function islower(s): boolean { - return s.toLowerCase() === s -} - -function isupper(s): boolean { - return s.toUpperCase() === s -} - -function precompute_bonus(haystack): number[] { - /* Which positions are beginning of words */ - let m = haystack.length - let match_bonus = new Array(m) - - let last_ch = '/' - for (let i = 0; i < m; i++) { - let ch = haystack[i] - - if (last_ch === '/') { - match_bonus[i] = SCORE_MATCH_SLASH - } else if (last_ch === '-' || last_ch === '_' || last_ch === ' ') { - match_bonus[i] = SCORE_MATCH_WORD - } else if (last_ch === '.') { - match_bonus[i] = SCORE_MATCH_DOT - } else if (islower(last_ch) && isupper(ch)) { - match_bonus[i] = SCORE_MATCH_CAPITAL - } else { - match_bonus[i] = 0 - } - - last_ch = ch - } - - return match_bonus -} - -function compute(needle, haystack, D, M): void { - let n = needle.length - let m = haystack.length - - let lower_needle = needle.toLowerCase() - let lower_haystack = haystack.toLowerCase() - - let match_bonus = precompute_bonus(haystack) - - /* - * D[][] Stores the best score for this position ending with a match. - * M[][] Stores the best possible score at this position. - */ - - for (let i = 0; i < n; i++) { - D[i] = new Array(m) - M[i] = new Array(m) - - let prev_score = SCORE_MIN - let gap_score = i === n - 1 ? SCORE_GAP_TRAILING : SCORE_GAP_INNER - - for (let j = 0; j < m; j++) { - if (lower_needle[i] === lower_haystack[j]) { - let score = SCORE_MIN - if (!i) { - score = (j * SCORE_GAP_LEADING) + match_bonus[j] - } else if (j) { /* i > 0 && j > 0*/ - score = Math.max( - M[i - 1][j - 1] + match_bonus[j], - - /* consecutive match, doesn't stack with match_bonus */ - D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE) - } - D[i][j] = score - M[i][j] = prev_score = Math.max(score, prev_score + gap_score) - } else { - D[i][j] = SCORE_MIN - M[i][j] = prev_score = prev_score + gap_score - } - } - } -} - -export function score(needle, haystack): number { - let n = needle.length - let m = haystack.length - - if (!n || !m) - return SCORE_MIN - - if (n === m) { - /* Since this method can only be called with a haystack which - * matches needle. If the lengths of the strings are equal the - * strings themselves must also be equal (ignoring case). - */ - return SCORE_MAX - } - - if (m > 1024) { - /* - * Unreasonably large candidate: return no score - * If it is a valid match it will still be returned, it will - * just be ranked below any reasonably sized candidates - */ - return SCORE_MIN - } - - let D = new Array(n) - let M = new Array(n) - - compute(needle, haystack, D, M) - - return M[n - 1][m - 1] -} - -export function groupPositions(arr: number[]): [number, number][] { - let res: [number, number][] = [] - for (let i = 0; i < arr.length; i++) { - let last = res.length ? res[res.length - 1] : undefined - let curr = arr[i] - if (last && curr == last[1]) { - last[1] = curr + 1 - } else { - res.push([curr, curr + 1]) - } - } - return res -} - -export function positions(needle: string, haystack: string): number[] { - let n = needle.length - let m = haystack.length - - let positions = new Array(n) - - if (!n || !m) - return positions - - if (n === m) { - for (let i = 0; i < n; i++) - positions[i] = i - return positions - } - - if (m > 1024) { - return positions - } - - let D = new Array(n) - let M = new Array(n) - - compute(needle, haystack, D, M) - - /* backtrack to find the positions of optimal matching */ - let match_required = false - - for (let i = n - 1, j = m - 1; i >= 0; i--) { - for (; j >= 0; j--) { - /* - * There may be multiple paths which result in - * the optimal weight. - * - * For simplicity, we will pick the first one - * we encounter, the latest in the candidate - * string. - */ - if (D[i][j] !== SCORE_MIN && - (match_required || D[i][j] === M[i][j])) { - /* If this score was determined using - * SCORE_MATCH_CONSECUTIVE, the - * previous character MUST be a match - */ - match_required = - i && j && - M[i][j] === D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE - positions[i] = j-- - break - } - } - } - - return positions -} - -export function hasMatch(needle: string, haystack: string): boolean { - needle = needle.toLowerCase() - haystack = haystack.toLowerCase() - let l = needle.length - for (let i = 0, j = 0; i < l; i += 1) { - j = haystack.indexOf(needle[i], j) + 1 - if (j === 0) return false - } - return true -} diff --git a/vim-config/plugins/coc.nvim/src/util/index.ts b/vim-config/plugins/coc.nvim/src/util/index.ts deleted file mode 100644 index 45067c0b..00000000 --- a/vim-config/plugins/coc.nvim/src/util/index.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { exec, ExecOptions } from 'child_process' -import debounce from 'debounce' -import fs from 'fs' -import isuri from 'isuri' -import path from 'path' -import { Disposable, MarkupContent, MarkupKind } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import which from 'which' -import * as platform from './platform' -export { platform } -const logger = require('./logger')('util-index') - -export type MapMode = 'n' | 'i' | 'v' | 'x' | 's' | 'o' - -export const CONFIG_FILE_NAME = 'coc-settings.json' - -export function isMarkdown(content: MarkupContent | string | undefined): boolean { - if (MarkupContent.is(content) && content.kind == MarkupKind.Markdown) { - return true - } - return false -} - -export function escapeSingleQuote(str: string): string { - return str.replace(/'/g, "''") -} - -export function wait(ms: number): Promise { - return new Promise(resolve => { - setTimeout(() => { - resolve(undefined) - }, ms) - }) -} - -export function waitNextTick(fn: () => void): Promise { - return new Promise(resolve => { - process.nextTick(() => { - fn() - resolve(undefined) - }) - }) -} - -export function getUri(fullpath: string, id: number, buftype: string, isCygwin: boolean): string { - if (!fullpath) return `untitled:${id}` - // https://github.com/neoclide/coc-java/issues/82 - if (platform.isWindows && !isCygwin && !fullpath.startsWith('jdt://')) fullpath = path.win32.normalize(fullpath) - if (path.isAbsolute(fullpath)) return URI.file(fullpath).toString() - if (isuri.isValid(fullpath)) return URI.parse(fullpath).toString() - if (buftype != '') return `${buftype}:${id}` - return `unknown:${id}` -} - -export function disposeAll(disposables: Disposable[]): void { - while (disposables.length) { - const item = disposables.pop() - if (item) { - item.dispose() - } - } -} - -export function executable(command: string): boolean { - try { - which.sync(command) - } catch (e) { - return false - } - return true -} - -export function runCommand(cmd: string, opts: ExecOptions = {}, timeout?: number): Promise { - if (!platform.isWindows) { - opts.shell = opts.shell || process.env.SHELL - } - opts.maxBuffer = 500 * 1024 - return new Promise((resolve, reject) => { - let timer: NodeJS.Timer - if (timeout) { - timer = setTimeout(() => { - reject(new Error(`timeout after ${timeout}s`)) - }, timeout * 1000) - } - exec(cmd, opts, (err, stdout, stderr) => { - if (timer) clearTimeout(timer) - if (err) { - reject(new Error(`exited with ${err.code}\n${err}\n${stderr}`)) - return - } - resolve(stdout) - }) - }) -} - -export function watchFile(filepath: string, onChange: () => void): Disposable { - let callback = debounce(onChange, 100) - try { - let watcher = fs.watch(filepath, { - persistent: true, - recursive: false, - encoding: 'utf8' - }, () => { - callback() - }) - return Disposable.create(() => { - callback.clear() - watcher.close() - }) - } catch (e) { - return Disposable.create(() => { - callback.clear() - }) - } -} - -export function isRunning(pid: number): boolean { - try { - let res: any = process.kill(pid, 0) - return res == true - } - catch (e) { - return e.code === 'EPERM' - } -} - -export function getKeymapModifier(mode: MapMode): string { - if (mode == 'n' || mode == 'o' || mode == 'x' || mode == 'v') return '' - if (mode == 'i') return '' - if (mode == 's') return '' - return '' -} - -export function concurrent(arr: T[], fn: (val: T) => Promise, limit = 3): Promise { - if (arr.length == 0) return Promise.resolve() - let finished = 0 - let total = arr.length - let remain = arr.slice() - return new Promise(resolve => { - let run = (val): void => { - let cb = () => { - finished = finished + 1 - if (finished == total) { - resolve() - } else if (remain.length) { - let next = remain.shift() - run(next) - } - } - fn(val).then(cb, cb) - } - for (let i = 0; i < Math.min(limit, remain.length); i++) { - let val = remain.shift() - run(val) - } - }) -} diff --git a/vim-config/plugins/coc.nvim/src/util/is.ts b/vim-config/plugins/coc.nvim/src/util/is.ts deleted file mode 100644 index 38ac2f0f..00000000 --- a/vim-config/plugins/coc.nvim/src/util/is.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { VimCompleteItem } from '../types' -/* eslint-disable id-blacklist */ -const hasOwnProperty = Object.prototype.hasOwnProperty - -export function vimCompleteItem(value: any): value is VimCompleteItem { - return value && typeof value.word === 'string' -} - -export function boolean(value: any): value is boolean { - return typeof value === 'boolean' -} - -export function string(value: any): value is string { - return typeof value === 'string' -} - -export function number(value: any): value is number { - return typeof value === 'number' -} - -export function array(array: any): array is any[] { - return Array.isArray(array) -} - -export function func(value: any): value is Function { - return typeof value == 'function' -} - -export function objectLiteral(obj: any): obj is object { - return ( - obj != null && - typeof obj === 'object' && - !Array.isArray(obj) && - !(obj instanceof RegExp) && - !(obj instanceof Date) - ) -} - -export function emptyObject(obj: any): boolean { - if (!objectLiteral(obj)) { - return false - } - - for (let key in obj) { - if (hasOwnProperty.call(obj, key)) { - return false - } - } - - return true -} - -export function typedArray( - value: any, - check: (value: any) => boolean -): value is T[] { - return Array.isArray(value) && (value as any).every(check) -} diff --git a/vim-config/plugins/coc.nvim/src/util/lodash.ts b/vim-config/plugins/coc.nvim/src/util/lodash.ts deleted file mode 100644 index 609c0ed6..00000000 --- a/vim-config/plugins/coc.nvim/src/util/lodash.ts +++ /dev/null @@ -1,52 +0,0 @@ - -/** Used for built-in method references. */ -const objectProto = Object.prototype - -/** Used to check objects for own properties. */ -const hasOwnProperty = objectProto.hasOwnProperty - -/** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @since 0.1.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see defaultsDeep - * @example - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }) - * // => { 'a': 1, 'b': 2 } - */ -export function defaults(obj: any, ...sources: any[]): any { - obj = Object(obj) - sources.forEach(source => { - if (source != null) { - source = Object(source) - for (const key in source) { - const value = obj[key] - if (value === undefined || - (value === objectProto[key] && !hasOwnProperty.call(obj, key))) { - obj[key] = source[key] - } - } - } - }) - return obj -} - -export function omit(obj: T, properties: string[]): T { - let o = {} - for (let key of Object.keys(obj)) { - if (!properties.includes(key)) { - o[key] = obj[key] - } - } - return o as T -} diff --git a/vim-config/plugins/coc.nvim/src/util/logger.ts b/vim-config/plugins/coc.nvim/src/util/logger.ts deleted file mode 100644 index 1c5c080e..00000000 --- a/vim-config/plugins/coc.nvim/src/util/logger.ts +++ /dev/null @@ -1,65 +0,0 @@ -import fs from 'fs' -import log4js from 'log4js' -import path from 'path' -import os from 'os' -import { mkdirpSync } from 'fs-extra' - -function getLogFile(): string { - let file = process.env.NVIM_COC_LOG_FILE - if (file) return file - let dir = process.env.XDG_RUNTIME_DIR - if (dir) { - try { - fs.accessSync(dir, fs.constants.R_OK | fs.constants.W_OK) - return path.join(dir, `coc-nvim-${process.pid}.log`) - } catch (err) { - // noop - } - } - let tmpdir = os.tmpdir() - dir = path.join(tmpdir, `coc.nvim-${process.pid}`) - if (!fs.existsSync(dir)) mkdirpSync(dir) - return path.join(dir, `coc-nvim.log`) -} - -const MAX_LOG_SIZE = 1024 * 1024 -const MAX_LOG_BACKUPS = 10 -let logfile = getLogFile() -const level = process.env.NVIM_COC_LOG_LEVEL || 'info' - -if (fs.existsSync(logfile)) { - // cleanup if exists - try { - fs.writeFileSync(logfile, '', { encoding: 'utf8', mode: 0o666 }) - } catch (e) { - // noop - } -} - -log4js.configure({ - disableClustering: true, - appenders: { - out: { - type: 'file', - mode: 0o666, - filename: logfile, - maxLogSize: MAX_LOG_SIZE, - backups: MAX_LOG_BACKUPS, - layout: { - type: 'pattern', - // Format log in following pattern: - // yyyy-MM-dd HH:mm:ss.mil $Level (pid:$pid) $categroy - $message. - pattern: `%d{ISO8601} %p (pid:${process.pid}) [%c] - %m`, - }, - } - }, - categories: { - default: { appenders: ['out'], level } - } -}) - -module.exports = (name = 'coc-nvim'): log4js.Logger => { - let logger = log4js.getLogger(name) - ; (logger as any).getLogFile = () => logfile - return logger -} diff --git a/vim-config/plugins/coc.nvim/src/util/match.ts b/vim-config/plugins/coc.nvim/src/util/match.ts deleted file mode 100644 index 2281b0d4..00000000 --- a/vim-config/plugins/coc.nvim/src/util/match.ts +++ /dev/null @@ -1,71 +0,0 @@ -import minimatch from 'minimatch' -import { DocumentFilter, DocumentSelector } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import * as platform from './platform' - -export function score(selector: DocumentSelector | DocumentFilter | string, uri: string, languageId: string): number { - if (Array.isArray(selector)) { - // array -> take max individual value - let ret = 0 - for (const filter of selector) { - const value = score(filter, uri, languageId) - if (value === 10) { - return value // already at the highest - } - if (value > ret) { - ret = value - } - } - return ret - } else if (typeof selector === 'string') { - // short-hand notion, desugars to - // 'fooLang' -> { language: 'fooLang'} - // '*' -> { language: '*' } - if (selector === '*') { - return 5 - } else if (selector === languageId) { - return 10 - } else { - return 0 - } - } else if (selector) { - let u = URI.parse(uri) - // filter -> select accordingly, use defaults for scheme - const { language, pattern, scheme } = selector - let ret = 0 - if (scheme) { - if (scheme === u.scheme) { - ret = 5 - } else if (scheme === '*') { - ret = 3 - } else { - return 0 - } - } - - if (language) { - if (language === languageId) { - ret = 10 - } else if (language === '*') { - ret = Math.max(ret, 5) - } else { - return 0 - } - } - - if (pattern) { - let caseInsensitive = platform.isWindows || platform.isMacintosh - let p = caseInsensitive ? pattern.toLowerCase() : pattern - let f = caseInsensitive ? u.fsPath.toLowerCase() : u.fsPath - if (p === f || minimatch(f, p, { dot: true })) { - ret = 5 - } else { - return 0 - } - } - - return ret - } else { - return 0 - } -} diff --git a/vim-config/plugins/coc.nvim/src/util/mutex.ts b/vim-config/plugins/coc.nvim/src/util/mutex.ts deleted file mode 100644 index 7d2b9bd2..00000000 --- a/vim-config/plugins/coc.nvim/src/util/mutex.ts +++ /dev/null @@ -1,46 +0,0 @@ -export class Mutex { - private tasks: (() => void)[] = [] - private count = 1 - - private sched(): void { - if (this.count > 0 && this.tasks.length > 0) { - this.count-- - let next = this.tasks.shift() - next() - } - } - - public get busy(): boolean { - return this.count == 0 - } - - public acquire(): Promise<() => void> { - return new Promise<() => void>(res => { - let task = () => { - let released = false - res(() => { - if (!released) { - released = true - this.count++ - this.sched() - } - }) - } - this.tasks.push(task) - process.nextTick(this.sched.bind(this)) - }) - } - - public use(f: () => Promise): Promise { - return this.acquire() - .then(release => f() - .then(res => { - release() - return res - }) - .catch(err => { - release() - throw err - })) - } -} diff --git a/vim-config/plugins/coc.nvim/src/util/object.ts b/vim-config/plugins/coc.nvim/src/util/object.ts deleted file mode 100644 index f2589db2..00000000 --- a/vim-config/plugins/coc.nvim/src/util/object.ts +++ /dev/null @@ -1,137 +0,0 @@ -import * as Is from './is' - -export function isEmpty(obj: object | null | undefined): boolean { - if (!obj) return true - if (Array.isArray(obj)) return obj.length == 0 - return Object.keys(obj).length == 0 -} - -export function deepClone(obj: T): T { - if (!obj || typeof obj !== 'object') { - return obj - } - if (obj instanceof RegExp) { - // See https://github.com/Microsoft/TypeScript/issues/10990 - return obj as any - } - const result: any = Array.isArray(obj) ? [] : {} - Object.keys(obj).forEach(key => { - if (obj[key] && typeof obj[key] === 'object') { - result[key] = deepClone(obj[key]) - } else { - result[key] = obj[key] - } - }) - return result -} - -const _hasOwnProperty = Object.prototype.hasOwnProperty - -export function deepFreeze(obj: T): T { - if (!obj || typeof obj !== 'object') { - return obj - } - const stack: any[] = [obj] - while (stack.length > 0) { - let obj = stack.shift() - Object.freeze(obj) - for (const key in obj) { - if (_hasOwnProperty.call(obj, key)) { - let prop = obj[key] - if (typeof prop === 'object' && !Object.isFrozen(prop)) { - stack.push(prop) - } - } - } - } - return obj -} - -/** - * Copies all properties of source into destination. The optional parameter "overwrite" allows to control - * if existing properties on the destination should be overwritten or not. Defaults to true (overwrite). - */ -export function mixin( - destination: any, - source: any, - overwrite = true -): any { - if (!Is.objectLiteral(destination)) { - return source - } - - if (Is.objectLiteral(source)) { - Object.keys(source).forEach(key => { - if (key in destination) { - if (overwrite) { - if (Is.objectLiteral(destination[key]) && Is.objectLiteral(source[key])) { - mixin(destination[key], source[key], overwrite) - } else { - destination[key] = source[key] - } - } - } else { - destination[key] = source[key] - } - }) - } - return destination -} - -export function equals(one: any, other: any): boolean { - if (one === other) { - return true - } - if ( - one === null || - one === undefined || - other === null || - other === undefined - ) { - return false - } - if (typeof one !== typeof other) { - return false - } - if (typeof one !== 'object') { - return false - } - if (Array.isArray(one) !== Array.isArray(other)) { - return false - } - - let i: number - let key: string - - if (Array.isArray(one)) { - if (one.length !== other.length) { - return false - } - for (i = 0; i < one.length; i++) { - if (!equals(one[i], other[i])) { - return false - } - } - } else { - const oneKeys: string[] = [] - - for (key in one) { - oneKeys.push(key) - } - oneKeys.sort() - const otherKeys: string[] = [] - for (key in other) { - otherKeys.push(key) - } - otherKeys.sort() - if (!equals(oneKeys, otherKeys)) { - return false - } - for (i = 0; i < oneKeys.length; i++) { - if (!equals(one[oneKeys[i]], other[oneKeys[i]])) { - return false - } - } - } - return true -} diff --git a/vim-config/plugins/coc.nvim/src/util/platform.ts b/vim-config/plugins/coc.nvim/src/util/platform.ts deleted file mode 100644 index d7d262fa..00000000 --- a/vim-config/plugins/coc.nvim/src/util/platform.ts +++ /dev/null @@ -1,83 +0,0 @@ -let _isWindows = false -let _isMacintosh = false -let _isLinux = false -let _isNative = false -let _isWeb = false - -export interface IProcessEnvironment { - [key: string]: string -} - -interface INodeProcess { - nextTick: Function - platform: string - env: IProcessEnvironment - getuid(): number -} - -declare let process: INodeProcess -declare let global: any - -interface INavigator { - userAgent: string - language: string -} -declare let self: any - -export const language = 'en' - -// OS detection -if ( - typeof process === 'object' && - typeof process.nextTick === 'function' && - typeof process.platform === 'string' -) { - _isWindows = process.platform === 'win32' - _isMacintosh = process.platform === 'darwin' - _isLinux = process.platform === 'linux' - _isNative = true -} - -export enum Platform { - Web, - Mac, - Linux, - Windows -} - -let _platform: Platform = Platform.Web -if (_isNative) { - if (_isMacintosh) { - _platform = Platform.Mac - } else if (_isWindows) { - _platform = Platform.Windows - } else if (_isLinux) { - _platform = Platform.Linux - } -} - -export const isWindows = _isWindows -export const isMacintosh = _isMacintosh -export const isLinux = _isLinux -export const isNative = _isNative -export const isWeb = _isWeb -export const platform = _platform - -const _globals = - typeof self === 'object' - ? self - : typeof global === 'object' - ? global - : ({} as any) -export const globals: any = _globals - -export const enum OperatingSystem { - Windows = 1, - Macintosh = 2, - Linux = 3 -} -export const OS = _isMacintosh - ? OperatingSystem.Macintosh - : _isWindows - ? OperatingSystem.Windows - : OperatingSystem.Linux diff --git a/vim-config/plugins/coc.nvim/src/util/position.ts b/vim-config/plugins/coc.nvim/src/util/position.ts deleted file mode 100644 index 9d247a29..00000000 --- a/vim-config/plugins/coc.nvim/src/util/position.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { Position, Range, TextEdit } from 'vscode-languageserver-protocol' - -export function rangeInRange(r: Range, range: Range): boolean { - return positionInRange(r.start, range) === 0 && positionInRange(r.end, range) === 0 -} - -/** - * Check if two ranges have overlap character. - */ -export function rangeOverlap(r: Range, range: Range): boolean { - let { start, end } = r - if (comparePosition(end, range.start) <= 0) { - return false - } - if (comparePosition(start, range.end) >= 0) { - return false - } - return true -} - -/** - * Check if two ranges have overlap or nested - */ -export function rangeIntersect(r: Range, range: Range): boolean { - if (positionInRange(r.start, range) == 0) { - return true - } - if (positionInRange(r.end, range) == 0) { - return true - } - if (rangeInRange(range, r)) { - return true - } - return false -} - -export function lineInRange(line: number, range: Range): boolean { - let { start, end } = range - return line >= start.line && line <= end.line -} - -export function emptyRange(range: Range): boolean { - let { start, end } = range - return start.line == end.line && start.character == end.character -} - -export function positionInRange(position: Position, range: Range): number { - let { start, end } = range - if (comparePosition(position, start) < 0) return -1 - if (comparePosition(position, end) > 0) return 1 - return 0 -} - -export function comparePosition(position: Position, other: Position): number { - if (position.line > other.line) return 1 - if (other.line == position.line && position.character > other.character) return 1 - if (other.line == position.line && position.character == other.character) return 0 - return -1 -} - -export function isSingleLine(range: Range): boolean { - return range.start.line == range.end.line -} - -export function getChangedPosition(start: Position, edit: TextEdit): { line: number; character: number } { - let { range, newText } = edit - if (comparePosition(range.end, start) <= 0) { - let lines = newText.split('\n') - let lineCount = lines.length - (range.end.line - range.start.line) - 1 - let characterCount = 0 - if (range.end.line == start.line) { - let single = isSingleLine(range) && lineCount == 0 - let removed = single ? range.end.character - range.start.character : range.end.character - let added = single ? newText.length : lines[lines.length - 1].length - characterCount = added - removed - } - return { line: lineCount, character: characterCount } - } - return { line: 0, character: 0 } -} - -export function adjustPosition(pos: Position, edit: TextEdit): Position { - let { range, newText } = edit - if (comparePosition(range.start, pos) > 1) return pos - let { start, end } = range - let newLines = newText.split('\n') - let delta = (end.line - start.line) - newLines.length + 1 - let lastLine = newLines[newLines.length - 1] - let line = pos.line - delta - if (pos.line != end.line) return { line, character: pos.character } - let pre = newLines.length == 1 && start.line != end.line ? start.character : 0 - let removed = start.line == end.line && newLines.length == 1 ? end.character - start.character : end.character - let character = pre + pos.character + lastLine.length - removed - return { - line, - character - } -} - -export function positionToOffset(lines: string[], line: number, character: number): number { - let offset = 0 - for (let i = 0; i <= line; i++) { - if (i == line) { - offset += character - } else { - offset += lines[i].length + 1 - } - } - return offset -} - -// edit a range to newText -export function editRange(range: Range, text: string, edit: TextEdit): string { - // outof range - if (!rangeInRange(edit.range, range)) return text - let { start, end } = edit.range - let lines = text.split('\n') - let character = start.line == range.start.line ? start.character - range.start.character : start.character - let startOffset = positionToOffset(lines, start.line - range.start.line, character) - character = end.line == range.start.line ? end.character - range.start.character : end.character - let endOffset = positionToOffset(lines, end.line - range.start.line, character) - return `${text.slice(0, startOffset)}${edit.newText}${text.slice(endOffset, text.length)}` -} - -export function getChangedFromEdits(start: Position, edits: TextEdit[]): Position | null { - let changed = { line: 0, character: 0 } - for (let edit of edits) { - let d = getChangedPosition(start, edit) - changed = { line: changed.line + d.line, character: changed.character + d.character } - } - return changed.line == 0 && changed.character == 0 ? null : changed -} diff --git a/vim-config/plugins/coc.nvim/src/util/processes.ts b/vim-config/plugins/coc.nvim/src/util/processes.ts deleted file mode 100644 index 6d50327e..00000000 --- a/vim-config/plugins/coc.nvim/src/util/processes.ts +++ /dev/null @@ -1,56 +0,0 @@ - -/* --------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -import * as cp from 'child_process' -import { join, dirname, resolve } from 'path' -import fs from 'fs' -import ChildProcess = cp.ChildProcess - -declare const ESBUILD - -const isWindows = process.platform === 'win32' -const isMacintosh = process.platform === 'darwin' -const isLinux = process.platform === 'linux' -const pluginRoot = typeof ESBUILD === 'undefined' ? resolve(__dirname, '../..') : dirname(__dirname) - -export function terminate(process: ChildProcess, cwd?: string): boolean { - if (process.killed) return - if (isWindows) { - try { - // This we run in Atom execFileSync is available. - // Ignore stderr since this is otherwise piped to parent.stderr - // which might be already closed. - let options: any = { - stdio: ['pipe', 'pipe', 'ignore'] - } - if (cwd) { - options.cwd = cwd - } - cp.execFileSync( - 'taskkill', - ['/T', '/F', '/PID', process.pid.toString()], - options - ) - return true - } catch (err) { - return false - } - } else if (isLinux || isMacintosh) { - try { - let filepath = join(pluginRoot, 'bin/terminateProcess.sh') - if (!fs.existsSync(filepath)) { - console.error(`"${filepath}" not found`) - return false - } - let result = cp.spawnSync(filepath, [process.pid.toString()]) - return result.error ? false : true - } catch (err) { - return false - } - } else { - process.kill('SIGKILL') - return true - } -} diff --git a/vim-config/plugins/coc.nvim/src/util/score.ts b/vim-config/plugins/coc.nvim/src/util/score.ts deleted file mode 100644 index d07b4acd..00000000 --- a/vim-config/plugins/coc.nvim/src/util/score.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { sep as pathSeparator } from 'path' -import { getCharCodes, fuzzyMatch, fuzzyChar, caseMatch } from './fuzzy' - -export interface MatchResult { - score: number - matches?: number[] // character indexes -} - -// first is start or path start +1, fuzzy +0.5 -// next is followed of path start +1, fuzzy +0.5 -// filename startsWith +1, fuzzy +0.5 - -export function getMatchResult(text: string, query: string, filename = ''): MatchResult { - if (!text) return { score: 0 } - if (!query) return { score: 1 } - let matches: number[] = [] - let codes = getCharCodes(query) - let filenameIdx = filename ? text.indexOf(filename) : -1 - let matchBase = filenameIdx != -1 && fuzzyMatch(codes, filename) - let score = 0 - let c = query[0] - let idx = 0 - // base => start => pathSeparator => fuzzy - if (matchBase) { - if (filename.startsWith(c)) { - score = score + 2 - idx = filenameIdx + 1 - matches.push(filenameIdx) - } else if (filename[0].toLowerCase() == c) { - score = score + 1.5 - idx = filenameIdx + 1 - matches.push(filenameIdx) - } else { - for (let i = 1; i < filename.length; i++) { - if (fuzzyChar(c, filename[i])) { - score = score + 1 - idx = filenameIdx + i + 1 - matches.push(filenameIdx + i) - break - } - } - } - } else if (text.startsWith(c)) { - score = score + 1 - matches.push(0) - idx = 1 - } else { - for (let i = 1; i < text.length; i++) { - let pre = text[i - 1] - if (pre == pathSeparator && text[i] == c) { - score = score + 1 - matches.push(i) - idx = i + 1 - break - } - } - if (idx == 0) { - for (let i = 0; i < text.length; i++) { - if (fuzzyChar(c, text[i])) { - score = score + 0.5 - matches.push(i) - idx = i + 1 - break - } - } - } - } - if (idx == 0) return { score: 0 } - if (codes.length == 1) return { score, matches } - return nextResult(codes.slice(1), text, idx, { score, matches }) -} - -/** - * - * @public - * @param {number[]} codes - remain codes - * @param {string} text - total text - * @param {number} idx - start index of text - * @param {MatchResult} curr - current result - * @returns {MatchResult | null} - */ -function nextResult(codes: number[], text: string, idx: number, curr: MatchResult): MatchResult | null { - let { score, matches } = curr - let results: MatchResult[] = [] - let c = codes[0] - let remain = codes.slice(1) - let result: MatchResult - - function getRemianResult(index: number): void { - if (!result) return - if (remain.length == 0) { - results.push(result) - } else if (result) { - let res = nextResult(remain, text, index, result) - if (res) results.push(res) - } - } - let followed = idx < text.length ? text[idx].charCodeAt(0) : null - if (!followed) return null - if (followed == c) { - result = { score: score + 1, matches: matches.concat([idx]) } - getRemianResult(idx + 1) - } else if (caseMatch(c, followed)) { - result = { score: score + 0.5, matches: matches.concat([idx]) } - getRemianResult(idx + 1) - } - if (idx + 1 < text.length) { - // follow path - for (let i = idx + 1; i < text.length; i++) { - let ch = text[i].charCodeAt(0) - if (text[i - 1] == pathSeparator && caseMatch(c, ch)) { - let add = c == ch ? 1 : 0.5 - result = { score: score + add, matches: matches.concat([i]) } - getRemianResult(i + 1) - break - } - } - // next fuzzy - for (let i = idx + 1; i < text.length; i++) { - let ch = text[i].charCodeAt(0) - if (caseMatch(c, ch)) { - let add = c == ch ? 0.5 : 0.2 - result = { score: score + add, matches: matches.concat([i]) } - getRemianResult(i + 1) - break - } - } - } - return results.length ? bestResult(results) : null -} - -function bestResult(results: MatchResult[]): MatchResult { - let res = results[0] - for (let i = 1; i < results.length; i++) { - if (results[i].score > res.score) { - res = results[i] - } - } - return res -} diff --git a/vim-config/plugins/coc.nvim/src/util/string.ts b/vim-config/plugins/coc.nvim/src/util/string.ts deleted file mode 100644 index d19bd19c..00000000 --- a/vim-config/plugins/coc.nvim/src/util/string.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { Range } from 'vscode-languageserver-protocol' - -export function rangeParts(text: string, range: Range): [string, string] { - let { start, end } = range - let lines = text.split(/\r?\n/) - let before = '' - let after = '' - let len = lines.length - // get start and end parts - for (let i = 0; i < len; i++) { - let curr = lines[i] - if (i < start.line) { - before += curr + '\n' - continue - } - if (i > end.line) { - after += curr + (i == len - 1 ? '' : '\n') - continue - } - if (i == start.line) { - before += curr.slice(0, start.character) - } - if (i == end.line) { - after += curr.slice(end.character) + (i == len - 1 ? '' : '\n') - } - } - return [before, after] -} - -// nvim use utf8 -export function byteLength(str: string): number { - return Buffer.byteLength(str) -} - -export function upperFirst(str: string): string { - return str ? str[0].toUpperCase() + str.slice(1) : '' -} - -export function byteIndex(content: string, index: number): number { - let s = content.slice(0, index) - return Buffer.byteLength(s) -} - -export function indexOf(str: string, ch: string, count = 1): number { - let curr = 0 - for (let i = 0; i < str.length; i++) { - if (str[i] == ch) { - curr = curr + 1 - if (curr == count) { - return i - } - } - } - return -1 -} - -export function characterIndex(content: string, byteIndex: number): number { - let buf = Buffer.from(content, 'utf8') - return buf.slice(0, byteIndex).toString('utf8').length -} - -export function byteSlice(content: string, start: number, end?: number): string { - let buf = Buffer.from(content, 'utf8') - return buf.slice(start, end).toString('utf8') -} - -export function isWord(character: string): boolean { - let code = character.charCodeAt(0) - if (code > 128) return false - if (code == 95) return true - if (code >= 48 && code <= 57) return true - if (code >= 65 && code <= 90) return true - if (code >= 97 && code <= 122) return true - return false -} - -export function isTriggerCharacter(character: string): boolean { - if (!character) return false - let code = character.charCodeAt(0) - if (code > 128) return false - if (code >= 65 && code <= 90) return false - if (code >= 97 && code <= 122) return false - return true -} - -export function isAsciiLetter(code: number): boolean { - if (code >= 65 && code <= 90) return true - if (code >= 97 && code <= 122) return true - return false -} - -function doEqualsIgnoreCase(a: string, b: string, stopAt = a.length): boolean { - if (typeof a !== 'string' || typeof b !== 'string') { - return false - } - for (let i = 0; i < stopAt; i++) { - const codeA = a.charCodeAt(i) - const codeB = b.charCodeAt(i) - if (codeA === codeB) { - continue - } - // a-z A-Z - if (isAsciiLetter(codeA) && isAsciiLetter(codeB)) { - const diff = Math.abs(codeA - codeB) - if (diff !== 0 && diff !== 32) { - return false - } - } - // Any other charcode - else { - if (String.fromCharCode(codeA).toLowerCase() !== String.fromCharCode(codeB).toLowerCase()) { - return false - } - } - } - return true -} - -export function equalsIgnoreCase(a: string, b: string): boolean { - const len1 = a ? a.length : 0 - const len2 = b ? b.length : 0 - if (len1 !== len2) { - return false - } - return doEqualsIgnoreCase(a, b) -} diff --git a/vim-config/plugins/coc.nvim/src/util/textedit.ts b/vim-config/plugins/coc.nvim/src/util/textedit.ts deleted file mode 100644 index 2c8b9042..00000000 --- a/vim-config/plugins/coc.nvim/src/util/textedit.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { TextEdit } from 'vscode-languageserver-protocol' - -export function singleLineEdit(edit: TextEdit): boolean { - let { range, newText } = edit - return range.start.line == range.end.line && newText.indexOf('\n') == -1 -} diff --git a/vim-config/plugins/coc.nvim/src/util/throttle.ts b/vim-config/plugins/coc.nvim/src/util/throttle.ts deleted file mode 100644 index 38bed3d5..00000000 --- a/vim-config/plugins/coc.nvim/src/util/throttle.ts +++ /dev/null @@ -1,42 +0,0 @@ - -/** - * Returns a new function that, when invoked, invokes `func` at most once per `wait` milliseconds. - * - * @param {Function} func Function to wrap. - * @param {Number} wait Number of milliseconds that must elapse between `func` invocations. - * @return {Function} A new function that wraps the `func` function passed in. - */ - -export default function throttle(func: Function, wait: number): Function & { clear(): void } { - let args - let rtn - let timeoutID - let last = 0 - - function fn(): any { - args = arguments - let delta = Date.now() - last - if (!timeoutID) { - if (last != 0 && delta >= wait) { - call() - } else { - timeoutID = setTimeout(call, wait - delta) - } - } - return rtn - } - - function call(): any { - timeoutID = 0 - last = Date.now() - rtn = func.apply(null, args) - args = null - } - - fn.clear = () => { - if (timeoutID) { - clearTimeout(timeoutID) - } - } - return fn -} diff --git a/vim-config/plugins/coc.nvim/src/watchman.ts b/vim-config/plugins/coc.nvim/src/watchman.ts deleted file mode 100644 index 285c81e7..00000000 --- a/vim-config/plugins/coc.nvim/src/watchman.ts +++ /dev/null @@ -1,196 +0,0 @@ -import watchman, { Client } from 'fb-watchman' -import os from 'os' -import path from 'path' -import { OutputChannel } from './types' -import { v1 as uuidv1 } from 'uuid' -import { Disposable } from 'vscode-languageserver-protocol' -import minimatch from 'minimatch' -import { isParentFolder } from './util/fs' -const logger = require('./util/logger')('watchman') -const requiredCapabilities = ['relative_root', 'cmd-watch-project', 'wildmatch', 'field-new'] - -export interface WatchResponse { - warning?: string - watcher: string - watch: string - relative_path?: string -} - -export interface FileChangeItem { - size: number - name: string - exists: boolean - new: boolean - type: 'f' | 'd' - mtime_ms: number -} - -export interface FileChange { - root: string - subscription: string - files: FileChangeItem[] -} - -export type ChangeCallback = (FileChange) => void - -const clientsMap: Map> = new Map() -/** - * Watchman wrapper for fb-watchman client - * - * @public - */ -export default class Watchman { - private client: Client - private watch: string | undefined - private relative_path: string | undefined - private _disposed = false - - constructor(binaryPath: string, private channel?: OutputChannel) { - this.client = new watchman.Client({ - watchmanBinaryPath: binaryPath - }) - this.client.setMaxListeners(300) - } - - public checkCapability(): Promise { - let { client } = this - return new Promise((resolve, reject) => { - client.capabilityCheck({ - optional: [], - required: requiredCapabilities - }, (error, resp) => { - if (error) return reject(error) - let { capabilities } = resp - for (let key of Object.keys(capabilities)) { - if (!capabilities[key]) return resolve(false) - } - resolve(true) - }) - }) - } - - public async watchProject(root: string): Promise { - try { - let resp = await this.command(['watch-project', root]) - let { watch, warning, relative_path } = (resp as WatchResponse) - if (warning) logger.warn(warning) - this.watch = watch - this.relative_path = relative_path - logger.info(`watchman watching project: ${root}`) - this.appendOutput(`watchman watching project: ${root}`) - } catch (e) { - logger.error(e) - return false - } - return true - } - - private command(args: any[]): Promise { - return new Promise((resolve, reject) => { - this.client.command(args, (error, resp) => { - if (error) return reject(error) - resolve(resp) - }) - }) - } - - public async subscribe(globPattern: string, cb: ChangeCallback): Promise { - let { watch, relative_path } = this - if (!watch) { - this.appendOutput(`watchman not watching: ${watch}`, 'Error') - return null - } - let { clock } = await this.command(['clock', watch]) - let uid = uuidv1() - let sub: any = { - expression: ['allof', ['match', '**/*', 'wholename']], - fields: ['name', 'size', 'new', 'exists', 'type', 'mtime_ms', 'ctime_ms'], - since: clock, - } - let root = watch - if (relative_path) { - sub.relative_root = relative_path - root = path.join(watch, relative_path) - } - let { subscribe } = await this.command(['subscribe', watch, uid, sub]) - if (global.hasOwnProperty('__TEST__')) (global as any).subscribe = subscribe - this.appendOutput(`subscribing "${globPattern}" in ${root}`) - this.client.on('subscription', resp => { - if (!resp || resp.subscription != uid) return - let { files } = resp as FileChange - if (!files) return - files = files.filter(f => f.type == 'f' && minimatch(f.name, globPattern, { dot: true })) - if (!files.length) return - let ev: FileChange = Object.assign({}, resp) - if (this.relative_path) ev.root = path.resolve(resp.root, this.relative_path) - this.appendOutput(`file change detected: ${JSON.stringify(ev, null, 2)}`) - cb(ev) - }) - return Disposable.create(() => this.unsubscribe(subscribe)) - } - - public unsubscribe(subscription: string): Promise { - if (this._disposed) return Promise.resolve() - let { watch } = this - if (!watch) return - this.appendOutput(`unsubscribe "${subscription}" in: ${watch}`) - return this.command(['unsubscribe', watch, subscription]).catch(e => { - logger.error(e) - }) - } - - public dispose(): void { - if (this._disposed) return - this._disposed = true - this.client.removeAllListeners() - this.client.end() - } - - private appendOutput(message: string, type = "Info"): void { - if (this.channel) { - this.channel.appendLine(`[${type} - ${(new Date().toLocaleTimeString())}] ${message}`) - } - } - - public static dispose(): void { - for (let promise of clientsMap.values()) { - promise.then(client => { - client.dispose() - }, _e => { - // noop - }) - } - } - - public static createClient(binaryPath: string, root: string, channel?: OutputChannel): Promise { - if (!isValidWatchRoot(root)) return null - let client = clientsMap.get(root) - if (client) return client - let promise = new Promise(async (resolve, reject) => { - try { - let watchman = new Watchman(binaryPath, channel) - let valid = await watchman.checkCapability() - if (!valid) return resolve(null) - let watching = await watchman.watchProject(root) - if (!watching) return resolve(null) - resolve(watchman) - } catch (e) { - reject(e) - } - }) - clientsMap.set(root, promise) - return promise - } -} - -/** - * Exclude user's home, driver, tmpdir - */ -export function isValidWatchRoot(root: string): boolean { - if (root == '/' || root == '/tmp' || root == '/private/tmp') return false - if (root.toLowerCase() === os.homedir().toLowerCase()) return false - if (path.parse(root).base == root) return false - if (root.startsWith('/tmp/') || root.startsWith('/private/tmp/')) return false - if (isParentFolder(os.tmpdir(), root, true)) return false - return true -} diff --git a/vim-config/plugins/coc.nvim/src/window.ts b/vim-config/plugins/coc.nvim/src/window.ts deleted file mode 100644 index 1088889c..00000000 --- a/vim-config/plugins/coc.nvim/src/window.ts +++ /dev/null @@ -1,657 +0,0 @@ -import { Neovim } from '@chemzqm/neovim' -import fs from 'fs' -import os from 'os' -import path from 'path' -import { CancellationToken, Disposable, Position } from 'vscode-languageserver-protocol' -import { URI } from 'vscode-uri' -import channels from './channels' -import events from './events' -import Dialog, { DialogConfig, DialogPreferences } from './model/dialog' -import Menu from './model/menu' -import Notification, { NotificationConfig, NotificationPreferences } from './model/notification' -import Picker, { QuickPickItem } from './model/picker' -import ProgressNotification, { Progress } from './model/progress' -import StatusLine, { StatusBarItem } from './model/status' -import { TreeView, TreeViewOptions } from './tree' -import { MessageLevel, OutputChannel } from './types' -import { CONFIG_FILE_NAME, disposeAll } from './util' -import { Mutex } from './util/mutex' -import { isWindows } from './util/platform' -import workspace from './workspace' -const logger = require('./util/logger')('window') - -export type MsgTypes = 'error' | 'warning' | 'more' - -export interface StatusItemOption { - progress?: boolean -} - -export interface ScreenPosition { - row: number - col: number -} - -export interface OpenTerminalOption { - /** - * Cwd of terminal, default to result of |getcwd()| - */ - cwd?: string - /** - * Close terminal on job finish, default to true. - */ - autoclose?: boolean - /** - * Keep foucus current window, default to false, - */ - keepfocus?: boolean -} - -export interface TerminalResult { - bufnr: number - success: boolean - content?: string -} -/** - * Value-object describing where and how progress should show. - */ -export interface ProgressOptions { - - /** - * A human-readable string which will be used to describe the - * operation. - */ - title?: string - - /** - * Controls if a cancel button should show to allow the user to - * cancel the long running operation. - */ - cancellable?: boolean -} - -/** - * Represents an action that is shown with an information, warning, or - * error message. - * - * @see [showInformationMessage](#window.showInformationMessage) - * @see [showWarningMessage](#window.showWarningMessage) - * @see [showErrorMessage](#window.showErrorMessage) - */ -export interface MessageItem { - - /** - * A short title like 'Retry', 'Open Log' etc. - */ - title: string - - /** - * A hint for modal dialogs that the item should be triggered - * when the user cancels the dialog (e.g. by pressing the ESC - * key). - * - * Note: this option is ignored for non-modal messages. - * Note: not used by coc.nvim for now. - */ - isCloseAffordance?: boolean -} - -class Window { - private mutex = new Mutex() - private statusLine: StatusLine | undefined - - public get nvim(): Neovim { - return workspace.nvim - } - - public dispose(): void { - this.statusLine?.dispose() - } - - /** - * Reveal message with message type. - * - * @param msg Message text to show. - * @param messageType Type of message, could be `error` `warning` and `more`, default to `more` - */ - public showMessage(msg: string, messageType: MsgTypes = 'more'): void { - if (this.mutex.busy || !this.nvim) return - let { messageLevel } = this - let method = process.env.VIM_NODE_RPC == '1' ? 'callTimer' : 'call' - if (global.hasOwnProperty('__TEST__')) logger.info(msg) - let hl = 'Error' - let level = MessageLevel.Error - switch (messageType) { - case 'more': - level = MessageLevel.More - hl = 'MoreMsg' - break - case 'warning': - level = MessageLevel.Warning - hl = 'WarningMsg' - break - } - if (level >= messageLevel) { - this.nvim[method]('coc#util#echo_messages', [hl, ('[coc.nvim] ' + msg).split('\n')], true) - } - } - - /** - * Run command in vim terminal for result - * - * @param cmd Command to run. - * @param cwd Cwd of terminal, default to result of |getcwd()|. - */ - public async runTerminalCommand(cmd: string, cwd?: string, keepfocus = false): Promise { - cwd = cwd || workspace.cwd - return await this.nvim.callAsync('coc#util#run_terminal', { cmd, cwd, keepfocus: keepfocus ? 1 : 0 }) as TerminalResult - } - - /** - * Open terminal window. - * - * @param cmd Command to run. - * @param opts Terminal option. - * @returns buffer number of terminal. - */ - public async openTerminal(cmd: string, opts: OpenTerminalOption = {}): Promise { - let bufnr = await this.nvim.call('coc#util#open_terminal', { cmd, ...opts }) - return bufnr as number - } - - /** - * Show quickpick for single item, use `window.menuPick` for menu at current current position. - * - * @param items Label list. - * @param placeholder Prompt text, default to 'choose by number'. - * @returns Index of selected item, or -1 when canceled. - */ - public async showQuickpick(items: string[], placeholder = 'Choose by number'): Promise { - let release = await this.mutex.acquire() - try { - let title = placeholder + ':' - items = items.map((s, idx) => `${idx + 1}. ${s}`) - let res = await this.nvim.callAsync('coc#util#quickpick', [title, items.map(s => s.trim())]) - release() - let n = parseInt(res, 10) - if (isNaN(n) || n <= 0 || n > items.length) return -1 - return n - 1 - } catch (e) { - release() - return -1 - } - } - - /** - * Show menu picker at current cursor position, |inputlist()| is used as fallback. - * Use `workspace.env.dialog` to check if the picker window/popup could work. - * - * @param items Array of texts. - * @param title Optional title of float/popup window. - * @param token A token that can be used to signal cancellation. - * @returns Selected index (0 based), -1 when canceled. - */ - public async showMenuPicker(items: string[], title?: string, token?: CancellationToken): Promise { - if (workspace.env.dialog) { - let release = await this.mutex.acquire() - if (token && token.isCancellationRequested) { - release() - return -1 - } - try { - let menu = new Menu(this.nvim, { items: items.map(s => s.trim()), title }, token) - let promise = new Promise(resolve => { - menu.onDidClose(selected => { - resolve(selected) - }) - }) - await menu.show(this.dialogPreference) - let res = await promise - release() - return res - } catch (e) { - logger.error(`Error on showMenuPicker:`, e) - release() - } - } - return await this.showQuickpick(items) - } - - /** - * Open local config file - */ - public async openLocalConfig(): Promise { - let { root } = workspace - if (root == os.homedir()) { - this.showMessage(`Can't create local config in home directory`, 'warning') - return - } - let dir = path.join(root, '.vim') - if (!fs.existsSync(dir)) { - let res = await this.showPrompt(`Would you like to create folder'${root}/.vim'?`) - if (!res) return - fs.mkdirSync(dir) - } - await workspace.jumpTo(URI.file(path.join(dir, CONFIG_FILE_NAME)).toString()) - } - - /** - * Prompt user for confirm, a float/popup window would be used when possible, - * use vim's |confirm()| function as callback. - * - * @param title The prompt text. - * @returns Result of confirm. - */ - public async showPrompt(title: string): Promise { - let release = await this.mutex.acquire() - try { - let res = await this.nvim.callAsync('coc#float#prompt_confirm', [title]) - release() - return res == 1 - } catch (e) { - release() - return false - } - } - - /** - * Show dialog window at the center of screen. - * Note that the dialog would always be closed after button click. - * Use `workspace.env.dialog` to check if dialog could work. - * - * @param config Dialog configuration. - * @returns Dialog or null when dialog can't work. - */ - public async showDialog(config: DialogConfig): Promise

    { - if (!this.checkDialog()) return null - let dialog = new Dialog(this.nvim, config) - await dialog.show(this.dialogPreference) - return dialog - } - - /** - * Request input from user - * - * @param title Title text of prompt window. - * @param defaultValue Default value of input, empty text by default. - */ - public async requestInput(title: string, defaultValue?: string): Promise { - let { nvim } = this - const preferences = workspace.getConfiguration('coc.preferences') - if (workspace.env.dialog && preferences.get('promptInput', true) && !isWindows) { - let release = await this.mutex.acquire() - let preferences = this.dialogPreference - try { - let opts: any = {} - if (preferences.floatHighlight) opts.highlight = preferences.floatHighlight - if (preferences.floatBorderHighlight) opts.borderhighlight = preferences.floatBorderHighlight - let arr = await nvim.call('coc#float#create_prompt_win', [title, defaultValue || '', opts]) as [number, number] - let [bufnr, winid] = arr - let res = await new Promise(resolve => { - let disposables: Disposable[] = [] - events.on('BufWinLeave', nr => { - if (nr == bufnr) { - disposeAll(disposables) - resolve(null) - } - }, null, disposables) - events.on('PromptInsert', async value => { - disposeAll(disposables) - await nvim.call('coc#float#close', [winid]) - if (!value) { - this.showMessage('Empty word, canceled', 'warning') - resolve(null) - } else { - resolve(value) - } - }, null, disposables) - }) - release() - return res - } catch (e) { - logger.error('Error on requestInput:', e) - release() - } - } else { - let res = await workspace.callAsync('input', [title + ': ', defaultValue || '']) - nvim.command('normal! :', true) - if (!res) { - this.showMessage('Empty word, canceled', 'warning') - return null - } - return res - } - } - - /** - * Create statusbar item that would be included in `g:coc_status`. - * - * @param priority Higher priority item would be shown right. - * @param option - * @return A new status bar item. - */ - public createStatusBarItem(priority = 0, option: StatusItemOption = {}): StatusBarItem { - if (!workspace.env) { - let fn = () => {} - return { text: '', show: fn, dispose: fn, hide: fn, priority: 0, isProgress: false } - } - if (!this.statusLine) { - this.statusLine = new StatusLine(this.nvim) - } - return this.statusLine.createStatusBarItem(priority, option.progress || false) - } - - /** - * Create a new output channel - * - * @param name Unique name of output channel. - * @returns A new output channel. - */ - public createOutputChannel(name: string): OutputChannel { - return channels.create(name, this.nvim) - } - - /** - * Reveal buffer of output channel. - * - * @param name Name of output channel. - * @param preserveFocus Preserve window focus when true. - */ - public showOutputChannel(name: string, preserveFocus?: boolean): void { - channels.show(name, preserveFocus) - } - - /** - * Echo lines at the bottom of vim. - * - * @param lines Line list. - * @param truncate Truncate the lines to avoid 'press enter to continue' when true - */ - public async echoLines(lines: string[], truncate = false): Promise { - let { nvim } = this - let cmdHeight = workspace.env.cmdheight - if (lines.length > cmdHeight && truncate) { - lines = lines.slice(0, cmdHeight) - } - let maxLen = workspace.env.columns - 12 - lines = lines.map(line => { - line = line.replace(/\n/g, ' ') - if (truncate) line = line.slice(0, maxLen) - return line - }) - if (truncate && lines.length == cmdHeight) { - let last = lines[lines.length - 1] - lines[cmdHeight - 1] = `${last.length == maxLen ? last.slice(0, -4) : last} ...` - } - await nvim.call('coc#util#echo_lines', [lines]) - } - - /** - * Get current cursor position (line, character both 0 based). - * - * @returns Cursor position. - */ - public async getCursorPosition(): Promise { - // vim can't count utf16 - let [line, content] = await this.nvim.eval(`[line('.')-1, strpart(getline('.'), 0, col('.') - 1)]`) as [number, string] - return Position.create(line, content.length) - } - - /** - * Move cursor to position. - * - * @param position LSP position. - */ - public async moveTo(position: Position): Promise { - await this.nvim.call('coc#cursor#move_to', [position.line, position.character]) - if (workspace.env.isVim) this.nvim.command('redraw', true) - } - - /** - * Get current cursor character offset in document, - * length of line break would always be 1. - * - * @returns Character offset. - */ - public async getOffset(): Promise { - return await this.nvim.call('coc#cursor#char_offset') as number - } - - /** - * Get screen position of current cursor(relative to editor), - * both `row` and `col` are 0 based. - * - * @returns Cursor screen position. - */ - public async getCursorScreenPosition(): Promise { - let [row, col] = await this.nvim.call('coc#cursor#screen_pos') as [number, number] - return { row, col } - } - - /** - * Show multiple picker at center of screen. - * Use `workspace.env.dialog` to check if dialog could work. - * - * @param items Array of QuickPickItem or string. - * @param title Title of picker dialog. - * @param token A token that can be used to signal cancellation. - * @return A promise that resolves to the selected items or `undefined`. - */ - public async showPickerDialog(items: string[], title: string, token?: CancellationToken): Promise - public async showPickerDialog(items: T[], title: string, token?: CancellationToken): Promise - public async showPickerDialog(items: any, title: string, token?: CancellationToken): Promise { - if (!this.checkDialog()) return undefined - let release = await this.mutex.acquire() - if (token && token.isCancellationRequested) { - release() - return undefined - } - try { - let useString = typeof items[0] === 'string' - let picker = new Picker(this.nvim, { - title, - items: useString ? items.map(s => { - return { label: s } - }) : items, - }, token) - let promise = new Promise(resolve => { - picker.onDidClose(selected => { - resolve(selected) - }) - }) - await picker.show(this.dialogPreference) - let picked = await promise - let res = picked == undefined ? undefined : items.filter((_, i) => picked.includes(i)) - release() - return res - } catch (e) { - logger.error(`Error on showPickerDialog:`, e) - release() - } - } - - /** - * Show an information message to users. Optionally provide an array of items which will be presented as - * clickable buttons. - * - * @param message The message to show. - * @param items A set of items that will be rendered as actions in the message. - * @return Promise that resolves to the selected item or `undefined` when being dismissed. - */ - public async showInformationMessage(message: string, ...items: string[]): Promise - public async showInformationMessage(message: string, ...items: T[]): Promise - public async showInformationMessage(message: string, ...items: T[]): Promise { - if (!this.enableMessageDialog) return await this.showConfirm(message, items, 'Info') as any - let texts = typeof items[0] === 'string' ? items : (items as any[]).map(s => s.title) - let idx = await this.createNotification('CocInfoFloat', message, texts) - return idx == -1 ? undefined : items[idx] - } - - /** - * Show an warning message to users. Optionally provide an array of items which will be presented as - * clickable buttons. - * - * @param message The message to show. - * @param items A set of items that will be rendered as actions in the message. - * @return Promise that resolves to the selected item or `undefined` when being dismissed. - */ - public async showWarningMessage(message: string, ...items: string[]): Promise - public async showWarningMessage(message: string, ...items: T[]): Promise - public async showWarningMessage(message: string, ...items: T[]): Promise { - if (!this.enableMessageDialog) return await this.showConfirm(message, items, 'Warning') as any - let texts = typeof items[0] === 'string' ? items : (items as any[]).map(s => s.title) - let idx = await this.createNotification('CocWarningFloat', message, texts) - return idx == -1 ? undefined : items[idx] - } - - /** - * Show an error message to users. Optionally provide an array of items which will be presented as - * clickable buttons. - * - * @param message The message to show. - * @param items A set of items that will be rendered as actions in the message. - * @return Promise that resolves to the selected item or `undefined` when being dismissed. - */ - public async showErrorMessage(message: string, ...items: string[]): Promise - public async showErrorMessage(message: string, ...items: T[]): Promise - public async showErrorMessage(message: string, ...items: T[]): Promise { - if (!this.enableMessageDialog) return await this.showConfirm(message, items, 'Error') as any - let texts = typeof items[0] === 'string' ? items : (items as any[]).map(s => s.title) - let idx = await this.createNotification('CocErrorFloat', message, texts) - return idx == -1 ? undefined : items[idx] - } - - public async showNotification(config: NotificationConfig): Promise { - if (!this.checkDialog()) return false - let notification = new Notification(this.nvim, config) - return await notification.show(this.notificationPreference) - } - - // fallback for vim without dialog - private async showConfirm(message: string, items: T[], kind: 'Info' | 'Warning' | 'Error'): Promise { - if (!items || items.length == 0) { - let msgType: MsgTypes = kind == 'Info' ? 'more' : kind == 'Error' ? 'error' : 'warning' - this.showMessage(message, msgType) - return undefined - } - let titles: string[] = typeof items[0] === 'string' ? items.slice() as string[] : items.map(o => (o as MessageItem).title) - let choices = titles.map((s, i) => `${i + 1}${s}`) - let res = await this.nvim.callAsync('coc#util#with_callback', ['confirm', [message, choices.join('\n'), 0, kind]]) - return items[res - 1] - } - - /** - * Show progress in the editor. Progress is shown while running the given callback - * and while the promise it returned isn't resolved nor rejected. - * - * @param task A callback returning a promise. Progress state can be reported with - * the provided [progress](#Progress)-object. - * - * To report discrete progress, use `increment` to indicate how much work has been completed. Each call with - * a `increment` value will be summed up and reflected as overall progress until 100% is reached (a value of - * e.g. `10` accounts for `10%` of work done). - * - * To monitor if the operation has been cancelled by the user, use the provided [`CancellationToken`](#CancellationToken). - * - * @return The thenable the task-callback returned. - */ - public async withProgress(options: ProgressOptions, task: (progress: Progress<{ message?: string; increment?: number }>, token: CancellationToken) => Thenable): Promise { - if (!this.checkDialog()) return undefined - let progress = new ProgressNotification(this.nvim, { - task, - title: options.title, - cancellable: options.cancellable - }) - return await progress.show(this.notificationPreference) - } - - /** - * Create a {@link TreeView} instance. - * - * @param viewId Id of the view, used as title of TreeView when title not exists. - * @param options Options for creating the {@link TreeView} - * @returns a {@link TreeView}. - */ - public createTreeView(viewId: string, options: TreeViewOptions): TreeView { - const BasicTreeView = require('./tree/TreeView').default - return new BasicTreeView(viewId, options) - } - - private createNotification(borderhighlight: string, message: string, items: string[]): Promise { - return new Promise(resolve => { - let config: NotificationConfig = { - content: message, - borderhighlight, - close: true, - buttons: items.map((s, index) => { - return { text: s, index } - }), - callback: idx => { - resolve(idx) - } - } - let notification = new Notification(this.nvim, config) - notification.show(this.notificationPreference).then(shown => { - if (!shown) { - logger.error('Unable to open notification window') - resolve(-1) - } - if (!items.length) resolve(-1) - }, e => { - logger.error('Unable to open notification window', e) - resolve(-1) - }) - }) - } - - private get dialogPreference(): DialogPreferences { - let config = workspace.getConfiguration('dialog') - return { - maxWidth: config.get('maxWidth'), - maxHeight: config.get('maxHeight'), - floatHighlight: config.get('floatHighlight'), - floatBorderHighlight: config.get('floatBorderHighlight'), - pickerButtons: config.get('pickerButtons'), - pickerButtonShortcut: config.get('pickerButtonShortcut'), - confirmKey: config.get('confirmKey'), - } - } - - private get notificationPreference(): NotificationPreferences { - let config = workspace.getConfiguration('notification') - return { - top: config.get('marginTop'), - right: config.get('marginRight'), - maxWidth: config.get('maxWidth'), - maxHeight: config.get('maxHeight'), - highlight: config.get('highlightGroup'), - minProgressWidth: config.get('minProgressWidth'), - } - } - - private checkDialog(): boolean { - if (workspace.env.dialog) return true - this.showMessage('Dialog requires vim >= 8.2.0750 or neovim >= 0.4.0, please upgrade your vim', 'warning') - return false - } - - private get enableMessageDialog(): boolean { - if (!workspace.env.dialog) return false - let config = workspace.getConfiguration('coc.preferences') - return config.get('enableMessageDialog', false) - } - - private get messageLevel(): MessageLevel { - let config = workspace.getConfiguration('coc.preferences') - let level = config.get('messageLevel', 'more') - switch (level) { - case 'error': - return MessageLevel.Error - case 'warning': - return MessageLevel.Warning - default: - return MessageLevel.More - } - } -} - -export default new Window() diff --git a/vim-config/plugins/coc.nvim/src/workspace.ts b/vim-config/plugins/coc.nvim/src/workspace.ts deleted file mode 100644 index ea53c190..00000000 --- a/vim-config/plugins/coc.nvim/src/workspace.ts +++ /dev/null @@ -1,1727 +0,0 @@ -import { Buffer, NeovimClient as Neovim } from '@chemzqm/neovim' -import bytes from 'bytes' -import fastDiff from 'fast-diff' -import fs from 'fs-extra' -import os from 'os' -import path from 'path' -import { v1 as uuid } from 'uuid' -import { CancellationTokenSource, CreateFile, CreateFileOptions, DeleteFile, DeleteFileOptions, Disposable, DocumentSelector, Emitter, Event, FormattingOptions, Location, LocationLink, Position, Range, RenameFile, RenameFileOptions, TextDocumentEdit, TextDocumentSaveReason, TextEdit, WorkspaceEdit, WorkspaceFolder, WorkspaceFoldersChangeEvent } from 'vscode-languageserver-protocol' -import { TextDocument } from 'vscode-languageserver-textdocument' -import { URI } from 'vscode-uri' -import which from 'which' -import channels from './channels' -import Configurations from './configuration' -import ConfigurationShape from './configuration/shape' -import events from './events' -import DB from './model/db' -import Document from './model/document' -import FileSystemWatcher from './model/fileSystemWatcher' -import Mru from './model/mru' -import Resolver from './model/resolver' -import Task from './model/task' -import TerminalModel, { TerminalOptions } from './model/terminal' -import BufferSync, { SyncItem } from './model/bufferSync' -import { TextDocumentContentProvider } from './provider' -import { ConfigurationChangeEvent, ConfigurationTarget, DidChangeTextDocumentParams, DocumentChange, EditerState, Env, FileCreateEvent, FileDeleteEvent, FileRenameEvent, FileWillCreateEvent, FileWillDeleteEvent, FileWillRenameEvent, IWorkspace, OutputChannel, PatternType, QuickfixItem, TextDocumentWillSaveEvent, WorkspaceConfiguration } from './types' -import { distinct } from './util/array' -import { findUp, fixDriver, inDirectory, isFile, isParentFolder, readFileLine, renameAsync, resolveRoot, statAsync } from './util/fs' -import { CONFIG_FILE_NAME, disposeAll, getKeymapModifier, platform, runCommand, wait, MapMode } from './util/index' -import { score } from './util/match' -import { getChangedFromEdits } from './util/position' -import { byteIndex, byteLength } from './util/string' -import Watchman from './watchman' -import window from './window' -import { version as VERSION } from '../package.json' - -export interface KeymapOption { - sync: boolean - cancel: boolean - silent: boolean - repeat: boolean -} - -export interface Autocmd { - pattern?: string - event: string | string[] - arglist?: string[] - request?: boolean - thisArg?: any - callback: Function -} - -const APIVERSION = 10 -const logger = require('./util/logger')('workspace') -let NAME_SPACE = 2000 -const methods = [ - 'showMessage', - 'runTerminalCommand', - 'openTerminal', - 'showQuickpick', - 'menuPick', - 'openLocalConfig', - 'showPrompt', - 'createStatusBarItem', - 'createOutputChannel', - 'showOutputChannel', - 'requestInput', - 'echoLines', - 'getCursorPosition', - 'moveTo', - 'getOffset'] - -export class Workspace implements IWorkspace { - public readonly nvim: Neovim - public readonly version: string - public readonly keymaps: Map = new Map() - public bufnr: number - private maxFileSize: number - private resolver: Resolver = new Resolver() - private rootPatterns: Map = new Map() - private _workspaceFolders: WorkspaceFolder[] = [] - private _insertMode = false - private _env: Env - private _root: string - private _cwd = process.cwd() - private _initialized = false - private _attached = false - private buffers: Map = new Map() - private autocmdMaxId = 0 - private autocmds: Map = new Map() - private terminals: Map = new Map() - private creatingSources: Map = new Map() - private schemeProviderMap: Map = new Map() - private namespaceMap: Map = new Map() - private disposables: Disposable[] = [] - private watchedOptions: Set = new Set() - - private _dynAutocmd = false - private _disposed = false - private _onDidOpenDocument = new Emitter() - private _onDidCloseDocument = new Emitter() - private _onDidChangeDocument = new Emitter() - private _onWillSaveDocument = new Emitter() - private _onDidSaveDocument = new Emitter() - private _onDidChangeWorkspaceFolders = new Emitter() - private _onDidChangeConfiguration = new Emitter() - private _onDidWorkspaceInitialized = new Emitter() - private _onDidOpenTerminal = new Emitter() - private _onDidCloseTerminal = new Emitter() - private _onDidRuntimePathChange = new Emitter() - - public readonly onDidCloseTerminal: Event = this._onDidCloseTerminal.event - public readonly onDidOpenTerminal: Event = this._onDidOpenTerminal.event - public readonly onDidChangeWorkspaceFolders: Event = this._onDidChangeWorkspaceFolders.event - public readonly onDidOpenTextDocument: Event = this._onDidOpenDocument.event - public readonly onDidCloseTextDocument: Event = this._onDidCloseDocument.event - public readonly onDidChangeTextDocument: Event = this._onDidChangeDocument.event - public readonly onWillSaveTextDocument: Event = this._onWillSaveDocument.event - public readonly onDidSaveTextDocument: Event = this._onDidSaveDocument.event - public readonly onDidChangeConfiguration: Event = this._onDidChangeConfiguration.event - public readonly onDidWorkspaceInitialized: Event = this._onDidWorkspaceInitialized.event - public readonly onDidRuntimePathChange: Event = this._onDidRuntimePathChange.event - public readonly configurations: Configurations - - private _onDidCreateFiles = new Emitter() - private _onDidRenameFiles = new Emitter() - private _onDidDeleteFiles = new Emitter() - private _onWillCreateFiles = new Emitter() - private _onWillRenameFiles = new Emitter() - private _onWillDeleteFiles = new Emitter() - - public readonly onDidCreateFiles: Event = this._onDidCreateFiles.event - public readonly onDidRenameFiles: Event = this._onDidRenameFiles.event - public readonly onDidDeleteFiles: Event = this._onDidDeleteFiles.event - public readonly onWillCreateFiles: Event = this._onWillCreateFiles.event - public readonly onWillRenameFiles: Event = this._onWillRenameFiles.event - public readonly onWillDeleteFiles: Event = this._onWillDeleteFiles.event - - constructor() { - this.version = VERSION - this.configurations = this.createConfigurations() - let cwd = process.cwd() - if (cwd != os.homedir() && inDirectory(cwd, ['.vim'])) { - this._workspaceFolders.push({ - uri: URI.file(cwd).toString(), - name: path.basename(cwd) - }) - } - } - - public async init(): Promise { - let { nvim } = this - for (let method of methods) { - Object.defineProperty(this, method, { - get: () => { - return (...args: any[]) => { - // logger.warn(`workspace.${method} is deprecated, please use window.${method} instead.`, Error().stack) - return window[method].apply(window, args) - } - } - }) - } - this._env = await nvim.call('coc#util#vim_info') as Env - if (this._env.apiversion != APIVERSION) { - console.error(`API version ${this._env.apiversion} is not ${APIVERSION}, please build coc.nvim by 'yarn install' after pull source code.`) - process.exit() - } - this._insertMode = this._env.mode.startsWith('insert') - if (this._env.workspaceFolders && Array.isArray(this._env.workspaceFolders)) { - this._workspaceFolders = this._env.workspaceFolders.map(f => ({ - uri: URI.file(f).toString(), - name: path.dirname(f) - })) - } - this.configurations.updateUserConfig(this._env.config) - let preferences = this.getConfiguration('coc.preferences') - let maxFileSize = preferences.get('maxFileSize', '10MB') - this.maxFileSize = bytes.parse(maxFileSize) - events.on(['InsertEnter', 'CursorMovedI'], () => { - this._insertMode = true - }, null, this.disposables) - events.on(['InsertLeave', 'CursorMoved'], () => { - this._insertMode = false - }, null, this.disposables) - events.on('BufEnter', this.onBufEnter, this, this.disposables) - events.on('CursorMoved', this.checkCurrentBuffer, this, this.disposables) - events.on('CursorMovedI', this.checkCurrentBuffer, this, this.disposables) - events.on('DirChanged', this.onDirChanged, this, this.disposables) - events.on('BufCreate', this.onBufCreate, this, this.disposables) - events.on('BufUnload', this.onBufUnload, this, this.disposables) - events.on('TermOpen', this.onBufCreate, this, this.disposables) - events.on('TermClose', this.onBufUnload, this, this.disposables) - events.on('BufWritePost', this.onBufWritePost, this, this.disposables) - events.on('BufWritePre', this.onBufWritePre, this, this.disposables) - events.on('FileType', this.onFileTypeChange, this, this.disposables) - events.on('CursorHold', this.checkCurrentBuffer, this, this.disposables) - events.on('TextChanged', this.checkBuffer, this, this.disposables) - events.on('BufReadCmd', this.onBufReadCmd, this, this.disposables) - events.on('VimResized', (columns, lines) => { - Object.assign(this._env, { columns, lines }) - }, null, this.disposables) - await this.attach() - this.attachChangedEvents() - this.configurations.onDidChange(e => { - this._onDidChangeConfiguration.fire(e) - }, null, this.disposables) - this.watchOption('runtimepath', (oldValue, newValue: string) => { - let result = fastDiff(oldValue, newValue) - for (let [changeType, value] of result) { - if (changeType == 1) { - let paths = value.replace(/,$/, '').split(',') - this._onDidRuntimePathChange.fire(paths) - } - } - this._env.runtimepath = newValue - }, this.disposables) - this.watchGlobal('coc_sources_disable_map', async (_, newValue) => { - this.env.disabledSources = newValue - }) - this.disposables.push(this.registerTextDocumentContentProvider('output', channels.getProvider(nvim))) - } - - public getConfigFile(target: ConfigurationTarget): string { - return this.configurations.getConfigFile(target) - } - - /** - * Register autocmd on vim. - */ - public registerAutocmd(autocmd: Autocmd): Disposable { - this.autocmdMaxId += 1 - let id = this.autocmdMaxId - this.autocmds.set(id, autocmd) - this.setupDynamicAutocmd() - return Disposable.create(() => { - this.autocmds.delete(id) - this.setupDynamicAutocmd() - }) - } - - /** - * Watch for option change. - */ - public watchOption(key: string, callback: (oldValue: any, newValue: any) => Thenable | void, disposables?: Disposable[]): void { - let watching = this.watchedOptions.has(key) - if (!watching) { - this.watchedOptions.add(key) - this.setupDynamicAutocmd() - } - let disposable = events.on('OptionSet', async (changed: string, oldValue: any, newValue: any) => { - if (changed == key && callback) { - await Promise.resolve(callback(oldValue, newValue)) - } - }) - if (disposables) { - disposables.push( - Disposable.create(() => { - disposable.dispose() - if (watching) return - this.watchedOptions.delete(key) - this.setupDynamicAutocmd() - }) - ) - } - } - - /** - * Watch global variable, works on neovim only. - */ - public watchGlobal(key: string, callback?: (oldValue: any, newValue: any) => Thenable | void, disposables?: Disposable[]): void { - let { nvim } = this - nvim.call('coc#_watch', key, true) - let disposable = events.on('GlobalChange', async (changed: string, oldValue: any, newValue: any) => { - if (changed == key && callback) { - await Promise.resolve(callback(oldValue, newValue)) - } - }) - if (disposables) { - disposables.push( - Disposable.create(() => { - disposable.dispose() - nvim.call('coc#_unwatch', key, true) - }) - ) - } - } - - public get cwd(): string { - return this._cwd - } - - public get env(): Env { - return this._env - } - - public get root(): string { - return this._root || this.cwd - } - - public get rootPath(): string { - return this.root - } - - public get workspaceFolders(): WorkspaceFolder[] { - return this._workspaceFolders - } - - /** - * uri of current file, could be null - * - * @deprecated this method is reliable, will be removed in the feature. - */ - public get uri(): string { - let { bufnr } = this - if (bufnr) { - let document = this.getDocument(bufnr) - if (document && document.schema == 'file') { - return document.uri - } - } - return null - } - - public get workspaceFolder(): WorkspaceFolder { - let { rootPath } = this - if (rootPath == os.homedir()) return null - return { - uri: URI.file(rootPath).toString(), - name: path.basename(rootPath) - } - } - - public get textDocuments(): TextDocument[] { - let docs: TextDocument[] = [] - for (let b of this.buffers.values()) { - docs.push(b.textDocument) - } - return docs - } - - public get documents(): Document[] { - return Array.from(this.buffers.values()) - } - - public createNameSpace(name = ''): number { - if (this.namespaceMap.has(name)) return this.namespaceMap.get(name) - NAME_SPACE = NAME_SPACE + 1 - this.namespaceMap.set(name, NAME_SPACE) - return NAME_SPACE - } - - public get channelNames(): string[] { - return channels.names - } - - public get pluginRoot(): string { - return path.dirname(__dirname) - } - - public get isVim(): boolean { - return this._env.isVim - } - - public get isNvim(): boolean { - return !this._env.isVim - } - - public get completeOpt(): string { - return this._env.completeOpt - } - - public get initialized(): boolean { - return this._initialized - } - - public get ready(): Promise { - if (this._initialized) return Promise.resolve() - return new Promise(resolve => { - let disposable = this.onDidWorkspaceInitialized(() => { - disposable.dispose() - resolve() - }) - }) - } - - /** - * Current filetypes. - */ - public get filetypes(): Set { - let res = new Set() - for (let doc of this.documents) { - res.add(doc.filetype) - } - return res - } - - /** - * Check if selector match document. - */ - public match(selector: DocumentSelector, document: TextDocument): number { - return score(selector, document.uri, document.languageId) - } - - /** - * Findup for filename or filenames from current filepath or root. - */ - public async findUp(filename: string | string[]): Promise { - let { cwd } = this - let filepath = await this.nvim.call('expand', '%:p') as string - filepath = path.normalize(filepath) - let isFile = filepath && path.isAbsolute(filepath) - if (isFile && !isParentFolder(cwd, filepath, true)) { - // can't use cwd - return findUp(filename, path.dirname(filepath)) - } - let res = findUp(filename, cwd) - if (res && res != os.homedir()) return res - if (isFile) return findUp(filename, path.dirname(filepath)) - return null - } - - // eslint-disable-next-line @typescript-eslint/require-await - public async resolveRootFolder(uri: URI, patterns: string[]): Promise { - let { cwd } = this - if (uri.scheme != 'file') return cwd - let filepath = path.normalize(uri.fsPath) - let dir = path.dirname(filepath) - return resolveRoot(dir, patterns) || dir - } - - /** - * Create a FileSystemWatcher instance, - * doesn't fail when watchman not found. - */ - public createFileSystemWatcher(globPattern: string, ignoreCreate?: boolean, ignoreChange?: boolean, ignoreDelete?: boolean): FileSystemWatcher { - let watchmanPath = global.hasOwnProperty('__TEST__') ? null : this.getWatchmanPath() - let channel: OutputChannel = watchmanPath ? window.createOutputChannel('watchman') : null - let promise = watchmanPath ? Watchman.createClient(watchmanPath, this.root, channel) : Promise.resolve(null) - let watcher = new FileSystemWatcher( - promise, - globPattern, - !!ignoreCreate, - !!ignoreChange, - !!ignoreDelete - ) - return watcher - } - - public getWatchmanPath(): string | null { - const preferences = this.getConfiguration('coc.preferences') - let watchmanPath = preferences.get('watchmanPath', 'watchman') - try { - return which.sync(watchmanPath) - } catch (e) { - return null - } - } - - /** - * Get configuration by section and optional resource uri. - */ - public getConfiguration(section?: string, resource?: string): WorkspaceConfiguration { - return this.configurations.getConfiguration(section, resource) - } - - /** - * Get created document by uri or bufnr. - */ - public getDocument(uri: number | string): Document { - if (typeof uri === 'number') { - return this.buffers.get(uri) - } - const caseInsensitive = platform.isWindows || platform.isMacintosh - uri = URI.parse(uri).toString() - for (let doc of this.buffers.values()) { - if (!doc) continue - if (doc.uri === uri) return doc - if (path.resolve(doc.uri) === path.resolve(uri)) return doc - if (caseInsensitive && doc.uri.toLowerCase() === uri.toLowerCase()) return doc - } - return null - } - - /** - * Apply WorkspaceEdit. - */ - public async applyEdit(edit: WorkspaceEdit): Promise { - let { nvim } = this - let { documentChanges, changes } = edit - let [bufnr, cursor] = await nvim.eval('[bufnr("%"),coc#cursor#position()]') as [number, [number, number]] - let document = this.getDocument(bufnr) - let uri = document ? document.uri : null - let currEdits = null - let locations: Location[] = [] - let changeCount = 0 - const preferences = this.getConfiguration('coc.preferences') - let promptUser = !global.hasOwnProperty('__TEST__') && preferences.get('promptWorkspaceEdit', true) - let listTarget = preferences.get('listOfWorkspaceEdit', 'quickfix') - try { - if (documentChanges && documentChanges.length) { - let changedUris = this.getChangedUris(documentChanges) - changeCount = changedUris.length - if (promptUser) { - let diskCount = changedUris.reduce((p, c) => { - return p + (this.getDocument(c) == null ? 1 : 0) - }, 0) - if (diskCount) { - let res = await window.showPrompt(`${diskCount} documents on disk would be loaded for change, confirm?`) - if (!res) return - } - } - let changedMap: Map = new Map() - for (const change of documentChanges) { - if (TextDocumentEdit.is(change)) { - let { textDocument, edits } = change - let doc = await this.loadFile(textDocument.uri) - if (textDocument.uri == uri) currEdits = edits - await doc.applyEdits(edits) - for (let edit of edits) { - locations.push({ uri: doc.uri, range: edit.range }) - } - } else if (CreateFile.is(change)) { - let file = URI.parse(change.uri).fsPath - await this.createFile(file, change.options) - } else if (RenameFile.is(change)) { - changedMap.set(change.oldUri, change.newUri) - await this.renameFile(URI.parse(change.oldUri).fsPath, URI.parse(change.newUri).fsPath, change.options) - } else if (DeleteFile.is(change)) { - await this.deleteFile(URI.parse(change.uri).fsPath, change.options) - } - } - // fix location uris on renameFile - if (changedMap.size) { - locations.forEach(location => { - let newUri = changedMap.get(location.uri) - if (newUri) location.uri = newUri - }) - } - } else if (changes) { - let uris = Object.keys(changes) - let unloaded = uris.filter(uri => this.getDocument(uri) == null) - if (unloaded.length) { - if (promptUser) { - let res = await window.showPrompt(`${unloaded.length} documents on disk would be loaded for change, confirm?`) - if (!res) return - } - await this.loadFiles(unloaded) - } - for (let uri of Object.keys(changes)) { - let document = this.getDocument(uri) - if (URI.parse(uri).toString() == uri) currEdits = changes[uri] - let edits = changes[uri] - for (let edit of edits) { - locations.push({ uri: document.uri, range: edit.range }) - } - await document.applyEdits(edits) - } - changeCount = uris.length - } - if (currEdits) { - let changed = getChangedFromEdits({ line: cursor[0], character: cursor[1] }, currEdits) - if (changed) await window.moveTo({ - line: cursor[0] + changed.line, - character: cursor[1] + changed.character - }) - } - if (locations.length) { - let items = await Promise.all(locations.map(loc => this.getQuickfixItem(loc))) - let silent = locations.every(l => l.uri == uri) - if (listTarget == 'quickfix') { - await this.nvim.call('setqflist', [items]) - if (!silent) window.showMessage(`changed ${changeCount} buffers, use :wa to save changes to disk and :copen to open quickfix list`, 'more') - } else if (listTarget == 'location') { - await nvim.setVar('coc_jump_locations', items) - if (!silent) window.showMessage(`changed ${changeCount} buffers, use :wa to save changes to disk and :CocList location to manage changed locations`, 'more') - } - } - } catch (e) { - logger.error('Error on applyEdits:', edit, e) - window.showMessage(`Error on applyEdits: ${e.message}`, 'error') - return false - } - await wait(50) - return true - } - - /** - * Convert location to quickfix item. - */ - public async getQuickfixItem(loc: Location | LocationLink, text?: string, type = '', module?: string): Promise { - if (LocationLink.is(loc)) { - loc = Location.create(loc.targetUri, loc.targetRange) - } - let doc = this.getDocument(loc.uri) - let { uri, range } = loc - let { line, character } = range.start - let sl = range.start.line - let sc = range.start.character - let el = range.end.line - let ec = range.end.character - let u = URI.parse(uri) - let bufnr = doc ? doc.bufnr : -1 - if (!text && u.scheme == 'file') { - text = await this.getLine(uri, line) - character = byteIndex(text, character) - } - let item: QuickfixItem = { - uri, - filename: u.scheme == 'file' ? u.fsPath : uri, - lnum: sl + 1, - end_lnum: el + 1, - col: sc + 1, - end_col: ec + 1, - text: text || '', - range - } - if (module) item.module = module - if (type) item.type = type - if (bufnr != -1) item.bufnr = bufnr - return item - } - - /** - * Create persistence Mru instance. - */ - public createMru(name: string): Mru { - return new Mru(name) - } - - /** - * Get selected range for current document - */ - public async getSelectedRange(mode: string, document: Document): Promise { - let { nvim } = this - if (mode === 'line') { - let line = await nvim.call('line', ['.']) - let content = document.getline(line - 1) - if (!content.length) return null - return Range.create(line - 1, 0, line, 0) - } - if (mode === 'cursor') { - let [line, character] = await nvim.eval("coc#cursor#position()") as [number, number] - return Range.create(line, character, line, character) - } - if (!['v', 'V', 'char', 'line', '\x16'].includes(mode)) { - throw new Error(`Mode '${mode}' not supported`) - } - let isVisual = ['v', 'V', '\x16'].includes(mode) - let [, sl, sc] = await nvim.call('getpos', isVisual ? `'<` : `'[`) as [number, number, number] - let [, el, ec] = await nvim.call('getpos', isVisual ? `'>` : `']`) as [number, number, number] - let range = Range.create(document.getPosition(sl, sc), document.getPosition(el, ec)) - if (mode == 'v' || mode == '\x16') { - range.end.character = range.end.character + 1 - } - return range - } - - /** - * Visual select range of current document - */ - public async selectRange(range: Range): Promise { - let { nvim } = this - let { start, end } = range - let [bufnr, ve, selection] = await nvim.eval(`[bufnr('%'), &virtualedit, &selection]`) as [number, string, string] - let doc = this.getDocument(bufnr) - if (!doc || !doc.attached) return - let line = doc.getline(start.line) - let col = line ? byteLength(line.slice(0, start.character)) : 0 - let endLine = doc.getline(end.line) - let endCol = endLine ? byteLength(endLine.slice(0, end.character)) : 0 - let move_cmd = '' - let resetVirtualEdit = false - move_cmd += 'v' - endCol = await nvim.eval(`virtcol([${end.line + 1}, ${endCol}])`) as number - if (selection == 'inclusive') { - if (end.character == 0) { - move_cmd += `${end.line}G` - } else { - move_cmd += `${end.line + 1}G${endCol}|` - } - } else if (selection == 'old') { - move_cmd += `${end.line + 1}G${endCol}|` - } else { - move_cmd += `${end.line + 1}G${endCol + 1}|` - } - col = await nvim.eval(`virtcol([${start.line + 1}, ${col}])`) as number - move_cmd += `o${start.line + 1}G${col + 1}|o` - nvim.pauseNotification() - if (ve != 'onemore') { - resetVirtualEdit = true - nvim.setOption('virtualedit', 'onemore', true) - } - nvim.command(`noa call cursor(${start.line + 1},${col + (move_cmd == 'a' ? 0 : 1)})`, true) - // nvim.call('eval', [`feedkeys("${move_cmd}", 'in')`], true) - nvim.command(`normal! ${move_cmd}`, true) - if (resetVirtualEdit) nvim.setOption('virtualedit', ve, true) - if (this.isVim) nvim.command('redraw', true) - await nvim.resumeNotification() - } - - /** - * Populate locations to UI. - */ - public async showLocations(locations: Location[]): Promise { - let items = await Promise.all(locations.map(loc => this.getQuickfixItem(loc))) - let { nvim } = this - const preferences = this.getConfiguration('coc.preferences') - if (preferences.get('useQuickfixForLocations', false)) { - let openCommand = await nvim.getVar('coc_quickfix_open_command') as string - if (typeof openCommand != 'string') { - openCommand = items.length < 10 ? `copen ${items.length}` : 'copen' - } - nvim.pauseNotification() - nvim.call('setqflist', [items], true) - nvim.command(openCommand, true) - // eslint-disable-next-line @typescript-eslint/no-floating-promises - nvim.resumeNotification(false, true) - } else { - await nvim.setVar('coc_jump_locations', items) - if (this.env.locationlist) { - nvim.command('CocList --normal --auto-preview location', true) - } else { - nvim.call('coc#util#do_autocmd', ['CocLocationsChange'], true) - } - } - } - - /** - * Get content of line by uri and line. - */ - public async getLine(uri: string, line: number): Promise { - let document = this.getDocument(uri) - if (document) return document.getline(line) || '' - if (!uri.startsWith('file:')) return '' - let fsPath = URI.parse(uri).fsPath - if (!fs.existsSync(fsPath)) return '' - return await readFileLine(fsPath, line) - } - - /** - * Get WorkspaceFolder of uri - */ - public getWorkspaceFolder(uri: string): WorkspaceFolder | null { - this.workspaceFolders.sort((a, b) => b.uri.length - a.uri.length) - let filepath = URI.parse(uri).fsPath - return this.workspaceFolders.find(folder => isParentFolder(URI.parse(folder.uri).fsPath, filepath, true)) - } - - /** - * Get content from buffer of file by uri. - */ - public async readFile(uri: string): Promise { - let document = this.getDocument(uri) - if (document) { - await document.patchChange() - return document.content - } - let u = URI.parse(uri) - if (u.scheme != 'file') return '' - let lines = await this.nvim.call('readfile', [u.fsPath]) as string[] - return lines.join('\n') + '\n' - } - - /** - * Current document. - */ - public get document(): Promise { - return new Promise((resolve, reject) => { - this.nvim.buffer.then(buf => { - let bufnr = buf.id - this.bufnr = bufnr - if (this.buffers.has(bufnr)) { - resolve(this.buffers.get(bufnr)) - return - } - this.onBufCreate(bufnr).catch(reject) - let disposable = this.onDidOpenTextDocument(doc => { - disposable.dispose() - resolve(this.getDocument(doc.uri)) - }) - }, reject) - }) - } - - /** - * Get current document and position. - */ - public async getCurrentState(): Promise { - let document = await this.document - let position = await window.getCursorPosition() - return { - document: document.textDocument, - position - } - } - - /** - * Get format options - */ - public async getFormatOptions(uri?: string): Promise { - let doc: Document - if (uri) doc = this.getDocument(uri) - let bufnr = doc ? doc.bufnr : 0 - let [tabSize, insertSpaces] = await this.nvim.call('coc#util#get_format_opts', [bufnr]) as [number, number] - return { - tabSize, - insertSpaces: insertSpaces == 1 - } as FormattingOptions - } - - /** - * Jump to location. - */ - public async jumpTo(uri: string, position?: Position | null, openCommand?: string): Promise { - const preferences = this.getConfiguration('coc.preferences') - let jumpCommand = openCommand || preferences.get('jumpCommand', 'edit') - let { nvim } = this - let doc = this.getDocument(uri) - let bufnr = doc ? doc.bufnr : -1 - if (bufnr != -1 && jumpCommand == 'edit') { - // use buffer command since edit command would reload the buffer - nvim.pauseNotification() - nvim.command(`silent! normal! m'`, true) - nvim.command(`buffer ${bufnr}`, true) - if (position) { - let line = doc.getline(position.line) - let col = byteLength(line.slice(0, position.character)) + 1 - nvim.call('cursor', [position.line + 1, col], true) - } - if (this.isVim) nvim.command('redraw', true) - await nvim.resumeNotification() - } else { - let { fsPath, scheme } = URI.parse(uri) - let pos = position == null ? null : [position.line, position.character] - if (scheme == 'file') { - let bufname = fixDriver(path.normalize(fsPath)) - await this.nvim.call('coc#util#jump', [jumpCommand, bufname, pos]) - } else { - if (os.platform() == 'win32') { - uri = uri.replace(/\/?/, '?') - } - await this.nvim.call('coc#util#jump', [jumpCommand, uri, pos]) - } - } - } - - /** - * Create a file in vim and disk - */ - public async createFile(filepath: string, opts: CreateFileOptions = {}): Promise { - let stat = await statAsync(filepath) - if (stat && !opts.overwrite && !opts.ignoreIfExists) { - window.showMessage(`${filepath} already exists!`, 'error') - return - } - if (!stat || opts.overwrite) { - // directory - if (filepath.endsWith('/')) { - try { - filepath = this.expand(filepath) - await fs.mkdirp(filepath) - } catch (e) { - window.showMessage(`Can't create ${filepath}: ${e.message}`, 'error') - } - } else { - let uri = URI.file(filepath).toString() - let doc = this.getDocument(uri) - if (doc) return - if (!fs.existsSync(path.dirname(filepath))) { - fs.mkdirpSync(path.dirname(filepath)) - } - fs.writeFileSync(filepath, '', 'utf8') - await this.loadFile(uri) - } - } - } - - /** - * Load uri as document. - */ - public async loadFile(uri: string): Promise { - let doc = this.getDocument(uri) - if (doc) return doc - let { nvim } = this - let filepath = uri.startsWith('file') ? URI.parse(uri).fsPath : uri - nvim.call('coc#util#open_files', [[filepath]], true) - return await new Promise((resolve, reject) => { - let disposable = this.onDidOpenTextDocument(textDocument => { - let fsPath = URI.parse(textDocument.uri).fsPath - if (textDocument.uri == uri || fsPath == filepath) { - clearTimeout(timer) - disposable.dispose() - resolve(this.getDocument(uri)) - } - }) - let timer = setTimeout(() => { - disposable.dispose() - reject(new Error(`Create document ${uri} timeout after 1s.`)) - }, 1000) - }) - } - - /** - * Load the files that not loaded - */ - public async loadFiles(uris: string[]): Promise { - uris = uris.filter(uri => this.getDocument(uri) == null) - if (!uris.length) return - let bufnrs = await this.nvim.call('coc#util#open_files', [uris.map(u => URI.parse(u).fsPath)]) as number[] - let create = bufnrs.filter(bufnr => this.getDocument(bufnr) == null) - if (!create.length) return - return new Promise((resolve, reject) => { - let timer = setTimeout(() => { - disposable.dispose() - reject(new Error(`Create document timeout after 2s.`)) - }, 2000) - let disposable = this.onDidOpenTextDocument(() => { - if (uris.every(uri => this.getDocument(uri) != null)) { - clearTimeout(timer) - disposable.dispose() - resolve() - } - }) - }) - } - - /** - * Rename file in vim and disk - */ - public async renameFile(oldPath: string, newPath: string, opts: RenameFileOptions = {}): Promise { - let { overwrite, ignoreIfExists } = opts - let { nvim } = this - try { - let stat = await statAsync(newPath) - if (stat && !overwrite && !ignoreIfExists) { - throw new Error(`${newPath} already exists`) - } - if (!stat || overwrite) { - let uri = URI.file(oldPath).toString() - let newUri = URI.file(newPath).toString() - let doc = this.getDocument(uri) - if (doc != null) { - let isCurrent = doc.bufnr == this.bufnr - let newDoc = this.getDocument(newUri) - if (newDoc) await this.nvim.command(`silent ${newDoc.bufnr}bwipeout!`) - let content = doc.getDocumentContent() - await fs.writeFile(newPath, content, 'utf8') - // open renamed file - if (!isCurrent) { - await nvim.call('coc#util#open_files', [[newPath]]) - await nvim.command(`silent ${doc.bufnr}bwipeout!`) - } else { - let view = await nvim.call('winsaveview') - nvim.pauseNotification() - nvim.call('coc#util#open_file', ['keepalt edit', newPath], true) - nvim.command(`silent ${doc.bufnr}bwipeout!`, true) - nvim.call('winrestview', [view], true) - await nvim.resumeNotification() - } - // avoid vim detect file unlink - await fs.unlink(oldPath) - } else { - await renameAsync(oldPath, newPath) - } - } - } catch (e) { - window.showMessage(`Rename error: ${e.message}`, 'error') - } - } - - /** - * Delete file from vim and disk. - */ - public async deleteFile(filepath: string, opts: DeleteFileOptions = {}): Promise { - let { ignoreIfNotExists, recursive } = opts - let stat = await statAsync(filepath.replace(/\/$/, '')) - let isDir = stat && stat.isDirectory() - if (filepath.endsWith('/') && !isDir) { - window.showMessage(`${filepath} is not directory`, 'error') - return - } - if (!stat && !ignoreIfNotExists) { - window.showMessage(`${filepath} not exists`, 'error') - return - } - if (stat == null) return - if (isDir && !recursive) { - window.showMessage(`Can't remove directory, recursive not set`, 'error') - return - } - try { - if (isDir && recursive) { - await fs.remove(filepath) - } else if (isDir) { - await fs.rmdir(filepath) - } else { - await fs.unlink(filepath) - } - if (!isDir) { - let uri = URI.file(filepath).toString() - let doc = this.getDocument(uri) - if (doc) await this.nvim.command(`silent! bwipeout! ${doc.bufnr}`) - } - } catch (e) { - window.showMessage(`Error on delete ${filepath}: ${e.message}`, 'error') - } - } - - /** - * Open resource by uri - */ - public async openResource(uri: string): Promise { - let { nvim } = this - // not supported - if (uri.startsWith('http')) { - await nvim.call('coc#util#open_url', uri) - return - } - let wildignore = await nvim.getOption('wildignore') - await nvim.setOption('wildignore', '') - await this.jumpTo(uri) - await nvim.setOption('wildignore', wildignore) - } - - /** - * Resolve module from yarn or npm. - */ - public async resolveModule(name: string): Promise { - return await this.resolver.resolveModule(name) - } - - /** - * Run nodejs command - */ - public async runCommand(cmd: string, cwd?: string, timeout?: number): Promise { - cwd = cwd || this.cwd - return runCommand(cmd, { cwd }, timeout) - } - - /** - * Expand filepath with `~` and/or environment placeholders - */ - public expand(filepath: string): string { - if (!filepath) return filepath - if (filepath.startsWith('~')) { - filepath = os.homedir() + filepath.slice(1) - } - if (filepath.includes('$')) { - let doc = this.getDocument(this.bufnr) - let fsPath = doc ? URI.parse(doc.uri).fsPath : '' - filepath = filepath.replace(/\$\{(.*?)\}/g, (match: string, name: string) => { - if (name.startsWith('env:')) { - let key = name.split(':')[1] - let val = key ? process.env[key] : '' - return val - } - switch (name) { - case 'workspace': - case 'workspaceRoot': - case 'workspaceFolder': - return this.root - case 'workspaceFolderBasename': - return path.dirname(this.root) - case 'cwd': - return this.cwd - case 'file': - return fsPath - case 'fileDirname': - return fsPath ? path.dirname(fsPath) : '' - case 'fileExtname': - return fsPath ? path.extname(fsPath) : '' - case 'fileBasename': - return fsPath ? path.basename(fsPath) : '' - case 'fileBasenameNoExtension': { - let basename = fsPath ? path.basename(fsPath) : '' - return basename ? basename.slice(0, basename.length - path.extname(basename).length) : '' - } - default: - return match - } - }) - filepath = filepath.replace(/\$[\w]+/g, match => { - if (match == '$HOME') return os.homedir() - return process.env[match.slice(1)] || match - }) - } - return filepath - } - - public async createTerminal(opts: TerminalOptions): Promise { - let cmd = opts.shellPath - let args = opts.shellArgs - if (!cmd) cmd = await this.nvim.getOption('shell') as string - let terminal = new TerminalModel(cmd, args || [], this.nvim, opts.name) - await terminal.start(opts.cwd || this.cwd, opts.env) - this.terminals.set(terminal.bufnr, terminal) - this._onDidOpenTerminal.fire(terminal) - return terminal - } - - public async callAsync(method: string, args: any[]): Promise { - if (this.isNvim) return await this.nvim.call(method, args) - return await this.nvim.callAsync('coc#util#with_callback', [method, args]) - } - - /** - * registerTextDocumentContentProvider - */ - public registerTextDocumentContentProvider(scheme: string, provider: TextDocumentContentProvider): Disposable { - this.schemeProviderMap.set(scheme, provider) - this.setupDynamicAutocmd() - let disposables: Disposable[] = [] - if (provider.onDidChange) { - provider.onDidChange(async uri => { - let doc = this.getDocument(uri.toString()) - if (doc) { - let { buffer } = doc - let tokenSource = new CancellationTokenSource() - let content = await Promise.resolve(provider.provideTextDocumentContent(uri, tokenSource.token)) - await buffer.setLines(content.split(/\r?\n/), { - start: 0, - end: -1, - strictIndexing: false - }) - } - }, null, disposables) - } - return Disposable.create(() => { - this.schemeProviderMap.delete(scheme) - disposeAll(disposables) - this.setupDynamicAutocmd() - }) - } - - /** - * Register unique keymap uses `(coc-{key})` as lhs - * Throw error when {key} already exists. - * - * @param {MapMode[]} modes - array of 'n' | 'i' | 'v' | 'x' | 's' | 'o' - * @param {string} key - unique name - * @param {Function} fn - callback function - * @param {Partial} opts - * @returns {Disposable} - */ - public registerKeymap(modes: MapMode[], key: string, fn: Function, opts: Partial = {}): Disposable { - if (!key) throw new Error(`Invalid key ${key} of registerKeymap`) - if (this.keymaps.has(key)) throw new Error(`${key} already exists.`) - opts = Object.assign({ sync: true, cancel: true, silent: true, repeat: false }, opts) - let { nvim } = this - this.keymaps.set(key, [fn, !!opts.repeat]) - let method = opts.sync ? 'request' : 'notify' - let silent = opts.silent ? '' : '' - for (let m of modes) { - if (m == 'i') { - nvim.command(`inoremap ${silent} (coc-${key}) coc#_insert_key('${method}', '${key}', ${opts.cancel ? 1 : 0})`, true) - } else { - let modify = getKeymapModifier(m) - nvim.command(`${m}noremap ${silent} (coc-${key}) :${modify}call coc#rpc#${method}('doKeymap', ['${key}'])`, true) - } - } - return Disposable.create(() => { - this.keymaps.delete(key) - for (let m of modes) { - nvim.command(`${m}unmap (coc-${key})`, true) - } - }) - } - - /** - * Register expr keymap. - */ - public registerExprKeymap(mode: 'i' | 'n' | 'v' | 's' | 'x', key: string, fn: Function, buffer = false): Disposable { - if (!key) return - let id = `${mode}${global.Buffer.from(key).toString('base64')}${buffer ? '1' : '0'}` - let { nvim } = this - this.keymaps.set(id, [fn, false]) - if (mode == 'i') { - nvim.command(`inoremap ${buffer ? '' : ''} ${key} coc#_insert_key('request', '${id}')`, true) - } else { - nvim.command(`${mode}noremap ${buffer ? '' : ''} ${key} coc#rpc#request('doKeymap', ['${id}'])`, true) - } - return Disposable.create(() => { - this.keymaps.delete(id) - nvim.command(`${mode}unmap ${buffer ? '' : ''} ${key}`, true) - }) - } - - public registerLocalKeymap(mode: 'n' | 'v' | 's' | 'x', key: string, fn: Function, notify = false): Disposable { - let id = uuid() - let { nvim, bufnr } = this - this.keymaps.set(id, [fn, false]) - let method = notify ? 'notify' : 'request' - let modify = getKeymapModifier(mode) - // neoivm's bug '<' can't be used. - let escaped = key.startsWith('<') && key.endsWith('>') ? `{${key.slice(1, -1)}}` : key - if (this.isNvim && !global.hasOwnProperty('__TEST__')) { - nvim.call('nvim_buf_set_keymap', [0, mode, key, `:${modify}call coc#rpc#${method}('doKeymap', ['${id}', '', '${escaped}'])`, { - silent: true, - nowait: true - }], true) - } else { - let cmd = `${mode}noremap ${key} :${modify}call coc#rpc#${method}('doKeymap', ['${id}', '', '${escaped}'])` - nvim.command(cmd, true) - } - return Disposable.create(() => { - this.keymaps.delete(id) - nvim.call('coc#compat#buf_del_keymap', [bufnr, mode, key], true) - }) - } - - /** - * Create DB instance at extension root. - */ - public createDatabase(name: string): DB { - let root: string - if (global.hasOwnProperty('__TEST__')) { - root = path.join(os.tmpdir(), `coc-${process.pid}`) - fs.mkdirpSync(root) - } else { - root = path.dirname(this.env.extensionRoot) - } - let filepath = path.join(root, name + '.json') - return new DB(filepath) - } - - /** - * Create Task instance that runs in vim. - */ - public createTask(id: string): Task { - return new Task(this.nvim, id) - } - - public registerBufferSync(create: (doc: Document) => T | undefined): BufferSync { - return new BufferSync(create, this) - } - - public setupDynamicAutocmd(initialize = false): void { - if (!initialize && !this._dynAutocmd) return - this._dynAutocmd = true - let schemes = this.schemeProviderMap.keys() - let cmds: string[] = [] - for (let scheme of schemes) { - cmds.push(`autocmd BufReadCmd,FileReadCmd,SourceCmd ${scheme}:/* call coc#rpc#request('CocAutocmd', ['BufReadCmd','${scheme}', expand('')])`) - } - for (let [id, autocmd] of this.autocmds.entries()) { - let args = autocmd.arglist && autocmd.arglist.length ? ', ' + autocmd.arglist.join(', ') : '' - let event = Array.isArray(autocmd.event) ? autocmd.event.join(',') : autocmd.event - let pattern = autocmd.pattern != null ? autocmd.pattern : '*' - if (/\buser\b/i.test(event)) { - pattern = '' - } - cmds.push(`autocmd ${event} ${pattern} call coc#rpc#${autocmd.request ? 'request' : 'notify'}('doAutocmd', [${id}${args}])`) - } - for (let key of this.watchedOptions) { - cmds.push(`autocmd OptionSet ${key} call coc#rpc#notify('OptionSet',[expand(''), v:option_old, v:option_new])`) - } - let content = ` -augroup coc_dynamic_autocmd - autocmd! - ${cmds.join('\n ')} -augroup end` - try { - let dir = path.join(process.env.TMPDIR || os.tmpdir(), `coc.nvim-${process.pid}`) - if (!fs.existsSync(dir)) fs.mkdirpSync(dir) - let filepath = path.join(dir, `coc-${process.pid}.vim`) - fs.writeFileSync(filepath, content, 'utf8') - let cmd = `source ${filepath}` - if (this.env.isCygwin && platform.isWindows) { - cmd = `execute "source" . substitute(system('cygpath ${filepath.replace(/\\/g, '/')}'), '\\n', '', 'g')` - } - this.nvim.command(cmd).logError() - } catch (e) { - window.showMessage(`Can't create tmp file: ${e.message}`, 'error') - } - } - - private async onBufReadCmd(scheme: string, uri: string): Promise { - let provider = this.schemeProviderMap.get(scheme) - if (!provider) { - window.showMessage(`Provider for ${scheme} not found`, 'error') - return - } - let tokenSource = new CancellationTokenSource() - let content = await Promise.resolve(provider.provideTextDocumentContent(URI.parse(uri), tokenSource.token)) - let buf = await this.nvim.buffer - await buf.setLines(content.split(/\r?\n/), { - start: 0, - end: -1, - strictIndexing: false - }) - setTimeout(async () => { - await events.fire('BufCreate', [buf.id]) - }, 30) - } - - public async attach(): Promise { - if (this._attached) return - this._attached = true - let [bufs, bufnr, winid] = await this.nvim.eval(`[map(getbufinfo({'bufloaded': 1}),'v:val["bufnr"]'),bufnr('%'),win_getid()]`) as [number[], number, number] - this.bufnr = bufnr - await Promise.all(bufs.map(buf => this.onBufCreate(buf))) - if (!this._initialized) { - this._onDidWorkspaceInitialized.fire(void 0) - this._initialized = true - } - await events.fire('BufEnter', [bufnr]) - await events.fire('BufWinEnter', [bufnr, winid]) - } - - // count of document need change - private getChangedUris(documentChanges: DocumentChange[] | null): string[] { - let uris: Set = new Set() - let createUris: Set = new Set() - for (let change of documentChanges) { - if (TextDocumentEdit.is(change)) { - let { textDocument } = change - let { uri, version } = textDocument - uris.add(uri) - if (version != null && version > 0) { - let doc = this.getDocument(uri) - if (!doc) { - throw new Error(`${uri} not loaded`) - } - if (doc.version != version) { - throw new Error(`${uri} changed before apply edit`) - } - } - } else if (CreateFile.is(change) || DeleteFile.is(change)) { - if (!isFile(change.uri)) { - throw new Error(`change of scheme ${change.uri} not supported`) - } - createUris.add(change.uri) - uris.add(change.uri) - } else if (RenameFile.is(change)) { - if (!isFile(change.oldUri) || !isFile(change.newUri)) { - throw new Error(`change of scheme ${change.oldUri} not supported`) - } - let newFile = URI.parse(change.newUri).fsPath - if (fs.existsSync(newFile)) { - throw new Error(`file "${newFile}" already exists for rename`) - } - uris.add(change.oldUri) - } else { - throw new Error(`Invalid document change: ${JSON.stringify(change, null, 2)}`) - } - } - return Array.from(uris) - } - - private createConfigurations(): Configurations { - let home = path.normalize(process.env.COC_VIMCONFIG) || path.join(os.homedir(), '.vim') - let userConfigFile = path.join(home, CONFIG_FILE_NAME) - return new Configurations(userConfigFile, new ConfigurationShape(this)) - } - - // events for sync buffer of vim - private attachChangedEvents(): void { - if (this.isVim) { - const onChange = (bufnr: number) => { - let doc = this.getDocument(bufnr) - if (doc && doc.attached) doc.fetchContent() - } - events.on('TextChangedP', onChange, null, this.disposables) - events.on('TextChangedI', onChange, null, this.disposables) - events.on('TextChanged', onChange, null, this.disposables) - } - } - - private async onBufCreate(buf: number | Buffer): Promise { - let buffer = typeof buf === 'number' ? this.nvim.createBuffer(buf) : buf - let bufnr = buffer.id - if (this.creatingSources.has(bufnr)) return - let document = this.getDocument(bufnr) - let source = new CancellationTokenSource() - try { - if (document) this.onBufUnload(bufnr, true) - document = new Document(buffer, this._env, this.maxFileSize) - let token = source.token - this.creatingSources.set(bufnr, source) - let created = await document.init(this.nvim, token) - if (!created) document = null - } catch (e) { - logger.error('Error on create buffer:', e) - document = null - } - if (this.creatingSources.get(bufnr) == source) { - source.dispose() - this.creatingSources.delete(bufnr) - } - if (!document || !document.textDocument) return - this.buffers.set(bufnr, document) - if (document.attached) { - document.onDocumentDetach(bufnr => { - let doc = this.getDocument(bufnr) - if (doc) this.onBufUnload(doc.bufnr) - }) - } - if (document.buftype == '' && document.schema == 'file') { - this.configurations.checkFolderConfiguration(document.uri) - let config = this.getConfiguration('workspace') - let filetypes = config.get('ignoredFiletypes', []) - if (!filetypes.includes(document.filetype)) { - let root = this.resolveRoot(document) - if (root) { - this.addWorkspaceFolder(root) - if (this.bufnr == buffer.id) { - this._root = root - } - } - } - } - if (document.enabled) { - let textDocument: TextDocument & { bufnr: number } = Object.assign(document.textDocument, { bufnr }) - this._onDidOpenDocument.fire(textDocument) - document.onDocumentChange(e => this._onDidChangeDocument.fire(e)) - } - logger.debug('buffer created', buffer.id) - } - - private onBufEnter(bufnr: number): void { - this.bufnr = bufnr - let doc = this.getDocument(bufnr) - if (doc) { - this.configurations.setFolderConfiguration(doc.uri) - let workspaceFolder = this.getWorkspaceFolder(doc.uri) - if (workspaceFolder) this._root = URI.parse(workspaceFolder.uri).fsPath - } - } - - private async checkCurrentBuffer(bufnr: number): Promise { - this.bufnr = bufnr - await this.checkBuffer(bufnr) - } - - private onBufWritePost(bufnr: number): void { - let doc = this.buffers.get(bufnr) - if (!doc) return - this._onDidSaveDocument.fire(doc.textDocument) - } - - private onBufUnload(bufnr: number, recreate = false): void { - logger.debug('buffer unload', bufnr) - if (!recreate) { - let source = this.creatingSources.get(bufnr) - if (source) { - source.cancel() - this.creatingSources.delete(bufnr) - } - } - if (this.terminals.has(bufnr)) { - let terminal = this.terminals.get(bufnr) - this._onDidCloseTerminal.fire(terminal) - this.terminals.delete(bufnr) - } - let doc = this.buffers.get(bufnr) - if (doc) { - let textDocument: TextDocument & { bufnr: number } = Object.assign(doc.textDocument, { bufnr }) - this._onDidCloseDocument.fire(textDocument) - this.buffers.delete(bufnr) - doc.detach() - } - } - - private async onBufWritePre(bufnr: number): Promise { - let doc = this.buffers.get(bufnr) - if (!doc || !doc.attached) return - await doc.synchronize() - let firing = true - let thenables: Thenable[] = [] - let event: TextDocumentWillSaveEvent = { - document: doc.textDocument, - reason: TextDocumentSaveReason.Manual, - waitUntil: (thenable: Thenable) => { - if (!firing) { - logger.error(`Can't call waitUntil in async manner:`, Error().stack) - window.showMessage(`waitUntil can't be used in async manner, check log for details`, 'error') - } else { - thenables.push(thenable) - } - } - } - this._onWillSaveDocument.fire(event) - firing = false - let total = thenables.length - if (total) { - let promise = new Promise(resolve => { - const preferences = this.getConfiguration('coc.preferences') - const willSaveHandlerTimeout = preferences.get('willSaveHandlerTimeout', 500) - let timer = setTimeout(() => { - window.showMessage(`Will save handler timeout after ${willSaveHandlerTimeout}ms`, 'warning') - resolve(undefined) - }, willSaveHandlerTimeout) - let i = 0 - let called = false - for (let p of thenables) { - let cb = (res: any) => { - if (called) return - called = true - clearTimeout(timer) - resolve(res) - } - p.then(res => { - if (Array.isArray(res) && res.length && TextEdit.is(res[0])) { - return cb(res) - } - i = i + 1 - if (i == total) cb(undefined) - }, () => { - i = i + 1 - if (i == total) cb(undefined) - }) - } - }) - let edits = await promise - if (edits) await doc.applyEdits(edits) - } - } - - private onDirChanged(cwd: string): void { - if (cwd == this._cwd) return - this._cwd = cwd - } - - private onFileTypeChange(filetype: string, bufnr: number): void { - let doc = this.getDocument(bufnr) - if (!doc) return - let converted = doc.convertFiletype(filetype) - if (converted == doc.filetype) return - let textDocument: TextDocument & { bufnr: number } = Object.assign(doc.textDocument, { bufnr }) - this._onDidCloseDocument.fire(textDocument) - doc.setFiletype(filetype) - this._onDidOpenDocument.fire(Object.assign(doc.textDocument, { bufnr })) - } - - private async checkBuffer(bufnr: number): Promise { - if (this._disposed || !bufnr) return - let doc = this.getDocument(bufnr) - if (!doc && !this.creatingSources.has(bufnr)) await this.onBufCreate(bufnr) - } - - private resolveRoot(document: Document): string { - let types = [PatternType.Buffer, PatternType.LanguageServer, PatternType.Global] - let u = URI.parse(document.uri) - let dir = path.dirname(u.fsPath) - let { cwd } = this - let config = this.getConfiguration('workspace') - let bottomUpFileTypes = config.get('bottomUpFiletypes', []) - let checkCwd = config.get('workspaceFolderCheckCwd', true) - for (let patternType of types) { - let patterns = this.getRootPatterns(document, patternType) - if (patterns && patterns.length) { - let isBottomUp = bottomUpFileTypes.includes(document.filetype) - let root = resolveRoot(dir, patterns, cwd, isBottomUp, checkCwd) - if (root) return root - } - } - if (this.cwd != os.homedir() && isParentFolder(this.cwd, dir, true)) return this.cwd - return null - } - - public getRootPatterns(document: Document, patternType: PatternType): string[] { - let { uri } = document - if (patternType == PatternType.Buffer) return document.getVar('root_patterns', []) || [] - if (patternType == PatternType.LanguageServer) return this.getServerRootPatterns(document.filetype) - const preferences = this.getConfiguration('coc.preferences', uri) - return preferences.get('rootPatterns', ['.git', '.hg', '.projections.json']).slice() - } - - public async renameCurrent(): Promise { - let { nvim } = this - let bufnr = await nvim.call('bufnr', '%') - let cwd = await nvim.call('getcwd') - let doc = this.getDocument(bufnr) - if (!doc || doc.buftype != '' || doc.schema != 'file') { - nvim.errWriteLine('current buffer is not file.') - return - } - let oldPath = URI.parse(doc.uri).fsPath - // await nvim.callAsync() - let newPath = await nvim.callAsync('coc#util#with_callback', ['input', ['New path: ', oldPath, 'file']]) - newPath = newPath ? newPath.trim() : null - if (newPath == oldPath || !newPath) return - let lines = await doc.buffer.lines - let exists = fs.existsSync(oldPath) - if (exists) { - let modified = await nvim.eval('&modified') - if (modified) await nvim.command('noa w') - if (oldPath.toLowerCase() != newPath.toLowerCase() && fs.existsSync(newPath)) { - let overwrite = await window.showPrompt(`${newPath} exists, overwrite?`) - if (!overwrite) return - fs.unlinkSync(newPath) - } - fs.renameSync(oldPath, newPath) - } - this._onWillRenameFiles.fire({ - files: [{ newUri: URI.parse(newPath), oldUri: URI.parse(oldPath) }], - waitUntil: async thenable => { - const edit = await Promise.resolve(thenable) - if (edit && WorkspaceEdit.is(edit)) { - await this.applyEdit(edit) - } - } - }) - this._onDidRenameFiles.fire({ - files: [{ newUri: URI.parse(newPath), oldUri: URI.parse(oldPath) }], - }) - let filepath = isParentFolder(cwd, newPath) ? path.relative(cwd, newPath) : newPath - let view = await nvim.call('winsaveview') - nvim.pauseNotification() - if (oldPath.toLowerCase() == newPath.toLowerCase()) { - nvim.command(`keepalt ${bufnr}bwipeout!`, true) - nvim.call('coc#util#open_file', ['keepalt edit', filepath], true) - } else { - nvim.call('coc#util#open_file', ['keepalt edit', filepath], true) - nvim.command(`${bufnr}bwipeout!`, true) - } - if (!exists && lines.join('\n') != '\n') { - nvim.call('append', [0, lines], true) - nvim.command('normal! Gdd', true) - } - nvim.call('winrestview', [view], true) - await nvim.resumeNotification() - } - - public get folderPaths(): string[] { - return this.workspaceFolders.map(f => URI.parse(f.uri).fsPath) - } - - public get floatSupported(): boolean { - let { env } = this - return env.floating || env.textprop - } - - public removeWorkspaceFolder(fsPath: string): void { - let idx = this._workspaceFolders.findIndex(f => URI.parse(f.uri).fsPath == fsPath) - if (idx != -1) { - let folder = this._workspaceFolders[idx] - this._workspaceFolders.splice(idx, 1) - this._onDidChangeWorkspaceFolders.fire({ - removed: [folder], - added: [] - }) - } - } - - public renameWorkspaceFolder(oldPath: string, newPath: string): void { - let idx = this._workspaceFolders.findIndex(f => URI.parse(f.uri).fsPath == oldPath) - if (idx == -1) return - let removed = this._workspaceFolders[idx] - let added: WorkspaceFolder = { - uri: URI.file(newPath).toString(), - name: path.dirname(newPath) - } - this._workspaceFolders.splice(idx, 1) - this._workspaceFolders.push(added) - this._onDidChangeWorkspaceFolders.fire({ - removed: [removed], - added: [added] - }) - } - - public addRootPattern(filetype: string, rootPatterns: string[]): void { - let patterns = this.rootPatterns.get(filetype) || [] - for (let p of rootPatterns) { - if (!patterns.includes(p)) { - patterns.push(p) - } - } - this.rootPatterns.set(filetype, patterns) - } - - public get insertMode(): boolean { - return this._insertMode - } - - public async detach(): Promise { - if (!this._attached) return - this._attached = false - channels.dispose() - for (let bufnr of this.buffers.keys()) { - await events.fire('BufUnload', [bufnr]) - } - } - - public dispose(): void { - this._disposed = true - for (let doc of this.documents) { - doc.detach() - } - disposeAll(this.disposables) - Watchman.dispose() - this.configurations.dispose() - this.buffers.clear() - } - - private addWorkspaceFolder(rootPath: string): WorkspaceFolder { - if (rootPath == os.homedir()) return - let { _workspaceFolders } = this - let uri = URI.file(rootPath).toString() - let workspaceFolder: WorkspaceFolder = { uri, name: path.basename(rootPath) } - if (_workspaceFolders.findIndex(o => o.uri == uri) == -1) { - _workspaceFolders.push(workspaceFolder) - if (this._initialized) { - this._onDidChangeWorkspaceFolders.fire({ - added: [workspaceFolder], - removed: [] - }) - } - } - return workspaceFolder - } - - private getServerRootPatterns(filetype: string): string[] { - let lspConfig = this.getConfiguration().get<{ [key: string]: unknown }>('languageserver', {}) - let patterns: string[] = [] - for (let key of Object.keys(lspConfig)) { - let config: any = lspConfig[key] - let { filetypes, rootPatterns } = config - if (Array.isArray(filetypes) && rootPatterns && filetypes.includes(filetype)) { - patterns.push(...rootPatterns) - } - } - patterns = patterns.concat(this.rootPatterns.get(filetype) || []) - return patterns.length ? distinct(patterns) : null - } -} - -export default new Workspace() diff --git a/vim-config/plugins/coc.nvim/tsconfig.json b/vim-config/plugins/coc.nvim/tsconfig.json deleted file mode 100644 index a73b1415..00000000 --- a/vim-config/plugins/coc.nvim/tsconfig.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "compilerOptions": { - "outDir": "lib", - "noEmit": true, - "sourceMap": true, - "importHelpers": true, - "allowUnreachableCode": false, - "forceConsistentCasingInFileNames": true, - "noImplicitAny": false, - "noImplicitThis": true, - "noUnusedLocals": false, - "noUnusedParameters": false, - "strictPropertyInitialization": false, - "target": "es2017", - "module": "commonjs", - "moduleResolution": "node", - "experimentalDecorators": true, - "lib": ["es2017", "es2018", "es2019"], - "declaration": false, - "resolveJsonModule": true, - "esModuleInterop": true, - "strictNullChecks": false, - "strictFunctionTypes": false, - "plugins": [] - }, - "include": ["src"], - "exclude": ["typings", "build", "node_modules"] -} diff --git a/vim-config/plugins/coc.nvim/typings/LICENSE b/vim-config/plugins/coc.nvim/typings/LICENSE deleted file mode 100644 index fc9556c9..00000000 --- a/vim-config/plugins/coc.nvim/typings/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright 2020 chemzqm@gmail.com - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vim-config/plugins/coc.nvim/typings/Readme.md b/vim-config/plugins/coc.nvim/typings/Readme.md deleted file mode 100644 index b3ebe4eb..00000000 --- a/vim-config/plugins/coc.nvim/typings/Readme.md +++ /dev/null @@ -1,18 +0,0 @@ -This package contains typings of coc.nvim only. - -Files were exported from https://github.com/neoclide/coc.nvim/blob/master/typings - -## Installation - - npm install --save-dev coc.nvim - -## Support coc.nvim - -If you like my work, consider supporting me on Patreon or PayPal: - -Patreon donate button -PayPal donate button - -## Credits - -[Visual Studio Code](https://github.com/microsoft/vscode), and [Microsoft](https://github.com/microsoft) diff --git a/vim-config/plugins/coc.nvim/typings/index.d.ts b/vim-config/plugins/coc.nvim/typings/index.d.ts deleted file mode 100644 index 261c6c4d..00000000 --- a/vim-config/plugins/coc.nvim/typings/index.d.ts +++ /dev/null @@ -1,8794 +0,0 @@ -// vim: set sw=2 ts=2 sts=2 et foldmarker={{,}} foldmethod=marker foldlevel=0 nofen: -/****************************************************************** -MIT License http://www.opensource.org/licenses/mit-license.php -Author Qiming Zhao (https://github.com/chemzqm) -*******************************************************************/ - -/// -import cp from 'child_process' - -declare module 'coc.nvim' { - // Language server protocol interfaces {{ - export interface Thenable { - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Thenable - // eslint-disable-next-line @typescript-eslint/unified-signatures - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => void): Thenable - } - - export interface Disposable { - /** - * Dispose this object. - */ - dispose(): void - } - - export namespace Disposable { - function create(func: () => void): Disposable - } - /** - * The declaration of a symbol representation as one or many [locations](#Location). - */ - export type Declaration = Location | Location[] - /** - * Information about where a symbol is declared. - * - * Provides additional metadata over normal [location](#Location) declarations, including the range of - * the declaring symbol. - * - * Servers should prefer returning `DeclarationLink` over `Declaration` if supported - * by the client. - */ - export type DeclarationLink = LocationLink - - export type ProgressToken = number | string - - export interface WorkDoneProgressBegin { - kind: 'begin' - /** - * Mandatory title of the progress operation. Used to briefly inform about - * the kind of operation being performed. - * - * Examples: "Indexing" or "Linking dependencies". - */ - title: string - /** - * Controls if a cancel button should show to allow the user to cancel the - * long running operation. Clients that don't support cancellation are allowed - * to ignore the setting. - */ - cancellable?: boolean - /** - * Optional, more detailed associated progress message. Contains - * complementary information to the `title`. - * - * Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". - * If unset, the previous progress message (if any) is still valid. - */ - message?: string - /** - * Optional progress percentage to display (value 100 is considered 100%). - * If not provided infinite progress is assumed and clients are allowed - * to ignore the `percentage` value in subsequent in report notifications. - * - * The value should be steadily rising. Clients are free to ignore values - * that are not following this rule. - */ - percentage?: number - } - - export interface WorkDoneProgressReport { - kind: 'report' - /** - * Controls enablement state of a cancel button. This property is only valid if a cancel - * button got requested in the `WorkDoneProgressStart` payload. - * - * Clients that don't support cancellation or don't support control the button's - * enablement state are allowed to ignore the setting. - */ - cancellable?: boolean - /** - * Optional, more detailed associated progress message. Contains - * complementary information to the `title`. - * - * Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". - * If unset, the previous progress message (if any) is still valid. - */ - message?: string - /** - * Optional progress percentage to display (value 100 is considered 100%). - * If not provided infinite progress is assumed and clients are allowed - * to ignore the `percentage` value in subsequent in report notifications. - * - * The value should be steadily rising. Clients are free to ignore values - * that are not following this rule. - */ - percentage?: number - } - - /** - * The file event type - */ - export namespace FileChangeType { - /** - * The file got created. - */ - const Created = 1 - /** - * The file got changed. - */ - const Changed = 2 - /** - * The file got deleted. - */ - const Deleted = 3 - } - - export type FileChangeType = 1 | 2 | 3 - - /** - * An event describing a file change. - */ - export interface FileEvent { - /** - * The file's uri. - */ - uri: string - /** - * The change type. - */ - type: FileChangeType - } - - export interface WorkDoneProgressEnd { - kind: 'end' - /** - * Optional, a final message indicating to for example indicate the outcome - * of the operation. - */ - message?: string - } - - /** - * A literal to identify a text document in the client. - */ - export interface TextDocumentIdentifier { - /** - * The text document's uri. - */ - uri: string - } - - /** - * A parameter literal used in requests to pass a text document and a position inside that - * document. - */ - export interface TextDocumentPositionParams { - /** - * The text document. - */ - textDocument: TextDocumentIdentifier - /** - * The position inside the text document. - */ - position: Position - } - - export interface WorkspaceFolder { - /** - * The associated URI for this workspace folder. - */ - uri: string - /** - * The name of the workspace folder. Used to refer to this - * workspace folder in the user interface. - */ - name: string - } - - /** - * An event describing a change to a text document. - */ - export interface TextDocumentContentChange { - /** - * The range of the document that changed. - */ - range: Range - /** - * The new text for the provided range. - */ - text: string - } - - /** - * The workspace folder change event. - */ - export interface WorkspaceFoldersChangeEvent { - /** - * The array of added workspace folders - */ - added: WorkspaceFolder[] - /** - * The array of the removed workspace folders - */ - removed: WorkspaceFolder[] - } - - /** - * An event that is fired when a [document](#TextDocument) will be saved. - * - * To make modifications to the document before it is being saved, call the - * [`waitUntil`](#TextDocumentWillSaveEvent.waitUntil)-function with a thenable - * that resolves to an array of [text edits](#TextEdit). - */ - export interface TextDocumentWillSaveEvent { - - /** - * The document that will be saved. - */ - document: TextDocument - - /** - * The reason why save was triggered. - */ - reason: 1 | 2 | 3 - } - - /** - * A document filter denotes a document by different properties like - * the [language](#TextDocument.languageId), the [scheme](#Uri.scheme) of - * its resource, or a glob-pattern that is applied to the [path](#TextDocument.fileName). - * - * Glob patterns can have the following syntax: - * - `*` to match one or more characters in a path segment - * - `?` to match on one character in a path segment - * - `**` to match any number of path segments, including none - * - `{}` to group conditions (e.g. `**โ€‹/*.{ts,js}` matches all TypeScript and JavaScript files) - * - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, โ€ฆ) - * - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) - * - * @sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }` - * @sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }` - */ - export type DocumentFilter = { - /** A language id, like `typescript`. */ - language: string - /** A Uri [scheme](#Uri.scheme), like `file` or `untitled`. */ - scheme?: string - /** A glob pattern, like `*.{ts,js}`. */ - pattern?: string - } | { - /** A language id, like `typescript`. */ - language?: string - /** A Uri [scheme](#Uri.scheme), like `file` or `untitled`. */ - scheme: string - /** A glob pattern, like `*.{ts,js}`. */ - pattern?: string - } | { - /** A language id, like `typescript`. */ - language?: string - /** A Uri [scheme](#Uri.scheme), like `file` or `untitled`. */ - scheme?: string - /** A glob pattern, like `*.{ts,js}`. */ - pattern: string - } - /** - * A document selector is the combination of one or many document filters. - * - * @sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**โˆ•tsconfig.json' }]`; - */ - export type DocumentSelector = (string | DocumentFilter)[] - /** - * A selection range represents a part of a selection hierarchy. A selection range - * may have a parent selection range that contains it. - */ - export interface SelectionRange { - /** - * The [range](#Range) of this selection range. - */ - range: Range - /** - * The parent selection range containing this range. Therefore `parent.range` must contain `this.range`. - */ - parent?: SelectionRange - } - - /** - * MarkedString can be used to render human readable text. It is either a markdown string - * or a code-block that provides a language and a code snippet. The language identifier - * is semantically equal to the optional language identifier in fenced code blocks in GitHub - * issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting - * - * The pair of a language and a value is an equivalent to markdown: - * ```${language} - * ${value} - * ``` - * - * Note that markdown strings will be sanitized - that means html will be escaped. - * @deprecated use MarkupContent instead. - */ - export type MarkedString = string | { - language: string - value: string - } - /** - * The result of a hover request. - */ - export interface Hover { - /** - * The hover's content - */ - contents: MarkupContent | MarkedString | MarkedString[] - /** - * An optional range - */ - range?: Range - } - - /** - * The definition of a symbol represented as one or many [locations](#Location). - * For most programming languages there is only one location at which a symbol is - * defined. - * - * Servers should prefer returning `DefinitionLink` over `Definition` if supported - * by the client. - */ - export type Definition = Location | Location[] - - /** - * Information about where a symbol is defined. - * - * Provides additional metadata over normal [location](#Location) definitions, including the range of - * the defining symbol - */ - export type DefinitionLink = LocationLink - - /** - * How a signature help was triggered. - */ - export namespace SignatureHelpTriggerKind { - /** - * Signature help was invoked manually by the user or by a command. - */ - const Invoked: 1 - /** - * Signature help was triggered by a trigger character. - */ - const TriggerCharacter: 2 - /** - * Signature help was triggered by the cursor moving or by the document content changing. - */ - const ContentChange: 3 - } - - export type SignatureHelpTriggerKind = 1 | 2 | 3 - - /** - * Represents the signature of something callable. A signature - * can have a label, like a function-name, a doc-comment, and - * a set of parameters. - */ - export interface SignatureInformation { - /** - * The label of this signature. Will be shown in - * the UI. - */ - label: string - /** - * The human-readable doc-comment of this signature. Will be shown - * in the UI but can be omitted. - */ - documentation?: string | MarkupContent - /** - * The parameters of this signature. - */ - parameters?: ParameterInformation[] - } - - /** - * Represents a parameter of a callable-signature. A parameter can - * have a label and a doc-comment. - */ - export interface ParameterInformation { - /** - * The label of this parameter information. - * - * Either a string or an inclusive start and exclusive end offsets within its containing - * signature label. (see SignatureInformation.label). The offsets are based on a UTF-16 - * string representation as `Position` and `Range` does. - * - * *Note*: a label of type string should be a substring of its containing signature label. - * Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`. - */ - label: string | [number, number] - /** - * The human-readable doc-comment of this signature. Will be shown - * in the UI but can be omitted. - */ - documentation?: string | MarkupContent - } - - /** - * Signature help represents the signature of something - * callable. There can be multiple signature but only one - * active and only one active parameter. - */ - export interface SignatureHelp { - /** - * One or more signatures. - */ - signatures: SignatureInformation[] - /** - * The active signature. Set to `null` if no - * signatures exist. - */ - activeSignature: number | null - /** - * The active parameter of the active signature. Set to `null` - * if the active signature has no parameters. - */ - activeParameter: number | null - } - /** - * Additional information about the context in which a signature help request was triggered. - * - * @since 3.15.0 - */ - export interface SignatureHelpContext { - /** - * Action that caused signature help to be triggered. - */ - triggerKind: SignatureHelpTriggerKind - /** - * Character that caused signature help to be triggered. - * - * This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter` - */ - triggerCharacter?: string - /** - * `true` if signature help was already showing when it was triggered. - * - * Retriggers occur when the signature help is already active and can be caused by actions such as - * typing a trigger character, a cursor move, or document content changes. - */ - isRetrigger: boolean - /** - * The currently active `SignatureHelp`. - * - * The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on - * the user navigating through available signatures. - */ - activeSignatureHelp?: SignatureHelp - } - - /** - * Represents a folding range. - */ - export interface FoldingRange { - /** - * The zero-based line number from where the folded range starts. - */ - startLine: number - /** - * The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. - */ - startCharacter?: number - /** - * The zero-based line number where the folded range ends. - */ - endLine: number - /** - * The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. - */ - endCharacter?: number - /** - * Describes the kind of the folding range such as `comment' or 'region'. The kind - * is used to categorize folding ranges and used by commands like 'Fold all comments'. See - * [FoldingRangeKind](#FoldingRangeKind) for an enumeration of standardized kinds. - */ - kind?: string - } - - /** - * A symbol kind. - */ - export namespace SymbolKind { - const File: 1 - const Module: 2 - const Namespace: 3 - const Package: 4 - const Class: 5 - const Method: 6 - const Property: 7 - const Field: 8 - const Constructor: 9 - const Enum: 10 - const Interface: 11 - const Function: 12 - const Variable: 13 - const Constant: 14 - const String: 15 - const Number: 16 - const Boolean: 17 - const Array: 18 - const Object: 19 - const Key: 20 - const Null: 21 - const EnumMember: 22 - const Struct: 23 - const Event: 24 - const Operator: 25 - const TypeParameter: 26 - } - - export type SymbolKind = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 - - /** - * Represents information about programming constructs like variables, classes, - * interfaces etc. - */ - export interface SymbolInformation { - /** - * The name of this symbol. - */ - name: string - /** - * The kind of this symbol. - */ - kind: SymbolKind - /** - * Indicates if this symbol is deprecated. - */ - deprecated?: boolean - /** - * The location of this symbol. The location's range is used by a tool - * to reveal the location in the editor. If the symbol is selected in the - * tool the range's start information is used to position the cursor. So - * the range usually spans more than the actual symbol's name and does - * normally include thinks like visibility modifiers. - * - * The range doesn't have to denote a node range in the sense of a abstract - * syntax tree. It can therefore not be used to re-construct a hierarchy of - * the symbols. - */ - location: Location - /** - * The name of the symbol containing this symbol. This information is for - * user interface purposes (e.g. to render a qualifier in the user interface - * if necessary). It can't be used to re-infer a hierarchy for the document - * symbols. - */ - containerName?: string - } - - /** - * Represents programming constructs like variables, classes, interfaces etc. - * that appear in a document. Document symbols can be hierarchical and they - * have two ranges: one that encloses its definition and one that points to - * its most interesting range, e.g. the range of an identifier. - */ - export interface DocumentSymbol { - /** - * The name of this symbol. Will be displayed in the user interface and therefore must not be - * an empty string or a string only consisting of white spaces. - */ - name: string - /** - * More detail for this symbol, e.g the signature of a function. - */ - detail?: string - /** - * The kind of this symbol. - */ - kind: SymbolKind - /** - * Indicates if this symbol is deprecated. - */ - deprecated?: boolean - /** - * The range enclosing this symbol not including leading/trailing whitespace but everything else - * like comments. This information is typically used to determine if the the clients cursor is - * inside the symbol to reveal in the symbol in the UI. - */ - range: Range - /** - * The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. - * Must be contained by the the `range`. - */ - selectionRange: Range - /** - * Children of this symbol, e.g. properties of a class. - */ - children?: DocumentSymbol[] - } - - export interface FormattingOptions { - /** - * If indentation is based on spaces (`insertSpaces` = true), the number of spaces that make an indent. - */ - tabSize?: number - /** - * Is indentation based on spaces? - */ - insertSpaces?: boolean - /** - * The default 'end of line' character. If not set, '\n' is used as default. - */ - eol?: string - } - - /** - * Contains additional diagnostic information about the context in which - * a [code action](#CodeActionProvider.provideCodeActions) is run. - */ - export interface CodeActionContext { - /** - * An array of diagnostics known on the client side overlapping the range provided to the - * `textDocument/codeAction` request. They are provied so that the server knows which - * errors are currently presented to the user for the given range. There is no guarantee - * that these accurately reflect the error state of the resource. The primary parameter - * to compute code actions is the provided range. - */ - diagnostics: Diagnostic[] - /** - * Requested kind of actions to return. - * - * Actions not of this kind are filtered out by the client before being shown. So servers - * can omit computing them. - */ - only?: string[] - } - - - /** - * A document highlight kind. - */ - export namespace DocumentHighlightKind { - /** - * A textual occurrence. - */ - const Text: 1 - /** - * Read-access of a symbol, like reading a variable. - */ - const Read: 2 - /** - * Write-access of a symbol, like writing to a variable. - */ - const Write: 3 - } - - export type DocumentHighlightKind = 1 | 2 | 3 - /** - * A document highlight is a range inside a text document which deserves - * special attention. Usually a document highlight is visualized by changing - * the background color of its range. - */ - export interface DocumentHighlight { - /** - * The range this highlight applies to. - */ - range: Range - /** - * The highlight kind, default is [text](#DocumentHighlightKind.Text). - */ - kind?: DocumentHighlightKind - } - - /** - * A document link is a range in a text document that links to an internal or external resource, like another - * text document or a web site. - */ - export interface DocumentLink { - /** - * The range this link applies to. - */ - range: Range - /** - * The uri this link points to. - */ - target?: string - /** - * The tooltip text when you hover over this link. - * - * If a tooltip is provided, is will be displayed in a string that includes instructions on how to - * trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS, - * user settings, and localization. - * - * @since 3.15.0 - */ - tooltip?: string - /** - * A data entry field that is preserved on a document link between a - * DocumentLinkRequest and a DocumentLinkResolveRequest. - */ - data?: any - } - - /** - * Represents a color in RGBA space. - */ - export interface Color { - /** - * The red component of this color in the range [0-1]. - */ - readonly red: number - /** - * The green component of this color in the range [0-1]. - */ - readonly green: number - /** - * The blue component of this color in the range [0-1]. - */ - readonly blue: number - /** - * The alpha component of this color in the range [0-1]. - */ - readonly alpha: number - } - - /** - * Represents a color range from a document. - */ - export interface ColorInformation { - /** - * The range in the document where this color appers. - */ - range: Range - /** - * The actual color value for this color range. - */ - color: Color - } - - export interface ColorPresentation { - /** - * The label of this color presentation. It will be shown on the color - * picker header. By default this is also the text that is inserted when selecting - * this color presentation. - */ - label: string - /** - * An [edit](#TextEdit) which is applied to a document when selecting - * this presentation for the color. When `falsy` the [label](#ColorPresentation.label) - * is used. - */ - textEdit?: TextEdit - /** - * An optional array of additional [text edits](#TextEdit) that are applied when - * selecting this color presentation. Edits must not overlap with the main [edit](#ColorPresentation.textEdit) nor with themselves. - */ - additionalTextEdits?: TextEdit[] - } - - /** - * A code lens represents a [command](#Command) that should be shown along with - * source text, like the number of references, a way to run tests, etc. - * - * A code lens is _unresolved_ when no command is associated to it. For performance - * reasons the creation of a code lens and resolving should be done to two stages. - */ - export interface CodeLens { - /** - * The range in which this code lens is valid. Should only span a single line. - */ - range: Range - /** - * The command this code lens represents. - */ - command?: Command - /** - * An data entry field that is preserved on a code lens item between - * a [CodeLensRequest](#CodeLensRequest) and a [CodeLensResolveRequest] - * (#CodeLensResolveRequest) - */ - data?: any - } - - /** - * Represents the connection of two locations. Provides additional metadata over normal [locations](#Location), - * including an origin range. - */ - export interface LocationLink { - /** - * Span of the origin of this link. - * - * Used as the underlined span for mouse definition hover. Defaults to the word range at - * the definition position. - */ - originSelectionRange?: Range - /** - * The target resource identifier of this link. - */ - targetUri: string - /** - * The full target range of this link. If the target for example is a symbol then target range is the - * range enclosing this symbol not including leading/trailing whitespace but everything else - * like comments. This information is typically used to highlight the range in the editor. - */ - targetRange: Range - /** - * The range that should be selected and revealed when this link is being followed, e.g the name of a function. - * Must be contained by the the `targetRange`. See also `DocumentSymbol#range` - */ - targetSelectionRange: Range - } - - /** - * The LocationLink namespace provides helper functions to work with - * [LocationLink](#LocationLink) literals. - */ - export namespace LocationLink { - /** - * Creates a LocationLink literal. - * @param targetUri The definition's uri. - * @param targetRange The full range of the definition. - * @param targetSelectionRange The span of the symbol definition at the target. - * @param originSelectionRange The span of the symbol being defined in the originating source file. - */ - function create(targetUri: string, targetRange: Range, targetSelectionRange: Range, originSelectionRange?: Range): LocationLink - /** - * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface. - */ - function is(value: any): value is LocationLink - } - - export type MarkupKind = 'plaintext' | 'markdown' - - /** - * Describes the content type that a client supports in various - * result literals like `Hover`, `ParameterInfo` or `CompletionItem`. - * - * Please note that `MarkupKinds` must not start with a `$`. This kinds - * are reserved for internal usage. - */ - export namespace MarkupKind { - /** - * Plain text is supported as a content format - */ - const PlainText: 'plaintext' - /** - * Markdown is supported as a content format - */ - const Markdown: 'markdown' - } - /** - * A `MarkupContent` literal represents a string value which content is interpreted base on its - * kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds. - * - * If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues. - * See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting - * - * Here is an example how such a string can be constructed using JavaScript / TypeScript: - * ```ts - * let markdown: MarkdownContent = { - * kind: MarkupKind.Markdown, - * value: [ - * '# Header', - * 'Some text', - * '```typescript', - * 'someCode();', - * '```' - * ].join('\n') - * }; - * ``` - * - * *Please Note* that clients might sanitize the return markdown. A client could decide to - * remove HTML from the markdown to avoid script execution. - */ - export interface MarkupContent { - /** - * The type of the Markup - */ - kind: MarkupKind - /** - * The content itself - */ - value: string - } - - /** - * The kind of a completion entry. - */ - export namespace CompletionItemKind { - const Text: 1 - const Method: 2 - const Function: 3 - const Constructor: 4 - const Field: 5 - const Variable: 6 - const Class: 7 - const Interface: 8 - const Module: 9 - const Property: 10 - const Unit: 11 - const Value: 12 - const Enum: 13 - const Keyword: 14 - const Snippet: 15 - const Color: 16 - const File: 17 - const Reference: 18 - const Folder: 19 - const EnumMember: 20 - const Constant: 21 - const Struct: 22 - const Event: 23 - const Operator: 24 - const TypeParameter: 25 - } - - export type CompletionItemKind = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 - - /** - * Defines whether the insert text in a completion item should be interpreted as - * plain text or a snippet. - */ - export namespace InsertTextFormat { - /** - * The primary text to be inserted is treated as a plain string. - */ - const PlainText: 1 - /** - * The primary text to be inserted is treated as a snippet. - * - * A snippet can define tab stops and placeholders with `$1`, `$2` - * and `${3:foo}`. `$0` defines the final tab stop, it defaults to - * the end of the snippet. Placeholders with equal identifiers are linked, - * that is typing in one will update others too. - * - * See also: https://github.com/microsoft/vscode/blob/main/src/vs/editor/contrib/snippet/snippet.md - */ - const Snippet: 2 - } - export type InsertTextFormat = 1 | 2 - - /** - * A completion item represents a text snippet that is - * proposed to complete text that is being typed. - */ - export interface CompletionItem { - /** - * The label of this completion item. By default - * also the text that is inserted when selecting - * this completion. - */ - label: string - /** - * The kind of this completion item. Based of the kind - * an icon is chosen by the editor. - */ - kind?: CompletionItemKind - /** - * Tags for this completion item. - * - * @since 3.15.0 - */ - tags?: number[] - /** - * A human-readable string with additional information - * about this item, like type or symbol information. - */ - detail?: string - /** - * A human-readable string that represents a doc-comment. - */ - documentation?: string | MarkupContent - /** - * Indicates if this item is deprecated. - * @deprecated Use `tags` instead. - */ - deprecated?: boolean - /** - * Select this item when showing. - * - * *Note* that only one completion item can be selected and that the - * tool / client decides which item that is. The rule is that the *first* - * item of those that match best is selected. - */ - preselect?: boolean - /** - * A string that should be used when comparing this item - * with other items. When `falsy` the [label](#CompletionItem.label) - * is used. - */ - sortText?: string - /** - * A string that should be used when filtering a set of - * completion items. When `falsy` the [label](#CompletionItem.label) - * is used. - */ - filterText?: string - /** - * A string that should be inserted into a document when selecting - * this completion. When `falsy` the [label](#CompletionItem.label) - * is used. - * - * The `insertText` is subject to interpretation by the client side. - * Some tools might not take the string literally. For example - * VS Code when code complete is requested in this example `con` - * and a completion item with an `insertText` of `console` is provided it - * will only insert `sole`. Therefore it is recommended to use `textEdit` instead - * since it avoids additional client side interpretation. - */ - insertText?: string - /** - * The format of the insert text. The format applies to both the `insertText` property - * and the `newText` property of a provided `textEdit`. If omitted defaults to - * `InsertTextFormat.PlainText`. - */ - insertTextFormat?: InsertTextFormat - /** - * An [edit](#TextEdit) which is applied to a document when selecting - * this completion. When an edit is provided the value of - * [insertText](#CompletionItem.insertText) is ignored. - * - * *Note:* The text edit's range must be a [single line] and it must contain the position - * at which completion has been requested. - */ - textEdit?: TextEdit - /** - * An optional array of additional [text edits](#TextEdit) that are applied when - * selecting this completion. Edits must not overlap (including the same insert position) - * with the main [edit](#CompletionItem.textEdit) nor with themselves. - * - * Additional text edits should be used to change text unrelated to the current cursor position - * (for example adding an import statement at the top of the file if the completion item will - * insert an unqualified type). - */ - additionalTextEdits?: TextEdit[] - /** - * An optional set of characters that when pressed while this completion is active will accept it first and - * then type that character. *Note* that all commit characters should have `length=1` and that superfluous - * characters will be ignored. - */ - commitCharacters?: string[] - /** - * An optional [command](#Command) that is executed *after* inserting this completion. *Note* that - * additional modifications to the current document should be described with the - * [additionalTextEdits](#CompletionItem.additionalTextEdits)-property. - */ - command?: Command - /** - * An data entry field that is preserved on a completion item between - * a [CompletionRequest](#CompletionRequest) and a [CompletionResolveRequest] - * (#CompletionResolveRequest) - */ - data?: any - } - - /** - * Represents a collection of [completion items](#CompletionItem) to be presented - * in the editor. - */ - export interface CompletionList { - /** - * This list it not complete. Further typing results in recomputing this list. - */ - isIncomplete: boolean - /** - * The completion items. - */ - items: CompletionItem[] - } - - /** - * How a completion was triggered - */ - export namespace CompletionTriggerKind { - /** - * Completion was triggered by typing an identifier (24x7 code - * complete), manual invocation (e.g Ctrl+Space) or via API. - */ - const Invoked: 1 - /** - * Completion was triggered by a trigger character specified by - * the `triggerCharacters` properties of the `CompletionRegistrationOptions`. - */ - const TriggerCharacter: 2 - /** - * Completion was re-triggered as current completion list is incomplete - */ - const TriggerForIncompleteCompletions: 3 - } - - export type CompletionTriggerKind = 1 | 2 | 3 - - /** - * Contains additional information about the context in which a completion request is triggered. - */ - export interface CompletionContext { - /** - * How the completion was triggered. - */ - triggerKind: CompletionTriggerKind, - /** - * The trigger character (a single character) that has trigger code complete. - * Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` - */ - triggerCharacter?: string - - option?: CompleteOption - } - - /** - * Represents a reference to a command. Provides a title which - * will be used to represent a command in the UI and, optionally, - * an array of arguments which will be passed to the command handler - * function when invoked. - */ - export interface Command { - /** - * Title of the command, like `save`. - */ - title: string - /** - * The identifier of the actual command handler. - */ - command: string - /** - * Arguments that the command handler should be - * invoked with. - */ - arguments?: any[] - } - - export interface TextDocumentEdit { - /** - * The text document to change. - */ - textDocument: { - uri: string - version: number | null - } - /** - * The edits to be applied. - */ - edits: TextEdit[] - } - - /** - * A workspace edit represents changes to many resources managed in the workspace. The edit - * should either provide `changes` or `documentChanges`. If documentChanges are present - * they are preferred over `changes` if the client can handle versioned document edits. - */ - export interface WorkspaceEdit { - /** - * Holds changes to existing resources. - */ - changes?: { - [uri: string]: TextEdit[] - } - /** - * Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes - * are either an array of `TextDocumentEdit`s to express changes to n different text documents - * where each text document edit addresses a specific version of a text document. Or it can contain - * above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations. - * - * Whether a client supports versioned document edits is expressed via - * `workspace.workspaceEdit.documentChanges` client capability. - * - * If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then - * only plain `TextEdit`s using the `changes` property are supported. - */ - documentChanges?: (TextDocumentEdit | CreateFile | RenameFile | DeleteFile)[] - } - - interface ResourceOperation { - kind: string - } - - /** - * Delete file options - */ - export interface DeleteFileOptions { - /** - * Delete the content recursively if a folder is denoted. - */ - recursive?: boolean - /** - * Ignore the operation if the file doesn't exist. - */ - ignoreIfNotExists?: boolean - } - /** - * Delete file operation - */ - export interface DeleteFile extends ResourceOperation { - /** - * A delete - */ - kind: 'delete' - /** - * The file to delete. - */ - uri: string - /** - * Delete options. - */ - options?: DeleteFileOptions - } - - /** - * Options to create a file. - */ - export interface CreateFileOptions { - /** - * Overwrite existing file. Overwrite wins over `ignoreIfExists` - */ - overwrite?: boolean - /** - * Ignore if exists. - */ - ignoreIfExists?: boolean - } - /** - * Create file operation. - */ - export interface CreateFile extends ResourceOperation { - /** - * A create - */ - kind: 'create' - /** - * The resource to create. - */ - uri: string - /** - * Additional options - */ - options?: CreateFileOptions - } - - /** - * Rename file options - */ - export interface RenameFileOptions { - /** - * Overwrite target if existing. Overwrite wins over `ignoreIfExists` - */ - overwrite?: boolean - /** - * Ignores if target exists. - */ - ignoreIfExists?: boolean - } - /** - * Rename file operation - */ - export interface RenameFile extends ResourceOperation { - /** - * A rename - */ - kind: 'rename' - /** - * The old (existing) location. - */ - oldUri: string - /** - * The new location. - */ - newUri: string - /** - * Rename options. - */ - options?: RenameFileOptions - } - /** - * Represents a related message and source code location for a diagnostic. This should be - * used to point to code locations that cause or related to a diagnostics, e.g when duplicating - * a symbol in a scope. - */ - export interface DiagnosticRelatedInformation { - /** - * The location of this related diagnostic information. - */ - location: Location - /** - * The message of this related diagnostic information. - */ - message: string - } - - /** - * The diagnostic's severity. - */ - export namespace DiagnosticSeverity { - /** - * Reports an error. - */ - const Error: 1 - /** - * Reports a warning. - */ - const Warning: 2 - /** - * Reports an information. - */ - const Information: 3 - /** - * Reports a hint. - */ - const Hint: 4 - } - - export type DiagnosticSeverity = 1 | 2 | 3 | 4 - - /** - * The diagnostic tags. - * - * @since 3.15.0 - */ - export namespace DiagnosticTag { - /** - * Unused or unnecessary code. - * - * Clients are allowed to render diagnostics with this tag faded out instead of having - * an error squiggle. - */ - const Unnecessary: 1 - /** - * Deprecated or obsolete code. - * - * Clients are allowed to rendered diagnostics with this tag strike through. - */ - const Deprecated: 2 - } - - export type DiagnosticTag = 1 | 2 - - /** - * Represents a diagnostic, such as a compiler error or warning. Diagnostic objects - * are only valid in the scope of a resource. - */ - export interface Diagnostic { - /** - * The range at which the message applies - */ - range: Range - /** - * The diagnostic's severity. Can be omitted. If omitted it is up to the - * client to interpret diagnostics as error, warning, info or hint. - */ - severity?: DiagnosticSeverity - /** - * The diagnostic's code, which usually appear in the user interface. - */ - code?: number | string - /** - * A human-readable string describing the source of this - * diagnostic, e.g. 'typescript' or 'super lint'. It usually - * appears in the user interface. - */ - source?: string - /** - * The diagnostic's message. It usually appears in the user interface - */ - message: string - /** - * Additional metadata about the diagnostic. - */ - tags?: DiagnosticTag[] - /** - * An array of related diagnostic information, e.g. when symbol-names within - * a scope collide all definitions can be marked via this property. - */ - relatedInformation?: DiagnosticRelatedInformation[] - } - - /** - * The Diagnostic namespace provides helper functions to work with - * [Diagnostic](#Diagnostic) literals. - */ - export namespace Diagnostic { - /** - * Creates a new Diagnostic literal. - */ - function create(range: Range, message: string, severity?: DiagnosticSeverity, code?: number | string, source?: string, relatedInformation?: DiagnosticRelatedInformation[]): Diagnostic - /** - * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface. - */ - function is(value: any): value is Diagnostic - } - - /** - * A code action represents a change that can be performed in code, e.g. to fix a problem or - * to refactor code. - * - * A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed. - */ - export interface CodeAction { - /** - * A short, human-readable, title for this code action. - */ - title: string - /** - * The kind of the code action. - * - * Used to filter code actions. - */ - kind?: CodeActionKind - /** - * The diagnostics that this code action resolves. - */ - diagnostics?: Diagnostic[] - /** - * Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted - * by keybindings. - * - * A quick fix should be marked preferred if it properly addresses the underlying error. - * A refactoring should be marked preferred if it is the most reasonable choice of actions to take. - * - * @since 3.15.0 - */ - isPreferred?: boolean - /** - * The workspace edit this code action performs. - */ - edit?: WorkspaceEdit - /** - * A command this code action executes. If a code action - * provides a edit and a command, first the edit is - * executed and then the command. - */ - command?: Command - /** - * Id of client that provide codeAction. - */ - clientId?: string - } - - /** - * The kind of a code action. - * - * Kinds are a hierarchical list of identifiers separated by `.`, e.g. `"refactor.extract.function"`. - * - * The set of kinds is open and client needs to announce the kinds it supports to the server during - * initialization. - */ - export type CodeActionKind = string - /** - * A set of predefined code action kinds - */ - export namespace CodeActionKind { - /** - * Empty kind. - */ - const Empty: CodeActionKind - /** - * Base kind for quickfix actions: 'quickfix' - */ - const QuickFix: CodeActionKind - /** - * Base kind for refactoring actions: 'refactor' - */ - const Refactor: CodeActionKind - /** - * Base kind for refactoring extraction actions: 'refactor.extract' - * - * Example extract actions: - * - * - Extract method - * - Extract function - * - Extract variable - * - Extract interface from class - * - ... - */ - const RefactorExtract: CodeActionKind - /** - * Base kind for refactoring inline actions: 'refactor.inline' - * - * Example inline actions: - * - * - Inline function - * - Inline variable - * - Inline constant - * - ... - */ - const RefactorInline: CodeActionKind - /** - * Base kind for refactoring rewrite actions: 'refactor.rewrite' - * - * Example rewrite actions: - * - * - Convert JavaScript function to class - * - Add or remove parameter - * - Encapsulate field - * - Make method static - * - Move method to base class - * - ... - */ - const RefactorRewrite: CodeActionKind - /** - * Base kind for source actions: `source` - * - * Source code actions apply to the entire file. - */ - const Source: CodeActionKind - /** - * Base kind for an organize imports source action: `source.organizeImports` - */ - const SourceOrganizeImports: CodeActionKind - /** - * Base kind for auto-fix source actions: `source.fixAll`. - * - * Fix all actions automatically fix errors that have a clear fix that do not require user input. - * They should not suppress errors or perform unsafe fixes such as generating new types or classes. - * - * @since 3.15.0 - */ - const SourceFixAll: CodeActionKind - } - - /** - * Position in a text document expressed as zero-based line and character offset. - * The offsets are based on a UTF-16 string representation. So a string of the form - * `a๐€b` the character offset of the character `a` is 0, the character offset of `๐€` - * is 1 and the character offset of b is 3 since `๐€` is represented using two code - * units in UTF-16. - * - * Positions are line end character agnostic. So you can not specify a position that - * denotes `\r|\n` or `\n|` where `|` represents the character offset. - */ - export interface Position { - /** - * Line position in a document (zero-based). - * If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document. - * If a line number is negative, it defaults to 0. - */ - line: number - /** - * Character offset on a line in a document (zero-based). Assuming that the line is - * represented as a string, the `character` value represents the gap between the - * `character` and `character + 1`. - * - * If the character value is greater than the line length it defaults back to the - * line length. - * If a line number is negative, it defaults to 0. - */ - character: number - } - - /** - * The Position namespace provides helper functions to work with - * [Position](#Position) literals. - */ - export namespace Position { - /** - * Creates a new Position literal from the given line and character. - * @param line The position's line. - * @param character The position's character. - */ - function create(line: number, character: number): Position - /** - * Checks whether the given liternal conforms to the [Position](#Position) interface. - */ - function is(value: any): value is Position - } - - /** - * Represents a typed event. - * - * A function that represents an event to which you subscribe by calling it with - * a listener function as argument. - * - * @example - * item.onDidChange(function(event) { console.log("Event happened: " + event); }); - */ - export interface Event { - - /** - * A function that represents an event to which you subscribe by calling it with - * a listener function as argument. - * - * @param listener The listener function will be called when the event happens. - * @param thisArgs The `this`-argument which will be used when calling the event listener. - * @param disposables An array to which a [disposable](#Disposable) will be added. - * @return A disposable which unsubscribes the event listener. - */ - (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]): Disposable - } - - export namespace Event { - const None: Event - } - - export interface EmitterOptions { - onFirstListenerAdd?: Function - onLastListenerRemove?: Function - } - - export class Emitter { - constructor(_options?: EmitterOptions | undefined) - /** - * For the public to allow to subscribe - * to events from this Emitter - */ - get event(): Event - /** - * To be kept private to fire an event to - * subscribers - */ - fire(event: T): any - dispose(): void - } - - /** - * Represents a location inside a resource, such as a line - * inside a text file. - */ - export interface Location { - uri: string - range: Range - } - - /** - * The Location namespace provides helper functions to work with - * [Location](#Location) literals. - */ - export namespace Location { - /** - * Creates a Location literal. - * @param uri The location's uri. - * @param range The location's range. - */ - function create(uri: string, range: Range): Location - /** - * Checks whether the given literal conforms to the [Location](#Location) interface. - */ - function is(value: any): value is Location - } - - /** - * A range in a text document expressed as (zero-based) start and end positions. - * - * If you want to specify a range that contains a line including the line ending - * character(s) then use an end position denoting the start of the next line. - * For example: - * ```ts - * { - * start: { line: 5, character: 23 } - * end : { line 6, character : 0 } - * } - * ``` - */ - export interface Range { - /** - * The range's start position - */ - start: Position - /** - * The range's end position. - */ - end: Position - } - - /** - * The Range namespace provides helper functions to work with - * [Range](#Range) literals. - */ - export namespace Range { - /** - * Create a new Range liternal. - * @param start The range's start position. - * @param end The range's end position. - */ - function create(start: Position, end: Position): Range - /** - * Create a new Range liternal. - * @param startLine The start line number. - * @param startCharacter The start character. - * @param endLine The end line number. - * @param endCharacter The end character. - */ - function create(startLine: number, startCharacter: number, endLine: number, endCharacter: number): Range - /** - * Checks whether the given literal conforms to the [Range](#Range) interface. - */ - function is(value: any): value is Range - } - - /** - * A text edit applicable to a text document. - */ - export interface TextEdit { - /** - * The range of the text document to be manipulated. To insert - * text into a document create a range where start === end. - */ - range: Range - /** - * The string to be inserted. For delete operations use an - * empty string. - */ - newText: string - } - - /** - * The TextEdit namespace provides helper function to create replace, - * insert and delete edits more easily. - */ - export namespace TextEdit { - /** - * Creates a replace text edit. - * @param range The range of text to be replaced. - * @param newText The new text. - */ - function replace(range: Range, newText: string): TextEdit - /** - * Creates a insert text edit. - * @param position The position to insert the text at. - * @param newText The text to be inserted. - */ - function insert(position: Position, newText: string): TextEdit - /** - * Creates a delete text edit. - * @param range The range of text to be deleted. - */ - function del(range: Range): TextEdit - function is(value: any): value is TextEdit - } - - /** - * Defines a CancellationToken. This interface is not - * intended to be implemented. A CancellationToken must - * be created via a CancellationTokenSource. - */ - export interface CancellationToken { - /** - * Is `true` when the token has been cancelled, `false` otherwise. - */ - readonly isCancellationRequested: boolean - /** - * An [event](#Event) which fires upon cancellation. - */ - readonly onCancellationRequested: Event - } - - export namespace CancellationToken { - const None: CancellationToken - const Cancelled: CancellationToken - function is(value: any): value is CancellationToken - } - - export class CancellationTokenSource { - get token(): CancellationToken - cancel(): void - dispose(): void - } - - /** - * A simple text document. Not to be implemented. The document keeps the content - * as string. - */ - export interface TextDocument { - /** - * The associated URI for this document. Most documents have the __file__-scheme, indicating that they - * represent files on disk. However, some documents may have other schemes indicating that they are not - * available on disk. - * - * @readonly - */ - readonly uri: string - /** - * The identifier of the language associated with this document. - * - * @readonly - */ - readonly languageId: string - /** - * The version number of this document (it will increase after each - * change, including undo/redo). - * - * @readonly - */ - readonly version: number - /** - * Get the text of this document. A substring can be retrieved by - * providing a range. - * - * @param range (optional) An range within the document to return. - * If no range is passed, the full content is returned. - * Invalid range positions are adjusted as described in [Position.line](#Position.line) - * and [Position.character](#Position.character). - * If the start range position is greater than the end range position, - * then the effect of getText is as if the two positions were swapped. - - * @return The text of this document or a substring of the text if a - * range is provided. - */ - getText(range?: Range): string - /** - * Converts a zero-based offset to a position. - * - * @param offset A zero-based offset. - * @return A valid [position](#Position). - */ - positionAt(offset: number): Position - /** - * Converts the position to a zero-based offset. - * Invalid positions are adjusted as described in [Position.line](#Position.line) - * and [Position.character](#Position.character). - * - * @param position A position. - * @return A valid zero-based offset. - */ - offsetAt(position: Position): number - /** - * The number of lines in this document. - * - * @readonly - */ - readonly lineCount: number - } - - /** - * @since 3.16.0 - */ - export interface SemanticTokensLegend { - /** - * The token types a server uses. - */ - tokenTypes: string[] - /** - * The token modifiers a server uses. - */ - tokenModifiers: string[] - } - - /** - * @since 3.16.0 - */ - export interface SemanticTokens { - /** - * An optional result id. If provided and clients support delta updating - * the client will include the result id in the next semantic token request. - * A server can then instead of computing all semantic tokens again simply - * send a delta. - */ - resultId?: string - /** - * The actual tokens. - */ - data: number[] - } - - /** - * @since 3.16.0 - */ - export interface SemanticTokensEdit { - /** - * The start offset of the edit. - */ - start: number - /** - * The count of elements to remove. - */ - deleteCount: number - /** - * The elements to insert. - */ - data?: number[] - } - - /** - * @since 3.16.0 - */ - export interface SemanticTokensDelta { - readonly resultId?: string - /** - * The semantic token edits to transform a previous result into a new result. - */ - edits: SemanticTokensEdit[] - } - - /** - * The result of a linked editing range request. - * - * @since 3.16.0 - */ - export interface LinkedEditingRanges { - /** - * A list of ranges that can be edited together. The ranges must have - * identical length and contain identical text content. The ranges cannot overlap. - */ - ranges: Range[] - /** - * An optional word pattern (regular expression) that describes valid contents for - * the given ranges. If no pattern is provided, the client configuration's word - * pattern will be used. - */ - wordPattern?: string - } - - /** - * Represents programming constructs like functions or constructors in the context - * of call hierarchy. - * - * @since 3.16.0 - */ - export interface CallHierarchyItem { - /** - * The name of this item. - */ - name: string - /** - * The kind of this item. - */ - kind: SymbolKind - /** - * Tags for this item. - */ - tags?: number[] - /** - * More detail for this item, e.g. the signature of a function. - */ - detail?: string - /** - * The resource identifier of this item. - */ - uri: string - /** - * The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code. - */ - range: Range - /** - * The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. - * Must be contained by the [`range`](#CallHierarchyItem.range). - */ - selectionRange: Range - /** - * A data entry field that is preserved between a call hierarchy prepare and - * incoming calls or outgoing calls requests. - */ - data?: unknown - } - - /** - * Represents an incoming call, e.g. a caller of a method or constructor. - * - * @since 3.16.0 - */ - export interface CallHierarchyIncomingCall { - /** - * The item that makes the call. - */ - from: CallHierarchyItem - /** - * The ranges at which the calls appear. This is relative to the caller - * denoted by [`this.from`](#CallHierarchyIncomingCall.from). - */ - fromRanges: Range[] - } - /** - * Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc. - * - * @since 3.16.0 - */ - export interface CallHierarchyOutgoingCall { - /** - * The item that is called. - */ - to: CallHierarchyItem - /** - * The range at which this item is called. This is the range relative to the caller, e.g the item - * passed to [`provideCallHierarchyOutgoingCalls`](#CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls) - * and not [`this.to`](#CallHierarchyOutgoingCall.to). - */ - fromRanges: Range[] - } - // }} - - // nvim interfaces {{ - type VimValue = - | number - | boolean - | string - | number[] - | { [key: string]: any } - - // see `:h nvim_set_client_info()` for details. - export interface VimClientInfo { - name: string - version: { - major?: number - minor?: number - patch?: number - prerelease?: string - commit?: string - } - type: 'remote' | 'embedder' | 'host' - methods?: { - [index: string]: any - } - attributes?: { - [index: string]: any - } - } - - export interface UiAttachOptions { - rgb?: boolean - ext_popupmenu?: boolean - ext_tabline?: boolean - ext_wildmenu?: boolean - ext_cmdline?: boolean - ext_linegrid?: boolean - ext_hlstate?: boolean - } - - export interface ChanInfo { - id: number - stream: 'stdio' | 'stderr' | 'socket' | 'job' - mode: 'bytes' | 'terminal' | 'rpc' - pty?: number - buffer?: number - client?: VimClientInfo - } - - /** - * Returned by nvim_get_commands api. - */ - export interface VimCommandDescription { - name: string - bang: boolean - bar: boolean - register: boolean - definition: string - count?: number | null - script_id: number - complete?: string - nargs?: string - range?: string - complete_arg?: string - } - - export interface NvimFloatOptions { - standalone?: boolean - focusable?: boolean - relative?: 'editor' | 'cursor' | 'win' - anchor?: 'NW' | 'NE' | 'SW' | 'SE' - height: number - width: number - row: number - col: number - } - - export interface NvimProc { - ppid: number - name: string - pid: number - } - - export interface SignPlaceOption { - id?: number - group?: string - name: string - lnum: number - priority?: number - } - - export interface SignUnplaceOption { - group?: string - id?: number - } - - export interface SignPlacedOption { - /** - * Use '*' for all group, default to '' as unnamed group. - */ - group?: string - id?: number - lnum?: number - } - - export interface SignItem { - group: string - id: number - lnum: number - name: string - priority: number - } - - export interface HighlightItem { - hlGroup: string - /** - * 0 based - */ - lnum: number - /** - * 0 based - */ - colStart: number - /** - * 0 based - */ - colEnd: number - } - - export interface BufferKeymapOption { - nowait?: boolean - silent?: boolean - script?: boolean - expr?: boolean - unique?: boolean - } - - export interface BufferHighlight { - /** - * Name of the highlight group to use - */ - hlGroup?: string - /** - * Namespace to use or -1 for ungrouped highlight - */ - srcId?: number - /** - * Line to highlight (zero-indexed) - */ - line?: number - /** - * Start of (byte-indexed) column range to highlight - */ - colStart?: number - /** - * End of (byte-indexed) column range to highlight, or -1 to highlight to end of line - */ - colEnd?: number - } - - export interface BufferClearHighlight { - srcId?: number - lineStart?: number - lineEnd?: number - } - - interface BaseApi { - /** - * unique identify number - */ - id: number - - /** - * Check if same by compare id. - */ - equals(other: T): boolean - - /** - * Request to vim, name need to be nvim_ prefixed and supported by vim. - * - * @param {string} name - nvim function name - * @param {VimValue[]} args - * @returns {Promise} - */ - request(name: string, args?: VimValue[]): Promise - - /** - * Send notification to vim, name need to be nvim_ prefixed and supported - * by vim - */ - notify(name: string, args?: VimValue[]): void - - /** - * Retrieves scoped variable, returns null when value not exists. - */ - getVar(name: string): Promise - - /** - * Set scoped variable by request. - * - * @param {string} name - * @param {VimValue} value - * @returns {Promise} - */ - setVar(name: string, value: VimValue): Promise - - /** - * Set scoped variable by notification. - */ - setVar(name: string, value: VimValue, isNotify: true): void - - /** - * Delete scoped variable by notification. - */ - deleteVar(name: string): void - - /** - * Retrieves a scoped option, not exists for tabpage. - */ - getOption(name: string): Promise - - /** - * Set scoped option by request, not exists for tabpage. - */ - setOption(name: string, value: VimValue): Promise - - /** - * Set scoped variable by notification, not exists for tabpage. - */ - setOption(name: string, value: VimValue, isNotify: true): void - } - - export interface Neovim extends BaseApi { - - /** - * Echo error message to vim and log error stack. - */ - echoError(msg: string | Error): void - - /** - * Check if `nvim_` function exists. - */ - hasFunction(name: string): boolean - - /** - * Get channelid used by coc.nvim. - */ - channelId: Promise - - /** - * Create buffer instance by id. - */ - createBuffer(id: number): Buffer - - /** - * Create window instance by id. - */ - createWindow(id: number): Window - - /** - * Create tabpage instance by id. - */ - createTabpage(id: number): Tabpage - - /** - * Stop send subsequent notifications. - */ - pauseNotification(): void - - /** - * Send paused notifications by nvim_call_atomic request - * - * **Note**: avoid call async function between pauseNotification and - * resumeNotification. - */ - resumeNotification(): Promise<[any[], [string, number, string] | null]> - - /** - * Send paused notifications by nvim_call_atomic notification - */ - resumeNotification(cancel: boolean, notify: true): void - - /** - * Get list of current buffers. - */ - buffers: Promise - - /** - * Get current buffer. - */ - buffer: Promise - - /** - * Set current buffer - */ - setBuffer(buffer: Buffer): Promise - - /** - * Get list of current tabpages. - */ - tabpages: Promise - - /** - * Get current tabpage. - */ - tabpage: Promise - - /** - * Set current tabpage - */ - setTabpage(tabpage: Tabpage): Promise - - /** - * Get list of current windows. - */ - windows: Promise - - /** - * Get current window. - */ - window: Promise - - /** - * Set current window. - */ - setWindow(window: Window): Promise - - /** - * Get information of all channels, - * **Note:** works on neovim only. - */ - chans: Promise - - /** - * Get information of channel by id, - * **Note:** works on neovim only. - */ - getChanInfo(id: number): Promise - - /** - * Creates a new namespace, or gets an existing one. - * `:h nvim_create_namespace()` - */ - createNamespace(name?: string): Promise - - /** - * Gets existing, non-anonymous namespaces. - * - * @return dict that maps from names to namespace ids. - */ - namespaces: Promise<{ [name: string]: number }> - - /** - * Gets a map of global (non-buffer-local) Ex commands. - * - * @return Map of maps describing commands. - */ - getCommands(opt?: { builtin: boolean }): Promise<{ [name: string]: VimCommandDescription }> - - /** - * Get list of all runtime paths - */ - runtimePaths: Promise - - /** - * Set global working directory. - * **Note:** works on neovim only. - */ - setDirectory(dir: string): Promise - - /** - * Get current line. - */ - line: Promise - - /** - * Creates a new, empty, unnamed buffer. - * - * **Note:** works on neovim only. - */ - createNewBuffer(listed?: boolean, scratch?: boolean): Promise - - /** - * Create float window of neovim. - * - * **Note:** works on neovim only, use high level api provided by window - * module is recommended. - */ - openFloatWindow(buffer: Buffer, enter: boolean, options: NvimFloatOptions): Promise - - /** - * Set current line. - */ - setLine(line: string): Promise - - /** - * Gets a list of global (non-buffer-local) |mapping| definitions. - * `:h nvim_get_keymap` - * - * **Note:** works on neovim only. - */ - getKeymap(mode: string): Promise - - /** - * Gets the current mode. |mode()| "blocking" is true if Nvim is waiting for input. - * - * **Note:** blocking would always be false when used with vim. - */ - mode: Promise<{ mode: string; blocking: boolean }> - - /** - * Returns a map of color names and RGB values. - * - * **Note:** works on neovim only. - */ - colorMap(): Promise<{ [name: string]: number }> - - /** - * Returns the 24-bit RGB value of a |nvim_get_color_map()| color name or - * "#rrggbb" hexadecimal string. - * - * **Note:** works on neovim only. - */ - getColorByName(name: string): Promise - - /** - * Gets a highlight definition by id. |hlID()| - * - * **Note:** works on neovim only. - */ - getHighlight(nameOrId: string | number, isRgb?: boolean): Promise - - /** - * Get a highlight by name, return rgb by default. - * - * **Note:** works on neovim only. - */ - getHighlightByName(name: string, isRgb?: boolean): Promise - - /** - * Get a highlight by id, return rgb by default. - * - * **Note:** works on neovim only. - */ - getHighlightById(id: number, isRgb?: boolean): Promise - - /** - * Delete current line in buffer. - */ - deleteCurrentLine(): Promise - - /** - * Evaluates a VimL expression (:help expression). Dictionaries - * and Lists are recursively expanded. On VimL error: Returns a - * generic error; v:errmsg is not updated. - * - */ - eval(expr: string): Promise - - /** - * Executes lua, it's possible neovim client does not support this - * - * **Note:** works on neovim only. - */ - executeLua(code: string, args?: VimValue[]): Promise - - /** - * Calls a VimL |Dictionary-function| with the given arguments. - */ - callDictFunction(dict: object | string, fname: string, args: VimValue | VimValue[]): Promise - - /** - * Call a vim function. - * - * @param {string} fname - function name - * @param {VimValue | VimValue[]} args - * @returns {Promise} - */ - call(fname: string, args?: VimValue | VimValue[]): Promise - - /** - * Call a vim function by notification. - */ - call(fname: string, args: VimValue | VimValue[], isNotify: true): void - - /** - * Call a vim function with timer of timeout 0. - * - * @param {string} fname - function name - * @param {VimValue | VimValue[]} args - * @returns {Promise} - */ - callTimer(fname: string, args?: VimValue | VimValue[]): Promise - - /** - * Call a vim function with timer of timeout 0 by notification. - */ - callTimer(fname: string, args: VimValue | VimValue[], isNotify: true): void - - /** - * Call async vim function that accept callback as argument - * by using notifications. - */ - callAsync(fname: string, args?: VimValue | VimValue[]): Promise - - /** - * Calls many API methods atomically. - */ - callAtomic(calls: [string, VimValue[]][]): Promise<[any[], any[] | null]> - - /** - * Executes an ex-command by request. - */ - command(arg: string): Promise - - /** - * Executes an ex-command by notification. - */ - command(arg: string, isNotify: true): void - - /** - * Runs a command and returns output. - * - * **Note:** works on neovim only. - */ - commandOutput(arg: string): Promise - - /** - * Gets a v: variable. - */ - getVvar(name: string): Promise - - /** - * `:h nvim_feedkeys` - */ - feedKeys(keys: string, mode: string, escapeCsi: boolean): Promise - - /** - * Queues raw user-input. Unlike |nvim_feedkeys()|, this uses a - * low-level input buffer and the call is non-blocking (input is - * processed asynchronously by the eventloop). - * - * On execution error: does not fail, but updates v:errmsg. - * - * **Note:** works on neovim only. - */ - input(keys: string): Promise - - /** - * Parse a VimL Expression. - */ - parseExpression(expr: string, flags: string, highlight: boolean): Promise - - /** - * Get process info, neovim only. - * - * **Note:** works on neovim only. - */ - getProc(pid: number): Promise - - /** - * Gets the immediate children of process `pid`. - * - * **Note:** works on neovim only. - */ - getProcChildren(pid: number): Promise - - /** - * Replaces terminal codes and |keycodes| (, , ...) - * in a string with the internal representation. - * - * **Note:** works on neovim only. - */ - replaceTermcodes(str: string, fromPart: boolean, doIt: boolean, special: boolean): Promise - - /** - * Gets width(display cells) of string. - */ - strWidth(str: string): Promise - - /** - * Gets a list of dictionaries representing attached UIs. - * - * **Note:** works on neovim only. - */ - uis: Promise - - /** - * Subscribe to nvim event broadcasts. - * - * **Note:** works on neovim only. - */ - subscribe(event: string): Promise - - /** - * Unsubscribe to nvim event broadcasts - * - * **Note:** works on neovim only. - */ - unsubscribe(event: string): Promise - - /** - * Activates UI events on the channel. - * - * **Note:** works on neovim only. - */ - uiAttach(width: number, height: number, options: UiAttachOptions): Promise - - /** - * `:h nvim_ui_try_resize` - * - * **Note:** works on neovim only. - */ - uiTryResize(width: number, height: number): Promise - - /** - * Deactivates UI events on the channel. - * - * **Note:** works on neovim only. - */ - uiDetach(): Promise - - /** - * Quit vim. - */ - quit(): Promise - } - - export interface Buffer extends BaseApi { - id: number - - /** Total number of lines in buffer */ - length: Promise - - /** - * Get lines of buffer. - */ - lines: Promise - - /** - * Get changedtick of buffer. - */ - changedtick: Promise - - /** - * Add buffer keymap by notification. - */ - setKeymap(mode: string, lhs: string, rhs: string, opts?: BufferKeymapOption): void - - /** - * Add sign to buffer by notification. - * - * @param {SignPlaceOption} sign - */ - placeSign(sign: SignPlaceOption): void - - /** - * Unplace signs by notification - */ - unplaceSign(opts: SignUnplaceOption): void - - /** - * Get signs by group name or id and lnum. - * - * @param {SignPlacedOption} opts - */ - getSigns(opts: SignPlacedOption): Promise - - /** - * Get highlight items by namespace (end exclusive). - * - * @param {string | number} ns Namespace key or id. - * @param {number} start 0 based line number, default to 0. - * @param {number} end 0 based line number, default to -1. - */ - getHighlights(ns: string | number, start?: number, end?: number): Promise - - /** - * Update namespaced highlights in range by notification. - * - * @param {string | number} ns Namespace key or id. - * @param {HighlightItem[]} highlights Highlight items. - * @param {number} start 0 based line number, default to 0. - * @param {number} end 0 based line number, default to -1. - */ - updateHighlights(ns: string | number, highlights: HighlightItem[], start?: number, end?: number): void - - /** - * Gets a map of buffer-local |user-commands|. - * - * **Note:** works on neovim only. - */ - getCommands(options?: {}): Promise - - /** - * Get lines of buffer, get all lines by default. - */ - getLines(opts?: { start: number, end: number, strictIndexing?: boolean }): Promise - - /** - * Set lines of buffer given indeces use request. - */ - setLines(lines: string[], opts?: { start: number, end: number, strictIndexing?: boolean }): Promise - - /** - * Set lines of buffer given indeces use notification. - */ - setLines(lines: string[], opts: { start: number, end: number, strictIndexing?: boolean }, isNotify: true): void - - /** - * Set virtual text for a line - * - * @public - * @param {number} src_id - Source group to use or 0 to use a new group, or -1 - * @param {number} line - Line to annotate with virtual text (zero-indexed) - * @param {Chunk[]} chunks - List with [text, hl_group] - * @param {[index} opts - * @returns {Promise} - */ - setVirtualText(src_id: number, line: number, chunks: [string, string][], opts?: { [index: string]: any }): Promise - - /** - * Append a string or list of lines to end of buffer - */ - append(lines: string[] | string): Promise - - /** - * Get buffer name. - */ - name: Promise - - /** - * Set buffer name. - */ - setName(name: string): Promise - - /** - * Check if buffer valid. - */ - valid: Promise - - /** - * Get mark position given mark name - * - * **Note:** works on neovim only. - */ - mark(name: string): Promise<[number, number]> - - /** - * Gets a list of buffer-local |mapping| definitions. - * - * @return Array of maparg()-like dictionaries describing mappings. - * The "buffer" key holds the associated buffer handle. - */ - getKeymap(mode: string): Promise - - /** - * Check if buffer loaded. - */ - loaded: Promise - - /** - * Returns the byte offset for a line. - * - * Line 1 (index=0) has offset 0. UTF-8 bytes are counted. EOL is - * one byte. 'fileformat' and 'fileencoding' are ignored. The - * line index just after the last line gives the total byte-count - * of the buffer. A final EOL byte is counted if it would be - * written, see 'eol'. - * - * Unlike |line2byte()|, throws error for out-of-bounds indexing. - * Returns -1 for unloaded buffer. - * - * @return {Number} Integer byte offset, or -1 for unloaded buffer. - */ - getOffset(index: number): Promise - - /** - * Adds a highlight to buffer, checkout |nvim_buf_add_highlight|. - * - * Note: when `srcId = 0`, request is made for new `srcId`, otherwire, use notification. - * Note: `hlGroup` as empty string is not supported. - * - * @deprecated use `highlightRanges()` instead. - */ - addHighlight(opts: BufferHighlight): Promise - - /** - * Clear highlights of specified lins. - * - * @deprecated use clearNamespace instead. - */ - clearHighlight(args?: BufferClearHighlight) - - /** - * Add highlight to ranges by notification, works on both vim & neovim. - * - * Works on neovim and `workspace.isVim && workspace.env.textprop` is true - * - * @param {string | number} srcId Unique key or namespace number. - * @param {string} hlGroup Highlight group. - * @param {Range[]} ranges List of highlight ranges - */ - highlightRanges(srcId: string | number, hlGroup: string, ranges: Range[]): void - - /** - * Clear namespace by id or name by notification, works on both vim & neovim. - * - * Works on neovim and `workspace.isVim && workspace.env.textprop` is true - * - * @param key Unique key or namespace number, use -1 for all namespaces - * @param lineStart Start of line, 0 based, default to 0. - * @param lineEnd End of line, 0 based, default to -1. - */ - clearNamespace(key: number | string, lineStart?: number, lineEnd?: number) - } - - export interface Window extends BaseApi { - /** - * The windowid that not change within a Vim session - */ - id: number - - /** - * Buffer in window. - */ - buffer: Promise - - /** - * Tabpage contains window. - */ - tabpage: Promise - - /** - * Cursor position as [line, col], 1 based. - */ - cursor: Promise<[number, number]> - - /** - * Window height. - */ - height: Promise - - /** - * Window width. - */ - width: Promise - - /** - * Set cursor position by request. - */ - setCursor(pos: [number, number]): Promise - - /** - * Set cursor position by notification. - */ - setCursor(pos: [number, number], isNotify: true): void - - /** - * Set height - */ - setHeight(height: number): Promise - - /** - * Set height by notification. - */ - setHeight(height: number, isNotify: true): void - - /** - * Set width. - */ - setWidth(width: number): Promise - - /** - * Set width by notification. - */ - setWidth(width: number, isNotify: true): void - - /** - * Get window position, not work with vim8's popup. - */ - position: Promise<[number, number]> - - /** 0-indexed, on-screen window position(row) in display cells. */ - row: Promise - - /** 0-indexed, on-screen window position(col) in display cells. */ - col: Promise - - /** - * Check if window valid. - */ - valid: Promise - - /** - * Get window number, throws for invalid window. - */ - number: Promise - - /** - * Config float window with options. - * - * **Note:** works on neovim only. - */ - setConfig(options: NvimFloatOptions): Promise - - /** - * Config float window with options by send notification. - * - * **Note:** works on neovim only. - */ - setConfig(options: NvimFloatOptions, isNotify: true): void - - /** - * Gets window configuration. - * - * **Note:** works on neovim only. - * - * @returns Map defining the window configuration, see |nvim_open_win()| - */ - getConfig(): Promise - - /** - * Close window by send request. - */ - close(force: boolean): Promise - - /** - * Close window by send notification. - */ - close(force: boolean, isNotify: true): void - - /** - * Add highlight to ranges by request (matchaddpos is used) - * - * @return {Promise} match ids. - */ - highlightRanges(hlGroup: string, ranges: Range[], priority?: number): Promise - - /** - * Add highlight to ranges by notification (matchaddpos is used) - */ - highlightRanges(hlGroup: string, ranges: Range[], priority: number, isNotify: true): void - - /** - * Clear match of highlight group by send notification. - */ - clearMatchGroup(hlGroup: string): void - - /** - * Clear match of match ids by send notification. - */ - clearMatches(ids: number[]): void - } - - export interface Tabpage extends BaseApi { - /** - * tabpage number. - */ - number: Promise - - /** - * Is current tabpage valid. - */ - valid: Promise - - /** - * Returns all windows of tabpage. - */ - windows: Promise - - /** - * Current window of tabpage. - */ - window: Promise - } - // }} - - // vscode-uri {{ - export interface UriComponents { - scheme: string - authority: string - path: string - query: string - fragment: string - } - /** - * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986. - * This class is a simple parser which creates the basic component parts - * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation - * and encoding. - * - * ```txt - * foo://example.com:8042/over/there?name=ferret#nose - * \_/ \______________/\_________/ \_________/ \__/ - * | | | | | - * scheme authority path query fragment - * | _____________________|__ - * / \ / \ - * urn:example:animal:ferret:nose - * ``` - */ - export class Uri implements UriComponents { - static isUri(thing: any): thing is Uri - /** - * scheme is the 'http' part of 'http://www.msft.com/some/path?query#fragment'. - * The part before the first colon. - */ - readonly scheme: string - /** - * authority is the 'www.msft.com' part of 'http://www.msft.com/some/path?query#fragment'. - * The part between the first double slashes and the next slash. - */ - readonly authority: string - /** - * path is the '/some/path' part of 'http://www.msft.com/some/path?query#fragment'. - */ - readonly path: string - /** - * query is the 'query' part of 'http://www.msft.com/some/path?query#fragment'. - */ - readonly query: string - /** - * fragment is the 'fragment' part of 'http://www.msft.com/some/path?query#fragment'. - */ - readonly fragment: string - /** - * @internal - */ - protected constructor(scheme: string, authority?: string, path?: string, query?: string, fragment?: string, _strict?: boolean) - /** - * @internal - */ - protected constructor(components: UriComponents) - /** - * Returns a string representing the corresponding file system path of this URI. - * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the - * platform specific path separator. - * - * * Will *not* validate the path for invalid characters and semantics. - * * Will *not* look at the scheme of this URI. - * * The result shall *not* be used for display purposes but for accessing a file on disk. - * - * - * The *difference* to `URI#path` is the use of the platform specific separator and the handling - * of UNC paths. See the below sample of a file-uri with an authority (UNC path). - * - * ```ts - const u = URI.parse('file://server/c$/folder/file.txt') - u.authority === 'server' - u.path === '/shares/c$/file.txt' - u.fsPath === '\\server\c$\folder\file.txt' - ``` - * - * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path, - * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working - * with URIs that represent files on disk (`file` scheme). - */ - readonly fsPath: string - with(change: { - scheme?: string - authority?: string | null - path?: string | null - query?: string | null - fragment?: string | null - }): Uri - /** - * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`, - * `file:///usr/home`, or `scheme:with/path`. - * - * @param value A string which represents an URI (see `URI#toString`). - */ - static parse(value: string, _strict?: boolean): Uri - /** - * Creates a new URI from a file system path, e.g. `c:\my\files`, - * `/usr/home`, or `\\server\share\some\path`. - * - * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument - * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as** - * `URI.parse('file://' + path)` because the path might contain characters that are - * interpreted (# and ?). See the following sample: - * ```ts - const good = URI.file('/coding/c#/project1'); - good.scheme === 'file'; - good.path === '/coding/c#/project1'; - good.fragment === ''; - const bad = URI.parse('file://' + '/coding/c#/project1'); - bad.scheme === 'file'; - bad.path === '/coding/c'; // path is now broken - bad.fragment === '/project1'; - ``` - * - * @param path A file system path (see `URI#fsPath`) - */ - static file(path: string): Uri - static from(components: { - scheme: string - authority?: string - path?: string - query?: string - fragment?: string - }): Uri - /** - * Creates a string representation for this URI. It's guaranteed that calling - * `URI.parse` with the result of this function creates an URI which is equal - * to this URI. - * - * * The result shall *not* be used for display purposes but for externalization or transport. - * * The result will be encoded using the percentage encoding and encoding happens mostly - * ignore the scheme-specific encoding rules. - * - * @param skipEncoding Do not encode the result, default is `false` - */ - toString(skipEncoding?: boolean): string - toJSON(): UriComponents - } - // }} - - // vim interfaces {{ - /** - * See `:h complete-items` - */ - export interface VimCompleteItem { - word: string - abbr?: string - menu?: string - info?: string - kind?: string - icase?: number - equal?: number - dup?: number - empty?: number - user_data?: string - } - - export interface LocationListItem { - bufnr: number - lnum: number - col: number - text: string - type: string - } - - export interface QuickfixItem { - uri?: string - bufnr?: number - module?: string - range?: Range - text?: string - type?: string - filename?: string - lnum?: number - col?: number - valid?: boolean - nr?: number - } - // }} - - // provider interfaces {{ - /** - * A provider result represents the values a provider, like the [`HoverProvider`](#HoverProvider), - * may return. For once this is the actual result type `T`, like `Hover`, or a thenable that resolves - * to that type `T`. In addition, `null` and `undefined` can be returned - either directly or from a - * thenable. - * - * The snippets below are all valid implementations of the [`HoverProvider`](#HoverProvider): - * - * ```ts - * let a: HoverProvider = { - * provideHover(doc, pos, token): ProviderResult { - * return new Hover('Hello World') - * } - * } - * - * let b: HoverProvider = { - * provideHover(doc, pos, token): ProviderResult { - * return new Promise(resolve => { - * resolve(new Hover('Hello World')) - * }) - * } - * } - * - * let c: HoverProvider = { - * provideHover(doc, pos, token): ProviderResult { - * return; // undefined - * } - * } - * ``` - */ - export type ProviderResult = - | T - | undefined - | null - | Thenable - - /** - * Supported provider names. - */ - export type ProviderName = 'rename' | 'onTypeEdit' | 'documentLink' | 'documentColor' - | 'foldingRange' | 'format' | 'codeAction' | 'workspaceSymbols' | 'formatRange' | 'formatOnType' - | 'hover' | 'signature' | 'documentSymbol' | 'documentHighlight' | 'definition' - | 'declaration' | 'typeDefinition' | 'reference' | 'implementation' - | 'codeLens' | 'selectionRange' | 'callHierarchy' | 'semanticTokens' | 'linkedEditing' - - /** - * The completion item provider interface defines the contract between extensions and - * [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense). - * - * Providers can delay the computation of the [`detail`](#CompletionItem.detail) - * and [`documentation`](#CompletionItem.documentation) properties by implementing the - * [`resolveCompletionItem`](#CompletionItemProvider.resolveCompletionItem)-function. However, properties that - * are needed for the initial sorting and filtering, like `sortText`, `filterText`, `insertText`, and `range`, must - * not be changed during resolve. - * - * Providers are asked for completions either explicitly by a user gesture or -depending on the configuration- - * implicitly when typing words or trigger characters. - */ - export interface CompletionItemProvider { - /** - * Provide completion items for the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @param context How the completion was triggered. - * - * @return An array of completions, a [completion list](#CompletionList), or a thenable that resolves to either. - * The lack of a result can be signaled by returning `undefined`, `null`, or an empty array. - */ - provideCompletionItems( - document: TextDocument, - position: Position, - token: CancellationToken, - context?: CompletionContext - ): ProviderResult - - /** - * Given a completion item fill in more data, like [doc-comment](#CompletionItem.documentation) - * or [details](#CompletionItem.detail). - * - * The editor will only resolve a completion item once. - * - * @param item A completion item currently active in the UI. - * @param token A cancellation token. - * @return The resolved completion item or a thenable that resolves to of such. It is OK to return the given - * `item`. When no result is returned, the given `item` will be used. - */ - resolveCompletionItem?( - item: CompletionItem, - token: CancellationToken - ): ProviderResult - } - - /** - * The hover provider interface defines the contract between extensions and - * the [hover](https://code.visualstudio.com/docs/editor/intellisense)-feature. - */ - export interface HoverProvider { - /** - * Provide a hover for the given position and document. Multiple hovers at the same - * position will be merged by the editor. A hover can have a range which defaults - * to the word range at the position when omitted. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return A hover or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideHover( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult - } - - /** - * The definition provider interface defines the contract between extensions and - * the [go to definition](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-definition) - * and peek definition features. - */ - export interface DefinitionProvider { - /** - * Provide the definition of the symbol at the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return A definition or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideDefinition( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult - } - - /** - * The definition provider interface defines the contract between extensions and - * the [go to definition](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-definition) - * and peek definition features. - */ - export interface DeclarationProvider { - /** - * Provide the declaration of the symbol at the given position and document. - */ - provideDeclaration( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult - } - - /** - * The signature help provider interface defines the contract between extensions and - * the [parameter hints](https://code.visualstudio.com/docs/editor/intellisense)-feature. - */ - export interface SignatureHelpProvider { - /** - * Provide help for the signature at the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return Signature help or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideSignatureHelp( - document: TextDocument, - position: Position, - token: CancellationToken, - context: SignatureHelpContext - ): ProviderResult - } - - /** - * The type definition provider defines the contract between extensions and - * the go to type definition feature. - */ - export interface TypeDefinitionProvider { - /** - * Provide the type definition of the symbol at the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return A definition or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideTypeDefinition( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult - } - - /** - * Value-object that contains additional information when - * requesting references. - */ - export interface ReferenceContext { - /** - * Include the declaration of the current symbol. - */ - includeDeclaration: boolean - } - - /** - * The reference provider interface defines the contract between extensions and - * the [find references](https://code.visualstudio.com/docs/editor/editingevolved#_peek)-feature. - */ - export interface ReferenceProvider { - /** - * Provide a set of project-wide references for the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param context - * @param token A cancellation token. - * @return An array of locations or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideReferences( - document: TextDocument, - position: Position, - context: ReferenceContext, - token: CancellationToken - ): ProviderResult - } - - /** - * Folding context (for future use) - */ - export interface FoldingContext {} - - /** - * The folding range provider interface defines the contract between extensions and - * [Folding](https://code.visualstudio.com/docs/editor/codebasics#_folding) in the editor. - */ - export interface FoldingRangeProvider { - /** - * Returns a list of folding ranges or null and undefined if the provider - * does not want to participate or was cancelled. - * - * @param document The document in which the command was invoked. - * @param context Additional context information (for future use) - * @param token A cancellation token. - */ - provideFoldingRanges( - document: TextDocument, - context: FoldingContext, - token: CancellationToken - ): ProviderResult - } - - /** - * The document symbol provider interface defines the contract between extensions and - * the [go to symbol](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-symbol)-feature. - */ - export interface DocumentSymbolProvider { - /** - * Provide symbol information for the given document. - * - * @param document The document in which the command was invoked. - * @param token A cancellation token. - * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentSymbols( - document: TextDocument, - token: CancellationToken - ): ProviderResult - } - - /** - * The implemenetation provider interface defines the contract between extensions and - * the go to implementation feature. - */ - export interface ImplementationProvider { - /** - * Provide the implementations of the symbol at the given position and document. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return A definition or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideImplementation( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult - } - - /** - * The workspace symbol provider interface defines the contract between extensions and - * the [symbol search](https://code.visualstudio.com/docs/editor/editingevolved#_open-symbol-by-name)-feature. - */ - export interface WorkspaceSymbolProvider { - /** - * Project-wide search for a symbol matching the given query string. It is up to the provider - * how to search given the query string, like substring, indexOf etc. To improve performance implementors can - * skip the [location](#SymbolInformation.location) of symbols and implement `resolveWorkspaceSymbol` to do that - * later. - * - * The `query`-parameter should be interpreted in a *relaxed way* as the editor will apply its own highlighting - * and scoring on the results. A good rule of thumb is to match case-insensitive and to simply check that the - * characters of *query* appear in their order in a candidate symbol. Don't use prefix, substring, or similar - * strict matching. - * - * @param query A non-empty query string. - * @param token A cancellation token. - * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideWorkspaceSymbols( - query: string, - token: CancellationToken - ): ProviderResult - - /** - * Given a symbol fill in its [location](#SymbolInformation.location). This method is called whenever a symbol - * is selected in the UI. Providers can implement this method and return incomplete symbols from - * [`provideWorkspaceSymbols`](#WorkspaceSymbolProvider.provideWorkspaceSymbols) which often helps to improve - * performance. - * - * @param symbol The symbol that is to be resolved. Guaranteed to be an instance of an object returned from an - * earlier call to `provideWorkspaceSymbols`. - * @param token A cancellation token. - * @return The resolved symbol or a thenable that resolves to that. When no result is returned, - * the given `symbol` is used. - */ - resolveWorkspaceSymbol?( - symbol: SymbolInformation, - token: CancellationToken - ): ProviderResult - } - - /** - * The rename provider interface defines the contract between extensions and - * the [rename](https://code.visualstudio.com/docs/editor/editingevolved#_rename-symbol)-feature. - */ - export interface RenameProvider { - /** - * Provide an edit that describes changes that have to be made to one - * or many resources to rename a symbol to a different name. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param newName The new name of the symbol. If the given name is not valid, the provider must return a rejected promise. - * @param token A cancellation token. - * @return A workspace edit or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideRenameEdits( - document: TextDocument, - position: Position, - newName: string, - token: CancellationToken - ): ProviderResult - - /** - * Optional function for resolving and validating a position *before* running rename. The result can - * be a range or a range and a placeholder text. The placeholder text should be the identifier of the symbol - * which is being renamed - when omitted the text in the returned range is used. - * - * @param document The document in which rename will be invoked. - * @param position The position at which rename will be invoked. - * @param token A cancellation token. - * @return The range or range and placeholder text of the identifier that is to be renamed. The lack of a result can signaled by returning `undefined` or `null`. - */ - prepareRename?( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult - } - - /** - * The document formatting provider interface defines the contract between extensions and - * the formatting-feature. - */ - export interface DocumentFormattingEditProvider { - /** - * Provide formatting edits for a whole document. - * - * @param document The document in which the command was invoked. - * @param options Options controlling formatting. - * @param token A cancellation token. - * @return A set of text edits or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentFormattingEdits( - document: TextDocument, - options: FormattingOptions, - token: CancellationToken - ): ProviderResult - } - - /** - * The document formatting provider interface defines the contract between extensions and - * the formatting-feature. - */ - export interface DocumentRangeFormattingEditProvider { - /** - * Provide formatting edits for a range in a document. - * - * The given range is a hint and providers can decide to format a smaller - * or larger range. Often this is done by adjusting the start and end - * of the range to full syntax nodes. - * - * @param document The document in which the command was invoked. - * @param range The range which should be formatted. - * @param options Options controlling formatting. - * @param token A cancellation token. - * @return A set of text edits or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentRangeFormattingEdits( - document: TextDocument, - range: Range, - options: FormattingOptions, - token: CancellationToken - ): ProviderResult - } - - /** - * The code action interface defines the contract between extensions and - * the [light bulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature. - * - * A code action can be any command that is [known](#commands.getCommands) to the system. - */ - export interface CodeActionProvider { - /** - * Provide commands for the given document and range. - * - * @param document The document in which the command was invoked. - * @param range The selector or range for which the command was invoked. This will always be a selection if - * there is a currently active editor. - * @param context Context carrying additional information. - * @param token A cancellation token. - * @return An array of commands, quick fixes, or refactorings or a thenable of such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideCodeActions( - document: TextDocument, - range: Range, - context: CodeActionContext, - token: CancellationToken - ): ProviderResult<(Command | CodeAction)[]> - - /** - * Given a code action fill in its [`edit`](#CodeAction.edit)-property. Changes to - * all other properties, like title, are ignored. A code action that has an edit - * will not be resolved. - * - * @param codeAction A code action. - * @param token A cancellation token. - * @return The resolved code action or a thenable that resolves to such. It is OK to return the given - * `item`. When no result is returned, the given `item` will be used. - */ - resolveCodeAction?(codeAction: T, token: CancellationToken): ProviderResult - } - - /** - * Metadata about the type of code actions that a [CodeActionProvider](#CodeActionProvider) providers - */ - export interface CodeActionProviderMetadata { - /** - * [CodeActionKinds](#CodeActionKind) that this provider may return. - * - * The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the provider - * may list our every specific kind they provide, such as `CodeActionKind.Refactor.Extract.append('function`)` - */ - readonly providedCodeActionKinds?: ReadonlyArray - } - - /** - * The document highlight provider interface defines the contract between extensions and - * the word-highlight-feature. - */ - export interface DocumentHighlightProvider { - - /** - * Provide a set of document highlights, like all occurrences of a variable or - * all exit-points of a function. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentHighlights( - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult - } - - /** - * The document link provider defines the contract between extensions and feature of showing - * links in the editor. - */ - export interface DocumentLinkProvider { - - /** - * Provide links for the given document. Note that the editor ships with a default provider that detects - * `http(s)` and `file` links. - * - * @param document The document in which the command was invoked. - * @param token A cancellation token. - * @return An array of [document links](#DocumentLink) or a thenable that resolves to such. The lack of a result - * can be signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentLinks(document: TextDocument, token: CancellationToken): ProviderResult - - /** - * Given a link fill in its [target](#DocumentLink.target). This method is called when an incomplete - * link is selected in the UI. Providers can implement this method and return incomple links - * (without target) from the [`provideDocumentLinks`](#DocumentLinkProvider.provideDocumentLinks) method which - * often helps to improve performance. - * - * @param link The link that is to be resolved. - * @param token A cancellation token. - */ - resolveDocumentLink?(link: DocumentLink, token: CancellationToken): ProviderResult - } - - /** - * A code lens provider adds [commands](#Command) to source text. The commands will be shown - * as dedicated horizontal lines in between the source text. - */ - export interface CodeLensProvider { - - /** - * Compute a list of [lenses](#CodeLens). This call should return as fast as possible and if - * computing the commands is expensive implementors should only return code lens objects with the - * range set and implement [resolve](#CodeLensProvider.resolveCodeLens). - * - * @param document The document in which the command was invoked. - * @param token A cancellation token. - * @return An array of code lenses or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideCodeLenses(document: TextDocument, token: CancellationToken): ProviderResult - - /** - * This function will be called for each visible code lens, usually when scrolling and after - * calls to [compute](#CodeLensProvider.provideCodeLenses)-lenses. - * - * @param codeLens code lens that must be resolved. - * @param token A cancellation token. - * @return The given, resolved code lens or thenable that resolves to such. - */ - resolveCodeLens?(codeLens: CodeLens, token: CancellationToken): ProviderResult - } - - /** - * The document formatting provider interface defines the contract between extensions and - * the formatting-feature. - */ - export interface OnTypeFormattingEditProvider { - - /** - * Provide formatting edits after a character has been typed. - * - * The given position and character should hint to the provider - * what range the position to expand to, like find the matching `{` - * when `}` has been entered. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param ch The character that has been typed. - * @param options Options controlling formatting. - * @param token A cancellation token. - * @return A set of text edits or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined`, `null`, or an empty array. - */ - provideOnTypeFormattingEdits(document: TextDocument, position: Position, ch: string, options: FormattingOptions, token: CancellationToken): ProviderResult - } - - /** - * The document color provider defines the contract between extensions and feature of - * picking and modifying colors in the editor. - */ - export interface DocumentColorProvider { - - /** - * Provide colors for the given document. - * - * @param document The document in which the command was invoked. - * @param token A cancellation token. - * @return An array of [color information](#ColorInformation) or a thenable that resolves to such. The lack of a result - * can be signaled by returning `undefined`, `null`, or an empty array. - */ - provideDocumentColors(document: TextDocument, token: CancellationToken): ProviderResult - - /** - * Provide [representations](#ColorPresentation) for a color. - * - * @param color The color to show and insert. - * @param context A context object with additional information - * @param token A cancellation token. - * @return An array of color presentations or a thenable that resolves to such. The lack of a result - * can be signaled by returning `undefined`, `null`, or an empty array. - */ - provideColorPresentations(color: Color, context: { document: TextDocument; range: Range }, token: CancellationToken): ProviderResult - } - - export interface TextDocumentContentProvider { - - /** - * An event to signal a resource has changed. - */ - onDidChange?: Event - - /** - * Provide textual content for a given uri. - * - * The editor will use the returned string-content to create a readonly - * [document](#TextDocument). Resources allocated should be released when - * the corresponding document has been [closed](#workspace.onDidCloseTextDocument). - * - * @param uri An uri which scheme matches the scheme this provider was [registered](#workspace.registerTextDocumentContentProvider) for. - * @param token A cancellation token. - * @return A string or a thenable that resolves to such. - */ - provideTextDocumentContent(uri: Uri, token: CancellationToken): ProviderResult - } - - export interface SelectionRangeProvider { - /** - * Provide selection ranges starting at a given position. The first range must [contain](#Range.contains) - * position and subsequent ranges must contain the previous range. - */ - provideSelectionRanges(document: TextDocument, positions: Position[], token: CancellationToken): ProviderResult - } - - /** - * The call hierarchy provider interface describes the contract between extensions - * and the call hierarchy feature which allows to browse calls and caller of function, - * methods, constructor etc. - */ - export interface CallHierarchyProvider { - - /** - * Bootstraps call hierarchy by returning the item that is denoted by the given document - * and position. This item will be used as entry into the call graph. Providers should - * return `undefined` or `null` when there is no item at the given location. - * - * @param document The document in which the command was invoked. - * @param position The position at which the command was invoked. - * @param token A cancellation token. - * @returns A call hierarchy item or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - prepareCallHierarchy(document: TextDocument, position: Position, token: CancellationToken): ProviderResult - - /** - * Provide all incoming calls for an item, e.g all callers for a method. In graph terms this describes directed - * and annotated edges inside the call graph, e.g the given item is the starting node and the result is the nodes - * that can be reached. - * - * @param item The hierarchy item for which incoming calls should be computed. - * @param token A cancellation token. - * @returns A set of incoming calls or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideCallHierarchyIncomingCalls(item: CallHierarchyItem, token: CancellationToken): ProviderResult - - /** - * Provide all outgoing calls for an item, e.g call calls to functions, methods, or constructors from the given item. In - * graph terms this describes directed and annotated edges inside the call graph, e.g the given item is the starting - * node and the result is the nodes that can be reached. - * - * @param item The hierarchy item for which outgoing calls should be computed. - * @param token A cancellation token. - * @returns A set of outgoing calls or a thenable that resolves to such. The lack of a result can be - * signaled by returning `undefined` or `null`. - */ - provideCallHierarchyOutgoingCalls(item: CallHierarchyItem, token: CancellationToken): ProviderResult - } - - /** - * The document semantic tokens provider interface defines the contract between extensions and - * semantic tokens. - */ - export interface DocumentSemanticTokensProvider { - /** - * An optional event to signal that the semantic tokens from this provider have changed. - */ - // TODO: SemantiTokens - onDidChangeSemanticTokens?: Event - - /** - * Tokens in a file are represented as an array of integers. The position of each token is expressed relative to - * the token before it, because most tokens remain stable relative to each other when edits are made in a file. - * - * --- - * In short, each token takes 5 integers to represent, so a specific token `i` in the file consists of the following array indices: - * - * - at index `5*i` - `deltaLine`: token line number, relative to the previous token - * - at index `5*i+1` - `deltaStart`: token start character, relative to the previous token (relative to 0 or the previous token's start if they are on the same line) - * - at index `5*i+2` - `length`: the length of the token. A token cannot be multiline. - * - at index `5*i+3` - `tokenType`: will be looked up in `SemanticTokensLegend.tokenTypes`. We currently ask that `tokenType` < 65536. - * - at index `5*i+4` - `tokenModifiers`: each set bit will be looked up in `SemanticTokensLegend.tokenModifiers` - * - * --- - * ### How to encode tokens - * - * Here is an example for encoding a file with 3 tokens in a uint32 array: - * ``` - * { line: 2, startChar: 5, length: 3, tokenType: "property", tokenModifiers: ["private", "static"] }, - * { line: 2, startChar: 10, length: 4, tokenType: "type", tokenModifiers: [] }, - * { line: 5, startChar: 2, length: 7, tokenType: "class", tokenModifiers: [] } - * ``` - * - * 1. First of all, a legend must be devised. This legend must be provided up-front and capture all possible token types. - * For this example, we will choose the following legend which must be passed in when registering the provider: - * ``` - * tokenTypes: ['property', 'type', 'class'], - * tokenModifiers: ['private', 'static'] - * ``` - * - * 2. The first transformation step is to encode `tokenType` and `tokenModifiers` as integers using the legend. Token types are looked - * up by index, so a `tokenType` value of `1` means `tokenTypes[1]`. Multiple token modifiers can be set by using bit flags, - * so a `tokenModifier` value of `3` is first viewed as binary `0b00000011`, which means `[tokenModifiers[0], tokenModifiers[1]]` because - * bits 0 and 1 are set. Using this legend, the tokens now are: - * ``` - * { line: 2, startChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 }, - * { line: 2, startChar: 10, length: 4, tokenType: 1, tokenModifiers: 0 }, - * { line: 5, startChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 } - * ``` - * - * 3. The next step is to represent each token relative to the previous token in the file. In this case, the second token - * is on the same line as the first token, so the `startChar` of the second token is made relative to the `startChar` - * of the first token, so it will be `10 - 5`. The third token is on a different line than the second token, so the - * `startChar` of the third token will not be altered: - * ``` - * { deltaLine: 2, deltaStartChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 }, - * { deltaLine: 0, deltaStartChar: 5, length: 4, tokenType: 1, tokenModifiers: 0 }, - * { deltaLine: 3, deltaStartChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 } - * ``` - * - * 4. Finally, the last step is to inline each of the 5 fields for a token in a single array, which is a memory friendly representation: - * ``` - * // 1st token, 2nd token, 3rd token - * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] - * ``` - * - * @see [SemanticTokensBuilder](#SemanticTokensBuilder) for a helper to encode tokens as integers. - * *NOTE*: When doing edits, it is possible that multiple edits occur until VS Code decides to invoke the semantic tokens provider. - * *NOTE*: If the provider cannot temporarily compute semantic tokens, it can indicate this by throwing an error with the message 'Busy'. - */ - provideDocumentSemanticTokens(document: TextDocument, token: CancellationToken): ProviderResult - - /** - * Instead of always returning all the tokens in a file, it is possible for a `DocumentSemanticTokensProvider` to implement - * this method (`provideDocumentSemanticTokensEdits`) and then return incremental updates to the previously provided semantic tokens. - * - * --- - * ### How tokens change when the document changes - * - * Suppose that `provideDocumentSemanticTokens` has previously returned the following semantic tokens: - * ``` - * // 1st token, 2nd token, 3rd token - * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] - * ``` - * - * Also suppose that after some edits, the new semantic tokens in a file are: - * ``` - * // 1st token, 2nd token, 3rd token - * [ 3,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] - * ``` - * It is possible to express these new tokens in terms of an edit applied to the previous tokens: - * ``` - * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] // old tokens - * [ 3,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] // new tokens - * - * edit: { start: 0, deleteCount: 1, data: [3] } // replace integer at offset 0 with 3 - * ``` - * - * *NOTE*: If the provider cannot compute `SemanticTokensEdits`, it can "give up" and return all the tokens in the document again. - * *NOTE*: All edits in `SemanticTokensEdits` contain indices in the old integers array, so they all refer to the previous result state. - */ - provideDocumentSemanticTokensEdits?(document: TextDocument, previousResultId: string, token: CancellationToken): ProviderResult - } - - /** - * The document range semantic tokens provider interface defines the contract between extensions and - * semantic tokens. - */ - export interface DocumentRangeSemanticTokensProvider { - /** - * @see [provideDocumentSemanticTokens](#DocumentSemanticTokensProvider.provideDocumentSemanticTokens). - */ - provideDocumentRangeSemanticTokens(document: TextDocument, range: Range, token: CancellationToken): ProviderResult - } - - export interface LinkedEditingRangeProvider { - /** - * For a given position in a document, returns the range of the symbol at the position and all ranges - * that have the same content. A change to one of the ranges can be applied to all other ranges if the new content - * is valid. An optional word pattern can be returned with the result to describe valid contents. - * If no result-specific word pattern is provided, the word pattern from the language configuration is used. - * - * @param document The document in which the provider was invoked. - * @param position The position at which the provider was invoked. - * @param token A cancellation token. - * @return A list of ranges that can be edited together - */ - provideLinkedEditingRanges(document: TextDocument, position: Position, token: CancellationToken): ProviderResult - } - // }} - - // Classes {{ - - export interface FloatWinConfig { - maxHeight?: number - maxWidth?: number - preferTop?: boolean - autoHide?: boolean - offsetX?: number - title?: string - border?: number[] - cursorline?: boolean - close?: boolean - highlight?: string - borderhighlight?: string - modes?: string[] - shadow?: boolean - winblend?: number - focusable?: boolean - excludeImages?: boolean - } - - export interface Documentation { - /** - * Filetype used for highlight, markdown is supported. - */ - filetype: string - /** - * Content of document. - */ - content: string - /** - * Byte offset (0 based) that should be undelined. - */ - active?: [number, number] - } - - /** - * Float window factory for create float around current cursor, works on vim and neovim. - * Use `workspace.floatSupported` to check if float could work. - * - * Float windows are automatic reused and hidden on specific events including: - * - BufEnter - * - InsertEnter - * - InsertLeave - * - MenuPopupChanged - * - CursorMoved - * - CursorMovedI - */ - export class FloatFactory implements Disposable { - get bufnr(): number | undefined - get buffer(): Buffer | null - get window(): Window | null - activated(): Promise - - constructor(nvim: Neovim) - - /** - * Show documentations in float window/popup around cursor. - * Window and buffer are reused when possible. - * Window is closed automatically on change buffer, InsertEnter, CursorMoved and CursorMovedI. - * - * @param docs List of documentations. - * @param config Configuration for floating window/popup. - */ - show(docs: Documentation[], config?: FloatWinConfig): Promise - - /** - * Close float window. - */ - close(): void - dispose(): void - } - - /** - * Build buffer with lines and highlights - */ - export class Highlighter { - constructor(srcId?: number) - /** - * Add a line with highlight group. - */ - addLine(line: string, hlGroup?: string): void - /** - * Add lines without highlights. - */ - addLines(lines: string[]): void - /** - * Add text with highlight. - */ - addText(text: string, hlGroup?: string): void - /** - * Get line count - */ - get length(): number - /** - * Render lines to buffer at specified range. - * Since notifications is used, use `nvim.pauseNotification` & `nvim.resumeNotification` - * when you need to wait for the request finish. - * - * @param {Buffer} buffer - * @param {number} start - * @param {number} end - * @returns {void} - */ - render(buffer: Buffer, start?: number, end?: number): void - } - - export interface ListConfiguration { - get(key: string, defaultValue?: T): T - previousKey(): string - nextKey(): string - dispose(): void - } - - export interface ListActionOptions { - persist?: boolean - reload?: boolean - parallel?: boolean - } - - export interface CommandTaskOption { - /** - * Command to run. - */ - cmd: string - /** - * Arguments of command. - */ - args: string[] - cwd: string - /** - * Runs for each line, return undefined for invalid item. - */ - onLine: (line: string) => ListItem | undefined - } - - export interface CommandTask extends ListTask { - } - - export abstract class BasicList implements IList { - /** - * Unique name, must be provided by implementation class. - */ - name: string - /** - * Default action name invoked by by default, must be provided by implementation class. - */ - defaultAction: string - /** - * Registered actions. - */ - readonly actions: ListAction[] - /** - * Arguments configuration of list. - */ - options: ListArgument[] - protected nvim: Neovim - protected disposables: Disposable[] - protected config: ListConfiguration - constructor(nvim: Neovim) - /** - * Should align columns when true. - */ - get alignColumns(): boolean - get hlGroup(): string - get previewHeight(): string - get splitRight(): boolean - /** - * Parse argument string array for argument object from `this.options`. - * Could be used inside `this.loadItems()` - */ - protected parseArguments(args: string[]): { [key: string]: string | boolean } - /** - * Get configurations of current list - */ - protected getConfig(): WorkspaceConfiguration - /** - * Add an action - */ - protected addAction(name: string, fn: (item: ListItem, context: ListContext) => ProviderResult, options?: ListActionOptions): void - /** - * Add action that support multiple selection. - */ - protected addMultipleAction(name: string, fn: (item: ListItem[], context: ListContext) => ProviderResult, options?: ListActionOptions): void - /** - * Create task from command task option. - */ - protected createCommandTask(opt: CommandTaskOption): ListTask - /** - * Add location related actions, should be called in constructor. - */ - protected addLocationActions(): void - protected convertLocation(location: Location | LocationWithLine | string): Promise - /** - * Jump to location - * - * @method - */ - protected jumpTo(location: Location | LocationWithLine | string, command?: string): Promise - /** - * Preview location. - * - * @method - */ - protected previewLocation(location: Location, context: ListContext): Promise - /** - * Preview lines. - * - * @method - */ - protected preview(options: PreviewOptions, context: ListContext): Promise - /** - * Use for syntax highlights, invoked after buffer loaded. - */ - doHighlight(): void - /** - * Invoked for listItems or listTask, could throw error when failed to load. - */ - abstract loadItems(context: ListContext, token?: CancellationToken): Promise - } - - export class Mutex { - /** - * Returns true when task is running. - */ - get busy(): boolean - /** - * Resolved release function that must be called after task finish. - */ - acquire(): Promise<() => void> - /** - * Captrue the async task function that ensures to be executed one by one. - */ - use(f: () => Promise): Promise - } - // }} - - // functions {{ - - export interface AnsiItem { - foreground?: string - background?: string - bold?: boolean - italic?: boolean - underline?: boolean - text: string - } - - export interface ParsedUrlQueryInput { - [key: string]: unknown - } - - export interface FetchOptions { - /** - * Default to 'GET' - */ - method?: string - /** - * Default no timeout - */ - timeout?: number - /** - * Always return buffer instead of parsed response. - */ - buffer?: boolean - /** - * Data send to server. - */ - data?: string | { [key: string]: any } | Buffer - /** - * Plain object added as query of url - */ - query?: ParsedUrlQueryInput - headers?: any - /** - * User for http basic auth, should use with password - */ - user?: string - /** - * Password for http basic auth, should use with user - */ - password?: string - } - - export interface DownloadOptions extends Omit { - /** - * Folder that contains downloaded file or extracted files by untar or unzip - */ - dest: string - /** - * Remove the specified number of leading path elements for *untar* only, default to `1`. - */ - strip?: number - /** - * If true, use untar for `.tar.gz` filename - */ - extract?: boolean | 'untar' | 'unzip' - onProgress?: (percent: string) => void - } - - export type ResponseResult = string | Buffer | { - [name: string]: any - } - - /** - * Parse ansi result from string contains ansi characters. - */ - export function ansiparse(str: string): AnsiItem[] - - /** - * Send request to server for response, supports: - * - * - Send json data and parse json response. - * - Throw error for failed response statusCode. - * - Timeout support (no timeout by default). - * - Send buffer (as data) and receive data (as response). - * - Proxy support from user configuration & environment. - * - Redirect support, limited to 3. - * - Support of gzip & deflate response content. - * - * @return Parsed object if response content type is application/json, text if content type starts with `text/` - */ - export function fetch(url: string, options?: FetchOptions, token?: CancellationToken): Promise - - /** - * Download file from url, with optional untar/unzip support. - * - * Note: you may need to set `strip` to 0 when using untar as extract method. - * - * @param {string} url - * @param {DownloadOptions} options contains dest folder and optional onProgress callback - */ - export function download(url: string, options: DownloadOptions, token?: CancellationToken): Promise - - interface ExecOptions { - cwd?: string - env?: NodeJS.ProcessEnv - shell?: string - timeout?: number - maxBuffer?: number - killSignal?: string - uid?: number - gid?: number - windowsHide?: boolean - } - - /** - * Dispose all disposables. - */ - export function disposeAll(disposables: Disposable[]): void - - /** - * Concurrent run async functions with limit support. - */ - export function concurrent(arr: T[], fn: (val: T) => Promise, limit?: number): Promise - - /** - * Create promise resolved after ms miliseconds. - */ - export function wait(ms: number): Promise - - /** - * Run command with `child_process.exec` - */ - export function runCommand(cmd: string, opts?: ExecOptions, timeout?: number): Promise - - /** - * Check if process with pid is running - */ - export function isRunning(pid: number): boolean - - /** - * Check if command is executable. - */ - export function executable(command: string): boolean - - /** - * Watch single file for change, the filepath needs to be exists file. - * - * @param filepath Full path of file. - * @param onChange Handler on file change detected. - */ - export function watchFile(filepath: string, onChange: () => void): Disposable - // }} - - // commands module {{ - export interface CommandItem { - id: string - internal?: boolean - execute(...args: any[]): any - } - /** - * Namespace for dealing with commands of coc.nvim - */ - export namespace commands { - /** - * Registered commands. - */ - export const commandList: CommandItem[] - - /** - * Execute specified command. - * - * @deprecated use `executeCommand()` instead. - */ - export function execute(command: { name: string, arguments?: any[] }): void - - /** - * Check if command is registered. - * - * @param id Unique id of command. - */ - export function has(id: string): boolean - - /** - * Registers a command that can be invoked via a keyboard shortcut, - * a menu item, an action, or directly. - * - * Registering a command with an existing command identifier twice - * will cause an error. - * - * @param command A unique identifier for the command. - * @param impl A command handler function. - * @param thisArg The `this` context used when invoking the handler function. - * @return Disposable which unregisters this command on disposal. - */ - export function registerCommand(id: string, impl: (...args: any[]) => void, thisArg?: any, internal?: boolean): Disposable - - /** - * Executes the command denoted by the given command identifier. - * - * * *Note 1:* When executing an editor command not all types are allowed to - * be passed as arguments. Allowed are the primitive types `string`, `boolean`, - * `number`, `undefined`, and `null`, as well as [`Position`](#Position), [`Range`](#Range), [`URI`](#URI) and [`Location`](#Location). - * * *Note 2:* There are no restrictions when executing commands that have been contributed - * by extensions. - * - * @param command Identifier of the command to execute. - * @param rest Parameters passed to the command function. - * @return A promise that resolves to the returned value of the given command. `undefined` when - * the command handler function doesn't return anything. - */ - export function executeCommand(command: string, ...rest: any[]): Promise - - /** - * Open uri with external tool, use `open` on mac, use `xdg-open` on linux. - */ - export function executeCommand(command: 'vscode.open', uri: string | Uri): Promise - - /** - * Reload current buffer by `:edit` command. - */ - export function executeCommand(command: 'workbench.action.reloadWindow'): Promise - - /** - * Insert snippet at range of current buffer. - * - * @param edit Contains snippet text and range to replace. - */ - export function executeCommand(command: 'editor.action.insertSnippet', edit: TextEdit): Promise - - /** - * Invoke specified code action. - */ - export function executeCommand(command: 'editor.action.doCodeAction', action: CodeAction): Promise - - /** - * Trigger coc.nvim's completion at current cursor position. - */ - export function executeCommand(command: 'editor.action.triggerSuggest'): Promise - - /** - * Trigger signature help at current cursor position. - */ - export function executeCommand(command: 'editor.action.triggerParameterHints'): Promise - - /** - * Add ranges to cursors session for multiple cursors. - */ - export function executeCommand(command: 'editor.action.addRanges', ranges: Range[]): Promise - - /** - * Restart coc.nvim service by `:CocRestart` command. - */ - export function executeCommand(command: 'editor.action.restart'): Promise - - /** - * Show locations by location list or vim's quickfix list. - */ - export function executeCommand(command: 'editor.action.showReferences', filepath: string | undefined, position: Position | undefined, locations: Location[]): Promise - - /** - * Invoke rename action at position of specified uri. - */ - export function executeCommand(command: 'editor.action.rename', uri: string, position: Position): Promise - - /** - * Run format action for current buffer. - */ - export function executeCommand(command: 'editor.action.format'): Promise - } - // }} - - // events module {{ - type MoveEvents = 'CursorMoved' | 'CursorMovedI' - type EventResult = void | Promise - type BufEvents = 'BufHidden' | 'BufEnter' | 'BufWritePost' - | 'CursorHold' | 'InsertLeave' | 'TermOpen' | 'TermClose' | 'InsertEnter' - | 'BufCreate' | 'BufUnload' | 'BufWritePre' | 'CursorHoldI' | 'Enter' - type EmptyEvents = 'FocusGained' | 'FocusLost' | 'InsertSnippet' - type InsertChangeEvents = 'TextChangedP' | 'TextChangedI' - type TaskEvents = 'TaskExit' | 'TaskStderr' | 'TaskStdout' - type WindowEvents = 'WinLeave' | 'WinEnter' - type AllEvents = BufEvents | EmptyEvents | MoveEvents | TaskEvents | WindowEvents | InsertChangeEvents | 'CompleteDone' | 'TextChanged' | 'MenuPopupChanged' | 'InsertCharPre' | 'FileType' | 'BufWinEnter' | 'BufWinLeave' | 'VimResized' | 'DirChanged' | 'OptionSet' | 'Command' | 'BufReadCmd' | 'GlobalChange' | 'InputChar' | 'WinLeave' | 'MenuInput' | 'PromptInsert' | 'FloatBtnClick' | 'InsertSnippet' - type OptionValue = string | number | boolean - - export interface CursorPosition { - bufnr: number - lnum: number - col: number - insert: boolean - } - - export interface InsertChange { - lnum: number - col: number - pre: string - changedtick: number - } - - export interface PopupChangeEvent { - completed_item: VimCompleteItem - height: number - width: number - row: number - col: number - size: number - scrollbar: boolean - } - - /** - * Used for listen to events send from vim. - */ - export namespace events { - /** - * Latest cursor position. - */ - export const cursor: CursorPosition - /** - * Latest pum position, is true when pum positioned above current line. - */ - export const pumAlignTop: boolean - /** - * Insert mode detected by latest events. - */ - export const insertMode: boolean - export function on(event: EmptyEvents | AllEvents[], handler: () => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - /** - * Attach handler to buffer events. - */ - export function on(event: BufEvents, handler: (bufnr: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - /** - * Attach handler to mouse move events. - */ - export function on(event: MoveEvents, handler: (bufnr: number, cursor: [number, number]) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - /** - * Attach handler to TextChangedI or TextChangedP. - */ - export function on(event: InsertChangeEvents, handler: (bufnr: number, info: InsertChange) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - /** - * Attach handler to window event. - */ - export function on(event: WindowEvents, handler: (winid: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - /** - * Attach handler to float button click. - */ - export function on(event: 'FloatBtnClick', handler: (bufnr: number, index: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - /** - * Fired on vim's TextChanged event. - */ - export function on(event: 'TextChanged', handler: (bufnr: number, changedtick: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'TaskExit', handler: (id: string, code: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'TaskStderr' | 'TaskStdout', handler: (id: string, lines: string[]) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - /** - * Fired on vim's BufReadCmd event. - */ - export function on(event: 'BufReadCmd', handler: (scheme: string, fullpath: string) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - /** - * Fired on vim's VimResized event. - */ - export function on(event: 'VimResized', handler: (columns: number, lines: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'MenuPopupChanged', handler: (event: PopupChangeEvent, cursorline: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'CompleteDone', handler: (item: VimCompleteItem) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'InsertCharPre', handler: (character: string) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'FileType', handler: (filetype: string, bufnr: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'BufWinEnter' | 'BufWinLeave', handler: (bufnr: number, winid: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'DirChanged', handler: (cwd: string) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'OptionSet' | 'GlobalChange', handler: (option: string, oldVal: OptionValue, newVal: OptionValue) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'InputChar', handler: (session: string, character: string, mode: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'PromptInsert', handler: (value: string, bufnr: number) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - export function on(event: 'Command', handler: (name: string) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - - /** - * Fired after user insert character and made change to the buffer. - * Fired before TextChangedI & TextChanged event. - */ - export function on(event: 'TextInsert', handler: (bufnr: number, info: InsertChange, character: string) => EventResult, thisArg?: any, disposables?: Disposable[]): Disposable - } - // }} - - // languages module {{ - export interface DocumentSymbolProviderMetadata { - /** - * A human-readable string that is shown when multiple outlines trees show for one document. - */ - label?: string - } - - export namespace languages { - /** - * Create a diagnostics collection. - * - * @param name The [name](#DiagnosticCollection.name) of the collection. - * @return A new diagnostic collection. - */ - export function createDiagnosticCollection(name?: string): DiagnosticCollection - - /** - * Register a formatting provider that works on type. The provider is active when the user enables the setting `coc.preferences.formatOnType`. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their [score](#languages.match) and the best-matching provider is used. Failure - * of the selected provider will cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider An on type formatting edit provider. - * @param triggerCharacters Trigger character that should trigger format on type. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerOnTypeFormattingEditProvider(selector: DocumentSelector, provider: OnTypeFormattingEditProvider, triggerCharacters: string[]): Disposable - - /** - * Register a completion provider. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their [score](#languages.match) and groups of equal score are sequentially asked for - * completion items. The process stops when one or many providers of a group return a - * result. A failing provider (rejected promise or exception) will not fail the whole - * operation. - * - * A completion item provider can be associated with a set of `triggerCharacters`. When trigger - * characters are being typed, completions are requested but only from providers that registered - * the typed character. Because of that trigger characters should be different than [word characters](#LanguageConfiguration.wordPattern), - * a common trigger character is `.` to trigger member completions. - * - * @param name Name of completion source. - * @param shortcut Shortcut used in completion menu. - * @param selector Document selector of created completion source. - * @param provider A completion provider. - * @param triggerCharacters Trigger completion when the user types one of the characters. - * @param priority Higher priority would shown first. - * @param allCommitCharacters Commit characters of completion source. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerCompletionItemProvider(name: string, shortcut: string, selector: DocumentSelector | null, provider: CompletionItemProvider, triggerCharacters?: string[], priority?: number, allCommitCharacters?: string[]): Disposable - - /** - * Register a code action provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A code action provider. - * @param clientId Optional id of language client. - * @param codeActionKinds Optional supported code action kinds. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerCodeActionProvider(selector: DocumentSelector, provider: CodeActionProvider, clientId: string | undefined, codeActionKinds?: string[]): Disposable - - /** - * Register a hover provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A hover provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerHoverProvider(selector: DocumentSelector, provider: HoverProvider): Disposable - - /** - * Register a selection range provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A selection range provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerSelectionRangeProvider(selector: DocumentSelector, provider: SelectionRangeProvider): Disposable - - /** - * Register a signature help provider. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their [score](#languages.match) and called sequentially until a provider returns a - * valid result. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A signature help provider. - * @param triggerCharacters Trigger signature help when the user types one of the characters, like `,` or `(`. - * @param metadata Information about the provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerSignatureHelpProvider(selector: DocumentSelector, provider: SignatureHelpProvider, triggerCharacters?: string[]): Disposable - - /** - * Register a document symbol provider. - * - * Multiple providers can be registered for a language. In that case providers only first provider - * are asked for result. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A document symbol provider. - * @param metadata Optional meta data. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerDocumentSymbolProvider(selector: DocumentSelector, provider: DocumentSymbolProvider, metadata?: DocumentSymbolProviderMetadata): Disposable - - /** - * Register a folding range provider. - * - * Multiple providers can be registered for a language. In that case providers only first provider - * are asked for result. - * - * A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A folding range provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerFoldingRangeProvider(selector: DocumentSelector, provider: FoldingRangeProvider): Disposable - - /** - * Register a document highlight provider. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their [score](#languages.match) and groups sequentially asked for document highlights. - * The process stops when a provider returns a `non-falsy` or `non-failure` result. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A document highlight provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerDocumentHighlightProvider(selector: DocumentSelector, provider: any): Disposable - - /** - * Register a code lens provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A code lens provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerCodeLensProvider(selector: DocumentSelector, provider: CodeLensProvider): Disposable - - /** - * Register a document link provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A document link provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerDocumentLinkProvider(selector: DocumentSelector, provider: DocumentLinkProvider): Disposable - - /** - * Register a color provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A color provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerDocumentColorProvider(selector: DocumentSelector, provider: DocumentColorProvider): Disposable - - /** - * Register a definition provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A definition provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerDefinitionProvider(selector: DocumentSelector, provider: DefinitionProvider): Disposable - - /** - * Register a declaration provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A declaration provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerDeclarationProvider(selector: DocumentSelector, provider: DeclarationProvider): Disposable - - - /** - * Register a type definition provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A type definition provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerTypeDefinitionProvider(selector: DocumentSelector, provider: TypeDefinitionProvider): Disposable - - /** - * Register an implementation provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider An implementation provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerImplementationProvider(selector: DocumentSelector, provider: ImplementationProvider): Disposable - - /** - * Register a reference provider. - * - * Multiple providers can be registered for a language. In that case providers are asked in - * parallel and the results are merged. A failing provider (rejected promise or exception) will - * not cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A reference provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerReferencesProvider(selector: DocumentSelector, provider: ReferenceProvider): Disposable - - /** - * Register a rename provider. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their [score](#workspace.match) and asked in sequence. The first provider producing a result - * defines the result of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A rename provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerRenameProvider(selector: DocumentSelector, provider: RenameProvider): Disposable - - /** - * Register a workspace symbol provider. - * - * Multiple providers can be registered. In that case providers are asked in parallel and - * the results are merged. A failing provider (rejected promise or exception) will not cause - * a failure of the whole operation. - * - * @param provider A workspace symbol provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerWorkspaceSymbolProvider(provider: WorkspaceSymbolProvider): Disposable - - /** - * Register a formatting provider for a document. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their priority. Failure of the selected provider will cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A document formatting edit provider. - * @param priority default to 0. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerDocumentFormatProvider(selector: DocumentSelector, provider: DocumentFormattingEditProvider, priority?: number): Disposable - - /** - * Register a formatting provider for a document range. - * - * *Note:* A document range provider is also a [document formatter](#DocumentFormattingEditProvider) - * which means there is no need to [register](#languages.registerDocumentFormattingEditProvider) a document - * formatter when also registering a range provider. - * - * Multiple providers can be registered for a language. In that case provider with highest priority is used. - * Failure of the selected provider will cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A document range formatting edit provider. - * @param priority default to 0. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - export function registerDocumentRangeFormatProvider(selector: DocumentSelector, provider: DocumentRangeFormattingEditProvider, priority?: number): Disposable - - /** - * Register a call hierarchy provider. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A call hierarchy provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. - */ - export function registerCallHierarchyProvider(selector: DocumentSelector, provider: CallHierarchyProvider): Disposable - - /** - * Register a semantic tokens provider for a whole document. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their {@link languages.match score} and the best-matching provider is used. Failure - * of the selected provider will cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A document semantic tokens provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. - */ - export function registerDocumentSemanticTokensProvider(selector: DocumentSelector, provider: DocumentSemanticTokensProvider, legend: SemanticTokensLegend): Disposable - - /** - * Register a semantic tokens provider for a document range. - * - * *Note:* If a document has both a `DocumentSemanticTokensProvider` and a `DocumentRangeSemanticTokensProvider`, - * the range provider will be invoked only initially, for the time in which the full document provider takes - * to resolve the first request. Once the full document provider resolves the first request, the semantic tokens - * provided via the range provider will be discarded and from that point forward, only the document provider - * will be used. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their {@link languages.match score} and the best-matching provider is used. Failure - * of the selected provider will cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A document range semantic tokens provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. - */ - export function registerDocumentRangeSemanticTokensProvider(selector: DocumentSelector, provider: DocumentRangeSemanticTokensProvider, legend: SemanticTokensLegend): Disposable - - /** - * Register a linked editing range provider. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their {@link languages.match score} and the best-matching provider that has a result is used. Failure - * of the selected provider will cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A linked editing range provider. - * @return A {@link Disposable} that unregisters this provider when being disposed. - */ - export function registerLinkedEditingRangeProvider(selector: DocumentSelector, provider: LinkedEditingRangeProvider): Disposable - } - // }} - - // services module {{ - export enum ServiceStat { - Initial, - Starting, - StartFailed, - Running, - Stopping, - Stopped, - } - - export interface IServiceProvider { - // unique service id - id: string - name: string - client?: LanguageClient - selector: DocumentSelector - // current state - state: ServiceStat - start(): Promise - dispose(): void - stop(): Promise | void - restart(): Promise | void - onServiceReady: Event - } - - export namespace services { - /** - * Register languageClient as service provider. - */ - export function registLanguageClient(client: LanguageClient): Disposable - /** - * Register service, nothing happens when `service.id` already exists. - */ - export function regist(service: IServiceProvider): Disposable - /** - * Get service by id. - */ - export function getService(id: string): IServiceProvider - /** - * Stop service by id. - */ - export function stop(id: string): Promise - /** - * Stop running service or start stopped service. - */ - export function toggle(id: string): Promise - } - // }} - - // sources module {{ - /** - * Source options to create source that could respect configuration from `coc.source.{name}` - */ - export type SourceConfig = Omit - - export interface SourceStat { - name: string - priority: number - triggerCharacters: string[] - type: 'native' | 'remote' | 'service' - shortcut: string - filepath: string - disabled: boolean - filetypes: string[] - } - - export enum SourceType { - Native, - Remote, - Service, - } - - export interface CompleteResult { - items: VimCompleteItem[] - isIncomplete?: boolean - startcol?: number - source?: string - priority?: number - } - - // option on complete & should_complete - export interface CompleteOption { - /** - * Current buffer number. - */ - readonly bufnr: number - /** - * Current line. - */ - readonly line: string - /** - * Column to start completion, determined by iskeyword options of buffer. - */ - readonly col: number - /** - * Input text. - */ - readonly input: string - readonly filetype: string - readonly filepath: string - /** - * Word under cursor. - */ - readonly word: string - /** - * Trigger character, could be empty string. - */ - readonly triggerCharacter: string - /** - * Col of cursor, 1 based. - */ - readonly colnr: number - readonly linenr: number - readonly synname: string - /** - * Black list words specified by user. - */ - readonly blacklist: string[] - /** - * Buffer changetick - */ - readonly changedtick: number - /** - * Is trigger for in complete completion. - */ - readonly triggerForInComplete?: boolean - } - - export interface ISource { - /** - * Identifier name - */ - name: string - /** - * @deprecated use documentSelector instead. - */ - filetypes?: string[] - /** - * Filters of document. - */ - documentSelector?: DocumentSelector - enable?: boolean - shortcut?: string - priority?: number - sourceType?: SourceType - /** - * Should only be used when completion is triggered, requirs `triggerPatterns` or `triggerCharacters` defined. - */ - triggerOnly?: boolean - triggerCharacters?: string[] - // regex to detect trigger completion, ignored when triggerCharacters exists. - triggerPatterns?: RegExp[] - disableSyntaxes?: string[] - filepath?: string - // should the first character always match - firstMatch?: boolean - refresh?(): Promise - /** - * For disable/enable - */ - toggle?(): void - - /** - * Triggered on BufEnter, used for cache normally - */ - onEnter?(bufnr: number): void - - /** - * Check if this source should doComplete - * - * @public - * @param {CompleteOption} opt - * @returns {Promise } - */ - shouldComplete?(opt: CompleteOption): Promise - - /** - * Run completion - * - * @public - * @param {CompleteOption} opt - * @param {CancellationToken} token - * @returns {Promise} - */ - doComplete(opt: CompleteOption, token: CancellationToken): ProviderResult - - /** - * Action for complete item on complete item selected - * - * @public - * @param {VimCompleteItem} item - * @param {CancellationToken} token - * @returns {Promise} - */ - onCompleteResolve?(item: VimCompleteItem, token: CancellationToken): ProviderResult - - /** - * Action for complete item on complete done - * - * @public - * @param {VimCompleteItem} item - * @returns {Promise} - */ - onCompleteDone?(item: VimCompleteItem, opt: CompleteOption): ProviderResult - - shouldCommit?(item: VimCompleteItem, character: string): boolean - } - - export namespace sources { - /** - * Names of registered sources. - */ - export const names: ReadonlyArray - export const sources: ReadonlyArray - /** - * Check if source exists by name. - */ - export function has(name: string): boolean - /** - * Get source by name. - */ - export function getSource(name: string): ISource | null - - /** - * Add source to sources list. - * - * Note: Use `sources.createSource()` for regist new source is recommended for - * user configuration support. - */ - export function addSource(source: ISource): Disposable - - /** - * Create source by source config, configurations starts with `coc.source.{name}` - * are automatically supported. - * - * `name` and `doComplete()` must be provided in config. - */ - export function createSource(config: SourceConfig): Disposable - - /** - * Get list of all source stats. - */ - export function sourceStats(): SourceStat[] - - /** - * Call refresh for _name_ source or all sources. - */ - export function refresh(name?: string): Promise - - /** - * Toggle state of _name_ source. - */ - export function toggleSource(name: string): void - - /** - * Remove source by name. - */ - export function removeSource(name: string): void - } - // }} - - // TreeView related {{ - export interface TreeItemLabel { - label: string - highlights?: [number, number][] - } - - export interface TreeItemIcon { - text: string - hlGroup: string - } - - /** - * Collapsible state of the tree item - */ - export enum TreeItemCollapsibleState { - /** - * Determines an item can be neither collapsed nor expanded. Implies it has no children. - */ - None = 0, - /** - * Determines an item is collapsed - */ - Collapsed = 1, - /** - * Determines an item is expanded - */ - Expanded = 2 - } - - export class TreeItem { - /** - * A human-readable string describing this item. When `falsy`, it is derived from {@link TreeItem.resourceUri resourceUri}. - */ - label?: string | TreeItemLabel - - /** - * Description rendered less prominently after label. - */ - description?: string - - /** - * The icon path or {@link ThemeIcon} for the tree item. - * When `falsy`, {@link ThemeIcon.Folder Folder Theme Icon} is assigned, if item is collapsible otherwise {@link ThemeIcon.File File Theme Icon}. - * When a file or folder {@link ThemeIcon} is specified, icon is derived from the current file icon theme for the specified theme icon using {@link TreeItem.resourceUri resourceUri} (if provided). - */ - icon?: TreeItemIcon - - /** - * Optional id for the tree item that has to be unique across tree. The id is used to preserve the selection and expansion state of the tree item. - * - * If not provided, an id is generated using the tree item's resourceUri when exists. **Note** that when labels change, ids will change and that selection and expansion state cannot be kept stable anymore. - */ - id?: string - - /** - * The {@link Uri} of the resource representing this item. - * - * Will be used to derive the {@link TreeItem.label label}, when it is not provided. - * Will be used to derive the icon from current file icon theme, when {@link TreeItem.iconPath iconPath} has {@link ThemeIcon} value. - */ - resourceUri?: Uri - - /** - * The tooltip text when you hover over this item. - */ - tooltip?: string | MarkupContent - - /** - * The {@link Command} that should be executed when the tree item is selected. - * - * Please use `vscode.open` or `vscode.diff` as command IDs when the tree item is opening - * something in the editor. Using these commands ensures that the resulting editor will - * appear consistent with how other built-in trees open editors. - */ - command?: Command - - /** - * {@link TreeItemCollapsibleState} of the tree item. - */ - collapsibleState?: TreeItemCollapsibleState - - /** - * @param label A human-readable string describing this item - * @param collapsibleState {@link TreeItemCollapsibleState} of the tree item. Default is {@link TreeItemCollapsibleState.None} - */ - constructor(label: string | TreeItemLabel, collapsibleState?: TreeItemCollapsibleState) - - /** - * @param resourceUri The {@link Uri} of the resource representing this item. - * @param collapsibleState {@link TreeItemCollapsibleState} of the tree item. Default is {@link TreeItemCollapsibleState.None} - */ - constructor(resourceUri: Uri, collapsibleState?: TreeItemCollapsibleState) - } - - /** - * Action resolved by {@link TreeDataProvider} - */ - export interface TreeItemAction { - /** - * Label text in menu. - */ - title: string - handler: (item: T) => ProviderResult - } - - /** - * Options for creating a {@link TreeView} - */ - export interface TreeViewOptions { - /** - * Fixed width for window, default to true - */ - winfixwidth?: boolean - /** - * Enable filter feature, default to false - */ - enableFilter?: boolean - /** - * Disable indent of leaves without children, default to false - */ - disableLeafIndent?: boolean - /** - * A data provider that provides tree data. - */ - treeDataProvider: TreeDataProvider - /** - * Whether the tree supports multi-select. When the tree supports multi-select and a command is executed from the tree, - * the first argument to the command is the tree item that the command was executed on and the second argument is an - * array containing all selected tree items. - */ - canSelectMany?: boolean - } - - /** - * The event that is fired when an element in the {@link TreeView} is expanded or collapsed - */ - export interface TreeViewExpansionEvent { - - /** - * Element that is expanded or collapsed. - */ - readonly element: T - - } - - /** - * The event that is fired when there is a change in {@link TreeView.selection tree view's selection} - */ - export interface TreeViewSelectionChangeEvent { - - /** - * Selected elements. - */ - readonly selection: T[] - - } - - /** - * The event that is fired when there is a change in {@link TreeView.visible tree view's visibility} - */ - export interface TreeViewVisibilityChangeEvent { - - /** - * `true` if the {@link TreeView tree view} is visible otherwise `false`. - */ - readonly visible: boolean - - } - - /** - * Represents a Tree view - */ - export interface TreeView extends Disposable { - - /** - * Event that is fired when an element is expanded - */ - readonly onDidExpandElement: Event> - - /** - * Event that is fired when an element is collapsed - */ - readonly onDidCollapseElement: Event> - - /** - * Currently selected elements. - */ - readonly selection: T[] - - /** - * Event that is fired when the {@link TreeView.selection selection} has changed - */ - readonly onDidChangeSelection: Event> - - /** - * Event that is fired when {@link TreeView.visible visibility} has changed - */ - readonly onDidChangeVisibility: Event - - /** - * `true` if the {@link TreeView tree view} is visible otherwise `false`. - * - * **NOTE:** is `true` when TreeView visible on other tab. - */ - readonly visible: boolean - - /** - * Window id used by TreeView. - */ - readonly windowId: number | undefined - - /** - * An optional human-readable message that will be rendered in the view. - * Setting the message to null, undefined, or empty string will remove the message from the view. - */ - message?: string - - /** - * The tree view title is initially taken from viewId of TreeView - * Changes to the title property will be properly reflected in the UI in the title of the view. - */ - title?: string - - /** - * An optional human-readable description which is rendered less prominently in the title of the view. - * Setting the title description to null, undefined, or empty string will remove the description from the view. - */ - description?: string - - /** - * Reveals the given element in the tree view. - * If the tree view is not visible then the tree view is shown and element is revealed. - * - * By default revealed element is selected. - * In order to not to select, set the option `select` to `false`. - * In order to focus, set the option `focus` to `true`. - * In order to expand the revealed element, set the option `expand` to `true`. To expand recursively set `expand` to the number of levels to expand. - * **NOTE:** You can expand only to 3 levels maximum. - * - * **NOTE:** The {@link TreeDataProvider} that the `TreeView` {@link window.createTreeView is registered with} with must implement {@link TreeDataProvider.getParent getParent} method to access this API. - */ - reveal(element: T, options?: { select?: boolean, focus?: boolean, expand?: boolean | number }): Thenable - - /** - * Create tree view in new window. - * - * **NOTE:** TreeView with same viewId in current tab would be disposed. - * - * @param splitCommand The command to open TreeView window, default to 'belowright 30vs' - */ - show(splitCommand?: string): Promise - } - - /** - * A data provider that provides tree data - */ - export interface TreeDataProvider { - /** - * An optional event to signal that an element or root has changed. - * This will trigger the view to update the changed element/root and its children recursively (if shown). - * To signal that root has changed, do not pass any argument or pass `undefined` or `null`. - */ - onDidChangeTreeData?: Event - - /** - * Get {@link TreeItem} representation of the `element` - * - * @param element The element for which {@link TreeItem} representation is asked for. - * @return {@link TreeItem} representation of the element - */ - getTreeItem(element: T): TreeItem | Thenable - - /** - * Get the children of `element` or root if no element is passed. - * - * @param element The element from which the provider gets children. Can be `undefined`. - * @return Children of `element` or root if no element is passed. - */ - getChildren(element?: T): ProviderResult - - /** - * Optional method to return the parent of `element`. - * Return `null` or `undefined` if `element` is a child of root. - * - * **NOTE:** This method should be implemented in order to access {@link TreeView.reveal reveal} API. - * - * @param element The element for which the parent has to be returned. - * @return Parent of `element`. - */ - getParent?(element: T): ProviderResult - - /** - * Called on hover to resolve the {@link TreeItem.tooltip TreeItem} property if it is undefined. - * Called on tree item click/open to resolve the {@link TreeItem.command TreeItem} property if it is undefined. - * Only properties that were undefined can be resolved in `resolveTreeItem`. - * Functionality may be expanded later to include being called to resolve other missing - * properties on selection and/or on open. - * - * Will only ever be called once per TreeItem. - * - * onDidChangeTreeData should not be triggered from within resolveTreeItem. - * - * *Note* that this function is called when tree items are already showing in the UI. - * Because of that, no property that changes the presentation (label, description, etc.) - * can be changed. - * - * @param item Undefined properties of `item` should be set then `item` should be returned. - * @param element The object associated with the TreeItem. - * @param token A cancellation token. - * @return The resolved tree item or a thenable that resolves to such. It is OK to return the given - * `item`. When no result is returned, the given `item` will be used. - */ - resolveTreeItem?(item: TreeItem, element: T, token: CancellationToken): ProviderResult - - /** - * Called with current element to resolve actions. - * Called when user press 'actions' key. - * - * @param item Resolved item. - * @param element The object under cursor. - */ - resolveActions?(item: TreeItem, element: T): ProviderResult[]> - } - // }} - - // workspace module {{ - /** - * An event describing the change in Configuration - */ - export interface ConfigurationChangeEvent { - - /** - * Returns `true` if the given section for the given resource (if provided) is affected. - * - * @param section Configuration name, supports _dotted_ names. - * @param resource A resource URI. - * @return `true` if the given section for the given resource (if provided) is affected. - */ - affectsConfiguration(section: string, resource?: string): boolean - } - - export interface WillSaveEvent extends TextDocumentWillSaveEvent { - /** - * Allows to pause the event loop and to apply [pre-save-edits](#TextEdit). - * Edits of subsequent calls to this function will be applied in order. The - * edits will be *ignored* if concurrent modifications of the document happened. - * - * *Note:* This function can only be called during event dispatch and not - * in an asynchronous manner: - * - * ```ts - * workspace.onWillSaveTextDocument(event => { - * // async, will *throw* an error - * setTimeout(() => event.waitUntil(promise)); - * - * // sync, OK - * event.waitUntil(promise); - * }) - * ``` - * - * @param thenable A thenable that resolves to [pre-save-edits](#TextEdit). - */ - waitUntil(thenable: Thenable): void - } - - export interface KeymapOption { - /** - * Use request instead of notify, default true - */ - sync: boolean - /** - * Cancel completion before invoke callback, default true - */ - cancel: boolean - /** - * Use for keymap, default false - */ - silent: boolean - /** - * Enable repeat support for repeat.vim, default false - */ - repeat: boolean - } - - export interface DidChangeTextDocumentParams { - /** - * The document that did change. The version number points - * to the version after all provided content changes have - * been applied. - */ - textDocument: { - version: number - uri: string - } - /** - * The actual content changes. The content changes describe single state changes - * to the document. So if there are two content changes c1 (at array index 0) and - * c2 (at array index 1) for a document in state S then c1 moves the document from - * S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed - * on the state S'. - */ - contentChanges: TextDocumentContentChange[] - /** - * Buffer number of document. - */ - bufnr: number - /** - * Original content before change - */ - original: string - } - - export interface EditerState { - document: TextDocument - position: Position - } - - export type MapMode = 'n' | 'i' | 'v' | 'x' | 's' | 'o' - - export interface Autocmd { - /** - * Vim event or event set. - */ - event: string | string[] - /** - * Callback functions that called with evaled arguments. - */ - callback: Function - /** - * Match pattern, default to `*`. - */ - pattern?: string - /** - * Vim expression that eval to arguments of callback, default to `[]` - */ - arglist?: string[] - /** - * Use request when `true`, use notification by default. - */ - request?: boolean - /** - * `this` of callback. - */ - thisArg?: any - } - - export interface Env { - /** - * |completeopt| option of (neo)vim. - */ - readonly completeOpt: string - /** - * |runtimepath| option of (neo)vim. - */ - readonly runtimepath: string - /** - * |guicursor| option of (neo)vim - */ - readonly guicursor: string - /** - * Could use float window on neovim, always false on vim. - */ - readonly floating: boolean - /** - * |sign_place()| and |sign_unplace()| can be used when true. - */ - readonly sign: boolean - /** - * Root directory of extensions. - */ - readonly extensionRoot: string - /** - * Process id of (neo)vim. - */ - readonly pid: number - /** - * Total columns of screen. - */ - readonly columns: number - /** - * Total lines of screen. - */ - readonly lines: number - /** - * Is true when |CompleteChanged| event is supported. - */ - readonly pumevent: boolean - /** - * |cmdheight| option of (neo)vim. - */ - readonly cmdheight: number - /** - * Value of |g:coc_filetype_map| - */ - readonly filetypeMap: { [index: string]: string } - /** - * Is true when not using neovim. - */ - readonly isVim: boolean - /** - * Is cygvim when true. - */ - readonly isCygwin: boolean - /** - * Is macvim when true. - */ - readonly isMacvim: boolean - /** - * Is true when iTerm.app is used on mac. - */ - readonly isiTerm: boolean - /** - * version of (neo)vim, on vim it's like: 8020750, on neoivm it's like: 0.5.0 - */ - readonly version: string - /** - * |v:progpath| value, could be empty. - */ - readonly progpath: string - /** - * Is true when dialog feature is supported, which need vim >= 8.2.750 or neovim >= 0.4.0 - */ - readonly dialog: boolean - /** - * Is true when vim's textprop is supported. - */ - readonly textprop: boolean - } - - export interface TerminalOptions { - /** - * A human-readable string which will be used to represent the terminal in the UI. - */ - name?: string - - /** - * A path to a custom shell executable to be used in the terminal. - */ - shellPath?: string - - /** - * Args for the custom shell executable, this does not work on Windows (see #8429) - */ - shellArgs?: string[] - - /** - * A path or URI for the current working directory to be used for the terminal. - */ - cwd?: string - - /** - * Object with environment variables that will be added to the VS Code process. - */ - env?: { [key: string]: string | null } - - /** - * Whether the terminal process environment should be exactly as provided in - * `TerminalOptions.env`. When this is false (default), the environment will be based on the - * window's environment and also apply configured platform settings like - * `terminal.integrated.windows.env` on top. When this is true, the complete environment - * must be provided as nothing will be inherited from the process or any configuration. - */ - strictEnv?: boolean - } - - /** - * An individual terminal instance within the integrated terminal. - */ - export interface Terminal { - - /** - * The bufnr of terminal buffer. - */ - readonly bufnr: number - - /** - * The name of the terminal. - */ - readonly name: string - - /** - * The process ID of the shell process. - */ - readonly processId: Promise - - /** - * Send text to the terminal. The text is written to the stdin of the underlying pty process - * (shell) of the terminal. - * - * @param text The text to send. - * @param addNewLine Whether to add a new line to the text being sent, this is normally - * required to run a command in the terminal. The character(s) added are \n or \r\n - * depending on the platform. This defaults to `true`. - */ - sendText(text: string, addNewLine?: boolean): void - - /** - * Show the terminal panel and reveal this terminal in the UI, return false when failed. - * - * @param preserveFocus When `true` the terminal will not take focus. - */ - show(preserveFocus?: boolean): Promise - - /** - * Hide the terminal panel if this terminal is currently showing. - */ - hide(): void - - /** - * Dispose and free associated resources. - */ - dispose(): void - } - - export interface Document { - readonly buffer: Buffer - /** - * Document is attached to vim. - */ - readonly attached: boolean - /** - * Is command line document. - */ - readonly isCommandLine: boolean - /** - * `buftype` option of buffer. - */ - readonly buftype: string - /** - * Text document that synchronized. - */ - readonly textDocument: TextDocument - /** - * Fired when document change. - */ - readonly onDocumentChange: Event - /** - * Fired on document detach. - */ - readonly onDocumentDetach: Event - /** - * Get current buffer changedtick. - */ - readonly changedtick: number - /** - * Scheme of document. - */ - readonly schema: string - /** - * Line count of current buffer. - */ - readonly lineCount: number - /** - * Window ID when buffer create, could be -1 when no window associated. - */ - readonly winid: number - /** - * Returns if current document is opended with previewwindow - */ - readonly previewwindow: boolean - /** - * Check if document changed after last synchronize - */ - readonly dirty: boolean - /** - * Buffer number - */ - readonly bufnr: number - /** - * Content of textDocument. - */ - readonly content: string - /** - * Converted filetype. - */ - readonly filetype: string - readonly uri: string - readonly version: number - /** - * Apply textEdits to current buffer lines, fire content change event. - */ - applyEdits(edits: TextEdit[]): Promise - - /** - * Change individual lines. - * - * @param {[number, string][]} lines - * @returns {void} - */ - changeLines(lines: [number, string][]): Promise - - /** - * Get offset from lnum & col - */ - getOffset(lnum: number, col: number): number - - /** - * Check string is word. - */ - isWord(word: string): boolean - - /** - * Word range at position. - * - * @param {Position} position - * @param {string} extraChars Extra characters that should be keyword. - * @param {boolean} current Use current lines instead of textDocument, default to true. - * @returns {Range | null} - */ - getWordRangeAtPosition(position: Position, extraChars?: string, current?: boolean): Range | null - - /** - * Get ranges of word in textDocument. - */ - getSymbolRanges(word: string): Range[] - - /** - * Get line for buffer - * - * @param {number} line 0 based line index. - * @param {boolean} current Use textDocument lines when false, default to true. - * @returns {string} - */ - getline(line: number, current?: boolean): string - - /** - * Get range of current lines, zero indexed, end exclude. - */ - getLines(start?: number, end?: number): string[] - - /** - * Get variable value by key, defined by `b:coc_{key}` - */ - getVar(key: string, defaultValue?: T): T - - /** - * Get position from lnum & col - */ - getPosition(lnum: number, col: number): Position - - /** - * Adjust col with new valid character before position. - */ - fixStartcol(position: Position, valids: string[]): number - - /** - * Get current content text. - */ - getDocumentContent(): string - } - - /** - * Store & retrive most recent used items. - */ - export interface Mru { - /** - * Load iems from mru file - */ - - load(): Promise - /** - * Add item to mru file. - */ - add(item: string): Promise - - /** - * Remove item from mru file. - */ - - remove(item: string): Promise - - /** - * Remove the data file. - */ - clean(): Promise - } - - /** - * Option to create task that runs in (neo)vim. - */ - export interface TaskOptions { - /** - * The command to run, without arguments - */ - cmd: string - /** - * Arguments of command. - */ - args?: string[] - /** - * Current working directory of the task, Default to current vim's cwd. - */ - cwd?: string - /** - * Additional environment key-value pairs. - */ - env?: { [key: string]: string } - /** - * Use pty when true. - */ - pty?: boolean - /** - * Detach child process when true. - */ - detach?: boolean - } - - /** - * Controls long running task started by (neo)vim. - * Useful to keep the task running after CocRestart. - */ - export interface Task extends Disposable { - /** - * Fired on task exit with exit code. - */ - onExit: Event - /** - * Fired with lines on stdout received. - */ - onStdout: Event - /** - * Fired with lines on stderr received. - */ - onStderr: Event - /** - * Start task, task will be restarted when already running. - * - * @param {TaskOptions} opts - * @returns {Promise} - */ - start(opts: TaskOptions): Promise - /** - * Stop task by SIGTERM or SIGKILL - */ - stop(): Promise - /** - * Check if the task is running. - */ - running: Promise - } - - /** - * A simple json database. - */ - export interface JsonDB { - filepath: string - /** - * Get data by key. - * - * @param {string} key unique key allows dot notation. - * @returns {any} - */ - fetch(key: string): any - /** - * Check if key exists - * - * @param {string} key unique key allows dot notation. - */ - exists(key: string): boolean - /** - * Delete data by key - * - * @param {string} key unique key allows dot notation. - */ - delete(key: string): void - /** - * Save data with key - */ - push(key: string, data: number | null | boolean | string | { [index: string]: any }): void - /** - * Empty db file. - */ - clear(): void - /** - * Remove db file. - */ - destroy(): void - } - - export interface RenameEvent { - oldUri: Uri - newUri: Uri - } - - export interface FileSystemWatcher { - readonly ignoreCreateEvents: boolean - readonly ignoreChangeEvents: boolean - readonly ignoreDeleteEvents: boolean - readonly onDidCreate: Event - readonly onDidChange: Event - readonly onDidDelete: Event - readonly onDidRename: Event - dispose(): void - } - - export interface ConfigurationInspect { - key: string - defaultValue?: T - globalValue?: T - workspaceValue?: T - } - - export interface WorkspaceConfiguration { - /** - * Return a value from this configuration. - * - * @param section Configuration name, supports _dotted_ names. - * @return The value `section` denotes or `undefined`. - */ - get(section: string): T | undefined - - /** - * Return a value from this configuration. - * - * @param section Configuration name, supports _dotted_ names. - * @param defaultValue A value should be returned when no value could be found, is `undefined`. - * @return The value `section` denotes or the default. - */ - get(section: string, defaultValue: T): T - - /** - * Check if this configuration has a certain value. - * - * @param section Configuration name, supports _dotted_ names. - * @return `true` if the section doesn't resolve to `undefined`. - */ - has(section: string): boolean - - /** - * Retrieve all information about a configuration setting. A configuration value - * often consists of a *default* value, a global or installation-wide value, - * a workspace-specific value - * - * *Note:* The configuration name must denote a leaf in the configuration tree - * (`editor.fontSize` vs `editor`) otherwise no result is returned. - * - * @param section Configuration name, supports _dotted_ names. - * @return Information about a configuration setting or `undefined`. - */ - inspect(section: string): ConfigurationInspect | undefined - /** - * Update a configuration value. The updated configuration values are persisted. - * - * - * @param section Configuration name, supports _dotted_ names. - * @param value The new value. - * @param isUser if true, always update user configuration - */ - update(section: string, value: any, isUser?: boolean): void - - /** - * Readable dictionary that backs this configuration. - */ - readonly [key: string]: any - } - - export interface BufferSyncItem { - /** - * Called on buffer unload. - */ - dispose: () => void - /** - * Called on buffer change. - */ - onChange?(e: DidChangeTextDocumentParams): void - } - - export interface BufferSync { - /** - * Current items. - */ - readonly items: Iterable - /** - * Get created item by uri - */ - getItem(uri: string): T | undefined - /** - * Get created item by bufnr - */ - getItem(bufnr: number): T | undefined - dispose: () => void - } - - export namespace workspace { - export const nvim: Neovim - /** - * Current buffer number, could be wrong since vim could not send autocmd as expected. - * - * @deprecated will be removed in the feature. - */ - export const bufnr: number - /** - * Current document. - */ - export const document: Promise - /** - * Environments or current (neo)vim. - */ - export const env: Env - /** - * Float window or popup can work. - */ - export const floatSupported: boolean - /** - * Current working directory of vim. - */ - export const cwd: string - /** - * Current workspace root. - */ - export const root: string - /** - * @deprecated aliased to root. - */ - export const rootPath: string - /** - * Not neovim when true. - */ - export const isVim: boolean - /** - * Is neovim when true. - */ - export const isNvim: boolean - /** - * Is true when current mode is insert, could be wrong when user cancel insert by - * - * @deprecated - */ - export const insertMode: boolean - /** - * All filetypes of loaded documents. - */ - export const filetypes: ReadonlySet - /** - * Root directory of coc.nvim - */ - export const pluginRoot: string - /** - * Current `&completeopt` of vim, may not correct. - */ - export const completeOpt: string - /** - * Exists channel names. - */ - export const channelNames: ReadonlyArray - /** - * Current document array. - */ - export const documents: ReadonlyArray - /** - * Current document array. - */ - export const textDocuments: ReadonlyArray - /** - * Current workspace folders. - */ - export const workspaceFolders: ReadonlyArray - /** - * Directory paths of workspaceFolders. - */ - export const folderPaths: ReadonlyArray - /** - * Current workspace folder, could be null when vim started from user's home. - */ - export const workspaceFolder: WorkspaceFolder | null - /** - * Event fired after terminal created, only fired with Terminal that created - * by `workspace.createTerminal` - */ - export const onDidOpenTerminal: Event - /** - * Event fired on terminal close, only fired with Terminal that created by - * `workspace.createTerminal` - */ - export const onDidCloseTerminal: Event - /** - * Event fired on workspace folder change. - */ - export const onDidChangeWorkspaceFolders: Event - /** - * Event fired after document create. - */ - export const onDidOpenTextDocument: Event - /** - * Event fired after document unload. - */ - export const onDidCloseTextDocument: Event - /** - * Event fired on document change. - */ - export const onDidChangeTextDocument: Event - /** - * Event fired before document save. - */ - export const onWillSaveTextDocument: Event - /** - * Event fired after document save. - */ - export const onDidSaveTextDocument: Event - - /** - * Event fired on configuration change. Configuration change could by many - * reasons, including: - * - * - Changes detected from `coc-settings.json`. - * - Change to document that using another configuration file. - * - Configuration change by call update API of WorkspaceConfiguration. - */ - export const onDidChangeConfiguration: Event - - /** - * Fired when vim's runtimepath change detected. - */ - export const onDidRuntimePathChange: Event> - - /** - * Create new namespace id by name. - */ - export function createNameSpace(name: string): number - - /** - * Register autocmd on vim. - * - * Note: avoid request autocmd when possible since vim could be blocked - * forever when request triggered during request. - */ - export function registerAutocmd(autocmd: Autocmd): Disposable - - /** - * Watch for vim's global option change. - */ - export function watchOption(key: string, callback: (oldValue: any, newValue: any) => Thenable | void, disposables?: Disposable[]): void - - /** - * Watch for vim's global variable change, works on neovim only. - */ - export function watchGlobal(key: string, callback?: (oldValue: any, newValue: any) => Thenable | void, disposables?: Disposable[]): void - - /** - * Check if selector match document. - */ - export function match(selector: DocumentSelector, document: TextDocument): number - - /** - * Findup from filename or filenames from current filepath or root. - * - * @return fullpath of file or null when not found. - */ - export function findUp(filename: string | string[]): Promise - - /** - * Resolve root folder of uri with match patterns. - * Cwd is returned when uri is not file scheme. - * Parent folder of uri is returned when failed to resolve. - * - * @deprecated avoid use it when possible. - */ - export function resolveRootFolder(uri: Uri, patterns: string[]): Promise - - /** - * Get possible watchman binary path. - */ - export function getWatchmanPath(): string | null - - /** - * Get configuration by section and optional resource uri. - */ - export function getConfiguration(section?: string, resource?: string): WorkspaceConfiguration - - /** - * Get created document by uri or bufnr. - */ - export function getDocument(uri: number | string): Document - - /** - * Apply WorkspaceEdit. - */ - export function applyEdit(edit: WorkspaceEdit): Promise - - /** - * Convert location to quickfix item. - */ - export function getQuickfixItem(loc: Location | LocationLink, text?: string, type?: string, module?: string): Promise - - /** - * Get selected range for current document - */ - export function getSelectedRange(visualmode: string, document: Document): Promise - - /** - * Visual select range of current document - */ - export function selectRange(range: Range): Promise - - /** - * Populate locations to UI. - */ - export function showLocations(locations: Location[]): Promise - - /** - * Get content of line by uri and line. - */ - export function getLine(uri: string, line: number): Promise - - /** - * Get WorkspaceFolder of uri - */ - export function getWorkspaceFolder(uri: string): WorkspaceFolder | null - - /** - * Get content from buffer of file by uri. - */ - export function readFile(uri: string): Promise - - /** - * Get current document and position. - */ - export function getCurrentState(): Promise - - /** - * Get format options of uri or current buffer. - */ - export function getFormatOptions(uri?: string): Promise - - /** - * Jump to location. - */ - export function jumpTo(uri: string, position?: Position | null, openCommand?: string): Promise - - /** - * Create a file in vim and disk - */ - export function createFile(filepath: string, opts?: CreateFileOptions): Promise - - /** - * Load uri as document, buffer would be invisible if not loaded. - */ - export function loadFile(uri: string): Promise - - /** - * Load the files that not loaded - */ - export function loadFiles(uris: string[]): Promise - - /** - * Rename file in vim and disk - */ - export function renameFile(oldPath: string, newPath: string, opts?: RenameFileOptions): Promise - - /** - * Delete file from vim and disk. - */ - export function deleteFile(filepath: string, opts?: DeleteFileOptions): Promise - - /** - * Open resource by uri - */ - export function openResource(uri: string): Promise - - /** - * Resolve full path of module from yarn or npm global directory. - */ - export function resolveModule(name: string): Promise - - /** - * Run nodejs command - */ - export function runCommand(cmd: string, cwd?: string, timeout?: number): Promise - - /** - * Expand filepath with `~` and/or environment placeholders - */ - export function expand(filepath: string): string - - /** - * Call a function by use notifications, useful for functions like |input| that could block vim. - */ - export function callAsync(method: string, args: any[]): Promise - - /** - * registerTextDocumentContentProvider - */ - export function registerTextDocumentContentProvider(scheme: string, provider: TextDocumentContentProvider): Disposable - - /** - * Register unique keymap uses `(coc-{key})` as lhs - * Throw error when {key} already exists. - * - * @param {MapMode[]} modes - array of 'n' | 'i' | 'v' | 'x' | 's' | 'o' - * @param {string} key - unique name - * @param {Function} fn - callback function - * @param {Partial} opts - * @returns {Disposable} - */ - export function registerKeymap(modes: MapMode[], key: string, fn: () => ProviderResult, opts?: Partial): Disposable - - /** - * Register expr key-mapping. - */ - export function registerExprKeymap(mode: 'i' | 'n' | 'v' | 's' | 'x', key: string, fn: () => ProviderResult, buffer?: boolean): Disposable - - /** - * Register local key-mapping. - */ - export function registerLocalKeymap(mode: 'n' | 'v' | 's' | 'x', key: string, fn: () => ProviderResult, notify?: boolean): Disposable - - /** - * Register for buffer sync objects, created item should be disposable - * and provide optional `onChange` which called when document change. - * - * The document is always attached and not command line buffer. - * - * @param create Called for each attached document and on document create. - * @returns Disposable - */ - export function registerBufferSync(create: (doc: Document) => T | undefined): BufferSync - - /** - * Create a FileSystemWatcher instance, when watchman not exists, the - * returned FileSystemWatcher can stil be used, but not work at all. - */ - export function createFileSystemWatcher(globPattern: string, ignoreCreate?: boolean, ignoreChange?: boolean, ignoreDelete?: boolean): FileSystemWatcher - /** - * Create persistence Mru instance. - */ - export function createMru(name: string): Mru - - /** - * Create Task instance that runs in (neo)vim, no shell. - * - * @param id Unique id string, like `TSC` - */ - export function createTask(id: string): Task - - /** - * Create terminal in (neo)vim. - */ - export function createTerminal(opts: TerminalOptions): Promise - - /** - * Create DB instance at extension root. - */ - export function createDatabase(name: string): JsonDB - } - // }} - - // window module {{ - /** - * Option for create status item. - */ - export interface StatusItemOption { - progress?: boolean - } - - /** - * Status item that included in `g:coc_status` - */ - export interface StatusBarItem { - /** - * The priority of this item. Higher value means the item should - * be shown more to the left. - */ - readonly priority: number - - isProgress: boolean - - /** - * The text to show for the entry. You can embed icons in the text by leveraging the syntax: - * - * `My text $(icon-name) contains icons like $(icon-name) this one.` - * - * Where the icon-name is taken from the [octicon](https://octicons.github.com) icon set, e.g. - * `light-bulb`, `thumbsup`, `zap` etc. - */ - text: string - - /** - * Shows the entry in the status bar. - */ - show(): void - - /** - * Hide the entry in the status bar. - */ - hide(): void - - /** - * Dispose and free associated resources. Call - * [hide](#StatusBarItem.hide). - */ - dispose(): void - } - - /** - * Value-object describing where and how progress should show. - */ - export interface ProgressOptions { - - /** - * A human-readable string which will be used to describe the - * operation. - */ - title?: string - - /** - * Controls if a cancel button should show to allow the user to - * cancel the long running operation. - */ - cancellable?: boolean - } - - /** - * Defines a generalized way of reporting progress updates. - */ - export interface Progress { - - /** - * Report a progress update. - * - * @param value A progress item, like a message and/or an - * report on how much work finished - */ - report(value: T): void - } - - /** - * Represents an action that is shown with an information, warning, or - * error message. - * - * @see [showInformationMessage](#window.showInformationMessage) - * @see [showWarningMessage](#window.showWarningMessage) - * @see [showErrorMessage](#window.showErrorMessage) - */ - export interface MessageItem { - - /** - * A short title like 'Retry', 'Open Log' etc. - */ - title: string - - /** - * A hint for modal dialogs that the item should be triggered - * when the user cancels the dialog (e.g. by pressing the ESC - * key). - * - * Note: this option is ignored for non-modal messages. - * Note: not used by coc.nvim for now. - */ - isCloseAffordance?: boolean - } - - export interface DialogButton { - /** - * Use by callback, should >= 0 - */ - index: number - text: string - /** - * Not shown when true - */ - disabled?: boolean - } - - export interface DialogConfig { - /** - * Content shown in window. - */ - content: string - /** - * Optional title text. - */ - title?: string - /** - * show close button, default to true when not specified. - */ - close?: boolean - /** - * highlight group for dialog window, default to `"dialog.floatHighlight"` or 'CocFlating' - */ - highlight?: string - /** - * highlight groups for border, default to `"dialog.borderhighlight"` or 'CocFlating' - */ - borderhighlight?: string - /** - * Buttons as bottom of dialog. - */ - buttons?: DialogButton[] - /** - * index is -1 for window close without button click - */ - callback?: (index: number) => void - } - - export interface NotificationConfig extends DialogConfig { - /** - * Timeout in miliseconds to dismiss notification, default no timeout. - */ - timeout?: number - } - - /** - * Represents an item that can be selected from - * a list of items. - */ - export interface QuickPickItem { - /** - * A human-readable string which is rendered prominent - */ - label: string - /** - * A human-readable string which is rendered less prominent in the same line - */ - description?: string - /** - * Optional flag indicating if this item is picked initially. - */ - picked?: boolean - } - - export interface ScreenPosition { - row: number - col: number - } - - export type MsgTypes = 'error' | 'warning' | 'more' - - export interface OpenTerminalOption { - /** - * Cwd of terminal, default to result of |getcwd()| - */ - cwd?: string - /** - * Close terminal on job finish, default to true. - */ - autoclose?: boolean - /** - * Keep foucus current window, default to false, - */ - keepfocus?: boolean - } - - /** - * An output channel is a container for readonly textual information. - * - * To get an instance of an `OutputChannel` use - * [createOutputChannel](#window.createOutputChannel). - */ - export interface OutputChannel { - - /** - * The human-readable name of this output channel. - */ - readonly name: string - - readonly content: string - /** - * Append the given value to the channel. - * - * @param value A string, falsy values will not be printed. - */ - append(value: string): void - - /** - * Append the given value and a line feed character - * to the channel. - * - * @param value A string, falsy values will be printed. - */ - appendLine(value: string): void - - /** - * Removes output from the channel. Latest `keep` lines will be remained. - */ - clear(keep?: number): void - - /** - * Reveal this channel in the UI. - * - * @param preserveFocus When `true` the channel will not take focus. - */ - show(preserveFocus?: boolean): void - - /** - * Hide this channel from the UI. - */ - hide(): void - - /** - * Dispose and free associated resources. - */ - dispose(): void - } - - export interface TerminalResult { - bufnr: number - success: boolean - content?: string - } - - export interface Dialog { - /** - * Buffer number of dialog. - */ - bufnr: number - /** - * Window id of dialog. - */ - winid: Promise - dispose: () => void - } - - export namespace window { - /** - * Reveal message with message type. - * - * @param msg Message text to show. - * @param messageType Type of message, could be `error` `warning` and `more`, default to `more` - */ - export function showMessage(msg: string, messageType?: MsgTypes): void - - /** - * Run command in vim terminal for result - * - * @param cmd Command to run. - * @param cwd Cwd of terminal, default to result of |getcwd()|. - */ - export function runTerminalCommand(cmd: string, cwd?: string, keepfocus?: boolean): Promise - - /** - * Open terminal window. - * - * @param cmd Command to run. - * @param opts Terminal option. - * @returns buffer number of terminal. - */ - export function openTerminal(cmd: string, opts?: OpenTerminalOption): Promise - - /** - * Show quickpick for single item, use `window.menuPick` for menu at current current position. - * - * @param items Label list. - * @param placeholder Prompt text, default to 'choose by number'. - * @returns Index of selected item, or -1 when canceled. - */ - export function showQuickpick(items: string[], placeholder?: string): Promise - - /** - * Show menu picker at current cursor position, |inputlist()| is used as fallback. - * Use `workspace.env.dialog` to check if the picker window/popup could work. - * - * @param items Array of texts. - * @param title Optional title of float/popup window. - * @param token A token that can be used to signal cancellation. - * @returns Selected index (0 based), -1 when canceled. - */ - export function showMenuPicker(items: string[], title?: string, token?: CancellationToken): Promise - - /** - * Open local config file - */ - export function openLocalConfig(): Promise - - /** - * Prompt user for confirm, a float/popup window would be used when possible, - * use vim's |confirm()| function as callback. - * - * @param title The prompt text. - * @returns Result of confirm. - */ - export function showPrompt(title: string): Promise - - /** - * Show dialog window at the center of screen. - * Note that the dialog would always be closed after button click. - * Use `workspace.env.dialog` to check if dialog could work. - * - * @param config Dialog configuration. - * @returns Dialog or null when dialog can't work. - */ - export function showDialog(config: DialogConfig): Promise - - /** - * Request input from user - * - * @param title Title text of prompt window. - * @param defaultValue Default value of input, empty text by default. - */ - export function requestInput(title: string, defaultValue?: string): Promise - - /** - * Create statusbar item that would be included in `g:coc_status`. - * - * @param priority Higher priority item would be shown right. - * @param option - * @return A new status bar item. - */ - export function createStatusBarItem(priority?: number, option?: StatusItemOption): StatusBarItem - - /** - * Create a new output channel - * - * @param name Unique name of output channel. - * @returns A new output channel. - */ - export function createOutputChannel(name: string): OutputChannel - - /** - * Create a {@link TreeView} instance, call `show()` method to render. - * - * @param viewId Id of the view, used as title of TreeView when title not exists. - * @param options Options for creating the {@link TreeView} - * @returns a {@link TreeView}. - */ - export function createTreeView(viewId: string, options: TreeViewOptions): TreeView - - /** - * Reveal buffer of output channel. - * - * @param name Name of output channel. - * @param preserveFocus Preserve window focus when true. - */ - export function showOutputChannel(name: string, preserveFocus: boolean): void - - /** - * Echo lines at the bottom of vim. - * - * @param lines Line list. - * @param truncate Truncate the lines to avoid 'press enter to continue' when true - */ - export function echoLines(lines: string[], truncate?: boolean): Promise - - /** - * Get current cursor position (line, character both 0 based). - * - * @returns Cursor position. - */ - export function getCursorPosition(): Promise - - /** - * Move cursor to position (line, character both 0 based). - * - * @param position LSP position. - */ - export function moveTo(position: Position): Promise - - /** - * Get current cursor character offset in document, - * length of line break would always be 1. - * - * @returns Character offset. - */ - export function getOffset(): Promise - - /** - * Get screen position of current cursor(relative to editor), - * both `row` and `col` are 0 based. - * - * @returns Cursor screen position. - */ - export function getCursorScreenPosition(): Promise - - /** - * Show multiple picker at center of screen. - * Use `workspace.env.dialog` to check if dialog could work. - * - * @param items A set of items that will be rendered as actions in the message. - * @param title Title of picker dialog. - * @param token A token that can be used to signal cancellation. - * @return A promise that resolves to the selected items or `undefined`. - */ - export function showPickerDialog(items: string[], title: string, token?: CancellationToken): Promise - - /** - * Show multiple picker at center of screen. - * Use `workspace.env.dialog` to check if dialog could work. - * - * @param items A set of items that will be rendered as actions in the message. - * @param title Title of picker dialog. - * @param token A token that can be used to signal cancellation. - * @return A promise that resolves to the selected items or `undefined`. - */ - export function showPickerDialog(items: T[], title: string, token?: CancellationToken): Promise - - /** - * Show an information message to users. Optionally provide an array of items which will be presented as - * clickable buttons. - * - * @param message The message to show. - * @param items A set of items that will be rendered as actions in the message. - * @return Promise that resolves to the selected item or `undefined` when being dismissed. - */ - export function showInformationMessage(message: string, ...items: string[]): Promise - /** - * Show an information message to users. Optionally provide an array of items which will be presented as - * clickable buttons. - * - * @param message The message to show. - * @param items A set of items that will be rendered as actions in the message. - * @return Promise that resolves to the selected item or `undefined` when being dismissed. - */ - export function showInformationMessage(message: string, ...items: T[]): Promise - - /** - * Show an warning message to users. Optionally provide an array of items which will be presented as - * clickable buttons. - * - * @param message The message to show. - * @param items A set of items that will be rendered as actions in the message. - * @return Promise that resolves to the selected item or `undefined` when being dismissed. - */ - export function showWarningMessage(message: string, ...items: string[]): Promise - /** - * Show an warning message to users. Optionally provide an array of items which will be presented as - * clickable buttons. - * - * @param message The message to show. - * @param items A set of items that will be rendered as actions in the message. - * @return Promise that resolves to the selected item or `undefined` when being dismissed. - */ - export function showWarningMessage(message: string, ...items: T[]): Promise - - /** - * Show an error message to users. Optionally provide an array of items which will be presented as - * clickable buttons. - * - * @param message The message to show. - * @param items A set of items that will be rendered as actions in the message. - * @return Promise that resolves to the selected item or `undefined` when being dismissed. - */ - export function showErrorMessage(message: string, ...items: string[]): Promise - /** - * Show an error message to users. Optionally provide an array of items which will be presented as - * clickable buttons. - * - * @param message The message to show. - * @param items A set of items that will be rendered as actions in the message. - * @return Promise that resolves to the selected item or `undefined` when being dismissed. - */ - export function showErrorMessage(message: string, ...items: T[]): Promise - - /** - * Show notification window at right of screen. - */ - export function showNotification(config: NotificationConfig): Promise - - /** - * Show progress in the editor. Progress is shown while running the given callback - * and while the promise it returned isn't resolved nor rejected. - * - * @param task A callback returning a promise. Progress state can be reported with - * the provided [progress](#Progress)-object. - * - * To report discrete progress, use `increment` to indicate how much work has been completed. Each call with - * a `increment` value will be summed up and reflected as overall progress until 100% is reached (a value of - * e.g. `10` accounts for `10%` of work done). - * - * To monitor if the operation has been cancelled by the user, use the provided [`CancellationToken`](#CancellationToken). - * - * @return The thenable the task-callback returned. - */ - export function withProgress(options: ProgressOptions, task: (progress: Progress<{ - message?: string - increment?: number - }>, token: CancellationToken) => Thenable): Promise - } - // }} - - // extensions module {{ - export interface Logger { - readonly category: string - readonly level: string - log(...args: any[]): void - trace(message: any, ...args: any[]): void - debug(message: any, ...args: any[]): void - info(message: any, ...args: any[]): void - warn(message: any, ...args: any[]): void - error(message: any, ...args: any[]): void - fatal(message: any, ...args: any[]): void - mark(message: any, ...args: any[]): void - } - - /** - * A memento represents a storage utility. It can store and retrieve - * values. - */ - export interface Memento { - - /** - * Return a value. - * - * @param key A string. - * @return The stored value or `undefined`. - */ - get(key: string): T | undefined - - /** - * Return a value. - * - * @param key A string. - * @param defaultValue A value that should be returned when there is no - * value (`undefined`) with the given key. - * @return The stored value or the defaultValue. - */ - get(key: string, defaultValue: T): T - - /** - * Store a value. The value must be JSON-stringifyable. - * - * @param key A string. - * @param value A value. MUST not contain cyclic references. - */ - update(key: string, value: any): Promise - } - - export type ExtensionState = 'disabled' | 'loaded' | 'activated' | 'unknown' - - export enum ExtensionType { - Global, - Local, - SingleFile, - Internal - } - - export interface ExtensionJson { - name: string - main?: string - engines: { - [key: string]: string - } - version?: string - [key: string]: any - } - - export interface ExtensionInfo { - id: string - version: string - description: string - root: string - exotic: boolean - uri?: string - state: ExtensionState - isLocal: boolean - packageJSON: Readonly - } - - /** - * Represents an extension. - * - * To get an instance of an `Extension` use [getExtension](#extensions.getExtension). - */ - export interface Extension { - - /** - * The canonical extension identifier in the form of: `publisher.name`. - */ - readonly id: string - - /** - * The absolute file path of the directory containing this extension. - */ - readonly extensionPath: string - - /** - * `true` if the extension has been activated. - */ - readonly isActive: boolean - - /** - * The parsed contents of the extension's package.json. - */ - readonly packageJSON: any - - /** - * The public API exported by this extension. It is an invalid action - * to access this field before this extension has been activated. - */ - readonly exports: T - - /** - * Activates this extension and returns its public API. - * - * @return A promise that will resolve when this extension has been activated. - */ - activate(): Promise - } - - /** - * An extension context is a collection of utilities private to an - * extension. - * - * An instance of an `ExtensionContext` is provided as the first - * parameter to the `activate`-call of an extension. - */ - export interface ExtensionContext { - - /** - * An array to which disposables can be added. When this - * extension is deactivated the disposables will be disposed. - */ - subscriptions: Disposable[] - - /** - * The absolute file path of the directory containing the extension. - */ - extensionPath: string - - /** - * Get the absolute path of a resource contained in the extension. - * - * @param relativePath A relative path to a resource contained in the extension. - * @return The absolute path of the resource. - */ - asAbsolutePath(relativePath: string): string - - /** - * The absolute directory path for extension to download persist data. - * The directory could be not exists. - */ - storagePath: string - - /** - * A memento object that stores state in the context - * of the currently opened [workspace](#workspace.workspaceFolders). - */ - workspaceState: Memento - - /** - * A memento object that stores state independent - * of the current opened [workspace](#workspace.workspaceFolders). - */ - globalState: Memento - - logger: Logger - } - - export type ExtensionApi = { - [index: string]: any - } | void | null | undefined - - export interface PropertyScheme { - type: string - default: any - description: string - enum?: string[] - items?: any - [key: string]: any - } - - export namespace extensions { - /** - * Fired on extension loaded, extension not activated yet. - */ - export const onDidLoadExtension: Event> - - /** - * Fired on extension activated. - */ - export const onDidActiveExtension: Event> - - /** - * Fired with extension id on extension unload. - */ - export const onDidUnloadExtension: Event - - /** - * Get all loaded extensions, without disabled extensions, extension may not activated. - */ - export const all: ReadonlyArray> - - /** - * Get state of specific extension. - */ - export function getExtensionState(id: string): ExtensionState - - /** - * Get state of all extensions, including disabled extensions. - */ - export function getExtensionStates(): Promise - - /** - * Check if extension is activated. - */ - export function isActivated(id: string): boolean - - /** - * Dynamic add custom json schemes without using package.json. - */ - export function addSchemeProperty(key: string, def: PropertyScheme): void - } - // }} - - // listManager module {{ - export interface LocationWithLine { - uri: string - /** - * Match text of line. - */ - line: string - /** - * Highlight text in line. - */ - text?: string - } - - export interface AnsiHighlight { - /** - * Byte indexes, 0 based. - */ - span: [number, number] - hlGroup: string - } - - export interface ListItem { - label: string - filterText?: string - /** - * A string that should be used when comparing this item - * with other items, only used for fuzzy filter. - */ - sortText?: string - location?: Location | LocationWithLine | string - data?: any - ansiHighlights?: AnsiHighlight[] - resolved?: boolean - } - - export interface ListHighlights { - /** - * Byte indexes list, 0 based. - */ - spans: [number, number][] - /** - * `list.matchHighlightGroup` is used when not exists. - */ - hlGroup?: string - } - - export type ListMode = 'normal' | 'insert' - - export type ListMatcher = 'strict' | 'fuzzy' | 'regex' - - export interface ListOptions { - position: string - input: string - ignorecase: boolean - interactive: boolean - sort: boolean - mode: ListMode - matcher: ListMatcher - autoPreview: boolean - numberSelect: boolean - noQuit: boolean - first: boolean - } - - export interface ListContext { - /** - * Input on list activated. - */ - input: string - /** - * Current work directory on activated. - */ - cwd: string - /** - * Options of list. - */ - options: ListOptions - /** - * Arguments passed to list. - */ - args: string[] - /** - * Original window on list invoke. - */ - window: Window - /** - * Original buffer on list invoke. - */ - buffer: Buffer - listWindow: Window | null - } - - export interface ListAction { - /** - * Action name - */ - name: string - /** - * Should persist list window on invoke. - */ - persist?: boolean - /** - * Should reload list after invoke. - */ - reload?: boolean - /** - * Inovke all selected items in parallel. - */ - parallel?: boolean - /** - * Support handle multiple items at once. - */ - multiple?: boolean - /** - * Item is array of selected items when multiple is true. - */ - execute: (item: ListItem | ListItem[], context: ListContext) => ProviderResult - } - - export interface MutipleListAction extends ListAction { - multiple: true - execute: (item: ListItem[], context: ListContext) => ProviderResult - } - - export interface ListTask { - on(event: 'data', callback: (item: ListItem) => void): void - on(event: 'end', callback: () => void): void - on(event: 'error', callback: (msg: string | Error) => void): void - dispose(): void - } - - export interface ListArgument { - key?: string - hasValue?: boolean - name: string - description: string - } - - export interface IList { - /** - * Unique name of list. - */ - name: string - /** - * Default action name. - */ - defaultAction: string - /** - * Action list. - */ - actions: ListAction[] - /** - * Load list items. - */ - loadItems(context: ListContext, token: CancellationToken): Promise - /** - * Should be true when interactive is supported. - */ - interactive?: boolean - /** - * Description of list. - */ - description?: string - /** - * Detail description, shown in help. - */ - detail?: string - /** - * Options supported by list. - */ - options?: ListArgument[] - /** - * Resolve list item. - */ - resolveItem?(item: ListItem): Promise - /** - * Highlight buffer by vim's syntax commands. - */ - doHighlight?(): void - /** - * Called on list unregisted. - */ - dispose?(): void - } - - export interface PreviewOptions { - bufname?: string - lines: string[] - filetype: string - lnum?: number - range?: Range - /** - * @deprecated not used - */ - sketch?: boolean - } - - export namespace listManager { - /** - * Registered list names set. - */ - export const names: ReadonlyArray - /** - * Register list, list session can be created by `CocList [name]` after registered. - */ - export function registerList(list: IList): Disposable - } - // }} - - // snippetManager module {{ - export interface SnippetSession { - isActive: boolean - } - export interface TextmateSnippet { - toString(): string - } - /** - * A snippet string is a template which allows to insert text - * and to control the editor cursor when insertion happens. - * - * A snippet can define tab stops and placeholders with `$1`, `$2` - * and `${3:foo}`. `$0` defines the final tab stop, it defaults to - * the end of the snippet. Variables are defined with `$name` and - * `${name:default value}`. The full snippet syntax is documented - * [here](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_creating-your-own-snippets). - */ - export class SnippetString { - /** - * The snippet string. - */ - value: string - - constructor( - /** - * The default snippet string. - */ - value?: string - ) - - /** - * Builder-function that appends the given string to - * the {@link SnippetString.value `value`} of this snippet string. - * - * @param string A value to append 'as given'. The string will be escaped. - * @return This snippet string. - */ - appendText(string: string): SnippetString - - /** - * Builder-function that appends a tabstop (`$1`, `$2` etc) to - * the {@link SnippetString.value `value`} of this snippet string. - * - * @param number The number of this tabstop, defaults to an auto-increment - * value starting at 1. - * @return This snippet string. - */ - appendTabstop(number?: number): SnippetString - - /** - * Builder-function that appends a placeholder (`${1:value}`) to - * the {@link SnippetString.value `value`} of this snippet string. - * - * @param value The value of this placeholder - either a string or a function - * with which a nested snippet can be created. - * @param number The number of this tabstop, defaults to an auto-increment - * value starting at 1. - * @return This snippet string. - */ - appendPlaceholder(value: string | ((snippet: SnippetString) => any), number?: number): SnippetString - - /** - * Builder-function that appends a choice (`${1|a,b,c|}`) to - * the {@link SnippetString.value `value`} of this snippet string. - * - * @param values The values for choices - the array of strings - * @param number The number of this tabstop, defaults to an auto-increment - * value starting at 1. - * @return This snippet string. - */ - appendChoice(values: string[], number?: number): SnippetString - - /** - * Builder-function that appends a variable (`${VAR}`) to - * the {@link SnippetString.value `value`} of this snippet string. - * - * @param name The name of the variable - excluding the `$`. - * @param defaultValue The default value which is used when the variable name cannot - * be resolved - either a string or a function with which a nested snippet can be created. - * @return This snippet string. - */ - appendVariable(name: string, defaultValue: string | ((snippet: SnippetString) => any)): SnippetString - } - /** - * Manage snippet sessions. - */ - export namespace snippetManager { - /** - * Get snippet session by bufnr. - */ - export function getSession(bufnr: number): SnippetSession | undefined - /** - * Parse snippet string to TextmateSnippet. - */ - export function resolveSnippet(body: string): Promise - /** - * Insert snippet at current buffer. - * - * @param {string} snippet Textmate snippet string. - * @param {boolean} select Not select first placeholder when false, default `true`. - * @param {Range} range Repalce range, insert to current cursor position when undefined. - * @returns {Promise} true when insert success. - */ - export function insertSnippet(snippet: string | SnippetString, select?: boolean, range?: Range): Promise - - /** - * Jump to next placeholder, only works when snippet session activated. - */ - export function nextPlaceholder(): Promise - /** - * Jump to previous placeholder, only works when snippet session activated. - */ - export function previousPlaceholder(): Promise - /** - * Cancel snippet session of current buffer, does nothing when no session activated. - */ - export function cancel(): void - /** - * Check if snippet activated for bufnr. - */ - export function isActived(bufnr: number): boolean - } - // }} - - // diagnosticManager module {{ - export interface DiagnosticItem { - file: string - lnum: number - col: number - source: string - code: string | number - message: string - severity: string - level: number - location: Location - } - - export enum DiagnosticKind { - Syntax, - Semantic, - Suggestion, - } - - /** - * A diagnostics collection is a container that manages a set of - * [diagnostics](#Diagnostic). Diagnostics are always scopes to a - * diagnostics collection and a resource. - * - * To get an instance of a `DiagnosticCollection` use - * [createDiagnosticCollection](#languages.createDiagnosticCollection). - */ - export interface DiagnosticCollection { - - /** - * The name of this diagnostic collection, for instance `typescript`. Every diagnostic - * from this collection will be associated with this name. Also, the task framework uses this - * name when defining [problem matchers](https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher). - */ - readonly name: string - - /** - * Assign diagnostics for given resource. Will replace - * existing diagnostics for that resource. - * - * @param uri A resource identifier. - * @param diagnostics Array of diagnostics or `undefined` - */ - set(uri: string, diagnostics: Diagnostic[] | null): void - /** - * Replace all entries in this collection. - * - * Diagnostics of multiple tuples of the same uri will be merged, e.g - * `[[file1, [d1]], [file1, [d2]]]` is equivalent to `[[file1, [d1, d2]]]`. - * If a diagnostics item is `undefined` as in `[file1, undefined]` - * all previous but not subsequent diagnostics are removed. - * - * @param entries An array of tuples, like `[[file1, [d1, d2]], [file2, [d3, d4, d5]]]`, or `undefined`. - */ - set(entries: [string, Diagnostic[] | null][] | string, diagnostics?: Diagnostic[]): void - - /** - * Remove all diagnostics from this collection that belong - * to the provided `uri`. The same as `#set(uri, undefined)`. - * - * @param uri A resource identifier. - */ - delete(uri: string): void - - /** - * Remove all diagnostics from this collection. The same - * as calling `#set(undefined)` - */ - clear(): void - - /** - * Iterate over each entry in this collection. - * - * @param callback Function to execute for each entry. - * @param thisArg The `this` context used when invoking the handler function. - */ - forEach(callback: (uri: string, diagnostics: Diagnostic[], collection: DiagnosticCollection) => any, thisArg?: any): void - - /** - * Get the diagnostics for a given resource. *Note* that you cannot - * modify the diagnostics-array returned from this call. - * - * @param uri A resource identifier. - * @returns An immutable array of [diagnostics](#Diagnostic) or `undefined`. - */ - get(uri: string): Diagnostic[] | undefined - - /** - * Check if this collection contains diagnostics for a - * given resource. - * - * @param uri A resource identifier. - * @returns `true` if this collection has diagnostic for the given resource. - */ - has(uri: string): boolean - - /** - * Dispose and free associated resources. Calls - * [clear](#DiagnosticCollection.clear). - */ - dispose(): void - } - - export interface DiagnosticEventParams { - bufnr: number - uri: string - diagnostics: ReadonlyArray - } - - export namespace diagnosticManager { - - export const onDidRefresh: Event - /** - * Create collection by name - */ - export function create(name: string): DiagnosticCollection - - /** - * Get readonly diagnostics for uri - */ - export function getDiagnostics(uri: string): { [collection: string]: Diagnostic[] } - - /** - * Get readonly diagnostics by document and range. - */ - export function getDiagnosticsInRange(doc: TextDocumentIdentifier, range: Range): ReadonlyArray - /** - * All diagnostics of current workspace - */ - export function getDiagnosticList(): ReadonlyArray - - /** - * All diagnostics at current cursor position. - */ - export function getCurrentDiagnostics(): Promise> - - /** - * Get diagnostic collection. - */ - export function getCollectionByName(name: string): DiagnosticCollection - } - // }} - - // language client {{ - /** - * An action to be performed when the connection is producing errors. - */ - export enum ErrorAction { - /** - * Continue running the server. - */ - Continue = 1, - /** - * Shutdown the server. - */ - Shutdown = 2 - } - /** - * An action to be performed when the connection to a server got closed. - */ - export enum CloseAction { - /** - * Don't restart the server. The connection stays closed. - */ - DoNotRestart = 1, - /** - * Restart the server. - */ - Restart = 2 - } - /** - * A pluggable error handler that is invoked when the connection is either - * producing errors or got closed. - */ - export interface ErrorHandler { - /** - * An error has occurred while writing or reading from the connection. - * - * @param error - the error received - * @param message - the message to be delivered to the server if know. - * @param count - a count indicating how often an error is received. Will - * be reset if a message got successfully send or received. - */ - error(error: Error, message: { jsonrpc: string }, count: number): ErrorAction - /** - * The connection to the server got closed. - */ - closed(): CloseAction - } - export interface InitializationFailedHandler { - (error: Error | any): boolean - } - - export interface SynchronizeOptions { - configurationSection?: string | string[] - fileEvents?: FileSystemWatcher | FileSystemWatcher[] - } - - export enum RevealOutputChannelOn { - Info = 1, - Warn = 2, - Error = 3, - Never = 4 - } - export interface ConfigurationItem { - /** - * The scope to get the configuration section for. - */ - scopeUri?: string - /** - * The configuration section asked for. - */ - section?: string - } - export interface ResponseError { - code: number - data: D | undefined - } - - export type HandlerResult = R | ResponseError | Thenable | Thenable> | Thenable> - - export interface RequestHandler { - (params: P, token: CancellationToken): HandlerResult - } - - export interface RequestHandler0 { - (token: CancellationToken): HandlerResult - } - /** - * The parameters of a configuration request. - */ - export interface ConfigurationParams { - items: ConfigurationItem[] - } - - export interface ConfigurationWorkspaceMiddleware { - configuration?: (params: ConfigurationParams, token: CancellationToken, next: RequestHandler) => HandlerResult - } - - export interface WorkspaceFolderWorkspaceMiddleware { - workspaceFolders?: (token: CancellationToken, next: RequestHandler0) => HandlerResult - didChangeWorkspaceFolders?: NextSignature - } - - export interface ProvideTypeDefinitionSignature { - ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken - ): ProviderResult - } - - export interface TypeDefinitionMiddleware { - provideTypeDefinition?: ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken, - next: ProvideTypeDefinitionSignature - ) => ProviderResult - } - - export interface ProvideImplementationSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult - } - - export interface ImplementationMiddleware { - provideImplementation?: (this: void, document: TextDocument, position: Position, token: CancellationToken, next: ProvideImplementationSignature) => ProviderResult - } - export type ProvideDocumentColorsSignature = (document: TextDocument, token: CancellationToken) => ProviderResult - - export type ProvideColorPresentationSignature = ( - color: Color, - context: { document: TextDocument; range: Range }, - token: CancellationToken - ) => ProviderResult - - export interface ColorProviderMiddleware { - provideDocumentColors?: ( - this: void, - document: TextDocument, - token: CancellationToken, - next: ProvideDocumentColorsSignature - ) => ProviderResult - provideColorPresentations?: ( - this: void, - color: Color, - context: { document: TextDocument; range: Range }, - token: CancellationToken, - next: ProvideColorPresentationSignature - ) => ProviderResult - } - - export interface ProvideDeclarationSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult - } - - export interface DeclarationMiddleware { - provideDeclaration?: (this: void, document: TextDocument, position: Position, token: CancellationToken, next: ProvideDeclarationSignature) => ProviderResult - } - - export type ProvideFoldingRangeSignature = ( - this: void, - document: TextDocument, - context: FoldingContext, - token: CancellationToken - ) => ProviderResult - - export interface FoldingRangeProviderMiddleware { - provideFoldingRanges?: ( - this: void, - document: TextDocument, - context: FoldingContext, - token: CancellationToken, - next: ProvideFoldingRangeSignature - ) => ProviderResult - } - - export interface PrepareCallHierarchySignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult - } - - export interface CallHierarchyIncomingCallsSignature { - (this: void, item: CallHierarchyItem, token: CancellationToken): ProviderResult - } - - export interface CallHierarchyOutgoingCallsSignature { - (this: void, item: CallHierarchyItem, token: CancellationToken): ProviderResult - } - export interface CallHierarchyMiddleware { - prepareCallHierarchy?: ( - this: void, - document: TextDocument, - positions: Position, - token: CancellationToken, - next: PrepareCallHierarchySignature - ) => ProviderResult - provideCallHierarchyIncomingCalls?: ( - this: void, - item: CallHierarchyItem, - token: CancellationToken, - next: CallHierarchyIncomingCallsSignature - ) => ProviderResult - provideCallHierarchyOutgoingCalls?: ( - this: void, - item: CallHierarchyItem, - token: CancellationToken, - next: CallHierarchyOutgoingCallsSignature - ) => ProviderResult - } - - export interface DocumentSemanticsTokensSignature { - (this: void, document: TextDocument, token: CancellationToken): ProviderResult - } - - export interface DocumentSemanticsTokensEditsSignature { - (this: void, document: TextDocument, previousResultId: string, token: CancellationToken): ProviderResult - } - - export interface DocumentRangeSemanticTokensSignature { - (this: void, document: TextDocument, range: Range, token: CancellationToken): ProviderResult - } - - export interface SemanticTokensMiddleware { - provideDocumentSemanticTokens?: ( - this: void, - document: TextDocument, - token: CancellationToken, - next: DocumentSemanticsTokensSignature - ) => ProviderResult - provideDocumentSemanticTokensEdits?: ( - this: void, - document: TextDocument, - previousResultId: string, - token: CancellationToken, - next: DocumentSemanticsTokensEditsSignature - ) => ProviderResult - provideDocumentRangeSemanticTokens?: ( - this: void, - document: TextDocument, - range: Range, - token: CancellationToken, - next: DocumentRangeSemanticTokensSignature - ) => ProviderResult - } - - export interface ProvideLinkedEditingRangeSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult - } - - export interface LinkedEditingRangeMiddleware { - provideLinkedEditingRange?: ( - this: void, - document: TextDocument, - position: Position, - token: CancellationToken, - next: ProvideLinkedEditingRangeSignature - ) => ProviderResult - } - - export interface ProvideSelectionRangeSignature { - (this: void, document: TextDocument, positions: Position[], token: CancellationToken): ProviderResult - } - - export interface SelectionRangeProviderMiddleware { - provideSelectionRanges?: (this: void, document: TextDocument, positions: Position[], token: CancellationToken, next: ProvideSelectionRangeSignature) => ProviderResult - } - - export interface HandleWorkDoneProgressSignature { - (this: void, token: ProgressToken, params: WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd): void - } - - export interface HandleDiagnosticsSignature { - (this: void, uri: string, diagnostics: Diagnostic[]): void - } - - export interface ProvideCompletionItemsSignature { - (this: void, document: TextDocument, position: Position, context: CompletionContext, token: CancellationToken): ProviderResult - } - - export interface ResolveCompletionItemSignature { - (this: void, item: CompletionItem, token: CancellationToken): ProviderResult - } - - export interface ProvideHoverSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult - } - - export interface ProvideSignatureHelpSignature { - (this: void, document: TextDocument, position: Position, context: SignatureHelpContext, token: CancellationToken): ProviderResult - } - - export interface ProvideDefinitionSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult - } - - export interface ProvideReferencesSignature { - (this: void, document: TextDocument, position: Position, options: { - includeDeclaration: boolean - }, token: CancellationToken): ProviderResult - } - - export interface ProvideDocumentHighlightsSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult - } - - export interface ProvideDocumentSymbolsSignature { - (this: void, document: TextDocument, token: CancellationToken): ProviderResult - } - - export interface ProvideWorkspaceSymbolsSignature { - (this: void, query: string, token: CancellationToken): ProviderResult - } - - export interface ProvideCodeActionsSignature { - (this: void, document: TextDocument, range: Range, context: CodeActionContext, token: CancellationToken): ProviderResult<(Command | CodeAction)[]> - } - - export interface ResolveCodeActionSignature { - (this: void, item: CodeAction, token: CancellationToken): ProviderResult - } - - export interface ProvideCodeLensesSignature { - (this: void, document: TextDocument, token: CancellationToken): ProviderResult - } - - export interface ResolveCodeLensSignature { - (this: void, codeLens: CodeLens, token: CancellationToken): ProviderResult - } - - export interface ProvideDocumentFormattingEditsSignature { - (this: void, document: TextDocument, options: FormattingOptions, token: CancellationToken): ProviderResult - } - - export interface ProvideDocumentRangeFormattingEditsSignature { - (this: void, document: TextDocument, range: Range, options: FormattingOptions, token: CancellationToken): ProviderResult - } - - export interface ProvideOnTypeFormattingEditsSignature { - (this: void, document: TextDocument, position: Position, ch: string, options: FormattingOptions, token: CancellationToken): ProviderResult - } - - export interface PrepareRenameSignature { - (this: void, document: TextDocument, position: Position, token: CancellationToken): ProviderResult - } - - export interface ProvideRenameEditsSignature { - (this: void, document: TextDocument, position: Position, newName: string, token: CancellationToken): ProviderResult - } - - export interface ProvideDocumentLinksSignature { - (this: void, document: TextDocument, token: CancellationToken): ProviderResult - } - - export interface ResolveDocumentLinkSignature { - (this: void, link: DocumentLink, token: CancellationToken): ProviderResult - } - - export interface ExecuteCommandSignature { - (this: void, command: string, args: any[]): ProviderResult - } - - export interface NextSignature { - (this: void, data: P, next: (data: P) => R): R - } - - export interface DidChangeConfigurationSignature { - (this: void, sections: string[] | undefined): void - } - - export interface DidChangeWatchedFileSignature { - (this: void, event: FileEvent): void - } - - export interface _WorkspaceMiddleware { - didChangeConfiguration?: (this: void, sections: string[] | undefined, next: DidChangeConfigurationSignature) => void - didChangeWatchedFile?: (this: void, event: FileEvent, next: DidChangeWatchedFileSignature) => void - } - - export type WorkspaceMiddleware = _WorkspaceMiddleware & ConfigurationWorkspaceMiddleware & WorkspaceFolderWorkspaceMiddleware - - /** - * Params to show a document. - * - * @since 3.16.0 - */ - export interface ShowDocumentParams { - /** - * The document uri to show. - */ - uri: string - /** - * Indicates to show the resource in an external program. - * To show for example `https://code.visualstudio.com/` - * in the default WEB browser set `external` to `true`. - */ - external?: boolean - /** - * An optional property to indicate whether the editor - * showing the document should take focus or not. - * Clients might ignore this property if an external - * program in started. - */ - takeFocus?: boolean - /** - * An optional selection range if the document is a text - * document. Clients might ignore the property if an - * external program is started or the file is not a text - * file. - */ - selection?: Range - } - /** - * The result of an show document request. - * - * @since 3.16.0 - */ - export interface ShowDocumentResult { - /** - * A boolean indicating if the show was successful. - */ - success: boolean - } - - export interface _WindowMiddleware { - showDocument?: ( - this: void, - params: ShowDocumentParams, - next: RequestHandler - ) => Promise - } - export type WindowMiddleware = _WindowMiddleware - - /** - * The Middleware lets extensions intercept the request and notications send and received - * from the server - */ - interface _Middleware { - didOpen?: NextSignature - didChange?: NextSignature - willSave?: NextSignature - willSaveWaitUntil?: NextSignature> - didSave?: NextSignature - didClose?: NextSignature - handleDiagnostics?: (this: void, uri: string, diagnostics: Diagnostic[], next: HandleDiagnosticsSignature) => void - provideCompletionItem?: (this: void, document: TextDocument, position: Position, context: CompletionContext, token: CancellationToken, next: ProvideCompletionItemsSignature) => ProviderResult - resolveCompletionItem?: (this: void, item: CompletionItem, token: CancellationToken, next: ResolveCompletionItemSignature) => ProviderResult - provideHover?: (this: void, document: TextDocument, position: Position, token: CancellationToken, next: ProvideHoverSignature) => ProviderResult - provideSignatureHelp?: (this: void, document: TextDocument, position: Position, context: SignatureHelpContext, token: CancellationToken, next: ProvideSignatureHelpSignature) => ProviderResult - provideDefinition?: (this: void, document: TextDocument, position: Position, token: CancellationToken, next: ProvideDefinitionSignature) => ProviderResult - provideReferences?: (this: void, document: TextDocument, position: Position, options: { - includeDeclaration: boolean - }, token: CancellationToken, next: ProvideReferencesSignature) => ProviderResult - provideDocumentHighlights?: (this: void, document: TextDocument, position: Position, token: CancellationToken, next: ProvideDocumentHighlightsSignature) => ProviderResult - provideDocumentSymbols?: (this: void, document: TextDocument, token: CancellationToken, next: ProvideDocumentSymbolsSignature) => ProviderResult - provideWorkspaceSymbols?: (this: void, query: string, token: CancellationToken, next: ProvideWorkspaceSymbolsSignature) => ProviderResult - provideCodeActions?: (this: void, document: TextDocument, range: Range, context: CodeActionContext, token: CancellationToken, next: ProvideCodeActionsSignature) => ProviderResult<(Command | CodeAction)[]> - handleWorkDoneProgress?: (this: void, token: ProgressToken, params: WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd, next: HandleWorkDoneProgressSignature) => void - resolveCodeAction?: (this: void, item: CodeAction, token: CancellationToken, next: ResolveCodeActionSignature) => ProviderResult - provideCodeLenses?: (this: void, document: TextDocument, token: CancellationToken, next: ProvideCodeLensesSignature) => ProviderResult - resolveCodeLens?: (this: void, codeLens: CodeLens, token: CancellationToken, next: ResolveCodeLensSignature) => ProviderResult - provideDocumentFormattingEdits?: (this: void, document: TextDocument, options: FormattingOptions, token: CancellationToken, next: ProvideDocumentFormattingEditsSignature) => ProviderResult - provideDocumentRangeFormattingEdits?: (this: void, document: TextDocument, range: Range, options: FormattingOptions, token: CancellationToken, next: ProvideDocumentRangeFormattingEditsSignature) => ProviderResult - provideOnTypeFormattingEdits?: (this: void, document: TextDocument, position: Position, ch: string, options: FormattingOptions, token: CancellationToken, next: ProvideOnTypeFormattingEditsSignature) => ProviderResult - prepareRename?: (this: void, document: TextDocument, position: Position, token: CancellationToken, next: PrepareRenameSignature) => ProviderResult - provideRenameEdits?: (this: void, document: TextDocument, position: Position, newName: string, token: CancellationToken, next: ProvideRenameEditsSignature) => ProviderResult - provideDocumentLinks?: (this: void, document: TextDocument, token: CancellationToken, next: ProvideDocumentLinksSignature) => ProviderResult - resolveDocumentLink?: (this: void, link: DocumentLink, token: CancellationToken, next: ResolveDocumentLinkSignature) => ProviderResult - executeCommand?: (this: void, command: string, args: any[], next: ExecuteCommandSignature) => ProviderResult - workspace?: WorkspaceMiddleware - window?: WindowMiddleware - } - export type Middleware = _Middleware & TypeDefinitionMiddleware & ImplementationMiddleware & ColorProviderMiddleware & DeclarationMiddleware & FoldingRangeProviderMiddleware & CallHierarchyMiddleware & SemanticTokensMiddleware & LinkedEditingRangeMiddleware & SelectionRangeProviderMiddleware - - export interface ConnectionOptions { - // cancellationStrategy: CancellationStrategy - maxRestartCount?: number - } - - export interface LanguageClientOptions { - ignoredRootPaths?: string[] - disableWorkspaceFolders?: boolean - disableSnippetCompletion?: boolean - disableDynamicRegister?: boolean - disableDiagnostics?: boolean - disableCompletion?: boolean - formatterPriority?: number - documentSelector?: DocumentSelector | string[] - synchronize?: SynchronizeOptions - diagnosticCollectionName?: string - outputChannelName?: string - outputChannel?: OutputChannel - revealOutputChannelOn?: RevealOutputChannelOn - /** - * The encoding use to read stdout and stderr. Defaults - * to 'utf8' if omitted. - */ - stdioEncoding?: string - initializationOptions?: any | (() => any) - initializationFailedHandler?: InitializationFailedHandler - progressOnInitialization?: boolean - errorHandler?: ErrorHandler - middleware?: Middleware - workspaceFolder?: WorkspaceFolder - connectionOptions?: ConnectionOptions - markdown?: { - isTrusted: boolean - } - } - export enum State { - Stopped = 1, - Running = 2, - Starting = 3 - } - export interface StateChangeEvent { - oldState: State - newState: State - } - export enum ClientState { - Initial = 0, - Starting = 1, - StartFailed = 2, - Running = 3, - Stopping = 4, - Stopped = 5 - } - export interface RegistrationData { - id: string - registerOptions: T - } - /** - * A static feature. A static feature can't be dynamically activate via the - * server. It is wired during the initialize sequence. - */ - export interface StaticFeature { - /** - * Called to fill the initialize params. - * - * @params the initialize params. - */ - fillInitializeParams?: (params: any) => void - /** - * Called to fill in the client capabilities this feature implements. - * - * @param capabilities The client capabilities to fill. - */ - fillClientCapabilities(capabilities: any): void - /** - * Initialize the feature. This method is called on a feature instance - * when the client has successfully received the initialize request from - * the server and before the client sends the initialized notification - * to the server. - * - * @param capabilities the server capabilities - * @param documentSelector the document selector pass to the client's constuctor. - * May be `undefined` if the client was created without a selector. - */ - initialize(capabilities: any, documentSelector: DocumentSelector | undefined): void - /** - * Called when the client is stopped to dispose this feature. Usually a feature - * unregisters listeners registered hooked up with the VS Code extension host. - */ - dispose(): void - } - - class ParameterStructures { - private readonly kind - /** - * The parameter structure is automatically inferred on the number of parameters - * and the parameter type in case of a single param. - */ - static readonly auto: ParameterStructures - /** - * Forces `byPosition` parameter structure. This is useful if you have a single - * parameter which has a literal type. - */ - static readonly byPosition: ParameterStructures - /** - * Forces `byName` parameter structure. This is only useful when having a single - * parameter. The library will report errors if used with a different number of - * parameters. - */ - static readonly byName: ParameterStructures - private constructor() - static is(value: any): value is ParameterStructures - toString(): string - } - /** - * An interface to type messages. - */ - export interface MessageSignature { - readonly method: string - readonly numberOfParams: number - readonly parameterStructures: ParameterStructures - } - - /** - * - * An abstract implementation of a MessageType. - */ - abstract class AbstractMessageSignature implements MessageSignature { - readonly method: string - readonly numberOfParams: number - constructor(method: string, numberOfParams: number) - get parameterStructures(): ParameterStructures - } - - /** - * Classes to type request response pairs - */ - export class RequestType0 extends AbstractMessageSignature { - /** - * Clients must not use this property. It is here to ensure correct typing. - */ - readonly _: [R, E, _EM] | undefined - constructor(method: string) - } - - export class RequestType extends AbstractMessageSignature { - private _parameterStructures - /** - * Clients must not use this property. It is here to ensure correct typing. - */ - readonly _: [P, R, E, _EM] | undefined - constructor(method: string, _parameterStructures?: ParameterStructures) - get parameterStructures(): ParameterStructures - } - - export class NotificationType

    extends AbstractMessageSignature { - /** - * Clients must not use this property. It is here to ensure correct typing. - */ - readonly _: [P, _EM] | undefined - constructor(method: string) - } - - export class NotificationType0 extends AbstractMessageSignature { - /** - * Clients must not use this property. It is here to ensure correct typing. - */ - readonly _: [_EM] | undefined - constructor(method: string) - } - - export interface InitializeParams { - /** - * The process Id of the parent process that started - * the server. - */ - processId: number | null - /** - * Information about the client - * - * @since 3.15.0 - */ - clientInfo?: { - /** - * The name of the client as defined by the client. - */ - name: string - /** - * The client's version as defined by the client. - */ - version?: string - } - /** - * The rootPath of the workspace. Is null - * if no folder is open. - * - * @deprecated in favour of rootUri. - */ - rootPath?: string | null - /** - * The rootUri of the workspace. Is null if no - * folder is open. If both `rootPath` and `rootUri` are set - * `rootUri` wins. - * - * @deprecated in favour of workspaceFolders. - */ - rootUri: string | null - /** - * The capabilities provided by the client (editor or tool) - */ - capabilities: any - /** - * User provided initialization options. - */ - initializationOptions?: any - /** - * The initial trace setting. If omitted trace is disabled ('off'). - */ - trace?: 'off' | 'messages' | 'verbose' - /** - * An optional token that a server can use to report work done progress. - */ - workDoneToken?: ProgressToken - } - class RegistrationType { - /** - * Clients must not use this property. It is here to ensure correct typing. - */ - readonly ____: [RO, _EM] | undefined - readonly method: string - constructor(method: string) - } - /** - * The result returned from an initialize request. - */ - export interface InitializeResult { - /** - * The capabilities the language server provides. - */ - capabilities: any - /** - * Information about the server. - * - * @since 3.15.0 - */ - serverInfo?: { - /** - * The name of the server as defined by the server. - */ - name: string - /** - * The servers's version as defined by the server. - */ - version?: string - } - /** - * Custom initialization results. - */ - [custom: string]: any - } - - export interface DynamicFeature { - /** - * Called to fill the initialize params. - * - * @params the initialize params. - */ - fillInitializeParams?: (params: InitializeParams) => void - /** - * Called to fill in the client capabilities this feature implements. - * - * @param capabilities The client capabilities to fill. - */ - fillClientCapabilities(capabilities: any): void - /** - * Initialize the feature. This method is called on a feature instance - * when the client has successfully received the initialize request from - * the server and before the client sends the initialized notification - * to the server. - * - * @param capabilities the server capabilities. - * @param documentSelector the document selector pass to the client's constructor. - * May be `undefined` if the client was created without a selector. - */ - initialize(capabilities: any, documentSelector: DocumentSelector | undefined): void - /** - * The signature (e.g. method) for which this features support dynamic activation / registration. - */ - registrationType: RegistrationType - /** - * Is called when the server send a register request for the given message. - * - * @param data additional registration data as defined in the protocol. - */ - register(data: RegistrationData): void - /** - * Is called when the server wants to unregister a feature. - * - * @param id the id used when registering the feature. - */ - unregister(id: string): void - /** - * Called when the client is stopped to dispose this feature. Usually a feature - * unregisters listeners registered hooked up with the VS Code extension host. - */ - dispose(): void - } - - export interface NotificationFeature { - /** - * Triggers the corresponding RPC method. - */ - getProvider(document: TextDocument): { - send: T - } - } - - export interface ExecutableOptions { - cwd?: string - env?: any - detached?: boolean - shell?: boolean - } - - export interface Executable { - command: string - args?: string[] - options?: ExecutableOptions - } - - export interface ForkOptions { - cwd?: string - env?: any - execPath?: string - encoding?: string - execArgv?: string[] - } - - export interface StreamInfo { - writer: NodeJS.WritableStream - reader: NodeJS.ReadableStream - detached?: boolean - } - - export enum TransportKind { - stdio = 0, - ipc = 1, - pipe = 2, - socket = 3 - } - - export interface SocketTransport { - kind: TransportKind.socket - port: number - } - - export interface NodeModule { - module: string - transport?: TransportKind | SocketTransport - args?: string[] - runtime?: string - options?: ForkOptions - } - - export interface ChildProcessInfo { - process: cp.ChildProcess - detached: boolean - } - - export interface PartialMessageInfo { - readonly messageToken: number - readonly waitingTime: number - } - - export interface MessageReader { - readonly onError: Event - readonly onClose: Event - readonly onPartialMessage: Event - listen(callback: (data: { jsonrpc: string }) => void): void - dispose(): void - } - - export interface MessageWriter { - readonly onError: Event<[Error, { jsonrpc: string } | undefined, number | undefined]> - readonly onClose: Event - write(msg: { jsonrpc: string }): void - dispose(): void - } - - export class NullLogger { - constructor() - error(message: string): void - warn(message: string): void - info(message: string): void - log(message: string): void - } - - export interface MessageTransports { - reader: MessageReader - writer: MessageWriter - detached?: boolean - } - - export namespace MessageTransports { - /** - * Checks whether the given value conforms to the [MessageTransports](#MessageTransports) interface. - */ - function is(value: any): value is MessageTransports - } - - export type ServerOptions = Executable | NodeModule | { - run: Executable - debug: Executable - } | { - run: NodeModule - debug: NodeModule - } | (() => Promise) - - export interface _EM { - _$endMarker$_: number - } - - export class ProgressType

    { - /** - * Clients must not use this property. It is here to ensure correct typing. - */ - readonly __?: [P, _EM] - constructor() - } - - export enum Trace { - Off = 0, - Messages = 1, - Verbose = 2 - } - - /** - * A language server for manage a language server. - * It's recommended to use `services.registLanguageClient` for regist language client to serviers, - * you can have language client listed in `CocList services` and services could start the language client - * by `documentselector` of `clientOptions`. - */ - export class LanguageClient { - readonly id: string - readonly name: string - constructor(id: string, name: string, serverOptions: ServerOptions, clientOptions: LanguageClientOptions, forceDebug?: boolean) - /** - * Create language client by name and options, don't forget regist language client - * to services by `services.registLanguageClient` - */ - constructor(name: string, serverOptions: ServerOptions, clientOptions: LanguageClientOptions, forceDebug?: boolean) - /** - * R => result - * E => Error result - */ - sendRequest(type: RequestType0, token?: CancellationToken): Promise - /** - * P => params - * R => result - * E => Error result - */ - sendRequest(type: RequestType, params: P, token?: CancellationToken): Promise - sendRequest(method: string, token?: CancellationToken): Promise - sendRequest(method: string, param: any, token?: CancellationToken): Promise - - onRequest(type: RequestType0, handler: RequestHandler0): Disposable - onRequest(type: RequestType, handler: RequestHandler): Disposable - onRequest(method: string, handler: (...params: any[]) => HandlerResult): Disposable - - sendNotification(type: NotificationType0): void - sendNotification

    (type: NotificationType

    , params?: P): void - sendNotification(method: string): void - sendNotification(method: string, params: any): void - - onNotification(type: NotificationType0, handler: () => void): Disposable - onNotification

    (type: NotificationType

    , handler: (params: P) => void): Disposable - onNotification(method: string, handler: (...params: any[]) => void): Disposable - - onProgress

    (type: ProgressType, token: string | number, handler: (params: P) => void): Disposable - sendProgress

    (type: ProgressType

    , token: string | number, value: P): void - - /** - * Append info to outputChannel - */ - info(message: string, data?: any): void - /** - * Append warning to outputChannel - */ - warn(message: string, data?: any): void - /** - * append error to outputChannel - */ - error(message: string, data?: any): void - getPublicState(): State - get initializeResult(): InitializeResult | undefined - - get clientOptions(): LanguageClientOptions - /** - * Fired on language server state change. - */ - get onDidChangeState(): Event - get outputChannel(): OutputChannel - get diagnostics(): DiagnosticCollection | undefined - - /** - * Current running state. - */ - get serviceState(): ServiceStat - /** - * Check if server could start. - */ - needsStart(): boolean - /** - * Check if server could stop. - */ - needsStop(): boolean - onReady(): Promise - get started(): boolean - set trace(value: Trace) - - /** - * Stop language server. - */ - stop(): Promise - - /** - * Start language server, not needed when registered to services by `services.registLanguageClient` - */ - start(): Disposable - /** - * Restart language client. - */ - restart(): void - - /** - * Regist custom feature. - */ - registerFeature(feature: StaticFeature | DynamicFeature): void - - /** - * Log failed request to outputChannel. - */ - handleFailedRequest(type: MessageSignature, token: CancellationToken | undefined, error: any, defaultValue: T) - } - - /** - * Monitor for setting change, restart language server when specified setting changed. - */ - export class SettingMonitor { - constructor(client: LanguageClient, setting: string) - start(): Disposable - } - // }} -} diff --git a/vim-config/plugins/coc.nvim/yarn.lock b/vim-config/plugins/coc.nvim/yarn.lock deleted file mode 100644 index 8b240bb8..00000000 --- a/vim-config/plugins/coc.nvim/yarn.lock +++ /dev/null @@ -1,3713 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@babel/code-frame@7.12.11": - version "7.12.11" - resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.12.11.tgz#f4ad435aa263db935b8f10f2c552d23fb716a63f" - integrity sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw== - dependencies: - "@babel/highlight" "^7.10.4" - -"@babel/code-frame@^7.12.13", "@babel/code-frame@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.14.5.tgz#23b08d740e83f49c5e59945fbf1b43e80bbf4edb" - integrity sha512-9pzDqyc6OLDaqe+zbACgFkb6fKMNG6CObKpnYXChRsvYGyEdc7CA2BaqeOM+vOtCS5ndmJicPJhKAwYRI6UfFw== - dependencies: - "@babel/highlight" "^7.14.5" - -"@babel/compat-data@^7.14.5": - version "7.14.7" - resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.14.7.tgz#7b047d7a3a89a67d2258dc61f604f098f1bc7e08" - integrity sha512-nS6dZaISCXJ3+518CWiBfEr//gHyMO02uDxBkXTKZDN5POruCnOZ1N4YBRZDCabwF8nZMWBpRxIicmXtBs+fvw== - -"@babel/compat-data@^7.15.0": - version "7.15.0" - resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.15.0.tgz#2dbaf8b85334796cafbb0f5793a90a2fc010b176" - integrity sha512-0NqAC1IJE0S0+lL1SWFMxMkz1pKCNCjI4tr2Zx4LJSXxCLAdr6KyArnY+sno5m3yH9g737ygOyPABDsnXkpxiA== - -"@babel/core@^7.1.0", "@babel/core@^7.7.5": - version "7.14.8" - resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.14.8.tgz#20cdf7c84b5d86d83fac8710a8bc605a7ba3f010" - integrity sha512-/AtaeEhT6ErpDhInbXmjHcUQXH0L0TEgscfcxk1qbOvLuKCa5aZT0SOOtDKFY96/CLROwbLSKyFor6idgNaU4Q== - dependencies: - "@babel/code-frame" "^7.14.5" - "@babel/generator" "^7.14.8" - "@babel/helper-compilation-targets" "^7.14.5" - "@babel/helper-module-transforms" "^7.14.8" - "@babel/helpers" "^7.14.8" - "@babel/parser" "^7.14.8" - "@babel/template" "^7.14.5" - "@babel/traverse" "^7.14.8" - "@babel/types" "^7.14.8" - convert-source-map "^1.7.0" - debug "^4.1.0" - gensync "^1.0.0-beta.2" - json5 "^2.1.2" - semver "^6.3.0" - source-map "^0.5.0" - -"@babel/core@^7.7.2": - version "7.15.0" - resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.15.0.tgz#749e57c68778b73ad8082775561f67f5196aafa8" - integrity sha512-tXtmTminrze5HEUPn/a0JtOzzfp0nk+UEXQ/tqIJo3WDGypl/2OFQEMll/zSFU8f/lfmfLXvTaORHF3cfXIQMw== - dependencies: - "@babel/code-frame" "^7.14.5" - "@babel/generator" "^7.15.0" - "@babel/helper-compilation-targets" "^7.15.0" - "@babel/helper-module-transforms" "^7.15.0" - "@babel/helpers" "^7.14.8" - "@babel/parser" "^7.15.0" - "@babel/template" "^7.14.5" - "@babel/traverse" "^7.15.0" - "@babel/types" "^7.15.0" - convert-source-map "^1.7.0" - debug "^4.1.0" - gensync "^1.0.0-beta.2" - json5 "^2.1.2" - semver "^6.3.0" - source-map "^0.5.0" - -"@babel/generator@^7.14.8": - version "7.14.8" - resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.14.8.tgz#bf86fd6af96cf3b74395a8ca409515f89423e070" - integrity sha512-cYDUpvIzhBVnMzRoY1fkSEhK/HmwEVwlyULYgn/tMQYd6Obag3ylCjONle3gdErfXBW61SVTlR9QR7uWlgeIkg== - dependencies: - "@babel/types" "^7.14.8" - jsesc "^2.5.1" - source-map "^0.5.0" - -"@babel/generator@^7.15.0", "@babel/generator@^7.7.2": - version "7.15.0" - resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.15.0.tgz#a7d0c172e0d814974bad5aa77ace543b97917f15" - integrity sha512-eKl4XdMrbpYvuB505KTta4AV9g+wWzmVBW69tX0H2NwKVKd2YJbKgyK6M8j/rgLbmHOYJn6rUklV677nOyJrEQ== - dependencies: - "@babel/types" "^7.15.0" - jsesc "^2.5.1" - source-map "^0.5.0" - -"@babel/helper-compilation-targets@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.14.5.tgz#7a99c5d0967911e972fe2c3411f7d5b498498ecf" - integrity sha512-v+QtZqXEiOnpO6EYvlImB6zCD2Lel06RzOPzmkz/D/XgQiUu3C/Jb1LOqSt/AIA34TYi/Q+KlT8vTQrgdxkbLw== - dependencies: - "@babel/compat-data" "^7.14.5" - "@babel/helper-validator-option" "^7.14.5" - browserslist "^4.16.6" - semver "^6.3.0" - -"@babel/helper-compilation-targets@^7.15.0": - version "7.15.0" - resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.15.0.tgz#973df8cbd025515f3ff25db0c05efc704fa79818" - integrity sha512-h+/9t0ncd4jfZ8wsdAsoIxSa61qhBYlycXiHWqJaQBCXAhDCMbPRSMTGnZIkkmt1u4ag+UQmuqcILwqKzZ4N2A== - dependencies: - "@babel/compat-data" "^7.15.0" - "@babel/helper-validator-option" "^7.14.5" - browserslist "^4.16.6" - semver "^6.3.0" - -"@babel/helper-function-name@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.14.5.tgz#89e2c474972f15d8e233b52ee8c480e2cfcd50c4" - integrity sha512-Gjna0AsXWfFvrAuX+VKcN/aNNWonizBj39yGwUzVDVTlMYJMK2Wp6xdpy72mfArFq5uK+NOuexfzZlzI1z9+AQ== - dependencies: - "@babel/helper-get-function-arity" "^7.14.5" - "@babel/template" "^7.14.5" - "@babel/types" "^7.14.5" - -"@babel/helper-get-function-arity@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-get-function-arity/-/helper-get-function-arity-7.14.5.tgz#25fbfa579b0937eee1f3b805ece4ce398c431815" - integrity sha512-I1Db4Shst5lewOM4V+ZKJzQ0JGGaZ6VY1jYvMghRjqs6DWgxLCIyFt30GlnKkfUeFLpJt2vzbMVEXVSXlIFYUg== - dependencies: - "@babel/types" "^7.14.5" - -"@babel/helper-hoist-variables@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-hoist-variables/-/helper-hoist-variables-7.14.5.tgz#e0dd27c33a78e577d7c8884916a3e7ef1f7c7f8d" - integrity sha512-R1PXiz31Uc0Vxy4OEOm07x0oSjKAdPPCh3tPivn/Eo8cvz6gveAeuyUUPB21Hoiif0uoPQSSdhIPS3352nvdyQ== - dependencies: - "@babel/types" "^7.14.5" - -"@babel/helper-member-expression-to-functions@^7.14.5": - version "7.14.7" - resolved "https://registry.yarnpkg.com/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.14.7.tgz#97e56244beb94211fe277bd818e3a329c66f7970" - integrity sha512-TMUt4xKxJn6ccjcOW7c4hlwyJArizskAhoSTOCkA0uZ+KghIaci0Qg9R043kUMWI9mtQfgny+NQ5QATnZ+paaA== - dependencies: - "@babel/types" "^7.14.5" - -"@babel/helper-member-expression-to-functions@^7.15.0": - version "7.15.0" - resolved "https://registry.yarnpkg.com/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.15.0.tgz#0ddaf5299c8179f27f37327936553e9bba60990b" - integrity sha512-Jq8H8U2kYiafuj2xMTPQwkTBnEEdGKpT35lJEQsRRjnG0LW3neucsaMWLgKcwu3OHKNeYugfw+Z20BXBSEs2Lg== - dependencies: - "@babel/types" "^7.15.0" - -"@babel/helper-module-imports@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-module-imports/-/helper-module-imports-7.14.5.tgz#6d1a44df6a38c957aa7c312da076429f11b422f3" - integrity sha512-SwrNHu5QWS84XlHwGYPDtCxcA0hrSlL2yhWYLgeOc0w7ccOl2qv4s/nARI0aYZW+bSwAL5CukeXA47B/1NKcnQ== - dependencies: - "@babel/types" "^7.14.5" - -"@babel/helper-module-transforms@^7.14.8": - version "7.14.8" - resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.14.8.tgz#d4279f7e3fd5f4d5d342d833af36d4dd87d7dc49" - integrity sha512-RyE+NFOjXn5A9YU1dkpeBaduagTlZ0+fccnIcAGbv1KGUlReBj7utF7oEth8IdIBQPcux0DDgW5MFBH2xu9KcA== - dependencies: - "@babel/helper-module-imports" "^7.14.5" - "@babel/helper-replace-supers" "^7.14.5" - "@babel/helper-simple-access" "^7.14.8" - "@babel/helper-split-export-declaration" "^7.14.5" - "@babel/helper-validator-identifier" "^7.14.8" - "@babel/template" "^7.14.5" - "@babel/traverse" "^7.14.8" - "@babel/types" "^7.14.8" - -"@babel/helper-module-transforms@^7.15.0": - version "7.15.0" - resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.15.0.tgz#679275581ea056373eddbe360e1419ef23783b08" - integrity sha512-RkGiW5Rer7fpXv9m1B3iHIFDZdItnO2/BLfWVW/9q7+KqQSDY5kUfQEbzdXM1MVhJGcugKV7kRrNVzNxmk7NBg== - dependencies: - "@babel/helper-module-imports" "^7.14.5" - "@babel/helper-replace-supers" "^7.15.0" - "@babel/helper-simple-access" "^7.14.8" - "@babel/helper-split-export-declaration" "^7.14.5" - "@babel/helper-validator-identifier" "^7.14.9" - "@babel/template" "^7.14.5" - "@babel/traverse" "^7.15.0" - "@babel/types" "^7.15.0" - -"@babel/helper-optimise-call-expression@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.14.5.tgz#f27395a8619e0665b3f0364cddb41c25d71b499c" - integrity sha512-IqiLIrODUOdnPU9/F8ib1Fx2ohlgDhxnIDU7OEVi+kAbEZcyiF7BLU8W6PfvPi9LzztjS7kcbzbmL7oG8kD6VA== - dependencies: - "@babel/types" "^7.14.5" - -"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.12.13", "@babel/helper-plugin-utils@^7.14.5", "@babel/helper-plugin-utils@^7.8.0": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.14.5.tgz#5ac822ce97eec46741ab70a517971e443a70c5a9" - integrity sha512-/37qQCE3K0vvZKwoK4XU/irIJQdIfCJuhU5eKnNxpFDsOkgFaUAwbv+RYw6eYgsC0E4hS7r5KqGULUogqui0fQ== - -"@babel/helper-replace-supers@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-replace-supers/-/helper-replace-supers-7.14.5.tgz#0ecc0b03c41cd567b4024ea016134c28414abb94" - integrity sha512-3i1Qe9/8x/hCHINujn+iuHy+mMRLoc77b2nI9TB0zjH1hvn9qGlXjWlggdwUcju36PkPCy/lpM7LLUdcTyH4Ow== - dependencies: - "@babel/helper-member-expression-to-functions" "^7.14.5" - "@babel/helper-optimise-call-expression" "^7.14.5" - "@babel/traverse" "^7.14.5" - "@babel/types" "^7.14.5" - -"@babel/helper-replace-supers@^7.15.0": - version "7.15.0" - resolved "https://registry.yarnpkg.com/@babel/helper-replace-supers/-/helper-replace-supers-7.15.0.tgz#ace07708f5bf746bf2e6ba99572cce79b5d4e7f4" - integrity sha512-6O+eWrhx+HEra/uJnifCwhwMd6Bp5+ZfZeJwbqUTuqkhIT6YcRhiZCOOFChRypOIe0cV46kFrRBlm+t5vHCEaA== - dependencies: - "@babel/helper-member-expression-to-functions" "^7.15.0" - "@babel/helper-optimise-call-expression" "^7.14.5" - "@babel/traverse" "^7.15.0" - "@babel/types" "^7.15.0" - -"@babel/helper-simple-access@^7.14.8": - version "7.14.8" - resolved "https://registry.yarnpkg.com/@babel/helper-simple-access/-/helper-simple-access-7.14.8.tgz#82e1fec0644a7e775c74d305f212c39f8fe73924" - integrity sha512-TrFN4RHh9gnWEU+s7JloIho2T76GPwRHhdzOWLqTrMnlas8T9O7ec+oEDNsRXndOmru9ymH9DFrEOxpzPoSbdg== - dependencies: - "@babel/types" "^7.14.8" - -"@babel/helper-split-export-declaration@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.14.5.tgz#22b23a54ef51c2b7605d851930c1976dd0bc693a" - integrity sha512-hprxVPu6e5Kdp2puZUmvOGjaLv9TCe58E/Fl6hRq4YiVQxIcNvuq6uTM2r1mT/oPskuS9CgR+I94sqAYv0NGKA== - dependencies: - "@babel/types" "^7.14.5" - -"@babel/helper-validator-identifier@^7.14.5", "@babel/helper-validator-identifier@^7.14.8": - version "7.14.8" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.8.tgz#32be33a756f29e278a0d644fa08a2c9e0f88a34c" - integrity sha512-ZGy6/XQjllhYQrNw/3zfWRwZCTVSiBLZ9DHVZxn9n2gip/7ab8mv2TWlKPIBk26RwedCBoWdjLmn+t9na2Gcow== - -"@babel/helper-validator-identifier@^7.14.9": - version "7.14.9" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.9.tgz#6654d171b2024f6d8ee151bf2509699919131d48" - integrity sha512-pQYxPY0UP6IHISRitNe8bsijHex4TWZXi2HwKVsjPiltzlhse2znVcm9Ace510VT1kxIHjGJCZZQBX2gJDbo0g== - -"@babel/helper-validator-option@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.14.5.tgz#6e72a1fff18d5dfcb878e1e62f1a021c4b72d5a3" - integrity sha512-OX8D5eeX4XwcroVW45NMvoYaIuFI+GQpA2a8Gi+X/U/cDUIRsV37qQfF905F0htTRCREQIB4KqPeaveRJUl3Ow== - -"@babel/helpers@^7.14.8": - version "7.14.8" - resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.14.8.tgz#839f88f463025886cff7f85a35297007e2da1b77" - integrity sha512-ZRDmI56pnV+p1dH6d+UN6GINGz7Krps3+270qqI9UJ4wxYThfAIcI5i7j5vXC4FJ3Wap+S9qcebxeYiqn87DZw== - dependencies: - "@babel/template" "^7.14.5" - "@babel/traverse" "^7.14.8" - "@babel/types" "^7.14.8" - -"@babel/highlight@^7.10.4", "@babel/highlight@^7.14.5": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.14.5.tgz#6861a52f03966405001f6aa534a01a24d99e8cd9" - integrity sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg== - dependencies: - "@babel/helper-validator-identifier" "^7.14.5" - chalk "^2.0.0" - js-tokens "^4.0.0" - -"@babel/parser@^7.1.0", "@babel/parser@^7.14.5", "@babel/parser@^7.14.8": - version "7.14.8" - resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.14.8.tgz#66fd41666b2d7b840bd5ace7f7416d5ac60208d4" - integrity sha512-syoCQFOoo/fzkWDeM0dLEZi5xqurb5vuyzwIMNZRNun+N/9A4cUZeQaE7dTrB8jGaKuJRBtEOajtnmw0I5hvvA== - -"@babel/parser@^7.15.0", "@babel/parser@^7.7.2": - version "7.15.3" - resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.15.3.tgz#3416d9bea748052cfcb63dbcc27368105b1ed862" - integrity sha512-O0L6v/HvqbdJawj0iBEfVQMc3/6WP+AeOsovsIgBFyJaG+W2w7eqvZB7puddATmWuARlm1SX7DwxJ/JJUnDpEA== - -"@babel/plugin-syntax-async-generators@^7.8.4": - version "7.8.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz#a983fb1aeb2ec3f6ed042a210f640e90e786fe0d" - integrity sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-bigint@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz#4c9a6f669f5d0cdf1b90a1671e9a146be5300cea" - integrity sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-class-properties@^7.8.3": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz#b5c987274c4a3a82b89714796931a6b53544ae10" - integrity sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA== - dependencies: - "@babel/helper-plugin-utils" "^7.12.13" - -"@babel/plugin-syntax-import-meta@^7.8.3": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz#ee601348c370fa334d2207be158777496521fd51" - integrity sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g== - dependencies: - "@babel/helper-plugin-utils" "^7.10.4" - -"@babel/plugin-syntax-json-strings@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz#01ca21b668cd8218c9e640cb6dd88c5412b2c96a" - integrity sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-logical-assignment-operators@^7.8.3": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz#ca91ef46303530448b906652bac2e9fe9941f699" - integrity sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig== - dependencies: - "@babel/helper-plugin-utils" "^7.10.4" - -"@babel/plugin-syntax-nullish-coalescing-operator@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz#167ed70368886081f74b5c36c65a88c03b66d1a9" - integrity sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-numeric-separator@^7.8.3": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz#b9b070b3e33570cd9fd07ba7fa91c0dd37b9af97" - integrity sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug== - dependencies: - "@babel/helper-plugin-utils" "^7.10.4" - -"@babel/plugin-syntax-object-rest-spread@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz#60e225edcbd98a640332a2e72dd3e66f1af55871" - integrity sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-optional-catch-binding@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz#6111a265bcfb020eb9efd0fdfd7d26402b9ed6c1" - integrity sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-optional-chaining@^7.8.3": - version "7.8.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz#4f69c2ab95167e0180cd5336613f8c5788f7d48a" - integrity sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg== - dependencies: - "@babel/helper-plugin-utils" "^7.8.0" - -"@babel/plugin-syntax-top-level-await@^7.8.3": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz#c1cfdadc35a646240001f06138247b741c34d94c" - integrity sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw== - dependencies: - "@babel/helper-plugin-utils" "^7.14.5" - -"@babel/plugin-syntax-typescript@^7.7.2": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.14.5.tgz#b82c6ce471b165b5ce420cf92914d6fb46225716" - integrity sha512-u6OXzDaIXjEstBRRoBCQ/uKQKlbuaeE5in0RvWdA4pN6AhqxTIwUsnHPU1CFZA/amYObMsuWhYfRl3Ch90HD0Q== - dependencies: - "@babel/helper-plugin-utils" "^7.14.5" - -"@babel/template@^7.14.5", "@babel/template@^7.3.3": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.14.5.tgz#a9bc9d8b33354ff6e55a9c60d1109200a68974f4" - integrity sha512-6Z3Po85sfxRGachLULUhOmvAaOo7xCvqGQtxINai2mEGPFm6pQ4z5QInFnUrRpfoSV60BnjyF5F3c+15fxFV1g== - dependencies: - "@babel/code-frame" "^7.14.5" - "@babel/parser" "^7.14.5" - "@babel/types" "^7.14.5" - -"@babel/traverse@^7.1.0", "@babel/traverse@^7.14.5", "@babel/traverse@^7.14.8": - version "7.14.8" - resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.14.8.tgz#c0253f02677c5de1a8ff9df6b0aacbec7da1a8ce" - integrity sha512-kexHhzCljJcFNn1KYAQ6A5wxMRzq9ebYpEDV4+WdNyr3i7O44tanbDOR/xjiG2F3sllan+LgwK+7OMk0EmydHg== - dependencies: - "@babel/code-frame" "^7.14.5" - "@babel/generator" "^7.14.8" - "@babel/helper-function-name" "^7.14.5" - "@babel/helper-hoist-variables" "^7.14.5" - "@babel/helper-split-export-declaration" "^7.14.5" - "@babel/parser" "^7.14.8" - "@babel/types" "^7.14.8" - debug "^4.1.0" - globals "^11.1.0" - -"@babel/traverse@^7.15.0", "@babel/traverse@^7.7.2": - version "7.15.0" - resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.15.0.tgz#4cca838fd1b2a03283c1f38e141f639d60b3fc98" - integrity sha512-392d8BN0C9eVxVWd8H6x9WfipgVH5IaIoLp23334Sc1vbKKWINnvwRpb4us0xtPaCumlwbTtIYNA0Dv/32sVFw== - dependencies: - "@babel/code-frame" "^7.14.5" - "@babel/generator" "^7.15.0" - "@babel/helper-function-name" "^7.14.5" - "@babel/helper-hoist-variables" "^7.14.5" - "@babel/helper-split-export-declaration" "^7.14.5" - "@babel/parser" "^7.15.0" - "@babel/types" "^7.15.0" - debug "^4.1.0" - globals "^11.1.0" - -"@babel/types@^7.0.0", "@babel/types@^7.14.5", "@babel/types@^7.14.8", "@babel/types@^7.3.0", "@babel/types@^7.3.3": - version "7.14.8" - resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.14.8.tgz#38109de8fcadc06415fbd9b74df0065d4d41c728" - integrity sha512-iob4soQa7dZw8nodR/KlOQkPh9S4I8RwCxwRIFuiMRYjOzH/KJzdUfDgz6cGi5dDaclXF4P2PAhCdrBJNIg68Q== - dependencies: - "@babel/helper-validator-identifier" "^7.14.8" - to-fast-properties "^2.0.0" - -"@babel/types@^7.15.0": - version "7.15.0" - resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.15.0.tgz#61af11f2286c4e9c69ca8deb5f4375a73c72dcbd" - integrity sha512-OBvfqnllOIdX4ojTHpwZbpvz4j3EWyjkZEdmjH0/cgsd6QOdSgU8rLSk6ard/pcW7rlmjdVSX/AWOaORR1uNOQ== - dependencies: - "@babel/helper-validator-identifier" "^7.14.9" - to-fast-properties "^2.0.0" - -"@bcoe/v8-coverage@^0.2.3": - version "0.2.3" - resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" - integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== - -"@chemzqm/neovim@^5.4.0": - version "5.4.0" - resolved "https://registry.yarnpkg.com/@chemzqm/neovim/-/neovim-5.4.0.tgz#ca7261d963507b4843db0efaa76df238203d2055" - integrity sha512-BjOAR5sliE2kp3EGZsyUmrYwTMRrxvXe6WBQTxL0m5uRIvfxShRaWyKOGbqoe0+sHCfgT67QsMevUAjB1Ovskw== - dependencies: - msgpack-lite "^0.1.26" - -"@eslint/eslintrc@^0.4.3": - version "0.4.3" - resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.3.tgz#9e42981ef035beb3dd49add17acb96e8ff6f394c" - integrity sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw== - dependencies: - ajv "^6.12.4" - debug "^4.1.1" - espree "^7.3.0" - globals "^13.9.0" - ignore "^4.0.6" - import-fresh "^3.2.1" - js-yaml "^3.13.1" - minimatch "^3.0.4" - strip-json-comments "^3.1.1" - -"@humanwhocodes/config-array@^0.5.0": - version "0.5.0" - resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.5.0.tgz#1407967d4c6eecd7388f83acf1eaf4d0c6e58ef9" - integrity sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg== - dependencies: - "@humanwhocodes/object-schema" "^1.2.0" - debug "^4.1.1" - minimatch "^3.0.4" - -"@humanwhocodes/object-schema@^1.2.0": - version "1.2.0" - resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-1.2.0.tgz#87de7af9c231826fdd68ac7258f77c429e0e5fcf" - integrity sha512-wdppn25U8z/2yiaT6YGquE6X8sSv7hNMWSXYSSU1jGv/yd6XqjXgTDJ8KP4NgjTXfJ3GbRjeeb8RTV7a/VpM+w== - -"@istanbuljs/load-nyc-config@^1.0.0": - version "1.1.0" - resolved "https://registry.yarnpkg.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz#fd3db1d59ecf7cf121e80650bb86712f9b55eced" - integrity sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ== - dependencies: - camelcase "^5.3.1" - find-up "^4.1.0" - get-package-type "^0.1.0" - js-yaml "^3.13.1" - resolve-from "^5.0.0" - -"@istanbuljs/schema@^0.1.2": - version "0.1.3" - resolved "https://registry.yarnpkg.com/@istanbuljs/schema/-/schema-0.1.3.tgz#e45e384e4b8ec16bce2fd903af78450f6bf7ec98" - integrity sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA== - -"@jest/console@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/console/-/console-27.0.6.tgz#3eb72ea80897495c3d73dd97aab7f26770e2260f" - integrity sha512-fMlIBocSHPZ3JxgWiDNW/KPj6s+YRd0hicb33IrmelCcjXo/pXPwvuiKFmZz+XuqI/1u7nbUK10zSsWL/1aegg== - dependencies: - "@jest/types" "^27.0.6" - "@types/node" "*" - chalk "^4.0.0" - jest-message-util "^27.0.6" - jest-util "^27.0.6" - slash "^3.0.0" - -"@jest/core@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/core/-/core-27.0.6.tgz#c5f642727a0b3bf0f37c4b46c675372d0978d4a1" - integrity sha512-SsYBm3yhqOn5ZLJCtccaBcvD/ccTLCeuDv8U41WJH/V1MW5eKUkeMHT9U+Pw/v1m1AIWlnIW/eM2XzQr0rEmow== - dependencies: - "@jest/console" "^27.0.6" - "@jest/reporters" "^27.0.6" - "@jest/test-result" "^27.0.6" - "@jest/transform" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/node" "*" - ansi-escapes "^4.2.1" - chalk "^4.0.0" - emittery "^0.8.1" - exit "^0.1.2" - graceful-fs "^4.2.4" - jest-changed-files "^27.0.6" - jest-config "^27.0.6" - jest-haste-map "^27.0.6" - jest-message-util "^27.0.6" - jest-regex-util "^27.0.6" - jest-resolve "^27.0.6" - jest-resolve-dependencies "^27.0.6" - jest-runner "^27.0.6" - jest-runtime "^27.0.6" - jest-snapshot "^27.0.6" - jest-util "^27.0.6" - jest-validate "^27.0.6" - jest-watcher "^27.0.6" - micromatch "^4.0.4" - p-each-series "^2.1.0" - rimraf "^3.0.0" - slash "^3.0.0" - strip-ansi "^6.0.0" - -"@jest/environment@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/environment/-/environment-27.0.6.tgz#ee293fe996db01d7d663b8108fa0e1ff436219d2" - integrity sha512-4XywtdhwZwCpPJ/qfAkqExRsERW+UaoSRStSHCCiQTUpoYdLukj+YJbQSFrZjhlUDRZeNiU9SFH0u7iNimdiIg== - dependencies: - "@jest/fake-timers" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/node" "*" - jest-mock "^27.0.6" - -"@jest/fake-timers@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/fake-timers/-/fake-timers-27.0.6.tgz#cbad52f3fe6abe30e7acb8cd5fa3466b9588e3df" - integrity sha512-sqd+xTWtZ94l3yWDKnRTdvTeZ+A/V7SSKrxsrOKSqdyddb9CeNRF8fbhAU0D7ZJBpTTW2nbp6MftmKJDZfW2LQ== - dependencies: - "@jest/types" "^27.0.6" - "@sinonjs/fake-timers" "^7.0.2" - "@types/node" "*" - jest-message-util "^27.0.6" - jest-mock "^27.0.6" - jest-util "^27.0.6" - -"@jest/globals@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/globals/-/globals-27.0.6.tgz#48e3903f99a4650673d8657334d13c9caf0e8f82" - integrity sha512-DdTGCP606rh9bjkdQ7VvChV18iS7q0IMJVP1piwTWyWskol4iqcVwthZmoJEf7obE1nc34OpIyoVGPeqLC+ryw== - dependencies: - "@jest/environment" "^27.0.6" - "@jest/types" "^27.0.6" - expect "^27.0.6" - -"@jest/reporters@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/reporters/-/reporters-27.0.6.tgz#91e7f2d98c002ad5df94d5b5167c1eb0b9fd5b00" - integrity sha512-TIkBt09Cb2gptji3yJXb3EE+eVltW6BjO7frO7NEfjI9vSIYoISi5R3aI3KpEDXlB1xwB+97NXIqz84qYeYsfA== - dependencies: - "@bcoe/v8-coverage" "^0.2.3" - "@jest/console" "^27.0.6" - "@jest/test-result" "^27.0.6" - "@jest/transform" "^27.0.6" - "@jest/types" "^27.0.6" - chalk "^4.0.0" - collect-v8-coverage "^1.0.0" - exit "^0.1.2" - glob "^7.1.2" - graceful-fs "^4.2.4" - istanbul-lib-coverage "^3.0.0" - istanbul-lib-instrument "^4.0.3" - istanbul-lib-report "^3.0.0" - istanbul-lib-source-maps "^4.0.0" - istanbul-reports "^3.0.2" - jest-haste-map "^27.0.6" - jest-resolve "^27.0.6" - jest-util "^27.0.6" - jest-worker "^27.0.6" - slash "^3.0.0" - source-map "^0.6.0" - string-length "^4.0.1" - terminal-link "^2.0.0" - v8-to-istanbul "^8.0.0" - -"@jest/source-map@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-27.0.6.tgz#be9e9b93565d49b0548b86e232092491fb60551f" - integrity sha512-Fek4mi5KQrqmlY07T23JRi0e7Z9bXTOOD86V/uS0EIW4PClvPDqZOyFlLpNJheS6QI0FNX1CgmPjtJ4EA/2M+g== - dependencies: - callsites "^3.0.0" - graceful-fs "^4.2.4" - source-map "^0.6.0" - -"@jest/test-result@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/test-result/-/test-result-27.0.6.tgz#3fa42015a14e4fdede6acd042ce98c7f36627051" - integrity sha512-ja/pBOMTufjX4JLEauLxE3LQBPaI2YjGFtXexRAjt1I/MbfNlMx0sytSX3tn5hSLzQsR3Qy2rd0hc1BWojtj9w== - dependencies: - "@jest/console" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/istanbul-lib-coverage" "^2.0.0" - collect-v8-coverage "^1.0.0" - -"@jest/test-sequencer@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/test-sequencer/-/test-sequencer-27.0.6.tgz#80a913ed7a1130545b1cd777ff2735dd3af5d34b" - integrity sha512-bISzNIApazYOlTHDum9PwW22NOyDa6VI31n6JucpjTVM0jD6JDgqEZ9+yn575nDdPF0+4csYDxNNW13NvFQGZA== - dependencies: - "@jest/test-result" "^27.0.6" - graceful-fs "^4.2.4" - jest-haste-map "^27.0.6" - jest-runtime "^27.0.6" - -"@jest/transform@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/transform/-/transform-27.0.6.tgz#189ad7107413208f7600f4719f81dd2f7278cc95" - integrity sha512-rj5Dw+mtIcntAUnMlW/Vju5mr73u8yg+irnHwzgtgoeI6cCPOvUwQ0D1uQtc/APmWgvRweEb1g05pkUpxH3iCA== - dependencies: - "@babel/core" "^7.1.0" - "@jest/types" "^27.0.6" - babel-plugin-istanbul "^6.0.0" - chalk "^4.0.0" - convert-source-map "^1.4.0" - fast-json-stable-stringify "^2.0.0" - graceful-fs "^4.2.4" - jest-haste-map "^27.0.6" - jest-regex-util "^27.0.6" - jest-util "^27.0.6" - micromatch "^4.0.4" - pirates "^4.0.1" - slash "^3.0.0" - source-map "^0.6.1" - write-file-atomic "^3.0.0" - -"@jest/types@^27.0.6": - version "27.0.6" - resolved "https://registry.yarnpkg.com/@jest/types/-/types-27.0.6.tgz#9a992bc517e0c49f035938b8549719c2de40706b" - integrity sha512-aSquT1qa9Pik26JK5/3rvnYb4bGtm1VFNesHKmNTwmPIgOrixvhL2ghIvFRNEpzy3gU+rUgjIF/KodbkFAl++g== - dependencies: - "@types/istanbul-lib-coverage" "^2.0.0" - "@types/istanbul-reports" "^3.0.0" - "@types/node" "*" - "@types/yargs" "^16.0.0" - chalk "^4.0.0" - -"@nodelib/fs.scandir@2.1.5": - version "2.1.5" - resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz#7619c2eb21b25483f6d167548b4cfd5a7488c3d5" - integrity sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g== - dependencies: - "@nodelib/fs.stat" "2.0.5" - run-parallel "^1.1.9" - -"@nodelib/fs.stat@2.0.5", "@nodelib/fs.stat@^2.0.2": - version "2.0.5" - resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz#5bd262af94e9d25bd1e71b05deed44876a222e8b" - integrity sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A== - -"@nodelib/fs.walk@^1.2.3": - version "1.2.8" - resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz#e95737e8bb6746ddedf69c556953494f196fe69a" - integrity sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg== - dependencies: - "@nodelib/fs.scandir" "2.1.5" - fastq "^1.6.0" - -"@sinonjs/commons@^1.7.0": - version "1.8.3" - resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.8.3.tgz#3802ddd21a50a949b6721ddd72da36e67e7f1b2d" - integrity sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ== - dependencies: - type-detect "4.0.8" - -"@sinonjs/fake-timers@^7.0.2": - version "7.1.2" - resolved "https://registry.yarnpkg.com/@sinonjs/fake-timers/-/fake-timers-7.1.2.tgz#2524eae70c4910edccf99b2f4e6efc5894aff7b5" - integrity sha512-iQADsW4LBMISqZ6Ci1dupJL9pprqwcVFTcOsEmQOEhW+KLCVn/Y4Jrvg2k19fIHCp+iFprriYPTdRcQR8NbUPg== - dependencies: - "@sinonjs/commons" "^1.7.0" - -"@tootallnate/once@1": - version "1.1.2" - resolved "https://registry.yarnpkg.com/@tootallnate/once/-/once-1.1.2.tgz#ccb91445360179a04e7fe6aff78c00ffc1eeaf82" - integrity sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw== - -"@types/babel__core@^7.0.0", "@types/babel__core@^7.1.14": - version "7.1.15" - resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.15.tgz#2ccfb1ad55a02c83f8e0ad327cbc332f55eb1024" - integrity sha512-bxlMKPDbY8x5h6HBwVzEOk2C8fb6SLfYQ5Jw3uBYuYF1lfWk/kbLd81la82vrIkBb0l+JdmrZaDikPrNxpS/Ew== - dependencies: - "@babel/parser" "^7.1.0" - "@babel/types" "^7.0.0" - "@types/babel__generator" "*" - "@types/babel__template" "*" - "@types/babel__traverse" "*" - -"@types/babel__generator@*": - version "7.6.3" - resolved "https://registry.yarnpkg.com/@types/babel__generator/-/babel__generator-7.6.3.tgz#f456b4b2ce79137f768aa130d2423d2f0ccfaba5" - integrity sha512-/GWCmzJWqV7diQW54smJZzWbSFf4QYtF71WCKhcx6Ru/tFyQIY2eiiITcCAeuPbNSvT9YCGkVMqqvSk2Z0mXiA== - dependencies: - "@babel/types" "^7.0.0" - -"@types/babel__template@*": - version "7.4.1" - resolved "https://registry.yarnpkg.com/@types/babel__template/-/babel__template-7.4.1.tgz#3d1a48fd9d6c0edfd56f2ff578daed48f36c8969" - integrity sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g== - dependencies: - "@babel/parser" "^7.1.0" - "@babel/types" "^7.0.0" - -"@types/babel__traverse@*", "@types/babel__traverse@^7.0.4", "@types/babel__traverse@^7.0.6": - version "7.14.2" - resolved "https://registry.yarnpkg.com/@types/babel__traverse/-/babel__traverse-7.14.2.tgz#ffcd470bbb3f8bf30481678fb5502278ca833a43" - integrity sha512-K2waXdXBi2302XUdcHcR1jCeU0LL4TD9HRs/gk0N2Xvrht+G/BfJa4QObBQZfhMdxiCpV3COl5Nfq4uKTeTnJA== - dependencies: - "@babel/types" "^7.3.0" - -"@types/cli-table@^0.3.0": - version "0.3.0" - resolved "https://registry.yarnpkg.com/@types/cli-table/-/cli-table-0.3.0.tgz#f1857156bf5fd115c6a2db260ba0be1f8fc5671c" - integrity sha512-QnZUISJJXyhyD6L1e5QwXDV/A5i2W1/gl6D6YMc8u0ncPepbv/B4w3S+izVvtAg60m6h+JP09+Y/0zF2mojlFQ== - -"@types/debounce@^3.0.0": - version "3.0.0" - resolved "https://registry.yarnpkg.com/@types/debounce/-/debounce-3.0.0.tgz#ea4290f6e2d7ab99464c93b4a69b843d0993b181" - integrity sha512-SbehVj+zL0QFTufW3HP/Xvwr/kFWw1sFMLCvmyJdp5Xegbo81sqA2tByWlyeryvSwWBrY4drpLOtGPh0fkxjCQ== - -"@types/fb-watchman@^2.0.0": - version "2.0.1" - resolved "https://registry.yarnpkg.com/@types/fb-watchman/-/fb-watchman-2.0.1.tgz#4f44c7b7ac98463488765d41d269272dd34cb815" - integrity sha512-iJ7/e6drSmuCzAp96/dpksm8YjxbhhyXWV6m1HPbRHvZwUOUZ5vZvZIAUJxKDtI0UpdNfDvLPiai0MTJmmS+HA== - -"@types/fs-extra@^9.0.6": - version "9.0.12" - resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-9.0.12.tgz#9b8f27973df8a7a3920e8461517ebf8a7d4fdfaf" - integrity sha512-I+bsBr67CurCGnSenZZ7v94gd3tc3+Aj2taxMT4yu4ABLuOgOjeFxX3dokG24ztSRg5tnT00sL8BszO7gSMoIw== - dependencies: - "@types/node" "*" - -"@types/graceful-fs@^4.1.2": - version "4.1.5" - resolved "https://registry.yarnpkg.com/@types/graceful-fs/-/graceful-fs-4.1.5.tgz#21ffba0d98da4350db64891f92a9e5db3cdb4e15" - integrity sha512-anKkLmZZ+xm4p8JWBf4hElkM4XR+EZeA2M9BAkkTldmcyDY4mbdIJnRghDJH3Ov5ooY7/UAoENtmdMSkaAd7Cw== - dependencies: - "@types/node" "*" - -"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0", "@types/istanbul-lib-coverage@^2.0.1": - version "2.0.3" - resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz#4ba8ddb720221f432e443bd5f9117fd22cfd4762" - integrity sha512-sz7iLqvVUg1gIedBOvlkxPlc8/uVzyS5OwGz1cKjXzkl3FpL3al0crU8YGU1WoHkxn0Wxbw5tyi6hvzJKNzFsw== - -"@types/istanbul-lib-report@*": - version "3.0.0" - resolved "https://registry.yarnpkg.com/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz#c14c24f18ea8190c118ee7562b7ff99a36552686" - integrity sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg== - dependencies: - "@types/istanbul-lib-coverage" "*" - -"@types/istanbul-reports@^3.0.0": - version "3.0.1" - resolved "https://registry.yarnpkg.com/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz#9153fe98bba2bd565a63add9436d6f0d7f8468ff" - integrity sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw== - dependencies: - "@types/istanbul-lib-report" "*" - -"@types/jest@^27.0.1": - version "27.0.1" - resolved "https://registry.yarnpkg.com/@types/jest/-/jest-27.0.1.tgz#fafcc997da0135865311bb1215ba16dba6bdf4ca" - integrity sha512-HTLpVXHrY69556ozYkcq47TtQJXpcWAWfkoqz+ZGz2JnmZhzlRjprCIyFnetSy8gpDWwTTGBcRVv1J1I1vBrHw== - dependencies: - jest-diff "^27.0.0" - pretty-format "^27.0.0" - -"@types/json-schema@^7.0.7": - version "7.0.8" - resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.8.tgz#edf1bf1dbf4e04413ca8e5b17b3b7d7d54b59818" - integrity sha512-YSBPTLTVm2e2OoQIDYx8HaeWJ5tTToLH67kXR7zYNGupXMEHa2++G8k+DczX2cFVgalypqtyZIcU19AFcmOpmg== - -"@types/marked@^2.0.4": - version "2.0.4" - resolved "https://registry.yarnpkg.com/@types/marked/-/marked-2.0.4.tgz#34a0ea548afe6e0c01095229d47b48b2af650613" - integrity sha512-L9VRSe0Id8xbPL99mUo/4aKgD7ZoRwFZqUQScNKHi2pFjF9ZYSMNShUHD6VlMT6J/prQq0T1mxuU25m3R7dFzg== - -"@types/minimatch@^3.0.3": - version "3.0.5" - resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.5.tgz#1001cc5e6a3704b83c236027e77f2f58ea010f40" - integrity sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ== - -"@types/minipass@*": - version "2.2.1" - resolved "https://registry.yarnpkg.com/@types/minipass/-/minipass-2.2.1.tgz#a52138867c493ff14f07616efcbe2af7662b76fb" - integrity sha512-0bI74UwEJ+JjGqzkyoiCxLVGK5C3Vy5MYdDB6VCtUAulcrulHvqhIrQP9lh/gvMgaNzvvJljMW97rRHVvbTe8Q== - dependencies: - "@types/node" "*" - -"@types/mkdirp@^1.0.1": - version "1.0.2" - resolved "https://registry.yarnpkg.com/@types/mkdirp/-/mkdirp-1.0.2.tgz#8d0bad7aa793abe551860be1f7ae7f3198c16666" - integrity sha512-o0K1tSO0Dx5X6xlU5F1D6625FawhC3dU3iqr25lluNv/+/QIVH8RLNEiVokgIZo+mz+87w/3Mkg/VvQS+J51fQ== - dependencies: - "@types/node" "*" - -"@types/node@*": - version "16.4.3" - resolved "https://registry.yarnpkg.com/@types/node/-/node-16.4.3.tgz#c01c1a215721f6dec71b47d88b4687463601ba48" - integrity sha512-GKM4FLMkWDc0sfx7tXqPWkM6NBow1kge0fgQh0bOnlqo4iT1kvTvMEKE0c1RtUGnbLlGRXiAA8SumE//90uKAg== - -"@types/node@12.12.12": - version "12.12.12" - resolved "https://registry.yarnpkg.com/@types/node/-/node-12.12.12.tgz#529bc3e73dbb35dd9e90b0a1c83606a9d3264bdb" - integrity sha512-MGuvYJrPU0HUwqF7LqvIj50RZUX23Z+m583KBygKYUZLlZ88n6w28XRNJRJgsHukLEnLz6w6SvxZoLgbr5wLqQ== - -"@types/prettier@^2.1.5": - version "2.3.2" - resolved "https://registry.yarnpkg.com/@types/prettier/-/prettier-2.3.2.tgz#fc8c2825e4ed2142473b4a81064e6e081463d1b3" - integrity sha512-eI5Yrz3Qv4KPUa/nSIAi0h+qX0XyewOliug5F2QAtuRg6Kjg6jfmxe1GIwoIRhZspD1A0RP8ANrPwvEXXtRFog== - -"@types/semver@^7.3.4": - version "7.3.8" - resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.3.8.tgz#508a27995498d7586dcecd77c25e289bfaf90c59" - integrity sha512-D/2EJvAlCEtYFEYmmlGwbGXuK886HzyCc3nZX/tkFTQdEU8jZDAgiv08P162yB17y4ZXZoq7yFAnW4GDBb9Now== - -"@types/stack-utils@^2.0.0": - version "2.0.1" - resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-2.0.1.tgz#20f18294f797f2209b5f65c8e3b5c8e8261d127c" - integrity sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw== - -"@types/tar@^4.0.5": - version "4.0.5" - resolved "https://registry.yarnpkg.com/@types/tar/-/tar-4.0.5.tgz#5f953f183e36a15c6ce3f336568f6051b7b183f3" - integrity sha512-cgwPhNEabHaZcYIy5xeMtux2EmYBitfqEceBUi2t5+ETy4dW6kswt6WX4+HqLeiiKOo42EXbGiDmVJ2x+vi37Q== - dependencies: - "@types/minipass" "*" - "@types/node" "*" - -"@types/uuid@^8.3.0": - version "8.3.1" - resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-8.3.1.tgz#1a32969cf8f0364b3d8c8af9cc3555b7805df14f" - integrity sha512-Y2mHTRAbqfFkpjldbkHGY8JIzRN6XqYRliG8/24FcHm2D2PwW24fl5xMRTVGdrb7iMrwCaIEbLWerGIkXuFWVg== - -"@types/which@^1.3.2": - version "1.3.2" - resolved "https://registry.yarnpkg.com/@types/which/-/which-1.3.2.tgz#9c246fc0c93ded311c8512df2891fb41f6227fdf" - integrity sha512-8oDqyLC7eD4HM307boe2QWKyuzdzWBj56xI/imSl2cpL+U3tCMaTAkMJ4ee5JBZ/FsOJlvRGeIShiZDAl1qERA== - -"@types/yargs-parser@*": - version "20.2.1" - resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-20.2.1.tgz#3b9ce2489919d9e4fea439b76916abc34b2df129" - integrity sha512-7tFImggNeNBVMsn0vLrpn1H1uPrUBdnARPTpZoitY37ZrdJREzf7I16tMrlK3hen349gr1NYh8CmZQa7CTG6Aw== - -"@types/yargs@^16.0.0": - version "16.0.4" - resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-16.0.4.tgz#26aad98dd2c2a38e421086ea9ad42b9e51642977" - integrity sha512-T8Yc9wt/5LbJyCaLiHPReJa0kApcIgJ7Bn735GjItUfh08Z1pJvu8QZqb9s+mMvKV6WUQRV7K2R46YbjMXTTJw== - dependencies: - "@types/yargs-parser" "*" - -"@typescript-eslint/eslint-plugin@^4.11.1": - version "4.28.5" - resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.28.5.tgz#8197f1473e7da8218c6a37ff308d695707835684" - integrity sha512-m31cPEnbuCqXtEZQJOXAHsHvtoDi9OVaeL5wZnO2KZTnkvELk+u6J6jHg+NzvWQxk+87Zjbc4lJS4NHmgImz6Q== - dependencies: - "@typescript-eslint/experimental-utils" "4.28.5" - "@typescript-eslint/scope-manager" "4.28.5" - debug "^4.3.1" - functional-red-black-tree "^1.0.1" - regexpp "^3.1.0" - semver "^7.3.5" - tsutils "^3.21.0" - -"@typescript-eslint/experimental-utils@4.28.5", "@typescript-eslint/experimental-utils@^4.0.1": - version "4.28.5" - resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-4.28.5.tgz#66c28bef115b417cf9d80812a713e0e46bb42a64" - integrity sha512-bGPLCOJAa+j49hsynTaAtQIWg6uZd8VLiPcyDe4QPULsvQwLHGLSGKKcBN8/lBxIX14F74UEMK2zNDI8r0okwA== - dependencies: - "@types/json-schema" "^7.0.7" - "@typescript-eslint/scope-manager" "4.28.5" - "@typescript-eslint/types" "4.28.5" - "@typescript-eslint/typescript-estree" "4.28.5" - eslint-scope "^5.1.1" - eslint-utils "^3.0.0" - -"@typescript-eslint/parser@^4.11.1": - version "4.28.5" - resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.28.5.tgz#9c971668f86d1b5c552266c47788a87488a47d1c" - integrity sha512-NPCOGhTnkXGMqTznqgVbA5LqVsnw+i3+XA1UKLnAb+MG1Y1rP4ZSK9GX0kJBmAZTMIktf+dTwXToT6kFwyimbw== - dependencies: - "@typescript-eslint/scope-manager" "4.28.5" - "@typescript-eslint/types" "4.28.5" - "@typescript-eslint/typescript-estree" "4.28.5" - debug "^4.3.1" - -"@typescript-eslint/scope-manager@4.28.5": - version "4.28.5" - resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.28.5.tgz#3a1b70c50c1535ac33322786ea99ebe403d3b923" - integrity sha512-PHLq6n9nTMrLYcVcIZ7v0VY1X7dK309NM8ya9oL/yG8syFINIMHxyr2GzGoBYUdv3NUfCOqtuqps0ZmcgnZTfQ== - dependencies: - "@typescript-eslint/types" "4.28.5" - "@typescript-eslint/visitor-keys" "4.28.5" - -"@typescript-eslint/types@4.28.5": - version "4.28.5" - resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.28.5.tgz#d33edf8e429f0c0930a7c3d44e9b010354c422e9" - integrity sha512-MruOu4ZaDOLOhw4f/6iudyks/obuvvZUAHBDSW80Trnc5+ovmViLT2ZMDXhUV66ozcl6z0LJfKs1Usldgi/WCA== - -"@typescript-eslint/typescript-estree@4.28.5": - version "4.28.5" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.28.5.tgz#4906d343de693cf3d8dcc301383ed638e0441cd1" - integrity sha512-FzJUKsBX8poCCdve7iV7ShirP8V+ys2t1fvamVeD1rWpiAnIm550a+BX/fmTHrjEpQJ7ZAn+Z7ZZwJjytk9rZw== - dependencies: - "@typescript-eslint/types" "4.28.5" - "@typescript-eslint/visitor-keys" "4.28.5" - debug "^4.3.1" - globby "^11.0.3" - is-glob "^4.0.1" - semver "^7.3.5" - tsutils "^3.21.0" - -"@typescript-eslint/visitor-keys@4.28.5": - version "4.28.5" - resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.28.5.tgz#ffee2c602762ed6893405ee7c1144d9cc0a29675" - integrity sha512-dva/7Rr+EkxNWdJWau26xU/0slnFlkh88v3TsyTgRS/IIYFi5iIfpCFM4ikw0vQTFUR9FYSSyqgK4w64gsgxhg== - dependencies: - "@typescript-eslint/types" "4.28.5" - eslint-visitor-keys "^2.0.0" - -abab@^2.0.3, abab@^2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/abab/-/abab-2.0.5.tgz#c0b678fb32d60fc1219c784d6a826fe385aeb79a" - integrity sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q== - -acorn-globals@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/acorn-globals/-/acorn-globals-6.0.0.tgz#46cdd39f0f8ff08a876619b55f5ac8a6dc770b45" - integrity sha512-ZQl7LOWaF5ePqqcX4hLuv/bLXYQNfNWw2c0/yX/TsPRKamzHcTGQnlCjHT3TsmkOUVEPS3crCxiPfdzE/Trlhg== - dependencies: - acorn "^7.1.1" - acorn-walk "^7.1.1" - -acorn-jsx@^5.3.1: - version "5.3.2" - resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937" - integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ== - -acorn-walk@^7.1.1: - version "7.2.0" - resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-7.2.0.tgz#0de889a601203909b0fbe07b8938dc21d2e967bc" - integrity sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA== - -acorn@^7.1.1, acorn@^7.4.0: - version "7.4.1" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.4.1.tgz#feaed255973d2e77555b83dbc08851a6c63520fa" - integrity sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A== - -acorn@^8.2.4: - version "8.4.1" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.4.1.tgz#56c36251fc7cabc7096adc18f05afe814321a28c" - integrity sha512-asabaBSkEKosYKMITunzX177CXxQ4Q8BSSzMTKD+FefUhipQC70gfW5SiUDhYQ3vk8G+81HqQk7Fv9OXwwn9KA== - -agent-base@6: - version "6.0.2" - resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-6.0.2.tgz#49fff58577cfee3f37176feab4c22e00f86d7f77" - integrity sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ== - dependencies: - debug "4" - -ajv@^6.10.0, ajv@^6.12.4: - version "6.12.6" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" - integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== - dependencies: - fast-deep-equal "^3.1.1" - fast-json-stable-stringify "^2.0.0" - json-schema-traverse "^0.4.1" - uri-js "^4.2.2" - -ajv@^8.0.1: - version "8.6.2" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.6.2.tgz#2fb45e0e5fcbc0813326c1c3da535d1881bb0571" - integrity sha512-9807RlWAgT564wT+DjeyU5OFMPjmzxVobvDFmNAhY+5zD6A2ly3jDp6sgnfyDtlIQ+7H97oc/DGCzzfu9rjw9w== - dependencies: - fast-deep-equal "^3.1.1" - json-schema-traverse "^1.0.0" - require-from-string "^2.0.2" - uri-js "^4.2.2" - -ansi-colors@^4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" - integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== - -ansi-escapes@^4.2.1: - version "4.3.2" - resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.2.tgz#6b2291d1db7d98b6521d5f1efa42d0f3a9feb65e" - integrity sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ== - dependencies: - type-fest "^0.21.3" - -ansi-regex@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.0.tgz#388539f55179bf39339c81af30a654d69f87cb75" - integrity sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg== - -ansi-styles@^3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" - integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== - dependencies: - color-convert "^1.9.0" - -ansi-styles@^4.0.0, ansi-styles@^4.1.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" - integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== - dependencies: - color-convert "^2.0.1" - -ansi-styles@^5.0.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b" - integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA== - -anymatch@^3.0.3: - version "3.1.2" - resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" - integrity sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg== - dependencies: - normalize-path "^3.0.0" - picomatch "^2.0.4" - -argparse@^1.0.7: - version "1.0.10" - resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" - integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== - dependencies: - sprintf-js "~1.0.2" - -array-union@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" - integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== - -astral-regex@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-2.0.0.tgz#483143c567aeed4785759c0865786dc77d7d2e31" - integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ== - -asynckit@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" - integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= - -at-least-node@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/at-least-node/-/at-least-node-1.0.0.tgz#602cd4b46e844ad4effc92a8011a3c46e0238dc2" - integrity sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg== - -babel-jest@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-27.0.6.tgz#e99c6e0577da2655118e3608b68761a5a69bd0d8" - integrity sha512-iTJyYLNc4wRofASmofpOc5NK9QunwMk+TLFgGXsTFS8uEqmd8wdI7sga0FPe2oVH3b5Agt/EAK1QjPEuKL8VfA== - dependencies: - "@jest/transform" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/babel__core" "^7.1.14" - babel-plugin-istanbul "^6.0.0" - babel-preset-jest "^27.0.6" - chalk "^4.0.0" - graceful-fs "^4.2.4" - slash "^3.0.0" - -babel-plugin-istanbul@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/babel-plugin-istanbul/-/babel-plugin-istanbul-6.0.0.tgz#e159ccdc9af95e0b570c75b4573b7c34d671d765" - integrity sha512-AF55rZXpe7trmEylbaE1Gv54wn6rwU03aptvRoVIGP8YykoSxqdVLV1TfwflBCE/QtHmqtP8SWlTENqbK8GCSQ== - dependencies: - "@babel/helper-plugin-utils" "^7.0.0" - "@istanbuljs/load-nyc-config" "^1.0.0" - "@istanbuljs/schema" "^0.1.2" - istanbul-lib-instrument "^4.0.0" - test-exclude "^6.0.0" - -babel-plugin-jest-hoist@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-27.0.6.tgz#f7c6b3d764af21cb4a2a1ab6870117dbde15b456" - integrity sha512-CewFeM9Vv2gM7Yr9n5eyyLVPRSiBnk6lKZRjgwYnGKSl9M14TMn2vkN02wTF04OGuSDLEzlWiMzvjXuW9mB6Gw== - dependencies: - "@babel/template" "^7.3.3" - "@babel/types" "^7.3.3" - "@types/babel__core" "^7.0.0" - "@types/babel__traverse" "^7.0.6" - -babel-preset-current-node-syntax@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz#b4399239b89b2a011f9ddbe3e4f401fc40cff73b" - integrity sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ== - dependencies: - "@babel/plugin-syntax-async-generators" "^7.8.4" - "@babel/plugin-syntax-bigint" "^7.8.3" - "@babel/plugin-syntax-class-properties" "^7.8.3" - "@babel/plugin-syntax-import-meta" "^7.8.3" - "@babel/plugin-syntax-json-strings" "^7.8.3" - "@babel/plugin-syntax-logical-assignment-operators" "^7.8.3" - "@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.3" - "@babel/plugin-syntax-numeric-separator" "^7.8.3" - "@babel/plugin-syntax-object-rest-spread" "^7.8.3" - "@babel/plugin-syntax-optional-catch-binding" "^7.8.3" - "@babel/plugin-syntax-optional-chaining" "^7.8.3" - "@babel/plugin-syntax-top-level-await" "^7.8.3" - -babel-preset-jest@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-27.0.6.tgz#909ef08e9f24a4679768be2f60a3df0856843f9d" - integrity sha512-WObA0/Biw2LrVVwZkF/2GqbOdzhKD6Fkdwhoy9ASIrOWr/zodcSpQh72JOkEn6NWyjmnPDjNSqaGN4KnpKzhXw== - dependencies: - babel-plugin-jest-hoist "^27.0.6" - babel-preset-current-node-syntax "^1.0.0" - -balanced-match@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" - integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== - -binary@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/binary/-/binary-0.3.0.tgz#9f60553bc5ce8c3386f3b553cff47462adecaa79" - integrity sha1-n2BVO8XOjDOG87VTz/R0Yq3sqnk= - dependencies: - buffers "~0.1.1" - chainsaw "~0.1.0" - -brace-expansion@^1.1.7: - version "1.1.11" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" - integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -braces@^3.0.1: - version "3.0.2" - resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" - integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== - dependencies: - fill-range "^7.0.1" - -browser-process-hrtime@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz#3c9b4b7d782c8121e56f10106d84c0d0ffc94626" - integrity sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow== - -browserslist@^4.16.6: - version "4.16.6" - resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.16.6.tgz#d7901277a5a88e554ed305b183ec9b0c08f66fa2" - integrity sha512-Wspk/PqO+4W9qp5iUTJsa1B/QrYn1keNCcEP5OvP7WBwT4KaDly0uONYmC6Xa3Z5IqnUgS0KcgLYu1l74x0ZXQ== - dependencies: - caniuse-lite "^1.0.30001219" - colorette "^1.2.2" - electron-to-chromium "^1.3.723" - escalade "^3.1.1" - node-releases "^1.1.71" - -bs-logger@0.x: - version "0.2.6" - resolved "https://registry.yarnpkg.com/bs-logger/-/bs-logger-0.2.6.tgz#eb7d365307a72cf974cc6cda76b68354ad336bd8" - integrity sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog== - dependencies: - fast-json-stable-stringify "2.x" - -bser@2.1.1, bser@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/bser/-/bser-2.1.1.tgz#e6787da20ece9d07998533cfd9de6f5c38f4bc05" - integrity sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ== - dependencies: - node-int64 "^0.4.0" - -buffer-from@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" - integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== - -buffers@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/buffers/-/buffers-0.1.1.tgz#b24579c3bed4d6d396aeee6d9a8ae7f5482ab7bb" - integrity sha1-skV5w77U1tOWru5tmorn9Ugqt7s= - -bytes@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.0.tgz#f6cf7933a360e0588fa9fde85651cdc7f805d1f6" - integrity sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg== - -callsites@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" - integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== - -camelcase@^5.3.1: - version "5.3.1" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" - integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== - -camelcase@^6.2.0: - version "6.2.0" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.2.0.tgz#924af881c9d525ac9d87f40d964e5cea982a1809" - integrity sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg== - -caniuse-lite@^1.0.30001219: - version "1.0.30001247" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001247.tgz#105be7a8fb30cdd303275e769a9dfb87d4b3577a" - integrity sha512-4rS7co+7+AoOSPRPOPUt5/GdaqZc0EsUpWk66ofE3HJTAajUK2Ss2VwoNzVN69ghg8lYYlh0an0Iy4LIHHo9UQ== - -chainsaw@~0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/chainsaw/-/chainsaw-0.1.0.tgz#5eab50b28afe58074d0d58291388828b5e5fbc98" - integrity sha1-XqtQsor+WAdNDVgpE4iCi15fvJg= - dependencies: - traverse ">=0.3.0 <0.4" - -chalk@^2.0.0: - version "2.4.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" - integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== - dependencies: - ansi-styles "^3.2.1" - escape-string-regexp "^1.0.5" - supports-color "^5.3.0" - -chalk@^4.0.0: - version "4.1.1" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.1.tgz#c80b3fab28bf6371e6863325eee67e618b77e6ad" - integrity sha512-diHzdDKxcU+bAsUboHLPEDQiw0qEe0qd7SYUn3HgcFlWgbDcfLGswOHYeGrHKzG9z6UYf01d9VFMfZxPM1xZSg== - dependencies: - ansi-styles "^4.1.0" - supports-color "^7.1.0" - -char-regex@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/char-regex/-/char-regex-1.0.2.tgz#d744358226217f981ed58f479b1d6bcc29545dcf" - integrity sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw== - -chownr@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece" - integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ== - -ci-info@^3.1.1: - version "3.2.0" - resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-3.2.0.tgz#2876cb948a498797b5236f0095bc057d0dca38b6" - integrity sha512-dVqRX7fLUm8J6FgHJ418XuIgDLZDkYcDFTeL6TA2gt5WlIZUQrrH6EZrNClwT/H0FateUsZkGIOPRrLbP+PR9A== - -cjs-module-lexer@^1.0.0: - version "1.2.2" - resolved "https://registry.yarnpkg.com/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz#9f84ba3244a512f3a54e5277e8eef4c489864e40" - integrity sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA== - -cli-table@^0.3.4: - version "0.3.6" - resolved "https://registry.yarnpkg.com/cli-table/-/cli-table-0.3.6.tgz#e9d6aa859c7fe636981fd3787378c2a20bce92fc" - integrity sha512-ZkNZbnZjKERTY5NwC2SeMeLeifSPq/pubeRoTpdr3WchLlnZg6hEgvHkK5zL7KNFdd9PmHN8lxrENUwI3cE8vQ== - dependencies: - colors "1.0.3" - -cliui@^7.0.2: - version "7.0.4" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" - integrity sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ== - dependencies: - string-width "^4.2.0" - strip-ansi "^6.0.0" - wrap-ansi "^7.0.0" - -co@^4.6.0: - version "4.6.0" - resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" - integrity sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ= - -collect-v8-coverage@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz#cc2c8e94fc18bbdffe64d6534570c8a673b27f59" - integrity sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg== - -color-convert@^1.9.0: - version "1.9.3" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" - integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== - dependencies: - color-name "1.1.3" - -color-convert@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" - integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== - dependencies: - color-name "~1.1.4" - -color-name@1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" - integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= - -color-name@~1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" - integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== - -colorette@^1.2.2: - version "1.2.2" - resolved "https://registry.yarnpkg.com/colorette/-/colorette-1.2.2.tgz#cbcc79d5e99caea2dbf10eb3a26fd8b3e6acfa94" - integrity sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w== - -colors@1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/colors/-/colors-1.0.3.tgz#0433f44d809680fdeb60ed260f1b0c262e82a40b" - integrity sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs= - -combined-stream@^1.0.8: - version "1.0.8" - resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" - integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== - dependencies: - delayed-stream "~1.0.0" - -comment-parser@^0.7.6: - version "0.7.6" - resolved "https://registry.yarnpkg.com/comment-parser/-/comment-parser-0.7.6.tgz#0e743a53c8e646c899a1323db31f6cd337b10f12" - integrity sha512-GKNxVA7/iuTnAqGADlTWX4tkhzxZKXp5fLJqKTlQLHkE65XDUKutZ3BHaJC5IGcper2tT3QRD1xr4o3jNpgXXg== - -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= - -content-disposition@^0.5.3: - version "0.5.3" - resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.3.tgz#e130caf7e7279087c5616c2007d0485698984fbd" - integrity sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g== - dependencies: - safe-buffer "5.1.2" - -convert-source-map@^1.4.0, convert-source-map@^1.6.0, convert-source-map@^1.7.0: - version "1.8.0" - resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.8.0.tgz#f3373c32d21b4d780dd8004514684fb791ca4369" - integrity sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA== - dependencies: - safe-buffer "~5.1.1" - -cross-spawn@^7.0.2, cross-spawn@^7.0.3: - version "7.0.3" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" - integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== - dependencies: - path-key "^3.1.0" - shebang-command "^2.0.0" - which "^2.0.1" - -cssom@^0.4.4: - version "0.4.4" - resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.4.4.tgz#5a66cf93d2d0b661d80bf6a44fb65f5c2e4e0a10" - integrity sha512-p3pvU7r1MyyqbTk+WbNJIgJjG2VmTIaB10rI93LzVPrmDJKkzKYMtxxyAvQXR/NS6otuzveI7+7BBq3SjBS2mw== - -cssom@~0.3.6: - version "0.3.8" - resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.3.8.tgz#9f1276f5b2b463f2114d3f2c75250af8c1a36f4a" - integrity sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg== - -cssstyle@^2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/cssstyle/-/cssstyle-2.3.0.tgz#ff665a0ddbdc31864b09647f34163443d90b0852" - integrity sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A== - dependencies: - cssom "~0.3.6" - -data-urls@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-2.0.0.tgz#156485a72963a970f5d5821aaf642bef2bf2db9b" - integrity sha512-X5eWTSXO/BJmpdIKCRuKUgSCgAN0OwliVK3yPKbwIWU1Tdw5BRajxlzMidvh+gwko9AfQ9zIj52pzF91Q3YAvQ== - dependencies: - abab "^2.0.3" - whatwg-mimetype "^2.3.0" - whatwg-url "^8.0.0" - -date-format@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/date-format/-/date-format-2.1.0.tgz#31d5b5ea211cf5fd764cd38baf9d033df7e125cf" - integrity sha512-bYQuGLeFxhkxNOF3rcMtiZxvCBAquGzZm6oWA1oZ0g2THUzivaRhv8uOhdr19LmoobSOLoIAxeUK2RdbM8IFTA== - -date-format@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/date-format/-/date-format-3.0.0.tgz#eb8780365c7d2b1511078fb491e6479780f3ad95" - integrity sha512-eyTcpKOcamdhWJXj56DpQMo1ylSQpcGtGKXcU0Tb97+K56/CF5amAqqqNj0+KvA0iw2ynxtHWFsPDSClCxe48w== - -debounce@^1.2.0: - version "1.2.1" - resolved "https://registry.yarnpkg.com/debounce/-/debounce-1.2.1.tgz#38881d8f4166a5c5848020c11827b834bcb3e0a5" - integrity sha512-XRRe6Glud4rd/ZGQfiV1ruXSfbvfJedlV9Y6zOlP+2K04vBYiJEte6stfFkCP03aMnY5tsipamumUjL14fofug== - -debug@4, debug@^4.0.1, debug@^4.1.0, debug@^4.1.1, debug@^4.3.1: - version "4.3.2" - resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" - integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== - dependencies: - ms "2.1.2" - -decimal.js@^10.2.1: - version "10.3.1" - resolved "https://registry.yarnpkg.com/decimal.js/-/decimal.js-10.3.1.tgz#d8c3a444a9c6774ba60ca6ad7261c3a94fd5e783" - integrity sha512-V0pfhfr8suzyPGOx3nmq4aHqabehUZn6Ch9kyFpV79TGDTWFmHqUqXdabR7QHqxzrYolF4+tVmJhUG4OURg5dQ== - -decompress-response@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/decompress-response/-/decompress-response-6.0.0.tgz#ca387612ddb7e104bd16d85aab00d5ecf09c66fc" - integrity sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ== - dependencies: - mimic-response "^3.1.0" - -dedent@^0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/dedent/-/dedent-0.7.0.tgz#2495ddbaf6eb874abb0e1be9df22d2e5a544326c" - integrity sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw= - -deep-extend@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" - integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA== - -deep-is@^0.1.3, deep-is@~0.1.3: - version "0.1.3" - resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" - integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ= - -deepmerge@^4.2.2: - version "4.2.2" - resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.2.2.tgz#44d2ea3679b8f4d4ffba33f03d865fc1e7bf4955" - integrity sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg== - -delayed-stream@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" - integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= - -detect-newline@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/detect-newline/-/detect-newline-3.1.0.tgz#576f5dfc63ae1a192ff192d8ad3af6308991b651" - integrity sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA== - -diff-sequences@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-27.0.6.tgz#3305cb2e55a033924054695cc66019fd7f8e5723" - integrity sha512-ag6wfpBFyNXZ0p8pcuIDS//D8H062ZQJ3fzYxjpmeKjnz8W4pekL3AI8VohmyZmsWW2PWaHgjsmqR6L13101VQ== - -dir-glob@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f" - integrity sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA== - dependencies: - path-type "^4.0.0" - -doctrine@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-3.0.0.tgz#addebead72a6574db783639dc87a121773973961" - integrity sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w== - dependencies: - esutils "^2.0.2" - -domexception@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/domexception/-/domexception-2.0.1.tgz#fb44aefba793e1574b0af6aed2801d057529f304" - integrity sha512-yxJ2mFy/sibVQlu5qHjOkf9J3K6zgmCxgJ94u2EdvDOV09H+32LtRswEcUsmUWN72pVLOEnTSRaIVVzVQgS0dg== - dependencies: - webidl-conversions "^5.0.0" - -electron-to-chromium@^1.3.723: - version "1.3.787" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.787.tgz#0d814dcc374bb8a0ae7a17c0308c39fb18fcc7bb" - integrity sha512-zeM5AFwvTlSYvGpBaFZKVo7GQEWSk6hS3rQ7mdrr3qB7CiqVl84K6nIPznyKSu0b8ABiEeMEIqyBuzqMkxnjjg== - -emittery@^0.8.1: - version "0.8.1" - resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.8.1.tgz#bb23cc86d03b30aa75a7f734819dee2e1ba70860" - integrity sha512-uDfvUjVrfGJJhymx/kz6prltenw1u7WrCg1oa94zYY8xxVpLLUu045LAT0dhDZdXG58/EpPL/5kA180fQ/qudg== - -emoji-regex@^8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" - integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== - -enquirer@^2.3.5: - version "2.3.6" - resolved "https://registry.yarnpkg.com/enquirer/-/enquirer-2.3.6.tgz#2a7fe5dd634a1e4125a975ec994ff5456dc3734d" - integrity sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg== - dependencies: - ansi-colors "^4.1.1" - -esbuild@^0.12.7: - version "0.12.16" - resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.12.16.tgz#c397144ce13b445a6ead9c1f747da11f79ec5e67" - integrity sha512-XqI9cXP2bmQ6MREIqrYBb13KfYFSERsV1+e5jSVWps8dNlLZK+hln7d0mznzDIpfISsg/AgQW0DW3kSInXWhrg== - -escalade@^3.1.1: - version "3.1.1" - resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" - integrity sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw== - -escape-string-regexp@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" - integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= - -escape-string-regexp@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz#a30304e99daa32e23b2fd20f51babd07cffca344" - integrity sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w== - -escape-string-regexp@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" - integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== - -escodegen@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-2.0.0.tgz#5e32b12833e8aa8fa35e1bf0befa89380484c7dd" - integrity sha512-mmHKys/C8BFUGI+MAWNcSYoORYLMdPzjrknd2Vc+bUsjN5bXcr8EhrNB+UTqfL1y3I9c4fw2ihgtMPQLBRiQxw== - dependencies: - esprima "^4.0.1" - estraverse "^5.2.0" - esutils "^2.0.2" - optionator "^0.8.1" - optionalDependencies: - source-map "~0.6.1" - -eslint-plugin-jest@^24.1.3: - version "24.4.0" - resolved "https://registry.yarnpkg.com/eslint-plugin-jest/-/eslint-plugin-jest-24.4.0.tgz#fa4b614dbd46a98b652d830377971f097bda9262" - integrity sha512-8qnt/hgtZ94E9dA6viqfViKBfkJwFHXgJmTWlMGDgunw1XJEGqm3eiPjDsTanM3/u/3Az82nyQM9GX7PM/QGmg== - dependencies: - "@typescript-eslint/experimental-utils" "^4.0.1" - -eslint-plugin-jsdoc@^30.7.13: - version "30.7.13" - resolved "https://registry.yarnpkg.com/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-30.7.13.tgz#52e5c74fb806d3bbeb51d04a0c829508c3c6b563" - integrity sha512-YM4WIsmurrp0rHX6XiXQppqKB8Ne5ATiZLJe2+/fkp9l9ExXFr43BbAbjZaVrpCT+tuPYOZ8k1MICARHnURUNQ== - dependencies: - comment-parser "^0.7.6" - debug "^4.3.1" - jsdoctypeparser "^9.0.0" - lodash "^4.17.20" - regextras "^0.7.1" - semver "^7.3.4" - spdx-expression-parse "^3.0.1" - -eslint-scope@^5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c" - integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw== - dependencies: - esrecurse "^4.3.0" - estraverse "^4.1.1" - -eslint-utils@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.1.0.tgz#d2de5e03424e707dc10c74068ddedae708741b27" - integrity sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg== - dependencies: - eslint-visitor-keys "^1.1.0" - -eslint-utils@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-3.0.0.tgz#8aebaface7345bb33559db0a1f13a1d2d48c3672" - integrity sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA== - dependencies: - eslint-visitor-keys "^2.0.0" - -eslint-visitor-keys@^1.1.0, eslint-visitor-keys@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" - integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== - -eslint-visitor-keys@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz#f65328259305927392c938ed44eb0a5c9b2bd303" - integrity sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw== - -eslint@^7.15.0: - version "7.31.0" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.31.0.tgz#f972b539424bf2604907a970860732c5d99d3aca" - integrity sha512-vafgJpSh2ia8tnTkNUkwxGmnumgckLh5aAbLa1xRmIn9+owi8qBNGKL+B881kNKNTy7FFqTEkpNkUvmw0n6PkA== - dependencies: - "@babel/code-frame" "7.12.11" - "@eslint/eslintrc" "^0.4.3" - "@humanwhocodes/config-array" "^0.5.0" - ajv "^6.10.0" - chalk "^4.0.0" - cross-spawn "^7.0.2" - debug "^4.0.1" - doctrine "^3.0.0" - enquirer "^2.3.5" - escape-string-regexp "^4.0.0" - eslint-scope "^5.1.1" - eslint-utils "^2.1.0" - eslint-visitor-keys "^2.0.0" - espree "^7.3.1" - esquery "^1.4.0" - esutils "^2.0.2" - fast-deep-equal "^3.1.3" - file-entry-cache "^6.0.1" - functional-red-black-tree "^1.0.1" - glob-parent "^5.1.2" - globals "^13.6.0" - ignore "^4.0.6" - import-fresh "^3.0.0" - imurmurhash "^0.1.4" - is-glob "^4.0.0" - js-yaml "^3.13.1" - json-stable-stringify-without-jsonify "^1.0.1" - levn "^0.4.1" - lodash.merge "^4.6.2" - minimatch "^3.0.4" - natural-compare "^1.4.0" - optionator "^0.9.1" - progress "^2.0.0" - regexpp "^3.1.0" - semver "^7.2.1" - strip-ansi "^6.0.0" - strip-json-comments "^3.1.0" - table "^6.0.9" - text-table "^0.2.0" - v8-compile-cache "^2.0.3" - -espree@^7.3.0, espree@^7.3.1: - version "7.3.1" - resolved "https://registry.yarnpkg.com/espree/-/espree-7.3.1.tgz#f2df330b752c6f55019f8bd89b7660039c1bbbb6" - integrity sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g== - dependencies: - acorn "^7.4.0" - acorn-jsx "^5.3.1" - eslint-visitor-keys "^1.3.0" - -esprima@^4.0.0, esprima@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" - integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== - -esquery@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.4.0.tgz#2148ffc38b82e8c7057dfed48425b3e61f0f24a5" - integrity sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w== - dependencies: - estraverse "^5.1.0" - -esrecurse@^4.3.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.3.0.tgz#7ad7964d679abb28bee72cec63758b1c5d2c9921" - integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag== - dependencies: - estraverse "^5.2.0" - -estraverse@^4.1.1: - version "4.3.0" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" - integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== - -estraverse@^5.1.0, estraverse@^5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.2.0.tgz#307df42547e6cc7324d3cf03c155d5cdb8c53880" - integrity sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ== - -esutils@^2.0.2: - version "2.0.3" - resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" - integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== - -event-lite@^0.1.1: - version "0.1.2" - resolved "https://registry.yarnpkg.com/event-lite/-/event-lite-0.1.2.tgz#838a3e0fdddef8cc90f128006c8e55a4e4e4c11b" - integrity sha512-HnSYx1BsJ87/p6swwzv+2v6B4X+uxUteoDfRxsAb1S1BePzQqOLevVmkdA15GHJVd9A9Ok6wygUR18Hu0YeV9g== - -execa@^5.0.0: - version "5.1.1" - resolved "https://registry.yarnpkg.com/execa/-/execa-5.1.1.tgz#f80ad9cbf4298f7bd1d4c9555c21e93741c411dd" - integrity sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg== - dependencies: - cross-spawn "^7.0.3" - get-stream "^6.0.0" - human-signals "^2.1.0" - is-stream "^2.0.0" - merge-stream "^2.0.0" - npm-run-path "^4.0.1" - onetime "^5.1.2" - signal-exit "^3.0.3" - strip-final-newline "^2.0.0" - -exit@^0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c" - integrity sha1-BjJjj42HfMghB9MKD/8aF8uhzQw= - -expect@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/expect/-/expect-27.0.6.tgz#a4d74fbe27222c718fff68ef49d78e26a8fd4c05" - integrity sha512-psNLt8j2kwg42jGBDSfAlU49CEZxejN1f1PlANWDZqIhBOVU/c2Pm888FcjWJzFewhIsNWfZJeLjUjtKGiPuSw== - dependencies: - "@jest/types" "^27.0.6" - ansi-styles "^5.0.0" - jest-get-type "^27.0.6" - jest-matcher-utils "^27.0.6" - jest-message-util "^27.0.6" - jest-regex-util "^27.0.6" - -fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" - integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== - -fast-diff@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.2.0.tgz#73ee11982d86caaf7959828d519cfe927fac5f03" - integrity sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w== - -fast-glob@^3.1.1: - version "3.2.7" - resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.7.tgz#fd6cb7a2d7e9aa7a7846111e85a196d6b2f766a1" - integrity sha512-rYGMRwip6lUMvYD3BTScMwT1HtAs2d71SMv66Vrxs0IekGZEjhM0pcMfjQPnknBt2zeCwQMEupiN02ZP4DiT1Q== - dependencies: - "@nodelib/fs.stat" "^2.0.2" - "@nodelib/fs.walk" "^1.2.3" - glob-parent "^5.1.2" - merge2 "^1.3.0" - micromatch "^4.0.4" - -fast-json-stable-stringify@2.x, fast-json-stable-stringify@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" - integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== - -fast-levenshtein@^2.0.6, fast-levenshtein@~2.0.6: - version "2.0.6" - resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" - integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= - -fastq@^1.6.0: - version "1.11.1" - resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.11.1.tgz#5d8175aae17db61947f8b162cfc7f63264d22807" - integrity sha512-HOnr8Mc60eNYl1gzwp6r5RoUyAn5/glBolUzP/Ez6IFVPMPirxn/9phgL6zhOtaTy7ISwPvQ+wT+hfcRZh/bzw== - dependencies: - reusify "^1.0.4" - -fb-watchman@^2.0.0, fb-watchman@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/fb-watchman/-/fb-watchman-2.0.1.tgz#fc84fb39d2709cf3ff6d743706157bb5708a8a85" - integrity sha512-DkPJKQeY6kKwmuMretBhr7G6Vodr7bFwDYTXIkfG1gjvNpaxBTQV3PbXg6bR1c1UP4jPOX0jHUbbHANL9vRjVg== - dependencies: - bser "2.1.1" - -file-entry-cache@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-6.0.1.tgz#211b2dd9659cb0394b073e7323ac3c933d522027" - integrity sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg== - dependencies: - flat-cache "^3.0.4" - -fill-range@^7.0.1: - version "7.0.1" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" - integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== - dependencies: - to-regex-range "^5.0.1" - -find-up@^4.0.0, find-up@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" - integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== - dependencies: - locate-path "^5.0.0" - path-exists "^4.0.0" - -flat-cache@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-3.0.4.tgz#61b0338302b2fe9f957dcc32fc2a87f1c3048b11" - integrity sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg== - dependencies: - flatted "^3.1.0" - rimraf "^3.0.2" - -flatted@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.2.tgz#4575b21e2bcee7434aa9be662f4b7b5f9c2b5138" - integrity sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA== - -flatted@^3.1.0: - version "3.2.1" - resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.1.tgz#bbef080d95fca6709362c73044a1634f7c6e7d05" - integrity sha512-OMQjaErSFHmHqZe+PSidH5n8j3O0F2DdnVh8JB4j4eUQ2k6KvB0qGfrKIhapvez5JerBbmWkaLYUYWISaESoXg== - -follow-redirects@^1.13.0: - version "1.14.1" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.1.tgz#d9114ded0a1cfdd334e164e6662ad02bfd91ff43" - integrity sha512-HWqDgT7ZEkqRzBvc2s64vSZ/hfOceEol3ac/7tKwzuvEyWx3/4UegXh5oBOIotkGsObyk3xznnSRVADBgWSQVg== - -form-data@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-3.0.1.tgz#ebd53791b78356a99af9a300d4282c4d5eb9755f" - integrity sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg== - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.8" - mime-types "^2.1.12" - -fs-extra@^8.1.0: - version "8.1.0" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-8.1.0.tgz#49d43c45a88cd9677668cb7be1b46efdb8d2e1c0" - integrity sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g== - dependencies: - graceful-fs "^4.2.0" - jsonfile "^4.0.0" - universalify "^0.1.0" - -fs-extra@^9.0.1: - version "9.1.0" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.1.0.tgz#5954460c764a8da2094ba3554bf839e6b9a7c86d" - integrity sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ== - dependencies: - at-least-node "^1.0.0" - graceful-fs "^4.2.0" - jsonfile "^6.0.1" - universalify "^2.0.0" - -fs-minipass@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-2.1.0.tgz#7f5036fdbf12c63c169190cbe4199c852271f9fb" - integrity sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg== - dependencies: - minipass "^3.0.0" - -fs.realpath@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" - integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= - -fsevents@^2.3.2: - version "2.3.2" - resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" - integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA== - -function-bind@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" - integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== - -functional-red-black-tree@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" - integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc= - -gensync@^1.0.0-beta.2: - version "1.0.0-beta.2" - resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0" - integrity sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg== - -get-caller-file@^2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" - integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== - -get-package-type@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/get-package-type/-/get-package-type-0.1.0.tgz#8de2d803cff44df3bc6c456e6668b36c3926e11a" - integrity sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q== - -get-stream@^6.0.0: - version "6.0.1" - resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-6.0.1.tgz#a262d8eef67aced57c2852ad6167526a43cbf7b7" - integrity sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg== - -glob-parent@^5.1.2: - version "5.1.2" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" - integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== - dependencies: - is-glob "^4.0.1" - -glob@^7.1.1, glob@^7.1.2, glob@^7.1.3, glob@^7.1.4: - version "7.1.7" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.7.tgz#3b193e9233f01d42d0b3f78294bbeeb418f94a90" - integrity sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ== - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -globals@^11.1.0: - version "11.12.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-11.12.0.tgz#ab8795338868a0babd8525758018c2a7eb95c42e" - integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA== - -globals@^13.6.0, globals@^13.9.0: - version "13.10.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-13.10.0.tgz#60ba56c3ac2ca845cfbf4faeca727ad9dd204676" - integrity sha512-piHC3blgLGFjvOuMmWZX60f+na1lXFDhQXBf1UYp2fXPXqvEUbOhNwi6BsQ0bQishwedgnjkwv1d9zKf+MWw3g== - dependencies: - type-fest "^0.20.2" - -globby@^11.0.3: - version "11.0.4" - resolved "https://registry.yarnpkg.com/globby/-/globby-11.0.4.tgz#2cbaff77c2f2a62e71e9b2813a67b97a3a3001a5" - integrity sha512-9O4MVG9ioZJ08ffbcyVYyLOJLk5JQ688pJ4eMGLpdWLHq/Wr1D9BlriLQyL0E+jbkuePVZXYFj47QM/v093wHg== - dependencies: - array-union "^2.1.0" - dir-glob "^3.0.1" - fast-glob "^3.1.1" - ignore "^5.1.4" - merge2 "^1.3.0" - slash "^3.0.0" - -graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.4: - version "4.2.6" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.6.tgz#ff040b2b0853b23c3d31027523706f1885d76bee" - integrity sha512-nTnJ528pbqxYanhpDYsi4Rd8MAeaBA67+RZ10CM1m3bTAVFEDcd5AuA4a6W5YkGZ1iNXHzZz8T6TBKLeBuNriQ== - -has-flag@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" - integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= - -has-flag@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" - integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== - -has@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" - integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== - dependencies: - function-bind "^1.1.1" - -html-encoding-sniffer@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-2.0.1.tgz#42a6dc4fd33f00281176e8b23759ca4e4fa185f3" - integrity sha512-D5JbOMBIR/TVZkubHT+OyT2705QvogUW4IBn6nHd756OwieSF9aDYFj4dv6HHEVGYbHaLETa3WggZYWWMyy3ZQ== - dependencies: - whatwg-encoding "^1.0.5" - -html-escaper@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453" - integrity sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg== - -http-proxy-agent@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz#8a8c8ef7f5932ccf953c296ca8291b95aa74aa3a" - integrity sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg== - dependencies: - "@tootallnate/once" "1" - agent-base "6" - debug "4" - -https-proxy-agent@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz#e2a90542abb68a762e0a0850f6c9edadfd8506b2" - integrity sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA== - dependencies: - agent-base "6" - debug "4" - -human-signals@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-2.1.0.tgz#dc91fcba42e4d06e4abaed33b3e7a3c02f514ea0" - integrity sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw== - -iconv-lite@0.4.24: - version "0.4.24" - resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" - integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== - dependencies: - safer-buffer ">= 2.1.2 < 3" - -ieee754@^1.1.8: - version "1.2.1" - resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" - integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== - -ignore@^4.0.6: - version "4.0.6" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-4.0.6.tgz#750e3db5862087b4737ebac8207ffd1ef27b25fc" - integrity sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg== - -ignore@^5.1.4: - version "5.1.8" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.1.8.tgz#f150a8b50a34289b33e22f5889abd4d8016f0e57" - integrity sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw== - -import-fresh@^3.0.0, import-fresh@^3.2.1: - version "3.3.0" - resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.3.0.tgz#37162c25fcb9ebaa2e6e53d5b4d88ce17d9e0c2b" - integrity sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw== - dependencies: - parent-module "^1.0.0" - resolve-from "^4.0.0" - -import-local@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.0.2.tgz#a8cfd0431d1de4a2199703d003e3e62364fa6db6" - integrity sha512-vjL3+w0oulAVZ0hBHnxa/Nm5TAurf9YLQJDhqRZyqb+VKGOB6LU8t9H1Nr5CIo16vh9XfJTOoHwU0B71S557gA== - dependencies: - pkg-dir "^4.2.0" - resolve-cwd "^3.0.0" - -imurmurhash@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" - integrity sha1-khi5srkoojixPcT7a21XbyMUU+o= - -inflight@^1.0.4: - version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" - integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= - dependencies: - once "^1.3.0" - wrappy "1" - -inherits@2: - version "2.0.4" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" - integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== - -ini@~1.3.0: - version "1.3.8" - resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.8.tgz#a29da425b48806f34767a4efce397269af28432c" - integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew== - -int64-buffer@^0.1.9: - version "0.1.10" - resolved "https://registry.yarnpkg.com/int64-buffer/-/int64-buffer-0.1.10.tgz#277b228a87d95ad777d07c13832022406a473423" - integrity sha1-J3siiofZWtd30HwTgyAiQGpHNCM= - -is-ci@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-ci/-/is-ci-3.0.0.tgz#c7e7be3c9d8eef7d0fa144390bd1e4b88dc4c994" - integrity sha512-kDXyttuLeslKAHYL/K28F2YkM3x5jvFPEw3yXbRptXydjD9rpLEz+C5K5iutY9ZiUu6AP41JdvRQwF4Iqs4ZCQ== - dependencies: - ci-info "^3.1.1" - -is-core-module@^2.2.0: - version "2.5.0" - resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.5.0.tgz#f754843617c70bfd29b7bd87327400cda5c18491" - integrity sha512-TXCMSDsEHMEEZ6eCA8rwRDbLu55MRGmrctljsBX/2v1d9/GzqHOxW5c5oPSgrUt2vBFXebu9rGqckXGPWOlYpg== - dependencies: - has "^1.0.3" - -is-extglob@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" - integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= - -is-fullwidth-code-point@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" - integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== - -is-generator-fn@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-generator-fn/-/is-generator-fn-2.1.0.tgz#7d140adc389aaf3011a8f2a2a4cfa6faadffb118" - integrity sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ== - -is-glob@^4.0.0, is-glob@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" - integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== - dependencies: - is-extglob "^2.1.1" - -is-number@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" - integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== - -is-potential-custom-element-name@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz#171ed6f19e3ac554394edf78caa05784a45bebb5" - integrity sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ== - -is-stream@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.1.tgz#fac1e3d53b97ad5a9d0ae9cef2389f5810a5c077" - integrity sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg== - -is-typedarray@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" - integrity sha1-5HnICFjfDBsR3dppQPlgEfzaSpo= - -isarray@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" - integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= - -isexe@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" - integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= - -istanbul-lib-coverage@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz#f5944a37c70b550b02a78a5c3b2055b280cec8ec" - integrity sha512-UiUIqxMgRDET6eR+o5HbfRYP1l0hqkWOs7vNxC/mggutCMUIhWMm8gAHb8tHlyfD3/l6rlgNA5cKdDzEAf6hEg== - -istanbul-lib-instrument@^4.0.0, istanbul-lib-instrument@^4.0.3: - version "4.0.3" - resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.3.tgz#873c6fff897450118222774696a3f28902d77c1d" - integrity sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ== - dependencies: - "@babel/core" "^7.7.5" - "@istanbuljs/schema" "^0.1.2" - istanbul-lib-coverage "^3.0.0" - semver "^6.3.0" - -istanbul-lib-report@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz#7518fe52ea44de372f460a76b5ecda9ffb73d8a6" - integrity sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw== - dependencies: - istanbul-lib-coverage "^3.0.0" - make-dir "^3.0.0" - supports-color "^7.1.0" - -istanbul-lib-source-maps@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.0.tgz#75743ce6d96bb86dc7ee4352cf6366a23f0b1ad9" - integrity sha512-c16LpFRkR8vQXyHZ5nLpY35JZtzj1PQY1iZmesUbf1FZHbIupcWfjgOXBY9YHkLEQ6puz1u4Dgj6qmU/DisrZg== - dependencies: - debug "^4.1.1" - istanbul-lib-coverage "^3.0.0" - source-map "^0.6.1" - -istanbul-reports@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-3.0.2.tgz#d593210e5000683750cb09fc0644e4b6e27fd53b" - integrity sha512-9tZvz7AiR3PEDNGiV9vIouQ/EAcqMXFmkcA1CDFTwOB98OZVDL0PH9glHotf5Ugp6GCOTypfzGWI/OqjWNCRUw== - dependencies: - html-escaper "^2.0.0" - istanbul-lib-report "^3.0.0" - -isuri@^2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/isuri/-/isuri-2.0.3.tgz#3437121db2fe65af0ba080b7e1a8636f632cca91" - integrity sha1-NDcSHbL+Za8LoIC34ahjb2MsypE= - dependencies: - rfc-3986 "1.0.1" - -jest-changed-files@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-changed-files/-/jest-changed-files-27.0.6.tgz#bed6183fcdea8a285482e3b50a9a7712d49a7a8b" - integrity sha512-BuL/ZDauaq5dumYh5y20sn4IISnf1P9A0TDswTxUi84ORGtVa86ApuBHqICL0vepqAnZiY6a7xeSPWv2/yy4eA== - dependencies: - "@jest/types" "^27.0.6" - execa "^5.0.0" - throat "^6.0.1" - -jest-circus@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-circus/-/jest-circus-27.0.6.tgz#dd4df17c4697db6a2c232aaad4e9cec666926668" - integrity sha512-OJlsz6BBeX9qR+7O9lXefWoc2m9ZqcZ5Ohlzz0pTEAG4xMiZUJoacY8f4YDHxgk0oKYxj277AfOk9w6hZYvi1Q== - dependencies: - "@jest/environment" "^27.0.6" - "@jest/test-result" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/node" "*" - chalk "^4.0.0" - co "^4.6.0" - dedent "^0.7.0" - expect "^27.0.6" - is-generator-fn "^2.0.0" - jest-each "^27.0.6" - jest-matcher-utils "^27.0.6" - jest-message-util "^27.0.6" - jest-runtime "^27.0.6" - jest-snapshot "^27.0.6" - jest-util "^27.0.6" - pretty-format "^27.0.6" - slash "^3.0.0" - stack-utils "^2.0.3" - throat "^6.0.1" - -jest-cli@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-cli/-/jest-cli-27.0.6.tgz#d021e5f4d86d6a212450d4c7b86cb219f1e6864f" - integrity sha512-qUUVlGb9fdKir3RDE+B10ULI+LQrz+MCflEH2UJyoUjoHHCbxDrMxSzjQAPUMsic4SncI62ofYCcAvW6+6rhhg== - dependencies: - "@jest/core" "^27.0.6" - "@jest/test-result" "^27.0.6" - "@jest/types" "^27.0.6" - chalk "^4.0.0" - exit "^0.1.2" - graceful-fs "^4.2.4" - import-local "^3.0.2" - jest-config "^27.0.6" - jest-util "^27.0.6" - jest-validate "^27.0.6" - prompts "^2.0.1" - yargs "^16.0.3" - -jest-config@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-config/-/jest-config-27.0.6.tgz#119fb10f149ba63d9c50621baa4f1f179500277f" - integrity sha512-JZRR3I1Plr2YxPBhgqRspDE2S5zprbga3swYNrvY3HfQGu7p/GjyLOqwrYad97tX3U3mzT53TPHVmozacfP/3w== - dependencies: - "@babel/core" "^7.1.0" - "@jest/test-sequencer" "^27.0.6" - "@jest/types" "^27.0.6" - babel-jest "^27.0.6" - chalk "^4.0.0" - deepmerge "^4.2.2" - glob "^7.1.1" - graceful-fs "^4.2.4" - is-ci "^3.0.0" - jest-circus "^27.0.6" - jest-environment-jsdom "^27.0.6" - jest-environment-node "^27.0.6" - jest-get-type "^27.0.6" - jest-jasmine2 "^27.0.6" - jest-regex-util "^27.0.6" - jest-resolve "^27.0.6" - jest-runner "^27.0.6" - jest-util "^27.0.6" - jest-validate "^27.0.6" - micromatch "^4.0.4" - pretty-format "^27.0.6" - -jest-diff@^27.0.0, jest-diff@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-27.0.6.tgz#4a7a19ee6f04ad70e0e3388f35829394a44c7b5e" - integrity sha512-Z1mqgkTCSYaFgwTlP/NUiRzdqgxmmhzHY1Tq17zL94morOHfHu3K4bgSgl+CR4GLhpV8VxkuOYuIWnQ9LnFqmg== - dependencies: - chalk "^4.0.0" - diff-sequences "^27.0.6" - jest-get-type "^27.0.6" - pretty-format "^27.0.6" - -jest-docblock@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-27.0.6.tgz#cc78266acf7fe693ca462cbbda0ea4e639e4e5f3" - integrity sha512-Fid6dPcjwepTFraz0YxIMCi7dejjJ/KL9FBjPYhBp4Sv1Y9PdhImlKZqYU555BlN4TQKaTc+F2Av1z+anVyGkA== - dependencies: - detect-newline "^3.0.0" - -jest-each@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-each/-/jest-each-27.0.6.tgz#cee117071b04060158dc8d9a66dc50ad40ef453b" - integrity sha512-m6yKcV3bkSWrUIjxkE9OC0mhBZZdhovIW5ergBYirqnkLXkyEn3oUUF/QZgyecA1cF1QFyTE8bRRl8Tfg1pfLA== - dependencies: - "@jest/types" "^27.0.6" - chalk "^4.0.0" - jest-get-type "^27.0.6" - jest-util "^27.0.6" - pretty-format "^27.0.6" - -jest-environment-jsdom@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-environment-jsdom/-/jest-environment-jsdom-27.0.6.tgz#f66426c4c9950807d0a9f209c590ce544f73291f" - integrity sha512-FvetXg7lnXL9+78H+xUAsra3IeZRTiegA3An01cWeXBspKXUhAwMM9ycIJ4yBaR0L7HkoMPaZsozCLHh4T8fuw== - dependencies: - "@jest/environment" "^27.0.6" - "@jest/fake-timers" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/node" "*" - jest-mock "^27.0.6" - jest-util "^27.0.6" - jsdom "^16.6.0" - -jest-environment-node@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-environment-node/-/jest-environment-node-27.0.6.tgz#a6699b7ceb52e8d68138b9808b0c404e505f3e07" - integrity sha512-+Vi6yLrPg/qC81jfXx3IBlVnDTI6kmRr08iVa2hFCWmJt4zha0XW7ucQltCAPhSR0FEKEoJ3i+W4E6T0s9is0w== - dependencies: - "@jest/environment" "^27.0.6" - "@jest/fake-timers" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/node" "*" - jest-mock "^27.0.6" - jest-util "^27.0.6" - -jest-get-type@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-27.0.6.tgz#0eb5c7f755854279ce9b68a9f1a4122f69047cfe" - integrity sha512-XTkK5exIeUbbveehcSR8w0bhH+c0yloW/Wpl+9vZrjzztCPWrxhHwkIFpZzCt71oRBsgxmuUfxEqOYoZI2macg== - -jest-haste-map@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-haste-map/-/jest-haste-map-27.0.6.tgz#4683a4e68f6ecaa74231679dca237279562c8dc7" - integrity sha512-4ldjPXX9h8doB2JlRzg9oAZ2p6/GpQUNAeiYXqcpmrKbP0Qev0wdZlxSMOmz8mPOEnt4h6qIzXFLDi8RScX/1w== - dependencies: - "@jest/types" "^27.0.6" - "@types/graceful-fs" "^4.1.2" - "@types/node" "*" - anymatch "^3.0.3" - fb-watchman "^2.0.0" - graceful-fs "^4.2.4" - jest-regex-util "^27.0.6" - jest-serializer "^27.0.6" - jest-util "^27.0.6" - jest-worker "^27.0.6" - micromatch "^4.0.4" - walker "^1.0.7" - optionalDependencies: - fsevents "^2.3.2" - -jest-jasmine2@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-jasmine2/-/jest-jasmine2-27.0.6.tgz#fd509a9ed3d92bd6edb68a779f4738b100655b37" - integrity sha512-cjpH2sBy+t6dvCeKBsHpW41mjHzXgsavaFMp+VWRf0eR4EW8xASk1acqmljFtK2DgyIECMv2yCdY41r2l1+4iA== - dependencies: - "@babel/traverse" "^7.1.0" - "@jest/environment" "^27.0.6" - "@jest/source-map" "^27.0.6" - "@jest/test-result" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/node" "*" - chalk "^4.0.0" - co "^4.6.0" - expect "^27.0.6" - is-generator-fn "^2.0.0" - jest-each "^27.0.6" - jest-matcher-utils "^27.0.6" - jest-message-util "^27.0.6" - jest-runtime "^27.0.6" - jest-snapshot "^27.0.6" - jest-util "^27.0.6" - pretty-format "^27.0.6" - throat "^6.0.1" - -jest-leak-detector@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-leak-detector/-/jest-leak-detector-27.0.6.tgz#545854275f85450d4ef4b8fe305ca2a26450450f" - integrity sha512-2/d6n2wlH5zEcdctX4zdbgX8oM61tb67PQt4Xh8JFAIy6LRKUnX528HulkaG6nD5qDl5vRV1NXejCe1XRCH5gQ== - dependencies: - jest-get-type "^27.0.6" - pretty-format "^27.0.6" - -jest-matcher-utils@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-27.0.6.tgz#2a8da1e86c620b39459f4352eaa255f0d43e39a9" - integrity sha512-OFgF2VCQx9vdPSYTHWJ9MzFCehs20TsyFi6bIHbk5V1u52zJOnvF0Y/65z3GLZHKRuTgVPY4Z6LVePNahaQ+tA== - dependencies: - chalk "^4.0.0" - jest-diff "^27.0.6" - jest-get-type "^27.0.6" - pretty-format "^27.0.6" - -jest-message-util@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-message-util/-/jest-message-util-27.0.6.tgz#158bcdf4785706492d164a39abca6a14da5ab8b5" - integrity sha512-rBxIs2XK7rGy+zGxgi+UJKP6WqQ+KrBbD1YMj517HYN3v2BG66t3Xan3FWqYHKZwjdB700KiAJ+iES9a0M+ixw== - dependencies: - "@babel/code-frame" "^7.12.13" - "@jest/types" "^27.0.6" - "@types/stack-utils" "^2.0.0" - chalk "^4.0.0" - graceful-fs "^4.2.4" - micromatch "^4.0.4" - pretty-format "^27.0.6" - slash "^3.0.0" - stack-utils "^2.0.3" - -jest-mock@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-mock/-/jest-mock-27.0.6.tgz#0efdd40851398307ba16778728f6d34d583e3467" - integrity sha512-lzBETUoK8cSxts2NYXSBWT+EJNzmUVtVVwS1sU9GwE1DLCfGsngg+ZVSIe0yd0ZSm+y791esiuo+WSwpXJQ5Bw== - dependencies: - "@jest/types" "^27.0.6" - "@types/node" "*" - -jest-pnp-resolver@^1.2.2: - version "1.2.2" - resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz#b704ac0ae028a89108a4d040b3f919dfddc8e33c" - integrity sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w== - -jest-regex-util@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-27.0.6.tgz#02e112082935ae949ce5d13b2675db3d8c87d9c5" - integrity sha512-SUhPzBsGa1IKm8hx2F4NfTGGp+r7BXJ4CulsZ1k2kI+mGLG+lxGrs76veN2LF/aUdGosJBzKgXmNCw+BzFqBDQ== - -jest-resolve-dependencies@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-resolve-dependencies/-/jest-resolve-dependencies-27.0.6.tgz#3e619e0ef391c3ecfcf6ef4056207a3d2be3269f" - integrity sha512-mg9x9DS3BPAREWKCAoyg3QucCr0n6S8HEEsqRCKSPjPcu9HzRILzhdzY3imsLoZWeosEbJZz6TKasveczzpJZA== - dependencies: - "@jest/types" "^27.0.6" - jest-regex-util "^27.0.6" - jest-snapshot "^27.0.6" - -jest-resolve@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-resolve/-/jest-resolve-27.0.6.tgz#e90f436dd4f8fbf53f58a91c42344864f8e55bff" - integrity sha512-yKmIgw2LgTh7uAJtzv8UFHGF7Dm7XfvOe/LQ3Txv101fLM8cx2h1QVwtSJ51Q/SCxpIiKfVn6G2jYYMDNHZteA== - dependencies: - "@jest/types" "^27.0.6" - chalk "^4.0.0" - escalade "^3.1.1" - graceful-fs "^4.2.4" - jest-pnp-resolver "^1.2.2" - jest-util "^27.0.6" - jest-validate "^27.0.6" - resolve "^1.20.0" - slash "^3.0.0" - -jest-runner@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-runner/-/jest-runner-27.0.6.tgz#1325f45055539222bbc7256a6976e993ad2f9520" - integrity sha512-W3Bz5qAgaSChuivLn+nKOgjqNxM7O/9JOJoKDCqThPIg2sH/d4A/lzyiaFgnb9V1/w29Le11NpzTJSzga1vyYQ== - dependencies: - "@jest/console" "^27.0.6" - "@jest/environment" "^27.0.6" - "@jest/test-result" "^27.0.6" - "@jest/transform" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/node" "*" - chalk "^4.0.0" - emittery "^0.8.1" - exit "^0.1.2" - graceful-fs "^4.2.4" - jest-docblock "^27.0.6" - jest-environment-jsdom "^27.0.6" - jest-environment-node "^27.0.6" - jest-haste-map "^27.0.6" - jest-leak-detector "^27.0.6" - jest-message-util "^27.0.6" - jest-resolve "^27.0.6" - jest-runtime "^27.0.6" - jest-util "^27.0.6" - jest-worker "^27.0.6" - source-map-support "^0.5.6" - throat "^6.0.1" - -jest-runtime@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-runtime/-/jest-runtime-27.0.6.tgz#45877cfcd386afdd4f317def551fc369794c27c9" - integrity sha512-BhvHLRVfKibYyqqEFkybsznKwhrsu7AWx2F3y9G9L95VSIN3/ZZ9vBpm/XCS2bS+BWz3sSeNGLzI3TVQ0uL85Q== - dependencies: - "@jest/console" "^27.0.6" - "@jest/environment" "^27.0.6" - "@jest/fake-timers" "^27.0.6" - "@jest/globals" "^27.0.6" - "@jest/source-map" "^27.0.6" - "@jest/test-result" "^27.0.6" - "@jest/transform" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/yargs" "^16.0.0" - chalk "^4.0.0" - cjs-module-lexer "^1.0.0" - collect-v8-coverage "^1.0.0" - exit "^0.1.2" - glob "^7.1.3" - graceful-fs "^4.2.4" - jest-haste-map "^27.0.6" - jest-message-util "^27.0.6" - jest-mock "^27.0.6" - jest-regex-util "^27.0.6" - jest-resolve "^27.0.6" - jest-snapshot "^27.0.6" - jest-util "^27.0.6" - jest-validate "^27.0.6" - slash "^3.0.0" - strip-bom "^4.0.0" - yargs "^16.0.3" - -jest-serializer@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-serializer/-/jest-serializer-27.0.6.tgz#93a6c74e0132b81a2d54623251c46c498bb5bec1" - integrity sha512-PtGdVK9EGC7dsaziskfqaAPib6wTViY3G8E5wz9tLVPhHyiDNTZn/xjZ4khAw+09QkoOVpn7vF5nPSN6dtBexA== - dependencies: - "@types/node" "*" - graceful-fs "^4.2.4" - -jest-snapshot@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-snapshot/-/jest-snapshot-27.0.6.tgz#f4e6b208bd2e92e888344d78f0f650bcff05a4bf" - integrity sha512-NTHaz8He+ATUagUgE7C/UtFcRoHqR2Gc+KDfhQIyx+VFgwbeEMjeP+ILpUTLosZn/ZtbNdCF5LkVnN/l+V751A== - dependencies: - "@babel/core" "^7.7.2" - "@babel/generator" "^7.7.2" - "@babel/parser" "^7.7.2" - "@babel/plugin-syntax-typescript" "^7.7.2" - "@babel/traverse" "^7.7.2" - "@babel/types" "^7.0.0" - "@jest/transform" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/babel__traverse" "^7.0.4" - "@types/prettier" "^2.1.5" - babel-preset-current-node-syntax "^1.0.0" - chalk "^4.0.0" - expect "^27.0.6" - graceful-fs "^4.2.4" - jest-diff "^27.0.6" - jest-get-type "^27.0.6" - jest-haste-map "^27.0.6" - jest-matcher-utils "^27.0.6" - jest-message-util "^27.0.6" - jest-resolve "^27.0.6" - jest-util "^27.0.6" - natural-compare "^1.4.0" - pretty-format "^27.0.6" - semver "^7.3.2" - -jest-util@^27.0.0, jest-util@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-27.0.6.tgz#e8e04eec159de2f4d5f57f795df9cdc091e50297" - integrity sha512-1JjlaIh+C65H/F7D11GNkGDDZtDfMEM8EBXsvd+l/cxtgQ6QhxuloOaiayt89DxUvDarbVhqI98HhgrM1yliFQ== - dependencies: - "@jest/types" "^27.0.6" - "@types/node" "*" - chalk "^4.0.0" - graceful-fs "^4.2.4" - is-ci "^3.0.0" - picomatch "^2.2.3" - -jest-validate@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-27.0.6.tgz#930a527c7a951927df269f43b2dc23262457e2a6" - integrity sha512-yhZZOaMH3Zg6DC83n60pLmdU1DQE46DW+KLozPiPbSbPhlXXaiUTDlhHQhHFpaqIFRrInko1FHXjTRpjWRuWfA== - dependencies: - "@jest/types" "^27.0.6" - camelcase "^6.2.0" - chalk "^4.0.0" - jest-get-type "^27.0.6" - leven "^3.1.0" - pretty-format "^27.0.6" - -jest-watcher@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-watcher/-/jest-watcher-27.0.6.tgz#89526f7f9edf1eac4e4be989bcb6dec6b8878d9c" - integrity sha512-/jIoKBhAP00/iMGnTwUBLgvxkn7vsOweDrOTSPzc7X9uOyUtJIDthQBTI1EXz90bdkrxorUZVhJwiB69gcHtYQ== - dependencies: - "@jest/test-result" "^27.0.6" - "@jest/types" "^27.0.6" - "@types/node" "*" - ansi-escapes "^4.2.1" - chalk "^4.0.0" - jest-util "^27.0.6" - string-length "^4.0.1" - -jest-worker@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-27.0.6.tgz#a5fdb1e14ad34eb228cfe162d9f729cdbfa28aed" - integrity sha512-qupxcj/dRuA3xHPMUd40gr2EaAurFbkwzOh7wfPaeE9id7hyjURRQoqNfHifHK3XjJU6YJJUQKILGUnwGPEOCA== - dependencies: - "@types/node" "*" - merge-stream "^2.0.0" - supports-color "^8.0.0" - -jest@27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/jest/-/jest-27.0.6.tgz#10517b2a628f0409087fbf473db44777d7a04505" - integrity sha512-EjV8aETrsD0wHl7CKMibKwQNQc3gIRBXlTikBmmHUeVMKaPFxdcUIBfoDqTSXDoGJIivAYGqCWVlzCSaVjPQsA== - dependencies: - "@jest/core" "^27.0.6" - import-local "^3.0.2" - jest-cli "^27.0.6" - -js-tokens@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" - integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== - -js-yaml@^3.13.1: - version "3.14.1" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.1.tgz#dae812fdb3825fa306609a8717383c50c36a0537" - integrity sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g== - dependencies: - argparse "^1.0.7" - esprima "^4.0.0" - -jsdoctypeparser@^9.0.0: - version "9.0.0" - resolved "https://registry.yarnpkg.com/jsdoctypeparser/-/jsdoctypeparser-9.0.0.tgz#8c97e2fb69315eb274b0f01377eaa5c940bd7b26" - integrity sha512-jrTA2jJIL6/DAEILBEh2/w9QxCuwmvNXIry39Ay/HVfhE3o2yVV0U44blYkqdHA/OKloJEqvJy0xU+GSdE2SIw== - -jsdom@^16.6.0: - version "16.7.0" - resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-16.7.0.tgz#918ae71965424b197c819f8183a754e18977b710" - integrity sha512-u9Smc2G1USStM+s/x1ru5Sxrl6mPYCbByG1U/hUmqaVsm4tbNyS7CicOSRyuGQYZhTu0h84qkZZQ/I+dzizSVw== - dependencies: - abab "^2.0.5" - acorn "^8.2.4" - acorn-globals "^6.0.0" - cssom "^0.4.4" - cssstyle "^2.3.0" - data-urls "^2.0.0" - decimal.js "^10.2.1" - domexception "^2.0.1" - escodegen "^2.0.0" - form-data "^3.0.0" - html-encoding-sniffer "^2.0.1" - http-proxy-agent "^4.0.1" - https-proxy-agent "^5.0.0" - is-potential-custom-element-name "^1.0.1" - nwsapi "^2.2.0" - parse5 "6.0.1" - saxes "^5.0.1" - symbol-tree "^3.2.4" - tough-cookie "^4.0.0" - w3c-hr-time "^1.0.2" - w3c-xmlserializer "^2.0.0" - webidl-conversions "^6.1.0" - whatwg-encoding "^1.0.5" - whatwg-mimetype "^2.3.0" - whatwg-url "^8.5.0" - ws "^7.4.6" - xml-name-validator "^3.0.0" - -jsesc@^2.5.1: - version "2.5.2" - resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-2.5.2.tgz#80564d2e483dacf6e8ef209650a67df3f0c283a4" - integrity sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA== - -json-schema-traverse@^0.4.1: - version "0.4.1" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" - integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== - -json-schema-traverse@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz#ae7bcb3656ab77a73ba5c49bf654f38e6b6860e2" - integrity sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug== - -json-stable-stringify-without-jsonify@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" - integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= - -json5@2.x, json5@^2.1.2: - version "2.2.0" - resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.0.tgz#2dfefe720c6ba525d9ebd909950f0515316c89a3" - integrity sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA== - dependencies: - minimist "^1.2.5" - -jsonc-parser@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.0.0.tgz#abdd785701c7e7eaca8a9ec8cf070ca51a745a22" - integrity sha512-fQzRfAbIBnR0IQvftw9FJveWiHp72Fg20giDrHz6TdfB12UH/uue0D3hm57UB5KgAVuniLMCaS8P1IMj9NR7cA== - -jsonfile@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb" - integrity sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss= - optionalDependencies: - graceful-fs "^4.1.6" - -jsonfile@^6.0.1: - version "6.1.0" - resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.1.0.tgz#bc55b2634793c679ec6403094eb13698a6ec0aae" - integrity sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ== - dependencies: - universalify "^2.0.0" - optionalDependencies: - graceful-fs "^4.1.6" - -kleur@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e" - integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w== - -leven@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/leven/-/leven-3.1.0.tgz#77891de834064cccba82ae7842bb6b14a13ed7f2" - integrity sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A== - -levn@^0.4.1: - version "0.4.1" - resolved "https://registry.yarnpkg.com/levn/-/levn-0.4.1.tgz#ae4562c007473b932a6200d403268dd2fffc6ade" - integrity sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ== - dependencies: - prelude-ls "^1.2.1" - type-check "~0.4.0" - -levn@~0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" - integrity sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4= - dependencies: - prelude-ls "~1.1.2" - type-check "~0.3.2" - -locate-path@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" - integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== - dependencies: - p-locate "^4.1.0" - -lodash.clonedeep@^4.5.0: - version "4.5.0" - resolved "https://registry.yarnpkg.com/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz#e23f3f9c4f8fbdde872529c1071857a086e5ccef" - integrity sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8= - -lodash.merge@^4.6.2: - version "4.6.2" - resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a" - integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ== - -lodash.truncate@^4.4.2: - version "4.4.2" - resolved "https://registry.yarnpkg.com/lodash.truncate/-/lodash.truncate-4.4.2.tgz#5a350da0b1113b837ecfffd5812cbe58d6eae193" - integrity sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM= - -lodash@4.x, lodash@^4.17.20, lodash@^4.7.0: - version "4.17.21" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" - integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== - -log4js@^6.3.0: - version "6.3.0" - resolved "https://registry.yarnpkg.com/log4js/-/log4js-6.3.0.tgz#10dfafbb434351a3e30277a00b9879446f715bcb" - integrity sha512-Mc8jNuSFImQUIateBFwdOQcmC6Q5maU0VVvdC2R6XMb66/VnT+7WS4D/0EeNMZu1YODmJe5NIn2XftCzEocUgw== - dependencies: - date-format "^3.0.0" - debug "^4.1.1" - flatted "^2.0.1" - rfdc "^1.1.4" - streamroller "^2.2.4" - -lru-cache@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" - integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== - dependencies: - yallist "^4.0.0" - -make-dir@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-3.1.0.tgz#415e967046b3a7f1d185277d84aa58203726a13f" - integrity sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw== - dependencies: - semver "^6.0.0" - -make-error@1.x: - version "1.3.6" - resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" - integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== - -makeerror@1.0.x: - version "1.0.11" - resolved "https://registry.yarnpkg.com/makeerror/-/makeerror-1.0.11.tgz#e01a5c9109f2af79660e4e8b9587790184f5a96c" - integrity sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw= - dependencies: - tmpl "1.0.x" - -marked@^2.1.3: - version "2.1.3" - resolved "https://registry.yarnpkg.com/marked/-/marked-2.1.3.tgz#bd017cef6431724fd4b27e0657f5ceb14bff3753" - integrity sha512-/Q+7MGzaETqifOMWYEA7HVMaZb4XbcRfaOzcSsHZEith83KGlvaSG33u0SKu89Mj5h+T8V2hM+8O45Qc5XTgwA== - -merge-stream@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" - integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== - -merge2@^1.3.0: - version "1.4.1" - resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae" - integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg== - -micromatch@^4.0.4: - version "4.0.4" - resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.4.tgz#896d519dfe9db25fce94ceb7a500919bf881ebf9" - integrity sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg== - dependencies: - braces "^3.0.1" - picomatch "^2.2.3" - -mime-db@1.48.0: - version "1.48.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.48.0.tgz#e35b31045dd7eada3aaad537ed88a33afbef2d1d" - integrity sha512-FM3QwxV+TnZYQ2aRqhlKBMHxk10lTbMt3bBkMAp54ddrNeVSfcQYOOKuGuy3Ddrm38I04If834fOUSq1yzslJQ== - -mime-types@^2.1.12: - version "2.1.31" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.31.tgz#a00d76b74317c61f9c2db2218b8e9f8e9c5c9e6b" - integrity sha512-XGZnNzm3QvgKxa8dpzyhFTHmpP3l5YNusmne07VUOXxou9CqUqYa/HBy124RqtVh/O2pECas/MOcsDgpilPOPg== - dependencies: - mime-db "1.48.0" - -mimic-fn@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" - integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== - -mimic-response@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" - integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== - -minimatch@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" - integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== - dependencies: - brace-expansion "^1.1.7" - -minimist@^1.2.0, minimist@^1.2.5: - version "1.2.5" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602" - integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw== - -minipass@^3.0.0: - version "3.1.3" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.1.3.tgz#7d42ff1f39635482e15f9cdb53184deebd5815fd" - integrity sha512-Mgd2GdMVzY+x3IJ+oHnVM+KG3lA5c8tnabyJKmHSaG2kAGpudxuOf8ToDkhumF7UzME7DecbQE9uOZhNm7PuJg== - dependencies: - yallist "^4.0.0" - -minizlib@^2.1.1: - version "2.1.2" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.2.tgz#e90d3466ba209b932451508a11ce3d3632145931" - integrity sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg== - dependencies: - minipass "^3.0.0" - yallist "^4.0.0" - -mkdirp@^0.5.1: - version "0.5.5" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" - integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== - dependencies: - minimist "^1.2.5" - -mkdirp@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" - integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== - -ms@2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" - integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== - -msgpack-lite@^0.1.26: - version "0.1.26" - resolved "https://registry.yarnpkg.com/msgpack-lite/-/msgpack-lite-0.1.26.tgz#dd3c50b26f059f25e7edee3644418358e2a9ad89" - integrity sha1-3TxQsm8FnyXn7e42REGDWOKprYk= - dependencies: - event-lite "^0.1.1" - ieee754 "^1.1.8" - int64-buffer "^0.1.9" - isarray "^1.0.0" - -natural-compare@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" - integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc= - -node-int64@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b" - integrity sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs= - -node-modules-regexp@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz#8d9dbe28964a4ac5712e9131642107c71e90ec40" - integrity sha1-jZ2+KJZKSsVxLpExZCEHxx6Q7EA= - -node-releases@^1.1.71: - version "1.1.73" - resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-1.1.73.tgz#dd4e81ddd5277ff846b80b52bb40c49edf7a7b20" - integrity sha512-uW7fodD6pyW2FZNZnp/Z3hvWKeEW1Y8R1+1CnErE8cXFXzl5blBOoVB41CvMer6P6Q0S5FXDwcHgFd1Wj0U9zg== - -normalize-path@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" - integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== - -npm-run-path@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea" - integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw== - dependencies: - path-key "^3.0.0" - -nwsapi@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/nwsapi/-/nwsapi-2.2.0.tgz#204879a9e3d068ff2a55139c2c772780681a38b7" - integrity sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ== - -once@^1.3.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" - integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= - dependencies: - wrappy "1" - -onetime@^5.1.2: - version "5.1.2" - resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.2.tgz#d0e96ebb56b07476df1dd9c4806e5237985ca45e" - integrity sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg== - dependencies: - mimic-fn "^2.1.0" - -optionator@^0.8.1: - version "0.8.3" - resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.3.tgz#84fa1d036fe9d3c7e21d99884b601167ec8fb495" - integrity sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA== - dependencies: - deep-is "~0.1.3" - fast-levenshtein "~2.0.6" - levn "~0.3.0" - prelude-ls "~1.1.2" - type-check "~0.3.2" - word-wrap "~1.2.3" - -optionator@^0.9.1: - version "0.9.1" - resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.1.tgz#4f236a6373dae0566a6d43e1326674f50c291499" - integrity sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw== - dependencies: - deep-is "^0.1.3" - fast-levenshtein "^2.0.6" - levn "^0.4.1" - prelude-ls "^1.2.1" - type-check "^0.4.0" - word-wrap "^1.2.3" - -p-each-series@^2.1.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/p-each-series/-/p-each-series-2.2.0.tgz#105ab0357ce72b202a8a8b94933672657b5e2a9a" - integrity sha512-ycIL2+1V32th+8scbpTvyHNaHe02z0sjgh91XXjAk+ZeXoPN4Z46DVUnzdso0aX4KckKw0FNNFHdjZ2UsZvxiA== - -p-limit@^2.2.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" - integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== - dependencies: - p-try "^2.0.0" - -p-locate@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" - integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== - dependencies: - p-limit "^2.2.0" - -p-try@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" - integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== - -parent-module@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/parent-module/-/parent-module-1.0.1.tgz#691d2709e78c79fae3a156622452d00762caaaa2" - integrity sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g== - dependencies: - callsites "^3.0.0" - -parse5@6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/parse5/-/parse5-6.0.1.tgz#e1a1c085c569b3dc08321184f19a39cc27f7c30b" - integrity sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw== - -path-exists@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" - integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== - -path-is-absolute@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" - integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= - -path-key@^3.0.0, path-key@^3.1.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" - integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== - -path-parse@^1.0.6: - version "1.0.7" - resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" - integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== - -path-type@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" - integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== - -picomatch@^2.0.4, picomatch@^2.2.3: - version "2.3.0" - resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.0.tgz#f1f061de8f6a4bf022892e2d128234fb98302972" - integrity sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw== - -pirates@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.1.tgz#643a92caf894566f91b2b986d2c66950a8e2fb87" - integrity sha512-WuNqLTbMI3tmfef2TKxlQmAiLHKtFhlsCZnPIpuv2Ow0RDVO8lfy1Opf4NUzlMXLjPl+Men7AuVdX6TA+s+uGA== - dependencies: - node-modules-regexp "^1.0.0" - -pkg-dir@^4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-4.2.0.tgz#f099133df7ede422e81d1d8448270eeb3e4261f3" - integrity sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ== - dependencies: - find-up "^4.0.0" - -prelude-ls@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396" - integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== - -prelude-ls@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" - integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= - -pretty-format@^27.0.0, pretty-format@^27.0.6: - version "27.0.6" - resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-27.0.6.tgz#ab770c47b2c6f893a21aefc57b75da63ef49a11f" - integrity sha512-8tGD7gBIENgzqA+UBzObyWqQ5B778VIFZA/S66cclyd5YkFLYs2Js7gxDKf0MXtTc9zcS7t1xhdfcElJ3YIvkQ== - dependencies: - "@jest/types" "^27.0.6" - ansi-regex "^5.0.0" - ansi-styles "^5.0.0" - react-is "^17.0.1" - -progress@^2.0.0: - version "2.0.3" - resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.3.tgz#7e8cf8d8f5b8f239c1bc68beb4eb78567d572ef8" - integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== - -prompts@^2.0.1: - version "2.4.1" - resolved "https://registry.yarnpkg.com/prompts/-/prompts-2.4.1.tgz#befd3b1195ba052f9fd2fde8a486c4e82ee77f61" - integrity sha512-EQyfIuO2hPDsX1L/blblV+H7I0knhgAd82cVneCwcdND9B8AuCDuRcBH6yIcG4dFzlOUqbazQqwGjx5xmsNLuQ== - dependencies: - kleur "^3.0.3" - sisteransi "^1.0.5" - -psl@^1.1.33: - version "1.8.0" - resolved "https://registry.yarnpkg.com/psl/-/psl-1.8.0.tgz#9326f8bcfb013adcc005fdff056acce020e51c24" - integrity sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ== - -punycode@^2.1.0, punycode@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec" - integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== - -queue-microtask@^1.2.2: - version "1.2.3" - resolved "https://registry.yarnpkg.com/queue-microtask/-/queue-microtask-1.2.3.tgz#4929228bbc724dfac43e0efb058caf7b6cfb6243" - integrity sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A== - -rc@^1.2.8: - version "1.2.8" - resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.8.tgz#cd924bf5200a075b83c188cd6b9e211b7fc0d3ed" - integrity sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw== - dependencies: - deep-extend "^0.6.0" - ini "~1.3.0" - minimist "^1.2.0" - strip-json-comments "~2.0.1" - -react-is@^17.0.1: - version "17.0.2" - resolved "https://registry.yarnpkg.com/react-is/-/react-is-17.0.2.tgz#e691d4a8e9c789365655539ab372762b0efb54f0" - integrity sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w== - -regexpp@^3.1.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.2.0.tgz#0425a2768d8f23bad70ca4b90461fa2f1213e1b2" - integrity sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg== - -regextras@^0.7.1: - version "0.7.1" - resolved "https://registry.yarnpkg.com/regextras/-/regextras-0.7.1.tgz#be95719d5f43f9ef0b9fa07ad89b7c606995a3b2" - integrity sha512-9YXf6xtW+qzQ+hcMQXx95MOvfqXFgsKDZodX3qZB0x2n5Z94ioetIITsBtvJbiOyxa/6s9AtyweBLCdPmPko/w== - -require-directory@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" - integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= - -require-from-string@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.2.tgz#89a7fdd938261267318eafe14f9c32e598c36909" - integrity sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw== - -resolve-cwd@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz#0f0075f1bb2544766cf73ba6a6e2adfebcb13f2d" - integrity sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg== - dependencies: - resolve-from "^5.0.0" - -resolve-from@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" - integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g== - -resolve-from@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" - integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== - -resolve@^1.20.0: - version "1.20.0" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.20.0.tgz#629a013fb3f70755d6f0b7935cc1c2c5378b1975" - integrity sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A== - dependencies: - is-core-module "^2.2.0" - path-parse "^1.0.6" - -reusify@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76" - integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw== - -rfc-3986@1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/rfc-3986/-/rfc-3986-1.0.1.tgz#eeeb88342fadbe8027c0f36ada921a13e6f96206" - integrity sha1-7uuINC+tvoAnwPNq2pIaE+b5YgY= - -rfdc@^1.1.4: - version "1.3.0" - resolved "https://registry.yarnpkg.com/rfdc/-/rfdc-1.3.0.tgz#d0b7c441ab2720d05dc4cf26e01c89631d9da08b" - integrity sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA== - -rimraf@^3.0.0, rimraf@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a" - integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA== - dependencies: - glob "^7.1.3" - -run-parallel@^1.1.9: - version "1.2.0" - resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.2.0.tgz#66d1368da7bdf921eb9d95bd1a9229e7f21a43ee" - integrity sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA== - dependencies: - queue-microtask "^1.2.2" - -safe-buffer@5.1.2, safe-buffer@~5.1.1: - version "5.1.2" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" - integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== - -"safer-buffer@>= 2.1.2 < 3": - version "2.1.2" - resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" - integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== - -saxes@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/saxes/-/saxes-5.0.1.tgz#eebab953fa3b7608dbe94e5dadb15c888fa6696d" - integrity sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw== - dependencies: - xmlchars "^2.2.0" - -semver@7.x, semver@^7.2.1, semver@^7.3.2, semver@^7.3.4, semver@^7.3.5: - version "7.3.5" - resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.5.tgz#0b621c879348d8998e4b0e4be94b3f12e6018ef7" - integrity sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ== - dependencies: - lru-cache "^6.0.0" - -semver@^6.0.0, semver@^6.3.0: - version "6.3.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" - integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== - -shebang-command@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" - integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== - dependencies: - shebang-regex "^3.0.0" - -shebang-regex@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" - integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== - -signal-exit@^3.0.2, signal-exit@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.3.tgz#a1410c2edd8f077b08b4e253c8eacfcaf057461c" - integrity sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA== - -sisteransi@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/sisteransi/-/sisteransi-1.0.5.tgz#134d681297756437cc05ca01370d3a7a571075ed" - integrity sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg== - -slash@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" - integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== - -slice-ansi@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-4.0.0.tgz#500e8dd0fd55b05815086255b3195adf2a45fe6b" - integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ== - dependencies: - ansi-styles "^4.0.0" - astral-regex "^2.0.0" - is-fullwidth-code-point "^3.0.0" - -source-map-support@^0.5.6: - version "0.5.19" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61" - integrity sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw== - dependencies: - buffer-from "^1.0.0" - source-map "^0.6.0" - -source-map@^0.5.0: - version "0.5.7" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" - integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= - -source-map@^0.6.0, source-map@^0.6.1, source-map@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" - integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== - -source-map@^0.7.3: - version "0.7.3" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.7.3.tgz#5302f8169031735226544092e64981f751750383" - integrity sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ== - -spdx-exceptions@^2.1.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz#3f28ce1a77a00372683eade4a433183527a2163d" - integrity sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A== - -spdx-expression-parse@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz#cf70f50482eefdc98e3ce0a6833e4a53ceeba679" - integrity sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q== - dependencies: - spdx-exceptions "^2.1.0" - spdx-license-ids "^3.0.0" - -spdx-license-ids@^3.0.0: - version "3.0.9" - resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.9.tgz#8a595135def9592bda69709474f1cbeea7c2467f" - integrity sha512-Ki212dKK4ogX+xDo4CtOZBVIwhsKBEfsEEcwmJfLQzirgc2jIWdzg40Unxz/HzEUqM1WFzVlQSMF9kZZ2HboLQ== - -sprintf-js@~1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" - integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= - -stack-utils@^2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/stack-utils/-/stack-utils-2.0.3.tgz#cd5f030126ff116b78ccb3c027fe302713b61277" - integrity sha512-gL//fkxfWUsIlFL2Tl42Cl6+HFALEaB1FU76I/Fy+oZjRreP7OPMXFlGbxM7NQsI0ZpUfw76sHnv0WNYuTb7Iw== - dependencies: - escape-string-regexp "^2.0.0" - -streamroller@^2.2.4: - version "2.2.4" - resolved "https://registry.yarnpkg.com/streamroller/-/streamroller-2.2.4.tgz#c198ced42db94086a6193608187ce80a5f2b0e53" - integrity sha512-OG79qm3AujAM9ImoqgWEY1xG4HX+Lw+yY6qZj9R1K2mhF5bEmQ849wvrb+4vt4jLMLzwXttJlQbOdPOQVRv7DQ== - dependencies: - date-format "^2.1.0" - debug "^4.1.1" - fs-extra "^8.1.0" - -string-length@^4.0.1: - version "4.0.2" - resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a" - integrity sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ== - dependencies: - char-regex "^1.0.2" - strip-ansi "^6.0.0" - -string-width@^4.1.0, string-width@^4.2.0: - version "4.2.2" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.2.tgz#dafd4f9559a7585cfba529c6a0a4f73488ebd4c5" - integrity sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA== - dependencies: - emoji-regex "^8.0.0" - is-fullwidth-code-point "^3.0.0" - strip-ansi "^6.0.0" - -strip-ansi@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.0.tgz#0b1571dd7669ccd4f3e06e14ef1eed26225ae532" - integrity sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w== - dependencies: - ansi-regex "^5.0.0" - -strip-bom@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-4.0.0.tgz#9c3505c1db45bcedca3d9cf7a16f5c5aa3901878" - integrity sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w== - -strip-final-newline@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad" - integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA== - -strip-json-comments@^3.1.0, strip-json-comments@^3.1.1: - version "3.1.1" - resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" - integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== - -strip-json-comments@~2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" - integrity sha1-PFMZQukIwml8DsNEhYwobHygpgo= - -supports-color@^5.3.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" - integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== - dependencies: - has-flag "^3.0.0" - -supports-color@^7.0.0, supports-color@^7.1.0: - version "7.2.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da" - integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== - dependencies: - has-flag "^4.0.0" - -supports-color@^8.0.0: - version "8.1.1" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" - integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q== - dependencies: - has-flag "^4.0.0" - -supports-hyperlinks@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/supports-hyperlinks/-/supports-hyperlinks-2.2.0.tgz#4f77b42488765891774b70c79babd87f9bd594bb" - integrity sha512-6sXEzV5+I5j8Bmq9/vUphGRM/RJNT9SCURJLjwfOg51heRtguGWDzcaBlgAzKhQa0EVNpPEKzQuBwZ8S8WaCeQ== - dependencies: - has-flag "^4.0.0" - supports-color "^7.0.0" - -symbol-tree@^3.2.4: - version "3.2.4" - resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" - integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw== - -table@^6.0.9: - version "6.7.1" - resolved "https://registry.yarnpkg.com/table/-/table-6.7.1.tgz#ee05592b7143831a8c94f3cee6aae4c1ccef33e2" - integrity sha512-ZGum47Yi6KOOFDE8m223td53ath2enHcYLgOCjGr5ngu8bdIARQk6mN/wRMv4yMRcHnCSnHbCEha4sobQx5yWg== - dependencies: - ajv "^8.0.1" - lodash.clonedeep "^4.5.0" - lodash.truncate "^4.4.2" - slice-ansi "^4.0.0" - string-width "^4.2.0" - strip-ansi "^6.0.0" - -tar@^6.1.9: - version "6.1.11" - resolved "https://registry.yarnpkg.com/tar/-/tar-6.1.11.tgz#6760a38f003afa1b2ffd0ffe9e9abbd0eab3d621" - integrity sha512-an/KZQzQUkZCkuoAA64hM92X0Urb6VpRhAFllDzz44U2mcD5scmT3zBc4VgVpkugF580+DQn8eAFSyoQt0tznA== - dependencies: - chownr "^2.0.0" - fs-minipass "^2.0.0" - minipass "^3.0.0" - minizlib "^2.1.1" - mkdirp "^1.0.3" - yallist "^4.0.0" - -terminal-link@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/terminal-link/-/terminal-link-2.1.1.tgz#14a64a27ab3c0df933ea546fba55f2d078edc994" - integrity sha512-un0FmiRUQNr5PJqy9kP7c40F5BOfpGlYTrxonDChEZB7pzZxRNp/bt+ymiy9/npwXya9KH99nJ/GXFIiUkYGFQ== - dependencies: - ansi-escapes "^4.2.1" - supports-hyperlinks "^2.0.0" - -test-exclude@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-6.0.0.tgz#04a8698661d805ea6fa293b6cb9e63ac044ef15e" - integrity sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w== - dependencies: - "@istanbuljs/schema" "^0.1.2" - glob "^7.1.4" - minimatch "^3.0.4" - -text-table@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" - integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ= - -throat@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/throat/-/throat-6.0.1.tgz#d514fedad95740c12c2d7fc70ea863eb51ade375" - integrity sha512-8hmiGIJMDlwjg7dlJ4yKGLK8EsYqKgPWbG3b4wjJddKNwc7N7Dpn08Df4szr/sZdMVeOstrdYSsqzX6BYbcB+w== - -tmpl@1.0.x: - version "1.0.4" - resolved "https://registry.yarnpkg.com/tmpl/-/tmpl-1.0.4.tgz#23640dd7b42d00433911140820e5cf440e521dd1" - integrity sha1-I2QN17QtAEM5ERQIIOXPRA5SHdE= - -to-fast-properties@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-2.0.0.tgz#dc5e698cbd079265bc73e0377681a4e4e83f616e" - integrity sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4= - -to-regex-range@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" - integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== - dependencies: - is-number "^7.0.0" - -tough-cookie@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-4.0.0.tgz#d822234eeca882f991f0f908824ad2622ddbece4" - integrity sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg== - dependencies: - psl "^1.1.33" - punycode "^2.1.1" - universalify "^0.1.2" - -tr46@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/tr46/-/tr46-2.1.0.tgz#fa87aa81ca5d5941da8cbf1f9b749dc969a4e240" - integrity sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw== - dependencies: - punycode "^2.1.1" - -"traverse@>=0.3.0 <0.4": - version "0.3.9" - resolved "https://registry.yarnpkg.com/traverse/-/traverse-0.3.9.tgz#717b8f220cc0bb7b44e40514c22b2e8bbc70d8b9" - integrity sha1-cXuPIgzAu3tE5AUUwisui7xw2Lk= - -ts-jest@^27.0.5: - version "27.0.5" - resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-27.0.5.tgz#0b0604e2271167ec43c12a69770f0bb65ad1b750" - integrity sha512-lIJApzfTaSSbtlksfFNHkWOzLJuuSm4faFAfo5kvzOiRAuoN4/eKxVJ2zEAho8aecE04qX6K1pAzfH5QHL1/8w== - dependencies: - bs-logger "0.x" - fast-json-stable-stringify "2.x" - jest-util "^27.0.0" - json5 "2.x" - lodash "4.x" - make-error "1.x" - semver "7.x" - yargs-parser "20.x" - -tslib@^1.8.1: - version "1.14.1" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" - integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== - -tslib@^2.0.3: - version "2.3.0" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.0.tgz#803b8cdab3e12ba581a4ca41c8839bbb0dacb09e" - integrity sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg== - -tsutils@^3.21.0: - version "3.21.0" - resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.21.0.tgz#b48717d394cea6c1e096983eed58e9d61715b623" - integrity sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA== - dependencies: - tslib "^1.8.1" - -type-check@^0.4.0, type-check@~0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.4.0.tgz#07b8203bfa7056c0657050e3ccd2c37730bab8f1" - integrity sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew== - dependencies: - prelude-ls "^1.2.1" - -type-check@~0.3.2: - version "0.3.2" - resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" - integrity sha1-WITKtRLPHTVeP7eE8wgEsrUg23I= - dependencies: - prelude-ls "~1.1.2" - -type-detect@4.0.8: - version "4.0.8" - resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" - integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== - -type-fest@^0.20.2: - version "0.20.2" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4" - integrity sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ== - -type-fest@^0.21.3: - version "0.21.3" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.21.3.tgz#d260a24b0198436e133fa26a524a6d65fa3b2e37" - integrity sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w== - -typedarray-to-buffer@^3.1.5: - version "3.1.5" - resolved "https://registry.yarnpkg.com/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz#a97ee7a9ff42691b9f783ff1bc5112fe3fca9080" - integrity sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q== - dependencies: - is-typedarray "^1.0.0" - -typescript@^4.3.5: - version "4.3.5" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.3.5.tgz#4d1c37cc16e893973c45a06886b7113234f119f4" - integrity sha512-DqQgihaQ9cUrskJo9kIyW/+g0Vxsk8cDtZ52a3NGh0YNTfpUSArXSohyUGnvbPazEPLu398C0UxmKSOrPumUzA== - -universalify@^0.1.0, universalify@^0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" - integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg== - -universalify@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/universalify/-/universalify-2.0.0.tgz#75a4984efedc4b08975c5aeb73f530d02df25717" - integrity sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ== - -unzip-stream@^0.3.1: - version "0.3.1" - resolved "https://registry.yarnpkg.com/unzip-stream/-/unzip-stream-0.3.1.tgz#2333b5cd035d29db86fb701ca212cf8517400083" - integrity sha512-RzaGXLNt+CW+T41h1zl6pGz3EaeVhYlK+rdAap+7DxW5kqsqePO8kRtWPaCiVqdhZc86EctSPVYNix30YOMzmw== - dependencies: - binary "^0.3.0" - mkdirp "^0.5.1" - -uri-js@^4.2.2: - version "4.4.1" - resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e" - integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg== - dependencies: - punycode "^2.1.0" - -uuid@^7.0.3: - version "7.0.3" - resolved "https://registry.yarnpkg.com/uuid/-/uuid-7.0.3.tgz#c5c9f2c8cf25dc0a372c4df1441c41f5bd0c680b" - integrity sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg== - -v8-compile-cache@^2.0.3: - version "2.3.0" - resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz#2de19618c66dc247dcfb6f99338035d8245a2cee" - integrity sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA== - -v8-to-istanbul@^8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/v8-to-istanbul/-/v8-to-istanbul-8.0.0.tgz#4229f2a99e367f3f018fa1d5c2b8ec684667c69c" - integrity sha512-LkmXi8UUNxnCC+JlH7/fsfsKr5AU110l+SYGJimWNkWhxbN5EyeOtm1MJ0hhvqMMOhGwBj1Fp70Yv9i+hX0QAg== - dependencies: - "@types/istanbul-lib-coverage" "^2.0.1" - convert-source-map "^1.6.0" - source-map "^0.7.3" - -vscode-jsonrpc@6.0.0, vscode-jsonrpc@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-6.0.0.tgz#108bdb09b4400705176b957ceca9e0880e9b6d4e" - integrity sha512-wnJA4BnEjOSyFMvjZdpiOwhSq9uDoK8e/kpRJDTaMYzwlkrhG1fwDIZI94CLsLzlCK5cIbMMtFlJlfR57Lavmg== - -vscode-languageserver-protocol@3.16.0, vscode-languageserver-protocol@^3.16.0: - version "3.16.0" - resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.16.0.tgz#34135b61a9091db972188a07d337406a3cdbe821" - integrity sha512-sdeUoAawceQdgIfTI+sdcwkiK2KU+2cbEYA0agzM2uqaUy2UpnnGHtWTHVEtS0ES4zHU0eMFRGN+oQgDxlD66A== - dependencies: - vscode-jsonrpc "6.0.0" - vscode-languageserver-types "3.16.0" - -vscode-languageserver-textdocument@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.1.tgz#178168e87efad6171b372add1dea34f53e5d330f" - integrity sha512-UIcJDjX7IFkck7cSkNNyzIz5FyvpQfY7sdzVy+wkKN/BLaD4DQ0ppXQrKePomCxTS7RrolK1I0pey0bG9eh8dA== - -vscode-languageserver-types@3.16.0, vscode-languageserver-types@^3.16.0: - version "3.16.0" - resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.16.0.tgz#ecf393fc121ec6974b2da3efb3155644c514e247" - integrity sha512-k8luDIWJWyenLc5ToFQQMaSrqCHiLwyKPHKPQZ5zz21vM+vIVUSvsRpcbiECH4WR88K2XZqc4ScRcZ7nk/jbeA== - -vscode-languageserver@7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/vscode-languageserver/-/vscode-languageserver-7.0.0.tgz#49b068c87cfcca93a356969d20f5d9bdd501c6b0" - integrity sha512-60HTx5ID+fLRcgdHfmz0LDZAXYEV68fzwG0JWwEPBode9NuMYTIxuYXPg4ngO8i8+Ou0lM7y6GzaYWbiDL0drw== - dependencies: - vscode-languageserver-protocol "3.16.0" - -vscode-uri@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-2.1.2.tgz#c8d40de93eb57af31f3c715dd650e2ca2c096f1c" - integrity sha512-8TEXQxlldWAuIODdukIb+TR5s+9Ds40eSJrw+1iDDA9IFORPjMELarNQE3myz5XIkWWpdprmJjm1/SxMlWOC8A== - -w3c-hr-time@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz#0a89cdf5cc15822df9c360543676963e0cc308cd" - integrity sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ== - dependencies: - browser-process-hrtime "^1.0.0" - -w3c-xmlserializer@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz#3e7104a05b75146cc60f564380b7f683acf1020a" - integrity sha512-4tzD0mF8iSiMiNs30BiLO3EpfGLZUT2MSX/G+o7ZywDzliWQ3OPtTZ0PTC3B3ca1UAf4cJMHB+2Bf56EriJuRA== - dependencies: - xml-name-validator "^3.0.0" - -walker@^1.0.7: - version "1.0.7" - resolved "https://registry.yarnpkg.com/walker/-/walker-1.0.7.tgz#2f7f9b8fd10d677262b18a884e28d19618e028fb" - integrity sha1-L3+bj9ENZ3JisYqITijRlhjgKPs= - dependencies: - makeerror "1.0.x" - -webidl-conversions@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-5.0.0.tgz#ae59c8a00b121543a2acc65c0434f57b0fc11aff" - integrity sha512-VlZwKPCkYKxQgeSbH5EyngOmRp7Ww7I9rQLERETtf5ofd9pGeswWiOtogpEO850jziPRarreGxn5QIiTqpb2wA== - -webidl-conversions@^6.1.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-6.1.0.tgz#9111b4d7ea80acd40f5270d666621afa78b69514" - integrity sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w== - -whatwg-encoding@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz#5abacf777c32166a51d085d6b4f3e7d27113ddb0" - integrity sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw== - dependencies: - iconv-lite "0.4.24" - -whatwg-mimetype@^2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz#3d4b1e0312d2079879f826aff18dbeeca5960fbf" - integrity sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g== - -whatwg-url@^8.0.0, whatwg-url@^8.5.0: - version "8.7.0" - resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-8.7.0.tgz#656a78e510ff8f3937bc0bcbe9f5c0ac35941b77" - integrity sha512-gAojqb/m9Q8a5IV96E3fHJM70AzCkgt4uXYX2O7EmuyOnLrViCQlsEBmF9UQIu3/aeAIp2U17rtbpZWNntQqdg== - dependencies: - lodash "^4.7.0" - tr46 "^2.1.0" - webidl-conversions "^6.1.0" - -which@^2.0.1, which@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" - integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== - dependencies: - isexe "^2.0.0" - -word-wrap@^1.2.3, word-wrap@~1.2.3: - version "1.2.3" - resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" - integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== - -wrap-ansi@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" - integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== - dependencies: - ansi-styles "^4.0.0" - string-width "^4.1.0" - strip-ansi "^6.0.0" - -wrappy@1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" - integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= - -write-file-atomic@^3.0.0: - version "3.0.3" - resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-3.0.3.tgz#56bd5c5a5c70481cd19c571bd39ab965a5de56e8" - integrity sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q== - dependencies: - imurmurhash "^0.1.4" - is-typedarray "^1.0.0" - signal-exit "^3.0.2" - typedarray-to-buffer "^3.1.5" - -ws@^7.4.6: - version "7.5.3" - resolved "https://registry.yarnpkg.com/ws/-/ws-7.5.3.tgz#160835b63c7d97bfab418fc1b8a9fced2ac01a74" - integrity sha512-kQ/dHIzuLrS6Je9+uv81ueZomEwH0qVYstcAQ4/Z93K8zeko9gtAbttJWzoC5ukqXY1PpoouV3+VSOqEAFt5wg== - -xml-name-validator@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-3.0.0.tgz#6ae73e06de4d8c6e47f9fb181f78d648ad457c6a" - integrity sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw== - -xmlchars@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/xmlchars/-/xmlchars-2.2.0.tgz#060fe1bcb7f9c76fe2a17db86a9bc3ab894210cb" - integrity sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw== - -y18n@^5.0.5: - version "5.0.8" - resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" - integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== - -yallist@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" - integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== - -yargs-parser@20.x, yargs-parser@^20.2.2: - version "20.2.9" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee" - integrity sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w== - -yargs@^16.0.3: - version "16.2.0" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-16.2.0.tgz#1c82bf0f6b6a66eafce7ef30e376f49a12477f66" - integrity sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw== - dependencies: - cliui "^7.0.2" - escalade "^3.1.1" - get-caller-file "^2.0.5" - require-directory "^2.1.1" - string-width "^4.2.0" - y18n "^5.0.5" - yargs-parser "^20.2.2"