Conceptadvanced
Rope
Also called rope, cord, rope data structure, string tree, Ropey, crope.
A rope stores a long string as a tree of short pieces, so concatenation, insertion and deletion change a few nodes and do not copy the whole text. Text editors use it.
- Applies to
- core-languages
Idea
A flat string keeps all of its characters in one block of memory. To insert a word in the middle, a program moves every character after the insertion point, and to join two strings, it copies at least one of them. For a short string that cost is too small to see. For a file of many megabytes in a text editor, each key press can copy the whole file. A rope is "a type of binary tree where each leaf (end node) holds a string of manageable size and length (also known as a weight), and each node further up the tree holds the sum of the lengths of all the leaves in its left subtree"1. An edit changes the tree and keeps the pieces of text.
# A rope is a tree. A leaf holds a short string, and a node joins two ropes.
class Leaf:
def __init__(self, s):
self.s, self.n = s, len(s)
class Node:
def __init__(self, left, right):
self.left, self.right = left, right
self.n = left.n + right.n # the length of the whole subtree
self.weight = left.n # the length of the left part
EMPTY = Leaf("")
def concat(a, b):
# O(1): no characters are copied.
if a.n == 0:
return b
if b.n == 0:
return a
return Node(a, b)
def index(r, i):
# Walk down from the root. The cost is the depth of the tree.
while isinstance(r, Node):
if i < r.weight:
r = r.left
else:
i, r = i - r.weight, r.right
return r.s[i]
def split(r, i):
# Return two ropes: the first i characters and the rest.
if i <= 0:
return EMPTY, r
if i >= r.n:
return r, EMPTY
if isinstance(r, Leaf):
return Leaf(r.s[:i]), Leaf(r.s[i:])
if i < r.weight:
a, b = split(r.left, i)
return a, concat(b, r.right)
a, b = split(r.right, i - r.weight)
return concat(r.left, a), b
def insert(r, i, s):
a, b = split(r, i)
return concat(concat(a, Leaf(s)), b)
def text(r):
return r.s if isinstance(r, Leaf) else text(r.left) + text(r.right)
world = Leaf("world")
r = concat(Leaf("Hello, "), world)
print(r.n, index(r, 7))
r2 = insert(r, 7, "big ")
print(text(r2))
# The old rope does not change, and the new rope shares the leaf "world".
print(text(r))
print(r2.right is world)
a, b = split(r2, 5)
print(text(a) + "|" + text(b))
12 w
Hello, big world
Hello, world
True
Hello|, big world
concat makes one new node and copies no characters. index uses the weights to choose the left or the right child at each node, so it reads one leaf. insert is a split and two concat calls. The old rope r still says Hello, world after the insert, and the new rope uses the same leaf object for world, because no node is ever changed.
How it works
Weights. Each node stores the length of its left subtree. To find character i, start at the root. If i is less than the weight, go left. If not, subtract the weight from i and go right. At a leaf, i is an index into a short flat string. The cost is one step per level, so it is O(log n) in a balanced tree1.
Split and concat. These two operations build all the others. Concat makes "a new root node with left = S1 and right = S2, which is constant time"1. Split at position i walks the path to i, cuts the leaf there if the point is inside it, and joins the pieces on each side of the path1. Then insert is a split and two concats, and delete is two splits and one concat1. A substring "only copies pieces of leaf nodes at the beginning and end of the substring", and "The interior of the substring can remain shared with the original rope"2.
Immutable pieces. In the usual design, the nodes and leaves do not change after they are made, and the strings in them "are assumed to be constant immutable objects in the typical nondestructive case"1. So two ropes can share nodes, and "Minor modifications of a rope can share memory with the original"3. When only nondestructive operations are used, the rope is a persistent data structure, which "leads to an easy support for multiple undo levels"1. A node that no rope uses any more is freed by a reference count or by a garbage collector2.
Balance. Concatenation alone can make a deep and thin tree. A rope built by appending one character at a time has a depth equal to its length, and then an index costs O(n). An implementation rebalances the tree. The SGI rope rebalances "whenever the depth is in danger of overflowing", or when the rope is deep but short, and its implementation notes say that "rebalancing typically consumes a small fraction of the running time"2.
Leaves of a useful size. A leaf of one character costs a node for each character, so real ropes join short pieces into one leaf. The SGI rope has a special case for a short leaf that is joined to the right of a rope, so that ropes built by repeated appends "will be composed of leaves of a minimum size"2.
Summaries. A node can store more than a length. If each node also stores the number of line breaks in its subtree, a program finds the start of line k in O(log n) time. The xi editor and the Zed editor use this idea: each node keeps a summary of its subtree, and "when you edit the text, you recompute the summary only for the nodes that changed, then bubble those up to the root"4.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Idiom | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | TypeScript has no rope type. The JavaScript code works with types for the leaf and the node. No example file exists. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Idiom | Kotlin has no rope in its standard library. A class can implement CharSequence, as in the Java example. No example file exists because kotlinc is not installed. |
| SQL | Absent | SQL has no rope type. A database stores the text of a column in its own format. No example file exists. |
| Bash | Absent | Bash has strings and arrays but no tree types, so it cannot hold a rope. No example file exists. |
| PowerShell | Absent | PowerShell uses .NET types, and .NET has no rope type. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no data structures. |
| CSS | Does not apply | CSS has no data structures. |
| Regular expressions | Does not apply | A pattern has no data structures. In Java, a regex can read a rope through CharSequence. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | classes for leaves and nodes; no rope in the standard library |
| JavaScript | idiom | objects for leaves and nodes; no rope in the language |
| TypeScript | idiom | the JavaScript code with types |
| Java | idiom | a class that implements CharSequence; no rope in Java SE |
| Kotlin | idiom | a class that implements CharSequence |
| C# | idiom | records for leaves and nodes; no rope in .NET |
| Go | idiom | a struct with pointers to its children |
| Rust | idiom | an enum with Rc children; the ropey crate for real use |
| C | idiom | structs with pointers; the C cords of the Boehm garbage collector |
| C++ | idiom | shared_ptr nodes; the SGI rope class is an extension, not standard C++ |
| Bash | absent | no tree data types |
| PowerShell | absent | no rope type in .NET |
| SQL | absent | no rope type |
| Regex | n/a | a pattern has no data structures |
| HTML | n/a | no data structures |
| CSS | n/a | no data structures |
No language in this list has a rope in its standard library, so each example writes a small one by hand. In C++, rope is an SGI class, and "The rope class, and the rope header, are SGI extensions; they are not part of the C++ standard"3. In C, the cord package of the Boehm garbage collector gives "immutable character strings" in which "concatenation takes constant time"5. In Rust, "Ropey is a utf8 text rope for Rust"6, and all of its edits use char indexes, "which prevents accidental creation of invalid utf8 data"6.
The examples show different parts of the idea. Python builds a rope with 64 appends, so its depth is 63, and a rebalance makes the depth 6. JavaScript keeps each version of a buffer in an array, so an undo is a step back. Java implements CharSequence, so Pattern.matcher reads the rope with no copy, but each charAt walks the tree. C# cuts a long string into leaves of at most 8 characters and copies a range from only the leaves that hold it. Go stores a count of newlines in each node to find the start of a line. Rust uses Rc and shows that the old and the new rope share their leaves. C joins a rope with itself 20 times, so 21 nodes hold 2 MiB of text. C++ inserts into a rope of 4096 characters with 13 new nodes, where std::string::insert moves 2046 bytes.
# Appending one piece at a time makes a deep, thin tree. A rebalance rebuilds it.
class Leaf:
def __init__(self, s):
self.s, self.n, self.depth = s, len(s), 0
class Node:
def __init__(self, left, right):
self.left, self.right = left, right
self.n = left.n + right.n
self.depth = 1 + max(left.depth, right.depth)
def leaves(r):
if isinstance(r, Leaf):
yield r
else:
yield from leaves(r.left)
yield from leaves(r.right)
def balance(r):
# Collect the leaves and join them in pairs, from the bottom up.
level = list(leaves(r))
while len(level) > 1:
pairs = [Node(level[k], level[k + 1]) for k in range(0, len(level) - 1, 2)]
if len(level) % 2 == 1:
pairs.append(level[-1])
level = pairs
return level[0]
def index(r, i):
# Return the character and the number of nodes on the path.
steps = 0
while isinstance(r, Node):
steps += 1
if i < r.left.n:
r = r.left
else:
i, r = i - r.left.n, r.right
return r.s[i], steps
pieces = [chr(ord("a") + k % 26) for k in range(64)]
r = Leaf(pieces[0])
for p in pieces[1:]:
r = Node(r, Leaf(p))
print(r.n, r.depth, *index(r, 0))
b = balance(r)
print(b.n, b.depth, *index(b, 0))
print("".join(leaf.s for leaf in leaves(b)) == "".join(pieces), index(b, 40)[0])
64 63 a 63
64 6 a 6
True o
- Verdict: idiom. Python has no rope in its standard library. Each of the 64 appends puts the old rope on the left of a new node, so the depth is 63, and
index(r, 0)passes 63 nodes.balancecollects the leaves and joins them in pairs, so the depth falls to 6 and the same index passes 6 nodes. The leaves and their order do not change.
#include <cstdio>
#include <memory>
#include <string>
#include <utility>
// A persistent rope with shared_ptr: an insert builds new nodes on one path and
// shares everything else with the old rope.
struct Node;
using R = std::shared_ptr<const Node>;
struct Node {
std::string s;
R l, r;
std::size_t n;
};
static int made = 0;
static const R kEmpty = std::make_shared<const Node>(Node{"", nullptr, nullptr, 0});
R leaf(std::string s) {
++made;
auto n = s.size();
return std::make_shared<const Node>(Node{std::move(s), nullptr, nullptr, n});
}
R cat(R a, R b) {
if (a->n == 0) return b;
if (b->n == 0) return a;
++made;
auto n = a->n + b->n;
return std::make_shared<const Node>(Node{"", std::move(a), std::move(b), n});
}
R build(const std::string& s, std::size_t a, std::size_t b) {
if (b - a <= 16) return leaf(s.substr(a, b - a));
auto m = (a + b) / 2;
return cat(build(s, a, m), build(s, m, b));
}
std::pair<R, R> split(const R& t, std::size_t i) {
if (i == 0) return {kEmpty, t};
if (i >= t->n) return {t, kEmpty};
if (!t->l) return {leaf(t->s.substr(0, i)), leaf(t->s.substr(i))};
if (i < t->l->n) {
auto [a, b] = split(t->l, i);
return {a, cat(b, t->r)};
}
auto [a, b] = split(t->r, i - t->l->n);
return {cat(t->l, a), b};
}
R insert(const R& t, std::size_t i, std::string s) {
auto [a, b] = split(t, i);
return cat(cat(a, leaf(std::move(s))), b);
}
void text(const R& t, std::string& out) {
if (!t->l) {
out += t->s;
return;
}
text(t->l, out);
text(t->r, out);
}
int main() {
std::string big;
for (int k = 0; k < 4096; ++k) big += static_cast<char>('a' + k % 26);
R r = build(big, 0, big.size());
std::printf("%zu %d\n", r->n, made);
// The insert makes a few nodes. std::string::insert moves every byte after the position.
made = 0;
R r2 = insert(r, 2050, "XYZ");
std::string flat = big;
flat.insert(2050, "XYZ");
std::printf("%d %zu\n", made, big.size() - 2050);
std::string out;
text(r2, out);
std::printf("%zu %s %d\n", r2->n, out.substr(2047, 9).c_str(), out == flat);
}
4096 511
13 2046
4099 tuvXYZwxy 1
- Verdict: idiom. Standard C++ has no rope. The SGI
ropeclass is an extension. The rope of 4096 characters has 256 leaves and 511 nodes. An insert at position 2050 makes 13 nodes: the two halves of the cut leaf, the leaf for the new text and the join nodes on the path.std::string::insertmoves the 2046 bytes after the position.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
// A rope that implements CharSequence, so the regex engine and String methods accept it.
static final class Rope implements CharSequence {
final String s;
final Rope left, right;
final int n;
Rope(String s) {
this.s = s;
this.left = null;
this.right = null;
this.n = s.length();
}
Rope(Rope left, Rope right) {
this.s = null;
this.left = left;
this.right = right;
this.n = left.n + right.n;
}
@Override
public int length() {
return n;
}
// charAt walks from the root to a leaf, so each call costs O(depth).
@Override
public char charAt(int i) {
Rope t = this;
while (t.s == null) {
if (i < t.left.n) {
t = t.left;
} else {
i -= t.left.n;
t = t.right;
}
}
return t.s.charAt(i);
}
@Override
public CharSequence subSequence(int start, int end) {
return toString().substring(start, end);
}
void appendTo(StringBuilder sb) {
if (s != null) {
sb.append(s);
} else {
left.appendTo(sb);
right.appendTo(sb);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(n);
appendTo(sb);
return sb.toString();
}
}
public static void main(String[] args) {
Rope r = new Rope(new Rope(new Rope("The quick "), new Rope("brown fox ")), new Rope("jumps over the lazy dog"));
System.out.println(r.length() + " " + r.charAt(10));
// Pattern.matcher takes any CharSequence, so it reads the rope without a copy.
Matcher m = Pattern.compile("\\b\\w{5}\\b").matcher(r);
List<String> words = new ArrayList<>();
while (m.find()) {
words.add(m.group());
}
System.out.println(String.join(",", words));
System.out.println("The quick brown fox jumps over the lazy dog".contentEquals(r));
}
}
43 b
quick,brown,jumps
true
- Verdict: idiom. Java SE has no rope. The class implements
CharSequence, soPattern.matcherandString.contentEqualsaccept it without a conversion toString. EachcharAtcall walks from the root to a leaf, so a regex scan costs O(n log n) on a rope and O(n) on aString.
#include <stdio.h>
/* A rope node is a leaf (s is set) or a join of two ropes (l and r are set). */
typedef struct Rope {
const char *s;
const struct Rope *l, *r;
size_t n;
} Rope;
static Rope pool[64];
static int used;
static const Rope *leaf(const char *s, size_t n) {
Rope *t = &pool[used++];
*t = (Rope){s, NULL, NULL, n};
return t;
}
static const Rope *cat(const Rope *a, const Rope *b) {
Rope *t = &pool[used++];
*t = (Rope){NULL, a, b, a->n + b->n};
return t;
}
/* fetch walks from the root to the leaf that holds character i. */
static char fetch(const Rope *t, size_t i) {
while (t->s == NULL) {
if (i < t->l->n) {
t = t->l;
} else {
i -= t->l->n;
t = t->r;
}
}
return t->s[i];
}
int main(void) {
/* Join a rope with itself 20 times. Both children are the same node,
so the tree is a graph that shares pieces, and nothing is copied. */
const Rope *r = leaf("ab", 2);
for (int k = 0; k < 20; k++) r = cat(r, r);
printf("%zu %d\n", r->n, used);
printf("%c %c\n", fetch(r, 0), fetch(r, 1000001));
/* Put a prefix and a suffix around the 2 MiB rope: 4 more nodes. */
const Rope *s = cat(cat(leaf("x = ", 4), r), leaf(";", 1));
printf("%zu %d %c %c\n", s->n, used, fetch(s, 4), fetch(s, s->n - 1));
return 0;
}
2097152 21
a b
2097157 25 a ;
- Verdict: idiom. The C standard library has no rope. The C cords of the Boehm garbage collector are a library. The loop joins a rope with itself 20 times, so 21 nodes describe 2097152 characters, and
fetchpasses 20 join nodes to reach a leaf. Two more joins add a prefix and a suffix.
using System.Text;
// Build a balanced rope from a long string: cut it into leaves of at most 8 chars.
const int MaxLeaf = 8;
var s = string.Concat(Enumerable.Range(0, 100).Select(k => (char)('a' + k % 26)));
Rope r = Build(s, 0, s.Length);
Console.WriteLine($"{r.Length} {Leaves(r)} {r.Depth}");
// Report(i, j) copies only the leaves that hold characters i to j - 1.
var sb = new StringBuilder();
int visited = Report(r, 40, 50, sb);
Console.WriteLine($"{sb} {visited} {sb.ToString() == s[40..50]}");
Rope Build(string text, int a, int b) =>
b - a <= MaxLeaf ? new Leaf(text[a..b]) : new Node(Build(text, a, (a + b) / 2), Build(text, (a + b) / 2, b));
int Leaves(Rope t) => t is Node n ? Leaves(n.L) + Leaves(n.R) : 1;
int Report(Rope t, int i, int j, StringBuilder output)
{
if (j <= 0 || i >= t.Length) return 0;
if (t is Leaf leaf)
{
int a = Math.Max(i, 0), b = Math.Min(j, leaf.S.Length);
output.Append(leaf.S, a, b - a);
return 1;
}
var node = (Node)t;
return Report(node.L, i, j, output) + Report(node.R, i - node.L.Length, j - node.L.Length, output);
}
abstract record Rope(int Length, int Depth);
record Leaf(string S) : Rope(S.Length, 0);
record Node(Rope L, Rope R) : Rope(L.Length + R.Length, 1 + Math.Max(L.Depth, R.Depth));
100 16 4
opqrstuvwx 2 True
- Verdict: idiom. .NET has no rope type.
Buildcuts 100 characters into 16 leaves of at most 8 characters, in a tree of depth 4.Report(40, 50)skips every subtree outside the range and copies from only 2 leaves.
// Each edit makes a new rope and keeps the old one, so an undo history is cheap.
const leaf = (s) => ({ s, n: s.length });
const EMPTY = leaf("");
const concat = (a, b) => (a.n === 0 ? b : b.n === 0 ? a : { left: a, right: b, n: a.n + b.n });
function split(t, i) {
if (i <= 0) return [EMPTY, t];
if (i >= t.n) return [t, EMPTY];
if (t.s !== undefined) return [leaf(t.s.slice(0, i)), leaf(t.s.slice(i))];
if (i < t.left.n) {
const [a, b] = split(t.left, i);
return [a, concat(b, t.right)];
}
const [a, b] = split(t.right, i - t.left.n);
return [concat(t.left, a), b];
}
const insert = (t, i, s) => {
const [a, b] = split(t, i);
return concat(concat(a, leaf(s)), b);
};
const remove = (t, i, j) => {
const [a, rest] = split(t, i);
const [, b] = split(rest, j - i);
return concat(a, b);
};
const text = (t) => (t.s !== undefined ? t.s : text(t.left) + text(t.right));
const leafCount = (t) => (t.s !== undefined ? 1 : leafCount(t.left) + leafCount(t.right));
const history = [leaf("let x = 1;")];
const edit = (f) => history.push(f(history.at(-1)));
edit((t) => remove(t, 4, 5));
edit((t) => insert(t, 4, "total"));
edit((t) => insert(t, t.n, " // sum"));
for (const [k, v] of history.entries()) {
console.log(k, v.n, leafCount(v), JSON.stringify(text(v)));
}
// Undo is a step back in the array. No version was copied or changed.
console.log("undo:", JSON.stringify(text(history[history.length - 2])));
0 10 1 "let x = 1;"
1 9 2 "let = 1;"
2 14 3 "let total = 1;"
3 21 4 "let total = 1; // sum"
undo: "let total = 1;"
- Verdict: idiom. JavaScript has no rope type. Each edit returns a new rope and does not change the old one, so the array
historyholds every version of the text, and an undo reads the version before the last. The edits split leaves, so the last version has 4 leaves.
package main
import (
"fmt"
"strings"
)
// Each node also stores the number of newlines in its subtree, so a line lookup
// walks one path from the root.
type rope struct {
s string
l, r *rope
n int
lines int
}
func leaf(s string) *rope { return &rope{s: s, n: len(s), lines: strings.Count(s, "\n")} }
func cat(a, b *rope) *rope { return &rope{l: a, r: b, n: a.n + b.n, lines: a.lines + b.lines} }
func text(t *rope) string {
if t.l == nil {
return t.s
}
return text(t.l) + text(t.r)
}
// lineStart returns the byte offset where line k starts. Line 0 starts at 0,
// and line k starts after the k-th newline.
func lineStart(t *rope, k int) int {
if k == 0 {
return 0
}
off := 0
for t.l != nil {
if k <= t.l.lines {
t = t.l
} else {
k -= t.l.lines
off += t.l.n
t = t.r
}
}
i := 0
for ; k > 0; k-- {
i += strings.IndexByte(t.s[i:], '\n') + 1
}
return off + i
}
func main() {
t := cat(cat(leaf("one\ntwo\nthr"), leaf("ee\nfour\n")), leaf("five\nsix"))
full := text(t)
fmt.Println(t.n, t.lines)
for k := 0; k <= t.lines; k++ {
off := lineStart(t, k)
line, _, _ := strings.Cut(full[off:], "\n")
fmt.Println(k, off, line)
}
}
27 5
0 0 one
1 4 two
2 8 three
3 14 four
4 19 five
5 24 six
- Verdict: idiom. Go has no rope in its standard library. Each node stores a count of newlines, so
lineStartwalks one path from the root to find the leaf that holds the k-th newline. The offsets are in bytes, because Go strings are bytes.
use std::rc::Rc;
// A persistent rope: nodes never change, and Rc lets versions share them.
enum Rope {
Leaf(String),
Node(Rc<Rope>, Rc<Rope>, usize),
}
fn len(r: &Rope) -> usize {
match r {
Rope::Leaf(s) => s.len(),
Rope::Node(_, _, n) => *n,
}
}
fn leaf(s: &str) -> Rc<Rope> {
Rc::new(Rope::Leaf(s.to_string()))
}
fn concat(a: Rc<Rope>, b: Rc<Rope>) -> Rc<Rope> {
if len(&a) == 0 {
return b;
}
if len(&b) == 0 {
return a;
}
let n = len(&a) + len(&b);
Rc::new(Rope::Node(a, b, n))
}
// split returns the first i bytes and the rest. A leaf is cut only at a char boundary.
fn split(r: &Rc<Rope>, i: usize) -> (Rc<Rope>, Rc<Rope>) {
if i == 0 {
return (leaf(""), Rc::clone(r));
}
if i >= len(r) {
return (Rc::clone(r), leaf(""));
}
match r.as_ref() {
Rope::Leaf(s) => {
assert!(s.is_char_boundary(i));
(leaf(&s[..i]), leaf(&s[i..]))
}
Rope::Node(left, right, _) => {
let w = len(left);
if i < w {
let (a, b) = split(left, i);
(a, concat(b, Rc::clone(right)))
} else {
let (a, b) = split(right, i - w);
(concat(Rc::clone(left), a), b)
}
}
}
}
fn insert(r: &Rc<Rope>, i: usize, s: &str) -> Rc<Rope> {
let (a, b) = split(r, i);
concat(concat(a, leaf(s)), b)
}
fn text(r: &Rope, out: &mut String) {
match r {
Rope::Leaf(s) => out.push_str(s),
Rope::Node(a, b, _) => {
text(a, out);
text(b, out);
}
}
}
fn show(r: &Rope) -> String {
let mut s = String::new();
text(r, &mut s);
s
}
fn main() {
let world = leaf("world");
let hello = leaf("Hello, ");
let r = concat(Rc::clone(&hello), Rc::clone(&world));
let r2 = insert(&r, 7, "big ");
println!("{} | {}", show(&r2), show(&r));
// Each leaf has three owners: its variable, the old rope and the new rope.
println!("{} {}", Rc::strong_count(&world), Rc::strong_count(&hello));
// When the old rope is dropped, the shared leaves stay alive in the new one.
drop(r);
println!("{} {}", Rc::strong_count(&world), show(&r2));
}
Hello, big world | Hello, world
3 3
2 Hello, big world
- Verdict: idiom. The Rust standard library has no rope, and the
ropeycrate is a common choice. The nodes are behindRc, soinsertreuses the leavesHello,andworld, and each leaf has 3 owners. Afterdrop(r), the leafworldhas 2 owners and the new rope still works.splitchecksis_char_boundary, because a byte index can fall inside a UTF-8 character.
Variations and related ideas
- Gap buffer. A gap buffer is one array with an empty gap at the cursor, and it "allows efficient insertion and deletion operations clustered near the same location"1. The author of Ropey compares the two: ropes are "not amazing at anything, but they're always solidly good"7, while gap buffers "degrade poorly with unfavorable editing patterns"7. "Emacs uses gap buffers"7.
- Piece table. A piece table keeps the original file in one buffer, the added text in a second buffer, and a list of pieces that point into the two. The initial memory use "is close to the size of the document"8. VS Code uses a piece table in a balanced tree, which its author calls a "piece tree"8.
- Functions as leaves. A leaf can be a function that makes its characters when they are read. The SGI rope says that "a piece of a rope may be a 100MByte file, which is read only when that section of the string is examined"3.
- B-tree ropes. A rope does not have to be a binary tree. The Zed rope is a SumTree, a "concurrency-friendly B-tree"7 in which each node stores a summary of its subtree.
Pitfalls
- A rope for short strings. For a few kilobytes of text, a flat string is faster for nearly every operation. "Array-based strings have smaller overhead, so (for example) concatenation and split operations are faster on small datasets"1. Use a rope when the text is large and edited often.
- Character-by-character access. Each index walks the tree. A loop that calls
charAt(i)for everyicosts O(n log n). Use an iterator, which keeps its place in a leaf2. The SGI rope iterator is "slower than for vector by a significant constant factor (roughly a factor of 5 or 10 if little processing is done on each character and the string is long)"3. - No rebalance. A rope that is built only with appends and never rebalanced becomes a list, and each index is O(n).
- Splits in the middle of a character. A rope of UTF-8 bytes can split a leaf inside a multi-byte character. Index the rope by code points, as Ropey does, or check the boundary before the split, as the Rust example does.
- Single-character updates. A change of one character is a split and a concat, so "Single character replacements in a rope are expensive"3 compared with an array write.
Cost
For a balanced rope of length n: index, split, insert and delete are O(log n), and concatenation is O(1) plus a rebalance when one is needed1. Reading a range of j characters costs O(j + log n)1. A rope uses more memory than a flat string, because of the nodes, but "The overhead is always O(n), but the constant can be made arbitrarily small"1 with large leaves. In practice, the SGI documentation says that "Inserting a character in the middle of a 10 megabyte rope should take on the order of 10s of microseconds", where a flat string "would take on the order of a second"3. A copy of a rope is a pointer copy, so a snapshot for an undo step or for a background save is cheap. The xi editor uses this for autosave: "the persistent rope data structure is copy-on-write so this operation is nearly free"9.
History
The Cedar programming environment of Xerox used ropes "almost since its inception"12. The C cords of the Boehm garbage collector have a Xerox copyright from 1993 and 1994, and their header lists a compiler and a text editor with an edit history as uses in which C strings would be too slow5. In December 1995, Hans-J. Boehm, Russ Atkinson and Michael Plass described the data structure in "Ropes: an Alternative to Strings"101. The SGI STL rope class "is based loosely on the ropes in the Xerox Cedar environment or C "cords", as described in"2 that paper. In April and May 2016, Raph Levien worked out the design of the xi editor11, which uses "A persistent rope data structure"9 and is written in Rust. Zed, Helix and other new editors use ropes too7, while VS Code chose a piece tree8.
References
- Rope (data structure), Wikipedia, Description; Operations; Comparison with monolithic arrays
- Rope Implementation Overview, SGI Standard Template Library (mirror on boost.org), Introduction; Basic Algorithms and Rope Balancing
- rope<T, Alloc>, SGI Standard Template Library Programmer's Guide (mirror on boost.org), Description; Notes
- Raph Levien, Rope science, part 1, MapReduce for text, xi-editor docs, Whole post
- cord.h, the C cord package of the Boehm-Demers-Weiser garbage collector, Header comment
- Crate ropey 1.6.1, docs.rs, Crate description; Low-level APIs
- Thorsten Ball, Rope and SumTree, Zed Decoded, Zed blog (2024), Problems with strings; Ropes; Why use a rope in Zed?
- Peng Lyu, Text Buffer Reimplementation, Visual Studio Code blog (2018), Avoiding too much meta-data by using a piece table; Piece tree
- xi-editor README, Design decisions
- Hans-J. Boehm, Russ Atkinson and Michael Plass, Ropes, an Alternative to Strings, Software Practice and Experience 25(12), 1995, pages 1315 to 1330
- Raph Levien, Rope science, introduction, xi-editor docs, Whole post
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag C3HG4C Edit this page History Report an error Markdown