block : OPEN_TAG contents CLOSE_TAG
                 | OPEN_TAG CLOSE_TAG
                 | OPEN_CLOSE_TAG
198637
def p_block(self, p):
        
        n = len(p)
        if n == 4:
            p[0] = ['block', p[1], p[2], p[3]]
        elif n == 3:
            p[0] = ['block', p[1],  [], p[2]]
        else:
            p[0] = ['block', p[1], [], p[1]]

        if self.options.get('lowercasenames'):
            for tag in (1, 3):
                p[0][tag] = p[0][tag].lower()
1042945
function (tpl) {
      var ldelim = new RegExp(this.ldelim + '\\*')
      var rdelim = new RegExp('\\*' + this.rdelim)
      var newTpl = ''

      for (var openTag = tpl.match(ldelim); openTag; openTag = tpl.match(ldelim)) {
        newTpl += tpl.slice(0, openTag.index)
        tpl = tpl.slice(openTag.index + openTag[0].length)
        var closeTag = tpl.match(rdelim)
        if (!closeTag) {
          throw new Error('Unclosed ' + ldelim + '*')
        }
        tpl = tpl.slice(closeTag.index + closeTag[0].length)
      }
      return newTpl + tpl
    }
537165
def _handle_tag(self, token):
        """"""
        close_tokens = (tokens.TagCloseSelfclose, tokens.TagCloseClose)
        implicit, attrs, contents, closing_tag = False, [], None, None
        wiki_markup, invalid = token.wiki_markup, token.invalid or False
        wiki_style_separator, closing_wiki_markup = None, wiki_markup
        self._push()
        while self._tokens:
            token = self._tokens.pop()
            if isinstance(token, tokens.TagAttrStart):
                attrs.append(self._handle_attribute(token))
            elif isinstance(token, tokens.TagCloseOpen):
                wiki_style_separator = token.wiki_markup
                padding = token.padding or ""
                tag = self._pop()
                self._push()
            elif isinstance(token, tokens.TagOpenClose):
                closing_wiki_markup = token.wiki_markup
                contents = self._pop()
                self._push()
            elif isinstance(token, close_tokens):
                if isinstance(token, tokens.TagCloseSelfclose):
                    closing_wiki_markup = token.wiki_markup
                    tag = self._pop()
                    self_closing = True
                    padding = token.padding or ""
                    implicit = token.implicit or False
                else:
                    self_closing = False
                    closing_tag = self._pop()
                return Tag(tag, contents, attrs, wiki_markup, self_closing,
                           invalid, implicit, padding, closing_tag,
                           wiki_style_separator, closing_wiki_markup)
            else:
                self._write(self._handle_token(token))
        raise ParserError("_handle_tag() missed a close token")
975567
function replaceBlocks(content, blocks) {
    var newContent = content.replace(/\{\{\-\%([\s\S]+?)\%\-\}\}/g, function(match, key) {
        var replacedWith = match;

        var block = blocks.get(key);
        if (block) {
            replacedWith = replaceBlocks(block.get('body'), blocks);
        }

        return replacedWith;
    });

    return newContent;
}
388216
def get_contents_dynamic(self, block_alias, context):
        """"""
        dynamic_block = get_dynamic_blocks().get(block_alias, [])
        if not dynamic_block:
            return ''

        dynamic_block = choice(dynamic_block)
        return dynamic_block(block_alias=block_alias, block_context=context)
82873
def tag(self, name, attrs=None, selfclosing=None):
        """"""
        if self.disable_tags > 0:
            return

        if name in self.linkable_tags and attrs and len(attrs) > 0:
            for attrib in attrs:
                if attrib[0] in self.linkable_attrs:
                    attrib[1] = INTERNAL_LINK.sub('{\g<1>}', attrib[1])

        super().tag(name, attrs, selfclosing)
856429
def article_tag(title = nil, options = nil, &block)
      output = tag(:article, options, true)
      if title.present?
        output.safe_concat(
          content_tag("header") do
            content_tag("h1", title)
          end
        )
      end
      output.concat(capture(&block)) if block_given?
      output.safe_concat("</article>")
    end
89134
def close( self ):
        """"""

        if self.tag in self.parent.twotags:
            self.parent.content.append( "</%s>" % self.tag )
        elif self.tag in self.parent.onetags:
            raise ClosingError( self.tag )
        elif self.parent.mode == 'strict_html' and self.tag in self.parent.deptags:
            raise DeprecationError( self.tag )
632483
def t_OPEN_TAG(t):
    '
    if '=' in t.value: t.type = 'OPEN_TAG_WITH_ECHO'
    t.lexer.lineno += t.value.count("\n")
    t.lexer.begin('php')
    return t
463206
def _handle_tag_close_close(self):
        """"""
        strip = lambda tok: tok.text.rstrip().lower()
        closing = self._pop()
        if len(closing) != 1 or (not isinstance(closing[0], tokens.Text) or
                                 strip(closing[0]) != strip(self._stack[1])):
            self._fail_route()
        self._emit_all(closing)
        self._emit(tokens.TagCloseClose())
        return self._pop()
1072358
protected function processEndTag(Tag $tag)
	{
		$tagName = $tag->getName();

		if (empty($this->cntOpen[$tagName]))
		{
			// This is an end tag with no start tag
			return;
		}

		/**
		* @var array List of tags need to be closed before given tag
		*/
		$closeTags = [];

		// Iterate through all open tags from last to first to find a match for our tag
		$i = count($this->openTags);
		while (--$i >= 0)
		{
			$openTag = $this->openTags[$i];

			if ($tag->canClose($openTag))
			{
				break;
			}

			$closeTags[] = $openTag;
			++$this->currentFixingCost;
		}

		if ($i < 0)
		{
			// Did not find a matching tag
			$this->logger->debug('Skipping end tag with no start tag', ['tag' => $tag]);

			return;
		}

		// Accumulate flags to determine whether whitespace should be trimmed
		$flags = $tag->getFlags();
		foreach ($closeTags as $openTag)
		{
			$flags |= $openTag->getFlags();
		}
		$ignoreWhitespace = (bool) ($flags & self::RULE_IGNORE_WHITESPACE);

		// Only reopen tags if we haven't exceeded our "fixing" budget
		$keepReopening = (bool) ($this->currentFixingCost < $this->maxFixingCost);

		// Iterate over tags that are being closed, output their end tag and collect tags to be
		// reopened
		$reopenTags = [];
		foreach ($closeTags as $openTag)
		{
			$openTagName = $openTag->getName();

			// Test whether this tag should be reopened automatically
			if ($keepReopening)
			{
				if ($openTag->getFlags() & self::RULE_AUTO_REOPEN)
				{
					$reopenTags[] = $openTag;
				}
				else
				{
					$keepReopening = false;
				}
			}

			// Find the earliest position we can close this open tag
			$tagPos = $tag->getPos();
			if ($ignoreWhitespace)
			{
				$tagPos = $this->getMagicEndPos($tagPos);
			}

			// Output an end tag to close this start tag, then update the context
			$endTag = new Tag(Tag::END_TAG, $openTagName, $tagPos, 0);
			$endTag->setFlags($openTag->getFlags());
			$this->outputTag($endTag);
			$this->popContext();
		}

		// Output our tag, moving the cursor past it, then update the context
		$this->outputTag($tag);
		$this->popContext();

		// If our fixing budget allows it, peek at upcoming tags and remove end tags that would
		// close tags that are already being closed now. Also, filter our list of tags being
		// reopened by removing those that would immediately be closed
		if (!empty($closeTags) && $this->currentFixingCost < $this->maxFixingCost)
		{
			/**
			* @var integer Rightmost position of the portion of text to ignore
			*/
			$ignorePos = $this->pos;

			$i = count($this->tagStack);
			while (--$i >= 0 && ++$this->currentFixingCost < $this->maxFixingCost)
			{
				$upcomingTag = $this->tagStack[$i];

				// Test whether the upcoming tag is positioned at current "ignore" position and it's
				// strictly an end tag (not a start tag or a self-closing tag)
				if ($upcomingTag->getPos() > $ignorePos
				 || $upcomingTag->isStartTag())
				{
					break;
				}

				// Test whether this tag would close any of the tags we're about to reopen
				$j = count($closeTags);

				while (--$j >= 0 && ++$this->currentFixingCost < $this->maxFixingCost)
				{
					if ($upcomingTag->canClose($closeTags[$j]))
					{
						// Remove the tag from the lists and reset the keys
						array_splice($closeTags, $j, 1);

						if (isset($reopenTags[$j]))
						{
							array_splice($reopenTags, $j, 1);
						}

						// Extend the ignored text to cover this tag
						$ignorePos = max(
							$ignorePos,
							$upcomingTag->getPos() + $upcomingTag->getLen()
						);

						break;
					}
				}
			}

			if ($ignorePos > $this->pos)
			{
				/**
				* @todo have a method that takes (pos,len) rather than a Tag
				*/
				$this->outputIgnoreTag(new Tag(Tag::SELF_CLOSING_TAG, 'i', $this->pos, $ignorePos - $this->pos));
			}
		}

		// Re-add tags that need to be reopened, at current cursor position
		foreach ($reopenTags as $startTag)
		{
			$newTag = $this->addCopyTag($startTag, $this->pos, 0);

			// Re-pair the new tag
			$endTag = $startTag->getEndTag();
			if ($endTag)
			{
				$newTag->pairWith($endTag);
			}
		}
	}
1281028
private static function sanitizeTag($tag, $allowed = null, $resetStack = false)
    {
        static $stack = [];
        if ($resetStack) {
            $ret = $stack;
            $stack = [];
            return $ret;
        }

        $tag = substr($tag, 1, -1); // strip off leading '<' and trailing '>'
        if ($tag[0] == '/') {
            preg_match('/^\w+/', substr($tag, 1), $m);
            $closingTag = strtolower($m[0]);
            $localStack = [];

            if (null !== $allowed
                && (is_array($allowed) && !array_key_exists($closingTag, $allowed))
                || (is_callable($allowed) && !call_user_func($allowed, $closingTag))
            ) {
                return '<!-- ' . htmlspecialchars($tag) . ' -->';
            }

            do {
                if (!count($stack)) {
                    $stack = array_reverse($localStack);
                    // tag was never opened. Drop closing tag
                    return '';
                }
                $top = array_pop($stack);
                $localStack[] = $top;
            } while (strtolower($top) != $closingTag);
            $ret = '';
            foreach ($localStack as $needClose) {
                $ret .= '</' . $needClose . '>';
            }

            return $ret;
        } else {
            $ret = '';
            $attributes = [];
            preg_match('/^[\w-:]+/', $tag, $m);
            $tagName = strtolower($m[0]);
            if (null !== $allowed
                && (is_array($allowed) && !array_key_exists($tagName, $allowed))
                || (is_callable($allowed) && !call_user_func($allowed, $tagName))
            ) {
                return '<!-- ' . htmlspecialchars($tag) . ' -->';
            }

            $paragraphLevelElements = ['p', 'h6', 'h5', 'h4', 'h3', 'h2', 'h1', 'table', 'ul', 'div'];
            $inlineElements = ['span', 'b', 'i', 'u', 'span', 'strong', 'em', 'a', 'sup', 'sub'];
            $selfClosingElements = ['li', 'td', 'th', 'tr'];
            $forcedParents = ['li' => ['ul', 'ol']];

            if (count($stack) && in_array($tagName, $paragraphLevelElements)) {
                while (in_array(end($stack), array_merge($paragraphLevelElements, $inlineElements))) {
                    $ret .= '</' . array_pop($stack) . '>';
                }
            }
            if (count($stack) && in_array($tagName, $selfClosingElements)) {
                while (in_array(end($stack), $inlineElements)) {
                    $ret .= '</' . array_pop($stack) . '>';
                }
                if (end($stack) === $tagName) {
                    $ret .= '</' . array_pop($stack) . '>';
                }
            }

            if (array_key_exists($tagName, $forcedParents) && !in_array(end($stack), $forcedParents[$tagName])) {
                // if the parent would close paragraph or inline elements, do it now.
                if (count($stack) && in_array($forcedParents[$tagName][0], $paragraphLevelElements)) {
                    while (in_array(end($stack), array_merge($paragraphLevelElements, $inlineElements))) {
                        $ret .= '</' . array_pop($stack) . '>';
                    }
                }
                $ret .= '<' . $forcedParents[$tagName][0] . '>';
                $stack[] = $forcedParents[$tagName][0];
            }

            if (substr($tag, -1) == '/') {
                $isEmpty = true;
            } else {
                $isEmpty = in_array($tagName, ['br', 'img', 'input', 'param', 'isindex', 'area']);
            }
            for ($i = strlen($m[0]); $i < strlen($tag); true) {
                $preI = $i;

                $chunk = substr($tag, $i);

                if (preg_match('/^([\w-]+)\s*=\s*\"([^"]*)\"?/', $chunk, $m)) {
                    $attributes[$m[1]] = $m[2];
                    $i += strlen($m[0]);
                } elseif (preg_match('/^([\w-]+)\s*=\s*\'([^\']*)\'?/', $chunk, $m)) {
                    $attributes[$m[1]] = $m[2];
                    $i += strlen($m[0]);
                } elseif (preg_match('/^([\w-]+)=(\S+)/', $chunk, $m)) {
                    $attributes[$m[1]] = $m[2];
                    $i += strlen($m[0]);
                } elseif (preg_match('/^(\w+)/', $chunk, $m)) {
                    $attributes[$m[1]] = $m[1];
                    $i += strlen($m[0]);
                } else {
                    // drop character
                    $i++;
                }
                assert($i != $preI);
            }

            $ret .= '<';
            $ret .= $tagName;
            if (count($attributes)) {
                foreach ($attributes as $attrName => $value) {
                    $callback = null;
                    if (is_callable($allowed)) {
                        $callback = $allowed;
                    } elseif (is_array($allowed) && isset($allowed[$tagName]) && is_callable($allowed[$tagName])) {
                        $callback = $allowed[$tagName];
                    } elseif (is_array($allowed[$tagName]) && isset($allowed[$tagName][$attrName])) {
                        $callback = $allowed[$tagName][$attrName];
                    }
                    if (null !== $callback) {
                        $value = call_user_func($callback, $tagName, $attrName, $value);
                    }
                    if (false === $value) {
                        continue;
                    }
                    if (!preg_match('/^[a-z_-]/', $attrName)) {
                        // drop malformed attribute name
                        continue;
                    }
                    $ret .= ' ';
                    $ret .= sprintf('%s="%s"', $attrName, str_replace('"', '&quot;', $value));
                }
            }
            if ($isEmpty) {
                $ret .= ' /';
            } else {
                $stack[] = $tagName;
            }
            $ret .= '>';
            return $ret;
        }
    }
358323
function findClosingPair(open, matcher) {
		var stack = [], tag = null;
		var text = matcher.text();
		
		for (var pos = open.range.end, len = text.length; pos < len; pos++) {
			if (matches(text, pos, '<!--')) {
				// skip to end of comment
				for (var j = pos; j < len; j++) {
					if (matches(text, j, '-->')) {
						pos = j + 3;
						break;
					}
				}
			}
			
			if ((tag = matcher.matches(pos))) {
				if (tag.type == 'open' && !tag.selfClose) {
					stack.push(tag.name);
				} else if (tag.type == 'close') {
					if (!stack.length) { // found valid pair?
						return tag.name == open.name ? tag : null;
					}
					
					// check if current closing tag matches previously opened one
					if (stack[stack.length - 1] == tag.name) {
						stack.pop();
					} else {
						var found = false;
						while (stack.length && !found) {
							var last = stack.pop();
							if (last == tag.name) {
								found = true;
							}
						}
						
						if (!stack.length && !found) {
							return tag.name == open.name ? tag : null;
						}
					}
				}

				pos = tag.range.end - 1;
			}
		}
	}
254946
def handle_endtag(self, tagName):
        '''
            
        '''
        try:
            foundIt = False
            inTag = self._inTag
            for i in range(len(inTag)):
                if inTag[i].tagName == tagName:
                    foundIt = True
                    break

            if not foundIt:
                return
            # Handle closing tags which should have been closed but weren't
            while inTag[-1].tagName != tagName:
                inTag.pop()

            inTag.pop()
        except:
            pass
1344334
def _really_parse_tag(self):
        """"""
        data = _TagOpenData()
        self._push(contexts.TAG_OPEN)
        self._emit(tokens.TagOpenOpen())
        while True:
            this, next = self._read(), self._read(1)
            can_exit = (not data.context & (data.CX_QUOTED | data.CX_NAME) or
                        data.context & data.CX_NOTE_SPACE)
            if this is self.END:
                if self._context & contexts.TAG_ATTR:
                    if data.context & data.CX_QUOTED:
                        # Unclosed attribute quote: reset, don't die
                        data.context = data.CX_ATTR_VALUE
                        self._memoize_bad_route()
                        self._pop()
                        self._head = data.reset
                        continue
                    self._pop()
                self._fail_route()
            elif this == ">" and can_exit:
                self._handle_tag_close_open(data, tokens.TagCloseOpen)
                self._context = contexts.TAG_BODY
                if is_single_only(self._stack[1].text):
                    return self._handle_single_only_tag_end()
                if is_parsable(self._stack[1].text):
                    return self._parse(push=False)
                return self._handle_blacklisted_tag()
            elif this == "/" and next == ">" and can_exit:
                self._handle_tag_close_open(data, tokens.TagCloseSelfclose)
                return self._pop()
            else:
                self._handle_tag_data(data, this)
            self._head += 1
4483
public function tag($tag, $attr = null, $content = null, $close = false)
    {
        $tag = strtolower($tag);

        if (! empty($attr) && is_array($attr)) {
            $attr = $this->Attr->attr($attr);
        }

        if ($close) {
            return sprintf('<%s%s>%s</%1$s>', $tag, $attr, $content);
        } else {
            return sprintf('<%s%s>', $tag, $attr);
        }
    }
1338571
function _tag_open( &$parser, $tag, $attributes ) {
		$this->currentElement = strtoupper( $tag );

		switch( $this->currentElement ) {
			case 'DROP':
				$this->drop();
				break;
			case 'CLUSTERED':
			case 'BITMAP':
			case 'UNIQUE':
			case 'FULLTEXT':
			case 'HASH':
				// Add index Option
				$this->addIndexOpt( $this->currentElement );
				break;
			default:
				// print_r( array( $tag, $attributes ) );
		}
	}