-
Notifications
You must be signed in to change notification settings - Fork 1
/
extension.js
306 lines (260 loc) · 10.3 KB
/
extension.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
const vscode = require('vscode')
const axios = require('axios').default
const md5 = require('md5')
const { Case } = require('change-case-all')
const switchId = 'banjiao.switch'
const batchId = 'banjiao.batch'
const keymapsId = 'banjiao.keymaps'
const setNameId = 'banjiao.setName'
const translateAppidId = 'banjiao.translateAppid'
const translateSecretId = 'banjiao.translateSecret'
let switchConfig
let batchConfig
let keymapsConfig
let translateAppidConfig
let translateSecretConfig
function setConfig () {
const config = vscode.workspace.getConfiguration()
switchConfig = config.get(switchId)
batchConfig = config.get(batchId)
keymapsConfig = config.get(keymapsId)
translateAppidConfig = config.get(translateAppidId)
translateSecretConfig = config.get(translateSecretId)
}
function getHalfWidthChar (char) {
for (let i = 0; i < keymapsConfig.length; i++) {
if (keymapsConfig[i].full === char) {
return keymapsConfig[i].half
}
}
return char
}
function convertToHalfWidthChar (event) {
if (vscode.window.activeTextEditor === undefined) return
vscode.window.activeTextEditor.edit(
editBuilder => {
event.contentChanges.forEach(content => {
const currentPosition = content.range.start
const contentText = content.text
let contentTextRange
if (contentText.length === 1) {
// 只处理单符号
let halfChar, prevChar
if (currentPosition.character > 0) {
prevChar = event.document.getText(new vscode.Range(currentPosition.translate(0, -1), currentPosition))
}
// ^ 全角 …… 会触发两次change事件
if (contentText === '…' && contentText === prevChar) {
halfChar = getHalfWidthChar(contentText)
contentTextRange = new vscode.Range(currentPosition.translate(0, -1), currentPosition.translate(0, 1))
editBuilder.replace(contentTextRange, halfChar)
}
// _ 全角 —— 会触发两次change事件
if (contentText === '—' && contentText === prevChar) {
halfChar = getHalfWidthChar(contentText)
contentTextRange = new vscode.Range(currentPosition.translate(0, -1), currentPosition.translate(0, 1))
editBuilder.replace(contentTextRange, halfChar)
}
// 其他全角字符
if (contentText !== '…' && contentText !== '—') {
halfChar = getHalfWidthChar(contentText)
if (halfChar !== contentText) {
contentTextRange = new vscode.Range(currentPosition, currentPosition.translate(0, 1))
editBuilder.replace(contentTextRange, halfChar)
}
}
} else if (batchConfig && contentText.length > 1) {
// 处理粘贴长文本
const replacedText = contentText.split('').reduce(
(previousChar, currentChar) => {
return previousChar + getHalfWidthChar(currentChar)
},
''
)
if (contentText !== replacedText) {
if (contentText.includes('\n')) { // 多行文本
const lines = contentText.split('\n')
const endLineNumber = currentPosition.line + lines.length - 1
const endLineText = lines[lines.length - 1]
const endLineDocumentText = vscode.window.activeTextEditor.document.lineAt(endLineNumber).text
const endLineCharacter = endLineDocumentText.indexOf(endLineText) + endLineText.length
const endPosition = new vscode.Position(endLineNumber, endLineCharacter)
contentTextRange = new vscode.Range(currentPosition, endPosition)
} else if (currentPosition.character === 0) { // 单行第一个位置
const lineText = vscode.window.activeTextEditor.document.lineAt(currentPosition.line).text
const startPosition = new vscode.Position(currentPosition.line, lineText.indexOf(contentText))
const endPosition = new vscode.Position(currentPosition.line, lineText.indexOf(contentText) + contentText.length)
contentTextRange = new vscode.Range(startPosition, endPosition)
} else { // 单行其他位置
const endPosition = new vscode.Position(currentPosition.line, currentPosition.character + content.text.length)
contentTextRange = new vscode.Range(currentPosition, endPosition)
}
editBuilder.replace(contentTextRange, replacedText)
}
}
})
},
{
undoStopAfter: false,
undoStopBefore: false
}
).then(fulfilled => {
if (fulfilled === false) {
convertToHalfWidthChar(event)
}
})
}
function getStatusBarItemLabel () {
return switchConfig ? '半角' : '全角'
}
function getStatusBarItemTooltip () {
return new vscode.MarkdownString(switchConfig ? '点击关半角 `Alt+B`' : '点击开半角 `Alt+B`')
}
async function fetchTranslateResult (originText, from, to) {
const domain = 'it'
const salt = Math.random()
try {
const response = await axios({
method: 'get',
url: 'https://fanyi-api.baidu.com/api/trans/vip/fieldtranslate',
params: {
q: originText,
from,
to,
appid: translateAppidConfig,
salt,
domain,
sign: md5(translateAppidConfig + originText + salt + domain + translateSecretConfig)
}
})
if (response.data.error_code) {
throw new Error(response.data.error_msg)
} else {
return {
translatedText: response.data.trans_result[0].dst
}
}
} catch (error) {
return {
errorMessage: error.message
}
}
}
function activate ({ subscriptions }) {
setConfig()
const switchCommand = vscode.commands.registerCommand(switchId, () => {
const config = vscode.workspace.getConfiguration()
const triggerSwitch = !switchConfig
config.update(switchId, triggerSwitch, vscode.ConfigurationTarget.Global)
})
subscriptions.push(switchCommand)
const setNameCommand = vscode.commands.registerCommand(setNameId, (variableNames, currentSelection) => {
const editor = vscode.window.activeTextEditor
if (!editor) return
const selection = new vscode.Selection(currentSelection.start, currentSelection.end)
editor.selection = selection
vscode.window.showQuickPick(
variableNames,
{
placeHolder: '请选择半角风格'
}
)
.then(selected => {
if (selected) {
editor.edit(editBuilder => {
editBuilder.replace(selection, selected)
})
}
})
})
subscriptions.push(setNameCommand)
const hoverProvider = vscode.languages.registerHoverProvider('*', {
async provideHover (document, position) {
if (
vscode.window.activeTextEditor === undefined ||
!(switchConfig && translateAppidConfig && translateSecretConfig)
) return
const selection = vscode.window.activeTextEditor.selection
const hoverRange = document.getWordRangeAtPosition(position)
let currentText, currentSelection
if (!hoverRange || hoverRange.isEmpty) return
if (selection.isEmpty) {
// 鼠标悬停且无选区
currentText = document.getText(hoverRange)
currentSelection = new vscode.Selection(hoverRange.start, hoverRange.end)
} else if (
selection.start.line === selection.end.line &&
position.line === selection.start.line &&
position.character >= selection.start.character &&
position.character <= selection.end.character
) {
// 鼠标悬停在当前选区范围内
currentText = document.getText(selection)
currentSelection = selection
} else {
return
}
const containsChinese = /[\u4e00-\u9fa5]/.test(currentText)
const sourceText = containsChinese ? currentText : Case.capital(currentText)
if (!sourceText || sourceText.length > 64) return
const sourceLanguage = containsChinese ? 'zh' : 'en'
const targetLanguage = containsChinese ? 'en' : 'zh'
const { translatedText, errorMessage } = await fetchTranslateResult(sourceText, sourceLanguage, targetLanguage)
if (errorMessage) {
vscode.window.showErrorMessage(errorMessage)
return
}
const capitalText = Case.capital(containsChinese ? translatedText : currentText)
const cleanedText = capitalText.replace(/The\s*|\s+/g, '') // 使用正则表达式删除所有的 The 和空格
const variableNames = [
Case.camel(cleanedText),
Case.pascal(cleanedText),
Case.kebab(cleanedText),
Case.snake(cleanedText),
Case.constant(cleanedText)
]
const command = vscode.Uri.parse(`command:banjiao.setName?${encodeURIComponent(JSON.stringify([variableNames, currentSelection]))}`)
const MarkdownString = new vscode.MarkdownString()
MarkdownString.isTrusted = true
MarkdownString.appendMarkdown(translatedText)
MarkdownString.appendMarkdown(` [半角](${command} "点击选择半角风格")`)
return new vscode.Hover(MarkdownString)
}
})
subscriptions.push(hoverProvider)
const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100)
statusBarItem.command = switchId
statusBarItem.text = getStatusBarItemLabel()
statusBarItem.tooltip = getStatusBarItemTooltip()
subscriptions.push(statusBarItem)
if (vscode.workspace.textDocuments.length > 0) {
statusBarItem.show()
}
vscode.window.onDidChangeActiveTextEditor(textEditor => {
if (textEditor) {
statusBarItem.show()
} else {
statusBarItem.hide()
}
})
vscode.workspace.onDidChangeConfiguration(() => {
setConfig()
statusBarItem.text = getStatusBarItemLabel()
statusBarItem.tooltip = getStatusBarItemTooltip()
})
vscode.workspace.onDidChangeTextDocument(event => {
// [undo 和 redo 时忽略转换](https://code.visualstudio.com/api/references/vscode-api#TextDocumentChangeReason)
if (event.reason === 1 || event.reason === 2) return
// 只处理代码文件修改
// 如 event.document.uri.scheme === 'vscode-scm' 是 vscode git 客户端 commit-msg 输入框会被禁止
if (switchConfig && event.document.uri.scheme !== 'vscode-scm') {
convertToHalfWidthChar(event)
}
})
console.info('已激活半角插件')
}
function deactivate () {}
module.exports = {
activate,
deactivate
}