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.<br>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.<br>Setting this config to `?/init.lua` means that when you enter `require 'myfile'`, `${workspace}/myfile/init.lua` will be searched from the loaded files.<br>if `runtime.pathStrict` is `false`, `${workspace}/**/myfile/init.lua` will also be searched.<br>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<br>The following example shows that 'include' is treated as' require '.<br>```json<br>"Lua.runtime.special" : {<br> "include" : "require"<br>}<br>``` | {} |
| **`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.<br><br>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.<br><br>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:<br><br>* OpenResty<br>* Cocos4.0<br>* LÖVE<br>* LÖVR<br>* skynet<br>* 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: ["<rootDir>/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 <<EOF
vim.cmd [[
call plug#begin('$PLUGGED')
Plug 'josa42/theme-theonedark', { 'rtp': 'dist/vim' }
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug '$DIR'
call plug#end()
]]
if vim.tbl_contains(vim.fn.getcompletion('', 'color'), 'theonedark') then
vim.cmd('colorscheme theonedark')
end
vim.opt.encoding = 'utf-8'
vim.opt.hidden = true
vim.opt.backup = false
vim.opt.writebackup = false
vim.opt.cmdheight = 2
vim.opt.updatetime = 300
vim.opt.shortmess:append('c')
vim.opt.signcolumn = 'yes'
vim.opt.number = true
vim.opt.listchars = 'tab:» ,extends:›,precedes:‹,nbsp:·,space:·,trail:·'
vim.opt.list = true
vim.opt.tabstop = 2
vim.opt.softtabstop = 2
vim.opt.shiftwidth = 2
vim.opt.expandtab = false
vim.api.nvim_set_keymap('i', '<c-space>', 'coc#refresh()', { silent = true, expr = true })
vim.api.nvim_set_keymap('n', 'gd', '<Plug>(coc-definition)', { silent = true })
vim.api.nvim_set_keymap('n', 'gf', 'CocAction("format")', { silent = true, expr = true })
vim.api.nvim_set_keymap("i", "<cr>", [[coc#pum#visible() ? coc#pum#confirm() : "\<CR>"]], { 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 <<EOF
{
"Lua": {}
}
EOF
export XDG_CONFIG_HOME=$TMP/config
export XDG_CACHE_HOME=$TMP/cache
export XDG_DATA_HOME=$TMP/share
export XDG_STATE_HOME=$TMP/state
if [[ ! -f "$PLUG_FILE" ]]; then
curl -sSfLo $PLUG_FILE --create-dirs $PLUG_URL
nvim --headless +'PlugInstall | PlugUpdate| qa!'
fi
nvim "$@"
================================================
FILE: scripts/update-settings.js
================================================
#!/usr/bin/env node
const fs = require("fs")
const https = require("https")
const path = require("path")
const pkgPath = path.join(__dirname, "..", "package.json")
const rmKey = ["Lua.awakened.cat", "Lua.develop.enable", "Lua.develop.debuggerPort", "Lua.develop.debuggerWait"]
async function run() {
const settings = fixSchema(JSON.parse(
await get("https://raw.githubusercontent.com/LuaLS/vscode-lua/master/setting/schema.json")
))
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"))
const props = pkg.contributes.configuration.properties
Object.keys(props)
.filter((k) => 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("<br>") ?? ''} | ${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<void> {
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<void> {
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<void> {
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<LanguageClient> {
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<LuaConfig>("lua")
}
interface State {
storagePath?: string
}
const state: State = {}
export function setStoragePath(dir: string): void {
state.storagePath = dir
}
export async function configDir(...names: string[]): Promise<string> {
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<string> {
const dir = await configDir()
return path.join(dir, "db.json")
}
async function write(data: DB): Promise<void> {
await fs.promises.writeFile(await dbPath(), JSON.stringify(data, null, " "))
}
async function read(): Promise<DB> {
try {
return JSON.parse(await fs.promises.readFile(await dbPath(), "utf-8")) as DB
} catch (err) {
return {}
}
}
export async function dbSet<T extends DBValue>(key: string, value: T): Promise<void> {
const db = await read()
db[key] = value
await write(db)
}
export async function dbGet<T extends DBValue>(key: string, defaultValue?: T): Promise<T> {
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<Release> {
const { assets, tag_name: version, published_at } = await getJSON<LatestResponse>(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<Version> {
const { tag_name: version, published_at } = await getJSON<LatestResponse>(latestURL)
return { version, publishedAt: new Date(published_at).getTime() }
}
export async function install(dir: string): Promise<void> {
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<void> }> {
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<void> {
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<void> {
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<number>(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<boolean> {
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<void> {
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<boolean> {
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<R>(url: string): Promise<R> {
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<boolean> {
return Boolean(await which(bin, { nothrow: true }))
}
export async function showInstallStatus(name: string, fn: () => Promise<void>): Promise<void> {
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"
}
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
SYMBOL INDEX (41 symbols across 8 files)
FILE: scripts/update-settings.js
function run (line 11) | async function run() {
function get (line 43) | async function get(sourceUrl) {
function updateTable (line 65) | async function updateTable(sections) {
function parseMarkdown (line 90) | function parseMarkdown(source) {
function fixSchema (line 105) | function fixSchema(schema, base = undefined) {
FILE: src/__mocks__/coc.nvim.ts
method getConfiguration (line 2) | getConfiguration() {
FILE: src/commands.ts
function version (line 6) | async function version(): Promise<void> {
function update (line 11) | async function update(client: LanguageClient): Promise<void> {
FILE: src/extension.ts
function activate (line 8) | async function activate(context: ExtensionContext): Promise<void> {
function createClient (line 29) | async function createClient(): Promise<LanguageClient> {
FILE: src/utils/config.ts
type LuaConfig (line 6) | interface LuaConfig {
function getConfig (line 12) | function getConfig(): LuaConfig {
type State (line 16) | interface State {
function setStoragePath (line 22) | function setStoragePath(dir: string): void {
function configDir (line 26) | async function configDir(...names: string[]): Promise<string> {
FILE: src/utils/db.ts
type DBValue (line 5) | type DBValue = string | number | boolean | undefined
type DB (line 7) | interface DB {
function dbPath (line 11) | async function dbPath(): Promise<string> {
function write (line 16) | async function write(data: DB): Promise<void> {
function read (line 20) | async function read(): Promise<DB> {
function dbSet (line 28) | async function dbSet<T extends DBValue>(key: string, value: T): Promise<...
function dbGet (line 34) | async function dbGet<T extends DBValue>(key: string, defaultValue?: T): ...
FILE: src/utils/installer.ts
type LatestResponse (line 34) | interface LatestResponse {
type Version (line 43) | interface Version {
type Release (line 48) | interface Release extends Version {
function getLatestRelease (line 53) | async function getLatestRelease(filePath: string): Promise<Release> {
function getLatestVersion (line 60) | async function getLatestVersion(): Promise<Version> {
function install (line 66) | async function install(dir: string): Promise<void> {
function downloadTar (line 74) | async function downloadTar(sourceUrl: string, targetPath: string) {
function mkTmpDir (line 90) | async function mkTmpDir(key: string): Promise<{ path: string; dispose: (...
function download (line 99) | async function download(sourceUrl: string, targetPath: string): Promise<...
function osEnv (line 121) | function osEnv(): { tarFile: string; bin: string } {
function checkForUpdate (line 146) | async function checkForUpdate(action: "disabled" | "inform" | "ask" | "i...
function shouldCheck (line 168) | async function shouldCheck(): Promise<boolean> {
function handleUpdateAction (line 181) | async function handleUpdateAction(action: "disabled" | "inform" | "ask" ...
function installLuaLs (line 197) | async function installLuaLs(force = false): Promise<void> {
function luaLsCommandAndArgs (line 207) | async function luaLsCommandAndArgs(): Promise<[string, string[]]> {
function luaLsExists (line 214) | async function luaLsExists(): Promise<boolean> {
function getJSON (line 225) | async function getJSON<R>(url: string): Promise<R> {
FILE: src/utils/tools.ts
function commandExists (line 4) | async function commandExists(bin: string): Promise<boolean> {
function showInstallStatus (line 8) | async function showInstallStatus(name: string, fn: () => Promise<void>):...
Condensed preview — 25 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (68K chars).
[
{
"path": ".eslintignore",
"chars": 17,
"preview": "/lib\nnode_module\n"
},
{
"path": ".eslintrc",
"chars": 84,
"preview": "{\n \"root\": true,\n \"extends\": \"josa-typescript\",\n \"env\": {\n \"jest\": true\n }\n}\n"
},
{
"path": ".github/workflows/main.yml",
"chars": 476,
"preview": "name: Main\n\non: push\n\njobs:\n test:\n strategy:\n fail-fast: false\n matrix:\n node: [ 16, 18 ]\n "
},
{
"path": ".github/workflows/publish.yml",
"chars": 450,
"preview": "name: Publish\n\non:\n schedule:\n - cron: '5 0 * * *'\n workflow_dispatch:\n inputs:\n version:\n type: ch"
},
{
"path": ".github/workflows/update-settings.yml",
"chars": 376,
"preview": "name: Settings\n\non:\n schedule:\n - cron: '0 0 * * *'\n workflow_dispatch:\n\njobs:\n update:\n runs-on: ubuntu-lates"
},
{
"path": ".gitignore",
"chars": 48,
"preview": "lib\nnode_modules\nyarn-error.log\n/.tmp\n.DS_Store\n"
},
{
"path": ".node-version",
"chars": 4,
"preview": "v18\n"
},
{
"path": ".npmignore",
"chars": 147,
"preview": "*.map\n*.ts\n/.eslintignore\n/.eslintrc\n/.github/\n/.node-version\n/.vim/\n/lib/**/*.test.js\n/lib/__mocks__/\n/scripts/\n/src/\n/"
},
{
"path": ".npmrc",
"chars": 22,
"preview": "legacy-peer-deps=true\n"
},
{
"path": ".vim/coc-settings.json",
"chars": 84,
"preview": "{\n \"coc.preferences.formatOnSaveFiletypes\": [\"javascript\", \"typescript\", \"json\"]\n}\n"
},
{
"path": "LICENSE",
"chars": 1068,
"preview": "MIT License\n\nCopyright (c) 2019 Josa Gesell\n\nPermission is hereby granted, free of charge, to any person obtaining a cop"
},
{
"path": "README.md",
"chars": 10725,
"preview": "# coc-lua\n\n\n\n----------------------------------------"
},
{
"path": "jest.config.js",
"chars": 189,
"preview": "module.exports = {\n roots: [\"<rootDir>/src\"],\n testMatch: [\"**/__tests__/**/*.+(ts|tsx|js)\", \"**/?(*.)+(spec|test).+(t"
},
{
"path": "package.json",
"chars": 30897,
"preview": "{\n \"name\": \"coc-lua\",\n \"version\": \"2.0.6\",\n \"description\": \"lua extension for coc\",\n \"author\": \"josa@gesell.me\",\n \""
},
{
"path": "scripts/nvim.sh",
"chars": 2353,
"preview": "#!/bin/bash\n\nDIR=\"$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")/..\" &> /dev/null && pwd)\"\nTMP=\"$DIR/.tmp\"\n\n# rm -rf $TMP\nmk"
},
{
"path": "scripts/update-settings.js",
"chars": 3744,
"preview": "#!/usr/bin/env node\n\nconst fs = require(\"fs\")\nconst https = require(\"https\")\nconst path = require(\"path\")\n\nconst pkgPath"
},
{
"path": "src/__mocks__/coc.nvim.ts",
"chars": 132,
"preview": "export const workspace = {\n getConfiguration() {\n return { get: () => ({}) }\n },\n}\nexport const window = {}\n\nexport"
},
{
"path": "src/commands.ts",
"chars": 529,
"preview": "import fs from \"fs\"\nimport path from \"path\"\nimport { installLuaLs } from \"./utils/installer\"\nimport { window, LanguageCl"
},
{
"path": "src/extension.ts",
"chars": 1420,
"preview": "import { commands, ExtensionContext, LanguageClient, ServerOptions, services, LanguageClientOptions } from \"coc.nvim\"\n\ni"
},
{
"path": "src/utils/config.ts",
"chars": 868,
"preview": "import fs from \"fs\"\nimport os from \"os\"\nimport path from \"path\"\nimport { workspace } from \"coc.nvim\"\n\ninterface LuaConfi"
},
{
"path": "src/utils/db.ts",
"chars": 973,
"preview": "import * as fs from \"fs\"\nimport * as path from \"path\"\nimport { configDir } from \"./config\"\n\ntype DBValue = string | numb"
},
{
"path": "src/utils/installer.test.ts",
"chars": 630,
"preview": "import * as fs from \"fs\"\nimport * as path from \"path\"\nimport * as os from \"os\"\n\nimport { install, osEnv } from \"./instal"
},
{
"path": "src/utils/installer.ts",
"chars": 6426,
"preview": "import * as crypto from \"crypto\"\nimport * as fs from \"fs\"\nimport * as https from \"https\"\nimport * as os from \"os\"\nimport"
},
{
"path": "src/utils/tools.ts",
"chars": 641,
"preview": "import which from \"which\"\nimport { window } from \"coc.nvim\"\n\nexport async function commandExists(bin: string): Promise<b"
},
{
"path": "tsconfig.json",
"chars": 373,
"preview": "{\n \"extends\": \"./node_modules/@chemzqm/tsconfig/tsconfig.json\",\n \"compilerOptions\": {\n \"outDir\": \"lib\",\n \"target"
}
]
About this extraction
This page contains the full source code of the josa42/coc-lua GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 25 files (61.2 KB), approximately 15.6k tokens, and a symbol index with 41 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.