Trims the superfluous whitespace out of an HTML block
426062
public static String cleanWhitespace(String theResult) {
		StringBuilder b = new StringBuilder();
		boolean inWhitespace = false;
		boolean betweenTags = false;
		boolean lastNonWhitespaceCharWasTagEnd = false;
		boolean inPre = false;
		for (int i = 0; i < theResult.length(); i++) {
			char nextChar = theResult.charAt(i);
			if (inPre) {
				b.append(nextChar);
				continue;
			} else if (nextChar == '>') {
				b.append(nextChar);
				betweenTags = true;
				lastNonWhitespaceCharWasTagEnd = true;
				continue;
			} else if (nextChar == '\n' || nextChar == '\r') {
				continue;
			}

			if (betweenTags) {
				if (Character.isWhitespace(nextChar)) {
					inWhitespace = true;
				} else if (nextChar == '<') {
					if (inWhitespace && !lastNonWhitespaceCharWasTagEnd) {
						b.append(' ');
					}
					b.append(nextChar);
					inWhitespace = false;
					betweenTags = false;
					lastNonWhitespaceCharWasTagEnd = false;
					if (i + 3 < theResult.length()) {
						char char1 = Character.toLowerCase(theResult.charAt(i + 1));
						char char2 = Character.toLowerCase(theResult.charAt(i + 2));
						char char3 = Character.toLowerCase(theResult.charAt(i + 3));
						char char4 = Character.toLowerCase((i + 4 < theResult.length()) ? theResult.charAt(i + 4) : ' ');
						if (char1 == 'p' && char2 == 'r' && char3 == 'e') {
							inPre = true;
						} else if (char1 == '/' && char2 == 'p' && char3 == 'r' && char4 == 'e') {
							inPre = false;
						}
					}
				} else {
					lastNonWhitespaceCharWasTagEnd = false;
					if (inWhitespace) {
						b.append(' ');
						inWhitespace = false;
					}
					b.append(nextChar);
				}
			} else {
				b.append(nextChar);
			}
		}
		return b.toString();
	}
400241
function purify(input) {
    var result = [], indent = null, codeBlock = false;
    
    // We can have two types of lines:
    // - those beginning with *
    // - and those without it
    input.split("\n").forEach(function(line) {
        // chomp !
        line = line.replace(/(\n|\r)+$/, '');

        if (!codeBlock && /^\s*\*\s*```/.test(line))
          codeBlock = true;
        else if (codeBlock && /^\s*\*\s*```/.test(line))
          codeBlock = false;

        var m;
        if ( ( m = line.match(/^\s*\*\s?(.*)$/)) ) {
            // When comment contains *-lines, switch indent-trimming off
            indent = 0;
            
            if (codeBlock)
              result.push(m[1]);
            else
              result.push(m[1].replace(/^\s+/,""));
        }
        else if (/^\s*$/.test(line)) {
            // pass-through empty lines
            result.push(line);
        }
        else if (indent === undefined && (m = line.match(/^(\s*)(.*?$)/) ) ) {
            // When indent not measured, measure it and remember
            indent = m[1];
            result.push(m[2]);
        }
        else {
            // Trim away indent if available
            //result.push(line.replace(new RegExp("^\s{0," + indent + "}"), ""));
            result.push(line.replace(/^\s+/,""));
        }
    });

    return result.join("\n");
}
819248
function whitespace(layout) {
	var whitespace = layout.size[0] * layout.size[1]
	for (var i = 0; i < layout.boxes.length; i++) {
		var box = layout.boxes[i]
		whitespace -= box.size[0] * box.size[1]
	}
	return whitespace
}
895232
function stripBlockBr( element ) {
		var br;

		if ( element.previous && !isBrOrBlock( element.previous ) ) {
			br = createBr();
			br.insertBefore( element );
		}

		if ( element.next && !isBrOrBlock( element.next ) ) {
			br = createBr();
			br.insertAfter( element );
		}

		element.replaceWithChildren();
	}
360138
function removeNestedBlocks (ast) {
  var tagged;
  while((tagged = findNestedBlocks(ast)).length) {
    fast.forEach(tagged, function (item) {
      var node = item[0],
          parent = item[1],
          index = parent.body.indexOf(node);
      fast.apply(Array.prototype.splice, parent.body, fast.concat([index, 1], node.body));
    });
  }
  return ast;
}
371969
function whitespaceEndPos( $tpl, &$text, $currentPosition, $textLength )
    {
        if ( $currentPosition >= $textLength )
            return $currentPosition;
        while( $currentPosition < $textLength and
               ( $text[$currentPosition] === ' '
                 or $text[$currentPosition] === "\n"
                 or $text[$currentPosition] === "\t"
                 or $text[$currentPosition] === "\r" ) )
        {
            ++$currentPosition;
        }
        return $currentPosition;
    }
512218
protected function fixBlockElementSpacing()
    {
        if ($this->parser->isStartTag) {
            $this->parser->html = ltrim($this->parser->html);
        }
    }
403153
function trimLeadingLineBreaks(node) {
          do {
            if (node.nodeType === 3) {
              node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
            }

            node = node.firstChild;
          } while (node);
        }
773194
def _strip_space(x):
    """"""
    r = repr(x)
    space_repr = '{!r}.element('.format(x.space)
    if r.startswith(space_repr) and r.endswith(')'):
        r = r[len(space_repr):-1]
    return r
1242620
function selector() {
        whitespace();

        while (css[0] === '}') {
            error('extra closing bracket');
        }

        const m = match(/^(("(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[^{])+)/);

        if (m) {
            return m[0]
                .trim() // remove all comments from selectors
                .replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '')
                .replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function(m) {
                    return m.replace(/,/g, '\u200C');
                })
                .split(/\s*(?![^(]*\)),\s*/)
                .map(function(s) {
                    return s.replace(/\u200C/g, ',');
                });
        }
    }
602275
def adjust_whitespace(text):
    """"""

    state = [False, False]
    (backslashed, triplequoted) = (0, 1)

    def in_multi_line(line):
        start_state = (state[backslashed] or state[triplequoted])

        if re.search(r"\\$", line):
            state[backslashed] = True
        else:
            state[backslashed] = False

        def match(reg, t):
            m = re.match(reg, t)
            if m:
                return m, t[len(m.group(0)):]
            else:
                return None, t

        while line:
            if state[triplequoted]:
                m, line = match(r"%s" % state[triplequoted], line)
                if m:
                    state[triplequoted] = False
                else:
                    m, line = match(r".*?(?=%s|$)" % state[triplequoted], line)
            else:
                m, line = match(r'#', line)
                if m:
                    return start_state

                m, line = match(r"\"\"\"|\'\'\'", line)
                if m:
                    state[triplequoted] = m.group(0)
                    continue

                m, line = match(r".*?(?=\"\"\"|\'\'\'|#|$)", line)

        return start_state

    def _indent_line(line, stripspace=''):
        return re.sub(r"^%s" % stripspace, '', line)

    lines = []
    stripspace = None

    for line in re.split(r'\r?\n', text):
        if in_multi_line(line):
            lines.append(line)
        else:
            line = line.expandtabs()
            if stripspace is None and re.search(r"^[ \t]*[^# \t]", line):
                stripspace = re.match(r"^([ \t]*)", line).group(1)
            lines.append(_indent_line(line, stripspace))
    return "\n".join(lines)
1355997
function elementTrailingWhitespace(el) {
  let style = getComputedStyle(el, null)
  let display = style.getPropertyValue('display')

  let lastNotIgnoredChild = () => {
    for(let i = el.children.length - 1; i >= 0; i--) {
      let n = el.children[i]
      if(!ignoredNode(n)) return n
    }
    return null
  }

  if(display === 'inline') {
    let last = lastNotIgnoredChild()
    if(last && last.nodeType === Node.ELEMENT_NODE) {
      let lastChunks = []
      innerRichText(last, lastChunks)
      return elementTrailingWhitespace(last, lastChunks)
    } else {
      return ''
    }
  } else if(display === 'inline-block'
    || display === 'inline-table'
    || display === 'none'
    || display === 'table-column'
    || display === 'table-column-group') {
    return ''
  } else if(display === 'table-cell') {
    return '\t'
  } else {
    let elChunks = []
    innerRichText(el, elChunks)
    if(elChunks && elChunks.length > 0) {
      let marginBottom = getPixelStyleProperty(style, 'margin-bottom')
      let fontSize = getPixelStyleProperty(style, 'font-size')
      if(marginBottom >= fontSize / 2) return '\n\n'
      else return '\n'
    } else return ''
  }
}
755229
def clean_whitespace(self, tree):
        

        pointer = 0
        end = len(tree)

        while pointer < end:
            piece = tree[pointer]
            if piece[0] == 'block':
                child_tree = piece[3]

                # Look at open tag, if the only other thing on the line is whitespace
                # then delete it so we don't introduce extra newlines to the output
                open_pre_whitespace = False
                open_pre_content = True
                if pointer > 1 and tree[pointer - 1][0] == 'whitespace' and (tree[pointer - 2][0] == 'newline' or tree[pointer - 2] == 'template'):
                    open_pre_whitespace = True
                    open_pre_content = False
                elif pointer > 0 and (tree[pointer - 1][0] == 'newline' or tree[pointer - 1] == 'template'):
                    open_pre_content = False

                open_post_whitespace = False
                open_post_content = True
                child_len = len(child_tree)
                if child_len > 2 and child_tree[1][0] == 'whitespace' and child_tree[2][0] == 'newline':
                    open_post_whitespace = True
                    open_post_content = False
                elif child_len > 1 and child_tree[1][0] == 'newline':
                    open_post_content = False

                if not open_pre_content and not open_post_content:
                    if open_pre_whitespace:
                        tree.pop(pointer - 1)
                        pointer -= 1
                        end -= 1
                    if open_post_whitespace:
                        child_tree.pop(1)
                    child_tree.pop(1)  # trailing newline

                # Do the same thing, but for the close tag
                close_pre_whitespace = False
                close_pre_content = True
                child_len = len(child_tree)
                if child_len > 2 and child_tree[child_len - 1][0] == 'whitespace' and child_tree[child_len - 2][0] == 'newline':
                    close_pre_whitespace = True
                    close_pre_content = False
                elif child_len > 1 and child_tree[child_len - 1][0] == 'newline':
                    close_pre_content = False

                close_post_whitespace = False
                close_post_content = True
                tree_len = len(tree)
                if tree_len > pointer + 2 and tree[pointer + 1][0] == 'whitespace' and tree[pointer + 2][0] == 'newline':
                    close_post_whitespace = True
                    close_post_content = False
                elif tree_len == pointer + 2 and tree[pointer + 1][0] == 'whitespace':
                    close_post_whitespace = True
                    close_post_content = False
                elif tree_len > pointer + 1 and tree[pointer + 1][0] == 'newline':
                    close_post_content = False
                elif tree_len == pointer + 1:
                    close_post_content = False

                if not close_pre_content and not close_post_content:
                    if close_pre_whitespace:
                        child_tree.pop()
                    child_tree.pop()  # preceeding newline
                    if close_post_whitespace:
                        tree.pop(pointer + 1)
                        end -= 1

                self.clean_whitespace(child_tree)

            pointer += 1
1341161
def _clean_html(html):
    
    content = html.replace(u'&#x000A;', u'\n').replace(u'¶', '')
    content = _LINK_PATTERN.sub(u'', content)
    content = _HTML_TAG_PATTERN.sub(u'', content)
    content = _BACKSLASH_PATTERN.sub(u'\n', content)
    return content
1362934
def remove_whitespace(text_string):
    '''
    
    '''
    if text_string is None or text_string == "":
        return ""
    elif isinstance(text_string, str):
        return " ".join(text_string.split())
    else:
        raise InputError("none type or string not passed as an argument")
120057
function( text ){
			if(text && text.length){
				var i = text.length,
					x = 0;

				// turn all whitespace chars at end into spaces
				while (i--) {
					if(this.isOnlyWhiteSpace(text[i])){
						text = this.replaceCharAt( text, i, ' ' );
					}else{
						break;
					}
				}

				// turn all whitespace chars at start into spaces
				i = text.length;
				while (x < i) {
					if(this.isOnlyWhiteSpace(text[x])){
						text = this.replaceCharAt( text, i, ' ' );
					}else{
						break;
					}
					x++;
				}
			}
			return this.trim(text);
		}
792355
def clean_tag_borders(string)
      result = string.gsub(/\s?\*{2,}.*?\*{2,}\s?/) do |match|
        preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do
          match.strip.sub('** ', '**').sub(' **', '**')
        end
      end

      result = result.gsub(/\s?\_{2,}.*?\_{2,}\s?/) do |match|
        preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do
          match.strip.sub('__ ', '__').sub(' __', '__')
        end
      end

      result = result.gsub(/\s?~{2,}.*?~{2,}\s?/) do |match|
        preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do
          match.strip.sub('~~ ', '~~').sub(' ~~', '~~')
        end
      end

      result.gsub(/\s?\[.*?\]\s?/) do |match|
        preserve_border_whitespaces(match) do
          match.strip.sub('[ ', '[').sub(' ]', ']')
        end
      end
    end