Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 91 additions & 41 deletions crates/ty_ide/src/folding_range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ use ruff_python_ast::visitor::source_order::{
SourceOrderVisitor, TraversalSignal, walk_body, walk_node,
};
use ruff_python_ast::{AnyNodeRef, Stmt, StmtClassDef, StmtFunctionDef};
use ruff_source_file::{Line, UniversalNewlines};
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use ruff_python_trivia::CommentLinePosition;
use ruff_source_file::{LineRanges, UniversalNewlines};
use ruff_text_size::{Ranged, TextRange, TextSize};

use crate::Db;

Expand Down Expand Up @@ -64,8 +65,24 @@ pub fn folding_ranges(
walk_node(&mut visitor, AnyNodeRef::from(parsed.syntax()));

// Add remaining ranges not covered by the AST visitor.
visitor.add_comment_ranges();
visitor.add_custom_region_ranges();
let own_line_comment_ranges: Vec<_> = parsed
.tokens()
.iter()
.filter_map(|token| {
if token.kind() == TokenKind::Comment
&& CommentLinePosition::for_range(token.range(), source.as_str()).is_own_line()
{
Some(TextRange::new(
source.as_str().line_start(token.start()),
token.end(),
))
} else {
None
}
})
.collect();
visitor.add_comment_ranges(&own_line_comment_ranges);
visitor.add_custom_region_ranges(&own_line_comment_ranges);

visitor.ranges
}
Expand All @@ -77,7 +94,7 @@ struct FoldingRangeVisitor<'a> {
range_filter: Option<TextRange>,
}

impl<'a> FoldingRangeVisitor<'a> {
impl FoldingRangeVisitor<'_> {
fn intersects_range_filter(&self, range: TextRange) -> bool {
self.range_filter
.is_none_or(|range_filter| range_filter.intersect(range).is_some())
Expand Down Expand Up @@ -113,11 +130,6 @@ impl<'a> FoldingRangeVisitor<'a> {
self.ranges.push(folding_range);
}

/// Iterate over lines with their starting byte offsets.
fn lines(&self) -> impl Iterator<Item = Line<'a>> + use<'a> {
self.source.universal_newlines()
}

fn is_multiline(&self, range: TextRange) -> bool {
self.source[range].contains('\n') || self.source[range].contains('\r')
}
Expand Down Expand Up @@ -189,21 +201,21 @@ impl<'a> FoldingRangeVisitor<'a> {
}

/// Compute folding ranges for `# region` / `# endregion` comments.
fn add_custom_region_ranges(&mut self) {
fn add_custom_region_ranges(&mut self, own_line_comment_ranges: &[TextRange]) {
let mut region_starts: Vec<TextSize> = Vec::new();

for line in self.lines() {
if !self.intersects_range_filter(line.full_range()) {
for &comment_range in own_line_comment_ranges {
if !self.intersects_range_filter(comment_range) {
continue;
}
let trimmed = line.trim_start();
if trimmed.starts_with("# region") || trimmed.starts_with("#region") {
region_starts.push(line.start());
} else if trimmed.starts_with("# endregion") || trimmed.starts_with("#endregion") {
let text = &self.source[comment_range];
let trimmed = text.strip_prefix('#').unwrap_or(text).trim_start();
if trimmed.starts_with("region") {
region_starts.push(comment_range.start());
} else if trimmed.starts_with("endregion") {
if let Some(start) = region_starts.pop() {
let end = line.start() + line.trim_end().text_len();
self.add_range(
FoldingRange::from(TextRange::new(start, end))
FoldingRange::from(TextRange::new(start, comment_range.end()))
.with_kind(FoldingRangeKind::Region),
);
}
Expand All @@ -212,40 +224,47 @@ impl<'a> FoldingRangeVisitor<'a> {
}

/// Compute folding ranges for consecutive comment lines.
fn add_comment_ranges(&mut self) {
let mut comment_range: Option<TextRange> = None;
fn add_comment_ranges(&mut self, own_line_comment_ranges: &[TextRange]) {
let mut comment_block_range: Option<TextRange> = None;

for line in self.lines() {
if !self.intersects_range_filter(line.full_range()) {
if let Some(range) = comment_range {
for &comment_range in own_line_comment_ranges {
if !self.intersects_range_filter(comment_range) {
if let Some(range) = comment_block_range {
self.add_range(FoldingRange::from(range).with_kind(FoldingRangeKind::Comment));
comment_range = None;
comment_block_range = None;
}
continue;
}

let trimmed = line.trim_start();
let comment = &self.source[comment_range];
let text = comment.strip_prefix('#').unwrap_or(comment).trim_start();

// Check if this is a comment line (but not a region marker)
let is_comment = trimmed.starts_with('#')
&& !trimmed.starts_with("# region")
&& !trimmed.starts_with("#region")
&& !trimmed.starts_with("# endregion")
&& !trimmed.starts_with("#endregion");

if is_comment {
let end = line.start() + line.trim_end().text_len();
if let Some(ref mut range) = comment_range {
*range = range.with_end(end);
let is_non_region_comment =
!text.starts_with("region") && !text.starts_with("endregion");

if is_non_region_comment {
// Extend the current comment block unless a blank line forces a new folding range.
if let Some(ref mut comment_block_range) = comment_block_range {
if self.has_blank_line_between(comment_block_range.end(), comment_range.start())
{
self.add_range(
FoldingRange::from(*comment_block_range)
.with_kind(FoldingRangeKind::Comment),
);
*comment_block_range = comment_range;
} else {
*comment_block_range = comment_block_range.with_end(comment_range.end());
}
} else {
comment_range = Some(TextRange::new(line.start(), end));
comment_block_range = Some(comment_range);
}
} else if let Some(range) = comment_range {
} else if let Some(range) = comment_block_range {
self.add_range(FoldingRange::from(range).with_kind(FoldingRangeKind::Comment));
comment_range = None;
comment_block_range = None;
}
}
if let Some(range) = comment_range {
if let Some(range) = comment_block_range {
self.add_range(FoldingRange::from(range).with_kind(FoldingRangeKind::Comment));
}
}
Expand Down Expand Up @@ -1375,7 +1394,7 @@ def main():
)
.build();

assert_snapshot!(test.folding_ranges(), @r"
assert_snapshot!(test.folding_ranges(), @"
info[folding-range]: Folding Range (imports)
--> main.py:3:1
|
Expand Down Expand Up @@ -1422,6 +1441,37 @@ def main():
");
}

#[test]
fn test_folding_range_regions_inside_multiline_fstring() {
let test = CursorTest::builder()
.source(
"main.py",
r#"
message = f"""
# region Not a real region
text inside an f-string
# endregion
"""
<CURSOR>
"#,
)
.build();

assert_snapshot!(test.folding_ranges(), @r#"
info[folding-range]: Folding Range
--> main.py:2:11
|
2 | message = f"""
| ___________^
3 | | # region Not a real region
4 | | text inside an f-string
5 | | # endregion
6 | | """
| |___^
|
"#);
}

#[test]
fn test_folding_range_docstring() {
let test = CursorTest::builder()
Expand Down
Loading