1mod buffer;
2mod diagnostic_set;
3mod highlight_map;
4pub mod proto;
5#[cfg(test)]
6mod tests;
7
8use anyhow::{anyhow, Result};
9pub use buffer::Operation;
10pub use buffer::*;
11use collections::HashSet;
12pub use diagnostic_set::DiagnosticEntry;
13use gpui::AppContext;
14use highlight_map::HighlightMap;
15use lazy_static::lazy_static;
16use parking_lot::Mutex;
17use serde::Deserialize;
18use std::{path::Path, str, sync::Arc};
19use theme::SyntaxTheme;
20use tree_sitter::{self, Query};
21pub use tree_sitter::{Parser, Tree};
22
23lazy_static! {
24 pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
25 LanguageConfig {
26 name: "Plain Text".to_string(),
27 path_suffixes: Default::default(),
28 brackets: Default::default(),
29 line_comment: None,
30 language_server: None,
31 },
32 None,
33 ));
34}
35
36#[derive(Default, Deserialize)]
37pub struct LanguageConfig {
38 pub name: String,
39 pub path_suffixes: Vec<String>,
40 pub brackets: Vec<BracketPair>,
41 pub line_comment: Option<String>,
42 pub language_server: Option<LanguageServerConfig>,
43}
44
45#[derive(Default, Deserialize)]
46pub struct LanguageServerConfig {
47 pub binary: String,
48 pub disk_based_diagnostic_sources: HashSet<String>,
49 pub disk_based_diagnostics_progress_token: Option<String>,
50 #[cfg(any(test, feature = "test-support"))]
51 #[serde(skip)]
52 pub fake_server: Option<(Arc<lsp::LanguageServer>, Arc<std::sync::atomic::AtomicBool>)>,
53}
54
55#[derive(Clone, Debug, Deserialize)]
56pub struct BracketPair {
57 pub start: String,
58 pub end: String,
59 pub close: bool,
60 pub newline: bool,
61}
62
63pub struct Language {
64 pub(crate) config: LanguageConfig,
65 pub(crate) grammar: Option<Arc<Grammar>>,
66}
67
68pub struct Grammar {
69 pub(crate) ts_language: tree_sitter::Language,
70 pub(crate) highlights_query: Query,
71 pub(crate) brackets_query: Query,
72 pub(crate) indents_query: Query,
73 pub(crate) highlight_map: Mutex<HighlightMap>,
74}
75
76#[derive(Default)]
77pub struct LanguageRegistry {
78 languages: Vec<Arc<Language>>,
79}
80
81impl LanguageRegistry {
82 pub fn new() -> Self {
83 Self::default()
84 }
85
86 pub fn add(&mut self, language: Arc<Language>) {
87 self.languages.push(language);
88 }
89
90 pub fn set_theme(&self, theme: &SyntaxTheme) {
91 for language in &self.languages {
92 language.set_theme(theme);
93 }
94 }
95
96 pub fn get_language(&self, name: &str) -> Option<&Arc<Language>> {
97 self.languages
98 .iter()
99 .find(|language| language.name() == name)
100 }
101
102 pub fn select_language(&self, path: impl AsRef<Path>) -> Option<&Arc<Language>> {
103 let path = path.as_ref();
104 let filename = path.file_name().and_then(|name| name.to_str());
105 let extension = path.extension().and_then(|name| name.to_str());
106 let path_suffixes = [extension, filename];
107 self.languages.iter().find(|language| {
108 language
109 .config
110 .path_suffixes
111 .iter()
112 .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())))
113 })
114 }
115}
116
117impl Language {
118 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
119 Self {
120 config,
121 grammar: ts_language.map(|ts_language| {
122 Arc::new(Grammar {
123 brackets_query: Query::new(ts_language, "").unwrap(),
124 highlights_query: Query::new(ts_language, "").unwrap(),
125 indents_query: Query::new(ts_language, "").unwrap(),
126 ts_language,
127 highlight_map: Default::default(),
128 })
129 }),
130 }
131 }
132
133 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
134 let grammar = self
135 .grammar
136 .as_mut()
137 .and_then(Arc::get_mut)
138 .ok_or_else(|| anyhow!("grammar does not exist or is already being used"))?;
139 grammar.highlights_query = Query::new(grammar.ts_language, source)?;
140 Ok(self)
141 }
142
143 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
144 let grammar = self
145 .grammar
146 .as_mut()
147 .and_then(Arc::get_mut)
148 .ok_or_else(|| anyhow!("grammar does not exist or is already being used"))?;
149 grammar.brackets_query = Query::new(grammar.ts_language, source)?;
150 Ok(self)
151 }
152
153 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
154 let grammar = self
155 .grammar
156 .as_mut()
157 .and_then(Arc::get_mut)
158 .ok_or_else(|| anyhow!("grammar does not exist or is already being used"))?;
159 grammar.indents_query = Query::new(grammar.ts_language, source)?;
160 Ok(self)
161 }
162
163 pub fn name(&self) -> &str {
164 self.config.name.as_str()
165 }
166
167 pub fn line_comment_prefix(&self) -> Option<&str> {
168 self.config.line_comment.as_deref()
169 }
170
171 pub fn start_server(
172 &self,
173 root_path: &Path,
174 cx: &AppContext,
175 ) -> Result<Option<Arc<lsp::LanguageServer>>> {
176 if let Some(config) = &self.config.language_server {
177 #[cfg(any(test, feature = "test-support"))]
178 if let Some((server, started)) = &config.fake_server {
179 started.store(true, std::sync::atomic::Ordering::SeqCst);
180 return Ok(Some(server.clone()));
181 }
182
183 const ZED_BUNDLE: Option<&'static str> = option_env!("ZED_BUNDLE");
184 let binary_path = if ZED_BUNDLE.map_or(Ok(false), |b| b.parse())? {
185 cx.platform()
186 .path_for_resource(Some(&config.binary), None)?
187 } else {
188 Path::new(&config.binary).to_path_buf()
189 };
190 lsp::LanguageServer::new(&binary_path, root_path, cx.background().clone()).map(Some)
191 } else {
192 Ok(None)
193 }
194 }
195
196 pub fn disk_based_diagnostic_sources(&self) -> Option<&HashSet<String>> {
197 self.config
198 .language_server
199 .as_ref()
200 .map(|config| &config.disk_based_diagnostic_sources)
201 }
202
203 pub fn disk_based_diagnostics_progress_token(&self) -> Option<&String> {
204 self.config
205 .language_server
206 .as_ref()
207 .and_then(|config| config.disk_based_diagnostics_progress_token.as_ref())
208 }
209
210 pub fn brackets(&self) -> &[BracketPair] {
211 &self.config.brackets
212 }
213
214 pub fn set_theme(&self, theme: &SyntaxTheme) {
215 if let Some(grammar) = self.grammar.as_ref() {
216 *grammar.highlight_map.lock() =
217 HighlightMap::new(grammar.highlights_query.capture_names(), theme);
218 }
219 }
220}
221
222impl Grammar {
223 pub fn highlight_map(&self) -> HighlightMap {
224 self.highlight_map.lock().clone()
225 }
226}
227
228#[cfg(any(test, feature = "test-support"))]
229impl LanguageServerConfig {
230 pub async fn fake(
231 executor: Arc<gpui::executor::Background>,
232 ) -> (Self, lsp::FakeLanguageServer) {
233 let (server, fake) = lsp::LanguageServer::fake(executor).await;
234 fake.started
235 .store(false, std::sync::atomic::Ordering::SeqCst);
236 let started = fake.started.clone();
237 (
238 Self {
239 fake_server: Some((server, started)),
240 disk_based_diagnostics_progress_token: Some("fakeServer/check".to_string()),
241 ..Default::default()
242 },
243 fake,
244 )
245 }
246}