Repository navigation
Expand file tree
/
Copy pathBeautificationManager.js
More file actions
369 lines (348 loc) · 16.4 KB
/
Copy pathBeautificationManager.js
File metadata and controls
369 lines (348 loc) · 16.4 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
// @INCLUDE_IN_API_DOCS
/**
* Beautification manager interacts with beautify extensions to determine what to do when user issues `beautify code`
* command. Beautification providers can use this module to register new providers to beautify new languages.
*
* ## API
* ### registerBeautificationProvider
* Register a Beautification provider with this api.
*
* @example
* ```js
* // syntax
* BeautificationManager.registerBeautificationProvider(provider, supportedLanguages, priority);
* ```
* The API requires three parameters:
* 1. `provider`: must implement a `beautifyEditorProvider` and `beautifyTextProvider` function. See doc below:
* 1. `supportedLanguages`: An array of languages that the provider supports. If `["all"]` is supplied, then the
* provider will be invoked for all languages. Restrict to specific languages: Eg: `["javascript", "html", "php"]`
* 1. `priority`: Used to break ties among providers for a particular language. Providers with a higher number
* will be asked for beatified code before those with a lower priority value. Defaults to zero.
*
* @example
* ```js
* // to register a provider that will be invoked for all languages. where provider is any object that implements
* // a `beautifyEditorProvider` and `beautifyTextProvider` function
* BeautificationManager.registerBeautificationProvider(provider, ["all"]);
*
* // to register a provider that will be invoked for specific languages
* BeautificationManager.registerBeautificationProvider(provider, ["javascript", "html", "php"]);
* ```
*
* ### removeBeautificationProvider
* Removes a registered Beautification provider. The API takes the same arguments as `registerBeautificationProvider`.
*
* @example
* ```js
* // syntax
* BeautificationManager.removeBeautificationProvider(provider, supportedLanguages);
* // Example
* BeautificationManager.removeBeautificationProvider(provider, ["javascript", "html"]);
* ```
*
* ### provider.beautifyEditorProvider
* Each provider must implement the `beautifyEditorProvider` function that returns a promise. The promise either resolves with
* the beautified code details or rejects if there is nothing to beautify for the provider.
*
* @example
* ```js
* // function signature
* provider.beautifyEditorProvider = function(editor) {
* return new Promise((resolve, reject)=>{
* resolve({
* originalText: "the original text sent to beautify",
* changedText: "partial or full text that changed.",
* // Optional cursor offset if given will set the editor cursor to the position after beautification.
* // either `cursorOffset` or `ranges` can be specified, but not both.
* cursorOffset: number,
* // Optional: If range is specified, only the given range will be replaced. else full text is replaced
* ranges:{
* replaceStart: {line,ch},
* replaceEnd: {line,ch}
* }
* });
* });
* };
* ```
*
* #### The resolved promise object
* The resolved promise should either be `null`(indicating that the extension itself has prettified the code and
* doesn't want any further processing from BeautificationManager.) or contain the following details:
* 1. `originalText` - string, the original text sent to beautify
* 1. `changedText` - string, this should be the fully prettified text of the whole `originalText` or a fragment of
* pretty text in `originalText` if a range was selected. If a `fragment` is returned, then the
* `ranges` object must be specified.
* 1. `cursorOffset` - Optional number, if given will set the editor cursor to the position after beautification.
* either `cursorOffset` or `ranges` can be specified, but not both.
* 1. `ranges` - Optional object, set of 2 cursors that gives details on what range to replace with given changed text.
* If range is not specified, the full text in the editor will be replaced. range has 2 fields:
* 1. `replaceStart{line,ch}` - the start of range to replace
* 1. `replaceEnd{line,ch}` - the end of range to replace
*
* ### provider.beautifyTextProvider
* Each provider must implement the `beautifyTextProvider` function that returns a promise.
* The promise either resolves with the beautified code details(same as beautifyEditorProvider) or rejects if
* there is nothing to beautify for the provider.
*
* @example
* ```js
* // function signature.
* provider.beautifyTextProvider = function(textToBeautify, filePathOrFileName) {
* return new Promise((resolve, reject)=>{
* resolve({
* originalText: "the original text sent to beautify",
* changedText: "partial or full text that changed.",
* // Optional: If range is specified, only the given range is assumed changed. else full text changed.
* ranges:{
* replaceStart: {line,ch},
* replaceEnd: {line,ch}
* }
* });
* });
* };
* ```
* #### Parameters
* The `beautifyTextProvider` callback will receive the following arguments.
* 1. textToBeautify - string
* 1. filePathOrFileName - string. This will either be a valid file path, or a file name to deduce which language the
* beautifier is dealing with.
* #### The resolved promise object
* The resolved object has the same structure as beautifyEditorProvider resolved promise object.
* @module features/BeautificationManager
*/
define(function (require, exports, module) {
const Commands = require("command/Commands"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils"),
AppInit = require("utils/AppInit"),
CommandManager = require("command/CommandManager"),
LanguageManager = require("language/LanguageManager"),
Menus = require("command/Menus"),
EditorManager = require("editor/EditorManager"),
DocumentManager = require("document/DocumentManager"),
ProjectManager = require("project/ProjectManager"),
PreferencesManager = require("preferences/PreferencesManager"),
ProviderRegistrationHandler = require("features/PriorityBasedRegistration").RegistrationHandler;
const PREFERENCES_BEAUTIFY_ON_SAVE = "BeautifyOnSave",
FAILED_EDITOR_TEXT_CHANGED = "Beautify failed- editorTextChanged";
let _providerRegistrationHandler = new ProviderRegistrationHandler(),
registerBeautificationProvider = _providerRegistrationHandler
.registerProvider.bind(_providerRegistrationHandler),
removeBeautificationProvider = _providerRegistrationHandler
.removeProvider.bind(_providerRegistrationHandler),
beautifyCommand,
beautifyOnSaveCommand;
function _getEnabledProviders(filepath) {
let language = LanguageManager.getLanguageForPath(filepath);
return _providerRegistrationHandler.getProvidersForLanguageId(language.getId());
}
async function _getBeautifiedCodeDetails(editor) {
let enabledProviders = _getEnabledProviders(editor.document.file.fullPath);
for(let item of enabledProviders){
if(!item.provider.beautifyEditorProvider || !item.provider.beautifyTextProvider){
console.error(
"Beautify providers must implement `beautifyEditorProvider` and `beautifyTextProvider` function",
item);
continue;
}
try{
let beautyObject = await item.provider.beautifyEditorProvider(editor);
if(beautyObject){
return beautyObject;
}
} catch (e) {
// providers reject if they didn't beautify the code. We do nothing in the case as expected failure.
}
}
throw new Error("No Providers beautified text");
}
function _onActiveEditorChange(_evt, current) {
if(current && _getEnabledProviders(current.document.file.fullPath).length){
beautifyCommand.setEnabled(true);
return;
}
beautifyCommand.setEnabled(false);
}
function _replaceText(editor, beautyObject) {
if (editor.document.getText() !== beautyObject.originalText){
// editor text changed in between beautification. we cant apply changes
throw new Error(FAILED_EDITOR_TEXT_CHANGED);
}
let ranges = beautyObject.ranges || {
replaceStart: {line: 0, ch: 0},
replaceEnd: editor.getEndingCursorPos()
};
if(editor.document.getRange(ranges.replaceStart, ranges.replaceEnd) !== beautyObject.changedText) {
if(editor.hasSelection()){
editor.setSelection(ranges.replaceStart, ranges.replaceEnd);
editor.replaceSelection(beautyObject.changedText, 'around');
} else {
let cursor = editor.getCursorPos();
editor.replaceRange(beautyObject.changedText, ranges.replaceStart, ranges.replaceEnd);
if(beautyObject.cursorOffset || beautyObject.cursorOffset === 0){
// we have accurate cursor positioning from beautifier
cursor = editor.posFromIndex(beautyObject.cursorOffset);
}
editor.setCursorPos(cursor.line, cursor.ch);
}
}
}
/**
* Beautifies text in the given editor with available providers.
* @param editor
* @return {Promise} - A promise that will be resolved to null if the selected text is beautified or rejects
* if beautification failed.
* @type {function}
*/
function beautifyEditor(editor){
return new Promise((resolve, reject)=>{
if(!editor){
reject();
return;
}
_getBeautifiedCodeDetails(editor).then(beautyObject => {
if(!beautyObject || !beautyObject.changedText){
reject();
return;
}
let rejected = false;
editor.operation(function () {
try{
_replaceText(editor, beautyObject);
} catch (e) {
rejected = true;
reject(e);
}
});
if(!rejected){
resolve();
}
}).catch(e => {
reject(e);
});
});
}
/**
* Beautifies text with available providers.
* @param {string} textToBeautify
* @param {string} filePathOrFileName Note that the file path may not actually exist on disk. It is just used to
* infer what language beautifier is to be applied.
* @return {Promise} - A promise that will be resolved to null if the selected text is beautified or rejects
* if beautification failed..
* #### The resolved promise object
* The resolved promise object contain the following details:
* 1. `originalText` - string, the original text sent to beautify
* 1. `changedText` - string, the prettified text.
* 1. `ranges` - Optional. if range object is returned, it means that only a part of the original text changed in
* the original text `textToBeautify`. The part that changed is supplied by two cursor positions below:
* 1. `replaceStart{line,ch}` - the start of range to replace
* 1. `replaceEnd{line,ch}` - the end of range to replace
* @type {function}
*/
async function beautifyText(textToBeautify, filePathOrFileName){
let enabledProviders = _getEnabledProviders(filePathOrFileName);
for(let item of enabledProviders){
if(!item.provider.beautifyEditorProvider || !item.provider.beautifyTextProvider){
console.error(
"Beautify providers must implement `beautifyEditorProvider` and `beautifyTextProvider` function",
item);
continue;
}
try{
let beautyObject = await item.provider.beautifyTextProvider(textToBeautify, filePathOrFileName);
if(beautyObject){
return beautyObject;
}
} catch (e) {
// providers reject if they didn't beautify the code. We do nothing in the case as expected failure.
}
}
throw new Error("No Providers beautified text");
}
function _beautifyCommand() {
let result = new $.Deferred();
let editor = EditorManager.getActiveEditor();
if(!editor){
result.reject();
return result.promise();
}
let busyMessage = StringUtils.format(Strings.BEAUTIFY_PROJECT_BUSY_MESSAGE, editor.getFile().name);
ProjectManager.setProjectBusy(true, busyMessage);
beautifyEditor(editor).then( () => {
ProjectManager.setProjectBusy(false, busyMessage);
console.log("Beautified");
result.resolve();
}).catch(e=>{
let message = editor.hasSelection() ? Strings.BEAUTIFY_ERROR_SELECTION : Strings.BEAUTIFY_ERROR;
if(e.message === FAILED_EDITOR_TEXT_CHANGED){
message = Strings.BEAUTIFY_ERROR_ORIGINAL_CHANGED;
}
editor.displayErrorMessageAtCursor(message);
ProjectManager.setProjectBusy(false, busyMessage);
console.warn("No beautify providers responded", e);
result.reject();
});
return result.promise();
}
function _beautifyOnSave(_evt, doc) {
let editor = EditorManager.getActiveEditor();
if(!_isBeautifyOnSaveEnabled() || !editor || editor.document.file.fullPath !== doc.file.fullPath){
return;
}
if(!_getEnabledProviders(doc.file.fullPath).length){
// no beautify provider registered for this file type, silently skip instead of showing an error.
return;
}
editor.clearSelection();
_beautifyCommand();
}
function _isBeautifyOnSaveEnabled() {
return PreferencesManager.getViewState(PREFERENCES_BEAUTIFY_ON_SAVE) === "true";
}
function _toggleBeautifyOnSave() {
let beautifyOnSave = _isBeautifyOnSaveEnabled();
PreferencesManager.setViewState(PREFERENCES_BEAUTIFY_ON_SAVE, `${!beautifyOnSave}`);
beautifyOnSaveCommand.setChecked(!beautifyOnSave);
}
AppInit.appReady(function () {
beautifyCommand = CommandManager.register(Strings.CMD_BEAUTIFY_CODE,
Commands.EDIT_BEAUTIFY_CODE, ()=>{
_beautifyCommand();
});
beautifyOnSaveCommand = CommandManager.register(Strings.CMD_BEAUTIFY_CODE_ON_SAVE,
Commands.EDIT_BEAUTIFY_CODE_ON_SAVE, ()=>{
_toggleBeautifyOnSave();
});
let editMenu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
editMenu.addMenuItem(Commands.EDIT_BEAUTIFY_CODE, "");
editMenu.addMenuItem(Commands.EDIT_BEAUTIFY_CODE_ON_SAVE, "");
let editorContextMenu = Menus.getContextMenu(Menus.ContextMenuIds.EDITOR_MENU);
editorContextMenu.addMenuItem(Commands.EDIT_BEAUTIFY_CODE, "", Menus.AFTER, Commands.EDIT_SELECT_ALL);
beautifyOnSaveCommand.setChecked(_isBeautifyOnSaveEnabled());
EditorManager.on("activeEditorChange", _onActiveEditorChange);
DocumentManager.on('documentSaved.beautificationManager', _beautifyOnSave);
});
exports.registerBeautificationProvider = registerBeautificationProvider;
exports.removeBeautificationProvider = removeBeautificationProvider;
exports.beautifyEditor = beautifyEditor;
exports.beautifyText = beautifyText;
});