use super::code_highlight_node::is_code_highlight_node;
use super::code_node::is_code_node;
use super::flat_structure_utils::{
get_code_line_direction, get_end_of_code_in_line, get_first_code_node_of_line,
get_last_code_node_of_line, get_start_of_code_in_line, outdent_leading_spaces,
};
use crate::caret::{CaretDirection, get_caret_range, get_sibling_caret, get_text_point_caret};
use crate::caret_utils::{
get_caret_range_in_direction, normalize_caret, set_selection_from_caret_range,
};
use crate::commands::{
INDENT_CONTENT_COMMAND, INSERT_TAB_COMMAND, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_LEFT_COMMAND,
KEY_ARROW_RIGHT_COMMAND, KEY_ARROW_UP_COMMAND, KEY_TAB_COMMAND, MOVE_TO_END, MOVE_TO_START,
OUTDENT_CONTENT_COMMAND,
};
use crate::editor::COMMAND_PRIORITY_LOW;
use crate::editor::LexicalCommand;
use crate::error::invariant;
use crate::events::KeyboardEvent;
use crate::lexical_selection::{Point, PointType, SelectionRef, Which, get_selection};
use crate::node::NodeRef;
use crate::nodes::element::Direction;
use crate::nodes::line_break::{LineBreakNode, create_line_break_node};
use crate::nodes::tab::{TabNode, create_tab_node};
use crate::selection_insert_nodes::insert_nodes;
use crate::utils::{on_escape_down, on_escape_up};
use crate::{Editor, LexicalError, Unregister};
fn is_tab_node(node: &NodeRef) -> bool {
node.get_latest().is::<TabNode>()
}
fn is_line_break_node(node: &NodeRef) -> bool {
node.get_latest().is::<LineBreakNode>()
}
fn is_selection_in_code(selection: Option<&SelectionRef>) -> Result<bool, LexicalError> {
let Some(range) = selection.and_then(SelectionRef::range) else {
return Ok(false);
};
let code_of = |point: &Point| -> Result<Option<NodeRef>, LexicalError> {
let node = point.get_node()?;
Ok(if is_code_node(&node) {
Some(node)
} else {
node.get_parent()
})
};
let maybe_anchor_code_node = code_of(&range.anchor)?;
let maybe_focus_code_node = code_of(&range.focus)?;
Ok(maybe_anchor_code_node
.as_ref()
.is_some_and(|a| is_code_node(a) && maybe_focus_code_node.as_ref() == Some(a)))
}
fn get_code_lines(selection: &SelectionRef) -> Result<Vec<Vec<NodeRef>>, LexicalError> {
let nodes = selection.get_nodes()?;
let mut lines = Vec::new();
if nodes.len() == 1 && is_code_node(&nodes[0]) {
return Ok(lines);
}
let mut last_line = Vec::new();
for node in nodes {
invariant!(
is_code_highlight_node(&node) || is_tab_node(&node) || is_line_break_node(&node),
"Expected selection to be inside CodeBlock and consisting of CodeHighlightNode, TabNode and LineBreakNode"
);
if is_line_break_node(&node) {
if !last_line.is_empty() {
lines.push(std::mem::take(&mut last_line));
}
} else {
last_line.push(node);
}
}
if let Some(first) = last_line.first() {
let selection_end = selection
.point(if selection.is_backward()? {
Which::Anchor
} else {
Which::Focus
})
.expect("a range selection");
let last_point = Point::new(first.get_key(), 0, PointType::Text);
if selection_end != last_point {
lines.push(last_line);
}
}
Ok(lines)
}
fn outdent_line_at_caret(
selection: &SelectionRef,
tab_size: Option<usize>,
) -> Result<(), LexicalError> {
let anchor_node = selection
.point(Which::Anchor)
.expect("a range selection")
.get_node()?;
if !is_code_highlight_node(&anchor_node) && !is_tab_node(&anchor_node) {
return Ok(());
}
let first_of_line = get_first_code_node_of_line(&anchor_node);
if is_tab_node(&first_of_line) {
first_of_line.remove(false)?;
} else if let Some(tab_size) = tab_size
&& is_code_highlight_node(&first_of_line)
{
outdent_leading_spaces(&first_of_line, tab_size, selection)?;
}
Ok(())
}
fn handle_multiline_indent(indent: bool, tab_size: Option<usize>) -> Result<bool, LexicalError> {
let Some(selection) = get_selection().filter(SelectionRef::is_range) else {
return Ok(false);
};
if !is_selection_in_code(Some(&selection))? {
return Ok(false);
}
let code_lines = get_code_lines(&selection)?;
let code_lines_length = code_lines.len();
let is_collapsed = selection.range().expect("a range selection").is_collapsed();
if code_lines_length == 0 && is_collapsed {
if indent {
selection.insert_nodes(vec![create_tab_node()])?;
} else {
outdent_line_at_caret(&selection, tab_size)?;
}
return Ok(true);
}
if code_lines_length == 0 && indent && selection.get_text_content()? == "\n" {
let tab_node = create_tab_node();
let line_break_node = create_line_break_node();
let direction = if selection.is_backward()? {
CaretDirection::Previous
} else {
CaretDirection::Next
};
selection.insert_nodes(vec![tab_node.clone(), line_break_node.clone()])?;
set_selection_from_caret_range(&get_caret_range_in_direction(
&get_caret_range(
get_text_point_caret(&tab_node, CaretDirection::Next, 0)?,
normalize_caret(&get_sibling_caret(&line_break_node, CaretDirection::Next)),
)?,
direction,
)?)?;
return Ok(true);
}
for (i, line) in code_lines.iter().enumerate() {
let Some(first) = line.first() else {
continue;
};
let first_of_line = if i == 0 {
get_first_code_node_of_line(first)
} else {
first.clone()
};
if indent {
let tab_node = create_tab_node();
first_of_line.insert_before(&tab_node, true)?;
if i == 0 {
let anchor_key = if selection.is_backward()? {
Which::Focus
} else {
Which::Anchor
};
let anchor_line = Point::new(first_of_line.get_key(), 0, PointType::Text);
if selection.point(anchor_key).as_ref() == Some(&anchor_line) {
selection.point_set(anchor_key, tab_node.get_key(), 0, PointType::Text)?;
}
}
} else if is_tab_node(&first_of_line) {
first_of_line.remove(false)?;
} else if let Some(tab_size) = tab_size
&& is_code_highlight_node(&first_of_line)
{
outdent_leading_spaces(&first_of_line, tab_size, &selection)?;
}
}
Ok(true)
}
fn handle_tab(shift_key: bool) -> Result<Option<LexicalCommand<()>>, LexicalError> {
let Some(selection) = get_selection().filter(SelectionRef::is_range) else {
return Ok(None);
};
if !is_selection_in_code(Some(&selection))? {
return Ok(None);
}
let indent_or_outdent = if shift_key {
OUTDENT_CONTENT_COMMAND
} else {
INDENT_CONTENT_COMMAND
};
let tab_or_outdent = if shift_key {
OUTDENT_CONTENT_COMMAND
} else {
INSERT_TAB_COMMAND
};
let range = selection.range().expect("a range selection");
let (anchor, focus) = (&range.anchor, &range.focus);
if anchor == focus {
return Ok(Some(tab_or_outdent));
}
let code_lines = get_code_lines(&selection)?;
if code_lines.len() != 1 {
return Ok(Some(indent_or_outdent));
}
let code_line = &code_lines[0];
invariant!(
!code_line.is_empty(),
"$getCodeLines only extracts non-empty lines"
);
let (selection_first, selection_last) = if selection.is_backward()? {
(focus, anchor)
} else {
(anchor, focus)
};
let first_of_line = get_first_code_node_of_line(&code_line[0]);
let last_of_line = get_last_code_node_of_line(&code_line[0]);
let anchor_of_line = Point::new(first_of_line.get_key(), 0, PointType::Text);
let focus_of_line = Point::new(
last_of_line.get_key(),
last_of_line.get_text_content_size(),
PointType::Text,
);
if selection_first.is_before(&anchor_of_line)? {
return Ok(Some(indent_or_outdent));
}
if focus_of_line.is_before(selection_last)? {
return Ok(Some(indent_or_outdent));
}
if anchor_of_line.is_before(selection_first)? || selection_last.is_before(&focus_of_line)? {
return Ok(Some(tab_or_outdent));
}
Ok(Some(indent_or_outdent))
}
fn is_code_line_node(node: &NodeRef) -> bool {
is_code_highlight_node(node) || is_tab_node(node)
}
fn handle_shift_lines(arrow_is_up: bool, event: &KeyboardEvent) -> Result<bool, LexicalError> {
let Some(selection) = get_selection().filter(SelectionRef::is_range) else {
return Ok(false);
};
let range = selection.range().expect("a range selection");
let (anchor_offset, focus_offset) = (range.anchor.offset, range.focus.offset);
let anchor_node = range.anchor.get_node()?;
let focus_node = range.focus.get_node()?;
if !is_selection_in_code(Some(&selection))?
|| !is_code_line_node(&anchor_node)
|| !is_code_line_node(&focus_node)
{
return Ok(false);
}
if !event.alt_key {
if range.is_collapsed() {
let code_node = anchor_node.get_parent_or_throw()?;
if arrow_is_up && anchor_offset == 0 && anchor_node.get_previous_sibling().is_none() {
if code_node.get_previous_sibling().is_none() {
code_node.select_previous(None, None)?;
event.prevent_default();
return Ok(false);
}
} else if !arrow_is_up
&& anchor_offset == anchor_node.get_text_content_size()
&& anchor_node.get_next_sibling().is_none()
&& code_node.get_next_sibling().is_none()
{
code_node.select_next(None, None)?;
event.prevent_default();
return Ok(false);
}
}
return Ok(false);
}
let (start, end) = if anchor_node.is_before(&focus_node) {
(
get_first_code_node_of_line(&anchor_node),
get_last_code_node_of_line(&focus_node),
)
} else {
(
get_first_code_node_of_line(&focus_node),
get_last_code_node_of_line(&anchor_node),
)
};
let range_nodes = start.get_nodes_between(&end);
if range_nodes
.iter()
.any(|node| !is_code_line_node(node) && !is_line_break_node(node))
{
return Ok(false);
}
event.prevent_default();
event.stop_propagation();
let linebreak = if arrow_is_up {
start.get_previous_sibling()
} else {
end.get_next_sibling()
};
let Some(linebreak) = linebreak.filter(is_line_break_node) else {
return Ok(true);
};
let sibling = if arrow_is_up {
linebreak.get_previous_sibling()
} else {
linebreak.get_next_sibling()
};
let Some(sibling) = sibling else {
return Ok(true);
};
let adjacent_line_is_blank = is_line_break_node(&sibling);
let mut insertion_point = if !adjacent_line_is_blank && is_code_line_node(&sibling) {
if arrow_is_up {
get_first_code_node_of_line(&sibling)
} else {
get_last_code_node_of_line(&sibling)
}
} else {
sibling
};
linebreak.remove(false)?;
for node in &range_nodes {
node.remove(false)?;
}
if adjacent_line_is_blank {
for node in &range_nodes {
insertion_point.insert_after(node, true)?;
insertion_point = node.clone();
}
insertion_point.insert_after(&linebreak, true)?;
} else if arrow_is_up {
for node in &range_nodes {
insertion_point.insert_before(node, true)?;
}
insertion_point.insert_before(&linebreak, true)?;
} else {
insertion_point.insert_after(&linebreak, true)?;
insertion_point = linebreak;
for node in &range_nodes {
insertion_point.insert_after(node, true)?;
insertion_point = node.clone();
}
}
selection.set_text_node_range(&anchor_node, anchor_offset, &focus_node, focus_offset)?;
Ok(true)
}
fn handle_move_to(is_move_to_start: bool, event: &KeyboardEvent) -> Result<bool, LexicalError> {
let Some(selection) = get_selection().filter(SelectionRef::is_range) else {
return Ok(false);
};
let range = selection.range().expect("a range selection");
let (anchor, focus) = (&range.anchor, &range.focus);
let anchor_node = anchor.get_node()?;
let focus_node = focus.get_node()?;
if !is_selection_in_code(Some(&selection))?
|| !is_code_line_node(&anchor_node)
|| !is_code_line_node(&focus_node)
{
return Ok(false);
}
let focus_line_node = focus_node;
let direction = get_code_line_direction(&focus_line_node);
let move_to_start = if direction == Some(Direction::Rtl) {
!is_move_to_start
} else {
is_move_to_start
};
let original_anchor = anchor.clone();
if move_to_start {
match get_start_of_code_in_line(&focus_line_node, focus.offset)? {
Some(start) => {
if is_line_break_node(&start.node) {
start.node.select_next(Some(0), Some(0))?;
} else {
selection.set_text_node_range(
&start.node,
start.offset,
&start.node,
start.offset,
)?;
}
}
None => {
focus_line_node.get_parent_or_throw()?.select_start()?;
}
}
} else {
get_end_of_code_in_line(&focus_line_node)?.select(None, None)?;
}
if event.shift_key {
selection.point_set(
Which::Anchor,
&original_anchor.key,
original_anchor.offset,
original_anchor.point_type,
)?;
}
event.prevent_default();
event.stop_propagation();
Ok(true)
}
pub fn register_code_indentation(
editor: &Editor,
tab_size: Option<usize>,
escape_with_arrows: bool,
) -> Unregister {
let mut unregisters = Vec::new();
if escape_with_arrows {
unregisters.extend([
editor.register_command(
&KEY_ARROW_DOWN_COMMAND,
|event, _| {
if event.alt_key {
return Ok(false);
}
on_escape_down(is_code_node, Some(event))
},
COMMAND_PRIORITY_LOW,
),
editor.register_command(
&KEY_ARROW_RIGHT_COMMAND,
|event, _| on_escape_down(is_code_node, Some(event)),
COMMAND_PRIORITY_LOW,
),
editor.register_command(
&KEY_ARROW_UP_COMMAND,
|event, _| {
if event.alt_key {
return Ok(false);
}
on_escape_up(is_code_node, Some(event))
},
COMMAND_PRIORITY_LOW,
),
editor.register_command(
&KEY_ARROW_LEFT_COMMAND,
|event, _| on_escape_up(is_code_node, Some(event)),
COMMAND_PRIORITY_LOW,
),
]);
}
unregisters.extend([
editor.register_command(
&KEY_TAB_COMMAND,
|event, editor| {
let Some(command) = handle_tab(event.shift_key)? else {
return Ok(false);
};
event.prevent_default();
editor.dispatch_command(&command, ())?;
Ok(true)
},
COMMAND_PRIORITY_LOW,
),
editor.register_command(
&INSERT_TAB_COMMAND,
|_, _| {
let selection = get_selection();
if !is_selection_in_code(selection.as_ref())? {
return Ok(false);
}
insert_nodes(vec![create_tab_node()])?;
Ok(true)
},
COMMAND_PRIORITY_LOW,
),
editor.register_command(
&INDENT_CONTENT_COMMAND,
|_, _| handle_multiline_indent(true, None),
COMMAND_PRIORITY_LOW,
),
editor.register_command(
&OUTDENT_CONTENT_COMMAND,
move |_, _| handle_multiline_indent(false, tab_size),
COMMAND_PRIORITY_LOW,
),
editor.register_command(
&KEY_ARROW_UP_COMMAND,
|event, _| {
let Some(selection) = get_selection().filter(SelectionRef::is_range) else {
return Ok(false);
};
let range = selection.range().expect("a range selection");
let anchor_node = range.anchor.get_node()?;
if !is_selection_in_code(Some(&selection))? {
return Ok(false);
}
let parent = anchor_node.get_parent();
if range.is_collapsed()
&& range.anchor.offset == 0
&& anchor_node.get_previous_sibling().is_none()
&& parent
.as_ref()
.is_some_and(|p| is_code_node(p) && p.get_previous_sibling().is_none())
{
event.prevent_default();
return Ok(true);
}
handle_shift_lines(true, event)
},
COMMAND_PRIORITY_LOW,
),
editor.register_command(
&KEY_ARROW_DOWN_COMMAND,
|event, _| {
let Some(selection) = get_selection().filter(SelectionRef::is_range) else {
return Ok(false);
};
let range = selection.range().expect("a range selection");
let anchor_node = range.anchor.get_node()?;
if !is_selection_in_code(Some(&selection))? {
return Ok(false);
}
if range.is_collapsed()
&& range.anchor.offset == anchor_node.get_text_content_size()
&& anchor_node.get_next_sibling().is_none()
{
let parent = anchor_node.get_parent_or_throw()?;
if is_code_node(&parent) && parent.get_next_sibling().is_none() {
event.prevent_default();
return Ok(true);
}
}
handle_shift_lines(false, event)
},
COMMAND_PRIORITY_LOW,
),
editor.register_command(
&MOVE_TO_START,
|event, _| handle_move_to(true, event),
COMMAND_PRIORITY_LOW,
),
editor.register_command(
&MOVE_TO_END,
|event, _| handle_move_to(false, event),
COMMAND_PRIORITY_LOW,
),
]);
super::merge(unregisters)
}