дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
feat(php): Blade and Twig languages, and framework files read as PHP (#7556)
Blade and Twig templates get their own languages with highlighting, and framework files that are PHP under other names are associated with PHP. The Blade highlighter's preceding-character check runs on WebKit, and language-server sharing between languages follows direct definitions only, preventing cycles and letting a shadowed server detach. Co-authored-by: samehelhawary <[email protected]>
Цей коміт міститься в:
1 джерело
d6d6fd0909
коміт
15b55c66ca
28 files changed
+1173
-60
No files matched your search
@@ -198,6 +198,20 @@ pub struct LanguageServerConfig {
|
||||
/// this one serves the file.
|
||||
#[serde(default)]
|
||||
pub replaces: Vec<String>,
|
||||
/// The `languageId` this server is told for the language's documents, when it
|
||||
/// knows them under another one (`php` for a PHP server on a Blade view).
|
||||
#[serde(default)]
|
||||
pub language_id: Option<String>,
|
||||
/// Another language whose server of this name also reads this language's files
|
||||
/// (the PHP server on the project's Twig templates and `.env`). The server is
|
||||
/// used only below one of its root markers, and only while it is the one that
|
||||
/// language uses there. Joins use the other language's direct server definitions.
|
||||
#[serde(default)]
|
||||
pub joins: Option<String>,
|
||||
/// Glob patterns of the files of the language the server reads (`**/lang/**/*.json`);
|
||||
/// empty means every one. `*` stays within a path segment.
|
||||
#[serde(default)]
|
||||
pub files: Vec<String>,
|
||||
/// What the server is used for (`completion`, `code-action`, `diagnostics`,
|
||||
/// … `FEATURES` in `ide-lsp/src/caps.rs`); empty means everything. The other
|
||||
/// capabilities it announces are ignored, so a refactoring-only server next
|
||||
|
||||
@@ -14,6 +14,7 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("astro", include_str!("../../../languages/astro.toml")),
|
||||
("axaml", include_str!("../../../languages/axaml.toml")),
|
||||
("bat", include_str!("../../../languages/bat.toml")),
|
||||
("blade", include_str!("../../../languages/blade.toml")),
|
||||
("c", include_str!("../../../languages/c.toml")),
|
||||
("clojure", include_str!("../../../languages/clojure.toml")),
|
||||
("cmake", include_str!("../../../languages/cmake.toml")),
|
||||
@@ -96,6 +97,7 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("terraform", include_str!("../../../languages/terraform.toml")),
|
||||
("terraform-vars", include_str!("../../../languages/terraform-vars.toml")),
|
||||
("toml", include_str!("../../../languages/toml.toml")),
|
||||
("twig", include_str!("../../../languages/twig.toml")),
|
||||
("typescript", include_str!("../../../languages/typescript.toml")),
|
||||
("typescriptreact", include_str!("../../../languages/typescriptreact.toml")),
|
||||
("typst", include_str!("../../../languages/typst.toml")),
|
||||
@@ -373,6 +375,19 @@ impl LanguageRegistry {
|
||||
self.state().languages.iter().find(|l| &l.id == id).cloned()
|
||||
}
|
||||
|
||||
/// The `languageId` the server named `server` is told for a `language`
|
||||
/// document: its `language-id` there, else the language's own id.
|
||||
pub fn server_language_id(&self, language: &LanguageId, server: &str) -> String {
|
||||
let state = self.state();
|
||||
state
|
||||
.languages
|
||||
.iter()
|
||||
.find(|l| &l.id == language)
|
||||
.and_then(|l| l.language_servers.iter().find(|s| s.name == server))
|
||||
.and_then(|s| s.language_id.clone())
|
||||
.unwrap_or_else(|| language.as_str().to_owned())
|
||||
}
|
||||
|
||||
/// The `framework-ui-modes` mode of a `language` file at `path`: the first
|
||||
/// whose root marker is in a directory above it, up to `project_root` (any
|
||||
/// directory without one: loose files). `None` keeps the language's own
|
||||
@@ -673,6 +688,8 @@ mod tests {
|
||||
"Angular TypeScript",
|
||||
"Thymeleaf",
|
||||
"ERB",
|
||||
"Blade",
|
||||
"Twig",
|
||||
"JSP",
|
||||
"Razor",
|
||||
"FreeMarker",
|
||||
@@ -1042,6 +1059,60 @@ mod tests {
|
||||
assert_eq!(served("lib/src/Parser.php"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blade_view_is_served_by_the_php_servers_which_know_it_as_php() {
|
||||
let reg = reg();
|
||||
let (php, blade) = (LanguageId::new("php"), LanguageId::new("blade"));
|
||||
let detect = |path: &str| reg.detect(Path::new(path), None);
|
||||
assert_eq!(detect("resources/views/orders/show.blade.php"), blade);
|
||||
assert_eq!(detect("resources/views/orders/SHOW.BLADE.PHP"), blade);
|
||||
assert_eq!(detect("app/Models/Blade.php"), php);
|
||||
// The same servers, defined the same way, so each runs once for both languages.
|
||||
let strip = |language: &LanguageId| -> Vec<crate::LanguageServerConfig> {
|
||||
let mut servers = reg.get(language).unwrap().language_servers;
|
||||
for server in &mut servers {
|
||||
server.language_id = None;
|
||||
server.install_hint = None;
|
||||
}
|
||||
servers
|
||||
};
|
||||
assert_eq!(strip(&blade), strip(&php));
|
||||
for server in reg.get(&blade).unwrap().language_servers {
|
||||
// Phoxite has Blade support of its own; the others read the view as PHP, as before.
|
||||
let told = if server.name == "phoxite" { "blade" } else { "php" };
|
||||
assert_eq!(reg.server_language_id(&blade, &server.name), told, "{}", server.name);
|
||||
assert_eq!(reg.server_language_id(&php, &server.name), "php", "{}", server.name);
|
||||
}
|
||||
assert_eq!(reg.server_language_id(&blade, "a-server-of-the-user"), "blade");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phoxite_reads_templates_env_and_translation_files_where_it_serves_php() {
|
||||
let reg = reg();
|
||||
let php = reg.get(&LanguageId::new("php")).unwrap();
|
||||
let of_php = php.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
|
||||
for (language, files) in [("twig", &[][..]), ("dotenv", &[][..]), ("json", &["**/lang/**/*.json"][..])] {
|
||||
let cfg = reg.get(&LanguageId::new(language)).unwrap();
|
||||
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
|
||||
assert_eq!(phoxite.joins.as_deref(), Some("php"), "{language}");
|
||||
assert_eq!(phoxite.files, files, "{language}");
|
||||
// The same program and roots as PHP's, so one process serves them all.
|
||||
assert_eq!(
|
||||
(&phoxite.command, &phoxite.args, &phoxite.root_markers),
|
||||
(&of_php.command, &of_php.args, &of_php.root_markers),
|
||||
"{language}"
|
||||
);
|
||||
assert_eq!(reg.server_language_id(&cfg.id, "phoxite"), language);
|
||||
}
|
||||
// No other language starts a PHP server.
|
||||
for lang in reg.all() {
|
||||
for server in lang.language_servers.iter().filter(|s| s.joins.is_some()) {
|
||||
assert_eq!((server.name.as_str(), server.joins.as_deref()), ("phoxite", Some("php")), "{}", lang.id);
|
||||
}
|
||||
}
|
||||
assert!(php.language_servers.iter().all(|s| s.joins.is_none() && s.files.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pylsp_adds_only_rope_refactorings_to_python() {
|
||||
let reg = reg();
|
||||
@@ -1399,6 +1470,8 @@ mod tests {
|
||||
("index.ftl", "freemarker"),
|
||||
("page.ftlh", "freemarker"),
|
||||
("index.php", "php"),
|
||||
("resources/views/welcome.blade.php", "blade"),
|
||||
("templates/base.html.twig", "twig"),
|
||||
("init.lua", "lua"),
|
||||
("main.dart", "dart"),
|
||||
("build.zig", "zig"),
|
||||
|
||||
@@ -66,6 +66,9 @@ fn server_config() -> LanguageServerConfig {
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
language_id: None,
|
||||
joins: None,
|
||||
files: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
|
||||
@@ -103,9 +103,7 @@ impl LspManager {
|
||||
});
|
||||
}
|
||||
self.language_servers(&lang).iter().any(|ls| {
|
||||
if ls.require_root_marker
|
||||
&& crate::launch::marked_root(&self.project_root, path, &ls.root_markers).is_none()
|
||||
{
|
||||
if !self.in_scope(ls, path) {
|
||||
return false;
|
||||
}
|
||||
let mut cfg = ls.clone();
|
||||
|
||||
@@ -178,11 +178,12 @@ struct FlutterOutline {
|
||||
}
|
||||
|
||||
impl DocState {
|
||||
fn did_open_params(&self) -> Value {
|
||||
/// `language_id`: what the receiving server knows the document's language as.
|
||||
fn did_open_params(&self, language_id: &str) -> Value {
|
||||
json!({
|
||||
"textDocument": {
|
||||
"uri": self.uri,
|
||||
"languageId": self.language.as_str(),
|
||||
"languageId": language_id,
|
||||
"version": self.version,
|
||||
"text": self.text.as_str(),
|
||||
}
|
||||
@@ -808,6 +809,10 @@ impl LspManager {
|
||||
/// only files below one, and stands in for no other. One that a server before
|
||||
/// it `replaces` is left out while that server serves the file.
|
||||
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
|
||||
self.declared_servers_for(language, path, true)
|
||||
}
|
||||
|
||||
fn declared_servers_for(&self, language: &LanguageId, path: &Path, allow_joins: bool) -> Vec<Arc<Server>> {
|
||||
let path = &*self.in_project_spelling(path);
|
||||
if let Some(servers) = self.arduino_servers(language, path) {
|
||||
return servers;
|
||||
@@ -816,12 +821,21 @@ impl LspManager {
|
||||
let mut available_before = false;
|
||||
let mut replaced: Vec<String> = Vec::new();
|
||||
for sc in &self.language_servers(language) {
|
||||
if (sc.fallback && available_before) || replaced.contains(&sc.name) {
|
||||
if !self.in_scope(sc, path) {
|
||||
continue;
|
||||
}
|
||||
if sc.require_root_marker
|
||||
&& launch::marked_root(&self.project_root_for(path), path, &sc.root_markers).is_none()
|
||||
{
|
||||
if let Some(host) = sc.joins.as_deref().map(LanguageId::new).filter(|host| host != language) {
|
||||
// The instance that serves the other language here, when this server is that one.
|
||||
if allow_joins
|
||||
&& let Some(server) =
|
||||
self.declared_servers_for(&host, path, false).into_iter().find(|s| s.name == sc.name)
|
||||
{
|
||||
server.add_language(language);
|
||||
out.push(server);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (sc.fallback && available_before) || replaced.contains(&sc.name) {
|
||||
continue;
|
||||
}
|
||||
let server = self.server_for(sc, language, path);
|
||||
@@ -834,6 +848,45 @@ impl LspManager {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `sc` may serve `path` at all: below a root marker when it needs one
|
||||
/// (also when it only joins another language's server), and among its `files`.
|
||||
fn in_scope(&self, sc: &LanguageServerConfig, path: &Path) -> bool {
|
||||
if (sc.require_root_marker || sc.joins.is_some())
|
||||
&& launch::marked_root(&self.project_root_for(path), path, &sc.root_markers).is_none()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
sc.files.is_empty() || {
|
||||
let path = path.to_string_lossy().replace('\\', "/");
|
||||
sc.files.iter().any(|pattern| {
|
||||
globset::GlobBuilder::new(pattern)
|
||||
.literal_separator(true)
|
||||
.build()
|
||||
.is_ok_and(|glob| glob.compile_matcher().is_match(&path))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the servers a language of `path` joins, and the ones listed before
|
||||
/// them there: whether a joined server serves the file is known once those
|
||||
/// before it run or turn out to be missing.
|
||||
fn wake_joined(&self, language: &LanguageId, path: &Path) {
|
||||
let path = &*self.in_project_spelling(path);
|
||||
for sc in self.language_servers(language).iter().filter(|sc| sc.joins.is_some() && self.in_scope(sc, path)) {
|
||||
let host = LanguageId::new(sc.joins.as_deref().unwrap_or_default());
|
||||
if &host == language {
|
||||
continue;
|
||||
}
|
||||
let chain = self.language_servers(&host);
|
||||
let upto = chain.iter().position(|c| c.name == sc.name).map_or(0, |at| at + 1);
|
||||
for server in self.declared_servers_for(&host, path, false) {
|
||||
if chain[..upto].iter().any(|c| c.name == server.name) {
|
||||
self.ensure_started(&server);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The definitions of the servers `language` uses.
|
||||
fn language_servers(&self, language: &LanguageId) -> Vec<LanguageServerConfig> {
|
||||
if !self.execution_allowed.load(Ordering::Acquire) {
|
||||
@@ -873,7 +926,8 @@ impl LspManager {
|
||||
let mut attached = Attached { server: server.clone(), opened_gen: None };
|
||||
if let Some(run) = server.running() {
|
||||
if run.caps.read().open_close {
|
||||
user_did_open(server, &run, &d.path, &d.uri, d.did_open_params());
|
||||
let language_id = self.languages.server_language_id(&d.language, &server.name);
|
||||
user_did_open(server, &run, &d.path, &d.uri, d.did_open_params(&language_id));
|
||||
}
|
||||
attached.opened_gen = Some(run.generation);
|
||||
opened.push((id, server.clone()));
|
||||
@@ -1148,7 +1202,7 @@ impl LspManager {
|
||||
} else {
|
||||
let open_close = run.caps.read().open_close;
|
||||
for (id, d) in docs.iter_mut().filter(|(_, d)| d.notebook.is_none()) {
|
||||
let params = d.did_open_params();
|
||||
let params = d.did_open_params(&self.languages.server_language_id(&d.language, &server.name));
|
||||
for a in
|
||||
d.servers.iter_mut().filter(|a| a.server.id == server.id && a.opened_gen != Some(generation))
|
||||
{
|
||||
@@ -1338,6 +1392,7 @@ impl LspManager {
|
||||
self.open_razor_document(uri.as_str(), true);
|
||||
}
|
||||
self.attach(doc, path.to_owned(), uri, language, version, text, servers);
|
||||
self.wake_joined(language, path);
|
||||
self.schedule_injections(doc);
|
||||
}
|
||||
|
||||
@@ -1392,15 +1447,18 @@ impl LspManager {
|
||||
let mut docs = self.docs.lock();
|
||||
let already_detected =
|
||||
compose_detected && docs.values().any(|d| d.compose_detected && d.path == state.path);
|
||||
let params = state.did_open_params();
|
||||
for a in &mut state.servers {
|
||||
let mut servers = std::mem::take(&mut state.servers);
|
||||
for a in &mut servers {
|
||||
if let Some(run) = a.server.running() {
|
||||
if run.caps.read().open_close {
|
||||
user_did_open(&a.server, &run, &state.path, &state.uri, params.clone());
|
||||
let language_id = self.languages.server_language_id(&state.language, &a.server.name);
|
||||
let params = state.did_open_params(&language_id);
|
||||
user_did_open(&a.server, &run, &state.path, &state.uri, params);
|
||||
}
|
||||
a.opened_gen = Some(run.generation);
|
||||
}
|
||||
}
|
||||
state.servers = servers;
|
||||
docs.insert(doc, state);
|
||||
compose_detected && !already_detected
|
||||
};
|
||||
@@ -4632,7 +4690,7 @@ impl LspManager {
|
||||
.iter()
|
||||
.filter(|a| {
|
||||
!wanted.iter().any(|w| w.id == a.server.id)
|
||||
&& (configs.iter().any(|c| c.fallback && c.name == a.server.name)
|
||||
&& (configs.iter().any(|c| (c.fallback || c.joins.is_some()) && c.name == a.server.name)
|
||||
|| configs.iter().any(|c| c.replaces.contains(&a.server.name))
|
||||
|| (a.server.name == "clangd" && wanted.iter().any(|s| s.name == arduino::SERVER)))
|
||||
})
|
||||
|
||||
@@ -460,8 +460,9 @@ impl LspManager {
|
||||
guard.razor.push(uri.clone());
|
||||
}
|
||||
if t.server.hold_transient(&path, t.run.generation) {
|
||||
let language = self.languages.server_language_id(&language, &t.server.name);
|
||||
let params = json!({
|
||||
"textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text }
|
||||
"textDocument": { "uri": uri, "languageId": language, "version": 0, "text": text }
|
||||
});
|
||||
if let Err(e) = t.run.peer.notify("textDocument/didOpen", params) {
|
||||
tracing::debug!("{}: didOpen: {e}", t.server.name);
|
||||
@@ -534,8 +535,8 @@ impl TransientFiles<'_> {
|
||||
let open = self.server.hold_transient(path, self.run.generation);
|
||||
let receiver = diagnostics.then(|| self.server.watch_transient_diagnostics(path));
|
||||
if open {
|
||||
let params =
|
||||
json!({ "textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text } });
|
||||
let language = self.mgr.languages.server_language_id(language, &self.server.name);
|
||||
let params = json!({ "textDocument": { "uri": uri, "languageId": language, "version": 0, "text": text } });
|
||||
if let Err(e) = self.run.peer.notify("textDocument/didOpen", params) {
|
||||
tracing::debug!("{}: didOpen: {e}", self.server.name);
|
||||
}
|
||||
|
||||
@@ -270,6 +270,9 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
language_id: None,
|
||||
joins: None,
|
||||
files: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
@@ -9189,6 +9192,144 @@ async fn c_family_files_use_sourcekit_lsp_only_with_an_xcode_bsp_config() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A server that knows a language's documents under another id (a PHP server on a
|
||||
/// Blade view) is told that one; the others are told the language's own.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_server_is_told_the_language_id_it_knows_the_documents_by() {
|
||||
let servers = [("known", incremental_caps()), ("own", incremental_caps())];
|
||||
let h = harness_languages(&[("view", "vw", &servers), ("base", "bs", &servers)], |cfg| {
|
||||
if cfg.name == "known" {
|
||||
cfg.language_id = Some("base".into());
|
||||
}
|
||||
});
|
||||
let told = |server: &str, path: &Path| -> Option<Value> {
|
||||
let uri = json!(uri_of(path));
|
||||
let opened = h.launcher.state(server).notified("textDocument/didOpen");
|
||||
opened.iter().find(|o| o["textDocument"]["uri"] == uri).map(|o| o["textDocument"]["languageId"].clone())
|
||||
};
|
||||
// Opened before the servers run, once they do, and as the other language.
|
||||
let (_, first) = h.open("a.vw", "one");
|
||||
h.wait_status("known", ServerStatus::Ready).await;
|
||||
h.wait_status("own", ServerStatus::Ready).await;
|
||||
let (_, second) = h.open("b.vw", "two");
|
||||
let base = h.root.join("c.bs");
|
||||
std::fs::write(&base, "three").unwrap();
|
||||
h.mgr.did_open(DocId::next(), &base, &LanguageId::new("base"), 1, "three");
|
||||
eventually(|| told("known", &base).is_some() && told("own", &base).is_some()).await;
|
||||
for view in [&first, &second] {
|
||||
assert_eq!(told("known", view), Some(json!("base")), "{}", view.display());
|
||||
assert_eq!(told("own", view), Some(json!("view")), "{}", view.display());
|
||||
}
|
||||
assert_eq!((told("known", &base), told("own", &base)), (Some(json!("base")), Some(json!("base"))));
|
||||
// One process each, for both languages.
|
||||
assert_eq!(h.launcher.state("known").requested("initialize").len(), 1);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// `code` is served by `main`, or by `alt` while `main` is missing; `tpl` by `own`, and by
|
||||
/// `alt` wherever `alt` is the server of `code` (`joins`), for the files `files` names.
|
||||
fn joining_harness(files: &[&str]) -> Harness {
|
||||
let caps = incremental_caps;
|
||||
let h = harness_languages(
|
||||
&[("tpl", "tp", &[("own", caps()), ("alt", caps())]), ("code", "cd", &[("main", caps()), ("alt", caps())])],
|
||||
|cfg| {
|
||||
if cfg.name == "alt" {
|
||||
cfg.fallback = true;
|
||||
cfg.joins = Some("code".into());
|
||||
cfg.files = files.iter().map(|f| f.to_string()).collect();
|
||||
}
|
||||
},
|
||||
);
|
||||
std::fs::write(h.root.join("mock.toml"), "").unwrap();
|
||||
h
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_joining_server_reads_the_files_only_while_it_serves_the_other_language() {
|
||||
let opened =
|
||||
|h: &Harness, server: &str, path: &Path| h.launcher.state(server).docs.lock().contains_key(&uri_of(path));
|
||||
|
||||
// The other language has its preferred server: the template is not sent to the alternative,
|
||||
// which never starts.
|
||||
let h = joining_harness(&[]);
|
||||
let (_, template) = h.open("page.tp", "x");
|
||||
h.wait_status("own", ServerStatus::Ready).await;
|
||||
h.wait_status("main", ServerStatus::Ready).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert!(h.statuses("alt").is_empty());
|
||||
assert!(opened(&h, "own", &template) && !opened(&h, "main", &template));
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
// The preferred one is missing: the alternative serves the other language, so it reads
|
||||
// the template too, opened before any file of that language.
|
||||
let h = joining_harness(&[]);
|
||||
h.launcher.state("main").missing.store(true, Ordering::SeqCst);
|
||||
let (_, template) = h.open("page.tp", "x");
|
||||
h.wait_status("main", ServerStatus::Missing).await;
|
||||
h.wait_status("alt", ServerStatus::Ready).await;
|
||||
eventually(|| opened(&h, "alt", &template)).await;
|
||||
assert!(opened(&h, "own", &template));
|
||||
let code = h.root.join("a.cd");
|
||||
std::fs::write(&code, "y").unwrap();
|
||||
h.mgr.did_open(DocId::next(), &code, &LanguageId::new("code"), 1, "y");
|
||||
let (_, later) = h.open("later.tp", "z");
|
||||
eventually(|| opened(&h, "alt", &code) && opened(&h, "alt", &later)).await;
|
||||
assert!(!opened(&h, "own", &code));
|
||||
// One process for both languages.
|
||||
assert_eq!(h.launcher.state("alt").requested("initialize").len(), 1);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn two_languages_cannot_join_each_others_joined_server() {
|
||||
let h = harness_languages(
|
||||
&[
|
||||
("tpl", "tp", &[("own", incremental_caps()), ("to-code", incremental_caps())]),
|
||||
("code", "cd", &[("to-tpl", incremental_caps())]),
|
||||
],
|
||||
|cfg| {
|
||||
cfg.joins = match cfg.name.as_str() {
|
||||
"to-code" => Some("code".into()),
|
||||
"to-tpl" => Some("tpl".into()),
|
||||
_ => None,
|
||||
};
|
||||
},
|
||||
);
|
||||
std::fs::write(h.root.join("mock.toml"), "").unwrap();
|
||||
h.open("page.tp", "x");
|
||||
h.wait_status("own", ServerStatus::Ready).await;
|
||||
assert!(h.statuses("to-code").is_empty() && h.statuses("to-tpl").is_empty());
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_joining_server_is_left_alone_outside_its_root_markers_and_files() {
|
||||
// No root marker of the server above the file: the other language's servers are not
|
||||
// started for a template, however they would fare.
|
||||
let h = joining_harness(&[]);
|
||||
std::fs::remove_file(h.root.join("mock.toml")).unwrap();
|
||||
h.launcher.state("main").missing.store(true, Ordering::SeqCst);
|
||||
h.open("page.tp", "x");
|
||||
h.wait_status("own", ServerStatus::Ready).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert!(h.statuses("main").is_empty() && h.statuses("alt").is_empty());
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
// Only the files its patterns name.
|
||||
let h = joining_harness(&["**/lang/**/*.tp"]);
|
||||
h.launcher.state("main").missing.store(true, Ordering::SeqCst);
|
||||
std::fs::create_dir_all(h.root.join("lang/en")).unwrap();
|
||||
let (_, named) = h.open("lang/en/messages.tp", "x");
|
||||
let (_, other) = h.open("language.tp", "y");
|
||||
h.wait_status("alt", ServerStatus::Ready).await;
|
||||
let alt = h.launcher.state("alt");
|
||||
eventually(|| alt.docs.lock().contains_key(&uri_of(&named))).await;
|
||||
h.wait_status("own", ServerStatus::Ready).await;
|
||||
eventually(|| h.launcher.state("own").docs.lock().contains_key(&uri_of(&other))).await;
|
||||
assert!(!alt.docs.lock().contains_key(&uri_of(&other)));
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Razor
|
||||
|
||||
const ROSLYN: &str = "roslyn-language-server";
|
||||
|
||||
@@ -421,6 +421,9 @@ async fn missing_binary_is_reported_with_install_hint() {
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
language_id: None,
|
||||
joins: None,
|
||||
files: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
@@ -715,6 +718,9 @@ async fn typescript_language_server_end_to_end() {
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
language_id: None,
|
||||
joins: None,
|
||||
files: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
@@ -770,6 +776,9 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
language_id: None,
|
||||
joins: None,
|
||||
files: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
@@ -1825,6 +1834,96 @@ async fn phoxite_pulls_a_member_up_end_to_end() {
|
||||
mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// Phoxite as the project's PHP server also reads its Twig templates: a template opened
|
||||
/// before any PHP file starts it, as a `twig` document, and it answers there.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires phoxite-lsp on PATH (or OPENIDEA_TEST_PHOXITE_LSP)"]
|
||||
async fn phoxite_serves_the_twig_templates_of_the_project_it_serves_php_in() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::create_dir_all(root.join("templates/blog")).unwrap();
|
||||
std::fs::write(root.join("composer.json"), r#"{"require":{"symfony/framework-bundle":"^7.0"}}"#).unwrap();
|
||||
let base = root.join("templates").join("base.html.twig");
|
||||
std::fs::write(&base, "<main>{% block body %}{% endblock %}</main>\n").unwrap();
|
||||
let path = root.join("templates").join("blog").join("show.html.twig");
|
||||
let source = "{% extends 'base.html.twig' %}\n{% block body %}<h1>{{ title }}</h1>{% endblock %}\n";
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let registry = LanguageRegistry::load(None).unwrap();
|
||||
let twig = registry.detect(&path, None);
|
||||
assert_eq!(twig.as_str(), "twig");
|
||||
// Phoxite alone, as when the other PHP servers are not installed.
|
||||
let languages = ["php", "twig"].map(|id| {
|
||||
let mut language = registry.get(&LanguageId::new(id)).unwrap();
|
||||
language.language_servers.retain(|s| s.name == "phoxite");
|
||||
assert_eq!(language.language_servers.len(), 1, "{id}");
|
||||
if let Ok(bin) = std::env::var("OPENIDEA_TEST_PHOXITE_LSP") {
|
||||
language.language_servers[0].command = bin;
|
||||
}
|
||||
language
|
||||
});
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(languages.to_vec()));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &path, &twig, 1, source);
|
||||
retry("phoxite ready", Duration::from_secs(30), || {
|
||||
let status = last_status(&events, "phoxite");
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("phoxite failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
// On `base.html.twig` in `extends`.
|
||||
let defs = retry("the extended template", Duration::from_secs(60), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.goto(doc, Pos::new(0, 15), GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(Path::new(&*defs[0].path).file_name(), base.file_name(), "{defs:?}");
|
||||
mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// Intelephense serves a Blade view as the PHP document it knows: it starts for one opened
|
||||
/// before any PHP file, and answers there.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires intelephense on PATH"]
|
||||
async fn intelephense_reads_a_blade_view_as_php() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
let root = dunce::simplified(&root).to_path_buf();
|
||||
std::fs::create_dir_all(root.join("resources/views")).unwrap();
|
||||
std::fs::write(root.join("composer.json"), "{}").unwrap();
|
||||
let path = root.join("resources").join("views").join("home.blade.php");
|
||||
let source = "<?php function greet(string $name): string { return $name; } ?>
|
||||
<p><?= greet('a') ?></p>
|
||||
";
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let registry = LanguageRegistry::load(None).unwrap();
|
||||
let blade = registry.detect(&path, None);
|
||||
assert_eq!(blade.as_str(), "blade");
|
||||
let mut language = registry.get(&blade).unwrap();
|
||||
language.language_servers.retain(|s| s.name == "intelephense");
|
||||
assert_eq!(language.language_servers[0].language_id.as_deref(), Some("php"));
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![language]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &path, &blade, 1, source);
|
||||
retry("intelephense ready", Duration::from_secs(30), || {
|
||||
let status = last_status(&events, "intelephense");
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("intelephense failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
// On the `greet` call in the PHP echo tag: Blade's own `{{ }}` is markup to it.
|
||||
let defs = retry("the function", Duration::from_secs(60), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.goto(doc, Pos::new(1, 8), GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(defs[0].range.start.line, 0, "{defs:?}");
|
||||
mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// jdtls keeps building incrementally even though the IDE's Java build compiles what runs:
|
||||
/// its build is what reports an API change in one Maven module in the files of the modules
|
||||
/// that use it, open or not. With `java.autobuild.enabled: false` (and
|
||||
|
||||
@@ -1546,6 +1546,10 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
}
|
||||
}
|
||||
|
||||
if name == "phoxite" {
|
||||
crate::php::configure_phoxite(cfg, root, s);
|
||||
}
|
||||
|
||||
// Node-based servers (`#!/usr/bin/env node`) run on the selected Node.js.
|
||||
if let Some(dir) = node_dir(root, s) {
|
||||
path_dirs.push(dir);
|
||||
@@ -1804,6 +1808,9 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
language_id: None,
|
||||
joins: None,
|
||||
files: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
|
||||
@@ -189,6 +189,46 @@ pub fn include_paths(root: &Path, s: &Settings) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What Settings › PHP says, as Phoxite's own settings: the PHP version when one is chosen
|
||||
/// (Phoxite reads `composer.json` itself for Auto, and the stubs of its `ext-*`), the include
|
||||
/// paths, the additional stubs and the interpreter that runs the project's analysers. The
|
||||
/// `settings` of Settings › Language Servers › Phoxite go on top, written as Phoxite's own
|
||||
/// object or wrapped in `phoxite`. Nothing is set when all of that is empty.
|
||||
///
|
||||
/// Phoxite takes its settings from `initializationOptions.settings` at startup and replaces
|
||||
/// them all with each `workspace/didChangeConfiguration`, where it reads the `phoxite`
|
||||
/// section: both carry the same object, so the notification that follows startup changes
|
||||
/// nothing.
|
||||
pub fn configure_phoxite(cfg: &mut LanguageServerConfig, root: &Path, s: &Settings) {
|
||||
let php = &s.languages.php;
|
||||
let mut own = json!({});
|
||||
let level = php.language_level.trim();
|
||||
if version(level).is_some() {
|
||||
own["phpVersion"] = json!(level);
|
||||
}
|
||||
let include = include_paths(root, s);
|
||||
if !include.is_empty() {
|
||||
own["includePaths"] = json!(include);
|
||||
}
|
||||
let stubs: Vec<&str> = php.stubs.iter().map(|stub| stub.trim()).filter(|stub| !stub.is_empty()).collect();
|
||||
if !stubs.is_empty() {
|
||||
own["stubs"] = json!(stubs);
|
||||
}
|
||||
if let Some(interpreter) = setting_path(root, &php.interpreter) {
|
||||
own["analyzers"] = json!({ "phpPath": interpreter.to_string_lossy() });
|
||||
}
|
||||
if let Some(user) = s.language_servers.get(&cfg.name).and_then(|ls| ls.settings.as_ref()) {
|
||||
merge(&mut own, user.get("phoxite").unwrap_or(user).clone());
|
||||
}
|
||||
if own.as_object().is_none_or(|own| own.is_empty()) {
|
||||
return;
|
||||
}
|
||||
merge_init_options(cfg, json!({ "settings": own.clone() }));
|
||||
let mut settings = cfg.settings.take().filter(Value::is_object).unwrap_or_else(|| json!({}));
|
||||
merge(&mut settings, json!({ "phoxite": own }));
|
||||
cfg.settings = Some(settings);
|
||||
}
|
||||
|
||||
/// `vendor/bin/phpstan analyse` of `files` with a JSON report and the configuration file of
|
||||
/// Settings › PHP, run from `root` with Xdebug off: in debug mode it would try to reach a
|
||||
/// debugger on every run. The selected PHP runs the script itself (and is first on `PATH`, as for
|
||||
|
||||
@@ -39,6 +39,9 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
|
||||
connect: None,
|
||||
fallback: false,
|
||||
replaces: Vec::new(),
|
||||
language_id: None,
|
||||
joins: None,
|
||||
files: Vec::new(),
|
||||
features: Vec::new(),
|
||||
code_action_kinds: Vec::new(),
|
||||
max_java: None,
|
||||
@@ -3256,6 +3259,59 @@ fn intelephense_gets_the_required_stubs_and_include_paths() {
|
||||
assert_eq!(other.initialization_options, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phoxite_gets_the_php_settings_at_startup_and_on_every_configuration_change() {
|
||||
use serde_json::json;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// Auto: Phoxite reads the version and the `ext-*` stubs from composer.json itself.
|
||||
std::fs::write(tmp.path().join("composer.json"), r#"{"require": {"php": "^8.1", "ext-redis": "*"}}"#).unwrap();
|
||||
let mut cfg = server("phoxite");
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), &Settings::default());
|
||||
assert_eq!((cfg.initialization_options, cfg.settings), (None, None));
|
||||
|
||||
let mut s = Settings::default();
|
||||
s.languages.php.language_level = "8.3".into();
|
||||
s.languages.php.stubs = vec!["wordpress".into(), " ".into()];
|
||||
s.languages.php.include_paths = vec!["../platform".into()];
|
||||
s.languages.php.interpreter = "/opt/php83/bin/php".into();
|
||||
// As the settings resolve it (a drive is added on Windows).
|
||||
let interpreter = crate::apply::setting_path(tmp.path(), "/opt/php83/bin/php").unwrap();
|
||||
let own = json!({
|
||||
"phpVersion": "8.3",
|
||||
"includePaths": [tmp.path().join("../platform").to_string_lossy()],
|
||||
"stubs": ["wordpress"],
|
||||
"analyzers": {"phpPath": interpreter.to_string_lossy()},
|
||||
});
|
||||
let mut cfg = server("phoxite");
|
||||
cfg.initialization_options = Some(toml::Value::try_from(json!({"cacheDir": "/cache"})).unwrap());
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
|
||||
assert_eq!(
|
||||
serde_json::to_value(&cfg.initialization_options).unwrap(),
|
||||
json!({"cacheDir": "/cache", "settings": own})
|
||||
);
|
||||
// What `workspace/didChangeConfiguration` carries: Phoxite reads the `phoxite` section.
|
||||
assert_eq!(cfg.settings, Some(json!({"phoxite": own})));
|
||||
|
||||
// The server's own settings in Settings › Language Servers go on top, wrapped or not.
|
||||
for user in [
|
||||
json!({"frameworks": {"wordpress": "enabled"}, "phpVersion": "8.4"}),
|
||||
json!({"phoxite": {"frameworks": {"wordpress": "enabled"}, "phpVersion": "8.4"}}),
|
||||
] {
|
||||
let mut s = s.clone();
|
||||
s.language_servers.entry("phoxite".into()).or_default().settings = Some(user);
|
||||
let mut cfg = server("phoxite");
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
|
||||
let sent = &cfg.settings.as_ref().unwrap()["phoxite"];
|
||||
assert_eq!(sent["frameworks"], json!({"wordpress": "enabled"}));
|
||||
assert_eq!((&sent["phpVersion"], &sent["stubs"]), (&json!("8.4"), &json!(["wordpress"])));
|
||||
assert_eq!(&serde_json::to_value(&cfg.initialization_options).unwrap()["settings"], sent);
|
||||
}
|
||||
|
||||
let mut other = server("intelephense");
|
||||
configure_server(&mut other, tmp.path(), tmp.path(), &s);
|
||||
assert_eq!(other.settings, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_constraints_change_only_protocol_settings() {
|
||||
use serde_json::json;
|
||||
|
||||
@@ -98,6 +98,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| AsciiDoc | `asciidoc` | `.adoc`, `.asciidoc` | Yes | — | — | — |
|
||||
| Astro | `astro` | `.astro` | Yes | — | **astro-ls** + **oxlint** | — |
|
||||
| Batch | `bat` | `.bat`, `.cmd` | Yes | — | — | — |
|
||||
| Blade | `blade` | `.blade.php` | Yes | — | **intelephense** → **phpantom** → **phpactor** → **phoxite** → devsense-php-ls + **laravel-lsp** | — |
|
||||
| C | `c` | `.c`, `.h` | Yes | Yes | **clangd** | lldb-dap |
|
||||
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **roslyn-language-server** → **csharp-ls** | **netcoredbg** |
|
||||
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | Yes | Yes | **clangd** | lldb-dap |
|
||||
@@ -152,7 +153,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird |
|
||||
| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — |
|
||||
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — |
|
||||
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor → **phoxite** → devsense-php-ls + **laravel-lsp** | **php-debug** |
|
||||
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → **phpantom** → **phpactor** → **phoxite** → devsense-php-ls + **laravel-lsp** | **php-debug** |
|
||||
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
|
||||
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | Yes | — | powershell-editor-services | — |
|
||||
| Prisma | `prisma` | `.prisma` | Yes | Yes | **prisma-language-server** | — |
|
||||
@@ -176,6 +177,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | Yes | Yes | **terraform-ls** | — |
|
||||
| Terraform Variables | `terraform-vars` | `.tfvars` | Yes | Yes | **terraform-ls** | — |
|
||||
| TOML | `toml` | `.toml` | Yes | Yes | **taplo** | — |
|
||||
| Twig | `twig` | `.twig` | Yes | — | **phoxite** (with PHP) | — |
|
||||
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | Yes | Yes | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** + **biome** | **js-debug** |
|
||||
| TypeScript JSX | `typescriptreact` | `.tsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
|
||||
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
---
|
||||
title: "PHP"
|
||||
description: "Intelephense, PHP interpreters and language level, Composer, PHPUnit and Pest, PHPStan, Xdebug debugging and Laravel support."
|
||||
description: "Intelephense and Phoxite, PHP interpreters and language level, Composer, PHPUnit and Pest, PHPStan, Xdebug debugging, Blade and Twig templates, and Laravel, Symfony and other framework support."
|
||||
---
|
||||
|
||||
OpenIDEA highlights PHP files (`.php`, `.phtml`, `.phpt` and older `.php3`–`.php5`, plus files starting with `<?php` or a `php` shebang) out of the box. Completion, navigation, refactoring and diagnostics come from Intelephense. Composer scripts and PHPUnit/Pest suites are detected as run configurations, and Xdebug sessions run through the PHP Debug adapter. See the [support matrix](/en/languages/index) for other languages.
|
||||
OpenIDEA highlights PHP files (`.php`, `.phtml`, `.phpt` and older `.php3`–`.php5`, plus files starting with `<?php` or a `php` shebang), Blade views (`.blade.php`) and Twig templates (`.twig`) out of the box. Completion, navigation, refactoring and diagnostics come from Intelephense. Composer scripts, PHPUnit/Pest suites and Laravel's development server are detected as run configurations, and Xdebug sessions run through the PHP Debug adapter. See the [support matrix](/en/languages/index) for other languages.
|
||||
|
||||
## Language servers
|
||||
|
||||
| Server | When it runs |
|
||||
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
|
||||
| `phpactor` | Fallback: used only while Intelephense is not installed. |
|
||||
| `phoxite` | Alternative with its own Laravel and Blade support: used while neither server above is installed, or when you pick it in **Settings › Languages & Frameworks › Language Servers**. |
|
||||
| `phpantom` | Fallback: used only while Intelephense is not installed. |
|
||||
| `phpactor` | Fallback: used only while neither server above is installed. |
|
||||
| `phoxite` | Alternative with its own framework, Blade and Twig support (see [Frameworks](#frameworks)): used while no server above is installed, or when you pick it in **Settings › Languages & Frameworks › Language Servers**. |
|
||||
| `devsense-php-ls` | Alternative whose engine ships as native builds, so the server itself needs no Node or PHP: used while no server above is installed, or when you pick it in **Settings › Languages & Frameworks › Language Servers**. |
|
||||
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
|
||||
|
||||
While Phoxite or DEVSENSE serves a project, `laravel-lsp` is not started: they answer the Laravel strings themselves.
|
||||
A Blade view is served by the same servers as the project's PHP files. While Phoxite or DEVSENSE serves a project, `laravel-lsp` is not started: they answer the Laravel strings themselves.
|
||||
|
||||
Phoxite, where it is the project's PHP server, also reads files of other languages: Twig templates, `.env` files and Laravel's `lang/*.json`. It runs once for all of them, next to those languages' own servers, and is never started for a project without PHP.
|
||||
|
||||
DEVSENSE is usable without a licence for everyday code insight (completion, hover, go to definition, references, diagnostics, Laravel and Blade support); its refactorings and call/type hierarchy need a DEVSENSE licence.
|
||||
|
||||
@@ -27,14 +30,15 @@ Intelephense checks code against the project's PHP version (see [Language level]
|
||||
|
||||
When a `.php` file opens and Intelephense is missing, a notification offers **Install**. The IDE installs it with npm into its own tools folder (needs `npm` or `pnpm` on `PATH`). Everything is also listed in **Settings › Languages & Frameworks › Language Servers**.
|
||||
|
||||
| Tool | Installed with |
|
||||
| ------------------ | ---------------------------------------------------------------------- |
|
||||
| Intelephense | npm (`intelephense`) |
|
||||
| Laravel LSP | GitHub release (`laravel/lsp`) |
|
||||
| Phoxite | GitHub release (`samehelhawary/phoxite`) |
|
||||
| DEVSENSE | npm (`devsense-php-ls`); needs Node.js to launch |
|
||||
| PHP Debug (Xdebug) | Open VSX (`xdebug.php-debug`); needs Node.js to run |
|
||||
| phpactor | Not installable from the IDE; install it yourself and put it on `PATH` |
|
||||
| Tool | Installed with |
|
||||
| ------------------ | ------------------------------------------------------------------ |
|
||||
| Intelephense | npm (`intelephense`) |
|
||||
| PHPantom | GitHub release (`PHPantom-dev/phpantom_lsp`) |
|
||||
| Phpactor | GitHub release (`phpactor/phpactor`, `phpactor.phar`); runs on PHP |
|
||||
| Laravel LSP | GitHub release (`laravel/lsp`) |
|
||||
| Phoxite | GitHub release (`samehelhawary/phoxite`) |
|
||||
| DEVSENSE | npm (`devsense-php-ls`); needs Node.js to launch |
|
||||
| PHP Debug (Xdebug) | Open VSX (`xdebug.php-debug`); needs Node.js to run |
|
||||
|
||||
### PHP interpreter
|
||||
|
||||
@@ -53,6 +57,8 @@ Also on this page:
|
||||
- **Include paths**: folders outside the project that Intelephense indexes too, such as a platform your module extends.
|
||||
- **Additional stubs**: Intelephense stub sets on top of its defaults (for example `wordpress`). Each `ext-*` in `require` / `require-dev` of `composer.json` adds its own stubs automatically.
|
||||
|
||||
Phoxite receives the same settings: a language level you choose (for **Auto** it reads `composer.json` itself), the include paths, the additional stubs, and the PHP interpreter for the analysers it runs. Its own settings, such as `frameworks` to turn a framework's support on or off (`{ "frameworks": { "wordpress": "disabled" } }`), go in **Settings › Languages & Frameworks › Language Servers › Phoxite › Workspace Configuration**, or in a `phoxite.json` at the project root.
|
||||
|
||||
### Composer
|
||||
|
||||
In a Composer project without `vendor/`, or whose installed packages differ from `composer.lock`, a banner "Composer dependencies are not installed" appears above PHP files and `composer.json`, with **Install** (runs `composer install` on the configured PHP) and **Ignore**.
|
||||
@@ -84,14 +90,34 @@ Debugging uses PHP Debug (vscode-php-debug) with Xdebug. The selected PHP must l
|
||||
|
||||
See [Debugging](/en/guide/debugging).
|
||||
|
||||
## Framework support
|
||||
## Frameworks
|
||||
|
||||
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration. With Phoxite as the PHP server, routes, views, config, translations and Eloquent models get completion, navigation and rename from it instead.
|
||||
- **WordPress** and similar platforms: add their stubs under **Additional stubs** and the platform folder under **Include paths**.
|
||||
Run configurations and template highlighting work with any PHP server. The names a framework gives things (routes, views, services, configuration keys, hooks) are understood by Phoxite: where a section says "with Phoxite", pick it as the PHP server in **Settings › Languages & Frameworks › Language Servers**. Phoxite finds the frameworks of a project from `composer.json` and their marker files, and supports each one it finds.
|
||||
|
||||
### Laravel
|
||||
|
||||
- **Run and debug**: an `artisan serve` configuration.
|
||||
- **Blade views** (`.blade.php`) are highlighted: HTML, directives, `{{ }}` and `{!! !!}` echoes and the PHP inside them, with `{{-- --}}` comments.
|
||||
- **Laravel LSP**, with Intelephense: hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`.
|
||||
- **With Phoxite**: completion, navigation, Find Usages, rename and "undefined" warnings for route names, views, config keys, translation keys, environment variables, validation rules, Eloquent columns and relations, Livewire components and Inertia pages; completion, hover, signature help and navigation inside Blade views; Find Usages and Rename of a key in `.env` and in `lang/*.json`.
|
||||
|
||||
### Symfony
|
||||
|
||||
- **Twig templates** (`.twig`) are highlighted: HTML, with tags, expressions and `{# #}` comments; blocks fold.
|
||||
- **With Phoxite**: completion, navigation and rename for route names, template names, services and parameters, translation keys and Doctrine fields; in Twig templates, completion, hover, navigation (to an extended or included template, a function, a filter, a route), rename, the outline, formatting and problems.
|
||||
|
||||
### WordPress, Drupal, Magento and Joomla
|
||||
|
||||
With Phoxite, in PHP: completion, navigation and Find Usages for the platform's names, such as WordPress hooks, shortcodes, options and block names, Drupal services, routes and permissions, Magento's events, configuration paths, ACL resources and layout handles, Joomla's language keys, layouts and form fields.
|
||||
|
||||
Without Phoxite, add a platform's stubs under **Additional stubs** (for example `wordpress`) and its folder under **Include paths**.
|
||||
|
||||
### CodeIgniter, Yii, CakePHP and Laminas
|
||||
|
||||
With Phoxite, in PHP: completion, navigation and Find Usages for the framework's names (routes, views or templates, config keys, translation messages, services and components), and the types of the services, models and view variables the framework provides.
|
||||
|
||||
## Limitations
|
||||
|
||||
- No Blade or Twig template support with Intelephense; only `.php` files get PHP code insight. Phoxite adds code insight in `.blade.php` files, without Blade highlighting.
|
||||
- phpactor is not installed by the IDE.
|
||||
- With Intelephense, PHPantom, Phpactor or DEVSENSE, Blade views and Twig templates are highlighted but get no code insight of their own (a Blade view is read as PHP); with Phoxite they do.
|
||||
- Run with Coverage is not available for PHPUnit.
|
||||
- Debugging needs the Xdebug extension in your PHP; the IDE does not install it.
|
||||
@@ -93,6 +93,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| AsciiDoc | `asciidoc` | `.adoc`, `.asciidoc` | 是 | — | — | — |
|
||||
| Astro | `astro` | `.astro` | 是 | — | **astro-ls** + **oxlint** | — |
|
||||
| Batch | `bat` | `.bat`, `.cmd` | 是 | — | — | — |
|
||||
| Blade | `blade` | `.blade.php` | 是 | — | **intelephense** → **phpantom** → **phpactor** → **phoxite** → devsense-php-ls + **laravel-lsp** | — |
|
||||
| C | `c` | `.c`, `.h` | 是 | 是 | **clangd** | lldb-dap |
|
||||
| C# | `csharp` | `.cs`, `.csx` | 是 | 是 | **roslyn-language-server** → **csharp-ls** | **netcoredbg** |
|
||||
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | 是 | 是 | **clangd** | lldb-dap |
|
||||
@@ -147,7 +148,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird |
|
||||
| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — |
|
||||
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — |
|
||||
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor → **phoxite** → devsense-php-ls + **laravel-lsp** | **php-debug** |
|
||||
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → **phpantom** → **phpactor** → **phoxite** → devsense-php-ls + **laravel-lsp** | **php-debug** |
|
||||
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
|
||||
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | 是 | — | powershell-editor-services | — |
|
||||
| Prisma | `prisma` | `.prisma` | 是 | 是 | **prisma-language-server** | — |
|
||||
@@ -170,6 +171,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | 是 | 是 | **terraform-ls** | — |
|
||||
| Terraform Variables | `terraform-vars` | `.tfvars` | 是 | 是 | **terraform-ls** | — |
|
||||
| TOML | `toml` | `.toml` | 是 | 是 | **taplo** | — |
|
||||
| Twig | `twig` | `.twig` | 是 | — | **phoxite**(随 PHP) | — |
|
||||
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | 是 | 是 | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** + **biome** | **js-debug** |
|
||||
| TypeScript JSX | `typescriptreact` | `.tsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
|
||||
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
---
|
||||
title: "PHP"
|
||||
description: "Intelephense、PHP 解释器与语言级别、Composer、PHPUnit 与 Pest、PHPStan、Xdebug 调试以及 Laravel 支持。"
|
||||
description: "Intelephense 与 Phoxite、PHP 解释器与语言级别、Composer、PHPUnit 与 Pest、PHPStan、Xdebug 调试、Blade 与 Twig 模板,以及 Laravel、Symfony 等框架支持。"
|
||||
---
|
||||
|
||||
OpenIDEA 开箱即可高亮 PHP 文件(`.php`、`.phtml`、`.phpt` 以及老式的 `.php3`–`.php5`,还有以 `<?php` 或 `php` shebang 开头的文件)。补全、跳转、重构和诊断由 Intelephense 提供。Composer 脚本和 PHPUnit/Pest 测试套件会被识别为运行配置,Xdebug 调试通过 PHP Debug 适配器进行。其他语言见[支持矩阵](/zh/languages/index)。
|
||||
OpenIDEA 开箱即可高亮 PHP 文件(`.php`、`.phtml`、`.phpt` 以及老式的 `.php3`–`.php5`,还有以 `<?php` 或 `php` shebang 开头的文件)、Blade 视图(`.blade.php`)和 Twig 模板(`.twig`)。补全、跳转、重构和诊断由 Intelephense 提供。Composer 脚本、PHPUnit/Pest 测试套件以及 Laravel 的开发服务器会被识别为运行配置,Xdebug 调试通过 PHP Debug 适配器进行。其他语言见[支持矩阵](/zh/languages/index)。
|
||||
|
||||
## 语言服务器
|
||||
|
||||
| 服务器 | 启用条件 |
|
||||
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
|
||||
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
|
||||
| `phoxite` | 备选,自带 Laravel 和 Blade 支持:仅在以上两个服务器都未安装时使用,或在 **设置 › 语言和框架 › 语言服务器** 中选中它时使用。 |
|
||||
| `phpantom` | 备选:仅在未安装 Intelephense 时使用。 |
|
||||
| `phpactor` | 备选:仅在以上两个服务器都未安装时使用。 |
|
||||
| `phoxite` | 备选,自带框架、Blade 和 Twig 支持(见[框架](#框架)):仅在以上服务器都未安装时使用,或在 **设置 › 语言和框架 › 语言服务器** 中选中它时使用。 |
|
||||
| `devsense-php-ls` | 备选,引擎为各平台原生构建,服务器本身无需 Node 或 PHP:仅在以上服务器都未安装时使用,或在 **设置 › 语言和框架 › 语言服务器** 中选中它时使用。 |
|
||||
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
|
||||
|
||||
Phoxite 或 DEVSENSE 为项目提供服务时不会启动 `laravel-lsp`:Laravel 相关的字符串由它们自己处理。
|
||||
Blade 视图由为项目 PHP 文件提供服务的同一组服务器处理。Phoxite 或 DEVSENSE 为项目提供服务时不会启动 `laravel-lsp`:Laravel 相关的字符串由它们自己处理。
|
||||
|
||||
Phoxite 作为项目的 PHP 服务器时,还会读取其他语言的文件:Twig 模板、`.env` 文件和 Laravel 的 `lang/*.json`。这些文件共用同一个 Phoxite 进程,与各自语言的服务器并存;没有 PHP 的项目不会启动它。
|
||||
|
||||
DEVSENSE 无需许可证即可用于日常代码智能(补全、悬停、跳转、查找引用、诊断,以及 Laravel 和 Blade 支持);其重构以及调用/类型层次结构需要 DEVSENSE 许可证。
|
||||
|
||||
@@ -27,14 +30,15 @@ Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别
|
||||
|
||||
打开 `.php` 文件时如果缺少 Intelephense,IDE 会弹出通知并提供 **安装** 按钮,用 npm 把它装进 IDE 自己的工具目录(需要 `PATH` 上有 `npm` 或 `pnpm`)。所有工具也都列在 **设置 › 语言和框架 › 语言服务器** 中。
|
||||
|
||||
| 工具 | 安装方式 |
|
||||
| ------------------ | -------------------------------------------------- |
|
||||
| Intelephense | npm(`intelephense`) |
|
||||
| Laravel LSP | GitHub release(`laravel/lsp`) |
|
||||
| Phoxite | GitHub release(`samehelhawary/phoxite`) |
|
||||
| DEVSENSE | npm(`devsense-php-ls`),启动时需要 Node.js |
|
||||
| PHP Debug (Xdebug) | Open VSX(`xdebug.php-debug`),运行时需要 Node.js |
|
||||
| phpactor | IDE 不负责安装,请自行安装并放到 `PATH` 上 |
|
||||
| 工具 | 安装方式 |
|
||||
| ------------------ | --------------------------------------------------------------------- |
|
||||
| Intelephense | npm(`intelephense`) |
|
||||
| PHPantom | GitHub release(`PHPantom-dev/phpantom_lsp`) |
|
||||
| Phpactor | GitHub release(`phpactor/phpactor` 的 `phpactor.phar`),用 PHP 运行 |
|
||||
| Laravel LSP | GitHub release(`laravel/lsp`) |
|
||||
| Phoxite | GitHub release(`samehelhawary/phoxite`) |
|
||||
| DEVSENSE | npm(`devsense-php-ls`),启动时需要 Node.js |
|
||||
| PHP Debug (Xdebug) | Open VSX(`xdebug.php-debug`),运行时需要 Node.js |
|
||||
|
||||
### PHP 解释器
|
||||
|
||||
@@ -53,6 +57,8 @@ Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别
|
||||
- **包含路径**:项目之外、也需要 Intelephense 索引的目录,例如模块所扩展的平台代码。
|
||||
- **附加存根**:在默认 stub 之外额外加载的 Intelephense stub 集(例如 `wordpress`)。`composer.json` 的 `require` / `require-dev` 中每个 `ext-*` 会自动加入对应的 stub。
|
||||
|
||||
Phoxite 也会收到这些设置:你选定的语言级别(**自动** 时它自己读取 `composer.json`)、包含路径、附加存根,以及运行分析器所用的 PHP 解释器。它自己的设置,例如用 `frameworks` 开启或关闭某个框架的支持(`{ "frameworks": { "wordpress": "disabled" } }`),写在 **设置 › 语言和框架 › 语言服务器 › Phoxite › 工作区配置** 中,或项目根目录的 `phoxite.json` 里。
|
||||
|
||||
### Composer
|
||||
|
||||
Composer 项目没有 `vendor/`,或已安装的包与 `composer.lock` 不一致时,PHP 文件和 `composer.json` 顶部会出现 “未安装 Composer 依赖” 横幅,提供 **安装**(用所配置的 PHP 执行 `composer install`)和 **忽略**。
|
||||
@@ -84,14 +90,34 @@ PHPUnit 运行配置类型包含 **目标**、**配置文件**、**测试过滤
|
||||
|
||||
详见[调试](/zh/guide/debugging)。
|
||||
|
||||
## 框架支持
|
||||
## 框架
|
||||
|
||||
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。以 Phoxite 作为 PHP 服务器时,路由、视图、配置、翻译和 Eloquent 模型的补全、跳转和重命名改由它提供。
|
||||
- **WordPress** 等平台:在 **附加存根** 中加入对应 stub,在 **包含路径** 中加入平台代码目录。
|
||||
运行配置和模板高亮适用于任何 PHP 服务器。框架为各种东西起的名字(路由、视图、服务、配置键、钩子)由 Phoxite 理解:下文标注“使用 Phoxite 时”的功能,需要在 **设置 › 语言和框架 › 语言服务器** 中把它选为 PHP 服务器。Phoxite 根据 `composer.json` 和各框架的标志文件识别项目使用的框架,并为识别出的每个框架提供支持。
|
||||
|
||||
### Laravel
|
||||
|
||||
- **运行与调试**:`artisan serve` 配置。
|
||||
- **Blade 视图**(`.blade.php`)有语法高亮:HTML、指令、`{{ }}` 和 `{!! !!}` 输出及其中的 PHP,注释为 `{{-- --}}`。
|
||||
- **Laravel LSP**(配合 Intelephense):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。
|
||||
- **使用 Phoxite 时**:路由名、视图、配置键、翻译键、环境变量、验证规则、Eloquent 字段和关联、Livewire 组件和 Inertia 页面的补全、跳转、查找用法、重命名和“未定义”警告;Blade 视图内的补全、悬停、签名帮助和跳转;`.env` 和 `lang/*.json` 中键的查找用法和重命名。
|
||||
|
||||
### Symfony
|
||||
|
||||
- **Twig 模板**(`.twig`)有语法高亮:HTML,以及标签、表达式和 `{# #}` 注释;块可以折叠。
|
||||
- **使用 Phoxite 时**:路由名、模板名、服务和参数、翻译键、Doctrine 字段的补全、跳转和重命名;在 Twig 模板中提供补全、悬停、跳转(到被继承或包含的模板、函数、过滤器、路由)、重命名、大纲、格式化和问题检查。
|
||||
|
||||
### WordPress、Drupal、Magento 和 Joomla
|
||||
|
||||
使用 Phoxite 时,在 PHP 中为平台的名字提供补全、跳转和查找用法,例如 WordPress 的钩子、短代码、选项和区块名,Drupal 的服务、路由和权限,Magento 的事件、配置路径、ACL 资源和布局句柄,Joomla 的语言键、布局和表单字段。
|
||||
|
||||
不使用 Phoxite 时,在 **附加存根** 中加入平台的 stub(例如 `wordpress`),在 **包含路径** 中加入平台代码目录。
|
||||
|
||||
### CodeIgniter、Yii、CakePHP 和 Laminas
|
||||
|
||||
使用 Phoxite 时,在 PHP 中为框架的名字(路由、视图或模板、配置键、翻译消息、服务和组件)提供补全、跳转和查找用法,并推断框架提供的服务、模型和视图变量的类型。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 使用 Intelephense 时不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。Phoxite 为 `.blade.php` 文件提供代码智能,但没有 Blade 语法高亮。
|
||||
- IDE 不会安装 phpactor。
|
||||
- 使用 Intelephense、PHPantom、Phpactor 或 DEVSENSE 时,Blade 视图和 Twig 模板只有语法高亮,没有针对模板的代码智能(Blade 视图被当作 PHP 读取);使用 Phoxite 时则有。
|
||||
- PHPUnit 不支持使用覆盖率运行。
|
||||
- 调试需要 PHP 已安装 Xdebug 扩展,IDE 不负责安装。
|
||||
@@ -0,0 +1,69 @@
|
||||
id = "blade"
|
||||
name = "Blade"
|
||||
# Laravel's views: `welcome.blade.php`. The compound extension wins over `php`.
|
||||
extensions = ["blade.php"]
|
||||
block-comment = ["{{--", "--}}"]
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
# The frontend's own mode (`src/editor/core/cm/blade.ts`): HTML, with directives,
|
||||
# echoes and the PHP inside them highlighted.
|
||||
ui-mode = "Blade"
|
||||
|
||||
# The PHP servers, in `php.toml`'s order, so a view is served by the server that
|
||||
# serves the project's PHP. Phoxite knows the file as a Blade view; the others
|
||||
# are told `php`, as they were before Blade was a language of its own.
|
||||
[[language-servers]]
|
||||
name = "intelephense"
|
||||
command = "intelephense"
|
||||
args = ["--stdio"]
|
||||
root-markers = ["composer.json", ".phpactor.json", "index.php"]
|
||||
install-hint = "npm i -g intelephense"
|
||||
resync-on-configuration = true
|
||||
language-id = "php"
|
||||
|
||||
[[language-servers]]
|
||||
name = "phpantom"
|
||||
ignored-progress-token-prefixes = ["find_references", "goto_implementation"]
|
||||
fallback = true
|
||||
command = "phpantom_lsp"
|
||||
args = []
|
||||
root-markers = ["composer.json", "index.php"]
|
||||
install-hint = "Install PHPantom in Settings › Languages & Frameworks › Language Servers"
|
||||
language-id = "php"
|
||||
|
||||
[[language-servers]]
|
||||
name = "phpactor"
|
||||
fallback = true
|
||||
command = "phpactor"
|
||||
args = ["language-server"]
|
||||
root-markers = ["composer.json", ".phpactor.json"]
|
||||
install-hint = "Install Phpactor in Settings › Languages & Frameworks › Language Servers (it runs on PHP)"
|
||||
language-id = "php"
|
||||
|
||||
# Completion, hover, signature help, navigation and problems inside the view.
|
||||
[[language-servers]]
|
||||
name = "phoxite"
|
||||
fallback = true
|
||||
command = "phoxite-lsp"
|
||||
args = []
|
||||
root-markers = ["composer.json", "artisan", "index.php"]
|
||||
replaces = ["laravel-lsp"]
|
||||
install-hint = "Install Phoxite in Settings › Languages & Frameworks › Language Servers"
|
||||
|
||||
[[language-servers]]
|
||||
name = "devsense-php-ls"
|
||||
fallback = true
|
||||
command = "devsense-php-ls"
|
||||
args = []
|
||||
root-markers = ["composer.json", "index.php"]
|
||||
replaces = ["laravel-lsp"]
|
||||
install-hint = "npm i -g devsense-php-ls"
|
||||
language-id = "php"
|
||||
|
||||
[[language-servers]]
|
||||
name = "laravel-lsp"
|
||||
command = "laravel-lsp"
|
||||
args = []
|
||||
root-markers = ["artisan"]
|
||||
require-root-marker = true
|
||||
install-hint = "composer global require laravel/lsp"
|
||||
language-id = "php"
|
||||
@@ -5,3 +5,13 @@ filenames = [".env", ".env.*", ".flaskenv"]
|
||||
line-comment = "#"
|
||||
indent = { tab-size = 2, insert-spaces = true }
|
||||
ui-mode = "Properties files"
|
||||
|
||||
# Phoxite, where it is the project's PHP server: Find Usages and Rename of a
|
||||
# key, with the `env('…')` calls that read it.
|
||||
[[language-servers]]
|
||||
name = "phoxite"
|
||||
command = "phoxite-lsp"
|
||||
args = []
|
||||
root-markers = ["composer.json", "artisan", "index.php"]
|
||||
joins = "php"
|
||||
install-hint = "Install Phoxite in Settings › Languages & Frameworks › Language Servers"
|
||||
@@ -69,3 +69,15 @@ root-markers = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome"]
|
||||
require-root-marker = true
|
||||
features = ["code-action", "diagnostics"]
|
||||
install-hint = "npm i -D @biomejs/biome"
|
||||
|
||||
# Phoxite, where it is the project's PHP server, on Laravel's translation files
|
||||
# (`lang/en.json`): Find Usages and Rename of a key, with the `__('…')` calls
|
||||
# that read it.
|
||||
[[language-servers]]
|
||||
name = "phoxite"
|
||||
command = "phoxite-lsp"
|
||||
args = []
|
||||
root-markers = ["composer.json", "artisan", "index.php"]
|
||||
joins = "php"
|
||||
files = ["**/lang/**/*.json"]
|
||||
install-hint = "Install Phoxite in Settings › Languages & Frameworks › Language Servers"
|
||||
@@ -45,7 +45,7 @@ args = []
|
||||
root-markers = ["composer.json", "artisan", "index.php"]
|
||||
# It answers the Laravel strings itself.
|
||||
replaces = ["laravel-lsp"]
|
||||
install-hint = "Install phoxite-lsp from https://github.com/samehelhawary/phoxite/releases and put it on PATH"
|
||||
install-hint = "Install Phoxite in Settings › Languages & Frameworks › Language Servers"
|
||||
|
||||
# Alternative whose engine ships as native builds for Windows, macOS and Linux;
|
||||
# only the npm launcher needs Node. Some features (refactorings, call and type
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
id = "twig"
|
||||
name = "Twig"
|
||||
# Also `page.html.twig`, `mail.txt.twig`: the last extension decides.
|
||||
extensions = ["twig"]
|
||||
block-comment = ["{#", "#}"]
|
||||
indent = { tab-size = 4, insert-spaces = true }
|
||||
# The frontend's own mode (`src/editor/core/cm/twig.ts`): HTML, with Twig's
|
||||
# tags, expressions and comments highlighted.
|
||||
ui-mode = "Twig"
|
||||
|
||||
# Phoxite, where it is the project's PHP server: completion, hover, navigation,
|
||||
# rename and problems of the template's names (functions, filters, routes, other
|
||||
# templates), the outline, formatting and semantic highlighting.
|
||||
[[language-servers]]
|
||||
name = "phoxite"
|
||||
command = "phoxite-lsp"
|
||||
args = []
|
||||
root-markers = ["composer.json", "artisan", "index.php"]
|
||||
joins = "php"
|
||||
install-hint = "Install Phoxite in Settings › Languages & Frameworks › Language Servers"
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
|
||||
import { classHighlighter, highlightTree } from "@lezer/highlight";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
import { commentLine } from "./comments";
|
||||
|
||||
async function tokens(source: string) {
|
||||
const desc = findLanguageDescription("Blade", "welcome.blade.php")!;
|
||||
const support = await loadSupport(desc);
|
||||
const state = EditorState.create({ doc: source, extensions: [support!] });
|
||||
ensureSyntaxTree(state, source.length, 1000);
|
||||
const result: { text: string; style: string }[] = [];
|
||||
highlightTree(syntaxTree(state), classHighlighter, (from, to, style) =>
|
||||
result.push({ text: source.slice(from, to), style }),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
const styleOf = (out: { text: string; style: string }[], text: string) => out.find((t) => t.text === text)?.style;
|
||||
|
||||
describe("Blade mode", () => {
|
||||
it("highlights HTML, echoes and the PHP inside them", async () => {
|
||||
const out = await tokens('<div class="x">{{ $user->name }} {!! format(1) !!}</div>\n{{-- note --}}');
|
||||
expect(styleOf(out, "div")).toBe("tok-typeName");
|
||||
expect(styleOf(out, "$user")).toContain("tok-variableName");
|
||||
expect(styleOf(out, "name")).toContain("tok-propertyName");
|
||||
expect(styleOf(out, "format")).toContain("tok-variableName");
|
||||
expect(styleOf(out, "1")).toBe("tok-number");
|
||||
expect(styleOf(out, "{{-- note --}}")).toBe("tok-comment");
|
||||
expect(out.filter((t) => ["{{", "}}", "{!!", "!!}"].includes(t.text))).toHaveLength(4);
|
||||
});
|
||||
|
||||
it("highlights known directives and their arguments", async () => {
|
||||
const out = await tokens("@if ($a === ')' && count($b))\n<p>[email protected] @click</p>\n@endif @php $x = 1; @endphp");
|
||||
expect(styleOf(out, "@if")).toBe("tok-keyword");
|
||||
expect(styleOf(out, "')'")).toBe("tok-string");
|
||||
expect(styleOf(out, "$b")).toContain("tok-variableName");
|
||||
expect(styleOf(out, "@endif")).toBe("tok-keyword");
|
||||
expect(styleOf(out, "@php")).toBe("tok-keyword");
|
||||
expect(styleOf(out, "$x")).toContain("tok-variableName");
|
||||
// E-mails and Alpine attributes are not directives.
|
||||
expect(out.some((t) => t.text.includes("@b") || t.text === "@click")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps state across lines", async () => {
|
||||
const out = await tokens("@include('a', [\n 'b' => $c,\n]) <p>\n{{-- x\n<p> --}}");
|
||||
expect(styleOf(out, "$c")).toContain("tok-variableName");
|
||||
expect(styleOf(out, "'b'")).toBe("tok-string");
|
||||
expect(out.filter((t) => t.text === "p")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Blade comments", () => {
|
||||
async function editor(doc: string, caret: number) {
|
||||
const support = await loadSupport(findLanguageDescription("Blade", "welcome.blade.php")!);
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc, selection: { anchor: caret }, extensions: [support!] }),
|
||||
parent: document.body,
|
||||
});
|
||||
ensureSyntaxTree(view.state, doc.length, 1000);
|
||||
return view;
|
||||
}
|
||||
|
||||
it("toggles the comment around a line with text", async () => {
|
||||
const view = await editor("<p>hi</p>", 2);
|
||||
commentLine(view);
|
||||
expect(view.state.doc.toString()).toBe("{{-- <p>hi</p> --}}");
|
||||
commentLine(view);
|
||||
expect(view.state.doc.toString()).toBe("<p>hi</p>");
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* Blade (Laravel views) editor mode: HTML outside, directives (`@if`,
|
||||
* `@include`) as keywords, and PHP inside `{{ }}`, `{!! !!}`, directive
|
||||
* arguments, `@php … @endphp` and `<?php ?>`. HTML is tokenized by the legacy
|
||||
* HTML mode on a sub-stream cut at the next Blade construct (as in `erb.ts`);
|
||||
* the PHP by a small expression tokenizer. Completion, hover and goto on the
|
||||
* PHP come from the PHP language server.
|
||||
*/
|
||||
import { LanguageSupport, StreamLanguage, StringStream, type StreamParser } from "@codemirror/language";
|
||||
import { tags } from "@lezer/highlight";
|
||||
|
||||
/** Blade's directives; other `@words` (an e-mail address, Alpine's `@click`) are HTML. */
|
||||
const DIRECTIVES = new Set(
|
||||
(
|
||||
"append auth aware break can canany cannot case checked choice class component componentFirst continue csrf dd " +
|
||||
"default disabled dump each else elseauth elsecan elsecanany elsecannot elseenv elseguest elseif empty endauth " +
|
||||
"endcan endcanany endcannot endcomponent endcomponentClass endempty endenv enderror endfor endforeach endforelse " +
|
||||
"endfragment endguest endif endisset endonce endPushOnce endPrependOnce endphp endprepend endproduction endpush " +
|
||||
"endpushIf endsection endsession endslot endswitch endunless endverbatim endwhile env error extends extendsFirst " +
|
||||
"for foreach forelse fragment guest hasSection if include includeFirst includeIf includeUnless includeWhen inject " +
|
||||
"isset js json lang livewire livewireScripts livewireStyles method once overwrite parent php prepend prependOnce " +
|
||||
"production props push pushIf pushOnce readonly required section sectionMissing selected session show slot stack " +
|
||||
"stop style switch unless use verbatim vite viteReactRefresh while yield"
|
||||
).split(" "),
|
||||
);
|
||||
|
||||
const PHP_KEYWORDS = new Set(
|
||||
(
|
||||
"abstract and array as break callable case catch class clone const continue declare default do echo else elseif " +
|
||||
"empty enum extends final finally fn for foreach function global goto if implements include instanceof insteadof " +
|
||||
"interface isset list match namespace new or print private protected public readonly require return static " +
|
||||
"switch throw trait try unset use var while xor yield"
|
||||
).split(" "),
|
||||
);
|
||||
const PHP_ATOMS = new Set(["true", "false", "null", "self", "parent"]);
|
||||
|
||||
type Mode = "html" | "comment" | "echo" | "raw" | "tag" | "block" | "args" | "verbatim";
|
||||
type State<H> = {
|
||||
html: H;
|
||||
mode: Mode;
|
||||
/** Open parentheses of directive arguments. */
|
||||
depth: number;
|
||||
/** Inside a PHP `/* … *\/` comment. */
|
||||
phpComment: boolean;
|
||||
/** The previous PHP token was `->`/`?->`/`::`: a member name follows. */
|
||||
member: boolean;
|
||||
};
|
||||
|
||||
/** Where each PHP region ends. */
|
||||
const CLOSE: Partial<Record<Mode, string>> = { echo: "}}", raw: "!!}", tag: "?>", block: "@endphp" };
|
||||
|
||||
function phpToken<H>(stream: StringStream, state: State<H>): string | null {
|
||||
if (state.phpComment) {
|
||||
const end = stream.string.indexOf("*/", stream.pos);
|
||||
if (end < 0) stream.skipToEnd();
|
||||
else {
|
||||
stream.pos = end + 2;
|
||||
state.phpComment = false;
|
||||
}
|
||||
return "comment";
|
||||
}
|
||||
if (stream.eatSpace()) return null;
|
||||
if (stream.match("/*")) {
|
||||
state.phpComment = true;
|
||||
return phpToken(stream, state) ?? "comment";
|
||||
}
|
||||
if (stream.match(/^(?:\/\/|#(?!\[)).*/)) return "comment";
|
||||
const member = state.member;
|
||||
state.member = false;
|
||||
if (stream.match(/^\$[A-Za-z_\x80-][\w\x80-]*/)) return "variableName";
|
||||
if (stream.match(/^'(?:[^'\\]|\\.)*'?/) || stream.match(/^"(?:[^"\\]|\\.)*"?/)) return "string";
|
||||
if (stream.match(/^(?:0x[0-9a-f_]+|\d[\d_]*(?:\.\d+)?(?:e[+-]?\d+)?)/i)) return "number";
|
||||
const word = stream.match(/^\\?[A-Za-z_\x80-][\w\x80-\\]*/);
|
||||
if (word) {
|
||||
const text = (typeof word === "object" ? word[0] : "").toLowerCase();
|
||||
if (member) return "propertyName";
|
||||
if (PHP_KEYWORDS.has(text)) return "keyword";
|
||||
if (PHP_ATOMS.has(text)) return "atom";
|
||||
return /^\s*\(/.test(stream.string.slice(stream.pos)) ? "functionName" : "typeName";
|
||||
}
|
||||
if (stream.match(/^(?:\?->|->|::)/)) {
|
||||
state.member = true;
|
||||
return "operator";
|
||||
}
|
||||
if (stream.match(/^[()[\]{},;]/)) return "punctuation";
|
||||
stream.next();
|
||||
return "operator";
|
||||
}
|
||||
|
||||
export function bladeParser<H>(html: StreamParser<H>): StreamParser<State<H>> {
|
||||
const copy = (state: H): H =>
|
||||
html.copyState
|
||||
? html.copyState(state)
|
||||
: (Object.fromEntries(
|
||||
Object.entries(state as object).map(([k, v]) => [k, Array.isArray(v) ? v.slice() : v]),
|
||||
) as H);
|
||||
|
||||
/** Runs `parse` on `stream` cut at `end`, then advances `stream` to where it stopped. */
|
||||
const within = (stream: StringStream, end: number, parse: (sub: StringStream) => string | null) => {
|
||||
const sub = new StringStream(stream.string.slice(0, end), 4, stream.indentUnit);
|
||||
sub.pos = stream.pos;
|
||||
sub.start = stream.start;
|
||||
const style = parse(sub);
|
||||
stream.pos = Math.max(sub.pos, stream.pos + (sub.pos === stream.pos ? 1 : 0));
|
||||
return style;
|
||||
};
|
||||
|
||||
/** The next offset at or after `from` where a Blade construct may start. */
|
||||
const nextSpecial = (line: string, from: number) => {
|
||||
const found = line.slice(from).search(/\{\{|\{!!|@|<\?/);
|
||||
return found < 0 ? line.length : from + found;
|
||||
};
|
||||
|
||||
const htmlToken = (stream: StringStream, state: State<H>): string | null => {
|
||||
const line = stream.string;
|
||||
const rest = line.slice(stream.pos);
|
||||
if (rest.startsWith("{{--")) {
|
||||
stream.pos += 4;
|
||||
state.mode = "comment";
|
||||
return commentToken(stream, state);
|
||||
}
|
||||
if (rest.startsWith("@{{")) {
|
||||
const close = line.indexOf("}}", stream.pos + 3);
|
||||
stream.pos = close < 0 ? line.length : close + 2;
|
||||
return null;
|
||||
}
|
||||
for (const [open, mode] of [
|
||||
["{!!", "raw"],
|
||||
["{{", "echo"],
|
||||
["<?php", "tag"],
|
||||
["<?=", "tag"],
|
||||
] as const) {
|
||||
if (rest.startsWith(open)) {
|
||||
stream.pos += open.length;
|
||||
state.mode = mode;
|
||||
return "bladeDelimiter";
|
||||
}
|
||||
}
|
||||
const directive = /^@(@?)(\w+)/.exec(rest);
|
||||
const wordBefore = stream.pos > 0 && /\w/.test(line[stream.pos - 1]!);
|
||||
if (directive && !wordBefore && !directive[1] && DIRECTIVES.has(directive[2]!)) {
|
||||
const name = directive[2]!;
|
||||
stream.pos += directive[0].length;
|
||||
const args = /^[ \t]*\(/.test(line.slice(stream.pos));
|
||||
if (name === "php" && !args) state.mode = "block";
|
||||
else if (name === "verbatim") state.mode = "verbatim";
|
||||
else if (args) {
|
||||
state.mode = "args";
|
||||
state.depth = 0;
|
||||
}
|
||||
return "bladeDirective";
|
||||
}
|
||||
if (directive?.[1]) {
|
||||
// `@@if`: written out.
|
||||
stream.pos += directive[0].length;
|
||||
return null;
|
||||
}
|
||||
const end = nextSpecial(line, stream.pos + 1);
|
||||
return within(stream, end, (sub) => html.token(sub, state.html));
|
||||
};
|
||||
|
||||
const commentToken = (stream: StringStream, state: State<H>) => {
|
||||
const close = stream.string.indexOf("--}}", stream.pos);
|
||||
if (close < 0) stream.skipToEnd();
|
||||
else {
|
||||
stream.pos = close + 4;
|
||||
state.mode = "html";
|
||||
}
|
||||
return "comment";
|
||||
};
|
||||
|
||||
return {
|
||||
name: "blade",
|
||||
languageData: { ...html.languageData, commentTokens: { block: { open: "{{--", close: "--}}" } } },
|
||||
tokenTable: {
|
||||
...html.tokenTable,
|
||||
bladeDelimiter: tags.special(tags.brace),
|
||||
bladeDirective: tags.controlKeyword,
|
||||
variableName: tags.variableName,
|
||||
propertyName: tags.propertyName,
|
||||
functionName: tags.function(tags.variableName),
|
||||
typeName: tags.typeName,
|
||||
punctuation: tags.punctuation,
|
||||
},
|
||||
startState: (indentUnit) => ({
|
||||
html: html.startState!(indentUnit),
|
||||
mode: "html",
|
||||
depth: 0,
|
||||
phpComment: false,
|
||||
member: false,
|
||||
}),
|
||||
copyState: (s) => ({ ...s, html: copy(s.html) }),
|
||||
blankLine: (s, unit) => (s.mode === "html" ? html.blankLine?.(s.html, unit) : undefined),
|
||||
indent: (s, text, cx) => (s.mode === "html" ? (html.indent?.(s.html, text, cx) ?? null) : null),
|
||||
token(stream, state) {
|
||||
const rest = stream.string.slice(stream.pos);
|
||||
switch (state.mode) {
|
||||
case "html":
|
||||
return htmlToken(stream, state);
|
||||
case "comment":
|
||||
return commentToken(stream, state);
|
||||
case "verbatim": {
|
||||
const close = stream.string.indexOf("@endverbatim", stream.pos);
|
||||
if (close === stream.pos) {
|
||||
stream.pos += "@endverbatim".length;
|
||||
state.mode = "html";
|
||||
return "bladeDirective";
|
||||
}
|
||||
return within(stream, close < 0 ? stream.string.length : close, (sub) => html.token(sub, state.html));
|
||||
}
|
||||
case "args": {
|
||||
if (!state.phpComment && rest.startsWith("(")) {
|
||||
stream.next();
|
||||
state.depth++;
|
||||
return "punctuation";
|
||||
}
|
||||
if (!state.phpComment && rest.startsWith(")")) {
|
||||
stream.next();
|
||||
if (--state.depth <= 0) state.mode = "html";
|
||||
return "punctuation";
|
||||
}
|
||||
// PHP tokens stop at parentheses, except inside strings and comments.
|
||||
return phpToken(stream, state);
|
||||
}
|
||||
default: {
|
||||
const close = CLOSE[state.mode]!;
|
||||
if (rest.startsWith(close)) {
|
||||
stream.pos += close.length;
|
||||
const block = state.mode === "block";
|
||||
state.mode = "html";
|
||||
state.phpComment = false;
|
||||
return block ? "bladeDirective" : "bladeDelimiter";
|
||||
}
|
||||
const at = rest.indexOf(close);
|
||||
return within(stream, at < 0 ? stream.string.length : stream.pos + at, (sub) => phpToken(sub, state));
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function blade(): Promise<LanguageSupport> {
|
||||
const { html } = await import("@codemirror/legacy-modes/mode/xml");
|
||||
return new LanguageSupport(StreamLanguage.define(bladeParser(html)));
|
||||
}
|
||||
@@ -257,6 +257,18 @@ const OWN_MODES = [
|
||||
extensions: ["erb", "rhtml"],
|
||||
load: () => import("./erb").then((m) => m.erb()),
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: "Blade",
|
||||
alias: ["blade"],
|
||||
extensions: ["blade.php"],
|
||||
load: () => import("./blade").then((m) => m.blade()),
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: "Twig",
|
||||
alias: ["twig"],
|
||||
extensions: ["twig"],
|
||||
load: () => import("./twig").then((m) => m.twig()),
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: "FreeMarker",
|
||||
alias: ["freemarker", "ftl"],
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { foldable, indentUnit, type LanguageSupport } from "@codemirror/language";
|
||||
import { classHighlighter, highlightTree } from "@lezer/highlight";
|
||||
import { completedSyntaxState, completedSyntaxTree } from "@/test/syntax";
|
||||
import { commentLine } from "./comments";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
import { twig } from "./twig";
|
||||
|
||||
const support = twig();
|
||||
|
||||
function state(doc: string, at = 0, mode: LanguageSupport = support): EditorState {
|
||||
return completedSyntaxState(
|
||||
EditorState.create({ doc, selection: EditorSelection.cursor(at), extensions: [mode, indentUnit.of(" ")] }),
|
||||
);
|
||||
}
|
||||
|
||||
/** `text:class` of the styled tokens of `doc`, markup included. */
|
||||
function tokens(doc: string): string[] {
|
||||
const out: string[] = [];
|
||||
highlightTree(completedSyntaxTree(state(doc)), classHighlighter, (from, to, cls) =>
|
||||
out.push(`${doc.slice(from, to)}:${cls}`),
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Types `ch` at `|` of `doc` through the real input handlers; the result with `|` at the caret. */
|
||||
function type(doc: string, ch: string): string {
|
||||
const at = doc.indexOf("|");
|
||||
const v = new EditorView({ state: state(doc.replace("|", ""), at) });
|
||||
const insert = () => v.state.update(v.state.replaceSelection(ch), { userEvent: "input.type" });
|
||||
if (!v.state.facet(EditorView.inputHandler).some((h) => h(v, at, at, ch, insert))) v.dispatch(insert());
|
||||
const head = v.state.selection.main.head;
|
||||
const out = v.state.doc.toString();
|
||||
v.destroy();
|
||||
return out.slice(0, head) + "|" + out.slice(head);
|
||||
}
|
||||
|
||||
describe("Twig templates", () => {
|
||||
it("are the mode of the backend's Twig language, whatever the template renders", async () => {
|
||||
for (const path of ["/p/templates/base.html.twig", "/p/templates/mail/order.txt.twig", "/p/page.twig"])
|
||||
expect(findLanguageDescription("Twig", path)?.name, path).toBe("Twig");
|
||||
expect(findLanguageDescription(null, "/p/templates/base.html.twig")?.name).toBe("Twig");
|
||||
expect((await loadSupport(findLanguageDescription("Twig", "/p/a.html.twig")!))?.language.name).toBe("jinja");
|
||||
});
|
||||
|
||||
it("highlights the template layer and the markup around it", () => {
|
||||
const out = tokens(
|
||||
"<a href=\"{{ path('order_show', {id: order.id}) }}\">{% if order.paid %}{{ order.total|number_format(2) }}{% endif %}</a>{# note #}",
|
||||
);
|
||||
expect(out).toEqual(
|
||||
expect.arrayContaining([
|
||||
"a:tok-typeName",
|
||||
"href:tok-propertyName",
|
||||
"'order_show':tok-string",
|
||||
"if:tok-keyword",
|
||||
"order:tok-variableName",
|
||||
"paid:tok-propertyName",
|
||||
"number_format:tok-variableName2",
|
||||
"2:tok-number",
|
||||
" note :tok-comment",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps highlighting after the syntax Twig has and Jinja lacks", () => {
|
||||
const doc =
|
||||
'{% set label = user.name ?? "guest" ~ "!" %}\n' +
|
||||
'{{ "Hello #{label}" }}\n' +
|
||||
"{{ items|map(i => i.price)|join(', ') }}\n" +
|
||||
"{% apply upper %}<b>x</b>{% endapply %}\n" +
|
||||
"<p>{{ total }}</p>";
|
||||
const out = tokens(doc);
|
||||
expect(out).toEqual(
|
||||
expect.arrayContaining(["set:tok-keyword", "p:tok-typeName", "total:tok-variableName", "b:tok-typeName"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("makes `{% %}` of `%` between braces and closes HTML tags", () => {
|
||||
expect(type("<p>{|}</p>", "%")).toBe("<p>{%|%}</p>");
|
||||
expect(type("<div|", ">")).toBe("<div>|</div>");
|
||||
});
|
||||
|
||||
it("folds a block's content", () => {
|
||||
const doc = "{% block body %}\n <p>x</p>\n{% endblock %}";
|
||||
expect(foldable(state(doc), 0, doc.indexOf("\n"))).toEqual({
|
||||
from: doc.indexOf("%}") + 2,
|
||||
to: doc.indexOf("{% endblock"),
|
||||
});
|
||||
});
|
||||
|
||||
it("comments lines out with {# #}", () => {
|
||||
const v = new EditorView({ state: state("<p>a</p>") });
|
||||
v.dispatch({ selection: EditorSelection.range(0, v.state.doc.length) });
|
||||
commentLine(v);
|
||||
expect(v.state.doc.toString()).toBe("{# <p>a</p> #}");
|
||||
v.destroy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Twig templates (Symfony, Drupal, Craft): HTML with Twig's tags, expressions
|
||||
* and comments. Twig took its delimiters and most of its syntax from Jinja, so
|
||||
* the template layer is `@codemirror/lang-jinja`'s grammar, with `{# #}`
|
||||
* comments in the markup too. Without that package's completion: its tags and
|
||||
* filters are Jinja's, and the PHP language server completes Twig's.
|
||||
*/
|
||||
import { LanguageSupport } from "@codemirror/language";
|
||||
import { closePercentBrace, jinjaLanguage } from "@codemirror/lang-jinja";
|
||||
import { html, htmlLanguage } from "@codemirror/lang-html";
|
||||
|
||||
const TWIG_COMMENT = { block: { open: "{#", close: "#}" } };
|
||||
|
||||
export function twig(): LanguageSupport {
|
||||
return new LanguageSupport(jinjaLanguage, [
|
||||
html().support,
|
||||
htmlLanguage.data.of({ commentTokens: TWIG_COMMENT, closeBrackets: { brackets: ["{"] } }),
|
||||
jinjaLanguage.data.of({ commentTokens: TWIG_COMMENT }),
|
||||
closePercentBrace,
|
||||
]);
|
||||
}
|
||||
@@ -30,12 +30,15 @@ const usePopup = create<{ open: boolean; status: Status | null }>(() => ({ open:
|
||||
const close = () => usePopup.setState({ open: false });
|
||||
const reset = () => usePopup.setState({ open: false, status: null });
|
||||
|
||||
/** The languages the PHP version applies to: a Blade view holds PHP. */
|
||||
const isPhpFile = (language: unknown) => language === "php" || language === "blade";
|
||||
|
||||
/** Whether the widget is on screen, read straight from the stores (the action runs outside a render). */
|
||||
function popupShown(): boolean {
|
||||
const root = useProject.getState().project?.root;
|
||||
const status = usePopup.getState().status;
|
||||
const context = getContext();
|
||||
return !!root && status?.root === root && status.path === context.editorPath && context.editorLangId === "php";
|
||||
return !!root && status?.root === root && status.path === context.editorPath && isPhpFile(context.editorLangId);
|
||||
}
|
||||
|
||||
/** `8.1.0` as `8.1`, the way the levels are listed. */
|
||||
@@ -59,7 +62,7 @@ function PhpStatus() {
|
||||
const linked = useProject((s) => s.project?.workspace?.projects);
|
||||
const configured = useProject((s) => s.settings?.languages?.php?.languageLevel ?? "");
|
||||
const path = useContextKeys((s) =>
|
||||
s.editorLangId === "php" && typeof s.editorPath === "string" ? s.editorPath : null,
|
||||
isPhpFile(s.editorLangId) && typeof s.editorPath === "string" ? s.editorPath : null,
|
||||
);
|
||||
const status = usePopup((s) => s.status);
|
||||
const open = usePopup((s) => s.open);
|
||||
|
||||
@@ -196,6 +196,7 @@ describe("fileIconName", () => {
|
||||
["page.html.j2", "file-html"],
|
||||
["nginx.conf.j2", "file-config"],
|
||||
["values.yaml.jinja2", "file-yaml"],
|
||||
["page.html.twig", "file-html"],
|
||||
["package.json", "file-npm"],
|
||||
["package-lock.json", "file-lock"],
|
||||
["yarn.lock", "file-lock"],
|
||||
|
||||
@@ -1200,7 +1200,7 @@ const EXT_ICONS = table({
|
||||
"file-text": "txt text",
|
||||
"file-log": "log",
|
||||
"file-csv": "csv tsv",
|
||||
"file-html": "html htm shtml html.tmpl djhtml jinja jinja2 j2",
|
||||
"file-html": "html htm shtml html.tmpl djhtml jinja jinja2 j2 twig",
|
||||
"file-xhtml": "xhtml",
|
||||
"file-css": "css pcss postcss",
|
||||
"file-less": "less",
|
||||
|
||||
Reference in new issue
Заблокувати користувача