From 013ff12e7166569e4094ac7c8c61a3efa1ff9082 Mon Sep 17 00:00:00 2001 From: "Justin M. Keyes" Date: Fri, 15 Nov 2024 16:14:24 -0500 Subject: [PATCH] lint: increased line-length Since `.editorconfig` was added, eslint (or prettier) seems to treat it as authoritative. So let's just increase the line length. --- .prettierrc.json | 1 + packages/decorators/src/plugin/autocmd.ts | 4 +- packages/decorators/src/plugin/plugin.ts | 17 +-- .../integration-tests/src/factory.test.ts | 47 +++----- packages/neovim/src/api/Base.ts | 22 +--- packages/neovim/src/api/Buffer.test.ts | 95 +++------------- packages/neovim/src/api/Buffer.ts | 47 ++------ packages/neovim/src/api/Neovim.test.ts | 25 ++--- packages/neovim/src/api/Neovim.ts | 104 +++--------------- packages/neovim/src/api/Window.ts | 8 +- packages/neovim/src/api/client.ts | 45 ++------ .../src/api/utils/createChainableApi.ts | 35 ++---- packages/neovim/src/attach/attach.test.ts | 10 +- packages/neovim/src/attach/attach.ts | 8 +- packages/neovim/src/host/NvimPlugin.test.ts | 76 +++---------- packages/neovim/src/host/NvimPlugin.ts | 60 +++------- packages/neovim/src/host/factory.ts | 4 +- packages/neovim/src/host/index.ts | 12 +- packages/neovim/src/plugin/plugin.test.ts | 16 +-- packages/neovim/src/plugin/plugin.ts | 13 +-- packages/neovim/src/testUtil.ts | 12 +- packages/neovim/src/types/VimValue.ts | 7 +- packages/neovim/src/utils/findNvim.test.ts | 38 ++----- packages/neovim/src/utils/findNvim.ts | 17 +-- packages/neovim/src/utils/logger.ts | 8 +- packages/neovim/src/utils/transport.ts | 42 ++----- packages/neovim/src/utils/util.ts | 13 +-- 27 files changed, 166 insertions(+), 620 deletions(-) diff --git a/.prettierrc.json b/.prettierrc.json index 9d9d30fb..168b240a 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -2,6 +2,7 @@ "tabWidth": 2, "trailingComma": "es5", "parser": "typescript", + "printWidth": 100, "singleQuote": true, "arrowParens": "avoid" } diff --git a/packages/decorators/src/plugin/autocmd.ts b/packages/decorators/src/plugin/autocmd.ts index 2337c501..1a73dccc 100644 --- a/packages/decorators/src/plugin/autocmd.ts +++ b/packages/decorators/src/plugin/autocmd.ts @@ -19,9 +19,7 @@ export function Autocmd(name: string, options?: AutocmdOptions) { } }); - const nameWithPattern = `${name}${ - options?.pattern ? `:${options.pattern}` : '' - }`; + const nameWithPattern = `${name}${options?.pattern ? `:${options.pattern}` : ''}`; Object.defineProperty(f, NVIM_METHOD_NAME, { value: `autocmd:${nameWithPattern}`, }); diff --git a/packages/decorators/src/plugin/plugin.ts b/packages/decorators/src/plugin/plugin.ts index 6421211d..49a83376 100644 --- a/packages/decorators/src/plugin/plugin.ts +++ b/packages/decorators/src/plugin/plugin.ts @@ -2,12 +2,7 @@ import { Neovim, NvimPlugin } from 'neovim'; import { NVIM_SPEC } from './properties'; -import { - PluginOptions, - AutocmdOptions, - CommandOptions, - FunctionOptions, -} from './types'; +import { PluginOptions, AutocmdOptions, CommandOptions, FunctionOptions } from './types'; interface Spec { type: 'function' | 'autocmd' | 'command'; @@ -57,11 +52,7 @@ function wrapper(cls: PluginWrapperConstructor, options?: PluginOptions): any { autoCmdOpts.eval = spec.opts.eval; } - plugin.registerAutocmd( - spec.name, - [this, method], - autoCmdOpts as any - ); + plugin.registerAutocmd(spec.name, [this, method], autoCmdOpts as any); break; case 'command': const cmdOpts: CommandOptions = { @@ -134,7 +125,5 @@ export function Plugin(outter: any): any { * * Plugin(TestPlugin) */ - return typeof outter !== 'function' - ? (cls: any) => wrapper(cls, outter) - : wrapper(outter); + return typeof outter !== 'function' ? (cls: any) => wrapper(cls, outter) : wrapper(outter); } diff --git a/packages/integration-tests/src/factory.test.ts b/packages/integration-tests/src/factory.test.ts index f57bcb90..8d8c1037 100644 --- a/packages/integration-tests/src/factory.test.ts +++ b/packages/integration-tests/src/factory.test.ts @@ -51,27 +51,20 @@ describe('Plugin Factory (used by host)', () => { }); it('should collect the handlers from a plugin', async () => { - expect(await pluginObj.handleRequest('Func', 'function', ['town'])).toEqual( - 'Funcy town' - ); + expect(await pluginObj.handleRequest('Func', 'function', ['town'])).toEqual('Funcy town'); }); it('should load the plugin a sandbox', async () => { - expect( - await pluginObj.handleRequest('Global', 'function', ['loaded']) - ).toEqual(true); - expect( - await pluginObj.handleRequest('Global', 'function', ['Buffer']) - ).not.toEqual(undefined); - expect( - await pluginObj.handleRequest('Global', 'function', ['process']) - ).not.toContain(['chdir', 'exit']); + expect(await pluginObj.handleRequest('Global', 'function', ['loaded'])).toEqual(true); + expect(await pluginObj.handleRequest('Global', 'function', ['Buffer'])).not.toEqual(undefined); + expect(await pluginObj.handleRequest('Global', 'function', ['process'])).not.toContain([ + 'chdir', + 'exit', + ]); }); it('should load files required by the plugin in a sandbox', async () => { - expect( - await pluginObj.handleRequest('Global', 'function', ['required']) - ).toEqual('you bet!'); + expect(await pluginObj.handleRequest('Global', 'function', ['required'])).toEqual('you bet!'); // expect( // Object.keys(required.globals.process), // ).not.toContain( @@ -94,10 +87,7 @@ describe('Plugin Factory (decorator api)', () => { let pluginObj: NvimPlugin; beforeEach(() => { - const p = loadPlugin( - '@neovim/example-plugin-decorators', - getFakeNvimClient() - ); + const p = loadPlugin('@neovim/example-plugin-decorators', getFakeNvimClient()); if (!p) { throw new Error(); } @@ -126,24 +116,19 @@ describe('Plugin Factory (decorator api)', () => { }); it('should collect the handlers from a plugin', async () => { - expect(await pluginObj.handleRequest('Func', 'function', ['town'])).toEqual( - 'Funcy town' - ); + expect(await pluginObj.handleRequest('Func', 'function', ['town'])).toEqual('Funcy town'); }); it('should load the plugin a sandbox', async () => { - expect( - await pluginObj.handleRequest('Global', 'function', ['loaded']) - ).toEqual(true); - expect( - await pluginObj.handleRequest('Global', 'function', ['process']) - ).not.toContain(['chdir', 'exit']); + expect(await pluginObj.handleRequest('Global', 'function', ['loaded'])).toEqual(true); + expect(await pluginObj.handleRequest('Global', 'function', ['process'])).not.toContain([ + 'chdir', + 'exit', + ]); }); it('should load files required by the plugin in a sandbox', async () => { - expect( - await pluginObj.handleRequest('Global', 'function', ['required']) - ).toEqual('you bet!'); + expect(await pluginObj.handleRequest('Global', 'function', ['required'])).toEqual('you bet!'); // expect( // Object.keys(required.globals.process), // ).not.toContain( diff --git a/packages/neovim/src/api/Base.ts b/packages/neovim/src/api/Base.ts index b88eaf29..5a0aef2e 100644 --- a/packages/neovim/src/api/Base.ts +++ b/packages/neovim/src/api/Base.ts @@ -39,13 +39,7 @@ export class BaseApi extends EventEmitter { // Node Buffer protected client: any; - constructor({ - transport, - data, - logger, - metadata, - client, - }: BaseConstructorOptions) { + constructor({ transport, data, logger, metadata, client }: BaseConstructorOptions) { super(); this.transport = transport; @@ -75,12 +69,7 @@ export class BaseApi extends EventEmitter { try { logData = res && typeof res === 'object' - ? partialClone( - res, - 2, - ['logger', 'transport', 'client'], - '[Object]' - ) + ? partialClone(res, 2, ['logger', 'transport', 'client'], '[Object]') : res; } catch { logData = String(res); @@ -108,12 +97,7 @@ export class BaseApi extends EventEmitter { return this[DO_REQUEST](name, args).catch(err => { // XXX: Get a `*.ts stacktrace. If we re-throw `err` we get a `*.js` trace. tsconfig issue? const newError = new Error(err.message); - this.logger.error( - `failed request to "%s": %s: %s`, - name, - newError.name, - newError.message - ); + this.logger.error(`failed request to "%s": %s: %s`, name, newError.name, newError.message); throw newError; }); } diff --git a/packages/neovim/src/api/Buffer.test.ts b/packages/neovim/src/api/Buffer.test.ts index 44455869..fb1398e3 100644 --- a/packages/neovim/src/api/Buffer.test.ts +++ b/packages/neovim/src/api/Buffer.test.ts @@ -17,10 +17,7 @@ describe('Buffer API', () => { // utility to allow each test to be run in its // own buffer - function withBuffer( - lines: string[], - test: (buffer: Buffer) => Promise - ) { + function withBuffer(lines: string[], test: (buffer: Buffer) => Promise) { return async () => { await nvim.command('new!'); @@ -118,38 +115,18 @@ describe('Buffer API', () => { it( 'replaces the right lines', - withBuffer( - ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], - async buffer => { - await buffer.replace(['a', 'b', 'c'], 2); - - expect(await buffer.lines).toEqual([ - '0', - '1', - 'a', - 'b', - 'c', - '5', - '6', - '7', - '8', - '9', - ]); - } - ) + withBuffer(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], async buffer => { + await buffer.replace(['a', 'b', 'c'], 2); + + expect(await buffer.lines).toEqual(['0', '1', 'a', 'b', 'c', '5', '6', '7', '8', '9']); + }) ); it( 'inserts line at index 2', withBuffer(['test', 'bar', 'bar', 'bar'], async buffer => { buffer.insert(['foo'], 2); - expect(await buffer.lines).toEqual([ - 'test', - 'bar', - 'foo', - 'bar', - 'bar', - ]); + expect(await buffer.lines).toEqual(['test', 'bar', 'foo', 'bar', 'bar']); }) ); @@ -192,13 +169,7 @@ describe('Buffer API', () => { withBuffer(['test', 'bar', 'foo'], async buffer => { await buffer.append(['test', 'test']); - expect(await buffer.lines).toEqual([ - 'test', - 'bar', - 'foo', - 'test', - 'test', - ]); + expect(await buffer.lines).toEqual(['test', 'bar', 'foo', 'test', 'test']); }) ); @@ -307,26 +278,12 @@ describe('Buffer API', () => { it( 'replaces the right lines', - withBuffer( - ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], - async () => { - const buffer = await nvim.buffer; - await buffer.replace(['a', 'b', 'c'], 2); - - expect(await buffer.lines).toEqual([ - '0', - '1', - 'a', - 'b', - 'c', - '5', - '6', - '7', - '8', - '9', - ]); - } - ) + withBuffer(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], async () => { + const buffer = await nvim.buffer; + await buffer.replace(['a', 'b', 'c'], 2); + + expect(await buffer.lines).toEqual(['0', '1', 'a', 'b', 'c', '5', '6', '7', '8', '9']); + }) ); it( @@ -352,13 +309,7 @@ describe('Buffer API', () => { withBuffer(['test', 'bar', 'bar', 'bar'], async () => { const buffer = await nvim.buffer; await buffer.insert(['foo'], 2); - expect(await buffer.lines).toEqual([ - 'test', - 'bar', - 'foo', - 'bar', - 'bar', - ]); + expect(await buffer.lines).toEqual(['test', 'bar', 'foo', 'bar', 'bar']); }) ); @@ -376,13 +327,7 @@ describe('Buffer API', () => { withBuffer(['test', 'bar', 'foo'], async () => { const buffer = await nvim.buffer; await buffer.append(['test', 'test']); - expect(await buffer.lines).toEqual([ - 'test', - 'bar', - 'foo', - 'test', - 'test', - ]); + expect(await buffer.lines).toEqual(['test', 'bar', 'foo', 'test', 'test']); }) ); @@ -477,13 +422,7 @@ describe('Buffer event updates', () => { const promise = new Promise(resolve => { const unlisten = buffer.listen( 'lines', - async ( - currentBuffer: Buffer, - tick: number, - start: number, - end: number, - data: string[] - ) => { + async (currentBuffer: Buffer, tick: number, start: number, end: number, data: string[]) => { expect(await currentBuffer.name).toBe(bufferName); expect(start).toBe(1); expect(end).toBe(1); diff --git a/packages/neovim/src/api/Buffer.ts b/packages/neovim/src/api/Buffer.ts index feb66dd2..969a8537 100644 --- a/packages/neovim/src/api/Buffer.ts +++ b/packages/neovim/src/api/Buffer.ts @@ -89,14 +89,8 @@ export class Buffer extends BaseApi { getLines( { start, end, strictIndexing } = { start: 0, end: -1, strictIndexing: true } ): Promise { - const indexing = - typeof strictIndexing === 'undefined' ? true : strictIndexing; - return this.request(`${this.prefix}get_lines`, [ - this, - start, - end, - indexing, - ]); + const indexing = typeof strictIndexing === 'undefined' ? true : strictIndexing; + return this.request(`${this.prefix}get_lines`, [this, start, end, indexing]); } /** Set lines of buffer given indeces */ @@ -109,18 +103,11 @@ export class Buffer extends BaseApi { if (_start === undefined || _end === undefined) { throw new Error('start and end are required'); } - const indexing = - typeof strictIndexing === 'undefined' ? true : strictIndexing; + const indexing = typeof strictIndexing === 'undefined' ? true : strictIndexing; const lines = typeof _lines === 'string' ? [_lines] : _lines; const end = typeof _end !== 'undefined' ? _end : _start + 1; - return this.request(`${this.prefix}set_lines`, [ - this, - _start, - end, - indexing, - lines, - ]); + return this.request(`${this.prefix}set_lines`, [this, _start, end, indexing, lines]); } /** Insert lines at `start` index */ @@ -265,9 +252,7 @@ export class Buffer extends BaseApi { */ clearHighlight(args: BufferClearHighlight = {}) { // eslint-disable-next-line no-console - console.warn( - '`clearHighlight` is deprecated, use ``clearNamespace()` instead' - ); + console.warn('`clearHighlight` is deprecated, use ``clearNamespace()` instead'); const defaults = { srcId: -1, @@ -277,12 +262,7 @@ export class Buffer extends BaseApi { const { srcId, lineStart, lineEnd } = { ...defaults, ...args }; - return this.request(`${this.prefix}clear_highlight`, [ - this, - srcId, - lineStart, - lineEnd, - ]); + return this.request(`${this.prefix}clear_highlight`, [this, srcId, lineStart, lineEnd]); } /** @@ -303,12 +283,7 @@ export class Buffer extends BaseApi { const { nsId, lineStart, lineEnd } = { ...defaults, ...args }; - this.request(`${this.prefix}clear_namespace`, [ - this, - nsId, - lineStart, - lineEnd, - ]); + this.request(`${this.prefix}clear_namespace`, [this, nsId, lineStart, lineEnd]); } /** @@ -348,13 +323,7 @@ export class Buffer extends BaseApi { chunks: VirtualTextChunk[], opts = {} ): Promise { - return this.request(`${this.prefix}set_virtual_text`, [ - this, - nsId, - line, - chunks, - opts, - ]); + return this.request(`${this.prefix}set_virtual_text`, [this, nsId, line, chunks, opts]); } /** diff --git a/packages/neovim/src/api/Neovim.test.ts b/packages/neovim/src/api/Neovim.test.ts index 542582e7..d2a05b9a 100644 --- a/packages/neovim/src/api/Neovim.test.ts +++ b/packages/neovim/src/api/Neovim.test.ts @@ -86,22 +86,13 @@ describe('Neovim API', () => { }); it('can run lua', async () => { - expect( - await nvim.lua('function test(a) return a end return test(...)', [1]) - ).toBe(1); + expect(await nvim.lua('function test(a) return a end return test(...)', [1])).toBe(1); - expect( - await nvim.lua('function test(a) return a end return test(...)', [ - 'foo', - ]) - ).toBe('foo'); - - expect( - await nvim.executeLua( - 'function test(a) return a end return test(...)', - ['foo'] - ) - ).toBe('foo'); + expect(await nvim.lua('function test(a) return a end return test(...)', ['foo'])).toBe('foo'); + + expect(await nvim.executeLua('function test(a) return a end return test(...)', ['foo'])).toBe( + 'foo' + ); }); it('get/set/delete current line', async () => { @@ -143,9 +134,7 @@ describe('Neovim API', () => { }); it('parse expression', async () => { - expect(await nvim.parseExpression('@', 'm', true)).toEqual( - expect.objectContaining({}) - ); + expect(await nvim.parseExpression('@', 'm', true)).toEqual(expect.objectContaining({})); }); it('gets api info', async () => { diff --git a/packages/neovim/src/api/Neovim.ts b/packages/neovim/src/api/Neovim.ts index 8933f9b5..598ea593 100644 --- a/packages/neovim/src/api/Neovim.ts +++ b/packages/neovim/src/api/Neovim.ts @@ -111,14 +111,7 @@ export interface OpenWindowOptions { style?: 'minimal'; // Style of (optional) window border. This can either be a string or an array. - border?: - | 'none' - | 'single' - | 'double' - | 'rounded' - | 'solid' - | 'shadow' - | string[]; + border?: 'none' | 'single' | 'double' | 'rounded' | 'solid' | 'shadow' | string[]; // If true then no buffer-related autocommand events such as |BufEnter|, |BufLeave| or |BufWinEnter| may fire from calling this function. noautocmd?: boolean; @@ -397,15 +390,9 @@ export class Neovim extends BaseApi { * @param isRgb Should export RGB colors * @return Highlight definition map */ - getHighlight( - nameOrId: string | number, - isRgb = true - ): Promise | void { + getHighlight(nameOrId: string | number, isRgb = true): Promise | void { const functionName = typeof nameOrId === 'string' ? 'by_name' : 'by_id'; - return this.request(`${this.prefix}get_hl_${functionName}`, [ - nameOrId, - isRgb, - ]); + return this.request(`${this.prefix}get_hl_${functionName}`, [nameOrId, isRgb]); } /** @@ -467,17 +454,9 @@ export class Neovim extends BaseApi { * * On execution error: fails with VimL error, does not update v:errmsg. */ - callDictFunction( - dict: object, - fname: string, - args: VimValue | VimValue[] = [] - ): object { + callDictFunction(dict: object, fname: string, args: VimValue | VimValue[] = []): object { const _args = Array.isArray(args) ? args : [args]; - return this.request(`${this.prefix}call_dict_function`, [ - dict, - fname, - _args, - ]); + return this.request(`${this.prefix}call_dict_function`, [dict, fname, _args]); } /** @@ -624,14 +603,7 @@ export class Neovim extends BaseApi { row: number, col: number ) { - return this.request(`${this.prefix}input_mouse`, [ - button, - action, - modifier, - grid, - row, - col, - ]); + return this.request(`${this.prefix}input_mouse`, [button, action, modifier, grid, row, col]); } /** @@ -639,16 +611,8 @@ export class Neovim extends BaseApi { * * TODO: return type, see :help */ - parseExpression( - expr: string, - flags: string, - highlight: boolean - ): Promise { - return this.request(`${this.prefix}parse_expression`, [ - expr, - flags, - highlight, - ]); + parseExpression(expr: string, flags: string, highlight: boolean): Promise { + return this.request(`${this.prefix}parse_expression`, [expr, flags, highlight]); } /** @@ -686,12 +650,7 @@ export class Neovim extends BaseApi { doIt: boolean, special: boolean ): Promise { - return this.request(`${this.prefix}replace_termcodes`, [ - str, - fromPart, - doIt, - special, - ]); + return this.request(`${this.prefix}replace_termcodes`, [str, fromPart, doIt, special]); } /** @@ -739,11 +698,7 @@ export class Neovim extends BaseApi { return this.request(`${this.prefix}list_uis`); } - uiAttach( - width: number, - height: number, - options: UiAttachOptions - ): Promise { + uiAttach(width: number, height: number, options: UiAttachOptions): Promise { return this.request(`${this.prefix}ui_attach`, [width, height, options]); } @@ -773,11 +728,7 @@ export class Neovim extends BaseApi { * @param {Number} height The new requested height */ uiTryResizeGrid(grid: number, width: number, height: number): Promise { - return this.request(`${this.prefix}ui_try_resize_grid`, [ - grid, - width, - height, - ]); + return this.request(`${this.prefix}ui_try_resize_grid`, [grid, width, height]); } /** @@ -820,13 +771,7 @@ export class Neovim extends BaseApi { methods: object, attributes: object ): void { - this.request(`${this.prefix}set_client_info`, [ - name, - version, - type, - methods, - attributes, - ]); + this.request(`${this.prefix}set_client_info`, [name, version, type, methods, attributes]); } /** @@ -878,18 +823,8 @@ export class Neovim extends BaseApi { * Implies `insert`. * @param {Object} opts Optional parameters. Reserved for future use. */ - selectPopupmenuItem( - item: number, - insert: boolean, - finish: boolean, - opts: object = {} - ) { - return this.request(`${this.prefix}select_popupmenu_item`, [ - item, - insert, - finish, - opts, - ]); + selectPopupmenuItem(item: number, insert: boolean, finish: boolean, opts: object = {}) { + return this.request(`${this.prefix}select_popupmenu_item`, [item, insert, finish, opts]); } /** @@ -899,10 +834,7 @@ export class Neovim extends BaseApi { * @param {Boolean} scratch Creates a "throwaway" |scratch-buffer| for temporary work (always 'nomodified') * @return {Buffer|Number} Buffer handle, or 0 on error */ - private createBuf( - listed: boolean, - scratch: boolean - ): Promise { + private createBuf(listed: boolean, scratch: boolean): Promise { return this.request(`${this.prefix}create_buf`, [listed, scratch]); } @@ -940,11 +872,7 @@ export class Neovim extends BaseApi { /** * Public alias for `openWin` */ - openWindow( - buffer: Buffer, - enter: boolean, - options: OpenWindowOptions - ): Promise { + openWindow(buffer: Buffer, enter: boolean, options: OpenWindowOptions): Promise { return this.openWin(buffer, enter, options); } diff --git a/packages/neovim/src/api/Window.ts b/packages/neovim/src/api/Window.ts index 7c977c97..6d8de3b0 100644 --- a/packages/neovim/src/api/Window.ts +++ b/packages/neovim/src/api/Window.ts @@ -65,16 +65,12 @@ export class Window extends BaseApi { /** 0-indexed, on-screen window position(row) in display cells. */ get row(): Promise { - return this.request(`${this.prefix}get_position`, [this]).then( - position => position[0] - ); + return this.request(`${this.prefix}get_position`, [this]).then(position => position[0]); } /** 0-indexed, on-screen window position(col) in display cells. */ get col(): Promise { - return this.request(`${this.prefix}get_position`, [this]).then( - position => position[1] - ); + return this.request(`${this.prefix}get_position`, [this]).then(position => position[1]); } /** Is window valid */ diff --git a/packages/neovim/src/api/client.ts b/packages/neovim/src/api/client.ts index 15a9acb5..26b3a42d 100644 --- a/packages/neovim/src/api/client.ts +++ b/packages/neovim/src/api/client.ts @@ -32,13 +32,7 @@ export class NeovimClient extends Neovim { } /** Attaches msgpack to read/write streams * */ - attach({ - reader, - writer, - }: { - reader: NodeJS.ReadableStream; - writer: NodeJS.WritableStream; - }) { + attach({ reader, writer }: { reader: NodeJS.ReadableStream; writer: NodeJS.WritableStream }) { this.transport.attach(writer, reader, this); this.transportAttached = true; this.setupTransport(); @@ -64,12 +58,7 @@ export class NeovimClient extends Neovim { } /** Handles incoming request (from the peer). */ - handleRequest( - method: string, - args: VimValue[], - resp: any, - ...restArgs: any[] - ) { + handleRequest(method: string, args: VimValue[], resp: any, ...restArgs: any[]) { // If neovim API is not generated yet and we are not handle a 'specs' request // then queue up requests // @@ -152,17 +141,13 @@ export class NeovimClient extends Neovim { requestApi(): Promise { return new Promise((resolve, reject) => { - this.transport.request( - 'nvim_get_api_info', - [], - (err: Error, res: any[]) => { - if (err) { - reject(err); - } else { - resolve(res); - } + this.transport.request('nvim_get_api_info', [], (err: Error, res: any[]) => { + if (err) { + reject(err); + } else { + resolve(res); } - ); + }); }); } @@ -205,13 +190,9 @@ export class NeovimClient extends Neovim { return true; } catch (e) { const err = e as Error; - this.logger.error( - `Could not dynamically generate neovim API: %s: %O`, - err.name, - { - error: err, - } - ); + this.logger.error(`Could not dynamically generate neovim API: %s: %O`, err.name, { + error: err, + }); this.logger.error(err.stack); return false; } @@ -252,9 +233,7 @@ export class NeovimClient extends Neovim { const bufferMap = this.attachedBuffers.get(bufferKey); if (!bufferMap) return false; - const handlers = (bufferMap.get(eventName) || []).filter( - handler => handler !== cb - ); + const handlers = (bufferMap.get(eventName) || []).filter(handler => handler !== cb); // Remove eventName listener from bufferMap if no more handlers if (!handlers.length) { diff --git a/packages/neovim/src/api/utils/createChainableApi.ts b/packages/neovim/src/api/utils/createChainableApi.ts index bfe09599..e6f636d8 100644 --- a/packages/neovim/src/api/utils/createChainableApi.ts +++ b/packages/neovim/src/api/utils/createChainableApi.ts @@ -12,11 +12,7 @@ export function createChainableApi( const that = this as any; // re-use current promise if not resolved yet - if ( - that[`${name}Promise`] && - that[`${name}Promise`].status === 0 && - that[`${name}Proxy`] - ) { + if (that[`${name}Promise`] && that[`${name}Promise`].status === 0 && that[`${name}Proxy`]) { return that[`${name}Proxy`]; } @@ -24,15 +20,13 @@ export function createChainableApi( // TODO: Optimize this // Define properties on the promise for devtools - [...baseProperties, ...Object.getOwnPropertyNames(Type.prototype)].forEach( - key => { - Object.defineProperty(that[`${name}Promise`], key, { - enumerable: true, - writable: true, - configurable: true, - }); - } - ); + [...baseProperties, ...Object.getOwnPropertyNames(Type.prototype)].forEach(key => { + Object.defineProperty(that[`${name}Promise`], key, { + enumerable: true, + writable: true, + configurable: true, + }); + }); const proxyHandler = { get: (target: any, prop: string) => { @@ -52,8 +46,7 @@ export function createChainableApi( Object.getOwnPropertyDescriptor(BaseApi.prototype, prop); const isGetter = descriptor && - (typeof descriptor.get !== 'undefined' || - typeof descriptor.set !== 'undefined'); + (typeof descriptor.get !== 'undefined' || typeof descriptor.set !== 'undefined'); // XXX: the promise can potentially be stale // Check if resolved, else do a refresh request for current buffer? @@ -61,16 +54,12 @@ export function createChainableApi( if ( isOnPrototype && !isGetter && - ((prop in Type.prototype && - typeof Type.prototype[prop] === 'function') || - (prop in BaseApi.prototype && - typeof (BaseApi.prototype as any)[prop] === 'function')) + ((prop in Type.prototype && typeof Type.prototype[prop] === 'function') || + (prop in BaseApi.prototype && typeof (BaseApi.prototype as any)[prop] === 'function')) ) { // If property is a method on Type, we need to invoke it with captured args return (...args: any[]) => - that[`${name}Promise`].then((res: any) => - res[prop].call(res, ...args) - ); + that[`${name}Promise`].then((res: any) => res[prop].call(res, ...args)); } // Otherwise return the property requested after promise is resolved diff --git a/packages/neovim/src/attach/attach.test.ts b/packages/neovim/src/attach/attach.test.ts index deb10786..75e94fb5 100644 --- a/packages/neovim/src/attach/attach.test.ts +++ b/packages/neovim/src/attach/attach.test.ts @@ -42,9 +42,7 @@ describe('Nvim API', () => { it('failure modes', async () => { const c = new NeovimClient(); - await expect(c.channelId).rejects.toThrow( - 'channelId requested before _isReady' - ); + await expect(c.channelId).rejects.toThrow('channelId requested before _isReady'); }); it('console.log is monkey-patched to logger.info #329', async () => { @@ -107,11 +105,7 @@ describe('Nvim API', () => { it('noisy RPC traffic', async () => { let requestCount = 0; const oldRequest = nvim.request; - nvim.request = function ( - this: any, - name: string, - args: any[] = [] - ): Promise { + nvim.request = function (this: any, name: string, args: any[] = []): Promise { requestCount = requestCount + 1; return oldRequest.call(this, name, args); }; diff --git a/packages/neovim/src/attach/attach.ts b/packages/neovim/src/attach/attach.ts index d18b1008..042e52d1 100644 --- a/packages/neovim/src/attach/attach.ts +++ b/packages/neovim/src/attach/attach.ts @@ -14,13 +14,7 @@ export interface Attach { }; } -export function attach({ - reader: _reader, - writer: _writer, - proc, - socket, - options = {}, -}: Attach) { +export function attach({ reader: _reader, writer: _writer, proc, socket, options = {} }: Attach) { let writer; let reader; diff --git a/packages/neovim/src/host/NvimPlugin.test.ts b/packages/neovim/src/host/NvimPlugin.test.ts index 3d1f6222..77f9c3f1 100644 --- a/packages/neovim/src/host/NvimPlugin.test.ts +++ b/packages/neovim/src/host/NvimPlugin.test.ts @@ -17,22 +17,14 @@ describe('NvimPlugin', () => { }); it('should set dev options when you call setOptions', () => { - const plugin = new NvimPlugin( - '/tmp/filename', - () => {}, - getFakeNvimClient() - ); + const plugin = new NvimPlugin('/tmp/filename', () => {}, getFakeNvimClient()); plugin.setOptions({ dev: true }); expect(plugin.dev).toBe(true); expect(plugin.shouldCacheModule).toBe(false); }); it('should store registered autocmds', () => { - const plugin = new NvimPlugin( - '/tmp/filename', - () => {}, - getFakeNvimClient() - ); + const plugin = new NvimPlugin('/tmp/filename', () => {}, getFakeNvimClient()); const fn = () => {}; const opts = { pattern: '*' }; const spec = { @@ -47,11 +39,7 @@ describe('NvimPlugin', () => { }); it('should store registered commands', () => { - const plugin = new NvimPlugin( - '/tmp/filename', - () => {}, - getFakeNvimClient() - ); + const plugin = new NvimPlugin('/tmp/filename', () => {}, getFakeNvimClient()); const fn = () => {}; const opts = { sync: true }; const spec = { @@ -66,11 +54,7 @@ describe('NvimPlugin', () => { }); it('should store registered functions', () => { - const plugin = new NvimPlugin( - '/tmp/filename', - () => {}, - getFakeNvimClient() - ); + const plugin = new NvimPlugin('/tmp/filename', () => {}, getFakeNvimClient()); const fn = () => {}; const opts = { sync: true }; const spec = { @@ -85,11 +69,7 @@ describe('NvimPlugin', () => { }); it('should not add autocmds with no pattern option', () => { - const plugin = new NvimPlugin( - '/tmp/filename', - () => {}, - getFakeNvimClient() - ); + const plugin = new NvimPlugin('/tmp/filename', () => {}, getFakeNvimClient()); plugin.registerAutocmd('BufWritePre', () => {}, { pattern: '' }); expect(Object.keys(plugin.autocmds)).toHaveLength(0); }); @@ -106,11 +86,7 @@ describe('NvimPlugin', () => { const thisObj = {}; expect(callable([thisObj, fn])()).toBe(thisObj); - const plugin = new NvimPlugin( - '/tmp/filename', - () => {}, - getFakeNvimClient() - ); + const plugin = new NvimPlugin('/tmp/filename', () => {}, getFakeNvimClient()); const obj = { func: jestMock.fn(function () { // @ts-expect-error intentional @@ -126,22 +102,14 @@ describe('NvimPlugin', () => { }); it('should not register commands with incorrect callable arguments', () => { - const plugin = new NvimPlugin( - '/tmp/filename', - () => {}, - getFakeNvimClient() - ); + const plugin = new NvimPlugin('/tmp/filename', () => {}, getFakeNvimClient()); // @ts-expect-error Intentionally passing empty array for command arguments. plugin.registerCommand('MyCommand', [], {}); expect(Object.keys(plugin.commands)).toHaveLength(0); }); it('should return specs for registered commands', () => { - const plugin = new NvimPlugin( - '/tmp/filename', - () => {}, - getFakeNvimClient() - ); + const plugin = new NvimPlugin('/tmp/filename', () => {}, getFakeNvimClient()); const fn = () => {}; const aOpts = { pattern: '*' }; const aSpec = { @@ -174,40 +142,24 @@ describe('NvimPlugin', () => { }); it('should handle requests for registered commands', async () => { - const plugin = new NvimPlugin( - '/tmp/filename', - () => {}, - getFakeNvimClient() - ); + const plugin = new NvimPlugin('/tmp/filename', () => {}, getFakeNvimClient()); const fn = (arg: any) => arg; plugin.registerAutocmd('BufWritePre', fn, { pattern: '*', sync: true }); plugin.registerCommand('MyCommand', fn, { sync: true }); plugin.registerFunction('MyFunction', fn); - expect(await plugin.handleRequest('BufWritePre *', 'autocmd', [true])).toBe( - true - ); - expect(await plugin.handleRequest('MyCommand', 'command', [false])).toBe( - false - ); - expect( - await plugin.handleRequest('MyFunction', 'function', ['blue']) - ).toEqual('blue'); + expect(await plugin.handleRequest('BufWritePre *', 'autocmd', [true])).toBe(true); + expect(await plugin.handleRequest('MyCommand', 'command', [false])).toBe(false); + expect(await plugin.handleRequest('MyFunction', 'function', ['blue'])).toEqual('blue'); }); it('should throw on unknown request', () => { - const plugin = new NvimPlugin( - '/tmp/filename', - () => {}, - getFakeNvimClient() - ); + const plugin = new NvimPlugin('/tmp/filename', () => {}, getFakeNvimClient()); expect.assertions(1); plugin.handleRequest('BufWritePre *', 'autocmd', [true]).catch(err => { expect(err).toEqual( - new Error( - 'Missing handler for autocmd: "BufWritePre *" in /tmp/filename' - ) + new Error('Missing handler for autocmd: "BufWritePre *" in /tmp/filename') ); }); }); diff --git a/packages/neovim/src/host/NvimPlugin.ts b/packages/neovim/src/host/NvimPlugin.ts index d96771e7..b5182edd 100644 --- a/packages/neovim/src/host/NvimPlugin.ts +++ b/packages/neovim/src/host/NvimPlugin.ts @@ -99,17 +99,11 @@ export class NvimPlugin { registerAutocmd(name: string, fn: Function, options: AutocmdOptions): void; - registerAutocmd( - name: string, - fn: [any, Function], - options: AutocmdOptions - ): void; + registerAutocmd(name: string, fn: [any, Function], options: AutocmdOptions): void; registerAutocmd(name: string, fn: any, options?: AutocmdOptions): void { if (!options?.pattern) { - this.nvim.logger.error( - `registerAutocmd expected pattern option for ${name}` - ); + this.nvim.logger.error(`registerAutocmd expected pattern option for ${name}`); return; } @@ -133,19 +127,13 @@ export class NvimPlugin { spec, }; } catch (err) { - this.nvim.logger.error( - `registerAutocmd expected callable argument for ${name}` - ); + this.nvim.logger.error(`registerAutocmd expected callable argument for ${name}`); } } registerCommand(name: string, fn: Function, options?: CommandOptions): void; - registerCommand( - name: string, - fn: [any, Function], - options?: CommandOptions - ): void; + registerCommand(name: string, fn: [any, Function], options?: CommandOptions): void; registerCommand(name: string, fn: any, options?: CommandOptions): void { const spec: Spec = { @@ -168,23 +156,13 @@ export class NvimPlugin { spec, }; } catch (err) { - this.nvim.logger.error( - `registerCommand expected callable argument for ${name}` - ); + this.nvim.logger.error(`registerCommand expected callable argument for ${name}`); } } - registerFunction( - name: string, - fn: Function, - options?: NvimFunctionOptions - ): void; + registerFunction(name: string, fn: Function, options?: NvimFunctionOptions): void; - registerFunction( - name: string, - fn: [any, Function], - options?: NvimFunctionOptions - ): void; + registerFunction(name: string, fn: [any, Function], options?: NvimFunctionOptions): void; registerFunction(name: string, fn: any, options?: NvimFunctionOptions): void { const spec: Spec = { @@ -207,22 +185,14 @@ export class NvimPlugin { spec, }; } catch (err) { - this.nvim.logger.error( - `registerFunction expected callable argument for ${name}` - ); + this.nvim.logger.error(`registerFunction expected callable argument for ${name}`); } } get specs(): Spec[] { - const autocmds = Object.keys(this.autocmds).map( - key => this.autocmds[key].spec - ); - const commands = Object.keys(this.commands).map( - key => this.commands[key].spec - ); - const functions = Object.keys(this.functions).map( - key => this.functions[key].spec - ); + const autocmds = Object.keys(this.autocmds).map(key => this.autocmds[key].spec); + const commands = Object.keys(this.commands).map(key => this.commands[key].spec); + const functions = Object.keys(this.functions).map(key => this.functions[key].spec); return autocmds.concat(commands).concat(functions); } @@ -248,15 +218,11 @@ export class NvimPlugin { if (handlers.hasOwnProperty(name)) { const handler = handlers[name]; try { - return handler.spec.sync - ? handler.fn(...args) - : await handler.fn(...args); + return handler.spec.sync ? handler.fn(...args) : await handler.fn(...args); } catch (e) { const err = e as Error; const msg = `Error in plugin for ${type}:${name}: ${err.message}`; - this.nvim.logger.error( - `${msg} (file: ${this.filename}, stack: ${err.stack})` - ); + this.nvim.logger.error(`${msg} (file: ${this.filename}, stack: ${err.stack})`); throw new Error(msg, { cause: err }); } } else { diff --git a/packages/neovim/src/host/factory.ts b/packages/neovim/src/host/factory.ts index 7c106265..ea7cebad 100644 --- a/packages/neovim/src/host/factory.ts +++ b/packages/neovim/src/host/factory.ts @@ -16,9 +16,7 @@ function createPlugin( options: LoadPluginOptions = {} ): NvimPlugin | null { try { - nvim.logger.debug( - `createPlugin.${filename}.clearCache: ${options && !options.cache}` - ); + nvim.logger.debug(`createPlugin.${filename}.clearCache: ${options && !options.cache}`); // Clear module from cache if (options && !options.cache) { diff --git a/packages/neovim/src/host/index.ts b/packages/neovim/src/host/index.ts index a19fbfe8..f29b3474 100644 --- a/packages/neovim/src/host/index.ts +++ b/packages/neovim/src/host/index.ts @@ -20,8 +20,7 @@ export class Host { getPlugin(filename: string, options: LoadPluginOptions = {}) { let plugin: (typeof this.loaded)[0] | null = this.loaded[filename]; - const shouldUseCachedPlugin = - plugin && plugin.shouldCacheModule && !plugin.alwaysInit; + const shouldUseCachedPlugin = plugin && plugin.shouldCacheModule && !plugin.alwaysInit; if (shouldUseCachedPlugin) { this.nvim?.logger.debug('getPlugin.useCachedPlugin'); @@ -36,10 +35,7 @@ export class Host { cache: plugin && plugin.shouldCacheModule, }); - this.nvim.logger.debug( - 'getPlugin.alwaysInit', - plugin && !plugin.alwaysInit - ); + this.nvim.logger.debug('getPlugin.alwaysInit', plugin && !plugin.alwaysInit); if (plugin) { this.loaded[filename] = plugin; } @@ -105,9 +101,7 @@ export class Host { } else { try { const plugResult = await this.handlePlugin(method, args); - res.send( - !plugResult || typeof plugResult === 'undefined' ? null : plugResult - ); + res.send(!plugResult || typeof plugResult === 'undefined' ? null : plugResult); } catch (e) { const err = e as Error; res.send(err.toString(), true); diff --git a/packages/neovim/src/plugin/plugin.test.ts b/packages/neovim/src/plugin/plugin.test.ts index 8a734a6f..6a0b3ebd 100644 --- a/packages/neovim/src/plugin/plugin.test.ts +++ b/packages/neovim/src/plugin/plugin.test.ts @@ -49,14 +49,8 @@ describe('Plugin class decorator', () => { } // This is how (closeish) babel applies decorators - FunctionDecorator('TestF', { eval: 'test', range: [1, 10] })( - MyClass.prototype, - 'testF' - ); - Command('TestCommand', { range: 'test', nargs: '3' })( - MyClass.prototype, - 'testC' - ); + FunctionDecorator('TestF', { eval: 'test', range: [1, 10] })(MyClass.prototype, 'testF'); + Command('TestCommand', { range: 'test', nargs: '3' })(MyClass.prototype, 'testC'); Autocmd('TestAutocmd', { pattern: '*.js', eval: 'test', @@ -114,11 +108,7 @@ describe('Plugin class decorator', () => { const plugin = Plugin(MyClass); - const pluginObject = new NvimPlugin( - '/tmp/filename', - plugin, - getFakeNvimClient() - ); + const pluginObject = new NvimPlugin('/tmp/filename', plugin, getFakeNvimClient()); expect(pluginObject.specs).toEqual([ { diff --git a/packages/neovim/src/plugin/plugin.ts b/packages/neovim/src/plugin/plugin.ts index 23e7fc0f..3144d553 100644 --- a/packages/neovim/src/plugin/plugin.ts +++ b/packages/neovim/src/plugin/plugin.ts @@ -21,10 +21,7 @@ export interface Constructor { new (...args: any[]): T; } -function wrapper>( - cls: T, - options?: PluginDecoratorOptions -) { +function wrapper>(cls: T, options?: PluginDecoratorOptions) { return class extends cls { public nvim!: Neovim; @@ -41,9 +38,7 @@ function wrapper>( // Search for decorated methods Object.getOwnPropertyNames(cls.prototype).forEach(methodName => { plugin.nvim.logger.info(`Method name ${methodName}`); - plugin.nvim.logger.info( - `${cls.prototype[methodName]} ${typeof cls.prototype[methodName]}` - ); + plugin.nvim.logger.info(`${cls.prototype[methodName]} ${typeof cls.prototype[methodName]}`); plugin.nvim.logger.info(`${this} ${typeof this}`); const method = cls.prototype[methodName]; @@ -132,7 +127,5 @@ export function plugin(outter: any): any { * * Plugin(TestPlugin) */ - return typeof outter !== 'function' - ? (cls: any) => wrapper(cls, outter) - : wrapper(outter); + return typeof outter !== 'function' ? (cls: any) => wrapper(cls, outter) : wrapper(outter); } diff --git a/packages/neovim/src/testUtil.ts b/packages/neovim/src/testUtil.ts index 9cbd8c05..13d2d8bf 100644 --- a/packages/neovim/src/testUtil.ts +++ b/packages/neovim/src/testUtil.ts @@ -25,12 +25,8 @@ export let proc: cp.ChildProcessWithoutNullStreams; export let nvim: NeovimClient; export function startNvim(): [cp.ChildProcessWithoutNullStreams, NeovimClient]; -export function startNvim( - doAttach: false -): [cp.ChildProcessWithoutNullStreams, undefined]; -export function startNvim( - doAttach: true -): [cp.ChildProcessWithoutNullStreams, NeovimClient]; +export function startNvim(doAttach: false): [cp.ChildProcessWithoutNullStreams, undefined]; +export function startNvim(doAttach: true): [cp.ChildProcessWithoutNullStreams, NeovimClient]; export function startNvim( doAttach: boolean = true ): [cp.ChildProcessWithoutNullStreams, NeovimClient | undefined] { @@ -51,9 +47,7 @@ export function startNvim( return [proc, nvim]; } -export function stopNvim( - proc_?: cp.ChildProcessWithoutNullStreams | NeovimClient -) { +export function stopNvim(proc_?: cp.ChildProcessWithoutNullStreams | NeovimClient) { // Stop all (proc + client). if (!proc_) { if (proc) { diff --git a/packages/neovim/src/types/VimValue.ts b/packages/neovim/src/types/VimValue.ts index 334642d8..831510c6 100644 --- a/packages/neovim/src/types/VimValue.ts +++ b/packages/neovim/src/types/VimValue.ts @@ -1,6 +1 @@ -export type VimValue = - | number - | boolean - | string - | number[] - | { [key: string]: any }; +export type VimValue = number | boolean | string | number[] | { [key: string]: any }; diff --git a/packages/neovim/src/utils/findNvim.test.ts b/packages/neovim/src/utils/findNvim.test.ts index e647d7f7..d5edfa96 100644 --- a/packages/neovim/src/utils/findNvim.test.ts +++ b/packages/neovim/src/utils/findNvim.test.ts @@ -23,12 +23,7 @@ describe('findNvim', () => { }); it('parseVersion()', () => { - expect(parseVersion('0.5.0-dev+1357-g192f89ea1')).toEqual([ - 0, - 5, - 0, - 'dev+1357-g192f89ea1', - ]); + expect(parseVersion('0.5.0-dev+1357-g192f89ea1')).toEqual([0, 5, 0, 'dev+1357-g192f89ea1']); expect(parseVersion('0.5.0-dev+1357-g192f89ea1-Homebrew')).toEqual([ 0, 5, @@ -51,39 +46,22 @@ describe('findNvim', () => { expect(compareVersions('0.3.0', '0.3.1')).toBe(-1); expect(compareVersions('0.3.1', '0.3.0')).toBe(1); expect(compareVersions('0.3.0-abc', '0.3.0-dev-420')).toBe(-1); - expect(compareVersions('0.3.0', '0.3.0-dev-658+g06694203e-Homebrew')).toBe( - 1 - ); - expect(compareVersions('0.3.0-dev-658+g06694203e-Homebrew', '0.3.0')).toBe( - -1 - ); + expect(compareVersions('0.3.0', '0.3.0-dev-658+g06694203e-Homebrew')).toBe(1); + expect(compareVersions('0.3.0-dev-658+g06694203e-Homebrew', '0.3.0')).toBe(-1); expect( - compareVersions( - '0.3.0-dev-658+g06694203e-Homebrew', - '0.3.0-dev-658+g06694203e-Homebrew' - ) + compareVersions('0.3.0-dev-658+g06694203e-Homebrew', '0.3.0-dev-658+g06694203e-Homebrew') ).toBe(0); expect( - compareVersions( - '0.3.0-dev-658+g06694203e-Homebrew', - '0.3.0-dev-659+g06694203e-Homebrew' - ) + compareVersions('0.3.0-dev-658+g06694203e-Homebrew', '0.3.0-dev-659+g06694203e-Homebrew') ).toBe(-1); expect( - compareVersions( - '0.3.0-dev-659+g06694203e-Homebrew', - '0.3.0-dev-658+g06694203e-Homebrew' - ) + compareVersions('0.3.0-dev-659+g06694203e-Homebrew', '0.3.0-dev-658+g06694203e-Homebrew') ).toBe(1); // Failure modes: expect(compareVersions('0.3.0', 'nonsense')).toBe(1); - expect(() => compareVersions('nonsense', '0.3.0')).toThrow( - 'Invalid version: "nonsense"' - ); - expect(() => compareVersions('nonsense', 'nonsense')).toThrow( - 'Invalid version: "nonsense"' - ); + expect(() => compareVersions('nonsense', '0.3.0')).toThrow('Invalid version: "nonsense"'); + expect(() => compareVersions('nonsense', 'nonsense')).toThrow('Invalid version: "nonsense"'); expect(() => compareVersions(undefined, undefined)).toThrow( 'Invalid version format: not a string' ); diff --git a/packages/neovim/src/utils/findNvim.ts b/packages/neovim/src/utils/findNvim.ts index abca031e..b12b4e5e 100644 --- a/packages/neovim/src/utils/findNvim.ts +++ b/packages/neovim/src/utils/findNvim.ts @@ -90,11 +90,7 @@ function parseVersion(version: string): (number | string)[] | undefined { const minorNumber = Number(minor); const patchNumber = Number(patch); - const versionParts: Array = [ - majorNumber, - minorNumber, - patchNumber, - ]; + const versionParts: Array = [majorNumber, minorNumber, patchNumber]; if (prerelease !== undefined) { versionParts.push(prerelease); } else { @@ -219,17 +215,14 @@ export function findNvim(opt: FindNvimOptions = {}): Readonly { try { accessSync(nvimPath, constants.X_OK); // TODO: fallback to `echo 'print(vim.version())' | nvim -l -` if parsing --version fails. - const nvimVersionFull = execFileSync(nvimPath, [ - '--version', - ]).toString(); + const nvimVersionFull = execFileSync(nvimPath, ['--version']).toString(); const nvimVersionMatch = nvimVersionRegex.exec(nvimVersionFull); const buildTypeMatch = buildTypeRegex.exec(nvimVersionFull); const luaJitVersionMatch = luaJitVersionRegex.exec(nvimVersionFull); if (nvimVersionMatch && buildTypeMatch && luaJitVersionMatch) { if ( 'minVersion' in opt && - compareVersions(opt.minVersion ?? '0.0.0', nvimVersionMatch[1]) === - 1 + compareVersions(opt.minVersion ?? '0.0.0', nvimVersionMatch[1]) === 1 ) { invalid.push({ nvimVersion: nvimVersionMatch[1], @@ -263,9 +256,7 @@ export function findNvim(opt: FindNvimOptions = {}): Readonly { } if (opt.orderBy === undefined || opt.orderBy === 'desc') { - matches.sort((a, b) => - compareVersions(b.nvimVersion ?? '0.0.0', a.nvimVersion ?? '0.0.0') - ); + matches.sort((a, b) => compareVersions(b.nvimVersion ?? '0.0.0', a.nvimVersion ?? '0.0.0')); } return { diff --git a/packages/neovim/src/utils/logger.ts b/packages/neovim/src/utils/logger.ts index acba525c..726d0ff5 100644 --- a/packages/neovim/src/utils/logger.ts +++ b/packages/neovim/src/utils/logger.ts @@ -22,8 +22,7 @@ function getFormat(colorize: boolean) { } catch { msg = info.message; } - const lvl = - info.level === 'debug' ? 'DBG' : info.level.slice(0, 3).toUpperCase(); + const lvl = info.level === 'debug' ? 'DBG' : info.level.slice(0, 3).toUpperCase(); return `${info.timestamp} ${lvl} ${msg}`; }) ); @@ -63,10 +62,7 @@ function setupWinstonLogger(): Logger { if (k === 'assert') { // XXX: support console.assert() even though our logger doesn't define it. // eslint-disable-next-line no-console - console.assert = function ( - condition?: boolean | undefined, - ...data: any[] - ) { + console.assert = function (condition?: boolean | undefined, ...data: any[]) { if (!condition) { logger.error('assertion failed', ...data); } diff --git a/packages/neovim/src/utils/transport.ts b/packages/neovim/src/utils/transport.ts index 681c4f1c..66fbe138 100644 --- a/packages/neovim/src/utils/transport.ts +++ b/packages/neovim/src/utils/transport.ts @@ -5,12 +5,7 @@ import { EventEmitter } from 'node:events'; import { inspect } from 'node:util'; -import { - encode, - decode, - ExtensionCodec, - decodeMultiStream, -} from '@msgpack/msgpack'; +import { encode, decode, ExtensionCodec, decodeMultiStream } from '@msgpack/msgpack'; import { Metadata } from '../api/types'; export let exportsForTesting: any; // eslint-disable-line import/no-mutable-exports @@ -38,16 +33,9 @@ class Response { throw new Error(`Response to id ${this.requestId} already sent`); } - const encoded = encode([ - 1, - this.requestId, - isError ? resp : null, - !isError ? resp : null, - ]); + const encoded = encode([1, this.requestId, isError ? resp : null, !isError ? resp : null]); - this.encoder.write( - Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength) - ); + this.encoder.write(Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength)); this.sent = true; } } @@ -61,8 +49,7 @@ class Transport extends EventEmitter { private writer!: NodeJS.WritableStream; - private readonly extensionCodec: ExtensionCodec = - this.initializeExtensionCodec(); + private readonly extensionCodec: ExtensionCodec = this.initializeExtensionCodec(); // Neovim client that holds state private client: any; @@ -96,11 +83,7 @@ class Transport extends EventEmitter { return Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); } - attach( - writer: NodeJS.WritableStream, - reader: NodeJS.ReadableStream, - client: any - ) { + attach(writer: NodeJS.WritableStream, reader: NodeJS.ReadableStream, client: any) { this.writer = writer; this.reader = reader; this.client = client; @@ -157,9 +140,7 @@ class Transport extends EventEmitter { request(method: string, args: any[], cb: Function) { this.nextRequestId = this.nextRequestId + 1; - this.writer.write( - this.encodeToBuffer([0, this.nextRequestId, method, args]) - ); + this.writer.write(this.encodeToBuffer([0, this.nextRequestId, method, args])); this.pending.set(this.nextRequestId, cb); } @@ -176,12 +157,7 @@ class Transport extends EventEmitter { // - msg[1]: id // - msg[2]: method name // - msg[3]: arguments - this.emit( - 'request', - msg[2].toString(), - msg[3], - new Response(this.writer, msg[1]) - ); + this.emit('request', msg[2].toString(), msg[3], new Response(this.writer, msg[1])); } else if (msgType === 1) { // response to a previous request: // - msg[1]: the id @@ -200,9 +176,7 @@ class Transport extends EventEmitter { // - msg[2]: arguments this.emit('notification', msg[1].toString(), msg[2]); } else { - this.writer.write( - this.encodeToBuffer([1, 0, 'Invalid message type', null]) - ); + this.writer.write(this.encodeToBuffer([1, 0, 'Invalid message type', null])); } } } diff --git a/packages/neovim/src/utils/util.ts b/packages/neovim/src/utils/util.ts index 46ae85c7..cc2e428e 100644 --- a/packages/neovim/src/utils/util.ts +++ b/packages/neovim/src/utils/util.ts @@ -19,11 +19,7 @@ export function partialClone( replacement: any = undefined ): any { // Base case: If input is not an object or has no children, return it. - if ( - typeof obj !== 'object' || - obj === null || - Object.getOwnPropertyNames(obj).length === 0 - ) { + if (typeof obj !== 'object' || obj === null || Object.getOwnPropertyNames(obj).length === 0) { return obj; } @@ -39,12 +35,7 @@ export function partialClone( if (omitKeys.includes(key)) { (clonedObj as any)[key] = replacement || (Array.isArray(obj) ? [] : {}); } else if (Object.prototype.hasOwnProperty.call(obj, key)) { - (clonedObj as any)[key] = partialClone( - obj[key], - depth - 1, - omitKeys, - replacement - ); + (clonedObj as any)[key] = partialClone(obj[key], depth - 1, omitKeys, replacement); } }