public
Last active

  • Download Gist
Bespin+Ubiquity.js
JavaScript
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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
 
//TODO: force this to be re-evaluated all the time
//if(CmdUtils.getDocument().location.href.indexOf("https://bespin.mozilla.com/") == 0){
var bespin = {cmd : {commands : {}}};
bespin.cmd.commands.add = function(obj){
var cmd = {};
var roles = ["object", "goal", "source", "location", "time"];
var ubiqArgs = [];
for(i in obj.takes){
ubiqArgs[i] = {role:roles[i],
nountype: noun_arb_text,
label : obj.takes[i]};
}
var names = [obj.name];
if(obj.aliases){
names = names.concat(obj.aliases);
}
var preview = obj.preview?obj.preview:"" +
"<br/>" + obj.usage?" Usage — " + obj.usage:"";
cmd["takes"] = null;
cmd["names"] = names;
cmd["icon"] = "https://bespin.mozilla.com/favicon.ico";
cmd["arguments"] = ubiqArgs;
cmd["description"] = obj.description?obj.description : "";
cmd["preview"] = preview;
cmd["execute"] = function( arguments ){
if(CmdUtils.getDocument().location.href.indexOf("https://bespin.mozilla.com/") != 0){
displayMessage("The command you just executed is a Bespin command and will only work if Bespin is your active tab.");
return;
}
var bespin = CmdUtils.getWindowInsecure().bespin;
var window = CmdUtils.getWindow();
var args = [];
for (i in obj.takes){
args.push(arguments[roles[i]].text?arguments[roles[i]].text:null);
}
bespin.get("actions").focusCommandline();
bespin.get("commandLine").executeCommand( obj.name + " " + args.join(" "), false);
}
CmdUtils.CreateCommand(cmd);
};
 
 
//TODO: stop the key event from propagating
//TODO: don't show hidden commands?
 
// ** {{{bespin.cmd.commands.add}}} **
//
// Add the command to the store which has a name -> command hash
// bespin.cmd.commands.add = function(command) {
// bespin.cmd.commands.store[command.name] = command;
// };
//
// // ** {{{bespin.cmd.commands.get}}} **
// //
// // Return a command from the store
// bespin.cmd.commands.get = function(commandname) {
// return bespin.cmd.commands.store[commandname];
// };
//
// // ** {{{Command: bespin.cmd.commands.toArgArray}}} **
// // Helper for when you have a command that needs to get a hold of it's params
// // as an array for processing
// bespin.cmd.commands.toArgArray = function(args) {
// if (args == null) {
// return [];
// }
// else {
// var spliten = args.split(" ");
// if (spliten.length == 1 && spliten[0] == "") {
// return [];
// }
// else {
// return spliten;
// }
// }
// };
//
// // == Start adding commands to the store ==
// //
// bespin.cmd.displayHelp = function(commandStore, instruction, extra, morehelpoutput) {
// var commands = [];
// var command, name;
//
// if (commandStore.commands[extra]) { // caught a real command
// command = commandStore.commands[extra];
// commands.push(command['description'] ? command.description : command.preview);
// } else {
// var showHidden = false;
//
// var subcmdextra = "";
// if (commandStore.subcommandFor) subcmdextra = " for " + commandStore.subcommandFor;
//
// if (extra) {
// if (extra == "hidden") { // sneaky, sneaky.
// extra = "";
// showHidden = true;
// }
// commands.push("Commands starting with '" + extra + "'.<br/>");
// }
//
// var tobesorted = [];
// for (name in commandStore.commands) {
// tobesorted.push(name);
// }
//
// var sorted = tobesorted.sort();
//
// commands.push("<table>");
// for (var i = 0; i < sorted.length; i++) {
// name = sorted[i];
// command = commandStore.commands[name];
//
// if (!showHidden && command.hidden) continue;
// if (extra && name.indexOf(extra) != 0) continue;
//
// var args = (command.takes) ? ' [' + command.takes.order.join('] [') + ']' : '';
//
// commands.push("<tr>");
// commands.push('<th>' + name + '</th>');
// commands.push('<td>' + command.preview + "</td>");
// commands.push('<td>' + args + '</td>');
// commands.push("</tr>");
// }
// commands.push("</table>");
// }
// instruction.addOutput(commands.join("") + (morehelpoutput || ""));
// };
 
// ** {{{Command: help}}} **
bespin.cmd.commands.add({
name: 'help',
takes: ['search'],
preview: 'show commands',
description: 'The <u>help</u> gives you access to the various commands in the Bespin system.<br/><br/>You can narrow the search of a command by adding an optional search params.<br/><br/>If you pass in the magic <em>hidden</em> parameter, you will find subtle hidden commands.<br/><br/>Finally, pass in the full name of a command and you can get the full description, which you just did to see this!',
completeText: 'optionally, narrow down the search',
execute: function(instruction, extra) {
bespin.cmd.displayHelp(instruction.commandLine.commandStore, instruction, extra);
}
});
 
// ** {{{Command: eval}}} **
bespin.cmd.commands.add({
name: 'eval',
takes: ['js-code'],
preview: 'evals given js code and show the result',
completeText: 'evals given js code and show the result',
execute: function(instruction, jscode) {
try {
var result = eval(jscode);
} catch (err) {
var result = '<b>Error: ' + err.message + '</b>';
}
 
var msg = '';
var type = '';
 
if (dojo.isFunction(result)) {
// converts the function to a well formated string
msg = (result + '').replace(/\n/g, '<br>').replace(/ /g, '&#160');
type = 'function';
} else if (dojo.isObject(result)) {
if (dojo.isArray(result)) {
type = 'array';
} else {
type = 'object';
}
 
var items = [];
var value;
 
for (x in result) {
if (dojo.isFunction(result[x])) {
value = "[function]";
} else if (dojo.isObject(result[x])) {
value = "[object]";
} else {
value = result[x];
}
 
items.push({name: x, value: value});
}
 
items.sort(function(a,b) {
return (a.name.toLowerCase() < b.name.toLowerCase()) ? -1 : 1;
});
 
for (var x = 0; x < items.length; x++) {
msg += '<b>' + items[x].name + '</b>: ' + items[x].value + '<br>';
}
 
} else {
msg = result;
type = typeof result;
}
 
instruction.addOutput("Result for eval <b>\""+jscode+"\"</b> (type: "+ type+"): <br><br>"+ msg);
}
});
 
// ** {{{Command: set}}} **
bespin.cmd.commands.add({
name: 'set',
takes: ['key', 'value'],
preview: 'define and show settings',
completeText: 'optionally, add a key and/or a value, else you will see all settings',
// complete: function(instruction, value) {
// console.log(instruction);
// console.log(value);
// return value;
// },
execute: function(instruction, setting) {
var output;
 
if (!setting.key) { // -- show all
var settings = bespin.get("settings").list();
output = "";
dojo.forEach(settings.sort(function (a, b) { // first sort the settings based on the key
if (a.key < b.key) {
return -1;
} else if (a.key == b.key) {
return 0;
} else {
return 1;
}
}), function(setting) { // now add to output unless hidden settings (start with a _)
if (setting.key[0] != '_') {
output += "<strong>" + setting.key + "</strong> = " + setting.value + "<br/>";
}
});
} else {
var key = setting.key;
if (setting.value === undefined) { // show it
var value = bespin.get("settings").get(key);
if (value) {
output = "<strong>" + key + "</strong> = " + value;
} else {
output = "You do not have a setting for '" + key + "'";
}
} else {
output = "Saving setting: <strong>" + key + "</strong> = " + setting.value;
bespin.get("settings").set(key, setting.value);
}
}
instruction.addOutput(output);
}
});
 
// ** {{{Command: unset}}} **
bespin.cmd.commands.add({
name: 'unset',
takes: ['key'],
preview: 'unset a setting entirely',
completeText: 'add a key for the setting to delete entirely',
execute: function(instruction, key) {
bespin.get("settings").unset(key);
instruction.addOutput("Unset the setting for " + key + ".");
}
});
 
// ** {{{Command: search}}} **
bespin.cmd.commands.add({
name: 'search',
takes: ['searchString'],
preview: 'searches the current file for the given searchString',
completeText: 'type in a string to search',
execute: function(instruction, str) {
bespin.get('actions').startSearch(str, 'commandLine');
}
});
 
// ** {{{Command: files (ls, list)}}} **
bespin.cmd.commands.add({
name: 'files',
aliases: ['ls', 'list'],
takes: ['project'],
preview: 'show files',
completeText: 'optionally, add the project name of your choice',
execute: function(instruction, project) {
if (!project) {
bespin.withComponent('editSession', function(editSession) {
project = editSession.project;
});
}
 
if (!project) {
instruction.addErrorOutput("You need to pass in a project");
return;
}
 
bespin.get('files').fileNames(project, function(fileNames) {
var files = "";
for (var x = 0; x < fileNames.length; x++) {
files += fileNames[x].name + "<br/>";
}
instruction.addOutput(files);
});
}
});
 
// ** {{{Command: status}}} **
bespin.cmd.commands.add({
name: 'status',
preview: 'get info on the current project and file',
execute: function(instruction) {
instruction.addOutput(bespin.get('editSession').getStatus());
}
});
 
// ** {{{Command: project}}} **
bespin.cmd.commands.add({
name: 'project',
takes: ['projectname'],
preview: 'show the current project, or set to a new one',
completeText: 'optionally, add the project name to change to that project',
execute: function(instruction, projectname) {
if (projectname) {
bespin.get('editSession').setProject(projectname);
instruction.addOutput('Changed project to ' + projectname);
} else {
instruction.addOutput(bespin.get('editSession').getStatus());
}
}
});
 
// ** {{{Command: projects}}} **
bespin.cmd.commands.add({
name: 'projects',
preview: 'show projects',
execute: function(instruction, extra) {
bespin.get('files').projects(function(projectNames) {
var projects = "";
for (var x = 0; x < projectNames.length; x++) {
projects += projectNames[x].name + "<br/>";
}
instruction.addOutput(projects);
});
}
});
 
// ** {{{Command: createproject}}} **
bespin.cmd.commands.add({
name: 'createproject',
takes: ['projectname'],
preview: 'create a new project',
usage: '[newprojectname]',
execute: function(instruction, project) {
if (!project) {
instruction.addUsageOutput(this);
return;
}
 
var onSuccess = instruction.link(function() {
bespin.get('editSession').setProject(project);
instruction.addOutput('Successfully created project \'' + project + '\'.');
});
 
var onFailure = instruction.link(function(xhr) {
instruction.addErrorOutput('Unable to create project \'' + project + '\: ' + xhr.responseText);
});
 
bespin.get('files').makeDirectory(project, '', onSuccess, onFailure);
}
});
 
// ** {{{Command: createproject}}} **
bespin.cmd.commands.add({
name: 'deleteproject',
takes: ['projectname'],
preview: 'delete a project',
usage: '[projectname]',
execute: function(instruction, project) {
if (!project) {
instruction.addUsageOutput(this);
return;
}
 
if (!project || project == bespin.userSettingsProject) {
instruction.addErrorOutput('Sorry, you can\'t delete the settings project.');
return;
}
 
var onSuccess = instruction.link(function() {
instruction.addOutput('Deleted project ' + project);
instruction.unlink();
});
 
var onFailure = instruction.link(function(xhr) {
instruction.addErrorOutput('Failed to delete project ' + project + ': ' + xhr.responseText);
instruction.unlink();
});
 
bespin.get('files').removeDirectory(project, '', onSuccess, onFailure);
}
});
 
// ** {{{Command: renameproject}}} **
bespin.cmd.commands.add({
name: 'renameproject',
takes: ['currentProject', 'newProject'],
preview: 'rename a project',
usage: '[currentProject], [newProject]',
execute: function(instruction, args) {
if (!args.currentProject || !args.newProject) {
instruction.addUsageOutput(this);
return;
}
bespin.publish("project:rename", { currentProject: args.currentProject, newProject: args.newProject });
}
});
 
// ** {{{Command: mkdir}}} **
bespin.cmd.commands.add({
name: 'mkdir',
takes: ['path', 'projectname'],
preview: 'create a new directory in the given project',
usage: '[path] [projectname]',
execute: function(instruction, args) {
if (!args.path) {
instruction.addUsageOutput(this);
return;
}
 
var editSession = bespin.get('editSession');
 
var path = args.path;
var project = args.projectname || editSession.project;
 
var onSuccess = instruction.link(function() {
if (path == '') editSession.setProject(project);
instruction.addOutput('Successfully created directory \'/' + project + '/' + path + '\'');
instruction.unlink();
});
 
var onFailure = instruction.link(function(xhr) {
instruction.addErrorOutput('Unable to create directory \'/' + project + '/' + path + '\': ' + xhr.responseText);
instruction.unlink();
});
 
bespin.get('files').makeDirectory(project, path, onSuccess, onFailure);
}
});
 
// ** {{{Command: save}}} **
bespin.cmd.commands.add({
name: 'save',
takes: ['filename'],
preview: 'save the current contents',
completeText: 'add the filename to save as, or use the current file',
withKey: "CMD S",
execute: function(instruction, filename) {
bespin.publish("editor:savefile", {
filename: filename
});
}
});
 
// ** {{{Command: load (open)}}} **
bespin.cmd.commands.add({
name: 'load',
aliases: ['open'],
takes: ['filename', 'project', 'line'],
preview: 'load up the contents of the file',
completeText: 'add the filename to open',
execute: function(instruction, opts) {
bespin.publish("editor:openfile", opts);
}
});
 
// ** {{{Command: preview}}} **
bespin.cmd.commands.add({
name: 'preview',
takes: ['filename'],
preview: 'view the file in a new browser window',
completeText: 'add the filename to view or use the current file',
execute: function(instruction, filename) {
bespin.publish("editor:preview", {
filename: filename
});
}
});
 
// ** {{{Command: editconfig}}} **
bespin.cmd.commands.add({
name: 'editconfig',
aliases: ['config'],
preview: 'load up the config file',
execute: function(instruction) {
bespin.publish("editor:config:edit");
}
});
 
// ** {{{Command: runconfig}}} **
bespin.cmd.commands.add({
name: 'runconfig',
preview: 'run your config file',
execute: function(instruction) {
bespin.publish("editor:config:run");
}
});
 
// ** {{{Command: cmdload}}} **
bespin.cmd.commands.add({
name: 'cmdload',
takes: ['commandname'],
preview: 'load up a new command',
completeText: 'command name to load (required)',
usage: '[commandname]: Command name required.',
execute: function(instruction, commandname) {
if (!commandname) {
instruction.addUsageOutput(this);
return;
}
bespin.publish("command:load", { commandname: commandname });
}
});
 
// ** {{{Command: cmdedit}}} **
bespin.cmd.commands.add({
name: 'cmdedit',
takes: ['commandname'],
aliases: ['cmdadd'],
preview: 'edit the given command (force if doesn\'t exist',
completeText: 'command name to edit (required)',
usage: '[commandname]: Command name required.',
execute: function(instruction, commandname) {
if (!commandname) {
instruction.addUsageOutput(this);
return;
}
 
bespin.publish("command:edit", { commandname: commandname });
}
});
 
// ** {{{Command: cmdlist}}} **
bespin.cmd.commands.add({
name: 'cmdlist',
preview: 'list my custom commands',
execute: function(instruction) {
bespin.publish("command:list");
}
});
 
// ** {{{Command: cmdrm}}} **
bespin.cmd.commands.add({
name: 'cmdrm',
takes: ['commandname'],
preview: 'delete a custom command',
completeText: 'command name to delete (required)',
usage: '[commandname]: Command name required.',
execute: function(instruction, commandname) {
if (!commandname) {
instruction.addUsageOutput(this);
return;
}
 
bespin.publish("command:delete", { commandname: commandname });
}
});
 
// ** {{{Command: newfile}}} **
bespin.cmd.commands.add({
name: 'newfile',
//aliases: ['new'],
takes: ['filename', 'project'],
preview: 'create a new buffer for file',
completeText: 'optionally, name the new filename first, and then the name of the project second',
withKey: "CTRL SHIFT N",
execute: function(instruction, args) {
if (args.filename) {
args.newfilename = args.filename;
delete args.filename;
}
bespin.publish("editor:newfile", args || {});
}
});
 
// ** {{{Command: rm (remove, del)}}} **
bespin.cmd.commands.add({
name: 'rm',
aliases: ['remove', 'del'],
takes: ['filename', 'project'],
preview: 'remove the file',
completeText: 'add the filename to remove, and optionally a specific project at the end. To delete a directory end the path in a '/'',
execute: function(instruction, args) {
var project = args.project || bespin.get('editSession').project;
var filename = args.filename;
 
if (!project) {
instruction.addErrorOutput("'rm' only works with the project is set.");
return;
}
 
if (!filename) {
instruction.addErrorOutput("give me a filename or directory to delete");
return;
}
 
bespin.get('files').removeFile(project, filename, function() {
if (bespin.get('editSession').checkSameFile(project, filename)) {
bespin.get("editor").model.clear(); // only clear if deleting the same file
}
 
instruction.addOutput('Removed file: ' + filename, true);
}, function(xhr) {
instruction.addErrorOutput("Wasn't able to remove the file <b>" + filename + "</b><br/><em>Error</em> (probably doesn't exist): " + xhr.responseText);
});
}
});
 
// ** {{{Command: closefile}}} **
bespin.cmd.commands.add({
name: 'closefile',
takes: ['filename', 'project'],
preview: 'close the file (may lose edits)',
completeText: 'add the filename to close (defaults to this file).<br>also, optional project name.',
execute: function(instruction, args) {
bespin.publish("editor:closefile", args);
}
});
 
// ** {{{Command: version}}} **
bespin.cmd.commands.add({
name: 'version',
takes: ['command'],
preview: 'show the version for Bespin or a command',
completeText: 'optionally, a command name',
execute: function(instruction, command) {
var bespinVersion = 'Your Bespin is at version ' + bespin.versionNumber + ', Code name: "' + bespin.versionCodename + '"';
var version;
if (command) {
var theCommand = instruction.commandLine.commandStore.commands[command];
if (!theCommand) {
version = "It appears that there is no command named '" + command + "', but " + bespinVersion;
} else {
version = (theCommand.version)
? "The command named '" + command + "' is at version " + theCommand.version
: "The command named '" + command + "' is a core command in Bespin version " + bespin.versionNumber;
}
}
else {
version = bespinVersion;
}
instruction.addOutput(version);
}
});
 
// ** {{{Command: clear}}} **
bespin.cmd.commands.add({
name: 'clear',
aliases: ['cls'],
preview: 'clear the file',
execute: function(instruction) {
bespin.get("editor").model.clear();
}
});
 
// ** {{{Command: goto}}} **
(function () {
var previewFull = 'move it! make the editor head to a line number or a function name.';
var preview = 'move it! make the editor head to a line number.';
var completeTextFull = 'add the line number to move to, or the name of a function in the file';
var completeText = 'add the line number to move to in the file';
var gotoCmd = {
name: 'goto',
takes: ['value'],
preview: previewFull,
completeText: completeTextFull,
execute: function(instruction, value) {
var settings = bespin.get("settings");
if (value) {
var linenum = parseInt(value, 10); // parse the line number as a decimal
 
if (isNaN(linenum)) { // it's not a number, so for now it is a function name
if(settings.isOn(settings.get("syntaxcheck"))) {
bespin.publish("parser:gotofunction", {
functionName: value
});
} else {
instruction.addErrorOutput("Please enter a valid line number.");
}
} else {
bespin.publish("editor:moveandcenter", {
row: linenum
});
}
}
}
};
bespin.cmd.commands.add(gotoCmd);
//TODO
// bespin.subscribe("settings:set:syntaxcheck", function () {
// var settings = bespin.get("settings");
// if(settings.isOn(settings.get("syntaxcheck"))) {
// gotoCmd.preview = previewFull;
// gotoCmd.completeText = completeTextFull;
// } else {
// gotoCmd.preview = preview;
// gotoCmd.completeText = completeText;
// }
// });
})();
 
// ** {{{Command: replace}}} **
bespin.cmd.commands.add({
name: 'replace',
takes: ['search', 'replace'],
preview: 's/foo/bar/g',
completeText: 'add the search regex, and then the replacement text',
execute: function(instruction, args) {
bespin.get("editor").ui.actions.replace(args);
}
});
 
// ** {{{Command: login}}} **
bespin.cmd.commands.add({
name: 'login',
// aliases: ['user'],
// takes: ['username', 'password'],
hidden: true,
takes: {
order: ['username', 'password'],
username: {
"short": 'u'
},
password: {
"short": 'p',
optional: true
}
},
preview: 'login to the service',
completeText: 'pass in your username and password',
execute: function(instruction, args) {
if (!args) { // short circuit if no username
instruction.commandLine.executeCommand("status");
return;
}
bespin.get('editSession').username = args.user; // TODO: normalize syncing
bespin.get('server').login(args.user, args.pass);
}
});
 
// ** {{{Command: logout}}} **
bespin.cmd.commands.add({
name: 'logout',
preview: 'log out',
execute: function(instruction) {
delete bespin.get('editSession').username;
bespin.get('server').logout(function() {
window.location.href="/";
});
}
});
 
// ** {{{Command: bespin}}} **
bespin.cmd.commands.add({
name: 'bespin',
preview: 'has',
hidden: true,
messages: [
"really wants you to trick it out in some way.",
"is your Web editor.",
"would love to be like Emacs on the Web.",
"is written on the Web platform, so you can tweak it."
],
execute: function(instruction) {
instruction.addOutput("Bespin " + this.messages[Math.floor(Math.random() * this.messages.length)]);
}
});
 
// ** {{{Command: sort}}} **
bespin.cmd.commands.add({
name: 'sort',
takes: ['direction'],
preview: 'sort the current buffer',
completeText: 'optionally, sort descending',
execute: function(instruction, direction) {
var buffer = bespin.get("editor").model.getDocument().split(/\n/);
buffer.sort();
if (direction && /^desc/.test(direction.toLowerCase())) {
buffer.reverse();
}
bespin.get("editor").model.insertDocument(buffer.join("\n"));
}
});
 
// ** {{{Command: quota}}} **
bespin.cmd.commands.add({
name: 'quota',
preview: 'show your quota info',
megabytes: function(bytes) {
return (bytes / 1024 / 1024).toFixed(2);
},
execute: function(instruction) {
var es = bespin.get('editSession');
var output = "You have " + this.megabytes(es.quota - es.amountUsed) +
" MB free space to put some great code!<br>" +
"Used " + this.megabytes(es.amountUsed) + " MB " +
"out of your " + this.megabytes(es.quota) + " MB quota.";
instruction.addOutput(output);
}
});
 
// ** {{{Command: export}}} **
bespin.cmd.commands.add({
name: 'export',
takes: ['project', 'archivetype'],
preview: 'export the given project with an archivetype of zip or tgz',
completeText: 'project name, archivetype (zip | tgz, defaults to zip)',
execute: function(instruction, args) {
var project = args.project || bespin.get('editSession').project;
 
var type = args.archivetype;
if (!bespin.util.include(['zip','tgz','tar.gz'], type)) {
type = 'zip';
}
 
bespin.get('server').exportProject(project, type); // try to do it via the iframe
}
});
 
// ** {{{Command: import}}} **
bespin.cmd.commands.add({
name: 'import',
takes: ['url', 'project'],
preview: 'import the given url as a project.<br>If a project name isn\'t given it will use the filename<br>If no URL is given to import, a file upload box will be shown to import.',
completeText: 'url (to an archive zip | tgz) and/or project name',
usage: "[url of archive] [projectname]<br><br><em>If only a URL is given, the projectname will be implied<br><br>If only a project name is given, a file upload window will be shown to upload.</em>",
// ** {{{calculateProjectName}}}
//
// Given a URL, work out the project name as a default
// For example, given http://foo.com/path/to/myproject.zip
// return "myproject"
calculateProjectName: function(url) {
var split = url.split('/');
var projectMaker = split[split.length - 1].split(".");
projectMaker.pop();
return projectMaker.join("_");
},
// ** {{{isURL}}}
//
// Test the given string to return if it is a URL.
// In this context it has to be http(s) only
isURL: function(url) {
return (url && (/^http(:|s:)/.test(url)));
},
upload: function(project) {
// use the center popup and inject a form in that points to the right place.
var el = dojo.byId('centerpopup');
 
 
el.innerHTML = "<div id='upload-container'><form method='POST' name='upload' id='upload' enctype='multipart/form-data'><div id='upload-header'>Import project via upload <img id='upload-close' src='images/icn_close_x.png' align='right'></div><div id='upload-content'><div id='upload-status'></div><p>Browse to find the project archive that you wish to archive<br>and then click on the <code>Upload</code> button.</p><center><input type='file' id='filedata' name='filedata' accept='application/zip,application/x-gzip'> <input type='submit' value='Upload'></center></div></form></div>";
 
dojo.require("dijit._base.place");
dojo.require("bespin.util.webpieces");
 
dojo.require("dojo.io.iframe");
 
dojo.connect(dojo.byId('upload'), "submit", function() {
dojo.byId('upload-status').innerHTML = 'Importing file into new project ' + project;
dojo.io.iframe.send({
url: '/project/import/' + project,
form: dojo.byId('upload'),
method: 'POST',
handleAs: 'text',
preventCache: true,
contentType: "multipart/form-data",
load: function(data, ioArg) {
dojo.byId('upload-status').innerHTML = 'Thanks for uploading the file!';
},
error: function(error, ioArg) {
setTimeout(function() {
bespin.get('files').projects(function(projectNames) {
if (dojo.some(projectNames, function(testProject) { return project + '/' == testProject.name; })) {
dojo.byId('upload-status').innerHTML = 'Archive imported and project ' + project + ' has been created!';
} else {
dojo.byId('upload-status').innerHTML = 'Error uploading the file. Sorry, try again!';
}
});
}, 100);
}
});
});
 
bespin.util.webpieces.showCenterPopup(el, true);
 
// TODO: refactor this block into webpieces if popup is modal
// pass the uploadClose DOM element as parameter to showCenterPopup
var uploadClose, overlay;
var hideCenterPopup = function(){
el.removeChild(el.firstChild);
bespin.util.webpieces.hideCenterPopup(el);
dojo.disconnect(uploadClose);
dojo.disconnect(overlay);
};
uploadClose = dojo.connect(dojo.byId("upload-close"), "onclick", hideCenterPopup);
overlay = dojo.connect(dojo.byId("overlay"), "onclick", hideCenterPopup);
},
 
// ** {{{execute}}}
//
// Can be called in three ways:
//
// * import http://foo.com/path/to/archive.zip
// * import http://foo.com/path/to/archive.zip projectName
// * import projectName http://foo.com/path/to/archive.zip
execute: function(instruction, args) {
var project, url;
 
// Fail fast. Nothing given?
if (!args.url) {
instruction.addUsageOutput(this);
return;
// * checking - import http://foo.com/path/to/archive.zip
} else if (!args.project && this.isURL(args.url)) {
args.project = this.calculateProjectName(args.url);
// * Oops, project and url are the wrong way around. That's fine
} else if (this.isURL(args.project)) {
project = args.project;
url = args.url;
args.project = url;
args.url = project;
// * Make sure that a URL came along at some point, else call up an upload box
} else if (!this.isURL(args.url)) {
var project = args.url; // only a project has been passed in
this.upload(project);
} else {
// * A project and URL are here and available to do a URL based import
project = args.project;
url = args.url;
 
instruction.addOutput("About to import " + project + " from:<br><br>" + url + "<br><br><em>It can take awhile to download the project, so be patient!</em>");
 
bespin.publish("project:import", { project: project, url: url });
}
}
});
 
// ** {{{Command: trim}}} **
bespin.cmd.commands.add({
name: 'trim',
takes: ['side'], // left, right, both
preview: 'trim trailing or leading whitespace',
completeText: 'optionally, give a side of left, right, or both (defaults to right)',
execute: function(instruction, side) {
if (!side) side = "right";
var replaceArgs = {
replace: ''
};
 
if (bespin.util.include(["left", "both"], side)) {
replaceArgs.search = "^\\s+";
bespin.get("editor").ui.actions.replace(replaceArgs);
}
 
if (bespin.util.include(["right", "both"], side)) {
replaceArgs.search = "\\s+$";
bespin.get("editor").ui.actions.replace(replaceArgs);
}
}
});
 
// ** {{{Command: bindkey}}} **
bespin.cmd.commands.add({
name: 'bindkey',
takes: ['modifiers', 'key', 'action'],
preview: 'Bind a key to an action, or show bindings',
completeText: 'With no arguments show bindings, else give modifier(s), key, and action name to set',
execute: function(instruction, args) {
if (args.key && args.action) { // bind a new key binding
if (args.modifiers == "none") args.modifiers = '';
 
bespin.publish("editor:bindkey", args);
} else { // show me the key bindings
var descriptions = bespin.get('editor').editorKeyListener.keyMapDescriptions;
var output = "<table>";
 
for (var keys in descriptions) {
var keyData = keys.split(','); // metaKey, ctrlKey, altKey, shiftKey
var keyCode = parseInt(keyData[0]);
 
var modifiers = [];
if (keyData[1] === "true") modifiers.push("CMD");
if (keyData[2] === "true") modifiers.push("CTRL");
if (keyData[3] === "true") modifiers.push("ALT");
if (keyData[4] === "true") modifiers.push("SHIFT");
 
var modifierInfo = modifiers.length > 0 ? modifiers.join(', ') + " " : "";
var keyInfo = modifierInfo + bespin.util.keys.KeyCodeToName[keyCode] || keyCode;
output += "<tr><td style='text-align:right;'>" + keyInfo + "</td><td>&#x2192;</td><td>" + descriptions[keys] + "</td></tr>";
}
output += "</table>";
instruction.addOutput(output);
}
}
});
 
// ** {{{Command: alias}}} **
bespin.cmd.commands.add({
name: 'alias',
takes: ['alias', 'command'],
preview: 'define and show aliases for commands',
completeText: 'optionally, add your alias name, and then the command name',
execute: function(instruction, args) {
var aliases = instruction.commandLine.commandStore.aliases;
 
if (!args.alias) {
// * show all
var output = "<table>";
for (var x in aliases) {
output += "<tr><td style='text-align:right;'>" + x + "</td><td>&#x2192;</td><td>" + aliases[x] + "</td></tr>";
}
output += "</table>";
instruction.addOutput(output);
} else {
// * show just one
if (args.command === undefined) {
var alias = aliases[args.alias];
if (alias) {
instruction.addOutput(args.alias + " &#x2192; " + aliases[args.alias]);
} else {
instruction.addErrorOutput("No alias set for '" + args.alias + "'");
}
} else {
// * save a new alias
var key = args.alias;
var value = args.command;
var aliascmd = value.split(' ')[0];
 
if (instruction.commandLine.commandStore.commands[key]) {
instruction.addErrorOutput("Sorry, there is already a command with the name: " + key);
} else if (instruction.commandLine.commandStore.commands[aliascmd]) {
aliases[key] = value;
instruction.addOutput("Saving alias: " + key + " &#x2192; " + value);
} else if (aliases[aliascmd]) {
// TODO: have the symlink to the alias not the end point
aliases[key] = value;
instruction.addOutput("Saving alias: " + key + " &#x2192; " + aliases[value] + " (" + value + " was an alias itself)");
} else {
instruction.addErrorOutput("Sorry, no command or alias with that name.");
}
}
}
}
});
 
// ** {{{Command: history}}} **
bespin.cmd.commands.add({
name: 'history',
preview: 'Show history of the commands',
execute: function(instruction) {
var instructions = instruction.commandLine.history.getInstructions();
var output = [];
output.push("<table>");
var count = 1;
dojo.forEach(instructions, function(instruction) {
output.push("<tr>");
output.push('<th>' + count + '</th>');
output.push('<td>' + instruction.typed + "</td>");
output.push("</tr>");
count++;
});
output.push("</table>");
 
instruction.addOutput(output.join(''));
}
});
 
bespin.cmd.commands.add({
name: 'uc',
preview: 'Change all selected text to uppercase',
withKey: "CMD SHIFT U",
execute: function(instruction) {
var args = { stringCase: 'u' };
bespin.get("editor").ui.actions.selectionChangeCase(args);
}
});
 
bespin.cmd.commands.add({
name: 'lc',
preview: 'Change all selected text to lowercase',
withKey: "CMD SHIFT L",
execute: function(instruction) {
var args = { stringCase: 'l' };
bespin.get("editor").ui.actions.selectionChangeCase(args);
}
});
 
// ** {{{Command: outline}}} **
bespin.cmd.commands.add({
name: 'outline',
preview: 'show outline of source code',
withKey: "ALT SHIFT O",
execute: function(instruction) {
bespin.publish("parser:showoutline");
}
});
 
//** {{{Command: rescan}}} **
bespin.cmd.commands.add({
name: 'rescan',
takes: ['project'],
preview: 'update the project catalog of files used by quick open',
execute: function(instruction, project) {
if (!project) {
bespin.withComponent('editSession', function(editSession) {
project = editSession.project;
});
}
bespin.get("server").rescan(project, instruction, {
onSuccess: instruction.link(function(response) {
instruction.addOutput(response);
instruction.unlink();
}),
onFailure: instruction.link(function(xhr) {
instruction.addErrorOutput(xhr.response);
instruction.unlink();
})
});
}
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.