This repository was archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Expand file tree
/
Copy pathFindInFiles.js
More file actions
444 lines (377 loc) · 18 KB
/
FindInFiles.js
File metadata and controls
444 lines (377 loc) · 18 KB
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, PathUtils, window */
/*
* Adds a "find in files" command to allow the user to find all occurances of a string in all files in
* the project.
*
* The keyboard shortcut is Cmd(Ctrl)-Shift-F.
*
* FUTURE:
* - Proper UI for both dialog and results
* - Refactor dialog class and share with Quick File Open
* - Search files in working set that are *not* in the project
* - Handle matches that span mulitple lines
* - Refactor UI from functionality to enable unit testing
*/
define(function (require, exports, module) {
"use strict";
var Async = require("utils/Async"),
CommandManager = require("command/CommandManager"),
Commands = require("command/Commands"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils"),
ProjectManager = require("project/ProjectManager"),
DocumentManager = require("document/DocumentManager"),
EditorManager = require("editor/EditorManager"),
FileIndexManager = require("project/FileIndexManager"),
KeyEvent = require("utils/KeyEvent"),
AppInit = require("utils/AppInit"),
StatusBar = require("widgets/StatusBar");
var searchResults = [];
var FIND_IN_FILES_MAX = 100,
maxHitsFoundInFile = false;
function _getQueryRegExp(query) {
// Clear any pending RegEx error message
$(".CodeMirror-dialog .alert-message").remove();
// If query is a regular expression, use it directly
var isRE = query.match(/^\/(.*)\/(g|i)*$/);
if (isRE) {
// Make sure the 'g' flag is set
var flags = isRE[2] || "g";
if (flags.search("g") === -1) {
flags += "g";
}
try {
return new RegExp(isRE[1], flags);
} catch (e) {
$(".CodeMirror-dialog div").append("<div class='alert-message' style='margin-bottom: 0'>" + e.message + "</div>");
return null;
}
}
// Query is a string. Turn it into a case-insensitive regexp
// Escape regex special chars
query = StringUtils.regexEscape(query);
return new RegExp(query, "gi");
}
/**
* Returns label text to indicate the search scope
* @param {?Entry} scope
*/
function _labelForScope(scope) {
var projName = ProjectManager.getProjectRoot().name;
if (scope) {
return StringUtils.format(Strings.FIND_IN_FILES_SCOPED, projName + "/" + ProjectManager.makeProjectRelativeIfPossible(scope.fullPath));
} else {
return StringUtils.format(Strings.FIND_IN_FILES_NO_SCOPE, projName);
}
}
// This dialog class was mostly copied from QuickOpen. We should have a common dialog
// class that everyone can use.
/**
* FindInFilesDialog class
* @constructor
*
*/
function FindInFilesDialog() {
this.closed = false;
this.result = null; // $.Deferred
}
/**
* Creates a dialog div floating on top of the current code mirror editor
*/
FindInFilesDialog.prototype._createDialogDiv = function (template) {
this.dialog = $("<div />")
.attr("class", "CodeMirror-dialog")
.html("<div>" + template + "</div>")
.prependTo($("#editor-holder"));
};
/**
* Closes the search dialog and resolves the promise that showDialog returned
*/
FindInFilesDialog.prototype._close = function (value) {
if (this.closed) {
return;
}
this.closed = true;
this.dialog.remove();
EditorManager.focusEditor();
this.result.resolve(value);
};
/**
* Shows the search dialog
* @param {?string} initialString Default text to prepopulate the search field with
* @param {?Entry} scope Search scope, or null to search whole proj
* @returns {$.Promise} that is resolved with the string to search for
*/
FindInFilesDialog.prototype.showDialog = function (initialString, scope) {
var dialogHTML = Strings.CMD_FIND_IN_FILES +
": <input type='text' id='findInFilesInput' style='width: 10em'> <span id='findInFilesScope'></span> " +
"<span style='color: #888'>(" + Strings.SEARCH_REGEXP_INFO + ")</span>";
this.result = new $.Deferred();
this._createDialogDiv(dialogHTML);
var $searchField = $("input#findInFilesInput");
var that = this;
$searchField.attr("value", initialString || "");
$searchField.get(0).select();
$("#findInFilesScope").text(_labelForScope(scope));
$searchField.bind("keydown", function (event) {
if (event.keyCode === KeyEvent.DOM_VK_RETURN || event.keyCode === KeyEvent.DOM_VK_ESCAPE) { // Enter/Return key or Esc key
event.stopPropagation();
event.preventDefault();
var query = $searchField.val();
if (event.keyCode === KeyEvent.DOM_VK_ESCAPE) {
query = null;
}
that._close(query);
}
})
.bind("input", function (event) {
// Check the query expression on every input event. This way the user is alerted
// to any RegEx syntax errors immediately.
_getQueryRegExp($searchField.val());
})
.blur(function () {
that._close(null);
})
.focus();
return this.result.promise();
};
function _getSearchMatches(contents, queryExpr) {
// Quick exit if not found
if (contents.search(queryExpr) === -1) {
return null;
}
var trimmedContents = contents;
var startPos = 0;
var matchStart;
var matches = [];
var match;
var lines = StringUtils.getLines(contents);
while ((match = queryExpr.exec(contents)) !== null) {
var lineNum = StringUtils.offsetToLineNum(lines, match.index);
var line = lines[lineNum];
var ch = match.index - contents.lastIndexOf("\n", match.index) - 1; // 0-based index
var matchLength = match[0].length;
// Don't store more than 200 chars per line
line = line.substr(0, Math.min(200, line.length));
matches.push({
start: {line: lineNum, ch: ch},
end: {line: lineNum, ch: ch + matchLength},
line: line
});
// We have the max hits in just this 1 file. Stop searching this file.
// This fixed issue #1829 where code hangs on too many hits.
if (matches.length >= FIND_IN_FILES_MAX) {
queryExpr.lastIndex = 0;
maxHitsFoundInFile = true;
break;
}
}
return matches;
}
function _showSearchResults(searchResults, query, scope) {
var $searchResultsDiv = $("#search-results");
if (searchResults && searchResults.length) {
var $resultTable = $("<table class='zebra-striped condensed-table' />")
.append("<tbody>");
// Count the total number of matches
var numMatches = 0;
searchResults.forEach(function (item) {
numMatches += item.matches.length;
});
// Show result summary in header
var numMatchesStr = "";
if (maxHitsFoundInFile) {
numMatchesStr = Strings.FIND_IN_FILES_MORE_THAN;
}
numMatchesStr += String(numMatches);
var summary = StringUtils.format(
Strings.FIND_IN_FILES_TITLE,
numMatchesStr,
(numMatches > 1) ? Strings.FIND_IN_FILES_MATCHES : Strings.FIND_IN_FILES_MATCH,
searchResults.length,
(searchResults.length > 1 ? Strings.FIND_IN_FILES_FILES : Strings.FIND_IN_FILES_FILE),
query,
scope ? _labelForScope(scope) : ""
);
$("#search-result-summary")
.text(summary +
(numMatches > FIND_IN_FILES_MAX ? StringUtils.format(Strings.FIND_IN_FILES_MAX, FIND_IN_FILES_MAX) : ""))
.prepend(" "); // putting a normal space before the "-" is not enough
var resultsDisplayed = 0;
searchResults.forEach(function (item) {
if (item && resultsDisplayed < FIND_IN_FILES_MAX) {
var makeCell = function (content) {
return $("<td/>").html(content);
};
// shorthand function name
var esc = StringUtils.htmlEscape;
var highlightMatch = function (line, start, end) {
return esc(line.substr(0, start)) + "<span class='highlight'>" + esc(line.substring(start, end)) + "</span>" + esc(line.substr(end));
};
// Add row for file name
$("<tr class='file-section' />")
.append("<td colspan='3'>" + StringUtils.format(Strings.FIND_IN_FILES_FILE_PATH, StringUtils.breakableUrl(esc(item.fullPath))) + "</td>")
.click(function () {
// Clicking file section header collapses/expands result rows for that file
var $fileHeader = $(this);
$fileHeader.nextUntil(".file-section").toggle();
})
.appendTo($resultTable);
// Add row for each match in file
item.matches.forEach(function (match) {
if (resultsDisplayed < FIND_IN_FILES_MAX) {
var $row = $("<tr/>")
.append(makeCell(" ")) // Indent
.append(makeCell(StringUtils.format(Strings.FIND_IN_FILES_LINE, (match.start.line + 1))))
.append(makeCell(highlightMatch(match.line, match.start.ch, match.end.ch)))
.appendTo($resultTable);
$row.click(function () {
CommandManager.execute(Commands.FILE_OPEN, {fullPath: item.fullPath})
.done(function (doc) {
// Opened document is now the current main editor
EditorManager.getCurrentFullEditor().setSelection(match.start, match.end);
});
});
resultsDisplayed++;
}
});
}
});
$("#search-results .table-container")
.empty()
.append($resultTable)
.scrollTop(0); // otherwise scroll pos from previous contents is remembered
$("#search-results .close")
.one("click", function () {
$searchResultsDiv.hide();
EditorManager.resizeEditor();
});
$searchResultsDiv.show();
} else {
$searchResultsDiv.hide();
}
EditorManager.resizeEditor();
}
/**
* @param {!FileInfo} fileInfo File in question
* @param {?Entry} scope Search scope, or null if whole project
* @return {boolean}
*/
function inScope(fileInfo, scope) {
if (scope) {
if (scope.isDirectory) {
// Dirs always have trailing slash, so we don't have to worry about being
// a substring of another dir name
return fileInfo.fullPath.indexOf(scope.fullPath) === 0;
} else {
return fileInfo.fullPath === scope.fullPath;
}
}
return true;
}
/**
* Displays a non-modal embedded dialog above the code mirror editor that allows the user to do
* a find operation across all files in the project.
* @param {?Entry} scope Project file/subfolder to search within; else searches whole project.
*/
function doFindInFiles(scope) {
var dialog = new FindInFilesDialog();
// Default to searching for the current selection
var currentEditor = EditorManager.getActiveEditor();
var initialString = currentEditor && currentEditor.getSelectedText();
searchResults = [];
maxHitsFoundInFile = false;
dialog.showDialog(initialString, scope)
.done(function (query) {
if (query) {
var queryExpr = _getQueryRegExp(query);
if (!queryExpr) {
return;
}
StatusBar.showBusyIndicator(true);
FileIndexManager.getFileInfoList("all")
.done(function (fileListResult) {
Async.doInParallel(fileListResult, function (fileInfo) {
var result = new $.Deferred();
if (!inScope(fileInfo, scope)) {
result.resolve();
} else {
// Search one file
DocumentManager.getDocumentForPath(fileInfo.fullPath)
.done(function (doc) {
var matches = _getSearchMatches(doc.getText(), queryExpr);
if (matches && matches.length) {
searchResults.push({
fullPath: fileInfo.fullPath,
matches: matches
});
}
result.resolve();
})
.fail(function (error) {
// Error reading this file. This is most likely because the file isn't a text file.
// Resolve here so we move on to the next file.
result.resolve();
});
}
return result.promise();
})
.done(function () {
// Done searching all files: show results
_showSearchResults(searchResults, query, scope);
StatusBar.hideBusyIndicator();
})
.fail(function () {
console.log("find in files failed.");
StatusBar.hideBusyIndicator();
});
});
}
});
}
/** Search within the file/subtree defined by the project tree selection */
function doFindInSubtree() {
var treeSelection = ProjectManager.getSelectedItem();
doFindInFiles(treeSelection);
}
// Initialize items dependent on HTML DOM
AppInit.htmlReady(function () {
var $searchResults = $("#search-results"),
$searchContent = $("#search-results .table-container");
});
function _fileNameChangeHandler(event, oldName, newName) {
if ($("#search-results").is(":visible")) {
// Update the search results
searchResults.forEach(function (item) {
item.fullPath = item.fullPath.replace(oldName, newName);
});
_showSearchResults(searchResults);
}
}
$(DocumentManager).on("fileNameChange", _fileNameChangeHandler);
CommandManager.register(Strings.CMD_FIND_IN_FILES, Commands.EDIT_FIND_IN_FILES, doFindInFiles);
CommandManager.register(Strings.CMD_FIND_IN_SUBTREE, Commands.EDIT_FIND_IN_SUBTREE, doFindInSubtree);
});