@@ -1,5 +1,8 @@
11use crate::graphemes::{nth_next_grapheme_boundary, nth_prev_grapheme_boundary, RopeGraphemes};
2−use crate::{Buffer, Rope, RopeSlice, Selection, SelectionRange};
2+use crate::{Rope, RopeSlice, Selection, SelectionRange};
3+use anyhow::Error;
4+
5+use std::path::PathBuf;
36
47pub enum Mode {
58 Normal,
@@ -8,7 +11,9 @@ pub enum Mode {
811
912/// A state represents the current editor state of a single buffer.
1013pub struct State {
11− pub doc: Buffer,
14+ /// Path to file on disk.
15+ pub path: Option<PathBuf>,
16+ pub doc: Rope,
1217 pub selection: Selection,
1318 pub mode: Mode,
1419}
@@ -28,15 +33,31 @@ pub enum Granularity {
2833
2934impl State {
3035 #[must_use]
31− pub fn new(doc: Buffer) -> Self {
36+ pub fn new(doc: Rope) -> Self {
3237 Self {
38+ path: None,
3339 doc,
3440 selection: Selection::single(0, 0),
3541 mode: Mode::Normal,
3642 }
3743 }
3844
39− // TODO: buf/selection accessors
45+ #[must_use]
46+ pub fn load(path: PathBuf) -> Result<Self, Error> {
47+ use std::{env, fs::File, io::BufReader, path::PathBuf};
48+ let _current_dir = env::current_dir()?;
49+
50+ let doc = Rope::from_reader(BufReader::new(File::open(path.clone())?))?;
51+
52+ // TODO: create if not found
53+
54+ let mut state = Self::new(doc);
55+ state.path = Some(path);
56+
57+ Ok(state)
58+ }
59+
60+ // TODO: doc/selection accessors
4061
4162 // update/transact:
4263 // update(desc) => transaction ? transaction.doc() for applied doc
@@ -68,7 +89,7 @@ impl State {
6889 granularity: Granularity,
6990 count: usize,
7091 ) -> usize {
71− let text = &self.doc.contents;
92+ let text = &self.doc;
7293 match (dir, granularity) {
7394 // TODO: clamp movement to line, prevent moving onto \n at the end
7495 (Direction::Backward, Granularity::Character) => {
@@ -125,16 +146,6 @@ impl State {
125146 Selection::new(ranges.collect(), sel.primary_index)
126147 // TODO: update selection in state via transaction
127148 }
128−
129− pub fn contents(&self) -> &Rope {
130− // used to access file contents for rendering to screen
131− &self.doc.contents
132− }
133−
134− pub fn contents_mut(&mut self) -> &mut Rope {
135− // used to access file contents for rendering to screen
136− &mut self.doc.contents
137− }
138149}
139150
140151/// Coordinates are a 0-indexed line and column pair.