Skip to content

Commit

Permalink
fix(keywordsInsertText): when return is accepted and then Enter
Browse files Browse the repository at this point in the history
…or `;` typed remove redundant space

fixes #57
  • Loading branch information
zardoy committed Nov 17, 2022
1 parent 3046778 commit 6cb12ba
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 38 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
"@vscode/emmet-helper": "^2.8.4",
"@vscode/test-electron": "^2.1.5",
"@zardoy/utils": "^0.0.9",
"@zardoy/vscode-utils": "^0.0.41",
"@zardoy/vscode-utils": "^0.0.45",
"chai": "^4.3.6",
"chokidar": "^3.5.3",
"chokidar-cli": "^3.0.0",
Expand Down
9 changes: 5 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 2 additions & 33 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable @typescript-eslint/no-require-imports */
import * as vscode from 'vscode'
import { defaultJsSupersetLangs } from '@zardoy/vscode-utils/build/langs'
import { getActiveRegularEditor } from '@zardoy/vscode-utils'
import { extensionCtx, getExtensionSettingId } from 'vscode-framework'
import { pickObj } from '@zardoy/utils'
import { Configuration } from './configurationType'
Expand All @@ -12,6 +11,7 @@ import experimentalPostfixes from './experimentalPostfixes'
import migrateSettings from './migrateSettings'
import figIntegration from './figIntegration'
import apiCommands from './apiCommands'
import onCompletionAccepted from './onCompletionAccepted'

export const activateTsPlugin = (tsApi: { configurePlugin; onCompletionAccepted }) => {
let webWaitingForConfigSync = false
Expand Down Expand Up @@ -46,38 +46,7 @@ export const activateTsPlugin = (tsApi: { configurePlugin; onCompletionAccepted
})
syncConfig()

tsApi.onCompletionAccepted((item: vscode.CompletionItem & { document: vscode.TextDocument }) => {
const enableMethodSnippets = vscode.workspace.getConfiguration(process.env.IDS_PREFIX, item.document).get('enableMethodSnippets')
const { documentation = '' } = item
const documentationString = documentation instanceof vscode.MarkdownString ? documentation.value : documentation
const insertFuncArgs = /<!-- insert-func: (.*)-->/.exec(documentationString)?.[1]
console.debug('insertFuncArgs', insertFuncArgs)
if (enableMethodSnippets && insertFuncArgs !== undefined) {
const editor = getActiveRegularEditor()!
const startPos = editor.selection.start
const nextSymbol = editor.document.getText(new vscode.Range(startPos, startPos.translate(0, 1)))
if (!['(', '.'].includes(nextSymbol)) {
const snippet = new vscode.SnippetString('')
snippet.appendText('(')
const args = insertFuncArgs.split(',')
for (let [i, arg] of args.entries()) {
if (!arg) continue
// skip empty, but add tabstops if we explicitly want it!
if (arg === ' ') arg = ''
snippet.appendPlaceholder(arg)
if (i !== args.length - 1) snippet.appendText(', ')
}

snippet.appendText(')')
void editor.insertSnippet(snippet, undefined, {
undoStopAfter: false,
undoStopBefore: false,
})
if (vscode.workspace.getConfiguration('editor.parameterHints').get('enabled'))
void vscode.commands.executeCommand('editor.action.triggerParameterHints')
}
}
})
onCompletionAccepted(tsApi)

if (process.env.PLATFORM === 'web') {
const possiblySyncConfig = async () => {
Expand Down
98 changes: 98 additions & 0 deletions src/onCompletionAccepted.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import * as vscode from 'vscode'
import { getActiveRegularEditor } from '@zardoy/vscode-utils'
import { watchExtensionSettings } from '@zardoy/vscode-utils/build/settings'
import { getExtensionSetting, Settings } from 'vscode-framework'
import { oneOf } from '@zardoy/utils'

export default (tsApi: { onCompletionAccepted }) => {
let justAcceptedReturnKeywordSuggestion = false

tsApi.onCompletionAccepted((item: vscode.CompletionItem & { document: vscode.TextDocument }) => {
const enableMethodSnippets = vscode.workspace.getConfiguration(process.env.IDS_PREFIX, item.document).get('enableMethodSnippets')
const { insertText, documentation = '', kind } = item
if (kind === vscode.CompletionItemKind.Keyword && insertText === 'return ') {
justAcceptedReturnKeywordSuggestion = true
}

const documentationString = documentation instanceof vscode.MarkdownString ? documentation.value : documentation
const insertFuncArgs = /<!-- insert-func: (.*)-->/.exec(documentationString)?.[1]
console.debug('insertFuncArgs', insertFuncArgs)
if (enableMethodSnippets && insertFuncArgs !== undefined) {
const editor = getActiveRegularEditor()!
const startPos = editor.selection.start
const nextSymbol = editor.document.getText(new vscode.Range(startPos, startPos.translate(0, 1)))
if (!['(', '.'].includes(nextSymbol)) {
const snippet = new vscode.SnippetString('')
snippet.appendText('(')
const args = insertFuncArgs.split(',')
for (let [i, arg] of args.entries()) {
if (!arg) continue
// skip empty, but add tabstops if we explicitly want it!
if (arg === ' ') arg = ''
snippet.appendPlaceholder(arg)
if (i !== args.length - 1) snippet.appendText(', ')
}

snippet.appendText(')')
void editor.insertSnippet(snippet, undefined, {
undoStopAfter: false,
undoStopBefore: false,
})
if (vscode.workspace.getConfiguration('editor.parameterHints').get('enabled')) {
void vscode.commands.executeCommand('editor.action.triggerParameterHints')
}
}
}
})

conditionallyRegister(
'suggestions.keywordsInsertText',
() =>
vscode.workspace.onDidChangeTextDocument(({ document, contentChanges, reason }) => {
if (!justAcceptedReturnKeywordSuggestion) return
if (document !== vscode.window.activeTextEditor?.document) return
try {
if (oneOf(reason, vscode.TextDocumentChangeReason.Redo, vscode.TextDocumentChangeReason.Undo)) {
return
}

const char = contentChanges[0]?.text
if (char?.length !== 1 || contentChanges.some(({ text }) => text !== char)) {
return
}

if (char === ';') {
void vscode.window.activeTextEditor.edit(builder => {
for (const { range } of contentChanges) {
const pos = range.start
builder.delete(new vscode.Range(pos.translate(0, -1), pos))
}
})
}
} finally {
justAcceptedReturnKeywordSuggestion = false
}
}),
val => val !== 'none',
)
}

const conditionallyRegister = <T extends keyof Settings>(
settingKey: T,
registerFn: () => vscode.Disposable,
acceptSettingValue: (val: Settings[T]) => boolean = val => !!val,
) => {
let disposable: vscode.Disposable | undefined
const changeRegisterState = () => {
const registerState = acceptSettingValue(getExtensionSetting(settingKey))
if (registerState) {
if (!disposable) disposable = registerFn()
} else {
disposable?.dispose()
disposable = undefined
}
}

changeRegisterState()
watchExtensionSettings([settingKey], changeRegisterState)
}

0 comments on commit 6cb12ba

Please sign in to comment.