Repository: josa42/coc-lua
Branch: main
Commit: ceedce75a82b
Files: 25
Total size: 61.2 KB
Directory structure:
gitextract_0h2b6rij/
├── .eslintignore
├── .eslintrc
├── .github/
│ └── workflows/
│ ├── main.yml
│ ├── publish.yml
│ └── update-settings.yml
├── .gitignore
├── .node-version
├── .npmignore
├── .npmrc
├── .vim/
│ └── coc-settings.json
├── LICENSE
├── README.md
├── jest.config.js
├── package.json
├── scripts/
│ ├── nvim.sh
│ └── update-settings.js
├── src/
│ ├── __mocks__/
│ │ └── coc.nvim.ts
│ ├── commands.ts
│ ├── extension.ts
│ └── utils/
│ ├── config.ts
│ ├── db.ts
│ ├── installer.test.ts
│ ├── installer.ts
│ └── tools.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .eslintignore
================================================
/lib
node_module
================================================
FILE: .eslintrc
================================================
{
"root": true,
"extends": "josa-typescript",
"env": {
"jest": true
}
}
================================================
FILE: .github/workflows/main.yml
================================================
name: Main
on: push
jobs:
test:
strategy:
fail-fast: false
matrix:
node: [ 16, 18 ]
os:
- ubuntu-latest
- macos-latest
# - windows-latest
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with: { node-version: '${{ matrix.node }}' }
- run: npm ci
- run: npm run build
- run: npm run test --color
- run: npm run lint
================================================
FILE: .github/workflows/publish.yml
================================================
name: Publish
on:
schedule:
- cron: '5 0 * * *'
workflow_dispatch:
inputs:
version:
type: choice
description: ''
default: patch
options:
- major
- minor
- patch
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: josa42/actions/npm-publish@main
with:
version: '${{ inputs.version }}'
npm-token: '${{ secrets.NPM_TOKEN }}'
================================================
FILE: .github/workflows/update-settings.yml
================================================
name: Settings
on:
schedule:
- cron: '0 0 * * *'
workflow_dispatch:
jobs:
update:
runs-on: ubuntu-latest
steps:
- uses: josa42/actions/update@main
with:
run-update: |
node ./scripts/update-settings.js
run-tests: |
npm ci
npm run build
npm run lint
npm run test
================================================
FILE: .gitignore
================================================
lib
node_modules
yarn-error.log
/.tmp
.DS_Store
================================================
FILE: .node-version
================================================
v18
================================================
FILE: .npmignore
================================================
*.map
*.ts
/.eslintignore
/.eslintrc
/.github/
/.node-version
/.vim/
/lib/**/*.test.js
/lib/__mocks__/
/scripts/
/src/
/tsconfig.json
/tslint.json
================================================
FILE: .npmrc
================================================
legacy-peer-deps=true
================================================
FILE: .vim/coc-settings.json
================================================
{
"coc.preferences.formatOnSaveFiletypes": ["javascript", "typescript", "json"]
}
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2019 Josa Gesell
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.
================================================
FILE: README.md
================================================
# coc-lua

--------------------------------------------------------------------------------
Lua language server extension using [`LuaLS/lua-language-server`](https://github.com/LuaLS/lua-language-server)
for [`coc.nvim`](https://github.com/neoclide/coc.nvim).
## Install
In your vim/neovim, run command:
```
:CocInstall coc-lua
```
## Features
See
- [`LuaLS/lua-language-server`](https://github.com/LuaLS/lua-language-server)
## Commands
| Key | Description |
|-------------------|-------------------------|
| **`lua.version`** | Print extension version |
| **`lua.update`** | Update language server |
## Settings
| Key | Description | Default |
|------------------|------------------------------------------------|---------|
| **`lua.enable`** | set to `false` to disable lua language server. | `true` |
Trigger completion in `coc-settings.json` to get complete list.
### LuaLS/lua-language-server
| Key | Description | Default |
|-----|-------------|---------|
| **`Lua.addonManager.enable`** | Set the on/off state for the addon manager. | true |
| **`Lua.codeLens.enable`** | Enable code lens. | |
| **`Lua.completion.autoRequire`** | When the input looks like a file name, automatically `require` this file. | true |
| **`Lua.completion.callSnippet`** | Shows function call snippets. | "Disable" |
| **`Lua.completion.displayContext`** | Previewing the relevant code snippet of the suggestion may help you understand the usage of the suggestion. The number set indicates the number of intercepted lines in the code fragment. If it is set to `0`, this feature can be disabled. | |
| **`Lua.completion.enable`** | Enable completion. | true |
| **`Lua.completion.keywordSnippet`** | Shows keyword syntax snippets. | "Replace" |
| **`Lua.completion.postfix`** | The symbol used to trigger the postfix suggestion. | "@" |
| **`Lua.completion.requireSeparator`** | The separator used when `require`. | "." |
| **`Lua.completion.showParams`** | Display parameters in completion list. When the function has multiple definitions, they will be displayed separately. | true |
| **`Lua.completion.showWord`** | Show contextual words in suggestions. | "Fallback" |
| **`Lua.completion.workspaceWord`** | Whether the displayed context word contains the content of other files in the workspace. | true |
| **`Lua.diagnostics.disable`** | Disabled diagnostic (Use code in hover brackets). | [] |
| **`Lua.diagnostics.disableScheme`** | Do not diagnose Lua files that use the following scheme. | ["git"] |
| **`Lua.diagnostics.enable`** | Enable diagnostics. | true |
| **`Lua.diagnostics.globals`** | Defined global variables. | [] |
| **`Lua.diagnostics.ignoredFiles`** | How to diagnose ignored files. | "Opened" |
| **`Lua.diagnostics.libraryFiles`** | How to diagnose files loaded via `Lua.workspace.library`. | "Opened" |
| **`Lua.diagnostics.unusedLocalExclude`** | Do not diagnose `unused-local` when the variable name matches the following pattern. | [] |
| **`Lua.diagnostics.workspaceDelay`** | Latency (milliseconds) for workspace diagnostics. | 3000 |
| **`Lua.diagnostics.workspaceEvent`** | Set the time to trigger workspace diagnostics. | "OnSave" |
| **`Lua.diagnostics.workspaceRate`** | Workspace diagnostics run rate (%). Decreasing this value reduces CPU usage, but also reduces the speed of workspace diagnostics. The diagnosis of the file you are currently editing is always done at full speed and is not affected by this setting. | 100 |
| **`Lua.doc.packageName`** | Treat specific field names as package, e.g. `m_*` means `XXX.m_id` and `XXX.m_type` are package, witch can only be accessed in the file where the definition is located. | [] |
| **`Lua.doc.privateName`** | Treat specific field names as private, e.g. `m_*` means `XXX.m_id` and `XXX.m_type` are private, witch can only be accessed in the class where the definition is located. | [] |
| **`Lua.doc.protectedName`** | Treat specific field names as protected, e.g. `m_*` means `XXX.m_id` and `XXX.m_type` are protected, witch can only be accessed in the class where the definition is located and its subclasses. | [] |
| **`Lua.format.defaultConfig`** | The default format configuration. Has a lower priority than `.editorconfig` file in the workspace.
Read [formatter docs](https://github.com/CppCXY/EmmyLuaCodeStyle/tree/master/docs) to learn usage. | {} |
| **`Lua.format.enable`** | Enable code formatter. | true |
| **`Lua.hint.arrayIndex`** | Show hints of array index when constructing a table. | "Auto" |
| **`Lua.hint.await`** | If the called function is marked `---@async`, prompt `await` at the call. | true |
| **`Lua.hint.enable`** | Enable inlay hint. | |
| **`Lua.hint.paramName`** | Show hints of parameter name at the function call. | "All" |
| **`Lua.hint.paramType`** | Show type hints at the parameter of the function. | true |
| **`Lua.hint.semicolon`** | If there is no semicolon at the end of the statement, display a virtual semicolon. | "SameLine" |
| **`Lua.hint.setType`** | Show hints of type at assignment operation. | |
| **`Lua.hover.enable`** | Enable hover. | true |
| **`Lua.hover.enumsLimit`** | When the value corresponds to multiple types, limit the number of types displaying. | 5 |
| **`Lua.hover.expandAlias`** | Whether to expand the alias. For example, expands `---@alias myType boolean|number` appears as `boolean|number`, otherwise it appears as `myType'. | true |
| **`Lua.hover.previewFields`** | When hovering to view a table, limits the maximum number of previews for fields. | 50 |
| **`Lua.hover.viewNumber`** | Hover to view numeric content (only if literal is not decimal). | true |
| **`Lua.hover.viewString`** | Hover to view the contents of a string (only if the literal contains an escape character). | true |
| **`Lua.hover.viewStringMax`** | The maximum length of a hover to view the contents of a string. | 1000 |
| **`Lua.misc.executablePath`** | Specify the executable path in VSCode. | |
| **`Lua.misc.parameters`** | [Command line parameters](https://github.com/LuaLS/lua-telemetry-server/tree/master/method) when starting the language server in VSCode. | [] |
| **`Lua.runtime.fileEncoding`** | File encoding. The `ansi` option is only available under the `Windows` platform. | "utf8" |
| **`Lua.runtime.meta`** | Format of the directory name of the meta files. | "${version} ${language} ${encoding}" |
| **`Lua.runtime.nonstandardSymbol`** | Supports non-standard symbols. Make sure that your runtime environment supports these symbols. | [] |
| **`Lua.runtime.path`** | When using `require`, how to find the file based on the input name.
Setting this config to `?/init.lua` means that when you enter `require 'myfile'`, `${workspace}/myfile/init.lua` will be searched from the loaded files.
if `runtime.pathStrict` is `false`, `${workspace}/**/myfile/init.lua` will also be searched.
If you want to load files outside the workspace, you need to set `Lua.workspace.library` first. | ["?.lua","?/init.lua"] |
| **`Lua.runtime.pathStrict`** | When enabled, `runtime.path` will only search the first level of directories, see the description of `runtime.path`. | |
| **`Lua.runtime.plugin`** | Plugin path. Please read [wiki](https://github.com/LuaLS/lua-language-server/wiki/Plugins) to learn more. | |
| **`Lua.runtime.pluginArgs`** | Additional arguments for the plugin. | [] |
| **`Lua.runtime.special`** | The custom global variables are regarded as some special built-in variables, and the language server will provide special support
The following example shows that 'include' is treated as' require '.
```json
"Lua.runtime.special" : {
"include" : "require"
}
``` | {} |
| **`Lua.runtime.unicodeName`** | Allows Unicode characters in name. | |
| **`Lua.runtime.version`** | Lua runtime version. | "Lua 5.4" |
| **`Lua.semantic.annotation`** | Semantic coloring of type annotations. | true |
| **`Lua.semantic.enable`** | Enable semantic color. You may need to set `editor.semanticHighlighting.enabled` to `true` to take effect. | true |
| **`Lua.semantic.keyword`** | Semantic coloring of keywords/literals/operators. You only need to enable this feature if your editor cannot do syntax coloring. | |
| **`Lua.semantic.variable`** | Semantic coloring of variables/fields/parameters. | true |
| **`Lua.signatureHelp.enable`** | Enable signature help. | true |
| **`Lua.spell.dict`** | Custom words for spell checking. | [] |
| **`Lua.type.castNumberToInteger`** | Allowed to assign the `number` type to the `integer` type. | true |
| **`Lua.type.weakNilCheck`** | When checking the type of union type, ignore the `nil` in it.
When this setting is `false`, the `number|nil` type cannot be assigned to the `number` type. It can be with `true`. | |
| **`Lua.type.weakUnionCheck`** | Once one subtype of a union type meets the condition, the union type also meets the condition.
When this setting is `false`, the `number|boolean` type cannot be assigned to the `number` type. It can be with `true`. | |
| **`Lua.window.progressBar`** | Show progress bar in status bar. | true |
| **`Lua.window.statusBar`** | Show extension status in status bar. | true |
| **`Lua.workspace.checkThirdParty`** | Automatic detection and adaptation of third-party libraries, currently supported libraries are:
* OpenResty
* Cocos4.0
* LÖVE
* LÖVR
* skynet
* Jass | true |
| **`Lua.workspace.ignoreDir`** | Ignored files and directories (Use `.gitignore` grammar). | [".vscode"] |
| **`Lua.workspace.ignoreSubmodules`** | Ignore submodules. | true |
| **`Lua.workspace.library`** | In addition to the current workspace, which directories will load files from. The files in these directories will be treated as externally provided code libraries, and some features (such as renaming fields) will not modify these files. | [] |
| **`Lua.workspace.maxPreload`** | Max preloaded files. | 5000 |
| **`Lua.workspace.preloadFileSize`** | Skip files larger than this value (KB) when preloading. | 500 |
| **`Lua.workspace.useGitIgnore`** | Ignore files list in `.gitignore` . | true |
| **`Lua.workspace.userThirdParty`** | Add private third-party library configuration file paths here, please refer to the built-in [configuration file path](https://github.com/LuaLS/lua-language-server/tree/master/meta/3rd) | [] |
## Development
1. Run `npm run build` or `npm run build:watch`
2. Link extension: `npm run link` / `npm run unlink`
## Credit
- [`LuaLS/lua-language-server`](https://github.com/LuaLS/lua-language-server#credit)
## License
[MIT © Josa Gesell](LICENSE)
================================================
FILE: jest.config.js
================================================
module.exports = {
roots: ["/src"],
testMatch: ["**/__tests__/**/*.+(ts|tsx|js)", "**/?(*.)+(spec|test).+(ts|tsx|js)"],
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
},
}
================================================
FILE: package.json
================================================
{
"name": "coc-lua",
"version": "2.0.6",
"description": "lua extension for coc",
"author": "josa@gesell.me",
"license": "MIT",
"main": "lib/extension.js",
"repository": {
"type": "git",
"url": "https://github.com/josa42/coc-lua.git"
},
"engines": {
"coc": "^0.0.82",
"node": ">=16"
},
"keywords": [
"coc.nvim",
"languageserver",
"lua"
],
"scripts": {
"clean": "rimraf lib",
"build": "tsc -p tsconfig.json",
"build:watch": "tsc --watch -p tsconfig.json",
"prepare": "npm run clean && npm run build",
"lint:fix": "eslint . --ext .ts,.js --fix",
"lint": "eslint . --ext .ts,.js",
"test": "jest"
},
"activationEvents": [
"onLanguage:lua",
"onCommand:lua.version",
"onCommand:lua.update"
],
"contributes": {
"configuration": {
"type": "object",
"title": "lua",
"properties": {
"lua.enable": {
"type": "boolean",
"default": true
},
"lua.checkForUpdates": {
"description": "Check for LuaLS/lua-language-server updates on start.",
"type": "string",
"default": "inform",
"enum": [
"disabled",
"inform",
"ask",
"install"
]
},
"lua.installPreReleases": {
"description": "Install latest pre-release of LuaLS/lua-language-server.",
"type": "boolean",
"default": false
},
"lua.trace.server": {
"type": "string",
"default": "off",
"enum": [
"off",
"messages",
"verbose"
]
},
"Lua.addonManager.enable": {
"default": true,
"markdownDescription": "Set the on/off state for the addon manager.",
"scope": "resource",
"type": "boolean"
},
"Lua.codeLens.enable": {
"default": false,
"markdownDescription": "Enable code lens.",
"scope": "resource",
"type": "boolean"
},
"Lua.completion.autoRequire": {
"default": true,
"markdownDescription": "When the input looks like a file name, automatically `require` this file.",
"scope": "resource",
"type": "boolean"
},
"Lua.completion.callSnippet": {
"default": "Disable",
"enum": [
"Disable",
"Both",
"Replace"
],
"markdownDescription": "Shows function call snippets.",
"markdownEnumDescriptions": [
"Only shows `function name`.",
"Shows `function name` and `call snippet`.",
"Only shows `call snippet.`"
],
"scope": "resource",
"type": "string"
},
"Lua.completion.displayContext": {
"default": 0,
"markdownDescription": "Previewing the relevant code snippet of the suggestion may help you understand the usage of the suggestion. The number set indicates the number of intercepted lines in the code fragment. If it is set to `0`, this feature can be disabled.",
"scope": "resource",
"type": "integer"
},
"Lua.completion.enable": {
"default": true,
"markdownDescription": "Enable completion.",
"scope": "resource",
"type": "boolean"
},
"Lua.completion.keywordSnippet": {
"default": "Replace",
"enum": [
"Disable",
"Both",
"Replace"
],
"markdownDescription": "Shows keyword syntax snippets.",
"markdownEnumDescriptions": [
"Only shows `keyword`.",
"Shows `keyword` and `syntax snippet`.",
"Only shows `syntax snippet`."
],
"scope": "resource",
"type": "string"
},
"Lua.completion.postfix": {
"default": "@",
"markdownDescription": "The symbol used to trigger the postfix suggestion.",
"scope": "resource",
"type": "string"
},
"Lua.completion.requireSeparator": {
"default": ".",
"markdownDescription": "The separator used when `require`.",
"scope": "resource",
"type": "string"
},
"Lua.completion.showParams": {
"default": true,
"markdownDescription": "Display parameters in completion list. When the function has multiple definitions, they will be displayed separately.",
"scope": "resource",
"type": "boolean"
},
"Lua.completion.showWord": {
"default": "Fallback",
"enum": [
"Enable",
"Fallback",
"Disable"
],
"markdownDescription": "Show contextual words in suggestions.",
"markdownEnumDescriptions": [
"Always show context words in suggestions.",
"Contextual words are only displayed when suggestions based on semantics cannot be provided.",
"Do not display context words."
],
"scope": "resource",
"type": "string"
},
"Lua.completion.workspaceWord": {
"default": true,
"markdownDescription": "Whether the displayed context word contains the content of other files in the workspace.",
"scope": "resource",
"type": "boolean"
},
"Lua.diagnostics.disable": {
"default": [],
"items": {
"enum": [
"action-after-return",
"ambiguity-1",
"ambiguous-syntax",
"args-after-dots",
"assign-type-mismatch",
"await-in-sync",
"block-after-else",
"break-outside",
"cast-local-type",
"cast-type-mismatch",
"circle-doc-class",
"close-non-object",
"code-after-break",
"codestyle-check",
"count-down-loop",
"deprecated",
"different-requires",
"discard-returns",
"doc-field-no-class",
"duplicate-doc-alias",
"duplicate-doc-field",
"duplicate-doc-param",
"duplicate-index",
"duplicate-set-field",
"empty-block",
"err-assign-as-eq",
"err-c-long-comment",
"err-comment-prefix",
"err-do-as-then",
"err-eq-as-assign",
"err-esc",
"err-nonstandard-symbol",
"err-then-as-do",
"exp-in-action",
"global-in-nil-env",
"index-in-func-name",
"invisible",
"jump-local-scope",
"keyword",
"local-limit",
"lowercase-global",
"lua-doc-miss-sign",
"luadoc-error-diag-mode",
"luadoc-miss-alias-extends",
"luadoc-miss-alias-name",
"luadoc-miss-arg-name",
"luadoc-miss-cate-name",
"luadoc-miss-class-extends-name",
"luadoc-miss-class-name",
"luadoc-miss-diag-mode",
"luadoc-miss-diag-name",
"luadoc-miss-field-extends",
"luadoc-miss-field-name",
"luadoc-miss-fun-after-overload",
"luadoc-miss-generic-name",
"luadoc-miss-local-name",
"luadoc-miss-module-name",
"luadoc-miss-operator-name",
"luadoc-miss-param-extends",
"luadoc-miss-param-name",
"luadoc-miss-see-name",
"luadoc-miss-sign-name",
"luadoc-miss-symbol",
"luadoc-miss-type-name",
"luadoc-miss-vararg-type",
"luadoc-miss-version",
"malformed-number",
"miss-end",
"miss-esc-x",
"miss-exp",
"miss-exponent",
"miss-field",
"miss-loop-max",
"miss-loop-min",
"miss-method",
"miss-name",
"miss-sep-in-table",
"miss-space-between",
"miss-symbol",
"missing-parameter",
"missing-return",
"missing-return-value",
"need-check-nil",
"need-paren",
"nesting-long-mark",
"newfield-call",
"newline-call",
"no-unknown",
"no-visible-label",
"not-yieldable",
"param-type-mismatch",
"redefined-label",
"redefined-local",
"redundant-parameter",
"redundant-return",
"redundant-return-value",
"redundant-value",
"return-type-mismatch",
"set-const",
"spell-check",
"trailing-space",
"unbalanced-assignments",
"undefined-doc-class",
"undefined-doc-name",
"undefined-doc-param",
"undefined-env-child",
"undefined-field",
"undefined-global",
"unexpect-dots",
"unexpect-efunc-name",
"unexpect-lfunc-name",
"unexpect-symbol",
"unicode-name",
"unknown-attribute",
"unknown-cast-variable",
"unknown-diag-code",
"unknown-operator",
"unknown-symbol",
"unreachable-code",
"unsupport-symbol",
"unused-function",
"unused-label",
"unused-local",
"unused-vararg"
],
"type": "string"
},
"markdownDescription": "Disabled diagnostic (Use code in hover brackets).",
"scope": "resource",
"type": "array"
},
"Lua.diagnostics.disableScheme": {
"default": [
"git"
],
"items": {
"type": "string"
},
"markdownDescription": "Do not diagnose Lua files that use the following scheme.",
"scope": "resource",
"type": "array"
},
"Lua.diagnostics.enable": {
"default": true,
"markdownDescription": "Enable diagnostics.",
"scope": "resource",
"type": "boolean"
},
"Lua.diagnostics.globals": {
"default": [],
"items": {
"type": "string"
},
"markdownDescription": "Defined global variables.",
"scope": "resource",
"type": "array"
},
"Lua.diagnostics.ignoredFiles": {
"default": "Opened",
"enum": [
"Enable",
"Opened",
"Disable"
],
"markdownDescription": "How to diagnose ignored files.",
"markdownEnumDescriptions": [
"Always diagnose these files.",
"Only when these files are opened will it be diagnosed.",
"These files are not diagnosed."
],
"scope": "resource",
"type": "string"
},
"Lua.diagnostics.libraryFiles": {
"default": "Opened",
"enum": [
"Enable",
"Opened",
"Disable"
],
"markdownDescription": "How to diagnose files loaded via `Lua.workspace.library`.",
"markdownEnumDescriptions": [
"Always diagnose these files.",
"Only when these files are opened will it be diagnosed.",
"These files are not diagnosed."
],
"scope": "resource",
"type": "string"
},
"Lua.diagnostics.unusedLocalExclude": {
"default": [],
"items": {
"type": "string"
},
"markdownDescription": "Do not diagnose `unused-local` when the variable name matches the following pattern.",
"scope": "resource",
"type": "array"
},
"Lua.diagnostics.workspaceDelay": {
"default": 3000,
"markdownDescription": "Latency (milliseconds) for workspace diagnostics.",
"scope": "resource",
"type": "integer"
},
"Lua.diagnostics.workspaceEvent": {
"default": "OnSave",
"enum": [
"OnChange",
"OnSave",
"None"
],
"markdownDescription": "Set the time to trigger workspace diagnostics.",
"markdownEnumDescriptions": [
"Trigger workspace diagnostics when the file is changed.",
"Trigger workspace diagnostics when the file is saved.",
"Disable workspace diagnostics."
],
"scope": "resource",
"type": "string"
},
"Lua.diagnostics.workspaceRate": {
"default": 100,
"markdownDescription": "Workspace diagnostics run rate (%). Decreasing this value reduces CPU usage, but also reduces the speed of workspace diagnostics. The diagnosis of the file you are currently editing is always done at full speed and is not affected by this setting.",
"scope": "resource",
"type": "integer"
},
"Lua.doc.packageName": {
"default": [],
"items": {
"type": "string"
},
"markdownDescription": "Treat specific field names as package, e.g. `m_*` means `XXX.m_id` and `XXX.m_type` are package, witch can only be accessed in the file where the definition is located.",
"scope": "resource",
"type": "array"
},
"Lua.doc.privateName": {
"default": [],
"items": {
"type": "string"
},
"markdownDescription": "Treat specific field names as private, e.g. `m_*` means `XXX.m_id` and `XXX.m_type` are private, witch can only be accessed in the class where the definition is located.",
"scope": "resource",
"type": "array"
},
"Lua.doc.protectedName": {
"default": [],
"items": {
"type": "string"
},
"markdownDescription": "Treat specific field names as protected, e.g. `m_*` means `XXX.m_id` and `XXX.m_type` are protected, witch can only be accessed in the class where the definition is located and its subclasses.",
"scope": "resource",
"type": "array"
},
"Lua.format.defaultConfig": {
"additionalProperties": false,
"default": {},
"markdownDescription": "The default format configuration. Has a lower priority than `.editorconfig` file in the workspace.\nRead [formatter docs](https://github.com/CppCXY/EmmyLuaCodeStyle/tree/master/docs) to learn usage.\n",
"patternProperties": {
".*": {
"default": "",
"type": "string"
}
},
"scope": "resource",
"title": "defaultConfig",
"type": "object"
},
"Lua.format.enable": {
"default": true,
"markdownDescription": "Enable code formatter.",
"scope": "resource",
"type": "boolean"
},
"Lua.hint.arrayIndex": {
"default": "Auto",
"enum": [
"Enable",
"Auto",
"Disable"
],
"markdownDescription": "Show hints of array index when constructing a table.",
"markdownEnumDescriptions": [
"Show hints in all tables.",
"Show hints only when the table is greater than 3 items, or the table is a mixed table.",
"Disable hints of array index."
],
"scope": "resource",
"type": "string"
},
"Lua.hint.await": {
"default": true,
"markdownDescription": "If the called function is marked `---@async`, prompt `await` at the call.",
"scope": "resource",
"type": "boolean"
},
"Lua.hint.enable": {
"default": false,
"markdownDescription": "Enable inlay hint.",
"scope": "resource",
"type": "boolean"
},
"Lua.hint.paramName": {
"default": "All",
"enum": [
"All",
"Literal",
"Disable"
],
"markdownDescription": "Show hints of parameter name at the function call.",
"markdownEnumDescriptions": [
"All types of parameters are shown.",
"Only literal type parameters are shown.",
"Disable parameter hints."
],
"scope": "resource",
"type": "string"
},
"Lua.hint.paramType": {
"default": true,
"markdownDescription": "Show type hints at the parameter of the function.",
"scope": "resource",
"type": "boolean"
},
"Lua.hint.semicolon": {
"default": "SameLine",
"enum": [
"All",
"SameLine",
"Disable"
],
"markdownDescription": "If there is no semicolon at the end of the statement, display a virtual semicolon.",
"markdownEnumDescriptions": [
"All statements display virtual semicolons.",
"When two statements are on the same line, display a semicolon between them.",
"Disable virtual semicolons."
],
"scope": "resource",
"type": "string"
},
"Lua.hint.setType": {
"default": false,
"markdownDescription": "Show hints of type at assignment operation.",
"scope": "resource",
"type": "boolean"
},
"Lua.hover.enable": {
"default": true,
"markdownDescription": "Enable hover.",
"scope": "resource",
"type": "boolean"
},
"Lua.hover.enumsLimit": {
"default": 5,
"markdownDescription": "When the value corresponds to multiple types, limit the number of types displaying.",
"scope": "resource",
"type": "integer"
},
"Lua.hover.expandAlias": {
"default": true,
"markdownDescription": "Whether to expand the alias. For example, expands `---@alias myType boolean|number` appears as `boolean|number`, otherwise it appears as `myType'.\n",
"scope": "resource",
"type": "boolean"
},
"Lua.hover.previewFields": {
"default": 50,
"markdownDescription": "When hovering to view a table, limits the maximum number of previews for fields.",
"scope": "resource",
"type": "integer"
},
"Lua.hover.viewNumber": {
"default": true,
"markdownDescription": "Hover to view numeric content (only if literal is not decimal).",
"scope": "resource",
"type": "boolean"
},
"Lua.hover.viewString": {
"default": true,
"markdownDescription": "Hover to view the contents of a string (only if the literal contains an escape character).",
"scope": "resource",
"type": "boolean"
},
"Lua.hover.viewStringMax": {
"default": 1000,
"markdownDescription": "The maximum length of a hover to view the contents of a string.",
"scope": "resource",
"type": "integer"
},
"Lua.misc.executablePath": {
"default": "",
"markdownDescription": "Specify the executable path in VSCode.",
"scope": "resource",
"type": "string"
},
"Lua.misc.parameters": {
"default": [],
"items": {
"type": "string"
},
"markdownDescription": "[Command line parameters](https://github.com/LuaLS/lua-telemetry-server/tree/master/method) when starting the language server in VSCode.",
"scope": "resource",
"type": "array"
},
"Lua.runtime.fileEncoding": {
"default": "utf8",
"enum": [
"utf8",
"ansi",
"utf16le",
"utf16be"
],
"markdownDescription": "File encoding. The `ansi` option is only available under the `Windows` platform.",
"markdownEnumDescriptions": [
"",
"",
"",
""
],
"scope": "resource",
"type": "string"
},
"Lua.runtime.meta": {
"default": "${version} ${language} ${encoding}",
"markdownDescription": "Format of the directory name of the meta files.",
"scope": "resource",
"type": "string"
},
"Lua.runtime.nonstandardSymbol": {
"default": [],
"items": {
"enum": [
"//",
"/**/",
"`",
"+=",
"-=",
"*=",
"/=",
"%=",
"^=",
"//=",
"|=",
"&=",
"<<=",
">>=",
"||",
"&&",
"!",
"!=",
"continue"
],
"type": "string"
},
"markdownDescription": "Supports non-standard symbols. Make sure that your runtime environment supports these symbols.",
"scope": "resource",
"type": "array"
},
"Lua.runtime.path": {
"default": [
"?.lua",
"?/init.lua"
],
"items": {
"type": "string"
},
"markdownDescription": "When using `require`, how to find the file based on the input name.\nSetting this config to `?/init.lua` means that when you enter `require 'myfile'`, `${workspace}/myfile/init.lua` will be searched from the loaded files.\nif `runtime.pathStrict` is `false`, `${workspace}/**/myfile/init.lua` will also be searched.\nIf you want to load files outside the workspace, you need to set `Lua.workspace.library` first.\n",
"scope": "resource",
"type": "array"
},
"Lua.runtime.pathStrict": {
"default": false,
"markdownDescription": "When enabled, `runtime.path` will only search the first level of directories, see the description of `runtime.path`.",
"scope": "resource",
"type": "boolean"
},
"Lua.runtime.plugin": {
"default": "",
"markdownDescription": "Plugin path. Please read [wiki](https://github.com/LuaLS/lua-language-server/wiki/Plugins) to learn more.",
"scope": "resource",
"type": "string"
},
"Lua.runtime.pluginArgs": {
"default": [],
"items": {
"type": "string"
},
"markdownDescription": "Additional arguments for the plugin.",
"scope": "resource",
"type": "array"
},
"Lua.runtime.special": {
"additionalProperties": false,
"default": {},
"markdownDescription": "The custom global variables are regarded as some special built-in variables, and the language server will provide special support\nThe following example shows that 'include' is treated as' require '.\n```json\n\"Lua.runtime.special\" : {\n \"include\" : \"require\"\n}\n```\n",
"patternProperties": {
".*": {
"default": "require",
"enum": [
"_G",
"rawset",
"rawget",
"setmetatable",
"require",
"dofile",
"loadfile",
"pcall",
"xpcall",
"assert",
"error",
"type",
"os.exit"
],
"type": "string"
}
},
"scope": "resource",
"title": "special",
"type": "object"
},
"Lua.runtime.unicodeName": {
"default": false,
"markdownDescription": "Allows Unicode characters in name.",
"scope": "resource",
"type": "boolean"
},
"Lua.runtime.version": {
"default": "Lua 5.4",
"enum": [
"Lua 5.1",
"Lua 5.2",
"Lua 5.3",
"Lua 5.4",
"LuaJIT"
],
"markdownDescription": "Lua runtime version.",
"markdownEnumDescriptions": [
"",
"",
"",
"",
""
],
"scope": "resource",
"type": "string"
},
"Lua.semantic.annotation": {
"default": true,
"markdownDescription": "Semantic coloring of type annotations.",
"scope": "resource",
"type": "boolean"
},
"Lua.semantic.enable": {
"default": true,
"markdownDescription": "Enable semantic color. You may need to set `editor.semanticHighlighting.enabled` to `true` to take effect.",
"scope": "resource",
"type": "boolean"
},
"Lua.semantic.keyword": {
"default": false,
"markdownDescription": "Semantic coloring of keywords/literals/operators. You only need to enable this feature if your editor cannot do syntax coloring.",
"scope": "resource",
"type": "boolean"
},
"Lua.semantic.variable": {
"default": true,
"markdownDescription": "Semantic coloring of variables/fields/parameters.",
"scope": "resource",
"type": "boolean"
},
"Lua.signatureHelp.enable": {
"default": true,
"markdownDescription": "Enable signature help.",
"scope": "resource",
"type": "boolean"
},
"Lua.spell.dict": {
"default": [],
"items": {
"type": "string"
},
"markdownDescription": "Custom words for spell checking.",
"scope": "resource",
"type": "array"
},
"Lua.type.castNumberToInteger": {
"default": true,
"markdownDescription": "Allowed to assign the `number` type to the `integer` type.",
"scope": "resource",
"type": "boolean"
},
"Lua.type.weakNilCheck": {
"default": false,
"markdownDescription": "When checking the type of union type, ignore the `nil` in it.\n\nWhen this setting is `false`, the `number|nil` type cannot be assigned to the `number` type. It can be with `true`.\n",
"scope": "resource",
"type": "boolean"
},
"Lua.type.weakUnionCheck": {
"default": false,
"markdownDescription": "Once one subtype of a union type meets the condition, the union type also meets the condition.\n\nWhen this setting is `false`, the `number|boolean` type cannot be assigned to the `number` type. It can be with `true`.\n",
"scope": "resource",
"type": "boolean"
},
"Lua.window.progressBar": {
"default": true,
"markdownDescription": "Show progress bar in status bar.",
"scope": "resource",
"type": "boolean"
},
"Lua.window.statusBar": {
"default": true,
"markdownDescription": "Show extension status in status bar.",
"scope": "resource",
"type": "boolean"
},
"Lua.workspace.checkThirdParty": {
"default": true,
"markdownDescription": "Automatic detection and adaptation of third-party libraries, currently supported libraries are:\n\n* OpenResty\n* Cocos4.0\n* LÖVE\n* LÖVR\n* skynet\n* Jass\n",
"scope": "resource",
"type": "boolean"
},
"Lua.workspace.ignoreDir": {
"default": [
".vscode"
],
"items": {
"type": "string"
},
"markdownDescription": "Ignored files and directories (Use `.gitignore` grammar).",
"scope": "resource",
"type": "array"
},
"Lua.workspace.ignoreSubmodules": {
"default": true,
"markdownDescription": "Ignore submodules.",
"scope": "resource",
"type": "boolean"
},
"Lua.workspace.library": {
"default": [],
"items": {
"type": "string"
},
"markdownDescription": "In addition to the current workspace, which directories will load files from. The files in these directories will be treated as externally provided code libraries, and some features (such as renaming fields) will not modify these files.",
"scope": "resource",
"type": "array"
},
"Lua.workspace.maxPreload": {
"default": 5000,
"markdownDescription": "Max preloaded files.",
"scope": "resource",
"type": "integer"
},
"Lua.workspace.preloadFileSize": {
"default": 500,
"markdownDescription": "Skip files larger than this value (KB) when preloading.",
"scope": "resource",
"type": "integer"
},
"Lua.workspace.useGitIgnore": {
"default": true,
"markdownDescription": "Ignore files list in `.gitignore` .",
"scope": "resource",
"type": "boolean"
},
"Lua.workspace.userThirdParty": {
"default": [],
"items": {
"type": "string"
},
"markdownDescription": "Add private third-party library configuration file paths here, please refer to the built-in [configuration file path](https://github.com/LuaLS/lua-language-server/tree/master/meta/3rd)",
"scope": "resource",
"type": "array"
}
}
},
"commands": [
{
"command": "lua.version",
"title": "Print extension version"
},
{
"command": "lua.update",
"title": "Update lua-lsp"
}
]
},
"devDependencies": {
"@chemzqm/tsconfig": "^0.0.3",
"@types/jest": "^29.4.0",
"@types/node": "^18.14.0",
"@types/tar": "^6.1.4",
"@types/which": "^2.0.2",
"@typescript-eslint/eslint-plugin": "^5.52.0",
"@typescript-eslint/parser": "^5.52.0",
"coc.nvim": "0.0.82",
"eslint": "8.34.0",
"eslint-config-josa-typescript": "^0.1.2",
"jest": "^29.4.3",
"rimraf": "^4.1.2",
"ts-jest": "^29.0.5",
"typescript": "^4.9.5"
},
"dependencies": {
"tar": "^6.1.13",
"tslib": "^2.5.0",
"which": "^3.0.0"
}
}
================================================
FILE: scripts/nvim.sh
================================================
#!/bin/bash
DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." &> /dev/null && pwd)"
TMP="$DIR/.tmp"
# rm -rf $TMP
mkdir -p $TMP/{share/nvim,state,cache,config/nvim/syntax}
PLUGGED="$TMP/share/data/plugged"
PLUG_FILE="$TMP/share/nvim/site/autoload/plug.vim"
PLUG_URL='https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
cat > $TMP/config/nvim/init.lua <', 'coc#refresh()', { silent = true, expr = true })
vim.api.nvim_set_keymap('n', 'gd', '(coc-definition)', { silent = true })
vim.api.nvim_set_keymap('n', 'gf', 'CocAction("format")', { silent = true, expr = true })
vim.api.nvim_set_keymap("i", "", [[coc#pum#visible() ? coc#pum#confirm() : "\"]], { silent = true, expr = true, expr = true, replace_keycodes = false })
function _G.__coc()
local info = vim.b.coc_diagnostic_info or {}
local parts = {
'E' .. (info.error or 0),
'W' .. (info.warning or 0),
(vim.g.coc_status or ''),
}
return vim.fn.join(parts, ' ')
end
vim.opt.statusline = '%{v:lua.__coc()}'
vim.cmd [[
hi CocUnderline gui=undercurl term=undercurl
hi CocErrorHighlight ctermfg=red guifg=#c4384b gui=undercurl term=undercurl
hi CocWarningHighlight ctermfg=yellow guifg=#c4ab39 gui=undercurl term=undercurl
]]
EOF
cat > $TMP/config/nvim/coc-settings.json < k.match(/^Lua\./))
.sort((a, b) => a.localeCompare(b))
.forEach((k) => delete props[k])
rmKey.forEach((k) => delete settings.properties[k])
Object.assign(props, {
...Object.fromEntries(
Object.entries(settings.properties)
.filter(([,value]) => !value.properties)
.map(([key,value]) => [`Lua.${key}`, value])
)
})
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, " ") + "\n")
const sections = parseMarkdown(await fs.promises.readFile(path.join(__dirname, "..", "README.md"), "utf-8"))
await updateTable(sections)
const out = sections.flatMap(({ title, lines }) => [title, ...lines]).join("\n")
await fs.promises.writeFile(path.join(__dirname, "..", "README.md"), out)
}
async function get(sourceUrl) {
let reponseData = ""
return new Promise((resolve, reject) => {
const get = (url) =>
https.get(url, (res) => {
const { statusCode } = res
if (statusCode === 301 || statusCode === 302) {
return get(res.headers.location)
}
res
.on("data", (data) => (reponseData += data))
.on("end", () => resolve(reponseData))
.on("error", (err) => reject(err))
})
return get(sourceUrl)
})
}
async function updateTable(sections) {
const pkg = JSON.parse(await fs.promises.readFile(path.join(__dirname, "..", "package.json")))
let lines = Object.entries(pkg.contributes.configuration.properties)
.filter(([k]) => k.startsWith('Lua.'))
.sort((p1, p2) => p1[0].localeCompare(p2[0]))
.flatMap(([k, v]) => {
const lines = [
]
if (!v.properties) {
lines.push(`| **\`${k}\`** | ${v?.markdownDescription.trim().split(/\n/).join("
") ?? ''} | ${v.default ? JSON.stringify(v.default) : ''} |`)
}
return lines
})
lines = [
'| Key | Description | Default |',
'|-----|-------------|---------|',
...lines,
]
sections.find((s) => s.title === "### LuaLS/lua-language-server").lines = ["", ...lines]
}
function parseMarkdown(source) {
let section
return source.split("\n").reduce((sections, line) => {
if (line.startsWith("#")) {
section = { title: line, lines: [] }
sections.push(section)
} else {
section.lines.push(line)
}
return sections
}, [])
}
function fixSchema(schema, base = undefined) {
base = base ?? schema
if (schema['$ref']) {
const [,key,prop] = schema['$ref'].match(/^#\/([^/]+)\/(.*)/) ?? []
if (!key || !prop || !base[key]?.[prop]) {
console.log(Object.keys(base[key]))
throw new Error(`ref / "${prop}" not found: ${schema['$ref']}`)
}
return base[key]?.[prop]
}
if (schema.properties) {
Object.entries(schema.properties).forEach(([key, value]) => {
schema.properties[key] = fixSchema(value, base)
})
}
if (schema.patternProperties) {
Object.entries(schema.patternProperties).forEach(([key, value]) => {
if (key === '') {
delete schema.patternProperties[key]
key = '.*'
}
schema.patternProperties[key] = fixSchema(value, base)
})
}
return schema
}
run()
================================================
FILE: src/__mocks__/coc.nvim.ts
================================================
export const workspace = {
getConfiguration() {
return { get: () => ({}) }
},
}
export const window = {}
export default {}
================================================
FILE: src/commands.ts
================================================
import fs from "fs"
import path from "path"
import { installLuaLs } from "./utils/installer"
import { window, LanguageClient } from "coc.nvim"
export async function version(): Promise {
const { version } = JSON.parse(fs.readFileSync(path.resolve(__dirname, "..", "package.json"), "utf-8"))
window.showMessage(`coc-lua: ${version}`, "more")
}
export async function update(client: LanguageClient): Promise {
await installLuaLs(true)
if (client.needsStop()) {
await client.stop()
client.start()
}
}
================================================
FILE: src/extension.ts
================================================
import { commands, ExtensionContext, LanguageClient, ServerOptions, services, LanguageClientOptions } from "coc.nvim"
import { installLuaLs, luaLsCommandAndArgs, checkForUpdate } from "./utils/installer"
import { commandExists } from "./utils/tools"
import { version, update } from "./commands"
import { setStoragePath, getConfig } from "./utils/config"
export async function activate(context: ExtensionContext): Promise {
setStoragePath(context.storagePath)
const config = getConfig()
if (config.enable === false) {
return
}
if (config.checkForUpdates !== "disabled") {
setTimeout(() => checkForUpdate(config.checkForUpdates), 0)
}
const client = await createClient()
context.subscriptions.push(
services.registLanguageClient(client),
commands.registerCommand("lua.version", () => version()),
commands.registerCommand("lua.update", async () => update(client))
)
}
async function createClient(): Promise {
const [command, args] = await luaLsCommandAndArgs()
if (!(await commandExists(command))) {
await installLuaLs()
}
const serverOptions: ServerOptions = { command, args }
const clientOptions: LanguageClientOptions = {
documentSelector: ["lua"],
progressOnInitialization: true,
initializationOptions: {
changeConfiguration: true,
}
}
return new LanguageClient("lua", "lua", serverOptions, clientOptions)
}
================================================
FILE: src/utils/config.ts
================================================
import fs from "fs"
import os from "os"
import path from "path"
import { workspace } from "coc.nvim"
interface LuaConfig {
enable: boolean
checkForUpdates: "disabled" | "inform" | "ask" | "install"
installPreReleases: boolean
}
export function getConfig(): LuaConfig {
return workspace.getConfiguration().get("lua")
}
interface State {
storagePath?: string
}
const state: State = {}
export function setStoragePath(dir: string): void {
state.storagePath = dir
}
export async function configDir(...names: string[]): Promise {
const storage =
state.storagePath ||
((): string => {
const home = os.homedir()
return path.join(home, ".config", "coc", "lua")
})()
const dir = path.join(storage, ...names)
return new Promise((resolve) => {
fs.mkdirSync(dir, { recursive: true })
resolve(dir)
})
}
================================================
FILE: src/utils/db.ts
================================================
import * as fs from "fs"
import * as path from "path"
import { configDir } from "./config"
type DBValue = string | number | boolean | undefined
interface DB {
[key: string]: DBValue
}
async function dbPath(): Promise {
const dir = await configDir()
return path.join(dir, "db.json")
}
async function write(data: DB): Promise {
await fs.promises.writeFile(await dbPath(), JSON.stringify(data, null, " "))
}
async function read(): Promise {
try {
return JSON.parse(await fs.promises.readFile(await dbPath(), "utf-8")) as DB
} catch (err) {
return {}
}
}
export async function dbSet(key: string, value: T): Promise {
const db = await read()
db[key] = value
await write(db)
}
export async function dbGet(key: string, defaultValue?: T): Promise {
const db = await read()
const value = db[key]
if (value !== undefined) {
return value as T
}
return defaultValue
}
================================================
FILE: src/utils/installer.test.ts
================================================
import * as fs from "fs"
import * as path from "path"
import * as os from "os"
import { install, osEnv } from "./installer"
describe("installer", () => {
let tmpDir: string
beforeEach(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "foo-"))
})
afterEach(async () => {
await fs.promises.rm(tmpDir, { recursive: true })
})
it("should install", async () => {
jest.setTimeout(30000)
await install(tmpDir)
const { bin } = osEnv()
expect(fs.existsSync(path.join(tmpDir, "main.lua"))).toBeTruthy()
expect(fs.existsSync(path.join(tmpDir, bin))).toBeTruthy()
})
})
================================================
FILE: src/utils/installer.ts
================================================
import * as crypto from "crypto"
import * as fs from "fs"
import * as https from "https"
import * as os from "os"
import * as path from "path"
import * as tar from "tar"
import { window } from "coc.nvim"
import { configDir } from "./config"
import { showInstallStatus } from "./tools"
import { dbGet, dbSet } from "./db"
const luaLsDir = "lua-language-server"
const oneDayMS = 24 * 60 * 60 * 1000
const fsp = fs.promises
const osPlatform = os.platform()
const tmpBaseDir = os.tmpdir()
const { join } = path
const latestURL = 'https://api.github.com/repos/LuaLS/lua-language-server/releases/latest'
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '../../package.json'), 'utf-8')) as {version: string}
const DBKey = {
VERSION: 'installed-version',
PUBLISHED_AT: 'installed-version-published-at',
LAST_UPDATE_CHECK: "last-update-check",
}
interface LatestResponse {
tag_name: string
published_at: string
assets: Array<{
name: string
browser_download_url: string
}>
}
interface Version {
version: string
publishedAt: number
}
interface Release extends Version {
url: string
}
async function getLatestRelease(filePath: string): Promise {
const { assets, tag_name: version, published_at } = await getJSON(latestURL)
const { browser_download_url: url } = assets.find(({ name }) => name.endsWith(filePath)) ?? {}
return { version, publishedAt: new Date(published_at).getTime(), url }
}
async function getLatestVersion(): Promise {
const { tag_name: version, published_at } = await getJSON(latestURL)
return { version, publishedAt: new Date(published_at).getTime() }
}
export async function install(dir: string): Promise {
const { tarFile } = osEnv()
const { url, version, publishedAt } = await getLatestRelease(tarFile)
await downloadTar(url, dir)
await dbSet(DBKey.VERSION, version)
await dbSet(DBKey.PUBLISHED_AT, publishedAt)
}
async function downloadTar(sourceUrl: string, targetPath: string) {
const dir = await mkTmpDir(sourceUrl)
if (osPlatform === 'win32') {
throw new Error('Windows is not currently supported')
} else {
const tarTmpPath = join(dir.path, "tmp.tar.gz")
await download(sourceUrl, tarTmpPath)
await tar.x({ file: tarTmpPath, cwd: targetPath, strip: 0 })
}
await dir.dispose()
}
async function mkTmpDir(key: string): Promise<{ path: string; dispose: () => Promise }> {
const hash = crypto.createHash("md5").update(key).digest("hex")
const dir = join(tmpBaseDir, hash)
await fsp.mkdir(dir, { recursive: true })
return { path: dir, dispose: async () => fsp.rm(dir, { recursive: true }) }
}
async function download(sourceUrl: string, targetPath: string): Promise {
const file = fs.createWriteStream(targetPath)
return new Promise((resolve, reject) => {
const get = (url: string) =>
https.get(url, (res) => {
const { statusCode } = res
if (statusCode === 301 || statusCode === 302) {
return get(res.headers.location)
}
res
.on("data", (data) => file.write(data))
.on("end", () => (file.end(), setTimeout(() => resolve(), 5)))
.on("error", (err: Error) => reject(err))
})
return get(sourceUrl)
})
}
export function osEnv(): { tarFile: string; bin: string } {
switch (osPlatform) {
case "darwin":
return {
tarFile: process.arch === 'arm64'
? "darwin-arm64.tar.gz"
: "darwin-x64.tar.gz",
bin: join("bin", "lua-language-server"),
}
case "linux":
return {
tarFile: process.arch === 'arm64'
? "linux-arm64.tar.gz"
: "linux-x64.tar.gz",
bin: join("bin", "lua-language-server"),
}
case "win32":
return {
tarFile: "win32-x64.zip",
bin: join("bin", "lua-language-server.exe"),
}
}
return { tarFile: "", bin: "" }
}
export async function checkForUpdate(action: "disabled" | "inform" | "ask" | "install"): Promise {
if (!(await shouldCheck())) {
return
}
const statusItem = window.createStatusBarItem(90, { progress: true })
statusItem.text = "Check for updates"
statusItem.show()
try {
const rinfo = (await getLatestVersion())
const linfo = await dbGet(DBKey.PUBLISHED_AT)
if (rinfo.publishedAt > linfo) {
handleUpdateAction(action, rinfo.version)
}
} catch (err) {
window.showMessage(JSON.stringify(err), "error")
}
statusItem.hide()
}
async function shouldCheck(): Promise {
const now = new Date().getTime()
const last = await dbGet(DBKey.LAST_UPDATE_CHECK, -1)
const diff = now - last
if (last === -1 || diff > oneDayMS) {
await dbSet(DBKey.LAST_UPDATE_CHECK, now)
return true
}
return false
}
async function handleUpdateAction(action: "disabled" | "inform" | "ask" | "install", version: string) {
switch (action) {
case "ask":
if (await window.showPrompt(`LuaLS/lua-language-server ${version} is available. Install?`)) {
installLuaLs(true)
}
break
case "install":
installLuaLs(true)
break
case "inform":
window.showMessage(`LuaLS/lua-language-server ${version} is available. Run ":CocCommand lua.update"`)
break
}
}
export async function installLuaLs(force = false): Promise {
if (!force && (await luaLsExists())) {
return
}
await showInstallStatus("LuaLS/lua-language-server", async () => {
await install(await configDir(luaLsDir))
})
}
export async function luaLsCommandAndArgs(): Promise<[string, string[]]> {
const baseDir = await configDir(luaLsDir)
const { bin } = osEnv()
return [path.join(baseDir, bin), ["-E", path.join(baseDir, "main.lua")]]
}
async function luaLsExists(): Promise {
const [bin] = await luaLsCommandAndArgs()
return new Promise((resolve) => fs.open(bin, "r", (err) => resolve(err === null)))
}
const getOptions = {
headers: {
'User-Agent': `coc-lua/${pkg.version}`,
}
}
async function getJSON(url: string): Promise {
return new Promise((resolve, reject) => {
https
.get(url, getOptions, (resp) => {
let data = ""
resp.on("data", (chunk) => (data += chunk))
resp.on("end", () => {
resolve(JSON.parse(data) as R)
})
})
.on("error", (err) => reject(err))
})
}
================================================
FILE: src/utils/tools.ts
================================================
import which from "which"
import { window } from "coc.nvim"
export async function commandExists(bin: string): Promise {
return Boolean(await which(bin, { nothrow: true }))
}
export async function showInstallStatus(name: string, fn: () => Promise): Promise {
const statusItem = window.createStatusBarItem(90, { progress: true })
statusItem.text = `Installing '${name}'`
statusItem.show()
try {
await fn()
window.showMessage(`Installed '${name}'`)
} catch (err) {
window.showMessage(`Failed to install '${name}': ${err}`, "error")
statusItem.hide()
throw err
}
statusItem.hide()
}
================================================
FILE: tsconfig.json
================================================
{
"extends": "./node_modules/@chemzqm/tsconfig/tsconfig.json",
"compilerOptions": {
"outDir": "lib",
"target": "es2015",
"module": "commonjs",
"noImplicitThis": true,
"moduleResolution": "node",
"importHelpers": true,
"lib": ["es2018"],
"plugins": []
},
"include": [
"src"
],
"exclude": [
],
"moduleResolution": "node"
}