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
use gpui::{
App, InteractiveElement as _, IntoElement, ListState, ParentElement as _, SharedString,
Styled as _, Window, div,
};
use std::{ops::RangeInclusive, sync::Arc};
use crate::text::{
SelectionFormat,
node::{BlockNode, NodeContext},
};
/// The parsed document AST.
#[derive(Debug, Clone, PartialEq, Default)]
pub(crate) struct ParsedDocument {
pub(crate) source: SharedString,
pub(crate) blocks: Arc<Vec<BlockNode>>,
}
#[derive(Default, Clone, Copy)]
pub(crate) struct NodeRenderOptions {
pub(crate) ix: usize,
pub(crate) in_list: bool,
pub(crate) todo: bool,
pub(crate) ordered: bool,
pub(crate) depth: usize,
pub(crate) is_last: bool,
}
impl NodeRenderOptions {
pub(crate) fn is_last(mut self, is_last: bool) -> Self {
self.is_last = is_last;
self
}
}
impl ParsedDocument {
pub(super) fn text(&self) -> String {
let mut text = String::new();
for block in self.blocks.iter() {
text.push_str(&block.text());
}
text
}
/// The selected text across all blocks, in `format`.
///
/// In [`SelectionFormat::Source`] each block reconstructs its own Markdown
/// source (inline markup, and block prefixes for headings and lists), and
/// top-level blocks are joined with a blank line so the result re-renders
/// with the same block structure.
///
/// A block only learns its selection when it is painted, so in a scrollable
/// (virtualized) view every block the user scrolled past reports nothing.
/// The selection is one continuous range, so blocks it spans that came up
/// empty are inside it and are emitted whole rather than dropped. `blocks`
/// bounds that span; it comes from the selection endpoints, which hold on to
/// their block index even after it scrolls out of view (the painted blocks
/// alone cannot bound the span, because the press that starts a drag leaves
/// an empty selection that never reaches paint). Without it, fall back to
/// the painted blocks. (Source mode is only used by non-scrollable views,
/// where `blocks` is `None` and every block paints.)
///
/// A standalone image (a paragraph that is only an image) has no selectable
/// text run, so it never carries a selection of its own. It is therefore
/// included when it is *enclosed* by the selection — some block before and
/// some block after it are selected — mirroring how an inline image is
/// emitted when the selection runs into it. (Select-all returns the source
/// verbatim, so a leading or trailing image is still copied there.)
pub(super) fn selected_text(
&self,
format: SelectionFormat,
blocks: Option<RangeInclusive<usize>>,
) -> String {
let requested_blocks = blocks.clone();
let painted = self
.blocks
.iter()
.map(|block| block.has_selection())
.collect::<Vec<_>>();
let (Some(painted_first), Some(painted_last)) = (
painted.iter().position(|painted| *painted),
painted.iter().rposition(|painted| *painted),
) else {
return String::new();
};
let last_ix = self.blocks.len().saturating_sub(1);
let (first, last) = match blocks {
Some(blocks) => (*blocks.start().min(&last_ix), *blocks.end().min(&last_ix)),
None => (painted_first, painted_last),
};
if format == SelectionFormat::Plain {
let mut text = String::new();
for (ix, block) in self.blocks.iter().enumerate().take(last + 1).skip(first) {
let selected = block.selected_text(format);
let is_virtual_endpoint = requested_blocks
.as_ref()
.is_some_and(|blocks| ix == *blocks.start() || ix == *blocks.end());
if requested_blocks.is_some() && !is_virtual_endpoint {
text.push_str(&block.text());
} else if !selected.is_empty() {
text.push_str(&selected);
} else if !painted[ix] {
// Never painted, so it cannot report a selection of its own
// even though the span covers it. A painted block that came
// up empty really has nothing selected, and stays empty.
text.push_str(&block.text());
}
}
return text;
}
let mut out: Vec<String> = Vec::new();
for (ix, block) in self.blocks.iter().enumerate().take(last + 1).skip(first) {
// The selection is one continuous range, so only the block it
// starts in and the block it ends in can be partly selected.
// Everything between them is covered whole, and so is any block
// that reports nothing — it either scrolled past without painting,
// or renders no selectable text run at all (a rule, a break, a
// custom node, a standalone image).
let source = if (ix == first || ix == last) && painted[ix] {
block.selected_text(format)
} else {
self.whole_source(block)
};
let trimmed = source.trim_end_matches('\n');
if !trimmed.is_empty() {
out.push(trimmed.to_string());
}
}
out.join("\n\n")
}
/// The whole source of a block the selection covers.
///
/// Copied straight out of the original text, which the Markdown parser
/// locates per block. That keeps whatever the author wrote — `_italic_`
/// stays `_italic_`, a reference link keeps its `[ref]` form, a table keeps
/// its column padding — and it needs no rule of its own per block type.
/// Blocks the parser could not locate fall back to reconstruction.
fn whole_source(&self, block: &BlockNode) -> String {
if let Some(span) = block.span()
&& let Some(source) = self.source.get(span.start..span.end)
{
return source.to_string();
}
block.selected_text(SelectionFormat::Source)
}
/// Synchronously clear the selection stored in every inline state.
///
/// This mirrors the [`selected_text`](Self::selected_text) traversal so the
/// stored selection can be cleared without relying on a repaint. Offscreen
/// (virtualized) views do not repaint, so their `InlineState.selection`
/// would otherwise retain stale values from the last painted frame.
pub(super) fn clear_selection(&self) {
for block in self.blocks.iter() {
block.clear_selection();
}
}
/// Converts the node to markdown format.
///
/// This is used to generate markdown for test.
#[allow(dead_code)]
pub(crate) fn to_markdown(&self) -> String {
self.blocks
.iter()
.map(|child| child.to_markdown())
.collect::<Vec<_>>()
.join("\n\n")
}
pub(super) fn render_root(
&self,
list_state: Option<ListState>,
node_cx: &NodeContext,
window: &mut Window,
cx: &mut App,
) -> impl IntoElement {
let Some(list_state) = list_state else {
let blocks_len = self.blocks.len();
return div()
.id("document")
.children(self.blocks.iter().enumerate().map(move |(ix, node)| {
let is_last = ix + 1 == blocks_len;
node.render_block(
NodeRenderOptions {
ix,
is_last,
..Default::default()
},
node_cx,
window,
cx,
)
}));
};
let options = NodeRenderOptions {
is_last: true,
..Default::default()
};
let blocks = &self.blocks;
if list_state.item_count() != blocks.len() {
list_state.reset(blocks.len());
}
div().id("document").size_full().child(
gpui::list(list_state, {
let node_cx = node_cx.clone();
let blocks = blocks.clone();
move |ix, window, cx| {
let is_last = ix + 1 == blocks.len();
blocks[ix]
.render_block(
NodeRenderOptions {
ix,
is_last,
..options
},
&node_cx,
window,
cx,
)
.into_any_element()
}
})
.size_full(),
)
}
}