@@ -323,12 +323,20 @@ export class TextSearchProvider implements vscode.TextSearchProvider {
323323
324324 const uri = DocumentContentProvider . getUri ( file . doc , "" , "" , true , options . folder ) ;
325325 const content = decoder . decode ( await vscode . workspace . fs . readFile ( uri ) ) . split ( "\n" ) ;
326+ const contentLength = content . length ;
326327 // Find all lines that we have matches on
327328 const lines = file . matches
328- . map ( ( match : SearchMatch ) => searchMatchToLine ( content , match , file . doc , api . configName ) )
329+ . map ( ( match : SearchMatch ) =>
330+ token . isCancellationRequested ? null : searchMatchToLine ( content , match , file . doc , api . configName )
331+ )
329332 . filter ( notNull ) ;
330- // Filter out duplicates and compute all matches for each one
331- [ ...new Set ( lines ) ] . forEach ( ( line ) => {
333+ // Remove duplicates and make them quickly searchable
334+ const matchedLines = new Set ( lines ) ;
335+ // Compute all matches for each one
336+ matchedLines . forEach ( ( line ) => {
337+ if ( token . isCancellationRequested ) {
338+ return ;
339+ }
332340 const text = content [ line ] ;
333341 const regex = new RegExp (
334342 query . isRegExp ? query . pattern : query . pattern . replace ( / [ - [ \] { } ( ) * + ? . , \\ ^ $ | # \s ] / g, "\\$&" ) ,
@@ -345,6 +353,19 @@ export class TextSearchProvider implements vscode.TextSearchProvider {
345353 counter ++ ;
346354 }
347355 if ( matchRanges . length && previewRanges . length ) {
356+ if ( options . beforeContext ) {
357+ // Add preceding context lines that aren't themselves result lines
358+ const previewFrom = Math . max ( line - options . beforeContext , 0 ) ;
359+ for ( let i = previewFrom ; i < line ; i ++ ) {
360+ if ( ! matchedLines . has ( i ) ) {
361+ progress . report ( {
362+ uri,
363+ text : content [ i ] ,
364+ lineNumber : i + 1 ,
365+ } ) ;
366+ }
367+ }
368+ }
348369 progress . report ( {
349370 uri,
350371 ranges : matchRanges ,
@@ -353,6 +374,19 @@ export class TextSearchProvider implements vscode.TextSearchProvider {
353374 matches : previewRanges ,
354375 } ,
355376 } ) ;
377+ if ( options . afterContext ) {
378+ // Add following context lines that aren't themselves result lines
379+ const previewTo = Math . min ( line + options . afterContext , contentLength - 1 ) ;
380+ for ( let i = line + 1 ; i <= previewTo ; i ++ ) {
381+ if ( ! matchedLines . has ( i ) ) {
382+ progress . report ( {
383+ uri,
384+ text : content [ i ] ,
385+ lineNumber : i + 1 ,
386+ } ) ;
387+ }
388+ }
389+ }
356390 }
357391 } ) ;
358392 } ;
0 commit comments