use core::ops::Range;
use crate::synth::{self, SynthSpec};
use crate::{parse_with, parse_with_options, CompileOptions};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum ItemKind {
Command,
Tone,
Envelope,
Vibrato,
Detune,
Arp,
Duty,
Wave,
Off,
Macro,
Library,
Shot,
Mark,
Directive,
File,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Item {
pub insert: String,
pub label: String,
pub kind: ItemKind,
pub detail: String,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "String::is_empty"))]
pub detail_key: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Completions {
pub replace: Range<usize>,
pub items: Vec<Item>,
}
impl Completions {
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn apply(&self, src: &str, index: usize) -> Option<(String, usize)> {
let item = self.items.get(index)?;
let start = byte_of(src, self.replace.start)?;
let end = byte_of(src, self.replace.end)?;
let mut out = String::with_capacity(src.len() + item.insert.len());
out.push_str(&src[..start]);
out.push_str(&item.insert);
out.push_str(&src[end..]);
Some((out, self.replace.start + item.insert.chars().count()))
}
}
pub const COMMANDS: &[&str] = &["env", "vib", "detune", "arp", "duty", "wave"];
const DEF_COMMANDS: &[&str] = &["env", "vib", "detune", "arp", "duty", "wave", "shot"];
const TRACK_COMMANDS: &[&str] = &[
"env", "vib", "detune", "arp", "duty", "wave", "mark", "bar", "swing",
];
const BASIC_COMMANDS: &[(&str, &str)] = &[
("l", "音長の既定"),
("o", "オクターブ"),
("t", "テンポ"),
("v", "音量"),
("q", "ゲート"),
("k", "移調"),
];
const DIRECTIVES: &[(&str, &str)] = &[
("#synth", "音源の選択"),
("#include", "ファイルの読み込み"),
("#sample", "録音の読み込み"),
("#title", "曲名"),
("#composer", "作曲者"),
("#frame", "フレームの長さ"),
("#meter", "拍子"),
("#swing", "スウィング"),
("#dialect", "方言"),
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CompleteOptions {
pub explicit: bool,
}
pub fn completions(src: &str, cursor: usize, opts: &CompileOptions<'_>) -> Completions {
completions_with(src, cursor, opts, &CompleteOptions::default())
}
pub fn completions_with(
src: &str,
cursor: usize,
opts: &CompileOptions<'_>,
how: &CompleteOptions,
) -> Completions {
let chars: Vec<char> = src.chars().collect();
let cursor = cursor.min(chars.len());
let line_start = chars[..cursor]
.iter()
.rposition(|&c| c == '\n')
.map_or(0, |i| i + 1);
let line: &[char] = &chars[line_start..cursor];
if let Some(c) = include_completions(line, line_start, cursor, opts) {
return c;
}
if line.contains(&';') {
return Completions::default();
}
if line.first() == Some(&'#') {
if how.explicit && !line.contains(&' ') {
return directive_items(line, line_start, cursor);
}
return Completions::default();
}
let first = line.first().copied();
let track_line = first.is_some_and(|c| c.is_ascii_uppercase());
let def_line = matches!(first, Some('@') | Some('$'));
if !track_line && !def_line && !line.is_empty() {
return Completions::default();
}
let word_start = line
.iter()
.rposition(|c| !is_name_char(*c))
.map_or(0, |i| i + 1);
let word: String = line[word_start..].iter().collect();
let before = word_start.checked_sub(1).map(|i| line[i]);
let abs = |i: usize| line_start + i;
let explicit_here = |track_line: bool| -> Completions {
if how.explicit {
explicit_items(line, line_start, cursor, track_line, &word, word_start)
} else {
Completions::default()
}
};
match before {
Some('@') => {
let at = word_start - 1;
let mut items = Vec::new();
let at_line_head = at == 0;
if track_line && word.chars().all(|c| c.is_ascii_digit()) {
let spec = synth_of(src, opts);
for t in spec.tones {
let label = format!("@{}", t.id);
if label[1..].starts_with(&word) {
items.push(Item {
insert: label.clone(),
label,
kind: ItemKind::Tone,
detail: spec
.tone_description(t.id, crate::text::DEFAULT_LANG)
.to_string(),
detail_key: synth::text_key::tone(spec.name, t.id),
});
}
}
}
if track_line || at_line_head {
let commands = if at_line_head {
DEF_COMMANDS
} else {
TRACK_COMMANDS
};
for c in commands {
if c.starts_with(&word) {
items.push(Item {
insert: format!("@{c} "),
label: format!("@{c}"),
kind: ItemKind::Command,
detail: String::new(),
detail_key: String::new(),
});
}
}
}
Completions {
replace: abs(at)..cursor,
items,
}
}
Some('$') if word_start - 1 > 0 => {
let (ast, _) = parse_with_options(src, opts);
let items = ast
.macros
.iter()
.filter(|m| m.name.starts_with(&word))
.map(|m| {
let library = (m.span.source as usize)
.checked_sub(1)
.and_then(|i| ast.sources.get(i))
.and_then(|path| library_spec(path, opts));
let (detail, detail_key) = match library {
Some(spec) => (
spec.library_description(&m.name, crate::text::DEFAULT_LANG)
.to_string(),
synth::text_key::library(spec.name, &m.name),
),
None => (String::new(), String::new()),
};
Item {
insert: format!("${}", m.name),
label: format!("${}", m.name),
kind: ItemKind::Macro,
detail,
detail_key,
}
})
.collect();
Completions {
replace: abs(word_start - 1)..cursor,
items,
}
}
Some('!') if track_line => {
let (ast, _) = parse_with_options(src, opts);
let items = ast
.shots
.iter()
.filter(|d| d.name.starts_with(&word))
.map(|d| named(&d.name, ItemKind::Shot))
.collect();
Completions {
replace: abs(word_start)..cursor,
items,
}
}
Some(' ') | Some('\t') if track_line => {
let gap_start = line[..word_start]
.iter()
.rposition(|c| *c != ' ' && *c != '\t')
.map_or(0, |i| i + 1);
let prev_end = gap_start;
let prev_start = line[..prev_end]
.iter()
.rposition(|c| !c.is_ascii_lowercase())
.map_or(0, |i| i + 1);
let prev: String = line[prev_start..prev_end].iter().collect();
let has_at = prev_start > 0 && line[prev_start - 1] == '@';
let kind = match (has_at, prev.as_str()) {
(true, "env") => Some(ItemKind::Envelope),
(true, "vib") => Some(ItemKind::Vibrato),
(true, "detune") => Some(ItemKind::Detune),
(true, "arp") => Some(ItemKind::Arp),
(true, "duty") => Some(ItemKind::Duty),
(true, "wave") => Some(ItemKind::Wave),
(false, p) if is_short_form(p, "mp") => Some(ItemKind::Vibrato),
(false, p) if is_short_form(p, "ep") => Some(ItemKind::Detune),
(false, p) if is_short_form(p, "en") => Some(ItemKind::Arp),
(true, "mark") => Some(ItemKind::Mark),
_ => None,
};
let Some(kind) = kind else {
return explicit_here(track_line);
};
if kind == ItemKind::Mark {
let others: String = chars[..abs(word_start)]
.iter()
.chain(chars[cursor..].iter())
.collect();
let items = mark_names(&others)
.into_iter()
.filter(|n| n.starts_with(&word))
.map(|n| named(&n, ItemKind::Mark))
.collect();
return Completions {
replace: abs(word_start)..cursor,
items,
};
}
let (ast, _) = parse_with(src, &opts.dialect);
let names: Vec<&str> = match kind {
ItemKind::Envelope => ast.envelopes.iter().map(|d| d.name.as_str()).collect(),
ItemKind::Vibrato => ast.vibratos.iter().map(|d| d.name.as_str()).collect(),
ItemKind::Arp => ast.arps.iter().map(|d| d.name.as_str()).collect(),
ItemKind::Duty => ast.duties.iter().map(|d| d.name.as_str()).collect(),
ItemKind::Wave => ast.waves.iter().map(|d| d.name.as_str()).collect(),
_ => ast.detunes.iter().map(|d| d.name.as_str()).collect(),
};
let mut items: Vec<Item> = names
.into_iter()
.filter(|n| n.starts_with(&word))
.map(|n| Item {
insert: n.to_string(),
label: n.to_string(),
kind,
detail: String::new(),
detail_key: String::new(),
})
.collect();
if has_at && kind != ItemKind::Envelope && "off".starts_with(&word) {
items.push(Item {
insert: "off".into(),
label: "off".into(),
kind: ItemKind::Off,
detail: String::new(),
detail_key: String::new(),
});
}
Completions {
replace: abs(word_start)..cursor,
items,
}
}
_ => explicit_here(track_line),
}
}
fn named(name: &str, kind: ItemKind) -> Item {
Item {
insert: name.to_string(),
label: name.to_string(),
kind,
detail: String::new(),
detail_key: String::new(),
}
}
fn mark_names(src: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for line in src.lines() {
let line = line.split(';').next().unwrap_or("");
let mut rest = line;
while let Some(i) = rest.find("@mark") {
rest = &rest[i + 5..];
let name: String = rest
.trim_start_matches([' ', '\t'])
.chars()
.take_while(|c| is_name_char(*c))
.collect();
if !name.is_empty() && !out.contains(&name) {
out.push(name);
}
}
}
out
}
fn explicit_items(
line: &[char],
line_start: usize,
cursor: usize,
track_line: bool,
word: &str,
word_start: usize,
) -> Completions {
let replace = line_start + word_start..cursor;
if line.is_empty() {
let mut c = directive_items(&[], line_start, cursor);
for name in DEF_COMMANDS {
c.items
.push(command_item(&format!("@{name} "), &format!("@{name}")));
}
return c;
}
if !track_line {
return Completions::default();
}
let mut items = Vec::new();
for (c, detail) in BASIC_COMMANDS {
if c.starts_with(word) {
items.push(Item {
insert: (*c).to_string(),
label: (*c).to_string(),
kind: ItemKind::Command,
detail: (*detail).to_string(),
detail_key: String::new(),
});
}
}
if word.is_empty() {
for name in TRACK_COMMANDS {
items.push(command_item(&format!("@{name} "), &format!("@{name}")));
}
}
Completions { replace, items }
}
fn command_item(insert: &str, label: &str) -> Item {
Item {
insert: insert.to_string(),
label: label.to_string(),
kind: ItemKind::Command,
detail: String::new(),
detail_key: String::new(),
}
}
fn directive_items(line: &[char], line_start: usize, cursor: usize) -> Completions {
let typed: String = line.iter().collect();
let items = DIRECTIVES
.iter()
.filter(|(d, _)| d.starts_with(&typed))
.map(|(d, detail)| Item {
insert: format!("{d} "),
label: (*d).to_string(),
kind: ItemKind::Directive,
detail: (*detail).to_string(),
detail_key: String::new(),
})
.collect();
Completions {
replace: line_start..cursor,
items,
}
}
fn include_completions(
line: &[char],
line_start: usize,
cursor: usize,
opts: &CompileOptions<'_>,
) -> Option<Completions> {
let text: String = line.iter().collect();
let rest = text.get(..8)?;
if !rest.eq_ignore_ascii_case("#include") || !text[8..].starts_with([' ', '\t', '"']) {
return None;
}
let after = text[8..].trim_start();
let typed = after.strip_prefix('"')?;
if typed.contains('"') || typed.contains(';') {
return Some(Completions::default());
}
let mut items = Vec::new();
for spec in opts.synths {
for f in spec.tone_files {
let path = format!("@{}/{}", spec.library_prefix(), f.name);
if !path.starts_with(typed) {
continue;
}
let names: Vec<&str> = f.tones().map(|(n, _)| n).collect();
items.push(Item {
insert: path.clone(),
label: path,
kind: ItemKind::Library,
detail: names.join(", "),
detail_key: String::new(),
});
}
}
if let Some(inc) = opts.include {
for (path, names) in inc.libraries() {
if path.starts_with(typed) && !items.iter().any(|i| i.insert == path) {
items.push(Item {
insert: path.clone(),
label: path,
kind: ItemKind::Library,
detail: names.join(", "),
detail_key: String::new(),
});
}
}
}
if !typed.starts_with('@') {
if let Some(inc) = opts.include {
let (dir, prefix) = match typed.rfind('/') {
Some(i) => (&typed[..=i], &typed[i + 1..]),
None => ("", typed),
};
for name in inc.list(dir) {
if name.starts_with(prefix) {
let path = format!("{dir}{name}");
items.push(Item {
insert: path.clone(),
label: path,
kind: ItemKind::File,
detail: String::new(),
detail_key: String::new(),
});
}
}
}
}
let typed_len = typed.chars().count();
Some(Completions {
replace: line_start + line.len() - typed_len..cursor,
items,
})
}
fn library_spec<'a>(path: &str, opts: &CompileOptions<'a>) -> Option<&'a SynthSpec> {
let (name, _) = path.strip_prefix('@')?.split_once('/')?;
synth::find(opts.synths, name)
}
fn is_name_char(c: char) -> bool {
c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'
}
fn is_short_form(p: &str, short: &str) -> bool {
p.strip_suffix(short)
.is_some_and(|head| head.chars().all(|c| "abcdefgr".contains(c)))
}
fn synth_of<'a>(src: &str, opts: &CompileOptions<'a>) -> &'a SynthSpec {
let (ast, _) = parse_with(src, &opts.dialect);
ast.synth
.as_ref()
.and_then(|c| synth::find(opts.synths, &c.name))
.unwrap_or(&synth::BASIC)
}
fn byte_of(s: &str, ch: usize) -> Option<usize> {
if ch == s.chars().count() {
return Some(s.len());
}
s.char_indices().nth(ch).map(|(b, _)| b)
}