Skip to main content

iced_code_editor/
i18n.rs

1//! Internationalization support for the code editor.
2//!
3//! This module provides translation support for UI text in the search dialog.
4//!
5//! # Using `Translations`
6//!
7//! The translations are available in YAML files in the `locales` directory,
8//! loaded through the `rust-i18n` crate. Application code does not call
9//! `rust-i18n`'s `t!` macro directly — it is not part of this crate's public
10//! API. Instead, look up translated strings through [`Translations`]:
11//!
12//! ```
13//! use iced_code_editor::{Language, Translations};
14//!
15//! let translations = Translations::new(Language::English);
16//! assert_eq!(translations.search_placeholder(), "Search...");
17//! ```
18
19/// Supported languages for the code editor UI.
20///
21/// # Examples
22///
23/// ```
24/// use iced_code_editor::Language;
25///
26/// let lang = Language::English;
27/// assert_eq!(lang, Language::default());
28/// ```
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30pub enum Language {
31    /// English language
32    #[default]
33    English,
34    /// French language
35    French,
36    /// Spanish language
37    Spanish,
38    /// German language
39    German,
40    /// Italian language
41    Italian,
42    /// Portuguese (Brazilian) language
43    PortugueseBR,
44    /// Portuguese (European) language
45    PortuguesePT,
46    /// Simplified Chinese language
47    ChineseSimplified,
48}
49
50impl Language {
51    /// Returns the locale code for this language.
52    ///
53    /// # Examples
54    ///
55    /// ```
56    /// use iced_code_editor::Language;
57    ///
58    /// assert_eq!(Language::English.to_locale(), "en");
59    /// assert_eq!(Language::French.to_locale(), "fr");
60    /// assert_eq!(Language::Spanish.to_locale(), "es");
61    /// assert_eq!(Language::German.to_locale(), "de");
62    /// assert_eq!(Language::Italian.to_locale(), "it");
63    /// assert_eq!(Language::PortugueseBR.to_locale(), "pt-BR");
64    /// assert_eq!(Language::PortuguesePT.to_locale(), "pt-PT");
65    /// ```
66    #[must_use]
67    pub const fn to_locale(self) -> &'static str {
68        match self {
69            Self::English => "en",
70            Self::French => "fr",
71            Self::Spanish => "es",
72            Self::German => "de",
73            Self::Italian => "it",
74            Self::PortugueseBR => "pt-BR",
75            Self::PortuguesePT => "pt-PT",
76            Self::ChineseSimplified => "zh-CN",
77        }
78    }
79}
80
81/// Provides translated text strings for UI elements.
82///
83/// This struct contains all UI text translations used in the search dialog,
84/// including placeholders, tooltips, and labels.
85///
86/// # Examples
87///
88/// ```
89/// use iced_code_editor::{Language, Translations};
90///
91/// let translations = Translations::new(Language::French);
92/// assert_eq!(translations.search_placeholder(), "Rechercher...");
93/// ```
94#[derive(Debug, Clone, Copy, Default)]
95pub struct Translations {
96    language: Language,
97}
98
99impl Translations {
100    /// Creates a new `Translations` instance with the specified language.
101    ///
102    /// This sets the global rust-i18n locale to the specified language.
103    ///
104    /// # Examples
105    ///
106    /// ```
107    /// use iced_code_editor::{Language, Translations};
108    ///
109    /// let translations = Translations::new(Language::Spanish);
110    /// assert_eq!(translations.language(), Language::Spanish);
111    /// ```
112    #[must_use]
113    pub fn new(language: Language) -> Self {
114        rust_i18n::set_locale(language.to_locale());
115        Self { language }
116    }
117
118    /// Returns the current language.
119    ///
120    /// # Examples
121    ///
122    /// ```
123    /// use iced_code_editor::{Language, Translations};
124    ///
125    /// let translations = Translations::new(Language::French);
126    /// assert_eq!(translations.language(), Language::French);
127    /// ```
128    #[must_use]
129    pub const fn language(&self) -> Language {
130        self.language
131    }
132
133    /// Sets the language for translations.
134    ///
135    /// This updates the global rust-i18n locale.
136    ///
137    /// # Examples
138    ///
139    /// ```
140    /// use iced_code_editor::{Language, Translations};
141    ///
142    /// let mut translations = Translations::new(Language::English);
143    /// translations.set_language(Language::Spanish);
144    /// assert_eq!(translations.language(), Language::Spanish);
145    /// ```
146    pub fn set_language(&mut self, language: Language) {
147        self.language = language;
148        rust_i18n::set_locale(language.to_locale());
149    }
150
151    /// Returns the placeholder text for the search input field.
152    ///
153    /// # Examples
154    ///
155    /// ```
156    /// use iced_code_editor::{Language, Translations};
157    ///
158    /// let en = Translations::new(Language::English);
159    /// assert_eq!(en.search_placeholder(), "Search...");
160    ///
161    /// let fr = Translations::new(Language::French);
162    /// assert_eq!(fr.search_placeholder(), "Rechercher...");
163    /// ```
164    #[must_use]
165    pub fn search_placeholder(&self) -> String {
166        rust_i18n::t!("search.placeholder", locale = self.language.to_locale()).into_owned()
167    }
168
169    /// Returns the placeholder text for the replace input field.
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// use iced_code_editor::{Language, Translations};
175    ///
176    /// let es = Translations::new(Language::Spanish);
177    /// assert_eq!(es.replace_placeholder(), "Reemplazar...");
178    /// ```
179    #[must_use]
180    pub fn replace_placeholder(&self) -> String {
181        rust_i18n::t!("replace.placeholder", locale = self.language.to_locale()).into_owned()
182    }
183
184    /// Returns the label text for the case sensitive checkbox.
185    ///
186    /// # Examples
187    ///
188    /// ```
189    /// use iced_code_editor::{Language, Translations};
190    ///
191    /// let fr = Translations::new(Language::French);
192    /// assert_eq!(fr.case_sensitive_label(), "Sensible à la casse");
193    /// ```
194    #[must_use]
195    pub fn case_sensitive_label(&self) -> String {
196        rust_i18n::t!(
197            "settings.case_sensitive_label",
198            locale = self.language.to_locale()
199        )
200        .into_owned()
201    }
202
203    /// Returns the tooltip text for the previous match button.
204    ///
205    /// # Examples
206    ///
207    /// ```
208    /// use iced_code_editor::{Language, Translations};
209    ///
210    /// let en = Translations::new(Language::English);
211    /// assert_eq!(en.previous_match_tooltip(), "Previous match (Shift+F3)");
212    /// ```
213    #[must_use]
214    pub fn previous_match_tooltip(&self) -> String {
215        rust_i18n::t!(
216            "search.previous_match_tooltip",
217            locale = self.language.to_locale()
218        )
219        .into_owned()
220    }
221
222    /// Returns the tooltip text for the next match button.
223    ///
224    /// # Examples
225    ///
226    /// ```
227    /// use iced_code_editor::{Language, Translations};
228    ///
229    /// let es = Translations::new(Language::Spanish);
230    /// assert_eq!(es.next_match_tooltip(), "Siguiente coincidencia (F3 / Enter)");
231    /// ```
232    #[must_use]
233    pub fn next_match_tooltip(&self) -> String {
234        rust_i18n::t!(
235            "search.next_match_tooltip",
236            locale = self.language.to_locale()
237        )
238        .into_owned()
239    }
240
241    /// Returns the tooltip text for the close search dialog button.
242    ///
243    /// # Examples
244    ///
245    /// ```
246    /// use iced_code_editor::{Language, Translations};
247    ///
248    /// let fr = Translations::new(Language::French);
249    /// assert_eq!(fr.close_search_tooltip(), "Fermer la recherche (Échap)");
250    /// ```
251    #[must_use]
252    pub fn close_search_tooltip(&self) -> String {
253        rust_i18n::t!("search.close_tooltip", locale = self.language.to_locale()).into_owned()
254    }
255
256    /// Returns the tooltip text for the replace current match button.
257    ///
258    /// # Examples
259    ///
260    /// ```
261    /// use iced_code_editor::{Language, Translations};
262    ///
263    /// let en = Translations::new(Language::English);
264    /// assert_eq!(en.replace_current_tooltip(), "Replace current match");
265    /// ```
266    #[must_use]
267    pub fn replace_current_tooltip(&self) -> String {
268        rust_i18n::t!(
269            "replace.current_tooltip",
270            locale = self.language.to_locale()
271        )
272        .into_owned()
273    }
274
275    /// Returns the tooltip text for the replace all matches button.
276    ///
277    /// # Examples
278    ///
279    /// ```
280    /// use iced_code_editor::{Language, Translations};
281    ///
282    /// let es = Translations::new(Language::Spanish);
283    /// assert_eq!(es.replace_all_tooltip(), "Reemplazar todo");
284    /// ```
285    #[must_use]
286    pub fn replace_all_tooltip(&self) -> String {
287        rust_i18n::t!("replace.all_tooltip", locale = self.language.to_locale()).into_owned()
288    }
289
290    /// Returns the context-menu label for undo.
291    ///
292    /// # Examples
293    ///
294    /// ```
295    /// use iced_code_editor::{Language, Translations};
296    ///
297    /// let en = Translations::new(Language::English);
298    /// assert_eq!(en.context_menu_undo(), "Undo");
299    ///
300    /// let fr = Translations::new(Language::French);
301    /// assert_eq!(fr.context_menu_undo(), "Annuler");
302    /// ```
303    #[must_use]
304    pub fn context_menu_undo(&self) -> String {
305        rust_i18n::t!("context_menu.undo", locale = self.language.to_locale()).into_owned()
306    }
307
308    /// Returns the context-menu label for redo.
309    ///
310    /// # Examples
311    ///
312    /// ```
313    /// use iced_code_editor::{Language, Translations};
314    ///
315    /// let en = Translations::new(Language::English);
316    /// assert_eq!(en.context_menu_redo(), "Redo");
317    ///
318    /// let fr = Translations::new(Language::French);
319    /// assert_eq!(fr.context_menu_redo(), "Rétablir");
320    /// ```
321    #[must_use]
322    pub fn context_menu_redo(&self) -> String {
323        rust_i18n::t!("context_menu.redo", locale = self.language.to_locale()).into_owned()
324    }
325
326    /// Returns the context-menu label for cut.
327    ///
328    /// # Examples
329    ///
330    /// ```
331    /// use iced_code_editor::{Language, Translations};
332    ///
333    /// let en = Translations::new(Language::English);
334    /// assert_eq!(en.context_menu_cut(), "Cut");
335    ///
336    /// let de = Translations::new(Language::German);
337    /// assert_eq!(de.context_menu_cut(), "Ausschneiden");
338    /// ```
339    #[must_use]
340    pub fn context_menu_cut(&self) -> String {
341        rust_i18n::t!("context_menu.cut", locale = self.language.to_locale()).into_owned()
342    }
343
344    /// Returns the context-menu label for copy.
345    ///
346    /// # Examples
347    ///
348    /// ```
349    /// use iced_code_editor::{Language, Translations};
350    ///
351    /// let en = Translations::new(Language::English);
352    /// assert_eq!(en.context_menu_copy(), "Copy");
353    ///
354    /// let it = Translations::new(Language::Italian);
355    /// assert_eq!(it.context_menu_copy(), "Copia");
356    /// ```
357    #[must_use]
358    pub fn context_menu_copy(&self) -> String {
359        rust_i18n::t!("context_menu.copy", locale = self.language.to_locale()).into_owned()
360    }
361
362    /// Returns the context-menu label for paste.
363    ///
364    /// # Examples
365    ///
366    /// ```
367    /// use iced_code_editor::{Language, Translations};
368    ///
369    /// let en = Translations::new(Language::English);
370    /// assert_eq!(en.context_menu_paste(), "Paste");
371    ///
372    /// let es = Translations::new(Language::Spanish);
373    /// assert_eq!(es.context_menu_paste(), "Pegar");
374    /// ```
375    #[must_use]
376    pub fn context_menu_paste(&self) -> String {
377        rust_i18n::t!("context_menu.paste", locale = self.language.to_locale()).into_owned()
378    }
379
380    /// Returns the context-menu label for select all.
381    ///
382    /// # Examples
383    ///
384    /// ```
385    /// use iced_code_editor::{Language, Translations};
386    ///
387    /// let en = Translations::new(Language::English);
388    /// assert_eq!(en.context_menu_select_all(), "Select All");
389    ///
390    /// let fr = Translations::new(Language::French);
391    /// assert_eq!(fr.context_menu_select_all(), "Tout sélectionner");
392    /// ```
393    #[must_use]
394    pub fn context_menu_select_all(&self) -> String {
395        rust_i18n::t!(
396            "context_menu.select_all",
397            locale = self.language.to_locale()
398        )
399        .into_owned()
400    }
401
402    /// Returns the macOS context-menu label for revealing a file.
403    ///
404    /// Prefer [`Self::context_menu_reveal_in_file_manager`], which picks the
405    /// right one of the three platform wordings for you.
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// use iced_code_editor::{Language, Translations};
411    ///
412    /// let en = Translations::new(Language::English);
413    /// assert_eq!(en.context_menu_reveal_in_finder(), "Reveal in Finder");
414    /// ```
415    #[must_use]
416    pub fn context_menu_reveal_in_finder(&self) -> String {
417        rust_i18n::t!(
418            "context_menu.reveal_in_finder",
419            locale = self.language.to_locale()
420        )
421        .into_owned()
422    }
423
424    /// Returns the Windows context-menu label for revealing a file.
425    ///
426    /// Prefer [`Self::context_menu_reveal_in_file_manager`], which picks the
427    /// right one of the three platform wordings for you.
428    ///
429    /// # Examples
430    ///
431    /// ```
432    /// use iced_code_editor::{Language, Translations};
433    ///
434    /// let en = Translations::new(Language::English);
435    /// assert_eq!(
436    ///     en.context_menu_reveal_in_file_explorer(),
437    ///     "Reveal in File Explorer"
438    /// );
439    /// ```
440    #[must_use]
441    pub fn context_menu_reveal_in_file_explorer(&self) -> String {
442        rust_i18n::t!(
443            "context_menu.reveal_in_file_explorer",
444            locale = self.language.to_locale()
445        )
446        .into_owned()
447    }
448
449    /// Returns the Linux context-menu label for opening a file's parent folder.
450    ///
451    /// Worded as "open the containing folder" rather than "reveal", matching
452    /// how Linux file managers describe the action.
453    ///
454    /// # Examples
455    ///
456    /// ```
457    /// use iced_code_editor::{Language, Translations};
458    ///
459    /// let en = Translations::new(Language::English);
460    /// assert_eq!(
461    ///     en.context_menu_open_containing_folder(),
462    ///     "Open Containing Folder"
463    /// );
464    /// ```
465    #[must_use]
466    pub fn context_menu_open_containing_folder(&self) -> String {
467        rust_i18n::t!(
468            "context_menu.open_containing_folder",
469            locale = self.language.to_locale()
470        )
471        .into_owned()
472    }
473
474    /// Returns the platform-appropriate label for revealing a file.
475    ///
476    /// Resolves to "Reveal in Finder" on macOS, "Reveal in File Explorer" on
477    /// Windows, and "Open Containing Folder" elsewhere, so the menu matches
478    /// the wording users already know from their own file manager.
479    ///
480    /// # Examples
481    ///
482    /// ```
483    /// use iced_code_editor::{Language, Translations};
484    ///
485    /// let en = Translations::new(Language::English);
486    /// let label = en.context_menu_reveal_in_file_manager();
487    ///
488    /// // Whichever platform this runs on, it matches that platform's wording.
489    /// #[cfg(target_os = "macos")]
490    /// assert_eq!(label, en.context_menu_reveal_in_finder());
491    /// #[cfg(target_os = "windows")]
492    /// assert_eq!(label, en.context_menu_reveal_in_file_explorer());
493    /// #[cfg(not(any(target_os = "macos", target_os = "windows")))]
494    /// assert_eq!(label, en.context_menu_open_containing_folder());
495    /// ```
496    #[must_use]
497    pub fn context_menu_reveal_in_file_manager(&self) -> String {
498        if cfg!(target_os = "macos") {
499            self.context_menu_reveal_in_finder()
500        } else if cfg!(target_os = "windows") {
501            self.context_menu_reveal_in_file_explorer()
502        } else {
503            self.context_menu_open_containing_folder()
504        }
505    }
506    /// Returns the command-palette label for the filter input's placeholder.
507    ///
508    /// # Examples
509    ///
510    /// ```
511    /// use iced_code_editor::{Language, Translations};
512    ///
513    /// let en = Translations::new(Language::English);
514    /// assert_eq!(en.command_palette_placeholder(), "Type a command...");
515    /// ```
516    #[must_use]
517    pub fn command_palette_placeholder(&self) -> String {
518        rust_i18n::t!(
519            "command_palette.placeholder",
520            locale = self.language.to_locale()
521        )
522        .into_owned()
523    }
524
525    /// Returns the command-palette label for the empty-result message.
526    ///
527    /// # Examples
528    ///
529    /// ```
530    /// use iced_code_editor::{Language, Translations};
531    ///
532    /// let en = Translations::new(Language::English);
533    /// assert_eq!(en.command_palette_no_results(), "No matching command");
534    /// ```
535    #[must_use]
536    pub fn command_palette_no_results(&self) -> String {
537        rust_i18n::t!(
538            "command_palette.no_results",
539            locale = self.language.to_locale()
540        )
541        .into_owned()
542    }
543
544    /// Returns the command-palette label for saving the document.
545    ///
546    /// # Examples
547    ///
548    /// ```
549    /// use iced_code_editor::{Language, Translations};
550    ///
551    /// let en = Translations::new(Language::English);
552    /// assert_eq!(en.command_palette_save(), "Save");
553    /// ```
554    #[must_use]
555    pub fn command_palette_save(&self) -> String {
556        rust_i18n::t!("command_palette.save", locale = self.language.to_locale()).into_owned()
557    }
558
559    /// Returns the command-palette label for toggling the line comment.
560    ///
561    /// # Examples
562    ///
563    /// ```
564    /// use iced_code_editor::{Language, Translations};
565    ///
566    /// let en = Translations::new(Language::English);
567    /// assert_eq!(en.command_palette_toggle_comment(), "Toggle Line Comment");
568    /// ```
569    #[must_use]
570    pub fn command_palette_toggle_comment(&self) -> String {
571        rust_i18n::t!(
572            "command_palette.toggle_comment",
573            locale = self.language.to_locale()
574        )
575        .into_owned()
576    }
577
578    /// Returns the command-palette label for moving the current line up.
579    ///
580    /// # Examples
581    ///
582    /// ```
583    /// use iced_code_editor::{Language, Translations};
584    ///
585    /// let en = Translations::new(Language::English);
586    /// assert_eq!(en.command_palette_move_line_up(), "Move Line Up");
587    /// ```
588    #[must_use]
589    pub fn command_palette_move_line_up(&self) -> String {
590        rust_i18n::t!(
591            "command_palette.move_line_up",
592            locale = self.language.to_locale()
593        )
594        .into_owned()
595    }
596
597    /// Returns the command-palette label for moving the current line down.
598    ///
599    /// # Examples
600    ///
601    /// ```
602    /// use iced_code_editor::{Language, Translations};
603    ///
604    /// let en = Translations::new(Language::English);
605    /// assert_eq!(en.command_palette_move_line_down(), "Move Line Down");
606    /// ```
607    #[must_use]
608    pub fn command_palette_move_line_down(&self) -> String {
609        rust_i18n::t!(
610            "command_palette.move_line_down",
611            locale = self.language.to_locale()
612        )
613        .into_owned()
614    }
615
616    /// Returns the command-palette label for duplicating the current line above.
617    ///
618    /// # Examples
619    ///
620    /// ```
621    /// use iced_code_editor::{Language, Translations};
622    ///
623    /// let en = Translations::new(Language::English);
624    /// assert_eq!(en.command_palette_duplicate_line_up(), "Duplicate Line Up");
625    /// ```
626    #[must_use]
627    pub fn command_palette_duplicate_line_up(&self) -> String {
628        rust_i18n::t!(
629            "command_palette.duplicate_line_up",
630            locale = self.language.to_locale()
631        )
632        .into_owned()
633    }
634
635    /// Returns the command-palette label for duplicating the current line below.
636    ///
637    /// # Examples
638    ///
639    /// ```
640    /// use iced_code_editor::{Language, Translations};
641    ///
642    /// let en = Translations::new(Language::English);
643    /// assert_eq!(en.command_palette_duplicate_line_down(), "Duplicate Line Down");
644    /// ```
645    #[must_use]
646    pub fn command_palette_duplicate_line_down(&self) -> String {
647        rust_i18n::t!(
648            "command_palette.duplicate_line_down",
649            locale = self.language.to_locale()
650        )
651        .into_owned()
652    }
653
654    /// Returns the command-palette label for jumping to a line.
655    ///
656    /// # Examples
657    ///
658    /// ```
659    /// use iced_code_editor::{Language, Translations};
660    ///
661    /// let en = Translations::new(Language::English);
662    /// assert_eq!(en.command_palette_goto_line(), "Go to Line");
663    /// ```
664    #[must_use]
665    pub fn command_palette_goto_line(&self) -> String {
666        rust_i18n::t!(
667            "command_palette.goto_line",
668            locale = self.language.to_locale()
669        )
670        .into_owned()
671    }
672
673    /// Returns the command-palette label for adding a cursor on the line above.
674    ///
675    /// # Examples
676    ///
677    /// ```
678    /// use iced_code_editor::{Language, Translations};
679    ///
680    /// let en = Translations::new(Language::English);
681    /// assert_eq!(en.command_palette_add_cursor_above(), "Add Cursor Above");
682    /// ```
683    #[must_use]
684    pub fn command_palette_add_cursor_above(&self) -> String {
685        rust_i18n::t!(
686            "command_palette.add_cursor_above",
687            locale = self.language.to_locale()
688        )
689        .into_owned()
690    }
691
692    /// Returns the command-palette label for adding a cursor on the line below.
693    ///
694    /// # Examples
695    ///
696    /// ```
697    /// use iced_code_editor::{Language, Translations};
698    ///
699    /// let en = Translations::new(Language::English);
700    /// assert_eq!(en.command_palette_add_cursor_below(), "Add Cursor Below");
701    /// ```
702    #[must_use]
703    pub fn command_palette_add_cursor_below(&self) -> String {
704        rust_i18n::t!(
705            "command_palette.add_cursor_below",
706            locale = self.language.to_locale()
707        )
708        .into_owned()
709    }
710
711    /// Returns the command-palette label for selecting the next occurrence.
712    ///
713    /// # Examples
714    ///
715    /// ```
716    /// use iced_code_editor::{Language, Translations};
717    ///
718    /// let en = Translations::new(Language::English);
719    /// assert_eq!(en.command_palette_select_next_occurrence(), "Select Next Occurrence");
720    /// ```
721    #[must_use]
722    pub fn command_palette_select_next_occurrence(&self) -> String {
723        rust_i18n::t!(
724            "command_palette.select_next_occurrence",
725            locale = self.language.to_locale()
726        )
727        .into_owned()
728    }
729
730    /// Returns the command-palette label for toggling Vim mode.
731    ///
732    /// # Examples
733    ///
734    /// ```
735    /// use iced_code_editor::{Language, Translations};
736    ///
737    /// let en = Translations::new(Language::English);
738    /// assert_eq!(en.command_palette_toggle_vim_mode(), "Toggle Vim Mode");
739    /// ```
740    #[must_use]
741    pub fn command_palette_toggle_vim_mode(&self) -> String {
742        rust_i18n::t!(
743            "command_palette.toggle_vim_mode",
744            locale = self.language.to_locale()
745        )
746        .into_owned()
747    }
748
749    /// Returns the command-palette label for opening the search dialog.
750    ///
751    /// # Examples
752    ///
753    /// ```
754    /// use iced_code_editor::{Language, Translations};
755    ///
756    /// let en = Translations::new(Language::English);
757    /// assert_eq!(en.command_palette_find(), "Find");
758    /// ```
759    #[must_use]
760    pub fn command_palette_find(&self) -> String {
761        rust_i18n::t!("command_palette.find", locale = self.language.to_locale()).into_owned()
762    }
763
764    /// Returns the command-palette label for opening the search-and-replace dialog.
765    ///
766    /// # Examples
767    ///
768    /// ```
769    /// use iced_code_editor::{Language, Translations};
770    ///
771    /// let en = Translations::new(Language::English);
772    /// assert_eq!(en.command_palette_replace(), "Replace");
773    /// ```
774    #[must_use]
775    pub fn command_palette_replace(&self) -> String {
776        rust_i18n::t!(
777            "command_palette.replace",
778            locale = self.language.to_locale()
779        )
780        .into_owned()
781    }
782
783    /// Returns the command-palette label for folding the block at the cursor.
784    ///
785    /// # Examples
786    ///
787    /// ```
788    /// use iced_code_editor::{Language, Translations};
789    ///
790    /// let en = Translations::new(Language::English);
791    /// assert_eq!(en.command_palette_fold_at_cursor(), "Toggle Fold at Cursor");
792    /// ```
793    #[must_use]
794    pub fn command_palette_fold_at_cursor(&self) -> String {
795        rust_i18n::t!(
796            "command_palette.fold_at_cursor",
797            locale = self.language.to_locale()
798        )
799        .into_owned()
800    }
801
802    /// Returns the command-palette label for folding every block.
803    ///
804    /// # Examples
805    ///
806    /// ```
807    /// use iced_code_editor::{Language, Translations};
808    ///
809    /// let en = Translations::new(Language::English);
810    /// assert_eq!(en.command_palette_fold_all(), "Fold All");
811    /// ```
812    #[must_use]
813    pub fn command_palette_fold_all(&self) -> String {
814        rust_i18n::t!(
815            "command_palette.fold_all",
816            locale = self.language.to_locale()
817        )
818        .into_owned()
819    }
820
821    /// Returns the command-palette label for unfolding every block.
822    ///
823    /// # Examples
824    ///
825    /// ```
826    /// use iced_code_editor::{Language, Translations};
827    ///
828    /// let en = Translations::new(Language::English);
829    /// assert_eq!(en.command_palette_unfold_all(), "Unfold All");
830    /// ```
831    #[must_use]
832    pub fn command_palette_unfold_all(&self) -> String {
833        rust_i18n::t!(
834            "command_palette.unfold_all",
835            locale = self.language.to_locale()
836        )
837        .into_owned()
838    }
839}
840
841#[cfg(test)]
842mod tests {
843    use std::collections::BTreeSet;
844
845    use super::*;
846
847    /// Every locale file, paired with the name used in failure messages.
848    ///
849    /// English comes first: it is the reference every other file is compared
850    /// against, and the fallback `rust_i18n` resolves a missing key through.
851    const LOCALE_FILES: [(&str, &str); 8] = [
852        ("en", include_str!("../locales/en.yml")),
853        ("fr", include_str!("../locales/fr.yml")),
854        ("es", include_str!("../locales/es.yml")),
855        ("de", include_str!("../locales/de.yml")),
856        ("it", include_str!("../locales/it.yml")),
857        ("pt-BR", include_str!("../locales/pt-BR.yml")),
858        ("pt-PT", include_str!("../locales/pt-PT.yml")),
859        ("zh-CN", include_str!("../locales/zh-CN.yml")),
860    ];
861
862    /// Collects the `section.key` paths a locale file defines.
863    ///
864    /// Deliberately a five-line reader rather than a YAML dependency: the
865    /// files are a flat list of `section:` headers with two-space-indented
866    /// entries under them, and reading them structurally is the whole point —
867    /// going through `rust_i18n` is exactly what cannot see a missing key.
868    fn locale_keys(yaml: &str) -> BTreeSet<String> {
869        let mut keys = BTreeSet::new();
870        let mut section = String::new();
871
872        for line in yaml.lines() {
873            let line = line.trim_end();
874            if line.trim_start().is_empty() || line.trim_start().starts_with('#') {
875                continue;
876            }
877
878            match line.strip_prefix("  ") {
879                // Indented: an entry belonging to the current section.
880                Some(entry) => {
881                    if let Some((name, _)) = entry.split_once(':') {
882                        keys.insert(format!("{section}.{}", name.trim()));
883                    }
884                },
885                // Flush left: a new section header.
886                None => {
887                    if let Some((name, _)) = line.split_once(':') {
888                        section = name.trim().to_string();
889                    }
890                },
891            }
892        }
893
894        keys
895    }
896
897    #[test]
898    fn test_locale_keys_reads_the_section_and_entry_layout() {
899        // Guards the guard: a reader that silently returned nothing would make
900        // every comparison below pass on an empty set.
901        let keys = locale_keys(
902            "# a comment\nsearch:\n  placeholder: \"Search...\"\n\nreplace:\n  all_tooltip: \"Replace all matches\"\n",
903        );
904
905        assert_eq!(
906            keys.iter().map(String::as_str).collect::<Vec<_>>(),
907            ["replace.all_tooltip", "search.placeholder"]
908        );
909    }
910
911    #[test]
912    fn test_every_locale_defines_exactly_the_keys_english_defines() {
913        // The structural check the runtime ones cannot perform: with
914        // `fallback = "en"`, a key present in `en.yml` and missing from
915        // `fr.yml` resolves to the *English* string, so no assertion made
916        // through `Translations` can tell the two apart. Comparing the files
917        // themselves is what catches a translator skipping an entry.
918        let (_, english_source) = LOCALE_FILES[0];
919        let english = locale_keys(english_source);
920        assert!(
921            english.contains("command_palette.fold_all"),
922            "en.yml did not parse as expected"
923        );
924
925        for (name, source) in LOCALE_FILES {
926            let keys = locale_keys(source);
927            let missing: Vec<&String> = english.difference(&keys).collect();
928            let extra: Vec<&String> = keys.difference(&english).collect();
929
930            assert!(missing.is_empty(), "{name}.yml is missing {missing:?}");
931            assert!(
932                extra.is_empty(),
933                "{name}.yml defines {extra:?}, which en.yml does not"
934            );
935        }
936    }
937
938    #[test]
939    fn test_default_language() {
940        let translations = Translations::default();
941        assert_eq!(translations.language(), Language::English);
942    }
943
944    #[test]
945    fn test_new_with_language() {
946        let translations = Translations::new(Language::French);
947        assert_eq!(translations.language(), Language::French);
948    }
949
950    #[test]
951    fn test_set_language() {
952        let mut translations = Translations::new(Language::English);
953        translations.set_language(Language::Spanish);
954        assert_eq!(translations.language(), Language::Spanish);
955    }
956
957    #[test]
958    fn test_english_translations() {
959        let t = Translations::new(Language::English);
960        assert_eq!(t.search_placeholder(), "Search...");
961        assert_eq!(t.replace_placeholder(), "Replace...");
962        assert_eq!(t.case_sensitive_label(), "Case sensitive");
963        assert_eq!(t.previous_match_tooltip(), "Previous match (Shift+F3)");
964        assert_eq!(t.next_match_tooltip(), "Next match (F3 / Enter)");
965        assert_eq!(t.close_search_tooltip(), "Close search dialog (Esc)");
966        assert_eq!(t.replace_current_tooltip(), "Replace current match");
967        assert_eq!(t.replace_all_tooltip(), "Replace all matches");
968    }
969
970    #[test]
971    fn test_french_translations() {
972        let t = Translations::new(Language::French);
973        assert_eq!(t.search_placeholder(), "Rechercher...");
974        assert_eq!(t.replace_placeholder(), "Remplacer...");
975        assert_eq!(t.case_sensitive_label(), "Sensible à la casse");
976        assert_eq!(t.previous_match_tooltip(), "Résultat précédent (Maj+F3)");
977        assert_eq!(t.next_match_tooltip(), "Résultat suivant (F3 / Entrée)");
978        assert_eq!(t.close_search_tooltip(), "Fermer la recherche (Échap)");
979        assert_eq!(
980            t.replace_current_tooltip(),
981            "Remplacer l'occurrence actuelle"
982        );
983        assert_eq!(t.replace_all_tooltip(), "Tout remplacer");
984    }
985
986    #[test]
987    fn test_spanish_translations() {
988        let t = Translations::new(Language::Spanish);
989        assert_eq!(t.search_placeholder(), "Buscar...");
990        assert_eq!(t.replace_placeholder(), "Reemplazar...");
991        assert_eq!(t.case_sensitive_label(), "Distinguir mayúsculas");
992        assert_eq!(
993            t.previous_match_tooltip(),
994            "Coincidencia anterior (Mayús+F3)"
995        );
996        assert_eq!(
997            t.next_match_tooltip(),
998            "Siguiente coincidencia (F3 / Enter)"
999        );
1000        assert_eq!(t.close_search_tooltip(), "Cerrar búsqueda (Esc)");
1001        assert_eq!(
1002            t.replace_current_tooltip(),
1003            "Reemplazar coincidencia actual"
1004        );
1005        assert_eq!(t.replace_all_tooltip(), "Reemplazar todo");
1006    }
1007
1008    #[test]
1009    fn test_german_translations() {
1010        let t = Translations::new(Language::German);
1011        assert_eq!(t.search_placeholder(), "Suchen...");
1012        assert_eq!(t.replace_placeholder(), "Ersetzen...");
1013        assert_eq!(t.case_sensitive_label(), "Groß-/Kleinschreibung");
1014        assert_eq!(
1015            t.previous_match_tooltip(),
1016            "Vorheriger Treffer (Umschalt+F3)"
1017        );
1018        assert_eq!(t.next_match_tooltip(), "Nächster Treffer (F3 / Enter)");
1019        assert_eq!(t.close_search_tooltip(), "Suchdialog schließen (Esc)");
1020        assert_eq!(t.replace_current_tooltip(), "Aktuellen Treffer ersetzen");
1021        assert_eq!(t.replace_all_tooltip(), "Alle ersetzen");
1022    }
1023
1024    #[test]
1025    fn test_italian_translations() {
1026        let t = Translations::new(Language::Italian);
1027        assert_eq!(t.search_placeholder(), "Cerca...");
1028        assert_eq!(t.replace_placeholder(), "Sostituisci...");
1029        assert_eq!(t.case_sensitive_label(), "Distingui maiuscole");
1030        assert_eq!(
1031            t.previous_match_tooltip(),
1032            "Risultato precedente (Maiusc+F3)"
1033        );
1034        assert_eq!(t.next_match_tooltip(), "Risultato successivo (F3 / Invio)");
1035        assert_eq!(t.close_search_tooltip(), "Chiudi finestra di ricerca (Esc)");
1036        assert_eq!(
1037            t.replace_current_tooltip(),
1038            "Sostituisci risultato corrente"
1039        );
1040        assert_eq!(t.replace_all_tooltip(), "Sostituisci tutto");
1041    }
1042
1043    #[test]
1044    fn test_portuguese_br_translations() {
1045        let t = Translations::new(Language::PortugueseBR);
1046        assert_eq!(t.search_placeholder(), "Pesquisar...");
1047        assert_eq!(t.replace_placeholder(), "Substituir...");
1048        assert_eq!(t.case_sensitive_label(), "Diferenciar maiúsculas");
1049        assert_eq!(
1050            t.previous_match_tooltip(),
1051            "Correspondência anterior (Shift+F3)"
1052        );
1053        assert_eq!(
1054            t.next_match_tooltip(),
1055            "Próxima correspondência (F3 / Enter)"
1056        );
1057        assert_eq!(t.close_search_tooltip(), "Fechar diálogo de pesquisa (Esc)");
1058        assert_eq!(
1059            t.replace_current_tooltip(),
1060            "Substituir correspondência atual"
1061        );
1062        assert_eq!(t.replace_all_tooltip(), "Substituir tudo");
1063    }
1064
1065    #[test]
1066    fn test_portuguese_pt_translations() {
1067        let t = Translations::new(Language::PortuguesePT);
1068        assert_eq!(t.search_placeholder(), "Pesquisar...");
1069        assert_eq!(t.replace_placeholder(), "Substituir...");
1070        assert_eq!(t.case_sensitive_label(), "Diferenciar maiúsculas");
1071        assert_eq!(
1072            t.previous_match_tooltip(),
1073            "Correspondência anterior (Shift+F3)"
1074        );
1075        assert_eq!(
1076            t.next_match_tooltip(),
1077            "Próxima correspondência (F3 / Enter)"
1078        );
1079        assert_eq!(t.close_search_tooltip(), "Fechar diálogo de pesquisa (Esc)");
1080        assert_eq!(
1081            t.replace_current_tooltip(),
1082            "Substituir correspondência actual"
1083        );
1084        assert_eq!(t.replace_all_tooltip(), "Substituir tudo");
1085    }
1086
1087    #[test]
1088    fn test_language_switching() {
1089        let mut t = Translations::new(Language::English);
1090        assert_eq!(t.search_placeholder(), "Search...");
1091
1092        t.set_language(Language::French);
1093        assert_eq!(t.search_placeholder(), "Rechercher...");
1094
1095        t.set_language(Language::Spanish);
1096        assert_eq!(t.search_placeholder(), "Buscar...");
1097
1098        t.set_language(Language::German);
1099        assert_eq!(t.search_placeholder(), "Suchen...");
1100
1101        t.set_language(Language::Italian);
1102        assert_eq!(t.search_placeholder(), "Cerca...");
1103
1104        t.set_language(Language::PortugueseBR);
1105        assert_eq!(t.search_placeholder(), "Pesquisar...");
1106
1107        t.set_language(Language::PortuguesePT);
1108        assert_eq!(t.search_placeholder(), "Pesquisar...");
1109
1110        t.set_language(Language::ChineseSimplified);
1111        assert_eq!(t.search_placeholder(), "搜索...");
1112    }
1113
1114    #[test]
1115    fn test_context_menu_translations_cover_all_locales() {
1116        let cases = [
1117            (
1118                Language::English,
1119                [
1120                    "Undo",
1121                    "Redo",
1122                    "Cut",
1123                    "Copy",
1124                    "Paste",
1125                    "Select All",
1126                    "Reveal in Finder",
1127                    "Reveal in File Explorer",
1128                    "Open Containing Folder",
1129                ],
1130            ),
1131            (
1132                Language::French,
1133                [
1134                    "Annuler",
1135                    "Rétablir",
1136                    "Couper",
1137                    "Copier",
1138                    "Coller",
1139                    "Tout sélectionner",
1140                    "Révéler dans le Finder",
1141                    "Afficher dans l'Explorateur de fichiers",
1142                    "Ouvrir le dossier contenant",
1143                ],
1144            ),
1145            (
1146                Language::Spanish,
1147                [
1148                    "Deshacer",
1149                    "Rehacer",
1150                    "Cortar",
1151                    "Copiar",
1152                    "Pegar",
1153                    "Seleccionar todo",
1154                    "Mostrar en Finder",
1155                    "Mostrar en el Explorador de archivos",
1156                    "Abrir carpeta contenedora",
1157                ],
1158            ),
1159            (
1160                Language::German,
1161                [
1162                    "Rückgängig",
1163                    "Wiederholen",
1164                    "Ausschneiden",
1165                    "Kopieren",
1166                    "Einfügen",
1167                    "Alle auswählen",
1168                    "Im Finder anzeigen",
1169                    "Im Datei-Explorer anzeigen",
1170                    "Übergeordneten Ordner öffnen",
1171                ],
1172            ),
1173            (
1174                Language::Italian,
1175                [
1176                    "Annulla azione",
1177                    "Ripeti",
1178                    "Taglia",
1179                    "Copia",
1180                    "Incolla",
1181                    "Seleziona tutto",
1182                    "Visualizza in Finder",
1183                    "Visualizza in Esplora file",
1184                    "Apri cartella superiore",
1185                ],
1186            ),
1187            (
1188                Language::PortugueseBR,
1189                [
1190                    "Desfazer",
1191                    "Refazer",
1192                    "Recortar",
1193                    "Copiar",
1194                    "Colar",
1195                    "Selecionar Tudo",
1196                    "Revelar no Finder",
1197                    "Revelar no Explorador de Arquivos",
1198                    "Abrir a Pasta Que Contém",
1199                ],
1200            ),
1201            (
1202                Language::PortuguesePT,
1203                [
1204                    "Anular",
1205                    "Refazer",
1206                    "Cortar",
1207                    "Copiar",
1208                    "Colar",
1209                    "Selecionar tudo",
1210                    "Mostrar no Finder",
1211                    "Mostrar no Explorador de Ficheiros",
1212                    "Abrir pasta contentora",
1213                ],
1214            ),
1215            (
1216                Language::ChineseSimplified,
1217                [
1218                    "撤消",
1219                    "恢复",
1220                    "剪切",
1221                    "复制",
1222                    "粘贴",
1223                    "选择全部",
1224                    "在访达中显示",
1225                    "在文件资源管理器中显示",
1226                    "打开所在的文件夹",
1227                ],
1228            ),
1229        ];
1230
1231        for (language, expected) in cases {
1232            let translations = Translations::new(language);
1233            assert_eq!(translations.context_menu_undo(), expected[0]);
1234            assert_eq!(translations.context_menu_redo(), expected[1]);
1235            assert_eq!(translations.context_menu_cut(), expected[2]);
1236            assert_eq!(translations.context_menu_copy(), expected[3]);
1237            assert_eq!(translations.context_menu_paste(), expected[4]);
1238            assert_eq!(translations.context_menu_select_all(), expected[5]);
1239            assert_eq!(translations.context_menu_reveal_in_finder(), expected[6]);
1240            assert_eq!(
1241                translations.context_menu_reveal_in_file_explorer(),
1242                expected[7]
1243            );
1244            assert_eq!(
1245                translations.context_menu_open_containing_folder(),
1246                expected[8]
1247            );
1248        }
1249    }
1250
1251    #[test]
1252    fn test_every_command_palette_accessor_resolves_to_a_defined_key() {
1253        // What this can catch: a typo in an accessor's `t!` key path. rust-i18n
1254        // echoes the path back when it resolves to nothing, so the label comes
1255        // out starting with "command_palette.".
1256        //
1257        // What it cannot: a key missing from one locale. `fallback = "en"`
1258        // makes that resolve to the English string, which is neither empty nor
1259        // a key path. Locale completeness is checked structurally instead, by
1260        // `test_every_locale_defines_exactly_the_keys_english_defines`; the
1261        // loop over all eight languages here is what proves every accessor is
1262        // reachable in each of them, not that each has its own wording.
1263        let languages = [
1264            Language::English,
1265            Language::French,
1266            Language::Spanish,
1267            Language::German,
1268            Language::Italian,
1269            Language::PortugueseBR,
1270            Language::PortuguesePT,
1271            Language::ChineseSimplified,
1272        ];
1273
1274        for language in languages {
1275            let t = Translations::new(language);
1276            let labels = [
1277                t.command_palette_placeholder(),
1278                t.command_palette_no_results(),
1279                t.command_palette_save(),
1280                t.command_palette_toggle_comment(),
1281                t.command_palette_move_line_up(),
1282                t.command_palette_move_line_down(),
1283                t.command_palette_duplicate_line_up(),
1284                t.command_palette_duplicate_line_down(),
1285                t.command_palette_goto_line(),
1286                t.command_palette_add_cursor_above(),
1287                t.command_palette_add_cursor_below(),
1288                t.command_palette_select_next_occurrence(),
1289                t.command_palette_toggle_vim_mode(),
1290                t.command_palette_find(),
1291                t.command_palette_replace(),
1292                t.command_palette_fold_at_cursor(),
1293                t.command_palette_fold_all(),
1294                t.command_palette_unfold_all(),
1295            ];
1296
1297            for label in labels {
1298                assert!(!label.is_empty(), "empty label for {language:?}");
1299                assert!(
1300                    !label.starts_with("command_palette."),
1301                    "missing translation {label} for {language:?}"
1302                );
1303            }
1304        }
1305    }
1306
1307    #[test]
1308    fn test_command_palette_labels_are_localized() {
1309        let cases = [
1310            (Language::English, "Fold All", "Go to Line"),
1311            (Language::French, "Tout replier", "Aller à la ligne"),
1312            (Language::Spanish, "Plegar todo", "Ir a la línea"),
1313            (Language::German, "Alles falten", "Gehe zu Zeile"),
1314            (Language::Italian, "Comprimi tutto", "Vai alla riga"),
1315            (Language::PortugueseBR, "Dobrar tudo", "Ir para a linha"),
1316            (Language::PortuguesePT, "Dobrar tudo", "Ir para a linha"),
1317            (Language::ChineseSimplified, "全部折叠", "转到行"),
1318        ];
1319
1320        for (language, fold_all, goto_line) in cases {
1321            let t = Translations::new(language);
1322            assert_eq!(t.command_palette_fold_all(), fold_all);
1323            assert_eq!(t.command_palette_goto_line(), goto_line);
1324        }
1325    }
1326}