prosemirror 0.4.1

A Rust implementation of ProseMirror's document model and transform pipeline
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! Structure analysis utilities for document transformations.

use crate::model::{ContentMatch, Node, NodeType, ResolveErr, ResolvedPos, Schema, Slice};
use serde_json::Value;

/// A wrapper descriptor for `Transform.wrap`, matching upstream JS.
#[derive(Debug, Clone)]
/// A wrapper descriptor used by `find_wrapping`.
pub struct Wrapper<S: Schema> {
    /// The node type to wrap with.
    pub node_type: S::NodeType,
    /// The attributes for the wrapper node.
    pub attrs: Value,
}

/// Test whether a node can be cut at the given child indices.
pub fn can_cut<S: Schema>(node: &S::Node, start: usize, end: usize) -> bool {
    if start == 0
        || node
            .can_replace(start, node.child_count(), None, ..)
            .unwrap_or(false)
    {
        end == node.child_count() || node.can_replace(0, end, None, ..).unwrap_or(false)
    } else {
        false
    }
}

/// Find the depth to which the given range can be lifted, if any.
pub fn lift_target<S: Schema>(range: &NodeRange<S>) -> Option<usize> {
    let parent = range.parent();
    let content = parent
        .content()
        .map(|c| c.cut_by_index(range.start_index(), range.end_index()))
        .unwrap_or_default();
    let mut depth = range.depth;
    let mut content_before: usize = 0;
    let mut content_after: usize = 0;
    loop {
        let node = range.from.node(depth);
        let index = range.from.index(depth) + content_before;
        let end_index = range.to.index_after(depth).saturating_sub(content_after);
        if depth < range.depth
            && node
                .can_replace(index, end_index, Some(&content), ..)
                .unwrap_or(false)
        {
            return Some(depth);
        }
        if depth == 0 || !can_cut::<S>(node, index, end_index) {
            break;
        }
        if index > 0 {
            content_before = 1;
        }
        if end_index < node.child_count() {
            content_after = 1;
        }
        depth -= 1;
    }
    None
}

/// Find the wrapping node types needed to make `node_type` valid at the given range.
pub fn find_wrapping<S: Schema>(
    range: &NodeRange<S>,
    node_type: S::NodeType,
    _attrs_check: impl Fn(&S::NodeType) -> bool,
) -> Option<Vec<Wrapper<S>>> {
    let around = find_wrapping_outside(range, node_type)?;
    let inner = find_wrapping_inside(range, node_type)?;

    let mut result = around;
    result.push(Wrapper {
        node_type,
        attrs: Value::Null,
    });
    result.extend(inner);
    // Check that the first around type can be inserted
    if result.is_empty() {
        return Some(result);
    }
    Some(result)
}

/// Find wrapping types outside the range
pub fn find_wrapping_outside<S: Schema>(
    range: &NodeRange<S>,
    node_type: S::NodeType,
) -> Option<Vec<Wrapper<S>>> {
    let parent = range.parent();
    let start_index = range.start_index();
    let end_index = range.end_index();
    let around = parent
        .content_match_at(start_index)
        .ok()?
        .find_wrapping(node_type)?;
    let outer = if around.is_empty() {
        node_type
    } else {
        around[0]
    };
    if parent.can_replace_with(start_index, end_index, outer) {
        Some(
            around
                .into_iter()
                .map(|t| Wrapper {
                    node_type: t,
                    attrs: Value::Null,
                })
                .collect(),
        )
    } else {
        None
    }
}

/// Find wrapping types inside the range
pub fn find_wrapping_inside<S: Schema>(
    range: &NodeRange<S>,
    node_type: S::NodeType,
) -> Option<Vec<Wrapper<S>>> {
    let parent = range.parent();
    let start_index = range.start_index();
    let end_index = range.end_index();
    let inner = parent.child(start_index)?;
    let inside = node_type.content_match().find_wrapping(inner.r#type())?;
    let last_type = if inside.is_empty() {
        node_type
    } else {
        inside[inside.len() - 1]
    };
    let mut inner_match = Some(last_type.content_match());
    let mut i = start_index;
    while let Some(m) = inner_match {
        if i >= end_index {
            break;
        }
        inner_match = m.match_type(parent.child(i)?.r#type());
        i += 1;
    }
    match inner_match {
        Some(m) if m.valid_end() => Some(
            inside
                .into_iter()
                .map(|t| Wrapper {
                    node_type: t,
                    attrs: Value::Null,
                })
                .collect(),
        ),
        _ => None,
    }
}

/// Check if the given node type can be changed at the given position.
pub fn can_change_type<S: Schema>(doc: &S::Node, pos: usize, node_type: S::NodeType) -> bool {
    if let Ok(pos_) = doc.resolve(pos) {
        let index = pos_.index(pos_.depth);
        pos_.parent().can_replace_with(index, index + 1, node_type)
    } else {
        false
    }
}

/// Check whether the document can be split at the given position.
pub fn can_split<S: Schema>(
    doc: &S::Node,
    pos: usize,
    depth: Option<usize>,
    types_after: Option<&[S::NodeType]>,
) -> bool {
    let depth = depth.unwrap_or(1);
    let pos_ = match doc.resolve(pos) {
        Ok(p) => p,
        Err(_) => return false,
    };
    let base = pos_.depth as isize - depth as isize;
    if base < 0 {
        return false;
    }
    let base = base as usize;

    let inner_type = types_after
        .and_then(|t| t.last().copied())
        .unwrap_or_else(|| pos_.parent().r#type());

    if !pos_
        .parent()
        .can_replace(
            pos_.index(pos_.depth),
            pos_.parent().child_count(),
            None,
            ..,
        )
        .unwrap_or(false)
    {
        return false;
    }
    if let Some(content) = pos_.parent().content() {
        if !inner_type
            .valid_content(&content.cut_by_index(pos_.index(pos_.depth), content.child_count()))
        {
            return false;
        }
    }

    let mut d = pos_.depth - 1;
    let mut i = depth as isize - 2;
    while d > base {
        let node = pos_.node(d);
        let index = pos_.index(d);
        if let Some(content) = node.content() {
            let rest = content.cut_by_index(index, content.child_count());

            let rest_to_check = rest;
            if let Some(types) = types_after {
                if (i + 1) >= 0 && ((i + 1) as usize) < types.len() {
                    let override_child_type = types[(i + 1) as usize];
                    // Create a node of the override type and replace the first child
                    // This is a simplified check
                    let _ = override_child_type;
                }
            }

            let after_type = types_after
                .and_then(|t| {
                    if i >= 0 && (i as usize) < t.len() {
                        Some(t[i as usize])
                    } else {
                        None
                    }
                })
                .unwrap_or_else(|| node.r#type());

            if !node
                .can_replace(index + 1, node.child_count(), None, ..)
                .unwrap_or(false)
                || !after_type.valid_content(&rest_to_check)
            {
                return false;
            }
        }
        d -= 1;
        i -= 1;
    }

    let index = pos_.index_after(base);
    let base_type = types_after.and_then(|t| t.first().copied());
    pos_.node(base).can_replace_with(
        index,
        index,
        base_type.unwrap_or_else(|| pos_.node(base + 1).r#type()),
    )
}

/// Check whether the document can be joined at the given position.
pub fn can_join<S: Schema>(doc: &S::Node, pos: usize) -> Option<bool> {
    let pos_ = doc.resolve(pos).ok()?;
    let index = pos_.index(pos_.depth);
    if joinable::<S>(pos_.node_before().as_deref(), pos_.node_after().as_deref()) {
        pos_.parent().can_replace(index, index + 1, None, ..).ok()
    } else {
        None
    }
}

/// Find a join point near the given position.
pub fn join_point<S: Schema>(doc: &S::Node, pos: usize, dir: Option<i32>) -> Option<usize> {
    let dir = dir.unwrap_or(-1);
    let pos_ = doc.resolve(pos).ok()?;
    let mut pos = pos;
    for d in (0..=pos_.depth).rev() {
        let (before, after, index) = if d == pos_.depth {
            (pos_.node_before(), pos_.node_after(), pos_.index(d))
        } else if dir > 0 {
            let idx = pos_.index(d) + 1;
            (
                Some(std::borrow::Cow::Borrowed(pos_.node(d + 1))),
                pos_.node(d)
                    .maybe_child(idx)
                    .map(std::borrow::Cow::Borrowed),
                idx,
            )
        } else {
            let idx = pos_.index(d);
            (
                if idx > 0 {
                    pos_.node(d)
                        .maybe_child(idx - 1)
                        .map(std::borrow::Cow::Borrowed)
                } else {
                    None
                },
                Some(std::borrow::Cow::Borrowed(pos_.node(d + 1))),
                idx,
            )
        };
        if let (Some(b), Some(a)) = (&before, &after) {
            if !b.r#type().is_textblock()
                && joinable::<S>(Some(b), Some(a))
                && pos_
                    .node(d)
                    .can_replace(index, index + 1, None, ..)
                    .unwrap_or(false)
            {
                return Some(pos);
            }
        }
        if d == 0 {
            break;
        }
        pos = if dir < 0 {
            pos_.before(d).unwrap_or(pos)
        } else {
            pos_.after(d).unwrap_or(pos)
        };
    }
    None
}

/// Find a valid insertion point for the given node type.
pub fn insert_point<S: Schema>(doc: &S::Node, pos: usize, node_type: S::NodeType) -> Option<usize> {
    let pos_ = doc.resolve(pos).ok()?;
    if pos_
        .parent()
        .can_replace_with(pos_.index(pos_.depth), pos_.index(pos_.depth), node_type)
    {
        return Some(pos);
    }
    if pos_.parent_offset == 0 {
        for d in (0..pos_.depth).rev() {
            let index = pos_.index(d);
            if pos_.node(d).can_replace_with(index, index, node_type) {
                return pos_.before(d + 1);
            }
            if index > 0 {
                return None;
            }
        }
    }
    if pos_.parent_offset == pos_.parent().content().map(|c| c.size()).unwrap_or(0) {
        for d in (0..pos_.depth).rev() {
            let index = pos_.index_after(d);
            if pos_.node(d).can_replace_with(index, index, node_type) {
                return pos_.after(d + 1);
            }
            if index < pos_.node(d).child_count() {
                return None;
            }
        }
    }
    None
}

/// Find a valid drop point for the given slice.
pub fn drop_point<S: Schema>(doc: &S::Node, pos: usize, slice: &Slice<S>) -> Option<usize> {
    if slice.content.size() == 0 {
        return Some(pos);
    }
    let pos_ = doc.resolve(pos).ok()?;
    let mut content = &slice.content;
    for _ in 0..slice.open_start {
        content = content.first_child()?.content()?;
    }
    let max_pass = if slice.open_start == 0 && slice.size() > 0 {
        2
    } else {
        1
    };
    for pass in 1..=max_pass {
        for d in (1..=pos_.depth).rev() {
            let bias = if d == pos_.depth {
                0
            } else if pos_.pos as f64 <= (pos_.start(d + 1) as f64 + pos_.end(d + 1) as f64) / 2.0 {
                -1
            } else {
                1
            };
            let insert_pos = pos_.index(d) + if bias > 0 { 1 } else { 0 };
            let parent = pos_.node(d);
            let fits = if pass == 1 {
                parent
                    .can_replace(insert_pos, insert_pos, Some(content), ..)
                    .unwrap_or(false)
            } else {
                match content.first_child() {
                    Some(first) => {
                        let wrapping = parent
                            .content_match_at(insert_pos)
                            .ok()
                            .and_then(|m| m.find_wrapping(first.r#type()));
                        wrapping.is_some()
                            && parent.can_replace_with(insert_pos, insert_pos, wrapping.unwrap()[0])
                    }
                    None => false,
                }
            };
            if fits {
                return Some(if bias == 0 {
                    pos_.pos
                } else if bias < 0 {
                    pos_.before(d + 1)?
                } else {
                    pos_.after(d + 1)?
                });
            }
        }
    }
    None
}

/// Check if two nodes are joinable (compatible content)
pub fn joinable<S: Schema>(a: Option<&S::Node>, b: Option<&S::Node>) -> bool {
    match (a, b) {
        (Some(a), Some(b)) => !a.is_leaf() && a.r#type().compatible_content(b.r#type()),
        _ => false,
    }
}

/// A range between two resolved positions at a given depth.
pub struct NodeRange<'a, S: Schema> {
    /// The start of the range
    pub from: ResolvedPos<'a, S>,
    /// The end of the range
    pub to: ResolvedPos<'a, S>,
    /// The depth at which the range is defined
    pub depth: usize,
}

impl<'a, S: Schema> NodeRange<'a, S> {
    /// Create a new NodeRange
    pub fn new(from: ResolvedPos<'a, S>, to: ResolvedPos<'a, S>, depth: usize) -> Self {
        NodeRange { from, to, depth }
    }

    /// Resolve two positions in a document and build a `NodeRange`.
    ///
    /// This is a convenience wrapper around `ResolvedPos::resolve` +
    /// `shared_depth` that is used by both language bindings.
    pub fn resolve(doc: &'a S::Node, from: usize, to: usize) -> Result<Self, ResolveErr> {
        let from_rp = ResolvedPos::resolve(doc, from)?;
        let depth = from_rp.shared_depth(to);
        let to_rp = ResolvedPos::resolve(doc, to)?;
        Ok(NodeRange::new(from_rp, to_rp, depth))
    }

    /// The start position of the range
    pub fn start(&self) -> usize {
        self.from.before(self.depth + 1).unwrap_or(0)
    }

    /// The end position of the range
    pub fn end(&self) -> usize {
        self.to.after(self.depth + 1).unwrap_or(0)
    }

    /// The parent node containing the range
    pub fn parent(&self) -> &'a S::Node {
        self.from.node(self.depth)
    }

    /// The start child index within the parent
    pub fn start_index(&self) -> usize {
        self.from.index(self.depth)
    }

    /// The end child index within the parent
    pub fn end_index(&self) -> usize {
        self.to.index_after(self.depth)
    }
}