Parses the inner shortcode to extract shortcode name & key-value attributes.
@param {string} innerShortcode - Extracted shortcode from between the start & end blocks.
426908
function parseShortcode(innerShortcode) {
  var trimmedInnerShortcode = innerShortcode.trim();

  // If no shortcode, it was blank between the blocks - return nothing.
  if (!trimmedInnerShortcode) return;

  // If no whitespace, then shortcode is just name with no attributes.
  if (!hasWhiteSpace(trimmedInnerShortcode)) {
    return { identifier: trimmedInnerShortcode, attributes: {} };
  }

  var splitShortcode = trimmedInnerShortcode.match(/^(\S+)\s(.*)/).slice(1);
  var shortcodeName = splitShortcode[0];
  var attributeString = splitShortcode[1];
  var attributes = parseShortcodeAttributes(attributeString);

  // If no attributes parsed, something went wrong - return nothing.
  if (!attributes) return;

  return {
    identifier: shortcodeName,
    attributes: attributes
  };
}
1056953
function parseHeaders(headerString) {
	var headers = {};
	var headersArray = headerString.split(/[\r\n]+/);
	headersArray.forEach(function (headerString) {
		var headerChunks = headerString.split(':');
		headers[headerChunks.shift().trim()] = headerChunks.join(':').trim();
	});
	return headers;
}
352421
function tagOutput(descriptor, innerDescriptor, name) {
	var out = '<' + name + innerDescriptor.attributes;
	if (innerDescriptor.style)
		out += ' style="' + innerDescriptor.style + '"';
	if (innerDescriptor.classes)
		out += ' class="' + innerDescriptor.classes + '"';
	if (innerDescriptor.children)
		descriptor.children += out + '>' + innerDescriptor.children + '</' + name + '>';
	else if (openTags.test(name))
		descriptor.children += out + '>';
	else if (strictTags.test(name))
		descriptor.children += out + '></' + name + '>';
	else
		descriptor.children += out + '/>';
}
1141254
function parseBlockKatex(state, startLine, endLine) {
        var marker, len, params, nextLine, mem,
            haveEndMarker = false,
            pos = state.bMarks[startLine] + state.tShift[startLine],
            max = state.eMarks[startLine];
        var dollar = 0x24;

        if (pos + 1 > max) { return false; }

        marker = state.src.charCodeAt(pos);
        if (marker !== dollar) { return false; }

        // scan marker length
        mem = pos;
        pos = state.skipChars(pos, marker);
        len = pos - mem;

        if (len != 2)  { return false; }

        // search end of block
        nextLine = startLine;

        for (;;) {
            ++nextLine;
            if (nextLine >= endLine) {

                // unclosed block should be autoclosed by end of document.
                // also block seems to be autoclosed by end of parent
                break;
            }

            pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];
            max = state.eMarks[nextLine];

            if (pos < max && state.tShift[nextLine] < state.blkIndent) {

                // non-empty line with negative indent should stop the list:
                // - ```
                //  test
                break;
            }

            if (state.src.charCodeAt(pos) !== dollar) { continue };

            if (state.tShift[nextLine] - state.blkIndent >= 4) {

                // closing fence should be indented less than 4 spaces
                continue;
            }

            pos = state.skipChars(pos, marker);

            // closing code fence must be at least as long as the opening one
            if (pos - mem < len) { continue; }

            // make sure tail has spaces only
            pos = state.skipSpaces(pos);

            if (pos < max) { continue; }

            haveEndMarker = true;

            // found!
            break;
        }

        // If a fence has heading spaces, they should be removed from its inner block
        len = state.tShift[startLine];

        state.line = nextLine + (haveEndMarker ? 1 : 0);
        
        var content = state.getLines(startLine + 1, nextLine, len, true)
                           .replace(/[ \n]+/g, ' ')
                           .trim();

        state.tokens.push({
            type: 'katex',
            params: params,
            content: content,
            lines: [startLine, state.line],
            level: state.level,
            block: true
        });

        return true;
    }
794154
protected boolean parse(HttpCode<TRANS, ?> code, String cntnt) {
		byte bytes[] = cntnt.getBytes();
		
		int cis,cie=-1,cend;
		int sis,sie,send;
		String name;
		ArrayList<String> props = new ArrayList<String>();
		do {
			// Clear these in case more than one Semi
			props.clear(); // on loop, do not want mixed properties
			name=null;
			
			cis = cie+1; // find comma start
			while(cis<bytes.length && Character.isSpaceChar(bytes[cis]))++cis;
			cie = cntnt.indexOf(',',cis); // find comma end
			cend = cie<0?bytes.length:cie; // If no comma, set comma end to full length, else cie
			while(cend>cis && Character.isSpaceChar(bytes[cend-1]))--cend;
			// Start SEMIS
			sie=cis-1; 
			do {
				sis = sie+1;  // semi start is one after previous end
				while(sis<bytes.length && Character.isSpaceChar(bytes[sis]))++sis;	
				sie = cntnt.indexOf(';',sis);
				send = sie>cend || sie<0?cend:sie;  // if the Semicolon is after the comma, or non-existent, use comma end, else keep
				while(send>sis && Character.isSpaceChar(bytes[send-1]))--send;
				if(name==null) { // first entry in Comma set is the name, not a property
					name = new String(bytes,sis,send-sis);
				} else { // We've looped past the first Semi, now process as properties
					// If there are additional elements (more entities within Semi Colons)
					// apply Properties
					int eq = cntnt.indexOf('=',sis);
					if(eq>sis && eq<send) {
						props.add(new String(bytes,sis,eq-sis));
						props.add(new String(bytes,eq+1,send-(eq+1)));
					}
				}
				// End Property
			} while(sie<=cend && sie>=cis); // End SEMI processing
			// Now evaluate Comma set and return if true
			if(eval(code,name,props))return true; // else loop again to check next comma
		} while(cie>=0); // loop to next comma
		return false; // didn't get even one match
	}
1211913
function parseComponentBlockParams(element, program) {
      var l = element.attributes.length;
      var attrNames = [];

      for (var i = 0; i < l; i++) {
        attrNames.push(element.attributes[i].name);
      }

      var asIndex = attrNames.indexOf('as');

      if (asIndex !== -1 && l > asIndex && attrNames[asIndex + 1].charAt(0) === '|') {
        // Some basic validation, since we're doing the parsing ourselves
        var paramsString = attrNames.slice(asIndex).join(' ');
        if (paramsString.charAt(paramsString.length - 1) !== '|' || paramsString.match(/\|/g).length !== 2) {
          throw new Error('Invalid block parameters syntax: \'' + paramsString + '\'');
        }

        var params = [];
        for (i = asIndex + 1; i < l; i++) {
          var param = attrNames[i].replace(/\|/g, '');
          if (param !== '') {
            if (ID_INVERSE_PATTERN.test(param)) {
              throw new Error('Invalid identifier for block parameters: \'' + param + '\' in \'' + paramsString + '\'');
            }
            params.push(param);
          }
        }

        if (params.length === 0) {
          throw new Error('Cannot use zero block parameters: \'' + paramsString + '\'');
        }

        element.attributes = element.attributes.slice(0, asIndex);
        program.blockParams = params;
      }
    }
1311516
function (charCode, keyCode) {
            var moduleCtrl = this._subTplModuleCtrl;
            if (moduleCtrl) {
                var value = this._subTplData.settings.value;
                if ((keyCode == 13 || keyCode == 32) && value) {
                    // SPACE or ENTER -> call dateSelect
                    this.dateSelect(value);
                    return true;
                } else {
                    return moduleCtrl.keyevent({
                        charCode : charCode,
                        keyCode : keyCode
                    });
                }
            } else {
                return false;
            }
        }
534419
function getCode(err, code) {
      if (err) {
        if (onDone) onDone(err)
        else console.error('>>>' + err);
        return;
      }

      if (htmlTemplate) {
        this.cat(fs.readFileSync(htmlTemplate));

        let mdCode = ''
        if (context) {
          mdCode = linkify(code, context);
        } else {
          mdCode = code;
        }
        this.replace(mdCode);
      } else {
        if (stylesheet || title) {
          if (titleText == null) titleText = fileName;
          this.cat('<!DOCTYPE html>\n' +
                   '<html>\n' +
                   '<head>\n' +
                   '  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>' + 
                   '  <title>' + titleText + '</title>\n');
          if (stylesheet) {
            this.cat('  <link rel="stylesheet" href="' + stylesheet + '">\n');
          }
          this.cat('</head>\n<body>\n' );
        }

        if (context) {
          this.cat( linkify(code, context) );
        } else {
          this.cat( code );
        }

        if (stylesheet || title) {
          this.cat( '</body>\n</html>\n' );
        }  
      }
      
      if (this.debug) console.error('>>>finished getting code');
      this.done = true;
      if (onDone) onDone();
    }
1164986
function parse_attribs(line) {
    var attributes = {},
        l = line.length,
        i, c,
        count = 1,
        quote = false,
        skip = false,
        open, close, joiner, seperator,
        pair = {
          start: 1,
          middle: null,
          end: null
        };

    if (!(l > 0 && (line.charAt(0) === '{' || line.charAt(0) === '('))) {
      return {
        content: line[0] === ' ' ? line.substr(1, l) : line
      };
    }
    open = line.charAt(0);
    close = (open === '{') ? '}' : ')';
    joiner = (open === '{') ? ':' : '=';
    seperator = (open === '{') ? ',' : ' ';

    function process_pair() {
      if (typeof pair.start === 'number' &&
          typeof pair.middle === 'number' &&
          typeof pair.end === 'number') {
        var key = line.substr(pair.start, pair.middle - pair.start).trim(),
            value = line.substr(pair.middle + 1, pair.end - pair.middle - 1).trim();
        attributes[key] = value;
      }
      pair = {
        start: null,
        middle: null,
        end: null
      };
    }

    for (i = 1; count > 0; i += 1) {

      // If we reach the end of the line, then there is a problem
      if (i > l) {
        throw "Malformed attribute block";
      }

      c = line.charAt(i);
      if (skip) {
        skip = false;
      } else {
        if (quote) {
          if (c === '\\') {
            skip = true;
          }
          if (c === quote) {
            quote = false;
          }
        } else {
          if (c === '"' || c === "'") {
            quote = c;
          }

          if (count === 1) {
            if (c === joiner) {
              pair.middle = i;
            }
            if (c === seperator || c === close) {
              pair.end = i;
              process_pair();
              if (c === seperator) {
                pair.start = i + 1;
              }
            }
          }

          if (c === open) {
            count += 1;
          }
          if (c === close) {
            count -= 1;
          }
        }
      }
    }
    attributes.content = line.substr(i, line.length);
    return attributes;
  }
1044542
function prune(code) {
  var ast = esprima.parse(code);

  estraverse.replace(ast, {
    leave: function leave(node, parent) {
      var ret;

      if ('IfStatement' === node.type) {
        if ('BinaryExpression' !== node.test.type) return;

        if ('self' === node.test.left.argument.name) {
          node.alternate = null;
        } else if ('global' === node.test.left.argument.name) {
          ret = node.alternate;
        }

        return ret;
      }

      if (
          'BlockStatement' === node.type
        && 'FunctionExpression' === parent.type
      ) {
        return node.body[0].alternate.alternate;
      }
    }
  });

  return escodegen.generate(ast, {
    format: {
      indent: { style: '  ' },
      semicolons: false,
      compact: true
    }
  });
}
492972
static Shortcode parseStart(final String str) throws ParseException {
      String exp = str.trim();

      if(exp.length() < 3) {
         throw new ParseException(String.format("Invalid shortcode ('%s')", str), 0);
      }

      if(exp.charAt(0) != '[') {
         throw new ParseException("Expecting '['", 0);
      }

      if(exp.charAt(exp.length() - 1) != ']') {
         throw new ParseException("Expecting ']'", exp.length() - 1);
      }

      exp = exp.substring(1, exp.length() - 1).trim();

      if(exp.length() == 0) {
         throw new ParseException(String.format("Invalid shortcode ('%s')", str), 0);
      }

      int attrStart = exp.indexOf(' ');
      if(attrStart < 0) {
         return new Shortcode(validateName(exp), ImmutableMap.of());
      } else {
         return new Shortcode(validateName(exp.substring(0, attrStart)), parseAttributes(exp.substring(attrStart).trim()));
      }
   }
1323411
func (s *shortcodeHandler) extractShortcode(ordinal, level int, pt *pageparser.Iterator) (*shortcode, error) {
	if s == nil {
		panic("handler nil")
	}
	sc := &shortcode{ordinal: ordinal}

	var cnt = 0
	var nestedOrdinal = 0
	var nextLevel = level + 1

	fail := func(err error, i pageparser.Item) error {
		return s.parseError(err, pt.Input(), i.Pos)
	}

Loop:
	for {
		currItem := pt.Next()
		switch {
		case currItem.IsLeftShortcodeDelim():
			next := pt.Peek()
			if next.IsShortcodeClose() {
				continue
			}

			if cnt > 0 {
				// nested shortcode; append it to inner content
				pt.Backup()
				nested, err := s.extractShortcode(nestedOrdinal, nextLevel, pt)
				nestedOrdinal++
				if nested.name != "" {
					s.nameSet[nested.name] = true
				}
				if err == nil {
					sc.inner = append(sc.inner, nested)
				} else {
					return sc, err
				}

			} else {
				sc.doMarkup = currItem.IsShortcodeMarkupDelimiter()
			}

			cnt++

		case currItem.IsRightShortcodeDelim():
			// we trust the template on this:
			// if there's no inner, we're done
			if !sc.isInline && !sc.info.IsInner {
				return sc, nil
			}

		case currItem.IsShortcodeClose():
			next := pt.Peek()
			if !sc.isInline && !sc.info.IsInner {
				if next.IsError() {
					// return that error, more specific
					continue
				}

				return sc, fail(_errors.Errorf("shortcode %q has no .Inner, yet a closing tag was provided", next.Val), next)
			}
			if next.IsRightShortcodeDelim() {
				// self-closing
				pt.Consume(1)
			} else {
				sc.isClosing = true
				pt.Consume(2)
			}

			return sc, nil
		case currItem.IsText():
			sc.inner = append(sc.inner, currItem.ValStr())
		case currItem.IsShortcodeName():

			sc.name = currItem.ValStr()

			// Check if the template expects inner content.
			// We pick the first template for an arbitrary output format
			// if more than one. It is "all inner or no inner".
			tmpl, found, _ := s.s.Tmpl.LookupVariant(sc.name, tpl.TemplateVariants{})
			if !found {
				return nil, _errors.Errorf("template for shortcode %q not found", sc.name)
			}

			sc.info = tmpl.(tpl.TemplateInfoProvider).TemplateInfo()
		case currItem.IsInlineShortcodeName():
			sc.name = currItem.ValStr()
			sc.isInline = true
		case currItem.IsShortcodeParam():
			if !pt.IsValueNext() {
				continue
			} else if pt.Peek().IsShortcodeParamVal() {
				// named params
				if sc.params == nil {
					params := make(map[string]string)
					params[currItem.ValStr()] = pt.Next().ValStr()
					sc.params = params
				} else {
					if params, ok := sc.params.(map[string]string); ok {
						params[currItem.ValStr()] = pt.Next().ValStr()
					} else {
						return sc, errShortCodeIllegalState
					}

				}
			} else {
				// positional params
				if sc.params == nil {
					var params []string
					params = append(params, currItem.ValStr())
					sc.params = params
				} else {
					if params, ok := sc.params.([]string); ok {
						params = append(params, currItem.ValStr())
						sc.params = params
					} else {
						return sc, errShortCodeIllegalState
					}

				}
			}
		case currItem.IsDone():
			// handled by caller
			pt.Backup()
			break Loop

		}
	}
	return sc, nil
}
658918
function parseJavascript(content) {
    var _return = {},
      parts = content.split("\n"),
      keys = [
        "name",
        "namespace",
        "type",
        "description",
        "example",
        "param",
        "event",
        "return",
        "main",
        "dependency"
      ];

    for (var pi in parts) {
      var p = parts[pi];

      for (var ki in keys) {
        var key = keys[ki];

        if (p.indexOf("@"+key) > -1 && p.indexOf("@events") < 0) {
          var pset = p.split("@"+key),
          part = pset[ pset.length - 1 ].trim();

          // Split down params, events and returns
          if ( ["param","event","return"].indexOf(key) > -1 ) {
            var parray = [];

            if (key !== "return") {
              parray = part.split(" ", 1);
              parray.push( part.replace(parray[0]+" ", "") );
              part = {
                "name": parray[0].trim()
              };
            } else {
              parray[0] = ''
              parray[1] = part;
              part = {};
            }

            if (parray[1]) {
              // 0 - all
              // 1 - type
              // 2 - default
              // 3 - description

              // Patterns: \[([^\]]*)\]|\<([^\]]*)\>|\"([^\]]*)\"
              var matches = parray[1].match(/\[([^\]]*)\]|\<([^\]]*)\>|\"([^\]]*)\"/g);

              for (var mi in matches) {
                var match = matches[mi];

                if (match.indexOf("[") === 0) {
                  part.type = match.replace("[", "").replace("]", "");
                }
                if (match.indexOf("<") === 0) {
                  part.default = match.replace("<", "").replace(">", "");
                }
                if (match.indexOf('"') === 0) {
                  part.description = match.replace(/"/g, "");
                }
              }
            }
          }

          if (key === "param") {
            if (!_return.params) {
              _return["params"] = [];
            }
            _return["params"].push(part);
          } else if (key === "example") {
            if (!_return.examples) {
              _return["examples"] = [];
            }
            _return["examples"].push(part);
          } else if (key === "event") {
            if (!_return.events) {
              _return["events"] = [];
            }
            _return["events"].push(part);
          } else if (key === "main") {
            if (!_return.main) {
              _return["main"] = [];
            }
            _return["main"].push(part);
          } else if (key === "dependency") {
            if (!_return.dependencies) {
              _return["dependencies"] = [];
            }
            _return["dependencies"].push(part);
          } else {
            _return[key] = part;
          }
        }
      }
    }

    return _return;
  }
349426
function parseIncludes(codes, includes) {
    const result = {};
    for (const id of Object.keys(codes)) {
        const code = codes[id];
        result[id] = code.split('\n').map(function(line) {
            if (line.trim().substr(0, 8) !== '#include') return line;
            const pos = line.indexOf('#include') + 8;
            let includeName = line.substr(pos).trim();
            // We accept all this systaxes:
            // #include foo
            // #include 'foo'
            // #include <foo>
            // #include "foo"
            if ("'<\"".indexOf(includeName.charAt(0)) > -1) {
                includeName = includeName.substr(1, includeName.length - 2);
            }
            const snippet = includes[includeName];
            if (typeof snippet !== 'string') {
                console.error("Include <" + includeName + "> not found in ", includes);
                throw Error("Include not found in shader: " + includeName);
            }
            return snippet;
        }).join("\n");
    }
    return result;
}
624178
function( HTMLCode ){
        var $ = cheerio.load( HTMLCode, { decodeEntities: false } );

        _.forEach(
            {
                a: "href",
                img: "src",
                link: "href",
                script: "src"
            },
            function( attr, tagName ){
                $( tagName + "[" + attr + "]" ).each( function( index, elm ){
                    var testValue = $( elm ).attr( attr );
                    if( testValue.match( /^(#|\/|http:\/\/|https:\/\/|tel:|mailto:)/ ) ){ return; }
                    $( elm ).attr( attr, "<%- __normalizePath__( \"" + this.convertResourcePathAbsolute( testValue ).replace( /\\/g, "\\\\" ) + "\" ) %>" );
                }.bind( this ) );
            },
            this
        );

        return $.html();
    }
479570
function checkKeyNamespace(key) {
            try {
        	    var regDot = /\./;
        	    if (regDot.test(key)) {
            		var fullname = '';
            		var names = key.split(/\./);
            		for (var i = 0; i < names.length; i++) {
            		    if (i > 0) {
            			    fullname += '.';
            		    }
            		    fullname += names[i];

                        if (typeof fullname === "undefined") {
                            fullname = {};
                        }

            		    /*if (eval('typeof ' + fullname + ' == "undefined"')) {
            			    eval(fullname + '={};');
            		    }*/
        		    }
    	        }
            } catch(e) {
                logger.error("AUGMENTED: MessageBundle " + e);
            }
    	}
319518
function parseMarkdown (markdownContent) {
  var codeBlocks =  markdownContent

  .split('```')

  .filter(function (codeBlock, index) {

    // Delete the text in between code sections
    if (index % 2 === 0 ||

        // Remove non JavaScript and JSON code blocks
        (codeBlock.trim().toLowerCase().indexOf('js')         !== 0 &&
         codeBlock.trim().toLowerCase().indexOf('javascript') !== 0)) {
      return false;
    }
    return true;
  })

  .map(function (codeBlock) {
    return {
      lang: codeBlock.split('\n')[0].trim().toLowerCase(),
      code: codeBlock.slice(codeBlock.indexOf('\n') + 1)
    };
  });

  return codeBlocks;
}