forked from stephenkeep/brackets-pretty-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
65 lines (50 loc) · 2.38 KB
/
main.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
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets */
/** Simple extension that adds a "File > Hello World" menu item. Inserts "Hello, world!" at cursor pos. */
define(function (require, exports, module) {
"use strict";
var CommandManager = brackets.getModule("command/CommandManager"),
EditorManager = brackets.getModule("editor/EditorManager"),
DocumentManager = brackets.getModule("document/DocumentManager"),
Menus = brackets.getModule("command/Menus");
// Function to run when the menu item is clicked
function prettyJson() {
var editor = EditorManager.getCurrentFullEditor();
if (editor) {
var unformattedText, isSelection = false;
var selectedText = editor.getSelectedText();
var selection = editor.getSelection();
if (selectedText.length > 0) {
isSelection = true;
unformattedText = selectedText;
} else {
unformattedText = DocumentManager.getCurrentDocument().getText();
}
var obj;
try {
obj = JSON.parse(unformattedText);
} catch (e) {
alert('Invalid JSON! Please check it');
return;
}
var formattedText = JSON.stringify(obj, null, "\t");
var doc = DocumentManager.getCurrentDocument();
doc.batchOperation(function () {
if (isSelection) {
doc.replaceRange(formattedText, selection.start, selection.end);
} else {
doc.setText(formattedText);
}
});
}
}
// First, register a command - a UI-less object associating an id to a handler
var MY_COMMAND_ID = "PrettyJson.MakePrettyJson"; // package-style naming to avoid collisions
CommandManager.register("PrettyJson", MY_COMMAND_ID, prettyJson);
// Then create a menu item bound to the command
// The label of the menu item is the name we gave the command (see above)
var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
// we use J here because P conficts with pep8 checker.
menu.addMenuItem(MY_COMMAND_ID, "Ctrl-Shift-J");
exports.prettyJson = prettyJson;
});