Replace the original block with new one, with special treatment for <pre> blocks to make sure content format is well preserved, and merging/splitting adjacent when necessary. (#3188)
185603
function replaceBlock( block, newBlock ) {
		// Block is to be removed, create a temp element to
		// save contents.
		var removeBlock = !newBlock;
		if ( removeBlock ) {
			newBlock = block.getDocument().createElement( 'div' );
			block.copyAttributes( newBlock );
		}

		var newBlockIsPre = newBlock && newBlock.is( 'pre' ),
			blockIsPre = block.is( 'pre' ),
			isToPre = newBlockIsPre && !blockIsPre,
			isFromPre = !newBlockIsPre && blockIsPre;

		if ( isToPre )
			newBlock = toPre( block, newBlock );
		else if ( isFromPre )
			// Split big <pre> into pieces before start to convert.
			newBlock = fromPres( removeBlock ? [ block.getHtml() ] : splitIntoPres( block ), newBlock );
		else
			block.moveChildren( newBlock );

		newBlock.replace( block );

		if ( newBlockIsPre ) {
			// Merge previous <pre> blocks.
			mergePre( newBlock );
		} else if ( removeBlock ) {
			removeNoAttribsElement( newBlock );
		}
	}
160506
def update(self, old_line, new_line, once=False):
        
        nb = 0
        for block in self.blocks:
            nb += block.update(old_line, new_line, once=once)
            if nb and once:
                return nb
        return nb
414360
def _reset_plain(self):
        ''''''
        if self._text:
            self._blocks.append(BlockText('\n'.join(self._text)))
        self._text.clear()
874449
function addBrToBlockIfNeeded(block) {
          var lastChild;

          // IE will render the blocks correctly other browsers needs a BR
          if (!isIE) {
            block.normalize(); // Remove empty text nodes that got left behind by the extract

            // Check if the block is empty or contains a floated last child
            lastChild = block.lastChild;
            if (!lastChild || (/^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true)))) {
              dom.add(block, 'br');
            }
          }
        }
773276
def replace_blocks(self, blocks):
        """"""
        start = 0
        bulk_insert = self.bulk_insert
        blocks_len = len(blocks)
        select = 'SELECT ?,?,?,?,?'
        query = 'REPLACE INTO gauged_data (namespace, offset, `key`, ' \
            'data, flags) '
        execute = self.cursor.execute
        while start < blocks_len:
            rows = blocks[start:start+bulk_insert]
            params = [param for params in rows for param in params]
            insert = (select + ' UNION ') * (len(rows) - 1) + select
            execute(query + insert, params)
            start += bulk_insert
476930
function tagReplace(original, tag, value) {
  var fullTag = `[[${  tag  }]]`;
  return original.split(fullTag).join(value ? value : '');
}
1103880
def add_next_block(prev_block, data)
      if valid_block?(prev_block)
        blockchain << next_block(data)
      else
        raise InvalidBlockError
      end
    end
519708
def replace(self, to_replace=None, value=None, inplace=False,
                limit=None, regex=False, method='pad', axis=None):
        
        if inplace:
            self._frame.replace(to_replace=to_replace, value=value,
                                inplace=inplace, limit=limit, regex=regex,
                                method=method, axis=axis)
        else:
            new = self.__class__(self._frame.replace(
                to_replace=to_replace, value=value, inplace=inplace,
                limit=limit, regex=regex, method=method, axis=axis))
            new.metadata = self.metadata.copy()
            new._metadata = copy.deepcopy(self._metadata)
            return new
458289
def new_block(self):
        
        child = Block(self, py3_wrapper=self.py3_wrapper)
        self.add(child)
        return child
1057508
def split_blocks(text_block, w, cols, part_fmter=None):
    
    ts = []
    for line in text_block.splitlines():
        parts = []
        # make equal len:
        line = line.ljust(w, ' ')
        # first part full width, others a bit indented:
        parts.append(line[:cols])
        scols = cols-2
        # the txt_block_cut in low makes the whole secondary tables
        # low. which i find a feature:
        # if you don't want it remove the col(.., L)
        parts.extend([' ' + col(txt_block_cut, L, no_reset=1) + \
                line[i:i+scols] \
                    for i in range(cols, len(line), scols)])
        ts.append(parts)

    blocks = []
    for block_part_nr in xrange(len(ts[0])):
        tpart = []
        for lines_block in ts:
            tpart.append(lines_block[block_part_nr])
        if part_fmter:
            part_fmter(tpart)
        tpart[1]  = col(tpart[1], H3)
        blocks.append('\n'.join(tpart))
    t = '\n'.join(blocks)
    return('\n%s\n' % t)
1370910
public function replaceWith()
    {
        $removed_nodes = new self();

        $this->importNodes(\func_get_args(), function ($node, $imported_node) use (&$removed_nodes) {
            if ($node->nextSibling) {
                $node->parentNode->insertBefore($imported_node, $node->nextSibling);
            } else { // node is last, so there is no next sibling to insert before
                $node->parentNode->appendChild($imported_node);
            }
            $removed_nodes->addDomNode($node);
            $node->parentNode->removeChild($node);
        });

        foreach (\func_get_args() as $new_content) {
            if (!\is_string($new_content)) {
                self::create($new_content)->remove();
            }
        }

        return $removed_nodes;
    }
517567
private function replaceAnBlock(BlockContent $block, array $data) {

    $block->field_text_block = [
      'value' => $data['textblock'],
      'format' => 'full_html',
    ];

    /* @var \Drupal\file\Entity\File $file */
    $block_image = $this->prepareImage($data['image'], 'Anonymous front page image homepage');
    // Insert is in the hero image field.
    $block->field_hero_image = $block_image;

    // Set the links.
    $action_links = [
      [
        'uri' => 'internal:' . $data['cta1']['url'],
        'title' => $data['cta1']['text'],
      ],
      [
        'uri' => 'internal:' . $data['cta2']['url'],
        'title' => $data['cta2']['text'],
      ],
    ];
    $itemList = new FieldItemList($block->field_call_to_action_link->getFieldDefinition());
    $itemList->setValue($action_links);
    $block->field_call_to_action_link = $itemList;
    $block->save();
  }
1081927
def replace(self, child, replacement):
        """"""
        for i in range(len(self.chunks)):
            if self.chunks[i] == child:
                self.chunks[i] = replacement
795804
private void normalizeBlocks(Node n) {
    if (NodeUtil.isControlStructure(n)
        && !n.isLabel()
        && !n.isSwitch()) {
      for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
        if (NodeUtil.isControlStructureCodeBlock(n, c) && !c.isBlock()) {
          Node newBlock = IR.block().srcref(n);
          n.replaceChild(c, newBlock);
          newBlock.setIsAddedBlock(true);
          if (!c.isEmpty()) {
            newBlock.addChildrenToFront(c);
          }
          c = newBlock;
          reportChange();
        }
      }
    }
  }
360808
private static void mergeBlocks(List< Block > blocks) {
        for (int i = 1; i < blocks.size(); i++) {
            Block b1 = blocks.get(i - 1);
            Block b2 = blocks.get(i);
            if ((b1.mode == b2.mode) &&
                (b1.mode != EncodingMode.NUM || b1.length + b2.length <= MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {
                b1.length += b2.length;
                blocks.remove(i);
                i--;
            }
        }
    }
264725
def replace_blocks(self, blocks):
        """"""
        start = 0
        bulk_insert = self.bulk_insert
        blocks_len = len(blocks)
        row = '(%s,%s,%s,%s,%s)'
        query = 'REPLACE INTO gauged_data (namespace, offset, `key`, ' \
            'data, flags) VALUES '
        execute = self.cursor.execute
        to_buffer = self.to_buffer
        while start < blocks_len:
            rows = blocks[start:start+bulk_insert]
            params = []
            for namespace, offset, key, data, flags in rows:
                params.extend((namespace, offset, key, to_buffer(data), flags))
            insert = (row + ',') * (len(rows) - 1) + row
            execute(query + insert, params)
            start += bulk_insert
951835
def copy(self, tagname, **kwargs):
        
        new_kwargs = {
            'replacement': self.replacement,
            'whitelist': self.whitelist,
            'safe_mode': self.safe_mode,
            'log_rejects': self.log_rejects,
            'ending_slash': self.ending_slash
        }
        new_kwargs.update(**kwargs)
        return TagWrap(tagname, **new_kwargs)