Declare requires, converters, global variables, list of needed behind functions, ...

@param  {object} code - Helper for Javascript code writing.

@return {string} Resulting JS code.
514632
function outputNeededConstants( code ) {
    try {
        let out = arrayToCodeWithNewLine( code.generateRequires(), "    " );
        out += arrayToCodeWithNewLine( code.generateNeededBehindFunctions(), "    " );
        out += arrayToCodeWithNewLine( code.generateFunctions(), "    " );
        out += arrayToCodeWithNewLine( code.generateGlobalVariables(), "    " );
        return out;
    } catch ( ex ) {
        bubble( ex, "outputNeededConstants" );
        return null;
    }
}
1293439
function( code ) {
		var script,
				indirect = eval;

		code = jQuery.trim( code );

		if ( code ) {
			// If the code includes a valid, prologue position
			// strict mode pragma, execute code by injecting a
			// script tag into the document.
			if ( code.indexOf("use strict") === 1 ) {
				script = document.createElement("script");
				script.text = code;
				document.head.appendChild( script ).parentNode.removeChild( script );
			} else {
			// Otherwise, avoid the DOM node creation, insertion
			// and removal by using an indirect global eval
				indirect( code );
			}
		}
	}
1038745
function(code)
        {
            if (code === null)
                code = '';

            this.code = code;

            var div = this.create('div');

            // create main HTML
            div.innerHTML = this.getHtml(code);

            // set up click handlers
            if (this.getParam('toolbar'))
                attachEvent(findElement(div, '.toolbar'), 'click', sh.toolbar.handler);

            if (this.getParam('quick-code'))
                attachEvent(findElement(div, '.code'), 'dblclick', quickCodeHandler);

            return div;
        }
1232
function(code)
        {
            var lines = [],
                firstLine = parseInt(this.getParam('first-line'))
                ;

            eachLine(code, function(line, index)
            {
                lines.push(index + firstLine);
            });

            return lines;
        }
1182454
function(code)
        {
            var html = '',
                classes = [ 'syntaxhighlighter' ],
                tabSize,
                matches,
                lineNumbers
                ;

            // process light mode
            if (this.getParam('light') == true)
                this.params.toolbar = this.params.gutter = false;

            className = 'syntaxhighlighter';

            if (this.getParam('collapse') == true)
                classes.push('collapsed');

            if ((gutter = this.getParam('gutter')) == false)
                classes.push('nogutter');

            // add custom user style name
            classes.push(this.getParam('class-name'));

            // add brush alias to the class name for custom CSS
            classes.push(this.getParam('brush'));

            code = trimFirstAndLastLines(code)
                .replace(/\r/g, ' ') // IE lets these buggers through
            ;

            tabSize = this.getParam('tab-size');

            // replace tabs with spaces
            code = this.getParam('smart-tabs') == true
                ? processSmartTabs(code, tabSize)
                : processTabs(code, tabSize)
            ;

            // unindent code by the common indentation
            if (this.getParam('unindent'))
                code = unindent(code);

            if (gutter)
                lineNumbers = this.figureOutLineNumbers(code);

            // find matches in the code using brushes regex list
            matches = this.findMatches(this.regexList, code);
            // processes found matches into the html
            html = this.getMatchesHtml(code, matches);
            // finally, split all lines so that they wrap well
            html = this.getCodeLinesHtml(html, lineNumbers);

            // finally, process the links
            if (this.getParam('auto-links'))
                html = processUrls(html);

            if (typeof(navigator) != 'undefined' && navigator.userAgent && navigator.userAgent.match(/MSIE/))
                classes.push('ie');

            html =
                '<div id="' + getHighlighterId(this.id) + '" class="' + classes.join(' ') + '">'
                    + (this.getParam('toolbar') ? sh.toolbar.getHtml(this) : '')
                    + '<table border="0" cellpadding="0" cellspacing="0">'
                    + this.getTitleHtml(this.getParam('title'))
                    + '<tbody>'
                    + '<tr>'
                    + (gutter ? '<td class="gutter">' + this.getLineNumbersHtml(code) + '</td>' : '')
                    + '<td class="code">'
                    + '<div class="container">'
                    + html
                    + '</div>'
                    + '</td>'
                    + '</tr>'
                    + '</tbody>'
                    + '</table>'
                    + '</div>'
            ;

            return html;
        }
721902
function parse (code) {
  Object.keys(syntax).forEach((s) => {
    code = code.replace(syntax[s], (_, m) => {
      // ensure if the regex only matches part of the string that we keep the leftover
      let leftOver = _.replace(m, '')
      // encode the string and class
      let parsed = `{#${s}#${encode(m)}#}`

      if (s === 'function' && leftOver) {
        // we want to parse sub commands and the easiest way to do that is to
        // run over the leftOver portion of the function call with the same regex
        let startingParenthesis = leftOver.indexOf('(')
        let endingParenthesis = leftOver.lastIndexOf(')')
        let endingComma = leftOver.lastIndexOf(';')

        // since we don't want to create a new string for every operation
        // we can simply walk the string and replace the character that needs it
        let subFunction = leftOver.replace(/./g, (c, i) => {
          // we can define a waterfall case that only replaces the three positions with nothing
          // leaving the other characters in their place
          switch (i) {
            case startingParenthesis:
            case endingParenthesis:
            case endingComma:
              return ''
            default:
              return c
          }
        })
        leftOver = `(${parse(subFunction)})${endingComma > -1 ? ';' : ''}`
      }
      return parsed + leftOver
    })
  })
  return code
}
452194
function getCommentedFunctionNode(node) {
    if (!node.leadingComments) {
        // JSDoc comments are always before the function, so if there is
        // nothing here, we ain't interested.
        return null;
    }
    // console.log("=================");
    // console.log("type: " + node.type);
    // console.log(util.inspect(node));
    /*
     * We handle the following function representations:
     *
     *     Type               Path to Function              Example
     * ==========================================================================================
     * FunctionDeclaration           -                  function foo(bar) {}
     * VariableDeclaration   .declarations[0].init      var foo = function(bar) {}
     * ExpressionStatement   .expression.right          ObjClass.prototype.foo = function(bar) {}
     * MethodDefinition      .value                     class ObjClass { foo(bar) {} }
     * Property              .value                     var obj = { key: function(bar) {} }
     * ReturnStatement       .argument                  return function(foo, bar) {}
     * ArrowFunctionExpression       -                  (foo, bar) => {}
     * ExportNamedDeclaration .declaration              export function foo(bar) {}
     *
     */
    var nodeTypes = [
        "FunctionDeclaration", "ExpressionStatement", "VariableDeclaration",
        "MethodDefinition", "Property", "ReturnStatement", "ArrowFunctionExpression",
        "ExportNamedDeclaration"
    ];
    if (nodeTypes.indexOf(node.type) === -1) {
        return null;
    }
    var funcNode = null;
    switch (node.type) {
        case "FunctionDeclaration":
        case "ArrowFunctionExpression":
            funcNode = node;
            break;
        case "VariableDeclaration":
            funcNode = node.declarations[0].init;
            break;
        case "ExpressionStatement":
            funcNode = node.expression.right;
            break;
        case "MethodDefinition":
            funcNode = node.value;
            break;
        case "Property":
            funcNode = node.value;
            break;
        case "ReturnStatement":
            funcNode = node.argument;
            break;
        case "ExportNamedDeclaration":
            var declaration = node.declaration;
            if (declaration.type === 'VariableDeclaration') {
                funcNode = declaration.declarations[0].init;
            } else {
                funcNode = declaration
            }
            break;
    }
    var funcNodeTypes = ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"];
    if (!funcNode || funcNodeTypes.indexOf(funcNode.type) === -1) {
        // We can't find a function here which can map to leadingComments.
        return null;
    }
    var funcDocs = null;
    for (var i=0; i<node.leadingComments.length; i++) {
        // Block comments are either JSDoc or flow-jsdoc specific in-inline syntax
        if (node.leadingComments[i].type === "Block") {
            funcDocs = extractJsdoc(node.leadingComments[i].value);
            if (funcDocs) { break; }
            // may be inline form with /* */
            funcDocs = extractInlineAnnotations(funcNode, node.leadingComments[i].value);
            if (funcDocs) {
                node.leadingComments[i].update("");
                break;
            }
        }
        else if (node.leadingComments[i].type === "Line") {
            // Line comments can only be flow-jsdoc specific in-line syntax.
            funcDocs = extractInlineAnnotations(funcNode, node.leadingComments[i].value);
            if (funcDocs) {
                node.leadingComments[i].update("");
                break;
            }
        }
    }

    return {
        node: funcNode,
        jsdoc: funcDocs
    };
}
1297909
function getCodeExtensions() {
    const configFilepath = path.join(constants.GLOBAL_DIR, constants.GLOBAL_CONFIG);
    const extensions = [];

    // Parse config file
    const config = fs.readJsonSync(configFilepath, 'utf8');
    if (config.extension) {
        extensions.push(config.extension);
    }

    // Default
    if (extensions.length === 0) {
        extensions.push('.js');
    }

    return extensions;
}
898675
function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
            if (declaration.flags & 134217728 /* JavaScriptFile */) {
                // If this is a variable in a JavaScript file, then use the JSDoc type (if it has
                // one as its type), otherwise fallback to the below standard TS codepaths to
                // try to figure it out.
                var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration);
                if (type && type !== unknownType) {
                    return type;
                }
            }
            // A variable declared in a for..in statement is always of type string
            if (declaration.parent.parent.kind === 207 /* ForInStatement */) {
                return stringType;
            }
            if (declaration.parent.parent.kind === 208 /* ForOfStatement */) {
                // checkRightHandSideOfForOf will return undefined if the for-of expression type was
                // missing properties/signatures required to get its iteratedType (like
                // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
                // or it may have led to an error inside getElementTypeOfIterable.
                return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType;
            }
            if (ts.isBindingPattern(declaration.parent)) {
                return getTypeForBindingElement(declaration);
            }
            // Use type from type annotation if one is present
            if (declaration.type) {
                return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality);
            }
            if (declaration.kind === 142 /* Parameter */) {
                var func = declaration.parent;
                // For a parameter of a set accessor, use the type of the get accessor if one is present
                if (func.kind === 150 /* SetAccessor */ && !ts.hasDynamicName(func)) {
                    var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 149 /* GetAccessor */);
                    if (getter) {
                        var getterSignature = getSignatureFromDeclaration(getter);
                        var thisParameter = getAccessorThisParameter(func);
                        if (thisParameter && declaration === thisParameter) {
                            // Use the type from the *getter*
                            ts.Debug.assert(!thisParameter.type);
                            return getTypeOfSymbol(getterSignature.thisParameter);
                        }
                        return getReturnTypeOfSignature(getterSignature);
                    }
                }
                // Use contextual parameter type if one is available
                var type = void 0;
                if (declaration.symbol.name === "this") {
                    var thisParameter = getContextualThisParameter(func);
                    type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined;
                }
                else {
                    type = getContextuallyTypedParameterType(declaration);
                }
                if (type) {
                    return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality);
                }
            }
            // Use the type of the initializer expression if one is present
            if (declaration.initializer) {
                return addOptionality(checkExpressionCached(declaration.initializer), /*optional*/ declaration.questionToken && includeOptionality);
            }
            // If it is a short-hand property assignment, use the type of the identifier
            if (declaration.kind === 254 /* ShorthandPropertyAssignment */) {
                return checkIdentifier(declaration.name);
            }
            // If the declaration specifies a binding pattern, use the type implied by the binding pattern
            if (ts.isBindingPattern(declaration.name)) {
                return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
            }
            // No type specified and nothing can be inferred
            return undefined;
        }
736148
function(fn) {
  var code = fn.toString();
  var match = code.match(/^(?:(?:function)?[\s]*\(([^)]*)\)|([^\=\(]+))/);
  var args = (match[1] || match[2]);
  if (typeof args === 'undefined') {
    return [];
  }
  return args.split(',').map(function(item) {
    return item.trim();
  }).filter(function(item) {
    return item;
  });
}
881187
function generateCodeDocs() {
  config.codeFiles.forEach(function (jsFile) {
    var jf = [jsFile];
    documentation(jf, {}, function (err, result) {
      documentation.formats.md(result, {}, function (err, md) {
        // Write to file
        fs.writeFile(path.resolve(__dirname, config.docFolder + "/" + jsFile + ".md"), md);
      });
    });
  });
}
403090
function render(code, data) {
  var js = '```js' + code + '```'
  return `<div class="vomit-snippet"><div class="column">${marked(js)}</div><div class="column"><script>
(function() {${code}document.currentScript.parentElement.appendChild(component(${JSON.stringify(data.data)}))
})()</script></div></div>`
}
1053852
function outputClassBody( code ) {
    try {
        let out = '';
        if ( code.that ) out += "        const that = this;\n";
        if ( code.pm ) out += "        const pm = PM(this);\n";
        out += generate( code.section.attribs.define, "Create attributes", "        " );
        out += generate( code.section.elements.define, "Create elements", "        " );
        out += generate( code.section.events, "Events", "        " );
        out += arrayToCodeWithNewLine( code.generateLinks(), "        " );
        out += generate( code.section.ons, "On attribute changed", "        " );
        out += generate( code.section.elements.init, "Initialize elements", "        " );
        out += generate( code.section.attribs.init, "Initialize attributes", "        " );
        if ( code.section.init ) {
            out += "        // Initialization.\n";
            out += `        CODE_BEHIND.${code.section.init}.call( this );\n`;
        }
        out += "        $.addClass(this, 'view', 'custom');\n";
        return out;
    } catch ( ex ) {
        bubble( ex, "outputClassBody" );
        return null;
    }
}
187631
function makeKeyDefinition ( code ) {
	return ( node, fire ) => {
		function keydownHandler ( event ) {
			var which = event.which || event.keyCode;

			if ( which === code ) {
				event.preventDefault();

				fire({
					node,
					original: event
				});
			}
		}

		node.addEventListener( 'keydown', keydownHandler, false );

		return {
			teardown () {
				node.removeEventListener( 'keydown', keydownHandler, false );
			}
		};
	};
}
906833
function tryToCoverWindow(code) {

        if (typeof window === "object") {

            var variables = Object.getOwnPropertyNames(window);

            if (!window.hasOwnProperty('window')) {

                variables.push('window');

            }

            var stubDeclarations = '';
            variables.forEach(function(name) {

                // If the name really can be the name of variable.
                if (lodash.isString(name)) {

                    var stub = 'var ' + name + '; \n';

                    stubDeclarations = stubDeclarations + stub;

                }

            });

            code = stubDeclarations + code;

        }

        return code;

    }
585556
function init() {
        _isInitialized = true;

        foldCode.init();
        foldGutter.init();

        // Many CodeMirror modes specify which fold helper should be used for that language. For a few that
        // don't, we register helpers explicitly here. We also register a global helper for generic indent-based
        // folding, which cuts across all languages if enabled via preference.
        CodeMirror.registerGlobalHelper("fold", "selectionFold", function (mode, cm) {
            return prefs.getSetting("makeSelectionsFoldable");
        }, selectionFold);
        CodeMirror.registerGlobalHelper("fold", "indent", function (mode, cm) {
            return prefs.getSetting("alwaysUseIndentFold");
        }, indentFold);

        CodeMirror.registerHelper("fold", "handlebars", handlebarsFold);
        CodeMirror.registerHelper("fold", "htmlhandlebars", handlebarsFold);
        CodeMirror.registerHelper("fold", "htmlmixed", handlebarsFold);

        EditorManager.on("activeEditorChange.CodeFolding", onActiveEditorChanged);
        DocumentManager.on("documentRefreshed.CodeFolding", function (event, doc) {
            restoreLineFolds(doc._masterEditor);
        });

        ProjectManager.on("beforeProjectClose.CodeFolding beforeAppClose.CodeFolding", saveBeforeClose);

        //create menus
        codeFoldingMenuDivider = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuDivider();
        Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(COLLAPSE_ALL);
        Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(EXPAND_ALL);
        Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(COLLAPSE);
        Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(EXPAND);

        //register keybindings
        KeyBindingManager.addBinding(COLLAPSE_ALL, [ {key: collapseAllKey}, {key: collapseAllKeyMac, platform: "mac"} ]);
        KeyBindingManager.addBinding(EXPAND_ALL, [ {key: expandAllKey}, {key: expandAllKeyMac, platform: "mac"} ]);
        KeyBindingManager.addBinding(COLLAPSE, collapseKey);
        KeyBindingManager.addBinding(EXPAND, expandKey);


        // Add gutters & restore saved expand/collapse state in all currently open editors
        Editor.registerGutter(GUTTER_NAME, CODE_FOLDING_GUTTER_PRIORITY);
        Editor.forEveryEditor(function (editor) {
            enableFoldingInEditor(editor);
        });
    }
1249800
function codeHandle(e) {
            const $selectionElem = editor.selection.getSelectionContainerElem()
            if (!$selectionElem) {
                return
            }
            const $parentElem = $selectionElem.parent()
            const selectionNodeName = $selectionElem.getNodeName()
            const parentNodeName = $parentElem.getNodeName()

            if (selectionNodeName !== 'CODE' || parentNodeName !== 'PRE') {
                // 不符合要求 忽略
                return
            }

            if (!editor.cmd.queryCommandSupported('insertHTML')) {
                // 必须原生支持 insertHTML 命令
                return
            }

            // 处理：光标定位到代码末尾，联系点击两次回车，即跳出代码块
            if (editor._willBreakCode === true) {
                // 此时可以跳出代码块
                // 插入 <p> ，并将选取定位到 <p>
                const $p = $('<p><br></p>')
                $p.insertAfter($parentElem)
                editor.selection.createRangeByElem($p, true)
                editor.selection.restoreSelection()

                // 修改状态
                editor._willBreakCode = false

                e.preventDefault()
                return
            }

            const _startOffset = editor.selection.getRange().startOffset

            // 处理：回车时，不能插入 <br> 而是插入 \n ，因为是在 pre 标签里面
            editor.cmd.do('insertHTML', '\n')
            editor.selection.saveRange()
            if (editor.selection.getRange().startOffset === _startOffset) {
                // 没起作用，再来一遍
                editor.cmd.do('insertHTML', '\n')
            }

            const codeLength = $selectionElem.html().length
            if (editor.selection.getRange().startOffset + 1 === codeLength) {
                // 说明光标在代码最后的位置，执行了回车操作
                // 记录下来，以便下次回车时候跳出 code
                editor._willBreakCode = true
            }

            // 阻止默认行为
            e.preventDefault()
        }