Debian Codegraph @

helix-view/src/macros.rs

raw symbols SCIP
1 //! These are macros to make getting very nested fields in the `Editor` struct easier
2 //! These are macros instead of functions because functions will have to take `&mut self`
3 //! However, rust doesn't know that you only want a partial borrow instead of borrowing the
4 //! entire struct which `&mut self` says. This makes it impossible to do other mutable
5 //! stuff to the struct because it is already borrowed. Because macros are expanded,
6 //! this circumvents the problem because it is just like indexing fields by hand and then
7 //! putting a `&mut` in front of it. This way rust can see that we are only borrowing a
8 //! part of the struct and not the entire thing.
9
10 /// Get the current view and document mutably as a tuple.
11 /// Returns `(&mut View, &mut Document)`
12 #[macro_export]
13 macro_rules! current {
14 ($editor:expr) => {{
15 let view = $crate::view_mut!($editor);
16 let id = view.doc;
17 let doc = $crate::doc_mut!($editor, &id);
18 (view, doc)
19 }};
20 }
21
22 #[macro_export]
23 macro_rules! current_ref {
24 ($editor:expr) => {{
25 let view = $editor.tree.get($editor.tree.focus);
26 let doc = &$editor.documents[&view.doc];
27 (view, doc)
28 }};
29 }
30
31 /// Get the current document mutably.
32 /// Returns `&mut Document`
33 #[macro_export]
34 macro_rules! doc_mut {
35 ($editor:expr, $id:expr) => {{
36 $editor.documents.get_mut($id).unwrap()
37 }};
38 ($editor:expr) => {{
39 $crate::current!($editor).1
40 }};
41 }
42
43 /// Get the current view mutably.
44 /// Returns `&mut View`
45 #[macro_export]
46 macro_rules! view_mut {
47 ($editor:expr, $id:expr) => {{
48 $editor.tree.get_mut($id)
49 }};
50 ($editor:expr) => {{
51 $editor.tree.get_mut($editor.tree.focus)
52 }};
53 }
54
55 /// Get the current view immutably
56 /// Returns `&View`
57 #[macro_export]
58 macro_rules! view {
59 ($editor:expr, $id:expr) => {{
60 $editor.tree.get($id)
61 }};
62 ($editor:expr) => {{
63 $editor.tree.get($editor.tree.focus)
64 }};
65 }
66
67 #[macro_export]
68 macro_rules! doc {
69 ($editor:expr, $id:expr) => {{
70 &$editor.documents[$id]
71 }};
72 ($editor:expr) => {{
73 $crate::current_ref!($editor).1
74 }};
75 }