Example #1
0
		editor.on("blur", function() {
			m.snippetText = editor.getValue();
			snippetManager.unregister(m.snippets);
			m.snippets = snippetManager
					.parseSnippetFile(m.snippetText, m.scope);
			snippetManager.register(m.snippets);
		});
Example #2
0
File: demo.js Project: Sts0mrg0/ace
 exec: function(editor, needle) {
     if (typeof needle == "object") {
         editor.cmdLine.setValue("snippet ", 1);
         editor.cmdLine.focus();
         return;
     }
     var s = snippetManager.getSnippetByName(needle, editor);
     if (s)
         snippetManager.insertSnippet(editor, s.content);
 },
Example #3
0
 config.loadModule(snippetFilePath, function(m) {
     if (m) {
         snippetManager.files[id] = m;
         if (m.snippetText)
             m.snippets = snippetManager.parseSnippetFile(m.snippetText);
         snippetManager.register(m.snippets, m.scope);
         if (m.includeScopes) {
             snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes;
             m.includeScopes.forEach(function(x) {
                 loadSnippetFile("ace/mode/" + x);
             });
         }
     }
 });
 Constr.prototype.importModule = function(name, namespace, location) {
     var prefix = name.indexOf(":") > -1 ? name.substring(0, name.indexOf(":")) : name;
     var row = 0;
     if (this.decl) {
         row = this.decl.pos.el;
     }
     for (var i = 0; i < this.prolog.children.length; i++) {
         if (this.prolog.children[i].name === "Import") {
             row = this.prolog.children[i].pos.sl - 1;
             break;
         }
     }
     row = row < 0 ? 0 : row;
     
     this.editor.editor.gotoLine(row + 1);
     this.editor.editor.navigateLineEnd();
     this.editor.editor.insert("\n\n");
     this.editor.editor.gotoLine(row + 3, 0);
     
     var template;
     if (namespace) {
         template = "import module namespace " + prefix + "=\"" + namespace + "\"";
         if (location) {
             template += " at \"" + location + "\";";
         } else {
             template += ";"
         }
     } else {
         template = "import module namespace " + prefix + "=\"${1}\";";
     }
     SnippetManager.insertSnippet(this.editor.editor, template);
     this.editor.editor.gotoLine(row + 3, 26 + prefix.length);
 };
Example #5
0
define("rstudio/snippets/markdown", ["require", "exports", "module"], function(require, exports, module) {

var utils = require("rstudio/snippets");
var SnippetManager = require("ace/snippets").snippetManager;

var snippets = [
   {
      name: "[",
      content: '[${1:label}](${2:location})'
   },
   {
      name: "![",
      content: '![${1:label}](${2:location})'
   },
   {
      name: "r",
      content: "```{r ${1:label}, ${2:options}}\n${0}\n```"
   },
   {
      name: "rcpp",
      content: "```{r, engine='Rcpp'}\n#include <Rcpp.h>\nusing namespace Rcpp;\n\n${0}\n\n```"
   }
];

utils.normalizeSnippets(snippets);
exports.snippetText = utils.toSnippetText(snippets);

SnippetManager.register(snippets, "markdown");

});
Example #6
0
define("rstudio/snippets/c_cpp", function(require, exports, module) {

var utils = require("rstudio/snippets");
var SnippetManager = require("ace/snippets").snippetManager;

var snippets = [
   {
      name: "once",
      content: [
         "#ifndef ${1:`HeaderGuardFileName`}",
         "#define ${1:`HeaderGuardFileName`}",
         "",
         "${0}",
         "",
         "#endif /* ${1:`HeaderGuardFileName`} */"
      ].join("\n")
   },
   {
      name: "ans",
      content: [
         "namespace {",
         "${0}",
         "} // anonymous namespace"
      ].join("\n")
   },
   {
      name: "ns",
      content: [
         "namespace ${1:ns} {",
         "${0}",
         "} // namespace ${1:ns}"
      ].join("\n")
   },
   {
      name: "cls",
      content: [
         "class ${1:ClassName} {",
         "public:",
         "    ${2}",
         "private:",
         "    ${3}",
         "};"
      ].join("\n")
   },
   {
      name: "str",
      content: [
         "struct ${1} {",
         "    ${0}",
         "};"
      ].join("\n")
   }
];

utils.normalizeSnippets(snippets);
exports.snippetText = utils.toSnippetText(snippets);

SnippetManager.register(snippets, "c_cpp");

});
 Constr.prototype.declareVariable = function(name) {
     $.log("prolog: %o", this.prolog);
     var row = -1;
     for (var i = 0; i < this.prolog.children.length; i++) {
         if (this.prolog.children[i].name === "AnnotatedDecl") {
             row = this.prolog.children[i].pos.sl - 1;
             break;
         }
     }
     if (row < 0) {
         if (this.prolog.children.length > 0) {
             row = this.prolog.children[this.prolog.children.length - 1].pos.el;
         } else if (this.decl) {
             row = this.decl.pos.el;
         } else {
             row = 0;
         }
     }
     
     $.log("Inserting at %d", row);
     
     this.editor.editor.gotoLine(row + 1);
     this.editor.editor.navigateLineEnd();
     this.editor.editor.insert("\n\n");
     this.editor.editor.gotoLine(row + 3, 0);
     
     var template = "declare variable \\$" + name + " := ${1:expression};";
     SnippetManager.insertSnippet(this.editor.editor, template);
 };
    Constr.prototype.extractVariable = function(doc) {
        this.xqlint(doc);
        // get text of selection
        var range = this.editor.getSelectionRange();
        var value = doc.getSession().getTextRange(range);   
        if (value.length == 0) {
            eXide.util.error("Please select code to extract.");
            return;
        }

        var anchor = new Anchor(doc.getSession().getDocument(), range.start.row, range.start.column);
        
        // disable validation while refactoring
        this.parent.validationEnabled = false;

        var template;
        var currentNode = eXide.edit.XQueryUtils.findNode(doc.ast, 
            {line: range.start.row, col: range.start.column + 1});
        var contextNode = eXide.edit.XQueryUtils.findAncestor(currentNode, ["IntermediateClause", "InitialClause", "ReturnClause"]);
        if (contextNode) {
            template = "let $${1} := " + value.replace("$", "\\$");
        } else {
            contextNode = eXide.edit.XQueryUtils.findAncestor(currentNode, "StatementsAndOptionalExpr");
            contextNode = eXide.edit.XQueryUtils.findChild(contextNode, "Expr");
            if (!contextNode) {
                eXide.util.error("Extract variable: unable to determine context. Giving up.")
                return;
            }
            template = "let $${1} := " + value.replace("$", "\\$") + "\nreturn";
            
        }
        $.log("extract variable: context: %o", contextNode);
        
        this.editor.insert("$");
        
        this.editor.gotoLine(contextNode.pos.sl + 1, contextNode.pos.sc);
        this.editor.insert("\n");
        this.editor.gotoLine(contextNode.pos.sl + 1, contextNode.pos.sc);
        SnippetManager.insertSnippet(this.editor, template);
        this.editor.focus();
        
        var sel = this.editor.getSelection();
        
        sel.toOrientedRange();
        var pos = anchor.getPosition();
        var callRange = new Range(pos.row, pos.column, pos.row, pos.column);
        callRange.cursor = pos;
        
        sel.addRange(callRange);
        
        anchor.detach();
        
        this.parent.validationEnabled = true;
    };
        replaceContent: function replaceContent(value, start, end, noIndent) {
            if (end == null) end = start == null ? this.getContent().length : start;
            if (start == null) start = 0;

            var editor = this.ace;
            var range = Range.fromPoints(editor.indexToPosition(start), editor.indexToPosition(end));
            editor.session.remove(range);

            range.end = range.start;

            value = this.$updateTabstops(value);
            snippetManager.insertSnippet(editor, value);
        },
 Constr.prototype.addFunction = function(name, params) {
     this.prepareFunction();
     var template = "declare function " + name + "(";
     if (params) {
         for (var i = 0; i < params.length; i++) {
             if (i > 0) {
                 template += ", ";
             }
             template += "$${" + (i + 1) + ":" + params[i] + "}";
         }
     }
     template += ") {\n\t${" + (arguments.length + 1) + ":()}\n};";
     SnippetManager.insertSnippet(this.editor.editor, template);
 };
     editor.session.remove(range);
     
     range.end = range.start;
     
     value = this.$updateTabstops(value);
     snippetManager.insertSnippet(editor, value)
 },
 getContent: function(){
     return this.ace.getValue();
 },
 getSyntax: function() {
     if (this.$syntax)
         return this.$syntax;
     var syntax = this.ace.session.$modeId.split("/").pop();
     if (syntax == "html" || syntax == "php") {
         var cursor = this.ace.getCursorPosition();
Example #12
0
exports.init = function(worker) {
    var loadSnippetsForMode = function(mode) {
        var id = mode.$id;
        if (!snippetManager.files)
            snippetManager.files = {};
        loadSnippetFile(id);
        if (mode.modes)
            mode.modes.forEach(loadSnippetsForMode);
    };

    function loadSnippetFile(id) {
        if (!id || snippetManager.files[id])
            return;
        var snippetFilePath = id.replace(/\/modes?\//, /snippets/);
        snippetManager.files[id] = {};
        config.loadModule(snippetFilePath, function(m) {
            if (m) {
                snippetManager.files[id] = m;
                if (m.snippetText)
                    m.snippets = snippetManager.parseSnippetFile(m.snippetText);
                snippetManager.register(m.snippets, m.scope);
                if (m.includeScopes) {
                    snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes;
                    m.includeScopes.forEach(function(x) {
                        loadSnippetFile("ace/mode/" + x);
                    });
                }
            }
        });
    }
    
    function sendSnippetsToWorker(e) {
        worker.emit("loadSnippets", { data: {
            language: e.scope,
            snippets: snippetManager.snippetNameMap[e.scope]
        }});
    }
    
    worker.on("changeMode", function(e) {
        loadSnippetsForMode(worker.$doc.$mode);
    });
    
    worker.on("terminate", function() {
        snippetManager.off("registerSnippets", sendSnippetsToWorker);
    });
    snippetManager.on("registerSnippets", sendSnippetsToWorker);
};
            insertComplete: function (editor) {
                editor.removeEventListener("change", self.refreshCompilation);
                var curr = self.view.current();

                for (var i = 0; i < self.inputText.length; i++) {
                    editor.remove("left");
                }

                if (curr) {
                    editor.insert($(curr).data("name"));

                    if ($(curr).data("kind") == "snippet") {
                        snippetManager.expandWithTab(editor);
                    }
                }
                self.deactivate();

            }
 Constr.prototype.declareNamespace = function(prefix) {
     var row = 0;
     if (this.decl) {
         row = this.decl.pos.el;
     }
     for (var i = 0; i < this.prolog.children.length; i++) {
         if (this.prolog.children[i].name === "NamespaceDecl") {
             row = this.prolog.children[i].pos.sl - 1;
             break;
         }
     }
     row = row < 0 ? 0 : row;
     
     this.editor.editor.gotoLine(row + 1);
     this.editor.editor.navigateLineEnd();
     this.editor.editor.insert("\n\n");
     this.editor.editor.gotoLine(row + 3, 0);
     
     var template = "declare namespace " + prefix + "=\"${1}\";";
     SnippetManager.insertSnippet(this.editor.editor, template);
 };
     function apply(selected) {
         if (complete) {
             var expansion = selected.label;
             if (selected.type == "function") {
 				expansion = eXide.util.parseSignature(expansion);
 			} else {
                 expansion = selected.template;   
 			}
             if (wordrange) {
                 $this.editor.getSession().remove(wordrange);
             }
             if (selected.type === "variable") {
                 $this.editor.insert(expansion);
             } else {
                 SnippetManager.insertSnippet($this.editor, expansion);
             }
             if (selected.completion) {
                 $this.autocomplete(doc);
             }
         }
         $.log("template applied");
     }
Example #16
0
 function addSnippet(data, plugin) {
     if (typeof data == "string") {
         data = { text: data };
         var text = data.text;
         var firstLine = text.split("\n", 1)[0].replace(/\#/g, "").trim();
         firstLine.split(";").forEach(function(n) {
             if (!n) return;
             var info = n.split(":");
             if (info.length != 2) return;
             data[info[0].trim()] = info[1].trim();
         });
     }
     if (data.include)
         data.include = data.include.split(",").map(function(n) {
             return n.trim();
         });
     if (!data.scope) throw new Error("Missing Snippet Scope");
     
     data.scope = data.scope.split(",");
     if (!data.snippets && data.text)
         data.snippets = snippetManager.parseSnippetFile(data.text);
     
     data.scope.forEach(function(scope) {
         snippetManager.register(data.snippets, scope);
     });
     
     // if (snippet.include) {
     //     snippetManager.snippetMap[snippet.scope].includeScopes = snippet.include;
     //     snippet.include.forEach(function(x) {
     //         // loadSnippetFile("ace/mode/" + x);
     //         // @nightwing help!
     //     });
     // }
     
     plugin.addOther(function() {
         snippetManager.unregister(data.snippets);
     });
 }
Example #17
0
    this.insertMatch = function(data) {
        if (!data)
            data = this.popup.getData(this.popup.getRow());
        if (!data)
            return false;

        if (data.completer && data.completer.insertMatch) {
            data.completer.insertMatch(this.editor);
        } else {
            if (this.completions.filterText) {
                var ranges = this.editor.selection.getAllRanges();
                for (var i = 0, range; range = ranges[i]; i++) {
                    range.start.column -= this.completions.filterText.length;
                    this.editor.session.remove(range);
                }
            }
            if (data.snippet)
                snippetManager.insertSnippet(this.editor, data.snippet);
            else
                this.editor.execCommand("insertstring", data.value || data);
        }
        this.detach();
    };
 resolve: function(helper, editor, doc, annotation) {
     var template;
     var contextNode = eXide.edit.XQueryUtils.findAncestor(ast, ["IntermediateClause", "InitialClause", "ReturnClause"]);
     if (contextNode) {
         template = "let \\$" + ast.value + " := ${1:()}";
     } else {
         contextNode = eXide.edit.XQueryUtils.findAncestor(ast, "StatementsAndOptionalExpr");
         contextNode = eXide.edit.XQueryUtils.findChild(contextNode, "Expr");
         if (!contextNode) {
             eXide.util.error("Extract variable: unable to determine context. Giving up.")
             return;
         }
         template = "let \\$" + ast.value + " := ${1:()}" + "\nreturn";
     }
     helper.parent.validator.setEnabled(false);
     $.log("extract variable: context: %o", contextNode);
     editor.editor.gotoLine(contextNode.pos.sl + 1, contextNode.pos.sc);
     editor.editor.insert("\n");
     editor.editor.gotoLine(contextNode.pos.sl + 1, contextNode.pos.sc);
     SnippetManager.insertSnippet(editor.editor, template);
     editor.editor.focus();
     helper.parent.validator.setEnabled(true);
 },
Example #19
0
ace.commands.bindKey("Tab", function(editor) {
    var success = snippetManager.expandWithTab(editor);
    if (!success)
        editor.execCommand("indent");
})
Example #20
0
function saveSnippets() {
    jsSnippets.snippets = snippetManager.parseSnippetFile(jsSnippets.snippetText);
    snippetManager.register(jsSnippets.snippets, "javascript")
}
Example #21
0
 worker.on("terminate", function() {
     snippetManager.off("registerSnippets", sendSnippetsToWorker);
 });
Example #22
0
 data.scope.forEach(function(scope) {
     snippetManager.register(data.snippets, scope);
 });
Example #23
0
define("rstudio/snippets/r", ["require", "exports", "module"], function(require, exports, module) {

var utils = require("rstudio/snippets");
var SnippetManager = require("ace/snippets").snippetManager;

var snippets = [

   /* Import */
   {
      name: "lib",
      content: "library(${1:package})"
   },
   {
      name: "req",
      content: 'require(${1:package})'
   },
   {
      name: "src",
      content: 'source("${1:file.R}")'
   },
   {
      name: "ret",
      content: 'return(${1:code})'
   },
   {
      name: "mat",
      content: 'matrix(${1:data}, nrow = ${2:rows}, ncol = ${3:cols})'
   },

   /* S4 snippets */
   {
      name: "sg",
      content: [
         'setGeneric("${1:generic}", function(${2:x, ...}) {',
         '    standardGeneric("${1:generic}")',
         '})'
      ].join("\n")
   },
   {
      name: "sm",
      content: [
         'setMethod("${1:generic}", ${2:class}, function(${2:x, ...}) {',
         '    ${0}',
         '})'
      ].join("\n")
   },
   {
      name: "sc",
      content: [
         'setClass("${1:Class}", slots = c(${2:name = "type"}))'
      ].join("\n")
   },

   /* Control Flow and Keywords */
   {
      name: "if",
      content: [
         'if (${1:condition}) {',
         '    ${0}',
         '}'
      ].join("\n")
   },
   {
      name: "el",
      content: [
         'else {',
         '    ${0}',
         '}'
      ].join("\n")
   },
   {
      name: "ei",
      content: [
         'else if (${1:condition}) {',
         '    ${0}',
         '}'
      ].join("\n")
   },
   {
      name: "fun",
      content: [
         "${1:name} <- function(${2:variables}) {",
         "    ${0}",
         "}"
      ].join("\n")
   },
   {
      name: "for",
      content: [
         'for (${1:variable} in ${2:vector}) {',
         '    ${0}',
         '}'
      ].join("\n")
   },
   {
      name: "while",
      content: [
         'while (${1:condition}) {',
         '    ${0}',
         '}'
      ].join("\n")
   },
   {
      name: "switch",
      content: [
         'switch (${1:object},',
         '    ${2:case} = ${3:action}',
         ')'
      ].join("\n")
   },

   /* Apply */
   {
      name: "apply",
      content: 'apply(${1:array}, ${2:margin}, ${3:...})'
   },
   {
      name: "lapply",
      content: "lapply(${1:list}, ${2:function})"
   },
   {
      name: "sapply",
      content: "sapply(${1:list}, ${2:function})"
   },
   {
      name: "mapply",
      content: "mapply(${1:function}, ${2:...})"
   },
   {
      name: "tapply",
      content: "tapply(${1:vector}, ${2:index}, ${3:function})"
   },
   {
      name: "vapply",
      content: 'vapply(${1:list}, ${2:function}, FUN.VALUE = ${3:type}, ${4:...})'
   },
   {
      name: "rapply",
      content: "rapply(${1:list}, ${2:function})"
   },

   /* Utilities */
   {
      name: "ts",
      content: '`r paste("#", date(), "------------------------------\\n")`'
   },

   /* Shiny */
   {
      name: "shinyapp",
      content: [
         'library(shiny)',
         '',
         'ui <- fluidPage(',
         '  ${0}',
         ')',
         '',
         'server <- function(input, output, session) {',
         '  ',
         '}',
         '',
         'shinyApp(ui, server)'
      ].join("\n")
   },
   {
      name: "shinymod",
      content: [
         '${1:name}_UI <- function(id) {',
         '  ns <- NS(id)',
         '  tagList(',
         '    ${0}',
         '  )',
         '}',
         '',
         '${1:name} <- function(input, output, session) {',
         '  ',
         '}'
      ].join("\n")
   }
];

utils.normalizeSnippets(snippets);
exports.snippetText = utils.toSnippetText(snippets);

SnippetManager.register(snippets, "r");

});
Example #24
0
 plugin.addOther(function() {
     snippetManager.unregister(data.snippets);
 });
 function apply(selected) {
     if (range) {
         self.editor.getSession().remove(range);
     }
     SnippetManager.insertSnippet(self.editor, selected.template);
 }
Example #26
0
        /**
         * Replaces the preceeding identifier (`prefix`) with `newText`, where ^^
         * indicate the cursor positions after the replacement.
         * If the prefix is already followed by an identifier substring, that string
         * is deleted.
         */
        function replaceText(ace, match, deleteSuffix) {
            if (!ace.inVirtualSelectionMode && ace.inMultiSelectMode) {
                ace.forEachSelection(function() {
                    replaceText(ace, match, deleteSuffix);
                }, null, { keepOrder: true });
                if (ace.tabstopManager)
                    ace.tabstopManager.tabNext();
                return;
            }

            var newText = match.replaceText;
            var pos = ace.getCursorPosition();
            var session = ace.getSession();
            var line = session.getLine(pos.row);
            var doc = session.getDocument();
            var idRegex = match.identifierRegex || getIdentifierRegex(null, ace);
            var prefix = completeUtil.retrievePrecedingIdentifier(line, pos.column, idRegex);
            var postfix = completeUtil.retrieveFollowingIdentifier(line, pos.column, idRegex) || "";
            
            var snippet = match.snippet;
            if (!snippet) {
                if (match.replaceText === "require(^^)" && isJavaScript(ace)) {
                    newText = "require(\"^^\")";
                    if (!isInvokeScheduled)
                        setTimeout(deferredInvoke.bind(null, false, ace), 0);
                }
                
                // Don't insert extra () in front of (
                var endingParens = newText.substr(newText.length - 4) === "(^^)"
                    ? 4
                    : newText.substr(newText.length - 2) === "()" ? 2 : 0;
                if (endingParens) {
                    if (line.substr(pos.column + (deleteSuffix ? postfix.length : 0), 1) === "(")
                        newText = newText.substr(0, newText.length - endingParens);
                    if (postfix && line.substr(pos.column, postfix.length + 1) === postfix + "(") {
                        newText = newText.substr(0, newText.length - endingParens);
                        deleteSuffix = true;
                    }
                }

                // Ensure cursor marker
                if (newText.indexOf("^^") === -1)
                    newText += "^^";
                    
                // Remove HTML duplicate '<' completions
                var preId = completeUtil.retrievePrecedingIdentifier(line, pos.column, idRegex);
                if (isHtml(ace) && line[pos.column - preId.length - 1] === '<' && newText[0] === '<')
                    newText = newText.substring(1);
                
                snippet = newText.replace(/[$]/g, "\\$").replace(/\^\^(.*)\^\^|\^\^/g, "${0:$1}");
                // Remove cursor marker
                newText = newText.replace(/\^\^/g, "");
            }
            
            tooltip.setLastCompletion(match, pos);

            if (deleteSuffix || newText.slice(-postfix.length) === postfix || match.deleteSuffix)
                doc.removeInLine(pos.row, pos.column - prefix.length, pos.column + postfix.length);
            else
                doc.removeInLine(pos.row, pos.column - prefix.length, pos.column);
            
            snippetManager.insertSnippet(ace, snippet);
            
            language.onCursorChange(null, null, true);
            emit("replaceText", {
                pos: pos,
                prefix: prefix,
                newText: newText,
                match: match
            });
            
            if (matchCompletionRegex(getCompletionRegex(), doc.getLine(pos.row), ace.getCursorPosition()))
                deferredInvoke(true);
        }