Skip to content

Commit

Permalink
Fix rename in VSCode (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
gimalay authored Jan 20, 2025
1 parent 695bc3b commit 19e1f3e
Show file tree
Hide file tree
Showing 13 changed files with 125 additions and 98 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ IWE functions in two modes:

This tool lets you process thousands of documents in just a second. With IWE, you can reformat documents and update link titles across your entire library. You can also use the CLI mode to combine multiple files into one extended document.

Please see the documenation at [IWE](https://iwe.md) for more information and setup instructions.
Please see the [documenation](https://iwe.md/docs/) at [IWE](https://iwe.md) for more information and [setup instructions](https://iwe.md/docs/how-to-install/).

## Inspired by many other opens-source projects

Expand Down
20 changes: 14 additions & 6 deletions crates/iwes/src/router/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ impl DatabaseContext for &Server {
fn parser(&self, id: &Key) -> Option<Parser> {
self.database().parser(id)
}

fn lines(&self, key: &Key) -> u32 {
self.database().lines(key)
}
}

impl Server {
Expand Down Expand Up @@ -295,12 +299,16 @@ impl Server {
.clone()
.to_url(&self.base_path)
.to_delete_file_op()])
.chain(vec![{
params.new_name.to_url(&self.base_path).to_override_file_op(
&self.base_path,
patch.export_key(&params.new_name).expect("to have key"),
)
}])
.chain(vec![
params.new_name.to_url(&self.base_path).to_create_file_op(),
params
.new_name
.to_url(&self.base_path)
.to_override_new_file_op(
&self.base_path,
patch.export_key(&params.new_name).expect("to have key"),
),
])
.collect();

WorkspaceEdit {
Expand Down
22 changes: 22 additions & 0 deletions crates/iwes/src/router/server/extensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,28 @@ pub impl Url {
DocumentChangeOperation::Edit(self.to_override_file(base_path, text))
}

fn to_override_new_file_op(
&self,
base_path: &BasePath,
text: String,
) -> DocumentChangeOperation {
DocumentChangeOperation::Edit(self.to_override_new_file(base_path, text))
}

fn to_override_new_file(&self, _: &BasePath, text: Content) -> TextDocumentEdit {
let insert_extracted_text = TextEdit {
range: Range::new(Position::new(0, 0), Position::new(0, 0)),
new_text: text,
};
TextDocumentEdit {
text_document: OptionalVersionedTextDocumentIdentifier {
uri: self.clone(),
version: None,
},
edits: vec![OneOf::Left(insert_extracted_text)],
}
}

fn to_override_file(&self, _: &BasePath, text: Content) -> TextDocumentEdit {
let insert_extracted_text = TextEdit {
range: Range::new(Position::new(0, 0), Position::new(u32::MAX, 0)),
Expand Down
24 changes: 19 additions & 5 deletions crates/iwes/tests/rename_test.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use std::u32;

use indoc::indoc;
use lsp_server::ResponseError;
use lsp_types::{
DeleteFile, DocumentChangeOperation, DocumentChanges, OneOf,
CreateFile, CreateFileOptions, DeleteFile, DocumentChangeOperation, DocumentChanges, OneOf,
OptionalVersionedTextDocumentIdentifier, Position, PrepareRenameResponse, Range, RenameParams,
ResourceOp, TextDocumentEdit, TextDocumentIdentifier, TextDocumentPositionParams, TextEdit,
WorkspaceEdit,
Expand Down Expand Up @@ -147,14 +145,22 @@ fn assert_rename_at(source: &str, expected: &str, position: Position, new_name:
uri: uri(1),
options: None,
})),
DocumentChangeOperation::Op(ResourceOp::Create(CreateFile {
uri: uri_from("new_name"),
options: Some(CreateFileOptions {
overwrite: Some(false),
ignore_if_exists: Some(false),
}),
annotation_id: None,
})),
DocumentChangeOperation::Edit(TextDocumentEdit {
text_document: OptionalVersionedTextDocumentIdentifier {
uri: uri_from("new_name"),
version: None,
},
edits: vec![OneOf::Left(TextEdit {
new_text: expected.to_string(),
range: Range::new(Position::new(0, 0), Position::new(u32::MAX, 0)),
range: Range::new(Position::new(0, 0), Position::new(0, 0)),
})],
}),
])),
Expand Down Expand Up @@ -212,14 +218,22 @@ fn assert_rename_updates_second_file(source: &str, expected1: &str, expected2: &
uri: uri(1),
options: None,
})),
DocumentChangeOperation::Op(ResourceOp::Create(CreateFile {
uri: uri_from("new_name"),
options: Some(CreateFileOptions {
overwrite: Some(false),
ignore_if_exists: Some(false),
}),
annotation_id: None,
})),
DocumentChangeOperation::Edit(TextDocumentEdit {
text_document: OptionalVersionedTextDocumentIdentifier {
uri: uri_from("new_name"),
version: None,
},
edits: vec![OneOf::Left(TextEdit {
new_text: expected1.to_string(),
range: Range::new(Position::new(0, 0), Position::new(u32::MAX, 0)),
range: Range::new(Position::new(0, 0), Position::new(0, 0)),
})],
}),
])),
Expand Down
63 changes: 33 additions & 30 deletions crates/liwe/src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,39 +342,42 @@ pub fn inline_quote(target_id: NodeId, context: impl GraphContext) -> Option<Act
pub fn inline_section(target_id: NodeId, context: impl GraphContext) -> Option<Action> {
Some(target_id)
.filter(|target_id| context.is_reference(*target_id))
.map(|target_id| {
.and_then(|target_id| {
let key = context.get_key(target_id);
let inline_key = context.get_reference_key(target_id);
let mut patch = context.patch();

patch.add_key(
&key,
context
.visit(&key)
.collect_tree()
.remove_node(target_id)
.append_pre_header(
context.get_surrounding_section_id(target_id).unwrap(),
context.visit(&inline_key).collect_tree(),
)
.iter(),
);

let markdown = patch.markdown(&key).unwrap();

Action {
title: "Inline section".to_string(),
changes: vec![
Change::Remove(Remove {
key: context.get_reference_key(target_id),
}),
Change::Update(Update {
key: key,
markdown: markdown,
}),
],
action_type: ActionType::ReferenceInlineSection,
}
context
.get_surrounding_section_id(target_id)
.map(|section_id| {
patch.add_key(
&key,
context
.visit(&key)
.collect_tree()
.remove_node(target_id)
.append_pre_header(
section_id,
context.visit(&inline_key).collect_tree(),
)
.iter(),
);

let markdown = patch.markdown(&key).unwrap();

Action {
title: "Inline section".to_string(),
changes: vec![
Change::Remove(Remove {
key: context.get_reference_key(target_id),
}),
Change::Update(Update {
key: key,
markdown: markdown,
}),
],
action_type: ActionType::ReferenceInlineSection,
}
})
})
}

Expand Down
12 changes: 12 additions & 0 deletions crates/liwe/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub struct Database {
}

pub trait DatabaseContext {
fn lines(&self, key: &Key) -> u32;
fn parser(&self, key: &Key) -> Option<Parser>;
}

Expand All @@ -26,6 +27,17 @@ impl DatabaseContext for &Database {
.get(key)
.map(|content| Parser::new(&content, MarkdownReader::new()))
}

fn lines(&self, key: &Key) -> u32 {
if key.ends_with(".md") {
panic!("Key should not end with .md")
}

self.content
.get(key)
.map(|content| content.lines().count() as u32)
.unwrap_or(0)
}
}

impl Database {
Expand Down
1 change: 1 addition & 0 deletions crates/liwe/src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub fn new_for_path(path: &PathBuf) -> State {
.unwrap()
.into_iter()
.map(|entry| entry.unwrap().path())
.filter(|path| path.extension().map_or(false, |ex| ex.eq("md")))
.collect::<Vec<PathBuf>>()
.par_iter()
.flat_map(|path| read_file(path))
Expand Down
4 changes: 2 additions & 2 deletions crates/liwe/src/key.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::model::{self, Key};
use crate::model::Key;

pub fn without_extension(key: &str) -> String {
if !key.ends_with(".md") {
Expand All @@ -7,7 +7,7 @@ pub fn without_extension(key: &str) -> String {
key.trim_end_matches(".md").to_string()
}

pub fn with_extension(link: &str) -> model::Key {
pub fn with_extension(link: &str) -> Key {
if link.ends_with(".md") {
return link.to_string();
}
Expand Down
47 changes: 16 additions & 31 deletions crates/liwe/src/markdown/reader.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::iter::once;
use std::ops::Range;

use itertools::Itertools;
use pulldown_cmark::{CodeBlockKind, Options, Tag, TagEnd};
use pulldown_cmark::{Event::*, Parser};

Expand Down Expand Up @@ -63,7 +62,7 @@ impl MarkdownEventsReader {
code_block.text = format!("{}{}", code_block.text, text.to_string())
}
DocumentBlock::RawBlock(block) => block.text = text.to_string(),
default => {
_ => {
self.push_inline(
DocumentInline::Str(text.to_string()),
self.to_line_range(range),
Expand Down Expand Up @@ -106,7 +105,7 @@ impl MarkdownEventsReader {
);
self.pop_inline();
}
FootnoteReference(cow_str) => {}
FootnoteReference(_) => {}
SoftBreak => {}
HardBreak => {}
Rule => {
Expand Down Expand Up @@ -164,22 +163,15 @@ impl MarkdownEventsReader {
inlines: vec![],
}));
}
Tag::Heading {
level,
id,
classes,
attrs,
} => self.push_block(DocumentBlock::Header(Header {
Tag::Heading { level, .. } => self.push_block(DocumentBlock::Header(Header {
line_range: self.to_line_range(range),
level: level as u8,
inlines: vec![],
})),
Tag::BlockQuote(block_quote_kind) => {
self.push_block(DocumentBlock::BlockQuote(BlockQuote {
line_range: self.to_line_range(range),
blocks: Vec::new(),
}))
}
Tag::BlockQuote(_) => self.push_block(DocumentBlock::BlockQuote(BlockQuote {
line_range: self.to_line_range(range),
blocks: Vec::new(),
})),
Tag::CodeBlock(code_block_kind) => {
self.push_block(DocumentBlock::CodeBlock(CodeBlock {
line_range: self.to_line_range(range),
Expand All @@ -203,11 +195,11 @@ impl MarkdownEventsReader {
Tag::Item => {
self.top_block().append_item();
}
Tag::FootnoteDefinition(str) => {}
Tag::FootnoteDefinition(_) => {}
Tag::DefinitionList => {}
Tag::DefinitionListTitle => {}
Tag::DefinitionListDefinition => {}
Tag::Table(vec) => {}
Tag::Table(_) => {}
Tag::TableHead => {}
Tag::TableRow => {}
Tag::TableCell => {}
Expand Down Expand Up @@ -239,10 +231,7 @@ impl MarkdownEventsReader {
);
}
Tag::Link {
link_type,
dest_url,
title,
id,
dest_url, title, ..
} => {
self.push_inline(
DocumentInline::Link(Link {
Expand All @@ -258,10 +247,7 @@ impl MarkdownEventsReader {
);
}
Tag::Image {
link_type,
dest_url,
title,
id,
dest_url, title, ..
} => {
self.push_inline(
DocumentInline::Image(Image {
Expand All @@ -276,17 +262,17 @@ impl MarkdownEventsReader {
self.to_line_range(range),
);
}
Tag::MetadataBlock(metadata_block_kind) => self.metadata_block = true,
Tag::MetadataBlock(_) => self.metadata_block = true,
}
}

fn end_tag(&mut self, tag: TagEnd, range: Range<usize>) {
fn end_tag(&mut self, tag: TagEnd, _: Range<usize>) {
match tag {
TagEnd::Paragraph => {
self.pop_block();
}
TagEnd::Heading(heading_level) => self.pop_block(),
TagEnd::BlockQuote(block_quote_kind) => self.pop_block(),
TagEnd::Heading(_) => self.pop_block(),
TagEnd::BlockQuote(_) => self.pop_block(),
TagEnd::CodeBlock => {
self.pop_block();
}
Expand All @@ -304,7 +290,7 @@ impl MarkdownEventsReader {
TagEnd::DefinitionListTitle => {}
TagEnd::FootnoteDefinition => {}
TagEnd::Image => self.pop_inline(),
TagEnd::MetadataBlock(metadata_block_kind) => self.metadata_block = false,
TagEnd::MetadataBlock(_) => self.metadata_block = false,
TagEnd::Table => {}
TagEnd::TableCell => {}
TagEnd::TableHead => {}
Expand Down Expand Up @@ -377,7 +363,6 @@ fn line_starts(content: &str) -> Vec<usize> {
mod tests {
use indoc::indoc;

use crate::graph::graph_node::Document;
use crate::markdown::reader::{line_starts, MarkdownEventsReader};
use crate::model::{document::*, InlineRange, Position};

Expand Down
Loading

0 comments on commit 19e1f3e

Please sign in to comment.