1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
|
use std::{env, error::Error};
type DynError = Box<dyn Error>;
pub mod helpers {
use std::{
fmt::Display,
path::{Path, PathBuf},
};
use crate::path;
use helix_core::syntax::Configuration as LangConfig;
#[derive(Copy, Clone)]
pub enum TsFeature {
Highlight,
TextObjects,
AutoIndent,
}
impl TsFeature {
pub fn all() -> &'static [Self] {
&[Self::Highlight, Self::TextObjects, Self::AutoIndent]
}
pub fn runtime_filename(&self) -> &'static str {
match *self {
Self::Highlight => "highlights.scm",
Self::TextObjects => "textobjects.scm",
Self::AutoIndent => "indents.toml",
}
}
}
impl Display for TsFeature {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match *self {
Self::Highlight => "Syntax Highlighting",
Self::TextObjects => "Treesitter Textobjects",
Self::AutoIndent => "Auto Indent",
}
)
}
}
/// Get the list of languages that support a particular tree-sitter
/// based feature.
pub fn ts_lang_support(feat: TsFeature) -> Vec<String> {
let queries_dir = path::ts_queries();
find_files(&queries_dir, feat.runtime_filename())
.iter()
.map(|f| {
// .../helix/runtime/queries/python/highlights.scm
let tail = f.strip_prefix(&queries_dir).unwrap(); // python/highlights.scm
let lang = tail.components().next().unwrap(); // python
lang.as_os_str().to_string_lossy().to_string()
})
.collect()
}
/// Get the list of languages that have any form of tree-sitter
/// queries defined in the runtime directory.
pub fn langs_with_ts_queries() -> Vec<String> {
std::fs::read_dir(path::ts_queries())
.unwrap()
.filter_map(|entry| {
let entry = entry.ok()?;
entry
.file_type()
.ok()?
.is_dir()
.then(|| entry.file_name().to_string_lossy().to_string())
})
.collect()
}
// naive implementation, but suffices for our needs
pub fn find_files(dir: &Path, filename: &str) -> Vec<PathBuf> {
std::fs::read_dir(dir)
.unwrap()
.filter_map(|entry| {
let path = entry.ok()?.path();
if path.is_dir() {
Some(find_files(&path, filename))
} else {
(path.file_name()?.to_string_lossy() == filename).then(|| vec![path])
}
})
.flatten()
.collect()
}
pub fn lang_config() -> LangConfig {
let bytes = std::fs::read(path::lang_config()).unwrap();
toml::from_slice(&bytes).unwrap()
}
}
pub mod md_gen {
use crate::DynError;
use crate::helpers;
use crate::path;
use std::fs;
use helix_term::commands::cmd::TYPABLE_COMMAND_LIST;
pub const TYPABLE_COMMANDS_MD_OUTPUT: &str = "typable-cmd.md";
pub const LANG_SUPPORT_MD_OUTPUT: &str = "lang-support.md";
fn md_table_heading(cols: &[String]) -> String {
let mut header = String::new();
header += &md_table_row(cols);
header += &md_table_row(&vec!["---".to_string(); cols.len()]);
header
}
fn md_table_row(cols: &[String]) -> String {
"| ".to_owned() + &cols.join(" | ") + " |\n"
}
fn md_mono(s: &str) -> String {
format!("`{}`", s)
}
pub fn typable_commands() -> Result<String, DynError> {
let mut md = String::new();
md.push_str(&md_table_heading(&[
"Name".to_owned(),
"Description".to_owned(),
]));
let cmdify = |s: &str| format!("`:{}`", s);
for cmd in TYPABLE_COMMAND_LIST {
let names = std::iter::once(&cmd.name)
.chain(cmd.aliases.iter())
.map(|a| cmdify(a))
.collect::<Vec<_>>()
.join(", ");
md.push_str(&md_table_row(&[names.to_owned(), cmd.doc.to_owned()]));
}
Ok(md)
}
pub fn lang_features() -> Result<String, DynError> {
let mut md = String::new();
let ts_features = helpers::TsFeature::all();
let mut cols = vec!["Language".to_owned()];
cols.append(
&mut ts_features
.iter()
.map(|t| t.to_string())
.collect::<Vec<_>>(),
);
cols.push("Default LSP".to_owned());
md.push_str(&md_table_heading(&cols));
let config = helpers::lang_config();
let mut langs = config
.language
.iter()
.map(|l| l.language_id.clone())
.collect::<Vec<_>>();
langs.sort_unstable();
let mut ts_features_to_langs = Vec::new();
for &feat in ts_features {
ts_features_to_langs.push((feat, helpers::ts_lang_support(feat)));
}
let mut row = Vec::new();
for lang in langs {
let lc = config
.language
.iter()
.find(|l| l.language_id == lang)
.unwrap(); // lang comes from config
row.push(lc.language_id.clone());
for (_feat, support_list) in &ts_features_to_langs {
row.push(
if support_list.contains(&lang) {
"✓"
} else {
""
}
.to_owned(),
);
}
row.push(
lc.language_server
.as_ref()
.map(|s| s.command.clone())
.map(|c| md_mono(&c))
.unwrap_or_default(),
);
md.push_str(&md_table_row(&row));
row.clear();
}
Ok(md)
}
pub fn write(filename: &str, data: &str) {
let error = format!("Could not write to {}", filename);
let path = path::book_gen().join(filename);
fs::write(path, data).expect(&error);
}
}
pub mod path {
use std::path::{Path, PathBuf};
pub fn project_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.to_path_buf()
}
pub fn book_gen() -> PathBuf {
project_root().join("book/src/generated/")
}
pub fn ts_queries() -> PathBuf {
project_root().join("runtime/queries")
}
pub fn lang_config() -> PathBuf {
project_root().join("languages.toml")
}
}
pub mod tasks {
use crate::md_gen;
use crate::DynError;
pub fn docgen() -> Result<(), DynError> {
use md_gen::*;
write(TYPABLE_COMMANDS_MD_OUTPUT, &typable_commands()?);
write(LANG_SUPPORT_MD_OUTPUT, &lang_features()?);
Ok(())
}
pub fn print_help() {
println!(
"
Usage: Run with `cargo xtask <task>`, eg. `cargo xtask docgen`.
Tasks:
docgen: Generate files to be included in the mdbook output.
"
);
}
}
fn main() -> Result<(), DynError> {
let task = env::args().nth(1);
match task {
None => tasks::print_help(),
Some(t) => match t.as_str() {
"docgen" => tasks::docgen()?,
invalid => return Err(format!("Invalid task name: {}", invalid).into()),
},
};
Ok(())
}
|