]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
e9a462a8759cf9ce42d26278e92dec4c34db5182
[lyx.git] / src / lyxfind.cpp
1 /**
2  * \file lyxfind.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jürgen Vigna
9  * \author Alfredo Braunstein
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "lyxfind.h"
17
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "Cursor.h"
21 #include "CutAndPaste.h"
22 #include "buffer_funcs.h"
23 #include "BufferView.h"
24 #include "Changes.h"
25 #include "support/debug.h"
26 #include "FuncRequest.h"
27 #include "support/gettext.h"
28 #include "Text.h"
29 #include "Paragraph.h"
30 #include "ParIterator.h"
31
32 #include "frontends/alert.h"
33
34 #include "support/convert.h"
35 #include "support/docstream.h"
36 #include "support/lstrings.h"
37
38 namespace lyx {
39
40 using support::compare_no_case;
41 using support::uppercase;
42 using support::split;
43
44 using std::advance;
45
46
47 namespace {
48
49 bool parse_bool(docstring & howto)
50 {
51         if (howto.empty())
52                 return false;
53         docstring var;
54         howto = split(howto, var, ' ');
55         return (var == "1");
56 }
57
58
59 class MatchString : public std::binary_function<Paragraph, pos_type, bool>
60 {
61 public:
62         MatchString(docstring const & str, bool cs, bool mw)
63                 : str(str), cs(cs), mw(mw)
64         {}
65
66         // returns true if the specified string is at the specified position
67         // del specifies whether deleted strings in ct mode will be considered
68         bool operator()(Paragraph const & par, pos_type pos, bool del = true) const
69         {
70                 return par.find(str, cs, mw, pos, del);
71         }
72
73 private:
74         // search string
75         docstring str;
76         // case sensitive
77         bool cs;
78         // match whole words only
79         bool mw;
80 };
81
82
83 bool findForward(DocIterator & cur, MatchString const & match,
84                  bool find_del = true)
85 {
86         for (; cur; cur.forwardChar())
87                 if (cur.inTexted() &&
88                     match(cur.paragraph(), cur.pos(), find_del))
89                         return true;
90         return false;
91 }
92
93
94 bool findBackwards(DocIterator & cur, MatchString const & match,
95                  bool find_del = true)
96 {
97         while (cur) {
98                 cur.backwardChar();
99                 if (cur.inTexted() &&
100                     match(cur.paragraph(), cur.pos(), find_del))
101                         return true;
102         }
103         return false;
104 }
105
106
107 bool findChange(DocIterator & cur)
108 {
109         for (; cur; cur.forwardPos())
110                 if (cur.inTexted() && !cur.paragraph().isUnchanged(cur.pos()))
111                         return true;
112         return false;
113 }
114
115
116 bool searchAllowed(BufferView * /*bv*/, docstring const & str)
117 {
118         if (str.empty()) {
119                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
120                 return false;
121         }
122         return true;
123 }
124
125
126 bool find(BufferView * bv, docstring const & searchstr,
127         bool cs, bool mw, bool fw, bool find_del = true)
128 {
129         if (!searchAllowed(bv, searchstr))
130                 return false;
131
132         DocIterator cur = bv->cursor();
133
134         MatchString const match(searchstr, cs, mw);
135
136         bool found = fw ? findForward(cur, match, find_del) :
137                           findBackwards(cur, match, find_del);
138
139         if (found)
140                 bv->putSelectionAt(cur, searchstr.length(), !fw);
141
142         return found;
143 }
144
145
146 int replaceAll(BufferView * bv,
147                docstring const & searchstr, docstring const & replacestr,
148                bool cs, bool mw)
149 {
150         Buffer & buf = bv->buffer();
151
152         if (!searchAllowed(bv, searchstr) || buf.isReadonly())
153                 return 0;
154
155         bv->cursor().recordUndoFullDocument();
156
157         MatchString const match(searchstr, cs, mw);
158         int num = 0;
159
160         int const rsize = replacestr.size();
161         int const ssize = searchstr.size();
162
163         DocIterator cur = doc_iterator_begin(buf.inset());
164         while (findForward(cur, match, false)) {
165                 pos_type pos = cur.pos();
166                 Font const font
167                         = cur.paragraph().getFontSettings(buf.params(), pos);
168                 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
169                                                             buf.params().trackChanges);
170                 cur.paragraph().insert(pos, replacestr, font,
171                                        Change(buf.params().trackChanges ?
172                                               Change::INSERTED : Change::UNCHANGED));
173                 for (int i = 0; i < rsize + striked; ++i)
174                         cur.forwardChar();
175                 ++num;
176         }
177
178         updateLabels(buf);
179         bv->putSelectionAt(doc_iterator_begin(buf.inset()), 0, false);
180         if (num)
181                 buf.markDirty();
182         return num;
183 }
184
185
186 bool stringSelected(BufferView * bv, docstring const & searchstr,
187                     bool cs, bool mw, bool fw)
188 {
189         // if nothing selected or selection does not equal search
190         // string search and select next occurance and return
191         docstring const & str1 = searchstr;
192         docstring const str2 = bv->cursor().selectionAsString(false);
193         if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
194                 find(bv, searchstr, cs, mw, fw);
195                 return false;
196         }
197
198         return true;
199 }
200
201
202 int replace(BufferView * bv, docstring const & searchstr,
203             docstring const & replacestr, bool cs, bool mw, bool fw)
204 {
205         if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
206                 return 0;
207
208         if (!stringSelected(bv, searchstr, cs, mw, fw))
209                 return 0;
210
211         Cursor & cur = bv->cursor();
212         cap::replaceSelectionWithString(cur, replacestr, fw);
213         bv->buffer().markDirty();
214         find(bv, searchstr, cs, mw, fw, false);
215         bv->processUpdateFlags(Update::Force | Update::FitCursor);
216
217         return 1;
218 }
219
220 } // namespace anon
221
222
223 docstring const find2string(docstring const & search,
224                          bool casesensitive, bool matchword, bool forward)
225 {
226         odocstringstream ss;
227         ss << search << '\n'
228            << int(casesensitive) << ' '
229            << int(matchword) << ' '
230            << int(forward);
231         return ss.str();
232 }
233
234
235 docstring const replace2string(docstring const & search, docstring const & replace,
236                             bool casesensitive, bool matchword,
237                             bool all, bool forward)
238 {
239         odocstringstream ss;
240         ss << search << '\n'
241            << replace << '\n'
242            << int(casesensitive) << ' '
243            << int(matchword) << ' '
244            << int(all) << ' '
245            << int(forward);
246         return ss.str();
247 }
248
249
250 void find(BufferView * bv, FuncRequest const & ev)
251 {
252         if (!bv || ev.action != LFUN_WORD_FIND)
253                 return;
254
255         //lyxerr << "find called, cmd: " << ev << std::endl;
256
257         // data is of the form
258         // "<search>
259         //  <casesensitive> <matchword> <forward>"
260         docstring search;
261         docstring howto = split(ev.argument(), search, '\n');
262
263         bool casesensitive = parse_bool(howto);
264         bool matchword     = parse_bool(howto);
265         bool forward       = parse_bool(howto);
266
267         bool const found = find(bv, search,
268                                   casesensitive, matchword, forward);
269
270         if (!found)
271                 // emit message signal.
272                 bv->message(_("String not found!"));
273 }
274
275
276 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
277 {
278         if (!bv || ev.action != LFUN_WORD_REPLACE)
279                 return;
280
281         // data is of the form
282         // "<search>
283         //  <replace>
284         //  <casesensitive> <matchword> <all> <forward>"
285         docstring search;
286         docstring rplc;
287         docstring howto = split(ev.argument(), search, '\n');
288         howto = split(howto, rplc, '\n');
289
290         bool casesensitive = parse_bool(howto);
291         bool matchword     = parse_bool(howto);
292         bool all           = parse_bool(howto);
293         bool forward       = parse_bool(howto);
294
295         if (!has_deleted) {
296                 int const replace_count = all
297                         ? replaceAll(bv, search, rplc, casesensitive, matchword)
298                         : replace(bv, search, rplc, casesensitive, matchword, forward);
299         
300                 Buffer & buf = bv->buffer();
301                 if (replace_count == 0) {
302                         // emit message signal.
303                         buf.message(_("String not found!"));
304                 } else {
305                         if (replace_count == 1) {
306                                 // emit message signal.
307                                 buf.message(_("String has been replaced."));
308                         } else {
309                                 docstring str = convert<docstring>(replace_count);
310                                 str += _(" strings have been replaced.");
311                                 // emit message signal.
312                                 buf.message(str);
313                         }
314                 }
315         } else {
316                 // if we have deleted characters, we do not replace at all, but
317                 // rather search for the next occurence
318                 bool const found = find(bv, search,
319                                         casesensitive, matchword, forward);
320
321                 if (!found)
322                         // emit message signal.
323                         bv->message(_("String not found!"));
324         }
325 }
326
327
328 bool findNextChange(BufferView * bv)
329 {
330         DocIterator cur = bv->cursor();
331
332         if (!findChange(cur))
333                 return false;
334
335         bv->cursor().setCursor(cur);
336         bv->cursor().resetAnchor();
337
338         Change orig_change = cur.paragraph().lookupChange(cur.pos());
339
340         CursorSlice & tip = cur.top();
341         for (; !tip.at_end(); tip.forwardPos()) {
342                 Change change = tip.paragraph().lookupChange(tip.pos());
343                 if (change != orig_change)
344                         break;
345         }
346         // avoid crash (assertion violation) if the imaginary end-of-par
347         // character of the last paragraph of the document is marked as changed
348         if (tip.at_end())
349                 tip.backwardPos();
350
351         // Now put cursor to end of selection:
352         bv->cursor().setCursor(cur);
353         bv->cursor().setSelection();
354
355         return true;
356 }
357
358 } // lyx namespace