summaryrefslogtreecommitdiffstats
path: root/comm/mail/components/compose/content/dialogs/EdReplace.js
blob: c937702416d3079a149c8b85269245ed24689653 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* import-globals-from ../editorUtilities.js */
/* import-globals-from EdDialogCommon.js */

var gReplaceDialog; // Quick access to document/form elements.
var gFindInst; // nsIWebBrowserFind that we're going to use
var gFindService; // Global service which remembers find params
var gEditor; // the editor we're using

document.addEventListener("dialogaccept", event => {
  onFindNext();
  event.preventDefault();
});

function initDialogObject() {
  // Create gReplaceDialog object and initialize.
  gReplaceDialog = {};
  gReplaceDialog.findInput = document.getElementById("dialog.findInput");
  gReplaceDialog.replaceInput = document.getElementById("dialog.replaceInput");
  gReplaceDialog.caseSensitive = document.getElementById(
    "dialog.caseSensitive"
  );
  gReplaceDialog.wrap = document.getElementById("dialog.wrap");
  gReplaceDialog.searchBackwards = document.getElementById(
    "dialog.searchBackwards"
  );
  gReplaceDialog.findNext = document.getElementById("findNext");
  gReplaceDialog.replace = document.getElementById("replace");
  gReplaceDialog.replaceAndFind = document.getElementById("replaceAndFind");
  gReplaceDialog.replaceAll = document.getElementById("replaceAll");
}

function loadDialog() {
  // Set initial dialog field contents.
  // Set initial dialog field contents. Use the gFindInst attributes first,
  // this is necessary for window.find()
  gReplaceDialog.findInput.value = gFindInst.searchString
    ? gFindInst.searchString
    : gFindService.searchString;
  gReplaceDialog.replaceInput.value = gFindService.replaceString;
  gReplaceDialog.caseSensitive.checked = gFindInst.matchCase
    ? gFindInst.matchCase
    : gFindService.matchCase;
  gReplaceDialog.wrap.checked = gFindInst.wrapFind
    ? gFindInst.wrapFind
    : gFindService.wrapFind;
  gReplaceDialog.searchBackwards.checked = gFindInst.findBackwards
    ? gFindInst.findBackwards
    : gFindService.findBackwards;

  doEnabling();
}

function onLoad() {
  // Get the xul <editor> element:
  var editorElement = window.arguments[0];

  // If we don't get the editor, then we won't allow replacing.
  gEditor = editorElement.getEditor(editorElement.contentWindow);
  if (!gEditor) {
    window.close();
    return;
  }

  // Get the nsIWebBrowserFind service:
  gFindInst = editorElement.webBrowserFind;

  try {
    // get the find service, which stores global find state
    gFindService = Cc["@mozilla.org/find/find_service;1"].getService(
      Ci.nsIFindService
    );
  } catch (e) {
    dump("No find service!\n");
    gFindService = 0;
  }

  // Init gReplaceDialog.
  initDialogObject();

  // Change "OK" to "Find".
  // dialog.find.label = document.getElementById("fBLT").getAttribute("label");

  // Fill dialog.
  loadDialog();

  if (gReplaceDialog.findInput.value) {
    gReplaceDialog.findInput.select();
  } else {
    gReplaceDialog.findInput.focus();
  }
}

function saveFindData() {
  // Set data attributes per user input.
  if (gFindService) {
    gFindService.searchString = gReplaceDialog.findInput.value;
    gFindService.matchCase = gReplaceDialog.caseSensitive.checked;
    gFindService.wrapFind = gReplaceDialog.wrap.checked;
    gFindService.findBackwards = gReplaceDialog.searchBackwards.checked;
  }
}

function setUpFindInst() {
  gFindInst.searchString = gReplaceDialog.findInput.value;
  gFindInst.matchCase = gReplaceDialog.caseSensitive.checked;
  gFindInst.wrapFind = gReplaceDialog.wrap.checked;
  gFindInst.findBackwards = gReplaceDialog.searchBackwards.checked;
}

function onFindNext() {
  // Transfer dialog contents to the find service.
  saveFindData();
  // set up the find instance
  setUpFindInst();

  // Search.
  var result = gFindInst.findNext();

  if (!result) {
    var bundle = document.getElementById("findBundle");
    Services.prompt.alert(
      window,
      GetString("Alert"),
      bundle.getString("notFoundWarning")
    );
    SetTextboxFocus(gReplaceDialog.findInput);
    gReplaceDialog.findInput.select();
    gReplaceDialog.findInput.focus();
    return false;
  }
  return true;
}

function onReplace() {
  if (!gEditor) {
    return false;
  }

  // Does the current selection match the find string?
  var selection = gEditor.selection;

  var selStr = selection.toString();
  var specStr = gReplaceDialog.findInput.value;
  if (!gReplaceDialog.caseSensitive.checked) {
    selStr = selStr.toLowerCase();
    specStr = specStr.toLowerCase();
  }
  // Unfortunately, because of whitespace we can't just check
  // whether (selStr == specStr), but have to loop ourselves.
  // N chars of whitespace in specStr can match any M >= N in selStr.
  var matches = true;
  var specLen = specStr.length;
  var selLen = selStr.length;
  if (selLen < specLen) {
    matches = false;
  } else {
    var specArray = specStr.match(/\S+|\s+/g);
    var selArray = selStr.match(/\S+|\s+/g);
    if (specArray.length != selArray.length) {
      matches = false;
    } else {
      for (var i = 0; i < selArray.length; i++) {
        if (selArray[i] != specArray[i]) {
          if (/\S/.test(selArray[i][0]) || /\S/.test(specArray[i][0])) {
            // not a space chunk -- match fails
            matches = false;
            break;
          } else if (selArray[i].length < specArray[i].length) {
            // if it's a space chunk then we only care that sel be
            // at least as long as spec
            matches = false;
            break;
          }
        }
      }
    }
  }

  // If the current selection doesn't match the pattern,
  // then we want to find the next match, but not do the replace.
  // That's what most other apps seem to do.
  // So here, just return.
  if (!matches) {
    return false;
  }

  // Transfer dialog contents to the find service.
  saveFindData();

  // For reverse finds, need to remember the caret position
  // before current selection
  var newRange;
  if (gReplaceDialog.searchBackwards.checked && selection.rangeCount > 0) {
    newRange = selection.getRangeAt(0).cloneRange();
    newRange.collapse(true);
  }

  // nsPlaintextEditor::InsertText fails if the string is empty,
  // so make that a special case:
  var replStr = gReplaceDialog.replaceInput.value;
  if (replStr == "") {
    gEditor.deleteSelection(gEditor.eNone, gEditor.eStrip);
  } else {
    gEditor.insertText(replStr);
  }

  // For reverse finds, need to move caret just before the replaced text
  if (gReplaceDialog.searchBackwards.checked && newRange) {
    gEditor.selection.removeAllRanges();
    gEditor.selection.addRange(newRange);
  }

  return true;
}

function onReplaceAll() {
  if (!gEditor) {
    return;
  }

  var findStr = gReplaceDialog.findInput.value;
  var repStr = gReplaceDialog.replaceInput.value;

  // Transfer dialog contents to the find service.
  saveFindData();

  var finder = Cc["@mozilla.org/embedcomp/rangefind;1"]
    .createInstance()
    .QueryInterface(Ci.nsIFind);

  finder.caseSensitive = gReplaceDialog.caseSensitive.checked;
  finder.findBackwards = gReplaceDialog.searchBackwards.checked;

  // We want the whole operation to be undoable in one swell foop,
  // so start a transaction:
  gEditor.beginTransaction();

  // and to make sure we close the transaction, guard against exceptions:
  try {
    // Make a range containing the current selection,
    // so we don't go past it when we wrap.
    var selection = gEditor.selection;
    var selecRange;
    if (selection.rangeCount > 0) {
      selecRange = selection.getRangeAt(0);
    }
    var origRange = selecRange.cloneRange();

    // We'll need a range for the whole document:
    var wholeDocRange = gEditor.document.createRange();
    var rootNode = gEditor.rootElement;
    wholeDocRange.selectNodeContents(rootNode);

    // And start and end points:
    var endPt = gEditor.document.createRange();

    if (gReplaceDialog.searchBackwards.checked) {
      endPt.setStart(wholeDocRange.startContainer, wholeDocRange.startOffset);
      endPt.setEnd(wholeDocRange.startContainer, wholeDocRange.startOffset);
    } else {
      endPt.setStart(wholeDocRange.endContainer, wholeDocRange.endOffset);
      endPt.setEnd(wholeDocRange.endContainer, wholeDocRange.endOffset);
    }

    // Find and replace from here to end (start) of document:
    var foundRange;
    var searchRange = wholeDocRange.cloneRange();
    while (
      (foundRange = finder.Find(findStr, searchRange, selecRange, endPt)) !=
      null
    ) {
      gEditor.selection.removeAllRanges();
      gEditor.selection.addRange(foundRange);

      // The editor will leave the caret at the end of the replaced text.
      // For reverse finds, we need it at the beginning,
      // so save the next position now.
      if (gReplaceDialog.searchBackwards.checked) {
        selecRange = foundRange.cloneRange();
        selecRange.setEnd(selecRange.startContainer, selecRange.startOffset);
      }

      // nsPlaintextEditor::InsertText fails if the string is empty,
      // so make that a special case:
      if (repStr == "") {
        gEditor.deleteSelection(gEditor.eNone, gEditor.eStrip);
      } else {
        gEditor.insertText(repStr);
      }

      // If we're going forward, we didn't save selecRange before, so do it now:
      if (!gReplaceDialog.searchBackwards.checked) {
        selection = gEditor.selection;
        if (selection.rangeCount <= 0) {
          gEditor.endTransaction();
          return;
        }
        selecRange = selection.getRangeAt(0).cloneRange();
      }
    }

    // If no wrapping, then we're done
    if (!gReplaceDialog.wrap.checked) {
      gEditor.endTransaction();
      return;
    }

    // If wrapping, find from start/end of document back to start point.
    if (gReplaceDialog.searchBackwards.checked) {
      // Collapse origRange to end
      origRange.setStart(origRange.endContainer, origRange.endOffset);
      // Set current position to document end
      selecRange.setEnd(wholeDocRange.endContainer, wholeDocRange.endOffset);
      selecRange.setStart(wholeDocRange.endContainer, wholeDocRange.endOffset);
    } else {
      // Collapse origRange to start
      origRange.setEnd(origRange.startContainer, origRange.startOffset);
      // Set current position to document start
      selecRange.setStart(
        wholeDocRange.startContainer,
        wholeDocRange.startOffset
      );
      selecRange.setEnd(
        wholeDocRange.startContainer,
        wholeDocRange.startOffset
      );
    }

    while (
      (foundRange = finder.Find(
        findStr,
        wholeDocRange,
        selecRange,
        origRange
      )) != null
    ) {
      gEditor.selection.removeAllRanges();
      gEditor.selection.addRange(foundRange);

      // Save insert point for backward case
      if (gReplaceDialog.searchBackwards.checked) {
        selecRange = foundRange.cloneRange();
        selecRange.setEnd(selecRange.startContainer, selecRange.startOffset);
      }

      // nsPlaintextEditor::InsertText fails if the string is empty,
      // so make that a special case:
      if (repStr == "") {
        gEditor.deleteSelection(gEditor.eNone, gEditor.eStrip);
      } else {
        gEditor.insertText(repStr);
      }

      // Get insert point for forward case
      if (!gReplaceDialog.searchBackwards.checked) {
        selection = gEditor.selection;
        if (selection.rangeCount <= 0) {
          gEditor.endTransaction();
          return;
        }
        selecRange = selection.getRangeAt(0);
      }
    }
  } catch (e) {}

  gEditor.endTransaction();
}

function doEnabling() {
  var findStr = gReplaceDialog.findInput.value;
  gReplaceDialog.enabled = findStr;
  gReplaceDialog.findNext.disabled = !findStr;
  gReplaceDialog.replace.disabled = !findStr;
  gReplaceDialog.replaceAndFind.disabled = !findStr;
  gReplaceDialog.replaceAll.disabled = !findStr;
}