1 // Copyright (c) 2013, Thomas Goyne <plorkyeran@aegisub.org>
2 //
3 // Permission to use, copy, modify, and distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 //
15 // Aegisub Project http://www.aegisub.org/
16 
17 #include <functional>
18 #include <boost/regex/icu.hpp>
19 #include <string>
20 
21 namespace agi { struct Context; }
22 class AssDialogue;
23 
24 struct MatchState {
25 	boost::u32regex *re;
26 	size_t start, end;
27 
28 	operator bool() const { return end != (size_t)-1; }
29 };
30 
31 struct SearchReplaceSettings {
32 	enum class Field {
33 		TEXT = 0,
34 		STYLE,
35 		ACTOR,
36 		EFFECT
37 	};
38 
39 	enum class Limit {
40 		ALL = 0,
41 		SELECTED
42 	};
43 
44 	std::string find;
45 	std::string replace_with;
46 
47 	Field field;
48 	Limit limit_to;
49 
50 	bool match_case;
51 	bool use_regex;
52 	bool ignore_comments;
53 	bool skip_tags;
54 	bool exact_match;
55 };
56 
57 class SearchReplaceEngine {
58 	agi::Context *context;
59 	bool initialized = false;
60 	SearchReplaceSettings settings;
61 
62 	bool FindReplace(bool replace);
63 	void Replace(AssDialogue *line, MatchState &ms);
64 
65 public:
FindNext()66 	bool FindNext() { return FindReplace(false); }
ReplaceNext()67 	bool ReplaceNext() { return FindReplace(true); }
68 	bool ReplaceAll();
69 
70 	void Configure(SearchReplaceSettings const& new_settings);
71 
72 	static std::function<MatchState (const AssDialogue*, size_t)> GetMatcher(SearchReplaceSettings const& settings);
73 
74 	SearchReplaceEngine(agi::Context *c);
75 };
76