Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Rename rules without regular expressions

KnifeLemon387202c57274
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 198590da..3a163612 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,12 +24,13 @@ find it, what it does and doesn't do.
many files in the folder match. Other files in the folder are left alone.
- *File name rule*: a name pattern for this folder in place of the preset's, with `{name}`, `{date}`, `{time}`,
`{index}` and `{preset}`.
- - *Rename converted files*: **Edit rules** opens a window of rules that find part of the name with a regular
- expression and replace it, applied from top to bottom (e.g. `IMG_(\d+)` → `Photo_$1`). **Common replacements**
- on the left lists ready-made ones (camera numbers, spaces, copy numbers like "(2)", text in brackets, dates,
- symbols, text at the start or end), each with an example of what it does; double-click one or press + to add it
- and change it from there. The preview shows files from the folder before and after, and any name you type.
- Nothing changes until you save.
+ - *Rename converted files*: **Edit rules** opens a window of rules applied from top to bottom. Each rule says
+ what it does — replace text, remove text, add at the start or end, spaces to `_`, remove a copy number like
+ "(2)", remove text in brackets, remove a leading number, remove symbols, all lowercase or uppercase — and asks
+ only for the text it needs. A regular expression is there as the last, advanced kind. **Common replacements** on
+ the left lists ready-made rules with an example of what each does; double-click one or press + to add it and
+ change it from there. The preview shows files from the folder before and after, and any name you type. Nothing
+ changes until you save.
- A **preview** on every watch folder shows a converted file as it will be saved (`IMG_0412.jpg →
converted\Photo_0412.pdf`, using a file already in the folder when there is one), what happens when the name is
taken and what happens to the original.
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 90079e7d..6190baff 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -484,11 +484,31 @@
"watch.rename": "Rename converted files",
"watch.rename_find": "Find, e.g. IMG_(\\d+)",
"watch.rename_replace": "Replace with, e.g. Photo_$1",
+ "watch.kind.Replace": "Replace text",
+ "watch.kind.Remove": "Remove text",
+ "watch.kind.Prefix": "Add at the start",
+ "watch.kind.Suffix": "Add at the end",
+ "watch.kind.SpacesToUnderscores": "Spaces to _",
+ "watch.kind.RemoveCopyNumber": "Remove a copy number like (2)",
+ "watch.kind.RemoveBrackets": "Remove text in brackets",
+ "watch.kind.RemoveLeadingNumber": "Remove a leading number",
+ "watch.kind.RemoveSymbols": "Remove symbols",
+ "watch.kind.Lowercase": "all lowercase",
+ "watch.kind.Uppercase": "ALL UPPERCASE",
+ "watch.kind.Regex": "Advanced: regular expression",
+ "watch.ph.find": "Text to find, e.g. IMG_",
+ "watch.ph.replace": "Replace with, e.g. Photo_",
+ "watch.ph.remove": "Text to remove, e.g. _copy",
+ "watch.ph.prefix": "Text to add, e.g. 2026_",
+ "watch.ph.suffix": "Text to add, e.g. _final",
+ "watch.advanced": "Advanced",
+ "watch.recipe.camera_to_photo": "Change IMG_ to Photo_",
+ "watch.recipe.lowercase": "All lowercase",
"watch.rename_none": "Names stay as the file name rule makes them.",
"watch.rename_edit": "Edit rules",
"watch.rename_add": "Add rules",
"watch.rename_title": "Rename converted files",
- "watch.rename_intro": "Each rule finds part of the name with a regular expression and replaces it; the rules run from top to bottom. The preview shows what happens to files in the folder.",
+ "watch.rename_intro": "Pick what each rule does and fill in the text. Rules run from top to bottom, and the preview shows what happens to files in the folder.",
"watch.rename_steps": "Rules (applied in order)",
"watch.rename_no_steps": "No rules yet. Pick one on the left or add an empty one.",
"watch.step_up": "Move up (run earlier)",
@@ -501,8 +521,7 @@
"watch.recipes_hint": "Double-click one (or press +) to add it as a rule, then change it if you like.",
"watch.recipe_add": "Add as a rule",
"watch.recipe_removes": "(removed)",
- "watch.recipe.photo_number": "Camera file names to Photo_number",
- "watch.recipe.drop_camera_prefix": "Remove IMG_, DSC_ or PXL_",
+ "watch.recipe.drop_camera_prefix": "Remove IMG_",
"watch.recipe.spaces": "Spaces to underscores",
"watch.recipe.copy_number": "Remove a copy number like (2)",
"watch.recipe.brackets": "Remove text in brackets",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 92021cb0..05c62b1b 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -484,11 +484,31 @@
"watch.rename": "변환된 파일 이름 바꾸기",
"watch.rename_find": "찾을 패턴 (예: IMG_(\\d+))",
"watch.rename_replace": "바꿀 내용 (예: 사진_$1)",
+ "watch.kind.Replace": "글자 바꾸기",
+ "watch.kind.Remove": "글자 지우기",
+ "watch.kind.Prefix": "앞에 붙이기",
+ "watch.kind.Suffix": "뒤에 붙이기",
+ "watch.kind.SpacesToUnderscores": "공백을 _로",
+ "watch.kind.RemoveCopyNumber": "(2) 같은 사본 번호 지우기",
+ "watch.kind.RemoveBrackets": "괄호와 그 안의 글자 지우기",
+ "watch.kind.RemoveLeadingNumber": "앞에 붙은 번호 지우기",
+ "watch.kind.RemoveSymbols": "특수 문자 지우기",
+ "watch.kind.Lowercase": "모두 소문자로",
+ "watch.kind.Uppercase": "모두 대문자로",
+ "watch.kind.Regex": "고급: 정규식",
+ "watch.ph.find": "찾을 글자 (예: IMG_)",
+ "watch.ph.replace": "바꿀 글자 (예: 사진_)",
+ "watch.ph.remove": "지울 글자 (예: _copy)",
+ "watch.ph.prefix": "붙일 글자 (예: 2026_)",
+ "watch.ph.suffix": "붙일 글자 (예: _final)",
+ "watch.advanced": "고급",
+ "watch.recipe.camera_to_photo": "IMG_를 Photo_로 바꾸기",
+ "watch.recipe.lowercase": "모두 소문자로",
"watch.rename_none": "파일명 규칙으로 만든 이름을 그대로 써요.",
"watch.rename_edit": "규칙 편집",
"watch.rename_add": "규칙 추가",
"watch.rename_title": "변환된 파일 이름 바꾸기",
- "watch.rename_intro": "규칙마다 이름의 일부를 정규식으로 찾아서 바꿔요. 위에서부터 차례로 적용되고, 미리보기에서 폴더의 파일이 어떻게 바뀌는지 바로 확인할 수 있어요.",
+ "watch.rename_intro": "규칙마다 할 일을 고르고 필요한 글자만 넣으세요. 위에서부터 차례로 적용되고, 미리보기에서 폴더의 파일이 어떻게 바뀌는지 바로 확인할 수 있어요.",
"watch.rename_steps": "규칙 (위에서부터 차례로 적용)",
"watch.rename_no_steps": "아직 규칙이 없어요. 왼쪽에서 고르거나 빈 규칙을 추가하세요.",
"watch.step_up": "위로 (먼저 적용)",
@@ -501,8 +521,7 @@
"watch.recipes_hint": "더블클릭하거나 + 를 누르면 규칙으로 추가돼요. 추가한 뒤 자유롭게 고칠 수 있어요.",
"watch.recipe_add": "규칙으로 추가",
"watch.recipe_removes": "(지우기)",
- "watch.recipe.photo_number": "카메라 파일 이름을 Photo_번호로",
- "watch.recipe.drop_camera_prefix": "IMG_, DSC_, PXL_ 지우기",
+ "watch.recipe.drop_camera_prefix": "IMG_ 지우기",
"watch.recipe.spaces": "공백을 밑줄(_)로",
"watch.recipe.copy_number": "(2) 같은 사본 번호 지우기",
"watch.recipe.brackets": "괄호와 그 안의 글자 지우기",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index e620c576..971be2e8 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -484,11 +484,31 @@
"watch.rename": "重命名转换后的文件",
"watch.rename_find": "查找,例如 IMG_(\\d+)",
"watch.rename_replace": "替换为,例如 照片_$1",
+ "watch.kind.Replace": "替换文字",
+ "watch.kind.Remove": "删除文字",
+ "watch.kind.Prefix": "在开头添加",
+ "watch.kind.Suffix": "在末尾添加",
+ "watch.kind.SpacesToUnderscores": "空格改为 _",
+ "watch.kind.RemoveCopyNumber": "删除 (2) 这样的副本编号",
+ "watch.kind.RemoveBrackets": "删除括号及其中的文字",
+ "watch.kind.RemoveLeadingNumber": "删除开头的编号",
+ "watch.kind.RemoveSymbols": "删除特殊符号",
+ "watch.kind.Lowercase": "全部小写",
+ "watch.kind.Uppercase": "全部大写",
+ "watch.kind.Regex": "高级:正则表达式",
+ "watch.ph.find": "要查找的文字,例如 IMG_",
+ "watch.ph.replace": "替换为,例如 照片_",
+ "watch.ph.remove": "要删除的文字,例如 _copy",
+ "watch.ph.prefix": "要添加的文字,例如 2026_",
+ "watch.ph.suffix": "要添加的文字,例如 _final",
+ "watch.advanced": "高级",
+ "watch.recipe.camera_to_photo": "把 IMG_ 改为 Photo_",
+ "watch.recipe.lowercase": "全部小写",
"watch.rename_none": "名称保持文件名规则生成的样子。",
"watch.rename_edit": "编辑规则",
"watch.rename_add": "添加规则",
"watch.rename_title": "重命名转换后的文件",
- "watch.rename_intro": "每条规则用正则表达式找到名称的一部分并替换,规则从上到下依次执行。预览会显示文件夹中的文件如何变化。",
+ "watch.rename_intro": "为每条规则选择要做的事,只需填写所需的文字。规则从上到下依次执行,预览会显示文件夹中的文件如何变化。",
"watch.rename_steps": "规则(按顺序执行)",
"watch.rename_no_steps": "还没有规则。从左侧选择,或添加一条空规则。",
"watch.step_up": "上移(先执行)",
@@ -501,8 +521,7 @@
"watch.recipes_hint": "双击(或点 +)即可添加为规则,添加后可以再修改。",
"watch.recipe_add": "添加为规则",
"watch.recipe_removes": "(删除)",
- "watch.recipe.photo_number": "相机文件名改为 Photo_编号",
- "watch.recipe.drop_camera_prefix": "去掉 IMG_、DSC_、PXL_",
+ "watch.recipe.drop_camera_prefix": "去掉 IMG_",
"watch.recipe.spaces": "空格改为下划线",
"watch.recipe.copy_number": "去掉 (2) 这样的副本编号",
"watch.recipe.brackets": "去掉括号及其中的文字",
diff --git a/src/Filee.App/Services/WatchFolderService.cs b/src/Filee.App/Services/WatchFolderService.cs
index 68fe22d7..e3b86588 100644
--- a/src/Filee.App/Services/WatchFolderService.cs
+++ b/src/Filee.App/Services/WatchFolderService.cs
@@ -87,7 +87,7 @@ public sealed class WatchFolderService(UserDataStore store, ConversionService co
private static string Signature(WatchRule rule) =>
string.Join('|', rule.Folder, rule.PresetId, rule.IncludeSubfolders, rule.OutputFolder, rule.Originals,
string.Join('/', rule.Include), rule.FileNamePattern,
- string.Join('/', rule.Renames.Select(r => $"{r.Find}>{r.Replace}")));
+ string.Join('/', rule.Renames.Select(r => $"{r.Kind}:{r.Find}>{r.Replace}")));
public async ValueTask DisposeAsync()
{
diff --git a/src/Filee.App/ViewModels/Pages/RenameRecipes.cs b/src/Filee.App/ViewModels/Pages/RenameRecipes.cs
index 4b92b00d..f8f8b434 100644
--- a/src/Filee.App/ViewModels/Pages/RenameRecipes.cs
+++ b/src/Filee.App/ViewModels/Pages/RenameRecipes.cs
@@ -1,27 +1,43 @@
-// Ready-made replacements for the names of converted files (Watch folders → More options → Replace part of the
-// name). Each one adds a step the user can edit afterwards.
+// Ready-made rules for the names of converted files (Watch folders → More options → Rename converted files → Edit
+// rules). Each one adds a rule the user can change afterwards.
+
+using Filee.Core.Localization;
+using Filee.Core.Presets;
namespace Filee.App.ViewModels.Pages;
/// <param name="TitleKey">Localization key of what it does.</param>
-/// <param name="Find">Regular expression.</param>
-/// <param name="Replace">What goes in its place; empty removes the match.</param>
+/// <param name="Step">The rule it adds.</param>
/// <param name="Example">A name it changes, shown with the result.</param>
-public sealed record RenameRecipe(string TitleKey, string Find, string Replace, string Example);
+public sealed record RenameRecipe(string TitleKey, RenameStep Step, string Example);
public static class RenameRecipes
{
public static IReadOnlyList<RenameRecipe> All { get; } =
[
- new("watch.recipe.photo_number", @"^(?:IMG|DSC|PXL)_(\d+)", "Photo_$1", "IMG_0412"),
- new("watch.recipe.drop_camera_prefix", @"^(?:IMG|DSC|PXL)_", "", "DSC_0815"),
- new("watch.recipe.spaces", @"\s+", "_", "trip to busan"),
- new("watch.recipe.copy_number", @"\s*\(\d+\)$", "", "report (2)"),
- new("watch.recipe.brackets", @"\s*[\(\[][^\)\]]*[\)\]]", "", "song [remix] (live)"),
- new("watch.recipe.leading_number", @"^\d+[\s._-]*", "", "01 - intro"),
- new("watch.recipe.date_dashes", @"(\d{4})(\d{2})(\d{2})", "$1-$2-$3", "scan_20261011"),
- new("watch.recipe.symbols", @"[^\w\s.-]", "", "invoice#12@acme!"),
- new("watch.recipe.prefix", "^", "new_", "report"),
- new("watch.recipe.suffix", "$", "_final", "report"),
+ new("watch.recipe.camera_to_photo", new RenameStep { Kind = RenameKind.Replace, Find = "IMG_", Replace = "Photo_" }, "IMG_0412"),
+ new("watch.recipe.drop_camera_prefix", new RenameStep { Kind = RenameKind.Remove, Find = "IMG_" }, "IMG_0412"),
+ new("watch.recipe.spaces", new RenameStep { Kind = RenameKind.SpacesToUnderscores }, "trip to busan"),
+ new("watch.recipe.copy_number", new RenameStep { Kind = RenameKind.RemoveCopyNumber }, "report (2)"),
+ new("watch.recipe.brackets", new RenameStep { Kind = RenameKind.RemoveBrackets }, "song [remix] (live)"),
+ new("watch.recipe.leading_number", new RenameStep { Kind = RenameKind.RemoveLeadingNumber }, "01 - intro"),
+ new("watch.recipe.symbols", new RenameStep { Kind = RenameKind.RemoveSymbols }, "invoice#12@acme!"),
+ new("watch.recipe.lowercase", new RenameStep { Kind = RenameKind.Lowercase }, "Report_FINAL"),
+ new("watch.recipe.prefix", new RenameStep { Kind = RenameKind.Prefix, Replace = "new_" }, "report"),
+ new("watch.recipe.suffix", new RenameStep { Kind = RenameKind.Suffix, Replace = "_final" }, "report"),
+ new("watch.recipe.date_dashes", new RenameStep { Kind = RenameKind.Regex, Find = @"(\d{4})(\d{2})(\d{2})", Replace = "$1-$2-$3" }, "scan_20261011"),
];
+
+ /// <summary>A rule in one line for the watch folder card: "Replace text: IMG_ → Photo_", "Spaces to _".</summary>
+ public static string Describe(ILocalizer loc, RenameStep step)
+ {
+ var kind = loc[$"watch.kind.{step.Kind}"];
+ return step.Kind switch
+ {
+ RenameKind.Replace or RenameKind.Regex => $"{kind}: {step.Find} → {(step.Replace.Length == 0 ? loc["watch.recipe_removes"] : step.Replace)}",
+ RenameKind.Remove => $"{kind}: {step.Find}",
+ RenameKind.Prefix or RenameKind.Suffix => $"{kind}: {step.Replace}",
+ _ => kind,
+ };
+ }
}
diff --git a/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs b/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
index 05284889..b3e70b9f 100644
--- a/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
@@ -334,7 +334,7 @@ public sealed partial class WatchRuleViewModel : ObservableObject
private void RefreshPreview()
{
- RenameSummary = Rule.Renames.Select(r => $"{r.Find} → {(r.Replace.Length == 0 ? _page.Text("watch.recipe_removes") : r.Replace)}").ToList();
+ RenameSummary = Rule.Renames.Select(r => RenameRecipes.Describe(_page.Localizer, r)).ToList();
OnPropertyChanged(nameof(HasRenames));
FileNamePlaceholder = _page.Format("watch.name_placeholder", _page.PresetNamePattern(Rule));
var preview = _page.PreviewOf(Rule);
diff --git a/src/Filee.App/ViewModels/RenameToolViewModel.cs b/src/Filee.App/ViewModels/RenameToolViewModel.cs
index a1bf2271..9952c61f 100644
--- a/src/Filee.App/ViewModels/RenameToolViewModel.cs
+++ b/src/Filee.App/ViewModels/RenameToolViewModel.cs
@@ -29,9 +29,10 @@ public sealed partial class RenameToolViewModel : ObservableObject
_loc = loc;
_rename = rename;
_samples = samples;
+ Kinds = Enum.GetValues<RenameKind>().Select(k => new Choice<RenameKind>(k, loc[$"watch.kind.{k}"])).ToList();
+ Recipes = RenameRecipes.All.Select(r => new RenameRecipeViewModel(r, loc[r.TitleKey], this)).ToList();
foreach (var step in steps)
Steps.Add(new RenameStepViewModel(step.Clone(), this));
- Recipes = RenameRecipes.All.Select(r => new RenameRecipeViewModel(r, loc[r.TitleKey], loc["watch.recipe_removes"], this)).ToList();
_customName = samples.Count == 0 ? loc["watch.sample_file"] : "";
Refresh();
}
@@ -39,7 +40,10 @@ public sealed partial class RenameToolViewModel : ObservableObject
/// <summary>Replacements applied in order.</summary>
public ObservableCollection<RenameStepViewModel> Steps { get; } = [];
- /// <summary>Ready-made replacements, each with what it does to an example name.</summary>
+ /// <summary>What a rule can do, for its drop-down.</summary>
+ public IReadOnlyList<Choice<RenameKind>> Kinds { get; }
+
+ /// <summary>Ready-made rules, each with what it does to an example name.</summary>
public IReadOnlyList<RenameRecipeViewModel> Recipes { get; }
/// <summary>Files from the folder, before and after.</summary>
@@ -58,8 +62,8 @@ public sealed partial class RenameToolViewModel : ObservableObject
/// <summary>True when every step's expression is valid.</summary>
public bool IsValid => Steps.All(s => s.Error is null);
- /// <summary>The steps to keep: the ones with an expression.</summary>
- public List<RenameStep> Result => Steps.Where(s => s.Find.Length > 0).Select(s => s.Step.Clone()).ToList();
+ /// <summary>The rules to keep: the ones that change something.</summary>
+ public List<RenameStep> Result => Steps.Where(s => !s.Step.IsBlank).Select(s => s.Step.Clone()).ToList();
partial void OnCustomNameChanged(string value) => Refresh();
@@ -93,9 +97,11 @@ public sealed partial class RenameToolViewModel : ObservableObject
internal string InvalidRegex(string error) => _loc.Format("watch.invalid_regex", error);
+ internal string Text(string key) => _loc[key];
+
private void Refresh()
{
- var steps = Steps.Select(s => s.Step).Where(s => s.Find.Length > 0).ToList();
+ var steps = Steps.Select(s => s.Step).Where(s => !s.IsBlank).ToList();
Previews.Clear();
foreach (var sample in _samples)
Previews.Add(new RenamePreview(sample, _rename(steps, sample)));
@@ -105,7 +111,7 @@ public sealed partial class RenameToolViewModel : ObservableObject
}
}
-/// <summary>One replacement: a regular expression and what goes in its place.</summary>
+/// <summary>One rule: what it does (<see cref="RenameKind"/>) and the text it needs.</summary>
public sealed partial class RenameStepViewModel : ObservableObject
{
private readonly RenameToolViewModel _tool;
@@ -114,6 +120,7 @@ public sealed partial class RenameStepViewModel : ObservableObject
{
Step = step;
_tool = tool;
+ _kind = tool.Kinds.First(k => k.Value == step.Kind);
_find = step.Find;
_replace = step.Replace;
Validate();
@@ -121,12 +128,56 @@ public sealed partial class RenameStepViewModel : ObservableObject
public RenameStep Step { get; }
+ public IReadOnlyList<Choice<RenameKind>> Kinds => _tool.Kinds;
+
+ [ObservableProperty] private Choice<RenameKind> _kind;
[ObservableProperty] private string _find;
[ObservableProperty] private string _replace;
/// <summary>Why <see cref="Find"/> is not a valid regular expression, or null.</summary>
[ObservableProperty] private string? _error;
+ /// <summary>The kind needs the text to look for.</summary>
+ public bool ShowFind => Kind.Value is RenameKind.Replace or RenameKind.Remove or RenameKind.Regex;
+
+ /// <summary>The kind needs the text that goes in.</summary>
+ public bool ShowReplace => Kind.Value is RenameKind.Replace or RenameKind.Prefix or RenameKind.Suffix or RenameKind.Regex;
+
+ public bool ShowArrow => ShowFind && ShowReplace;
+
+ public bool ShowFindOnly => ShowFind && !ShowReplace;
+
+ public bool ShowReplaceOnly => ShowReplace && !ShowFind;
+
+ public string FindPlaceholder => _tool.Text(Kind.Value switch
+ {
+ RenameKind.Remove => "watch.ph.remove",
+ RenameKind.Regex => "watch.rename_find",
+ _ => "watch.ph.find",
+ });
+
+ public string ReplacePlaceholder => _tool.Text(Kind.Value switch
+ {
+ RenameKind.Prefix => "watch.ph.prefix",
+ RenameKind.Suffix => "watch.ph.suffix",
+ RenameKind.Regex => "watch.rename_replace",
+ _ => "watch.ph.replace",
+ });
+
+ partial void OnKindChanged(Choice<RenameKind> value)
+ {
+ Step.Kind = value.Value;
+ OnPropertyChanged(nameof(ShowFind));
+ OnPropertyChanged(nameof(ShowReplace));
+ OnPropertyChanged(nameof(ShowArrow));
+ OnPropertyChanged(nameof(ShowFindOnly));
+ OnPropertyChanged(nameof(ShowReplaceOnly));
+ OnPropertyChanged(nameof(FindPlaceholder));
+ OnPropertyChanged(nameof(ReplacePlaceholder));
+ Validate();
+ _tool.StepsChanged();
+ }
+
partial void OnFindChanged(string value)
{
Step.Find = value;
@@ -146,21 +197,24 @@ public sealed partial class RenameStepViewModel : ObservableObject
[RelayCommand]
private void MoveUp() => _tool.MoveUp(this);
- private void Validate() => Error = OutputPathResolver.RenameError(Find) is { } error ? _tool.InvalidRegex(error) : null;
+ // Only a regular expression can be wrong; plain text is taken as it is.
+ private void Validate() => Error = Step.Kind == RenameKind.Regex && OutputPathResolver.RenameError(Find) is { } error
+ ? _tool.InvalidRegex(error)
+ : null;
}
-/// <summary>A ready-made replacement in the list: what it does, its expression and an example.</summary>
-public sealed partial class RenameRecipeViewModel(RenameRecipe recipe, string title, string removes, RenameToolViewModel tool) : ObservableObject
+/// <summary>A ready-made rule in the list: what it does and an example.</summary>
+public sealed partial class RenameRecipeViewModel(RenameRecipe recipe, string title, RenameToolViewModel tool) : ObservableObject
{
public string Title { get; } = title;
- /// <summary>"IMG_(\d+) → Photo_$1"; an empty replacement shows as "(removed)".</summary>
- public string Expression { get; } = $"{recipe.Find} → {(recipe.Replace.Length == 0 ? removes : recipe.Replace)}";
-
/// <summary>"IMG_0412 → Photo_0412".</summary>
- public string Example { get; } = $"{recipe.Example} → {OutputPathResolver.Rename(recipe.Example, recipe.Find, recipe.Replace)}";
+ public string Example { get; } = $"{recipe.Example} → {recipe.Step.Apply(recipe.Example)}";
+
+ /// <summary>Marks the one that needs a regular expression.</summary>
+ public bool IsAdvanced { get; } = recipe.Step.Kind == RenameKind.Regex;
- /// <summary>Adds the replacement as the last step (double-click, or the + button).</summary>
+ /// <summary>Adds the rule as the last one (double-click, or the + button).</summary>
[RelayCommand]
- private void Add() => tool.AddStep(new RenameStep { Find = recipe.Find, Replace = recipe.Replace });
+ private void Add() => tool.AddStep(recipe.Step.Clone());
}
diff --git a/src/Filee.App/Views/RenameToolWindow.axaml b/src/Filee.App/Views/RenameToolWindow.axaml
index 9fb22991..6f43b334 100644
--- a/src/Filee.App/Views/RenameToolWindow.axaml
+++ b/src/Filee.App/Views/RenameToolWindow.axaml
@@ -55,9 +55,13 @@
<PathIcon Width="12" Height="12" Data="{StaticResource Icon.Plus}" />
</Button>
<StackPanel Spacing="1">
- <TextBlock FontWeight="SemiBold" Text="{Binding Title}" TextWrapping="Wrap" />
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <TextBlock FontWeight="SemiBold" Text="{Binding Title}" TextWrapping="Wrap" />
+ <Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="4" Padding="5,0" IsVisible="{Binding IsAdvanced}" VerticalAlignment="Center">
+ <TextBlock Classes="caption" Text="{DynamicResource watch.advanced}" />
+ </Border>
+ </StackPanel>
<TextBlock Classes="caption" Text="{Binding Example}" TextWrapping="Wrap" />
- <TextBlock Classes="caption code" Text="{Binding Expression}" TextWrapping="Wrap" Opacity="0.75" />
</StackPanel>
</DockPanel>
</Border>
@@ -83,17 +87,25 @@
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="vm:RenameStepViewModel">
<StackPanel Spacing="2">
- <Grid ColumnDefinitions="*,Auto,*,Auto,Auto">
- <TextBox Text="{Binding Find}" PlaceholderText="{DynamicResource watch.rename_find}" FontFamily="Consolas, Menlo, monospace" />
- <TextBlock Grid.Column="1" Classes="muted" Text="→" Margin="8,0" VerticalAlignment="Center" />
- <TextBox Grid.Column="2" Text="{Binding Replace}" PlaceholderText="{DynamicResource watch.rename_replace}" FontFamily="Consolas, Menlo, monospace" />
- <Button Grid.Column="3" Classes="icon" Margin="6,0,0,0" Command="{Binding MoveUpCommand}" ToolTip.Tip="{DynamicResource watch.step_up}">
- <PathIcon Width="12" Height="12" Data="{StaticResource Icon.ChevronRight}" RenderTransform="rotate(-90deg)" />
- </Button>
- <Button Grid.Column="4" Classes="icon" Margin="2,0,0,0" Command="{Binding RemoveCommand}" ToolTip.Tip="{DynamicResource watch.remove_step}">
+ <DockPanel>
+ <Button DockPanel.Dock="Right" Classes="icon" Margin="2,0,0,0" Command="{Binding RemoveCommand}" ToolTip.Tip="{DynamicResource watch.remove_step}">
<PathIcon Width="12" Height="12" Data="{StaticResource Icon.Close}" />
</Button>
- </Grid>
+ <Button DockPanel.Dock="Right" Classes="icon" Margin="6,0,0,0" Command="{Binding MoveUpCommand}" ToolTip.Tip="{DynamicResource watch.step_up}">
+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.ChevronRight}" RenderTransform="rotate(-90deg)" />
+ </Button>
+ <!-- What the rule does, then only the boxes that kind needs -->
+ <ComboBox DockPanel.Dock="Left" Width="190" Margin="0,0,8,0" ItemsSource="{Binding Kinds}" SelectedItem="{Binding Kind}" />
+ <Panel>
+ <Grid ColumnDefinitions="*,Auto,*" IsVisible="{Binding ShowArrow}">
+ <TextBox Text="{Binding Find}" PlaceholderText="{Binding FindPlaceholder}" />
+ <TextBlock Grid.Column="1" Classes="muted" Text="→" Margin="8,0" VerticalAlignment="Center" />
+ <TextBox Grid.Column="2" Text="{Binding Replace}" PlaceholderText="{Binding ReplacePlaceholder}" />
+ </Grid>
+ <TextBox Text="{Binding Find}" PlaceholderText="{Binding FindPlaceholder}" IsVisible="{Binding ShowFindOnly}" />
+ <TextBox Text="{Binding Replace}" PlaceholderText="{Binding ReplacePlaceholder}" IsVisible="{Binding ShowReplaceOnly}" />
+ </Panel>
+ </DockPanel>
<TextBlock Classes="caption danger" Text="{Binding Error}" TextWrapping="Wrap" IsVisible="{Binding Error, Converter={x:Static ObjectConverters.IsNotNull}}" />
</StackPanel>
</DataTemplate>
diff --git a/src/Filee.Core/Presets/OutputPathResolver.cs b/src/Filee.Core/Presets/OutputPathResolver.cs
index 922c3fba..be779bff 100644
--- a/src/Filee.Core/Presets/OutputPathResolver.cs
+++ b/src/Filee.Core/Presets/OutputPathResolver.cs
@@ -58,7 +58,7 @@ public static class OutputPathResolver
/// <summary>Applies <paramref name="steps"/> to <paramref name="name"/> in order.</summary>
public static string Rename(string name, IEnumerable<RenameStep> steps) =>
- steps.Aggregate(name, (current, step) => Rename(current, step.Find, step.Replace));
+ steps.Aggregate(name, (current, step) => step.Apply(current));
/// <summary>
/// Replaces the regular expression <paramref name="find"/> in <paramref name="name"/>. A pattern that isn't valid
diff --git a/src/Filee.Core/Presets/OutputRule.cs b/src/Filee.Core/Presets/OutputRule.cs
index 65304f2e..735a15fb 100644
--- a/src/Filee.Core/Presets/OutputRule.cs
+++ b/src/Filee.Core/Presets/OutputRule.cs
@@ -64,13 +64,75 @@ public sealed class OutputRule
}
}
-/// <summary>A regular expression replaced in a file name, e.g. <c>IMG_(\d+)</c> → <c>Photo_$1</c>.</summary>
+/// <summary>What a <see cref="RenameStep"/> does to a name.</summary>
+public enum RenameKind
+{
+ /// <summary>Replaces the text <see cref="RenameStep.Find"/> with <see cref="RenameStep.Replace"/> (case ignored).</summary>
+ Replace,
+ /// <summary>Removes the text <see cref="RenameStep.Find"/> (case ignored).</summary>
+ Remove,
+ /// <summary>Puts <see cref="RenameStep.Replace"/> before the name.</summary>
+ Prefix,
+ /// <summary>Puts <see cref="RenameStep.Replace"/> after the name.</summary>
+ Suffix,
+ /// <summary>"my trip photo" → "my_trip_photo".</summary>
+ SpacesToUnderscores,
+ /// <summary>"report (2)" → "report".</summary>
+ RemoveCopyNumber,
+ /// <summary>"song [remix] (live)" → "song".</summary>
+ RemoveBrackets,
+ /// <summary>"01 - intro" → "intro".</summary>
+ RemoveLeadingNumber,
+ /// <summary>"invoice#12@acme!" → "invoice12acme".</summary>
+ RemoveSymbols,
+ Lowercase,
+ Uppercase,
+ /// <summary>Replaces the regular expression <see cref="RenameStep.Find"/> with <see cref="RenameStep.Replace"/> (<c>$1</c> inserts a group).</summary>
+ Regex,
+}
+
+/// <summary>One change to the name of a converted file, e.g. "replace IMG_ with Photo_" or "spaces to underscores".</summary>
public sealed class RenameStep
{
+ private static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(250);
+
+ public RenameKind Kind { get; set; } = RenameKind.Replace;
+
+ /// <summary>The text (or, for <see cref="RenameKind.Regex"/>, the expression) looked for.</summary>
public string Find { get; set; } = "";
- /// <summary>What <see cref="Find"/> is replaced with; <c>$1</c> inserts the first group.</summary>
+ /// <summary>What goes in its place, or the text added by <see cref="RenameKind.Prefix"/> and <see cref="RenameKind.Suffix"/>.</summary>
public string Replace { get; set; } = "";
+ /// <summary>True for a step that changes nothing because its text is still missing.</summary>
+ public bool IsBlank => Kind switch
+ {
+ RenameKind.Replace or RenameKind.Remove or RenameKind.Regex => Find.Length == 0,
+ RenameKind.Prefix or RenameKind.Suffix => Replace.Length == 0,
+ _ => false,
+ };
+
+ /// <summary>The name after this step. A regular expression that isn't valid leaves it as it is.</summary>
+ public string Apply(string name) => Kind switch
+ {
+ _ when IsBlank => name,
+ RenameKind.Replace => name.Replace(Find, Replace, StringComparison.OrdinalIgnoreCase),
+ RenameKind.Remove => name.Replace(Find, "", StringComparison.OrdinalIgnoreCase),
+ RenameKind.Prefix => Replace + name,
+ RenameKind.Suffix => name + Replace,
+ RenameKind.SpacesToUnderscores => Fixed(name, @"\s+", "_"),
+ RenameKind.RemoveCopyNumber => Fixed(name, @"\s*\(\d+\)$", ""),
+ RenameKind.RemoveBrackets => Fixed(name, @"\s*(\([^)]*\)|\[[^\]]*\]|\{[^}]*\})", "").Trim(),
+ RenameKind.RemoveLeadingNumber => Fixed(name, @"^\d+[\s._-]*", ""),
+ RenameKind.RemoveSymbols => Fixed(name, @"[^\p{L}\p{N}\s._-]", ""),
+ RenameKind.Lowercase => name.ToLowerInvariant(),
+ RenameKind.Uppercase => name.ToUpperInvariant(),
+ RenameKind.Regex => OutputPathResolver.Rename(name, Find, Replace),
+ _ => name,
+ };
+
public RenameStep Clone() => (RenameStep)MemberwiseClone();
+
+ private static string Fixed(string name, string pattern, string replacement) =>
+ System.Text.RegularExpressions.Regex.Replace(name, pattern, replacement, System.Text.RegularExpressions.RegexOptions.CultureInvariant, Timeout);
}
diff --git a/src/Filee.Core/Watching/WatchRule.cs b/src/Filee.Core/Watching/WatchRule.cs
index 37f096e1..d134e876 100644
--- a/src/Filee.Core/Watching/WatchRule.cs
+++ b/src/Filee.Core/Watching/WatchRule.cs
@@ -70,7 +70,7 @@ public sealed class WatchRule
if (!string.IsNullOrWhiteSpace(FileNamePattern))
applied.Output.FileNamePattern = FileNamePattern.Trim();
// Steps without a pattern are being typed; leaving them out keeps the name as it is.
- applied.Output.Renames.AddRange(Renames.Where(r => r.Find.Length > 0).Select(r => r.Clone()));
+ applied.Output.Renames.AddRange(Renames.Where(r => !r.IsBlank).Select(r => r.Clone()));
return applied;
}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index b69be987..b13f9ebc 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -118,17 +118,26 @@ public class RenderTests
// The rename window works on copies: a ready-made replacement becomes a rule, the preview follows.
var tool = item.CreateRenameTool();
- tool.Recipes[0].AddCommand.Execute(null); // camera number → Photo_number
+ tool.Recipes[0].AddCommand.Execute(null); // change IMG_ to Photo_
Assert.Empty(rule.Renames); // nothing changes before saving
Assert.Equal(new Filee.App.ViewModels.RenamePreview("IMG_0412.jpg", "Photo_0412_scan.pdf"), Assert.Single(tool.Previews));
- tool.CustomName = "DSC_0815.heic";
+ tool.CustomName = "img_0815.heic";
Assert.Equal("Photo_0815_scan.pdf", tool.CustomResult);
- var step = tool.Steps[0];
- step.Find = "IMG_(";
- Assert.NotNull(step.Error);
+
+ // Plain text is never "wrong"; only the advanced kind checks its expression.
+ tool.AddStepCommand.Execute(null);
+ var extra = tool.Steps[1];
+ extra.Find = "(";
+ Assert.Null(extra.Error);
+ extra.Kind = tool.Kinds.First(k => k.Value == Filee.Core.Presets.RenameKind.Regex);
+ Assert.NotNull(extra.Error);
Assert.False(tool.IsValid);
- step.Find = @"^(?:IMG|DSC|PXL)_(\d+)";
+ extra.Kind = tool.Kinds.First(k => k.Value == Filee.Core.Presets.RenameKind.Suffix);
+ Assert.True(extra.ShowReplaceOnly);
+ extra.Replace = "_v2";
Assert.True(tool.IsValid);
+ Assert.Equal("Photo_0412_scan_v2.pdf", tool.Previews[0].After);
+ extra.RemoveCommand.Execute(null);
var dialog = new Filee.App.Views.RenameToolWindow { DataContext = tool };
dialog.Show();
Pump();
@@ -136,7 +145,7 @@ public class RenderTests
dialog.Close();
item.SetRenames(tool.Result); // saved
- Assert.Equal(@"^(?:IMG|DSC|PXL)_(\d+)", Assert.Single(rule.Renames).Find);
+ Assert.Equal("IMG_", Assert.Single(rule.Renames).Find);
// A file already in the folder that the patterns let through, renamed by the name rule and the rule.
Assert.Equal($"IMG_0412.jpg → {Path.Combine("converted", "Photo_0412_scan.pdf")}", item.PreviewExample);
Pump();
diff --git a/tests/Filee.Core.Tests/WatchRuleOptionsTests.cs b/tests/Filee.Core.Tests/WatchRuleOptionsTests.cs
index cd259969..2c5110c3 100644
--- a/tests/Filee.Core.Tests/WatchRuleOptionsTests.cs
+++ b/tests/Filee.Core.Tests/WatchRuleOptionsTests.cs
@@ -76,7 +76,7 @@ public class WatchRuleOptionsTests
{
Folder = "Inbox",
FileNamePattern = "{name}_{date}",
- Renames = [new() { Find = @"IMG_(\d+)", Replace = "Photo_$1" }, new() { Find = "", Replace = "typing" }],
+ Renames = [new() { Kind = RenameKind.Regex, Find = @"IMG_(\d+)", Replace = "Photo_$1" }, new() { Find = "", Replace = "typing" }],
};
var own = rule.Apply(preset);
Assert.Equal("{name}_{date}", own.Output.FileNamePattern);
@@ -91,7 +91,7 @@ public class WatchRuleOptionsTests
var rule = new OutputRule
{
Location = OutputLocation.SameFolder,
- Renames = [new() { Find = @"IMG_(\d+)", Replace = "Photo $1" }, new() { Find = @"\s+", Replace = "_" }],
+ Renames = [new() { Find = "img_", Replace = "Photo " }, new() { Kind = RenameKind.SpacesToUnderscores }],
};
var source = Path.Combine(Path.GetTempPath(), "IMG_0412.heic");
@@ -100,6 +100,26 @@ public class WatchRuleOptionsTests
Assert.Equal(Path.Combine(Path.GetTempPath(), "Photo_0412.jpg"), path);
}
+ [Theory]
+ [InlineData(RenameKind.Replace, "IMG_", "Photo_", "IMG_0412", "Photo_0412")]
+ [InlineData(RenameKind.Remove, "_copy", "", "report_COPY", "report")]
+ [InlineData(RenameKind.Prefix, "", "2026_", "report", "2026_report")]
+ [InlineData(RenameKind.Suffix, "", "_final", "report", "report_final")]
+ [InlineData(RenameKind.SpacesToUnderscores, "", "", "trip to busan", "trip_to_busan")]
+ [InlineData(RenameKind.RemoveCopyNumber, "", "", "report (2)", "report")]
+ [InlineData(RenameKind.RemoveBrackets, "", "", "song [remix] (live)", "song")]
+ [InlineData(RenameKind.RemoveLeadingNumber, "", "", "01 - intro", "intro")]
+ [InlineData(RenameKind.RemoveSymbols, "", "", "invoice#12@acme!", "invoice12acme")]
+ [InlineData(RenameKind.RemoveSymbols, "", "", "보고서#1", "보고서1")]
+ [InlineData(RenameKind.Lowercase, "", "", "Report_FINAL", "report_final")]
+ [InlineData(RenameKind.Uppercase, "", "", "report", "REPORT")]
+ [InlineData(RenameKind.Regex, @"(\d{4})(\d{2})(\d{2})", "$1-$2-$3", "scan_20261011", "scan_2026-10-11")]
+ [InlineData(RenameKind.Replace, "", "x", "report", "report")] // still being typed: no change
+ public void Each_kind_of_rule_changes_the_name_as_it_says(RenameKind kind, string find, string replace, string name, string expected)
+ {
+ Assert.Equal(expected, new RenameStep { Kind = kind, Find = find, Replace = replace }.Apply(name));
+ }
+
[Fact]
public void A_rename_pattern_that_is_not_valid_leaves_the_name_as_it_is()
{