| 1 |
use anyhow::{anyhow, bail, Error}; |
| 2 |
use arc_swap::access::DynAccess; |
| 3 |
use arc_swap::ArcSwap; |
| 4 |
use futures_util::future::BoxFuture; |
| 5 |
use futures_util::FutureExt; |
| 6 |
use helix_core::auto_pairs::AutoPairs; |
| 7 |
use helix_core::chars::char_is_word; |
| 8 |
use helix_core::command_line::Token; |
| 9 |
use helix_core::diagnostic::DiagnosticProvider; |
| 10 |
use helix_core::doc_formatter::TextFormat; |
| 11 |
use helix_core::encoding::Encoding; |
| 12 |
use helix_core::snippets::{ActiveSnippet, SnippetRenderCtx}; |
| 13 |
use helix_core::syntax::config::LanguageServerFeature; |
| 14 |
use helix_core::text_annotations::{InlineAnnotation, Overlay}; |
| 15 |
use helix_event::TaskController; |
| 16 |
use helix_lsp::util::lsp_pos_to_pos; |
| 17 |
use helix_stdx::faccess::{copy_metadata, readonly}; |
| 18 |
use helix_vcs::{DiffHandle, DiffProviderRegistry}; |
| 19 |
use once_cell::sync::OnceCell; |
| 20 |
use thiserror; |
| 21 |
|
| 22 |
use ::parking_lot::Mutex; |
| 23 |
use serde::de::{self, Deserialize, Deserializer}; |
| 24 |
use serde::Serialize; |
| 25 |
use std::borrow::Cow; |
| 26 |
use std::cell::Cell; |
| 27 |
use std::collections::{HashMap, HashSet}; |
| 28 |
use std::fmt::Display; |
| 29 |
use std::future::Future; |
| 30 |
use std::io; |
| 31 |
use std::path::{Path, PathBuf}; |
| 32 |
use std::str::FromStr; |
| 33 |
use std::sync::{Arc, Weak}; |
| 34 |
use std::time::SystemTime; |
| 35 |
|
| 36 |
use helix_core::{ |
| 37 |
editor_config::EditorConfig, |
| 38 |
encoding, |
| 39 |
history::{History, State, UndoKind}, |
| 40 |
indent::{auto_detect_indent_style, IndentStyle}, |
| 41 |
line_ending::auto_detect_line_ending, |
| 42 |
syntax::{self, config::LanguageConfiguration}, |
| 43 |
ChangeSet, Diagnostic, LineEnding, Range, Rope, RopeBuilder, Selection, Syntax, Transaction, |
| 44 |
}; |
| 45 |
|
| 46 |
use crate::{ |
| 47 |
editor::Config, |
| 48 |
events::{DocumentDidChange, SelectionDidChange}, |
| 49 |
expansion, |
| 50 |
view::ViewPosition, |
| 51 |
DocumentId, Editor, Theme, View, ViewId, |
| 52 |
}; |
| 53 |
|
| 54 |
|
| 55 |
const BUF_SIZE: usize = 8192; |
| 56 |
|
| 57 |
const DEFAULT_INDENT: IndentStyle = IndentStyle::Tabs; |
| 58 |
const DEFAULT_TAB_WIDTH: usize = 4; |
| 59 |
|
| 60 |
pub const DEFAULT_LANGUAGE_NAME: &str = "text"; |
| 61 |
|
| 62 |
pub const SCRATCH_BUFFER_NAME: &str = "[scratch]"; |
| 63 |
|
| 64 |
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] |
| 65 |
pub enum Mode { |
| 66 |
Normal = 0, |
| 67 |
Select = 1, |
| 68 |
Insert = 2, |
| 69 |
} |
| 70 |
|
| 71 |
impl Display for Mode { |
| 72 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 73 |
match self { |
| 74 |
Mode::Normal => f.write_str("normal"), |
| 75 |
Mode::Select => f.write_str("select"), |
| 76 |
Mode::Insert => f.write_str("insert"), |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
impl FromStr for Mode { |
| 82 |
type Err = Error; |
| 83 |
|
| 84 |
fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 85 |
match s { |
| 86 |
"normal" => Ok(Mode::Normal), |
| 87 |
"select" => Ok(Mode::Select), |
| 88 |
"insert" => Ok(Mode::Insert), |
| 89 |
_ => bail!("Invalid mode '{}'", s), |
| 90 |
} |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
|
| 95 |
impl<'de> Deserialize<'de> for Mode { |
| 96 |
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 97 |
where |
| 98 |
D: Deserializer<'de>, |
| 99 |
{ |
| 100 |
let s = String::deserialize(deserializer)?; |
| 101 |
s.parse().map_err(de::Error::custom) |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
impl Serialize for Mode { |
| 106 |
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 107 |
where |
| 108 |
S: serde::Serializer, |
| 109 |
{ |
| 110 |
serializer.collect_str(self) |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
#[derive(Debug, Clone)] |
| 115 |
pub struct DocumentSavedEvent { |
| 116 |
pub revision: usize, |
| 117 |
pub save_time: SystemTime, |
| 118 |
pub doc_id: DocumentId, |
| 119 |
pub path: PathBuf, |
| 120 |
pub text: Rope, |
| 121 |
} |
| 122 |
|
| 123 |
pub type DocumentSavedEventResult = Result<DocumentSavedEvent, anyhow::Error>; |
| 124 |
pub type DocumentSavedEventFuture = BoxFuture<'static, DocumentSavedEventResult>; |
| 125 |
|
| 126 |
#[derive(Debug)] |
| 127 |
pub struct SavePoint { |
| 128 |
|
| 129 |
pub view: ViewId, |
| 130 |
revert: Mutex<Transaction>, |
| 131 |
} |
| 132 |
|
| 133 |
#[derive(Debug, thiserror::Error)] |
| 134 |
pub enum DocumentOpenError { |
| 135 |
#[error("path must be a regular file, symlink, or directory")] |
| 136 |
IrregularFile, |
| 137 |
#[error(transparent)] |
| 138 |
IoError(#[from] io::Error), |
| 139 |
} |
| 140 |
|
| 141 |
pub struct Document { |
| 142 |
pub(crate) id: DocumentId, |
| 143 |
text: Rope, |
| 144 |
selections: HashMap<ViewId, Selection>, |
| 145 |
view_data: HashMap<ViewId, ViewData>, |
| 146 |
pub active_snippet: Option<ActiveSnippet>, |
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
pub(crate) inlay_hints: HashMap<ViewId, DocumentInlayHints>, |
| 152 |
|
| 153 |
pub(crate) jump_labels: HashMap<ViewId, Vec<Overlay>>, |
| 154 |
|
| 155 |
pub(crate) document_highlights: HashMap<ViewId, DocumentHighlights>, |
| 156 |
|
| 157 |
pub(crate) code_action_hints: HashSet<ViewId>, |
| 158 |
|
| 159 |
|
| 160 |
pub inlay_hints_oudated: bool, |
| 161 |
|
| 162 |
path: Option<PathBuf>, |
| 163 |
relative_path: OnceCell<Option<PathBuf>>, |
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
workspace_root: OnceCell<PathBuf>, |
| 169 |
encoding: &'static encoding::Encoding, |
| 170 |
has_bom: bool, |
| 171 |
|
| 172 |
pub restore_cursor: bool, |
| 173 |
|
| 174 |
|
| 175 |
pub indent_style: IndentStyle, |
| 176 |
editor_config: EditorConfig, |
| 177 |
|
| 178 |
|
| 179 |
pub line_ending: LineEnding, |
| 180 |
|
| 181 |
pub syntax: Option<Syntax>, |
| 182 |
|
| 183 |
pub language: Option<Arc<LanguageConfiguration>>, |
| 184 |
|
| 185 |
|
| 186 |
changes: ChangeSet, |
| 187 |
|
| 188 |
old_state: Option<State>, |
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
pub history: Cell<History>, |
| 194 |
pub config: Arc<dyn DynAccess<Config>>, |
| 195 |
|
| 196 |
savepoints: Vec<Weak<SavePoint>>, |
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
last_saved_time: SystemTime, |
| 201 |
|
| 202 |
last_saved_revision: usize, |
| 203 |
version: i32, |
| 204 |
pub(crate) modified_since_accessed: bool, |
| 205 |
|
| 206 |
pub(crate) diagnostics: Vec<Diagnostic>, |
| 207 |
pub(crate) language_servers: HashMap<LanguageServerName, Arc<Client>>, |
| 208 |
|
| 209 |
diff_handle: Option<DiffHandle>, |
| 210 |
version_control_head: Option<Arc<ArcSwap<Box<str>>>>, |
| 211 |
|
| 212 |
|
| 213 |
pub focused_at: std::time::Instant, |
| 214 |
|
| 215 |
pub readonly: bool, |
| 216 |
|
| 217 |
pub previous_diagnostic_ids: HashMap<LanguageServerId, String>, |
| 218 |
|
| 219 |
|
| 220 |
pub color_swatches: Option<DocumentColorSwatches>, |
| 221 |
|
| 222 |
pub document_links: Vec<DocumentLink>, |
| 223 |
|
| 224 |
|
| 225 |
pub color_swatch_controller: TaskController, |
| 226 |
|
| 227 |
pub document_highlight_controllers: HashMap<ViewId, TaskController>, |
| 228 |
|
| 229 |
pub code_action_controllers: HashMap<ViewId, TaskController>, |
| 230 |
pub pull_diagnostic_controller: TaskController, |
| 231 |
pub document_link_controller: TaskController, |
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
syn_loader: Arc<ArcSwap<syntax::Loader>>, |
| 237 |
} |
| 238 |
|
| 239 |
#[derive(Debug, Clone, Default)] |
| 240 |
pub struct DocumentColorSwatches { |
| 241 |
pub color_swatches: Vec<InlineAnnotation>, |
| 242 |
pub colors: Vec<syntax::Highlight>, |
| 243 |
pub color_swatches_padding: Vec<InlineAnnotation>, |
| 244 |
} |
| 245 |
|
| 246 |
|
| 247 |
#[derive(Debug, Clone, Default)] |
| 248 |
pub struct DocumentHighlights { |
| 249 |
pub ranges: Vec<std::ops::Range<usize>>, |
| 250 |
} |
| 251 |
|
| 252 |
#[derive(Debug, Clone)] |
| 253 |
pub struct DocumentLink { |
| 254 |
|
| 255 |
pub start: usize, |
| 256 |
pub end: usize, |
| 257 |
pub link: lsp::DocumentLink, |
| 258 |
pub language_server_id: LanguageServerId, |
| 259 |
} |
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
#[derive(Debug, Clone)] |
| 276 |
pub struct DocumentInlayHints { |
| 277 |
|
| 278 |
|
| 279 |
pub id: DocumentInlayHintsId, |
| 280 |
|
| 281 |
|
| 282 |
pub type_inlay_hints: Vec<InlineAnnotation>, |
| 283 |
|
| 284 |
|
| 285 |
pub parameter_inlay_hints: Vec<InlineAnnotation>, |
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
pub other_inlay_hints: Vec<InlineAnnotation>, |
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
pub padding_before_inlay_hints: Vec<InlineAnnotation>, |
| 297 |
pub padding_after_inlay_hints: Vec<InlineAnnotation>, |
| 298 |
} |
| 299 |
|
| 300 |
impl DocumentInlayHints { |
| 301 |
|
| 302 |
pub fn empty_with_id(id: DocumentInlayHintsId) -> Self { |
| 303 |
Self { |
| 304 |
id, |
| 305 |
type_inlay_hints: Vec::new(), |
| 306 |
parameter_inlay_hints: Vec::new(), |
| 307 |
other_inlay_hints: Vec::new(), |
| 308 |
padding_before_inlay_hints: Vec::new(), |
| 309 |
padding_after_inlay_hints: Vec::new(), |
| 310 |
} |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
|
| 320 |
#[derive(Copy, Clone, PartialEq, Eq)] |
| 321 |
pub struct DocumentInlayHintsId { |
| 322 |
|
| 323 |
pub first_line: usize, |
| 324 |
|
| 325 |
pub last_line: usize, |
| 326 |
} |
| 327 |
|
| 328 |
use std::{fmt, mem}; |
| 329 |
impl fmt::Debug for Document { |
| 330 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 331 |
f.debug_struct("Document") |
| 332 |
.field("id", &self.id) |
| 333 |
.field("text", &self.text) |
| 334 |
.field("selections", &self.selections) |
| 335 |
.field("inlay_hints_oudated", &self.inlay_hints_oudated) |
| 336 |
.field("text_annotations", &self.inlay_hints) |
| 337 |
.field("view_data", &self.view_data) |
| 338 |
.field("path", &self.path) |
| 339 |
.field("encoding", &self.encoding) |
| 340 |
.field("restore_cursor", &self.restore_cursor) |
| 341 |
.field("syntax", &self.syntax) |
| 342 |
.field("language", &self.language) |
| 343 |
.field("changes", &self.changes) |
| 344 |
.field("old_state", &self.old_state) |
| 345 |
|
| 346 |
.field("last_saved_time", &self.last_saved_time) |
| 347 |
.field("last_saved_revision", &self.last_saved_revision) |
| 348 |
.field("version", &self.version) |
| 349 |
.field("modified_since_accessed", &self.modified_since_accessed) |
| 350 |
.field("diagnostics", &self.diagnostics) |
| 351 |
|
| 352 |
.finish() |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
impl fmt::Debug for DocumentInlayHintsId { |
| 357 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 358 |
|
| 359 |
f.debug_struct("DocumentInlayHintsId") |
| 360 |
.field("lines", &(self.first_line..self.last_line)) |
| 361 |
.finish() |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
impl Editor { |
| 366 |
pub(crate) fn clear_doc_relative_paths(&mut self) { |
| 367 |
for doc in self.documents_mut() { |
| 368 |
doc.relative_path.take(); |
| 369 |
} |
| 370 |
} |
| 371 |
} |
| 372 |
|
| 373 |
enum Encoder { |
| 374 |
Utf16Be, |
| 375 |
Utf16Le, |
| 376 |
EncodingRs(encoding::Encoder), |
| 377 |
} |
| 378 |
|
| 379 |
impl Encoder { |
| 380 |
fn from_encoding(encoding: &'static encoding::Encoding) -> Self { |
| 381 |
if encoding == encoding::UTF_16BE { |
| 382 |
Self::Utf16Be |
| 383 |
} else if encoding == encoding::UTF_16LE { |
| 384 |
Self::Utf16Le |
| 385 |
} else { |
| 386 |
Self::EncodingRs(encoding.new_encoder()) |
| 387 |
} |
| 388 |
} |
| 389 |
|
| 390 |
fn encode_from_utf8( |
| 391 |
&mut self, |
| 392 |
src: &str, |
| 393 |
dst: &mut [u8], |
| 394 |
is_empty: bool, |
| 395 |
) -> (encoding::CoderResult, usize, usize) { |
| 396 |
if src.is_empty() { |
| 397 |
return (encoding::CoderResult::InputEmpty, 0, 0); |
| 398 |
} |
| 399 |
let mut write_to_buf = |convert: fn(u16) -> [u8; 2]| { |
| 400 |
let to_write = src.char_indices().map(|(indice, char)| { |
| 401 |
let mut encoded: [u16; 2] = [0, 0]; |
| 402 |
( |
| 403 |
indice, |
| 404 |
char.encode_utf16(&mut encoded) |
| 405 |
.iter_mut() |
| 406 |
.flat_map(|char| convert(*char)) |
| 407 |
.collect::<Vec<u8>>(), |
| 408 |
) |
| 409 |
}); |
| 410 |
|
| 411 |
let mut total_written = 0usize; |
| 412 |
|
| 413 |
for (indice, utf16_bytes) in to_write { |
| 414 |
let character_size = utf16_bytes.len(); |
| 415 |
|
| 416 |
if dst.len() <= (total_written + character_size) { |
| 417 |
return (encoding::CoderResult::OutputFull, indice, total_written); |
| 418 |
} |
| 419 |
|
| 420 |
for character in utf16_bytes { |
| 421 |
dst[total_written] = character; |
| 422 |
total_written += 1; |
| 423 |
} |
| 424 |
} |
| 425 |
|
| 426 |
(encoding::CoderResult::InputEmpty, src.len(), total_written) |
| 427 |
}; |
| 428 |
|
| 429 |
match self { |
| 430 |
Self::Utf16Be => write_to_buf(u16::to_be_bytes), |
| 431 |
Self::Utf16Le => write_to_buf(u16::to_le_bytes), |
| 432 |
Self::EncodingRs(encoder) => { |
| 433 |
let (code_result, read, written, ..) = encoder.encode_from_utf8(src, dst, is_empty); |
| 434 |
|
| 435 |
(code_result, read, written) |
| 436 |
} |
| 437 |
} |
| 438 |
} |
| 439 |
} |
| 440 |
|
| 441 |
|
| 442 |
fn apply_bom(encoding: &'static encoding::Encoding, buf: &mut [u8; BUF_SIZE]) -> usize { |
| 443 |
if encoding == encoding::UTF_8 { |
| 444 |
buf[0] = 0xef; |
| 445 |
buf[1] = 0xbb; |
| 446 |
buf[2] = 0xbf; |
| 447 |
3 |
| 448 |
} else if encoding == encoding::UTF_16BE { |
| 449 |
buf[0] = 0xfe; |
| 450 |
buf[1] = 0xff; |
| 451 |
2 |
| 452 |
} else if encoding == encoding::UTF_16LE { |
| 453 |
buf[0] = 0xff; |
| 454 |
buf[1] = 0xfe; |
| 455 |
2 |
| 456 |
} else { |
| 457 |
0 |
| 458 |
} |
| 459 |
} |
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
pub fn from_reader<R: std::io::Read + ?Sized>( |
| 468 |
reader: &mut R, |
| 469 |
encoding: Option<&'static Encoding>, |
| 470 |
) -> Result<(Rope, &'static Encoding, bool), io::Error> { |
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
let mut buf = [0u8; BUF_SIZE]; |
| 477 |
let mut buf_out = [0u8; BUF_SIZE]; |
| 478 |
let mut builder = RopeBuilder::new(); |
| 479 |
|
| 480 |
let (encoding, has_bom, mut decoder, read) = |
| 481 |
read_and_detect_encoding(reader, encoding, &mut buf)?; |
| 482 |
|
| 483 |
let mut slice = &buf[..read]; |
| 484 |
let mut is_empty = read == 0; |
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
let buf_str = unsafe { std::str::from_utf8_unchecked_mut(&mut buf_out[..]) }; |
| 501 |
let mut total_written = 0usize; |
| 502 |
loop { |
| 503 |
let mut total_read = 0usize; |
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
loop { |
| 510 |
let (result, read, written, ..) = decoder.decode_to_str( |
| 511 |
&slice[total_read..], |
| 512 |
&mut buf_str[total_written..], |
| 513 |
is_empty, |
| 514 |
); |
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
total_read += read; |
| 521 |
total_written += written; |
| 522 |
match result { |
| 523 |
encoding::CoderResult::InputEmpty => { |
| 524 |
debug_assert_eq!(slice.len(), total_read); |
| 525 |
break; |
| 526 |
} |
| 527 |
encoding::CoderResult::OutputFull => { |
| 528 |
debug_assert!(slice.len() > total_read); |
| 529 |
builder.append(&buf_str[..total_written]); |
| 530 |
total_written = 0; |
| 531 |
} |
| 532 |
} |
| 533 |
} |
| 534 |
|
| 535 |
|
| 536 |
if is_empty { |
| 537 |
debug_assert_eq!(reader.read(&mut buf)?, 0); |
| 538 |
builder.append(&buf_str[..total_written]); |
| 539 |
break; |
| 540 |
} |
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
let read = reader.read(&mut buf)?; |
| 547 |
slice = &buf[..read]; |
| 548 |
is_empty = read == 0; |
| 549 |
} |
| 550 |
let rope = builder.finish(); |
| 551 |
Ok((rope, encoding, has_bom)) |
| 552 |
} |
| 553 |
|
| 554 |
pub fn read_to_string<R: std::io::Read + ?Sized>( |
| 555 |
reader: &mut R, |
| 556 |
encoding: Option<&'static Encoding>, |
| 557 |
) -> Result<(String, &'static Encoding, bool), Error> { |
| 558 |
let mut buf = [0u8; BUF_SIZE]; |
| 559 |
|
| 560 |
let (encoding, has_bom, mut decoder, read) = |
| 561 |
read_and_detect_encoding(reader, encoding, &mut buf)?; |
| 562 |
|
| 563 |
let mut slice = &buf[..read]; |
| 564 |
let mut is_empty = read == 0; |
| 565 |
let mut buf_string = String::with_capacity(buf.len()); |
| 566 |
|
| 567 |
loop { |
| 568 |
let mut total_read = 0usize; |
| 569 |
|
| 570 |
loop { |
| 571 |
let (result, read, ..) = |
| 572 |
decoder.decode_to_string(&slice[total_read..], &mut buf_string, is_empty); |
| 573 |
|
| 574 |
total_read += read; |
| 575 |
|
| 576 |
match result { |
| 577 |
encoding::CoderResult::InputEmpty => { |
| 578 |
debug_assert_eq!(slice.len(), total_read); |
| 579 |
break; |
| 580 |
} |
| 581 |
encoding::CoderResult::OutputFull => { |
| 582 |
debug_assert!(slice.len() > total_read); |
| 583 |
buf_string.reserve(buf.len()) |
| 584 |
} |
| 585 |
} |
| 586 |
} |
| 587 |
|
| 588 |
if is_empty { |
| 589 |
debug_assert_eq!(reader.read(&mut buf)?, 0); |
| 590 |
break; |
| 591 |
} |
| 592 |
|
| 593 |
let read = reader.read(&mut buf)?; |
| 594 |
slice = &buf[..read]; |
| 595 |
is_empty = read == 0; |
| 596 |
} |
| 597 |
Ok((buf_string, encoding, has_bom)) |
| 598 |
} |
| 599 |
|
| 600 |
|
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
|
| 608 |
|
| 609 |
fn read_and_detect_encoding<R: std::io::Read + ?Sized>( |
| 610 |
reader: &mut R, |
| 611 |
encoding: Option<&'static Encoding>, |
| 612 |
buf: &mut [u8], |
| 613 |
) -> Result<(&'static Encoding, bool, encoding::Decoder, usize), io::Error> { |
| 614 |
let read = reader.read(buf)?; |
| 615 |
let is_empty = read == 0; |
| 616 |
let (encoding, has_bom) = encoding |
| 617 |
.map(|encoding| (encoding, false)) |
| 618 |
.or_else(|| encoding::Encoding::for_bom(buf).map(|(encoding, _bom_size)| (encoding, true))) |
| 619 |
.unwrap_or_else(|| { |
| •620 |
let mut encoding_detector = chardetng::EncodingDetector::new(); |
| 621 |
encoding_detector.feed(buf, is_empty); |
| •622 |
(encoding_detector.guess(None, true), false) |
| 623 |
}); |
| 624 |
let decoder = encoding.new_decoder(); |
| 625 |
|
| 626 |
Ok((encoding, has_bom, decoder, read)) |
| 627 |
} |
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
|
| 632 |
|
| 633 |
|
| 634 |
|
| 635 |
pub async fn to_writer<'a, W: tokio::io::AsyncWriteExt + Unpin + ?Sized>( |
| 636 |
writer: &'a mut W, |
| 637 |
encoding_with_bom_info: (&'static Encoding, bool), |
| 638 |
rope: &'a Rope, |
| 639 |
) -> Result<(), Error> { |
| 640 |
|
| 641 |
|
| 642 |
|
| 643 |
|
| 644 |
|
| 645 |
|
| 646 |
let (encoding, has_bom) = encoding_with_bom_info; |
| 647 |
|
| 648 |
let iter = rope |
| 649 |
.chunks() |
| 650 |
.filter(|c| !c.is_empty()) |
| 651 |
.chain(std::iter::once("")); |
| 652 |
let mut buf = [0u8; BUF_SIZE]; |
| 653 |
|
| 654 |
let mut total_written = if has_bom { |
| 655 |
apply_bom(encoding, &mut buf) |
| 656 |
} else { |
| 657 |
0 |
| 658 |
}; |
| 659 |
|
| 660 |
let mut encoder = Encoder::from_encoding(encoding); |
| 661 |
|
| 662 |
for chunk in iter { |
| 663 |
let is_empty = chunk.is_empty(); |
| 664 |
let mut total_read = 0usize; |
| 665 |
|
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
loop { |
| 671 |
let (result, read, written, ..) = |
| 672 |
encoder.encode_from_utf8(&chunk[total_read..], &mut buf[total_written..], is_empty); |
| 673 |
|
| 674 |
|
| 675 |
|
| 676 |
|
| 677 |
|
| 678 |
total_read += read; |
| 679 |
total_written += written; |
| 680 |
match result { |
| 681 |
encoding::CoderResult::InputEmpty => { |
| 682 |
debug_assert_eq!(chunk.len(), total_read); |
| 683 |
debug_assert!(buf.len() >= total_written); |
| 684 |
break; |
| 685 |
} |
| 686 |
encoding::CoderResult::OutputFull => { |
| 687 |
debug_assert!(chunk.len() > total_read); |
| 688 |
writer.write_all(&buf[..total_written]).await?; |
| 689 |
total_written = 0; |
| 690 |
} |
| 691 |
} |
| 692 |
} |
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
if is_empty { |
| 697 |
writer.write_all(&buf[..total_written]).await?; |
| 698 |
writer.flush().await?; |
| 699 |
break; |
| 700 |
} |
| 701 |
} |
| 702 |
|
| 703 |
Ok(()) |
| 704 |
} |
| 705 |
|
| 706 |
fn take_with<T, F>(mut_ref: &mut T, f: F) |
| 707 |
where |
| 708 |
T: Default, |
| 709 |
F: FnOnce(T) -> T, |
| 710 |
{ |
| 711 |
*mut_ref = f(mem::take(mut_ref)); |
| 712 |
} |
| 713 |
|
| 714 |
use helix_lsp::{lsp, Client, LanguageServerId, LanguageServerName}; |
| 715 |
use helix_stdx::Url; |
| 716 |
|
| 717 |
impl Document { |
| 718 |
pub fn from( |
| 719 |
text: Rope, |
| 720 |
encoding_with_bom_info: Option<(&'static Encoding, bool)>, |
| 721 |
config: Arc<dyn DynAccess<Config>>, |
| 722 |
syn_loader: Arc<ArcSwap<syntax::Loader>>, |
| 723 |
) -> Self { |
| 724 |
let (encoding, has_bom) = encoding_with_bom_info.unwrap_or((encoding::UTF_8, false)); |
| 725 |
let line_ending = config.load().default_line_ending.into(); |
| 726 |
let changes = ChangeSet::new(text.slice(..)); |
| 727 |
let old_state = None; |
| 728 |
|
| 729 |
Self { |
| 730 |
id: DocumentId::default(), |
| 731 |
active_snippet: None, |
| 732 |
path: None, |
| 733 |
relative_path: OnceCell::new(), |
| 734 |
workspace_root: OnceCell::new(), |
| 735 |
encoding, |
| 736 |
has_bom, |
| 737 |
text, |
| 738 |
selections: HashMap::default(), |
| 739 |
inlay_hints: HashMap::default(), |
| 740 |
inlay_hints_oudated: false, |
| 741 |
view_data: Default::default(), |
| 742 |
indent_style: DEFAULT_INDENT, |
| 743 |
editor_config: EditorConfig::default(), |
| 744 |
line_ending, |
| 745 |
restore_cursor: false, |
| 746 |
syntax: None, |
| 747 |
language: None, |
| 748 |
changes, |
| 749 |
old_state, |
| 750 |
diagnostics: Vec::new(), |
| 751 |
version: 0, |
| 752 |
history: Cell::new(History::default()), |
| 753 |
savepoints: Vec::new(), |
| 754 |
last_saved_time: SystemTime::now(), |
| 755 |
last_saved_revision: 0, |
| 756 |
modified_since_accessed: false, |
| 757 |
language_servers: HashMap::new(), |
| 758 |
diff_handle: None, |
| 759 |
config, |
| 760 |
version_control_head: None, |
| 761 |
focused_at: std::time::Instant::now(), |
| 762 |
readonly: false, |
| 763 |
jump_labels: HashMap::new(), |
| 764 |
document_highlights: HashMap::new(), |
| 765 |
code_action_hints: HashSet::new(), |
| 766 |
color_swatches: None, |
| 767 |
document_links: Vec::new(), |
| 768 |
color_swatch_controller: TaskController::new(), |
| 769 |
document_highlight_controllers: HashMap::new(), |
| 770 |
code_action_controllers: HashMap::new(), |
| 771 |
syn_loader, |
| 772 |
previous_diagnostic_ids: HashMap::new(), |
| 773 |
pull_diagnostic_controller: TaskController::new(), |
| 774 |
document_link_controller: TaskController::new(), |
| 775 |
} |
| 776 |
} |
| 777 |
|
| 778 |
pub fn default( |
| 779 |
config: Arc<dyn DynAccess<Config>>, |
| 780 |
syn_loader: Arc<ArcSwap<syntax::Loader>>, |
| 781 |
) -> Self { |
| 782 |
let line_ending: LineEnding = config.load().default_line_ending.into(); |
| 783 |
let text = Rope::from(line_ending.as_str()); |
| 784 |
Self::from(text, None, config, syn_loader) |
| 785 |
} |
| 786 |
|
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
pub fn open( |
| 791 |
path: &Path, |
| 792 |
mut encoding: Option<&'static Encoding>, |
| 793 |
detect_language: bool, |
| 794 |
config: Arc<dyn DynAccess<Config>>, |
| 795 |
syn_loader: Arc<ArcSwap<syntax::Loader>>, |
| 796 |
) -> Result<Self, DocumentOpenError> { |
| 797 |
|
| 798 |
if path.metadata().is_ok_and(|metadata| !metadata.is_file()) { |
| 799 |
return Err(DocumentOpenError::IrregularFile); |
| 800 |
} |
| 801 |
|
| 802 |
let editor_config = if config.load().editor_config { |
| 803 |
EditorConfig::find(path) |
| 804 |
} else { |
| 805 |
EditorConfig::default() |
| 806 |
}; |
| 807 |
encoding = encoding.or(editor_config.encoding); |
| 808 |
|
| 809 |
|
| 810 |
let (rope, encoding, has_bom) = if path.exists() { |
| 811 |
let mut file = std::fs::File::open(path)?; |
| 812 |
from_reader(&mut file, encoding)? |
| 813 |
} else { |
| 814 |
let line_ending = editor_config |
| 815 |
.line_ending |
| 816 |
.unwrap_or_else(|| config.load().default_line_ending.into()); |
| 817 |
let encoding = encoding.unwrap_or(encoding::UTF_8); |
| 818 |
(Rope::from(line_ending.as_str()), encoding, false) |
| 819 |
}; |
| 820 |
|
| 821 |
let loader = syn_loader.load(); |
| 822 |
let mut doc = Self::from(rope, Some((encoding, has_bom)), config, syn_loader); |
| 823 |
|
| 824 |
|
| 825 |
doc.set_path(Some(path)); |
| 826 |
if detect_language { |
| 827 |
doc.detect_language(&loader); |
| 828 |
} |
| 829 |
|
| 830 |
doc.editor_config = editor_config; |
| 831 |
doc.detect_indent_and_line_ending(); |
| 832 |
|
| 833 |
Ok(doc) |
| 834 |
} |
| 835 |
|
| 836 |
|
| 837 |
|
| 838 |
pub fn auto_format( |
| 839 |
&self, |
| 840 |
editor: &Editor, |
| 841 |
) -> Option<BoxFuture<'static, Result<Transaction, FormatterError>>> { |
| 842 |
if self.language_config()?.auto_format { |
| 843 |
self.format(editor) |
| 844 |
} else { |
| 845 |
None |
| 846 |
} |
| 847 |
} |
| 848 |
|
| 849 |
|
| 850 |
|
| 851 |
|
| 852 |
|
| 853 |
pub fn format( |
| 854 |
&self, |
| 855 |
editor: &Editor, |
| 856 |
) -> Option<BoxFuture<'static, Result<Transaction, FormatterError>>> { |
| 857 |
if let Some((fmt_cmd, fmt_args)) = self |
| 858 |
.language_config() |
| 859 |
.and_then(|c| c.formatter.as_ref()) |
| 860 |
.and_then(|formatter| { |
| 861 |
Some(( |
| 862 |
helix_stdx::env::which(&formatter.command).ok()?, |
| 863 |
&formatter.args, |
| 864 |
)) |
| 865 |
}) |
| 866 |
{ |
| 867 |
log::debug!( |
| 868 |
"formatting '{}' with command '{}', args {fmt_args:?}", |
| 869 |
self.display_name(), |
| 870 |
fmt_cmd.display(), |
| 871 |
); |
| 872 |
use std::process::Stdio; |
| 873 |
let text = self.text().clone(); |
| 874 |
|
| 875 |
let mut process = tokio::process::Command::new(&fmt_cmd); |
| 876 |
|
| 877 |
if let Some(doc_dir) = self.path.as_ref().and_then(|path| path.parent()) { |
| 878 |
process.current_dir(doc_dir); |
| 879 |
} |
| 880 |
|
| 881 |
let args = match fmt_args |
| 882 |
.iter() |
| 883 |
.map(|content| expansion::expand(editor, Token::expand(content))) |
| 884 |
.collect::<Result<Vec<_>, _>>() |
| 885 |
{ |
| 886 |
Ok(args) => args, |
| 887 |
Err(err) => { |
| 888 |
log::error!("Failed to expand formatter arguments: {err}"); |
| 889 |
return None; |
| 890 |
} |
| 891 |
}; |
| 892 |
|
| 893 |
process |
| 894 |
.args(args.iter().map(AsRef::as_ref)) |
| 895 |
.stdin(Stdio::piped()) |
| 896 |
.stdout(Stdio::piped()) |
| 897 |
.stderr(Stdio::piped()); |
| 898 |
|
| 899 |
let formatting_future = async move { |
| 900 |
let mut process = process |
| 901 |
.spawn() |
| 902 |
.map_err(|e| FormatterError::SpawningFailed { |
| 903 |
command: fmt_cmd.to_string_lossy().into(), |
| 904 |
error: e.kind(), |
| 905 |
})?; |
| 906 |
|
| 907 |
let mut stdin = process.stdin.take().ok_or(FormatterError::BrokenStdin)?; |
| 908 |
let input_text = text.clone(); |
| 909 |
let input_task = tokio::spawn(async move { |
| 910 |
to_writer(&mut stdin, (encoding::UTF_8, false), &input_text).await |
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
}); |
| 915 |
let (input_result, output_result) = tokio::join! { |
| 916 |
input_task, |
| 917 |
process.wait_with_output(), |
| 918 |
}; |
| 919 |
let _ = input_result.map_err(|_| FormatterError::BrokenStdin)?; |
| 920 |
let output = output_result.map_err(|_| FormatterError::WaitForOutputFailed)?; |
| 921 |
|
| 922 |
if !output.status.success() { |
| 923 |
if !output.stderr.is_empty() { |
| 924 |
let err = String::from_utf8_lossy(&output.stderr).to_string(); |
| 925 |
log::error!("Formatter error: {}", err); |
| 926 |
return Err(FormatterError::NonZeroExitStatus(Some(err))); |
| 927 |
} |
| 928 |
|
| 929 |
return Err(FormatterError::NonZeroExitStatus(None)); |
| 930 |
} else if !output.stderr.is_empty() { |
| 931 |
log::debug!( |
| 932 |
"Formatter printed to stderr: {}", |
| 933 |
String::from_utf8_lossy(&output.stderr) |
| 934 |
); |
| 935 |
} |
| 936 |
|
| 937 |
let str = std::str::from_utf8(&output.stdout) |
| 938 |
.map_err(|_| FormatterError::InvalidUtf8Output)?; |
| 939 |
|
| 940 |
Ok(helix_core::diff::compare_ropes(&text, &Rope::from(str))) |
| 941 |
}; |
| 942 |
return Some(formatting_future.boxed()); |
| 943 |
}; |
| 944 |
|
| 945 |
let text = self.text.clone(); |
| 946 |
|
| 947 |
let language_server = self |
| 948 |
.language_servers_with_feature(LanguageServerFeature::Format) |
| 949 |
.next()?; |
| 950 |
let offset_encoding = language_server.offset_encoding(); |
| 951 |
let request = language_server.text_document_formatting( |
| 952 |
self.identifier(), |
| 953 |
lsp::FormattingOptions { |
| 954 |
tab_size: self.tab_width() as u32, |
| 955 |
insert_spaces: matches!(self.indent_style, IndentStyle::Spaces(_)), |
| 956 |
..Default::default() |
| 957 |
}, |
| 958 |
None, |
| 959 |
)?; |
| 960 |
|
| 961 |
let fut = async move { |
| 962 |
let edits = request |
| 963 |
.await |
| 964 |
.unwrap_or_else(|e| { |
| 965 |
log::warn!("LSP formatting failed: {}", e); |
| 966 |
Default::default() |
| 967 |
}) |
| 968 |
.unwrap_or_default(); |
| 969 |
Ok(helix_lsp::util::generate_transaction_from_edits( |
| 970 |
&text, |
| 971 |
edits, |
| 972 |
offset_encoding, |
| 973 |
)) |
| 974 |
}; |
| 975 |
Some(fut.boxed()) |
| 976 |
} |
| 977 |
|
| 978 |
pub fn save<P: Into<PathBuf>>( |
| 979 |
&mut self, |
| 980 |
path: Option<P>, |
| 981 |
force: bool, |
| 982 |
) -> Result< |
| 983 |
impl Future<Output = Result<DocumentSavedEvent, anyhow::Error>> + 'static + Send, |
| 984 |
anyhow::Error, |
| 985 |
> { |
| 986 |
let path = path.map(|path| path.into()); |
| 987 |
self.save_impl(path, force) |
| 988 |
|
| 989 |
|
| 990 |
} |
| 991 |
|
| 992 |
|
| 993 |
|
| 994 |
fn save_impl( |
| 995 |
&mut self, |
| 996 |
path: Option<PathBuf>, |
| 997 |
force: bool, |
| 998 |
) -> Result< |
| 999 |
impl Future<Output = Result<DocumentSavedEvent, anyhow::Error>> + 'static + Send, |
| 1000 |
anyhow::Error, |
| 1001 |
> { |
| 1002 |
log::debug!( |
| 1003 |
"submitting save of doc '{:?}'", |
| 1004 |
self.path().map(|path| path.to_string_lossy()) |
| 1005 |
); |
| 1006 |
|
| 1007 |
|
| 1008 |
|
| 1009 |
let text = self.text().clone(); |
| 1010 |
|
| 1011 |
let path = match path { |
| 1012 |
Some(path) => helix_stdx::path::canonicalize(path), |
| 1013 |
None => { |
| 1014 |
if self.path.is_none() { |
| 1015 |
bail!("Can't save with no path set!"); |
| 1016 |
} |
| 1017 |
self.path.as_ref().unwrap().clone() |
| 1018 |
} |
| 1019 |
}; |
| 1020 |
|
| 1021 |
let identifier = self.path().map(|_| self.identifier()); |
| 1022 |
let language_servers: Vec<_> = self.language_servers.values().cloned().collect(); |
| 1023 |
|
| 1024 |
|
| 1025 |
let current_rev = self.get_current_revision(); |
| 1026 |
let doc_id = self.id(); |
| 1027 |
let atomic_save = self.config.load().atomic_save; |
| 1028 |
|
| 1029 |
let encoding_with_bom_info = (self.encoding, self.has_bom); |
| 1030 |
let last_saved_time = self.last_saved_time; |
| 1031 |
|
| 1032 |
|
| 1033 |
let future = async move { |
| 1034 |
use tokio::fs; |
| 1035 |
if let Some(parent) = path.parent() { |
| 1036 |
|
| 1037 |
if !parent.exists() { |
| 1038 |
if force { |
| 1039 |
std::fs::DirBuilder::new().recursive(true).create(parent)?; |
| 1040 |
} else { |
| 1041 |
bail!("can't save file, parent directory does not exist (use :w! to create it)"); |
| 1042 |
} |
| 1043 |
} |
| 1044 |
} |
| 1045 |
|
| 1046 |
|
| 1047 |
if !force { |
| 1048 |
if let Ok(metadata) = fs::metadata(&path).await { |
| 1049 |
if let Ok(mtime) = metadata.modified() { |
| 1050 |
if last_saved_time < mtime { |
| 1051 |
bail!("file modified by an external process, use :w! to overwrite"); |
| 1052 |
} |
| 1053 |
} |
| 1054 |
} |
| 1055 |
} |
| 1056 |
let write_path = tokio::fs::read_link(&path) |
| 1057 |
.await |
| 1058 |
.ok() |
| 1059 |
.and_then(|p| { |
| 1060 |
if p.is_relative() { |
| 1061 |
path.parent().map(|parent| parent.join(p)) |
| 1062 |
} else { |
| 1063 |
Some(p) |
| 1064 |
} |
| 1065 |
}) |
| 1066 |
.unwrap_or_else(|| path.clone()); |
| 1067 |
|
| 1068 |
if readonly(&write_path) { |
| 1069 |
bail!(std::io::Error::new( |
| 1070 |
std::io::ErrorKind::PermissionDenied, |
| 1071 |
"Path is read only" |
| 1072 |
)); |
| 1073 |
} |
| 1074 |
|
| 1075 |
|
| 1076 |
let is_hardlink = helix_stdx::faccess::hardlink_count(&write_path).unwrap_or(2) > 1; |
| 1077 |
let is_symlink = match tokio::fs::symlink_metadata(&write_path).await { |
| 1078 |
Ok(meta) => meta.is_symlink(), |
| 1079 |
Err(err) if err.kind() == std::io::ErrorKind::NotFound => false, |
| 1080 |
Err(err) => return Err(err.into()), |
| 1081 |
}; |
| 1082 |
let must_copy = is_hardlink || is_symlink; |
| 1083 |
let backup = if path.exists() && atomic_save { |
| 1084 |
let path_ = write_path.clone(); |
| 1085 |
|
| 1086 |
|
| 1087 |
|
| 1088 |
|
| 1089 |
|
| 1090 |
tokio::task::spawn_blocking(move || -> Option<PathBuf> { |
| 1091 |
let mut builder = tempfile::Builder::new(); |
| 1092 |
builder.prefix(path_.file_name()?).suffix(".bck"); |
| 1093 |
|
| 1094 |
let backup_path = if must_copy { |
| 1095 |
builder |
| 1096 |
.make_in(path_.parent()?, |backup| std::fs::copy(&path_, backup)) |
| 1097 |
.ok()? |
| 1098 |
.into_temp_path() |
| 1099 |
} else { |
| 1100 |
builder |
| 1101 |
.make_in(path_.parent()?, |backup| std::fs::rename(&path_, backup)) |
| 1102 |
.ok()? |
| 1103 |
.into_temp_path() |
| 1104 |
}; |
| 1105 |
|
| 1106 |
backup_path.keep().ok() |
| 1107 |
}) |
| 1108 |
.await |
| 1109 |
.ok() |
| 1110 |
.flatten() |
| 1111 |
} else { |
| 1112 |
None |
| 1113 |
}; |
| 1114 |
|
| 1115 |
let write_result: anyhow::Result<_> = async { |
| 1116 |
let mut dst = tokio::fs::File::create(&write_path).await?; |
| 1117 |
to_writer(&mut dst, encoding_with_bom_info, &text).await?; |
| 1118 |
|
| 1119 |
|
| 1120 |
match dst.sync_all().await { |
| 1121 |
Ok(_) => (), |
| 1122 |
Err(err) if err.kind() == io::ErrorKind::Unsupported => (), |
| 1123 |
|
| 1124 |
|
| 1125 |
|
| 1126 |
|
| 1127 |
#[allow(unreachable_patterns)] |
| 1128 |
#[cfg(unix)] |
| 1129 |
Err(err) |
| 1130 |
if matches!(err.raw_os_error(), Some(libc::ENOTSUP | libc::EOPNOTSUPP)) => { |
| 1131 |
} |
| 1132 |
Err(err) => return Err(err.into()), |
| 1133 |
} |
| 1134 |
Ok(()) |
| 1135 |
} |
| 1136 |
.await; |
| 1137 |
|
| 1138 |
let save_time = match fs::metadata(&write_path).await { |
| 1139 |
Ok(metadata) => metadata.modified().map_or(SystemTime::now(), |mtime| mtime), |
| 1140 |
Err(_) => SystemTime::now(), |
| 1141 |
}; |
| 1142 |
|
| 1143 |
if let Some(backup) = backup { |
| 1144 |
if must_copy { |
| 1145 |
let mut delete = true; |
| 1146 |
if write_result.is_err() { |
| 1147 |
|
| 1148 |
let _ = tokio::fs::copy(&backup, &write_path).await.map_err(|e| { |
| 1149 |
delete = false; |
| 1150 |
log::error!("Failed to restore backup on write failure: {e}") |
| 1151 |
}); |
| 1152 |
} |
| 1153 |
|
| 1154 |
if delete { |
| 1155 |
|
| 1156 |
let _ = tokio::fs::remove_file(backup) |
| 1157 |
.await |
| 1158 |
.map_err(|e| log::error!("Failed to remove backup file on write: {e}")); |
| 1159 |
} |
| 1160 |
} else if write_result.is_err() { |
| 1161 |
|
| 1162 |
let _ = tokio::fs::rename(&backup, &write_path) |
| 1163 |
.await |
| 1164 |
.map_err(|e| log::error!("Failed to restore backup on write failure: {e}")); |
| 1165 |
} else { |
| 1166 |
|
| 1167 |
let _ = tokio::task::spawn_blocking(move || { |
| 1168 |
let _ = copy_metadata(&backup, &write_path) |
| 1169 |
.map_err(|e| log::error!("Failed to copy metadata on write: {e}")); |
| 1170 |
let _ = std::fs::remove_file(backup) |
| 1171 |
.map_err(|e| log::error!("Failed to remove backup file on write: {e}")); |
| 1172 |
}) |
| 1173 |
.await; |
| 1174 |
} |
| 1175 |
} |
| 1176 |
|
| 1177 |
write_result?; |
| 1178 |
|
| 1179 |
let event = DocumentSavedEvent { |
| 1180 |
revision: current_rev, |
| 1181 |
save_time, |
| 1182 |
doc_id, |
| 1183 |
path, |
| 1184 |
text: text.clone(), |
| 1185 |
}; |
| 1186 |
|
| 1187 |
for language_server in language_servers { |
| 1188 |
if !language_server.is_initialized() { |
| 1189 |
continue; |
| 1190 |
} |
| 1191 |
if let Some(id) = identifier.clone() { |
| 1192 |
language_server.text_document_did_save(id, &text); |
| 1193 |
} |
| 1194 |
} |
| 1195 |
|
| 1196 |
Ok(event) |
| 1197 |
}; |
| 1198 |
|
| 1199 |
Ok(future) |
| 1200 |
} |
| 1201 |
|
| 1202 |
|
| 1203 |
pub fn detect_language(&mut self, loader: &syntax::Loader) { |
| 1204 |
self.set_language(self.detect_language_config(loader), loader); |
| 1205 |
} |
| 1206 |
|
| 1207 |
|
| 1208 |
pub fn detect_language_config( |
| 1209 |
&self, |
| 1210 |
loader: &syntax::Loader, |
| 1211 |
) -> Option<Arc<syntax::config::LanguageConfiguration>> { |
| 1212 |
let language = loader |
| 1213 |
.language_for_filename(self.path.as_ref()?) |
| 1214 |
.or_else(|| loader.language_for_shebang(self.text().slice(..)))?; |
| 1215 |
|
| 1216 |
Some(loader.language(language).config().clone()) |
| 1217 |
} |
| 1218 |
|
| 1219 |
|
| 1220 |
|
| 1221 |
|
| 1222 |
pub fn detect_indent_and_line_ending(&mut self) { |
| 1223 |
self.indent_style = if let Some(indent_style) = self.editor_config.indent_style { |
| 1224 |
indent_style |
| 1225 |
} else { |
| 1226 |
auto_detect_indent_style(&self.text).unwrap_or_else(|| { |
| 1227 |
self.language_config() |
| 1228 |
.and_then(|config| config.indent.as_ref()) |
| 1229 |
.map_or(DEFAULT_INDENT, |config| IndentStyle::from_str(&config.unit)) |
| 1230 |
}) |
| 1231 |
}; |
| 1232 |
if let Some(line_ending) = self |
| 1233 |
.editor_config |
| 1234 |
.line_ending |
| 1235 |
.or_else(|| auto_detect_line_ending(&self.text)) |
| 1236 |
{ |
| 1237 |
self.line_ending = line_ending; |
| 1238 |
} |
| 1239 |
} |
| 1240 |
|
| 1241 |
pub fn detect_editor_config(&mut self) { |
| 1242 |
if self.config.load().editor_config { |
| 1243 |
if let Some(path) = self.path.as_ref() { |
| 1244 |
self.editor_config = EditorConfig::find(path); |
| 1245 |
} |
| 1246 |
} |
| 1247 |
} |
| 1248 |
|
| 1249 |
pub fn pickup_last_saved_time(&mut self) { |
| 1250 |
self.last_saved_time = match self.path() { |
| 1251 |
Some(path) => match path.metadata() { |
| 1252 |
Ok(metadata) => match metadata.modified() { |
| 1253 |
Ok(mtime) => mtime, |
| 1254 |
Err(err) => { |
| 1255 |
log::debug!("Could not fetch file system's mtime, falling back to current system time: {}", err); |
| 1256 |
SystemTime::now() |
| 1257 |
} |
| 1258 |
}, |
| 1259 |
Err(err) => { |
| 1260 |
log::debug!("Could not fetch file system's mtime, falling back to current system time: {}", err); |
| 1261 |
SystemTime::now() |
| 1262 |
} |
| 1263 |
}, |
| 1264 |
None => SystemTime::now(), |
| 1265 |
}; |
| 1266 |
} |
| 1267 |
|
| 1268 |
|
| 1269 |
pub fn detect_readonly(&mut self) { |
| 1270 |
|
| 1271 |
self.readonly = match &self.path { |
| 1272 |
None => false, |
| 1273 |
Some(p) => readonly(p), |
| 1274 |
}; |
| 1275 |
} |
| 1276 |
|
| 1277 |
|
| 1278 |
pub fn reload( |
| 1279 |
&mut self, |
| 1280 |
view: &mut View, |
| 1281 |
provider_registry: &DiffProviderRegistry, |
| 1282 |
trust_full: bool, |
| 1283 |
) -> Result<(), Error> { |
| 1284 |
let encoding = self.encoding; |
| 1285 |
let path = match self.path() { |
| 1286 |
None => return Ok(()), |
| 1287 |
Some(path) => match path.exists() { |
| 1288 |
true => path.to_owned(), |
| 1289 |
false => bail!("can't find file to reload from {:?}", self.display_name()), |
| 1290 |
}, |
| 1291 |
}; |
| 1292 |
|
| 1293 |
|
| 1294 |
self.detect_readonly(); |
| 1295 |
|
| 1296 |
let mut file = std::fs::File::open(&path)?; |
| 1297 |
let (rope, ..) = from_reader(&mut file, Some(encoding))?; |
| 1298 |
|
| 1299 |
|
| 1300 |
|
| 1301 |
|
| 1302 |
let transaction = helix_core::diff::compare_ropes(self.text(), &rope); |
| 1303 |
self.apply(&transaction, view.id); |
| 1304 |
self.append_changes_to_history(view); |
| 1305 |
self.reset_modified(); |
| 1306 |
self.pickup_last_saved_time(); |
| 1307 |
self.detect_indent_and_line_ending(); |
| 1308 |
|
| 1309 |
match provider_registry.get_diff_base(&path, trust_full) { |
| 1310 |
Some(diff_base) => self.set_diff_base(diff_base), |
| 1311 |
None => self.diff_handle = None, |
| 1312 |
} |
| 1313 |
|
| 1314 |
self.version_control_head = provider_registry.get_current_head_name(&path, trust_full); |
| 1315 |
|
| 1316 |
Ok(()) |
| 1317 |
} |
| 1318 |
|
| 1319 |
|
| 1320 |
pub fn set_encoding(&mut self, label: &str) -> Result<(), Error> { |
| 1321 |
let encoding = |
| 1322 |
Encoding::for_label(label.as_bytes()).ok_or_else(|| anyhow!("unknown encoding"))?; |
| 1323 |
|
| 1324 |
self.encoding = encoding; |
| 1325 |
|
| 1326 |
Ok(()) |
| 1327 |
} |
| 1328 |
|
| 1329 |
|
| 1330 |
pub fn encoding(&self) -> &'static Encoding { |
| 1331 |
self.encoding |
| 1332 |
} |
| 1333 |
|
| 1334 |
|
| 1335 |
|
| 1336 |
|
| 1337 |
pub fn set_path(&mut self, path: Option<&Path>) { |
| 1338 |
let path = path.map(helix_stdx::path::canonicalize); |
| 1339 |
|
| 1340 |
|
| 1341 |
|
| 1342 |
self.relative_path.take(); |
| 1343 |
|
| 1344 |
self.workspace_root.take(); |
| 1345 |
|
| 1346 |
|
| 1347 |
|
| 1348 |
self.path = path; |
| 1349 |
|
| 1350 |
self.detect_readonly(); |
| 1351 |
self.pickup_last_saved_time(); |
| 1352 |
} |
| 1353 |
|
| 1354 |
|
| 1355 |
|
| 1356 |
pub fn set_language( |
| 1357 |
&mut self, |
| 1358 |
language_config: Option<Arc<syntax::config::LanguageConfiguration>>, |
| 1359 |
loader: &syntax::Loader, |
| 1360 |
) { |
| 1361 |
self.language = language_config; |
| 1362 |
self.syntax = self.language.as_ref().and_then(|config| { |
| 1363 |
Syntax::new(self.text.slice(..), config.language(), loader) |
| 1364 |
.map_err(|err| { |
| 1365 |
|
| 1366 |
|
| 1367 |
|
| 1368 |
if err != syntax::HighlighterError::NoRootConfig { |
| 1369 |
log::warn!("Error building syntax for '{}': {err}", self.display_name()); |
| 1370 |
} |
| 1371 |
}) |
| 1372 |
.ok() |
| 1373 |
}); |
| 1374 |
} |
| 1375 |
|
| 1376 |
|
| 1377 |
|
| 1378 |
pub fn set_language_by_language_id( |
| 1379 |
&mut self, |
| 1380 |
language_id: &str, |
| 1381 |
loader: &syntax::Loader, |
| 1382 |
) -> anyhow::Result<()> { |
| 1383 |
let language = loader |
| 1384 |
.language_for_name(language_id) |
| 1385 |
.ok_or_else(|| anyhow!("invalid language id: {}", language_id))?; |
| 1386 |
let config = loader.language(language).config().clone(); |
| 1387 |
self.set_language(Some(config), loader); |
| 1388 |
Ok(()) |
| 1389 |
} |
| 1390 |
|
| 1391 |
|
| 1392 |
pub fn set_selection(&mut self, view_id: ViewId, selection: Selection) { |
| 1393 |
|
| 1394 |
self.selections |
| 1395 |
.insert(view_id, selection.ensure_invariants(self.text().slice(..))); |
| 1396 |
helix_event::dispatch(SelectionDidChange { |
| 1397 |
doc: self, |
| 1398 |
view: view_id, |
| 1399 |
}) |
| 1400 |
} |
| 1401 |
|
| 1402 |
|
| 1403 |
|
| 1404 |
|
| 1405 |
pub fn origin(&self) -> Range { |
| 1406 |
if self.text().len_chars() == 0 { |
| 1407 |
return Range::new(0, 0); |
| 1408 |
} |
| 1409 |
|
| 1410 |
Range::new(0, 1).grapheme_aligned(self.text().slice(..)) |
| 1411 |
} |
| 1412 |
|
| 1413 |
|
| 1414 |
|
| 1415 |
pub fn reset_selection(&mut self, view_id: ViewId) { |
| 1416 |
let origin = self.origin(); |
| 1417 |
self.set_selection(view_id, Selection::single(origin.anchor, origin.head)); |
| 1418 |
} |
| 1419 |
|
| 1420 |
|
| 1421 |
|
| 1422 |
pub fn ensure_view_init(&mut self, view_id: ViewId) { |
| 1423 |
if !self.selections.contains_key(&view_id) { |
| 1424 |
self.reset_selection(view_id); |
| 1425 |
} |
| 1426 |
|
| 1427 |
self.view_data_mut(view_id); |
| 1428 |
} |
| 1429 |
|
| 1430 |
|
| 1431 |
pub fn mark_as_focused(&mut self) { |
| 1432 |
self.focused_at = std::time::Instant::now(); |
| 1433 |
} |
| 1434 |
|
| 1435 |
|
| 1436 |
pub fn remove_view(&mut self, view_id: ViewId) { |
| 1437 |
self.selections.remove(&view_id); |
| 1438 |
self.view_data.remove(&view_id); |
| 1439 |
self.inlay_hints.remove(&view_id); |
| 1440 |
self.jump_labels.remove(&view_id); |
| 1441 |
self.document_highlights.remove(&view_id); |
| 1442 |
self.document_highlight_controllers.remove(&view_id); |
| 1443 |
self.code_action_hints.remove(&view_id); |
| 1444 |
self.code_action_controllers.remove(&view_id); |
| 1445 |
} |
| 1446 |
|
| 1447 |
|
| 1448 |
fn apply_impl( |
| 1449 |
&mut self, |
| 1450 |
transaction: &Transaction, |
| 1451 |
view_id: ViewId, |
| 1452 |
emit_lsp_notification: bool, |
| 1453 |
) -> bool { |
| 1454 |
use helix_core::Assoc; |
| 1455 |
|
| 1456 |
let old_doc = self.text().clone(); |
| 1457 |
let changes = transaction.changes(); |
| 1458 |
if !changes.apply(&mut self.text) { |
| 1459 |
return false; |
| 1460 |
} |
| 1461 |
|
| 1462 |
if changes.is_empty() { |
| 1463 |
if let Some(selection) = transaction.selection() { |
| 1464 |
self.selections.insert( |
| 1465 |
view_id, |
| 1466 |
selection.clone().ensure_invariants(self.text.slice(..)), |
| 1467 |
); |
| 1468 |
helix_event::dispatch(SelectionDidChange { |
| 1469 |
doc: self, |
| 1470 |
view: view_id, |
| 1471 |
}); |
| 1472 |
} |
| 1473 |
return true; |
| 1474 |
} |
| 1475 |
|
| 1476 |
self.modified_since_accessed = true; |
| 1477 |
self.version += 1; |
| 1478 |
|
| 1479 |
for selection in self.selections.values_mut() { |
| 1480 |
*selection = selection |
| 1481 |
.clone() |
| 1482 |
|
| 1483 |
.map(transaction.changes()) |
| 1484 |
|
| 1485 |
.ensure_invariants(self.text.slice(..)); |
| 1486 |
} |
| 1487 |
|
| 1488 |
for view_data in self.view_data.values_mut() { |
| 1489 |
view_data.view_position.anchor = transaction |
| 1490 |
.changes() |
| 1491 |
.map_pos(view_data.view_position.anchor, Assoc::Before); |
| 1492 |
} |
| 1493 |
|
| 1494 |
|
| 1495 |
if !self.savepoints.is_empty() { |
| 1496 |
let revert = transaction.invert(&old_doc); |
| 1497 |
self.savepoints |
| 1498 |
.retain_mut(|save_point| match save_point.upgrade() { |
| 1499 |
Some(savepoint) => { |
| 1500 |
let mut revert_to_savepoint = savepoint.revert.lock(); |
| 1501 |
*revert_to_savepoint = |
| 1502 |
revert.clone().compose(mem::take(&mut revert_to_savepoint)); |
| 1503 |
true |
| 1504 |
} |
| 1505 |
None => false, |
| 1506 |
}) |
| 1507 |
} |
| 1508 |
|
| 1509 |
|
| 1510 |
if let Some(syntax) = &mut self.syntax { |
| 1511 |
let loader = self.syn_loader.load(); |
| 1512 |
if let Err(err) = syntax.update( |
| 1513 |
old_doc.slice(..), |
| 1514 |
self.text.slice(..), |
| 1515 |
transaction.changes(), |
| 1516 |
&loader, |
| 1517 |
) { |
| 1518 |
log::error!("TS parser failed, disabling TS for the current buffer: {err}"); |
| 1519 |
self.syntax = None; |
| 1520 |
} |
| 1521 |
} |
| 1522 |
|
| 1523 |
|
| 1524 |
|
| 1525 |
if let Some(diff_handle) = &self.diff_handle { |
| 1526 |
diff_handle.update_document(self.text.clone(), false); |
| 1527 |
} |
| 1528 |
|
| 1529 |
|
| 1530 |
changes.update_positions(self.diagnostics.iter_mut().map(|diagnostic| { |
| 1531 |
let assoc = if diagnostic.starts_at_word { |
| 1532 |
Assoc::BeforeWord |
| 1533 |
} else { |
| 1534 |
Assoc::After |
| 1535 |
}; |
| 1536 |
(&mut diagnostic.range.start, assoc) |
| 1537 |
})); |
| 1538 |
changes.update_positions(self.diagnostics.iter_mut().filter_map(|diagnostic| { |
| 1539 |
if diagnostic.zero_width { |
| 1540 |
|
| 1541 |
|
| 1542 |
return None; |
| 1543 |
} |
| 1544 |
let assoc = if diagnostic.ends_at_word { |
| 1545 |
Assoc::AfterWord |
| 1546 |
} else { |
| 1547 |
Assoc::Before |
| 1548 |
}; |
| 1549 |
Some((&mut diagnostic.range.end, assoc)) |
| 1550 |
})); |
| 1551 |
self.diagnostics.retain_mut(|diagnostic| { |
| 1552 |
if diagnostic.zero_width { |
| 1553 |
diagnostic.range.end = diagnostic.range.start |
| 1554 |
} else if diagnostic.range.start >= diagnostic.range.end { |
| 1555 |
return false; |
| 1556 |
} |
| 1557 |
diagnostic.line = self.text.char_to_line(diagnostic.range.start); |
| 1558 |
true |
| 1559 |
}); |
| 1560 |
|
| 1561 |
self.diagnostics.sort_by_key(|diagnostic| { |
| 1562 |
( |
| 1563 |
diagnostic.range, |
| 1564 |
diagnostic.severity, |
| 1565 |
diagnostic.provider.clone(), |
| 1566 |
) |
| 1567 |
}); |
| 1568 |
|
| 1569 |
|
| 1570 |
let apply_inlay_hint_changes = |annotations: &mut Vec<InlineAnnotation>| { |
| 1571 |
changes.update_positions( |
| 1572 |
annotations |
| 1573 |
.iter_mut() |
| 1574 |
.map(|annotation| (&mut annotation.char_idx, Assoc::After)), |
| 1575 |
); |
| 1576 |
}; |
| 1577 |
|
| 1578 |
self.inlay_hints_oudated = true; |
| 1579 |
for text_annotation in self.inlay_hints.values_mut() { |
| 1580 |
let DocumentInlayHints { |
| 1581 |
id: _, |
| 1582 |
type_inlay_hints, |
| 1583 |
parameter_inlay_hints, |
| 1584 |
other_inlay_hints, |
| 1585 |
padding_before_inlay_hints, |
| 1586 |
padding_after_inlay_hints, |
| 1587 |
} = text_annotation; |
| 1588 |
|
| 1589 |
apply_inlay_hint_changes(padding_before_inlay_hints); |
| 1590 |
apply_inlay_hint_changes(type_inlay_hints); |
| 1591 |
apply_inlay_hint_changes(parameter_inlay_hints); |
| 1592 |
apply_inlay_hint_changes(other_inlay_hints); |
| 1593 |
apply_inlay_hint_changes(padding_after_inlay_hints); |
| 1594 |
} |
| 1595 |
|
| 1596 |
for highlights in self.document_highlights.values_mut() { |
| 1597 |
let text_len = self.text.len_chars(); |
| 1598 |
let mut updated = Vec::with_capacity(highlights.ranges.len()); |
| 1599 |
for mut range in highlights.ranges.drain(..) { |
| 1600 |
changes.update_positions( |
| 1601 |
[ |
| 1602 |
(&mut range.start, Assoc::After), |
| 1603 |
(&mut range.end, Assoc::After), |
| 1604 |
] |
| 1605 |
.into_iter(), |
| 1606 |
); |
| 1607 |
if range.start >= text_len { |
| 1608 |
continue; |
| 1609 |
} |
| 1610 |
let end = range.end.min(text_len); |
| 1611 |
if range.start < end { |
| 1612 |
updated.push(range.start..end); |
| 1613 |
} |
| 1614 |
} |
| 1615 |
highlights.ranges = updated; |
| 1616 |
} |
| 1617 |
|
| 1618 |
helix_event::dispatch(DocumentDidChange { |
| 1619 |
doc: self, |
| 1620 |
view: view_id, |
| 1621 |
old_text: &old_doc, |
| 1622 |
changes, |
| 1623 |
ghost_transaction: !emit_lsp_notification, |
| 1624 |
}); |
| 1625 |
|
| 1626 |
|
| 1627 |
if let Some(selection) = transaction.selection() { |
| 1628 |
self.selections.insert( |
| 1629 |
view_id, |
| 1630 |
selection.clone().ensure_invariants(self.text.slice(..)), |
| 1631 |
); |
| 1632 |
helix_event::dispatch(SelectionDidChange { |
| 1633 |
doc: self, |
| 1634 |
view: view_id, |
| 1635 |
}); |
| 1636 |
} |
| 1637 |
|
| 1638 |
true |
| 1639 |
} |
| 1640 |
|
| 1641 |
fn apply_inner( |
| 1642 |
&mut self, |
| 1643 |
transaction: &Transaction, |
| 1644 |
view_id: ViewId, |
| 1645 |
emit_lsp_notification: bool, |
| 1646 |
) -> bool { |
| 1647 |
|
| 1648 |
|
| 1649 |
if self.changes.is_empty() && !transaction.changes().is_empty() { |
| 1650 |
self.old_state = Some(State { |
| 1651 |
doc: self.text.clone(), |
| 1652 |
selection: self.selection(view_id).clone(), |
| 1653 |
}); |
| 1654 |
} |
| 1655 |
|
| 1656 |
let success = self.apply_impl(transaction, view_id, emit_lsp_notification); |
| 1657 |
|
| 1658 |
if !transaction.changes().is_empty() { |
| 1659 |
|
| 1660 |
take_with(&mut self.changes, |changes| { |
| 1661 |
changes.compose(transaction.changes().clone()) |
| 1662 |
}); |
| 1663 |
} |
| 1664 |
success |
| 1665 |
} |
| 1666 |
|
| 1667 |
pub fn apply(&mut self, transaction: &Transaction, view_id: ViewId) -> bool { |
| 1668 |
self.apply_inner(transaction, view_id, true) |
| 1669 |
} |
| 1670 |
|
| 1671 |
|
| 1672 |
|
| 1673 |
|
| 1674 |
pub fn apply_temporary(&mut self, transaction: &Transaction, view_id: ViewId) -> bool { |
| 1675 |
self.apply_inner(transaction, view_id, false) |
| 1676 |
} |
| 1677 |
|
| 1678 |
fn undo_redo_impl(&mut self, view: &mut View, undo: bool) -> bool { |
| 1679 |
if undo { |
| 1680 |
self.append_changes_to_history(view); |
| 1681 |
} else if !self.changes.is_empty() { |
| 1682 |
return false; |
| 1683 |
} |
| 1684 |
let mut history = self.history.take(); |
| 1685 |
let txn = if undo { history.undo() } else { history.redo() }; |
| 1686 |
let success = if let Some(txn) = txn { |
| 1687 |
self.apply_impl(txn, view.id, true) |
| 1688 |
} else { |
| 1689 |
false |
| 1690 |
}; |
| 1691 |
self.history.set(history); |
| 1692 |
|
| 1693 |
if success { |
| 1694 |
|
| 1695 |
self.changes = ChangeSet::new(self.text().slice(..)); |
| 1696 |
|
| 1697 |
view.sync_changes(self); |
| 1698 |
} |
| 1699 |
success |
| 1700 |
} |
| 1701 |
|
| 1702 |
|
| 1703 |
pub fn undo(&mut self, view: &mut View) -> bool { |
| 1704 |
self.undo_redo_impl(view, true) |
| 1705 |
} |
| 1706 |
|
| 1707 |
|
| 1708 |
pub fn redo(&mut self, view: &mut View) -> bool { |
| 1709 |
self.undo_redo_impl(view, false) |
| 1710 |
} |
| 1711 |
|
| 1712 |
|
| 1713 |
|
| 1714 |
|
| 1715 |
|
| 1716 |
|
| 1717 |
pub fn savepoint(&mut self, view: &View) -> Arc<SavePoint> { |
| 1718 |
let revert = Transaction::new(self.text()).with_selection(self.selection(view.id).clone()); |
| 1719 |
|
| 1720 |
if let Some(savepoint) = self |
| 1721 |
.savepoints |
| 1722 |
.iter() |
| 1723 |
.rev() |
| 1724 |
.find_map(|savepoint| savepoint.upgrade()) |
| 1725 |
{ |
| 1726 |
let transaction = savepoint.revert.lock(); |
| 1727 |
if savepoint.view == view.id |
| 1728 |
&& transaction.changes().is_empty() |
| 1729 |
&& transaction.selection() == revert.selection() |
| 1730 |
{ |
| 1731 |
drop(transaction); |
| 1732 |
return savepoint; |
| 1733 |
} |
| 1734 |
} |
| 1735 |
let savepoint = Arc::new(SavePoint { |
| 1736 |
view: view.id, |
| 1737 |
revert: Mutex::new(revert), |
| 1738 |
}); |
| 1739 |
self.savepoints.push(Arc::downgrade(&savepoint)); |
| 1740 |
savepoint |
| 1741 |
} |
| 1742 |
|
| 1743 |
pub fn restore(&mut self, view: &mut View, savepoint: &SavePoint, emit_lsp_notification: bool) { |
| 1744 |
assert_eq!( |
| 1745 |
savepoint.view, view.id, |
| 1746 |
"Savepoint must not be used with a different view!" |
| 1747 |
); |
| 1748 |
|
| 1749 |
|
| 1750 |
let savepoint_idx = self |
| 1751 |
.savepoints |
| 1752 |
.iter() |
| 1753 |
.position(|savepoint_ref| std::ptr::eq(savepoint_ref.as_ptr(), savepoint)) |
| 1754 |
.expect("Savepoint must belong to this document"); |
| 1755 |
|
| 1756 |
let savepoint_ref = self.savepoints.remove(savepoint_idx); |
| 1757 |
let mut revert = savepoint.revert.lock(); |
| 1758 |
self.apply_inner(&revert, view.id, emit_lsp_notification); |
| 1759 |
*revert = Transaction::new(self.text()).with_selection(self.selection(view.id).clone()); |
| 1760 |
self.savepoints.push(savepoint_ref) |
| 1761 |
} |
| 1762 |
|
| 1763 |
fn earlier_later_impl(&mut self, view: &mut View, uk: UndoKind, earlier: bool) -> bool { |
| 1764 |
if earlier { |
| 1765 |
self.append_changes_to_history(view); |
| 1766 |
} else if !self.changes.is_empty() { |
| 1767 |
return false; |
| 1768 |
} |
| 1769 |
let txns = if earlier { |
| 1770 |
self.history.get_mut().earlier(uk) |
| 1771 |
} else { |
| 1772 |
self.history.get_mut().later(uk) |
| 1773 |
}; |
| 1774 |
let mut success = false; |
| 1775 |
for txn in txns { |
| 1776 |
if self.apply_impl(&txn, view.id, true) { |
| 1777 |
success = true; |
| 1778 |
} |
| 1779 |
} |
| 1780 |
if success { |
| 1781 |
|
| 1782 |
self.changes = ChangeSet::new(self.text().slice(..)); |
| 1783 |
|
| 1784 |
view.sync_changes(self); |
| 1785 |
} |
| 1786 |
success |
| 1787 |
} |
| 1788 |
|
| 1789 |
|
| 1790 |
pub fn earlier(&mut self, view: &mut View, uk: UndoKind) -> bool { |
| 1791 |
self.earlier_later_impl(view, uk, true) |
| 1792 |
} |
| 1793 |
|
| 1794 |
|
| 1795 |
pub fn later(&mut self, view: &mut View, uk: UndoKind) -> bool { |
| 1796 |
self.earlier_later_impl(view, uk, false) |
| 1797 |
} |
| 1798 |
|
| 1799 |
|
| 1800 |
pub fn append_changes_to_history(&mut self, view: &mut View) { |
| 1801 |
if self.changes.is_empty() { |
| 1802 |
return; |
| 1803 |
} |
| 1804 |
|
| 1805 |
let new_changeset = ChangeSet::new(self.text().slice(..)); |
| 1806 |
let changes = std::mem::replace(&mut self.changes, new_changeset); |
| 1807 |
|
| 1808 |
|
| 1809 |
let transaction = |
| 1810 |
Transaction::from(changes).with_selection(self.selection(view.id).clone()); |
| 1811 |
|
| 1812 |
|
| 1813 |
let old_state = self.old_state.take().expect("no old_state available"); |
| 1814 |
|
| 1815 |
let mut history = self.history.take(); |
| 1816 |
history.commit_revision(&transaction, &old_state); |
| 1817 |
self.history.set(history); |
| 1818 |
|
| 1819 |
|
| 1820 |
view.apply(&transaction, self); |
| 1821 |
} |
| 1822 |
|
| 1823 |
pub fn id(&self) -> DocumentId { |
| 1824 |
self.id |
| 1825 |
} |
| 1826 |
|
| 1827 |
|
| 1828 |
pub fn is_modified(&self) -> bool { |
| 1829 |
let history = self.history.take(); |
| 1830 |
let current_revision = history.current_revision(); |
| 1831 |
self.history.set(history); |
| 1832 |
log::debug!( |
| 1833 |
"id {} modified - last saved: {}, current: {}", |
| 1834 |
self.id, |
| 1835 |
self.last_saved_revision, |
| 1836 |
current_revision |
| 1837 |
); |
| 1838 |
current_revision != self.last_saved_revision || !self.changes.is_empty() |
| 1839 |
} |
| 1840 |
|
| 1841 |
|
| 1842 |
pub fn reset_modified(&mut self) { |
| 1843 |
let history = self.history.take(); |
| 1844 |
let current_revision = history.current_revision(); |
| 1845 |
self.history.set(history); |
| 1846 |
self.last_saved_revision = current_revision; |
| 1847 |
} |
| 1848 |
|
| 1849 |
|
| 1850 |
pub fn set_last_saved_revision(&mut self, rev: usize, save_time: SystemTime) { |
| 1851 |
log::debug!( |
| 1852 |
"doc {} revision updated {} -> {}", |
| 1853 |
self.id, |
| 1854 |
self.last_saved_revision, |
| 1855 |
rev |
| 1856 |
); |
| 1857 |
self.last_saved_revision = rev; |
| 1858 |
self.last_saved_time = save_time; |
| 1859 |
} |
| 1860 |
|
| 1861 |
|
| 1862 |
pub fn get_last_saved_revision(&mut self) -> usize { |
| 1863 |
self.last_saved_revision |
| 1864 |
} |
| 1865 |
|
| 1866 |
|
| 1867 |
pub fn get_current_revision(&mut self) -> usize { |
| 1868 |
let history = self.history.take(); |
| 1869 |
let current_revision = history.current_revision(); |
| 1870 |
self.history.set(history); |
| 1871 |
current_revision |
| 1872 |
} |
| 1873 |
|
| 1874 |
|
| 1875 |
pub fn language_scope(&self) -> Option<&str> { |
| 1876 |
self.language |
| 1877 |
.as_ref() |
| 1878 |
.map(|language| language.scope.as_str()) |
| 1879 |
} |
| 1880 |
|
| 1881 |
|
| 1882 |
|
| 1883 |
pub fn language_name(&self) -> Option<&str> { |
| 1884 |
self.language |
| 1885 |
.as_ref() |
| 1886 |
.map(|language| language.language_id.as_str()) |
| 1887 |
} |
| 1888 |
|
| 1889 |
|
| 1890 |
|
| 1891 |
pub fn language_id(&self) -> Option<&str> { |
| 1892 |
self.language_config()? |
| 1893 |
.language_server_language_id |
| 1894 |
.as_deref() |
| 1895 |
.or_else(|| self.language_name()) |
| 1896 |
} |
| 1897 |
|
| 1898 |
|
| 1899 |
pub fn language_config(&self) -> Option<&LanguageConfiguration> { |
| 1900 |
self.language.as_deref() |
| 1901 |
} |
| 1902 |
|
| 1903 |
|
| 1904 |
|
| 1905 |
|
| 1906 |
pub fn language_config_at<'a>( |
| 1907 |
&'a self, |
| 1908 |
loader: &'a syntax::Loader, |
| 1909 |
byte_pos: usize, |
| 1910 |
) -> Option<&'a LanguageConfiguration> { |
| 1911 |
match self.syntax() { |
| 1912 |
Some(syntax) => { |
| 1913 |
let layer = syntax.layer_for_byte_range(byte_pos as u32, byte_pos as u32); |
| 1914 |
Some(&**loader.language(syntax.layer(layer).language).config()) |
| 1915 |
} |
| 1916 |
None => self.language_config(), |
| 1917 |
} |
| 1918 |
} |
| 1919 |
|
| 1920 |
|
| 1921 |
pub fn version(&self) -> i32 { |
| 1922 |
self.version |
| 1923 |
} |
| 1924 |
|
| 1925 |
pub fn word_completion_enabled(&self) -> bool { |
| 1926 |
self.language_config() |
| 1927 |
.and_then(|lang_config| lang_config.word_completion.and_then(|c| c.enable)) |
| 1928 |
.unwrap_or_else(|| self.config.load().word_completion.enable) |
| 1929 |
} |
| 1930 |
|
| 1931 |
pub fn path_completion_enabled(&self) -> bool { |
| 1932 |
self.language_config() |
| 1933 |
.and_then(|lang_config| lang_config.path_completion) |
| 1934 |
.unwrap_or_else(|| self.config.load().path_completion) |
| 1935 |
} |
| 1936 |
|
| 1937 |
|
| 1938 |
pub fn language_servers(&self) -> impl Iterator<Item = &helix_lsp::Client> { |
| 1939 |
self.language_config().into_iter().flat_map(move |config| { |
| 1940 |
config.language_servers.iter().filter_map(move |features| { |
| 1941 |
let ls = &**self.language_servers.get(&features.name)?; |
| 1942 |
if ls.is_initialized() { |
| 1943 |
Some(ls) |
| 1944 |
} else { |
| 1945 |
None |
| 1946 |
} |
| 1947 |
}) |
| 1948 |
}) |
| 1949 |
} |
| 1950 |
|
| 1951 |
pub fn remove_language_server_by_name(&mut self, name: &str) -> Option<Arc<Client>> { |
| 1952 |
self.language_servers.remove(name) |
| 1953 |
} |
| 1954 |
|
| 1955 |
pub fn language_servers_with_feature( |
| 1956 |
&self, |
| 1957 |
feature: LanguageServerFeature, |
| 1958 |
) -> impl Iterator<Item = &helix_lsp::Client> { |
| 1959 |
self.language_config().into_iter().flat_map(move |config| { |
| 1960 |
config.language_servers.iter().filter_map(move |features| { |
| 1961 |
let ls = &**self.language_servers.get(&features.name)?; |
| 1962 |
if ls.is_initialized() |
| 1963 |
&& ls.supports_feature(feature) |
| 1964 |
&& features.has_feature(feature) |
| 1965 |
{ |
| 1966 |
Some(ls) |
| 1967 |
} else { |
| 1968 |
None |
| 1969 |
} |
| 1970 |
}) |
| 1971 |
}) |
| 1972 |
} |
| 1973 |
|
| 1974 |
pub fn supports_language_server(&self, id: LanguageServerId) -> bool { |
| 1975 |
self.language_servers().any(|l| l.id() == id) |
| 1976 |
} |
| 1977 |
|
| 1978 |
pub fn diff_handle(&self) -> Option<&DiffHandle> { |
| 1979 |
self.diff_handle.as_ref() |
| 1980 |
} |
| 1981 |
|
| 1982 |
|
| 1983 |
pub fn set_diff_base(&mut self, diff_base: Vec<u8>) { |
| 1984 |
if let Ok((diff_base, ..)) = from_reader(&mut diff_base.as_slice(), Some(self.encoding)) { |
| 1985 |
if let Some(differ) = &self.diff_handle { |
| 1986 |
differ.update_diff_base(diff_base); |
| 1987 |
return; |
| 1988 |
} |
| 1989 |
self.diff_handle = Some(DiffHandle::new(diff_base, self.text.clone())) |
| 1990 |
} else { |
| 1991 |
self.diff_handle = None; |
| 1992 |
} |
| 1993 |
} |
| 1994 |
|
| 1995 |
pub fn version_control_head(&self) -> Option<Arc<Box<str>>> { |
| 1996 |
self.version_control_head.as_ref().map(|a| a.load_full()) |
| 1997 |
} |
| 1998 |
|
| 1999 |
pub fn set_version_control_head( |
| 2000 |
&mut self, |
| 2001 |
version_control_head: Option<Arc<ArcSwap<Box<str>>>>, |
| 2002 |
) { |
| 2003 |
self.version_control_head = version_control_head; |
| 2004 |
} |
| 2005 |
|
| 2006 |
#[inline] |
| 2007 |
|
| 2008 |
pub fn syntax(&self) -> Option<&Syntax> { |
| 2009 |
self.syntax.as_ref() |
| 2010 |
} |
| 2011 |
|
| 2012 |
|
| 2013 |
pub fn tab_width(&self) -> usize { |
| 2014 |
self.editor_config |
| 2015 |
.tab_width |
| 2016 |
.map(|n| n.get() as usize) |
| 2017 |
.unwrap_or_else(|| { |
| 2018 |
self.language_config() |
| 2019 |
.and_then(|config| config.indent.as_ref()) |
| 2020 |
.map_or(DEFAULT_TAB_WIDTH, |config| config.tab_width) |
| 2021 |
}) |
| 2022 |
} |
| 2023 |
|
| 2024 |
|
| 2025 |
pub fn indent_width(&self) -> usize { |
| 2026 |
self.indent_style.indent_width(self.tab_width()) |
| 2027 |
} |
| 2028 |
|
| 2029 |
|
| 2030 |
pub fn insert_final_newline(&self) -> bool { |
| 2031 |
self.editor_config |
| 2032 |
.insert_final_newline |
| 2033 |
.unwrap_or_else(|| self.config.load().insert_final_newline) |
| 2034 |
} |
| 2035 |
|
| 2036 |
|
| 2037 |
pub fn trim_trailing_whitespace(&self) -> bool { |
| 2038 |
self.editor_config |
| 2039 |
.trim_trailing_whitespace |
| 2040 |
.unwrap_or_else(|| self.config.load().trim_trailing_whitespace) |
| 2041 |
} |
| 2042 |
|
| 2043 |
pub fn changes(&self) -> &ChangeSet { |
| 2044 |
&self.changes |
| 2045 |
} |
| 2046 |
|
| 2047 |
#[inline] |
| 2048 |
|
| 2049 |
pub fn path(&self) -> Option<&Path> { |
| 2050 |
self.path.as_deref() |
| 2051 |
} |
| 2052 |
|
| 2053 |
|
| 2054 |
pub fn url(&self) -> Option<Url> { |
| 2055 |
Url::from_file_path(self.path()?).ok() |
| 2056 |
} |
| 2057 |
|
| 2058 |
pub fn uri(&self) -> Option<helix_core::Uri> { |
| 2059 |
Some(self.path()?.into()) |
| 2060 |
} |
| 2061 |
|
| 2062 |
#[inline] |
| 2063 |
pub fn text(&self) -> &Rope { |
| 2064 |
&self.text |
| 2065 |
} |
| 2066 |
|
| 2067 |
#[inline] |
| 2068 |
pub fn selection(&self, view_id: ViewId) -> &Selection { |
| 2069 |
&self.selections[&view_id] |
| 2070 |
} |
| 2071 |
|
| 2072 |
#[inline] |
| 2073 |
pub fn selections(&self) -> &HashMap<ViewId, Selection> { |
| 2074 |
&self.selections |
| 2075 |
} |
| 2076 |
|
| 2077 |
fn view_data(&self, view_id: ViewId) -> &ViewData { |
| 2078 |
self.view_data |
| 2079 |
.get(&view_id) |
| 2080 |
.expect("This should only be called after ensure_view_init") |
| 2081 |
} |
| 2082 |
|
| 2083 |
fn view_data_mut(&mut self, view_id: ViewId) -> &mut ViewData { |
| 2084 |
self.view_data.entry(view_id).or_default() |
| 2085 |
} |
| 2086 |
|
| 2087 |
pub(crate) fn get_view_offset(&self, view_id: ViewId) -> Option<ViewPosition> { |
| 2088 |
Some(self.view_data.get(&view_id)?.view_position) |
| 2089 |
} |
| 2090 |
|
| 2091 |
pub fn view_offset(&self, view_id: ViewId) -> ViewPosition { |
| 2092 |
self.view_data(view_id).view_position |
| 2093 |
} |
| 2094 |
|
| 2095 |
pub fn set_view_offset(&mut self, view_id: ViewId, new_offset: ViewPosition) { |
| 2096 |
self.view_data_mut(view_id).view_position = new_offset; |
| 2097 |
} |
| 2098 |
|
| 2099 |
pub fn relative_path(&self) -> Option<&Path> { |
| 2100 |
self.relative_path |
| 2101 |
.get_or_init(|| { |
| 2102 |
self.path |
| 2103 |
.as_ref() |
| 2104 |
.map(|path| helix_stdx::path::get_relative_path(path).to_path_buf()) |
| 2105 |
}) |
| 2106 |
.as_deref() |
| 2107 |
} |
| 2108 |
|
| 2109 |
`, |
| 2110 |
|
| 2111 |
|
| 2112 |
pub fn workspace_root(&self) -> &Path { |
| 2113 |
self.workspace_root |
| 2114 |
.get_or_init(|| match self.path.as_deref() { |
| 2115 |
Some(p) => p |
| 2116 |
.parent() |
| 2117 |
.map(|dir| helix_loader::find_workspace_in(dir).0) |
| 2118 |
.unwrap_or_else(|| helix_loader::find_workspace().0), |
| 2119 |
None => helix_loader::find_workspace().0, |
| 2120 |
}) |
| 2121 |
} |
| 2122 |
|
| 2123 |
pub fn display_name(&self) -> Cow<'_, str> { |
| 2124 |
self.relative_path() |
| 2125 |
.map_or_else(|| SCRATCH_BUFFER_NAME.into(), |path| path.to_string_lossy()) |
| 2126 |
} |
| 2127 |
|
| 2128 |
|
| 2129 |
|
| 2130 |
|
| 2131 |
|
| 2132 |
#[inline] |
| 2133 |
pub fn identifier(&self) -> lsp::TextDocumentIdentifier { |
| 2134 |
lsp::TextDocumentIdentifier::new(self.url().unwrap()) |
| 2135 |
} |
| 2136 |
|
| 2137 |
pub fn versioned_identifier(&self) -> lsp::VersionedTextDocumentIdentifier { |
| 2138 |
lsp::VersionedTextDocumentIdentifier::new(self.url().unwrap(), self.version) |
| 2139 |
} |
| 2140 |
|
| 2141 |
pub fn position( |
| 2142 |
&self, |
| 2143 |
view_id: ViewId, |
| 2144 |
offset_encoding: helix_lsp::OffsetEncoding, |
| 2145 |
) -> lsp::Position { |
| 2146 |
let text = self.text(); |
| 2147 |
|
| 2148 |
helix_lsp::util::pos_to_lsp_pos( |
| 2149 |
text, |
| 2150 |
self.selection(view_id).primary().cursor(text.slice(..)), |
| 2151 |
offset_encoding, |
| 2152 |
) |
| 2153 |
} |
| 2154 |
|
| 2155 |
pub fn lsp_diagnostic_to_diagnostic( |
| 2156 |
text: &Rope, |
| 2157 |
language_config: Option<&LanguageConfiguration>, |
| 2158 |
diagnostic: &helix_lsp::lsp::Diagnostic, |
| 2159 |
provider: DiagnosticProvider, |
| 2160 |
offset_encoding: helix_lsp::OffsetEncoding, |
| 2161 |
) -> Option<Diagnostic> { |
| 2162 |
use helix_core::diagnostic::{Range, Severity::*}; |
| 2163 |
|
| 2164 |
|
| 2165 |
let start = |
| 2166 |
if let Some(start) = lsp_pos_to_pos(text, diagnostic.range.start, offset_encoding) { |
| 2167 |
start |
| 2168 |
} else { |
| 2169 |
log::warn!("lsp position out of bounds - {:?}", diagnostic); |
| 2170 |
return None; |
| 2171 |
}; |
| 2172 |
|
| 2173 |
let end = if let Some(end) = lsp_pos_to_pos(text, diagnostic.range.end, offset_encoding) { |
| 2174 |
end |
| 2175 |
} else { |
| 2176 |
log::warn!("lsp position out of bounds - {:?}", diagnostic); |
| 2177 |
return None; |
| 2178 |
}; |
| 2179 |
|
| 2180 |
let severity = diagnostic.severity.and_then(|severity| match severity { |
| 2181 |
lsp::DiagnosticSeverity::ERROR => Some(Error), |
| 2182 |
lsp::DiagnosticSeverity::WARNING => Some(Warning), |
| 2183 |
lsp::DiagnosticSeverity::INFORMATION => Some(Info), |
| 2184 |
lsp::DiagnosticSeverity::HINT => Some(Hint), |
| 2185 |
severity => { |
| 2186 |
log::error!("unrecognized diagnostic severity: {:?}", severity); |
| 2187 |
None |
| 2188 |
} |
| 2189 |
}); |
| 2190 |
|
| 2191 |
if let Some(lang_conf) = language_config { |
| 2192 |
if let Some(severity) = severity { |
| 2193 |
if severity < lang_conf.diagnostic_severity { |
| 2194 |
return None; |
| 2195 |
} |
| 2196 |
} |
| 2197 |
}; |
| 2198 |
use helix_core::diagnostic::{DiagnosticTag, NumberOrString}; |
| 2199 |
|
| 2200 |
let code = match diagnostic.code.clone() { |
| 2201 |
Some(x) => match x { |
| 2202 |
lsp::NumberOrString::Number(x) => Some(NumberOrString::Number(x)), |
| 2203 |
lsp::NumberOrString::String(x) => Some(NumberOrString::String(x)), |
| 2204 |
}, |
| 2205 |
None => None, |
| 2206 |
}; |
| 2207 |
|
| 2208 |
let tags = if let Some(tags) = &diagnostic.tags { |
| 2209 |
let new_tags = tags |
| 2210 |
.iter() |
| 2211 |
.filter_map(|tag| match *tag { |
| 2212 |
lsp::DiagnosticTag::DEPRECATED => Some(DiagnosticTag::Deprecated), |
| 2213 |
lsp::DiagnosticTag::UNNECESSARY => Some(DiagnosticTag::Unnecessary), |
| 2214 |
_ => None, |
| 2215 |
}) |
| 2216 |
.collect(); |
| 2217 |
|
| 2218 |
new_tags |
| 2219 |
} else { |
| 2220 |
Vec::new() |
| 2221 |
}; |
| 2222 |
|
| 2223 |
let ends_at_word = |
| 2224 |
start != end && end != 0 && text.get_char(end - 1).is_some_and(char_is_word); |
| 2225 |
let starts_at_word = start != end && text.get_char(start).is_some_and(char_is_word); |
| 2226 |
|
| 2227 |
Some(Diagnostic { |
| 2228 |
range: Range { start, end }, |
| 2229 |
ends_at_word, |
| 2230 |
starts_at_word, |
| 2231 |
zero_width: start == end, |
| 2232 |
line: diagnostic.range.start.line as usize, |
| 2233 |
message: diagnostic.message.clone(), |
| 2234 |
severity, |
| 2235 |
code, |
| 2236 |
tags, |
| 2237 |
source: diagnostic.source.clone(), |
| 2238 |
data: diagnostic.data.clone(), |
| 2239 |
provider, |
| 2240 |
}) |
| 2241 |
} |
| 2242 |
|
| 2243 |
#[inline] |
| 2244 |
pub fn diagnostics(&self) -> &[Diagnostic] { |
| 2245 |
&self.diagnostics |
| 2246 |
} |
| 2247 |
|
| 2248 |
pub fn replace_diagnostics( |
| 2249 |
&mut self, |
| 2250 |
diagnostics: impl IntoIterator<Item = Diagnostic>, |
| 2251 |
unchanged_sources: &[String], |
| 2252 |
provider: Option<&DiagnosticProvider>, |
| 2253 |
) { |
| 2254 |
if unchanged_sources.is_empty() { |
| 2255 |
if let Some(provider) = provider { |
| 2256 |
self.diagnostics |
| 2257 |
.retain(|diagnostic| &diagnostic.provider != provider); |
| 2258 |
} else { |
| 2259 |
self.diagnostics.clear(); |
| 2260 |
} |
| 2261 |
} else { |
| 2262 |
self.diagnostics.retain(|d| { |
| 2263 |
if provider.is_some_and(|provider| provider != &d.provider) { |
| 2264 |
return true; |
| 2265 |
} |
| 2266 |
|
| 2267 |
if let Some(source) = &d.source { |
| 2268 |
unchanged_sources.contains(source) |
| 2269 |
} else { |
| 2270 |
false |
| 2271 |
} |
| 2272 |
}); |
| 2273 |
} |
| 2274 |
self.diagnostics.extend(diagnostics); |
| 2275 |
self.diagnostics.sort_by_key(|diagnostic| { |
| 2276 |
( |
| 2277 |
diagnostic.range, |
| 2278 |
diagnostic.severity, |
| 2279 |
diagnostic.provider.clone(), |
| 2280 |
) |
| 2281 |
}); |
| 2282 |
} |
| 2283 |
|
| 2284 |
|
| 2285 |
pub fn clear_diagnostics_for_language_server(&mut self, id: LanguageServerId) { |
| 2286 |
self.diagnostics |
| 2287 |
.retain(|d| d.provider.language_server_id() != Some(id)); |
| 2288 |
} |
| 2289 |
|
| 2290 |
|
| 2291 |
|
| 2292 |
|
| 2293 |
|
| 2294 |
pub fn auto_pairs<'a>( |
| 2295 |
&'a self, |
| 2296 |
editor: &'a Editor, |
| 2297 |
loader: &'a syntax::Loader, |
| 2298 |
view: &View, |
| 2299 |
) -> Option<&'a AutoPairs> { |
| 2300 |
let global_config = (editor.auto_pairs).as_ref(); |
| 2301 |
|
| 2302 |
|
| 2303 |
|
| 2304 |
#[allow(clippy::question_mark)] |
| 2305 |
{ |
| 2306 |
if global_config.is_none() { |
| 2307 |
return None; |
| 2308 |
} |
| 2309 |
} |
| 2310 |
|
| 2311 |
self.syntax |
| 2312 |
.as_ref() |
| 2313 |
.and_then(|syntax| { |
| 2314 |
let selection = self.selection(view.id).primary(); |
| 2315 |
let (start, end) = selection.into_byte_range(self.text().slice(..)); |
| 2316 |
let layer = syntax.layer_for_byte_range(start as u32, end as u32); |
| 2317 |
|
| 2318 |
let lang_config = loader.language(syntax.layer(layer).language).config(); |
| 2319 |
lang_config.auto_pairs.as_ref() |
| 2320 |
}) |
| 2321 |
.or(global_config) |
| 2322 |
} |
| 2323 |
|
| 2324 |
pub fn snippet_ctx(&self) -> SnippetRenderCtx { |
| 2325 |
SnippetRenderCtx { |
| 2326 |
|
| 2327 |
resolve_var: Box::new(|_| None), |
| 2328 |
tab_width: self.tab_width(), |
| 2329 |
indent_style: self.indent_style, |
| 2330 |
line_ending: self.line_ending.as_str(), |
| 2331 |
} |
| 2332 |
} |
| 2333 |
|
| 2334 |
pub fn text_width(&self) -> usize { |
| 2335 |
self.editor_config |
| 2336 |
.max_line_length |
| 2337 |
.map(|n| n.get() as usize) |
| 2338 |
.or_else(|| self.language_config().and_then(|config| config.text_width)) |
| 2339 |
.unwrap_or_else(|| self.config.load().text_width) |
| 2340 |
} |
| 2341 |
|
| 2342 |
pub fn text_format(&self, mut viewport_width: u16, theme: Option<&Theme>) -> TextFormat { |
| 2343 |
let config = self.config.load(); |
| 2344 |
let text_width = self.text_width(); |
| 2345 |
let mut soft_wrap_at_text_width = self |
| 2346 |
.language_config() |
| 2347 |
.and_then(|config| { |
| 2348 |
config |
| 2349 |
.soft_wrap |
| 2350 |
.as_ref() |
| 2351 |
.and_then(|soft_wrap| soft_wrap.wrap_at_text_width) |
| 2352 |
}) |
| 2353 |
.or(config.soft_wrap.wrap_at_text_width) |
| 2354 |
.unwrap_or(false); |
| 2355 |
if soft_wrap_at_text_width { |
| 2356 |
|
| 2357 |
|
| 2358 |
if text_width >= viewport_width as usize { |
| 2359 |
soft_wrap_at_text_width = false; |
| 2360 |
} else { |
| 2361 |
viewport_width = text_width as u16; |
| 2362 |
} |
| 2363 |
} |
| 2364 |
let config = self.config.load(); |
| 2365 |
let editor_soft_wrap = &config.soft_wrap; |
| 2366 |
let language_soft_wrap = self |
| 2367 |
.language |
| 2368 |
.as_ref() |
| 2369 |
.and_then(|config| config.soft_wrap.as_ref()); |
| 2370 |
let enable_soft_wrap = language_soft_wrap |
| 2371 |
.and_then(|soft_wrap| soft_wrap.enable) |
| 2372 |
.or(editor_soft_wrap.enable) |
| 2373 |
.unwrap_or(false); |
| 2374 |
let max_wrap = language_soft_wrap |
| 2375 |
.and_then(|soft_wrap| soft_wrap.max_wrap) |
| 2376 |
.or(config.soft_wrap.max_wrap) |
| 2377 |
.unwrap_or(20); |
| 2378 |
let max_indent_retain = language_soft_wrap |
| 2379 |
.and_then(|soft_wrap| soft_wrap.max_indent_retain) |
| 2380 |
.or(editor_soft_wrap.max_indent_retain) |
| 2381 |
.unwrap_or(40); |
| 2382 |
let wrap_indicator = language_soft_wrap |
| 2383 |
.and_then(|soft_wrap| soft_wrap.wrap_indicator.clone()) |
| 2384 |
.or_else(|| config.soft_wrap.wrap_indicator.clone()) |
| 2385 |
.unwrap_or_else(|| "↪ ".into()); |
| 2386 |
let tab_width = self.tab_width() as u16; |
| 2387 |
TextFormat { |
| 2388 |
soft_wrap: enable_soft_wrap && viewport_width > 10, |
| 2389 |
tab_width, |
| 2390 |
max_wrap: max_wrap.min(viewport_width / 4), |
| 2391 |
max_indent_retain: max_indent_retain.min(viewport_width * 2 / 5), |
| 2392 |
|
| 2393 |
|
| 2394 |
viewport_width, |
| 2395 |
wrap_indicator: wrap_indicator.into_boxed_str(), |
| 2396 |
wrap_indicator_highlight: theme |
| 2397 |
.and_then(|theme| theme.find_highlight("ui.virtual.wrap")), |
| 2398 |
soft_wrap_at_text_width, |
| 2399 |
} |
| 2400 |
} |
| 2401 |
|
| 2402 |
|
| 2403 |
pub fn set_inlay_hints(&mut self, view_id: ViewId, inlay_hints: DocumentInlayHints) { |
| 2404 |
self.inlay_hints.insert(view_id, inlay_hints); |
| 2405 |
} |
| 2406 |
|
| 2407 |
pub fn set_jump_labels(&mut self, view_id: ViewId, labels: Vec<Overlay>) { |
| 2408 |
self.jump_labels.insert(view_id, labels); |
| 2409 |
} |
| 2410 |
|
| 2411 |
pub fn remove_jump_labels(&mut self, view_id: ViewId) { |
| 2412 |
self.jump_labels.remove(&view_id); |
| 2413 |
} |
| 2414 |
|
| 2415 |
pub fn set_document_highlights( |
| 2416 |
&mut self, |
| 2417 |
view_id: ViewId, |
| 2418 |
ranges: Vec<std::ops::Range<usize>>, |
| 2419 |
) { |
| 2420 |
if ranges.is_empty() { |
| 2421 |
self.document_highlights.remove(&view_id); |
| 2422 |
} else { |
| 2423 |
self.document_highlights |
| 2424 |
.insert(view_id, DocumentHighlights { ranges }); |
| 2425 |
} |
| 2426 |
} |
| 2427 |
|
| 2428 |
pub fn clear_document_highlights(&mut self, view_id: ViewId) { |
| 2429 |
self.document_highlights.remove(&view_id); |
| 2430 |
} |
| 2431 |
|
| 2432 |
pub fn clear_all_document_highlights(&mut self) { |
| 2433 |
self.document_highlights.clear(); |
| 2434 |
self.document_highlight_controllers.clear(); |
| 2435 |
} |
| 2436 |
|
| 2437 |
pub fn document_highlights(&self, view_id: ViewId) -> Option<&[std::ops::Range<usize>]> { |
| 2438 |
self.document_highlights |
| 2439 |
.get(&view_id) |
| 2440 |
.map(|highlights| highlights.ranges.as_slice()) |
| 2441 |
} |
| 2442 |
|
| 2443 |
pub fn document_highlight_controller(&mut self, view_id: ViewId) -> &mut TaskController { |
| 2444 |
self.document_highlight_controllers |
| 2445 |
.entry(view_id) |
| 2446 |
.or_default() |
| 2447 |
} |
| 2448 |
|
| 2449 |
pub fn set_code_action_hints(&mut self, view_id: ViewId) { |
| 2450 |
self.code_action_hints.insert(view_id); |
| 2451 |
} |
| 2452 |
|
| 2453 |
pub fn clear_code_action_hints(&mut self, view_id: ViewId) { |
| 2454 |
self.code_action_hints.remove(&view_id); |
| 2455 |
} |
| 2456 |
|
| 2457 |
pub fn clear_all_code_action_hints(&mut self) { |
| 2458 |
self.code_action_hints.clear(); |
| 2459 |
self.code_action_controllers.clear(); |
| 2460 |
} |
| 2461 |
|
| 2462 |
pub fn code_action_hints(&self, view_id: ViewId) -> bool { |
| 2463 |
self.code_action_hints.contains(&view_id) |
| 2464 |
} |
| 2465 |
|
| 2466 |
pub fn code_action_controller(&mut self, view_id: ViewId) -> &mut TaskController { |
| 2467 |
self.code_action_controllers.entry(view_id).or_default() |
| 2468 |
} |
| 2469 |
|
| 2470 |
|
| 2471 |
pub fn inlay_hints(&self, view_id: ViewId) -> Option<&DocumentInlayHints> { |
| 2472 |
self.inlay_hints.get(&view_id) |
| 2473 |
} |
| 2474 |
|
| 2475 |
|
| 2476 |
|
| 2477 |
pub fn reset_all_inlay_hints(&mut self) { |
| 2478 |
self.inlay_hints = Default::default(); |
| 2479 |
} |
| 2480 |
|
| 2481 |
pub fn has_language_server_with_feature(&self, feature: LanguageServerFeature) -> bool { |
| 2482 |
self.language_servers_with_feature(feature).next().is_some() |
| 2483 |
} |
| 2484 |
} |
| 2485 |
|
| 2486 |
#[derive(Debug, Default)] |
| 2487 |
pub struct ViewData { |
| 2488 |
view_position: ViewPosition, |
| 2489 |
} |
| 2490 |
|
| 2491 |
#[derive(Clone, Debug)] |
| 2492 |
pub enum FormatterError { |
| 2493 |
SpawningFailed { |
| 2494 |
command: String, |
| 2495 |
error: std::io::ErrorKind, |
| 2496 |
}, |
| 2497 |
BrokenStdin, |
| 2498 |
WaitForOutputFailed, |
| 2499 |
InvalidUtf8Output, |
| 2500 |
NonZeroExitStatus(Option<String>), |
| 2501 |
} |
| 2502 |
|
| 2503 |
impl std::error::Error for FormatterError {} |
| 2504 |
|
| 2505 |
impl Display for FormatterError { |
| 2506 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 2507 |
match self { |
| 2508 |
Self::SpawningFailed { command, error } => { |
| 2509 |
write!(f, "Failed to spawn formatter {}: {:?}", command, error) |
| 2510 |
} |
| 2511 |
Self::BrokenStdin => write!(f, "Could not write to formatter stdin"), |
| 2512 |
Self::WaitForOutputFailed => write!(f, "Waiting for formatter output failed"), |
| 2513 |
Self::InvalidUtf8Output => write!(f, "Invalid UTF-8 formatter output"), |
| 2514 |
Self::NonZeroExitStatus(Some(output)) => write!(f, "Formatter error: {}", output), |
| 2515 |
Self::NonZeroExitStatus(None) => { |
| 2516 |
write!(f, "Formatter exited with non zero exit status") |
| 2517 |
} |
| 2518 |
} |
| 2519 |
} |
| 2520 |
} |
| 2521 |
|
| 2522 |
#[cfg(test)] |
| 2523 |
mod test { |
| 2524 |
use arc_swap::ArcSwap; |
| 2525 |
|
| 2526 |
use super::*; |
| 2527 |
|
| 2528 |
#[test] |
| 2529 |
fn changeset_to_changes_ignore_line_endings() { |
| 2530 |
use helix_lsp::{lsp, Client, OffsetEncoding}; |
| 2531 |
let text = Rope::from("hello\r\nworld"); |
| 2532 |
let mut doc = Document::from( |
| 2533 |
text, |
| 2534 |
None, |
| 2535 |
Arc::new(ArcSwap::new(Arc::new(Config::default()))), |
| 2536 |
Arc::new(ArcSwap::from_pointee(syntax::Loader::default())), |
| 2537 |
); |
| 2538 |
let view = ViewId::default(); |
| 2539 |
doc.set_selection(view, Selection::single(0, 0)); |
| 2540 |
|
| 2541 |
let transaction = |
| 2542 |
Transaction::change(doc.text(), vec![(5, 7, Some("\n".into()))].into_iter()); |
| 2543 |
let old_doc = doc.text().clone(); |
| 2544 |
doc.apply(&transaction, view); |
| 2545 |
let changes = Client::changeset_to_changes( |
| 2546 |
&old_doc, |
| 2547 |
doc.text(), |
| 2548 |
transaction.changes(), |
| 2549 |
OffsetEncoding::Utf8, |
| 2550 |
); |
| 2551 |
|
| 2552 |
assert_eq!(doc.text(), "hello\nworld"); |
| 2553 |
|
| 2554 |
assert_eq!( |
| 2555 |
changes, |
| 2556 |
&[lsp::TextDocumentContentChangeEvent { |
| 2557 |
range: Some(lsp::Range::new( |
| 2558 |
lsp::Position::new(0, 5), |
| 2559 |
lsp::Position::new(1, 0) |
| 2560 |
)), |
| 2561 |
text: "\n".into(), |
| 2562 |
range_length: None, |
| 2563 |
}] |
| 2564 |
); |
| 2565 |
} |
| 2566 |
|
| 2567 |
#[test] |
| 2568 |
fn changeset_to_changes() { |
| 2569 |
use helix_lsp::{lsp, Client, OffsetEncoding}; |
| 2570 |
let text = Rope::from("hello"); |
| 2571 |
let mut doc = Document::from( |
| 2572 |
text, |
| 2573 |
None, |
| 2574 |
Arc::new(ArcSwap::new(Arc::new(Config::default()))), |
| 2575 |
Arc::new(ArcSwap::from_pointee(syntax::Loader::default())), |
| 2576 |
); |
| 2577 |
let view = ViewId::default(); |
| 2578 |
doc.set_selection(view, Selection::single(5, 5)); |
| 2579 |
|
| 2580 |
|
| 2581 |
|
| 2582 |
let transaction = Transaction::insert(doc.text(), doc.selection(view), " world".into()); |
| 2583 |
let old_doc = doc.text().clone(); |
| 2584 |
doc.apply(&transaction, view); |
| 2585 |
let changes = Client::changeset_to_changes( |
| 2586 |
&old_doc, |
| 2587 |
doc.text(), |
| 2588 |
transaction.changes(), |
| 2589 |
OffsetEncoding::Utf8, |
| 2590 |
); |
| 2591 |
|
| 2592 |
assert_eq!( |
| 2593 |
changes, |
| 2594 |
&[lsp::TextDocumentContentChangeEvent { |
| 2595 |
range: Some(lsp::Range::new( |
| 2596 |
lsp::Position::new(0, 5), |
| 2597 |
lsp::Position::new(0, 5) |
| 2598 |
)), |
| 2599 |
text: " world".into(), |
| 2600 |
range_length: None, |
| 2601 |
}] |
| 2602 |
); |
| 2603 |
|
| 2604 |
|
| 2605 |
|
| 2606 |
let transaction = transaction.invert(&old_doc); |
| 2607 |
let old_doc = doc.text().clone(); |
| 2608 |
doc.apply(&transaction, view); |
| 2609 |
let changes = Client::changeset_to_changes( |
| 2610 |
&old_doc, |
| 2611 |
doc.text(), |
| 2612 |
transaction.changes(), |
| 2613 |
OffsetEncoding::Utf8, |
| 2614 |
); |
| 2615 |
|
| 2616 |
|
| 2617 |
|
| 2618 |
|
| 2619 |
|
| 2620 |
|
| 2621 |
|
| 2622 |
assert_eq!( |
| 2623 |
changes, |
| 2624 |
&[lsp::TextDocumentContentChangeEvent { |
| 2625 |
range: Some(lsp::Range::new( |
| 2626 |
lsp::Position::new(0, 5), |
| 2627 |
lsp::Position::new(0, 11) |
| 2628 |
)), |
| 2629 |
text: "".into(), |
| 2630 |
range_length: None, |
| 2631 |
}] |
| 2632 |
); |
| 2633 |
|
| 2634 |
|
| 2635 |
|
| 2636 |
|
| 2637 |
|
| 2638 |
doc.set_selection(view, Selection::single(0, 5)); |
| 2639 |
let transaction = Transaction::change( |
| 2640 |
doc.text(), |
| 2641 |
vec![(0, 2, Some("aei".into())), (3, 5, Some("ou".into()))].into_iter(), |
| 2642 |
); |
| 2643 |
|
| 2644 |
let old_doc = doc.text().clone(); |
| 2645 |
doc.apply(&transaction, view); |
| 2646 |
let changes = Client::changeset_to_changes( |
| 2647 |
&old_doc, |
| 2648 |
doc.text(), |
| 2649 |
transaction.changes(), |
| 2650 |
OffsetEncoding::Utf8, |
| 2651 |
); |
| 2652 |
|
| 2653 |
assert_eq!( |
| 2654 |
changes, |
| 2655 |
&[ |
| 2656 |
|
| 2657 |
|
| 2658 |
|
| 2659 |
|
| 2660 |
|
| 2661 |
lsp::TextDocumentContentChangeEvent { |
| 2662 |
range: Some(lsp::Range::new( |
| 2663 |
lsp::Position::new(0, 0), |
| 2664 |
lsp::Position::new(0, 2) |
| 2665 |
)), |
| 2666 |
text: "aei".into(), |
| 2667 |
range_length: None, |
| 2668 |
}, |
| 2669 |
|
| 2670 |
|
| 2671 |
|
| 2672 |
|
| 2673 |
|
| 2674 |
lsp::TextDocumentContentChangeEvent { |
| 2675 |
range: Some(lsp::Range::new( |
| 2676 |
lsp::Position::new(0, 4), |
| 2677 |
lsp::Position::new(0, 6) |
| 2678 |
)), |
| 2679 |
text: "ou".into(), |
| 2680 |
range_length: None, |
| 2681 |
} |
| 2682 |
] |
| 2683 |
); |
| 2684 |
} |
| 2685 |
|
| 2686 |
#[test] |
| 2687 |
fn test_line_ending() { |
| 2688 |
assert_eq!( |
| 2689 |
Document::default( |
| 2690 |
Arc::new(ArcSwap::new(Arc::new(Config::default()))), |
| 2691 |
Arc::new(ArcSwap::from_pointee(syntax::Loader::default())) |
| 2692 |
) |
| 2693 |
.text() |
| 2694 |
.to_string(), |
| 2695 |
helix_core::NATIVE_LINE_ENDING.as_str() |
| 2696 |
); |
| 2697 |
} |
| 2698 |
|
| 2699 |
macro_rules! decode { |
| 2700 |
($name:ident, $label:expr, $label_override:expr) => { |
| 2701 |
#[test] |
| 2702 |
fn $name() { |
| 2703 |
let encoding = encoding::Encoding::for_label($label_override.as_bytes()).unwrap(); |
| 2704 |
let base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/encoding"); |
| 2705 |
let path = base_path.join(format!("{}_in.txt", $label)); |
| 2706 |
let ref_path = base_path.join(format!("{}_in_ref.txt", $label)); |
| 2707 |
assert!(path.exists()); |
| 2708 |
assert!(ref_path.exists()); |
| 2709 |
|
| 2710 |
let mut file = std::fs::File::open(path).unwrap(); |
| 2711 |
let text = from_reader(&mut file, Some(encoding.into())) |
| 2712 |
.unwrap() |
| 2713 |
.0 |
| 2714 |
.to_string(); |
| 2715 |
let expectation = std::fs::read_to_string(ref_path).unwrap(); |
| 2716 |
assert_eq!(text[..], expectation[..]); |
| 2717 |
} |
| 2718 |
}; |
| 2719 |
($name:ident, $label:expr) => { |
| 2720 |
decode!($name, $label, $label); |
| 2721 |
}; |
| 2722 |
} |
| 2723 |
|
| 2724 |
macro_rules! encode { |
| 2725 |
($name:ident, $label:expr, $label_override:expr) => { |
| 2726 |
#[test] |
| 2727 |
fn $name() { |
| 2728 |
let encoding = encoding::Encoding::for_label($label_override.as_bytes()).unwrap(); |
| 2729 |
let base_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/encoding"); |
| 2730 |
let path = base_path.join(format!("{}_out.txt", $label)); |
| 2731 |
let ref_path = base_path.join(format!("{}_out_ref.txt", $label)); |
| 2732 |
assert!(path.exists()); |
| 2733 |
assert!(ref_path.exists()); |
| 2734 |
|
| 2735 |
let text = Rope::from_str(&std::fs::read_to_string(path).unwrap()); |
| 2736 |
let mut buf: Vec<u8> = Vec::new(); |
| 2737 |
helix_lsp::block_on(to_writer(&mut buf, (encoding, false), &text)).unwrap(); |
| 2738 |
|
| 2739 |
let expectation = std::fs::read(ref_path).unwrap(); |
| 2740 |
assert_eq!(buf, expectation); |
| 2741 |
} |
| 2742 |
}; |
| 2743 |
($name:ident, $label:expr) => { |
| 2744 |
encode!($name, $label, $label); |
| 2745 |
}; |
| 2746 |
} |
| 2747 |
|
| 2748 |
decode!(big5_decode, "big5"); |
| 2749 |
encode!(big5_encode, "big5"); |
| 2750 |
decode!(euc_kr_decode, "euc_kr", "EUC-KR"); |
| 2751 |
encode!(euc_kr_encode, "euc_kr", "EUC-KR"); |
| 2752 |
decode!(gb18030_decode, "gb18030"); |
| 2753 |
encode!(gb18030_encode, "gb18030"); |
| 2754 |
decode!(iso_2022_jp_decode, "iso_2022_jp", "ISO-2022-JP"); |
| 2755 |
encode!(iso_2022_jp_encode, "iso_2022_jp", "ISO-2022-JP"); |
| 2756 |
decode!(jis0208_decode, "jis0208", "EUC-JP"); |
| 2757 |
encode!(jis0208_encode, "jis0208", "EUC-JP"); |
| 2758 |
decode!(jis0212_decode, "jis0212", "EUC-JP"); |
| 2759 |
decode!(shift_jis_decode, "shift_jis"); |
| 2760 |
encode!(shift_jis_encode, "shift_jis"); |
| 2761 |
} |