-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
68 lines (59 loc) · 1.73 KB
/
index.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
var fs = require('fs'),
path = require('path'),
spawn = require('child_process').spawn;
module.exports = {
config: {
binary: {
type: "string",
default: "/usr/local/bin/perltidy"
},
options: {
type: "array",
default: ["--pro=.../.perltidyrc"],
items: {
type: "string"
}
}
},
activate: function() {
atom.commands.add('atom-workspace', 'perltidy:tidy', function() {
var editor = atom.workspace.getActiveTextEditor();
var cwd = path.dirname(editor.getPath());
var binary = atom.config.get('perltidy.binary');
var options = atom.config.get('perltidy.options');
var selection = editor.getSelectedText();
var hasSelection = selection !== '';
var editorText = hasSelection ? selection : editor.getText();
if (fs.existsSync(binary)) {
var position = editor.getCursorScreenPosition();
perlTidy(binary, cwd, options, editorText, function (perl) {
editor.transact(function() {
if (hasSelection) {
editor.insertText(perl);
}
else {
editor.setText(perl);
}
editor.getLastCursor().setScreenPosition(position);
});
});
}
else {
editor.setText('No Perltidy found at "' + binary + '".');
}
});
}
};
function perlTidy(binary, cwd, options, before, cb) {
var after = '';
var perltidy = spawn(binary, options, {cwd: cwd, stdio: 'pipe'});
perltidy.stdin.setEncoding = 'utf-8';
perltidy.stdout.setEncoding = 'utf-8';
perltidy.stdin.end(before);
perltidy.on('exit', function() {
cb(after);
});
perltidy.stdout.on('data', function(chunk) {
after += chunk;
});
}