coc-dictd
Version:
dictd extension for coc.nvim
1,435 lines (1,404 loc) • 110 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
activate: () => activate
});
module.exports = __toCommonJS(src_exports);
// node_modules/coc-helper/lib/esm/index.js
var import_coc14 = require("coc.nvim");
// node_modules/coc-helper/lib/esm/events.js
var import_coc7 = require("coc.nvim");
// node_modules/coc-helper/lib/esm/VimModule.js
var import_coc5 = require("coc.nvim");
// node_modules/coc-helper/lib/esm/notifier.js
var import_coc4 = require("coc.nvim");
// node_modules/coc-helper/lib/esm/util/collection.js
var compactI = (arr) => arr.filter((it) => it !== void 0 && it !== null);
// node_modules/coc-helper/lib/esm/util/config.js
var import_coc2 = require("coc.nvim");
// node_modules/coc-helper/lib/esm/util/text.js
var import_coc = require("coc.nvim");
// node_modules/coc-helper/lib/esm/util/env.js
var isWindows = process.platform === "win32";
var isMacintosh = process.platform === "darwin";
var isLinux = process.platform === "linux";
var isTest = process.env.NODE_ENV === "test";
// node_modules/coc-helper/lib/esm/util/text.js
async function displayWidth(content) {
return await import_coc.workspace.nvim.call("strdisplaywidth", [content]);
}
// node_modules/coc-helper/lib/esm/util/log.js
var import_coc3 = require("coc.nvim");
var import_util = __toESM(require("util"));
var levelList = [
"trace",
"debug",
"info",
"warn",
"error",
"fatal",
"off"
];
var levelErrorNum = levelList.indexOf("error");
function formatDate(date) {
return `${date.toLocaleString()} ${date.getMilliseconds().toString().padStart(3, "0")}`;
}
var HelperLogger = class {
constructor(channelName2) {
this.channelName = channelName2;
this.timeMarkers = /* @__PURE__ */ new Map();
this.levelStatus = "trace";
this.levelNumber = levelList.indexOf(this.levelStatus);
this.appendLine = (line) => {
this.outputChannel.appendLine(line);
};
this.log = (levelName, data) => {
var _a, _b;
const levelNum = levelList[levelName];
if (levelNum < this.levelNumber) {
return;
}
const prefix = `[${formatDate(new Date())}] [${levelName}]: `;
if (data instanceof Error) {
this.appendLine(`${prefix}${(_a = data.stack) !== null && _a !== void 0 ? _a : data.toString()}`);
void import_coc3.window.showErrorMessage(data.message);
if (isTest) {
console.error((_b = data.stack) !== null && _b !== void 0 ? _b : data.toString());
}
return;
}
this.appendLine(`${prefix}${data}`);
if (levelNum > levelErrorNum) {
void import_coc3.window.showErrorMessage(data);
if (isTest) {
console.error(data);
}
}
};
this.trace = (line) => {
this.log("trace", line);
};
this.debug = (line) => {
this.log("debug", line);
};
this.info = (line) => {
this.log("info", line);
};
this.warn = (line) => {
this.log("warn", line);
};
this.error = (data) => {
if (!(data instanceof Error)) {
data = new Error(data);
}
this.log("error", data);
};
this.fatal = (data) => {
this.log("fatal", data);
};
}
set level(level) {
this.levelStatus = level;
this.levelNumber = levelList[level];
}
get level() {
return this.levelStatus;
}
dispose() {
var _a;
(_a = this.outputChannel_) === null || _a === void 0 ? void 0 : _a.dispose();
}
get outputChannel() {
if (!this.outputChannel_) {
this.outputChannel_ = import_coc3.window.createOutputChannel(this.channelName);
}
return this.outputChannel_;
}
time(label = "default") {
this.timeMarkers.set(label, new Date().valueOf());
}
timeElapsed(label = "default") {
const time = this.timeMarkers.get(label);
if (time !== void 0) {
return new Date().valueOf() - time;
}
}
timeLog(label = "default") {
const time = this.timeElapsed(label);
if (time !== void 0) {
this.appendLine(`${label}: ${time} ms`);
}
}
measureTime(task) {
const time = new Date().valueOf();
const result = task();
if (!("then" in result)) {
return [result, new Date().valueOf() - time];
}
return result.then((r) => {
return [r, new Date().valueOf() - time];
});
}
measureTask(task, label = "default", level = "info") {
const response = this.measureTime(task);
if (!("then" in response)) {
const [result, time] = response;
this.log(level, `[measureTask] ${label}: ${time} ms`);
return result;
}
return response.then(([result, time]) => {
this.log(level, `${label}: ${time} ms`);
return result;
});
}
asyncCatch(fn) {
return async (...args) => {
try {
return await fn(...args);
} catch (e) {
this.error(e);
}
};
}
prettyPrint(...data) {
this.info(prettyObject(...data));
void import_coc3.window.showErrorMessage(`[${formatDate(new Date())}] ${prettyObject(...data)}`);
}
};
var helperLogger = new HelperLogger("coc-helper");
function prettyObject(...data) {
return data.map((d) => import_util.default.inspect(d)).join(" ");
}
// node_modules/coc-helper/lib/esm/_package.json
var package_default = {
name: "coc-helper",
version: "0.15.2",
description: "Helpers for coc.nvim",
module: "lib/esm/index.js",
main: "lib/cjs/index.js",
homepage: "https://github.com/weirongxu/coc-helper",
repository: "git@github.com:weirongxu/coc-helper.git",
author: "Weirong Xu <weirongxu.raidou@gmail.com>",
license: "MIT",
files: [
"lib",
"tests",
"jest.config.js",
"JestHelper.js",
"JestHelper.d.ts"
],
scripts: {
clean: "rimraf lib",
"copy:pkg": "cpy --rename=_package.json package.json src/",
"build:esm": "tsc -p ./tsconfig.prod.json --module es2020 --outDir lib/esm",
"build:cjs": "tsc -p ./tsconfig.prod.json --module commonjs --outDir lib/cjs",
build: "npm-run-all clean copy:pkg build:esm build:cjs",
lint: "eslint src --ext ts",
"setup:test-env": "node ./tests/setup.js",
prepare: "run-s clean setup:test-env build",
unittest: "jest --runInBand --detectOpenHandles --forceExit",
test: "npm-run-all copy:pkg lint unittest"
},
engines: {
coc: "^0.0.77"
},
activationEvents: [
"*"
],
prettier: {
singleQuote: true,
printWidth: 80,
semi: true,
trailingComma: "all"
},
peerDependencies: {
"coc.nvim": "*"
},
devDependencies: {
"@chemzqm/neovim": "^5.7.10",
"@raidou/eslint-config-base": "^1.5.0",
"@types/eslint": "^8.4.6",
"@types/jest": "^29.0.2",
"@types/node": "^18.7.18",
"@types/rimraf": "^3.0.2",
"@types/uuid": "^8.3.4",
"coc.nvim": "0.0.82",
"cpy-cli": "^4.2.0",
eslint: "^8.23.1",
jest: "^29.0.3",
log4js: "^6.6.1",
"npm-run-all": "^4.1.5",
prettier: "^2.7.1",
"ts-jest": "^29.0.1",
"type-fest": "^2.19.0",
typescript: "^4.8.3"
},
dependencies: {
rimraf: "^3.0.2",
uuid: "^9.0.0"
}
};
// node_modules/coc-helper/lib/esm/util/version.js
var version = package_default.version;
var versionName = version.replace(/[.-]/g, "_");
// node_modules/coc-helper/lib/esm/notifier.js
var Notifier = class {
constructor(notify) {
this.notifyFns = [];
this.notifyFns.push(notify);
}
static async run(notifier) {
if (!notifier) {
return;
}
if ("then" in notifier) {
const awaitedNotifier = await notifier;
if (awaitedNotifier) {
return awaitedNotifier.run();
}
} else {
return notifier.run();
}
}
static notifyAll(lazyNotifies) {
for (const n of lazyNotifies) {
if (n) {
n.notify();
}
}
}
static async runAll(notifierPromises) {
const notifiers = await Promise.all(notifierPromises);
import_coc4.workspace.nvim.pauseNotification();
this.notifyAll(notifiers);
return import_coc4.workspace.nvim.resumeNotification();
}
static combine(notifiers) {
const compactedNotifiers = compactI(notifiers);
if (compactedNotifiers.length < 1) {
return Notifier.noop();
}
if (compactedNotifiers.length === 1) {
return compactedNotifiers[0];
}
return compactedNotifiers.reduce((ret, cur) => ret.concat(cur), Notifier.noop());
}
static noop() {
return this.create(() => {
});
}
static create(notify) {
return new Notifier(notify);
}
async run() {
return Notifier.runAll([this]);
}
notify() {
for (const fn of this.notifyFns) {
fn();
}
}
concat(notifier) {
this.notifyFns.push(...notifier.notifyFns);
return this;
}
};
// node_modules/coc-helper/lib/esm/util/module.js
var globalModuleIdKey = "__coc_helper_module_max_id";
function getModuleId(key) {
const globalKey2 = `${globalModuleIdKey}_${key}`;
if (!(globalKey2 in global)) {
global[globalKey2] = 0;
}
global[globalKey2] += 1;
return global[globalKey2];
}
// node_modules/coc-helper/lib/esm/VimModule.js
var mid = getModuleId("VimModule");
var globalKey = `coc_helper_module_m${mid}_v${versionName}`;
var globalVariable = `g:${globalKey}`;
var callFunc = `CocHelperCallFn_m${mid}_v${versionName}`;
var declareVar = `CocHelperCallVar_m${mid}_v${versionName}`;
function filterLineCont(content) {
return content.replace(/\n\s*\\/g, "");
}
var VimModule = class {
constructor(moduleKey) {
this.moduleKey = moduleKey;
}
static async init(context) {
this.inited = true;
await import_coc5.workspace.nvim.call("execute", `
if !exists('${globalVariable}')
let ${globalVariable} = {}
endif
function! ${callFunc}(module_key, method_name, args)
try
return call(${globalVariable}[a:module_key][a:method_name], a:args)
catch
let ex = v:exception
let msg = printf('error when call %s.%s.%s, args: [%s]', '${globalVariable}', a:module_key, a:method_name, join(a:args, ','))
echom msg
echom ex
throw msg . ' ' . ex
endtry
endfunction
function! ${declareVar}(module_key, var_name, expression)
try
let ${globalVariable}[a:module_key][a:var_name] = eval(a:expression)
catch
let ex = v:exception
let msg = printf('error when declare %s.%s.%s, expression: %s', '${globalVariable}', a:module_key, a:var_name, a:expression)
echom msg
echom ex
throw msg . ' ' . ex
endtry
endfunction
`);
const queue = [...this.initQueue];
while (queue.length) {
const it = queue.shift();
try {
await it.fn(context);
} catch (error) {
helperLogger.error(error);
}
if (this.initAfterQueue.length) {
queue.push(...this.initAfterQueue);
this.initAfterQueue = [];
}
}
}
static registerInit(description, fn) {
if (!this.inited) {
this.initQueue.push({ description, fn });
} else {
this.initAfterQueue.push({ description, fn });
}
}
static create(moduleName, cb) {
const id = getModuleId("VimModule.module");
const moduleKey = `${id}_${moduleName}`;
const vMod = new VimModule(moduleKey);
let mod = void 0;
function initedMod() {
if (!mod) {
mod = cb(vMod);
}
return mod;
}
VimModule.registerInit(`module ${moduleKey}`, async () => {
await import_coc5.workspace.nvim.call("execute", `
if !exists('${globalVariable}.${moduleKey}')
let ${globalVariable}.${moduleKey} = {}
endif
`);
initedMod();
});
return new Proxy({}, {
get(_o, key) {
return Reflect.get(initedMod(), key);
},
has(_o, key) {
return key in initedMod();
},
ownKeys() {
return Object.keys(initedMod());
}
});
}
registerInit(description, fn) {
if (typeof description === "string") {
return VimModule.registerInit(description, fn);
} else {
return this.registerInit("", description);
}
}
fn(fnName, getContent) {
const { nvim } = import_coc5.workspace;
const name = `${globalVariable}.${this.moduleKey}.${fnName}`;
const content = getContent({ name });
this.registerInit(`fn ${name}`, async () => {
helperLogger.debug(`declare fn ${name}`);
await nvim.call("execute", [filterLineCont(content)]);
});
return {
name,
inlineCall: (argsExpression = "") => `${callFunc}('${this.moduleKey}', '${fnName}', [${argsExpression}])`,
call: (...args) => {
helperLogger.debug(`call ${name}`);
return nvim.call(callFunc, [
this.moduleKey,
fnName,
args
]);
},
callNotify: (...args) => {
helperLogger.debug(`callNotify ${name}`);
return nvim.call(callFunc, [this.moduleKey, fnName, args], true);
},
callNotifier: (...args) => {
helperLogger.debug(`callNotifier ${name}`);
return Notifier.create(() => {
nvim.call(callFunc, [this.moduleKey, fnName, args], true);
});
}
};
}
var(varName, expression) {
const { nvim } = import_coc5.workspace;
const name = `${globalVariable}.${this.moduleKey}.${varName}`;
this.registerInit(`var ${name}`, async () => {
helperLogger.debug(`declare var ${name}`);
await nvim.call(declareVar, [
this.moduleKey,
varName,
filterLineCont(expression)
]);
});
return {
name,
inline: name,
get: () => {
return nvim.eval(name);
},
set: async (expression2) => {
await nvim.call(declareVar, [
this.moduleKey,
varName,
filterLineCont(expression2)
]);
},
setNotify: (expression2) => {
nvim.call(declareVar, [this.moduleKey, varName, filterLineCont(expression2)], true);
},
setNotifier: (expression2) => {
return Notifier.create(() => {
nvim.call(declareVar, [this.moduleKey, varName, filterLineCont(expression2)], true);
});
}
};
}
};
VimModule.inited = false;
VimModule.initQueue = [];
VimModule.initAfterQueue = [];
// node_modules/coc-helper/lib/esm/modules/util.js
var import_coc6 = require("coc.nvim");
var utilModule = VimModule.create("util", (m) => {
const isNvim = import_coc6.workspace.isNvim;
return {
globalCursorPosition: m.fn("global_cursor_position", ({ name }) => `
function! ${name}()
let nr = winnr()
let [row, col] = win_screenpos(nr)
return [row + winline() - 2, col + wincol() - 2]
endfunction
`),
isFloat: m.fn("is_float", ({ name }) => isNvim ? `
function! ${name}(winnr) abort
if !exists('*nvim_win_get_config')
return v:false
endif
let winid = win_getid(a:winnr)
return nvim_win_get_config(winid)['relative'] != ''
endfunction
` : `
function! ${name}(winnr) abort
return v:false
endfunction
`),
closeWinByBufnr: m.fn("close_win_by_bufnr", ({ name }) => `
if exists('*nvim_win_close')
function! ${name}(bufnrs) abort
for bufnr in a:bufnrs
try
let winid = bufwinid(bufnr)
if winid >= 0
call nvim_win_close(winid, v:true)
endif
catch
endtry
endfor
endfunction
else
function! ${name}(bufnrs) abort
for bufnr in a:bufnrs
try
let winnr = bufwinnr(bufnr)
if winnr >= 0
execute winnr . 'wincmd c'
endif
catch
endtry
endfor
endfunction
endif
`),
runCocCmd: m.fn("run_coc_cmd", ({ name }) => `
function! ${name}(name, ...) abort
return call('CocAction', extend(['runCommand', a:name], a:000))
endfunction
`),
runCocCmdAsync: m.fn("run_coc_cmd_async", ({ name }) => `
function! ${name}(name, ...) abort
return call('CocActionAsync', extend(['runCommand', a:name], a:000))
endfunction
`)
};
});
// node_modules/coc-helper/lib/esm/events.js
var mid2 = getModuleId("events");
var uname = `m${mid2}_v${versionName}`;
var HelperEventEmitter = class {
constructor(helperLogger2, concurrent = false) {
this.helperLogger = helperLogger2;
this.concurrent = concurrent;
this.listenersMap = /* @__PURE__ */ new Map();
}
listeners(event) {
if (!this.listenersMap.has(event)) {
const listeners = [];
this.listenersMap.set(event, listeners);
return listeners;
}
return this.listenersMap.get(event);
}
once(event, listener, disposables) {
this.listeners(event).push(async (...args) => {
const result = await listener(...args);
disposable.dispose();
return result;
});
const disposable = import_coc7.Disposable.create(() => this.off(event, listener));
if (disposables) {
disposables.push(disposable);
}
return disposable;
}
on(event, listener, disposables) {
this.listeners(event).push(listener);
const disposable = import_coc7.Disposable.create(() => this.off(event, listener));
if (disposables) {
disposables.push(disposable);
}
return disposable;
}
off(event, listener) {
if (typeof listener.cancel === "function") {
listener.cancel();
}
const listeners = this.listeners(event);
const index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
}
}
async fire(event, ...args) {
if (this.concurrent) {
await Promise.all(this.listeners(event).map(async (listener) => {
try {
await listener(...args);
} catch (e) {
this.helperLogger.error(e);
}
}));
} else {
for (const listener of this.listeners(event)) {
try {
await listener(...args);
} catch (e) {
this.helperLogger.error(e);
}
}
}
}
};
var HelperVimEvents = class {
constructor(vimEvents, helperLogger2, options = {}) {
var _a;
this.vimEvents = vimEvents;
this.helperLogger = helperLogger2;
this.options = options;
this.id = getModuleId("events.id");
this.augroupName = `CocHelperInternal_${uname}_${options.name ? `${options.name}_` : ""}${this.id}`;
this.commandName = `coc-helper.internal.didVimEvent_${uname}_${options.name ? `${options.name}_` : ""}${this.id}`;
this.events = new HelperEventEmitter(this.helperLogger, (_a = options.concurrent) !== null && _a !== void 0 ? _a : false);
}
async register(context) {
await eventsModule.activate.call(this.augroupName, this.commandName, Object.entries(this.vimEvents).map(([key, e]) => Object.assign({ event: key }, e)));
context.subscriptions.push(import_coc7.Disposable.create(() => {
eventsModule.deactivate.call(this.augroupName).catch(this.helperLogger.error);
}));
context.subscriptions.push(import_coc7.commands.registerCommand(this.commandName, helperLogger.asyncCatch((event, ...args) => this.events.fire(event, ...args)), void 0, true));
}
};
var helperVimEvents = new HelperVimEvents({
BufDelete: {
eventExpr: "BufDelete *",
argExprs: ["+expand('<abuf>')"]
},
BufWipeout: {
eventExpr: "BufWipeout *",
argExprs: ["+expand('<abuf>')"]
}
}, helperLogger, {
name: "coc_helper"
});
var helperEvents = helperVimEvents.events;
var eventsModule = VimModule.create("events", (m) => {
const activate2 = m.fn("activate", ({ name }) => `
function! ${name}(augroup_name, autocmd_events) abort
execute 'augroup ' . a:augroup_name
autocmd!
for autocmd_event in a:autocmd_events
execute autocmd_event
endfor
augroup END
endfunction
`);
function getActivateEvents(commandName, activateEvents) {
return activateEvents.map((e) => {
var _a;
const args = `${[
`'${commandName}'`,
`'${e.event}'`,
...(_a = e.argExprs) !== null && _a !== void 0 ? _a : []
].join(", ")}`;
return `autocmd ${e.eventExpr} call ${e.async === false ? utilModule.runCocCmd.inlineCall(args) : utilModule.runCocCmdAsync.inlineCall(args)}`;
});
}
return {
activate: {
call: (augroupName, commandName, activateEvents) => activate2.call(augroupName, getActivateEvents(commandName, activateEvents)),
callNotify: (augroupName, commandName, activateEvents) => activate2.callNotify(augroupName, getActivateEvents(commandName, activateEvents)),
callNotifier: (augroupName, commandName, activateEvents) => activate2.callNotifier(augroupName, getActivateEvents(commandName, activateEvents))
},
deactivate: m.fn("deactivate", ({ name }) => `
function! ${name}(augroup_name) abort
execute 'augroup ' . a:augroup_name
autocmd!
augroup END
endfunction
`),
doAutocmd: m.fn("do_autocmd", ({ name }) => `
function! ${name}(name) abort
if exists('#User#'.a:name)
exe 'doautocmd <nomodeline> User '.a:name
endif
endfunction
`)
};
});
// node_modules/coc-helper/lib/esm/FloatingWindow.js
var import_coc11 = require("coc.nvim");
// node_modules/coc-helper/lib/esm/modules/floating.js
var import_coc9 = require("coc.nvim");
// node_modules/coc-helper/lib/esm/modules/buf.js
var import_coc8 = require("coc.nvim");
var bufModule = VimModule.create("buf", (m) => {
const isNvim = import_coc8.workspace.isNvim;
const createByName = m.fn("create_by_name", ({ name }) => `
function! ${name}(name) abort
return bufadd(a:name)
endfunction
`);
return {
createByName,
create: m.fn("create", ({ name }) => isNvim ? `
function! ${name}(...) abort
let name = get(a:000, 0, '')
if name is ''
return nvim_create_buf(v:false, v:true)
else
return ${createByName.inlineCall("name")}
endif
endfunction
` : `
function! ${name}(...) abort
let name = get(a:000, 0, '')
return ${createByName.inlineCall("name")}
endfunction
`)
};
});
// node_modules/coc-helper/lib/esm/modules/floating.js
var floatingModule = VimModule.create("float", (m) => {
const isNvim = import_coc9.workspace.isNvim;
const initExecute = m.fn("init_execute", ({ name }) => `
function! ${name}(ctx, inited_execute) abort
execute a:inited_execute
endfunction
`);
const openWin = m.fn("open_win", ({ name }) => isNvim ? `
function! ${name}(bufnr, focus, win_config, win_hl, inited_execute) abort
noau let winid = nvim_open_win(a:bufnr, a:focus, a:win_config)
if !empty(a:win_hl)
call nvim_win_set_option(winid, 'winhl', a:win_hl)
endif
if !empty(a:inited_execute)
call ${initExecute.inlineCall("{'bufnr': a:bufnr, 'winid': winid}, a:inited_execute")}
endif
return winid
endfunction
` : `
function! ${name}(bufnr, focus, win_config, win_hl, inited_execute) abort
let winid = popup_create(a:bufnr, a:win_config)
call ${initExecute.inlineCall("{'bufnr': a:bufnr, 'winid': winid}, a:inited_execute")}
return winid
endfunction
`);
return {
create: m.fn("create", ({ name }) => isNvim ? `
function! ${name}(name, inited_execute, has_border_buf, border_inited_execute) abort
let bufnr = ${bufModule.create.inlineCall("a:name")}
call ${initExecute.inlineCall("{'bufnr': bufnr}, a:inited_execute")}
let border_bufnr = v:null
if a:has_border_buf
let border_bufnr = nvim_create_buf(v:false, v:true)
call ${initExecute.inlineCall("{'bufnr': border_bufnr}, a:border_inited_execute")}
endif
return [bufnr, border_bufnr]
endfunction
` : `
function! ${name}(name, inited_execute, has_border_buf, border_inited_execute) abort
let bufnr = ${bufModule.create.inlineCall("a:name")}
call ${initExecute.inlineCall("{'bufnr': bufnr}, a:inited_execute")}
return [bufnr, v:null]
endfunction
`),
open: m.fn("open", ({ name }) => `
function! ${name}(bufnr, win_config, inited_execute, border_bufnr, border_win_config, border_inited_execute, focus, win_hl) abort
let winid = ${openWin.inlineCall("a:bufnr, a:focus, a:win_config, a:win_hl, a:inited_execute")}
call setbufvar(a:bufnr, 'coc_helper_winid', winid)
if a:border_bufnr
let border_winid = ${openWin.inlineCall("a:border_bufnr, v:false, a:border_win_config, a:win_hl, a:border_inited_execute")}
call setbufvar(a:bufnr, 'coc_helper_border_winid', border_winid)
endif
endfunction
`),
resume: m.fn("resume", ({ name }) => `
function! ${name}(bufnr, win_config, border_bufnr, border_win_config, focus, win_hl) abort
let winid = ${openWin.inlineCall("a:bufnr, a:focus, a:win_config, a:win_hl, ''")}
call setbufvar(a:bufnr, 'coc_helper_winid', winid)
if a:border_bufnr
let border_winid = ${openWin.inlineCall("border_bufnr, v:false, a:border_win_config, a:win_hl, ''")}
call setbufvar(a:bufnr, 'coc_helper_border_winid', border_winid)
endif
endfunction
`),
update: m.fn("update", ({ name }) => isNvim ? `
function! ${name}(bufnr, win_config, border_bufnr, border_win_config, win_hl) abort
let winid = getbufvar(a:bufnr, 'coc_helper_winid', v:null)
if !winid
return
endif
call nvim_win_set_config(winid, a:win_config)
if !empty(a:win_hl)
call nvim_win_set_option(winid, 'winhl', a:win_hl)
endif
if has('nvim')
redraw!
endif
if a:border_bufnr
let border_winid = getbufvar(a:bufnr, 'coc_helper_border_winid', v:null)
if border_winid
call nvim_win_set_config(border_winid, a:border_win_config)
if !empty(a:win_hl)
call nvim_win_set_option(border_winid, 'winhl', a:win_hl)
endif
if has('nvim')
redraw!
endif
endif
endif
endfunction
` : `
function! ${name}(bufnr, win_config, border_bufnr, border_win_config, win_hl) abort
let winid = getbufvar(a:bufnr, 'coc_helper_winid', v:null)
if !winid
return
endif
call popup_setoptions(winid, a:win_config)
endfunction
`),
winid: m.fn("winid", ({ name }) => `
function! ${name}(bufnr) abort
let id = getbufvar(a:bufnr, 'coc_helper_winid', v:null)
let nr = win_id2win(id)
return nr is 0 ? v:null : id
endfunction
`),
borderWinid: m.fn("border_winid", ({ name }) => `
function! ${name}(bufnr) abort
return getbufvar(a:bufnr, 'coc_helper_border_winid', v:null)
endfunction
`),
close: m.fn("close", ({ name }) => isNvim ? `
function! ${name}(bufnr) abort
let winid = getbufvar(a:bufnr, 'coc_helper_winid', v:null)
let border_winid = getbufvar(a:bufnr, 'coc_helper_border_winid', v:null)
try
if winid
call nvim_win_close(winid, v:true)
endif
if border_winid
call nvim_win_close(border_winid, v:true)
endif
catch
endtry
endfunction
` : `
function! ${name}(bufnr) abort
let winid = getbufvar(a:bufnr, 'coc_helper_winid', v:null)
try
if winid
call popup_close(winid)
endif
catch
endtry
endfunction
`)
};
});
// node_modules/coc-helper/lib/esm/FloatingUtil.js
var import_coc10 = require("coc.nvim");
var defaultBorderChars = ["\u2500", "\u2502", "\u2500", "\u2502", "\u250C", "\u2510", "\u2518", "\u2514"];
var defaultWinHl = "CocHelperNormalFloat";
var defaultWinHlNC = "CocHelperNormalFloatNC";
var defaultBorderWinHl = "CocHelperNormalFloatBorder";
var FloatingUtil = class {
constructor(srcId) {
this.srcId = srcId;
}
async createContext(options) {
var _a, _b;
return (_a = options.context) !== null && _a !== void 0 ? _a : {
lines: import_coc10.workspace.env.lines,
columns: import_coc10.workspace.env.columns - import_coc10.workspace.env.cmdheight - 1,
globalCursorPosition: await utilModule.globalCursorPosition.call(),
title: options.title ? {
text: options.title,
width: await displayWidth(options.title)
} : { text: "", width: 0 },
borderEnabled: !!options.border,
border: this.extendEdges((_b = options.border) === null || _b === void 0 ? void 0 : _b.map((b) => typeof b === "boolean" ? 1 : b)),
paddingEnabled: !!options.padding,
padding: this.extendEdges(options.padding)
};
}
getCenterPos(ctx, box) {
const [, , width, height] = box;
const top = Math.floor((ctx.lines - height) / 2);
const left = Math.floor((ctx.columns - width) / 2);
return [top, left];
}
getPosForAround(ctx, size, cursorPosition, preferAbove = false) {
const columns = ctx.columns;
const lines = ctx.lines - 1;
const [width, height] = size;
let [top, left] = cursorPosition;
if (preferAbove) {
if (top - height < 0) {
top += 1;
} else {
top -= height;
}
} else {
if (top + height >= lines) {
top -= height;
} else {
top += 1;
}
}
if (left + width >= columns) {
left -= width - 1;
}
return [top, left];
}
extendEdges(edges) {
var _a, _b, _c, _d;
if (!edges) {
return [0, 0, 0, 0];
}
const top = (_a = edges[0]) !== null && _a !== void 0 ? _a : 1;
const right = (_b = edges[1]) !== null && _b !== void 0 ? _b : top;
const bottom = (_c = edges[2]) !== null && _c !== void 0 ? _c : top;
const left = (_d = edges[3]) !== null && _d !== void 0 ? _d : right;
return [top, right, bottom, left];
}
changeBoxByEdgesList(box, edgesList) {
let retBox = [...box];
for (const edges of edgesList) {
retBox = this.changeBoxByEdges(retBox, edges);
}
return retBox;
}
changeBoxByEdges(box, edges) {
if (!edges) {
return box;
}
const [wTop, wRight, wBottom, wLeft] = edges;
let [top, left, width, height] = box;
top -= wTop;
left -= wLeft;
width += wLeft + wRight;
height += wTop + wBottom;
return [top, left, width, height];
}
getBoxSizes(ctx, options, updateCursorPosition) {
var _a, _b;
const [top, left] = [(_a = options.top) !== null && _a !== void 0 ? _a : 0, (_b = options.left) !== null && _b !== void 0 ? _b : 0];
const width = Math.max(options.width, ctx.title.width);
const contentBox = [0, 0, width, options.height];
const paddingBox = this.changeBoxByEdges(contentBox, ctx.padding);
const borderBox = this.changeBoxByEdges(paddingBox, ctx.border);
let fullPos;
if (options.relative === "center") {
fullPos = this.getCenterPos(ctx, borderBox);
} else {
const cursorPosition = !updateCursorPosition && this.storeCursorPosition ? this.storeCursorPosition : ctx.globalCursorPosition;
if (options.relative === "cursor") {
fullPos = cursorPosition;
} else if (options.relative === "cursor-around") {
fullPos = this.getPosForAround(ctx, [borderBox[2], borderBox[3]], cursorPosition);
} else {
fullPos = [top, left];
}
this.storeCursorPosition = cursorPosition;
}
[borderBox[0], borderBox[1]] = [fullPos[0], fullPos[1]];
[paddingBox[0], paddingBox[1]] = [
borderBox[0] + ctx.border[0],
borderBox[1] + ctx.border[3]
];
[contentBox[0], contentBox[1]] = [
paddingBox[0] + ctx.padding[0],
paddingBox[1] + ctx.padding[3]
];
return {
contentBox,
paddingBox,
borderBox
};
}
vimWinConfig(ctx, options, updateCursorPosition) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const [top, left, width, height] = [
(_a = options.top) !== null && _a !== void 0 ? _a : 0,
(_b = options.left) !== null && _b !== void 0 ? _b : 0,
options.width,
options.height
];
const config = {
line: 0,
col: 0,
zindex: ((_c = options.borderOnly) !== null && _c !== void 0 ? _c : false) ? 1 : 100,
minwidth: width,
minheight: height,
maxwidth: width,
maxheight: height
};
if (options.relative === "center") {
config.pos = "center";
} else {
const cursorPosition = !updateCursorPosition && this.storeCursorPosition ? this.storeCursorPosition : ctx.globalCursorPosition;
if (options.relative === "cursor") {
[config.line, config.col] = cursorPosition;
} else if (options.relative === "cursor-around") {
const box = this.changeBoxByEdgesList([top, left, width, height], [ctx.padding, ctx.border]);
[config.line, config.col] = this.getPosForAround(ctx, [box[2], box[3]], cursorPosition);
} else {
[config.line, config.col] = [top, left];
}
this.storeCursorPosition = cursorPosition;
config.line += 1;
config.col += 1;
}
const topOffset = (_d = options.topOffset) !== null && _d !== void 0 ? _d : 0;
const leftOffset = (_e = options.leftOffset) !== null && _e !== void 0 ? _e : 0;
config.line += topOffset;
config.col += leftOffset;
if (options.maxWidth) {
config.maxwidth = options.maxWidth;
}
if (options.maxHeight) {
config.maxheight = options.maxHeight;
}
config.highlight = (_f = options.winHl) !== null && _f !== void 0 ? _f : defaultWinHl;
if (options.padding) {
config.padding = options.padding;
}
if (ctx.borderEnabled) {
config.border = ctx.border;
if (config.border[0]) {
if (ctx.title.width) {
config.title = ctx.title.text;
}
config.close = "button";
}
config.borderchars = (_g = options.borderChars) !== null && _g !== void 0 ? _g : defaultBorderChars;
config.borderhighlight = [(_h = options.borderWinHl) !== null && _h !== void 0 ? _h : defaultBorderWinHl];
}
return config;
}
nvimWinConfig(ctx, options, updateCursorPosition) {
var _a, _b, _c;
const { contentBox, borderBox } = this.getBoxSizes(ctx, options, updateCursorPosition);
const topOffset = (_a = options.topOffset) !== null && _a !== void 0 ? _a : 0;
const leftOffset = (_b = options.leftOffset) !== null && _b !== void 0 ? _b : 0;
const winConfig = {
relative: "editor",
row: contentBox[0] + topOffset,
col: contentBox[1] + leftOffset,
width: contentBox[2],
height: contentBox[3],
focusable: (_c = options.focusable) !== null && _c !== void 0 ? _c : true
};
let winConfigBorder;
if (borderBox) {
winConfigBorder = {
relative: "editor",
row: borderBox[0] + topOffset,
col: borderBox[1] + leftOffset,
width: borderBox[2],
height: borderBox[3],
focusable: false
};
}
return [winConfig, winConfigBorder];
}
winConfig(ctx, options, updateCursorPosition = true) {
return import_coc10.workspace.isVim ? [this.vimWinConfig(ctx, options, updateCursorPosition), void 0] : this.nvimWinConfig(ctx, options, updateCursorPosition);
}
getRenderBorderData(ctx, options, winOptions) {
var _a, _b, _c, _d, _e, _f;
const title = (_b = (_a = ctx.title) === null || _a === void 0 ? void 0 : _a.text) !== null && _b !== void 0 ? _b : "";
const titleWidth = (_d = (_c = ctx.title) === null || _c === void 0 ? void 0 : _c.width) !== null && _d !== void 0 ? _d : 0;
if (!ctx.borderEnabled) {
return;
}
const [bTop, bRight, bBottom, bLeft] = ctx.border;
let [cTop, cRight, cBottom, cLeft, cTopleft, cTopright, cBotright, cBotleft] = (_e = options.borderChars) !== null && _e !== void 0 ? _e : defaultBorderChars;
if (!bTop) {
cTop = "";
}
if (!bRight) {
cRight = "";
}
if (!bBottom) {
cBottom = "";
}
if (!bLeft) {
cLeft = "";
}
if (!bTop || !bLeft) {
cTopleft = "";
}
if (!bTop || !bRight) {
cTopright = "";
}
if (!bBottom || !bLeft) {
cBotleft = "";
}
if (!bBottom || !bRight) {
cBotright = "";
}
const width = winOptions[0];
const height = winOptions[1];
const spaceWidth = width - bLeft - bRight;
const spaceHeight = height - bTop - bBottom;
const lines = [];
if (bTop) {
lines.push(cTopleft + title + cTop.repeat(spaceWidth - titleWidth) + cTopright);
}
lines.push(...Array.from({ length: spaceHeight }, () => cLeft + " ".repeat(spaceWidth) + cRight));
if (bBottom) {
lines.push(cBotleft + cBottom.repeat(spaceWidth) + cBotright);
}
const highlights = [];
const borderWinHl = (_f = options.borderWinHl) !== null && _f !== void 0 ? _f : defaultBorderWinHl;
if (borderWinHl) {
highlights.push({
hlGroup: borderWinHl,
line: 0,
colStart: 0,
colEnd: width
});
for (let l = 0, len = spaceHeight; l < len; l++) {
if (bLeft) {
highlights.push({
hlGroup: borderWinHl,
line: l + 1,
colStart: 0,
colEnd: bLeft
});
}
if (bRight) {
highlights.push({
hlGroup: borderWinHl,
line: l + 1,
colStart: bLeft + spaceWidth,
colEnd: width
});
}
}
if (bBottom) {
highlights.push({
hlGroup: borderWinHl,
line: height - 1,
colStart: 0,
colEnd: width
});
}
}
return {
lines,
highlights
};
}
renderBorderNotifier(buf, ctx, options, winOptions) {
const renderData = this.getRenderBorderData(ctx, options, "width" in winOptions ? [winOptions.width, winOptions.height] : [winOptions.minwidth, winOptions.minheight]);
if (!renderData) {
return Notifier.noop();
}
const { lines, highlights } = renderData;
return Notifier.create(() => {
buf.setOption("modifiable", true, true);
buf.setOption("readonly", false, true);
void buf.setLines(lines, { start: 0, end: -1 }, true);
buf.setOption("modifiable", false, true);
buf.setOption("readonly", true, true);
this.addHighlightsNotify(buf, highlights);
});
}
nvimWinHl(options) {
var _a, _b;
if (import_coc10.workspace.isVim) {
return "";
}
const arr = [];
arr.push(`Normal:${(_a = options.winHl) !== null && _a !== void 0 ? _a : defaultWinHl}`);
arr.push(`NormalNC:${(_b = options.winHlNC) !== null && _b !== void 0 ? _b : defaultWinHlNC}`);
return arr.join(",");
}
addHighlightsNotify(buf, highlights) {
for (const hl of highlights) {
if (!hl.hlGroup || hl.line === void 0 || hl.colStart === void 0 || hl.colEnd === void 0) {
continue;
}
buf.highlightRanges(this.srcId, hl.hlGroup, [
import_coc10.Range.create(hl.line, hl.colStart, hl.line, hl.colEnd)
]);
}
}
};
// node_modules/coc-helper/lib/esm/FloatingWindow.js
var FloatingWindow = class {
constructor(bufnr, borderBufnr, createOptions, mode, util3) {
this.bufnr = bufnr;
this.borderBufnr = borderBufnr;
this.createOptions = createOptions;
this.mode = mode;
this.util = util3;
this.nvim = import_coc11.workspace.nvim;
this.disposables = [];
this.nvim = import_coc11.workspace.nvim;
this.buffer = this.nvim.createBuffer(bufnr);
if (borderBufnr) {
this.borderBuffer = import_coc11.workspace.nvim.createBuffer(borderBufnr);
this.disposables.push(import_coc11.events.on("BufWinLeave", helperLogger.asyncCatch(async (curBufnr) => {
if (this.borderBufnr && curBufnr === this.bufnr) {
await utilModule.closeWinByBufnr.call([this.borderBufnr]);
}
})));
}
}
static getInitedExecute(mode, options) {
var _a, _b, _c, _d;
let initedExecute = (_b = (_a = options.initedExecute) === null || _a === void 0 ? void 0 : _a.call(options, FloatingWindow.initedContextVars.create)) !== null && _b !== void 0 ? _b : "";
initedExecute = `${FloatingWindow.modePresets[mode].createInitedExecute(FloatingWindow.initedContextVars.create)}
${initedExecute}`;
const borderInitedExecute = (_d = (_c = options.borderInitedExecute) === null || _c === void 0 ? void 0 : _c.call(options, FloatingWindow.initedContextVars.create)) !== null && _d !== void 0 ? _d : FloatingWindow.modePresets.show.createInitedExecute(FloatingWindow.initedContextVars.create);
return [initedExecute, borderInitedExecute];
}
static async create(options = {}) {
var _a, _b, _c;
const mode = (_a = options.mode) !== null && _a !== void 0 ? _a : "default";
const [initedExecute, borderInitedExecute] = this.getInitedExecute(mode, options);
const [bufnr, borderBufnr] = await floatingModule.create.call((_b = options.name) !== null && _b !== void 0 ? _b : "", initedExecute, (_c = options.hasBorderBuf) !== null && _c !== void 0 ? _c : true, borderInitedExecute);
const floatingUtil = new FloatingUtil(this.srcId);
return new FloatingWindow(bufnr, borderBufnr !== null && borderBufnr !== void 0 ? borderBufnr : void 0, options, mode, floatingUtil);
}
getInitedExecute(options) {
var _a, _b, _c, _d;
let initedExecute = (_b = (_a = options.initedExecute) === null || _a === void 0 ? void 0 : _a.call(options, FloatingWindow.initedContextVars.open)) !== null && _b !== void 0 ? _b : "";
initedExecute = `${FloatingWindow.modePresets[this.mode].openInitedExecute(FloatingWindow.initedContextVars.open)}
${initedExecute}`;
const borderInitedExecute = (_d = (_c = options.borderInitedExecute) === null || _c === void 0 ? void 0 : _c.call(options, FloatingWindow.initedContextVars.open)) !== null && _d !== void 0 ? _d : FloatingWindow.modePresets.show.openInitedExecute(FloatingWindow.initedContextVars.open);
return [initedExecute, borderInitedExecute];
}
getFocus(options) {
var _a, _b;
return (_b = (_a = options.focus) !== null && _a !== void 0 ? _a : this.mode ? FloatingWindow.modePresets[this.mode].focus : void 0) !== null && _b !== void 0 ? _b : false;
}
getModifiable(options) {
var _a, _b;
return (_b = (_a = options.modifiable) !== null && _a !== void 0 ? _a : this.mode ? FloatingWindow.modePresets[this.mode].modifiable : void 0) !== null && _b !== void 0 ? _b : false;
}
setLinesNotifier(options) {
return Notifier.create(() => {
if (!options.lines && !options.modifiable) {
return;
}
const modifiable = this.getModifiable(options);
this.buffer.setOption("modifiable", true, true);
this.buffer.setOption("readonly", false, true);
if (options.lines) {
void this.buffer.setLines(options.lines, { start: 0, end: -1 }, true);
}
if (!modifiable) {
this.buffer.setOption("modifiable", false, true);
this.buffer.setOption("readonly", true, true);
}
if (options.highlights) {
for (const hl of options.highlights) {
this.util.addHighlightsNotify(this.buffer, [hl]);
}
}
if (import_coc11.workspace.isVim) {
this.nvim.command("redraw!", true);
}
});
}
async setLines(options) {
await this.setLinesNotifier(options).run();
}
async opened() {
const win = await this.win();
return !!win;
}
async openNotifier(options) {
var _a;
if (options.width <= 0 || options.height <= 0) {
return Notifier.noop();
}
const notifiers = [];
notifiers.push(this.closeNotifier());
const ctx = await this.util.createContext(options);
const [initedExecute, borderInitedExecute] = this.getInitedExecute(options);
const [winConfig, borderWinConfig] = this.util.winConfig(ctx, options);
if (options.borderOnly && borderWinConfig) {
notifiers.push(floatingModule.open.callNotifier(this.bufnr, borderWinConfig, borderInitedExecute, null, null, "", false, this.util.nvimWinHl(options)));
notifiers.push(this.util.renderBorderNotifier(this.buffer, ctx, options, borderWinConfig));
} else {
notifiers.push(floatingModule.open.callNotifier(this.bufnr, winConfig, initedExecute, (_a = this.borderBufnr) !== null && _a !== void 0 ? _a : null, borderWinConfig !== null && borderWinConfig !== void 0 ? borderWinConfig : null, borderInitedExecute, this.getFocus(options), this.util.nvimWinHl(options)));
}
if (import_coc11.workspace.isNvim && this.borderBuffer && borderWinConfig) {
notifiers.push(this.util.renderBorderNotifier(this.borderBuffer, ctx, options, borderWinConfig));
}
notifiers.push(this.setLinesNotifier(options), Notifier.create(() => {
if (options.filetype) {
this.buffer.setOption("filetype", options.filetype, true);
}
}));
return Notifier.combine(notifiers);
}
async open(options) {
await (await this.openNotifier(options)).run();
}
async resumeNotifier(options) {
const ctx = await this.util.createContext(options);
const [winConfig, borderWinConfig] = this.util.winConfig(ctx, options);
return Notifier.create(() => {
var _a;
floatingModule.resume.callNotify(this.bufnr, winConfig, (_a = this.borderBufnr) !== null && _a !== void 0 ? _a : null, borderWinConfig !== null && borderWinConfig !== void 0 ? borderWinConfig : null, this.getFocus(options), this.util.nvimWinHl(options));
if (this.borderBuffer && borderWinConfig) {
this.util.renderBorderNotifier(this.borderBuffer, ctx, options, borderWinConfig).notify();
}
if (import_coc11.workspace.isVim) {
this.nvim.command("redraw!", true);
}
});
}
async resume(options) {
await (await this.resumeNotifier(options)).run();
}
async resizeNotifier(options) {
var _a;
const ctx = await this.util.createContext(options);
const [winConfig, borderWinConfig] = this.util.winConfig(ctx, options, false);
const notifiers = [];
if (options.borderOnly && borderWinConfig) {
notifiers.push(floatingModule.update.callNotifier(this.bufnr, borderWinConfig, null, null, this.util.nvimWinHl(options)));
notifiers.push(this.util.renderBorderNotifier(this.buffer, ctx, options, borderWinConfig));
} else {
notifiers.push(floatingModule.update.callNotifier(this.bufnr, winConfig, (_a = this.borderBufnr) !== null && _a !== void 0 ? _a : null, borderWinConfig !== null && borderWinConfig !== void 0 ? borderWinConfig : null, this.util.nvimWinHl(options)));
}
if (import_coc11.workspace.isNvim && this.borderBuffer && borderWinConfig) {
notifiers.push(this.util.renderBorderNotifier(this.borderBuffer, ctx, options, borderWinConfig));
}
notifiers.push(Notifier.create(() => {
if (import_coc11.workspace.isVim) {
this.nvim.command("redraw!", true);
}
}));
return Notifier.combine(notifiers);
}
async resize(options) {
await (await this.resizeNotifier(options)).run();
}
async win() {
const winid = await floatingModule.winid.call(this.bufnr);
return winid ? this.nvim.createWindow(winid) : void 0;
}
async borderWin() {
const borderWinid = await floatingModule.winid.call(this.bufnr);
return borderWinid ? this.nvim.createWindow(borderWinid) : void 0;
}
closeNotifier() {
return floatingModule.close.callNotifier(this.bufnr);
}
async close() {
await this.closeNotifier().run();
}
dispose() {
(0, import_coc11.disposeAll)(this.disposables);
this.disposables.forEach((s) => s.dispose());
}
};
FloatingWindow.modePresets = {
default: {
modifiable: false,
focus: false,
createInitedExecute: () => "",
openInitedExecute: () => ""
},
base: {
createInitedExecute: (ctx) => `
call setbufvar(${ctx.bufnr}, '&buftype', 'nofile')
call setbufvar(${ctx.bufnr}, '&buf